  Legal Information

Information in this online help system is subject to change without notice and does not represent a commitment on the part of Microsoft Corporation. The software and/or files described in this online help system are furnished under a license agreement or nondisclosure agreement. The software and/or files may be used or copied only in accordance with the terms of the agreement. The purchaser may make one copy of the software for backup purposes. No part of this online help system may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or information and retrieval systems, for any purpose other than the purchaser's personal use, without the written permission of Microsoft Corporation.

Microsoft may have patents or pending patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document. The furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property rights except as expressly provided in any written license agreement from Microsoft.

Copyright © 1992-1995 Microsoft Corporation. All rights reserved.

Microsoft, MS, MS-DOS, Win32, Win32s, and Windows are registered trademarks, and Windows NT is a trademark of Microsoft Corporation.

Portions of this documentation are provided under license from Digital Equipment Corporation. Copyright © 1990, 1992 Digital Equipment Corporation. All rights reserved.

DEC, DECnet and PATHWORKS are trademarks of Digital Equipment Corporation.


 Windows

A window in an application written for the Microsoft® Windows® operating system is a rectangular area of the screen where the application displays output and receives input from the user. 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

Windows are the only means a Windows-based application has to interact with the user and accomplish tasks, so one of the first tasks of a Windows-based application is to create a window. This overview describes the elements of the Microsoft® Win32® application programming interface (API) that applications use to create and use windows; manage relationships between windows; and size, move, and display windows.


 Desktop Window

When Windows starts, 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 Win32-based applications.

The desktop window uses a bitmap stored in a bitmap file (with the .BMP filename extension) 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 file specified in the registry as the desktop wallpaper.

A system configuration application, such as a Control Panel application, can change the desktop wallpaper by using the SystemParametersInfo function with the wAction parameter set to SPI_SETDESKWALLPAPER and the lpvParam parameter specifying a bitmap filename. SystemParametersInfo then loads the bitmap from the specified file, uses the bitmap to paint the background of the screen, and enters the new filename in the registry. For more information about bitmaps, see Bitmaps. For more information about the registry, see Registry.


 Application Windows

Every Win32-based application creates at least one window, called the main window, that serves as the main window for the application. This window serves as the primary interface between the user and the application. Most applications also create many 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.


 Components of an Application Window

An application window can include a title bar, a menu bar, a System menu (also called the Control menu), a minimize box, a maximize box, a sizing border, a client area, a horizontal scroll bar, and a vertical scroll bar. An application's main window typically includes all of these components. The following illustration shows these components in a typical main window.

The title bar displays an application-defined icon and line of text; typically, the text specifies the name of the application or indicates the purpose of the window. An application specifies the icon and text when creating the window. The title bar also makes it possible for the user to move the window by using a mouse or other pointing device.

Most applications include a menu that lists the commands supported by the application. Items in the menu bar represent the main categories of commands. Choosing an item from the menu bar typically opens a pop-up menu whose items correspond to the tasks within a given category. By selecting a command, the user directs the application to carry out a task.

The System-menu box is a bitmap that, when clicked, displays the System menu. The System menu is a menu created and managed by Windows. 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 open the Task List. For more information about menus and the System menu, see Menus (Windows NT).

The maximize and minimize boxes are bitmaps that, when clicked, affect a window's size and position. When the user clicks the maximize box, Windows enlarges the window to the size of the screen and positions the window, so it covers the entire screen. At the same time, Windows replaces the maximize box with the restore box. The restore box is a bitmap that, when clicked, restores the window to its previous size and position.

When the user clicks the minimize box, Windows reduces the window to the size of an icon, positions the window at the bottom of the screen, and displays the window's icon at the position of the window. An icon is a 32- by 32-pixel bitmap that represents a window. For more information about icons, see Icons.

The sizing border is an area around the perimeter of the window that enables the user to size the window by using a mouse or other pointing device.

The client area is the part of a window where the application displays output, such as text or graphics. For example, a desktop publishing application displays the current page of a document in the client area. The application must provide a function, called a window procedure, to process input to the window and display output in the client area. For more information about window procedures, see Window Procedures.

The horizontal and vertical scroll bars convert mouse or keyboard input into values that an application uses to shift the contents of the client area either horizontally or vertically. For example, a word-processing application that displays a lengthy document typically provides a vertical scroll bar to enable the user to page up and down through the document.

The title bar, menu bar, System menu, minimize and maximize boxes, sizing border, and scroll bars are referred to collectively as the window's nonclient area. Windows manages most aspects of the nonclient area; the application manages everything else about the window. In particular, the application manages the appearance and behavior of the client area.


 Controls, Dialog Boxes, and Message Boxes

An application uses several types of windows in addition to its main window, including controls, dialog boxes, and message boxes.

A control is a window that an application uses to obtain a specific piece of information from the user, such as the name of a file to open or the desired point size of a text selection. Applications also use controls to obtain information needed to control a particular feature of an application. For example, a word-processing application typically provides a control to let the user turn wordwrapping on and off.

Controls are always used in conjunction with another window — typically, a dialog box. A dialog box is a window that contains one or more controls. An application uses a dialog box to prompt the user for input needed to complete a command. For example, an application that includes a command to open a file would display a dialog box that includes controls in which the user specifies a path and filename.

A message box is a window that displays a note, caution, or warning to the user. For example, a message box can inform the user of a problem the application has encountered while performing a task.

Dialog boxes and message boxes do not typically use the same set of window components as does a main window. Most have a title bar, a System menu, a border (nonsizing), and a client area, but they typically do not have a menu bar, minimize and maximize buttons, or scroll bars. For more information about dialog boxes and message boxes, see Dialog Boxes.


 Window Creation

An application creates its main window by using the CreateWindow or CreateWindowEx function and providing information Windows requires to define the attributes of the window. CreateWindowEx has a parameter, dwExStyle, that CreateWindow does not have; otherwise, the functions are identical. In fact, CreateWindow simply calls CreateWindowEx, setting the dwExStyle parameter to zero. For this reason, the remainder of this topic refers only to CreateWindowEx.

The Win32 API provides additional functions — including DialogBox, CreateDialog, and MessageBox — for creating special-purpose windows such as dialog boxes and message boxes. For more information about these functions, see Dialog Boxes.


 Window Attributes

An application must provide the following information when creating a window:

•	Window class

•	Window name

•	Window style

•	Parent or owner window

•	Size

•	Location

•	Position

•	Child-window identifier or menu handle

•	Instance handle

•	Creation data

These attributes are described in the following sections.

Window Class

Every window belongs to a window class. An application must register a window class before creating any windows of that class. The window class defines most aspects of a window's appearance and behavior. The chief component of a window class is the window procedure, a function that receives and processes all input and requests sent to the window. Windows provides the input and requests in the form of messages. For more information about window classes, window procedures, or messages, see Window Classes, Window Procedures, or Messages and Message Queues.

Window Name

A window can have a name. A window name (also called window text) is a text string that identifies a window for the user. A main window, dialog box, or message box typically displays its window name in its title bar, if present. For a control, the appearance of the window name depends on the control's class. A button, edit control, or static control displays its window name within the rectangle occupied by the control. A list box, combo box, or static control does not display its window name.

An application uses the SetWindowText function to change the window name after creating the window. It uses the GetWindowTextLength and GetWindowText functions to retrieve the current window-name text from a window.

Window Style

Every window has one or more window styles. A window style is a named constant that defines an aspect of the window's appearance and behavior that is not specified by the window's class. For example, the SCROLLBAR class creates a scroll bar control, but the SBS_HORZ and SBS_VERT styles determine whether a horizontal or vertical scroll bar control is created. A few window styles apply to all windows, but most apply to windows of specific window classes. Windows and, to some extent, the window procedure for the class, interpret the styles.

Parent or Owner Window

A window can have a parent window. A window that has a parent is called a child window. The parent window provides the coordinate system used for positioning a child window. Having a parent window affects aspects of a window's appearance; for example, a child window is clipped so that no part of the child window can appear outside the borders of its parent window. A window that has no parent, or whose parent is the desktop window, is called a top-level window. An application uses the EnumWindows function to obtain the handle of each of its top-level windows. EnumWindows passes the handle of each top-level window, in turn, to an application-defined callback function (a function called by Windows).

A window can own, or be owned by, another window. An owned window always appears in front of its owner window, is hidden when its owner window is minimized, and is destroyed when its owner window is destroyed.

Location, Size, and Position in the Z Order

Every window has a location, size, and position in the Z order. The location is the coordinates of the window's upper left corner, relative to the upper left corner of the screen or, in the case of a child window, the upper left corner of the parent's client area. A window's size is its width and height measured in pixels. A window's position in the Z order is the position of the window in a stack of overlapping windows.

Child-Window Identifier or Menu Handle

A child window can have a child-window identifier, a unique, application-defined value associated with the child window. Child-window identifiers are especially useful in applications that create multiple child windows. When creating a child window, an application specifies the identifier of the child window. After creating the window, the application can change the window's identifier by using the SetWindowLong function, or it can retrieve the identifier by using the GetWindowLong function.

Every window, except a child window, can have a menu. An application can include a menu by providing a menu handle either when registering the window's class or when creating the window.

Instance Handle

Every Win32-based application has an instance handle associated with it. Windows provides the instance handle to an application when the application starts. Because it can run multiple copies of the same application, Windows 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, Windows 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.


 Main Window Creation

Every Win32-based application must have a WinMain function as its entry point. WinMain performs a number of tasks, including registering the window class for the main window and creating the main window. WinMain registers the main window class by calling the RegisterClass function, and it creates the main window by calling the CreateWindowEx function.

Portability Issue  The entry point need not be named WinMain.

Windows 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: the handle of 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 that are defined in the Win32 header files. However, when ShowWindow is called to display the application's main window, the flag must be set to SW_SHOWDEFAULT. This flag tells Windows to display the window as directed by the program that launched the application.


 Window-Creation Messages

When creating any window, Windows sends messages to the window procedure for the window. Windows 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 Windows 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, Windows 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. An application can use the EnumThreadWindows function to enumerate the windows created by a particular thread. This function passes the handle of each thread window, in turn, to an application-defined callback function. The GetWindowThreadProcessId function returns the identifier of the thread that created a particular window.


 Window Handles

After creating a window, the creation function returns a window handle that uniquely identifies the window. An application uses this handle in other functions to direct their actions to the window. A window handle has the HWND data type; an application must use this type when declaring a variable that holds a window handle.

The Win32 API includes several special constants that can replace a window handle in certain functions. These constants begin with the HWND_ prefix. For example, an application can use HWND_TOP or HWND_BOTTOM in the SetWindowPos function to move a window to the top or bottom of the Z order.

Although the NULL constant is not a window handle, an application can use it in some functions to specify that no window is affected. For example, specifying NULL for the CreateWindowEx function's hwndParent parameter creates a window that has no parent or owner. Some functions may return NULL instead of a handle, indicating that the given action applies to no window.

An application can use the FindWindow function to discover whether a window with the specified class name or window name exists in the system. If such a window exists, FindWindow returns the handle of the window. The IsWindow function determines whether a window handle identifies a valid, existing window.


 Window Styles

The Win32 API provides general window styles and class-specific window styles. The general windows styles are constants that begin with the WS_ prefix; they can be combined to form different types of windows, including main windows, dialog boxes, and child windows. The class-specific window styles define the appearance and behavior of windows belonging to the predefined control classes such as edit controls and list boxes. This section describes the general window styles.

An application usually sets a window's styles when creating the window. It can also set the styles after creating the window by using the SetWindowLong function.


 Overlapped Window

An overlapped window is a top-level window that has a title bar, border, and client area; it is meant to serve as an application's main window. It can also have a System menu, minimize and maximize boxes, 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 can create an overlapped window. If created with the WS_OVERLAPPED style, the window has a title bar and border. If created with the WS_OVERLAPPEDWINDOW style, the window has a title bar, sizing border, System menu, and minimize and maximize boxes.


 Pop-up Window

A pop-up window is a special type of overlapped window used for dialog boxes, message boxes, and other temporary windows that appear outside an application's main window. Title bars are optional for pop-up windows; otherwise, pop-up windows are the same as overlapped windows of the WS_OVERLAPPED style.

An application creates a pop-up window by specifying the WS_POPUP style in CreateWindowEx. To include a title bar, the WS_CAPTION style must also be specified. An application can use the WS_POPUPWINDOW style to create a pop-up window that has a border and a System menu. The WS_CAPTION style must be combined with the WS_POPUPWINDOW style to make the System menu visible.


 Child Window

A child window has the WS_CHILD style and is confined to the client area of its parent window. An application typically uses child windows to divide the client area of a parent window into functional areas. An application creates 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. An application specifies the parent window when calling CreateWindowEx. If the application specifies the WS_CHILD style in CreateWindowEx but does not specify a parent window, Windows 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 System menu, minimize and maximize boxes, a border, and scroll bars for a child window, but a child window cannot have a menu. If the application specifies a menu handle, either when it registers the child's window class or creates the child window, the menu handle is ignored.

Positioning

Windows always positions the child window relative to the upper left corner of the 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, Windows 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

Windows 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. Windows does, however, 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, Windows 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 the handle of 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 of each child window to an application-defined callback function. Descendant windows of the given parent window are also enumerated.

Messages

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


 Window Border

The Win32 API provides the following border styles.

Style	Description
WS_BORDER	Creates a window with a thin-line border.
WS_DLGFRAME	Creates a window with a double border, a style typically used with dialog boxes. A window with this style cannot have a title bar.
WS_EX_DLGMODALFRAME	Creates a window with a double border. Unlike the WS_DLGFRAME style, an application can also specify the WS_CAPTION style to create a title bar for the window.
WS_EX_STATICEDGE	Creates a window with a three-dimensional border style intended to be used for items that do not accept user input.
WS_THICKFRAME	Creates a window with a sizing border.
A window with the WS_OVERLAPPED or WS_POPUPWINDOW style has the WS_BORDER style by default. One of the other border styles must be combined with the WS_OVERLAPPED or WS_POPUPWINDOW style to give an overlapped window a different border style.

If no border style is specified for a window with the WS_POPUP or WS_CHILD style, the system creates a borderless window. An application can use borderless child windows to divide the parent window's client area while keeping the divisions invisible to the user.


 Nonclient-Area Components

The nonclient area of a window can include a title bar, System menu, minimize and maximize boxes, sizing border, and horizontal and vertical scroll bars. An application can create a window with one or more of these components by specifying the following styles in the CreateWindowEx function.

Style	Description
WS_CAPTION	Creates a window that has a title bar (includes the WS_BORDER style).
WS_HSCROLL	Creates a window that has a horizontal scroll bar.
WS_MAXIMIZEBOX	Creates a window that has a maximize box.
WS_MINIMIZEBOX	Creates a window that has a minimize box.
WS_SYSMENU	Creates a window that has a System-menu box in its title bar. The WS_CAPTION style must also be specified.
WS_VSCROLL	Creates a window that has a vertical scroll bar.


 Initial State

The following styles determine whether a window is enabled or disabled, visible or invisible, and minimized or maximized.

Style	Description
WS_DISABLED	Creates a window that is initially disabled. A disabled window cannot receive input from the user.
WS_MAXIMIZE	Creates a window that is initially maximized.
WS_MINIMIZE	Creates a window that is initially minimized.
WS_VISIBLE	Creates a window that is initially visible.


 Parent and Child Styles

The following styles affect the clipping relationship between a parent window and its child windows, and between a child window and its sibling windows.

Style	Description
WS_CLIPCHILDREN	Excludes the area occupied by child windows when drawing within the parent window. Use this style when creating the parent window.
WS_CLIPSIBLINGS	Clips child windows relative to each other; that is, when a particular child window receives a WM_PAINT message, the WS_CLIPSIBLINGS style clips all other overlapping child windows out of the region of the child window to be updated. If WS_CLIPSIBLINGS is not specified and child windows overlap, it is possible, when drawing within the client area of one child window, to draw within the client area of another neighboring child window.


 Dialog Box Styles

A dialog box includes a built-in keyboard interface that processes the direction and TAB keys. The user can use these keys instead of the mouse to navigate among the controls in the dialog box. The following styles affect how the built-in keyboard interface processes the direction and TAB keys.

Style	Description
WS_GROUP	Specifies the first control of a group of controls. The user can change the keyboard focus from one control in the group to the next by using the direction keys. The next control with the WS_GROUP style ends the group and starts the next group.
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 of the WS_TABSTOP style.


 Extended Styles

The following styles can be specified in the dwExStyle parameter of the CreateWindowEx function.

Style	Description
WS_EX_ACCEPTFILES	Specifies that a window created with this style accepts drag-drop files.
WS_EX_CONTEXTHELP	Includes a question mark in the title bar of the window. When the user clicks the question mark, the cursor changes to a question mark with a pointer. If the user then clicks a child window, the child receives a WM_HELP message. The child window should pass the message to the parent window procedure, which should call the WinHelp function using the HELP_WM_HELP command. The Help application displays a pop-up window that typically contains help for the child window.
WS_EX_CONTROLPARENT	Allows the user to navigate among the child windows of the window by using the TAB key.
WS_EX_DLGMODALFRAME	Creates a window with a double border. Unlike the WS_DLGFRAME style, an application can also specify the WS_CAPTION style to create a title bar for the window.
WS_EX_NOPARENTNOTIFY	Specifies that a child window created with this style will not send the WM_PARENTNOTIFY message to its parent window when either created or destroyed.
WS_EX_TOPMOST	Specifies that a window created with this style should be placed above all non-topmost windows and stay above them even when the window is deactivated.
WS_EX_TOOLWINDOW	Creates a tool window; that is, a window intended to be used as a floating toolbar. A tool window has a title bar that is shorter than a normal title bar, and the window title is drawn using a smaller font. A tool window does not appear in the task bar or in the window that appears when the user presses ALT+TAB.


 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.

•	Windows 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 one. 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, Windows 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 the handle of a window's owner.


 Disabled Windows

A window can be disabled. A disabled window receives no keyboard or mouse input, but it can receive messages from other windows, from other applications, and from Windows. 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. Windows 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, Windows 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 about mouse input, 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 about the keyboard focus, see Keyboard Input.


 Foreground and Background Windows

Each process can have multiple threads of execution, and each thread can create windows. The thread that created the window with which the user is currently working is called the foreground thread, and the window is called the foreground window. All other threads are background threads, and the windows created by background threads are called background windows.

Each thread has a priority level that determines the amount of CPU time the thread receives. Although an application can set the priority level of its threads, normally the foreground thread has a slightly higher priority level than the background threads. Because it has a higher priority, the foreground thread receives more CPU time than the background threads. The foreground thread has a normal base priority of 9; a background thread has a normal base priority of 7.

The user sets the foreground window by clicking a window, or by using the ALT+TAB or ALT+ESC key combination. An application sets the foreground window by using the SetForegroundWindow function. If the new foreground window is a top-level window, Windows activates it; otherwise, it activates the associated top-level window. An application retrieves the handle of the foreground window by using the GetForegroundWindow function.


 Show State

At any one given time, a window may be active or inactive; hidden or visible; and minimized, maximized, or restored. These qualities are referred to collectively as the window's show state.


 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, Windows 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, Windows 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. A number of other functions can cause Windows 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 the handle of the active window.

When the activation changes from a top-level window of one application to the top-level window of another, Windows 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, Windows sends both windows a WM_ACTIVATE message.


 Visibility

A window can be either visible or hidden. Windows 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 Windows 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, Windows sends the WM_SHOWWINDOW message to the window after creating the window, but before displaying it.

An application can determine whether a window is visible by using the IsWindowVisible function. An application can show (make visible) or hide a window by using the ShowWindow, SetWindowPos, DeferWindowPos, or SetWindowPlacement function. These functions show or hide a window by setting or removing the WS_VISIBLE style for the window. They also send the WM_SHOWWINDOW message to the window before showing or hiding it.

When an owner window is minimized, Windows automatically hides the associated owned windows. Similarly, when an owner window is restored, Windows automatically shows the associated owned windows. In both cases, Windows 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, Windows 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. Windows 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, Windows 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, Windows reduces a minimized window to the size of an icon and moves the minimized window to the lower part of the screen or the lower part of the parent window's client area. The lower part of the screen or client area is sometimes called the icon area. Windows moves a minimized window into the first available position in the icon area, unless the application specifies another position. A restored window is a window that has been returned to its preminimized or premaximized size and position.

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 application's minimized top-level windows along the bottom of the screen, or it arranges a parent window's minimized child windows along the bottom of the parent window.

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 Windows receives a command to maximize or restore a minimized window, Windows sends the window a WM_QUERYOPEN message. If the window procedure returns FALSE, Windows ignores the Maximize or Restore command.

Windows 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 Windows is about to maximize the window. WM_GETMINMAXINFO includes a pointer to a MINMAXINFO structure containing values Windows 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 about bounding rectangles, see Filled Shapes.


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


 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 the handle of the window occupying a particular point on the screen. Similarly, the ChildWindowFromPoint and ChildWindowFromPointEx functions retrieve the handle of the child window occupying a particular point in the parent window's client area. Although ChildWindowFromPointEx can ignore invisible, disabled, and transparent child windows, ChildWindowFromPoint cannot.


 Default Size and Position

An application can allow Windows 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, Windows 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, Windows calculates the size of the new window. If the application has created other top-level windows, Windows 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 Windows to set the window's size to the default minimum window size.


 Tracking Size

Windows 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 the user can produce by dragging the window's sizing border. Similarly, the maximum tracking size is the largest window size the user can produce by dragging the sizing border.

A window's minimum and maximum tracking sizes are set to system-defined default values when Windows creates the window. An application can discover the defaults and override them by processing the WM_GETMINMAXINFO message. For more information about this message, see Size and Position Messages.


 System Commands

An application that has a window with a System 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 System 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_RESTORE	Restores a minimized or maximized window to its previous size and position.
SC_SIZE	Starts a Size command. The user can change the size of the window by using the mouse or keyboard.


 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. An application sets a window's position in the Z order by placing it behind a given window, or at the top or bottom of the stack.

Windows maintains three separate Z orders — one for top-level windows, one for sibling windows, and one for topmost 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.

By default, Windows puts a window at the top of the Z order when creating the window. The user changes the Z order by activating a different window; Windows always positions the active window at the top of the Z order. An application uses the BringWindowToTop function to bring a window to the top of the Z order. It can rearrange the Z order by using SetWindowPos or DeferWindowPos.


 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.


 Size and Position Messages

Windows 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 chooses the Move or Size command from the System 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.

Windows 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, Windows 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, Windows does not send WM_SIZE and WM_MOVE messages to the window.

Windows sends the WM_NCCALCSIZE message to a window when the window is created or sized. Windows 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 about window size, see Painting and Drawing.


 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, Windows 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 window. In this way, all descendant windows of the window being destroyed are also destroyed.

A window with a System menu receives a WM_CLOSE message when the user chooses the Close command from the System menu. 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

•	Creating a main window.

•	Creating, enumerating, and sizing child windows.

•	Destroying a window.


 Creating a Main Window

The first window an application creates is typically the main window. You create the main window by using the CreateWindowEx function, specifying the window class, window name, window styles, size, position, menu handle, instance handle, and creation data. A main window belongs to an application-defined window class, so you must register the window class and provide a window procedure for the class before creating the main window.

Most applications typically use the WS_OVERLAPPEDWINDOW style to create the main window. This style gives the window a title bar, a System menu, a sizing border, and minimize and maximize boxes. 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;

.

. /* Register the window class for the main window. */

.

/* 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 launched the application, and send the application

 * a WM_PAINT message.

 */

ShowWindow(hwndMain, SW_SHOWDEFAULT);

UpdateWindow(hwndMain);

.

. /* Start the message loop for the application. */

.

Notice that the preceding example calls the ShowWindow function after creating the main window. This is done because Windows does not automatically display the main window after creating it. By passing the SW_SHOWDEFAULT flag to ShowWindow, the application allows the program that launched 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 of 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, uMsg, wParam, lParam)

HWND hwnd;

UINT uMsg;

UINT wParam;

LONG 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(hwndChild, lParam)

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 System menu automatically receives the WM_CLOSE message when the user chooses the Close command from the menu. If the user confirms that the window should be destroyed, the application calls DestroyWindow. Windows 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 the Yes button, DestroyWindow is called; otherwise, the window is not destroyed. Because the window being destroyed is a main window, the example calls PostQuitMessage in response to WM_DESTROY.

case WM_CLOSE:

    /*

     * Create the message box. If the user clicks

     * the Yes button, destroy the main window.

     */

    if (MessageBox(hwnd, szConfirm, szAppName,

            MB_YESNOCANCEL) == IDYES)

        DestroyWindow(hwndMain);

    else

        return 0;

case WM_DESTROY:

    /*

     * Post the WM_QUIT message to

     * quit the application terminate.

     */

    PostQuitMessage(0);

    return 0;


 Window Reference

The following functions and messages are associated with windows.


 Window Functions

Following are the functions to create and manage windows.

AdjustWindowRect
AdjustWindowRectEx
AnyPopup
BeginDeferWindowPos
BringWindowToTop
ChildWindowFromPoint
CloseWindow
CreateWindow
CreateWindowEx
DeferWindowPos
DestroyWindow
EnableWindow
EndDeferWindowPos
EnumChildProc
EnumChildWindows
EnumThreadWindows
EnumThreadWndProc
EnumWindows
EnumWindowsProc
FindWindow
GetClientRect
GetDesktopWindow
GetForegroundWindow
GetLastActivePopup
GetNextWindow
GetParent
GetTopWindow
GetWindow
GetWindowPlacement
GetWindowRect
GetWindowText
GetWindowTextLength
GetWindowThreadProcessId
IsChild
IsWindow
IsWindowUnicode
IsWindowVisible
IsZoomed
MoveWindow
SetForegroundWindow
SetParent
SetWindowLong
SetWindowPlacement
SetWindowPos
SetWindowText
ShowOwnedPopups
ShowWindow
WindowFromPoint
WinMain

Obsolete or Deleted Functions

EnumTaskWindows
GetSysModalWindow
GetWindowTask
SetSysModalWindow


 Window Messages

Following are the messages to create and manage windows.

WM_ACTIVATE
WM_ACTIVATEAPP
WM_CANCELMODE
WM_CHILDACTIVATE
WM_CLOSE
WM_COPYDATA
WM_CREATE
WM_DESTROY
WM_ENABLE
WM_ENDSESSION
WM_GETMINMAXINFO
WM_GETTEXT
WM_MOVE
WM_NCACTIVATE
WM_NCCALCSIZE
WM_NCCREATE
WM_NCDESTROY
WM_PARENTNOTIFY
WM_POWER
WM_QUERYENDSESSION
WM_QUERYOPEN
WM_QUIT
WM_SETTEXT
WM_SHOWWINDOW
WM_SIZE
WM_WINDOWPOSCHANGED
WM_WINDOWPOSCHANGING


 Carets

A caret is a flashing 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.

Because only one window at a time can have the keyboard focus or be active, there is only one caret in the system. Generally, each window that accepts keyboard input must create the caret when it receives the keyboard focus and destroy the caret when it loses the keyboard focus. For more information on keyboard input, see Keyboard Input.

An application written for Microsoft® Windows® can create a caret, display or hide it, relocate the caret, and change its blink time.


 About Carets

An application uses the CreateCaret function to specify the parameters for a caret. Windows 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.

After the caret is defined, an application uses the ShowCaret function to make the caret visible. When the caret appears, it automatically begins flashing. To display a solid caret, Windows inverts every pixel in the rectangle; to display a gray caret, Windows inverts every other pixel; to display a bitmap caret, Windows inverts only the white bits of the bitmap.

The elapsed time, in milliseconds, required to invert the caret is called the blink time. An application can determine the caret's blink time by using the GetCaretBlinkTime function. If it is necessary to define a specific blink time, 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.

An application can determine the caret's position by 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

An application can use the HideCaret function to remove the caret from the screen. 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.

An application can remove the caret from the screen and destroy its shape by 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:

                /* Process all other characters. */

                /* 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

Because there is only one caret in the system, use caution when your application must adjust the rate of the blink time, so as not to disrupt subsequent windows that may receive the keyboard focus. If your application changes the blink time, it must restore the blink time to its original value upon losing the keyboard focus. The GetCaretBlinkTime function returns the current blink time, in milliseconds, and the SetCaretBlinkTime function sets the blink time to the specified number of milliseconds.

If you anticipate that your application will adjust the blink time, add the following line to the WM_SETFOCUS message processing.

uOldBlink = GetCaretBlinkTime();

Then, you can restore the blink time to its original rate by including the following line in the WM_KILLFOCUS message processing.

SetCaretBlinkTime(uOldBlink);


 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)

HINSTANCE hinst;      /* current instance                 */

HBITMAP hCaret;       /* caret bitmap                     */

HDC hdc;              /* device context                   */

PAINTSTRUCT ps;       /* client area paint info           */

static char *pTextMatrix = NULL; /* points to text matrix */

static int  nCharX,   /* width of char. in logical units  */

            nCharY,   /* height of char. in logical units */

            nWindowX, /* width of client area             */

            nWindowY, /* height of client area            */

            nWindowCharsX, /* width of client area        */

            nWindowCharsY, /* height of client area       */

            nCaretPosX,    /* x-position of caret         */

            nCaretPosY;    /* y-position of caret         */

static UINT uOldBlink;     /* previous blink rate         */

int x, y;    /* x and y coordinates to use in text matrix */

TEXTMETRIC tm;             /* font information            */

LONG APIENTRY MainWndProc(

    HWND hwnd,            /* window handle              */

    UINT message,         /* type of message            */

    UINT wParam,          /* additional information     */

    LONG lParam)          /* additional information     */

{

switch (message) {

    case WM_CREATE:

        /*

         * Select a fixed-width system font,

         * and get the text metrics of the font.

         */

        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 */

                /* No processing. */

                MessageBeep((UINT) -1);

                break;

            default:            /* all other characters */

                /* 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:                /* passes it on if unprocessed */

        return DefWindowProc(hwnd, message, wParam, lParam);

}                       /* ends switch (message)      */

    return NULL;

}                       /* ends main window procedure */


 Caret Functions

The following functions are used with carets.

CreateCaret
DestroyCaret
GetCaretBlinkTime
GetCaretPos
HideCaret
SetCaretBlinkTime
SetCaretPos
ShowCaret


 Clipboard

The clipboard is a set of functions and messages that enable applications designed for the Microsoft® Win32® application programming interface (API) to transfer data. Because all applications have access to the clipboard, data can be easily transferred between applications or within an application.

This overview does not describe how to copy and paste linked or embedded objects. For information on these subjects, see the OLE Programmer's Reference in the OLE volume.


 About the Clipboard

A memory object on the clipboard can be in any data format, called a clipboard format. Each format is identified by an unsigned integer value. For standard (predefined) clipboard formats, this value is a constant defined by the Win32 API; for registered clipboard formats, it is the return value of the RegisterClipboardFormat function.

Except for registering clipboard formats, individual windows perform most clipboard operations. Typically, a window procedure transfers information to or from the clipboard in response to the WM_COMMAND message.

The clipboard is user-driven. A window should transfer data to or from the clipboard only in response to a command from the user. A window must not use the clipboard to transfer data without the user's knowledge.


 Clipboard Formats

A window can place more than one object on the clipboard, each representing the same information in a different clipboard format. Users need not be aware of the clipboard formats used for an object on the clipboard.


 Registered Clipboard Formats

Many applications work with data that cannot be translated into a standard clipboard format without loss of information. Such applications can register new clipboard formats by using the RegisterClipboardFormat function. A clipboard format that is used by an application, as opposed to a standard clipboard format, is called a registered clipboard format. For example, if a word-processing application copied formatted text to the clipboard using a standard text format, the formatting information would be lost. The solution would be to register a new clipboard format, such as rich-text format (RTF).

If more than one application registers a clipboard format with exactly the same name, the clipboard format is registered only once. Both calls to the RegisterClipboardFormat function return the same value. In this way, two different applications can share data by using a registered clipboard format.

For a list of standard clipboard formats, see the SetClipboardData function.


 Private Clipboard Formats

An application can identify a private clipboard format by defining a value in the range CF_PRIVATEFIRST through CF_PRIVATELAST. An application can use a private clipboard format for an application-defined data format that does not need to be registered with the system.

Data handles associated with private clipboard formats are automatically freed by the system. Windows that use private clipboard formats can use the WM_DESTROYCLIPBOARD message to free any related resources that are no longer needed.

For more information about the WM_DESTROYCLIPBOARD message, see Clipboard Ownership.

An application can place data handles on the clipboard by defining a private format in the range CF_GDIOBJFIRST through CF_GDIOBJLAST. When using values in this range, the data handle is not a handle to a GDI object, but is a handle allocated by the GlobalAlloc function with the GMEM_DDESHARE and GMEM_MOVEABLE flags. When the clipboard is emptied the system automatically deletes the object using the GlobalFree function


 Multiple Clipboard Formats

A window can place more than one clipboard object on the clipboard, each representing the same information in a different clipboard format. When placing information on the clipboard, the window should provide data in as many formats as possible.

Clipboard formats that contain the most information should be placed on the clipboard first, followed by less descriptive formats. A window pasting information from the clipboard typically retrieves a clipboard object in the first format it recognizes. Because clipboard formats are enumerated in the order they are placed on the clipboard, the first recognized format is also the most descriptive.

For example, suppose a user copies styled text from a word-processing document. The window containing the document might first place data on the clipboard in a registered format, such as RTF. Subsequently, the window would place data on the clipboard in a less descriptive format, such as text (CF_TEXT).

When the content of the clipboard is pasted into another window, the window retrieves data in the most descriptive format it recognizes. If the window recognizes RTF, the corresponding data is pasted into the document. Otherwise, the text data is pasted into the document and the formatting information is lost.


 Synthesized Clipboard Formats

The system implicitly converts data between certain clipboard formats: if a window requests data in a format that is not on the clipboard, the system converts an available format to the requested format. The system can convert data between the text formats CF_UNICODETEXT, CF_TEXT, and CF_OEMTEXT; between the metafile formats CF_ENHMETAFILE and CF_METAFILEPICT; and between the bitmap formats CF_BITMAP and CF_DIB. The system can also convert CF_DIB to CF_PALETTE.

If the system provides a conversion between multiple formats, there is no advantage to placing multiple formats on the clipboard. When copying bitmaps, it is best to place only the CF_DIB format on the clipboard. This is because the colors in a device-dependent bitmap (CF_BITMAP) are relative to the system palette, which may change before the bitmap is pasted. If only the CF_DIB format is on the clipboard and a window requests the CF_BITMAP format, the system renders the device-dependent bitmap (DIB) using the current palette at that time.

If you place the CF_BITMAP format on the clipboard (and not CF_DIB), the system renders the CF_DIB clipboard format as soon as the clipboard is closed. This ensures that the correct palette is used to generate the DIB. Conversions between other clipboard formats occur upon demand.


 Clipboard Operations

A window should use the clipboard when cutting, copying, or pasting data. A window places data on the clipboard for cut and copy operations and retrieves data from the clipboard for paste operations. The following sections describe these operations and related issues.

To place data on or retrieve data from the clipboard, a window must first open the clipboard by using the OpenClipboard function. Only one window can have the clipboard open at a time. When it has finished, the window must close the clipboard by calling the CloseClipboard function.


 Cut and Copy Operations

To place information on the clipboard, a window first clears any previous clipboard content by using the EmptyClipboard function. This function sends the WM_DESTROYCLIPBOARD message to the previous clipboard owner, frees resources associated with data on the clipboard, and assigns clipboard ownership to the window that has the clipboard open.

After emptying the clipboard, a window places data on the clipboard in as many clipboard formats as possible. For each format, the window calls the SetClipboardData function, specifying the format identifier and a global memory handle. The memory handle can be NULL, indicating that the window renders the data on request. (For more information about the rendering of data, see Delayed Rendering.) A window should place data on the clipboard in order from the most descriptive clipboard format to the least descriptive.


 Paste Operations

To retrieve paste information from the clipboard, a window first determines the clipboard format to retrieve. Typically, a window enumerates the available clipboard formats by using the EnumClipboardFormats function and uses the first format it recognizes. This method selects the best available format according to the priority set when the data was placed on the clipboard.

Alternatively, a window can use the GetPriorityClipboardFormat function. This function identifies the best available clipboard format according to a specified priority. A window that recognizes only one clipboard format can simply determine whether that format is available by using the IsClipboardFormatAvailable function.

After determining the clipboard format to use, a window calls the GetClipboardData function. This function returns the handle of a global memory object containing data in the specified format. A window can briefly lock the memory object in order to examine or copy the data. However, a window should not free the object or leave it locked for a long period of time.


 Clipboard Ownership

The clipboard owner is the window associated with the information on the clipboard. A window becomes the clipboard owner when it places data on the clipboard — specifically, when it calls the EmptyClipboard function. The window remains the clipboard owner until it is closed or another window empties the clipboard.

When the clipboard is emptied, the clipboard owner receives a WM_DESTROYCLIPBOARD message. Following are some reasons why a window might process this message:

•	The window delayed rendering of one or more clipboard formats. In response to the WM_DESTROYCLIPBOARD message, the window might free resources it had allocated in order to render data on request. For more information about the rendering of data, see Delayed Rendering.

•	The window placed data on the clipboard in a private clipboard format. The data for private clipboard formats is not freed by the system when the clipboard is emptied. Therefore, the clipboard owner should free the data upon receiving the WM_DESTROYCLIPBOARD message. For more information about private clipboard formats, see Clipboard Formats.

•	The window placed data on the clipboard using the CF_OWNERDISPLAY clipboard format. In response to the WM_DESTROYCLIPBOARD message, the window might free resources it had used to display information in the clipboard viewer window. For more information about this alternative format, see Owner-Display Format.


 Delayed Rendering

When placing a clipboard format on the clipboard, a window can delay rendering the data in that format until the data is needed. To do so, an application can specify NULL for the hData parameter of the SetClipboardData function. This is useful if the application supports several clipboard formats, some or all of which are time-consuming to render. By passing a NULL handle, a window renders complex clipboard formats only when and if they are needed.

If a window delays rendering a clipboard format, it must be prepared to render the format upon request for as long as it is the clipboard owner. The system sends the clipboard owner a WM_RENDERFORMAT message when a request is received for a specific format that has not been rendered. Upon receiving this message, the window should call the SetClipboardData function to place a global memory handle on the clipboard in the requested format.

If the clipboard owner is destroyed and has delayed rendering some or all clipboard formats, it receives the WM_RENDERALLFORMATS message. Upon receiving this message, the window should place valid memory handles on the clipboard for all clipboard formats that it provides. This ensures that these formats remain available after the clipboard owner is destroyed.

An application should not open the clipboard before calling SetClipboardData in response to the WM_RENDERFORMAT or WM_RENDERALLFORMATS message.

Any clipboard formats that are not rendered in response to the WM_RENDERALLFORMATS message cease to be available to other applications and are no longer enumerated by the clipboard functions.


 Memory and the Clipboard

A memory object that is to be placed on the clipboard should be allocated by using the GlobalAlloc function with the GMEM_DDESHARE and GMEM_MOVEABLE flags.

Once a memory object is placed on the clipboard, ownership of that memory handle is transferred to the system. When the clipboard is emptied and the memory object has one of the following clipboard formats, the system frees the memory object by calling the indicated Win32 function:

Function called to free object	Clipboard format
DeleteMetaFile	CF_DSPENHMETAFILE
	CF_DSPMETAFILEPICT
	CF_ENHMETAFILE
	CF_METAFILEPICT
DeleteObject	CF_BITMAP
	CF_DSPBITMAP
	CF_PALETTE
GlobalFree	CF_DIB
	CF_DSPTEXT
	CF_OEMTEXT
	CF_TEXT
	CF_UNICODETEXT
When the clipboard is emptied of a memory object whose clipboard format is not shown in the preceding list, the application itself must free the memory object.


 Clipboard Viewers

A clipboard viewer is a window that displays the current content of the clipboard. The clipboard viewer window is a convenience for the user and does not affect the data-transaction functions of the clipboard.

Typically, a clipboard viewer window can display at least the three most common formats: CF_TEXT, CF_BITMAP, and CF_METAFILEPICT. If a window does not make data available in any of these three formats, it should provide data in a display format or use the owner-display format.

A clipboard viewer chain is the linking together of two or more entities so that they are dependent upon one another for operation. This interdependency (chain) allows all running clipboard viewer applications to receive the messages sent to the current clipboard.


 Clipboard Viewer Windows

A window adds itself to the clipboard viewer chain by calling the SetClipboardViewer function. The return value is the handle of the next window in the chain. Each clipboard viewer window must keep track of the next window in the clipboard viewer chain. When the content of the clipboard changes, the system sends a WM_DRAWCLIPBOARD message to the first window in the chain. After updating its display, each clipboard viewer window must pass this message on to the next window in the chain.

Before closing, a clipboard viewer window must remove itself from the clipboard viewer chain by calling the ChangeClipboardChain function. The system then sends a WM_CHANGECBCHAIN message to the first window in the chain.

For more information about processing the WM_DRAWCLIPBOARD and WM_CHANGECBCHAIN messages, see Creating a Clipboard Viewer Window.


 Display Formats

A display format is a clipboard format used to display information in a clipboard viewer window. A clipboard owner that uses a private or registered clipboard format, and none of the most common standard formats, must provide data in a display format for viewing in a clipboard viewer window. The display formats are intended for viewing only and must not be pasted into a document.

The four display formats are: CF_DSPBITMAP, CF_DSPMETAFILEPICT, CF_DSPTEXT, and CF_DSPENHMETAFILE. These display formats are rendered in the same way as the standard formats, which are: CF_BITMAP, CF_TEXT, CF_METAFILEPICT, and CF_ENHMETAFILE.


 Owner-Display Format

For a clipboard owner that does not use any of the common standard clipboard formats, an alternative to providing a display format is to use the owner-display (CF_OWNERDISPLAY) clipboard format.

By using the owner-display format, a clipboard owner can avoid the overhead of rendering data in an additional format by taking direct control over painting the clipboard viewer window. The clipboard viewer window sends messages to the clipboard owner whenever a portion of the window must be repainted or when the window is scrolled or resized.


 Clipboard Commands

A user typically carries out clipboard operations by choosing commands from an application's Edit menu. Following is a brief description of the standard clipboard commands.

Command	Description
Cut	Places a copy of the current selection on the clipboard and deletes the selection from the document. The previous content of the clipboard is destroyed.
Copy	Places a copy of the current selection on the clipboard. The document remains unchanged. The previous content of the clipboard is destroyed.
Paste	Replaces the current selection with the content of the clipboard. The content of the clipboard is not changed.
Delete	Deletes the current selection from the document. The content of the clipboard is not changed. This command does not involve the clipboard, but it should appear with the clipboard commands on the Edit menu.


 Using the Clipboard

•	Implementing the Cut, Copy, and Paste commands

•	Creating a clipboard viewer window


 Implementing the Cut, Copy, and Paste Commands

This section describes how standard Cut, Copy, and Paste commands are implemented in an application. The example in this section uses these methods to place data on the clipboard using a registered clipboard format, the CF_OWNERDISPLAY format, and the CF_TEXT format. The registered format is used to represent rectangular or elliptical text windows, called labels.


 Selecting Data

Before information can be copied to the clipboard, the user must select specific information to be copied or cut. An application should provide a means for the user to select information within a document and some kind of visual feedback to indicate selected data.


 Creating an Edit Menu

An application should load an accelerator table containing the standard keyboard accelerators for the Edit menu commands. The TranslateAccelerator function must be added to the application's message loop for the accelerators to take effect. For more information about keyboard acceleratiors, see Keyboard Accelerators.


 Processing the WM_INITMENUPOPUP Message

Not all clipboard commands are available to the user at any given time. An application should process the WM_INITMENUPOPUP message to enable the menu items for available commands and disable unavailable commands.

Following is the WM_INITMENUPOPUP case for an application named Label.

case WM_INITMENUPOPUP:
    InitMenu((HMENU) wParam);
    break;

The InitMenu function is defined as follows.

void PASCAL InitMenu(HMENU hmenu)

{

    int  cMenuItems = GetMenuItemCount(hmenu);

    int  nPos;

    UINT id;

    UINT fuFlags;

    PLABELBOX pbox = (hwndSelected == NULL) ? NULL :

        (PLABELBOX) GetWindowLong(hwndSelected, 0);

    for (nPos = 0; nPos < cMenuItems; nPos++) {

        id = GetMenuItemID(hmenu, nPos);

        switch (id) {

            case IDM_CUT:

            case IDM_COPY:

            case IDM_DELETE:

                if (pbox == NULL || !pbox->fSelected)

                    fuFlags = MF_BYCOMMAND | MF_GRAYED;

                else if (pbox->fEdit)

                    fuFlags = (id != IDM_DELETE && pbox->ichSel

                            == pbox->ichCaret) ?

                        MF_BYCOMMAND | MF_GRAYED :

                        MF_BYCOMMAND | MF_ENABLED;

                else

                    fuFlags = MF_BYCOMMAND | MF_ENABLED;

                EnableMenuItem(hmenu, id, fuFlags);

                break;

            case IDM_PASTE:

                if (pbox != NULL && pbox->fEdit)

                    EnableMenuItem(hmenu, id,

                        IsClipboardFormatAvailable(CF_TEXT) ?

                            MF_BYCOMMAND | MF_ENABLED :

                            MF_BYCOMMAND | MF_GRAYED

                    );

                else

                    EnableMenuItem(hmenu, id,

                        IsClipboardFormatAvailable(

                                uLabelFormat) ?

                            MF_BYCOMMAND | MF_ENABLED :

                            MF_BYCOMMAND | MF_GRAYED

                    );

        }

    }

}


 Processing the WM_COMMAND Message

To process menu commands, add the WM_COMMAND case to your application's main window procedure. Following is the WM_COMMAND case for the Label application's window procedure.

case WM_COMMAND:

    switch (LOWORD(wParam)) {

        case IDM_CUT:

            if (EditCopy())

                EditDelete();

            break;

        case IDM_COPY:

            EditCopy();

            break;

        case IDM_PASTE:

            EditPaste();

            break;

        case IDM_DELETE:

            EditDelete();

            break;

        case IDM_EXIT:

            DestroyWindow(hwnd);

    }

    break;

To carry out the Copy and Cut commands, the window procedure calls the application-defined EditCopy function. For more information about the EditCopy function, see Copying Information to the Clipboard. To carry out the Paste command, the window procedure calls the application-defined EditPaste function. For more information about the EditPaste function, see Pasting Information from the Clipboard.


 Copying Information to the Clipboard

In the Label application, the application-defined EditCopy function copies the current selection to the clipboard. This function does the following:

1.	Opens the clipboard by calling the OpenClipboard function.

2.	Empties the clipboard by calling the EmptyClipboard function.

3.	Calls the SetClipboardData function once for each clipboard format the application provides.

4.	Closes the clipboard by calling the CloseClipboard function.

Depending on the current selection, the EditCopy function either copies a range of text or copies an application-defined structure representing an entire label. The structure, called LABELBOX, is defined as follows.

#define BOX_ELLIPSE  0

#define BOX_RECT     1

#define CCH_MAXLABEL 80

#define CX_MARGIN    12

typedef struct tagLABELBOX {  /* box */

    RECT rcText;    /* coordinates of rectangle containing text  */

    BOOL fSelected; /* TRUE if the label is selected             */

    BOOL fEdit;     /* TRUE if text is selected                  */

    int nType;      /* rectangular or elliptical                 */

    int ichCaret;   /* caret position                            */

    int ichSel;     /* with ichCaret, delimits selection         */

    int nXCaret;    /* window position corresponding to ichCaret */

    int nXSel;      /* window position corresponding to ichSel   */

    int cchLabel;   /* length of text in atchLabel               */

    TCHAR atchLabel[CCH_MAXLABEL];

} LABELBOX, *PLABELBOX;

Following is the EditCopy function.

BOOL PASCAL EditCopy(VOID)

{

    PLABELBOX pbox;

    LPTSTR  lptstrCopy;

    HGLOBAL hglbCopy;

    int ich1, ich2, cch;

    if (hwndSelected == NULL)

        return FALSE;

    /* Open the clipboard, and empty it. */

    if (!OpenClipboard(hwndMain))

        return FALSE;

    EmptyClipboard();

    /* Get a pointer to the structure for the selected label. */

    pbox = (PLABELBOX) GetWindowLong(hwndSelected, 0);

    /* If text is selected, copy it using the CF_TEXT format. */

    if (pbox->fEdit) {

        if (pbox->ichSel == pbox->ichCaret) {   /* zero-length */

            CloseClipboard();                   /* selection   */

            return FALSE;

        }

        if (pbox->ichSel < pbox->ichCaret) {

            ich1 = pbox->ichSel;

            ich2 = pbox->ichCaret;

        }

        else {

            ich1 = pbox->ichCaret;

            ich2 = pbox->ichSel;

        }

        cch = ich2 - ich1;

        /* Allocate a global memory object for the text. */

        hglbCopy = GlobalAlloc(GMEM_DDESHARE,

            (cch + 1) * sizeof(TCHAR));

        if (hglbCopy == NULL) {

            CloseClipboard();

            return FALSE;

        }

        /* Lock the handle and copy the text to the buffer. */

        lptstrCopy = GlobalLock(hglbCopy);

        memcpy(lptstrCopy, &pbox->atchLabel[ich1],

            cch * sizeof(TCHAR));

        lptstrCopy[cch] = (TCHAR) 0;    /* null character */

        GlobalUnlock(hglbCopy);

        /* Place the handle on the clipboard. */

        SetClipboardData(CF_TEXT, hglbCopy);

    }

    /* If no text is selected, the label as a whole is copied. */

    else {

        /*

         * Save a copy of the selected label as a local memory

         * object. This copy is used to render data on request.

         * It is freed in response to the WM_DESTROYCLIPBOARD

         * message.

         */

        pboxLocalClip = (PLABELBOX) LocalAlloc(

            LMEM_FIXED,

            sizeof(LABELBOX)

        );

        if (pboxLocalClip == NULL) {

            CloseClipboard();

            return FALSE;

        }

        memcpy(pboxLocalClip, pbox, sizeof(LABELBOX));

        pboxLocalClip->fSelected = FALSE;

        pboxLocalClip->fEdit = FALSE;

        /*

         * Place a registered clipboard format, the owner-display

         * format, and the CF_TEXT format on the clipboard using

         * delayed rendering.

         */

        SetClipboardData(uLabelFormat, NULL);

        SetClipboardData(CF_OWNERDISPLAY, NULL);

        SetClipboardData(CF_TEXT, NULL);

    }

    /* Close the clipboard. */

    CloseClipboard();

    return TRUE;

}


 Pasting Information from the Clipboard

In the Label application, the application-defined EditPaste function pastes the content of the clipboard. This function does the following:

1.	Opens the clipboard by calling the OpenClipboard function.

2.	Determines which of the available clipboard formats to retrieve.

3.	Retrieves the handle of the data in the selected format by calling the GetClipboardData function.

4.	Inserts a copy of the data into the document.

The handle returned by GetClipboardData is still owned by the clipboard, so an application must not free it or leave it locked.

5.	Closes the clipboard by calling the CloseClipboard function.

If a label is selected and contains an insertion point, the EditPaste function inserts the text from the clipboard at the insertion point. If there is no selection or if a label is selected, the function creates a new label, using the application-defined LABELBOX structure on the clipboard. The LABELBOX structure is placed on the clipboard by using a registered clipboard format.

Following is the EditPaste function.

VOID PASCAL EditPaste(VOID)

{

    PLABELBOX pbox;

    HGLOBAL   hglb;

    LPTSTR    lptstr;

    PLABELBOX pboxCopy;

    int cx, cy;

    HWND hwnd;

    pbox = hwndSelected == NULL ? NULL :

        (PLABELBOX) GetWindowLong(hwndSelected, 0);

    /*

     * If the application is in edit mode,

     * get the clipboard text.

     */

    if (pbox != NULL && pbox->fEdit) {

        if (!IsClipboardFormatAvailable(CF_TEXT))

            return;

        if (!OpenClipboard(hwndMain))

            return;

        hglb = GetClipboardData(CF_TEXT);

        if (hglb != NULL) {

            lptstr = GlobalLock(hglb);

            if (lptstr != NULL) {

                /*

                 * Call the application-defined ReplaceSelection

                 * function to insert the text and repaint the

                 * window.

                 */

                ReplaceSelection(hwndSelected, pbox, lptstr);

                GlobalUnlock(hglb);

            }

        }

        CloseClipboard();

        return;

    }

    /*

     * If the application is not in edit mode,

     * create a label window.

     */

    if (!IsClipboardFormatAvailable(uLabelFormat))

        return;

    if (!OpenClipboard(hwndMain))

        return;

    hglb = GetClipboardData(uLabelFormat);

    if (hglb != NULL) {

        pboxCopy = GlobalLock(hglb);

        if (pboxCopy != NULL) {

            cx = pboxCopy->rcText.right + CX_MARGIN;

            cy = pboxCopy->rcText.top * 2 + cyText;

            hwnd = CreateWindowEx(

                WS_EX_NOPARENTNOTIFY | WS_EX_TRANSPARENT,

                atchClassChild, NULL, WS_CHILD, 0, 0, cx, cy,

                hwndMain, NULL, hinst, NULL

            );

            if (hwnd != NULL) {

                pbox = (PLABELBOX) GetWindowLong(hwnd, 0);

                memcpy(pbox, pboxCopy, sizeof(LABELBOX));

                ShowWindow(hwnd, SW_SHOWNORMAL);

                SetFocus(hwnd);

            }

            GlobalUnlock(hglb);

        }

    }

    CloseClipboard();

}


 Registering a Clipboard Format

To register a clipboard format, add a call to the RegisterClipboardFormat function to your application's instance initialization function, as follows.

/* Register a clipboard format. */

LoadString(hinstCurrent, IDS_FORMATNAME, atchTemp,

    sizeof(atchTemp));

uLabelFormat = RegisterClipboardFormat(atchTemp);

if (uLabelFormat == 0)

    return FALSE;


 Processing the WM_RENDERFORMAT and WM_RENDERALLFORMATS Messages

If a window passes a NULL handle to the SetClipboardData function, it must process the WM_RENDERFORMAT and WM_RENDERALLFORMATS messages to render data upon request.

If the WM_RENDERFORMAT message delayed rendering a specific format and an application requested data in that format, the message is sent to the clipboard owner. If the WM_RENDERFORMAT message has delayed rendering one or more formats, the message is sent to the clipboard owner before it is destroyed.

To render a clipboard format, the window procedure must place a data handle on the clipboard by using the SetClipboardData function. It must not open the clipboard before calling SetClipboardData.

The Label application processes the WM_RENDERFORMAT and WM_RENDERALLFORMATS messages as follows.

case WM_RENDERFORMAT:

    RenderFormat((UINT) wParam);

    break;

case WM_RENDERALLFORMATS:

    RenderFormat(uLabelFormat);

    RenderFormat(CF_TEXT);

    break;

In both cases, the window procedure calls the application-defined RenderFormat function, defined as follows.

void PASCAL RenderFormat(UINT uFormat)

{

    HGLOBAL hglb;

    PLABELBOX pbox;

    LPTSTR  lptstr;

    int cch;

    if (pboxLocalClip == NULL)

        return;

    if (uFormat == CF_TEXT) {

        /* Allocate a buffer for the text. */

        cch = pboxLocalClip->cchLabel;

        hglb = GlobalAlloc(GMEM_DDESHARE,

            (cch + 1) * sizeof(TCHAR));

        if (hglb == NULL)

            return;

        /* Copy the text from pboxLocalClip. */

        lptstr = GlobalLock(hglb);

        memcpy(lptstr, pboxLocalClip->atchLabel,

            cch * sizeof(TCHAR));

        lptstr[cch] = (TCHAR) 0;

        GlobalUnlock(hglb);

        /* Place the handle on the clipboard. */

        SetClipboardData(CF_TEXT, hglb);

    }

    else if (uFormat == uLabelFormat) {

        hglb = GlobalAlloc(GMEM_DDESHARE, sizeof(LABELBOX));

        if (hglb == NULL)

            return;

        pbox = GlobalLock(hglb);

        memcpy(pbox, pboxLocalClip, sizeof(LABELBOX));

        GlobalUnlock(hglb);

        SetClipboardData(uLabelFormat, hglb);

    }

}


 Processing the WM_DESTROYCLIPBOARD Message

A window can process the WM_DESTROYCLIPBOARD message in order to free any resources that it set aside to support delayed rendering. For example the Label application, when copying a label to the clipboard, allocates a local memory object. It then frees this object in response to the WM_DESTROYCLIPBOARD message, as follows.

case WM_DESTROYCLIPBOARD:

    if (pboxLocalClip != NULL) {

        LocalFree(pboxLocalClip);

        pboxLocalClip = NULL;

    }

    break;


 Using the Owner-Display Clipboard Format

If a window places information on the clipboard by using the CF_OWNERDISPLAY clipboard format, it must do the following:

•	Process the WM_PAINTCLIPBOARD message. This message is sent to the clipboard owner when a portion of the clipboard viewer window must be repainted.

•	Process the WM_SIZECLIPBOARD message. This message is sent to the clipboard owner when the clipboard viewer window has been resized or its content has changed.

Typically, a window responds to this message by setting the scroll positions and ranges for the clipboard viewer window. In response to this message, the Label application also updates a SIZE structure for the clipboard viewer window.

•	Process the WM_HSCROLLCLIPBOARD and WM_VSCROLLCLIPBOARD messages. These messages are sent to the clipboard owner when a scroll bar event occurs in the clipboard viewer window.

•	Process the WM_ASKCBFORMATNAME message. The clipboard viewer window sends this message to an application to retrieve the name of the owner-display format.

The window procedure for the Label application processes these messages, as follows.

LRESULT CALLBACK MainWindowProc(hwnd, msg, wParam, lParam)

HWND hwnd;

UINT msg;

WPARAM wParam;

LPARAM lParam;

{

    static RECT rcViewer;

    RECT rc;

    LPRECT lprc;

    LPPAINTSTRUCT lpps;

    .

    .

    .

    switch (msg) {

        .

        .

        .

        case WM_PAINTCLIPBOARD:

            /* Determine the dimensions of the label. */

            SetRect(&rc, 0, 0,

                pboxLocalClip->rcText.right + CX_MARGIN,

                pboxLocalClip->rcText.top * 2 + cyText

            );

            /* Center the image in the clipboard viewer window. */

            if (rc.right < rcViewer.right) {

                rc.left = (rcViewer.right - rc.right) / 2;

                rc.right += rc.left;

            }

            if (rc.bottom < rcViewer.bottom) {

                rc.top = (rcViewer.bottom - rc.bottom) / 2;

                rc.bottom += rc.top;

            }

            /*

             * Paint the image, using the specified PAINTSTRUCT

             * structure, by calling the application-defined

             * PaintLabel function.

             */

            lpps = (LPPAINTSTRUCT) GlobalLock((HGLOBAL) lParam);

            PaintLabel(lpps, pboxLocalClip, &rc);

            GlobalUnlock((HGLOBAL) lParam);

            break;

        case WM_SIZECLIPBOARD:

            /*

             * Save the dimensions of the window in a static

             * RECT structure.

             */

            lprc = (LPRECT) GlobalLock((HGLOBAL) lParam);

            memcpy(&rcViewer, lprc, sizeof(RECT));

            GlobalUnlock((HGLOBAL) lParam);

            /*

             * Set the scroll ranges to zero (thus eliminating

             * the need to process the WM_HSCROLLCLIPBOARD and

             * WM_VSCROLLCLIPBOARD messages).

             */

            SetScrollRange((HWND) wParam, SB_HORZ, 0, 0, TRUE);

            SetScrollRange((HWND) wParam, SB_VERT, 0, 0, TRUE);

            break;

        case WM_ASKCBFORMATNAME:

            LoadString(hinst, IDS_OWNERDISPLAY,

                (LPSTR) lParam, wParam);

            break;

            .

            .

            .

        default:

            return DefWindowProc(hwnd, msg, wParam, lParam);

    }

    return 0;

}


 Creating a Clipboard Viewer Window

A clipboard viewer window displays the current content of the clipboard, and receives messages when the clipboard content changes. To create a clipboard viewer window, your application must do the following:

•	Add the window to the clipboard viewer chain.

•	Process the WM_CHANGECBCHAIN message.

•	Process the WM_DRAWCLIPBOARD message.

•	Remove the window from the clipboard viewer chain before it is destroyed.


 Adding a Window to the Clipboard Viewer Chain

A window adds itself to the clipboard viewer chain by calling the SetClipboardViewer function. The return value is the handle of the next window in the chain. A window must keep track of this value — for example, by saving it in a static variable named hwndNextViewer.

The following example adds a window to the clipboard viewer chain in response to the WM_CREATE message.

case WM_CREATE:

    /* Add the window to the clipboard viewer chain. */

    hwndNextViewer = SetClipboardViewer(hwnd);

    break;


 Processing the WM_CHANGECBCHAIN Message

A clipboard viewer window receives the WM_CHANGECBCHAIN message when another window is removing itself from the clipboard viewer chain. If the window being removed is the next window in the chain, the window receiving the message must unlink the next window from the chain. Otherwise, this message should be passed to the next window in the chain.

The following example shows the processing of the WM_CHANGECBCHAIN message.

case WM_CHANGECBCHAIN:

    /* If the next window is closing, repair the chain. */

    if ((HWND) wParam == hwndNextViewer)

        hwndNextViewer = (HWND) lParam;

    /* Otherwise, pass the message to the next link. */

    else if (hwndNextViewer != NULL)

        SendMessage(hwndNextViewer, uMsg, wParam, lParam);

    break;


 Removing a Window from the Clipboard Viewer Chain

To remove itself from the clipboard viewer chain, a window calls the ChangeClipboardChain function. The following example removes a window from the clipboard viewer chain in response to the WM_DESTROY message.

case WM_DESTROY:

    ChangeClipboardChain(hwnd, hwndNextViewer);

    PostQuitMessage(0);

    break;


 Processing the WM_DRAWCLIPBOARD Message

The WM_DRAWCLIPBOARD message notifies a clipboard viewer window that the content of the clipboard has changed. A window should do the following when processing the WM_DRAWCLIPBOARD message:

1.	Determine which of the available clipboard formats to display.

2.	Retrieve the clipboard data and display it in the window. Or if the clipboard format is CF_OWNERDISPLAY, send a WM_PAINTCLIPBOARD message to the clipboard owner.

3.	Send the message to the next window in the clipboard viewer chain.

For an example of processing the WM_DRAWCLIPBOARD message, see the example listing in Example of a Clipboard Viewer.


 Example of a Clipboard Viewer

The following example shows a simple clipboard viewer application.

HINSTANCE hinst;

UINT uFormat = (UINT)(-1);

BOOL fAuto = TRUE;

LRESULT APIENTRY MainWndProc(hwnd, uMsg, wParam, lParam)

HWND hwnd;

UINT uMsg;

WPARAM wParam;

LPARAM lParam;

{

    static HWND hwndNextViewer;

    HDC hdc;

    HDC hdcMem;

    PAINTSTRUCT ps;

    LPPAINTSTRUCT lpps;

    RECT rc;

    LPRECT lprc;

    HGLOBAL hglb;

    LPSTR lpstr;

    HBITMAP hbm;

    HENHMETAFILE hemf;

    HWND hwndOwner;

    switch (uMsg) {

        case WM_PAINT:

            hdc = BeginPaint(hwnd, &ps);

            /* Branch depending on the clipboard format. */

            switch (uFormat) {

                case CF_OWNERDISPLAY:

                    hwndOwner = GetClipboardOwner();

                    hglb = GlobalAlloc(GMEM_DDESHARE,

                        sizeof(PAINTSTRUCT));

                    lpps = GlobalLock(hglb);

                    memcpy(lpps, &ps, sizeof(PAINTSTRUCT));

                    GlobalUnlock(hglb);

                    SendMessage(hwndOwner, WM_PAINTCLIPBOARD,

                        (WPARAM) hwnd, (LPARAM) hglb);

                    GlobalFree(hglb);

                    break;

                case CF_BITMAP:

                    hdcMem = CreateCompatibleDC(hdc);

                    if (hdcMem != NULL) {

                        if (OpenClipboard(hwnd)) {

                            hbm = (HBITMAP)

                                GetClipboardData(uFormat);

                            SelectObject(hdcMem, hbm);

                            GetClientRect(hwnd, &rc);

                            BitBlt(hdc, 0, 0, rc.right, rc.bottom,

                                hdcMem, 0, 0, SRCCOPY);

                            CloseClipboard();

                        }

                        DeleteDC(hdcMem);

                    }

                    break;

                case CF_TEXT:

                    if (OpenClipboard(hwnd)) {

                        hglb = GetClipboardData(uFormat);

                        lpstr = GlobalLock(hglb);

                        GetClientRect(hwnd, &rc);

                        DrawText(hdc, lpstr, -1, &rc, DT_LEFT);

                        GlobalUnlock(hglb);

                        CloseClipboard();

                    }

                    break;

                case CF_ENHMETAFILE:

                    if (OpenClipboard(hwnd)) {

                        hemf = GetClipboardData(uFormat);

                        GetClientRect(hwnd, &rc);

                        PlayEnhMetaFile(hdc, hemf, &rc);

                        CloseClipboard();

                    }

                    break;

                case 0:

                    GetClientRect(hwnd, &rc);

                    DrawText(hdc, "The clipboard is empty.", -1,

                        &rc, DT_CENTER | DT_SINGLELINE |

                        DT_VCENTER);

                    break;

                default:

                    GetClientRect(hwnd, &rc);

                    DrawText(hdc, "Unable to display format.", -1,

                        &rc, DT_CENTER | DT_SINGLELINE |

                        DT_VCENTER);

            }

            EndPaint(hwnd, &ps);

            break;

        case WM_SIZE:

            if (uFormat == CF_OWNERDISPLAY) {

                hwndOwner = GetClipboardOwner();

                hglb = GlobalAlloc(GMEM_DDESHARE, sizeof(RECT));

                lprc = GlobalLock(hglb);

                GetClientRect(hwnd, lprc);

                GlobalUnlock(hglb);

                SendMessage(hwndOwner, WM_SIZECLIPBOARD,

                    (WPARAM) hwnd, (LPARAM) hglb);

                GlobalFree(hglb);

            }

            break;

        case WM_CREATE:

            /* Add the window to the clipboard viewer chain. */

            hwndNextViewer = SetClipboardViewer(hwnd);

            break;

        case WM_CHANGECBCHAIN:

            /* If the next window is closing, repair the chain. */

            if ((HWND) wParam == hwndNextViewer)

                hwndNextViewer = (HWND) lParam;

            /* Otherwise, pass the message to the next link. */

            else if (hwndNextViewer != NULL)

                SendMessage(hwndNextViewer, uMsg, wParam, lParam);

            break;

        case WM_DESTROY:

            ChangeClipboardChain(hwnd, hwndNextViewer);

            PostQuitMessage(0);

            break;

        case WM_DRAWCLIPBOARD:  /* clipboard contents changed. */

            /*

             * Update the window by using Auto clipboard format.

             */

            SetAutoView(hwnd);

            /*

             * Pass the message to the next window in clipboard

             * viewer chain.

             */

            SendMessage(hwndNextViewer, uMsg, wParam, lParam);

            break;

        case WM_INITMENUPOPUP:

            if (!HIWORD(lParam))

                InitMenu(hwnd, (HMENU) wParam);

            break;

        case WM_COMMAND:

            switch (LOWORD(wParam)) {

                case IDM_EXIT:

                    DestroyWindow(hwnd);

                    break;

                case IDM_AUTO:

                    SetAutoView(hwnd);

                    break;

                default:

                    fAuto = FALSE;

                    uFormat = LOWORD(wParam);

                    InvalidateRect(hwnd, NULL, TRUE);

            }

            break;

        default:

            return DefWindowProc(hwnd, uMsg, wParam, lParam);

    }

    return (LRESULT) NULL;

}

void PASCAL SetAutoView(HWND hwnd)

{

    static UINT auPriorityList[] = {

        CF_OWNERDISPLAY,

        CF_TEXT,

        CF_ENHMETAFILE,

        CF_BITMAP

    };

    uFormat = GetPriorityClipboardFormat(auPriorityList, 4);

    fAuto = TRUE;

    InvalidateRect(hwnd, NULL, TRUE);

    UpdateWindow(hwnd);

}

void PASCAL InitMenu(HWND hwnd, HMENU hmenu)

{

    UINT uFormat;

    char szFormatName[80];

    LPCSTR lpFormatName;

    UINT fuFlags;

    UINT idMenuItem;

    /*

     * If a menu is not the display menu, no initialization is necessary. */

     */

    if (GetMenuItemID(hmenu, 0) != IDM_AUTO)

        return;

    /* Delete all menu items except the first. */

    while (GetMenuItemCount(hmenu) > 1)

        DeleteMenu(hmenu, 1, MF_BYPOSITION);

    /* Check or uncheck the Auto menu item. */

    fuFlags = fAuto ? MF_BYCOMMAND | MF_CHECKED :

        MF_BYCOMMAND | MF_UNCHECKED;

    CheckMenuItem(hmenu, IDM_AUTO, fuFlags);

    /* If there are no clipboard formats, return. */

    if (CountClipboardFormats() == 0)

        return;

    /* Open the clipboard. */

    if (!OpenClipboard(hwnd))

        return;

    /* Add a separator and then a menu item for each format. */

    AppendMenu(hmenu, MF_SEPARATOR, 0, NULL);

    uFormat = EnumClipboardFormats(0);

    while (uFormat) {

        /*

         * Call an application-defined function to get the name

         * of the clipboard format.

         */

        lpFormatName = GetPredefinedClipboardFormatName(uFormat);

        /* For registered formats, get the registered name. */

        if (lpFormatName == NULL) {

            if (GetClipboardFormatName(uFormat, szFormatName,

                    sizeof(szFormatName)))

                lpFormatName = szFormatName;

            else

                lpFormatName = "(unknown)";

        }

        /*

         * Add a menu item for the format. For displayable

         * formats, use the format ID for the menu ID.

         */

        if (IsDisplayableFormat(uFormat)) {

            fuFlags = MF_STRING;

            idMenuItem = uFormat;

        }

        else {

            fuFlags = MF_STRING | MF_GRAYED;

            idMenuItem = 0;

        }

        AppendMenu(hmenu, fuFlags, idMenuItem, lpFormatName);

        uFormat = EnumClipboardFormats(uFormat);

    }

    CloseClipboard();

}

BOOL PASCAL IsDisplayableFormat(UINT uFormat)

{

    switch (uFormat) {

        case CF_OWNERDISPLAY:

        case CF_TEXT:

        case CF_ENHMETAFILE:

        case CF_BITMAP:

            return TRUE;

    }

    return FALSE;

}


 Clipboard Reference

The following functions and messages are associated with the Clipboard.


 Clipboard Functions

Following are the functions used with the Clipboard.

ChangeClipboardChain
CloseClipboard
CountClipboardFormats
EmptyClipboard
EnumClipboardFormats
GetClipboardData
GetClipboardFormatName
GetClipboardOwner
GetClipboardViewer
GetOpenClipboardWindow
GetPriorityClipboardFormat
IsClipboardFormatAvailable
OpenClipboard
RegisterClipboardFormat
SetClipboardData
SetClipboardViewer


 Clipboard Messages

Following are the messages used with the clipboard.

WM_ASKCBFORMATNAME
WM_CHANGECBCHAIN
WM_COPY
WM_CUT
WM_DESTROYCLIPBOARD
WM_DRAWCLIPBOARD
WM_HSCROLLCLIPBOARD
WM_PAINTCLIPBOARD
WM_PASTE
WM_RENDERALLFORMATS
WM_RENDERFORMAT
WM_SIZECLIPBOARD
WM_VSCROLLCLIPBOARD


Chapter 1


 Common Dialog Box Library

The following Windows 95 overview discusses the Common Dialog Box Library. Various common dialog boxes are described, and examples are included to help you use common dialog boxes in your Win32-based applications.


 Common Dialog Box Library Platform Differences

The overviews for common dialog box libraries in Windows 95 and Windows NT are substantially different. To accommodate these differences, the Windows 95 overview is first presented in its entirety, followed by the Windows NT version.


 About Common Dialog Boxes

Windows 95 Overview
For more information, see the Windows NT overview About Common Dialog Boxes.

Common dialog boxes are the standard file, print, color, font, and search dialog boxes used by applications based on the Microsoft Win32 application programming interface (API). Common dialog boxes provide a uniform user interface that lets users carry out common tasks, such as opening files and printing documents, without being forced to learn new techniques with each application.

You can create common dialog boxes for your own 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.


 Common Dialog Box Basics

Common dialog boxes offer varying levels of control to the application. When you use a common dialog box in its simplest form, you fill a structure with initial values, call a function, and retrieve the user's input from the structure after the function returns. But you can also specify options that modify the appearance and behavior of a common dialog; create hook functions that let you monitor and filter messages sent to the dialog box procedure; use registered messages to receive or send information to the dialog box; and modify or replace the template that defines the number, type, and position of controls in the dialog box. The following sections describe the basics you need to work with common dialog boxes at all levels of control.


 Dialog Box Types

Although you create all common dialog boxes in essentially the same way (by filling a structure with initial values and calling a dialog box function), you use different functions and structures to create the different common dialog box types. There are these common dialog boxes:

Color	Displays available colors and lets the user select basic colors or create a select custom colors. Use the ChooseColor function and CHOOSECOLOR structure.
Font	Displays lists of facenames, point sizes, and other font attributes that the user can select. Use the ChooseFont function and CHOOSEFONT structure.
Open	Displays the names of files, directories and drives, and lets the user select the combination of names that uniquely identifies the file to be opened. Use the GetOpenFileName function and OPENFILENAME structure.
Save As	Displays the names of files, directories and drives, and lets the user select or enter the combination of names that uniquely identifies the file to be saved. Use the GetSaveFileName function and OPENFILENAME structure.
Print	Displays and lets the user select print job options, such as the range of pages to print and the number of copies. Use the PrintDlg function. and PRINTDLG structure.
Page Setup	Displays and lets the user select page configuration options, such as paper orientation, size, source, and margins. Use the PageSetupDlg function and PAGESETUPDLG structure.
Find	Displays and lets the user select a search string and search options, such as the direction of the search. Use the FindText function and FINDREPLACE structure.
Replace	Displays and lets the user select search and replacement strings and replacement options, such as the direction of the search and the scope of the replacement. Use the ReplaceText function and FINDREPLACE structure.
Although a Print Setup dialog box is also available, it has been superseded by the Page Setup dialog box. Applications written for Win32 API version 4.0 or later should not use the Print Setup dialog box.

All common dialog boxes, except the Find and Replace dialog boxes, are modal. This means the function that you use the create the dialog box does not return until the user has closed the dialog box. 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 process dialog box keys, such as TAB and ESC, correctly.


 Initialization Flags

You can modify the behavior and appearance of a common dialog box by using initialization flags. These are 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 functions 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 controls that let the user choose the color of the logical font as well as whether to use strike through and underline effects.

The initialization flag values are unique to each common dialog box and are described in detail with the corresponding structures.


 Hook Functions and Custom Dialog Box Templates

Windows 95 Overview
For more information, see the Windows NT overview Hook Functions and Custom Dialog Box Templates.

All common dialog box functions use default dialog box procedures to process messages for the dialog box and its controls. You can customize the operation of a common dialog box by providing a hook function that monitors and responds to messages sent to the default dialog box procedure. You enable a hook procedure by setting an ENABLEHOOK value in the Flags member and the address of the hook function in an lpfnHook member of the structure for the dialog box. A hook function has this general form:

UINT APIENTRY MyHook(HWND hdlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
    switch (wParam) {
    case WM_*:
        // process the message
        return TRUE;
    default:
        return FALSE;
    }
}

The hook function receives messages and notifications before the dialog box procedure attempts to process them. (The exception is the WM_INITDIALOG message which the hook function receives after the dialog box procedure.) The hook function can process a message or let the dialog box procedure process it. If the hook function processes a message, it must return TRUE; otherwise, it must must return FALSE to direct the dialog procedure to process the message.

If the hook function 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 given control.

A hook function should never attempt to terminate the dialog box by calling the EndDialog function. Instead, the function must use 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 an application needs a specific error code, it must work out its own comunication mechanism with the hook function.

Although you can subclass controls in any of the common dialog boxes, you must do so from the hook function while processing the WM_INITDIALOG message. Because the common dialog box procedure may also subclass the controls, subclassing after the dialog box procedure ensures that your subclass hook procedure receives the control-specific messages before the subclass hook procedure set by the dialog box procedure.


 Registered Messages and Message Strings

Common dialog boxes send registered messages to your window procedure or hook function to notify you of events and to request responses. A registered message is like any other window message except that the message identifier is not predefined. Before you can detect and process a registered message, you must retrieve the message identifier by passing the predefined message string to the RegisterWindowMessage function. There are these predefined message strings:

COLOROKSTRING	Approve or reject a color selection.
FILEOKSTRING	Approve or reject a filename.
FINDMSGSTRING	Find or replace a given string.
HELPMSGSTRING	Display help for a dialog box.
LBSELCHSTRING	Selection in a list box has changed.
SETRGBSTRING	Set the current color selection.
SHAREVISTRING	Opening a file causes a sharing violation.
The Find and Replace dialog boxes send their registered message, FINDMSGSTRING, to the window procedure of the window that owns the dialog box. Other common dialog boxes send their registered messages to hook functions. This means you must enable the hook function for these dialog boxes to receive the messages. One registered message, SETRGBSTRING, is intended to be sent to the common dialog box from the hook function.

In addition to registered messages, some common dialog boxes send and can accept other window messages. For example, the hook function for a Font dialog box can send the WM_CHOOSEFONT_GETLOGFONT message to retrieve the current logical font selections. These other messages and the registered messages are described in more detail in the sections later in this chapter that described the inidividual common dialog boxes.


 Custom Templates

All common dialog box functions use default templates to define the number, type and position of controls in the dialog box. You can give users access to additional controls that are unique to your application by defining custom templates. For some dialog boxes, the custom template replaces the default template; for others, the custom template defines a "child" dialog box whose controls are combined with the controls specified by the default template.

Because a primary goal for common dialog boxes is to provide a consistent user interface for all applications, it is important that you customize a common dialog box only when it is absolutely necessary. If you do customize, always try to leave the original controls intact. In particular, avoid hiding a control or changing its function. If you add new controls, place them in empty space already in the dialog box or increase the size of the dialog box to make space.

You enable a custom template by setting a ENABLETEMPLATE or ENABLETEMPLATEHANDLE value in the Flags member in the corresponding structure for the dialog box. If the template is a resource in an application or dynamic link library, you must set the hInstance and lpTemplateName members of the structure. If the template is already in memory, the member you set depends on the given structure. In most cases, you must also enable a hook function for the dialog box to support and process input for the additional controls in your custom template.

When making a custom template, make sure the identifiers for the controls that you add are unique and do not conflict with existing controls. The default templates and identifier values are available in resource script (.DLG) and corresponding header (.H) files. Use these to determine the identifiers for the default controls.


 Help Support

All common dialog boxes provide online help by default. The user can display help for individual controls by selecting the control and pressing the F1 key or by clicking the ? button in the title bar and subsequently clicking on a control.

If you customize a dialog box by adding new controls, you also need to extend help support for these controls by processing requests for help in the hook function. The hook function receives WM_HELP or WM_CONTEXTMENU messages when the user requests help by pressing the F1 key, using the ? button, or clicking the right mouse button. You should process these messages for the controls you have added, but let the default dialog box procedure process the messages for the original controls. For more information about how to process these messages, see the chapter describing the WinHelp function.

Although no longer recommended, you can supplement the default help by adding and supporting a Help button in the the dialog box. The Help button is useful for describing the general purpose of the dialog box as it applies to your application. You add a Help button to a dialog box by setting a SHOWHELP value in the Flags member of the structure for the dialog box. You support the Help button by processing the registered message associated with the HELPMSGSTRING message string. The common dialog box sends this message to the window procedure of the owner window whenever the user clicks the Help button.


 Color Dialog Box

Windows 95 Overview
For more information, see the Windows NT overview Color Dialog Box.

The Color dialog box lets users select from a set of basic colors or create and select from a set of custom colors. You create and display a Color dialog box by initializing a CHOOSECOLOR structure and passing the structure to the ChooseColor function. The Color dialog box typically looks like this:

If the user chooses a color and clicks the OK button, ChooseColor returns TRUE and sets the rgbResult member of the CHOOSECOLOR structure to the RGB color value corresponding to 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 RGB macro to create color values, and the GetRValue, GetBValue, and GetGValue macros to extract individual colors from a color value.

If the user cancels the Color dialog box or an error occurs, ChooseColor returns FALSE and the rgbResult member is not defined. You can determine the cause of an error by using the CommDlgExtendedError function to retrieve the extended error value.

The user can select from either the basic colors or custom colors. The basic colors, set by the Color dialog box, represent a reasonable selection of the colors available on the given device. Custom colors are reserved for colors that you choose or that the user creates. You must set the initial values for the 16 custom colors by setting the elements of the array pointed to by the lpCustColors member of the CHOOSECOLOR structure to the desired RGB color values.

You can modify the appearance and behavior of the Color dialog box by setting the Flags member of the CHOOSECOLOR structure to selected values. For example, you can direct the dialog box to display only solid colors by using the CC_SOLIDCOLOR value and you can direct the dialog box to propose an initial color selection (other than black) by setting the rgbResult member to the desired color value and using the CC_RGBINIT value.

The user can create custom colors by clicking the Define Custom Colors button in the dialog box. This displays an extension to the Color dialog box with which the user can pick a color, enter an RGB color value directly, or enter an RGB value indirectly by supplying hue, saturation, and luminousity (HSL) values. You can direct the Color dialog box to always display this extension by setting the Flags member to CC_FULLOPEN. You can prevent this extension from displaying by using the CC_PREVENTFULLOPEN value to disable the Define Custom Colors button. When the user creates a custom color, the dialog box also copies the new RGB color value to the corresponding element in the array pointed to by the lpCustColors member. To preserve new custom colors between calls to ChooseFont, it is recommended that you allocate static memory for the array.

You can enable a hook function for the dialog box by setting the CC_ENABLEHOOK value in the Flags member; the lpfnHook member must specify the address of the hook function. The dialog box sends the registered message defined by the COLOROKSTRING message string to the hook function whenever the user selects a color and click the OK button. The hook function returns a nonzero value to accept this color value; zero to reject it and keep the dialog box open. You can force the dialog box to select a given color by sending the registered message defined by the SETRGBSTRING message string from the hook function to the dialog box.

You can customize the Color dialog box by setting the CC_ENABLETEMPLATE or CC_ENABLETEMPLATEHANDLE value in the Flags member. Because the Color dialog box replaces the default template with the custom template, you should always start with the default template, specified in the COLOR.DLG file, when creating the custom template.


 Font Dialog Box

Windows 95 Overview
For more information, see the Windows NT overview 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, effect (underline or strikeout), text color, and 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 Font dialog box typically looks like this:

If the user chooses font attributes and 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.

If the user cancels the Font dialog box or an error occurs, ChooseFont returns FALSE and the LOGFONT structure is not defined. You can determine the cause of an error by using the CommDlgExtendedError function to retrieve the extended error value.

When initializing the CHOOSEFONT structure, you must set the Flags member to CF_SCREENFONTS, CF_PRINTERFONTS, or CF_BOTH. To display the options for strikeout, underline, and color, you must use the CF_EFFECTS value.

To list device fonts for a printer, you must obtain a device context (DC) handle for the printer and use this handle in the hDC member of the CHOOSEFONT structure. To restrict the fonts the dialog box displays, you can use the CF_TTONLY, CF_FIXEDPITCHONLY, CF_NOVECTORFONTS, CF_NOVERTFONTS, CF_SCALABLEONLY, and CF_WYSIWYG values. You can also restrict the available styles, point sizes, and effects the dialog box displays for some fonts by using the CF_NOSIMULATIONS value. You can restrict the scripts represented by the displayed fonts by using the CF_SCRIPTSONLY and CF_SELECTSCRIPT values.

You can use the CF_INITTOLOGFONTSTRUCT value in Flags to initialize the controls in the dialog box with the values given in the LOGFONT structure. To initialize the text color, set the rgbColors member of CHOOSEFONT to a RGB color value. You can use the CF_USESTYLE to initialize the style control to the style name given in the buffer pointed to by the lpszStyle member. Use the CF_NOFACESEL, CF_NOSTYLESEL, CF_NOSIZESEL, and CF_NOSCRIPTSEL values 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, point size, or script value. These values will also be set in Flags when ChooseFont returns if the user did not select a corresponding value.

You can force the user to enter only valid typeface names, styles, and point sizes by using the CF_FORCEFONTEXIST value. You can further force the user to enter only point sizes in a given range by using the CF_LIMITSIZE value and setting the minimum and maximum point sizes in the nSizeMin and nSizeMax members.

You can enable the hook function for the Font dialog box by setting the CF_ENABLEHOOK value in Flags and setting the lpfnHook member to the address of the function. The dialog box procedure sends a WM_INITDIALOG message to the hook function with the lParam parameter set to the address of the CHOOSEFONT structure used to initialize the dialog box. The hook function 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. This is especially useful when processing processing the WM_COMMAND sent by the Apply button. (You can enable the Apply button by setting the Flags member to CF_APPLY.) The function can send the WM_CHOOSEFONT_SETLOGFONT to force the current selections to given values. The function can also send the WM_CHOOSEFONT_SETFLAGS message to set flags to the given value.

You can customize the Font dialog box by setting the CF_ENABLETEMPLATE or CF_ENABLETEMPLATEHANDLE value in the Flags member. Because the Font dialog box replaces the default template with the custom template, you should always start with the default template, specified in the FONT.DLG file, when creating the custom template.


 Open and Save As Dialog Boxes

Windows 95 Overview
For more information, see the Windows NT overview Open and Save As Dialog Boxes.

The Open dialog box and the Save As dialog box let the user choose the location (drive and directory) and the name of a file or a set of files to open and save. The dialog boxes are nearly identical in appearance and behavior and you initialize them using the same OPENFILENAME structure. You create the Open dialog box by using the GetOpenFileName function and the Save As dialog box by using the GetSaveFileName function.

The appearance of the dialog boxes these functions create depend on the version of the Win32 API and whether you set the OFN_EXPLORER value in the Flags member of the OPENFILENAME structure. When running under version 4.0 or with OFN_EXPLORER, the dialog boxes provide user-interface features that are similar to the Windows Explorer. The Open dialog box looks like this:

The Save As dialog box looks like this:

Although the default title for a dialog box is either Open or Save As, you can change the title by setting the lpstrTitle member to the address of a new title. Also, you can hide the Open as read only option by using the OFN_HIDEREADONLY value. If this option is not hidden, the dialog box sets Flags to OFN_READONLY on return if the user checks this option.


 Filenames and Directories

To retrieve a filename from the dialog box, you must set the lpstrFile member of the OPENFILENAME structure to the address of the buffer to receive the filename and set the nMaxFile member to the size of that buffer. Buffer sizes must be in bytes for the ANSI version of the structure and characters for the Unicode version. If the user chooses a filename and clicks the OK button, the dialog box copies the selected drive, directory, and filename to the given buffer. The function also sets the nFileOffset and nFileExtension members to the offsets, in bytes or characters, from the start of the buffer to the filename and to the filename extension, respectively. You can retrieve just the filename from the buffer pointed to by lpstrFile by using the GetFileTitle function. Alternately you can have the dialog box copy the filename to a buffer by setting the lpstrFileTitle member to the address of the buffer and the nMaxFileTitle member to size of the buffer.

If the user cancels the dialog box or an error occurs, the function returns FALSE. You can determine the cause of an error by using the CommDlgExtendedError function to retrieve the extended error value. If the buffer is too small to receive the full name, the CommDlgExtendedError function 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.

The dialog box uses the current directory as the initial directory from which to display files and directories. You can set your own initial directory by setting the lpstrInitialDir member to the address of a string that specifies a directory. To prevent the dialog box from changing the current directory for the application, you can set the Flags member to OFN_NOCHANGEDIR. The user can still change directories to find a file, but the dialog box returns to the original directory when it closes.

You can direct the dialog box to add a default filename extension, if the user does not, by setting the lpstrDefExt member to the address of a string specifying an extension. Otherwise, the dialog box leaves filenames without extensions. If the user explicitly enters an extension or selects a file that already has an extension, the dialog box sets the Flags member to OFN_EXTENSIONDIFFERENT if that extension is different than that given by lpstrDefExt.

You can let the user select more than one file from a directory by using the OFN_ALLOWMULTISELECT value. If this case, the dialog box copies two or more consecutive, null-terminated strings to the buffer pointed to by lpstrFile. The first string specifies the selected drive and directory; all subsequent strings specify the names of files. The last string ends with an extra null character. The nFileExtension member is not used, and the nFileOffset member is the offset to the first filename.


 Filters

You can restrict the number of files displayed by the dialog box by setting the lpstrFilter member to the address of a buffer that contains one or more filters. A filter consists of two 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; it uses the pattern to pick out which files to display. The pattern can be a combination of valid filename characters and the asterisk (*). The asterisk is a wildcard that represents any combination of valid filename characters. The dialog box displays only those files that match the pattern. For example, if the pattern is "*.TXT", the dialog box displays only the files having the filename extension TXT. You can have multiple patterns for a given description, but must separate each pattern from the preceding with a semicolon (;).

You can supply multiple filters by concatenating them in the buffer. You must terminate the last filter with an extra null character. You can specify which filter the dialog box should initially use by setting the nFilterIndex member to the index of the filter. 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 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.


 File and Directory Validation

The dialog box automatically checks filenames entered by the user to make sure the names contain valid characters. You can also direct the dialog to verify that the given file or drive and directory exist by using the OFN_FILEMUSTEXIST or OFN_PATHMUSTEXIST value, respectively. You can override the filename character validation by using the OFN_NOVALIDATE value.

The dialog box returns an error if opening the selected file would cause a sharing violation. You can direct the dialog box to send notification messages about sharing violations by using the OFN_SHAREAWARE value.

When using the Save As dialog box, you can direct the dialog box to prompt the user for permission to create a new file or overwrite an existing file by using the OFN_CREATEPROMPT and OFN_OVERWRITEPROMPT values. By default, the dialog box tests whether a new file can be created in the selected directory by creating a zero-length test file. You can prevent the creation of this test file by using the OFN_NOTESTFILECREATE value.

You can prevent the dialog box from return names of existing files that have the read-only attribute by using the OFN_NOREADONLYRETURN value. You can also prevent the dialog box from dereferencing link files by using 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.


 Hook Function

Windows 95 Overview
For more information, see the Windows NT overview The Hook Function.

You can enable a hook function for the dialog box by using the OFN_ENABLEHOOK value and setting the lpfnHook member to the address of the function. The hook function lets you monitor messages sent from the dialog box procedure. It also lets you support any controls you may add to the dialog box as described in the next section. When enabling the hook function, you should also set the OFN_EXPLORER value in the Flags member to make sure the dialog box displays the Windows Explorer-style user interface. This section only describes the hook function for dialog boxes created using OFN_EXPLORER.

The hook function receives a variety of messages while the dialog box is created and eventually destroyed. For example, the hook function receives a WM_INITDIALOG message with the lParam parameter set to the address of the OPENFILENAME structure used to initialize the dialog box. Most messages, however, are WM_NOTIFY notification messages indicating actions taken by the user in the dialog box. The lParam parameter for each WM_NOTIFY message is the address of a OFNOTIFY structure that defines the action. The code member in the header for the OFNOTIFY structure contains one of these notification values:

CDN_FILEOK	The user click the Open or Save button; the dialog box is about to close.
CDN_FOLDERCHANGE	A new folder has been opened in the Open or Save As dialog box.
CDN_HELP	The user clicked the Help button.
CDN_INITDONE	The system has finished initializing the dialog box, and the dialog box has finished processing the WM_INITDIALOG message. Also, the system has finished arranging controls in the common dialog box to make room for the controls of the child dialog box (if any).
CDN_SELCHANGE	The user has 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 "Files of type" combo box.
These messages are useful for modifying the behavior of the dialog box. For example, the hook function receives the CDN_FILEOK message when to user chooses a filename and clicks the OK button. The hook function can accept or reject the selected name by returning 0 or 1, respectively. Rejecting the filename forces the dialog box to remain open. To return a value from the hook function, you must set the message result value by using the SetWindowLong function and the DWL_MSGRESULT value.

Although the WM_NOTIFY messages supersede the registered messages previously used with the Open and Save As dialog boxes (such as the FILEOKSTRING, LBSELCHSTRING, SHAREVISTRING, and HELPMSGSTRING messages), the hook function also receives the superseded message after the WM_NOTIFY message if it does not use SetWindowLong to set the message result value or sets this value to zero.

You can send messages to the dialog box from the hook function to retrieve information about the status of the dialog box. The messages include:

CDM_GETFILEPATH	Retrieves the path and filename of the selected file.
CDM_GETFOLDERIDLIST	Retrieves the address of the item identifier list corresponding to the folder that the dialog box currently has open.
CDM_GETFOLDERPATH	Retrieves the path and name of the currently open folder or directory for the dialog box.
CDM_GETSPEC	Retrieves the filename (not including the path) of the currently selected file in the dialog box.
CDM_HIDECONTROL	Hides the given control.
CDM_SETCONTROLTEXT	Sets the text in the given control.
CDM_SETDEFEXT	Sets the default filename extension for the dialog box.


 Customizing Dialog Boxes

You can customize the Open or Save As dialog box by using the OFN_ENABLETEMPLATE or OFN_ENABLETEMPLATEHANDLE value and setting the hInstance and lpTemplateName members to values that specify a custom dialog box template. Customizing a dialog box lets you add controls to the default Open or Save As dialog box, giving users options that are specific to your application. When customizing a dialog box, you must use the OFN_EXPLORER value to make sure the controls in your custom dialog box are added to (rather than replace) the controls in the default dialog box. This section only describes customizing dialog boxes that you have created using OFN_EXPLORER.

If you use the OFN_ENABLETEMPLATE value, the lpTemplateName member must point to the name or resource identifier of a dialog template resource in the module identified by hInstance. If you use the OFN_ENABLETEMPLATEHANDLE value, hInstance must be the handle of a block of memory containing the the dialog template. In both cases, you must also enable a hook function by using the OFN_ENABLEHOOK value. This hook function serves as the dialog box procedure for the custom dialog box as well as monitors notification messages sent from the default dialog box.

You can create your custom 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 that the custom dialog box be created as a child of the default Open or Save As dialog box. The WS_CLIPSIBLINGS style ensures that the custom dialog box does not paint over any of the controls in the default dialog box. The DS_3DLOOK style makes sure that the controls in the custom dialog box are 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 such 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 function to process all messages intended for the custom dialog box and therefore sends the same window messages to the hook function as to any other dialog box procedure. For example, the hook function receives WM_COMMAND messages when the user clicks on button controls in the custom dialog box. The hook function is responsible for initializing these controls and retrieve values from the controls when the dialog box is closed. Note that when the hook function 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 function receives the WM_NOTIFY notification messages for user actions on these controls as described in the previous section.


 Print Dialog Box

Windows 95 Overview
For more information, see the Windows NT overview Print Dialog Box.

The Print dialog box lets the user select options for a particular print job, such as such as the printer to use, the range of pages to print, and the number of copies. You create and display a Print dialog box by initializing a PRINTDLG structure and passing the structure to the PrintDlg function. The Print dialog box typically looks like this:

If the user chooses options and clicks the OK button, PrintDlg returns TRUE and sets the hDevMode and hDevNames members to global memory handles for the DEVMODE and DEVNAMES structures that specify the user's selections. You can use the information in these structures to create a device or 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.

When the PrintDlg function returns, you can determine which options the user selected by checking the Flags member. The PD_ALLPAGES, PD_SELECTION, or PD_PAGENUMS value is set to indicate whether the user wants to print all pages, selected pages, or pages in a range of page numbers. If PD_PAGENUMS is set, the nFromPage and nToPage members specify the page range. The PD_COLLATE value indicates that the user wants the pages to be collated when printed. The PD_PRINTTOFILE value indicates that the user selected the Print To File option. You can also set these values in the Flags member before calling PrintDlg to initially set the corresponding option. Use the PD_NOPAGENUMS and PD_NOSELECTION values to disable the corresponding options.

By default, the Print dialog box initially displays information about the current default printer. You can direct it to display information for another installed printer by initializing a DEVMODE or DEVNAMES structure and assigning the global memory handle for the structure to the hDevMode or hDevNames member. The device name you specify in the dmDeviceName member of the DEVMODE structure or in the wDriverOffset member of the DEVNAMES structure must identify a printer device that is also listed in the [Devices] section of the WIN.INI file. Otherwise, PrintDlg returns an error.

When the PrintDlg function successfully returns, the application must render the number of copies in nCopies, printing them collated or not collated depending on whether the PD_COLLATE flag is set. If the application does not support multiple copies or simulated collation, it should specify PD_USEDEVMODECOPIESANDCOLLATE to allow these options only if the printer driver supports them.

You can direct PrintDlg to automatically create a device or information context for the printer by using the PD_RETURNDC or PD_RETURNIC value. The function returns the handle of the context in the hDC member. If you use the PD_RETURNDC value, you can use the device context to generate output for the printer. If the user also selects the Print To File option, however, you should retrieve the address of the filename at the offset indicated by the wOutputOffset member of the DEVNAMES structure. You should specify the address of the filename in the lpszOutput member of the DOCINFO structure. The print subsystem will query the user for the filename. If you do not want the user to select Print To File option, set the Flags member to PD_HIDEPRINTTOFILE to hide the option or PD_DISABLEPRINTTOFILE to disable it.

You can retrieve information about the default printer without displaying the Print dialog box by using the PD_RETURNDEFAULT value. In this case, PrintDlg returns immediately after setting the hDevMode and hDevNames members to handles for structures containing the information.

You can prevent PrintDlg from displaying warnings on errors by using the PD_NOWARNING value. Otherwise, the function displays message boxes on errors such as no printers installed.

You can enable a hook function by using the PD_ENABLEPRINTHOOK value and setting the lpfnPrintHook member to the address of your hook function. You can customize the Print dialog box by using the PD_ENABLEPRINTTEMPLATE or PD_ENABLEPRINTTEMPLATEHANDLE value and specifying a custom dialog box template. PrintDlg uses the custom dialog box to replace the default dialog box. If you use PD_ENABLEPRINTTEMPLATE, you set the hInstance and lpPrintTemplateName members to specify the name and module instance for a dialog box template. If PD_ENABLEPRINTTEMPLATEHANDLE, set hPrintTemplate to the handle of a dialog box template in memory.

Although you can also create and display a Printer Setup dialog box using the PrintDlg function and the PD_PRINTSETUP value, the Printer Setup dialog box has been superseded by the Page Setup dialog box and should not be used. The PD_ENABLESETUPHOOK, PD_ENABLESETUPTEMPLATE, and PD_ENABLESETUPTEMPLATEHANDLE values apply only to the Page Setup dialog box.


 Page Setup Dialog Box

Windows 95 Overview
For more information, see the Windows NT overview Page Setup Dialog Box.

The Page Setup dialog box lets the user to set the attributes of the printed page, such as 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), and the width of the page margins. You create and display a Page Setup dialog box by initializing a PAGESETUPDLG structure and passing the structure to the PageSetupDlg function. The Page Setup dialog box typically looks like this:

If the user chooses options and clicks the OK button, PageSetupDlg returns TRUE after setting various members in the PAGESETUPDLG structure to specify the user's selections. 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, the function returns FALSE. You can determine the cause of an error by using the CommDlgExtendedError function to retrieve the extended error value.

When PageSetupDlg returns, the ptPaperSize and rtMargin members contain the values selected by the user. The hDevMode and hDevNames members contain to global memory handles for the DEVMODE and DEVNAMES structures that contain additional page information as well as information about the printer.

By default, the Page Setup dialog box displays information about the current default printer. You can direct the dialog box to display information about a specific printer by setting the members of a DEVMODE or DEVNAMES structure and assigning the global memory handles of the 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. You can prevent the dialog box from displaying error messages by using the PSD_NOWARNING value. You can use the PSD_RETURNDEFAULT value to retrieve information about the default printer without displaying the Page Setup dialog box.

By default, measurements returned by the dialog box are in thousandths of inches if inches are the default measurement, or hundredths of millimeters if metric is the default measurement system. You can set the units of measurement for the margin widths in the dialog box by using the PSD_INHUNDREDTHSOFMILLIMETERS and PSD_INTHOUSANDTHSOFINCHES value. You can set the initial values for the margins by using the PSD_MARGINS value and the rtMargin member. The default initial values are one inch. You can set the minimum values that the user can enter for the margins by using the PSD_MINMARGINS values and the rtMinMargin member. The default minimum values are the minimum margins allowed by the printer.

You can prevent users from selecting given options by using the PSD_DISABLEMARGINS, PSD_DISABLEORIENTATION, PSD_DISABLEPAPER, and PSD_DISABLEPRINTER values to disable the corresponding controls.

You can enable a hook function for the dialog box by using the PSD_ENABLEPAGESETUPHOOK value and setting the lpfnPageSetupHook member to the address of your hook function. You can customize the Page Setup dialog box by using the PSD_ENABLEPAGESETUPTEMPLATE or PSD_ENABLEPAGESETUPTEMPLATEHANDLE value and specifying a custom dialog box template. PageSetupDlg uses the custom dialog box to replace the default dialog box. If you use PD_ENABLEPAGESETUPTEMPLATE, you set the hInstance and lpPageSetupTemplateName members to specify the name and module instance for a dialog box template. If PD_ENABLEPAGESETUPTEMPLATEHANDLE, set hPageSetupTemplate to the handle of a dialog box template in memory.

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. You can customize the appearance of the sample page by using the PSD_ENABLEPAGEPAINTHOOK value and setting the lpfnPagePaintHook member to the address of a hook function. The dialog box sends the following paint messages to the hook function whenever it needs a portion of the sample page redrawn:

WM_PSD_PAGESETUPDLG	Notifies the hook function to carry out initialization tasks.
WM_PSD_FULLPAGERECT	Specifies the bounding rectangle of the sample page.
WM_PSD_MINMARGINRECT	Specifies the minimum margin rectangle.
WM_PSD_MARGINRECT	Specifies the margin rectangle.
WM_PSD_GREEKTEXTRECT	Specifies the greek-text rectangle.
WM_PSD_ENVSTAMPRECT	Specifies the envelope-stamp rectangle (envelopes only).
WM_PSD_YAFULLPAGERECT	Specifies the bounding rectangle of the sample page.
The hook function receives these messages in the order in which they are listed. If the hook function processes a given message, it should draw the particular area within the sample page and return TRUE. Otherwise, it should return FALSE.

You can disable the display of the sample page by using the PSD_DISABLEPAGEPAINTING in the Flags member. Disabling the sample page prevents the WM_PSD_* message from being sent to your hook function. It also prevents the default dialog box procedure from painting the same page.


 Find and Replace Dialog Boxes

Windows 95 Overview
For more information, see the Windows NT overview Find and Replace Dialog Boxes.

The Find dialog box and the Replace dialog box let users enter information that you can use to search for and possibly replace text in a document. The Find dialog box lets users enter a string to search for and specify search options. The Replace dialog box lets users enter both a search and replace string and specify search-and-replace options. You create and display a Find dialog box by initializing a FINDREPLACE structure and passing the structure to the FindText function. The Find dialog box typically looks like this:

You create and display a Replace dialog box by initializing a FINDREPLACE structure and passing the structure to the ReplaceText function. The Replace dialog box typically looks like this:

Unlike other common dialog boxes, the Find and the Replace dialog boxes are modeless. This means the user can switch between the dialog box and the window that created that dialog box. This is useful for letting the user search for a string, switch to the application window to work on the string, and switch back to the dialog box to search for another string without repeating the command needed to open the dialog box.

If the FindText or ReplaceText function successfully creates the dialog box, it returns the handle of the dialog box. You can use this handle to move and communicate with the dialog box. If the function cannot create the dialog box, it returns NULL. You can determine the cause of an error by using the CommDlgExtendedError function to retrieve the extended error value.

When the user clicks the Find Next, Replace, or Replace All button in a dialog box, the dialog box procedure sends a registered message to the window procedure of the owner window. To receive and process these messages, you must set the hwndOwner member of the FINDREPLACE structure to the handle of the window to receive the messages and you must register the FINDMSGSTRING message string to retrieve the value of the registered message.

Each registered message contains the address of the FINDREPLACE structure. Before sending the message, the dialog box sets the members of this structure with the latest user selections, including the string to search for, the replacement string (if any) and the search-and-replace options. You must check the Flags member to determine the action to carry out and the options selected.

You can determine whether the search for a string, replace a string, or replace all occurrences of a string by checking the Flags member for the the FR_FINDNEXT, FR_REPLACE, and FR_REPLACEALL value, respectively. When the user eventually closes the dialog box, the dialog box sets the FR_DIALOGTERM value in the Flags member of the FINDREPLACE structure in the last registered message sent to the owner window. After the owner window processes this message, the handle of the dialog box is no longer valid.

You can determine the search options by checking for the FR_DOWN, FR_MATCHCASE, and FR_WHOLEWORD values. If a value is not present, the opposite action is implied. For example, if FR_DOWN is present, the search should be carried out from the current location to the end of the document; but if not present, the search should be to the beginning of the document. You can disable the search options by using the FR_NOUPDOWN, FR_NOMATCHCASE, and FR_NOWHOLEWORD values. You can remove the options from the dialog box by using the FR_HIDEUPDOWN, FR_HIDEMATCHCASE, and FR_HIDEWHOLEWORD values.

You can enable a hook function for a Find dialog box or Replace dialog box by using the FR_ENABLEHOOK value and setting the lpfnHook member to the address of the hook function. If the hook function returns FALSE in response to the WM_INITDIALOG message, the function is responsible for calling the ShowWindow and UpdateWindow functions to display the dialog box any painting operations are complete. You can customize the dialog box by using the FR_ENABLETEMPLATE or FR_ENABLETEMPLATEHANDLE value. The custom dialog box replaces the default dialog box.


 Using Common Dialog Boxes

Windows 95 Overview
For more information, see the Windows NT overview Using Common Dialog Boxes.

•	Choosing a color.

•	Choosing a font.

•	Opening a file.

•	Displaying the Print dialog box.

•	Setting up the printed page.

•	Finding text.


 Choosing a Color

You can let the user choose a color, such as for a new solid brush, by displaying the Color dialog box. To display the dialog box, you initialize the lStructSize, hwndOwner, lpCustColors and Flags members in a CHOOSECOLOR structure and call the ChooseColor function as in the following example:

CHOOSECOLOR cc;          // common dialog box structure
COLORREF acrCustClr[16]; // array of custom colors
HWND hwnd;               // owner window
HBRUSH hbrush;           // brush handle

// Initialize CHOOSECOLOR

cc.lStructSize = sizeof(CHOOSECOLOR);
cc.hwndOwner = hwnd;
cc.lpCustColors = (LPDWORD) acrCustClr;
cc.Flags = CC_FULLOPEN;

if (ChooseColor(&cc)==TRUE)
    hbrush = CreateSolidBrush(cc.rgbResult);

In this example, the CC_FULLOPEN value in the Flags member directs the dialog box to display the Add Custom Colors extension to the dialog box with which the user can create new custom colors. Custom colors are copied back into the array pointed to by lpCustColors.

The ChooseColor function returns TRUE if the user selected a color. The RGB value of the selected is in the rgbResult member of the structure.


 Choosing a Font

You can let the user choose the attributes of font, such as when creating a new logical font, by displaying the Font dialog box. To display the dialog box, you must initialize the members in a CHOOSEFONT structure and call the ChooseFont function as in the following example:

CHOOSEFONT cf;     // common dialog box structure
LOGFONT lf;        // logical font structure
HWND hwnd;         // owner window
HFONT hfont;       // new logical font handle

// Initialize CHOOSEFONT
cf.lStructSize = sizeof (CHOOSEFONT);
cf.hwndOwner = hwnd;
cf.lpLogFont = &lf;
cf.Flags = CF_SCREENFONTS | CF_EFFECTS;

if (ChooseFont(&cf)==TRUE)
    hfont = CreateFontIndirect(cf.lpLogFont);

In this example, the CF_SCREENFONTS defines the type of font to display information for and CF_EFFECTS causes the dialog box to display options to let the user select strikethrough, underlining, and color for the font. The function copies the font attributes to the lf variable, a LOGFONT structure.


 Opening a File

You can let the user select the name of a file to open by displaying an Open dialog box. You initialize the lStructSize, hwndOwner, lpstrFile, and nMaxFile members of an OPENFILENAME structure and call the GetOpenFileName function as in the following example:

OPENFILENAME ofn;       // common dialog box structure
char szFile[260];       // buffer for filename
HWND hwnd;              // owner window
HANDLE hf;              // file handle

// Initialize 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_EXPLORER | 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);

In this example, the lpstrFilter member receives the address of a filter that contains two patterns that the user can choose to view all files or just text files. The nFilterIndex member specifies that the first pattern is used when the dialog box is created. The OFN_EXPLORER value ensures that the Open dialog box displays a user-interface that is similar to the Windows Explorer. The OFN_PATHMUSTEXIST and OFN_FILEMUSTEXIST values direct the function to verify the the path and filename that the user enters exists before returning.


 Displaying the Print Dialog Box

You can let the user choose options for printing a document by displaying a Print dialog box. To display the dialog box for the default printer, you initialize a PRINTDLG structure and call the PrintDlg function as in the following example:

PRINTDLG pd;
HWND hwnd;

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;

if (PrintDlg(&pd)==TRUE) {

    // GDI calls to render output

    // Delete DC when done
    DeleteDC(pd.hDC);
}

In this example, the PD_RETURNDC value directs PrintDlg to return a device context handle for the selected printer. This handle is used to render output on the printer.


 Setting Up the Printed Page

You can let the user select the attributes of the printed page, such as the paper type, paper source, page orientation, and page margins by displaying a Page Setup dialog box. To display the dialog box, you initialize a PAGESETUPDLG structure and call the PageSetupDlg function as in the following example:

PAGESETUPDLG psd;    // common dialog box structure
HWND hwnd;           // owner window

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.rtMargin.top = 1000;
psd.rtMargin.left = 1250;
psd.rtMargin.right = 1250;
psd.rtMargin.bottom = 1000;

if (PageSetupDlg(&psd)==TRUE) {
    // check paper size and margin values here
}

In this example, the PSD_MARGINS value directs the function to set the initial margin values as specified in the rtMargin member. In this case, the initial and returned margin values are expressed in thousandths of an inch. The initial paper size is the paper size specified in the device mode identified by the hDevMode member of the PAGESETUPDLG structure, or by the default printer's device mode if no printer was specified.

One of the ways an application can customize the Page Setup dialog box is to use a hook function to paint the sample page of the dialog box. You set the hook function by using the PSD_ENABLEPAGEPAINTHOOK value when creating the dialog box. The following example shows a sample hook function 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

You can let the user enter a string and search options for a search by displaying a Find dialog box and monitoring messages sent by the dialog box. To display and manage the Find dialog box, you need to carry out three steps: register the FINDMSGSTRING message string, call the FindText function to create and display the dialog box, and check for the registered messages in the window procedure of the window that owns the dialog box.

To register the message string, you make the following call when initializing your application:

UINT uFindReplaceMsg;  // message id for FINDMSGSTRING

uFindReplaceMsg = RegisterWindowMessage();

To make sure the Find dialog box operates properly when eventually displayed, you must include a call to the IsDialogMessage function in your main message loop.

To display the Find dialog box, you initialize the FINDREPLACE structure and call the FindText function as in the following example:

FINDREPLACE fr;       // common dialog box structure
HWND hwnd;            // owner window
CHAR szFindWhat[80];  // buffer receiving string
HWND hdlg = NULL;     // handle of Find dialog box

fr.lStructSize = sizeof(FINDREPLACE);
fr.hwndOwner = hwnd;
fr.lpstrFindWhat = szFindWhat;
fr.wFindWhatLen = 80;
fr.Flags = 0;

hdlg = FindText(&fr);

Note that the FINDREPLACE structure and the buffer for the search string should be a global or static variable. You must set the hwndOwner member to specify the window that receives the registered messages. Once the dialog box is created, you can move or manipulate it by using the returned handle.

To monitor messages sent from the dialog box, you check for the registered message and process the values passed in the FINDREPLACE structure as in the following example:

LPFINDREPLACE lpfr;

if (msg == uFindReplaceMsg) {
    lpfr = (LPFINDREPLACE)lParam;
    if (lpfr->Flags & FR_FINDNEXT) {
        // search for string specified by lpfr->lpstrFindWhat
    } else if (lpfr->FR_DIALOGTERM) {
        // user has closed the dialog box
        hdlg = NULL;
    }
}

To fully process the message, you must check the Flags member for search options, indicated by values such as FR_DOWN, FR_WHOLEWORD, and FR_MATCHCASE.


 Common Dialog Box Reference

The following functions, structures, and messages are associated with common dialog boxes in Windows 95.


 Common Dialog Box Functions

Following are the functions used with common dialog boxes.

ChooseColor
ChooseFont
CommDlgExtendedError
FindText
GetFileTitle
GetOpenFileName
GetSaveFileName
PageSetupDlg
PrintDlg
ReplaceText


 Common Dialog Box Structures

Following are the structures used with common dialog boxes.

OFNOTIFY
PAGESETUPDLG


 Common Dialog Box Messages

Following are the messages used with common dialog boxes.

CDM_GETFILEPATH
CDM_GETFOLDERIDLIST
CDM_GETFOLDERPATH
CDM_GETSPEC
CDM_HIDECONTROL
CDM_SETCONTROLTEXT
CDM_SETDEFEXT
CDN_FILEOK
CDN_FOLDERCHANGE
CDN_HELP
CDN_INITDONE
CDN_SELCHANGE
CDN_SHAREVIOLATION
CDN_TYPECHANGE
COLOROKSTRING
FILEOKSTRING
FINDMSGSTRING
LBSELCHSTRING
SETRGBSTRING
SHAREVISTRING
WM_CHOOSEFONT_SETFLAGS
WM_CHOOSEFONT_SETLOGFONT
WM_PSD_ENVSTAMPRECT
WM_PSD_FULLPAGERECT
WM_PSD_GREEKTEXTRECT
WM_PSD_MARGINRECT
WM_PSD_MINMARGINRECT
WM_PSD_PAGESETUPDLG
WM_PSD_YAFULLPAGERECT


 Common Dialog Box Library (Windows NT)

The following Windows NT overview discusses the Common Dialog Box Library. Various common dialog boxes are described, and examples are included to help you use common dialog boxes in your Win32-based applications.


 About Common Dialog Boxes

Windows NT Overview
For more information, see the Windows 95 overview About Common Dialog Boxes.

Common dialog boxes make it easier to develop applications based on the Microsoft® Win32® application programming interface (API). A common dialog box is a dialog box that an application displays by calling a single function rather than by supplying a dialog box procedure and a resource file containing a dialog box template. The dynamic-link library COMDLG32.DLL provides a default procedure and a default template for each type of common dialog box. Each default dialog box procedure processes messages and notifications for a common dialog box and its controls. The default dialog box template defines the appearance of a common dialog box and its controls.

In addition to simplifying the development of Win32-based applications, common dialog boxes are helpful to users because they provide a standard set of controls for performing certain operations. Once Windows developers begin using common dialog boxes extensively in their applications, users will find that they can easily perform the same operations in all applications after mastering one.

This chapter describes the various common dialog boxes and includes examples to help you use common dialog boxes in your Win32-based applications.

Following are the types of common dialog boxes in the order in which they are presented in this chapter.

Name	Description
Color	Displays available colors as well as controls that allow the user to define custom colors.
Font	Displays lists of fonts and point sizes that correspond to available fonts. After the user selects a font, the dialog box displays sample text rendered with that font.
Open	Displays a list of filenames matching any specified extensions, directories, and drives. By selecting one of the listed filenames, the user indicates the file an application should open.
Save As	Displays a list of filenames matching any specified extensions, directories, and drives. By selecting one of the listed filenames, the user indicates the file an application should save.
Print	Displays information about the installed printer and its configuration. By altering and selecting controls in this dialog box, the user specifies how output should be printed and starts the printing process.
Page Setup	Displays the current page configuration and provides options for setting the paper orientation, size, source, and margins (when the printer driver supports these options).
Print Setup	This common dialog box has been superseded by the Page Setup dialog box. Win-32 applications should not use the Print Setup dialog box.
Find	Displays an edit control in which the user can type a string for an application to search. The user can specify which direction to search and can indicate whether the application should match the case of the specified string, and whether the string to match is an entire word.
Replace	Displays two edit controls in which the user can type strings. The first string identifies a word or value that the application should replace, and the second string identifies the replacement word or value.


 Color Dialog Box

Windows NT Overview
For more information, see the Windows 95 overview Color Dialog Box.

The Color dialog box contains controls that enable a user to select and create colors.

Following is a Color dialog box.

The Basic Colors control displays up to 48 colors. 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. By using the Basic Colors control, the user can select a displayed color.

To display the Custom Colors control, the user clicks the Define Custom Colors button. The Custom Colors control displays custom colors. The user can select one of the 16 rectangles in this control and then create a new color by using one of the following methods:

•	Specifying red, green, and blue (RGB) values by using the Red, Green, and Blue edit controls, and then choosing the Add to Custom Colors button to display the new color in the selected rectangle.

•	Moving the cursor in the color spectrum control (the box at the upper right of the dialog box) to select hue and saturation values, moving the cursor in the luminosity control (the rectangle to the right of the spectrum control), and then choosing the Add to Custom Colors button to display the new color in the selected rectangle.

•	Specifying hue, saturation, and luminosity (HSL) values by using the Hue, Sat, and Lum edit controls, and then choosing the Add to Custom Colors button to display the new color in the selected rectangle.

The Color|Solid control displays the dithered and solid colors that correspond to the user's selection. (A dithered color is a color created by combining one or more pure or solid colors.) The Flags member of the CHOOSECOLOR structure contains a flag that, when specified, displays a Help button.

An application can display the Color dialog box in one of two ways: fully open or partially open. When the Color dialog box is displayed partially open, the user cannot change the custom colors.


 Color Models Used by the Color Dialog Box

The Color dialog box uses two models for specifying colors: the RGB model and the HSL model. Regardless of the model used, internal storage is accomplished by use of the RGB model.

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 are in the range 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
Windows stores internal colors as 32-bit RGB values. The high-order byte of the high-order word is reserved; the low-order byte of the high-order word specifies the intensity of the blue component; the high-order byte of the low-order word specifies the intensity of the green component; and the low-order byte of the low-order word specifies the intensity of the red component.

HSL Color Model

The Color dialog box provides controls for specifying HSL values. The following illustration shows the color spectrum control and the luminosity control that appear in the Color dialog box and 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

Windows NT Overview
For more information, see the Windows 95 overview Font Dialog Box.

The Font dialog box contains controls that allow a user to choose a font, a font style (such as bold, italic, or regular), a point size, an effect (such as underline or strikeout), or a text color. Following is a Font dialog box.


 Open and Save As Dialog Boxes

Windows NT Overview
For more information, see the Windows 95 overview Open and Save As Dialog Boxes.

The Open dialog box and the Save As dialog box are similar in appearance. Each contains controls that enable a user to specify the location (drive and directory) and the name of a file or a set of files. In the case of the Open dialog box, the user selects the file or files to be opened. In the case of the Save As dialog box, however, the user selects the file or files to be saved. Following is an Open dialog box.


 Print Dialog Box

Windows NT Overview
For more information, see the Windows 95 overview Print Dialog Box.

The Print dialog box contains controls that allow a user to configure a printer for a particular print job. The user can make selections, such as print quality, print range, and number of copies (if the printer supports multiple copies).

The Print dialog box differs from other common dialog boxes in that part of its dialog box procedure resides in COMDLG32.DLL and part in a printer driver. A printer driver is a program that configures a printer, converts graphics device interface (GDI) commands to low-level printer commands, and stores commands for a particular print job in a printer's queue.

A printer driver exports a function called ExtDeviceMode that displays a dialog box and its controls. Applications written for previous versions of Windows called the LoadLibrary function to load a device driver, and the GetProcAddress function to obtain the address of the ExtDeviceMode function. Win32-based applications no longer need to call LoadLibrary and GetProcAddress. Instead, an application calls a single function, PrintDlg, to display the Print dialog box and begin a print job. The code for PrintDlg resides in COMDLG32.DLL. The dialog box that appears when an application calls PrintDlg differs slightly from the dialog box that appears when the application calls directly into the device driver. The functionality is very similar in spite of the different appearance.


 Page Setup Dialog Box

Windows NT Overview
For more information, see the Windows 95 overview Page Setup Dialog Box.

The Page Setup dialog box allows the user to set the attibutes of the printed page, including 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), and the width of the page margins. The attributes presented in the dialog box vary depending on the capabilities of the printer.

The 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. The system uses a dotted-line rectangle to represent the current margins, and fills the rectangle with greeking characters to show how text will look on a printed page.

The system uses a multiple-step process to draw the sample page. You can customize the appearance of the sample page by specifying a hook function that the system calls at each step in the drawing process. When the system calls the hook procedure, it sends a message that contains information that the hook procedure uses to draw in a particular area within the sample page.


 Find and Replace Dialog Boxes

Windows NT Overview
For more information, see the Windows 95 overview Find and Replace Dialog Boxes.

The Find dialog box and the Replace dialog box are similar in appearance. You can use the Find dialog box to add string-search capabilities to an application and the Replace dialog box to add both string-search and string-substitution capabilities.

The Find and the Replace dialog boxes differ from other common dialog boxes in that they are modeless. This means the user can switch between the dialog box and the window that created that dialog box.


 Using Common Dialog Boxes

Windows NT Overview
For more information, see the Windows 95 overview Using Common Dialog Boxes.

This section explains how to perform the following tasks:

•	Using the Color dialog box to display basic colors.

•	Using the Color dialog box to display custom colors.

•	Displaying the Font dialog box in an application.

•	Displaying the Open dialog box in an application.

•	Displaying the Save As dialog box in an application.

•	Monitoring List Box Controls in an Open or Save As dialog box.

•	Monitoring Filenames in an Open or Save As dialog box.

•	Displaying Explorer-Style Open and Save As Dialog Boxes.

•	Displaying a Print dialog box for the default printer.

•	Displaying the Find dialog box.

•	Displaying the Replace dialog box.

•	Processing Messages for a Find or Replace dialog box.

•	Customizing common dialog boxes.


 Using the Color Dialog Box to Display Basic Colors

You can have your application display the Color dialog box so that a user can select one color from a list of basic screen colors. This section describes how you can provide code and structures in your application to make this possible.


 Initializing the CHOOSECOLOR Structure to Display Basic Colors

Before displaying a Color dialog box, an application must initialize a CHOOSECOLOR structure. This structure should be global or be declared as a static variable. The members of this structure contain information about the following items:

•	The structure size

•	The window that owns the dialog box

•	Any customization of the common dialog box by the application

•	The hook function and custom dialog box template to use for a customized version of the Color dialog box

•	The RGB values for the selected basic color

If your application does not customize the dialog box and you want the user to be able to select a single color from the basic colors, initialize the CHOOSECOLOR structure in the following manner.

/* Color variables */

CHOOSECOLOR cc;     /* common dialog box structure */

COLORREF acrCustClr[16] = {

    RGB(255, 255, 255), RGB(239, 239, 239),

    RGB(223, 223, 223), RGB(207, 207, 207),

    RGB(191, 191, 191), RGB(175, 175, 175),

    RGB(159, 159, 159), RGB(143, 143, 143),

    RGB(127, 127, 127), RGB(111, 111, 111),

    RGB(95, 95, 95), RGB(79, 79, 79),

    RGB(63, 63, 63), RGB(47, 47, 47),

    RGB(31, 31, 31), RGB(15, 15, 15)

    }; /* array of gray colors */

/* Initialize the necessary members. */

cc.lStructSize = sizeof(CHOOSECOLOR);

cc.hwndOwner = hwnd;

cc.lpCustColors = (LPDWORD) acrCustClr;

cc.Flags = CC_PREVENTFULLOPEN;

/* Call the ChooseColor function. */

if (ChooseColor(&cc)){

.

.   /* Use cc.lpCustColors to select the requested color. */

.

}

In this example, the array pointed to by lpCustColors contains 16 doubleword RGB values that specify the color white, and the CC_PREVENTFULLOPEN flag is specified in the Flags member to disable the Define Custom Colors button and prevent the user from selecting a custom color.


 Calling the ChooseColor Function to Display Basic Colors

After you initialize the structure, call the ChooseColor function. If the function succeeds and the user chooses the OK button to close the dialog box, the rgbResult member of the CHOOSECOLOR structure contains the RGB values for the basic color the user selected.


 Using the Color Dialog Box to Display Custom Colors

You can have your application display the Color dialog box so that the user can create and select a custom color. This section describes how you can provide code and structures in your application to make this possible.


 Initializing the CHOOSECOLOR Structure to Display Custom Colors

Before displaying a Color dialog box, an application must initialize a CHOOSECOLOR structure. This structure should be global or declared as a static variable. The members of this structure contain information about the following items:

•	The structure size

•	The window that owns the dialog box

•	Any customization of the common dialog box by the application

•	The hook function and custom dialog box template to use for a customized version of the Color dialog box

•	The RGB values for the custom color control

If your application does not customize the dialog box and you want the user to be able to create and select custom colors, initialize the CHOOSECOLOR structure in the following manner.

/* Color variables */

CHOOSECOLOR cc;     /* common dialog box structure */

COLORREF acrCustClr[16] = {

    RGB(255, 255, 255), RGB(239, 239, 239),

    RGB(223, 223, 223), RGB(207, 207, 207),

    RGB(191, 191, 191), RGB(175, 175, 175),

    RGB(159, 159, 159), RGB(143, 143, 143),

    RGB(127, 127, 127), RGB(111, 111, 111),

    RGB(95, 95, 95), RGB(79, 79, 79),

    RGB(63, 63, 63), RGB(47, 47, 47),

    RGB(31, 31, 31), RGB(15, 15, 15)

    }; /* array of gray colors */

/* Initialize the necessary members. */

cc.lStructSize = sizeof(CHOOSECOLOR);

cc.hwndOwner = hwnd;

cc.lpCustColors = (LPDWORD) acrCustClr;

cc.Flags = CC_FULLOPEN;

In the previous example, the array pointed to by the lpCustColors member contains sixteen 32-bit RGB values that specify 16 scales of gray, and the CC_FULLOPEN flag is specified in the Flags member to display the complete Color dialog box.


 Calling the ChooseColor Function to Display Custom Colors

After you initialize the structure, you should call the ChooseColor function. If the function succeeds and the user chooses the OK button to close the dialog box, the lpCustColors member points to an array that contains the RGB values for the custom colors requested by the user.

You can give your application more control over custom colors by creating a new message identifier for the string defined by COLOROKSTRING . The application creates the new message identifier by calling RegisterWindowMessage and passing this value as the single parameter. After calling RegisterWindowMessage, the application receives a message immediately before the dialog box closes. The lParam parameter of this message contains a pointer to the CHOOSECOLOR structure. The application can use the lpCustColors member of this structure to check the current color. If the application returns a nonzero value when it processes this message, the dialog box does not close.

Similarly, you can have your application create a new message identifier for the string defined by the SETRGBSTRING value. The application's hook function can use the message identifier returned by calling RegisterWindowMessage with the SETRGBSTRING value to set a color in the dialog box. For example, the following line sets the color selection to blue.

SendMessage(hwndDlg, wSetRGBMsg, 0, (LPARAM) RGB(0, 0, 255));

In this example, the wSetRGBMsg argument is the message identifier returned by RegisterWindowMessage. The lParam parameter of the SendMessage function is set to the RGB values of the desired color. The wParam parameter is not used.

You can have your application specify any valid RGB values in the call to SendMessage. If the RGB values match one of the basic colors, the operating system selects the basic color and updates the spectrum and luminosity controls. If the RGB values do not match one of the basic colors, the system updates the spectrum and luminosity controls, but the basic color selection remains unchanged.

Note that if the Color dialog box is not fully open and the application sends RGB values that do not match one of the basic colors, the operating system does not update the dialog box. Updates are unnecessary because the spectrum and luminosity controls are not visible when the dialog box is only partially open.

For more information about processing registered window messages, see Displaying the Find Dialog Box.


 Displaying the Font Dialog Box in An Application

The Font dialog box appears after you initialize the members in a CHOOSEFONT structure and call the ChooseFont function. This structure should be global or be declared as a static variable. The members of the CHOOSEFONT structure contain information about the following items:

•	Which attributes of the font initially appear in the dialog box.

•	Which attributes of the font the user has selected.

•	Which point size of the font the user has selected.

•	Whether the list of fonts corresponds to a printer, a screen, or both.

•	Whether the available fonts listed are TrueType only.

•	Whether the Effects box should appear in the dialog box.

•	Whether dialog box messages should be processed by an application-defined hook function.

•	Whether the point sizes of the selectable fonts should be limited to a specified range.

•	Whether the dialog box displays only what-you-see-is-what-you-get (WYSIWYG) fonts. (These fonts are resident on both the screen and the printer.)

•	Which color ChooseFont uses to render text in the Sample box the first time the application displays the dialog box.

•	Which color the user selected for text output.

To display the Font dialog box, include the following steps in your application:

1.	If the application requires printer fonts, obtain a device context (DC) handle for the printer and use this handle in the hDC member of the CHOOSEFONT structure. (If the Font dialog box displays only screen fonts, this member should be NULL.)

2.	Use appropriate flags in the Flags member of the CHOOSEFONT structure. They must include CF_SCREENFONTS, CF_PRINTERFONTS, or CF_BOTH.

3.	Set the rgbColors member of the CHOOSEFONT structure if the default color (black) is not appropriate.

4.	Set the nFontType member of the CHOOSEFONT structure by using the appropriate constant.

5.	Set the nSizeMin and nSizeMax members of the CHOOSEFONT structure if the CF_LIMITSIZE flag is specified in the Flags member.

6.	Call the ChooseFont function.

The following example initializes the CHOOSEFONT structure, calls ChooseFont, and uses the requested font to draw text on the display.

/* Font variables */

CHOOSEFONT cf;     /* common dialog box structure  */

LOGFONT lf;        /* logical font structure       */

HDC hdc;           /* display DC handle            */

HFONT hfont;       /* new logical font handle      */

HFONT hfontOld;    /* original logical font handle */

COLORREF crOld;    /* original text color          */

/* Initialize the necessary members. */

cf.lStructSize = sizeof (CHOOSEFONT);

cf.hwndOwner = hwnd;

cf.lpLogFont = &lf;

cf.Flags = CF_SCREENFONTS | CF_EFFECTS;

cf.rgbColors = RGB(0, 255, 255);

cf.nFontType = SCREEN_FONTTYPE;

/*

 * Display the dialog box, allow the user to

 * choose a font, and render the text in the

 * window with that selection.

 */

if (ChooseFont(&cf)){

    hdc = GetDC(hwnd);

    hfont = CreateFontIndirect(cf.lpLogFont);

    hfontOld = SelectObject(hdc, hfont);

    crOld = SetTextColor(hdc, cf.rgbColors);

    TextOut(hdc, 50, 150,

        "AaBbCcDdEeFfGgHh", 16);

    SetTextColor(hdc, crOld);

    SelectObject(hdc, hfontOld);

    DeleteObject(hfont);

    ReleaseDC(hwnd, hdc);

    }

An application can also use the WM_CHOOSEFONT_GETLOGFONT message to retrieve the current LOGFONT structure for the Font dialog box before the user closes the dialog box.


 Displaying the Open Dialog Box in An Application

The Open dialog box appears after you initialize the members of an OPENFILENAME structure and call the GetOpenFileName function.

Before you call GetOpenFileName, structure members contain certain data, such as the name of the directory and the filter that appears in the dialog box. (A filter is a filename extension. The common dialog box code uses the extension to filter appropriate filenames from a directory.) After the call, structure members contain other data, such as the name of the selected file and the number of characters in that filename.

To display an Open dialog box, include the following steps in your application:

1.	Store the valid filters in a character array.

2.	Set the lpstrFilter member to point to this array.

3.	Set the nFilterIndex member to the value of the index that identifies the default filter.

4.	Set the lpstrFile member to point to an array that contains the initial filename and receives the selected filename.

5.	Set the nMaxFile member to the value that specifies the length of the filename array.

6.	Set the lpstrFileTitle member to point to a buffer that receives the title of the selected file.

7.	Set the nMaxFileTitle member to specify the length of the buffer.

8.	Set the lpstrInitialDir member to point to a string that specifies the initial directory. (If this member does not point to a valid string, it must be set to zero or point to a string set to NULL.)

9.	Set the lpstrTitle member to point to a string specifying the name that appears in the title bar of the dialog box. (If this pointer is NULL, the title is Open by default.)

10.	Initialize the lpstrDefExt member to point to the default extension. (This extension can be 0, 1, 2, or 3 characters long.)

11.	Call the GetOpenFileName function.

The following example initializes an OPENFILENAME structure, calls GetOpenFileName, and opens the file by using the lpstrFile member of the structure. The OPENFILENAME structure should be global or be declared as a static variable.

OPENFILENAME ofn;       /* common dialog box structure   */

char szDirName[MAX_PATH];    /* directory string              */

char szFile[260];       /* filename string               */

char szFileTitle[260];  /* file title string             */

char szFilter[260];     /* filter string                 */

char chReplace;         /* string separator for szFilter */

int i, cbString;        /* integer count variables       */

HANDLE hf;              /* file handle                   */

.

.

.

/*

 * Obtain the system directory name and

 * store it in szDirName.

 */

GetSystemDirectory(szDirName, sizeof(szDirName));

/* Place the terminating null character in the szFile. */

szFile[0] = '\0';

/* Load the filter string from the .RC file. */

cbString = LoadString(hinst, IDS_FILTERSTRING,

    szFilter, sizeof(szFilter));

/*

 * Add a terminating null character to the filter string.

 */

chReplace = szFilter[cbString - 1];

for (i = 0; szFilter[i] != '\0'; i++){

    if (szFilter[i] == chReplace)

        szFilter[i] = '\0';

}

/* Set the members of the OPENFILENAME structure. */

ofn.lStructSize = sizeof(OPENFILENAME);

ofn.hwndOwner = hwnd;

ofn.lpstrFilter = szFilter;

ofn.nFilterIndex = 1;

ofn.lpstrFile = szFile;

ofn.nMaxFile = sizeof(szFile);

ofn.lpstrFileTitle = szFileTitle;

ofn.nMaxFileTitle = sizeof(szFileTitle);

ofn.lpstrInitialDir = szDirName;

ofn.Flags = OFN_SHOWHELP | OFN_PATHMUSTEXIST |

    OFN_FILEMUSTEXIST;

/* Display the Open dialog box. */

if (GetOpenFileName(&ofn)) {

    /* Open the file. */

    hf = CreateFile(ofn.lpstrFile, GENERIC_READ,

        0, (LPSECURITY_ATTRIBUTES) NULL,

        OPEN_EXISTING,

        FILE_ATTRIBUTE_NORMAL,

        (HANDLE) NULL);

    .

    .   /* Perform the necessary file operations. */

    .

    /* Close the file. */

    CloseHandle(hf);

} /* end if */

The string referred to by the IDS_FILTERSTRING value in the preceding example is defined as follows in the resource-definition file.

STRINGTABLE

BEGIN

    IDS_FILTERSTRING "Bitmap File(*.BMP)|*.bmp|"

END

The vertical bars in this string are used as wildcards. After the LoadString function is used to retrieve the string, the wildcards are replaced with NULL. The wildcard can be any unique character and must be included as the last character in the string. Initializing strings in this manner guarantees that the parts of the string are contiguous in memory and that the string is terminated with two null characters.

An application that can open files over a network can create a new message identifier for the string defined by the SHAREVISTRING value. The application creates the new message identifier by calling RegisterWindowMessage and passing this value as the single parameter. After calling RegisterWindowMessage, the application is notified whenever a sharing violation occurs during a call to the OpenFile function. For more information about processing registered window messages, see Displaying the Find Dialog Box.


 Displaying the Save As Dialog Box in An Application

The Save As dialog box appears after you initialize the members of an OPENFILENAME structure and call the GetSaveFileName function.

Before you call GetSaveFileName, structure members contain certain data, such as the name of the initial directory and a filter string. After the call, structure members contain other data, such as the name of the file to be saved and the number of characters in that filename.

The following example initializes an OPENFILENAME structure, calls GetSaveFileName, and saves the file. The OPENFILENAME structure should be global or be declared as a static variable.

OPENFILENAME ofn;       /* common dialog box structure   */

char szDirName[MAX_PATH];    /* directory string              */

char szFile[260];       /* filename string               */

char szFileTitle[260];  /* file title string             */

char szFilter[260];     /* filter string                 */

char chReplace;         /* string separator for szFilter */

int i, cbString;        /* integer count variables       */

HANDLE hf;              /* file handle                   */

/*

 * Obtain the system directory name and

 * store it in szDirName.

 */

GetSystemDirectory(szDirName, sizeof(szDirName));

/* Place the terminating null character in szFile. */

szFile[0] = '\0';

/* Load the filter string from the .RC file. */

cbString = LoadString(hinst, IDS_FILTERSTRING,

    szFilter, sizeof(szFilter));

/*

 * Add a terminating null character to the filter string.

 */

chReplace = szFilter[cbString - 1];

for (i = 0; szFilter[i] != '\0'; i++){

    if (szFilter[i] == chReplace)

        szFilter[i] = '\0';

}

/* Set the members of the OPENFILENAME structure. */

ofn.lStructSize = sizeof(OPENFILENAME);

ofn.hwndOwner = hwnd;

ofn.lpstrFilter = szFilter;

ofn.nFilterIndex = 1;

ofn.lpstrFile = szFile;

ofn.nMaxFile = sizeof(szFile);

ofn.lpstrFileTitle = szFileTitle;

ofn.nMaxFileTitle = sizeof(szFileTitle);

ofn.lpstrInitialDir = szDirName;

ofn.Flags = OFN_SHOWHELP | OFN_OVERWRITEPROMPT;

/* Display the Save As dialog box. */

if (GetSaveFileName(&ofn)) {

    .

    .   /* Perform the necessary file operations. */

    .

    /* Close the file. */

    CloseHandle(hf);

} /* end if */

The string referred to by the IDS_FILTERSTRING value in the preceding example is defined in the resource-definition file. It is used in exactly the same way as the IDS_FILTERSTRING value discussed in Displaying the Open Dialog Box in An Application.


 Monitoring List Box Controls in an Open or Save As Dialog Box

An application can monitor list box selections to process and display data in custom controls. For example, an application can use a custom control to display the total length, in bytes, of all files selected in the File Name box. One method that the application can use to obtain this value is to recompute the total count of bytes each time the user selects a file or cancels the selection of a file. A faster method is for the application to use the LBSELCHSTRING message to identify a new selection and to add the corresponding file length to the value that appears in the custom control. (Note that, in this example, the custom control is a standard Windows control that is identified in a resource file template for one of the common dialog boxes.)

An application uses RegisterWindowMessage to register the selection change message. After registering the message, the application uses this function's return value to identify messages from the dialog box. The message is processed in the application-defined hook function for the common dialog box. The wParam parameter of each message identifies the list box in which the selection occurred. The low-order word of the lParam parameter identifies the list box item. The high-order word of the lParam parameter is one of the following values.

Value	Meaning
CD_LBSELCHANGE	The item identified by the low-order word of lParam was the item in a single-selection list box.
CD_LBSELSUB	The item identified by the low-order word of lParam is no longer selected in a multiple-selection list box.
CD_LBSELADD	The item identified by the low-order word of lParam was selected from a multiple-selection list box.
CD_LBSELNOITEMS	No items exist in a multiple-selection list box.
For an example that registers a common dialog box message, see Displaying the Find Dialog Box.


 Monitoring Filenames in an Open or Save As Dialog Box

An application can alter the normal processing of an Open or Save As dialog box by monitoring the filename the user types and by performing other unique operations. For example, one application can prevent the user from closing the dialog box if the selected filename is prohibited. Another application, however, can enable the user to select multiple filenames.

To monitor filenames, register the FILEOKSTRING message. Do this by calling the RegisterWindowMessage function and passing the message name as its single parameter. After the message has been registered, the dialog box procedure in COMDLG32.DLL uses it to signal that the user has selected a filename and chosen the OK button and that the dialog box has checked the filename and is ready to return. The dialog box procedure signals these actions by sending the message to the application's hook function. After receiving the message, the hook function should return a value to the dialog box procedure that called it. If the hook function did not process the message, it should return 0; if the hook function processed the message and the dialog box should close, the hook function should return 0; and if the hook function processed the message but the dialog box should not close, the hook function should return 1. All other return values are reserved.


 Displaying Explorer-Style Open and Save As Dialog Boxes

If you specify OFN_EXPLORER in the Flags member of the OPENFILENAME structure used to create the Open or Save As common dialog box, the system creates a dialog box that incorporates many of the user-interface features of the Windows Explorer. In addition, specifying OFN_EXPLORER allows you to customize the Open and Save As dialog boxes by adding a dialog template that includes the items that you want to add to the dialog box.

The OFN_EXPLORER value affects the way that the system interprets the hInstance, lpfnHook, and lpTemplateName members of the OPENFILENAME structure. If the Flags member includes OFN_ENABLETEMPLATE, the lpTemplateName member must point to the name of a dialog template resource in the module identified by hInstance. The dialog template must have the WS_CHILD style, and should also have the DS_3DLOOK style to ensure that the child dialog box incorporates the same user interface style as the common dialog box. The system uses the dialog template to create a child dialog box and positions it at the upper left corner of the standard file dialog box, growing the child dialog box if necessary to fit all controls for both dialog boxes.

If the child dialog box has a control with a identifier equal to stc32, the system attempts to place all of the standard dialog box controls within the stc32 control. If the stc32 control is too small to fit the standard controls, the system moves other controls in the child dialog box to the right of or below the stc32 control to make room — you don't need to know the exact dimensions of the common dialog box. If there is no stc32 control, the system positions all controls defined by the child dialog template below the standard controls. The system resizes the stc32 control to the size of the standard dialog box.

If the Flags member includes OFN_ENABLETEMPLATEHANDLE, the hInstance member is the memory handle of the dialog template. The system uses this template exactly as it uses the dialog template specified in lpTemplateName when Flags includes OFN_ENABLETEMPLATE, as described in the previous paragraphs.

The system communicates with the child dialog box by sending messages to the dialog procedure of the child dialog box. To specify the dialog box procedure, you must include OFN_ENABLEHOOK in the Flags member of the OPENFILENAME structure, and specify the address the procedure in the lpfnHook member.

When the system creates the dialog box, it sends WM_INITDIALOG message to the child dialog procedure specified in the lpfnHook member. The child dialog procedure receives the message before the system has moved any controls. The lParam parameter specifies the address of the OPENFILENAME structure that was passed to the GetOpenFileName or GetSaveFileName function.

The system also sends notification messages to the child dialog procedure to notify it of user and system activity affecting the child dialog box. The notification messages, sent using the WM_NOTIFY message, consist of the following:

Notification message	Description
CDN_FILEOK	The user click the Open or Save button; the common dialog box is about to close.
CDN_FOLDERCHANGE	A new folder has been opened in the Open or Save As dialog box.
CDN_HELP	The user clicked the Help button.
CDN_INITDONE	The system has finished initializating 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.
CDN_SELCHANGE	The user has 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 "Files of type" combo box.
If the child dialog procedure needs to return a value to the common dialog box, the procedure must use the SetWindowLong function to set the DWL_MSGRESULT value.

An application can send messages to an explorer-style Open or Save As dialog box to retrieve information about the status of the dialog box. The messages include:

Message	Description
CDM_GETFILEPATH	Retrieves the path and filename of the selected file.
CDM_GETFOLDERIDLIST	Retrieves the address of the item identifier list corresponding to the folder that the dialog box currently has open.
CDM_GETFOLDERPATH	Retrieves the path and name of the currently open folder or directory for the dialog box.
CDM_GETSPEC	Retrieves the filename (not including the path) of the currently selected file in the dialog box.


 Displaying a Print Dialog Box for the Default Printer

To display a Print dialog box for the default printer, initialize a PRINTDLG structure and then call the PrintDlg function.

The members of the PRINTDLG structure can contain information about the following items:

•	The printer device context

•	The values that should appear in the dialog box controls

•	The hook function and custom dialog box template to use for a customized version of the Print dialog box or Print Setup dialog box

To display a Print dialog box for the currently installed printer, include the following steps in your application:

1.	Use the PD_RETURNDC flag in the Flags member of the PRINTDLG structure. This flag should be specified only if the application requires a device context (DC) handle.

2.	Initialize the lStructSize, hDevMode, and hDevNames members.

3.	Call the PrintDlg function and pass a pointer to the PRINTDLG structure just initialized.

Using the PD_RETURNDC flag causes PrintDlg to display the Print dialog box and return a handle identifying a printer device context in the hDC member of the PRINTDLG structure. The application passes the DC handle as the first parameter to the graphics device interface (GDI) functions that render output on the printer.


 Displaying the Page Setup Dialog Box

The Page Setup dialog box allows the user to set the attibutes of the printed page, including the paper type, the paper source, the page orientation, and the width of the page margins. To display the Page Setup dialog box, initialize a PAGESETUPDLG structure and call the PageSetupDlg function.

One of the ways an application can customize the Page Setup dialog box is to use a hook function to paint the sample page of the dialog box. To use such a hook function, you must specify the PSD_ENABLEPAGEPAINTHOOK flag in the Flags member of the PAGESETUPDLG structure, and the name of your hook function in the lpfnPagePaintHook member.

After the dialog box is created, the system makes a sequence of calls to the hook function. Each call corresponds to a step in the drawing process, and includes a message that identifies the area of the sample page to be drawn, and the device context for the sample page. By processing these messages, the hook function can draw in one or more areas of the sample page. For a list of messages, see the description of the PAGESETUPDLG structure.

The following example creates a Page Setup dialog box and uses a hook function to draw the margin rectangle in the sample page area:

void DoPage(HWND hwnd, RECT rcMarg, RECT rcMinMarg, POINT ptPaperSize)

{

    PAGESETUPDLG psd = {0};

    psd.lStructSize = sizeof(PAGESETUPDLG);

    psd.hwndOwner   = hwnd;

    psd.hDevMode    = hDevMode;

    psd.hDevNames   = hDevNames;

    psd.Flags       = PSD_INTHOUSANDTHSOFINCHES | PSD_MARGINS |

        PSD_MINMARGINS | PSD_ENABLEPAGEPAINTHOOK;

    psd.ptPaperSize = ptPaperSize;

    psd.rtMargin = rcMarg;

    psd.rtMinMargin = rcMinMarg;

    psd.hInstance= g_hinst;

    psd.lCustData = 0;

    psd.lpfnPagePaintHook = PaintHook;

    PageSetupDlg(&psd);

}

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;

}


 Displaying the Find Dialog Box

The Find dialog box contains controls that allow a user to specify the following items:

•	Which string the application should find

•	Whether the string specifies a complete word or part of a word

•	Whether the application should match the case of the specified string

•	Which direction the application should search (preceding or following the current cursor location)

•	Whether the application should resume the search, searching for the next occurrence of the string

To display the Find dialog box, initialize a FINDREPLACE structure and call the FindText function. Members of the FINDREPLACE structure contain information about the following items:

•	Which window owns the dialog box

•	How the application should perform the search

•	Which character buffer should receive the string

To initialize the FINDREPLACE structure, perform the following tasks:

1.	Set the lStructSize member by using the sizeof operator.

2.	Set the hwndOwner member by using the handle that identifies the owner window of the dialog box.

3.	If you are customizing the Find dialog box, set the hInstance member to identify the instance of the module that contains your custom dialog box template.

4.	Set the Flags member to indicate the selection state of the dialog box options. (For example, specifying the FR_NOUPDOWN flag disables the Up and Down buttons, specifying the FR_NOWHOLEWORD flag disables the Match Whole Word Only check box, and specifying the FR_NOMATCHCASE flag disables the Match Case check box.)

5.	If you are supplying a custom dialog box template or hook function, specify additional flags in the Flags member.

6.	Set the lpstrFindWhat member to point to the buffer receiving the string to be found.

7.	Set the wFindWhatLen member to specify the size, in bytes, of the buffer pointed to by lpstrFindWhat.

8.	Set the lCustData member with any custom data your application may need to access.

9.	If your application customizes the Find dialog box, set the lpfnHook member to point to your hook function.

10.	If your application uses a custom dialog box template, set the lpTemplateName member to point to the string that identifies the template.

The following example initializes the FINDREPLACE structure and then calls FindText. This structure should be global or be declared as a static variable.

/* Find/Replace variables */

FINDREPLACE fr;        /* common dialog box structure     */

FINDREPLACE FAR* lpfr; /* pointer to dialog box structure */

CHAR szFindWhat[80];   /* buffer receiving string         */

HWND hdlg;             /* handle of dialog window         */

UINT uFindReplaceMsg;  /* returned by RegisterMessage()   */

/* Initialize the necessary members. */

fr.lStructSize = sizeof(FINDREPLACE);

fr.hwndOwner = hwnd;

fr.lpstrFindWhat = szFindWhat;

fr.wFindWhatLen = sizeof(szFindWhat);

/* Display the modeless Find dialog box. */

hdlg = FindText(&fr);


 Displaying the Replace Dialog Box

The Replace dialog box is similar to the Find dialog box. However, the Replace dialog box has no Direction check box and has three additional controls that enable the user to specify the following:

•	Which string to replace

•	Whether the application should replace the occurrence of the string currently highlighted

•	Whether the application should replace all occurrences of the string

To display the Replace dialog box, initialize a FINDREPLACE structure and call the ReplaceText function.


 Processing Messages for a Find or Replace Dialog Box

The Find and Replace dialog boxes differ from the other common dialog boxes in two respects: they are modeless and their respective dialog box procedures send messages to the application that calls the FindText or ReplaceText function. These messages contain data specified by the user in the dialog box controls, including which direction the application should search for a string, whether the application should match the case of the specified string, and whether the application should match the entire string.

To process messages from a Find or Replace dialog box, an application must register the dialog box's unique message, FINDMSGSTRING.

The application registers this message with the RegisterWindowMessage function. After the application registers the message, it uses the function's return value to identify messages from the Find or Replace dialog box. The following example registers the message with RegisterWindowMessage.

/* Register the FindReplace message. */

uFindReplaceMsg = RegisterWindowMessage(FINDMSGSTRING);

After the application registers this message, it can process messages for the Find or Replace dialog box by using the RegisterWindowMessage function's return value. The following example processes messages for the Find dialog box and then calls its own SearchFile function to locate the string of text. If the user is closing the dialog box (that is, if the Flags member of the FINDREPLACE structure is FR_DIALOGTERM), the handle is invalidated and the procedure returns zero.

if (message == uFindReplaceMsg){

    /*

     * Extract a pointer to the FINDREPLACE

     * structure from lParam.

     */

     lpfr = (FINDREPLACE FAR*) lParam;

    /*

     * If the system has set the FR_DIALOGTERM

     * flag, invalidate the handle identifying

     * the dialog box.

     */

     if (lpfr->Flags & FR_DIALOGTERM){

        hdlg = NULL;

        return 0;

        }

    /*

     * If the dialog box is still valid, call the

     * application-defined search routine (SearchFile) to

     * search for the requested string.

     */

     SearchFile((BOOL) (lpfr->Flags & FR_DOWN),

        (BOOL) (lpfr->Flags & FR_MATCHCASE));

     return 0;

     }


 Customizing Common Dialog Boxes

A custom common dialog box is a common dialog box altered to suit a particular Windows-based application. The customization may be complex and include the hiding of original controls, the addition of new controls, or a change in the size of the original dialog box; or it may be simple, involving the alteration of a single existing control.

If you want to customize a common dialog box, you must provide a special hook function and, in most cases, a custom dialog box template. Customizations of this kind require a significant amount of additional code — displaying a customized common dialog box is not as simple as initializing the members of a structure and calling a single function.

Applications that subclass controls in any of the common dialog boxes must do so while processing the WM_INITDIALOG message in the application's hook function. This method allows the application to receive the control-specific messages first, because it subclasses the control after the common dialog box has installed its subclassing procedures. (The previous hook function should be called for all messages not handled by the application's subclass function, as is standard for subclassing.)

An application cannot subclass a control by defining a local class to override a specific control type. This is not possible because the data segment will not be initialized correctly when the class is called — the data segment will be the common dialog box's data segment, not the application's data segment.


 Appropriate and Inappropriate Customizations

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 available space already 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.


 Hook Functions and Custom Dialog Box Templates

Windows NT Overview
For more information, see the Windows 95 overview Hook Functions and Custom Dialog Box Templates.

Each common dialog box uses the dialog box procedure and dialog box template provided for it in COMDLG32.DLL. The dialog box procedure processes messages and notifications for the common dialog box and its controls. The dialog box template defines the appearance of the dialog box — its dimensions, its location, and the dimensions and locations of controls within it.

In addition to the procedure and template provided, a custom dialog box requires a hook function that you provide and, usually, a custom version of the dialog box template.


 The Hook Function

Windows NT Overview
For more information, see the Windows 95 overview Hook Function.

The dialog box procedure provided in COMDLG32.DLL for a common dialog box calls the application's hook function if the application specifies the appropriate flag and pointer in the structure for that common dialog box. The structure for each common dialog box contains a Flags member that specifies whether the application defines a hook function and contains an lpfnHook member that points to the hook function, if one exists. If the application sets the Flags member to indicate that a hook function exists, it must also set the lpfnHook member. The following example sets the Flags and lpfnHook members of an OPENFILENAME structure to support an application's hook function.

#include <windows.h>

#include <commdlg.h>

#include <dlgs.h>

#include "generic.h"

OPENFILENAME ofn;       /* common dialog box structure    */

char szDirName[256];    /* directory string               */

char szFile[256];       /* filename string                */

char szFileTitle[256];  /* file title string              */

char szFilter[256];     /* filter string                  */

char chReplace;         /* string separator for szFilter  */

int i, cbString;        /* integer count variables        */

DWORD cBufLen;          /* dword count                    */

DWORD cTmp;             /* dword count                    */

HANDLE hf;              /* original file handle           */

HANDLE hfBackup;        /* backup file handle             */

char szBuffer[256];     /* character buffer               */

char szChar[256];       /* character buffer               */

char* pszBackupFile;    /* pointer to backup filename     */

BOOL fBackup;           /* TRUE if user checked "backup"  */

/* Obtain the system directory name. */

GetSystemDirectory((LPSTR)szDirName, sizeof(szDirName));

/* Place the terminating null character in the szFile. */

szFile[0] = '\0';

/* Load the filter string from the .RC file. */

cbString = LoadString(hinst, IDS_FILTERSTRING,

    szFilter, sizeof(szFilter));

/* Add a terminating null character to the string. */

chReplace = szFilter[cbString - 1];

for (i = 0; szFilter[i] != '\0'; i++) {

    if (szFilter[i] == chReplace)

        szFilter[i] = '\0';

}

/* Initialize the required OPENFILENAME members. */

ofn.lStructSize = sizeof(OPENFILENAME);

ofn.hwndOwner = hwnd;

ofn.hInstance = hinst;

ofn.lpstrFilter = szFilter;

ofn.nFilterIndex = 1;

ofn.lpstrFile = szFile;

ofn.nMaxFile = sizeof(szFile);

ofn.lpstrFileTitle = szFileTitle;

ofn.nMaxFileTitle = sizeof(szFileTitle);

ofn.lpstrInitialDir = szDirName;

ofn.Flags = OFN_SHOWHELP | OFN_PATHMUSTEXIST |

    OFN_FILEMUSTEXIST | OFN_ENABLEHOOK |

    OFN_ENABLETEMPLATE;

ofn.lpfnHook = FileOpenHookProc;

ofn.lpTemplateName = "FILEOPEN";

In the previous example, the address of the application-defined hook function is assigned to the lpfnHook member of the OPENFILENAME structure. The hook function processes any messages or notifications the custom dialog box requires. With the exception of one message (WM_INITDIALOG), the hook function receives messages and notifications before the dialog box procedure provided in COMDLG32.DLL receives them. In the case of WM_INITDIALOG, the hook function receives the message after the dialog box procedure. When the hook function finishes processing a message, it returns a value that indicates whether the dialog box procedure provided in COMDLG32.DLL should also process the message. If the dialog box procedure should process the message, the return value is FALSE. However, if the dialog box procedure should ignore the message, the return value is TRUE.

To process the message from the OK button after the dialog box procedure processes it, an application must post a message to itself when the OK message is received. When the application receives the message it has posted, the common dialog box procedure will have finished processing messages for the dialog box. This technique is particularly useful when working with the Find and Replace dialog boxes, because the Flags member of the FINDREPLACE structure does not reflect changes to the dialog box until after the messages have been processed by COMDLG32.DLL.

The following example shows a hook function for a custom Open dialog box.

UINT FAR PASCAL FileOpenHookProc(HWND hdlg, UINT msg, WPARAM wParam,

    LPARAM lParam)

{

    switch (msg) {

        /* WM_INITDIALOG is received after commdlg

        /* is processed.

         */

        case WM_INITDIALOG:

            return TRUE;

        case WM_COMMAND:

            /* Use IsDlgButtonChecked to set lCustData. */

            if (wParam == IDOK)

                /* Set the "backup file" flag. */

                fBackup = (DWORD) IsDlgButtonChecked(hdlg,

                    ID_CUSTCHX);

            return FALSE; /* Allow standard processing. */

            break;

        default:

            return FALSE;

    } /* end switch */

    return FALSE;

}

This hook function tests a custom check box when the user chooses the OK button. If the check box is selected, the hook function sets a global variable to a nonzero value; otherwise, it sets this variable to zero.

A hook function should never call the EndDialog function. Instead, if a hook function contains code that abnormally terminates a common dialog box, this code should pass the IDABORT value to the dialog box procedure by using the PostMessage function, as shown in the following example.

PostMessage(hDlg, WM_COMMAND, IDABORT, (LONG) FALSE);

When a hook function posts the IDABORT value, the common dialog box function returns the value contained in the low-order word of the lParam parameter. For example, if the hook function for GetOpenFileName calls the PostMessage function with (LONG) 100 as the last parameter, GetOpenFileName returns 100.

A hook function must be exported in an application's module-definition (.DEF) file, as shown in the following example.

NAME         Generic       ; application's module name

DESCRIPTION  'Sample Win32-based Application'

EXETYPE      WINDOWS       ; required for all Win32-based applications

STUB         'WINSTUB.EXE' ; Generates an error message if the

                           ; application is run without

                           ; Windows

CODE  PRELOAD MOVEABLE DISCARDABLE

DATA  PRELOAD MOVEABLE MULTIPLE

EXPORTS

        MainWndProc   @1   ; window processing function

        About         @2   ; "About" processing function

        FileOpenHookProc @3; common dialog box callback


 Customizing a Dialog Box Template

The dialog box template provided in COMDLG32.DLL for each common dialog box contains the data the dialog box procedure uses to display that common dialog box. Most applications that customize a common dialog box also need to create a custom dialog box template to use instead of the dialog box template in COMDLG32.DLL. (A custom dialog box template is not required for all custom dialog boxes. A template would not be necessary, for instance, if an application changed a dialog box in a relatively minor way and only in an unusual situation.)

A developer should create a custom dialog box template by modifying the appropriate dialog box template in COMDLG32.DLL. Following are the template filenames and the names of their corresponding common dialog boxes.

Template filename	Corresponding dialog box
COLOR.DLG	Color
FILEOPEN.DLG	Open (single selection)
FILEOPEN.DLG	Open (multiple selection)
FINDTEXT.DLG	Find
FINDTEXT.DLG	Replace
FONT.DLG	Font
PRNSETUP.DLG	Print
PRNSETUP.DLG	Print Setup
Note  The custom dialog box templates listed above are defined in DLGS.H, except for COLOR.DLG, which is defined in COLORDLG.H.

The following example is from a custom dialog box template created for an Open dialog box.

FILEOPEN DIALOG LOADONCALL MOVEABLE DISCARDABLE

    36, 24, 264, 134

CAPTION "Open"

STYLE WS_CAPTION | WS_SYSMENU | WS_POPUP | DS_MODALFRAME

FONT 8, "Helv"

BEGIN

    LTEXT "File &Name:", stc3, 6, 6, 76, 10

    CONTROL "", edt1, "edit", ES_LEFT | ES_AUTOHSCROLL |

        WS_BORDER | WS_TABSTOP | WS_CHILD | ES_OEMCONVERT |

        ES_LOWERCASE, 6, 16, 90, 12

    CONTROL "", lst1, "listbox", LBS_SORT | LBS_NOTIFY |

        LBS_DISABLENOSCROLL | WS_VSCROLL | WS_BORDER |

        WS_TABSTOP | LBS_EXTENDEDSEL | LBS_HASSTRINGS |

        LBS_OWNERDRAWFIXED, 6, 32, 90, 68

    LTEXT "&Directories:", -1, 110,  6, 92, 9

    LTEXT "", stc1,            110, 16, 92, 9, SS_NOPREFIX

    CONTROL "", lst2, "listbox", LBS_SORT | LBS_HASSTRINGS |

        LBS_NOTIFY | LBS_DISABLENOSCROLL | WS_VSCROLL |

        WS_CHILD | WS_BORDER | WS_TABSTOP |

        LBS_OWNERDRAWFIXED, 110, 32, 92, 68

    LTEXT "List Files of &Type:", stc2, 6, 102, 90, 9

    CONTROL "", cmb1, "combobox", CBS_DROPDOWNLIST |

        CBS_AUTOHSCROLL | WS_BORDER | WS_VSCROLL |

        WS_TABSTOP | WS_CHILD, 6,  112,  90,  36

    LTEXT "Dri&ves:", stc4, 110, 102, 92, 9

    CONTROL "", cmb2, "combobox", CBS_SORT |

        CBS_HASSTRINGS | CBS_OWNERDRAWFIXED |

        CBS_DROPDOWNLIST | WS_CHILD |

        CBS_AUTOHSCROLL | WS_BORDER | WS_VSCROLL |

        WS_TABSTOP, 110, 112,  92, 68

    DEFPUSHBUTTON "OK",  IDOK,     208,  6, 50, 14, WS_GROUP

    PUSHBUTTON "Cancel", IDCANCEL, 208, 24, 50, 14, WS_GROUP

    PUSHBUTTON "&Help", pshHelp,     208,  46, 50, 14,

        WS_GROUP

    PUSHBUTTON "Net&work...", psh14, 208, 114, 50, 14,

        WS_GROUP

    AUTOCHECKBOX "&Read Only", chx1, 208,  68, 50, 12,

        WS_TABSTOP | WS_GROUP

    AUTOCHECKBOX "&Backup File", ID_CUSTCHX,

        208, 86, 50, 12, BS_AUTOCHECKBOX | WS_CHILD |

        WS_TABSTOP | WS_GROUP

END

The last entry supports the addition of a new Backup File check box immediately below the existing Read Only check box.

The custom template should be added to the application's resource file. You must use all of the unique control identifiers (that is, all identifiers whose values are other than −1) in the template, even if the dialog box does not use those controls. If you do not want to display all of the controls, you can specify coordinates for them outside the dialog box. You should also disable unwanted buttons and remove unnecessary tab stops.


 Displaying the Custom Dialog Box

After your application creates the hook function and the dialog box template, it should set the members of the structure for the common dialog box being customized and call the appropriate function to display the custom dialog box.

The following example calls the GetOpenFileName function and creates a backup file if the user selects the Backup File check box in the custom Open dialog box.

/* Process the requested file. */

if (GetOpenFileName(&ofn)) {

    /*

     * If the user checked the Backup File Check box,

     * create a backup file.

     */

    if (fBackup) {

        /* Open the requested file. */

        hf = CreateFile(ofn.lpstrFile, GENERIC_READ,

             0, (LPSECURITY_ATTRIBUTES) NULL,

             OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,

             (HANDLE) NULL);

        /* Process the extension (if it exists). */

        if (ofn.nFileExtension) {

            for(i = 0; i < (int)ofn.nFileExtension;

                i++)

                szChar[i] = *ofn.lpstrFile++;

        } /* end if */

        else {

            i = 0;

            while (*ofn.lpstrFile != '\0')

                szChar[i++] = *ofn.lpstrFile++;

            szChar[i] = '.';

        } /* end else */

        /* Create the backup filename string. */

        pszBackupFile = lstrcat(szChar, "BAK");

        /* Create the backup file. */

        hfBackup = CreateFile(pszBackupFile, GENERIC_WRITE,

            0, (LPSECURITY_ATTRIBUTES) NULL,

            CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL,

            (HANDLE) NULL);

        /*

         * Copy the contents of the original file

         * to the new file.

         */

        ReadFile(hf, szBuffer, 256, &cBufLen,

            NULL);

        while (cBufLen == 256) {

            WriteFile(hfBackup, szBuffer, 256, &cBufLen,

                NULL);

            ReadFile(hf, szBuffer, 256, &cBufLen, NULL);

        }

        WriteFile(hfBackup, szBuffer, cBufLen, &cTmp,

            NULL);

        /* Close the files. */

        CloseHandle(hfBackup);

        CloseHandle(hf);

    } /* end if */

} /* end if */


 Supporting Help for Common Dialog Boxes

An application can display a Help button in any of the common dialog boxes by specifying the appropriate flag in the Flags member of the structure for a specific common dialog box. Following are the structures for the common dialog boxes and the Help flag that corresponds to each structure.

Structure	Flag
OPENFILENAME	OFN_SHOWHELP
CHOOSECOLOR	CC_SHOWHELP
FINDREPLACE	FR_SHOWHELP
CHOOSEFONT	CF_SHOWHELP
PRINTDLG	PD_SHOWHELP
If an application displays the Help button, it must process the user's request for help. The processing can be done either in one of the application's window procedures or in a hook function.

If the application processes the request for help in one of the application's window procedures, it must first create a new message identifier for the string defined by the HELPMSGSTRING value. The application creates the new message identifier by calling the RegisterWindowMessage function and passing this value as the single parameter. (For more information about processing registered window messages, see "Displaying the Find Dialog Box" earlier in this chapter.) In addition to creating a new message identifier, the application must use the hwndOwner member of the appropriate structure for the common dialog box, so this member contains the handle of the dialog box's owner window. After the message identifier is created and the hwndOwner member is specified, the dialog box procedure notifies the window procedure of the owner window whenever the user chooses the Help button.

The following example processes a user's request for help in the window procedure of its owner window. The if statement should be in the default section of the switch statement that processes messages.

MyHelpMsg = RegisterWindowMessage(HELPMSGSTRING);

.

.

.

if (message == MyHelpMsg)

    WinHelp(hWnd, "appfile.hlp", HELP_CONTEXT, ID_MY_CONTEXT);

If the application processes the request for help in a hook function, it should test for the following condition in the WM_COMMAND message.

wParam == pshHelp

When this condition is true, the hook function should call the WinHelp function, as shown in the preceding example. (To process the request for help in a hook function, you must include the DLGS.H header file in the source file that contains the hook-function code.)


 Error Detection

Whenever a common dialog box function fails, an application can call the CommDlgExtendedError function to find out the cause of the failure. This function returns an error value that identifies the cause of the most recent error.

Six values are defined in the CDERR.H header file that identify the ranges of error values for categories of errors returned by CommDlgExtendedError. Following are these values in ascending order by value range.

Value	Meaning
CDERR_GENERALCODES	General error codes for common dialog boxes. These errors are in the range 0x0000 through 0x0FFF.
PDERR_PRINTERCODES	Error codes for the Print common dialog box. These errors are in the range 0x1000 through 0x1FFF.
CFERR_CHOOSEFONTCODES	Error codes for the Font common dialog box. These errors are in the range 0x2000 through 0x2FFF.
FNERR_FILENAMECODES	Error codes for the Open and Save As common dialog boxes. These errors are in the range 0x3000 through 0x3FFF.
FRERR_FINDREPLACECODES	Error codes for the Find and Replace common dialog boxes. These errors are in the range 0x4000 through 0x4FFF.
CCERR_CHOOSECOLORCODES	Error codes for the Color common dialog box. These errors are in the range 0x5000 through 0x5FFF.


 Common Dialog Box Reference

The following functions, structures, and messages are associated with common dialog boxes in Windows NT.


 Common Dialog Box Functions

Following are the functions used with common dialog boxes.

ChooseColor
ChooseFont
CommDlgExtendedError
FindText
GetFileTitle
GetOpenFileName
GetSaveFileName
PageSetupDlg
PrintDlg
ReplaceText


 Common Dialog Box Structures

Following are the structures used with common dialog boxes.

OFNOTIFY
PAGESETUPDLG


 Common Dialog Box Messages

Following are the messages used with common dialog boxes.

CDM_GETFILEPATH
CDM_GETFOLDERIDLIST
CDM_GETFOLDERPATH
CDM_GETSPEC
CDM_HIDECONTROL
CDM_SETCONTROLTEXT
CDM_SETDEFEXT
CDN_FILEOK
CDN_FOLDERCHANGE
CDN_HELP
CDN_INITDONE
CDN_SELCHANGE
CDN_SHAREVIOLATION
CDN_TYPECHANGE
COLOROKSTRING
FILEOKSTRING
FINDMSGSTRING
LBSELCHSTRING
SETRGBSTRING
SHAREVISTRING
WM_CHOOSEFONT_SETFLAGS
WM_CHOOSEFONT_SETLOGFONT
WM_PSD_ENVSTAMPRECT
WM_PSD_FULLPAGERECT
WM_PSD_GREEKTEXTRECT
WM_PSD_MARGINRECT
WM_PSD_MINMARGINRECT
WM_PSD_PAGESETUPDLG
WM_PSD_YAFULLPAGERECT


 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 section, the term mouse refers to any pointing device.) When the user moves the mouse, Microsoft® Windows® moves the cursor accordingly. Microsoft Win32® cursor functions enable applications to create, load, display, move, confine, and destroy cursors.


 About Cursors

Windows provides a set of standard cursors that are available for any application to use at any time. The Windows header files contain identifiers for the standard cursors — the identifiers begin with the "IDC_" prefix.

Each standard cursor has a corresponding default image associated with it. The user or an application can replace the default image associated with any standard cursor at any time. An application replaces a default image by using the SetSystemCursor function.

An application can use the GetIconInfo function to retrieve the current image for a cursor, and can draw the cursor by using the DrawIconEx function. To draw the default image for a standard cursor, specify the DI_COMPAT flag in the call to DrawIconEx. If you do not specify the DI_COMPAT flag, DrawIconEx draws the standard cursor using the image that the user specified.

Custom cursors are designed for use in a specific application and can be any design the developer defines. The following illustration shows several custom cursors.

Cursors can be either monochrome or color, and either static or animated. The type of cursor used on a particular computer system depends on the system's display. Old displays such as VGA do not support color or animated cursors, but new displays (whose display drivers use the DIB engine) do support them.

Cursors and icons are similar and can be used interchangeably in many situations. The only difference between them is that an image specified as a cursor must be in the format that the display can support. For example, a cursor must be monochrome for a VGA display.


 The Hot Spot

In the cursor, a pixel called the hot spot marks the exact screen location that is affected by a mouse event, such as clicking a mouse button. Typically, the hot spot is the focal point of the cursor. The system tracks and recognizes this point as the position of the cursor. For example, typical hot spots are the pixel at the tip of an arrow-shaped cursor and the pixel in the middle of a crosshair-shaped cursor.

When a mouse input event occurs, the Windows mouse driver translates the event into an appropriate mouse message that includes the coordinates of the hot spot. Windows sends the mouse message to the window that contains the hot spot or to the window that is capturing mouse input. For more information about mouse input, see Mouse Input.


 The Mouse and the Cursor

If the system includes a mouse, Windows 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, Windows (or an application) changes the appearance of the cursor. For example, when the cursor crosses a window border, Windows changes the cursor into a two-headed arrow.

If the system does not have a mouse, Windows displays and moves the cursor only when the user chooses certain system commands, such as those used to size or move a window. To provide the user with a method of displaying and moving the cursor when a mouse isn't available, an application can use the cursor functions to simulate mouse movement. Given this simulation capability, the user can use the arrow keys to move the cursor.


 Cursor Creation

Because standard cursors are predefined, it is not necessary to create them. To use a standard cursor, an application retrieves a cursor handle by using the LoadCursor or LoadImage function. A cursor handle is a unique value of the HCURSOR type that identifies a standard or custom cursor.

To create a custom cursor for an application, developers typically use a graphics application and include the cursor as a resource in the application's resource-definition file. At run time, an application calls LoadCursor to retrieve the cursor handle. Cursor resources contain data for several different display devices. LoadCursor automatically selects the most appropriate data for the current display device.

An application can also create a custom cursor at run time by using the CreateIconIndirect function, which creates a cursor based on the content of an ICONINFO structure. The GetIconInfo function fills this structure with hot spot coordinates and information concerning the associated bitmask and color.

Applications should implement custom cursors as resources and use LoadCursor 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

If the system includes a mouse, Windows automatically displays a cursor and updates its position on the screen. Applications can obtain current screen coordinates of the cursor; applications move the cursor to any location on the screen by using the GetCursorPos and SetCursorPos functions, respectively.

Applications can also retrieve the handle of the current cursor by using the GetCursor function and can set the cursor by using the SetCursor function. After an application uses SetCursor, the appearance of the cursor does not change until the mouse moves, until the cursor is explicitly set to a different cursor, or until a system command is executed.

When the user moves the mouse, the system redraws the cursor at the new location as designated by the mouse. The system automatically redraws the cursor design associated with the window to which the cursor is pointing.

Applications can hide and redisplay the cursor, without changing the cursor design, by using the ShowCursor function. This function uses an internal counter to determine when to hide or display the cursor. An attempt to show the cursor increments the counter; an attempt to hide the cursor decrements the counter. The cursor is visible only if this counter is greater than or equal to zero.


 The Window Class Cursor

When registering a window class, an application can assign it a default cursor, known as the class cursor. After the application registers the window class, each window of that class will have the specified class cursor.

To override the class cursor, an application can process the WM_SETCURSOR message. Applications can also replace a class cursor by using the SetClassLong function. This function changes the default window settings for all windows of a given class. For more information about window classes, see Window Classes.


 Cursor Confinement

Applications can confine the cursor to a rectangular area on the screen by using the ClipCursor function. This can be useful when the user must respond to a certain event within the confined area of the rectangle. For example, an application 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, the application can also use this function to save the coordinates of the original area in which the cursor can move. Then, the application can restore the cursor to the original area when the new confinement is no longer necessary.


 Cursor Destruction

When an application no longer needs a cursor it created by using the CreateIconIndirect function, it should destroy the cursor. The DestroyCursor function destroys the cursor handle and frees any memory that it used. Applications should use this function only on cursors that were created with CreateIconIndirect; it is not necessary to destroy other cursors.

The DestroyCursor function has no effect on a shared cursor; that is, a cursor that was loaded by using the LR_SHARED flag with the LoadImage function. A shared cursor is valid as long as the module from which it was loaded remains in memory.


 Cursor Duplication

The CopyCursor function copies a cursor handle. This enables an application or DLL to retrieve the handle of a cursor owned by another module. Then, if the other module is freed, the application that copied the cursor will still be able to use the cursor design.

For information on how to add, remove, or replace cursor resources in executable files, see Resources.


 Using Cursors

•	Creating a cursor

•	Displaying a cursor

•	Confining a cursor

•	Using cursor functions to create a mousetrap

•	Using the keyboard to move the cursor


 Creating a Cursor

The following example creates two cursor handles: one for the standard hourglass cursor and one for a custom cursor included as a resource in the application's resource-definition file.

HINSTANCE hinst;            /* handle of 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));

An application should implement custom cursors as resources. Rather than create the cursors at run time, use the LoadCursor or LoadImage function to avoid device dependence, to simplify localization, and to enable applications to share cursor designs.

The following example uses the CreateCursor function to create a custom cursor at run time. The example is included here to illustrate how the system interprets cursor bitmasks. Even though this example uses the CreateCursor function, you should use the CreateIconIndirect function instead because it is more efficient.

HINSTANCE hinst;            /* handle of current instance */

HCURSOR hCurs1, hCurs2;     /* cursor handles             */

HCURSOR hCurs3;             /* cursor handle              */

/* Yin cursor AND bitmask */

BYTE ANDmaskCursor[] = {

    0xFF, 0xFC, 0x3F, 0xFF,   /* line 1  */

    0xFF, 0xC0, 0x1F, 0xFF,   /* line 2  */

    0xFF, 0x00, 0x3F, 0xFF,   /* line 3  */

    0xFE, 0x00, 0xFF, 0xFF,   /* line 4  */

    0xF7, 0x01, 0xFF, 0xFF,   /* line 5  */

    0xF0, 0x03, 0xFF, 0xFF,   /* line 6  */

    0xF0, 0x03, 0xFF, 0xFF,   /* line 7  */

    0xE0, 0x07, 0xFF, 0xFF,   /* line 8  */

    0xC0, 0x07, 0xFF, 0xFF,   /* line 9  */

    0xC0, 0x0F, 0xFF, 0xFF,   /* line 10 */

    0x80, 0x0F, 0xFF, 0xFF,   /* line 11 */

    0x80, 0x0F, 0xFF, 0xFF,   /* line 12 */

    0x80, 0x07, 0xFF, 0xFF,   /* line 13 */

    0x00, 0x07, 0xFF, 0xFF,   /* line 14 */

    0x00, 0x03, 0xFF, 0xFF,   /* line 15 */

    0x00, 0x00, 0xFF, 0xFF,   /* line 16 */

    0x00, 0x00, 0x7F, 0xFF,   /* line 17 */

    0x00, 0x00, 0x1F, 0xFF,   /* line 18 */

    0x00, 0x00, 0x0F, 0xFF,   /* line 19 */

    0x80, 0x00, 0x0F, 0xFF,   /* line 20 */

    0x80, 0x00, 0x07, 0xFF,   /* line 21 */

    0x80, 0x00, 0x07, 0xFF,   /* line 22 */

    0xC0, 0x00, 0x07, 0xFF,   /* line 23 */

    0xC0, 0x00, 0x0F, 0xFF,   /* line 24 */

    0xE0, 0x00, 0x0F, 0xFF,   /* line 25 */

    0xF0, 0x00, 0x1F, 0xFF,   /* line 26 */

    0xF0, 0x00, 0x1F, 0xFF,   /* line 27 */

    0xF8, 0x00, 0x3F, 0xFF,   /* line 28 */

    0xFE, 0x00, 0x7F, 0xFF,   /* line 29 */

    0xFF, 0x00, 0xFF, 0xFF,   /* line 30 */

    0xFF, 0xC3, 0xFF, 0xFF,   /* line 31 */

    0xFF, 0xFF, 0xFF, 0xFF};  /* line 32 */

/* Yin cursor XOR bitmask */

BYTE XORmaskCursor[] = {

    0x00, 0x00, 0x00, 0x00,   /* line 1  */

    0x00, 0x03, 0xC0, 0x00,   /* line 2  */

    0x00, 0x3F, 0x00, 0x00,   /* line 3  */

    0x00, 0xFE, 0x00, 0x00,   /* line 4  */

    0x0E, 0xFC, 0x00, 0x00,   /* line 5  */

    0x07, 0xF8, 0x00, 0x00,   /* line 6  */

    0x07, 0xF8, 0x00, 0x00,   /* line 7  */

    0x0F, 0xF0, 0x00, 0x00,   /* line 8  */

    0x1F, 0xF0, 0x00, 0x00,   /* line 9  */

    0x1F, 0xE0, 0x00, 0x00,   /* line 10 */

    0x3F, 0xE0, 0x00, 0x00,   /* line 11 */

    0x3F, 0xE0, 0x00, 0x00,   /* line 12 */

    0x3F, 0xF0, 0x00, 0x00,   /* line 13 */

    0x7F, 0xF0, 0x00, 0x00,   /* line 14 */

    0x7F, 0xF8, 0x00, 0x00,   /* line 15 */

    0x7F, 0xFC, 0x00, 0x00,   /* line 16 */

    0x7F, 0xFF, 0x00, 0x00,   /* line 17 */

    0x7F, 0xFF, 0x80, 0x00,   /* line 18 */

    0x7F, 0xFF, 0xE0, 0x00,   /* line 19 */

    0x3F, 0xFF, 0xE0, 0x00,   /* line 20 */

    0x3F, 0xC7, 0xF0, 0x00,   /* line 21 */

    0x3F, 0x83, 0xF0, 0x00,   /* line 22 */

    0x1F, 0x83, 0xF0, 0x00,   /* line 23 */

    0x1F, 0x83, 0xE0, 0x00,   /* line 24 */

    0x0F, 0xC7, 0xE0, 0x00,   /* line 25 */

    0x07, 0xFF, 0xC0, 0x00,   /* line 26 */

    0x07, 0xFF, 0xC0, 0x00,   /* line 27 */

    0x01, 0xFF, 0x80, 0x00,   /* line 28 */

    0x00, 0xFF, 0x00, 0x00,   /* line 29 */

    0x00, 0x3C, 0x00, 0x00,   /* line 30 */

    0x00, 0x00, 0x00, 0x00,   /* line 31 */

    0x00, 0x00, 0x00, 0x00};  /* line 32 */

/* Create a custom cursor at run time. */

hCurs3 = CreateCursor(hinst,  /* app instance */

             19,     /* horiz pos of hot spot */

             2,      /* vert pos of hot spot  */

             32,     /* cursor width          */

             32,     /* cursor height         */

             ANDmaskCursor,    /* AND bitmask */

             XORmaskCursor);   /* XOR bitmask */

To create the cursor, CreateCursor applies the following truth table to the AND and XOR bitmasks.

AND bitmask	XOR bitmask	Display
0	0	Black
0	1	White
1	0	Screen
1	1	Reverse screen
For more information about bitmaps, see Bitmaps.

Before closing, your application must use the DestroyCursor function to destroy any cursors it created with CreateCursor. It is not necessary to destroy cursors created by other functions.


 Displaying a Cursor

If the system includes a mouse, Windows automatically displays the class cursor (the cursor associated with the window to which the cursor is pointing). Your application 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 proc.   */

wc.cbClsExtra = 0;           /* no per-class extra data   */

wc.cbWndExtra = 0;           /* no per-window extra data  */

wc.hInstance = hinstance;    /* app that owns the class   */

wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); /* class icon */

wc.hCursor = LoadCursor(hinstance, MAKEINTRESOURCE(230));

                                          /* class cursor */

wc.hbrBackground = GetStockObject(WHITE_BRUSH);

                                      /* class background */

wc.lpszMenuName =  "GenericMenu";           /* class menu */

wc.lpszClassName = "GenericWClass"          /* class name */

/* Register the window class. */

return RegisterClass(&wc);

When the window class is registered, the cursor identified by 230 in the application's resource-definition file will be the default cursor for all windows based on the class.

Your application can change the design of the cursor by using the SetCursor function and specifying a different cursor handle. However, when the cursor moves, Windows redraws the class cursor at the new location. To prevent the class cursor from being redrawn, your application must process the WM_SETCURSOR message. Each time the cursor moves and mouse input is not captured, Windows 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, Windows displays the class cursor.

Your application can replace a class cursor by using the SetClassLong function. This function changes the default window settings for all windows of a given class. The following example replaces the existing class cursor with the hCurs2 cursor.

/* Change the cursor for hwnd's window class. */

SetClassLong(hwnd,    /* window handle */

    GCL_HCURSOR,      /* change cursor */

    (LONG) hCurs2);   /* new cursor    */

For more information about window classes and mouse input, 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 ClipCursor area      */

RECT rcOldClip;        /* previous ClipCursor area */

/* Record the area in which the cursor can move. */

GetClipCursor(&rcOldClip);

/* Get the dimensions of the application's window. */

GetWindowRect(hwnd, &rcClip);

/* Confine the cursor to the application's window. */

ClipCursor(&rcClip);

    .

    .  /* Process input from the confined cursor. */

    .

/* Restore the cursor to its previous area. */

ClipCursor(&rcOldClip);

Because there is only one cursor at a time available in the system, an application that confines the cursor must restore the cursor before relinquishing control to another window.


 Using Cursor Functions to Create a Mousetrap

The following example uses the SetCursorPos, GetCursorPos, CreateCursor, LoadCursor, and SetCursor functions to create a simple mousetrap. It also uses cursor and timer functions to monitor the cursor's position every 10 seconds. If the cursor position has not changed in the last 10 seconds and the application's main window is minimized, the application changes the cursor and moves it to the mousetrap icon.

An example for a similar mousetrap is included in Icons. It uses the LoadCursor and LoadIcon functions instead of the more device-dependent CreateCursor and CreateIcon functions.

HICON hIcon1;               /* icon handles             */

POINT ptOld;                /* previous cursor location */

HCURSOR hCurs1;             /* cursor handle            */

/*

 * The following cursor bitmasks are defined in a code

 * example that appears earlier in this topic.

 */

/* Yin cursor AND and XOR bitmasks */

BYTE ANDmaskCursor[] = ...

BYTE XORmaskCursor[] = ...

/* Yang icon AND bitmask */

BYTE ANDmaskIcon[] = {0xFF, 0xFF, 0xFF, 0xFF,  /* line 1  */

                      0xFF, 0xFF, 0xC3, 0xFF,  /* line 2  */

                      0xFF, 0xFF, 0x00, 0xFF,  /* line 3  */

                      0xFF, 0xFE, 0x00, 0x7F,  /* line 4  */

                      0xFF, 0xFC, 0x00, 0x1F,  /* line 5  */

                      0xFF, 0xF8, 0x00, 0x0F,  /* line 6  */

                      0xFF, 0xF8, 0x00, 0x0F,  /* line 7  */

                      0xFF, 0xF0, 0x00, 0x07,  /* line 8  */

                      0xFF, 0xF0, 0x00, 0x03,  /* line 9  */

                      0xFF, 0xE0, 0x00, 0x03,  /* line 10 */

                      0xFF, 0xE0, 0x00, 0x01,  /* line 11 */

                      0xFF, 0xE0, 0x00, 0x01,  /* line 12 */

                      0xFF, 0xF0, 0x00, 0x01,  /* line 13 */

                      0xFF, 0xF0, 0x00, 0x00,  /* line 14 */

                      0xFF, 0xF8, 0x00, 0x00,  /* line 15 */

                      0xFF, 0xFC, 0x00, 0x00,  /* line 16 */

                      0xFF, 0xFF, 0x00, 0x00,  /* line 17 */

                      0xFF, 0xFF, 0x80, 0x00,  /* line 18 */

                      0xFF, 0xFF, 0xE0, 0x00,  /* line 19 */

                      0xFF, 0xFF, 0xE0, 0x01,  /* line 20 */

                      0xFF, 0xFF, 0xF0, 0x01,  /* line 21 */

                      0xFF, 0xFF, 0xF0, 0x01,  /* line 22 */

                      0xFF, 0xFF, 0xF0, 0x03,  /* line 23 */

                      0xFF, 0xFF, 0xE0, 0x03,  /* line 24 */

                      0xFF, 0xFF, 0xE0, 0x07,  /* line 25 */

                      0xFF, 0xFF, 0xC0, 0x0F,  /* line 26 */

                      0xFF, 0xFF, 0xC0, 0x0F,  /* line 27 */

                      0xFF, 0xFF, 0x80, 0x1F,  /* line 28 */

                      0xFF, 0xFF, 0x00, 0x7F,  /* line 29 */

                      0xFF, 0xFC, 0x00, 0xFF,  /* line 30 */

                      0xFF, 0xF8, 0x03, 0xFF,  /* line 31 */

                      0xFF, 0xFC, 0x3F, 0xFF}; /* line 32 */

/* Yang icon XOR bitmask */

BYTE XORmaskIcon[] = {0x00, 0x00, 0x00, 0x00,  /* line 1  */

                      0x00, 0x00, 0x00, 0x00,  /* line 2  */

                      0x00, 0x00, 0x00, 0x00,  /* line 3  */

                      0x00, 0x00, 0x00, 0x00,  /* line 4  */

                      0x00, 0x00, 0x00, 0x00,  /* line 5  */

                      0x00, 0x00, 0x00, 0x00,  /* line 6  */

                      0x00, 0x00, 0x00, 0x00,  /* line 7  */

                      0x00, 0x00, 0x38, 0x00,  /* line 8  */

                      0x00, 0x00, 0x7C, 0x00,  /* line 9  */

                      0x00, 0x00, 0x7C, 0x00,  /* line 10 */

                      0x00, 0x00, 0x7C, 0x00,  /* line 11 */

                      0x00, 0x00, 0x38, 0x00,  /* line 12 */

                      0x00, 0x00, 0x00, 0x00,  /* line 13 */

                      0x00, 0x00, 0x00, 0x00,  /* line 14 */

                      0x00, 0x00, 0x00, 0x00,  /* line 15 */

                      0x00, 0x00, 0x00, 0x00,  /* line 16 */

                      0x00, 0x00, 0x00, 0x00,  /* line 17 */

                      0x00, 0x00, 0x00, 0x00,  /* line 18 */

                      0x00, 0x00, 0x00, 0x00,  /* line 19 */

                      0x00, 0x00, 0x00, 0x00,  /* line 20 */

                      0x00, 0x00, 0x00, 0x00,  /* line 21 */

                      0x00, 0x00, 0x00, 0x00,  /* line 22 */

                      0x00, 0x00, 0x00, 0x00,  /* line 23 */

                      0x00, 0x00, 0x00, 0x00,  /* line 24 */

                      0x00, 0x00, 0x00, 0x00,  /* line 25 */

                      0x00, 0x00, 0x00, 0x00,  /* line 26 */

                      0x00, 0x00, 0x00, 0x00,  /* line 27 */

                      0x00, 0x00, 0x00, 0x00,  /* line 28 */

                      0x00, 0x00, 0x00, 0x00,  /* line 29 */

                      0x00, 0x00, 0x00, 0x00,  /* line 30 */

                      0x00, 0x00, 0x00, 0x00,  /* line 31 */

                      0x00, 0x00, 0x00, 0x00}; /* line 32 */

hIcon1 = CreateIcon(hinstance, /* handle of app instance  */

             32,           /* icon width                  */

             32,           /* icon height                 */

             1,            /* number of XOR planes        */

             1,            /* number of bits per pixel    */

             ANDmaskIcon,  /* AND bitmask                 */

             XORmaskIcon); /* XOR bitmask                 */

hCurs1 = CreateCursor(hinstance, /* handle of app inst.   */

             19,         /* horiz. position of hot spot   */

             2,          /* vert. position of hot spot    */

             32,         /* cursor width                  */

             32,         /* cursor height                 */

             ANDmaskCursor,            /* AND bitmask     */

             XORmaskCursor);           /* XOR bitmask     */

.

. /* Fill in the window class structure. */

.

WNDCLASS  wc;

wc.hIcon = hIcon1;                        /* class icon   */

wc.hCursor = LoadCursor(NULL, IDC_ARROW); /* class cursor */

.

. /*

.  * Register the window class and perform

.  * other application initialization.

.  */

.

/* Set a timer for the mousetrap. */

GetCursorPos(&ptOld);

SetTimer(hwnd, IDT_CURSOR, 10000, (TIMERPROC) NULL);

LONG APIENTRY MainWndProc(

    HWND hwnd,          /* window handle          */

    UINT message,       /* type of message        */

    UINT wParam,        /* additional information */

    LONG lParam)        /* additional information */

{

    HDC hdc;              /* handle of 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;

                .

                . /* Process other messages. */

                .

    }             /* ends switch (message) */


 Using the Keyboard to Move the Cursor

Because Windows 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++;           /* increments 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;            /* clears repeat count */

        break;

        .

        .

        .

    }               /* ends switch (message) */


 Cursor Reference

The following functions and messages are associated with cursors.


 Cursor Functions

Following are the functions used with cursors.

ClipCursor
CopyCursor
CreateCursor
DestroyCursor
GetClipCursor
GetCursor
GetCursorPos
LoadCursor
LoadCursorFromFile
SetCursor
SetCursorPos
SetSystemCursor
ShowCursor


 Cursor Messages

The following message is used with cursors.

WM_SETCURSOR


 Extended Menus

A menu is one or more lists of application commands. Each command, which is represented by a text string or bitmap, is called a menu item. By using the mouse or the keyboard to choose a menu item, the user directs the application to perform the command associated with the menu item. When the user chooses a menu item, Microsoft® Windows® sends the application a command message that indicates which menu item the user chose.

This Windows 95 overview describes the extended menu functions and explains how to use them in a Win32-based application.


 Menus and Extended Menus Platform Differences

The overviews for menus and extended menus in Windows 95 and Windows NT are substantially different. To accommodate these differences, the Windows 95 overview is first presented in its entirety, followed by the Windows NT version.


 About Extended Menus

Windows 95 Overview
For more information, see the Windows NT overview About Menus.

This overview describes menus and explains how to use them in applications designed for the Microsoft Win32® application programming interface (API).

The extended menu functions described in this section supercede the menu functions described in Menus (Windows NT). However, the two sets of functions can be used interchangeably insofar as their capabilities overlap.


 Menu Bars and Pop-up Menus

Windows 95 Overview
For more information, see the Windows NT overview Menu Bars and Pop-up Menus.

The menus in an application written for Windows are arranged hierarchically. A menu bar (sometimes called a top-level menu) resides at the uppermost level of the hierarchy; the lower levels consist of pop-up menus (also known as submenus).

The items in a menu bar represent the main categories of commands provided by an application. Selecting an item from the menu bar typically activates a pop-up menu whose items correspond to the commands in a given category. For example, a menu bar might contain a File menu item that, when the user selects it, activates a pop-up menu with such menu items as New, Open, Save, and so on.

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, Windows positions the menu bar just below it. A menu bar is always visible. In contrast, a pop-up menu is not visible until the user selects a menu item that activates it. When the menu is displayed, it is attached to the title bar.

Every menu must have an owner window. Windows sends messages to a menu's owner window when the user selects the menu or chooses a command from the menu. These messages are described in Menu Messages.


 Floating Pop-up Menus

Windows 95 Overview
For more information, see the Windows NT overview Floating Pop-up Menus.

Windows provides a special type of pop-up menu called a floating pop-up menu. A floating pop-up menu is not attached to the menu bar; it can appear anywhere on the screen. An application typically associates a floating pop-up menu with a portion of a window, such as the client area, or with a specific object, such as an icon. For this reason, floating pop-up menus are also called context menus.

A floating pop-up menu remains hidden until the user activates it, typically by clicking the right mouse button. The menu is usually displayed at the position of the caret or mouse cursor.


 The System Menu

Windows 95 Overview
For more information, see the Windows NT overview The System Menu.

A System menu (also known as the Control menu) is a pop-up menu defined and managed almost exclusively by the operating system. It is represented by a small box containing a horizontal line that is displayed at the left end of the title bar. When the user clicks the box, Windows displays the System menu. Windows also displays the System menu when the user clicks the icon of a minimized application.

A System menu provides a standard set of menu items that the user can choose to change a window's size or position, close the application, or activate the Windows Task List. Items in a System 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 System menu. It is uncommon for an overlapped or pop-up window not to include a System menu.

When the user chooses a command from a System menu, Windows sends a WM_SYSCOMMAND message to the menu's owner window. In most applications, the window procedure does not process messages from a System menu. Instead, it simply passes the messages to the DefWindowProc function for system-default processing of the message. If a command is added to a System menu, the window procedure must process the command.


 Help Identifier

Associated with each menu bar and pop-up menu is a 32-bit help identifier. If the user presses the F1 key while the menu is active, this value is sent to the owner window as part of a WM_HELP message. For more information about help identifiers, see Help.


 Menu Handles

Windows 95 Overview
For more information, see the Windows NT overview 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 Windows menu functions. You receive the handle of a menu bar when you create the menu or load a menu resource. For more information about creating and loading menus, see Menu Creation.

To retrieve the handle of a menu that has been created or loaded, use the GetMenu or GetSubMenu function. GetMenu returns the handle of the menu bar assigned to the specified window. GetSubMenu returns the handle of the pop-up menu associated with a pop-up item (the GetMenuItemInfo function can also be used for this purpose.) The GetSystemMenu function retrieves the handle of a window's System menu.


 Menu Items

Windows 95 Overview
For more information, see the Windows NT overview Menu Items.

Each menu contains one or more menu items. By choosing a menu item, a user can carry out a command or open a pop-up menu. The following sections introduce the various types of menu items and the ways in which an application can control a menu item's appearance and functionality.


 Command Items and Pop-up Items

Choosing a menu item may either perform a command or open a pop-up menu. Menu items that perform commands are called command items; those that open pop-up menus are called pop-up items.

When the user chooses a command item, Windows sends a command message to the window that owns the menu. If the command item is on the System menu, Windows sends the WM_SYSCOMMAND message. Otherwise, it sends the WM_COMMAND message.

Associated with each pop-up item is the handle of a corresponding pop-up menu. When the user selects a pop-up item, Windows opens the pop-up menu. No command message is sent to the owner window. However, Windows sends a WM_INITMENUPOPUP message to the owner window before displaying the pop-up menu. You can get the handle of the pop-up menu associated with a pop-up item by using the GetSubMenu or GetMenuItemInfo function (the handle is NULL for command items).

A menu bar typically contains pop-up items, but it may also contain command items. A pop-up menu typically contains command items, but it may also contain pop-up items. By adding pop-up items to a pop-up menu, you can nest pop-up menus to an arbitrary depth. If you include a pop-up item in a pop-up menu, Windows automatically displays a small arrow to the right of the menu item text as a visual cue to the user that a pop-up menu has been nested.


 Menu Item Identifier

Windows 95 Overview
For more information, see the Windows NT overview, Menu-Item Identifier.

Associated with each menu item is a 16-bit integer called an identifier. An application should assign a unique identifier to each menu item. When a command item is chosen, the item's identifier is sent to the owner window as part of a WM_COMMAND or WM_SYSCOMMAND message. You can also use an identifier to specify a menu item when you call many menu functions.

Pop-up items have identifiers just as command items do. However, Windows does not send a command message when a pop-up item is selected from a menu. Instead, Windows activates the pop-up menu 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

Windows 95 Overview
For more information, see the Windows NT overview, Menu-Item Position.

In addition to having a unique identifier, each menu item in a menu bar or pop-up menu has a unique position value. The leftmost item in a menu bar, or the topmost item in a pop-up menu, has position zero. The position value is incremented for subsequent menu items. Windows 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 a pop-up 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.


 Default Menu Items

A pop-up menu may contain one default menu item. When the user opens a pop-up by double-clicking, Windows sends a command message to the menu's owner window and closes the menu as if the default item had been chosen. If there is no default command item, the pop-up menu remains open. To retrieve and set the default item for a pop-up menu, use the GetMenuDefaultItem and SetMenuDefaultItem functions.


 Checked and Unchecked Menu Items

Windows 95 Overview
For more information, see the Windows NT overview Checked and Unchecked Menu Items.

A menu item can be either checked or unchecked. Windows displays a bitmap next to checked menu items to indicate their checked state. Windows does not display a bitmap next to unchecked items, unless an application-defined "unchecked" bitmap is specified. Only menu items in a pop-up menu can be checked; items in a menu bar cannot be checked.

Applications typically check or uncheck a menu item to indicate whether an option is in effect. For example, suppose an application has a toolbar that the user can show or hide using a Toolbar command. When the toolbar is hidden, the Toolbar menu item is unchecked. When the user chooses the command, the application checks the menu item and shows the toolbar. To retrieve and set the check state of a menu item, use the GetMenuItemInfo and SetMenuItemInfo functions.

Sometimes, a group of menu items corresponds to a set of mutually exclusive options. In this case, you can indicate the selected option by using a checked radio menu item (analogous to a radio button control). Checked radio items are displayed with a bullet bitmap instead of a check-mark bitmap. To check a menu item and make it a radio item, use the CheckMenuRadioItem function.

By default, Windows displays a check-mark or bullet bitmap next to checked menu items and no bitmap next to unchecked menu items. However, you can use the SetMenuItemBitmaps function to associate application-defined "checked" and "unchecked" bitmaps with a menu item. Windows then uses the specified bitmaps to indicate the menu item's checked or unchecked state.

Application-defined bitmaps associated with a menu item must be the same size as the default check-mark bitmap, the dimensions of which may vary depending on screen resolution. To retrieve the correct dimensions, use the GetMenuCheckMarkDimensions 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.


 Enabled, Disabled, and Grayed Menu Items

Windows 95 Overview
For more information, see the Windows NT overview Enabled, Disabled, and Grayed Menu Items.

A menu item can be enabled, disabled, or grayed. By default, a menu item is enabled. When the user chooses an enabled menu item, Windows sends a command message to the owner window or displays the corresponding pop-up menu, depending on whether the menu item is a command or a pop-up item.

When menu items are not available to the user, they should be disabled or grayed. Disabled and grayed menu items cannot be chosen. Typically, applications gray an unavailable menu item to provide a visual clue to the user that a command is not available; a disabled menu item does not provide this visual clue. A disabled item can serve as a heading for a group of related menu items. (For example, a disabled Save menu item can serve as a heading for a series of enabled command items, such as Save File, Save All, and Save As.) A grayed item can be used when an action is not appropriate. (For example, the Print command in the File menu can be grayed when the system does not have a printer installed.)

The EnableMenuItem function enables, disables, or grays a menu item. To determine whether a menu item is enabled, disabled, or grayed, use the GetMenuItemInfo function.


 Highlighted Menu Items

Windows 95 Overview
For more information, see the Windows NT overview Highlighted Menu Items.

Windows automatically highlights menu items as the user selects them. However, highlighting can be explicitly added or removed from a menu item on the menu bar by using the HiliteMenuItem function. This function has no effect on menu items in pop-up menus. When HiliteMenuItem is used to highlight a menu item, though, the menu item only appears to be selected. If the user presses the ENTER key, the highlighted item is not chosen.


 String, Bitmap, and Owner-Drawn Menu Items

An application can display a menu item using a string or a bitmap. In addition, an application can completely control the appearance of a menu item by using an owner-drawn item. The application is responsible for drawing owner-drawn items in any of their possible states (highlighted, checked, and so on).

For example, an application that has a Font menu might draw each menu item using the corresponding font (that is, the item for roman would be drawn using a roman font, the item for italic in an italic font, and so on).


 Menu Item Separators and Line Breaks

Windows 95 Overview
For more information, see the Windows NT overview, Menu-Item Separators and Line Breaks.

Windows provides a special type of menu item, called a separator, that appears as a horizontal line. A separator can be used in a pop-up menu 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 items than will fit on one line, Windows automatically breaks the line 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. Windows places that item and all subsequent item on a new line.

When a pop-up menu contains more items than will fit in one column, Windows automatically breaks the menu into two or more columns. You can cause a column break to occur at a specific item in a pop-up menu by assigning the MFT_MENUBREAK type flag to the item. Windows 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.


 Keyboard Access to Menus

Windows 95 Overview
For more information, see the Windows NT overview Keyboard Access to Menus.

Windows provides a standard keyboard interface for menus. You can enhance this interface by providing mnemonics and accelerator keys for your menu items. The following sections describe the standard keyboard interface, mnemonics, and accelerator keys.


 Standard Keyboard Interface

Windows 95 Overview
For more information, see the Windows NT overview Standard Keyboard Interface.

Windows is designed to work with or without a mouse or other pointing device. Because Windows 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 a menu item is selected 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 mnemonic. If the selected item invokes a pop-up 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 System menu.
ENTER	Activates a pop-up menu and selects the first menu item if an item has a pop-up 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	Works like the RIGHT ARROW key, except in the opposite direction. In pop-up menus, this keystroke backs up one column; when the currently selected item is in the far-left column, the previous pop-up menu is selected.
RIGHT ARROW	Cycles to the next top-level menu item. Top-level menu items include menu bar items and the System menu. If the selected item is in a pop-up menu, the next column in the pop-up menu is selected or the next top-level menu item is selected.
UP or DOWN ARROWS	Activates a pop-up menu when pressed in a top-level menu. When pressed in a pop-up menu, either keystroke selects the next or previous item.


 Menu Mnemonics

Windows 95 Overview
For more information, see the Windows NT overview Menu Mnemonics.

The standard keyboard interface for menus can be enhanced by adding mnemonics to menu items. A mnemonic 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 menu bar is active when the user presses and releases the ALT key and the first item on the menu bar is highlighted. A pop-up menu is active when it is displayed.

A mnemonic keystroke for a menu item is created by preceding any character in the item's text string with an ampersand. For example, the text string "&Move" causes Windows to underline the letter "M".


 Menu Keyboard Accelerators

Windows 95 Overview
For more information, see the Windows NT overview Menu Keyboard Accelerators.

In addition to having a mnemonic, a menu item can have a keyboard accelerator associated with it. A keyboard accelerator is different from a mnemonic, because the menu does not have to be active for the accelerator key to work. Also, a mnemonic is always associated with a menu item, while a keyboard accelerator is usually (but does not have to be) associated with a menu item.

Text that identifies the keyboard accelerator is added to the menu item text string. The accelerator 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 item with the ALT+F4 key combination as its keyboard accelerator and with the letter "C" as its mnemonic. For more information about accelerators, see Keyboard Accelerators.


 Menu Creation

Windows 95 Overview
For more information, see the Windows NT overview Menu Creation.

You can create a menu using either a menu template or using 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.


 Menu Template Resources

Windows 95 Overview
For more information, see the Windows NT overview, 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 pop-up menus. For information about creating a menu template resource, see the documentation included with your development tools.

Once you have created a menu template resource and have added it to your application's executable (.EXE) file, you can use the LoadMenu function to load the resource into memory. This function returns the handle of the menu, which you can then assign to a window by using the SetMenu function.

Implementing menus as resources makes an application easier to localize for use in multiple countries. Only the resource-definition file needs to be translated for each language, not the application's source code.


 Menu Template in Memory

Windows 95 Overview
For more information, see the Windows NT overview 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.

There are two types of menu templates. A standard menu template consists of a MENUITEMTEMPLATEHEADER structure followed by one or more MENUITEMTEMPLATE structures. In most cases, an extended menu template is used; it consists of a MENUEX_TEMPLATE_HEADER structure followed by one or more MENUEX_TEMPLATE_ITEM structures.


 Menu Creation Functions

Windows 95 Overview
For more information, see the Windows NT overview, 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 pop-up menu. To add items to a menu, use the InsertMenuItem function.


 Menu Display

Windows 95 Overview
For more information, see the Windows NT overview Menu Display.

After a menu has been loaded or created, it must be assigned to a window before Windows can display it. This assignment can be done by defining a class menu. For more information about class menus, see Class Menus. You can also assign a menu to a window by specifying the handle of the menu as the hmenu parameter of the CreateWindowEx function or by calling the SetMenu function.

To display a floating pop-up menu, use the TrackPopupMenu or TrackPopupMenuEx function. Floating pop-up menus, also called context menus, are typically displayed when the WM_CONTEXTMENU message is processed.


 Class Menus

Windows 95 Overview
For more information, see the Windows NT overview 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 that you do not have 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 about window classes, see Window Classes.


 Menu Destruction

Windows 95 Overview
For more information, see the Windows NT overview Menu Destruction.

If a menu is assigned to a window and that window is destroyed, Windows automatically destroys the menu, freeing the menu's handle and the memory occupied by the menu. Windows 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.


 Menu Messages

Windows 95 Overview
For more information, see the Windows NT overview Menu Messages Overview.

Windows reports menu-related activity by sending messages to the window procedure of the window that owns the menu. Windows sends a series of messages when the user selects items on the menu bar or clicks the right mouse button to display a floating pop-up 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 using the keyboard (SC_KEYMENU) or mouse (SC_MOUSEMENU). For more information about the keyboard interface for menus, see Keyboard Access to Menus.

Next, before displaying any pop-up menus, Windows sends the WM_INITMENU message to the window procedure so that an application can modify the menus before the user sees them. Windows sends the WM_INITMENU message only once per menu activation.

When the user selects a pop-up item, Windows sends the owner window the WM_INITMENUPOPUP message before displaying the pop-up menu. This message gives the application an opportunity to modify the pop-up menu before it is displayed.

Each time the user moves the highlighting from one item to another, Windows 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, Windows sends a WM_COMMAND message to the window procedure. The low-order word of the WM_COMMAND message's wParam parameter contains the identifier of the chosen item. The window procedure should examine the identifier and process the message accordingly.

Not all menus are accessed through a window's menu bar. Many applications display floating pop-up menus when the user clicks the right mouse button at a specific location. Such applications should process the WM_CONTEXTMENU message and display a floating pop-up menu, if appropriate. If an application does not display a floating pop-up menu, it should pass the WM_CONTEXTMENU message to the DefWindowProc function for default processing.


 Menu Modifications

Windows 95 Overview
For more information, see the Windows NT overview Menu Modifications.

A number of functions enable the developer to change a menu after it has been loaded or created. These changes may include adding or removing menu items and modifying existing menu items.

To add a menu item, use the InsertMenuItem function. You can use the SetMenuItemInfo function to change the attributes of an existing menu item. The lpmii parameter points to a MENUITEMINFO structure, which contains the new attributes and specifies which attributes to change. A menu item's attributes include its type, state, identifier, pop-up menu, bitmaps, item data, and text.

To retrieve information about a menu item, use the GetMenuItemInfo function. The lpmii parameter points to a MENUITEMINFO structure, which specifies the attributes to retrieve and receives their current values.

The DeleteMenu or RemoveMenu function is used to delete a menu item from a menu. If the item being deleted is a pop-up item, DeleteMenu deletes the associated pop-up menu, discarding the menu handle and freeing the memory used by the pop-up menu. RemoveMenu deletes a menu item, but if the item activates a pop-up menu, the function does not destroy the pop-up menu or its handle, allowing the menu to be reused.

After a menu bar has been modified, the DrawMenuBar function must be called to redraw the menu bar. Otherwise, the modifications will not appear until Windows redraws the owner window.


 Superseded Functions

The following menu functions have been superseded. The new function should be used instead of the corresponding superseded function.

Superseded function	New function
AppendMenu	InsertMenuItem
ChangeMenu	SetMenuItemInfo
CheckMenuItem	SetMenuItemInfo
GetMenuState	GetMenuItemInfo
InsertMenu	InsertMenuItem
ModifyMenu	SetMenuItemInfo


 Using Extended Menus

•	Using a menu template resource.

•	Creating a floating pop-up menu.

•	Using menu item bitmaps.

•	Creating owner-drawn menu items.

•	Using custom check mark bitmaps.


 Using a Menu Template Resource

Windows 95 Overview
For more information, see the Windows NT overview, 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 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.


 Loading a Menu Template Resource

Windows 95 Overview
For more information, see the Windows NT overview, Loading a Menu-Template Resource.

You can load a menu template resource by calling the LoadMenu function, specifying the handle of the module that contains the resource and the menu template's identifier. LoadMenu 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.

You can assign a menu to a window by using the SetMenu function or by specifying the menu's handle in the hmenu parameter of the CreateWindowEx function when creating a window. Another way that you can assign a menu to a window is to specify a menu template when you register a window class; the template identifies the menu as the class menu for the given window class. Whenever you create a window of the given class, Windows automatically assigns the given menu to the window.

You can create a class menu by including the identifier of the menu template resource as the lpszMenuName member of a WNDCLASS structure and then passing the address of the structure to the RegisterClass function.


 Creating a Class Menu

Windows 95 Overview
For more information, see the Windows NT overview 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.

HINSTANCE hinst;

int APIENTRY WinMain(hinstance, hPrevInstance, lpCmdLine, nCmdShow)

HINSTANCE hinstance;

HINSTANCE hPrevInstance;

LPSTR lpCmdLine;

int nCmdShow;

{

    MSG msg;        // message

    WNDCLASS wc;    // windowclass data

    HWND hwnd;      // handle of 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 =  "MyMenuResource";

    wc.lpszClassName = "MainWClass";

    if (!RegisterClass(&wc))

        return FALSE;

    hinst = hinstance;

    // Create the main window. Set the hmenu parameter to NULL so

    // that Windows uses the class menu for the window.

    hwnd = CreateWindow("MainWClass", "Sample Application",

        WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT,

        CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hinstance,

        NULL);

    if (hwnd == NULL)

        return FALSE;

    // Make the window visible and send a WM_PAINT message to the

    // window procedure.

    ShowWindow(hwnd, nCmdShow);

    UpdateWindow(hwnd);

    // Start the main message loop.

    while (GetMessage(&msg, NULL, 0, 0)) {

        TranslateMessage(&msg);

        DispatchMessage(&msg);

    }

    return msg.wParam;

        UNREFERENCED_PARAMETER(hPrevInstance);

}

LRESULT APIENTRY MainWndProc(hwnd, uMsg, wParam, lParam)

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 Floating Pop-up Menu

Windows 95 Overview
For more information, see the Windows NT overview Creating a Floating Pop-up Menu.

To use a floating pop-up menu in an application, pass the handle of a pop-up menu to the TrackPopupMenu or TrackPopupMenuEx function. An application typically calls these functions in a window procedure when processing the WM_CONTEXTMENU message. For more information about this message, see Processing the WM_CONTEXTMENU Message.

In addition to the pop-up menu handle, TrackPopupMenu requires that you specify the handle of the owner window, the position of the floating pop-up menu (in screen coordinates), and the mouse button that the user can use to choose an item. TrackPopupMenuEx requires the same parameters as TrackPopupMenu, but TrackPopupMenuEx also enables you to specify a portion of the screen that the menu should not obscure.

You can specify the position of a 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 menu relative to the x- and y-coordinates.

You should permit the user to choose an item from a pop-up 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 floating pop-up menu appropriate to a specific portion of its display. If the application does not display a 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. 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, LOWORD(lParam), HIWORD(lParam)))

        return DefWindowProc(hwnd, uMsg, wParam, lParam);

    break;

The following application-defined OnContextMenu function displays a floating pop-up 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 floating pop-up menu, this example calls an application-defined function called DisplayContextMenu. For a description of this function, see Displaying a Floating Pop-up 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 floating

    // pop-up menu.

    if (PtInRect(&rc, pt)) {

        ClientToScreen(hwnd, &pt);

        DisplayContextMenu(hwnd, pt);

        return TRUE;

    }

    // Return FALSE if no menu is displayed.

    return FALSE;

}


 Displaying a Floating Pop-up Menu

The function shown in the following example displays a floating pop-up menu. This function might be called when an application's window procedure receives a WM_CONTEXTMENU message.

The application includes a menu resource identified by the string "PopupMenu". The top-level menu, or menu bar, simply contains a pop-up menu item. The application uses the TrackPopupMenu function to display the pop-up menu associated with this menu item. (The top-level menu itself is not displayed because TrackPopupMenu requires the handle of a pop-up menu.)

VOID APIENTRY DisplayContextMenu(HWND hwnd, POINT pt)

{

    HMENU hmenu;            // top-level menu

    HMENU hmenuTrackPopup;  // pop-up menu

    // Load the menu resource.

    if ((hmenu = LoadMenu(hinst, "PopupMenu")) == NULL)

        return;

    // TrackPopupMenu cannot display the top-level menu, so get

    // the handle of the first pop-up menu.

    hmenuTrackPopup = GetSubMenu(hmenu, 0);

    // Display the floating pop-up menu. Track the right mouse

    // button on the assumption that this function is called

    // during WM_CONTEXTMENU processing.

    TrackPopupMenu(hmenuTrackPopup,

            TPM_LEFTALIGN | TPM_RIGHTBUTTON,

            pt.x, pt.y, 0, hwnd, NULL);

    // Destroy the menu.

    DestroyMenu(hmenu);

}


 Using Menu Item Bitmaps

Windows 95 Overview
For more information, see the Windows NT overview, Using Menu-Item Bitmaps.

Windows can use a bitmap instead of a text string to display a menu item. To use a bitmap, you must set the MF_BITMAP flag for the menu item and specify the handle of the bitmap that Windows should display for the menu item. This section describes how to set the MF_BITMAP flag and retrieve the handle of a bitmap.


 Setting the MFT_BITMAP Type Flag

The MFT_BITMAP type flag tells Windows to use a bitmap rather than a text string to display a menu item. A menu item's MFT_BITMAP flag must be set at run time; it cannot be set in a menu-template resource.

You can use the SetMenuItemInfo or InsertMenuItem function to set the MFT_BITMAP type flag. To change a menu item from a text item to a bitmap item, use SetMenuItemInfo. To add a new bitmap item to a menu, use the InsertMenuItem function.


 Creating the Bitmap

Windows 95 Overview
For more information, see the Windows NT overview Creating the Bitmap.

When you set the MFT_BITMAP type flag for a menu item, you must also specify the handle of the bitmap that Windows 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 about bitmaps, see Bitmaps.


 Example of Menu Item Bitmaps

The example in this section creates two pop-up menus, each containing several bitmap menu items. For each pop-up menu, the application adds a corresponding pop-up item to the main window's menu bar.

The first pop-up 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" pop-up item on the menu bar.

The second pop-up 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" pop-up item 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 section.

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 pop-up

             // menus containing the bitmap menu items. The function

             // also adds a pop-up item to the window's menu bar.

            AddBitmapMenu(

                    hwnd,      // menu bar's owner window

                    "&Chart",  // text of pop-up item on menu bar

                    IDM_PIE,   // ID of first item on pop-up menu

                    aHbmChart, // array of bitmap handles

                    C_CHARTS   // number of items on pop-up 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 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 pop-up menu and adds the specified number of bitmap menu items to it. Then it adds a corresponding pop-up item to the specified window's menu bar.

VOID WINAPI AddBitmapMenu(

        HWND hwnd,          // window that owned the menu bar

        LPSTR lpszText,     // text of pop-up item 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 pop-up menu.

    for (i = 0; i < cItems; i++) {

        mii.fMask = MIIM_ID | MIIM_TYPE | MIIM_DATA;

        mii.fType = MFT_BITMAP;

        mii.wID = uID + i;

        mii.dwTypeData = (LPSTR) (paHbm[i]);

        InsertMenuItem(hmenuPopup, i, TRUE, &mii);

    }

    // Add a pop-up item to the menu bar.

    mii.fMask = MIIM_TYPE | MIIM_DATA | MIIM_SUBMENU;

    mii.fType = MFT_STRING;

    mii.hSubMenu = hmenuPopup;

    mii.dwTypeData = lpszText;

    InsertMenuItem(hmenuBar,

        GetMenuItemCount(hmenuBar), TRUE, &mii);

}


 Creating Owner-Drawn Menu Items

If you need complete control over the appearance of a menu item, you can use an owner-drawn menu item in your application. This section describes the steps involved in creating and using an owner-drawn menu item.


 Setting the MFT_OWNERDRAW 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, so it has the MFT_OWNERDRAW type flag.

You can use the InsertMenuItem or SetMenuItemInfo function to specify an owner-drawn menu item. To place a new item on a menu, moving the other items down, use InsertMenuItem. To change the content of a menu, use SetMenuItemInfo.

When calling these two functions, you must specify the address of a MENUITEMINFO structure, giving the properties of the new menu item or the properties you want to change for an existing menu item. To make an item an owner-drawn item, specify the MIIM_TYPE value for the fMask member and the MFT_OWNERDRAW value for the fType member.

By setting the appropriate members of the MENUITEMINFO structure, you can associate an application-defined value, which is called item data, with each menu item. To do so, specify the MIIM_DATA value for the fMask member and the application-defined value for the dwItemData member.

You can use item data with any type of menu item, but it is particularly useful for owner-drawn items. For example, suppose a structure contains information used to draw a menu item. An application might use the item data for a menu item to store a pointer to the structure. The item data is sent to the menu's owner window with the WM_MEASUREITEM and WM_DRAWITEM messages. To retrieve the item data for a menu at any time, use the GetMenuItemInfo function.


 Owner-Drawn Menus and the WM_MEASUREITEM Message

Before Windows 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. Windows 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), Windows sends the WM_DRAWITEM message to the window procedure of the menu's owner window. This message contains a pointer to a DRAWITEMSTRUCT structure, which contains information about the item, including the item data that an application may have assigned to it. In addition, DRAWITEMSTRUCT contains flags that indicate the state of the item (such as whether it is grayed or checked) as well as a bounding rectangle and a DC that the application uses to draw the item.

An application must do the following while processing the WM_DRAWITEM message:

1.	Determine the type of drawing that is necessary. To do so, check the itemAction member of the DRAWITEMSTRUCT structure.

2.	Draw the menu item appropriately, using the bounding rectangle and DC obtained from the DRAWITEMSTRUCT structure. The application must draw only within the bounding rectangle. For performance reasons, Windows does not clip portions of the image that are drawn outside the rectangle.

3.	Restore all GDI objects selected for the menu item's DC.

If the user selects the menu item, Windows 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.


 Example of Owner-Drawn Menu Items

The example in this section uses owner-drawn menu items in a pop-up 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 pop-up item on the menu bar opens the pop-up menu.

The menu bar and pop-up menu are defined initially by an extended menu-template resource. Because a menu template cannot specify owner-drawn items, the pop-up menu initially contains four text menu items with the following strings: "Regular," "Bold," "Italic," and "Underline." The application's window procedure changes these to owner-drawn items when it processes the WM_CREATE message. When it receives the WM_CREATE message, the window procedure calls the application-defined OnCreate function, which performs the following steps for each menu item:

1.	Allocates an application-defined MYITEM structure.

2.	Gets the text of the menu item and saves it in the application-defined MYITEM structure.

3.	Creates the font used to display the menu item and saves its handle in the application-defined MYITEM structure.

4.	Changes the menu item type to MFT_OWNERDRAW and saves a pointer to the application-defined MYITEM structure as item data.

Because a pointer to each application-defined MYITEM structure is saved as item data, it is passed to the window procedure in conjunction with the WM_MEASUREITEM and WM_DRAWITEM messages for the corresponding menu item. The pointer is contained in the itemData member of both the MEASUREITEMSTRUCT and DRAWITEMSTRUCT structures.

A WM_MEASUREITEM message is sent for each owner-drawn menu item the first time that it is displayed. The application processes this message by selecting the font for the menu item into a DC 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 GetTextExtentPoint function.

The window procedure processes the WM_DRAWITEM message by displaying the menu item text in the appropriate font. The font and menu item text are both specified by the menu item's MYITEM structure. The application selects text and background colors appropriate to the menu item's state.

The window procedure processes the WM_DESTROY message to destroy fonts and free memory. The application deletes the font and frees the application-defined MYITEM structure for each menu item.

Following are the relevant portions of the application's header file.

// Menu item identifiers for the Character menu

#define IDM_CHARACTER 10

#define IDM_REGULAR   11

#define IDM_BOLD      12

#define IDM_ITALIC    13

#define IDM_UNDERLINE 14

// Structure associated with menu items

typedef struct tagMYITEM {

    HFONT hfont;

    int   cchItemText;

    char  szItemText[1];

} MYITEM;

#define CCH_MAXITEMTEXT 256

Following are the relevant portions of the application's window procedure and its associated functions.

LRESULT CALLBACK MainWindowProc(

        HWND hwnd,

        UINT uMsg,

        WPARAM wParam,

        LPARAM lParam

        )

{

    switch (uMsg) {

        case WM_CREATE:

            if (!OnCreate(hwnd))

                return -1;

            break;

        case WM_DESTROY:

            OnDestroy(hwnd);

            PostQuitMessage(0);

            break;

        case WM_MEASUREITEM:

            OnMeasureItem(hwnd, (LPMEASUREITEMSTRUCT) lParam);

            return TRUE;

        case WM_DRAWITEM:

            OnDrawItem(hwnd, (LPDRAWITEMSTRUCT) lParam);

            return TRUE;

        .

        . // Additional message processing goes here.

        .

        default:

            return DefWindowProc(hwnd, uMsg, wParam, lParam);

    }

    return 0;

}

BOOL WINAPI OnCreate(HWND hwnd)

{

    HMENU hmenuBar = GetMenu(hwnd);

    HMENU hmenuPopup;

    MENUITEMINFO mii;

    UINT uID;

    MYITEM *pMyItem;

    // Get the handle of the pop-up menu.

    mii.fMask = MIIM_SUBMENU;     // information to get

    GetMenuItemInfo(hmenuBar, IDM_CHARACTER, FALSE, &mii);

    hmenuPopup = mii.hSubMenu;

    // Modify each menu item. Assume that the IDs IDM_REGULAR

    // through IDM_UNDERLINE are consecutive numbers.

    for (uID = IDM_REGULAR; uID <= IDM_UNDERLINE; uID++) {

         // Allocate an item structure, leaving space for a

         // string of up to CCH_MAXITEMTEXT characters.

        pMyItem = (MYITEM *) LocalAlloc(LMEM_FIXED,

                sizeof(MYITEM) + CCH_MAXITEMTEXT);

        // Save the item text in the item structure.

        mii.fMask = MIIM_TYPE;

        mii.dwTypeData = pMyItem->szItemText;

        mii.cch = CCH_MAXITEMTEXT;

        GetMenuItemInfo(hmenuPopup, uID, FALSE, &mii);

        pMyItem->cchItemText = mii.cch;

        // Reallocate the structure to the minimum required size.

        pMyItem = (MYITEM *) LocalReAlloc(pMyItem,

                sizeof(MYITEM) + mii.cch, LMEM_MOVEABLE);

        // Create the font used to draw the item.

        pMyItem->hfont = CreateMenuItemFont(uID);

        // Change the item to an owner-drawn item, and save

        // the address of the item structure as item data.

        mii.fMask = MIIM_TYPE | MIIM_DATA;

        mii.fType = MFT_OWNERDRAW;

        mii.dwItemData = (DWORD) pMyItem;

        SetMenuItemInfo(hmenuPopup, uID, FALSE, &mii);

    }

    return TRUE;

}

HFONT CreateMenuItemFont(UINT uID)

{

    LOGFONT lf;

    ZeroMemory(&lf, sizeof(lf));

    lf.lfHeight = 20;

    lstrcpy(lf.lfFaceName, "Times New Roman");

    switch (uID) {

        case IDM_BOLD:

            lf.lfWeight = FW_HEAVY;

            break;

        case IDM_ITALIC:

            lf.lfItalic = TRUE;

            break;

        case IDM_UNDERLINE:

            lf.lfUnderline = TRUE;

            break;

    }

    return CreateFontIndirect(&lf);

}

VOID WINAPI OnDestroy(HWND hwnd)

{

    HMENU hmenuBar = GetMenu(hwnd);

    HMENU hmenuPopup;

    MENUITEMINFO mii;

    UINT uID;

    MYITEM *pMyItem;

    // Get the handle of the pop-up 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;

    GetTextExtentPoint(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 += LOWORD(GetMenuCheckMarkDimensions());

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

Windows 95 Overview
For more information, see the Windows NT overview Using Custom Check Mark Bitmaps.

Windows provides a default check mark bitmap for displaying next to a menu item that is checked. You can customize an individual menu item by providing a pair of bitmaps to replace the default check mark bitmap. Windows displays one bitmap when the item is checked and the other when it is unchecked. This section describes the steps involved in creating and using custom check mark bitmaps.


 Creating Custom Check Mark Bitmaps

Windows 95 Overview
For more information, see the Windows NT overview 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 GetMenuCheckMarkDimensions 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. For the typical method, you follow these steps:

1.	Use the CreateCompatibleDC function to create a DC compatible with the DC 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 DC.

4.	Use GDI drawing functions, such as Ellipse and LineTo, to draw an image into the bitmap.


 Associating Bitmaps with a Menu Item

Windows 95 Overview
For more information, see the Windows NT overview 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 hbmUnchecked parameter identifies the unchecked bitmap, and the hbmChecked parameter identifies the checked bitmap. If you want to remove one or both check marks from a menu item, you can set the hbmUnchecked or hbmChecked parameter, or both, to NULL.


 Setting the Check Mark Attribute

Windows 95 Overview Setting the Check Mark Attribute
For more information, see the Windows NT overview Setting the Check Mark Attribute.

The CheckMenuItem function sets a menu item's check mark attribute to either checked or unchecked. You can specify the MF_CHECKED value to set the check mark attribute to checked and the MF_UNCHECKED value to set it to unchecked. You can also set the check state of a menu item by using the SetMenuItemInfo function.

Sometimes a group of menu items represents a set of mutually exclusive options. By using the CheckMenuRadioItem function, you can check one menu item while simultaneously removing the check mark from all other menu items in the group.


 Example of Using Custom Check Mark Bitmaps

The example in this section assigns custom check mark bitmaps to menu items in two pop-up menus. The menu items in the first pop-up menu specify character attributes: bold, italic, and underline. Each menu item can be either checked or unchecked. For these menu items, the example uses check mark bitmaps that resemble the checked and unchecked states of a check box control.

The menu items in the second pop-up menu specify paragraph alignment settings: left, centered, and right. Only one of these menu items is checked at any given time. For these menu items, the example uses check mark bitmaps that resemble the checked and unchecked states of a radio button control.

The window procedure processes the WM_CREATE message by calling the application-defined OnCreate function. The application-defined OnCreate function creates the four check mark bitmaps and then assigns them to their appropriate menu items by using the SetMenuItemBitmaps function.

To create each bitmap, the application-defined OnCreate function calls the application-defined CreateMenuBitmaps function, specifying a pointer to a bitmap-specific drawing function. The application-defined CreateMenuBitmaps function creates a monochrome bitmap of the required size, selects it into a memory DC, and erases the background. Then it calls the specified drawing function to fill in the foreground.

The four application-defined drawing functions are DrawCheck, DrawUncheck, DrawRadioCheck, and DrawRadioUncheck. They draw a rectangle with an X, an empty rectangle, an ellipse containing a smaller filled ellipse, and an empty ellipse, respectively.

The window procedure processes the WM_DESTROY message by deleting the check mark bitmaps. It retrieves each bitmap handle by using the GetMenuItemInfo function and then passes the handle to the DeleteObject function.

When the user chooses a menu item, a WM_COMMAND message is sent to the owner window. For menu items on the Character menu, the window procedure calls the application-defined CheckCharacterItem function. For items on the Paragraph menu, the window procedure calls the application-defined CheckParagraphItem function.

Each item on the Character menu can be checked and unchecked independently. Therefore, the application-defined CheckCharacterItem function simply toggles the specified menu item's check state. First, the function calls the GetMenuItemInfo function to get the current menu item state. Then it toggles 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, the application-defined CheckParagraphItem function checks the specified menu item and removes the check mark from all other items on the menu. To do so, it calls the CheckMenuRadioItem function.

Following are the relevant portions of the application's header file.

// Menu item identifiers for the Character menu

#define IDM_CHARACTER 10

#define IDM_BOLD      11

#define IDM_ITALIC    12

#define IDM_UNDERLINE 13

// Menu item identifiers for the Paragraph menu

#define IDM_PARAGRAPH 20

#define IDM_LEFT      21

#define IDM_CENTER    22

#define IDM_RIGHT     23

// Function-pointer type for drawing functions

typedef VOID (WINAPI * DRAWFUNC)(HDC hdc, SIZE size);

Following are the relevant portions of the application's window procedure and related functions.

LRESULT CALLBACK MainWindowProc(

        HWND hwnd,

        UINT uMsg,

        WPARAM wParam,

        LPARAM lParam

        )

{

    switch (uMsg) {

        case WM_CREATE:

            if (!OnCreate(hwnd))

                return -1;

            break;

        case WM_DESTROY:

            OnDestroy(hwnd);

            PostQuitMessage(0);

            break;

        case WM_COMMAND:

            switch (LOWORD(wParam)) {

                case IDM_BOLD:

                case IDM_ITALIC:

                case IDM_UNDERLINE:

                    CheckCharacterItem(hwnd, LOWORD(wParam));

                    break;

                case IDM_LEFT:

                case IDM_CENTER:

                case IDM_RIGHT:

                    CheckParagraphItem(hwnd, LOWORD(wParam));

                    break;

                .

                . // Process other commands here.

                .

            }

            break;

        .

        . // Process other messages here.

        .

        default:

            return DefWindowProc(hwnd, uMsg, wParam, lParam);

    }

    return 0;

}

VOID WINAPI CheckCharacterItem(HWND hwnd, UINT uID)

{

    HMENU hmenuBar = GetMenu(hwnd);

    HMENU hmenuPopup;

    MENUITEMINFO mii;

    // Get the handle of the Character pop-up menu.

    mii.fMask = MIIM_SUBMENU;  // information to get

    GetMenuItemInfo(hmenuBar, IDM_CHARACTER, FALSE, &mii);

    hmenuPopup = mii.hSubMenu;

    // Get the state of the specified menu item.

    mii.fMask = MIIM_STATE;    // information to get

    GetMenuItemInfo(hmenuPopup, uID, FALSE, &mii);

    // Toggle the checked state.

    mii.fState ^= MFS_CHECKED;

    SetMenuItemInfo(hmenuPopup, uID, FALSE, &mii);

}

VOID WINAPI CheckParagraphItem(HWND hwnd, UINT uID)

{

    HMENU hmenuBar = GetMenu(hwnd);

    HMENU hmenuPopup;

    MENUITEMINFO mii;

    // Get the handle of the Paragraph pop-up 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 of pop-up menu

            IDM_LEFT,           // first item in range

            IDM_RIGHT,          // last item in range

            uID,                // item to check

            MF_BYCOMMAND        // IDs, not positions

            );

}

BOOL WINAPI OnCreate(HWND hwnd)

{

    HMENU hmenuBar = GetMenu(hwnd);

    HMENU hmenuPopup;

    MENUITEMINFO mii;

    UINT uID;

    HBITMAP hbmChecked;

    HBITMAP hbmUnchecked;

    // Get the handle of the Character pop-up menu.

    mii.fMask = MIIM_SUBMENU;     // information to get

    GetMenuItemInfo(hmenuBar, IDM_CHARACTER, FALSE, &mii);

    hmenuPopup = mii.hSubMenu;

    // Create the checked and unchecked bitmaps.

    hbmChecked = CreateMenuBitmap(DrawCheck);

    hbmUnchecked = CreateMenuBitmap(DrawUncheck);

    // Set the checkmark bitmaps for each menu item.

    for (uID = IDM_BOLD; uID <= IDM_UNDERLINE; uID++) {

        SetMenuItemBitmaps(hmenuPopup, uID, MF_BYCOMMAND,

                hbmUnchecked, hbmChecked);

    }

    // Get the handle of the Paragraph pop-up menu.

    mii.fMask = MIIM_SUBMENU;     // information to get

    GetMenuItemInfo(hmenuBar, IDM_PARAGRAPH, FALSE, &mii);

    hmenuPopup = mii.hSubMenu;

    // Create the checked and unchecked bitmaps.

    hbmChecked = CreateMenuBitmap(DrawRadioCheck);

    hbmUnchecked = CreateMenuBitmap(DrawRadioUncheck);

    // Set the checkmark bitmaps for each menu item.

    for (uID = IDM_LEFT; uID <= IDM_RIGHT; uID++) {

        SetMenuItemBitmaps(hmenuPopup, uID, MF_BYCOMMAND,

                hbmUnchecked, hbmChecked);

    }

    // Initially check the IDM_LEFT paragraph item.

    CheckMenuRadioItem(hmenuPopup, IDM_LEFT, IDM_RIGHT,

            IDM_LEFT, MF_BYCOMMAND);

    return TRUE;

}

HBITMAP WINAPI CreateMenuBitmap(DRAWFUNC lpfnDraw)

{

    // Create a DC compatible with the desktop window's DC.

    HWND hwndDesktop = GetDesktopWindow();

    HDC hdcDesktop = GetDC(hwndDesktop);

    HDC hdcMem = CreateCompatibleDC(hdcDesktop);

    // Determine the required bitmap size.

    DWORD dwExt = GetMenuCheckMarkDimensions();

    SIZE size = { LOWORD(dwExt), HIWORD(dwExt) };

    // Create a monochrome bitmap and select it.

    HBITMAP hbm = CreateBitmap(size.cx, size.cy, 1, 1, NULL);

    HBITMAP hbmOld = SelectObject(hdcMem, hbm);

    // Erase the background and call the drawing function.

    PatBlt(hdcMem, 0, 0, size.cx, size.cy, WHITENESS);

    (*lpfnDraw)(hdcMem, size);

    // Clean up.

    SelectObject(hdcMem, hbmOld);

    DeleteDC(hdcMem);

    ReleaseDC(hwndDesktop, hdcDesktop);

    return hbm;

}

VOID WINAPI DrawCheck(HDC hdc, SIZE size)

{

    HBRUSH hbrOld;

    hbrOld = SelectObject(hdc, GetStockObject(NULL_BRUSH));

    Rectangle(hdc, 0, 0, size.cx, size.cy);

    MoveToEx(hdc, 0, 0, NULL);

    LineTo(hdc, size.cx, size.cy);

    MoveToEx(hdc, 0, size.cy - 1, NULL);

    LineTo(hdc, size.cx - 1, 0);

    SelectObject(hdc, hbrOld);

}

VOID WINAPI DrawUncheck(HDC hdc, SIZE size)

{

    HBRUSH hbrOld;

    hbrOld = SelectObject(hdc, GetStockObject(NULL_BRUSH));

    Rectangle(hdc, 0, 0, size.cx, size.cy);

    SelectObject(hdc, hbrOld);

}

VOID WINAPI DrawRadioCheck(HDC hdc, SIZE size)

{

    HBRUSH hbrOld;

    hbrOld = SelectObject(hdc, GetStockObject(NULL_BRUSH));

    Ellipse(hdc, 0, 0, size.cx, size.cy);

    SelectObject(hdc, GetStockObject(BLACK_BRUSH));

    Ellipse(hdc, 2, 2, size.cx - 2, size.cy - 2);

    SelectObject(hdc, hbrOld);

}

VOID WINAPI DrawRadioUncheck(HDC hdc, SIZE size)

{

    HBRUSH hbrOld;

    hbrOld = SelectObject(hdc, GetStockObject(NULL_BRUSH));

    Ellipse(hdc, 0, 0, size.cx, size.cy);

    SelectObject(hdc, hbrOld);

}

VOID WINAPI OnDestroy(HWND hwnd)

{

    HMENU hmenuBar = GetMenu(hwnd);

    HMENU hmenuPopup;

    MENUITEMINFO mii;

    // Get the handle of the Character pop-up menu.

    mii.fMask = MIIM_SUBMENU;     // information to get

    GetMenuItemInfo(hmenuBar, IDM_CHARACTER, FALSE, &mii);

    hmenuPopup = mii.hSubMenu;

    // Get the check mark bitmaps and delete them.

    mii.fMask = MIIM_CHECKMARKS;

    GetMenuItemInfo(hmenuPopup, IDM_BOLD, FALSE, &mii);

    DeleteObject(mii.hbmpChecked);

    DeleteObject(mii.hbmpUnchecked);

    // Get the handle of the Paragraph pop-up 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);

}


 Extended Menu Reference

The functions, structures, and messages used with extended menus can be grouped as follows. Some of these application programming interface (API) elements are also used with menus.

Menu Handles

GetMenu
GetSubMenu
GetSystemMenu

Menu-Item Information

GetMenuItemID
GetMenuItemInfo
SetMenuItemInfo
MENUITEMINFO

Default Menu Items

GetMenuDefaultItem
SetMenuDefaultItem

Menu-Item States

CheckMenuRadioItem
EnableMenuItem
GetMenuCheckMarkDimensions
HiliteMenuItem
SetMenuItemBitmaps

Menu Templates

LoadMenu
LoadMenuIndirect
MENUITEMTEMPLATE
MENUITEMTEMPLATEHEADER
MENUEX_TEMPLATE_HEADER
MENUEX_TEMPLATE_ITEM

Menu Creation and Modification

CreateMenu
CreatePopupMenu
DeleteMenu
DestroyMenu
DrawMenuBar
InsertMenuItem
RemoveMenu

Menu Display

SetMenu
TrackPopupMenu
TrackPopupMenuEx
WM_CONTEXTMENU

Menu Messages

WM_COMMAND
WM_INITMENU
WM_INITMENUPOPUP
WM_MENUSELECT
WM_SYSCOMMAND


 Extended Menu Functions

The following are the extended menu functions.

CheckMenuRadioItem
GetMenuDefaultItem
GetMenuItemInfo
GetMenuItemRect
InsertMenuItem
MenuItemFromPoint
SetMenuDefaultItem
SetMenuItemInfo
TrackPopupMenuEx


 Extended Menu Structures

The following are the extended menu structures.

MENUEX_TEMPLATE_HEADER
MENUEX_TEMPLATE_ITEM
MENUITEMINFO
TPMPARAMS


 Extended Menu Messages

The following are the extended menu messages.

WM_CONTEXTMENU


 Menus (Windows NT)

A menu is one or more lists of application commands. Each command, which is represented by a text string or bitmap, is called a menu item. By using the mouse or the keyboard to choose a menu item, the user directs the application to perform the command associated with the menu item. When the user chooses a menu item, Microsoft® Windows® sends the application a command message that indicates which menu item the user chose.

This Windows NT overview describes menus and explains how to use them in a Win32-based application.


 About Menus

Windows NT Overview
For more information, see the Windows 95 overview About Extended Menus.

A menu is one or more lists of application commands. Each command, which is represented by a text string or bitmap, is called a menu item. By using the mouse or the keyboard to choose a menu item, the user directs the application to perform the command associated with that menu item. When the user chooses a menu item, Microsoft® Windows® sends the application a command message that indicates which menu item the user chose.

Win32 also provides extended menu functions that give applications an improved way to create and control menus. The extended functions supersede the menu functions described in this topic and should be used in Win32-based applications whenever possible. For information about extended menu functions, see Extended Menus.


 Menu Bars and Pop-up Menus

Windows NT Overview
For more information, see the Windows 95 overview Menu Bars and Pop-up Menus.

The menus in an application written for Microsoft Windows are arranged hierarchically. A menu bar (sometimes called a top-level menu) resides at the uppermost level of the hierarchy; the lower levels consist of pop-up menus (also known as submenus).

The items in a menu bar represent the main categories of commands provided by an application. Selecting an item from the menu bar typically activates a pop-up menu whose items correspond to the commands in a given category. For example, a menu bar might contain a File item that, when the user selects it, activates a pop-up menu with menu items such as New, Open, Save, and so on.

Only an overlapped or pop-up window can contain a menu bar; a child window cannot contain one. A menu bar is always visible. If the window has a title bar, Windows positions the menu bar just below it. By contrast, a pop-up menu is not visible until the user selects a menu item that activates it. When this menu is displayed, it is attached to the title bar.

Every menu must have an owner window. Windows sends messages to a menu's owner window when the user selects the menu or chooses a command from the menu. These messages are described in Menu Messages Overview.


 Floating Pop-up Menus

Windows NT Overview
For more information, see the Windows 95 overview Floating Pop-up Menus.

Windows provides a special type of pop-up menu called a floating pop-up menu. A floating pop-up menu is not attached to the menu bar; it can appear anywhere on the screen. An application typically associates a floating pop-up menu with a portion of a window such as the client area or with a specific object such as an icon.

A floating pop-up menu remains hidden until the user selects it (for example, by clicking the appropriate screen location with the mouse.) A floating pop-up menu is typically displayed at the position of the caret or mouse cursor.


 The System Menu

Windows NT Overview
For more information, see the Windows 95 overview The System Menu.

A System menu (also known as the Control menu) is a pop-up menu defined and managed almost exclusively by the system. It is represented by a small box containing a horizontal line that is displayed at the left end of the title bar. When the user clicks the box, Windows displays the System menu. Windows also displays the System menu when the user clicks the icon of a minimized application.

A System menu provides a standard set of menu items the user can choose to change a window's size or position, close the application, or activate the Windows Task List. Items in a System 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 System menu. It is uncommon for an overlapped or pop-up window not to include a System menu.

When the user chooses a command from a System menu, Windows sends a WM_SYSCOMMAND message to the menu's owner window. In most applications, the window procedure does not process messages from a System menu. Instead, it simply passes the messages to the DefWindowProc function for system-default processing of the message. If a command is added to a System menu, the window procedure must process the command.


 Menu Handles

Windows NT Overview
For more information, see the Windows 95 overview 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 Windows menu functions. You receive the handle of a menu bar when you create the menu or loads a menu resource. For information about creating menus and loading menus, see Menu Creation.

The GetMenu or GetSubMenu function is used to retrieve the handle of a menu that has been created or loaded. GetMenu returns the handle of the menu bar assigned to the specified window. GetSubMenu returns the handle of a pop-up menu within the specified menu bar or pop-up menu. The GetSystemMenu function is used to retrieve the handle of a window's System menu.


 Class Menus

Windows NT Overview
For more information, see the Windows 95 overview Class Menus.

When registering a window class, the developer can specify a default menu for that class. This default menu is known as the class menu. To specify a class menu, the developer must assign the name of the menu, as given in your application's resource-definition file, to the lpszMenuName member of the WNDCLASS structure used to register the window class. After the window class has been registered, each window of that class will have the specified class menu. The developer can override the class menu by specifying the handle of a different menu when creating a window of that class. For more information about window classes, see Window Classes.


 Menu Items

Windows NT Overview
For more information, see the Windows 95 overview Menu Items.

There are two kinds of menu items in Win32 applications: command items and pop-up items. When the user chooses a command item, Windows sends a WM_COMMAND or WM_SYSCOMMAND message to the window procedure of the menu's owner window. A command item on a System menu generates a WM_SYSCOMMAND message; command items in other menus generate WM_COMMAND messages. When the user selects a pop-up item, Windows displays a pop-up menu but doesn't send a command message to the window procedure.

A menu bar typically contains pop-up items, but may also contain command items. A pop-up menu typically contains command items, but may also contain pop-up items. By adding pop-up items to a pop-up menu, you can nest pop-up menus to an arbitrary depth. If you include a pop-up item in a pop-up menu, Windows automatically displays a small arrow to the right of the menu item text as a visual cue to the user.


 Menu-Item Identifier

Windows NT Overview
For more information, see the Windows 95 overview, Menu Item Identifier.

Associated with each menu item is a unique, application-defined integer, called an identifier. When the user chooses a command item, Windows sends the item's identifier to the owner window as part of a WM_COMMAND message. The window procedure examines the identifier to determine the source of the message, and processes the message accordingly. In addition, you can specify a menu item using its identifier when you call menu functions — for example, to enable or disable a menu item.

A menu identifier must be a value from 0 to 65,535, even though it is a 32-bit integer. This is because the WM_COMMAND message passes a menu identifier as the low-order word of its wParam parameter.

Beginning with the Win32 API, pop-up menu items have identifiers just as other menu items do. However, Windows does not send a WM_COMMAND message when a pop-up menu item is selected. Instead, Windows activates the pop-up menu associated with the pop-up menu item.


 Checked and Unchecked Menu Items

Windows NT Overview
For more information, see the Windows 95 overview Checked and Unchecked Menu Items.

A menu item can be either checked or unchecked. When a menu item is checked, Windows uses a bitmap to display a check mark to the left of the menu item. When the menu item is unchecked, Windows does not display the check mark. Only menu items in a pop-up menu can be checked; menu items in a menu bar can not be checked.

An application typically uses check marks to indicate menu options that are in effect. For example, when the user selects paragraph formatting options from a menu in a word processing application, the application places check marks next to the selected options. The following illustration shows check marks next to the Left and Single Space options in a word processing application's Paragraph menu.

A check mark attribute controls whether a menu item is checked or not. A menu item's check mark attribute can be set by using the CheckMenuItem function. The GetMenuState function is used to determine whether a menu item is currently checked or unchecked.

Windows provides a default bitmap for displaying check marks. The developer, however, can substitute other bitmaps and direct Windows to use them instead of the default. Windows requires, however, that these check mark bitmaps have the same dimensions as the default check mark bitmap. The GetMenuCheckMarkDimensions function can be used to retrieve the default dimensions.

Two bitmaps can be associated with each menu item: one for when the menu item is checked and another for when it is unchecked. The SetMenuItemBitmaps function can be used to associate bitmaps with a menu item.

The developer can either provide check mark bitmaps as bitmap resources or create the bitmaps at run time by using graphic device interface (GDI) bitmap functions. A bitmap resource, however, isn't suitable for all video resolutions and aspect ratios, so the bitmap must be sized appropriately. The check mark bitmaps can be either monochrome or color. However, on a color screen the bitmap colors are inverted when the menu item is highlighted, and this result may be undesirable. For more information about bitmaps, see Bitmaps.


Enabled, Disabled, and Grayed Menu Items
 Enabled, Disabled, and Graye Menu Items

Windows NT Overview
For more information, see the Windows 95 overview Enabled, Disabled, and Grayed Menu Items.

A menu item can be enabled, disabled, or grayed. By default, a menu item is enabled. When the user chooses an enabled menu item, Windows sends a command message to the corresponding window procedure or displays the corresponding pop-up menu, depending on whether the menu item is a command item or a pop-up item.

When menu items are not available to the user, they should be disabled or grayed. Disabled or grayed menu items do not generate a command message or display a pop-up menu when a user chooses them. Typically, applications gray an unavailable menu item to provide a visual clue to the user that a command is not available. A disabled menu item does not provide this visual clue. A disabled item can serve as a heading for group related menu items. (For example, a Save heading can be listed and then a series of commands such as Save File, Save All, and Save As). A grayed item can be used when an action is not appropriate. (For example, the Print command in the File menu can be grayed when the system does not have a printer installed.)

The EnableMenuItem function is used to enable, disable, or gray a menu item, and the GetMenuState function is used to determine whether a menu item is enabled, disabled, or grayed.


 Menu-Item Separators and Line Breaks

Windows NT Overview
For more information, see the Windows 95 overview, Menu Item Separators and Line Breaks.

Windows provides a special type of menu item, called a separator, that consists of a horizontal line. A separator menu item can be used in a pop-up menu to divide a menu into groups of related items. A separator item cannot be used in a menu bar. The user cannot select a separator menu item, and a separator does not send command messages to the window procedure.

When a menu bar contains more items than will fit on one line, Windows automatically breaks it into two or more lines. You can force a line break at a specific item on a menu bar by assigning the MF_MENUBREAK flag to the item. Windows places that item and all remaining items on a new line.

The MF_MENUBREAK and MF_MENUBARBREAK flags are used to divide items in a pop-up menu into multiple columns. When MF_MENUBREAK flag is assigned to an item, Windows places it and all remaining items in a new column. The MF_MENUBARBREAK flag creates a similar effect, except Windows includes a vertical line in the menu to separate the new column from the old one.


 Menu-Item Position

Windows NT Overview
For more information, see the Windows 95 overview, Menu-Item Position.

Windows assigns an integer position value to each item on a menu and uses the value to keep track of each item's position in the menu. Position values are zero-based; that is, the first item on a menu occupies position zero, the next position one, and so on. In a menu bar, the leftmost menu item is considered the first item, so it occupies position zero; in a pop-up menu, the uppermost menu item occupies position zero. Windows assigns position values to menu-item separators. The following illustration shows the position values of both items and separators in a menu bar and a pop-up menu.

A number of functions are used to add an item to a menu, delete an item from a menu, or modify an existing item on a menu. When one of these functions is called, the item to be modified is identified either by its position or by its identifier. Either the MF_BYPOSITION or MF_BYCOMMAND flag is also specified. For more information about modifying the contents of a menu, see Menu Modifications.


 Highlighted Menu Items

Windows NT Overview
For more information, see the Windows 95 overview Highlighted Menu Items.

Windows automatically highlights menu items as the user selects them. Highlighting can, however, be explicitly added or removed from a menu item on the menu bar by calling the HiliteMenuItem function. This function has no effect on menu items in pop-up menus. When you use HiliteMenuItem to highlight a menu item, however, the menu item only appears to be selected; if the user presses the ENTER key, the highlighted item is not chosen.


 Owner-drawn Menu Items

An application can completely control the appearance of a menu item by using an owner-drawn item. Owner-drawn items require an application to take total responsibility for drawing selected (highlighted), checked, and unchecked states. For example, if an application provided a font menu it could draw each menu item by using the corresponding font; the item for roman would be drawn with a roman font, the item for italic would be drawn in italic, and so on.

For information on how to create owner-drawn menu items, see Creating Owner-drawn Menu Items.


 Help Item

The developer should provide a standard interface for the user, including a Help item on an application's menu bars. The item should read "Help," and it should be the rightmost item on the menu bar.


 Keyboard Access to Menus

Windows NT Overview
For more information, see the Windows 95 overview Keyboard Access to Menus.

Windows provides a standard keyboard interface for menus. You can enhance this interface by including mnemonics and accelerator keys for your menu items. The following three sections describe the standard keyboard interface, mnemonics, and accelerator keys.


 Standard Keyboard Interface

Windows NT Overview
For more information, see the Windows 95 overview Standard Keyboard Interface.

Windows is designed to work with or without a mouse or other pointing device. Because Windows provides a standard keyboard interface the user can use the keyboard to select menu items. Special code is not needed to support this keyboard interface. An application receives a command message whether a menu item is selected through the keyboard or by using a mouse. The standard keyboard interface processes the following keystrokes.

Keystroke	Action
ALT	Toggles in and out of menu bar mode.
ALT+SPACEBAR	Displays the System menu.
ESC	Exits menu mode.
RIGHT ARROW	Cycles to the next top-level menu item. This keystroke cycles between the application and System menus. If the selected item is in a pop-up menu, the next column in the pop-up menu is selected or the next top-level menu item is selected.
LEFT ARROW	Works like the RIGHT ARROW key, except in the opposite direction. In pop-up menus, this keystroke backs up one column; when the currently selected item is in the far-left column, the previous pop-up menu is selected.
UP or DOWN ARROWS	Activate a pop-up menu when pressed in a top-level menu. When pressed in a pop-up menu, either keystroke selects the next or previous item.
ENTER	Activates a pop-up menu and highlights the first item if an item has a pop-up menu associated with it; otherwise, this keystroke chooses the item as if the user released the mouse button while the item was selected.
Alphabetic character	Selects the first menu item with the specified character as its mnemonic. If the selected item onvokes a pop-up menu, the menu is displayed and the first item is highlighted; otherwise, the item is chosen.


 Menu Mnemonics

Windows NT Overview
For more information, see the Windows 95 overview Menu Mnemonics.

The standard keyboard interface for menus can be enhanced by adding mnemonics to menu items. A mnemonic is a 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 menu bar is active when the user presses and releases the ALT key and the first item on the menu bar is highlighted. A pop-up menu is active when it is displayed.

A mnemonic keystroke for a menu item is created by preceding a character in the item's text string with an ampersand. For example, "&Move" causes Windows to underline the "M" character.


 Menu Keyboard Accelerators

Windows NT Overview
For more information, see the Windows 95 overview Menu Keyboard Accelerators.

In addition to having a mnemonic, a menu item can have a keyboard accelerator associated with it. A keyboard accelerator is different from a mnemonic in that the menu need not be active for the accelerator key to work. Also, a mnemonic is always associated with a menu item, while a keyboard accelerator is usually associated with a menu item, but it does not have to be.

Text to identify the keyboard accelerator is added to the menu-item text string. The accelerator text appear to the right of the menu-item name after a backslash and tab character. For example, "&Close\tAlt+F4" represents a Close item with the ALT+F4 key combination as its keyboard accelerator and with C as its mnemonic. For more information on accelerators, see Keyboard Accelerators.


 Menu Creation

Windows NT Overview
For more information, see the Windows 95 overview Menu Creation.

You can use the following methods to create a menu for use in an application:

•	Load a menu from a menu-template resource.

•	Build a menu from a menu template created at run time.

•	Use the menu creation functions to build a menu at run time.

The following sections describe how to use these three methods to create menus.


 Menu-Template Resources

Windows NT Overview
For more information, see the Windows 95 overview, Menu Template Resources.

Most developers implement menus by creating a menu-template resource that is loaded at run time. A menu template defines a menu, including the items in the menu bar and all pop-up menus. For information about creating menu template resources, see your tools documentation.

Once you have created a menu-template resource and added it to your application's executable file, you can use the LoadMenu function to load the menu-template resource into memory. This function returns the handle of the menu, which you can then assign to a window by using the SetMenu function.

Implementing menus as resources makes an application easier to localize for use in multiple countries. Only the resource definition needs to be translated for each language, not the application's source code.


 Menu Template in Memory

Windows NT Overview
For more information, see the Windows 95 overview Menu Template in Memory.

Instead of loading a menu-template resource, an application can create create a menu template in memory at run time. You create a menu from a template in memory by using the LoadMenuIndirect function. For descriptions of menu-template formats, see Using a Menu-Template Resource.


 Menu-Creation Functions

Windows NT Overview
For more information, see the Windows 95 overview, Menu Creation Functions.

Another way to create a menu at run time is to use the CreateMenu and CreatePopupMenu functions to create empty menus. CreateMenu creates an empty menu bar; CreatePopupMenu creates an empty pop-up menu. Then menu items are added to the menus by using the AppendMenu or InsertMenu functions.


 Menu Display

Windows NT Overview
For more information, see the Windows 95 overview Menu Display.

After a menu has been loaded or created, it must be assigned to a window before Windows can display it. This can be done by creating a class menu (see Class Menus), by specifying the handle of the menu as the hmenu parameter of the CreateWindowEx function, or by calling the SetMenu function.

The TrackPopupMenu function can be used to display a pop-up menu. To do so, the handle of a pop-up menu is passed to the function. The menu's owner window, the screen position where Windows should display the menu, and the mouse button the user must use to choose an item must also be specified.


 Menu Destruction

Windows NT Overview
For more information, see the Windows 95 overview Menu Destruction.

If a menu is assigned to a window and that window is destroyed, Windows automatically destroys the menu, freeing the menu's handle and the memory occupied by the menu. Windows 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.


 Menu Messages Overview

Windows NT Overview
For more information, see the Windows 95 overview Menu Messages.

Windows reports menu-related activity by sending messages to the window procedure of the window that owns the menu. The first menu-related message the window procedure receives is WM_SYSCOMMAND. Windows sends this message when the user activates the menu by clicking the menu bar or by pressing a key that activates the menu (for more information, see Keyboard Access to Menus). The WM_SYSCOMMAND message includes a flag, either SC_KEYMENU or SC_MOUSEMENU, that indicates the hardware device used to activate the menu.

Next, Windows sends the WM_INITMENU message to the window procedure before Windows displays any pop-up menus, so an application can modify the menus before the user sees them. Windows sends the WM_INITMENU message only once per menu activation.

When the user selects a pop-up item, Windows sends the owner window the WM_INITMENUPOPUP message before displaying the pop-up menu. This message gives the application a second opportunity to modify the pop-up menu before it is displayed.

Each time the user moves the highlighting from one item to another, Windows 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.

Windows sends a WM_COMMAND message to the window procedure when the user chooses a command item from a menu. 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.


 Menu Modifications

Windows NT Overview
For more information, see the Windows 95 overview Menu Modifications.

A number of functions can be used to modify a menu after it has been loaded or created. The AppendMenu and InsertMenu functions are used to add items to a menu. AppendMenu appends a menu item to the end of a menu; InsertMenu inserts a menu item at a specified position in a menu. Both functions permit the attributes of the menu item to be specified, including whether the menu item is enabled, checked, grayed, and so on.

The ModifyMenu function is used to change the appearance or attributes of an existing menu item. For example, the text string or bitmap of a menu item can be enabled, disabled, grayed, checked, or unchecked. ModifyMenu replaces the specified menu item with a new item.

The DeleteMenu or RemoveMenu functions are used to delete a menu item from a menu. If the item being deleted is a pop-up item, DeleteMenu deletes the associated pop-up menu, discarding the menu handle and freeing the memory used by the pop-up menu. The RemoveMenu function deletes a menu item, but if the item activates a pop-up menu, it does not destroy the pop-up menu or its handle, allowing the menu to be reused.

After a menu bar has been modified, the DrawMenuBar function must be called to redraw the menu bar. Otherwise, the modifications will not appear until Windows redraws the owner window.


 Using Menus

•	Using a menu template resource.

•	Creating a floating pop-up menu.

•	Using menu item bitmaps.

•	Creating owner-drawn menu items.

•	Using custom check mark bitmaps.


 Using a Menu-Template Resource

Windows NT Overview
For more information, see the Windows 95 overview, Using a Menu Template Resource.

You typically include a menu in an application by defining a menu template in the application's resource-definition file and then loading the menu at run time. Alternatively, you can create a menu template dynamically in memory. This section describes the format of a menu template, and explains how to load a menu-template resource. For information about defining a menu-template resource, see your tools documentation.


 Extended Menu Template Format

The extended menu template format supports the new menu functionality available in the Win32 API. Like old menu template resources, extended menu template resources have the RC_MENU resource type. Windows distinguishes the two resource formats by the version number, which is the first member of the resource header.

Note  The structure definitions in this section are for explanation only. They are not defined in any standard header file.

An extended menu template consists of a header followed by one more more item definitions. The header has the following form:

typedef struct {

    WORD  wVersion;  // must be 1 for extended menu resources

    WORD  wOffset;   // offset of first item; typically 4

    DWORD dwHelpId;  // Help identifier for menu

} MENUEX_HDR;

Following is a description of each member:

wVersion

Specifies the template version number. This value must be 1 for extended menu templates.

wOffset

Specifies the offset of the first menu-item definition, relative to the end of this member. If the first menu-item definition immediately follows the dwHelpId member, this value should be 4.

dwHelpId

Specifies the Help identifier for the menu.

Following the header are one or more item definitions. Item definitions vary in size depending on the length of the menu text, and are packed on byte boundaries. Each item definition has the following form:

typedef struct {

    DWORD  dwType;      // menu-item type (MFT_* flags)

    DWORD  dwState;     // menu-item state (MFS_* flags)

    WORD   wId;         // application-defined menu-item identifier

    BYTE   bResInfo;    // resource info (MFR_* flags)

    char   szText[1];   // null-terminated menu text

    // dwHelpId - In pop-up menu items, a 32-bit Help identifier

    //     follows the variable-length szText member.

} MENUEX_ITEM;

Following is a description of each member:

dwType

Specifies the type of menu item. Can be a combination of the MFT_* flags defined in WINDOWS.H. For a list of menu-item types, see the description of the MENUITEMINFO structure.

dwState

Specifies the menu-item state. Can be a combination of the MFS_* flags defined in WINDOWS.H. For a list of menu-item states, see the description of the MENUITEMINFO structure.

wId

Specifies the menu-item identifier. This is an application-defined 16-bit value used to identify the menu item. Pop-up menu items can now have identifiers; previously, only command menu-items could have identifiers.

bResInfo

Specifies the type of menu-item definition. Can be zero or more of these values:

MFR_POPUP	The item definition is for a pop-up menu item.
MFR_END	The item is the last menu item in the menu or submenu.
szText

Specifies the menu-item text. This member is a null-terminated ANSI string. The size of the menu-item definition varies depending on the length of the string.

dwHelpId

Specifies the Help identifier for a submenu. This member follows the menu-item text for pop-up menu items. It is omitted for other menu items.

The following assembly-language example defines an extended menu template:

My_Menu_Template LABEL DWORD

        dw 0001h         ; template version number

        dw 0004h         ; Windows version number

        dd 0             ; Help id for main menu

        ; The following item definition specifies a pop-up menu

        ; item for a File submenu.

        dd MFT_STRING    ; type

        dd 0             ; state

        dw 1             ; identifier

        db MFR_POPUP     ; specifies a pop-up item

        db "&File", 0    ; text, including null character

        dd 0             ; Help id for the File submenu

        ; The following definition specifies an Exit command item,

        ; which appears in the File submenu. Because it is the last

        ; item in the submenu, the MFR_END flag is specified.

        dd MFT_STRING    ; type

        dd MFS_DEFAULT   ; state

        dw 2             ; identifier

        db MFR_END       ; last menu-item in submenu

        db "E&xit", 0    ; text, including null character

        ; The following definition specifies a Help command item.

        ; Because it is the last item in the menu, the MFR_END flag

        ; is specified.

        dd MFT_STRING    ; type

        dd 0             ; state

        dw 3             ; id

        db MFR_END       ; last menu-item in main menu

        db "&Help", 0    ; text, including null character


 Old Menu Template Format

An old menu template defines a menu, but does not support the new menu functionality available in the Win32 API. 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

Windows NT Overview
For more information, see the Windows 95 overview, Loading a Menu Template Resource.

You can load a menu-template resource by calling the LoadMenu function, specifying the handle of the module that contains the resource and the menu-template's identifier. LoadMenu 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.

You can create a menu from a menu template that is already in memory by using the LoadMenuIndirect function. This is useful if your application generates menu templates dynamically.

Use the SetMenu function to assign a menu to a window, or specify the menu's handle in the hmenu parameter of the CreateWindowEx function when you create a window. Another way that you can assign a menu to a window is to specify a menu template when you register a window class. This identifies the menu as the class menu for the given window class. Whenever you create a window of the given class, Windows automatically assigns the given menu to the window.

You can create a class menu by including the identifier of the menu-template resource as the lpszMenuName member of a WNDCLASS structure and then passing the address of the structure to the RegisterClass function.


 Creating a Class Menu

Windows NT Overview
For more information, see the Windows 95 overview Creating a Class Menu.

The following example shows how to create a class menu for an application, how to create a window that uses the class menu, and how to process menu commands in the window procedure.

HINSTANCE hinst;

int APIENTRY WinMain(hinstance, hPrevInstance, lpCmdLine, nCmdShow)

HINSTANCE hinstance;

HINSTANCE hPrevInstance;

LPSTR lpCmdLine;

int nCmdShow;

{

    MSG msg;        /* message               */

    WNDCLASS wc;    /* window-class data     */

    HWND hwnd;      /* handle of 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 =  "MyMenuResource";

    wc.lpszClassName = "MainWClass";

    if (!RegisterClass(&wc))

        return FALSE;

    hinst = hinstance;

    /*

     * Create the main window. Set the hmenu parameter to NULL so

     * that Windows uses the class menu for the window.

     */

    hwnd = CreateWindow("MainWClass", "Sample Application",

        WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT,

        CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hinstance,

        NULL);

    if (hwnd == NULL)

        return FALSE;

    /*

     * Make the window visible and send a WM_PAINT message to the

     * window procedure.

     */

    ShowWindow(hwnd, nCmdShow);

    UpdateWindow(hwnd);

    /* Start the main message loop. */

    while (GetMessage(&msg, NULL, 0, 0)) {

        TranslateMessage(&msg);

        DispatchMessage(&msg);

    }

    return msg.wParam;

        UNREFERENCED_PARAMETER(hPrevInstance);

}

LRESULT APIENTRY MainWndProc(hwnd, uMsg, wParam, lParam)

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 Floating Pop-up Menu

Windows NT Overview
For more information, see the Windows 95 overview Creating a Floating Pop-up Menu.

To use a floating pop-up menu in an application, pass the handle of a pop-up menu to the TrackPopupMenu function. An application typically calls TrackPopupMenu 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, TrackPopupMenu requires that you specify the handle of the owner window, the position of the floating pop-up menu (in screen coordinates), and the mouse button the user can use to choose an item.

Specify the position by providing x- and y-coordinates along with the TPM_CENTERALIGN, TPM_LEFTALIGN, or TPM_RIGHTALIGN flag. The flag specifies the position of the menu relative to the x- and y-coordinates.

You should permit the user to choose an item from a pop-up menu by using the same mouse button used to display the menu. To do this, specify either TPM_LEFTBUTTON or TPM_RIGHTBUTTON flags to indicate which mouse button the user can use to select a menu item.


 Creating a Floating Font-Attributes Menu

The example in this section contains portions of code from an application that creates and displays a floating pop-up 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 pop-up 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 floating pop-up menu.

LRESULT APIENTRY MenuWndProc(hwnd, uMsg, wParam, lParam)

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 = LOWORD(lParam);

            pt.y = HIWORD(lParam);

            /*

             * If the mouse click took place inside the client

             * area, execute the application-defined function

             * that displays the floating pop-up 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, pt)

HWND hwnd;

POINT pt;

{

    HMENU hmenu;            /* menu template         */

    HMENU hmenuTrackPopup;  /* floating pop-up menu  */

    /*

     * Load the menu template containing the pop-up menu from the

     * application's resources.

     */

    hmenu = LoadMenu(hinst, "PopupMenu");

    if (hmenu == NULL)

        return;

    /*

     * Get the first pop-up 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 floating pop-up menu. */

    TrackPopupMenu(hmenuTrackPopup, TPM_LEFTALIGN | TPM_LEFTBUTTON,

        pt.x, pt.y, 0, hwnd, NULL);

    /* Destroy the menu.*/

    DestroyMenu(hmenu);

}


 Using Menu-Item Bitmaps

Windows NT Overview
For more information, see the Windows 95 overview, Using Menu Item Bitmaps.

Windows can use a bitmap instead of a text string to display a menu item. To use a bitmap, you must set the MF_BITMAP flag for the menu item and specify the handle of the bitmap that Windows should display for the menu item. This section describes how to set the MF_BITMAP flag and retrieve the handle of a bitmap.


 Setting the MF_BITMAP Flag

The MF_BITMAP flag tells Windows to use a bitmap rather than a text string to display a menu item. A menu item's MF_BITMAP flag must be set at run time; you cannot set it in the resource-definition file.

You can use the ModifyMenu, InsertMenu, or AppendMenu function to set the MF_BITMAP flag. To convert 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

Windows NT Overview
For more information, see the Windows 95 overview Creating the Bitmap.

When you set the MF_BITMAP flag for a menu item, you must also specify the handle of the bitmap that Windows should display for the menu item. You can provide the bitmap as a bitmap resource or create the bitmap at run time.

To provide a bitmap resource, use a resource editor, such as ImageEdit, to create a bitmap resource, and then use a resource compiler to add the bitmap to your application's executable file. At run time, use the LoadBitmap function to load the bitmap and obtain its handle.

To create the bitmap at run time, use GDI functions. GDI provides several ways to create a bitmap at run time, but developers typically use the following method:

•	Use the CreateCompatibleDC function to create a device context compatible with the device context used by the application's main window.

•	Use the CreateCompatibleBitmap function to create a bitmap compatible with the application's main window.

•	Use the SelectObject function to select the bitmap into the compatible device context.

•	Use GDI drawing functions, such as Ellipse and LineTo, to draw an image into the bitmap.

•	Pass the handle of the bitmap to the ModifyMenu, InsertMenu, or AppendMenu function.

For more information about bitmaps, 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 pop-up menus shown in the following illustration. 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 pop-up menu is a Lines menu. It contains bitmaps showing the line styles provided by the predefined pen in Windows. 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, uMsg, wParam, lParam)

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 hwnd;              /* handle of owner window      */

{

    HBITMAP hbmpPie;    /* handle of pie chart bitmap  */

    HBITMAP hbmpLine;   /* handle of line chart bitmap */

    HBITMAP hbmpBar;    /* handle of bar chart bitmap  */

    HMENU hmenuMain;    /* handle of main menu         */

    HMENU hmenuChart;   /* handle of chart pop-up 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 pop-up menu and add it to the menu bar.

     * Append the Pie, Line, and Bar menu items to the Chart

     * pop-up 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, phpen, phbmp)

HWND hwnd;

HPEN *phpen;

HBITMAP *phbmp;

{

    HMENU hmenuLines;       /* handle of Lines pop-up menu     */

    HMENU hmenu;            /* handle of main menu             */

    COLORREF crMenuClr;     /* menu-item background color      */

    HBRUSH hbrBackground;   /* handle of background brush      */

    HBRUSH hbrOld;          /* handle of previous brush        */

    LONG lCheckXY;          /* dimensions of check mark bitmap */

    WORD wLineX;            /* width of line bitmaps           */

    WORD wLineY;            /* height of line bitmaps          */

    HDC hdcMain;            /* handle of main window's DC      */

    HDC hdcLines;           /* handle of compatible DC         */

    HBITMAP hbmpOld;        /* handle of previous bitmap       */

    int i;                  /* loop counter                    */

    /* Create the Lines pop-up 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.

     */

    lCheckXY = GetMenuCheckMarkDimensions();

    wLineX = LOWORD(lCheckXY) * (WORD) 5;

    wLineY = HIWORD(lCheckXY);

    /*

     * 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;

}


 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 on your application. This section describes the steps involved in creating and using an owner-drawn menu item.


 Setting the MF_OWNERDRAW Flag

You cannot define an owner-drawn menu item on your application's resource-definition file. Instead, you must create a new menu item or modify an existing one by using the MF_OWNERDRAW menu flag.

You can use the AppendMenu, InsertMenu, or ModifyMenu function to specify an owner-drawn menu item. Use AppendMenu to add a new item to the end of the given menu. Use InsertMenu to place a new item onto a menu, moving the other items down. Use ModifyMenu to change the contents of a menu.

When you call any of these three functions, you can pass a 32-bit value as the lpNewItem parameter. This value can represent any information that is meaningful to your application, and that will be available to your application when the item is to be displayed. For example, the value could contain a pointer to a structure; the structure, in turn, might contain a text string and the handle of a logical font that your application will use to draw the string.


 Responding to the WM_MEASUREITEM Message

Before Windows 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 an optional 32-bit value for the item. When the window procedure receives the WM_MEASUREITEM message, it must fill the itemWidth and itemHeight members of the structure before returning from processing the message. Windows uses the information in these members when creating the bounding rectangle in which your application draws the menu item. It also uses the information to detect when the user chooses the item.


 Responding to the WM_DRAWITEM Message

Whenever the item must be drawn (for example, when it is first displayed or when the user chooses it as a command), Windows sends the WM_DRAWITEM message to the window procedure of the menu's owner window. This message contains a pointer to a DRAWITEMSTRUCT structure. Like the MEASUREITEMSTRUCT structure, DRAWITEMSTRUCT contains information about the item and its optional 32-bit data. In addition, DRAWITEMSTRUCT contains flags that indicate the state of the item (such as whether it is grayed or checked) as well as a bounding rectangle and a device context that the application uses to draw the item.

In response to the WM_DRAWITEM message, your application must perform the following actions before returning from processing the message:

1.	Determine the type of drawing that is necessary. To do so, check the itemAction member of the DRAWITEMSTRUCT structure.

2.	Draw the menu item appropriately, using the bounding rectangle and device context obtained from the DRAWITEMSTRUCT structure. Your application must draw only within the bounding rectangle. For performance reasons, Windows doesn't clip portions of the image that are drawn outside the rectangle.

3.	Restore all GDI objects selected for the menu item's device context.

If the menu item is selected, Windows sets the itemAction member of the DRAWITEMSTRUCT structure to ODA_SELECT and sets the ODS_SELECTED flag in the itemState member. This is an application's cue to redraw the menu item to indicate that it is selected.


 Setting Fonts for Menu-Item Text Strings

This section contains an example from an application that uses owner-drawn menu items in a pop-up menu. The pop-up 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 items are assigned at run time, so their strings are empty in the resource-definition file.

MainMenu MENU

BEGIN

    POPUP   "&Character"

    BEGIN

        MENUITEM    "",    IDM_REGULAR

        MENUITEM SEPARATOR

        MENUITEM    "",    IDM_BOLD

        MENUITEM    "",    IDM_ITALIC

        MENUITEM    "",    IDM_ULINE

    END

END

The application's window procedure processes the messages involved in using owner-drawn menu items. The application uses the WM_CREATE message to do the following:

•	Set the MF_OWNERDRAW flag for the menu items.

•	Set the text strings for the menu items.

•	Obtain handles of the fonts used to draw the items.

•	Obtain the text and background color values for selected menu items.

The text strings and font handles are stored in an array of application-defined MYITEM structures. The application-defined GetAFont function creates a font that corresponds to the given font attribute and returns the handle of 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. Windows uses the width and height values to calculate the size of the pop-up 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, uMsg, wParam, lParam)

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 of 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;  /* points to item of data            */

    LPDRAWITEMSTRUCT lpdis;     /* points to item drawing data       */

    HDC hdc;                    /* handle of screen DC               */

    SIZE size;                  /* menu-item text extents            */

    DWORD dwCheckXY;            /* check mark dimensions             */

    WORD wCheckX;               /* check mark width                  */

    int nTextX;                 /* width of menu item                */

    int nTextY;                 /* height of menu item               */

    int i;                      /* loop counter                      */

    HFONT hfontOld;             /* handle of 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.

             */

            dwCheckXY = GetMenuCheckMarkDimensions();

            wCheckX = LOWORD(dwCheckXY);

            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(fnFont)

int fnFont;             /* font-attribute flag            */

{

    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);

}


 Using Custom Check Mark Bitmaps

Windows NT Overview
For more information, see the Windows 95 overview Using Custom Check Mark Bitmaps.

A Windows video device driver provides a default check mark bitmap that Windows displays next to a menu item that is checked. You can customize an individual menu item by providing a pair of bitmaps to replace the default check mark bitmap. Windows displays one bitmap when the item is checked and the other when it is unchecked. This section describes the steps involved in creating and using custom check mark bitmaps.


 Creating Custom Check Mark Bitmaps

Windows NT Overview
For more information, see the Windows 95 overview 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 bitmap's size by calling the GetMenuCheckMarkDimensions function. The low-order word of this function's return value specifies the width; the high-order word specifies the height.

Bitmap resources can be used to provide check mark bitmaps. However, a bitmap resource is not suitable for all screen resolutions and aspect ratios, so you'll need to use the StretchBlt function to size the bitmap, as appropriate. Depending on the bitmap being sized, the result of the sizing may not be acceptable, because stretching may distort the bitmap.

Instead of using a bitmap resource, GDI functions can be used to provide check mark bitmaps at run time. This involves the following steps, which an application typically performs during the WM_CREATE message:

1.	Create a device context in memory that is compatible with the screen.

2.	Create a bitmap that is compatible with the display.

3.	Select the bitmap into the device context.

4.	Draw or copy an image into the bitmap.

Call the CreateCompatibleDC function to create a device context that is compatible with the screen. The function's hdc parameter can specify either NULL or the return value from the GetDC function. CreateCompatibleDC returns the handle of the compatible device context.

Call the CreateCompatibleBitmap function to create an "empty" bitmap that is compatible with the screen. This function's nWidth and nHeight parameters set the size of the bitmap; they should specify the width and height information returned by the GetMenuCheckMarkDimensions function.

The CreateCompatibleBitmap function returns the handle of the bitmap. Pass this handle of the SelectObject function to select the bitmap into the compatible device context. Afterward, you can use the GDI drawing functions such as Rectangle and Ellipse to draw into the bitmap, or you can use functions such as BitBlt and StretchBlt to copy an image into the bitmap.

GDI provides several other ways to create bitmaps. For more information about bitmaps, see Bitmaps.


 Associating Bitmaps with a Menu Item

Windows NT Overview
For more information, see the Windows 95 overview 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 hbmUnchecked parameter identifies the unchecked bitmap; the hbmChecked parameter identifies the checked bitmap. If you want to remove one or both check marks from a menu item, you can set the hbmUnchecked or hbmChecked parameter, or both, to NULL.


 Setting the Check Mark Attribute

Windows NT Overview
For more information, see the Windows 95 overview Setting the Check Mark Attribute.

The CheckMenuItem function sets a menu item's check mark attribute to either checked or unchecked. Specify the MF_CHECKED flag to set the check mark attribute to checked, or specify MF_UNCHECKED to set it to unchecked.


 Simulating Check Boxes in a Menu

This section contains an example that shows how to simulate check boxes in a pop-up 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, it is displayed in an empty check box next to the item.

The example in this section replaces the default check mark bitmap with two bitmaps: a bitmap with a checked box and the bitmap with an empty box. The checked check box bitmap is displayed next to the Bold, Italic, or Underline menu item when the item's check mark attribute is set to MF_CHECKED. The unchecked or empty check box bitmap is displayed when the check mark attribute is set to MF_UNCHECKED.

Windows provides a predefined bitmap that contains the images used for check boxes and radio buttons. The example in this section isolates the checked and empty check boxes, copies them to two separate bitmaps, and then uses them as the checked and unchecked bitmaps for items in the Character menu.

To retrieve the handle of the system-defined check box bitmap, the example in this section calls the LoadBitmap function, specifying NULL as the hinst parameter and OBM_CHECKBOXES as the lpBitmapName parameter. Because the images in the bitmap are all the same size, the example can isolate them by dividing the bitmap's width and height by the number of images in its rows and columns.

The following portion of a resource-definition file shows how the menu items in the Character menu are defined. Note that no font attributes are in effect initially, so the check mark attribute for the Regular item is set to checked and, by default, the check mark attribute of the remaining items is set to unchecked.

#include "men3.h"

MainMenu MENU

BEGIN

    POPUP   "&Character"

    BEGIN

        MENUITEM    "&Regular",     IDM_REGULAR, CHECKED

        MENUITEM SEPARATOR

        MENUITEM    "&Bold",        IDM_BOLD

        MENUITEM    "&Italic",      IDM_ITALIC

        MENUITEM    "&Underline",   IDM_ULINE

    END

END

Here is 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(hwndMain, uMsg, wParam, lParam)

HWND hwndMain;

UINT uMsg;

WPARAM wParam;

LPARAM lParam;

{

    static HBITMAP hbmpCheck;   /* handle of checked bitmap   */

    static HBITMAP hbmpUncheck; /* handle of unchecked bitmap */

    static HMENU hmenu;         /* handle of main menu        */

    BYTE fbFontAttrib;          /* font-attribute flags       */

    switch (uMsg) {

        case WM_CREATE:

            /*

             * Call the application-defined GetMyCheckBitmaps

             * function to get the predefined checked and

             * unchecked check box bitmaps.

             */

            hbmpCheck = GetMyCheckBitmaps(CHECK);

            hbmpUncheck = GetMyCheckBitmaps(UNCHECK);

            /*

             * Set the checked and unchecked bitmaps for the menu

             * items.

             */

            hmenu = GetMenu(hwndMain);

            SetMenuItemBitmaps(hmenu, IDM_BOLD, MF_BYCOMMAND,

                hbmpUncheck, hbmpCheck);

            SetMenuItemBitmaps(hmenu, IDM_ITALIC, MF_BYCOMMAND,

                hbmpUncheck, hbmpCheck);

            SetMenuItemBitmaps(hmenu, IDM_ULINE, MF_BYCOMMAND,

                hbmpUncheck, hbmpCheck);

            return 0;

        case WM_COMMAND:

            switch (LOWORD(wParam)) {

                /* Process the menu commands. */

                case IDM_REGULAR:

                case IDM_BOLD:

                case IDM_ITALIC:

                case IDM_ULINE:

                    /*

                     * CheckOrUncheckMenuItem is an application-

                     * defined function that sets the menu item

                     * check marks and returns the user-selected

                     * font attributes.

                     */

                    fbFontAttrib = CheckOrUncheckMenuItem(

                        (BYTE) LOWORD(wParam), hmenu);

                    .

                    . /* Set the font attributes. */

                    .

                    return 0;

                .

                . /* Process other command messages. */

                .

                default:

                    break;

            }

            break;

        .

        . /* Process other window messages. */

        .

        case WM_DESTROY:

            /* Destroy the checked and unchecked bitmaps. */

            DeleteObject(hbmpCheck);

            DeleteObject(hbmpUncheck);

            PostQuitMessage(0);

            break;

        default:

            return DefWindowProc(hwndMain, uMsg, wParam, lParam);

    }

    return NULL;

}

HBITMAP GetMyCheckBitmaps(fuCheck)

UINT fuCheck;               /* CHECK or UNCHECK flag            */

{

    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 of check box bitmap       */

    BITMAP bmCheckbox;      /* structure for bitmap data        */

    HBITMAP hbmpSourceOld;  /* handle of original source bitmap */

    HBITMAP hbmpTargetOld;  /* handle of original target bitmap */

    HBITMAP hbmpCheck;      /* handle of check mark bitmap      */

    RECT rc;                /* rectangle for check box bitmap   */

    DWORD dwCheckXY;        /* dimensions of check mark 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 Windows default check mark bitmap and

     * create a compatible bitmap of the same size.

     */

    dwCheckXY = GetMenuCheckMarkDimensions();

    wBitmapX = LOWORD(dwCheckXY);

    wBitmapY = LOWORD(dwCheckXY);

    hbmpCheck = CreateCompatibleBitmap(hdcSource, wBitmapX,

        wBitmapY);

    /*

     * Select the background brush and bitmap into the target DC.

     */

    hbrTargetOld = SelectObject(hdcTarget, hbrBackground);

    hbmpTargetOld = SelectObject(hdcTarget, hbmpCheck);

    /*

     * Use the selected brush to initialize the background color

     * of the bitmap in the target device context.

     */

    PatBlt(hdcTarget, 0, 0, wBitmapX, wBitmapY, PATCOPY);

    /*

     * Load the predefined check box bitmaps and select it

     * into the source DC.

     */

    hbmpCheckboxes = LoadBitmap((HINSTANCE) NULL,

        (LPTSTR) OBM_CHECKBOXES);

    hbmpSourceOld = SelectObject(hdcSource, hbmpCheckboxes);

    /*

     * Fill a BITMAP structure with information about the

     * check box bitmaps, and then find the upper-left corner of

     * the unchecked check box or the checked check box.

     */

    GetObject(hbmpCheckboxes, sizeof(BITMAP), &bmCheckbox);

    if (fuCheck == UNCHECK) {

        rc.left = 0;

        rc.right = (bmCheckbox.bmWidth / 4);

    }

    else {

        rc.left = (bmCheckbox.bmWidth / 4);

        rc.right = (bmCheckbox.bmWidth / 4) * 2;

    }

    rc.top = 0;

    rc.bottom = (bmCheckbox.bmHeight / 3);

    /*

     * Copy the appropriate bitmap into the target DC. If the

     * check box bitmap is larger than the default check mark

     * bitmap, use StretchBlt to make it fit; otherwise, just

     * copy it.

     */

    if (((rc.right - rc.left) > (int) wBitmapX) ||

            ((rc.bottom - rc.top) > (int) wBitmapY))

        StretchBlt(hdcTarget, 0, 0, wBitmapX, wBitmapY,

            hdcSource, rc.left, rc.top, rc.right - rc.left,

            rc.bottom - rc.top, SRCCOPY);

    else

        BitBlt(hdcTarget, 0, 0, rc.right - rc.left,

            rc.bottom - rc.top,

            hdcSource, rc.left, rc.top, SRCCOPY);

    /*

     * Select the old source and destination bitmaps into the

     * source and destination DCs, and then delete the DCs and

     * the background brush.

     */

    SelectObject(hdcSource, hbmpSourceOld);

    SelectObject(hdcTarget, hbrTargetOld);

    hbmpCheck = SelectObject(hdcTarget, hbmpTargetOld);

    DeleteObject(hbrBackground);

    DeleteObject(hdcSource);

    DeleteObject(hdcTarget);

    /* Return the handle of the new check mark bitmap. */

    return hbmpCheck;

}

BYTE CheckOrUncheckMenuItem(bMenuItemID, hmenu)

BYTE bMenuItemID;

HMENU hmenu;

{

    DWORD fdwMenu;

    static BYTE fbAttributes;

    switch (bMenuItemID) {

        case IDM_REGULAR:

            /*

             * Whenever the Regular menu item is selected, add a

             * check mark to it and then remove check marks from

             * any font-attribute menu items.

             */

            CheckMenuItem(hmenu, IDM_REGULAR, MF_BYCOMMAND |

                MF_CHECKED);

            if (fbAttributes & ATTRIBMASK) {

                CheckMenuItem(hmenu, IDM_BOLD, MF_BYCOMMAND |

                    MF_UNCHECKED);

                CheckMenuItem(hmenu, IDM_ITALIC, MF_BYCOMMAND |

                    MF_UNCHECKED);

                CheckMenuItem(hmenu, IDM_ULINE, MF_BYCOMMAND |

                    MF_UNCHECKED);

            }

            fbAttributes = IDM_REGULAR;

            return fbAttributes;

        case IDM_BOLD:

        case IDM_ITALIC:

        case IDM_ULINE:

            /*

             * Toggle the check mark for the selected menu item and

             * set the font attribute flags appropriately.

             */

            fdwMenu = GetMenuState(hmenu, (UINT) bMenuItemID,

                MF_BYCOMMAND);

            if (!(fdwMenu & MF_CHECKED)) {

                CheckMenuItem(hmenu, (UINT) bMenuItemID,

                    MF_BYCOMMAND | MF_CHECKED);

                fbAttributes |= bMenuItemID;

            } else {

                CheckMenuItem(hmenu, (UINT) bMenuItemID,

                    MF_BYCOMMAND | MF_UNCHECKED);

                fbAttributes ^= bMenuItemID;

            }

            /*

             * If any font attributes are currently selected,

             * remove the check mark from the Regular menu item;

             * if no attributes are selected, add a check mark

             * to the Regular menu item.

             */

            if (fbAttributes & ATTRIBMASK) {

                CheckMenuItem(hmenu, IDM_REGULAR,

                    MF_BYCOMMAND | MF_UNCHECKED);

                fbAttributes &= (BYTE) ~IDM_REGULAR;

            } else {

                CheckMenuItem(hmenu, IDM_REGULAR,

                    MF_BYCOMMAND | MF_CHECKED);

                fbAttributes = IDM_REGULAR;

            }

            return fbAttributes;

    }

}


 Menu Reference

The following functions and messages are associated with menus.


 Menu Functions

Following are the Windows functions used with menus.

AppendMenu
CheckMenuItem
CheckMenuRadioItem
CreateMenu
CreatePopupMenu
DeleteMenu
DestroyMenu
DrawMenuBar
EnableMenuItem
GetMenu
GetMenuCheckMarkDimensions
GetMenuDefaultItem
GetMenuItemCount
GetMenuItemID
GetMenuItemInfo
GetMenuItemRect
GetMenuState
GetMenuString
GetSubMenu
GetSystemMenu
HiliteMenuItem
InsertMenu
InsertMenuItem
IsMenu
LoadMenu
LoadMenuIndirect
MenuItemFromPoint
ModifyMenu
RemoveMenu
SetMenu
SetMenuDefaultItem
SetMenuItemBitmaps
SetMenuItemInfo
TrackPopupMenu
TrackPopupMenuEx

Obsolete or Deleted Functions

ChangeMenu


 Menu Messages

Following are the Windows messages used with menus.

WM_CONTEXTMENU
WM_DRAWITEM
WM_ENTERMENULOOP
WM_EXITMENULOOP
WM_INITMENU
WM_INITMENUPOPUP
WM_MEASUREITEM
WM_MENUCHAR
WM_MENUSELECT
WM_SYSCOMMAND


 Hooks

A hook is a point in the Microsoft® Windows® message-handling mechanism where an application can install a subroutine to monitor the message traffic in the system and process certain types of messages before they reach the target window procedure.

This overview describes Windows hooks and explains how to use them in a Windows-based application.


 About Hooks

Hooks tend to slow down the system because they increase the amount of processing the system must perform for each message. You should install a hook only when necessary, and remove it as soon as possible.


 Hook Chains

Windows contains many different types of hooks; each type provides access to a different aspect of the Windows message-handling mechanism. For example, an application can use the WH_MOUSE hook to monitor the message traffic for mouse messages.

Windows maintains a separate hook chain for each type of hook. A hook chain is a list of pointers to special, application-defined callback functions called hook procedures. When a message occurs that is associated with a particular type of hook, Windows passes the message to each hook procedure referenced in the hook chain, one after the other. The action a hook procedure can take depends on the type of hook involved. The hook procedures for some types of hooks can only monitor messages; others can modify messages or stop their progress though the chain, preventing them from reaching the next hook procedure or the destination window.


 Hook Procedures

To take advantage of a particular type of hook, the developer provides a hook procedure and uses the SetWindowsHookEx function to install it into the chain associated with the hook. A hook procedure must have the following syntax:

LRESULT CALLBACK HookProc(nCode, wParam, lParam)
int nCode;
WPARAM wParam;
LPARAM lParam;

HookProc is a placeholder for an application-defined name. Because Windows must call the hook procedure, the actual name must be exported by listing it and, optionally, its ordinal value, in the EXPORTS statement of the application's module-definition file.

The nCode parameter is a hook code that the hook procedure uses to determine the action to perform. The value of the hook code depends on the type of the hook; each type has its own characteristic set of hook codes. The values of the wParam and lParam parameters depend on the hook code, but they typically contain information about a message that was sent or posted.

SetWindowsHookEx always installs a hook procedure at the beginning of a hook chain. When an event occurs that is monitored by a particular type of hook, Windows calls the procedure at the beginning of the hook chain associated with the hook. Each hook procedure in the chain determines whether to pass the event to the next procedure. A hook procedure passes an event to the next procedure by calling the CallNextHookEx function.

Note that the hook procedures for some types of hooks can only monitor messages. Windows passes messages to each hook procedure, regardless of whether a particular procedure calls CallNextHookEx.

A hook procedure can be global, monitoring messages for all threads in the system, or it can be thread specific, monitoring messages for only an individual thread. A global hook procedure can be called in the context of any application, so the procedure must be in a separate dynamic-link library (DLL) module. A thread specific hook procedure is called only in the context of the associated thread. If an application installs a hook procedure for one of its own threads, the hook procedure can be in either the same module as the rest of the application's code or in a DLL. If the application installs a hook procedure for a thread of a different application, the procedure must be in a DLL. For information about DLLs, see Dynamic-Link Libraries.

Note  You should use global hooks only for debugging purposes; otherwise, you should avoid them. Global hooks hurt system performance and cause conflicts with other applications that implement the same type of global hook.


 Hook Types

Each type of hook enables an application to monitor a different aspect of the Windows message-handling mechanism. The following sections describe the types of hooks available in Windows.


 WH_CALLWNDPROC and WH_CALLWNDPROCRET Hooks

The WH_CALLWNDPROC and WH_CALLWNDPROCRET hooks enable an application to monitor messages sent to window procedures by the SendMessage function. Windows calls a WH_CALLWNDPROC hook procedure before passing the message to the receiving window procedure, and calls the WH_CALLWNDPROCRET hook procedure after the window procedure has processed the message.

The WH_CALLWNDPROCRET hook passes the address of a CWPRETSTRUCT structure to the hook procedure. The structure contains the return value from the window procedure that processed the message, as well as the message parameters associated with the message. In previous versions of Windows, an application that needed the return value had to set a WH_CALLWNDPROC hook and subclass the window when the hook was called. However, subclassing does not work for messages set between processes.


 WH_CBT Hook

Windows calls a WH_CBT hook procedure before activating, creating, destroying, minimizing, maximizing, moving, or sizing a window; before completing a system command; before removing a mouse or keyboard event from the system message queue; before setting the input focus; or before synchronizing with the system message queue. The value the hook procedure returns determines whether Windows allows or prevents one of these operations. The WH_CBT hook is intended primarily for Windows computer-based training (CBT) applications.


 WH_DEBUG Hook

Windows calls a WH_DEBUG hook procedure before calling hook procedures associated with any other hook in the system. An application can use this hook to determine whether to allow the system to call hook procedures associated with other types of hooks.


 WH_FOREGROUNDIDLE Hook

The WH_FOREGROUNDIDLE hook enables an application to peform low priority tasks during times when its foreground thread is idle. Windows calls a WH_FOREGROUNDIDLE hook procedure when the application's foreground thread is about to become idle.


 WH_GETMESSAGE Hook

The WH_GETMESSAGE hook enables an application to monitor messages about to be returned by the GetMessage or PeekMessage function. An application uses the WH_GETMESSAGE hook to monitor mouse and keyboard input and other messages posted to a queue.


 WH_JOURNALRECORD Hook

The WH_JOURNALRECORD hook enables an application to monitor and record input events. Typically, an application uses this hook to record a sequence of mouse and keyboard events it can play back later by using the WH_JOURNALPLAYBACK hook. The WH_JOURNALRECORD hook is a global hook — it cannot be used as a thread-specific hook.


 WH_JOURNALPLAYBACK Hook

The WH_JOURNALPLAYBACK hook enables an application to insert messages into the system message queue. An application might use this hook to play back a series of mouse and keyboard events recorded earlier by using the WH_JOURNALRECORD hook. Regular mouse and keyboard input is disabled as long as a WH_JOURNALPLAYBACK hook is installed. A WH_JOURNALPLAYBACK hook is a global hook — it cannot be used as a thread-specific hook.

The WH_JOURNALPLAYBACK hook returns a time-out value. This value tells the system how many milliseconds to wait before processing the current message from the playback hook. This enables the hook to control the timing of the events it plays back.


 WH_KEYBOARD Hook

The WH_KEYBOARD hook enables an application to monitor message traffic for WM_KEYDOWN and WM_KEYUP messages about to be returned by the GetMessage or PeekMessage function. An application uses the WH_KEYBOARD hook to monitor keyboard input posted to a message queue.


 WH_MOUSE Hook

The WH_MOUSE hook enables an application to monitor mouse messages about to be returned by the GetMessage or PeekMessage function. An application uses the WH_MOUSE hook to monitor mouse input posted to a message queue.


 WH_MSGFILTER and WH_SYSMSGFILTER Hooks

The WH_MSGFILTER and WH_SYSMSGFILTER hooks enable an application to monitor messages about to be processed by a menu, scroll bar, message box, or dialog box, and to detect when a different window is about to be activated as a result of the user's pressing the ALT+TAB or ALT+ESC key combination. The WH_MSGFILTER hook can monitor only messages passed to a menu, scroll bar, message box, or dialog box created by the application that installed the hook procedure. The WH_SYSMSGFILTER hook monitors such messages for all applications.

The WH_MSGFILTER and WH_SYSMSGFILTER hooks enable an application to perform message filtering during modal loops that is equivalent to the filtering done in the main message loop. For example, an application often examines a new message in the main loop between the time it retrieves the message from the queue and the time it dispatches the message, performing special processing as appropriate. However, during a modal loop, the system retrieves and dispatches messages without allowing an application the chance to filter the messages in its main message loop. If an application installs a WH_MSGFILTER or WH_SYSMSGFILTER hook procedure, the system calls the procedure during the modal loop. For more information about modal loops, see Windows.

An application can call the WH_MSGFILTER hook directly by calling the CallMsgFilter function. By using this function, the application can use the same code to filter messages during modal loops as it uses in the main message loop. To do so, the application encapsulates the filtering operations in a WH_MSGFILTER hook procedure and calls CallMsgFilter between the calls to the GetMessage and DispatchMessage functions.

while (GetMessage(&msg, (HWND) NULL, 0, 0)) {

    if (!CallMsgFilter(&qmsg, 0))

        DispatchMessage(&qmsg);

}

The last argument of CallMsgFilter is simply passed to the hook procedure; the application can enter any value. The hook procedure, by defining a constant such as MSGF_MAINLOOP, can use this value to determine where the procedure was called from.


 WH_SHELL Hook

A Windows shell application can use the WH_SHELL hook to receive important notifications. Windows calls a WH_SHELL hook procedure when the shell application is about to be activated and when a top-level window is created or destroyed.


 Using Hooks

•	Installing and Releasing Hook Procedures

•	Monitoring System Events


 Installing and Releasing Hook Procedures

You can install a hook procedure by calling the SetWindowsHookEx function and specifying the type of hook calling the procedure, whether the procedure should be associated with all threads or with a particular thread, and a pointer to a procedure entry point.

You must place a global hook procedure in a DLL separate from the application installing the hook procedure. The installing application must have the handle of the DLL module before it can install the hook procedure. The LoadLibrary function, when given the name of the DLL, returns the handle of the DLL module. After you have the handle, you can call the GetProcAddress function to retrieve the address of the hook procedure. Finally, you use SetWindowsHookEx to install the hook procedure address in the appropriate hook chain. SetWindowsHookEx passes the module handle, a pointer to the hook-procedure entry point, and 0 for the thread identifier, indicating that the hook procedure should be associated with all threads in the system. This sequence is shown in the following example.

HOOKPROC hkprcSysMsg;

static HINSTANCE hinstDLL;

static HHOOK hhookSysMsg;

    .

    .

    .

hinstDLL = LoadLibrary((LPCTSTR) "c:\\windows\\sysmsg.dll");

hkprcSysMsg = (HOOKPROC)GetProcAddress(hinstDLL, "SysMessageProc");

hhookSysMsg = SetWindowsHookEx(WH_SYSMSGFILTER,

    hkprcSysMsg, hinstDLL, 0);

    .

    .

    .

You can release a thread-specific hook procedure (remove its address from the hook chain) by calling the UnhookWindowsHookEx function, specifying the handle of the hook procedure to release. Release a hook procedure as soon as your application no longer needs it.

You can release a global hook procedure by using UnhookWindowsHookEx, but this function does not free the DLL containing the hook procedure. This is because global hook procedures are called in the process context of every Windows-based application in the system, causing an implicit call to the LoadLibrary function for all of those processes. Because a call to the FreeLibrary function cannot be made for another process, there is then no way to free the DLL. Windows eventually frees the DLL after all processes explicitly linked to the DLL have either terminated or called FreeLibrary and all processes that called the hook procedure have resumed processing outside the DLL.

An alternative method for installing a global hook procedure is to provide an installation function in the DLL, along with the hook procedure. With this method, the installing application does not need the handle of the DLL module. By linking with the DLL, the application gains access to the installation function. The installation function can supply the DLL module handle and other details in the call to SetWindowsHookEx. The DLL can also contain a function that releases the global hook procedure; the application can call this hook-releasing function when terminating.


 Monitoring System Events

The example in this section uses a variety of thread-specific hook procedures to monitor the system for events affecting a thread. It demonstrates how to process events for the following types of hook procedures:

WH_CALLWNDPROC
WH_CBT
WH_DEBUG
WH_GETMESSAGE
WH_KEYBOARD
WH_MOUSE
WH_MSGFILTER

In this example, the user can install and remove a hook procedure by using the menu. When a hook procedure is installed and an event that is monitored by the procedure occurs, the procedure writes information about the event to the client area of the application's main window.

#define NUMHOOKS 7

/* Global variables */

typedef struct _MYHOOKDATA {

    int nType;

    HOOKPROC hkprc;

    HHOOK hhook;

} MYHOOKDATA;

MYHOOKDATA myhookdata[NUMHOOKS];

LONG APIENTRY MainWndProc(hwndMain, uMsg, wParam, lParam)

HWND hwndMain;

UINT uMsg;

UINT wParam;

LONG lParam;

{

    static BOOL afHooks[NUMHOOKS];

    int index;

    static HMENU hmenu;

    switch (uMsg) {

        case WM_CREATE:

            /* Save the menu handle. */

            hmenu = GetMenu(hwndMain);

            /*

             * Initialize structures with hook data. The menu-item

             * identifiers are defined as 0 through 6 in the

             * header file. They can be used to identify array

             * elements both here and during the WM_COMMAND

             * message.

             */

            myhookdata[IDM_CALLWNDPROC].nType = WH_CALLWNDPROC;

            myhookdata[IDM_CALLWNDPROC].hkprc = CallWndProc;

            myhookdata[IDM_CBT].nType = WH_CBT;

            myhookdata[IDM_CBT].hkprc = CBTProc;

            myhookdata[IDM_DEBUG].nType = WH_DEBUG;

            myhookdata[IDM_DEBUG].hkprc = DebugProc;

            myhookdata[IDM_GETMESSAGE].nType = WH_GETMESSAGE;

            myhookdata[IDM_GETMESSAGE].hkprc = GetMsgProc;

            myhookdata[IDM_KEYBOARD].nType = WH_KEYBOARD;

            myhookdata[IDM_KEYBOARD].hkprc = KeyboardProc;

            myhookdata[IDM_MOUSE].nType = WH_MOUSE;

            myhookdata[IDM_MOUSE].hkprc = MouseProc;

            myhookdata[IDM_MSGFILTER].nType = WH_MSGFILTER;

            myhookdata[IDM_MSGFILTER].hkprc = MessageProc;

            /* Initialize all flags in the array to FALSE. */

            memset(afHooks, FALSE, sizeof(afHooks));

            return 0;

        case WM_COMMAND:

            switch (LOWORD(wParam)) {

                /*

                 * The user selected a hook command from the menu.

                 */

                case IDM_CALLWNDPROC:

                case IDM_CBT:

                case IDM_DEBUG:

                case IDM_GETMESSAGE:

                case IDM_KEYBOARD:

                case IDM_MOUSE:

                case IDM_MSGFILTER:

                    /*

                     * Use the menu-item identifier as an index

                     * into the array of structures with hook data.

                     */

                    index = LOWORD(wParam);

                    /*

                     * If the selected type of hook procedure isn't

                     * installed yet, install it and check the

                     * associated menu item.

                     */

                    if (!afHooks[index]) {

                        myhookdata[index].hhook = SetWindowsHookEx(

                            myhookdata[index].nType,

                            myhookdata[index].hkprc,

                            (HINSTANCE) NULL, GetCurrentThreadId());

                        CheckMenuItem(hmenu, index,

                            MF_BYCOMMAND | MF_CHECKED);

                        afHooks[index] = TRUE;

                    }

                    /*

                     * If the selected type of hook procedure is

                     * already installed, remove it and remove the

                     * check mark from the associated menu item.

                     */

                    else {

                        UnhookWindowsHookEx(myhookdata[index].hhook);

                        CheckMenuItem(hmenu, index,

                            MF_BYCOMMAND | MF_UNCHECKED);

                        afHooks[index] = FALSE;

                    }

                default:

                    return (DefWindowProc(hwndMain, uMsg, wParam,

                        lParam));

            }

            break;

            .

            . /* Process other messages. */

            .

        default:

            return DefWindowProc(hwndMain, uMsg, wParam, lParam);

    }

    return NULL;

}

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

  WH_CALLWNDPROC hook procedure

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

LRESULT CALLBACK CallWndProc(nCode, wParam, lParam)

int nCode;

WPARAM wParam;

LPARAM lParam;

{

    CHAR szCWPBuf[256];

    CHAR szMsg[16];

    HDC hdc;

    static int c = 0;

    int cch;

    if (nCode < 0)  /* do not process message */

        return CallNextHookEx(myhookdata[CALLWNDPROC].hhook, nCode,

                wParam, lParam);

    /*

     * Call an application-defined function that converts a message

     * constant to a string and copies it to a buffer.

     */

    LookUpTheMessage((PMSG) lParam, szMsg);

    hdc = GetDC(hwndMain);

    switch (nCode) {

        case HC_ACTION:

            cch = wsprintf(szCWPBuf,

               "CALLWNDPROC - tsk: %ld, msg: %s, %d times   ",

                wParam, szMsg, c++);

            TextOut(hdc, 2, 15, szCWPBuf, cch);

            break;

        default:

            break;

    }

    ReleaseDC(hwndMain, hdc);

    return CallNextHookEx(myhookdata[CALLWNDPROC].hhook, nCode,

        wParam, lParam);

}

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

  WH_GETMESSAGE hook procedure

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

LRESULT CALLBACK GetMsgProc(nCode, wParam, lParam)

int nCode;

WPARAM wParam;

LPARAM lParam;

{

    CHAR szMSGBuf[256];

    CHAR szRem[16];

    CHAR szMsg[16];

    HDC hdc;

    static int c = 0;

    int cch;

    if (nCode < 0) /* do not process message */

        return CallNextHookEx(myhookdata[GETMESSAGE].hhook, nCode,

            wParam, lParam);

    switch (nCode) {

        case HC_ACTION:

            switch (wParam) {

                case PM_REMOVE:

                    lstrcpy(szRem, "PM_REMOVE");

                    break;

                case PM_NOREMOVE:

                    lstrcpy(szRem, "PM_NOREMOVE");

                    break;

                default:

                    lstrcpy(szRem, "Unknown");

                    break;

            }

            /*

             * Call an application-defined function that converts a

             * message constant to a string and copies it to a

             * buffer.

             */

            LookUpTheMessage((PMSG) lParam, szMsg);

            hdc = GetDC(hwndMain);

            cch = wsprintf(szMSGBuf,

                "GETMESSAGE - wParam: %s, msg: %s, %d times   ",

                szRem, szMsg, c++);

            TextOut(hdc, 2, 35, szMSGBuf, cch);

            break;

        default:

            break;

    }

    ReleaseDC(hwndMain, hdc);

    return CallNextHookEx(myhookdata[GETMESSAGE].hhook, nCode,

        wParam, lParam);

}

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

  WH_DEBUG hook procedure

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

LRESULT CALLBACK DebugProc(nCode, wParam, lParam)

int nCode;

WPARAM wParam;

LPARAM lParam;

{

    CHAR szBuf[128];

    HDC hdc;

    static int c = 0;

    int cch;

    if (nCode < 0)  /* do not process message */

        return CallNextHookEx(myhookdata[DEBUG].hhook, nCode,

            wParam, lParam);

    hdc = GetDC(hwndMain);

    switch (nCode) {

        case HC_ACTION:

            cch = wsprintf(szBuf,

                "DEBUG - nCode: %d, tsk: %ld, %d times   ",

                nCode,wParam, c++);

            TextOut(hdc, 2, 55, szBuf, cch);

            break;

        default:

            break;

    }

    ReleaseDC(hwndMain, hdc);

    return CallNextHookEx(myhookdata[DEBUG].hhook, nCode, wParam,

        lParam);

}

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

  WH_CBT hook procedure

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

LRESULT CALLBACK CBTProc(nCode, wParam, lParam)

int nCode;

WPARAM wParam;

LPARAM lParam;

{

    CHAR szBuf[128];

    CHAR szCode[128];

    HDC hdc;

    static int c = 0;

    int cch;

    if (nCode < 0)  /* do not process message */

        return CallNextHookEx(myhookdata[CBT].hhook, nCode, wParam,

            lParam);

    hdc = GetDC(hwndMain);

    switch (nCode) {

        case HCBT_ACTIVATE:

            lstrcpy(szCode, "HCBT_ACTIVATE");

            break;

        case HCBT_CLICKSKIPPED:

            lstrcpy(szCode, "HCBT_CLICKSKIPPED");

            break;

        case HCBT_CREATEWND:

            lstrcpy(szCode, "HCBT_CREATEWND");

            break;

        case HCBT_DESTROYWND:

            lstrcpy(szCode, "HCBT_DESTROYWND");

            break;

        case HCBT_KEYSKIPPED:

            lstrcpy(szCode, "HCBT_KEYSKIPPED");

            break;

        case HCBT_MINMAX:

            lstrcpy(szCode, "HCBT_MINMAX");

            break;

        case HCBT_MOVESIZE:

            lstrcpy(szCode, "HCBT_MOVESIZE");

            break;

        case HCBT_QS:

            lstrcpy(szCode, "HCBT_QS");

            break;

        case HCBT_SETFOCUS:

            lstrcpy(szCode, "HCBT_SETFOCUS");

            break;

        case HCBT_SYSCOMMAND:

            lstrcpy(szCode, "HCBT_SYSCOMMAND");

            break;

        default:

            lstrcpy(szCode, "Unknown");

            break;

    }

    cch = wsprintf(szBuf, "CBT - nCode: %s, tsk: %ld, %d times   ",

        szCode, wParam, c++);

    TextOut(hdc, 2, 75, szBuf, cch);

    ReleaseDC(hwndMain, hdc);

    return CallNextHookEx(myhookdata[CBT].hhook, nCode, wParam,

        lParam);

}

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

  WH_MOUSE hook procedure

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

LRESULT CALLBACK MouseProc(nCode, wParam, lParam)

int nCode;

WPARAM wParam;

LPARAM lParam;

{

    CHAR szBuf[128];

    CHAR szMsg[16];

    HDC hdc;

    static int c = 0;

    int cch;

    if (nCode < 0)  /* do not process the message */

        return CallNextHookEx(myhookdata[MOUSE].hhook, nCode,

            wParam, lParam);

    /*

     * Call an application-defined function that converts a message

     * constant to a string and copies it to a buffer.

     */

    LookUpTheMessage((PMSG) lParam, szMsg);

    hdc = GetDC(hwndMain);

    cch = wsprintf(szBuf,

        "MOUSE - nCode: %d, msg: %s, x: %d, y: %d, %d times   ",

        nCode, szMsg, LOWORD(lParam), HIWORD(lParam), c++);

    TextOut(hdc, 2, 95, szBuf, cch);

    ReleaseDC(hwndMain, hdc);

    return CallNextHookEx(myhookdata[MOUSE].hhook, nCode, wParam,

        lParam);

}

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

  WH_KEYBOARD hook procedure

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

LRESULT CALLBACK KeyboardProc(nCode, wParam, lParam)

int nCode;

WPARAM wParam;

LPARAM lParam;

{

    CHAR szBuf[128];

    HDC hdc;

    static int c = 0;

    int cch;

    if (nCode < 0)  /* do not process message */

        return CallNextHookEx(myhookdata[KEYBOARD].hhook, nCode,

            wParam, lParam);

    hdc = GetDC(hwndMain);

    cch = wsprintf(szBuf, "KEYBOARD - nCode: %d, vk: %d, %d times ",

        nCode, wParam, c++);

    TextOut(hdc, 2, 115, szBuf, cch);

    ReleaseDC(hwndMain, hdc);

    return CallNextHookEx(myhookdata[KEYBOARD].hhook, nCode, wParam,

        lParam);

}

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

  WH_MSGFILTER hook procedure

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

LRESULT CALLBACK MessageProc(nCode, wParam, lParam)

int nCode;

WPARAM wParam;

LPARAM lParam;

{

    CHAR szBuf[128];

    CHAR szMsg[16];

    CHAR szCode[32];

    HDC hdc;

    static int c = 0;

    int cch;

    if (nCode < 0)  /* do not process message */

        return CallNextHookEx(myhookdata[MSGFILTER].hhook, nCode,

            wParam, lParam);

    switch (nCode) {

        case MSGF_DIALOGBOX:

            lstrcpy(szCode, "MSGF_DIALOGBOX");

            break;

        case MSGF_MENU:

            lstrcpy(szCode, "MSGF_MENU");

            break;

        case MSGF_SCROLLBAR:

            lstrcpy(szCode, "MSGF_SCROLLBAR");

            break;

        case MSGF_NEXTWINDOW:

            lstrcpy(szCode, "MSGF_NEXTWINDOW");

            break;

        default:

            wsprintf(szCode, "Unknown: %d", nCode);

            break;

    }

    /*

     * Call an application-defined function that converts a message

     * constant to a string and copies it to a buffer.

     */

    LookUpTheMessage((PMSG) lParam, szMsg);

    hdc = GetDC(hwndMain);

    cch = wsprintf(szBuf,

        "MSGFILTER  nCode: %s, msg: %s, %d times    ",

        szCode, szMsg, c++);

    TextOut(hdc, 2, 135, szBuf, cch);

    ReleaseDC(hwndMain, hdc);

    return CallNextHookEx(myhookdata[MSGFILTER].hhook, nCode,

        wParam, lParam);

}


 Hook Reference

The following functions and messages are associated with hooks.


 Hook Functions

Following are the functions used with hooks.

CallMsgFilter
CallNextHookEx
CallWndProc
CBTProc
DebugProc
GetMsgProc
JournalPlaybackProc
JournalRecordProc
KeyboardProc
MessageProc
MouseProc
SetWindowsHookEx
ShellProc
SysMsgProc
UnhookWindowsHookEx

Obsolete or Deleted Functions

DefHookProc
SetWindowsHook
UnhookWindowsHook


 Hook Messages

Following are the messages used with hooks.

WM_QUEUESYNC


 Icons

An icon is a picture that consists of a bitmapped image combined with a mask to create transparent areas in the picture. This overview describes creating, displaying, destroying, and duplicating icons.


 About Icons

Windows uses icons throughout the user interface to represent objects such as files, printers, applications, and windows. The icon functions in the Microsoft® Win32® application programming interface (API) enable applications to create, load, display, arrange, and destroy icons.

The operating system provides a set of standard icons that are available for any application to use at any time. The Windows 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.

An application can retrieve the image for a cursor by using the GetIconInfo function, and can draw it by using the DrawIconEx function. To draw the default image for a cursor, specify the DI_COMPAT flag in the call to DrawIconEx. If you do not specify the DI_COMPAT flag, DrawIconEx draws the cursor using the image that the user specified.

Custom icons are designed for use in a particular application and can be any design the developer defines. Following are several custom icons.


 The Iconic 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 Creation

Standard icons are predefined in Win32, 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, developers typically use a graphics application and include the icon as a resource in the application's resource-definition file. At run time, an application can call LoadIcon or LoadImage to retrieve the handle of the icon. An icon resource contains data for several different display devices. LoadIcon and LoadImage automatically select the most appropriate data 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 Resources.


 Icon Display

Once an application has loaded an icon, it can use the DrawIcon or DrawIconEx functions to draw the icon.

When registering a window class, an application can assign one or two icons to the class, depending on the operating system version. A class icon is a picture that the system uses to represent a window of a particular class. For more information about class icons, see Window Classes.


 Icon Destruction

When an application no longer needs an icon it created by using the CreateIconIndirect (or CreateIcon) function, it should destroy the icon. The DestroyIcon function destroys the icon handle and frees any memory used by the icon. Applications should use this function only for icons created with CreateIconIndirect; it is not necessary to destroy other icons.


 Icon Duplication

The CopyIcon function copies an icon handle. This enables an application or DLL to get its own handle for an icon owned by another module. Then, if the other module is freed, the application that copied the icon will still be able to use the icon.

The CopyImage function creates a new icon based on the specified source icon. The new icon can be larger or smaller than the source icon.

For information about adding, removing, or replacing icon resources in executable (.EXE) files, see Resources.


 Using Icons

•	Creating an icon

•	Displaying an icon

•	Using icon functions to create a mousetrap

•	Sharing icon resources


 Creating an Icon

To use an icon, your application must get the handle of 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
For information about full-color bitmaps, see Bitmaps and Colors.

Before closing, your application must use DestroyIcon to destroy any icon it created by using CreateIcon. 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 of display context */

DrawIcon(hdc, 10, 20, hIcon1);

Windows 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 of 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))); /* new */

For more information about window classes, see Window Classes.


 Using Icon Functions to Create a Mousetrap

The following example applies to operating system versions earlier than 4.0. It uses IsIconic, LoadIcon, and several cursor and timer functions to create a simple mousetrap. The example uses the cursor and timer functions to monitor the location of the cursor at 10-second intervals. If the cursor location has not changed in the last 10 seconds and the application's main window is minimized, the application changes the cursor shape and moves the cursor to the icon.

HICON hIcon1;              /* icon handle                */

POINT ptOld;               /* previous cursor location   */

HCURSOR hCurs1;            /* cursor handle              */

HINSTANCE hinstance;       /* handle of current instance */

hCurs1 = LoadCursor(hinstance, MAKEINTRESOURCE(220));

.

. /* Fill in the window class structure. */

.

WNDCLASS  wc;

wc.hIcon = LoadIcon(hinstance, MAKEINTRESOURCE(470));

wc.hCursor = LoadCursor(hinstance, MAKEINTRESOURCE(240));

.

. /*

.  * 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;            /* device context handle    */

    POINT pt;           /* current cursor location  */

    RECT rc;            /* iconized window location */

    switch (message) {

         .

         . /* Process other messages here. */

         .

        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_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 the timer. */

            KillTimer(hwnd, IDT_CURSOR);

            PostQuitMessage(0);

            break;

                .

                . /* Process other messages here. */

                .

    }             /* ends switch (message) */

An example for a similar mousetrap is included in Cursors. That example uses CreateIcon to create the class icon.


 Sharing Icon Resources

The following code uses the functions CreateIconFromResourceEx, DrawIcon, and LookupIconIdFromDirectoryEx, and several of the resource functions, to create an icon handle based on icon data from another executable file. Then, it displays the icon in a window.

HICON hIcon1;       /* icon handle                */

HINSTANCE hExe;     /* handle to loaded .EXE file */

HRSRC hResource;    /* handle for FindResource    */

HRSRC hMem;         /* handle for LoadResource    */

BYTE *lpResource;   /* address of resource data   */

int nID;            /* ID of resource that best

                       fits current screen        */

HDC hdc;        /* handle of 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 functions and messages are associated with icons.


 Icon Functions

Following are the functions used with icons.

ArrangeIconicWindows
CopyIcon
CreateIcon
CreateIconFromResource
CreateIconIndirect
DestroyIcon
DrawIcon
DrawIconEx
GetIconInfo
IsIconic
LoadIcon
LookupIconIdFromDirectory
OpenIcon


 Icon Messages

Following are the messages used with icons.

WM_ERASEBKGND
WM_ICONERASEBKGND
WM_PAINTICON


 Keyboard Accelerators

In Microsoft® Windows®, a keyboard accelerator (or, simply, accelerator) is a keystroke or combination of keystrokes that generates a WM_COMMAND or WM_SYSCOMMAND message for an application.


 About Keyboard Accelerators

Accelerators are closely related to menus — both provide the user with access to an application's command set. Typically, users rely on an application's menus to learn the command set and then switch over to using accelerators as they become more proficient with the application. Accelerators provide faster, more direct access to commands than menus do. At a minimum, an application should provide accelerators for the more commonly used commands. Although accelerators typically generate commands that exist as menu items, they can also generate commands that have no equivalent menu items.


 Accelerator Tables

An accelerator table consists of an array of ACCEL structures, each defining an individual accelerator. Each ACCEL structure includes the following information:

•	The accelerator's keystroke combination.

•	The accelerator's identifier.

•	Various flags. This includes one that specifies whether Windows is to provide visual feedback by highlighting the corresponding menu item, if any, when the accelerator is used

To process accelerator keystrokes for a given thread, the developer must call the TranslateAccelerator function in the message loop associated with the thread's message queue. The TranslateAccelerator function monitors keyboard input to the message queue, checking for key combinations that match an entry in the accelerator table. When TranslateAccelerator finds a match, it translates the keyboard input (that is, the WM_KEYUP and WM_KEYDOWN messages) into a WM_COMMAND or WM_SYSCOMMAND message and then sends the message to the window procedure of the specified window. The following illustration shows how accelerators are processed.

The WM_COMMAND message includes the identifier of the accelerator that caused TranslateAccelerator to generate the message. The window procedure examines the identifier to determine the source of the message and then processes the message accordingly.

Accelerator tables exist at two different levels in Windows. Windows 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.

Windows also maintains accelerator tables for each application. An application can define any number of accelerator tables for use with its own windows. A unique 32-bit handle (HACCEL) identifies each table. However, only one accelerator table can be active at a time for a given thread. The handle of 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 of 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.

Windows automatically destroys accelerator tables loaded by LoadAccelerators. An accelerator table created by CreateAcceleratorTable must be destroyed before an application closes; otherwise, the table continues to exist in memory after the application has closed. An accelerator table is destroyed by calling the DestroyAcceleratorTable function.

An existing accelerator table can be copied and modified. The existing accelerator table is copied by using the CopyAcceleratorTable function. After the copy is modified, a handle of the new accelerator table is retrieved by calling CreateAcceleratorTable. Finally, the handle is passed to TranslateAccelerator to activate the new table.


 Accelerator Keystroke Assignments

An ASCII character code or a virtual-key code can be used to define the accelerator. An ASCII character code makes the accelerator case sensitive. The ASCII "C" character can define the accelerator as ALT+c rather than ALT+C. Case-sensitive accelerators can, however, be confusing to use. For example, the ALT+C accelerator will be generated if the CAPS LOCK key is down or if the SHIFT key is down, but not if both are down.

Typically, accelerators don't need to be case sensitive, so most applications use virtual-key codes for accelerators rather than ASCII character codes. .

Avoid accelerators that conflict with an application's menu mnemonics, because the accelerator overrides the mnemonic, which can confuse the user. For more information about menu mnemonics, see Menus (Windows NT).

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 Windows 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 System menu for a document window.
ALT+PRINT SCREEN	Copies an image in the active window onto the clipboard.
ALT+SPACEBAR	Opens the System menu for an application window.
ALT+TAB	Switches to the next application.
CTRL+ESC	Switches to Windows Task List.
CTRL+F4	Closes the active group or document window.
F1	Starts Help if the application has Help.
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 Windows 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 (Windows NT).

An accelerator that corresponds to a menu item should be included in the text of the menu item.


 Using Keyboard Accelerators

•	Using an accelerator-table resource

•	Using an accelerator table created at run time


 Using an Accelerator-Table Resource

The most common way to add accelerator support to a Windows-based application is to include an accelerator-table resource with the application's executable file and then load the resource at run time. The steps involved in using an accelerator-table resource are as follows:

•	Create an accelerator table in a resource-definition file. Compile it and add the resulting resource to your application's executable file.

•	Include a call to the LoadAccelerators function to load the accelerator-table resource and receive a handle of the accelerator table.

•	Add the TranslateAccelerator function to the message loop associated with the accelerator table.

•	Process the WM_COMMAND messages generated when the user uses the accelerator.


 Creating the Accelerator-Table Resource

You create an accelerator-table resource by using the ACCELERATORS statement in your application's resource-definition file. You must assign a name or resource identifier to the accelerator table, preferably unlike that of any other resource. Windows 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 Windows 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, Windows 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 of 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 of 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 of the window that is to receive the WM_COMMAND messages, the handle of the accelerator table used to translate accelerators, and a pointer to an MSG structure containing a message from the queue. The following example shows how to call TranslateAccelerator from within a message loop.

while (GetMessage(&msg, (HWND) NULL, 0, 0)) {

    /* Check for accelerator keystrokes. */

    if (!TranslateAccelerator(

            hwndMain,      /* handle of receiving window    */

            haccel,        /* handle of active accel. table */

            &msg)) {       /* address of message data       */

        TranslateMessage(&msg);

        DispatchMessage(&msg);

    }

}


 Processing WM_COMMAND Messages

When an accelerator is used, the window specified in the TranslateAccelerator function receives a WM_COMMAND or WM_SYSCOMMAND message. The low-order word of the wParam parameter contains the identifier of the accelerator. The window procedure examines the identifier to determine the source of the WM_COMMAND message and process the message accordingly.

Typically, if an accelerator corresponds to a menu item in the application, the accelerator and menu item are assigned the same identifier. If you need to know whether a given WM_COMMAND message was generated by an accelerator or by a menu item, you can examine the high-order word of the wParam parameter. If an accelerator generated the message, the high-order word is 1; if a menu item generated the message, the high-order word is 0.


 Destroying the Accelerator-Table Resource

Windows automatically destroys accelerator-table resources loaded by the LoadAccelerators function, removing the resource from memory after the application closes.


 Creating Accelerators for Font Attributes

The example in this section shows how to perform the following tasks:

•	Create an accelerator-table resource.

•	Load the accelerator table at run time.

•	Translate accelerators in a message loop.

•	Process WM_COMMAND messages generated by the accelerators.

These tasks are demonstrated in the context of an application that includes a Character menu and corresponding accelerators that allow the user to select attributes of the current font.

The following portion of a resource-definition file defines the Character menu and the associated accelerator table. Note that the menu items show the accelerator keystrokes and that each accelerator has the same identifier as its associated menu item.

#include <windows.h>

#include "acc.h"

MainMenu MENU

BEGIN

    POPUP   "&Character"

    BEGIN

        MENUITEM    "&Regular\tF5",         IDM_REGULAR

        MENUITEM    "&Bold\tCtrl+B",        IDM_BOLD

        MENUITEM    "&Italic\tCtrl+I",      IDM_ITALIC

        MENUITEM    "&Underline\tCtrl+U",   IDM_ULINE

    END

END

FontAccel ACCELERATORS

BEGIN

    VK_F5,  IDM_REGULAR,    VIRTKEY

    "B",    IDM_BOLD,       CONTROL, VIRTKEY

    "I",    IDM_ITALIC,     CONTROL, VIRTKEY

    "U",    IDM_ULINE,      CONTROL, VIRTKEY

END

The following sections from the application's source file show how to implement the accelerators.

HWND hwndMain;      /* handle of main window          */

HANDLE hinstAcc;    /* handle of application instance */

int WINAPI WinMain(hinst, hinstPrev, lpCmdLine, nCmdShow)

HINSTANCE hinst;

HINSTANCE hinstPrev;

LPSTR lpCmdLine;

int nCmdShow;

{

    MSG msg;            /* application messages              */

    HACCEL haccel;      /* handle of accelerator table       */

    .

    . /* Perform the initialization procedure. */

    .

    /* Create a main window for this application instance.  */

    hwndMain = CreateWindowEx(0L, "MainWindowClass",

        "Sample Application", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT,

        CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL,

        hinst, NULL );

    /* If a window cannot be created, return "failure." */

    if (!hwndMain)

        return FALSE;

    /* Make the window visible and update its client area. */

    ShowWindow(hwndMain, nCmdShow);

    UpdateWindow(hwndMain);

    /* Load the accelerator table. */

    haccel = LoadAccelerators(hinstAcc, "FontAccel");

    if (haccel == NULL)

        HandleAccelErr(ERR_LOADING);     /* application defined */

    /*

     * Get and dispatch messages until a WM_QUIT message is

     * received.

     */

    while (GetMessage(&msg, NULL, NULL, NULL)) {

        /* Check for accelerator keystrokes. */

        if (!TranslateAccelerator(

                hwndMain,      /* handle of receiving window    */

                haccel,        /* handle of active accel. table */

                &msg)) {       /* address of message data       */

            TranslateMessage(&msg);

            DispatchMessage(&msg);

        }

    }

    return msg.wParam;

}

LRESULT APIENTRY MainWndProc(hwndMain, uMsg, wParam, lParam)

HWND hwndMain;

UINT uMsg;

WPARAM wParam;

LPARAM lParam;

{

    BYTE fbFontAttrib;        /* array of font-attribute flags  */

    static HMENU hmenu;       /* handle of 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 application programming interface (API) allows you to create accelerator tables at run time. The steps involved in creating and using an accelerator table at run time are as follows:

•	Define the accelerators by filling an array of ACCEL structures, and then create an accelerator table by passing the array to the CreateAcceleratorTable function.

•	Activate the accelerator table and process WM_COMMAND messages generated by the accelerators.

•	Destroy the accelerator table before the application closes.


 Creating the Accelerator Table

The first step in creating an accelerator table at run time is filling an array of ACCEL structures. Each structure in the array defines an accelerator in the table. An accelerator's definition includes its flags, its key, and its identifier. The ACCEL structure has the following form.

typedef struct tagACCEL { // accl

    BYTE   fVirt;

    WORD   key;

    WORD   cmd;

} ACCEL;

You define an accelerator's keystroke by specifying an ASCII character code or a virtual-key code in the key member of the ACCEL structure. If you specify a virtual-key code, you must first include the FVIRTKEY flag in the fVirt member; otherwise, Windows interprets the code as an ASCII character code. You can include the FCONTROL, FALT, or FSHIFT flag, or all three, to combine the CTRL, ALT, or SHIFT key with the keystroke.

To create the accelerator table, pass the address of the array of ACCEL structures to the CreateAcceleratorTable function. CreateAcceleratorTable creates the accelerator table and returns the handle of the table.


 Processing Accelerators

The process of loading and calling accelerators provided by an accelerator table created at run time is the same as processing those provided by an accelerator-table resource. For more information, see Loading the Accelerator-Table Resource through Processing WM_COMMAND Messages.


 Destroying the Accelerator Table

Before an application closes, it must destroy accelerator tables created at run time. You can destroy an accelerator table and remove it from memory by passing the table's handle to the DestroyAcceleratorTable function.


 Creating User-Editable Accelerators

This example shows how to construct a dialog box that allows the user to change the accelerator associated with a menu item. The dialog box consists of a combo box containing menu items, a combo box containing the names of keys, and check boxes for selecting the CTRL, ALT, and SHIFT keys. The following illustration shows the dialog box.

The following example shows how the dialog box is defined in the resource-definition file.

EdAccelBox DIALOG 5, 17, 193, 114

STYLE DS_MODALFRAME | WS_POPUP | WS_VISIBLE | WS_CAPTION

CAPTION "Edit Accelerators"

BEGIN

    COMBOBOX        IDD_MENUITEMS, 10, 22, 52, 53,

                        CBS_SIMPLE | CBS_SORT | WS_VSCROLL |

                        WS_TABSTOP

    CONTROL         "Control", IDD_CNTRL, "Button",

                        BS_AUTOCHECKBOX | WS_TABSTOP,

                        76, 35, 40, 10

    CONTROL         "Alt", IDD_ALT, "Button",

                        BS_AUTOCHECKBOX | WS_TABSTOP,

                        76, 48, 40, 10

    CONTROL         "Shift", IDD_SHIFT, "Button",

                        BS_AUTOCHECKBOX | WS_TABSTOP,

                        76, 61, 40, 10

    COMBOBOX        IDD_KEYSTROKES, 124, 22, 58, 58,

                        CBS_SIMPLE | CBS_SORT | WS_VSCROLL |

                        WS_TABSTOP

    PUSHBUTTON      "Ok", IDOK, 43, 92, 40, 14

    PUSHBUTTON      "Cancel", IDCANCEL, 103, 92, 40, 14

    LTEXT           "Select Item:", 101, 10, 12, 43, 8

    LTEXT           "Select Keystroke:", 102, 123, 12, 60, 8

END

The 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 26

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.

/* Global variables */

HWND hwndMain;      /* handle of main window          */

HANDLE hinstAcc;    /* handle of application instance */

HACCEL haccel;      /* handle of accelerator table    */

.

.

.

/* Dialog-box procedure */

LRESULT CALLBACK EdAccelProc(hwndDlg, uMsg, wParam, lParam)

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 of control window        */

    static HMENU hmenu;     /* handle of "Character" menu      */

    PCHAR pch, pch2;        /* pointers for string copying     */

    WORD wVKCode;           /* accelerator virtual-key code    */

    BYTE fAccelFlags;       /* fVirt flags for ACCEL structure */

    LPACCEL lpaccelNew;     /* address of new accel. table     */

    HACCEL haccelOld;       /* handle of old accel. 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 of the menu-item combo box. */

            hwndCtl = GetDlgItem(hwndDlg, IDD_MENUITEMS);

            /*

             * The application's menu bar contains a "Character"

             * submenu whose items have accelerators associated

             * with them. Get the handle of the "Character"

             * submenu (its position within the main menu is 2),

             * and count the number of items it has.

             */

            hmenu = GetSubMenu(GetMenu(hwndMain), 2);

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

                     * item 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 menu-

                     * item 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 functions and messages are associated with keyboard accelerators.


 Keyboard Accelerator Functions

Following are the functions used with accelerators.

CopyAcceleratorTable
CreateAcceleratorTable
DestroyAcceleratorTable
LoadAccelerators
TranslateAccelerator


 Keyboard Accelerator Messages

Following are the messages used with accelerators.

WM_COMMAND
WM_INITMENU
WM_INITMENUPOPUP
WM_MENUCHAR
WM_MENUSELECT
WM_SYSCHAR
WM_SYSCOMMAND


 Keyboard Input

This overview describes how Windows generates keyboard input and how an application receives and processes that input.


 About Keyboard Input

All applications written for Microsoft® Windows® should accept user input from the keyboard as well as from the mouse. A Windows-based application receives keyboard input in the form of messages posted to its windows.


 Keyboard Input Model

Windows provides device-independent keyboard support for applications by installing a keyboard device driver appropriate for the current keyboard. Windows 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 Windows 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. Windows 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 for Windows.


 Keyboard Focus and Activation

Windows 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. Windows shares the keyboard among all windows on the display by shifting the keyboard focus, at the user's direction, from one window to another. The window that has the keyboard focus receives (from the message queue of the thread that created it) all keyboard messages until the focus changes to a different window.

A thread can call the GetFocus function to determine which of its windows (if any) currently has the keyboard focus. A thread can give the keyboard focus to one of its windows by calling the SetFocus function. When the keyboard focus changes from one window to another, the system sends a WM_KILLFOCUS message to the window that has lost the focus, and then sends a WM_SETFOCUS message to the window that has gained the focus.

The concept of keyboard focus is related to that of the active window. The active window is the top-level window the user is currently working with. The window with the keyboard focus is either the active window, or a child window of the active window. So the user can easily identify the active window, the system places it at the top of the Z order and makes its title bar (if it has one) and border highlighted.

The user can activate a top-level window by clicking it, selecting it using the ALT+TAB or ALT+ESC key combination, or selecting if from Task List. A thread can activate a top-level window by using the SetActiveWindow function. It can determine whether a top-level window it created is active by using the GetActiveWindow function.

When one window is deactivated and another activated, Windows sends the WM_ACTIVATE message first to the window being deactivated, then to the window being activated. The low-order word of the wParam parameter is zero if the window is being deactivated and nonzero if it is being activated. When the default window procedure receives the WM_ACTIVATE message, it sets the keyboard focus to the active window.


 Keystroke Messages

Pressing a key results in a WM_KEYDOWN or WM_SYSKEYDOWN message being placed in the thread message queue associated with the window that has the keyboard focus. Releasing a key results in a WM_KEYUP or WM_SYSKEYUP message being placed in the queue.

Key-up and key-down messages typically occur in pairs, but if the user holds down a key long enough to start the keyboard's automatic repeat feature, the system generates a number of WM_KEYDOWN or WM_SYSKEYDOWN messages in a row. It then generates a single WM_KEYUP or WM_SYSKEYUP message when the user releases the key.


 System and Nonsystem Keystrokes

Windows 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 Windows rather than by an application. Windows uses them to provide its built-in keyboard interface to menus and to allow the user to control which window is active. System keystroke messages are generated when the user types a key in combination with the ALT key, or when the user types and no window has the keyboard focus (for example, when the active application is minimized). In this case, the messages are posted to the message queue associated with the active window.

Nonsystem keystroke messages are for use by application windows; the DefWindowProc function does nothing with them. A window procedure can discard any nonsystem keystroke messages that it does not need.


 Virtual-Key Codes Described

The wParam parameter of a keystroke message contains the virtual-key code of the key that was pressed or released. A window procedure processes or ignores a keystroke message, depending on the value of the virtual-key code.

A typical window procedure processes only a small subset of the keystroke messages that it receives and ignores the rest. For example, a window procedure might process only WM_KEYDOWN keystroke messages, and only those that contain virtual-key codes for the cursor movement keys, shift keys (also called control keys), and function keys. A typical window procedure does not process keystroke messages from character keys. Instead, it uses the TranslateMessage function to convert the message into character messages. For more information about TranslateMessage and character messages, see Character Messages.


 Keystroke Message Flags

The lParam parameter of a keystroke message contains additional information about the keystroke that generated the message. This information includes the repeat count, the scan code, the extended-key flag, the context code, the previous key-state flag, and the transition-state flag. The following illustration shows the locations of these flags and values in the lParam parameter:

An application can use the following values to manipulate the keystroke flags:

Value	Meaning
KF_ALTDOWN	Manipulates the ALT key flag, which indicated if the ALT key is pressed.
KF_DLGMODE	Manipulates the dialog mode flag, which indicates whether a dialog box is active.
KF_EXTENDED	Manipulates the extended key flag.
KF_MENUMODE	Manipulates the menu mode flag, which indicates whether a menu is active.
KF_REPEAT	Manipulates the repeat count.
KF_UP	Manipulates the transition state flag.
Repeat Count

You can check the repeat count to determine whether a keystroke message represents more than one keystroke. The system increments the count when the keyboard generates WM_KEYDOWN or WM_SYSKEYDOWN messages faster than an application can process them. This often occurs when the user holds down a key long enough to start the keyboard's automatic repeat feature. Instead of filling the system message queue with the resulting key-down messages, the system combines the messages into a single key down message and increments the repeat count. Releasing a key cannot start the automatic repeat feature, so the repeat count for WM_KEYUP and WM_SYSKEYUP messages is always set to 1.

Scan Code

The scan code is the value that the keyboard hardware generates when the user presses a key. It is a device-dependent value that identifies the key pressed, as opposed to the character represented by the key. An application typically ignores scan codes. Instead, it uses the device-independent virtual-key codes to interpret keystroke messages.

Extended-Key Flag

The extended-key flag indicates whether the keystroke message originated from one of the additional keys on the enhanced keyboard. The extended keys consist of the ALT and CTRL keys on the right-hand side of the keyboard; the INS, DEL, HOME, END, PAGE UP, PAGE DOWN and arrow keys in the clusters to the left of the numeric keypad; the NUM LOCK key; the BREAK (CTRL+PAUSE) key; the PRINT SCRN key; and the divide (/) and ENTER keys in the numeric keypad. The extended-key flag is set if the key is an extended key.

Context Code

The context code indicates whether the ALT key was down when the keystroke message was generated. The code is 1 if the ALT key was down and 0 if it was up.

Previous Key-State Flag

The previous key-state flag indicates whether the key that generated the keystroke message was previously up or down. It is 1 if the key was previously down and 0 if the key was previously up. You can use this flag to identify keystroke messages generated by the keyboard's automatic repeat feature. This flag is set to 1 for WM_KEYDOWN and WM_SYSKEYDOWN keystroke messages generated by the automatic repeat feature. It is always set to 0 for WM_KEYUP and WM_SYSKEYUP messages.

Transition-State Flag

The transition-state flag indicates whether pressing a key or releasing a key generated the keystroke message. This flag is always set to 0 for WM_KEYDOWN and WM_SYSKEYDOWN messages; it is always set to 1 for WM_KEYUP and WM_SYSKEYUP messages.


 Character Messages

Keystroke messages provide a lot of information about keystrokes, but they don't provide character codes for character keystrokes. To retrieve character codes, an application must include the TranslateMessage function in its thread message loop. TranslateMessage passes a WM_KEYDOWN or WM_SYSKEYDOWN message to the keyboard layout. The layout examines the message's virtual-key code and, if it corresponds to a character key, provides the character code equivalent (taking into account the state of the SHIFT and CAPS LOCK keys). It then generates a character message that includes the character code and places the message at the top of the message queue. The next iteration of the message loop removes the character message from the queue and dispatches the message to the appropriate window procedure.


 Nonsystem Character Messages

A window procedure can receive four different character messages, including WM_CHAR, WM_DEADCHAR, WM_SYSCHAR, and WM_SYSDEADCHAR. The TranslateMessage function generates a WM_CHAR or WM_DEADCHAR message when it processes a WM_KEYDOWN message. Similarly, it generates a WM_SYSCHAR or WM_SYSDEADCHAR message when it processes a WM_SYSKEYDOWN message.

An application that processes keyboard input typically ignores all but the WM_CHAR message, passing any other messages to the DefWindowProc function. Windows 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 from the Windows character set. For more information about Unicode, 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 about the contents of the lParam parameter, 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, Windows 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

Windows includes several special purpose functions that translate scan codes, character codes, and virtual-key codes provided by various keystroke messages. These functions include MapVirtualKey, ToAscii, ToUnicode, and VkKeyScan.


 Hot-Key Support

Windows 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 of the window to receive the message, and the identifier of the hot key. When the user presses the hot key, a WM_HOTKEY message is placed in the message queue of the thread that created the given window. The wParam parameter of the message contains the identifier of the hot key. The application can define multiple hot keys for a thread, but each hot key in the thread must have a unique identifier. Before the application terminates, it should use the UnregisterHotKey function to destroy the hot key.

Applications can use a hot key control to make it easy for the user to choose a hot key. Hot key controls are typically used to define a hot key that activates a window; they do not use the RegisterHotKey and UnregisterHotKey functions. Instead, an application that uses a hot key control typically sends the WM_SETHOTKEY message to set the hot key. Whenever the user presses the hot key, the system sends a WM_SYSCOMMAND message specifying SC_HOTKEY. For more information about hot key controls, see Hot-Key Controls.


 Languages, Locales, and Keyboard Layouts

A language is a natural language, such as English, French, and Japanese. A sublanguange is a variant of a natural language that is spoken in a specific geographical region, such as the English sublanguages spoken in Great Britian and the United States. Win32-based applications use values, called locales, to uniquely identify languages and sublanguages. Applications typically use locales to set the language in which input and output is processed. Setting the locale for the keyboard, for example, affects the character values generated by the keyboard. Setting the locale for the display or printer affects the glyphs displayed or printed. Applications set the locale for a keyboard by loading and using keyboard layouts. They set the locale for a display or printer by selecting a font that supports the given locale.

A keyboard layout not only specifies the physical position of the keys on the keyboard but also determines the character values generated by pressing those keys. Each layout has an associated locale which 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 which identifies of the layout and language. The low word of the handle is a language identifier. The high word is a device handle, specifying the physical layout, or is zero, indicating a default physical layout. The user can associate any input language with a given physical layout. For example, an English-speaking user who very occasionally works in French can set the input language of the keyboard to French without changing the physical layout of the keyboard. This means the user can enter text in French using the familiar English layout.

Applications are generally not expected to manipulate input languages directly. Instead, the user sets up language and layout combinations, then switches among them. When the user clicks into text marked with a different language, the application calls the ActivateKeyboardLayout function to activate the user's default layout for that language. If the user edits text in a language which is not in the active list, the application can call the LoadKeyboardLayout function with the language to get a layout based on that language.

The ActivateKeyboardLayout function sets the input language for the current task. The hkl parameter can be either the handle of the keyboard layout or a zero-extended language identifier. Keyboard layout handles can be obtained from the LoadKeyboardLayout or GetKeyboardLayoutList function. The HKL_NEXT and HKL_PREV values can also be used to select the next or previous keyboard. For some operating systems, the KLF_UNLOADPREVIOUS value has no meaning and is ignored.

The GetKeyboardLayoutName function retrieves the name of the active keyboard layout for the calling thread. If an application creates the active layout using the LoadKeyboardLayout function, GetKeyboardLayoutName retrieves the same string used to create the layout. Otherwise, the string is the primary language identifier correspoding 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 use the make the layout immediately active for the current thread by using the KLF_ACTIVATE value. An application can use the KLF_REORDER value to reorder the layouts without also specifying the KLF_ACTIVATE value. Applications should always use the KLF_SUBSTITUTE_OK value when loading keyboard layouts to ensure that the user's preference, if any, is selected. For some operating systems, the KLF_UNLOADPREVIOUS value is ignored.

For multilingual support, the LoadKeyboardLayout function provides the KLF_REPLACELANG and KLF_NOTELLSHELL flags. The KLF_REPLACELANG flag directs the function to replace an existing keyboard layout without changing associated the language. Attempting to replace an existing layout using the same language identifier but without specifying KLF_REPLACELANG is an error. The KLF_NOTELLSHELL flag prevents the function from notifying the shell when a keyboard layout is added or replaced. This is useful for applications that add multiple layouts in a consecutive series of calls. This flag should be used in all but the last call.

The UnloadKeyboardLayout function is restricted in that it cannot unload the system default input language. This ensures that the user always has one layout available for enter text using the same character set as used by the shell and file system.


 Using Keyboard Input

A window receives keyboard input in the form of keystroke messages and character messages. The message loop associated with the window must include code to translate keystroke messages into the corresponding character messages. If the window displays keyboard input in its client area, it should create and display a caret to indicate the position where the next character will be entered. The following sections describe the code involved in receiving, processing, and displaying keyboard input.

•	Processing Keystroke Messages

•	Translating Character Messages

•	Processing Character Messages

•	Using the Caret

•	Displaying Keyboard Input


 Processing Keystroke Messages

The window procedure of the window that has the keyboard focus receives keystroke messages when the user types at the keyboard. The keystroke messages are WM_KEYDOWN, WM_KEYUP, WM_SYSKEYDOWN, and WM_SYSKEYUP. A typical window procedure ignores all keystroke messages except WM_KEYDOWN. Windows 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 noncharacter keystrokes. */

                .

                default:

                    break;

            }


 Translating Character Messages

Any thread that receives character input from the user must include the TranslateMessage function in its message loop. This function examines the virtual-key code of a keystroke message and, if the code corresponds to a character, places a character message into the message queue. The character message is removed and dispatched on the next iteration of the message loop; the wParam parameter of the message contains the character code.

In general, a thread's message loop should use the TranslateMessage function to translate every message, not just virtual-key messages. Although TranslateMessage has no effect on other types of messages, it guarantees that keyboard input is translated correctly. The following example shows how to include the TranslateMessage function in a typical thread message loop.

while (GetMessage(&msg, (HWND) NULL, 0, 0)) {

    if (TranslateAccelerator(hwndMain, haccl, &msg) == 0) {

        TranslateMessage(&msg);

        DispatchMessage(&msg);

    }

}


 Processing Character Messages

A window procedure receives a character message when the TranslateMessage function translates a virtual-key code corresponding to a character key. The character messages are WM_CHAR, WM_DEADCHAR, WM_SYSCHAR, and WM_SYSDEADCHAR. A typical window procedure ignores all character messages except WM_CHAR. The TranslateMessage function generates a WM_CHAR message when the user presses any of the following keys.

•	Any character key

•	BACKSPACE

•	ENTER (carriage return)

•	ESC

•	SHIFT+ENTER (linefeed)

•	TAB

When a window procedure receives the WM_CHAR message, it should examine the character code that accompanies the message to determine how to process the character. The character code is in the message's wParam parameter.

The following example shows the window procedure framework that a typical application uses to receive and process character messages.

        case WM_CHAR:

            switch (wParam) {

                case 0x08:

                    .

                    . /* Process a backspace. */

                    .

                    break;

                case 0x0A:

                    .

                    . /* Process a linefeed. */

                    .

                    break;

                case 0x1B:

                    .

                    . /* Process an escape. */

                    .

                    break;

                case 0x09:

                    .

                    . /* Process a tab. */

                    .

                    break;

                case 0x0D:

                    .

                    . /* Process a carriage return. */

                    .

                    break;

                default:

                    .

                    . /* Process displayable characters. */

                    .

                    break;

            }


 Using the Caret

A window that receives keyboard input typically displays the characters the user types in the window's client area. A window should use a caret to indicate the position in the client area where the next character will appear. The window should also create and display the caret when it receives the keyboard focus, and hide and destroy the caret when it loses the focus. A window can perform these operations in the processing of the WM_SETFOCUS and WM_KILLFOCUS messages. For more information about carets, see Carets.


 Displaying Keyboard Input

The example in this section shows how an application can receive characters from the keyboard, display them in the client area of a window, and update the position of the caret with each character typed. It also demonstrates how to move the caret in response to the LEFT ARROW, RIGHT ARROW, HOME and END keystrokes, and shows how to highlight selected text in response to the SHIFT+RIGHT ARROW key combination.

During processing of the WM_CREATE message, the window procedure shown in the example allocates a 64K buffer for storing keyboard input. It also retrieves the metrics of the currently loaded font, saving the height and average width of characters in the font. The height and width are used in processing the WM_SIZE message to calculate the line length and maximum number of lines, based on the size of the client area.

The window procedure creates and displays the caret when processing the WM_SETFOCUS message. It hides and deletes the caret when processing the WM_KILLFOCUS message.

When processing the WM_CHAR message, the window procedure displays characters, stores them in the input buffer, and updates the caret position. The window procedure also converts tab characters to four consecutive space characters. Backspace, linefeed, and escape characters generate a beep, but are not otherwise processed.

The window procedure performs the left, right, end, and home caret movements when processing the WM_KEYDOWN message. While processing the action of the RIGHT ARROW key, the window procedure checks the state of the SHIFT key and, if it is down, selects the character to the right of the caret as the caret is moved.

Note that the following code is written so that it can be compiled either as Unicode™ or as ANSI. If the source code defines Unicode, strings are handled as Unicode characters; otherwise, they are handled as ANSI characters.

#define BUFSIZE 65535

#define SHIFTED 0x8000

LONG APIENTRY MainWndProc(hwndMain, uMsg, wParam, lParam)

HWND hwndMain;

UINT uMsg;

UINT wParam;

LONG lParam;

{

    HDC hdc;                   /* handle of device context      */

    TEXTMETRIC tm;             /* structure for text metrics    */

    static DWORD dwCharX;      /* average width of characters   */

    static DWORD dwCharY;      /* height of characters          */

    static DWORD dwClientX;    /* width of client area          */

    static DWORD dwClientY;    /* height of client area         */

    static DWORD dwLineLen;    /* line length                   */

    static DWORD dwLines;      /* text lines in client area     */

    static int nCaretPosX = 0; /* horizontal position of caret  */

    static int nCaretPosY = 0; /* vertical position of caret    */

    static int nCharWidth = 0; /* width of a character          */

    static int cch = 0;        /* characters in buffer          */

    static int nCurChar = 0;   /* index of current character    */

    static PTCHAR pchInputBuf; /* address of input buffer       */

    int i, j;                  /* loop counters                 */

    int cCR = 0;               /* count of carriage returns     */

    int nCRIndex = 0;          /* index of last carriage return */

    int nVirtKey;              /* virtual-key code              */

    TCHAR szBuf[128];          /* temporary buffer              */

    TCHAR ch;                  /* current character             */

    PAINTSTRUCT ps;            /* required by BeginPaint        */

    RECT rc;                   /* output rectangle for DrawText */

    SIZE sz;                   /* string dimensions             */

    COLORREF crPrevText;       /* previous text color           */

    COLORREF crPrevBk;         /* previous background color     */

    switch (uMsg) {

        case WM_CREATE:

            /* Get the metrics of the current font. */

            hdc = GetDC(hwndMain);

            GetTextMetrics(hdc, &tm);

            ReleaseDC(hwndMain, hdc);

            /* Save the average character width and height. */

            dwCharX = tm.tmAveCharWidth;

            dwCharY = tm.tmHeight;

            /* Allocate a buffer to store keyboard input. */

            pchInputBuf = (LPTSTR) GlobalAlloc(GPTR,

                BUFSIZE * sizeof(TCHAR));

            return 0;

        case WM_SIZE:

            /* Save the new width and height of the client area. */

            dwClientX = LOWORD(lParam);

            dwClientY = HIWORD(lParam);

            /*

             * Calculate the maximum width of a line and the

             * maximum number of lines in the client area.

             */

            dwLineLen = dwClientX - dwCharX;

            dwLines = dwClientY / dwCharY;

            break;

        case WM_SETFOCUS:

            /*

             * Create, position, and display the caret when the

             * window receives the keyboard focus.

             */

            CreateCaret(hwndMain, (HBITMAP) 1, 0, dwCharY);

            SetCaretPos(nCaretPosX, nCaretPosY * dwCharY);

            ShowCaret(hwndMain);

            break;

        case WM_KILLFOCUS:

            /*

             * Hide and destroy the caret when the window loses the

             * keyboard focus.

             */

            HideCaret(hwndMain);

            DestroyCaret();

            break;

        case WM_CHAR:

            switch (wParam) {

                case 0x08:  /* backspace */

                case 0x0A:  /* linefeed */

                case 0x1B:  /* escape */

                    MessageBeep(0xFFFFFFFF);

                    return 0;

                case 0x09:  /* tab */

                    /* Convert tabs to four consecutive spaces. */

                    for (i = 0; i < 4; i++)

                        SendMessage(hwndMain, WM_CHAR, 0x20, 0);

                    return 0;

                case 0x0D:  /* carriage return */

                    /*

                     * Record the carriage return and position the

                     * caret at the beginning of the new line.

                     */

                    pchInputBuf[cch++] = 0x0D;

                    nCaretPosX = 0;

                    nCaretPosY += 1;

                    break;

                default:    /* displayable character */

                    ch = (TCHAR) wParam;

                    HideCaret(hwndMain);

                     /*

                      * Retrieve the character's width and output

                      * the character.

                      */

                    hdc = GetDC(hwndMain);

                    GetCharWidth32(hdc, (UINT) wParam, (UINT) wParam,

                        &nCharWidth);

                    TextOut(hdc, nCaretPosX, nCaretPosY * dwCharY,

                        &ch, 1);

                    ReleaseDC(hwndMain, hdc);

                    /* Store the character in the buffer. */

                    pchInputBuf[cch++] = ch;

                    /*

                     * Calculate the new horizontal position of the

                     * caret. If the position exceeds the maximum,

                     * insert a carriage return and move the caret

                     * to the beginning of the next line.

                     */

                    nCaretPosX += nCharWidth;

                    if ((DWORD) nCaretPosX > dwLineLen) {

                        nCaretPosX = 0;

                        pchInputBuf[cch++] = 0x0D;

                        ++nCaretPosY;

                    }

                    nCurChar = cch;

                    ShowCaret(hwndMain);

                    break;

            }

            SetCaretPos(nCaretPosX, nCaretPosY * dwCharY);

            break;

        case WM_KEYDOWN:

            switch (wParam) {

                case VK_LEFT:   /* LEFT ARROW */

                    /*

                     * The caret can move only to the beginning of

                     * the current line.

                     */

                    if (nCaretPosX > 0) {

                        HideCaret(hwndMain);

                        /*

                         * Retrieve the character to the left of

                         * the caret, calculate the character's

                         * width, then subtract the width from the

                         * current horizontal position of the caret

                         * to obtain the new position.

                         */

                        ch = pchInputBuf[--nCurChar];

                        hdc = GetDC(hwndMain);

                        GetCharWidth32(hdc, ch, ch, &nCharWidth);

                        ReleaseDC(hwndMain, hdc);

                        nCaretPosX = max(nCaretPosX - nCharWidth,

                            0);

                        ShowCaret(hwndMain);

                    }

                    break;

                case VK_RIGHT:  /* RIGHT ARROW */

                    /*

                     * Caret moves to the right or, when a carriage

                     * return is encountered, to the beginning of

                     * the next line.

                     */

                    if (nCurChar < cch) {

                        HideCaret(hwndMain);

                        /*

                         * Retrieve the character to the right of

                         * the caret. If it's a carriage return,

                         * position the caret at the beginning of

                         * the next line.

                         */

                        ch = pchInputBuf[nCurChar];

                        if (ch == 0x0D) {

                            nCaretPosX = 0;

                            nCaretPosY++;

                        }

                        /*

                         * If the character isn't a carriage

                         * return, check to see whether the SHIFT

                         * key is down. If it is, invert the text

                         * colors and output the character.

                         */

                        else {

                            hdc = GetDC(hwndMain);

                            nVirtKey = GetKeyState(VK_SHIFT);

                            if (nVirtKey & SHIFTED) {

                                crPrevText = SetTextColor(hdc,

                                    RGB(255, 255, 255));

                                crPrevBk = SetBkColor(hdc,

                                    RGB(0,0,0));

                                TextOut(hdc, nCaretPosX,

                                    nCaretPosY * dwCharY,

                                    &ch, 1);

                                SetTextColor(hdc, crPrevText);

                                SetBkColor(hdc, crPrevBk);

                            }

                            /*

                             * Get the width of the character and

                             * calculate the new horizontal

                             * position of the caret.

                             */

                            GetCharWidth32(hdc, ch, ch, &nCharWidth);

                            ReleaseDC(hwndMain, hdc);

                            nCaretPosX = nCaretPosX + nCharWidth;

                        }

                        nCurChar++;

                        ShowCaret(hwndMain);

                        break;

                    }

                    break;

                case VK_UP:     /* UP ARROW   */

                case VK_DOWN:   /* DOWN ARROW */

                    MessageBeep(0xFFFFFFFF);

                    return 0;

                case VK_HOME:   /* HOME */

                    /*

                     * Set the caret's position to the upper left

                     * corner of the client area.

                     */

                    nCaretPosX = nCaretPosY = 0;

                    nCurChar = 0;

                    break;

                case VK_END:    /* END */

                    /* Move the caret to the end of the text. */

                    for (i=0; i < cch; i++) {

                        /*

                         * Count the carriage returns and save the

                         * index of the last one.

                         */

                        if (pchInputBuf[i] == 0x0D) {

                            cCR++;

                            nCRIndex = i + 1;

                        }

                    }

                    nCaretPosY = cCR;

                    /*

                     * Copy all text between the last carriage

                     * return and the end of the keyboard input

                     * buffer to a temporary buffer.

                     */

                    for (i = nCRIndex, j = 0; i < cch; i++, j++)

                        szBuf[j] = pchInputBuf[i];

                    szBuf[j] = TEXT('\0');

                    /*

                     * Retrieve the text extent and use it

                     * to set the horizontal position of the

                     * caret.

                     */

                    hdc = GetDC(hwndMain);

                    GetTextExtentPoint32(hdc, szBuf, lstrlen(szBuf),

                        &sz);

                    nCaretPosX = sz.cx;

                    ReleaseDC(hwndMain, hdc);

                    nCurChar = cch;

                    break;

                default:

                    break;

            }

            SetCaretPos(nCaretPosX, nCaretPosY * dwCharY);

            break;

        case WM_PAINT:

            if (cch == 0)       /* nothing in input buffer */

                break;

            hdc = BeginPaint(hwndMain, &ps);

            HideCaret(hwndMain);

            /*

             * Set the clipping rectangle, and then draw the text

             * into it.

             */

            SetRect(&rc, 0, 0, dwLineLen, dwClientY);

            DrawText(hdc, pchInputBuf, -1, &rc, DT_LEFT);

            ShowCaret(hwndMain);

            EndPaint(hwndMain, &ps);

            break;

        .

        . /* Process other messages. */

        .

        case WM_DESTROY:

            PostQuitMessage(0);

            /* Free the input buffer. */

            GlobalFree((HGLOBAL) pchInputBuf);

            UnregisterHotKey(hwndMain, 0xAAAA);

            break;

        default:

            return DefWindowProc(hwndMain, uMsg, wParam, lParam);

    }

    return NULL;

}


 Keyboard Input Reference

The following functions and messages are associated with keyboard input.


 Keyboard Input Functions

Following are the functions used to receive and process keyboard input.

ActivateKeyboardLayout
EnableWindow
GetActiveWindow
GetAsyncKeyState
GetFocus
GetKeyboardLayoutName
GetKeyboardState
GetKeyNameText
GetKeyState
IsWindowEnabled
keybd_event
LoadKeyboardLayout
MapVirtualKey
OemKeyScan
RegisterHotKey
SetActiveWindow
SetFocus
SetKeyboardState
ToAscii
ToUnicode
UnloadKeyboardLayout
UnregisterHotKey
VkKeyScan

Obsolete or Deleted Functions

GetKBCodePage


 Keyboard Input Messages

Following are the messages used to receive and process keyboard input.

WM_ACTIVATE
WM_CHAR
WM_DEADCHAR
WM_HOTKEY
WM_KEYDOWN
WM_KEYUP
WM_KILLFOCUS
WM_SETFOCUS
WM_SYSCHAR
WM_SYSDEADCHAR
WM_SYSKEYDOWN
WM_SYSKEYUP


 Multiple Document Interface

The multiple document interface (MDI) is a specification that defines the standard user interface for applications written for Microsoft® Windows®.

Windows provides extensive support for MDI applications. This overview describes the structure of an MDI application and how to take advantage of the built-in MDI support found in the Microsoft® Win32® application program interface (API).


 About the Multiple Document Interface

An MDI application enables the user to work with more than one document at the same time. Each document is displayed in a separate child window within the client area of the application's main window. Typical MDI applications include word-processing applications that allow the user to work with multiple text documents, and spreadsheet applications that allow the user to work with multiple charts and spreadsheets.


 Frame, Client, and Child Windows

An MDI application has three kinds of windows: a frame window, a 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 System menu (also known as the Control menu), a Minimize button, and a Maximize button. The application must register a window class for the frame window and provide a window procedure to support it.

An MDI application does not display output in the client area of the frame window. Instead, it displays the MDI client window. An MDI client window is a special type of child window belonging to the preregistered window class MDICLIENT. The client window is a child of the frame window; it serves as the background for child windows. It also provides support for creating and manipulating child windows. For example, an MDI application can create, activate, or maximize child windows by sending messages to the MDI client window.

When the user opens or creates a document, the client window creates a child window for the document. The client window is the parent window of all MDI child windows in a given application. Each child window has a sizing border, a title bar, a System 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.

Windows keeps track of each child window's position in the stack of overlapping windows. This stacking is known as the Z order. The user can activate the next child window in the Z order by choosing the Next command from the System 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 of 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 item and its corresponding pop-up menu. The Window pop-up menu should include command 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, Windows 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 choosing the menu item, the user can activate the corresponding child window. When a child window is destroyed, Windows automatically removes the corresponding menu item from the Window menu.

Windows can add up to ten menu items to the Window menu. When the tenth child window is created, Windows adds the More Windows item to the Window menu. Choosing this item causes the Select Window dialog box to appear. 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 choosing its title from 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 of 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 System menu to the System menu of the active child window, and then to the first item on the menu bar.


 Accelerators

To receive and process accelerator keys for its child windows, an MDI application must include the TranslateMDISysAccel function in its message loop. The loop must call TranslateMDISysAccel before calling the TranslateAccelerator or DispatchMessage function.

Accelerator keys on the System 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 System 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, Windows automatically hides the child window's title bar, and adds the child window's System menu icon and Restore icon 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 chooses the Cascade command from the Window menu.

When the child windows are tiled, Windows 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 chooses the Tile command from 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. Windows 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 Windows to arrange child window icons by sending a WM_MDIICONARRANGE message to the client window. Typically, the application sends this message when the user chooses the Arrange Icons command from 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. Nontitle windows return NULL. Note that this test is insufficient for top-level windows, because menus and dialog boxes are owned windows.


 Child Window Data

Because the number of child windows varies depending on how many documents the user opens, an MDI application must be able to associate data (for example, the name of the current file) with each child window. There are two ways to do this:

•	Store child window data in the window structure.

•	Use window properties.


 Data in the Window Structure

When an MDI application registers a window class, it may reserve extra space in the window structure for application data specific to this particular class of windows. To store and retrieve data in this extra space, the application uses the GetWindowWord, SetWindowWord, GetWindowLong, and SetWindowLong functions.

To maintain a large amount of data for a child window, an application can allocate memory for a data structure and then store the handle of the memory containing the structure in the extra space associated with the child window.


 Multiple Document Window Properties

An MDI application can also store per-document data by using window properties. (Per-document data is data specific to the type of document contained in a particular child window.) Properties are different from extra space in the window structure in that you need not allocate extra space when registering the window class. A window can have any number of properties. Also, where offsets are used to access the extra space in window structures, properties are referred to by string names. For more information about window properties, see Window Properties.


 Using the Multiple Document Interface

This section explains how to perform the following tasks:

•	Registering child and frame window classes.

•	Creating frame and child windows.

•	Writing the main message loop.

•	Writing the frame window procedure.

•	Writing the child window procedure.

•	Creating a child window.

To illustrate these tasks, this section includes examples from Multipad, a typical MDI application.


 Registering Child and Frame Window Classes

A typical MDI application must register two window classes: one for its frame window and one for its child windows. If an application supports more than one type of document (for example, a spreadsheet and a chart), it must register a window class for each type.

The class structure for the frame window is similar to the class structure for the main window in non-MDI applications. The class structure for the MDI child windows differs slightly from the structure for child windows in non-MDI applications as follows:

•	The class structure should have an icon, because the user can minimize an MDI child window as if it were a normal application window.

•	The menu name should be NULL, because an MDI child window cannot have its own menu.

•	The class structure should reserve extra space in the window structure. With this space, the application can associate data, such as a filename, with a particular child window.

The following example shows how Multipad registers its frame and child window classes.

BOOL APIENTRY 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 Windows. 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	Identifies 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 choosing its title from 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, Windows immediately reassigns the window identifiers to keep their range contiguous.
When a child window's title is added to the Window menu, Windows assigns an identifier to the child window. When the user chooses 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 of 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. (The Window menu is repainted whenever a child window is created or destroyed.) An MDI application that adds strings to its Window menu should use the InsertMenu function and verify that the titles of child windows have not overwritten these new strings.

Use the WS_CLIPCHILDREN style to create the MDI client window to prevent the window from painting over its child windows.


 Writing the Main Message Loop

The main message loop of an MDI application is similar to that of a non-MDI application handling accelerator keys. The difference is that the MDI message loop calls the TranslateMDISysAccel function before checking for application-defined accelerator keys or before dispatching the message.

The following example shows the message loop of a typical MDI application.

while (GetMessage(&msg, (HWND) NULL, 0, 0)) {

    if (!TranslateMDISysAccel(hwndMDIClient, &msg) &&

            !TranslateAccelerator(hwndFrame, hAccel, &msg)){

        TranslateMessage(&msg);

        DispatchMessage(&msg);

    }

}

The TranslateMDISysAccel function translates WM_KEYDOWN messages into WM_SYSCOMMAND messages and sends them to the active MDI child window. If the message is not an MDI accelerator message, the function returns FALSE, in which case the application uses the TranslateAccelerator function to determine whether any of the application-defined accelerator keys were pressed. If not, the loop dispatches the message to the appropriate window procedure.


 Writing the Frame Window Procedure

The window procedure for an MDI frame window is similar to that of a non-MDI application's main window. The difference is that a frame window procedure passes all messages it does not handle to the DefFrameProc function rather than to the DefWindowProc function. In addition, the frame window procedure must also pass some messages that it does handle, including those listed in the following table.

Message	Response
WM_COMMAND	Activates the MDI child window that the user chooses. This message is sent when the user chooses an MDI child window from the Window menu of the MDI frame window. The window identifier accompanying this message identifies the MDI child window to be activated.
WM_MENUCHAR	Opens the System 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 choosing the window's menu item (command) 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 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 Windows 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 functions and messages are used in MDI applications.


MDI Functions
 Multiple Document Interface Functions

CreateMDIWindow
DefFrameProc
DefMDIChildProc
TranslateMDISysAccel


MDI Messages
 Multiple Document Interface Messages

WM_MDIACTIVATE
WM_MDICASCADE
WM_MDICREATE
WM_MDIDESTROY
WM_MDIGETACTIVE
WM_MDIICONARRANGE
WM_MDIMAXIMIZE
WM_MDINEXT
WM_MDIREFRESHMENU
WM_MDIRESTORE
WM_MDISETMENU
WM_MDITILE


 Messages and Message Queues

This overview describes messages and message queues and explains how to use them in your application.


 About Messages and Message Queues

Unlike traditional applications, applications written for Microsoft® Windows® do not make explicit function calls (such as to getchar) to obtain input. Instead, they wait for Windows to pass input to them.

Windows passes all input for an application to the various windows in the application. Each window has a function, called a window procedure, that Windows calls whenever it has input for the window. The window procedure processes the input and returns control to Windows. For more information about window procedures, see Window Procedures.


 Messages

Windows passes input to a window procedure in the form of messages. Messages are generated by Windows and by applications. Windows 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. Windows 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.

Windows sends a message to a window procedure with a set of four parameters: a window handle, a message identifier, and two 32-bit values called message parameters. The window handle identifies the window for which the message is intended. Windows uses it to determine which window procedure to send the message to.

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, it typically sets them to NULL. A window procedure must check the message identifier to determine how to interpret the message parameters.


 Message Routing

Windows 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

Windows can display any number of windows at a time. To route mouse and keyboard input to the appropriate window, Windows uses message queues.

Windows maintains a single system message queue and any number of thread message queues, one for each GUI thread. To avoid the overhead of creating a message queue for non-GUI threads, all threads are created initially without a message queue. The system creates a thread's message queue only when the thread makes its first call to one of the Win32 USER or GDI functions.

Whenever the user moves the mouse, clicks the mouse buttons, or types on the keyboard, the device driver for the mouse or keyboard converts the input into messages and places them in the system message queue. Windows 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 Windows to send them to the appropriate window procedure for processing. For more information about threads, see Processes and Threads.

With the exception of the WM_PAINT message, Windows 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 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 messate 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 Windows 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.


 Nonqueued Messages

Nonqueued messages are sent immediately to the destination window procedure, bypassing the system message queue and thread message queue. Windows typically sends nonqueued messages to notify a window of events that affect it. For example, when the user activates a new application window, Windows 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 Windows functions. For example, Windows sends the WM_WINDOWPOSCHANGED message after an application uses the SetWindowPos function to move a window.

An application can send a message by calling the SendMessage, SendNotifyMessage, or SendDlgItemMessage function. For more information about sending messages, see Sending a Message.


 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

A simple message loop consists of one function call to each of these three functions: GetMessage, TranslateMessage, and DispatchMessage. The GetMessage function retrieves a message from the queue and copies it to an MSG structure. GetMessage returns TRUE 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 in 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. Windows 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.

An application can modify its message loop in a variety of ways. For example, it can retrieve messages from the queue without dispatching them to a window. This is useful for applications that post messages not specifying a window. (These messages apply to the application rather than to a specific window because they have NULL window handles.) An application can also direct GetMessage to search for specific messages, leaving other messages in the queue. This is useful for applications that must temporarily bypass the usual first-in, first-out 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.


 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 types of messages and pass the others on to the system by calling DefWindowProc.

Because a window procedure is shared by all windows belonging to the same class, it can process messages for several different windows. To identify the specific window affected by the message, a window procedure can examine the window handle passed with a message. For more information about window procedures, see Window Procedures.


 Posting and Sending Messages

Any application can post and send messages. Like the system, an application posts a message by copying it to a message queue and sends a message by passing the message data as arguments to a window procedure. To post and send messages, an application uses the PostMessage and SendMessage functions.

An application typically posts a message to notify a specific window to perform a task. PostMessage creates an MSG structure for the message and copies the message to the message queue. The application's message loop eventually retrieves the message and dispatches it to the appropriate window procedure.

An application typically sends a message to notify a window procedure to perform a task immediately. The SendMessage function sends the message to the window procedure corresponding to the given window. The function waits until the window procedure completes processing and then returns the message result. Parent and child windows often communicate by sending messages to each other. For example, a parent window that has an edit control as its child window can set the text of the control by sending a message to it. The control can notify the parent window of changes to the text that are carried out by the user by sending messages back to the parent.

Occasionally, an application may be required to send or post a message to all top-level windows in the system. For example, if the application changes the system time, it must notify all top-level windows about the change by sending a WM_TIMECHANGE message. An application can send or post a message to all top-level windows by calling the SendMessage or PostMessage function and specifying HWND_TOPMOST in the hwnd parameter.

An application can post a message without specifying a window. If the application supplies a NULL window handle when calling PostMessage, the message is posted to the queue associated with the current thread. Because no window handle is specified, the application must process the message in the message loop. This is one way to create a message that applies to the entire application, instead of to a specific window.

By using the InSendMessage function, a window procedure can determine whether it is processing a message sent by another thread. This capability is useful when message processing depends on the origin of the message.

A common programming error is to assume that the PostMessage function always posts a message. This is not true when the message queue is full. An application should check the return value of the PostMessage function to determine whether the message has been posted and, if it has not been, repost it.


 Message Types

This section describes the two types of Windows messages: system defined and application defined.


 System-Defined Messages

The system uses system-defined messages to control the operations of applications and to provide input and other information for applications to process. The system sends or posts a system-defined message when it communicates with an application. An application can also send or post system-defined messages. Applications usually use these messages to control the operation of control windows created by using preregistered window classes.

Each system message has a unique message identifier and a corresponding symbolic constant (defined in the Windows 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
BM	Button control
CB	Combo box control
DM	Default push button control
EM	Edit control
LB	List box control
SBM	Scroll bar 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 use in 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.

Windows reserves message-identifier values in the range 0x0000 through 0x03FF (the value of WM_USER − 1) and 0x8000 through 0xBFFF 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 defined by an application for its own use. Values in the range 0xC000 through 0xFFFF are available for message identifiers defined by an application for use in communicating with windows in other applications.

Windows 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. If your application creates messages to communicate with windows in other applications, it should use RegisterWindowMessage to register the message. Use of this function prevents conflicts that can arise if other applications use the same message identifier for different purposes.


 Message Filtering

An application can choose specific messages to retrieve from the message queue (while ignoring other messages) by using the GetMessage or PeekMessage function to specify a message filter. The filter is a range of message identifiers (specified by a first and last identifier), a window handle, or both. GetMessage and PeekMessage use a message filter to select which messages to retrieve from the queue. Message filtering is useful if an application must search the message queue for messages that have arrived later in the queue.

Any application that filters messages must ensure that a message satisfying the message filter can be posted. For example, if an application filters for a WM_CHAR message in a window that does not receive keyboard input, the GetMessage function does not return. This effectively "hangs" the application.

To filter for keyboard, mouse, and DDE messages, an application can use the WM_KEYFIRST and WM_KEYLAST, WM_MOUSEFIRST and WM_MOUSELAST messages, and WM_DDE_FIRST and WM_DDE_LAST constants.


 Message Deadlocks

A thread that calls the SendMessage function to send a message to another thread cannot continue executing until the window procedure that receives the message returns. If the receiving thread yields control while processing the message, the sending thread cannot continue executing, because it is waiting for SendMessage to return. This situation is called a deadlock. The receiving thread need not yield control explicitly; calling any of the following functions can cause a thread to yield control.

DialogBox
DialogBoxIndirect
DialogBoxIndirectParam
DialogBoxParam
GetMessage
MessageBox
PeekMessage

A window procedure can determine whether a message it has received was sent by another thread by calling the InSendMessage function. Before calling any of the functions in the preceding list while processing a message, the window procedure should first call InSendMessage. If this function returns TRUE, the window procedure must call the ReplyMessage function before any function that causes the thread to yield control.


 Using Messages and Message Queues

•	Creating a message loop

•	Examining a message queue

•	Posting a message

•	Sending a message


 Creating a Message Loop

Windows 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 Windows directs messages to individual windows in an application, a thread must create at least one window before starting its message loop. Most Windows-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 Windows-based application.

HINSTANCE hinst;

HWND hwndMain;

int APIENTRY WinMain(hInstance, hPrevInstance, lpszCmdLine,

    nCmdShow)

HINSTANCE hInstance;

HINSTANCE hPrevInstance;

LPSTR lpszCmdLine;

int nCmdShow;

{

    MSG msg;

    WNDCLASS wc;

    UNREFERENCED_PARAMETER(lpszCmdLine);

    /* Register the window class for the main window. */

    if (!hPrevInstance) {

        wc.style = 0;

        wc.lpfnWndProc = (WNDPROC) WndProc;

        wc.cbClsExtra = 0;

        wc.cbWndExtra = 0;

        wc.hInstance = hInstance;

        wc.hIcon = LoadIcon((HINSTANCE) NULL,

            IDI_APPLICATION);

        wc.hCursor = LoadCursor((HINSTANCE) NULL,

            IDC_ARROW);

        wc.hbrBackground = GetStockObject(WHITE_BRUSH);

        wc.lpszMenuName =  "MainMenu";

        wc.lpszClassName = "MainWndClass";

        if (!RegisterClass(&wc))

            return FALSE;

    }

    hinst = hInstance;  /* save instance handle */

    /* Create the main window. */

    hwndMain = CreateWindow("MainWndClass", "Sample",

        WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT,

        CW_USEDEFAULT, CW_USEDEFAULT, (HWND) NULL,

        (HMENU) NULL, hinst, (LPVOID) NULL);

    /*

     * If the main window cannot be created, terminate

     * the application.

     */

    if (!hwndMain)

        return FALSE;

    /* Show the window and paint its contents. */

    ShowWindow(hwndMain, nCmdShow);

    UpdateWindow(hwndMain);

    /* Start the message loop. */

    while (GetMessage(&msg, (HWND) NULL, 0, 0)) {

        TranslateMessage(&msg);

        DispatchMessage(&msg);

    }

    /* Return the exit code to Windows. */

    return msg.wParam;

}

The GetMessage, TranslateMessage, and DispatchMessage functions take a pointer to an MSG structure as a parameter. If a message is available, GetMessage copies it to the MSG structure. If the message is a virtual-key message (such as WM_KEYDOWN or WM_SYSKEYDOWN), TranslateMessage generates a character message (WM_CHAR or WM_SYSCHAR) and places it in the message queue. DispatchMessage uses the members of the MSG structure as arguments for the window procedure; DispatchMessage does not return until the window procedure finishes processing the message.

If a thread supports accelerators, its message loop must include the TranslateAccelerator function. This function checks for key combinations that match an entry in the thread's accelerator table. When it finds a match, TranslateAccelerator translates the key combination into a WM_COMMAND message and dispatches it to the window procedure. For more information about accelerators, 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. For more information about dialog boxes, see Dialog Boxes.

The following example shows a message loop for a thread that uses accelerators and displays a modeless dialog box. When TranslateAccelerator or IsDialogMessage returns TRUE (indicating that the message has been processed), TranslateMessage and DispatchMessage are not called. The reason for this is that TranslateAccelerator and IsDialogMessage perform all necessary translating and dispatching of messages.

HWND hwndMain;

HWND hwndDlgModeless = NULL;

MSG msg;

HACCEL haccel;

.

. /* Perform initialization and create a main window. */

.

while (GetMessage(&msg, (HWND) NULL, 0, 0)) {

    if (hwndDlgModeless == (HWND) NULL ||

            !IsDialogMessage(hwndDlgModeless, &msg) &&

            !TranslateAccelerator(hwndMain, haccel,

                &msg)) {

        TranslateMessage(&msg);

        DispatchMessage(&msg);

    }

}


 Examining a Message Queue

Occasionally, an application needs to examine the contents of a thread's message queue from outside the thread's message loop. For example, if an application's window procedure performs a lengthy drawing operation, you may want the user to be able to interrupt the operation. Unless your application periodically examines the message queue during the operation for mouse and keyboard messages, it will not respond to user input until after the operation has completed. The reason for this is that the DispatchMessage function in the thread's message loop does not return until the window procedure finishes processing a message.

You can use the PeekMessage function to examine a message queue during a lengthy operation. PeekMessage is similar to the GetMessage function; both check a message queue for a message that matches the filter criteria and then copy the message to an MSG structure. The main difference between the two functions is that GetMessage does not return until a message matching the filter criteria is placed in the queue, whereas PeekMessage returns immediately regardless of whether a message is in the queue.

The following example shows how to use PeekMessage to examine a message queue for mouse clicks and keyboard input during a lengthy operation.

HWND hwnd;

BOOL fDone;

MSG msg;

/*

 * Begin the operation and continue until it is complete

 * or until the user clicks the mouse or presses a key.

 */

fDone = FALSE;

while (!fDone) {

    fDone = DoLengthyOperation(); /* application-defined */

    /*

     * 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. Windows copies these parameters to an MSG structure, fills the time and pt members of the structure, and places the structure in the message queue.

Windows 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, Windows 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 Windows 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. Windows uses the handle to determine which window procedure should receive the message.

If a window procedure yields control when processing a message sent by another thread, a message deadlock may result. (For more information about message deadlocks, see Message Deadlocks.) 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. */

    .

}


 Message and Message Queue Functions

Following are the functions used with messages and message queues.

BroadcastSystemMessage
DefWindowProc
DispatchMessage
GetInputState
GetMessage
GetMessageExtraInfo
GetMessagePos
GetMessageTime
GetQueueStatus
InSendMessage
PeekMessage
PostAppMessage
PostMessage
PostQuitMessage
PostThreadMessage
RegisterWindowMessage
ReplyMessage
SendAsyncProc
SendMessage
SendMessageCallback
SendMessageTimeout
SendNotifyMessage
SetMessageExtraInfo
TranslateMessage
WaitMessage

Obsolete or Deleted Functions

SetMessageQueue


 Mouse Input

This overview describes how Windows generates mouse input and explains how an application receives and processes that input.


 About Mouse Input

The mouse is an important, but optional, user-input device for applications written for Microsoft® Windows®. A well-written Windows-based application should include a mouse interface, but it should not depend on the mouse as the sole means of acquiring user input. The application should provide full keyboard support as well.

A Windows-based application receives mouse input in the form of messages that are sent or posted to its windows.


 Mouse Cursor

When the user moves the mouse, the system moves a bitmap on the screen called the mouse cursor. The mouse cursor contains a single-pixel point called the hot spot, a point that the system tracks and recognizes as the position of the cursor. When a mouse event occurs, the window that contains the hot spot typically receives the mouse message resulting from the event. The window need not be active or have the keyboard focus to receive a mouse message.

The system maintains a variable that controls the mouse speed — that is, the distance the cursor moves when the user moves the mouse. You can use the SystemParametersInfo function with the SPI_GETMOUSE or SPI_SETMOUSE flag to retrieve or set the mouse speed. For more information about mouse cursors, see Cursors.


 Mouse Capture

The system typically posts a mouse message to the window that contains the cursor hot spot at the time a mouse event occurs. An application can change this behavior by using the SetCapture function to route mouse messages to a specific window. The window receives all mouse messages until the application calls the ReleaseCapture function or specifies another capture window, or until the user clicks a window created by another thread.

Whenever the mouse capture changes, Windows sends a WM_CAPTURECHANGED message to the window that is losing the mouse capture. The lParam parameter of the message specifies the handle of the window that is gaining the mouse capture.

Only the foreground window can capture mouse input. When a background window attempts to capture mouse input, it receives messages only for mouse events that occur when the cursor hot spot is within the visible portion of the window.

Capturing mouse input is useful if a window must receive all mouse input, even when the cursor moves outside the window. For example, an application typically tracks the cursor position after a mouse "button down" event, following the cursor until a "button up" event occurs. If an application has not captured mouse input and the user releases the mouse button outside the window, the window does not receive the button up message.

A thread can use the GetCapture function to determine whether one of its windows has captured the mouse. If one of the thread's windows has captured the mouse, GetCapture retrieves the handle of the window.


 Mouse Configuration

Although the mouse is an important input device for Windows-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.

Windows supports a mouse having up to three buttons. On a three-button mouse, the buttons are designated as the left, middle, and right buttons. Windows 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 Windows supports a mouse with multiple buttons, most applications use the left button primarily and use the others little, if at all.

An application can determine the number of buttons on the mouse by passing the SM_CMOUSEBUTTONS value to the GetSystemMetrics function. To configure the mouse for a left-handed user, the application can use the SwapMouseButton function to reverse the meaning of the left and right mouse buttons. Passing the SPI_SETMOUSEBUTTONSWAP value to the SystemParametersInfo function is another way to reverse the meaning of the buttons. Note, however, that the mouse is a shared resource, so reversing the meaning of the buttons affects all applications.


 Mouse Messages

The mouse generates an input event whenever the user moves the mouse, or presses or releases a mouse button. Windows 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, Windows discards all but the most recent mouse message.

A window receives a mouse message when a mouse event occurs while the cursor is within the borders of the window, or when the window has captured the mouse. Mouse messages are divided into two groups: client area messages and nonclient area messages. Typically, an application processes client area messages and ignores nonclient area messages.


 Client Area Mouse Messages

A window receives a client area mouse message when a mouse event occurs within the window's client area. The system posts the WM_MOUSEMOVE message to the window when the user moves the cursor within the client area. It posts one of the following messages when the user presses or releases a mouse button while the cursor is within the client area.

Message	Meaning
WM_LBUTTONDBLCLK	The left mouse button was double-clicked.
WM_LBUTTONDOWN	The left mouse button was pressed.
WM_LBUTTONUP	The left mouse button was released.
WM_MBUTTONDBLCLK	The middle mouse button was double-clicked.
WM_MBUTTONDOWN	The middle mouse button was pressed.
WM_MBUTTONUP	The middle mouse button was released.
WM_RBUTTONDBLCLK	The right mouse button was double-clicked.
WM_RBUTTONDOWN	The right mouse button was pressed.
WM_RBUTTONUP	The right mouse button was released.
Message Parameters

The lParam parameter of a client area mouse message indicates the position of the cursor hot spot. The low-order word indicates the x-coordinate of the hot spot, and the high-order word indicates the y-coordinate. The coordinates are given in client coordinates. In the client coordinate system, all points on the screen are given relative to the coordinates (0,0) of the upper left corner of the client area.

The wParam parameter contains flags that indicate the status of the other mouse buttons and the CTRL and SHIFT keys at the time of the mouse event. You can check for these flags when mouse-message processing depends on the state of another mouse button or of the CTRL or SHIFT key. The lParam parameter can be a combination of the following values.

Value	Meaning
MK_CONTROL	The CTRL key is down.
MK_LBUTTON	The left mouse button is down.
MK_MBUTTON	The middle mouse button is down.
MK_RBUTTON	The right mouse button is down.
MK_SHIFT	The SHIFT key is down.
Double-Click Messages

The system generates a double-click message when the user clicks a mouse button twice in quick succession. When the user clicks a button, the system establishes a rectangle centered around the cursor hot spot. It also marks the time at which the click occurred. When the user clicks the same button a second time, the system determines whether the hot spot is still within the rectangle and calculates the time elapsed since the first click. If the hot spot is still within the rectangle and the elapsed time does not exceeded the double-click time-out value, the system generates a double-click message.

An application can get and set double-click time-out values by using the GetDoubleClickTime and SetDoubleClickTime functions, respectively. Alternatively, the application can set the double-click time-out value by using the SPI_SETDOUBLECLICKTIME flag with the SystemParametersInfo function. It can also set the size of the rectangle that Windows 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 about window classes, 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 Windows Paintbrush™, Paintbrush displays the selected color next to the palette. When the user double-clicks a color, Paintbrush 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, System menu (also called the Control menu), Minimize button, and Maximize button.

Windows generates nonclient area messages primarily for its own use. For example, Windows 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 found in Windows.

There is a corresponding nonclient area mouse message for each client area mouse message. The names of these messages are similar except that the named constants for the nonclient area messages include the letters "NC". For example, moving the cursor in the nonclient area generates a WM_NCMOUSEMOVE message, and pressing the left mouse button while the cursor is in the nonclient area generates a WM_NCLBUTTONDOWN message.

The lParam parameter of a nonclient area mouse message is a POINTS structure that contains the x- and y-coordinates of the cursor hot spot. Unlike coordinates of client area mouse messages, the coordinates are given in screen coordinates rather than client coordinates. In the screen coordinate system, all points on the screen are relative to the coordinates (0,0) of the upper left corner of the screen.

The wParam parameter contains a hit-test value, a value that indicates where in the nonclient area the mouse event occurred. The following section explains the purpose of hit-test values.


 The WM_NCHITTEST Message

Whenever a mouse event occurs, the system sends a WM_NCHITTEST message to either the window that contains the cursor hot spot or the window that has captured the mouse. Windows uses this message to determine whether to send a client area or nonclient area mouse message. An application that must receive mouse movement and mouse button messages must pass the WM_NCHITTEST message to the DefWindowProc function.

The lParam parameter of the WM_NCHITTEST message contains the screen coordinates of the cursor hot spot. The DefWindowProc function examines the coordinates and returns a hit-test value that identifies the location of the hot spot. The hit-test value can be one of the following values.

Value	Location of hot spot
HTBORDER	In the border of a window that does not have a sizing border
HTBOTTOM	In the lower horizontal border of a window
HTBOTTOMLEFT	In the lower left corner of a window border
HTBOTTOMRIGHT	In the lower right corner of a window border
HTCAPTION	In a title bar
HTCLIENT	In a client area
HTCLOSE	In close button.
HTERROR	On the screen background or on a dividing line between windows (same as HTNOWHERE, except that the DefWindowProc function produces a system beep to indicate an error)
HTGROWBOX	In a size box (same as HTSIZE)
HTHELP	In Help button.
HTHSCROLL	In a horizontal scroll bar
HTLEFT	In the left border of a window
HTMENU	In a menu
HTMAXBUTTON	In Maximize button.
HTMINBUTTON	In Minimize button.
HTNOWHERE	On the screen background or on a dividing line between windows
HTREDUCE	In a Minimize button
HTRIGHT	In the right border of a window
HTSIZE	In a size box (same as HTGROWBOX)
HTSYSMENU	In a System menu or in a Close button in a child window
HTTOP	In the upper horizontal border of a window
HTTOPLEFT	In the upper left corner of a window border
HTTOPRIGHT	In the upper right corner of a window border
HTTRANSPARENT	In a window currently covered by another window
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, Windows 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, Windows posts a nonclient area mouse message, placing the hit-test value in the message's wParam parameter and the cursor coordinates in the lParam parameter.


 Window Activation

When the user clicks an inactive top-level window or the child window of a inactive top-level window, Windows sends the WM_MOUSEACTIVATE message (among others) to the top-level or child window. Windows 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, Windows activates the top-level window and then posts the button down message to the top-level or child window.

By processing WM_MOUSEACTIVATE, a window can control whether the top-level window becomes the active window as a result of a mouse click, and whether the window that was clicked receives the subsequent button down message. It does so by returning one of the following values after processing WM_MOUSEACTIVATE.

Value	Meaning
MA_ACTIVATE	Activates the window and does not discard the mouse message.
MA_NOACTIVATE	Does not activate the window and does not discard the mouse message.
MA_ACTIVATEANDEAT	Activates the window and discards the mouse message.
MA_NOACTIVATEANDEAT	Does not activate the window but discards the mouse message.


 Using Mouse Input

•	Tracking the mouse cursor

•	Drawing lines with the mouse

•	Processing a double-click message

•	Selecting a line of text


 Tracking the Mouse Cursor

Windows-based applications often perform tasks that involve tracking the position of the mouse cursor. Most drawing applications, for example, track it during drawing operations, allowing the user to draw in a window's client area by dragging the mouse. Word-processing applications also track the cursor, enabling the user to select a word or block of text by clicking and dragging the mouse.

Tracking the cursor typically involves processing the WM_LBUTTONDOWN, WM_MOUSEMOVE, and WM_LBUTTONUP messages. A window determines when to begin tracking the cursor by checking the cursor position provided in the lParam parameter of the WM_LBUTTONDOWN message. For example, a word-processing application would begin tracking the cursor only if the WM_LBUTTONDOWN message occurred while the cursor was on a line of text, but not if it was past the end of the document.

A window tracks the position of the cursor by processing the stream of WM_MOUSEMOVE messages posted to the window as the mouse moves. Processing the WM_MOUSEMOVE message typically involves a repetitive painting or drawing operation in the client area. For example, a drawing application might redraw a line repeatedly as the mouse moves. A window uses the WM_LBUTTONUP message as a signal to stop tracking the cursor.


 Drawing Lines with the Mouse

The example in this section demonstrates how to track the mouse cursor. It contains portions of a window procedure that enables the user to draw lines in a window's client area by dragging the mouse.

When the window procedure receives a WM_LBUTTONDOWN message, it captures the mouse and saves the coordinates of the cursor, using the coordinates as the starting point of the line. It also uses the ClipCursor function to confine the cursor to the client area during the line drawing operation.

During the first WM_MOUSEMOVE message, the window procedure draws a line from the starting point to the current position of the cursor. During subsequent WM_MOUSEMOVE messages, the window procedure erases the previous line by drawing over it with an inverted pen color. Then it draws a new line from the starting point to the new position of the cursor.

The WM_LBUTTONUP message signals the end of the drawing operation. The window procedure releases the mouse capture and frees the mouse from the client area.

LRESULT APIENTRY MainWndProc(hwndMain, uMsg, wParam, lParam)

HWND hwndMain;

UINT uMsg;

WPARAM wParam;

LPARAM lParam;

{

    HDC hdc;                       /* handle of device context  */

    RECT rcClient;                 /* client area rectangle     */

    POINT ptClientUL;              /* client upper left corner  */

    POINT ptClientLR;              /* client lower right corner */

    static POINTS ptsBegin;        /* beginning point           */

    static POINTS ptsEnd;          /* new endpoint              */

    static POINTS ptsPrevEnd;      /* previous endpoint         */

    static BOOL fPrevLine = FALSE; /* previous line flag        */

    switch (uMsg) {

        case WM_LBUTTONDOWN:

            /* Capture mouse input. */

            SetCapture(hwndMain);

            /*

             * Retrieve the screen coordinates of the client area,

             * and convert them into client coordinates.

            /*

            GetClientRect(hwndMain, &rcClient);

            ptClientUL.x = rcClient.left;

            ptClientUL.y = rcClient.top;

            /*

             * Add one to the right and bottom sides, because the

             * coordinates retrieved by GetClientRect do not

             * include the far left and lowermost pixels.

             */

            ptClientLR.x = rcClient.right + 1;

            ptClientLR.y = rcClient.bottom + 1;

            ClientToScreen(hwndMain, &ptClientUL);

            ClientToScreen(hwndMain, &ptClientLR);

            /*

             * Copy the client coordinates of the client area

             * to the rcClient structure. Confine the mouse cursor

             * to the client area by passing the rcClient structure

             * to the ClipCursor function.

             */

            SetRect(&rcClient, ptClientUL.x, ptClientUL.y,

                ptClientLR.x, ptClientLR.y);

            ClipCursor(&rcClient);

            /*

             * Convert the cursor coordinates into a POINTS

             * structure, which defines the beginning point of the

             * line drawn during a WM_MOUSEMOVE message.

             */

            ptsBegin = MAKEPOINTS(lParam);

            return 0;

        case WM_MOUSEMOVE:

            /*

             * When moving the mouse, the user must hold down

             * the left mouse button to draw lines.

             */

            if (wParam & MK_LBUTTON) {

                /*

                 * Retrieve a device context (DC) for the client

                 * area.

                 */

                hdc = GetDC(hwndMain);

                /*

                 * The following function ensures that pixels of

                 * the previously drawn line are set to white and

                 * those of the new line are set to black.

                 */

                SetROP2(hdc, R2_NOTXORPEN);

                /*

                 * If a line was drawn during an earlier

                 * WM_MOUSEMOVE message, draw over it. This erases

                 * the line by setting the color of its pixels to

                 * white.

                 */

                if (fPrevLine) {

                    MoveToEx(hdc, ptsBegin.x, ptsBegin.y,

                        (LPPOINT) NULL);

                    LineTo(hdc, ptsPrevEnd.x, ptsPrevEnd.y);

                }

                /*

                 * Convert the current cursor coordinates to a

                 * POINTS structure, and then draw a new line.

                 */

                ptsEnd = MAKEPOINTS(lParam);

                MoveToEx(hdc, ptsBegin.x, ptsBegin.y,

                    (LPPOINT) NULL);

                LineTo(hdc, ptsEnd.x, ptsEnd.y);

                /*

                 * Set the previous line flag, save the ending

                 * point of the new line, and then release the DC.

                 */

                fPrevLine = TRUE;

                ptsPrevEnd = ptsEnd;

                ReleaseDC(hwndMain, hdc);

            }

            break;

        case WM_LBUTTONUP:

            /*

             * The user has finished drawing the line. Reset the

             * previous line flag, release the mouse cursor, and

             * release the mouse capture.

             */

            fPrevLine = FALSE;

            ClipCursor(NULL);

            ReleaseCapture();

            return 0;

        case WM_DESTROY:

            PostQuitMessage(0);

            break;

        .

        . /* Process other messages. */

        .


 Processing a Double-Click Message

To receive double-click messages, a window must belong to a window class that has the CS_DBLCLKS class style. You set this style when registering the window class, as shown in the following example.

BOOL InitApplication(hInstance)

HINSTANCE 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(hwndMain, uMsg, wParam, lParam)

HWND hwndMain;

UINT uMsg;

WPARAM wParam;

LPARAM lParam;

{

    HDC hdc;                     /* handle of device context     */

    TEXTMETRIC tm;               /* font size data               */

    int i, j;                    /* loop counters                */

    int cCR = 0;                 /* count of carriage returns    */

    char ch;                     /* character from input buffer  */

    static int nBegLine;         /* beginning of selected line   */

    static int nCurrentLine = 0; /* currently selected line      */

    static int nLastLine = 0;    /* last text line               */

    static int nCaretPosX = 0;   /* x-coordinate of caret        */

    static int cch = 0;          /* number of characters entered */

    static int nCharWidth = 0;   /* exact width of a character   */

    static char szHilite[128];   /* text string to highlight     */

    static DWORD dwCharX;        /* average width of characters  */

    static DWORD dwLineHeight;   /* line height                  */

    static POINTS ptsCursor;     /* coordinates of mouse cursor  */

    static COLORREF crPrevText;  /* previous text color          */

    static COLORREF crPrevBk;    /* previous background color    */

    static PTCHAR pchInputBuf;   /* address of input buffer      */

    static BOOL fTextSelected = FALSE; /* text-selection flag    */

    switch (uMsg) {

        case WM_CREATE:

            /* Get the metrics of the current font. */

            hdc = GetDC(hwndMain);

            GetTextMetrics(hdc, &tm);

            ReleaseDC(hwndMain, hdc);

            /* Save the average character width and height. */

            dwCharX = tm.tmAveCharWidth;

            dwLineHeight = tm.tmHeight;

            /* Allocate a buffer to store keyboard input. */

            pchInputBuf = (LPSTR) GlobalAlloc(GPTR,

                BUFSIZE * sizeof(TCHAR));

            return 0;

        case WM_CHAR:

            switch (wParam) {

                case 0x08:  /* backspace */

                case 0x0A:  /* linefeed */

                case 0x1B:  /* escape */

                    MessageBeep(0xFFFFFFFF);

                    return 0;

                case 0x09:  /* tab */

                    /* Convert tabs to four consecutive spaces. */

                    for (i = 0; i < 4; i++)

                        SendMessage(hwndMain, WM_CHAR, 0x20, 0);

                    return 0;

                case 0x0D:  /* carriage return */

                    /*

                     * Record the carriage return, and position the

                     * caret at the beginning of the new line.

                     */

                    pchInputBuf[cch++] = 0x0D;

                    nCaretPosX = 0;

                    nCurrentLine += 1;

                    break;

                default:    /* displayable character */

                    ch = (char) wParam;

                    HideCaret(hwndMain);

                    /*

                     * Retrieve the character's width, and display the

                     * character.

                     */

                    hdc = GetDC(hwndMain);

                    GetCharWidth32(hdc, (UINT) wParam, (UINT) wParam,

                        &nCharWidth);

                    TextOut(hdc, nCaretPosX,

                        nCurrentLine * dwLineHeight, &ch, 1);

                    ReleaseDC(hwndMain, hdc);

                    /* Store the character in the buffer. */

                    pchInputBuf[cch++] = ch;

                    /*

                     * Calculate the new horizontal position of

                     * the caret. If the new position exceeds the

                     * maximum, insert a carriage return and

                     * reposition the caret at the beginning of

                     * the next line.

                     */

                    nCaretPosX += nCharWidth;

                    if ((DWORD) nCaretPosX > dwMaxCharX) {

                        nCaretPosX = 0;

                        pchInputBuf[cch++] = 0x0D;

                        ++nCurrentLine;

                    }

                    ShowCaret(hwndMain);

                    break;

            }

            SetCaretPos(nCaretPosX, nCurrentLine * dwLineHeight);

            nLastLine = max(nLastLine, nCurrentLine);

            break;

        .

        . /* Process other messages. */

        .

        case WM_LBUTTONDOWN:

            /*

             * If a line of text is currently highlighted, redraw

             * the text to remove the highlighting.

             */

            if (fTextSelected) {

                hdc = GetDC(hwndMain);

                SetTextColor(hdc, crPrevText);

                SetBkColor(hdc, crPrevBk);

                TextOut(hdc, 0, nCurrentLine * dwLineHeight,

                    szHilite, lstrlen(szHilite));

                ReleaseDC(hwndMain, hdc);

                ShowCaret(hwndMain);

                fTextSelected = FALSE;

            }

            /* Save the current mouse-cursor coordinates. */

            ptsCursor = MAKEPOINTS(lParam);

            /*

             * Determine which line the cursor is on, and save

             * the line number. Do not allow line numbers greater

             * than the number of the last line of text. The

             * line number is later multiplied by the average height

             * of the current font. The result is used to set the

             * y-coordinate of the caret.

             */

            nCurrentLine = min((int)(ptsCursor.y / dwLineHeight),

                nLastLine);

            /*

             * Parse the text input buffer to find the first

             * character in the selected line of text. Each

             * line ends with a carriage return, so it is possible

             * to count the carriage returns to find the selected

             * line.

             */

            cCR = 0;

            nBegLine = 0;

            if (nCurrentLine != 0) {

                for (i = 0; (i < cch) &&

                        (cCR < nCurrentLine); i++) {

                    if (pchInputBuf[i] == 0x0D)

                        ++cCR;

                }

                nBegLine = i;

            }

            /*

             * Starting at the beginning of the selected line,

             * measure  the width of each character, summing the

             * width with each character measured. Stop when the

             * sum is greater than the x-coordinate of the cursor.

             * The sum is used to set the x-coordinate of the caret.

             */

            hdc = GetDC(hwndMain);

            nCaretPosX = 0;

            for (i = nBegLine;

                    (pchInputBuf[i] != 0x0D) && (i < cch); i++) {

                ch = pchInputBuf[i];

                GetCharWidth32(hdc, (int) ch, (int) ch, &nCharWidth);

                if ((nCaretPosX + nCharWidth) > ptsCursor.x)

                    break;

                else

                    nCaretPosX += nCharWidth;

            }

            ReleaseDC(hwndMain, hdc);

            /* Set the caret to the user-selected position. */

            SetCaretPos(nCaretPosX, nCurrentLine * dwLineHeight);

            break;

        case WM_LBUTTONDBLCLK:

            /* Copy the selected line of text to a buffer. */

            for (i = nBegLine, j = 0; (pchInputBuf[i] != 0x0D) &&

                    (i < cch); i++)

                szHilite[j++] = pchInputBuf[i];

            szHilite[j] = '\0';

            /*

             * Hide the caret, invert the background and foreground

             * colors, and then redraw the selected line.

             */

            HideCaret(hwndMain);

            hdc = GetDC(hwndMain);

            crPrevText = SetTextColor(hdc, RGB(255, 255, 255));

            crPrevBk = SetBkColor(hdc, RGB(0, 0, 0));

            TextOut(hdc, 0, nCurrentLine * dwLineHeight, szHilite,

                lstrlen(szHilite));

            SetTextColor(hdc, crPrevText);

            SetBkColor(hdc, crPrevBk);

            ReleaseDC(hwndMain, hdc);

            fTextSelected = TRUE;

            break;

            .

            . /* Process other messages. */

            .

        default:

            return DefWindowProc(hwndMain, uMsg, wParam, lParam);

    }

    return NULL;

}


 Mouse Input Reference

The following functions and messages are associated with mouse input.


 Mouse Input Functions

Following are the functions used with mouse input.

DragDetect
GetCapture
GetDoubleClickTime
mouse_event
ReleaseCapture
SetCapture
SetDoubleClickTime
SwapMouseButton


 Mouse Input Messages

Following are the messages used with mouse input.

WM_CAPTURECHANGED
WM_LBUTTONDBLCLK
WM_LBUTTONDOWN
WM_LBUTTONUP
WM_MBUTTONDBLCLK
WM_MBUTTONDOWN
WM_MBUTTONUP
WM_MOUSEACTIVATE
WM_MOUSEMOVE
WM_NCHITTEST
WM_NCLBUTTONDBLCLK
WM_NCLBUTTONDOWN
WM_NCLBUTTONUP
WM_NCMBUTTONDBLCLK
WM_NCMBUTTONDOWN
WM_NCMBUTTONUP
WM_NCMOUSEMOVE
WM_NCRBUTTONDBLCLK
WM_NCRBUTTONDOWN
WM_NCRBUTTONUP
WM_RBUTTONDBLCLK
WM_RBUTTONDOWN
WM_RBUTTONUP


 Painting and Drawing

This overview describes how Windows manages output to the screen and explains what applications must do to draw in a window. In particular, this overview describes display device contexts (or, more simply, display DCs) and how to prepare and use them. The overview does not explain how to use graphics device interface (GDI) functions to generate output, nor does it explain how to print.


 About Painting and Drawing

Nearly all applications use the screen to display the data they manipulate. An application paints images, draws figures, and writes text so that the user can view data as it is created, edited, and printed. Microsoft® Windows® provides a rich environment for painting and drawing, but, because Windows is a multitasking operating system, applications must cooperate with one another when accessing the screen.

To keep all applications functioning smoothly and cooperatively, Windows manages all output to the screen. Applications use windows as their primary output device rather than the screen itself. Windows supplies display DCs that uniquely correspond to the windows. Applications use display DCs to direct their output to the given windows. Drawing in a window (directing output to it) prevents an application from interfering with the output of other applications and allows applications to coexist with one another while still taking full advantage of the graphics capabilities of Windows.


 When to Draw in a Window

An application draws in a window at a variety of times: when first creating a window, when changing the size of the window, when moving the window from behind another window, when minimizing or maximizing the window, when displaying data from an opened file, and when scrolling, changing, or selecting a portion of the displayed data.

Windows manages actions such as moving and sizing a window. If an action affects the content of the window, Windows marks the affected portion of the window as ready for updating and, at the next opportunity, sends a WM_PAINT message to the window procedure of the window. The message is a signal to the application to determine what must be updated and to carry out the necessary drawing.

Some actions are managed by the application, such as displaying open files and selecting displayed data. For these actions, an application can mark for updating the portion of the window affected by the action, causing a WM_PAINT message to be sent at the next opportunity. If an action requires immediate feedback, the application can draw while the action takes place, without waiting for WM_PAINT. For example, a typical application highlights the area the user selects rather than waiting for the next WM_PAINT message to update the area.

In all cases, an application can draw in a window as soon as it is created. To draw in the window, the application must first retrieve a handle of a display DC for the window. Ideally, an application carries out most of its drawing operations during the processing of WM_PAINT messages. In this case, the application retrieves a display DC by calling the BeginPaint function. If an application draws at any other time, such as from within WinMain or during processing of keyboard or mouse messages, it calls the GetDC or GetDCEx function to retrieve the display DC.


 The WM_PAINT Message

Typically, an application draws in a window in response to a WM_PAINT message. Windows sends this message to a window procedure when changes to the window have altered the content of the client area. Windows sends the message only if there are no other messages in the application message queue.

Upon receiving a WM_PAINT message, an application can call BeginPaint to retrieve the display DC for the client area and use it in calls to GDI functions to carry out whatever drawing operations are necessary to update the client area. After completing the drawing operations, the application calls the EndPaint function to release the display DC.

Before BeginPaint returns the display DC, Windows prepares the DC for the given window. It first sets the clipping region for the DC to be equal to the intersection of the portion of the window that needs updating and the portion that is visible to the user. Only those portions of the window that have changed are redrawn. Attempts to draw outside this region are clipped and do not appear on the screen.

Windows can also send WM_NCPAINT and WM_ERASEBKGND messages to the window procedure before BeginPaint returns. These messages direct the application to draw the nonclient area and window background. The nonclient area is the part of a window that is outside of the client area. The area includes features such as the title bar, System menu (also known as the Control menu), and scroll bars. Most applications rely on the default window function, DefWindowProc, to draw this area and therefore pass the WM_NCPAINT message to this function. The window background is the color or pattern a window is filled with before other drawing operations begin. The background covers any images previously in the window or on the screen under the window. If a window belongs to a window class having a class background brush, the DefWindowProc function draws the window background automatically.

BeginPaint fills a PAINTSTRUCT structure with information such as the dimensions of the portion of the window to be updated and a flag indicating whether the window background has been drawn. The application can use this information to optimize drawing. For example, it can use the dimensions of the update region, specified by the rcPaint member, to limit drawing to only those portions of the window that need updating. If an application has very simple output, it can ignore the update region and draw in the entire window, relying on Windows to discard (clip) any unneeded output. Because the system clips drawing that extends outside the clipping region, only drawing that is in the update region is visible.

BeginPaint sets the update region of a window to NULL. This clears the region, preventing it from generating subsequent WM_PAINT messages. If an application processes a WM_PAINT message but does not call BeginPaint or otherwise clear the update region, the application continues to receive WM_PAINT messages as long as the region is not empty. In all cases, an application must clear the update region before returning from the WM_PAINT message.

After the application finishes drawing, it should call EndPaint. For most windows, EndPaint releases the display DC, making it available to other windows. EndPaint also shows the caret, if it was previously hidden by BeginPaint. BeginPaint hides the caret to prevent drawing operations from corrupting it.


 The Update Region

The update region identifies the portion of a window that is out-of-date or invalid and in need of redrawing. Windows uses the update region to generate WM_PAINT messages for applications and to minimize the time applications spend bringing the contents of their windows up to date. Windows adds only the invalid portion of the window to the update region, requiring only that portion to be drawn.

When Windows determines that a window needs updating, it sets the dimensions of the update region to the invalid portion of the window. Setting the update region does not immediately cause the application to draw. Instead, the application continues retrieving messages from the application message queue until no messages remain. Windows then checks the update region, and if the region is not empty (non-NULL), it sends a WM_PAINT message to the window procedure.

An application can use the update region to generate its WM_PAINT messages. For example, an application that loads data from open files typically sets the update region while loading so that new data is drawn during processing of the next WM_PAINT message. In general, an application should not draw at the time its data changes, but route all drawing operations through the WM_PAINT message.


 Invalidating and Validating the Update Region

An application invalidates a portion of a window and sets the update region by using the InvalidateRect or InvalidateRgn function. These functions add the specified rectangle or region (given in client coordinates) to the update region, combining the rectangle or region with anything Windows or the application may have previously added to the update region.

The InvalidateRect and InvalidateRgn functions do not generate WM_PAINT messages. Instead, Windows accumulates the changes made by these functions and its own changes while a window processes other messages in its message queue. By accumulating changes, a window processes all changes at once instead of updating bits and pieces one step at a time.

The ValidateRect and ValidateRgn functions validate a portion of the window by removing a specified rectangle or region from the update region. These functions are typically used when the window has updated a specific part of the screen in the update region before receiving the WM_PAINT message.


 Retrieving the Update Region

The GetUpdateRect and GetUpdateRgn functions retrieve the current update region for the window. GetUpdateRect retrieves the smallest rectangle (in client coordinates) that encloses the entire update region. GetUpdateRgn retrieves the update region itself. These functions can be used to calculate the current size of the update region to determine where to carry out a drawing operation.

BeginPaint also retrieves the dimensions of the smallest rectangle enclosing the current update region, copying the dimensions to the rcPaint member in the PAINTSTRUCT structure. Because BeginPaint validates the update region, any call to GetUpdateRect and GetUpdateRgn immediately after a call to BeginPaint returns an empty update region.


 Excluding the Update Region

The ExcludeUpdateRgn function excludes the update region from the clipping region for the display DC. This function is useful when drawing in a window other than when a WM_PAINT message is processing. It prevents drawing in the areas that will be updated during the next WM_PAINT message.


 Synchronous and Asynchronous Drawing

Most drawing carried out during processing of the WM_PAINT message is asynchronous; that is, there is a delay between the time a portion of the window is invalidated and the time WM_PAINT is sent. During the delay, the application typically retrieves messages from the queue and carries out other tasks. The reason for the delay is that Windows generally treats drawing in a window as a low-priority operation and works as though user-input messages and messages that may affect the position or size of a window will be processed before WM_PAINT.

In some cases, it is necessary for an application to draw synchronously — that is, draw in the window immediately after invalidating a portion of the window. A typical application draws its main window immediately after creating the window to signal the user that the application has started successfully. Windows draws some control windows synchronously, such as buttons, because such windows serve as the focus for user input. Although any window with a simple drawing routine can be drawn synchronously, all such drawing should be done quickly and should not interfere with the application's ability to respond to user input.

The UpdateWindow and RedrawWindow functions allow for synchronous drawing. UpdateWindow sends a WM_PAINT message directly to the window if the update region is not empty. RedrawWindow also sends a WM_PAINT message, but gives the application greater control over how to draw the window, such as whether to draw the nonclient area and window background or whether to send the message regardless of whether the update region is empty. These functions send the WM_PAINT message directly to the window, regardless of the number of other messages in the application message queue.

Any window requiring time-consuming drawing operations should be drawn asynchronously to prevent pending messages from being blocked as the window is drawn. Also, any application that frequently invalidates small portions of a window should allow these invalid portions to consolidate into a single asynchronous WM_PAINT message, rather than a series of synchronous WM_PAINT messages.


 Drawing Without the WM_PAINT Message

Although applications carry out most drawing operations while the WM_PAINT message is processing, it is sometimes more efficient for an application to draw directly in a window without relying on the WM_PAINT message. This can be useful when the user needs immediate feedback, such as when selecting text and dragging or sizing an object. In such cases, the application usually draws while processing keyboard or mouse messages.

To draw in a window without using a WM_PAINT message, the application uses the GetDC or GetDCEx function to retrieve a display DC for the window. With the display DC, the application can draw in the window and avoid intruding into other windows. When the application has finished drawing, it calls the ReleaseDC function to release the display DC for use by other applications.

When drawing without using a WM_PAINT message, the application usually does not invalidate the window. Instead, it draws in such a fashion that it can easily restore the window and remove the drawing. For example, when the user selects text or an object, the application typically draws the selection by inverting whatever is already in the window. The application can remove the selection and restore the original contents of the window by simply inverting again.

The application is responsible for carefully managing any changes it makes to the window. In particular, if an application draws a selection and an intervening WM_PAINT message occurs, the application must ensure that any drawing done during the message does not corrupt the selection. To avoid this, many applications remove the selection, carry out usual drawing operations, and then restore the selection when drawing is complete.


 Window Coordinate System

The coordinate system for a window is based on the coordinate system of the display device. The basic unit of measure is the device unit (typically, the pixel). Points on the screen are described by x- and y-coordinate pairs. The x-coordinates increase to the right; y-coordinates increase from top to bottom. The origin (0,0) for the system depends on the type of coordinates being used.

Windows and applications specify the position of a window on the screen in screen coordinates. For screen coordinates, the origin is the upper left corner of the screen. The full position of a window is often described by a RECT structure containing the screen coordinates of two points that define the upper left and lower right corners of the window.

Windows and applications specify the position of points in a window by using client coordinates. The origin in this case is the upper left corner of the window or client area. Client coordinates ensure that an application can use consistent coordinate values while drawing in the window, regardless of the position of the window on the screen.

The dimensions of the client area are also described by a RECT structure that contains client coordinates for the area. In all cases, the upper left coordinate of the rectangle is included in the window or client area, while the lower right coordinate is excluded. Graphics operations in a window or client area are excluded from the right and lower edges of the enclosing rectangle.

Occasionally, applications may be required to map coordinates in one window to those of another window. An application can map coordinates by using the MapWindowPoints function. If one of the windows is the desktop window, the function effectively converts screen coordinates to client coordinates and vice versa; the desktop window is always specified in screen coordinates.


 Window Regions

In addition to the update region, every window has a visible region that defines the window portion visible to the user. The system changes the visible region for the window whenever the window changes size or whenever another window is moved such that it obscures or exposes a portion of the window. Applications cannot change the visible region directly, but Windows automatically uses the visible region to create the clipping region for any display DC retrieved for the window.

The clipping region determines where the system permits drawing. When the application retrieves a display DC using the BeginPaint, GetDC, or GetDCEx function, the system sets the clipping region for the DC to the intersection of the visible region and the update region. Applications can change the clipping region by using functions such as SetWindowRgn, SelectClipPath and SelectClipRgn, to further limit drawing to a particular portion of the update area.

The WS_CLIPCHILDREN and WS_CLIPSIBLINGS styles further specify how Windows calculates the visible region for a window. If a window has one or both of these styles, the visible region excludes any child window or sibling windows (windows having the same parent window). Therefore, drawing that would otherwise intrude in these windows will always be clipped.


 Window Background

The window background is the color or pattern used to fill the client area before a window begins drawing. The window background covers whatever was on the screen before the window was moved there, erasing existing images and preventing the application's new output from being mixed with unrelated information.

Windows paints the background for a window or gives the window the opportunity to do so by sending it a WM_ERASEBKGND message when the application calls BeginPaint. If an application does not process the message but passes it to DefWindowProc, Windows erases the background by filling it with the pattern in the background brush specified by the window's class. If the brush is not valid or the class has no background brush, Windows sets the fErase member in the PAINTSTRUCT structure BeginPaint returns, but carries out no other action. The application then has a second chance to draw the window background, if necessary.

If it processes WM_ERASEBKGND, the application should use the message's wParam parameter to draw the background. This parameter contains the handle of the display DC for the window. After drawing the background, the application should return a nonzero value. This ensures that BeginPaint does not erroneously set the fErase member of the PAINTSTRUCT structure to a nonzero value (indicating the background should be erased) when the application processes the subsequent WM_PAINT message.

An application can define a class background brush by assigning a brush handle or a system color value to the hbrBackground member of the WNDCLASS structure when registering the class with the RegisterClass function. The GetStockObject or CreateSolidBrush function can be used to create a brush handle. A system color value can be one of those defined for the SetSysColors function. (The value must be increased by one before it is assigned to the member.)

An application can process the WM_ERASEBKGND message even though a class background brush is defined. This is typical in applications that enable the user to change the window background color or pattern for a given window without affecting other windows in the class. In such cases, the application must not pass the message to DefWindowProc.

It is not necessary for an application to align brushes, because the system draws the brush using the window origin as the point of reference. Given this, the user can move the window without affecting the alignment of pattern brushes.


 Minimized Windows

Windows reduces an application's main window (overlapping style) to a minimized window when the user chooses the Minimize command from the System menu or the application calls the ShowWindow function and specifies a value such as SW_MINIMIZE. Minimizing a window speeds up system performance by reducing the amount of work an application must do when updating its main window.

For a typical application, Windows draws an icon, called the class icon, when the window is minimized, labeling the icon with the name of the window. The class icon, a static image that represents the application, is specified by the application when it registers the window class. The application assigns the handle of the class icon to the hIcon member of WNDCLASS before calling RegisterClass. The application can use the LoadIcon function to retrieve the icon handle.

Before drawing the class icon, Windows sends a WM_ICONERASEBKGND message to the window procedure, enabling the application to prepare the background for drawing the icon by setting the best possible background colors for the icon. This is useful for applications that combine the icon with the current background colors. If the application processes the message, it should use the display DC provided with the message to draw the background (the wParam parameter contains the handle of the display DC). If the application does not process the WM_ICONERASEBKGND message, it should pass the message to DefWindowProc; the function fills the icon area with the current desktop color and pattern. After sending the WM_ICONERASEBKGND message, Windows sends the WM_PAINTICON message to the window procedure. The application should immediately forward this internal message to DefWindowProc.

Windows does not require that a window class have a class icon. If an application sets the hIcon member of WNDCLASS to NULL, a class icon is not defined. In this case, Windows sends the WM_ERASEBKGND message (instead of WM_ICONERASEBKGND) to a window of the class whenever the window must paint the icon background. Windows then sends a WM_PAINT message and the application draws an icon or another image representing the minimized window. In such cases, the application must determine when the window is minimized and draw accordingly. It can do so by calling the IsIconic function. If the function returns TRUE, the window is minimized. If an application has no class icon and fails to process WM_ERASEBKGND and WM_PAINT, the area that Windows reserves for the application's icon will contain whatever was previously on the screen.


 Window Size

Windows changes the size of a window when the user chooses System menu commands, such as Size and Maximize, or when the application calls functions, such as the SetWindowPos function. When a window changes size, Windows assumes that the contents of the previously exposed portion of the window are not affected and need not be redrawn. Windows invalidates only the newly exposed portion of the window, which saves time when the eventual WM_PAINT message is processed by the application. In this case, WM_PAINT is not generated when the size of the window is reduced.

For some windows, any change to the size of the window invalidates the contents. For example, a clock application that adapts the face of the clock to fit neatly within its window must redraw the clock whenever the window changes size. To force Windows to invalidate the entire client area of the window when a vertical, horizontal, or both vertical and horizontal change is made, an application must specify the CS_VREDRAW or CS_HREDRAW style, or both, when registering the window class. Any window belonging to a window class having these styles is invalidated each time the user or the application changes the size of the window.


 Nonclient Area

Windows sends a WM_NCPAINT message to the window whenever a part of the nonclient area of the window, such as the title bar, menu bar, or window frame, must be updated. Windows may also send other messages to direct a window to update a portion of its client area; for example, when a window becomes active or inactive, it sends the WM_NCACTIVATE message to update its title bar. In general, processing these messages for standard windows is not recommended, because the application must be able to draw all the required parts of the nonclient area for the window. For this reason, most applications pass these messages to DefWindowProc for default processing.

An application that creates custom nonclient areas for its windows must process these messages. When doing so, the application must use a window DC to carry out drawing in the window. The window DC enables the application to draw in all portions of the window, including the nonclient area. An application retrieves a window DC by using the GetWindowDC or GetDCEx function and, when drawing is complete, must release the window DC by using the ReleaseDC function.

Windows maintains an update region for the nonclient area. When an application receives a WM_NCPAINT message, the wParam parameter contains the handle of a region defining the dimensions of the update region. The application can use the handle to combine the update region with the clipping region for the window DC. Windows does not automatically combine the update region when retrieving the window DC unless the application uses GetDCEx and specifies both the region handle and the DCX_INTERSECTRGN flag. If the application does not combine the update region, only drawing operations that would otherwise extend outside the window are clipped. The application is not responsible for clearing the update region, regardless of whether it uses the region.

If an application processes the WM_NCACTIVATE message, after processing it must return TRUE to direct Windows to complete the change of active window. If the window is minimized when the application receives the WM_NCACTIVATE message, it should pass the message to DefWindowProc. In such cases, the default function redraws the label for the icon.


 Child Windows

A child window is a window with the WS_CHILD or WS_CHILDWINDOW style. Like other window styles, child windows receive WM_PAINT messages to prompt updating. Each child window has an update region, which either Windows or the application can set to generate eventual WM_PAINT messages.

A child window's update and visible regions are affected by the child's parent window; this is not true for windows of other styles. Windows often sets the child window's update region when it sets the parent window's update region, causing the child window to receive WM_PAINT messages when the parent window receives them. Windows limits the location of the child window's visible region to within the client area of the parent window and clips any portion of the child window moved outside the parent window.

Windows sets the update region for a child window whenever part of the parent window's update region includes a portion of the child window. In such cases, Windows first sends a WM_PAINT message to the parent window and then sends a message to the child window, allowing the child to restore any portions of the window that the parent may have drawn over.

Windows does not set the parent's update region when the child's is set. An application cannot generate a WM_PAINT message for the parent window by invalidating the child window. Similarly, an application cannot generate a WM_PAINT message for the child by invalidating a portion of the parent's client area that lies entirely under the child window. In such cases, neither window receives a WM_PAINT message.

An application can prevent a child window's update region from being set when the parent window's is set by specifying the WS_CLIPCHILDREN style when creating the parent window. When this style is set, Windows excludes the child windows from the parent's visible region and therefore ignores any portion of the update region that may contain the child windows. When the application paints in the parent window, any drawing that would cover the child window is clipped, making a subsequent WM_PAINT message to the child window unnecessary.

The update and visible regions of a child window are also affected by the child window's siblings. Sibling windows are any windows that have a common parent window. If sibling windows overlap, then setting the update region for one affects the update region of another, causing WM_PAINT messages to be sent to both windows. Sibling windows receive WM_PAINT messages in the reverse order of their position in the Z order. Given this, the window highest in the Z order (on the top) receives its WM_PAINT message last, and vice versa.

Sibling windows are not automatically clipped. One sibling can draw over another overlapping sibling even if the window that is drawing has a lower position in the Z order. An application can prevent this by specifying the WS_CLIPSIBLINGS style when creating the windows. When this style is set, Windows excludes all portions of an overlapping sibling window from a window's visible region if the overlapping sibling window has a higher position in the Z order.

Note  The update and visible regions for windows that have the WS_POPUP or WS_POPUPWINDOW style are not affected by their parent windows.


 About Display Device Contexts

A display DC is a device context, created by Windows, that an application uses to paint and draw a window. Windows prepares each display DC for output to a window, setting the drawing objects, colors, and modes for the window instead of for the display device. When the application supplies the display DC through calls to GDI functions, GDI uses the information in the context to generate output in the given window without intruding on other windows or other parts of the screen.

Windows provides five kinds of display DC: common, class, parent, private, and window. The common, class, and private DCs permit drawing in the client area of a given window. The parent and window DCs permit drawing anywhere in the window. Although the parent DC also permits drawing in the parent window, it is not intended to be used in this way.

Windows supplies a common, class, parent, or private DC to a window based on the type of display DC specified in that window's class style. Windows supplies a window DC only when the application explicitly requests one — for example, by calling the GetWindowDC or GetDCEx function. In all cases, an application can use the WindowFromDC function to determine which window a display DC currently represents.


 Display Device Context Cache

Windows maintains a cache of display DCs that it uses for common, parent, and window DCs. Windows retrieves a DC from the cache whenever an application calls the GetDC or BeginPaint function; Windows returns the DC to the cache when the application subsequently calls the ReleaseDC or EndPaint function.

In Windows 3.x, the cache contains five display DCs, but only five DCs from the cache can be active at a time. To ensure that other applications have access to these DCs, an application must release a device context immediately after using it. Failure to do so eventually causes the application to fail.

There is no predetermined limit on the amount of DCs that a cache can hold; Windows creates a new display DC for the cache if none is available. Given this, a Win32-based application can have more than five active DCs from the cache at a time. However, the application must continue to release these DCs after use. Because new display DCs for the cache are allocated in the application's heap space, failing to release the DCs eventually consumes all available heap space. Windows indicates this failure by returning an error when it cannot allocate space for the new DC. Other functions unrelated to the cache may also return errors.

Portability  To minimize porting efforts, applications that use common DCs should be limited to no more than five and ensure that a common DC is released as soon as possible after it is used.


 Display Device Context Defaults

Upon first creating a display DC, Windows assigns default values for the attributes (that is, drawing objects, colors, and modes) that comprise the DC. The following table shows the default values for the attributes of a display DC.

Attribute	Default value
Background color	Background color setting from Windows Control Panel (typically, white).
Background mode	OPAQUE.
Bitmap	None.
Brush	WHITE_BRUSH.
Brush origin	(0,0).
Clipping region	Entire window or client area with the update region clipped, as appropriate. Child and pop-up windows in the client area may also be clipped.
Palette	DEFAULT_PALETTE.
Current pen position	(0,0).
Device origin	Upper left corner of the window or the client area.
Drawing mode	R2_COPYPEN.
Font	SYSTEM_FONT (SYSTEM_FIXED_FONT for applications written to run with Windows versions 3.0 and earlier).
Intercharacter spacing	0.
Mapping mode	MM_TEXT.
Pen	BLACK_PEN.
Polygon-fill mode	ALTERNATE.
Stretch mode	BLACKONWHITE.
Text color	Text color setting from Control Panel (typically, black).
Viewport extent	(1,1).
Viewport origin	(0,0).
Window extent	(1,1).
Window origin	(0,0).
An application can modify the values of the display DC attributes by using selection and attribute functions, such as SelectObject, SetMapMode, and SetTextColor. For example, an application can modify the default units of measure in the coordinate system by using SetMapMode to change the mapping mode.

Changes to the attribute values of a common, parent, or window DC are not permanent. When an application releases these DCs, the current selections, such as mapping mode and clipping region, are lost as the context is returned to the cache. Changes to a class or private DC persist indefinitely. To restore them to their original defaults, an application must explicitly set each attribute.


 Common Display Device Contexts

A common DC is used for drawing in the client area of the window. The Win32 API provides a common DC by default for any window whose window class does not explicitly specify a display DC style. Common DCs are typically used with windows that can be drawn without extensive changes to the DC attributes. Common DCs are convenient because they do not require additional memory or system resources, but they can be inconvenient if the application must set up many attributes before using them.

Windows retrieves all common DCs from the display DC cache. An application can retrieve a common DC immediately after the window is created. Because the common DC is from the cache, the application must always release the DC as soon as possible after drawing. After the common DC is released, it is no longer valid and the application must not attempt to draw with it. To draw again, the application must retrieve a new common DC, and continue to retrieve and release a common DC each time it draws in the window. If the application retrieves the DC handle by using the GetDC function, it must use the ReleaseDC function to release the handle. Similarly, for each BeginPaint function, the application must use a corresponding EndPaint function.

When the application retrieves the DC, Windows adjusts the origin so that it aligns with the upper left corner of the client area. It also sets the clipping region so that output to the DC is clipped to the client area. Any output that would otherwise appear outside the client area is clipped. If the application retrieves the common DC by using BeginPaint, Windows also includes the update region in the clipping region to further restrict the output.

When an application releases a common DC, Windows restores the default values for the attributes of the DC. An application that modifies attribute values must do so each time it retrieves a common DC. Releasing the DC releases any drawing objects the application may have selected into it, so the application need not release these objects before releasing the DC. In all cases, an application must never assume that the common DC retains nondefault selections after being released.


 Private Display Device Contexts

A private DC enables an application to avoid retrieving and initializing a display DC each time the application must draw in a window. Private DCs are useful for windows that require many changes to the values of the attributes of the DC to prepare it for drawing. Private DCs reduce the time required to prepare the DC and therefore the time needed to carry out drawing in the window.

An application directs Windows to create a private DC for a window by specifying the CS_OWNDC style in the window class. Windows creates a unique private DC each time it creates a new window belonging to the class. Initially, the private DC has the same default values for attributes as a common DC, but the application can modify these at any time. Windows preserves changes to the DC for the life of the window or until the application makes additional changes.

An application can retrieve the handle of the private DC by using the GetDC function any time after the window is created. The application must retrieve the handle only once. Thereafter, it can keep and use the handle any number of times. Because a private DC is not part of the display DC cache, an application need never release the DC by using the ReleaseDC function.

Windows automatically adjusts the DC to reflect changes to the window, such as moving or sizing. This ensures that any overlapping windows are always properly clipped; that is, no action is required by the application to ensure clipping. However, Windows does not revise the DC to include the update region. Therefore, when processing a WM_PAINT message, the application must incorporate the update region either by calling BeginPaint or by retrieving the update region and intersecting it with the current clipping region. If the application does not call BeginPaint, it must explicitly validate the update region by using the ValidateRect or ValidateRgn function. If the application does not validate the update region, the window receives an endless series of WM_PAINT messages.

Because BeginPaint hides the caret if a window is showing it, an application that calls BeginPaint should also call the EndPaint function to restore the caret. EndPaint has no other effect on a private DC.

Although a private DC is convenient to use, it is expensive in terms of system resources, requiring 800 or more bytes to store. Private DCs are recommended when performance considerations outweigh storage costs.

Windows includes the private DC when sending the WM_ERASEBKGND message to the application. The current selections of the private DC, including mapping mode, are in effect when the application or Windows processes these messages. To avoid undesirable effects, Windows uses logical coordinates when erasing the background; for example, it uses the GetClipBox function to retrieve the logical coordinates of the area to erase and passes these coordinates to the FillRect function. Applications that process these messages can use similar techniques. Windows supplies a window DC with the WM_ICONERASEBKGND message regardless of whether the corresponding window has a private DC.

An application can use the GetDCEx function to force Windows to return a common DC for the window that has a private DC. This is useful for carrying out quick touch-ups to a window without changing the current values of the attributes of the private DC.


 Class Display Device Contexts

By using a class DC, an application can use a single display DC for every window belonging to a given class. Class DCs are often used with control windows that are drawn using the same attribute values. Like private DCs, class DCs minimize the time required to prepare a DC for drawing.

Windows supplies a class DC for a window if it belongs to a window class having the CS_CLASSDC style. Windows creates the DC when creating the first window belonging to the class and then uses the same DC for all subsequently created windows in the class. Initially, the class DC has the same default values for attributes as a common DC, but the application can modify these at any time. Windows preserves all changes, except for the clipping region and device origin, until the last window in the class has been destroyed. A change made for one window applies to all windows in that class.

An application can retrieve the handle for the class DC by using the GetDC function any time after the first window has been created. The application can keep and use the handle without releasing it because the class DC is not part of the display DC cache. If the application creates another window in the same window class, the application must retrieve the class DC again. Retrieving the DC sets the correct device origin and clipping region for the new window. After the application retrieves the class DC for a new window in the class, the DC can no longer be used to draw in the original window without again retrieving it for that window. In general, each time it must draw in a window, an application must explicitly retrieve the class DC for the window.

Applications that use class DCs should always call BeginPaint when processing a WM_PAINT message. The function sets the correct device origin and clipping region for the window, and incorporates the update region. The application should also call EndPaint to restore the caret if BeginPaint hid it. EndPaint has no other effect on a class DC.

Windows passes the class DC when sending the WM_ERASEBKGND message to the application, permitting the current attribute values to affect any drawing carried out by the application or Windows when processing this message. Windows supplies a window DC with the WM_ICONERASEBKGND message regardless of whether the corresponding window has a class DC. As it could with a window having a private DC, an application can use GetDCEx to force Windows to return a common DC for the window that has a class DC.

Using class DCs is not recommended.


 Window Display Device Contexts

A window DC enables an application to draw anywhere in a window, including the nonclient area. Window DCs are typically used by applications that process the WM_NCPAINT and WM_NCACTIVATE messages for windows with custom nonclient areas. Using a window DC is not recommended for any other purpose.

An application can retrieve a window DC by using the GetWindowDC or GetDCEx function with the DCX_WINDOW option specified. The function retrieves a window DC from the display DC cache. A window that uses a window DC must release it after drawing by using the ReleaseDC function as soon as possible. Window DCs are always from the cache; the CS_OWNDC and CS_CLASSDC class styles do not affect the DC.

When an application retrieves a window DC, Windows sets the device origin to the upper left corner of the window instead of the upper left corner of the client area. It also sets the clipping region to include the entire window, not just the client area. Windows sets the current attribute values of a window DC to the same default values as a common DC. An application can change the attribute values, but Windows does not preserve any changes when the DC is released.


 Parent Display Device Contexts

A parent DC enables an application to minimize the time necessary to set up the clipping region for a window. An application typically uses parent DCs to speed up drawing for control windows without requiring a private or class DC. For example, Windows uses parent DCs for push button and edit controls. Parent DCs are intended for use with child windows only, never with top-level or pop-up windows.

Windows supplies a parent DC for any window belonging to a window class specifying the CS_PARENTDC style. An application can retrieve the parent DC by using GetDC immediately after the window is created. Windows always retrieves the parent DC from the display DC cache even if the parent uses a private or class DC, so the application must release the DC by using ReleaseDC as soon as possible after drawing. When processing a WM_PAINT message, the application must retrieve the parent DC by using BeginPaint and release it by using EndPaint.

When a parent DC is retrieved, Windows searches the cache for the display DC previously used by the parent window. In most cases, the parent window retrieves and releases a display DC before the child window attempts to retrieve one, so the parent DC is usually in the cache. If Windows finds the display DC, Windows uses it and its corresponding clipping region, which was previously calculated for the parent DC. The time saved is in skipping the calculation required to define the clipping region. If Windows does not find the parent DC, it retrieves a common DC for the window and calculates the clipping region for the window rather than for the parent window.

Windows sets the device origin for the parent DC to the upper left corner of the child window. Attribute values set by the parent window are not preserved for the child window; for example, the parent window cannot set the brush for its child windows. The only property preserved is the clipping region. The window must clip its own output to the limits of the window. Because the clipping region for the parent DC is identical to the parent window, the child window can potentially draw over the entire parent window, but the parent DC must not be used in this way.

Windows ignores the CS_PARENTDC style if the parent window uses a private or class DC, if the parent window clips its child windows, or if the child window clips its child windows or sibling windows. In these cases, Windows always retrieves a common DC for the window.


 Window Update Lock

A window update lock is a temporary suspension of drawing in a window. Windows uses the lock to prevent other windows from drawing over the tracking rectangle whenever the user moves or sizes a window. Applications can use the lock to prevent drawing if they carry out similar moving or sizing operations with their own windows.

An application uses the LockWindowUpdate function to set or clear a window update lock, specifying the window to lock. The lock applies to the given window and all of its child windows. When the lock is set, the GetDC and BeginPaint functions return a display DC with a visible region that is empty. Given this, the application can continue to draw in the window, but all output is clipped. The lock persists until the application clears it by calling LockWindowUpdate, specifying NULL for the window. Although LockWindowUpdate forces a window's visible region to be empty, the function does not make the given window invisible and does not clear the WS_VISIBLE style bit.

After the lock is set, the application can use the GetDCEx function, with the DCX_LOCKWINDOWUPDATE value, to retrieve a display DC to draw over the locked window. This allows the application to draw a tracking rectangle when processing keyboard or mouse messages. Windows uses this method when the user moves and sizes windows. GetDCEx retrieves the display DC from the display DC cache, so the application must release the DC as soon as possible after drawing.

While a window update lock is set, the system creates an accumulated bounding rectangle for each locked window. When the lock is cleared, Windows uses this bounding rectangle to set the update region for the window and its child windows, forcing an eventual WM_PAINT message. If the accumulated bounding rectangle is empty (that is, if no drawing has occurred while the lock was set), the update region is not set.


 Accumulated Bounding Rectangle

The accumulated bounding rectangle is the smallest rectangle enclosing the portion of a window or client area affected by recent drawing operations. An application can use this rectangle to conveniently determine the extent of changes caused by drawing operations. It is sometimes used in conjunction with LockWindowUpdate to determine which portion of the client area must be redrawn after the update lock is cleared.

An application uses the SetBoundsRect function (specifying DCB_ENABLE) to begin accumulating the bounding rectangle. Windows subsequently accumulates points for the bounding rectangle as the application uses the specified display DC. The application can retrieve the current bounding rectangle at any time by using the GetBoundsRect function. The application stops the accumulation by calling SetBoundsRect again, specifying the DCB_DISABLE value.


 Using the WM_PAINT Message

You can use the WM_PAINT message to carry out the drawing necessary for displaying information. Because Windows sends WM_PAINT messages to your application when your window must be updated or when you explicitly request an update, you can consolidate the code for drawing in your application's window procedure. You can then use this code whenever your application must draw either new or existing information.

The following sections show a variety of ways to use the WM_PAINT message to draw in a window.

•	Drawing in the client area

•	Redrawing the entire client area

•	Redrawing in the update region

•	Invalidating the client area

•	Drawing a minimized window

•	Drawing a custom window background


 Drawing in the Client Area

You use the BeginPaint and EndPaint functions to prepare for and complete the drawing in the client area. BeginPaint returns a handle of the display DC used for drawing in the client area; EndPaint ends the paint request and releases the DC.

In the following example, the window procedure writes the message "Hello, Windows!" in the client area. To make sure the string is visible when the window is first created, the WinMain function calls UpdateWindow immediately after creating and showing the window. This causes a WM_PAINT message to be sent immediately to the window procedure.

LRESULT APIENTRY WndProc(hwnd, message, wParam, lParam)

HWND hwnd;

UINT message;

WPARAM wParam;

LPARAM lParam;

{

    PAINTSTRUCT ps;

    HDC hdc;

    switch (message) {

        case WM_PAINT:

            hdc = BeginPaint(hwnd, &ps);

            TextOut(hdc, 0, 0, "Hello, Windows!", 15);

            EndPaint(hwnd, &ps);

            return 0L;

        .

        .

        .

    }

}

int APIENTRY WinMain(hInstance, hPrevInstance, lpCmdLine, nCmdShow)

HINSTANCE hInstance;         /* handle of current instance   */

HINSTANCE hPrevInstance;     /* handle of previous instance  */

LPSTR lpCmdLine;             /* address of command line      */

int nCmdShow;                /* show-window type (open/icon) */

{

    HWND hwnd;

    hwnd = CreateWindowEx( /* parameters */ );

    ShowWindow(hwnd, SW_SHOW);

    UpdateWindow(hwnd);

    .

    .

    .

    return msg.wParam;

}


 Redrawing the Entire Client Area

You can have your application redraw the entire contents of the client area whenever the window changes size by setting the CS_HREDRAW and CS_VREDRAW styles for the window class. Applications that adjust the size of the drawing based on the size of the window use these styles to ensure that they start with a completely empty client area when drawing.

In the following example, the window procedure draws a five-pointed star that fits neatly in the client area. It uses a common DC and must set the mapping mode as well as window and viewport extents each time the WM_PAINT message is processed.

LRESULT APIENTRY WndProc(hwnd, message, wParam, lParam)

HWND hwnd;

UINT message;

WPARAM wParam;

LPARAM lParam;

{

    PAINTSTRUCT ps;

    HDC hdc;

    RECT rc;

    POINT aptStar[6] = {50,2, 2,98, 98,33, 2,33, 98,98, 50,2};

    .

    .

    .

        case WM_PAINT:

            hdc = BeginPaint(hwnd, &ps);

            GetClientRect(hwnd, &rc);

            SetMapMode(hdc, MM_ANISOTROPIC);

            SetWindowExtEx(hdc, 100, 100, NULL);

            SetViewportExtEx(hdc, rc.right, rc.bottom, NULL);

            Polyline(hdc, aptStar, 6);

            EndPaint(hwnd, &ps);

            return 0L;

        .

        .

        .

}

int APIENTRY WinMain(hInstance, hPrevInstance, lpCmdLine, nCmdShow)

HINSTANCE hInstance;         /* handle of current instance   */

HINSTANCE hPrevInstance;     /* handle of previous instance  */

LPSTR lpCmdLine;             /* address of command line      */

int nCmdShow;                /* show-window type (open/icon) */

{

    WNDCLASS wc;

    .

    .

    .

        wc.style = CS_HREDRAW | CS_VREDRAW;

        wc.lpfnWndProc = (WNDPROC) WndProc;

    .

    .

    .

        RegisterClass(&wc);

    .

    .

    .

    return msg.wParam;

}


 Redrawing in the Update Region

You can limit the amount of drawing your application carries out when processing the WM_PAINT message by determining the size and location of the update region. Because Windows uses the update region when creating the clipping region for the window's display DC, you can indirectly determine the update region by examining the clipping region.

In the following example, the window procedure draws a triangle, a rectangle, a pentagon, and a hexagon, but only if all or a portion of each figure lies within the update region. The window procedure uses the RectVisible function and a 100-by-100 rectangle to determine whether a figure is within the clipping region (and therefore the update region) for the common DC retrieved by BeginPaint.

POINT aptTriangle[4]  = {50,2, 98,86,  2,86, 50,2},

      aptRectangle[5] = { 2,2, 98,2,  98,98,  2,98, 2,2},

      aptPentagon[6]  = {50,2, 98,35, 79,90, 21,90, 2,35, 50,2},

      aptHexagon[7]   = {50,2, 93,25, 93,75, 50,98, 7,75, 7,25, 50,2};

  .

  .

  .

        case WM_PAINT:

            hdc = BeginPaint(hwnd, &ps);

            SetRect(&rc, 0, 0, 100, 100);

            if (RectVisible(hdc, &rc))

                Polyline(hdc, aptTriangle, 4);

            SetViewportOrgEx(hdc, 100, 0, NULL);

            if (RectVisible(hdc, &rc))

                Polyline(hdc, aptRectangle, 5);

            SetViewportOrgEx(hdc, 0, 100, NULL);

            if (RectVisible(hdc, &rc))

                Polyline(hdc, aptPentagon, 6);

            SetViewportOrgEx(hdc, 100, 100, NULL);

            if (RectVisible(hdc, &rc))

                Polyline(hdc, aptHexagon, 7);

            EndPaint(hwnd, &ps);

            return 0L;

  .

  .

  .

The coordinates of each figure in this example lie within the same 100-by-100 rectangle. Before drawing a figure, the window procedure sets the viewport origin to a different part of the client area by using the SetViewportOrgEx function. This prevents figures from being drawn one on top of the other. Changing the viewport origin does not affect the clipping region, but does affect how the coordinates of the rectangle passed to RectVisible are interpreted. Changing the origin also allows you to use a single rectangle to check the update region rather than individual rectangles for each figure.


 Invalidating the Client Area

Windows is not the only source of WM_PAINT messages. The InvalidateRect or InvalidateRgn function can indirectly generate WM_PAINT messages for your windows. These functions mark all or part of a client area as invalid (that must be redrawn).

In the following example, the window procedure invalidates the entire client area when processing WM_CHAR messages. This allows the user to change the figure by typing a number and view the results; these results are drawn as soon as there are no other messages in the application's message queue.

POINT aptPentagon[6] = {50,2, 98,35, 79,90, 21,90, 2,35, 50,2},

      aptHexagon[7]  = {50,2, 93,25, 93,75, 50,98, 7,75, 7,25, 50,2};

POINT *ppt = aptPentagon;

int cpt = 6;

  .

  .

  .

case WM_CHAR:

    switch (wParam) {

    case '5':

        ppt = aptPentagon;

        cpt = 6;

        break;

    case '6':

        ppt = aptHexagon;

        cpt = 7;

        break;

    }

    InvalidateRect(hwnd, NULL, TRUE);

    return 0L;

case WM_PAINT:

    hdc = BeginPaint(hwnd, &ps);

    GetClientRect(hwnd, &rc);

    SetMapMode(hdc, MM_ANISOTROPIC);

    SetWindowExtEx(hdc, 100, 100, NULL);

    SetViewportExtEx(hdc, rc.right, rc.bottom, NULL);

    Polyline(hdc, ppt, cpt);

    EndPaint(hwnd, &ps);

    return 0L;

In this example, the NULL argument used by InvalidateRect specifies the entire client area; the TRUE argument causes the background to be erased. If you do not want the application to wait until the application's message queue has no other messages, use the UpdateWindow function to force the WM_PAINT message to be sent immediately. If there is any invalid part of the client area, UpdateWindow sends the WM_PAINT message for the given window directly to the window procedure.


 Drawing a Minimized Window

You can draw your own minimized windows rather than having Windows draw them for you. Most applications define a class icon when registering the window class for the window, and Windows draws the icon when the window is minimized. If you set the class icon to NULL, however, Windows sends a WM_PAINT message to your window procedure whenever the window is minimized, enabling the window procedure to draw in the minimized window.

In the following example, the window procedure draws a star in the minimized window. The procedure uses the IsIconic function to determine when the window is minimized. This ensures that the star is drawn only when the window is minimized.

POINT aptStar[6] = {50,2, 2,98, 98,33, 2,33, 98,98, 50,2};

  .

  .

  .

case WM_PAINT:

    hdc = BeginPaint(hwnd, &ps);

    /* Determine whether the window is minimized. */

    if (IsIconic(hwnd)) {

        GetClientRect(hwnd, &rc);

        SetMapMode(hdc, MM_ANISOTROPIC);

        SetWindowExtEx(hdc, 100, 100, NULL);

        SetViewportExtEx(hdc, rc.right, rc.bottom, NULL);

        Polyline(hdc, aptStar, 6);

    } else {

        TextOut(hdc, 0,0, "Hello, Windows!", 15);

    }

    EndPaint(hwnd, &ps);

    return 0L;

You set the class icon to NULL by setting the hIcon member of the WNDCLASS structure to NULL before calling the RegisterClass function for the window class.


 Drawing a Custom Window Background

You can draw your own window background rather than having Windows draw it for you. Most applications specify a brush handle or system color value for the class background brush when registering the window class; Windows uses the brush or color to draw the background. If you set the class background brush to NULL, however, Windows sends a WM_ERASEBKGND message to your window procedure whenever the window background must be drawn, letting you draw a custom background.

In the following example, the window procedure draws a large checkerboard pattern that fits neatly in the window. The procedure fills the client area with a white brush and then draws thirteen 20-by-20 rectangles using a gray brush. The display DC to use when drawing the background is specified in the wParam parameter for the message.

HBRUSH hbrWhite, hbrGray;

  .

  .

  .

case WM_CREATE:

    hbrWhite = GetStockObject(WHITE_BRUSH);

    hbrGray  = GetStockObject(GRAY_BRUSH);

    return 0L;

case WM_ERASEBKGND:

    hdc = (HDC) wParam;

    GetClientRect(hwnd, &rc);

    SetMapMode(hdc, MM_ANISOTROPIC);

    SetWindowExtEx(hdc, 100, 100, NULL);

    SetViewportExtEx(hdc, rc.right, rc.bottom, NULL);

    FillRect(hdc, &rc, hbrWhite);

    for (i = 0; i < 13; i++) {

        x = (i * 40) % 100;

        y = ((i * 40) / 100) * 20;

        SetRect(&rc, x, y, x + 20, y + 20);

        FillRect(hdc, &rc, hbrGray);

    }

  return 1L;

If the application draws its own minimized window, Windows also sends the WM_ERASEBKGND message to the window procedure to draw the background for the minimized window. You can use the same technique used by WM_PAINT to determine whether the window is minimized — that is, call the IsIconic function and check for the return value TRUE.


 Using the GetDC Function

You use the GetDC function to carry out drawing that must occur instantly rather than when a WM_PAINT message is processing. Such drawing is usually in response to an action by the user, such as making a selection or drawing with the mouse. In such cases, the user should receive instant feedback and must not be forced to stop selecting or drawing in order for the application to display the result. The following sections show how to use GetDC to draw in a window.


 Drawing with the Mouse

You can permit the user to draw lines with the mouse by having your window procedure draw while processing the WM_MOUSEMOVE message. Windows sends the WM_MOUSEMOVE message to the window procedure whenever the user moves the cursor within the window. To draw lines, the window procedure can retrieve a display DC and draw a line in the window between the current and previous cursor positions.

In the following example, the window procedure prepares for drawing when the user presses and holds the left mouse button (sending the WM_LBUTTONDOWN message). As the user moves the cursor within the window, the window procedure receives a series of WM_MOUSEMOVE messages. For each message, the window procedure draws a line connecting the previous position and the current position. To draw the line, the procedure uses GetDC to retrieve a display DC; then, as soon as drawing is complete and before returning from the message, the procedure uses the ReleaseDC function to release the display DC. As soon as the user releases the mouse button, the window procedure clears the flag, and the drawing stops (which sends the WM_LBUTTONUP message).

BOOL fDraw = FALSE;

POINT ptPrevious;

  .

  .

  .

case WM_LBUTTONDOWN:

    fDraw = TRUE;

    ptPrevious.x = LOWORD(lParam);

    ptPrevious.y = HIWORD(lParam);

    return 0L;

case WM_LBUTTONUP:

    if (fDraw) {

        hdc = GetDC(hwnd);

        MoveToEx(hdc, ptPrevious.x, ptPrevious.y, NULL);

        LineTo(hdc, LOWORD(lParam), HIWORD(lParam));

        ReleaseDC(hwnd, hdc);

    }

    fDraw = FALSE;

    return 0L;

case WM_MOUSEMOVE:

    if (fDraw) {

        hdc = GetDC(hwnd);

        MoveToEx(hdc, ptPrevious.x, ptPrevious.y, NULL);

        LineTo(hdc, ptPrevious.x = LOWORD(lParam),

          ptPrevious.y = HIWORD(lParam));

        ReleaseDC(hwnd, hdc);

    }

  return 0L;

An application that enables drawing, as in this example, typically records either the points or lines so that the lines can be redrawn whenever the window is updated. Drawing applications often use a memory DC and an associated bitmap to store lines that were drawn by using a mouse.


 Drawing at Timed Intervals

You can draw at timed intervals by creating a timer with the SetTimer function. By using a timer to send WM_TIMER messages to the window procedure at regular intervals, an application can carry out simple animation in the client area while other applications continue running.

In the following example, the application bounces a star from side to side in the client area. Each time the window procedure receives a WM_TIMER message, the procedure erases the star at the current position, calculates a new position, and draws the star within the new position. The procedure starts the timer by calling SetTimer while processing the WM_CREATE message.

RECT rcCurrent = {0,0,20,20};

POINT aptStar[6] = {10,1, 1,19, 19,6, 1,6, 19,19, 10,1};

int X = 2, Y = -1, idTimer = -1;

BOOL fVisible = FALSE;

HDC hdc;

LRESULT APIENTRY WndProc(hwnd, message, wParam, lParam)

HWND hwnd;

UINT message;

WPARAM wParam;

LPARAM lParam;

{

    PAINTSTRUCT ps;

    RECT rc;

    switch (message) {

        case WM_CREATE:

            /* Calculate the starting point. */

            GetClientRect(hwnd, &rc);

            OffsetRect(&rcCurrent, rc.right / 2, rc.bottom / 2);

            /* Initialize the private DC. */

            hdc = GetDC(hwnd);

            SetViewportOrgEx(hdc, rcCurrent.left,

                rcCurrent.top, NULL);

            SetROP2(hdc, R2_NOT);

            /* Start the timer. */

            SetTimer(hwnd, idTimer = 1, 10, NULL);

            return 0L;

        case WM_DESTROY:

            KillTimer(hwnd, 1);

            PostQuitMessage(0);

            return 0L;

        case WM_SIZE:

            switch (wParam) {

                case SIZE_MINIMIZED:

                    /* Stop the timer if the window is minimized. */

                    KillTimer(hwnd, 1);

                    idTimer = -1;

                    break;

                case SIZE_RESTORED:

                    /*

                     * Move the star back into the client area

                     * if necessary.

                     */

                    if (rcCurrent.right > (int) LOWORD(lParam))

                        rcCurrent.left =

                            (rcCurrent.right =

                                (int) LOWORD(lParam)) - 20;

                    if (rcCurrent.bottom > (int) HIWORD(lParam))

                        rcCurrent.top =

                            (rcCurrent.bottom =

                                (int) HIWORD(lParam)) - 20;

                    /* Fall through to the next case. */

                case SIZE_MAXIMIZED:

                    /* Start the timer if it had been stopped. */

                    if (idTimer == -1)

                        SetTimer(hwnd, idTimer = 1, 10, NULL);

                    break;

            }

            return 0L;

        case WM_TIMER:

            /* Hide the star if it is visible. */

            if (fVisible)

                Polyline(hdc, aptStar, 6);

            /* Bounce the star off a side if necessary. */

            GetClientRect(hwnd, &rc);

            if (rcCurrent.left + X < rc.left ||

                rcCurrent.right + X > rc.right)

                X = -X;

            if (rcCurrent.top + Y < rc.top ||

                rcCurrent.bottom + Y > rc.bottom)

                Y = -Y;

            /* Show the star in its new position. */

            OffsetRect(&rcCurrent, X, Y);

            SetViewportOrgEx(hdc, rcCurrent.left,

                rcCurrent.top, NULL);

            fVisible = Polyline(hdc, aptStar, 6);

            return 0L;

        case WM_ERASEBKGND:

            /* Erase the star. */

            fVisible = FALSE;

            return DefWindowProc(hwnd, message, wParam, lParam);

        case WM_PAINT:

            /*

             * Show the star if it is not visible. Use BeginPaint

             * to clear the update region.

             */

            BeginPaint(hwnd, &ps);

            if (!fVisible)

                fVisible = Polyline(hdc, aptStar, 6);

            EndPaint(hwnd, &ps);

            return 0L;

    }

    return DefWindowProc(hwnd, message, wParam, lParam);

}

This application uses a private DC to minimize the time required to prepare the DC for drawing. The window procedure retrieves and initializes the private DC when processing the WM_CREATE message, setting the binary raster operation mode to allow the star to be erased and drawn using the same call to the Polyline function. The window procedure also sets the viewport origin to allow the star to be drawn using the same set of points regardless of the star's position in the client area.

The application uses the WM_PAINT message to draw the star whenever the window must be updated. The window procedure draws the star only if it is not visible; that is, only if it has been erased by the WM_ERASEBKGND message. The window procedure intercepts the WM_ERASEBKGND message to set the fVisible variable, but passes the message to DefWindowProc so that Windows can draw the window background.

The application uses the WM_SIZE message to stop the timer when the window is minimized and to restart the timer when the minimized window is restored. The window procedure also uses the message to update the current position of the star if the size of the window has been reduced so that the star is no longer in the client area. The application keeps track of the star's current position by using the structure specified by rcCurrent, which defines the bounding rectangle for the star. Keeping all corners of the rectangle in the client area keeps the star in the area. The window procedure initially centers the star in the client area when processing the WM_CREATE message.


 Painting and Drawing Reference

The following functions and messages are associated with painting and drawing.


 Painting and Drawing Functions

Following are the functions used with painting and drawing.

BeginPaint
DrawAnimatedRects
DrawCaption
DrawEdge
DrawFocusRect
DrawFrameControl
DrawState
DrawStateProc
DrawTextEx
EndPaint
ExcludeUpdateRgn
GdiFlush
GdiGetBatchLimit
GdiSetBatchLimit
GetBkColor
GetBkMode
GetBoundsRect
GetROP2
GetUpdateRect
GetUpdateRgn
GetWindowDC
GrayString
InvalidateRect
InvalidateRgn
LockWindowUpdate
OutputProc
PaintDesktop
RedrawWindow
ResetDisplay
SetBkColor
SetBkMode
SetBoundsRect
SetRectRgn
SetROP2
UpdateWindow
ValidateRect
ValidateRgn
WindowFromDC


 Painting and Drawing Messages

Following are the messages used with painting and drawing.

WM_DISPLAYCHANGE
WM_ERASEBKGND
WM_ICONERASEBKGND
WM_NCPAINT
WM_PAINT
WM_PAINTICON
WM_PRINT
WM_PRINTCLIENT
WM_SETREDRAW


 Rectangles

Applications written for Microsoft® Windows® use rectangles to specify rectangular areas on the screen or in a window.


 About Rectangles

In Windows applications, rectangles are used for the cursor clipping region, the invalid portion of the client area, an area for displaying formatted text, or the scroll area. Your applications can also use rectangles to fill, frame, or invert a portion of the client area with a given brush, and to retrieve the coordinates of a window or a window's client area.


 Rectangle Coordinates

An application must use a RECT structure to define a rectangle. The structure specifies the coordinates of two points: the upper left and lower right corners of the rectangle. The sides of the rectangle extend from these two points and are parallel to the x- and y-axes.

The coordinate values for a rectangle are expressed as signed integers. The coordinate value of a rectangle's right side must be greater than that of its left side. Likewise, the coordinate value of the bottom must be greater than that of the top.

Because applications can use rectangles for many different purposes, the Windows rectangle functions do not use an explicit unit of measure. Instead, all rectangle coordinates and dimensions are given in signed, logical values. The mapping mode and the function in which the rectangle is used determine the units of measure. For more information about coordinates and mapping modes, see Coordinate Spaces and Transformations.


 Rectangle Operations

The Microsoft® Win32® application programming interface (API) provides several functions for working with rectangles.

The SetRect function creates a rectangle, the CopyRect function makes a copy of a given rectangle, and the SetRectEmpty function creates an empty rectangle. An empty rectangle is any rectangle that has zero width, zero height, or both. The IsRectEmpty function determines whether a given rectangle is empty. The EqualRect function determines whether two rectangles are identical — that is, whether they have the same coordinates.

The InflateRect function increases or decreases the width or height of a rectangle, or both. It can add or remove width from both ends of the rectangle; it can add or remove height from both the top and bottom of the rectangle.

The OffsetRect function moves a rectangle by a given amount. It moves the rectangle by adding the given x-amount, y-amount, or x- and y-amounts to the corner coordinates.

The PtInRect function determines whether a given point lies within a given rectangle. The point is in the rectangle if it lies on the left or top side or is completely within the rectangle. The point is not in the rectangle if it lies on the right or bottom side.

The IntersectRect function creates a new rectangle that is the intersection of two existing rectangles, as shown in the following figure.

The UnionRect function creates a new rectangle that is the union of two existing rectangles, as shown in the following figure.

For information about functions that draw ellipses and polygons, see Filled Shapes.


 Using Rectangles

The example in this section illustrates how to use the rectangle functions. It consists of the main window procedure from an application that enables the user to move and size a bitmap.

When the application starts, it draws a 32-pixel by 32-pixel bitmap in the upper left corner of the screen. The user can move the bitmap by dragging it. To size the bitmap, the user creates a target rectangle by dragging the mouse, then drags the bitmap and "drops" it on the target rectangle. The application responds by copying the bitmap into the target rectangle.

The window procedure that allows the user to move and size the bitmap is given in the following example.

LRESULT CALLBACK MainWndProc(hwnd, uMsg, wParam, lParam)

HWND hwnd;      /* handle of window         */

UINT uMsg;      /* message                  */

WPARAM wParam;  /* first message parameter  */

LPARAM lParam;  /* second message parameter */

{

    HDC hdc;                 /* device context (DC) for window   */

    RECT rcTmp;              /* temporary rectangle              */

    PAINTSTRUCT ps;          /* paint data for Begin/EndPaint    */

    POINT ptClientUL;        /* client area upper left corner    */

    POINT ptClientLR;        /* client area lower right corner   */

    static HDC hdcCompat;    /* DC for copying bitmap            */

    static POINT pt;         /* x and y coordinates of cursor    */

    static RECT rcBmp;       /* rectangle that encloses bitmap   */

    static RECT rcTarget;    /* rectangle to receive bitmap      */

    static RECT rcClient;    /* client-area rectangle            */

    static BOOL fDragRect;   /* TRUE if bitmap rect. is dragged  */

    static HBITMAP hbmp;     /* handle of bitmap to display      */

    static HBRUSH hbrBkgnd;  /* handle of background-color brush */

    static COLORREF crBkgnd; /* color of client-area background  */

    static HPEN hpenDot;     /* handle of dotted pen             */

    switch (uMsg) {

        case WM_CREATE:

            /* Load the bitmap resource. */

            hbmp = LoadBitmap(hinst, MAKEINTRESOURCE(1));

            /*

             * Create a device context (DC) to hold the bitmap.

             * The bitmap is copied from this DC to the window's DC

             * whenever it must be drawn.

             */

            hdc = GetDC(hwnd);

            hdcCompat = CreateCompatibleDC(hdc);

            SelectObject(hdcCompat, hbmp);

            /*

             * Create a brush of the same color as the background

             * of the client area. The brush is used later to erase

             * the old bitmap before copying the bitmap into the

             * target rectangle.

             */

            crBkgnd = GetBkColor(hdc);

            hbrBkgnd = CreateSolidBrush(crBkgnd);

            ReleaseDC(hwnd, hdc);

            /*

             * Create a dotted pen. The pen is used to draw the

             * bitmap rectangle as the user drags it.

             */

            hpenDot = CreatePen(PS_DOT, 1, RGB(0, 0, 0));

            /*

             * Set the initial rectangle for the bitmap. Note that

             * this application supports only a 32- by 32-pixel

             * bitmap. The rectangle is slightly larger than the

             * bitmap.

             */

            SetRect(&rcBmp, 1, 1, 34, 34);

            return 0;

        case WM_PAINT:

            /*

             * Draw the bitmap rectangle and copy the bitmap into

             * it. The 32-pixel by 32-pixel bitmap is centered

             * in the rectangle by adding 1 to the left and top

             * coordinates of the bitmap rectangle, and subtracting

             * 2 from the right and bottom coordinates.

             */

            BeginPaint(hwnd, &ps);

            Rectangle(ps.hdc, rcBmp.left, rcBmp.top,

                rcBmp.right, rcBmp.bottom);

            StretchBlt(ps.hdc, rcBmp.left + 1, rcBmp.top + 1,

                (rcBmp.right - rcBmp.left) - 2,

                (rcBmp.bottom - rcBmp.top) - 2, hdcCompat,

                0, 0, 32, 32, SRCCOPY);

            EndPaint(hwnd, &ps);

            break;

        case WM_MOVE:

        case WM_SIZE:

            /*

             * Convert the client coordinates of the client-area

             * rectangle to screen coordinates and save them in a

             * rectangle. The rectangle is passed to the ClipCursor

             * function during WM_LBUTTONDOWN processing.

             */

            GetClientRect(hwnd, &rcClient);

            ptClientUL.x = rcClient.left;

            ptClientUL.y = rcClient.top;

            ptClientLR.x = rcClient.right;

            ptClientLR.y = rcClient.bottom;

            ClientToScreen(hwnd, &ptClientUL);

            ClientToScreen(hwnd, &ptClientLR);

            SetRect(&rcClient, ptClientUL.x, ptClientUL.y,

                ptClientLR.x, ptClientLR.y);

            return 0;

        case WM_LBUTTONDOWN:

            /*

             * Restrict the mouse cursor to the client area. This

             * ensures that the window receives a matching

             * WM_LBUTTONUP message.

             */

            ClipCursor(&rcClient);

            /* Save the coordinates of the mouse cursor. */

            pt.x = (LONG) LOWORD(lParam);

            pt.y = (LONG) HIWORD(lParam);

            /*

             * If the user has clicked the bitmap rectangle, redraw

             * it using the dotted pen. Set the fDragRect flag to

             * indicate that the user is about to drag the

             * rectangle.

             */

            if (PtInRect(&rcBmp, pt)) {

                hdc = GetDC(hwnd);

                SelectObject(hdc, hpenDot);

                Rectangle(hdc, rcBmp.left, rcBmp.top, rcBmp.right,

                    rcBmp.bottom);

                fDragRect = TRUE;

                ReleaseDC(hwnd, hdc);

            }

            return 0;

        case WM_MOUSEMOVE:

            /*

             * Draw a target rectangle or drag the bitmap

             * rectangle, depending on the status of the fDragRect

             * flag.

             */

            if ((wParam && MK_LBUTTON)

                    && !fDragRect) {  /* draw a target rectangle */

                /*

                 * Set the mix mode so that the pen color is the

                 * inverse of the background color. The previous

                 * rectangle can then be erased by drawing

                 * another rectangle on top of it.

                 */

                hdc = GetDC(hwnd);

                SetROP2(hdc, R2_NOTXORPEN);

                /*

                 * If a previous target rectangle exists, erase

                 * it by drawing another rectangle on top of it.

                 */

                if (!IsRectEmpty(&rcTarget))

                    Rectangle(hdc, rcTarget.left, rcTarget.top,

                        rcTarget.right, rcTarget.bottom);

                /*

                 * Save the coordinates of the target rectangle.

                 * Avoid invalid rectangles by ensuring that the

                 * value of the left coordinate is greater than

                 * that of the right coordinate, and that the

                 * value of the bottom coordinate is greater than

                 * that of the top.

                 */

                if ((pt.x < (LONG) LOWORD(lParam)) &&

                        (pt.y > (LONG) HIWORD(lParam)))

                    SetRect(&rcTarget, pt.x, HIWORD(lParam),

                        LOWORD(lParam), pt.y);

                else if ((pt.x > (LONG) LOWORD(lParam)) &&

                        (pt.y > (LONG) HIWORD(lParam)))

                    SetRect(&rcTarget, LOWORD(lParam),

                        HIWORD(lParam), pt.x, pt.y);

                else if ((pt.x > (LONG) LOWORD(lParam)) &&

                        (pt.y < (LONG) HIWORD(lParam)))

                    SetRect(&rcTarget, LOWORD(lParam), pt.y,

                        pt.x, HIWORD(lParam));

                else

                    SetRect(&rcTarget, pt.x, pt.y, LOWORD(lParam),

                        HIWORD(lParam));

                /* Draw the new target rectangle. */

                Rectangle(hdc, rcTarget.left, rcTarget.top,

                    rcTarget.right, rcTarget.bottom);

                ReleaseDC(hwnd, hdc);

            }

            else if ((wParam && MK_LBUTTON)

                    && fDragRect) { /* drag the bitmap rectangle */

                /*

                 * Set the mix mode so that the pen color is the

                 * inverse of the background color.

                 */

                hdc = GetDC(hwnd);

                SetROP2(hdc, R2_NOTXORPEN);

                /*

                 * Select the dotted pen into the DC and erase

                 * the previous bitmap rectangle by drawing

                 * another rectangle on top of it.

                 */

                SelectObject(hdc, hpenDot);

                Rectangle(hdc, rcBmp.left, rcBmp.top,

                    rcBmp.right, rcBmp.bottom);

                /*

                 * Set the new coordinates of the bitmap

                 * rectangle, then redraw it.

                 */

                OffsetRect(&rcBmp, LOWORD(lParam) - pt.x,

                    HIWORD(lParam) - pt.y);

                Rectangle(hdc, rcBmp.left, rcBmp.top,

                    rcBmp.right, rcBmp.bottom);

                ReleaseDC(hwnd, hdc);

                /* Save the coordinates of the mouse cursor. */

                pt.x = (LONG) LOWORD(lParam);

                pt.y = (LONG) HIWORD(lParam);

            }

            return 0;

        case WM_LBUTTONUP:

            /*

             * If the bitmap rectangle and target rectangle

             * intersect, copy the bitmap into the target

             * rectangle. Otherwise, copy the bitmap into the

             * rectangle bitmap at its new location.

             */

            if (IntersectRect(&rcTmp, &rcBmp, &rcTarget)) {

                /*

                 * Erase the bitmap rectangle by filling it with

                 * the background color.

                 */

                hdc = GetDC(hwnd);

                FillRect(hdc, &rcBmp, hbrBkgnd);

                /*

                 * Redraw the target rectangle because the part

                 * that intersected with the bitmap rectangle was

                 * erased by the call to FillRect.

                 */

                Rectangle(hdc, rcTarget.left, rcTarget.top,

                    rcTarget.right, rcTarget.bottom);

                /* Copy the bitmap into the target rectangle. */

                StretchBlt(hdc, rcTarget.left + 1, rcTarget.top + 1,

                    (rcTarget.right - rcTarget.left) - 2,

                    (rcTarget.bottom - rcTarget.top) - 2, hdcCompat,

                    0, 0, 32, 32, SRCCOPY);

                /*

                 * Copy the target rectangle to the bitmap

                 * rectangle, set the coordinates of the target

                 * rectangle to 0, then reset the fDragRect flag.

                 */

                CopyRect(&rcBmp, &rcTarget);

                SetRectEmpty(&rcTarget);

                ReleaseDC(hwnd, hdc);

                fDragRect = FALSE;

            }

            else if (fDragRect) {

                /*

                 * Draw the bitmap rectangle, copy the bitmap into

                 * it, and reset the fDragRect flag.

                 */

                hdc = GetDC(hwnd);

                Rectangle(hdc, rcBmp.left, rcBmp.top,

                    rcBmp.right, rcBmp.bottom);

                StretchBlt(hdc, rcBmp.left + 1, rcBmp.top + 1,

                    (rcBmp.right - rcBmp.left) - 2,

                    (rcBmp.bottom - rcBmp.top) - 2, hdcCompat,

                    0, 0, 32, 32, SRCCOPY);

                ReleaseDC(hwnd, hdc);

                fDragRect = FALSE;

            }

            /* Release the mouse cursor. */

            ClipCursor((LPRECT) NULL);

            return 0;

        case WM_DESTROY:

            /*

             * Destroy the background brush, compatible bitmap,

             * and the bitmap.

             */

            DeleteObject(hbrBkgnd);

            DeleteDC(hdcCompat);

            DeleteObject(hbmp);

            PostQuitMessage(0);

            break;

        default:

            return DefWindowProc(hwnd, uMsg, wParam, lParam);

    }

    return (LRESULT) NULL;

}


 Rectangle Functions

Following are the functions used with rectangles.

CopyRect
EqualRect
InflateRect
IntersectRect
IsRectEmpty
OffsetRect
PtInRect
SetRect
SetRectEmpty
SubtractRect
UnionRect


 Timers

A timer is an internal routine that repeatedly measures a specified interval, in milliseconds. Each time the interval (or time-out value) 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.


 About Timers

An application written for Microsoft® Windows® creates a timer by using the SetTimer function. If a window handle is given in this function, the application creates the timer for that window. Then, whenever the time-out value elapses, the system posts a WM_TIMER message to the window. If no window handle is given in SetTimer, the application that created the timer must monitor its message queue for WM_TIMER messages and dispatch them to the appropriate window.

A new timer starts timing 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.


 Using Timers

•	Creating a timer

•	Destroying a timer

•	Using timer functions to create a mousetrap

•	Process the WM_TIMER message.

•	Use a TimerProc callback function.


 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 of main window */

    IDT_TIMER1,            /* timer identifier      */

    10000,                 /* 10-second interval    */

    (TIMERPROC) NULL);     /* no timer callback     */

SetTimer(hwnd,             /* handle of 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 of main window */

    IDT_TIMER3,               /* timer identifier      */

    5000,                     /* 5-second interval     */

    (TIMERPROC) MyTimerProc); /* timer callback        */

The calling convention for MyTimerProc must be based on the Microsoft® Win32® callback function, TimerProc.

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.

HWND hwndTimer;   /* handle of window for timer messages */

MSG msg;          /* message structure */

    while (GetMessage(&msg, /* message structure                */

            NULL,           /* handle of window receiving msg.  */

            NULL,           /* lowest message to examine        */

            NULL))          /* highest message to examine       */

        {

        /* 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 of 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 of 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 of main window  */

UINT message,       /* type of message        */

UINT wParam,        /* additional information */

LONG lParam)        /* additional information */

{

    HDC hdc;        /* handle of 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 of 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 of 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 of main window  */

UINT message,       /* type of message        */

UINT wParam,        /* additional information */

LONG lParam)        /* additional information */

{

    HDC hdc;        /* handle of 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 of 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 Functions

The following functions are used with timers.

KillTimer
SetTimer
TimerProc


 Window Classes

Every window is a member of a window class. A window class is a set of attributes that Microsoft® Windows® uses as a template to create a window in an application. This overview describes the types of window classes, how Windows locates them, and the elements that define the default behavior of windows that belong to them.


 About Window Classes

Each window class has an associated window procedure shared by all windows of the same class. The window procedure processes messages for all windows of that class and therefore controls their behavior and appearance. For more information about window procedures, see Window Procedures.

An application 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 an application specifies a class name in the CreateWindow or CreateWindowEx function, the operating 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 global, application global, and application local. These types differ in scope and in when and how they are registered and destroyed.


 System Global Classes

When Windows starts, it registers a set of system global classes for controls, including buttons, combo boxes, list boxes, scroll bars, edit controls, and static controls.

Any application can use a system global class at any time. Because Windows registers system global classes on behalf of all applications, an application cannot destroy any of these classes.


 Application Global Classes

An application global class is a window class registered by a dynamic-link library (DLL) and available to all applications in the system. For example, you can register a window class that defines a custom control as an application global class so that all applications can create instances of the custom control.

In Windows, all window classes are process specific. An application can create a global class by creating the window class in a DLL and listing the name of the DLL in the registry under the appropriate keys.

Whenever a process starts, the system loads the specified DLL in the context of the newly started process before calling the main function in that process. The DLL must register the class during its initialization procedure and must specify the CS_GLOBALCLASS style. (For more information about class styles, see Class Styles.) After a class has been registered, any application can use it to create any number of windows belonging to that class.

Windows does not automatically destroy a class when the DLL that registered it is unloaded. For this reason, the Windows exit procedure of the DLL should call the UnregisterClass function to remove the class.


 Application Local Classes

An application local class is any window class that an application registers for its exclusive use. Although an application can register any number of local classes, most applications register only one. This window class supports the window procedure of the application's main window.

Registering a local class is similar to registering an application global class, except that the CS_GLOBALCLASS style is not specified in the style member of the WNDCLASSEX structure.

Windows destroys a local class when the application 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 Windows Locates a Class

Windows maintains a list of WNDCLASSEX 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, Windows uses the following procedure to locate the class:

1.	Windows searches the list of application local classes for a class with the specified name. Note that several application instances can use the same name to register local classes. Windows uses instance handles to differentiate among local classes that have the same name.

2.	If the name is not in the application local class list, Windows searches the list of application global classes.

3.	If the name is not in the application global class list, Windows searches the list of system global classes.

All windows created by the application use this procedure, including windows created by Windows on the application's behalf, such as dialog boxes. It is possible to override system global classes without affecting other applications. That is, an application can register an application local class having the same name as a system global class. This replaces the system global class in the context of the application but does not prevent other applications from using the system global class.


 Class Ownership

The owner of a class is the application or DLL that registered the class. Windows determines class ownership from the hInstance member of the WNDCLASSEX structure passed to the RegisterClassEx function when the class is registered. For Windows DLLs, the hInstance member must be the instance handle of the DLL. The class is destroyed when the owner closes or is unloaded. For this reason, the application must destroy all windows using the class before it closes or the DLL is unloaded.


 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, Windows requires only that an application supply a class name, the window-procedure address, and an instance handle. Use the other elements to define default attributes for windows of the class, such as the shape of the cursor and the content of the menu for the window. You must initialize any unused members of the WNDCLASSEX structure to zero or NULL. The window class elements are as follows.

Element	Purpose
Class name	Distinguishes the class from other registered classes.
Window-procedure address	Points 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 Windows displays for a window of the class.
Class icon	Defines the large icon.
Small class icon	Defines the small icon (Windows version 4.0 and higher).
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 Windows should reserve for the class. All windows in the class share the extra memory and can use it for any application-defined purpose. Windows initializes this memory to zero.
Extra window memory	Specifies the amount of extra memory, in bytes, that Windows should reserve for each window belonging to the class. The extra memory can be used for any application-defined purpose. Windows 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 in Windows, 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. Windows 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. An application assigns a window procedure to a class by copying its address to the lpfnWndProc member of the WNDCLASSEX structure. For more information about window procedures, see Window Procedures.


 Instance Handle

Every window class requires an instance handle to identify the application or DLL that registered the class. As a multitasking system, Windows lets several applications or DLLs run at the same time, so it requires instance handles to keep track of all of them. Windows assigns a handle to each copy of a running application or DLL.

Multiple instances of the same application or DLL all use the same code segment, but each has its own data segment. Windows uses an instance handle to identify the data segment that corresponds to a particular instance of an application or DLL.

Windows passes an instance handle to an application or DLL when the application starts. The application or DLL assigns this instance handle to the class by copying it to the hInstance member of the WNDCLASSEX structure.


 Class Cursor

The class cursor defines the shape of the cursor when it is in the client area of a window in the class. Windows 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.

Windows does not require a class cursor. If an application sets the hCursor member of the WNDCLASSEX structure to NULL, a class cursor is not defined. Windows 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. A class can have one or two icons, depending on the operating system version. You can use the GetVersionEx function to retrieve the version number.

Class Icons in Version 4.0 or Later

With version 4.0 or later, 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 about creating icons and loading icon resources, 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 Icons in Versions Earlier Than 4.0

In operating system versions earlier than 4.0, the class icon defines the icon used when a window of the given class is minimized. To assign an icon to a window class, specify an icon handle in the hIcon member of the WNDCLASS structure. If an application sets the hIcon member of WNDCLASS to NULL, a class icon is not defined. In this case, Windows sends the WM_ICONERASEBKGND message to a window of the class whenever it must paint the icon background. If the window does not process the WM_ICONERASEBKGND message, Windows draws an image of the contents of the window's client area when the window is minimized. For more information about drawing minimized windows, see Painting and Drawing.


 Class Background Brush

A class background brush prepares the client area of a window for subsequent drawing by the application. Windows uses the brush to fill the client area with a solid color or pattern, thereby removing all previous images from that location whether they belonged to the window or not. Windows notifies a window that its background should be painted by sending the WM_ERASEBKGND message to the window. For more information about brushes, see Brushes.

To assign a background brush to a class, create a brush by using the appropriate GDI functions and assign the returned brush handle to the hbrBackground member of the WNDCLASSEX structure.

Instead of creating a brush, an application can set the hbrBackground member to one of the standard system color values. For a list of the standard system color values, see SetSysColors.

To use a standard system color, the application must increase the background-color value by one. For example, COLOR_BACKGROUND + 1 is the system background color. Alternatively, you can use the GetSysColorBrush function to retrieve the handle of a brush that corresponds to a standard system color, and then specify the handle in the hbrBackground member of the WNDCLASSEX structure.

Windows 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. Windows automatically loads the menu when it is needed. Note that 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.

Windows does not require a class menu. If an application sets the lpszMenuName member of the WNDCLASSEX structure to NULL, Windows assumes the 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.

Windows does not allow menu bars with child windows. If a menu is given for a class and a child window of that class is created, the menu is ignored. For more information about menus, see Menus (Windows NT).


 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) to enhance performance during drawing operations. 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) to enhance performance during operations that involve moving or sizing the window. 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. For more information about device contexts, see Class and Private Device Contexts and Device Contexts.
CS_DBLCLKS	Instructs Windows to send a double-click message to the window procedure when the user double-clicks the mouse while the cursor is within a window belonging to the class. For more information about double-clicks, see Mouse Input.
CS_GLOBALCLASS	Specifies that the window class is an application global class. For more information, see Application Global Classes.
CS_HREDRAW	Specifies that the entire window is to be redrawn if a movement or size adjustment changes the width of the client area.
CS_NOCLOSE	Disables the Close command on the System menu.
CS_OWNDC	Allocates a unique device context for each window in the class. For more information about device contexts, see Class and Private Device Contexts and Device Contexts.
CS_PARENTDC	Sets the clipping rectangle of the child window to that of the parent window so that the child can draw on the parent. A window with the CS_PARENTDC style bit receives a regular device context from the system's cache of device contexts. It does not give the child the parent's device context or device context settings. Specifying CS_PARENTDC enhances an application's performance. For more information about device contexts, see Class and Private Device Contexts and Device Contexts.
CS_SAVEBITS	Saves, as a bitmap, the portion of the screen image obscured by a window. Windows uses the saved bitmap to re-create the screen image when the window is removed. Windows displays the bitmap at its original location and does not send WM_PAINT messages to windows obscured by the window if other screen actions have not invalidated the stored image. Use this style for small windows that are displayed briefly and then removed before other screen activity takes place (for example, menus or dialog boxes). This style increases the time required to display the window, because the operating system must first allocate memory to store the bitmap.
CS_VREDRAW	Specifies that the entire window is to be redrawn if a movement or size adjustment changes the height of the client area.


 Extra Class Memory

Windows maintains a WNDCLASSEX structure internally for each window class in the system. When an application registers a window class, it can direct Windows 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. With operating system version 4.0 or later, 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

Windows 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, Windows 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 operating system version 4.0 or later, the RegisterClassEx function fails if the amount of extra window memory requested is greater than 40 bytes. If an application requires more than 40 bytes, it should allocate its own memory and store a pointer to the memory in the extra window memory.

The SetWindowWord and SetWindowLong functions copy a value to the extra memory. The GetWindowWord and GetWindowLong functions retrieve a value from the extra memory. The cbWndExtra member of the WNDCLASSEX structure specifies the amount of extra window memory to allocate. An application that doesn't use the memory must initialize cbWndExtra to zero.


 Class and Private Device Contexts

A device context is a special set of values that applications use for drawing in the client area of their windows. Windows requires a device context for each window on the display but allows some flexibility in how the operating system stores and treats that device context.

If no device-context style is explicitly given, Windows assumes each window uses a device context retrieved from a pool of contexts maintained by Windows. 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 Windows 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. Although the CS_OWNDC style is convenient, use it carefully, because each device context uses a significant portion of system resources.

By specifying the CS_CLASSDC style, an application can create a class device context. A class device context is a rarely used feature that allows multiple windows created from the same window class within a process to use exactly the same device context for drawing.

An application can specify the CS_PARENTDC style to create child windows that inherit the device context of their parent window. This style allows a child window to draw in the client area of its parent.

An application can specify the CS_PARENTDC style to set the clipping rectangle of the child window to that of the parent window so the child can draw in the parent. A window with the CS_PARENTDC style receives a regular device context from the system's cache of device contexts. It does not give a child window's device context or device context settings to the parent window. Specifying CS_PARENTDC enhances an application's performance because Windows doesn't need to keep recalculating the visible region for each child window.

For more information about device contexts, see Device Contexts. For more information about painting, see Painting and Drawing.


 Using Window Classes

In Windows, each application must register its own window classes. Your application can register an application local class at any time by using the RegisterClassEx function. You must define the window procedure in the application, 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 your application's 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, hPrevInstance, lpCmdLine, nCmdShow)

HINSTANCE hinstance;

HINSTANCE hPrevInstance;

LPSTR lpCmdLine;

int nCmdShow;

{

    MSG msg;

    if (!InitApplication(hinstance))

        return FALSE;

    if (!InitInstance(hinstance, nCmdShow))

        return FALSE;

    while (GetMessage(&msg, (HWND) NULL, 0, 0)) {

        TranslateMessage(&msg);

        DispatchMessage(&msg);

    }

    return msg.wParam;

        UNREFERENCED_PARAMETER(lpCmdLine);

}

BOOL InitApplication(hinstance)

HINSTANCE 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 proc. */

    wcx.cbClsExtra = 0;                /* no extra class memory  */

    wcx.cbWndExtra = 0;                /* no extra window memory */

    wcx.hInstance = hinstance;         /* handle of instance     */

    wcx.hIcon = LoadIcon(NULL,

        IDI_APPLICATION);              /* predefined app. icon   */

    wcx.hCursor = LoadCursor(NULL,

        IDC_ARROW);                    /* predefined arrow       */

    wcx.hbrBackground = GetStockObject(

        WHITE_BRUSH);                  /* white background brush */

    wcx.lpszMenuName =  "MainMenu";    /* name of menu resource  */

    wcx.lpszClassName = "MainWClass";  /* name of window class   */

    wcx.hIconSm = LoadImage(hinstance, /* small class icon       */

        MAKEINTRESOURCE(5),

        GetSystemMetrics(SM_CXSMICON),

        GetSystemMetrics(SM_CYSMICON),

        LR_DEFAULTCOLOR);

    /* Register the window class. */

    return RegisterClassEx(&wcx);

}

BOOL InitInstance(hinstance, nCmdShow)

HINSTANCE hinstance;

int nCmdShow;

{

    HWND hwnd;

    /* Save the application-instance handle. */

    hinst = hinstance;

    /* Create the main window. */

    hwnd = CreateWindow(

        "MainWClass",        /* name of window class        */

        "Sample",            /* title-bar string            */

        WS_OVERLAPPEDWINDOW, /* top-level window            */

        CW_USEDEFAULT,       /* default horizontal position */

        CW_USEDEFAULT,       /* default vertical position   */

        CW_USEDEFAULT,       /* default width               */

        CW_USEDEFAULT,       /* default height              */

        (HWND) NULL,         /* no owner window             */

        (HMENU) NULL,        /* use class menu              */

        hinstance,           /* handle of app. 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, with the following exceptions:

•	The style parameter of the WNDCLASSEX structure must specify the CS_GLOBALCLASS style.

•	The class can be registered by an application or a DLL. If registered by an application, the class is global only within the application. If the class is registered by a DLL and listed in the registry, the system loads the DLL for every application.

•	The application or DLL need not check for a previous instance of the application or DLL before registering the class.


 Window Class Functions

Following are the functions used with window classes.

GetClassInfo
GetClassInfoEx
GetClassLong
GetClassName
GetClassWord
GetWindowLong
GetWindowWord
RegisterClass
RegisterClassEx
SetClassLong
SetClassWord
SetWindowLong
SetWindowWord
UnregisterClass


 Window Procedures

In Microsoft® Windows®, every window has an associated window procedure — a function that processes all messages sent or posted to all windows of the class. All aspects of a window's appearance and behavior depend on the window procedure's response to these messages.


 About Window Procedures

Each window is a member of a particular window class. The window class determines the default window procedure that an individual window uses to process its messages. All windows belonging to the same class use the same default window procedure. For example, the system defines a window procedure for the combo box class (COMBOBOX); all combo boxes then use that window procedure.

An application typically registers at least one new window class and an associated window procedure. After registering a class, the application can create many windows of that class, all of which use the same default window procedure. Because this means several sources could simultaneously call the same piece of code, the developer must be careful when modifying shared resources from a window procedure. For more information about window classes, 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 about dialog boxes, 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. The operating system defines a WPARAM value as a 32-bit unsigned integer and an LPARAM value as a 32-bit signed integer.

The window procedure parameters are described in the following table.

Parameter	Description
hwnd	Handle of the window receiving the message.
uMsg	Message identifier. The identifier corresponds to one of the predefined constants (for example, WM_CREATE) defined in the system header files or to an application-defined message identifier.
wParam, lParam	Message parameters. Their interpretation depends on the value of the uMsg parameter.
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 return value of a window procedure is declared as an LRESULT data type, which is defined as a 32-bit signed value. 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 operating 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 Windows 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. Although it is not recommended, an application can subclass any window, including those 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. For an explanation of the risks involved, see the following section.

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.

Windows 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 of the window to subclass, and the address of the subclass procedure to SetWindowLong. The subclass procedure can reside in either the application's module or a dynamic-link library (DLL). An application must list the name of the subclass procedure in the EXPORTS statement of the application's or DLL's module-definition (.DEF) file.

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 of the window.

An application can subclass any window in the system; however, when subclassing a window it does not own, the application must ensure that the subclass procedure does not destroy the original behavior of the window. Because the application does not control the window, it must not depend on information about the window that the owner might change in the future.

An application should not use the extra window bytes or the class bytes for a window without knowing exactly what the bytes mean and how the original window procedure uses them. Even so, the application should not use them unless it owns the window. If the application uses the extra window bytes of a window that another application owns and the owner changes some aspect of the extra bytes, the subclass procedure may fail. For this reason, an application should not subclass a window that belongs to a system global control class. Windows owns the system global classes, and aspects of the controls might change from one version of Windows 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 Windows is released.

Because instance subclassing occurs after a window is created, the application subclassing the window 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 about window properties, 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.

An application must not globally subclass a system global class. An unrecoverable system error may occur if more than one application globally subclasses a control class. If the application could benefit from globally subclassing a control class, use the technique called superclassing.


 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 APIENTRY MainWndProc(hwnd, uMsg, wParam, lParam)

HWND hwnd;      // handle of 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. For more information about dialog box procedures, see Dialog Boxes.


 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, hinstPrev, lpCmdLine, nCmdShow)

HINSTANCE hinstance;  // handle of current instance

HINSTANCE hinstPrev;  // handle of 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 of 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(hwndDlg, uMsg, wParam, lParam)

HWND hwndDlg;

UINT uMsg;

WPARAM wParam;

LPARAM lParam;

{

    HWND hwndEdit;

    switch(uMsg) {

        case WM_INITDIALOG:

            // Retrieve the handle of 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, uMsg, wParam, lParam)

HWND hwnd;

UINT uMsg;

WPARAM wParam;

LPARAM lParam;

{

    if (uMsg == WM_GETDLGCODE)

        return DLGC_WANTALLKEYS;

    return CallWindowProc(wpOrigEditProc, hwnd, uMsg,

        wParam, lParam);

}


 Window Procedure Functions

Following are the functions used with window procedures.

CallWindowProc
DefWindowProc
WindowProc


 Window Properties

A window property is any data assigned to a window by the SetProp function. 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

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. Window properties, however, are accessed by their string identifiers, not by offsets.

For more information about subclassing, see Window Procedures. For more information about MDI windows, see Multiple Document Interface.

The Microsoft® Win32® application programming interface (API) provides several functions that enable applications to use window properties. The SetProp function assigns a window property and its string identifier to a window. The GetProp function retrieves the window property identified by a given string. The RemoveProp function destroys the association between a window and a window property but does not destroy the data itself. The EnumProps and EnumPropsEx functions enumerate all of a window's properties by using an application-defined callback function. EnumPropsEx includes an extra parameter for application-defined data used by the callback function.


 Using Window Properties

•	Adding a window property

•	Retrieving a window property

•	Listing window properties for a given window

•	Deleting a window property


 Adding a Window Property

The following example loads an icon and then a cursor and allocates memory for a buffer. The example then uses the SetProp function to assign the resulting icon, cursor, and memory handles as window properties for the window identified by the application-defined hwndSubclass variable. The properties are identified by the strings PROP_ICON, PROP_CURSOR, and PROP_BUFFER.

#define BUFFER 4096

HINSTANCE hinst;       /* handle of current instance    */

HWND hwndSubclass;     /* handle of a subclassed window */

HANDLE hIcon, hCursor;

HGLOBAL hMem;

char *lpMem;

TCHAR tchPath[] = "c:\\winnt\\samples\\winprop.c";

/* Load resources. */

hIcon = LoadIcon(hinst, MAKEINTRESOURCE(400));

hCursor = LoadCursor(hinst, MAKEINTRESOURCE(220));

/* Allocate and fill a memory buffer. */

hMem = GlobalAlloc(GPTR, BUFFER);

lpMem = GlobalLock(hMem);

lstrcpy(lpMem, tchPath);

GlobalUnlock(hMem);

/* Set the window properties for hwndSubclass. */

SetProp(hwndSubclass, "PROP_ICON", hIcon);

SetProp(hwndSubclass, "PROP_CURSOR", hCursor);

SetProp(hwndSubclass, "PROP_BUFFER", hMem);


 Retrieving a Window Property

A window can create handles to its window property data and use the data for any purpose. The following example uses GetProp to obtain handles to the window properties identified by PROP_ICON, PROP_CURSOR, and PROP_BUFFER. The example then displays the contents of the newly obtained memory buffer, cursor, and icon in the window's client area.

#define PATHLENGTH 256

HWND hwndSubclass;     /* handle of a subclassed window */

HANDLE hIconProp, hCursProp;

HGLOBAL hMemProp;

char *lpFilename;

TCHAR tchBuffer[PATHLENGTH];

int nSize;

HDC hdc;

/* Get the window properties, then use the data. */

hIconProp = (HICON) GetProp(hwndSubclass, "PROP_ICON");

TextOut(hdc, 10, 40, "PROP_ICON", 9);

DrawIcon(hdc, 90, 40, hIconProp);

hCursProp = (HCURSOR) GetProp(hwndSubclass, "PROP_CURSOR");

TextOut(hdc, 10, 85, "PROP_CURSOR", 9);

DrawIcon(hdc, 110, 85, hCursProp);

hMemProp = (HGLOBAL) GetProp(hwndSubclass, "PROP_BUFFER");

lpFilename = GlobalLock(hMemProp);

nSize = sprintf(tchBuffer,

    "Path to file:  %s", lpFilename);

TextOut(hdc, 10, 10, tchBuffer, nSize);


 Listing Window Properties for a Given Window

In the following example, the EnumPropsEx function lists the string identifiers of the window properties for the window identified by the application-defined hwndSubclass variable. This function relies on the application-defined callback function WinPropProc to display the strings in the window's client area.

EnumPropsEx(hwndSubclass, WinPropProc, NULL);

/*

 * WinPropProc is an application-defined callback function

 * that lists a window property.

 */

BOOL CALLBACK WinPropProc(

    HWND hwndSubclass,  /* handle of window with property */

    LPCSTR lpszString,  /* property string or atom        */

    HANDLE hData)       /* data handle                    */

{

    static int nProp = 1;    /* property counter          */

    TCHAR tchBuffer[BUFFER]; /* expanded-string buffer    */

    int nSize;               /* size of string in buffer  */

    HDC hdc;                 /* device-context handle     */

    hdc = GetDC(hwndSubclass);

    /* Display window property string in client area. */

    nSize = sprintf(tchBuffer, "WinProp %d:  %s", nProp++,

        lpszString);

    TextOut(hdc, 10, nProp * 20, tchBuffer, nSize);

    ReleaseDC(hwndSubclass, hdc);

    return TRUE;

}


 Deleting a Window Property

When a window is destroyed, it must destroy any window properties it set. The following example uses the EnumPropsEx function and the application-defined callback function DelPropProc to destroy the properties associated with the window identified by the application-defined hwndSubclass variable. The callback function, which uses the RemoveProp function, is also shown.

case WM_DESTROY:

    EnumPropsEx(hwndSubclass, DelPropProc, NULL);

    PostQuitMessage(0);

    break;

    .

    .

    .

/*

 * DelPropProc is an application-defined callback function

 * that deletes a window property.

 */

BOOL CALLBACK DelPropProc(

    HWND hwndSubclass,  /* handle of window with property */

    LPCSTR lpszString,  /* property string or atom        */

    HANDLE hData)       /* data handle                    */

{

    RemoveProp(hwndSubclass, lpszString);

    return TRUE;

}


 Window Property Functions

Following are the functions used with window properties.

EnumProps
EnumPropsEx
GetProp
PropEnumProc
PropEnumProcEx
RemoveProp
SetProp


 Animation Controls

An animation control is a window that silently displays an Audio Video Interleaved (AVI) clip. An AVI clip is a series of bitmap frames like a movie. Although AVI clips can have sound, you cannot use such clips with animation controls. You can use only silent AVI clips.


 About Animation Controls

Because the thread continues executing while the AVI clip is displayed, one common use for an animation control is to indicate system activity during a lengthy operation. For example, the Find dialog box of the Microsoft® Windows® Explorer displays a moving magnifying glass as the system searches for a file.

An animation control can display an AVI clip originating from either an uncompressed .AVI file or from an .AVI file that was compressed using run-length encoding (RLE). You can add the AVI clip to your application as an AVI resource, or the clip can accompany your application as a separate .AVI file.

The capabilities of an animation control are severely limited and are subject to change. If you need a control to provide multimedia playback and recording capabilities for your application, you can use the MCIWnd control. For more information about the MCIWnd control, see the multimedia documentation.


 Animation Control Creation

An animation control belongs to the ANIMATE_CLASS window class. You create an animation control by using the CreateWindow function or the Animate_Create macro. The macro positions the animation control in the upper-left corner of the parent window and, if the ACS_CENTER style is not specified, sets the width and height of the control based on the dimensions of a frame in the AVI clip. If ACS_CENTER is specified, Animate_Create sets the width and height of the control to zero. You can use the SetWindowPos function to set the position and size of the control.

If you create an animation control within a dialog box or from a dialog box resource, the control is automatically destroyed when the user closes the dialog box. If you create an animation control within a window, you must explicitly destroy the control.


 Animation Control Messages

An application sends messages to an animation control to open, play, stop, and close the corresponding AVI clip. Each message has one or more macros that you can use instead of sending the message explicitly.

After creating an animation control, an application sends the ACM_OPEN message to open an AVI clip and load it into memory. The message specifies either the path of an .AVI file or the name of an AVI resource. The system loads the AVI resource from the module that created the animation control.

If the animation control has the ACS_AUTOPLAY style, the control begins playing the AVI clip immediately after the .AVI file or AVI resource is opened. Otherwise, an application can use the ACM_PLAY message to start the AVI clip. An application can stop the clip at any time by sending the ACM_STOP message. The last frame played remains displayed when the control finishes playing the AVI clip or when ACM_STOP is sent.

An animation control can send two notification messages, ACN_START and ACN_STOP, to its parent window. Most applications do not handle either notification.

To close the .AVI file or AVI resource and remove it from memory, an application can use the Animate_Close macro, which sends ACM_OPEN with the filename or resource name set to NULL.


 Default Message Processing

This section describes the window messages handled by the window procedure for the ANIMATE_CLASS window class.

Message	Processing performed
WM_CLOSE	Frees the .AVI file or AVI resource associated with the animation control.
WM_DESTROY	Frees the .AVI file or AVI resource, frees an internal data structure, and then calls the DefWindowProc function.
WM_ERASEBKGND	Erases the window background using the current background color for static controls.
WM_NCCREATE	Allocates and initializes an internal data structure and then calls DefWindowProc.
WM_NCHITTEST	Returns the HTTRANSPARENT hit test value.
WM_PAINT	Draws an AVI frame in the animation control.
WM_SIZE	Checks if the control has the ACS_CENTER style. If the control does not, it calls DefWindowProc. Otherwise, it centers the animation in the control, invalidates the control, and then calls DefWindowProc.


 Using Animation Controls

•	Creating an animation control

•	Controlling the AVI clip


 Creating an Animation Control

The following function creates an animation control in a dialog box. The animation control is positioned below the specified control, and the dimensions of the animation control are based on the dimensions of a frame in the AVI clip.

// CreateAnimationCtrl - creates an animation control, positions it

//     below the specified control in a dialog box, and opens the AVI

//     clip for the animation control.

// Returns the handle to the animation control.

// hwndDlg - handle to the dialog box

// nIDCtl - identifier of the control below which the animation control

//     is to be positioned

//

// Constants

//     IDC_ANIMATE - identifier of the animation control

//     CX_FRAME, CY_FRAME - width and height of the frames

//         in the AVI clip

HWND CreateAnimationCtrl(HWND hwndDlg, int nIDCtl)

{

    HWND hwndAnim = NULL;

    RECT rc;

    POINT pt;

    // Create the animation control.

    hwndAnim = Animate_Create(hwndDlg, IDC_ANIMATE,

        WS_BORDER | WS_CHILD, g_hinst);

    // Get the screen coordinates of the specified control button.

    GetWindowRect(GetDlgItem(hwndDlg, nIDCtl), &rc);

    // Convert the coordinates of the lower-left corner to

    // client coordinates.

    pt.x = rc.left;

    pt.y = rc.bottom;

    ScreenToClient(hwndDlg, &pt);

    // Position the animation control below the Stop button.

    SetWindowPos(hwndAnim, 0, pt.x, pt.y + 20,

        CX_FRAME, CY_FRAME,

        SWP_NOZORDER | SWP_DRAWFRAME);

    // Open the AVI clip, and show the animation control.

    Animate_Open(hwndAnim, "SEARCH");

    ShowWindow(hwndAnim, SW_SHOW);

    return hwndAnim;

}


 Controlling the AVI Clip

The following function uses the predefined macros to control the display of the AVI clip in an animation control.

// DoAnimation - plays, stops, or closes an animation control's

//     AVI clip, depending on the value of an action flag.

// hwndAnim - handle to an animation control

// nAction - flag that determines whether to play, stop, or close

//     the AVI clip

void DoAnimation(HWND hwndAnim, int nAction)

{

    switch (nAction) {

        case PLAYIT:

            // Play the clip continuously starting with the

            // first frame.

            Animate_Play(hwndAnim, 0, -1, -1);

            break;

        case STOPIT:

            Animate_Stop(hwndAnim);

            break;

        case CLOSEIT:

            Animate_Close(hwndAnim);

            break;

        default:

            break;

    }

    return;

}


 Animation Control Reference

The following function messages, macros, and notification messages are associated with animation controls.


 Animation Control Messages and Macros

An application sends messages to control the playing of an AVI clip in an animation control. Each message has a corresponding macro, which you can use instead of sending the message explicitly. Some messages have related macros, which are a more specialized form of the corresponding macro.

ACM_OPEN
ACM_PLAY
ACM_STOP
Animate_Create


 Animation Control Notification Messages

An animation control sends notifications, in the form of WM_COMMAND messages, to its parent window to notify it about events.

ACN_START
ACN_STOP


 Animation Control Styles

The following window styles are used with animation controls.

ACS_AUTOPLAY	Starts playing the animation as soon as the animation clip is opened.
ACS_CENTER	Centers the animation in the animation control's window.
ACS_TRANSPARENT	Draws the animation using a transparent background rather than the background color specified in the animation clip.


 Common Controls

Common controls are a set of windows that are supported by the common control library, which is a dynamic-link library (DLL) included with the Microsoft® Windows® operating system. Like other control windows, a common control is a child window that an application uses in conjunction with another window to perform input and output (I/O) tasks.


 About Common Controls

Most common controls belong to a window class defined in the common control DLL. The window class and the corresponding window procedure define the properties, appearance, and behavior of the control. To ensure that the common control DLL is loaded, include the InitCommonControls function in your application. You create a common control by specifying the name of the window class when calling the CreateWindowEx function or by specifying the appropriate class name in a dialog box template.

For more detailed information about common controls, see the following topics.

•	Animation Controls

•	Drag List Boxes

•	Header Controls

•	Hot-Key Controls

•	Image Lists

•	List View Controls

•	Progress Bars

•	Property Sheets

•	Rich Edit Controls

•	Status Windows

•	Tab Controls

•	Toolbars

•	Tooltip Controls

•	Trackbars

•	Tree View Controls

•	Up-Down Controls


 About Common Control Styles

Each type of common control has a set of control styles that you can use to vary the appearance and behavior of the control. The common control library also includes a set of control styles that apply to two or more types of common controls. The common control styles are described in the following topics.


 About Common Control Messages

Because common controls are windows, an application can manipulate them by using messages, such as WM_GETFONT or WM_SETTEXT. In addition, the window class of each common control supports a set of control-specific messages that an application can use to manipulate the control. An application can use any of the message sending or posting functions to pass messages to the control. In addition, some common controls have a set of macros that an application can use instead of the sending or posting functions. The macros are typically easier to use than the functions.

When a change is made to the system color settings, Windows sends a WM_SYSCOLORCHANGE message to all top level windows. Your top level window must forward the WM_SYSCOLORCHANGE message to its common controls; otherwise, the controls will not be notified of the color change. This ensures that the colors used by your common controls are consistent with those used by other user interface objects. For example, a toolbar control uses the "3D Objects" color to draw its buttons. If the user changes the 3D Objects color but the WM_SYSCOLORCHANGE message is not forwarded to the toolbar, the toolbar buttons will remain in their original color while the color of other buttons in the system changes.


 About Common Control Notification Messages

Common controls are child windows that send notification messages to the 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 it to take. Except for trackbars, which use WM_HSCROLL message, common controls send notification messages as WM_NOTIFY messages. The lParam parameter of WM_NOTIFY is either the address of an NMHDR structure or the address of a larger structure that includes NMHDR as its first member. The structure contains the notification code and identifies the common control that sent the notification message. The meaning of the remaining structure members, if any, varies depending on the notification code.

Each type of common control has a corresponding set of notification codes. The common control library also provides notification codes that can be sent by more than one type of common control. Values for common notification values are described in the following topics.


 Common Control Reference

The following functions, messages, notification messages, macros, and structures apply to all common controls.

Notification Processing

FORWARD_WM_NOTIFY
HANDLE_WM_NOTIFY
NMHDR

Mouse Click Notifications

NM_CLICK
NM_DBLCLK
NM_RCLICK
NM_RDBLCLK

Operation-Related Notifications

NM_OUTOFMEMORY

Focus Notifications

NM_KILLFOCUS
NM_RETURN
NM_SETFOCUS

Miscellaneous

GetEffectiveClientRect
INDEXTOSTATEIMAGEMASK
InitCommonControls
ShowHideMenuCtl


 Common Control Functions

The following functions are used with common controls.

GetEffectiveClientRect
InitCommonControls
ShowHideMenuCtl


 Common Control Message

Common controls send the following message to notify the parent window of events that affect the control.

WM_NOTIFY


 Common Control Notification Messages

Common controls send notification messages to the parent window to inform it about events. The following notifications are used with common controls.

NM_CLICK
NM_DBLCLK
NM_KILLFOCUS
NM_OUTOFMEMORY
NM_RCLICK
NM_RDBLCLK
NM_RETURN
NM_SETFOCUS


 Common Control Macros

The following macros are used with common controls.

FORWARD_WM_NOTIFY
HANDLE_WM_NOTIFY
INDEXTOSTATEIMAGEMASK


 Common Control Structure

The following structure is used with common controls.

NMHDR


 Common Control Constants

The following window classes and control styles are used with common controls.


 Common Control Window Classes

The following window class names are provided by the common control library.

Class name	Description
ANIMATE_CLASS	Creates animation controls. These controls silently display an Audio Video Interleaved (AVI) clip.
HOTKEY_CLASS	Creates hot-key controls. These controls make it easy for the user to define hot keys.
PROGRESS_CLASS	Creates progress bars. These controls indicate the progress of a lengthy operation.
STATUSCLASSNAME	Creates status windows. These controls display status information in a horizontal window.
TOOLBARCLASSNAME	Creates toolbars. These controls contain buttons that carry out menu commands.
TOOLTIPS_CLASS	Creates tooltip controls. These controls display a small pop-up window containing a line of text that describes the purpose of a tool in an application.
TRACKBAR_CLASS	Creates trackbars. These controls let the user select from a range of values by moving a slider.
UPDOWN_CLASS	Creates up-down controls. These controls combine a pair of arrows with an edit control. Clicking the arrows increments or decrements the value in the edit control.
WC_HEADER	Creates header controls. These controls display headings at the top of columns of information and let the user sort the information by clicking the headings.
WC_LISTVIEW	Creates list-view controls. These controls display a collection of items, each consisting of an icon and a label, and provide several ways to arrange the items.
WC_TABCONTROL	Creates tab controls. These controls define multiple pages for the same area of a window or dialog box. Each page consists of a set of information or a group of controls that an application displays when the user selects the corresponding tab.
WC_TREEVIEW	Creates tree-view controls. These controls display a hierarchical list of items. Each item consists of a label and an optional bitmap.


 Common Control Styles

Following are the common control styles. Except where noted, these styles apply to header controls, toolbar controls, and status windows.

Common control style	Description
CCS_ADJUSTABLE	Enables a toolbar's built-in customization features, which allow the user to drag a button to a new position or to remove a button by dragging it off the toolbar. In addition, the user can double-click the toolbar to display the Customize Toolbar dialog box, allowing the user to add, delete, and rearrange toolbar buttons.
CCS_BOTTOM	Causes the control to position itself at the bottom of the parent window's client area and sets the width to be the same as the parent window's width. Status windows have this style by default.
CCS_NODIVIDER	Prevents a two-pixel highlight from being drawn at the top of the control.
CCS_NOHILITE	Prevents a one-pixel highlight from being drawn at the top of the control.
CCS_NOMOVEY	Causes the control to resize and move itself horizontally, but not vertically, in response to a WM_SIZE message. If CCS_NORESIZE is used, this style does not apply. Header windows have this style by default.
CCS_NOPARENTALIGN	Prevents the control from automatically moving to the top or bottom of the parent window. Instead, the control keeps its position within the parent window despite changes to the size of the parent. If CCS_TOP or CCS_BOTTOM is also used, the height is adjusted to the default, but the position and width remain unchanged.
CCS_NORESIZE	Prevents the control from using the default width and height when setting its initial size or a new size. Instead, the control uses the width and height specified in the request for creation or sizing.
CCS_TOP	Causes the control to position itself at the top of the parent window's client area and sets the width to be the same as the parent window's width. Toolbars have this style by default.


 Drag List Boxes

A drag list box is a special type of list box that enables the user to drag items from one position to another. An application can use a drag list box to display strings in a particular sequence and allow the user to change the sequence.


 About Drag List Boxes

To create a drag list box, you first create a standard list box and then call the MakeDragList function. To convert a list box in a dialog box to a drag list box, you can call MakeDragList when the WM_INITDIALOG message is processed.

Drag list boxes have the same window styles and process the same messages as standard list boxes.


 About Drag List Box Messages

A drag list box notifies its parent window of drag events by sending it a drag list message. The parent window must process the drag list message.

The drag list box registers the drag list message when the MakeDragList function is called. To get the message identifer (numeric value) of the drag list message, you must call the RegisterWindowMessage function, specifying the DRAGLISTMSGSTRING value.

The wParam parameter of the drag list message is the control identifier for the drag list box. The lParam parameter is the pointer to a DRAGLISTINFO structure, which contains the notification code for the drag event and other information. The return value of the message depends on the notification.


 About Drag List Box Notification Messages

A drag list box sends its parent window notification messages in the form of drag list messages. The specific notification, which is identified by the uNotification member of the specified DRAGLISTINFO structure, can be DL_BEGINDRAG, DL_DRAGGING, DL_CANCELDRAG, or DL_DROPPED.

The DL_BEGINDRAG notification message is sent when the user clicks the left mouse button with the cursor on a list item. The parent window can return TRUE to begin the drag operation or FALSE to disallow dragging. In this way, the parent window can enable dragging for some list items and disable it for others. You can determine which list item is at the specified location by using the LBItemFromPt function.

If dragging is in effect, the DL_DRAGGING notification message is sent whenever the mouse is moved, or at regular intervals if the mouse is not being moved. The parent window should determine the list item under the cursor by using LBItemFromPt and then draw the insert icon by using the DrawInsert function. By specifying TRUE for the bAutoScroll parameter of LBItemFromPt, you can cause the list box to scroll by one line if the cursor is above or below its client area. The value you return for this notification specifies the type of mouse cursor that the drag list box should set.

The DL_CANCELDRAG notification message is sent if the user cancels a drag operation by clicking the right mouse button or pressing the ESC key. The DL_DROPPED notification message is sent if the user completes a drag operation by releasing the left mouse button, even if the cursor is not over a list item. The drag list box releases the mouse capture before sending either notification. The return value of these two notifications is ignored.


 Drag List Box Reference

The following functions, notification messages, and structures are associated with drag list boxes.


 Drag List Box Functions

The following functions are used with drag list boxes.

DrawInsert
LBItemFromPt
MakeDragList


 Drag List Box Notification Messages

A drag list box sends notification messages to its parent window by using a registered window message, which is called a drag list message. There are the following drag list notification messages.

DL_BEGINDRAG
DL_CANCELDRAG
DL_DRAGGING
DL_DROPPED


 Drag List Box Structure

The following structure is used with drag list boxes.

DRAGLISTINFO


 Header Controls

A header control is a window that is usually positioned above columns of text or numbers. It contains a title for each column, and it can be divided into parts. The user can drag the dividers that separate the parts to set the width of each column. The following illustration shows a header control that has labeled columns giving detailed information about files in a directory.


 About Header Controls

You can create a header control by using the CreateWindowEx function, specifying the WC_HEADER window class. This window class is registered when the common control dynamic-link library (DLL) is loaded. To ensure that this DLL is loaded, use the InitCommonControls function. After you create a header control, you can divide it into parts, set the text in each part, and control the appearance of the window by using header window messages.


 About Header Control Styles

Header controls have a number of styles that determine the control's appearance and behavior. You set the initial styles when you create the header control. To retrieve and change the styles after creating the control, use the GetWindowLong and SetWindowLong functions.

A header control can be divided into two or more parts called header items. If a header control has the HDS_BUTTONS style, each item in the control looks and behaves like a push button. This style is useful if an application carries out a task when the user clicks an item in the header control. For example, an application could sort information in the columns differently depending on which item the user clicks.

The HDS_HORZ style creates a header control with a horizontal orientation.


 Header Control Size and Position

Typically, you must set the size and position of a header control to fit within the boundaries of a particular rectangle, such as the client area of a window. By using the HDM_LAYOUT message, you can retrieve the appropriate size and position values from the header control.

When sending HDM_LAYOUT, you specify the address of an HD_LAYOUT structure that contains the coordinates of the rectangle that the header control is to occupy and provides a pointer to a WINDOWPOS structure. The control fills the WINDOWPOS structure with size and position values appropriate for positioning the control along the top of the specified rectangle. The height value is the sum of the heights of the control's horizontal borders and the average height of characters in the font currently selected into the control's device context.

If you want to use HDM_LAYOUT to set the initial size and position of a header control, you should set the initial visibility state of the control so that it is hidden. After sending HDM_LAYOUT to retrieve the size and position values, you can use the SetWindowPos function to set the new size, position, and visibility state.


 Items

Each item in a header control can have a string, a bitmapped image, and an application-defined 32-bit value associated with it. The string and bitmap are displayed within the boundaries of the header item. If an item contains both a string and an image, the image is displayed above the string. If the string and image overlap, the string overwrites the overlapping portion of the image.

You add an item to a header control by sending the HDM_INSERTITEM message to the control. The message includes the address of an HD_ITEM structure, which defines the properties of the header item, including its string, bitmap, initial size, and application-defined value. The structure also specifies formatting flags that tell the control whether to center, left-align, or right-align the string or bitmap in the item's rectangle.

HDM_INSERTITEM returns the index of the newly added item. You can use the index in other messages to set properties or retrieve information about the item. You can delete an item by using the HDM_DELETEITEM message, specifying the index of the item to delete.

You can use the HDM_SETITEM message to set the properties of an existing header item and the HDM_GETITEM message to retrieve the current properties of an item. To retrieve a count of the items in a header control, use the HDM_GETITEMCOUNT message.

You can use the HBT_SPRING value to give a header item a "springy" quality. Although an item has a minimum width, it can grow wider if there is extra room in the owner window. A header control can have multiple springy items; the extra room in the owner window is distributed among the springy items.

To make an item springy, send the WM_SETTEXT message to the header control. In the wParam parameter, use the logical OR operator to combine the index of the header item with the HBT_SPRING value.


 Owner-Drawn Header Controls

You can define individual items of a header control to be owner-drawn items. Using this technique gives you more control than you would otherwise have over the appearance of a header item.

You can use the HDM_INSERTITEM message to insert a new owner-drawn item into a header control or the HDM_SETITEM message to change an existing item to an owner-drawn item. Both messages include the address of an HD_ITEM structure, which should have the fmt member set to the HDF_OWNERDRAW value.

When a header control must draw an owner-drawn item, it sends the WM_DRAWITEM message to the parent window. The wParam parameter of the message is the child window identifier of the header control, and the lParam parameter is a pointer to a DRAWITEMSTRUCT structure. The parent window uses the information in the structure to draw the item. For an owner-drawn item in a header control, the DRAWITEMSTRUCT structure contains the following information.

Member	Description
CtlType	ODT_HEADER owner-drawn control type.
CtlID	Child-window identifier of the header control.
itemID	Index of the item to be drawn.
itemAction	ODA_DRAWENTIRE drawing-action flag.
itemState	ODS_SELECTED drawing-action flag if the cursor is on the item and the mouse button is down. Otherwise, this member is zero.
hwndItem	Handle of the header control.
hDC	Handle of the device context of the header control.
rcItem	Coordinates of the header item to be drawn. The coordinates are relative to the upper left corner of the header control.
itemData	Application-defined 32-bit value associated with the item.


 About Header Control Notification Messages

A header control sends notification messages to its parent window when the user clicks or double-clicks an item, when the user drags an item divider, and when the attributes of an item change. The parent window receives the notifications in the form of WM_NOTIFY messages. The following notifications are used with header controls.

Notification	Description
HDN_BEGINTRACK	Signals the start of divider dragging.
HDN_DIVIDERDBLCLICK	Indicates that the user double-clicked a divider.
HDN_ENDTRACK	Signals the end of divider dragging.
HDN_ITEMCHANGED	Indicates a change in the attributes of an item.
HDN_ITEMCHANGING	Indicates that the attributes of an item are about to change.
HDN_ITEMCLICK	Indicates that the user clicked an item.
HDN_ITEMDBLCLICK	Indicates that the user double-clicked an item.
HDN_TRACK	Indicates that the user dragged a divider.


 Default Header Control Message Processing

This section describes the window messages handled by the window procedure for the WC_HEADER window class.

Message	Processing performed
WM_CREATE	Initializes the header control.
WM_DESTROY	Frees resources allocated for the header control.
WM_ERASEBKGND	Erases the background of the header control using the current background color for the control.
WM_GETDLGCODE	Returns a combination of the DLGC_WANTTAB and DLGC_WANTARROWS values.
WM_GETFONT	Returns the handle of the current font, which is used by the header control to draw its text.
WM_LBUTTONDBLCLK	Captures mouse input. If the mouse cursor is on a divider, the control sends a HDN_BEGINTRACK notification message and begins tracking mouse movement. If the cursor is on a header item, the control redraws the item in the style that indicates the item is pressed.
WM_LBUTTONDOWN	Same as the WM_LBUTTONDBLCLK message.
WM_LBUTTONUP	Releases the mouse capture. If the control was tracking mouse movement, it sends the HDN_ENDTRACK notification message and redraws the header control. Otherwise, the control sends the HDN_ITEMCLICK notification message and redraws the header item that was clicked.
WM_MOUSEMOVE	If a divider is being dragged, the control sends the HDN_TRACK notification message and redraws itself. If the left mouse button is down and the cursor is on an item, the control redraws the item in the style that indicates the item is pressed.
WM_NCCREATE	Allocates and initializes an internal data structure.
WM_NCDESTROY	Frees resources allocated by the header control.
WM_PAINT	Paints the invalid region of the header control.
WM_SETCURSOR	Sets the cursor shape, depending on whether the cursor is on a divider or in a header item.
WM_SETFONT	Selects a new font handle into the device context for the header control.


 Using Header Controls

•	Creating a header control

•	Adding an item to a header control


 Creating a Header Control

The following example creates a header control and positions it along the top of the parent window's client area. The control is initially hidden. The example uses the HDM_LAYOUT message to determine the appropriate size and position of the control given the bounding rectangle of the parent window. Then the example sets the size and position of the control and makes it visible.

// DoCreateHeader - creates a header control that is positioned along

//     the top of the parent window's client area.

// Returns the handle of the header control.

// hwndParent - handle of the parent window

//

// Global variable

//    g_hinst - handle of the application instance

extern HINSTANCE g_hinst;

HWND DoCreateHeader(HWND hwndParent)

{

        HWND hwndHeader;

        RECT rcParent;

        HD_LAYOUT hdl;

        WINDOWPOS wp;

        // Ensure that the common control DLL is loaded, and then create

        // the header control.

        InitCommonControls();

        if ((hwndHeader = CreateWindowEx(0, WC_HEADER, (LPCTSTR) NULL,

                WS_CHILD | WS_BORDER | HDS_BUTTONS | HDS_HORZ,

                0, 0, 0, 0, hwndParent, (HMENU) ID_HEADER, g_hinst,

                (LPVOID) NULL)) == NULL)

            return (HWND) NULL;

        // Retrieve the bounding rectangle of the parent window's

        // client area, and then request size and position values

        // from the header control.

        GetClientRect(hwndParent, &rcParent);

        hdl.prc = &rcParent;

        hdl.pwpos = &wp;

        if (!SendMessage(hwndHeader, HDM_LAYOUT, 0, (LPARAM) &hdl))

            return (HWND) NULL;

        // Set the size, position, and visibility of the header control.

        SetWindowPos(hwndHeader, wp.hwndInsertAfter, wp.x, wp.y,

            wp.cx, wp.cy, wp.flags | SWP_SHOWWINDOW);

        return hwndHeader;

}


 Adding an Item to a Header Control

The following example demonstrates how to use the HDM_INSERTITEM message and the HD_ITEM structure to add an item to a header control. The new item consists of a string that is left-justified within the item rectangle.

// DoInsertItem - inserts items into a header control.

// Returns the index of the newly added item.

// hwndHeader - handle of the header control

// iInsertAfter - index of the previous item

// nWidth - width of the new item

// lpsz - address of the item string

int DoInsertItem(HWND hwndHeader, int iInsertAfter,

    int nWidth, LPSTR lpsz)

{

    HD_ITEM hdi;

    int index;

    hdi.mask = HDI_TEXT | HDI_FORMAT | HDI_WIDTH;

    hdi.pszText = lpsz;

    hdi.cxy = nWidth;

    hdi.cchTextMax = lstrlen(hdi.pszText);

    hdi.fmt = HDF_LEFT | HDF_STRING;

    index = SendMessage(hwndHeader, HDM_INSERTITEM,

        (WPARAM) iInsertAfter, (LPARAM) &hdi);

    return index;

}


 Header Control Reference

The following messages, notification messages, and structures are associated with header controls. These elements can be grouped as follows.

Size and Position

HDM_LAYOUT
HD_LAYOUT

Inserting and Deleting Items

HDM_DELETEITEM
HDM_INSERTITEM

Item Attributes

HDM_SETITEM
HDN_ITEMCHANGED
HDN_ITEMCHANGING
HDN_TRACK

Item Information

HDM_GETITEM
HDM_GETITEMCOUNT
HDN_ITEMCLICK
HDN_ITEMDBLCLICK
HD_ITEM
HD_NOTIFY

Divider Tracking

HDN_BEGINTRACK
HDN_DIVIDERDBLCLICK
HDN_ENDTRACK

Hit Testing

HD_HITTESTINFO
HDM_HITTEST


 Header Control Messages

An application sends messages to add items and to control the appearance and behavior of a header control. Each message has a corresponding macro, which you can use instead of sending the message explicitly. There are the following header control messages.

HDM_DELETEITEM
HDM_GETITEM
HDM_GETITEMCOUNT
HDM_HITTEST
HDM_INSERTITEM


 Header Control Notification Messages

A header control sends notification messages, in the form of WM_NOTIFY messages, to its parent window to notify it about events. The following notification messages are used with header controls.

HDN_BEGINTRACK
HDN_DIVIDERDBLCLICK
HDN_ENDTRACK
HDN_ITEMCHANGED
HDN_ITEMCHANGING
HDN_ITEMCLICK
HDN_ITEMDBLCLICK
HDN_TRACK


 Header Control Structures

The following structures are used with header controls.

HD_HITTESTINFO
HD_ITEM
HD_LAYOUT
HD_NOTIFY


 Header Control Styles

The following window styles are used with header controls.

HDS_BUTTONS	Header items behave like buttons.
HDS_HORZ	The header control is horizontal.


 Hot-Key Controls

A hot-key control is a window that enables the user to enter a combination of keystrokes to be used as a hot key. A hot key is a key combination that the user can press to perform an action quickly. (For example, a user can create a hot key that activates a given window and brings it to the top of the Z order.) The hot-key control displays the user's choices and ensures that the user selects a valid key combination.


 About Hot-Key Controls

When the user enters a key combination to be used as a hot key, the names of the keys appear in the hot-key control. A key combination can consist of a modifier key (such as CTRL, ALT, or SHIFT) and an accompanying key (such as a character key, an arrow key, a function key, and so on).

After the user has chosen a key combination, the application retrieves the key combination from the hot-key control and uses it to set up a hot key in the system. The information retrieved from the hot-key control includes a flag indicating the modifier key and the virtual-key code of the accompanying key.

The application can use the information provided by a hot-key control to set up a global hot key or a thread-specific hot key. A global hot key is associated with a particular window; it allows the user to activate the window from any part of the system. An application sets a global hot key by using the WM_SETHOTKEY message. Whenever the user uses a global hot key, the window specified in WM_SETHOTKEY receives a WM_SYSCOMMAND message that specifies the SC_HOTKEY value. This message activates the window that receives it. The hot key remains valid until the application that called WM_SETHOTKEY exits.

A thread-specific hot key generates a WM_HOTKEY message that is posted to the beginning of a particular thread so that it is removed by the next iteration of the message loop. An application sets a thread-specific hot key by using the RegisterHotKey function.


 Hot-Key Control Creation

You create a hot-key control by using the CreateWindowEx function, specifying the HOTKEY_CLASS window class. When the function returns a handle to the hot-key control, an application typically sets some rules about invalid hot-key combinations and provides perhaps a default key combination. If an application does not set any rules, the user can choose any key or key combination as a hot key. Most applications, however, do not allow the user to use a common key (for example, the letter A) as a hot key.


 About Hot-Key Control Messages

After creating a hot-key control, an application interacts with it by using three messages: HKM_SETRULES, HKM_SETHOTKEY, and HKM_GETHOTKEY.

An application can send the HKM_SETRULES message to specify a set of CTRL, ALT, and SHIFT key combinations that are considered invalid hot keys. If the application specifies an invalid key combination, it should also specify a default modifier combination to use when the user selects the invalid combination. When the user enters the invalid combination, the system performs a logical-OR operation on the invalid combination entered by the user and the default combination. The result is considered a valid combination; it is converted to a string and displayed in the control.

The HKM_SETHOTKEY message allows an application to set the hot key combination for a hot-key control. This message is also typically used when the hot-key control is created.

Applications use the HKM_GETHOTKEY message to retrieve the virtual-key code and modifier flags of the hot key chosen by the user of a hot-key control.


 Default Hot-Key Message Processing

This section describes the window messages handled by the window procedure for the predefined HOTKEY_CLASS window class used with hot-key controls.

Message	Processing performed
WM_CHAR	Retrieves the virtual-key code.
WM_CREATE	Initializes the hot-key control, sets no hot-key rules, and uses the system font.
WM_ERASEBKGND	Hides the caret, calls the DefWindowProc function, and shows the caret again.
WM_GETDLGCODE	Returns a combination of the DLGC_WANTCHARS and DLGC_WANTARROWS values.
WM_GETFONT	Retrieves the font.
WM_KEYDOWN	Calls the DefWindowProc function if the key is ENTER, TAB, SPACE BAR, DEL, ESC, or BACKSPACE. If the key is SHIFT, CTRL, or ALT, it checks whether the combination is valid and, if it is, sets the hot key using the combination. Other keys are set as hot keys without their validity being checked first.
WM_KEYUP	Retrieves the virtual-key code.
WM_KILLFOCUS	Destroys the caret.
WM_LBUTTONDOWN	Sets the focus to the window.
WM_NCCREATE	Sets the WS_EX_CLIENTEDGE window style.
WM_PAINT	Paints the hot-key control.
WM_SETFOCUS	Creates and shows the caret.
WM_SETFONT	Sets the font.
WM_SYSCHAR	Retrieves the virtual-key code.
WM_SYSKEYDOWN	Calls the DefWindowProc function if the key is ENTER, TAB, SPACE BAR, DEL, ESC, or BACKSPACE. If the key is SHIFT, CTRL, or ALT, it checks whether the combination is valid and, if it is, sets the hot key using the combination. Other keys are set as hot keys without their validity being checked first.
WM_SYSKEYUP	Retrieves the virtual-key code.


 Using Hot-Key Controls

•	Creating a hot-key control

•	Retrieving and setting a hot key


 Creating a Hot-Key Control

The following function creates a hot-key control, uses the HKM_SETRULES and HKM_SETHOTKEY messages to initialize it, and returns a handle to the control. This hot-key control does not allow the user to choose a hot key that is a single unmodified key, nor does it permit the user to choose only SHIFT and a key. (These rules effectively prevent the user from choosing a hot key that might be accidentally entered while typing text.)

// InitializeHotkey - creates a hot-key control and sets rules

//    and default settings for it.

// Returns the handle of the hot-key control.

// hwndDlg - handle of the parent window (dialog box)

//

// Global variable

//     g_hinst - handle of the application instance

extern HINSTANCE g_hinst;

HWND WINAPI InitializeHotkey(HWND hwndDlg)

{

    // Ensure that the common control DLL is loaded.

    InitCommonControls();

    hwndHot = CreateWindowEx(

        0,                             // no extended styles

        HOTKEY_CLASS,                  // class name

        "",                            // no title (caption)

        WS_CHILD | WS_VISIBLE,         // style

        10, 10,                        // position

        200, 20,                       // size

        hwndDlg,                       // parent window

        NULL,                          // uses class menu

        g_hinst,                       // instance

        NULL                           // no WM_CREATE parameter

        );

    SetFocus(hwndHot);

    // Set rules for invalid key combinations. If the user

    // does not supply a modifier key, use ALT as a modifier.

    // If the user supplies SHIFT as a modifier key, use

    // SHIFT + ALT instead.

    SendMessage(hwndHot, HKM_SETRULES,

        (WPARAM) HKCOMB_NONE | HKCOMB_S, // invalid key combinations

        MAKELPARAM(HOTKEYF_ALT, 0));     // add ALT to invalid entries

    // Set CTRL + ALT + A as the default hot key for this window.

    // 0x41 is the virtual-key code for 'A'.

    SendMessage(hwndHot, HKM_SETHOTKEY,

        MAKEWORD(0x41, HOTKEYF_CONTROL | HOTKEYF_ALT), 0);

    return hwndHot;

}


 Retrieving and Setting a Hot Key

After the user has chosen a hot key, an application should retrieve the hot key from the hot-key control by using the HKM_GETHOTKEY message. This message retrieves a 16-bit value that contains the virtual-key code and modifier keys describing the hot key.

The following function retrieves a key combination from a hot-key control and then uses the WM_SETHOTKEY message to set a global hot key. Note that you cannot set a global hot key for a window that has the WS_CHILD window style.

// ProcessHotkey - retrieves the hot key from the hot-key control and

//     sets it as the hot key for the application's main window.

// Returns TRUE if successful or FALSE otherwise.

// hwndHot - handle of the hot-key control

// hwndMain - handle of the main window

BOOL WINAPI ProcessHotkey(HWND hwndHot, HWND hwndMain)

{

    WORD wHotkey;

    UINT iSetResult;

    // Retrieve the hot key (virtual-key code and modifiers).

    wHotkey = SendMessage(hwndHot, HKM_GETHOTKEY, 0, 0);

    // Use the result as wParam for WM_SETHOTKEY.

    iSetResult = SendMessage(hwndMain, WM_SETHOTKEY, wHotkey, 0);

    switch (iSetResult) {

        case 2:            // WM_SETHOTKEY succeeded

            MessageBox(NULL, "Hot key previously assigned",

                "Okay", MB_OK);

            return TRUE;

        case 1:            // WM_SETHOTKEY succeeded

            return TRUE;

        case 0:

            MessageBox(NULL, "Invalid window for hot key",

                "Error", MB_OK);

            return FALSE;

        case -1:

            MessageBox(NULL, "Invalid hot key",

                "Error", MB_OK);

            return FALSE;

        default:

            MessageBox(NULL, "Unknown error", "Error", MB_OK);

            return FALSE;

    }

}


 Hot-Key Control Messages

The following messages are associated with hot-key controls.

HKM_GETHOTKEY
HKM_SETHOTKEY
HKM_SETRULES


 Image Lists

An image list is a collection of same-sized images, each of which can be referred to by its index. Image lists are used to efficiently manage large sets of icons or bitmaps. All images in an image list are contained in a single, wide bitmap in screen device format. An image list may also include a monochrome bitmap that contains masks used to draw images transparently (icon style).


 About Image Lists

The Microsoft® Win32® application programming interface (API) provides image list functions, which enable you to draw images, create and destroy image lists, add and remove images, replace images, merge images, and drag images.

To use the image list functions, you must include the common control header file in your source code files and link with the common control export library. In addition, before calling any image list function, you must use the InitCommonControls function to ensure that the common control dynamic-link library (DLL) is loaded.


 Types

There are two types of image lists: nonmasked and masked. A nonmasked image list consists of a color bitmap that contains one or more images. A masked image list consists of two bitmaps of equal size. The first is a color bitmap that contains the images, and the second is a monochrome bitmap that contains a series of masks — one for each image in the first bitmap.

When a nonmasked image is drawn, it is simply copied into the target device context; that is, it is drawn over the existing background color of the device context. When a masked image is drawn, the bits of the image are combined with the bits of the mask, typically producing transparent areas in the bitmap where the background color of the target device context shows through. There are several drawing styles that you can specify when drawing a masked image. For example, you can specify that the image be dithered to indicate a selected object. For more information about drawing images, see Drawing Images.


 Image List Creation

You create an image list by calling the ImageList_Create function. The parameters include the type of image list to create, the dimensions of each image, and the number of images you intend to add to the list. For a nonmasked image list, the function creates a single bitmap large enough to hold the specified number of images of the given dimensions. Then it creates a screen-compatible device context and selects the bitmap into it. For a masked image list, the function creates two bitmaps and two screen-compatible device contexts. It selects the image bitmap into one device context and the mask bitmap into the other.

The initial size of an image list is determined by the size values you specify in ImageList_Create. If you attempt to add more images than you initially specified, the image list automatically grows to accommodate the additional images. In ImageList_Create, you specify the amount of images by which the image list can grow.

If ImageList_Create succeeds, it returns a handle of the HIMAGELIST type. You use this handle in other image list functions to access the image list and manage the images. You can add and remove images, copy images from one image list to another, and merge images from two different image lists. When you no longer need an image list, you can destroy it by specifying its handle in a call to the ImageList_Destroy function.


 Adding and Removing Images

You can add bitmapped images, icons, or cursors to an image list. You add bitmapped images by specifying the handles of two bitmaps in a call to the ImageList_Add function. The first bitmap contains one or more images to add to the image bitmap, and the second bitmap contains the masks to add to the mask bitmap. For nonmasked image lists, the second bitmap handle is ignored; it can be set to NULL.

The ImageList_AddMasked function also adds bitmapped images to a masked image list. This function is similar to ImageList_Add, except that you do not specify a mask bitmap. Instead, you specify a color that the system combines with the image bitmap to automatically generate the masks. Each pixel of the specified color in the image bitmap is changed to black, and the corresponding bit in the mask is set to one. As a result, any pixel in the image that matches the specified color is transparent when the image is drawn.

The ImageList_AddIcon function adds an icon or cursor to an image list. If the image list is masked, ImageList_AddIcon adds the mask provided with the icon or cursor to the mask bitmap. If the image list is nonmasked, the mask for the icon or cursor is not used when drawing the image.

You can create an icon based on an image and mask in an image list by using the ImageList_GetIcon function. The function returns the handle of the new icon.

ImageList_Add, ImageList_AddMasked, and ImageList_AddIcon assign an index to each image as it is added to an image list. The indexes are zero-based; that is, the first image in the list has an index of zero, the next has an index of one, and so on. After adding a single image, the functions return the index of the image. When more than one image is added at a time, the functions return the index of the first image.

The ImageList_Remove function removes an image from an image list.


 Replacing and Merging Images

The ImageList_Replace and ImageList_ReplaceIcon functions replace an image in an image list with a new image. ImageList_Replace replaces an image with a bitmapped image and mask, and ImageList_ReplaceIcon replaces an image with an icon or cursor.

The ImageList_Merge function merges two images, storing the new image in a new image list. The new image is created by drawing the second image transparently over the first. The mask for the new image is the result of performing a logical OR operation on the bits of the masks for the two existing images.


 Drawing Images

To draw an image, you use the ImageList_Draw or ImageList_DrawEx function. You specify the handle of an image list, the index of the image to draw, the handle of the destination device context, a location within the device context, and one or more drawing styles.

When you specify the ILD_TRANSPARENT style, ImageList_Draw or ImageList_DrawEx uses a two-step process to draw a masked image. First, it performs a logical AND operation on the bits of the image and the bits of the mask. Then it performs a logical XOR operation on the results of the first operation and the background bits of the destination device context. This process creates transparent areas in the resulting image; that is, each white bit in the mask causes the corresponding bit in the resulting image to be transparent.

Before drawing a masked image on a solid color background, you should use the ImageList_SetBkColor function to set the background color of the image list to the same color as the destination. Setting the color eliminates the need to create transparent areas in the image and enables ImageList_Draw or ImageList_DrawEx to simply copy the image to the destination device context, resulting in a significant increase in performance. To draw the image, specify the ILD_NORMAL style in a call to ImageList_Draw or ImageList_DrawEx.

You can set the background color for a masked image list at any time so that it draws correctly on any solid background. Setting the background color to CLR_NONE causes images to be drawn transparently by default. To retrieve the background color of an image list, use the ImageList_GetBkColor function.

The ILD_BLEND25 and ILD_BLEND50 styles dither the image with the system highlight color. These styles are useful if you use a masked image to represent an object that the user can select. For example, you can use the ILD_BLEND50 style to draw the image when the user selects it.

A nonmasked image is copied to the destination device context using the SRCCOPY raster operation. The colors in the image appear the same regardless of the background color of the device context. The drawing styles specified in ImageList_Draw or ImageList_DrawEx also have no effect on the appearance of a nonmasked image.


 Overlay Mask

Every image list includes a list of images to use as overlay masks. An overlay mask is an image drawn transparently over another image. Any image can be used as an overlay mask. You can specify up to four overlay masks per image list.

You add the index of an image to the list of overlay masks by using the ImageList_SetOverlayImage function, specifying the handle of the image list, the index of an image, and the index of an overlay mask. Note that the indices for the overlay masks are one-based rather than zero-based.

You draw an overlay mask over an image using a single call to the ImageList_Draw or ImageList_DrawEx function. The parameters include the index of the image to draw and the index of an overlay mask. You must use the INDEXTOOVERLAYMASK macro to specify the index of the overlay mask.


 Dragging Images

The Win32 API includes functions for dragging an image on the screen. The dragging functions move an image smoothly, in color, and without any flashing of the cursor. Both masked and unmasked images can be dragged.

The ImageList_BeginDrag function begins a drag operation. The parameters include the handle of the image list, the index of the image to drag, and the location of the hot spot within the image. The hot spot is a single pixel that the dragging functions recognize as the exact screen location of the image. Typically, an application sets the hot spot so that it coincides with the hot spot of the mouse cursor. The ImageList_DragMove function moves the image to a new location.

The ImageList_DragEnter function sets the initial position of the drag image within a window and draws the image at the position. The parameters include the handle of the window in which to draw the image and the coordinates of the initial position within the window. The coordinates are relative to the window's upper-left corner, not the client area. The same is true for all of the image dragging functions that take coordinates as parameters. This means you must compensate for the widths of window elements, such as the border, title bar, and menu bar, when specifying the coordinates. If you specify a NULL window handle when calling ImageList_DragEnter, the dragging functions draw the image in the device context associated with the desktop window, and the coordinates are relative to the upper-left corner of the screen.

ImageList_DragEnter locks all other updates to the given window during the drag operation. If you need to do any drawing during a drag operation, such as highlighting the target of a drag and drop operation, you can temporarily hide the dragged image by using the ImageList_DragLeave function. Another method is to use the GetDCEx function with the DCX_LOCKWINDOWUPDATE value to retrieve a device context that allows you to draw. You must be careful, however, not to obliterate the dragged image.

The ImageList_SetDragCursorImage creates a new drag image by combining the given image (typically a mouse cursor image) with the current drag image. Because the dragging functions use the new image during a drag operation, you should use the ShowCursor function to hide the actual mouse cursor after calling ImageList_SetDragCursorImage. Otherwise, the system may appear to have two mouse cursors for the duration of the drag operation.

When an application calls ImageList_BeginDrag, the system creates an temporary, internal image list can copies the specified drag image to the internal list. You can retrieves the handle of the temporary drag image list by using the ImageList_GetDragImage function. The function also retrieves the current drag position, and the offset of the drag image relative to the drag position.


 Image Information

The Win32 API includes a number of functions that retrieve information from an image list. The ImageList_GetImageInfo function fills an IMAGEINFO structure with information about a single image, including the handles of the image and mask bitmaps, the number of color planes and bits per pixel, and the bounding rectangle of the image within the image bitmap. You can use this information to directly manipulate the bitmaps for the image.

The ImageList_GetImageCount function retrieves the number of images in an image list.


 Using Image Lists

•	Creating an image list.

•	Dragging an image.


 Creating an Image List

To create an image list, use the ImageList_Create function, specifying the type of image list to create (unmasked or masked); the width and height, in pixels, of the images; the number of images you intend to add to the image list; and the amount of images by which the list can grow when it is resized to accommodate additional images. The common control DLL contains the executable code for the image list functions. You must ensure that the library is loaded by using the InitCommonControls function before making any calls to image list functions.

The following example creates a masked image list and uses the ImageList_AddIcon function to add two icons to the list.

// AddIconsToImageList - creates a masked image list and adds some

//     icons to it.

// Returns the handle of the new image list.

// hinst - handle of the application instance

//

// Global variables and constants

//     g_nBird and g_nTree - indexes of the images

//     CX_ICON and CY_ICON - width and height of the icon

//     NUM_ICONS - number of icons to add to the image list

extern int g_nBird, g_nTree;

#define CX_ICON  32

#define CY_ICON  32

#define NUM_ICONS 3

HIMAGELIST AddIconsToImageList(HINSTANCE hinst)

{

    HIMAGELIST himlIcons;  // handle of new image list

    HICON hicon;           // handle of icon

    // Ensure that the common control DLL is loaded.

    InitCommonControls();

    // Create a masked image list large enough to hold the icons.

    himlIcons = ImageList_Create(CX_ICON, CY_ICON, TRUE, NUM_ICONS, 0);

    // Load the icon resources, and add the icons to the image list.

    hicon = LoadIcon(hinst, MAKEINTRESOURCE(IDI_BIRD));

    g_nBird = ImageList_AddIcon(himlIcons, hicon);

    hicon = LoadIcon(hinst, MAKEINTRESOURCE(IDI_TREE));

    g_nTree = ImageList_AddIcon(himlIcons, hicon);

    return himlIcons;

}


 Dragging an Image

Dragging an image involves calls to the ImageList_BeginDrag, ImageList_DragMove, and ImageList_EndDrag functions. ImageList_BeginDrag begins a drag operation by combining an image with the current mouse cursor, setting a hot spot in the image, and drawing the image in its initial position. The function also prevents the system from updating any other parts of the display. ImageList_DragMove drags the image to a new location. ImageList_EndDrag ends a drag operation, permitting the system to update any part of the display.

The remainder of this section provides an example using four functions that demonstrates how to drag an image. The first function shows how to draw an image in a window's client area, and subsequent functions show how to drag the image.


 Drawing the Image

The following function draws an image and saves the client coordinates of the image's bounding rectangle. A subsequent function uses the bounding rectangle to determine whether the user has clicked the image.

// DrawTheImage - draws an image transparently and saves

//     the bounding rectangle of the drawn image

// Returns TRUE if successful or FALSE otherwise.

// hwnd - handle of the window in which to draw the image

// himl - handle of the image list that contains the image

// cx and cy - client coordinates for the upper-left corner of the image

//

// Global variables and constants

//     g_nImage - index of the image to draw

//     g_rcImage - bounding rectangle of the image

//     CX_IMAGE and CY_IMAGE - width and height of the image

extern int g_nImage;

extern RECT g_rcImage;

#define CX_IMAGE 32

#define CY_IMAGE 32

BOOL DrawTheImage(HWND hwnd, HIMAGELIST himl, int cx, int cy)

{

    HDC hdc;

    if ((hdc = GetDC(hwnd)) == NULL)

        return FALSE;

    if (!ImageList_Draw(himl, g_nImage, hdc, cx, cy, ILD_TRANSPARENT))

        return FALSE;

    ReleaseDC(hwnd, hdc);

    SetRect(&g_rcImage, cx, cy, CX_IMAGE + cx, CY_IMAGE + cy);

    return TRUE;

}


 Beginning the Drag Operation

The following function is intended to be called in response to a mouse button-down message, such as WM_LBUTTONDOWN. The function determines whether the user has clicked within the bounding rectangle of the image. If the user has clicked, the function captures the mouse input, erases the image from the client area, and calculates the position for the hot spot within the image. The function sets the hot spot to coincide with the hot spot of the mouse cursor. Then the function begins the drag operation by calling ImageList_BeginDrag.

// StartDragging - begins dragging a bitmap.

// Returns TRUE if successful or FALSE otherwise.

// hwnd - handle of the window in which the bitmap is dragged

// ptCur - coordinates of the cursor

// himl - handle of the image list

//

// Global variables

//     g_rcImage - bounding rectangle of the image to drag

//     g_nImage - index of the image

//     g_ptHotSpot - location of the image's hot spot

//     g_cxBorder and g_cyBorder - width and height of border

//     g_cyCaption and g_cyMenu - height of title bar and menu bar

extern RECT g_rcImage;

extern int g_nImage;

extern POINT g_ptHotSpot;

BOOL StartDragging(HWND hwnd, POINT ptCur, HIMAGELIST himl)

{

    // Return if the cursor is not in the bounding rectangle of

    // the image.

    if (!PtInRect(&g_rcImage, ptCur))

        return FALSE;

    // Capture the mouse input.

    SetCapture(hwnd);

    // Erase the image from the client area.

    InvalidateRect(hwnd, &g_rcImage, TRUE);

    UpdateWindow(hwnd);

    // Calculate the location of the hot spot, and save it.

    g_ptHotSpot.x = ptCur.x - g_rcImage.left;

    g_ptHotSpot.y = ptCur.y - g_rcImage.top;

    // Begin the drag operation.

    if (!ImageList_BeginDrag(himl, g_nImage,

            g_ptHotSpot.x, g_ptHotSpot.y))

        return FALSE;

    // Set the initial location of the image, and make it visible.

    // Because the ImageList_DragEnter function expects coordinates to

    // be relative to the upper-left corner of the given window, the

    // width of the border, title bar, and menu bar need to be taken

    // into account.

    ImageList_DragEnter(hwnd, ptCur.x + g_cxBorder,

        ptCur.y + g_cyBorder + g_cyCaption + g_cyMenu);

    g_fDragging = TRUE;

    return TRUE;

}


 Moving the Image

The following function, which drags the image to a new location, is intended to be called in response to the WM_MOUSEMOVE message.

// MoveTheImage - drags an image to the specified coordinates.

// Returns TRUE if successful or FALSE otherwise.

// ptCur - new coordinates for the image

BOOL MoveTheImage(POINT ptCur)

{

    if (!ImageList_DragMove(ptCur.x, ptCur.y))

        return FALSE;

    return TRUE;

}


 Ending the Drag Operation

The following function ends the drag operation and draws the image in its final location. It also releases the mouse capture.

// StopDragging - ends a drag operation and draws the image

//     at its final location.

// Returns TRUE if successful or FALSE otherwise.

// hwnd - handle of the window in which the bitmap is dragged

// himl - handle of the image list

// ptCur - coordinates of the cursor

//

// Global variable

//     g_ptHotSpot - location of the image's hot spot

extern POINT g_ptHotSpot;

BOOL StopDragging(HWND hwnd, HIMAGELIST himl, POINT ptCur)

{

    ImageList_EndDrag();

    ImageList_DragLeave(hwnd)

    g_fDragging = FALSE;

    DrawTheImage(hwnd, himl, ptCur.x - g_ptHotSpot.x,

        ptCur.y - g_ptHotSpot.y);

    ReleaseCapture();

    return TRUE;

}


 Image List Reference

The following functions, macros, and structures are associated with image lists. These elements can be grouped as follows.

Creating Image Lists

ImageList_Create
ImageList_Destroy
ImageList_LoadBitmap
ImageList_LoadImage

Adding and Removing Images

ImageList_Add
ImageList_AddIcon
ImageList_AddMasked
ImageList_Remove

Replacing and Merging Images

ImageList_Replace
ImageList_ReplaceIcon
ImageList_Merge

Drawing Images

ImageList_Draw
ImageList_DrawEx
ImageList_ExtractIcon
ImageList_GetBkColor
ImageList_GetIcon
ImageList_SetBkColor
INDEXTOOVERLAYMASK

Dragging Images

ImageList_BeginDrag
ImageList_DragEnter
ImageList_DragLeave
ImageList_DragMove
ImageList_DragShowNolock
ImageList_EndDrag
ImageList_GetDragImage
ImageList_SetDragCursorImage
ImageList_SetOverlayImage

Image Information

ImageList_GetIconSize
ImageList_GetImageCount
ImageList_GetImageInfo
ImageList_SetIconSize
IMAGEINFO

Storing Image Lists

ImageList_Read
ImageList_Write


 Image List Functions

The following functions are used with image lists.

ImageList_Add
ImageList_AddMasked
ImageList_BeginDrag
ImageList_Create
ImageList_Destroy
ImageList_DragEnter
ImageList_DragLeave
ImageList_DragMove
ImageList_DragShowNolock
ImageList_Draw
ImageList_DrawEx
ImageList_EndDrag
ImageList_ExtractIcon
ImageList_GetBkColor
ImageList_GetDragImage
ImageList_GetIcon
ImageList_GetIconSize
ImageList_GetImageCount
ImageList_GetImageInfo
ImageList_LoadBitmap
ImageList_LoadImage
ImageList_Merge
ImageList_Read
ImageList_Remove
ImageList_Replace
ImageList_ReplaceIcon
ImageList_SetBkColor
ImageList_SetDragCursorImage
ImageList_SetIconSize
ImageList_SetOverlayImage
ImageList_Write


 Image List Macro

The following macros are used with image lists.

ImageList_AddIcon
INDEXTOOVERLAYMASK


 Image List Structure

The following structure is used with image lists.

IMAGEINFO


 List View Controls

A list view control is a window that displays a collection of items, each item consisting of an icon and a label. List view controls provide several ways of arranging items and displaying individual items. For example, additional information about each item can be displayed in columns to the right of the icon and label.


 About List View Controls

You can create a list view control by calling the CreateWindowEx function, specifying the WC_LISTVIEW window class. This window class is registered when the common controls dynamic-link library (DLL) is loaded. To ensure that this DLL is loaded, use the InitCommonControls function.

An application sends messages to a list view control to add, remove, arrange, and otherwise manipulate items. Each message has a macro that you can use instead of sending the message explicitly.

Like most common controls, a list view control sends notification messages to its parent window in the form of WM_NOTIFY messages. For more information about common controls, see Common Controls.


 Views and Styles

List view controls can display their contents in four different views. The current view is specified by the control's window style. Additional window styles specify the alignment of items and control-specific functionality of the list view control. Information about the four views follows.

View	Description
Icon view	Specified by the LVS_ICON window style. Each item appears as a full-sized icon with a label below it. The user can drag the items to any location in the list view window.
Small icon view	Specified by the LVS_SMALLICON window style. Each item appears as a small icon with the label to the right of it. The user can drag the items to any location.
List view	Specified by the LVS_LIST window style. Each item appears as a small icon with a label to the right of it. Items are arranged in columns and cannot be dragged to any arbitrary location by the user.
Report view	Specified by the LVS_REPORT window style. Each item appears on its own line with information arranged in columns. The leftmost column contains the small icon and label, and subsequent columns contain subitems as specified by the application. Unless the LVS_NOCOLUMNHEADER window style is also specified, each column has a header.
You can change the view type after a list view control is created. To retrieve and change the window style, use the GetWindowLong and SetWindowLong functions. To determine the window styles that correspond to the current view, use the LVS_TYPEMASK value.

You can control the way items are arranged in icon or small icon view by specifying either the LVS_ALIGNTOP (default) or LVS_ALIGNLEFT window style. You can change the alignment after a list view control is created. To isolate the window styles that specify the alignment of items, use the LVS_ALIGNMASK value.

Additional window styles control other options — for example, whether a user can edit labels in place, whether more than one item can be selected at a time, and so on.


 List View Image Lists

The icons for list view items are contained in image lists, which you create and assign to the list view control. One image list contains the full-sized icons used in icon view, and a separate image list contains smaller versions of the same icons for use in other views. You can also specify a third image list that contains state images, which are displayed next to an item's icon to indicate an application-defined state.

You assign an image list to a list view control by using the LVM_SETIMAGELIST message, specifying whether the image list contains full-sized icons, small icons, or state images. You can use the GetSystemMetrics function to determine appropriate dimensions for the full-sized and small icons and the ImageList_Create function to create the image lists. For more information about image lists, see Image Lists.

You can retrieve the handle of an image list currently assigned to a list view control by using the LVM_GETIMAGELIST message.

The full-sized and small icon image lists typically contain icons for each type of list view item. You do not need to create both of these image lists if only one is used — for example, if a list view control is never in icon view. If you create both image lists, they must contain the same images in the same order because a single value is used to identify a list view item's icon in both image lists.

The full-sized and small icon image lists can also contain overlay images, which are designed to be superimposed on item icons. A nonzero value in bits 8 through 11 of a list view item's state specifies the one-based index of an overlay image (zero indicates no overlay image). Because a 4-bit, one-based index is used, overlay images must be among the first 15 images in the image lists. For more information about list view item states, see Item States.

If a state image list is specified, a list view control reserves space to the left of each item's icon for a state image. An application can use state images, such as checked and cleared check boxes, to indicate application-defined item states. A nonzero value in bits 12 through 15 specifies the one-based index of a state image (zero indicates no state image). State images are typically not used in icon view.

By default, a list view control destroys the image lists assigned to it when it is destroyed. However, if a list view control has the LVS_SHAREIMAGELISTS window style, the application is responsible for destroying the image lists when they are no longer in use. You should specify this style if you assign the same image lists to multiple list view controls; otherwise, more than one control might try to destroy the same image list.


 Items and Subitems

Each item in a list view control consists of an icon, a label, a current state, and an application-defined value. One or more subitems can also be associated with each item. A subitem is a string that, in report view, can be displayed in a column to the right of an item's icon and label. All items in a list view control have the same number of subitems. By using list view messages, you can add, modify, retrieve information about, and delete items. You can also find items with specific attributes.

The LV_ITEM structure defines a list view item or subitem. The iItem member is the zero-based index of the item. The iSubItem member is the one-based index of a subitem or zero if the structure contains information about an item. Additional members specify the item's text, icon, state, and item data. Item data is an application-defined value associated with a list view item.

To add an item to a list view control, use the LVM_INSERTITEM message, specifying the address of an LV_ITEM structure. Before adding multiple items, you can send the control an LVM_SETITEMCOUNT message, specifying the number of items the control will ultimately contain. This message enables the list view control to reallocate its internal data structures only once rather than every time you add an item. You can determine the number of items in a list view control by using the LVM_GETITEMCOUNT message.

To change the attributes of a list view item, use the LVM_SETITEM message, specifying the address of an LV_ITEM structure. The mask member of this structure specifies the item attributes you want to change. To change only the text of an item or subitem, use the LVM_SETITEMTEXT message.

To retrieve information about a list view item, use the LVM_GETITEM message, specifying the address of the LV_ITEM structure to fill in. The mask member of this structure specifies the item attributes to be retrieved. To retrieve only an item or subitem's text, use the LVM_GETITEMTEXT message.

To delete a list view item, use the LVM_DELETEITEM message. You can delete all items in a list view control by using the LVM_DELETEALLITEMS message.


 Item States

An item's state is a value that specifies the item's availablility, indicates user actions, or otherwise reflects the item's status. A list view control changes some state bits, such as when the user selects an item. An application might change other state bits to disable or hide the item or to specify an overlay image or state image. For more information about overlay images and state images, see List View Image Lists.

An item's state is specified by the state member of the LV_ITEM structure. When you specify or change an item's state, the stateMask member specifies which state bits you want to change. You can change an item's state by using the LVM_SETITEMSTATE message. You can specify an item's state when you create it or when you change its attributes by using the LMV_SETITEM message. To determine an item's current state, use the LVM_GETITEMSTATE or LVM_GETITEM message.

To set an item's overlay image, the stateMask member of the LV_ITEM structure must include the LVIS_OVERLAYMASK value, and the state member must include the one-based index of the overlay image shifted left 8 bits by using the INDEXTOOVERLAYMASK macro. The index can be zero to specify no overlay image.

To set an item's state image, the stateMask member of the LV_ITEM structure must include the LVIS_STATEIMAGEMASK value, and the state member must include the one-based index of the state image shifted left 12 bits by using the INDEXTOSTATEIMAGEMASK macro. The index can be zero to specify no state image.


 Callback Items and the Callback Mask

A callback item is a list view item for which the application — rather than the control — stores the text, icon, or both. Although a list view control can store these attributes for you, you may want to use callback items if your application already maintains some of this information. The callback mask specifies which item state bits are maintained by the application, and it applies to the whole control rather than to a specific item. The callback mask is zero by default, meaning that the list view control tracks all item states. If an application uses callback items or specifies a nonzero callback mask, it must be able to supply list view item attributes on demand.

A list view control requests any information that it needs to display an item by sending its owner window an LVN_GETDISPINFO notification message. The specified LV_DISPINFO structure identifies the item or subitem and indicates which attributes the application must supply. If item attributes or state bits that are maintained by the application change, the list view control sends its owner window an LVN_SETDISPINFO notification message. This notification enables the application to update its information.

If you change a callback item's attributes, you can use the LVM_UPDATE message to force the control to repaint the item. This message also arranges the list view control if it has the LVS_AUTOARRANGE style. You can use the LVM_REDRAWITEMS message to redraw a range of items by invaliding the corresponding portions of the list view control's client area.

You can define a callback item by specifying appropriate values for the pszText and iImage members of the LV_ITEM structure. If the application maintains the item's or subitem's text, you should specify the LPSTR_TEXTCALLBACK value for the pszText member. If the application keeps track of the icon for the item, you should specify the I_IMAGECALLBACK value for the iImage member.

To set the callback mask for a list view control, use the LVM_SETCALLBACKMASK message. A one bit in the callback mask means the application maintains the corresponding state bit for each list view item. To get the current callback mask, use the LVM_GETCALLBACKMASK message.

By effectively using callback items and the callback mask, you can ensure that each item attribute is maintained in only one place. Doing this can simplify your application, but the only space saved is the memory that would otherwise be required to store item labels and subitem text.


 Columns

Columns control the way items and their subitems are displayed in report view. Each column has a title and width and is associated with a specific subitem (subitem zero is the item's icon and label). The attributes of a column are defined by an LV_COLUMN structure.

To add a column to a list view control, use the LVM_INSERTCOLUMN message. To delete a column, use the LVM_DELETECOLUMN message. You can retrieve and change the properties of an existing column by using the LVM_GETCOLUMN and LVM_SETCOLUMN messages.

To retrieve or change a column's width, use the LVM_GETCOLUMNWIDTH and LVM_SETCOLUMNWIDTH messages. You can determine the minimum column width necessary to display all of a string by using the LVM_GETSTRINGWIDTH message.

Unless the LVS_NOCOLUMNHEADER window style is specified, column headers appear in report view. The user can click a column header, causing an LVN_COLUMNCLICK notification message to be sent to the parent window. Typically, the parent window sorts the list view control by the specified column when this clicking occurs. The user can also drag the column guides between the headers to size the columns.


 Arranging, Sorting, and Finding

You can use list view messages to arrange and sort items and to find items based on their attributes or positions. Arranging repositions items to align on a grid, but the indexes of the items do not change. Sorting changes the sequence of items (and their corresponding indexes) and then repositions them accordingly. You can arrange items only in icon and small icon views, but you can sort items in any view.

To arrange items, use the LVM_ARRANGE message. You can ensure that items are arranged at all times by specifying the LVS_AUTOARRANGE window style.

To sort items, use the LVM_SORTITEMS message. When you sort using this message, you specify an application-defined callback function that is called to compare the relative order of any two items. By supplying an appropriate comparison function, you can sort items by their label, by any subitem, or by any other property. Note that sorting items does not reorder the corresponding subitems. Thus, if any subitems are not callback items, you must regenerate the subitems after sorting.

You can ensure that a list view control is always sorted by specifying the LVS_SORTASCENDING or LVS_SORTDESCENDING window style. You cannot supply a comparison function when using these window styles. The list view sorts the items in ascending or descending order by label.

You can find a list view item with specific properties by using the LVM_FINDITEM message. You can find a list view item that is in a specified state and bears a specified geometrical relationship to a given item by using the LVM_GETNEXTITEM message. For example, you can retrieve the next selected item to the right of a specified item.


 List View Item Position

Every list view item has a position and size, which you can retrieve and set using messages. You can also determine which item, if any, is at a specified position. The position of list view items is specified in view coordinates, which are client coordinates offset by the scroll position.

To retrieve and set an item's position, use the LVM_GETITEMPOSITION and LVM_SETITEMPOSITION messages. LVM_GETITEMPOSITION works for all views, but LVM_SETITEMPOSITION works only for icon and small icon views.

You can determine which item, if any, is at a particular location by using the LVM_HITTEST message.

To get the bounding rectangle for a list item or for only its icon or label, use the LVM_GETITEMRECT message.


 Scroll Position

Unless the LVS_NOSCROLL window style is specified, a list view control can be scrolled to show more items than can fit in the client area of the control. You can get a list view control's scroll position and related information, scroll a list view control by a specified amount, or scroll a list view control such that a specified list item is visible.

In icon view or small icon view, the current scroll position is defined by the view origin. The view origin is the set of coordinates, relative to the visible area of the list view control, that correspond to the view coordinates (0, 0). To get the current view origin, use the LVM_GETORIGIN message. This message should be used only in icon or small icon view; it returns an error in list or report view.

In list or report view, the current scroll position is defined by the top index. The top index is the index of the first visible item in the list view control. To get the current top index, use the LVM_GETTOPINDEX message. This message returns a valid result only in list or report view; it returns zero in icon or small icon view.

You can use the LVM_GETVIEWRECT message to get the bounding rectangle of all items in a list view control, relative to the visible area of the control.

The LVM_GETCOUNTPERPAGE message returns the number of items that fit in one page of the list view control. This message returns a valid result only in list and report views; in icon and small icon views, it returns the total number of items.

To scroll a list view control by a specific amount, use the LVM_SCROLL message. Using the LVM_ENSUREVISIBLE message, you can scroll the list view control, if necessary, to ensure that a specified item is visible.


 Label Editing

A list view control that has the LVS_EDITLABELS window style enables a user to edit item labels in place. The user begins editing by clicking the label of an item that has the focus. An application can begin editing automatically by using the LVM_EDITLABEL message. The list view control notifies the parent window when editing begins and when it is canceled or completed. When editing is completed, the parent window is responsible for updating the item's label, if appropriate.

When label editing begins, a list view control sends its parent window an LVN_BEGINLABELEDIT notification message. You can process this message to allow selective editing of specific labels; returning a nonzero value prevents label editing.

When label editing is canceled or completed, a list view control sends its parent window an LVN_ENDLABELEDIT notification message. The lParam parameter is the address of an LV_DISPINFO structure identifying the item and specifying the edited text. The parent window is responsible for updating the item's label, if appropriate, perhaps after validating the edited string. If editing is canceled, the iItem member is  − 1.

During label editing, you can get the handle of the edit control used for label editing by using the LVM_GETEDITCONTROL message. To limit the amount of text a user can enter, you can send the edit control an EM_LIMITTEXT message. You can even subclass the edit control to intercept and discard invalid characters. The edit control is created after the LVN_BEGINLABELEDIT notification message is sent.


 List View Colors

An application can retrieve and set three colors for a list view control. To retrieve and set the text color, use the LVM_GETTEXTCOLOR and LVM_SETTEXTCOLOR messages. To retrieve and set the text background color, use the LVM_GETTEXTBKCOLOR and LVM_SETTEXTBKCOLOR messages. To retrieve and set the window background color, use the LVM_GETBKCOLOR and LVM_SETBKCOLOR messages.


 List View Notification Messages

A list view control sends notification messages to its parent window in the form of WM_NOTIFY messages. The following notification messages are sent by a list view control.

Notification message	Description
LVN_BEGINDRAG	Signals the start of a drag and drop operation.
LVN_BEGINLABELEDIT	Signals the start of in-place label editing.
LVN_BEGINRDRAG	Signals the start of a drag and drop operation, using the right mouse button.
LVN_COLUMNCLICK	Indicates that the user clicked a column header in report view.
LVN_DELETEALLITEMS	Signals the deletion of all list view items.
LVN_DELETEITEM	Signals the deletion of a specific item.
LVN_ENDLABELEDIT	Signals the end of label editing.
LVN_GETDISPINFO	Requests information that the list view control requires to display an item.
LVN_INSERTITEM	Signals the insertion of a new list view item.
LVN_ITEMCHANGED	Indicates that an item has changed.
LVN_ITEMCHANGING	Indicates that an item is in the process of changing and enables the parent window to accept or deny the change.
LVN_KEYDOWN	Signals a keyboard event.
LVN_SETDISPINFO	Notifies a parent window that it must update the information it maintains for an item.


 Default List View Message Processing

This section describes the window message processing performed by a list view control. Messages specific to list view controls are discussed elsewhere and are, therefore, not included here.

Message	Processing performed
WM_CHAR	Searches for a list view item that begins with the specified character and, if the item is found, selects and sets the focus to the item. Multiple characters received within a time-out interval are concatenated, and the list view control searches for an item that begins with the resulting string.
WM_COMMAND	Processes the EN_UPDATE and EN_KILLFOCUS notification messages and forwards all other edit control notifications to the parent window.
WM_CREATE	Performs additional initialization. If the LVS_SHAREIMAGELISTS window style is not specified, the list view control creates the icon and small icon image lists at this point.
WM_DESTROY	Frees resources.
WM_ERASEBKGND	Erases the window background using the current background color for the list view control. If the background color is the CLR_NONE value, the list view control forwards the message to the parent window.
WM_GETDLGCODE	Returns a combination of the DLGC_WANTTAB and DLGC_WANTARROWS values.
WM_GETFONT	Returns the handle of the current label font.
WM_HSCROLL	Scrolls the list view control horizontally.
WM_KEYDOWN	Processes the SPACEBAR, ENTER, and arrow keys and sends a LVN_KEYDOWN notification message to the parent window.
WM_KILLFOCUS	Repaints the focused list item, if any, and sends a NM_KILLFOCUS notification message to the parent window.
WM_LBUTTONDBLCLK	Sends the parent window an NM_DBLCLK notification message.
WM_LBUTTONDOWN	Processed in different ways depending on whether a click or drag operation is being initiated. To determine which operation is involved, the list view control enters a modal message loop until either the button is released or the mouse is moved. In the case of a click, the list view control may change which item has the focus and which items are selected, taking into account the cursor position, the state of the SHIFT and CTRL keys, and so on. Then the list view control sends its parent window an NM_CLICK notification message. If dragging begins over an item, the list view control selects and sets the focus to the item. Then it sends an LVN_BEGINDRAG notification message to the parent window. The parent window is responsible for actually carrying out the drag operation. If dragging begins over the window background, the list view control enters another modal message loop, enabling the user to form a rectangle by dragging the mouse. Items within the rectangle are selected.
WM_NCCREATE	Allocates and initializes an internal data structure and then calls the DefWindowProc function.
WM_NCDESTROY	Frees resources allocated by the list view control. Unless the LVS_SHAREIMAGELISTS style is used, this includes deleting the full-sized and small image lists.
WM_NOTIFY	Processes header control notification messages.
WM_PAINT	Displays any items in the update region. For callback items, the control first sends an LVN_GETDISPINFO notification message to the owner window to request display information.
WM_RBUTTONDOWN	Processed the same way as the WM_LBUTTONDOWN message, except that the control sends an NM_RCLICK notification message (instead of NM_CLICK) and an LVN_BEGINRDRAG notification message (instead of LVN_BEGINDRAG).
WM_SETFOCUS	Repaints the focused list item, if any, and sends an NM_SETFOCUS notification message to the parent window.
WM_SETFONT	Saves the specified font handle, forwards the message to the header window, if any, and repaints using the new font.
WM_SETREDRAW	Turns redrawing on or off.
WM_TIMER	Begins editing of an item label. If the user clicks the label of the focused item, the list view control sets a timer instead of entering edit mode immediately. The timer makes it possible for the list view control to not enter edit mode if the user double-clicks the label.
WM_VSCROLL	Scrolls the list view control vertically.
WM_WINDOWPOSCHANGED	Updates the window scroll bars. If the current view is icon or small icon view and the LVS_AUTOARRANGE style is specified, the list view control also arranges the list items.
WM_WININICHANGE	Processes changes to system metrics.


 Using List View Controls

•	Creating a list view control

•	Initializing the image lists for a list view control

•	Adding columns to a list view control

•	Adding items to a list view control

•	Processing the WM_NOTIFY message

•	Changing list view styles


 Creating a List View Control

To create a list view control, use the CreateWindowEx function, specifying the WC_LISTVIEW window class. The list view window class is registered in the application's address space when the common controls dynamic-link library (DLL) is loaded. To ensure that the DLL is loaded, use the InitCommonControls function.

The following example creates a list view control and then calls application-defined functions that add image lists, columns, and list view items. The window style specifies the list view control's initial view and other options. This example specifies report view, which enables the user to edit the labels of list view items.

// CreateListView - creates a list view control.

// Returns the handle of the new control if successful or NULL

//     otherwise.

// hwndParent - handle of the control's parent window

// pfData - file containing list view items

HWND WINAPI CreateListView(HWND hwndParent, FILE *pfData)

{

    HWND hwndLV;

    // Force the common controls DLL to be loaded.

    InitCommonControls();

    // Create the list view window.

    hwndLV = CreateWindow(WC_LISTVIEW, "",

        WS_CHILD | LVS_REPORT | LVS_EDITLABELS,

        0, 0, CW_USEDEFAULT, CW_USEDEFAULT,

        hwndParent, NULL, g_hinst, NULL);

    if (hwndLV == NULL)

        return NULL;

    // Call application-defined functions to initialize the

    // image lists, add columns, and add some items.

    if (!InitListViewImageLists(hwndLV) ||

            !InitListViewColumns(hwndLV) ||

            !InitListViewItems(hwndLV, pfData)) {

        DestroyWindow(hwndLV);

        return FALSE;

    }

    return hwndLV;              // return the control's handle

}


 Initializing the Image Lists for a List View Control

A list view control can have up to three image lists associated with it: one for item icons in icon view, one for item icons in other views, and one for application-defined item states. The following example creates two image lists, adds an icon to each, and assigns them to a list view control by using the LVM_SETIMAGELIST message.

// InitListViewImageList - creates image lists for a list view.

// Returns TRUE if successful or FALSE otherwise.

// hwndLV - handle of the list view control

BOOL WINAPI InitListViewImageLists(HWND hwndLV)

{

    HICON hiconItem;        // icon for list view items

    HIMAGELIST himlLarge;   // image list for icon view

    HIMAGELIST himlSmall;   // image list for other views

    // Create the full-sized and small icon image lists.

    himlLarge = ImageList_Create(GetSystemMetrics(SM_CXICON),

        GetSystemMetrics(SM_CYICON), TRUE, 1, 1);

    himlSmall = ImageList_Create(GetSystemMetrics(SM_CXSMICON),

        GetSystemMetrics(SM_CYSMICON), TRUE, 1, 1);

    // Add an icon to each image list.

    hiconItem = LoadIcon(g_hinst, MAKEINTRESOURCE(IDI_ITEM));

    ImageList_AddIcon(himlLarge, hiconItem);

    ImageList_AddIcon(himlSmall, hiconItem);

    DeleteObject(hiconItem);

    // Assign the image lists to the list view control.

    ListView_SetImageList(hwndLV, himlLarge, LVSIL_NORMAL);

    ListView_SetImageList(hwndLV, himlSmall, LVSIL_SMALL);

    return TRUE;

}


 Adding Columns to a List View Control

Columns appear only in report view, and they enable multiple pieces of information to be displayed for each list item. You can add columns to a list view control by using the LVM_INSERTCOLUMN message. Each item in a list view control can have, in addition to its item text, any number of strings called subitems. When you add a column to a list view control, you specify which subitem to display in the column.

Unless a list view control has the LVS_NOCOLUMNHEADER window style, each column has a header showing the column name. The user can click the header and can size the columns using the header.

The following example adds several columns to a list view control. The column headings are defined as string resources, which are consecutively numbered starting with IDS_FIRSTCOLUMN (defined in the application's header file). The number of columns is defined in the application's header file as C_COLUMNS.

// InitListViewColumns - adds columns to a list view control.

// Returns TRUE if successful or FALSE otherwise.

// hwndLV - handle of the list view control

BOOL WINAPI InitListViewColumns(HWND hwndLV)

{

    extern char g_achTemp[256];     // temporary buffer

    LV_COLUMN lvc;

    int iCol;

    // Initialize the LV_COLUMN structure.

    lvc.mask = LVCF_FMT | LVCF_WIDTH | LVCF_TEXT | LVCF_SUBITEM;

    lvc.fmt = LVCFMT_LEFT;

    lvc.cx = 100;

    lvc.pszText = g_achTemp;

    // Add the columns.

    for (iCol = 0; iCol < C_COLUMNS; iCol++) {

        lvc.iSubItem = iCol;

        LoadString(g_hinst, IDS_FIRSTCOLUMN + iCol,

                g_achTemp, sizeof(g_achTemp));

        if (ListView_InsertColumn(hwndLV, iCol, &lvc) == -1)

            return FALSE;

    }

    return TRUE;

}


 Adding Items to a List View Control

An application can add items to a list view control by using the LVM_INSERTITEM message. The attributes of a list view item that are specified by an LV_ITEM structure include a state, a label, an icon, and item data. Associated with each item may be one or more subitems, which are strings that appear to the right of an item in report view.

The example in this section adds a list view item for each line in a text file. Semicolons are assumed to separate the item label and the subitem strings that follow it. The example saves each item's label and subitem strings in a structure, which is defined in the application's header file, as follows.

#define C_COLUMNS 6

typedef struct myitem_tag {

    LPSTR aCols[C_COLUMNS];

} MYITEM;

The application fills in an LV_ITEM structure and adds a list view item by using the LVM_INSERTITEM message. Because the application saves the item label in its own application-defined MYITEM structure, it specifies the LPSTR_TEXTCALLBACK value for the pszText member of the LV_ITEM structure. Specifying this value causes the control to send an LVN_GETDISPINFO notification message to its owner window whenever it needs to display the item. The address of the application-defined structure is saved as item data.

// InitListViewItems - adds items and subitems to a list view.

// Returns TRUE if successful or FALSE otherwise.

// hwndLV - handle of the list view control

// pfData - text file containing list view items with columns

//          separated by semicolons

BOOL WINAPI InitListViewItems(HWND hwndLV, FILE *pfData)

{

    extern char g_achTemp[256];         // temporary buffer

    PSTR pszStart;

    PSTR pszEnd;

    int iItem;

    int iSubItem;

    LV_ITEM lvi;

    // Initialize LV_ITEM members that are common to all items.

    lvi.mask = LVIF_TEXT | LVIF_IMAGE | LVIF_PARAM | LVIF_STATE;

    lvi.state = 0;

    lvi.stateMask = 0;

    lvi.pszText = LPSTR_TEXTCALLBACK;   // app. maintains text

    lvi.iImage = 0;                     // image list index

    // Read each line in the specified file.

    for (iItem = 0;

            fgets(g_achTemp, sizeof(g_achTemp), pfData);

            iItem++) {

        // Allocate an application-defined structure to store the

        // item label and the text of each subitem.

        MYITEM *pItem = LocalAlloc(LPTR, sizeof(MYITEM));

        // Copy the first string (the label).

        pszEnd = strchr(g_achTemp, ';');

        *pszEnd = '\0';

        pItem->aCols[0] = DupString(g_achTemp);

        // Copy subsequent strings (subitems).

        for (iSubItem = 1;

                iSubItem < C_COLUMNS && pszEnd != NULL;

                iSubItem++) {

            pszStart = pszEnd + 1;

            if ((pszEnd = strchr(pszStart, ';')) != NULL)

                *pszEnd = '\0';

            pItem->aCols[iSubItem] = DupString(pszStart);

        }

        // Initialize item-specific LV_ITEM members.

        lvi.iItem = iItem;

        lvi.iSubItem = 0;

        lvi.lParam = (LPARAM) pItem;    // item data

        // Add the item.

        ListView_InsertItem(hwndLV, &lvi);

        // There is no need to set the text of the subitems. They

        // default to LPSTR_TEXTCALLBACK.

    }

    return TRUE;

}

// DupString - allocates a copy of a string.

// lpsz - address of the null-terminated string to copy

LPSTR DupString(LPSTR lpsz)

{

    int cb = lstrlen(lpsz) + 1;

    LPSTR lpszNew = LocalAlloc(LMEM_FIXED, cb);

    if (lpszNew != NULL)

        CopyMemory(lpszNew, lpsz, cb);

    return lpszNew;

}


 Processing the WM_NOTIFY Message

A list view control notifies its parent window of events by sending a WM_NOTIFY message. The wParam parameter is the identifier of the list view control, and the lParam parameter is the address of an NMHDR structure (or to a larger structure that has an NMHDR structure as its first member). The example in this section processes the LVN_GETDISPINFO, LVN_ENDLABELEDIT, and LVN_COLUMNCLICK notification messages.

A list view control sends the LVN_GETDISPINFO notification message to retrieve information about an item or subitem from the parent window. This notification is sent, for example, when an item with the LPSTR_TEXTCALLBACK value needs to be displayed.

A list view control sends the LVN_ENDLABELEDIT notification message when the user completes or cancels editing of an item's label. This notification is only sent if the list view control has the LVS_EDITLABELS window style. If editing is being canceled, the parent window typically does nothing. If editing is being completed, the parent window should set the item label to the new text, unless the item label is LPSTR_TEXTCALLBACK. In that case, the parent window should simply update the application-defined data it maintains for the list item.

If the user clicks a column header in report view, a list view control sends the LVN_COLUMNCLICK notification message. Typically, an application sorts a list view by the specified column when this clicking occurs. To sort, use the LVM_SORTITEMS message, specifying an application-defined comparison function.

The following example shows the portion of the application's window procedure that processes the WM_NOTIFY message.

case WM_NOTIFY:

    // Branch depending on the specific notification message.

    switch (((LPNMHDR) lParam)->code) {

        // Process LVN_GETDISPINFO to supply information about

        // callback items.

        case LVN_GETDISPINFO:

            Main_OnGetDispInfo((LV_DISPINFO *) lParam);

            break;

        // Process LVN_ENDLABELEDIT to change item labels after

        // in-place editing.

        case LVN_ENDLABELEDIT:

            return Main_OnEndLabelEdit(

                (LV_DISPINFO *) lParam

                );

        // Process LVN_COLUMNCLICK to sort items by column.

        case LVN_COLUMNCLICK:

            #define pnm ((NM_LISTVIEW *) lParam)

            ListView_SortItems(

                pnm->hdr.hwndFrom,

                ListViewCompareFunc,

                (LPARAM) (pnm->iSubItem)

                );

            #undef pnm

            break;

    }

    break;

The following example shows the application-defined functions that the window procedure uses to process list view notification messages.

// Main_OnGetDispInfo - processes the LVN_GETDISPINFO

//     notification message.

// pnmv - value of lParam (points to an LV_DISPINFO structure)

VOID WINAPI Main_OnGetDispInfo(LV_DISPINFO *pnmv)

{

    // Provide the item or subitem's text, if requested.

    if (pnmv->item.mask & LVIF_TEXT) {

        MYITEM *pItem = (MYITEM *) (pnmv->item.lParam);

        lstrcpy(pnmv->item.pszText,

                pItem->aCols[pnmv->item.iSubItem]);

    }

}

// Main_OnEndLabelEdit - processes the LVN_ENDLABELEDIT

//     notification message.

// Returns TRUE if the label is changed or FALSE otherwise.

// pnmv - value of lParam (points to an LV_DISPINFO structure)

BOOL Main_OnEndLabelEdit(LV_DISPINFO *pnmv)

{

    MYITEM *pItem;

    // The item is -1 if editing is being canceled.

    if (pnmv->item.iItem == -1)

        return FALSE;

    // Copy the new text to the application-defined structure,

    // a pointer to which is saved as item data.

    pItem = (MYITEM *) (pnmv->item.lParam);

    pItem->aCols[0] = (PSTR) LocalReAlloc(

        (HLOCAL) (pItem->aCols[0]),

        lstrlen(pnmv->item.pszText) + 1,

        LMEM_MOVEABLE

        );

    lstrcpy(pItem->aCols[0], pnmv->item.pszText);

    // No need to set the item text, because it is a callback item.

    return TRUE;

}

// ListViewCompareFunc - sorts the list view control. It is a

//     comparison function.

// Returns a negative value if the first item should precede the

//     second item, a positive value if the first item should

//     follow the second item, and zero if the items are equivalent.

// lParam1 and lParam2 - item data for the two items (in this

//     case, pointers to application-defined MYITEM structures)

// lParamSort - value specified by the LVM_SORTITEMS message

//     (in this case, the index of the column to sort)

int CALLBACK ListViewCompareFunc(

    LPARAM lParam1,

    LPARAM lParam2,

    LPARAM lParamSort)

{

    MYITEM *pItem1 = (MYITEM *) lParam1;

    MYITEM *pItem2 = (MYITEM *) lParam2;

    // Compare the specified column.

    int iCmp = lstrcmpi(pItem1->aCols[lParamSort],

        pItem2->aCols[lParamSort]);

    // Return the result if nonzero, or compare the

    // first column otherwise.

    return (iCmp != 0) ? iCmp :

        lstrcmpi(pItem1->aCols[0], pItem2->aCols[0]);

}


 Changing List View Styles

An application can change the window style of a list view control after it is created by using the GetWindowLong and SetWindowLong functions. The following example changes the style bits that govern the view mode.

// SetView - sets a list view's window style to change the view.

// hwndLV - handle of the list view control

// dwView - value specifying a view style

VOID WINAPI SetView(HWND hwndLV, DWORD dwView)

{

    // Get the current window style.

    DWORD dwStyle = GetWindowLong(hwndLV, GWL_STYLE);

    // Only set the window style if the view bits have changed.

    if ((dwStyle & LVS_TYPEMASK) != dwView)

        SetWindowLong(hwndLV, GWL_STYLE,

            (dwStyle & ~LVS_TYPEMASK) | dwView);

}


 List View Control Reference

The following messages, notification messages, and structures are associated with list view controls. These elements can be grouped, as follows.

Items and Subitems

LV_ITEM
LVM_DELETEALLITEMS
LVM_DELETEITEM
LVM_GETITEM
LVM_GETITEMCOUNT
LVM_GETITEMSPACING
LVM_GETITEMSTATE
LVM_GETITEMTEXT
LVM_GETSELECTEDCOUNT
LVM_INSERTITEM
LVM_SETITEM
LVM_SETITEMCOUNT
LVM_SETITEMSTATE
LVM_SETITEMTEXT

Callback Items

LV_DISPINFO
LVM_GETCALLBACKMASK
LVM_REDRAWITEMS
LVM_SETCALLBACKMASK
LVM_UPDATE
LVN_GETDISPINFO
LVN_SETDISPINFO

Columns

LV_COLUMN
LVM_DELETECOLUMN
LVM_GETCOLUMN
LVM_GETCOLUMNWIDTH
LVM_GETSTRINGWIDTH
LVM_INSERTCOLUMN
LVM_SETCOLUMN
LVM_SETCOLUMNWIDTH
LVN_COLUMNCLICK

Arranging, Sorting, and Finding

LV_FINDINFO
LVM_ARRANGE
LVM_FINDITEM
LVM_GETNEXTITEM
LVM_SORTITEMS

Item Positions and Scrolling

LV_HITTESTINFO
LVM_ENSUREVISIBLE
LVM_GETCOUNTPERPAGE
LVM_GETITEMPOSITION
LVM_GETITEMRECT
LVM_GETORIGIN
LVM_GETTOPINDEX
LVM_GETVIEWRECT
LVM_HITTEST
LVM_SCROLL
LVM_SETITEMPOSITION
LVM_SETITEMPOSITION32

Colors

LVM_GETBKCOLOR
LVM_GETTEXTBKCOLOR
LVM_GETTEXTCOLOR
LVM_SETBKCOLOR
LVM_SETTEXTBKCOLOR
LVM_SETTEXTCOLOR

Miscellaneous

LV_KEYDOWN
LVM_CREATEDRAGIMAGE
LVM_EDITLABEL
LVM_GETEDITCONTROL
LVM_GETIMAGELIST
LVM_SETIMAGELIST
LVN_BEGINDRAG
LVN_BEGINLABELEDIT
LVN_BEGINRDRAG
LVN_DELETEALLITEMS
LVN_DELETEITEM
LVN_ENDLABELEDIT
LVN_INSERTITEM
LVN_ITEMCHANGED
LVN_ITEMCHANGING
LVN_KEYDOWN
LVN_PEN
NM_LISTVIEW


 List View Control Messages

An application sends messages to a list view control to alter its appearance, add or change items and columns, and so on. Each message has a corresponding macro, which you can use instead of sending the message explicitly.

LVM_ARRANGE
LVM_CREATEDRAGIMAGE
LVM_DELETEALLITEMS
LVM_DELETECOLUMN
LVM_DELETEITEM
LVM_EDITLABEL
LVM_ENSUREVISIBLE
LVM_FINDITEM
LVM_GETBKCOLOR
LVM_GETCALLBACKMASK
LVM_GETCOLUMN
LVM_GETCOLUMNWIDTH
LVM_GETCOUNTPERPAGE
LVM_GETEDITCONTROL
LVM_GETIMAGELIST
LVM_GETISEARCHSTRING
LVM_GETITEM
LVM_GETITEMCOUNT
LVM_GETITEMPOSITION
LVM_GETITEMRECT
LVM_GETITEMSPACING
LVM_GETITEMSTATE
LVM_GETITEMTEXT
LVM_GETNEXTITEM
LVM_GETORIGIN
LVM_GETSELECTEDCOUNT
LVM_GETSTRINGWIDTH
LVM_GETTEXTBKCOLOR
LVM_GETTEXTCOLOR
LVM_GETTOPINDEX
LVM_GETVIEWRECT
LVM_HITTEST
LVM_INSERTCOLUMN
LVM_INSERTITEM
LVM_REDRAWITEMS
LVM_SCROLL
LVM_SETBKCOLOR
LVM_SETCALLBACKMASK
LVM_SETCOLUMN
LVM_SETCOLUMNWIDTH
LVM_SETIMAGELIST
LVM_SETITEM
LVM_SETITEMCOUNT
LVM_SETITEMPOSITION
LVM_SETITEMPOSITION32
LVM_SETITEMSTATE
LVM_SETITEMTEXT
LVM_SETTEXTBKCOLOR
LVM_SETTEXTCOLOR
LVM_SORTITEMS
LVM_UPDATE


 List View Control Notification Messages

A list view control sends notification messages to its owner window when events occur in the control.

LVN_BEGINDRAG
LVN_BEGINLABELEDIT
LVN_BEGINRDRAG
LVN_COLUMNCLICK
LVN_DELETEALLITEMS
LVN_DELETEITEM
LVN_ENDLABELEDIT
LVN_GETDISPINFO
LVN_INSERTITEM
LVN_ITEMCHANGED
LVN_ITEMCHANGING
LVN_KEYDOWN
LVN_PEN
LVN_SETDISPINFO


 List View Control Structures

The following structures are used with list view controls.

LV_COLUMN
LV_DISPINFO
LV_FINDINFO
LV_HITTESTINFO
LV_ITEM
LV_KEYDOWN
NM_LISTVIEW


 List View Control Constants

The following sections list window style flags and item state flags are used with list view controls.


 List View Window Styles

The following window styles are specific to list view controls.

LVS_ALIGNLEFT	Specifies that items are left-aligned in icon and small icon view.
LVS_ALIGNTOP	Specifies that items are aligned with the top of the list view control in icon and small icon view.
LVS_AUTOARRANGE	Specifies that icons are automatically kept arranged in icon and small icon view.
LVS_BUTTON	Specifies that item icons look like buttons in icon view.
LVS_EDITLABELS	Allows item text to be edited in place. The parent window must process the LVN_ENDLABELEDIT notification message.
LVS_ICON	Specifies icon view.
LVS_LIST	Specifies list view.
LVS_NOCOLUMNHEADER	Specifies that a column header is not displayed in report view. By default, columns have headers in report view.
LVS_NOLABELWRAP	Displays item text on a single line in icon view. By default, item text may wrap in icon view.
LVS_NOSCROLL	Disables scrolling. All items must be within the client area.
LVS_NOSORTHEADER	Specifies that column headers do not work like buttons. This style is useful if clicking a column header in report view does not carry out an action, such as sorting.
LVS_OWNERDRAWFIXED	Enables the owner window to paint items in report view. The list view control sends a WM_DRAWITEM message to paint each item; it does not send separate messages for each subitem. The itemData member of the DRAWITEMSTRUCT structure contains the item data for the specified list view item.
LVS_REPORT	Specifies report view. When using the LVS_REPORT style with a List View control, the first column is always left-aligned. You can not use LVCFMT_RIGHT to change this alignment.
LVS_SHAREIMAGELISTS	Specifies that the control does not take ownership of the image lists assigned to it;  that is, it does not destroy the image lists when it is destroyed. This style enables the same image lists to be used with multiple list view controls.
LVS_SHOWSELALWAYS	Always show the selection,if any, even if the control does not have the focus.
LVS_SINGLESEL	Allows only one item at a time to be selected. By default, multiple items may be selected.
LVS_SMALLICON	Specifies small icon view.
LVS_SORTASCENDING	Sorts items based on item text in ascending order.
LVS_SORTDESCENDING	Sorts items based on item text in descending order.
You can use the LVS_TYPESTYLEMASK value to isolate the window styles that correspond to the current view: LVS_ICON, LVS_SMALLICON, LVS_LIST, and LVS_REPORT.

You can use the LVS_ALIGNMASK value to isolate the window styles that specify the alignment of items: LVS_ALIGNLEFT and LVS_ALIGNTOP.


 List View Item States

An item's state determines its appearance and functionality. The state can be zero, or one or more of the following values.

LVIS_CUT	The item is marked for a cut and paste operation.
LVIS_DROPHILITED	The item is highlighted as a drag-and-drop target.
LVIS_FOCUSED	The item has the focus, so it is surrounded by a standard focus rectangle. Although more than one item may be selected, only one item can have the focus.
LVIS_SELECTED	The item is selected. The appearance of a selected item depends on whether it has the focus and on the system colors used for selection.
You can use the LVIS_OVERLAYMASK value to isolate the state bits that contain the one-based index of the overlay image. You can use the LVIS_STATEIMAGEMASK value to isolate the state bits that contain the one-based index of the state image.


 Progress Bars

A progress bar is a window that an application can use to indicate the progress of a lengthy operation. It consists of a rectangle that is gradually filled, from left to right, with the system highlight color as an operation progresses. The following illustration shows a progress bar positioned along the bottom of a window.


 About Progress Bars

You create a progress bar by using the CreateWindowEx function, specifying the PROGRESS_CLASS window class. This window class is registered when the common control dynamic-link library (DLL) is loaded. To ensure that this DLL is loaded, use the InitCommonControls function first.


 Range and Current Position

A progress bar has a range and a current position. The range represents the entire duration of the operation, and the current position represents the progress that the application has made toward completing the operation. The window procedure uses the range and the current position to determine the percentage of the progress bar to fill with the highlight color and to determine the text, if any, to display within the progress bar. Because the range and current position values are expressed as unsigned integers, the highest possible range or current position value is 65,535.

The minimum value in the range can be from 0 to 65,535. Likewise, the maximum value can be from 0 to 65,535. If you do not set the range values, the system sets the minimum value to 0 and the maximum value to 100. You can adjust the range to convenient integers by using the PBM_SETRANGE message.

A progress bar provides several messages that you can use to set the current position. The PBM_SETPOS message sets the position to a given value. The PBM_DELTAPOS message advances the position by adding a specified value to the current position.

The PBM_SETSTEP message allows you to specify a step increment for a progress bar. Subsequently, whenever you send the PBM_STEPIT message to the progress bar, the current position advances by the specified increment. By default, the step increment is set to 10.


 Default Progress Bar Message Processing

This section describes the window messages handled by the window procedure for the PROGRESS_CLASS window class.

Message	Processing performed
WM_CREATE	Allocates and initializes an initial structure.
WM_DESTROY	Frees all resources associated with the progress bar.
WM_ERASEBKGND	Draws the background and borders of the progress bar.
WM_GETFONT	Returns the handle of the font that the progress bar is currently using to draw text.
WM_PAINT	Draws the progress bar.
WM_SETFONT	Saves the handle of the new font and returns the handle of the previous font.


 Using Progress Bars

The following example shows how to use a progress bar to indicate the progress of a lengthy file-parsing operation. The example creates a progress bar and positions it along the bottom of the parent window's client area. The height of the progress bar is based on the height of the arrow bitmap used in a scroll bar. The range is based on the size of the file divided by 2048, which is the size of each "chunk" of data read from the file. The example also sets an increment and advances the current position of the progress bar by the increment after parsing each chunk.

// ParseALargeFile - parses a large file and uses a progress bar to

//   indicate the progress of the parsing operation.

// Returns TRUE if successful or FALSE otherwise.

// hwndParent - parent window of the progress bar

// lpszFileName - name of the file to parse

//

// Global variable

//     g_hinst - instance handle

extern HINSTANCE g_hinst;

BOOL ParseALargeFile(HWND hwndParent, LPSTR lpszFileName)

{

    RECT rcClient;  // client area of parent window

    int cyVScroll;  // height of scroll bar arrow

    HWND hwndPB;    // handle of progress bar

    HANDLE hFile;   // handle of file

    DWORD cb;       // size of file and count of bytes read

    LPCH pch;       // address of data read from file

    LPCH pchTmp;    // temporary pointer

    // Ensure that the common control DLL is loaded and create a

    // progress bar along the bottom of the client area of the

    // parent window. Base the height of the progress bar on

    // the height of a scroll bar arrow.

    InitCommonControls();

    GetClientRect(hwndParent, &rcClient);

    cyVScroll = GetSystemMetrics(SM_CYVSCROLL);

    hwndPB = CreateWindowEx(0, PROGRESS_CLASS, (LPSTR) NULL,

        WS_CHILD | WS_VISIBLE, rcClient.left,

        rcClient.bottom - cyVScroll,

        rcClient.right, cyVScroll,

        hwndParent, (HMENU) 0, g_hinst, NULL);

    // Open the file for reading, and retrieve the size of the file.

    hFile = CreateFile(lpszFileName, GENERIC_READ, FILE_SHARE_READ,

        (LPSECURITY_ATTRIBUTES) NULL, OPEN_EXISTING,

        FILE_ATTRIBUTE_NORMAL, (HANDLE) NULL);

    if (hFile == (HANDLE) INVALID_HANDLE_VALUE)

        return FALSE;

    cb = GetFileSize(hFile, (LPDWORD) NULL);

    // Set the range and increment of the progress bar.

    SendMessage(hwndPB, PBM_SETRANGE, 0, MAKELPARAM(0, cb / 2048));

    SendMessage(hwndPB, PBM_SETSTEP, (WPARAM) 1, 0);

    // Parse the file.

    pch = (LPCH) LocalAlloc(LPTR, sizeof(char) * 2048);

    pchTmp = pch;

    do {

        ReadFile(hFile, pchTmp, sizeof(char) * 2048, &cb,

            (LPOVERLAPPED) NULL);

        .

        . // Include here any code that parses the file.

        .

        // Advance the current position of the progress bar

        // by the increment.

        SendMessage(hwndPB, PBM_STEPIT, 0, 0);

    } while (cb);

    CloseHandle((HANDLE) hFile);

    DestroyWindow(hwndPB);

    return TRUE;

}


 Progress Bar Messages

The following messages are associated with progress bars.

PBM_DELTAPOS
PBM_SETPOS
PBM_SETRANGE
PBM_SETSTEP
PBM_STEPIT


 Property Sheets

A property sheet is a window that allows the user to view and edit the properties of an item. For example, a spreadsheet application can use a property sheet to allow the user to set the font and border properties of a cell or to view and set the properties of a device, such as a disk drive, printer, or mouse.

This overview assumes that you have a thorough understanding of dialog box templates and dialog box procedures. If you do not, you should read Dialog Boxes before continuing with this overview.


 About Property Sheets

A property sheet contains one or more overlapping child windows called pages, each containing control windows for setting a group of related properties. For example, a page can contain the controls for setting the font properties of an item, including the type style, point size, color, and so on. Each page has a tab that the user can select to bring the page to the foreground of the property sheet. The following illustration shows a property sheet for viewing and setting the properties of a floppy disk drive.


 Property Sheet Dialog Boxes

A property sheet and the pages it contains are actually dialog boxes. The property sheet is a system-defined dialog box that manages the pages and provides a common container for them. The property sheet dialog box can be modal or modeless. It includes a frame, a title bar, and four buttons: OK, Cancel, Apply Now, and Help. (The Help button may be hidden as in the preceding illustration.) The dialog box procedures for the pages receive notification messages when the user selects the buttons.

Each page in a property sheet is an application-defined modeless dialog box that manages the control windows used to view and edit the properties of an item. You provide the dialog box template used to create each page as well as the dialog box procedure that manages the controls and sets the properties of the corresponding item.

A property sheet sends notification messages to the dialog box procedure for a page when the page is gaining or losing the activation and when the user chooses the OK, Cancel, Apply Now, or Help button. The notifications are sent in the form of WM_NOTIFY messages. The lParam parameter points to an NMHDR structure, which includes the window handle of the property sheet dialog box.

Some notification messages require a page to return either TRUE or FALSE in response to the WM_NOTIFY message. A page cannot simply return TRUE or FALSE; instead, it must use the SetWindowLong function to set the DWL_MSGRESULT value for the page dialog box to either TRUE or FALSE.


 Pages

A property sheet must contain at least one page, but cannot contain more than the value of MAXPROPPAGES as defined in the Win32 header files. Each page has a zero-based index that the property sheet assigns according to the order in which the page is added to the property sheet. The indexes are used in messages that you send to the property sheet.

A property page can contain a nested dialog box. If it does, you must include the WS_EX_CONTROLPARENT style for the top-level dialog box and call the IsDialogMessage function with the handle of the parent dialog box. This ensures that the user can use mnemonics and the dialog box navigation keys to move the focus to controls in the nested dialog box.

Each page has a corresponding icon and label. The property sheet creates a tab for each page and displays the icon and label in the tab. All property sheet pages are expected to use a nonbold font. To ensure that the font is not bold, specify the DS_3DLOOK style in the dialog box template.

The dialog box procedure for a page must not call the EndDialog function. Doing so will destroy the entire property sheet, not just the page.


 Property Sheet Creation

Before creating a property sheet, you must define one or more pages. This involves filling a PROPSHEETPAGE structure with information about the page — its icon, label, dialog box template, dialog box procedure, and so on — and then specifying the address of the structure in a call to the CreatePropertySheetPage function. The function returns a handle of the HPROPSHEETPAGE type that uniquely identifies the page.

To create a property sheet, you specify the address of a PROPSHEETHEADER structure in a call to the PropertySheet function. The structure defines the icon and title for the property sheet and also includes a pointer to an array of HPROPSHEETPAGE handles. When PropertySheet creates the property sheet, it includes the pages identified in the array. The order of the array determines the order of the pages in the property sheet.

Another way to create a property sheet is to specify an array of PROPSHEETPAGE structures instead of an array of HPROPSHEETPAGE handles. In this case, PropertySheet creates handles for the pages before adding them to the property sheet.

When a page is created, the dialog box procedure for the page receives a WM_INITDIALOG message. The message's lParam parameter points to the PROPSHEETPAGE structure used to create the page. The dialog box can save the information in the structure and use it later to modify the page.

PropertySheet automatically sets the size and initial position of a property sheet. The position is based on the position of the owner window, and the size is based on the largest page specified in the array of pages when the property sheet was created. If you want the pages to match the width of the four buttons at the bottom of the property sheet, set the width of the widest page to 190 dialog units.


 Adding and Removing Pages

After creating a property sheet, an application can add a page by using the PSM_ADDPAGE message. Note that the size of the property sheet cannot change after it has been created, so the new page must be no larger than the largest page currently in the property sheet.

An application removes a page by using the PSM_REMOVEPAGE message. When you define a page, you can specify the address of a PropSheetPageProc callback function that the property sheet calls when it is creating or removing the page. Using PropSheetPageProc gives you an opportunity to perform initialization and cleanup operations for individual pages.

When a property sheet is destroyed, it automatically destroys all of the pages that have been added to it. The pages are destroyed in reverse order from that specified in the array used to create the pages. To destroy a page that was created by the CreatePropertySheetPage function but was not added to the property sheet, use the DestroyPropertySheetPage function.


 Property Sheet Title and Page Labels

You specify the title of a property sheet in the PROPSHEETHEADER structure used to create the property sheet. If the dwFlags member includes the PSH_PROPTITLE value, the property sheet adds the "Properties for" prefix to the specified title string. An application can change the title after a property sheet is created by using the PSM_SETTITLE message.

By default, a property sheet uses the name string specified in the dialog box template as the label for a page. You can override the name string by including the PSP_USETITLE value in the dwFlags member of the PROPSHEETPAGE structure that defines the page. When PSP_USETITLE is specified, the pszTitle member must contain the address of the label string for the page.


 Page Activation

A property sheet can have only one active page at a time. The page that has the activation is at the foreground of the overlapping stack of pages. The user activates a page by selecting its tab; an application activates a page by using the PSM_SETCURSEL message.

The property sheet sends the PSN_KILLACTIVE notification message to the page that is about to lose the activation. In response, the page should validate any changes that the user has made to the page. If the page requires additional user input before losing the activation, it should use the SetWindowLong function to set the DWL_MSGRESULT value of the page to TRUE. Also, the page should display a message box that describes the problem and provides the recommended action. The page should set DWL_MSGRESULT to FALSE when it is okay to lose the activation.

Before the page that is gaining the activation is visible, the property sheet sends the PSN_SETACTIVE notification message to the page. The page should respond by initializing its control windows.


 Help Button

When a page is activated, the property sheet determines whether to enable or disable the Help button for the page by checking for the PSP_HASHELP style. If the page has this style, it supports the Help button. If the PSP_HASHELP style is not present, the button is disabled.

When the user chooses the Help button, the active page receives the PSN_HELP notification message. The page should respond by displaying help information, typically by calling the WinHelp function.


 OK, Cancel, and Apply Now Buttons

The OK and Apply Now buttons are similar; both direct a property sheet's pages to validate and apply the property changes that the user has made. The only difference is that choosing the OK button causes the property sheet to be destroyed after the changes are applied, but choosing the Apply Now button does not.

When the user chooses the OK or Apply Now button, the property sheet sends the PSN_KILLACTIVE notification message to the active page, giving it an opportunity to validate the user's changes. If the page determines that the changes are valid, it should call the SetWindowLong function to set the DWL_MSGRESULT value for the page to FALSE. In this case, the property sheet sends the PSN_APPLY notification message to each page, directing them to apply the new properties to the corresponding item. If the page determines that the user's changes are not valid, it should set DWL_MSGRESULT to TRUE and display a dialog box informing the user of the problem. The page remains active until it sets DWL_MSGRESULT to FALSE in response to a PSN_KILLACTIVE message. An application can use the PSM_APPLY message to simulate the choice of the Apply Now button.

The Apply Now button is initially disabled when a page becomes active, indicating that there are not yet any property changes to apply. When the page receives user input through one of its controls indicating that the user has edited a property, the page should send the PSM_CHANGED message to the property sheet. The message causes the property sheet to enable the Apply Now button. If the user subsequently chooses the Apply Now or Cancel button, the page should reinitialize its controls and then send the PSM_UNCHANGED message to disable again the Apply Now button.

Sometimes the Apply Now button causes a page to make a change to a property sheet, and the change cannot be undone. When this happens, the page should send the PSM_CANCELTOCLOSE message to the property sheet. The message causes the property sheet to change the text of the OK button to "Close," indicating that the applied changes cannot be canceled.

Sometimes a page makes a change to the system configuration that requires Windows to be to restarted or the system rebooted before the change can take effect. After making such a change, a page should send either the PSM_RESTARTWINDOWS or PSM_REBOOTSYSTEM message to the property sheet. These messages cause the PropertySheet function to return the ID_PSRESTARTWINDOWS or ID_PSREBOOTSYSTEM value after the property sheet is destroyed.

The property sheet sends the the PSN_RESET notification message to all pages when the user chooses the Cancel button, indicating that the property sheet is about to be destroyed. A page should use the notification to perform cleanup operations.


 Wizard Property Sheets

You can create a special type of property sheet called a wizard, which consists of a sequence of dialog boxes that guide the user through the steps of an operation, such as setting up a device or creating a birthday card. In a wizard property sheet, the pages do not have tabs, and only one page is visible at a time. Also, instead of having Ok and Apply Now buttons, a wizard property sheet has a Back button, a Next or Finish button, and a Cancel button. To tell the property sheet which buttons to enable, use the PSM_SETWIZBUTTONS message with the PSWIZB_BACK, PSWIZB_NEXT, and PSWIZB_FINISH values. You create and initialize a wizard property sheet just as you would a standard property sheet, except that you must include the PSH_WIZARD value in the dwFlags member of the PROPSHEETHEADER structure. The system ignores the pszCaption member; instead, it puts the label of the current page in the title bar of the property sheet. When the user switches from one page to the next, the system updates the title using the label of the current page.

You should use the following values to set the sizes of the elements in your wizard property sheet. Using these values ensures that your pages conform to the Window standards.

WIZ_BODYCX	Width of the body of a page in a wizard property sheet. The body does not include the bitmap area.
WIZ_BODYX	Horizontal coordinate of the upper left corner of the body of a page in a wizard property sheet. Use zero for the vertical coordinate of the body of a page.
WIZ_CXBMP	Width of the bitmap area in a page of a wizard property sheet. Use WIZ_CYDLG for the height of the bitmap area.
WIZ_CXDLG	Width of a page in a wizard property sheet.
WIZ_CYDLG	Height of a page in a wizard property sheet.
The dialog box procedure for a page in a wizard property sheet receives all of the same notification messages as a standard property sheet page. In addition, a wizard property sheet page receives three notification messages that a standard property sheet page does not receive: PSN_WIZBACK, PSN_WIZNEXT, and PSN_WIZFINISH. A wizard page receives these notifications when the user chooses the Back, Next, or Finish button.

When the user chooses the Back or Next button, the property sheet automatically advances to the previous or next page. An application can prevent the property sheet from advancing by setting the DWL_MSGRESULT value to −1 in response to the PSN_WIZBACK or PSN_WIZNEXT notification. To jump to a page other than the previous or next one, an application should set DWL_MSGRESULT to the identifier of the dialog box to be displayed.

The system automatically destroys the wizard property sheet when the user clicks the Finish button. An application can prevent the wizard from being destroyed by setting DWL_MSGRESULT to a nonzero value in response to the PSN_WIZFINISH notification message.


 Property Sheet Extensions

A property sheet extension is a dynamic-link library (DLL) that adds one or more pages to a property sheet created by another module. The module that creates the property sheet includes an AddPropSheetPageProc callback function that the extension DLL calls to add a page. The function receives the handle of a page and an application-defined 32-bit value.

The extension DLL also contains a callback function called ExtensionPropSheetPageProc, which receives the address of AddPropSheetPageProc from the module that creates the property sheet. The extension DLL must export ExtensionPropSheetPageProc.

The Windows header files include two prototypes for defining property sheet callback functions. To define AddPropSheetPageProc, use the following prototype.

typedef BOOL (CALLBACK FAR * LPFNADDPROPSHEETPAGE)(HPROPSHEETPAGE,
    LPARAM);

To define ExtensionPropSheetPageProc, use the following prototype.

typedef BOOL (CALLBACK FAR * LPFNADDPROPSHEETPAGES)(LPVOID, LPFNADDPROPSHEETPAGE, LPARAM);


 Using Property Sheets

•	Creating a property sheet

•	Processing notification messages


 Creating a Property Sheet

The example in this section creates a property sheet that contains two pages — one for setting the font properties of a cell in a spreadsheet and another for setting the border properties of the cell. The example defines the pages by filling a pair of PROPSHEETPAGE structures and specifying the address in the PROPSHEETHEADER structure that is passed to the PropertySheet function. The dialog box templates, icons, and labels for the pages are loaded from the resources contained in the application's executable file. The icon for the property sheet is also loaded from the application's resources.

// DoPropertySheet - creates a property sheet that contains two pages.
// hwndOwner - handle of the owner window of the property sheet
//
// Global variables
//     g_hinst - instance handle
extern HINSTANCE g_hinst;

VOID DoPropertySheet(HWND hwndOwner)
{
    PROPSHEETPAGE psp[2];
    PROPSHEETHEADER psh;

    psp[0].dwSize = sizeof(PROPSHEETPAGE);
    psp[0].dwFlags = PSP_USEICONID | PSP_USETITLE;
    psp[0].hInstance = g_hinst;
    psp[0].pszTemplate = MAKEINTRESOURCE(DLG_FONT);
    psp[0].pszIcon = MAKEINTRESOURCE(IDI_FONT);
    psp[0].pfnDlgProc = FontDialogProc;
    psp[0].pszTitle = MAKEINTRESOURCE(IDS_FONT)
    psp[0].lParam = 0;
    psp[0].pfnCallback = NULL;

    psp[1].dwSize = sizeof(PROPSHEETPAGE);
    psp[1].dwFlags = PSP_USEICONID | PSP_USETITLE;
    psp[1].hInstance = g_hinst;
    psp[1].pszTemplate = MAKEINTRESOURCE(DLG_BORDER);
    psp[1].pszIcon = MAKEINTRESOURCE(IDI_BORDER);
    psp[1].pfnDlgProc = BorderDialogProc;
    psp[1].pszTitle = MAKEINTRESOURCE(IDS_BORDER);
    psp[1].lParam = 0;
    psp[1].pfnCallback = NULL;

    psh.dwSize = sizeof(PROPSHEETHEADER);
    psh.dwFlags = PSH_USEICONID | PSH_PROPSHEETPAGE;
    psh.hwndParent = hwndOwner;
    psh.hInstance = g_hinst;
    psh.pszIcon = MAKEINTRESOURCE(IDI_CELL_PROPERTIES);
    psh.pszCaption = (LPSTR) "Cell Properties";
    psh.nPages = sizeof(psp) / sizeof(PROPSHEETPAGE);
    psh.nStartPage = 0;
    psh.ppsp = (LPCPROPSHEETPAGE) &psp;
    psh.pfnCallback = NULL;

    PropertySheet(&psh);
    return;
}


 Processing Notification Messages

A property sheet sends WM_NOTIFY messages to retrieve information from the pages and to notify the pages of user actions. The lParam parameter of the message is the address of an NMHDR structure, which contains the handle of the property sheet dialog box, the handle of the page dialog box, and a notification code. The page must respond to some notification messages by setting the DWL_MSGRESULT value of the page to either TRUE or FALSE.

The following example is a code fragment from the dialog box procedure for a page. It shows how to process the PSN_HELP notification message.

case WM_NOTIFY:
    switch (((NMHDR FAR *) lParam)->code) {

        case PSN_HELP:
             {
             char szBuf[FILE_LEN]; // buffer for name of help file

             // Display help for the font properties page.
             LoadString(g_hinst, IDS_HELPFILE, &szBuf, FILE_LEN)
             WinHelp(((NMHDR FAR *) lParam)->hwndFrom, &szBuf,
                 HELP_CONTEXT, IDH_FONT_PROPERTIES);
             break;
             }
        .
        . // Process other property sheet notifications here.
        .
    }


 Property Sheet Reference

The following functions, messages, notification messages, and structures are associated with property sheets. These elements can be grouped as follows.

Property Sheet Creation

CreatePropertySheetPage
DestroyPropertySheetPage
PropertySheet
PROPSHEETHEADER
PROPSHEETPAGE
PropSheetPageProc
PropSheetProc
PSM_ADDPAGE
PSM_REMOVEPAGE

Property Sheet Extensions

AddPropSheetPageProc
ExtensionPropSheetPageProc

Page Activation

PSM_SETCURSEL
PSM_SETCURSELID
PSN_KILLACTIVE
PSN_SETACTIVE

Property Sheet Buttons

PSM_APPLY
PSM_CANCELTOCLOSE
PSM_CHANGED
PSM_PRESSBUTTON
PSM_REBOOTSYSTEM
PSM_RESTARTWINDOWS
PSM_UNCHANGED
PSN_APPLY
PSN_HELP
PSN_QUERYCANCEL
PSN_RESET

Wizard Property Sheets

PSM_SETFINISHTEXT
PSM_SETWIZBUTTONS
PSN_WIZBACK
PSN_WIZFINISH
PSN_WIZNEXT

Miscellaneous Messages

PSM_GETTABCONTROL
PSM_SETTITLE
PSM_QUERYSIBLINGS


 Property Sheet Functions

The following functions are used with property sheets.

AddPropSheetPageProc
CreatePropertySheetPage
DestroyPropertySheetPage
ExtensionPropSheetPageProc
PropertySheet
PropSheetPageProc
PropSheetProc


 Property Sheet Messages

An application sends messages to direct a property sheet to add and remove pages, enable and disable buttons, set the return value of the PropertySheet function, and so on. The following are the property sheet messages.

PSM_ADDPAGE
PSM_APPLY
PSM_CANCELTOCLOSE
PSM_CHANGED
PSM_GETCURRENTPAGEHWND
PSM_GETTABCONTROL
PSM_ISDIALOGMESSAGE
PSM_PRESSBUTTON
PSM_QUERYSIBLINGS
PSM_REBOOTSYSTEM
PSM_REMOVEPAGE
PSM_RESTARTWINDOWS
PSM_SETCURSEL
PSM_SETCURSELID
PSM_SETFINISHTEXT
PSM_SETTITLE
PSM_SETWIZBUTTONS
PSM_UNCHANGED


 Property Sheet Notification Messages

A property sheet sends notification messages to the pages to notify them of events. The following are the property sheet notifications.

PSN_APPLY
PSN_HELP
PSN_KILLACTIVE
PSN_QUERYCANCEL
PSN_RESET
PSN_SETACTIVE
PSN_WIZBACK
PSN_WIZFINISH
PSN_WIZNEXT


 Property Sheet Structures

The following structures are used with property sheets.

PROPSHEETHEADER
PROPSHEETPAGE


 Rich Edit Controls

A rich edit control is a window in which the user can enter and edit text. The text can be assigned character and paragraph formatting, and can include embedded OLE objects. Rich edit controls provide a programming interface for formatting text. However, an application must implement any user interface components necessary to make formatting operations available to the user.


 About Rich Edit Controls

Rich edit controls support almost all of the messages and notification messages used with multiline edit controls. Thus, applications that already use edit controls can be easily changed to use rich edit controls. Additional messages and notifications enable applications to access the functionality unique to rich edit controls. For information about edit controls, see Edit Controls.

An application can send messages to a rich edit control to perform such operations as formatting text, printing, and saving. An application can process notification messages to monitor events in a rich edit control. For example, an application can process notifications to filter keyboard and mouse input, to permit or deny changes to protected text, or to resize the control as needed to fit its content.

You create a rich edit control by using the CreateWindowEx function, specifying the "RichEdit" window class. Because the common control library registers this window class, you must call the LoadLibrary function to ensure that the RICHED32.DLL library is loaded before the rich edit control is created.

Rich edit controls support most of the window styles used with edit controls as well as additional styles. You should specify the ES_MULTILINE window style if you want to allow more than one line of text in the control.


 Text Formatting

An application can send messages to a rich edit control to format characters and paragraphs and to retrieve formatting information. Paragraph formatting attributes include alignment, tabs, indents, and numbering. For characters, you can specify typeface, size, color, and effects such as bold, italic, and protected.

You can apply paragraph formatting by using the EM_SETPARAFORMAT message. To determine the current paragraph formatting for the selected text, use the EM_GETPARAFORMAT message. The PARAFORMAT structure is used with both messages to specify paragraph formatting attributes.

You can apply character formatting by using the EM_SETCHARFORMAT message. To determine the current character formatting for the selected text, you can use the EM_GETCHARFORMAT message. The CHARFORMAT structure is used with both messages to specify character attributes.

You can also use EM_SETCHARFORMAT and EM_GETCHARFORMAT messages to set and retrieve the default character formatting, which is the formatting applied to any subsequently inserted characters. For example, if an application sets the default character formatting to bold and the user then types a character, that character is bold.

The default character formatting is applied to newly inserted text only if the current selection is empty. Otherwise, the new text assumes the character formatting of the text it replaces. If the selection changes, the default character formatting changes to match the first character in the new selection.

The protected character effect is unique in that it does not change the appearance of text. If the user attempts to modify protected text, a rich edit control sends its parent window an EN_PROTECTED notification message, allowing the parent window to allow or prevent the change. To receive this notification message, you must enable it by using the EM_SETEVENTMASK message.

Foreground color is a character attribute, but background color is a property of the rich edit control. To set the background color, use the EM_SETBKGNDCOLOR message.


 Current Selection in a Rich Edit Control

The user can select text in a rich edit control by using the mouse or the keyboard. The current selection is the range of selected characters, or the position of the insertion point if no characters are selected. An application can get information about the current selection, set the current selection, determine when the current selection changes, and show or hide the selection highlight.

To determine the current selection in a rich edit control, use the EM_EXGETSEL message. To set the current selection, use the EM_EXSETSEL message. The CHARRANGE structure is used with both messages and specifies a range of characters. To retrieve information about the contents of the current selection, you can use the EM_SELECTIONTYPE message.

An application can detect when the current selection changes by processing the EN_SELCHANGE notification message. The notification message specifies a SELCHANGE structure containing information about the new selection. A rich edit control sends this notification message only if you enable it by using the EM_SETEVENTMASK message.

By default, a rich edit control shows and hides the selection highlight when it gains and loses the focus. You can show or hide the selection highlight at any time by using the EM_HIDESELECTION message. For example, an application might provide a Search dialog box to find text in a rich edit control. The application might select matching text without closing the dialog box, in which case it must use the EM_HIDESELECTION message to highlight the selection.

As with edit controls, you can specify the ES_NOHIDESEL window style to prevent a rich edit control from hiding the selection highlight when it loses the focus. You can also use the EM_HIDESELECTION message to change the ES_NOHIDESEL window style after a rich edit control is created.

Instead of using the EM_EXGETSEL and EM_EXSETSEL messages, you retrieve and set the current selection by using the EM_GETSEL and EM_SETSEL edit control messages. The EM_GETSEL message packs two 16-bit character indexes into its 32-bit return value and, therefore, works only for selections that fall entirely within the first 64K. However, a rich edit control will never contain more than 32K of text, unless you extend this limit by using the EM_EXLIMITTEXT message. For selections that extend beyond the first 64K of text, the EM_GETSEL message returns  − 1.


 Rich Edit Text Operations

An application can send messages to retrieve or find text in a rich edit control. You can retrieve either the selected text or a specified range of text.

To get the selected text in a rich edit control, use the EM_GETSELTEXT message. The text is copied to the specified character array. You must ensure that the array is large enough to hold the selected text plus a terminating null character.

To retrieve a specified range of text, use the EM_GETTEXTRANGE message. The TEXTRANGE structure used with this message specifies the text range to retrieve and points to a character array that receives the text. Here again, the application must ensure that the array is large enough for the specified text plus a terminating null character.

You can search for a string in a rich edit control by using the EM_FINDTEXT message. The FINDTEXT structure used with this message specifies the text range to search and the string to search for. You can also specify such options as whether the search is case-sensitive.


 Word and Line Breaks

A rich edit control calls a function called a word break procedure to find breaks between words and to determine where it can break lines. The control uses this information when performing word wrap operations and when processing the CTRL+LEFT and CTRL+RIGHT key combinations. An application can send messages to a rich edit control to replace the default word break procedure, to retrieve word break information, and to determine what line a given character falls on.

Word break procedures for rich edit controls are similar to those for edit controls, but they have additional capabilities. Word break procedures for both kinds of controls can determine whether a character is a delimiter and can find the nearest word break before or after the specified position. A delimiter is a character that marks the end of a word, such as a space. In an edit control, word breaks occur only after delimiters.

Word break procedures for rich edit controls also group characters into character classes, each identified by a value in the range 0x00 through 0x0F. Word breaks occur either after delimiters or between characters of different classes. Thus, a word break procedure with different classes for alphanumeric and punctuation characters would find two word breaks in the string "WIN.COM".

A character's class can be combined with zero or more word break flags to form an eight-bit value. When performing word wrap operations, a rich edit control uses word break flags to determine where it can break lines. There are the following word break flags.

WBF_BREAKAFTER	Lines may be broken after the character.
WBF_BREAKLINE	The character is a delimiter. Delimiters mark the ends of words. Lines may be broken after delimiters.
WBF_ISWHITE	The character is a white space character. Trailing white space characters are not included in the length of a line when wrapping.
The WBF_BREAKAFTER value is used to allow wrapping after a character that does not mark the end of a word, such as a hyphen.

You can replace a rich edit control's default word break procedure with your own by using the EM_SETWORDBREAKPROC message. For more information about word break procedures, see the description of the EditWordBreakProc function.

Alternately, you can use the EM_SETWORDBREAKPROCEX message to replace the default extended word break procedure with an EditWordBreakProcEx function. This function provides additional information about the text, such as the character set. You can use the EM_GETWORDBREAKPROCEX message to retrieve the address of the current extended word break procedure.

You can use the EM_FINDWORDBREAK message to find word breaks or to determine a character's class and word break flags. In turn, the control calls its word break procedure to get the requested information.

To determine which line a given character falls on, you can use the EM_EXLINEFROMCHAR message.


 Rich Edit Clipboard Operations

An application can paste the contents of the clipboard into a rich edit control using either the best available clipboard format or a specific clipboard format. You can also determine whether a rich edit control is capable of pasting a clipboard format.

As with an edit control, you can copy or cut the contents of the current selection by using the WM_COPY or WM_CUT message. Similarly, you can paste the contents of the clipboard into a rich edit control by using the WM_PASTE message. The control pastes the first available format that it recognizes, which presumably is the most descriptive format.

To paste a specific clipboard format, you can use the EM_PASTESPECIAL message. This message is useful for applications with a Paste Special command that enables the user to select the clipboard format. You can use the EM_CANPASTE message to determine whether a given format is recognized by the control.

You can also use the EM_CANPASTE message to determine whether any available clipboard format is recognized by a rich edit control. This message is useful when processing the WM_INITMENUPOPUP message. An application might enable or gray its Paste command depending on whether the control can paste any available format.

Rich edit controls register two clipboard formats: rich-text format and a format called RichEdit Text and Objects. An application can register these formats by using the RegisterClipboardFormat function, specifying the CF_RTF and CF_RETEXTOBJ values.


 Streams

You can use streams to transfer data into or out of a rich edit control. A stream is defined by an EDITSTREAM structure, which specifies a buffer and an application-defined callback function.

To read data into a rich edit control (that is, stream the data in), use the EM_STREAMIN message. The control repeatedly calls the application's callback function, which transfers a portion of the data into the buffer each time.

To save the contents of a rich edit control (that is, stream the data out), you can use the EM_STREAMOUT message. The control repeatedly writes to the buffer and then calls the application's callback function. For each call, the callback function saves the contents of the buffer.


 Printing

You can send messages to a rich edit control to render its output for a specified device, such as a printer. You can also specify the output device for which a rich edit control formats its text.

To format part of a rich edit control's contents for a specific device, you can use the EM_FORMATRANGE message. The FORMATRANGE structure used with this message specifies the range of text to format as well as the device context (DC) for the target device.

After formatting text for an output device, you can send the output to the device by using the EM_DISPLAYBAND message. By repeatedly using the EM_FORMATRANGE and EM_DISPLAYBAND messages, an application that prints the contents of a rich edit control can implement banding. (Banding is division of output into smaller parts for pringing purposes).

You can use the EM_SETTARGETDEVICE message to specify the target device for which a rich edit control formats its text. This message is useful for WYSIWYG  (what you see is what you get) formatting, in which an application positions text using the default printer's font metrics instead of the screen's.


 Bottomless Rich Edit Controls

An application can resize a rich edit control as needed so that it is always the same size as its contents. A rich edit control supports this so-called "bottomless" functionality by sending its parent window an EN_REQUESTRESIZE notification message whenever the size of its contents changes.

When processing the EN_REQUESTRESIZE notification message, an application should resize the control to the dimensions in the specified REQRESIZE structure. An application might also move any information near the control to accommodate the control's change in height. To resize the control, you can use the SetWindowPos function.

You can force a bottomless rich edit control to send an EN_REQUESTRESIZE notification message by using the EM_REQUESTRESIZE message. This message can be useful when processing the WM_SIZE message.

To receive EN_REQUESTRESIZE notification messages, you must enable the notification by using the EM_SETEVENTMASK message.


 Miscellaneous Notification Messages

A rich edit control's parent window can process notification messages to monitor events affecting the control. Rich edit controls support all of the notification messages used with edit controls as well as several additional ones. You can determine which notification messages a rich edit control sends its parent window by setting its event mask.

To set the event mask for a rich edit control, use the EM_SETEVENTMASK message. You can retrieve the current event mask for a rich edit control by using the EM_GETEVENTMASK message.

A rich edit control's parent window can filter all keyboard and mouse input to the control by processing the EN_MSGFILTER notification message. The parent window can prevent the keyboard or mouse message from being processed or can change the message by modifying the specified MSGFILTER structure.

An application can process the EN_PROTECTED notification message to detect when the users attempts to modify protected text. To mark a range of text as protected, you can set the protected character effect. For more information, see Text Formatting.

You can enable the user to drop files in a rich edit control by processing the EN_DROPFILES notification message. The specified ENDROPFILES structure contains information about the files being dropped.


 Unsupported Edit Control Functionality

Rich edit controls support most but not all of the functionality of multiline edit controls. This section lists the edit control messages and window styles that are not supported by rich edit controls.

The following messages are processed by edit controls but not by rich edit controls.

Unsupported message	Comments
EM_FMTLINES	Not supported.
EM_GETHANDLE	Rich edit controls do not store text as a simple array of characters.
EM_GETMARGINS	Not supported.
EM_GETPASSWORDCHAR	The ES_PASSWORD style is not supported.
EM_SETHANDLE	Rich edit controls do not store text as a simple array of characters.
EM_SETMARGINS	Not supported.
EM_SETPASSWORDCHAR	The ES_PASSWORD style is not supported.
EM_SETRECTNP	Not supported.
EM_SETTABSTOPS	The EM_SETPARAFORMAT message is used instead.
WM_CTLCOLOR	The EM_SETBKGNDCOLOR message is used instead.
WM_GETFONT	The EM_GETCHARFORMAT message is used instead.
The following window styles are used with multiline edit controls but not with rich edit controls:

ES_LOWERCASE	ES_PASSWORD
ES_OEMCONVERT	ES_UPPERCASE


 Rich Edit Control Reference

The messages, notification messages, and structures associated with rich edit controls are grouped as follows. Some of these application programming interface (API) elements are also used with edit controls.

Formatting

CHARFORMAT
EM_GETCHARFORMAT
EM_GETPARAFORMAT
EM_GETRECT
EM_SETBKGNDCOLOR
EM_SETCHARFORMAT
EM_SETEVENTMASK
EM_SETPARAFORMAT
EM_SETRECT
PARAFORMAT

Selection and Hit Testing

CHARRANGE
EM_CHARFROMPOS
EM_EXGETSEL
EM_EXSETSEL
EM_GETFIRSTVISIBLELINE
EM_GETSEL
EM_HIDESELECTION
EM_POSFROMCHAR
EM_SELECTIONTYPE
EM_SETSEL
EN_SELCHANGE
SELCHANGE

Text Operations

EM_EXLIMITTEXT
EM_FINDTEXT
EM_GETLIMITTEXT
EM_GETSELTEXT
EM_GETTEXTRANGE
EM_REPLACESEL
EM_SETLIMITTEXT
FINDTEXT
TEXTRANGE

Word and Line Breaks

EM_EXLINEFROMCHAR
EM_FINDWORDBREAK
EM_GETWORDBREAKPROC
EM_SETWORDBREAKPROC
EM_GETWORDBREAKPROCEX
EM_SETWORDBREAKPROCEX
EditWordBreakProcEx

Lines and Scrolling

EM_GETLINE
EM_GETLINECOUNT
EM_GETTHUMB
EM_LINEFROMCHAR
EM_LINEINDEX
EM_LINELENGTH
EM_LINESCROLL
EM_SCROLL
EM_SCROLLCARET

Editing Operations

EM_CANPASTE
EM_CANUNDO
EM_EMPTYUNDOBUFFER
EM_PASTESPECIAL
EM_UNDO

Streams

EDITSTREAM
EM_STREAMIN
EM_STREAMOUT

Printing

EM_DISPLAYBAND
EM_FORMATRANGE
EM_SETTARGETDEVICE
FORMATRANGE

Bottomless Rich Edit Controls

EM_REQUESTRESIZE
EN_REQUESTRESIZE
REQRESIZE

OLE Interfaces

IRichEditOle
IRichEditOleCallback

Miscellaneous

EM_GETEVENTMASK
EM_GETIMECOLOR
EM_GETIMEOPTIONS
EM_GETMODIFY
EM_GETOPTIONS
EM_GETPUNCTUATION
EM_GETWORDWRAPMODE
EM_SETEVENTMASK
EM_SETIMECOLOR
EM_SETIMEOPTIONS
EM_SETEVENTMASK
EM_SETMODIFY
EM_SETREADONLY
EM_SETOPTIONS
EM_SETPUNCTUATION
EM_SETWORDWRAPMODE
EN_CHANGE
EN_CORRECTTEXT
EN_DROPFILES
EN_ERRSPACE
EN_HSCROLL
EN_IMECHANGE
EN_KILLFOCUS
EN_MAXTEXT
EN_MSGFILTER
EN_OLEOPFAILED
EN_PROTECTED
EN_SAVECLIPBOARD
EN_SETFOCUS
EN_STOPNOUNDO
EN_UPDATE
EN_VSCROLL
IMC_GETCOMPOSITIONCOLOR
IMC_SETCOMPOSITIONCOLOR
WM_CONTEXTMENU
WM_CTLCOLOREDIT
COMPCOLOR
ENCORRECTTEXT
ENDROPFILES
ENOLEOPFAILED
ENPROTECTED
ENSAVECLIPBOARD
PUNCTUATION
MSGFILTER


 Rich Edit Callback Functions

The following callback function is unique to rich edit controls:

EditWordBreakProcEx


 Rich Edit Messages

The following messages are unique to rich edit controls.

EM_CANPASTE
EM_DISPLAYBAND
EM_EXGETSEL
EM_EXLIMITTEXT
EM_EXLINEFROMCHAR
EM_EXSETSEL
EM_FINDTEXT
EM_FINDTEXTEX
EM_FINDWORDBREAK
EM_FORMATRANGE
EM_GETCHARFORMAT
EM_GETEVENTMASK
EM_GETIMECOLOR
EM_GETIMEOPTIONS
EM_GETOLEINTERFACE
EM_GETOPTIONS
EM_GETPARAFORMAT
EM_GETPUNCTUATION
EM_GETSELTEXT
EM_GETTEXTRANGE
EM_GETWORDBREAKPROCEX
EM_GETWORDWRAPMODE
EM_HIDESELECTION
EM_PASTESPECIAL
EM_REQUESTRESIZE
EM_SELECTIONTYPE
EM_SETBKGNDCOLOR
EM_SETCHARFORMAT
EM_SETEVENTMASK
EM_SETIMECOLOR
EM_SETIMEOPTIONS
EM_SETOLEINTERFACE
EM_SETOPTIONS
EM_SETPARAFORMAT
EM_SETPUNCTUATION
EM_SETTARGETDEVICE
EM_SETWORDBREAKPROCEX
EM_SETWORDWRAPMODE
EM_STREAMIN
EM_STREAMOUT
IMC_GETCOMPOSITIONCOLOR
IMC_SETCOMPOSITIONCOLOR
WM_CONTEXTMENU


 Rich Edit Notification Messages

Rich edit controls support most of the notification messages used with edit controls, plus the following notification messages. A rich edit control sends the following notification messages only if they have been enabled by using the EM_SETEVENTMASK message.

EN_CORRECTTEXT
EN_DROPFILES
EN_IMECHANGE
EN_MSGFILTER
EN_OLEOPFAILED
EN_PROTECTED
EN_REQUESTRESIZE
EN_SAVECLIPBOARD
EN_SELCHANGE
EN_STOPNOUNDO


 Rich Edit Structures

The following structures are used with rich edit controls.

CHARFORMAT
CHARRANGE
COMPCOLOR
EDITSTREAM
ENDROPFILES
ENOLEOPFAILED
ENPROTECTED
ENSAVECLIPBOARD
FINDTEXT
FINDTEXTEX
FORMATRANGE
MSGFILTER
PARAFORMAT
PUNCTUATION
REOBJECT
REPASTESPECIAL
REQRESIZE
SELCHANGE
TEXTRANGE


 Rich Edit OLE Interfaces

The rich edit control supports the client functionality defined by OLE. The control provides full support for most OLE client features. It does not support linking to its contents. The client is responsible for dialogs and error messages, managing storage for OLE objects, and document and application window level in-place activation support. The client can use the EM_GETOLEINTERFACE message to obtain an IRichEditOle interface from the rich edit control which allows it to manage objects. The client uses the EM_SETOLEINTERFACE message to register an IRichEditOleCallback interface that the control uses to obtain the required interfaces and storage.

The following OLE interfaces are used with rich text edit controls:

IRichEditOle
IRichEditOleCallback


 Rich Edit Constants

The following sections describe constants used with rich edit controls.


 Rich Edit Control Styles

The following window styles are unique to rich edit controls:

Style	Description
ES_DISABLENOSCROLL	Disables scrollbars instead of hiding them when they are not needed.
ES_EX_NOCALLOLEINIT	Prevents the control from calling the OleInitialize function when created. Useful only in dialog templates because CreateWindowEx does not accept this style.
ES_NOIME	Disables the input method editor (IME) operation. Available for Asian-languages only.
ES_SAVESEL	Preserves the selection when the control loses the focus. By default, the entire contents of the control are selected when it regains the focus.
ES_SELFIME	Directs the rich edit control to allow the application to handle all IME operations. Available for Asian-languages only.
ES_SUNKEN	Displays the control with a sunken border style so that the rich edit control appears recessed into its parent window. Applications developed for Windows 95 should use WS_EX_CLIENTEDGE instead of ES_SUNKEN.
ES_VERTICAL	Draws text and objects in a vertical direction. Available for Asian-languages only.
Rich edit controls also support the following edit control styles. To allow more than one line of text, you must specify the ES_MULTILINE style.

ES_AUTOHSCROLL	ES_NOHIDESEL
ES_AUTOVSCROLL	ES_READONLY
ES_CENTER	ES_RIGHT
ES_LEFT	ES_WANTRETURN
ES_MULTILINE
Rich edit controls do not support the following edit control styles:

ES_LOWERCASE	ES_PASSWORD
ES_OEMCONVERT	ES_UPPERCASE


 Rich Edit Control Event Mask Flags

The event mask specifies which notification messages a rich edit control sends its parent window. The event mask can be zero or more of these values:

Value	Meaning
ENM_CHANGE	Sends EN_CHANGE notifications.
ENM_CORRECTTEXT	Sends EN_CORRECTTEXT notifications.
ENM_DROPFILES	Sends EN_DROPFILES notifications.
ENM_KEYEVENTS	Sends EN_MSGFILTER  notifications for keyboard events.
ENM_MOUSEEVENTS	Sends EN_MSGFILTER notifications for mouse events.
ENM_PROTECTED	Sends EN_PROTECTED notifications.
ENM_RESIZEREQUEST	Sends EN_REQUESTRESIZE notifications.
ENM_SCROLL	Sends EN_HSCROLL notifications.
ENM_SELCHANGE	Sends EN_SELCHANGE notifications.
ENM_UPDATE	Sends EN_UPDATE notifications.
The default event mask is ENM_NONE in which case no notification messages are sent to the parent window. You can retrieve and set the event mask for a rich edit control by using the ENM_GETEVENTMASK and ENM_SETEVENTMASK messages.


 Status Windows

A status window is a horizontal window at the bottom of a parent window in which an application can display various kinds of status information. The status window can be divided into parts to display more than one type of information. The following illustration shows the status bar in the Microsoft® Windows® Paint application.


 About Status Windows

You can create a status window by using the CreateStatusWindow function or by using the CreateWindowEx function and specifying the STATUSCLASSNAME window class. To ensure that the common control dynamic-link library (DLL) is loaded, use the InitCommonControls function first. After you create the status window, you can divide it into parts, set the text for each part, and control the appearance of the window by using status window messages.


 Types and Styles

The default position of a status window is along the bottom of the parent window, but you can specify the CCS_TOP style to have it appear at the top of the parent window's client area.

You can specify the SBARS_SIZEGRIP style to include a sizing grip at the right end of the status window. A sizing grip is similar to a sizing border; it is a rectangular area that the user can click and drag to resize the parent window.

Note  You can combine the CCS_TOP and SBARS_SIZEGRIP styles. Doing so, however, is not recommended, because the resulting sizing grip is not functional even though the system draws it in the status window.


 Size and Height

The window procedure for the status window automatically sets the initial size and position of the window, ignoring the values specified in the CreateWindowEx function. The width is the same as that of the parent window's client area. The height is based on the metrics of the font that is currently selected into the status window's device context and on the width of the window's borders.

The window procedure automatically adjusts the size of the status window whenever it receives a WM_SIZE message. Typically, when the size of the parent window changes, the parent sends a WM_SIZE message to the status window.

An application can set the minimum height of a status window's drawing area by sending the window an SB_SETMINHEIGHT message, specifying the minimum height, in pixels. The drawing area does not include the window's borders. A minimum height is useful for drawing in an owner-drawn status window. For more information about owner-drawn status windows, see Owner-Drawn Status Windows.

You retrieve the widths of the borders of a status window by sending the window an SB_GETBORDERS message. The message includes the pointer to a three element array that receives the widths.


 Multiple-Part Status Windows

A status window can have many different parts, each displaying a different line of text. You divide a status window into parts by sending the window an SB_SETPARTS message, specifying the number of parts to create and the pointer to an integer array. The array contains one element for each part, and each element specifies the client coordinate of the right edge of a part.

A status window can have a maximum of 255 parts, although applications typically use far fewer than that. You retrieve a count of the parts in a status window, as well as the coordinate of the right edge of each part, by sending the window an SB_GETPARTS message.


 Status Window Text Operations

You set the text of any part of a status window by sending the SB_SETTEXT message, specifying the zero-based index of a part, a pointer to the string to draw in the part, and the technique for drawing the string. The drawing technique determines whether the text has a border and, if it does, the style of the border. It also determines whether the parent window is responsible for drawing the text. For more information, see the following topic.

By default, text is left-aligned within the specified part of a status window. You can embed tab characters (\ t) in the text to center or right-align it. Text to the right of a single tab character is centered, and text to the right of a second tab character is right-aligned.

To retrieve text from a status window, use the SB_GETTEXTLENGTH and SB_GETTEXT messages.

If your application uses a status window that has only one part, you can use the WM_SETTEXT, WM_GETTEXT, and WM_GETTEXTLENGTH messages to perform text operations. These messages deal only with the part that has an index of zero, allowing you to treat the status window much like a static text control.

To display a line of status without creating a status window, use the DrawStatusText function. The function uses the same techniques to draw the status as the window procedure for the status window, but it does not automatically set the size and position of the status information. When calling the function, you must specify the size and position of the status information, as well as the device context of the window in which to draw it.


 Owner-Drawn Status Windows

You can define individual parts of a status window to be owner-drawn parts. Using this technique gives you more control than you would otherwise have over the appearance of the window part. For example, you can display a bitmap rather than text in a part or draw text using a different font.

To define a window part as owner-drawn, send the SB_SETTEXT message to the status window, specifying the part and the SBT_OWNERDRAW drawing technique. When SBT_OWNERDRAW is specified, the lParam parameter is a 32-bit application-defined value that the application can use when drawing the part. For example, you can specify a font handle, a bitmap handle, a pointer to a string, and so on.

When a status window needs to draw an owner-drawn part, it sends the WM_DRAWITEM message to the parent window. The wParam parameter of the message is the child window identifier of the status window, and the lParam parameter is a pointer to a DRAWITEMSTRUCT structure. The parent window uses the information in the structure to draw the part. For an owner-drawn part of a status window, DRAWITEMSTRUCT contains the following information.

Member	Description
CtlType	Undefined; do not use.
CtlID	Child-window identifier of the status window.
itemID	Zero-based index of the part to be drawn.
itemAction	Undefined; do not use.
itemState	Undefined; do not use.
hwndItem	Handle to the status window.
hDC	Handle to the device context of the status window.
rcItem	Coordinates of the window part to be drawn. The coordinates are relative to the upper left corner of the status window.
itemData	Application-defined 32-bit value specified in the lParam parameter of the SB_SETTEXT message.


 Simple Mode Status Windows

You put a status window into "simple mode" by sending it an SB_SIMPLE message. A simple mode status window displays only one part. When the text of the window is set, the window is invalidated, but it is not redrawn until the next WM_PAINT message. Waiting for the message reduces screen flicker by minimizing the number of times the window is redrawn. A simple mode status window is useful for displaying help text for menu items while the user is scrolling through a menu.

The string that a status window displays while in simple mode is maintained separately from the strings that it displays while not in simple mode. This means that you can put the window in simple mode, set its text, and switch back to nonsimple mode without the text being used in either mode.

When setting the text of a simple mode status window, you can specify any drawing technique except SBT_OWNERDRAW. A simple mode status window does not support owner drawing.


 Default Status Window Message Processing

This section describes the window messages handled by the window procedure for the predefined STATUSCLASSNAME window class.

Message	Default processing
WM_CREATE	Initializes the status window.
WM_DESTROY	Frees resources allocated for the status window.
WM_GETFONT	Returns the handle to the current font with which the status window draws its text.
WM_GETTEXT	Copies the text from the first part of a status window to a buffer. It returns a 32-bit value that specifies the length, in characters, of the text and the technique used to draw the text.
WM_GETTEXTLENGTH	Returns a 32-bit value that specifies the length, in characters, of the text in the first part of a status window and the technique used to draw the text.
WM_NCHITTEST	Returns the HTBOTTOMRIGHT value if the mouse cursor is in the sizing grip, causing the system to display the sizing cursor. If the mouse cursor is not in the sizing grip, the status window passes this message to the DefWindowProc function.
WM_PAINT	Paints the invalid region of the status window.
WM_SETFONT	Selects the font handle into the device context for the status window.
WM_SETTEXT	Copies the specified text into the first part of a status window, using the default drawing operation (specified as zero). It returns TRUE if successful or FALSE otherwise.
WM_SIZE	Resizes the status window based on the current width of the parent window's client area and the height of the current font of the status window.


 Using Status Windows

The following example creates a status window that has a sizing grip and divides the window into four equal parts based on the width of the parent window's client area.

// DoCreateStatusWindow - creates a status window and divides it into

//     the specified number of parts.

// Returns the handle to the status window.

// hwndParent - parent window for the status window

// nStatusID - child window identifier

// hinst - handle to the application instance

// nParts - number of parts into which to divide the status window

HWND DoCreateStatusWindow(HWND hwndParent, int nStatusID,

    HINSTANCE hinst, int nParts)

{

    HWND hwndStatus;

    RECT rcClient;

    HLOCAL hloc;

    LPINT lpParts;

    int i, nWidth;

    // Ensure that the common control DLL is loaded.

    InitCommonControls();

    // Create the status window.

    hwndStatus = CreateWindowEx(

        0,                       // no extended styles

        STATUSCLASSNAME,         // name of status window class

        (LPCTSTR) NULL,          // no text when first created

        SBARS_SIZEGRIP |         // includes a sizing grip

        WS_CHILD,                // creates a child window

        0, 0, 0, 0,              // ignores size and position

        hwndParent,              // handle to parent window

        (HMENU) nStatusID,       // child window identifier

        hinst,                   // handle to application instance

        NULL);                   // no window creation data

    // Get the coordinates of the parent window's client area.

    GetClientRect(hwndParent, &rcClient);

    // Allocate an array for holding the right edge coordinates.

    hloc = LocalAlloc(LHND, sizeof(int) * nParts);

    lpParts = LocalLock(hloc);

    // Calculate the right edge coordinate for each part, and

    // copy the coordinates to the array.

    nWidth = rcClient.right / nParts;

    for (i = 0; i < nParts; i++) {

        lpParts[i] = nWidth;

        nWidth += nWidth;

    }

    // Tell the status window to create the window parts.

    SendMessage(hwndStatus, SB_SETPARTS, (WPARAM) nParts,

        (LPARAM) lpParts);

    // Free the array, and return.

    LocalUnlock(hloc);

    LocalFree(hloc);

    return hwndStatus;

}


 Status Window Reference

The following functions and messages are associated with status windows. These elements can be grouped as follows.

Creation

CreateStatusWindow

Size and Height

SB_GETRECT
SB_SETMINHEIGHT
SB_GETBORDERS

Text Operations

DrawStatusText
MenuHelp
SB_GETTEXT
SB_GETTEXTLENGTH
SB_SETTEXT

Multiple Part Status Windows

SB_GETPARTS
SB_SETPARTS

Simple Mode Status Windows

SB_SIMPLE


 Status Window Functions

The following functions are used with status windows.

CreateStatusWindow
DrawStatusText
MenuHelp


 Status Window Messages

The following messages are used with status windows.

SB_GETBORDERS
SB_GETPARTS
SB_GETRECT
SB_GETTEXT
SB_GETTEXTLENGTH
SB_SETMINHEIGHT
SB_SETPARTS
SB_SETTEXT
SB_SIMPLE


 Tab Controls

A tab control is analogous to the dividers in a notebook or the labels in a file cabinet. By using a tab control, an application can define multiple pages for the same area of a window or dialog box. Each page consists of a set of information or a group of controls that the application displays when the user selects the corresponding tab. A special type of tab control displays tabs that look like buttons. Clicking a button should immediately perform a command instead of displaying a page.


 About Tab Controls

You can create a tab control by calling the CreateWindowEx function, specifying the WC_TABCONTROL window class. This window class is registered when the common controls dynamic-link library (DLL) is loaded. To ensure that the DLL is loaded, use the InitCommonControls function.

You send messages to a tab control to add tabs and otherwise affect the control's appearance and behavior. Each message has a corresponding macro, which you can use instead of sending the message explicitly. You cannot, however, disable an individual tab in a tab control. However, you can disable a tab control in a property sheet by disabling the corresponding page.


 About Tab Control Styles

You can apply specific characteristics to tab controls by specifying tab control styles (window styles specific to tab controls). For example, you can specify the alignment and general appearance of the tabs in a tab control.

You can cause the tabs to look like buttons by specifying the TCS_BUTTONS style. Tabs in this type of tab control should serve the same function as button controls; that is, clicking a tab should carry out a command instead of displaying a page. Because the display area in a button tab control is typically not used, no border is drawn around it.

You can cause a tab to receive the input focus when clicked by specifying the TCS_FOCUSONBUTTONDOWN style. This style is typically used only with the TCS_BUTTONS style. You can specify that a tab never receives the input focus by using the TCS_FOCUSNEVER style.

By default, a tab control displays only one row of tabs. If not all tabs can be shown at once, the tab control displays an up-down control so that the user can scroll additional tabs into view. For more information about up-down controls, see Up-Down Controls. You can cause a tab control to display multiple rows of tabs, if necessary, by specifying the TCS_MULTILINE style. In this way, all tabs can be displayed at once. The tabs are left-aligned within each row unless you specify the TCS_RIGHTJUSTIFY style. In this case, the width of each tab is increased so that each row of tabs fills the entire width of the tab control.

A tab control automatically sizes each tab to fit its icon, if any, and its label. To give all tabs the same width, you can specify the TCS_FIXEDWIDTH style. The control sizes all the tabs to fit the widest label, or you can assign a specific width and height by using the TCM_SETITEMSIZE message. Within each tab, the control centers the icon and label with the icon to the left of the label. You can force the icon to the left, leaving the label centered, by specifying the TCS_FORCEICONLEFT style. You can left-align both the icon and label by using the TCS_FORCELABELLEFT style. You cannot use the TCS_FIXEDWIDTH style with the TCS_RIGHTJUSTIFY style.

You can specify that the parent window draws the tabs in the control by using the TCS_OWNERDRAWFIXED style. For more information about owner-drawn tabs, see Owner-Drawn Tabs.

You can specify that a tab control create a tool tip control by using the TCS_TOOLTIPS style. For more information about using tool tip controls with a tab control, see Tooltip Controls.


 Tabs and Tab Attributes

Each tab in a tab control consists of an icon, a label, and application-defined data. This information is specified by a TC_ITEM structure. You can add tabs to a tab control, get the number of tabs, retrieve and set the contents of a tab, and delete tabs. Tabs are identified by their zero-based index.

To add tabs to a tab control, use the TCM_INSERTITEM message, specifying the position of the item and the address of a TC_ITEM structure. You can retrieve and set the contents of an existing tab by using the TCM_GETITEM and TCM_SETITEM messages. For each tab, you can specify an icon, a label, or both. You can also specify application-defined data to associate with the tab.

You can retrieve the current number of tabs by using the TCM_GETITEMCOUNT message, delete a tab by using the TCM_DELETEITEM message, and delete all tabs in a tab control by using the TCM_DELETEALLITEMS message.

You can associate application-defined data with each tab. For example, you might save information about each page with its corresponding tab. By default, a tab control allocates four extra bytes per tab for application-defined data. You can change the number of extra bytes per tab by using the TCM_SETITEMEXTRA message. You can only use this message when the tab control is empty.

The application-defined data is specified by the lParam member of the TC_ITEM structure. If you use more than four bytes of application-defined data, you need to define your own structure and use it instead of TC_ITEM. You can retrieve and set application-defined data the same way you retrieve and set other information about a tab — by using the TCM_GETITEM and TCM_SETITEM messages.

The first member of your structure must be a TC_ITEMHEADER structure, and the remaining members must specify application-defined data. TC_ITEMHEADER is identical to TC_ITEM, except it does not have the lParam member. The difference between the size of your structure and the size of TC_ITEMHEADER should equal the number of extra bytes per tab.


 Display Area

The display area of a tab control is the area in which an application displays the current page. Typically, an application creates a child window or dialog box, setting the window size and position to fit the display area. Given the window rectangle for a tab control, you can calculate the bounding rectangle of the display area by using the TCM_ADJUSTRECT message.

Sometimes the display area must be a particular size — for example, the size of a modeless child dialog box. Given the bounding rectangle for the display area, you can use TCM_ADJUSTRECT to calculate the corresponding window rectangle for the tab control.


 Tab Selection

When the user selects a tab, a tab control sends its parent window notification messages in the form of WM_NOTIFY messages. The TCN_SELCHANGING notification message is sent before the selection changes, and the TCN_SELCHANGE notification message is sent after the selection changes.

You can process TCN_SELCHANGING to save the state of the outgoing page. You can return TRUE to prevent the selection from changing. For example, you might not want to switch away from a child dialog box in which a control has an invalid setting.

You must process TCN_SELCHANGE to display the incoming page in the display area. This might simply entail changing the information displayed in a child window. More often, each page consists of a child window or dialog box. In this case, an application might process this notification by destroying or hiding the outgoing child window or dialog box and by creating or showing the incoming child window or dialog box.

You can retrieve and set the current selection by using the TCM_GETCURSEL and TCM_SETCURSEL messages.


 Tab Control Image Lists

Each tab can have an icon associated with it, which is specified by an index into the image list for the tab control. When a tab control is created, it has no image list associated with it. An application can create an image list by using the ImageList_Create function and then assign it to a tab control by using the TCM_SETIMAGELIST message.

You can add images to a tab control's image list just as you would to any other image list. However, an application should remove images by using the TCM_REMOVEIMAGE message instead of the ImageList_Remove function. This message ensures that each tab remains associated with the same image it had been.

Destroying a tab control does not destroy an image list that is associated with it. You must destroy the image list separately. This is useful if you want to assign the same image list to multiple tab controls.

To retrieve the handle of the image list currently associated with a tab control, you can use the TCM_GETIMAGELIST message.


 Tab Size and Position

Each tab in a tab control has a size and position. You can set the size of tabs, retrieve the bounding rectangle of a tab, or determine which tab is at a specified position.

For fixed-width and owner-drawn tab controls, you can set the exact width and height of tabs by using the TCM_SETITEMSIZE message. In other tab controls, each tab's size is calculated based on the icon and label for the tab. The tab control includes space for a border and an additional margin. You can set the thickness of the margin by using the TCM_SETPADDING message.

You can determine the current bounding rectangle for a tab by using the TCM_GETITEMRECT message. You can determine which tab, if any, is at a specified location by using the TCM_HITTEST message.

In a tab control with the TCS_MULTILINE style, you can determine the current number of rows of tabs by using the TCM_GETROWCOUNT message.


 Owner-Drawn Tabs

If a tab control has the TCS_OWNERDRAWFIXED style, the parent window must paint tabs by processing the WM_DRAWITEM message. The tab control sends this message whenever a tab needs to be painted. The lParam parameter specifies the address of a DRAWITEMSTRUCT structure, which contains the index of the tab, its bounding rectangle, and the device context (DC) in which to draw.

By default, the itemData member of DRAWITEMSTRUCT contains the value of the lParam member of the TC_ITEM structure. However, if you change the amount of application-defined data per tab, itemData contains a pointer to the data instead. You can change the amount of application-defined data per tab by using the TCM_SETITEMEXTRA message.

To specify the size of items in a tab control, the parent window must process the WM_MEASUREITEM message. Because all tabs in an owner-drawn tab control are the same size, this message is sent only once. There is no tab control style for owner-drawn tabs of varying size. You can also set the width and height of tabs by using the TCM_SETITEMSIZE message.


 Tooltip Controls

You can use a tooltip control to provide a brief description of each tab in a tab control. A tab control that has the TCS_TOOLTIPS style creates a tooltip control when it is created, and when the tab control is destroyed, it destroys the tooltip control. You can also create a tooltip control and assign it to a tab control.

If you use a tooltip control with a tab control, the parent window must process the TTN_NEEDTEXT notification message to provide a description of each tab on request.

To use the same tooltip control with more than one tab control, create the tooltip control yourself and assign it to the tab control by using the TCM_SETTOOLTIPS message. You can get the handle of a tab control's current tooltip control by using the TCM_GETTOOLTIPS message. If you use this method, you should not use the TCS_TOOLTIPS style. For more information about tooltip controls, see Tooltip Controls.


 Default Tab Control Message Processing

This section describes the message processing performed by a tab control. Messages specific to tab controls are discussed elsewhere and are, therefore, not included here.

Message	Processing performed
WM_CAPTURECHANGED	Does nothing if the tab control released the mouse capture itself. If another window captured the mouse and a button is held down, the command releases the button.
WM_CREATE	Allocates and initializes an internal data structure. The control creates a tool tip control if the TCS_TOOLTIPS style is specified.
WM_DESTROY	Frees resources allocated during WM_CREATE processing.
WM_GETDLGCODE	Returns a combination of the DLGC_WANTARROWS and DLGC_WANTCHARS values.
WM_GETFONT	Returns the handle of the font used for labels.
WM_KEYDOWN	Processes DIRECTION keys and changes the selection, if appropriate.
WM_KILLFOCUS	Invalidates the tab that has the focus, so it will be repainted to reflect an unfocused state.
WM_LBUTTONDOWN	Forwards the message to the tool tip control, if any, and changes the selection if the user is clicking a tab. If the user is clicking a button, the control redraws the button to give a sunken appearance and captures the mouse. If the user is clicking either a tab or button and the TCS_FOCUSONBUTTONDOWN style is specified, the control sets the focus to itself.
WM_LBUTTONUP	Releases the mouse if a button was pressed. If the cursor is over the button and is being held down, the control changes the selection accordingly and redraws the button.
WM_MOUSEMOVE	Forwards the message to the tool tip control, if any. If the TCS_BUTTONS style is specified and the mouse button is being held down after clicking, the control may also redraw the affected button to give it a raised or sunken appearance.
WM_NOTIFY	Forwards notification messages sent by the tool tip control.
WM_PAINT	Draws a border around the display area (unless the TCS_BUTTONS style is specified) and paints any tabs that intersect the invalid rectangle. For each tab, it draws the body of each tab (or sends a WM_DRAWITEM message to the parent window) and then draws a border around the tab.
WM_RBUTTONDOWN	Sends an NM_RCLICK notification message to the parent window.
WM_SETFOCUS	Invalidates the tab that has the focus so that it will be repainted to reflect a focused state.
WM_SETFONT	Sets the font used for labels.
WM_SETREDRAW	Sets the state of an internal flag that determines whether the control is repainted when items are inserted and deleted, when the font is changed, and so on.
WM_SIZE	Recalculates the positions of tabs and may invalidate part of the tab control to force repainting of some or all tabs.


 Using Tab Controls

This section provides two examples that use tab controls. The first example uses a tab control to switch between multiple pages of text in an application's main window. The second example uses a tab control to switch between multiple pages of controls in a dialog box.

•	Creating a tab control

•	Creating a tabbed dialog box


 Creating a Tab Control

The example in this section creates a tab control and displays it in the client area of the application's main window. The application displays a third window (a static control) in the display area of the tab control. The parent window positions and sizes the tab control and static control when it processes the WM_SIZE message.

There are seven tabs, one for each day of the week. When the user selects a tab, the application displays the name of the corresponding day in the static control. The following global variables are used in this example.

// Global variables

HINSTANCE g_hinst;    // handle of application instance

char g_achTemp[256];  // temporary buffer for strings

HWND g_hwndMain;      // main application window

HWND g_hwndTab;       // tab control

HWND g_hwndDisplay;   // handle of static control in

                      //   tab control's display area

The following function creates the tab control and adds a tab for each day of the week. The names of the days are defined as string resources, consecutively numbered starting with IDS_FIRSTDAY (defined in the application's header file). Both the parent window and the tab control must have the WS_CLIPSIBLINGS window style. The application's initialization function calls this function after creating the main window.

// DoCreateTabControl - creates a tab control, sized to fit the

//     specified parent window's client area, and adds some tabs.

// Returns the handle of the tab control.

// hwndParent - parent window (the application's main window)

HWND WINAPI DoCreateTabControl(HWND hwndParent)

{

    RECT rcClient;

    HWND hwndTab;

    TC_ITEM tie;

    int i;

    // Get the dimensions of the parent window's client area, and

    // create a tab control child window of that size.

    GetClientRect(hwndParent, &rcClient);

    InitCommonControls();

    hwndTab = CreateWindow(

        WC_TABCONTROL, "",

        WS_CHILD | WS_CLIPSIBLINGS | WS_VISIBLE,

        0, 0, rcClient.right, rcClient.bottom,

        hwndParent, NULL, g_hinst, NULL

        );

    if (hwndTab == NULL)

        return NULL;

    // Add tabs for each day of the week.

    tie.mask = TCIF_TEXT | TCIF_IMAGE;

    tie.iImage = -1;

    tie.pszText = g_achTemp;

    for (i = 0; i < 7; i++) {

        LoadString(g_hinst, IDS_FIRSTDAY + i,

                g_achTemp, sizeof(g_achTemp));

        if (TabCtrl_InsertItem(hwndTab, i, &tie) == -1) {

            DestroyWindow(hwndTab);

            return NULL;

        }

    }

    return hwndTab;

}

The following function creates the static control that occupies the tab control's display area. The application's initialization function calls this function after creating the main window and the tab control.

// DoCreateDisplayWindow - creates a child window (a static

//     control) to occupy the tab control's display area.

// Returns the handle of the static control.

// hwndParent - parent window (the application's main window)

HWND WINAPI DoCreateDisplayWindow(HWND hwndParent)

{

    HWND hwndStatic = CreateWindow("STATIC", "",

        WS_CHILD | WS_VISIBLE | WS_BORDER,

        0, 0, CW_USEDEFAULT, CW_USEDEFAULT,

        hwndParent, NULL, g_hinst, NULL);

    return hwndStatic;

}

Following are the relevant portions of the application's window procedure. The application processes the WM_SIZE message to position and size the tab control and the static control. To determine the appropriate position and size for the static control, this example sends the tab control a TCM_ADJUSTRECT message (by using the TabCtrl_AdjustRect macro).

When a tab is selected, the tab control sends a WM_NOTIFY message, specifying the TCN_SELCHANGE notification message. The application processes this notification message by setting the text of the static control.

// MainWindowProc - processes the message for the main window class.

// The return value depends on the message.

// hwnd - handle of the window

// uMsg - identifier for the message

// wParam - message-specific parameter

// lParam - message-specific parameter

LRESULT CALLBACK MainWindowProc(

        HWND hwnd,

        UINT uMsg,

        WPARAM wParam,

        LPARAM lParam

        )

{

    switch (uMsg) {

        case WM_SIZE: {

                HDWP hdwp;

                RECT rc;

                // Calculate the display rectangle, assuming the

                // tab control is the size of the client area.

                SetRect(&rc, 0, 0,

                        LOWORD(lParam), HIWORD(lParam));

                TabCtrl_AdjustRect(g_hwndTab, FALSE, &rc);

                // Size the tab control to fit the client area.

                hdwp = BeginDeferWindowPos(2);

                DeferWindowPos(hdwp, g_hwndTab, NULL, 0, 0,

                    LOWORD(lParam), HIWORD(lParam),

                    SWP_NOMOVE | SWP_NOZORDER

                    );

                // Position and size the static control to fit the

                // tab control's display area, and make sure the

                // static control is in front of the tab control.

                DeferWindowPos(hdwp,

                    g_hwndDisplay, HWND_TOP, rc.left, rc.top,

                    rc.right - rc.left, rc.bottom - rc.top, 0

                    );

                EndDeferWindowPos(hdwp);

            }

            break;

        case WM_NOTIFY:

            switch (HIWORD(wParam)) {

                case 0:

                    .

                    .    // menu command processing

                    .

                case TCN_SELCHANGE: {

                        int iPage = TabCtrl_GetCurSel(g_hwndTab);

                        LoadString(g_hinst, IDS_FIRSTDAY + iPage,

                            g_achTemp, sizeof(g_achTemp));

                        SendMessage(g_hwndDisplay, WM_SETTEXT, 0

                            (LPARAM) g_achTemp);

                    }

                    break;

            }

            break;

            .

            .       // additional message processing

            .

        default:

            return DefWindowProc(hwnd, uMsg, wParam, lParam);

    }

    return 0;

}


 Creating a Tabbed Dialog Box

The example in this section creates a dialog box that uses tabs to provide multiple pages of controls. The main dialog box is a modal dialog box. Each page of controls is defined by a dialog box template that specifies the WS_CHILD style. When a tab is selected, the example creates a modeless dialog box for the incoming page and destroys the dialog box for the outgoing page.

Note  In many cases, you can implement multiple-page dialog boxes more easily by using property sheets. For more information about property sheets, see Property Sheets.

The template for the main dialog box simply defines two button controls. When processing the WM_INITDIALOG message, the dialog box procedure creates a tab control and loads the dialog template resources for each of the child dialog boxes.

The information is saved in an application-defined structure called DLGHDR. A pointer to this structure is associated with the dialog box window by using the SetWindowLong function. The structure is defined in the application's header file, as follows.

#define C_PAGES 3

typedef struct tag_dlghdr {

    HWND hwndTab;       // tab control

    HWND hwndDisplay;   // current child dialog box

    RECT rcDisplay;     // display rectangle for the tab control

    DLGTEMPLATE *apRes[C_PAGES];

} DLGHDR;

The following function processes the WM_INITDIALOG message for the main dialog box. The function allocates the DLGHDR structure, loads the dialog template resources for the child dialog boxes, and creates the tab control.

The size of each child dialog box is specified by the DLGTEMPLATE structure. The function examines the size of each dialog box and uses the macro for the TCM_ADJUSTRECT message to calculate an appropriate size for the tab control. Then it sizes the dialog box and positions the two buttons accordingly. This example sends TCM_ADJUSTRECT by using the TabCtrl_AdjustRect macro.

VOID WINAPI OnTabbedDialogInit(HWND hwndDlg)

{

    DLGHDR *pHdr = (DLGHDR *) LocalAlloc(LPTR, sizeof(DLGHDR));

    DWORD dwDlgBase = GetDialogBaseUnits();

    int cxMargin = LOWORD(dwDlgBase) / 4;

    int cyMargin = HIWORD(dwDlgBase) / 8;

    TC_ITEM tie;

    RECT rcTab;

    HWND hwndButton;

    RECT rcButton;

    int i;

    // Save a pointer to the DLGHDR structure.

    SetWindowLong(hwndDlg, GWL_USERDATA, (LONG) pHdr);

    // Create the tab control.

    pHdr->hwndTab = CreateWindow(

        WC_TABCONTROL, "",

        WS_CHILD | WS_CLIPSIBLINGS | WS_VISIBLE,

        0, 0, 100, 100,

        hwndDlg, NULL, g_hinst, NULL

        );

    // Add a tab for each of the three child dialog boxes.

    tie.mask = TCIF_TEXT | TCIF_IMAGE;

    tie.iImage = -1;

    tie.pszText = "First";

    TabCtrl_InsertItem(pHdr->hwndTab, 0, &tie);

    tie.pszText = "Second";

    TabCtrl_InsertItem(pHdr->hwndTab, 1, &tie);

    tie.pszText = "Third";

    TabCtrl_InsertItem(pHdr->hwndTab, 2, &tie);

    // Lock the resources for the three child dialog boxes.

    pHdr->apRes[0] = DoLockDlgRes(MAKEINTRESOURCE(DLG_FIRST));

    pHdr->apRes[1] = DoLockDlgRes(MAKEINTRESOURCE(DLG_SECOND));

    pHdr->apRes[2] = DoLockDlgRes(MAKEINTRESOURCE(DLG_THIRD));

    // Determine the bounding rectangle for all child dialog boxes.

    SetRectEmpty(&rcTab);

    for (i = 0; i < C_PAGES; i++) {

        if (pHdr->apRes[i]->cx > rcTab.right)

            rcTab.right = pHdr->apRes[i]->cx;

        if (pHdr->apRes[i]->cy > rcTab.bottom)

            rcTab.bottom = pHdr->apRes[i]->cy;

    }

    rcTab.right = rcTab.right * LOWORD(dwDlgBase) / 4;

    rcTab.bottom = rcTab.bottom * HIWORD(dwDlgBase) / 8;

    // Calculate how large to make the tab control, so

    // the display area can accomodate all the child dialog boxes.

    TabCtrl_AdjustRect(pHdr->hwndTab, TRUE, &rcTab);

    OffsetRect(&rcTab, cxMargin - rcTab.left,

            cyMargin - rcTab.top);

    // Calculate the display rectangle.

    CopyRect(&pHdr->rcDisplay, &rcTab);

    TabCtrl_AdjustRect(pHdr->hwndTab, FALSE, &pHdr->rcDisplay);

    // Set the size and position of the tab control, buttons,

    // and dialog box.

    SetWindowPos(pHdr->hwndTab, NULL, rcTab.left, rcTab.top,

            rcTab.right - rcTab.left, rcTab.bottom - rcTab.top,

            SWP_NOZORDER);

    // Move the first button below the tab control.

    hwndButton = GetDlgItem(hwndDlg, BTN_CLOSE);

    SetWindowPos(hwndButton, NULL,

            rcTab.left, rcTab.bottom + cyMargin, 0, 0,

            SWP_NOSIZE | SWP_NOZORDER);

    // Determine the size of the button.

    GetWindowRect(hwndButton, &rcButton);

    rcButton.right -= rcButton.left;

    rcButton.bottom -= rcButton.top;

    // Move the second button to the right of the first.

    hwndButton = GetDlgItem(hwndDlg, BTN_TEST);

    SetWindowPos(hwndButton, NULL,

        rcTab.left + rcButton.right + cxMargin,

        rcTab.bottom + cyMargin, 0, 0,

        SWP_NOSIZE | SWP_NOZORDER);

    // Size the dialog box.

    SetWindowPos(hwndDlg, NULL, 0, 0,

        rcTab.right + cyMargin +

        2 * GetSystemMetrics(SM_CXDLGFRAME),

        rcTab.bottom + rcButton.bottom + 2 * cyMargin +

        2 * GetSystemMetrics(SM_CYDLGFRAME) +

        GetSystemMetrics(SM_CYCAPTION),

        SWP_NOMOVE | SWP_NOZORDER);

    // Simulate selection of the first item.

    OnSelChanged(hwndDlg);

}

// DoLockDlgRes - loads and locks a dialog template resource.

// Returns a pointer to the locked resource.

// lpszResName - name of the resource

DLGTEMPLATE * WINAPI DoLockDlgRes(LPCSTR lpszResName)

{

    HRSRC hrsrc = FindResource(NULL, lpszResName, RT_DIALOG);

    HGLOBAL hglb = LoadResource(g_hinst, hrsrc);

    return (DLGTEMPLATE *) LockResource(hglb);

}

The following function processes the TCN_SELCHANGE notification message for the main dialog box. The function destroys the dialog box for the outgoing page, if any. Then it uses the CreateDialogIndirect function to create a modeless dialog box for the incoming page.

// OnSelChanged - processes the TCN_SELCHANGE notification.

// hwndDlg - handle of the parent dialog box

VOID WINAPI OnSelChanged(HWND hwndDlg)

{

    DLGHDR *pHdr = (DLGHDR *) GetWindowLong(

        hwndDlg, GWL_USERDATA);

    int iSel = TabCtrl_GetCurSel(pHdr->hwndTab);

    // Destroy the current child dialog box, if any.

    if (pHdr->hwndDisplay != NULL)

        DestroyWindow(pHdr->hwndDisplay);

    // Create the new child dialog box.

    pHdr->hwndDisplay = CreateDialogIndirect(g_hinst,

        pHdr->apRes[iSel], hwndDlg, ChildDialogProc);

}

The following function processes the WM_INITDIALOG message for each of the child dialog boxes. You cannot specify the position of a dialog box created using the CreateDialogIndirect function. This function uses the SetWindowPos function to position the child dialog within the tab control's display area.

// OnChildDialogInit - Positions the child dialog box to fall

//     within the display area of the tab control.

VOID WINAPI OnChildDialogInit(HWND hwndDlg)

{

    HWND hwndParent = GetParent(hwndDlg);

    DLGHDR *pHdr = (DLGHDR *) GetWindowLong(

        hwndParent, GWL_USERDATA);

    SetWindowPos(hwndDlg, HWND_TOP,

        pHdr->rcDisplay.left, pHdr->rcDisplay.top,

        0, 0, SWP_NOSIZE);

}


 Tab Control Reference

The messages, notification messages, and structures are associated with tab controls. These elements can be grouped as follows.

Tabs and Tab Attributes

TC_ITEM
TC_ITEMHEADER
TCM_DELETEALLITEMS
TCM_DELETEITEM
TCM_GETITEM
TCM_INSERTITEM
TCM_SETITEM
TCM_SETITEMEXTRA

Tab Selection

TCM_GETCURFOCUS
TCM_GETCURSEL
TCM_SETCURSEL
TCN_SELCHANGE
TCN_SELCHANGING

Tab Size and Position

TC_HITTESTINFO
TCM_ADJUSTRECT
TCM_GETITEMRECT
TCM_GETROWCOUNT
TCM_HITTEST
TCM_SETITEMSIZE
TCM_SETPADDING

Miscellaneous

TC_KEYDOWN
TCM_GETIMAGELIST
TCM_GETITEMCOUNT
TCM_GETTOOLTIPS
TCM_REMOVEIMAGE
TCM_SETIMAGELIST
TCM_SETTOOLTIPS
TCN_KEYDOWN


 Tab Control Messages

An application sends messages to add tabs and otherwise control the appearance and behavior of a tab control. Each message has a corresponding macro, which you can use instead of sending the message explicitly.

TCM_ADJUSTRECT
TCM_DELETEALLITEMS
TCM_DELETEITEM
TCM_GETCURFOCUS
TCM_GETCURSEL
TCM_GETIMAGELIST
TCM_GETITEM
TCM_GETITEMCOUNT
TCM_GETITEMRECT
TCM_GETROWCOUNT
TCM_GETTOOLTIPS
TCM_HITTEST
TCM_INSERTITEM
TCM_REMOVEIMAGE
TCM_SETCURSEL
TCM_SETIMAGELIST
TCM_SETITEM
TCM_SETITEMEXTRA
TCM_SETITEMSIZE
TCM_SETPADDING
TCM_SETTOOLTIPS


 Tab Control Notification Messages

The following notification messages are used with tab controls.

TCN_KEYDOWN
TCN_SELCHANGE
TCN_SELCHANGING


 Tab Control Structures

The following structures are used with tab controls.

TC_HITTESTINFO
TC_ITEM
TC_ITEMHEADER
TC_KEYDOWN


 Tab Control Styles

The following window styles are specific to tab controls.

TCS_BUTTONS	Specifies that tabs appear as buttons and no border is drawn around the display area.
TCS_FIXEDWIDTH	Specifies that all tabs are the same width. This style cannot be combined with the TCS_RIGHTJUSTIFY style.
TCS_FOCUSNEVER	Specifies that the tab control never receives the input focus.
TCS_FOCUSONBUTTONDOWN	Specifies that tabs receive the input focus when clicked.
TCS_FORCEICONLEFT	Aligns icons with the left edge of each fixed-width tab. This style can only be used with the TCS_FIXEDWIDTH style.
TCS_FORCELABELLEFT	Aligns labels with the left edge of each fixed-width tab; that is, it displays the label immediately to the right of the icon instead of centering it. This style can only be used with the TCS_FIXEDWIDTH style, and it implies the TCS_FORCEICONLEFT style.
TCS_MULTILINE	Displays multiple rows of tabs, if necessary, so all tabs are visible at once.
TCS_OWNERDRAWFIXED	Specifies that the parent window is responsible for drawing tabs.
TCS_RAGGEDRIGHT	Does not stretch each row of tabs to fill the entire width of the control. This style is the default.
TCS_RIGHTJUSTIFY	Increases the width of each tab, if necessary, so that each row of tabs fills the entire width of the tab control.  This window style is ignored unless the TCS_MULTILINE style is also specified.
TCS_SINGLELINE	Displays only one row of tabs. The user can scroll to see more tabs, if necessary. This style is the default.
TCS_TABS	Specifies that tabs appear as tabs and that a border is drawn around the display area. This style is the default.
TCS_TOOLTIPS	Specifies that the tab control has a tooltip control associated with it. For more information about tooltip controls, see Tooltip Controls.


 Toolbars

A toolbar is a control window that contains one or more buttons. Each button sends a command message to the parent window when the user chooses it.


 About Toolbars

Typically, the buttons in a toolbar correspond to items in the application's menu, providing an additional and more direct way for the user to access an application's commands. The following illustration shows a window that has a toolbar positioned below the menu bar.

A toolbar has built-in customization features, including a system-defined customization dialog box, that allow the user to insert, delete, or rearrange toolbar buttons. An application determines whether the customization features are available to the user and controls the extent to which the user may customize the toolbar.


 Toolbar Creation

You can use the CreateToolbarEx function to create a toolbar and add an initial set of buttons to it. You can also use the CreateWindowEx function, specifying the TOOLBARCLASSNAME window class, but this second method creates a toolbar that initially contains no buttons. You add buttons to the toolbar by using the TB_ADDBUTTONS or TB_INSERTBUTTON message.

The TOOLBARCLASSNAME window class is registered when the common control dynamic-link library (DLL) is loaded. To ensure that this DLL is loaded, use the InitCommonControls function first.

A toolbar must be created as a child window with the WS_CHILD style. If you use CreateWindowEx to create a toolbar, you must specify the WS_CHILD window style. CreateToolbarEx includes the WS_CHILD style by default. You must specify the initial parent window when creating the toolbar, but you can change the parent window after creation by using the TB_SETPARENT message.


 Toolbar Size and Position

The window procedure for a toolbar automatically sets the size and position of the toolbar window. The height is based on the height of the buttons in the toolbar. The width is the same as the width of the parent window's client area. The CCS_TOP and CCS_BOTTOM common control styles determine whether the toolbar is positioned along the top or bottom of the client area. By default, a toolbar has the CCS_TOP style.

The toolbar window procedure automatically adjusts the size of the toolbar whenever it receives a WM_SIZE or TB_AUTOSIZE message. An application should send either of these messages whenever the size of the parent window changes or after sending a message that requires the size of the toolbar to be adjusted — for example, the TB_SETBUTTONSIZE message.


 Tooltip Style

There is only one class-specific style associated with toolbars: TBSTYLE_TOOLTIPS. When you specify this style, the toolbar creates and manages a tooltip control. A tooltip control is a small pop-up window that contains a line of text describing a toolbar button. The tooltip control is hidden and appears only when the user puts the cursor on a toolbar button, leaving it there for approximately one second. The tooltip control is displayed near the cursor.

When the toolbar receives a WM_MOUSEMOVE message, it sends a notification message to the tooltip control. The tooltip control sets a timer, and after approximately one second, checks if the cursor is still at the same location and is on a toolbar button. If it is, the tooltip control sends the TTN_NEEDTEXT notification message to the parent window to retrieve the descriptive text for the button. Then the tooltip control creates a pop-up window and displays the text in the window. The tooltip control destroys the pop-up window when the user clicks a mouse button or moves the cursor out of the toolbar.

An application that needs to send messages directly to the tooltip control can retrieve the handle of the tooltip by using the TB_GETTOOLTIPS message. An application can replace the tooltip control of a toolbar by using the TB_SETTOOLTIPS message. For more information about tooltip controls, see Tooltip Controls.


 Toolbar Bitmaps

Each button in a toolbar can include a bitmapped image. A toolbar stores the information that it needs to draw the images in an internal list. When you call the CreateToolbarEx function, you specify a monochrome or color bitmap that contains the initial images, and the toolbar adds the information to the internal list of images. You can add additional images later by using the TB_ADDBITMAP message.

Each image has a zero-based index. The first image added to the internal list has an index of zero, the second image has an index of one, and so on. TB_ADDBITMAP adds images to the end of the list and returns the index of the first new image that it added. You use an image's index to associate the image with a button.

Windows assumes that all of a toolbar's bitmapped images are the same size. You specify the size when you create the toolbar by using CreateToolbarEx. If you use the CreateWindowEx function to create a toolbar, the size of the images is set to the default dimensions of 16 by 15 pixels. You can use the TB_SETBITMAPSIZE message to change the dimensions of the bitmapped images, but you must do so before adding any images to the internal list of images.


 Toolbar Strings

Each button can display a string in addition to, or instead of, an image. A toolbar maintains an internal list that contains all of the strings available to toolbar buttons. You add strings to the internal list by using the TB_ADDSTRING message, specifying the address of the buffer containing the strings to add. Each string must be null-terminated, and the last string must be terminated with two null characters.

Each string has a zero-based index. The first string added to the internal list of strings has an index of zero, the second string has an index of one, and so on. TB_ADDSTRING adds strings to the end of the list and returns the index of the first new string. You use a string's index to associate the string with a button.


 Toolbar Buttons

You add buttons to a toolbar by filling an array of TBBUTTON structures and specifying the address of the array either in the TB_ADDBUTTONS message or in a call to the CreateToolbarEx function. You can also use the TB_INSERTBUTTON message, which passes the address of a TBBUTTON structure to the toolbar. Each TBBUTTON structure defines the attributes of a button, including the indexes of its string and bitmap as well as its style, state, command identifier, and application-defined 32-bit value.

If you use the CreateWindowEx function to create a toolbar, you must send the TB_BUTTONSTRUCTSIZE message before adding any buttons. The message passes the size of the TBBUTTON structure to the toolbar.


 Toolbar Button Styles

A button's style determines how the button appears and how it responds to user input. The TBSTYLE_BUTTON style creates a toolbar button that behaves like a standard push button. A button that has the TBSTYLE_CHECK style is similar to a standard push button, except it toggles between the pressed and nonpressed states each time the user clicks it.

You can create groups of toolbar buttons by using the TBSTYLE_GROUP or TBSTYLE_CHECKGROUP style, causing a button to stay pressed until the user chooses another button in the group. The TBSTYLE_SEP style creates a small gap between buttons. A button with this style does not receive user input.


 Toolbar Button States

Each button in a toolbar has a current state. The toolbar updates a button's state to reflect user actions, such as clicking the button. The state indicates whether the button is currently pressed or not pressed, enabled or disabled, hidden or visible, and so on. Although an application sets a button's initial state when adding the button to the toolbar, it can change and retrieve the state by sending messages to the toolbar. For a list of toolbar button states, see Toolbar States.

An application can use the TB_GETSTATE and TB_SETSTATE messages to retrieve and set the state of a button. In addition, a toolbar includes the following messages that retrieve or set a particular state.

TB_CHECKBUTTON	TB_ISBUTTONCHECKED
TB_ENABLEBUTTON	TB_ISBUTTONENABLED
TB_HIDEBUTTON	TB_ISBUTTONHIDDEN
TB_INDETERMINATE	TB_ISBUTTONINDETERMINATE
TB_PRESSBUTTON	TB_ISBUTTONPRESSED


 Command Identifier

Each button has a command identifier associated with it. When the user selects a button, the toolbar sends the parent window a WM_COMMAND message that includes the command identifier of the button. The parent window examines the command identifier and carries out the command associated with the button.


 Button Size and Position

A toolbar keeps track of its buttons by assigning each button a position index. The index is zero based; that is, the leftmost button has an index of zero, the next button to the right has an index of one, and so on. An application must specify the index of a button when sending messages to retrieve information about the button or set the button's attributes.

A toolbar updates the position indexes as buttons are inserted and removed. An application can retrieve the current position index of a button by using the TB_COMMANDTOINDEX message. The message specifies the command identifier of a button, and the toolbar window uses the identifier to locate the button and return its position index.

All buttons in a toolbar are the same size. The CreateToolbarEx function requires you to set the initial size of the buttons when you create the toolbar. When you use the CreateWindowEx function to create a toolbar, the initial size is set to the default dimensions of 24 by 22 pixels. You can use the TB_SETBUTTONSIZE message to change the button size, but you must do so before adding any buttons to the toolbar. The TB_GETITEMRECT message retrieves the current dimensions of the buttons.

A toolbar automatically sets the width of its buttons when you add a string to the toolbar that is longer than any current toolbar string. The width is set to accommodate the longest string in the toolbar.


 Customization

A toolbar has built in customization features that you can make available to the user by giving the toolbar the CCS_ADJUSTABLE common control style. The customization features allow the user to drag a button to a new position or to remove a button by dragging it off the toolbar. In addition, the user can double-click the toolbar to display the Customize Toolbar dialog box, which allows the user to add, delete, and rearrange toolbar buttons. An application can display the dialog box by using the TB_CUSTOMIZE message.

The toolbar sends notification messages (in the form of WM_NOTIFY messages) to the parent window at each step in the customization process. If the user holds the SHIFT key down and begins dragging a button, the toolbar automatically handles the drag operation. The toolbar sends the TBN_QUERYDELETE notification message to the parent window to determine whether the button may be deleted. The drag operation ends if the parent window returns FALSE. Otherwise, the toolbar captures mouse input and waits for the user to release the mouse button.

When the user releases the mouse button, the toolbar determines the location of the mouse cursor. If the cursor is outside the toolbar, the button is deleted. If the cursor is on another toolbar button, the toolbar sends the TBN_QUERYINSERT notification message to the parent window to determine if a button may be inserted to the left of the given button. The button is inserted if the parent window returns TRUE; otherwise, it is not. The toolbar sends the TBN_TOOLBARCHANGE notification message to signal the end of the drag operation.

If the user begins a drag operation without holding down the SHIFT key, the toolbar sends the TBN_BEGINDRAG notification message to the parent window. An application that implements its own button-dragging code can use this message as a signal to begin a drag operation. The toolbar sends the TBN_ENDDRAG notification message to signal the end of the drag operation.

A toolbar sends notification messages when the user customizes a toolbar by using the Customize Toolbar dialog box. The toolbar sends the TBN_BEGINADJUST notification message after the user double-clicks the toolbar, but before the dialog box is created. Next, the toolbar begins sending a series of TBN_QUERYINSERT notification messages to determine whether the toolbar allows buttons to be inserted. When the parent window returns TRUE, the toolbar stops sending TBN_QUERYINSERT notifications. If the parent window does not return TRUE for any button, the toolbar destroys the dialog box.

Next, the toolbar determines if any buttons may be deleted by sending one TBN_QUERYDELETE notification message for each button in the toolbar. The parent window returns TRUE to indicate that a button may be deleted; otherwise, it returns FALSE. The toolbar adds all toolbar buttons to the dialog box, but it grays those that may not be deleted.

Whenever the toolbar needs information about a button in the Customize Toolbar dialog box, it sends the TBN_GETBUTTONINFO notification message, specifying the index of the button for which it needs information and the address of a TBNOTIFY structure. The parent window must fill the structure with the relevant information.

The Customize Toolbar dialog box includes a Help button and a Reset button. When the user chooses the Help button, the toolbar sends the TBN_CUSTHELP notification message. The parent window should respond by displaying help information. The dialog box sends the TBN_RESET notification message when the user selects the Reset button. This message signals that the toolbar is about to reinitialize the dialog box.

An application can use the TB_SAVERESTORE message to save the current state of a toolbar in an initialization file or to restore the state based on information previously stored in an initialization file. The message saves the state information in the specified initialization file or in the WIN.INI file if no initialization file is specified. An application typically stores the state before the user begins customizing the toolbar in case the user later wants to restore the toolbar to its original state.


 Default Message Handling

This section describes the window message processing performed by a toolbar. Because messages specific to toolbars are discussed elsewhere, they are not included here.

Message	Default processing
WM_CHARTOITEM	Forwards this message to the parent window.
WM_COMMAND	Forwards this message to the parent window.
WM_CREATE	Allocates internal memory and graphics objects. It also initializes internal variables and data structures.
WM_DESTROY	Frees all memory and graphics objects previously allocated for the toolbar.
WM_DRAWITEM	Forwards this message to the parent window.
WM_LBUTTONDBLCLK	Forwards this message to the DefWindowProc function and returns the result.
WM_LBUTTONDOWN	Forwards this message to the tooltip control. If a button was clicked, it sets the state of the button and redraws it. It begins a drag operation if the toolbar has the CCS_ADJUSTABLE style and the SHIFT key is down (or the ALT key, if the toolbar has the TBSTYLE_ALTDRAG style).
WM_LBUTTONUP	Forwards this message to the tooltip control. If a button was clicked, it sets the state of the button and redraws it. It also ends the drag operation, if one is underway, and redraws the toolbar.
WM_MEASUREITEM	Forwards this message to the parent window.
WM_MOUSEMOVE	Forwards this message to the tooltip control. If a button has the mouse capture and the cursor moves out of the button rectangle, it redraws the button. It checks whether the toolbar has lost the mouse capture and, if it has, ends the drag operation.
WM_NCACTIVATE, WM_NCPAINT	Redraws the borders of the toolbar if the toolbar does not have the CCS_NODIVIDER style. Otherwise, it forwards the message to the DefWindowProc function.
WM_NOTIFY	Forwards the TTN_NEEDTEXT notification message from the tooltip control to the parent of the toolbar.
WM_PAINT	Draws the toolbar.
WM_SIZE	Recalculates the size and position of the toolbar and redraws it.
WM_SYSCOLORCHANGE	Updates the colors of the buttons and toolbar to march the system colors.
WM_VKEYTOITEM	Forwards this message to the parent window.
WM_WININICHANGE	Reinitializes internal variables that depend on system metric values.


 Using Toolbars

•	Creating a toolbar

•	Processing tooltip notification messages


 Creating a Toolbar

The following example uses the CreateWindowEx function to create a toolbar that the user can customize and that has a tooltip control associated with it. The example uses the TB_ADDBITMAP and TB_ADDSTRING messages to add button images and buttons strings to the toolbar. The example also adds three buttons by using the TB_ADDBUTTONS message.

// CreateAToolBar - creates a toolbar and adds the initial set of

//     buttons to it.

// Returns the handle of the toolbar if successful or NULL otherwise.

// hwndParent - handle of the parent window

HWND CreateAToolBar(HWND hwndParent)

{

    HWND hwndTB;

    TBADDBITMAP tbab;

    TBBUTTON tbb[3];

    char szBuf[16];

    int iCut, iCopy, iPaste;

    // Ensure that the common control DLL is loaded.

    InitCommonControls();

    // Create a toolbar that the user can customize and that has a

    // tooltip associated with it.

    hwndTB = CreateWindowEx(0, TOOLBARCLASSNAME, (LPSTR) NULL,

        WS_CHILD | TBSTYLE_TOOLTIPS | CCS_ADJUSTABLE,

        0, 0, 0, 0, hwndParent, (HMENU) ID_TOOLBAR, g_hinst, NULL);

    // Send the TB_BUTTONSTRUCTSIZE message, which is required for

    // backward compatibility.

    SendMessage(hwndTB, TB_BUTTONSTRUCTSIZE,

        (WPARAM) sizeof(TBBUTTON), 0);

    // Add the bitmap containing button images to the toolbar.

    tbab.hInst = g_hinst;

    tbab.nID   = IDB_BUTTONS;

    SendMessage(hwndTB, TB_ADDBITMAP, (WPARAM) NUM_BUTTON_BITMAPS,

        (WPARAM) &tbab);

    // Add the button strings to the toolbar.

    LoadString(g_hinst, IDS_CUT, (LPSTR) &szBuf, MAX_LEN);

    iCut = SendMessage(hwndTB, TB_ADDSTRING, 0, (LPARAM) (LPSTR) szBuf);

    LoadString(g_hinst, IDS_COPY, (LPSTR) &szBuf, MAX_LEN);

    iCopy = SendMessage(hwndTB, TB_ADDSTRING, (WPARAM) 0,

        (LPARAM) (LPSTR) szBuf);

    LoadString(g_hinst, IDS_PASTE, (LPSTR) &szBuf, MAX_LEN);

    iPaste = SendMessage(hwndTB, TB_ADDSTRING, (WPARAM) 0,

        (LPARAM) (LPSTR) szBuf);

    // Fill the TBBUTTON array with button information, and add the

    // buttons to the toolbar.

    tbb[0].iBitmap = BMP_CUT;

    tbb[0].idCommand = IDM_CUT;

    tbb[0].fsState = TBSTATE_ENABLED;

    tbb[0].fsStyle = TBSTYLE_BUTTON;

    tbb[0].dwData = 0;

    tbb[0].iString = iCut;

    tbb[1].iBitmap = BMP_COPY;

    tbb[1].idCommand = IDM_COPY;

    tbb[1].fsState = TBSTATE_ENABLED;

    tbb[1].fsStyle = TBSTYLE_BUTTON;

    tbb[1].dwData = 0;

    tbb[1].iString = iCopy;

    tbb[2].iBitmap = BMP_PASTE;

    tbb[2].idCommand = IDM_PASTE;

    tbb[2].fsState = TBSTATE_ENABLED;

    tbb[2].fsStyle = TBSTYLE_BUTTON;

    tbb[2].dwData = 0;

    tbb[2].iString = iPaste;

    SendMessage(hwndTB, TB_ADDBUTTONS, (WPARAM) NUM_BUTTONS,

        (LPARAM) (LPTBBUTTON) &tbb);

    ShowWindow(hwndTB, SW_SHOW);

    return hwndTB;

}


 Processing Tooltip Notification Messages

A toolbar that has the TBSTYLE_TOOLTIPS style creates a tooltip control, which an application can use to display help text for toolbar buttons. The parent window receives the TTN_NEEDTEXT notification message when the toolbar needs the help text for a button. The tooltip sends the notification in the form of a WM_NOTIFY message. The lParam parameter includes the address of a TOOLTIPTEXT structure that specifies the command identifier of the button for which help text is needed. An application can copy the help text to the structure, specify the address of a string containing the help text, or specify the instance handle and resource identifier of a string resource.

The following example demonstrates how to process the TTN_NEEDTEXT notification.

case WM_NOTIFY:

    switch (((LPNMHDR) lParam)->code) {

        case TTN_NEEDTEXT:

            {

            LPTOOLTIPTEXT lpttt;

            lpttt = (LPTOOLTIPTEXT) lParam;

            lpttt->hinst = g_hinst;

            // Specify the resource identifier of the descriptive

            // text for the given button.

            idButton = lpttt->hdr.idFrom;

            switch (idButton) {

                case IDM_CUT:

                    lpttt->lpszText = MAKEINTRESOURCE(IDS_TIPS_CUT);

                    break;

                case IDM_COPY:

                    lpttt->lpszText = MAKEINTRESOURCE(IDS_TIPS_COPY);

                    break;

                case IDM_PASTE:

                    lpttt->lpszText = MAKEINTRESOURCE(IDS_TIPS_PASTE);

                    break;

            }

            break;

            }

        .

        . // Process other notifications here.

        .

        default:

            break;

    }


 Toolbar Reference

The functions, messages, notification messages, and structures are associated with toolbars. These elements can be grouped as follows.

Toolbar Creation

CreateToolbarEx
TB_BUTTONSTRUCTSIZE
TB_SETPARENT

Toolbar Size and Position

TB_AUTOSIZE
TB_SETBUTTONSIZE

Tooltip Style

TB_GETTOOLTIPS
TB_SETTOOLTIPS
TTN_NEEDTEXT

Toolbar Bitmaps

COLORMAP
CreateMappedBitmap
TB_ADDBITMAP
TB_CHANGEBITMAP
TB_GETBITMAP
TB_GETBITMAPFLAGS
TB_SETBITMAPSIZE
TBADDBITMAP

Toolbar Strings

TB_ADDSTRING
TB_GETBUTTONTEXT

Toolbar Buttons

TB_ADDBUTTONS
TB_BUTTONCOUNT
TB_COMMANDTOINDEX
TB_DELETEBUTTON
TB_GETBUTTON
TB_GETITEMRECT
TB_GETROWS
TB_INSERTBUTTON
TB_SETCMDID
TB_SETROWS
TBBUTTON
TBNOTIFY

Toolbar Button States

TB_CHECKBUTTON
TB_ENABLEBUTTON
TB_GETSTATE
TB_HIDEBUTTON
TB_INDETERMINATE
TB_ISBUTTONCHECKED
TB_ISBUTTONENABLED
TB_ISBUTTONHIDDEN
TB_ISBUTTONINDETERMINATE
TB_ISBUTTONPRESSED
TB_PRESSBUTTON
TB_SETSTATE

Toolbar Customization

TB_CUSTOMIZE
TB_SAVERESTORE
TBN_BEGINADJUST
TBN_BEGINDRAG
TBN_CUSTHELP
TBN_ENDADJUST
TBN_ENDDRAG
TBN_GETBUTTONINFO
TBN_QUERYDELETE
TBN_QUERYINSERT
TBN_RESET
TBN_TOOLBARCHANGE
TBSAVEPARAMS


 Toolbar Functions

The following functions are used with toolbars.

CreateMappedBitmap
CreateToolbarEx


 Toolbar Messages

The following messages are used with toolbars.

TB_ADDBITMAP
TB_ADDBUTTONS
TB_ADDSTRING
TB_AUTOSIZE
TB_BUTTONCOUNT
TB_BUTTONSTRUCTSIZE
TB_CHANGEBITMAP
TB_CHECKBUTTON
TB_COMMANDTOINDEX
TB_CUSTOMIZE
TB_DELETEBUTTON
TB_ENABLEBUTTON
TB_GETBITMAP
TB_GETBITMAPFLAGS
TB_GETBUTTON
TB_GETBUTTONTEXT
TB_GETITEMRECT
TB_GETROWS
TB_GETSTATE
TB_GETTOOLTIPS
TB_HIDEBUTTON
TB_INDETERMINATE
TB_INSERTBUTTON
TB_ISBUTTONCHECKED
TB_ISBUTTONENABLED
TB_ISBUTTONHIDDEN
TB_ISBUTTONINDETERMINATE
TB_ISBUTTONPRESSED
TB_PRESSBUTTON
TB_SAVERESTORE
TB_SETBITMAPSIZE
TB_SETBUTTONSIZE
TB_SETCMDID
TB_SETPARENT
TB_SETROWS
TB_SETSTATE
TB_SETTOOLTIPS


 Toolbar Notification Messages

The parent window receives the following notification messages from a toolbar.

TBN_BEGINADJUST
TBN_BEGINDRAG
TBN_CUSTHELP
TBN_ENDADJUST
TBN_ENDDRAG
TBN_GETBUTTONINFO
TBN_QUERYDELETE
TBN_QUERYINSERT
TBN_RESET
TBN_TOOLBARCHANGE


 Toolbar Structures

The following structures are used with toolbars.

COLORMAP
TBADDBITMAP
TBBUTTON
TBNOTIFY
TBSAVEPARAMS


 Toolbar Constants

The following style flags and state flags are used with toolbars.


 Toolbar Styles

A toolbar can have a combination of the following styles.

TBSTYLE_ALTDRAG	Allows the user to change the position of a toolbar button by dragging it while holding down the ALT key. If this style is not specified, the user must hold down the SHIFT key while dragging a button. Note that the CCS_ADJUSTABLE style must be specified to enable toolbar buttons to be dragged.
TBSTYLE_TOOLTIPS	Creates a tooltip control that an application can use to display descriptive text for the buttons in the toolbar.
TBSTYLE_WRAPABLE	Creates a toolbar that can have multiple lines of buttons. Toolbar buttons can "wrap" to the next line when the toolbar becomes too narrow to include all buttons on the same line. Wrapping occurs on separation and non-group boundaries.
A button in a toolbar can have a combination of the following styles.

TBSTYLE_BUTTON	Creates a standard push button.
TBSTYLE_CHECK	Creates a button that toggles between the pressed and not pressed states each time the user clicks it. The button has a different background color when it is in the pressed state.
TBSTYLE_CHECKGROUP	Creates a check button that stays pressed until another button in the group is pressed.
TBSTYLE_GROUP	Creates a button that stays pressed until another button in the group is pressed.
TBSTYLE_SEP	Creates a separator, providing a small gap between button groups. A button that has this style does not receive user input.


 Toolbar States

A toolbar button can have a combination of the following states.

TBSTATE_CHECKED	The button has the TBSTYLE_CHECKED style and is being pressed.
TBSTATE_ENABLED	The button accepts user input. A button not having this state does not accept user input and is grayed.
TBSTATE_HIDDEN	The button is not visible and cannot receive user input.
TBSTATE_INDETERMINATE	The button is grayed.
TBSTATE_PRESSED	The button is being pressed.
TBSTATE_WRAP	A line break follows the button. The button must also have the TBSTATE_ENABLED state.


 Tooltip Controls

A tooltip control is a small pop-up window that displays a single line of descriptive text giving the purpose of tools in an application. A tool is either a window, such as a child window or control, or an application-defined rectangular area within a window's client area.


 About Tooltip Controls

A tooltip control is hidden most of the time, appearing only when the user puts the cursor on a tool and leaves it there for approximately one-half second. The tooltip control appears near the cursor and disappears when the user clicks a mouse button or moves the cursor off of the tool. A single tooltip control can support any number of tools. The following illustration shows a tooltip control associated with a button in a toolbar control.


 Tooltip Creation

You create a tooltip control by using the CreateWindowEx function, specifying the TOOLTIPS_CLASS window class. The class is registered when the common control dynamic-link library (DLL) is loaded. To ensure that this DLL is loaded, include the InitCommonControls function in your application.

The window procedure for a tooltip control automatically sets the size, position, and visibility of the tooltip control. The height of the tooltip window is based on the height of the font currently selected into the device context for the tooltip control. The width varies based on the length of the string currently in the tooltip window.


 Style and Activation

A tooltip control has two class-specific styles: TTS_ALWAYSTIP and TTS_NOPREFIX.

A tooltip control with the TTS_ALWAYSTIP style appears when the cursor is on a tool, regardless of whether the tooltip control's owner window is active or inactive. Without this style, the tooltip control appears when the tool's owner window is active, but not when it is inactive.

The TTS_NOPREFIX style prevents the system from stripping the ampersand (&) character from a string. If a tooltip control does not have the TTS_NOPREFIX style, the system automatically strips ampersand characters, allowing an application to use the same string as both a menu item and as text in a tooltip control.

A tooltip control itself can be either active or inactive. When it is active, the tooltip control appears when the cursor is on a tool. When it is inactive, the tooltip control does not appear, even if the cursor is on a tool. The TTM_ACTIVATE message activates and deactivates a tooltip control.

A tooltip control has the WS_POPUP and WS_EX_TOOLWINDOW window styles, regardless of whether you specify them when creating the control.


 Types of Tools

A tooltip control can support any number of tools. To support a particular tool, you must register the tool with the tooltip control by sending the TTM_ADDTOOL message to the tooltip control. The message includes the address of a TOOLINFO structure, which provides information the tooltip control needs to display text for the tool. The cbSize member is required and must specify the size of the structure.

A tooltip control supports tools implemented as windows (such as child windows or control windows) and as rectangular areas within a window's client area. When you add a tool implemented as a rectangular area, the hwnd member of TOOLINFO must specify the handle of the window that contains the area, and the rect member must specify the client coordinates of the area's bounding rectangle. In addition, the uId member must specify the application-defined identifier for the tool.

When you add a tool implemented as a window, the uId member of TOOLINFO must contain the window handle of the tool. Also, the uFlags member must specify the TTF_IDISHWND value, which tells the tooltip control to interpret the uId member as a window handle.


 Tool Text

When you add a tool to a tooltip control, the lpszText member of the TOOLINFO structure must specify the address of the string to display for the tool. You can change the text any time after adding the tool by using the TTM_UPDATETIPTEXT message.

If the high-order word of lpszText is zero, the low-order word must be the identifier of a string resource. When the tooltip control needs the text, the system loads the specified string resource from the application instance identified by the hinst member of TOOLINFO.

If you specify the LPSTR_TEXTCALLBACK value in the lpszText member, the tooltip control notifies the window specified in the hwnd member of TOOLINFO whenever the tooltip control needs to display text for the tool. The tooltip control sends the TTN_NEEDTEXT notification message to the window. The message includes the address of a TOOLTIPTEXT structure, which contains the window handle as well as the application-defined identifier for the tool. The window examines the structure to determine the tool for which text is needed, and it fills the appropriate structure members with information that the tooltip control needs to display the string.

Many applications create toolbars containing tools that correspond to menu commands. For such tools, it is convenient for the tooltip control to display the same text as the corresponding menu item. The system automatically strips the ampersand (&) accelerator characters from all strings passed to a tooltip control, unless the control has the TTS_NOPREFIX style.

To retrieve the text for a tool, use the TTM_GETTEXT message.


 Relaying Mouse Messages to the Tooltip

A tooltip control needs to receive mouse messages to determine when to display the tooltip window. Because Windows sends mouse messages only to the window that contains the cursor, you must use the TTM_RELAYEVENT message to relay mouse messages to the tooltip control.

If a tool is implemented as a rectangular area in an application-defined window, the window procedure receives mouse messages and can relay them to the tooltip control. However, if a tool is implemented as a system-defined window, the mouse messages are sent to the window and are not readily available to the application. You must use a message hook to access and relay the mouse messages, or you must subclass the window.

When a tooltip control receives a relayed WM_MOUSEMOVE message, it determines whether the cursor is in the bounding rectangle of a tool. If the cursor is there, the tooltip control sets a timer. At the end of the time-out duration, the tooltip control checks the position of the cursor to see whether it has moved. If the cursor has not, the tooltip control retrieves the text for the tool, copies the text into the tooltip window, and shows the window. The tooltip control continues to show the window until it receives a relayed button-up or button-down message or until a relayed WM_MOUSEMOVE message indicates that the cursor has moved outside the bounding rectangle of the tool.

A tooltip control actually has three time-out durations associated with it. The initial duration is the length of time that the cursor must remain stationary within the bounding rectangle of a tool before the tooltip window is displayed. The reshow duration is the length of the delay before subsequent tooltip windows are displayed when the cursor moves from one tool to another. The autopopup duration is the length of time that the tooltip window remains displayed before it is hidden. That is, if the cursor remains stationary within the bounding rectangle after the tooltip window is displayed, the tooltip window is automatically hidden at the end of the autopopup duration. You can adjust all of the time-out durations by using the TTM_SETDELAYTIME message.

If an application includes a tool implemented as a rectangular area and the size or position of the control changes, it can use the TTM_NEWTOOLRECT message to report the change to the tooltip control. An application does not need to report size and position changes for a tool implemented as a window. Reporting that is not necessary because the tooltip control uses the window handle of a tool to determine if the cursor is on the tool, not the tool's bounding rectangle.

When it is about to be displayed, a tootip control sends the TTN_SHOW notification to the owner window. A tooltip control sends the TTN_POP notification when it is about to be hidden. Each notification is sent in the context of a WM_NOTIFY message.


 Tooltip Hit Testing

The TTM_HITTEST message allows you to retrieve information that a tooltip control maintains about the tool occupying a particular point. The message includes a TTHITTESTINFO structure that contains a window handle, the coordinates of a point, and the address of a TOOLINFO structure. The tooltip control determines whether a tool occupies the point and, if it does, fills TOOLINFO with information about the tool.


 Miscellaneous Messages

The TTM_GETCURRENTTOOL and TTM_GETTOOLINFO messages fill a TOOLINFO structure with information about a tool that has been registered with a tooltip control. The TTM_SETTOOLINFO message allows you to change the information that a tooltip control maintains for a particular tool. The TTM_DELTOOL message deletes a tool from a tooltip control.


 Default Tooltip Control Message Processing

This section describes the window messages handled by the window procedure for the TOOLTIPS_CLASS window class.

Message	Default processing
WM_CREATE	Ensures that the tooltip control has the WS_EX_TOOLWINDOW and WS_POPUP window styles. It also allocates memory and initializes internal variables.
WM_DESTROY	Frees resources allocated for the tooltip control.
WM_GETFONT	Returns the handle of the font currently selected into the DC for the tooltip control.
WM_MOUSEMOVE	Hides the tooltip window.
WM_PAINT	Draws the tooltip window.
WM_SETFONT	Selects a new font handle into the DC for the tooltip control.
WM_TIMER	Hides the tooltip window if the tool has changed position or if the cursor has moved outside the tool. Otherwise, it shows the tooltip window.
WM_WININICHANGE	Resets internal variables that are based on system metrics.


 Using Tooltip Controls

•	Creating a tooltip control

•	Using a tooltip control with a dialog box


 Creating a Tooltip Control

The following example creates a tooltip control and adds several tools to it. The example creates a grid of rectangles in the client area of a window and then uses the TTM_ADDTOOL message to add each rectangle to the tooltip control. Note that the window procedure for the owner of the tooltip control must handle mouse messages and pass them on to the tooltip control by using the TTM_RELAYEVENT message.

// DoCreateTooltip - creates a tooltip control and adds some tools

//     to it.

// Returns the handle of the tooltip control if successful or NULL
//     otherwise.

// hwndOwner - handle of the owner window

//

// Global variable

//     g_hinst - handle of the application instance

extern HINSTANCE g_hinst;

HWND DoCreateTooltip(HWND hwndOwner)

{

    HWND hwndTT;    // handle of tooltip

    int row, col;   // rows and columns

    TOOLINFO ti;    // tool information

    int id = 0;     // offset to string identifiers

    static char *szTips[NUM_TIPS] =   // tip text

    {

    "Cut", "Copy", "Paste", "Undo", "Open", "Save"

    };

    // Ensure that the common control DLL is loaded, and create

    // a tooltip control.

    InitCommonControls();

    hwndTT = CreateWindow(TOOLTIPS_CLASS, (LPSTR) NULL, TTS_ALWAYSTIP,

        CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,

        NULL, (HMENU) NULL, g_hinst, NULL);

    if (hwndTT == (HWND) NULL)

        return (HWND) NULL;

    // Divide the client area into a grid of rectangles, and add each

    // rectangle to the tooltip.

    for (row = 0; row < MAX_ROWS ; row++ )

        for (col = 0; col < MAX_COLS; col++) {

            ti.cbSize = sizeof(TOOLINFO);

            ti.uFlags = 0;

            ti.hwnd = hwndOwner;

            ti.hinst = g_hinst;

            ti.uId = (UINT) id;

            ti.lpszText = (LPSTR) szTips[id++];

            ti.rect.left = col * CX_COLUMN;

            ti.rect.top = row * CY_ROW;

            ti.rect.right = ti.rect.left + CX_COLUMN;

            ti.rect.bottom = ti.rect.top + CY_ROW;

            if (!SendMessage(hwndTT, TTM_ADDTOOL, 0,

                    (LPARAM) (LPTOOLINFO) &ti))

                return NULL;

        }

    return hwndTT;

}


 Using a Tooltip Control with a Dialog Box

The following example includes a set of application-defined functions that implement a tooltip control for a dialog box. The DoCreateDialogTooltip function creates a tooltip control and uses the EnumChildWindows function to enumerate the controls in the dialog box. The enumeration procedure, EnumChildProc, registers each control with the tooltip control. The procedure specifies the dialog box as the parent window of each tooltip control and includes the LPSTR_TEXTCALLBACK value for each tooltip control. As a result, the dialog box receives a WM_NOTIFY message that contains the TTN_NEEDTEXT notification message whenever the tooltip control needs the text for a control. The dialog box procedure calls the OnWMNotify function to process the TTN_NEEDTEXT notifications. OnWMNotify provides the appropriate string based on the identifier of the tooltip control.

The tooltip control needs to receive mouse messages that the system sends to the control windows. To access the messages, the DoCreateDialogTooltip function installs a hook procedure of the WH_GETMESSAGE type. The hook procedure, GetMsgProc, monitors the message stream for mouse messages intended for one of the control windows and relays the messages to the tooltip control.

// DoCreateDialogTooltip - creates a tooltip control for a dialog box,

//     enumerates the child control windows, and installs a hook

//     procedure to monitor the message stream for mouse messages posted

//     to the control windows.

// Returns TRUE if successful or FALSE otherwise.

//

// Global variables

// g_hinst — handle of the application instance

// g_hwndTT — handle of the tooltip control

// g_hwndDlg — handle of the dialog box

// g_hhk — handle of the hook procedure

BOOL DoCreateDialogTooltip(void)

{

    // Ensure that the common control DLL is loaded, and create

    // a tooltip control.

    InitCommonControls();

    g_hwndTT = CreateWindowEx(0, TOOLTIPS_CLASS, (LPSTR) NULL,

        TTS_ALWAYSTIP, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,

        CW_USEDEFAULT, g_hwndDlg, (HMENU) NULL, g_hinst, NULL);

    if (g_hwndTT == NULL)

        return FALSE;

    // Enumerate the child windows to register them with the tooltip
    // control.

    if (!EnumChildWindows(g_hwndDlg, (WNDENUMPROC) EnumChildProc, 0))

        return FALSE;

    // Install a hook procedure to monitor the message stream for mouse

    // messages intended for the controls in the dialog box.

    g_hhk = SetWindowsHookEx(WH_GETMESSAGE, GetMsgProc,

        (HINSTANCE) NULL, GetCurrentThreadId());

    if (g_hhk == (HHOOK) NULL)

        return FALSE;

    return TRUE;

}

// EmumChildProc - registers control windows with a tooltip control by
//     using the TTM_ADDTOOL message to pass the address of a

//     TOOLINFO structure.

// Returns TRUE if successful or FALSE otherwise.

// hwndCtrl - handle of a control window

// lParam - application-defined value (not used)

BOOL EnumChildProc(HWND hwndCtrl, LPARAM lParam)

{

    TOOLINFO ti;

    char szClass[64];

    // Skip static controls.

    GetClassName(hwndCtrl, szClass, sizeof(szClass));

    if (lstrcmp(szClass, "STATIC") {

        ti.cbSize = sizeof(TOOLINFO);

        ti.uFlags = TTF_IDISHWND;

        ti.hwnd = g_hwndDlg;

        ti.uId = (UINT) hwndCtrl;

        ti.hinst = 0;

        ti.lpszText = LPSTR_TEXTCALLBACK;

        SendMessage(g_hwndTT, TTM_ADDTOOL, 0,

            (LPARAM) (LPTOOLINFO) &ti);

    }

    return TRUE;

}

// GetMsgProc - monitors the message stream for mouse messages intended

//     for a control window in the dialog box.

// Returns a message-dependent value.

// nCode - hook code

// wParam - message flag (not used)

// lParam - address of an MSG structure

LRESULT CALLBACK GetMsgProc(int nCode, WPARAM wParam, LPARAM lParam)

{

    MSG *lpmsg;

    lpmsg = (MSG *) lParam;

    if (nCode < 0 || !(IsChild(g_hwndDlg, lpmsg->hwnd)))

        return (CallNextHookEx(g_hhk, nCode, wParam, lParam));

    switch (lpmsg->message) {

        case WM_MOUSEMOVE:

        case WM_LBUTTONDOWN:

        case WM_LBUTTONUP:

        case WM_RBUTTONDOWN:

        case WM_RBUTTONUP:

            if (g_hwndTT != NULL) {

                MSG msg;

                msg.lParam = lpmsg->lParam;

                msg.wParam = lpmsg->wParam;

                msg.message = lpmsg->message;

                msg.hwnd = hwnd;

                SendMessage(g_hwndTT, TTM_RELAYEVENT, 0,

                    (LPARAM) (LPMSG) &msg);

            }

            break;

        default:

            break;

    }

    return (CallNextHookEx(g_hhk, nCode, wParam, lParam));

}

// OnWMNotify - provides the tooltip control with the appropriate text

//     to display for a control window. This function is called by

//     the dialog box procedure in response to a WM_NOTIFY message.

// lParam - second message parameter of the WM_NOTIFY message

VOID OnWMNotify(LPARAM lParam)

{

    LPTOOLTIPTEXT lpttt;

    int idCtrl;

    if ((((LPNMHDR) lParam)->code) == TTN_NEEDTEXT) {

        idCtrl = GetDlgCtrlID((HWND) ((LPNMHDR) lParam)->idFrom);

        lpttt = (LPTOOLTIPTEXT) lParam;

        switch (idCtrl) {

            case ID_HORZSCROLL:

                lpttt->lpszText = "A horizontal scroll bar.";

                return;

            case ID_CHECK:

                lpttt->lpszText = "A check box.";

                return;

            case ID_EDIT:

                lpttt->lpszText = "An edit control.";

                return;

        }

    }

return;

}


 Tooltip Control Reference

The following messages and structures are associated with tooltip controls. These elements can be grouped as follows.

Tooltip Activation

TTM_ACTIVATE

Adding and Deleting Tools

TOOLINFO
TTM_ADDTOOL
TTM_DELTOOL

Mouse Messages

TTM_NEWTOOLRECT
TTM_RELAYEVENT
TTM_SETDELAYTIME
TTN_POP
TTN_SHOW

Tool Text

TOOLTIPTEXT
TTM_GETTEXT
TTM_UPDATETIPTEXT
TTN_NEEDTEXT

Tooltip Hit Testing

TTHITTESTINFO
TTM_HITTEST
TTM_WINDOWFROMPOINT

Tool Information

TTM_ENUMTOOLS
TTM_GETCURRENTTOOL
TTM_GETTOOLCOUNT
TTM_GETTOOLINFO
TTM_SETTOOLINFO


 Tooltip Control Messages

An application sends messages to activate and deactivate a tooltip control, add and delete tools, and so on.

TTM_ACTIVATE
TTM_ADDTOOL
TTM_DELTOOL
TTM_ENUMTOOLS
TTM_GETCURRENTTOOL
TTM_GETTEXT
TTM_GETTOOLCOUNT
TTM_GETTOOLINFO
TTM_HITTEST
TTM_NEWTOOLRECT
TTM_RELAYEVENT
TTM_SETDELAYTIME
TTM_SETTOOLINFO
TTM_UPDATETIPTEXT
TTM_WINDOWFROMPOINT


 Tooltip Control Notification Messages

The following notification messages are used with tooltip controls.

TTN_NEEDTEXT
TTN_POP
TTN_SHOW


 Tooltip Control Structures

The following structures are used with tooltip control messages.

TOOLINFO
TOOLTIPTEXT
TTHITTESTINFO


 Trackbars

A trackbar is a window that contains a slider and optional tick marks. When the user moves the slider, using either the mouse or the direction keys, the trackbar sends notification messages to indicate the change. The following illustration shows a typical trackbar.


 About Trackbars

Trackbars are useful when you want the user to select a discrete value or a set of consecutive values in a range. For example, you might use a trackbar to allow the user to set the repeat rate of the keyboard by moving the slider to a given tick mark.

The slider in a trackbar moves in increments that you specify when you create it. For example, if you specify that the trackbar should have a range of five, the slider can only occupy six positions: a position at the left side of the trackbar and one position for each increment in the range. Typically, each of these positions is identified by a tick mark.

You create a trackbar by using the CreateWindowEx function, specifying the TRACKBAR_CLASS window class. Once you have created a trackbar, you can use trackbar messages to change many of its properties. Changes that you can make include setting the minimum and maximum positions for the slider, drawing tick marks, setting a selection range, and repositioning the slider.


 Trackbar Styles

Trackbars can have either a vertical or horizontal orientation. They can have tick marks on either side, both sides, or neither. They can also be used to specify a range of consecutive values. These properties are controlled by using trackbar styles, which you specify when you create the trackbar.

The TBS_HORZ and TBS_VERT styles determine the orientation of the trackbar. If you do not specify an orientation, the trackbar is oriented horizontally.

The TBS_AUTOTICKS style creates a trackbar that has a tick mark for each increment in its range of values. These tick marks are added automatically when an application sends the TBM_SETRANGE message. If you do not specify TBS_AUTOTICKS, you can use messages, such as TBM_SETTIC and TBM_SETTICFREQ, to specify the positions of the tick marks. To create a trackbar that does not display tick marks, you can use the TSM_NOTICKS style.

You can display tick marks on either or both sides of the trackbar. For horizontal trackbars, you can specify the TBS_BOTTOM or TBS_TOP style. For vertical trackbars, you can specify the TBS_RIGHT or TBS_LEFT style. (TBS_BOTTOM and TBS_RIGHT are the default settings.) For tick marks on both sides of the trackbar in any orientation, specify the TBS_BOTH style.

A trackbar can display a selection range only if you specify the TBS_ENABLESELRANGE style when you create it. When a trackbar has this style, the tick marks at the starting and ending positions of a selection range are displayed as triangles (instead of vertical dashes) and the selection range is highlighted. For example, selection ranges might be useful in a simple scheduling application. The user could select a range of tick marks corresponding to hours in a day to identify a scheduled meeting time.

By default, the length of a trackbar's slider varies as the selection range changes. If the trackbar has the TBS_FIXEDLENGTH style, the length of the slider remains the same even if the selection range changes. A trackbar that has the TBS_NOTHUMB style does not include a slider.


 Messages to Trackbars

An application can send messages to the trackbar to retrieve information about the window and to change its characteristics.

To retrieve the position of the slider (that is, the value the user has chosen), use the TBM_GETPOS message. To set the position of the slider, use the TBM_SETPOS message.

The range of a trackbar is the set of contiguous values that the trackbar can represent. Most applications use the TBM_SETRANGE message to set the range of a trackbar when it is first created. Applications can dynamically alter the range after the trackbar has been created by using the TBM_SETRANGEMAX and TBM_SETRANGEMIN messages. An application that allows the range to be changed dynamically typically retrieves the final range settings when the user has finished working with the trackbar. To retrieve these settings, use the TBM_GETRANGEMAX and TBM_GETRANGEMIN messages.

An application can use the TBS_AUTOTICKS style to have a trackbar's tick marks displayed automatically. If an application needs to control the position or frequency of the tick marks, however, a number of messages can be used. To set the position of a tick mark, an application can use the TBM_SETTIC message. The TBM_SETTICFREQ message allows an application to set tick marks that appear at regular intervals in the trackbar's range. For example, the application can use this message to display only ten tick marks in a range of 1 through 100. To retrieve the index in the range corresponding to a tick mark, use the TBM_GETTIC message. The TBM_GETPTICS message retrieves an array of these indices. To retrieve the position of a tick mark, in client coordinates, use the TBM_GETTICPOS message. An application can retrieve the number of tick marks by using the TBM_GETNUMTICS message. The TBM_CLEARTICS message removes all of a trackbar's tick marks.

A trackbar's line size determines how far the slider moves when an application receives a TB_LINEDOWN or TB_LINEUP notification message. Similarly, the page size determines the response to the TB_PAGEDOWN and TB_PAGEUP notification messages. Applications can retrieve and set the line and page size values by using the TBM_GETLINESIZE, TBM_SETLINESIZE, TBM_GETPAGESIZE, and TBM_SETPAGESIZE messages.

An application can use messages to retrieve the dimensions of a trackbar. The TBM_GETTHUMBRECT message retrieves the bounding rectangle for the slider. The TBM_GETCHANNELRECT message retrieves the bounding rectangle for the trackbar's channel. (The channel is the area over which the slider moves and which contains the highlight when a range is selected.)

If a trackbar has the TBS_ENABLESELRANGE style, the user can select a range of contiguous values from it. A number of messages allow the selection range to be adjusted dynamically. The TBM_SETSEL message sets the starting and ending positions of a selection. To set just the starting position or just the ending position of a selection, use the TBM_SETSELSTART or TBM_SETSELEND message. When the user has finished setting a selection range, an application can retrieve the settings by using the TBM_GETSELSTART and TBM_GETSELEND messages. To clear a user's selection, use the TBM_CLEARSEL message.


 Trackbar Notification Messages

A trackbar notifies its parent window of user actions by sending the parent WM_HSCROLL messages. The low-order word of the wParam parameter of WM_HSCROLL contains the notification code, and the high-order word specifies the position of the slider. The lParam parameter is the handle of the trackbar.

The system sends the TB_BOTTOM, TB_LINEDOWN, TB_LINEUP, and TB_TOP notification messages only when the user interacts with a trackbar by using the keyboard. The TB_THUMBPOSITION and TB_THUMBTRACK notification messages are only sent when the user is using the mouse. The TB_ENDTRACK, TB_PAGEDOWN, and TB_PAGEUP notification messages are sent in both cases. The following table lists the trackbar notification messages and the events (virtual-key codes or mouse events) that cause the notifications to be sent.

Notification message	Reason sent
TB_BOTTOM	VK_END
TB_ENDTRACK	WM_KEYUP (the user released a key that sent a relevant virtual-key code)
TB_LINEDOWN	VK_RIGHT or VK_DOWN
TB_LINEUP	VK_LEFT or VK_UP
TB_PAGEDOWN	VK_NEXT (the user clicked the channel below or to the right of the slider)
TB_PAGEUP	VK_PRIOR (the user clicked the channel above or to the left of the slider)
TB_THUMBPOSITION	WM_LBUTTONUP following a TB_THUMBTRACK notification message
TB_THUMBTRACK	Slider movement (the user dragged the slider)
TB_TOP	VK_HOME


 Default Trackbar Message Processing

This section describes the window message processing performed by a trackbar.

Message	Processing performed
WM_CAPTURECHANGED	Kills the timer if one was set during WM_LBUTTONDOWN processing and sends the TB_THUMBPOSITION notification message, if necessary. It always sends the TB_ENDTRACK notification message.
WM_CREATE	Performs additional initialization. It sets the initial tick frequency to 1, the line size to 1, and the page size to  − 1.
WM_DESTROY	Frees resources.
WM_ENABLE	Repaints the trackbar window.
WM_ERASEBKGND	Erases the window background, using the current background color for the trackbar.
WM_GETDLGCODE	Returns the DLGC_WANTARROWS value.
WM_KEYDOWN	Processes the direction keys and sends the TB_TOP, TB_BOTTOM, TB_PAGEUP, TB_PAGEDOWN, TB_LINEUP, and TB_LINEDOWN notification messages, as appropriate.
WM_KEYUP	Sends the TB_ENDTRACK notification message if the key was one of the direction keys.
WM_KILLFOCUS	Repaints the trackbar window.
WM_LBUTTONDOWN	Sets the focus and the mouse capture to the trackbar. When necessary, it sets a timer that determines how quickly the slider moves toward the mouse cursor when the user holds down the mouse button in the window.
WM_LBUTTONUP	Releases the mouse capture and kills the timer if one was set during WM_LBUTTONDOWN processing. It sends the TB_THUMBPOSITION notification message, if necessary. It always sends the TB_ENDTRACK notification message.
WM_MOUSEMOVE	Moves the slider and sends the TB_THUMBTRACK notification message when tracking the mouse (see WM_TIMER).
WM_PAINT	Paints the trackbar.
WM_SETFOCUS	Repaints the trackbar window.
WM_SIZE	Sets the dimensions of the trackbar, removing the slider if there is not enough room to display it.
WM_TIMER	Retrieves the mouse position and updates the position of the slider. (It is received only when the user is dragging the slider.)
WM_WININICHANGE	Initializes slider dimensions.


 Using Trackbars

•	Creating a trackbar

•	Processing trackbar notification messages


 Creating a Trackbar

The following example shows how to create a trackbar with the TBS_AUTOTICKS and TBS_ENABLESELRANGE styles. When the trackbar is created, both its range and its selection range are initialized. The page size is also set at this time.

// CreateTrackbar - creates and initializes a trackbar.

//

// Global variable

//     g_hinst - instance handle

HWND WINAPI CreateTrackbar(

    HWND hwndDlg,  // handle of dialog box (parent window)

    UINT iMin,     // minimum value in trackbar range

    UINT iMax,     // maximum value in trackbar range

    UINT iSelMin,  // minimum value in trackbar selection

    UINT iSelMax)  // maximum value in trackbar selection

{

    InitCommonControls(); // loads common control's DLL

    hwndTrack = CreateWindowEx(

        0,                             // no extended styles

        TRACKBAR_CLASS,                // class name

        "Trackbar Control",            // title (caption)

        WS_CHILD | WS_VISIBLE |

        TBS_AUTOTICKS | TBS_ENABLESELRANGE,  // style

        10, 10,                        // position

        200, 30,                       // size

        hwndDlg,                       // parent window

        ID_TRACKBAR,             // control identifier

        g_hinst,                       // instance

        NULL                           // no WM_CREATE parameter

        );

    SendMessage(hwndTrack, TBM_SETRANGE,

        (WPARAM) TRUE,                   // redraw flag

        (LPARAM) MAKELONG(iMin, iMax));  // min. & max. positions

    SendMessage(hwndTrack, TBM_SETPAGESIZE,

        0, (LPARAM) 4);                  // new page size

    SendMessage(hwndTrack, TBM_SETSEL,

        (WPARAM) FALSE,                  // redraw flag

        (LPARAM) MAKELONG(iSelMin, iSelMax);

    SendMessage(hwndTrack, TBM_SETPOS,

        (WPARAM) TRUE,                   // redraw flag

        (LPARAM) iSelMin);

    SetFocus(hwndTrack);

    return hwndTrack;

}


 Processing Trackbar Notification Messages

The following example is a function that is called whenever a WM_HSCROLL message is received by the dialog box containing the trackbar. The trackbar has the TBS_ENABLESELRANGE style. The position of the slider is compared against the selection range, and the slider is moved to the starting or ending position of the selection range, when necessary.

// TBNotifications - handles trackbar notifications received

//     in the wParam parameter of WM_HSCROLL. This function simply

//     ensures that the slider remains within the selection range.

VOID WINAPI TBNotifications(

    WPARAM wParam,  // wParam of WM_HSCROLL message

    HWND hwndTrack, // handle of trackbar window

    UINT iSelMin,   // minimum value of trackbar selection

    UINT iSelMax)   // maximum value of trackbar selection

{

    DWORD dwPos;    // current position of slider

    switch (LOWORD(wParam)) {

        case TB_ENDTRACK:

            dwPos = SendMessage(hwndTrack, TBM_GETPOS, 0, 0);

            if (dwPos > iSelMax)

                SendMessage(hwndTrack, TBM_SETPOS,

                    (WPARAM) TRUE,       // redraw flag

                    (LPARAM) iSelMax);

            else if (dwPos < iSelMin)

                SendMessage(hwndTrack, TBM_SETPOS,

                    (WPARAM) TRUE,       // redraw flag

                    (LPARAM) iSelMin);

            break;

        default:

            break;

        }

}


 Trackbar Reference

The following messages are associated with trackbars.

Size and Position

TBM_GETCHANNELRECT
TBM_GETTHUMBLENGTH
TBM_GETTHUMBRECT
TBM_SETTHUMBLENGTH

Slider Position

TBM_GETPOS
TBM_SETPOS

Line and Page Size

TBM_GETLINESIZE
TBM_GETPAGESIZE
TBM_SETLINESIZE
TBM_SETPAGESIZE

Range

TBM_GETRANGEMAX
TBM_GETRANGEMIN
TBM_SETRANGE
TBM_SETRANGEMAX
TBM_SETRANGEMIN

Selection

TBM_CLEARSEL
TBM_GETSELEND
TBM_GETSELSTART
TBM_SETSEL
TBM_SETSELEND
TBM_SETSELSTART

Tick Marks

TBM_CLEARTICS
TBM_GETNUMTICS
TBM_GETPTICS
TBM_GETTIC
TBM_GETTICPOS
TBM_SETTIC
TBM_SETTICFREQ


 Trackbar Messages

An application sends messages to the trackbar to retrieve information about the trackbar and to change its characteristics. The following are the trackbar messages.

TBM_CLEARSEL
TBM_CLEARTICS
TBM_GETCHANNELRECT
TBM_GETLINESIZE
TBM_GETNUMTICS
TBM_GETPAGESIZE
TBM_GETPOS
TBM_GETPTICS
TBM_GETRANGEMAX
TBM_GETRANGEMIN
TBM_GETSELEND
TBM_GETSELSTART
TBM_GETTHUMBLENGTH
TBM_GETTHUMBRECT
TBM_GETTIC
TBM_GETTICPOS
TBM_SETLINESIZE
TBM_SETPAGESIZE
TBM_SETPOS
TBM_SETRANGE
TBM_SETRANGEMAX
TBM_SETRANGEMIN
TBM_SETSEL
TBM_SETSELEND
TBM_SETSELSTART
TBM_SETTHUMBLENGTH
TBM_SETTIC
TBM_SETTICFREQ


 Tree-View Controls

A tree-view control is a window that displays a hierarchical list of items, such as the headings in a document, the entries in an index, or the files and directories on a disk. Each item consists of a label and an optional bitmapped image, and each item can have a list of subitems associated with it. By clicking an item, the user can expand and collapse the associated list of subitems. The following illustration shows a tree-view control that displays a table of contents.


 About Tree-View Controls

You create a tree-view control by using the CreateWindowEx function, specifying the WC_TREEVIEW window class. The class is registered when the common control dynamic-link library (DLL) is loaded. To ensure that this DLL is loaded, include the InitCommonControls function in your application.

After creating a tree-view control, you add, remove, arrange, or otherwise manipulate items by sending messages to it. Each message has one or more corresponding macros that you can use instead of sending the message explicitly. The macros are documented with the messages in the Reference section of this topic.


 Tree-View Styles

Tree-view styles govern aspects of a tree-view control's appearance. You set the initial styles when you create the tree-view control. You can retrieve and change the styles after creating the tree-view control by using the GetWindowLong and SetWindowLong functions.

The TVS_HASLINES style enhances the graphic representation of a tree-view control's hierarchy by drawing lines that link child items to their corresponding parent item. This style does not link items at the root of the hierarchy. To do so, you need to combine the TVS_HASLINES and TVS_LINESATROOT styles.

The user can expand or collapse a parent item's list of child items by double-clicking the parent item. A tree-view control that has the TVS_HASBUTTONS style adds a button to the left side of each parent item. The user can click the button to expand or collapse the child items as an alternative to double-clicking the parent item. TVS_HASBUTTONS does not add buttons to items at the root of the hierarchy. To do so, you must combine TVS_HASLINES, TVS_LINESATROOT, and TVS_HASBUTTONS.

The TVS_EDITLABELS style makes it possible for the user to edit the labels of tree-view items. For more information about editing labels, see Tree-View Label Editing.

The TVS_SHOWSELALWAYS style causes a selected item to remain selected when the tree-view control loses focus.


 Parent and Child Items

Any item in a tree-view control can have a list of subitems, which are called child items, associated with it. An item that has one or more child items is called a parent item. A child item is displayed below its parent item and is indented to indicate it is subordinate to the parent. An item that has no parent is at the top of the hierarchy and is called a root item.

You add an item to a tree-view control by sending the TVM_INSERTITEM message to the tree-view control. The message returns a handle of the HTREEITEM type, which uniquely identifies the item. When adding an item, you must specify the handle of the new item's parent item. If you specify NULL or the TVI_ROOT value instead of an parent item handle in the TV_INSERTSTRUCT structure, the item is added as a root item.

At any given time, the state of a parent item's list of child items can be either expanded or collapsed. When the state is expanded, the child items are displayed below the parent item. When it is collapsed, the child items are not displayed. The list automatically toggles between the expanded and collapsed states when the user double-clicks the parent item or, if the parent has the TVS_HASBUTTONS style, when the user clicks the button associated with the parent item. An application can expand or collapse the child items by using the TVM_EXPAND message.

A tree-view control sends the parent window a TVN_ITEMEXPANDING notification message when a parent item's list of child items is about to be expanded or collapsed. The notification gives an application the opportunity to prevent the change or to set any attributes of the parent item that depend on the state of the list of child items. After changing the state of the list, the tree-view control sends the parent window a TVN_ITEMEXPANDED notification message.

When a list of child items is expanded, it is indented relative to the parent item. You can set the amount of indentation by using the TVM_SETINDENT message or retrieve the current amount by using the TVM_GETINDENT message.

A tree-view control uses memory allocated from the heap of the process that creates the tree-view control. The maximum number of items in a tree view is based on the amount of memory available in the heap. Each item takes 64 bytes.


 Item Labels

You typically specify the text of an item's label when adding the item to the tree-view control. The TVM_INSERTITEM message includes a TV_ITEM structure that defines the item's properties, including a string containing the text of the label.

A tree-view control allocates memory for storing each item; the text of the item labels takes up a significant portion of this memory. If your application maintains a copy of the strings in the tree-view control, you can decrease the memory requirements of the control by specifying the LPSTR_TEXTCALLBACK value in the pszText member of TV_ITEM instead of passing actual strings to the tree view. Using LPSTR_TEXTCALLBACK causes the tree-view control to retrieve the text of an item's label from the parent window whenever the item needs to be redrawn. To retrieve the text, the tree-view control sends a TVN_GETDISPINFO notification message, which includes the address of a TV_DISPINFO structure. The parent window must fill the appropriate members of the included structure.


 Tree-View Label Editing

The user can directly edit the labels of items in a tree-view control that has the TVS_EDITLABELS style. The user begins editing by clicking the label of the item that has the focus. An application begins editing by using the TVM_EDITLABEL message. The tree-view control notifies the parent window when editing begins and when it is canceled or completed. When editing is completed, the parent window is responsible for updating the item's label, if appropriate.

When label editing begins, a tree-view control sends its parent window a TVN_BEGINLABELEDIT notification message. By processing this notification, an application can allow editing of some labels and prevent editing of others. Returning zero allows editing, and returning nonzero prevents it.

When label editing is canceled or completed, a tree-view control sends its parent window a TVN_ENDLABELEDIT notification message. The lParam parameter is the address of a TV_DISPINFO structure. The item member is a TV_ITEM structure that identifies the item and includes the edited text. The parent window is responsible for updating the item's label, if appropriate, perhaps after validating the edited string. The pszText member of TV_ITEM is zero if editing is canceled.

During label editing, typically in response to the TVN_BEGINLABELEDIT notification message, you can get the handle of the edit control used for label editing by using the TVM_GETEDITCONTROL message. You can send the edit control an EM_SETLIMITTEXT message to limit the amount of text a user can enter or subclass the edit control to intercept and discard invalid characters. Note, however, that the edit control is displayed only after TVN_BEGINLABELEDIT is sent.


 Tree-View Item Position

An item's initial position is set when the item is added to the tree-view control by using the TVM_INSERTITEM message. The message includes a TV_INSERTSTRUCT structure that specifies the handle of the parent item and the handle of the item after which the new item is to be inserted. The second handle must identify either a child item of the given parent or one of these values: TVI_FIRST, TVI_LAST, or TVI_SORT.

When TVI_FIRST or TVI_LAST is specified, the tree-view control places the new item at the beginning or end of the given parent item's list of child items. When TVI_SORT is specified, the tree-view control inserts the new item into the list of child items in alphabetical order based on the text of the item labels.

You can put a parent item's list of child items into alphabetical order by using the TVM_SORTCHILDREN message. The message includes a parameter that specifies whether all levels of child items descending from the given parent item are also sorted in alphabetical order.

The TVM_SORTCHILDRENCB message allows you to sort child items based on criteria that you define. When you use this message, you specify an application-defined callback function that the tree-view control can call whenever the relative order of two child items needs to be decided. The callback function receives two 32-bit application-defined values for the items being compared and a third 32-bit value that you specify when sending TVM_SORTCHILDRENCB.


 Tree-View Item States Overview

Each item in a tree-view control has a current state. For example, an item can be selected, disabled, expanded, and so on. For the most part, the tree-view control automatically sets an item's state to reflect user actions, such as selection of an item. However, you can also set an item's state by using the TVM_SETITEM message and retrieve the current state of an item by using the TVM_GETITEM message. For a complete list of item states, see Tree-View Control Constants.

An item's current state is specified by the state member of the TV_ITEM structure. A tree-view control might change an item's state to reflect a user action, such as selecting the item or setting the focus to the item. In addition, an application might change an item's state to disable or hide the item or to specify an overlay image or state image.

When you specify or change an item's state, the stateMask member of TV_ITEM specifies which state bits to set, and the state member contains the new values for those bits. To set an item's overlay image, stateMask must include the TVIS_OVERLAYMASK value, and state must include the one-based index of the overlay image shifted left eight bits by using the INDEXTOOVERLAYMASK macro. The index can be zero to specify no overlay image. The overlay image must have been added to the tree-view control's list of overlay images by a previous call to the ImageList_SetOverlayImage function. The function specifies the one-based index of the image to add; this is the index used with the INDEXTOOVERLAYMASK macro. A tree-view control can have up to four overlay images.

To set an item's state image, stateMask of TV_ITEM must include the TVIS_STATEIMAGEMASK value, and state must include the one-based index of the state image shifted left twelve bits by using the INDEXTOSTATEIMAGEMASK macro. The index can be zero to specify no state image. For more information about overlay and state images, see Tree-View Image Lists.


 Item Selection

A tree-view control notifies the parent window when the selection changes from one item to another by sending the TVN_SELCHANGING and TVN_SELCHANGED notification messages. Both notifications include a value that specifies whether the change is the result of a mouse click or a keystroke. The notifications also include information about the item that is gaining the selection and the item that is losing the selection. You can use this information to set item attributes that depend on the selection state of the item. Returning TRUE in response to TVN_SELCHANGING prevents the selection from changing; returning FALSE allows the change.

An application can change the selection by sending the TVM_SELECTITEM message.


 Item Information

Tree-view controls are used with a number of messages that retrieve information about items in the control. TVM_GETITEM retrieves the attributes of an item, including its current state, its selected and nonselected bitmapped images, a count of its child items, a pointer to its label string, and its application-defined 32-bit value.

The TVM_GETNEXTITEM message retrieves the tree-view item that bears the specified relationship to the current item. The message can retrieve an item's parent, the next or previous visible item, the first child item, and so on.

The TVM_GETITEMRECT message retrieves the bounding rectangle for a tree-view item. The TVM_GETCOUNT and TVM_GETVISIBLECOUNT messages retrieve a count of the items in a tree-view control and a count of the items that are currently visible in the tree-view control's window, respectively. You can ensure that a particular item is visible by using the TVM_ENSUREVISIBLE message.


 Tree-View Image Lists

Each item in a tree-view control can have a pair of bitmapped images associated with it. The images appear on the left side of an item's label. One image is displayed when the item is selected, and the other is displayed when the item is not selected. For example, an item might display an open folder when it is selected and a closed folder when it is not selected.

To use item images, you must create an image list by using the ImageList_Create function, add the desired bitmaps to the list, and associate the list with the tree-view control by using the TVM_SETIMAGELIST message. By default, all items display the first image in the image list for both the selected and nonselected states. You can change the default behavior for a particular item by specifying the indexes of the selected and nonselected images when adding the item to the tree view using the TVM_INSERTITEM message. You can change the indexes after adding an item by using the TVM_SETITEM message.

A tree-view control's image lists can also contain overlay images, which are designed to be superimposed on item images. A nonzero value in bits 8 through 11 of a tree-view item's state specifies the one-based index of an overlay image (zero indicates no overlay image). Because a 4-bit, one-based index is used, overlay images must be among the first 15 images in the image lists. For more information about tree-view item states, see Tree-View Item States Overview.

If a state image list is specified, a tree-view control reserves space to the left of each item's icon for a state image. An application can use state images, such as checked and cleared check boxes, to indicate application-defined item states. A nonzero value in bits 12 through 15 specifies the one-based index of a state image (zero indicates no state image).

By specifying the I_IMAGECALLBACK value instead of the index of an image in the TV_ITEM structure, you can put off specifying the selected or nonselected image until the item is about to be redrawn. I_IMAGECALLBACK directs the tree view to query the parent window for the index by sending the TVN_GETDISPINFO notification message.

The TVM_GETIMAGELIST message retrieves the handle of a tree-view control's image list. This message is useful if you need to add more images to the list. For more information about image lists, see Image Lists.


 Drag and Drop Operations

A tree-view control notifies the parent window when the user starts to drag an item. The parent window receives a TVN_BEGINDRAG notification message when the user begins dragging an item with the left mouse button and a TVN_BEGINRDRAG notification message when the user begins dragging with the right button. You can prevent a tree-view control from sending these notifications by giving the tree-view control the TVS_DISABLEDRAGDROP style.

You obtain an image to display during a drag operation by using the TVM_CREATEDRAGIMAGE message. The tree-view control creates a dragging bitmap based on the label of the item being dragged. Then the tree-view control creates an image list, adds the bitmap to it, and returns the handle of the image list.

You must provide the code that actually drags the item. This typically involves using the dragging capabilities of the image list functions and processing the WM_MOUSEMOVE and WM_LBUTTONUP (or WM_RBUTTONUP) messages sent to the parent window after the drag operation has begun. For more information about the image list functions, see Image Lists. For more information about dragging a tree-view item, see Dragging a Tree-View Item.

If items in a tree-view control are to be the targets of a drag and drop operation, you need to know when the mouse cursor is on a target item. You can find out by using the TVM_HITTEST message. You specify the address of a TV_HITTESTINFO structure that contains the current coordinates of the mouse cursor. When the SendMessage function returns, the structure contains a flag indicating the location of the mouse cursor relative to the tree-view control. If the cursor is over an item in the tree-view control, the structure contains the handle of the item as well.

You can indicate that an item is the target of a drag and drop operation by using the TVM_SETITEM message to set the state to the TVIS_DROPHILITED value. An item that has this state is drawn in the style used to indicate a drag and drop target.


 About Tree-View Control Notification Messages

A tree-view control sends the following notification messages to its parent window in the form of WM_NOTIFY messages.

Notification	Description
TVN_BEGINDRAG	Signals the start of a drag and drop operation.
TVN_BEGINLABELEDIT	Signals the start of in-place label editing.
TVN_BEGINRDRAG	Signals the start of a drag and drop operation, using the right mouse button.
TVN_DELETEITEM	Signals the deletion of a specific item.
TVN_ENDLABELEDIT	Signals the end of label editing.
TVN_GETDISPINFO	Requests information that the tree-view control requires to display an item.
TVN_ITEMEXPANDED	Signals that a parent item's list of child items was expanded or collapsed.
TVN_ITEMEXPANDING	Signals that a parent item's list of child items is about to be expanded or collapsed.
TVN_KEYDOWN	Signals a keyboard event.
TVN_SELCHANGED	Signals that the selection has changed from one item to another.
TVN_SELCHANGING	Signals that the selection is about to be changed from one item to another.
TVN_SETDISPINFO	Notifies a parent window that it must update the information it maintains for an item.


 Default Tree-View Controls Message Processing

This section describes the window message processing performed by a tree-view control. Because messages specific to tree-view controls are discussed elsewhere, they are not included here.

Message	Processing performed
WM_COMMAND	Processes the EN_UPDATE and EN_KILLFOCUS edit control notification  messages and forwards all other edit control notifications to the parent window. There is no return value.
WM_CREATE	Allocates memory and initializes internal data structures. It returns zero if successful or  − 1 otherwise.
WM_DESTROY	Frees all system resources associated with the control. It returns zero.
WM_ENABLE	Enables or disables the control.
WM_ERASEBKGND	Erases the window background using the current background color for the tree-view control. It returns TRUE.
WM_GETDLGCODE	Returns a combination of the DLGC_WANTARROWS and DLGC_WANTCHARS values.
WM_GETFONT	Returns the handle of the current label font.
WM_HSCROLL	Scrolls the tree-view control. It returns TRUE if scrolling occurs or FALSE otherwise.
WM_KEYDOWN	Sends the NM_RETURN notification message when the user presses the ENTER key. It moves the caret when the user presses the direction keys or the PAGE UP, PAGE DOWN, HOME, END, or BACKSPACE key. It scrolls the tree-view control when the user presses the CTRL key in combination with those keys. It sends the TVN_KEYDOWN notification message to the parent window. It returns TRUE if a key is processed or FALSE otherwise.
WM_KILLFOCUS	Repaints the focused item, if any, and sends an NM_KILLFOCUS notification message to the parent window.
WM_LBUTTONDBLCLK	Cancels label editing and, if an item was double-clicked, sends the NM_DBLCLK or NM_RDBLCLK notification message to the parent window. If the parent window returns TRUE, the tree-view control toggles the expanded state of the item, sending the parent window the TVN_ITEMEXPANDING and TVN_ITEMEXPANDED notification messages. There is no return value.
WM_LBUTTONDOWN	Toggles the expanded state if the user clicked the button associated with a parent item. If the user clicked an item label, the tree-view control selects and sets the focus to the item. If the user moves the mouse before releasing the mouse button, the tree-view control begins a drag and drop operation. There is no return value.
WM_PAINT	Paints the invalid region of the tree-view control. It returns zero.
WM_RBUTTONDOWN	Checks to see if an item was clicked and a drag operation was begun. If the operation has begun, it sends a TVN_BEGINRDRAG notification message to the parent window and highlights the drop target. Otherwise, it sends an NM_RCLICK notification message to the parent window. There is no return value.
WM_SETFOCUS	Repaints the focused item, if any, and sends an NM_SETFOCUS notification message to the parent window.
WM_SETFONT	Saves the specified font handle and repaints the tree-view control using the new font.
WM_SETREDRAW	Sets or clears the redraw flag. The tree-view control is redrawn after the redraw flag is set. It returns zero.
WM_SIZE	Recomputes internal variables that depend on the size of the tree-view control's client area. It returns TRUE.
WM_STYLECHANGED	Cancels label editing and redraws the tree-view control using the new styles. It returns zero.
WM_SYSCOLORCHANGE	Redraws the tree-view control using the new color if the redraw flag is set. There is no return value.
WM_TIMER	Begins editing an item label. If the user clicks the label of the focused item, the tree-view control sets a timer instead of entering edit mode immediately. The timer makes it possible for the tree view to avoid entering edit mode if the user double-clicks the label. It returns zero.
WM_VSCROLL	Scrolls the tree-view control. It returns TRUE if scrolling occurs or FALSE otherwise.


 Using Tree-View Controls

•	Creating a tree-view control

•	Initializing the image list

•	Adding tree-view items

•	Dragging a tree-view item


 Creating a Tree-View Control

To create a tree-view control, use the CreateWindowEx function, specifying the WC_TREEVIEW value for the window class. The tree-view window class is registered in the application's address space when the common control dynamic-link library (DLL) is loaded. To ensure that the DLL is loaded, use the InitCommonControls function.

The following example creates a tree-view control that is sized to fit the client area of the parent window. It also uses application-defined functions to associate an image list with the control and add items to the control.

// CreateATreeView - creates a tree-view control.

// Returns the handle of the new control if successful or NULL
//     otherwise.

// hwndParent - handle of the control's parent window

// lpszFileName - name of the file to parse for tree-view items

HWND CreateATreeView(HWND hwndParent, LPSTR lpszFileName)

{

    RECT rcClient;  // dimensions of client area

    HWND hwndTV;    // handle of tree-view control

    // Ensure that the common control DLL is loaded.

    InitCommonControls();

    // Get the dimensions of the parent window's client area, and create

    // the tree-view control.

    GetClientRect(hwndParent, &rcClient);

    hwndTV = CreateWindowEx(0, WC_TREEVIEW, "Tree View",

        WS_VISIBLE | WS_CHILD | WS_BORDER | TVS_HASLINES,

        0, 0, rcClient.right, rcClient.bottom,

        hwndParent, (HMENU) ID_TREEVIEW, g_hinst, NULL);

    // Initialize the image list, and add items to the control.

    // InitTreeViewImageLists and InitTreeViewItems are application-

    // defined functions.

    if (!InitTreeViewImageLists(hwndTV) ||

            !InitTreeViewItems(hwndTV, lpszFileName)) {

        DestroyWindow(hwndTV);

        return FALSE;

    }

    return hwndTV;

}


 Initializing the Image List

Every item in a tree-view control can have two images associated with it. An item displays one image when it is selected and the other when it is not. To include images with tree-view items, you must use the image list functions to create an image list and add images to it. Then you must associate the image list with the tree-view control by using the TVM_SETIMAGELIST message.

The following example creates an image list, adds three bitmaps to the list, and associates the image list with a tree-view control.

// InitTreeViewImageLists - creates an image list, adds three bitmaps to //     it, and associates the image list with a tree-view control.

// Returns TRUE if successful or FALSE otherwise.

// hwndTV - handle of the tree-view control

//
// Global variables and constants

//     g_nOpen, g_nClosed, and g_nDocument - integer variables for

//         indexes of the images

//     CX_BITMAP and CY_BITMAP - width and height of an icon

//     NUM_BITMAPS - number of bitmaps to add to the image list

BOOL InitTreeViewImageLists(HWND hwndTV)

{

    HIMAGELIST himl;  // handle of image list

    HBITMAP hbmp;     // handle of bitmap

    // Create the image list.

    if ((himl = ImageList_Create(CX_BITMAP, CY_BITMAP,

            FALSE, NUM_BITMAPS, 0)) == NULL)

        return FALSE;

    // Add the open file, closed file, and document bitmaps.

    hbmp = LoadBitmap(g_hinst, MAKEINTRESOURCE(IDB_OPEN_FILE));

    g_nOpen = ImageList_Add(himl, hbmp, (HBITMAP) NULL);

    DeleteObject(hbmp);

    hbmp = LoadBitmap(g_hinst, MAKEINTRESOURCE(IDB_CLOSED_FILE));

    g_nClosed = ImageList_Add(himl, hbmp, (HBITMAP) NULL);

    DeleteObject(hbmp);

    hbmp = LoadBitmap(g_hinst, MAKEINTRESOURCE(IDB_DOCUMENT));

    g_nDocument = ImageList_Add(himl, hbmp, (HBITMAP) NULL);

    DeleteObject(hbmp);

    // Fail if not all of the images were added.

    if (ImageList_GetImageCount(himl) < 3)

        return FALSE;

    // Associate the image list with the tree-view control.

    TreeView_SetImageList(hwndTV, himl, TVSIL_NORMAL);

    return TRUE;

}


 Adding Tree-View Items

You add an item to a tree-view control by sending the TVM_INSERTITEM message to the control. The message includes a pointer to a TV_INSERTSTRUCT structure, specifying the parent item, the item after which the new item is inserted, and a TV_ITEM structure that defines the attributes of the item. The attributes include the item's label, its selected and nonselected images, and a 32-bit application-defined value.

The example in this section creates a table of contents based on the information in a text file. The example includes two functions. The first function searches a file for headings. When it finds one, it extracts the text of the heading and the value that indicates the level of the heading and then passes them to the second function. Headings are assumed to be in the following form, .[heading].n, where heading is the text of the heading and n indicates the heading level. The example ignores heading levels greater than level four.

The second function adds an item to a tree-view control, using the heading text as the item's label and the heading level to determine the parent item for the new item. A level one heading is added to the root of the tree-view control, a level two heading is added as a child item of the previous level one item, and so on. The function assigns an image to an item based on whether it has any child items. If an item has child items, it gets an image representing a closed folder. Otherwise, it gets an image representing a document. An item uses the same image for both the selected and nonselected states.

// InitTreeViewItems - extracts headings from the specified file and

//     passes them to a function that adds them to a tree-view control.

// Returns TRUE if successful or FALSE otherwise.

// hwndTV - handle of the tree-view control

// lpszFileName - name of file with headings

BOOL InitTreeViewItems(HWND hwndTV, LPSTR lpszFileName)

{

    HANDLE hf;            // handle of file

    DWORD cbRead;         // number of bytes read

    char szItemText[128]; // label text of tree-view item

    int nLevel;           // heading level

    LPCH pch;             // pointer to data read from file

    LPCH pchTmp;          // temporary pointer

    DWORD i, j;           // counters

    // Open the file to parse.

    if ((hf = CreateFile(lpszFileName, GENERIC_READ,

            FILE_SHARE_READ, (LPSECURITY_ATTRIBUTES) NULL,

            OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,

            (HANDLE) NULL)) == (HANDLE) INVALID_HANDLE_VALUE)

        return FALSE;

    // Parse the file looking for headings.

    pch = (LPCH) LocalAlloc(LPTR, sizeof(char) * 2048);

    pchTmp = pch;

    do {

        // Read a chunk of the file.

        ReadFile(hf, pchTmp, sizeof(char) * 2048, &cbRead,

            (LPOVERLAPPED) NULL);

        // Parse the chunk looking for ".[".

        for (i = 0, j = 0; i < cbRead; i++) {

            if ((i + 2) > cbRead)    // break if end of chunk

                break;

             // Extract the heading text from between the brackets.

            if ((*pchTmp == '.') && (*(pchTmp+1) == '[')) {

                pchTmp = pchTmp + 2;

                i += 2;

                while (*pchTmp != ']' && ((i++) <= cbRead) )

                    szItemText[j++] = *pchTmp++;

                szItemText[j] = '\0';

                j = 0;

                nLevel = atoi(pchTmp + 2);

                // Add the item to the tree-view control.

                AddItemToTree(hwndTV, (LPSTR) &szItemText, nLevel);

            } else

                ++pchTmp;

        }

        pchTmp = pch;

    } while (cbRead != 0);

    CloseHandle((HANDLE) hf);

    return TRUE;

}

// AddItemToTree - adds items to a tree-view control.

// Returns the handle of the newly added item.

// hwndTV - handle of the tree-view control

// lpszItem - text of the item to add

// nLevel - level at which to add the item

HTREEITEM AddItemToTree(HWND hwndTV, LPSTR lpszItem, int nLevel)

{

    TV_ITEM tvi;

    TV_INSERTSTRUCT tvins;

    static HTREEITEM hPrev = (HTREEITEM) TVI_FIRST;

    static HTREEITEM hPrevRootItem = NULL;

    static HTREEITEM hPrevLev2Item = NULL;

    HTREEITEM hti;

    tvi.mask = TVIF_TEXT | TVIF_IMAGE

        | TVIF_SELECTEDIMAGE | TVIF_PARAM;

    // Set the text of the item.

    tvi.pszText = lpszItem;

    tvi.cchTextMax = lstrlen(lpszItem);

    // Assume the item is not a parent item, so give it a

    // document image.

    tvi.iImage = g_nDocument;

    tvi.iSelectedImage = g_nDocument;

    // Save the heading level in the item's application-defined

    // data area.

    tvi.lParam = (LPARAM) nLevel;

    tvins.item = tvi;

    tvins.hInsertAfter = hPrev;

    // Set the parent item based on the specified level.

    if (nLevel == 1)

        tvins.hParent = TVI_ROOT;

    else if (nLevel == 2)

        tvins.hParent = hPrevRootItem;

    else

        tvins.hParent = hPrevLev2Item;

    // Add the item to the tree-view control.

    hPrev = (HTREEITEM) SendMessage(hwndTV, TVM_INSERTITEM, 0,

         (LPARAM) (LPTV_INSERTSTRUCT) &tvins);

    // Save the handle of the item.

    if (nLevel == 1)

        hPrevRootItem = hPrev;

    else if (nLevel == 2)

        hPrevLev2Item = hPrev;

    // The new item is a child item. Give the parent item a

    // closed folder bitmap to indicate it now has child items.

    if (nLevel > 1) {

        hti = TreeView_GetParent(hwndTV, hPrev);

        tvi.mask = TVIF_IMAGE | TVIF_SELECTEDIMAGE;

        tvi.hItem = hti;

        tvi.iImage = g_nClosed;

        tvi.iSelectedImage = g_nClosed;

        TreeView_SetItem(hwndTV, &tvi);

    }

    return hPrev;

}


 Dragging a Tree-View Item

Dragging a tree-view item typically involves processing the TVN_BEGINDRAG (or TVN_BEGINRDRAG) notification message, the WM_MOUSEMOVE message, and the WM_LBUTTONUP (or WM_RBUTTONUP) message. It also involves using the image list functions to draw the item as it is being dragged. For more information about image lists, see Image Lists.

The remainder of this section provides an example that demonstrates how to drag a tree-view item. The example consists of three functions. The first function begins the drag operation, the second drags the image, and the third ends the drag operation.


 Beginning the Tree-View Drag Operation

A tree-view control sends the parent window a TVN_BEGINDRAG (or TVN_BEGINRDRAG) notification message whenever the user starts to drag an item. The parent window receives the notification in the form of a WM_NOTIFY message whose lParam parameter is the address of an NM_TREEVIEW structure. The members of this structure include the screen coordinates of the mouse cursor and a TV_ITEM structure that contains information about the item to be dragged.

The following example shows how to process the WM_NOTIFY message to obtain TVN_BEGINDRAG.

case WM_NOTIFY:

    switch (((LPNMHDR) lParam)->code) {

        case TVN_BEGINDRAG:

            Main_OnBeginDrag(hwndTV,    // application-defined function

                (NM_TREEVIEW *) lParam);

            break;

     .

     .  // Handle other notifications here.

     .

    }

    break;

Beginning the drag operation involves using the ImageList_BeginDrag function. The function's parameters include the handle of the image list containing the image to use during the drag operation and the index of the image. You can either provide your own image list and image, or you can have the tree-view control create them for you by using the TVM_CREATEDRAGIMAGE message.

Because the drag image replaces the mouse cursor for the duration of the drag operation, ImageList_BeginDrag requires you to specify a hot spot within the image. The coordinates of the hot spot are relative to the upper left corner of the image. ImageList_BeginDrag also requires you to specify the initial location of the drag image. An application typically sets the initial location so that the hot spot of the drag image corresponds to that of the mouse cursor at the time the user began the drag operation.

The following function demonstrates how to begin dragging a tree-view item. It uses the drag image provided by the tree-view control and obtains the bounding rectangle of the item to determine the appropriate point for the hot spot. (The dimensions of the bounding rectangle are the same as those of the image.) Note that the bounding rectangle does not account for the indentation of child items. For this reason, the function adds the amount of indentation to the x-coordinate of the hot spot.

The function captures mouse input, causing mouse messages to be sent to the parent window. The parent window needs the subsequent WM_MOUSEMOVE messages to determine where to drag the image and the WM_LBUTTONUP message to determine when to end the drag operation.

// Main_OnBeginDrag - begins dragging an item in a tree-view control.

// hwndTV - handle of the image list

// lpnmtv - address of information about the item being dragged

void Main_OnBeginDrag(HWND hwndTV, NM_TREEVIEW *lpnmtv)

{

    HIMAGELIST himl;    // handle of image list

    RECT rcItem;        // bounding rectangle of item

    DWORD dwLevel;      // heading level of item

    DWORD dwIndent;     // amount that child items are indented

    // Tell the tree-view control to create an image to use

    // for dragging.

    himl = TreeView_CreateDragImage(hwndTV, lpnmtv->itemNew.hItem);

    // Get the bounding rectangle of the item being dragged.

    TreeView_GetItemRect(hwndTV, lpnmtv->itemNew.hItem, &rcItem, TRUE);

    // Get the heading level and the amount that the child items are

    // indented.

    dwLevel = lpnmtv->itemNew.lParam;

    dwIndent = (DWORD) SendMessage(hwndTV, TVM_GETINDENT, 0, 0);

    // Start the drag operation.

    ImageList_BeginDrag(himl, hwndTV, 0,

        lpnmtv->ptDrag.x,

        lpnmtv->ptDrag.y,

        lpnmtv->ptDrag.x - ((dwLevel - 1) * dwIndent),

        lpnmtv->ptDrag.y - rcItem.top);

    // Hide the mouse cursor, and direct mouse input to the

    // parent window.

    ShowCursor(FALSE);

    SetCapture(GetParent(hwndTV));

    g_fDragging = TRUE;

    return;

}


 Dragging the Tree-View Item

You drag a tree-view item by calling the ImageList_DragMove function when the parent window receives a WM_MOUSEMOVE message, as the following example shows. The example also performs hit testing during the drag operation to determine whether to highlight other items in the tree view as targets of a drag and drop operation.

// Main_OnMouseMove - drags an item in a tree-view control,

//     highlighting the item that is the target.

// hwndParent - handle of the parent window

// hwndTV - handle of the tree-view control

// xCur and yCur - x- and y-coordinates of the mouse cursor

void Main_OnMouseMove(HWND hwndParent, HWND hwndTV, LONG xCur, LONG yCur)

{

    HTREEITEM htiTarget;  // handle of target item

    TV_HITTESTINFO tvht;  // hit test information

    if (g_fDragging) {

        // Drag the item to the current position of the mouse cursor.

        ImageList_DragMove(xCur, yCur);

        // Find out if the cursor is on the item. If it is, highlight

        // the item as a drop target.

        tvht.pt.x = xCur;

        tvht.pt.y = yCur;

        if ((htiTarget = TreeView_HitTest(hwndTV, &tvht)) != NULL) {

            TreeView_SelectDropTarget(hwndTV, htiTarget);

        }

    }

    return;

}


 Ending the Tree-View Drag Operation

The follow example ends a drag operation. The ImageList_EndDrag function is called when the parent window receives a WM_LBUTTONUP message.

// Main_OnLButtonUp - stops dragging a tree-view item, releases the

//     mouse capture, and shows the mouse cursor.

//
// Global variable

//     g_fDragging - indicates whether a drag operation is underway.

void Main_OnLButtonUp(void)

{

    if (g_fDragging) {

        ImageList_EndDrag();

        ReleaseCapture();

        ShowCursor(TRUE);

        g_fDragging = FALSE;

    }

    return;

}


 Tree-View Control Reference

The following messages, macros, notification messages, and structures are associated with tree-view controls. These elements can be grouped as follows.

Item Labels

TV_ITEM
TVN_GETDISPINFO

Label Editing

TVM_EDITLABEL
TVM_ENDEDITLABELNOW
TVM_GETEDITCONTROL
TVN_BEGINLABELEDIT
TVN_ENDLABELEDIT

Item States

TVM_GETITEM
TVM_SELECTITEM
TVM_SETITEM
TVN_SELCHANGED
TVN_SELCHANGING

Tree-View Image Lists

TVM_GETIMAGELIST
TVM_SETIMAGELIST

Item Position

TV_INSERTSTRUCT
TVM_INSERTITEM
TVM_SORTCHILDREN
TVM_SORTCHILDRENCB

Parent and Child Items

TVM_EXPAND
TVM_GETINDENT
TVM_SETINDENT
TVN_ITEMEXPANDED
TVN_ITEMEXPANDING

Item Information

TV_DISPINFO
TVM_ENSUREVISIBLE
TVM_GETCOUNT
TVM_GETNEXTITEM
TVM_GETVISIBLECOUNT

Drag and Drop Operations

TV_HITTESTINFO
TVM_CREATEDRAGIMAGE
TVM_HITTEST
TVN_BEGINDRAG
TVN_BEGINRDRAG

Miscellaneous

NM_TREEVIEW
TV_KEYDOWN
TV_SORTCB
TVM_DELETEITEM
TVM_GETISEARCHSTRING
TVM_GETITEMRECT
TVN_DELETEITEM
TVN_KEYDOWN
TVN_SETDISPINFO


 Tree-View Control Messages

An application sends messages to add items and to alter the appearance and behavior of a tree-view control. Each message has a corresponding macro, which you can use instead of sending the message explicitly. Some messages may have related macros, which are a more specialized form of a corresponding macro.

TVM_CREATEDRAGIMAGE
TVM_DELETEITEM
TVM_EDITLABEL
TVM_ENDEDITLABELNOW
TVM_ENSUREVISIBLE
TVM_EXPAND
TVM_GETCOUNT
TVM_GETEDITCONTROL
TVM_GETIMAGELIST
TVM_GETINDENT
TVM_GETISEARCHSTRING
TVM_GETITEM
TVM_GETITEMRECT
TVM_GETNEXTITEM
TVM_GETVISIBLECOUNT
TVM_HITTEST
TVM_INSERTITEM
TVM_SELECTITEM
TVM_SETIMAGELIST
TVM_SETINDENT
TVM_SETITEM
TVM_SORTCHILDREN
TVM_SORTCHILDRENCB


 Tree-View Control Notification Messages

A tree-view control sends notifications messages to its parent window to notify it about events.

TVN_BEGINDRAG
TVN_BEGINLABELEDIT
TVN_BEGINRDRAG
TVN_DELETEITEM
TVN_ENDLABELEDIT
TVN_GETDISPINFO
TVN_ITEMEXPANDED
TVN_ITEMEXPANDING
TVN_KEYDOWN
TVN_SELCHANGED
TVN_SELCHANGING
TVN_SETDISPINFO


 Tree-View Control Structures

The following structures are used with tree-view control messages.

NM_TREEVIEW
TV_DISPINFO
TV_HITTESTINFO
TV_INSERTSTRUCT
TV_ITEM
TV_KEYDOWN
TV_SORTCB


 Tree-View Control Constants

The following window style flags and item state flags are used with tree-view controls.


 Tree-View Window Styles

A tree view's window style can include one or more of the following values.

TVS_DISABLEDRAGDROP	Prevents the tree-view control from sending TVN_BEGINDRAG notification messages.
TVS_EDITLABELS	Allows the user to edit the labels of tree-view items.
TVS_HASBUTTONS	Displays plus (+) and minus (-) buttons next to parent items. The user clicks the buttons to expand or collapse a parent item's list of child items. To include buttons with items at the root of the tree view, TVS_LINESATROOT must also be specified.
TVS_HASLINES	Uses lines to show the hierarchy of items.
TVS_LINESATROOT	Uses lines to link items at the root of the tree-view control. This value is ignored if TVS_HASLINES is not also specified.
TVS_SHOWSELALWAYS	Causes a selected item to remain selected when the tree-view control loses focus.


 Tree-View Item States

An item's state determines its appearance and functionality. It can be zero, or one or more of the following values.

TVIS_BOLD	The item is bold.
TVIS_CUT	The item is selected as part of a cut and paste operation.
TVIS_DROPHILITED	The item is selected as a drag and drop target.
TVIS_EXPANDED	The item's list of child items is currently expanded; that is, the child items are visible. This value applies only to parent items.
TVIS_EXPANDEDONCE	The item's list of child items has been expanded at least once. The TVN_ITEMEXPANDING and TVN_ITEMEXPANDED notification messages are not sent for parent items that have specified this value. This value applies only to parent items.
TVIS_FOCUSED	The item has the focus, so it is surrounded by a standard focus rectangle. Only one item can have the focus.
TVIS_OVERLAYMASK	The item's overlay image is included when the item is drawn. The index of the overlay image must be specified in the state member of the TV_ITEM structure by using the INDEXTOOVERLAYMASK macro. The overlay image must be added to the tree view's image list by using the ImageList_SetOverlayImage function. This value should not be combined with any other value.
TVIS_SELECTED	The item is selected. The appearance of a selected item depends on whether it has the focus and on whether the system colors are used for selection.
TVIS_STATEIMAGEMASK	The item's state image is included when the item is drawn. The index of the state image must be specified in the state member of the TV_ITEM structure by using theINDEXTOSTATEIMAGEMASK macro. This value should not be combined with any other value.
TVIS_USERMASK	Same as TVIS_STATEIMAGEMASK.


 Up-Down Controls

An up-down control is a pair of arrow buttons that the user can click to increment or decrement a value, such as a scroll position or a number displayed in a companion control. The value associated with an up-down control is called its current position. An up-down control is most often used with a companion control, which is called a buddy window.


 About Up-Down Controls

To the user, an up-down control and its buddy window often look like a single control. You can specify that an up-down control automatically position itself next to its buddy window and that it automatically set the caption of the buddy window to its current position. For example, you can use an up-down control with an edit control to prompt the user for numeric input. For more information about edit controls, see Edit Controls The following illustration shows an up-down control with an edit control as its buddy window, a combination that is sometimes referred to as a spinner control.

An up-down control without a buddy window functions as a sort of simplified scroll bar. For example, a tab control sometimes displays an up-down control to enable the user to scroll additional tabs into view. The following illustration shows an up-down control in the upper right corner of a tab control.

You can create an up-down control and specify its buddy window in several ways. The UPDOWN_CLASS value specifies an up-down control's window class. You can specify this window class in a dialog box template or in a call to the CreateWindowEx function. For more information about dialog box templates, see Dialog Boxes. Another way is to use the CreateUpDownControl function to create an up-down control and, at the same time, specify its buddy window, current position, and minimum and maximum positions.

The UPDOWN_CLASS window class is registered when the common controls dynamic-link library (DLL) is loaded. If you create an up-down control without using the CreateUpDownControl function, you must ensure that the DLL is loaded. You can do so by using the InitCommonControls function. For more information about common controls, see Common Controls.

CreateUpDownControl enables you to specify a buddy window. If you create an up-down control without using this function, you can assign a buddy window by specifying the UDS_AUTOBUDDY window style or by using the UDM_SETBUDDY message. If UDS_AUTOBUDDY is specified, the up-down control automatically selects the previous window in the Z order as its buddy window. This window might be the previous control in a dialog box template. You can use UDM_SETBUDDY to assign a specific buddy window to an up-down control. To determine an up-down control's current buddy window, use the UDM_GETBUDDY message. An up-down control and its buddy window must have the same parent window.

An up-down control notifies its parent window when its current position changes by sending it a UDN_DELTAPOS notification message and a WM_VSCROLL message.


 About Up-Down Control Styles

Using window styles, you can control characteristics of an up-down control, such as how it positions itself relative to its buddy window, whether it sets the text of its buddy window, and whether it processes the UP ARROW and DOWN ARROW keys.

An up-down control with the UDS_ALIGNLEFT or UDS_ALIGNRIGHT style aligns with the left or right edge of its buddy window. The width of the buddy window is decreased to accommodate the width of the up-down control.

An up-down control with the UDS_SETBUDDYINT style sets the caption of its buddy window (using the WM_SETTEXT message) whenever the current position changes. The control inserts a thousands separator between every three digits of a decimal string unless the UDS_NOTHOUSANDS style is specified. If the buddy window is a list box, an up-down control sets its current selection instead of its caption.

You can specify the UDS_ARROWKEYS style to provide a keyboard interface for an up-down control. If this style is specified, the control processes the UP ARROW and DOWN ARROW keys. The control also subclasses the buddy window so that it can process these keys when the buddy window has the focus.

If you use an up-down control for horizontal scrolling, you can specify the UDS_HORZ style. This style causes the up-down control's arrows to point left and right instead of up and down.

By default, the current position does not change if the user attempts to increment it or decrement it beyond the maximum or minimum value. You can change this behavior by using the UDS_WRAP style, so the position "wraps" to the opposite extreme. For example, incrementing past the upper limit wraps the position back to the lower limit.


 Position and Acceleration

After an up-down control is created, you can change the control's current position, minimum position, and maximum position by sending messages. You can also change the radix base used to display the current position in the buddy window and the rate at which the current position changes when the up or down arrow is clicked.

To retrieve the current position of an up-down control, use the UDM_GETPOS message. For an up-down control with a buddy window, the current position is the number in the buddy window's caption. Because the caption may have changed (for example, the user may have edited the text of an edit control), the up-down control retrieves the current caption and updates its current position accordingly.

The buddy window's caption may be either a decimal or hexadecimal string, depending on the radix base (that is, either base 10 or 16) of the up-down control. You can set the radix base by using the UDM_SETBASE message and retrieve the radix base by using the UDM_GETBASE message.

The UDM_SETPOS message sets the current position of a buddy window. Note that, unlike a scroll bar, an up-down control automatically changes its current position when the up and down arrows are clicked. An application, therefore, does not need to set the current position when processing the WM_VSCROLL message.

You can change the minimum and maximum positions of an up-down control by using the UDM_SETRANGE message. The maximum position may be less than the minimum, and in that case clicking the up arrow decreases the current position. To put it another way, up means moving towards the maximum position. To retrieve the minimum and maximum positions for an up-down control, use the UDM_GETRANGE message.

You can control the rate at which the position changes when the user holds down an arrow button by setting the up-down control's acceleration. The acceleration is defined by an array of UDACCEL structures. Each structure specifies a time interval and the number of units by which to increment or decrement at the end of that interval. To set the acceleration, use the UDM_SETACCEL message. To retrieve acceleration information, use the UDM_GETACCEL message.


 Default Up-Down Controls Message Processing

This section describes the window message processing performed by an up-down control.

Message	Processing performed
WM_CREATE	Allocates and initializes a private data structure and saves its address as window data.
WM_DESTROY	Frees data allocated during WM_CREATE processing.
WM_ENABLE	Invalidates the window.
WM_KEYDOWN	Changes the current position in the case of an  UP ARROW or DOWN ARROW key.
WM_KEYUP	Ends changing the position.
WM_LBUTTONDOWN	Captures the mouse. If the buddy window is an edit control or list box, it sets the focus to the buddy window. If the mouse is over the up or down button, it begins changing the position and sets a timer.
WM_LBUTTONUP	Ends changing the position and releases the mouse capture if the up-down control has captured the mouse. If the buddy window is an edit control, it selects all the text in the edit control.
WM_PAINT	Paints the up-down control.
WM_TIMER	Changes the current position if the mouse is being held down over a button and a sufficient interval has elapsed.


 Up-Down Control Reference

The following functions, messages, notification messages, and structures are associated with up-down controls. These elements can be grouped as follows.

Up-Down Control Creation

CreateUpDownControl
UDM_GETBUDDY
UDM_SETBUDDY

Current Position and Acceleration

UDACCEL
UDM_GETACCEL
UDM_GETBASE
UDM_GETPOS
UDM_GETRANGE
UDM_SETACCEL
UDM_SETBASE
UDM_SETPOS
UDM_SETRANGE

Notification Messages

UDN_DELTAPOS
WM_VSCROLL


 Up-Down Control Functions

The following function is used with up-down controls.

CreateUpDownControl


 Up-Down Control Messages

The following messages are used with up-down controls.

UDM_GETACCEL
UDM_GETBASE
UDM_GETBUDDY
UDM_GETPOS
UDM_GETRANGE
UDM_SETACCEL
UDM_SETBASE
UDM_SETBUDDY
UDM_SETPOS
UDM_SETRANGE


 Up-Down Control Notification Messages

The following notification message is used with up-down controls.

UDN_DELTAPOS


 Up-Down Control Structures

The following structure is used with up-down controls.

UDACCEL


 Up-Down Control Styles

The following window styles are used with up-down controls.

UDS_ALIGNLEFT	Positions the up-down control next to the left edge of the buddy window. The buddy window is moved to the right and its width decreased to accommodate the width of the up-down control.
UDS_ALIGNRIGHT	Positions the up-down control next to the right edge of the buddy window. The width of the buddy window is decreased to accommodate the width of the up-down control.
UDS_ARROWKEYS	Causes the up-down control to increment and decrement the position when the UP ARROW and DOWN ARROW keys are pressed.
UDS_AUTOBUDDY	Automatically selects the previous window in the Z order as the up-down control's buddy window.
UDS_HORZ	Causes the up-down control's arrows to point left and right instead of up and down.
UDS_NOTHOUSANDS	Does not insert a thousands separator between every three decimal digits.
UDS_SETBUDDYINT	Causes the up-down control to set the text of the buddy window (using the WM_SETTEXT message) when the position changes. The text consists of the position formatted as a decimal or hexadecimal string.
UDS_WRAP	Causes the position to "wrap" if it is incremented or decremented beyond the ending or beginning of the range.


 Buttons

Microsoft® Windows® provides dialog boxes and controls to support communication between an application and the user. A button is a control the user can turn on or off to provide input to an application.


 About Buttons

There are several types of buttons and, within each type, one or more styles to distinguish among buttons of the same type. The user turns a button on or off by selecting it using the mouse or keyboard. Selecting a button typically changes its visual appearance and state (from checked to unchecked, for example). Windows, 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 Windows, 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 Windows 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. For more information about window subclassing, see Window Procedures.


 Button Types and Styles

Windows provides five kinds of buttons: push buttons, check boxes, radio buttons, group boxes, and owner-drawn buttons. Each type has one or more 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 selects 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 selects a push button (of either style), it receives the keyboard focus from Windows, which sends the button's parent window a WM_COMMAND message containing the BN_CLICKED notification code. In response, the dialog box typically closes and carries out the operation indicated by the button.


 Check Boxes

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

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

When the user selects a check box (of any style), the check box receives the keyboard focus from Windows, which 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 Windows 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, not Windows, is responsible for setting the check state for those styles. Regardless of the check box style, Windows automatically repaints the check box once its state is changed.


 Radio Buttons

A radio button consists of a round button and application-defined text (a label), an icon, or a bitmap that indicates a choice the user can make by selecting the button. An application typically uses radio buttons in a group box to permit the user to choose from a set of related, but mutually exclusive options. For example, the application might present a group of radio buttons from which the user can select a format preference for text selected in the client area. The user could select a left-aligned, right-aligned, or centered format by selecting the corresponding radio button. Typically, the user can select only one option at a time from a set of radio buttons.

A radio button can be one of two styles: standard or automatic, as defined by the constants BS_RADIOBUTTON and BS_AUTORADIOBUTTON. Each style can assume two check states: checked (a dot in the button) or unchecked (no dot in the button). Repeatedly selecting a radio button (standard or automatic) toggles it from checked to unchecked and back again.

When the user selects either state, the radio button receives the keyboard focus from Windows, which 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 Windows 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, not Windows, is responsible for setting the check state 1for that style. Regardless of the radio button style, Windows automatically repaints the button as its state changes.

When the user selects an automatic radio button, Windows automatically sets the  check state of all other radio buttons within the same group to unchecked. The same behavior is available for standard radio buttons by using the WS_GROUP style, as discussed in Dialog Boxes.


 Owner-Drawn Buttons

Unlike radio buttons, an owner-drawn button is painted by the application, not by Windows, 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, Windows 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.


 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 Styles

Many developers create dialog boxes by using standalone tools, not requiring them to specify button styles. However, if an application creates a button by using the CreateWindow or CreateWindowEx function, the following table of constants can be used to define the button style.

Style	Meaning
BS_3STATE	Creates a button that is the same as a check box, except that the box can be grayed as well as checked or unchecked. Use the grayed state to show that the state of the check box is not determined.
BS_AUTO3STATE	Creates a button that is the same as a three-state check box, except that the box changes its state when the user selects it. The state cycles through checked, grayed, and unchecked.
BS_AUTOCHECKBOX	Creates a button that is the same as a check box, except that the check state automatically toggles between checked and unchecked each time the user selects the check box.
BS_AUTORADIOBUTTON	Creates a button that is the same as a radio button, except that when the user selects it, Windows automatically sets the button's check state to checked and automatically sets the check state for all other buttons in the same group to unchecked.
BS_CHECKBOX	Creates a small, empty check box with text. By default, the text is displayed to the right of the check box. To display the text to the left of the check box, combine this flag with the BS_LEFTTEXT style (or on Windows 95 only, 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 Windows 95 BS_RIGHTBUTTON style.
BS_OWNERDRAW	Creates an owner-drawn button. The owner window receives a WM_MEASUREITEM message when the button is created and a WM_DRAWITEM message when a visual aspect of the button has changed. Do not combine the BS_OWNERDRAW style with any other button styles.
BS_PUSHBUTTON	Creates a push button that posts a WM_COMMAND message to the owner window when the user selects the button.
BS_RADIOBUTTON	Creates a small circle with text. By default, the text is displayed to the right of the circle. To display the text to the left of the circle, combine this flag with the BS_LEFTTEXT style (or on Windows 95 only, 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	Windows 95 only: Specifies that the button displays a bitmap.
BS_BOTTOM	Windows 95 only: Places text at the bottom of the button rectangle.
BS_CENTER	Windows 95 only: Centers text horizontally in the button rectangle.
BS_ICON	Windows 95 only: Specifies that the button displays an icon.
BS_LEFT	Windows 95 only: 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	Windows 95 only: 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	Windows 95 only: Enables a button to send BN_DBLCLK, BN_KILLFOCUS, and BN_SETFOCUS notification messages to its parent window. Note that buttons send the BN_CLICKED notification message regardless of whether it has this style.
BS_PUSHLIKE	Windows 95 only: 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	Windows 95 only: 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	Windows 95 only: 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	Windows 95 only: Specifies that the button displays text.
BS_TOP	Windows 95 only: Places text at the top of the button rectangle.
BS_VCENTER	Windows 95 only: Places text in the middle (vertically) of the button rectangle.


 Button States

This section discusses how selecting a button changes its state and how the application should respond.


 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 Windows. For a complete description of this interface, see Dialog Boxes.

Selecting a button typically causes the following events:

•	Windows gives the button the keyboard focus.

•	The button sends its parent window a message to notify it of the selection.

•	The parent window (or Windows) sends the button a message to change its state.

•	The parent window (or Windows) repaints the button to reflect its new state.

The following topics discuss these events and button states in greater detail.


 Elements of a Button State

A button's state can be characterized by its focus state, push state, and check 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. Windows automatically changes the highlight for an automatic button, but the application must change the highlight for a nonautomatic button by sending messages.

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 pushed, the background of the button is grayed. When it is not pushed, the background of the button is not grayed.

The check state applies to a check box, radio button, or three-state check box, but does not apply to other buttons. The state can be checked, unchecked, or (for three-state check boxes) indeterminate. A check box is checked when it contains a check mark, and is unchecked when it does not. A radio button is checked when it contains a black dot; and is unchecked when it does not. A three-state check box is checked when it contains a check mark, is unchecked when it does not, and is indeterminate when it contains a grayed box. Windows automatically changes the check state of an automatic button, but the application must change the check state of a nonautomatic 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. Windows automatically changes the focus state for all button types, the push state for push buttons or buttons with the BS_PUSHLIKE style, and the check state for all automatic buttons. The application must make all other state changes, taking into account the button's type, style, and current state. The following list shows the state elements that must be changed for each button type:

•	A check box must change the check state.

•	A radio button must change the check state. It may also be necessary to change the check state of other radio buttons in the same group to ensure the mutually exclusive nature of radio buttons.

•	Because the state of an owner-drawn button is application dependent, what the application must change in the button can vary. No elements of a group box must be changed, because users cannot select group boxes.

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


 Notification Messages from Buttons

When the user selects a button, its state changes, and the button sends notification messages to its parent window. For example, a push button control sends the BN_CLICKED notification message whenever the user chooses the button. In all cases, the low-order word of the wParam parameter contains the control identifier, the high-order word of wParam contains the notification code, and the lParam parameter contains the control window handle.

Portability Issue  The placement of notification message has moved from the lParam parameter to the wParam parameter. Windows 3.x − based applications that process notification messages must be modified in this respect when they are ported to Win32-based applications.

Both the message and the parent window's response depend on the type, style, and current state of the button. Following are the button notification messages an application should monitor and process.

Message	Description
BN_CLICKED	The user clicked a button.
BN_DBLCLK	The user double-clicked a button.
BN_DISABLE	A button is disabled.
BN_PUSHED	The user pushed a button.
BN_KILLFOCUS	The button lost the keyboard focus.
BN_PAINT	The button should be painted.
BN_SETFOCUS	The button gained the keyboard focus.
BN_UNPUSHED	The button is no longer pushed.
A button sends the BN_DISABLE, BN_PUSHED, BN_KILLFOCUS, BN_PAINT, BN_SETFOCUS, and BN_UNPUSHED notification messages only if it has the BS_NOTIFY style. It sends the BN_CLICKED and BN_DBLCLK notification messages regardless of the BS_NOTIFY style.

For automatic buttons, the operating system performs pushing, unpushing, and painting. 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, 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 the handle of a bitmap or icon with a button. The BM_GETIMAGE message retrieves the handle of 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

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

Value	Element colored
COLOR_BTNFACE	Button faces.
COLOR_BTNHIGHLIGHT	Highlight area (the top and left edges) of a button.
COLOR_BTNSHADOW	Shadow area (the bottom and right edges) of a button.
COLOR_BTNTEXT	Regular (nongrayed) text in buttons.
COLOR_GRAYTEXT	Disabled (gray) text in buttons. This color is set to 0 if the current display driver does not support a solid gray color.
COLOR_WINDOW	Window backgrounds.
COLOR_WINDOWFRAME	Window frames.
COLOR_WINDOWTEXT	Text in windows.
An application can retrieve the default values for these colors by calling the GetSysColor function, or set the values by calling the SetSysColors function. For more information about system colors, see System Information. For more information about how colors are used with controls, see Controls.

Portability Issue  The WM_CTLCOLOR message has been replaced by the set of control-color messages. When porting your Windows 3.x−based application to the Win32 API, you must modify any code that processes the WM_CTLCOLOR 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 the handle of 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 the handle of the previous bitmap or icon.
BM_SETSTATE	Sets the push state of the button. For owner-drawn buttons, a WM_DRAWITEM message is sent to the parent window if the state of the button has changed.
BM_SETSTYLE	Sets the button style. If the low-order word of the lParam parameter is TRUE, the button is redrawn.
WM_CHAR	Checks a check box or automatic check box when the user presses the plus (+) or equal (=) keys. Unchecks a check box or automatic check box when the user presses the minus (−) key.
WM_ENABLE	Paints the button.
WM_ERASEBKGND	Erases the background for owner-drawn buttons. The backgrounds of other buttons are erased as part of the WM_PAINT and WM_ENABLE processing.
WM_GETDLGCODE	Returns values indicating the type of input processed by the default button procedure, as shown in the following table.
Button style	Returns
BS_AUTOCHECKBOX
	DLGC_WANTCHARS | DLGC_BUTTON
BS_AUTORADIOBUTTON
	DLGC_RADIOBUTTON
BS_CHECKBOX
	DLGC_WANTCHARS | DLGC_BUTTON
BS_DEFPUSHBUTTON
	DLGC_DEFPUSHBUTTON
BS_GROUPBOX
	DLGC_STATIC
BS_PUSHBUTTON
	DLGC_UNDEFPUSHBUTTON
BS_RADIOBUTTON
	DLGC_RADIOBUTTON
WM_GETFONT	Returns a handle of 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

•	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 a dialog box, as 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 push 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 IDB_BOX1        101             // first check box

#define IDB_BOX2        102             // second check box

#define IDB_BOX3        103             // third check box

#define IDB_REDBACK     104             // top radio button

#define IDB_BLUEBACK    105             // bottom radio button

#define IDB_CLEARBOXES  107             // top push button

#define IDB_CLEARBACK   108             // bottom push button

HBRUSH hbrRed, hbrBlue, hbrWhite;

BOOL fRedBack, fBlueBack, fClearColor;  // background-state flags

Note that it is not necessary to define IDOK, the identifier for the OK push button.

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

LRESULT APIENTRY ButtonProc(hDlg, message, wParam, lParam)

HWND hDlg;                // window handle of dialog box

UINT message;             // type of message

UINT wParam;              // message-specific information

LONG 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

                    IDB_BOX1,             // button identifier

                    BM_SETCHECK,          // message

                    0,                    // check state unchecked)

                    0);                   // must be zero

                SendDlgItemMessage(hDlg, IDB_BOX2,

                    BM_SETCHECK, 0, 0);

                SendDlgItemMessage(hDlg, IDB_BOX3,

                    BM_SETCHECK, 0, 0);

                SendDlgItemMessage(hDlg, IDB_REDBACK,

                    BM_SETCHECK, 0, 0);

                SendDlgItemMessage(hDlg, IDB_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 IDB_BOX1:

                            // Retrieve the state of the

                            // check box.

                            lState = SendDlgItemMessage(

                                hDlg, IDB_BOX1, BM_GETSTATE,

                                0, 0);

                             // The box-painting function is

                             // application defined.

                            BoxPainter(

                                hDlg,     // window handle

                                1,        // box to paint

                                lState);  // state of box

                            break;

                        case IDB_BOX2:

                            lState = SendDlgItemMessage(

                                hDlg, IDB_BOX2, BM_GETSTATE,

                                0, 0);

                            BoxPainter(hDlg, 2, lState);

                            break;

                        case IDB_BOX3:

                            lState = SendDlgItemMessage(

                                hDlg, IDB_BOX3, BM_GETSTATE,

                                0, 0);

                            BoxPainter(hDlg, 3, lState);

                            break;

                        case IDB_REDBACK:

                            fRedBack = TRUE;

                            InvalidateRect(hDlg, NULL,

                                TRUE);

                            break;

                        case IDB_BLUEBACK:

                            fBlueBack = TRUE;

                            InvalidateRect(hDlg, NULL,

                                TRUE);

                            break;

                        case IDB_CLEARBACK:

                            fClearColor = TRUE;

                            InvalidateRect(hDlg, NULL,

                                TRUE);

                            break;

                        case IDB_CLEARBOXES:

                            BoxPainter(hDlg, 4,

                                (LRESULT) 0);

                            break;

                    }

                }

        case WM_DESTROY:

            DeleteObject(hbrRed);

            DeleteObject(hbrBlue);

            // Do not delete hbrWhite, because it is a

            // stock object.

            break;

    }

    return FALSE;       // did not process a message

        UNREFERENCED_PARAMETER(lParam);

}


 Using Owner-Drawn Buttons

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

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

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

LRESULT APIENTRY OwnDrawProc(hDlg, message, wParam, lParam)

HWND hDlg;      // window handle of dialog box

UINT message;   // type of message

UINT wParam;    // message-specific information

LONG 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 IDB_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 functions and messages are associated with buttons.


 Button Functions

Following are the functions used with buttons.

CheckDlgButton
CheckRadioButton
IsDlgButtonChecked


 Button Messages

Following are the messages used with buttons.

BM_CLICK
BM_GETCHECK
BM_GETSTATE
BM_SETCHECK
BM_SETSTATE
BM_SETSTYLE
BN_CLICKED
BN_DISABLE
BN_HILITE
BN_PAINT
BN_UNHILITE
DM_GETDEFID
DM_SETDEFID
WM_CTLCOLORBTN
BN_DBLCLK
BN_DOUBLECLICKED
BN_KILLFOCUS
BN_SETFOCUS


 Combo Boxes

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

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


 About Combo Boxes

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

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

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


 Combo Box Types and Styles

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

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

Combo box type	Drop-down list	Edit control
Drop-down combo box	Yes	Yes
Drop-down list box	Yes	No
Simple combo box	No	Yes
Combo box styles define specific properties of a combo box. An application can combine styles; however some styles only apply to certain combo box types. The following table describes the 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	Specifies a drop-down combo box.
CBS_DROPDOWNLIST	Specifies a drop-down list box.
CBS_HASSTRINGS	Specifies that an owner-drawn combo box contains items consisting of strings. The combo box maintains the memory and address for the strings so the application can use the CB_GETLBTEXT message to retrieve the text for a particular item.
CBS_LOWERCASE	Converts to lowercase all text in both the selection field and the list.
CBS_NOINTEGRALHEIGHT	Specifies that the size of the combo box is exactly the size specified by the application when it created the combo box. Normally, Windows sizes a combo box so that it does not display partial items.
CBS_OEMCONVERT	Converts text entered in the combo box edit control from the Windows character set to the OEM character set and then back to the Windows set. This ensures proper character conversion when the application calls the CharToOem function to convert a Windows string in the combo box to OEM characters. This style is most useful for combo boxes that contain filenames and applies only to combo boxes created with the CBS_SIMPLE or CBS_DROPDOWN style.
CBS_OWNERDRAWFIXED	Specifies that the owner of the list box is responsible for drawing its contents and that the items in the list box are all the same height. The owner window receives a WM_MEASUREITEM message when the combo box is created and a WM_DRAWITEM message when a visual aspect of the combo box has changed.
CBS_OWNERDRAWVARIABLE	Specifies that the owner of the list box is responsible for drawing its contents and that the items in the list box are variable in height. The owner window receives a WM_MEASUREITEM message for each item in the combo box when you create the combo box and a WM_DRAWITEM message when a visual aspect of the combo box has changed.
CBS_SIMPLE	Specifies a simple combo box.
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.


 Combo Box List

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


 List Contents

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

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

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

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

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


 Current Selection

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

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

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

When the user changes the current selection in a combo box, the parent window or dialog-box procedure receives a WM_COMMAND message with the notification message CBN_SELCHANGE in the high-order word of the wParam parameter. As a result, the application can respond to this notification message and execute a specific process each time the user selects a list item. This notification message is not sent when the current selection is set using the CB_SETCURSEL message.

In a drop-down combo box or drop-down list box, an application wait for the use to close the list box before processing a change in the current selection. This can be useful when significant processing is required. For example, to update a directory list based on the selected drive, an application can process the CBN_CLOSEUP message instead of CBN_SELCHANGE to update a directory list after the user selects a drive.

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

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


 Drop-Down Lists

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

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


 Edit Control Selection Fields

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

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

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

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

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

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


 Owner-Drawn Combo Boxes

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

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

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

The owner of an owner-drawn combo box can process a WM_MEASUREITEM message to specify the dimensions of list items in the combo box. If the application creates the combo box by using the CBS_OWNERDRAWFIXED style, Windows 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, Windows 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 of the information as item data. For more information about item data, see Data Associated with List Items. To free data objects associated with items in a combo box, the owner can process the WM_DELETEITEM message.

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


 Subclassed Combo Boxes

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

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

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

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

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


 Special Combo Box Features

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


 Directory Lists

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

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

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

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


 Data Associated with List Items

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

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

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


 The Extended User Interface

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

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


 Combo Box Notifications

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

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


 Default Combo Box Behavior

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

Message	Description
CB_ADDSTRING	Sends an LB_ADDSTRING message to the list window to add a list item.
CB_DELETESTRING	Sends an LB_DELETESTRING message to the list window to delete a list item.
CB_DIR	Adds the filenames matching the specified attributes and path to the list.
CB_FINDSTRING	Sends an LB_FINDSTRING message to the list window. This message returns the index of the first list item that begins with the specified text.
CB_FINDSTRINGEXACT	Sends an LB_FINDSTRING message to the list window. This message returns the index of the first list item exactly matching the specified text.
CB_GETCOUNT	Sends an LB_GETCOUNT message to the list window. It returns the number of list items.
CB_GETCURSEL	Sends an LB_GETCURSEL message to the list window. It returns the index of the currently selected item, if any.
CB_GETDROPPEDCONTROLRECT	Fills the specified rectangle structure with the screen coordinates of a drop-down list.
CB_GETDROPPEDSTATE	Returns TRUE if a drop-down list is open; otherwise, it returns FALSE.
CB_GETDROPPEDWIDTH	Returns the minimum allowable width, in pixels, of the drop down list.
CB_GETEDITSEL	Sends an EM_GETSEL message to the edit control, and it returns the starting and ending position of the current selection. In drop-down list boxes, the window procedure returns CB_ERR.
CB_GETEXTENDEDUI	Returns TRUE if the combo box is a drop-down combo box or drop-down list box and the extend user-interface flag is set; otherwise, it returns FALSE.
CB_GETHORIZONTALEXTENT	Sends an LB_GETHORIZONTALEXTENT message to the list window. It returns the scrollable width, in pixels, of the drop down list.
CB_GETITEMDATA	Sends an LB_GETITEMDATA message to the list window. It returns the 32-bit value associated with the specified list item.
CB_GETITEMHEIGHT	Sends an LB_GETITEMHEIGHT message to the list window. It returns the height, in pixels, of the specified owner-drawn list item.
CB_GETLBTEXT	Sends an LB_GETTEXT message to the list window. It copies the specified list text to the specified buffer.
CB_GETLBTEXTLEN	Sends an LB_GETTEXTLEN message to the list window. It returns the length, in bytes, of the specified list text.
CB_GETLOCALE	Sends an LB_GETLOCALE message to the list window. It returns the current locale for the list.
CB_GETTOPINDEX	Sends an LB_GETTOPINDEX message to the list window. It returns the index of the first visible item in the drop down list.
CB_INITSTORAGE	Sends an LB_INITSTORAGE message to the list window. It initializes space for the specified number of items and the specified number of bytes for item strings.
CB_INSERTSTRING	Sends an LB_INSERTSTRING message to the list window. It inserts a list item at the specified position.
CB_LIMITTEXT	Sends an EM_LIMITTEXT message to the edit control. It sets the maximum number of characters a user can enter in the edit control. In drop-down list boxes, the window procedure returns CB_ERR.
CB_RESETCONTENT	Sends an LB_RESETCONTENT message to the list window, and it removes the contents of the list.
CB_SELECTSTRING	Sends an LB_SELECTSTRING message to the list window. It selects the first list item, if any, that begins with the characters in the specified text.
CB_SETCURSEL	Sends an LB_SETCURSEL message to the list window, and it sets the current selection.
CB_SETDROPPEDWIDTH	Sets the minimum allowable width, in pixels, of the drop down list.
CB_SETEDITSEL	Sends an EM_SETSEL message to the edit control. It selects the specified range of text. In drop-down list boxes, the window procedure returns CB_ERR.
CB_SETEXTENDEDUI	Sets or clears the extended user-interface flag. This flag changes the keys that open and close the list in a drop-down combo box or drop-down list box. If the combo box is a simple combo box, the window procedure returns CB_ERR.
CB_SETHORIZONTALEXTENT	Sends an LB_SETHORIZONTALEXTENT message to the list window. It sets the scrollable width, in pixels, of the drop down list.
CB_SETITEMDATA	Sends an LB_SETITEMDATA message to the list window. It associates the specified 32-bit value with a list item.
CB_SETITEMHEIGHT	Sends an LB_SETITEMHEIGHT message to the list window. It sets the height of the specified owner-drawn list item or the selection field.
CB_SETLOCALE	Sends an LB_SETLOCALE message to the list window, and it sets the current locale for the list. The locale affects how the list is sorted if it has the CBS_SORT style and strings are added using CB_ADDSTRING.
CB_SETTOPINDEX	Sends an LB_SETTOPINDEX message to the list window. It scrolls the drop down list so the specified item is at the top of the visible range.
CB_SHOWDROPDOWN	Shows or hides the drop-down list. This message has no effect on simple combo boxes.
WM_CHAR	Processes character input. In drop-down list boxes, this message is passed to the list window, which moves the selection to the first item beginning with the specified character. In simple and drop-down combo boxes, this message is passed to the edit control.
WM_CLEAR	Deletes the edit selection. In simple and drop-down combo boxes, the edit control processes this message. In drop-down list boxes, the window procedure returns CB_ERR.
WM_COMMAND	Processes notification messages from the edit control and list window and sends corresponding combo box notification messages to the parent window.
	For edit control notifications, the window procedure may update the list window's current selection, caret index, and top index. For list notification messages, the window procedure may update the content of the selection field.
WM_COMPAREITEM	Passes the message to the parent window, enabling the application to specify the relative sort position of two owner-drawn list items. The combo box window receives this message from the list window.
WM_COPY	Copies the edit selection to the clipboard. In simple and drop-down combo boxes, the edit control processes this message. In drop-down list boxes, the window procedure returns CB_ERR.
WM_CREATE	Initializes the combo box.
WM_CUT	Deletes the edit selection and places it on the clipboard. In simple and drop-down combo boxes, the edit control processes this message. In drop-down list boxes, the window procedure returns CB_ERR.
WM_DELETEITEM	Passes the message to the parent window, notifying the application that a list item has been deleted. The combo box window receives this message from the list window.
WM_DRAWITEM	Passes the message on to the parent window enabling the application to paint the specified list item. The combo box window receives this message from the list window. The window procedure can also originate this message to have the application paint the selection field of a drop-down list box.
WM_ENABLE	Sets the state to enable or prohibit mouse and keyboard input.
WM_ERASEBKGND	Returns 1, indicating that the background is erased.
WM_GETDLGCODE	Returns a combination of the DLG_WANTCHARS and DLGC_WANTARROWS values.
WM_GETFONT	Returns the handle of 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 Win32 API. 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 chooses 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 chooses 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(hwndDlg, msg, wParam, lParam)

HWND hwndDlg;

UINT msg;

WPARAM wParam;

LPARAM lParam;

{

    switch (msg) {

        case WM_INITDIALOG:

            if (!OpenDictionary()) {

                EndDialog(hwndDlg, 0);

                break;

            }

            SendMessage(hwndEdit, EM_SETSEL, 0, 0);

            do

                if (!SelectNextWord(hwndEdit, achTemp)) {

                    GlobalFree((HGLOBAL) lpstrDict);

                    LocalFree((HLOCAL) paLpDict);

                    EndDialog(hwndDlg, 0);

                    break;

                }

            while (!InitSpellList(

                GetDlgItem(hwndDlg, IDCOMBO), achTemp));

            break;

        case WM_COMMAND:

            switch (LOWORD(wParam)) {

                case IDCOMBO:

                    if (HIWORD(wParam) != CBN_DBLCLK)

                        break;

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

                case IDOK:

                    SendDlgItemMessage(hwndDlg, IDCOMBO,

                        WM_GETTEXT, sizeof(achTemp),

                        (LPARAM) achTemp);

                    SendMessage(hwndEdit, EM_REPLACESEL, 0,

                        (LPARAM) achTemp);

                    /* Fall through to get the next word. */

                case IDIGNORE:

                    do

                        if (!SelectNextWord(hwndEdit, achTemp)) {

                            EndDialog(hwndDlg, 0);

                            break;

                        }

                    while (!InitSpellList(GetDlgItem(hwndDlg,

                        IDCOMBO), achTemp));

                    break;

                case IDCANCEL:

                    EndDialog(hwndDlg, 0);

            }

            break;

        case WM_DESTROY:

            GlobalFree((HGLOBAL) lpstrDict);

            LocalFree((HLOCAL) paLpDict);

            break;

        default:

            return FALSE;

    }

    return TRUE;

}

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

    FUNCTION:   InitSpellList

    PURPOSE:    Initializes the selection field and list

                of suggestions for the specified word, if

                it is not in the dictionary.

    RETURNS:    If the list is initialized, the return

                value is TRUE. If an error occurs or the

                word is in the dictionary, the return

                value is FALSE.

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

BOOL PASCAL InitSpellList(HWND hwndCombo, LPSTR lpszWord)

{

    int min = 0;        /* beginning of search range */

    int max = cWords;   /* end of search range       */

    int n;              /* index of word             */

    int cmp;            /* result of comparison      */

    char ch;            /* first character in word   */

    ch = *lpszWord;

    CharLowerBuff(&ch, 1);

    /*

     * Perform a binary search for the word.

     *

     * The global array paLpDict contains pointers to words

     * in the global array lpstrDict. These two variables are

     * initialized by the OpenDictionary function.

     */

    n = max / 2;

    while (min < max) {

        cmp = lstrcmpi(lpszWord, paLpDict[n]);

        if (cmp == 0)

            return FALSE;       /* not misspelled */

        if (cmp < 0)

            max = n;

        else

            min = n + 1;

        n = (min + max) / 2;

    }

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

    SendMessage(hwndCombo, CB_RESETCONTENT, 0, 0);

    while (n > 0 && *paLpDict[n - 1] == ch)

        n--;

    while (*paLpDict[n] == ch)

        SendMessage(hwndCombo, CB_ADDSTRING,

            0, (LPARAM) paLpDict[n++]);

    /* Place the word in the selection field. */

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

    return TRUE;

}


 Creating an Owner-Drawn Combo Box

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


 Creating the Owner-Drawn Dialog Box

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

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

For more information about dialog boxes, see Dialog Boxes.


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

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

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

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

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


 Processing the WM_MEASUREITEM Message

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

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


 Processing the WM_DRAWITEM Message

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

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

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


 Processing the WM_COMMAND Message in an Owner-Drawn Dialog Box

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

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

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

If the control identifier is IDOK, the user has chosen the OK button. In response, the dialog box procedure inserts the name of the selected food into the application's multiline 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(hwndDlg, msg, wParam, lParam)

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

             * 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 of each edit control by using the ChildWindowFromPoint function.

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

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


 Processing the WM_SETFOCUS Message

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


 Processing the Application-Defined Messages

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

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

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


 Creating a Combo-box Toolbar

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

#define WM_TAB (WM_USER)

#define WM_ESC (WM_USER + 1)

#define WM_ENTER (WM_USER + 2)

HWND hwndMain;

HWND hwndEdit;

WNDPROC lpfnEditWndProc; /* original window procedure for */

                         /*   the combo box edit windows  */

int cyToolbar;           /* toolbar window height        */

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

    FUNCTION:   ToolbarWindowProc

    PURPOSE:    Window procedure for the toolbar window

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

LRESULT CALLBACK ToolbarWindowProc(hwnd, msg, wParam, lParam)

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;

    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, msg, wParam, lParam)

HWND hwnd;

UINT msg;

WPARAM wParam;

LPARAM lParam;

{

    switch (msg) {

        case WM_KEYDOWN:

            switch (wParam) {

                case VK_TAB:

                    SendMessage(hwndToolbar, WM_TAB, 0, 0);

                    return 0;

                case VK_ESCAPE:

                    SendMessage(hwndToolbar, WM_ESC, 0, 0);

                    return 0;

                case VK_RETURN:

                    SendMessage(hwndToolbar, 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 functions and messages are associated with combo boxes.


 Combo Box Functions

Following are the functions used with combo boxes.

DlgDirListComboBox
DlgDirSelect
DlgDirSelectComboBox
DlgDirSelectComboBoxEx


 Combo Box Messages

Following are the messages used with combo boxes.

CB_ADDSTRING
CB_DELETESTRING
CB_DIR
CB_FINDSTRING
CB_FINDSTRINGEXACT
CB_GETCOUNT
CB_GETCURSEL
CB_GETDROPPEDCONTROLRECT
CB_GETEDITSEL
CB_GETEXTENDEDUI
CB_GETITEMDATA
CB_GETITEMHEIGHT
CB_GETLBTEXT
CB_GETLBTEXTLEN
CB_GETLOCALE
CB_INSERTSTRING
CB_LIMITTEXT
CB_RESETCONTENT
CB_SELECTSTRING
CB_SETCURSEL
CB_SETEDITSEL
CB_SETEXTENDEDUI
CB_SETITEMDATA
CB_SETITEMHEIGHT
CB_SETLOCALE
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


 Controls

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


 About Controls

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

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

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


 Predefined Controls

Windows 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. 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.
COMBOBOX	Creates combo boxes. These controls are a combination of list boxes and edit controls, letting the user choose and edit items.
EDIT	Creates edit controls. These controls let the user view and edit text.
LISTBOX	Creates list boxes. These controls display a list from which the user can select one or more items.
SCROLLBAR	Creates scroll bar controls. These controls let the user choose the direction and distance to scroll information in a related window.
STATIC	Creates static controls. These controls often act as labels for other 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. Windows provides the following ways to create custom controls:

•	Use owner-drawn buttons, list boxes, and combo boxes.

•	Subclass an existing control-window class.

•	Register and implement from scratch an application-defined window class.

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, Windows 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 the individual topics for buttons, list boxes, and combo boxes.

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 about subclassing, see Window Classes.

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 topics for the predefined controls.

An application can create custom controls by registering an application-defined window class and specifying the name of the window class in the CreateWindowEx function or in the dialog box template. 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. Each class must have a unique name, a corresponding window procedure, and other information.

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


 Control Notification Messages

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

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


 Control Messages

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

Control messages can be predefined or application defined. Windows 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. Windows 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 Messages

Following are the messages used with controls.

WM_GETFONT
WM_SETFONT
WM_SETTEXT


 Dialog Boxes

In Microsoft® Windows®, a dialog box is a temporary window an application creates to retrieve user input. An application typically uses dialog boxes to prompt the user for additional information for commands. A dialog box usually contains one or more controls (child windows) with which the user enters text, chooses options, or directs the action of the command.


 About Dialog Boxes

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

Windows also provides many predefined, or "common," dialog boxes that support commands, such as File Open and File Print. Applications that use these commands should use the common dialog boxes to prompt for the same user input, regardless of the type of application carrying out the commands. For more information about using common dialog boxes in your applications, see Common Dialog Box Library.


 When to Use a Dialog Box

Most applications use dialog boxes to prompt for additional information for commands that require user input. Using a dialog box is the only recommended way for an application to retrieve the input. For example, the File Open command requires the name of a file to open, so an application should use a dialog box to prompt the user for the name. In such cases, the application creates the dialog box when the user chooses the command and destroys the dialog box immediately after the user supplies the information.

Many applications also use dialog boxes to display information or options while the user works in another window. For example, word processing applications often use a dialog box with a text-search command. While the application searches for the text, the dialog box remains on the screen. The user can then return to the dialog box and search for the same word again; or the user can change the entry in the dialog box and search for a new word. Applications that use dialog boxes in this way typically create one when the user chooses a command and continue to display it for as long as the application runs or until the user explicitly closes the dialog box.

To support the different ways applications use dialog boxes, Windows provides two types of dialog box: modal and modeless. A modal dialog box requires the user to supply information or cancel the dialog box before allowing the application to continue. Applications use modal dialog boxes in conjunction with commands that require additional information before they can proceed. A modeless dialog box allows the user to supply information and return to the previous task without closing the dialog box. Modal dialog boxes are simpler to manage than modeless dialog boxes because they are created, perform their task, and are destroyed by calling a single function.

To create either a modal or modeless dialog box, an application must supply a dialog box template to describe the dialog box style and content; the application must also supply a dialog box procedure to carry out tasks. The dialog box template is a binary description of the dialog box and the controls it contains. The developer can create this template as a resource to be loaded from the application's executable file, or created in memory while the application runs. The dialog box procedure is an application-defined callback function that Windows 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 and pass additional information to the dialog box procedure as the dialog box is created.

Dialog boxes usually belong to a predefined, exclusive window class. Windows uses this window class and its corresponding window procedure for both modal and modeless dialog boxes. When the function is called, it creates the window for the dialog box, as well as the windows for the controls in the dialog box, then sends selected messages to the dialog box procedure. While the dialog box is visible, the predefined window procedure manages all messages, processing some messages and passing others to the dialog box procedure so that the procedure can carry out tasks. Applications do not have direct access to the predefined window class or window procedure, but they can use the dialog box template and dialog box procedure to modify the style and behavior of a dialog box.


 Owner Window

Most dialog boxes have an owner window (or more simply, an owner). When creating the dialog box, the application sets the owner by specifying the owner's window handle. Windows 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, Windows can send messages to the window procedure of the owner, notifying it of events in the dialog box.

Windows automatically hides or destroys the dialog box whenever its owner is hidden or destroyed. This means the dialog box procedure requires no special processing to detect changes to the state of the owner window.

Because the typical dialog box is used in conjunction with a command in a menu, the owner window is usually the window containing the menu. Although it is possible to create a dialog box that has no owner, it is not recommended. For example, when a modal dialog box has no owner, Windows 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, Windows neither hides nor destroys the dialog box when other windows in the application are hidden or destroyed. Although this does not defeat the purpose of the modeless dialog box, it requires that the application carry out special processing to ensure the dialog box is hidden and destroyed at appropriate times.


 Message Boxes

A message box is a special dialog box that an application can use to display messages and prompt for simple input. A message box typically contains a text message and one or more buttons. An application creates the message box by using the MessageBox or MessageBoxEx function, specifying the text and the number and types of buttons to display. The MessageBoxEx function also allows you to specify the language to use for the text of any predefined push buttons in the message box.

Although the message box is a dialog box, Windows 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. Windows 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 Windows creates it by using the same internal functions that DialogBox uses. If the application specifies an owner window when calling MessageBox or MessageBoxEx, Windows disables the owner. An application can also direct Windows to disable all top-level windows belonging to the current task by specifying the MB_TASKMODAL value when creating the dialog box.

Windows can send messages to the owner, such as WM_CANCELMODE and WM_ENABLE, just as it does when creating a modal dialog box. The owner window should carry out any actions requested by these messages.


 Modal Dialog Boxes

A modal dialog box should be a pop-up window having a System menu, a title bar, and a thick border; that is, the dialog box template should specify the WS_POPUP, WS_SYSMENU, WS_CAPTION, and DS_MODALFRAME styles. Although an application can designate the WS_VISIBLE style, Windows always displays a modal dialog box regardless of whether the dialog box template specifies the WS_VISIBLE style. An application must not create a modal dialog box having the WS_CHILD style. A modal dialog box with this style disables itself, preventing any subsequent input from reaching the application.

An application creates a modal dialog box by using either the DialogBox or DialogBoxIndirect function. DialogBox requires the name or identifier of a resource containing a dialog box template; DialogBoxIndirect requires the handle of a memory object containing a dialog box template. The DialogBoxParam and DialogBoxIndirectParam functions also create modal dialog boxes; they are identical to the previously mentioned functions but pass a specified parameter to the dialog box procedure when the dialog box is created.

When creating the modal dialog box, Windows makes it the active window. The dialog box remains active until the dialog box procedure calls the EndDialog function or Windows 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, Windows 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, Windows enables the owner window again, but only if the modal dialog box caused the owner to be disabled.

As Windows 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 Windows 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, Windows starts its own message loop, taking temporary control of the message queue for the entire application. When Windows 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.

Windows sends the WM_ENTERIDLE message to the owner window whenever the application message queue is empty. The application can use this message to carry out a background task while the dialog box remains on the screen. When an application uses the message in this way, the application must frequently yield control (for example, by using the PeekMessage function) so that the modal dialog box can receive any user input. To prevent the modal dialog box from sending the WM_ENTERIDLE messages, the application can specify the DS_NOIDLEMSG style when creating the dialog box.

An application destroys a modal dialog box by using the EndDialog function. In most cases, the dialog box procedure calls EndDialog when the user chooses the Close command from the dialog box's System menu or chooses the OK or Cancel button in the dialog box. The dialog box can return a value through the DialogBox function (or other creation functions) by specifying a value when calling the EndDialog function. Windows 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. Windows does not return control from the function that creates the dialog box until the dialog box procedure has called the EndDialog function.


 Modeless Dialog Boxes

A modeless dialog box should be a pop-up window having a System menu, a title bar, and a thin border; that is, the dialog box template should specify the WS_POPUP, WS_CAPTION, WS_BORDER, and WS_SYSMENU styles. Windows does not automatically display the dialog box unless the template specifies the WS_VISIBLE style.

An application creates a modeless dialog box by using the CreateDialog or CreateDialogIndirect function. CreateDialog requires the name or identifier of a resource containing a dialog box template; CreateDialogIndirect requires the handle of a memory object containing a dialog box template. Two other functions, CreateDialogParam and CreateDialogIndirectParam, also create modeless dialog boxes; they pass a specified parameter to the dialog box procedure when the dialog box is created.

CreateDialog and other creation functions return a window handle for the dialog box. The application and the dialog box procedure can use this handle to manage the dialog box. For example, if WS_VISIBLE is not specified in the dialog box template, the application can display the dialog box by passing the window handle to the ShowWindow function.

A modeless dialog box neither disables the owner window nor sends messages to it. When creating the dialog box, Windows makes it the active window, but the user or the application can change the active window at any time. If the dialog box does become inactive, it remains above the owner window in the Z order, even if the owner window is active.

The application is responsible for retrieving and dispatching input messages to the dialog box. Most applications use the main message loop for this. To permit the user to move to and select controls by using the keyboard, however, the application must call the IsDialogMessage function. For more information about this function, see Dialog Box Keyboard Interface.

A modeless dialog box cannot return a value to the application as a modal dialog box does, but the dialog box procedure can send information to the owner window by using the SendMessage function.

An application must destroy all modeless dialog boxes before terminating. It can destroy a modeless dialog box by using the DestroyWindow function. In most cases, the dialog box procedure calls DestroyWindow in response to user input, such as choosing the Cancel button. If the user never closes the dialog box in this way, the application must call DestroyWindow.

DestroyWindow invalidates the window handle for the dialog box, so any subsequent calls to functions that use the handle return error values. To prevent errors, the dialog box procedure should notify the owner that the dialog box has been destroyed. Many applications maintain a global variable containing the handle for the dialog box. When the dialog box procedure destroys the dialog box, it also sets the global variable to NULL, indicating that the dialog box is no longer valid.

The dialog box procedure must not call the EndDialog function to destroy a modeless dialog box.


 Dialog Box Template

A dialog box template is binary data that describes the dialog box, defining its height, width, style, and the controls it contains. To create a dialog box, Windows 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 book. For more information about creating template resources and adding them to an executable file, see the documentation provided with your application development tools.

Applications that create dialog boxes without using template resources must create templates in memory and pass the templates to either the DialogBoxIndirect or CreateDialogIndirect function. An application creates a memory template by allocating a global memory object and filling it with a DLGTEMPLATE structure and one or more DLGITEMTEMPLATE structures. A memory template is identical in form and content to a template resource. Many applications that use memory templates first load a template resource into memory by using the LoadResource function, then modify the loaded resource to create a new memory template.

The following sections describe the styles, measurements, and other values used in a dialog box template.


 Dialog Box Template Styles

Every dialog box template specifies a combination of style values that define the appearance and features of the dialog box. The style values can be window styles, such as WS_POPUP and WS_SYSMENU, and dialog box styles, such as DS_MODALFRAME. The number and type of styles for a template depends on the type and purpose of the dialog box.

Windows passes all window styles given in the template to the CreateWindowEx function when creating the dialog box. Windows may pass one or more extended styles depending on the given dialog box styles. For example, when the template specifies DS_MODALFRAME, Windows uses WS_EX_DLGMODALFRAME when creating the dialog box. When the template specifies DS_SYSMODAL, Windows uses WS_EX_TOPMOST. All other dialog box styles affect how Windows manages the dialog box.

Most dialog boxes are pop-up windows that have a System menu and a title bar. Therefore, the typical template specifies the WS_POPUP, WS_SYSMENU, and WS_CAPTION styles. The template also specifies a border style: WS_BORDER for modeless dialog boxes, and DS_MODALFRAME for modal dialog boxes. A template may specify a window type other than pop-up (such as WS_OVERLAPPED) if it creates a customized window instead of a dialog box.

Windows always displays a modal dialog box regardless of whether the WS_VISIBLE style is given. When the template for a modeless dialog box specifies the WS_VISIBLE style, Windows automatically displays the dialog box when it is created. Otherwise, the application is responsible for displaying the dialog box by using the ShowWindow function.

The template can specify the DS_SETFOREGROUND style to force Windows to bring the dialog box to the foreground. This is especially useful for modal dialog boxes that require immediate attention from the user regardless of whether the owner window is the foreground window.

Using the DS_ABSALIGN style, Windows interprets dialog box measurements as screen coordinates; using the DS_SETFONT style, Windows uses a given font, instead of the system font, to draw text in the dialog box client area and in the controls in the dialog box; the DS_NOIDLEMSG style prevents a modal dialog box from sending WM_ENTERIDLE messages to the owner window. These styles are described in more detail in later topics.

The DS_LOCALEDIT style does not apply to Win32-based applications.

Dialog boxes with the DS_SYSMODAL style receive the WS_EX_TOPMOST window style but no other special properties or styles; this means the user still has access to other windows on the desktop even though a DS_SYSMODAL dialog box may be displayed.


 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.

Dialog box measurements are given in dialog base units. One horizontal unit is equal to one-fourth of the average character width for the system font. One vertical unit is equal to one-eighth of the average character height for the system font. An application can retrieve the number of pixels per base unit for the current display by using the GetDialogBaseUnits function. An application can convert measurements from dialog base units to pixels by using the MapDialogRect function.

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. Windows 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 and are within the client area of the dialog box. Although Windows 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. Windows creates each control by passing this data to the CreateWindowEx function. Controls are created in the order they are given in the template. The template should specify the appropriate number, type, and order of controls to ensure that the user can enter the input needed to complete the command associated with the dialog box.

For each control, the template specifies style values that define the appearance and operation of the control. Every control is a child window and therefore must have the WS_CHILD style. To ensure that the control is visible when the dialog box is displayed, each control must also have the WS_VISIBLE style. Other commonly used window styles are WS_BORDER for controls that have optional borders, WS_DISABLED for controls that should be disabled when the dialog box is initially created, and WS_TABSTOP and WS_GROUP for controls that can be accessed using the keyboard. The WS_TABSTOP and WS_GROUP styles are used in conjunction with the dialog keyboard interface described later in this topic.

The template may also specify control styles specific to the control's window class. For example, a template that specifies a button control must give a button control style such as BS_PUSHBUTTON or BS_CHECKBOX. Windows 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.

Windows converts the position coordinates and the width and height measurements from dialog base units to pixels, before passing these to CreateWindowEx. When Windows creates a control, it specifies the dialog box as the parent window. This means Windows 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 a custom control window class, the template gives the name of that registered window class or the atom value currently associated with the name.

Each control in a dialog box must have a unique identifier to distinguish it from other controls. Controls send information to the dialog box procedure through WM_COMMAND messages, so the control identifiers are essential for the procedure to determine which control sent a given message. The only exception to this rule are control identifiers for static controls. Static controls do not require unique identifiers because they send no WM_COMMAND messages.

To permit the user to close the dialog box, the template should specify at least one push button and give it the control identifier IDCANCEL. To permit the user to choose between completing or canceling the command associated with the dialog box, the template should specify two push buttons, labeled OK and Cancel, with control identifiers of IDOK and IDCANCEL, respectively.

A template also specifies optional text and creation data for a control. The text typically provides labels for button controls or specifies the initial content of a static text control. The creation data is one or more bytes of data that Windows passes to the control window procedure when creating the control. Creation data is useful for controls that require more information about their initial content or style than is given by other data. For example, an application can use creation data to set the initial setting and range for a scroll bar control.


 System Menu

Windows gives a dialog box a System menu when the template specifies the WS_SYSMENU style. To prevent inappropriate command input, Windows automatically disables all commands in the menu except the Move and Close commands. The user can use the Move command to move the dialog box. When the user chooses the Close command, Windows sends a WM_COMMAND message to the dialog box procedure with the wParam parameter set to IDCANCEL. This is identical to the message sent by the Cancel button when the user chooses it. The recommended action for this message is to close the dialog box and cancel the requested command or task.

Although other menus in dialog boxes are not recommended, a dialog box template can specify a menu by supplying the identifier or the name of a menu resource. In this case, Windows 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

Windows draws all text in dialog box using the system font by default. An application can direct Windows to use another font by setting the DS_SETFONT style for the dialog box and specifying a point size and typeface name. Although a dialog box template can specify a font, Windows always uses the system font for the title and menus of the dialog box; the DS_SETFONT style does not change this.

When the DS_SETFONT style is specified, the system sends a WM_SETFONT message to the dialog box procedure and to each control as it creates the control. The dialog box procedure is responsible for saving the font handle passed with the WM_SETFONT message and selecting the handle into the display device context whenever it writes text to the window. Predefined controls do this by default.

When the DS_SETFONT style is given, Windows uses the average character width of the font to calculate the position and dimensions of the dialog box. Otherwise, it uses the average character width of the system font.


 Templates in Memory

A template in memory consists of a DLGTEMPLATE structure and related data followed by one or more DLGITEMTEMPLATE structures and related data. There is one DLGITEMTEMPLATE structure for each control in the dialog box.

The DLGTEMPLATE structure specifies the position, width, height, style, and number of controls in the dialog box. Additional data following the structure specifies the optional menu, class, title, and font for the dialog box. The DLGTEMPLATE structure has the following form:

typedef struct { // dltt

    DWORD style;

    DWORD dwExtendedStyle;

    WORD  cdit;

    WORD  x;

    WORD  y;

    WORD  cx;

    WORD  cy;

} DLGTEMPLATE;

The style member specifies the window and dialog box styles for the dialog box. Windows does not use the dwExtendedStyle member when creating a dialog box. An application that uses templates to create other types of windows can use this member to specify extended window styles for the other windows. The x and y members specify the dialog box position; cx and cy specify the width and height. The cdit member specifies the number of controls in the dialog box and is the same as the number of DLGITEMTEMPLATE structures in the template.

The DLGTEMPLATE structure is immediately followed by a 16-bit value that specifies whether the dialog box has a menu. When the value is 0x0000, the dialog box has no menu. When the value is 0xFFFF, the subsequent 16-bit value specifies the identifier of the menu resource that describes the dialog box's menu. When the initial value is neither 0x0000 nor 0xFFFF, Windows assumes it is the start of a null-terminated string specifying the name of the menu resource that describes the dialog box's menu.

The first 16-bit value following the menu identifier or name specifies the window class to which the dialog box belongs. When the value is 0x0000, Windows uses the predefined dialog box class for the dialog box. When the value is 0xFFFF, the subsequent 16-bit value is an atom value identifying a registered window class. When the initial value is neither 0x0000 nor 0xFFFF, Windows assumes it is the start of a null-terminated string identifying a registered window class.

The dialog box title immediately follows the class atom or name. The title is a null-terminated string. When the string is empty, Windows leaves the title bar for the dialog box blank. When the dialog box does not have the WS_CAPTION style, Windows sets the title to the given string but does not display it.

When the dialog box has the DS_SETFONT style, the dialog box title is immediately followed by a 16-bit value specifying the point size and by a null-terminated string specifying the typeface for the font. Windows uses this data to create a font for use when writing text in the dialog box client area and in each control. When the dialog box does not have the DS_SETFONT style, the 16-bit value and string are not part of the template.

Each DLGITEMTEMPLATE structure in the template contains data specifying the position, width, height, style, and identifier of the control. Additional information follows each structure, specifying the window class to which the control belongs, the initial text for the control, and any other creation data needed to create the control. A DLGITEMTEMPLATE structure has the following form:

typedef struct { // dlit

    DWORD style;

    DWORD dwExtendedStyle;

    WORD  x;

    WORD  y;

    WORD  cx;

    WORD  cy;

    WORD  id;

} DLGITEMTEMPLATE;

The style member specifies the control style. This member is a combination of window-style flags, such as BS_PUSHBUTTON and WS_VISIBLE. Windows does not use the dwExtendedStyle member to create controls for dialog boxes. Applications that use templates to create other types of windows can use this member to specify extended window styles for those controls. The x and y members specify the coordinates of the upper left corner of the control; cx and cy specify the width and height of the control. The id member is the control identifier.

The control's window class is specified by an atom or name immediately following the DLGITEMTEMPLATE structure. When the first 16-bit value after the structure is 0xFFFF, the subsequent 16-bit value is an atom value identifying a registered window class. Otherwise, the first value is the start of a null-terminated string specifying the name of a registered window class.

The control text starts on the first 16-bit boundary after the class atom or name. This text is either two 16-bit values specifying a resource identifier or a null- terminated string specifying the initial text for the control. If this member is a resource identifier, the first 16-bit value is 0xFFFF and the second is the identifier. Resource identifiers are usually given for controls, such as static icon controls, that load and display icons or other resources rather than displaying text.

Any additional creation data required by the control follows the control text. Windows passes this data to the control as the creation parameters when it calls the CreateWindowEx function.


 Dialog Box Procedure

A dialog box procedure is similar to a window procedure in that Windows sends messages to the procedure when it has information to give or tasks to carry out. Unlike a window procedure, a dialog box procedure never calls the DefWindowProc function. Instead, it returns the Boolean value TRUE if it processes a message or FALSE if it does not.

Every dialog box procedure has the following form:

BOOL APIENTRY DlgProc(hwndDlg, message, wParam, lParam)

HWND hwndDlg;

UINT message;

WPARAM wParam;

LPARAM lParam;

{

    switch (message) {

        // Place message cases here.

        default:

            return FALSE;

    }

}

The procedure parameters serve the same purpose as in a window procedure, with the hwndDlg parameter receiving the window handle of the dialog box.

Most dialog box procedures process the WM_INITDIALOG message and the WM_COMMAND messages sent by the controls, but process few if any other messages. If a dialog box procedure does not process a message, it must return FALSE to direct Windows 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 Windows to further process the WM_INITDIALOG message. In any case, the procedure must not call DefWindowProc.


 The WM_INITDIALOG Message

Windows does not send a WM_CREATE message to the dialog box procedure. Instead, it sends a WM_INITDIALOG message when it creates the dialog box and all its controls but before it displays the dialog box. The procedure should carry out any initialization required to ensure that the dialog box displays the current settings associated with the command or task. For example, when a dialog box contains a control to show the current drive and directory, the procedure must determine the current drive and directory and set the control to that value.

The procedure can initialize controls by using functions such as SetDlgItemText and CheckDlgButton. Because controls are windows, the procedure can also manipulate them by using window-management functions such as EnableWindow and SetFocus. The procedure can retrieve the window handle for a control by using the GetDlgItem function.

The dialog box procedure can change the contents, state, and position of any control as needed. For example, in a dialog box that contains a list box of filenames and an Open button, the procedure can disable the Open button until the user selects a file from the list. In this example, the dialog box template specifies the WS_DISABLED style for the Open button and Windows 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.

If the application creates the dialog box by using one of the functions DialogBoxParam, DialogBoxIndirectParam, CreateDialogParam, or CreateDialogIndirectParam, the lParam parameter for the WM_INITDIALOG message contains the extra parameter passed to the function. Applications typically use this extra parameter to pass the address of additional initialization information to the dialog box procedure, but the dialog box procedure must determine the meaning of the parameter. If the application uses another function to create the dialog box, Windows sets the lParam parameter to NULL.

Before returning from the WM_INITDIALOG message, the procedure should determine whether it should set the input focus to a given control. If the dialog box procedure returns TRUE, Windows 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 Windows from setting the default focus. The control receiving the default input focus is always the first control given in the template that is visible, not disabled, and has the WS_TABSTOP style. If no such control exists, Windows sets the default input focus to the first control in the template.


 The WM_COMMAND Message

A control can send a WM_COMMAND message to the dialog box procedure when the user carries out an action in the control. These messages, called notification messages, inform the procedure of user input and permit it to carry out appropriate responses.

All predefined controls, except static controls, send notification messages for selected user actions. For example, a push button sends the BN_CLICKED notification message whenever the user chooses the button. In all cases, the low-order word of the wParam parameter contains the control identifier, the high-order word of wParam contains the notification code, and the lParam parameter contains the control window handle.

The dialog box procedure should monitor and process notification messages. In particular, the procedure must process messages having the IDOK or IDCANCEL identifiers; these messages represent a request by the user to close the dialog box. The procedure should close the dialog box by using the EndDialog function for modal dialog boxes and the DestroyWindow function for modeless dialog boxes.

Windows also sends WM_COMMAND messages to the dialog box procedure if the dialog box has a menu, such as the System menu, and the user chooses a command. In particular, Windows sends a WM_COMMAND message with the wParam parameter set to IDCANCEL whenever the user chooses the Close command in the dialog box's System menu. The message is nearly identical to the notification message sent by the Cancel button and should be processed in exactly the same way.


 The WM_PARENTNOTIFY Message

A control sends a WM_PARENTNOTIFY message whenever the user presses a mouse button while pointing to the control. Some applications interpret this message as a signal to carry out an action related to the control, such as displaying a line of text describing the purpose of the control.

Windows also sends WM_PARENTNOTIFY messages when it creates and destroys a window, but not for controls created from a dialog box template. Windows 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 Windows 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 of the display device context to the procedure in the message's wParam parameter.

Windows 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, Windows 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, Windows 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	Returns the control identifier of the default push button if it exists. Otherwise, returns zero.
DM_SETDEFID	Sets the control specified by the control identifier in the wParam parameter to the default push button.
WM_ACTIVATE	Restores the input focus to the control identified by the previously saved handle if the dialog box is activated. Otherwise, the procedure saves the handle of the control having the input focus.
WM_CHARTOITEM	Returns zero.
WM_CLOSE	Posts the BN_CLICKED notification message to the dialog box, specifying IDCANCEL as the control identifier. If the dialog box has an IDCANCEL control identifier and the control is currently disabled, the procedure sounds a warning and does not post the message.
WM_COMPAREITEM	Returns zero.
WM_ERASEBKGND	Fills the dialog box client area by using either the brush returned from the WM_CTLCOLORDLG message or with the default window color.
WM_GETFONT	Returns the handle of the application-defined dialog box font.
WM_INITDIALOG	Returns zero.
WM_LBUTTONDOWN	Sends a CB_SHOWDROPDOWN message to the combo box having the input focus, directing the control to hide its drop-down list box. The procedure calls DefWindowProc to complete the default action.
WM_NCDESTROY	Releases global memory allocated for edit controls in the dialog box (applies to dialog boxes in Windows-based applications that specify the DS_LOCALEDIT style) and frees any application-defined font (applies to dialog boxes that specify the DS_SETFONT style). The procedure calls the DefWindowProc function to complete the default action.
WM_NCLBUTTONDOWN	Sends a CB_SHOWDROPDOWN message to the combo box having the input focus, directing the control to hide its drop-down list box. The procedure calls DefWindowProc to complete the default action.
WM_NEXTDLGCTL	Sets the input focus to the next or previous control in the dialog box, to the control identified by the handle in the wParam parameter, or to the first control in the dialog box that is visible, not disabled, and has the WS_TABSTOP style. The procedure ignores this message if the current window with the input focus is not a control.
WM_SETFOCUS	Sets the input focus to the control identified by a previously saved control window handle. If no such handle exists, the procedure sets the input focus to the first control in the dialog box template that is visible, not disabled, and has the WS_TABSTOP style. If no such control exists, the procedure sets the input focus to the first control in the template.
WM_SHOWWINDOW	Saves the handle of the control having the input focus if the dialog box is being hidden, then calls DefWindowProc to complete the default action.
WM_SYSCOMMAND	Saves the handle of the control having the input focus if the dialog box is being minimized, then calls DefWindowProc to complete the default action.
WM_VKEYTOITEM	Returns zero.
The predefined window procedure passes all other messages to DefWindowProc for default processing.


 Dialog Box Keyboard Interface

Windows provides a special keyboard interface for dialog boxes that carries out special processing for several keys. The interface generates messages that correspond to certain buttons in the dialog box or changes the input focus from one control to another. Following are the keys used in this interface and their respective actions.

Key	Action
ALT+mnemonic	Moves the input focus to the first control (having the WS_TABSTOP style) after the static control containing the given mnemonic.
DOWN	Moves the input focus to the next control in the group.
ENTER	Sends a WM_COMMAND message to the dialog box procedure. The wParam parameter is set to IDOK or control identifier of the default push button.
ESC	Sends a WM_COMMAND message to the dialog box procedure. The wParam parameter is set to IDCANCEL.
LEFT	Moves the input focus to the previous control in the group.
mnemonic	Moves the input focus to the first control (having the WS_TABSTOP style) after the static control containing the given mnemonic.
RIGHT	Moves the input focus to the next control in the group.
SHIFT+TAB	Moves the input focus to the previous control that has the WS_TABSTOP style.
TAB	Moves the input focus to the next control that has the WS_TABSTOP style.
UP	Moves the input focus to the previous control in the group.
The Win32 API automatically provides the keyboard interface for all modal dialog boxes. It does not provide the interface for modeless dialog boxes unless the application calls the IsDialogMessage function to filter messages in its main message loop. This means that the application must pass the message to IsDialogMessage immediately after retrieving the message from the message queue. The function processes the messages if it is for the dialog box and returns a nonzero value to indicate that the message has been processed and must not be passed to the TranslateMessage or DispatchMessage function.

Because the dialog box keyboard interface uses direction keys to move between controls in a dialog box, an application cannot use these keys to scroll the contents of any modal dialog box or any modeless dialog box for which IsDialogMessage is called. When a dialog box has scroll bars, the application must provide an alternate keyboard interface for the scroll bars. Note that the mouse interface for scrolling is available when the system includes a mouse.


 The WS_TABSTOP Style

The TAB key and SHIFT+TAB keys have no effect when the controls in the dialog box do not have the WS_TABSTOP style. Windows looks for this style as it searches for the next control in the dialog box to receive the input focus.

When the user presses TAB or SHIFT+TAB, Windows first determines whether the control having the input focus processes these keys. It sends the control a WM_GETDLGCODE message, and if the control returns DLGC_WANTTAB, Windows passes the keys to the control. Otherwise, Windows 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, Windows moves the input focus to it.

An application can also use GetNextDlgTabItem to locate controls having the WS_TABSTOP style. The function retrieves the window handle of the next or previous control having the WS_TABSTOP style without moving the input focus.


 The WS_GROUP Style

By default, Windows 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, Windows 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, Windows first determines whether the current control having the input focus processes the direction keys. Windows sends a WM_GETDLGCODE message to the control and if the control returns the DLGC_WANTARROWS value, passes the key to the control. Otherwise, Windows uses the GetNextDlgGroupItem function to determine the next control in the group.

GetNextDlgGroupItem searches controls in the order (or reverse order) they were created. If the user presses the RIGHT or DOWN key, GetNextDlgGroupItem returns the next control if that control does not have WS_GROUP style. Otherwise, the function reverses the order of the search and returns the first control that has the WS_GROUP style. If the user presses the LEFT or UP key, the function returns the previous control unless the current control already has the WS_GROUP style. If the current control has this style, the function reverses the order of the search, locates the first control having the WS_GROUP style, and returns the control that immediately precedes the located control.

Once Windows has the next or previous control, it sends a WM_GETDLGCODE message to the control to determine the control type. Windows then moves the input focus to control if it is not a static control. If the control is an automatic radio button, Windows 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. Windows 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. Windows moves the input focus to the control associated with the mnemonic whenever the user either presses the key that corresponds to the mnemonic or presses this key and the ALT key in combination. Mnemonics provide a quick way for the user to move to a given control by using the keyboard.

An application creates a mnemonic for a control by inserting the ampersand (&) immediately before the selected letter or digit in the label or text for the control. In most cases, the null-terminated string provided with the control in the dialog box template contains the ampersand. However, an application can create a mnemonic at any time by replacing a control's existing label or text by using the SetDlgItemText function. Only one mnemonic can be given for each control. Although it is recommended, mnemonics in a dialog box need not be unique.

When the user presses a letter or digit key, Windows first determines whether the current control having the input focus processes the key. Windows sends a WM_GETDLGCODE message to the control, and if the control returns the DLGC_WANTALLKEYS or DLG_WANTMESSAGE value, Windows passes the key to the control. Otherwise, it searches for a control whose mnemonic matches the given letter or digit. It continues to search until it locates a control or has examined all controls. During the search, it skips any static controls that have the SS_NOPREFIX style.

If Windows locates a static control and the control is not disabled, Windows 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 Windows 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, Windows 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, Windows sends the BM_CLICK message to the control.


 Dialog Box Settings

The dialog box settings are the current selections and values for the controls in the dialog box. The dialog box procedure is responsible for initializing the controls to these settings when creating the dialog box. It is also responsible for retrieving the current settings from the controls before destroying the dialog box. The methods used to initialize and retrieve settings depend on the type of control.


 Radio Buttons and Check Boxes

Dialog boxes use radio buttons and check boxes to let the user choose from a list of options. Radio buttons let the user choose from mutually exclusive options; check boxes let the user pick a combination of options.

The dialog box procedure can set the initial state of a check box by using the CheckDlgButton function, which sets or clears the check box. For radio buttons in a group of mutually exclusive radio buttons, the dialog box procedure can use the CheckRadioButton function to set the appropriate radio button and automatically clear any other radio button.

Before a dialog box terminates, the dialog box procedure can check the state of each radio button and check box by using the IsDlgButtonChecked function, which returns the current state of the button. A dialog box typically saves this information to initialize the buttons the next time it creates the dialog box.


 Dialog Box Edit Controls

Many dialog boxes have edit controls that let the user supply text as input. Most dialog box procedures initialize an edit control when the dialog box first starts. For example, the dialog box procedure may place a proposed filename in the control that the user can then select, modify, or replace. The dialog box procedure can set the text in an edit control by using the SetDlgItemText function, which copies text from a given buffer to the edit control. When the edit control receives the input focus, it automatically selects the complete text for editing.

Because edit controls do not automatically return their text to the dialog box, the dialog box procedure must retrieve the text before it terminates. It can retrieve the text by using the GetDlgItemText function, which copies the edit control text to a buffer. The dialog box procedure typically saves this text to initialize the edit control later or passes it on to the parent window for processing.

Some dialog boxes use edit controls that let the user enter numbers. The dialog box procedure can retrieve a number from an edit control by using the GetDlgItemInt function, which retrieves the text from the edit control and converts the text to a decimal value. The user types the number in decimal digits. It can be either signed or unsigned. The dialog box procedure can display an integer by using the SetDlgItemInt function. SetDlgItemInt converts a signed or unsigned integer to a string of decimal digits.


 List Boxes, Combo Boxes, and Directory Listings

Some dialog boxes display lists of names from which the user can select one or more names. To display a list of filenames, for example, a dialog box typically uses a list box and the DlgDirList and DlgDirSelect 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 DlgDirSelectComboBox function retrieves a selected filename from the list box portion.


 Dialog Box Control Messages

Many controls recognize predefined messages that, when received by controls, cause them to carry out some action. For example, the BM_SETCHECK message sets the check in a check box and the EM_GETSEL message retrieves the portion of the control's text that is currently selected. The control messages give a dialog procedure greater and more flexible access to the controls than the standard functions, so they are often used when the dialog box requires complex interactions with the user.

A dialog box procedure can send a message to a control by supplying the control identifier and using the SendDlgItemMessage function, which is identical to the SendMessage function, except that it uses a control identifier instead of a window handle to identify the control that is to receive the message. A given message may require that the dialog procedure send parameters with the message, and the message may have corresponding return values. The operation and requirements of each control message depends on the purpose of the message and the control that processes it.

For more information about the control messages, see Controls.


 Custom Dialog Boxes

An application can create custom dialog boxes by using an application-defined window class for the dialog boxes instead of using the predefined dialog box class. Applications typically use this method when a dialog box is their main window, but it is also useful for creating modal and modeless dialog boxes for applications that have standard overlapping windows.

The application-defined window class allows the application to define a window procedure for the dialog box and process messages before sending them to the dialog box procedure. It also lets the application define a class icon, a class background brush, and a class menu for the dialog box. The application must register the window class before attempting to create a dialog box and must provide the dialog box template with the atom value or name of the window class.

Many applications create a new dialog box class by first retrieving the class information for the predefined dialog box class, and passing it to the GetClassInfo function, which fills a WNDCLASS structure with the information. The application modifies individual members of the structure, such as the class name, brush, and icon, then registers the new class by using the RegisterClass function. If an application fills the WNDCLASS structure on its own, it must set the cbWndExtra member to the DLGWINDOWEXTRA, which is the number of extra bytes Windows 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 Windows.

The window procedure for the custom dialog box has the same parameters and requirements as any other window procedure. Unlike other window procedures, however, the window procedure for this dialog box should call the DefDlgProc function instead of the DefWindowProc function for any messages it does not process. DefDlgProc carries out the same default message processing as the window procedure for the predefined dialog box, which includes calling the dialog box procedure.

An application can also create custom dialog boxes by subclassing the window procedure of the predefined dialog box. The SetWindowLong function lets an application set the address of the window procedure for a given window. The application may also attempt to subclass by using the SetClassLong function, but doing so affects all dialog boxes in the system, not just those belonging to the application.

Applications that create custom dialog boxes sometimes provide an alternate keyboard interface for the dialog boxes. For modeless dialog boxes, this may mean the application does not call the IsDialogMessage function and instead processes all keyboard input in the custom window procedure. In such cases, the application can use the WM_NEXTDLGCTL message to minimize the code needed to move the input focus from one control to another. This message, when passed to DefDlgProc, moves the input focus to a specified control and updates the appearance of the controls, such as moving the default push button border or setting an automatic radio button.


 Using Dialog Boxes

You use dialog boxes to display information and prompt for input from the user. Your application loads and initializes the dialog box, processes user input, and destroys the dialog box when the user finishes the task. The process for handling dialog boxes varies, depending on whether the dialog box is modal or modeless. A modal dialog box requires the user to close the dialog box before activating another window in the application. However, the user can activate windows in different applications. A modeless dialog box does not require an immediate response from the user. It is similar to a main window containing controls. The following sections discuss how to use both types of dialog boxes.

•	Displaying a message box

•	Creating a modal dialog box

•	Creating a modeless dialog box

•	Initializing a dialog box

•	Creating a template in memory


 Displaying a Message Box

The simplest form of modal dialog box is the message box. Most applications use message boxes to warn the user of errors and to prompt for directions on how to proceed after an error has occurred. You create a message box by using the MessageBox or MessageBoxEx function, specifying the message and the number and type of buttons to display. Windows creates a modal dialog box, providing its own dialog box template and procedure. After the user closes the message box, MessageBox or MessageBoxEx returns a value identifying the button chosen by the user to close the message box.

In the following example, the application displays a message box if the fError variable is TRUE. The message box displays the message describing the error. The MB_OKCANCEL style directs MessageBox to provide two buttons with which the user can choose how to proceed:

if (fError) {

    if (MessageBox(hwndDlg, SZNOTFOUND, SZDELETEITEM,

        MB_OKCANCEL)==IDOK)

        .

        . // Prompt for a new item name and repeat the command.

        .

    else

        .

        . // Cancel the command.

        .

}

In this example, SZNOTFOUND and SZDELETEITEM are application-defined, null-terminated strings that represent the message text and the title for the message box.


 Creating a Modal Dialog Box

You create a modal dialog box by using the DialogBox function. You must specify the identifier or name of a dialog box template resource and the address of the dialog box procedure. The DialogBox function loads the template, displays the dialog box, and processes all user input until the user closes the dialog box.

In the following example, the application displays a modal dialog box when the user chooses a Delete Item command from an application menu. The dialog box contains an edit control (in which the user enters the name of an item) and OK and Cancel buttons. The control identifiers for these controls are ID_ITEMNAME, IDOK, and IDCANCEL, respectively.

The first part of the example consists of the statements that create the modal dialog box. These statements, in the window procedure for the application's main window, create the dialog box when the system receives a WM_COMMAND message having the IDM_DELETEITEM command identifier. The second part of the example is the dialog box procedure, which retrieves the contents of the edit control and closes the dialog box upon receiving a WM_COMMAND message.

The following statements create the modal dialog box. The dialog box template is a resource in the application's executable file and has the resource identifier DLG_DELETEITEM:

        case WM_COMMAND:

            switch (LOWORD(wParam)) {

                case IDM_DELETEITEM:

                    if (DialogBox(hinst,

                         MAKEINTRESOURCE(DLG_DELETEITEM),

                         hwnd, (DLGPROC)DeleteItemProc)==IDOK)

                        .

                        . // Complete the command; szItemName

                        . // contains the name of the item to

                        . // delete.

                        .

                     else

                        .

                        . // Cancel the command.

                        .

                break;

            }

            return 0L;

In this example, the application identifies its main window as the owner window for the dialog box. When Windows initially displays the dialog box, its position is relative to the upper left corner of the owner window's client area. The application uses the return value from DialogBox to determine whether to proceed with the command or cancel it. The following statements define the dialog box procedure.

char szItemName[80]; // receives name of item to delete.

BOOL CALLBACK DeleteItemProc(hwndDlg, message, wParam, lParam)

HWND hwndDlg;

UINT message;

WPARAM wParam;

LPARAM lParam;

{

    switch (message) {

        case WM_COMMAND:

            switch (LOWORD(wParam)) {

                case IDOK:

                    if (!GetDlgItemText(hwndDlg, ID_ITEMNAME,

                             szItemName, 80))

                         *szItemName=0;

                    // Fall through.

                case IDCANCEL:

                    EndDialog(hwndDlg, wParam);

                    return TRUE;

            }

    }

    return FALSE;

}

In this example, the procedure uses GetDlgItemText to retrieve the current text from the edit control identified by ID_ITEMNAME. The procedure then calls the EndDialog function to set the dialog box's return value to either IDOK or IDCANCEL, depending on the message received, and to begin the process of closing the dialog box. The IDOK and IDCANCEL identifiers correspond to the OK and Cancel buttons. After the procedure calls EndDialog, Windows sends additional messages to the procedure to destroy the dialog box and returns the dialog box's return value back to the function that created the dialog box.


 Creating a Modeless Dialog Box

You create a modeless dialog box by using the CreateDialog function, specifying the identifier or name of a dialog box template resource and the address of the dialog box procedure. CreateDialog loads the template, creates the dialog box, and optionally displays it. Your application is responsible for retrieving and dispatching user input messages to the dialog box procedure.

In the following example, the application displays a modeless dialog box — if it is not already displayed — when the user chooses a Go To command from an application menu. The dialog box contains an edit control, a check box, and OK and Cancel buttons. The dialog box template is a resource in the application's executable file and has the resource identifier DLG_GOTO. The user enters a line number in the edit control and checks the check box to specify that the line number is relative to the current line. The control identifiers are ID_LINE, ID_ABSREL, IDOK, and IDCANCEL.

The statements in the first part of the example create the modeless dialog box. These statements, in the window procedure for the application's main window, create the dialog box when the window procedure receives a WM_COMMAND message having the IDM_GOTO command identifier, but only if the global variable hwndGoto does not already contain a valid handle. The second part of the example is the application's main message loop. The loop includes the IsDialogMessage function to ensure that the user can use the dialog box keyboard interface in this modeless dialog box. The third part of the example is the dialog box procedure. The procedure retrieves the contents of the edit control and check box when the user chooses the OK button. The procedure destroys the dialog box when the user chooses the Cancel button.

HWND hwndGoto = NULL;  // window handle of dialog box

    .

    .

    .

    case WM_COMMAND:

        switch (LOWORD(wParam)) {

            case IDM_GOTO:

                if (!IsWindow(hwndGoto)) {

                    hwndGoto = CreateDialog(hinst,

                         MAKEINTRESOURCE(DLG_GOTO),

                         hwnd, (DLGPROC) GoToProc);

                    ShowWindow(hwndGoto, SW_SHOW);

                }

                break;

        }

        return 0L;

In the preceding statements, CreateDialog is called only if hwndGoto does not contain a valid window handle. This ensures that the application does not display two dialog boxes at the same time. To support this method of checking, the dialog procedure must set hwndGoto to NULL when it destroys the dialog box.

The message loop for an application consists of the following statements:

while (GetMessage(&msg, NULL, NULL, NULL)) {

    if (!IsWindow(hwndGoto) || !IsDialogMessage(hwndGoto, &msg)) {

        TranslateMessage(&msg);

        DispatchMessage(&msg);

    }

}

The loop checks the validity of the window handle for the dialog box and only calls the IsDialogMessage function if the handle is valid. IsDialogMessage only processes the message if it belongs to the dialog box. Otherwise, it returns FALSE and the loop dispatches the message to the appropriate window.

The following statements define the dialog box procedure:

int iLine;             // receives line number

BOOL fRelative;        // receives check box status

    .

    .

    .

BOOL CALLBACK GoToProc(hwndDlg, message, wParam, lParam)

HWND hwndDlg;

UINT message;

WPARAM wParam;

LPARAM lParam;

{

    BOOL fError;

    switch (message) {

        case WM_INITDIALOG:

            CheckDlgButton(hwndDlg, ID_ABSREL, fRelative);

            return TRUE;

        case WM_COMMAND:

            switch (LOWORD(wParam)) {

                case IDOK:

                    fRelative = IsDlgButtonChecked(hwndDlg,

                        ID_ABSREL);

                    iLine = GetDlgItemInt(hwndDlg, ID_LINE,

                        &fError, fRelative);

                    if (fError) {

                        MessageBox(hwndDlg, SZINVALIDNUMBER,

                            SZGOTOERR, MB_OK);

                        SendDlgItemMessage(hwndDlg, ID_LINE,

                            EM_SETSEL, 0, -1L);

                    } else

                        .

                        . // Notify the owner window to carry

                        . // out the command.

                        .

                    return TRUE;

                case IDCANCEL:

                    DestroyWindow(hwndDlg);

                    hwndGoto = NULL;

                    return TRUE;

            }

    }

    return FALSE;

}

In the preceding statements, the procedure processes the WM_INITDIALOG and WM_COMMAND messages. During WM_INITDIALOG processing, the procedure initializes the check box by passing the current value of the global variable fRelative to CheckDlgButton. The procedure then returns TRUE to direct Windows to set the default input focus.

During WM_COMMAND processing, the procedure closes the dialog box only if the user chooses the Cancel button — that is, the button having the IDCANCEL identifier. The procedure must call DestroyWindow to close a modeless dialog box. Notice that the procedure also sets the hwndGoto variable to NULL to ensure that other statements that depend on this variable operate correctly.

If the user chooses the OK button, the procedure retrieves the current state of the check box and assigns it to the fRelative variable. It then uses the variable to retrieve the line number from the edit control. GetDlgItemInt translates the text in the edit control into an integer. The value of fRelative determines whether the function interprets the number as a signed or unsigned value. If the edit control text is not a valid number, GetDlgItemInt sets the value of the fError variable to nonzero. The procedure checks this value to determine whether to display an error message or carry out the command. In the event of an error, the dialog box procedure sends a message to the edit control, directing it to select the text in the control so that the user can easily replace it. If GetDlgItemInt does not return an error, the procedure can either carry out the requested command itself or send a message to the owner window, directing it to carry out the command.


 Initializing a Dialog Box

You initialize the dialog box and its contents while processing the WM_INITDIALOG message. The most common task is to initialize the controls to reflect the current dialog box settings. Another common task is to center a dialog box on the screen or within its owner window. A useful task for some dialog boxes is to set the input focus to a given control rather than accept the default input focus.

In the following example, the dialog box procedure centers the dialog box and sets the input focus while processing the WM_INITDIALOG message. To center the dialog box, the procedure retrieves the window rectangles for the dialog box and the owner window and calculates a new position for the dialog box. To set the input focus, the procedure checks the wParam parameter to determine the identifier of the default input focus:

HWND hwndOwner;

RECT rc, rcDlg, rcOwner;

    case WM_INITDIALOG:

        // Get the owner window and dialog box rectangles.

        if ((hwndOwner = GetParent(hwndDlg)) == NULL)

            hwndOwner = GetDesktopWindow();

        GetWindowRect(hwndOwner, &rcOwner);

        GetWindowRect(hwndDlg, &rcDlg);

        CopyRect(&rc, &rcOwner);

         // Offset the owner and dialog box rectangles so that

         // right and bottom values represent the width and

         // height, and then offset the owner again to discard

         // space taken up by the dialog box.

        OffsetRect(&rcDlg, -rcDlg.left, -rcDlg.top);

        OffsetRect(&rc, -rc.left, -rc.top);

        OffsetRect(&rc, -rcDlg.right, -rcDlg.bottom);

         // The new position is the sum of half the remaining

         // space and the owner's original position.

        SetWindowPos(hwndDlg,

            HWND_TOP,

            rcOwner.left + (rc.right / 2),

            rcOwner.top + (rc.bottom / 2),

            0, 0,          // ignores size arguments

            SWP_NOSIZE);

        if (GetDlgCtrlID((HWND) wParam) != ID_ITEMNAME) {

            SetFocus(GetDlgItem(hwndDlg, ID_ITEMNAME));

            return FALSE;

        }

        return TRUE;

In the preceding statements, the procedure uses the GetParent function to retrieve the owner window handle for a dialog box. The function returns the owner window handle for dialog boxes, and the parent window handle for child windows. Because an application can create a dialog box that has no owner, the procedure checks the returned handle and uses the GetDesktopWindow function to retrieve the desktop window handle, if necessary. After calculating the new position, the procedure uses the SetWindowPos function to move the dialog box, specifying the HWND_TOP value to ensure that the dialog box remains on top of the owner window.

Before setting the input focus, the procedure checks the control identifier of the default input focus. Windows 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:

LRESULT DisplayMyMessage(HINSTANCE hinst, HWND hwndOwner,

    LPSTR lpszMessage)

{

    HGLOBAL hgbl;

    LPDLGTEMPLATE lpdt;

    LPDLGITEMTEMPLATE lpdit;

    LPWORD lpw;

    LPWSTR lpwsz;

    LRESULT ret;

    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->cdit = 1;

    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;

    lstrcpyW(lpwsz, L"My Message");  // dialog title (Unicode)

    lpw = (LPWORD) (lpwsz + lstrlenW(lpwsz) + 1);

    // Define an OK button.

    lpdit = (LPDLGITEMTEMPLATE) lpw;

    lpdit->x  = 10; lpdit->y  = 10;

    lpdit->cx = 40; 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;

    lstrcpyW(lpwsz, L"OK");  // button label (Unicode)

    lpw = (LPWORD) (lpwsz + lstrlenW(lpwsz) + 1);

    *lpw++ = 0;              // no creation data

    // Define a Help button.

    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;

    lstrcpyW(lpwsz, L"Help");        // button label (Unicode)

    lpw = (LPWORD) (lpwsz + lstrlenW(lpwsz) + 1);

    *lpw++ = 0;                      // no creation data

    // Define a static text control.

    lpdit = (LPDLGITEMTEMPLATE) lpw;

    lpdit->x  = 55; 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++;  // message

         );

    lpw = (LPWORD) lpwsz;

    *lpw++ = 0;                              // no creation data

    GlobalUnlock(hgbl);

    ret = DialogBoxIndirect(hinst, (LPDLGTEMPLATE) hgbl,

        hwndOwner, (DLGPROC) DialogProc);

    GlobalFree(hgbl);

    return ret;

}


 Dialog Box Reference

The following functions, structures, and messages are associated with dialog boxes.


 Dialog Box Functions

Following are the functions used to create and manage dialog boxes and controls within dialog boxes.

CreateDialog
CreateDialogIndirect
CreateDialogIndirectParam
CreateDialogParam
DefDlgProc
DialogBox
DialogBoxIndirect
DialogBoxIndirectParam
DialogBoxParam
DialogProc
EndDialog
GetDialogBaseUnits
GetDlgCtrlID
GetDlgItem
GetDlgItemInt
GetDlgItemText
GetNextDlgGroupItem
GetNextDlgTabItem
IsDialogMessage
MapDialogRect
MessageBox
MessageBoxEx
SendDlgItemMessage
SetDlgItemInt
SetDlgItemText
MessageBoxIndirect


 Dialog Box Structures

Following are the structures used to create and manage dialog boxes and controls within dialog boxes.

DLGITEMTEMPLATE
DLGTEMPLATE
MSGBOXPARAMS


 Dialog Box Messages

Following are the messages used to create and manage dialog boxes and controls within dialog boxes.

WM_CTLCOLORMSGBOX
WM_ENTERIDLE
WM_GETDLGCODE
WM_INITDIALOG
WM_NEXTDLGCTL


 Edit Controls

Microsoft® Windows® 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 from the keyboard.


 About Edit Controls

An edit control is selected and receives the input focus when a user clicks the mouse inside it or presses the TAB key. After it is selected, the edit control displays its text (if any) and a flashing caret that indicates the insertion point. The user can then enter text, move the insertion point, or select text to be moved or deleted by using the keyboard or the mouse. An edit control can send notification messages to its parent window in the form of WM_COMMAND messages. For more information about messages from an edit control, see Edit Control Notification Messages. A parent window can send messages to an edit control in a dialog box by calling the SendDlgItemMessage function. Each of the messages sent to edit controls are discussed in this overview.

Windows provides both single line edit controls (sometime called SLEs) and multiline edit controls (sometimes called MLEs). Edit controls belong to the EDIT window class.

A combo box is a control that combines much of the functionality of an edit control and a list box. In a combo box, the edit control displays the current selection and the list box presents options a user can select. For more information about combo boxes, see Combo Boxes.

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


 Edit Control Styles

Windows provides several edit control styles. An individual edit control can have several styles at the same time. Most developers use standalone 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.

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

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

There are three styles that cause Windows 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. These styles apply only to multiline edit controls.

An application can use a style to determine how Windows 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 Windows string (such as a filename) into a specific character set. The ES_OEMCONVERT style ensures the proper conversion of characters in these instances. For more information about character sets, see Consoles and Character-Mode Support.

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

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

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


 The Text Buffer

Windows stores edit control text in a buffer and copies it to the control, as necessary. This section discusses the tools Windows provides to allocate and initialize the buffer and to change its characteristics.


 Allocating a Text Buffer

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

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

1.	Retrieve the handle of the memory currently allocated for the text in a multiline edit control by sending the control an EM_GETHANDLE message.

2.	Free the buffer by calling the LocalFree function.

3.	Obtain a new buffer (and buffer handle) by calling LocalAlloc.

4.	Give the buffer handle to Windows 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, Windows maintains a read-only flag that indicates whether the control's text is read-write (the default) or read-only. An application can set the read-write or read-only flag for the text by sending the control an EM_SETREADONLY message. To determine whether an edit control is read-only, an application can call the GetWindowLong function using the GWL_STYLE constant. The EM_SETREADONLY message applies to both single-line and multiline edit controls.


 Changing the Formatting Rectangle

The visibility of an edit control's text is governed by the dimensions of its window rectangle and its formatting rectangle. The window rectangle is the client area of the window containing the edit control. The formatting rectangle is a construct maintained by Windows 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

Windows automatically processes all user-initiated text operations and notifies the application when the operations are completed. This section discusses user-initiated text operations and the application's response.


 Character Sets

Windows (except version 4.0) supports two character sets: Unicode™, a two-byte character set, and ANSI, a one-byte character set that is a strict subset of Unicode. In ANSI, n characters equals n bytes, but in Unicode, n characters equals 2n bytes. For more information about Unicode and character sets, see Unicode and Character Sets.


 Fonts

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.


 Selecting an Edit Control

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


 Selecting Text

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

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

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


 Replacing Text

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

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


 Cut, Copy, Paste, and Clear Operations

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


 Modifying Text

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


 Limiting User-Entered Text

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

When the user reaches the character limit of an edit control, Windows 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, Windows would send an EN_MAXTEXT notification message to the application.


 Character and Line Operations

The Microsoft® Win32® application programming interface (API) provides several messages that return information about the characters and lines in an edit control. Most of the messages return an index, usually a zero-based number, to refer to a character or line. Given this, a single-line edit control containing n characters, the line index is zero and the characters are indexed from zero to n − 1. In a multiline edit control containing m lines and n characters, the lines are indexed from zero to m − 1, and the characters are indexed from zero to n − 1. Note that character indexing ignores linebreaks.

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

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

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


 Scrolling Text in an Edit Control

An application can implement scrolling in an edit control by using the automatic scrolling styles discussed in Edit Control Styles or by explicitly adding scroll bars to the 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.

Windows 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. This message applies to multiline edit controls only.

The EM_SCROLL message scrolls a multiline edit control vertically, which is the same effect as sending a WM_VSCROLL message. The wParam parameter specifies the scrolling action. The EM_SCROLL message applies to multiline edit controls only.

The EM_SCROLLCARET message scrolls the caret into view in an edit control. This was done in previous versions of Windows by specifying wParam = FALSE in an EM_SETSEL message. A Win32-based application should use the EM_SCROLLCARET message for the task.


 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 Windows to redraw the text. To do that, an application can call the InvalidateRect function. The EM_SETTABSTOPS message applies to multiline edit controls only.

An application can set width of the left and right margins for an edit control by using the EM_SETMARGINS message. After sending this message, Windows redraws the edit control to reflect the new margin settings. An application can retrieve the width of the left or right margin by sending the EM_GETMARGINS message. By default, the edit control margins are set to be just wide enough to accommodate the largest character horizontal overhang (negative ABC widths) for the font currently in use in the edit control.


 Password Characters

An application can use a password character in an edit control to conceal user input. When a password character is set, it is displayed in place of each character the user types. When a password character is removed, the control displays the characters the user types. If the application creates an edit control using the style ES_PASSWORD, the default password character is an asterisk (*). An application can use the EM_SETPASSWORDCHAR message to remove or define a different password character and the EM_GETPASSWORDCHAR message to retrieve the current password character. These messages apply to single-line edit controls only.


 Using Integers

Windows provides two integer-conversion functions for edit controls designed to contain numbers only. The SetDlgItemInt function creates the string representation of a specified integer (signed or unsigned) and sends the string to an edit control. SetDlgItemInt returns no value. The GetDlgItemInt function creates an integer (signed or unsigned) from its string representation in an edit control. GetDlgItemInt returns the integer (or an error value).


 Undoing Text Operations

Every edit control maintains an undo flag that indicates whether an application can reverse (undo) the most recent operation on the edit control (to undo a text deletion, for example). The edit control sets the undo flag to indicate that the operation can be undone and resets it to indicate that the operation cannot be undone. An application can determine the setting of the undo flag by sending the control an EM_CANUNDO message.

An application can undo the most recent operation by sending the control an EM_UNDO message. An operation can be undone provided no other edit control operation occurs first. For example, the user can delete text, replace the text (undo the deletion), and then delete the text again (undo the replacement). The EM_UNDO message applies to both single-line and multiline edit controls and always works for single-line edit controls.

An application can reset an edit control's undo flag by sending the control an EM_EMPTYUNDOBUFFER message. Windows 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.


 Wordwrap Functions

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 Windows, lines always end at the spaces between words. An application can specify its own wordwrap function by supplying a EditWordBreakProc wordwrap function and sending an 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 linebreak character (two carriage returns and a linefeed) automatically at the end of wrapped text lines. An application can turn this feature on or off by sending the edit control an EM_FMTLINES message. This message applies only to multiline edit controls and does not affect a line that ends with a hard linebreak (one carriage return and a linefeed entered by the user).


 Retrieving Points and Characters

An application can determine which character is closest to the specified point in an edit control by sending the EM_CHARFROMPOS message. The message returns the character index and line index of the character nearest the point. Similarly, an application can determine the client coordinates of the specified character in an edit control by sending the EM_POSFROMCHAR message. The application specifies the index of a character and the message returns the x and y coordinates of the upper left corner of the character.


 Edit Control Notification Messages

The user makes editing requests by using the keyboard and mouse. Windows 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.

Portability issue  In Microsoft® Windows NT™, the placement of the notification code in a notification message has moved from the lParam parameter to the wParam parameter. Windows 3.x applications that process notification messages must modify this code when porting to Windows NT.

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. Windows 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. Windows 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 Windows is about to display the new text. Windows 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. Windows 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. Windows automatically clears the undo flag whenever the edit control receives a WM_SETTEXT or EM_SETHANDLE message.
EM_FMTLINES	Adds or removes soft linebreak characters (two carriage returns and a linefeed) to the ends of wrapped lines in a multiline edit control. It is not processed by single-line edit controls.
EM_GETFIRSTVISIBLELINE	Returns the zero-based index of the first visible character in a single-line edit control or the zero-based index of the uppermost visible line in a multiline edit control.
EM_GETHANDLE	Returns a handle identifying the buffer containing the multiline edit control's text. It is not processed by single-line edit controls.
EM_GETLIMITTEXT	Returns the current text limit, in characters.
EM_GETLINE	Copies characters in a single-line edit control to a buffer and returns the number of characters copied. In a multiline edit control, retrieves a line of text from the control and returns the number of characters copied.
EM_GETLINECOUNT	Returns the number of lines in the edit control.
EM_GETMARGINS	Returns the widths of the left and right margins.
EM_GETMODIFY	Returns a flag indicating whether the content of an edit control has been modified.
EM_GETPASSWORDCHAR	Returns the character that edit controls use in conjunction with the ES_PASSWORD style.
EM_GETRECT	Returns the coordinates of the formatting rectangle in an edit control.
EM_GETSEL	Returns the starting and ending character positions of the current selection in the edit control.
EM_GETTHUMB	Returns the position of the scroll box.
EM_GETWORDBREAKPROC	Returns the address of the current 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. In earlier versions of Windows this was done via EM_SETSEL using particular parameters. A Win32-based application should use EM_SCROLLCARET.
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. For single-line edit controls, this value is either 0x7FFFFFFE (0x7FFE for version 4.0) or the value of the wParam parameter, whichever is smaller. For multiline edit controls, this value is either 0xFFFFFFFF (0xFFFF for version 4.0) 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 down, extends the selection to the word under the cursor.
WM_LBUTTONDOWN	Changes the current insertion point. If the SHIFT key is down, it extends the selection to the position of the cursor. In multiline edit controls, also sets the timer to automatically scroll when the user holds down the mouse button outside the multiline edit control window.
WM_LBUTTONUP	Releases the mouse capture and sets the text insertion point in the single-line edit control. In a multiline edit control, it also kills the timer set in the WM_LBUTTONDOWN message.
WM_MOUSEMOVE	Changes the current selection in the single-line edit control, if the mouse button is down. In a multiline edit controls, also sets the timer to automatically scroll if the user holds down the mouse button outside the multiline edit control window.
WM_NCCREATE	Points to the CREATESTRUCT structure for the window. This message is sent to the WM_CREATE message when a window is first created.
WM_NCDESTROY	Frees all memory associated with the edit control window, including the text buffer, undo buffer, tab-stop buffer, and highlight brush.
WM_PAINT	Erases the background, fills the window with the current color of the edit control window, draws the border (if any), sets the font and draws any text, and shows the text-insertion caret.
WM_PASTE	Pastes text from the clipboard into the edit control window at the caret position.
WM_SETFOCUS	Sets the keyboard focus of an edit control window (shows the current selection, if it was hidden, and creates the caret).
WM_SETFONT	Sets the font and optionally redraws the edit control.
WM_SETTEXT	Copies text to the single-line edit control, notifies the parent window when there is insufficient memory, empties the undo buffer, and sends the EN_UPDATE and EN_CHANGE notification messages to the parent window. In multiline edit controls, also rewraps the lines (if necessary) and sets the scroll positions.
WM_SIZE	Changes the size of the edit control window and ensures that the minimum size accommodates the height and width of a character.
WM_SYSCHAR	Returns TRUE if the user presses ALT+BACKSPACE; otherwise, it takes no action.
WM_SYSKEYDOWN	Undoes the last action if the user presses ALT+BACKSPACE; otherwise, it takes no action.
WM_TIMER	Scrolls the text in the edit control window if the user holds down the mouse button outside the multiline edit control window.
WM_UNDO	Removes any text that was just inserted or inserts any deleted characters and sets the selection to the inserted text. If necessary, sends the EN_UPDATE and EN_CHANGE notification messages to the parent window.
WM_VSCROLL	Scrolls a multiline edit control vertically and handles scroll box movement. It is not processed by single-line edit controls.
The predefined edit control window procedure passes all other messages to the DefWindowProc function for default processing.


 Using Edit Controls

Edit controls are typically used in dialog boxes, but you can use them in the client area of a standard window as well. Single-line edit controls are useful for retrieving a single string from the user. Multiline edit controls make it easy for your application to implement most of the features of a simple word processor.

•	Simple word processing with an edit control

•	Using single-line edit controls


 Simple Word Processing with an Edit Control

The following example implements much of the functionality of a simple word processor by filling the client area of a window with a multiline edit control. The system automatically performs 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                 */

UINT wParam,              /* additional information          */

LONG 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(hDlg, message, wParam, lParam)

HWND hDlg;                /* window handle of the dialog box */

UINT message;             /* type of message                 */

UINT wParam;              /* message-specific information    */

LONG 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 functions and messages are associated with edit controls.


 Edit Control Functions

Following are the functions used with edit controls.

EditWordBreakProc


 Edit Control Messages

Following are the messages used with edit controls.

EM_CANUNDO
EM_CHARFROMPOS
EM_EMPTYUNDOBUFFER
EM_FMTLINES
EM_GETFIRSTVISIBLELINE
EM_GETHANDLE
EM_GETLIMITTEXT
EM_GETLINE
EM_GETLINECOUNT
EM_GETMARGINS
EM_GETMODIFY
EM_GETPASSWORDCHAR
EM_GETRECT
EM_GETSEL
EM_GETWORDBREAKPROC
EM_LINEFROMCHAR
EM_LINEINDEX
EM_LINELENGTH
EM_LINESCROLL
EM_POSFROMCHAR
EM_REPLACESEL
EM_SCROLL
EM_SCROLLCARET
EM_SETHANDLE
EM_SETLIMITTEXT
EM_SETMARGINS
EM_SETMODIFY
EM_SETPASSWORDCHAR
EM_SETREADONLY
EM_SETRECT
EM_SETRECTNP
EM_SETSEL
EM_SETTABSTOPS
EM_SETWORDBREAKPROC
EM_UNDO
EN_CHANGE
EN_ERRSPACE
EN_HSCROLL
EN_KILLFOCUS
EN_MAXTEXT
EN_SETFOCUS
EN_UPDATE
EN_VSCROLL
WM_COMMAND
WM_COPY
WM_CTLCOLOREDIT
WM_CUT
WM_PASTE
WM_UNDO


 List Boxes

The Microsoft® Win32® application programming interface (API) provides dialog boxes and controls to support communication between an application and the user. A list box is a control window that contains a list of items from which the user can choose.


 About List Boxes

List box items can be represented by text strings, bitmaps, or both. If the list box is not large enough to display all the list box items at once, the list box can provide a scroll bar. The user maneuvers through the list box items, scrolling the list when necessary, and selects or removes the selection from items. Selecting a list box item changes its visual appearance, usually by changing the text and background colors to the colors specified by the operating system metrics for selected items. When the user selects an item or removes the selection from an item, Windows sends a notification message to the parent window of the list box.

A dialog box procedure is responsible for initializing and monitoring its child windows, including any list boxes. The dialog box procedure communicates with the list box by sending messages to it and by processing the notification messages sent by the list box. For more information about dialog boxes, see Dialog Boxes.

For general information about controls, see Controls.


 List Box Styles

The Win32 API provides two general styles of list box: single-selection (the default style) 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; an application must specify either the LBS_MULTIPLESEL or the LBS_EXTENDEDSEL style for a multiple-selection list box.

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 information about how to create a dialog box template and include it in an application, see the documentation provided with your development tools.

To create a list box by using the CreateWindow or CreateWindowEx function, use the LISTBOX class, appropriate window style constants, and the following style constants to define the list box.

List box style	Description
LBS_DISABLENOSCROLL	Shows a disabled vertical scroll bar for the list box when the box does not contain enough items to scroll. If you do not specify this style, the scroll bar is hidden when the list box does not contain enough items.
LBS_EXTENDEDSEL	Allows multiple items to be selected by using the SHIFT key and the mouse or special key combinations.
LBS_HASSTRINGS	Specifies that a list box contains items consisting of strings. The list box maintains the memory and addresses for the strings so that the application can use the LB_GETTEXT message to retrieve the text for a particular item. By default, all list boxes except owner-drawn list boxes have this style. You can create an owner-drawn list box either with or without this style.
LBS_MULTICOLUMN	Specifies a multicolumn list box that is scrolled horizontally. The LB_SETCOLUMNWIDTH message sets the width of the columns.
LBS_MULTIPLESEL	Turns string selection on or off each time the user clicks or double-clicks a string in the list box. The user can select any number of strings.
LBS_NODATA	Obsolete.
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, Windows sizes a list box so that the list box does not display partial items.
LBS_NOREDRAW	Specifies that the list box's appearance is not updated when changes are made. You can change this style by sending a WM_SETREDRAW message at any time.
LBS_NOSEL	Specifies that the list box contains items that can be viewed but not selected.
LBS_NOTIFY	Notifies the parent window with an input message whenever the user clicks or double-clicks a string in the list box.
LBS_OWNERDRAWFIXED	Specifies that the owner of the list box is responsible for drawing its contents and that the items in the list box are the same height. The owner window receives a WM_MEASUREITEM message when the list box is created and a WM_DRAWITEM message when a visual aspect of the list box has changed.
LBS_OWNERDRAWVARIABLE	Specifies that the owner of the list box is responsible for drawing its contents and that the items in the list box are variable in height. The owner window receives a WM_MEASUREITEM message for each item in the combo box when the combo box is created and a WM_DRAWITEM message when a visual aspect of the combo box has changed.
LBS_SORT	Sorts strings in the list box alphabetically.
LBS_STANDARD	Sorts strings in the list box alphabetically. The parent window receives an input message whenever the user clicks or double-clicks a string. The list box has borders on all sides.
LBS_USETABSTOPS	Enables a list box to recognize and expand tab characters when drawing its strings. The default tab positions are 32 dialog box units. A dialog box unit is a horizontal or vertical distance. One horizontal dialog box unit is equal to 0.25 of the current dialog box base-width unit. Windows calculates these units based on the height and width of the current system font. The GetDialogBaseUnits function returns the current dialog box base units in pixels.
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.


 List Box Functions Overview

The Win32 API provides two functions specific to list boxes. The DlgDirList function fills a list box with the files and directories in a specified path. The DlgDirSelectEx function retrieves the current selection in a list box initialized by DlgDirList. These functions make it possible for the user to select a file from a list box without typing the location and name of the file.


 Notification Messages from List Boxes

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

Portability Issue  The placement of notification message has moved from the lParam parameter to the wParam parameter. Windows 3.x−based applications that process notification messages must be modified in this respect when they are ported to Win32-based applications.

A dialog box procedure is not required to process these messages; the default window procedure processes them.

An application should monitor and process the following list box notification messages.

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


 Messages to List Boxes

A dialog box procedure can send messages to a list box to add, delete, examine, and change list box items. For example, a dialog box procedure could send an LB_ADDSTRING message to a list box to add an item, and an LB_GETSEL message to determine whether the item is selected. Other messages set and retrieve information about the size, appearance, and behavior of the list box. For example, the LB_SETHORIZONTALEXTENT message sets the scrollable width of a list box. A dialog box procedure can send any message to a list box by using the SendMessage or SendDlgItemMessage function.

A list box item is often referenced by its index, an integer that represents the item's position in the list box. The index of the first item in a list box is 0, the index of the second item is 1, and so on.

The following table describes how the predefined list box procedure responds to list box messages.

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


 Default Window-Message Processing

The window procedure for the predefined list box window class carries out default processing for all messages that the list box does not process. When the list box procedure returns FALSE for a message, the predefined window procedure checks the message and performs default actions, as shown in the following table.

Message	Default action
WM_CHAR	Moves the selection to the first item that begins with the character the user typed. If the list box has the LBS_OWNERDRAW style, no action occurs. Multiple characters typed within a short interval are treated as a group, and the first item that begins with that series of characters is selected.
WM_CREATE	Creates an empty list box.
WM_DESTROY	Destroys the list box and frees any resources it uses.
WM_DROPFILES	Passes the message to the dialog box procedure or parent window process.
WM_ENABLE	If the control is visible, invalidates the rectangle so the strings can be painted gray.
WM_ERASEBKGND	Erases the background of a list box. If the list box has the LBS_OWNERDRAW style, the background is not erased.
WM_GETDLGCODE	Returns DLGC_WANTARROWS | DLGC_WANTCHARS, indicating the default list box procedure processes the arrow keys and WM_CHAR messages.
WM_GETFONT	Returns a handle of 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 of 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.


 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[] = {

        {"Pete", "shortstop", 26, 90, .608, "Rutabaga"},

        {"Suzanna", "catcher", 16, 53, .286, "Toast"},

        {"Jack", "pitcher", 27, 110, .542, "Animal Crackers"},

        {"Karen", "second base", 26, 140, .238, "Pez"},

        {"Dave", "first base", 28, 138, .508, "Suds"},

        {"Wendy", "third base", 25, 154, .493, "Ham"},

        {"Matt", "shortstop", 24, 112, .579, "Oats"},

        {"Jenny", "right field", 22, 101, .509, "Mashed Potatoes"},

        {"Seth", "left-center field", 20, 76, .407, "Otter Pop"},

        {"Kathie", "left field", 26, 127, .353, "Baba Ganouj"},

        {"Colin", "pitcher", 26, 96, .456, "Lefse"},

        {"Penny", "right field", 24, 112, .393, "Zotz"},

        {"Art", "left-center field", 17, 56, .375, "Cannelloni"},

        {"Cindy", "second base", 13, 58, .207, "Tequila"},

        {"David", "center field", 18, 101, .612, "Bok Choy"}

    };

/*

 * FUNCTION: DlgTeamProc(HWND, unsigned, UINT, LONG)

 *

 * PURPOSE:  Dialog box for "BFG Softball Statistics"

 */

BOOL APIENTRY DlgTeamProc(

    HWND hDlg,            /* window handle of 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

/*

 * FUNCTION: DlgDelFileProc(HWND, unsigned, UINT, LONG)

 *

 * PURPOSE:  "Delete File" dialog box

 */

BOOL APIENTRY DlgDelFileProc(

    HWND hDlg,            /* window handle of 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

/*

 * FUNCTION: DlgDelFilesProc(HWND, unsigned, UINT, LONG)

 *

 * PURPOSE:  "Delete files" dialog box

 */

BOOL APIENTRY DlgDelFilesProc(

    HWND hDlg,            /* window handle of 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

                         * indice 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 of 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 Which one? (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 functions and messages are associated with list boxes.


 List Box Functions

Following are the functions used with list boxes.

DlgDirList
DlgDirSelectEx


 List Box Messages

Following are the messages used with list boxes.

LB_ADDFILE
LB_ADDSTRING
LB_DELETESTRING
LB_DIR
LB_FINDSTRING
LB_FINDSTRINGEXACT
LB_GETANCHORINDEX
LB_GETCARETINDEX
LB_GETCOUNT
LB_GETCURSEL
LB_GETHORIZONTALEXTENT
LB_GETITEMDATA
LB_GETITEMHEIGHT
LB_GETITEMRECT
LB_GETLOCALE
LB_GETSEL
LB_GETSELCOUNT
LB_GETSELITEMS
LB_GETTEXT
LB_GETTEXTLEN
LB_GETTOPINDEX
LB_INSERTSTRING
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_DELETEITEM
WM_VKEYTOITEM


 Scroll Bars

A window in an application written for Microsoft® Windows® can display a data object, such as a document or a bitmap, that is larger than the window's client area. When provided with a scroll bar, the user can scroll a data object in the client area to bring into view the portions of the object that extend beyond the borders of the window.


 About Scroll Bars

Scroll bars should be included in any window for which the content of the client area extends beyond the window's borders. A scroll bar's orientation determines the direction in which scrolling occurs when the user operates the scroll bar. A horizontal scroll bar enables the user to scroll the content of a window to the left or right. A vertical scroll bar enables the user to scroll the content up or down.


 Parts of a Scroll Bar

A scroll bar consists of a shaded shaft with an arrow button at each end and a scroll box (sometimes called a thumb) between the arrow buttons. A scroll bar represents the overall length or width of a data object in a window's client area; the scroll box represents the portion of the object that is visible in the client area. The position of the scroll box changes whenever the user scrolls a data object to display a different portion of it. In version 4.0 or later, Windows also adjusts the size of a scroll bar's scroll box so that it indicates what portion of the entire data object is currently visible in the window. If most of the object is visible, the scroll box occupies most of the scroll bar's shaft. Similarly, if only a small portion of the object is visible, the scroll box occupies a small part of the shaft.

The user scrolls the content of a window by clicking one of the arrow buttons, by clicking the area in the shaded shaft, or by dragging the scroll box. When the user clicks an arrow button, the application scrolls the content by one unit (typically a single line or column). When the user clicks the shaded areas, the application scrolls the content by one window. The amount of scrolling that occurs when the user drags the scroll box depends on the distance the user drags the scroll box and on the scrolling range of the scroll bar. For more information about the scrolling range, see Scroll Box Position and Scrolling Range.


 Standard Scroll Bars and Scroll Bar Controls

A scroll bar is included in a window either as a standard scroll bar or as a scroll bar control. A standard scroll bar is located in the nonclient area of a window. It is created with the window and displayed when the window is displayed. The sole purpose of a standard scroll bar is to enable the user to generate scrolling requests for viewing the entire content of the client area. You can include a standard scroll bar in a window by specifying WS_HSCROLL, WS_VSCROLL, or both styles when you create the window. The WS_HSCROLL style creates a horizontal scroll bar positioned at the bottom of the client area. The WS_VSCROLL style creates a vertical scroll bar positioned at the right of the client area. The SM_CXHSCROLL and SM_CYHSCROLL system metric values define the width and height of a standard horizontal scroll bar. The SM_CXVSCROLL and SM_CYVSCROLL values define the width and height of a standard vertical scroll bar.

A scroll bar control is a control window that belongs to the SCROLLBAR window class. A scroll bar control appears and functions like a standard scroll bar, but it is a separate window. As a separate window, a scroll bar control receives direct input focus, indicated by a flashing caret displayed in the scroll box. Unlike a standard scroll bar, a scroll bar control also has a built-in keyboard interface that enables the user to direct scrolling. You can use as many scroll bar controls as needed in a single window. When you create a scroll bar control, you must specify the scroll bar's size and position. However, if a scroll bar control's window can be resized, adjustments to the scroll bar's size must be made whenever the size of the window changes.

The advantage of using a standard scroll bar is that Windows 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. Following are the scroll bar control styles.

Style	Meaning
SBS_BOTTOMALIGN
	Aligns the bottom edge of the scroll bar with the bottom edge of the rectangle defined by the CreateWindowEx parameters x, y, nWidth, and nHeight. 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 parameters of CreateWindowEx.
SBS_LEFTALIGN
	Aligns the left edge of the scroll bar with the left edge of the rectangle defined by the 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 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 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 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 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 (version 4.0 or later).
SBS_TOPALIGN
	Aligns the top edge of the scroll bar with the top edge of the rectangle defined by the 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 parameters of CreateWindowEx.


 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. With operating system version 4.0 or later, you can use the SetScrollInfo function to set the range values, and the GetScrollInfo function to retrieve the current range values. In versions earlier than 4.0, you can use the SetScrollRange and GetScrollRange functions.

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.

In version 4.0 or later, an application 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. Windows 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.

In version 4.0 or later, 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. In version 4.0 or later, 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. With version 4.0 or later, 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, in version 4.0 or later, 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. Windows sends the request to the given window in the form of a WM_HSCROLL or WM_VSCROLL message. A horizontal scroll bar sends the WM_HSCROLL message; a vertical scroll bar sends the WM_VSCROLL message. Each message includes a notification code that corresponds to the user's action, to the handle of the scroll bar (scroll bar controls only), and, in some cases, to the position of the scroll box.

The following figure shows the notification messages that the user generates when clicking various parts of a scroll bar.

The scroll bar notification codes specify the action the user takes. An application examines the codes that accompany the WM_HSCROLL and WM_VSCROLL messages and then performs the appropriate scrolling operation. In the following table of notification messages, the user's action is specified for each message, followed by the application's response. In each case, a unit is defined by the application as appropriate for the given data. For example, the typical unit for scrolling text vertically is a line of text.

Notification  message	Action	Response
SB_LINEUP	The user clicks the top scroll arrow.	Decrements the scroll box position; scrolls toward the top of the data by one unit.
SB_LINEDOWN	The user clicks the bottom scroll arrow.	Increments the scroll box position; scrolls toward the bottom of the data by one unit.
SB_LINELEFT	The user clicks the left scroll arrow.	Decrements the scroll box position; scrolls toward the left end of the data by one unit.
SB_LINERIGHT	The user clicks the right scroll arrow.	Increments the scroll box position; scrolls toward the right end of the data by one unit.
SB_PAGEUP	The user clicks the scroll bar shaft above the scroll box.	Decrements the scroll box position by the number of data units in the window; scrolls toward the top of the data by the same number of units.
SB_PAGEDOWN	The user clicks the scroll bar shaft below the scroll box.	Increments the scroll box position by the number of data units in the window; scrolls toward the bottom of the data by the same number of units.
SB_PAGELEFT	The user clicks the scroll bar shaft to the left of the scroll box.	Decrements the scroll box position by the number of data units in the window; scrolls toward the left end of the data by the same number of units.
SB_PAGERIGHT	The user clicks the scroll bar shaft to the right of the scroll box.	Increments the scroll box position by the number of data units in the window; scrolls toward the right end of the data by the same number of units.
SB_THUMBPOSITION	The user releases the scroll box after dragging it.	Sets the scroll box to the position given in the message; scrolls the data by the same number of units the scroll box has moved.
SB_THUMBTRACK	The user drags the scroll box.	Sets the scroll box to the position given in the message and scrolls the data by the same number of units the scroll box has moved for applications that draw data quickly. Applications that cannot draw data quickly must wait for the SB_THUMBPOSITION message before moving the scroll box and scrolling the data.
SB_ENDSCROLL	The user releases the mouse after holding it on an arrow or in the scroll bar shaft.	No response is needed.
A scroll bar generates the SB_THUMBPOSITION and SB_THUMBTRACK notification messages when the user clicks and drags the scroll box. An application should be programmed to process either the SB_THUMBTRACK or the SB_THUMBPOSITION notification message.

The SB_THUMBPOSITION notification message occurs when the user releases the mouse button after clicking the scroll box. An application that processes this message performs the scrolling operation after the user has dragged the scroll box to the desired position and released the mouse button.

SB_THUMBTRACK notification messages occur as the user drags the scroll box. If an application processes SB_THUMBTRACK messages, it can scroll the content of a window as the user drags the scroll box. However, a scroll bar can generate many SB_THUMBTRACK notification messages in a short period, so an application should process these messages only if it can quickly repaint the content of the window.


 Keyboard Interface for a Scroll Bar

A scroll bar control provides a built-in keyboard interface that enables the user to issue scrolling requests by using the keyboard; a standard scroll bar does not. When a scroll bar control has the keyboard focus, it sends WM_HSCROLL and WM_VSCROLL messages to its parent window when the user presses the arrow keys. The notification message is sent with each message corresponding to the arrow key the user has pressed. Following are the arrow keys and their corresponding notification messages.

Arrow key	Notification message
DOWN	SB_LINEDOWN or SB_LINERIGHT
END	SB_BOTTOM
HOME	SB_TOP
LEFT	SB_LINEUP or SB_LINELEFT
PGDN	SB_PAGEDOWN or SB_PAGERIGHT
PGUP	SB_PAGEUP or SB_PAGELEFT
RIGHT	SB_LINEDOWN or SB_LINERIGHT
UP	SB_LINEUP or SB_LINELEFT
Note that the keyboard interface of a scroll bar control sends the SB_TOP and SB_BOTTOM notification messages. The SB_TOP message indicates that the user has reached the top value of the scrolling range. An application scrolls the window content downward so that the top of the data object is visible. The SB_BOTTOM message indicates that the user has reached the bottom value of the scrolling range. If an application processes the SB_BOTTOM message, it scrolls the window content upward so that the bottom of the data object is visible.

If you want a keyboard interface for a standard scroll bar, you can create one yourself by processing the WM_KEYDOWN message in your window procedure and then performing the appropriate scrolling action based on the virtual-key code that accompanies the message. For information about how to create a keyboard interface for a scroll bar, see Creating a Keyboard Interface for a Standard Scroll Bar.


 Scrolling the Client Area

The simplest way to scroll the content of a client area is to erase and then redraw it. This is the method an application is likely to use with SB_PAGEUP, SB_PAGEDOWN, and SB_TOP notification messages, which typically require completely new content.

For some notification messages, such as SB_LINEUP and SB_LINEDOWN, not all the content need be erased, because some remains visible after scrolling occurs. The ScrollWindowEx function preserves a portion of the client area's content, move the preserved portion a specified amount, and then prepares the rest of the client area for painting new information. ScrollWindowEx uses the BitBlt function to move a specific part of the data object to a new location within the client area. Any uncovered part of the client area (anything not preserved) is invalidated, erased, and painted when the next WM_PAINT message occurs.

The ScrollWindowEx function can be used to exclude a portion of the client area from the scrolling operation. This keeps items with fixed positions, such as child windows, from moving within the client area. It automatically invalidates the portion of the client area that is to receive the new information, so the application does not have to compute its own clipping regions. For more information on clipping, see Clipping.

Usually an application scrolls the content of a window in the direction opposite that indicated by the scroll bar. For example, when the user clicks the shaft in the area below the scroll box, an application scrolls the object in the window upward to reveal a portion of the object that is below the visible portion.


 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 Windows 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. In version 4.0 or later, 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. In version 4.0 or later, 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

Note  The examples in this section set the scroll range, scroll position, and page size by using SetScrollInfo function, which is available only with version 4.0 and later. For operating system versions earlier than 4.0, use the SetScrollRange and SetScrollPos functions.


 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 of 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. For versions earlier than 4.0, use the SetScrollRange function to set the minimum and maximum position values, and the SetScrollPos function to adjust the scroll box to reflect the scrolling position.


 Scrolling Text with the WM_HSCROLL and WM_VSCROLL Messages

The scroll bar sends WM_HSCROLL and WM_VSCROLL messages to the window procedure whenever the user clicks the scroll bar or drags the scroll box. The low-order words of WM_VSCROLL and WM_HSCROLL each contain a notification message that indicates the direction and magnitude of the scrolling action.

When the WM_HSCROLL and WM_VSCROLL messages are processed, the scroll bar notification message is examined and the scrolling increment is calculated. After the increment is applied to the current scrolling position, the window is scrolled to the new position by using the ScrollWindowEx function, and the position of the scroll box is adjusted by using the SetScrollInfo function. For operating system versions earlier than 4.0, use the SetScrollPos function to adjust the scroll box position.

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 horiz. scrolling position     */

static int yMax;        /* maximum vert. scrolling position      */

int xInc;               /* horizontal scrolling increment        */

int yInc;               /* vertical scrolling increment          */

int i;                  /* loop counter                          */

int x, y;               /* horiz. and vert. printing coords      */

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 of 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. For operating system versions earlier than 4.0, use the SetScrollPos function to adjust the scroll box position.


 Scrolling a Bitmap with the WM_HSCROLL and WM_VSCROLL Messages

When the WM_HSCROLL and WM_VSCROLL messages are processed, the scroll bar notification message is examined and the scrolling position is set to a new value that reflects the scrolling action of the user. If the scrolling position is within the scrolling range, the window is scrolled to the new position by using the ScrollWindow function. The position of the scroll box is then adjusted by using the SetScrollInfo function. In versions earlier than 4.0, use the SetScrollPos function.

After a window is scrolled, part of its client area is made invalid. To ensure that the invalid region is updated, use the UpdateWindow function to generate a WM_PAINT message. When processing the WM_PAINT message, an application must repaint the invalid region at the bottom of the client area. When scrolling or resizing the client area, the example uses the BitBlt function to copy the appropriate portion of the bitmap to the invalid portion of the client area.


 Example of Scrolling a Bitmap

The following example enables the user to capture the screen content into a bitmap and scroll the bitmap in the client area.

HDC hdc;

PAINTSTRUCT ps;

SCROLLINFO si;

/* These variables are required by BitBlt.                      */

static HDC hdcWin;           /* window DC                       */

static HDC hdcScreen;        /* DC for entire screen            */

static HDC hdcScreenCompat;  /* memory DC for screen            */

static HBITMAP hbmpCompat;   /* bitmap handle for old DC        */

static BITMAP bmp;           /* bitmap data structure           */

static BOOL fBlt;            /* TRUE if BitBlt occurred         */

static BOOL fScroll;         /* TRUE if scrolling occurred      */

static BOOL fSize;           /* TRUE if fBlt & WM_SIZE          */

/* These variables are required for horizontal scrolling.       */

static int xMinScroll;       /* minimum horizontal scroll value */

static int xCurrentScroll;   /* current horizontal scroll value */

static int xMaxScroll;       /* maximum horizontal scroll value */

/* These variables are required for vertical scrolling.         */

static int yMinScroll;       /* minimum vertical scroll value   */

static int yCurrentScroll;   /* current vertical scroll value   */

static int yMaxScroll;       /* maximum vertical scroll value   */

switch (uMsg) {

    case WM_CREATE:

        /*

         * Create a normal DC and a memory DC for the entire

         * screen. The normal DC provides a snapshot of the

         * screen contents. The memory DC keeps a copy of this

         * snapshot in the associated bitmap.

         */

        hdcScreen = CreateDC("DISPLAY", (LPCSTR) NULL,

            (LPCSTR) NULL, (CONST DEVMODE *) NULL);

        hdcScreenCompat = CreateCompatibleDC(hdcScreen);

        /*

         * Retrieve the metrics for the bitmap associated with the

         * regular device context.

         */

        bmp.bmBitsPixel =

            (BYTE) GetDeviceCaps(hdcScreen, BITSPIXEL);

        bmp.bmPlanes = (BYTE) GetDeviceCaps(hdcScreen, PLANES);

        bmp.bmWidth = GetDeviceCaps(hdcScreen, HORZRES);

        bmp.bmHeight = GetDeviceCaps(hdcScreen, VERTRES);

        /* The width must be byte-aligned. */

        bmp.bmWidthBytes = ((bmp.bmWidth + 15) &~15)/8;

        /* Create a bitmap for the compatible DC. */

        hbmpCompat = CreateBitmap(bmp.bmWidth, bmp.bmHeight,

            bmp.bmPlanes, bmp.bmBitsPixel, (CONST VOID *) NULL);

        /* Select the bitmap for the compatible DC. */

        SelectObject(hdcScreenCompat, hbmpCompat);

        /* Initialize the flags. */

        fBlt = FALSE;

        fScroll = FALSE;

        fSize = FALSE;

        /* Initialize the horizontal scrolling variables. */

        xMinScroll = 0;

        xCurrentScroll = 0;

        xMaxScroll = 0;

        /* Initialize the vertical scrolling variables. */

        yMinScroll = 0;

        yCurrentScroll = 0;

        yMaxScroll = 0;

        break;

    case WM_SIZE: {

        int xNewSize;

        int yNewSize;

        xNewSize = LOWORD(lParam);

        yNewSize = HIWORD(lParam);

        if (fBlt)

            fSize = TRUE;

        /*

         * The horizontal scrolling range is defined by

         * (bitmap_width) - (client_width). The current horizontal

         * scroll value remains within the horizontal scrolling range.

         */

        xMaxScroll = max(bmp.bmWidth-xNewSize, 0);

        xCurrentScroll = min(xCurrentScroll, xMaxScroll);

        si.cbSize = sizeof(si);

        si.fMask  = SIF_RANGE | SIF_PAGE | SIF_POS;

        si.nMin   = xMinScroll;

        si.nMax   = xMaxScroll;

        si.nPage  = xNewSize;

        si.nPos   = xCurrentScroll;

        SetScrollInfo(hwnd, SB_HORZ, &si, TRUE);

        /*

         * The vertical scrolling range is defined by

         * (bitmap_height) - (client_height). The current vertical

         * scroll value remains within the vertical scrolling range.

         */

        yMaxScroll = max(bmp.bmHeight - yNewSize, 0);

        yCurrentScroll = min(yCurrentScroll, yMaxScroll);

        si.cbSize = sizeof(si);

        si.fMask  = SIF_RANGE | SIF_PAGE | SIF_POS;

        si.nMin   = yMinScroll;

        si.nMax   = yMaxScroll;

        si.nPage  = yNewSize;

        si.nPos   = yCurrentScroll;

        SetScrollInfo(hwnd, SB_VERT, &si, TRUE);

    }

        break;

    case WM_PAINT: {

        PRECT prect;

        hdc = BeginPaint(hwnd, &ps);

        /*

         * If the window has been resized and the user has

         * captured the screen, use the following call to

         * BitBlt to paint the window's client area.

         */

        if (fSize) {

            BitBlt(ps.hdc,

                0, 0,

                bmp.bmWidth, bmp.bmHeight,

                hdcScreenCompat,

                xCurrentScroll, yCurrentScroll,

                SRCCOPY);

            fSize = FALSE;

        }

        /*

         * If scrolling has occurred, use the following call to

         * BitBlt to paint the invalid rectangle.

         *

         * The coordinates of this rectangle are specified in the

         * RECT structure to which prect points.

         *

         * Note that it is necessary to increment the seventh

         * argument (prect->left) by xCurrentScroll and the

         * eighth argument (prect->top) by yCurrentScroll in

         * order to map the correct pixels from the source bitmap.

         */

        if (fScroll) {

            prect = &ps.rcPaint;

            BitBlt(ps.hdc,

                prect->left, prect->top,

                (prect->right - prect->left),

                (prect->bottom - prect->top),

                hdcScreenCompat,

                prect->left + xCurrentScroll,

                prect->top + yCurrentScroll,

                SRCCOPY);

            fScroll = FALSE;

        }

        EndPaint(hwnd, &ps);

    }

        break;

    case WM_HSCROLL: {

        int xDelta;     /* xDelta = new_pos - current_pos */

        int xNewPos;    /* new position */

        int yDelta = 0;

        switch (LOWORD(wParam)) {

            /* User clicked the shaft left of the scroll box. */

            case SB_PAGEUP:

                xNewPos = xCurrentScroll - 50;

                break;

            /* User clicked the shaft right of the scroll box. */

            case SB_PAGEDOWN:

                xNewPos = xCurrentScroll + 50;

                break;

            /* User clicked the left arrow. */

            case SB_LINEUP:

                xNewPos = xCurrentScroll - 5;

                break;

            /* User clicked the right arrow. */

            case SB_LINEDOWN:

                xNewPos = xCurrentScroll + 5;

                break;

            /* User dragged the scroll box. */

            case SB_THUMBPOSITION:

                xNewPos = HIWORD(wParam);

                break;

            default:

                xNewPos = xCurrentScroll;

        }

        /* New position must be between 0 and the screen width. */

        xNewPos = max(0, xNewPos);

        xNewPos = min(xMaxScroll, xNewPos);

        /* If the current position does not change, do not scroll.*/

        if (xNewPos == xCurrentScroll)

            break;

        /* Set the scroll flag to TRUE. */

        fScroll = TRUE;

        /* Determine the amount scrolled (in pixels). */

        xDelta = xNewPos - xCurrentScroll;

        /* Reset the current scroll position. */

        xCurrentScroll = xNewPos;

        /*

         * Scroll the window. (The system repaints most of the

         * client area when ScrollWindowEx is called; however, it is

         * necessary to call UpdateWindow in order to repaint the

         * rectangle of pixels that were invalidated.)

         */

        ScrollWindowEx(hwnd, -xDelta, -yDelta, (CONST RECT *) NULL,

            (CONST RECT *) NULL, (HRGN) NULL, (LPRECT) NULL,

            SW_INVALIDATE);

        UpdateWindow(hwnd);

        /* Reset the scroll bar. */

        si.cbSize = sizeof(si);

        si.fMask  = SIF_POS;

        si.nPos   = xCurrentScroll;

        SetScrollInfo(hwnd, SB_HORZ, &si, TRUE);

    }

        break;

    case WM_VSCROLL: {

        int xDelta = 0;

        int yDelta;     /* yDelta = new_pos - current_pos */

        int yNewPos;    /* new position */

        switch (LOWORD(wParam)) {

            /* User clicked the shaft above the scroll box. */

            case SB_PAGEUP:

                yNewPos = yCurrentScroll - 50;

                break;

            /* User clicked the shaft below the scroll box. */

            case SB_PAGEDOWN:

                yNewPos = yCurrentScroll + 50;

                break;

            /* User clicked the top arrow. */

            case SB_LINEUP:

                yNewPos = yCurrentScroll - 5;

                break;

            /* User clicked the bottom arrow. */

            case SB_LINEDOWN:

                yNewPos = yCurrentScroll + 5;

                break;

            /* User dragged the scroll box. */

            case SB_THUMBPOSITION:

                yNewPos = HIWORD(wParam);

                break;

            default:

                yNewPos = yCurrentScroll;

        }

        /* New position must be between 0 and the screen height. */

        yNewPos = max(0, yNewPos);

        yNewPos = min(yMaxScroll, yNewPos);

        /* If the current position does not change, do not scroll.*/

        if (yNewPos == yCurrentScroll)

            break;

        /* Set the scroll flag to TRUE. */

        fScroll = TRUE;

        /* Determine the amount scrolled (in pixels). */

        yDelta = yNewPos - yCurrentScroll;

        /* Reset the current scroll position. */

        yCurrentScroll = yNewPos;

        /*

         * Scroll the window. (The system repaints most of the

         * client area when ScrollWindowEx is called; however, it is

         * necessary to call UpdateWindow in order to repaint the

         * rectangle of pixels that were invalidated.)

         */

        ScrollWindowEx(hwnd, -xDelta, -yDelta, (CONST RECT *) NULL,

            (CONST RECT *) NULL, (HRGN) NULL, (LPRECT) NULL,

            SW_INVALIDATE);

        UpdateWindow(hwnd);

        /* Reset the scroll bar. */

        si.cbSize = sizeof(si);

        si.fMask  = SIF_POS;

        si.nPos   = yCurrentScroll;

        SetScrollInfo(hwnd, SB_VERT, &si, TRUE);

    }

        break;

    case WM_COMMAND:        /* uMsg: command from app. menu */

        switch(wParam) {

            case IDM_STC:

                /*

                 * Copy the contents of the current screen

                 * into the compatible DC.

                 */

                BitBlt(hdcScreenCompat, 0, 0, bmp.bmWidth,

                    bmp.bmHeight, hdcScreen, 0, 0, SRCCOPY);

                /*

                 * Copy the compatible DC to the client area.

                 */

                hdcWin = GetDC(hwnd);

                BitBlt(hdcWin, 0, 0, bmp.bmWidth, bmp.bmHeight,

                    hdcScreenCompat, 0, 0, SRCCOPY);

                ReleaseDC(hwnd, hdcWin);

                fBlt = TRUE;

                break;

            default:

                return (DefWindowProc(hwnd, uMsg,

                    wParam, lParam));

        }

        break;


 Creating a Keyboard Interface for a Standard Scroll Bar

Although a scroll bar control provides a built-in keyboard interface, a standard scroll bar does not. To implement a keyboard interface for a standard scroll bar, a window procedure must process the WM_KEYDOWN message and examine the virtual-key code specified by the wParam parameter. If the virtual-key code corresponds to an arrow key, the window procedure sends itself a WM_HSCROLL or WM_VSCROLL message with the low-order word of the wParam parameter set to the appropriate scroll bar notification message. For example, when the user presses the UP arrow key, the window procedure receives a WM_KEYDOWN message with wParam equal to VK_UP. In response, the window procedure sends itself a WM_VSCROLL message with the low-order word of wParam set to the SB_LINEUP notification message.

The following example shows how to include a keyboard interface for a standard scroll bar.

WORD wScrollNotify = 0xFFFF;

.

.

.

case WM_KEYDOWN:

    switch (wParam) {

        case VK_UP:

            wScrollNotify = SB_LINEUP;

            break;

        case VK_PRIOR:

            wScrollNotify = SB_PAGEUP;

            break;

        case VK_NEXT:

            wScrollNotify = SB_PAGEDOWN;

            break;

        case VK_DOWN:

            wScrollNotify = SB_LINEDOWN;

            break;

        case VK_HOME:

            wScrollNotify = SB_TOP;

            break;

        case VK_END:

            wScrollNotify = SB_BOTTOM;

            break;

    }

    if (wScrollNotify != -1)

        SendMessage(hwnd, WM_VSCROLL,

            MAKELONG(wScrollNotify, 0), 0L);

    break;

.

.

.


 Scroll Bar Reference

The following functions and messages are associated with scroll bars.


 Scroll Bar Functions

Following are the functions used with scroll bars.

EnableScrollBar
GetScrollPos
GetScrollRange
ScrollDC
ScrollWindow
ScrollWindowEx
SetScrollPos
SetScrollRange
ShowScrollBar


 Scroll Bar Messages

Following are the messages used with scroll bars.

SBM_ENABLE_ARROWS
SBM_GETPOS
SBM_GETRANGE
SBM_SETPOS
SBM_SETRANGE
SBM_SETRANGEREDRAW
WM_CTLCOLORSCROLLBAR
WM_HSCROLL
WM_VSCROLL


 Static Controls

The Microsoft® Windows® operating system provides dialog boxes and controls to support communication between an application and the user. A static control is a control that enables an application to provide the user with certain types of text and graphics that typically require no response.


 About Static Controls

Applications often use static controls to label other controls or to separate a group of controls. Although static controls are child windows, they cannot be selected. Therefore, they cannot receive the keyboard focus and cannot have a keyboard interface. A static control that has the SS_NOTIFY style receives mouse input, notifying the parent window when the user clicks or double clicks the control. Static controls belong to the STATIC window class.

Although static controls can be used in overlapped, pop-up, and child windows, they are designed for use in dialog boxes, where Windows 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 and Styles

The Microsoft® Win32® application programming interface (API) provides four types of static controls: simple graphics, text, images, and owner-drawn. Each type has one or more styles.


 Simple Graphics

A simple graphics static control displays a frame or a filled rectangle. A frame can be drawn in a number of styles, included black, gray, or white. In addition, a frame and can drawn with an etched style to give it a three-dimensional appearance. The frame styles include SS_BLACKFRAME, SS_GRAYFRAME, SS_WHITEFRAME, SS_ETCHEDHORZ, SS_ETCHEDVERT, and SS_ETCHEDFRAME.

A rectangle can be filled with color in one of three styles: black, gray, or white. These styles are defined by the constants SS_BLACKRECT, SS_GRAYRECT, and SS_WHITERECT.


 Text

A text static control displays text in a rectangle in one of five styles: left-aligned without wordwrap, left aligned with wordwrap, centered, right-aligned, or "simple." These styles are defined by the constants SS_LEFTNOWORDWRAP, SS_LEFT, SS_CENTER, SS_RIGHT, and SS_SIMPLE, respectively. Windows 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.


 Images

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 the handle of 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 the handle of the new graphic object. An application can retrieve the handle of 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

By using the SS_OWNERDRAW style, an application can take responsibility for painting a static control. The parent window of an owner-drawn static control (its owner) receives a WM_DRAWITEM message whenever the static control needs to be painted. The message includes the address of a DRAWITEMSTRUCT structure that contains information that the owner window uses when drawing the control.


 Static Control Styles

Many developers create dialog boxes by using standalone tools and so may not need to specify static control styles. However, if a developer uses the CreateWindow or CreateWindowEx function to create a static control for an application, the developer must use the following constants to define the style.

Style	Description
SS_BITMAP	Specifies a bitmap is to be displayed in the static control. The given text is the name of a bitmap (not a filename) defined elsewhere in the resource file. The style ignores the nWidth and nHeight parameters; the control automatically sizes itself to accommodate the bitmap.
SS_BLACKFRAME	Specifies a box with a frame drawn in the same color as the window frames. This color is black in the default Windows color scheme.
SS_BLACKRECT	Specifies a rectangle filled with the current window frame color. This color is black in the default Windows color scheme.
SS_CENTER	Specifies a simple rectangle and centers the given text in the rectangle. The text is formatted before it is displayed. Words that extend past the end of a line are automatically wrapped to the beginning of the next centered line.
SS_CENTERIMAGE	Specifies that, if the bitmap or icon is smaller than the client area of the static control, the rest of the client area is filled with the color of the pixel in the top left corner of the bitmap or icon. If the static control contains a single line of text, the text is centered vertically in the client area of the control.
SS_ENHMETAFILE	Specifies an enhanced metafile is to be displayed in the static control. The given text is the name of a metafile. An enhanced metafile static control has a fixed size; the metafile is scaled to fit the static control's client area.
SS_ETCHEDFRAME	Draws the frame of the static control using the EDGE_ETCHED edge style. For more information, see the DrawEdge function.
SS_ETCHEDHORZ	Draws the top and bottom edges of the static control using the EDGE_ETCHED edge style. For more information, see the DrawEdge function.
SS_ETCHEDVERT	Draws the left and right edges of the static control using the EDGE_ETCHED edge style. For more information, see the DrawEdge function.
SS_GRAYFRAME	Specifies a box with a frame drawn with the same color as the screen background (desktop). This color is gray in the default Windows color scheme.
SS_GRAYRECT	Specifies a rectangle filled with the current screen background color. This color is gray in the default Windows color scheme.
SS_ICON	Specifies an icon is to be displayed in the dialog box. The given text is the name of an icon (not a filename) defined elsewhere in the resource file. The icon can be an animated cursor. The style ignores the nWidth and nHeight parameters; the control automatically sizes itself to accommodate the icon.
SS_LEFT	Specifies a simple rectangle and left-aligns the given text in the rectangle. The text is formatted before it is displayed. Words that extend past the end of a line are automatically wrapped to the beginning of the next left-aligned line.
SS_LEFTNOWORDWRAP	Specifies a simple rectangle and left-aligns the given text in the rectangle. Tabs are expanded, but words are not wrapped. Text that extends past the end of a line is clipped.
SS_NOPREFIX	Prevents interpretation of any ampersand (&) characters in the control's text as accelerator prefix characters. These are displayed with the ampersand removed and the next character in the string underlined. This static control style may be included with any of the defined static controls. An application can combine SS_NOPREFIX with other styles by using the bitwise OR (|) operator. This can be useful when filenames or other strings that may contain an ampersand (&) must be displayed in a static control in a dialog box.
SS_NOTIFY	Sends the parent window STN_CLICKED, STN_DBLCLK, STN_DISABLE, and STN_ENABLE notification messages when the user clicks or double-clicks the control.
SS_OWNERDRAW	Specifies that the owner of the static control is responsible for drawing the control. The owner window receives a WM_DRAWITEM message whenever the control needs to be drawn.
SS_REALSIZEIMAGE	Prevents a static icon or bitmap control (that is, static controls that have the SS_ICON or SS_BITMAP style) from being resized as it is loaded or drawn. If the icon or bitmap is larger than the destination area, the image is clipped.
SS_RIGHT	Specifies a simple rectangle and right-aligns the given text in the rectangle. The text is formatted before it is displayed. Words that extend past the end of a line are automatically wrapped to the beginning of the next right-aligned line.
SS_RIGHTJUST	Specifies that the lower right corner of a static control with the SS_BITMAP or SS_ICON style is to remain fixed when the control is resized. Only the top and left sides are adjusted to accommodate a new bitmap or icon.
SS_SIMPLE	Specifies a simple rectangle and displays a single line of left-aligned text in the rectangle. The text line cannot be shortened or altered in any way. The control's parent window or dialog box must not process the WM_CTLCOLORSTATIC message.
SS_SUNKEN	Draws a half-sunken border around a static control.
SS_WHITEFRAME	Specifies a box with a frame drawn with the same color as the window background. This color is white in the default Windows color scheme.
SS_WHITERECT	Specifies a rectangle filled with the current window background color. This color is white in the default Windows color scheme.


 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 the handle of the font for text static controls.
WM_GETTEXTLENGTH	Returns the length, in characters, of the text for a text static control.
WM_LBUTTONDBLCLK	Sends the parent window an STN_DBLCLK notification message if the control style is SS_NOTIFY.
WM_LBUTTONDOWN	Sends the parent window an STN_CLICKED notification message if the control style is SS_NOTIFY.
WM_NCLBUTTONDBLCLK	Sends the parent window an STN_DBLCLK notification message if the control style is SS_NOTIFY.
WM_NCLBUTTONDOWN	Sends the parent window an STN_CLICKED notification message if the control style is SS_NOTIFY.
WM_NCHITTEST	Returns HTCLIENT if the control style is SS_NOTIFY; otherwise, returns HTTRANSPARENT.
WM_PAINT	Repaints the control.
WM_SETFONT	Sets the font and repaints for text static controls.
WM_SETTEXT	Sets the text and repaints for text static controls.
The predefined window procedure passes all other messages to DefWindowProc for default processing.


 Using Static Controls

The following example uses a timer and the STM_SETIMAGE message to animate an icon in a dialog box. The icon handles and the icon identifier (IDI_ICON) are defined in a global header file.

LRESULT APIENTRY StaticProc(hDlg, message, wParam, lParam)

HWND hDlg;      /* window handle of dialog box           */

UINT message;   /* type of message                       */

UINT wParam;    /* message-specific information          */

LONG lParam;

{

    UINT idTimer = 1;

    static UINT i;

    static HICON aIcons[11];

    switch (message) {

        case WM_INITDIALOG:             /* initialize dialog box */

            i = 0;

            /* Load icons("hinst" is defined globally). */

            hiconOne    = LoadIcon(hinst, "OneIco");

            aIcons[i]   = hiconOne;

            hiconTwo    = LoadIcon(hinst, "TwoIco");

            aIcons[++i] = hiconTwo;

                .

                . /* Continue with the remaining icons. */

                .

            i = 0;

             /*

              * Use STM_SETIMAGE to associate an icon with the

              * IDI_ICON identifier.

              */

            SendDlgItemMessage(hDlg,  /* dialog box window handle */

               IDI_ICON,              /* icon identifier          */

               STM_SETIMAGE,          /* message to send          */

               (WPARAM) IMAGE_ICON,   /* image type               */

               (LPARAM) aIcons[i++]); /* icon handle              */

            /* Set a timer for 50-millisecond intervals. */

            SetTimer(hDlg, idTimer, 50, (TIMERPROC) NULL);

            return TRUE;

        case WM_TIMER:

             /*

              * Use STM_SETIMAGE to associate a new icon with

              * the IDI_ICON identifier whenever a WM_TIMER

              * message is received.

              */

            SendDlgItemMessage(hDlg,  /* dialog box window handle */

               IDI_ICON,              /* icon identifier          */

               STM_SETIMAGE,          /* message to send          */

               (WPARAM) IMAGE_ICON,   /* image type               */

               (LPARAM) aIcons[i++]); /* new icon handle          */

            if (i == 10)

                i = 0;

            break;

        case WM_COMMAND:

            if (wParam == IDOK

                || wParam == IDCANCEL) {

                EndDialog(hDlg, TRUE);

                return TRUE;

            }

            return 0;

        case WM_DESTROY: /* clean up  */

            KillTimer(hDlg, idTimer);

            DeleteObject(hiconOne);

            DeleteObject(hiconTwo);

                .

                . /* Continue with the remaining icons. */

                .

            return 0;

    }

    return FALSE;

        UNREFERENCED_PARAMETER(lParam);

}


 Static Control Messages

Following are the messages used with static controls. (STM_GETICON and STM_SETICON are used only with icons.)

STM_GETICON
STM_SETICON
WM_CTLCOLORSTATIC


 Control Panel Applications

Control Panel applications are special-purpose dynamic-link libraries (DLLs) that let users configure the environment of Microsoft® Windows®.

This overview describes Control Panel applications and explains the functions and messages that these applications use and process to complete their work.


 About Control Panel Applications

Even though Windows provides a number of standard Control Panel applications, you can create additional applications to let users examine and modify the settings and operational modes of specific hardware and software.


 Application Responsibilities and Operation

The primary responsibility of any Control Panel application is to display a dialog box and to carry out any tasks specified by the user. Despite this responsibility, Control Panel applications do not provide menus or other direct means for users to access their dialog boxes. Instead, these applications operate under the control of another application and display their dialog boxes only when requested by the controlling application.

Control Panel applications are usually controlled by a Windows system utility specifically designed to give users access to these applications. However, any application can load and manage Control Panel applications, as long as the controlling application sends messages and processes return values in the way that the Control Panel applications expect.

Most Control Panel applications display and manage a single dialog box, giving the user control of the settings and operational modes of a single system component. However, any given Control Panel application can provide any number of dialog boxes to control any number of system components. (These individual dialog boxes are sometimes called applets.) To distinguish between dialog boxes, a Control Panel application typically supplies the controlling application with a unique icon for each dialog box. The controlling application displays these icons and the user can choose a dialog box by choosing the corresponding icon.


 Application Entry-Point Function

Every Control Panel application must export the standard entry-point function, CPlApplet. This function receives requests, in the form of Control Panel (CPL) messages, and carries out the requested work, such as initializing the application, displaying and managing the dialog box(es), and closing the application.

When the controlling application first loads the Control Panel application, it retrieves the address of the CPlApplet function and subsequently uses the address to call the function and pass it messages. The controlling application may send the following messages:

Message	Description
CPL_DBLCLK	Sent to notify CPlApplet that the user has chosen the icon associated with a given dialog box. CPlApplet should display the corresponding dialog box and carry out any user-specified tasks.
CPL_EXIT	Sent after the last CPL_STOP message and immediately before the controlling application uses the FreeLibrary function to free the DLL containing the Control Panel application. CPlApplet should free any remaining memory and prepare to close.
CPL_GETCOUNT	Sent after the CPL_INIT message to prompt CPlApplet to return a number indicating how many dialog boxes it supports.
CPL_INIT	Sent immediately after the DLL containing the Control Panel application is loaded, to prompt CPlApplet to perform initialization procedures, including memory allocation.
CPL_INQUIRE	Sent after the CPL_GETCOUNT message, to prompt CPlApplet to provide information about a given dialog box. This message has been superseded by the CPL_NEWINQUIRE message.
CPL_NEWINQUIRE	Sent after the CPL_GETCOUNT message, to prompt CPlApplet to provide information about a given dialog box . The second parameter (lParam2) is a pointer to a NEWCPLINFO structure.
CPL_SELECT	Sent to notify CPlApplet that the user has selected the icon. associated with a given dialog box.
CPL_STOP	Sent once for each dialog box before the controlling application closes. CPlApplet should free any memory associated with the given dialog box.


 Message Processing

CPlApplet processes all messages sent to a Control Panel application by a controlling application. The function expects to be sent messages in a given order. The controlling application expects the messages to be processed in a given way.

CPlApplet receives the CPL_INIT message when the controlling application first loads the Control Panel application. The function should carry out any initialization, such as allocating memory, and return nonzero. If CPlApplet cannot complete the initialization, it must return zero, directing the controlling application to terminate communication and release the DLL.

CPlApplet receives the CPL_GETCOUNT message only if the CPL_INIT message succeeded. The function must then return the number of dialog boxes supported by the Control Panel application.

CPlApplet receives one CPL_NEWINQUIRE message for each dialog box supported by the Control Panel application. Each message includes the address of a NEWCPLINFO structure and a unique identifier that the controlling application uses to identify the given dialog box. The function must set the dwSize member in the NEWCPLINFO structure to the size of the structure, set the hIcon member to the handle of the icon that represents the dialog box, and set the szName and szInfo members to the addresses of the short name and description of the dialog box. If the function also sets the dwHelpContext and szHelpFile members, the controlling application will provide context-sensitive Help for the dialog box. The lData member can be used for application-defined data.

Note  The CPL_NEWINQUIRE message and NEWCPLINFO structure supersede the CPL_INQUIRE message and CPLINFO structure, respectively.

CPlApplet receives a CPL_SELECT message as a notification that the user has selected the icon representing the dialog box. The function may receive this message any number of times. The message includes the dialog box identifier previously supplied by the controlling application and the lData value previously supplied by CPlApplet. Typically, Control Panel applications do not respond to the CPL_SELECT message.

CPlApplet receives a CPL_DBLCLK message as a notification that the user has chosen the icon representing the dialog box. The function may receive this message any number of times. The message includes the dialog box identifier and the lData value. The function should display the corresponding dialog box and process subsequent user input.

Before the controlling application terminates, CPlApplet receives the CPL_STOP message once for each dialog box supported by the Control Panel application. The message includes the identifier for the dialog box and the lData value. The function should free any memory that it allocated for the given dialog box.

After the last CPL_STOP message, CPlApplet receives a CPL_EXIT message. The function should free all remaining allocated memory and unregister any private window classes that it may have registered. Immediately after the function returns from this message, the controlling application releases the Control Panel application by calling the FreeLibrary function.


 Application Setup

Every Control Panel application is a dynamic-link library. To make sure the DLL containing your Control Panel application can be located and automatically loaded by the Windows system utility, the DLL file must have the .CPL filename extension and must be set up in one of the following ways:

•	Copied to the directory that contains the Windows system utility.

•	Copied to the Windows SYSTEM directory.

•	Registered under the the MMCPL key of the HKEY_CURRENT_USER key in the registry.

You should register the DLL in the registry if the DLL exports functions other than CPlApplet and provides functionality beyond the scope of a Control Panel application. For more information about the registry, seeRegistry.


 Creating Control Panel Applications

Although a Control Panel application may support more than one dialog box, it processes all requests through the single CPlApplet function. In the following example, the Control Panel application supports three dialog boxes that let the user set preferences for a component stereo system attached to the computer. The example uses an application-defined StereoApplets array that contains three structures, each corresponding to one of the dialog boxes. Each structure contains all the information required by the CPL_NEWINQUIRE message, as well as the dialog box template and dialog box procedure required by the CPL_DBLCLK message. The code demonstrates how to fill the structures in the StereoApplets array.

#define NUM_APPLETS 3

typedef struct tagApplets

{

    int icon;         // icon resource identifier

    int namestring;   // name-string resource identifier

    int descstring;   // description-string resource identifier

    int dlgtemplate;  // dialog box template resource identifier

    DLGPROC dlgfn;    // dialog box procedure

} APPLETS;

APPLETS StereoApplets[NUM_APPLETS] =

{

    AMP_ICON, AMP_NAME, AMP_DESC, AMP_DLG, AmpDlgProc,

    TUNER_ICON, TUNER_NAME, TUNER_DESC, TUNER_DLG, TunerDlgProc,

    TAPE_ICON, TAPE_NAME, TAPE_DESC, TAPE_DLG, TapeDlgProc,

};

LONG CALLBACK CPlApplet(hwndCPL, uMsg, lParam1, lParam2)

HWND hwndCPL;      // handle of Control Panel window

UINT uMsg;         // message

LPARAM lParam1;    // first message parameter

LPARAM lParam2;    // second message parameter

{

    int i;

    LPNEWCPLINFO lpNewCPlInfo;

    i = (int) lParam1;

    switch (uMsg) {

        case CPL_INIT:      // first message, sent once

            hinst = GetModuleHandle("ecp.cpl");

            return TRUE;

        case CPL_GETCOUNT:  // second message, sent once

            return NUM_APPLETS;

            break;

        case CPL_NEWINQUIRE: // third message, sent once per app

            lpNewCPlInfo = (LPNEWCPLINFO) lParam2;

            lpNewCPlInfo->dwSize = (DWORD) sizeof(NEWCPLINFO);

            lpNewCPlInfo->dwFlags = 0;

            lpNewCPlInfo->dwHelpContext = 0;

            lpNewCPlInfo->lData = 0;

            lpNewCPlInfo->hIcon = LoadIcon(hinst,

                (LPCTSTR) MAKEINTRESOURCE(StereoApplets[i].icon));

            lpNewCPlInfo->szHelpFile[0] = '\0';

            LoadString(hinst, StereoApplets[i].namestring,

                lpNewCPlInfo->szName, 32);

            LoadString(hinst, StereoApplets[i].descstring,

                lpNewCPlInfo->szInfo, 64);

            break;

        case CPL_SELECT:    // applet icon selected

            break;

        case CPL_DBLCLK:    // applet icon double-clicked

            MessageBeep(MB_ICONEXCLAMATION);

            DialogBox(hinst,

                MAKEINTRESOURCE(StereoApplets[i].dlgtemplate),

                hwndCPL, StereoApplets[i].dlgfn);

            break;

        case CPL_STOP:      // sent once per app. before CPL_EXIT

            break;

        case CPL_EXIT:    // sent once before FreeLibrary is called

            break;

        default:

            break;

    }

    return 0;

}


 Control Panel Reference

The following functions and messages are associated with the Control Panel.


 Control Panel Functions

Following is the function used with the Control Panel.

CPlApplet


 Control Panel Messages

Following are the messages used with the Control Panel.

CPL_DBLCLK
CPL_EXIT
CPL_GETCOUNT
CPL_INIT
CPL_INQUIRE
CPL_NEWINQUIRE
CPL_SELECT
CPL_STOP
WM_CPL_LAUNCH
WM_CPL_LAUNCHED


 File Installation Library

The Microsoft® Win32® application programming interface (API) includes a file installation library that makes it easier for applications to install files properly and enables setup programs to analyze files currently installed.


 About File Installation

The functions included in the file installation library determine where a file should be installed, identify conflicts with currently installed files, and perform the installation process. These functions enable installation programs 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 file installation library also includes functions that 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.

Version information can be added to any Microsoft® Windows® file that can have Windows resources, such as a dynamic-link library (DLL), an executable file, or a font file. To add the information, a developer must create a version resource and add the resource to the file by using a resource compiler and specifying VS_FILE_INFO as the resource type.


 Creating an Installation Program

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, the developer must have the following information for each file on the installation disk(s):

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

For each file on the installation disk(s), the installation program must, at a minimum, call the VerFindFile and VerInstallFile functions. These functions are described briefly in the following paragraphs.

The installation program can use VerFindFile with the destination-file name 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 Windows 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.

VerInstallFile 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 for all errors a common 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. The file installation library provides four functions the installation program can use for this purpose: GetFileVersionInfoSize, GetFileVersionInfo, VerQueryValue, and 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.


 File Installation Library Functions

Following are the functions used for file installation.

GetFileVersionInfo
GetFileVersionInfoSize
VerFindFile
VerInstallFile
VerLanguageName
VerQueryValue

Obsolete or Deleted Functions

GetFileResource
GetFileResourceSize


 File Manager Extensions

In Microsoft® Windows®, a File Manager extension is a dynamic-link library (DLL) that adds a menu and buttons to File Manager. A File Manager extension can also display (in the status bar) Help text for the buttons. This guide describes how to create and install extensions for File Manager.


 About File Manager Extensions

File Manager maintains a list of extensions in an initialization file and loads the extensions when starting. An extension DLL contains an entry point that processes menu commands and notification messages sent by File Manager. Up to five extension DLLs can be installed at any one time.


 Creating a File Manager Extension

A File Manager extension must reside in a DLL that includes a standard entry point, the FMExtensionProc callback function. The extension must include the WFEXT.H header file that defines File Manager messages and structures. File Manager communicates with the extension DLL by sending the following messages to the DLL's FMExtensionProc function.

Message	Meaning
1−99	User has selected an item from the extension-supplied menu. The value is the identifier of the selected menu item.
FMEVENT_HELPSTRING	User is selecting an extension menu or toolbar command item. File Manager wants the extension to supply a helpstring.
FMEVENT_HELPMENUITEM	User has pressed F1 while selecting an extension menu or toolbar command item. File Manager wants the extension to call WinHelp appropriately for the command item.
FMEVENT_INITMENU	User has selected the extension's menu. The extension should initialize items in the menu.
FMEVENT_LOAD	File Manager is loading the extension DLL and prompts the DLL for information about the menu that the DLL supplies.
FMEVENT_SELCHANGE	Selection in the File Manager directory window or Search Results window has changed.
FMEVENT_TOOLBARLOAD	File Manager is creating the toolbar and prompts the extension DLL for information about any buttons the DLL adds to the toolbar.
FMEVENT_UNLOAD	File Manager is unloading the extension DLL.
FMEVENT_USER_REFRESH	User has chosen the Refresh command from the Window menu. The extension should update items in the menu, if necessary.


 Creating the Entry-Point Function

File Manager communicates with an extension DLL through the FMExtensionProc callback function. Make sure to export this function by listing it in the EXPORTS statement of your extension's module-definition (.DEF) file. The FMExtensionProc function handles the messages listed in the preceding section by performing the tasks listed in the following table.

Task	Action
Initializing the extension (FMEVENT_LOAD)	Provides File Manager with the name and handle of the menu and saves the menu-item delta value.
Initializing the menu (FMEVENT_INITMENU)	Initializes all top-level menu items and the items in any submenus.
Initializing the toolbar (FMEVENT_TOOLBARLOAD)	Provides File Manager with information about the buttons to add to the toolbar, including the command identifier, Help string identifier, styles, and bitmap identifier.
Processing menu selections	Carries out commands that the user chooses from the extension's menu.
Processing file selections (FMEVENT_SELCHANGE)	Queries File Manager for information about the file that the user has selected from the directory window or Search Results window.
Updating items in the menu (FMEVENT_USER_REFRESH)	Modifies the menu as appropriate when the user chooses File Manager's Refresh command from the Window menu.
Providing menu item help strings (FMEVENT_HELPSTRING)	Provides File Manager with a help string for a specified command in a specified menu. File Manager displays this string in the area at the bottom left of the window.
Passing menu item help requests on to WinHelp (FMEVENT_HELPMENUITEM)	Provides WinHelp with the window passed by File Manager and menu item information,
Quitting the extension DLL (FMEVENT_UNLOAD)	Frees any memory allocated and prepares to exit.
The FMExtensionProc function is defined as follows.

LONG WINAPI FMExtensionProc(hwnd, wMsg, lParam)

HWND hwnd;

WORD wMsg;

LONG lParam;

The hwnd parameter identifies the File Manager window. An extension should use this window handle to specify the parent window for any dialog box or message box it must display. It should also use this handle to send query messages to File Manager. The uMsg parameter contains one of the File Manager messages listed previously. The lParam parameter contains a message-specific value. The return value from the FMExtensionProc function depends on the value of the uMsg parameter.

The menu added to File Manager may be a hierarchical (cascaded) menu and may contain grayed, disabled, or checked menu items in addition to command items. Menu items should be text only; owner-drawn menus and bitmap menus are not supported. Changing the bitmap for check marks is not supported.

Whenever File Manager calls the FMExtensionProc function, it waits to refresh its directory windows (for changes in the file system) until after the function returns. This allows the extension to perform large numbers of file operations without excessive repainting on the part of File Manager. It is not necessary for the extension to send the FM_REFRESH_WINDOWS message to notify File Manager to repaint its directory windows.


 Loading the Extension

File Manager first sends the FMEVENT_LOAD message to the FMExtensionProc function. The lParam parameter accompanying the FMEVENT_LOAD message points to an FMS_LOAD structure that File Manager uses to obtain information about the extension-supplied menu, including the menu name and menu handle.

File Manager also uses the FMS_LOAD structure to pass the menu-item delta value to the extension. To avoid conflicts with its own menu-item identifiers, File Manager renumbers the menu-item identifiers in an extension-supplied menu by adding the delta value to each identifier. An extension DLL that must modify its menu after File Manager has loaded it must use the delta value. For example, to delete a menu item, the extension DLL finds the sum of the delta value and the menu-item identifier and passes it as the idItem parameter to the DeleteMenu function.

If an extension returns FALSE in response to this message, File Manager calls the FreeLibrary function and ends any communication with the extension DLL. This is the only place where an extension can notify File Manager of initialization problems and thus prevent the extension from being loaded.


 Adding Custom Buttons

A File Manager extension can add custom buttons to the File Manager toolbar by returning button information in response to the FMEVENT_TOOLBARLOAD message. File Manager sends this message to the FMExtensionProc function of the extension only if the extension successfully installed a custom menu during the processing of the FMEVENT_LOAD message. Use custom buttons as accelerator keys for menu commands specified in the custom menu.

When FMExtensionProc receives the FMEVENT_TOOLBARLOAD message, the lParam parameter points to an FMS_TOOLBARLOAD structure. The File Manager extension must copy information about the custom buttons to the structure, including the number of buttons and a specifier for the bitmap containing the button images (either the identifier for a bitmap resource or a handle to a memory bitmap). The extension must also include the address of an array of EXT_BUTTON structures, each of which must contain a command identifier for the corresponding button. If the button is an accelerator for a menu command, the button identifier and corresponding menu-command identifier must be equal.

The bitmap containing the button images must be a bitmap resource or a memory bitmap. The extension must copy either the resource identifier or the memory bitmap's handle to the FMS_TOOLBARLOAD structure; and, in the case of a bitmap resource, the resource must be in the extension's executable file.

The bitmap must contain one image for each specified button. The bitmap height is always 15 pixels; the width is always a multiple of 16 pixels because each button image must be 16 pixels wide. Button images are concatenated from left to right. For example, the image of the first button specified in the array of EXT_BUTTON structures must be the leftmost image in the bitmap.

An extension can provide a line of Help text for a button by specifying the identifier of a string resource in the idsHelp member of the EXT_BUTTON structure. When the user selects the button, File Manager retrieves the string resource and displays it on the toolbar.


 Processing Menu Selections

The menu resource that you define for your extension's menu must use menu-item identifiers in the range 1 through 99. When the user selects an item, the extension receives a command notification that is the identifier of the selected item as defined in the resource-definition file (which has the .RC filename extension). The command notification is not the sum of the delta value and the identifier. An extension DLL's FMExtensionProc function carries out commands by processing command notifications.


 Initializing the Extension Menu

Whenever the user selects the extension's main menu item from File Manager's menu bar, File Manager sends the FMEVENT_INITMENU message to the extension DLL. An extension can use this message to initialize its menu items. For example, an extension can add check marks, disable items, or gray items during this message.

When the user selects submenus within the extension's menu, File Manager does not send the FMEVENT_INITMENU message. An extension DLL must initialize all items at the same time, including those in submenus.


 Updating the Extension Menu

When the user chooses the Refresh command from the Window menu, File Manager sends an FMEVENT_USER_REFRESH message to an extension DLL. The extension can use this opportunity to update its menu items.


 Processing File Selections

When the user selects a filename in the directory window or in the Search Results window, File Manager sends the FMEVENT_SELCHANGE message to an extension DLL. The extension can use this opportunity to send a query message to File Manager to obtain more information about the user's selection.

Because the user can change the selection often, the extension should return promptly after processing the FMEVENT_SELCHANGE message to avoid slowing the user's selection process.


 Quitting the Extension Dynamic-Link Library

When File Manager quits, it sends the FMEVENT_UNLOAD message to each extension DLL and then calls the FreeLibrary function to free the DLLs. Each DLL should free any memory that it has allocated.


 Installing Extensions

File Manager installs extensions that have settings in the [AddOns] section of the WINFILE.INI initialization file. Each setting contains an entry and a value. An entry consists of a string that represents the name of an extension. The value assigned to the entry consists of a string that specifies the path to the extension DLL. An application can use the WritePrivateProfileString function to add a setting to WINFILE.INI. The following example shows a setting in WINFILE.INI.

[AddOns]

MyExtension=C:\NT\SYSTEM\MYEXT.DLL

File Manager does not display an error message if it cannot find an extension DLL, so an extension DLL can be deleted in order to uninstall it. Even so, an application that installs an extension DLL should provide an uninstall option to remove the extension's setting from the WINFILE.INI file.


 Extension Messages

An extension can send the following window messages to retrieve relevant information from File Manager. File Manager is guaranteed to respond correctly only to messages sent from the FMExtensionProc function.

Message	Description
FM_GETDRIVEINFO	File Manager returns drive information from the active window. An extension provides a pointer to an FMS_GETDRIVEINFO structure; File Manager fills the structure with drive information.
FM_GETFILESEL	File Manager returns information about a selected file from the active File Manager window (either the directory window or the Search Results window). An extension provides a pointer to an FMS_GETFILESEL structure; File Manager fills the structure with file information.
FM_GETFILESELLFN	Same as the FM_GETFILESEL message except that the selected file may have a long filename.
FM_GETFOCUS	File Manager returns a value that identifies the type of window with input focus.
FM_GETSELCOUNT	File Manager returns the count of selected files in the directory and Search Results windows.
FM_GETSELCOUNTLFN	Same as the FM_GETSELCOUNT message except that the count includes files with long filenames.
FM_REFRESH_WINDOWS	File Manager repaints either its active window or all of its windows. This message is similar to File Manager's Refresh command on the Window menu.
FM_RELOAD_EXTENSIONS	File Manager reloads all extensions. First, File Manager unloads all extensions, sending an FMEVENT_UNLOAD message to each extension. Then, it reloads the extensions, sending an FMEVENT_LOAD message to each extension. The FM_RELOAD_EXTENSIONS message allows an extension to uninstall itself by removing its setting from the WINFILE.INI file; this action causes File Manager to reload the remaining extensions. Other applications and programs (for example, installation programs) can also post this message by calling the PostMessage function.


 Processing Commands and Messages from File Manager

The following code shows the FMExtensionProc function for a sample extension DLL. It demonstrates how an extension processes the menu commands and notification messages sent by File Manager.

HINSTANCE hinst;

HMENU hmenu;

WORD wMenuDelta;

BOOL fMultiple = FALSE;

BOOL fLFN = FALSE;

LONG WINAPI FMExtensionProc(hwnd, wMsg, lParam)

HWND hwnd;

WORD wMsg;

LONG lParam;

{

    CHAR szBuf[200];

    INT count;

    switch (wMsg) {

    case FMEVENT_LOAD:

       #define lpload  ((LPFMS_LOAD) lParam)

       /* Save the menu-item delta value. */

       wMenuDelta = lpload->wMenuDelta;

       /* Fill the FMS_LOAD structure. */

       lpload->dwSize = sizeof(FMS_LOAD);

       lstrcpy(lpload->szMenuName, "&Extension");

       /* Return the handle of the menu. */

       hinst = GetModuleHandle("ext.dll");

       lpload->hMenu = GetSubMenu(LoadMenu(hinst,

       MAKEINTRESOURCE(MYMENU)), 0);

       return (LONG)TRUE;

   case FMEVENT_UNLOAD:

       /* Perform any cleanup procedures here. */

       break;

   case FMEVENT_INITMENU:

       /* Copy the menu handle. */

       hmenu = (HMENU) lParam;

       /*

             * Add check marks to menu items as appropriate.

             * Add menu-item delta values to menu-item

             * identifiers to specify the menu items to check.

        */

       CheckMenuItem(hmenu,

               wMenuDelta + IDM_MULTIPLE,

               fMultiple ? MF_BYCOMMAND | MF_CHECKED :

                       MF_BYCOMMAND | MF_UNCHECKED);

       CheckMenuItem(hmenu,

               wMenuDelta + IDM_LFN,

               fLFN ? MF_BYCOMMAND | MF_CHECKED :

                       MF_BYCOMMAND | MF_UNCHECKED);

       break;

   case FMEVENT_TOOLBARLOAD:

   {

       static EXT_BUTTON extbtn[] = {

          {1, 0, 0},

       };

            /* Fill the FMS_TOOLBARLOAD structure. */

       #define lptbld ((LPFMS_TOOLBARLOAD) lParam)

       lptbld->dwSize = sizeof(FMS_TOOLBARLOAD);

       lptbld->lpButtons = (LPEXT_BUTTON) &extbtn;

       lptbld->cButtons = 1;

       lptbld->cBitmaps = 1;

       lptbld->idBitmap = ID_BUTTONBITMAP;

       return (LONG)TRUE;

   }

   case FMEVENT_USER_REFRESH:

            MessageBox(hwnd, "User refresh event",

                "Hey!", MB_OK);

       break;

   case FMEVENT_SELCHANGE:

       break;

        /*

         * The following messages are generated when the user

         * chooses items from the extension menu.

         */

   case FMEVENT_HELPSTRING:

       #define lphs ((LPFMS_HELPSTRING)lParam)

       if (lphs->idCommand == -1)

          lstrcpy(lphs->szHelp, "Help for extension menu");

       else

          wsprintf(lphs->szHelp, "Help for item %d", lphs->idCommand);

       break;

   case FMEVENT_HELPMENUITEM:

       wsprintf(szBuf, "Help for %d", lParam);

       MessageBox(hwnd, szBuf, "WinHelp call", MB_OK);

       /*

        * Use: WinHelp(hwnd, "ExtHelp.hlp", HELP_CONTEXT, lParam);

        */

       break;

   case IDM_GETFOCUS:

       wsprintf(szBuf, "Focus %d",

               (INT) SendMessage(hwnd, FM_GETFOCUS, 0, 0));

       MessageBox(hwnd, szBuf, "Focus", MB_OK);

       break;

   case IDM_GETCOUNT:

       count = (INT) SendMessage(hwnd,

                fLFN ? FM_GETSELCOUNTLFN : FM_GETSELCOUNT,

                0, 0);

       wsprintf(szBuf, "%d files selected", count);

       MessageBox(hwnd, szBuf, "Selection Count", MB_OK);

       break;

   case IDM_GETFILE:

   {

       FMS_GETFILESEL file;

       count = (INT) SendMessage(hwnd,

               fLFN ? FM_GETSELCOUNTLFN : FM_GETSELCOUNT,

               FMFOCUS_DIR,

               0);

       while (count >= 1) {

                /*

                 * Selection indices are zero-based (0 is

                 * first).

                 */

      count--;

      SendMessage(hwnd, FM_GETFILESEL, count,

          (LONG) (LPFMS_GETFILESEL) &file);

      wsprintf(szBuf, "file %s\nSize %ld",

          (LPSTR) file.szName, file.dwSize);

                MessageBox(hwnd, szBuf, "File Information",

                    MB_OK);

      if (!fMultiple)

         break;

       }

       break;

   }

   case IDM_GETDRIVE:

   {

       FMS_GETDRIVEINFO drive;

       SendMessage(hwnd, FM_GETDRIVEINFO, 0,

       (LONG) (LPFMS_GETDRIVEINFO)&drive);

       wsprintf(szBuf,

                "%s\nFree %ld\nTotal %ld\nVolume %s\nShare %s",

       (LPSTR) drive.szPath, drive.dwFreeSpace,

       drive.dwTotalSpace, (LPSTR) drive.szVolume,

       (LPSTR) drive.szShare);

       MessageBox(hwnd, szBuf, "Drive Info", MB_OK);

       break;

   }

   case IDM_LFN:

       MessageBox(hwnd, "IDM_LFN", "Hi", MB_OK);

       fLFN = !fLFN;

       break;

   case IDM_MULTIPLE:

       MessageBox(hwnd, "IDM_MULTIPLE", "Hi", MB_OK);

       fMultiple = !fMultiple;

       break;

   case IDM_REFRESH:

   case IDM_REFRESHALL:

       SendMessage(hwnd, FM_REFRESH_WINDOWS,

       wMsg == IDM_REFRESHALL, 0);

       break;

   case IDM_RELOAD:

       PostMessage(hwnd, FM_RELOAD_EXTENSIONS, 0, 0);

       break;

    }

    return 0L;

}


 Adding the Undelete Command

File Manager supports a hook for adding an Undelete command to the File menu (below the Delete command). If an "undelete" dynamic-link library is specified in the WINFILE.INI file, File Manager adds the Undelete command to the File menu when starting. When the user chooses the Undelete command, File Manager calls the DLL.

The [settings] section of the WINFILE.INI file should include a reference to the undelete DLL, as follows.

[settings]

UNDELETE.DLL=C:\MYDIR\OTHER.DLL

An undelete DLL must include a standard entry point, the UndeleteFile function. This function must be exported by specifying the name of the function in the EXPORTS statement of the DLL's module-definition (.DEF) file.

The UndeleteFile function is defined as follows:

DWORD APIENTRY UndeleteFile(hwndParent, lpszDir)

HWND hwndParent;

LPSTR lpszDir;

The hwndParent parameter identifies the parent window for any dialog boxes the DLL creates. The lpszDir parameter specifies the initial directory to be used (for example, C:\TEMP).


 File Manager Extension Functions

Following are the functions used with File Manager extensions.

FMExtensionProc
UndeleteFile


 Screen Saver Library

The Microsoft® Win32® application programming interface (API) supports special applications called screen savers that start when the mouse and keyboard have been idle for a period of time. Screen savers exist for two main reasons:

•	To avoid phosphor burn caused by static images on a screen

•	To conceal sensitive information left on a screen


 About Screen Savers

The Desktop application in Windows Control Panel lets users select from a list of screen savers, specify how much time should elapse before the screen saver is started, configure screen savers, and preview screen savers. Screen savers are loaded automatically when Windows starts or when a user activates the screen saver feature by using Control Panel.

Once a screen saver is chosen, Windows monitors keystrokes and mouse movements, starting the screen saver after a period of inactivity. However, Windows does not start the screen saver if any of the following conditions exist:

•	The active application is not a Windows-based application.

•	A computer-based training (CBT) window is present.

•	The active application receives the WM_SYSCOMMAND message with wParam set to the SC_SCREENSAVE value, but does not pass the message to the DefWindowProc function.

Screen savers contain specific exported functions, resource definitions, and variable declarations. The static-link library SCRNSAVE.LIB contains the main function and other startup code required for a screen saver. When a screen saver starts, the startup code in SCRNSAVE.LIB creates a full-screen window. The window class for this window is declared as follows.

WNDCLASS cls;

cls.hCursor        = NULL;

cls.hIcon          = LoadIcon(hInst, MAKEINTATOM(ID_APP));

cls.lpszMenuName   = NULL;

cls.lpszClassName  = "WindowsScreenSaverClass";

cls.hbrBackground  = GetStockObject(BLACK_BRUSH);

cls.hInstance      = hInst;

cls.style          = CS_VREDRAW | CS_HREDRAW |

                     CS_SAVEBITS | CS_DBLCLKS;

cls.lpfnWndProc    = (WNDPROC) ScreenSaverProc;

cls.cbWndExtra     = 0;

cls.cbClsExtra     = 0;

To create a screen saver, most developers create a source-code module containing three required functions and link them with SCRNSAVE.LIB. A screen saver module is responsible only for configuring itself and for providing visual effects.

One of the three required functions in a screen saver module is ScreenSaverProc. This function processes specific messages and passes any unprocessed messages back to SCRNSAVE.LIB. Following are some of the typical messages processed by ScreenSaverProc.

Message	Meaning
WM_CREATE	Retrieve any initialization data from the file REGEDIT.INI. Set a window timer for the screen saver window. Perform any other required initialization.
WM_ERASEBKGND	Erase the screen saver window and prepare for subsequent drawing operations.
WM_TIMER	Perform drawing operations.
WM_DESTROY	Destroy the timer(s) created when the application processed the WM_CREATE message. Perform any additional required cleanup.
ScreenSaverProc passes unprocessed messages to SCRNSAVE.LIB by calling the DefScreenSaverProc function. The following table describes how this function processes various messages.

Message	Action
WM_SETCURSOR	Sets the cursor to the null cursor, removing it from the screen.
WM_PAINT	Paints the screen background.
WM_LBUTTONDOWN	Terminates the screen saver.
WM_MBUTTONDOWN	Terminates the screen saver.
WM_RBUTTONDOWN	Terminates the screen saver.
WM_KEYDOWN	Terminates the screen saver.
WM_MOUSEMOVE	Terminates the screen saver.
WM_ACTIVATE	If wParam is FALSE, terminates the screen saver.
The second required function in a screen saver module is ScreenSaverConfigureDialog. This function displays a dialog box that enables the user to configure the screen saver. (Thus, an application must provide a corresponding dialog box template.) Windows displays the configuration dialog box when the user chooses the Setup button in the Screen Saver box in the Desktop application in Control Panel. The data entered by the user with the configuration dialog box is stored in the REGEDIT.INI file.

The third required function in a screen saver module is RegisterDialogClasses. This function must be called by all screen saver applications. However, applications that do not require special windows or custom controls in the configuration dialog box can simply return TRUE. Applications requiring custom controls or special windows should use this function to register the corresponding window classes.

In addition to creating a module that supports the three functions just described, a screen saver should supply an icon. This icon is visible only when the screen saver is run as a standalone application. (To be run by Control Panel, a screen saver must have the .SCR filename extension; to be run as a standalone application, it must have the .EXE filename extension.) The icon must be identified in the screen saver's resource file by the constant ID_APP, which is defined in the header file SCRNSAVE.H.

One final requirement is a screen saver description string. The resource file for a screen saver must contain a descriptive string that Control Panel displays as the screen saver name. The description string must be the first string in the resource file's string table (identified with the ordinal value 1).


 Using the Screen Saver Functions

•	Creating a screen saver

•	Installing new screen savers

•	Adding help


 Creating a Screen Saver

This section contains example code taken from a screen saver application. At intervals ranging from 1 through 10 seconds, this application repaints the screen with one of four colors: white, light gray, dark gray, and black. The application paints the screen each time it receives a WM_TIMER message. The user can adjust the interval at which this message is sent by displaying the application's configuration dialog box and adjusting a single horizontal scroll bar.


 Supporting the Configuration Dialog Box

Most screen savers provide a configuration dialog box to let the user specify customization data such as unique colors, drawing speeds, line thicknesses, fonts, and so on. To support the configuration dialog box, the application must provide a dialog box template and must also support the ScreenSaverConfigureDialog function. Following is the dialog box template for the sample application.

DLG_SCRNSAVECONFIGURE DIALOG 6, 18, 160, 63
LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL
STYLE DS_MODALFRAME | WS_POPUP | WS_VISIBLE | WS_CAPTION |
    WS_SYSMENU
CAPTION "Sample Screen-Saver Setup"
FONT 8, "MS Sans Serif"
BEGIN
    GROUPBOX      "Redraw Speed", 101, 0, 6, 98, 40
    SCROLLBAR     ID_SPEED, 5, 31, 89, 10
    LTEXT         "Fast", 103, 6, 21, 20, 8
    LTEXT         "Slow", 104, 75, 21, 20, 8
    PUSHBUTTON    "OK", ID_OK, 117, 10, 40, 14
    PUSHBUTTON    "Cancel", ID_CANCEL, 117, 32, 40, 14
END

You must define the constant used to identify the dialog box template by using the decimal value 2003, as in the following example.

#define  DLG_SCRNSAVECONFIGURE 2003

The following example shows the ScreenSaverConfigureDialog function found in the sample application.

#define MINVEL  1               /* minimum redraw-speed value    */

#define MAXVEL  10              /* maximum redraw-speed value    */

#define DEFVEL  5               /* default redraw-speed value    */

LONG    lSpeed = DEFVEL;        /* redraw-speed variable         */

extern HINSTANCE hMainInstance; /* screen saver instance handle  */

CHAR   szAppName[80];           /* .INI section name             */

CHAR   szTemp[20];              /* temporary array of characters */

CHAR   szRedrawSpeed[] = "Redraw Speed";   /* .INI speed entry   */

BOOL WINAPI ScreenSaverConfigureDialog(hDlg, message, wParam, lParam)

HWND  hDlg;

UINT  message;

DWORD wParam;

LONG  lParam;

{

    static HWND hSpeed; /* handle of speed scroll bar */

    static HWND hOK;    /* handle of OK push button */

    switch(message)

    {

        case WM_INITDIALOG:

            /* Retrieve the application name from the .RC file. */

            LoadString(hMainInstance, idsAppName, szAppName, 40);

            /* Retrieve the .INI (or registry) filename. */

            LoadString(hMainInstance, idsIniFile, szIniFile,

                MAXFILELEN);

            /* Retrieve any redraw-speed data from the registry. */

            lSpeed = GetPrivateProfileInt(szAppName, szRedrawSpeed,

                DEFVEL, szIniFile);

            /*

             * If the initialization file does not contain an entry

             * for this screen saver, use the default value.

             */

            if(lSpeed > MAXVEL || lSpeed < MINVEL)

                lSpeed = DEFVEL;

            /* Initialize the redraw-speed scroll bar control. */

            hSpeed = GetDlgItem(hDlg, ID_SPEED);

            SetScrollRange(hSpeed, SB_CTL, MINVEL, MAXVEL, FALSE);

            SetScrollPos(hSpeed, SB_CTL, lSpeed, TRUE);

            /* Retrieve a handle of the OK push button control. */

            hOK = GetDlgItem(hDlg, ID_OK);

            return TRUE;

        case WM_HSCROLL:

            /*

             * Process scroll bar input, adjusting the lSpeed

             * value as appropriate.

             */

            switch (LOWORD(wParam))

                {

                    case SB_PAGEUP:

                        --lSpeed;

                    break;

                    case SB_LINEUP:

                        --lSpeed;

                    break;

                    case SB_PAGEDOWN:

                        ++lSpeed;

                    break;

                    case SB_LINEDOWN:

                        ++lSpeed;

                    break;

                    case SB_THUMBPOSITION:

                        lSpeed = HIWORD(wParam);

                    break;

                    case SB_BOTTOM:

                        lSpeed = MINVEL;

                    break;

                    case SB_TOP:

                        lSpeed = MAXVEL;

                    break;

                    case SB_THUMBTRACK:

                    case SB_ENDSCROLL:

                        return TRUE;

                    break;

                }

                if ((int) lSpeed <= MINVEL)

                    lSpeed = MINVEL;

                if ((int) lSpeed >= MAXVEL)

                    lSpeed = MAXVEL;

                SetScrollPos((HWND) lParam, SB_CTL, lSpeed, TRUE);

            break;

        case WM_COMMAND:

            switch(LOWORD(wParam))

            {

                case ID_OK:

                   /*

                    * Write the current redraw-speed variable to

                    * the .INI file.

                    */

                    wsprintf(szTemp, "%ld", lSpeed);

                    WritePrivateProfileString(szAppName, szRedrawSpeed,

                        szTemp, szIniFile);

                case ID_CANCEL:

                    EndDialog(hDlg, LOWORD(wParam) == ID_OK);

                return TRUE;

            }

    }

    return FALSE;

}

In addition to providing the dialog box template and supporting the ScreenSaverConfigureDialog function, an application must also support the RegisterDialogClasses function. This function registers any nonstandard window classes required by the screen saver. Because the sample application used only standard window classes in its dialog box procedure, this function simply returns TRUE, as in the following example.

BOOL WINAPI RegisterDialogClasses(hInst)

HANDLE  hInst;

{

    return TRUE;

}


 Supporting the Screen Saver Window Procedure

Each screen saver must support a window procedure named ScreenSaverProc. Like most window procedures, ScreenSaverProc processes a set of specific messages and passes any unprocessed messages to a default procedure. However, instead of passing them to the DefWindowProc function, ScreenSaverProc passes unprocessed messages to the DefScreenSaverProc function. Another difference between ScreenSaverProc and a normal window procedure is that the handle passed to ScreenSaverProc identifies the entire desktop rather than a client window. The following example shows the ScreenSaverProc window procedure for the sample screen saver.

LONG WINAPI ScreenSaverProc(hwnd, message, wParam, lParam)

HWND  hwnd;

UINT  message;

DWORD wParam;

LONG  lParam;

{

static HDC          hdc;    /* device-context handle */

static RECT         rc;     /* RECT structure */

static UINT         uTimer; /* timer identifier */

    switch(message)

    {

        case WM_CREATE:

            /* Retrieve the application name from the .RC file. */

            LoadString(hMainInstance, idsAppName, szAppName, 40);

            /* Retrieve the .INI (or registry) filename. */

            LoadString(hMainInstance, idsIniFile, szIniFile,

                MAXFILELEN);

            /* Retrieve any redraw-speed data from the registry. */

            lSpeed = GetPrivateProfileInt(szAppName, szRedrawSpeed,

                DEFVEL, szIniFile);

           /*

            * Set a timer for the screen saver window using the

            * redraw-rate stored in REGEDIT.INI.

            */

            uTimer = SetTimer(hwnd, 1, lSpeed * 1000, NULL);

            break;

        case WM_ERASEBKGND:

           /*

            * The WM_ERASEBKGND message is issued before the

            * WM_TIMER message, allowing the screen saver to

            * paint the background as appropriate.

            */

            hdc = GetDC(hwnd);

            GetClientRect (hwnd, &rc);

            FillRect (hdc, &rc, GetStockObject(BLACK_BRUSH));

            ReleaseDC(hwnd,hdc);

            break;

        case WM_TIMER:

           /*

            * The WM_TIMER message is issued at (lSpeed * 1000)

            * intervals, where lSpeed == .001 seconds. This

            * code repaints the entire desktop with a white,

            * light gray, dark gray, or black brush each

            * time a WM_TIMER message is issued.

            */

            hdc = GetDC(hwnd);

            GetClientRect(hwnd, &rc);

            if (i++ <= 4)

                FillRect(hdc, &rc, GetStockObject(i));

            else

                (i = 0);

            ReleaseDC(hwnd,hdc);

            break;

        case WM_DESTROY:

           /*

            * When the WM_DESTROY message is issued, the screen saver

            * must destroy any of the timers that were set at WM_CREATE

            * time.

            */

            if (uTimer)

                KillTimer(hwnd, uTimer);

            break;

    }

   /*

    * DefScreenSaverProc processes any messages

    * ignored by ScreenSaverProc.

    */

    return DefScreenSaverProc(hwnd, message, wParam, lParam);

}


 Creating a Module-Definition File

The ScreenSaverProc and ScreenSaverConfigureDialog functions must be exported in the application's module-definition file; RegisterDialogClasses should not be exported, however. The following example shows the module-definition file for the sample application.

NAME    SSTEST.SCR

DESCRIPTION 'SCRNSAVE : Test'

STUB    'WINSTUB.EXE'

EXETYPE WINDOWS

CODE    MOVEABLE

DATA    MOVEABLE MULTIPLE

HEAPSIZE  1024

STACKSIZE 4096

EXPORTS

        ScreenSaverProc

        ScreenSaverConfigureDialog


 Installing New Screen Savers

When compiling the list of available screen savers, Control Panel searches the Windows startup directory for files with the .SCR extension. Because screen savers are standard Windows executable files with .EXE extensions, you must rename them so they have .SCR extensions and copy them to the correct directory.


 Adding Help

The configuration dialog box for a screen saver typically includes a Help button. Screen saver applications can check for the Help button identifier and call the WinHelp function in the same way Help is provided in other Windows-based applications.


 Screen Saver Functions

Following are the functions used with screen savers.

DefScreenSaverProc
RegisterDialogClasses
ScreenSaverConfigureDialog
ScreenSaverProc


 Shell Dynamic Data Exchange Interface

This overview describes the dynamic data exchange (DDE) interface of Program Manager (PROGMAN.EXE). Program Manager is a shell — that is, an application that enables users to group, start, and otherwise control other applications for the Microsoft® Windows® operating system.


 About Program Manager Initialization

Program Manager starts automatically when the user starts Windows and runs as long as Windows is in use. When it starts, Program Manager displays one or more windows within its main window. Each window contains icons that correspond to logically related Windows-based applications. For example, the Accessories window contains icons for Windows Write, Paintbrush, Notepad, and other accessory applications.

Program Manager stores initialization and configuration information in the registry. This information is stored under the Settings, Groups, and Restrictions keys in the following section of the registry:

HKEY_CURRENT_USER\Software\Microsoft\WindowsNT\
        CurrentVersion\Program Manager

Additional information is stored in the Program Groups key in the following section of the registry:

HKEY_LOCAL_MACHINE\SOFTWARE


 Settings Key

The Settings key contains information that Program Manager uses to configure its environment. The following entries appear in the Settings key.

Entry	Description
MinOnRun	Specifies whether to minimize Program Manager when an application is started.
AutoArrange	Specifies whether Program Manager should automatically arrange icons within groups.
SaveSettings	Specifies whether to save the position of the Program Manager window when Program Manager terminates.
DISPLAY.DRV	Specifies the filename of the display driver in use when Program Manager last terminated. When Program Manager starts, it compares this value to the filename of the display driver currently in use. If the names are different, Program Manager re-extracts the application icons.
Window	Specifies the location and dimensions of the Program Manager window.
Order	Specifies the order that the groups listed in the Groups key appear in the Program Manager window.
Startup	Specifies the name of the startup group. Program Manager automatically starts the applications in the startup group whenever it starts.


 Groups Key

The windows that appear in the Program Manager window correspond to group files. From the user's perspective, a group file is a collection of icons that represent logically related applications, but from the programmer's perspective, a group file is actually a collection of data. This data includes the color information for the icons (AND and XOR masks), an offset to the resource header of each icon, the ideal resolution for displaying each icon, the name of the executable (.EXE) file that contains the application, and so on.

There are two types of groups: common and personal. A common group is shared among multiple users through network connections; a personal group is not shared. Program Manager stores information about personal groups under the Groups key. It stores information about common groups under the HKEY_LOCAL_MACHINE\SOFTWARE key.

The Groups key of the registry identifies the names of the group files that Program Manager displays as unique windows or icons. The groups must be numbered, but they need not be listed in any particular order. Program Manager never changes the number of an existing group.


 Restrictions Key

The Restrictions key controls whether certain features of Program Manager are enabled or disabled. The following entries can appear in the Restrictions key.

Entry	Description
NoRun	Specifies whether to disable the Run command on the File menu. If this entry is set to 1, the Run command is disabled. If this entry is set to 0, the Run command is enabled. The default is 0 if no value is specified.
NoClose	Specifies whether to prevent the user from closing Program Manager through the File menu, the System menu, the ALT+F4 key combination, or the Task List. If this entry is set to 1, closing is prevented. If this entry is set to 0, closing is allowed. The default is 0 if no value is specified.
EditLevel	Controls the extent to which the user can modify read-write groups. (Shared read-only groups cannot be modified.) This entry can be set to one of the following values.
Value	Action
0	Allows any modifications to the group. This is the default value.
1	Prevents the user from creating, deleting, or renaming groups.
2	Prevents the user from creating, deleting, or renaming groups and from creating or deleting items in a group.
3	Prevents the user from creating, deleting, or renaming groups; from creating or deleting items in a group; and from changing command lines for items in a group.
4	Prevents the user from changing any property of an item in a group; from creating, deleting, or renaming groups; from creating or deleting items in a group; and from changing command lines for items in a group.
NoFileMenu	Specifies whether to disable the File menu and all of its commands. If this entry is set to 1, the File menu is disabled. If this entry is set to 0, the menu is enabled. The default setting is 0 if no value is specified.
NoSaveSettings	Specifies whether to disable the Save Settings on Exit command on the Options menu. If this entry is set to 1, the Save Settings on Exit command is disabled. If this entry is set to 0, the command is enabled. The default setting is 0 if no value is specified.
Setting the value of NoRun to 1 and the value of EditLevel to 3 prevents a user from using Program Manager to run any applications not already in a program group.


 Command-String Interface

Program Manager has a DDE command-string interface that allows other applications to create, display, delete, and reload groups; add items to groups; replace items in groups; delete items from groups; and close Program Manager. The following commands perform these actions:

AddItem	ExitProgman
CreateGroup	Reload
DeleteGroup	ReplaceItem
DeleteItem	ShowGroup
For example, the setup program for an application can use these commands to instruct Program Manager to install the application's icon in a group.

Multiple commands can be concatenated; each command must be contained in square brackets, and parameters must be contained in parentheses and separated by commas. Quotation marks must delimit arguments that contain spaces, brackets, or parentheses. For example, the following set of commands adds WINAPP.EXE to the Windows Applications group:

[CreateGroup("Windows Applications")]

[ShowGroup("My Group",1)]

[AddItem(winapp.exe,Win App,winapp.exe,2)]

To use these commands, an application must first initiate a DDE conversation with Program Manager. The application and topic names for the conversation are both PROGMAN. Then the application sends the WM_DDE_EXECUTE message, specifying the appropriate command and its parameters.

Note  The user can configure Windows to use a shell other than Program Manager as the default. Therefore, do not design an application that assumes Program Manager will be available for a DDE conversation.

The following sections describe Program Manager DDE command strings in detail. In the syntax blocks in the following sections, brackets enclose optional parameters.


 CreateGroup

The syntax for the CreateGroup command has this form:

CreateGroup(GroupName[,CommonGroupFlag])

The CreateGroup command instructs Program Manager to create a new group or activate the window of an existing group.

Following are the parameters for this command:

GroupName

Identifies the group to be created or activated. This parameter is a string. If a group already exists with the name specified by GroupName, CreateGroup activates the group window.

CommonGroupFlag

Specifies whether the new group is a common group or a personal group. If this parameter is 1, a common group is created; if it is 0, a personal group is created. To create a common group, the user currently logged on must have administrative privileges. If this parameter is 1 but the user does not have administrative privileges, the command fails. The default value of this parameter is 1 (common group) if no value is specified and if the user has administrative privileges. The default value is 0 (personal group) if no value is specified and the user does not have administrative privileges.

  Note  If the second parameter of the CreateGroup command specifies the path of the group file (as was required in Windows version 3.1), the parameter is ignored.


 ShowGroup

The syntax for the ShowGroup command has this form:

ShowGroup(GroupName,ShowCommand[,CommonGroupFlag])

The ShowGroup command instructs Program Manager to minimize, maximize, or restore the window of an existing group.

Following are the parameters for this command:

GroupName

Identifies the group window to be minimized, maximized, or restored.

ShowCommand

Specifies the action Program Manager is to perform on the group window. This parameter is an integer. It must have one of the following values.

Value	Action
1	Activates and displays the group window. If the window is minimized or maximized, Windows restores it to its original size and position.
2	Activates the group window and displays it as an icon.
3	Activates the group window and displays it as a maximized window.
4	Displays the group window in its most recent size and position. The window that is currently active remains active.
5	Activates the group window and displays it in its current size and position.
6	Minimizes the group window.
7	Displays the group window as an icon. The currently active window remains active.
8	Displays the group window in its current state. The currently active window remains active.
CommonGroupFlag

Specifies whether the group is a common group or a personal group. If this parameter is 1, the group being minimized, maximized, or restored is a common group; if it is 0, the group is a personal group. This parameter defaults to 1 (common group) if no value is specified. To minimize, maximize, or restore a common group, the user currently logged on must have administrative privileges. If this parameter is 1 but the user does not have administrative privileges, the command fails.


 DeleteGroup

The syntax for the DeleteGroup command has this form:

DeleteGroup(GroupName[,CommonGroupFlag])

The DeleteGroup command instructs Program Manager to delete an existing group.

Following are the parameters for this command:

GroupName

Identifies the group to be deleted.

CommonGroupFlag

Specifies whether the group is a common group or a personal group. If this parameter is 1, the group being deleted is a common group; if it is 0, the group is a personal group. This parameter defaults to 1 (common group) if no value is specified. To delete a common group, the user currently logged on must have administrative privileges. If this parameter is 1 but the user does not have administrative privileges, the command fails.

  Note  If the second parameter of the DeleteGroup command specifies the path of the group file (as was required in Windows version 3.1), the parameter is ignored.


 Reload

The syntax for the Reload command has this form:

Reload(GroupName[,CommonGroupFlag])

The ReloadGroup command instructs Program Manager to remove and reload an existing group. An application that modifies group files can use this command to cause Program Manager to update the groups when it has finished making modifications.

Following are the parameters for this command:

GroupName

Identifies the group to be removed and reloaded. If no value is specified for the GroupName parameter, Program Manager unloads all groups and reloads the groups specified in the Groups key of the registry. The Settings and Restrictions keys are not reread.

CommonGroupFlag

Specifies whether the group is a common group or a personal group. If this parameter is 1, the group being reloaded is a common group; if it is 0, the group is a personal group. This parameter defaults to 1 (common group) if no value is specified. To reload a common group, the user currently logged on must have administrative privileges. If this parameter is 1 but the user does not have administrative privileges, the command fails.


 AddItem

The syntax for the AddItem command has this form:

AddItem(CmdLine[,
    Name[,IconPath[,IconIndex[,xPos,yPos[,DefDir[,
    HotKey[,fMinimize[fSeparateMemSpace] ] ] ] ] ] ])

The AddItem command instructs Program Manager to add an icon to an existing group. There is a limit of 50 items per group.

Following are the parameters for this command:

CmdLine

Specifies the full command line required to run the application. This parameter is a string. At a minimum, this string is the name of the executable file for the application. It can also include the full path of the application and any parameters required by the application.

Name

Specifies the title that is displayed below the icon in the group window.

IconPath

Identifies the filename for the icon to be displayed in the group window. This parameter is a string. This file can be either a Windows-based executable file or an icon file. If no value is specified for the IconPath parameter, Program Manager uses the first icon in the file specified by the CmdLine parameter if that file is an executable file. If CmdLine specifies an associated file, Program Manager uses the first icon of the associated executable file. The association is taken from the registry. (For more information about the registry, see Registry.) If CmdLine specifies neither an executable file nor an associated executable file, Program Manager uses a default icon.

IconIndex

Specifies the index of the icon in the file identified by the IconPath parameter. The IconIndex parameter is an integer. PROGMAN.EXE contains five built-in icons that can be used for programs not written for Windows.

xPos

Specifies the horizontal position of the icon in the group window. This parameter is an integer. Both the xPos and yPos parameters must be used to specify the position of the icon. If the position is not specified, Program Manager places the icon in the next available space.

yPos

Specifies the vertical position of the icon in the group window. This parameter is an integer. Both the xPos and yPos parameters must be used to specify the position of the icon. If the position is not specified, Program Manager places the icon in the next available space.

DefDir

Specifies the name of the default (or working) directory. This parameter is a string.

HotKey

Identifies a hot (or shortcut) key that is specified by the user.

fMinimize

Specifies whether an application window is to be minimized when first displayed.

fSeparateMemSpace

Specifies whether a 16-bit application runs in a separate memory space.


 ReplaceItem

The syntax for the ReplaceItem command has this form:

ReplaceItem(ItemName)

The ReplaceItem command instructs Program Manager to delete an item and record the position of the deleted item. Program Manager adds a new item (specified by the next AddItem command) at this recorded position.

Following is the parameter for this command:

ItemName

Specifies the item to be deleted. Its position is recorded by Program Manager.


 DeleteItem

The syntax for the DeleteItem command has this form:

DeleteItem(ItemName)

The DeleteItem command instructs Program Manager to delete an item from the currently active group.

Following is the parameter for this command:

ItemName

Specifies the item to be deleted from the currently active group.


 ExitProgman

The syntax for the ExitProgman command has this form:

ExitProgman(bSaveGroups)

If Program Manager was started by another application, the ExitProgman command instructs Program Manager to terminate and, optionally, save its group information.

Following is the parameter for this command:

bSaveGroups

Specifies a Boolean value that, if it is nonzero, causes Program Manager to save its group information before closing. If bSaveGroups is zero, Program Manager does not save its group information.


 Requesting Group Information

Program Manager can provide information about its groups to an application. Applications can request this information from Program Manager by using the PROGMAN topic.

An application can obtain a list of Program Manager groups by issuing a request for the Group item. Program Manager provides the list in CF_TEXT format. The list consists of group-name strings separated by carriage returns.

An application can use a group name as an item name to request information about the group. Program Manager provides this information in CF_TEXT format. The fields of group information are separated by commas. The first line of the information contains the group name (in quotation marks), the path of the group file, and the number of items in the group. Each subsequent line contains information about an item in the group, including the command line (in quotation marks), the default directory, the icon path, the position in the group, the icon index, the shortcut key (in numeric form), and the minimize flag.


 Shell Library

A shell is an application that enables users to group, start, and otherwise control other applications. This overview describes features of the shell for the Microsoft® Windows® operating system.


 About the Shell Library

The following features are supported by the dynamic-link library SHELL.DLL:

•	The drag-drop feature

•	Associations (used) to find and start applications

•	Extraction of icons from executable files

The header file for the functions that support these features is SHELLAPI.H. The library is SHELL32.LIB.


 Using the Shell Features

•	Using the drag-drop feature

•	Using associations to find and start applications

•	Extracting icons from executable files


 Using the Drag-Drop Feature

When an application implements the drag-drop feature, a user can select one or more files in File Manager, drag them to an open application, and drop them there. The application in which the files were dropped receives a message it can use to retrieve the filenames and the coordinates of the point at which the files were dropped.

An application that can accept dropped files from File Manager calls the DragAcceptFiles function for one or more of its windows. When the user releases the mouse button to drop a file or files in the window specified in the call to DragAcceptFiles, File Manager sends the application a WM_DROPFILES message. (File Manager does not send the WM_DROPFILES message to an application unless the application calls DragAcceptFiles.) WM_DROPFILES contains a handle of a structure the application can query to retrieve the name of the dropped file and the coordinates of the cursor when the file was dropped. The application can use the DragQueryFile function to retrieve a count of the files that were dropped and their names. The DragQueryPoint function returns the window coordinates of the cursor when the user released the mouse button.

To free the memory allocated by the system for the WM_DROPFILES message, an application calls the DragFinish function when it is finished.

For example, an application can call the DragAcceptFiles function when it starts and call a drag-drop function when it receives a WM_DROPFILES message, as shown in the following example.

case WM_CREATE:

    DragAcceptFiles(hwnd, TRUE);

    break;

case WM_DROPFILES:

    DragFunc(hwnd, wParam); /* application-defined function */

    break;

case WM_DESTROY:

    DragAcceptFiles(hwnd, FALSE);

    break;

The following example uses the DragQueryPoint function to determine where to begin to write text. The first call to the DragQueryFile function determines the number of dropped files. The loop writes the name of each file, beginning at the point returned by DragQueryPoint.

POINT pt;

WORD cFiles, a;

char lpszFile[80];

DragQueryPoint((HANDLE) wParam, &pt);

cFiles = DragQueryFile((HANDLE) wParam, 0xFFFF, (LPSTR) NULL, 0);

for(a = 0; a < cFiles; pt.y += 20, a++) {

    DragQueryFile((HANDLE) wParam, a, lpszFile, sizeof(lpszFile));

    TextOut(hdc, pt.x, pt.y, lpszFile, lstrlen(lpszFile));

}

DragFinish((HANDLE) wParam);


 Using Associations to Find and Start Applications

File Manager includes an Associate dialog box that makes it possible for users to associate a filename extension with a specific application. File Manager stores these associations in the registry (under HKEY_CURRENT_USER\Software\Description\Microsoft\Windows\CurrentVersion\Extensions). If a file has a filename extension that is associated with an application, that application starts automatically whenever a user double-clicks that file in File Manager.

Using the FindExecutable and ShellExecute functions, applications can take advantage of such associations to find and start applications or open and print files.

An application can use the FindExecutable function to retrieve the name and handle of the executable file that is associated with a specified filename. The ShellExecute function either opens or prints a specified file, depending on the value of its lpOperation parameter. To open a document file, the function relies on the association of the filename extension.

Windows 95: You can use ShellExecute to open or explore a Windows 95 folder. To open a folder, use either of the following calls:

ShellExecute(handle, NULL, "path_to_folder", NULL, NULL, SW_SHOWNORMAL);

or

ShellExecute(handle, "open", "path_to_folder", NULL, NULL, SW_SHOWNORMAL);

To explore a folder, use the following call:

ShellExecute(handle, "explore", "path_to_folder", NULL, NULL, SW_SHOWNORMAL);

If the lpOperation parameter is NULL, the function opens the file specified by its lpFile parameter. If lpOperation is "open" or "explore", the function will force a open window or explorer.


 Extracting Icons from Executable Files

An application can use the ExtractIcon function to retrieve the handle of an icon from a specified executable file, dynamic-link library, or icon file. The following example uses the DragQueryPoint function to retrieve the coordinates of the point where a file was dropped, the DragQueryFile function to retrieve the filename of a dropped file, and the ExtractIcon function to retrieve the handle of the first icon in the file, if any.

POINT pt;

WORD cFiles;

HDC hdc;

char lpszFile[80];

HANDLE hCurrentInst, hicon;

DragQueryPoint((HANDLE) wParam, &pt);

cFiles = DragQueryFile((HANDLE) wParam, 0xFFFF, NULL, NULL);

if(cFiles > 1) {

    TextOut(hdc, pt.x, pt.y,

        "Please drop only one icon file.", 31);

    return FALSE;

}

else {

    DragQueryFile((HANDLE) wParam, 0, lpszFile, sizeof(lpszFile));

    hCurrentInst = (HINSTANCE) GetWindowLong(hwnd, GWL_HINSTANCE);

    hicon = ExtractIcon(hCurrentInst, lpszFile, 0);

    if (hicon == NULL)

        TextOut(hdc, pt.x, pt.y, "No icons found.", 15);

    else if (hicon == (HICON) 1)

        TextOut(hdc, pt.x, pt.y,

            "File must be .EXE, .ICO, or .DLL.", 33);

    else

        DrawIcon(hdc, pt.x, pt.y, hicon);

}

DragFinish((HANDLE) wParam);


 Shell Library Reference

The following functions, interfaces, messages, and structures are associated with shell features.


 Shell Library Functions

The following functions are used to implement shell features.

DragAcceptFiles
DragFinish
DragQueryFile
DragQueryPoint
ExtractAssociatedIcon
ExtractIcon
FindExecutable
ShellAbout
ShellExecute
ShellExecuteEx


 Shell Library Interfaces

The following interfaces are used to implement shell features.

IContextMenu
ICopyHook
IExtractIcon
IShellPropSheetExt
IShellExtInit
IShellLink
IShellFolder
IEnumIDList


 Shell Library Messages

The following message is used to implement shell features.

WM_DROPFILES


 Shell Library Structures

The following structure is used to implement shell features.

SHELLEXECUTEINFO


 About Windows 95 Shell Extensions

Applications can extend the shell of the Microsoft Windows 95 operating system in a number of ways. A shell extension enhances the shell by providing additional ways to manipulate file objects, by simplifying the task of browsing through the file system and networks, or by giving the user easier access to tools that manipulate objects in the file system. For example, a shell extension can assign an icon to each file or add commands to the context menu and file menu for a file.

Windows 95 supports the following types of shell extensions:

•	Context menu handlers: These add items to the context menu for a particular file object. (The context menu is displayed when the user clicks a file object with the alternate mouse button.)

•	Drag-and-drop handlers: These are context menu handlers that the system calls when the user drops an object after dragging it to a new position.

•	Icon handlers: These typically add instance-specific icons for file objects. They can also be used to add icons for all files belonging to the same class.

•	Property-sheet handlers: These add pages to the property sheet dialog box that the shell displays for a file object. The pages are specific to a class of files or a particular file object.

•	Copy-hook handlers: These are called when a folder object is about to be copied, moved, deleted, or renamed. The handler can either allow or prevent the operation.

The design of a shell extension is based on the Component Object Model in Object Linking and Embedding (OLE). The shell accesses an object through interfaces. An application implements the interfaces in a shell extension dynamic-link library (DLL), which is similar to an In-Process Server DLL in OLE.

For more information, see "Extending the Windows 95 Shell" in the Windows 95 Guide to Programming.


 Windows 95 Shell Extensions on Windows NT

Applications that employ Windows 95 shell-extension handlers (icon handlers, property-page handlers, context-menu handlers, copy hooks, drag-and-drop handlers, and other such DLL-based shell extension classes) can run on the next release of Windows NT with the new shell. To do so, you must take one additional step while registering during setup. This topic describes how to install such applications on Windows NT.

Because shell extensions handlers run in a system process, namely the shell process, Windows NT administrators require control over which shell handlers are allowed to run. When the new shell is available on Windows NT, administrators will have control over which shell handlers can run in much the same way they can now control which device drivers can run.

For the Windows NT shell to recognize and run a shell-extension handler, the handler's CLSID must be listed in the Registry Editor under a new registry key (as well as being registered in the typical way as specified for Windows 95). This registry key contains a list of the handlers that are approved for the shell to run. By default, this key's access control permissions allow only someone with administrator privileges to modify the list.

The CLSID for the extension must be registered at the following location:

HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Shell Extensions\Approved

To register the extension, a "named value" should be added to the "Approved" key. The name of the value must be the string form of the CLSID as obtained from the StringFromCLSID() function, which is used elsewhere in the registry. The value itself should be the ProgID. The ProgID is stored here simply to make inspection of the registry easier, as it is easier to decipher than a CLSID. The Windows NT shell does not look at this value, however, only at the presence or absence of the CLSID.

Your setup application may or may not be able to write to this key, depending on the privileges of the person installing the application. The setup application should attempt to open the key described above, requesting the KEY_SET_VALUE permission. If it succeeds, the new CLSID can be added to fully register the corresponding shell extension. If the request fails with a security violation, then the person installing the application does not have permission to register new shell extensions. In this case, the setup application might warn the user that some application features will not be available unless an administrator turns them on (by installing the application, or by writing the registry keys directly). Or, if the shell extension is crucial to the application's functioning, the setup application might cause the installation to fail completely, notifying the user that the program must be installed by an administrator.

When setting up on Windows 95, it is not necessary to write the CLSID to this key, although writing it is harmless. Note, however, that the key may not exist in a Windows 95 installation, so that if your setup application does attempt to open the key, it may fail.

The following sample code details this process. Full error handling has been omitted.

#include <windows.h>

#include <string.h>

void main(void)

{

     //

     // First, attempt to open the registry key where approved extensions are

     // listed. Note the extra slashes within the second parameter (the

     // registry path string).

     //

     long err;

     HKEY hkApproved;

     err = RegOpenKeyEx(

               HKEY_LOCAL_MACHINE,

"Software\\Microsoft\\Windows\\CurrentVersion\\Shell Extensions\\Approved",

               0,

               KEY_SET_VALUE,

               &hkApproved);

     if (err == ERROR_ACCESS_DENIED)

     {

          //

          // The user does not have permissions to add a new value to this key. In this

          // case, a reasonable action would be to warn the user that some

          // application features will not be available unless an administrator

          // installs the application. If the shell extension is central to the

          // functioning of the application, tell the user that the install

          // can only be performed by an administrator, and stop the install.

          //

     }

     else if (err == ERROR_FILE_NOT_FOUND)

     {

          //

          // The key does not exist. This should only happen if setup is running

          // on Windows 95 instead of Windows NT, or if you are installing on an older

          // version of either operating system that does not have the Windows 95-style UI.

          //

     }

     else if (err != ERROR_SUCCESS)

     {

          //

          // some other problem...

          //

     }

     else

     {

          //

          // The open of the key succeeded. Now register the new shell extension

          // under this key. This requires having the ProgID and string form of the

          // CLSID handy.

          //

          //

          // Assume that lpstrProgID contains our ProgID string.

          //

            LPSTR lpstrProgID = "My Bogus Class";

          //

          // Assume that clsidExtension contains the CLSID struct. The code below

          // creates a string form this CLSID. If  a string version of

          // the CLSID is already handy, skip this code.

          //

          CLSID clsidExtension = {0x11111111, 0x1111, 0x1111, 0x11, 0x11,

                                  0x11, 0x11, 0x11, 0x11, 0x11, 0x11};

          HRESULT hr;

          LPOLESTR lpolestrCLSID;

          CHAR rgchCLSID[40];

          CoInitialize(NULL);

          hr = StringFromCLSID(clsidExtension, &lpolestrCLSID);

          //

          // StringFromCLSID returns a Unicode string, so convert to ANSI for

          // calling the registry. Note that on Windows NT you can call the Unicode

          // version of the registry API instead.

          //

          WideCharToMultiByte(CP_ACP,     0, lpolestrCLSID, -1, rgchCLSID, 40,

                                    NULL, NULL);

          CoTaskMemFree(lpolestrCLSID);

          CoUninitialize();

          //

          // Now add the new value to the registry.

          // Note that each new shell extension CLSID must be registered here.

          //

          err = RegSetValueEx(

                    hkApproved,

                    rgchCLSID,

                    0,

                    REG_SZ,

                    (const BYTE *)lpstrProgID,

                    strlen(lpstrProgID));

          //

          // Finally, close the key.

          //

          err = RegCloseKey(hkApproved);

     }

}


 Bitmaps

A bitmap is a powerful graphics object used to create, manipulate (scale, scroll, rotate, and paint), and store images as files on a disk.


 About Bitmaps

A bitmap is one of seven objects that can be selected into a device context. The other six objects are the pen, brush, font, region, logical palette, and path. (For more information about device contexts and related objects, see Device Contexts.)

In the Microsoft® Win32® application programming interface (API), Control Panel applications are examples of applications that use bitmaps. When a user selects wallpaper for the desktop, the user actually selects a bitmap, which Windows uses to paint the desktop background.

Windows creates this pattern by repeatedly drawing a 32- by 32-pixel pattern on the desktop. This pattern is stored as a bitmap in the file REDBRICK.BMP.

From the user's point of view, a bitmap is a rectangle of pixels that form a visual image. However, from the developer's perspective, a bitmap is a collection of structures that specify or contain the following elements:

•	A header that describes the resolution of the device on which the rectangle of pixels was created, the dimensions of the rectangle, the size of the array of bits, and so on.

•	A logical palette.

•	An array of bits that defines the relationship between pixels in the bitmapped image and entries in the logical palette.

The following illustration shows the developer's perspective of the bitmap found in the file REDBRICK.BMP. It shows a palette array, a 32- by 32-pixel rectangle, and the index array that maps colors from the palette to pixels in the rectangle.

In the preceding example, the rectangle of pixels was created on a VGA display device using a palette of 16 colors. A 16-color palette requires 4-bit indices; therefore, the array that maps palette colors to pixel colors is composed of 4-bit indices as well. (For more information about logical color-palettes, see Colors.)

Note that in the above bitmap, Windows maps indices to pixels beginning with the bottom scan line of the rectangular region and ending with the top scan line. (A scan line is a single row of adjacent pixels on a video display.) For example, the first row of the array (row 0) corresponds to the bottom row of pixels, scan line 31. This is because the above bitmap is a "bottom-up" device-independent bitmap (DIB), a common type of bitmap. In "top-down" DIBs and in device-dependent bitmaps (DDBs), Windows maps indices to pixels beginning with the top scan line.


 Bitmap Types

There are two types of bitmaps: device-dependent (DDBs) and device-independent (DIBs). DDBs were common in early (pre-3.0) versions of Windows. In fact, they were the only bitmaps available to developers. However, as display technology improved and as the variety of display devices increased among Windows users, certain inherent problems surfaced. For example, there was no method of storing (or retrieving) the resolution of the display type on which a bitmap was created, so a drawing application could not quickly determine whether a bitmap was suitable for the type of video display device on which the application was running. To solve this problem, Microsoft created DIBs.


 Device-Independent Bitmaps

A DIB contains the following color and dimension information:

•	The color format of the device on which the rectangular image was created.

•	The resolution of the device on which the rectangular image was created.

•	The palette for the device on which the image was created.

•	An array of bits that maps red, green, blue (RGB) triplets to pixels in the rectangular image.

•	A data-compression identifier that indicates the data compression scheme (if any) used to reduce the size of the array of bits.

This information is stored in a BITMAPINFO structure consisting of a BITMAPINFOHEADER structure followed by two or more RGBQUAD structures. The BITMAPINFOHEADER specifies the dimensions of the pixel rectangle, describes the device's color technology, and identifies the compression schemes used to reduce the bitmap's size. The RGBQUAD structures identify the colors that appear in the pixel rectangle.

There are two varieties of DIB: "bottom-up" DIBs, in which the origin lies at the lower left corner, and "top-down" DIBs, in which the origin lies at the upper left corner. If the height of a DIB, as indicated by the biHeight member of the BITMAPINFOHEADER structure, is a positive value, it is a bottom-up DIB; if the height is a negative value, it is a top-down DIB. Top-down DIBs cannot be compressed.

The color format is specified in terms of a count of color planes and color bits. The count of color planes is always 1; the count of color bits is 1 for monochrome bitmaps, 4 for VGA bitmaps, and 8, 16, 24, or 32 for bitmaps on other color devices. An application retrieves the number of color bits a particular display (or printer) uses by calling the GetDeviceCaps function, specifying BITSPIXEL as the second argument.

The resolution of a display device is specified in pixels per meter. An application can retrieve the horizontal resolution for a video display, or printer, by following a three-step process:

1.	Call the GetDeviceCaps function, specifying HORZRES as the second argument.

2.	Call GetDeviceCaps a second time, specifying HORZSIZE as the second argument.

3.	Divide the first return value by the second return value.

The application can retrieve the vertical resolution by using the same three-step process with different parameters: VERTRES in place of HORZRES, and VERTSIZE in place of HORZSIZE.

The palette is represented by an array of RGBQUAD structures that specify the red, green, and blue intensity components for each color in a display device's color palette. Each color index in the palette array maps to a specific pixel in the rectangular region associated with the bitmap. The size of this array, in bits, is equivalent to the width of the rectangle, in pixels, multiplied by the height of the rectangle, in pixels, multiplied by the count of color bits for the device. An application can retrieve the size of the device's palette by calling the GetDeviceCaps function, specifying the NUMCOLORS constant as the second argument.

The Win32 API supports the compression of the palette array for 8-bit-per-pixel and 4-bit-per-pixel bottom-up DIBs. These arrays can be compressed by using the run-length encoding (RLE) scheme. The RLE scheme uses 2-byte values, the first byte specifying the number of consecutive pixels that use a color index and the second byte specifying the index. For more information about bitmap compression, see the description of the BITMAPINFOHEADER structure.

An application can create a DIB from a DDB by initializing the required structures and calling the GetDIBits function. To determine whether a device supports this function, call the GetDeviceCaps function, specifying RC_DI_BITMAP as the RASTERCAPS flag.

An application can use a DIB to set pixels on the display device by calling the SetDIBitsToDevice or the StretchDIBits function. To determine whether a device supports the SetDIBitsToDevice function, call the GetDeviceCaps function, specifying RC_DIBTODEV as the RASTERCAPS flag. Specify RC_STRETCHDIB as the RASTERCAPS flag to determine if the device supports StretchDIBits.

An application that simply needs to display a preexisting DIB can use the SetDIBitsToDevice function. For example, a spreadsheet application can open existing charts and display them in a window by using the SetDIBitsToDevice function. To repeatedly redraw a bitmap in a window, however, the application should use the BitBlt function. For example, a multimedia application that combines animated graphics with sound would benefit from calling the BitBlt function because it executes faster than SetDIBitsToDevice.


 Device-Dependent Bitmaps

Device-dependent bitmaps are supported only for compatibility with applications written for Windows versions earlier than 3.0. A developer writing a new application, or porting an application written for a previous version of Windows to the Win32 platform, should use DIBs.

DDBs are described by using a single structure, the BITMAP structure. The members of this structure specify the width and height of a rectangular region, in pixels; the width of the array that maps entries from the device palette to pixels; and the device's color format, in terms of color planes and bits per pixel. An application can retrieve the color format of a device by calling the GetDeviceCaps function and specifying the appropriate constants.

There are two types of DDBs: discardable and nondiscardable. A discardable DDB is a bitmap that Windows discards if the bitmap is not selected into a DC and if system memory is low. The CreateDiscardableBitmap function creates discardable bitmaps. The CreateBitmap, CreateCompatibleBitmap, and CreateBitmapIndirect functions create nondiscardable bitmaps.

An application can create a DDB from a DIB by initializing the required structures and calling the CreateDIBitmap function. Specifying CBM_INIT in the call to CreateDIBitmap is equivalent to calling the CreateCompatibleBitmap function to create a DDB in the format of the device and then calling the SetDIBits function to translate the DIB bits to the DDB. To determine whether a device supports the SetDIBits function, call the GetDeviceCaps function, specifying RC_DI_BITMAP as the RASTERCAPS flag.


 Bitmaps, Device Contexts, and Drawing Surfaces

A device context (DC) is a data structure defining the graphics objects, their associated attributes, and the graphics modes affecting output on a device. An application creates a DC by calling the CreateDC function; it retrieves a window manager device context by calling the GetDC function.


 The Drawing Surface

Before returning a handle that identifies that DC, the window manager selects a drawing surface into the DC. If the application called the CreateDC function to create a device context for a VGA display, the dimensions of this drawing surface are 640 by 480 pixels. If the application called the GetDC function, the dimensions reflect the size of the client area.

When an application passes the handle returned by CreateDC or GetDC to one of the graphics device interface (GDI) drawing functions, the requested output appears on the drawing surface selected into the device context.


 Compatible Device Contexts

To enable applications to place output in memory rather than sending it to an actual device, the Win32 API provides a special device context for bitmap operations called a compatible device context. A compatible DC enables Windows to treat a portion of memory as a virtual device. It is an array of bits in memory that an application can use temporarily to store the color data for bitmaps created on a normal drawing surface.

An application creates a compatible DC by calling the CreateCompatibleDC function and receives a handle that identifies a normal device context. Windows creates a temporary one-bit placeholder for the array. Before performing drawing operations using the compatible DC handle, the application must increase the size of this array. To do this, the application can call the CreateBitmap, CreateBitmapIndirect, or CreateCompatibleBitmap function to create a bitmap of the appropriate dimensions and then call the SelectObject function to select the bitmap into the DC. After the bitmap is selected into the compatible DC, Windows replaces the single-bit array with an array large enough to store color information for the specified rectangle of pixels.

When an application passes the handle returned by CreateCompatibleDC to one of the GDI drawing functions, the requested output does not appear on a device's drawing surface. Instead, Windows stores the color information for the resultant line, curve, text or region in the array of bits. The application can copy the image stored in memory back onto a drawing surface by calling the BitBlt function, identifying the compatible DC as the source device context and a window or screen DC as the target device context.

When displaying a DIB or a DDB created from a DIB on a palette device, you can improve the speed at which the image is drawn by arranging the logical palette to match the layout of the system palette. To do this, call GetDeviceCaps with the NUMRESERVED value to get the number of reserved colors in the system. Then call GetSystemPaletteEntries and fill in the first and last NUMRESERVED/2 entries of the logical palette with the corresponding system colors. For example, if NUMRESERVED is 20, you would fill in the first and last 10 entries of the logical palette with the system colors. Then fill in the remaining 256 − NUMRESERVED colors of the logical palette (in our example, the remaining 236 colors) with colors from the DIB and set the PC_NOCOLLAPSE flag on each of these colors. For more information about color and palettes, see Colors.


 Bitmap Rotation

Windows provides a function to copy a bitmap into a parallelogram; this function, PlgBlt, performs a bit-block transfer from a rectangle in a source device context into a parallelogram in a destination device context. In order to rotate the bitmap, an application must provide the coordinates, in world units, to be used for the corners of the parallelogram. (For more information about rotation and world units, see Coordinate Spaces and Transformations.)


 Bitmap Scaling

The Win32 API also provides a function to scale a bitmap; this function, StretchBlt, performs a bit-block transfer from a rectangle in a source device context into a rectangle in a destination device context. However, unlike the BitBlt function, which duplicates the source rectangle dimensions in the destination rectangle, StretchBlt allows an application to specify the dimensions of both the source and the destination rectangles. When the destination bitmap is smaller than the source bitmap, Windows combines rows or columns of color data (or both) in the bitmap before rendering the corresponding image on the display device. Windows combines the color data according to the specified stretch mode, which the application defines by calling the SetStretchBltMode function. When the destination bitmap is larger than the source bitmap, Windows scales or magnifies each pixel in the resultant image accordingly.


 Bitmaps as Brushes

The Win32 API provides a number of functions that use the brush currently selected into a device context to perform bitmap operations. For example, the PatBlt function replicates the brush in a rectangular region within a window, and the FloodFill function replicates the brush inside an area in a window bounded by the specified color (unlike PatBlt, FloodFill does fill nonrectangular shapes).

The PatBlt function name (an abbreviation for pattern block transfer) implies that the function simply replicates the brush (or pattern) until it fills a specified rectangle. However, the function is actually much more powerful. Before replicating the brush, it combines the color data for the pattern with the color data for the existing pixels on the video display by using a raster operation (ROP). An ROP is a bitwise operation that is applied to the bits of color data for the replicated brush and the bits of color data for the target rectangle on the display device. There are 256 ROPs in the Win32 API; however, the PatBlt function recognizes only those that require a pattern and a destination (not those that require a source). The following table identifies the five most common ROPs.

ROP	Description
PATCOPY	Copies the pattern to the destination bitmap.
PATINVERT	Combines the destination bitmap with the pattern by using the Boolean OR operator.
DSTINVERT	Inverts the destination bitmap.
BLACKNESS	Turns all output to binary zeroes.
WHITENESS	Turns all output to binary ones.
The FloodFill function replicates the brush within a region bounded by a specified color. However, unlike the PatBlt function, FloodFill does not combine the color data for the brush with the color data for the pixels on the display; it simply sets the color of all pixels within the enclosed region on the display to the color of the brush that is currently selected into the device context.


 Bitmap Storage

Bitmaps should be saved in a file that uses the established Windows format and assigned a name with the three-character .BMP extension. The established Windows format consists of a BITMAPFILEHEADER structure followed by a BITMAPINFOHEADER structure. An array of RGBQUAD structures (also called a color table) follows the BITMAPINFOHEADER structure. The color table is followed by a second array of indexes into the color table (the actual bitmap data).

The Windows format is shown in the following illustration.

The members of the BITMAPFILEHEADER structure identify the file; specify the size of the file, in bytes; and specify the offset from the first byte in the header to the first byte of bitmap data. The members of the BITMAPINFOHEADER structure specify the bitmap's width and height, in pixels; the color format (count of color planes and color bits per pixel) of the display device on which the bitmap was created; whether the bitmap data was compressed before storage and the type of compression used; the number of bytes of bitmap data; the resolution of the display device on which the bitmap was created; and the number of colors represented in the data. The RGBQUAD structures specify the RGB intensity values for each of the colors in the device's palette. The color-index array maps indices values from the RGBQUAD array to pixels in a rectangular region on the display.

The following hexadecimal output shows the contents of the file REDBRICK.BMP.

0000    42 4d 76 02 00 00 00 00  00 00 76 00 00 00 28 00

0010    00 00 20 00 00 00 20 00  00 00 01 00 04 00 00 00

0020    00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00

0030    00 00 00 00 00 00 00 00  00 00 00 00 80 00 00 80

0040    00 00 00 80 80 00 80 00  00 00 80 00 80 00 80 80

0050    00 00 80 80 80 00 c0 c0  c0 00 00 00 ff 00 00 ff

0060    00 00 00 ff ff 00 ff 00  00 00 ff 00 ff 00 ff ff

0070    00 00 ff ff ff 00 00 00  00 00 00 00 00 00 00 00

0080    00 00 00 00 00 00 00 00  00 00 00 00 00 00 09 00

0090    00 00 00 00 00 00 11 11  01 19 11 01 10 10 09 09

00a0    01 09 11 11 01 90 11 01  19 09 09 91 11 10 09 11

00b0    09 11 19 10 90 11 19 01  19 19 10 10 11 10 09 01

00c0    91 10 91 09 10 10 90 99  11 11 11 11 19 00 09 01

00d0    91 01 01 19 00 99 11 10  11 91 99 11 09 90 09 91

00e0    01 11 11 11 91 10 09 19  01 00 11 90 91 10 09 01

00f0    11 99 10 01 11 11 91 11  11 19 10 11 99 10 09 10

0100    01 11 11 11 19 10 11 09  09 10 19 10 10 10 09 01

0110    11 19 00 01 10 19 10 11  11 01 99 01 11 90 09 19

0120    11 91 11 91 01 11 19 10  99 00 01 19 09 10 09 19

0130    10 91 11 01 11 11 91 01  91 19 11 00 99 90 09 01

0140    01 99 19 01 91 10 19 91  91 09 11 99 11 10 09 91

0150    11 10 11 91 99 10 90 11  01 11 11 19 11 90 09 11

0160    00 19 10 11 01 11 99 99  99 99 99 99 99 99 09 99

0170    99 99 99 99 99 99 00 00  00 00 00 00 00 00 00 00

0180    00 00 00 00 00 00 90 00  00 00 00 00 00 00 00 00

0190    00 00 00 00 00 00 99 11  11 11 19 10 19 19 11 09

01a0    10 90 91 90 91 00 91 19  19 09 01 10 09 01 11 11

01b0    91 11 11 11 10 00 91 11  01 19 10 11 10 01 01 11

01c0    90 11 11 11 91 00 99 09  19 10 11 90 09 90 91 01

01d0    19 09 91 11 01 00 90 10  19 11 00 11 11 00 10 11

01e0    01 10 11 19 11 00 90 19  10 91 01 90 19 99 00 11

01f0    91 01 11 01 91 00 99 09  09 01 10 11 91 01 10 91

0200    99 11 10 90 91 00 91 11  00 10 11 01 10 19 19 09

0210    10 00 99 01 01 00 91 01  19 91 19 91 11 09 10 11

0220    00 91 00 10 90 00 99 01  11 10 09 10 10 19 09 01

0230    91 90 11 09 11 00 90 99  11 11 11 90 19 01 19 01

0240    91 01 01 19 09 00 91 10  11 91 99 09 09 90 11 91

0250    01 19 11 11 91 00 91 19  01 00 11 00 91 10 11 01

0260    11 11 10 01 11 00 99 99  99 99 99 99 99 99 99 99

0270    99 99 99 99 99 90

The following table shows the data bytes associated with the structures in a bitmap file.

Structure	Corresponding bytes
BITMAPFILEHEADER	0x00 − 0x0D
BITMAPINFOHEADER	0x0E − 0x31
RGBQUAD array	0x32 − 0x75
Color-index array	0x76 − 0x275


 Using Bitmaps

•	Capturing an image

•	Scaling an image

•	Storing an image


 Capturing an Image

You can use a bitmap to capture an image, and you can store the captured image in memory, display it at a different location in your application's window, or display it in another window.

In some cases, you may want your application to capture images and store them only temporarily. For example, when you scale or "zoom" a picture created in a drawing application, the application must temporarily save the normal view of the image and display the zoomed view. Later, when the user selects the normal view, the application must replace the zoomed image with a copy of the normal view that it temporarily saved.

To store an image temporarily, your application must call CreateCompatibleDC to create a DC that is compatible with the current window DC. After you create a compatible DC, you create a bitmap with the appropriate dimensions by calling the CreateCompatibleBitmap function and then select it into this device context by calling the SelectObject function.

After the compatible device context is created and the appropriate bitmap has been selected into it, you can capture the image. The Win32 API provides the BitBlt function to capture images. This function performs a bit block transfer — that is, it copies data from a source bitmap into a destination bitmap. Because it copies data from bitmaps, you'd expect that two arguments to this function would be bitmap handles; however, this is not the case. Instead, BitBlt receives handles that identify two device contexts and copies the bitmap data from a bitmap selected into the source DC into a bitmap selected into the target DC. In this case, the target DC is the compatible DC, so when BitBlt completes the transfer, the image has been stored in memory. To redisplay the image, call BitBlt a second time, specifying the compatible DC as the source DC and a window (or printer) DC as the target DC.

The following example code, from an application that captures an image of the entire desktop, creates a compatible device context and a bitmap with the appropriate dimensions, selects the bitmap into the compatible DC, and then copies the image using the BitBlt function.

/*

 * 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", NULL, NULL, NULL);

hdcCompatible = CreateCompatibleDC(hdcScreen);

/* Create a compatible bitmap for hdcScreen. */

hbmScreen = CreateCompatibleBitmap(hdcScreen,

                     GetDeviceCaps(hdcScreen, HORZRES),

                     GetDeviceCaps(hdcScreen, VERTRES));

if (hbmScreen == 0)

    errhandler("hbmScreen", hwnd);

/* Select the bitmaps into the compatible DC. */

if (!SelectObject(hdcCompatible, hbmScreen))

    errhandler("Compatible Bitmap Selection", hwnd);

        /* Hide the application window. */

        ShowWindow(hwnd, SW_HIDE);

        /*

         * Copy color data for the entire display into a

         * bitmap that is selected into a compatible DC.

         */

        if (!BitBlt(hdcCompatible,

               0,0,

               bmp.bmWidth, bmp.bmHeight,

               hdcScreen,

               0,0,

               SRCCOPY))

        errhandler("Screen to Compat Blt Failed", hwnd);

        /* Redraw the application window. */

        ShowWindow(hwnd, SW_SHOW);


 Scaling an Image

Some applications scale images — that is, they display zoomed or reduced views of an image. For example, a drawing application may provide a zoom feature that enables the user to view and edit a drawing on a pixel-by-pixel basis.

Applications scale images by calling the StretchBlt function. Like the BitBlt function, StretchBlt copies bitmap data from a bitmap in a source DC into a bitmap in a target DC. However, unlike the BitBlt function, StretchBlt scales the image based on the specified dimensions of the source and target rectangles. If the source rectangle is larger than the target rectangle, the resultant image will appear to have shrunk; if the source rectangle is smaller than the target rectangle, the resultant image will appear to have expanded.

If the target rectangle is smaller than the source rectangle, StretchBlt removes color data from the image according to a specified stretch mode as shown in the following table.

Stretch Mode	Method
BLACKONWHITE	Performs a logical AND operation on the color data for the eliminated pixels and the color data for the remaining pixels.
WHITEONBLACK	Performs a logical OR operation on the color data for the eliminated pixels and the color data for the remaining pixels.
COLORONCOLOR	Eliminates the color data of the deleted pixels completely.
HALFTONE	Approximates the original (source) color data in the destination.
You set the stretch mode by calling the SetStretchBltMode function.

The following example code is taken from an application that displays an image either at its original size or a twice the original size. (This application uses the default stretch mode.)

    hdcScaled = CreateCompatibleDC(hdcScreen);

    hbmScaled = CreateCompatibleBitmap(hdcScreen,

                    GetDeviceCaps(hdcScreen, HORZRES) * 2,

                    GetDeviceCaps(hdcScreen, VERTRES) * 2);

    if (hbmScaled == 0)

        errhandler("hbmScaled", hwnd);

    /* Select the bitmaps into the compatible DC. */

    if (!SelectObject(hdcScaled, hbmScaled))

        errhandler("Scaled Bitmap Selection", hwnd);

case WM_COMMAND:     /* message: command from application menu */

    switch(wParam) {

        case IDM_SCALEX1:

            if (fBlt){

                 fScaled = FALSE;

                 hdcWin = GetDC(hwnd);

                 BitBlt(hdcWin,

                    0,0,

                    bmp.bmWidth, bmp.bmHeight,

                    hdcCompatible,

                    0,0,

                    SRCCOPY);

                 ReleaseDC(hwnd, hdcWin);

            }

            break;

        case IDM_SCALEX2:

            if (fBlt){

                 fScaled = TRUE;

                 StretchBlt(hdcScaled,

                     0, 0,

                     bmp.bmWidth * 2, bmp.bmHeight * 2,

                     hdcCompatible,

                     0, 0,

                     bmp.bmWidth, bmp.bmHeight,

                     SRCCOPY);

                 hdcWin = GetDC(hwnd);

                 BitBlt(hdcWin,

                    0,0,

                    bmp.bmWidth, bmp.bmHeight,

                    hdcScaled,

                    0,0,

                    SRCCOPY);

                 ReleaseDC(hwnd, hdcWin);

            }

            break;


 Storing an Image

Many applications store images permanently as files. For example, drawing applications store pictures, spreadsheet applications store charts, CAD applications store drawings, and so on.

If you are writing an application that will store a bitmapped image in a file, you should use the Windows file format described in Bitmap Storage. In order to store a bitmap in this format, you must initialize a BITMAPINFO structure (consisting of a BITMAPFILEHEADER structure and an array of RGBQUAD structures), as well as an array of palette indices.

The following example code defines a function that allocates memory for and initializes members within a BITMAPINFOHEADER structure.

PBITMAPINFO CreateBitmapInfoStruct(HWND hwnd, HBITMAP hBmp) {

    BITMAP bmp;

    PBITMAPINFO pbmi;

    WORD    cClrBits;

    /* Retrieve the bitmap's color format, width, and height. */

    if (!GetObject(hBmp, sizeof(BITMAP), (LPSTR)&bmp))

        errhandler("GetObject", hwnd);

    /* Convert the color format to a count of bits. */

    cClrBits = (WORD)(bmp.bmPlanes * bmp.bmBitsPixel);

    if (cClrBits == 1)

        cClrBits = 1;

    else if (cClrBits <= 4)

        cClrBits = 4;

    else if (cClrBits <= 8)

        cClrBits = 8;

    else if (cClrBits <= 16)

        cClrBits = 16;

    else if (cClrBits <= 24)

        cClrBits = 24;

    else

        cClrBits = 32;

    /*

     * Allocate memory for the BITMAPINFO structure. (This structure

     * contains a BITMAPINFOHEADER structure and an array of RGBQUAD data

     * structures.)

     */

    if (cClrBits != 24)

         pbmi = (PBITMAPINFO) LocalAlloc(LPTR,

                    sizeof(BITMAPINFOHEADER) +

                    sizeof(RGBQUAD) * (2^cClrBits));

    /*

     * There is no RGBQUAD array for the 24-bit-per-pixel format.

     */

    else

         pbmi = (PBITMAPINFO) LocalAlloc(LPTR,

                    sizeof(BITMAPINFOHEADER));

    /* Initialize the fields in the BITMAPINFO structure. */

    pbmi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);

    pbmi->bmiHeader.biWidth = bmp.bmWidth;

    pbmi->bmiHeader.biHeight = bmp.bmHeight;

    pbmi->bmiHeader.biPlanes = bmp.bmPlanes;

    pbmi->bmiHeader.biBitCount = bmp.bmBitsPixel;

    if (cClrBits < 24)

        pbmi->bmiHeader.biClrUsed = 2^cClrBits;

    /* If the bitmap is not compressed, set the BI_RGB flag. */

    pbmi->bmiHeader.biCompression = BI_RGB;

    /*

     * Compute the number of bytes in the array of color

     * indices and store the result in biSizeImage.

     */

    pbmi->bmiHeader.biSizeImage = (pbmi->bmiHeader.biWidth + 7) /8

                                  * pbmi->bmiHeader.biHeight

                                  * cClrBits;

    /*

     * Set biClrImportant to 0, indicating that all of the

     * device colors are important.

     */

    pbmi->bmiHeader.biClrImportant = 0;

    return pbmi;

}

The following example code defines a function that initializes the remaining structures, retrieves the array of palette indices, opens the file, copies the data, and closes the file.

void CreateBMPFile(HWND hwnd, LPTSTR pszFile, PBITMAPINFO pbi,

                  HBITMAP hBMP, HDC hDC)

 {

    HANDLE hf;                  /* file handle */

    BITMAPFILEHEADER hdr;       /* bitmap file-header */

    PBITMAPINFOHEADER pbih;     /* bitmap info-header */

    LPBYTE lpBits;              /* memory pointer */

    DWORD dwTotal;              /* total count of bytes */

    DWORD cb;                   /* incremental count of bytes */

    BYTE *hp;                   /* byte pointer */

    DWORD dwTmp;

    pbih = (PBITMAPINFOHEADER) pbi;

    lpBits = (LPBYTE) GlobalAlloc(GMEM_FIXED, pbih->biSizeImage);
    if (!lpBits)

         errhandler("GlobalAlloc", hwnd);

    /*

     * Retrieve the color table (RGBQUAD array) and the bits

     * (array of palette indices) from the DIB.

     */

    if (!GetDIBits(hDC, hBMP, 0, (WORD) pbih->biHeight,

                   lpBits, pbi, DIB_RGB_COLORS))

        errhandler("GetDIBits", hwnd);

    /* Create the .BMP file. */

    hf = CreateFile(pszFile,

                   GENERIC_READ | GENERIC_WRITE,

                   (DWORD) 0,

                   (LPSECURITY_ATTRIBUTES) NULL,

                   CREATE_ALWAYS,

                   FILE_ATTRIBUTE_NORMAL,

                   (HANDLE) NULL);

    if (hf == INVALID_HANDLE_VALUE)

        errhandler("CreateFile", hwnd);

    hdr.bfType = 0x4d42;        /* 0x42 = "B" 0x4d = "M" */

    /* Compute the size of the entire file. */

    hdr.bfSize = (DWORD) (sizeof(BITMAPFILEHEADER) +

                 pbih->biSize + pbih->biClrUsed

                 * sizeof(RGBQUAD) + pbih->biSizeImage);

    hdr.bfReserved1 = 0;

    hdr.bfReserved2 = 0;

    /* Compute the offset to the array of color indices. */

    hdr.bfOffBits = (DWORD) sizeof(BITMAPFILEHEADER) +

                    pbih->biSize + pbih->biClrUsed

                    * sizeof (RGBQUAD);

    /* Copy the BITMAPFILEHEADER into the .BMP file. */

    if (!WriteFile(hf, (LPVOID) &hdr, sizeof(BITMAPFILEHEADER),

       (LPDWORD) &dwTmp, (LPOVERLAPPED) NULL))

       errhandler("WriteFile", hwnd);

    /* Copy the BITMAPINFOHEADER and RGBQUAD array into the file. */

    if (!WriteFile(hf, (LPVOID) pbih, sizeof(BITMAPINFOHEADER)

                  + pbih->biClrUsed * sizeof (RGBQUAD),

                  (LPDWORD) &dwTmp, (LPOVERLAPPED) NULL))

       errhandler("WriteFile", hwnd);

    /* Copy the array of color indices into the .BMP file. */

    dwTotal = cb = pbih->biSizeImage;

    hp = lpBits;

    while (cb > MAXWRITE)  {

            if (!WriteFile(hf, (LPSTR) hp, (int) MAXWRITE,

                          (LPDWORD) &dwTmp, (LPOVERLAPPED) NULL))

                errhandler("WriteFile", hwnd);

            cb-= MAXWRITE;

            hp += MAXWRITE;

    }

    if (!WriteFile(hf, (LPSTR) hp, (int) cb,

         (LPDWORD) &dwTmp, (LPOVERLAPPED) NULL))

           errhandler("WriteFile", hwnd);

    /* Close the .BMP file. */

    if (!CloseHandle(hf))

           errhandler("CloseHandle", hwnd);

    /* Free memory. */

    GlobalFree((HGLOBAL)lpBits);
}


 Bitmap Functions

Following are the functions used with bitmaps.

BitBlt
CreateBitmap
CreateBitmapIndirect
CreateCompatibleBitmap
CreateDIBitmap
CreateDIBSection
CreateDiscardableBitmap
ExtFloodFill
FloodFill
GetBitmapBits
GetBitmapDimensionEx
GetDIBColorTable
GetDIBits
GetPixel
GetStretchBltMode
LoadBitmap
MaskBlt
PatBlt
PlgBlt
SetBitmapBits
SetBitmapDimensionEx
SetDIBColorTable
SetDIBits
SetDIBitsToDevice
SetPixel
SetPixelV
SetStretchBltMode
StretchBlt
StretchDIBits

Obsolete or Deleted Functions

GetBitmapDimension
SetBitmapDimension


 Brushes

A brush is a graphics tool that a Microsoft® Win32®-based application uses to paint the interior of polygons, ellipses, and paths. Drawing applications use brushes to paint shapes; word processing applications use brushes to paint rules; computer-aided design (CAD) applications use brushes to paint the interiors of cross-section views; and spreadsheet applications use brushes to paint the sections of pie charts and the bars in bar graphs.


 About Brushes

There are two types of brushes: logical and physical. A logical brush is a description of the ideal bitmap that an application would use to paint shapes. A physical brush is the actual bitmap that a device driver creates based on an application's logical-brush definition. For more information about bitmaps, see Bitmaps.

When an application calls one of the functions that create a brush, it retrieves a handle that identifies a logical brush. When the application passes this handle to the SelectObject function, the device driver for the corresponding display or printer creates the physical brush.


 Brush Origin

When an application calls a drawing function to paint a shape, Windows positions a brush at the start of the paint operation and maps a pixel in the brush bitmap to the window origin of the client area. (The window origin is the upper-left corner of the  window's client area.) The coordinates of the pixel that Windows maps are called the brush origin. The default brush origin is located in the upper-left corner of the brush bitmap, at the coordinates (0,0). Windows then copies the brush across the client area, forming a pattern that is as tall as the bitmap. The copy operation continues, row by row, until the entire client area is filled. However, the brush pattern is visible only within the boundaries of the specified shape.

There are instances when the default brush origin should not be used. For example, it may be necessary for an application to use the same brush to paint the backgrounds of its parent and child windows and blend a child window's background with that of the parent window. To do this, the application should reset the brush origin by calling the SetBrushOrgEx function and shifting the origin the required number of pixels. (An application can retrieve the current brush origin by calling the GetBrushOrgEx function.)

The following illustration shows a five-pointed star filled by using an application-defined brush. The illustration shows a zoomed image of the brush, as well as the location to which it was mapped at the beginning of the paint operation.


 Logical Brush Types

There are four types of logical brushes (solid, stock, hatch, and pattern) as shown in the following illustration.

The stock and hatch types each have several predefined brushes, as described in Hatch Brush.


 Solid Brush

A solid brush is a logical brush that contains 64 pixels of the same color. An application can create a solid logical brush by calling the CreateSolidBrush function, specifying the color of the brush required. After creating the solid brush, the application can select it into its device context and use it to paint filled shapes.


 Stock Brush

There are seven predefined logical stock brushes maintained by the graphics device interface (GDI). There are also 21 predefined logical stock brushes maintained by the window management interface (USER).

The following rectangles were painted by using the seven predefined stock brushes.

An application can retrieve a handle identifying one of the seven stock brushes by calling the GetStockObject function, specifying the brush type.

The 21 stock brushes maintained by the window management interface correspond to the colors of window elements such as menus, scroll bars, and buttons. An application can obtain a handle identifying one of these brushes by calling the GetSysColorBrush function and specifying a system-color value. An application can retrieve the color corresponding to a particular window element by calling the GetSysColor function. An application can set the color corresponding to a window element by calling the SetSysColors function.


 Hatch Brush

There are six predefined logical hatch brushes maintained by GDI. The following rectangles were painted by using the six predefined hatch brushes.

An application can create a hatch brush by calling the CreateHatchBrush function, specifying one of the six hatch styles.


 Pattern Brush

A pattern (or custom) brush is created from an application-defined bitmap or device-independent bitmap (DIB). The following rectangles were painted by using different pattern brushes.

To create a logical pattern brush, an application must first create a bitmap. After creating the bitmap, the application can create the logical pattern brush by calling the CreatePatternBrush or CreateDIBPatternBrushPt function, supplying a handle that identifies the bitmap (or DIB). The brushes that appear in the preceding illustration were created from monochrome bitmaps. For a description of bitmaps, DIBs, and the functions that create them, see Bitmaps.


 Using Brushes

You can use a brush to paint the interior of virtually any shape by using a GDI function. This includes the interiors of rectangles, ellipses, polygons, and paths. Depending on the requirements of your application, you can use a solid brush of a specified color, a stock brush, a hatch brush, or a pattern brush.

This section contains code samples that demonstrate the creation of a custom brush dialog box. The dialog box contains a grid that represents the bitmap Windows uses as a brush. A user can use this grid to create a pattern-brush bitmap and then view the custom pattern by clicking the Test Pattern button.

The following illustration shows a pattern created by using the Custom Brush dialog box.

To display a dialog box, you must first create a dialog box template. The following dialog box template defines the Custom Brush dialog box.

CustBrush DIALOG 6, 18, 160, 118

STYLE WS_DLGFRAME | WS_POPUP | WS_VISIBLE | WS_CAPTION

CAPTION "Custom Brush"

FONT 8, "MS Sans Serif"

BEGIN

    CONTROL         "", IDD_GRID, "Static", SS_BLACKFRAME |

                    WS_CHILD, 3, 2, 83, 79

    CONTROL         "", IDD_RECT, "Static", SS_BLACKFRAME |

                    WS_CHILD, 96, 11, 57, 28

    PUSHBUTTON      "Test Pattern", IDD_PAINTRECT, 96, 47, 57, 14

    PUSHBUTTON      "OK", IDD_OK, 29, 98, 40, 14

    PUSHBUTTON      "Cancel", IDD_CANCEL, 92, 98, 40, 14

END

The Custom Brush dialog box contains five controls: a bitmap-grid window, a pattern-viewing window, and three push buttons, labeled Test Pattern, OK and Cancel. The Test Pattern push button enables the user to view the pattern. The dialog box template specifies the overall dimensions of the dialog box window, assigns a value to each control, specifies the location of each control, and so forth. (For more information about creating dialog box templates, see Dialog Boxes.)

The control values in the dialog box template are constants that have been defined as follows in the application's header file.

#define IDD_GRID  120

#define IDD_RECT  121

#define IDD_PAINTRECT 122

#define IDD_OK  123

#define IDD_CANCEL 124

After you create a dialog box template and include it in the application's resource-definition file, you must write a dialog procedure. This procedure processes messages that Windows sends to the dialog box. The following excerpt from an application's source code shows the dialog box procedure for the Custom Brush dialog box and the two application-defined functions it calls.

int APIENTRY BrushDlgProc(HWND hdlg, WORD message, LONG wParam,

                         LONG lParam)

{

    static HWND hwndGrid;       /* grid-window control     */

    static HWND hwndBrush;      /* pattern-brush control   */

    static RECT rctGrid;        /* grid-window rectangle   */

    static RECT rctBrush;       /* pattern-brush rectangle */

    static UINT bBrushBits[8];  /* bitmap bits             */

    static RECT rect[64];       /* grid-cell array         */

    static HBITMAP hbm;         /* bitmap handle           */

    HBRUSH hbrush;              /* current brush           */

    HBRUSH hbrushOld;           /* default brush           */

    HRGN hrgnCell;              /* test-region handle      */

    HDC hdc;                    /* DC handle               */

    int x, y, deltaX, deltaY;   /* drawing coordinates     */

    POINTS ptlHit;              /* mouse coordinates       */

    int i;                      /* count variable          */

    switch (message)

        {

        case WM_INITDIALOG:

            /*

             * Retrieve a window handle for the grid-window and

             * pattern-brush controls

             */

            hwndGrid = GetDlgItem(hdlg, IDD_GRID);

            hwndBrush = GetDlgItem(hdlg, IDD_RECT);

            /* Initialize the array of bits that defines the

             * custom brush pattern with the value 1 to produce a

             * solid white brush).

             */

            for (i=0; i<8; i++)

                bBrushBits[i] = 0xFF;

            /*

             * Retrieve dimensions for the grid-window and pattern-brush

             * controls.

             */

            GetClientRect(hwndGrid, &rctGrid);

            GetClientRect(hwndBrush, &rctBrush);

            /* Determine the width and height of a single cell. */

            deltaX = (rctGrid.right - rctGrid.left)/8;

            deltaY = (rctGrid.bottom - rctGrid.top)/8;

            /* Initialize the array of cell rectangles. */

            for (y=rctGrid.top, i=0; y < rctGrid.bottom; y += deltaY){

                for (x=rctGrid.left; x < (rctGrid.right - 8) && i < 64;

                        x += deltaX, i++) {

                    rect[i].left = x; rect[i].top = y;

                    rect[i].right = x + deltaX;

                    rect[i].bottom = y + deltaY;

                }

            }

            return FALSE;

        case WM_PAINT:

            /* Draw the grid. */

            hdc = GetDC(hwndGrid);

            for (i=rctGrid.left; i<rctGrid.right;

                 i+=(rctGrid.right - rctGrid.left)/8){

                 MoveToEx(hdc, i, rctGrid.top, NULL);

                 LineTo(hdc, i, rctGrid.bottom);

            }

            for (i=rctGrid.top; i<rctGrid.bottom;

                 i+=(rctGrid.bottom - rctGrid.top)/8){

                 MoveToEx(hdc, rctGrid.left, i, NULL);

                 LineTo(hdc, rctGrid.right, i);

            }

            ReleaseDC(hwndGrid, hdc);

            return FALSE;

        case WM_LBUTTONDOWN:

            /* Store the mouse coordinates in a POINT structure. */

            ptlHit = MAKEPOINTS((POINTS FAR *)lParam);

            /*

             * Create a rectangular region with dimensions and

             * coordinates that correspond to those of the grid

             * window.

             */

            hrgnCell = CreateRectRgn(rctGrid.left, rctGrid.top,

                        rctGrid.right, rctGrid.bottom);

            /* Retrieve a window DC for the grid window. */

            hdc = GetDC(hwndGrid);

            /* Select the region into the DC. */

            SelectObject(hdc, hrgnCell);

            /* Test for a button click in the grid-window rectangle. */

            if (PtInRegion(hrgnCell, ptlHit.x, ptlHit.y)){

                /*

                 * A button click occurred in the grid-window rectangle;

                 * isolate the cell in which it occurred.

                 */

                for(i=0; i<64; i++){

                    DeleteObject(hrgnCell);

                    hrgnCell = CreateRectRgn(rect[i].left, rect[i].top,

                               rect[i].right, rect[i].bottom);

                    if (PtInRegion(hrgnCell, ptlHit.x, ptlHit.y)){

                         InvertRgn(hdc, hrgnCell);

                         /* Set the appropriate brush bits. */

                         if (i % 8 == 0)

                            bBrushBits[i/8] = bBrushBits[i/8] ^ 0x80;

                         else if (i % 8 == 1)

                            bBrushBits[i/8] = bBrushBits[i/8] ^ 0x40;

                         else if (i % 8 == 2)

                            bBrushBits[i/8] = bBrushBits[i/8] ^ 0x20;

                         else if (i % 8 == 3)

                            bBrushBits[i/8] = bBrushBits[i/8] ^ 0x10;

                         else if (i % 8 == 4)

                            bBrushBits[i/8] = bBrushBits[i/8] ^ 0x08;

                         else if (i % 8 == 5)

                            bBrushBits[i/8] = bBrushBits[i/8] ^ 0x04;

                         else if (i % 8 == 6)

                            bBrushBits[i/8] = bBrushBits[i/8] ^ 0x02;

                         else if (i % 8 == 7)

                            bBrushBits[i/8] = bBrushBits[i/8] ^ 0x01;

                      /* Exit the "for" loop after the bit is set. */

                         break;

                    } /* end if */

                } /* end for */

            } /* end if */

            /* Release the DC for the control. */

            ReleaseDC(hwndGrid, hdc);

            return TRUE;

        case WM_COMMAND:

            switch (wParam){

               case IDD_PAINTRECT:

                    hdc = GetDC(hwndBrush);

                    /* Create a monochrome bitmap. */

                    hbm = CreateBitmap(8, 8, 1, 1,

                          (LPBYTE)bBrushBits);

                    /* Select the custom brush into the DC.      */

                    hbrush = CreatePatternBrush(hbm);

                    hbrushOld = SelectObject(hdc, hbrush);

                    /* Use the custom brush to fill the rectangle. */

                    Rectangle(hdc, rctBrush.left, rctBrush.top,

                              rctBrush.right, rctBrush.bottom);

                    /* Clean up memory. */

                    SelectObject(hdc, hbrushOld);

                    DeleteObject(hbrush);

                    DeleteObject(hbm);

                    ReleaseDC(hwndBrush, hdc);

                  return TRUE;

                case IDD_OK:

                case IDD_CANCEL:

                    EndDialog(hdlg, TRUE);

                    return TRUE;

            } /* end switch */

            break;

        default:

            return FALSE;

        }

}

int GetStrLngth(LPTSTR cArray)

{

    int i = 0;

    while (cArray[i++] != 0);

    return i-1;

}

DWORD RetrieveWidth(LPTSTR cArray, int iLength)

{

    int i, iTmp;

    double dVal, dCount;

    dVal = 0.0;

    dCount = (double)(iLength-1);

    for (i=0; i<iLength; i++){

        iTmp = cArray[i] - 0x30;

        dVal = dVal + (((double)iTmp) * pow(10.0, dCount--));

    }

    return (DWORD)dVal;

}

The dialog box procedure for the Custom Brush dialog box processes four messages, as described in the following table.

Message	Action
WM_INITDIALOG	Retrieves a window handle and dimensions for the grid-window and pattern-brush controls, computes the dimensions of a single cell in the grid-window control, and initializes an array of grid-cell coordinates.
WM_PAINT	Draws the grid pattern in the grid-window control.
WM_LBUTTONDOWN	Determines whether the cursor is within the grid-window control when the user presses the left mouse button. If so, the dialog box procedure inverts the appropriate grid cell and records the state of that cell in an array of bits that is used to create the bitmap for the custom brush.
WM_COMMAND	Processes input for the three push button controls. If the user presses the Test Pattern button, the dialog box procedure paints the Test Pattern control with the new custom brush pattern. If the user presses the OK or Cancel button, the dialog box procedure performs actions accordingly.
For more information about messages and message processing, see Messages and Message Queues.

After you write the dialog box procedure, export it in the module-definition file, include the function definition for the procedure in the application's header file, and then call the dialog box procedure at the appropriate point in the application.

The following excerpt from the module-definition file shows how the dialog box procedure for the Custom Brush is exported.

; Export all functions that are called by a Windows routine.

EXPORTS

        MainWndProc   @1   ; name of window processing function

        BrushDlgProc  @2   ; name of custom-brush processing function

The following excerpt from the application's header file shows the function definition for the dialog box procedure and the two functions it calls.

int APIENTRY BrushDlgProc(HWND hdlg, WORD message, LONG wParam,

             LONG lParam);

int GetStrLngth(LPTSTR cArray);

DWORD RetrieveWidth(LPTSTR cArray, int iLength);

Finally, the following code shows how the dialog box procedure is called from the application's source-code file. In this example, the dialog box procedure is called when the user chooses an option from the application's menu.

switch (message) {

    case WM_CREATE:

        break;

    case WM_COMMAND:           /* message: command from application menu */

        switch(wParam) {

            case IDM_CUSTOMBRUSH:

                    DialogBox((HANDLE)GetModuleHandle(NULL),

                    (LPTSTR)"CustBrush", hWnd,

                    (DLGPROC)BrushDlgProc);

                break;


 Brush Functions

Following are the functions that can be used with brushes.

CreateBrushIndirect
CreateDIBPatternBrush
CreateDIBPatternBrushPt
CreateHatchBrush
CreatePatternBrush
CreateSolidBrush
GetBrushOrgEx
GetSysColorBrush
SetBrushOrgEx

Obsolete or Deleted Functions

FixBrushOrgEx


 Clipping

Clipping is the process of limiting output to a region or path within the client area of an application's window.


 About Clipping

Clipping is used by Microsoft® Win32®-based applications in a variety of ways. Word processing and spreadsheet applications clip keyboard input to keep it from appearing in the margins of a page or spreadsheet. Computer-aided design (CAD) and drawing applications clip graphics output to keep it from overwriting the edges of a drawing or picture.

A clipping region is a region with edges that are either straight lines or curves. A clip path is a region with edges that are straight lines, Bézier curves, or combinations of both. For more information about regions, see Regions. For more information about paths, see Paths.


 Clipping Regions

A clipping region is one of the graphic objects that an application can select into a device context (DC). It is typically rectangular. Some device contexts provide a predefined or default clipping region while others do not. For example, if you obtain a device context handle from the BeginPaint function, the DC contains a predefined rectangular clipping region that corresponds to the invalid rectangle that requires repainting. However, if you obtain a device context handle by calling the CreateDC or GetDC function, the DC does not contain a default clipping region. For more information about device contexts returned by the BeginPaint function, see Painting and Drawing. For more information about device contexts returned by the CreateDC and GetDC functions, see Device Contexts.

Applications can perform a variety of operations on clipping regions. Some of these operations require a handle identifying the region and some do not. For example, an application can perform the following operations directly on a device context's clipping region:

•	Determine whether graphics output appears within the region's borders by passing coordinates of the corresponding line, arc, bitmap, text, or filled shape to the PtVisible function.

•	Determine whether part of the client area intersects a region by calling the RectVisible function.

•	Move the existing region by a specified offset by calling the OffsetClipRgn function.

•	Exclude a rectangular part of the client area from the current clipping region by calling the ExcludeClipRect function.

•	Combine a rectangular part of the client area with the current clipping region by calling the IntersectClipRect function.

After obtaining a handle identifying the clipping region, an application can perform any operation that is common with regions; for example:

•	Combining a copy of the current clipping region with a second region by calling the CombineRgn function.

•	Compare a copy of the current clipping region to a second region by calling the EqualRgn function.

•	Determine whether a point lies within the interior of a copy of the current clipping region by calling the PtInRegion function.


 Clip Paths

Like a clipping region, a clip path is another graphics object that an application can select into a device context. Unlike a clipping region, a clip path is always created by an application and it is used for clipping to one or more irregular shapes. For example, an application can use the lines and curves that form the outlines of characters in a string of text to define a clip path.

To create a clip path, it's first necessary to create a path that describes the required irregular shape. Paths are created by calling the appropriate graphics device interface (GDI) drawing functions after calling the BeginPath function and before calling the EndPath function. This collection of functions is called a path bracket. For more information about paths and path brackets, see Paths.

After the path is created, it can be converted to a clip path by calling the SelectClipPath function, identifying a device context, and specifying a usage mode. The usage mode determines how Windows combines the new clip path with the device context's original clipping region. The following table describes the usage modes.

Mode	Description
RGN_AND	The clip path includes the intersection (overlapping areas) of the device context's clipping region and the current path.
RGN_COPY	The clip path is the current path.
RGN_DIFF	The clip path includes the device context's clipping region with any intersecting parts of the current path excluded.
RGN_OR	The clip path includes the union (combined areas) of the device context's clipping region and the current path.
RGN_XOR	The clip path includes the union of the device context's clipping region and the current path but excludes the intersection.


 Using Clipping

This section contains example code that shows how to generate a clip path consisting of a character string. The example creates a logical font and uses it to draw a string within a clip path, then fills the path by drawing horizontal and vertical lines.

/*

 * DoClipPat - Draws a clip path using the specified string

 * Return value - TRUE if successful; FALSE otherwise

 * lplf - address of a LOGFONT structure that defines the font to

 *        use to draw the clip path

 * lpsz - address of a string to use for the clip path

 */

BOOL DoClipPath(LPLOGFONT lplf, LPSTR lpsz)

{

    LOGFONT lf;         /* logical font structure                    */

    HFONT hfont;        /* new logical font handle                   */

    HFONT hfontOld;     /* original logical font handle              */

    HDC hdc;            /* display DC handle                         */

    int nXStart, nYStart; /* drawing coordinates                     */

    RECT rc;            /* rectangle structure for painting window   */

    SIZE sz;            /* size structure that receives text extents */

    int nStrLen;        /* length of the string                      */

    int i;              /* loop counter                              */

    /* Retrieve a cached DC for the window. */

    hdc = GetDC(hwnd);

    /* Erase the current window contents. */

    GetClientRect(hwnd, &rc);

    FillRect(hdc, &rc, GetStockObject(WHITE_BRUSH));

    /*

     * Use the specified font to create a logical font and select it

     * into the DC.

     */

    hfont = CreateFontIndirect(lplf);

    if (hfont == NULL)

        return FALSE;

    hfontOld = SelectObject(hdc, hfont);

    /* Create a clip path. */

    nStrLen = lstrlen(lpsz);

    BeginPath(hdc);

        TextOut(hdc, nXStart, nYStart, lpsz, nStrLen);

    EndPath(hdc);

    SelectClipPath(hdc, RGN_DIFF);

    /*

     * Retrieve the dimensions of the rectangle surrounding

     * the text.

     */

    GetTextExtentPoint32(hdc, lpsz, nStrLen, &sz);

    /* Draw horizontal lines through the clip path. */

    for (i = nYStart + 1; i < (nYStart + sz.cy); i += 3) {

       MoveToEx(hdc, nXStart, i, (LPPOINT) NULL);

       LineTo(hdc, (nXStart + sz.cx), i);

    }

    /* Draw vertical lines through the clip path. */

    for (i = nXStart + 1; i < (nXStart + sz.cx); i += 3){

       MoveToEx(hdc, i, nYStart, (LPPOINT) NULL);

       LineTo(hdc, i, (nYStart + sz.cy));

    }

    /* Select the original font into the DC and release the DC. */

    SelectObject(hdc, hfontOld);

    DeleteObject(hfont);

    ReleaseDC(hwnd, hdc);

    return TRUE;

}

For an example that demonstrates how an application creates a rectangular clipping region, see Regions.


 Clipping Functions

Following are the functions that can be used with clipping.

ExcludeClipRect
ExtSelectClipRgn
GetClipBox
GetClipRgn
GetMetaRgn
IntersectClipRect
OffsetClipRgn
PtVisible
RectVisible
SelectClipPath
SelectClipRgn
SetMetaRgn


 Colors

Color is an important element in the pictures and images generated by Windows-based applications. This overview describes how Windows-based applications can manage and use colors with pens, brushes, text, or bitmaps.


 About Colors

Color can be used to communicate ideas, show relationships between items, and improve the appeal and quality of output. Windows enables applications to discover the color capabilities of given devices and to choose from the available colors those that best suit their needs.

Although not described in this overview, image color matching is an important feature of color management that helps ensure that color images look the same whether displayed on screen or printed on paper. For more information, see Image Color Matching.


 Color Basics

The color capabilities of devices, such as displays and printers, can range from monochrome to thousands of colors. Because an application may need to generate output for devices throughout this range, it should be prepared be prepared to handle varying color capabilities.

An application can discover the number of colors available for a given device by using the GetDeviceCaps function to retrieve the NUMCOLORS value. This value specifies the count of colors available for use by the application. Usually, this count corresponds to a physical property of the output device, such as the number of inks in the printer or the number of distinct color signals the display adapter can transmit to the monitor.

Although the NUMCOLORS value specifies the count of colors, it does not identify what the available colors are. An application can discover what colors are available by enumerating all pens having the PS_SOLID type. Because the device driver that supports a given device usually has a full range of solid pens and because Windows requires that solid pens have only colors that the device can generate, enumerating these pens is often equivalent to enumerating the colors. An application can enumerate the pens by using the EnumObjects function.


 Color Values

By default, Windows defines color as a combination of three primary colors — red, green, and blue. Windows identifies a color by giving it a color value (sometimes called an RGB triplet), which consists of three 8-bit values specifying the intensities of its color components. Black has the minimum intensity for red, green, and blue, so the color value for black is (0, 0, 0). White has the maximum intensity for red, green, and blue, so its color value is (255, 255, 255).

Note  If image color matching is enabled, the definition of color and the meaning of a color value depends on the type of color space that is currently set for the device context.

Windows and applications use parameters and variables having the COLORREF type to pass and store color values. For example, the EnumObjects function identifies the color of each pen by setting the lopnColor member in a LOGPEN structure to a color value. Applications can extract the individual values of the red, green, and blue components from a color value by using the GetRValue, GetGValue, and GetBValue macros, respectively. Applications can create a color value from individual component values by using the RGB macro. When creating or examining a logical palette, an application uses the RGBQUAD structure to define color values and to examine individual component values.


 Color Approximations and Dithering

Although an application can use color without regard to the color capabilities of the device, the resulting output may not be as informative and pleasing as output for which color is carefully chosen. Few, if any, devices guarantee an exact match for every possible color value; therefore, if an application requests a color that the device cannot generate, Windows approximates that color by using a color that the device can generate. For example, if an application attempts to create a red pen for a black and white printer, it will receive a black pen instead — Windows uses black as the approximation for red.

An application can discover whether Windows will approximate a given color by using the GetNearestColor function. The function takes a color value and returns the color value of the closest matching color the device can generate. The method Windows uses to determine this approximation depends on the device driver and its color capabilities. In most cases, the approximated color's overall intensity is closest to that of the requested color.

When an application creates a pen or sets the color for text, Windows always approximates a color if no exact match exists. When an application creates a solid brush, Windows may attempt to simulate the requested color by dithering. Dithering simulates a color by alternating two or more colors in a pattern. For example, different shades of pink can be simulated by alternating different combinations of red and white. Depending on the colors and the pattern, dithering can produce reasonable simulations. It is most useful for monochrome devices, because it expands the number of available "colors" well beyond simple black and white.

The method used to create dithered colors depends on the device driver. Most device drivers use a standard dithering algorithm, which generates a pattern based on the intensity values of the requested red, green, and blue colors. In general, any requested color that cannot be generated by the device is subject to simulation, but an application is not notified when Windows simulates a color. Furthermore, an application cannot modify or change the dithering algorithm of the device driver. An application, however, can bypass the algorithm by creating and using pattern brushes. In this way, the application creates its own dithered colors by combining solid colors in the bitmap that it uses to create the brush.


 Color in Bitmaps

Windows handles colors in bitmaps differently than colors in pens, brushes, and text. Compatible bitmaps, created by using the CreateBitmap or CreateCompatibleBitmap function, are device specific and retain color information in a device-dependent format. No color values are used, and the colors are not subject to approximations and dithering.

Device-independent bitmaps (DIBs) retain color information either as color values or color palette indices. If color values are used, the colors are subject to approximation, but not dithering. Color palette indices can only be used with devices that support color palettes. Although Windows does not approximate or dither colors identified by indices, the resulting color may be different than that intended, because the indices yield valid results only in the context of the color palette that was current at the time the bitmap was created. If the palette changes, so do the colors in the bitmap.


 Color Mixing

Color mixing lets an application create new colors by combining the pen or brush color with colors in the existing image. The application can choose either to draw the pen or brush color as is (effectively drawing over any existing image) or to mix the color with the colors already present.

The foreground mix mode, sometimes called the binary raster operation, determines how these colors are mixed. An application can merge colors, preserving all components of both colors; mask colors, removing or moderating components that are not common; or exclusively mask colors, removing or moderating components that are common. There are several variations on these basic mixing operations.

Color mixing is subject to color approximation. If the result of color mixing is a color that the device cannot generate, Windows approximates the result, using a color it can generate. If an application mixes dithered colors, the individual colors used to create the dithered color are mixed, and the results are subject to color approximation.

An application sets the foreground mix mode by using the SetROP2 function and retrieves the current mode by using the GetROP2 function.

Although there is a background mix mode, that mode does not control the mixing of colors. Instead, it specifies whether a background color is used when drawing styled lines, hatched brushes, and text.


 Color Palettes

A color palette is an array that contains color values identifying the colors that can currently be displayed or drawn on the output device. Color palettes are used by devices that are capable of generating many colors but that can only display or draw a subset of these at any given time. For such devices, Windows maintains a system palette to track and manage the current colors of the device. Applications do not have direct access to the system palette. Instead, Windows associates a default palette with each device context. Applications can use the colors in the default palette or define their own colors by creating logical palettes and associating them with individual device contexts.

An application can determine whether a device supports color palettes by checking for the RC_PALETTE bit in the RASTERCAPS value returned by the GetDeviceCaps function.


 Default Palette

The default palette is an array of color values identifying the colors that can be used with a device context by default. Windows associates the default palette with a context whenever an application creates a context for a device that supports color palettes. The default palette ensures that colors are available for use by an application without any further action.

The default palette typically has 20 entries (colors), but the exact number of entries may vary from device to device. This number is equal to the NUMCOLORS value returned by the GetDeviceCaps function. An application can retrieve the color values for colors in the default palette by enumerating solid pens, the same technique used to discover the colors available on nonpalette devices. The colors in the default palette depend on the device. Display devices, for example, often use the 16 standard colors of the VGA display and 4 other colors defined by Windows. Printer devices may use other default colors.

When using the default palette, applications use color values to specify pen and text colors. If the requested color is not in the palette, Windows approximates the color by using the closest color in the palette. If an application requests a solid brush color that is not in the palette, Windows simulates the color by dithering with colors that are in the palette.

To avoid approximations and dithering, applications can also specify pen, brush, and text colors by using color palette indices rather than color values. A color palette index is an integer value that identifies a specific palette entry. Applications can use color palette indices in place of color values but must use the PALETTEINDEX macro to create the indices.

Color palette indices are only useful for devices that support color palettes. To avoid this device dependence, applications that use the same code to draw to both palette and nonpalette devices should use palette-relative color values to specify pen, brush, and text colors. These values are identical to color values except when creating solid brushes. (On palette devices, a solid brush color specified by a palette-relative color value is subject to color approximation instead of dithering.) Applications must use the PALETTERGB macro to create palette-relative color values.

Windows does not allow an application to change the entries in the default palette. To use colors other than those in the default palette, an application must create its own logical palette and select the palette into the device context.


 Logical Palette

A logical palette is a color palette that an application creates and associates with a given device context. Logical palettes let applications define and use colors that meet their specific needs. Applications can create any number of logical palettes, using them for separate device contexts or switching between them for a single device context. The maximum number of palettes that an application can create depends on the resources of the system.

An application creates a logical palette by using the CreatePalette function. The application fills a LOGPALETTE structure, which specifies the number of entries and the color values for each entry, and then the application passes the structure to CreatePalette. The function returns a palette handle that the application uses in all subsequent operations to identify the palette. To use colors in the logical palette, the application selects the palette into a device context by using the SelectPalette function and then realizes the palette by using the RealizePalette function. The colors in the palette are available as soon as the logical palette is realized.

An application should limit the size of its logical palettes to just enough entries to represent the colors needed. Applications cannot create logical palettes larger than the maximum palette size, a device-dependent value. Applications can obtain the maximum size by using the GetDeviceCaps function to retrieve the SIZEPALETTE value.

Although an application can specify any color value for a given entry in a logical palette, not all colors can be generated by the given device. Windows does not provide a way to discover which colors are supported, but the application can discover the total number of these colors by retrieving the color resolution of the device. The color resolution, specified in color bits per pixel, is equal to the COLORRES value returned by the GetDeviceCaps function. A device that has a color resolution of 18 has 262,144 possible colors. If an application requests a color that is not supported, Windows chooses an appropriate approximation.

Once a logical palette is created, an application can change colors in the palette by using the SetPaletteEntries function. If the logical palette has been selected and realized, changing the palette does not immediately affect the colors being displayed. The application must use the UnrealizeObject and RealizePalette functions to update the colors. In some cases, the application may need to deselect, unrealize, select, and realize the logical palette to ensure that the colors are updated exactly as requested. If an application selects a logical palette into more than one device context, changes to the logical palette affect all device contexts for which it is selected.

An application can change the number of entries in a logical palette by using the ResizePalette function. If the application reduces the size, the remaining entries are unchanged. If the application extends the size, Windows sets the color for each new entry to black (0, 0, 0) and the flag to zero.

An application can retrieve the color and flag values for entries in a given logical palette by using the GetPaletteEntries function. An application can retrieve the index for the entry in a given logical palette that most closely matches a specified color value by using the GetNearestPaletteIndex function.

When an application no longer needs a logical palette, it can delete it by using the DeleteObject function. The application must make sure the logical palette is no longer selected into a device context before deleting the palette.


 Palette Animation

Palette animation is a technique to simulate motion by rapidly changing the colors of selected entries in a color palette. An application can carry out palette animation by creating a logical palette that contains "reserved" entries and then using the AnimatePalette function to change colors in those reserved entries.

An application creates a reserved entry in a logical palette by setting the peFlags member of the PALETTEENTRY structure to the PC_RESERVED flag. Once this logical palette is selected and realized, the application can call the AnimatePalette function to change one or more reserved entries. If the given palette is associated with the active window, Windows updates the colors on the screen immediately.


 System Palette

Windows maintains a system palette for each device that uses palettes. The system palette contains the color values for all colors that can currently be displayed or drawn by the device. Other than viewing the contents of the system palette, applications cannot access the system palette directly. Instead, Windows has complete control of the system palette and permits access only through the use of logical palettes.

An application can view the contents of the system palette by using the GetSystemPaletteEntries function. This function retrieves the contents of one or more entries, up to the total number of entries in the system palette. The total is always equal to the number returned for the SIZEPALETTE value by the GetDeviceCaps function and is the same as the maximum size for any given logical palette.

Although applications cannot change colors in the system palette directly, they may cause changes when realizing logical palettes. To realize a palette, Windows examines each requested color and attempts to find an entry in the system palette that contains an exact match. If Windows finds a matching color, it maps the logical palette index to the corresponding system palette index. If Windows does not find an exact match, it copies the requested color to an unused system palette entry before mapping the indices. If all system palette entries are in use, Windows maps the logical palette index to the system palette entry whose color most closely matches the requested color. Once this mapping is set, applications cannot override it. For example, applications cannot use system palette indices to specify colors; only logical palette indices are permitted.

Applications can modify the way indices are mapped by setting the peFlags member of the PALETTEENTRY structure to selected values when creating the logical palette. For example, the PC_NOCOLLAPSE flag directs Windows to immediately copy the requested color to an unused system palette entry regardless of whether a system palette entry already contains that color. Also, the PC_EXPLICIT flag directs Windows to map the logical palette index to an explicitly given system palette index. (The application gives the system palette index in the low-order word of the PALETTEENTRY structure.)

Palettes can be realized as either a background palette or a foreground palette by specifying TRUE or FALSE respectively for the bForceBackground parameter in the SelectPalette function. There can be only one foreground palette in the system at a time. If the window is the currently active window or a descendent of the currently active window, it can realize a foreground palette. Otherwise the palette is realized as a background palette regardless of the value of the bForceBackground parameter. The critical property of a foreground palette is that, when realized, it can overwrite all entries (except for the static entries) in the system palette. Windows accomplishes this by marking all of the entries that are not static in the system palette as unused before the realization of a foreground palette, thereby eliminating all of the used entries. No preprocessing occurs on the system palette for a background palette realization. The foreground palette sets all of the possible nonstatic colors. Background palettes can set only what remains open and are prioritized in a first-come, first-serve manner. Typically, applications use background palettes for child windows which realize their own individual palettes. This helps minimize the number of changes that occur to the system palette.

An unused system palette entry is any entry that is not reserved and does not contain a static color. Reserved entries are explicitly marked with the PC_RESERVED value. These entries are created when an application realizes a logical palette for palette animation. Static color entries are created by Windows and correspond to the colors in the default palette. The GetDeviceCaps function can be used to retrieve the NUMRESERVED value, which specifies the number of system palette entries reserved for static colors.

Because the system palette has a limited number of entries, selecting and realizing a logical palette for a given device may affect the colors associated with other logical palettes for the same device. These color changes are especially dramatic when they occur on the display. An application can make sure that reasonable colors are used for its currently selected logical palette by resetting the palette before each use. An application resets the palette by calling the UnrealizeObject and RealizePalette functions. Using these functions causes Windows to remap the colors in the logical palette to reasonable colors in the system palette.


 System Palette and Static Colors

Ordinarily, the system palette entries that Windows reserves for static colors cannot be changed. An application can override this default behavior by using the SetSystemPaletteUse function to reduce the number of static color entries and, thereby, increase the number of unused system palette entries. However, because changing the static colors can have an immediate and dramatic effect on all windows on the display, an application should not call SetSystemPaletteUse, unless it has a maximized window and the input focus.

When an application calls SetSystemPaletteUse with the SYSPAL_NOSTATIC value, Windows frees all but two of the reserved entries, allowing those entries to receive new color values when the application subsequently realizes its logical palette. The remaining two static color entries remain reserved and are set to white and black. An application can restore the reserved entries by calling SetSystemPaletteUse with the SYSPAL_STATIC value. It can discover the current system palette usage by using the GetSystemPaletteUse function.

Furthermore, after setting the system palette usage to SYSPAL_NOSTATIC, the application must immediately realize its logical palette, call the GetSysColor function to save the current system color settings, call the SetSysColors function to set the system colors to reasonable values using black and white, and finally send the WM_SYSCOLORCHANGE message to other top-level windows to allow them to be redrawn with the new system colors. When setting system colors using black and white, the application should make sure adjacent or overlapping items, such as window frames and borders, are set to black and white, respectively.

Before the application loses the input focus, closes its window, or terminates, it must immediately call SetSystemPaletteUse with the SYSPAL_STATIC value, realize its logical palette, restore the system colors to their previous values, and send the WM_SYSCOLORCHANGE message. Windows sends a WM_PAINT message to any window that is affected by a system color change. Applications that have brushes using the existing system colors should delete those brushes and recreate them using the new system colors.


 Palette Messages

Changes to the system palette for the display device can have dramatic and sometimes undesirable effects on the colors used in windows on the desktop. To minimize the impact of these changes, Windows provides a set of messages that help applications manage their logical palettes while ensuring that colors in the active window are as close as possible to the colors intended.

Windows sends a WM_QUERYNEWPALETTE message to a top-level or overlapped window just before activating the window. This message gives an application the opportunity to select and realize its logical palette so that it receives the best possible mapping of colors for its logical palette. When the application receives the message, it should use the SelectPalette, UnrealizeObject, and RealizePalette functions to select and realize the logical palette. Doing so directs Windows to update colors in the system palette so that its colors match as many colors in the logical palette as possible.

When an application causes changes to the system palette as a result of realizing its logical palette, Windows sends a WM_PALETTECHANGED message to all top-level and overlapped windows. This message gives applications the opportunity to update the colors in the client areas of their windows, replacing colors that have changed with colors that more closely match the intended colors. An application that receives the WM_PALETTECHANGED message should use UnrealizeObject and RealizePalette to reset the logical palettes associated with all inactive windows and then update the colors in the client area for each inactive window by using the UpdateColors function. This technique does not guarantee the greatest number of exact color matches; however, it does ensure that colors in the logical palette are mapped to reasonable colors in the system palette.

Note  To avoid creating an infinite loop, an application should never realize the palette for the window whose handle matches the handle passed in the wParam parameter of the WM_PALETTECHANGED message.

The UpdateColors function typically updates a client area of an inactive window faster than redrawing the area. However, because UpdateColors performs color translation based on the color of each pixel before the system palette changed, each call to this function results in the loss of some color accuracy. This means UpdateColors cannot be used to update colors when the window becomes active. In such cases, the application should redraw the client area.

Windows may send the WM_QUERYNEWPALETTE message when changes to the logical palette are made. Also, Windows may send the WM_PALETTEISCHANGING message to all top-level and overlapped windows when the system palette is about to change.


 Halftone Palette and Color Adjustment

Halftone palettes are intended to be used whenever the stretching mode of a device context is set to HALFTONE. An application creates a halftone palette by using the CreateHalftonePalette function. The application must select and realize this palette into the device context before calling the StretchBlt or StretchDIBits function.

Windows automatically adjusts the input color of source bitmaps whenever applications call the StretchBlt and StretchDIBits functions and the stretching mode of a device context is set to HALFTONE. These color adjustments affect certain attributes of the image, such as contrast and brightness. An application can set the color adjustment values by using the SetColorAdjustment function. The application can retrieve the color adjustment values for the specified device context by using the GetColorAdjustment function.


 Using Color

•	Enumerating colors

•	Creating colored pens and brushes


 Enumerating Colors

You can determine how many colors a device supports and what those colors are by retrieving the count of colors for the device and enumerating the colors of the solid pens. To retrieve the number of colors, use the GetDeviceCaps function with the NUMCOLORS value. To enumerate solid pens, use the EnumObjects function and a corresponding callback function that receives information about each pen.

// GetTheColors - returns the count and color values of solid colors
// Returns the address of array containing colors
// hdc - handle of device context

COLORREF *GetTheColors(HDC hdc)
{
    int cColors;
    COLORREF *aColors;

    // Get the number of colors.
    cColors = GetDeviceCaps(hdcCurrent, NUMCOLORS);

    // Allocate space for the array.
    aColors = (COLORREF *)LocalAlloc(LPTR, sizeof(COLORREF) *
        (cColors+1));

    // Save the count of colors in first element.
    aColors[0] = (LONG)cColors;

    // Enumerate all pens and save solid colors in the array.
    EnumObjects(hdc, OBJ_PEN, (GOBJENUMPROC)MyEnumProc, (LONG)aColors);

    // Refresh the count of colors.
    aColors[0] = (LONG)cColors;

    return aColors;
}

int MyEnumProc(LPVOID lp, LPBYTE lpb)
{
    LPLOGPEN lopn;
    COLORREF *aColors;
    int iColor;

    lopn = (LPLOGPEN)lp;
    aColors = (COLORREF *)lpb;

    if (lopn->lopnStyle==PS_SOLID) {
        // Check for too many colors.
        if ((iColor = (int)aColors[0]) <= 0)
             return 0;
        aColors[iColor] = lopn->lopnColor;
        aColors[0]--;
    }
    return 1;
}


 Creating Colored Pens and Brushes

Although you can specify any color for a pen when creating it, Windows uses only colors that are available on the device. This means Windows uses the closest matching color when it realizes the pen for drawing. When creating brushes, Windows generates a dithered color if you specify a color that the device does not support. In either case, you can use the RGB macro to specify a color when creating a pen or brush.

// DrawARectangle - draws a red rectangle with a green border
// No return value.
// hdc - handle of the device context

void DrawARectangle(HDC hdc)

{
    HPEN hpen, hpenOld;
    HBRUSH hbrush, hbrushOld;

    // Create a green pen.
    hpen = CreatePen(PS_SOLID, 10, RGB(0, 255, 0));
    // Create a red brush.
    hbrush = CreateSolidBrush(RGB(255, 0, 0));

    // Select the new pen and brush, and then draw.
    hpenOld = SelectObject(hdc, hpen);
    hbrushOld = SelectObject(hdc, hbrush);
    Rectangle(hdc, 100,100, 200,200);

    // Do not forget to clean up.
    SelectObject(hdc, hpenOld);
    DeleteObject(hpen);
    SelectObject(hdc, hbrushOld);
    DeleteObject(hbrush);
}


 Color Reference

The following functions and messages are associated with color.


 Color Functions

Following are the functions used with color.

AnimatePalette
CreateHalftonePalette
CreatePalette
GetColorAdjustment
GetNearestColor
GetNearestPaletteIndex
GetPaletteEntries
GetSystemPaletteEntries
GetSystemPaletteUse
RealizePalette
ResizePalette
SelectPalette
SetColorAdjustment
SetPaletteEntries
SetSystemPaletteUse
UnrealizeObject
UpdateColors


 Color Messages

Following are the messages used with color.

WM_PALETTECHANGED
WM_PALETTEISCHANGING
WM_QUERYNEWPALETTE
WM_SYSCOLORCHANGE


 Coordinate Spaces and Transformations

Applications written for the Microsoft® Windows® operating system use coordinate spaces and transformations to scale, rotate, translate, shear, and reflect graphics output. A coordinate space is a planar space based on the Cartesian coordinate system. This system requires two axes that are perpendicular and equal in length. There are four coordinate spaces in Windows: world, page, device, and physical device (client area, or desktop, or page of printer paper). A transformation is an algorithm that alters ("transforms") the size, orientation, and shape of objects.


 About Coordinate Spaces and Transformations

Coordinate spaces and transformations are used, for example, by desktop publishing applications to "zoom" parts of a page or to display adjacent pages in a window; computer-aided design (CAD) applications use them to rotate objects, scale drawings, or to create perspective views; and spreadsheet applications use them to move and size graphs.

The following illustrations show successive views of an object created in a drawing application. The first illustration shows the object as it appears in the original drawing; the five remaining illustrations show the effects of applying various transformations.

Original View

Scaled View

Translated View

Rotated View

Sheared View

Reflection


 Transformation of Coordinate Spaces

A coordinate space is a planar space based on the Cartesian coordinate system. This system provides a means of specifying the location of each point on a plane. It requires two axes that are perpendicular and equal in length. The following illustration shows a coordinate space.

The Microsoft® ( ) Win32® application programming interface (API) uses four coordinate spaces: world, page, device, and physical device. Applications use world space to rotate, shear, or reflect graphics output. World space measures 2^32 units high by 2^32 units wide. Page space (referred to as logical space in earlier versions of Windows) also measures 2^32 units high by 2^32 units wide. Device space measures 2^27 units high by 2^27 units wide. Page space works with device space to provide applications with device-independent units, such as millimeters and inches. The Win32 API refers to both world space and page space as logical space. The final coordinate space, physical device, usually refers to the client area of the application's window; however, it can also include the entire desktop, a complete window (including the frame, title bar, and menu bar), or a page of printer or plotter paper. Physical device dimensions vary according to the dimensions set by the display, printer, or plotter technology.

To depict output on a physical device, Windows copies (or maps) a rectangular region from one coordinate space into the next coordinate space until finally the output appears in its entirety on the physical device. Mapping begins in the application's world space if the application has called the SetWorldTransform function; otherwise, mapping occurs in page space. As Windows copies each point within the rectangular region from one space into another, it applies an algorithm called a transformation. A transformation alters (or transforms) the size, orientation, and shape of objects that are copied from one coordinate space into another. Although a transformation affects an object as a whole, it is applied to each point, or to each line, in the object.

The following illustration shows a typical transformation performed by using the SetWorldTransform function.


 World-Space to Page-Space Transformations

World-space to page-space transformations are new to Windows. They support translation and scaling that were available in previous versions of Windows. In addition, they support rotation, shear, and reflection capabilities. The following sections describe these transformations, illustrate their effects, and provide the algorithms used to achieve them.


 Translation

Some applications translate (or shift) objects drawn in the client area. If your application features this capability, use the SetWorldTransform function to set the appropriate world-space to page-space transformation. This function receives a pointer to an XFORM structure containing the appropriate values. The eDx and eDy members of XFORM specify the horizontal and vertical translation components, respectively.

When translation occurs, each point in an object is shifted vertically, horizontally, or both, by a specified amount. The following illustration shows a 20- by 20-unit rectangle that was translated to the right by 10 units when copied from world coordinate space to page coordinate space.

In the preceding illustration, the x-coordinate of each point in the rectangle is 10 units greater than the original x-coordinate.

Horizontal translation can be represented by the following algorithm.

x' = x + Dx

Where x' is the new x-coordinate, x is the original x-coordinate, and Dx is the horizontal distance moved.

Vertical translation can be represented by the following algorithm.

y' = y + Dy

Where y' is the new y-coordinate, y is the original y-coordinate, and Dy is the vertical distance moved.

The horizontal and vertical translation transformations can be combined into a single operation by using a 3-by-3 matrix.

                      |1   0   0|

|x' y' 1| = |x y 1| * |0   1   0|

                      |Dx  Dy  1|

(The rules of matrix multiplication state that the number of rows in one matrix must equal the number of columns in the other. The integer 1 in the matrix |x y 1| is a placeholder that was added to meet this requirement.)

The 3-by-3 matrix that produced the illustrated translation transformation contains the following values.

|1  0  0|

|0  1  0|

|10 0  1|


 Scaling

Most CAD and drawing applications provide features that scale output created by the user. If your application features scaling (or zoom) capabilities, use the SetWorldTransform function to set the appropriate world-space to page-space transformation. This function receives a pointer to an XFORM structure containing the appropriate values. The eM11 and eM22 members of XFORM specify the horizontal and vertical scaling components, respectively.

When scaling occurs, the vertical and horizontal lines (or vectors), that constitute an object, are stretched or compressed with respect to the x- or y-axis. The following illustration shows a 20- by 20-unit rectangle scaled vertically to twice its original height when copied from world coordinate space to page coordinate space.

In the preceding illustration, the vertical lines that define the original rectangle's side measure 20 units, while the vertical lines that define the scaled rectangle's sides measure 40 units.

Vertical scaling can be represented by the following algorithm.

y' = y * Dy

Where y' is the new length, y is the original length, and Dy is the vertical scaling factor.

Horizontal scaling can be represented by the following algorithm.

x' = x * Dx

Where x' is the new length, x is the original length, and Dx is the horizontal scaling factor.

The vertical and horizontal scaling transformations can be combined into a single operation by using a 2-by-2 matrix.

|x' y'|  =  |Dx   0|  *  |x y|

            |0   Dy|

The 2-by-2 matrix that produced the scaling transformation contains the following values.

|1    0|

|0    2|


 Rotation

Many CAD applications provide features that rotate objects drawn in the client area. If your application features rotation capabilities, use the SetWorldTransform function to set the appropriate world-space to page-space transformation. This function receives a pointer to an XFORM structure containing the appropriate values. The eM11, eM12, eM21, and eM22 members of XFORM specify, respectively, the cosine, sine, negative sine, and cosine of the angle of rotation.

When rotation occurs, the points that constitute an object are rotated with respect to the coordinate-space origin. The following illustration shows a 20- by 20-unit rectangle rotated 30 degrees when copied from world coordinate space to page coordinate space.

In the preceding illustration, each point in the rectangle was rotated 30 degrees with respect to the coordinate-space origin.

The following algorithm computes the new x-coordinate (x') for a point (x,y) that is rotated by angle A with respect to the coordinate-space origin.

x' = (x * cos A) - (y * sin A)

The following algorithm computes the y-coordinate (y') for a point (x,y) that is rotated by the angle A with respect to the origin.

y' = (x * sin A) + (y * cos A)

The two rotation transformations can be combined in a 2-by-2 matrix as follows.

|x' y'| == |x y| * | cos A   sin A|

                   |-sin A   cos A|

The 2-by-2 matrix that produced the rotation contains the following values.

| .8660    .5000|

|-.5000    .8660|

Rotation Algorithm Derivation

Rotation algorithms are based on trigonometry's addition theorem stating that the trigonometric function of a sum of two angles (A1 and A2) can be expressed in terms of the trigonometric functions of the two angles.

sin(A1 + A2) = (sin A1 * cos A2) + (cos A1 * sin A2)

cos(A1 + A2) = (cos A1 * cos A2) - (sin A1 * sin A2)

The following illustration shows a point p rotated counterclockwise to a new position p'. In addition, it shows two triangles formed by a line drawn from the coordinate-space origin to each point and a line drawn from each point through the x-axis.

Using trigonometry, the x-coordinate of point p can be obtained by multiplying the length of the hypotenuse h by the cosine of A1.

x = h * cos A1

The y-coordinate of point p can be obtained by multiplying the length of the hypotenuse h by the sine of A1.

y = h * sin A1

Likewise, the x-coordinate of point p' can be obtained by multiplying the length of the hypotenuse h by the cosine of (A1 + A2).

x' = h * cos (A1 + A2)

Finally, the y-coordinate of point p' can be obtained by multiplying the length of the hypotenuse h by the sine of (A1 + A2).

y' = h * sin (A1 + A2)

Using the addition theorem, the preceding algorithms become the following.

x' = (h * cos A1 * cos A2) - (h * sin A1 * sin A2)

y' = (h * cos A1 * sin A2) + (h * sin A1 * cos A2)

The rotation algorithms for a given point rotated by angle A2 can be obtained by substituting x for each occurrence of (h * cos A1) and substituting y for each occurrence of (h * sin A1).

x' = (x * cos A2) - (y * sin A2)

y' = (x * sin A2) + (y * cos A2)


 Shear

Some applications provide features that shear objects drawn in the client area. If your application features shear capabilities, use the SetWorldTransform function to set appropriate values in the world-space to page-space transformation. This function receives a pointer to an XFORM structure containing the appropriate values. The eM12 and eM21 members of XFORM specify the horizontal and vertical proportionality constants, respectively.

There are two components of the shear transformation. The first alters the vertical lines in an object; the second alters the horizontal lines. The following illustration shows a 20- by 20-unit rectangle sheared horizontally when copied from world space to page space.

A horizontal shear can be represented by the following algorithm:

x' = x + (Sx * y)

where x is the original x-coordinate, Sx is the proportionality constant, and x' is the result of the shear transformation.

A vertical shear can be represented by the following algorithm:

y' = y + (Sy * x)

where y is the original y-coordinate, Sy is the proportionality constant, and y' is the result of the shear transformation.

The horizontal-shear and vertical-shear transformations can be combined into a single operation using a 2-by-2 matrix.

|x' y'| == |x y| * |  1   Sx|

                   | Sy    1|

The 2-by-2 matrix that produced the shear contains the following values.

|1    1|

|0    1|


 Reflection

Some applications provide features that reflect (or mirror) objects drawn in the client area. If your application features reflection capabilities, use the SetWorldTransform function to set the appropriate values in the world-space to page-space transformation. This function receives a pointer to an XFORM structure containing the appropriate values. The eM11 and eM22 members of XFORM specify the horizontal and vertical reflection components, respectively.

The reflection transformation creates a "mirror" image of an object with respect to either the x- or y-axis. In short, reflection is just negative scaling. To produce a horizontal reflection, x-coordinates are multiplied by −1. To produce a vertical reflection, y-coordinates are multiplied by  − 1.

Horizontal reflection can be represented by the following algorithm:

x' = −x

where x is the x-coordinate and x' is the result of the reflection.

The 2-by-2 matrix that produced horizontal reflection contains the following values:

|-1    0|

|0     1|

Vertical reflection can be represented by the following algorithm:

y' = -y

where y is the y-coordinate and y' is the result of the reflection.

The 2-by-2 matrix that produced vertical reflection contains the following values:

|1    0|

|0   -1|

The horizontal-reflection and vertical-reflection operations can be combined into a single operation by using the following 2-by-2 matrix:

|-1    0|

|0    -1|


 Combined World-to-Page Space Transformations

You can combine the five world-to-page transformations into a single 3-by-3 matrix. The CombineTransform function can be used to combine two world-space to page-space transformations. You can use the combined transformations to alter output associated with a particular device context (DC) by calling the SetWorldTransform function and supplying the elements for this matrix. When an application calls SetWorldTransform, it stores the elements of the 3-by-3 matrix in an XFORM structure. The members of this structure correspond to the first two columns of a 3-by-3 matrix; the last column of the matrix is not required because its values are constant.

You can retrieve the elements of the current world transformation matrix by calling the GetWorldTransform function and supplying a pointer to an XFORM structure.


 Page-Space to Device-Space Transformations

The page-space to device-space transformation was part of the original Windows interface. This transformation determines the mapping mode for all graphics output associated with a particular DC. A mapping mode is a scaling transformation that specifies the size of the units used for drawing operations. The mapping mode may also perform translation. In some cases, the mapping mode alters the orientation of the x- and y-axes in device space. The mapping modes are described in the following table.

Mapping mode	Description
MM_ANISOTROPIC	Each unit in page space is mapped to an application-specified unit in device space. The axis may or may not be equally scaled (for example, a circle drawn in world space may appear to be an ellipse when depicted on a given device). The orientation of the axis is also specified by the application.
MM_HIENGLISH	Each unit in page space is mapped to 0.001 inch in device space. Increasing values of x occur as you move to the right; increasing values of y occur as you move up.
MM_HIMETRIC	Each unit in page space is mapped to 0.01 millimeter in device space. Increasing values of x occur as you move to the right; increasing values of y occur as you move up.
MM_ISOTROPIC	Each unit in page space is mapped to an application-defined unit in device space. The axes are always equally scaled. The orientation of the axes may be specified by the application.
MM_LOENGLISH	Each unit in page space is mapped to 0.01 inch in device space. Increasing values of x occur as you move to the right; increasing values of y occur as you move up.
MM_LOMETRIC	Each unit in page space is mapped to 0.1 millimeter in device space. Increasing values of x occur as you move to the right; increasing values of y occur as you move up.
MM_TEXT	Each unit in page space is mapped to one pixel; that is, no scaling is performed at all. When no translation is in effect (this is the default), page space in the MM_TEXT mapping mode is equivalent to physical device space. Increasing values of x occur as you move to the right; increasing values of y occur as you move down.
MM_TWIPS	Each unit in page space is mapped to one twentieth of a printer's point (1/1440 inch). Increasing values of x occur as you move to the right; increasing values of y occur as you move up.
You set a mapping mode by calling the SetMapMode function. You retrieve the current mapping mode for a DC by calling the GetMapMode function.

The page-space to device-space transformations consist of values calculated from the points given by the window and viewport. The window and viewport each consist of a pair of points, with one point specifying an origin and the other a width and height (called the extents). The window points are in logical coordinates; the viewport in device coordinates (pixels). Windows combines the origins and extents from both the window and viewport to create the transformation. This means that the window and viewport each specify half of the factors needed to define the transformation used to map points in page space to device space. The effect of a transformation calculated in this way is that Windows maps the window origin to the viewport origin and the window extents to the viewport extents, as shown in the following illustration.

The window and viewport extents establish a ratio or scaling factor used in the page-space to device-space transformations. For the six predefined mapping modes (MM_HIENGLISH, MM_LOENGLISH, MM_HIMETRIC, MM_LOMETRIC, MM_TEXT, and MM_TWIPS), the extents are set by Windows when you call SetMapMode. They cannot be changed. The other two mapping modes (MM_ISOTROPIC and MM_ANISOTROPIC) require that you specify the extents. This is done by calling SetMapMode to set the appropriate mode and then calling the SetWindowExtEx and SetViewportExtEx functions to specify the extents. In the MM_ISOTROPIC mapping mode, it is important to call SetWindowExtEx before calling SetViewportExtEx.

The window and viewport origins establish the translation used in the page-space to device-space transformations. You set the window and viewport origins by using the SetWindowOrgEx and SetViewportOrgEx functions. The origins are independent of the extents, and an application can set them regardless of the current mapping mode. Changing a mapping mode does not affect the currently set origins (although it can affect the extents). Origins are specified in absolute units that the current mapping mode does not affect. You can also alter the origins by using the OffsetWindowOrgEx and OffsetViewportOrgEx functions.

The following formula shows the math involved in converting a point from page space to device space.

Dx = ((Lx - WOx) * VEx / WEx) + VOx

The following variables are involved.

Dx	 x value in device units

Lx	 x value in logical units (also known as page space units)

WOx	 window x origin

VOx	 viewport x origin

WEx	 window x-extent

VEx	 viewport x-extent

The same equation with y replacing x transforms the y component of a point.

The formula first offsets the point from its coordinate origin. This value, no longer biased by the origin, is then scaled into the destination coordinate system by the ratio of the extents. Finally, the scaled value is offset by the destination origin to its final mapping.

The LPtoDP and DPtoLP functions may be used to convert from logical points to device points and from device points to logical points, respectively.


 Predefined Mapping Modes

Of the six predefined mapping modes, one is device dependent (MM_TEXT) while the remaining five (MM_HIENGLISH, MM_LOENGLISH, MM_HIMETRIC, MM_LOMETRIC, and MM_TWIPS) are device independent.

The default mapping mode is MM_TEXT. One logical unit equals one pixel. Positive x is to the right, and positive y is down. This mode maps directly to the device's coordinate system. The logical-to-physical mapping involves only an offset in x and y that is defined by the application-controlled window and viewport origins. The viewport and window extents are all set to 1, creating a one-to-one mapping.

If your application displays geometric shapes (circles, squares, polygons, and so on), you may want to choose one of the device-independent mapping modes. For example, if you are writing code to provide charting capabilities for a spreadsheet application and want to guarantee that the diameter of each pie chart is 2 inches, you can choose the MM_LOENGLISH mapping mode and call the appropriate functions to draw and fill the chart. By specifying MM_LOENGLISH, you guarantee that the diameter of the chart is consistent on any display or printer. If you were to choose MM_TEXT instead of MM_LOENGLISH, a chart that appears circular on a VGA display would appear elliptical on an EGA display and would appear very small on a 300 dpi (dots per inch) laser printer.


 Application-Defined Mapping Modes

The two application-defined mapping modes (MM_ISOTROPIC and MM_ANISOTROPIC) are provided for application-specific mapping modes. The MM_ISOTROPIC mode guarantees that logical units in the x-direction and in the y-direction are equal, while the MM_ANISOTROPIC mode allows the units to differ. A CAD or drawing application can benefit from the MM_ISOTROPIC mapping mode but may need to specify logical units that correspond to the increments on an engineer's scale (1/64 inch). These units would be difficult to obtain with the predefined mapping modes (MM_HIENGLISH or MM_HIMETRIC); however, they can easily be obtained by selecting the MM_ISOTROPIC (or MM_ANISOTROPIC) mode. The following example shows how to set logical units to 1/64 inch:

SetMapMode(hDC, MM_ISOTROPIC);

SetWindowExtEx(hDC, 64, 64, NULL);

SetViewportExtEx(hDC, GetDeviceCaps(hDC, LOGPIXELSX),

                      GetDeviceCaps(hDC, LOGPIXELSY), NULL);


 Device-Space to Physical-Device Transformation

The device-space to physical-device transformation is unique in several respects. For example, it is limited to translation and is controlled by the window manager component of Windows. The sole purpose of this transformation is to ensure that the origin of device space is mapped to the proper point on the physical device. There are no functions to set this transformation, nor are there any functions to retrieve related data.


 Default Transformations

Whenever an application creates a DC and immediately begins calling GDI drawing or output functions, it takes advantage of the default page-space to device-space, and device-space to client-area transformations. A world-to-page space transformation cannot happen until the application first calls the SetGraphicsMode function to set the mode to GM_ADVANCED and then calls the SetWorldTransform function.

Use of MM_TEXT (the default page-space to device-space transformation) results in a one-to-one mapping; that is, a given point in page space maps to the same point in device space. As previously mentioned, this transformation is not specified by a matrix. Instead, it is obtained by dividing the width of the viewport by the width of the window and the height of the viewport by the height of the window. In the default case, the viewport dimensions are 1-pixel by 1-pixel and the window dimensions are 1-page unit by 1-page unit.

The device-space to physical-device (client area, desktop, or printer paper) transformation always results in a one-to-one mapping; that is, one unit in device space is always equivalent to one unit in the client area, on the desktop, or on a page. The sole purpose of this transformation is translation; it ensures that output appears correctly in an application's window no matter where that window is moved on the desktop.

The one unique aspect of MM_TEXT is the orientation of the y-axis in page space. In MM_TEXT, the positive y-axis extends downward and the negative y-axis extends upward.


 Using Coordinate Spaces and Transformations

This section contains an example that demonstrates the following tasks:

•	Drawing graphics with predefined units.

•	Centering graphics in the application's client area.

•	Scaling graphics output to half its original size.

•	Translating graphics output 3/4 of an inch to the right.

•	Rotating graphics 30 degrees.

•	Shearing graphics output along the x-axis.

•	Reflecting graphics output about an imaginary horizontal axis drawn through its midpoint.

The following example was used to create the illustrations that appear earlier in this topic.

void TransformAndDraw(int iTransform, HWND hWnd)

{

HDC hDC;

XFORM xForm;

RECT rect;

/* Retrieve a DC handle for the application's window. */

hDC = GetDC(hWnd);

/*

 * Set the mapping mode to LOENGLISH. This moves the

 * client area origin from the upper left corner of the

 * window to the lower left corner (this also reorients

 * the y-axis so that drawing operations occur in a true

 * Cartesian space). It guarantees portability so that

 * the object drawn retains its dimensions on any

 * display running Windows.

 */

SetMapMode(hDC, MM_LOENGLISH);

/*

 * Set the appropriate world transformation (based on the

 * user's menu selection).

 */

switch (iTransform) {

        case SCALE:        /* Scale to 1/2 of the original size. */

            xForm.eM11 = (FLOAT) 0.5;

            xForm.eM12 = (FLOAT) 0.0;

            xForm.eM21 = (FLOAT) 0.0;

            xForm.eM22 = (FLOAT) 0.5;

            xForm.eDx  = (FLOAT) 0.0;

            xForm.eDy  = (FLOAT) 0.0;

            SetWorldTransform(hDC, &xForm);

            break;

        case TRANSLATE:   /* Translate right by 3/4 inch. */

            xForm.eM11 = (FLOAT) 1.0;

            xForm.eM12 = (FLOAT) 0.0;

            xForm.eM21 = (FLOAT) 0.0;

            xForm.eM22 = (FLOAT) 1.0;

            xForm.eDx  = (FLOAT) 75.0;

            xForm.eDy  = (FLOAT) 0.0;

            SetWorldTransform(hDC, &xForm);

            break;

        case ROTATE:      /* Rotate 30 degrees counterclockwise. */

            xForm.eM11 = (FLOAT) 0.8660;

            xForm.eM12 = (FLOAT) 0.5000;

            xForm.eM21 = (FLOAT) -0.5000;

            xForm.eM22 = (FLOAT) 0.8660;

            xForm.eDx  = (FLOAT) 0.0;

            xForm.eDy  = (FLOAT) 0.0;

            SetWorldTransform(hDC, &xForm);

            break;

        case SHEAR:       /* Shear along the x-axis with a    */

                          /* proportionality constant of 1.0. */

            xForm.eM11 = (FLOAT) 1.0;

            xForm.eM12 = (FLOAT) 1.0;

            xForm.eM21 = (FLOAT) 0.0;

            xForm.eM22 = (FLOAT) 1.0;

            xForm.eDx  = (FLOAT) 0.0;

            xForm.eDy  = (FLOAT) 0.0;

            SetWorldTransform(hDC, &xForm);

            break;

        case REFLECT:     /* Reflect about a horizontal axis. */

            xForm.eM11 = (FLOAT) 1.0;

            xForm.eM12 = (FLOAT) 0.0;

            xForm.eM21 = (FLOAT) 0.0;

            xForm.eM22 = (FLOAT) -1.0;

            xForm.eDx  = (FLOAT) 0.0;

            xForm.eDy  = (FLOAT) 0.0;

            SetWorldTransform(hDC, &xForm);

            break;

        case NORMAL:      /* Set the unity transformation. */

            xForm.eM11 = (FLOAT) 1.0;

            xForm.eM12 = (FLOAT) 0.0;

            xForm.eM21 = (FLOAT) 0.0;

            xForm.eM22 = (FLOAT) 1.0;

            xForm.eDx  = (FLOAT) 0.0;

            xForm.eDy  = (FLOAT) 0.0;

            SetWorldTransform(hDC, &xForm);

            break;

    }

/* Find the midpoint of the client area. */

GetClientRect(hWnd, (LPRECT) &rect);

DPtoLP(hDC, (LPPOINT) &rect, 2);

/* Select a hollow brush. */

SelectObject(hDC, GetStockObject(HOLLOW_BRUSH));

/* Draw the exterior circle. */

Ellipse(hDC, (rect.right / 2 - 100), (rect.bottom / 2 + 100),

    (rect.right / 2 + 100), (rect.bottom / 2 - 100));

/* Draw the interior circle. */

Ellipse(hDC, (rect.right / 2 -94), (rect.bottom / 2 + 94),

    (rect.right / 2 + 94), (rect.bottom / 2 - 94));

/* Draw the key. */

Rectangle(hDC, (rect.right / 2 - 13), (rect.bottom / 2 + 113),

    (rect.right / 2 + 13), (rect.bottom / 2 + 50));

Rectangle(hDC, (rect.right / 2 - 13), (rect.bottom / 2 + 96),

    (rect.right / 2 + 13), (rect.bottom / 2 + 50));

/* Draw the horizontal lines. */

MoveToEx(hDC, (rect.right / 2 - 150), (rect.bottom / 2 + 0), NULL);

LineTo(hDC, (rect.right / 2 - 16), (rect.bottom / 2 + 0));

MoveToEx(hDC, (rect.right / 2 - 13), (rect.bottom / 2 + 0), NULL);

LineTo(hDC, (rect.right / 2 + 13), (rect.bottom / 2 + 0));

MoveToEx(hDC, (rect.right / 2 + 16), (rect.bottom / 2 + 0), NULL);

LineTo(hDC, (rect.right / 2 + 150), (rect.bottom / 2 + 0));

/* Draw the vertical lines. */

MoveToEx(hDC, (rect.right / 2 + 0), (rect.bottom / 2 - 150), NULL);

LineTo(hDC, (rect.right / 2 + 0), (rect.bottom / 2 - 16));

MoveToEx(hDC, (rect.right / 2 + 0), (rect.bottom / 2 - 13), NULL);

LineTo(hDC, (rect.right / 2 + 0), (rect.bottom / 2 + 13));

MoveToEx(hDC, (rect.right / 2 + 0), (rect.bottom / 2 + 16), NULL);

LineTo(hDC, (rect.right / 2 + 0), (rect.bottom / 2 + 150));

ReleaseDC(hWnd, hDC);

}


 Coordinate Space and Transformation Functions

Following are the functions used with coordinate spaces and transformations.

ClientToScreen
CombineTransform
DPtoLP
GetCurrentPositionEx
GetGraphicsMode
GetMapMode
GetViewportExtEx
GetViewportOrgEx
GetWindowExtEx
GetWindowOrgEx
GetWorldTransform
LPtoDP
MapWindowPoints
ModifyWorldTransform
OffsetViewportOrgEx
OffsetWindowOrgEx
ScaleViewportExtEx
ScaleWindowExtEx
ScreenToClient
SetGraphicsMode
SetMapMode
SetViewportExtEx
SetViewportOrgEx
SetWindowExtEx
SetWindowOrgEx
SetWorldTransform


 Device Contexts

A device context is a structure that defines a set of graphic objects and their associated attributes, and the graphic modes that affect output. The graphic objects include a pen for line drawing, a brush for painting and filling, a bitmap for copying or scrolling parts of the screen, a palette for defining the set of available colors, a region for clipping and other operations, and a path for painting and drawing operations.


 About Device Contexts

One of the chief features of the Microsoft® Win32® application programming interface (API) is device independence. Win32-based applications can draw and print output on a variety of devices. The software that supports this device independence is contained in two dynamic-link libraries. The first, GDI.DLL, is referred to as the graphics device interface (GDI); the second is referred to as a device driver. The name of the second depends on the device where the application draws output. For example, if the application draws output in the client area of its window on a VGA display, this library is VGA.DLL; if the application prints output on an Epson® FX-80 printer, this library is EPSON9.DLL.

An application must inform GDI to load a particular device driver and, once the driver is loaded, to prepare the device for drawing operations (such as selecting a line color and width, a brush pattern and color, a font typeface, a clipping region, and so on). These tasks are accomplished by creating and maintaining a device context. A device context is a structure that defines a set of graphic objects and their associated attributes, and the graphic modes that affect output. The graphic objects include a pen for line drawing, a brush for painting and filling, a bitmap for copying or scrolling parts of the screen, a palette for defining the set of available colors, a region for clipping and other operations, and a path for painting and drawing operations. Unlike most of the Win32 structures, an application never has direct access to the device context; instead, it operates on the structure indirectly by calling various functions.


 Graphic Objects

The pen, brush, bitmap, palette, region, and path associated with a device context are referred to as the device context's graphic objects. Following are the attributes associated with each of these objects.

Graphic object	Associated attributes
Bitmap	Size, in bytes; dimensions, in pixels; color-format; compression scheme; and so on
Brush	Style, color, pattern, and origin
Palette	Colors and size (or number of colors)
Font	Typeface name, width, height, weight, character set, and so on
Path	Shape
Pen	Style, width, and color
Region	Location and dimensions
When an application creates a device context, Windows automatically stores a set of default objects in it. (There is no default bitmap or path.) An application can examine the attributes of the default objects by calling the GetCurrentObject and GetObject functions. The application can change these defaults by creating a new object and selecting it into the device context. An object is selected into a device context by calling the SelectObject function.


 Graphic Modes

Windows supports five graphic modes that allow an application to specify how colors are mixed, where output appears, how the output is scaled, and so on. These modes, which are stored in a device context, are described in the following table.

Mode	Description
Background mode	Defines how background colors are mixed with existing window or screen colors for bitmap and text operations.
Drawing mode	Defines how foreground colors are mixed with existing window or screen colors for pen, brush, bitmap, and text operations.
Mapping mode	Defines how graphics output is mapped from logical (or world) space onto the window, screen, or printer paper.
Polygon-fill mode	Defines how the brush pattern is used to fill the interior of complex regions.
Stretching mode	Defines how bitmap colors are mixed with existing window or screen colors when the bitmap is compressed (or scaled down).
As it does with graphic objects, Windows initializes a device context with default graphic modes. An application can retrieve and examine these default modes by calling the following functions.

Graphic mode	Function
Background mode	GetBkMode
Drawing mode	GetROP2
Mapping mode	GetMapMode
Polygon-fill mode	GetPolyFillMode
Stretching mode	GetStretchBltMode
An application can change the default modes by calling one of the following functions.

Graphic mode	Function
Background mode	SetBkMode
Drawing mode	SetROP2
Mapping mode	SetMapMode
Polygon-fill mode	SetPolyFillMode
Stretching mode	SetStretchBltMode


 Device Context Types

The Win32 API provides four types of device contexts: display, printer, memory (or compatible), and information. Each type serves a specific purpose, as described in the following table.

Device context	Purpose
Display	Supports drawing operations on a video display.
Printer	Supports drawing operations on a printer or plotter.
Memory	Supports drawing operations on a bitmap.
Information	Supports the retrieval of device data.


 Display Device Contexts

Windows provides three types of device contexts for video displays: class, common and private. Class and private device contexts are used in applications that perform numerous drawing operations such as computer-aided design (CAD) applications, desktop-publishing applications, drawing and painting applications, and so on. Common device contexts are used in applications that perform infrequent drawing operations.

An application obtains a display device context by calling either the BeginPaint or GetDC function and identifying the window in which the corresponding output will appear. (The type of device context Windows returns is dependent on how the application registered its window class.) Typically, an application obtains a display device context only when it must draw in the client area. When the application is finished drawing, it must release the device context by calling the EndPaint or ReleaseDC function.

Class Device Contexts

Class device contexts are supported strictly for compatibility with previous versions of Windows. When writing a Win32-based application, avoid using the class device context. Use a private device context instead.

Common Device Contexts

Common device contexts are display device contexts maintained in a special cache by the window-management component of the Win32 API. An application obtains a handle identifying one of the available common device contexts by calling the GetDC, GetDCEx, or BeginPaint function. Before returning this device context handle, Windows initializes a common device context with default objects, attributes, and modes. Any drawing operations performed by the application use these defaults unless one of the GDI functions is called to select a new object, change the attributes of an existing object, or select a new mode.

Because only a limited number of common device contexts exist in the window manager's heap, an application should release these device contexts after it has finished drawing. An application releases a common device context by calling the ReleaseDC or EndPaint function. When the application releases a common device context, any changes to the default data are lost.

Private Device Contexts

Private device contexts are display device contexts that, unlike common device contexts, retain any changes to the default data — even after an application calls the ReleaseDC or EndPaint function. Private device contexts are not part of the window manager's cache and therefore need not be released after use. The window manager automatically removes a private device context after the last window of that class has been destroyed.

An application creates a private device context by first specifying the CS_OWNDC window-class style when it initializes the style member of the WNDCLASS structure and calls the RegisterClass function. (For more information about window classes, see Window Classes.) After creating a window with the CS_OWNDC style, an application can call the GetDC, GetDCEx, or BeginPaint function once to obtain a handle identifying a private device context. The application can continue using this handle (and the associated device context) until it deletes the window created with this class. Any changes to graphic objects and their attributes, or graphic modes are retained by Windows until the window is deleted.


 Printer Device Contexts

Windows provides a single type of printer device context that can be used when printing on a dot-matrix printer, ink-jet printer, laser printer, or plotter. An application creates a printer device context by calling the CreateDC function and supplying the appropriate arguments (the name of the printer driver, the name of the printer, the file or device name for the physical output medium, and other initialization data). When an application has finished printing, it deletes the printer device context by calling the DeleteDC function. An application must delete (rather than release) a printer device context; the ReleaseDC function fails when an application attempts to use it to release a printer device context.


 Memory Device Contexts

Windows supports a memory device context that stores bitmapped images for a particular device. An application creates a memory device context by calling the CreateCompatibleDC function and supplying a handle that identifies a device context for a particular device. When Windows processes this call, it creates a bitmap having a color format compatible with the original device. Because the bitmap is compatible with the given device, a memory device context is also sometimes referred to as a compatible device context.

The original bitmap in a memory device context is simply a placeholder. Its dimensions are one pixel by one pixel. Before an application can begin drawing, it must select a bitmap with the appropriate width and height into the device context by calling the SelectObject function. Once the new bitmap is selected into the memory device context, an application can begin using the device context to store images. For more information about bitmaps and bitmap operations, see Bitmaps.


 Information Device Contexts

Windows supports an information device context used to retrieve default device data. For example, an application can call the CreateIC function to create an information device context for a particular model of printer and then call the GetCurrentObject and GetObject functions to retrieve the default pen or brush attributes. Because Windows can retrieve device information without creating the structures normally associated with the other types of device contexts, an information device context involves far less overhead and is created significantly faster than any of the other types. After an application finishes retrieving data by using an information device context, it must call the DeleteDC function.


 Device Context Operations

An application can perform the following operations on a device context:

•	Enumerate existing graphic objects.

•	Select new graphic objects.

•	Delete existing graphic objects.

•	Save the current graphic objects, their attributes, and the graphic modes.

•	Restore previously saved graphic objects, their attributes, and the graphic modes.

In addition, an application can use a device context to determine how graphics output is translated, cancel lengthy drawing operations (begun by a thread in a multithreaded application), or reset a printer to a particular state.


 Operations on Graphic Objects

Once an application creates a display or printer device context, it can begin drawing on the associated device or, in the case of the memory device context, it can begin drawing on the bitmap stored in memory. However, before drawing begins and sometimes while drawing is in progress, it is often necessary to replace the default objects with new objects.

An application can examine a default object's attributes by calling the GetCurrentObject and GetObject functions. The GetCurrentObject function returns a handle identifying the current pen, brush, palette, bitmap, or font, and the GetObject function initializes a structure containing that object's attributes.

Some printers provide resident pens, brushes, and fonts that can be used to improve drawing speed in an application. Two functions can be used to enumerate these objects: EnumObjects and EnumFontFamilies. If the application must enumerate resident pens or brushes, it can call the EnumObjects function to examine the corresponding attributes. If the application must enumerate resident fonts, it can call the EnumFontFamilies function (which can also enumerate GDI fonts).

Once an application determines that a default object needs replacing, it creates a new object by calling one of the following creation functions.

Graphic object	Function
Bitmap	CreateBitmap, CreateBitmapIndirect, CreateCompatibleBitmap, CreateDiscardableBitmap, CreateDIBitmap
Brush	CreateBrushIndirect, CreateDIBPatternBrush, CreateDIBPatternBrushPt, CreateHatchBrush, CreatePatternBrush, CreateSolidBrush
Color Palette	CreatePalette
Font	CreateFont, CreateFontIndirect
Pen	CreatePen, CreatePenIndirect, ExtCreatePen
Region	CreateEllipticRgn, CreateEllipticRgnIndirect, CreatePolygonRgn, CreatePolyPolygonRgn, CreateRectRgn, CreateRectRgnIndirect, CreateRoundRectRgn
Each of these functions returns a handle identifying a new object. After an application retrieves a handle, it must call the SelectObject function to replace the default object. However, the application should save the handle identifying the default object and use this handle to replace the new object when it is no longer needed. When the application finishes drawing with the new object, it must restore the default object by calling the SelectObject function and delete the new object by calling the DeleteObject function. Failing to delete objects causes serious performance problems.


 Cancellation of Drawing Operations

When complex drawing applications perform lengthy graphics operations, they consume valuable system resources. By taking advantage of Win32 multitasking features, an application can use threads and the CancelDC function to manage these operations. For example, if the graphics operation performed by thread A is consuming needed resources, thread B can call the CancelDC function to halt that operation.


 Retrieving Device Data

Windows supports two functions, GetDeviceCaps and DeviceCapabilities, that applications can use to retrieve device data using a device context. GetDeviceCaps retrieves general device data for the following devices:

•	Raster displays

•	Dot-matrix printers

•	Ink-jet printers

•	Laser printers

•	Vector plotters

•	Raster cameras

The data includes the supported capabilities of the device, including device resolution (for video displays), color format (for video displays and color printers), number of graphic objects, raster capabilities, curve drawing, line drawing, polygon drawing, and text drawing. An application retrieves this data by supplying a handle identifying the appropriate device context as well as an index specifying the type of data the function is to retrieve.

The DeviceCapabilities function retrieves data specific to printers, including the number of available paper bins, the duplex capabilities of the printer, the resolutions supported by the printer, the maximum and minimum supported paper size, and so on. An application retrieves this data by supplying strings specifying a printer device and port, as well as an index specifying the type of data that the function is to retrieve.


 Saving, Restoring, and Resetting a Device Context

The Win32 API supports three functions that an application can use to save, restore, and reset a device context: SaveDC, RestoreDC, and ResetDC. The SaveDC function records on a special GDI stack the current device context's graphic objects and their attributes, and graphic modes. A drawing application can call this function before a user begins drawing and save the application's original state — providing a "clean slate" for the user. To return to this original state, the application calls the RestoreDC function.

ResetDC is provided to reset printer device context data. An application calls this function to reset the paper orientation, paper size, output scaling factor, number of copies to be printed, paper source (or bin), duplex mode, and so on. Typically, an application calls this function after a user has changed one of the printer options and Windows has issued a WM_DEVMODECHANGE message.


 Using the Device Context Functions

•	Obtaining a private display device context

•	Creating a printer device context

•	Retrieving the capabilities of a printer

•	Retrieving graphic-object attributes and selecting new graphic objects


 Obtaining a Private Display Device Context

An application performing numerous drawing operations in the client area of its window must use a private display device context. To create this type of device context, the application must specify the CS_OWNDC constant for the style member of the WNDCLASS structure when registering the window class. After registering the window class, the application obtains a handle identifying a private display device context by calling the GetDC function.

The following example shows how to create a private display device context.

#include <windows.h>    /* required for all Windows apps */

#include <stdio.h>

#include <string.h>     /* strtok                        */

#include "dc.h"         /* specific to this program      */

/* Function prototypes */

BOOL InitApplication(HINSTANCE);

long FAR PASCAL MainWndProc(HWND, UINT, UINT, LONG);

/* Global variables */

HINSTANCE hinst;       /* handle of current instance     */

HDC hdc;               /* display device context handle  */

    .

    .

    .

BOOL InitApplication(HINSTANCE hinstance)

{

    WNDCLASS  wc;

    /*

     * Fill in the window class structure with parameters

     * describing the main window.

     */

    wc.style = CS_OWNDC;         /* Private-DC constant */

    wc.lpfnWndProc = (WNDPROC) MainWndProc;

    wc.cbClsExtra = 0;

    wc.cbWndExtra = 0;

    wc.hInstance = hinstance;

    wc.hIcon = LoadIcon((HINSTANCE) NULL,

        MAKEINTRESOURCE(IDI_APPLICATION));

    wc.hCursor = LoadCursor((HINSTANCE) NULL,

        MAKEINTRESOURCE(IDC_ARROW));

    wc.hbrBackground = GetStockObject(WHITE_BRUSH);

    wc.lpszMenuName =  "GenericMenu";

    wc.lpszClassName = "GenericWClass";

    /* Register the window class and return the

     * resultant code.

     */

    return RegisterClass(&wc);

}

LRESULT APIENTRY MainWndProc(

        HWND hwnd,           /* window handle          */

        UINT message,        /* type of message        */

        WPARAM wParam,       /* additional information */

        LPARAM lParam)       /* additional information */

{

PAINTSTRUCT ps;              /* paint structure        */

    /* Retrieve a handle identifying the private DC.   */

    hdc = GetDC(hwnd);

    switch (message) {

        case WM_PAINT:

              BeginPaint(hwnd, &ps);

        .

        . /* Draw and paint using private DC. */

        .


 Creating a Printer Device Context

An application can create a printer device context in one of two ways:

•	Calling the PrintDlg function to display a common dialog box that allows the user to specify printer options, then creating a printer device context by using those options.

•	Creating a printer device context by using the default printer data from the WIN.INI file.

This section contains code demonstrating the latter method.

To use the default printer, retrieve and parse the appropriate string from the WIN.INI file. This string is retrieved by calling the GetProfileString function and specifying the appropriate section and entry names. In the case of the default printer, this data is stored in the [windows] section and identified by the entry named device. The seventh line in the following excerpt from a WIN.INI file shows an entry for a Kodak® Diconix™ printer.

[windows]

    load=

    run=

    Beep=yes

    Spooler=yes

    NullPort=None

    device=Diconix,winspool,LPT1:

    CoolSwitch=1

    BorderWidth=3

    KeyboardSpeed=31

    InitialKeyboardIndicators=2

    CursorBlinkRate=530

    DoubleClickSpeed=686

    Programs=com exe bat pif cmd

    Documents=

    DeviceNotSelectedTimeout=15

    TransmissionRetryTimeout=45

    swapdisk=

    NetWarn=1

    fPromptOnVerbose=FALSE

    fPromptOnWarning=FALSE

    fPromptOnError=TRUE

    fPrintVerbose=FALSE

    fPrintFileLine=FALSE

    shell=

    ScreenSaveTimeOut=300

    ScreenSaveActive=0

    DebugOptions=2048

The following example shows how a printer device context was created by using the data from WIN.INI.

HDC hdcPrint;               /* printer DC handle        */

char szDevString[120];      /* array for WIN.INI data   */

char *szPrinter, *szDriver; /* printer and driver names */

char *szPort;               /* port name                */

    /*

     * Retrieve the printer, printer-driver, and

     * output-port names from WIN.INI.

     */

    GetProfileString("windows", "device", ",,,",

        szDevString, 120);

    /*

     * Parse the string of names, setting ptrs

     * as required. If the string contains the

     * required names, use them to create a

     * device context.

     */

    if ((szPrinter = strtok(szDevString,

               (const char *) ","))

            && (szDriver = strtok ((char *) NULL,

               (const char *) ", "))

            && (szPort = strtok ((char *) NULL,

               (const char *) ", ")))

        hdcPrint = CreateDC(szDriver, szPrinter,

            szPort, NULL);

    /*

     * Print a test page that contains the string

     * "PRINTER TEST" in the upper left corner.

     */

    Escape(hdcPrint, STARTDOC, 8, "Test-Doc", NULL);

    TextOut(hdcPrint, 50, 50, "PRINTER TEST", 12);

    Escape(hdcPrint, NEWFRAME, 0, NULL, NULL);

    Escape(hdcPrint, ENDDOC, 0, NULL, NULL);

    /* Delete the printer DC. */

    DeleteDC(hdcPrint);


 Retrieving the Capabilities of a Printer

Not every output device supports the entire set of Win32 graphics functions. For example, because of hardware limitations, most vector plotters do not support bit-block transfers. An application can determine whether a device supports a particular Win32 graphics function by calling the GetDeviceCaps function, specifying the appropriate index, and examining the return value.

The following example shows how an application tests a printer to determine whether it supports bit-block transfers.

/*

 * Examine the raster capabilities of the device

 * identified by hdcPrint to verify that it supports

 * the BitBlt function.

 */

if ((GetDeviceCaps(hdcPrint, RASTERCAPS)

       & RC_BITBLT) == 0) {

   DeleteDC(hdcPrint);

   break;

}

else

/* Print the bitmap using the printer DC. */


 Retrieving Graphic-Object Attributes and Selecting New Graphic Objects

An application can retrieve the attributes for a pen, brush, palette, font, or bitmap by calling the GetCurrentObject and GetObject functions. The GetCurrentObject function returns a handle identifying the object currently selected into the device context; the GetObject function returns a structure that describes the object's attributes.

The following example shows how an application can retrieve the current brush attributes and use the retrieved data to determine whether it is necessary to select a new brush.

HDC hdc;                     /* display DC handle       */

HBRUSH hbrushNew, hbrushOld; /* brush handles           */

HBRUSH hbrush;               /* brush handle            */

LOGBRUSH lb;                 /* logical-brush structure */

    /*

     * Retrieve a handle identifying the current brush.

     */

    hbrush = GetCurrentObject(hdc, OBJ_BRUSH);

    /*

     * Retrieve a LOGBRUSH structure that contains the

     * current brush attributes.

     */

    GetObject(hbrush, sizeof(LOGBRUSH), &lb);

    /*

     * If the current brush is not a solid-black brush,

     * replace it with the solid-black stock brush.

     */

    if ((lb.lbStyle != BS_SOLID)

           || (lb.lbColor != 0x000000)) {

        hbrushNew = GetStockObject(BLACK_BRUSH);

        hbrushOld = SelectObject(hdc, hbrushNew);

    }

    /* Perform painting operations with the white brush. */

    /*

     * After completing the last painting operation

     * with the new brush, the application should

     * select the original brush back into the

     * device context and delete the new brush.

     * In this example, hbrushNew contains a handle

     * to a stock object. It is not necessary (but it

     * is not harmful) to call DeleteObject on a stock

     * object. If hbrushNew contained a handle to a brush

     * created by a function such as CreateBrushIndirect,

     * it would be necessary to call DeleteObject.

     */

    SelectObject(hdc, hbrushOld);

    DeleteObject(hbrushNew);

Note that the application saved the original brush handle when calling the SelectObject function the first time. This handle is saved so that the original brush can be selected back into the device context after the last painting operation has been completed with the new brush. After the original brush is selected back into the device context, the new brush is deleted, freeing memory in the GDI heap.


 Device Context Reference

The following functions and messages are associated with device contexts.


 Device Context Functions

Following are the functions used with device contexts.

CancelDC
ChangeDisplaySettings
CreateCompatibleDC
CreateDC
CreateIC
DeleteDC
DeleteObject
DeviceCapabilities
DrawEscape
EnumDisplaySettings
EnumObjects
EnumObjectsProc
GetCurrentObject
GetDC
GetDCEx
GetDCOrgEx
GetDeviceCaps
GetGraphicsMode
GetObject
GetObjectType
GetStockObject
ReleaseDC
ResetDC
RestoreDC
SaveDC
SelectObject


 Device Context Messages

Following is the message used with device contexts.

WM_DEVMODECHANGE


 Enhanced Metafile Records

An enhanced metafile is an array of variable-length structures called enhanced metafile records. This overview contains definitions for enhanced metafile records.


 About Enhanced Metafile Records

The first records in a metafile specify general information, such as the resolution of the device on which the picture was created, the dimensions of the picture, and so on. The remaining records, which constitute the bulk of the metafile, identify the graphics device interface (GDI) functions used to create the picture.


 Enhanced Metafile Record Structure

At the beginning of every enhanced metafile record is an EMR structure, which contains two members. The first member, iType, identifies the record type — that is, the GDI function whose parameters are contained in the record. Because the structures are variable in length, the other member, nSize, contains the size of the record. Immediately following the nSize member are the remaining parameters, if any, of the GDI function.


 Playing Back Enhanced Metafiles

Applications can play back enhanced metafiles using the PlayEnhMetaFile or EnumEnhMetaFile function. If using PlayEnhMetaFile to draw the picture, you pass a handle to the enhanced metafile without being concerned with the format of the enhanced metafile records. However, it is sometimes desirable to enumerate the records in the enhanced metafile to search for a particular GDI function and modify the parameters of the function in some manner. To do this, you can use EnumEnhMetaFile and provide a callback function of the type ENHMFENUMPROC to process the enhanced metafile records. To modify the parameters for an enhanced metafile record, you must know the format of the parameters within the record.


 Enhanced Metafile Reference

The following structures are used with enhanced metafile records. Note that the first structure, EMR, is used as the first member of the remaining structures.

EMR
EMRANGLEARC
EMRARC, EMRARCTO, EMRCHORD, EMRPIE
EMRBITBLT
EMRCREATEBRUSHINDIRECT
EMRCREATECOLORSPACE
EMRCREATEDIBPATTERNBRUSHPT
EMRCREATEMONOBRUSH
EMRCREATEPALETTE
EMRCREATEPEN
EMRELLIPSE, EMRRECTANGLE
EMREOF
EMREXCLUDECLIPRECT, EMRINTERSECTCLIPRECT
EMREXTCREATEFONTINDIRECTW
EMREXTCREATEPEN
EMREXTFLOODFILL
EMREXTSELECTCLIPRGN
EMREXTTEXTOUTA, EMREXTTEXTOUTW
EMRFILLRGN
EMRFRAMERGN
EMRGDICOMMENT
EMRINVERTRGN, EMRPAINTRGN
EMRLINETO, EMRMOVETOEX
EMRMASKBLT
EMRMODIFYWORLDTRANSFORM
EMROFFSETCLIPRGN
EMRPLGBLT
EMRPOLYDRAW
EMRPOLYDRAW16
EMRPOLYPOLYLINE, EMRPOLYPOLYGON
EMRPOLYPOLYLINE16, EMRPOLYPOLYGON16
EMRPOLYTEXTOUTA, EMRPOLYTEXTOUTW
EMRRESIZEPALETTE
EMRRESTOREDC
EMRROUNDRECT
EMRSELECTOBJECT, EMRDELETEOBJECT
EMRSELECTPALETTE
EMRSETARCDIRECTION
EMRSETCOLORADJUSTMENT
EMRSETDIBITSTODEVICE
EMRSETMAPPERFLAGS
EMRSETBKCOLOR, EMRSETTEXTCOLOR
EMRSETMITERLIMIT
EMRSETPALETTEENTRIES
EMRSETPIXELV
EMRSETWORLDTRANSFORM
EMRSTRETCHDIBITS
EMRSTRETCHBLT
EMRTEXT
EMRFILLPATH, EMRSTROKEANDFILLPATH, EMRSTROKEPATH
EMRPOLYLINE, EMRPOLYBEZIER, EMRPOLYGON, EMRPOLYBEZIERTO, EMRPOLYLINETO
EMRPOLYLINE16, EMRPOLYBEZIER16, EMRPOLYGON16, EMRPOLYBEZIERTO16, EMRPOLYLINETO16
EMRSCALEVIEWPORTEXTEX, EMRSCALEWINDOWEXTEX
EMRSELECTCOLORSPACE, EMRDELETECOLORSPACE
EMRSETVIEWPORTORGEX, EMRSETWINDOWORGEX, EMRSETBRUSHORGEX
EMRSETVIEWPORTEXTEX, EMRSETWINDOWEXTEX


 Enhanced Metafile Records with No Parameters

typedef struct tagABORTPATH

{

    EMR emr;

} EMRABORTPATH,      *PEMRABORTPATH,
  EMRBEGINPATH,      *PEMRBEGINPATH,
  EMRENDPATH,        *PEMRENDPATH,
  EMRCLOSEFIGURE,    *PEMRCLOSEFIGURE,
  EMRFLATTENPATH,    *PEMRFLATTENPATH,
  EMRWIDENPATH,      *PEMRWIDENPATH,
  EMRSETMETARGN,     *PEMRSETMETARGN,
  EMRSAVEDC,         *PEMRSAVEDC,
  EMRREALIZEPALETTE, *PEMRREALIZEPALETTE;

Contains data for the AbortPath, BeginPath, EndPath, CloseFigure, FlattenPath, WidenPath, SetMetaRgn, SaveDC, and RealizePalette enhanced metafile records.


 Enhanced Metafile Records with One Parameter

typedef struct tagEMRSELECTCLIPPATH
{
    EMR   emr;

    DWORD iMode;

} EMRSELECTCLIPPATH,    *PEMRSELECTCLIPPATH,
  EMRSETBKMODE,         *PEMRSETBKMODE,
  EMRSETMAPMODE,        *PEMRSETMAPMODE,
  EMRSETPOLYFILLMODE,   *PEMRSETPOLYFILLMODE,
  EMRSETROP2,           *PEMRSETROP2,
  EMRSETSTRETCHBLTMODE, *PEMRSETSTRETCHBLTMODE,
  EMRSETTEXTALIGN,      *PEMRSETTEXTALIGN,
  EMRENABLEICM,         *PEMRENABLEICM

Contains parameters for the SelectClipPath, SetBkMode, SetPolyFillMode, SetROP2, SetStretchBltMode, SetTextAlign, and EnableICM enhanced metafile records.

Members

emr

Base structure for all record types.

iMode

Value and meaning that varies depending on the function contained in the enhanced metafile record. For a description of this member, see the documentation of the functions contained in this record .

See Also

SelectClipPath, SetBkMode, SetPolyFillMode, SetROP2, SetStretchBltMode, SetTextAlign


 Filled Shapes

Filled shapes are geometric shapes that are outlined by using the current pen and filled by using the current brush. There are five filled shapes: ellipse, chord, pie, polygon, and rectangle.


 About Filled Shapes

An application written for Microsoft® Windows® uses filled shapes in a variety of ways. Spreadsheet applications, for example, use filled shapes to construct charts and graphs, and drawing and painting applications use filled shapes to allow the user to draw figures and illustrations.


 About Ellipses

An ellipse is a closed curve defined by two fixed points (f1 and f2) such that the sum of the distances (d1 + d2) from any point on the curve to the two fixed points is constant. The following illustration shows an ellipse drawn by using the Ellipse function.

When calling Ellipse, an application supplies the coordinates of the upper left and lower right corners of the ellipse's bounding rectangle. A bounding rectangle is the smallest rectangle completely surrounding the ellipse. When Windows draws the ellipse, it excludes the right and lower sides if no world transformations are set. Therefore, for any rectangle measuring x units wide by y units high, the associated ellipse measures x−1 units wide by y−1 units high. If the application sets a world transformation by calling the SetWorldTransform or ModifyWorldTransform function, Windows includes the right and lower sides.


 About Chords

A chord is a region bounded by the intersection of an ellipse and a line segment called a secant. The following illustration shows a chord drawn by using the Chord function.

When calling Chord, an application supplies the coordinates of the upper left and lower right corners of the ellipse's bounding rectangle, as well as the coordinates of two points defining two radials. A radial is a line drawn from the center of an ellipse's bounding rectangle to a point on the ellipse.

When Windows draws the curved part of the chord, it does so by using the current arc direction for the specified device context. The default arc direction is counterclockwise. You can have your application reset the arc direction by calling the SetArcDirection function.


 About Pies

A pie is a region bounded by the intersection of an ellipse curve and two radials. The following illustration shows a pie drawn by using the Pie function.

When calling Pie, an application supplies the coordinates of the upper left and lower right corners of the ellipse's bounding rectangle, as well as the coordinates of two points defining two radials.

When Windows draws the curved part of the pie, it uses the current arc direction for the given device context. The default arc direction is counterclockwise. An application can reset the arc direction by calling the SetArcDirection function.


 About Polygons

A polygon is a filled shape with straight sides. The sides of a polygon are drawn by using the current pen. When Windows fills a polygon, it uses the current brush and the current polygon fill mode. The two fill modes — alternate (the default) and winding — determine whether regions within a complex polygon are filled or left unpainted. An application can select either mode by calling the SetPolyFillMode function. For more information about polygon fill modes, see Regions.

The following illustration shows a polygon drawn by using Polygon.

In addition to drawing a single polygon by using Polygon, an application can draw multiple polygons by using the PolyPolygon function.


 Drawing Rectangles

A rectangle is a four-sided polygon whose opposing sides are parallel and equal in length. Although an application can draw a rectangle by calling the Polygon function, supplying the coordinates of each corner, Windows provides a simpler method, use of the Rectangle function. This function requires only the coordinates for the upper left and the lower right corners. When an application calls the Rectangle function, Windows draws the rectangle, excluding the right and lower sides if no world transformation is set for the given device context.

If a world transformation has been set by using the SetWorldTransform or ModifyWorldTransform function, Windows includes the right and lower edges.

In addition to drawing a normal rectangle, the Microsoft® Win32® application programming interface (API) provides a function that applications can use to draw rectangles with rounded corners. This function, RoundRect, requires that the application supply the coordinates of the lower left and upper right corners, as well as the width and height of the ellipse used to round each corner.

The Win32 API also provides three functions that applications can use to manipulate rectangles, described as follows.

Function	Description
FillRect	Repaints the interior of a rectangle.
FrameRect	Redraws the sides of a rectangle.
InvertRect	Inverts the colors that appear within the interior of a rectangle.


 Using Filled Shapes

This section illustrates how to use filled shape functions. The example uses the main window procedure from an application that enables the user to draw ellipses, rectangles, and rectangles with rounded corners.

The user draws a filled shape by selecting a particular shape from the menu, positioning the cursor at the upper left corner of the shape (or the shape's bounding rectangle in the case of an ellipse), and then dragging the mouse until the desired dimensions are obtained.

The following illustration shows three filled shapes drawn using the sample code in this section.

To enable the user to draw filled shapes, include the following code in your application.

LRESULT APIENTRY MainWndProc(hwnd, uMsg, wParam, lParam)

HWND hwnd;      /* handle of window         */

UINT uMsg;      /* message                  */

WPARAM wParam;  /* first message parameter  */

LPARAM lParam;  /* second message parameter */

{

    HDC hdc;         /* handle of device context (DC)   */

    PAINTSTRUCT ps;  /* paint data for Begin/EndPaint   */

    POINT ptClientUL; /* client area upper left corner  */

    POINT ptClientLR; /* client area lower right corner */

    static HDC hdcCompat;/* handle of DC for bitmap     */

    static POINT pt;     /* x- and y-coordinates of cursor    */

    static RECT rcTarget; /* rect to receive filled shape     */

    static RECT rcClient; /* client area rectangle            */

    static BOOL fSizeEllipse; /* TRUE if ellipse is sized     */

    static BOOL fDrawEllipse;   /* TRUE if ellipse is drawn   */

    static BOOL fDrawRectangle; /* TRUE if rectangle is drawn */

    static BOOL fSizeRectangle; /* TRUE if rectangle is sized */

    static BOOL fSizeRoundRect; /* TRUE if rounded rect is sized */

    static BOOL fDrawRoundRect; /* TRUE if rounded rect is drawn */

    static int nEllipseWidth;   /* width for round corners       */

    static int nEllipseHeight;  /* height for round corners      */

    switch (uMsg) {

        case WM_COMMAND:

            switch (wParam) {

                /*

                 * Set the appropriate flag to indicate which

                 * filled shape the user is drawing.

                 */

                case IDM_ELLIPSE:

                    fSizeEllipse = TRUE;

                break;

                case IDM_RECTANGLE:

                    fSizeRectangle = TRUE;

                break;

                case IDM_ROUNDRECT:

                    fSizeRoundRect = TRUE;

                break;

                default:

                    return DefWindowProc(hwnd, uMsg, wParam,

                         lParam);

            }

            break;

        case WM_CREATE:

            nEllipseWidth = 20;

            nEllipseHeight = 20;

            return 0;

        case WM_PAINT:

            BeginPaint(hwnd, &ps);

            /*

             * Because the default brush is white, select

             * a different brush into the device context

             * to demonstrate the painting of filled shapes.

             */

            SelectObject(ps.hdc, GetStockObject(GRAY_BRUSH));

            /*

             * If one of the filled shape "draw" flags is TRUE,

             * draw the corresponding shape.

             */

            if (fDrawEllipse) { /* draws ellipse */

                Ellipse(ps.hdc, rcTarget.left, rcTarget.top,

                    rcTarget.right, rcTarget.bottom);

                    fDrawEllipse = FALSE;

                    rcTarget.left = rcTarget.right = 0;

                    rcTarget.top = rcTarget.bottom = 0;

                    }

            if (fDrawRectangle) { /* Draws rectangle */

                Rectangle(ps.hdc, rcTarget.left, rcTarget.top,

                    rcTarget.right, rcTarget.bottom);

                    fDrawRectangle = FALSE;

                    rcTarget.left = rcTarget.right = 0;

                    rcTarget.top = rcTarget.bottom = 0;

                    }

            if (fDrawRoundRect) { /* Draws rounded rectangle */

                RoundRect(ps.hdc, rcTarget.left, rcTarget.top,

                    rcTarget.right, rcTarget.bottom,

                    nEllipseWidth, nEllipseHeight);

                    fDrawRectangle = FALSE;

                    rcTarget.left = rcTarget.right = 0;

                    rcTarget.top = rcTarget.bottom = 0;

                    }

            EndPaint(hwnd, &ps);

            break;

        case WM_SIZE:

            /*

             * Convert the client coordinates of the client area

             * rectangle to screen coordinates and save them in a

             * rectangle. The rectangle is passed to the ClipCursor

             * function during WM_LBUTTONDOWN processing.

             */

            GetClientRect(hwnd, &rcClient);

            ptClientUL.x = rcClient.left;

            ptClientUL.y = rcClient.top;

            ptClientLR.x = rcClient.right;

            ptClientLR.y = rcClient.bottom;

            ClientToScreen(hwnd, &ptClientUL);

            ClientToScreen(hwnd, &ptClientLR);

            SetRect(&rcClient, ptClientUL.x, ptClientUL.y,

                ptClientLR.x, ptClientLR.y);

            return 0;

        case WM_LBUTTONDOWN:

            /*

             * Restrict the cursor to the client area.

             * This ensures that the window receives a matching

             * WM_LBUTTONUP message.

             */

            ClipCursor(&rcClient);

            /* Save the coordinates of the cursor. */

            pt.x = (LONG) LOWORD(lParam);

            pt.y = (LONG) HIWORD(lParam);

            /*

             * If the user chooses one of the filled shapes,

             * set the appropriate flag to indicate that the

             * shape is being sized.

             */

             if (fDrawEllipse)

                fSizeEllipse = TRUE;

            return 0;

        case WM_MOUSEMOVE:

            /*

             * If one of the "size" flags is set, draw

             * the target rectangle as the user drags

             * the mouse.

             */

            if ((wParam && MK_LBUTTON)

                    && (fSizeEllipse || fSizeRectangle

                    || fSizeRoundRect)) {  /* draws target rect. */

                /*

                 * Set the mixing mode so that the pen color is the

                 * inverse of the background color. The previous

                 * rectangle can then be erased by drawing

                 * another rectangle on top of it.

                 */

                hdc = GetDC(hwnd);

                SetROP2(hdc, R2_NOTXORPEN);

                /*

                 * If a previous target rectangle exists, erase

                 * it by drawing another rectangle on top.

                 */

                 if (!IsRectEmpty(&rcTarget))

                     Rectangle(hdc, rcTarget.left, rcTarget.top,

                         rcTarget.right, rcTarget.bottom);

                /*

                 * Save the coordinates of the target rectangle.

                 * Avoid invalid rectangles by ensuring that the

                 * value of the left coordinate is greater than

                 * that of the right, and that the value of the

                 * bottom coordinate is greater than that of

                 * the top.

                 */

                if ((pt.x < (LONG) LOWORD(lParam)) &&

                        (pt.y > (LONG) HIWORD(lParam)))

                    SetRect(&rcTarget, pt.x, HIWORD(lParam),

                        LOWORD(lParam), pt.y);

                else if ((pt.x > (LONG) LOWORD(lParam)) &&

                        (pt.y > (LONG) HIWORD(lParam)))

                    SetRect(&rcTarget, LOWORD(lParam),

                        HIWORD(lParam), pt.x, pt.y);

                else if ((pt.x > (LONG) LOWORD(lParam)) &&

                        (pt.y < (LONG) HIWORD(lParam)))

                    SetRect(&rcTarget, LOWORD(lParam), pt.y,

                        pt.x, HIWORD(lParam));

                else

                    SetRect(&rcTarget, pt.x, pt.y, LOWORD(lParam),

                        HIWORD(lParam));

                /* Draw the new target rectangle. */

                Rectangle(hdc, rcTarget.left, rcTarget.top,

                    rcTarget.right, rcTarget.bottom);

                ReleaseDC(hwnd, hdc);

            }

            return 0;

        case WM_LBUTTONUP:

            /*

             * If one of the "size" flags is TRUE, reset

             * it to FALSE, and then set the corresponding

             * "draw" flag.

             * Invalidate the appropriate rectangle and issue

             * a WM_PAINT message.

             */

             if (fSizeEllipse) {

                 fSizeEllipse = FALSE;

                 fDrawEllipse = TRUE;

                }

             if (fSizeRectangle) {

                 fSizeRectangle = FALSE;

                 fDrawRectangle = TRUE;

                }

             if (fSizeRoundRect) {

                 fSizeRoundRect = FALSE;

                 fDrawRoundRect = TRUE;

                }

             if (fDrawEllipse || fDrawRectangle || fDrawRoundRect)

               {

                 InvalidateRect(hwnd, &rcTarget, TRUE);

                 UpdateWindow(hwnd);

                }

            /* Release the cursor. */

            ClipCursor((LPRECT) NULL);

            return 0;

        case WM_DESTROY:

            /*

             * Destroy the background brush, compatible bitmap,

             * and bitmap.

             */

            DeleteDC(hdcCompat);

            PostQuitMessage(0);

            break;

        default:

            return DefWindowProc(hwnd, uMsg, wParam, lParam);

    }

    return (LRESULT) NULL;

}


 Filled Shape Functions

The following functions are used with filled shapes.

Chord
Ellipse
FillRect
FrameRect
InvertRect
Pie
Polygon
PolyPolygon
Rectangle
RoundRect


 Fonts and Text

Fonts are used to draw text on video displays and other output devices. The Microsoft® Windows® operating system provides a set of functions that developers can use to install, select, and query different fonts.


 About Fonts

To a person trained in the mechanics of manuscript composition or familiar with standard typography, some of the typographic terms used in Windows may be unusual. Most of the differences between standard typography and Windows reflect changes in technology. The original typographic terms were based on hot-metal composition, whereas the terms used in Windows, which appear as member names for the font and text output structures, reflect a new technology based on laser-printer output and composition performed on a personal computer using desktop publishing software.


 Fonts Overview

In Windows, a font is a collection of characters and symbols that share a common design. The three major elements of this design are referred to as typeface, style, and size.

Typeface

The term typeface refers to specific characteristics of characters and symbols in the font, such as the width of the thick and thin strokes that compose the characters and the presence or absence of serifs. A serif is the short cross line at the ends of an unconnected stroke. A font or typeface without serifs is usually called a sans-serif font.

Style

The term style refers to the weight and slant of a font. Font weights can range from thin to black. The following list identifies possible weights for Windows fonts (beginning with the lightest and ending with the heaviest).

Thin
Extralight
Light
Normal
Medium
Semibold
Bold
Extrabold
Heavy

Three terms categorize the slant of a Windows font: roman, oblique, and italic.

The characters in a roman font are upright. The characters in an oblique font are artificially slanted. The slant is achieved by performing a shear transformation on the characters from a roman font. The characters in an italic font are truly slanted and appear as they were designed. For more information on shearing, see Coordinate Spaces and Transformations.

Size

In Windows, the size of a font is an imprecise value. It can generally be determined by measuring the distance from the bottom of a lowercase "g" to the top of an adjacent uppercase "M," as shown in the following illustration.

A font's size is specified in units called points. A point is .013837 of an inch. Following the point system devised by Pierre Simon Fournier, it is common practice to approximate a point as 1/72 inch.


 Font Families

Windows organizes fonts by family; a family is a set of fonts having common stroke width and serif characteristics. Windows categorizes families with five family names. A sixth name ("Dontcare") allows an application to use the default font. The following table describes the font-family names.

Font-family name	Description
Decorative	Specifies a novelty font. An example is Old English.
Dontcare	Specifies a generic family name. This name is used when information about a font does not exist or does not matter.
Modern	Specifies a monospace font with or without serifs. Monospace fonts are usually modern; examples include Pica, Elite, and Courier New®.
Roman	Specifies a proportional font with serifs. An example is Times New Roman.
Script	Specifies a font that is designed to look like handwriting; examples include Script and Cursive.
Swiss	Specifies a proportional font without serifs. An example is Arial.
These family names correspond to constants found in the WINGDI.H file: FF_DECORATIVE, FF_DONTCARE, FF_MODERN, FF_ROMAN, FF_SCRIPT, and FF_SWISS. An application uses these constants when it creates a font, selects a font, or retrieves information about a font.

Fonts within a family are distinguished by size (10 point, 24 point, etc.) and style (regular, italic, etc.).


 Raster, Vector, and TrueType® Fonts

Windows-based applications can use three different kinds of font technologies to display and print text: raster, vector, and TrueType. The differences between these fonts reflect the way that the glyph for each character or symbol is stored in the respective font-resource file. In raster fonts, a glyph is a bitmap that Windows uses to draw a single character or symbol in the font. In vector fonts, a glyph is a collection of line endpoints that define the line segments Windows uses to draw a character or symbol in the font. In TrueType fonts, a glyph is a collection of line and curve commands as well as a collection of hints. Windows uses the line and curve commands to define the outline of the bitmap for a character or symbol in the TrueType font. Windows uses the hints to adjust the length of the lines and shapes of the curves used to draw the character or symbol. These hints and the respective adjustments are based on the amount of scaling used to reduce or increase the size of the bitmap.

Because the bitmaps for each glyph in a raster font are designed for a specific resolution of device, raster fonts are generally considered to be device dependent. Vector fonts, on the other hand, are not device dependent, because each glyph is stored as a collection of scalable lines. However, vector fonts are generally drawn more slowly than raster or TrueType fonts. TrueType fonts provide both relatively fast drawing speed and true device independence. By using the hints associated with a glyph, a developer can scale the characters from a TrueType font up or down and still maintain their original shape.

As previously mentioned, the glyphs for a font are stored in a font-resource file. A font-resource file is actually a Windows library that contains only data — there is no code. For raster and vector fonts, this data is divided into two parts: a header describing the font's metrics and the glyph data. A font-resource file for a raster or vector font is identified by the .FON filename extension. For TrueType fonts, there are two files for each font: the first file contains a relatively short header and the second contains the actual font data. The first file is identified by a .FOT extension and the second is identified by a .TTF extension.


 Character Sets Used by Fonts

All fonts use a character set. A character set contains punctuation marks, numerals, uppercase and lowercase letters, and all other printable characters. Each element of a character set is identified by a number.

Most character sets used in Windows are supersets of the U.S. ASCII character set, which defines characters for the 96 numeric values from 32 through 127. There are five major groups of character sets:

•	Windows

•	Unicode™

•	OEM (original equipment manufacturer)

•	Symbol

•	Vendor-specific

Windows Character Set

The Windows character set is the most commonly used character set in Windows programming. It is essentially equivalent to the ANSI character set. The blank character is the first character in the Windows character set. It has a hexadecimal value of 0x20 (decimal 32). The last character in the Windows character set has a hexadecimal value of 0xFF (decimal 255).

Many fonts specify a default character. Whenever a request is made for a character that is not in the font, Windows provides this default character. Many fonts using the Windows character set specify the period (.) as the default character. TrueType fonts typically use an open box as the default character.

Fonts use a break character called a quad to separate words and justify text. Most fonts using the Windows character set specify that the blank character will serve as the break character.

Windows version 3.1 added 24 characters to the Windows code page, as shown in the following table.

Character	Name	Windows character code
‚	base line single quote	130
ƒ	florin	131
„	base line double quote	132
…	ellipsis	133
†	dagger	134
‡	double dagger	135
ˆ	circumflex	136
‰	permille	137
Š	S Hacek	138
‹	left single guillemet	139
Œ	OE ligature	140
'	left single quote	145
'	right single quote	146
"	left double quote	147
"	right double quote	148
•	bullet	149
−	en dash	150
—	em dash	151
˜	tilde	152
™	trademark ligature	153
š	s Hacek	154
›	right single guillemet	155
œ	oe ligature	156
Ÿ	Y Dieresis	159
It should be noted that the characters for left and right single quote were first added to the character set for the release of Windows version 3.0.

Unicode™ Character Set

The Windows ANSI character uses 8 bits to represent each character; therefore, the maximum number of characters that can be expressed using 8 bits is 256 (2^8). This is usually sufficient for Western languages, including the diacritical marks used in French, German, Spanish, and other languages. However, Eastern languages employ thousands of separate characters, which cannot be encoded by using a single-byte coding scheme. With the proliferation of computer commerce, double-byte coding schemes were developed so that characters could be represented in 8-bit, 16-bit, 24-bit, or 32-bit sequences. This requires complicated passing algorithms; even so, using different code sets could yield entirely different results on two different computers.

To address the problem of multiple coding schemes, the Unicode standard for data representation was developed. A 16-bit character coding scheme, Unicode can represent 65,536 (2^16) characters, which is enough to include all languages in computer commerce today, as well as punctuation marks, mathematical symbols, and room for future expansion. Unicode establishes a unique code for every character to ensure that character translation is always accurate.

OEM Character Set

The OEM character set is typically used in full-screen MS-DOS® sessions for screen display. Characters 32 through 127 are usually the same in the OEM, U.S. ASCII, and Windows character sets. The other characters in the OEM character set (0 through 31 and 128 through 255) correspond to the characters that can be displayed in a full-screen MS-DOS session. These characters are generally different from the Windows characters.

Symbol Character Set

The Symbol character set contains special characters typically used to represent mathematical and scientific formulas.

Vendor-Specific Character Sets

Many printers and other output devices provide fonts based on character sets that differ from the Windows and OEM sets — for example, the Extended Binary Coded Decimal Interchange Code (EBCDIC) character set. To use one of these character sets, the printer driver translates from the Windows character set to the vendor-specific character set.


 Font Installation and Deletion

A font must already be resident on a given device or installed in the Windows font table in order for an application to draw text using glyphs from that font. The Windows font table is an internal array that identifies all nondevice fonts that are available to a Windows-based application. An application can retrieve the names of fonts currently installed on a device and stored in the internal font table by calling the EnumFontFamilies or ChooseFont function.

An application can install a font by calling the font-installation function AddFontResource. The AddFontResource function loads a font that is stored in a font-resource file.

In the case of TrueType fonts, an additional step is sometimes necessary before the font can be installed in the font table. Some font manufacturers ship only the TrueType font-data files (identified by the .TTF extension). Before Windows can load these fonts, it requires a corresponding header file (identified by the .FOT extension). To create this header file, an application must call the CreateScalableFontResource function and pass the name of the font-data file as the third parameter. When this header file is created, an application can install the font by calling the AddFontResource function and passing the name of the new header file.

When an application finishes using an installed font, it must remove that font by calling the RemoveFontResource function.

Whenever an application calls the functions that add and delete font resources, it should also call the SendMessage function and send a WM_FONTCHANGE message to all top-level windows in the system. This message notifies other applications that the internal font table has been altered by an application that added or removed a font.


 Font Creation and Selection

Previous versions of Windows required that the application developer provide source code and a dialog box template to support an interface that displayed the available fonts from which the user could choose. The new Font common dialog box simplifies the creation and selection process. By initializing the CHOOSEFONT structure and calling the ChooseFont function, an application can support the same font-selection interface that previously required many lines of code. (For more information about the Font common dialog box, see Common Dialog Box Library.)

Selection by the User

Most font creation and selection operations involve the user. For example, word processing applications let the user select unique fonts for headings, footnotes, and body text. After the user selects a font by using the Font dialog box and presses the OK button, the ChooseFont function initializes the members of a LOGFONT structure with the attributes of the requested font. To use this font for text-output operations, an application must first create a logical font and then select that font into its device context. A logical font is an application-supplied description of an ideal font. A developer can create a logical font by calling the CreateFont or the CreateFontIndirect functions. In this case, the application would call CreateFontIndirect and supply a pointer to the LOGFONT structure initialized by ChooseFont. In general, it is more efficient to call CreateFontIndirect because CreateFont requires several parameters while CreateFontIndirect requires only one — a pointer to LOGFONT.

Before an application can actually begin drawing text with a logical font, it must find the closest match from the fonts stored internally on the device and the fonts whose resources have been loaded into the operating system. The fonts stored on the device or in the operating system are called physical fonts. The process of finding the physical font that most closely matches a specified logical font is called font mapping. This process occurs when an application calls the SelectObject function and supplies a handle identifying a logical font. Font mapping is performed by using an internal algorithm that compares the attributes of the requested logical font against the attributes of available physical fonts. When the font mapper algorithm completes its search and determines the closest possible match, the SelectObject function returns and the application can begin drawing text with the new font.

The SetMapperFlags function specifies whether or not the font mapper algorithm searches only for physical fonts with aspect ratios that match the physical device. The aspect ratio for a device is the ratio formed by the width and the height of a pixel on that device.


 Special Font Selection Considerations

Although most font selection operations involve the user, there are some instances where this is not true. For example, a developer may want to use a unique font in an application to draw text in a control window. To select an appropriate font, the application must be able to determine what fonts are available, create a logical font that describes one of these available fonts, and then select that font into the appropriate device context.

An application can enumerate the available fonts by using the EnumFontFamilies function. This can be useful when an application must determine which fonts are available from a given family.

Once an application has enumerated the available fonts and located an appropriate match, it should use the values returned by the font enumeration function to initialize the members of a LOGFONT structure. Then it can call the CreateFontIndirect function, passing to it a pointer to the initialized LOGFONT structure. If the CreateFontIndirect function is successful, the application can then select the logical font by calling the SelectObject function.

When initializing the members of the LOGFONT structure, be sure to specify a specific character set in the lfCharSet member. This member is important in the font mapping process and the results will be inconsistent if this member is not initialized correctly. If you specify a typeface name in the lfFaceName member of the LOGFONT structure, make sure that the lfCharSet value matches the character set of the typeface specified in lfFaceName. For example, if you want to select a font such as "MS Mincho", lfCharSet must be set to the predefined value SHIFTJIS_CHARSET.


 Embedded Fonts

Embedding a font is the technique of bundling a document and the fonts it contains into a file for transmission to another computer. Embedding a font guarantees that a font specified in a transmitted file will be present on the computer receiving the file. Not all fonts can be moved from computer to computer, however, since most fonts are licensed to only one computer at a time. In Windows, only TrueType fonts can be embedded.

Applications should embed a font in a document only when requested by a user. An application cannot be distributed along with documents that contain embedded fonts, nor can an application itself contain an embedded font. Whenever an application distributes a font, in any format, the proprietary rights of the owner of the font must be acknowledged.

It may be a violation of a font vendor's proprietary rights or user license agreement to embed any fonts where embedding is not permitted or to fail to observe the following guidelines on embedding fonts. A font's license may give only read-write permission for a font to be installed and used on the destination computer. Or the license may give read-only permission. Read-only permission allows a document to be viewed and printed (but not modified) by the destination computer; documents with read-only embedded fonts are themselves read-only. Read-only embedded fonts may not be unbundled from the document and installed on the destination computer.

An application can determine the license status by calling the GetOutlineTextMetrics function and examining the otmfsType member of the OUTLINETEXTMETRIC structure. If bit 1 of otmfsType is set, embedding is not permitted for the font. If bit 1 is clear, the font can be embedded. If bit 2 is set, the embedding is read-only.

To embed a font, an application can use the GetFontData function to read the font file. Setting the dwTable and dwOffset parameters of GetFontData to 0L and the cbData parameter to −1L ensures that the application reads the entire font file from the beginning.

After an application retrieves the font data, it can store the data with the document by using any applicable format. Most applications build a font directory in the document, listing the embedded fonts and whether the embedding is read-write or read-only. An application can use the otmpStyleName and otmFamilyName members of the OUTLINETEXTMETRIC structure to identify the font.

If the read-only bit is set for the embedded font, applications must encrypt the font data before storing it with the document. The encryption method need not be complicated; for example, using the XOR operator to combine the font data with an application-defined constant is adequate and fast.


 About Text Output

Text output is the most common type of graphic output found within the client area of Windows-based applications. It is used by Windows-based applications in different ways. Word processing and desktop publishing applications create documents with formatted text; spreadsheet applications use text, numbers, and symbols to specify formulas, label columns, and list values; database applications create records and display queries with text, and CAD applications use text to label objects and display dimensions.

The Win32® application programming interface (API) provides a complete set of functions to format and draw text in an application's client area and on a page of printer paper. These functions can be divided into two categories: those that format the text (or prepare it for output) and those that actually draw the text. The formatting functions align text, set the intercharacter spacing, set the text and text-background colors, and justify text. The drawing functions draw individual characters (or symbols) or entire strings of text.


 Formatting Text

The formatting functions can be divided into three categories: those that retrieve or set the text-formatting attributes for a device context, those that retrieve character widths, and those that retrieve string widths and heights.


 Text-Formatting Attributes

An application can use six functions to set the text-formatting attributes for a device context: SetBkColor, SetBkMode, SetTextAlign, SetTextCharacterExtra, SetTextColor, and SetTextJustification. These functions affect the text alignment, the intercharacter spacing, the text justification, and text and background colors. In addition, six other functions can be used to retrieve the current text formatting attributes for any device context: GetBkColor, GetBkMode, GetTextAlign, GetTextCharacterExtra, GetTextColor, and GetTextExtentPoint32.

Text Alignment

Applications can use the SetTextAlign function to specify how Windows should position the characters in a string of text when they call one of the drawing functions. This function can be used to position headings, page numbers, callouts, and so on. Windows positions a string of text by aligning a reference point on an imaginary rectangle that surrounds the string, with the current cursor position or with a point passed as an argument to one of the text drawing functions. The SetTextAlign function lets the application specify the location of this reference point. The list below identifies the possible reference point locations.

Location	Description
left/bottom	The reference point is located at the bottom left corner of the rectangle.
left/base line	The reference point is located at the intersection of the character-cell base line and the left edge of the rectangle.
left/top	The reference point is located at the top left corner of the rectangle.
center/bottom	The reference point is located at the center of the bottom of the rectangle.
center/base line	The reference point is located at the intersection of the character-cell base line and the center of the rectangle.
center/top	The reference point is located at the center of the top of the rectangle.
right/bottom	The reference point is located at the bottom right corner of the rectangle.
right/base line	The reference point is located at the intersection of the character-cell base line and the right edge of the rectangle.
right/top	The reference point is located at the top right corner of the rectangle.
The following illustration shows a string of text drawn by calling the TextOut function. Before drawing the text, the SetTextAlign function was called to relocate the reference point at each one of the nine possible locations.

The default text alignment for a device context is the upper left corner of the imaginary rectangle that surrounds the text. An application can retrieve the current text-alignment setting for any device context by calling the GetTextAlign function.

Intercharacter Spacing

Applications can use the SetTextCharacterExtra function to alter the intercharacter spacing for all text output operations in a given device context. The following illustration shows a string of text drawn twice by calling the TextOut function. Before drawing the text the second time, the SetTextCharacterExtra function was called to increment the intercharacter spacing.

The default intercharacter spacing value for any device context is zero. An application can retrieve the current intercharacter spacing value for a device context by calling the GetTextCharacterExtra function.

Text Justification

Applications can use the GetTextExtentPoint32 and SetTextJustification functions to justify a line of text. Text justification is a common operation in any desktop publishing and in most word processing applications. The GetTextExtentPoint32 function computes the width and height of a string of text. After the width is computed, the application can call the SetTextJustification function to distribute extra spacing between each of the words in a line of text. The following illustration shows a paragraph of text printed twice: in the first paragraph, the text was not justified; in the second paragraph, the text was justified by calling the GetTextExtentPoint32 and SetTextJustification functions.

Text and Background Color

Applications can use the SetTextColor function to set the color of text drawn in the client-area of their windows, as well as the color of text drawn on a color printer. An application can use the SetBkColor function to set the color that appears behind each character and the SetBkMode function to specify how Windows should blend the selected background color with the current color or colors on the video display.

The default text color for a display device context is black; the default background color is white; and the default background mode is OPAQUE. An application can retrieve the current text color for a device context by calling the GetTextColor function. An application can retrieve the current background color for a device context by calling the GetBkColor function and the current background mode by calling the GetBkMode function.


 Character Widths

Applications need to retrieve character-width data when they perform such tasks as fitting strings of text to page or column widths. There are four functions that an application can use to retrieve character-width data. Two of these functions retrieve the character-advance width and two of these functions retrieve actual character-width data.

An application can use the GetCharWidth32 and GetCharWidthFloat functions to retrieve the advance width for individual characters or symbols in a string of text. The advance width is the distance that the cursor on a video display or the print-head on a printer must advance before printing the next character in a string of text. The GetCharWidth32 function returns the advance width as an integer value. If greater precision is required, an application can use the GetCharWidthFloat function to retrieve fractional advance-width values.

An application can retrieve actual character-width data by using the GetCharABCWidths and GetCharABCWidthsFloat functions. To retrieve character widths for characters in a string of text that will be printed using a TrueType font, an application can call the GetCharABCWidths function; however, for any other font, the application should call the GetCharABCWidthsFloat function. (For more information about TrueType fonts, see Raster, Vector, and TrueType® Fonts). The following illustration shows the three components of the ABC width:

The "A" spacing is the width to add to the current position before placing the character. The "B" spacing is the width of the character itself. The "C" spacing is the white space to the right of the character. The total advance width is determined by calculating the sum of A+B+C. The character cell is an imaginary rectangle that surrounds each character or symbol in a Windows font. Because characters can overhang or underhang the character cell, either or both of the A and C increments can be a negative number.


 String Widths and Heights

In addition to retrieving character-width data for individual characters, applications also need to compute the width and height of entire strings. Two functions retrieve string-width and height measurements: GetTextExtentPoint32, and GetTabbedTextExtent. If the string does not contain tab characters, an application can use the GetTextExtentPoint32 function to retrieve the width and height of a specified string. If the string contains tab characters, an application should call the GetTabbedTextExtent function.

Windows also supports a special function, called GetTextExtentExPoint, that applications can use for word-wrapping operations. This function returns the number of characters from a specified string that fit within a given space.

Font Ascenders and Descenders

Some applications determine the line spacing between text lines of different sizes by using a font's maximum ascender and descender. An application can retrieve these values by calling the GetTextMetrics function and then checking the tmAscent and tmDescent members of the TEXTMETRIC.

The maximum ascent and descent are different from the typographic ascent and descent. In TrueType fonts, the typographic ascent and descent are typically the top of the "f" glyph and bottom of the "g" glyph. An application can retrieve the typographic ascender and descender for a TrueType font by calling the GetOutlineTextMetrics function and checking the values in the otmMacAscent and otmMacDescent members of the OUTLINETEXTMETRIC structure. It is important to note that TrueType font metrics do not correspond exactly to the metrics for Windows raster fonts, because TrueType font metrics have been designed by Apple Computer, Inc. for consistency across a variety of display and output devices.

The following figure shows the difference between the vertical text metric values returned in the NEWTEXTMETRIC and OUTLINETEXTMETRIC structures. (The names beginning with otm are members of the OUTLINETEXTMETRIC structure.)

Font Dimensions

An application can retrieve the physical dimensions of a TrueType font by calling the GetOutlineTextMetrics function. An application can retrieve the physical dimensions of any other font by calling the GetTextMetrics function. To determine the dimensions of an output device, an application can call the GetDeviceCaps function. GetDeviceCaps returns both physical and logical dimensions.

A logical inch is a measure Windows uses to present legible fonts on the screen and is approximately 30 to 40 percent larger than a physical inch. The use of logical inches precludes an exact match between the output of the screen and printer. Developers should be aware that the text on a screen is not simply a scaled version of the text that will appear on the page, particularly if graphics are incorporated into the text.


 Drawing Text

After an application selects the appropriate font, sets the required text-formatting options, and computes the necessary character width and height values for a string of text, it can begin drawing characters and symbols by calling any of the four text-output functions. Two of these functions, DrawText and TabbedTextOut, are part of Window Manager and found in the library USER.DLL; the remaining two functions are part of GDI and found in the library GDI.DLL. When an application calls one of these functions, the operating system passes the call to the graphics engine, which in turn passes the call to the appropriate device driver. At the device driver level, all of these calls are supported by one or more calls to the driver's own ExtTextOut or TextOut function. An application will achieve the fastest execution by calling the ExtTextOut function, which is quickly converted into an ExtTextOut call for the device. However, there are instances when an application should call one of the other three functions; for example, to draw multiple lines of text within the borders of a specified rectangular region, it is more efficient to call the DrawText function. To create a multicolumn table with justified columns of text, it is more efficient to call the TabbedTextOut function.


 Using the Font and Text-Output Functions

This section describes how you can use the font and text-output functions to draw normal text, draw text from different fonts on the same line, rotate lines of text, display the font-selection common dialog-box, enumerate fonts, and so on.

•	Using a stock font to draw text

•	Creating a logical font

•	Enumerating the installed fonts

•	Checking the text capabilities of a device

•	Setting the text alignment

•	Drawing text from different fonts on the same line

•	Rotating lines of text

•	Retrieving character outlines

•	Using portable truetype metrics

•	Using PANOSE numbers

•	Creating customized fonts


 Using a Stock Font to Draw Text

Windows provides six stock fonts. A stock font is a logical font that an application can obtain by calling the GetStockObject function and passing a value that identifies the requested font. The following list contains the six values that you can specify to obtain a stock font.

Value	Meaning
ANSI_FIXED_FONT	Specifies a monospace font based on the Windows character set. A Courier font is typically used.
ANSI_VAR_FONT	Specifies a proportional font based on the Windows character set. MS Sans Serif is typically used.
DEVICE_DEFAULT_FONT	Specifies the preferred font for the given device. This is typically the System font for display devices; however, for some dot-matrix printers this is a font that is resident on the device. (Printing with this font is usually faster than printing with a downloaded, bitmapped font).
OEM_FIXED_FONT	Specifies a monospace font based on an OEM character set. For IBM® computers and compatibles, the OEM font is based on the IBM PC character set.
SYSTEM_FONT	Specifies the System font. This is a proportional font based on the Windows character set, and is used by the operating system to display window titles, menu names, and text in dialog boxes. The System font is always available. Other fonts are available only if they have been installed.
SYSTEM_FIXED_FONT	Specifies a monospace font compatible with the System font in Windows versions earlier than 3.0.
The following example retrieves a handle of the Windows variable stock font, selects it into a device context, and then writes a string using that font:

HFONT hfnt, hOldFont;

    hfnt = GetStockObject(ANSI_VAR_FONT);

    if (hOldFont = SelectObject(hdc, hfnt)) {

        TextOut(hdc, 10, 50, "Sample ANSI_VAR_FONT text.", 26);

        SelectObject(hdc, hOldFont);

    }

If other stock fonts are not available, GetStockObject returns a handle to the System font (SYSTEM_FONT). You should use stock fonts only if the mapping mode for your application's device context is MM_TEXT.


 Creating a Logical Font

You can use the Font common dialog box to display available fonts. The ChooseFont dialog box is displayed after an application initializes the members of a CHOOSEFONT structure and calls the ChooseFont function. After the user chooses one of the available fonts and presses the OK button, the ChooseFont function initializes a LOGFONT structure with the relevant data. Your application can then call the CreateFontIndirect function and create a logical font based on the user's request. The following example demonstrates how this is done.

HFONT FAR PASCAL MyCreateFont( void )

{

CHOOSEFONT cf;

LOGFONT lf;

HFONT hfont;

    /* Initialize members of the CHOOSEFONT structure. */

    cf.lStructSize = sizeof(CHOOSEFONT);

    cf.hwndOwner = (HWND)NULL;

    cf.hDC = (HDC)NULL;

    cf.lpLogFont = &lf;

    cf.iPointSize = 0;

    cf.Flags = CF_SCREENFONTS;

    cf.rgbColors = RGB(0,0,0);

    cf.lCustData = 0L;

    cf.lpfnHook = (LPCFHOOKPROC)NULL;

    cf.lpTemplateName = (LPSTR)NULL;

    cf.hInstance = (HINSTANCE) NULL;

    cf.lpszStyle = (LPSTR)NULL;

    cf.nFontType = SCREEN_FONTTYPE;

    cf.nSizeMin = 0;

    cf.nSizeMax = 0;

    /* Display the CHOOSEFONT common-dialog box. */

    ChooseFont(&cf);

    /* Create a logical font based on the user's   */

    /* selection and return a handle identifying   */

    /* that font.                                  */

    hfont = CreateFontIndirect(cf.lpLogFont);

    return (hfont);

}


 Enumerating the Installed Fonts

In some instances, an application must be able to enumerate the available fonts and select the one most appropriate for a particular operation. An application can enumerate the available fonts by calling the EnumFonts or EnumFontFamilies function. These functions send information about the available fonts to a callback function that the application supplies. The callback function receives information in LOGFONT and NEWTEXTMETRIC structures. (The NEWTEXTMETRIC structure contains information about a TrueType font. When the callback function receives information about a non-TrueType font, the information is contained in a TEXTMETRIC structure.) By using this information, an application can limit the user's choices to only those fonts that are available.

The EnumFontFamilies function is similar to the EnumFonts function but includes some extra functionality. EnumFontFamilies allows an application to take advantage of styles available with TrueType fonts. New and upgraded applications should use EnumFontFamilies instead of EnumFonts.

In previous versions of Windows, the only style attributes were weight and italic; any other styles were specified in the family name for the font. For example, when an application used the EnumFonts function to query the available Courier fonts, EnumFonts might return information for Courier, Courier Bold, Courier Bold Italic, and Courier Italic. It would not return information about any other Courier fonts that might be installed, because any other Courier fonts would typically have a different family name.

TrueType fonts are organized around a typeface name (for example, Courier New) and style names (for example, italic, bold, and extra-bold). The EnumFontFamilies function enumerates all the styles associated with a given family name, not simply the bold and italic attributes. For example, when the system includes a TrueType font called Courier New Extra-Bold, EnumFontFamilies lists it with the other Courier New fonts. The capabilities of EnumFontFamilies are helpful for fonts with many or unusual styles and for fonts that cross international borders.

If an application does not supply a typeface name, the EnumFonts and EnumFontFamilies functions supply information about one font in each available family. To enumerate all the fonts in a device context, the application can specify NULL for the typeface name, compile a list of the available typefaces, and then enumerate each font in each typeface.

The following example uses the EnumFontFamilies function to retrieve the number of available raster, vector, and TrueType font families.

    UINT uAlignPrev;

    int aFontCount[] = { 0, 0, 0 };

    char szCount[8];

    EnumFontFamilies(hdc, (LPCTSTR) NULL,

        (FONTENUMPROC) EnumFamCallBack, (LPARAM) aFontCount);

    uAlignPrev = SetTextAlign(hdc, TA_UPDATECP);

    MoveToEx(hdc, 10, 50, (LPPOINT)NULL);

    TextOut(hdc, 0, 0, "Number of raster fonts: ", 24);

    itoa(aFontCount[0], szCount, 10);

    TextOut(hdc, 0, 0, szCount, strlen(szCount));

    MoveToEx(hdc, 10, 75, (LPPOINT)NULL);

    TextOut(hdc, 0, 0, "Number of vector fonts: ", 24);

    itoa(aFontCount[1], szCount, 10);

    TextOut(hdc, 0, 0, szCount, strlen(szCount));

    MoveToEx(hdc, 10, 100, (LPPOINT)NULL);

    TextOut(hdc, 0, 0, "Number of TrueType fonts: ", 26);

    itoa(aFontCount[2], szCount, 10);

    TextOut(hdc, 0, 0, szCount, strlen(szCount));

    SetTextAlign(hdc, uAlignPrev);

        .

        .

        .

BOOL FAR PASCAL EnumFamCallBack(lplf, lpntm, FontType, aFontCount)

LPLOGFONT lplf;

LPNEWTEXTMETRIC lpntm;

DWORD FontType;

LPVOID aFontCount;

{

    int far * aiFontCount = (int far *) aFontCount;

    /*

     * Record the number of raster, TrueType, and vector

     * fonts in the font-count array.

     */

    if (FontType & RASTER_FONTTYPE)

        aiFontCount[0]++;

    else if (FontType & TRUETYPE_FONTTYPE)

        aiFontCount[2]++;

    else

        aiFontCount[1]++;

    if (aiFontCount[0] || aiFontCount[1] || aiFontCount[2])

        return TRUE;

    else

        return FALSE;

    UNREFERENCED_PARAMETER( lplf );

    UNREFERENCED_PARAMETER( lpntm );

}

This example uses two masks, RASTER_FONTTYPE and TRUETYPE_FONTTYPE, to determine the type of font being enumerated. If the RASTER_FONTTYPE bit is set, the font is a raster font. If the TRUETYPE_FONTTYPE bit is set, the font is a TrueType font. If neither bit is set, the font is a vector font. A third mask, DEVICE_FONTTYPE, is set when a device (for example, a laser printer) supports downloading TrueType fonts; it is zero if the device is a display adapter, dot-matrix printer, or other raster device. An application can also use the DEVICE_FONTTYPE mask to distinguish GDI-supplied raster fonts from device-supplied fonts. Windows can simulate bold, italic, underline, and strikeout attributes for GDI-supplied raster fonts, but not for device-supplied fonts.

An application can also check bits 1 and 2 in the tmPitchAndFamily member of the NEWTEXTMETRIC structure to identify a TrueType font. If bit 1 is 0 and bit 2 is 1, the font is a TrueType font.

Vector fonts are categorized as OEM_CHARSET instead of ANSI_CHARSET. Some applications identify vector fonts by using this information, checking the tmCharSet member of the NEWTEXTMETRIC structure. This categorization usually prevents the font mapper from choosing vector fonts unless they are specifically requested. (Most applications no longer use vector fonts because their strokes are single lines and they take longer to draw than TrueType fonts, which offer many of the same scaling and rotation features that required vector fonts in earlier versions of Windows.)


 Checking the Text Capabilities of a Device

You can use the EnumFonts and EnumFontFamilies functions to enumerate the fonts that are available in a printer-compatible memory device context. You can also use the GetDeviceCaps function to retrieve information about the text capabilities of a device. By calling the GetDeviceCaps function with the NUMFONTS index, you can determine the minimum number of fonts supported by a printer. (An individual printer may support more fonts than specified in the return value from GetDeviceCaps with the NUMFONTS index.) By using the TEXTCAPS index, you can identify many of the text capabilities of the specified device.


 Setting the Text Alignment

You can query and set the text alignment for a device context by using the GetTextAlign and SetTextAlign functions. The text-alignment settings determine how text is positioned relative to a given location. Text can be aligned to the right or left of the position or centered over it; it can also be aligned above or below the point.

The following example shows a method for determining which horizontal alignment flag is set:

switch ((TA_LEFT | TA_RIGHT | TA_CENTER) & GetTextAlign(hdc))

{

case TA_LEFT:

   .

   .

   .

case TA_RIGHT:

   .

   .

   .

case TA_CENTER:

   .

   .

   .

}

You can also use the SetTextAlign function to update the current position when a text-output function is called. For instance, the following example uses the SetTextAlign function to update the current position when the TextOut function is called. In this example, the cArial parameter is an integer that specifies the number of Arial fonts.

UINT uAlignPrev;

char szCount[8];

uAlignPrev = SetTextAlign(hdc, TA_UPDATECP);

MoveToEx(hdc, 10, 50, (LPPOINT) NULL);

TextOut(hdc, 0, 0, "Number of Arial fonts: ", 23);

itoa(cArial, szCount, 10);

TextOut(hdc, 0, 0, (LPSTR) szCount, strlen(szCount));

SetTextAlign(hdc, uAlignPrev);


 Drawing Text From Different Fonts on the Same Line

Different type styles within a font family can have different widths. For example, bold and italic styles of a family are always wider than the roman style for a given point size. When you display or print several type styles on a single line, you must keep track of the width of the line to avoid having characters displayed or printed on top of one another.

You can use two functions to retrieve the width (or extent) of text in the current font. The GetTabbedTextExtent function computes the width and height of a character string. If the string contains one or more tab characters, the width of the string is based upon a specified array of tab-stop positions. The GetTextExtentPoint32 function computes the width and height of a line of text.

When necessary, Windows synthesizes a font by changing the character bitmaps. To synthesize a character in a bold font, Windows draws the character twice: once at the starting point, and again one pixel to the right of the starting point. To synthesize a character in an italic font, Windows draws two rows of pixels at the bottom of the character cell, moves the starting point one pixel to the right, draws the next two rows, and continues until the character has been drawn. By shifting pixels, each character appears to be sheared to the right. The amount of shear is a function of the height of the character.

One way to write a line of text that contains multiple fonts is to use the GetTextExtentPoint32 function after each call to TextOut and add the length to a current position. The following example writes the line "This is a sample string." using bold characters for "This is a", switches to italic characters for "sample", then returns to bold characters for "string." After printing all the strings, it restores the system default characters.

int XIncrement;

int YStart;

TEXTMETRIC tm;

HFONT hfntDefault, hfntItalic, hfntBold;

SIZE sz;

LPSTR lpszString1 = "This is a ";

LPSTR lpszString2 = "sample ";

LPSTR lpszString3 = "string.";

/* Create a bold and an italic logical font. */

hfntItalic = MyCreateFont();

hfntBold = MyCreateFont();

/* Select the bold font and draw the first string         */

/* beginning at the specified point (XIncrement, YStart). */

XIncrement = 10;

YStart = 50;

hfntDefault = SelectObject(hdc, hfntBold);

TextOut(hdc, XIncrement, YStart, lpszString1,

        lstrlen(lpszString1));

/*

 * Compute the length of the first string and add

 * this value to the x-increment that is used for the

 * text-output operation.

 */

GetTextExtentPoint32(hdc, lpszString1,

                   lstrlen(lpszString1), &sz);

XIncrement += sz.cx;

/*

 * Retrieve the overhang value from the TEXTMETRIC

 * structure and subtract it from the x-increment.

 * (This is only necessary for non-TrueType raster

 * fonts.)

 */

GetTextMetrics(hdc, &tm);

XIncrement -= tm.tmOverhang;

/*

 * Select an italic font and draw the second string

 * beginning at the point (XIncrement, YStart).

 */

hfntBold = SelectObject(hdc, hfntItalic);

GetTextMetrics(hdc, &tm);

XIncrement -= tm.tmOverhang;

TextOut(hdc, XIncrement, YStart, lpszString2,

        lstrlen(lpszString2));

/*

 * Compute the length of the second string and add

 * this value to the x-increment that is used for the

 * text-output operation.

 */

GetTextExtentPoint32(hdc, lpszString2, lstrlen(lpszString2), &sz);

XIncrement += sz.cx;

/*

 * Reselect the bold font and draw the third string

 * beginning at the point (XIncrement, YStart).

 */

SelectObject(hdc, hfntBold);

TextOut(hdc, XIncrement - tm.tmOverhang, YStart, lpszString3,

            lstrlen(lpszString3));

/* Reselect the original font. */

SelectObject(hdc, hfntDefault);

/* Delete the bold and italic fonts. */

DeleteObject(hfntItalic);

DeleteObject(hfntBold);

In this example, the GetTextExtentPoint32 function initializes the members of a SIZE structure with the length and height of the specified string. The GetTextMetrics function retrieves the overhang for the current font. Because the overhang is zero if the font is a TrueType font, the overhang value does not change the string placement. For raster fonts, however, it is important to use the overhang value.

The overhang is subtracted from the bold string once, to bring subsequent characters closer to the end of the string if the font is a raster font. Because overhang affects both the beginning and end of the italic string in a raster font, the glyphs start at the right of the specified location and end at the left of the endpoint of the last character cell. (The GetTextExtentPoint32 function retrieves the extent of the character cells, not the extent of the glyphs.) To account for the overhang in the raster italic string, the example subtracts the overhang before placing the string and subtracts it again before placing subsequent characters.

The SetTextJustification function adds extra space to the break characters in a line of text. You can use the GetTextExtentPoint function to determine the extent of a string, then subtract that extent from the total amount of space the line should occupy, and use the SetTextJustification function to distribute the extra space among the break characters in the string. The SetTextCharacterExtra function adds extra space to every character cell in the selected font, including the break character. (You can use the GetTextCharacterExtra function to determine the current amount of extra space being added to the character cells; the default setting is zero.)

You can place characters with greater precision by using the GetCharWidth32 or GetCharABCWidths function to retrieve the widths of individual characters in a font. The GetCharABCWidths function is more accurate than the GetCharWidth32 function, but only when it is used with TrueType fonts; when you use GetCharABCWidths with non-TrueType fonts, it retrieves the same information as GetCharWidth32.

ABC spacing also allows an application to perform very accurate text alignment. For example, when the application right aligns a raster roman font without using ABC spacing, the advance width is calculated as the character width. This means the white space to the right of the glyph in the bitmap is aligned, not the glyph itself. By using ABC widths, applications have more flexibility in the placement and removal of white space when aligning text, because they have information that allows them to finely control intercharacter spacing.


 Rotating Lines of Text

You can rotate TrueType fonts at any angle. This is useful for labeling charts and other illustrations. The following example rotates a string in 10-degree increments around the center of the client area by changing the value of the lfEscapement and lfOrientation members of the LOGFONT structure used to create the font.

RECT rc;

int angle;

HFONT hfnt, hfntPrev;

LPSTR lpszRotate = "String to be rotated.";

/* Allocate memory for a LOGFONT structure. */

PLOGFONT plf = (PLOGFONT) LocalAlloc(LPTR, sizeof(LOGFONT));

/* Specify a font typeface name and weight. */

lstrcpy(plf->lfFaceName, "Arial");

plf->lfWeight = FW_NORMAL;

/* Retrieve the client-rectangle dimensions. */

GetClientRect(hwnd, &rc);

/*

 * Set the background mode to transparent for the

 * text-output operation.

 */

SetBkMode(hdc, TRANSPARENT);

/*

 * Draw the string 36 times, rotating 10 degrees

 * counter-clockwise each time.

 */

for (angle = 0; angle < 3600; angle += 100) {

    plf->lfEscapement = angle;

    hfnt = CreateFontIndirect(plf);

    hfntPrev = SelectObject(hdc, hfnt);

    TextOut(hdc, rc.right / 2, rc.bottom / 2,

        lpszRotate, lstrlen(lpszRotate));

    SelectObject(hdc, hfntPrev);

    DeleteObject(hfnt);

}

/* Reset the background mode to its default. */

SetBkMode(hdc, OPAQUE);

/* Free the memory allocated for the LOGFONT structure. */

LocalFree((LOCALHANDLE) plf);


 Retrieving Character Outlines

You can use the GetGlyphOutline function to retrieve the outline of a glyph from a TrueType font. The glyph outline returned by the GetGlyphOutline function is for a grid-fitted glyph. (A grid-fitted glyph has been modified so that its bitmap image conforms as closely as possible to the original design of the glyph.) If your application requires an unmodified glyph outline, request the glyph outline for a character in a font whose size is equal to the font's em units. (To create a font with this size, set the lfHeight member of the LOGFONT structure to the negative of the value of the ntmSizeEM member of the NEWTEXTMETRIC structure.)

GetGlyphOutline returns the outline as a bitmap or as a series of polylines and splines. When an application retrieves a glyph outline as a series of polylines and splines, the information is returned in a TTPOLYGONHEADER structure followed by as many TTPOLYCURVE structures as required to describe the glyph. All points are returned as POINTFX structures and represent absolute positions, not relative moves. The starting point given by the pfxStart member of the TTPOLYGONHEADER structure is the point where the outline for a contour begins. The TTPOLYCURVE structures that follow can be either polyline records or spline records.

To render a TrueType character outline in Windows, you must use both the polyline and the spline records. Windows can render both polylines and splines easily. Each polyline and spline record contains as many sequential points as possible, to minimize the number of records returned.

The starting point given in the TTPOLYGONHEADER structure is always on the outline of the glyph. The specified point serves as both the starting and ending points for the contour.


 Polyline Records

Polyline records are a series of points; lines drawn between the points describe the outline of the character. A polyline record begins with the last point in the previous record (or, for the first record in the contour, the starting point). Each point in the record is on the glyph outline and can be connected simply by using straight lines.


 Spline Records

Spline records represent the quadratic curves (that is, quadratic b-splines) used by TrueType. A spline record begins with the last point in the previous record (or for the first record in the contour, with the starting point). For the first spline record, the starting point and the last point in the record are on the glyph outline. For all other spline records, only the last point is on the glyph outline. All other points in the spline records are off the glyph outline and must be rendered as the control points of b-splines.

The last spline or polyline record in a contour always ends with the contour's starting point. This arrangement ensures that every contour is closed.

Because b-splines require three points (one point off the glyph outline between two points that are on the outline), you must perform some calculations when a spline record contains more than one off-curve point.

For example, if a spline record contains three points (A, B, and C) and it is not the first record, points A and B are off the glyph outline. To interpret point A, use the current position (which is always on the glyph outline) and the point on the glyph outline between points A and B. To find the midpoint (M) between A and B, you can perform the following calculation.

M = A + (B − A)/2

The midpoint between consecutive off-outline points in a spline record is a point on the glyph outline, according to the definition of the spline format used in TrueType fonts.

If the current position is designated by P, the two quadratic splines defined by this spline record are (P, A, M) and (M, B, C).


 Using Portable TrueType Metrics

Applications that use the TrueType text metrics can achieve a high degree of printer and document portability; even applications that must maintain compatibility with earlier versions of Windows can use the TrueType metrics.

Design widths overcome most of the problems of device-dependent text introduced by physical devices. Design widths are a kind of logical width. Independent of any rasterization problems or scaling transformations, each glyph has a logical width and height. Composed to a logical page, each character in a string has a place that is independent of the physical device widths. Although a logical width implies that widths can be scaled linearly at all point sizes, this is not necessarily true for either nonportable or most TrueType fonts. At smaller point sizes, some glyphs are made wider relative to their height for better readability.

The characters in TrueType core fonts are designed against a 2048 by 2048 grid. The design width is the width of a character in these grid units. (TrueType supports any integer grid size up to 16,384 by 16,384; grid sizes that are integer powers of 2 scale faster than other grid sizes.)

The font outline is designed in notional units. The em square is the notional grid against which the font outline is fitted. (You can use the otmEMSquare member of OUTLINETEXTMETRIC and the ntmSizeEM member of NEWTEXTMETRIC to retrieve the size of the em square in notional units.) When a font is created that has a point size (in device units) equal to the size of its em square, the ABC widths for this font are the desired design widths. For example, assume the size of an em square is 1000 and the ABC widths of a character in the font are 150, 400, and 150. A character in this font that is 10 device units high would have ABC widths of 1.5, 4, and 1.5, respectively. Since the MM_TEXT mapping mode is most commonly used with fonts (and MM_TEXT is equivalent to device units), this is a simple calculation.

Because of the high resolution of TrueType design widths, applications that use them must take into account the large numeric values that can be created.


 Device vs. Design Units

An application can retrieve font metrics for a physical font only after the font has been selected into a device context. When a font is selected into a device context, it is scaled for the device. The font metrics specific to the device are known as device units.

Portable metrics in fonts are known as design units. To apply to a given device, design units must be converted to device units. Use the following formula to convert design units to device units.

DeviceUnits = (DesignUnits/unitsPerEm) * (PointSize/72) * DeviceResolution

The variables in this formula have the following meanings.

Variable	Description
DeviceUnits	Specifies the DesignUnits font metric converted to device units. This value is in the same units as the value given for DeviceResolution.
DesignUnits	Specifies the font metric to be converted to device units. This value can be any font metric, including the width of a character or the ascender value for an entire font.
unitsPerEm	Specifies the em square size for the font.
PointSize	Specifies size of the font, in points. (One point equals 1/72 of an inch.)
DeviceResolution	Specifies number of device units (pixels) per inch. Typical values might be 300 for a laser printer or 96 for a VGA screen.
This formula should not be used to convert device units back to design units. Device units are always rounded to the nearest pixel. The propagated round-off error can become very large, especially when an application is working with screen sizes.

To request design units, create a logical font whose height is specified as −unitsPerEm. Applications can retrieve the value for unitsPerEm by calling the EnumFontFamilies function and checking the ntmSizeEM member of the NEWTEXTMETRIC structure.


 Metrics for Portable Documents

The following table specifies the most important font metrics for applications that require portable documents and the functions that allow an application to retrieve them.

Function	Metric	Use
EnumFontFamilies	ntmSizeEM	Retrieval of design metrics; conversion to device metrics
GetCharABCWidths	ABCWidths	Accurate placement of characters at the start and end of margins, picture boundaries, and other text breaks
GetCharWidth32	AdvanceWidths	Placement of characters on a line
GetOutlineTextMetrics	otmfsType	Font-embedding bits
	otmsCharSlopeRise	Y-component for slope of cursor for italic fonts
	otmsCharSlopeRun	X-component for slope of cursor for italic fonts
	otmAscent	Line spacing
	otmDescent	Line spacing
	otmLineGap	Line spacing
	otmpFamilyName	Font identification
	otmpStyleName	Font identification
	otmpFullName	Font identification (typically, family and style name)
The otmsCharSlopeRise, otmsCharSlopeRun, otmAscent, otmDescent, and otmLineGap members of the OUTLINETEXTMETRIC structure are scaled or transformed to correspond to the current device mode and physical height (as given in the tmHeight member of the NEWTEXTMETRIC structure).

Font identification is important in those instances when an application must select the same font — for example, when a document is reopened or moved to a different operating system. The font mapper always selects the correct font when an application requests a font by full name. The family and style names provide input to the standard font dialog box, which ensures that the selection bars are properly placed.

The otmsCharSlopeRise and otmsCharSlopeRun values are used to produce a close approximation of the main italic angle of the font. For typical roman fonts, otmsCharSlopeRise is 1 and otmsCharSlopeRun is 0. For italic fonts, the values attempt to approximate the sine and cosine of the main italic angle of the font (in counterclockwise degrees past vertical); note that the italic angle for upright fonts is 0. Because these values are not expressed in design units, they should not be converted into device units.

The character placement and line spacing metrics enable an application to compute device-independent line breaks that are portable across screens, printers, typesetters, and even platforms.

Device-independent page layout requires the following seven basic steps:

1.	Normalize all design metrics to a common ultra-high resolution (UHR) value (for example, 65,536 DPI); this prevents round-off errors.

2.	Compute line breaks based on UHR metrics and physical page width; this yields a starting point and an ending point of a line within the text stream.

3.	Compute the device page width in device units (for example, pixels).

4.	Fit each line of text into the device page width, using the line breaks computed in step 2.

5.	Compute page breaks by using UHR metrics and the physical page length; this yields the number of lines per page.

6.	Compute the line heights in device units.

7.	Fit the lines of text onto the page, using the lines per page from step 5 and the line heights from step 6.

If all applications adopt these techniques, developers can virtually guarantee that documents moved from one application to another will retain their original appearance and format.


 Using PANOSE Numbers

TrueType font files include PANOSE numbers, which applications can use to choose a font that closely matches their specifications. The PANOSE system classifies faces by 10 different attributes. For more information about these attributes, see the PANOSE structure. A PANOSE structure is part of the OUTLINETEXTMETRIC structure (whose values are filled in by calling the GetOutlineTextMetrics function).

The PANOSE attributes are rated individually on a scale. The resulting values are concatenated to produce a number. Given this number for a font and a mathematical metric to measure distances in the PANOSE space, an application can determine the nearest neighbors.


 Creating Customized Fonts

Windows keeps a font table containing all the fonts that applications can use. Windows chooses a font from this table when an application calls the CreateFont or CreateFontIndirect function. There can be up to 253 entries in the table.

A font resource is a group of individual fonts representing characters in a given character set that have various combinations of heights, widths, and pitches. You can load font resources and add the fonts in each resource to the operating system font table by using the AddFontResource function. To remove a font resource from the font table, you can use the RemoveFontResource function.

After you add a font resource to the font table, you can use the individual fonts in the resource. In other words, the CreateFont function takes the fonts into account when it tries to match a physical font to the specified logical font. (Fonts in the table are never directly accessible to an application. They are available only through the CreateFontIndirect and CreateFont functions, which return the handles of the fonts, not their memory addresses.)

Whenever your application adds or removes a font resource, it should inform all other applications of the change by sending a WM_FONTCHANGE message to them. Use the following call to the SendMessage function to send the message to all windows.

SendMessage(HWND_BROADCAST, WM_FONTCHANGE, 0, 0);

You can use the GetProfileString function to search the [Fonts] section of the WIN.INI file for the list of fonts that the user has used Control Panel to install.


 Creating Font Resources

A font resource file is an empty Windows dynamic-link library; it contains no code or data, but it does contain resources. You can create font resources by creating font files and adding them as resources to a font resource file. To create a font resource file, follow these steps:

1.	Create the font files.

2.	Create a resource-definition file for the font.

3.	Create a dummy code module.

4.	Create a module-definition file that describes the fonts and the devices that use the fonts.

5.	Compile and link the source files.

You can add a font file to an empty library, along with such resources as icons, cursors, and menus, by using resource compiler.

Note  A complete explanation of how to create a font resource file is beyond the scope of this book. For more information on this topic, see the documentation provided with your application development tools.


 Installing and Using an Embedded Font

You must separate an embedded font from the containing document and install it in the user's operating system before Windows can use it. Although the exact procedure for separating the font from the document depends on the method used to embed it, your application should always perform these steps:

1.	Resolve name conflicts before installing the font.

2.	Write the font data to a file, decoding read-only fonts as necessary.

3.	Use the CreateScalableFontResource function to create a font resource file for the unembedded font.

In Windows, only a TrueType font can be embedded.

Your application should avoid installing a font with the same name as a font that is already on the system. To determine whether there are duplicate style names, an application can compare the information returned by EnumFontFamilies against the family name and style name stored with the embedded font.

Read-Write Permission

Embedded fonts that have read-write permission (and that therefore can be permanently installed on the user's system) should be written to a file that has the .TTF filename extension.

Most applications put the files for embedded fonts that have read-write permission into either the SYSTEM subdirectory of the user's Windows directory or into the application's working directory. Files for read-only embedded fonts are typically put into a temporary directory.

Before installing an embedded font, you must use the CreateScalableFontResource function to create a font resource file. Because Windows cannot directly interpret the native TrueType font file format, it requires a file that mimics the standard .FON file (called a .FOT file) to make internal bookkeeping and enumeration easier. The CreateScalableFontResource function produces a .FOT file that points to the TrueType font file. Once this .FOT file is produced, Windows applications can use TrueType fonts transparently by using the AddFontResource and RemoveFontResource functions. You can also use the CreateScalableFontResource function to install special fonts for logos, icons, and other graphics. Font resource files for read-only fonts should use a different extension (for example, .FOR) and should be hidden from other applications in the system by specifying 1 for the first parameter of CreateScalableFontResource.

Your application should offer users the option of permanently installing embedded fonts that have read-write permission. To permanently install a font, applications should concatenate the typeface and style names and then use the WriteProfileString function to insert this string along with the .FOT file name in the [Fonts] section of the WIN.INI file. A typical font entry in the [Fonts] section looks like the following example.

Times New Roman Bold (TrueType)=TIMESBD.FOT

Read-Only Permission

Embedded fonts with read-only permission should not use the .TTF extension and should avoid the .FOT and .FON extensions. A typical filename extension for read-only embedded fonts is .TTR. Files for read-only embedded fonts must be removed from the operating system and from both physical and logical memory as soon as the containing document is closed, so their names do not need to be meaningful except to the application.

If a document contains one or more read-only embedded fonts, the user must not be permitted to edit the document. If the user is allowed to edit the document in any way, your application must first strip away and delete the read-only embedded fonts. As mentioned earlier, read-only embedded fonts must be removed from the operating system and memory immediately when the document in which they are bundled is closed.

To delete read-only embedded fonts, your application should follow these steps:

1.	Call the RemoveFontResource function for each font to be deleted.

2.	Delete the font resource file for each font.

3.	Delete each TrueType font file for each font.

When an application creates a file for a read-only embedded font and specifies 1 for the first parameter of the CreateScalableFontResource function, the EnumFonts and EnumFontFamilies functions will not enumerate this font. Hiding read-only embedded fonts in this manner makes it unlikely that another application can use them, even though Windows resources are theoretically available to all processes in Windows. The RemoveFontResource function does not delete a font currently in use. If your application uses a read-only embedded font installed by another application, it can be difficult for the installing application to delete the font. In this case, your application should delete the resource file and the TrueType font file when the user closes the document containing the read-only fonts.

It is very important that applications delete the TrueType font file for read-only embedded fonts. If the delete operation fails when the user closes the document, the application should periodically attempt to delete the file as the application runs, when it closes, and the next time it starts.

In some cases, an application is unable to delete a TrueType font file for a read-only embedded font because of external events (such as a system failure). There is no legal liability for events that are out of the control of the application.


 Font and Text Functions

Following are the functions used with fonts.

AddFontResource
CreateFont
CreateFontIndirect
CreateScalableFontResource
DrawText
DrawTextEx
EnumFontFamilies
EnumFontFamProc
EnumFonts
EnumFontsProc
ExtTextOut
GetAspectRatioFilterEx
GetCharABCWidths
GetCharABCWidthsFloat
GetCharacterPlacement
GetCharWidth
GetCharWidth32
GetCharWidthFloat
GetFontData
GetGlyphOutline
GetKerningPairs
GetOutlineTextMetrics
GetRasterizerCaps
GetTabbedTextExtent
GetTextAlign
GetTextCharacterExtra
GetTextColor
GetTextExtentExPoint
GetTextExtentPoint
GetTextExtentPoint32
GetTextFace
GetTextMetrics
PolyTextOut
RemoveFontResource
SetMapperFlags
SetTextAlign
SetTextCharacterExtra
SetTextColor
SetTextJustification
TabbedTextOut
TextOut

Obsolete or Deleted Functions

GetAspectRatioFilter
GetTextExtent


 Lines and Curves

Lines and curves are used to draw graphics output on raster devices. As discussed in this overview, a line is a set of highlighted pixels on a raster display (or a set of dots on a printed page) identified by two points: a starting point and an ending point. A regular curve is a set of highlighted pixels on a raster display (or dots on a printed page) that defines the perimeter (or part of the perimeter) of a conic section. An irregular curve is a set of pixels that defines a curve that does not fit the perimeter of a conic section.


 About Lines and Curves

All types of applications written for Microsoft® Windows® use lines and curves to draw graphics output on raster devices. Computer-aided design (CAD) and drawing applications use lines and curves to outline objects, specify the centers of objects, the dimensions of objects, and so on. Spreadsheet applications use lines and curves to draw grids, charts, and graphs. Word processing applications use lines to create rules and borders on a page of text.


 Lines

A line is a set of highlighted pixels on a raster display (or a set of dots on a printed page) identified by two points: a starting point and an ending point. In Windows, the pixel located at the starting point is always included in the line, and the pixel located at the ending point is always excluded. (This kind of line is sometimes called inclusive-exclusive.)

When an application calls one of the Windows line-drawing functions, graphics device interface (GDI), or in some cases a device driver, determines which pixels should be highlighted. GDI is a dynamic-link library (DLL) that processes graphics function calls from a Windows-based application and passes those calls to a device driver. A device driver is a DLL that receives input from GDI, converts the input to device commands, and passes those commands to the appropriate device. GDI uses a digital differential analyzer (DDA) to determine the set of pixels that define a line. A DDA determines the set of pixels by examining each point on the line and identifying those pixels on the display surface (or dots on a printed page) that correspond to the points. The following illustration shows a line, its starting point, its ending point, and the pixels highlighted by using a simple DDA.

The simplest and most common DDA is the Bresenham, or incremental, DDA. A modified version of this algorithm draws lines in Windows versions 3.x. The incremental DDA is noted for its simplicity, but it is also noted for its inaccuracy. Because it rounds off to the nearest integer value, it sometimes fails to represent the original line requested by the application. The Microsoft® Win32® DDA used by GDI does not round off to the nearest integer. As a result, this new DDA produces output that is sometimes much closer in appearance to the original line requested by the application.

Note  If an application requires line output that cannot be achieved with the new DDA, it can draw its own lines by calling the LineDDA function and supplying a private DDA. However, the LineDDA function draws lines much slower than the Windows line-drawing functions. Do not use this function within an application if speed is a primary concern.

An application can use the new DDA to draw single lines and multiple, connected line segments. An application can draw a single line by calling the LineTo function. This function draws a line from the current position up to, but not including, a specified ending point. An application can draw a series of connected line segments by calling the Polyline function, supplying an array of points that specify the ending point of each line segment. An application can draw multiple, disjointed series of connected line segments by calling the PolyPolyline function, supplying the required ending points.

The following illustration shows line output created by calling the LineTo, Polyline, and PolyPolyline functions.


 Curves

A regular curve is a set of highlighted pixels on a raster display (or dots on a printed page) that define the perimeter (or part of the perimeter) of a conic section. An irregular curve is a set of pixels that define a curve that does not fit the perimeter of a conic section. In Windows, the ending point is excluded from a curve just as it is excluded from a line.

When an application calls one of the Windows curve-drawing functions, GDI breaks the curve into a number of extremely small, discrete line segments. After determining the endpoints (starting point and ending point) for each of these line segments, GDI determines which pixels (or dots) define each line by applying its DDA.

An application can draw an ellipse or part of an ellipse by calling the Arc function. This function draws the curve within the perimeter of an invisible rectangle called a bounding rectangle. The size of the ellipse is specified by two invisible radials extending from the center of the rectangle to the sides of the rectangle. The following illustration shows an arc (part of an ellipse) drawn by using the Arc function.

When calling the Arc function, an application specifies the coordinates of the bounding rectangle and radials. The preceding illustration shows the rectangle and radials with dashed lines while the actual arc was drawn using a solid line.

When drawing the arc of another object, the application can call the SetArcDirection and GetArcDirection functions to control the direction (clockwise or counterclockwise) in which the object is drawn. The default direction for drawing arcs and other objects is counterclockwise.

In addition to drawing ellipses or parts of ellipses, Windows-based applications can draw irregular curves called Bézier curves. A Bézier curve is an irregular curve whose curvature is defined by four control points (p1, p2, p3, and p4). The control points p1 and p4 define the starting and ending points of the curve, and the control points p2 and p3 define the shape of the curve by marking points where the curve reverses orientation.

An application can draw irregular curves by calling the PolyBezier function, supplying the appropriate control points.


 Combined Lines and Curves

In addition to drawing lines or curves, Windows-based applications can draw combinations of line and curve output by calling a single function. For example, an application can draw the outline of a pie chart by calling the AngleArc function.

The AngleArc function draws an arc along a circle's perimeter and draws a line connecting the starting point of the arc to the circle's center. In addition to using the AngleArc function, a Windows-based application can also combine line and irregular curve output by using the PolyDraw function.


 Line and Curve Attributes

A device context (DC) contains attributes that affect line and curve output. The line and curve attributes include the current position, brush style, brush color, pen style, pen color, transformation, and so on.

The default current position for any DC is located at the point (0,0) in logical (or world) space. You can set these coordinates to a new position by calling the MoveToEx function and passing a new set of coordinates.

Note  Windows provides two sets of line- and curve-drawing functions. The first set retains the current position in a DC, and the second set alters the position. You can identify the functions that alter the current position by examining the function name. If the function name ends with the preposition "To", the function sets the current position to the ending point of the last line drawn (LineTo, ArcTo, PolylineTo, or PolyBezierTo). If the function name does not end with this preposition, it leaves the current position intact (Arc, Polyline, or PolyBezier).

The default brush is a solid white brush. An application can create a new brush by calling the CreateBrushIndirect function. After creating a brush, the application can select it into its DC by calling the SelectObject function. Windows provides a complete set of functions to create, select, and alter the brush in an application's DC. For more information about these functions and about brushes in general, see Brushes.

The default pen is a cosmetic, solid black pen that is one pixel wide. An application can create a pen by using the ExtCreatePen function. After creating a pen, your application can select it into its DC by calling the SelectObject function. Windows provides a complete set of functions to create, select, and alter the pen in an application's DC. For more information about these functions and about pens in general, see Pens.

The default transformation is the unity transformation (specified by the identity matrix). An application can specify a new transformation by calling the SetWorldTransform function. Windows provides a complete set of functions to transform lines and curves by altering their width, location, and general appearance. For more information about these functions, see Coordinate Spaces and Transformations.


 Using Lines and Curves

You can use the line and curve functions to draw virtually any shape or object in the client area of an application window. This section illustrates how these functions can be used to draw markers or a pie chart.

•	Drawing markers

•	Drawing a pie chart


 Drawing Markers

You can use the line functions to draw markers. A marker is a symbol centered over a point. Drawing applications use markers to designate starting points, ending points, and control points. Spreadsheet applications use markers to designate points of interest on a chart or graph.

In the following code sample, the application-defined Marker function creates a marker by using the MoveToEx and LineTo functions. These functions draw two intersecting lines, 20 pixels in length, centered over the cursor coordinates.

void Marker(LONG x, LONG y, HWND hwnd)

{

    HDC hdc;

    hdc = GetDC(hwnd);

        MoveToEx(hdc, (int) x - 10, (int) y, (LPPOINT) NULL);

        LineTo(hdc, (int) x + 10, (int) y);

        MoveToEx(hdc, (int) x, (int) y - 10, (LPPOINT) NULL);

        LineTo(hdc, (int) x, (int) y + 10);

    ReleaseDC(hwnd, hdc);

}

Windows stores the coordinates of the cursor in the lParam parameter of the WM_LBUTTONDOWN message when the user presses the left mouse button. The following code demonstrates how an application gets these coordinates, determines whether they lie within its client area, and passes them to the Marker function to draw the marker.

/* Line- and arc-drawing variables */

static BOOL bCollectPoints;

static POINT ptMouseDown[32];

static int index;

POINTS ptTmp;

RECT rc;

    case WM_LBUTTONDOWN:

        if (bCollectPoints && index < 32){

            /* Create the region from the client area. */

            GetClientRect(hwnd, &rc);

            hrgn = CreateRectRgn(rc.left, rc.top,

                rc.right, rc.bottom);

            ptTmp = MAKEPOINTS((POINTS FAR *) lParam);

            ptMouseDown[index].x = (LONG) ptTmp.x;

            ptMouseDown[index].y = (LONG) ptTmp.y;

            /* Test for a hit in the client rectangle. */

            if (PtInRegion(hrgn, ptMouseDown[index].x,

                    ptMouseDown[index].y)) {

                /* If a hit occurs, record the mouse coords. */

                Marker(ptMouseDown[index].x, ptMouseDown[index].y,

                    hwnd);

                index++;

            }

        }

        break;


 Drawing a Pie Chart

You can use the line and curve functions to draw a pie chart. The primary function used to draw pie charts is the AngleArc function, which requires you to supply the coordinates of the center of the pie, the radius of the pie, a start angle, and a sweep angle. Following is a dialog box that the user can use to enter these values.

The dialog box template found in the application's resource script (.RC) file specifies characteristics of the preceding dialog box (its height, the controls it contains, and its style), as follows.

AngleArc DIALOG 6, 18, 160, 100

STYLE WS_DLGFRAME | WS_POPUP | WS_VISIBLE | WS_CAPTION

CAPTION "Pie Chart"

FONT 8, "MS Sans Serif"

BEGIN

    EDITTEXT   IDD_X, 18, 22, 25, 12, ES_AUTOHSCROLL

    LTEXT      "X", 102, 4, 24, 9, 8

    EDITTEXT   IDD_Y, 18, 39, 25, 12, ES_AUTOHSCROLL

    LTEXT      "Y", 104, 5, 42, 12, 8

    LTEXT      "Center", 105, 19, 11, 23, 8

    EDITTEXT   IDD_RADIUS, 103, 9, 32, 12, ES_AUTOHSCROLL

    EDITTEXT   IDD_STARTANGLE, 103, 31, 32, 12, ES_AUTOHSCROLL

    EDITTEXT   IDD_SWEEPANGLE, 103, 53, 32, 12, ES_AUTOHSCROLL

    LTEXT      "Radius", 109, 73, 11, 25, 8

    LTEXT      "Start Angle", 110, 59, 33, 42, 8

    LTEXT      "Sweep Angle", 111, 55, 55, 43, 8

    PUSHBUTTON "OK", IDD_OK, 9, 82, 40, 14

    PUSHBUTTON "Cancel", IDD_CANCEL, 110, 82, 40, 14

END

The dialog box procedure, found in the application's source file, retrieves data (center coordinates, arc radius, and start and sweep angles) by following these steps:

1.	The application-defined ClearBits function initializes the array that receives the user-input to zero.

2.	The application-defined GetStrLngth function retrieves the length of the string entered by the user.

3.	The application-defined RetrieveInput function retrieves the value entered by the user.

The following sample code shows the dialog box procedure.

BOOL CALLBACK ArcDlgProc(HWND hdlg, UINT uMsg, WPARAM wParam,

                       LPARAM lParam)

{

    CHAR chInput[4];    /* receives control-window input  */

    int cch;            /* array-size and count variable  */

    switch (uMsg) {

        case WM_INITDIALOG:

            return FALSE;

        case WM_COMMAND:

            switch (wParam){

                /*

                 * If the user pressed the OK button, retrieve the

                 * data that was entered in the various AngleArc

                 * controls.

                 */

                case IDD_OK:

                    /*

                     * Retrieve the x-coordinate of the arc's

                     * center.

                     */

                    ClearBits(chInput, sizeof(chInput));

                    GetDlgItemText(hdlg, IDD_X, chInput,

                        sizeof(chInput));

                    cch = GetStrLngth(chInput);

                    nX = (int)RetrieveInput(chInput, cch);

                    /*

                     * Retrieve the y-coordinate of the arc's

                     * center.

                     */

                    ClearBits(chInput, sizeof(chInput));

                    GetDlgItemText(hdlg, IDD_Y, chInput,

                        sizeof(chInput));

                    cch = GetStrLngth(chInput);

                    nY = (int)RetrieveInput(chInput, cch);

                    /* Retrieve the radius of the arc. */

                    ClearBits(chInput, sizeof(chInput));

                    GetDlgItemText(hdlg, IDD_RADIUS, chInput,

                        sizeof(chInput));

                    cch = GetStrLngth(chInput);

                    dwRadius = (DWORD) RetrieveInput(chInput, cch);

                    /* Retrieve the start angle. */

                    ClearBits(chInput, sizeof(chInput));

                    GetDlgItemText(hdlg, IDD_STARTANGLE, chInput,

                        sizeof(chInput));

                    cch = GetStrLngth(chInput);

                    xStartAngle = (float) RetrieveInput(chInput,

                                    cch);

                    /* Retrieve the sweep angle. */

                    ClearBits(chInput, sizeof(chInput));

                    GetDlgItemText(hdlg, IDD_SWEEPANGLE, chInput,

                        sizeof(chInput));

                    cch = GetStrLngth(chInput);

                    xSweepAngle = (float) RetrieveInput(chInput,

                                     cch);

                    EndDialog(hdlg, FALSE);

                    return TRUE;

                /*

                 * If user presses the CANCEL button, close the

                 * dialog box.

                 */

                case IDD_CANCEL:

                    EndDialog(hdlg, FALSE);

                    return TRUE;

            } /* end switch (wParam) */

            break;

        default:

            return FALSE;

    } /* end switch (message) */

    UNREFERENCED_PARAMETER(lParam);

}

void ClearBits(LPTSTR cArray, int iLength)

{

    int i;

    for (i = 0; i < iLength; i++)

        cArray[i] = 0;

}

int GetStrLngth(LPTSTR cArray)

{

    int i = 0;

    while (cArray[i++] != 0);

        return i - 1;

}

DWORD RetrieveInput(LPTSTR cArray, int iLength)

{

    int i, iTmp;

    double dVal, dCount;

    dVal = 0.0;

    dCount = (double) (iLength - 1);

    /* Convert ASCII input to a floating-point value. */

    for (i = 0; i < iLength; i++) {

        iTmp = cArray[i] - 0x30;

        dVal = dVal + (((double)iTmp) * pow(10.0, dCount--));

    }

    return (DWORD) dVal;

}

To draw each section of the pie chart, pass the values entered by the user to the AngleArc function. To fill the pie chart using the current brush, embed the call to AngleArc in a path bracket. The following code sample shows the defined path bracket and the call to AngleArc.

int nX;

int nY;

DWORD dwRadius;

float xStartAngle;

float xSweepAngle;

                case (IDM_ANGLEARC):

                   DialogBox((HINSTANCE) GetModuleHandle (NULL),

                             (LPTSTR) "AngleArc",

                             hwnd, (DLGPROC) ArcDlgProc);

                    hdc = GetDC(hwnd);

                        BeginPath(hdc);

                            SelectObject(hdc,

                                GetStockObject(GRAY_BRUSH));

                            MoveToEx(hdc, nX, nY, (LPPOINT) NULL);

                            AngleArc(hdc, nX, nY, dwRadius,

                                xStartAngle, xSweepAngle);

                            LineTo(hdc, nX, nY);

                        EndPath(hdc);

                    StrokeAndFillPath(hdc);

                    ReleaseDC(hwnd, hdc);

                    break;


 Line and Curve Functions

Following are the functions used with lines and curves.

AngleArc
Arc
ArcTo
GetArcDirection
LineDDA
LineDDAProc
LineTo
MoveToEx
PolyBezier
PolyBezierTo
PolyDraw
Polyline
PolylineTo
PolyPolyline
SetArcDirection


 Metafiles

Applications written for the Microsoft® Windows® operating system use two graphics tools to store pictures: metafiles and bitmaps. For information about bitmaps, see Bitmaps. This overview describes metafiles.


 About Metafiles

A metafile is a collection of structures that store a picture in a device-independent format. Device independence is the one feature that sets metafiles apart from bitmaps: unlike a bitmap, a metafile guarantees device independence. For example, when an application creates a picture measuring 2 by 2 inches on a VGA display and stores that picture in a metafile, the picture maintains its original dimensions when printed on a 300 dpi laser printer or copied over a network and displayed in another application that is running on an 8514/A video display. There is a drawback to metafiles, however; they are generally drawn more slowly than bitmaps. Therefore, if an application requires fast drawing and device independence is not an issue, it should use bitmaps instead of metafiles.

Internally, a metafile is an array of variable-length structures called metafile records. The first records in the metafile specify general information such as the resolution of the device on which the picture was created, the dimensions of the picture, and so on. The remaining records, which constitute the bulk of any metafile, correspond to the graphics device interface (GDI) functions required to draw the picture. These records are stored in the metafile after a special metafile device context (DC) is created. This DC is then used for all drawing operations required to create the picture. When Windows processes a GDI function associated with a metafile DC, it converts the function into the appropriate data and stores this data in a record appended to the metafile.

After a picture is complete and the last record is stored in the metafile, the metafile can be passed to another application by means of the clipboard, embedded within another file, stored on disk, or played repeatedly. A metafile is played when its records are converted to device commands and processed by the appropriate device.

There are two types of metafiles: enhanced and Windows. An enhanced metafile is used in applications written using the Microsoft® Win32® application programming interface (API). The enhanced format consists of a header, a table of handles to GDI objects, a private palette, and an array of metafile records. Enhanced metafiles provide true device independence. (You can think of the picture stored in an enhanced metafile as a "snapshot" of the video display taken at a particular moment. This "snapshot" maintains its dimensions no matter where it appears: on a printer, a plotter, or the desktop, or in the client area of any Win32-based application.)

A Windows metafile is used for applications written using the Windows version 3.x API. The Windows format consists of a header and an array of metafile records. Windows-format metafiles are limited in their capabilities and should rarely be used — the Windows-metafile API is supported to maintain backward compatibility with applications that were written to run with Windows version 3.x.


 Enhanced-Format Metafiles

A developer can use enhanced metafiles to store a picture created by using the Win32 GDI functions (including new path and transformation functions). Because the enhanced metafile format is standardized for the Win32 API, pictures that are stored in this format can be copied from one Win32 application to another; and, because the pictures are truly device independent, they are guaranteed to maintain their shape and proportion on any output device.


 Enhanced Metafiles

An enhanced metafile is an array of records. A metafile record is a variable-length ENHMETARECORD structure. This structure identifies the record type, specifies the record length, and contains additional data that is dependent on the record type.

The first record in an enhanced metafile is always the enhanced-metafile header. The header specifies the following information.

•	Size of the metafile, in bytes

•	Dimensions of the picture frame, in device units

•	Dimensions of the picture frame, in .01-millimeter units

•	Number of records in the metafile

•	Offset to an optional text description

•	Size of the optional palette

•	Resolution of the original device, in pixels

•	Resolution of the original device, in millimeters

An optional text description can follow the header record. The text description describes the picture and the author's name. The optional palette specifies the colors used to create the enhanced metafile. The remaining records identify the GDI functions used to create the picture. The following hexadecimal output corresponds to a record generated for a call to the SetMapMode function.

00000011 0000000C 00000004

The value 0x00000011 specifies the record type (corresponds to the EMR_SETMAPMODE constant defined in the file WINGDI.H). The value 0x0000000C specifies the length of the record, in bytes. The value 0x00000004 identifies the mapping mode (corresponds to the MM_LOENGLISH constant defined in the file WINGDI.H).


 Enhanced Metafile Operations

A developer creates an enhanced metafile by using the CreateEnhMetaFile function and supplying the appropriate arguments. The Win32 API uses these arguments to maintain picture dimensions, to determine whether the metafile should be stored on a disk or in memory, and so on.

To maintain picture dimensions across output devices, the Win32 API requires the resolution of the reference device. This reference device is the device on which the picture first appeared, and the reference DC is the DC associated with the reference device. When calling the CreateEnhMetaFile function, the application must supply a handle that identifies this DC. The application can get this handle by calling the GetDC or CreateDC function or specify NULL as the handle to use the current display device for the reference device.

Most applications store pictures permanently and therefore create an enhanced metafile that is stored on a disk; however, there are some instances when this is not necessary. For example, a word-processing application that provides chart-drawing capabilities could store a user-defined chart in memory as an enhanced metafile and then copy the enhanced metafile bits from memory into the user's document file. An application that requires a metafile that is stored permanently on a disk must supply the filename when it calls the CreateEnhMetaFile function. If the developer does not supply a filename, Windows automatically treats the metafile as a temporary file and stores it in memory.

The developer can add an optional text description to a metafile containing information about the picture and the author. An application can display these strings in the File Open dialog box to provide the user with information about metafile content that will help in selecting the appropriate file. If an application includes the text description, the application must supply a pointer to the string when it calls the CreateEnhMetaFile function.

When the CreateEnhMetaFile function is successful, it returns a handle that identifies a special metafile DC. A metafile DC is unique in that it is associated with a file rather than with an output device. When Windows processes a GDI function that received a handle to a metafile DC, it converts the GDI function into an enhanced-metafile record and appends the record to the end of the enhanced metafile.

After a picture is complete and the last record is appended to the enhanced metafile, the application can close the file by calling the CloseEnhMetaFile function. This function closes and deletes the special metafile DC and returns a handle identifying the enhanced metafile. The application can use this handle to accomplish the following tasks.

•	Display the picture stored in the enhanced metafile.

•	Create copies of the enhanced metafile.

•	Enumerate, edit, or copy the individual records in the enhanced metafile.

•	Retrieve the optional description that is stored in the enhanced metafile.

•	Retrieve a copy of the enhanced-metafile header.

•	Retrieve a binary version of the enhanced metafile.

•	Enumerate the colors in the optional palette.

•	Convert an enhanced-format metafile into a Windows-format metafile.

Some applications create temporary backup (or duplicate) copies of a file before enabling the user to alter the original. An application can create a backup copy of an enhanced metafile by calling the CopyEnhMetaFile function, supplying a handle that identifies the enhanced metafile, and supplying a pointer to the name of the new file.

Most drawing, illustration, and computer-aided design (CAD) applications require a means of editing a picture stored in an enhanced metafile. Although editing an enhanced metafile is a complex task, a developer can use the EnumEnhMetaFile function in combination with other Win32 functions to provide this capability in your application. The EnumEnhMetaFile function and its associated callback function enable the application to process individual records in an enhanced metafile.

Some applications display the text description of an enhanced metafile with the corresponding filename in the File Open dialog box. An application can determine whether this string exists in an enhanced metafile by retrieving the metafile header and examining one of its members. The GetEnhMetaFileHeader function can retrieve the metafile header. If the string exists, the application retrieves it by calling the GetEnhMetaFileDescription function.

Some applications retrieve the contents of a metafile by calling the GetEnhMetaFileBits function; however, before retrieving the contents, the application must specify the size of the file. To get the size, the application can use the GetEnhMetaFileHeader function and examine the appropriate member.

To achieve consistent colors when a picture is displayed on various output devices, an application can call the CreatePalette function and store a logical palette in an enhanced metafile. Other applications that display the picture stored in the enhanced metafile retrieve this palette and call the RealizePalette function before displaying the picture. To determine whether a palette is stored in an enhanced metafile, an application can retrieve the metafile header and examine the appropriate member. If a palette exists, the application can call the GetEnhMetaFilePaletteEntries function to retrieve the logical palette.


 Windows-Format Metafiles

The Win32 API supports the Windows metafile format to maintain compatibility with applications written for Windows version 3.x. Following are the limitations of this format.

•	A Windows-format metafile is application and device dependent. Changes in the application's mapping modes or the device resolution affect the appearance of metafiles created in this format.

•	A Windows-format metafile does not contain a comprehensive header that describes the original picture dimensions, the resolution of the device on which the picture was created, an optional text description, or an optional palette.

•	A Windows-format metafile does not support the new curve, path, and transformation functions.

•	Some Windows-format metafile records cannot be scaled.

•	The metafile DC associated with a Windows-format metafile cannot be queried (that is, an application cannot retrieve device-resolution data, font metrics, and so on).

To convert a Windows-format metafile to an enhanced-format metafile, an application can call the GetMetaFileBitsEx function to retrieve the data from the Windows-format metafile and then call the SetWinMetaFileBits function to convert this data into an enhanced-format metafile.

A developer writing a Win32-based application should avoid using the Windows-format functions and use the enhanced-format functions instead.


 Using Metafiles

•	Creating an enhanced metafile

•	Displaying a picture and storing it in an enhanced metafile

•	Opening an enhanced metafile and displaying its contents

•	Editing an enhanced metafile


 Creating an Enhanced Metafile

This section contains an example that demonstrates the creation of an enhanced metafile that is stored on a disk, using a filename specified by the user.

The example uses a DC for the application window as the reference DC. (Windows stores the resolution data for this device in the enhanced-metafile's header.) The application retrieves a handle identifying this DC by calling the GetDC function.

The example uses the dimensions of the application's client area to define the dimensions of the picture frame. Using the rectangle dimensions returned by the GetClientRect function, the application converts the device units to .01-millimeter units and passes the converted values to the CreateEnhMetaFile function.

The example displays a Save As common dialog box that enables the user to specify the filename of the new enhanced metafile. The system appends the three-character .EMF extension to this filename and passes the name to the CreateEnhMetaFile function.

The example also embeds a text description of the picture in the enhanced-metafile header. This description is specified as a resource in the string table of the application's resource file. However, in a working application, this string would be retrieved from a custom control in a common dialog box or from a separate dialog box displayed solely for this purpose.

/* Obtain a handle to a reference DC. */

hdcRef = GetDC(hWnd);

/*

 * Determine the picture frame dimensions.

 * iWidthMM is the display width in millimeters.

 * iHeightMM is the display height in millimeters.

 * iWidthPels is the display width in pixels.

 * iHeightPels is the display height in pixels

 */

iWidthMM = GetDeviceCaps(hdcRef, HORZSIZE);

iHeightMM = GetDeviceCaps(hdcRef, VERTSIZE);

iWidthPels = GetDeviceCaps(hdcRef, HORZRES);

iHeightPels = GetDeviceCaps(hdcRef, VERTRES);

/*

 * Retrieve the coordinates of the client

 * rectangle, in pixels.

 */

GetClientRect(hWnd, &rect);

/*

 * Convert client coordinates to .01-mm units.

 * Use iWidthMM, iWidthPels, iHeightMM, and

 * iHeightPels to determine the number of

 * .01-millimeter units per pixel in the x-

 *  and y-directions.

 */

rect.left = (rect.left * iWidthMM * 100)/iWidthPels;

rect.top = (rect.top * iHeightMM * 100)/iHeightPels;

rect.right = (rect.right * iiWidthMM * 100)/iWidthPels;

rect.bottom = (rect.bottom * iHeightMM * 100)/iHeightPels;

/* Load the filename filter from the string table. */

LoadString(hInst, IDS_FILTERSTRING,

     (LPSTR)szFilter, sizeof(szFilter));

/*

 * Replace the '%' separators that are embedded

 * between the strings in the string-table entry

 * with '\0'.

 */

for (i=0; szFilter[i]!='\0'; i++)

    if (szFilter[i] == '%')

            szFilter[i] = '\0';

/* Load the dialog title string from the table. */

LoadString(hInst, IDS_TITLESTRING,

     (LPSTR)szTitle, sizeof(szTitle));

/* Initialize the OPENFILENAME members. */

szFile[0] = '\0';

Ofn.lStructSize = sizeof(OPENFILENAME);

Ofn.hwndOwner = hWnd;

Ofn.lpstrFilter = szFilter;

Ofn.lpstrFile= szFile;

Ofn.nMaxFile = sizeof(szFile);

Ofn.lpstrFileTitle = szFileTitle;

Ofn.nMaxFileTitle = sizeof(szFileTitle);

Ofn.lpstrInitialDir = (LPSTR)NULL;

Ofn.Flags = OFN_SHOWHELP | OFN_OVERWRITEPROMPT;

Ofn.lpstrTitle = szTitle;

/*

 * Display the Filename common dialog box. The

 * filename specified by the user is passed

 * to the CreateEnhMetaFile function and used to

 * store the metafile on disk.

 */

GetSaveFileName(&Ofn);

/* Load the description from the string table. */

LoadString(hInst, IDS_DESCRIPTIONSTRING,

     (LPSTR)szDescription, sizeof(szDescription));

/*

 * Replace the '%' string separators that are

 * embedded between strings in the string-table

 * entry with '\0'.

 */

for (i=0; szDescription[i]!='\0'; i++)

    if (szDescription[i] == '%')

            szDescription[i] = '\0';

/* Create the metafile DC. */

hdcMeta = CreateEnhMetaFile(hdcRef,

          (LPTSTR) Ofn.lpstrFile,

          &rect, (LPSTR)szDescription);

if (!hdcMeta)

    errhandler("CreateEnhMetaFile", hWnd);

/* Release the reference DC. */

ReleaseDC(hWnd, hdcRef);


 Displaying a Picture and Storing It in an Enhanced Metafile

This section contains an example demonstrating the creation of a picture and the process of storing the corresponding records in a metafile. The example draws a picture to the display or stores it in a metafile. If a display DC handle is given, it draws a picture to the screen using various GDI functions. If an enhanced metafile DC is given, it stores the same picture in the enhanced metafile.

void DrawOrStore(HWND hwnd, HDC hdcMeta, HDC hdcDisplay)

{

RECT rect;

HDC hDC;

int fnMapModeOld;

HBRUSH hbrOld;

/* Draw it to the display DC or store it in the metafile DC. */

if (hdcMeta)

    hDC = hdcMeta;

else

    hDC = hdcDisplay;

/* Set the mapping mode in the DC. */

fnMapModeOld = SetMapMode(hDC, MM_LOENGLISH);

/* Find the midpoint of the client area. */

GetClientRect(hwnd, (LPRECT)&rect);

DPtoLP(hDC, (LPPOINT)&rect, 2);

/* Select a gray brush. */

hbrOld = SelectObject(hDC, GetStockObject(GRAY_BRUSH));

/* Draw a circle with a one inch raduis. */

Ellipse(hDC, (rect.right/2 - 100), (rect.bottom/2 + 100),

       (rect.right/2 + 100), (rect.bottom/2 - 100));

/* Perform additional drawing here. */

/* Set the device context back to its original state. */

SetMapMode(hDC, fnMapModeOld);

SelectObject(hDC, hbrOld);

}


 Opening an Enhanced Metafile and Displaying Its Contents

This section contains an example demonstrating how an application opens an enhanced metafile stored on disk and displays the associated picture in the client area.

The example uses the Open common dialog box to enable the user to select an enhanced metafile from a list of existing files. It then passes the name of the selected file to the GetEnhMetaFile function, which returns a handle identifying the file. This handle is passed to the PlayEnhMetaFile function in order to display the picture.

LoadString(hInst, IDS_FILTERSTRING,

     (LPSTR)szFilter, sizeof(szFilter));

/*

 * Replace occurrences of '%' string separator

 * with '\0'.

 */

for (i=0; szFilter[i]!='\0'; i++)

    if (szFilter[i] == '%')

            szFilter[i] = '\0';

LoadString(hInst, IDS_DEFEXTSTRING,

     (LPSTR)szDefExt, sizeof(szFilter));

/*

 * Use the OpenFilename common dialog box

 * to obtain the desired filename.

 */

 szFile[0] = '\0';

 Ofn.lStructSize = sizeof(OPENFILENAME);

 Ofn.hwndOwner = hWnd;

 Ofn.lpstrFilter = szFilter;

 Ofn.lpstrCustomFilter = (LPSTR)NULL;

 Ofn.nMaxCustFilter = 0L;

 Ofn.nFilterIndex = 1L;

 Ofn.lpstrFile = szFile;

 Ofn.nMaxFile = sizeof(szFile);

 Ofn.lpstrFileTitle = szFileTitle;

 Ofn.nMaxFileTitle = sizeof(szFileTitle);

 Ofn.lpstrInitialDir = (LPSTR) NULL;

 Ofn.lpstrTitle = (LPSTR)NULL;

 Ofn.Flags = OFN_SHOWHELP | OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;

 Ofn.nFileOffset = 0;

 Ofn.nFileExtension = 0;

 Ofn.lpstrDefExt = szDefExt;

 GetOpenFileName(&Ofn);

/* Open the metafile. */

hemf = GetEnhMetaFile(Ofn.lpstrFile);

/* Retrieve a handle to a window DC. */

hDC = GetDC(hWnd);

/* Retrieve the client rectangle dimensions. */

GetClientRect(hWnd, &rct);

/* Draw the picture. */

PlayEnhMetaFile(hDC, hemf, &rct);

/* Release the metafile handle. */

DeleteEnhMetaFile(hemf);

/* Release the window DC. */

ReleaseDC(hWnd, hDC);


 Editing an Enhanced Metafile

To edit a picture stored in an enhanced metafile, an application must perform the following tasks.

1.	Use hit-testing to capture the cursor coordinates and retrieve the position of the object (line, arc, rectangle, ellipse, polygon, or irregular shape) that the user wants to alter.

2.	Convert these coordinates to logical (or world) units.

3.	Call the EnumEnhMetaFile function and examine each metafile record.

4.	Determine whether a given record corresponds to a GDI drawing function.

5.	If it does, determine whether the coordinates stored in the record correspond to the line, arc, ellipse, or other graphics element that intersects the coordinates specified by the user.

6.	Upon finding the record that corresponds to the output that the user wants to alter, erase the object on the screen that corresponds to the original record.

7.	Delete the corresponding record from the metafile, saving a pointer to its location.

8.	Permit the user to redraw or replace the object.

9.	Convert the GDI functions used to draw the new object into one or more enhanced-metafile records.

10.	Store these records in the enhanced metafile.


 Metafile Functions

Following are the functions used with enhanced format metafiles.

CloseEnhMetaFile
CopyEnhMetaFile
CreateEnhMetaFile
DeleteEnhMetaFile
EnhMetaFileProc
EnumEnhMetaFile
GdiComment
GetEnhMetaFile
GetEnhMetaFileBits
GetEnhMetaFileDescription
GetEnhMetaFileHeader
GetEnhMetaFilePaletteEntries
GetWinMetaFileBits
PlayEnhMetaFile
PlayEnhMetaFileRecord
SetEnhMetaFileBits
SetWinMetaFileBits

The following functions are provided for compatibility with Windows-format metafiles:

CloseMetaFile
CopyMetaFile
CreateMetaFile
DeleteMetaFile
EnumMetaFile
EnumMetaFileProc
GetMetaFile
GetMetaFileBitsEx
PlayMetaFile
PlayMetaFileRecord
SetMetaFileBitsEx


 Paths

A path is one or more figures (or shapes) that are filled, outlined, or both filled and outlined. Applications written for Microsoft® Windows® use paths in many ways. Paths are used in drawing and painting applications. Computer-aided design (CAD) applications use paths to create unique clipping regions, to draw outlines of irregular shapes, and to fill the interiors of irregular shapes. An irregular shape is a shape composed of Bézier curves and straight lines. (A regular shape is an ellipse, a circle, a rectangle, or a polygon.)


 About Paths

A path is one of the objects associated with a device context (DC). However, unlike the default objects (the pen, the brush, and the font) that are part of any new DC, there is no default path. For more information about DCs, see Device Contexts.

To create a path and select it into a DC, it is first necessary to define the points that describe it. This is done by calling the BeginPath function, specifying the appropriate drawing functions, and then by calling the EndPath function. This combination of functions (BeginPath, drawing functions, and EndPath) constitute a path bracket. The following functions can be used in a path bracket.

AngleArc	LineTo	Polyline
Arc	MoveToEx	PolylineTo
ArcTo	Pie	PolyPolygon
Chord	PolyBezier	PolyPolyline
CloseFigure	PolyBezierTo	Rectangle
Ellipse	PolyDraw	RoundRect
ExtTextOut	Polygon	TextOut
When an application calls EndPath, Windows selects the associated path into the specified DC. (If another path had previously been selected into the DC, Windows deletes that path without saving it.) After Windows selects the path into the DC, an application can operate on the path in one of the following ways:

•	Draw the outline of the path (using the current pen).

•	Paint the interior of the path (using the current brush).

•	Draw the outline and fill the interior of the path.

•	Modify the path (converting curves to line segments).

•	Convert the path into a clip path.

•	Convert the path into a region.

•	Flatten the path by converting each curve in the path into a series of line segments.

•	Retrieve the coordinates of the lines and curves that compose a path.


 Outlined and Filled Paths

An application can draw the outline of a path by calling the StrokePath function, it can fill the interior of a path by calling the FillPath function, and it can both outline and fill the path by calling the StrokeAndFillPath function.

Whenever an application fills a path, Windows uses the DC's current fill mode. An application can retrieve this mode by calling the GetPolyFillMode function, and it can set a new fill mode by calling the SetPolyFillMode function. For a description of the two fill modes, see Regions.

The following illustration shows the cross-section of an object created by a computer-aided design (CAD) application using paths that were both outlined and filled.


 Transformations of Paths

Paths are defined using logical units and current transformations. (If the SetWorldTransform function has been called, the logical units are world units; otherwise, the logical units are page units.) An application can use world transformations to scale, rotate, shear, translate, and reflect the lines and Bézier curves that define a path.

Note  A world transformation within a path bracket only affects those lines and curves drawn after the transformation was set. It will have no affect on those lines and curves that were drawn before it was set. For a description of the world transformation, see Coordinate Spaces and Transformations.

An application can also use SetWorldTransform to outline the shape of the pen used to outline a path if the pen is a geometric pen. For a description of geometric pens, see Pens.


 Clip Paths and Graphic Effects

An application can use clipping and paths to create special graphic effects. The following illustration shows a string of text drawn with a large Arial font.

The next illustration shows the result of selecting the text as a clip path and drawing radial lines for a circle whose center is located above and left of the string.

Note  Before graphics device interface (GDI) adds text created with a bitmapped font to a path, it converts the font to an outline or vector font.

An application creates a clip path by generating a path bracket and then calling the SelectClipPath function. After a clip path is selected into a DC, output only appears within the borders of the path.

In addition to creating special graphics effects, clip paths are also useful in applications that save images as enhanced metafiles. By using a clip path, an application is able to ensure device independence because the units used to specify a path are logical units (as opposed to device units that are used to specify a region).


 Conversion of Paths to Regions

An application can convert a path into a region by calling the PathToRegion function. Like SelectClipPath, PathToRegion is useful in the creation of special graphics effects. For example, there are no functions that allow an application to offset a path; however, there is a function that enables an application to offset a region (OffsetRgn). Using PathToRegion, an application can create the effect of animating a complex shape by creating a path that defines the shape, converting the path into a region (by calling PathToRegion), and then repeatedly painting, moving, and erasing the region (by calling functions in a sequence, such as FillRgn, OffsetRgn, and FillRgn).


 Curved Paths

An application can flatten the curves in a path by calling the FlattenPath function. This function is especially useful for applications that fit text onto the contour of a path which contains curves. To fit the text, the application must perform the following steps:

1.	Create the path where the text appears.

2.	Call the FlattenPath function to convert the curves in a path into line segments.

3.	Call the GetPath function to retrieve those line segments.

4.	Calculate the length of each line and the width of each character in the string.

5.	Use line-width and character-width data to position each character along the curve.


 Using Paths

This section contains a code sample that enables the user to select a font of a particular point size (by using the Choose Font dialog box), select a clip path (by using text drawn with this font), and then view the result of clipping to the text.

This code sample was used to create the illustration that appears in Clip Paths.

CHOOSEFONT cf;          /* common dialog box font structure */

LOGFONT lf;             /* logical font structure */

HFONT hfont;            /* new logical font handle */

HFONT hfontOld;         /* original logical font handle */

HDC hdc;                /* display DC handle */

int nXStart, nYStart;   /* drawing coordinates */

RECT rc;                /* rect structure for painting window */

SIZE sz;                /* structure that receives text extents */

double aflSin[90];      /* sine of 0-90 degrees */

double aflCos[90];      /* cosine of 0-90 degrees */

double flRadius,a;      /* radius of circle */

int iMode;              /* clipping mode */

HRGN hrgn;              /* clip region handle */

LRESULT APIENTRY MainWndProc(

    HWND hwnd,                /* window handle                   */

    UINT message,             /* type of message                 */

    WPARAM wParam,            /* additional information          */

    LPARAM lParam)            /* additional information          */

{

    PAINTSTRUCT ps;

    switch (message) {

        case WM_PAINT:

            hdc = BeginPaint(hwnd, &ps);

            EndPaint(hwnd, &ps);

            break;

        case WM_COMMAND:     /* command from app's menu */

            switch (wParam) {

                case IDM_VANISH:  /* erases client area */

                    hdc = GetDC(hwnd);

                    GetClientRect(hwnd, &rc);

                    FillRect(hdc, &rc, GetStockObject(WHITE_BRUSH));

                    ReleaseDC(hwnd, hdc);

                    break;

                case IDM_AND: /* sets clip mode to RGN_AND */

                    iMode = RGN_AND;

                    break;

                case IDM_COPY: /* sets clip mode to RGN_COPY */

                    iMode = RGN_COPY;

                    break;

                case IDM_DIFF: /* sets clip mode to RGN_DIFF */

                    iMode = RGN_DIFF;

                    break;

                case IDM_OR: /* sets clip mode to RGN_OR */

                    iMode = RGN_OR;

                    break;

                case IDM_XOR: /* sets clip mode to RGN_XOR */

                    iMode = RGN_XOR;

                    break;

                case IDM_CLIP_PATH:

                    /* Retrieve a cached DC for the window. */

                    hdc = GetDC(hwnd);

                    /*

                     * Use the font requested by the user in the

                     * Choose Font dialog box to create a logical font,

                     * then select that font into the device context.

                     */

                    hfont = CreateFontIndirect(cf.lpLogFont);

                    hfontOld = SelectObject(hdc, hfont);

                    /*

                     * Retrieve the dimensions of the rectangle

                     * that surrounds the text.

                     */

                     GetTextExtentPoint32(hdc, "Clip Path", 9, &sz);

                    /*

                     * Set a clipping region using the rect that

                     * surrounds the text.

                     */

                     hrgn = CreateRectRgn(nXStart, nYStart,

                         nXStart + sz.cx,

                         nYStart + sz.cy);

                     SelectClipRgn(hdc, hrgn);

                    /*

                     * Create a clip path using text drawn with

                     * the user's requested font.

                     */

                    BeginPath(hdc);

                        TextOut(hdc, nXStart, nYStart, "Clip Path", 9);

                    EndPath(hdc);

                    SelectClipPath(hdc, iMode);

                    /* Compute the sine of 0, 1, ... 90 degrees. */

                    for (i = 0; i < 90; i++) {

                        aflSin[i] = sin( (((double)i) / 180.0)

                                    * 3.14159);

                        }

                    /* Compute the cosine of 0, 1,... 90 degrees. */

                    for (i = 0; i < 90; i++) {

                        aflCos[i] = cos( (((double)i) / 180.0)

                                    * 3.14159);

                        }

                    /* Set the radius value. */

                    flRadius = (double)(2 * sz.cx);

                    /*

                     * Draw the 90 rays extending from the

                     * radius to the edge of the circle.

                     */

                    for (i = 0; i < 90; i++) {

                        MoveToEx(hdc, nXStart, nYStart,

                           (LPPOINT) NULL);

                        LineTo(hdc, nXStart + ((int) (flRadius

                            * aflCos[i])),

                               nYStart + ((int) (flRadius

                            * aflSin[i])));

                        }

                    /* Reselect the original font into the DC. */

                     SelectObject(hdc, hfontOld);

                    /* Delete the user's font. */

                     DeleteObject(hfont);

                    /* Release the DC. */

                    ReleaseDC(hwnd, hdc);

                    break;

                case IDM_FONT:

                    /* Initialize necessary members. */

                    cf.lStructSize = sizeof (CHOOSEFONT);

                    cf.hwndOwner = hwnd;

                    cf.lpLogFont = &lf;

                    cf.Flags = CF_SCREENFONTS | CF_EFFECTS;

                    cf.rgbColors = RGB(0, 255, 255);

                    cf.nFontType = SCREEN_FONTTYPE;

                    /*

                     * Display the Font dialog box, allow the user

                     * to choose a font, and render text in the

                     * window with that selection.

                     */

                    if (ChooseFont(&cf)) {

                        hdc = GetDC(hwnd);

                        hfont = CreateFontIndirect(cf.lpLogFont);

                        hfontOld = SelectObject(hdc, hfont);

                        crOld = SetTextColor(hdc, cf.rgbColors);

                        TextOut(hdc, nXStart, nYStart,

                            "Clip Path", 9);

                        SetTextColor(hdc, crOld);

                        SelectObject(hdc, hfontOld);

                        DeleteObject(hfont);

                        ReleaseDC(hwnd, hdc);

                    }

                    break;

                default:

                    return DefWindowProc(hwnd, message, wParam,

                         lParam);

            }

            break;

        case WM_DESTROY:    /* window is being destroyed    */

            PostQuitMessage(0);

            break;

        default:                 /* if unprocessed...      */

            return DefWindowProc(hwnd, message, wParam, lParam);

    }

    return 0;

}


 Path Functions

Use the following functions to create, alter, or draw paths.

AbortPath
BeginPath
CloseFigure
EndPath
FillPath
FlattenPath
GetMiterLimit
GetPath
PathToRegion
SetMiterLimit
StrokeAndFillPath
StrokePath
WidenPath


 Pens

A pen is a graphics tool that an application for Microsoft® Windows® uses to draw lines and curves. Drawing applications use pens to draw freehand lines, straight lines, and curves. Computer-aided design (CAD) applications use pens to draw visible lines, hidden lines, section lines, center lines, and so on. Word processing and desktop publishing applications use pens to draw borders and rules. Spreadsheet applications use pens to designate trends in graphs and to outline bar graphs and pie charts.


 About Pens

There are two types of pen: cosmetic and geometric. A cosmetic pen is used with applications requiring lines of fixed width and lines that are quickly drawn. A CAD application, for example, uses a cosmetic pen to generate hidden, section, center, and dimension lines that are between .015 and .022 inches wide — regardless of the scale factor. A geometric pen is used with applications requiring scalable lines, lines with unique end or join styles, and lines that are wider than a single pixel. A spreadsheet application, for example, uses a geometric pen to define each of the bars in a bar graph as a wide line.


 Cosmetic Pens

The dimensions of a cosmetic pen are specified in device units. Therefore, lines drawn with a cosmetic pen always have a fixed width. Lines drawn with a cosmetic pen are generally drawn three to ten times faster than lines drawn with a geometric pen. Cosmetic pens have three attributes: width, style, and color. For more information about these attributes, see Pen Attributes.

To create a cosmetic pen, an application uses the CreatePen, CreatePenIndirect, or ExtCreatePen function. To retrieve one of the three stock cosmetic pens managed by window manager, the application uses the GetStockObject function.

After a pen is created (or a handle identifying one of the stock pens is obtained), the pen is selected into the application's device context (DC) by calling the SelectObject function. From this point on, the application uses this pen for any line-drawing operations in its client area.


 Geometric Pens

The dimensions of a geometric pen are specified in logical units. Therefore, lines drawn with a geometric pen can be scaled — that is, they may appear wider or narrower, depending on the current world transformation. For more information about the world transformation, see Coordinate Spaces and Transformations.

In addition to the three attributes shared with cosmetic pens (width, style, and color), geometric pens possess the following four attributes: pattern, optional hatch, end style, and join style. For more information about these attributes, see Pen Attributes.

To create a geometric pen, an application uses the ExtCreatePen function. As with cosmetic pens, the SelectObject function selects a geometric pen into the application's DC.


 Pen Attributes

There are seven pen attributes that define the type of pen and its characteristics: width, style, color, pattern, hatch, end style, and join style. Both cosmetic and geometric pens have the width, style, and color attributes. Only geometric pens have the pattern, hatch, end style, and join style attributes. The pattern and optional hatch attribute are usually associated with a brush, but can also be used with geometric pens.


 Width

The width attribute specifies a cosmetic pen width in device units. When used with a geometric pen, however, it specifies the pen's width in logical units. For more information about device units, see Coordinate Spaces and Transformations.

Currently, Windows limits the width of cosmetic pens to a single pixel; however, future versions may remove this limitation.


 Style

The style attribute specifies the line pattern that appears when a particular cosmetic or geometric pen is used. There are eight predefined pen styles. The following illustration shows the seven of these styles that are defined by Windows.

The inside-frame style is identical to the solid style for cosmetic pens. However, it operates differently when used with a geometric pen. If the geometric pen is wider than a single pixel and a drawing function uses the pen to draw a border around a filled object, Windows draws the border inside the object's frame. By using the inside-frame style, an application can ensure that an object appears entirely within the specified dimensions, regardless of the geometric pen width.

In addition to the seven styles defined by Windows, there is an eighth style that is user (or application) defined. A user-defined style generates lines with a customized series of dashes and dots.

Use the CreatePen, CreatePenIndirect, or ExtCreatePen function to create a pen that has the Windows-defined styles. Use the ExtCreatePen function to create a pen that has a user-defined style.


 Color

The color attribute specifies the pen's color. An application can create a cosmetic pen with a unique color by storing the red, green, blue (RGB) triplet that specifies the desired color in a COLORREF structure and passing this structure's address to the CreatePen, CreatePenIndirect, or ExtCreatePen function. (The stock pens are limited to black, white, and invisible.) For more information about RGB triplets and color, see Colors.


 Pattern

The pattern attribute specifies the pattern of a geometric pen.

The following illustration shows lines drawn with different geometric pens. Each pen was created using a different pattern attribute.

The first line in the previous illustration is drawn using one of the six available hatch patterns; for more information about hatch patterns, see Hatch. The next line is drawn using the hollow pattern, identical to the null pattern. The third line is drawn using a custom pattern created from an 8- by 8-pixel bitmap. (For more information about bitmaps and their creation, see Bitmaps.) The last line is drawn using a solid pattern. Creating a brush and passing its handle to the ExtCreatePen function creates a pattern.


 Hatch

The hatch attribute specifies the hatch type of a geometric pen with the hatch pattern attribute. There are six patterns available. The following illustration shows lines drawn using different hatch patterns.


 End Cap

The end cap attribute specifies the shape of a geometric pen: round, square, or flat. The following illustration shows parallel lines drawn using each type of end cap.

The round and square end caps extend past the starting and ending points of a line drawn with a geometric pen; the flat end cap does not.


 Join

The join attribute specifies how the ends of two geometric lines are joined: beveled, mitered, or round. The following illustration shows pairs of connected lines drawn using each type of join.


 Using Pens

This section contains sample code that demonstrates the appearance of lines drawn using various pen styles and attributes.

LRESULT CALLBACK MainWndProc(HWND hWnd, UINT uMsg, WPARAM wParam,

                             LPARAM lParam)

{

    PAINTSTRUCT ps;

    LOGBRUSH lb;

    RECT rc;

    HDC hdc;

    int i;

    HPEN hPen, hPenOld;

    DWORD dwPenStyle[] = {

                           PS_DASH,

                           PS_DASHDOT,

                           PS_DOT,

                           PS_INSIDEFRAME,

                           PS_NULL,

                           PS_SOLID

                        };

    UINT uHatch[] = {

                      HS_BDIAGONAL,

                      HS_CROSS,

                      HS_DIAGCROSS,

                      HS_FDIAGONAL,

                      HS_HORIZONTAL,

                      HS_VERTICAL

                     };

    switch (uMsg)

    {

        case WM_PAINT:

        {

            GetClientRect(hWnd, &rc);

            rc.left += 10;

            rc.top += 10;

            rc.bottom -= 10;

            /* Initialize the pen's "brush." */

            lb.lbStyle = BS_SOLID;

            lb.lbColor = RGB(255,0,0);

            lb.lbHatch = 0;

            hdc = BeginPaint(hWnd, &ps);

            for (i = 0; i < 6; i++)

            {

                hPen = ExtCreatePen(PS_COSMETIC | dwPenStyle[i],

                                    1, &lb, 0, NULL);

                hPenOld = SelectObject(hdc, hPen);

                MoveToEx(hdc, rc.left + (i * 20), rc.top, NULL);

                LineTo(hdc, rc.left + (i * 20), rc.bottom);

                SelectObject(hdc, hPenOld);

                DeleteObject(hPen);

            }

            rc.left += 150;

            for (i = 0; i < 6; i++)

            {

                lb.lbStyle = BS_HATCHED;

                lb.lbColor = RGB(0,0,255);

                lb.lbHatch = uHatch[i];

                hPen = ExtCreatePen(PS_GEOMETRIC,

                                    5, &lb, 0, NULL);

                hPenOld = SelectObject(hdc, hPen);

                MoveToEx(hdc, rc.left + (i * 20), rc.top, NULL);

                LineTo(hdc, rc.left + (i * 20), rc.bottom);

                SelectObject(hdc, hPenOld);

                DeleteObject(hPen);

            }

            EndPaint(hWnd, &ps);

        }

        break;

        case WM_DESTROY:

            DeleteObject(hPen);

            PostQuitMessage(0);

            break;

        default:

            return DefWindowProc(hWnd, uMsg, wParam, lParam);

    }

    return FALSE;

}


 Pen Functions

Following are the functions that support the pen interface.

CreatePen
CreatePenIndirect
ExtCreatePen


 Printing and Print Spooler

Microsoft® Windows® provides a complete set of functions that allow applications to print on a variety of devices: laser printers, vector plotters, raster printers, and fax machines.


 About Printing

One of the chief features of Windows printing functions is their support of device independence; instead of issuing device-specific commands to draw output on a particular printer or plotter, an application calls high-level functions from graphics device interface (GDI). For example, to print a bitmapped image, an application can call the BitBlt function, supplying the coordinates for the bitmap as well as handles identifying the source and destination device contexts (DCs). The call to BitBlt is then converted to raw device commands by a printer device driver. A device driver is a Windows dynamic-link library (DLL) that supports the Windows device driver interface (DDI). A device driver generates raw device commands when it processes calls to DDI functions made by the graphics engine. The commands are processed by the printer when it prints the image. The syntax, number, and type of these commands vary from device to device.


 Default Printing Interface

In addition to GDI and the device driver, the default printing interface consists of several other components that process output before it arrives at the printer. These components are the print spooler, the print processor, the graphics engine, and the monitor.


 Print Spooler

The primary component of the printing interface is the print spooler. The print spooler is a Windows executable file that manages the printing process. Management of printing involves retrieving the location of the correct printer driver, loading that driver, converting high-level function calls to journal records, storing those journal records on disk as a print job, and so on.

The spooler is loaded at startup and continues to run until the operating system is shut down. Windows Print Manager provides a graphical interface that the user or system administrator can use to access and configure the spooler; however, if Print Manager is disabled or shut down, the spooler continues to run.

Applications that print create a printer DC. When an application creates a printer DC, the spooler performs necessary tasks such as determining the location of the required printer driver and then loading the appropriate printer driver. It also determines the data type used to record the print job. The supported data types include journal records, ASCII text, and PostScript®. A print job is a document stored internally (by using one of the supported data types) that may contain one or more pages of output. It may consist of multiple forms; for example, a job may consist of one envelope and three pages of A4 paper. A print job is defined (or bracketed) by the StartDoc and EndDoc functions.

The default data type for a print job is the journal record. A journal record is a compact structure used to store text output commands, raster graphics commands, and so on. When an application calls StartDoc, the spooler creates a journal file and a data file and begins storing journal records in the journal file. Each time the application calls one of the GDI drawing functions, one or more new journal records are created and stored in the journal file. The journal and data files are created in an operating system directory. The spooler uses the journal file to store journal records and uses the data file to record the type of form, the data type for the print job, the target printer, and so on. These files are deleted by the spooler when the job has successfully printed.


 Print Processor

The spooler monitors the current print jobs and the target printer to determine an appropriate time to print a job. Once the spooler determines that a job should be printed, it calls the print processor. The print processor is a Windows DLL that reads and converts journal records into DDI calls.


 Graphics Engine

The graphics engine is a Windows DLL that converts print processor output into calls to device driver functions. The device driver, in turn, processes these calls and converts them into raw device commands that the device can process.


 Monitor

Once a device driver has converted an entire journal file into raw device commands, the file of converted commands is passed back to the spooler. The spooler sends these low-level commands to a monitor. A monitor is a Windows DLL that passes the raw device commands over the network, through a parallel port, or through a serial port to the device.


 Printer Device Contexts Overview

Just as an application requires a display DC before it can begin drawing in the client area of a window, it needs a special printer DC before it can begin sending output to a printer. A printer DC is similar to a display DC in that it is an internal data structure that defines a set of graphic objects and their associated attributes and specifies the graphic modes that affect output. The graphic objects include a pen (for line drawing), a brush (for painting and filling), and a font (for text output).

Unlike a display DC, printer DCs are not owned by the window management component, and they cannot be obtained by calling the GetDC function. Instead, an application must call the CreateDC or PrintDlg function. When an application calls CreateDC, it must supply a driver and port name. This data is stored in one of the operating system initialization (.INI) files. It can be retrieved by calling the EnumPrinters function.

When an application calls PrintDlg and specifies the PD_RETURNDC value in the Flags member of the PRINTDLG structure, Windows automatically returns a handle identifying the user's selected printer DC. For an example that demonstrates this task, see Using a Print Dialog Box and Retrieving a Printer Device Context.


 Printer Escapes

Windows version 3.x supported as many as 64 special functions called printer escapes that applications used to access special device features. An application called these functions by specifying one of 64 predefined values as the second parameter to the Escape function. For example, one of these applications printing on a PostScript printer could draw a PostScript graphic object called a path by calling the Escape function and supplying the BEGIN_PATH and END_PATH values. Most of these escapes are obsolete in the Microsoft® Win32® application programming interface (API) but are provided to simplify the porting of 16-bit Windows-based applications. The Win32 version of GDI supports a complete set of path functions that applications can use instead of the escapes to draw paths on any device. For a list of the Win32 functions that replace some of the escapes, see the Escape function.

Of the 64 original printer escapes, only the QUERYESCSUPPORT and the PASSTHROUGH escapes can be used by Win32-based applications:

Applications written for Windows 3.x can also use QUERYESCSUPPORT and PASSTHROUGH as well as the following 10 escapes. Note that the following escapes are only supported for backwards compatibility with Windows 3.x-based applications. The Escape function may fail if a Win32-based application uses any of these.

•	ABORTDOC

•	ENDDOC

•	GETPHYSPAGESIZE

•	GETPRINTINGOFFSET

•	GETSCALINGFACTOR

•	NEWFRAME

•	NEXTBAND

•	SETABORTPROC

•	SETCOPYCOUNT

•	STARTDOC

In addition to supporting Escape, the Win32 API provides a new extended escape function called ExtEscape. This function allows applications to access capabilities of a particular device not directly available through GDI.


 WYSIWYG Display and Output

Most applications attempt to support WYSIWYG (what you see is what you get) output. This means that text drawn with a 10-point Helvetica bold font in the application window should have a similar appearance when it is printed. Obtaining true WYSIWYG output is virtually impossible and even undesirable in most cases. This is due, in part, to the differences in video and printer technologies; a pixel on a screen is generally larger than a dot on a common laser printer. Viewing distances are different as well; a computer user typically sits about two feet away from the screen, but a reader's eyes are usually one foot or less from the printed page.

To compensate for legibility differences between screens and the printed page, Windows supports a unit called the logical inch that is always specified in pixels. For a video display, the logical inch is always greater than the physical inch to compensate for the longer viewing distance and the (generally) coarser resolution. For printers, the logical inch is always equal to the physical inch.

To obtain a WYSIWYG effect when drawing text, an application can use the CreateFont function to specify the typeface name and point size of an ideal (or logical) font and then call the SelectObject function to identify the display or printer DC. When the application calls SelectObject, Windows selects a physical font that is the closest possible match to the specified logical font. When Windows selects the display font, it chooses a physical font that is larger than the actual point size. From the user's perspective, however, it appears to be very close to the correct height. When Windows selects the font for the printer, it chooses a physical font that is actually the requested point size. For more information about fonts and text output, see Fonts and Text.

To obtain a WYSIWYG effect when drawing bitmapped graphics, an application can retrieve the width and height, in logical inches, of the screen and the printed page. Using these values, the application can create horizontal and vertical scaling factors to maintain the proportion of bitmapped images when they are drawn on a printer. For an example that demonstrates this process, see WYSIWYG Display and Output. For more information about bitmaps and bitmap output, see Bitmaps.


 Using the Printing Functions

This section contains examples that demonstrate how to print text and graphics. The code was taken from an application that allows a user to open and display a 16-color bitmapped image that is stored as a .BMP file.

In addition to displaying the bitmapped image, the application allows the user to configure the printer and then print the image and a string of text specifying the location of the file that contained the image. The application prints the text at the top of the page and the image in the center of the page.

•	Opening and displaying a .BMP file

•	Using a print dialog box and retrieving a printer device context

•	Preparing to print

•	Printing a document


 Opening and Displaying a .BMP File

In the sample application, a user is able to open a .BMP file that contains a bitmapped image and display that image in the client area of the application's window. The user selects the file to be opened when the application displays the Open dialog box. (For more information about the Open dialog box, see Common Dialog Box Library.)

After the user selects a file and closes the dialog box, the file and path names are stored in members of the OPENFILENAME structure. The application uses this data to open the appropriate file and retrieve the bitmap header and data. The following code sample can be used to retrieve this data.

 /* Retrieve a handle identifying the file. */

 hfbm = CreateFile(ofn.lpstrFile, GENERIC_READ,

        FILE_SHARE_READ, (LPSECURITY_ATTRIBUTES) NULL,

        OPEN_EXISTING, FILE_ATTRIBUTE_READONLY,

        (HANDLE) NULL);

 /* Retrieve the BITMAPFILEHEADER structure. */

 ReadFile(hfbm, &bmfh, sizeof(BITMAPFILEHEADER),

     &dwRead, (LPOVERLAPPED)NULL);

 /* Retrieve the BITMAPFILEHEADER structure. */

 ReadFile(hfbm, &bmih, sizeof(BITMAPINFOHEADER),

     &dwRead, (LPOVERLAPPED)NULL);

 /* Allocate memory for the BITMAPINFO structure. */

 hmem1 = GlobalAlloc(GHND,

     sizeof(BITMAPINFOHEADER) +

     ((1<<bmih.biBitCount) * sizeof(RGBQUAD)));

 lpbmi = GlobalLock(hmem1);

 /*

  * Load BITMAPINFOHEADER into the BITMAPINFO

  * structure.

  */

 lpbmi->bmiHeader.biSize = bmih.biSize;

 lpbmi->bmiHeader.biWidth = bmih.biWidth;

 lpbmi->bmiHeader.biHeight = bmih.biHeight;

 lpbmi->bmiHeader.biPlanes = bmih.biPlanes;

 lpbmi->bmiHeader.biBitCount = bmih.biBitCount;

 lpbmi->bmiHeader.biCompression = bmih.biCompression;

 lpbmi->bmiHeader.biSizeImage = bmih.biSizeImage;

 lpbmi->bmiHeader.biXPelsPerMeter = bmih.biXPelsPerMeter;

 lpbmi->bmiHeader.biYPelsPerMeter = bmih.biYPelsPerMeter;

 lpbmi->bmiHeader.biClrUsed = bmih.biClrUsed;

 lpbmi->bmiHeader.biClrImportant = bmih.biClrImportant;

 /*

  * Retrieve the color table.

  * 1 << bmih.biBitCount == 2 ^ bmih.biBitCount

  */

 ReadFile(hfbm, lpbmi->bmiColors,

     ((1<<bmih.biBitCount) * sizeof(RGBQUAD)),

     &dwRead, (LPOVERLAPPED) NULL);

 /*

  * Allocate memory for the required number of

  * bytes.

  */

 hmem2 = GlobalAlloc(GHND,

     (bmfh.bfSize - bmfh.bfOffBits));

 lpvBits = GlobalLock(hmem2);

 /* Retrieve the bitmap data. */

 ReadFile(hfbm, lpvBits,

     (bmfh.bfSize - bmfh.bfOffBits),

     &dwRead, (LPOVERLAPPED) NULL);

 /*

  * Create a bitmap from the data stored in the

  * .BMP file.

  */

 hbm = CreateDIBitmap(hdc, &bmih,

     CBM_INIT, lpvBits,

     lpbmi, DIB_RGB_COLORS);

/*

 * Unlock the global memory objects and

 * close the .BMP file.

 */

 GlobalUnlock(hmem1);

 GlobalUnlock(hmem2);

 CloseHandle(hfbm);

 /* Set the fDisplayBitmap flag. */

 if (hbm)

     fDisplayBitmap = TRUE;

 else

     TextOut(hdc, 100, 100, "LoadBitmap Failed", 17);

 /* Paint the window (and draw the bitmap). */

 GetClientRect(hwnd, &rect);

 InvalidateRect(hwnd, &rect, TRUE);

 UpdateWindow(hwnd);

Once the bitmap data is retrieved, the bitmapped image can be drawn in the application's client area. The following code sample is used to draw the bitmap.

case WM_PAINT:

    BeginPaint(hwnd, &ps);

        if (fDisplayBitmap) {

            hdcMem = CreateCompatibleDC(ps.hdc);

            SelectObject(hdcMem, hbm);

            GetObject(hbm, sizeof(BITMAP), (LPSTR) &bm);

            BitBlt(ps.hdc, 0, 0, bm.bmWidth, bm.bmHeight,

                hdcMem, 0, 0, SRCCOPY);

            DeleteDC(hdcMem);

        }

    EndPaint(hwnd, &ps);

    break;


 Using a Print Dialog Box and Retrieving a Printer Device Context

The first step in printing involves setting up the printer and obtaining a printer DC. In the sample application, the File menu contains two options, Print and Print Setup. By selecting either option, the user can configure the printer. When the user selects the Print Setup option, the Print Setup dialog box is displayed and the user can select a printer, a page orientation, a paper size, and so on. When the user selects the Print option, the Print dialog box is displayed and the user can select a range of pages, a print quality, a number of copies, and so on. The user can also display the Print Setup dialog box by clicking the Setup push button.

The Print and Print Setup dialog boxes are both displayed by initializing the members of a PRINTDLG structure and calling the PrintDlg function. (For more information about displaying the Print Setup dialog box, see Common Dialog Box Library). In addition to retrieving user-specified data, PrintDlg can be used to obtain a printer DC by specifying the PD_RETURNDC value in the Flags member of the PRINTDLG structure. The following code sample shows how to intialize the members of the structure and to display the Print dialog box.

/* Initialize the PRINTDLG members. */

pd.lStructSize = sizeof(PRINTDLG);

pd.hDevMode = (HANDLE) NULL;

pd.hDevNames = (HANDLE) NULL;

pd.Flags = PD_RETURNDC;

pd.hwndOwner = hwnd;

pd.hDC = (HDC) NULL;

pd.nFromPage = 1;

pd.nToPage = 1;

pd.nMinPage = 0;

pd.nMaxPage = 0;

pd.nCopies = 1;

pd.hInstance = (HANDLE) NULL;

pd.lCustData = 0L;

pd.lpfnPrintHook = (LPPRINTHOOKPROC) NULL;

pd.lpfnSetupHook = (LPSETUPHOOKPROC) NULL;

pd.lpPrintTemplateName = (LPSTR) NULL;

pd.lpSetupTemplateName = (LPSTR)  NULL;

pd.hPrintTemplate = (HANDLE) NULL;

pd.hSetupTemplate = (HANDLE) NULL;

/* Display the PRINT dialog box. */

PrintDlg(&pd);


 Preparing to Print

The following code sample determines whether the selected printer is capable of printing bitmaps by calling the GetDeviceCaps function, supplying the RASTERCAPS value. By examining this function's return value, the application can determine whether it should print a document or inform the user that the device does not support raster output.

/*

 * Examine the raster capabilities of the device

 * identified by pd.hDC to verify that it supports

 * the BitBlt function.

 */

if (!(GetDeviceCaps(pd.hDC, RASTERCAPS)

    & RC_BITBLT)) {

    DeleteDC(pd.hDC);

    MessageBox(hwnd,

        "Printer cannot display bitmaps.",

        "Device Error",

        MB_OK);

    break;

}

After the sample application determines that the selected printer is capable of printing bitmaps, it follows these steps:

1.	Sets a Boolean flag that the application's abort procedure can examine to determine whether to allow printing to continue.

2.	Registers the application's AbortProc function, which is used to cancel a print job.

3.	Displays a modeless Cancel dialog box.

4.	Disables the application's window while the dialog box is displayed.

The steps are illustrated in the following code sample.

/*

 * Set the flag used by the AbortPrintJob

 * dialog procedure.

 */

 bPrint = TRUE;

/*

 * Register the application's AbortProc

 * function with GDI.

 */

 SetAbortProc(pd.hDC, AbortProc);

/* Display the modeless Cancel dialog box. */

 hdlgCancel = CreateDialog(hinst, (LPTSTR) "AbortDlg",

    hwnd, (DLGPROC) AbortPrintJob);

/* Disable the application's window. */

 EnableWindow(hwnd, FALSE);

Once the application registers AbortProc with Windows, GDI calls the function repeatedly during the printing process to determine whether to cancel a job. In the current version of the Win32 API, GDI calls this function approximately every two seconds until the entire job has been spooled.

If the user chooses to cancel the job, GDI notifies the spooler that it should delete the corresponding journal file from the print queue and reset the printer to its default state.


 Abort Procedure

Any application written for Windows that supports printing should provide an abort procedure and a modeless dialog box that allow a user to cancel a print job. The abort procedure for the sample application contains a message loop that retrieves messages for the modeless dialog box.

BOOL CALLBACK AbortProc(HDC hdc, int nCode)

{

    MSG msg;

    /*

     * Retrieve and remove messages from the thread's message

     * queue.

     */

    while (PeekMessage((LPMSG) &msg, (HWND) NULL,

            0, 0, PM_REMOVE)) {

        /* Process any messages for the Cancel dialog box. */

        if (!IsDialogMessage(hdlgCancel, (LPMSG) &msg)) {

            TranslateMessage((LPMSG) &msg);

            DispatchMessage((LPMSG) &msg);

         }

    }

    /*

     * Return the global bPrint flag (which is set to FALSE

     * if the user presses the Cancel button).

     */

     return bPrint;

}

For Win16-based applications, this procedure must be exported in the application's module-definition (.DEF) file.


 Cancel Dialog Box

The Cancel dialog box typically contains a single push button that allows the user to cancel a print job. The following template for the Cancel dialog box was taken from the sample application's resource (.RES) file.

AbortDlg DIALOG LOADONCALL MOVEABLE DISCARDABLE 33, 32, 160, 70

CAPTION "Sample Printing App"

STYLE WS_BORDER | WS_CAPTION | WS_DLGFRAME | WS_VISIBLE |

      WS_POPUP | WS_SYSMENU

BEGIN

    CONTROL "Now Printing: ", IDD_TEXT, "static",

        SS_CENTER | WS_CHILD, 0, 10, 160, 8

    CONTROL "", IDD_FILE, "static",

        SS_CENTER | WS_CHILD, 0, 25, 160, 8

    CONTROL "Cancel", IDD_CANCEL, "button",

        BS_DEFPUSHBUTTON | WS_TABSTOP | WS_CHILD,

        60, 45, 45, 15

END

The code sample that follows shows the dialog box procedure for the application.

LRESULT CALLBACK AbortPrintJob(

        HWND hwndDlg,     /* window handle of dialog box     */

        UINT message,     /* type of message                 */

        WPARAM wParam,    /* message-specific information    */

        LPARAM lParam)    /* message-specific information    */

{

    switch (message) {

        case WM_INITDIALOG:  /* message: initialize dialog box  */

            /* Initialize the static text control. */

            SetDlgItemText(hwndDlg, IDD_FILE, ofn.lpstrFile);

            return TRUE;

        case WM_COMMAND:     /* message: received a command */

            /* User pressed "Cancel" button--stop print job. */

            MessageBox(hwndDlg, "Incoming", "WM_COMMAND", MB_OK);

            bPrint = FALSE;

            return TRUE;

        default:

            return FALSE;     /* didn't process a message   */

    }

        UNREFERENCED_PARAMETER(lParam);

        UNREFERENCED_PARAMETER(wParam);

        UNREFERENCED_PARAMETER(message);

}


 Printing a Document

Once the application initializes the necessary variables, registers its AbortProc function, and displays its modeless Cancel dialog box, it can start the print job by calling the StartDoc function.

After the application begins a print job, it can define individual pages in the document by calling the StartPage and EndPage functions and embedding the appropriate calls to GDI drawing functions within this bracket. After the application has defined the last page, it can close the document and end the print job by calling the EndDoc function.

The following example shows the code required to print a string of text and a bitmapped image. The string of text, centered at the top of the page, identifies the path and filename for the file that contains the bitmapped image. The bitmapped image, centered vertically and horizontally on the page, is drawn so that the same proportions used to draw the image in the application's window are maintained.

                /*

                 * Initialize the members of a DOCINFO

                 * structure.

                 */

                 di.cbSize = sizeof(DOCINFO);

                 di.lpszDocName = "Bitmap Printing Test";

                 di.lpszOutput = (LPTSTR) NULL;

                 di.lpszDataType = (LPTSTR) NULL;

                 di.fwType = 0;

                /*

                 * Begin a print job by calling the StartDoc

                 * function.

                 */

                 nError = StartDoc(pd.hDC, &di);

                 if (nError == SP_ERROR) {

                     errhandler("StartDoc", hwnd);

                     goto Error;

                    }

                /*

                 * Inform the driver that the application is

                 * about to begin sending data.

                 */

                 nError = StartPage(pd.hDC);

                 if (nError <= 0) {

                     errhandler("StartPage", hwnd);

                     goto Error;

                    }

                /*

                 * Retrieve the number of pixels-per-logical-inch

                 * in the horizontal and vertical directions

                 * for the display upon which the bitmap

                 * was created.

                 */

                 fLogPelsX1 = (float) GetDeviceCaps(pd.hDC, LOGPIXELSX);

                 fLogPelsY1 = (float) GetDeviceCaps(pd.hDC, LOGPIXELSY);

                /*

                 * Retrieve the number of pixels-per-logical-inch

                 * in the horizontal and vertical directions

                 * for the printer upon which the bitmap

                 * will be printed.

                 */

                 fLogPelsX2 = (float) GetDeviceCaps(pd.hDC,

                     LOGPIXELSX);

                 fLogPelsY2 = (float) GetDeviceCaps(pd.hDC,

                     LOGPIXELSY);

                /*

                 * Determine the scaling factors required to

                 * print the bitmap and retain its original

                 * proportions.

                 */

                 if (fLogPelsX1 > fLogPelsX2)

                    fScaleX = (fLogPelsX1 / fLogPelsX2);

                 else

                    fScaleX = (fLogPelsX2 / fLogPelsX1);

                 if (fLogPelsY1 > fLogPelsY2)

                    fScaleY = (fLogPelsY1 / fLogPelsY2);

                 else

                    fScaleY = (fLogPelsY2 / fLogPelsY1);

                /*

                 * Compute the coordinate of the upper left

                 * corner of the centered bitmap.

                 */

                 cWidthPels = GetDeviceCaps(pd.hDC, HORZRES);

                 xLeft = ((cWidthPels / 2) -

                            ((int) (((float) bmih.biWidth)

                             * fScaleX)) / 2);

                 cHeightPels = GetDeviceCaps(pd.hDC, VERTRES);

                 yTop = ((cHeightPels / 2) -

                            ((int) (((float) bmih.biHeight)

                             * fScaleY)) / 2);

                /*

                 * Create a memory DC that is compatible with

                 * the printer and select the bitmap (which

                 * the user requested) into this DC.

                 */

                 hdcMem = CreateCompatibleDC(pd.hDC);

                 if (!SelectObject(hdcMem, hbm))

                    errhandler("SelectObject Failed", hwnd);

                /*

                 * Use the StretchBlt function to scale the

                 * bitmap and maintain its original proportions

                 * (that is, if the bitmap was square when it

                 * appeared in the application's client area,

                 * it should also appear square on the page).

                 */

                 if (!StretchBlt(pd.hDC, xLeft, yTop,

                         (int) ((float) bmih.biWidth * fScaleX),

                         (int) ((float) bmih.biHeight * fScaleY),

                         hdcMem, 0, 0,

                         bmih.biWidth, bmih.biHeight,

                         SRCCOPY))

                     errhandler("StretchBlt Failed", hwnd);

                /* Delete the memory DC. */

                 DeleteDC(hdcMem);

                /*

                 * Retrieve the width of the string that

                 * specifies the full path and filename for the

                 * file that contains the bitmap.

                 */

                 GetTextExtentPoint32(pd.hDC, ofn.lpstrFile,

                     ofn.nFileExtension + 3,

                     &szMetric);

                /*

                 * Compute the starting point for the

                 * text-output operation. The string will

                 * be centered horizontally and positioned

                 * three-lines down from the top of the page.

                 */

                 xLeft = ((cWidthPels / 2) - (szMetric.cx / 2));

                 yTop = (szMetric.cy * 3);

                /*

                 * Print the path and filename for the bitmap,

                 * centered at the top of the page.

                 */

                 TextOut(pd.hDC, xLeft, yTop, ofn.lpstrFile,

                     ofn.nFileExtension + 3);

                /*

                 * Determine whether the user has pressed

                 * the Cancel button in the AbortPrintJob

                 * dialog box; if the button has been pressed,

                 * call the AbortDoc function. Otherwise, inform

                 * the spooler that the page is complete.

                 */

                 nError = EndPage(pd.hDC);

                 if (nError <= 0) {

                    errhandler("EndPage", hwnd);

                    goto Error;

                 }

                /* Inform the driver that document has ended. */

                 nError = EndDoc(pd.hDC);

                 if (nError <= 0)

                    errhandler("EndDoc", hwnd);

Error:

                /* Enable the application's window. */

                EnableWindow(hwnd, TRUE);

                /* Remove the AbortPrintJob dialog box. */

                DestroyWindow(hdlgCancel);

                /* Delete the printer DC. */

                DeleteDC(pd.hDC);

Because the pixels on a screen typically have different dimensions than the dots on a printer, it is necessary to scale bitmapped images to obtain a WYSIWYG effect. This is done by obtaining horizontal and vertical scaling factors and then applying those factors to the width and height values passed to the StretchBlt function. In the sample application, the scaling factors were obtained by retrieving the horizontal and vertical logical-pixel count for the two devices. Once the scaling factors were obtained, they were used to adjust the bitmap width and height.

To center the bitmap on the page, the application first computed the width and height of the scaled bitmap. (The bitmap was scaled to maintain the original proportions of the image.) These values were divided by two and then subtracted from half of the width and height of the page. The result defines the coordinates of the upper left corner of the bitmap.

To center the text at the top of the page, the application called the GetTextExtentPoint32 function to retrieve the width and height of the string specifying the path names and filenames. Once these values were obtained, the application used the height to position the string three lines down the page and the width to position the string horizontally centered on the page.

The following illustration shows a representation of the page that appeared when the application printed the bitmapped image in the WINLOGO.BMP file. This illustration also depicts the variables used to position the text and to position and scale the bitmap.


 Printing and Print Spooler Reference

The following functions, structures, and messages are associated with printing and the print spooler.


 Printing and Print Spooler Functions

Following are the functions used to print.

AbortDoc
DeviceCapabilities
EndDoc
EndPage
Escape
ExtEscape
SetAbortProc
StartDoc
StartPage

Following are the functions used to access the print spooler.

AbortPrinter
AbortProc
AddForm
AddJob
AddMonitor
AddPort
AddPrinter
AddPrinterConnection
AddPrinterDriver
AddPrintProcessor
AddPrintProvidor
AdvancedDocumentProperties
ClosePrinter
ConfigurePort
ConnectToPrinterDlg
DeleteForm
DeleteMonitor
DeletePort
DeletePrinter
DeletePrinterConnection
DeletePrinterDriver
DeletePrintProcessor
DeletePrintProvidor
DocumentProperties
EndDocPrinter
EndPagePrinter
EnumForms
EnumJobs
EnumMonitors
EnumPorts
EnumPrinterDrivers
EnumPrinters
EnumPrintProcessorDataTypes
EnumPrintProcessors
FindClosePrinterChangeNotification
FindFirstPrinterChangeNotification
FindNextPrinterChangeNotification
FreePrinterNotifyInfo
GetForm
GetJob
GetPrinter
GetPrinterData
GetPrinterDriver
GetPrinterDriverDirectory
GetPrintProcessorDirectory
OpenPrinter
PrinterMessageBox
PrinterProperties
ReadPrinter
ResetPrinter
ScheduleJob
SetForm
SetJob
SetPrinter
SetPrinterData
StartDocPrinter
StartPagePrinter
WaitForPrinterChange
WritePrinter


 Printing and Print Spooler Structures

The following structures are used with the print spooler:

DATATYPES_INFO_1
PRINTER_NOTIFY_OPTIONS
PRINTER_NOTIFY_OPTIONS_TYPE
PRINTER_NOTIFY_INFO
PRINTER_NOTIFY_INFO_DATA


 Printing and Print Spooler Messages

Following is the message used with the print spooler.

WM_SPOOLERSTATUS


 Regions

In Microsoft® Windows®, a region is a rectangle, polygon, or ellipse (or a combination of two or more of these shapes) that can be filled, painted, inverted, framed, and used to perform hit testing (testing for the cursor location).


 About Regions

Following are three types of regions that have been filled and framed.


 Region Creation and Selection

An application creates a region by calling a function associated with a specific shape. The following table shows the function(s) associated with each of the standard shapes.

Shape	Function
Rectangular region	CreateRectRgn, CreateRectRgnIndirect
Rectangular region with rounded corners	CreateRoundRectRgn
Elliptical region	CreateEllipticRgn, CreateEllipticRgnIndirect
Polygonal region	CreatePolygonRgn, CreatePolyPolygonRgn
Each region creation function returns a handle that identifies the new region. An application can use this handle to select the region into a device context by calling the SelectObject function and supplying this handle as the second argument. After a region is selected into a device context, the application can perform various operations on it.


 Region Operations

Applications can combine regions, compare them, paint or invert their interiors, draw a frame around them, retrieve their dimensions, and test whether the cursor lies within their boundaries.


 Combining

An application combines two regions by calling the CombineRgn function. Using this function, an application can combine the intersecting parts of two regions, all but the intersecting parts of two regions, the two original regions in their entirety, and so on. Following are five values that define the region combinations.

Value	Meaning
RGN_AND	The intersecting parts of two original regions define a new region.
RGN_COPY	A copy of the first (of the two original regions) defines a new region.
RGN_DIFF	The part of the first region that does not intersect the second defines a new region.
RGN_OR	The two original regions define a new region.
RGN_XOR	Those parts of the two original regions that do not overlap define a new region.
The following illustration shows the five possible combinations of a square and a circular region resulting from a call to CombineRgn.


 Comparing

An application compares two regions to determine whether or not they are identical by calling the EqualRgn function. EqualRgn considers two regions identical if they are equal in size and shape.


 Filling

An application fills the interior of a region by calling the FillRgn function and supplying a handle that identifies a specific brush. When an application calls FillRgn, Windows fills the region with the brush by using the current fill mode for the specified device context. There are two fill modes: alternate and winding. The application can set the fill mode for a device context by calling the SetPolyFillMode function. The application can retrieve the current fill mode for a device context by calling the GetPolyFillMode function.

The following illustration shows two identical regions: one filled using alternate mode and the other filled using winding mode.

Alternate Mode

To determine which pixels Windows highlights when alternate mode is specified, perform the following test:

1.	Select a pixel within the region's interior.

2.	Draw an imaginary ray, in the positive x-direction, from that pixel towards infinity.

3.	Each time the ray intersects a boundary line, increment a count value.

Windows highlights the pixel if the count value is an odd number.

Winding Mode

To determine which pixels Windows highlights when winding mode is specified, perform the following test:

1.	Determine the direction in which each boundary line is drawn.

2.	Select a pixel within the region's interior.

3.	Draw an imaginary ray, in the positive x-direction, from the pixel toward infinity.

4.	Each time the ray intersects a boundary line with a positive y-component, increment a count value. Each time the ray intersects a boundary line with a negative y-component, decrement the count value.

Windows highlights the pixel if the count value is nonzero.


 Painting

An application fills the interior of a region by using the brush currently selected into a device context by the PaintRgn function. This function uses the current polygon fill modes (alternate and winding).


 Inverting

An application inverts the colors that appear within a region by calling the InvertRgn function. On monochrome displays, InvertRgn makes white pixels black and black pixels white. On color screens, this inversion is dependent on the type of technology used to generate the colors for the screen.


 Framing

An application draws a border around a region by calling the FrameRgn function and specifying the border width and brush pattern that Windows uses when drawing the frame.


 Retrieving a Bounding Rectangle

An application retrieves the dimensions of a region's bounding rectangle by calling the GetRgnBox function. If the region is rectangular, GetRgnBox returns the dimensions of the region. If the region is elliptical, the function returns the dimensions of the smallest rectangle that can be drawn around the ellipse. The long sides of the rectangle are the same length as the ellipse's major axis, and the short sides of the rectangle are the same length as the ellipse's minor axis. If the region is polygonal, GetRgnBox returns the dimensions of the smallest rectangle that can be drawn around the entire polygon.


 Moving

An application moves a region by calling the OffsetRgn function. The given offsets along the x-axis and y-axis determine the number of logical units to move left or right and up or down.


 Hit Testing

An application performs hit testing on regions to determine the coordinates of the current cursor position. Then it passes these coordinates — as well as a handle identifying the region — to the PtInRegion function. The cursor coordinates can be retrieved by processing the various mouse messages, such as WM_LBUTTONDOWN, WM_LBUTTONUP, WM_RBUTTONDOWN, and WM_RBUTTONUP. The return value for PtInRegion indicates whether the cursor position is within the given region.


 Using Regions

•	Using regions to clip output

•	Using regions to perform hit testing


 Using Regions to Clip Output

This section contains a single example that demonstrates how you can use regions to enable the user to define how a part of client area output can appear. Regions used for this purpose are called clipping regions.

The example for this section is taken from a Windows-based application that enables a user to capture the entire desktop as a bitmap and then isolate and save a part of this image as a .BMP file.

By selecting the Define Clip Region option from the application's menu, the user is able to select a clipping region by clicking the left mouse button and dragging the mouse. As the user drags the mouse, the application draws a rectangle that corresponds to the new clipping region.

By selecting the Clip option, the user is able to redraw the isolated part of the image within the boundaries of the specified rectangle.


 Defining the Clipping Region

When the user selects the Define Clip Region option, Windows issues a WM_COMMAND message. The wParam parameter of this message contains an application-defined constant, IDM_DEFINE, that indicates that the user selected this option from the menu. The application processes this input by setting a Boolean flag, fDefineRegion, as shown in the following code sample.

case WM_COMMAND:

    switch (wParam) {

case IDM_DEFINE:

    fDefineRegion = TRUE;

break;

After selecting the Define Clipping Region option, the user can begin drawing the rectangle by clicking and dragging the mouse while the cursor is in the application's client area.

When the user presses the left button, Windows issues a WM_LBUTTONDOWN message. The lParam parameter of this message contains the cursor coordinates, which correspond to the upper left corner of a rectangle used to define the clipping region. The application processes the WM_LBUTTONDOWN message, as follows.

/* These variables are required for clipping. */

static POINT ptUpperLeft;

static POINT ptLowerRight;

static POINT aptRect[5];

static POINT ptTmp;

static POINTS ptsTmp;

static BOOL fDefineRegion;

static BOOL fRegionExists;

static HRGN hrgn;

static RECT rctTmp;

int i;

switch (message) {

case WM_LBUTTONDOWN:

    if (fDefineRegion) {

        /* Retrieve the new upper left corner. */

        ptsTmp = MAKEPOINTS(lParam);

        ptUpperLeft.x = (LONG) ptsTmp.x;

        ptUpperLeft.y = (LONG) ptsTmp.y;

    }

    if (fRegionExists) {

        /* Erase the previous rectangle. */

        hdc = GetDC(hwnd);

        SetROP2(hdc, R2_NOTXORPEN);

        if (!Polyline(hdc, (CONST POINT *) aptRect, 5))

            errhandler("Polyline Failed", hwnd);

        ReleaseDC(hwnd, hdc);

        /* Clear the rectangle coordinates. */

        for (i = 0; i < 4; i++) {

               aptRect[i].x = 0;

               aptRect[i].y = 0;

        }

        /* Clear the temporary point structure. */

        ptTmp.x = 0;

        ptTmp.y = 0;

        /* Clear the lower right coordinates. */

        ptLowerRight.x = 0;

        ptLowerRight.y = 0;

        /* Reset the flag. */

        fRegionExists = FALSE;

        fDefineRegion = TRUE;

        /* Retrieve the new upper left corner. */

        ptsTmp = MAKEPOINTS(lParam);

        ptUpperLeft.x = (LONG) ptsTmp.x;

        ptUpperLeft.y = (LONG) ptsTmp.y;

    }

break;

As the user drags the mouse, Windows issues WM_MOUSEMOVE messages and stores the new cursor coordinates in the lParam parameter. Each time the application receives a new WM_MOUSEMOVE message, it erases the previous rectangle (if one exists) and draws the new rectangle by calling the Polyline function, passing it the coordinates of the four corners of the rectangle. The application performs the following tasks.

/* These variables are required for clipping. */

static POINT ptUpperLeft;

static POINT ptLowerRight;

static POINT aptRect[5];

static POINT ptTmp;

static POINTS ptsTmp;

static BOOL fDefineRegion;

static BOOL fRegionExists;

static HRGN hrgn;

static RECT rctTmp;

int i;

switch (message) {

case WM_MOUSEMOVE:

    if (wParam & MK_LBUTTON && fDefineRegion) {

        /* Get a window DC. */

        hdc = GetDC(hwnd);

        if (!SetROP2(hdc, R2_NOTXORPEN))

            errhandler("SetROP2 Failed", hwnd);

        /*

         * If previous mouse movement occurred, store the original

         * lower right corner coordinates in a temporary structure.

         */

        if (ptLowerRight.x) {

            ptTmp.x = ptLowerRight.x;

            ptTmp.y = ptLowerRight.y;

        }

        /*

         * Get the new coordinates of the clipping region's lower

         * right corner.

         */

        ptsTmp = MAKEPOINTS(lParam);

        ptLowerRight.x = (LONG) ptsTmp.x;

        ptLowerRight.y = (LONG) ptsTmp.y;

        /*

         * If previous mouse movement occurred, erase the original

         * rectangle.

         */

        if (ptTmp.x) {

            aptRect[0].x = ptUpperLeft.x;

            aptRect[0].y = ptUpperLeft.y;

            aptRect[1].x = ptTmp.x;

            aptRect[1].y = ptUpperLeft.y;

            aptRect[2].x = ptTmp.x;

            aptRect[2].y = ptTmp.y;

            aptRect[3].x = ptUpperLeft.x;

            aptRect[3].y = ptTmp.y;

            aptRect[4].x = aptRect[0].x;

            aptRect[4].y = aptRect[0].y;

            if (!Polyline(hdc, (CONST POINT *) aptRect, 5))

                errhandler("Polyline Failed", hwnd);

        }

        aptRect[0].x = ptUpperLeft.x;

        aptRect[0].y = ptUpperLeft.y;

        aptRect[1].x = ptLowerRight.x;

        aptRect[1].y = ptUpperLeft.y;

        aptRect[2].x = ptLowerRight.x;

        aptRect[2].y = ptLowerRight.y;

        aptRect[3].x = ptUpperLeft.x;

        aptRect[3].y = ptLowerRight.y;

        aptRect[4].x = aptRect[0].x;

        aptRect[4].y = aptRect[0].y;

        if (!Polyline(hdc, (CONST POINT *) aptRect, 5))

             errhandler("Polyline Failed", hwnd);

        ReleaseDC(hwnd, hdc);

    }

    break;


 Clipping Output

After the user chooses the Clip option from the menu, the application uses the coordinates of the rectangle the user created to define a clipping region. After defining the clipping region and selecting it into the application's device context, the application redraws the bitmapped image. The application performs these tasks, as follows.

/* These variables are required for clipping. */

static POINT ptUpperLeft;

static POINT ptLowerRight;

static POINT aptRect[5];

static POINT ptTmp;

static POINTS ptsTmp;

static BOOL fDefineRegion;

static BOOL fRegionExists;

static HRGN hrgn;

static RECT rctTmp;

int i;

case WM_COMMAND:

    switch (wParam) {

case IDM_CLIP:

    hdc = GetDC(hwnd);

    /*

     * Retrieve the application's client rectangle and paint

     * with the default (white) brush.

     */

    GetClientRect(hwnd, &rctTmp);

    FillRect(hdc, &rctTmp, GetStockObject(WHITE_BRUSH));

    /* Use the rect coordinates to define a clipping region. */

    hrgn = CreateRectRgn(aptRect[0].x, aptRect[0].y,

        aptRect[2].x, aptRect[2].y);

    SelectClipRgn(hdc, hrgn);

    /* Transfer (draw) the bitmap into the clipped rectangle. */

    BitBlt(hdc,

       0, 0,

       bmp.bmWidth, bmp.bmHeight,

       hdcCompatible,

       0, 0,

       SRCCOPY);

    ReleaseDC(hwnd, hdc);

break;


 Using Regions to Perform Hit Testing

The example in Brushes uses regions to simulate a "zoomed" view of an 8- by 8-pixel monochrome bitmap. By clicking on the pixels in this bitmap, the user creates a custom brush suitable for drawing operations. The example shows how to use the PtInRegion function to perform hit testing and the InvertRgn function to invert the colors in a region.


 Region Functions

Following are the functions used with regions.

CombineRgn
CreateEllipticRgn
CreateEllipticRgnIndirect
CreatePolygonRgn
CreatePolyPolygonRgn
CreateRectRgn
CreateRectRgnIndirect
CreateRoundRectRgn
EqualRgn
ExtCreateRegion
FillRgn
FrameRgn
GetPolyFillMode
GetRegionData
GetRgnBox
InvertRgn
OffsetRgn
PaintRgn
PtInRegion
RectInRegion
SetPolyFillMode


 Accessibility

The Microsoft® Win32® API provides a set of accessibility features that make it easier for persons with disabilities to use computers. This overview describes the provided accessibility features and the Win32 functions and structures for controlling these features.


 About Accessibility

There are two categories of accessibility features:

•	Accessibility parameters. These are system parameters that can be set by the user. Applications can check the state of an accessibility parameter to determine whether the user wants special behavior that can be provided in an application-specific manner. For example, the ShowSounds parameter indicates that an application that typically uses sound to convey important information should also provide the information visually.

•	Built-in accessibility features. These features are built into the system or provided as an extension to the system. They affect how the user provides keyboard and mouse input to the computer. When enabled, their functionality is available regardless of which applications are running. An example is a keyboard filter that makes it easier for users with movement impairments to type key combinations such as CTRL+ALT+DEL.


 Accessibility Parameters

The system maintains a set of accessibility parameters that indicate whether the user has special needs or preferences. The user controls the state of these parameters, typically using a Control Panel application. Control Panel applications or other programs that allow the user to customize the Windows environment can use the SystemParametersInfo function to set the accessibility parameters.

Applications should use the GetSystemMetrics function to determine the state of the accessibility parameters. When an accessibility parameter is set to TRUE, the application should modify its user interface, if necessary, to accomodate the user's preferences.

Win32 supports the following accessibility parameter:

Parameter	Description
ShowSounds	Indicates that an application that typically uses sound to convey important information should provide the information visually.


 Built-in Accessibility Features

The built-in accessibility features are extensions to the operating system. These features affect the behavior of the system regardless of which applications are running.

Win32 supports the following built-in accessibility features:

Feature	Description
AccessTimeout	Enables a user to specify a timeout interval after which system-wide accessibility features are automatically disabled. The AccessTimeout feature is intended for computers that are shared by several users with different preferences. Each individual can use hot keys or the Control Panel to enable preferred features. After a user leaves, the features he or she enabled will be automatically disabled by the timeout. The accessibility features affected by the timeout are FilterKeys, MouseKeys, StickyKeys, and ToggleKeys. The ACCESSTIMEOUT structure defines the parameters for this feature.
FilterKeys	Enables control of keyboard properties, such as the amount of time before a keystroke is accepted as input and the amount of time before a keystroke begins to repeat. The FilterKeys feature also provides sound feedback when a key is pressed and when it is accepted as input. The FILTERKEYS structure defines the parameters for this feature.
MouseKeys	Enables the user to control the mouse pointer using the numeric keypad. The MOUSEKEYS structure defines the parameters for this feature.
SoundSentry	Displays a visual signal when a sound is generated by a Windows-based application or an MS-DOS application running in a window. The SOUNDSENTRY structure defines the parameters for this feature.
StickyKeys	Enables the user to type key combinations, such as CTRL+ALT+DEL, in sequence rather than at the same time. The STICKYKEYS structure defines the parameters for this feature.
ToggleKeys	Provides sound feedback when the user turns on or off the CAPS LOCK, NUM LOCK, or SCROLL LOCK keys. The TOGGLEKEYS structure defines the parameters for this feature.
The SystemParametersInfo function provides the programming interface to the built-in accessibility features. This function is useful in Control Panel applications or other programs that allow the user to customize the Windows environment. The SystemParametersInfo function can perform the following tasks:

•	Query the system to determine the availability and current state of a specified built-in accessibility feature

•	Enable a feature and specify parameters that control its behavior

•	Disable a feature

•	Enable a hot key that allows the user to enable or disable a feature

For each of the built-in features, Win32 defines a structure that applications use with SystemParametersInfo to query or set the parameters of the feature.

An application can use SystemParametersInfo to enable or disable a feature directly. For some of the features, SystemParametersInfo can enable a hot key or key combination so the user can toggle the state of a feature. There are no hot keys for the SoundSentry feature. The following accessibility features have hot keys:

Feature	Description
FilterKeys	Hold down the LEFT SHIFT key for eight seconds to toggle the FilterKeys feature on or off. Holding down the LEFT SHIFT key for 12 seconds enables FilterKeys using the most conservative values for FILTERKEYS.iBounceMSec. Holding down the LEFT SHIFT key for 16 seconds enables FilterKeys using the most conservative values for FILTERKEYS.iWaitMSec.
MouseKeys	LEFT ALT+LEFT SHIFT+NUM LOCK
StickyKeys	Press the SHIFT key 5 times
ToggleKeys	Hold down the NUM LOCK key for 5 seconds


 Using Accessibility

•	Checking the state of an accessibility parameter.

•	Enabling a built-in accessibility feature.


 Checking the State of an Accessibility Parameter

The following code fragment uses the GetSystemMetrics function to check the ShowSounds parameter. If GetSystemMetrics returns TRUE, the application should present all important information in visual form.

BOOL fShowSounds;

fShowSounds = GetSystemMetrics(SM_SHOWSOUNDS);


 Enabling a Built-in Accessibility Feature

The following code fragment uses the SystemParametersInfo function to enable the FilterKeys feature:

FILTERKEYS fk;

BOOL bSuccess;

// fill in members of the FILTERKEYS structure

fk.cbSize = sizeof(FILTERKEYS);

fk.dwFlags = (FKF_FILTERKEYSON | FKF_HOTKEYACTIVE |

                       FKF_AVAILABLE | FKF_HOTKEYSOUND | FKF_CLICKON);

fk.iWaitMSec = 1000;

fk.iDelayMSec = 1000;

fk.iRepeatMSec = 500;

fk.iBounceMSec = 0;

// call SystemParametersInfo with SPI_SETFILTERKEYS code

bSuccess = SystemParametersInfo(SPI_SETFILTERKEYS, 0, (LPVOID) &fk, 0);


 Accessibility Reference

The following structures and messages are associated with accessibility features.


 Accessibility Functions

Use the following functions to implement accessibility features:

GetSystemMetrics
SystemParametersInfo


 Accessibility Structures

Use the following structures to implement accessibility features:

ACCESSTIMEOUT
FILTERKEYS
HIGHCONTRAST
MOUSEKEYS
SERIALKEYS
SOUNDSENTRY
STICKYKEYS
TOGGLEKEYS


 Atoms

In Microsoft® Windows®, an atom table is a system-defined table that stores strings and corresponding identifiers. An application places a string in an atom table and receives a 16-bit integer, called an atom, that can be used to access the string. A string that has been placed in an atom table is called an atom name.


 About Atom Tables

Dynamic data exchange (DDE) applications use an atom table to share item-name and topic-name strings with other applications. Rather than passing actual strings, a DDE application passes atoms to its partner application. The partner uses the atoms to obtain the strings from the atom table.


 Global Atom Table

The Windows global atom table, which can contain up to 37 entries, is available to all applications. When an application places a string in the global atom table, the system generates an atom that is unique throughout the system. Any application that has the atom can obtain the string it identifies by querying the global atom table.

An application that defines a private clipboard-data format or DDE-data format for sharing data with other applications should place the format name in the global atom table. This technique prevents conflicts with the names of formats defined by the system or by other applications, and makes the identifiers (atoms) for the messages or formats available to the other applications.


 Local Atom Tables

An application can use a local atom table to efficiently manage a large number of strings used only within the application. These strings, and the associated atoms, are available only to the application that created the table.

An application requiring the same string in a number of structures can reduce memory usage by using a local atom table. Rather than copying the string into each structure, the application can place the string in the atom table and include the resulting atom in the structures. In this way, a string appears only once in memory but can be used many times in the application.

Applications can also use local atom tables to save time when searching for a particular string. To perform a search, an application need only place the search string in the atom table and compare the resulting atom with the atoms in the relevant structures. Comparing atoms is typically faster than comparing strings.

By default, a local atom table can contain up to 37 entries. However, the size of a local atom table, unlike the size of a global atom table, can be changed. An application uses the InitAtomTable function to accomplish this task. If the application calls InitAtomTable, however, it must do so before calling any other atom-management functions.


 Atom Types

Applications can use two types of atoms: string and integer. The following sections describe these types.


 String Atoms

Applications pass null-terminated strings to atom tables and receive string atoms (16-bit integers) in return. String atoms have the following properties:

•	The values of string atoms are in the range 0xC000 through 0xFFFF.

•	Case is not significant in searches for an atom name in an atom table. Also, the entire string must match in a search operation; no substring matching is performed.

•	The string associated with a string atom can be no more than 255 bytes in size. This limitation applies to all atom functions.

•	A reference count is associated with each atom name. The count is incremented each time the atom name is added to the table and decremented each time the atom name is deleted from it. This prevents different users of the same string atom from destroying each other's atom names. When the reference count for an atom name equals zero, the system removes the atom and the atom name from the table.


 Integer Atoms

Integer atoms differ from string atoms in the following ways:

•	The values of integer atoms are in the range 0x0001 through 0xBFFF. The values of integer atoms and string atoms do not overlap, so both types of atoms can be used in the same block of code.

•	The string representation of an integer atom is #dddd, where the values represented by dddd are decimal digits. Leading zeros are ignored.

•	There is no reference count or storage overhead associated with an integer atom.

Several Windows functions accept either string or integer atoms as parameters. When passing an integer atom to these functions, an application must use the MAKEINTATOM macro to create the atom.


 Atom Creation and Usage Count

An application creates a local atom by calling the AddAtom function; it creates a global atom by calling the GlobalAddAtom function. Both functions require a pointer to a string. The system searches the appropriate atom table for the string and returns the corresponding atom to the application. In the case of a string atom, if the string already resides in the atom table, the system increments the reference count for the string during this process.

Repeated calls to add the same atom name return the same atom. If the atom name does not exist in the table when AddAtom is called, the atom name is added to the table and a new atom is returned. If it is a string atom, its reference count is also set to one.

An application should call the DeleteAtom function when it no longer needs to use a local atom; it should call the GlobalDeleteAtom function when it no longer needs a global atom. In the case of a string atom, either of these functions reduces the reference count of the corresponding atom by one. When the reference count reaches zero, the system deletes the atom name from the table.

The atom name of a string atom remains in the global atom table as long as its reference count is greater than zero, even after the application that placed it in the table terminates. A local atom table is destroyed when the associated application terminates, regardless of the reference counts of the atoms in the table.


 Atom-Table Queries

An application can determine whether a particular string is already in an atom table by using the FindAtom or GlobalFindAtom function. These functions search an atom table for the specified string and, if the string is there, return the corresponding atom.

An application can use the GetAtomName or GlobalGetAtomName function to retrieve an atom-name string from an atom table, provided the application has the atom corresponding to the string sought. Both functions copy the atom-name string of the specified atom to a buffer and return the length of the string that was copied. GetAtomName retrieves an atom-name string from a local atom table, and GlobalGetAtomName retrieves an atom-name string from the global atom table.


 Atom String Formats

The AddAtom, GlobalAddAtom, FindAtom, and GlobalFindAtom functions take a pointer to a null-terminated string. An application can specify this pointer in one of the following ways.

Format	Description
#dddd	An integer specified as a decimal string. Used to create or find an integer atom.
string atom name	A string atom name. Used to add a string atom name to an atom table and receive an atom in return.


 Using Atoms

The most typical use for atoms is in DDE applications. In the DDE protocol, applications use global atoms to identify the applications exchanging data, the nature of the data being exchanged, and the actual data items being exchanged. For more information about DDE and for examples that show how to use atoms, see Dynamic Data Exchange.


 Atom Functions

Following are the functions associated with atoms.

AddAtom
DeleteAtom
FindAtom
GetAtomName
GlobalAddAtom
GlobalDeleteAtom
GlobalFindAtom
GlobalGetAtomName
InitAtomTable

Obsolete or Deleted Functions

GetAtomHandle


 Communications

A communications resource is a physical or logical device that provides a single bidirectional, asynchronous data stream. Serial ports, parallel ports, fax machines, and modems are examples of communications resources. For each communications resource, there is a service provider, consisting of a library or driver, that enables applications to access the resource.


 About Communications

The file input and output (I/O) functions (CreateFile, CloseHandle, ReadFile, ReadFileEx, WriteFile, and WriteFileEx) provide the basic interface for opening and closing a communications resource handle and for performing read and write operations. The Microsoft® Win32® application programming interface (API) also includes a set of communications functions that provide access to communications resources. This overview describes the use of file I/O and communications functions, which enable applications to perform the following tasks:

•	Open a handle to a specified communications resource.

•	Set and query the configuration of a serial communications resource.

•	Read from or write to a serial communications resource.

•	Monitor a specified set of events that might occur for a given serial communications resource.

•	Send a control command to the device driver associated with a specified communications resource, causing the driver to execute an extended function.


 Communications Resource Handles

A process uses the CreateFile function to open a handle to a communications resource. For example, specifying COM1 opens a handle to a serial port, and LPT1 opens a handle to a parallel port. If the specified resource is currently being used by another process, CreateFile fails. Any thread of the process can use the handle returned by CreateFile to identify the resource in any of the functions that access the resource.

When using CreateFile to open a handle directly to a device, an application must use the special characters " \\ .\" to identify the device. For example, to open a handle to drive A, specify " \\ .\a:" for the lpszName parameter of CreateFile. The calling process can use the handle in the DeviceIoControl function to send control codes to the device.

When the process calls CreateFile to open a communications resource, it specifies the following attributes:

•	What type of read-write access exists for the specified resource.

•	Whether the handle can be inherited by child processes.

•	Whether the handle can be used in overlapped (asynchronous) I/O operations. (For a description of overlapped operations, see Synchronization.)

When the process uses CreateFile to open a communications resource, it must specify certain values for the following parameters:

•	The fdwShareMode parameter must be zero, opening the resource for exclusive access.

•	The fdwCreate parameter must specify the OPEN_EXISTING flag.

•	The hTemplateFile parameter must be NULL.


 Modification of Communications Resource Settings

When the CreateFile function opens a handle to a serial communications resource, the system initializes and configures the resource according to the values set up the last time the resource was opened. Preserving the previous settings enables the user to retain the settings specified through an MS-DOS® mode command when the device is reopened. The values inherited from the previous open operation include the configuration settings of the device control block (a DCB structure) and the time-out values used in I/O operations. If the device has never been opened, it is configured with the system defaults.

To determine the initial configuration of a serial communications resource, a process calls the GetCommState function, which fills in a serial port DCB structure with the current configuration settings. To modify this configuration, a process specifies a DCB structure in a call to the SetCommState function.

Members of the DCB structure specify the configuration settings such as the baud rate, the number of data bits per byte, and the number of stop bits per byte. Other DCB members specify special characters and enable parity checking and flow control. When a process needs to modify only a few of these configuration settings, it should first call GetCommState to fill in a DCB structure with the current configuration. Then the process can adjust the important values in the DCB structure and reconfigure the device by calling SetCommState and specifying the modified DCB structure. This procedure ensures that the unmodified members of the DCB structure contain appropriate values. For example, a common error is to configure a device with a DCB structure in which the structure's XonChar member is equal to the XoffChar member. Some members of the DCB structure are different from those in previous versions of Microsoft Windows®. In particular, the flags for controlling RTS (request-to-send) and DTR (data-terminal-ready) flow control have changed.

The BuildCommDCB function provides another way to modify a DCB structure. BuildCommDCB uses a string with the same form as the command-line arguments of the mode command to specify the baud rate, parity scheme, number of stop bits, and number of data bits. The remaining members of DCB are not changed by this function, except that the appropriate members are set to disable XON/XOFF and hardware flow control. BuildCommDCB only modifies a DCB structure; it does not reconfigure the device.

A process can reconfigure a communications resource by using the GetCommProperties function to get information from a device driver about the configuration settings that it supports. The process can use this information to avoid specifying a configuration that is not supported.

The SetCommState function reconfigures the communications resource, but it does not affect the internal output and input buffers of the specified driver. The buffers are not flushed, and pending read and write operations are not terminated prematurely.

A process reinitializes a communications resource by using the SetupComm function, which performs the following tasks:

•	Terminates pending read and write operations, even if they have not been completed.

•	Discards unread characters and frees the internal output and input buffers of the driver associated with the specified resource.

•	Reallocates the internal output and input buffers.

A process is not required to call SetupComm. If it does not, the resource's driver initializes the device with the default settings the first time that the communications resource handle is used.


 Communications Resource Configuration

The COMMCONFIG structure defines the configuration of a communications resource, serial or otherwise. The format of the structure varies depending on the type of communications resource (the provider subtype). The first few structure members are common to all communications resources; additional members are defined for specific provider subtypes. Specific service providers may extend the COMMCONFIG structure as well.

An application can get and set the configuration of a communications resource by using the GetCommConfig and SetCommConfig functions. When opened, a communications resource is initialized using the default configuration for its provider subtype. To get and set the default configuration for a provider subtype, use the GetDefaultCommConfig and SetDefaultCommConfig functions.

To prompt the user for configuration information, use the CommConfigDialog function. This function displays a dialog box defined by the service provider and fills in a COMMCONFIG structure based on user input.


 Modem Configuration

Modem configuration functions enable you to configure a modem before making a connection. An application can set modem options and determine the features of a modem without using commands specific to any modem device. Following are the general features an application may set before making a call:

•	Primary mode of operation (synchronous, asynchronous, and whether error control is enabled).

•	V.42 error control (defined by CCITT recommendation V.42), including specific parameters. CCITT stands for the International Telegraph and Telephone Consultative Committee.

•	V.42bis (defined by CCITT recommendation V.42bis) and MNP5 data compression.

•	Time-out options, including call setup, inactivity, and buffered data delivery.

Before setting a modem's configuration, an application should determine the capabilities of the modem device by using the GetCommProperties function. This function fills in a COMMPROP structure. This structure contains both a general portion, which applies to all communications devices, and a portion that is specific to each provider subtype. For modem devices, the provider-specific portion of the COMMPROP structure is a MODEMDEVCAPS structure.

An application can get and set the current configuration of a modem by using the GetCommConfig and SetCommConfig functions, both of which use a COMMCONFIG structure. This structure contains both a general portion, which applies to all communications devices, and a portion that is specific to each provider subtype. For modem devices, the provider-specific portion of the COMMCONFIG structure is a MODEMSETTINGS structure.

After configuring a modem, an application can use the telephony application programming interface (TAPI) to actually establish a connection.

The modem configuration functions do not provide for long-term management and maintenance of a modem. Modem service providers should supply modem configuration dialog boxes for this purpose.


 Read and Write Operations

The Win32 API supports both synchronous and asynchronous (overlapped) file I/O operations on serial communications resources. Overlapped operations enable the calling thread to perform other tasks while the operation executes in the background. A thread uses the ReadFile or ReadFileEx function to read from a communications resource, and the WriteFile or WriteFileEx function to write to a communications resource. ReadFile and WriteFile can be performed synchronously or asynchronously. ReadFileEx and WriteFileEx can only be performed asynchronously.

The behavior of these read and write functions is affected by whether the function is executed as an overlapped operation, whether the time-out parameters are associated with the handle, and whether flow control parameters are associated with the handle.

A thread can also write to a communications resource by using the TransmitCommChar function, which transmits a specified character ahead of any pending data in the output buffer. This function is useful for transmitting a high priority signal character to the receiving system. Transmission of the high priority character is still subject to flow control and write time-outs, and the operation is performed synchronously.

A thread can use the PurgeComm function to discard all characters in a device's output or input buffer. PurgeComm can also terminate pending read or write operations, even if the operations have not been completed. If a thread uses PurgeComm to flush an output buffer, the deleted characters are not transmitted. To empty the output buffer while ensuring that the contents are transmitted, a thread can call the FlushFileBuffers function (a synchronous operation). Note, however, that FlushFileBuffers is subject to flow control but not to write time-outs, and it will not return until all pending write operations have been transmitted.


 Overlapped Operations

Overlapped operations enable a thread to execute a time-consuming I/O operation in the background, leaving the thread free to perform other tasks. To enable overlapped I/O operations on a communications resource, the thread must specify the FILE_FLAG_OVERLAPPED flag in the CreateFile function when the handle is opened. To execute the ReadFile or WriteFile function as an overlapped operation, the calling thread must specify a pointer to an OVERLAPPED structure.The OVERLAPPED structure must contain a handle to a manual-reset (not an auto-reset) event object. The system sets the state of the event object to not-signaled when a call to the I/O function returns before the operation has been completed. The system sets the state of the event object to signaled when the operation has been completed. The thread uses a wait function to check the current state of the event object or to wait for its state to be signaled.

The ReadFileEx and WriteFileEx functions can be performed only as overlapped operations. The calling thread specifies a pointer to the FileIOCompletionRoutine function, which is executed when the overlapped operation is completed. The completion routine is executed only if the calling thread performs an alertable operation.

For more information about event objects, wait functions, alertable waits, and completion routines, see Synchronization.


 Time-Outs

A handle to a communications resource has an associated set of time-out parameters that affect the behavior of read and write operations. Time-outs can cause a ReadFile, ReadFileEx, WriteFile, or WriteFileEx operation to conclude when a time-out interval elapses, even though the specified number of characters have not been read or written. It is not treated as an error when a time-out occurs during a read or write operation (that is, the read or write function's return value indicates success). The count of bytes actually read or written is reported by ReadFile or WriteFile (or by the GetOverlappedResult or FileIOCompletionRoutine function, if the I/O was performed as an overlapped operation).

When an application opens a communications resource, the operating system sets the resource's time-out values to the values in effect when the resource was last used. If the communications resource has never been opened, the operating system sets the time-out values to some default value. In either case, an application should always determine the current time-out values after opening the resource, and then explicitly set them to meet its requirements. To determine the current time-out values of a communications resource, use the GetCommTimeouts function. To change the time-out values, use the SetCommTimeouts function.

Two types of time-outs are enabled by the time-out parameters. An interval time-out occurs when the time between the receipt of any two characters exceeds a specified number of milliseconds. Timing starts when the first character is received and is restarted when each new character is received. A total time-out occurs when the total amount of time consumed by a read operation exceeds a calculated number of milliseconds. Timing starts immediately when the I/O operation begins. Write operations support only total time-outs. Read operations support both interval and total time-outs, which can be used separately or combined.

The time, in milliseconds, of the total time-out period for a read or write operation is calculated by using the multiplier and constant values from the COMMTIMEOUTS structure specified in the GetCommTimeouts or SetCommTimeouts function. The following formula is used:

Timeout = (MULTIPLIER * number_of_bytes) + CONSTANT

Using both a multiplier and a constant enables the total time-out period to vary, depending on the amount of data being requested. An application can use only the constant by setting the multiplier to zero, or use only the multiplier by setting the constant to zero. If both the constant and multiplier are zero, total time-out is not used.

If all read time-out parameters are zero, read time-outs are not used, and a read operation is not complete until the requested number of bytes have been read or an error occurs. Similarly, if all write time-out parameters are zero, a write operation is not completed until the requested number of bytes have been written or an error occurs.

If the read interval time-out parameter is the MAXDWORD value and both read total time-out parameters are zero, a read operation is completed immediately after reading whatever characters are available in the input buffer, even if it is empty. This is the same as the ReadComm function in previous versions of Windows.

Interval timing forces a read operation to return when there is a lull in reception. A process using interval time-outs can set a fairly short interval parameter, so it can respond quickly to small, isolated bursts of one or a few characters, yet it can still collect large buffers of characters with a single call when data is received in a steady stream.

Time-outs for a write operation can be useful when transmission is blocked by some kind of flow control or when the SetCommBreak function has been called to suspend character transmission.

The following table summarizes the behavior of read operations based on the values specified for total and interval time-outs.

Total	Interval	Behavior
0	0	Returns when the buffer is completely filled. Time-outs are not used.
T	0	Returns when the buffer is completely filled or when T milliseconds have elapsed since the beginning of the operation.
0	Y	Returns when the buffer is completely filled or when Y milliseconds have elapsed between the receipt of any two characters. Timing does not begin until the first character is received.
T	Y	Returns when the buffer is completely filled or when either type of time-out occurs.
Note, however, that timing is relative to the system controlling the physical device. For a remote device such as a modem, the timing is relative to the server system to which the modem is attached. Any network propagation delay is not factored in. For example, a client application might specify a total time-out that computes to be 500 milliseconds. When 500 milliseconds have elapsed at the server, a time-out error is returned to the client. If there is a 50 milliseconds network propagation delay, the client will not be notified of the time-out until approximately 50 milliseconds after the time-out actually occurred.

The time-out parameters affect the behavior of overlapped read and write operations on a communications device. With overlapped I/O, the ReadFile, WriteFile, ReadFileEx, or WriteFileEx function can return before the operation has been completed. The time-out parameters can determine when the operation has been completed.


 Communications Errors

There are other circumstances where a read or write operation can be completed with fewer than the requested number of characters, even though a time-out has not occurred. Following are some examples:

•	Some drivers support the use of special characters, which complete a read operation immediately with only the characters that have been read up to the point when they are received.

•	The PurgeComm function can be called to prematurely terminate pending read or write operations. This function can also delete the contents of the output or input buffers, or both.

•	If a communications error occurs during a read or write operation, all I/O operations on the communications resource are terminated. Break conditions, parity errors, or framing errors are examples of such errors. When an error occurs, the process must call the ClearCommError function to clear the error flag before it can begin additional I/O operations. ClearCommError reports the specific error that occurred and the current status of the device.


 Communications Events

A process can monitor a set of events that occur in a communications resource. For example, an application can use event monitoring to determine when the CTS (clear-to-send) and DSR (data-set-ready) signals change state.

A process can monitor events on a given communications resource by using the SetCommMask function to create an event mask. To determine the current event mask for a communications resource, a process can use the GetCommMask function. The following values specify events that can be monitored.

Value	Meaning
EV_BREAK	A break was detected on input.
EV_CTS	The CTS (clear-to-send) signal changed state.
EV_DSR	The DSR (data-set-ready) signal changed state.
EV_ERR	A line-status error occurred. Line-status errors are CE_FRAME, CE_OVERRUN, and CE_RXPARITY.
EV_RING	A ring indicator was detected.
EV_RLSD	The RLSD (receive-line-signal-detect) signal changed state.
EV_RXCHAR	A character was received and placed in the input buffer.
EV_RXFLAG	The event character was received and placed in the input buffer. The event character is specified in the device's DCB structure, which is applied to a serial port by using the SetCommState function.
EV_TXEMPTY	The last character in the output buffer was sent.
After a set of events is specified, a process uses the WaitCommEvent function to wait for one of the events to occur. WaitCommEvent can be used synchronously or as an overlapped operation. For additional information about executing a function as an overlapped operation, see Synchronization.

When one of the events specified in the event mask occurs, the process completes the wait operation and sets an event mask variable to indicate the type of event detected. If the SetCommMask is called for a communications resource while a wait is pending for that resource, WaitCommEvent returns an error.

The WaitCommEvent function detects events that have occurred since the last call to SetCommMask or WaitCommEvent. For example, if you specify the EV_RXCHAR event as a wait-satisfying event, a call to WaitCommEvent will be satisfied if there are characters in the driver's input buffer that have arrived since the last call to WaitCommEvent or SetCommMask. Thus, given the following pseudo-code,

while (we_care) {

WaitCommEvent

T1:	// Read bytes

// process them

T2:	}

... any characters received between T1 and T2 will satisfy the next call to WaitCommEvent.

When monitoring an event that occurs when a signal (CTS, DSR, and so on) changes state, WaitCommEvent reports the change, but not the current state. To query the current state of the CTS (clear-to-send), DSR (data-set-ready), RLSD (receive-line-signal-detect), and ring indicator signals, a process can use the GetCommModemStatus function.


 Extended Functions

Some communications functions can be called for a device by using the EscapeCommFunction function. This function sends a code to direct the device to execute an extended function. For example, an application can suspend character transmission with the SETBREAK code and resume transmission with the CLRBREAK code. These particular operations can also be started by calling the SetCommBreak and ClearCommBreak functions. EscapeCommFunction can also be used to implement manual modem control. For example, the CLRDTR and SETDTR codes can be used to implement manual DTR (data-terminal-ready) flow control. Note, however, that an error occurs if a process uses EscapeCommFunction to manipulate the DTR line when the device has been configured to enable DTR handshaking, or the RTS (request-to-send) line if RTS handshaking is enabled.

The DeviceIoControl function enables a process to send an extended function code directly to a specified device driver, causing the device to perform a given operation. DeviceIoControl gives a device associated with a communications resource capabilities not supported by the standard serial communications functions. It enables an application to configure a device using parameters unique to that device as well as to call any device-specific functions.


 Using the Communications Functions

•	Configuring a communications resource

•	Monitoring communications events


 Configuring a Communications Resource

The following example opens a handle to COM1 and fills in a DCB structure with the current configuration. The DCB structure is then modified and used to reconfigure the device.

DCB dcb;
HANDLE hCom;
DWORD dwError;
BOOL fSuccess;

hCom = CreateFile("COM1",
    GENERIC_READ | GENERIC_WRITE,
    0,    /* comm devices must be opened w/exclusive-access */
    NULL, /* no security attrs */
    OPEN_EXISTING, /* comm devices must use OPEN_EXISTING */
    0,    /* not overlapped I/O */
    NULL  /* hTemplate must be NULL for comm devices */
    );

if (hCom == INVALID_HANDLE_VALUE) {
    dwError = GetLastError();

    /* handle error */
}

/*
 * Omit the call to SetupComm to use the default queue sizes.
 * Get the current configuration.
 */

fSuccess = GetCommState(hCom, &dcb);

if (!fSuccess) {
    /* Handle the error. *
}

/* Fill in the DCB: baud=9600, 8 data bits, no parity, 1 stop bit. */

dcb.BaudRate = 9600;
dcb.ByteSize = 8;
dcb.Parity = NOPARITY;
dcb.StopBits = ONESTOPBIT;

fSuccess = SetCommState(hCom, &dcb);

if (!fSuccess) {
    /* Handle the error. *
}


 Monitoring Communications Events

The following example code opens the serial port for overlapped I/O, creates an event mask to monitor CTS and DSR signals, and then waits for an event to occur. The WaitCommEvent function should be executed as an overlapped operation so the other threads of the process cannot perform I/O operations during the wait.

HANDLE hCom;
OVERLAPPED o;
BOOL fSuccess;
DWORD dwEvtMask;

hCom = CreateFile("COM1",
    GENERIC_READ | GENERIC_WRITE,
    0, /* exclusive access */
    NULL, /* no security attrs */
    OPEN_EXISTING,
    FILE_FLAG_OVERLAPPED,
    NULL
    );

if (hCom == INVALID_HANDLE_VALUE) {
    /* Deal with the error. */
}

/* Set the event mask. */

fSuccess = SetCommMask(hCom, EV_CTS | EV_DSR);

if (!fSuccess) {
    /* deal with error */
}

/* Create an event object for use in WaitCommEvent. */

o.hEvent = CreateEvent(NULL, /* no security attributes */
    FALSE, /* auto reset event */
    FALSE, /* not signaled */
    NULL /* no name */
    );

assert(o.hEvent);

if (WaitCommEvent(hCom, &dwEvtMask, &o)) {
    if (dwEvtMask & EV_DSR) {
        /*
         * . . .
         */
    }

    if (dwEvtMask & EV_CTS) {
        /*
         * . . .
         */
    }
}


 Communication Functions

Following are the functions used with communications devices.

BuildCommDCB
BuildCommDCBAndTimeouts
ClearCommBreak
ClearCommError
CommConfigDialog
DeviceIoControl
EscapeCommFunction
GetCommConfig
GetCommMask
GetCommModemStatus
GetCommProperties
GetCommState
GetCommTimeouts
PurgeComm
SetCommBreak
SetCommConfig
SetCommMask
SetCommState
SetCommTimeouts
SetupComm
TransmitCommChar
WaitCommEvent


 Consoles and Character-Mode Support

The Microsoft® Win32® application programming interface (API) provides consoles that manage input and output (I/O) for character-mode applications (applications that do not provide their own graphical user interface).

This overview describes Win32 support for character-mode applications.


 About Character-Mode Support

Consoles provide high-level support for simple character-mode applications that interact with the user by using functions that read from standard input and write to standard output or standard error. Consoles also provide sophisticated low-level support that gives direct access to a console's screen buffer and that enables applications to receive extended input information (such as mouse input).


 Consoles

A console is an interface that provides I/O to character-mode applications. This processor-independent mechanism makes it easy to port existing character-mode applications or to create new character-mode tools and applications.

A console consists of an input buffer and one or more screen buffers. The input buffer contains a queue of input records, each of which contains information about an input event. The input queue always includes key-press and key-release events. It can also include mouse events (pointer movements and button presses and releases) and events during which user actions affect the size of the active screen buffer. A screen buffer is a two-dimensional array of character and color data for output in a console window.

The Win32 API functions enable different levels of access to a console. The high-level console I/O functions enable an application to read from standard input to retrieve keyboard input stored in a console's input buffer. The functions also enable an application to write to standard output or standard error to display text in the console's screen buffer. The high-level functions also support redirection of standard handles and control of console modes for different I/O functionality. The low-level console I/O functions enable applications to receive detailed input about keyboard and mouse events, as well as events involving user interactions with the console window. The low-level functions also enable greater control of output to the screen.


 Creation of a Console

Microsoft Windows® creates a new console when it starts a console process, a character-mode process whose entry point is the main function. For example, Windows creates a new console when it starts the command processor. When the command processor starts a new console process, the user can specify whether the system creates a new console for the new process or whether it inherits the command processor's console. A process can create a console by using one of the following methods:

•	A graphical user interface (GUI) or console process that is not currently attached to a console can use the AllocConsole function to create a new console.

•	A GUI or console process can use the CreateProcess function to create a new console process and specify a flag to tell the system to create a new console.

Typically, a process uses AllocConsole to create a console when an error occurs requiring interaction with the user. For example, a GUI process can create a console when an error occurs that prevents it from using its normal graphical interface, or a console process that does not normally interact with the user can create a console when an error makes it necessary. The process that calls AllocConsole must not be attached to an existing console. GUI processes are not attached to any console when they are created. A console process is not attached to a console if the DETACHED_PROCESS flag was specified in a call to CreateProcess when the process was created. A process can use the FreeConsole function to detach itself from an inherited console or from a console created by AllocConsole.

A process can also create a console by specifying the CREATE_NEW_CONSOLE flag in a call to CreateProcess. This method creates a new console that is accessible to the child process but not to the parent process. Separate consoles enable both parent and child processes to interact with the user without conflict. If this flag is not specified when a console process is created, both processes are attached to the same console, and there is no guarantee that the correct process will receive the input intended for it. Applications can prevent confusion by creating child processes that do not inherit handles of the input buffer, or by enabling only one child process at a time to inherit an input buffer handle while preventing the parent process from reading console input until the child has finished.

Creating a new console results in a new console window, as well as separate I/O screen buffers. The process associated with the new console uses the GetStdHandle function to get the handles of the new console's input and screen buffers. These handles enable the process to access the console.

When a process uses CreateProcess, it can specify a STARTUPINFO structure, whose members control the characteristics of the first new console (if any) created for the child process. The STARTUPINFO structure specified in the call to CreateProcess affects a console created if the CREATE_NEW_CONSOLE flag is specified. It also affects a console created if the child process subsequently uses AllocConsole. The following console characteristics can be specified:

•	The size, in character cells, and the location, in screen pixel coordinates, of the new console window

•	The size, in character cells, of the new console's screen buffer

•	The text and background color attributes of the new console's screen buffer

•	The name appearing in the title bar of the new console's window

The system uses default values if the STARTUPINFO values are not specified. A child process can use the GetStartupInfo function to determine the values in its STARTUPINFO structure.

A process cannot change the location of its console window on the screen, but the following console functions are available to set or retrieve the other properties specified in the STARTUPINFO structure.

Function	Description
GetConsoleScreenBufferInfo	Retrieves the window size, screen buffer size, and color attributes.
SetConsoleWindowInfo	Changes the size of the console window.
SetConsoleScreenBufferSize	Changes the size of the screen buffer.
SetConsoleTextAttribute	Sets the color attributes.
SetConsoleTitle	Sets the console window title.
GetConsoleTitle	Retrieves the console window title.


 Closing a Console

A process can use the FreeConsole function to detach itself from its console. If other processes share the console, the console is not destroyed, but the process that called FreeConsole cannot refer to it. After calling FreeConsole, the process can use AllocConsole to create a new console.

A console is closed when the last process attached to it terminates or calls FreeConsole.


 Console Handles

A console process uses handles to access the input and screen buffers of its console. A process can use the GetStdHandle, CreateFile, or CreateConsoleScreenBuffer function to open one of these handles.

The GetStdHandle function provides a mechanism for retrieving the standard input (STDIN), standard output (STDOUT), and standard error (STDERR) handles associated with a process. During console creation, the system creates these handles. Initially, STDIN is a handle of the console's input buffer, and STDOUT and STDERR are handles of the console's active screen buffer. However, the SetStdHandle function can redirect the standard handles by changing the handle associated with STDIN, STDOUT, or STDERR. Because the parent's standard handles are inherited by any child process, subsequent calls to GetStdHandle return the redirected handle. A handle returned by GetStdHandle may, therefore,  refer to something other than console I/O. For example, before creating a child process, a parent process can use SetStdHandle to set a pipe handle to be the STDIN handle that is inherited by the child process. When the child process calls GetStdHandle, it gets the pipe handle. This means that the parent process can control the standard handles of the child process. The handles returned by GetStdHandle have GENERIC_READ | GENERIC_WRITE access unless SetStdHandle has been used to set the standard handle to have lesser access.

The value of the handles returned by GetStdHandle will not be 0, 1, and 2, so the standard predefined stream constants in the STDIO.H header file (STDIN, STDOUT, and STDERR) cannot be used in functions that require a console handle.

The CreateFile function enables a process to get a handle of its console's input buffer and active screen buffer, even if STDIN and STDOUT have been redirected. To open a handle of a console's input buffer, specify the CONIN$ value in a call to CreateFile. Specify the CONOUT$ value in a call to CreateFile to open a handle of a console's active screen buffer. CreateFile enables you to specify the read-write access of the handle that it returns.

The CreateConsoleScreenBuffer function creates a new screen buffer and returns a handle, which can be used in any function that accepts a handle of console output. The new screen buffer is not active until its handle is specified in a call to the SetConsoleActiveScreenBuffer function. Note that changing the active screen buffer does not affect the handle returned by GetStdHandle. Similarly, using SetStdHandle to change the STDOUT handle does not affect the active screen buffer.

Console handles returned by CreateFile and CreateConsoleScreenBuffer can be used in any of the console functions that require a handle of a console's input buffer or of a console screen buffer. Handles returned by GetStdHandle can be used by the console functions if they have not been redirected to refer to something other than console I/O. If a standard handle has been redirected to refer to a file or a pipe, however, the handle can only be used by the ReadFile and WriteFile functions.

A process can use the DuplicateHandle function to create a duplicate console handle that has different access or inheritability from the original handle. Note, however, that a process can create a duplicate console handle only for its own use. This differs from other handle types (such as file, pipe, or mutex objects), for which DuplicateHandle can create a duplicate that is valid for a different process.

To close a console handle, a process can use the CloseHandle function.


 Console Input Buffer

Each console has an input buffer that contains a queue of input event records. When a console's window has the keyboard focus, a console formats each input event (such as a single keystroke, a movement of the mouse, or a mouse-button click) as an input record that it places in the console's input buffer.

Applications can access a console's input buffer indirectly by using the high-level console I/O functions, or directly by using the low-level console I/O functions. The high-level input functions filter and process the data in the input buffer, returning only a stream of input characters. The low-level input functions enable applications to read input records directly from a console's input buffer, or to place input records into the input buffer.

An input record is a structure containing information about the type of event that occurred (keyboard, mouse, window resizing, focus, or menu event) as well as specific details about the event. The EventType member in an INPUT_RECORD structure indicates which type of event is contained in the record.

Focus and menu events are placed in a console's input buffer for internal use by the system and should be ignored by applications.

Keyboard Events

Keyboard events are generated when any key is pressed or released; this includes control keys. However, the ALT key has special meaning to Windows when pressed and released without being combined with another character, and it is not passed through to the application. Also, the CTRL+C key combination is not passed through if the input handle is in processed mode.

If the input event is a keystroke, the Event member in INPUT_RECORD is a KEY_EVENT_RECORD structure containing the following information:

•	A Boolean value indicating whether the key was pressed or released.

•	A repeat count that can be greater than one when a key is held down.

•	The virtual-key code, identifying the given key in a device-independent manner.

•	The virtual-scan code, indicating the device-dependent value generated by the keyboard hardware.

•	The translated Unicode™ or ANSI character.

•	A flag variable indicating the state of the control keys (the ALT, CTRL, SHIFT, NUM LOCK, SCROLL LOCK, and CAPS LOCK keys) and indicating whether an enhanced key was pressed. Enhanced keys for the IBM® 101-key and 102-key keyboards are 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.

Mouse Events

Mouse events are generated whenever the user moves the mouse or presses or releases one of the mouse buttons. Mouse events are placed in the input buffer only if the following conditions are met:

•	The console input mode is set to ENABLE_MOUSE_INPUT (the default mode).

•	The console window has the keyboard focus.

•	The mouse pointer is within the borders of the console's window.

If the input event is a mouse event, the Event member in INPUT_RECORD is a MOUSE_EVENT_RECORD structure containing the following information:

•	The coordinates of the mouse pointer in terms of the character-cell row and column in the screen buffer's coordinate system.

•	A flag variable indicating the state of the mouse buttons.

•	A flag variable indicating the state of the control keys (ALT, CTRL, SHIFT, NUM LOCK, SCROLL LOCK, and CAPS LOCK) and indicating whether an enhanced key was pressed. Enhanced keys for the IBM 101-key and 102-key keyboards are 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.

•	A flag variable indicating whether the event was a normal button-press or button-release event, a mouse movement event, or the second click of a double-click event.

Note that the mouse position coordinates are in terms of the screen buffer, not the console window. The screen buffer may have been scrolled with respect to the window, so the upper left corner of the window is not necessarily the (0,0) coordinate of the screen buffer. To determine the coordinates of the mouse relative to the coordinate system of the window, subtract the window origin coordinates from the mouse position coordinates. Use the GetConsoleScreenBufferInfo function to determine the window origin coordinates.

The dwButtonState member of the MOUSE_EVENT_RECORD structure has a bit corresponding to each mouse button. The bit is 1 if the button is down and 0 if the button is up. A button-release event is detected by a 0 value for the dwEventFlags member of MOUSE_EVENT_RECORD and a change in a button's bit from 1 to 0. The GetNumberOfConsoleMouseButtons function retrieves the number of buttons on the mouse.

Buffer-Resizing Events

A console window's menu enables the user to change the size of the active screen buffer; this change generates a buffer-resizing event. Buffer-resizing events are placed in the input buffer if the console's input mode is set to ENABLE_WINDOW_INPUT (that is, the default mode is disabled).

If the input event is a buffer-resizing event, the Event member of INPUT_RECORD is a WINDOW_BUFFER_SIZE_RECORD structure containing the new size of the screen buffer, expressed in character-cell columns and rows.

If the user reduces the size of the screen buffer, any data in the discarded portion of the buffer is lost.

Changes to the screen buffer size as a result of application calls to the SetConsoleScreenBufferSize function are not generated as buffer-resizing events.


 Console Screen Buffers

A screen buffer is a two-dimensional array of character and color data for output in a console window. A console can have multiple screen buffers. The active screen buffer is the one that is displayed on the screen.

The system creates a screen buffer whenever it creates a new console. A process can use the CreateConsoleScreenBuffer function to create additional screen buffers for its console. A new screen buffer is not active until its handle is specified in a call to the SetConsoleActiveScreenBuffer function. However, screen buffers can be accessed for reading and writing whether they are active or inactive.

Each screen buffer has its own two-dimensional array of character information records. The data for each character is stored in a CHAR_INFO structure that specifies the Unicode or ANSI character and the foreground and background colors in which that character is displayed.

A number of properties associated with a screen buffer can be set independently for each screen buffer. This means that changing the active screen buffer can have a dramatic effect on the appearance of the console window. The properties associated with a screen buffer include:

•	Screen buffer size, in character rows and columns.

•	Text attributes (foreground and background colors for displaying text to be written by the WriteFile or WriteConsole function).

•	Window size and location (the rectangular region of the screen buffer that is displayed in the console window).

•	Cursor position, appearance, and visibility.

•	Output modes (ENABLE_PROCESSED_OUTPUT and ENABLE_WRAP_AT_EOL_OUTPUT). For more information about console output modes, see High-Level Console Modes.

When a screen buffer is created, it contains blanks. Its cursor is visible and positioned at the buffer's origin (0,0), and the window is positioned with its upper left corner at the buffer's origin. The size of the screen buffer, the window size, the text attributes, and the appearance of the cursor are determined by the user or by the system defaults. To retrieve the current values of the various properties associated with the screen buffer, use the GetConsoleScreenBufferInfo, GetConsoleCursorInfo, and GetConsoleMode functions.

Applications that change any of the screen buffer properties should either create their own screen buffer or save the state of the inherited screen buffer during startup and restore it at exit.


 Window and Screen Buffer Size

The size of a screen buffer is expressed in terms of a coordinate grid based on character cells. The width is the number of character cells in each row, and the height is the number of rows. Associated with each screen buffer is a window that determines the size and location of the rectangular portion of the screen buffer displayed in the console window. A screen buffer's window is defined by specifying the character-cell coordinates of the upper left and lower right cells of the window's rectangle.

A screen buffer can be any size, limited only by available memory. The dimensions of a screen buffer's window cannot exceed the corresponding dimensions of either the screen buffer or the maximum window that can fit on the screen based on the current font size (controlled exclusively by the user).

The GetConsoleScreenBufferInfo function returns the following information about a screen buffer and its window:

•	The current size of the screen buffer

•	The current location of the window

•	The maximum size of the window given the current screen buffer size, the current font size, and the screen size

The GetLargestConsoleWindowSize function returns the maximum size of a console's window based on the current font and screen sizes. This size differs from the maximum window size returned by GetConsoleScreenBufferInfo in that the screen buffer size is ignored.

To change a screen buffer's size, use the SetConsoleScreenBufferSize function. This function fails if either dimension of the specified size is less than the corresponding dimension of the console's window.

To change the size or location of a screen buffer's window, use the SetConsoleWindowInfo function. This function fails if the specified window-corner coordinates exceed the limits of the screen buffer or the screen. Changing the window size of the active screen buffer changes the size of the console window displayed on the screen.

A process can change its console's input mode to enable window input so that the process is able to receive input when the user changes the screen buffer size. If an application enables window input, it can use GetConsoleScreenBufferInfo to retrieve window and screen buffer size at startup. This information can then be used to determine the way data is displayed in the window. If the user changes the screen buffer size, the application can respond by changing the way data is displayed. For example, an application can adjust the way text wraps at the end of the line if the number of characters per row changes. If an application does not enable window input, it must either use the inherited window and screen buffer sizes, or set them to the desired size during startup and restore the inherited sizes at exit. For additional information about window input mode, see Low-Level Console Modes.


 Scrolling the Screen Buffer

The console window displays a portion of the active screen buffer. Each screen buffer maintains its own current window rectangle that specifies the coordinates of the upper left and lower right character cells to be displayed in the console window. To determine the current window rectangle of a screen buffer, use GetConsoleScreenBufferInfo. When a screen buffer is created, the upper left corner of its window is at the upper left corner of the screen buffer at (0,0).

The window rectangle can change to display different parts of the screen buffer. The window rectangle of a screen buffer can change in the following situations:

•	When SetConsoleWindowInfo is called to specify a new window rectangle, it scrolls the view of the screen buffer by changing the position of the window rectangle without changing the size of the window. For examples of scrolling the window's contents, see Scrolling a Screen Buffer's Window.

•	When using the WriteFile function to write to a screen buffer with wrap at end-of-line (EOL) output mode enabled, the window rectangle shifts automatically, so the cursor is always displayed.

•	When the SetConsoleCursorPosition function specifies a new cursor position that is outside the boundaries of the current window rectangle, the window rectangle shifts automatically to display the cursor.

•	When the user changes the size of the console window or uses the window's scroll bars, the window rectangle of the active screen buffer can change. This change is not reported as a window resizing event in the input buffer.

In each of these situations, the window rectangle shifts to display a different part of the screen buffer, but the contents of the screen buffer remain in the same position. The following situations can cause the screen buffer's contents to shift:

•	When the ScrollConsoleScreenBuffer function is called, a rectangular block is copied from one part of a screen buffer to another.

•	When using WriteFile to write to a screen buffer with wrap at EOL output mode enabled, the screen buffer's contents scroll automatically when the end of the screen buffer is encountered. This scrolling discards the top row of the screen buffer.

ScrollConsoleScreenBuffer specifies the screen buffer rectangle that is moved and the new upper left coordinates to which the rectangle is copied. This function can scroll a portion or the entire contents of the screen buffer.

The illustration shows a ScrollConsoleScreenBuffer operation that scrolls the entire contents of the screen buffer up by several rows. The contents of the top rows are discarded, and the bottom rows are filled with a specified character and color.

The effects of ScrollConsoleScreenBuffer can be limited by specifying an optional clipping rectangle so that the contents of the screen buffer outside the clipping rectangle are unchanged. The effect of clipping is to create a subwindow (the clipping rectangle) whose contents are scrolled without affecting the rest of the screen buffer. For an example that uses ScrollConsoleScreenBuffer, see Scrolling a Screen Buffer's Contents.

Cursor Appearance and Position

A screen buffer's cursor can be visible or hidden. When it is visible, its appearance can vary, ranging from from completely filling a character cell to appearing as a horizontal line at the bottom of the cell. To retrieve information about the appearance and visibility of the cursor, use the GetConsoleCursorInfo function. This function reports whether the cursor is visible and describes the appearance of the cursor as the percentage of a character cell that it fills. To set the appearance and visibility of the cursor, use the SetConsoleCursorInfo function.

Characters written by the high-level console I/O functions are written at the current cursor location, advancing the cursor to the next location. To determine the current cursor position in the coordinate system of a screen buffer, use GetConsoleScreenBufferInfo. You can use SetConsoleCursorPosition to set the cursor position and, thereby, control the placement of text that is written or echoed by the high-level I/O functions. If you move the cursor, text at the new cursor location is overwritten.

The position, appearance, and visibility of the cursor are set independently for each screen buffer.

Screen Buffer Color Attributes

Each screen buffer character cell stores the color attributes for the colors used in drawing the text and background of that cell. An application can set the color data for each character cell individually, storing the data in the Attributes member of the CHAR_INFO structure for each cell.

The current text attributes of each screen buffer determine the foreground (text) and background colors of characters subsequently written or echoed by the high-level functions. An application can use GetConsoleScreenBufferInfo to determine the current text attributes of a screen buffer and the SetConsoleTextAttribute function to set the text attributes. Changing a screen buffer's text attributes does not affect the display of characters previously written. These text attributes do not affect characters written by the low-level console I/O functions (such as the WriteConsoleOutput or WriteConsoleOutputCharacter function) which either explicitly specify the attributes for each cell that is written or leave the attributes unchanged at the written positions.

The following attribute constants are defined in the WINCON.H header file:

•	FOREGROUND_BLUE

•	FOREGROUND_GREEN

•	FOREGROUND_RED

•	FOREGROUND_INTENSITY

•	BACKGROUND_BLUE

•	BACKGROUND_GREEN

•	BACKGROUND_RED

•	BACKGROUND_INTENSITY

The foreground attributes specify the text color, and the background attributes specify the color used to fill the cell's background. An application can combine the constants to achieve different colors. For example, the following combination results in bright cyan text on a blue background.

FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_INTENSITY | BACKGROUND_BLUE

If no background constant is specified, the background is black, and if no foreground constant is specified, the text is black. For example, the following combination produces black text on a white background.

BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED


 Input and Output Methods

The Win32 API provides two very different approaches to console I/O, the choice of which depends on how much flexibility and control an application needs. The high-level approach enables simple character stream I/O, but it limits access to a console's input and screen buffers. The low-level approach requires that developers write more code and choose among a greater range of functions, but it also gives an application more flexibility.

An application can use the file I/O functions, ReadFile and WriteFile, and the console functions, ReadConsole and WriteConsole, for high-level I/O that provides indirect access to a console's input and screen buffers. The high-level input functions filter and process the data in a console's input buffer to return input as a stream of characters, discarding mouse and buffer-resizing input. Similarly, the high-level output functions write a stream of characters that are displayed at the current cursor location in a screen buffer. An application controls the way these functions work by setting a console's I/O modes.

The low-level I/O functions provide direct access to a console's input and screen buffers, enabling an application to access mouse and buffer-resizing input events and extended information for keyboard events. Low-level output functions enable an application to read from or write to a specified number of consecutive character cells in a screen buffer, or to read or write to rectangular blocks of character cells at a specified location in a screen buffer. A console's input modes affect low-level input by enabling the application to determine whether mouse and buffer-resizing events are placed in the input buffer. A console's output modes have no effect on low-level output.

The high-level and low-level I/O methods are not mutually exclusive, and an application can use any combination of these functions. Typically, however, an application uses one approach or the other exclusively.

The sections that follow describe in detail the console modes and the high-level and low-level I/O functions.


 Console Modes

Associated with each console input buffer are a set of input modes that affects input operations. Similarly, each console screen buffer has a set of output modes that affects output operations. The input modes can be divided into two groups: those that affect the high-level input functions and those that affect the low-level input functions. The output modes only affect applications that use the high-level output functions.

The GetConsoleMode function reports the current input mode of a console's input buffer or the current output mode of a screen buffer. The SetConsoleMode function sets the current mode of either a console input buffer or a screen buffer. If a console has multiple screen buffers, the output modes of each can be different. An application can change I/O modes at any time. For more information about the console modes that affect high-level and low-level I/O operations, see High-Level Console Modes and Low-Level Console Modes.


 High-Level Console I/O

The high-level I/O functions provide a simple way to read a stream of characters from console input or to write a stream of characters to console output. A high-level read operation gets input characters from a console's input buffer and stores them in a specified buffer. A high-level write operation takes characters from a specified buffer and writes them to a screen buffer at the current cursor location, advancing the cursor as each character is written.

High-level I/O gives you a choice between the ReadFile and WriteFile functions and the ReadConsole and WriteConsole functions. They are identical, except for two important differences. The console functions support the use of either Unicode characters or the ANSI character set; the file I/O functions do not support Unicode. Also, the file I/O functions can be used to access files, pipes, and serial communications devices; the console functions can only be used with console handles. This distinction is important if an application relies on standard handles that may have been redirected.

When using either set of high-level functions, an application can control the text and background colors used to display characters subsequently written to a screen buffer. An application can also use the console modes that affect high-level console I/O to enable or disable the following properties:

•	Echoing of keyboard input to the active screen buffer

•	Line input, in which a read operation does not return until the ENTER key is pressed

•	Automatic processing of keyboard input to handle carriage returns, CTRL+C, and other input details

•	Automatic processing of output to handle line wrapping, carriage returns, backspaces, and other output details


 High-Level Console Modes

The behavior of the high-level console functions is affected by the console input and output modes. All of the following console input modes are enabled for a console's input buffer when a console is created:

•	Line input mode

•	Processed input mode

•	Echo input mode

Both of the following console output modes are enabled for a console screen buffer when it is created:

•	Processed output mode

•	Wrapping at EOL output mode

All three input modes, along with processed output mode, are designed to work together. It is best to either enable or disable all of these modes as a group. When all are enabled, the application is said to be in "cooked" mode, which means that most of the processing is handled for the application. When all are disabled, the application is in "raw" mode, which means that input is unfiltered and any processing is left to the application.

An application can use the GetConsoleMode function to determine the current mode of a console's input buffer or screen buffer. You can enable or disable any of these modes by using the following values in the SetConsoleMode function. Note that setting the output mode of one screen buffer does not affect the output mode of other screen buffers.

Mode	Description
ENABLE_PROCESSED_INPUT
	Used with a console input handle to cause the system to process any system editing or control key input rather than returning it as input in the read operation's buffer. If line input is also enabled, backspaces and carriage returns are handled correctly. A backspace causes the cursor to move back one space without affecting the character at the cursor position. A carriage return is converted to carriage return − linefeed character combination. If echo input mode is enabled and the output should reflect system editing, processed output must be enabled for the active screen buffer. If processed input is enabled, the CTRL+C key combination is passed on to the appropriate handler regardless of whether line input is enabled. For more information about control handlers, see Console Control Handlers.
ENABLE_LINE_INPUT
	Used with a console input handle to cause the ReadFile and ReadConsole functions to return when the ENTER key is pressed. If line input mode is disabled, the functions return when one or more characters are available in the input buffer.
ENABLE_ECHO_INPUT
	Used with a console input handle to cause keyboard input read by the ReadFile or ReadConsole function to be echoed to the active screen buffer. Characters are echoed only if the process that calls ReadFile or ReadConsole has an open handle of the active screen buffer. Echo mode cannot be enabled unless line input is also enabled. The output mode of the active screen buffer affects the way echoed input is displayed.
ENABLE_PROCESSED_OUTPUT
	Used with a console screen buffer handle to cause the system to perform the appropriate action for ANSI control characters that are written to a screen buffer. The backspace, tab, bell, carriage return, and linefeed characters are processed. A tab character moves the cursor to the next tab stop, which occurs every eight characters. A bell character sounds a short tone.
ENABLE_WRAP_AT_EOL_OUTPUT
	Used with a console screen buffer handle to cause the current output position (cursor position) to move to the first column in the next row (line) when the end of the current row is reached. If the bottom of the window region is reached, the window origin is moved down one row. This movement has the effect of scrolling the contents of the window up one row. If the bottom of the screen buffer is reached, the contents of the screen buffer are scrolled up one row, and the top row of the screen buffer is discarded. If this mode is disabled, the last character in the row is overwritten with any subsequent characters.


 High-Level Console Input and Output Functions

The ReadFile and WriteFile functions, or the ReadConsole and WriteConsole functions, enable an application to read console input and write console output as a stream of characters. ReadConsole and WriteConsole behave exactly like ReadFile and WriteFile except that they can be used either as wide-character functions (in which text arguments must use Unicode) or as ANSI functions (in which text arguments must use characters from the Windows 3.x character set). Applications that need to maintain a single set of sources to support either Unicode or the ANSI character set should use ReadConsole and WriteConsole.

ReadConsole and WriteConsole can only be used with console handles; ReadFile and WriteFile can be used with other handles (such as files or pipes). ReadConsole and WriteConsole fail if used with a standard handle that has been redirected and is no longer a console handle.

To get keyboard input, a process can use ReadFile or ReadConsole with a handle of the console's input buffer, or it can use ReadFile to read input from a file or a pipe if STDIN has been redirected. These functions only return keyboard events that can be translated into ANSI characters (or Unicode characters in the case of ReadConsole). The input that can be returned includes control key combinations. The functions do not return keyboard events involving the function keys or arrow keys. Input events generated by mouse, window, focus, or menu input are discarded.

If line input mode is enabled (the default mode), ReadFile and ReadConsole do not return to the calling application until the ENTER key is pressed. If line input mode is disabled, the functions do not return until at least one character is available. In either mode, all available characters are read until either no more keys are available or the specified number of characters has been read. Unread characters are buffered until the next read operation. The functions report the total number of characters actually read. If echo input mode is enabled, characters read by these functions are written to the active screen buffer at the current cursor position.

A process can use WriteFile or WriteConsole to write to either an active or inactive screen buffer, or it can use WriteFile to write to a file or a pipe if STDOUT has been redirected. Processed output mode and wrap at EOL output mode control the way characters are written or echoed to a screen buffer.

Characters written by WriteFile or WriteConsole, or echoed by ReadFile or ReadConsole, are inserted in a screen buffer at the current cursor position. As each character is written, the cursor position advances to the next character cell; however, the behavior at the end of a row depends on the screen buffer's wrap at EOL output mode. An application can use the GetConsoleScreenBufferInfo function to determine the current cursor position and the SetConsoleCursorPosition function to set the cursor position.

For an example that uses the high-level console I/O functions, see Using the High-Level Input and Output Functions.


 Low-Level Console I/O

The low-level console I/O functions expand an application's control over console I/O by enabling direct access to a console's input and screen buffers. These functions enable an application to perform the following tasks:

•	Receive input about mouse and buffer-resizing events

•	Receive extended information about keyboard input events

•	Write input records to the input buffer

•	Read input records without removing them from the input buffer

•	Determine the number of pending events in the input buffer

•	Flush the input buffer

•	Read and write strings of Unicode or ANSI characters at a specified location in a screen buffer

•	Read and write strings of text and background color attributes at a specified screen buffer location

•	Read and write rectangular blocks of character and color data at a specified screen buffer location

•	Write a single Unicode or ANSI character, or a text and background color attribute combination, to a specified number of consecutive cells beginning at a specified screen buffer location


 Low-Level Console Modes

The types of input events reported in a console's input buffer depend on the console's mouse and window input modes. The console's processed input mode determines how the system handles the CTRL+C key combination. To set or retrieve the state of a console's input modes, an application can specify a console input buffer handle in a call to the SetConsoleMode or GetConsoleMode function. The following modes are used with console input handles.

Mode	Description
ENABLE_MOUSE_INPUT
	Controls whether mouse events are reported in the input buffer. By default, mouse input is enabled and window input is disabled. Changing either of these modes affects only input that occurs after the mode is set; pending mouse or window events in the input buffer are not flushed. The mouse pointer is displayed regardless of the mouse mode.
ENABLE_WINDOW_INPUT
	Controls whether buffer-resizing events are reported in the input buffer. By default, mouse input is enabled and window input is disabled. Changing either of these modes affects only input that occurs after the mode is set; pending mouse or window events in the input buffer are not flushed. The mouse pointer is displayed regardless of the mouse mode.
ENABLE_PROCESSED_INPUT
	Controls the processing of input for applications using the high-level console I/O functions. However, if processed input mode is enabled, the CTRL+C key combination is not reported in the console's input buffer. Instead, it is passed on to the appropriate control handler function. For more information about control handlers, see Console Control Handlers.
The output modes of a screen buffer do not affect the behavior of the low-level output functions.


 Low-Level Console Input Functions

A console's input buffer contains input records that can include information about keyboard, mouse, buffer-resizing, focus, and menu events. The low-level functions provide direct access to the input buffer, unlike the high-level functions that filter and process the input buffer's data, discarding all but keyboard input.

The Win32 API provides five low-level functions for accessing a console's input buffer:

•	ReadConsoleInput

•	PeekConsoleInput

•	GetNumberOfConsoleInputEvents

•	WriteConsoleInput

•	FlushConsoleInputBuffer

The ReadConsoleInput, PeekConsoleInput, and WriteConsoleInput functions use the INPUT_RECORD structure to read from or write to an input buffer.

Following are descriptions of the low-level console input functions.

Function	Description
ReadConsoleInput	Reads and removes input records from an input buffer. The function does not return until at least one record is available to be read. Then all available records are transferred to the buffer of the calling process until either no more records are available or the specified number of records has been read. Unread records remain in the input buffer for the next read operation. The function reports the total number of records that have been read. For an example that uses ReadConsoleInput, see Reading Input Buffer Events.
PeekConsoleInput	Reads without removing the pending input records in an input buffer. All available records up to the specified number are copied into the buffer of the calling process. If no records are available, the function returns immediately. The function reports the total number of records that have been read.
GetNumberOfConsoleInputEvents	Determines the number of unread input records in an input buffer.
WriteConsoleInput	Places input records into the input buffer behind any pending records in the buffer. The input buffer grows dynamically, if necessary, to hold as many records as are written. To use this function, the specified input buffer handle must have GENERIC_WRITE access.
FlushConsoleInputBuffer	Discards all unread events in the input buffer. To use this function, the specified input buffer handle must have GENERIC_WRITE access.
A thread of an application's process can perform a wait operation to wait for input to be available in an input buffer. To initiate a wait operation, specify a handle of the input buffer in a call to any of the wait functions (WaitForSingleObject, WaitForMultipleObjects, WaitForSingleObjectEx, or WaitForMultipleObjectsEx). These functions can return when the state of one or more objects is signaled. The state of a console input handle becomes signaled when there are unread records in its input buffer. The state is reset to nonsignaled when the input buffer becomes empty. If there is no input available, the calling thread enters an efficient wait state, consuming very little processor time while waiting for the conditions of the wait operation to be satisfied.


 Low-Level Console Output Functions

The low-level console output functions provide direct access to the character cells of a screen buffer. One set of functions reads from or writes to consecutive cells beginning at any location in the screen buffer. Another set of functions reads from or writes to rectangular blocks of cells.

The following functions read from or write to a specified number of consecutive character cells in a screen buffer, beginning with a specified cell.

Function	Description
ReadConsoleOutputCharacter
	Copies a string of Unicode or ANSI characters from a screen buffer.
WriteConsoleOutputCharacter
	Writes a string of Unicode or ANSI characters to a screen buffer.
ReadConsoleOutputAttribute
	Copies a string of text and background color attributes from a screen buffer.
WriteConsoleOutputAttribute
	Writes a string of text and background color attributes to a screen buffer.
FillConsoleOutputCharacter
	Writes a single Unicode or ANSI character to a specified number of consecutive cells in a screen buffer.
FillConsoleOutputAttribute
	Writes a text and background color attribute combination to a specified number of consecutive cells in a screen buffer.
For all of these functions, when the last cell of a row is encountered, reading or writing wraps around to the first cell of the next row. When the end of the last row of the screen buffer is encountered, the write functions discard all unwritten characters or attributes, and the read functions report the number of characters or attributes actually written..

The following functions read from or write to rectangular blocks of character cells at a specified location in a screen buffer.

Function	Description
ReadConsoleOutput
	Copies character and color data from a specified block of screen buffer cells into a given block in a destination buffer.
WriteConsoleOutput
	Writes character and color data to a specified block of screen buffer cells from a given block in a source buffer.
These functions treat screen buffers and source or destination buffers as two-dimensional arrays of CHAR_INFO structures (containing character and color attribute data for each cell). The functions specify the width and height, in character cells, of the source or destination buffer, and the pointer to the buffer is treated as a pointer to the origin cell (0,0) of the two-dimensional array. The functions use a SMALL_RECT structure to specify which rectangle to access in the screen buffer, and the coordinates of the upper left cell in the source or destination buffer determine the location of the corresponding rectangle in that buffer.

These functions automatically clip the specified screen buffer rectangle to fit within the boundaries of the screen buffer. For example, if the rectangle specifies lower right coordinates that are (column 100, row 50) and the screen buffer is only 80 columns wide, the coordinates are clipped so that they are (column 79, row 50). Similarly, this adjusted rectangle is again clipped to fit within the boundaries of the source or destination buffer. The screen buffer coordinates of the actual rectangle that was read from or written to are specified. For an example that uses these functions, see Reading and Writing Blocks of Characters and Attributes.

The illustration shows a ReadConsoleOutput operation where clipping occurs when the block is read from the screen buffer, and again when the block is copied into the destination buffer. The function reports the actual screen buffer rectangle that it copied from.


 Console Code Pages

A code page is a mapping of 256 character codes to individual characters. Different code pages include different special characters, typically customized for a language or a group of languages.

Associated with each console are two code pages: one for input and one for output. A console uses its input code page to translate keyboard input into the corresponding character value. It uses its output code page to translate the character values written by the various output functions into the images displayed in the console window. An application can use the SetConsoleCP and GetConsoleCP functions to set and retrieve a console's input code pages and the SetConsoleOutputCP and GetConsoleOutputCP functions to set and retrieve its output code pages.

The identifiers of the code pages available on the local computer are stored in the registry under the following key.

%HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Nls\\CodePage%

For information about using the registry functions to determine the available code pages, see Registry.

For more information about code pages, see String Manipulation.


 Console Control Handlers

Each console process has its own list of control handler functions that are called by the system when the process receives a CTRL+C, CTRL+BREAK, or CTRL+CLOSE signal. Initially, the list of control handlers for each process contains only a default handler function that calls the ExitProcess function. A console process can add or remove additional handler functions by calling the SetConsoleCtrlHandler function. This function does not affect the lists of control handlers for other processes. When a console process receives any of the control signals, it calls the handler functions on a last-registered, first-called basis until one of the handlers returns TRUE. If none of the handlers returns TRUE, the default handler is called.

The following typedef declaration illustrates the format of a control handler function.

typedef BOOL (*PHANDLER_ROUTINE)(DWORD dwCtrlType);

The function's dwCtrlType parameter identifies which control signal was received, and the return value indicates whether the signal was handled.

For an example of a control handler function, see Registering a Control Handler Function.


 CTRL+C and CTRL+BREAK Signals

The CTRL+C and CTRL+BREAK key combinations receive special handling by console processes. By default, when a console window has the keyboard focus, CTRL+C or CTRL+BREAK is treated as a signal (SIGINT or SIGBREAK) and not as keyboard input. By default, these signals are passed to all console processes that are attached to the console, causing the system to call the control handler function or functions associated with these processes. Detached processes (GUI processes or console processes started with the DETACHED_PROCESS or CREATE_NEW_CONSOLE flag) are not affected.

CTRL+BREAK is always treated as a signal, but an application can change the default CTRL+C behavior in two ways that prevent the handler functions from being called:

•	The SetConsoleMode function can disable the ENABLE_PROCESSED_INPUT input mode for a console's input buffer, so CTRL+C is reported as keyboard input rather than as a signal.

•	When SetConsoleCtrlHandler is called with NULL and TRUE values for its parameters, the calling process ignores CTRL+C signals. Normal CTRL+C processing is restored by calling SetConsoleCtrlHandler with NULL and FALSE values. This attribute of ignoring or not ignoring CTRL+C signals is inherited by child processes, but it can be enabled or disabled by any process without affecting existing processes.


 CTRL+CLOSE Signal

The system generates a CTRL+CLOSE signal when the user closes a console. All processes attached to the console receive the signal, giving each process an opportunity to clean up before termination. When a process receives this signal, the handler function can take one of the following actions after performing any cleanup operations:

•	Call ExitProcess to terminate the process.

•	Return FALSE. If none of the registered handler functions returns TRUE, the default handler terminates the process.

•	Return TRUE. In this case, no other handler functions are called, and a pop-up dialog box asks the user whether to terminate the process. If the user chooses not to terminate the process, the system does not close the console until the process finally terminates.


 Console Process Groups

When a process uses the CreateProcess function to create a new console process, it can specify the CREATE_NEW_PROCESS_GROUP flag to make the new process the root process of a console process group. The process group includes all processes that are descendants of the root process.

A process can use the GenerateConsoleCtrlEvent function to send a CTRL+C or CTRL+BREAK signal to all processes in a console process group. The signal is only received by those processes in the group that are attached to the same console as the process that called GenerateConsoleCtrlEvent.


 Using the Console

•	Using the high-level input and output functions

•	Writing characters or colors to consecutive cells

•	Reading and writing blocks of characters and attributes

•	Reading input buffer events

•	Scrolling a screen buffer's window

•	Scrolling a screen buffer's contents

•	Registering a control handler function

•	Console application issues


 Using the High-Level Input and Output Functions

The following example uses the high-level console I/O functions for console I/O. For more information about the high-level console I/O functions, see High-Level Console I/O.

The example assumes that the default I/O modes are in effect initially for the first calls to the ReadFile and WriteFile functions. Then the input mode is changed to turn off line input mode and echo input mode for the second calls to ReadFile and WriteFile. The SetConsoleTextAttribute function is used to set the colors in which subsequently written text will be displayed. Before exiting, the program restores the original console input mode and color attributes.

The example's NewLine function is used when line input mode is disabled. It handles carriage returns by moving the cursor position to the first cell of the next row. If the cursor is already in the last row of the screen buffer, the contents of the screen buffer are scrolled up one line. For an example that illustrates the use of the ScrollConsoleScreenBuffer function to scroll a screen buffer, see Scrolling a Screen Buffer's Contents.

#include <windows.h>

VOID NewLine(VOID);

VOID ScrollScreenBuffer(HANDLE, INT);

HANDLE hStdout, hStdin;

CONSOLE_SCREEN_BUFFER_INFO csbiInfo;

VOID main(void) {

LPSTR lpszPrompt1 = "Type something and press Enter:\n";

LPSTR lpszPrompt2 = "Type any key: ";

CHAR chBuffer[256];

DWORD cRead, cWritten, fdwMode, fdwOldMode;

WORD wOldColorAttrs;

/* Get handles to STDIN and STDOUT. */

hStdin = GetStdHandle(STD_INPUT_HANDLE);

hStdout = GetStdHandle(STD_OUTPUT_HANDLE);

if (hStdin == INVALID_HANDLE_VALUE ||

        hStdout == INVALID_HANDLE_VALUE)

    MyErrorExit("GetStdHandle");

/* Save the current text colors. */

if (! GetConsoleScreenBufferInfo(hStdout, &csbiInfo))

    MyErrorExit("GetConsoleScreenBufferInfo");

wOldColorAttrs = csbiInfo.wAttributes;

/* Set the text attr. to draw red text on black background. */

if (! SetConsoleTextAttribute(hStdout, FOREGROUND_RED))

        MyErrorExit("SetConsoleTextAttribute");

/*

 * Write to STDOUT and read from STDIN by using the default

 * modes. Input is echoed automatically, and ReadFile

 * does not return until a carriage return is typed.

 *

 * The default input modes are line, processed, and echo.

 * The default output modes are processed and wrap at EOL.

 */

while (1) {

    if (! WriteFile(

            hStdout,              /* output handle  */

            lpszPrompt1,          /* prompt string  */

            lstrlen(lpszPrompt1), /* string length  */

            &cWritten,            /* bytes written  */

            NULL) )               /* not overlapped */

        break;

    if (! ReadFile(

            hStdin,    /* input handle        */

            chBuffer,  /* buffer to read into */

            255,       /* size of buffer      */

            &cRead,    /* actual bytes read   */

            NULL) )    /* not overlapped      */

        break;

    if (chBuffer[0] == 'q') break;

}

/* Turn off the line input mode, and echo the input mode. */

if (! GetConsoleMode(hStdin, &fdwOldMode))

    MyErrorExit("GetConsoleMode");

fdwMode = fdwOldMode &

          ~(ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT);

if (! SetConsoleMode(hStdin, fdwMode))

    MyErrorExit("SetConsoleMode");

/* Prompt for input. */

if (! WriteFile(

        hStdout,              /* output handle  */

        lpszPrompt2,          /* prompt string  */

        lstrlen(lpszPrompt2), /* string length  */

        &cWritten,            /* bytes written  */

        NULL) )               /* not overlapped */

    MyErrorExit("WriteFile");

/*

 * Without line and echo input modes, ReadFile returns

 * when any input is available. Carriage returns must

 * be handled, and WriteFile is used to echo input.

 */

while (1) {

    if (! ReadFile(hStdin, chBuffer, 1, &cRead, NULL))

        break;

    if (chBuffer[0] == '\r')

        NewLine();

    else

        if (! WriteFile(hStdout, chBuffer, cRead,

                        &cWritten, NULL))

            break;

    if (chBuffer[0] == 'q') break;

}

/* Restore the original console mode. */

if (! SetConsoleMode(hStdin, fdwOldMode))

    MyErrorExit("SetConsoleMode");

/* Restore the original text colors. */

if (! SetConsoleTextAttribute(hStdout, wOldColorAttrs))

    MyErrorExit("SetConsoleTextAttribute");

}

/*

 * The NewLine function handles carriage returns when the processed

 * input mode is disabled. It gets the current cursor position

 * and resets it to the first cell of the next row.

 */

VOID NewLine(VOID) {

if (! GetConsoleScreenBufferInfo(hStdout, &csbiInfo))

    MyErrorExit("GetConsoleScreenBufferInfo");

csbiInfo.dwCursorPosition.X = 0;

/*

 * If it is the last line in the screen buffer, scroll

 * the buffer up.

 */

if ((csbiInfo.dwSize.Y-1) == csbiInfo.dwCursorPosition.Y) {

    ScrollScreenBuffer(hStdout, 1);

}

/* Otherwise, advance the cursor to the next line. */

else

    csbiInfo.dwCursorPosition.Y += 1;

if (! SetConsoleCursorPosition(hStdout,

              csbiInfo.dwCursorPosition))

    MyErrorExit("SetConsoleCursorPosition");

}


 Writing Characters or Colors to Consecutive Cells

Characters or color attributes can be written to specified character cells in a screen buffer. The following example uses the WriteConsoleOutputCharacter function to write a string of characters beginning at the upper left corner of a screen buffer. Then the example uses the WriteConsoleOutputAttribute function to write a string of color attributes to the first 51 cells of the same row. The coord parameter for both functions specifies the character cell in the screen buffer at which writing begins. The location in the console window where these characters or colors appear depends on the current window rectangle of the screen buffer. For additional information about the relationship between a screen buffer and its windows, see Window and Screen Buffer Size and Scrolling the Screen Buffer.

    HANDLE hOutput;

    LPTSTR lpszString = "Character String";

    DWORD cWritten;

    BOOL fSuccess;

    COORD coord;

    WORD wColors[3], wColor;

    CHAR chFillChar;

/* Write a string of characters to a screen buffer. */

    coord.X = 0;            /* start at first cell */

    coord.Y = 0;            /*   of first row      */

    fSuccess = WriteConsoleOutputCharacter(

        hOutput,              /* screen buffer handle     */

        lpszString,           /* pointer to source string */

        lstrlen(lpszString),  /* length of string         */

        coord,                /* first cell to write to   */

        &cWritten);           /* actual number written to */

    if (! fSuccess)

        MyErrorExit("WriteConsoleOutputCharacter");

/* Write a string of colors to a screen buffer. */

    wColors[0] = BACKGROUND_RED;

    wColors[1] = BACKGROUND_RED |     /* white background */

                 BACKGROUND_GREEN |

                 BACKGROUND_BLUE;

    wColors[2] = BACKGROUND_BLUE;

    for (;fSuccess && coord.X < 50; coord.X += 3)

        fSuccess = WriteConsoleOutputAttribute(

            hOutput,          /* screen buffer handle     */

            wColors,          /* pointer to source string */

            3,                /* length of string         */

            coord,            /* first cell to write to   */

            &cWritten);       /* actual number written to */

    if (! fSuccess)

        MyErrorExit("WriteConsoleOutputAttribute");

The same character or color attribute can be written to a specified number of consecutive screen buffer cells beginning at a specified location. The following example uses the FillConsoleOutputCharacter function to clear a 80-by-50-character screen buffer, and then it uses the FillConsoleOutputAttribute function to set the color attributes of the same cells.

/* Fill an 80-by-50-character screen buffer with the space character. */

    coord.X = 0;            /* start at first cell */

    coord.Y = 0;            /*   of first row      */

    chFillChar = ' ';

    fSuccess = FillConsoleOutputCharacter(

        hStdout,          /* screen buffer handle     */

        chFillChar,       /* fill with spaces         */

        80*50,            /* number of cells to fill  */

        coord,            /* first cell to write to   */

        &cWritten);       /* actual number written to */

    if (! fSuccess)

        MyErrorExit("FillConsoleOutputCharacter");

/* Set 80-by-50-character screen buffer colors to white text on red. */

    wColor = BACKGROUND_RED |

             FOREGROUND_RED |

             FOREGROUND_GREEN |

             FOREGROUND_BLUE;

    fSuccess = FillConsoleOutputAttribute(

        hStdout,          /* screen buffer handle     */

        wColor,           /* color to fill with       */

        80*50,            /* number of cells to fill  */

        coord,            /* first cell to write to   */

        &cWritten);       /* actual number written to */

    if (! fSuccess)

        MyErrorExit("FillConsoleOutputAttribute");


 Reading and Writing Blocks of Characters and Attributes

The ReadConsoleOutput function copies a rectangular block of character and color attribute data from a console screen buffer into a destination buffer. The function treats the destination buffer as a two-dimensional array of CHAR_INFO structures. Similarly, the WriteConsoleOutput function copies a rectangular block of character and color attribute data from a source buffer to a console screen buffer. For more information about reading from or writing to rectangular blocks of screen buffer cells, see Input and Output Methods.

The following example uses the CreateConsoleScreenBuffer function to create a new screen buffer. After the SetConsoleActiveScreenBuffer function makes this the active screen buffer, a block of characters and color attributes is copied from the top two rows of the SDTOUT screen buffer into a temporary buffer. The data is then copied from the temporary buffer into the new active screen buffer. When the application is finished using the new screen buffer, it calls SetConsoleActiveScreenBuffer to restore the original STDOUT screen buffer.

#include <windows.h>

VOID main(void) {

    HANDLE hStdout, hNewScreenBuffer;

    SMALL_RECT srctReadRect;

    SMALL_RECT srctWriteRect;

    CHAR_INFO chiBuffer[160]; // [2][80];

    COORD coordBufSize;

    COORD coordBufCoord;

    BOOL fSuccess;

    /*

     * Get a handle of the STDOUT screen buffer to copy from and

     * create a new screen buffer to copy to.

     */

    hStdout = GetStdHandle(STD_OUTPUT_HANDLE);

    hNewScreenBuffer = CreateConsoleScreenBuffer(

       GENERIC_READ |           /* read-write access      */

       GENERIC_WRITE,

       0,                       /* not shared             */

       NULL,                    /* no security attributes */

       CONSOLE_TEXTMODE_BUFFER, /* must be TEXTMODE       */

       NULL);                   /* reserved; must be NULL */

    if (hStdout == INVALID_HANDLE_VALUE ||

            hNewScreenBuffer == INVALID_HANDLE_VALUE)

        MyErrorExit("CreateConsoleScreenBuffer");

    /* Make the new screen buffer the active screen buffer. */

    if (! SetConsoleActiveScreenBuffer(hNewScreenBuffer) )

        MyErrorExit("SetConsoleActiveScreenBuffer");

    /* Set the source rectangle. */

    srctReadRect.Top = 0;    /* top left: row 0, col 0  */

    srctReadRect.Left = 0;

    srctReadRect.Bottom = 1; /* bot. right: row 1, col 79 */

    srctReadRect.Right = 79;

    /* The temporary buffer size is 2 rows x 80 columns. */

    coordBufSize.Y = 2;

    coordBufSize.X = 80;

    /*

     * The top left destination cell of the temporary buffer is

     * row 0, col 0.

     */

    coordBufCoord.X = 0;

    coordBufCoord.Y = 0;

    /* Copy the block from the screen buffer to the temp. buffer. */

    fSuccess = ReadConsoleOutput(

       hStdout,        /* screen buffer to read from       */

       chiBuffer,      /* buffer to copy into              */

       coordBufSize,   /* col-row size of chiBuffer        */

       coordBufCoord,  /* top left dest. cell in chiBuffer */

       &srctReadRect); /* screen buffer source rectangle   */

    if (! fSuccess)

        MyErrorExit("ReadConsoleOutput");

    /* Set the destination rectangle. */

    srctWriteRect.Top = 10;    /* top lt: row 10, col 0 */

    srctWriteRect.Left = 0;

    srctWriteRect.Bottom = 11; /* bot. rt: row 11, col 79 */

    srctWriteRect.Right = 79;

    /* Copy from the temporary buffer to the new screen buffer. */

    fSuccess = WriteConsoleOutput(

        hNewScreenBuffer, /* screen buffer to write to    */

        chiBuffer,        /* buffer to copy from          */

        coordBufSize,     /* col-row size of chiBuffer    */

        coordBufCoord, /* top left src cell in chiBuffer  */

        &srctWriteRect); /* dest. screen buffer rectangle */

    if (! fSuccess)

        MyErrorExit("WriteConsoleOutput");

    Sleep(10000);

    /* Restore the original active screen buffer. */

    if (! SetConsoleActiveScreenBuffer(hStdout))

        MyErrorExit("SetConsoleActiveScreenBuffer");

}


 Reading Input Buffer Events

The ReadConsoleInput function can be used to directly access a console's input buffer. When a console is created, mouse input is enabled and window input is disabled. To ensure that the process receives all types of events, this example uses the SetConsoleMode function to enable window and mouse input. Then it goes into a loop that reads and handles console input events.

VOID MouseEventProc(MOUSE_EVENT_RECORD);

VOID ResizeEventProc(WINDOW_BUFFER_SIZE_RECORD);

VOID KeyEventProc(KEY_EVENT_RECORD);

VOID GetInputEvents(VOID);

DWORD main(VOID) {

    HANDLE hStdin;

    DWORD cNumRead, fdwMode, fdwSaveOldMode, i;

    INPUT_RECORD irInBuf[128];

    /* Get the standard input handle. */

    hStdin = GetStdHandle(STD_INPUT_HANDLE);

    if (hStdin == INVALID_HANDLE_VALUE)

        MyErrorExit("GetStdHandle");

    /* Save the current input mode, to be restored on exit. */

    if (! GetConsoleMode(hStdin, &fdwSaveOldMode) )

        MyErrorExit("GetConsoleMode");

    /* Enable the window and mouse input events. */

    fdwMode = ENABLE_WINDOW_INPUT | ENABLE_MOUSE_INPUT;

    if (! SetConsoleMode(hStdin, fdwMode) )

        MyErrorExit("SetConsoleMode");

    /* Loop to read and handle the input events. */

    while (1) {

        /* Wait for the events. */

        if (! ReadConsoleInput(

                hStdin,      /* input buffer handle    */

                irInBuf,     /* buffer to read into    */

                128,         /* size of read buffer    */

                &cNumRead) ) /* number of records read */

            MyErrorExit("ReadConsoleInput");

        /* Dispatch the events to the appropriate handler. */

        for (i = 0; i < cNumRead; i++)

            switch(irInBuf[i].EventType) {

                case KEY_EVENT: /* keyboard input */

                    KeyEventProc(irInBuf[i].Event.KeyEvent);

                    break;

                case MOUSE_EVENT: /* mouse input */

                    MouseEventProc(irInBuf[i].Event.MouseEvent);

                    break;

                case WINDOW_BUFFER_SIZE_EVENT: /* scrn buf. resizing */

                    ResizeEventProc(

                        irInBuf[i].Event.WindowBufferSizeEvent);

                    break;

                case FOCUS_EVENT:  /* disregard focus events */

                case MENU_EVENT:   /* disregard menu events  */

                    break;

                default:

                    MyErrorExit("unknown event type");

                    break;

            }

    }

    return 0;

}


 Scrolling a Screen Buffer's Window

The SetConsoleWindowInfo function can be used to scroll the contents of a screen buffer in the console window. This function can also change the window size. The function can either specify the new upper left and lower right corners of the screen buffer's window as absolute screen buffer coordinates or specify the changes from the current window coordinates. The function fails if the specified window coordinates are outside the boundaries of the screen buffer.

The following example scrolls the view of the screen buffer up one row by modifying the absolute window coordinates returned by the GetConsoleScreenBufferInfo function.

HANDLE hStdout;

CONSOLE_SCREEN_BUFFER_INFO csbiInfo;

SMALL_RECT srctWindow;

hStdout = GetStdHandle(STD_OUTPUT_HANDLE);

/* Get the current screen buffer size and window position. */

if (! GetConsoleScreenBufferInfo(hStdout, &csbiInfo))

    MyErrorExit("GetConsoleScreenBufferInfo");

/* Set srctWindow to the current window size and location. */

srctWindow = csbiInfo.srWindow;

/* If window is not at the screen buffer top, move it up one line. */

if ( srctWindow.Top > 0 ) {

    srctWindow.Top -= 1;      /* move top up by one row    */

    srctWindow.Bottom -= 1;   /* move bottom up by one row */

    if (! SetConsoleWindowInfo(

               hStdout,      /* screen buffer handle       */

               TRUE,         /* absolute coordinates       */

               &srctWindow)) /* specifies new location     */

        MyErrorExit("SetConsoleWindowInfo");

}

The same scrolling can be done by specifying changes in the window coordinates.

/* Get the current screen buffer window position. */

if (! GetConsoleScreenBufferInfo(hStdout, &csbiInfo))

    MyErrorExit("GetConsoleScreenBufferInfo");

/*If window is not at the screen buffer top, move it up one line. */

if (csbiInfo.srWindow.Top > 0) {

    srctWindow.Top = -1;      /* move top up by one row    */

    srctWindow.Bottom = -1;   /* move bottom up by one row */

    srctWindow.Left = 0;      /* no change                 */

    srctWindow.Right = 0;     /* no change                 */

    if (! SetConsoleWindowInfo(

               hStdout,      /* screen buffer handle   */

               FALSE,        /* deltas, not absolute   */

               &srctWindow)) /* specifies new location */

        MyErrorExit("SetConsoleWindowInfo");

}


 Scrolling a Screen Buffer's Contents

The ScrollConsoleScreenBuffer function moves a block of character cells from one part of a screen buffer to another part of the same screen buffer. The function specifies the upper left and lower right cells of the source rectangle to be moved and the destination coordinates of the new location for the upper left cell. The character and color data in the source cells is moved to the new location, and any cells left empty by the move are filled in with a specified character and color. If a clipping rectangle is specified, the cells outside of it are left unchanged.

ScrollConsoleScreenBuffer can be used to delete a line by specifying coordinates of the first cell in the line as the destination coordinates and specifying a scrolling rectangle that includes all the rows below the line.

The following example shows the use of a clipping rectangle to scroll only the bottom 15 rows of the screen buffer. The rows in the specified rectangle are scrolled up one line at a time, and the top row of the block is discarded. The contents of the screen buffer outside the clipping rectangle are left unchanged.

HANDLE hStdout;

BOOL fSuccess;

CONSOLE_SCREEN_BUFFER_INFO csbiInfo;

SMALL_RECT srctScrollRect, srctClipRect;

CHAR_INFO chiFill;

COORD coordDest;

hStdout = GetStdHandle(STD_OUTPUT_HANDLE);

if (hStdout == INVALID_HANDLE_VALUE)

    MyErrorExit("GetStdHandle");

/* Get the screen buffer size. */

fSuccess = GetConsoleScreenBufferInfo(hStdout, &csbiInfo);

if (! fSuccess)

    MyErrorExit("GetConsoleScreenBufferInfo");

/*

 * The scrolling rectangle is the bottom 15 rows of the

 * screen buffer.

 */

srctScrollRect.Top = csbiInfo.dwSize.Y - 16;

srctScrollRect.Bottom = csbiInfo.dwSize.Y - 1;

srctScrollRect.Left = 0;

srctScrollRect.Right = csbiInfo.dwSize.X - 1;

/* The destination for the scroll rectangle is one row up. */

coordDest.X = 0;

coordDest.Y = csbiInfo.dwSize.Y - 17;

/*

 * The clipping rectangle is the same as the scrolling rectangle.

 * The destination row is left unchanged.

 */

srctClipRect = srctScrollRect;

/* Fill the bottom row with green blanks. */

chiFill.Attributes = BACKGROUND_GREEN | FOREGROUND_RED;

chiFill.Char.AsciiChar = ' ';

/* Scroll up one line. */

fSuccess = ScrollConsoleScreenBuffer(

    hStdout,         /* screen buffer handle     */

    &srctScrollRect, /* scrolling rectangle      */

    &srctClipRect,   /* clipping rectangle       */

    coordDest,       /* top left destination cell*/

    &chiFill);       /* fill character and color */


 Registering a Control Handler Function

This section shows an example of the SetConsoleCtrlHandler function that is used to install a control handler.

When a CTRL+C signal is received, the control handler returns TRUE, indicating that it has handled the signal. Doing this prevents other control handlers from being called.

When a CTRL_CLOSE_EVENT signal is received, the control handler returns TRUE, causing the system to display a dialog box that gives the user the choice of terminating the process and closing the console or allowing the process to continue execution. If the user chooses not to terminate the process, the system closes the console when the process finally terminates.

When a CTRL+BREAK, CTRL_LOGOFF_EVENT, or CTRL_SHUTDOWN_EVENT signal is received, the control handler returns FALSE. Doing this causes the signal to be passed to the next control handler function. If no other control handlers have been registered or none of the registered handlers returns TRUE, the default handler will be used, resulting in the process being terminated.

BOOL CtrlHandler(DWORD fdwCtrlType) {

    switch (fdwCtrlType) {

        /* Handle the CTRL+C signal. */

        case CTRL_C_EVENT:

            Beep(1000, 1000);

            return TRUE;

        /* CTRL+CLOSE: confirm that the user wants to exit. */

        case CTRL_CLOSE_EVENT:

            return TRUE;

        /* Pass other signals to the next handler. */

        case CTRL_BREAK_EVENT:

        case CTRL_LOGOFF_EVENT:

        case CTRL_SHUTDOWN_EVENT:

        default:

            return FALSE;

    }

}

VOID main(void) {

BOOL fSuccess;

fSuccess = SetConsoleCtrlHandler(

    (PHANDLER_ROUTINE) CtrlHandler,  /* handler function */

    TRUE);                           /* add to list      */

if (! fSuccess)

    MyErrorExit("Could not set control handler");


 Console Application Issues

The 8-bit console functions use the OEM code page. All other functions use the ANSI code page by default. This means that strings returned by the console functions may not be processed correctly by the other functions and vice versa. For example, if FindFirstFileA returns a string that contains certain extended ANSI characters, WriteConsoleA will not display the string properly.

The best long-term solution for a console application is to use Unicode. Barring that solution, a console application should use the SetFileApisToOEM function. That function changes relevant Win32 file functions so that they produce OEM character set strings rather than ANSI character set strings.

Following are the Win32 file functions:

_lopen	GetDriveType	LoadLibrary
CopyFile	GetFileAttributes	LoadLibraryEx
CreateDirectory	GetFullPathName	MoveFile
CreateFile	GetModuleFileName	MoveFileEx
CreateProcess	GetModuleHandle	OpenFile
DeleteFile	GetSystemDirectory	RemoveDirectory
FindFirstFile	GetTempFileName	SearchPath
FindNextFile	GetTempPath	SetCurrentDirectory
GetCurrentDirectory	GetVolumeInformation	SetFileAttributes
GetDiskFreeSpace	GetWindowsDirectory
When dealing with command lines, a console application should obtain the command line in Unicode form and convert it to OEM form, using the relevant  character-to-OEM functions. Note, also, that argv uses the ANSI character set.


 Console Reference

The following functions and structures are associated with accessing a console.


 Console Functions

Following are the functions used to access a console.

AllocConsole
CreateConsoleScreenBuffer
FillConsoleOutputAttribute
FillConsoleOutputCharacter
FlushConsoleInputBuffer
FreeConsole
GenerateConsoleCtrlEvent
GetConsoleCP
GetConsoleCursorInfo
GetConsoleMode
GetConsoleOutputCP
GetConsoleScreenBufferInfo
GetConsoleTitle
GetLargestConsoleWindowSize
GetNumberOfConsoleInputEvents
GetNumberOfConsoleMouseButtons
GetStdHandle
HandlerRoutine
PeekConsoleInput
ReadConsole
ReadConsoleInput
ReadConsoleOutput
ReadConsoleOutputAttribute
ReadConsoleOutputCharacter
ScrollConsoleScreenBuffer
SetConsoleActiveScreenBuffer
SetConsoleCP
SetConsoleCtrlHandler
SetConsoleCursorInfo
SetConsoleCursorPosition
SetConsoleMode
SetConsoleOutputCP
SetConsoleScreenBufferSize
SetConsoleTextAttribute
SetConsoleTitle
SetConsoleWindowInfo
SetStdHandle
WriteConsole
WriteConsoleInput
WriteConsoleOutput
WriteConsoleOutputAttribute
WriteConsoleOutputCharacter


 Console Structures

Following are the structures used to access a console.

CHAR_INFO
CONSOLE_CURSOR_INFO
CONSOLE_SCREEN_BUFFER_INFO
FOCUS_EVENT_RECORD
INPUT_RECORD
MENU_EVENT_RECORD
WINDOW_BUFFER_SIZE_RECORD


 Data Decompression Library

This overview describes important concepts relating to data compression and describes the decompression functions in LZEXPAND.DLL.


 About the Data Decompression Library

The Microsoft® Windows® operating system includes a dynamic-link library (DLL) named LZEXPAND.DLL. Typically, an application calls functions in LZEXPAND.DLL to decompress data previously compressed by using the Microsoft File Compression Utility (COMPRESS.EXE).


 Data Compression

Data compression is an operation that reduces the size of a file by minimizing redundant data. In a file that contains text, redundant data can be frequently occurring characters, such as the space character, or common vowels, such as the letters e and a; it can also be frequently occurring character strings. Data compression creates a compressed version of a file by minimizing this redundant data.

Each type of data-compression algorithm minimizes redundant data in a unique manner. For example, the Huffman encoding algorithm assigns a code to characters in a file based on how frequently those characters occur. Another compression algorithm, called run-length encoding, generates a two-part value for repeated characters: the first part specifies the number of times the character is repeated, and the second part identifies the character. Another compression algorithm, known as the Lempel-Ziv algorithm, converts variable-length strings into fixed-length codes that consume less space than the original strings.

To compress large applications or data files, you can run COMPRESS.EXE from the command line. COMPRESS.EXE uses the Lempel-Ziv compression algorithm.


 Data Decompression

Applications can call the functions in LZEXPAND.DLL to decompress files compressed by using COMPRESS.EXE. The functions can also process uncompressed files without attempting to decompress them. To use these functions, applications must include the LZEXPAND.H header file.

The following table describes each function found in LZEXPAND.DLL.

Function	Purpose
CopyLZFile	This function is obsolete. It is provided to simplify porting of 16-bit Windows-based applications. Win32-based applications should use the LZCopy function.
GetExpandedName	Retrieves the original name of a compressed file, if the /r option was used during compression of the file.
LZClose	Closes a file that was opened when the application called the LZOpenFile function.
LZCopy	Copies a source file to a destination file. If the source file is compressed, this function creates a decompressed destination file. If the source file is not compressed, this function duplicates the original file. This function is intended for single-file copy operations.
LZDone	This function is obsolete and should not be used in Win32-based applications. It is provided to simplify porting of 16-bit Windows-based applications.
LZInit	Creates structures used for decompressing files.
LZOpenFile	Opens a file and returns a handle that identifies it.
LZRead	Reads a specified number of bytes from a file. If the file is compressed, this function decompresses the bytes before copying them to the destination buffer.
LZSeek	Positions the file pointer within the decompressed image of a compressed file. The application calls this function to position the pointer before calling the LZRead function.
LZStart	This function is obsolete and should not be used in Win32-based applications. It is provided to simplify porting of 16-bit Windows-based applications.


 Using the Data Decompression Library

Functions in LZEXPAND.DLL can be used to decompress single or multiple files. They can also be used to decompress compressed files a portion at a time.

•	Decompressing a single file

•	Decompressing multiple files

•	Reading bytes from compressed files


 Decompressing a Single File

An application can decompress a single compressed file by performing the following tasks.

1.	Open the source file by calling the LZOpenFile function.

2.	Open the destination file by calling LZOpenFile.

3.	Copy the source file to the destination file by calling the LZCopy function and passing the handles returned by LZOpenFile.

4.	Close the files by calling the LZClose function.


 Decompressing Multiple Files

An application can decompress multiple files by performing the following tasks.

1.	Open the source files by calling the LZOpenFile function.

2.	Open the destination files by calling LZOpenFile.

3.	Copy the source files to the destination files by calling the LZCopy function.

4.	Close the files by calling the LZClose function.


 Reading Bytes from Compressed Files

In addition to decompressing a complete file in a single operation, an application can decompress a compressed file a portion at a time by using the LZSeek and LZRead functions. These functions are particularly useful when it is necessary to extract parts of large files. For example, a font manufacturer may have compressed files containing font metrics in addition to character data. To use the information in these files, an application would need to decompress the file; however, most applications would use only part of the file at any particular time. To get information about font metrics, the application would extract data from the header. To get information from the text, the application would reposition the file pointer by calling LZSeek and extract character data by calling LZRead.


 Data Decompression Library Functions

Following are the functions used to decompress files.

GetExpandedName
LZClose
LZCopy
LZInit
LZOpenFile
LZRead
LZSeek

Obsolete or Deleted Functions

CopyLZFile
LZDone
LZStart


 Debugging

A debugger is an application that enables a developer to observe and correct programming errors.

The first section of this overview describes the debugging-specific features of certain standard Windows functions — specifically, process, thread, and exception-handling functions.

The second section of this overview describes the Windows debugging functions. These functions enable an application to wait for debugging events, cause breakpoint exceptions, transfer execution control to the debugger, and so on.


 About Debugging Support

Microsoft® Windows® supports several functions that can be used to create a basic, event-driven debugger. "Event-driven" means that the debugger is notified every time certain events occur in the process being debugged. Notification enables the debugger to take appropriate action in response to the events.


 Support from Process, Thread, and Exception Functions

Some functions essential to debugging are actually part of the process, thread, or exception-handling architectures. This section describes how to start a process that is going to be debugged and how to examine and manipulate the context and execution of a thread. It also describes how a debugger should handle exceptions.


 Process Functions

The CreateProcess function enables a debugger to start a process and debug it. The fdwCreate parameter of CreateProcess is used to specify the type of debugging operation. If the DEBUG_PROCESS flag is specified for the parameter, a debugger debugs the new process and all of the process's descendants, provided that the descendants are created without the DEBUG_PROCESS flag.

If the DEBUG_PROCESS and DEBUG_ONLY_THIS_PROCESS flags are specified for fdwCreate, a debugger debugs the new process but none of its descendants.

One debugger can debug another by creating a process with the DEBUG_PROCESS flag. The new process (the debugger being debugged) must then create a process with the DEBUG_PROCESS flag.

The OpenProcess function enables a debugger to obtain the identifier of an existing process. (The DebugActiveProcess function uses this identifier to attach the debugger to the process.) Typically, debuggers open a process with the PROCESS_VM_READ and PROCESS_VM_WRITE flags. Using these flags enables the debugger to read from and write to the virtual memory of the process by using the ReadProcessMemory and WriteProcessMemory functions. For more information about processes, see Processes and Threads.


 Thread Functions

The CreateThread function creates a new thread for a process. Debuggers typically need to examine or change the contents of a thread's registers. To accomplish this, a debugger must obtain a handle of the thread by using the DuplicateHandle function and specifying the appropriate access to the thread (THREAD_GET_CONTEXT, THREAD_SET_CONTEXT, or both).

A process with appropriate access to a thread can examine the thread's registers by using the GetThreadContext function and set the contents of the thread's registers by using the SetThreadContext function.

A process can also obtain THREAD_SUSPEND_RESUME access to a thread. This type of access enables a debugger to control a thread's execution with the SuspendThread and ResumeThread functions. For more information about threads, see Processes and Threads.


 Exception Handling for Debugging

When an exception occurs in a process that is being debugged, the kernel notifies the debugger by passing the exception to it. This is known as first-chance notification. The kernel then suspends all threads in the process being debugged.

If the debugger does not handle the exception, the kernel attempts to locate an appropriate exception handler. If the kernel cannot locate an appropriate one, the kernel again notifies the debugger that an exception has occurred. This is known as last-chance notification. If the debugger does not handle the exception after the last-chance notification, the kernel terminates the process being debugged.

For more information about exception handling, see Structured Exception Handling.


 Debugging Functions

Although most of the Windows debugging functions are used to create a debugger, several functions are designed for use in the process being debugged.

To start a process and debug it, a debugger must use CreateProcess, as described in the previous section.

To debug a process that is already executing, the debugger should use DebugActiveProcess with the process identifier retrieved by OpenProcess. DebugActiveProcess attaches the debugger to the active process. In this case, only the active process can be debugged; its descendants cannot. The debugger must have appropriate access to the executing process to use DebugActiveProcess. For more information about access rights, see Security.

After the debugger has either created or attached itself to the process it intends to debug, the kernel notifies the debugger of all debugging events that occur in the process, and, if specified, in the process's descendants. For more information about debugging events, see Debugging Events.

The debugger uses the WaitForDebugEvent function at the beginning of its main loop. This function blocks the debugger until a debugging event occurs. When the debugging event occurs, the kernel suspends all threads in the process being debugged and notifies the debugger of the event. The debugger can interact with the user, or manipulate the state of the process being debugged, by using the FlushInstructionCache, GetThreadContext, GetThreadSelectorEntry, ReadProcessMemory, SetThreadContext, and WriteProcessMemory functions.

GetThreadSelectorEntry returns the descriptor table entry for a specified selector and thread. Debuggers use the descriptor table entry to convert a segment-relative address to a linear virtual address. The ReadProcessMemory and WriteProcessMemory functions require linear virtual addresses.

Debuggers frequently read the memory of the process being debugged and write the memory that contains instructions to the instruction cache. After the instructions are written, the debugger calls FlushInstructionCache to execute the cached instructions.

The debugger uses the ContinueDebugEvent function at the end of its main loop. This function allows the process being debugged to continue executing.


 Communicating with the Debugger

The OutputDebugString function sends a string from the process being debugged to the debugger by generating an OUTPUT_DEBUG_STRING_EVENT debugging event.

The DebugBreak function causes a breakpoint exception in the current process. A breakpoint is a location in a program where execution is stopped to allow the developer to examine the program's code, variables, and register values and, as necessary, to make changes, continue execution, or terminate execution.

The FatalExit function terminates the current process and gives execution control to the debugger, but unlike DebugBreak, it does not generate an exception. This function should only be used as a last resort, because it does not always free the process's memory or close its files.


 Debugging Events

A debugging event is an incident in the process being debugged that causes the kernel to notify the debugger. Debugging events include creating a process, creating a thread, loading a dynamic-link library (DLL), unloading a DLL, sending an output string, and generating an exception.

If a debugging event occurs while a debugger is waiting for one, the kernel fills the DEBUG_EVENT structure specified by WaitForDebugEvent with information describing the event.

When the kernel notifies the debugger of a debugging event, it also suspends all threads in the affected process. The threads do not resume execution until the debugger continues the debugging event by using ContinueDebugEvent. The following debugging events may occur while a process is being debugged.

Debugging event	Description
CREATE_PROCESS_DEBUG_EVENT
	Generated whenever a new process is created in a process being debugged or whenever the debugger begins debugging an already active process. The kernel generates this debugging event before the process begins to execute in user mode and before the kernel generates any other debugging events for the new process.
	The DEBUG_EVENT structure contains a CREATE_PROCESS_DEBUG_INFO structure. This structure includes a handle of the new process, a handle of the process's image file, a handle of the process's initial thread, and other information that describes the new process.
	The handle of the process has PROCESS_VM_READ and PROCESS_VM_WRITE access. If a debugger has these types of access to a thread, it can read and write to the process's memory by using the ReadProcessMemory and WriteProcessMemory functions.
	The handle of the process's image file has GENERIC_READ access and is opened for read-sharing.
	The handle of the process's initial thread has THREAD_GET_CONTEXT, THREAD_SET_CONTEXT, and THREAD_SUSPEND_RESUME access to the thread. If a debugger has these types of access to a thread, it can read from and write to the thread's registers by using the GetThreadContext and SetThreadContext functions and can suspend and resume the thread by using the SuspendThread and ResumeThread functions.
CREATE_THREAD_DEBUG_EVENT
	Generated whenever a new thread is created in a process being debugged or whenever the debugger begins debugging an already active process. This debugging event is generated before the new thread begins to execute in user mode.
	The DEBUG_EVENT structure contains a CREATE_THREAD_DEBUG_INFO structure. This structure includes a handle of the new thread and the thread's starting address. The handle has THREAD_GET_CONTEXT, THREAD_SET_CONTEXT, and THREAD_SUSPEND_RESUME access to the thread. If a debugger has these types of access to a thread, it can read from and write to the thread's registers by using the GetThreadContext and SetThreadContext functions and can suspend and resume the thread by using the SuspendThread and ResumeThread functions.
EXCEPTION_DEBUG_EVENT
	Generated whenever an exception occurs in the process being debugged. Possible exceptions include attempting to access inaccessible memory, executing breakpoint instructions, attempting to divide by zero, or any other exception noted in Structured Exception Handling.
	The DEBUG_EVENT structure contains an EXCEPTION_DEBUG_INFO structure. This structure describes the exception that caused the debugging event.
	Besides the standard exception conditions, an additional exception code can occur during console process debugging. The kernel generates a DBG_CONTROL_C exception code when CTRL+C is input to a console process that handles CTRL+C signals and is being debugged. This exception code is not meant to be handled by applications. An application should never use an exception handler to deal with it. It is raised only for the benefit of the debugger and is only used when a debugger is attached to the console process.
	If a process is not being debugged or if the debugger passes on the DBG_CONTROL_C exception unhandled (through the gn command), the application's list of handler functions is searched, as documented for the SetConsoleCtrlHandler function.
	If the debugger handles the DBG_CONTROL_C exception (through the gh command), an application will not notice the CTRL+C except in code like this.
	while ((inputChar = getchar()) != EOF) ... while (gets(inputString)) ...
	Thus, the debugger cannot be used to stop the read wait in such code from terminating.
EXIT_PROCESS_DEBUG_EVENT
	Generated whenever the last thread in a process being debugged exits. This debugging event occurs immediately after the kernel unloads the process's DLLs and updates the process's exit code.
	The DEBUG_EVENT structure contains an EXIT_PROCESS_DEBUG_INFO structure that specifies the exit code.
	The debugger deallocates any internal structures associated with the process on receipt of this debugging event. The kernel closes the debugger's handle of the exiting process and all of the process's threads.
EXIT_THREAD_DEBUG_EVENT
	Generated whenever a thread that is part of a process being debugged exits. The kernel generates this debugging event immediately after it updates the thread's exit code.
	The DEBUG_EVENT structure contains an EXIT_THREAD_DEBUG_INFO structure that specifies the exit code.
	The debugger deallocates any internal structures associated with the thread on receipt of this debugging event. The system closes the debugger's handle of the exiting thread.
	This debugging event does not occur if the exiting thread is the last thread of a process. In this case, the EXIT_PROCESS_DEBUG_EVENT debugging event occurs instead.
LOAD_DLL_DEBUG_EVENT
	Generated whenever a process being debugged loads a DLL. This debugging event occurs when the system loader resolves links to a DLL or when the debugged process uses the LoadLibrary function. This debugging event only occurs the first time the kernel attaches a DLL to the virtual address space of a process.
	The DEBUG_EVENT structure contains a LOAD_DLL_DEBUG_INFO structure. This structure includes a handle of the newly loaded DLL, the base address of the DLL, and other information that describes the DLL.
	Typically, a debugger loads a symbol table associated with the DLL on receipt of this debugging event.
OUTPUT_DEBUG_STRING_EVENT
	Generated when a process being debugged uses the OutputDebugString function.
	The DEBUG_EVENT structure contains an OUTPUT_DEBUG_STRING_INFO structure. This structure specifies the address, length, and format of the debugging string.
UNLOAD_DLL_DEBUG_EVENT
	Generated whenever a process being debugged unloads a DLL by using the FreeLibrary function. This debugging event only occurs the last time a DLL is unloaded from a process's address space (that is, when the DLL's usage count is zero).
	The DEBUG_EVENT structure contains an UNLOAD_DLL_DEBUG_INFO structure. This structure specifies the base address of the DLL in the address space of the process that unloads the DLL.
	Typically, a debugger unloads a symbol table associated with the DLL upon receiving this debugging event.
	When a process exits, the kernel automatically unloads the process's DLLs, but does not generate an UNLOAD_DLL_DEBUG_EVENT debugging event.


 Using Debugging Support

The following example uses the WaitForDebugEvent and ContinueDebugEvent functions to illustrate how a simple debugger might be organized.

DEBUG_EVENT DebugEv;                   /* debugging event info.  */

DWORD dwContinueStatus = DBG_CONTINUE; /* exception continuation */

for(;;) {

 /*

  * Wait for a debugging event to occur. The second parameter

  * indicates that the function does not return until

  * a debugging event occurs.

  */

WaitForDebugEvent(&DebugEv, INFINITE);

  /* Process the debugging event code. */

  switch (DebugEv.dwDebugEventCode) {

    case EXCEPTION_DEBUG_EVENT:

      /*

       * Process the exception code. When handling

       * exceptions, remember to set the continuation

       * status parameter (dwContinueStatus). This value

       * is used by the ContinueDebugEvent function.

       */

      switch (DebugEv.u.Exception.ExceptionRecord.ExceptionCode) {

          case EXCEPTION_ACCESS_VIOLATION:

                 /*

                  * First chance: Pass this on to the kernel.

                  * Last chance: Display an appropriate error.

                  */

          case EXCEPTION_BREAKPOINT:

                 /*

                  * First chance: Display the current

                  * instruction and register values.

                  */

          case EXCEPTION_DATATYPE_MISALIGNMENT:

                 /*

                  * First chance: Pass this on to the kernel.

                  * Last chance: Display an appropriate error.

                  */

          case EXCEPTION_SINGLE_STEP:

                 /*

                  * First chance: Update the display of the

                  * current instruction and register values.

                  */

          case DBG_CONTROL_C:

                 /*

                  * First chance: Pass this on to the kernel.

                  * Last chance: Display an appropriate error.

                  */

          /* Handle other exceptions. */

      }

    case CREATE_THREAD_DEBUG_EVENT:

           /*

            * As needed, examine or change the thread's registers

            * with the GetThreadContext and SetThreadContext functions;

            * and suspend and resume thread execution with the

            * SuspendThread and ResumeThread functions.

            */

    case CREATE_PROCESS_DEBUG_EVENT:

           /*

            * As needed, examine or change the registers of the

            * process's initial thread with the GetThreadContext and

            * SetThreadContext functions; read from and write to the

            * process's virtual memory with the ReadProcessMemory and

            * WriteProcessMemory functions; and suspend and resume

            * thread execution with the SuspendThread and ResumeThread

            * functions.

            */

    case EXIT_THREAD_DEBUG_EVENT:

           /* Display the thread's exit code. */

    case EXIT_PROCESS_DEBUG_EVENT:

           /* Display the process's exit code. */

    case LOAD_DLL_DEBUG_EVENT:

           /*

            * Read the debugging information included

            * in the newly loaded DLL.

            */

    case UNLOAD_DLL_DEBUG_EVENT:

           /*

            * Display a message that the DLL has

            * been unloaded.

            */

    case OUTPUT_DEBUG_STRING_EVENT:

           /* Display the output debugging string. */

  }

/* Resume executing the thread that reported the debugging event. */

ContinueDebugEvent(DebugEv.dwProcessId,

    DebugEv.dwThreadId, dwContinueStatus);

}


 Debugging Functions

Following are the functions that support debugging:

ContinueDebugEvent
DebugActiveProcess
DebugBreak
FatalAppExit
FatalExit
FlushInstructionCache
GetThreadContext
GetThreadSelectorEntry
OutputDebugString
ReadProcessMemory
SetDebugErrorLevel
SetThreadContext
WaitForDebugEvent
WriteProcessMemory


 Device Input and Output

Applications use a device input and output control to communicate with a device driver. This overview discusses device handles, which identify the device being accessed, and device control codes, which specify the action the driver is to perform.


 About Device Input and Output

The DeviceIoControl function provides a device input and output control (IOCTL) interface through which an application can communicate directly with a device driver. The DeviceIoControl function is a general-purpose interface that can send control codes to a variety of devices.


 Device Handles

A DeviceIoControl call specifies a handle of a device driver to identify the device being accessed. You can use the CreateFile function to get a device driver handle.

The CreateFile call must specify either the name of a device or the name of the driver associated with a device. To specify a device name, the lpszname parameter of CreateFile specifies a string with the format

\\.\DeviceName

The types of devices that you can open and the method that you must use to specify them in the CreateFile function depend on the Win32 platform on which your application is running.

On Windows NT, DeviceIoControl can open a handle of a specific device. For example, to open a handle to the logical drive A:, specify "\\\\.\\a:". Alternatively, you can use the names "\\\\.\\PhysicalDrive0", "\\\\.\\PhysicalDrive1", and so on, to open handles to the physical drives on a system.

For Win32-based applications running on Windows 95, DeviceIoControl must specify a handle of a virtual device driver. For example, to open a handle to the system VxD, specify "\\\\.\\vwin32".

The CreateFile call should specify the FILE_SHARE_READ and FILE_SHARE_WRITE access flags when opening a handle to a device driver. However, when opening a communications resource, such as a serial port, CreateFile must specify exclusive access. Other CreateFile parameters are used as follows when opening a device handle:

•	The fdwCreate parameter must specify the OPEN_EXISTING flag.

•	The hTemplateFile parameter must be NULL.

•	The fdwAttrsAndFlags parameter can specify FILE_FLAG_OVERLAPPED to indicate that the returned handle can be used in overlapped (asynchronous) I/O operations.


 Device Control Codes

An application can use the DeviceIoControl function to send a control code to a device driver. The control code specifies the action that the driver is to perform. For example, a control code can ask a device driver to return information about the corresponding device, or direct the driver to carry out an action on the device, such as formatting a disk.

A number of standard control codes are defined in the Win32 header files. For a list of standard control codes, see  DeviceIoControl . In addition, device drivers can define their own device-specific control codes. The types of control codes you can specify depend on the device being accessed and the Win32 platform on which your application is running.

Applications running on Windows NT can use the standard control codes or device-specific control codes to perform direct input and output operations on a floppy disk drive, hard disk drive, tape drive, or CD-ROM drive.

Win32-based applications running on Windows 95 cannot use the standard control codes in the Win32 header files. These applications are restricted to using the control codes supported by the virtual device driver being accessed. For example, the system VxD, VWIN32.VXD, supports the input and output control (IOCTL) functions originally provided by MS-DOS Interrupt 21h.

The control code specified in a DeviceIoControl call determines the values that must be specified for the other DeviceIoControl parameters. For example, a Windows NT application can specify the IOCTL_DISK_FORMAT_TRACKS control code. In this case, the lpvInBuffer parameter must point to a filled-in FORMAT_PARAMETERS structure, and the cbInBuffer parameter must specify the size of the structure.


 Using Device Input and Output Control

•	Calling DeviceIoControl on Windows NT

•	Calling DeviceIoControl on Windows 95


 Calling DeviceIoControl on Windows NT

On Windows NT, an application can use the DeviceIoControl function to perform direct input and output operations on, or retrieve information about, a floppy disk drive, hard disk drive, tape drive, or CD-ROM drive. The following example demonstrates how to retrieve information about the first physical drive in the system. It uses the CreateFile function to obtain the device handle of the first physical drive, and then uses the DeviceIoControl function with the IOCTL_DISK_GET_DRIVE_GEOMETRY control code to fill a DISK_GEOMETRY structure with information about the drive.

BOOL GetDriveGeometry(DISK_GEOMETRY *pdg)

{

    HANDLE hDevice;

    BOOL fResult;

    DWORD cb;

    hDevice = CreateFile("\\\\.\\PhysicalDrive0",

        0, FILE_SHARE_READ | FILE_SHARE_WRITE,

        NULL, OPEN_EXISTING, 0, NULL);

    if (hDevice == NULL)

        return FALSE;

    fResult = DeviceIoControl(hDevice,

        IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0,

        pdg, sizeof(*pdg), &cb, (LPOVERLAPPED) NULL);

    if (!fResult)

        return FALSE;

    CloseHandle(hDevice);

}

This example succeeds only when it runs on Windows NT, for two reasons:

•	The standard device input/output control codes are available only on Windows NT, and

•	On Windows 95, an application must specify a virtual device driver in the CreateFile function — not a specific device.


 Calling DeviceIoControl on Windows 95

A Win32-based application running on Windows 95 can use the DeviceIoControl function to send control codes directly to a virtual device driver (VxD). Any VxD can support any number of control codes, or none at all.

The system VxD, VWIN32.VXD, supports the input and output control (IOCTL) functions originally provided by MS-DOS Interrupt 21h. The following example shows how to call Get Media ID (Interrupt 21h Function 440Dh Minor Code 66h) from a Win32-based application:

"\\\\.\\VxDName"

In Windows 95,

#define VWIN32_DIOC_DOS_IOCTL 1

typedef struct _DEVIOCTL_REGISTERS {

    DWORD reg_EBX;

    DWORD reg_EDX;

    DWORD reg_ECX;

    DWORD reg_EAX;

    DWORD reg_EDI;

    DWORD reg_ESI;

    DWORD reg_Flags;

} DEVIOCTL_REGISTERS, *PDEVIOCTL_REGISTERS;

typedef struct _MID {

    WORD  midInfoLevel;

    DWORD midSerialNum;

    BYTE  midVolLabel[11];

    BYTE  midFileSysType[8];

} MID, *PMID;

BOOL GetMediaID(PMID pmid, UINT nDrive)

{

    DEVIOCTL_REGISTERS reg;

    reg.reg_EAX = 0x440D;       /* IOCTL for block devices */

    reg.reg_EBX = nDrive;       /* zero-based drive ID     */

    reg.reg_ECX = 0x0866;       /* Get Media ID command    */

    reg.reg_EDX = (DWORD) pmid; /* receives media ID info  */

    if (!DoIOCTL(&reg))

        return FALSE;

    if (reg.reg_Flags & 0x8000) /* error if carry flag set */

        return FALSE;

    return TRUE;

}

BOOL DoIOCTL(PDEVIOCTL_REGISTERS preg)

{

    HANDLE hDevice;

    BOOL fResult;

    DWORD cb;

    preg->reg_Flags = 0x8000; /* assume error (carry flag set) */

    hDevice = CreateFile("\\\\.\\vwin32",

        GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,

        (LPSECURITY_ATTRIBUTES) NULL, OPEN_EXISTING,

        FILE_ATTRIBUTE_NORMAL, (HANDLE) NULL);

    if (hDevice == (HANDLE) INVALID_HANDLE_VALUE)

        return FALSE;

    else {

        fResult = DeviceIoControl(hDevice, VWIN32_DIOC_DOS_IOCTL,

            preg, sizeof(*preg), preg, sizeof(*preg), &cb, 0);

        if (!fResult)

            return FALSE;

    }

    CloseHandle(hDevice);

    return TRUE;

}


 Device Input and Output Reference

The following functions, operations, and structures are associated with device input and output.


 Device Input and Output Functions

Use the following function to implement device input and output:

DeviceIoControl


 Device Input and Output Operations

Use the following operations to implement device input and output:

FSCTL_DISMOUNT_VOLUME
FSCTL_LOCK_VOLUME
FSCTL_UNLOCK_VOLUME
IOCTL_DISK_CHECK_VERIFY
IOCTL_DISK_EJECT_MEDIA
IOCTL_DISK_FORMAT_TRACKS
IOCTL_DISK_GET_DRIVE_GEOMETRY
IOCTL_DISK_GET_DRIVE_LAYOUT
IOCTL_DISK_GET_MEDIA_TYPES
IOCTL_DISK_GET_PARTITION_INFO
IOCTL_DISK_LOAD_MEDIA
IOCTL_DISK_MEDIA_REMOVAL
IOCTL_DISK_PERFORMANCE
IOCTL_DISK_REASSIGN_BLOCKS
IOCTL_DISK_SET_DRIVE_LAYOUT
IOCTL_DISK_SET_PARTITION_INFO
IOCTL_DISK_VERIFY
IOCTL_SERIAL_LSRMST_INSERT


 Device Input and Output Structures

Use these structures in device input and output operations:

FORMAT_PARAMETERS
DISK_GEOMETRY
DRIVE_LAYOUT_INFORMATION
PARTITION_INFORMATION
PREVENT_MEDIA_REMOVAL
DISK_PERFORMANCE
REASSIGN_BLOCKS
SET_PARTITION_INFORMATION
VERIFY_INFORMATION


 Dynamic Data Exchange

This overview provides guidelines for implementing dynamic data exchange for applications that cannot use the Dynamic Data Exchange Management Library (DDEML). For more information about the DDEML, see Dynamic Data Exchange Management Library.


 About Dynamic Data Exchange

The Microsoft® Win32® application programming interface (API) provides several methods for transferring data between applications. One method is to use the Win32 dynamic data exchange (DDE) protocol. The DDE protocol is a set of messages and guidelines. It sends messages between applications that share data and uses shared memory to exchange data between applications. Applications can use the DDE protocol for one-time data transfers and for continuous exchanges in which applications send updates to one another as new data becomes available.

The Win32 API also includes the Dynamic Data Exchange Management Library (DDEML). The DDEML is a dynamic-link library (DLL) that applications running with Windows can use to share data. The DDEML provides an application programming interface (API) that simplifies the task of adding DDE capability to a Win32-based application. Instead of sending, posting, and processing DDE messages directly, an application uses the DDEML functions to manage DDE conversations. (A DDE conversation is the interaction between client and server applications.)

The DDEML also provides a facility for managing the strings and data that DDE applications share. Instead of using atoms and pointers to shared memory objects, DDE applications create and exchange string handles, which identify strings, and data handles, which identify memory objects. The DDEML also makes it possible for a server application to register the service names it supports. The names are broadcast to other applications in the system, which can use the names to connect to the server. Moreover, the DDEML ensures compatibility among DDE applications by forcing them to implement the DDE protocol in a consistent manner.

Existing applications that use the message-based DDE protocol are fully compatible with those that use the DDEML. That is, an application that uses message-based DDE can establish conversations and perform transactions with applications that use the DDEML. Because of the many advantages of the DDEML, new applications should use it rather than the DDE messages. To use the API elements of the DDEML, you must include the DDEML header file in your source files, link with the DDEML library, and ensure that the DDEML dynamic-link library is in the system's search path.


 Dynamic Data Exchange Protocol

Because the Win32 API has a message-based architecture, passing messages is the most appropriate method for automatically transferring information between applications. However, Win32 messages contain only two parameters (wParam and lParam) for passing data. As a result, these parameters must refer indirectly to other pieces of data when more than a few words of information pass between applications. The DDE protocol defines exactly how applications should use the wParam and lParam parameters to pass larger pieces of data by means of global atoms and shared memory handles. The DDE protocol has specific rules for allocating and deleting global atoms and shared memory objects.

A global atom is a reference to a character string. In the DDE protocol, atoms identify the applications exchanging data, the nature of the data being exchanged, and the data items themselves. For more information about atoms, see Atoms. A shared memory handle is a handle to a memory object allocated by GlobalAlloc, using the GMEM_DDESHARE flag. In the DDE protocol, shared memory objects store data items passed between applications, protocol options, and remote command execution strings.


 Uses for Windows Dynamic Data Exchange

DDE is most appropriate for data exchanges that do not require ongoing user interaction. Usually, an application provides a method for the user to establish the link between the applications exchanging data. Once that link is established, however, the applications exchange data without further user involvement.

DDE can be used to implement a broad range of application features — for example:

•	Linking to real-time data, such as to stock market updates, scientific instruments, or process control.

•	Creating compound documents, such as a word processing document that includes a chart produced by a graphics application. Using DDE, the chart will change when the source data is changed, while the rest of the document remains the same.

•	Performing data queries between applications, such as a spreadsheet querying a database for accounts past due.


 Dynamic Data Exchange from the User's Point of View

The following example illustrates illustrates how two DDE applications can cooperate, as seen from the user's point of view.

A spreadsheet user wants to use Microsoft® Excel to track the price of a particular stock on the New York Stock Exchange. The user has a Win32-based application called Quote that in turn has access to NYSE data. The DDE conversation between Microsoft Excel and Quote takes place as follows:

•	The user initiates the conversation by supplying the name of the application (Quote) that will supply the data and the particular topic of interest (NYSE). The resulting DDE conversation is used to request quotes on specific stocks.

•	Microsoft Excel broadcasts the application and topic names to all DDE applications currently running in the system. Quote responds, establishing a conversation with Microsoft Excel about the NYSE topic.

•	The user can then create a spreadsheet formula in a cell that requests that the spreadsheet be automatically updated whenever a particular stock quotation changes. For example, the user could request an automatic update whenever a change occurs in the selling price of ZAXX stock by specifying the following Microsoft Excel formula:

='Quote'|'NYSE'!ZAXX

•	The user can terminate the automatic updating of the ZAXX stock quotation at any time. Other data links that were established separately (such as for quotations for other stocks) still will remain active under the same NYSE conversation.

•	The user can also terminate the entire conversation between Microsoft Excel and Quote on the NYSE topic, so that no specific data links on that topic can be established without initiating a new conversation.


 Dynamic Data Exchange Concepts

The following sections explain the important concepts and terminology that are key to understanding dynamic data exchange.


 Client, Server, and Conversation

Two applications participating in dynamic data exchange are said to be engaged in a DDE conversation. The application that initiates the conversation is the DDE client application; the application that responds to the client is the DDE server application. An application can engage in several conversations at the same time, acting as the client in some and as the server in others.

A DDE conversation takes place between two windows, one for each of the participating applications. A window may be the main window of the application; a window associated with a specific document, as in a multiple document interface (MDI) application; or a hidden (invisible) window whose only purpose is to process DDE messages.

Since a DDE conversation is identified by the pair of handles to the windows engaged in the conversation, no window should be engaged in more than one conversation with another window. Either the client application or the server application must provide a different window for each of its conversations with a particular server or client application.

An application can ensure a pair of client and server windows is never involved in more than one conversation by creating a hidden window for each conversation. The sole purpose of this window is to process DDE messages.


 Application, Topic, and Item Names

The DDE protocol identifies the units of data passed between the client and server with a three-level hierarchy of application, topic, and item names.

Each DDE conversation is uniquely defined by the application name and topic. At the beginning of a DDE conversation, the client and server determine the application name and topic. The application name is usually the name of the server application. For example, when Microsoft Excel acts as the server in a conversation, the application name is Excel.

The DDE topic is a general classification of data within which multiple data items may be "discussed" (exchanged) during the conversation. For applications that operate on file-based documents, the topic is usually a filename. For other applications, the topic is an application-specific name.

Because the client and server window handles together identify a DDE conversation, the application name and topic that define a conversation cannot be changed during the course of the conversation.

A DDE data item is information related to the conversation topic exchanged between the applications. Values for the data item can be passed from the server to the client, or from the client to the server. Data can be passed with any of the standard clipboard formats or with a registered clipboard format. A special, registered format named Link identifies an item in a DDE conversation. For more information about clipboard formats, see Clipboard.


 The System Topic

Applications should support the system topic at all times. This topic provides a context for information that may be of general interest to another application.

Data-item values must be rendered in the CF_TEXT clipboard format. Individual elements of item values for a system topic must be delimited by tab characters. The following table suggests some items for the system topic.

Item	Description
Formats	Tab-delimited list of clipboard formats the application can render. Typically, CF_ formats are listed with the "CF_" portion of the names removed (for example, CF_TEXT is listed as "TEXT").
Help	Text that briefly explains how to use the DDE server.
ReturnMessage	Supporting detail for the most recently used WM_DDE_ACK message. This item is useful when more than eight bits of application-specific return data are required.
Status	Indication of the current status of the application. When a server receives a WM_DDE_REQUEST message for this system-topic item, it should respond by posting a WM_DDE_DATA message with a string containing either Busy or Ready, as appropriate.
SysItems	List of system-topic items the application supports.
TopicItemList	Similar to the SysItems item, except that TopicItemList should be supported for each topic other than the system topic. This allows browsing of the items supported under any topic. If the items cannot be enumerated, this item should contain only "TopicItemList".
Topics	List of topics the application supports at the current time; this list can vary from moment to moment.


 Permanent Data Links

Once a DDE conversation has begun, the client can establish one or more permanent data links with the server. A data link is a communications mechanism by which the server notifies the client whenever the value of a given data item changes. The data link is permanent in the sense that this notification process continues until the data link or the DDE conversation itself is terminated.

There are two kinds of permanent DDE data links: warm and hot. In a warm data link, the server notifies the client that the value of the data item has changed, but the server does not send the data value to the client until the client requests it. In a hot data link, the server immediately sends the changed data value to the client.

Applications that support warm or hot data links typically provide a Copy or Paste Link command in their Edit menu to enable the user to establish links between applications. For more information, see Initiating a Data Link.


 Atoms and Shared Memory Objects

Certain arguments of DDE messages are global atoms or shared memory objects. Applications using these arguments must follow explicit rules about when to allocate and delete them. In all cases, the message sender must delete any atom or shared memory object that the intended receiver will not receive because of an error condition, such as failure of the PostMessage function.

DDE uses shared memory objects for three purposes:

•	To carry a data-item value to be exchanged. This is an item referenced by the hData parameter in the WM_DDE_DATA and WM_DDE_POKE messages.

•	To carry options in a message. This is an item referenced by the hOptions parameter in a WM_DDE_ADVISE message.

•	To carry a command execution string. This is an item referenced by the hCommands parameter in the WM_DDE_EXECUTE message and its corresponding WM_DDE_ACK message.

An application that receives a DDE shared memory object must treat it as read only. The application must not use the object as a mutual read-write area for the free exchange of data.

As it does with a DDE atom, an application should free a shared memory object to manage memory effectively. The application should also lock and unlock memory objects.


 Dynamic Data Exchange Messages Overview

Because DDE is a message-based protocol, it employs no special Win32 functions or libraries. All DDE transactions are conducted by passing certain defined DDE messages between the client and server windows.

There are nine DDE messages; the symbolic constants for these messages are defined in the DDE header file. Certain structures for the various DDE messages are also defined in this header file.

The following table summarizes the nine DDE messages.

Message	Description
WM_DDE_ACK	Acknowledges receiving or not receiving a message.
WM_DDE_ADVISE	Requests the server application to supply an update or notification for a data item whenever it changes. This establishes a permanent data link.
WM_DDE_DATA	Sends a data-item value to the client application.
WM_DDE_EXECUTE	Sends a string to the server application, which is expected to process the string as a series of commands.
WM_DDE_INITIATE	Initiates a conversation between the client and server applications.
WM_DDE_POKE	Sends a data-item value to the server application.
WM_DDE_REQUEST	Requests the server application to provide the value of a data item.
WM_DDE_TERMINATE	Terminates a conversation.
WM_DDE_UNADVISE	Terminates a permanent data link.
An application calls SendMessage to issue the WM_DDE_INITIATE message or a WM_DDE_ACK message sent in response to WM_DDE_INITIATE. All other messages are sent by PostMessage. The first parameter of these calls is the handle of the receiving window; the second parameter contains the message to be sent; the third parameter identifies the sending window; and the fourth parameter contains the message-specific arguments.


 Dynamic Data Exchange Message Flow

A typical DDE conversation consists of the following events:

1.	The client application initiates the conversation, and the server application responds.

2.	The applications exchange data by any or all of the following methods:

•	The server application sends data to the client at the client's request.

•	The client application sends unsolicited data to the server application.

•	The client application requests the server application to notify the client whenever a data item changes (warm data link).

•	The client application requests the server application to send data whenever the data changes (hot data link).

•	The server application carries out a command at the client's request.

3.	Either the client or server application terminates the conversation.

An application window that processes requests from a client or server must process them strictly in the order they are received.

A client can establish conversations with more than one server; a server can have conversations with more than one client. When handling messages from more than one source, a client or server must process the messages of a given conversation synchronously, but need not process all messages synchronously. In other words, it can shift from one conversation to another as needed.

If an application is unable to process an incoming request because it is waiting for a DDE response, it must prevent deadlock by posting a WM_DDE_ACK message with the fBusy member of the DDEACK structure set to 1. An application can also send a busy WM_DDE_ACK message if, for any reason, it cannot process an incoming request within a reasonable amount of time.

An application should be able to handle the failure of a client or server to respond to a message within a certain time. Since the time-out interval may vary depending on the nature of the application and the configuration of the user's system (including whether it is connected to a network), the application should provide a way for the user to specify the interval.


 Parameter-Packing Functions

The lParam parameter of many DDE messages contains two pieces of data. For example, the lParam of the WM_DDE_DATA message contains a data handle and an atom. In previous versions of Windows, an application could use the MAKELONG macro to prepare an lParam parameter, and the LOWORD and HIWORD macros to remove the low-order and high-order values from lParam. Because a Win32 data handle is a 32-bit value, a Win32-based application must use the PackDDElParam function to pack the handle and atom into an lParam parameter, and the UnpackDDElParam function to remove the values. DDE applications must use PackDDElParam and UnpackDDElParam for all messages posted during a DDE conversation.

The Win32 API also includes the ReuseDDElParam and FreeDDElParam functions. ReuseDDElParam allows a DDE application to reuse a packed lParam parameter, helping reduce the number of memory reallocations the application must perform during a conversation. An application can use FreeDDElParam to free the memory associated with a data handle received during a DDE conversation.


 Using Dynamic Data Exchange

•	Initiating a DDE conversation

•	Transferring a single data item

•	Establishing a permanent data link

•	Carrying out commands in a server application

•	Terminating a DDE conversation


 Initiating a Conversation

To initiate a DDE conversation, the client sends a WM_DDE_INITIATE message. Usually, the client broadcasts this message by calling SendMessage, with −1 as the first parameter. If the application already has the window handle of the server application, it can send the message directly to that window. The client prepares atoms for the application name and topic name by calling GlobalAddAtom. The client can request conversations with any potential server application and for any potential topic by supplying NULL (wildcard) atoms for the application and topic.

The following example illustrates how the client initiates a conversation, where both the application and topic are specified.

/* Global variable */

static BOOL fInInitiate = FALSE;

    char *szApplication;

    char *szTopic;

    atomApplication = *szApplication == 0 ?

        NULL : GlobalAddAtom((LPSTR) szApplication);

    atomTopic = *szTopic == 0 ?

        NULL : GlobalAddAtom((LPSTR) szTopic);

    fInInitiate = TRUE;

    SendMessage((HWND) -1,        /* broadcasts message          */

        WM_DDE_INITIATE,          /* initiates conversation      */

        (WPARAM) hwndClientDDE,   /* handle of client DDE window */

        MAKELONG(atomApplication, /* application-name atom       */

            atomTopic));          /* topic-name atom             */

    fInInitiate = FALSE;

    if (atomApplication != NULL)

        GlobalDeleteAtom(atomApplication);

    if (atomTopic != NULL)

        GlobalDeleteAtom(atomTopic);

Note that if your application uses NULL atoms, you need not use the GlobalAddAtom and GlobalDeleteAtom functions. In this example, the client application creates two global atoms containing the name of the server and the name of the topic, respectively.

The client application sends a WM_DDE_INITIATE message with these two atoms in the lParam parameter of the message. In the call to the SendMessage function, the special window handle −1 directs Windows to send this message to all other active applications. SendMessage does not return to the client application until all applications that receive the message have, in turn, returned control to Windows. This means that all WM_DDE_ACK messages sent in reply by the server applications are guaranteed to have been processed by the client by the time the SendMessage call has returned.

After SendMessage returns, the client application deletes the global atoms.

Server applications respond according to the logic illustrated in the following diagram.

To acknowledge one or more topics, the server must create atoms for each conversation (requiring duplicate application-name atoms if there are multiple topics) and send a WM_DDE_ACK message for each conversation, as illustrated in the following example.

if ((atomApplication = GlobalAddAtom("Server")) != 0) {

    if ((atomTopic = GlobalAddAtom(szTopic)) != 0) {

        SendMessage(hwndClientDDE,

            WM_DDE_ACK,

            (WPARAM) hwndServerDDE,

            MAKELONG(atomApplication, atomTopic));

        GlobalDeleteAtom(atomApplication);

    }

    GlobalDeleteAtom(atomTopic);

}

if ((atomApplication == 0) || (atomTopic == 0)) {

     .

     . /* error handling */

     .

}

When a server responds with a WM_DDE_ACK message, the client application should save the handle of the server window. The client receiving the handle as the wParam parameter of the WM_DDE_ACK message then sends all subsequent DDE messages to the server window this handle identifies.

If your client application uses a NULL atom for the application name or topic name, expect the application to receive acknowledgments from more than one server application. Multiple acknowledgements can also come from multiple instances of a DDE server, even if your client application does not use NULL atoms. A server should always use a unique window for each conversation. The window procedure in the client application can use the handle of the server window (provided as the lParam parameter of WM_DDE_INITIATE) to track multiple conversations. This allows a single client window to process several conversations without needing to terminate and reconnect with a new client window for each conversation.


 Transferring a Single Item

Once a DDE conversation has been established, the client can either retrieve the value of a data item from the server by issuing the WM_DDE_REQUEST message, or submit a data-item value to the server by issuing WM_DDE_POKE.


 Retrieving an Item from the Server

To retrieve an item from the server, the client sends the server a WM_DDE_REQUEST message specifying the item and format to retrieve, as shown in the following example.

if ((atomItem = GlobalAddAtom(szItemName)) != 0) {

    if (!PostMessage(hwndServerDDE,

            WM_DDE_REQUEST,

            (WPARAM) hwndClientDDE,

            PackDDElParam(WM_DDE_REQUEST, CF_TEXT, atomItem)))

        GlobalDeleteAtom(atomItem);

}

if (atomItem == 0) {

     .

     . /* error handling */

     .

}

In this example, the client specifies the clipboard format CF_TEXT as the preferred format for the requested data item.

The receiver (server) of the WM_DDE_REQUEST message typically must delete the item atom, but if the PostMessage call fails, the client must delete the atom.

If the server has access to the requested item and can render it in the requested format, the server copies the item value as a shared memory object and sends the client a WM_DDE_DATA message, as illustrated in the following example.

/*

 * Allocate the size of the DDE data header, plus the data: a

 * string,<CR><LF><NULL>. The byte for the string's terminating

 * null character is counted by DDEDATA.Value[1].

 */

if (!(hData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE,

        (LONG) sizeof(DDEDATA) + lstrlen(szItemValue) + 2)))

    return;

if (!(lpData = (DDEDATA FAR*) GlobalLock(hData)))  {

    GlobalFree(hData);

    return;

}

   .

   .

   .

lpData->cfFormat = CF_TEXT;

lstrcpy((LPSTR) lpData->Value, (LPSTR) szItemValue);

/* Each line of CF_TEXT data is terminated by CR/LF. */

lstrcat((LPSTR) lpData->Value, (LPSTR) "\r\n");

GlobalUnlock(hData);

if ((atomItem = GlobalAddAtom((LPSTR) szItemName)) != 0) {

    lParam = PackDDElParam(WM_DDE_ACK, (UINT) hData, atomItem);

    if (!PostMessage(hwndClientDDE,

            WM_DDE_DATA,

            (WPARAM) hwndServerDDE,

            lParam)) {

        GlobalFree(hData);

        GlobalDeleteAtom(atomItem);

        FreeDDElParam(WM_DDE_ACK, lParam);

    }

}

if (atomItem == 0) {

     .

     . /* error handling */

     .

}

In this example, the server application allocates a memory object to contain the data item. The memory is allocated with the GMEM_DDESHARE option, so that the server and client applications can share the memory. After allocating the memory object, the server application locks the object so it can obtain the object's address. The data object is initialized as a DDEDATA structure.

The server application then sets the cfFormat member of the structure to CF_TEXT to inform the client application that the data is in text format. The client responds by copying the value of the requested data into the Value member of the DDEDATA structure. After the server has filled the data object, the server unlocks the data and creates a global atom containing the name of the data item.

Finally, the server issues the WM_DDE_DATA message by calling PostMessage. The handle of the data object and the atom containing the item name are packed into the lParam parameter of the message by the PackDDElParam function.

If PostMessage fails, the server must use the FreeDDElParam function to free the packed lParam parameter. The server must also free the packed lParam parameter for the WM_DDE_REQUEST message it received.

If the server cannot satisfy the request, it sends a negative WM_DDE_ACK message to the client, as shown in the following example.

/* negative acknowledgment */

PostMessage(hwndClientDDE,

    WM_DDE_ACK,

    (WPARAM) hwndServerDDE,

    PackDDElParam(WM_DDE_ACK, 0, atomItem));

Upon receiving a WM_DDE_DATA message, the client processes the data-item value as appropriate. Then, if the fAckReq member pointed to in the WM_DDE_DATA message is 1, the client must send the server a positive WM_DDE_ACK message, as shown in the following example.

UnpackDDElParam(WM_DDE_DATA, lParam, (PUINT) &hData,

    (PUINT) &atomItem);

if (!(lpDDEData = (DDEDATA FAR*) GlobalLock(hData))

        || (lpDDEData->cfFormat != CF_TEXT)) {

    PostMessage(hwndServerDDE,

        WM_DDE_ACK,

        (WPARAM) hwndClientDDE,

        PackDDElParam(WM_DDE_ACK, 0, atomItem)); /* negative ACK */

}

/* Copy data from lpDDEData here.*/

if (lpDDEData->fAckReq) {

    PostMessage(hwndServerDDE,

        WM_DDE_ACK,

        (WPARAM) hwndClientDDE,

        PackDDElParam(WM_DDE_ACK, 0x8000,

            atomItem)); /* positive ACK */

}

bRelease = lpDDEData->fRelease;

GlobalUnlock(hData);

if (bRelease)

    GlobalFree(hData);

In this example, the client examines the format of the data. If the format is not CF_TEXT (or if the client cannot lock the memory for the data), the client sends a negative WM_DDE_ACK message to indicate that it cannot process the data. If the client cannot lock a data handle because the handle contains the fAckReq member, the client should not send a negative WM_DDE_ACK message. Instead, the client should terminate the conversation.

If a client sends a negative acknowledgement in response to a WM_DDE_DATA message, the server is responsible for freeing the memory (but not the lParam parameter) referenced by the WM_DDE_DATA message associated with the negative acknowledgement.

If it can process the data, the client examines the fAckReq member of the DDEDATA structure to determine whether the server requested that it be informed that the client received and processed the data successfully. If the server did request this information, the client sends the server a positive WM_DDE_ACK message.

Because unlocking data invalidates the pointer to the data, the client saves the value of the fRelease member before unlocking the data object. After saving the value, the client then examines it to determine whether the server application requested the client to free the memory containing the data; the client acts accordingly.

Upon receiving a negative WM_DDE_ACK message, the client can ask for the same item value again, specifying a different clipboard format. Typically, a client will first ask for the most complex format it can support, then step down if necessary through progressively simpler formats until it finds one the server can provide.

If the server supports the Formats item of the system topic, the client can determine once what clipboard formats the server supports, instead of determining them each time the client requests an item. For more information about the system topic, see The System Topic.


 Submitting an Item to the Server

The client may send an item value to the server by using the WM_DDE_POKE message. The client renders the item to be sent and sends the WM_DDE_POKE message, as illustrated in the following example.

if (!(hPokeData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE,

        (LONG) sizeof(DDEPOKE) + lstrlen(szValue) + 2)))

    return;

if (!(lpPokeData = (DDEPOKE FAR*) GlobalLock(hPokeData))) {

    GlobalFree(hPokeData);

    return;

}

lpPokeData->fRelease = TRUE;

lpPokeData->cfFormat = CF_TEXT;

lstrcpy((LPSTR) lpPokeData->Value, (LPSTR) szValue);

/* Each line of CF_TEXT data is terminated by CR/LF. */

lstrcat((LPSTR) lpPokeData->Value, (LPSTR) "\r\n");

GlobalUnlock(hPokeData);

if ((atomItem = GlobalAddAtom((LPSTR) szItem)) != 0) {

       .

       .

       .

        if (!PostMessage(hwndServerDDE,

                WM_DDE_POKE,

                (WPARAM) hwndClientDDE,

                PackDDElParam(WM_DDE_POKE, (UINT) hPokeData,

                    atomItem))) {

           GlobalDeleteAtom(atomItem);

           GlobalFree(hPokeData);

        }

}

if (atomItem == 0) {

     .

     . /* error handling */

     .

}

Note that sending data by using a WM_DDE_POKE message is essentially the same as sending it by using WM_DDE_DATA, except that WM_DDE_POKE is sent from the client to the server.

If the server is able to accept the data-item value in the format rendered by the client, the server processes the item value as appropriate and sends the client a positive WM_DDE_ACK message. If it is unable to process the item value, because of its format or for other reasons, the server sends the client a negative WM_DDE_ACK message.

UnpackDDElParam(WM_DDE_POKE, lParam, (PUINT) &hPokeData,

    (PUINT) &atomItem);

GlobalGetAtomName(atomItem, szItemName, ITEM_NAME_MAX_SIZE);

if (!(lpPokeData = (DDEPOKE FAR*) GlobalLock(hPokeData))

        || lpPokeData->cfFormat != CF_TEXT

        || !IsItemSupportedByServer(szItemName)) {

    PostMessage(hwndClientDDE,

        WM_DDE_ACK,

        (WPARAM) hwndServerDDE,

        PackDDElParam(WM_DDE_ACK, 0, atomItem)); /* negative ACK */

}

lstrcpy(szItemValue, lpPokeData->Value); /* copies value */

bRelease = lpPokeData->fRelease;

GlobalUnlock(hPokeData);

if (bRelease) {

    GlobalFree(hPokeData);

}

PostMessage(hwndClientDDE,

    WM_DDE_ACK,

    (WPARAM) hwndServerDDE,

    PackDDElParam(WM_DDE_ACK,

         0x8000, atomItem));    /* positive ACK */

In this example, the server calls GlobalGetAtomName to retrieve the name of the item the client sent. The server then determines whether it supports the item and whether the item is rendered in the correct format (that is, CF_TEXT). If the item is not supported and not rendered in the correct format, or if the server cannot lock the memory for the data, the server sends a negative acknowledgment back to the client application. Note that in this case, sending a negative acknowledgement is correct because WM_DDE_POKE messages are always assumed to have the fAckReq member set. The server should ignore the member.

If a server sends a negative acknowledgement in response to a WM_DDE_POKE message, the client is responsible for freeing the memory (but not the lParam parameter) referenced by the WM_DDE_POKE message associated with the negative acknowledgement.


 Establishing a Permanent Data Link

A client application can use DDE to establish a link to an item in a server application. After such a link is established, the server sends periodic updates of the linked item to the client, typically, whenever the value of the item changes. Thus, a permanent data stream is established between the two applications; this data stream remains in place until it is explicitly disconnected.


 Initiating a Data Link

The client initiates a data link by posting a WM_DDE_ADVISE message, as shown in the following example.

if (!(hOptions = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE,

        sizeof(DDEADVISE))))

    return;

if (!(lpOptions = (DDEADVISE FAR*) GlobalLock(hOptions))) {

    GlobalFree(hOptions);

    return;

}

lpOptions->cfFormat = CF_TEXT;

lpOptions->fAckReq = TRUE;

lpOptions->fDeferUpd = FALSE;

GlobalUnlock(hOptions);

if ((atomItem = GlobalAddAtom(szItemName)) != 0) {

    if (!(PostMessage(hwndServerDDE,

            WM_DDE_ADVISE,

            (WPARAM) hwndClientDDE,

            PackDDElParam(WM_DDE_ADVISE, (UINT) hOptions,

                atomItem)))) {

        GlobalDeleteAtom(atomItem);

        GlobalFree(hOptions);

        FreeDDElParam(WM_DDE_ADVISE, lParam);

    }

}

if (atomItem == 0) {

    .

    . /* error handling */

    .

}

In this example, the client application sets the fDeferUpd flag of the WM_DDE_ADVISE message to FALSE. This directs the server application to send the data to the client whenever the data changes.

If the server is unable to service the WM_DDE_ADVISE request, it sends the client a negative WM_DDE_ACK message. But if the server has access to the item and can render it in the requested format, the server notes the new link (recalling the flags specified in the hOptions parameter) and sends the client a positive WM_DDE_ACK message. From then on, until the client issues a matching WM_DDE_UNADVISE message, the server sends the new data to the client every time the value of the item changes in the server.

The WM_DDE_ADVISE message establishes the format of the data to be exchanged during the link. If the client attempts to establish another link with the same item but is using a different data format, the server can choose to reject the second data format or attempt to support it. If a warm link has been established for any data item, the server can support only one data format at a time. This is because the WM_DDE_DATA message for a warm link has a NULL data handle, which otherwise contains the format information. Thus, a server must reject all warm links for an item already linked, and must reject all links for an item that has warm links. Another interpretation may be that the server changes the format and the hot or warm state of a link when a second link is requested for the same data item.

In general, client applications should not attempt to establish more than one link at a time for a data item.


 Initiating a Data Link with the Paste Link Command

Applications that support hot or warm data links typically support a registered clipboard format named Link. When associated with the application's Copy and Paste Link commands, this clipboard format enables the user to establish DDE conversations between applications simply by copying a data item in the server application and pasting it into the client application.

A server application supports the Link clipboard format by placing in the clipboard a string containing the application, topic, and item names when the user chooses the Copy command from the Edit menu. Following is the standard Link format:

application\0topic\0item\0\0

A single null character separates the names, and two null characters terminate the entire string.

Both the client and server applications must register the Link clipboard format, as shown:

cfLink = RegisterClipboardFormat("Link");

A client application supports the Link clipboard format by means of a Paste Link command on its Edit menu. When the user chooses this command, the client application parses the application, topic, and item names from the Link-format clipboard data. Using these names, the client application initiates a conversation for the application and topic, if such a conversation does not already exist. The client application then sends a WM_DDE_ADVISE message to the server application, specifying the item name contained in the Link-format clipboard data.

Following is an example of a client application's response when the user chooses the Paste Link command.

void DoPasteLink(hwndClientDDE)

HWND hwndClientDDE;

{

    HANDLE hData;

    LPSTR lpData;

    HWND hwndServerDDE;

    CHAR szApplication[APP_MAX_SIZE + 1];

    CHAR szTopic[TOPIC_MAX_SIZE + 1];

    CHAR szItem[ITEM_MAX_SIZE + 1];

    int nBufLen;

    if (OpenClipboard(hwndClientDDE)) {

        if (!(hData = GetClipboardData(cfLink)) ||

                !(lpData = GlobalLock(hData))) {

            CloseClipboard();

            return;

        }

        /* Parse the clipboard data. */

        if ((nBufLen = lstrlen(lpData)) >= APP_MAX_SIZE) {

            CloseClipboard();

            GlobalUnlock(hData);

            return;

        }

        lstrcpy(szApplication, lpData);

        lpData += (nBufLen + 1); /* skips over null */

        if ((nBufLen = lstrlen(lpData)) >= TOPIC_MAX_SIZE) {

            CloseClipboard();

            GlobalUnlock(hData);

            return;

        }

        lstrcpy(szTopic, lpData);

        lpData += (nBufLen + 1); /* skips over null */

        if ((nBufLen = lstrlen(lpData)) >= ITEM_MAX_SIZE) {

            CloseClipboard();

            GlobalUnlock(hData);

            return;

        }

        lstrcpy(szItem, lpData);

        GlobalUnlock(hData);

        CloseClipboard();

        if (hwndServerDDE =

                FindServerGivenAppTopic(szApplication, szTopic)) {

            /* App/topic conversation is already started. */

            if (DoesAdviseAlreadyExist(hwndServerDDE, szItem))

                MessageBox(hwndMain,

                    "Advisory already established",

                    "Client", MB_ICONEXCLAMATION | MB_OK);

            else

                SendAdvise(hwndClientDDE, hwndServerDDE, szItem);

        }

        else {

            /* Client must initiate a new conversation first. */

            SendInitiate(szApplication, szTopic);

            if (hwndServerDDE =

                    FindServerGivenAppTopic(szApplication,

                        szTopic))

                SendAdvise(hwndClientDDE, hwndServerDDE, szItem);

        }

    }

    return;

}

In this example, the client application opens the clipboard and determines whether it contains data in the Link format (that is, cfLink) it had previously registered. If not, or if it cannot lock the data in the clipboard, the client returns.

After the client application retrieves a pointer to the clipboard data, it parses the data to extract the application, topic, and item names.

The client application determines whether a conversation on the topic already exists between it and the server application. If a conversation does exist, the client checks whether a link already exists for the data item. If such a link exists, the client displays a message box to the user; otherwise, it calls its own SendAdvise function to send a WM_DDE_ADVISE message to the server for the item.

If a conversation on the topic does not already exist between the client and the server, the client first calls its own SendInitiate function to broadcast the WM_DDE_INITIATE message to request a conversation and, second, calls its own FindServerGivenAppTopic function to establish the conversation with the window that responds on behalf of the server application. After the conversation has begun, the client application calls SendAdvise to request the link.


 Notifying the Client that Data Has Changed

When the client establishes a link by using the WM_DDE_ADVISE message, with the fDeferUpd member not set (that is, equal to zero) in the DDEDATA structure, the client has requested the server send the data item each time the item's value changes. In such cases, the server renders the new value of the data item in the previously specified format and sends the client a WM_DDE_DATA message, as shown in the following example.

/*

 * Allocate the size of a DDE data header, plus data (a string),

 * plus a <CR><LF><NULL>

 */

if (!(hData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE,

        sizeof(DDEDATA) + lstrlen(szItemValue) + 3)))

    return;

if (!(lpData = (DDEDATA FAR*) GlobalLock(hData))) {

    GlobalFree(hData);

    return;

}

lpData->fAckReq = bAckRequest;  /* as specified in original     */

                                /* WM_DDE_ADVISE message        */

lpData->cfFormat = CF_TEXT;

lstrcpy(lpData->Value, szItemValue); /* copies value to be sent */

lstrcat(lpData->Value, "\r\n"); /* CR/LF for CF_TEXT format     */

GlobalUnlock(hData);

if ((atomItem = GlobalAddAtom(szItemName)) != 0) {

    if (!PostMessage(hwndClientDDE,

            WM_DDE_DATA,

            (WPARAM) hwndServerDDE,

            PackDDElParam(WM_DDE_DATA, (UINT) hData, atomItem))) {

        GlobalFree(hData);

        GlobalDeleteAtom(atomItem);

        FreeDDElParam(WM_DDE_DATA, lParam);

    }

}

if (atomItem == 0) {

     .

     . /* error handling */

     .

}

In this example, the client processes the item value as appropriate. If the fAckReq flag for the item is set, the client sends the server a positive WM_DDE_ACK message.

When the client establishes the link, with the fDeferUpd member set (that is, equal to 1), the client has requested that only a notification, not the data itself, be sent each time the data changes. In such cases, when the item value changes, the server does not render the value but simply sends the client a WM_DDE_DATA message with a null data handle, as illustrated in the following example.

if (bDeferUpd) {     /* checking whether the flag was originally */

                     /* set in the WM_DDE_ADVISE message         */

    if ((atomItem = GlobalAddAtom(szItemName)) != 0) {

        if (!PostMessage(hwndClientDDE,

                WM_DDE_DATA,

                (WPARAM) hwndServerDDE,

                PackDDElParam(WM_DDE_DATA, 0,

                    atomItem))) {                   /* NULL data */

            GlobalDeleteAtom(atomItem);

            FreeDDElParam(WM_DDE_DATA, lParam);

        }

    }

}

if (atomItem == 0) {

     .

     . /* error handling */

     .

}

As necessary, the client can request the latest value of the data item by issuing a normal WM_DDE_REQUEST message, or it can simply ignore the notice from the server that the data has changed. In either case, if fAckReq is equal to 1, the client is expected to send a positive WM_DDE_ACK message to the server.


 Terminating a Data Link

If the client requests that a specific data link be terminated, the client sends the server a WM_DDE_UNADVISE message, as shown in the following example.

if ((atomItem = GlobalAddAtom(szItemName)) != 0) {

    if (!PostMessage(hwndServerDDE,

            WM_DDE_UNADVISE,

            (WPARAM) hwndClientDDE,

            PackDDElParam(WM_DDE_UNADVISE, 0, atomItem))) {

        GlobalDeleteAtom(atomItem);

        FreeDDElParam(WM_DDE_UNADVISE, lParam);

    }

}

if (atomItem == 0) {

     .

     . /* error handling */

     .

}

The server checks whether the client currently has a link to the specific item in this conversation. If a link exists, the server sends the client a positive WM_DDE_ACK message; the server is then no longer required to send updates about the item. If no link exists, the server sends the client a negative WM_DDE_ACK message.

The WM_DDE_UNADVISE message specifies a data format. A format of zero informs the server to stop all links for the specified item, even if several hot links are established and each uses a different format.

To terminate all links for a conversation, the client application sends the server a WM_DDE_UNADVISE message with a null item atom. The server determines whether the conversation has at least one link currently established. If a link exists, the server sends the client a positive WM_DDE_ACK message; the server then no longer has to send any updates in the conversation. If no link exists, the server sends the client a negative WM_DDE_ACK message.


 Carrying Out Commands in a Server Application

A Win32-based application can use the WM_DDE_EXECUTE message to cause a certain command or series of commands to be carried out in another application. To do this, the client sends the server a WM_DDE_EXECUTE message containing a handle to a command string, as shown in the following example.

if (!(hCommand = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE,

        sizeof(szCommandString) + 1)))

    return;

if (!(lpCommand = GlobalLock(hCommand))) {

    GlobalFree(hCommand);

    return;

}

lstrcpy(lpCommand, szCommandString);

GlobalUnlock(hCommand);

if (!PostMessage(hwndServerDDE,

        WM_DDE_EXECUTE,

        (WPARAM) hwndClientDDE,

        PackDDElParam(WM_DDE_EXECUTE, 0, (UINT) hCommand))) {

    GlobalFree(hCommand);

    FreeDDElParam(WM_DDE_EXECUTE, lParam);

}

In this example, the server attempts to carry out the specified command string. If it succeeds, the server sends the client a positive WM_DDE_ACK message; otherwise, it sends a negative WM_DDE_ACK message. This WM_DDE_ACK message reuses the hCommand handle passed in the original WM_DDE_EXECUTE message.

If the client's command execution string requests that the server terminate, the server should respond by sending a positive WM_DDE_ACK message and then post a WM_DDE_TERMINATE message before terminating. All other commands sent with a WM_DDE_EXECUTE message should be executed synchronously; that is, the server should send a WM_DDE_ACK message only after successfully completing the command.


 Terminating a Conversation

Either the client or the server can issue a WM_DDE_TERMINATE message to terminate a conversation at any time. Similarly, both the client and server applications should be prepared to receive this message at any time. An application must terminate all of its conversations before shutting down.

In the following example, the application terminating the conversation posts a WM_DDE_TERMINATE message.

PostMessage(hwndServerDDE, WM_DDE_TERMINATE,

    PackDDElParam(WM_DDE_TERMINATE, (UINT) hwndClientDDE, 0), 0);

This informs the other application that the sending application will send no further messages and the recipient can close its window. The recipient is expected in all cases to respond promptly by sending a WM_DDE_TERMINATE message. The recipient must not send a negative, busy, or positive WM_DDE_ACK message.

After an application has sent the WM_DDE_TERMINATE message to the partner in a DDE conversation, it must not respond to messages from that partner, since the partner might have destroyed the window to which the response would be sent.

If an application receives a DDE message other than WM_DDE_TERMINATE after it has posted WM_DDE_TERMINATE, it should free all objects associated with the received messages except the data handles for WM_DDE_DATA or WM_DDE_POKE messages that do not have the fRelease member set.

When an application is about to terminate, it should end all active DDE conversations before completing processing of the WM_DESTROY message. However, if an application does not end its active DDE conversations, the system will terminate any DDE conversations associated with a window when the window is destroyed. The following example shows how a server application terminates all DDE conversations.

void TerminateConversations(hwndServerDDE)

HWND hwndServerDDE;

{

    HWND hwndClientDDE;

    /* Terminate each active conversation. */

    while (hwndClientDDE = GetNextLink(hwndClientDDE)) {

        SendTerminate(hwndServerDDE, hwndClientDDE);

    }

    return;

}

BOOL AtLeastOneLinkActive(VOID)

{

    return TRUE;

}

HWND GetNextLink(hwndDummy)

    HWND hwndDummy;

{

    return (HWND) 1;

}

VOID SendTerminate(HWND hwndServerDDE, HWND hwndClientDDE)

{

    return;

}


 Dynamic Data Exchange Reference

The following functions and messages are associated with dynamic data exchange.


 Dynamic Data Exchange Functions

Following are the functions used with DDE.

DdeSetQualityOfService
FreeDDElParam
ImpersonateDdeClientWindow
PackDDElParam
ReuseDDElParam
UnpackDDElParam


 Dynamic Data Exchange Messages

Following are the messages used with DDE.

WM_DDE_ACK
WM_DDE_ADVISE
WM_DDE_DATA
WM_DDE_EXECUTE
WM_DDE_INITIATE
WM_DDE_POKE
WM_DDE_REQUEST
WM_DDE_TERMINATE
WM_DDE_UNADVISE


 Dynamic Data Exchange Management Library

In Microsoft® Windows®, dynamic data exchange (DDE) is a form of interprocess communications that uses shared memory to exchange data between applications. Applications can use DDE for one-time data transfers and for ongoing exchanges and updating of data.


 About the DDEML

DDE differs from the clipboard data-transfer mechanism that is also part of the Windows operating system. One difference is that the clipboard is almost always used as a one-time response to a specific action by the user — such as choosing the Paste command from a menu. Although DDE may also be initiated by a user, it typically continues without the user's further involvement.

The dynamic data exchange management library (DDEML) provides an application programming interface (API) that simplifies the task of adding DDE capability to a Windows application. Instead of sending, posting, and processing DDE messages directly, an application uses the functions provided by the DDEML to manage DDE conversations. A DDE conversation is the interaction between client and server applications. The DDEML also provides a means for managing the strings and data shared among DDE applications. Instead of using atoms and pointers to shared memory objects, DDE applications create and exchange string handles, which identify strings, and data handles, which identify DDE objects. The DDEML provides a function (DdeNameService) that enables a server application to register the service names it supports. The service names are then broadcast to other applications in the system, which use the names to connect to the server. The DDEML also ensures compatibility among DDE applications by requiring them to implement the DDE protocol in a consistent manner.

Existing applications using the message-based DDE protocol are fully compatible with those that use the DDEML; that is, an application using message-based DDE can establish conversations and perform transactions with applications using the DDEML. Instead of using DDE messages in your new application, take advantage of the DDEML and the many improvements it offers.

To use the API elements of the DDEML, you must include the DDEML.H header file in your source files, link with the USER32.LIB file, and ensure that the DDEML.DLL file resides in the system's path.


 Basic Concepts

The concepts in this section are key to understanding DDE and the DDEML.


 Client and Server Interaction

DDE always occurs between a client application and a server application. The DDE client application initiates the exchange by establishing a conversation with the server to send transactions to the server. A transaction is a request for data or services. The DDE server application responds to transactions by providing data or services to the client. For example, a graphics application might contain a bar graph representing a corporation's quarterly profits, but the data for the bar graph might be contained in a spreadsheet application. To obtain the latest profit figures, the graphics application (the client) could establish a conversation with the spreadsheet application (the server). The graphics application could then send a transaction to the spreadsheet application, requesting the latest profit figures.

A server can have many clients at the same time, and a client can request data from multiple servers. An application can also be both a client and a server. Either the client or the server can terminate the conversation at any time.


 Transactions and the DDE Callback Function

The DDEML notifies an application about DDE activity that affects the application by sending transactions to the application's DDE callback function. A DDE transaction is similar to a message — it is a named constant accompanied by other parameters that contain additional information about the transaction.

The DDEML passes a transaction to an application-defined DDE callback function that carries out an action appropriate to the type of transaction. For example, when a client application attempts to establish a conversation with a server application, the client calls the DdeConnect function. This function causes the DDEML to send an XTYP_CONNECT transaction to the server's DDE callback function. The callback function can allow the conversation by returning TRUE to the DDEML, or it can deny the conversation by returning FALSE. For a detailed discussion of transactions, see Transaction Management.


 Service Names, Topic Names, and Item Names

A DDE server uses a three-level hierarchy — service name (called "application name" in previous DDE documentation), topic name, and item name — to uniquely identify a unit of data the server can exchange during a conversation.

A service name is a string a server application responds to when a client attempts to establish a conversation with the server. A client must specify this service name to establish a conversation with the server. Although a server can respond to many service names, most servers respond to only one name.

A topic name is a string that identifies a logical data context. For servers that operate on file-based documents, topic names are typically filenames; for other servers, they are other application-specific strings. A client must specify a topic name along with a server's service name when it attempts to establish a conversation with a server.

An item name is a string that identifies a unit of data a server can pass to a client during a transaction. For example, an item name might identify an integer, a string, several paragraphs of text, or a bitmap.

The service, topic, and item names enable the client to establish a conversation with a server and to receive data from the server.


 System Topic

The System topic provides a context for information of general interest to any DDE client. It is recommended that server applications support the System topic at all times. The System topic is defined in the DDEML.H header file as SZDDESYS_TOPIC.

To determine which servers are present and the kinds of information they can provide, a client application can request a conversation on the System topic upon starting, setting the device name to NULL. Such wildcard conversations are costly in terms of system performance, so they should be kept to a minimum. For more information about initiating DDE conversations, see Conversation Management.

A server must support the following item names within the System topic and any other item names that are useful to a client.

Item	Description
SZDDE_ITEM_ITEMLIST	A list of the items supported under a non-System topic. (This list may vary from moment to moment and from topic to topic.)
SZDDESYS_ITEM_FORMATS	A tab-delimited list of strings representing all clipboard formats potentially supported by the service application. Strings that represent predefined clipboard formats are equivalent to the CF_ values with the "CF_" prefix removed. For example, the CF_TEXT format is represented by the string "TEXT". These strings must be uppercase to further identify them as predefined formats. The list of formats must appear in the order of most rich in content to least rich in content.
	For more information about clipboard formats and rendering data, see Clipboard.
SZDDESYS_ITEM_HELP	User-readable information of general interest. This item must contain, at a minimum, information on how to use the server application's DDE features. This information may include, but is not limited to, how to specify items within topics, what execute strings the server can perform, what poke transactions are allowed, and how to find help on other System topic items.
SZDDESYS_ITEM_RTNMSG	Supporting detail for the most recently used WM_DDE_ACK message. This item is useful when more than 8 bits of application-specific return data are required.
SZDDESYS_ITEM_STATUS	An indication of the current status of the server. Typically, this item supports only the CF_TEXT format and contains the Ready or Busy string.
SZDDESYS_ITEM_SYSITEMS	A list of the items supported under the System topic by this server.
SZDDESYS_ITEM_TOPICS	A list of the topics supported by the server at the current time. (This list may vary from moment to moment.)
These item names are values defined in the DDEML.H header file. To obtain string handles for these strings, an application must use the DDEML string-management functions, just as it would for any other string in a DDEML application. For more information about managing strings, see String Management.


 DDEML and Threads

The DDEInitialize function registers an application with the DDEML, creating a DDEML instance. A DDEML instance is thread-based, associated with the thread that called DDEInitialize.

All DDEML function calls for objects belonging to a DDEML instance must be made from the same thread that called DDEInitialize to create the instance. If you call a DDEML function from a different thread, the function will fail. You cannot access a DDEML conversation from a thread other than the one that allocated the conversation.


 Initialization

Before calling any other DDEML function, an application must call the DdeInitialize function. DdeInitialize obtains an instance identifier for the application, registers the application's DDE callback function with the DDEML, and specifies the transaction filter flags for the callback function.

Each instance of an application or a dynamic-link library (DLL) must pass its instance identifier as the idInst parameter to any other DDEML function that requires it. The purpose of multiple DDEML instances is to support DLLs that must use the DDEML at the same time an application is using it. An application must not use more than one instance of the DDEML.

Transaction filters optimize system performance by preventing the DDEML from passing unwanted transactions to the application's DDE callback function. An application sets the transaction filters when it calls DdeInitialize. An application must specify a transaction filter flag for each type of transaction that it does not process in its callback function. An application can change its transaction filters with a subsequent call to DdeInitialize. For a complete list of transaction filter flags, see the description of DdeInitialize in the Microsoft Win32 Programmer's Reference, Volume 3. For more information about transactions, see Transaction Management.

The following example shows how to initialize an application to use the DDEML.

DWORD idInst = 0;

HINSTANCE hinst;

.

.

.

DdeInitialize(&idInst,         /* receives instance identifier */

    (PFNCALLBACK) DdeCallback, /* address of callback function */

    CBF_FAIL_EXECUTES |        /* filter XTYPE_EXECUTE         */

    CBF_SKIP_ALLNOTIFICATIONS, /* filter notifications         */

    0);

.

.

.

An application must call the DdeUninitialize function when it is no longer going to use the DDEML. This function terminates any conversations currently open for the application and frees the DDEML resources the system allocated for the application.


 Callback Function

An application that uses the DDEML must provide a callback function that processes the DDE events affecting the application. The DDEML notifies an application of such events by sending transactions to the application's DDE callback function. The transactions a callback function receives depend on which callback filter flags the application specified in DdeInitialize and whether the application is a client, a server, or both. The following example shows the general structure of a callback function for a typical client application.

HDDEDATA CALLBACK DdeCallback(uType, uFmt, hconv, hsz1,

    hsz2, hdata, dwData1, dwData2)

UINT uType;       /* transaction type                 */

UINT uFmt;        /* clipboard data format            */

HCONV hconv;      /* handle of conversation           */

HSZ hsz1;         /* handle of string                 */

HSZ hsz2;         /* handle of string                 */

HDDEDATA hdata;   /* handle of global memory object   */

DWORD dwData1;    /* transaction-specific data        */

DWORD dwData2;    /* transaction-specific data        */

{

    switch (uType) {

        case XTYP_REGISTER:

        case XTYP_UNREGISTER:

            .

            .

            .

            return (HDDEDATA) NULL;

        case XTYP_ADVDATA:

            .

            .

            .

            return (HDDEDATA) DDE_FACK;

        case XTYP_XACT_COMPLETE:

            .

            .

            .

            return (HDDEDATA) NULL;

        case XTYP_DISCONNECT:

            .

            .

            .

            return (HDDEDATA) NULL;

        default:

            return (HDDEDATA) NULL;

    }

}

The uType parameter specifies the transaction type sent to the callback function by the DDEML. The values of the remaining parameters depend on the transaction type. The transaction types and the events that generate them are described in the following topics. For detailed information about each transaction type, see Transaction Management.


 String Management

To carry out a DDE task, many DDEML functions require access to strings. For example, a client must specify a service name and a topic name when it calls the DdeConnect function to request a conversation with a server. An application specifies a string by passing a string handle (HSZ) rather than a pointer in a DDEML function. A string handle is a doubleword value, assigned by the system, that identifies a string.

An application can obtain a string handle for a particular string by calling the DdeCreateStringHandle function. This function registers the string with the system and returns a string handle to the application. The application can pass the handle to DDEML functions that must access the string. The following example obtains string handles for the System topic string and the service name string.

HSZ hszServName;

HSZ hszSysTopic;

.

.

.

hszServName = DdeCreateStringHandle(

    idInst,         /* instance identifier    */

    "MyServer",     /* string to register     */

    CP_WINANSI);    /* Windows ANSI code page */

hszSysTopic = DdeCreateStringHandle(

    idInst,         /* instance identifier    */

    SZDDESYS_TOPIC, /* System topic           */

    CP_WINANSI);    /* Windows ANSI code page */

.

.

.

The idInst parameter in the preceding example specifies the instance identifier obtained by the DdeInitialize function.

An application's DDE callback function receives one or more string handles during most DDE transactions. For example, a server receives two string handles during the XTYP_REQUEST transaction: one identifies a string specifying a topic name, and the other identifies a string specifying an item name. An application can obtain the length of the string that corresponds to a string handle and copy the string to an application-defined buffer by calling the DdeQueryString function, as shown in the following example.

DWORD idInst;

DWORD cb;

HSZ hszServ;

PSTR pszServName;

.

.

.

cb = DdeQueryString(idInst, hszServ, (LPSTR) NULL, 0,

    CP_WINANSI) + 1;

pszServName = (PSTR) LocalAlloc(LPTR, (UINT) cb);

DdeQueryString(idInst, hszServ, pszServName, cb, CP_WINANSI);

.

.

.

An instance-specific string handle cannot be mapped from string handle to string and back to string handle. For instance, although DdeQueryString creates a string from a string handle and then DdeCreateStringHandle creates a string handle from that string, the two handles are not the same, as shown in the following example.

DWORD idInst;

DWORD cb;

HSZ hszInst, hszNew;

PSZ pszInst;

.

.

.

DdeQueryString(idInst, hszInst, pszInst, cb, CP_WINANSI);

hszNew = DdeCreateStringHandle(idInst, pszInst, CP_WINANSI);

/* hszNew != hszInst ! */

.

.

.

A string handle passed to an application's DDE callback function becomes invalid when the callback function returns. An application can save a string handle for use after the callback function returns by using the DdeKeepStringHandle function.

When an application calls DdeCreateStringHandle, the system enters the specified string into a string table and generates a handle that it uses to access the string. The system also maintains a usage count for each string in the string table.

When an application calls DdeCreateStringHandle and specifies a string that already exists in the table, the system increments the usage count rather than adding another occurrence of the string. (An application can also increment the usage count by using DdeKeepStringHandle.) When an application calls the DdeFreeStringHandle function, the system decrements the usage count.

A string is removed from the table when its usage count equals zero. Because more than one application can obtain the handle of a particular string, an application must not free a string handle more times than it has created or retained the handle. Otherwise, the application can cause the string to be removed from the table, denying other applications access to the string.

The DDEML string-management functions are based on the Windows atom manager and are subject to the same size restrictions as are atoms.


 Name Service

The DDEML makes it possible for a server application to register the service names that it supports and to prevent the DDEML from sending XTYP_CONNECT transactions for unsupported service names to the server's DDE callback function. The remaining topics in this section describe the name service.


 Service Name Registration

By registering its service names with the DDEML, a server informs other DDE applications in the system that a new server is available. A server registers a service name by calling the DdeNameService function and specifying a string handle that identifies the name. In response, the DDEML sends an XTYP_REGISTER transaction to the callback function of each DDEML application in the system (except those that specified the CBF_SKIP_REGISTRATIONS filter flag in the DdeInitialize function). The XTYP_REGISTER transaction passes two string handles to a callback function: the first identifies the string specifying the base service name, and the second identifies the string specifying the instance-specific service. A client typically uses the base service name in a list of available servers, so the user can select a server from the list. The client uses the instance-specific service name to establish a conversation with a specific instance of a server application, if more than one instance is running.

A server can use DdeNameService to unregister a service name. This function causes the DDEML to send XTYP_UNREGISTER transactions to the other DDE applications in the system, informing them that they can no longer use the name to establish conversations.

A server must call DdeNameService to register its service names soon after calling DdeInitialize. A server must unregister its service names by using DdeNameService just before calling the DdeUninitialize function.


 Service Name Filter

In addition to registering service names, DdeNameService enables a server to turn its service name filter on or off. When a server turns off its service name filter, the DDEML sends the XTYP_CONNECT transaction to the server's DDE callback function whenever any client calls the DdeConnect function, regardless of the service name specified in the function. When a server turns on its service name filter, the DDEML sends the XTYP_CONNECT transaction to the server only when DdeConnect specifies a service name the server has specified in a call to DdeNameService.

By default, the service name filter is on when an application calls DdeInitialize. This default prevents the DDEML from sending the XTYP_CONNECT transaction to a server before the server has created the string handles it needs. A server can turn off its service name filter by specifying the DNS_FILTEROFF flag in a call to DdeNameService. The DNS_FILTERON flag turns on the filter.


 Conversation Management

A conversation between a client and a server is always established at the request of the client. When a conversation is established, each partner receives a handle that identifies the conversation. The partners use this handle in other DDEML functions to send transactions and manage the conversation. A client can request a conversation with a single server, or it can request multiple conversations with one or more servers.

The remaining topics in this section describe how an application establishes new conversations and gets information about existing conversations.


 Single Conversations

A client application requests a single conversation with a server by calling the DdeConnect function and specifying string handles that identify the strings containing the service name of the server application and the topic name for the conversation. The DDEML responds by sending the XTYP_CONNECT transaction to the DDE callback function of each server application that either has registered a service name that matches the one specified in DdeConnect or has turned service name filtering off by calling DdeNameService. A server can also filter XTYP_CONNECT transactions by specifying the CBF_FAIL_CONNECTIONS filter flag in the DdeInitialize function. During the XTYP_CONNECT transaction, the DDEML passes the service name and the topic name to the server. The server must examine the names and return TRUE if it supports the service name and topic name pair or FALSE if it does not.

If no server responds positively to the client's request to connect, the client receives NULL from DdeConnect and no conversation is established. If a server returns TRUE, a conversation is established and the client receives a conversation handle — a doubleword value that identifies the conversation. The client uses the handle in subsequent DDEML calls to obtain data from the server. The server receives the XTYP_CONNECT_CONFIRM transaction (unless the server specified the CBF_SKIP_CONNECT_CONFIRMS filter flag). This transaction passes the conversation handle to the server.

The following example requests a conversation on the System topic with a server that recognizes the service name MyServer. The hszServName and hszSysTopic parameters are previously created string handles.

HCONV hConv;         /* conversation handle            */

HWND hwndParent;     /* parent window handle           */

HSZ hszServName;     /* service name string handle     */

HSZ hszSysTopic;     /* System topic string handle     */

.

.

hConv = DdeConnect(

    idInst,               /* instance identifier        */

    hszServName,          /* service name string handle */

    hszSysTopic,          /* System topic string handle */

    (PCONVCONTEXT) NULL); /* use default context        */

if (hConv == NULL) {

    MessageBox(hwndParent, "MyServer is unavailable.",

        (LPSTR) NULL, MB_OK);

    return FALSE;

}

.

.

.

In the preceding example, DdeConnect causes the DDE callback function of the MyServer application to receive an XTYP_CONNECT transaction.

In the following example, the server responds to the XTYP_CONNECT transaction by comparing the topic name string handle the DDEML passed to the server with each element in the array of topic name string handles the server supports. If the server finds a match, it establishes the conversation.

#define CTOPICS 5

HSZ hsz1;                  /* string handle passed by DDEML  */

HSZ ahszTopics[CTOPICS];   /* array of supported topics      */

int i;                     /* loop counter                   */

.

. /* Use a switch statement to examine transaction types. */

.

case XTYP_CONNECT:

    for (i = 0; i < CTOPICS; i++) {

        if (hsz1 == ahszTopics[i])

            return TRUE;   /* establish a conversation       */

    }

    return FALSE; /* topic not supported; deny conversation  */

.

. /* Process other transaction types. */

.

If the server returns TRUE in response to the XTYP_CONNECT transaction, the DDEML sends an XTYP_CONNECT_CONFIRM transaction to the server's DDE callback function. The server can obtain the handle for the conversation by processing this transaction.

A client can establish a wildcard conversation by specifying NULL for the service name string handle, the topic name string handle, or both in a call to DdeConnect. If at least one of the string handles is NULL, the DDEML sends the XTYP_WILDCONNECT transaction to the callback functions of all DDE applications (except those that filter the XTYP_WILDCONNECT transaction). Each server application should respond by returning a data handle that identifies a null-terminated array of HSZPAIR structures. If the server application has not called DdeNameService to register its service names and if filtering is on, the server does not receive XTYP_WILDCONNECT transactions. For more information about data handles, see Data Management.

The array must contain one structure for each service name and topic name pair that matches the pair specified by the client. The DDEML selects one of the pairs to establish a conversation and returns to the client a handle that identifies the conversation. The DDEML sends the XTYP_CONNECT_CONFIRM transaction to the server (unless the server filters this transaction). The following example shows a typical server response to the XTYP_WILDCONNECT transaction.

#define CTOPICS 2

UINT uType;

HSZPAIR ahszp[(CTOPICS + 1)];

HSZ ahszTopicList[CTOPICS];

HSZ hszServ, hszTopic;

WORD i, j;

if (uType == XTYP_WILDCONNECT) {

     /*

      * Scan the topic list and create an array of HSZPAIR

      * structures.

      */

    j = 0;

    for (i = 0; i < CTOPICS; i++) {

        if (hszTopic == (HSZ) NULL ||

                hszTopic == ahszTopicList[i]) {

            ahszp[j].hszSvc = hszServ;

            ahszp[j++].hszTopic = ahszTopicList[i];

        }

    }

    /*

     * End the list with an HSZPAIR structure that contains NULL

     * string handles as its members.

     */

    ahszp[j].hszSvc = NULL;

    ahszp[j++].hszTopic = NULL;

    /*

     * Return a handle to a global memory object containing the

     * HSZPAIR structures.

     */

    return DdeCreateDataHandle(

        idInst,          /* instance identifier     */

        (LPBYTE) &ahszp, /* points to HSZPAIR array */

        sizeof(HSZ) * j, /* length of the array     */

        0,               /* start at the beginning  */

        (HSZ) NULL,      /* no item name string     */

        0,               /* return the same format  */

        0);              /* let the system own it   */

}

Either the client or the server can terminate a conversation at any time by calling the DdeDisconnect function. This function causes the callback function of the partner in the conversation to receive the XTYP_DISCONNECT transaction (unless the partner specified the CBF_SKIP_DISCONNECTS filter flag). Typically, an application responds to the XTYP_DISCONNECT transaction by using the DdeQueryConvInfo function to obtain information about the conversation that terminated. After the callback function returns from processing the XTYP_DISCONNECT transaction, the conversation handle is no longer valid.

A client application that receives an XTYP_DISCONNECT transaction in its DDE callback function can attempt to reestablish the conversation by calling the DdeReconnect function. The client must call DdeReconnect from within its DDE callback function.


 Multiple Conversations

A client application can use the DdeConnectList function to determine whether any servers of interest are available in the system. A client specifies a service name and topic name when it calls DdeConnectList, causing the DDEML to broadcast the XTYP_WILDCONNECT transaction to the DDE callback functions of all servers that match the service name (except those that filter the transaction). A server's callback function should return a data handle that identifies a null-terminated array of HSZPAIR structures. The array should contain one structure for each service name and topic name pair that matches the pair specified by the client. The DDEML establishes a conversation for each HSZPAIR structure filled by the server and returns a conversation list handle to the client. The server receives the conversation handle by way of the XTYP_CONNECT_CONFIRM transaction (unless the server filters this transaction).

A client can specify NULL for the service name, topic name, or both when it calls DdeConnectList. If the service name is NULL, all servers in the system that support the specified topic name respond. A conversation is established with each responding server, including multiple instances of the same server. If the topic name is NULL, a conversation is established on each topic recognized by each server that matches the service name.

A client can use the DdeQueryNextServer and DdeQueryConvInfo functions to identify the servers that respond to DdeConnectList. DdeQueryNextServer returns the next conversation handle in a conversation list, and DdeQueryConvInfo fills a CONVINFO structure with information about the conversation. The client can keep the conversation handles that it needs and discard the rest from the conversation list.

The following example uses DdeConnectList to establish conversations with all servers that support the System topic and then uses the DdeQueryNextServer and DdeQueryConvInfo functions to obtain the servers' service name string handles and store them in a buffer.

HCONVLIST hconvList; /* conversation list       */

DWORD idInst;        /* instance identifier     */

HSZ hszSystem;       /* System topic            */

HCONV hconv = NULL;  /* conversation handle     */

CONVINFO ci;         /* holds conversation data */

UINT cConv = 0;      /* count of conv. handles  */

HSZ *pHsz, *aHsz;    /* point to string handles */

/* Connect to all servers that support the System topic. */

hconvList = DdeConnectList(idInst, NULL, hszSystem, NULL, NULL);

/* Count the number of handles in the conversation list. */

while ((hconv = DdeQueryNextServer(hconvList, hconv)) != NULL)

    cConv++;

/* Allocate a buffer for the string handles. */

hconv = NULL;

aHsz = (HSZ *) LocalAlloc(LMEM_FIXED, cConv * sizeof(HSZ));

/* Copy the string handles to the buffer. */

pHsz = aHsz;

while ((hconv = DdeQueryNextServer(hconvList, hconv)) != NULL) {

    DdeQueryConvInfo(hconv, QID_SYNC, (PCONVINFO) &ci);

    DdeKeepStringHandle(idInst, ci.hszSvcPartner);

    *pHsz++ = ci.hszSvcPartner;

}

.

. /* Use the handles; converse with the servers. */

.

/* Free the memory and terminate the conversations. */

LocalFree((HANDLE) aHsz);

DdeDisconnectList(hconvList);

An application can terminate an individual conversation in a conversation list by calling the DdeDisconnect function. An application can terminate all conversations in a conversation list by calling the DdeDisconnectList function. Both functions cause the DDEML to send XTYP_DISCONNECT transactions to each partner's DDE callback function. DdeDisconnectList sends an XTYP_DISCONNECT transaction for each conversation handle in the list.

A client can retrieve a list of the conversation handles in a conversation list by passing an existing conversation list handle to DdeConnectList. The enumeration process removes the handles of terminated conversations from the list, and nonduplicate conversations that fit the specified service name and topic name are added.

If DdeConnectList specifies an existing conversation list handle, the function creates a new conversation list that contains the handles of any new conversations and the handles from the existing list.

If duplicate conversations exist, DdeConnectList attempts to prevent duplicate conversation handles in the conversation list. A duplicate conversation is a second conversation with the same server on the same service name and topic name. Two such conversations would have different handles, yet they would identify the same conversation.


 Data Management

Because DDE uses memory objects to pass data from one application to another, the DDEML provides a set of functions that DDE applications can use to create and manage DDE objects.

All transactions that involve the exchange of data require the application supplying the data to create a local buffer containing the data and then to call the DdeCreateDataHandle function. This function allocates a DDE object, copies the data from the buffer to the object, and returns a data handle. A data handle is a doubleword value that the DDEML uses to provide access to data in the DDE object. To share the data in a DDE object, an application passes the data handle to the DDEML, and the DDEML passes the handle to the DDE callback function of the application that is receiving the data transaction.

The following example shows how to create a DDE object and obtain a handle of the object. During the XTYP_ADVREQ transaction, the callback function converts the current time to an ASCII string, copies the string to a local buffer, and then creates a DDE object that contains the string. The callback function returns the handle of the DDE object (HDDEDATA) to the DDEML, which passes the handle to the client application.

typedef struct tagTIME

  {

    INT     hour;   /* 0 - 11 hours for analog clock */

    INT     hour12; /* 12-hour format */

    INT     hour24; /* 24-hour format */

    INT     minute;

    INT     second;

    INT     ampm;   /* 0 - AM , 1 - PM */

  } TIME;

HDDEDATA EXPENTRY DdeCallback(uType, uFmt, hconv, hsz1, hsz2,

    hdata, dwData1, dwData2)

UINT uType;

UINT uFmt;

HCONV hconv;

HSZ hsz1;

HSZ hsz2;

HDDEDATA hdata;

DWORD dwData1;

DWORD dwData2;

{

    CHAR szBuf[32];

    switch (uType) {

    case XTYP_ADVREQ:

        if ((hsz1 == hszTime && hsz2 == hszNow) &&

                (uFmt == CF_TEXT)) {

            /* Copy the formatted string to a buffer. */

            itoa(tmTime.hour, szBuf, 10);

            lstrcat(szBuf, ":");

            if (tmTime.minute < 10)

                lstrcat(szBuf, "0");

            itoa(tmTime.minute, &szBuf[lstrlen(szBuf)], 10);

            lstrcat(szBuf, ":");

            if (tmTime.second < 10)

                strcat(szBuf, "0");

            itoa(tmTime.second, &szBuf[lstrlen(szBuf)], 10);

            szBuf[lstrlen(szBuf)] = '\0';

            /* Create a global object and return its data handle. */

            return (DdeCreateDataHandle(

                idInst,

                (LPBYTE) szBuf,     /* instance identifier   */

                lstrlen(szBuf) + 1, /* source buffer length  */

                0,                  /* offset from beginning */

                hszNow,             /* item name string      */

                CF_TEXT,            /* clipboard format      */

                0));                /* no creation flags     */

        } else

            return (HDDEDATA) NULL;

    .

    . /* Process other transactions. */

    .

    }

}

The receiving application obtains a pointer to the DDE object by passing the data handle to the DdeAccessData function. The pointer returned by DdeAccessData provides read-only access. The application should use the pointer to review the data and then call the DdeUnaccessData function to invalidate the pointer. The application can copy the data to a local buffer by using the DdeGetData function.

The following example obtains a pointer to the DDE object identified by the hData parameter, copies the contents to a local buffer, and then invalidates the pointer.

HDDEDATA hdata;

LPBYTE lpszAdviseData;

DWORD cbDataLen;

DWORD i;

char szData[32];

.

.

.

case XTYP_ADVDATA:

    lpszAdviseData = DdeAccessData(hdata, &cbDataLen);

    for (i = 0; i < cbDataLen; i++)

        szData[i] = *lpszAdviseData++;

    DdeUnaccessData(hdata);

    return (HDDEDATA) TRUE;

.

.

.

Usually, when an application that created a data handle passes that handle to the DDEML, the handle becomes invalid in the creating application. This situation is not a problem if the application must share data with only a single application. If an application must share the same data with multiple applications, however, the creating application should specify the HDATA_APPOWNED flag in DdeCreateDataHandle. Doing so gives ownership of the DDE object to the creating application and prevents the DDEML from invalidating the data handle. The application can then pass the data handle any number of times after calling DdeCreateDataHandle only once.

If an application specifies the HDATA_APPOWNED flag in the afCmd parameter of DdeCreateDataHandle, it must call the DdeFreeDataHandle function to free the memory handle, regardless of whether it passed the handle to the DDEML. Before it terminates, an application must call DdeFreeDataHandle to free any data handle that it created but did not pass to the DDEML.

An application that has not yet passed the handle of a DDE object to the DDEML can add data to the object or overwrite data in the object by using the DdeAddData function. Typically, an application uses DdeAddData to fill an uninitialized DDE object. After an application passes a data handle to the DDEML, the DDE object identified by the handle cannot be changed; it can only be freed.


 Transaction Management

After establishing a conversation with a server, a client can send transactions to obtain data and services from the server. The remaining topics in this section describe the types of transactions that clients can use to interact with a server.


 Request Transaction

A client application can use the XTYP_REQUEST transaction to request a data item from a server application. The client calls the DdeClientTransaction function, specifying XTYP_REQUEST as the transaction type and specifying the data item the application needs.

The DDEML passes the XTYP_REQUEST transaction to the server, specifying the topic name, item name, and data format requested by the client. If the server supports the requested topic, item, and format, the server should return a data handle that identifies the current value of the item. The DDEML passes this handle to the client as the return value from DdeClientTransaction. The server should return NULL if it does not support the topic, item, or format requested.

DdeClientTransaction uses the lpdwResult parameter to return a transaction-status flag to the client. If the server does not process the XTYP_REQUEST transaction, DdeClientTransaction returns NULL, and lpdwResult points to the DDE_FNOTPROCESSED or DDE_FBUSY flag. If the DDE_FNOTPROCESSED flag is returned, the client cannot determine why the server did not process the transaction.

If a server does not support the XTYP_REQUEST transaction, it should specify the CBF_FAIL_REQUESTS filter flag in the DdeInitialize function. This flag prevents the DDEML from sending the transaction to the server.


 Poke Transaction

A client can send unsolicited data to a server by using DdeClientTransaction to send an XTYP_POKE transaction to a server's callback function.

The client application first creates a buffer that contains the data to send to the server and then passes a pointer to the buffer as a parameter to DdeClientTransaction. Alternatively, the client can use the DdeCreateDataHandle function to obtain a data handle that identifies the data and then pass the handle to DdeClientTransaction. In either case, the client also specifies the topic name, item name, and data format when it calls DdeClientTransaction.

The DDEML passes the XTYP_POKE transaction to the server, specifying the topic name, item name, and data format that the client requested. To accept the data item and format, the server should return DDE_FACK. To reject the data, the server should return DDE_FNOTPROCESSED. If the server is too busy to accept the data, the server should return DDE_FBUSY.

When DdeClientTransaction returns, the client can use the lpdwResult parameter to access the transaction-status flag. If the flag is DDE_FBUSY, the client should send the transaction again later.

If a server does not support the XTYP_POKE transaction, it should specify the CBF_FAIL_POKES filter flag in DdeInitialize. This flag prevents the DDEML from sending this transaction to the server.


 Advise Transaction

A client application can use the DDEML to establish one or more links to items in a server application. When such a link has been established, the server sends periodic updates about the linked item to the client (typically, whenever the value of the item associated with the server application changes). Linking establishes an advise loop between the two applications that remains in place until the client ends it.

There are two kinds of advise loops: "hot" and "warm." In a hot advise loop, the server immediately sends a data handle that identifies the changed value. In a warm advise loop, the server notifies the client that the value of the item has changed but does not send the data handle until the client requests it.

A client can request a hot advise loop with a server by specifying the XTYP_ADVSTART transaction type in a call to DdeClientTransaction. To request a warm advise loop, the client must combine the XTYPF_NODATA flag with the XTYP_ADVSTART transaction type. In either event, the DDEML passes the XTYP_ADVSTART transaction to the server's DDE callback function. The server's DDE callback function should examine the parameters that accompany the XTYP_ADVSTART transaction (including the requested format, topic name, and item name) and then return TRUE to allow the advise loop or FALSE to deny it.

After an advise loop has been established, the server application should call the DdePostAdvise function whenever the value of the item associated with the requested item name changes. This call results in an XTYP_ADVREQ transaction being sent to the server's own DDE callback function. The server's DDE callback function should return a data handle that identifies the new value of the data item. The DDEML then notifies the client that the specified item has changed by sending the XTYP_ADVDATA transaction to the client's DDE callback function.

If the client requested a hot advise loop, the DDEML passes the data handle for the changed item to the client during the XTYP_ADVDATA transaction. Otherwise, the client can send an XTYP_REQUEST transaction to obtain the data handle.

It is possible for a server to send updates faster than a client can process the new data. The speed of updates can be a problem for a client that must perform lengthy processing operations on the data. In this case, the client should specify the XTYPF_ACKREQ flag when it requests an advise loop. This flag causes the server to wait for the client to acknowledge that it has received and processed a data item before the server sends the next data item. Advise loops that are established with the XTYPF_ACKREQ flag are more robust with fast servers but may occasionally miss updates. Advise loops established without the XTYPF_ACKREQ flag are guaranteed not to miss updates as long as the client keeps up with the server.

A client can end an advise loop by specifying the XTYP_ADVSTOP transaction type in a call to DdeClientTransaction.

If a server does not support advise loops, it should specify the CBF_FAIL_ADVISES filter flag in the DdeInitialize function. This flag prevents the DDEML from sending the XTYP_ADVSTART and XTYP_ADVSTOP transactions to the server.


 Execute Transaction

A client can use the XTYP_EXECUTE transaction to cause a server to execute a command or a series of commands.

To execute a server command, the client first creates a buffer that contains a command string for the server to execute and then passes either a pointer to the buffer or a data handle identifying the buffer when it calls DdeClientTransaction. Other required parameters include the conversation handle, the item name string handle, the format specification, and the XTYP_EXECUTE transaction type. An application that creates a data handle for passing execute data must specify NULL for the hszItem parameter of the DdeCreateDataHandle function and zero for the uFmt parameter.

The DDEML passes the XTYP_EXECUTE transaction to the server's DDE callback function and specifies the format name, conversation handle, topic name, and data handle identifying the command string. If the server supports the command, it should use the DdeAccessData function to obtain a pointer to the command string, execute the command, and then return DDE_FACK. If the server does not support the command or cannot complete the transaction, it should return DDE_FNOTPROCESSED. The server should return DDE_FBUSY if it is too busy to complete the transaction.

In general, a server's callback function should process the XTYP_EXECUTE transaction before returning with the following exceptions:

1.	When the command passed with the XTYP_EXECUTE transaction requests the server to terminate, the server should not terminate until its callback function returns from processing XTYP_EXECUTE.

2.	If the server must perform an operation, such as processing a dialog box or a DDE transaction that might cause DDEML recursion problems, the server should return the CBR_BLOCK return code to block the execute transaction, perform the operation, and then resume processing the execute transaction.

When DdeClientTransaction returns, the client can use the lpdwResult parameter to access the transaction status flag. If the flag is DDE_FBUSY, the client should send the transaction again later.

If a server does not support the XTYP_EXECUTE transaction, it should specify the CBF_FAIL_EXECUTES filter flag in the DdeInitialize function. Doing so prevents the DDEML from sending the transaction to the server.


 Synchronous and Asynchronous Transactions

A client can send either synchronous or asynchronous transactions. In a synchronous transaction, the client specifies a time-out value that indicates the maximum amount of time it will wait for the server to process the transaction. DdeClientTransaction does not return until the server processes the transaction, the transaction fails, or the time-out value expires. The client specifies the time-out value when it calls DdeClientTransaction.

During a synchronous transaction, the client enters a modal loop while waiting for the transaction to be processed. The client can still process user input but cannot send another synchronous transaction until DdeClientTransaction returns.

A client sends an asynchronous transaction by specifying the TIMEOUT_ASYNC flag in DdeClientTransaction. The function returns after the transaction has begun, passing a transaction identifier to the client. When the server finishes processing the asynchronous transaction, the DDEML sends an XTYP_XACT_COMPLETE transaction to the client. One of the parameters that the DDEML passes to the client during the XTYP_XACT_COMPLETE transaction is the transaction identifier. By comparing this transaction identifier with the identifier returned by DdeClientTransaction, the client identifies which asynchronous transaction the server has finished processing.

A client can use the DdeSetUserHandle function as an aid in processing an asynchronous transaction. This function makes it possible for a client to associate an application-defined doubleword value with a conversation handle and a transaction identifier. The client can use the DdeQueryConvInfo function during the XTYP_XACT_COMPLETE transaction to obtain the application-defined doubleword value. Because of this function, an application need not maintain a list of active transaction identifiers.

When a client successfully completes a request for data using a synchronous transaction, the DDEML has no way to tell when the client has finished using the data received. The client application must pass the data handle received to the DdeFreeDataHandle function, notifying the DDEML that the handle will no longer be used. Data handles returned by synchronous transactions are effectively owned by the client.

If a server does not process an asynchronous transaction in a timely manner, the client can abandon the transaction by calling the DdeAbandonTransaction function. The DDEML releases all resources associated with the transaction and discards the results of the transaction when the server finishes processing it. A time-out during a synchronous transaction effectively cancels the transaction.

The asynchronous transaction method is provided for applications that must send a high volume of DDE transactions while simultaneously performing a substantial amount of processing, such as performing calculations. The asynchronous method is also useful in applications that must stop processing DDE transactions temporarily so they can complete other tasks without interruption. In most other situations, an application should use the synchronous method.

Synchronous transactions are simpler to maintain and are faster than asynchronous transactions. However, only one synchronous transaction can be performed at a time, whereas many asynchronous transactions can be performed simultaneously. With synchronous transactions, a slow server can cause a client to remain idle while it is waiting for a response. Also, synchronous transactions cause the client to enter a modal loop that could bypass message filtering in the application's own message loop.

If the client has installed a hook procedure to filter messages (that is, specified the WH_MSGFILTER hook type in a call to the SetWindowsHookEx function), a synchronous transaction will not cause the system to bypass the hook procedure. When an input event occurs while the client is waiting for a synchronous transaction to end, the hook procedure receives an MSGF_DDEMGR hook code. The main danger of using a synchronous transaction modal loop is that a modal loop created by a dialog box can interfere with its operation. Asynchronous transactions should always be used when the DDEML is being used by a dynamic-link library (DLL).


 Transaction Control

An application can suspend transactions to its DDE callback function — either those transactions associated with a specific conversation handle or all transactions regardless of the conversation handle. This capability is useful when an application receives a transaction that requires lengthy processing. In such a case, the application can return the CBR_BLOCK return code to suspend future transactions associated with the transaction's conversation handle, so that the application is free to process other conversations.

When processing has been completed, the application calls the DdeEnableCallback function to resume transactions associated with the suspended conversation. Calling DdeEnableCallback causes the DDEML to resend the transaction that resulted in the application suspending the conversation. Therefore, the application should store the result of the transaction in such a way that it can obtain and return the result without reprocessing the transaction.

An application can suspend all transactions associated with a specific conversation handle by specifying the handle and the EC_DISABLE flag in a call to DdeEnableCallback. By specifying a NULL handle, an application can suspend all transactions for all conversations.

When a conversation has been suspended, the DDEML saves transactions for the conversation in a transaction queue. When the application reenables the conversation, the DDEML removes the saved transactions from the queue and passes each transaction to the appropriate callback function. The capacity of the transaction queue is large, but an application should reenable a suspended conversation as soon as possible to avoid losing transactions.

An application can resume usual transaction processing by specifying the EC_ENABLEALL flag in DdeEnableCallback. For a more controlled resumption of transaction processing, the application can specify the EC_ENABLEONE flag. This flag removes one transaction from the transaction queue and passes it to the appropriate callback function; after that transaction has been processed, any conversations are again disabled.

If the EC_ENABLEONE flag and a conversation handle are specified in the call to DdeEnableCallback, only that conversation is blocked after the transaction has been processed. If a NULL conversation handle is specified, all conversations are blocked after a transaction has been processed in any conversation.


 Transaction Classes

The DDEML has four classes of transactions. Each class is identified by a constant that begins with the XCLASS_ prefix. The classes are defined in the DDEML header file. The class value is combined with the transaction-type value and is passed to the DDE callback function of the receiving application.

A transaction's class determines the return value that a callback function is expected to return if it processes the transaction. The following return values and transaction types are associated with each of the four transaction classes.

Class	Return value	Transaction
XCLASS_BOOL	TRUE or FALSE	XTYP_ADVSTART XTYP_CONNECT
XCLASS_DATA	A data handle, the CBR_BLOCK return code, or NULL	XTYP_ADVREQ XTYP_REQUEST XTYP_WILDCONNECT
XCLASS_FLAGS	A transaction flag: DDE_FACK, DDE_FBUSY, or DDE_FNOTPROCESSED	XTYP_ADVDATA XTYP_EXECUTE XTYP_POKE
XCLASS_NOTIFICATION	None	XTYP_ADVSTOP XTYP_CONNECT_ CONFIRM  XTYP_DISCONNECT XTYP_ERROR XTYP_REGISTER XTYP_UNREGISTER XTYP_XACT_ COMPLETE


 Transaction Types

Each DDE transaction type has a receiver and an associated activity that causes the DDEML to generate each type.

Transaction type	Receiver	Cause
XTYP_ADVDATA	Client	A server responded to an XTYP_ADVREQ transaction by returning a data handle.
XTYP_ADVREQ	Server	A server called the DdePostAdvise function, indicating that the value of a data item in an advise loop had changed.
XTYP_ADVSTART	Server	A client specified the XTYP_ADVSTART transaction type in a call to the DdeClientTransaction function.
XTYP_ADVSTOP	Server	A client specified the XTYP_ADVSTOP transaction type in a call to DdeClientTransaction.
XTYP_CONNECT	Server	A client called the DdeConnect function and specified a service name and topic name supported by the server.
XTYP_CONNECT_CONFIRM	Server	The server returned TRUE in response to an XTYP_CONNECT or XTYP_WILDCONNECT transaction.
XTYP_DISCONNECT	Client/Server	A partner in a conversation called the DdeDisconnect function, causing both partners to receive this transaction.
XTYP_ERROR	Client/Server	A critical error has occurred. The DDEML may not have sufficient resources to continue.
XTYP_EXECUTE	Server	A client specified the XTYP_EXECUTE transaction type in a call to DdeClientTransaction.
XTYP_MONITOR	DDE monitoring application	A DDE event occurred in the system. For more information about DDE monitoring applications, see Monitoring Applications.
XTYP_POKE	Server	A client specified the XTYP_POKE transaction type in a call to DdeClientTransaction.
XTYP_REGISTER	Client/Server	A server application used the DdeNameService function to register a service name.
XTYP_REQUEST	Server	A client specified the XTYP_REQUEST transaction type in a call to DdeClientTransaction.
XTYP_UNREGISTER	Client/Server	A server application used DdeNameService to unregister a service name.
XTYP_WILDCONNECT	Server	A client called the DdeConnect or DdeConnectList function, specifying NULL for the service name, the topic name, or both.
XTYP_XACT_COMPLETE	Client	An asynchronous transaction, sent when the client specified the TIMEOUT_ASYNC flag in a call to DdeClientTransaction, has concluded.


 Error Detection for DDEML Functions

Whenever a DDEML function fails, an application can call the DdeGetLastError function to determine the cause of the failure. DdeGetLastError returns an error value that specifies the cause of the most recent error.


 Monitoring Applications

The application programming interface (API) elements of the DDEML can be used to create an application that monitors DDE activity in the system. Like any DDEML application, a DDE monitoring application contains a DDE callback function. The DDEML notifies a monitoring application's DDE callback function whenever a DDE event occurs, passing information about the event to the callback function. The application typically displays the information in a window or writes it to a file.

To receive notifications from the DDEML, an application must have registered as a DDE monitor by specifying the APPCLASS_MONITOR flag in a call to the DdeInitialize function. In this same call, the application can specify one or more monitor flags to indicate the types of events for which the DDEML is to notify the application's callback function. The following monitor flags can be specified by an application:

Flag	Description
MF_CALLBACKS	Notifies the callback function whenever a transaction is sent to any DDE callback function in the system.
MF_CONV	Notifies the callback function whenever a conversation is established or terminated.
MF_ERRORS	Notifies the callback function whenever a DDEML error occurs.
MF_HSZ_INFO	Notifies the callback function whenever a DDEML application creates, frees, or increments the usage count of a string handle or whenever a string handle is freed as a result of a call to the DdeUninitialize function.
MF_LINKS	Notifies the callback function whenever an advise loop is started or ended.
MF_POSTMSGS	Notifies the callback function whenever the system or an application posts a DDE message.
MF_SENDMSGS	Notifies the callback function whenever the system or an application sends a DDE message.
The following example shows how to register a DDE monitoring application so that its DDE callback function receives notifications of all DDE events.

DWORD idInst;

PFNCALLBACK lpDdeProc;

hInst = hInstance;

if (DdeInitialize(

        (LPDWORD) &idInst,  /* instance identifier              */

        DDECallback,        /* points to callback function      */

        APPCLASS_MONITOR |  /* this is a monitoring application */

        MF_CALLBACKS     |  /* monitor callback functions       */

        MF_CONV          |  /* monitor conversation data        */

        MF_ERRORS        |  /* monitor DDEML errors             */

        MF_HSZ_INFO      |  /* monitor data handle activity     */

        MF_LINKS         |  /* monitor advise loops             */

        MF_POSTMSGS      |  /* monitor posted DDE messages      */

        MF_SENDMSGS,        /* monitor sent DDE messages        */

        0))                 /* reserved                         */

    return FALSE;

The DDEML informs a monitoring application of a DDE event by sending an XTYP_MONITOR transaction to the application's DDE callback function. During this transaction, the DDEML passes a monitor flag that specifies the type of DDE event that has occurred and a handle of a DDE object that contains detailed information about the event. The DDEML provides a set of structures that the application can use to extract the information from the DDE object. There is a corresponding structure for each type of DDE event.

Structure	Description
MONCBSTRUCT	Contains information about a transaction.
MONCONVSTRUCT	Contains information about a conversation.
MONERRSTRUCT	Contains information about the latest DDE error.
MONLINKSTRUCT	Contains information about an advise loop.
MONHSZSTRUCT	Contains information about a string handle.
MONMSGSTRUCT	Contains information about a DDE message that was sent or posted.
The following example shows the DDE callback function of a DDE monitoring application that formats information about each string handle event and then displays the information in a window. The function uses the MONHSZSTRUCT structure to extract the information from the DDE object.

HDDEDATA CALLBACK DDECallback(uType, uFmt, hconv, hsz1, hsz2,

    hdata, dwData1, dwData2)

UINT uType;

UINT uFmt;

HCONV hconv;

HSZ hsz1;

HSZ hsz2;

HDDEDATA hdata;

DWORD dwData1;

DWORD dwData2;

{

    LPVOID lpData;

    CHAR *szAction;

    CHAR szBuf[256];

    DWORD cb;

    switch (uType) {

        case XTYP_MONITOR:

            /* Obtain a pointer to the global memory object. */

            if (lpData = DdeAccessData(hdata, &cb)) {

                /* Examine the monitor flag. */

                switch (dwData2) {

                    case MF_HSZ_INFO:

#define PHSZS ((MONHSZSTRUCT FAR *)lpData)

                        /*

                         * The global memory object contains

                         * string handle data. Use the MONHSZSTRUCT

                         * structure to access the data.

                         */

                        switch (PHSZS->fsAction) {

                            /*

                             * Examine the action flags to

                             * determine the action performed on

                             * the handle.

                             */

                            case MH_CREATE:

                                szAction = "Created";

                                break;

                            case MH_KEEP:

                                szAction = "Incremented";

                                break;

                            case MH_DELETE:

                                szAction = "Deleted";

                                break;

                            case MH_CLEANUP:

                                szAction = "Cleaned up";

                                break;

                            default:

                                DdeUnaccessData(hdata);

                                return (HDDEDATA) 0;

                        }

                        /* Write formatted output to a buffer. */

                        wsprintf(szBuf,

                            "Handle %s, Task: %x, Hsz: %lx(%s)",

                            (LPSTR) szAction, PHSZS->hTask,

                            PHSZS->hsz, (LPSTR) PHSZS->str);

                        .

                        . /* Display text or write to a file. */

                        .

                        break;

#undef PHSZS

                    .

                    . /* Process other MF_* flags. */

                    .

                    default:

                        break;

                }

            }

            /* Free the global memory object. */

            DdeUnaccessData(hdata);

            break;

        default:

            break;

    }

    return (HDDEDATA) 0;

}


 Dynamic Data Exchange Management Functions

Following are the functions used to manage dynamic data exchange.

DdeAbandonTransaction
DdeAccessData
DdeAddData
DdeCallback
DdeClientTransaction
DdeCmpStringHandles
DdeConnect
DdeConnectList
DdeCreateDataHandle
DdeCreateStringHandle
DdeDisconnect
DdeDisconnectList
DdeEnableCallback
DdeFreeDataHandle
DdeFreeStringHandle
DdeGetData
DdeGetLastError
DdeInitialize
DdeKeepStringHandle
DdeNameService
DdePostAdvise
DdeQueryConvInfo
DdeQueryNextServer
DdeQueryString
DdeReconnect
DdeSetUserHandle
DdeUnaccessData
DdeUninitialize


 Dynamic-Link Libraries

In Microsoft® Windows®, dynamic linking provides a way for a process to call a function that is not part of its executable code. The executable code for the function is located in a dynamic-link library (DLL), containing one or more functions that are compiled, linked, and stored separately from the processes using them. The Microsoft® Win32® application programming interface (API) is implemented as a set of dynamic-link libraries, so any process using the Win32 API uses dynamic linking.


 About Dynamic-Link Libraries

Dynamic linking allows an executable module (either a .DLL or .EXE file) to include only the information needed at run time to locate the executable code for a DLL function. This type of linking differs from the more familiar static linking, which requires a copy of a library function's executable code in the executable module of each application using it.

There are two methods for calling a function in a DLL:

•	Load-time dynamic linking occurs when an application's code makes an explicit call to a DLL function. This type of linking requires that the executable module of the application be built by linking with the DLL's import library, which supplies the information needed to locate the DLL function when the application starts. For more information, see Load-Time Dynamic Linking.

•	Run-time dynamic linking occurs when a program uses the LoadLibrary and GetProcAddress functions to get the starting address of a DLL function. This type of linking eliminates the need to link with an import library. For more information, see Using Run-Time Dynamic Linking.

A DLL attaches to a process when the process starts or when one of its threads calls the LoadLibrary function. When a DLL attaches to a process, the operating system maps the DLL module into the address space of the process, making the DLL's executable code available to the process. When a DLL detaches from a process at process termination or as a result of a call to the FreeLibrary function, the DLL module is unmapped from the address space of the process.

Like any other function, a DLL function is executed in the context of the thread (and the thread's process) that calls it. Therefore, the following conditions apply:

•	The threads of the process that called the DLL can use handles opened by a DLL function. Similarly, handles opened by any thread of the calling process can be used in the DLL function.

•	The DLL uses the user stack of the calling thread and the address space of the calling process.

•	Memory allocated by the DLL is in the address space of the calling process.

•	The threads of the process that called the DLL can read from or write to the globally declared variables in the DLL.


 Advantages of Dynamic Linking

Dynamic linking has the following advantages:

•	Many processes can use a single DLL simultaneously, sharing a single copy of the DLL in memory. Doing this saves memory space and reduces swapping.

•	When the functions in a DLL change, the applications that use them do not need to be recompiled or relinked as long as the functions' arguments and return values do not change. In contrast, statically linked object code requires that the application be relinked when the functions change.

•	A DLL can provide after-market support. For example, a display driver DLL can be modified to support a display that was not available when the application was shipped.

•	Programs written in different programming languages can call the same DLL function as long as the programs follow the function's calling convention. The programs and the DLL function must be compatible in the following ways: the order the function expects its arguments to be pushed onto the stack, whether the function or the application is responsible for cleaning up the stack, and whether any arguments are passed in registers.

A potential disadvantage to using DLLs is that the application is not self-contained; it depends on the existence of a separate DLL module. A process using load-time dynamic linking is terminated by the operating system if the DLL is not found at process startup. A process using run-time dynamic linking is not terminated in this situation, but capabilities provided by the DLL are not available to the program.


 Dynamic-Link Library Creation

To create a DLL, first create one or more source code (.C) files and a module-definition (.DEF) file. The .C file contains the exported functions for the DLL. The .DEF file lists these functions and defines other attributes of the DLL.

The compiler uses the .C file to create an object code (.OBJ) file. The library manager creates an export (.EXP) file and an import library (.LIB) file from the .DEF file.

Finally, the linker uses the .OBJ, .EXP, and .LIB files to build the executable files for the DLL. The .OBJ and .EXP files provide information the linker needs to build the .DLL file. The .LIB file contains information the linker needs to resolve external references to DLL functions, so that a program can locate the specified DLL at run time. The .LIB file enables the linker to build an executable module (.EXE or .DLL) that calls a function in the DLL. For more information about .DEF files, see Module-Definition File.

Note that the information in this section is based on using Win32 software development tools. For more detailed information about creating DLLs, see the documentation included with your development tools.


 Dynamic-Link Library Entry-Point Function

A DllEntryPoint function is an optional DLL function that the operating system calls to perform user-defined operations. DllEntryPoint is not a typical function; it is a reference to a function specified in the linker command line. A DLL is not required to have an entry-point function, but it can be useful for initializing and cleaning up processes and threads. The name of a DLL's entry-point function is specified by the -entry switch of the linker. For example, the following command line specifies LibMain as the entry-point function of MYDLL.DLL.

link -entry:LibMain -out:mydll.dll mydll.exp mydll.obj $(mylibs)

If an entry-point function is specified, the operating system causes it to be called whenever any of the following events occurs:

•	The DLL attaches to a process. For processes using load-time dynamic linking, attachment occurs during initialization. For processes using run-time linking, the DLL attaches and the entry-point function is called before LoadLibrary returns.

•	The DLL detaches from a process. Detachment occurs when the process terminates or when the DLL is unloaded by a call to the FreeLibrary function. If the process terminates as a result of the TerminateProcess or TerminateThread function, the system does not call the entry-point function.

•	The DLL attaches to a thread. Attachment occurs whenever a new thread is created in a process to which a DLL is attached.

•	The DLL detaches from a thread. Detachment occurs whenever a thread of an attached process terminates, except as a result of the TerminateThread or TerminateProcess function. When a DLL detaches from a process, the entry-point function is called only once for the entire process rather than once for each existing thread of the process.

The system causes the entry-point function to be called, but it is called in the context of a process or thread attaching to or detaching from the DLL. This allows a DLL to use its entry-point function for allocating memory in the address space of the process or to open handles accessible to the process. When it is called to attach a new thread, the entry-point function can allocate memory for thread local storage (TLS) that is private to the new thread. For more information about thread local storage, see Processes and Threads.

When a DLL's entry-point function is called for process attachment, it returns TRUE to indicate success. For processes using load-time linking, a return value of FALSE causes the process initialization to fail and the process terminates. For processes using run-time linking, a return value of FALSE causes the LoadLibrary function to return NULL, indicating failure. The return value of the entry-point function is disregarded when it is called for any other reasons, such as process detaching, thread attaching, or thread detaching.


 Module-Definition File

A module-definition (.DEF) file is a text file containing one or more module statements that describe various attributes of a DLL. The descriptions and examples in this section are based on the keywords and syntax used by the Win32 software development tools. For complete information about module-definition files, see the documentation included with your development tools.

A DLL requires a .DEF file to create an import library (.LIB) file and an export (.EXP) file. The linker uses the import library to build any executable module that uses the DLL and uses the export file to build the .DLL file.

A DLL's module-definition file must include a LIBRARY statement and an EXPORTS statement. The LIBRARY statement identifies the module-definition file as belonging to a DLL, and it must be the first statement in the file. The name specified in the LIBRARY statement identifies the library in the DLL's import library. The EXPORTS statement lists the names and, optionally, the ordinal values of the functions exported by the DLL. When ordinal values are specified, they must be in the range 1 through N, where N is the number of functions exported by the DLL.

The following .DEF file for a DLL exports three functions and associates an ordinal value with each function.

LIBRARY mydll

EXPORTS

    Func_A @1

    Func_B @2

    Func_C @3

The .DEF file can contain additional statements, specifying other attributes of a DLL. For example, the SECTIONS statements can change the default scope of global and static variables. The following SECTIONS statement makes the DLL's initialized data shared, but its uninitialized variables are not shared.

SECTIONS

    .data READ WRITE SHARED    ; share initialized variables


 Load-Time Dynamic Linking

Load-time dynamic linking occurs when an application's code explicitly calls a DLL function. When the source code is compiled or assembled, the DLL function call generates an external function reference in the object code. To resolve this external reference, the application must be linked with the import library for the DLL.

Finding an external function in an import library informs the linker that the code for that function is in a DLL. To resolve external references to DLLs, the linker simply adds information to the executable file that tells the system where to find the DLL code when the process starts up.

When the system starts a program that contains dynamically linked references, it uses the information in the program's executable file to locate the required DLLs. The system first searches the set of pre-installed DLLs, such as the performance library (KERNEL32.DLL) and the security library (USER32.DLL). The system then searches for the DLLs in the following sequence:

1.	The directory where the executable module for the current process is located.

2.	The current directory.

3.	The windows system directory. The GetSystemDirectory function retrieves the path of this directory.

4.	The windows directory. The GetWindowsDirectory function retrieves the path of this directory.

5.	The directories listed in the PATH environment variable.

Note that the LIBPATH environment variable is not used.

If it cannot locate a specified DLL, the system terminates the process and displays a dialog box that reports the error. Otherwise, the system maps the DLL modules into the process's address space.

If any of the DLLs has a DllEntryPoint function, the operating system calls the function. DllEntryPoint specifies a code that indicates the DLL is attaching to the process. If the entry-point function does not return TRUE, the system terminates the process and reports the error. For more information about the entry-point function, see Dynamic-Link Library Entry-Point Function.

Finally, the system modifies the executable code of the process to provide starting addresses for the DLL functions.

Like the rest of a program's code, DLL code is mapped into the address space of the process when the process starts up and is loaded into memory only when needed. As a result, the PRELOAD and LOADONCALL code attributes used by .DEF files to control loading in previous versions of Windows no longer have meaning.


 Run-Time Dynamic Linking

Run-time dynamic linking occurs when the process calls the LoadLibrary function to specify the name of a DLL and the GetProcAddress function to get the starting address of any function in the DLL. Run-time dynamic linking eliminates the need to link the process with an import library. Since the process does not explicitly call the DLL's functions, it does not generate external references to them.

If the call to LoadLibrary specifies a DLL module already mapped into the address space of the calling process, the function simply returns a handle of the DLL and increments the module's reference count. Otherwise, LoadLibrary attempts to locate the DLL using the same search sequence used for load-time dynamic linking (see Load-Time Dynamic Linking). If the search succeeds, the system maps the DLL module into the address space of the process. If the DLL has a DllEntryPoint function, the operating system calls the function in the context of the thread that called LoadLibrary. The entry-point function is not called if the DLL is already attached to the process due to a previous call to LoadLibrary with no corresponding call to the FreeLibrary function.

If the system cannot find the DLL or if the entry-point function returns FALSE, LoadLibrary returns NULL. If LoadLibrary succeeds, it returns a handle of the DLL module. The process can use this handle to identify the DLL in a call to the GetProcAddress or FreeLibrary function.

The GetModuleHandle function also returns a handle used in GetProcAddress or FreeLibrary. GetModuleHandle succeeds only if the DLL module is already mapped into the address space of the process by load-time linking or by a previous call to LoadLibrary. Unlike LoadLibrary, GetModuleHandle does not increment the module's reference count. The GetModuleFileName function retrieves the full path of the module associated with a handle returned by GetModuleHandle or LoadLibrary.

The process can use GetProcAddress to get the starting handle returned by LoadLibrary or the address of a function in the DLL using a DLL module handle returned by either LoadLibrary or GetModuleHandle. The function is specified by using its name or ordinal value as listed in the EXPORTS statement of the DLL's .DEF file.

When the DLL module is no longer needed, the process can call the FreeLibrary function. This function decrements the module's reference count and unmaps it from the address space of the process if the reference count is zero.

Run-time dynamic linking enables the process to continue executing even if a DLL is not available. The process can then use an alternate method to accomplish its objective. For example, if a process is unable to locate one DLL, it can try to use another, or it can notify the user of an error. If the user can provide the full path of the missing DLL, the process can use this information to load the library even though it is not in the normal search path. This situation contrasts with load-time linking in which the operating system simply terminates the process if it cannot find the DLL.

It is not necessary for the developer to know the names of either the DLLs or the functions within a DLL. The process can get this information from a configuration file or from the user.

Run-time dynamic linking can cause problems if the DLL is using the DllEntryPoint function to perform initialization for each thread of a process, because threads existing when LoadLibrary is called will not be initialized. For an example showing how to deal with this problem, see Using Thread Local Storage in a Dynamic-Link Library.


 Dynamic-Link Library Data

Windows supports the use of the following DLL data:

•	Global and static variables in a DLL module private to each process that uses the DLL.

•	Global and static variables shared by all processes simultaneously using a DLL.

•	Dynamically allocated memory private to each process that uses a DLL.

•	Dynamically allocated memory shared by multiple processes.

•	Static storage private to each thread of a multithreaded process.

The default scope of a DLL's variables is the same as that of any statically linked code. Global variables in a DLL source code file are global to each process using the DLL. Static variables create permanent storage for each process, limiting their scope to the block in which they are declared. As a result, each process has its own instance of a DLL's global and static variables by default.

Win32 development tools enable a DLL's .DEF file to override the default scope of global and static variables. For more information, see Module-Definition File and the documentation included with your development tools.

When a DLL allocates memory using any of the allocation functions (GlobalAlloc, LocalAlloc, HeapAlloc, VirtualAlloc, malloc, and other C run-time allocation functions), the memory is allocated in the address space of the calling process and is accessible only to the threads of that process. A DLL's .DEF file cannot be used to change the scope of dynamically allocated memory.

A DLL can use file mapping to allocate memory that can be shared among processes. For a general discussion of using file mapping to create named shared memory, see File Mapping. For an example that uses the DllEntryPoint function to set up shared memory using file mapping, see Using Shared Memory in a Dynamic-Link Library.

The thread local storage functions enable a DLL to allocate an index for storing and retrieving a different value for each thread of a multithreaded process. For example, a spreadsheet application can create a new instance of the same thread each time the user opens a new spreadsheet. A DLL providing the functions for various spreadsheet operations can use thread local storage to save information about the current state of each spreadsheet (row, column, and so on). For a general discussion of thread local storage, see Processes and Threads. For an example that uses the DllEntryPoint function to set up thread local storage, see Using Thread Local Storage in a Dynamic-Link Library.


 Using Dynamic-Link Libraries

•	Creating a simple dynamic-link library

•	Using load-time dynamic linking

•	Using run-time dynamic linking

•	Using shared memory in a dynamic-link library

•	Using thread local storage in a dynamic-link library


 Creating a Simple Dynamic-Link Library

DLLs make common functions available to a number of processes or threads at once. The following file, MYPUTS.C, contains a simple string printing function. This DLL does not use a DllEntryPoint function because it has no initialization or cleanup functions to perform.

#include <windows.h>

/*

 * A function that writes a null-terminated string to the

 * console output.

 */

VOID myPuts(LPTSTR lpszMsg) {

    DWORD cchWritten;

    HANDLE hStdout;

    /* Get a handle to the console output. */

    hStdout = GetStdHandle(STD_OUTPUT_HANDLE);

    /* Write a null-terminated string to the console output. */

    while (*lpszMsg)

        WriteFile(hStdout, lpszMsg++, 1, &cchWritten, NULL);

}

The module-definition file for this DLL is MYPUTS.DEF, and it contains the following information.

LIBRARY myputs

EXPORTS

     myPuts

The name specified in the LIBRARY statement identifies the DLL in the DLL's import library. Load-time dynamic linking enables the system to use this name for locating the DLL. If run-time dynamic linking is being used, the LoadLibrary function does not use this name to locate the DLL. The EXPORTS statement indicates that other .EXE or .DLL modules can call the myPuts function.

The source code in MYPUTS.C is compiled to produce an object module (MYPUTS.OBJ). The library manager uses the module-definition file (MYPUTS.DEF) to create the import library (MYPUTS.LIB) and the export file (MYPUTS.EXP). The linker uses MYPUTS.EXP and MYPUTS.OBJ to produce the executable DLL module (MYPUTS.DLL). MYPUTS.LIB is not used in creating MYPUTS.DLL, but the linker uses it to create any executable module (.EXE or .DLL) that calls the myPuts function.

Following are some typical command lines used to compile and link a DLL. For more information about compiling and linking dynamic-link libraries and programs that use them, see the documentation included with your development tools.

cvars=-DWIN32 -D_MT -DSTRICT

# Compile myputs.c to create myputs.obj.

myputs.obj: myputs.c

    $(cc)  $(cflags) $(cvars) myputs.c

# Create the DLL's import library.

# Also create the myputs.exp export file.

myputs.lib: myputs.def

    $(lib) -machine:i386 \

    -def:myputs.def     \

    -out:myputs.lib

# Link myputs.obj and myputs.exp to create myputs.dll.

# myputs.lib is not used here but is included as a

# dependency to force creation of myputs.exp.

myputs.dll: myputs.obj myputs.lib

    $(link)          \

    -out:myputs.dll  \

    myputs.exp myputs.obj $(conlibs)

# If the DLL has a DllEntryPoint function, substitute a line

# like this to specify the name of the entry-point function.

#    $(link) -entry:LibMain    \


 Using Load-Time Dynamic Linking

Once you have created a DLL, you can use it in an application. The following file, LOADTIME.C, is the source code for a simple console process that uses the myPuts function from MYPUTS.DLL.

/*

 *   File:  loadtime.c

 *   A simple program that uses myPuts() from myputs.dll

 */

#include <windows.h>

VOID myPuts(LPTSTR);   /* a function from a DLL */

VOID main(VOID) {

    myPuts("message printed using the DLL function\n");

}

Because LOADTIME.C calls the DLL function explicitly, the executable module for the application must be linked with the import library (MYPUTS.LIB). Following are some typical command lines used for compiling and linking a program that uses a DLL.

# Compile loadtime.c to create loadtime.obj.

loadtime.obj: loadtime.c

    $(cc)  $(cflags) $(cvars) loadtime.c

# Link loadtime.obj and myputs.lib to create loadtime.exe.

loadtime.exe: loadtime.obj myputs.lib

    $(link) $(conflags) \

    -out:loadtime.exe loadtime.obj myputs.lib $(conlibs)


 Using Run-Time Dynamic Linking

You can use the same DLL in both load-time and run-time dynamic linking. If the system can find the specified DLL module, the following source code produces the same output as the load-time example in the previous section. The program uses the LoadLibrary function to get a handle of MYPUTS.DLL. If LoadLibrary succeeds, the program uses the returned handle in the GetProcAddress function to get the starting address of the DLL's myPuts function. After calling the DLL function, the program calls the FreeLibrary function to detach the DLL from the process.

The following example illustrates an important difference between run-time and load-time dynamic linking. If the MYPUTS.DLL file is not available, the application using load-time dynamic linking simply terminates. The run-time dynamic linking example, however, can respond to the error.

/*

 *   File:  runtime.c

 *   A simple program that uses LoadLibrary and

 *   GetProcAddress to access myPuts() from the myputs DLL.

 */

#include <stdio.h>

#include <windows.h>

typedef VOID (*MYPROC)(LPTSTR);

VOID main(VOID) {

    HINSTANCE hinstLib;

    MYPROC ProcAdd;

    BOOL fFreeResult, fRunTimeLinkSuccess = FALSE;

    /* Get a handle to the DLL module. */

    hinstLib = LoadLibrary("myputs");

    /* If the handle is valid, try to get the function address. */

    if (hinstLib != NULL) {

        ProcAdd = (MYPROC) GetProcAddress(hinstLib, "myPuts");

        /* If the function address is valid, call the function. */

        if (fRunTimeLinkSuccess = (ProcAdd != NULL))

            (ProcAdd) ("message via DLL function\n");

        /* Free the DLL module. */

        fFreeResult = FreeLibrary(hinstLib);

  }

    /* If unable to call the DLL function, use an alternative. */

    if (! fRunTimeLinkSuccess)

        printf("message via alternative method\n");

}

Because the program uses run-time dynamic linking, it is not necessary to link with the DLL's import library when creating the program's executable module. The following lines are typical of the command lines used to compile and link a program using run-time linking.

# Compile runtime.c to create runtime.obj.

runtime.obj: runtime.c

    $(cc)  $(cflags) $(cvars) runtime.c

# Link runtime.obj to create loadtime.exe.

runtime.exe: runtime.obj

    $(link) $(conflags) \

    -out:runtime.exe runtime.obj $(conlibs)


 Using Shared Memory in a Dynamic-Link Library

This section shows the use of a DLL's entry-point function to set up memory that can be shared by multiple processes. In this DLL, the name of the entry-point function is LibMain. The module-definition file for this DLL is MYPUTS.DEF, and it contains the following information.

LIBRARY myputs

EXPORTS

     myPuts

The example uses file mapping to map a block of named shared memory into the address space of each process to which the DLL is attached. The entry-point function calls the CreateFileMapping function to create a file-mapping object whenever the DLL attaches to a new process. This function can be used to either create or open a named file-mapping object. The first process to which the DLL attaches creates the file-mapping object. Subsequent processes open a handle of the existing object. The GetLastError function triggers initialization of the shared memory because it returns NO_ERROR to the first process and ERROR_ALREADY_EXISTS to subsequent processes.

The MapViewOfFile function maps the file-mapping object into the address space of each process, returning a pointer to the memory. Note that the shared memory can be mapped to a different address in each process. For this reason, each process has its own instance of lpvMem, which is declared as a global variable so that it is available to the DLL's functions. The example assumes that the DLL's global data is not shared, so each attaching process has its own instance of lpvMem. By default, DLL data is not shared, but the default can be modified by the DLL's module-definition (.DEF) file (see Module-Definition File).

Any shared DLL memory persists only as long as the DLL is attached to a process. In this example, the shared memory is released when the last handle of the file-mapping object is closed. To create persistent shared memory, a DLL can create a detached process (see Processes and Threads) when the DLL attaches to the first process. If this detached process uses the DLL and does not terminate, it has a handle of the file-mapping object that prevents the shared memory from being released.

/*

 *   File:  dllshmem.c

 *

 *   A DLL entry-point function sets up shared memory using

 *   named file mapping.

 */

#include <windows.h>

#include <memory.h>

#define SHMEMSIZE 4096

static LPVOID lpvMem = NULL; /* address of shared memory */

/*

 * LibMain() is the DllEntryPoint function for this DLL.

 */

BOOL LibMain(HINSTANCE hinstDLL,   /* DLL module handle  */

        DWORD fdwReason,      /* reason called           */

        LPVOID lpvReserved) { /* reserved                */

    HANDLE hMapObject = NULL;   /* handle to file mapping */

    BOOL fInit, fIgnore;

    switch (fdwReason) {

        /*

         * The DLL is attaching to a process due to process

         * initialization or a call to LoadLibrary.

         */

          case DLL_PROCESS_ATTACH:

            /* Create a named file mapping object */

            hMapObject = CreateFileMapping(

                (HANDLE) 0xFFFFFFFF, /* use paging file    */

                NULL,                /* no security attr.  */

                PAGE_READWRITE,      /* read/write access  */

                0,                   /* size: high 32-bits */

                SHMEMSIZE,           /* size: low 32-bits  */

                "dllmemfilemap");    /* name of map object */

            if (hMapObject == NULL)

                return FALSE;

            /* The first process to attach initializes memory. */

            fInit = (GetLastError() != ERROR_ALREADY_EXISTS);

            /* Get a pointer to the file-mapped shared memory. */

            lpvMem = MapViewOfFile(

                hMapObject,     /* object to map view of    */

                FILE_MAP_WRITE, /* read/write access        */

                0,              /* high offset:   map from  */

                0,              /* low offset:    beginning */

                0);             /* default: map entire file */

            if (lpvMem == NULL)

                return FALSE;

            /* Initialize memory if this is the first process. */

            if (fInit)

                memset(lpvMem, '\0', SHMEMSIZE);

            break;

        /* The attached process creates a new thread. */

        case DLL_THREAD_ATTACH:

            break;

        /* The thread of the attached process terminates. */

        case DLL_THREAD_DETACH:

            break;

        /*

         * The DLL is detaching from a process due to

         * process termination or a call to FreeLibrary.

         */

        case DLL_PROCESS_DETACH:

            /* Unmap shared memory from the process's address space. */

            fIgnore = UnmapViewOfFile(lpvMem);

            /* Close the process's handle to the file-mapping object. */

            fIgnore = CloseHandle(hMapObject);

            break;

        default:

          break;

  }

    return TRUE;

    UNREFERENCED_PARAMETER(hinstDLL);

    UNREFERENCED_PARAMETER(lpvReserved);

}

/*

 * SetSharedMem sets the contents of shared memory.

 */

VOID SetSharedMem(LPTSTR lpszBuf) {

    LPTSTR lpszTmp;

    /* Get the address of the shared memory block. */

    lpszTmp = (LPTSTR) lpvMem;

    /* Copy the null-terminated string into shared memory. */

    while (*lpszBuf)

        *lpszTmp++ = *lpszBuf++;

    *lpszTmp = '\0';

}

/*

 * GetSharedMem gets the contents of shared memory.

 */

VOID GetSharedMem(LPTSTR lpszBuf, DWORD cchSize) {

    LPTSTR lpszTmp;

    /* Get the address of the shared memory block. */

    lpszTmp = (LPTSTR) lpvMem;

    /* Copy from shared memory into the caller's buffer. */

    while (*lpszTmp && --cchSize)

        *lpszBuf++ = *lpszTmp++;

    *lpszBuf = '\0';

}


 Using Thread Local Storage in a Dynamic-Link Library

This section shows the use of a DLL's entry-point function to set up a thread local storage (TLS) index to provide private storage for each thread of a multithreaded process.

The entry-point function uses the TlsAlloc function to allocate a TLS index whenever the DLL attaches to a process. Each thread of the process can then use this index to store a pointer to its own block of memory.

When the entry-point function is called with the DLL_PROCESS_ATTACH value, it peforms the following actions:

1.	Uses the TlsAlloc function to allocate a TLS index.

2.	Allocates a block of memory to be used exclusively by the initial thread of the process.

3.	Uses the TLS index in a call to the TlsSetValue function to store a pointer to the allocated memory.

Each time the process creates a new thread, the entry-point function is called with the DLL_THREAD_ATTACH value. The entry-point function then allocates a block of memory for the new thread and stores a pointer to it by using the TLS index. Each thread can use the TLS index in a call to TlsGetValue to retrieve the pointer to its own block of memory.

When a thread terminates, the entry-point function is called with the DLL_THREAD_DETACH value and the memory for that thread is freed. When a process terminates, the entry-point function is called with the DLL_PROCESS_DETACH value and the TLS index is freed.

The TLS index is stored in a global variable, making it available to all of the DLL's functions. The following example assumes that the DLL's global data is not shared, because the TLS index is not necessarily the same for each process to which the DLL is attached.

static DWORD dwTlsIndex; /* address of shared memory */

/*

 * LibMain() is the DllEntryPoint function for this DLL.

 */

BOOL LibMain(HINSTANCE hinstDLL,   /* DLL module handle  */

        DWORD fdwReason,     /* reason called      */

        LPVOID lpvReserved) {/* reserved           */

    LPVOID lpvData;

    BOOL fIgnore;

    switch (fdwReason) {

        /*

         * The DLL is attaching to a process due to process

         * initialization or a call to LoadLibrary.

         */

        case DLL_PROCESS_ATTACH:

              /* Allocate a TLS index. */

              if ((dwTlsIndex = TlsAlloc()) == 0xFFFFFFFF)

                  return FALSE;

            /* No break: Initialize the index for first thread. */

        /* The attached process creates a new thread. */

        case DLL_THREAD_ATTACH:

            /* Initialize the TLS index for this thread. */

            lpvData = (LPVOID) LocalAlloc(LPTR, 256);

            if (lpvData != NULL)

                fIgnore = TlsSetValue(dwTlsIndex, lpvData);

            break;

        /* The thread of the attached process terminates. */

        case DLL_THREAD_DETACH:

            /* Release the allocated memory for this thread. */

            lpvData = TlsGetValue(dwTlsIndex);

            if (lpvData != NULL)

                LocalFree((HLOCAL) lpvData);

            break;

        /*

         * The DLL is detaching from a process due to

         * process termination or call to FreeLibrary.

         */

        case DLL_PROCESS_DETACH:

            /* Release the allocated memory for this thread. */

            lpvData = TlsGetValue(dwTlsIndex);

            if (lpvData != NULL)

                LocalFree((HLOCAL) lpvData);

            /* Release the TLS index. */

            TlsFree(dwTlsIndex);

            break;

        default:

            break;

    }

    return TRUE;

    UNREFERENCED_PARAMETER(hinstDLL);

    UNREFERENCED_PARAMETER(lpvReserved);

}

When a process uses load-time linking with this DLL, the entry-point function is sufficient to manage the thread local storage. Problems can occur with a process that uses run-time linking because the TLS memory is not allocated for threads that exist before the LoadLibrary function is called to attach the process. The following example solves this problem by checking the value returned by the TlsGetValue function and allocating memory if the value indicates that the TLS slot for this thread is not set.

LPVOID lpvData;

/* Retrieve a data pointer for the current thread. */

lpvData = TlsGetValue(dwTlsIndex);

/* If NULL, allocate memory for this thread. */

if (lpvData == NULL) {

    lpvData = (LPVOID) LocalAlloc(LPTR, 256);

    if (lpvData != NULL)

        TlsSetValue(dwTlsIndex, lpvData);

}


 Dynamic-Link Library Functions

Following are the functions used in dynamic linking.

DisableThreadLibraryCalls
DllEntryPoint
FreeLibrary
FreeLibraryAndExitThread
GetModuleFileName
GetModuleHandle
GetProcAddress
LoadLibrary
LoadLibraryEx
LoadModule

Obsolete or Deleted Functions

FreeModule
FreeProcInstance
GetCodeHandle
GetInstanceData
GetModuleUsage
MakeProcInstance


 Errors

Well-written applications include code that allows them to recover gracefully from unexpected errors. When an error occurs, the application may need to request user intervention, or it may be able to recover without help. In extreme cases, the application may log the user off or shut down the system.


 About Errors

Microsoft® Windows® includes a special error-handling mechanism for exceptions, such as divide-by-zero errors. For more information about exception handling, see Structured Exception Handling.


 Notifying the User

To notify the user that some kind of error has occurred, many applications simply produce a sound by using the Beep or MessageBeep function or flash the window by using the FlashWindow function. An application can also use these functions to call attention to an error and then display a message box or an error message containing details about the error.


 Logging Off or Shutting Down

An application can use the ExitWindows function to log the current user off. The ExitWindowsEx function can also perform the following tasks:

•	Shut down the system.

•	Shut down the system and restart it.

•	Log off and force all running applications to terminate.

Logging off stops all processes associated with the security context of the process that called the exit function, logs the user off the system, and displays the Logon dialog box.

Shutting down brings the system to a condition in which it is safe to turn off the computer. All file-system buffers are flushed to the disk, and a message box is displayed informing the user that the computer can be turned off. If the reboot option is specified, the computer restarts.

The calling process must have the SE_SHUTDOWN_NAME privilege to shut down or to shut down and restart. For an example that enables this privilege and shuts down the system, see Shutting Down.


 Last-Error Code

When an error occurs, most functions in the Microsoft® Win32® application programming interface (API) return an error code, usually FALSE, NULL, 0xFFFFFFFF, or −1. Most functions in the Win32 API also set an internal error code called the last-error code. When a function succeeds, the last-error code is not reset. The error code is maintained separately for each running thread; an error in one thread does not overwrite the last-error code in another thread. An application can retrieve the last-error code by using the GetLastError function; the error code may tell more about what actually occurred to make the function fail.

The SetLastError function sets the error code for the current thread. The SetLastErrorEx function also allows the caller to set an error type indicating the severity of the error. These functions are intended primarily for dynamic-link libraries (DLLs), so they can emulate the behavior of the Win32 API.

The Win32 API defines a set of error codes that can be set as last-error codes or be returned by these functions..

Error codes are 32-bit values (bit 31 is the most significant bit). Bit 29 is reserved for application-defined error codes; no Win32 API error code has this bit set. Developers who define an error code for an application should set this bit to indicate that the error code has been defined by an application and to ensure that the error code does not conflict with any system-defined error codes.


 Error Message Boxes

Some errors, such as a drive-not-ready error (when the door of the floppy disk drive is open), cause Windows to display a message box informing the user that an error has occurred. Applications that handle these errors without user intervention can use the SetErrorMode function to suppress error message boxes.


 Using Errors

•	Notifying the user of errors - example

•	Logging off

•	Shutting down

•	Retrieving the last-error code


 Notifying the User of Errors - Example

The following example flashes a window and plays the system exclamation sound.

FlashWindow(hwnd, TRUE); /* invert the title bar   */

Sleep(500);              /* wait a bit             */

FlashWindow(hwnd, TRUE); /* invert again           */

/* Play the system exclamation sound. */

MessageBeep(MB_ICONEXCLAMATION);


 Logging Off

The ExitWindows function logs the current user off. All applications must agree to terminate before the user logs off. If any application returns FALSE when it processes the WM_QUERYENDSESSION message, the user is not logged off. If your application handles the WM_QUERYENDSESSION message, you can allow the user to cancel the log-off operation, even if another application or Windows originated the end-session request.

The following example logs off the current user, unless the user selects the No button in the message box displayed when the application receives the WM_QUERYENDSESSION message.

            ExitWindows(0, 0); /* log the current user off    */

case WM_QUERYENDSESSION:  /* in application's MainWndProc */

{

    int i  = MessageBox(NULL, "Shutdown?",

       "Received WM_QUERYENDSESSION", MB_YESNO);

    /*

     * Return TRUE to allow shutdown, FALSE to stop.

     */

    return i == IDYES;

    break;

}


 Shutting Down

The ExitWindowsEx function can be used to shut down the system. Shutting down flushes file buffers to disk and brings the system to a condition in which it is safe to turn off the computer. The calling process must have the SE_SHUTDOWN_NAME privilege to shut down the system.

The following example enables the SE_SHUTDOWN_NAME privilege and then shuts down the system.

HANDLE hToken;

TOKEN_PRIVILEGES tkp;

/* Get a token for this process. */

if (!OpenProcessToken(GetCurrentProcess(),

        TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))

    error("OpenProcessToken");

/* Get the LUID for the shutdown privilege. */

LookupPrivilegeValue(NULL, TEXT("SE_SHUTDOWN_NAME"),

        &tkp.Privileges[0].Luid);

tkp.PrivilegeCount = 1;  /* one privilege to set    */

tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

/* Get the shutdown privilege for this process. */

AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,

        (PTOKEN_PRIVILEGES)NULL, 0);

/* Cannot test the return value of AdjustTokenPrivileges. */

if (GetLastError() != ERROR_SUCCESS)

    error("AdjustTokenPrivileges");

/* Shut down the system and force all applications to close. */

if (!ExitWindowsEx(EWX_SHUTDOWN | EWX_FORCE, 0))

    error("ExitWindowsEx");

For more information about setting security privileges, see Security.


 Retrieving the Last-Error Code

When a function in the Win32 API fails, it sets the last-error code. If your application needs more details about an error, it can retrieve the last-error code.

The following example shows an error-handling function used by the other examples in this topic.

void error(LPSTR lpszFunction)

{

    CHAR szBuf[80];

    DWORD dw = GetLastError();

    sprintf(szBuf, "%s failed: GetLastError returned %u\n",

        lpszFunction, dw);

    MessageBox(NULL, szBuf, "ERROR", MB_OK);

    ExitProcess(dw);

}


 Error Functions

Following are the functions used with errors.

Beep
ExitWindows
ExitWindowsEx
FlashWindow
GetLastError
MessageBeep
SetErrorMode
SetLastError
SetLastErrorEx


 Event Logging

When an error occurs in an application written for Microsoft® Windows®, the system administrator or support personnel must determine what caused the error, attempt to recover any lost data, and prevent the error from recurring. If applications record important events such as low-memory conditions or excessive disk retries, the record of this information, called an event log, can be used to help determine what conditions may have caused the error and the context in which the error occurred. (Event logging can also be applied to the Windows operating system and to system services.) By periodically viewing the event log, the system administrator may be able to identify problems before they cause serious damage.

Many applications record errors and events in various proprietary error logs. These proprietary logs have different formats, apply different user interfaces for their display, and cannot be merged to provide a complete report. But all of these logs store similar information and present the logged data in similar ways.

Event logging in Windows provides a standard, centralized way for applications (and Windows) to record important software and hardware events. It also supplies a standard user interface for viewing the logs and a programming interface for examining the logs. Event logging provides a means to merge events from various sources into a single informative story.


 Event Logging Model

Event logs store records of significant events on behalf of the Windows operating system and the applications that run with Windows. Generally, applications should log only information that could be useful in diagnosing a hardware or software problem.

Events are classified as information, warnings, and errors. All event classifications have well-defined common data and can optionally include event-specific data. For example, information can assert that a service has started. Warnings are used for recoverable problems such as low disk-space conditions. Errors are used for nonrecoverable conditions that might cause an application to fail. In addition to logging event classifications, the security service logs successes and failures in audits.


 Logging Guidelines

Because logging functions are general purpose, developers must decide what information is appropriate to log. It is important to note that logging consumes resources: disk space and logging time. The event log is not intended to be used as a trace facility.

You should log information about events that can be used to diagnose problems after they have occurred. Logging low-memory conditions, for example, can provide information about a problem that the system administrator can solve by adding more memory to the computer.

Following are more examples in which event logging is helpful:

•	A disk driver encounters a bad sector on the disk. It may be able to read from or write to the sector after some retries, but the sector will probably go bad eventually. The disk driver should log a warning if it can proceed; otherwise, it should log an error.

•	A file system finds a bad sector and fixes it. A large number of events of this type might indicate that the disk is about to fail. The file system logs a warning event.

•	A device driver encounters a hardware problem, such as a disk controller time-out, a power failure in a parallel port, or a data error from a network or serial card. Logging information about these events can help in diagnosing hardware problems. The device driver logs the hardware problem.

•	An Application encounters resource problems. An application or a device driver may get into a low-memory situation (caused by a code bug, for example) that degrades performance. Logging an event when memory allocation fails might later provide a clue about what went wrong. The application logs the resource problem.

•	A server application (a database or a communications server, for example) records events such as a user logging on, opening a database, or starting a file transfer. The server can also log important information as it runs, such as the number of resources the application is using, errors it encounters (cannot access file, host process disconnected, and so on), a corruption in the database (not able to find a leaf node down a certain path in a tree), or whether a file transfer was successful or not. All of this information can be valuable to a support person (or to the developer of the application). The application records such events and logs them as information events.


 Logging Performance and Size

Typically, how much disk space does an event log require? What is the overhead for an application that makes a call to log an event? The answers to these questions depend on how much information the application chooses to log. This is why it is important to log only essential information and to place event logging calls in an error path in the application, rather than place them in the main path, where the performance hit would be more severe.


 Event Logging Management Information

Event logging management information is stored in the Services key of the configuration database and can be modified by a system administrator.

The structure of the configuration information is as follows:

HKEY_LOCAL_MACHINE

  SYSTEM

    CurrentControlSet

      Services

        EventLog

          Application

          Security

          System

The EventLog key contains several subkeys, called logfiles. The default logfiles are Application, Security, and System. Each logfile subkey can contain subkeys, called sources. You cannot use a source name that has been used as a logfile name, and source names should not be hierarchical. (The backslash character [\] cannot be used in a registry key.) Each source entry contains information specific to the source of the event, as shown in the following table.

Value	Description
EventMessageFile	Specifies the path for the event identifier message file. This value has the type REG_EXPAND_SZ.
CategoryMessageFile	Specifies the path for the category message file. The event category and event identifier message strings can be in the same file. This value has the type REG_EXPAND_SZ.
ParameterMessageFile	Specifies the path for the event source's parameter message file. This file contains language-independent strings that are to be inserted into the event description strings. You can use the same message file for parameter, category, and event identifier message strings. This value has the type REG_EXPAND_SZ.
CategoryCount	Specifies the number of categories supported. This value has the type REG_DWORD.
TypesSupported	Specifies a bitmask of supported types. This value has the type REG_DWORD.
When an application uses the RegisterEventSource or OpenEventLog function to get a handle of an event log, the event logging service searches for the specified source name in the registry. For example, the Application logfile might have configured sources of Microsoft® SQL Server™ and Microsoft® Excel. If an application uses RegisterEventSource or OpenEventLog with a source name of Application, SQL, or Excel, the event logging service returns a handle to the Application logfile.

An application can use the Application event log without adding a new source key to the registry. If the application calls RegisterEventSource, passing a source name that cannot be found in the registry, the event logging service uses the Application logfile by default. However, because there is not a message or category string file, the event viewer will not be able to map the event identifier or category to a replacement string. For this reason, the recommended procedure is to add a unique source name for the application to the registry. This allows you to specify message files for the event identifier and category in your events. Applications and services should add their source names to the Application logfile. Device drivers should add their source name to the System logfile.

An event viewer application uses the OpenEventLog function to open the event log for an event source. The event viewer can then use the ReadEventLog function to read event records from the log. ReadEventLog returns a buffer containing an EVENTLOGRECORD structure and additional information that describes a logged event. The EventID member of the EVENTLOGRECORD is the identifier of a description string in the source's event message file. The event viewer uses the LoadLibrary function to load the file indicated by the source's EventMessageFile registry value. The viewer then uses the FormatMessage function to retrieve the description string from the loaded module.

The description string may contain insertion string placeholders, such as %n, where %1 indicates the first insertion string, and so on. In this case, the buffer returned by ReadEventLog contains the insertion strings. The NumStrings member of the EVENTLOGRECORD indicates the number of insertion strings. The StringOffset member of the EVENTLOGRECORD indicates the location of the first insertion string in the buffer.

An insertion string may also contain placeholders of the form %%n, where n is the identifier of a string in the source's parameter message file. In this case, the event viewer uses LoadLibrary and FormatMessage to retrieve the insertion string from the file indicated by the source's ParameterMessageFile registry value.

For more information about using the registry, see Registry. For more information about creating and using message files, see your message compiler documentation.


 Event Logging Operations

In the following table are the five operations that can be performed on the event logs.

Operation	Function
Backup	BackupEventLog
Clear	ClearEventLog
Query	GetOldestEventLogRecord, GetNumberOfEventLogRecords
Read	ReadEventLog
Write	ReportEvent
The OpenEventLog, OpenBackupEventLog, RegisterEventSource, DeregisterEventSource, and CloseEventLog functions also open and close event log handles; this provides an object-oriented model for the function set, as well as some performance gain when performing multiple operations on the logs.

The OpenEventLog and ReportEvent functions take an optional server name as a parameter so that the operations can be performed on the remote server. OpenEventLog should be used for reading or performing some administrative operation (backup, clear, query) on the log, and RegisterEventSource should be used for writing to logs.


 Event Log Entry

This guide describes the parameters supplied for logged events.


 Source

Source is the name of the software that logs the event. For many applications, Source may be simply the application name, or it may reflect a subcomponent of a larger application.


 Event Identifier

Event identifiers are looked up within a message file to locate a description string that can be presented to the user. Support personnel also use event identifiers; if a user can identify the source and the event identifier, support personnel will know exactly which event has occurred. Event identifiers are unique to a particular source.


 Type

Windows NT™ defines five types of event logging. Each event must be of a single type, because types cannot be combined.

Event type	Description
Information	Information events are used to note infrequent but significant successful operations. For example, when Microsoft SQL Server successfully loads, it may be appropriate to log a "SQL Server has started" information event. Note that while this is appropriate for major server services, it is generally inappropriate for a desktop application (Microsoft Excel, for example) to log an event each time it is started. Information events should not be used as a trace facility.
Warning	Warning events are used to indicate problems that are not significant, but that may foretell of future errors or other problems. Resource consumption is a good candidate for a Warning event. For example, a warning could be logged if disk space is low. Errors that are recovered without loss of function or data can be classified as warnings.
Error	Error events are used to indicate significant problems that have occurred and that the user should know about. Errors usually indicate a loss of functionality or data. For example, if a service cannot be loaded as the system boots, an Error event can be logged.
Success Audit	Success Audit events are security events that occur when an audited access attempt is successful. For example, a successful logon attempt is a Success Audit event.
Failure Audit	Failure Audit events are security events that occur when an audited access attempt fails. For example, a failed attempt to open a file is a Failure Audit event.


 Category

Categories are used to help organize events so that they can be filtered in the Event Viewer. Each Source can define its own numbered Categories and the text strings to which they are mapped. The Categories must be numbered consecutively beginning with the number 1. With Event Viewer, it is possible to filter by Source and within Source, by Category. The security system uses several categories: Logon/Logoff, File System Access, Privileged Actions, Change in Security Policy. Categories for other parts of the system are developed over time as it becomes clear which events are being logged. An application can define its own categories.


 Strings

Strings are optional language-independent (nonlocalized) strings used to fill in values for placeholders in description strings. Because the strings are not localized, it is critical that this field be used only to store language-independent strings such as numeric values or string tokens (filenames, user names, and so on). String length must not exceed 32 kilobytes − 1 characters.

It is not acceptable to use several strings to "paste" together a larger description or to use nontoken strings. The insertion string should be treated as data, not text. For example, the following example is not recommended:

Str1$ = successfully

Description = "User was %1 added to database."

Using these two strings to form the string, "User was successfully added to database." (the alternative being Str1$ = "not") is not acceptable for three reasons:

1.	The strings "successfully" and "not" should be localized.

2.	Even if the insertion strings are obtained from language-dependent message files, this is done when the event is logged, not when it is viewed. When the event is viewed, the language may be wrong.

3.	Such substitutions of adverbs and adjectives will not work in many other languages. The preceding example should use two separate events.

The following example shows an appropriate use of strings:

Str1$ = "c:\testapp.c".

Description = "Access denied. Attempted to open the file %1"


 Description

Each event is associated with a description located in a message file that is registered by the Source. The description should help the user understand what went wrong and suggest what actions to take. Focus the description toward users solving their own problems, not toward support people or developers. Make the description clear and concise and avoid culture-specific phrases. If your event includes private data in the Data field, include at the end of the description an explanation about what the Data field contains. For example, the network software often notes: "(The SMB is the event data)." As a convention, use parentheses around such remarks, as indicated in this example. Several applications can share the same message file, and the message file can contain descriptions for both the event identifier and the event category.

The description strings are indexed by event identifier, enabling Event Viewer to display event-specific text for any event based on the event identifier. All descriptions are localized and language dependent. Description strings can optionally contain placeholders for insertion strings. Each placeholder is represented by a percent sign and an index number for the string to substitute. For example, the placeholder %1 is replaced by the first insertion string, %5 is replaced by the fifth insertion string, and so on.


 Data

Each event can have event-specific data associated with it. Event Viewer has no information of any of the events, and only displays extra data in a combined hexadecimal and text dump format. Use event-specific data sparingly, including it only if you are sure it will be useful to a support technician or a developer. You might include, for example, data containing a structure filled with information that could help a technician debug an application failure.

Examples of event-specific data are found in many network events; network control blocks (NCBs) are included as event-specific data. In all cases, the last part of the description string should include a note about what information is available as event-specific data. Third-party applications can use the Data field to store information the application can process independently of Event Viewer. For example, you could write your own viewer specific to your events, or write a program that scans the logfiles and makes reports, including information from the event-specific data.


 The EVENTLOGRECORD Structure

The ReadEventLog function uses the EVENTLOGRECORD structure to format event log information. This structure contains information relating to the content of the event record. The actual event record information follows this structure in the buffer returned by the ReadEventLog function.


 Special Cases

Each call to an event logging function is considered to be an atomic operation. For reading the event log, only whole event records are returned. For logging events, each event record is guaranteed to be written as a complete record in the log. The following list describes how the event logging service handles special conditions:

•	Multiple calls written to the same log. The event logging service serializes the operations; the event logs are written sequentially in the logfile.

•	A call to read and a call to write are made at the same time. What happens depends on where the current read operation is being carried out in the file. If the read position is at the end of the file, either the read operation fails with an "end-of-file" status (if the write operation has not been done), or it returns the new record that the write operation has just written to the log.

•	Clearing the log before reading. The read operation returns an "end-of-file" status after the file is cleared.

•	Clearing the log before writing. The clear operation truncates the logfile; the write operation then writes the new record at the beginning of the log.


 Using Event Logging

•	Adding a source to the registry.

•	Reporting an event.

•	Querying the event log.

•	Reading the event log.

You can use the Windows Registration Database Editor (REGEDIT.EXE) to view the event log registry keys, and you can use Event Viewer to view the event logs.


 Adding a Source to the Registry

You can use the default Application event log without adding your source name to the registry. However, Event Viewer will not be able to map your event identifier codes to message strings unless you register your source and provide a message-file name.

You can add a new source name to the registry by opening a new registry subkey under the Application key and adding registry values to the new subkey. The following code sample opens a new source name called SamplApp and adds to the new subkey a message-file name and a bitmask of supported types.

HKEY hk;

DWORD dwData;

UCHAR szBuf[80];

/*

 * Add your source name as a subkey under the Application

 * key in the EventLog service portion of the registry.

 */

if (RegCreateKey(HKEY_LOCAL_MACHINE,

"SYSTEM\\CurrentControlSet\\Services\

\\EventLog\\Application\\SamplApp",

            &hk))

    ErrorExit("could not create registry key");

/* Set the Event ID message-file name. */

strcpy(szBuf, "%SystemRoot%\\System\\SamplApp.dll");

/* Add the Event ID message-file name to the subkey. */

if (RegSetValueEx(hk,             /* subkey handle         */

        "EventMessageFile",       /* value name            */

        0,                        /* must be zero          */

        REG_EXPAND_SZ,            /* value type            */

        (LPBYTE) szBuf,           /* address of value data */

        strlen(szBuf) + 1))       /* length of value data  */

    ErrorExit("could not set event message file");

/* Set the supported types flags. */

dwData = EVENTLOG_ERROR_TYPE | EVENTLOG_WARNING_TYPE |

    EVENTLOG_INFORMATION_TYPE;

if (RegSetValueEx(hk,      /* subkey handle                */

        "TypesSupported",  /* value name                   */

        0,                 /* must be zero                 */

        REG_DWORD,         /* value type                   */

        (LPBYTE) &dwData,  /* address of value data        */

        sizeof(DWORD)))    /* length of value data         */

    ErrorExit("could not set supported types");

RegCloseKey(hk);


 Reporting an Event

After you have added a source name to the registry, use the RegisterEventSource function to get a handle of the Application event log, as in the following example, which gets the handle and then adds an event to the logs.

LPSTR aszMsg[] = {

    "SamplApp",

    };

HANDLE h;

h = RegisterEventSource(NULL, /* uses local computer         */

    "SamplApp");              /* source name                 */

if (h == NULL)

    ErrorExit("could not register event source");

if (!ReportEvent(h,           /* event log handle            */

        EVENTLOG_ERROR_TYPE,  /* event type                  */

        0,                    /* category zero               */

        0x1003,               /* event identifier            */

        NULL,                 /* no user security identifier */

        1,                    /* one substitution string     */

        0,                    /* no data                     */

        (LPTSTR *) aszMsg,    /* address of string array     */

        NULL))                /* address of data             */

    ErrorExit("could not report event");

DeregisterEventSource(h);


 Querying the Event Log

The following code sample displays the number of event records currently in the Application event log and the System event log.

/* Open the System log. */

h = OpenEventLog(NULL,  /* uses local computer   */

    "System");          /* source name          */

if (h == NULL)

    ErrorExit("could not open System event log");

/* Get the number of records in the System event log. */

if (!GetNumberOfEventLogRecords(h, &cRecords))

    ErrorExit

       ("could not get number of records");

printf("There are %d records in the System event log.\n", cRecords);

CloseEventLog(h);

/* Open the Application log. */

h = OpenEventLog(NULL,  /* uses local computer  */

    "Application");     /* source name          */

if (h == NULL)

    ErrorExit("could not open Application event log");

/* Get the number of records in the Application event log. */

if (!GetNumberOfEventLogRecords(h, &cRecords))

    ErrorExit("could not get number of records");

printf("There are %d records in the Application event log.\n",

    cRecords);

CloseEventLog(h);


 Reading the Event Log

The following code sample reads all the records in the Application logfile and displays the event identifier, event type, and source name for each event log entry.

EVENTLOGRECORD *pevlr;

BYTE bBuffer[BUFFER_SIZE];

DWORD dwRead, dwNeeded, cRecords, dwThisRecord = 0;

    /* Open the Application event log. */

    h = OpenEventLog(NULL,  /* uses local computer      */

        "Application");     /* source name              */

    if (h == NULL)

        ErrorExit("could not open Application event log");

    pevlr = (EVENTLOGRECORD *) &bBuffer;

    /*

     * Opening the event log positions the file pointer

     * for this handle at the beginning of the log.

     *

     * Read records sequentially until there

     * are no more.

     */

    while (ReadEventLog(h,                /* event log handle */

                EVENTLOG_FORWARDS_READ |  /* reads forward    */

                EVENTLOG_SEQUENTIAL_READ, /* sequential read  */

                0,            /* ignored for sequential reads */

                pevlr,        /* address of buffer            */

                BUFFER_SIZE,  /* size of buffer               */

                &dwRead,      /* count of bytes read          */

                &dwNeeded)) { /* bytes in next record         */

        while (dwRead > 0) {

            /*

             * Print the event ID, type, and source name.

             * The source name is just past the end of the

             * formal structure.

             */

            printf("%02d  Event ID: 0x%08X ",

                dwThisRecord++, pevlr->EventID);

            printf("EventType: %d Source: %s\n",

                pevlr->EventType, (LPSTR) ((LPBYTE) pevlr +

                sizeof(EVENTLOGRECORD)));

            dwRead -= pevlr->Length;

            pevlr = (EVENTLOGRECORD *)

                ((LPBYTE) pevlr + pevlr->Length);

        }

        pevlr = (EVENTLOGRECORD *) &bBuffer;

    }

    CloseEventLog(h);


 Event Logging Functions

The following functions are used with event logging.

BackupEventLog
ClearEventLog
CloseEventLog
DeregisterEventSource
GetNumberOfEventLogRecords
GetOldestEventLogRecord
NotifyChangeEventLog
OpenBackupEventLog
OpenEventLog
ReadEventLog
RegisterEventSource
ReportEvent


 File Mapping

This Windows 95 overview discusses the file-mapping functions in the Microsoft® Win32® application programming interface (API). These functions allow a process to create file-mapping objects and file views to easily access and share data.


 File Mapping Platform Differences

The overviews for file mapping in Windows 95 and Windows NT are substantially different. To accommodate these differences, the Windows 95 overview is first presented in its entirety, followed by the Windows NT version.


 About File Mapping

Windows 95 Overview
For more information, see the Windows NT overview About File Mapping.

File mapping is the association of a file's contents to a portion of a process's virtual address space. The operating system creates a file-mapping object to maintain this association. A file view is the portion of virtual address space that is used to access the file's contents. Processes read and write to the file view using pointers just as they would with dynamically allocated memory. Also, the VirtualProtect function operates on file views just like any other virtual memory.

Windows reads data from the file into the file view and writes it back out to the file as needed. In effect, file mapping is a way to tell the system to back a specified part of a process's virtual address space with a specified file or with the system pagefile.

Mapping a file allows a process to access files on disk in the same way as dynamically allocated memory or to share memory between two or more processes. The file-mapping functions in the Microsoft® Win32® application programming interface (API) allow a process to create file-mapping objects and file views to easily access and share data.


 Accessing Files Using the CreateFile Function

The first step in mapping a file is to open the file by calling the CreateFile function. The file should be opened with exclusive access to ensure that other processes cannot write to the portion of the file that is mapped. An easy way to obtain exclusive access is to specify zero in the fdwShareMode parameter of CreateFile.

The CreateFileMapping function uses the handle returned by CreateFile to create a file-mapping object. CreateFileMapping enables you to specify an object name, the number of bytes to be mapped from the file, and the read-write access to the mapped memory. CreateFileMapping fails if the access flags conflict with those specified when the file was opened by using CreateFile. For example, to read and write to the file, specify the GENERIC_READ and GENERIC_WRITE values in the fdwAccess parameter of CreateFile and specify the PAGE_READWRITE value in the fdwProtect parameter of CreateFileMapping.

A file mapping can map a file as large as the file system allows. The dwMaximumSizeHigh and dwMaximumSizeLow parameters of CreateFileMapping allow you to specify the number of bytes to be mapped from the file. The size of the file mapping is independent of the size of the file being mapped.

However, if the mapping is larger than the file, the system grows the file before CreateFileMapping returns. If the file mapping is smaller than the file, only the specified number of bytes from the file is mapped.

When you do not want the size of the file to change (for example, when mapping read-only files), call CreateFileMapping and specify zero for both dwMaximumSizeHigh and dwMaximumSizeLow. Doing this creates a file-mapping object exactly the same size as the file. Otherwise, you must calculate or estimate the size of the finished file because file-mapping objects are static in size; once created they cannot grow or shrink.

To actually map the data from the file to memory, you must create a view of the file. The MapViewOfFile and MapViewOfFileEx functions use the file-mapping object handle returned by CreateFileMapping to create a view (or a copy) of the file or a portion of the file in the process's virtual address space. These functions fail if the access flags conflict with those specified when the file-mapping object was created by CreateFileMapping. MapViewOfFileEx works exactly like MapViewOfFile except that it allows a process to specify the base address of the view of the file in the process's virtual address space.

MapViewOfFile returns a pointer to the file view. An application uses this pointer to read and write data to the file mapping in the same way as it would access dynamic memory. By dereferencing a pointer in the range of addresses specified in MapViewOfFile, an application can read and write data to the file. The actual reading and writing to the file on disk is handled by the system. Data is not actually transferred at the time the file-mapping object is written to. Instead, much of the file input and output (I/O) is cached to improve general system performance. Applications may override this behavior by calling the FlushViewOfFile function to force the system to perform disk transactions immediately.

An application may create multiple file views from the same file-mapping object. A file view can be a different size than the file-mapping object from which it is derived, but it must fit within the file-mapping object. The offset specified by the dwOffsetHigh and dwOffsetLow parameters of MapViewOfFile must be a multiple of the allocation granularity of the system. To obtain the system's memory allocation granularity, use the GetSystemInfo function, which fills in the members of a SYSTEM_INFO structure.

When done with the file-mapping object, the process should destroy all file views in its address space by using the UnmapViewOfFile function for each file view. This function invalidates the pointer to the process's virtual address space. If any of the pages of the file view have changed since the view was mapped, the system writes the changed pages of the file "lazily" to disk. To commit the data to disk immediately, call FlushViewOfFile before unmapping the view.

Both the file-mapping object and the file must be closed by calling CloseHandle to first close the file-mapping object and then the file.

After closing a file-mapping object and unmapping all views, if necessary, a process can adjust the size of the file by using the SetFilePointer and SetEndOfFile functions. For example, if the mapping is larger than the desired size of the file, a process can set the file pointer to the desired size of the file.


 Sharing Files and Memory

File mapping can be used to share a file or memory between two or more processes. To do so, all of the processes must use the same file-mapping object to create identical views of the file or memory. Each process's view resides in the process's own virtual address space. If one process updates its view, the other process sees the update immediately.

To share a file the first process creates or opens a file by using CreateFile. Next, it creates a file-mapping object by using CreateFileMapping and specifying a name for the file-mapping object. To share memory that is not associated with a file, a process must use the CreateFileMapping function and specify (HANDLE)0xFFFFFFFF instead of an existing file handle. The corresponding file-mapping object accesses memory backed by the system paging file. You must specify a size greater than zero when you specify (HANDLE)0xFFFFFFFF in a call to CreateFileMapping.

The easiest way for other processes to obtain a handle of the file-mapping object created by the first process is to use the OpenFileMapping function and specify the object's name. If the file-mapping object does not have a name, the process must obtain a handle to it through inheritance or duplication. For more information on inheritance and duplication, see Processes and Threads, and Handles and Objects.

Processes that share files or memory must create file views by using the MapViewOfFile or MapViewOfFileEx function just as they would when accessing a file. They must coordinate their access using semaphores, mutexes, events, or some other mutual exclusion technique. For more information on synchronization, see Synchronization.

A shared file-mapping object will not be destroyed until all processes that use it close their handles to it by using CloseHandle and call UnMapViewOfFile on all file views.


 Coherence

Coherence guarantees that the data accessible in a file view is an identical copy of the file's contents on disk. Although the CreateFileMapping function works with remote files, it does not keep them coherent. For example, if two computers both map a file as writable, and both change the same page, each computer will see only its own write operations to the page. When the data gets updated on the disk, it is not merged.


 Using File Mapping

Windows 95 Overview
For more information, see the Windows NT overview Using File Mapping.

The code samples in this guide illustrate how two processes might access an existing file as named shared memory.

As discussed earlier, the processes must synchronize their access to the memory. For more information on synchronization, see Synchronization.

In the following code, the first process calls CreateFileMapping function to create a file-mapping object. When a corresponding file view is created, the process has read-write access to the memory.

hMapFile = CreateFileMapping(hFile,    // current file handle

    NULL,                              // default security

    PAGE_READWRITE,                    // read-write access

    0,                                 // max. object size

    0,                                 // size of hFile

    "MyFileMappingObject");            // name of map. object

if (hMapFile == NULL) {

    ErrorHandler("Could not create file-mapping object.");

}

The following code uses the file-mapping object handle returned by CreateFileMapping to create a view of the file in the process's address space.

lpMapAddress = MapViewOfFile(hMapFile, // handle to map. object

    FILE_MAP_ALL_ACCESS,               // read-write access

    0,                                 // max. object size

    0,                                 // size of hFile

    0);                                // map entire file

if (lpMapAddress == NULL) {

    ErrorHandler("Could not map view of file.");

}

The MapViewOfFile function returns a pointer to the file view. The process can use the pointer to access the memory for whatever it needs to do.

In the next example, a second process uses the OpenFileMapping function to share the same memory. As in the original process, the MapViewOfFile function returns a pointer to the file view.

hMapFile = OpenFileMapping(FILE_MAP_ALL_ACCESS, // r-w access

    FALSE,                             // do not inherit

    "MyFileMappingObject");            // name of mapping obj.

if (hMapFile == NULL) {

    ErrorHandler("Could not open file-mapping object.");

}

lpMapAddress = MapViewOfFile(hMapFile, // handle to map. obj.

    FILE_MAP_ALL_ACCESS,               // read-write access

    0,                                 // max. object size

    0,                                 // size of hFile

    0);                                // map entire file

if (lpMapAddress == NULL) {

    ErrorHandler("Could not map view of file.");

}

Note that MapViewOfFile may return different addresses in different processes. To specify the location of the file view within a process's address space, use the MapViewOfFileEx function rather than MapViewOfFile.

The following example uses the UnmapViewOfFile function to invalidate the pointer to the mapped memory. This destroys the file view in the process's address space. If any pages of the file view have changed since the file view was mapped, UnmapViewOfFile also copies the changed pages to the file on disk.

if (!UnmapViewOfFile(lpMapAddress)) {

    ErrorHandler("Could not unmap view of file.");

}

When a process is finished using a file mapping and has umapped all views, it must close the file mapping object's handle by calling CloseHandle.

CloseHande(hMapFile);

The FlushViewOfFile function copies the specified number of bytes of the file view to the physical file but does not destroy the file view:

if (!FlushViewOfFile(lpMapAddress, dwBytesToFlush)) {

    ErrorHandler("Could not flush memory to disk.");

}


 File Mapping Functions

The following functions are used with file mapping.

CreateFileMapping
FlushViewOfFile
MapViewOfFile
MapViewOfFileEx
OpenFileMapping
UnmapViewOfFile


 File Mapping (Windows NT)

This Windows NT™ overview discusses the file-mapping functions in the Microsoft® Win32® application programming interface (API). These functions allow a process to create file-mapping objects and file views to easily access and share data.


 About File Mapping

Windows NT Overview
For more information, see the Windows 95 overview About File Mapping.

File mapping is the copying of a file's contents to a process's virtual address space. The copy of the file's contents is called the file view, and the internal structure the operating system uses to maintain the copy is called the file-mapping object.

Another process can create an identical file view in its own virtual address space by using the first process's file-mapping object to create the view. This enables the processes to share data. Any process that has the name or a handle of a file-mapping object can create a file view.

Microsoft® Windows NT™ file-mapping functions create file-mapping objects and file views necessary for this method of data sharing.


 Sharing a File

If two (or more) processes need to share a file, one process should open the file for exclusive access by using the CreateFile function. The CreateFileMapping function uses the handle returned by CreateFile to create a file-mapping object. Processes that have the name or a handle of the file-mapping object can share the file's data. The file handle should remain open until the processes are no longer sharing the file; this prevents nonsharing processes from reading from or writing to the file.

CreateFileMapping enables you to specify an object name, the number of bytes to be mapped from the file, and the read-and-write access to the mapped memory. CreateFileMapping fails if the access flags conflict with those specified when the file was opened by using CreateFile. CreateFileMapping returns a handle of the file-mapping object. This handle is used to create a "view of the file," or "file view," in the process's virtual address space. A file view is a copy of the entire file or a portion of the file, depending on the number of bytes requested.

The process that created the file-mapping object uses the MapViewOfFile function with the file-mapping object handle to create a file view, or copy of the file, in the process's virtual address space. MapViewOfFile returns a pointer to the file view. This function fails if the access flags conflict with those specified when the mapping object was created with CreateFileMapping.

To share the data in the file view, another process must create an identical file view in its own virtual address space. To do this, the process must first obtain a handle of the same file-mapping object and then create its own file view by using MapViewOfFile. The easiest way to obtain a handle of the file-mapping object is to use the OpenFileMapping function and specify the object's name. If the file-mapping object does not have a name, the process must obtain a handle of it through inheritance or duplication. For more information on inheritance and duplication, see Processes and Threads and Handles and Objects.

MapViewOfFile returns a pointer to the file view. To ensure that multiple processes are sharing the same data through their own pointers, all views of a file must be derived from the same file-mapping object. If this is the case, the file views are said to be coherent, or identical. Typically, file views are not coherent if they are derived from different file-mapping objects, even if the mapping objects refer to the same file.

Because the file view is basically a block of memory and not a file, processes read from and write to the file view by using pointers just as though the block were dynamically allocated. You do not need to use the ReadProcessMemory and WriteProcessMemory functions.

If one or more of the processes has write access to the shared data, processes must synchronize their access to the shared data by using a semaphore. This ensures that the file views remain coherent in all processes. For more information on synchronization, see Synchronization.

Some applications require that a file be mapped to the same address in multiple processes. To place the file view at a specific location within the process's address space, you should use the MapViewOfFileEx function and specify the desired address. If there is not enough space at the specified address, the function fails.

Although CreateFileMapping works with remote files, it does not keep them coherent. For example, if two machines both map a file as writable, and both change the same page, each machine will only see its own writes to the page. When the data gets updated on the disk, it is not merged.


 Sharing a Memory Block

If two (or more) processes need to share a memory block not associated with a file, one process must use the CreateFileMapping function and specify (HANDLE)0xFFFFFFFF instead of an existing file handle. The corresponding file-mapping object accesses memory from the operating-system paging file. Processes sharing the operating-system paging file must create file views by using the MapViewOfFile or MapViewOfFileEx function just as when sharing a named file.


 Closing a File View

When a process has finished using the shared memory, it should destroy the file view in its address space by using the UnmapViewOfFile function. This invalidates the pointer to the shared memory. If any of the pages of the file view changed since the view was mapped, this function copies the changed pages to the physical file.

To copy a specified number of bytes from the file view to the physical file, you should use the FlushViewOfFile function. FlushViewOfFile does not destroy the file view.

For information on other ways to share data among applications, see Dynamic Data Exchange Management Library.


 Using File Mapping

Windows NT Overview
For more information, see the Windows 95 overview Using File Mapping.

The code samples in this guide illustrate how two processes might access an existing file as named shared memory.

If one or both processes write to the shared memory, the processes must use a semaphore to synchronize their access to the memory. For more information on synchronization, see Synchronization.

In the following code, the CreateFileMapping function creates a file-mapping object. When a corresponding file view is created, the process has read-and-write access to the memory.

hMapFile = CreateFileMapping(hFile,    /* current file handle */

    (LPSECURITY_ATTRIBUTES) NULL,      /* no security         */

    PAGE_READWRITE,                    /* read-write access   */

    0,                                 /* max. object size is */

    0,                                 /*   size of hFile     */

    "MyFileMappingObject");            /* name of map. object */

if (hMapFile == NULL) {

    ErrorHandler("Could not create file-mapping object.");

}

The following code uses the file-mapping object handle returned by CreateFileMapping to create a view of the file in the process's address space.

lpMapAddress = MapViewOfFile(hMapFile, /* handle to map. object */

    FILE_MAP_ALL_ACCESS,               /* read-write access     */

    0,                                 /* max. object size is   */

    0,                                 /*   size of hFile       */

    0);                                /* map entire file       */

if (lpMapAddress == NULL) {

    ErrorHandler("Could not map view of file.");

}

The MapViewOfFile function returns a pointer to the file view. The process can use the pointer to access the memory for whatever it needs to do.

In the next example, a second process uses the OpenFileMapping function to share the same memory. As in the original process, the MapViewOfFile function returns a pointer to the file view.

hMapFile = OpenFileMapping(FILE_MAP_ALL_ACCESS, /* r-w access  */

    FALSE,                             /* do not inherit       */

    "MyFileMappingObject");            /* name of mapping obj. */

if (hMapFile == NULL) {

    ErrorHandler("Could not open file-mapping object.");

}

lpMapAddress = MapViewOfFile(hMapFile, /* hndl. to map. obj.   */

    FILE_MAP_ALL_ACCESS,               /* read-write access   */

    0,                                 /* max. object size is */

    0,                                 /*   size of hFile     */

    0);                                /* map entire file     */

if (lpMapAddress == NULL) {

    ErrorHandler("Could not map view of file.");

}

Note that MapViewOfFile returns different addresses in different processes. To specify the location of the file view within a process's address space, use the MapViewOfFileEx function, rather than MapViewOfFile.

The following example uses the UnmapViewOfFile function to invalidate the pointer to the mapped memory. This destroys the file view in the process's address space. If any pages of the file view changed since the view was mapped, UnmapViewOfFile also copies the changed pages to the physical file.

if (!UnmapViewOfFile(lpMapAddress)) {

    ErrorHandler("Could not unmap view of file.");

}

The FlushViewOfFile function copies the specified number of bytes of the file view to the physical file but does not destroy the file view:

if (!FlushViewOfFile(lpMapAddress, dwBytesToFlush)) {

    ErrorHandler("Could not flush memory to disk.");

}


 File Mapping Functions

The following functions are used with file mapping.

CreateFileMapping
FlushViewOfFile
MapViewOfFile
MapViewOfFileEx
OpenFileMapping
UnmapViewOfFile


 File Systems

Applications based on the Microsoft® Win32® application programming interface (API) rely on file systems to store and retrieve information on mass storage devices. File systems provide the underlying support that applications need to create and access files and directories on the individual volumes associated with the devices.


 About File Systems

Depending on the configuration of a computer, a Win32-based application may have access to volumes managed by any of the following file systems:

•	New Technology file system (NTFS)

•	File allocation table (FAT) file system

•	Protected-mode FAT file system

•	High-performance file system (HPFS)

For example, applications that connect to network drives may encounter file systems that range from FAT to NTFS. Because different volumes may be managed by different file systems, it is important to understand the differences between file systems and to prepare applications to work effectively with all available file systems. The following sections describe these differences and present guidelines for handling them within applications.


 Guidelines

Each file system consists of one or more drivers and supporting dynamic-link libraries that define the data formats and features of the file system. These determine the conventions used for filenames, the level of security and recoverability available, and the general performance of input and output (I/O) operations. Before you access files and directories on a given volume, you should determine the capabilities of the file system by using the GetVolumeInformation function. The function returns values, such as the maximum length of filenames, that you can use to adapt your application to work effectively with the file system.

In general, you should always avoid using static buffers for filenames and paths. Instead, use the values returned by GetVolumeInformation to allocate buffers as you need them. If you must use static buffers, reserve 256 characters for filenames and 260 characters for paths. These are the maximums currently recommended for Win32-based applications.


 The New Technology File System

The New Technology file system (NTFS) organizes data on fixed disks. This file system supports object-oriented applications by treating all files as objects with user- and system-defined attributes. NTFS provides all the capabilities of the FAT and HPFS file systems without many of their limitations. Accessing files under NTFS is often faster than accessing similar files under the FAT or HPFS file systems.

NTFS is a fully recoverable file system. It is designed to restore consistency to a disk after a CPU failure, system crash, or I/O error. NTFS allows the operating system to recover without your having to use disk-checking utilities. However, NTFS provides these utilities in case recovery fails or corruption occurs outside the control of the file system. NTFS also includes features not present in HPFS or FAT, such as security, Unicode filenames, automatic creation of MS-DOS® aliases, multiple data streams, and unique functionality specific to the POSIX subsystem. For more information about security, see Security.

NTFS follows the filename conventions described in the HPFS section, but it also supports Unicode filenames.

NTFS cannot manipulate a file's extended attributes if the file was created on HPFS.


 The File Allocation Table File System

The FAT file system organizes data on fixed disks and floppy disks. The distinguishing feature of the FAT file system is its filename convention. The filename convention consists of a filename (up to eight characters), a separating period (.), and a filename extension (up to three characters).

The main advantage of FAT volumes is that they are accessible by MS-DOS, Microsoft® Windows®, and OS/2 systems. FAT is also the only file system currently supported on floppy disks and other removable media.

Valid FAT filenames have the following form:

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

The drive parameter must name an existing drive and can be any letter from A through Z. The drive letter must be followed by a colon (:).

The directory parameter specifies the directory that contains the file's directory entry. This value must be followed by a backslash (\) to separate it from the filename. If the specified directory is not in the current directory, directory must include the names of all directories in the file's path, separated by backslashes. The root directory is specified by using a backslash at the beginning of the name. For example, if the directory ABCD is in the directory SAMPLE and SAMPLE is in the root directory, the correct directory specification is \SAMPLE\ABCD. A directory name consists of any combination of up to eight letters, digits, or the following special characters:

$ % ' − _ @ { } ~ ` ! # ( )

A directory name can also have an extension that is any combination of up to three letters, digits, or special characters, preceded by a period (.).

The filename and extension parameters specify the file. Filename can be any combination of up to eight letters, digits, or the special characters previously listed; extension can be any combination of up to three letters, digits, or special characters, all preceded by a period. Filename can also include embedded (preceded and followed by one or more letters, digits, or special characters just noted) spaces. For example, the string "disk 1" is a legal value for filename.

FAT volumes do not distinguish between uppercase and lowercase letters.


 The Protected-Mode FAT File System

The protected-mode FAT file system organizes data on fixed and floppy disks. Protected-mode FAT is compatible with the FAT file system, using file allocation tables and directory entries to store information about the contents of a disk. Protected-mode FAT also supports long filenames, storing these names and other information such as the date and time the file was last accessed in the FAT structures.

Protected-mode FAT allows filenames of up to 255 characters, including the terminating null character. This is similar to the New Technology file system (NTFS) which allows filenames of up to 256 characters.

Protected-mode FAT allows paths of up to 260 characters, including the terminating null character.


 The High-Performance File System

HPFS organizes data on fixed disks. Filenames under HPFS can be any practical length (up to 254 characters) and can contain characters that are not valid for the FAT file system, such as spaces and periods. In many cases, accessing files under HPFS is faster than accessing similar files under the FAT file system.

Blank spaces can be used anywhere in an HPFS filename or directory name, but blank spaces and periods at the end of a filename are ignored. There is no requirement that HPFS filenames have extensions; however, many applications still create and use them.

The following special characters can also be used in HPFS filenames:

, + = [ ] ; _

An HPFS filename can be all uppercase, all lowercase, or mixed case. The case is preserved for directory listings but is ignored in file searches and all other system operations. Therefore, in a given directory, there cannot be more than one file with the same name when the only difference is case.


 Files

A file is the basic unit of storage that enables a computer to distinguish one set of information from another.


 About Files

In Microsoft® Windows®, files are stored on storage media, such as disks or tapes, and can be organized into groups called directories. The Windows file input and output (I/O) functions enable applications to create, open, modify, and delete files and directories. They also enable applications to obtain system information, such as what disk drives are present.


 System Organization

A volume is a storage device, such as a fixed disk or floppy disk, formatted to store directories and files. Each volume has a root directory. Directories and files on the volume are organized in a tree structure that starts at the root directory. Each directory entry identifies the name, attributes, location, and size of the file or subdirectory.

A large volume can be divided into more than one logical volume, also called a partition. To the user and to the operating system, each partition appears to be a separate volume.

A file system is operating system software that manages the low-level organization of files on a volume. Windows supports the following file systems:

•	File allocation table (FAT)

•	High-performance file system (HPFS)

•	New Technology file system (NTFS)

The type of file system defines the filename conventions on a volume and may also provide specific file system features, such as security, recoverability, and high I/O performance. Each volume can use a different file system.

For more information on the FAT, HPFS, and NTFS file systems, see File Systems.


 Accessing Files

The first time a file function accesses a volume and whenever a volume is placed in a floppy-disk drive, Windows examines the volume to determine the appropriate file system. Thereafter, Windows manages all I/O to that volume through the device driver supporting the file system. If an error occurs, the driver returns it to Windows, which then passes it back to the application.

The Windows file functions enable applications to access files regardless of the underlying file system. However, capabilities may vary depending on the file system and/or operating system in use. For example, the CreateFile function includes a security parameter that provides no security benefits for an application written for Windows running with current versions of MS-DOS.

The Windows file functions that create, open, and delete files and directories identify them by their names. These functions store or search for the file or directory in the current directory on the current disk drive, unless the name explicitly specifies a path to a different directory, disk drive, or both.


 Filename Conventions

Although each file system can have specific rules about the formation of individual components in a directory or filename, all file systems follow the same general conventions for combining components. For example, the FAT file system requires file and directory names to have the 8.3-character filename format, the HPFS file system allows names to be up to 254 characters, and the NTFS file system allows names to be up to 255 characters. All three file systems use the backslash (\) character to separate directory names and the filename when forming a path.

General rules for applications creating names for directories and files or processing names supplied by the user include the following:

•	Use any character in the current code page for a name, but do not use a path separator, a character in the range 0 through 31, or any character explicitly disallowed by the file system. A name can contain characters in the extended character set (128−255).

•	Use the backslash (\), the forward slash (/), or both to separate components in a path. No other character is acceptable as a path separator.

•	Use a period (.) as a directory component in a path to represent the current directory.

•	Use two consecutive periods (..) as a directory component in a path to represent the parent of the current directory.

•	Use a period (.) to separate components in a directory name or filename.

•	Do not use the following characters in directory names or filenames, because they are reserved for Windows:

< > : " / \ |

•	Do not use reserved words, such as aux, con, and prn, as filenames or directory names.

•	Process a path as a null-terminated string. The maximum length for a path is given by MAX_PATH.

The wide (Unicode) versions of the CreateDirectory, FindFirstFile, GetFileAttributes, and SetFileAttributes functions permit paths that exceed the MAX_PATH length if the path has the "\\?\" or "\\?\UNC\" prefix. These prefixes direct the functions to turn off path parsing. Use the "\\?\" prefix with paths for local storage devices and the "\\?\UNC\" prefix with paths having the Universal Naming Convention format.

•	Do not assume case sensitivity. Consider names such as OSCAR, Oscar, and oscar to be the same.

By following the rules listed in this section, an application can create valid names for files and directories regardless of the file system in use.

Long Filenames on Windows NT FAT Partitions

You can create or open long filenames on Windows NT FAT partitions.

The operating system stores the long filenames on disk in Unicode. This means that the original long file name is always preserved, even if it contains extended characters, and regardless of the code page that is active during a disk read or write operation.

The legal character set for these long filenames is the NTFS legal character set, less one character: the colon (':') that NTFS uses for opening alternate file streams. This means that you can freely copy files between NTFS and FAT partitions without losing any file name information.

The operating system stores the long filenames on disk masquerading as extra volume label directory entries. These entries are not available from the DOS dir command, but they are available from the Windows NT dir command. When you create a long filename on a Windows NT FAT partition, the operating system creates a corresponding short 8.3 form of the name, just as it does on an NTFS partition.


 File Operations

This section describes the file I/O operations and operating system information provided by the file functions in the Microsoft® Win32® application programming interface (API).


 Creating and Opening Files with the CreateFile Function

The CreateFile function can create a new file or open an existing file. When an application uses this function, it must specify whether it will read from the file, write to the file, or both. The application must also specify what action to take whether or not the file exists. For example, an application can specify that CreateFile always be used to create the file. As a result, the function creates the file if it does not exist and overwrites the file if it does exist.

CreateFile also enables an application to specify whether it wants to share the file for reading, writing, both, or neither. A file that is not shared cannot be opened more than once by the first application nor by another application until the first application has closed.

Windows assigns a unique identifier, called a file handle, to each file that is opened or created. An application can use the file handle in functions that read from, write to, and describe the file. It is valid until the file is closed. When an application starts, it inherits all open file handles from the process that started it, if the handles are inheritable. For more information about processes, see Processes and Threads.

For information about the standard input, standard output, and standard error file handles, see Consoles and Character-Mode Support.

An application should check the return value of CreateFile before attempting to use the handle to access the file. If an error occurs, the application can use the GetLastError function to get extended error information.


 Closing and Deleting Files

To use operating system resources efficiently, an application should close files when they are no longer needed by using the CloseHandle function. If a file is open when an application terminates, Windows closes it automatically.

The DeleteFile function can be used to delete a file. The file must, however, be closed before any attempt to delete it.


 Copying and Moving Files

Before a file can be copied, it must be closed or opened only for reading. No thread can have the file opened for writing. To copy an existing file to a new one, use the CopyFile function. Applications can specify whether CopyFile fails if the new file already exists.

A file must also be closed before an application can move it. The MoveFile function copies an existing file to a new location and deletes the original. Applications frequently use this function to rename files.


 Reading from and Writing to a File

Every open file has a file pointer that specifies the next byte to be read or the location to receive the next byte written. When a file is opened for the first time, Windows places the file pointer at the beginning of the file. As each byte is read or written, Windows advances the file pointer. An application can also move the file pointer by using the SetFilePointer function.

An application reads from and writes to a file by using the ReadFile and WriteFile functions. These functions require a handle of a file to be opened for reading and writing, respectively. ReadFile and WriteFile read and write a specified number of bytes at the location indicated by the file pointer. The data is read and written exactly as given; the functions do not format the data.

When the file pointer reaches the end of a file and the application attempts to read from the file, no error occurs, but no bytes are read. Therefore, reading zero bytes without an error means the program has reached the end of the file.

An application can truncate or extend a file by using the SetEndOfFile function. This function sets the end of file to the current position of the file pointer. A WriteFile of zero bytes does nothing.

When an application writes to a file, Windows usually collects the data being written in an internal buffer and writes the data to the disk on a regular basis.

An application can force the operating system to write the contents of the buffer to the disk by using the FlushFileBuffers function. Alternatively, an application can specify that write operations are to bypass the internal buffer and write directly to the disk by setting a flag when the file is created or opened by using the CreateFile function.

If there is data in the internal buffer when the file is closed, Windows does not automatically write the contents of the buffer to the disk before closing the file. If the application does not force the operating system to write the buffer to disk before closing the file, the caching algorithm determines when the buffer is written.

Locking and Unlocking Files

Although Windows allows more than one application to open a file and write to it, applications must not write over each other's work. An application can prevent this problem by temporarily locking a region in a file. The LockFile function locks a specified range of bytes in a file. The range may extend beyond the current end of the file. Locking part of a file prevents all other processes from reading or writing anywhere in the specified area. Attempts to read from or write to a region locked by another process always fail. The application unlocks the region by using the UnlockFile function. An application should unlock all locked areas before closing a file.

Synchronizing Input and Output

Asynchronous input and output is a type of I/O that allows some I/O functions to return immediately, even though an I/O request is still pending. Asynchronous I/O enables an application to continue with other processing and wait for the I/O to be completed at a later time. Asynchronous I/O is also called overlapped I/O.

The ReadFile and WriteFile functions enable an application to specify an OVERLAPPED structure that indicates where to position the file pointer before the read or write operation. The handle of the file being read from or written to must have been opened with the FILE_FLAG_OVERLAPPED flag. The OVERLAPPED structure can also contain an event handle on which the WaitForSingleObject or WaitForMultipleObjects function can wait.

An application can also wait on the file handle to synchronize the completion of an I/O operation, but doing so requires extreme caution. Each time an I/O operation is started, the operating system sets the file handle to the nonsignaled state. Each time an I/O operation is completed, the operating system sets the file handle to the signaled state. Therefore, if an application starts two I/O operations and waits on the file handle, there is no way to determine which operation is finished when the handle is set to the signaled state. If an application must perform multiple asynchronous I/O operations on a single file, it should wait on the event handle in the OVERLAPPED structure for each I/O operation, rather than on the file handle.

The ReadFileEx and WriteFileEx functions enable an application to specify a routine to execute when the asynchronous I/O request is completed.

For more information about synchronization, see Synchronization.


 Searching for Files

An application can search the current directory for all filenames that match a given pattern by using the FindFirstFile, FindNextFile, and FindClose functions. The pattern must be a valid filename and can include wildcard characters.

FindFirstFile creates a handle that FindNextFile uses to search for other files with the same pattern. Both functions also return information about the file that was found in a WIN32_FIND_DATA structure. This information includes the filename, size, attributes, and time. The FindClose function destroys the handle created by FindFirstFile.

An application can search for a single file on a specific path by using the SearchPath function.


 Creating Temporary Files

Applications can create temporary filenames with the GetTempFileName function. The GetTempPath function retrieves the path to the directory where temporary files are to be created.


 Getting Information About Files

Nine characteristics called attributes may be associated with a file. The attributes can be one or more of the following values.

Value	Meaning
FILE_ATTRIBUTE_ARCHIVE	The file is an archive file. Applications use this value to mark files for backup or removal.
FILE_ATTRIBUTE_DIRECTORY	The file is a directory.
FILE_ATTRIBUTE_HIDDEN	The file is hidden. It is not included in an ordinary directory listing.
FILE_ATTRIBUTE_NORMAL	The file has no other attributes. This value is valid only if used alone.
FILE_ATTRIBUTE_READONLY	The file is read-only. Applications can read from the file but cannot write to it or delete it.
FILE_ATTRIBUTE_SYSTEM	The file is part of the operating system or is used exclusively by it.
FILE_ATTRIBUTE_TEMPORARY	The file is being used for temporary storage. Applications can write to the file only if absolutely necessary. Most of the file's data remains in memory without being flushed to the media, because the file will soon be deleted.
FILE_ATTRIBUTE_ATOMIC_WRITE	Reserved; do not use.
FILE_ATTRIBUTE_XACTION_WRITE	Reserved; do not use.
An application can retrieve and set a file's attributes by using the GetFileAttributes and SetFileAttributes functions. Applications cannot, however, use SetFileAttributes to set the directory attribute.

The GetFileType function returns the type of a file: disk, character (such as a console), pipe, or unknown. The GetFileSize function returns the size of a file. Applications can retrieve the full path of a file by using the GetFullPathName function.

Applications can retrieve and set the date and time a file was created, last modified, or last accessed by using the GetFileTime and SetFileTime functions. For more information about file times, see Time.


 Directory Operations

When an application creates a new file, the operating system adds it to the specified directory. Each directory can have any number of files, up to the physical limit of the disk. An application can create new directories and delete existing directories by using the CreateDirectory and RemoveDirectory functions. An application cannot delete a directory unless it is empty.

The directory at the end of the active path is called the current directory; it is the directory in which the active application started, unless explicitly changed. An application can determine which directory is current by using the GetCurrentDirectory function. An application can change the current directory by using the SetCurrentDirectory function.

On the Windows NT platform, you can obtain a handle to a directory by calling the CreateFile function with the FILE_FLAG_BACKUP_SEMANTICS flag set. You can pass a directory handle to some functions in place of a file handle.

An application can monitor the contents of a directory and its subdirectories by using the FindFirstChangeNotification, FindNextChangeNotification, and FindCloseChangeNotification functions. Waiting for a change notification is similar to having a read operation pending against a directory and, if necessary, its subdirectories. When something changes within the directory being watched, the read operation is completed. For example, an application can use these functions to update a directory listing whenever a filename within the monitored directory changes.

An application can specify a set of conditions that trigger a change notification by using the FindFirstChangeNotification function. The conditions include changes to filenames, directory names, attributes, file size, time of last write, and security. This function also returns a handle that can be waited on by using the WaitForSingleObject or WaitForMultipleObjects function. If the wait condition is satisfied, FindNextChangeNotification can be used to provide a notification handle to wait on subsequent changes.

The FindCloseChangeNotification function closes the notification handle.


 Getting System Information

Windows provides several functions that applications can use to obtain information about the file system, operating system, and hardware.

The GetVolumeInformation function retrieves information about the file system on a given volume. This information includes the volume name, volume serial number, file system name, file system flags, maximum length of a filename, and so on.

The GetSystemDirectory and GetWindowsDirectory functions retrieve the paths to the Windows system directory and the Windows directory, respectively.

The GetDiskFreeSpace function retrieves organizational information about a disk, including the number of bytes per sector, the number of sectors per cluster, the number of free clusters, and the total number of clusters.

The GetDriveType function indicates whether the disk referenced by the specified disk drive is a removable, fixed, CD-ROM, RAM, or network drive.

The GetLogicalDrives function identifies the drives currently present on the operating system. The GetLogicalDriveStrings function retrieves a null-terminated string for each drive present on the operating system. Use these strings whenever a root directory is required.


 File Compression

Windows NT release 3.51 supports file compression on an individual file basis for volumes that use the NTFS file system.


 Compression Attribute

On volumes that use the NTFS file system, each file and directory has a compression attribute. Other file systems may also implement a compression attribute for individual files and directories.

You can determine whether a file system supports a compression attribute for files and directories by calling the GetVolumeInformation function and examining the FS_FILE_COMPRESSION bit flag.

If a file's compression attribute is set, all of the data in the file is compressed. If the attribute is clear, none of the data in the file is compressed. There is no partially compressed state. The compression attribute is a simple Boolean indicator of compression state.

A directory's compression attribute provides a default compression attribute for newly created files and subdirectories. When you call CreateFile or CreateDirectory to create a new file or directory, the new file or directory inherits the compression attribute of its parent directory.


 Compression State

Each file and directory on a volume that supports compression for individual files and directories has a compression state. Windows NT release 3.51 provides such support for volumes that use the NTFS file system.

Whereas the compression attribute of a file or directory indicates simply whether the file or directory is compressed or not compressed, the compression state also specifies the format of any compressed data.

Compression state is encoded as a 16-bit value. A compression state value of zero indicates that a file is not compressed. A value of one indicates that a file is compressed, using the default compression format for its parent directory. Any other value indicates that a file is compressed, using the compression format encoded by the compression state value.

For directories, the compression state provides a default compression state for newly created files and subdirectories. In other words, new files and directories inherit the compression state of their parent directory.


 Determining Compression Attribute and State

Use the GetFileAttributes function to determine the compression attribute of a file or directory.

Use the FSCTL_GET_COMPRESSION DeviceIoControl operation to determine the compression state of a file or directory.


 Setting Compression Attribute and State

On volumes whose file system supports the compression of files or directories, such as NTFS volumes under Windows NT release 3.51, new files and subdirectories inherit the compression attribute and compression state of their parent directory.

Use the FSCTL_SET_COMPRESSION DeviceIoControl operation to set the compression state of a file or directory. This operation also sets the compression attribute of the file or directory.

Setting the compression state of a file to a nonzero value compresses the file, using the compression format encoded by the compression state value. Setting a file's compression state to zero decompresses the file. These are synchronous operations. The file is compressed or decompressed immediately when you set its compression state.

Setting a directory's compression state does not cause any immediate compression or decompression. Instead, setting a directory's compression state sets a default compression state that will be given to all newly created files and subdirectories.


 Obtaining the Size of a Compressed File

Use the GetCompressedFileSize function to obtain the compressed size of a file. If the file is compressed, its compressed size will be less than its uncompressed size. Use the GetFileSize).function to determine the uncompressed size of a file.


 Using Files

The Windows file functions enable applications to access files regardless of the underlying file system. However, their functionality may vary depending on the operating system in use. If you have questions about a specific function, consult the reference information for that function.

For functions that manipulate files, the filenames may be relative to the current directory. A filename is relative to the current directory if it does not begin with a disk designator or directory name separator, such as a backslash (\). If the filename begins with a disk designator, it is a fully qualified path.

The examples in this section illustrate how to perform the following tasks:

•	Creating and opening files

•	Reading, writing, and locking files

•	Creating and using a temporary file

•	Searching for files and changing file attributes

•	Monitoring changes in a directory or directory tree

•	Testing for the end of the file

•	Retrieving a file pointer


 Creating and Opening Files

You can use the CreateFile function to create a new file or open an existing file. You must specify the filename, preferred access, share mode, creation instructions, and attributes.

The following example returns a handle of the current console input buffer.

HANDLE hReadWriteInput;

hReadWriteInput = CreateFile("CONIN$",

    GENERIC_READ | GENERIC_WRITE,

    FILE_SHARE_READ | FILE_SHARE_WRITE, /* share with cmd.      */

    NULL,

    OPEN_EXISTING,              /* open already created console */

    0,                          /* normal file open             */

    NULL

    );

For more information about consoles, see Consoles and Character-Mode Support.

In the following example, CreateFile opens an existing file for reading.

HANDLE hFile;

hFile = CreateFile("MYFILE.TXT",           /* open MYFILE.TXT    */

                GENERIC_READ,              /* open for reading   */

                FILE_SHARE_READ,           /* share for reading  */

                (LPSECURITY_ATTRIBUTES) NULL, /* no security     */

                OPEN_EXISTING,             /* existing file only */

                FILE_ATTRIBUTE_NORMAL,     /* normal file        */

                (HANDLE) NULL);            /* no attr. template  */

if (hFile == INVALID_HANDLE_VALUE) {

        ErrorHandler("Could not open file.");   /* process error */

}

In this example, CreateFile succeeds only if a file named MYFILE.TXT already exists in the current directory. An application should check the return value of CreateFile before attempting to use the handle to access the file. If an error occurs, the application should use the GetLastError function to get extended error information and respond accordingly.

A file must be closed before it can be deleted. The following lines close and delete the MYFILE.TXT file.

CloseHandle(hFile);

DeleteFile("MYFILE.TXT");

In the following example, CreateFile creates a new file and opens it for writing.

HANDLE hFile;

hFile = CreateFile("MYFILE.TXT",           /* create MYFILE.TXT  */

             GENERIC_WRITE,                /* open for writing   */

             0,                            /* do not share       */

             (LPSECURITY_ATTRIBUTES) NULL, /* no security        */

             CREATE_ALWAYS,                /* overwrite existing */

             FILE_ATTRIBUTE_NORMAL |       /* normal file        */

             FILE_FLAG_OVERLAPPED,         /* asynchronous I/O   */

             (HANDLE) NULL);               /* no attr. template  */

if (hFile == INVALID_HANDLE_VALUE) {

    ErrorHandler("Could not open file.");  /* process error      */

}

In addition to the standard attributes (read only, hidden, system, and so on), you can also specify security attributes by including a pointer to a SECURITY_ATTRIBUTES structure as the fourth parameter. However, the underlying operating system must support security for these attributes for them to have any effect. For more information about security, see Security.


 Reading, Writing, and Locking Files

The ReadFile function requires a file handle that is open for reading, or reading and writing. ReadFile copies a specified number of bytes, up to the end of the file, to a specified buffer. It returns the actual number of bytes read in a variable specified by its fourth parameter.

The WriteFile function requires a file handle that is open for writing, or writing and reading. WriteFile copies a specified number of bytes, up to the end of the buffer, to a specified file. It returns the actual number of bytes written in a variable specified by its fourth parameter.

The following example illustrates a possible flow for using callback completion asynchronous I/O.

Completion Routine:

VOID IoCompletionRoutine(DWORD dwErrorCode,

        DWORD dwNumberOfBytesTransfered, LPOVERLAPPED lpOverlapped)

{

    /* If an I/O error occurred, display the error and then exit. */

    if (dwErrorCode) {

        printf("FATAL I/O Error %ld I/O Context %lx.%lx\n",

            dwErrorCode, lpOverlapped, lpOverlapped->hEvent);

        ExitProcess(dwErrorCode);

    }

    LocalFree(lpOverlapped);

}

Main Thread:

VOID IoWorkerThread(VOID)

{

    HANDLE HandleVector[2];

    DWORD CompletionStatus;

    PIOREQUEST IoRequestPacket;

    LPOVERLAPPED Overlapped;

    BOOL IoOperationStatus;

    HandleVector[0] = IoWorkerListLock;

    HandleVector[1] = IoWorkerListSemaphore;

    for(;;) {

        /* Do an alertable wait on the handle vector. Both objects */

        /* being signaled at the same time means that there is an  */

        /* I/O request in the queue and the caller has exclusive   */

        /* access to the queue.                                    */

        CompletionStatus = WaitForMultipleObjectsEx(2, HandleVector,

                TRUE, INFINITE, TRUE);

        /* If the wait failed, error out. */

        if (CompletionStatus == 0xFFFFFFFF) {

            printf("FATAL WAIT ERROR %ld\n", GetLastError());

            ExitProcess(1);

        }

        /* If an I/O completion occurred, wait for another         */

        /* I/O request or I/O completion.                          */

        if (CompletionStatus != WAIT_IO_COMPLETION) {

        /* The wait was satisfied. Ownership of the I/O            */

        /* request queue is exclusive, and there is something in   */

        /* the queue. To insert something in the queue, the        */

        /* inserter gets the list lock (mutex), inserts an entry,  */

        /* signals the list semaphore, and finally releases the    */

        /* list lock.                                              */

            IoRequestPacket = RemoveHeadList(&IoRequestList);

            ReleaseMutex(IoWorkerListLock);

            /* Allocate an overlapped structure. */

            Overlapped = LocalAlloc(LMEM_ZEROINIT,

                    sizeof(OVERLAPPED));

            if (!Overlapped) {

                printf("FATAL allocation error\n");

                ExitProcess(1);

            }

            Overlapped->Offset = IoRequestPacket->Offset;

            Overlapped->OffsetHigh = IoRequestPacket->OffsetHigh;

            Overlapped->hEvent =

                    IoRequestPacket->dwAdditionalIoContext;

            if (IoRequestPacket->bRead) {

                IoOperationStatus =

                            ReadFileEx(IoRequestPacket->hFile,

                    IoRequestPacket->lpBuffer,

                    IoRequestPacket->dwTransferCount,

                    Overlapped, IoCompletionRoutine);

            }

            else {

                IoOperationStatus =

                    WriteFileEx(IoRequestPacket->hFile,

                        IoRequestPacket->lpBuffer,

                        IoRequestPacket->dwTransferCount,

                        Overlapped,

                        IoCompletionRoutine);

            }

            /* Test to see if the I/O was queued successfully. */

            if (!IoOperationStatus) {

                printf("FATAL I/O Error %ld I/O Context %lx.%lx\n",

                    GetLastError(), Overlapped, Overlapped->hEvent);

                ExitProcess(1);

            }

            /* The I/O queued successfully. Go back into the */

            /* alertable wait for I/O completion or for      */

            /* more I/O requests.                            */

        }

    }

}

The SetFilePointer function moves the file pointer a specified number of bytes, relative to the beginning or end of the file, or the file pointer's current position. If a positive number of bytes is specified, SetFilePointer moves the file pointer toward the beginning of the file; a negative value moves the pointer toward the end of the file.

The following example appends one file to the end of another file. The application opens two files by using CreateFile: ONE.TXT is opened for reading, and TWO.TXT is opened for writing. Then the application appends the contents of ONE.TXT to the end of TWO.TXT by reading and writing 4K blocks by using ReadFile and WriteFile. Before writing to the second file, the application sets the second file's pointer to the end of the file by using SetFilePointer and locks the area to be written by using LockFile. This prevents another process from accessing the area while the write is in progress. After each write operation, UnlockFile unlocks the locked area.

HANDLE hFile;

HANDLE hAppend;

DWORD  dwBytesRead, dwBytesWritten, dwPos;

char   buff[4096];

/* Open the existing file. */

hFile = CreateFile("ONE.TXT",     /* open ONE.TXT       */

    GENERIC_READ,                 /* open for reading   */

    0,                            /* do not share       */

    (LPSECURITY_ATTRIBUTES) NULL, /* no security        */

    OPEN_EXISTING,                /* existing file only */

    FILE_ATTRIBUTE_NORMAL,        /* normal file        */

    (HANDLE) NULL);               /* no attr. template  */

if (hFile == INVALID_HANDLE_VALUE) {

    ErrorHandler("Could not open ONE.");  /* process error */

}

/*

 * Open the existing file, or if the file does not exist,

 * create a new file.

 */

hAppend = CreateFile("TWO.TXT",   /* open TWO.TXT       */

    GENERIC_WRITE,                /* open for writing   */

    0,                            /* do not share       */

    (LPSECURITY_ATTRIBUTES) NULL, /* no security        */

    OPEN_ALWAYS,                  /* open or create     */

    FILE_ATTRIBUTE_NORMAL,        /* normal file        */

    (HANDLE) NULL);               /* no attr. template  */

if (hAppend == INVALID_HANDLE_VALUE) {

    ErrorHandler("Could not open TWO.");    /* process error */

}

/*

 * Append the first file to the end of the second file.

 * Lock the second file to prevent another process from

 * accessing it while writing to it. Unlock the

 * file when writing is finished.

 */

do {

  if (ReadFile(hFile, (LPSTR) buff, 4096, &dwBytesRead, NULL)) {

      dwPos = SetFilePointer(hAppend, 0, (LPLONG) NULL, FILE_END);

      LockFile(hAppend, dwPos, 0, dwPos + dwBytesRead, 0);

      WriteFile(hAppend, (LPSTR) buff, dwBytesRead,

          &dwBytesWritten, NULL);

      UnlockFile(hAppend, dwPos, 0, dwPos + dwBytesRead, 0);

  }

} while (dwBytesRead == 4096);

/* Close both files. */

CloseHandle(hFile);

CloseHandle(hAppend);


 Creating and Using a Temporary File

The following example copies one file to another. The second file is an uppercase version of the first file.

The application opens the ORIGINAL.TXT file by using CreateFile. The application then obtains a temporary filename with the GetTempFileName function and uses CreateFile to create the temporary file. The application reads 4K blocks into a buffer, converts the buffer contents to uppercase, and writes the converted buffer to the temporary file. When all of ORIGINAL.TXT has been written to the temporary file, the application closes both files and renames the temporary file to ALLCAPS.TXT by using the MoveFile function.

HANDLE hFile;

HANDLE hTempFile;

DWORD  dwBytesRead, dwBytesWritten, dwPos;

char szTempName[MAX_PATH];

char buffer[4096];

/* Open the existing file. */

hFile = CreateFile("ORIGINAL.TXT",        /* filename   */

    GENERIC_READ,                 /* open for reading   */

    0,                            /* do not share       */

    (LPSECURITY_ATTRIBUTES) NULL, /* no security        */

    OPEN_EXISTING,                /* existing file only */

    FILE_ATTRIBUTE_NORMAL,        /* normal file        */

    (HANDLE) NULL);               /* no attr. template  */

if (hFile == INVALID_HANDLE_VALUE) {

    ErrorHandler("Could not open file."); /* process err. on fail*/

}

/* Create a temporary file. */

GetTempFileName("\\TEMP", /* dir. for temp. files            */

    "NEW",                /* temp. filename prefix           */

    0,                    /* create unique name w/ sys. time */

    (LPTSTR) szTempName); /* buffer for name                 */

hTempFile = CreateFile((LPTSTR) szTempName,  /* filename     */

    GENERIC_READ | GENERIC_WRITE, /* open for read-write     */

    0,                            /* do not share            */

    (LPSECURITY_ATTRIBUTES) NULL, /* no security             */

    CREATE_ALWAYS,                /* overwrite existing      */

    FILE_ATTRIBUTE_NORMAL,        /* normal file             */

    (HANDLE) NULL);               /* no attr. template       */

if (hTempFile == INVALID_HANDLE_VALUE) {

    ErrorHandler("Could not create temporary file.");

}

/*

 * Read 4K blocks to the buffer.

 * Change all characters in the buffer to uppercase.

 * Write the buffer to the temporary file.

 */

do {

    if (ReadFile(hFile, (LPSTR) buffer, 4096,

        &dwBytesRead, NULL)) {

        CharUpperBuff((LPTSTR) buffer, dwBytesRead);

        WriteFile(hTempFile, (LPSTR) buffer, dwBytesRead,

            &dwBytesWritten, NULL);

    }

} while (dwBytesRead == 4096);

/* Close both files. */

CloseHandle(hFile);

CloseHandle(hTempFile);

/* Move the temporary file to the new text file. */

if (!MoveFile(szTempName, "ALLCAPS.TXT")) {

    ErrorHandler("Could not move temp. file.");

}


 Searching for Files and Changing File Attributes

The following example copies all text files in the current directory to a new directory of read-only files named \TEXTRO. Files in the new directory are changed to read only, if necessary.

The application uses the GetCurrentDirectory function to retrieve the current directory path. This function is also used to return to the current directory after changing to the \TEXTRO directory.

The application then creates the \TEXTRO directory by using the CreateDirectory function.

The application searches the current directory for all .TXT files by using the FindFirstFile and FindNextFile functions. Each .TXT file is copied to the \TEXTRO directory. After a file is copied, the GetFileAttributes function determines whether the file is read only. If the file is not read only, the application changes directories to \TEXTRO and converts the copied file to read only by using the SetFileAttributes function.

After all .TXT files in the current directory have been copied, the application closes the search handle by using the FindClose function.

WIN32_FIND_DATA FileData;

HANDLE hSearch;

DWORD dwAttrs;

char szDirPath[] = "c:\\TEXTRO\\";

char szNewPath[MAX_PATH];

char szHome[MAX_PATH];

BOOL fFinished = FALSE;

/* Create a new directory. */

if (!CreateDirectory(szDirPath, NULL)) {

    ErrorHandler("Couldn't create new directory.");

}

/* Start searching for .TXT files in the current directory. */

hSearch = FindFirstFile("*.txt", &FileData);

if (hSearch == INVALID_HANDLE_VALUE) {

    ErrorHandler("No .TXT files found.");

}

/*

 * Copy each .TXT file to the new directory

 * and change it to read only, if not already.

 */

while (!fFinished) {

    lstrcpy(szNewPath, szDirPath);

    lstrcat(szNewPath, FileData.cFileName);

    if (CopyFile(FileData.cFileName, szNewPath, FALSE)) {

        dwAttrs = GetFileAttributes(FileData.cFileName);

        if (!(dwAttrs & FILE_ATTRIBUTE_READONLY)) {

                SetFileAttributes(szNewPath,

                    dwAttrs | FILE_ATTRIBUTE_READONLY);

            }

    }

    else {

        ErrorHandler("Couldn't copy file.");

    }

    if (!FindNextFile(hSearch, &FileData))

        if (GetLastError() == ERROR_NO_MORE_FILES) {

            MessageBox(hwnd, "No more .TXT files.",

                "Search completed.", MB_OK);

            fFinished = TRUE;

        }

        else {

            ErrorHandler("Couldn't find next file.");

        }

}

/* Close the search handle. */

if (!FindClose(hSearch)) {

    ErrorHandler("Couldn't close search handle.");

}


 Monitoring Changes in a Directory or Directory Tree

The following example monitors the directory tree starting at C:\ for directory name changes. It also monitors the C:\WINDOWS directory for filename changes.

The example uses the FindFirstChangeNotification function to create two notification handles and the WaitForMultipleObjects function to wait on the handles. Whenever a directory is created or deleted in the tree starting at C:\ , the example updates the entire directory tree. Whenever a file is created or deleted in the C:\WINDOWS directory, the example refreshes the WINDOWS directory. The FindNextChangeNotification function restarts the change notification each time the example processes a change.

DWORD dwWaitStatus;

HANDLE dwChangeHandles[2];

/*

 * Watch the C:\WINDOWS directory for file creation and

 * deletion.

 */

dwChangeHandles[0] = FindFirstChangeNotification(

    "C:\\WINDOWS",                 /* directory to watch       */

    FALSE,                         /* do not watch the subtree */

    FILE_NOTIFY_CHANGE_FILE_NAME); /* watch filename changes   */

if (dwChangeHandles[0] == INVALID_HANDLE_VALUE)

    ExitProcess(GetLastError());

/*

 * Watch the C:\ subtree for directory creation and

 * deletion.

 */

dwChangeHandles[1] = FindFirstChangeNotification(

    "C:\\",                        /* directory to watch      */

    TRUE,                          /* watch the subtree       */

    FILE_NOTIFY_CHANGE_DIR_NAME);  /* watch dir. name changes */

if (dwChangeHandles[1] == INVALID_HANDLE_VALUE)

    ExitProcess(GetLastError());

/*

 * Change notification is set. Now wait on both notification

 * handles and refresh accordingly.

 */

while (TRUE) {

  /* Wait for notification. */

  dwWaitStatus = WaitForMultipleObjects(2, dwChangeHandles,

      FALSE, INFINITE);

  switch (dwWaitStatus) {

    case WAIT_OBJECT_0:

      /*

       * A file was created or deleted in C:\WINDOWS.

       * Refresh this directory and restart the

       * change notification. RefreshDirectory is an

       * application-defined function.

       */

      RefreshDirectory("C:\\WINDOWS")

      if (FindNextChangeNotification(dwChangeHandles[0]) == FALSE)

          ExitProcess(GetLastError());

      break;

    case WAIT_OBJECT_0 + 1:

      /*

       * A directory was created or deleted in C:\.

       * Refresh the directory tree and restart the

       * change notification. RefreshTree is an

       * application-defined function.

       */

      RefreshTree("C:\\");

      if (FindNextChangeNotification(dwChangeHandles[1]) == FALSE)

          ExitProcess(GetLastError());

      break;

       default:

            ExitProcess(GetLastError());

  }

}


 Testing for the End of the File

The ReadFile function checks for the end-of-file condition (eof) differently for synchronous and asynchronous read operations. When a synchronous read operation reaches the end of a file, ReadFile returns TRUE and sets the variable pointed to by lpNumberOfBytesRead to zero. An asynchronous read operation can encounter the end of a file during the initiating call to ReadFile or during subsequent asynchronous operation.

The test for end-of-file during a synchronous read operation is simple, as shown in the following example:

// attempt a synchronous read operation
bResult = ReadFile(hFile, &inBuffer, nBytesToRead, &nBytesRead, NULL);
// check for eof
if (bResult &&  nBytesRead == 0, ) {
    // we're at the end of the file
}

The test for end-of-file during an asynchronous read operation is more difficult. There are three end-of-file indicators for asynchronous read operations:

•	ReadFile returns FALSE and GetLastError returns ERROR_HANDLE_EOF.

•	ReadFile returns FALSE and GetLastError returns ERROR_IO_PENDING.

•	GetOverLappedResult returns FALSE and GetLastError returns ERROR_HANDLE_EOF.

The following example shows how to test for an end-of-file during an asynchronous read operation:

// attempt to initiate an asynchronous read operation
bResult = ReadFile(hFile, &inBuffer, nBytesToRead, &nBytesRead, NULL);
// if there was a problem ...
if (!bResult) {
    switch (dwError = GetLastError()) {
    case ERROR_HANDLE_EOF: {
    // we're at the end of the file
    }
    case ERROR_IO_PENDING: {
    // we're at the end of the file
    }
    // other error cases
    }
}
    .
    .
    .
// check on an asynchronous read operation
bResult = GetOverlappedResult(hFile, &gOverlapped, &nBytesRead,
    &gOverlapped) ;
// if there was a problem ...
if (!bResult) {
    switch (dwError = GetLastError()) {
    case ERROR_HANDLE_EOF: {
    // we're at the end of the file
    }
    // other error cases
    }
}


 Retrieving a File Pointer

The following example retrieves the current position of the file pointer in the file specified by the hFile value.

HANDLE hFile;

DWORD dwCurrentFilePosition;

dwCurrentFilePosition = SetFilePointer(

    hFile, /* must have GENERIC_READ and/or GENERIC_WRITE    */

    0,     /* do not move pointer                            */

    NULL,  /* hFile is not large enough to need this pointer */

    FILE_CURRENT);  /* provides offset from current position */


 File Functions

Following are the functions used with files.

_hread
_hwrite
_lclose
_lcreat
_llseek
_lopen
_lread
_lwrite
AreFileApisANSI
CopyFile
CreateDirectory
CreateDirectoryEx
CreateFile
CreateIoCompletionPort
DefineDosDevice
DeleteFile
FileIOCompletionRoutine
FindClose
FindCloseChangeNotification
FindFirstChangeNotification
FindFirstFile
FindNextChangeNotification
FindNextFile
FlushFileBuffers
GetBinaryType
GetCurrentDirectory
GetDiskFreeSpace
GetDriveType
GetFileAttributes
GetFileInformationByHandle
GetFileSize
GetFileType
GetFullPathName
GetLogicalDrives
GetLogicalDriveStrings
GetQueuedCompletionStatus
GetShortPathName
GetTempDrive
GetTempFileName
GetTempPath
GetVolumeInformation
LockFile
LockFileEx
MoveFile
MoveFileEx
OpenFile
QueryDosDevice
ReadFile
ReadFileEx
RemoveDirectory
SearchPath
SetCurrentDirectory
SetEndOfFile
SetFileApisToANSI
SetFileApisToOEM
SetFileAttributes
SetFilePointer
SetHandleCount
SetVolumeLabel
UnlockFile
UnlockFileEx
WriteFile
WriteFileEx


 Handles and Objects

An object is an internal structure that represents a system resource, such as a file, a thread, or a graphic image. An application cannot directly access the internal structure of an object or the system resource that an object represents. Instead, an application must obtain an object handle and use this handle to examine or modify the system resource (or both). In the Microsoft® Win32® application programming interface (API), handles are usually implemented as indirect pointers, but this is not always the case.


 About Handles and Objects

Windows uses objects and handles to regulate access to system resources for two main reasons. First, the use of objects ensures that developers are not writing code specifically to low-level, internal structures. This enables Microsoft to add or change functionality of the operating system, as long as the original calling conventions are maintained. When subsequent versions of the operating system are released, applications will gain this new functionality with little or no additional development.

Second, the use of objects enables developers to take advantage of Win32 security. Each object has its own access-control list (ACL) that specifies the types of actions processes can perform on the object. The operating system examines an object's ACL each time an application attempts to create a handle to the object. For more information about security, see Security.

For most objects, the Win32 API provides functions that create the object, create an object handle, close the object handle, and destroy the object. These tasks may be combined or unnecessary, depending on the type of object and the situation. For example, an application could create an event object. Other applications could open the event and each would have a unique handle to the same event object. In this scenario, as the applications finish using the object, each closes its handle. When there are no open handles to the event object, the operating system removes the object from memory.

In contrast, an application could obtain the existing window-object handle. In this instance, when the window object is no longer needed, the application must remove the object from memory, which invalidates the window handle.

When a process terminates, the system automatically closes handles and deletes objects created by the process. However, when a thread terminates, the system usually does not close handles or delete objects. The only exceptions are window, hook, window position, and dynamic data exchange (DDE) conversation objects that are deleted when the creating thread terminates.

Handles and objects consume memory. Therefore, to preserve system performance, an application should close handles and delete objects as soon as they are no longer needed. Applications that do not do this can slow the operating system, due to excessive use of the paging file.

Windows provides three categories of objects: user, graphics device interface (GDI), and kernel, as shown in the following tables. The system uses user objects to support window management, GDI objects to support graphics, and kernel objects to support memory management, process execution, and interprocess communications (IPC). For information about creating and using a specific object, refer to the associated overview.

Windows User Objects

User object	Overview
Accelerator table	Keyboard Accelerators
Caret	Carets
Cursor	Cursors
Dynamic data exchange conversation	Dynamic Data Exchange Management Library
Desktop	Security
Hook	Hooks
Icon	Icons
Menu	Menus (Windows NT)
Window	Windows
Window position	Windows
Window station	Windows
Windows GDI Objects

GDI object	Overview
Bitmap	Bitmaps
Brush	Brushes
Font	Fonts and Text
Palette	Colors
Pen	Pens
Extended pen	Pens
Region	Regions
Device context	Device Contexts
Memory device context	Device Contexts
Metafile	Metafiles
Metafile device context	Metafiles
Enhanced metafile	Metafiles
Enhanced-metafile device context	Metafiles
Windows Kernel Objects

Kernel object	Overview
Process	Processes and Threads
Thread	Processes and Threads
File	Files
File mapping	File Mapping
Event	Synchronization
Semaphore	Synchronization
Mutex	Synchronization
Pipe (named and anonymous)	Pipes
Mailslot	Mailslots
Communications device	Communications
Heap	Memory Management
Module	Dynamic-Link Libraries
Update resource	Resources
Find file	Files
Event log	Event Logging
Change notification	Files
Token	Security
Service object	Printing and Print Spooler
LZ file	Data Decompression Library


 Handle Limitations

Some objects, such as user and GDI objects, support only one handle at a time. The system provides the handle when an application creates the object and invalidates the handle when the application destroys the object. Other objects, such as some kernel objects, support multiple handles to a single object. The operating system automatically removes the object from memory after the last handle to the object is closed.

The total number of open handles in the operating system is limited only by the amount of memory available to the operating system. However, a single process may have no more than 16,384 open GDI object handles. The per-process limit on kernel handles is 2^30. There is no per-process limit on user handles, but there is a systemwide limit of 65,536.


 User and Graphics Device Interface Objects

User and GDI objects support only one handle per object. Processes cannot inherit or duplicate handles to user or GDI objects.

Handles to user objects are public to all processes. That is, any process can use the user object handle, provided that the process has access to the object as defined by user security. For more information about security, see Security.

Handles to GDI objects are private to a process. That is, only the process that created the GDI object can use the object handle.

In the following illustration, an application creates a window object. The CreateWindow function creates the window object and returns an object handle.

After the window object has been created, the application can use the window handle to display or change the window. The handle remains valid until the window object is destroyed.

In the next illustration, the application destroys the window object. The DestroyWindow function removes the window object from memory, which invalidates the window handle.

The following table lists the Windows user objects and each object's creator and destructor functions. The creator functions either create the object and an object handle or simply return the existing object handle. The destructor functions remove the object from memory, which invalidates the object handle.

Note that the window station and desktop objects are created and maintained by the system; applications cannot delete these objects.

User Objects

Object	Creator function	Destructor function
Accelerator table	CreateAcceleratorTable	DestroyAcceleratorTable
Cursor	CreateCursor, LoadCursor, GetCursor, SetCursor	DestroyCursor
DDE conversation	DdeConnect, DdeConnectList, DdeQueryNextServer, DdeReconnect	DdeDisconnect, DdeDisconnectList
Desktop	GetThreadDesktop	−
Hook	SetWindowsHook, SetWindowsHookEx	UnhookWindowsHook, UnhookWindowsHookEx
Menu	CreateMenu, CreatePopupMenu, GetMenu, GetSubMenu, GetSystemMenu, LoadMenu, LoadMenuIndirect	DestroyMenu
Window	CreateWindow, CreateWindowEx, CreateDialogParam, CreateDialogIndirectParam, CreateMDIWindow, FindWindow, GetWindow, GetClipboardOwner, GetDesktopWindow, GetDlgItem, GetForegroundWindow, GetLastActivePopup, GetOpenClipboardWindow, GetTopWindow, WindowFromDC, WindowFromPoint, and others	DestroyWindow
Window position	BeginDeferWindowPos	EndDeferWindowPos
Window station	GetProcessWindowStation	−
The following table lists the Windows GDI objects and each object's creator and destructor functions. The creator functions either create the object and an object handle or simply return the existing object handle. The destructor functions remove the object from memory, which invalidates the object handle.

GDI Objects

Object	Creator function	Destructor function
Bitmap	CreateBitmap, CreateBitmapIndirect, CreateCompatibleBitmap, CreateDIBitmap, CreateDIBSection, CreateDiscardableBitmap	DeleteObject
Brush	CreateBrushIndirect, CreateDIBPatternBrush, CreateDIBPatternBrushPt, CreateHatchBrush, CreatePatternBrush, CreateSolidBrush	DeleteObject
Font	CreateFont, CreateFontIndirect	DeleteObject
Palette	CreatePalette	DeleteObject
Pen	CreatePen, CreatePenIndirect	DeleteObject
Extended pen	ExtCreatePen	DeleteObject
Region	CombineRgn, CreateEllipticRgn, CreateEllipticRgnIndirect, CreatePolygonRgn, CreatePolyPolygonRgn, CreateRectRgn, CreateRectRgnIndirect, CreateRoundRectRgn, ExtCreateRegion, PathToRegion	DeleteObject
Device context (DC)	CreateDC, GetDC	DeleteDC, ReleaseDC
Memory DC	CreateCompatibleDC	DeleteDC
Metafile	CloseMetaFile, CopyMetaFile, GetMetaFile, SetMetaFileBitsEx	DeleteMetaFile
Metafile DC	CreateMetafile	CloseMetaFile
Enhanced metafile	CloseEnhMetaFile, CopyEnhMetaFile, GetEnhMetaFile, SetEnhMetaFileBits	DeleteEnhMetaFile
Enhanced-metafile DC	CreateEnhMetaFile	CloseEnhMetaFile


 Kernel Objects

Kernel object handles are process specific. That is, a process must either create a kernel object or open an existing object to obtain an object handle. Any process can create a new handle to an existing kernel object (even one created by another process), provided that the process knows the name of the object and has access to the object as defined by user security. For more information about security, see Security.

Processes can inherit or duplicate handles to the following types of kernel objects:

•	Processes

•	Threads

•	Files (including file-mapping objects)

•	Events

•	Semaphores

•	Mutexes

•	Pipes (named and anonymous)

•	Mailslots

•	Communications devices

All other kernel objects are private to the process that created them; object handles cannot be duplicated or inherited.

A child process inherits an open handle from its parent process if inheritance was specified when the original handle was created and if the child process was created with the "inherit handles" flag set. An inherited handle is valid only in the context of the child process.

The DuplicateHandle function duplicates a handle into the current process or into another process. If an application duplicates one of its handles into another process, the duplicated handle is valid only in the context of the other process.

A duplicated or inherited handle is a unique value, but it refers to the same object as the original handle.

Kernel object handles include access rights that indicate the actions the application wants to perform on the object. An application specifies access rights when it creates an object or obtains an existing object handle. Each type of kernel object supports its own set of access rights. For example, event handles can have "set" or "wait" access (or both), file handles can have "read" or "write" access (or both), and so on. For more information about access rights, see Security, and topics that describe individual objects.

In the following illustration, an application creates an event object. The CreateEvent function creates the event object and returns an object handle.

After the event object has been created, the application can use the event handle to set or wait on the event. The handle remains valid until the application closes the handle or terminates.

Most kernel objects support multiple handles to a single object. For example, the application in the preceding illustration could obtain additional event object handles by using the OpenEvent function, as shown in the following illustration.

This method enables an application to have handles with different access rights. For example, Handle 1 might have "set" and "wait" access to the event, and Handle 2 might have only "wait" access.

If another process knows the event name and has security access to the object, it can create its own event object handle by using OpenEvent, as shown in the following illustration.

The original application could also duplicate one of its handles into the same process or into another process by using the DuplicateHandle function, as shown in the following illustration.

The following illustration shows how a child process inherits a handle created by its parent process.

A child process of an application automatically inherits handles created by its parent process if inheritance was specified when the handles were created and if the child process was created with the "inherit handles" flag set. Note that in the preceding illustration, Handle 2 is not equivalent to Handle 1 but does refer to the same event object.

For more information about inheritance, see Processes and Threads and Files

An object remains in memory as long as at least one object handle exists. In the following illustration, the applications use the CloseHandle function to close their event object handles. When there are no event handles, the system removes the object from memory, as shown in the following illustration.

Occasionally, an object remains in memory after all object handles have been closed. For example, a thread could create an event object and wait on the event handle. While the thread is waiting, another thread could close the same event object handle. The event object remains in memory, without any event object handles, until the event object is set to the signaled state and the wait operation is completed. At this time, the system removes the object from memory.

Windows manages file objects somewhat differently from other kernel objects. File objects contain the file pointer — the pointer to the next byte to be read or written in a file. Whenever an application creates a new file handle, the system creates a new file object. Therefore, more than one file object can refer to a single file on disk, as shown in the next illustration.

Only through duplication or inheritance can more than one file handle refer to the same file object, as shown in the following illustration.

The following table lists each of the Windows kernel objects and each object's creator and destructor functions. The creator functions either create the object and an object handle or create a new existing object handle. The destructor functions close the object handle. When an application closes the last handle to a kernel object, the system removes the object from memory.

Kernel Objects

Object	Creator function	Destructor function
Process	CreateProcess, OpenProcess, GetCurrentProcess	CloseHandle, TerminateProcess
Thread	CreateThread, CreateRemoteThread, GetCurrentThread	CloseHandle, TerminateThread
File	CreateFile	CloseHandle, DeleteFile
File mapping	CreateFileMapping, OpenFileMapping	CloseHandle
Event	CreateEvent, OpenEvent	CloseHandle
Semaphore	CreateSemaphore, OpenSemaphore	CloseHandle
Mutex	CreateMutex, OpenMutex	CloseHandle
Pipe	CreatePipe	CloseHandle
Named pipe	CreateNamedPipe	CloseHandle, DisconnectNamedPipe
Mailslot	CreateMailslot	CloseHandle
Communications device	GetStdHandle	CloseHandle
Heap	HeapCreate	HeapDestroy
Module	LoadLibrary, GetModuleHandle	FreeLibrary
Update resource	BeginUpdateResource	EndUpdateResource
Find file	FindFirstFile	FindClose
Event log	OpenEventLog, RegisterEventSource, OpenBackupEventLog	CloseEventLog
Change notification	FindFirstChangeNotification	FindCloseChangeNotification


 Handles and Objects Functions

CloseHandle
DuplicateHandle
GetHandleInformation
SetHandleInformation


,


 Help

Online help can come in a variety of forms, from detailed conceptual information to quick definitions. This overview discusses elements of the Win32 application programming interface (API) that support online help.


 About Help

An important element of a user-friendly application is readily available online help. Microsoft® Windows® provides functions and messages that when used in conjunction with the Windows Help application make it easy to implement online help in your application. This overview discusses elements of the Win32 application programming interface (API) that support online help. It describes how to use these elements to give users a means to request help and explains how to use the Windows Help application to display help.


 Help Requests

Most Windows-based applications provide online help information in a variety of forms, ranging from conceptual help that explains the purpose of an application's features to pop-up help that provides quick definitions of individual elements in the application's user interface. You use Win32 functions and messages to give users a variety of ways to request access to this information. The following sections describe these help requests.


 Help Menu

Most applications provide user access to help information by including a Help menu in the main window. When the user selects an item from a Help menu, the corresponding window procedure receives a WM_COMMAND message that identifies the selected item. The application responds by displaying the appropriate help information, such as a list of help topics, an index, or an introduction to the application.


 Help from the Keyboard

Windows provides user access to help information from the keyboard by notifying the application whenever the user presses the F1 key. The system sends WM_HELP to the window that has the keyboard focus when the user presses the F1 key. If the window is child window (for example, a control in a dialog box), the DefWindowProc function passes the message to the parent window. If a menu is active when F1 is pressed, the system sends the message to the window associated with the menu. The application responds by displaying help information associated with the window, control, or menu that has the focus or is active. For example, if the user selects a control in a dialog box and presses F1, the application displays help information for that control.

The lParam parameter of WM_HELP is a pointer to a HELPINFO structure that contains detailed information about the item for which help is requested. You use this information to determine the help topic to display. The HELPINFO structure also includes the coordinates of the mouse cursor at the time the user pressed the F1 key. You can use this information to provide help based on the location of the mouse cursor.


 Help from the Mouse

Windows provides user access to help information from the mouse by notifying the application whenever the user clicks the right mouse button or clicks a window, control, or menu after clicking the Question (?) button. The application responds by displaying help information associated with the given window, control, or menu.

The system sends a WM_CONTEXTMENU message when the user clicks the right mouse button. The window that was clicked receives the message. If the window is a child window, such as a control, the DefWindowProc function passes the message to the parent window. The WM_CONTEXTMENU message specifies the coordinates of the mouse cursor. The x-coordinate is in the low-order word of the lParam parameter, and the y-coordinate is in the high-order word. If the user clicked a control, the wParam parameter is the handle of the control that received the button click.

The system sends a WM_HELP message when the user clicks an item in a window after clicking the Question (?) button that appears in the title bar of the window. You can add a Question button to a title bar by specifying the WS_EX_CONTEXTHELP style in the CreateWindowEx function when creating the window. The lParam parameter of WM_HELP is a pointer to a HELPINFO structure that contains detailed information about the item for which help is requested, including the coordinates of the mouse cursor at the time the user clicked the mouse button.

The Question button is recommended for use in dialog boxes only. In the past, applications have provided user access to help information about a dialog box by providing a Help button in the dialog box. This method is no longer recommended. Use the Question button instead.


 Help Display and Windows Help

Once an application receives a request for help, it should display the appropriate help information. Because the Windows Help application supports a variety of ways to display help and a user interface that is consistent with that used by Windows to display its own help information, it is recommended that applications use Windows Help rather than other ways to display help. To direct Windows Help to display help information, an application uses the WinHelp function, specifying details such as the information to display and the form of the window in which to display it. The following sections explain how to use WinHelp to display help information.


 Help Files

To view help information, you must specify a help file when calling the WinHelp function. The help file must have the Windows Help (.HLP) file format and have one or more topics. Each topic is a distinct unit of information, such as a conceptual description, a set of instructions, a picture, a glossary definition, and so on. Topics must be uniquely identified so that Windows Help can locate the topic whenever it is requested. Internally, Windows Help uses topic identifiers to locate topics, but applications most often use context identifiers (unique integer values) to specify topics to display. The help file author must explicitly map context identifiers to topic identifiers in the [MAP] section of the project file used to build the help file.

When you specify a help file but you do not specify a path, WinHelp looks for the help file in the Help directory or in a directory specified by the PATH environment variable. In addition, WinHelp can find a help file whose name is listed in the following registry location:

HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\Help

To take advantage of the registry, you must create a value name that has the same name as your help file. The value assigned to that name must be the directory where the help file resides.

If WinHelp cannot find the given help file, it displays a dialog box that allows the user to specify the location of the help file. Because WinHelp saves the location information in the registry, WinHelp does not ask again for the location of the same help file.

For more information about how to author and build a help file, see the documentation provided with your development tools.


 Starting Windows Help

The following example uses the WinHelp function to start the Windows Help application and open the Windows NT Help file to its Contents topic.

HWND hwnd;     // main window handle

BOOL bResult   // for checking boolean function result

bResult = WinHelp(hWnd, "WINNT.HLP", HELP_CONTENTS, 0L);

This next example opens the Windows NT user Help file, searches the file for the topic associated with a keyword string, and then displays the topic.

HWND hwnd;     // main window handle

BOOL bResult   // for checking boolean function result

bResult = WinHelp(hWnd, "WINNT.HLP", HELP_KEY,

                  (DWORD) "finding topics");


 Help Topics Dialog Box

You can display the Help Topics dialog box by calling the WinHelp function with the HELP_FINDER command. The Help Topics dialog box lets the user select topics to display by viewing the titles of the topics, the keywords associated with the topics, or the words and phrases found in the topics. Applications typically display the Help Topics dialog box when the user chooses a command, such as Help Topics, from the Help menu. An application may also display this dialog box if the user presses the F1 key when no specific window, control, or menu in the application has the focus or is active.

In the past, applications have used the HELP_CONTENTS and HELP_INDEX commands with the WinHelp function to display the Contents topic and the keyword index of the help file. These commands are no longer recommended. Use the HELP_FINDER command instead.


 Information Topics

You can display a specific topic by calling the WinHelp function with the HELP_CONTEXT command and specifying the context identifier for the topic. Applications typically use the HELP_CONTEXT command in response to user requests for topics containing conceptual information or procedural help rather than information about a specific control or menu. In such cases, the user may continue to browse the help file looking for related information before returning to the application.

The HELP_CONTEXT command invokes a regular instance of Windows Help, enabling the user to access other topics in the help file. It typically displays the main help window, which includes a title bar, system menu, minimize and maximize buttons, main menu, optional navigation bar, sizing border, and a client area. The text of the selected topic appears in the client area, and the user can navigate through the help file by using hot links or navigation buttons in the main window. The regular instance of Windows Help can also be used to display help in one or more secondary windows instead of the main window.


 Pop-up Topics

You can display a pop-up topic that contains information for a specific control or menu by calling the WinHelp function with the HELP_WM_HELP or HELP_CONTEXTMENU command. These commands display a topic in a pop-up window near the corresponding control or menu. To let the user return immediately to work in the application, the pop-up window is destroyed as soon as the user presses a key or clicks the left mouse button.

You use the HELP_WM_HELP command when processing WM_HELP messages for control windows. Because most controls pass the WM_HELP message to the DefWindowProc function, the corresponding dialog box procedure (or parent window procedure) processes this message. Rather than give a specific context identifier, the dialog box procedure must pass an array of control and context identifier pairs to WinHelp along with the control handle specified in the hItemHandle member of HELPINFO structure passed with the WM_HELP message. The function determines the identifier of the control for which the WM_HELP message was generated and uses the matching context identifier to display the appropriate topic.

You use the HELP_CONTEXTMENU command when processing WM_CONTEXTMENU messages. Because most controls pass the WM_CONTEXTMENU message to the DefWindowProc function, the corresponding dialog box procedure (or parent window procedure) processes this message. Again, the procedure specify an array of control and context identifier pairs and the handle in wParam when calling WinHelp so that the function can pick the appropriate context identifier from the array and display the appropriate topic. Unlike the HELP_WM_HELP command, HELP_CONTEXTMENU first displays a What's This? command in a menu. If the user chooses the command, WinHelp displays the topic. Otherwise, the request is canceled.

You can also display pop-up topics by using the HELP_CONTEXTPOPUP command and specifying a context identifier of the topic. This command is similar to the HELP_CONTEXT command but invokes the pop-up instance of Windows Help used by HELP_WM_HELP and HELP_CONTEXTMENU. Applications can use this command in response to WM_HELP messages to display help for menus and for windows that are not controls in a dialog box. To use this command most effectively, the application should assign context identifiers to these menus and windows.

You can assign a context identifier to any window or menu in the application. When the user's help requests generates a WM_HELP message, the system includes the context identifier in the HELPINFO structure that it passes to the parent window along with the WM_HELP message. The parent window can then pass the context identifier to WinHelp to display the requested help topic.

You use the SetWindowContextHelpId function to assign a context identifier to a window or control and the SetMenuContextHelpId function to assign a context identifier to a menu. You can retrieve the context identifier for a window or menu by using the GetWindowContextHelpId or GetMenuContextHelpId function.


 Keyword Searches

You can enable the user to find and view topics by assigning keywords to topics in the help file. A keyword is simply a string that is associated with one or more topics. Windows Help collects all keywords in a help file, places them in a table, and displays them in the Index list of the Help Topics dialog box. When the user selects a keyword, Windows Help displays the associated help topic or displays a list of topics from which the user can choose if there is more than one topic associated with the keyword.

In an application, you can use the HELP_KEY, HELP_PARTIALKEY, or HELP_MULTIKEY command with WinHelp to search for and display help topics based on whole or partial keywords. You specify the command, the keyword string, the help file, and the handle of the owner window. In all cases, if a single match is found, WinHelp displays the corresponding topic. If more than one match is found, the function displays the Topics Found dialog, letting the user choose which topic to view. If no match is found, WinHelp either displays the Index list (for HELP_KEY and HELP_PARTIALKEY) or displays an error message (for HELP_MULTIKEY).

You can search for multiple keywords in a single call to WinHelp by separating each keyword from the preceeding one with a semicolon (;). (Searching for multiple keywords is not supported for help files created for version 3.x.) You can also search for a keywords across multiple help files if the help file that you specify has a contents (.CNT) file that contains :Index or :Link commands. With the HELP_KEY command, WinHelp searches for keywords in all files specified by these commands. With the HELP_MULTIKEY and HELP_PARTIALKEY commands, the function searches all files except those specified by :Link commands.

By default, Windows Help recognizes only the keyword table identified by the K footnote character in the help source file. You can direct Windows Help to create additional keyword tables by specifying a footnote character other than K with the keyword definitions in the Windows Help file. (The footnote character A, however, is reserved.) You must define any additional keyword tables by using MULTIKEY statements in the [OPTIONS] section of the project file when building the help file.

An application can use the HELP_SETINDEX command with the WinHelp function to direct Windows Help to display a keyword table other than K in its Index list. To direct Windows Help to search for a keyword in an alternate keyword table, an application can use the HELP_MULTIKEY command. You specify the keyword and keyword table in a MULTIKEYHELP structure, which you pass to WinHelp.

When WinHelp displays a topic, it displays it in the window specified by the > footnote for the topic, or in the window specified by the :Base command in the contents file, or in the main window. If the main window is already open to a different help file when you call WinHelp, the function hides main window while searching. In this case, canceling both the Topics Found and Help Topics dialogs, close the main window.


 Secondary Help Windows

The main window of the Windows Help application is called the primary window. Windows Help can also display help topics in a secondary window. Unlike the main help window, a secondary window does not contain a menu bar. You can include a navigation bar in a secondary window, and you can add buttons to the bar. You can also choose to have Windows Help automatically adjust the height of secondary window to accommodate the topic.

You must define secondary windows in the [WINDOWS] section of your help project file, providing the name and, optionally, initial size and position of each window. You can direct the Windows Help application to display a topic in a secondary window by appending an angle bracket (>) and the name you have defined for the secondary window to the name of the help file and then passing the resulting string to the WinHelp function.

An application can change the size and position of a primary or secondary window by specifying the address of a HELPWININFO structure and the HELP_SETWINPOS command in a call to WinHelp. HELPWININFO specifies the name of the window and its new size and position. The primary help window is the "main" window.


 Training Card Help

Using training card help, an application can display a sequence of instructions to guide the user through the steps of a task. A training card typically consists of text that explains a particular step and authorable buttons associated with TCard macros that allow the user to tell the application what to do next. Training cards may only be displayed in secondary windows and must not contain hot links to other topics in the help file.

An application initiates the training card instance of Windows Help by calling the WinHelp function and specifying the HELP_TCARD command in combination with another command such as HELP_CONTEXT. Subsequently, when the user clicks an authorable button in the training card, clicks a hot spot assigned to the TCard macro, or closes the training card, Windows Help notifies the application by sending it a WM_TCARD message. The wParam parameter identifies the button or user action, and the lParam parameter contains additional data, the meaning of which depends on the value of wParam.


 Canceling Help

Windows Help requires an application to explicitly cancel Help so that it can free any resources it used to keep track of the application and its help files. The application can do this at any time by calling the WinHelp function and specifying the HELP_QUIT command. Note that this is not true for the pop-up instance of Windows Help. An application should not try to close the pop-up instance.

If an application has made any calls to WinHelp, it must cancel Help before it closes its main window (for example, in response to the WM_DESTROY message in the main window procedure). An application needs to call WinHelp only once to cancel Help, no matter how many help files it has opened. Windows Help remains running until all applications or dynamic-link libraries (DLLs) that have called WinHelp have canceled Help.

To close the training card instance of Windows Help, you must specify both the HELP_TCARD and HELP_QUIT commands when calling the WinHelp function. An application does not need to cancel the training card instance of Windows Help if the user cancels it first. Windows Help notifies an application when the user cancels the training card instance by sending the WM_TCARD message with the wParam parameter set to IDCLOSE.


 Using Help

This section shows how to provide context-sensitive help for a dialog box and how to set the appearance of a secondary help window.

•	Providing Help in a dialog box

•	Setting the appearance of a secondary help window


 Providing Help in a Dialog Box

To provide context-sensitive help in a dialog box, you must create an array consisting of pairs of doubleword values. The first value in each pair is the identifier of a control in the dialog box, and the second is the context identifier of the help topic for the control. The array should contain one pair of identifiers for each control in the dialog box.

The dialog box procedure must process the WM_HELP and WM_CONTEXTMENU messages. The dialog box procedure receives WM_HELP when the user presses the F1 key and WM_CONTEXTMENU when the user clicks the right mouse button.

The lParam parameter of WM_HELP is a pointer to a HELPINFO structure. The hItemHandle member of this structure identifies the control for which the user has requested help. You must pass the handle to the WinHelp function along with the HELP_WM_HELP command, the name of your help file, and a pointer to the array of identifiers. The WinHelp function searches the array for the control identifier of the specified control and then retrieves the corresponding help context identifier. Next, the function passes the help context identifier to Windows Help, which finds the corresponding topic and displays it in a pop-up window. If the control has an identifier of  − 1, the system searches for the next control that is a tab stop and uses its identifier to find the help context identifier. For this reason, it is important that you place static text before controls in a resource file.

Processing WM_CONTEXTMENU is similar to processing WM_HELP when calling the WinHelp function, with these two exceptions:

•	You pass the wParam parameter from WM_CONTEXTMENU, which is the handle of the control that sent the message.

•	You specify the HELP_CONTEXTMENU command instead of HELP_WM_HELP.

The HELP_CONTEXTMENU command causes Windows Help to display a menu before it displays the help topic. The menu is system defined. It allows the user to display help for the control or to display the Help Topics dialog box.

The following example shows how to implement context-sensitive help in a dialog box.

LRESULT CALLBACK EditDlgProc(HWND hwndDlg, UINT uMsg, WPARAM 	wParam,

    LPARAM lParam)

{

// Create an array of control identifiers and context identifiers.

static DWORD aIds[] = {

    ID_SAVE,   IDH_SAVE,

    ID_DELETE, IDH_DELETE,

    ID_COPY,   IDH_COPY,

    ID_PASTE,  IDH_PASTE,

    0,0

};

switch (uMsg) {

    case WM_HELP:

        WinHelp(((LPHELPINFO) lParam)->hItemHandle, "helpfile.hlp",

            HELP_WM_HELP, (DWORD) (LPSTR) aIds);

        break;

    case WM_CONTEXTMENU:

        WinHelp((HWND) wParam, "helpfile.hlp", HELP_CONTEXTMENU,

            (DWORD) (LPVOID) aIds);

        break;

    .

    . // process other messages here

    .

    }

return FALSE;

}


 Setting the Appearance of a Secondary Help Window

An application can set the size, position, and show state of a secondary help window by passing the HELP_SETWINPOS command and the address of a HELPWININFO structure to the WinHelp function. The members of HELPWININFO specify the name of the window to change and the window's new size, position, and show state.

The following example sets the appearance of a secondary window named "wnd_menu". The name must be defined in the [WINDOWS] section of the help project file.

BOOL DoWindowSize(VOID)

{

    HANDLE hhwi;

    LPHELPWININFO lphwi;

    WORD wSize;

    char *szWndName = "wnd_menu";

    wSize = sizeof(HELPWININFO) + lstrlen(szWndName);

    hhwi = GlobalAlloc(GHND, wSize);

    lphwi = (LPHELPWININFO) GlobalLock(hhwi);

    lphwi->wStructSize = wSize;

    lphwi->x    = 256;      // horizontal position

    lphwi->y    = 256;      // vertical position

    lphwi->dx   = 767;      // width

    lphwi->dy   = 512;      // height

    lphwi->wMax = SW_SHOW;  // show the window

    lstrcpy(lphwi->rgchMember, szWndName);  // secondary window

    WinHelp(hwnd, "myhelp.hlp", HELP_SETWINPOS, (DWORD) lphwi);

    GlobalUnlock(hhwi);

    GlobalFree(hhwi);

return;

}


 Help Reference

The following sections list the messages and functions associated with Help controls.


 Help Functions

The following functions are used with online Help.

GetMenuContextHelpId
GetWindowContextHelpId
SetMenuContextHelpId
SetWindowContextHelpId
WinHelp


 Help Messages

The following messages are used with online Help.

WM_HELP
WM_TCARD


 Image Color Matching

Image color matching provides accurate and consistent reproductions of color images on all output devices. This overview describes image color matching and explains how to use the related functions. For general information about colors and how to specify colors when drawing, see Colors.


 About Image Color Matching

Despite differences in imaging technologies and color capabilities between devices, image color matching ensures that a color image will look the same or as close as possible to the same when output to screen, paper, film, and other media. Applications typically use image color matching to let users create color images on the screen that can then be reproduced exactly on a printer or on other screens.


 Logical Colors, Gamuts, and Gamut Matching

By default, Windows disables image color matching to ensure that existing applications continue to draw color images as originally intended. You can enable image color matching for a device context by using the SetICMMode function. You must enable image color matching for each device context you intend to use for output.

Once you enable image color matching, you can create a color space and select it into the device contexts of the devices you wish to use. The color space defines the set of logical colors that you may use to draw. For each device, the system or the device driver transforms the logical colors to device (or physical) colors in a way that ensures consistency across devices.

To use a color from the color space, you specify a logical color value. The format of the value depends on the color space type. In some color spaces, this is similar to RGB (red, green, blue) color value described in previous Windows documentation, but the red, green, and blue components of logical color values are defined in terms of independent colormetric measure rather than arbitrary color units imposed by a device driver. In other cases, you may use color values that actually contain CMYK (cyan, magenta, yellow, black) values.

Not all devices support all colors. You can determine which colors are supported by a given device by checking its gamut, the set of colors it can produce. Different devices have different gamuts. For example, the screen can display cyans that no printer can produce; likewise, there are some reds on a page that never appear on a display.

An important element of image color matching is gamut matching, the process of finding color matches in the gamuts of different devices. This can range from the simple (such as truncating to the surface of the printer gamut), to the sophisticated (such as moving all colors a bit to maintain contrasts). Matching is not simply the process of ensuring that each pixel is faithfully reproduced with a given color. Instead, image color matching works within the capabilities of the given output device to produce an image in which the colors have the same relation to one another as they do when produced on other devices.

You can determine whether given colors are within the gamut of a device by using the CheckColorsInGamut function. This is useful for determining whether the screen has a larger gamut than the current printer. In such cases, you can notify the user of which screen colors won't print. You can preview the colors of a print job on the screen by using the ColorMatchToTarget function. The function first uses the current color space and gamut-matching method of a given device context, such as for a printer, to convert the colors in an image. It then converts the converted image to display on the preview device.

Image color matching applies to any drawing operation in which colors are given as color values. It affects colors that you specify directly, such as when setting the color of individual pixels using the SetPixel function, or indirectly, when you set the colors in pens, brushes, fonts and other graphics objects. Image color matching does not apply to device-dependent bitmaps, such as those created by the CreateBitmap and CreateCompatibleBitmap functions.


 Color Spaces

Image color matching uses color spaces to define the set of colors available for a device. To each device context, the system assigns a default color space whose attributes, such as color space type, gamut-matching method and color endpoints, fully define how the system transforms color values for the device. You can create your own color spaces and replace the default color space for a device context by using the CreateColorSpace and SetColorSpace functions. These functions let you explicitly set the format of the color values you use in your application and how the device interprets those values and generates colors.

To create a color space, you set the members of a LOGCOLORSPACE structure and pass the structure to the CreateColorSpace function. You can either set the members to the values you want or specify the filename of a color profile that contains the characterization of the device. For more information, see Color Profiles.

Every color space must have a color space type and a gamut matching method. Gamut matching specifies whether colors in a given image are transformed into an exact match or are modified to make best use of the gamut of the given device, and is described in Gamut Matching Method.

The color space types can be device RGB (red, green, blue), device CMYK (cyan, magenta, yellow, black), or calibrated RGB. Device RGB, the default color space for device contexts, consists of the arbitrary set of colors for the specified output device. Logical color values in this space are given as three 8-bit color values (in a 32-bit value) and are sent to the device driver without transformation. Device CMYK is similar to device RGB except that logical color values are given as four 8-bit values. You use this color space for devices, typically printers, that use CMYK color values. For example, you might use it to carry out color separation and pass color values directly to a CMYK printer.

Calibrated RGB consists of colors in the set defined by three color endpoints. The color endpoints are given as three 32-bit values and are interpreted as defined by the 1931 CIE (Commission Internationale de L'Eclairage) XYZ standard.

After you have created a color space, you can select it into a device context by using the SetColorSpace function. You can delete a color space if you no longer need it by using the DeleteColorSpace function.

You can retrieve the color space for a specified device context by using the GetColorSpace function. This is useful if you want to get the logical definition or color profile file associated with the color space. You can use the GetLogColorSpace function to copy this information to a LOGCOLORSPACE structure.


 Gamut Matching Method

The gamut matching method determines how colors on a given device are "matched" with colors on another device. The type of matching needed depends on the image. There are some images for which users rarely want image color matching. For example, users like saturated, undithered colors in bar charts and highlights used in presentations — the device colors are far superior to dithered patterns of primary colors.

Gamut-matching methods include the following:

•	Business graphics

Preserves saturation (prevents dithering) if the requested color is not available. Useful for business charts and many computer-generated presentations.

•	Colormetric

Produces exact colormetric matches. Dithers primary colors if necessary. Colormetric matching is important when named colors are wanted.

•	Photographic

Produces the best perceptual match between devices. Takes advantage of the entire gamut of the device to maximize the number of distinct colors presented. This is best for photographic images.

You set the gamut-matching method for a device context by setting the lcsIntent member in the LOGCOLORSPACE structure when creating the color space. The matching choices for the display and printer are global settings; they apply to all applications at all times.

In some cases, a user may want to use different matching methods in the same document. For example, the user may want to use the colormetric method to draw the company logo but the business graphics method for bar charts. You can mix gamut-matching methods on the same page of output by creating appropriate color spaces and using SetColorSpace to switch between the spaces as needed.


 Color Profiles

A color profile is a file that contains information that defines the color capabilities of a device. A color profile for a display monitor, for example, defines the chromaticities of the phosphors for that monitor; one for a printer defines the chromaticities of the inks on a given type of paper. The system uses this information when mapping logical colors to the physical colors available on the device.

Color profiles exist for display monitors, printers, and scanners. By default, the system uses the color profile that best matches a given device, based on information in the profile and provided by the device driver. If a color profile is not present for a given device, the system uses a default profile for that device.

In some cases, it may be important to let the user choose the color profile to use for a given device. This can occur when the device configuration has changed in a way that the system cannot detect. You can enumerate all color profiles for a device by using the EnumICMProfiles function. This identifies each color profile by passing its filename to an EnumICMProfilesProc callback function that you supply. You can set the color profile for the device by using the SetICMProfile function. You can determine the current color profile for the device by using the GetICMProfile function.

A color profile is available only if it is listed in the registry. You can install or remove color profiles in the registry by using the UpdateICMRegKey function. You can also use this function to query for printer profiles that match specified device settings, or to associate a color profile with a given color-matching DLL and output device.


 Device-Independent Bitmaps and Enhanced Metafiles

To provide for image color matching, color characterization is included in device-independent bitmaps (DIBs) and enhanced metafiles. In DIBs, the color characterization is placed in the DIB header. In enhanced metafiles, the characterization is in metafile records. Color characterization is not available for compatible bitmaps and standard (16-bit) metafiles.

You set the color characterization for a DIB by setting the appropriate members in the BITMAPV4HEADER structure for the DIB. This structure is identical to the BITMAPINFOHEADER structure except that it includes members that define the color space type, color endpoints, and other related values. Some operating systems support the device CMYK color space type in DIBs but only for 32-bit DIBs. In such cases, the output device must also accept this format. If a DIB does not contain color characterization information, the system uses a default characterization.

You set color characterization for an enhanced metafile by using the CreateColorSpace and SetColorSpace functions when recording the metafile. The system records information about the color spaces and carries out color matching with the intended output device when the metafile is played. The system also records the SetICMMode and DeleteColorSpace functions, but no other image color matching functions can be used with enhanced metafiles. If you specify a color profile in the LOGCOLORSPACE structure when recording an enhanced metafile, the system records the filename of the color profile but not the content of the profile. This is similar to the way fonts are handled in enhanced metafiles.


 Gamma Correction

Some display adapters support downloadable gamma correction tables. These tables let you control the colors generated by the digital-to-analog converter (DAC) by mapping specific RGB values to DAC values. You can set the gamma ramp for any 24-bit display adapters that provide hardware gamma correction by using the SetDeviceGammaRamp function. The hardware gamma ramp is a global property that affects all running applications and is not changed on a per-device context basis. You can retrieve the current gamma ramp by using the GetDeviceGammaRamp function.


 Image Color Matching Reference

This section provides a listing of the image color matching functions and structures.


 Image Color Matching Functions

This following are the image color matching functions.

CheckColorsInGamut
ColorMatchToTarget
CreateColorSpace
DeleteColorSpace
EnumICMProfiles
EnumICMProfilesProc
GetColorSpace
GetDeviceGammaRamp
GetICMProfile
GetLogColorSpace
SetColorSpace
SetDeviceGammaRamp
SetICMMode
SetICMProfile
UpdateICMRegKey


 Image Color Matching Macros

This following are the image color matching macros.

CMYK
GetCValue
GetKValue
GetMValue
GetYValue


 Image Color Matching Structures

The following structures are used with the image color matching functions.

BITMAPV4HEADER
CIEXYZ
CIEXYZTRIPLE
LOGCOLORSPACE


 Interprocess Communications

The Microsoft® Win32® application programming interface (API) provides a rich set of mechanisms for facilitating communications and data sharing between applications. Collectively, the activities enabled by these mechanisms are called interprocess communications (IPC). In addition to facilitating the division of labor among several specialized processes, some forms of IPC can distribute the computational load among cooperating computers on a network.


 About Interprocess Communications

As computer users become more sophisticated, they demand more power from the applications they use. To meet this demand, developers add more features to their applications, and the applications become larger. These large applications can eventually become unmanageable, both from a development standpoint and from a user-interface point of view. Therefore, developers now tend to produce highly focused applications that do a good job on a limited number of features and then to enable those applications to communicate and share data with other specialized applications. No longer can any one application meet all user expectations; the age of cooperating and communicating applications has arrived.

Typically, cooperating and communicating applications can be categorized as clients or servers. A client is an application or a process that requests a service from some other process. A server is an application or a process that responds to a client request. Many applications act as both a client and a server, depending on the situation. For example, a word processing application might act as a client in requesting a summary table of manufacturing costs from a spreadsheet application acting as a server. The spreadsheet application, in turn, might act as a client in requesting the latest inventory levels from an automated inventory control application.


 Development Considerations

If a developer decides that an application would benefit from IPC, the developer must consider some of the following questions before deciding which of the available IPC methods to use.

•	Should the application be able to communicate with other applications running on other computers on a network, or is it sufficient for the application to communicate only with applications on the local computer? In other words, does the application need to be networkable? Some IPC methods work either on the local computer or over a network; others work only on the local computer.

•	Should the application be able to communicate with applications running on other computers that may be running under different operating systems (that is, MS-DOS®, Microsoft® Windows® Version 3.x, UNIX®)? In other words, must the application be interoperable?

•	Should the user of the application have to choose the other application(s) with which the application communicates, or can the application implicitly find its cooperating partners?

•	Should the application communicate with many different applications in a general way, such as allowing cut and paste operations with any other application, or should its communications requirements be limited to a restricted set of interactions with specific other applications? Applications that communicate in a general way are called loosely coupled; applications that have a more strictly defined interaction are called tightly coupled.

•	Is performance a critical aspect of the application? All IPC mechanisms include some amount of communications overhead.

•	Should the application be a Windows-based application, or will character-mode functionalities be sufficient? Some IPC mechanisms discussed in this topic do not work in character-mode−only applications. The clipboard, dynamic data exchange (DDE), and object linking and embedding (OLE) all require that the application have at least one window.

The answers to these questions determine whether an application can benefit by using one or more of the IPC mechanisms available in the Win32 API. This topic discusses the strengths and weaknesses of each of the Win32 IPC mechanisms.


 File Mapping and IPC

File mapping enables a process to treat the content of a file as if it were a block of memory in the process's address space. Therefore, instead of using file input and output (I/O) operations, the process can use simple pointer operations to examine and modify the contents of the file.

The Win32 API enables two or more processes to access the same file-mapping object. Each process receives a pointer to memory in its own address space. With this pointer, the process can read or modify the contents of the file.

There are three ways an application can share a file-mapping object created in one process with another process:

•	Inheritance. The first process creates the file-mapping object and then allows the handle of the object to be inherited by a child process.

•	Named file mapping. The first process creates the file-mapping object with a well-known name (which can be different from the filename). The second process opens the file-mapping object by specifying the well-known name. Alternatively, the first process can create a file-mapping object with a unique name and communicate that name to the second process through some other IPC mechanism (named pipe, mailslot, and so on).

•	Handle duplication. The first process creates the file-mapping object and then passes the handle of the object to the second process. The second process then duplicates the handle to gain access to the shared memory. The original process can communicate the file-mapping handle to the second process through one of the other IPC mechanisms described in this topic (named pipe, mailslot, and so on). For more information about duplicating handles, see Synchronization.

When two or more processes have read-write access to a shared memory block, they must use some sort of synchronization object, such as a semaphore, to prevent data corruption in a multitasking environment.

File mapping is quite efficient and also provides operating-system−supported security attributes that can help prevent unauthorized data corruption. File mapping can be used only between processes on a local computer; it cannot be used over a network. An application can, however, create a file-mapping object to a file on a remotely mounted volume. For example, if a remote server is mounted as the F drive, an application can create a file-mapping object to a file on that volume. However, a process running on a remote server cannot share a file-mapping object with a process running on a local computer.

Key Point  File mapping is an efficient way for two or more processes on the same computer to share data, but the developer must provide synchronization between the processes. For more information, see File Mapping, and Synchronization.


 Shared Memory and IPC

The Win32 API uses a special case of file mapping to provide shared memory access between processes. If you specify the system swapping file when creating a file-mapping object, the file-mapping object is treated as a shared memory block. Other processes can access the same block of memory by opening the same file-mapping object, as described in File Mapping.

Because shared memory is implemented with file mapping, it supports security access attributes and can operate only between processes running on the same computer.

Key Point  Shared memory in the Win32 API is implemented by using file mapping. All characteristics of file mapping apply to shared memory. For more information, see File Mapping.


 Anonymous Pipes and IPC

An anonymous (or unnamed) pipe enables related processes to transfer information back and forth as if they were reading from and writing to a file. Typically, anonymous pipes are used for redirecting the standard input and output (I/O) of a child process so that it can exchange data with its parent process.

To use an anonymous pipe, the parent process typically creates the pipe and then allows its read and write handles to be inherited by a child process. The parent process writes data to the pipe; the child process can read the data from the other end of the pipe. Likewise, the child process can write data to the pipe and the parent process can read the data from its end of the pipe. A parent process can also create two or more child processes that inherit the read and write handles to an anonymous pipe. Those child processes can use that pipe to communicate between each other directly, without going through the parent process.

Anonymous pipes cannot be used over a network, nor can they be used between unrelated processes. For information about a pipe mechanism that can be used with unrelated processes and over a network, see Named Pipes.

Key Point  Anonymous pipes provide an efficient way to redirect standard I/O to child processes on the same computer. For more information, see Pipes.


 Named Pipes and IPC

Like anonymous pipes, named pipes are used to transfer data back and forth between processes. Unlike anonymous pipes, however, named pipes can operate between unrelated processes and across a network between computers. Typically, a server process creates a named pipe with a well-known name. Client processes that can get the name of the pipe can open the other end of the pipe, subject to access restrictions specified by the pipe's creator. After they are connected, the server and client can exchange data by performing read and write operations on the pipe. Alternatively, the pipe creator can create a pipe and let a child process inherit the handle to the pipe, or it can create a pipe with a unique name and communicate that name to the client through some other IPC mechanism (such as a mailslot maintained by the client).

Key Point  Named pipes provide a relatively simple programming interface that makes transferring data across a network no more difficult than transferring data between two processes on the same computer. For more information, see Pipes.


 IPC Mailslots

Mailslots provide a one-way interprocess communications capability. Any process can create a mailslot and become a mailslot server. Other processes, called mailslot clients, can gain access to the mailslot by its name and send messages to the mailslot server process. A process can be both a mailslot server and a mailslot client, so two-way IPC is possible with multiple mailslots.

Incoming messages are always appended to the mailslot. The mailslot saves the messages until the creating process has a chance to read them.

Mailslots are similar to named pipes, but with a somewhat simplified programming interface and the added ability to broadcast messages to all computers in a specified network domain. A mailslot client can send a message to a mailslot on its local computer, to a mailslot on another computer, or to all mailslots with the same name on all computers in a specified network domain. Messages broadcast to a domain can be no longer than 400 bytes; messages sent to a single mailslot are limited only by the maximum message size specified by the creator of the mailslot (which can be unlimited).

Key Point  Mailslots offer an easy way for applications to send and receive short messages. They also provide the ability to broadcast messages across all computers in a network domain. For more information, see Mailslots.


 Using the Clipboard for IPC

The clipboard provides a mechanism for the well-established cut-copy-paste model for simple data sharing between Win32-based applications. It enables an application to read or write data in many different standard and application-defined formats. It also works between applications on the same computer or on different computers on a network.

The clipboard acts as a central depository for data sharing among applications. When a user performs a cut or copy operation in an application, the application puts the selected data on the clipboard in one or more formats. Any other application can then retrieve the data from the clipboard, choosing from the available formats. The clipboard is a very loosely coupled exchange medium, wherein the two applications need only agree on the data format.

Key Point  All Win32-based applications should support the clipboard for those data formats that they understand. For example, a text editor or word processor should at least be able to produce and accept clipboard data in pure text format. For more information, see Clipboard.


 Dynamic Data Exchange and IPC

Dynamic data exchange (DDE) is a protocol for interprocess communications that enables applications to exchange data in a variety of formats. Applications can use DDE for one-time data exchanges or for ongoing exchanges in which the applications update one another as new data becomes available.

The data formats used by DDE are the same as those used for the Windows clipboard IPC mechanism. DDE can be thought of as an extension of the clipboard mechanism. The clipboard is almost always used for a one-time response to a user command, such as choosing the Paste command from a menu. DDE is also usually initiated by a user command, but it often continues to function without further user interaction.

Three types of data exchange are possible with DDE:

•	Cold link. The exchange is a one-time data transfer, like the clipboard.

•	Warm link. A server notifies the client when data changes, and the client must then request new data.

•	Hot link. A server sends data updates to the client when data changes.

DDE exchanges can occur between applications running on the same computer or on different computers on a network.

Key Point  Most major Windows-based applications support DDE. Like the clipboard, DDE support enables an application to exchange data in a variety of standard formats with other Windows-based applications that support DDE. A developer can also define custom DDE data formats for special-purpose IPC between applications with more tightly coupled communications requirements. For more information, see Dynamic Data Exchange and Dynamic Data Exchange Management Library.


 Object Linking and Embedding

Object linking and embedding (OLE) applications manage compound documents — that is, documents made up of data from a variety of different applications. OLE provides services that make it easy for applications to call on other applications for data editing. For example, an OLE-aware word processor could embed a graph from a spreadsheet. The user could start the spreadsheet automatically from within the word processor by choosing the embedded chart for editing. The OLE libraries would take care of starting the spreadsheet and presenting the graph for editing. When the user quit the spreadsheet, the graph would be updated in the original word processor document. Contrast this with a DDE link involving a spreadsheet graph in a word processor document. With DDE, the user would have to explicitly start the spreadsheet and open the graph document in order to make changes. With OLE, the spreadsheet appears to be an extension of the word processor.

Like an application using DDE, an OLE-aware application can communicate with a wide variety of other Windows-based applications. Because the OLE protocol includes all necessary context information, the application will be able to hold OLE conversations with all other OLE-aware applications — even those that have yet to be written.

Key Point  OLE supports compound documents and enables an application to include embedded or linked data that, when chosen, automatically starts another application for data editing. This enables the application to be extended by any other OLE-aware application.


 Dynamic-Link Libraries and IPC

It is possible to build a Win32-based dynamic-link library (DLL) so that its global data is shared with all processes that call the DLL. Therefore, cooperating processes can call the DLL to examine and modify global data owned by the DLL. For example, process A calls a DLL function with data that the DLL stores in its global data space. Process B calls another DLL function that retrieves that data. Because of the multitasking nature of the Win32 API, the DLL would have to use a semaphore or another synchronization object to control access to the shared memory.

Although shared global data can be used in a DLL, Win32 file mapping is recommended for shared memory. File mapping is more efficient and provides the additional benefit of access protection. (For example, a client can be limited to read-only access to a file-mapping object.)

Key Point  Although a developer can use shared global data segments in a DLL to allow two or more applications to share data, it is preferable to use Win32 file-mapping functions to create shared memory. For more information, see Dynamic-Link Libraries.


 Remote Procedure Call

The Win32 API provides remote procedure calls (RPC) to enable applications to call functions remotely. With RPC, communication with other processes becomes as easy as calling a function. RPC operates between processes on a single computer or on different computers on a network. One way to think of RPC is as a DLL that works on a network.

The RPC provided by the Win32 API is compliant with the Open Software Foundation (OSF) Distributed Computing Environment (DCE). This means that RPC applications written by using the Win32 API are able to communicate with other RPC applications running with other operating systems that support DCE. RPC automatically supports data conversion to account for different hardware architectures and for byte-ordering between dissimilar environments.

The Win32 software development kit includes RPC libraries that support MS-DOS−hosted RPC clients. With this facility, a Windows NT server, for example, can provide service to many MS-DOS clients through RPC.

RPC clients and servers are tightly coupled but still maintain high performance. Windows makes extensive use of RPC to facilitate a client-server relationship between different parts of the operating system.

Key Point  RPC provides IPC with a function interface, with support for automatic data conversion and for communications with other operating systems. Using RPC, a developer can create high-performance, tightly coupled distributed applications. For more information, see the Microsoft RPC Components.


 The Netbios Function and IPC

The Win32 API provides the Netbios function to process low-level network control functions. This capability is provided primarily for applications written using the IBM NetBIOS system that must be ported to Windows. It is highly recommended that a developer writing a new application use the other IPC mechanisms described in this topic rather than the low-level Netbios function. The IPC mechanisms provided in the Win32 API encapsulate and hide an enormous amount of raw NetBIOS functionality that the developer would otherwise have to implement.

Consider, for example, the following list of NetBIOS actions that would be necessary to emulate a Win32-based mailslot:

On the server end

•	Add the name to the local table.

•	Listen for the session connection.

•	Read the data upon connection.

•	Append the data to the message queue.

•	Close the session.

•	Listen for another session connection.

•	Allow the queued messages to be retrieved.

On the client side

•	Open the session.

•	Write the data.

•	Close the session.

Key Point  The Netbios function is provided only for porting an existing application written using the IBM NetBIOS system or for those applications that need specialized access to low-level network functionality. For most applications, it is better to use the higher-level IPC mechanisms available in the Win32 API. For more information, see Networks.


 Summary

It is likely that an application will support IPC by using several of the mechanisms described in this topic. For example, all Win32-based applications should provide at least minimal support for the clipboard. In addition, DDE and OLE may offer the application an opportunity to communicate in a loosely coupled way with a wide variety of applications that support these protocols. The great strength of these loosely coupled mechanisms is that a developer can enable an application to share data with other applications without knowing anything about the applications themselves. By supporting the protocols for the clipboard, DDE, and OLE, the developer is assured of a growing number of applications with which the application can share data. As new applications are written that support these protocols, the developer's application will be ready to communicate with them.

As an application becomes more sophisticated, a developer may find it advantageous to break up the application into tightly coupled cooperating processes that use shared memory, pipes, or RPC to communicate. These tightly coupled mechanisms can provide high-performance extensions to the application. But when adding these more specialized IPC methods, the developer should not abandon the more loosely coupled IPC methods that allow the application to share data in a general way with most other Win32-based applications.


 Large Integer Operations

This overview describes Microsoft Win32 support for operations on large (64-bit) integers.


 About Large Integer Operations

Applications can multiply signed or unsigned 32-bit integers, generating 64-bit results, by using the Int32x32To64 and UInt32x32To64 functions. Applications can shift bits in 64-bit values to the left or right by using the Int64ShllMod32, Int64ShraMod32, and Int64ShrlMod32 functions. These functions provide logical and arithmetic shifting.

Applications can also multiply and divide 32-bit values in a single operation by using the MulDiv function. Although the result of the operation is a 32-bit value, the function stores the intermediate result as a 64-bit value, so that information is not lost when large 32-bit values are multiplied and divided.


 Large Integer Operations Functions

Following are the functions used with large integer operations.

Int32x32To64
Int64ShllMod32
Int64ShraMod32
Int64ShrlMod32
MulDiv
UInt32x32To64


 Mailslots

A mailslot is a mechanism for one-way interprocess communications (IPC). An application written for Microsoft® Windows® can store messages in a mailslot. The owner of the mailslot can retrieve messages that are stored there. These messages are typically sent over a network to either a specified computer or to all computers in a specified domain. A domain is a group of workstations and servers that share a group name.


 About Mailslots

A mailslot is a pseudofile; it resides in memory, and standard Windows file functions write to it. Unlike disk files, however, mailslots are temporary. When every handle of a mailslot is closed, the mailslot and all the data it contains are deleted. The data in a mailslot message can be in any form.

A mailslot server is a process that creates and owns a mailslot. When the server creates a mailslot, it receives a mailslot handle. This handle must be used when a process reads messages from the mailslot. Only the process that creates a mailslot (or has obtained the handle by some other mechanism, such as inheritance) can read from the mailslot. A mailslot exists until all server handles to it have been closed or all server processes have exited. All mailslots are local to the process that creates them; a process cannot create a remote mailslot.

A mailslot client is a process that writes a message to a mailslot. Any process that has the name of a mailslot can put a message there. New messages follow preexisting messages in the mailslot.

Mailslots can broadcast messages within a domain. If several processes in a domain each create a mailslot using the same name, every message that is addressed to that mailslot and sent to the domain is received by the participating processes. Because one process can control both a server mailslot handle and the client handle retrieved when the mailslot is opened for a write operation, applications can easily implement a simple message-passing facility within a domain.

Some developers choose to use named pipes instead of mailslots for interprocess communications. Named pipes are a simple way for two processes to exchange messages. Mailslots, on the other hand, are a simple way for a process to broadcast messages to many other processes. For more information about named pipes, see Pipes.

Another issue in the choice between mailslots and named pipes is that mailslots use datagrams, and named pipes do not. A datagram is a small packet of information that the network sends along the wire. Like a radio or television broadcast, a datagram offers no confirmation of receipt; there is no  way to guarantee that a datagram has been received. Just as mountains, large buildings, or interfering signals might cause a radio or television signal to get lost, there are things the sender has no knowledge of that can prevent a datagram from reaching a particular destination. Named pipes are more like simple one-to-one telephone calls: you can talk only to one party, but you know that the conversation is occurring. So, if an application requires guaranteed reception, it  should use a named pipe; but named pipes cannot broadcast. Mailslots do not guarantee reception, but they can broadcast.


 Mailslot Names

When a process creates a mailslot, the mailslot name must have the following form.

\\.\mailslot\[path]name

A mailslot name requires the following elements: two backslashes to begin the name, a period, a backslash following the period, the word mailslot, and a trailing backslash. Case, however, is not important. A mailslot name can be preceded by a path consisting of the names of one or more pseudodirectories, separated by backslashes. For example, if a user expects messages on the subject of taxes from Bob, Pete, and Sue, the user's mailslot application might allow the user to create individual mailslots for each sender.

\\.\mailslot\taxes\bobs_comments

\\.\mailslot\taxes\petes_comments

\\.\mailslot\taxes\sues_comments

To put a message into a mailslot, a process opens a mailslot whose name is in one of several forms. To write to a mailslot on the local computer, a process can use a mailslot name using the same form required for creating a mailslot. This situation, however, is relatively uncommon. More frequently, a process uses the following form to write to a mailslot on a specific remote computer.

\\computername\mailslot\[path]name

The following form allows a process to put a message into every mailslot in the specified domain that has the given name.

\\domainname\mailslot\[path]name

To put a message into every mailslot with a given name in the system's primary domain, a process uses the following form.

\\*\mailslot\[path]name


 Mailslots and Microsoft LAN Manager 2.x

Windows uses mailslots similar to those developed for Microsoft LAN Manager version 2.0. An application that uses LAN Manager 2.x mailslots can interact easily with mailslots created by Windows. There are significant differences, however, between Windows-based mailslots and LAN Manager mailslots:

•	Windows-based mailslots all have the same class — there are no "first class" and "second class" mailslots.

•	All Windows-based mailslot messages have equal priority and are always appended to the mailslot buffer. When a Windows-based mailslot message is written to a mailslot on a computer that requires message priority, the system sets the priority to the lowest value (0).

•	Write operations to Windows-based mailslots on local computers return an error value if an error occurs. Write operations to remote Windows-based mailslots do not return an error value when they fail. (Because there is no built-in limit to the size of the mailslot buffer failure is unlikely.)

•	Write operations to Windows-based mailslots fail immediately if the message cannot be appended to the mailslot buffer (if the buffer is too small, for example). Immediate failure makes write time-outs irrelevant; contrary to LAN Manager mailslots, there are no write time-outs for Windows-based mailslots.

•	A process that creates a Windows-based mailslot can specify that the mailslot handle be inherited by its child processes. (Mailslot handles in LAN Manager cannot be inherited.)

A process writes messages to a Windows-based mailslot by using standard file input and output functions. The following table shows LAN Manager mailslot functions and their corresponding Windows functions.

LAN Manager functions	Windows functions
DosDeleteMailslot	CloseHandle
DosMailslotInfo	GetMailslotInfo
DosMakeMailslot	CreateMailslot
DosReadMailslot	ReadFile
DosWriteMailslot	WriteFile


 Server and Client Functions

Clients and servers when working with mailslots should use only the functions discussed in this section. Other Windows functions should not be used, even if they accept file handles or filenames as arguments.


 Mailslot Server Functions

Mailslot servers have exclusive use of three functions, as shown in the following table.

Function	Description
CreateMailslot	Creates a mailslot and returns a mailslot handle.
GetMailslotInfo	Retrieves the maximum message size, the mailslot size, the size of the next message in the mailslot, the number of messages in the mailslot, and the amount of time a read operation can wait for a message.
SetMailslotInfo	Changes the read time-out for a mailslot.
The following functions are also used by mailslot servers.

Function	Description
DuplicateHandle	Duplicates the mailslot handle.
ReadFile	Retrieves messages from a mailslot.
GetFileTime	Retrieves the date and time a mailslot was created.
SetFileTime	Sets the date and time a mailslot was created.


 Client Functions

A client process uses the following functions when interacting with a mailslot.

Function	Description
CloseHandle	Closes a mailslot handle for a client process.
CreateFile	Creates a mailslot handle for a client process.
DuplicateHandle	Duplicates a mailslot handle.
WriteFile	Writes data to a mailslot.


 Using Mailslots

•	Creating a mailslot

•	Writing to a mailslot

•	Reading from a mailslot


 Creating a Mailslot

Mailslots are supported by three specialized functions: CreateMailslot, GetMailslotInfo, and SetMailslotInfo. These functions are used by the mailslot server.

The following code sample uses the CreateMailslot function to retrieve the handle of a mailslot named sample_mailslot.

BOOL FAR PASCAL Makeslot(HWND hwnd, HDC hdc)

{

    LPSTR lpszSlotName = "\\\\.\\mailslot\\sample_mailslot";

    /* The mailslot handle "hSlot1" is declared globally. */

    hSlot1 = CreateMailslot(lpszSlotName,

        0,                         /* no maximum message size         */

        MAILSLOT_WAIT_FOREVER,     /* no time-out for read operations */

        (LPSECURITY_ATTRIBUTES) NULL); /* no security attributes      */

    if (hSlot1 == INVALID_HANDLE_VALUE) {

        ErrorHandler(hwnd, "CreateMailslot"); /* local error handler */

        return FALSE;

    }

    TextOut(hdc, 10, 10, "CreateMailslot successful.", 26);

    return TRUE;

}

To create a mailslot that can be inherited by child processes, an application should change the SECURITY_ATTRIBUTES structure passed as the last parameter of CreateMailslot. To do this, the application sets the bInheritHandle member of this structure to TRUE (the default setting is FALSE).


 Writing to a Mailslot

Writing to a mailslot is similar to writing to a standard disk file. The following code uses the CreateFile, WriteFile, and CloseHandle functions to put a short message in a mailslot. The message is broadcast to every computer in the primary domain of the system.

LPSTR lpszMessage = "Message for sample_mailslot in primary domain.";

BOOL fResult;

HANDLE hFile;

DWORD cbWritten;

hFile = CreateFile("\\\\*\\mailslot\\sample_mailslot",

    GENERIC_WRITE,

    FILE_SHARE_READ, /* required to write to a mailslot */

    (LPSECURITY_ATTRIBUTES) NULL,

    OPEN_EXISTING,

    FILE_ATTRIBUTE_NORMAL,

    (HANDLE) NULL);

if (hFile == INVALID_HANDLE_VALUE) {

    ErrorHandler(hwnd, "Primary domain"); /* local error handler */

    return FALSE;

}

fResult = WriteFile(hFile,

    lpszMessage,

    (DWORD) lstrlen(lpszMessage) + 1, /* include terminat. null char. */

    &cbWritten,

    (LPOVERLAPPED) NULL);

if (!fResult) {

    ErrorHandler(hwnd, "WriteFile");

    return FALSE;

}

TextOut(hdc, 10, 10, "WriteFile successful.", 21);

fResult = CloseHandle(hFile);

if (!fResult) {

    ErrorHandler(hwnd, "CloseHandle");

    return FALSE;

}

TextOut(hdc, 10, 30, "CloseHandle successful.", 23);

return TRUE;

Messages broadcast to a domain must be no longer than 400 bytes. Messages that are not broadcast should be smaller than 64 kilobytes. There is no limit to the number of messages that can be sent to a mailslot.


 Reading from a Mailslot

The process that creates a mailslot can read messages from it by using the mailslot handle in a call to the ReadFile function. The code in the following example calls the GetMailslotInfo function to determine whether there are messages in the mailslot. If messages are waiting, each is displayed in a message box along with the number of messages remaining to be read.

BOOL FAR PASCAL Readslot(HWND hwnd, HDC hdc)

{

    DWORD cbMessage, cMessage, cbRead;

    BOOL fResult;

    LPSTR lpszBuffer;

    CHAR achID[80];

        DWORD cAllMessages;

    cbMessage = cMessage = cbRead = 0;

    /* Mailslot handle "hSlot1" is declared globally. */

    fResult = GetMailslotInfo(hSlot1, /* mailslot handle         */

        (LPDWORD) NULL,               /* no maximum message size */

        &cbMessage,                   /* size of next message    */

        &cMessage,                    /* number of messages      */

        (LPDWORD) NULL);              /* no read time-out        */

    if (!fResult) {

        ErrorHandler(hwnd, "GetMailslotInfo");

        return FALSE;

    }

    if (cbMessage == MAILSLOT_NO_MESSAGE) {

        TextOut(hdc, 10, 10, "No waiting messages.", 20);

        return TRUE;

    }

    cAllMessages = cMessage;

    while (cMessage != 0) {              /* retrieves each message  */

        /* Create a message-number string. */

        wsprintf((LPSTR) achID,

            "\nMessage #%d of %d\n", cAllMessages - cMessage + 1,

            cAllMessages);

        /* Allocate memory for the message. */

        lpszBuffer = (LPSTR) GlobalAlloc(GPTR,

            lstrlen((LPSTR) achID) + cbMessage);

        lpszBuffer[0] = '\0';

        fResult = ReadFile(hSlot1,

            lpszBuffer,

            cbMessage,

            &cbRead,

            (LPOVERLAPPED) NULL);

        if (!fResult) {

            ErrorHandler(hwnd, "ReadFile");

            GlobalFree((HGLOBAL) lpszBuffer);

            return FALSE;

        }

        /* Concatenate the message and the message-number string. */

        lstrcat(lpszBuffer, (LPSTR) achID);

        /* Display the message. */

        MessageBox(hwnd,

            lpszBuffer,

            "Contents of Mailslot",

            MB_OK);

        GlobalFree((HGLOBAL) lpszBuffer);

        fResult = GetMailslotInfo(hSlot1, /* mailslot handle         */

            (LPDWORD) NULL,               /* no maximum message size */

            &cbMessage,                   /* size of next message    */

            &cMessage,                    /* number of messages      */

            (LPDWORD) NULL);              /* no read time-out        */

        if (!fResult) {

            ErrorHandler(hwnd, "GetMailslotInfo");

            return FALSE;

        }

    }

    return TRUE;

}

A mailslot exists until the CloseHandle function is called for all open server handles or until all server processes that own a mailslot handle exit. In both cases, any unread messages are deleted from the mailslot, all client handles to the mailslot are closed, and the mailslot itself is deleted from memory.


 Mailslot Functions

The following functions can be used with mailslots.

CreateMailslot
GetMailslotInfo
SetMailslotInfo


 Memory Management

This overview describes Win32 memory management. It also explains how to allocate and use memory.


 About Memory Management

In the Microsoft® Win32® application programming interface (API), each process has its own 32-bit virtual address space that enables addressing up to 4 gigabytes (GB) of memory. The 2 GB in low memory (0x00 to 0x7FFFFFFF) are available to the user, and the 2 GB in high memory (0x80000000 to 0xFFFFFFFF) are reserved for the kernel. The virtual addresses used by a process do not represent the actual physical location of an object in memory. Instead, for each process the kernel maintains a page map, an internal data structure used to translate virtual addresses into corresponding physical addresses.


 Virtual Address Space and Physical Storage

The virtual address space of each process is much larger than the total physical memory, random-access memory (RAM), available to all processes. To increase the size of physical storage, the kernel uses the disk for additional storage. The total amount of storage available to all executing processes is the sum of the physical memory, RAM, and the free space on disk available to the paging file, a disk file used to increase the amount of physical storage. Physical storage and the virtual (logical) address space of each process are organized into pages, units of memory, whose size depends on the host computer. For example, on x86 computers the host page size is 4 kilobytes (K).

To maximize its flexibility in managing memory, the kernel can move pages of physical memory to and from a paging file on disk. When a page is moved in physical memory, the kernel updates the page maps of the affected processes. When the kernel needs space in physical memory, it moves the least recently used pages of physical memory to the paging file. Manipulation of physical memory by the kernel is completely transparent to applications, which operate only in their virtual address spaces.

The pages of a process's virtual address space can be in one of the following states.

State	Description
Free	A free page is not currently accessible, but it is available to be committed or reserved.
Reserved	A reserved page is a block of the process's virtual address space that has been set aside for future use. The process cannot access a reserved page, and there is no physical storage associated with it. A reserved page reserves a range of virtual addresses that cannot be used subsequently by other allocation operations (that is, by functions such as malloc, LocalAlloc, and so on). A process can use the VirtualAlloc function to reserve pages of its address space and later to commit the reserved pages. It can use the VirtualFree function to release them.
Committed	A committed page is one for which physical storage (in memory or on disk) has been allocated. It can be protected to allow either no access or read-only access, or it can have read and write access. A process can use the VirtualAlloc function to allocate committed pages. The GlobalAlloc and LocalAlloc functions allocate committed pages with read-write access. A committed page allocated by VirtualAlloc can be decommitted by the VirtualFree function, which releases the page's storage and changes the state of the page to reserved.


 Global and Local Functions

A process can use the GlobalAlloc and LocalAlloc functions to allocate memory. In the linear 32-bit environment of the Win32 API, the local heap and the global heap are not distinguished. As a result, there is no difference between the memory objects allocated by these functions.

Memory objects allocated by GlobalAlloc and LocalAlloc are in private, committed pages with read-write access. Private memory cannot be accessed by other processes. Memory allocated by using GlobalAlloc with the GMEM_DDESHARE flag is not actually shared globally as it is in Windows version 3. x. However, this flag is available for compatibility purposes and can be used by some applications to enhance the performance of dynamic data exchange (DDE) operations. Applications requiring shared memory for other purposes must use file-mapping objects. Multiple processes can map a view of the same file-mapping object to provide named shared memory. For more information about file mapping, see File Mapping and Shared Memory.

By using GlobalAlloc and LocalAlloc, you can allocate a block of memory of any size that can be represented by 32 bits. You are limited only by the available physical memory, including storage in the paging file on disk. These functions, along with the other global and local functions that manipulate global and local memory objects, are included in the Win32 API for compatibility with 16-bit versions of Windows. However, the change from a 16-bit segmented memory model to a 32-bit virtual memory model has made some of the functions and their options unnecessary or meaningless. For example, there are no longer near and far pointers, because both local and global allocations return 32-bit virtual addresses.

Both GlobalAlloc and LocalAlloc can allocate fixed or movable memory objects. Movable objects can also be marked as discardable. In earlier versions of Windows, movable memory objects were important for memory management. They enabled the system to compact the heap when necessary to make space available for other memory allocations. By using virtual memory, the system is able to manage memory by moving pages of physical memory without affecting the virtual addresses of the processes using the pages. When the system moves a page of physical memory, it simply maps the process's virtual page to the new location of the physical page. Movable memory is still useful for allocating discardable memory. When the system needs additional physical storage, it can use a "least recently used" algorithm to free discardable memory that is not locked. Discardable memory should be used for data that is needed infrequently and can be regenerated easily.

When allocating a fixed memory object, GlobalAlloc and LocalAlloc return a 32-bit pointer that the calling process can immediately use to access the memory. For movable memory, the return value is a handle. To get a pointer to a movable memory object, the calling process uses the GlobalLock and LocalLock functions. These functions lock the memory so that it cannot be moved or discarded. The internal data structures for each memory object include a lock count that is initially zero. For movable memory objects, GlobalLock and LocalLock increment the count by one, and the GlobalUnlock and LocalUnlock functions decrement the count by one. Locked memory is not moved or discarded, unless the memory object is reallocated by using the GlobalReAlloc or LocalReAlloc function. The memory block of a locked memory object remains locked in memory until its lock count is decreased to zero, at which time it can be moved or discarded.

The actual size of the memory allocated by GlobalAlloc or LocalAlloc can be larger than the requested size. To determine the actual number of bytes allocated, use the GlobalSize or LocalSize function. If the amount allocated is greater than the amount requested, the process can use the entire amount.

The GlobalReAlloc and LocalReAlloc functions change the size, in bytes, or the attributes of a memory object allocated by GlobalAlloc and LocalAlloc. The size can increase or decrease.

The GlobalFree and LocalFree functions release memory allocated by GlobalAlloc, LocalAlloc, GlobalReAlloc, or LocalReAlloc.

Other global and local functions include the GlobalDiscard, LocalDiscard, GlobalFlags, LocalFlags, GlobalHandle, and LocalHandle functions. To discard a specified discardable memory object without invalidating the handle, use GlobalDiscard or LocalDiscard. The handle can be used later by GlobalReAlloc or LocalReAlloc to allocate a new block of memory associated with the same handle. To return information about a specified memory object, use GlobalFlags or LocalFlags. The information includes the object's lock count and indicates whether the object is discardable or has already been discarded. To return the handle of the memory object associated with a specified pointer, use GlobalHandle or LocalHandle.


 Standard C Library Functions

Win32 processes can safely use the standard C library functions (malloc, free, and so on) to manipulate memory. When used with previous versions of Windows, these functions had potential problems that no longer apply to applications using the Win32 API. For example, malloc allocates a fixed pointer that does not take advantage of movable memory. Memory management is no longer a problem because the system is free to manage memory by moving pages of physical memory without affecting the virtual addresses. Similarly, the distinction between near and far pointers is no longer relevant. So, unless you want to allocate discardable memory, it is now reasonable to use the standard C library functions for memory management.


 Virtual Memory Functions

The Win32 API provides a set of virtual memory functions that enable a process to manipulate or determine the status of pages in its virtual address space. Many applications are able to satisfy their memory needs by using the standard allocation functions (GlobalAlloc, LocalAlloc, malloc, and so on). However, virtual memory functions provide some capabilities not available to the standard allocation functions. They can perform the following operations:

•	Reserve a range of a process's virtual address space. Reserving address space does not allocate any physical storage, but it prevents other allocation operations from using the specified range. It does not affect the virtual address spaces of other processes. Reserving pages prevents needless consumption of physical storage, while enabling a process to reserve a range of its address space into which a dynamic data structure can grow. The process can allocate physical storage for this space, as needed.

•	Commit a range of reserved pages in a process's virtual address space so that physical storage (either in RAM or on disk) is accessible only to the allocating process.

•	Specify read-write, read-only, or no access for a range of committed pages. This differs from the standard allocation functions that always allocate pages with read-write access.

•	Free a range of reserved pages, making the range of virtual addresses available for subsequent allocation operations by the calling process.

•	Decommit a range of committed pages, releasing their physical storage and making it available for subsequent allocation by any process.

•	Lock one or more pages of committed memory into physical memory (RAM) so that the system cannot swap the pages out to the paging file.

•	Obtain information about a range of pages in the virtual address space of the calling process or a specified process.

•	Change the access protection for a specified range of committed pages in the virtual address space of the calling process or a specified process.

The virtual memory functions manipulate pages of memory. The functions use the size of a page on the current computer to round off specified sizes and addresses.

To determine the size of a page on the current computer, use the GetSystemInfo function.

The VirtualAlloc function performs one of the following operations:

•	Reserves one or more free pages.

•	Commits one or more reserved pages.

•	Reserves and commits one or more free pages.

You can specify the starting address of the pages to be reserved or committed, or you can allow the system to determine the address. The function rounds the specified address to the appropriate page boundary. Reserved pages are not accessible, but committed pages can be allocated with the PAGE_READWRITE, PAGE_READONLY, or PAGE_NOACCESS flag. When pages are committed, storage is allocated in the paging file, but each page is initialized and loaded into physical memory only at the first attempt to read from or write to that page. You can use normal pointer references to access memory committed by the VirtualAlloc function.

The VirtualFree function performs one of the following operations:

•	Decommits one or more committed pages, changing the state of the pages to reserved. Decommitting pages releases the physical storage associated with the pages, making it available to be allocated by any process. Any block of committed pages can be decommitted.

•	Releases a block of one or more reserved pages, changing the state of the pages to free. Releasing a block of pages makes the range of reserved addresses available to be allocated by the process. Reserved pages can be released only by freeing the entire block that was initially reserved by VirtualAlloc.

•	Decommits and releases a block of one or more committed pages simultaneously, changing the state of the pages to free. The specified block must include the entire block initially reserved by VirtualAlloc, and all of the pages must be currently committed.

The VirtualLock function enables a process to lock one or more pages of committed memory into physical memory (RAM), preventing the system from swapping the pages out to the paging file. It can be used to ensure that critical data is accessible without disk access. Locking pages into memory is dangerous because it restricts the system's ability to manage memory. Excessive use of VirtualLock can degrade system performance by causing executable code to be swapped out to the paging file. The VirtualUnlock function unlocks memory locked by VirtualLock.

The VirtualQuery and VirtualQueryEx functions return information about a region of consecutive pages beginning at a specified address in the address space of a process. VirtualQuery returns information about memory in the calling process. VirtualQueryEx returns information about memory in a specified process and is used to support debuggers that need information about a process being debugged. The region of pages is bounded by the specified address rounded down to the nearest page boundary. It extends through all subsequent pages with the following attributes in common:

•	The state of all pages is the same: either committed, reserved, or free.

•	If the initial page is not free, all pages in the region are part of the same initial allocation of pages that were reserved by a call to VirtualAlloc.

•	The access protection of all pages is the same (that is, the PAGE_READONLY, PAGE_READWRITE, or PAGE_NOACCESS flag).

The VirtualProtect function enables a process to modify the access protection of any committed page in the address space of a process. For example, a process can allocate read-write pages to store sensitive data, and then it can change the access to read only or no access to protect against accidental overwriting. VirtualProtect is typically used with pages allocated by VirtualAlloc, but it also works with pages committed by any of the other allocation functions. However, VirtualProtect changes the protection of entire pages, and pointers returned by the other functions are not necessarily aligned on page boundaries. The VirtualProtectEx function is similar to VirtualProtect, except it changes the protection of memory in a specified process. Changing the protection is useful to debuggers in accessing the memory of a process being debugged.


 Heap Functions

The heap functions enable a process to create a private heap, a block of one or more pages in the address space of the calling process. The process can then use a separate set of functions to manage the memory in that heap. There is no difference between memory allocated from a private heap and that allocated by using the standard allocation functions (GlobalAlloc, LocalAlloc, malloc, and so on).

The HeapCreate function creates a private heap object from which the calling process can allocate memory blocks by using the HeapAlloc function. HeapCreate specifies both an initial size and a maximum size for the heap. The initial size determines the number of committed, read-write pages initially allocated for the heap. The maximum size determines the total number of reserved pages. These pages create a contiguous block in the virtual address space of a process into which the heap can grow. Additional pages are automatically committed from this reserved space if requests by HeapAlloc exceed the current size of committed pages, assuming that the physical storage for it is available. Once the pages are committed, they are not decommitted until the process is terminated or until the heap is destroyed by calling the HeapDestroy function.

The memory of a private heap object is accessible only to the process that created it. If a dynamic-link library (DLL) creates a private heap, it does so in the address space of the process that called the DLL. It is accessible only to that process.

The HeapAlloc function allocates a specified number of bytes from a private heap and returns a pointer to the allocated block. The pointer identifies the block for the HeapFree function to release or for the HeapSize function to determine the size.

Memory allocated by HeapAlloc is not movable. Because the system cannot compact a private heap, the heap can become fragmented.

A possible use for the heap functions is to create a private heap when a process starts up, specifying an initial size sufficient to satisfy the memory requirements of the process. If the call to the HeapCreate function fails, the process can terminate or notify the user of the memory shortage; if it succeeds, however, the process is assured of having the memory it needs.


 Shared Memory

In the Win32 API, shared memory is implemented by file mapping. All memory allocated by the other allocation methods (the GlobalAlloc, LocalAlloc, HeapAlloc, or VirtualAlloc function) is accessible only to the calling process. Memory allocated by a DLL, however, is in the address space of the process that called the DLL and is not accessible to other processes using the same DLL.

Named file mapping provides an easy way to create a block of shared memory. A process can specify a name when it uses the CreateFileMapping function to create a file-mapping object. Other processes can specify the same name to either the CreateFileMapping or OpenFileMapping function to obtain a handle of the mapping object. The names of event objects, semaphore objects, mutex objects, and file-mapping objects share the same name space. If a specified name matches the name of an existing object of a different type, an error occurs. When creating named objects, try to use unique names and check the function return values for duplicate name errors.

Each process specifies its handle of the file-mapping object in the MapViewOfFile function to map a view of the file into its own address space. The views of all processes for a single file-mapping object are mapped into the same sharable pages of physical storage. However, the virtual addresses of the mapped views can vary from one process to another, unless the MapViewOfFileEx function is used to map the view at a specified address. Although sharable, the pages of physical storage used for a mapped file view are not global; they are not accessible to processes that have not mapped a view of the file.

A file-mapping object is associated with a disk file that the system uses when the mapped view is swapped out of physical memory and onto the disk. This disk swap file can be the system's paging file, or it can be some other file that was specified when the file-mapping object was created. In that case, the memory is initialized along with the contents of the file. Mapping a specified file in the file system is useful for processes that need to share the data in an existing file or that want to use the file to save data generated by the sharing processes. If you map a specified file, you should open it for exclusive access and keep the handle open until you are finished with the shared memory. Keeping it open will prevent other processes from opening another handle on the file to use ReadFile or WriteFile or from creating additional mapping objects for the same file, any of which actions can lead to unpredictable results.

Any pages committed by mapping a view of a file are released when the last process with a view of the mapping object either terminates or unmaps its view by calling the UnmapViewOfFile function. At this time, the specified file (if any) associated with the mapping object is updated. A specified file can also be forced to update by calling the FlushViewOfFile function.

For more information about file mapping, see File Mapping. For an example of shared memory in a DLL, see Dynamic-Link Libraries.

If multiple processes have write access to shared memory, access to the memory should be synchronized. For more information about interprocess synchronization, see Synchronization.


 Access Validation

The Win32 API provides a set of functions that a process can use to verify whether it has a specified type of access to a given memory address or range of addresses. The following access validation functions are available.

Function	Description
IsBadCodePtr	Determines whether the calling process has read access to the memory at the specified address.
IsBadReadPtr	Determines whether the calling process has read access to the memory at a specified range of addresses.
IsBadStringPtr	Determines whether the calling process has read access to the memory pointed to by a null-terminated string pointer. The function validates access for a specified number of characters or until it encounters the string's terminating null character.
IsBadWritePtr	Determines whether the calling process has write access to the memory at a specified range of addresses.
The IsBadHugeReadPtr and IsBadHugeWritePtr functions are also available for compatibility with earlier versions of Windows that distinguished between normal memory allocations and huge allocations occupying multiple segments. In the Win32 API, these functions are equivalent to IsBadReadPtr and IsBadWritePtr.

In a preemptive multitasking environment, it is possible for some other thread to change the process's access to the memory being tested. Even when an access validation function indicates that the process has the desired access to the specified memory, you should use structured exception handling when attempting to access the memory. Use of structured exception handling enables the system to notify the process if an access violation exception occurs, giving the process an opportunity to handle the exception. For more information about structured exception handling, see Structured Exception Handling.


 Guard Pages

An application establishes a guard page by setting a memory page's PAGE_GUARD page protection modifier flag. This flag can be specified, along with other page protection flags, in the functions VirtualAlloc, VirtualProtect, and VirtualProtectEx. The PAGE_GUARD flag can be used with any other page protection flag, except for the NO_ACCESS flag.

If a program attempts to access an address within a guard page, the operating system raises a STATUS_GUARD_PAGE (0x80000001) exception. The operating system also clears the PAGE_GUARD flag, removing the memory page's guard page status. The system will not stop the next attempt to access the memory page with a STATUS_GUARD_PAGE exception.

If a guard page exception occurs during a system service, the service fails and typically returns some failure status indicator. Since the system also removes the relevant memory page's guard page status, the next invocation of the same system service won't fail due to a STATUS_GUARD_PAGE exception (unless, of course, someone reestablishes the guard page).

A guard page thus provides a one-shot alarm for memory page access. This can be useful for an application that needs to monitor the growth of large dynamic data structures. For example, there are operating systems that use guard pages to implement automatic stack checking.

The following short program illustrates the one-shot behavior of guard page protection, and how it can cause a system service to fail:

#include <windows.h>

#include <stdio.h>

#include <stdlib.h>

int main()

{

// local variables

LPVOID lpvAddr;

DWORD cbSize;

BOOL vLock;

LPVOID commit;

// amount of memory we'll allocate

cbSize = 512;

// try to allocate some memory

lpvAddr = VirtualAlloc(NULL,cbSize,MEM_RESERVE,PAGE_NOACCESS);

// if we failed ...

if(lpvAddr == NULL)

fprintf(stdout,"VirtualAlloc failed on RESERVE with %ld\n",

GetLastError());

// try to commit the allocated memory

commit = VirtualAlloc(NULL,cbSize,MEM_COMMIT,PAGE_READONLY|PAGE_GUARD);

// if we failed ...

if(commit == NULL)

fprintf(stderr,"VirtualAlloc failed on COMMIT with %ld\n",

GetLastError());

else  // we succeeded

fprintf(stderr,"Committed %lu bytes at address %lp\n",

cbSize,commit);

// try to lock the committed memory

vLock = VirtualLock(commit,cbSize);

// if we failed ...

if(!vLock)

fprintf(stderr,"Cannot lock at %lp, error = %lu\n",

commit,GetLastError());

else  // we succeeded

       fprintf(stderr,"Lock Achieved at %lp\n",commit);

// try to lock the committed memory again

vLock = VirtualLock(commit,cbSize);

// if we failed ...

if(!vLock)

fprintf(stderr,"Cannot get 2nd lock at %lp, error = %lu\n",

commit,GetLastError());

else  // we succeeded

fprintf(stderr,"2nd Lock Achieved at %lp\n",commit);

} // endof function

The output of this program looks like this:

Committed 512 bytes at address 003F0000

Cannot lock at 003F0000, error = 0x80000001

2nd Lock Achieved at 003F0000

Note that the first attempt to lock the memory block fails, raising a STATUS_GUARD_PAGE exception. The second attempt succeeds, because the memory block's guard page protection has been toggled off by the first attempt.


 Using the Virtual Memory Functions

This section explains how to use the virtual memory functions for dynamic allocation.

The following example illustrates the use of the VirtualAlloc and VirtualFree functions in reserving and committing memory as needed for a dynamic array. First, VirtualAlloc is called to reserve a block of pages with NULL specified as the base address parameter, forcing the kernel to determine the location of the block. Later, VirtualAlloc is called whenever it is necessary to commit a page from this reserved region, and the base address of the next page to be committed is specified.

The example uses try-except structured exception-handling syntax to commit pages from the reserved region. Whenever a page fault exception occurs during the execution of the try block, the filter function in the expression preceding the except block is executed. If the filter function can allocate another page, execution continues in the try block at the point where the exception occurred. Otherwise, the exception handler in the except block is executed. For more information about structured exception handling, see Structured Exception Handling.

As an alternative to dynamic allocation, the process can simply commit the entire region instead of only reserving it. However, committing the region consumes physical storage that might not be needed, making it unavailable for use by other processes.

The example uses VirtualFree to free the reserved and committed pages when it is finished with them. The function is called twice: first to decommit the committed pages and again to release the entire region of reserved pages.

#define PAGELIMIT 80

#define PAGESIZE 0x1000

INT PageFaultExceptionFilter(DWORD);

VOID MyErrorExit(LPTSTR);

LPTSTR lpNxtPage;

DWORD dwPages = 0;

VOID UseDynamicVirtualAlloc(VOID) {

  LPVOID lpvBase;

  LPTSTR lpPtr;

  BOOL bSuccess;

  DWORD i;

  /* Reserve pages in the process's virtual address space. */

  lpvBase = VirtualAlloc(

         NULL,               /* system selects address   */

         PAGELIMIT*PAGESIZE, /* size of allocation       */

         MEM_RESERVE,        /* allocates reserved pages */

         PAGE_NOACCESS);     /* protection = no access   */

  if (lpvBase == NULL )

      MyErrorExit("VirtualAlloc reserve");

  lpPtr = lpNxtPage = (LPTSTR) lpvBase;

  /*

   * Use try-except structured exception handling when

   * accessing the pages. If a page fault occurs, the

   * exception filter is executed to commit another page

   * from the reserved block of pages.

   */

  for (i=0; i < PAGELIMIT*PAGESIZE; i++) {

      try {

          /* Write to memory. */

          lpPtr[i] = 'a';

      }

      /*

       * If there is a page fault, commit another page

       * and try again.

       */

      except ( PageFaultExceptionFilter(

                   GetExceptionCode() ) ) {

          /*

           * This is executed only if the filter function is

           * unsuccessful in committing the next page.

           */

          ExitProcess( GetLastError() );

      }

  }

  /* Release the block of pages when you are finished using them. */

  /* First, decommit the committed pages. */

  bSuccess = VirtualFree(

            lpvBase,          /* base address of block    */

            dwPages*PAGESIZE, /* bytes of committed pages */

            MEM_DECOMMIT);    /* decommit the pages       */

  /* Release the entire block. */

  if (bSuccess)

      bSuccess = VirtualFree(

            lpvBase,        /* base address of block     */

            0,              /* releases the entire block */

            MEM_RELEASE);   /* releases the pages        */

}

INT PageFaultExceptionFilter(DWORD dwCode) {

LPVOID lpvResult;

  /* If the exception is not a page fault, exit. */

  if (dwCode != EXCEPTION_ACCESS_VIOLATION) {

      printf("exception code = %d\n", dwCode);

      return EXCEPTION_EXECUTE_HANDLER;

  }

  printf("page fault\n");

  /* If the reserved pages are used up, exit. */

  if (dwPages >= PAGELIMIT) {

      printf("out of pages\n");

      return EXCEPTION_EXECUTE_HANDLER;

  }

  /* Otherwise, commit another page. */

  lpvResult = VirtualAlloc(

      (LPVOID) lpNxtPage, /* next page to commit  */

      PAGESIZE,           /* page size, in bytes  */

      MEM_COMMIT,         /* alloc committed page */

      PAGE_READWRITE);    /* read-write access    */

  if (lpvResult == NULL ) {

      printf("VirtualAlloc failed\n");

      return EXCEPTION_EXECUTE_HANDLER;

  }

  /*

   * Increment the page count, and advance lpNxtPage

   * to the next page.

   */

  dwPages++;

  lpNxtPage += PAGESIZE;

  /* Continue execution where the page fault occurred. */

  return EXCEPTION_CONTINUE_EXECUTION;

}


 Memory Management Functions

Following are the Win32 functions used in memory management.

CopyMemory
FillMemory
GetProcessHeap
GetProcessHeaps
GlobalAlloc
GlobalDiscard
GlobalFlags
GlobalFree
GlobalHandle
GlobalLock
GlobalMemoryStatus
GlobalReAlloc
GlobalSize
GlobalUnlock
HeapAlloc
HeapCompact
HeapCreate
HeapDestroy
HeapFree
HeapLock
HeapReAlloc
HeapSize
HeapUnlock
HeapValidate
IsBadCodePtr
IsBadHugeReadPtr
IsBadHugeWritePtr
IsBadReadPtr
IsBadStringPtr
IsBadWritePtr
LocalAlloc
LocalDiscard
LocalFlags
LocalFree
LocalHandle
LocalLock
LocalReAlloc
LocalSize
LocalUnlock
MoveMemory
VirtualAlloc
VirtualFree
VirtualLock
VirtualProtect
VirtualProtectEx
VirtualQuery
VirtualQueryEx
VirtualUnlock
ZeroMemory

Obsolete or Deleted Functions

ChangeSelector
DefineHandleTable
FreeSelector
GetCodeInfo
GetFreeSpace
GlobalCompact
GlobalDosAlloc
GlobalDosFree
GlobalFix
GlobalLRUNewest
GlobalLRUOldest
GlobalNotify
GlobalPageLock
GlobalPageUnlock
GlobalUnfix
GlobalUnWire
GlobalWire
LimitEmsPages
LocalCompact
LocalInit
LocalShrink
LockSegment
SetSwapAreaSize
SwitchStackBack
SwitchStackTo
UnlockSegment


 Performance Monitoring

Performance monitoring refers to the procedure for determining the system resources that an application consumes, such as processor time and memory.


 About Performance Monitoring

An application developer can use the Microsoft® Win32® performance monitoring functions to determine whether an application uses system resources efficiently and to fine-tune its performance. These functions are especially helpful in evaluating the effects of changes as developers migrate Microsoft® Windows® version 3.x applications to Win32.


 Counters and Elapsed Times

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. The elapsed time can be used to fine-tune sections of source code. Win32 provides two functions that enable application developers to obtain the value of a counter.

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 (if one exists on the system). By calling this function at the beginning and end of a section of code, an application essentially uses the counter as a stopwatch.

For example, QueryPerformanceFrequency might indicate that the frequency of the high-resolution performance counter on the system 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.


 Registry Database

Windows includes several tools that monitor the system. To present data in a different format, to use data inside another application, or to create a performance monitor, an application must retrieve information through the registry. For more information about the registry, see Registry.


 Getting Performance Data

An application can obtain system-performance information by using the RegQueryValueEx registry function with the HKEY_PERFORMANCE_DATA key. The application can use the RegOpenKey function to open the HKEY_PERFORMANCE_DATA handle, but it should use RegCloseKey to close the handle when it has finished running. This allows monitored software to be to be removed or installed, which cannot happen while they are being monitored. Network transports and drivers are examples of monitored software you may wish to remove.

Performance data is not stored in the registry. Using the RegQueryValueEx function with the HKEY_PERFORMANCE_DATA key causes the system to collect the data from the appropriate system object managers.

If an application is accessing a remote system, it must use the RegConnectRegistry function with the name of the remote system and the HKEY_PERFORMANCE_DATA key. RegConnectRegistry retrieves a key that the application can use with RegQueryValueEx to retrieve performance data from the remote system.

The basic layout of the data retrieved by RegQueryValueEx is a PERF_DATA_BLOCK structure followed by one PERF_OBJECT_TYPE structure and accompanying data for each type of object being monitored. The system being observed defines objects that can be monitored. Typical object types include processors, disks, and memory.

The PERF_DATA_BLOCK structure describes the system and the performance data. This structure contains the size of the data, the number of objects being monitored, the frequency and value of the high-resolution performance counter, an offset to the system name, and so on.

The PERF_OBJECT_TYPE structure describes the performance data for one type of object. This structure contains the size of the structure and the object-specific data that follows the structure, the number of counters defined for the object type, the number of instances of this object type, the level of informational details provided, the code page, indices to the object name and Explain title in the title database, and so on.

Following each PERF_OBJECT_TYPE structure, there is a list of PERF_COUNTER_DEFINITION structures, one for each counter defined for the object. The PERF_COUNTER_DEFINITION structure specifies the type and size of the counter, the offset to the counter, the detail level, the counter name, and Explain title in the registry, and so on.

An instance is a unique copy of a particular object type. The number of instances of a particular object type determines what follows the list of counter definitions. Not all object types have instances. A memory object, for example, has no instances because the system has only one memory. If the object type does not have instances, the counter definitions are followed by a single PERF_COUNTER_BLOCK structure and data for each counter. PERF_COUNTER_BLOCK contains the total length of the structure, in bytes, and the counter data that follows it.

If the object type has one or more instances, the list of counter definitions is followed by a PERF_INSTANCE_DEFINITION structure and a PERF_COUNTER_BLOCK structure for each instance. The PERF_INSTANCE_DEFINITION structure includes the name, identifier, and name of the parent of the instance. For example, the thread object type has instances; each thread in the system is an instance.

The number of object types, instances, and counters may vary from one call to the RegQueryValueEx function to another. Therefore, the number and size of structures included in the performance data as well as the size of the data that follows each structure may also vary. To ensure that it is receiving the appropriate information, an application must use the offsets included in the performance structures to navigate through the performance data. Every offset is relative to the beginning of the structure containing it.


 Getting Descriptive Text

The names of the objects and counters, as well as the text that explains their meaning, can be obtained by calling the RegQueryValueEx function with hkey set to HKEY_PERFORMANCE_DATA and lpszValueName set to "Counter <langid>" or "Explain <langid>", where <langid> is a language identifier string. A language identifier string is the ASCII representation of a 3-digit hexadecimal language identifier. For example, the code for English is "009"; calling RegQueryValueEx with "Counter 009" will obtain the object names in English.

The 'Counter' and 'Explain' data are stored as MULTI_SZ strings. This type of data consists of a list of Unicode strings, each terminated with UNICODE_NULL. The last string is followed by an additional UNICODE_NULL.

The strings are listed in pairs. The first item is the Unicode string of the index contained in PERF_OBJECT_TYPE.ObjectNameTitleIndex or PERF_COUNTER_DEFINITION.CounterNameTitleIndex. The second item is the actual name of the index. Following is a fragment of the paired data:

2     System

4     Memory

6     % Processor Time

10    Read Operations/sec

12    Write Operations/sec

To retrieve a name or the Explain text for an item, an application should perform the following steps:

1.	If the system is remote, call the RegConnectRegistry function to establish a connection to the remote machine's registry.

2.	Call the RegQueryValueEx function, specifying either 'Counter <langid>' or 'Explain <langid>' as the name of the value to query. This provides MULTI_SZ data containing either the names of all the objects and counters, or Help information for all the objects and counters. Note that these query strings are case-sensitive.

If the call to RegQueryValueEx is successful, the return value is ERROR_SUCCESS, and the names are returned in the buffer pointed to by the function's lpbData parameter.

If the input buffer size is 0, the RegQueryValueEx return value is the buffer size needed to store the names.

If the input buffer size is too small, the RegQueryValueEx return value is ERROR_MORE_DATA.

If the specified language code is not installed in the system, the RegQueryValueEx return value is ERROR_FILE_NOT_FOUND.

Refer to RegQueryValueEx for further details on its operation.

3.	Convert the appropriate index (PERF_OBJECT_TYPE.ObjectNameTitleIndex, PERF_OBJECT_TYPE.ObjectHelpTitleIndex, PERF_COUNTER_DEFINITION.CounterNameTitleIndex, or PERF_COUNTER_DEFINITION.CounterHelpTitleIndex) into Unicode or ASCII, depending on whether the application is Unicode or ASCII.

4.	Search the MULTI_SZ data for the appropriate index.

5.	Retrieve the string following the matching index as the object's name or descriptive information.

See Displaying Object, Counter, and Instance Names and Displaying Counter Title Indices for sample code illustrating these tasks.


 Getting Selected Data

When using the RegQueryValueEx function, an application must use the lpcbData parameter to specify a byte count of the amount of data to retrieve. Estimating this amount is difficult because the number of object types and their instances is determined by the system configuration and system activity. The amount may vary from one request to another. If the function does not pass enough space, the return value will be ERROR_MORE_DATA. Therefore, an application should include a retry loop in which it passes increasing amounts of buffer space until it no longer gets this error. The successful buffer size should be the starting point for subsequent calls to RegQueryValueEx.

In some cases, the application may not need to retrieve all the performance data provided by the system. Retrieving all of that data may be costly in terms of processor or memory requirements. The lpszValueName parameter of RegQueryValueEx indicates the amount of information to retrieve. This parameter can be in one of the following formats. The strings are case-sensitive. If a string includes more than one word, the words must be separated by a space.

String	Description
Global	The function returns all data for counters on the local computer except those included in the Costly category, described later in this table.
nnn xx yyy	Each of these strings is a Unicode string representing the decimal value for PERF_OBJECT_TYPE.ObjectNameTitleIndex. The function returns data only about the specified object types on the local computer.
	Note that more object types may be returned than are requested. This situation occurs if other object types are needed to support the requested data; for example, processes are needed to identify threads, so processes will also be returned even if only threads are requested.
Foreign ssss	The string ssss is the name of a foreign computer — that is, one that does not support the registry calls for returning data remotely. The function returns all data for counters on the foreign computer if your system is capable of collecting data from a foreign computer. This approach can be tried if RegConnectRegistry fails to connect to a foreign computer.
Foreign ssss nnn xx yyy	This format combines Foreign ssss and nnn xx yyy, discussed previously. The function returns all data for the specified counters on the foreign computer if the system is capable of collecting data from a foreign computer. An application can try this approach if RegConnectRegistry fails to connect to a foreign computer, but all of the available data is not wanted.
Costly	The function returns data for object types whose data is expensive to collect in terms of processor time or memory usage. A secondary thread may be started if an application needs to respond to the user during data collection.


 Using Performance Monitoring

This section includes examples of code that display objects, counters, and Explain text for a system.

•	Displaying object, counter, and instance names

•	Displaying counter title indices


 Displaying Object, Counter, and Instance Names

The example in this section shows how an application can display object, counter, and instance names.

#define UNICODE 1

#define _UNICODE 1

//

//  "C" Include files

//

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <malloc.h>

//

//  Windows Include files

//

#include <windows.h>

#include <winperf.h>

#include <tchar.h>

//

//  Local constants

//

#define RESERVED        0L       // reserved argument in fn. calls

#define INITIAL_SIZE    40960L   // initial perf data buff size

#define EXTEND_SIZE     4096L    // extend size of perf data buff

#define LINE_LENGTH     80       // display line length

#define WRAP_POINT       LINE_LENGTH-12   // wrap point for explain text

#define OBJECT_TEXT_INDENT  4    // indent of object explain text

//

//  Command line option values

//

#define COMMAND_ERROR      0

#define COMMAND_HELP       1

#define COMMAND_COUNTER    2

#define COMMAND_NOT_FOUND  3

//

//

//  Text string Constant definitions

//

const LPTSTR NamesKey = TEXT("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Perflib");

const LPTSTR DefaultLangId = TEXT("009");

const LPTSTR Counters = TEXT("Counter ");

const LPTSTR Help = TEXT("Explain ");

const LPTSTR LastHelp = TEXT("Last Help");

const LPTSTR LastCounter = TEXT("Last Counter");

const LPTSTR Slash = TEXT("\\");

const LPTSTR Global = TEXT("Global");

//

//  Global Buffers

//

TCHAR   cValueName[LINE_LENGTH];  // used to store counter value string

CHAR    cExeName[LINE_LENGTH*2];  // used in processing command line

CHAR    cCtrName[LINE_LENGTH];    // used in processing command line

BOOL

StringToInt (

    IN  LPTSTR  InStr,

    OUT PDWORD  pdwOutInt

)

/*++

StringToInt

    Returns the decimal interpretation of the string in the InStr

    argument. Works for either Unicode or ANSI strings.

Arguments:

    InStr

        string to translate

    pdwOutInt

        base 10 version of the number in the InStr argument

Return Value:

    TRUE if conversion was successful

    FALSE if not

--*/

{

    // check for NULL pointers passed to function

    if ((!InStr) || (!pdwOutInt)) {

        SetLastError (ERROR_BAD_ARGUMENTS);

        return FALSE;

    }

    if ( (_stscanf (InStr, TEXT(" %d"), pdwOutInt)) == 1) {

        return TRUE;

    } else {

        return FALSE;

    }

} // StringToInt

VOID

DisplayCommandHelp (

)

/*++

DisplayCommandHelp

    displays usage of command line arguments

Arguments

    NONE

Return Value

    NONE

--*/

{

    printf ("\n\nPERFEX:");

    printf ("\n    Sample program to demonstrate Win32 Performance API");

    printf ("\n\nUsage:");

    printf ("\n\n     perfex [-? | counter]");

    printf ("\n\n          -?  Displays a list of all counter objects in the system");

    printf ("\n     counter  is the name of a counter object");

    printf ("\n                  and displays the performance counters for that object");

    printf ("\n");

} // DisplayCommandHelp

VOID

DisplayNotFound (

)

/*++

DisplayNotFound

    displays not found & usage of command line arguments

Arguments

    NONE

Return Value

    NONE

--*/

{

    printf ("\n*** Counter object not found in the system***\n");

    DisplayCommandHelp();        // display command line usage

} // DisplayNotFound

LPTSTR

*BuildNameTable(

    HKEY    hKeyRegistry,   // handle to registry db with counter names

    LPTSTR  lpszLangId,     // unicode value of Language subkey

    PDWORD  pdwLastItem     // size of array in elements

)

/*++

BuildNameTable

    Caches the counter names and explain text to accelerate name lookups

    for display.

Arguments:

    hKeyRegistry

        Handle to an open registry (this can be local or remote.) and

        is the value returned by RegConnectRegistry or a default key.

    lpszLangId

            The unicode id of the language to look up. (default is 009)

    pdwLastItem

            The last array element

Return Value:

    pointer to an allocated table.

    (the caller must free it when finished!)

    the table is an array of pointers to zero terminated TEXT strings.

    A NULL pointer is returned if an error occured. (error value is

    available using the GetLastError function).

    The structure of the buffer returned is:

        Array of pointers to zero terminated strings consisting of

            pdwLastItem elements

        MULTI_SZ string containing counter id's and names returned from

            registry for the specified language

        MULTI_SZ string containing explain text id's

            and explain text strings

            as returned by the registry for the specified language

    The structures listed above are contiguous so that they may be freed

    by a single "free" call when finished with them, however only the

    array elements are intended to be used.

--*/

{

    LPTSTR  *lpReturnValue;     // returned pointer to buffer

    LPTSTR  *lpCounterId;       //

    LPTSTR  lpCounterNames;  // pointer to Names buffer returned by reg.

    LPTSTR  lpHelpText ;     // pointet to exlpain buffer returned by reg.

    LPTSTR  lpThisName;         // working pointer

    BOOL    bStatus;            // return status from TRUE/FALSE fn. calls

    LONG    lWin32Status;       // return status from fn. calls

    DWORD   dwHelpItems;        // number of explain text items

    DWORD   dwCounterItems;     // number of counter text items

    DWORD   dwValueType;        // value type of buffer returned by reg.

    DWORD   dwArraySize;        // size of pointer array in bytes

    DWORD   dwBufferSize;       // size of total buffer in bytes

    DWORD   dwCounterSize;      // size of counter text buffer in bytes

    DWORD   dwHelpSize;         // size of help text buffer in bytes

    DWORD   dwThisCounter;      // working counter

    DWORD   dwLastId;           // largest ID value used by explain/counter text

    HKEY    hKeyValue;          // handle to Perflib entry in registry

    TCHAR   CounterNameBuffer[LINE_LENGTH]; // buffer conatining Counter query

    TCHAR   HelpNameBuffer[LINE_LENGTH]; // buffer conatining Help query

    BOOL    bClosePerformanceKey; // flag for closing HKEY_PERFORMANCE_DATA key

    //initialize data

    lpReturnValue = NULL;

    hKeyValue = NULL;

    bClosePerformanceKey = FALSE;

    // check for null arguments and insert defaults if necessary

    if (!lpszLangId) {

        lpszLangId = DefaultLangId;

    }

    // open handle to Perflib key in registry to get number of items

    // used in order to compute array and buffer sizes

    lWin32Status = RegOpenKeyEx (

        hKeyRegistry,

        NamesKey,

        RESERVED,

        KEY_READ,

        &hKeyValue);

    // on error, free buffers, close keys and return NULL pointer

    if (lWin32Status != ERROR_SUCCESS) {

        goto BNT_BAILOUT;

    }

    // query registry to get number of Explain text items

    dwBufferSize = sizeof (dwHelpItems);

    lWin32Status = RegQueryValueEx (

        hKeyValue,

        LastHelp,

        RESERVED,

        &dwValueType,

        (LPBYTE)&dwHelpItems,

        &dwBufferSize);

    if ((lWin32Status != ERROR_SUCCESS) || (dwValueType != REG_DWORD)) {

        goto BNT_BAILOUT;

    }

    // query registry to get number of counter and object name items

    dwBufferSize = sizeof (dwCounterItems);

    lWin32Status = RegQueryValueEx (

        hKeyValue,

        LastCounter,

        RESERVED,

        &dwValueType,

        (LPBYTE)&dwCounterItems,

        &dwBufferSize);

    if ((lWin32Status != ERROR_SUCCESS) || (dwValueType != REG_DWORD)) {

        goto BNT_BAILOUT;

    }

    // use the greater of Help items or Counter Items to size array

    if (dwHelpItems >= dwCounterItems) {

        dwLastId = dwHelpItems;

    } else {

        dwLastId = dwCounterItems;

    }

    // array size is # of elements (+ 1, since names are "1" based)

    // times the size of a pointer

    dwArraySize = (dwLastId + 1) * sizeof(LPTSTR);

    // build the Query strings for the specified language ID

    lstrcpy (CounterNameBuffer, Counters);

    lstrcat (CounterNameBuffer, lpszLangId);

    lstrcpy (HelpNameBuffer, Help);

    lstrcat (HelpNameBuffer, lpszLangId);

    // get size of counter names

    dwBufferSize = 0;

    lWin32Status = RegQueryValueEx (

        HKEY_PERFORMANCE_DATA,

        CounterNameBuffer,

        RESERVED,

        &dwValueType,

        NULL,

        &dwBufferSize);

    if (lWin32Status != ERROR_SUCCESS) goto BNT_BAILOUT;

    bClosePerformanceKey = TRUE;

    dwCounterSize = dwBufferSize;

    // get size of help text

    dwBufferSize = 0;

    lWin32Status = RegQueryValueEx (

        HKEY_PERFORMANCE_DATA,

        HelpNameBuffer,

        RESERVED,

        &dwValueType,

        NULL,

        &dwBufferSize);

    if (lWin32Status != ERROR_SUCCESS) goto BNT_BAILOUT;

    dwHelpSize = dwBufferSize;

    // allocate buffer with room for pointer array, counter name

    // strings and help name strings

    lpReturnValue = malloc (dwArraySize + dwCounterSize + dwHelpSize);

    if (!lpReturnValue) {

        lWin32Status = ERROR_OUTOFMEMORY;

        goto BNT_BAILOUT;

    }

    // initialize pointers into buffer

    lpCounterId = lpReturnValue;

    lpCounterNames = (LPTSTR)((LPBYTE)lpCounterId + dwArraySize);

    lpHelpText = (LPTSTR)((LPBYTE)lpCounterNames + dwCounterSize);

    // initialize the pointers to NULL

    for (dwBufferSize = 0; dwBufferSize <= dwLastId; dwBufferSize++) {

        lpCounterId[dwBufferSize] = NULL;

    }

    // read counter names into buffer. Counter names will be stored as

    // a MULTI_SZ string in the format of "###" "Name"

    dwBufferSize = dwCounterSize;

    lWin32Status = RegQueryValueEx (

        HKEY_PERFORMANCE_DATA,

        CounterNameBuffer,

        RESERVED,

        &dwValueType,

        (LPVOID)lpCounterNames,

        &dwBufferSize);

    if (lWin32Status != ERROR_SUCCESS) goto BNT_BAILOUT;

    // read explain text into buffer. Counter names will be stored as

    // a MULTI_SZ string in the format of "###" "Text..."

    dwBufferSize = dwHelpSize;

    lWin32Status = RegQueryValueEx (

        HKEY_PERFORMANCE_DATA,

        HelpNameBuffer,

        RESERVED,

        &dwValueType,

        (LPVOID)lpHelpText,

        &dwBufferSize);

    if (lWin32Status != ERROR_SUCCESS) goto BNT_BAILOUT;

    // load counter array items, by locating each text string

    // in the returned buffer and loading the

    // address of it in the corresponding pointer array element.

    for (lpThisName = lpCounterNames;

         *lpThisName;

         lpThisName += (lstrlen(lpThisName)+1) ) {

        // first string should be an integer

        //       (in decimal digit characters)

        // so translate to an integer for use in array

        //       element identification

        bStatus = StringToInt (lpThisName, &dwThisCounter);

        if (!bStatus) {

            // error is in GetLastError

            goto BNT_BAILOUT;  // bad entry

        }

        // point to corresponding counter name which follows the id number

        // string.

        lpThisName += (lstrlen(lpThisName)+1);

        // and load array element with pointer to string

        lpCounterId[dwThisCounter] = lpThisName;

    }

    // repeat the above for the explain text strings

    for (lpThisName = lpHelpText;

         *lpThisName;

         lpThisName += (lstrlen(lpThisName)+1) ) {

        // first string should be an integer (in decimal unicode digits)

        bStatus = StringToInt (lpThisName, &dwThisCounter);

        if (!bStatus) {

            // error is in GetLastError

            goto BNT_BAILOUT;  // bad entry

        }

        // point to corresponding counter name

        lpThisName += (lstrlen(lpThisName)+1);

        // and load array element;

        lpCounterId[dwThisCounter] = lpThisName;

    }

    // if the last item arugment was used,

    // then load the last ID value in it

    if (pdwLastItem) *pdwLastItem = dwLastId;

    // close the registry keys

    RegCloseKey (hKeyValue);

    RegCloseKey (HKEY_PERFORMANCE_DATA);

    // exit returning the pointer to the buffer

    return lpReturnValue;

BNT_BAILOUT:

    if (lWin32Status != ERROR_SUCCESS) {

        // if lWin32Status has error, then set last error value to it,

        // otherwise assume that last error already has value in it

        SetLastError (lWin32Status);

    }

    if (lpReturnValue) {

        free ((LPVOID)lpReturnValue);

    }

    if (bClosePerformanceKey == TRUE) RegCloseKey (HKEY_PERFORMANCE_DATA);

    if (hKeyValue) RegCloseKey (hKeyValue);

    return NULL;

} // BuildNameTable

DWORD

GetSystemPerfData (

    IN HKEY hKeySystem,

    IN LPTSTR   pValue,

    IN PPERF_DATA_BLOCK *pPerfData

)

/*++

GetSystemPerfData

    Allocates data buffer as required and queries performance data

    specified in pValue from registry.

Arguments

    hKeySystem

        Handle to performance data in registry

    pValue

        Value string to return from registry

    pPerfData

        address of pointer to allocated perf data block that is

        filled in by call to RegQueryValue.

Return Value

    ERROR_SUCCESS if data returned

    WIN 32 ERROR if error encountered

--*/

{  // GetSystemPerfData

    LONG     lError ;   // Win 32 Error returned by fn. calls

    DWORD    Size;      // size of data buffer passed to fn. call

    DWORD    Type;      // type of data buffer returned by fn. call

    // allocate initial buffer if one is not passed into this routine

    if (*pPerfData == NULL) {

        *pPerfData = malloc (INITIAL_SIZE);

        if (*pPerfData == NULL) {

            return ERROR_OUTOFMEMORY;

        }

    }

    while (TRUE) {

        Size = _msize (*pPerfData); // query the size of the data buffer

        lError = RegQueryValueEx (  // get performance data from reg.

            hKeySystem,

            pValue,

            RESERVED,

            &Type,

            (LPBYTE)*pPerfData,

            &Size) ;

        // check for success and valid perf data block signature

        if ((!lError) &&

            (Size > 0) &&

            (*pPerfData)->Signature[0] == (WCHAR)'P' &&

            (*pPerfData)->Signature[1] == (WCHAR)'E' &&

            (*pPerfData)->Signature[2] == (WCHAR)'R' &&

            (*pPerfData)->Signature[3] == (WCHAR)'F' ) {

            return (ERROR_SUCCESS) ;

        }

        // if buffer is not big enough, reallocate and try again

        if (lError == ERROR_MORE_DATA) {

            *pPerfData = realloc (

                *pPerfData,

                _msize (*pPerfData) +

                EXTEND_SIZE) ;

            if (!*pPerfData) {

                return (lError) ;

            }

        } else {

            return (lError) ;

        }

    }

}  // GetSystemPerfData

/*++

Pointer Functions

    These functions are used to walk down the various structures

    in the perf data block returned by the call to RegQueryValueEx

--*/

PPERF_OBJECT_TYPE

FirstObject (

    PPERF_DATA_BLOCK pPerfData

)

{

    return ((PPERF_OBJECT_TYPE) ((PBYTE) pPerfData + pPerfData->HeaderLength)) ;

}

PPERF_OBJECT_TYPE

NextObject (

    PPERF_OBJECT_TYPE pObject

)

{  // NextObject

    return ((PPERF_OBJECT_TYPE) ((PBYTE) pObject + pObject->TotalByteLength)) ;

}  // NextObject

PERF_COUNTER_DEFINITION *

FirstCounter(

    PERF_OBJECT_TYPE *pObjectDef

)

{

    return (PERF_COUNTER_DEFINITION *)

               ((PCHAR) pObjectDef + pObjectDef->HeaderLength);

}

PERF_COUNTER_DEFINITION *

NextCounter(

    PERF_COUNTER_DEFINITION *pCounterDef

)

{

    return (PERF_COUNTER_DEFINITION *)

               ((PCHAR) pCounterDef + pCounterDef->ByteLength);

}

PERF_INSTANCE_DEFINITION *

FirstInstance (

    PERF_OBJECT_TYPE    *pObject

)

{

    return (PERF_INSTANCE_DEFINITION *)

        ((PBYTE) pObject + pObject->DefinitionLength);

}

PERF_INSTANCE_DEFINITION *

NextInstance (

    PERF_INSTANCE_DEFINITION *pInstance

)

{

    // next instance is after

    //    this instance + this instances counter data

    PERF_COUNTER_BLOCK  *pCtrBlk;

    pCtrBlk = (PERF_COUNTER_BLOCK *)

        ((PBYTE)pInstance + pInstance->ByteLength);

    return (PERF_INSTANCE_DEFINITION *)

        ((PBYTE)pInstance + pInstance->ByteLength + pCtrBlk->ByteLength);

}

LONG

PrintExplainText(

    DWORD   Indent,

    LPTSTR  szTextString

)

/*++

PrintExplainText

    Prints Long strings in a wrapped format for display on screen

Arguments

    Indent

        number of characters to indent text from left margin

    szTextString

        string to print on stdout

ReturnValue

    number of lines of text printed

--*/

{

    LPTSTR  szThisChar;

    BOOL    bNewLine;

    DWORD   dwThisPos;

    DWORD   dwLinesUsed;

    szThisChar = szTextString;

    dwLinesUsed = 0;

    // check arguments

    if (!szTextString) {

        return dwLinesUsed;

    }

    if (Indent > WRAP_POINT) {

        return dwLinesUsed; // can't do this

    }

    bNewLine = TRUE;

    // print text

    while (*szThisChar) {

        if (bNewLine){

            for (dwThisPos = 0; dwThisPos < Indent; dwThisPos++) {

                printf (" ");

            }

            bNewLine = FALSE;

        }

        if ((*szThisChar == ' ') && (dwThisPos >= WRAP_POINT)) {

            printf ("\n");

            bNewLine = TRUE;

            // go to next printable character

            while (*szThisChar <= ' ') {

                szThisChar++;

            }

            dwLinesUsed++;

        } else {

            printf ("%c", *szThisChar);

            szThisChar++;

        }

        dwThisPos++;

    }

    printf ("\n");

    bNewLine = TRUE;

    dwLinesUsed++;

    return dwLinesUsed;

} // PrintExplainText

DWORD

ProcessCommandLine (

    IN LPTSTR  lpCmdLine,

    IN LPTSTR  *lppCounterNames,

    IN DWORD   dwLastCounter,

    OUT LPTSTR  *lpValueString

)

/*++

ProcesCommandLine

    Reads arguments in command line and determines

    what program should do.

    Command line syntax is:

        PERFEX [ ? | Object]

    if "?" is in command line, then list of counter objects is displayed

    if a text string (other than "?") then string is translated to a

    counter object id and the counters for that object are displayed

Arguments

    lpCmdLine

        null terminated string that contains command line arguments

    lppCounterNames

        pointer to array of counter names (used for lookup)

    dwLastCounter

        number of elements in CounterNames array

    lpValueString

        value string to send to ReqQueryValue in order to return counter

        data for specified counter

ReturnValue

    TRUE    if valid data is returned

    FALSE   if unable to process command line

            (command syntax help should be displayed).

--*/

{

    LPTSTR  lpLocalString;

    DWORD   dwReturnValue;

    DWORD   dwElem;

    TCHAR   LocalBuffer[100];

    INT     BufferSize;

    INT     Index;

    dwReturnValue = COMMAND_ERROR;  // assume error until

                                    // proven otherwise

    lpLocalString = lpCmdLine;

    // move pointer past exe name

    while ((*lpLocalString > TEXT(' ')) && (*lpLocalString)) lpLocalString++;

    // move pointer to next non-space char;

    while ((*lpLocalString <= TEXT(' ')) && (*lpLocalString)) lpLocalString++;

    if (*lpLocalString) {

        // check for "HELP" command line argument

        if (*lpLocalString == TEXT('-')) {

            if (*++lpLocalString == TEXT('?')) {

                *lpValueString = Global;

                dwReturnValue = COMMAND_HELP;

            }

        } else { // first arg is not preceded by a '-'

                 // so compare to counters

            // see if command line matches a counter name

            // duplicate the LocalString

            BufferSize = sizeof(LocalBuffer) / sizeof(TCHAR) - 1;

            for (Index=0; Index < BufferSize; Index++) {

               if (*lpLocalString == TEXT('\0') ||

                  *lpLocalString == TEXT(' ')){

                  LocalBuffer[Index] = TEXT('\0');

                  break;

               } else {

                  LocalBuffer[Index] = *lpLocalString++;

               }

            }

            LocalBuffer[BufferSize] = TEXT('\0');

            dwReturnValue = COMMAND_NOT_FOUND;

            for (dwElem = 0; dwElem <= dwLastCounter; dwElem++) {

                // compare counter name to command line

                if (lppCounterNames[dwElem]) {

                    if ((lstrcmpi(lppCounterNames[dwElem], LocalBuffer))

                          == 0) {

                        // match found

                        // make element Number a string and exit

                        _stprintf ((LPTSTR)&cValueName[0], TEXT("%d"), dwElem);

                        *lpValueString = (LPTSTR)&cValueName[0];

                        dwReturnValue = COMMAND_COUNTER;

                        break;  // out of for loop

                    } // endif command line matches string

                } // endif lppCounterNames[dwElem] not equal NULL

            } // end for loop that searches table

        } // if not "-?"

    } else {

        dwReturnValue = COMMAND_ERROR;

    }

    return dwReturnValue;

} // ProcessCommandLine

VOID

DisplayObjectNames (

    PPERF_DATA_BLOCK    pPerf,

    LPTSTR              *pNames

)

/*++

DisplayObjectNames

    Scans the perf data and prints the name of each object found in the

    list

Arguments

    pPerf

        pointer to the perf data block returned by the call to

        RegQueryValueEx

    pNames

        pointer to the name table containing the array of counter names

        and explain text pointers.

Return Value

    NONE

--*/

{

    DWORD       dwThisObject;   // count of objects

    PPERF_OBJECT_TYPE pThisObject;    // pointer to object structure

    printf ("\nThe available performance counter objects are:");

    // loop from first object in buffer returned and display the

    // number of objects in the buffer

    for (dwThisObject = 0, pThisObject = FirstObject (pPerf);

        dwThisObject < pPerf->NumObjectTypes;

        dwThisObject++, pThisObject = NextObject(pThisObject)) {

        printf ("\n\"%ws\"\n",

            pNames[pThisObject->ObjectNameTitleIndex]);

        PrintExplainText (OBJECT_TEXT_INDENT,

            pNames[pThisObject->ObjectHelpTitleIndex]);

    }

} // DisplayObjectNames

VOID

DisplayCounterData (

    PPERF_DATA_BLOCK    pPerf,

    LPTSTR              *pNames

)

/*++

DisplayCounterData

    Scans the perf data and prints the name of counter and

    instance found in the list

Arguments

    pPerf

        pointer to the perf data block returned by the call to

        RegQueryValueEx

    pNames

        pointer to the name table containing the array of counter names

        and explain text pointers.

Return Value

    NONE

--*/

{

    DWORD               dwThisObject;   // count of objects

    PPERF_OBJECT_TYPE   pThisObject;    // pointer to object structure

    DWORD               dwThisCounter;  // count of counters

    PPERF_COUNTER_DEFINITION    pThisCounter;

    LONG               lThisInstance;

    PPERF_INSTANCE_DEFINITION   pThisInstance;

    // for each object in buffer, display each counter and instance

    for (dwThisObject = 0, pThisObject = FirstObject (pPerf);

        dwThisObject < pPerf->NumObjectTypes;

        dwThisObject++, pThisObject = NextObject(pThisObject)) {

        printf ("\n\nThe object \"%ws\", ",

            pNames[pThisObject->ObjectNameTitleIndex]);

        // if there are instnances, then loop through all instances

        // of this object

        if (pThisObject->NumInstances != PERF_NO_INSTANCES) {

            printf (" which has the following instances:");

            for (lThisInstance = 0,

                 pThisInstance = FirstInstance(pThisObject);

                lThisInstance < pThisObject->NumInstances;

                lThisInstance++,

                pThisInstance = NextInstance(pThisInstance)) {

                printf ("\n\t\"%ws\"",

                    (LPWSTR)((PBYTE)pThisInstance

                     + pThisInstance->NameOffset));

            }

            printf ("\n");

        } else {

            printf (" which has only one occurance,");

        }

        // now display all counters described in this object

        printf ("\nand has the following counters:");

        for (dwThisCounter = 0,

             pThisCounter = FirstCounter (pThisObject);

            dwThisCounter < pThisObject->NumCounters;

            dwThisCounter++, pThisCounter = NextCounter(pThisCounter)) {

            printf ("\n    \"%ws\"",

                    pNames[pThisCounter->CounterNameTitleIndex]);

        }

    }

} // DisplayCounterData

int

_CRTAPI1 main(

    int argc,

    char *argv[]

)

/*++

main

    entry point to perfex

    This program illustrates how to:

        get performance counter names and explain text from the registry

        obtain counter object value strings for use

        in querying perf. data

        walk the performance data structures returned by the registry

    This program does not show how to:

        format or process the counter data returned

            the counter data returned by the registry depends on the

            counter type. This data must be processed and formatted by

            the application program.

Arguments

    argc

        # of command line arguments present

    argv

        array of pointers to command line strings

    (note that these are obtained from the GetCommandLine function in

    order to work with both Unicode and ANSI strings.)

ReturnValue

    0 (ERROR_SUCCESS) if command was processed

    Non-Zero if command error was detected.

--*/

{

    LPTSTR  *lpCounterText; // array of counter name strings

    LPTSTR  lpCommandLine;  // pointer to command line string

    LPTSTR  lpValueString;  // value string to pass to registry for data

    DWORD   dwLastElement;  // number of elements in lpCounterText

    PPERF_DATA_BLOCK  pDataBlock; // pointer to perfdata block

    DWORD   dwStatus;       // return status of fn. calls

    DWORD   dwAction;       // display mode indicated by command line

    // query counter names from registry and load into table

    lpCounterText = BuildNameTable (

        HKEY_LOCAL_MACHINE,

        DefaultLangId,

        &dwLastElement);

    if (!lpCounterText) {

        printf ("ERROR: Unable to read counter names from registry.");

        return (TRUE);

    }

    lpCommandLine = GetCommandLine(); // get command line

    // read command line to determine what to do

    dwAction = ProcessCommandLine (lpCommandLine,

        lpCounterText,

        dwLastElement,

        &lpValueString);

    if (dwAction == COMMAND_ERROR) { // if unable to read command line

        DisplayCommandHelp();        // display command line usage

        free (lpCounterText);        // free buffer and return error

        return (TRUE);

    } else if (dwAction == COMMAND_NOT_FOUND) {

        DisplayNotFound();           // display not found

                                     // & command line usage

        free (lpCounterText);        // free buffer and return error

        return (TRUE);

    } else {

        // of command requires processing, then get perf data from reg.

        pDataBlock = NULL;

        dwStatus = GetSystemPerfData (

            HKEY_PERFORMANCE_DATA,

            lpValueString,

            &pDataBlock);

        if (dwStatus != ERROR_SUCCESS) {

            printf ("\nERROR: Unable to obtain data for that counter");

            free (lpCounterText);

            return (dwStatus);

        } else {

            // if data was returned, then display in format requested by

            // command line

            if (dwAction == COMMAND_HELP) {

                // display object names returned from registry

                DisplayObjectNames (pDataBlock, lpCounterText);

            } else {

                // display counter data for specified object

                DisplayCounterData (pDataBlock, lpCounterText);

            }

        }

        free (lpCounterText);

        return (ERROR_SUCCESS); // success

    }

}


 Displaying Counter Title Indices

This section includes example code that displays counter title indices and their names.

#define UNICODE 1

#define _UNICODE 1

#include <stdio.h>

#include <stdlib.h>

#include <assert.h>

#include <windows.h>

#include <string.h>

#include <memory.h>

#include <process.h>

#include <tchar.h>

#define SZ_DUMMY 10

int GetRegDataBound(HKEY hkey)

{

    TCHAR chDummy[SZ_DUMMY];

    DWORD cSubKeys;

    DWORD cbMaxSubkey;

    DWORD cbMaxClass;

    DWORD cValues;

    DWORD cbMaxValueName;

    DWORD cbMaxValueData;

    DWORD cbSecurityDescriptor;

    FILETIME ftLastWriteTime;

    DWORD lErr;

    DWORD cbClassSize = SZ_DUMMY;

    lErr = RegQueryInfoKey(hkey, chDummy, &cbClassSize,

        NULL, &cSubKeys, &cbMaxSubkey, &cbMaxClass,

        &cValues, &cbMaxValueName, &cbMaxValueData,

        &cbSecurityDescriptor, &ftLastWriteTime);

    if (lErr == ERROR_SUCCESS)

        return cbMaxValueData;

    else

        return -1;

}

int

_CRTAPI1 main(

)

{

    HKEY hKeyData;

    LONG lErr;

    LPTSTR lptstr;

    int   iSize;

    DWORD dwType;

    DWORD dwSize;

    int   iIndex;

    lErr = RegOpenKeyEx(HKEY_LOCAL_MACHINE,

TEXT("Software\\Microsoft\\Windows\\CurrentVersion\\Perflib\\009"),

        0, KEY_ALL_ACCESS, &hKeyData);

    assert(lErr == ERROR_SUCCESS);

    iSize = GetRegDataBound(hKeyData);

    if (iSize == -1)

        exit(-1);

    iSize++;

    lptstr = malloc(iSize * sizeof(TCHAR));

    dwSize = iSize;

    lErr = RegQueryValueEx(hKeyData, TEXT("Counters"), 0, &dwType,

        (LPBYTE) lptstr, &dwSize);

    assert(lErr == ERROR_SUCCESS);

    while (*lptstr) {

        _stscanf (lptstr, TEXT(" %d"), &iIndex);

//        iIndex = atoi(lptstr);

        lptstr += lstrlen(lptstr) + 1;

        printf("#define CNTR_%.3d\t \"%ws\"\n", iIndex, lptstr);

        lptstr += lstrlen(lptstr) + 1;

    }

    lErr = RegCloseKey(hKeyData);

    assert(lErr == ERROR_SUCCESS);

    return 0;

}


 Performance Monitoring Functions

Following are the functions used for performance monitoring.

RegConnectRegistry
RegQueryValueEx
QueryPerformanceCounter
QueryPerformanceFrequency

Obsolete or Deleted Functions

ProfClear
ProfFinish
ProfFlush
ProfInsChk
ProfSampRate
ProfSetup
ProfStart
ProfStop


 Pipes

A pipe is a communication conduit with two ends: a process with a handle to one end can communicate with a process having a handle to the other end. This overview describes how to create, manage, and use pipes.


 About Pipes

Pipes can be one-way — where one end is read-only and the other end is write-only, or they can be two-way — where both ends of the pipe can read or write. The Microsoft® Win32® application programming interface (API) provides both anonymous (unnamed) pipes and named pipes.


 Anonymous Pipes

An anonymous pipe is an unnamed, one-way pipe that transfers data between a parent process and a child process or between two child processes of the same parent process. Although it is possible to use anonymous pipes for communication between unrelated processes, it is easier to use named pipes for that purpose (for more information, see Named Pipes). Anonymous pipes are always local; they cannot be used for communication over a network.

The CreatePipe function creates an anonymous pipe and returns two handles, one to the read end and one to the write end of the pipe. The read handle has only read access to the pipe, and the write handle has only write access to the pipe. To communicate through the pipe, a handle to one of the ends must be passed to another process. Usually, this is done through inheritance; that is, a child process inherits a handle from its parent process. The inheritability of these handles is controlled by the creating process in the following ways:

•	The CreatePipe function specifies a SECURITY_ATTRIBUTES structure. If the bInheritHandle member of this structure is TRUE, the handles can be inherited.

•	The DuplicateHandle function can change the inheritability of a pipe handle. This function enables a process to create a noninheritable duplicate of an inheritable pipe handle or to create an inheritable duplicate of a noninheritable pipe handle.

•	The CreateProcess function enables a parent process to specify whether the new child process will inherit all or none of the parent's inheritable handles.

When a child process inherits a handle, the system enables the process to access the pipe referred to by that handle. However, the parent process must communicate the handle value to the child process. Typically, this is done by using the SetStdHandle and GetStdHandle functions, which set and retrieve the standard handles (standard input, standard output, or standard error) of a process. The parent process can specify a pipe handle in a call to SetStdHandle before the child process is created. The current standard handles of the parent process are inherited by the child process. So, when the child process starts up, it can use the GetStdHandle function to retrieve the handle value. The parent process can change its own standard handles without affecting the standard handles of its existing child processes.

To read from the pipe, a process uses the read handle in a call to the ReadFile function. Unless an error occurs, ReadFile does not return until the specified number of bytes has been read or until all handles to the write end of the pipe have been closed.

To write to the pipe, a process uses the write handle in a call to the WriteFile function. WriteFile does not return until the specified number of bytes has been written or an error occurs. If the pipe's buffer is full and bytes remain to be written, WriteFile does not return until some other process or thread reads from the pipe, making more buffer space available. CreatePipe enables the creating process to specify a buffer size for the pipe, or it can use the default buffer size.

Asynchronous (overlapped) read and write operations are not supported for anonymous pipes. This means that the ReadFileEx and WriteFileEx functions cannot be used with anonymous pipes. The lpOverLapped parameter of the ReadFile and WriteFile functions is ignored when used with an anonymous pipe.

An anonymous pipe exists until all handles to both read and write ends of the pipe are closed by the CloseHandle function.


 Named Pipes

A named pipe is a one-way or two-way pipe for communicating between a server process and one or more client processes. A server process specifies a name when it calls the CreateNamedPipe function to create one or more instances of a named pipe. All instances of a named pipe share the same pipe name, but each instance has its own buffers and handles and provides a separate conduit for client-server communication. When a client process specifies a pipe name in the CreateFile or CallNamedPipe function, it connects to an instance of the pipe. The use of instances enables multiple client processes to use the same named pipe simultaneously.

Subject to security checks, any client process can access a named pipe, making it easy to communicate between related or unrelated processes. Named pipes can be used locally to communicate between processes on the same machine or across a network to connect processes on different machines.

In the Win32 API, the difference between client and server processes is greatly diminished, because any process can act as both a server and a client, making peer-to-peer communication possible. As used here, server refers to a process that uses CreateNamedPipe to create a named pipe, and client refers to a process that uses CreateFile or CallNamedPipe to connect to an instance of a named pipe.


 Pipe Names

Each named pipe must have a unique name that distinguishes it from other named pipes. Use the following form when specifying the name of a pipe in the CreateNamedPipe, CreateFile, WaitNamedPipe, or CallNamedPipe function.

\\servername\pipe\pipename

The server process cannot create a pipe on a computer, so CreateNamedPipe must use a period to indicate the local computer as shown in this example.

\\.\pipe\pipename

Client processes using CreateFile, WaitNamedPipe, or CallNamedPipe can use a period to specify a local pipe, but they must specify the name of a server to open a pipe on a remote computer.

The pipename part of the name can include any character, including numbers and special characters. The entire pipe name string can be up to 256 characters long. Pipe names are not case-sensitive.


 Named Pipe Modes

A number of modes associated with a named pipe or with a handle to a named pipe affect the use and behavior of the pipe. Some of these modes can be set differently for each handle to a pipe, while others must be the same for all handles to a pipe.

The server process specifies the following modes when it calls the CreateNamedPipe function. The type and access modes must be the same for all instances of a pipe.

Mode	Meaning
Type	PIPE_TYPE_BYTE or PIPE_TYPE_MESSAGE. The type mode determines whether data is written to a named pipe as a stream of messages or as a stream of bytes. If no type is specified in CreateNamedPipe, the default is PIPE_TYPE_BYTE. A handle to a byte pipe must be in byte-read mode. A handle to a message pipe can be in either byte-read or message-read mode. For more information about pipe types, see Named Pipe Type and Read Mode.
Access	PIPE_ACCESS_INBOUND, PIPE_ACCESS_OUTBOUND, or PIPE_ACCESS_DUPLEX. This mode is equivalent to specifying the read or write access of the server's handles to the pipe, where inbound is equivalent to GENERIC_READ access, outbound is equivalent to GENERIC_WRITE access, and duplex is equivalent to GENERIC_READ | GENERIC_WRITE access. Client processes using the CreateFile function to connect to a named pipe must specify an access compatible with the access specified by the server. For example, a client must specify GENERIC_READ access for an outbound pipe.
The remaining pipe modes can differ for each pipe handle. This means that the client and server ends of the same pipe instance can use different modes. CreateNamedPipe sets all of these modes for the pipe handles of a server. CreateFile supports setting the overlapped and write-through modes for the pipe handles of a client. Both client and server processes use the SetNamedPipeHandleState function to set the read and wait modes of a pipe handle.

Mode	Meaning
Read	PIPE_READMODE_BYTE or PIPE_READMODE_MESSAGE. In byte-read mode, data is read from a named pipe as a stream of bytes. In message-read mode, data is read from a named pipe as a stream of messages. Only byte-read mode is allowed for byte-type pipes. Either byte-read or message-read mode is allowed for message-type pipes. The default is byte-type mode, if no read mode is specified in CreateNamedPipe. For more information about read modes, see Named Pipe Type and Read Mode.
Wait	PIPE_WAIT or PIPE_NOWAIT. In blocking-wait mode, the ReadFile, WriteFile, and ConnectNamedPipe functions wait indefinitely  in some situations   for a process on the other end of the pipe to perform an action. In nonblocking-wait mode, the functions return if they cannot finish their operations immediately. For more information about wait modes, see Blocking and Nonblocking Pipe Operations.
Overlapped	FILE_FLAG_OVERLAPPED. In overlapped mode, functions performing read, write, and connect operations that take a significant time to be completed can return immediately. This enables the thread to perform other operations while a time-consuming operation executes in the background. For more information about overlapped mode, see Synchronous and Overlapped Input and Output.
Write-through	FILE_FLAG_WRITE_THROUGH. In write-through mode, the functions that write to a named pipe do not return until the data written is transmitted across the network and into the pipe's buffer on the remote computer. This mode affects only write operations on byte-type pipes and, then, only when the client and server processes are on different computers. If write-through mode is not enabled, a write function returns successfully, even if the data is not transmitted. For more information about write-through modes, see Write-through to Remote Clients.
The initial read mode for a pipe handle is specified when a server process calls CreateNamedPipe. If PIPE_READMODE_BYTE is specified or if no read mode is specified, the pipe handle is created in byte-read mode. If both PIPE_READMODE_MESSAGE and PIPE_TYPE_MESSAGE are specified, the handle is created in message-read mode. For a client process, a pipe handle returned by CreateFile is always in byte-read mode initially. Both client and server processes can use the SetNamedPipeHandleState function to change the read mode of a pipe handle. For a message-type pipe, the read mode can be different for server and client handles to the same pipe instance.


 Named Pipe Operations

The first time the server calls CreateNamedPipe, the function specifies the maximum number of instances of the pipe that can exist simultaneously. Limited by this maximum, the server can call CreateNamedPipe repeatedly to create additional instances of the pipe. If the function succeeds, each call returns a handle to the server end of a named pipe instance.

As soon as a pipe instance is created, a client process can connect to it by calling the CreateFile or CallNamedPipe function. If a pipe instance is available, CreateFile returns a handle to the client end of the pipe instance. If no instances of the pipe are available, a client process can use the WaitNamedPipe function to wait for one to become available.

A client process can also use CallNamedPipe to combine into a single operation the functions that connect to a pipe instance (waiting for one to be available, if necessary), write a message, read a message, and close its pipe handle. CallNamedPipe can be used only by a client process and only with a message-type pipe.

A server process specifies a handle to a pipe instance in a call to the ConnectNamedPipe function to determine when a client process is connected to it. If the pipe handle is in blocking mode, the ConnectNamedPipe operation does not return until a client is connected.

Client and server processes can call one of several functions — in addition to CallNamedPipe — to read from and write to a named pipe. The behavior of these functions depends on the type of pipe and the modes in effect for the specified pipe handle, as follows:

•	The ReadFile and WriteFile functions can be used with either byte-type or message-type pipes.

•	The ReadFileEx and WriteFileEx functions can be used with either byte-type or message-type pipes if the pipe handle was opened for overlapped operations.

•	The PeekNamedPipe function can be used to read without removing the contents of either a byte-type pipe or a message-type pipe. PeekNamedPipe can also return additional information about the pipe instance.

•	The TransactNamedPipe function can be used with message-type pipes if the pipe handle of the calling process is set to message-read mode. The function writes a request message and reads a reply message in a single operation, enhancing network performance.

For a pipe handle in byte-read mode, a read operation is completed successfully when all available bytes in the pipe are read or when the specified number of bytes is read.

For a pipe handle in message-read mode, a ReadFile or ReadFileEx operation is completed successfully only when the entire message is read. If the specified number of bytes to read is less than the size of the next message, the function reads as much of the message as possible before returning FALSE (with the GetLastError function returning ERROR_MORE_DATA). However, the remainder of the message can be read by making additional calls to ReadFile, ReadFileEx, or PeekNamedPipe. Note that PeekNamedPipe returns TRUE after reading a complete or partial message, and it reports the number of bytes remaining in a partially read message.

For a message-type pipe with multiple unread messages, a read operation using a message-read pipe handle returns after reading one message. An operation using a byte-read handle does not distinguish between the messages — it reads all available bytes up to the specified number.

When a client and server finish using a pipe instance, the server calls the DisconnectNamedPipe function to close the connection to the client process. This function makes the client's handle invalid (if it has not already been closed). Any unread data in the pipe is discarded. To ensure that all bytes or messages written to the pipe are read by the client, the server first calls the FlushFileBuffers function, which does not return until the client has read all data from the pipe. After the client is disconnected, the server calls the CloseHandle function to close its handle to the pipe instance. Alternatively, the server can use ConnectNamedPipe to enable a new client to connect to this instance of the pipe.

A process can retrieve information about a named pipe by calling the GetNamedPipeInfo function, which returns the type of the pipe, the size of the input and output buffers, and the maximum number of pipe instances that can be created. The GetNamedPipeHandleState function reports on the read and wait modes of a pipe handle, the current number of pipe instances, and additional relevant information for pipes that communicate over a network. The SetNamedPipeHandleState function sets the read mode and wait modes of a pipe handle. For client processes communicating with a remote server, the function also controls the maximum number of bytes to collect or the maximum time to wait before transmitting a message (assuming the client's handle was not opened with write-through mode enabled).


 Named Pipe Server Process

The simplest server process can use the CreateNamedPipe function to create a single instance of a pipe, connect to a single client, communicate with the client, disconnect the pipe, close the pipe handle, and terminate. Typically, however, a server process must communicate with multiple client processes. A server process can use a single pipe instance by connecting to and disconnecting from each client in sequence, but performance would be poor. To handle multiple clients simultaneously, the server process must create multiple pipe instances.

The Win32 API supports three basic strategies for servicing multiple pipe instances. The server process can perform the following tasks:

•	Create multiple threads (and/or processes) with a separate thread for each instance of the pipe. For an example of a multithreaded server process, see Multithreaded Server.

•	Overlap operations by specifying an OVERLAPPED structure in the ReadFile, WriteFile, and ConnectNamedPipe functions. For an example of a server process that uses overlapped operations, see Server Using Overlapped Input and Output.

•	Overlap operations by using the ReadFileEx and WriteFileEx functions, which specify a completion routine to be executed when the operation is complete. For an example of a server process that uses completion routines, see Server Using Completion Routines.

The multithreaded server strategy is easy to write, because the thread for each instance handles communications for only a single client. The system allocates processor time to each thread as needed. But each thread uses system resources, which is a potential disadvantage for a server that handles a large number of clients. Other complications occur if the actions of one client necessitate communications with other clients (as for a network game program, where a move by one player must be communicated to the other players).

With a single-threaded server, it is easier to coordinate operations that affect multiple clients, and it is easier to protect shared resources (for example, a database file) from simultaneous access by multiple clients. The challenge of a single-threaded server is that it requires coordination of overlapped operations in order to allocate processor time for handling the simultaneous needs of the clients.


 Named Pipe Type and Read Mode

The type of a pipe determines how data is written to a named pipe, and the read mode determines how data is read from a named pipe. Data can be transmitted through a named pipe as either a stream of bytes or as a stream of messages. When using the CreateNamedPipe function to create an instance of a named pipe, the server process specifies the pipe's type, the type it must specify for all instances.

A byte-type pipe is created if PIPE_TYPE_BYTE is specified or, by default, if no type is specified. This means that data is written to the pipe as a stream of bytes, and the system does not differentiate between the bytes written in different write operations. A handle to a byte-type pipe can be in byte-read mode only.

A message-type pipe is created if PIPE_TYPE_MESSAGE is specified. This means that the system treats each write operation to the pipe as a message unit. A handle to a message-type pipe can be in either byte-read or message-read mode.


 Blocking and Nonblocking Pipe Operations

The wait mode (blocking or nonblocking) of a pipe handle determines whether the ReadFile, WriteFile, and ConnectNamedPipe functions return immediately in situations that would otherwise require an indefinite wait. By default, all named pipe handles returned by the CreateNamedPipe or CreateFile function are created with blocking-wait mode enabled. Nonblocking-wait mode can be enabled for a server's pipe handle by specifying PIPE_NOWAIT in CreateNamedPipe. Both server and client processes can change a pipe handle's wait mode by specifying either PIPE_WAIT or PIPE_NOWAIT in a call to the SetNamedPipeHandleState function.

Note that nonblocking-wait mode is supported for compatibility with Microsoft® LAN Manager version 2.0, and it should not be used to achieve overlapped input and output (I/O) with named pipes. Overlapped I/O should be used instead because it enables time-consuming ReadFile, WriteFile, and ConnectNamedPipe operations to execute in the background after the function returns. For more information about overlapped I/O, see Synchronous and Overlapped Input and Output.

A ReadFile operation is affected by the wait mode of a pipe handle when the pipe is empty. With a blocking-wait handle, the operation is not completed successfully until data is available from a thread writing to the other end of the pipe. Using a nonblocking-wait handle, the function returns FALSE immediately, and the GetLastError function returns ERROR_NO_DATA.

A WriteFile operation is affected by a pipe handle's wait mode when there is insufficient space in the pipe's buffer to hold all the data. With a blocking-wait handle, the write operation cannot succeed until sufficient space is created in the buffer by a thread reading from the other end of the pipe. With a nonblocking-wait handle, the write operation returns TRUE immediately, without writing any bytes (for a message-type pipe) or after writing as many bytes as the buffer holds (for a byte-type pipe).

A ConnectNamedPipe operation is affected by the wait mode of a pipe handle when there is no client connected or waiting to connect to the pipe instance. With a blocking-wait handle, the connect operation does not succeed until a client process connects to the pipe instance by calling either the CreateFile or CallNamedPipe function. With a nonblocking-wait handle, the connect operation returns FALSE immediately, and the GetLastError function returns ERROR_PIPE_LISTENING.

The wait mode of a pipe handle does not affect read or write operations when using the TransactNamedPipe or CallNamedPipe function.


 Synchronous and Overlapped Input and Output

The Win32 API supports both synchronous and asynchronous (overlapped) operations on named pipes. The ReadFile, WriteFile, TransactNamedPipe, and ConnectNamedPipe functions can run either synchronously or asynchronously. The ReadFileEx and WriteFileEx functions can run only asynchronously. When functions run synchronously, they do not return until the operation is finished. This means that the execution of the calling thread can be blocked for an indefinite period while it waits for a time-consuming operation to finish. When functions run asynchronously, they return immediately even before their operations are finished. This enables a time-consuming operation to be executed in the background while the calling thread is free to perform other tasks. In the Win32 API, asynchronous execution is known as overlapped I/O.

Overlapped operations make it possible for one pipe to read and write data simultaneously and for a single thread to perform simultaneous I/O operations on multiple pipe handles. This enables a single-threaded server process to handle communications with multiple client processes efficiently. For examples that illustrate overlapped operations by a server process, see Server Using Overlapped Input and Output and Server Using Completion Routines.

For a server process to use synchronous operations to communicate with more than one client, it must create a separate thread for each client process so that one or more threads can run while other threads are waiting. For an example of a multithreaded server process that uses synchronous operations, see Multithreaded Server.

Overlapped operations on a named pipe are enabled by specifying the FILE_FLAG_OVERLAPPED flag when the handle is created (by the CreateNamedPipe function for a server process or the CreateFile function for a client process). If this flag is not specified, overlapped mode is disabled. The overlapped mode of a pipe handle cannot be changed after the pipe handle has been created. The overlapped mode can be different for server and client handles to the same pipe instance.

The ReadFile, WriteFile, TransactNamedPipe, and ConnectNamedPipe functions can be performed asynchronously only if overlapped mode is enabled for the specified pipe handle and a valid pointer to an OVERLAPPED structure is specified. If the OVERLAPPED pointer is NULL, the system attempts to make the operation look synchronous. Depending on the number of pending operations, this attempt may or may not be successful. Therefore, it is strongly recommended that if you create a handle with FILE_FLAG_OVERLAPPED and want asynchronous behavior, you should always specify a valid OVERLAPPED structure or use the functions intended for asynchronous operations such as ReadFileEx and WriteFileEx.

When ReadFile, WriteFile, TransactNamedPipe, and ConnectNamedPipe are performed asynchronously, one of the following outcomes occurs:

•	If the operation is complete when the function returns, the return value indicates the success or failure of the operation. If an error occurs, the return value is FALSE and the GetLastError function returns something other than ERROR_IO_PENDING.

•	If the operation has not finished when the function returns, the return value is FALSE and GetLastError returns ERROR_IO_PENDING. In this case, the calling thread must wait until the operation has finished. The calling thread must then call the GetOverlappedResult function to determine the results.

The hEvent member of the specified OVERLAPPED structure must contain a handle to a manual-reset — not an auto-reset — event object. This is a synchronization object created by the CreateEvent function. The thread that initiates the overlapped operation uses the event object to determine when the operation is finished. For more information about event objects, see Synchronization.

An event object is either in a signaled or nonsignaled state. If an overlapped function returns before its operation has finished, the system sets the state of the event object to nonsignaled. When the operation is finished, the system sets the state to signaled. The thread can detect the object's state by specifying a handle to the event object in a call to one of the wait functions: WaitForSingleObject, WaitForMultipleObjects, WaitForSingleObjectEx, or WaitForMultipleObjectsEx. These functions do not return until the state of a specified object is signaled or until a time-out interval has elapsed. For the wait functions that wait for multiple objects, the function's return value indicates which of the objects is signaled. Doing this enables a server process to use a loop that performs the following steps:

1.	Specifies multiple event objects in a call to WaitForMultipleObjects or WaitForMultipleObjectsEx, and then waits for one of the objects to be in a signaled state.

2.	Uses the wait function's return value to determine which overlapped operation is finished.

3.	Performs the tasks necessary to clean up the completed operation and initiate the next operation for that pipe handle. This may involve starting another overlapped operation for the same pipe handle.

If the hEvent member of the OVERLAPPED structure is a NULL pointer instead of a handle to an event object, the calling thread can use the pipe handle to determine when an overlapped operation has finished. In this case, the system sets the state of the pipe handle to signaled or nonsignaled, as described previously for the state of an event object. It is strongly recommended that you always use an event object when performing overlapped operations rather than relying on the pipe handle. In particular, you should not use the pipe handle for this purpose when performing simultaneous operations on the same handle because there is no way of knowing which operation's completion caused the pipe handle to be signaled. The only safe technique for performing simultaneous operations on the same pipe handle is to use a separate OVERLAPPED structure with its own event object for each operation.

The ReadFileEx and WriteFileEx functions provide another form of overlapped I/O. Unlike the overlapped ReadFile and WriteFile functions, which use an event object to signal completion, the extended functions specify a completion routine. A completion routine is a function that is queued for execution when the read or write operation is finished. The completion routine is not executed until the thread that called ReadFileEx and WriteFileEx enters an alertable wait by calling one of the extended wait functions: WaitForSingleObjectEx, WaitForMultipleObjectsEx, or SleepEx. These functions are like the normal wait functions in that they return when a specified object is in the signaled state or when a time-out interval has elapsed. However, these functions can also perform an alertable wait that occurs when their fAlertable parameter is set to TRUE. In an alertable wait, the functions also return when a ReadFileEx or WriteFileEx completion routine is queued for execution. A server process can use the extended functions to perform a sequence of read and write operations for each client that connects to it. Each read or write operation in the sequence specifies a completion routine, and each completion routine initiates the next step in the sequence.


 Write-through to Remote Clients

The write-through mode of a named pipe handle affects the behavior of byte-type pipes when data is transmitted across a network. To enable write-through mode for a named pipe handle, a process specifies the FILE_FLAG_WRITE_THROUGH flag in the CreateNamedPipe function for a server process or in the CreateFile function for a client process. If this flag is not specified, write-through mode is disabled. The write-through mode of a pipe handle cannot be changed after the pipe handle has been created. The write-through mode can be different for server and client handles to the same pipe instance.

If write-through mode is not enabled, the system enhances the efficiency of network operations by buffering data until a minimum number of bytes have accumulated or until a maximum time period has elapsed. Buffering enables multiple write operations to be combined into a single network transmission. This means that a write operation can be successfully completed after the data is in the outbound buffer but before it is transmitted across the network.

A client process can use the SetNamedPipeHandleState function to control the number of bytes and the time-out period before transmission for a pipe on which write-through mode is disabled.

If write-through mode is enabled, the transmission across the network is not delayed and the write operation is not completed until the data is in the pipe buffer on the remote machine. Write-through mode is useful for applications that require synchronization for every write operation.

The system always performs write operations on message-type pipes as if write-through mode were enabled.


 Pipe Security

A server process uses the ImpersonateNamedPipeClient function to assume the security token of the client process connected to the specified pipe instance. This function can be useful in determining whether to grant the request of a client process. For example, a named pipe server can provide access to a database or file system to which the server process has privileged access. When a client process makes a request from the server, the client typically has some lesser level of security access. By assuming the security token of the client, the server can attempt to access the protected database. The system then grants or denies the server's access, based on the security level of the client. When the server is finished, it uses the RevertToSelf function to restore its original security token.


 Using Pipes

Pipes are useful in applications that must pass a continuous stream of data between processes.

•	Anonymous pipes overview

•	Multithreaded server

•	Server using overlapped input and output

•	Server using completion routines

•	Named pipe client process

•	Transactions on named pipes


 Anonymous Pipes Overview

A typical use of an anonymous pipe is to create a channel for communication between a parent process and its child process by redirecting the standard input or standard output handles of the child process. To redirect the standard output handle of a child process, the parent process performs the following steps:

1.	Calls the GetStdHandle function to get the current standard output handle, which it saves for later use.

2.	Calls the CreatePipe function to create an anonymous pipe. This function returns handles to the read and write ends of the pipe.

3.	Calls the SetStdHandle function to set its standard output to be the write handle of the pipe.

4.	Calls the CreateProcess function to create the child process. The child process inherits the inheritable handles of the parent process. It also inherits the values of the standard handles of its parent process, which it can retrieve using the GetStdHandle function.

5.	Calls the CloseHandle function to close the parent's handle to the write end of the pipe. After the child process inherits this handle, the parent process no longer needs its copy of the handle.

6.	Calls the ReadFile function to read from the pipe. This operation enables the parent process to read the data written to standard output by the child process.

The child process uses the GetStdHandle function to get its standard output handle, which is actually a handle to the write end of the pipe. The child process then uses the WriteFile function to write its output to the pipe.

Data is written to an anonymous pipe as a stream of bytes. This means that a process reading from a pipe cannot distinguish between the bytes written in separate write operations, unless both reading and writing processes use some protocol that lets the reading process know how many bytes to read. Typically, there is no protocol, so the reading process reads from the pipe until all write handles to the pipe are closed, which causes the ReadFile function to return FALSE. When a child process's standard output is redirected, the child process calls CloseHandle or terminates (which automatically closes the handle). Note that it is important for the parent process to close its handle to the write end of the pipe before trying to read from the pipe. Otherwise, its ReadFile operation cannot return FALSE because there is still an open handle to the write end of the pipe.

The procedure for redirecting standard input is similar to that for redirecting standard output, except that the pipe's read handle is used for the child's standard input. In this case, the parent process must ensure that the child process does not inherit the pipe's write handle. Otherwise, the ReadFile operation of the child process cannot return FALSE because the child process has an open handle to the write end of the pipe.

The parent process typically creates the read and write handles to the pipe so that they can be inherited by a child process. It does this by using CreatePipe, specifying a SECURITY_ATTRIBUTES structure with the bInheritHandle member set to TRUE. When a child's standard input is redirected, the child process should not inherit the pipe's write handle. The parent process prevents inheritance by using the DuplicateHandle function to create a noninheritable duplicate of the handle and then using CloseHandle to close the inheritable handle.

For an example program that uses anonymous pipes to redirect the standard handles of a child process, see Processes and Threads.


 Multithreaded Server

This example of a multithreaded server process has a main thread that loops continuously, creating a pipe instance and waiting for a client process to connect. When a client process connects, the server process creates a thread to service that client and the loop starts over. It is possible for a client process to connect successfully to the pipe instance in the interval between calls to the CreateNamedPipe and ConnectNamedPipe functions. If this happens, ConnectNamedPipe returns FALSE, and GetLastError returns ERROR_PIPE_CONNECTED.

The thread created to service each pipe instance reads requests from the pipe and writes replies to the pipe until the client process closes its handle. When this happens, the thread flushes the pipe, disconnects, closes its pipe handle, and terminates.

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <windows.h>

VOID InstanceThread(LPVOID);

VOID GetAnswerToRequest(LPTSTR, LPTSTR, LPDWORD);

int xx = 0;

DWORD main(VOID) {

  BOOL fConnected;

  DWORD dwThreadId;

  HANDLE hPipe, hThread;

  LPTSTR lpszPipename = "\\\\.\\pipe\\mynamedpipe";

  /*

   * The main loop creates an instance of the named pipe and

   * then waits for a client to connect to it. When the client

   * connects, a thread is created to handle communications

   * with that client, and the loop is repeated.

   */

  for (;;) {

      hPipe = CreateNamedPipe(

          lpszPipename,             /* pipe name          */

          PIPE_ACCESS_DUPLEX,       /* read/write access  */

          PIPE_TYPE_MESSAGE |       /* message type pipe  */

          PIPE_READMODE_MESSAGE |   /* message-read mode  */

          PIPE_WAIT,                /* blocking mode      */

          PIPE_UNLIMITED_INSTANCES, /* max. instances     */

          BUFSIZE,                  /* output buffer size */

          BUFSIZE,                  /* input buffer size  */

          PIPE_TIMEOUT,             /* client time-out    */

          NULL);                    /* no security attr.  */

      if (hPipe == INVALID_HANDLE_VALUE)

          MyErrExit("CreatePipe");

      /*

       * Wait for the client to connect; if it succeeds,

       * the function returns TRUE. If the function returns FALSE,

       * GetLastError returns ERROR_PIPE_CONNECTED.

       */

      fConnected = ConnectNamedPipe(hPipe, NULL) ?

                   TRUE :

                   (GetLastError() == ERROR_PIPE_CONNECTED);

      if (fConnected) {

          /* Create a thread for this client. */

          hThread = CreateThread(

              NULL,           /* no security attr.    */

              0,              /* default stack size   */

              (LPTHREAD_START_ROUTINE) InstanceThread,

              (LPVOID) hPipe, /* thread parameter     */

              0,              /* not suspended        */

              &dwThreadId);   /* returns thread ID    */

          if (hThread == INVALID_HANDLE_VALUE)

              MyErrExit("CreateThread");

      } else

         /* The client could not connect, so close the pipe. */

         CloseHandle(hPipe);

  }

  return 1;

}

VOID InstanceThread(LPVOID lpvParam) {

  CHAR chRequest[BUFSIZE];

  CHAR chReply[BUFSIZE];

  DWORD cbBytesRead, cbReplyBytes, cbWritten;

  BOOL fSuccess;

  HANDLE hPipe;

  /* The thread's parameter is a handle to a pipe instance. */

  hPipe = (HANDLE) lpvParam;

  while (1) {

      /* Read client requests from the pipe. */

      fSuccess = ReadFile(

          hPipe,        /* handle to pipe         */

          chRequest,    /* buffer to receive data */

          BUFSIZE,      /* size of buffer         */

          &cbBytesRead, /* number of bytes read   */

          NULL);        /* not overlapped I/O     */

      if (! fSuccess || cbBytesRead == 0)

          break;

      GetAnswerToRequest(chRequest, chReply, &cbReplyBytes);

      /* Write the reply to the pipe. */

      fSuccess = WriteFile(

         hPipe,        /* handle to pipe           */

         chReply,      /* buffer to write from     */

         cbReplyBytes, /* number of bytes to write */

         &cbWritten,   /* number of bytes written  */

         NULL);        /* not overlapped I/O       */

      if (! fSuccess || cbReplyBytes != cbWritten) break;

  }

  /*

   * Flush the pipe to allow the client to read the pipe's contents

   * before disconnecting. Then disconnect the pipe, and close the

   * handle to this pipe instance.

   */

  FlushFileBuffers(hPipe);

  DisconnectNamedPipe(hPipe);

  CloseHandle(hPipe);

}


 Server Using Overlapped Input and Output

This example is a single-threaded server process that uses overlapped operations to service simultaneous connections to multiple client processes. The server process creates a fixed number of pipe instances, each of which can be connected to a separate client process. When a client process has finished using its pipe instance, the server disconnects from the client and reuses the pipe instance to connect to a new client.

Associated with each pipe instance is an OVERLAPPED structure containing an event object. This structure is specified as a parameter in each ReadFile, WriteFile, and ConnectNamedPipe operation on the pipe instance. Although the example shows simultaneous operations on different pipe instances, it avoids simultaneous operations on a single pipe instance. Because the same event object is used for read, write, and connect operations for each instance, there is no way to know which operation's completion caused the event to be set to the signaled state for simultaneous operations using the same pipe instance.

The event handles for each pipe instance are also stored in an array used by the WaitForMultipleObjects function. This function waits for one of the events to be signaled, and its return value is the array index of the event that satisfied the wait. The example uses this index to retrieve a structure containing information for the pipe instance. The server uses the fPendingIO member of the structure to keep track of whether the most recent I/O operation on the instance was pending, necessitating a call to the GetOverlappedResult function. It uses the dwState member of the structure to determine the next operation that must be performed for the instance.

Overlapped ReadFile, WriteFile, and ConnectNamedPipe operations may have finished when the function returns, or they may still be pending when the function returns. If the operation is pending, the event object in the specified OVERLAPPED structure is set to the nonsignaled state before the function returns. When the pending operation has finished, the system sets the state of the event object to signaled. The state of the event object is not changed if the operation finishes before the function returns.

Because the example uses manual reset event objects, the state of the event objects is not changed to nonsignaled by the WaitForMultipleObjects function. This is important, because the example relies on the event objects remaining in the signaled state except when there is a pending operation.

If the operation is already finished when ReadFile, WriteFile, or ConnectNamedPipe returns, the function's return value indicates the result. For read and write operations, the number of bytes transferred is also returned. If the operation is still pending, the ReadFile, WriteFile, or ConnectNamedPipe function returns FALSE and the GetLastError function returns ERROR_IO_PENDING. In this case, the results are retrieved using the GetOverlappedResult function after the operation has finished. GetOverlappedResult returns only the results of operations that were pending, and does not report the results of operations that were completed before the overlapped ReadFile, WriteFile, or ConnectNamedPipe function returned.

Before disconnecting from a client, the multithreaded server example in the previous section used FlushFileBuffers to ensure that the client had read everything written to the pipe. This would defeat the purpose of overlapped I/O, because the flush operation would block the execution of the server thread while it waits for the client to empty the pipe. Consequently, it is necessary to wait for a signal from the client that it has finished before disconnecting. In this example, the signal is the error generated by trying to read from the pipe after the client process closes its handle.

#include <windows.h>

#define CONNECTING_STATE 0

#define READING_STATE 1

#define WRITING_STATE 2

#define INSTANCES 4

typedef struct {

  OVERLAPPED oOverlap;

  HANDLE hPipeInst;

  CHAR chBuf[BUFSIZE];

  DWORD cbToWrite;

  DWORD dwState;

  BOOL fPendingIO;

} PIPEINST, *LPPIPEINST;

VOID DisconnectAndReconnect(DWORD);

BOOL ConnectToNewClient(HANDLE, LPOVERLAPPED);

VOID GetDataToWriteToClient(LPPIPEINST);

PIPEINST Pipe[INSTANCES];

HANDLE hEvents[INSTANCES];

DWORD main(VOID) {

  DWORD i, dwWait, cbBytes, dwErr;

  BOOL fSuccess;

  LPTSTR lpszPipename = "\\\\.\\pipe\\mynamedpipe";

  /*

   * The initial loop creates several instances of a named pipe

   * along with an event object for each instance.  An

   * overlapped ConnectNamedPipe operation is started for

   * each instance.

   */

  for (i = 0; i < INSTANCES; i++) {

      /* Create an event object for this instance. */

      hEvents[i] = CreateEvent(

          NULL,    /* no security attr.        */

          TRUE,    /* manual-reset event       */

          TRUE,    /* initial state = signaled */

          NULL);   /* unnamed event object     */

      if (hEvents[i] == NULL)

          MyErrExit("CreateEvent");

      Pipe[i].oOverlap.hEvent = hEvents[i];

      Pipe[i].hPipeInst = CreateNamedPipe(

          lpszPipename,            /* pipe name           */

          PIPE_ACCESS_DUPLEX |     /* read/write access   */

          FILE_FLAG_OVERLAPPED,    /* overlapped mode     */

          PIPE_TYPE_MESSAGE |      /* message-type pipe   */

          PIPE_READMODE_MESSAGE |  /* message-read mode   */

          PIPE_WAIT,               /* blocking mode       */

          INSTANCES,               /* number of instances */

          BUFSIZE,                 /* output buffer size  */

          BUFSIZE,                 /* input buffer size   */

          PIPE_TIMEOUT,            /* client time-out     */

          NULL);                   /* no security attr.   */

      if (Pipe[i].hPipeInst == INVALID_HANDLE_VALUE)

          MyErrExit("CreatePipe");

      /* Call the subroutine to connect to the new client. */

      Pipe[i].fPendingIO = ConnectToNewClient(

          Pipe[i].hPipeInst,

          &Pipe[i].oOverlap);

      Pipe[i].dwState = Pipe[i].fPendingIO ?

          CONNECTING_STATE : /* still connecting   */

          READING_STATE;     /* ready to read      */

  }

  while (1) {

      /*

       * Wait for the event object to be signaled, indicating

       * completion of an overlapped read, write, or

       * connect operation.

       */

      dwWait = WaitForMultipleObjects(

         INSTANCES,    /* number of event objects */

         hEvents,      /* array of event objects  */

         FALSE,        /* does not wait for all   */

         INFINITE);    /* waits indefinitely      */

      /* dwWait shows which pipe completed the operation.  */

      i = dwWait - WAIT_OBJECT_0; /* determines which pipe */

      if (i < 0 || i > (INSTANCES - 1))

          MyErrExit("index out of range");

      /* Get the result if the operation was pending. */

      if (Pipe[i].fPendingIO) {

          fSuccess = GetOverlappedResult(

               Pipe[i].hPipeInst, /* handle to pipe       */

               &Pipe[i].oOverlap, /* OVERLAPPED structure */

               &cbBytes,          /* bytes transferred    */

               FALSE);            /* do not wait          */

          switch (Pipe[i].dwState) {

              /* Pending connect operation */

              case CONNECTING_STATE:

                  if (! fSuccess)

                      MyErrExit("ConnectNamedPipe");

                  Pipe[i].dwState = READING_STATE;

                  break;

              /* Pending read operation */

              case READING_STATE:

                  if (! fSuccess || cbBytes == 0) {

                      DisconnectAndReconnect(i);

                      continue;

                  }

                  Pipe[i].dwState = WRITING_STATE;

                  break;

              /* Pending write operation */

              case WRITING_STATE:

                  if (! fSuccess ||

                          cbBytes != Pipe[i].cbToWrite) {

                      DisconnectAndReconnect(i);

                      continue;

                  }

                  Pipe[i].dwState = READING_STATE;

                  break;

              default:

                  MyErrExit("invalid pipe state");

          }

      }

      /* The pipe state determines which operation to do next. */

      switch (Pipe[i].dwState) {

          /*

           * READING_STATE:

           * The pipe instance is connected to the client

           * and is ready to read a request from the client.

           */

          case READING_STATE:

                  fSuccess = ReadFile(

                  Pipe[i].hPipeInst,

                  Pipe[i].chBuf,

                  BUFSIZE,

                  &cbBytes,

                  &Pipe[i].oOverlap);

              /* The read operation completed successfully. */

              if (fSuccess && cbBytes != 0) {

                  Pipe[i].fPendingIO = FALSE;

                  Pipe[i].dwState = WRITING_STATE;

                  continue;

              }

              /* The read operation is still pending */

              dwErr = GetLastError();

              if (! fSuccess &&

                    (dwErr == ERROR_IO_PENDING)) {

                Pipe[i].fPendingIO = TRUE;

                continue;

              }

              /* An error occurred; disconnect from the client. */

              DisconnectAndReconnect(i);

              break;

          /*

           * WRITING_STATE:

           * The request was successfully read from the client.

           * Get the reply data and write it to the client.

           */

          case WRITING_STATE:

              GetDataToWriteToClient(&Pipe[i]);

              fSuccess = WriteFile(

                  Pipe[i].hPipeInst,

                  Pipe[i].chBuf,

                  Pipe[i].cbToWrite,

                  &cbBytes,

                  &Pipe[i].oOverlap);

              /* The write operation completed successfully. */

              if (fSuccess &&

                      cbBytes == Pipe[i].cbToWrite) {

                  Pipe[i].fPendingIO = FALSE;

                  Pipe[i].dwState = READING_STATE;

                  continue;

              }

              /* The write operation is still pending. */

              dwErr = GetLastError();

              if (! fSuccess &&

                      (dwErr == ERROR_IO_PENDING)) {

                  Pipe[i].fPendingIO = TRUE;

                  continue;

              }

              /* An error occurred; disconnect from the client. */

              DisconnectAndReconnect(i);

              break;

          default:

              MyErrExit("invalid pipe state");

      }

  }

  return 0;

}

/*

 * DisconnectAndReconnect(DWORD)

 * This function is called when an error occurs or when the client

 * closes its handle to the pipe. Disconnect from this client, and then

 * call ConnectNamedPipe to wait for another client to connect.

 */

VOID DisconnectAndReconnect(DWORD i) {

  /* Disconnect the pipe instance. */

  if (! DisconnectNamedPipe(Pipe[i].hPipeInst) )

      MyErrExit("DisconnectNamedPipe");

  /* Call a subroutine to connect to the new client. */

  Pipe[i].fPendingIO = ConnectToNewClient(

      Pipe[i].hPipeInst,

      &Pipe[i].oOverlap);

  Pipe[i].dwState = Pipe[i].fPendingIO ?

      CONNECTING_STATE : /* still connecting   */

      READING_STATE;     /* ready to read      */

}

/*

 * ConnectToNewClient(HANDLE, LPOVERLAPPED)

 * This function is called to start an overlapped connect operation. It

 * returns TRUE if an operation is pending or FALSE if the connection

 * has been completed.

 */

BOOL ConnectToNewClient(HANDLE hPipe, LPOVERLAPPED lpo) {

  BOOL fConnected, fPendingIO = FALSE;

  /* Start an overlapped connection for this pipe instance. */

  fConnected = ConnectNamedPipe(hPipe, lpo);

  /* Overlapped ConnectNamedPipe should return FALSE. */

  if (fConnected)

      MyErrExit("ConnectNamedPipe");

  switch (GetLastError()) {

      /* The overlapped connection in progress. */

      case ERROR_IO_PENDING:

          fPendingIO = TRUE;

          break;

      /* Client is already connected, so signal an event. */

      case ERROR_PIPE_CONNECTED:

          if (SetEvent(lpo->hEvent))

              break;

      /* If an error occurs during the connect operation... */

      default:

          MyErrExit("ConnectNamedPipe");

  }

  return fPendingIO;

}


 Server Using Completion Routines

The ReadFileEx and WriteFileEx functions provide another form of overlapped I/O. Unlike the overlapped ReadFile and WriteFile functions, which use an event object to signal completion, the extended functions specify a completion routine. A completion routine is a function that is queued for execution when the read or write operation is done. The completion routine is not executed until the thread that called ReadFileEx and WriteFileEx enters an alertable wait by calling one of the extended wait functions: WaitForSingleObjectEx, WaitForMultipleObjectsEx, or SleepEx. These functions are like the other wait functions in that they return when a specified object is in the signaled state or when a time-out interval has elapsed. However, these functions can also perform an alertable wait, which occurs when their fAlertable parameter is set to TRUE. In an alertable wait, the functions also return when a ReadFileEx or WriteFileEx completion routine is queued for execution. A server process can use the extended functions to perform a sequence of read and write operations for each client that connects to it. Each read or write operation in the sequence specifies a completion routine, and each completion routine initiates the next step in the sequence.

Like the previous example, this example is a single-threaded server process that creates a message-type pipe and uses overlapped operations. The server process differs in that it uses the extended functions ReadFileEx and WriteFileEx to perform overlapped I/O. Unlike the overlapped ReadFile and WriteFile functions, which signal an event object upon completion, the extended functions specify a completion routine, which is queued for execution when the operation is finished. The server process uses the WaitForSingleObjectEx function, which performs an alertable wait that returns when a completion routine is ready to execute. The wait function also returns when an event object is signaled, which in this example indicates that the overlapped ConnectNamedPipe operation has finished (a new client has connected).

Initially, the server process creates a single instance of the pipe and starts an overlapped ConnectNamedPipe operation. When a client connects, the server allocates a structure to provide storage for that pipe instance and then calls the ReadFileEx function to launch a sequence of I/O operations to handle communications with the client. Each operation specifies a completion routine that performs the next operation in the sequence. The sequence terminates when the client is disconnected and the pipe instance closed. After starting the sequence of operations for the new client, the server creates another pipe instance and waits for the next client to connect.

The parameters of the ReadFileEx and WriteFileEx functions specify a completion routine and a pointer to an OVERLAPPED structure. This pointer is later passed to the completion routine in its lpOverLap parameter. Because the OVERLAPPED structure points to the first member in the structure allocated for each pipe instance, the completion routine can use its lpOverLap parameter to access the structure for the pipe instance.

To avoid duplication, the listing for the ConnectToNewClient subroutine is not shown; it is identical to the one used by the overlapped server process in the previous section.

#include <windows.h>

typedef struct {

  OVERLAPPED oOverlap;

  HANDLE hPipeInst;

  CHAR chBuf[BUFSIZE];

  DWORD cbToWrite;

} PIPEINST, *LPPIPEINST;

BOOL CreateAndConnectInstance();

BOOL ConnectToNewClient(HANDLE, LPOVERLAPPED);

VOID GetDataToWriteToClient(LPPIPEINST);

VOID DisconnectAndClose(LPPIPEINST);

VOID CompletedWriteRoutine(DWORD, DWORD, LPOVERLAPPED);

VOID CompletedReadRoutine(DWORD, DWORD, LPOVERLAPPED);

HANDLE hPipe;

DWORD main(VOID) {

  HANDLE hConnectEvent;

  OVERLAPPED oConnect;

  LPPIPEINST lpPipeInst;

  DWORD dwWait, cbBytes;

  BOOL fSuccess, fPendingIO;

  /* Create one event object for the connect operation. */

  hConnectEvent = CreateEvent(

      NULL,    /* no security attr.         */

      TRUE,    /* manual reset event        */

      TRUE,    /* initial state = signaled  */

      NULL);   /* unnamed event object      */

  if (hConnectEvent == NULL)

      MyErrExit("CreateEvent");

  oConnect.hEvent = hConnectEvent;

  /*

   * Call a subroutine to create one instance, and wait for

   * the client to connect.

   */

  fPendingIO = CreateAndConnectInstance(&oConnect);

  while (1) {

   /*

    * Wait for a client to connect, or for a read or write

    * operation to be completed, which causes a completion

    * routine to be queued for execution.

    */

      dwWait = WaitForSingleObjectEx(

          hConnectEvent,  /* event object to wait for */

          INFINITE,       /* waits indefinitely       */

          TRUE);          /* alertable wait enabled   */

      switch (dwWait) {

        /* The wait is satisfied by a completed connect operation. */

          case 0:

              /* If an operation is pending, get the result of the

               * connect operation.

               */

              if (fPendingIO) {

                  fSuccess = GetOverlappedResult(

                      hPipe,     /* pipe handle          */

                      &oConnect, /* OVERLAPPED structure */

                      &cbBytes,  /* bytes transferred    */

                      FALSE);    /* does not wait        */

                  if (! fSuccess)

                      MyErrExit("ConnectNamedPipe");

              }

              /* Allocate storage for this instance. */

              lpPipeInst = (LPPIPEINST) GlobalAlloc(

                  GPTR, sizeof(PIPEINST));

              if (lpPipeInst == NULL)

                  MyErrExit("GlobalAlloc lpPipeInst");

              lpPipeInst->hPipeInst = hPipe;

              /*

               * Start the read operation for this client.

               * Note that this same routine is later used as a

               * completion routine after a write operation.

               */

              lpPipeInst->cbToWrite = 0;

              CompletedWriteRoutine(0, 0,

                  (LPOVERLAPPED) lpPipeInst);

              /* Create new pipe instance for the next client. */

              fPendingIO = CreateAndConnectInstance(

                  &oConnect);

              break;

        /*

         * The wait is satisfied by a completed read or write

         * operation. This allows the system to execute the

         * completion routine.

         */

          case WAIT_IO_COMPLETION:

              break;

        /* An error occurred in the wait function. */

          default:

              MyErrExit("WaitForSingleObjectEx");

      }

  }

  return 0;

}

/*

 * CompletedWriteRoutine(DWORD, DWORD, LPOVERLAPPED)

 * This routine is called as an I/O completion routine after writing to

 * the pipe, or when a new client has connected to a pipe instance. It

 * starts another read operation.

 */

VOID CompletedWriteRoutine(DWORD dwErr, DWORD cbWritten,

    LPOVERLAPPED lpOverLap) {

  LPPIPEINST lpPipeInst;

  BOOL fRead = FALSE;

  /* lpOverlap points to storage for this instance. */

  lpPipeInst = (LPPIPEINST) lpOverLap;

  /*

   * The write operation has finished, so read the next request (if

   * there is no error).

   */

  if ((dwErr == 0) && (cbWritten == lpPipeInst->cbToWrite))

      fRead = ReadFileEx(

          lpPipeInst->hPipeInst,

          lpPipeInst->chBuf,

          BUFSIZE,

          (LPOVERLAPPED) lpPipeInst,

          (LPOVERLAPPED_COMPLETION_ROUTINE) CompletedReadRoutine);

  /* Disconnect if an error occurred. */

  if (! fRead)

      DisconnectAndClose(lpPipeInst);

}

/*

 * CompletedReadRoutine(DWORD, DWORD, LPOVERLAPPED)

 * This routine is called as an I/O completion routine after reading a

 * request from the client. It gets data and writes it to the pipe.

 */

VOID CompletedReadRoutine(DWORD dwErr, DWORD cbBytesRead,

    LPOVERLAPPED lpOverLap) {

  LPPIPEINST lpPipeInst;

  BOOL fWrite = FALSE;

  /* lpOverlap points to storage for this instance. */

  lpPipeInst = (LPPIPEINST) lpOverLap;

  /*

   * The read operation has finished, so write a response (if no

   * error occurred).

   */

  if ((dwErr == 0) && (cbBytesRead != 0)) {

      GetDataToWriteToClient(lpPipeInst);

      fWrite = WriteFileEx(

          lpPipeInst->hPipeInst,

          lpPipeInst->chBuf,

          lpPipeInst->cbToWrite,

          (LPOVERLAPPED) lpPipeInst,

          (LPOVERLAPPED_COMPLETION_ROUTINE) CompletedWriteRoutine);

  }

  /* Disconnect if an error occurred. */

  if (! fWrite)

      DisconnectAndClose(lpPipeInst);

}

/*

 * DisconnectAndClose(LPPIPEINST)

 * This routine is called when an error occurs or when the client closes

 * its handle to the pipe.

 */

VOID DisconnectAndClose(LPPIPEINST lpPipeInst)

{

  /* Disconnect the pipe instance. */

  if (! DisconnectNamedPipe(lpPipeInst->hPipeInst) )

      MyErrExit("DisconnectNamedPipe");

  /* Close the handle to the pipe instance. */

  CloseHandle(lpPipeInst->hPipeInst);

  /* Release the storage for the pipe instance. */

  if (lpPipeInst != NULL)

      GlobalFree(lpPipeInst);

}

/*

 * CreateAndConnectInstance(LPOVERLAPPED)

 * This function creates a pipe instance and connects to the new client.

 * It returns TRUE if the connect operation is pending and FALSE if

 * the connection has been completed.

 */

BOOL CreateAndConnectInstance(LPOVERLAPPED lpoOverlap) {

  LPTSTR lpszPipename = "\\\\.\\pipe\\mynamedpipe";

  hPipe = CreateNamedPipe(

      lpszPipename,             /* pipe name           */

      PIPE_ACCESS_DUPLEX |      /* read/write access   */

      FILE_FLAG_OVERLAPPED,     /* overlapped mode     */

      PIPE_TYPE_MESSAGE |       /* message-type pipe   */

      PIPE_READMODE_MESSAGE |   /* message read mode   */

      PIPE_WAIT,                /* blocking mode       */

      PIPE_UNLIMITED_INSTANCES, /* unlimited instances */

      BUFSIZE,                  /* output buffer size  */

      BUFSIZE,                  /* input buffer size   */

      PIPE_TIMEOUT,             /* client time-out     */

      NULL);                    /* no security attr.   */

  if (hPipe == INVALID_HANDLE_VALUE)

      MyErrExit("CreatePipe");

  /* Call a subroutine to connect to the new client. */

  return ConnectToNewClient(hPipe, lpoOverlap);

}


 Named Pipe Client Process

A client process uses the CreateFile function to open a handle to a named pipe. If the pipe exists but all of its instances are busy, CreateFile returns FALSE and the GetLastError function returns ERROR_PIPE_BUSY. When this happens, the client process uses the WaitNamedPipe function to wait for an instance of the pipe to be available.

CreateFile fails if the access specified is incompatible with the access specified (duplex, outbound, or inbound) when the server created the pipe. For a duplex pipe (read/write), the client can specify read, write, or read/write access; for an outbound pipe (server write only), the client must specify read only; and for an inbound pipe (server read only), the client must specify write only.

The handle returned by CreateFile defaults to byte-read mode, blocking-wait mode, overlapped mode disabled, and write-through mode disabled. The client process can use CreateFile to enable overlapped mode by specifying FILE_FLAG_OVERLAPPED or to enable write-through mode by specifying FILE_FLAG_WRITE_THROUGH. The client can use the SetNamedPipeHandleState function to enable nonblocking mode by specifying PIPE_WAIT or to enable message-read mode by specifying PIPE_READMODE_MESSAGE.

The following example shows a client process that opens a named pipe, sets the pipe handle to message-read mode, uses WriteFile to send a request to the server, and uses ReadFile to read the server's reply. This client process can be used with any of the message-type servers shown in the previous sections. With a byte-type server, however, this client process fails when it calls SetNamedPipeHandleState to change to message-read mode. Because the client is reading from the pipe in message-read mode, it is possible for the ReadFile operation to return FALSE after reading a partial message. This happens when the message is larger than the read buffer. In this situation, GetLastError returns ERROR_MORE_DATA, and the remainder of the message is read by additional calls to ReadFile.

#include <windows.h>

 DWORD main(int argc, char *argv[]) {

  HANDLE hPipe;

  LPVOID lpvMessage;

  CHAR chBuf[512];

  BOOL fSuccess;

  DWORD cbRead, cbWritten, dwMode;

  LPTSTR lpszPipename = "\\\\.\\pipe\\mynamedpipe";

  /* Try to open a named pipe; wait for it, if necessary. */

  while (1) {

      hPipe = CreateFile(

          lpszPipename,   /* pipe name           */

          GENERIC_READ |  /* read/write access   */

          GENERIC_WRITE,

          0,              /* no sharing          */

          NULL,           /* no security attr.   */

          OPEN_EXISTING,  /* opens existing pipe */

          0,              /* default attributes  */

          NULL);          /* no template file    */

      /* Break if the pipe handle is valid. */

      if (hPipe != INVALID_HANDLE_VALUE)

          break;

      /* Exit if an error other than ERROR_PIPE_BUSY occurs. */

      if (GetLastError() != ERROR_PIPE_BUSY)

          MyErrExit("Could not open pipe");

      /* All pipe instances are busy, so wait for 20 seconds. */

      if (! WaitNamedPipe(lpszPipename, 20000) )

          MyErrExit("Could not open pipe");

  }

  /* The pipe connected; change to message-read mode. */

  dwMode = PIPE_READMODE_MESSAGE;

  fSuccess = SetNamedPipeHandleState(

      hPipe,    /* pipe handle          */

      &dwMode,  /* new pipe mode        */

      NULL,     /* don't set max. bytes */

      NULL);    /* don't set max. time  */

  if (! fSuccess)

      MyErrExit("SetNamedPipeHandleState");

  /* Send a message to the pipe server. */

  lpvMessage = (argc > 1) ? argv[1] : "default message";

  fSuccess = WriteFile(

      hPipe,                  /* pipe handle     */

      lpvMessage,             /* message         */

      strlen(lpvMessage) + 1, /* message length  */

      &cbWritten,             /* bytes written   */

      NULL);                  /* not overlapped  */

  if (! fSuccess)

      MyErrExit("WriteFile");

  do {

      /* Read from the pipe. */

      fSuccess = ReadFile(

          hPipe,    /* pipe handle              */

          chBuf,    /* buffer to receive reply  */

          512,      /* size of buffer           */

          &cbRead,  /* number of bytes read     */

          NULL);    /* not overlapped           */

      if (! fSuccess && GetLastError() != ERROR_MORE_DATA)

          break;

      /* Reply from the pipe is written to STDOUT. */

      if (! WriteFile(GetStdHandle(STD_OUTPUT_HANDLE),

              chBuf, cbRead, &cbWritten, NULL))

          break;

  } while (! fSuccess); /* repeat loop if ERROR_MORE_DATA */

  CloseHandle(hPipe);

  return 0;

}


 Transactions on Named Pipes

A named pipe transaction is a client-server communication that combines a write operation and a read operation into a single network operation. A transaction can be used only on a duplex, message-type pipe. Transactions improve the performance of network communications between a client and a remote server. Processes can use the TransactNamedPipe and CallNamedPipe functions to perform named pipe transactions.

TransactNamedPipe is typically used by a client process to write a request message to the named pipe server and read the server's response message. The client process must specify GENERIC_READ | GENERIC_WRITE access when it opens its pipe handle by calling the CreateFile function. Then, the client process sets the pipe handle to message-read mode by calling the SetNamedPipeHandleState function. If the read buffer specified in the call to TransactNamedPipe is not large enough to hold the entire message written by the server, the function returns FALSE and GetLastError returns ERROR_MORE_DATA. The client can read the remainder of the message by calling either the ReadFile, ReadFileEx, or PeekNamedPipe function.

TransactNamedPipe is typically called by client processes, but can also be used by a server process.

The following example shows a client process using TransactNamedPipe. The example assumes that the client process has used CreateFile to connect to the pipe and SetNamedPipeHandleState to set the pipe handle's read mode, as shown in the client process example in the preceding section.

fSuccess = TransactNamedPipe(

    hPipe,               /* pipe handle             */

    lpszWrite,           /* message to server       */

    strlen(lpszWrite)+1, /* message length          */

    chReadBuf,           /* buffer to receive reply */

    512,                 /* size of read buffer     */

    &cbRead,             /* number of bytes read    */

    NULL);               /* not overlapped          */

/*

 * Exit if an error occurs, unless the error indicates there is more

 * data in the message.

 */

if (! fSuccess && (GetLastError() != ERROR_MORE_DATA))

    MyErrExit("TransactNamedPipe");

while(1) {

    /* Data from the pipe is written to STDOUT. */

    if (! WriteFile(GetStdHandle(STD_OUTPUT_HANDLE),

            chReadBuf, cbRead, &cbWritten, NULL) )

        break;

    /* Break if TransactNamedPipe or ReadFile is successful. */

    if (fSuccess)

        break;

    /* Read from the pipe if there is more data in the message.*/

    fSuccess = ReadFile(

        hPipe,      /* pipe handle              */

        chReadBuf,  /* buffer to receive reply  */

        512,        /* size of buffer           */

        &cbRead,    /* number of bytes read     */

        NULL);      /* not overlapped           */

    /* Exit if an error other than ERROR_MORE_DATA occurs. */

    if (! fSuccess && (GetLastError() != ERROR_MORE_DATA))

        break;

}

A client process uses CallNamedPipe to combine the CreateFile, WaitNamedPipe (if necessary), TransactNamedPipe, and CloseHandle operations into a single function. Because the pipe handle is closed before the function returns, any additional bytes in the message are lost if the message is larger than the speciffied size of the read buffer. The following example shows the use of CallNamedPipe.

/* Combines connect, wait, write, read, and close operations. */

fSuccess = CallNamedPipe(

    lpszPipename,        /* pipe name               */

    lpszWrite,           /* message to server       */

    strlen(lpszWrite)+1, /* message length          */

    chReadBuf,           /* buffer to receive reply */

    512,                 /* size of read buffer     */

    &cbRead,             /* number of bytes read    */

    20000);              /* waits for 20 seconds    */

if (fSuccess || GetLastError() == ERROR_MORE_DATA) {

    /* Data from the pipe is written to STDOUT. */

    WriteFile(GetStdHandle(STD_OUTPUT_HANDLE),

        chReadBuf, cbRead, &cbWritten, NULL);

    /*

     * The pipe is closed, so no more bytes can be read from the

     * message.

     */

    if (! fSuccess)

        printf("\n...extra data in message was lost\n");

}


 Pipe Functions

Following are the functions used with pipes.

CallNamedPipe
ConnectNamedPipe
CreateNamedPipe
CreatePipe
DisconnectNamedPipe
GetNamedPipeHandleState
GetNamedPipeInfo
PeekNamedPipe
SetNamedPipeHandleState
TransactNamedPipe
WaitNamedPipe


 Power Management

This overview describes the power management functions and messages, and explains how to use them in applications and installable drivers.


 About Power Management

The Windows operating system uses power management to reduce the power consumption of a computer and the attached devices. Windows works in conjunction with the computer and its devices to monitor system operation and shut down devices or the computer itself when idle. To help applications and installable drivers take advantage of power management and to ensure that no data is lost when a device or the computer is shut down, Windows provides functions and messages that reveal the system power status and notify of power management events.


 About System Power Status

System power status indicates the source of power for a computer, that is, whether it uses a system battery or AC power. For computers that use batteries, the status also indicates how much battery life remains and whether the battery is currently charging.

You can retrieve the system power status by using the GetSystemPowerStatus function. This copies information about the power supply and battery status to a SYSTEM_POWER_STATUS structure. This structure identifies whether the system has a battery, and if it does, whether the battery is being used and the percentage of charge remaining.

Applications and installable drivers typically use the system power status to make decisions about whether to continue operation. For example, an application that is beginning a lengthy operation may check the status to determine whether enough battery power exists to complete the operation.

If power is low, an application can request user intervention or request that the system to shut itself down. You can suspend the operation of the system by using the SetSystemPowerState function. This generates a power management event that, if approved by all applications and drivers in the system, shuts the system down until the user restores power. Even if a computer uses AC power, an application that determines that the system is idle and can request that the system shut itself down to save power.


 Power Management Events

A power management event is a change in either the system power status or the operational mode of a device or the computer. Because these events can affect the operation of applications and installable drivers and can lead to loss of data, Windows notifies all applications and installable drivers by broadcasting a WM_POWERBROADCAST message for each event.

A system power status event occurs when there is a change in the power supply or in the system battery status. For example, the system broadcasts a message whenever the user switches from battery to AC power or vice versa. The system also broadcasts a message when remaining battery power slips below 10%.

An operational mode event occurs when there is a change in power consumption, such as the system shutting itself down or the user turning the system back on. Some changes in operational mode can cause loss of data if applications and drivers do not prepare for them. Therefore, the system broadcasts messages about these changes before they actually occur. For example, if the system determines that it is idle, it broadcasts a message notifying applications and drivers that it is about to suspend operation and shut itself down to save power. The applications and drivers can prepare for this suspension by closing files and saving data that may otherwise be lost when power is shut off.

The system has three ways to shut itself down. It can suspend operation, place operation on standby, or carry out critical suspension. An application can also shut the system down by using the SetSystemPowerState function to suspend operation.

When system operation is suspended, power to all devices is lost. The WM_POWERBROADCAST messages, sent immediately before suspension, allow device drivers to save the state of the device. For many devices (but not all), saving the state means the driver can restore the state when power is eventually restored, allowing the device to continue operation as if power was never lost.

When the system goes into standby, power to devices may be reduced but no state is lost and interrupts continue to be processed. For example, a hard disk drive on standby may stop spinning but state information is preserved and the drive responds to requests for access. Standby operation is transparent to applications because the corresponding WM_POWERBROADCAST messages are never sent to them. Instead only device drivers receive and process these messages.

When the system carries out a critical suspension, battery power is too low to let the computer continue to run. Unlike for suspended and standby operations, the system does not notify applications and drivers before carrying out a critical suspension. This means data may be lost.

When system operation is restored after having been suspended or placed on standby, the system notifies all applications and drivers. It also identifies how the system was previously shut down so that the application or driver can take appropriate steps to restore its data and continue its own operation.


 Power Messages

The system sends power messages to all applications and installable drivers whenever a power management event occurs or whenever an application calls the SetSystemPowerState function to suspend operation. The system sends these messages through the WM_POWERBROADCAST message, setting the wParam parameter to the message type. For example, the message type, PBT_APMPOWERSTATUSCHANGE, indicates a system power status change message.

The system sends a PBT_APMQUERYSUSPEND or PBT_APMQUERYSTANDBY message to request permission to suspend system operation or place it on stanmdby. The system expects each application and driver to determine whether the requested event should occur and to return TRUE or FALSE indicating this decision. Any application or driver can deny the request and prevent it from occurring.

The system sends a PBT_APMSUSPEND or PBT_APMSTANDBY message immediately before suspending operation or placing it on standby. This gives applications and drivers one last chance to prepare for the event before it occurs. In many cases, the system sends these messages without requesting permission to do so. This happens, for example, if an application forces suspension with the SetSystemPowerState function.

The standby messages (PBT_APMQUERYSTANDBY, PBT_APMQUERYSTANDBYFAILED, PBT_APMRESUMESTANDBY, and PBT_APMSTANDBY) are not set to applications. these are intended to be sent to low-level drivers and system components.

The system sends the PBT_APMQUERYSUSPENDFAILED or PBT_APMQUERYSTANDBYFAILED message whenever a requested event is denied. These messages are intended to notify applications and drivers to continue operation as usual.

The system sends the PBT_APMRESUMESUSPEND, PBT_APMRESUMESTANDBY, or PBT_APMRESUMECRITICAL message when system operation has been restored.

Note  The WM_POWER message, previously available to applications and drivers for use with power management, is maintained for backward compatibility. All current applications and installable drivers should use and process the WM_POWERBROADCAST message instead.


 Power Management Reference

This section describes the power management functions, messages, and structures.


 Power Management Functions

This section describes the power management functions.

GetSystemPowerStatus
SetSystemPowerState


 Power Management Messages

This section descibes the power management messages.

PBT_APMPOWERSTATUSCHANGE
PBT_APMQUERYSTANDBY
PBT_APMQUERYSTANDBYFAILED
PBT_APMQUERYSUSPEND
PBT_APMQUERYSUSPENDFAILED
PBT_APMRESUMECRITICAL
PBT_APMRESUMESTANDBY
PBT_APMRESUMESUSPEND
PBT_APMSTANDBY
PBT_APMSUSPEND
WM_POWERBROADCAST


 Power Management Structure

This section describes the power management structure.

SYSTEM_POWER_STATUS


 Processes and Threads

A process is an executing application that consists of a private virtual address space, code, data, and other operating system resources, such as files, pipes, and synchronization objects that are visible to the process. A process also contains one or more threads that run in the context of the process. A thread is the basic entity to which the operating system allocates CPU time. A thread can execute any part of the application's code, including a part currently being executed by another thread. All threads of a process share the virtual address space, global variables, and operating system resources of the process.

This overview describes processes and threads, and explains how to create and use them.


 About Processes and Threads

An application written for Microsoft® Windows® can consist of more than one process, and a process can consist of more than one thread. The Microsoft® Win32® application program interface (API) supports multitasking, which creates the effect of simultaneous execution of multiple processes and threads.


 Multitasking

A process is a program that is loaded into memory and prepared for execution. Each process has a private virtual address space. A process consists of the code, data, and other system resources — such as files, pipes, and synchronization objects — that are accessible to the threads of the process. Each process is started with a single thread, but additional independently executing threads can be created.

A thread can execute any part of the program's code, including a part executed by another thread. Threads are the basic entity to which the operating system allocates CPU time. Each thread maintains a set of structures for saving its context while waiting to be scheduled for processing time. The context includes the thread's set of machine registers, the kernel stack, a thread environment block, and a user stack in the address space of the thread's process. All threads of a process share the virtual address space and can access the global variables and system resources of the process.

A multitasking operating system divides the available CPU time among the threads that need it. In Windows, the Win32 API is designed for preemptive multitasking; this means that the system allocates small slices of CPU time among the competing threads. The currently executing thread is suspended when its time slice elapses, allowing another thread to run. When the system switches from one thread to another, it saves the context of the suspended thread and restores the saved context of the next thread in the queue.

Because each time slice is small (approximately 20 milliseconds), it appears that multiple threads are executing at the same time. This is actually the case on multiprocessor systems, where the executable threads are distributed among the available processors. On a single processor system, however, using multiple threads does not result in more instructions being executed. In fact, the system can slow down if it is forced to keep track of too many threads.

To the user, the advantage of multitasking is the ability to have several applications open and working at the same time. For example, a user can edit a file with one application while another application is printing or recalculating a spreadsheet.

To the application developer, the advantage of multitasking is the ability to create applications that use more than one process and to create processes that use more than one thread of execution. For example, you can have one thread that handles interactions with the user (keyboard and mouse input), while other threads with lower priority perform the other work of the process. The higher priority of the input thread makes the program responsive to the user, while the other threads ensure that the processor can be used efficiently during the slices of time between keystrokes.


 When to Use Multitasking

Any thread of any process can use the CreateThread and CreateProcess functions to create additional threads or processes. An application might use multiple processes for functions that require a private address space and private resources, to protect them from the activities of other threads. Functions that are to be distributed as separate executable modules but that can be integrated to form a single application, can benefit from the multiprocess approach.

It is useful for a process to have multiple threads in situations where the application has several tasks to run concurrently. For example, an application that opens more than one window can have a separate thread perform the work of the application in each window. Multiple threads can be a convenient way to structure a program that performs several similar or identical tasks. For example, a named pipe server can create a thread to handle communications with each client process that attaches to the pipe. Other examples of using multiple threads are processes that do the following:

•	Handle input for multiple windows.

•	Manage input from several communications devices.

•	Need to distinguish among tasks of varying priority. For example, a high-priority thread handles time-critical tasks, and a low-priority thread performs other tasks.

It is typically more efficient for an application to implement multitasking by distributing tasks among the threads of a single process, rather than by creating multiple processes, for the following reasons:

•	The system can create and execute threads more quickly than it can create processes, primarily because the code for threads has already been mapped into the address space of the process, while the code for a new process must be loaded.

•	All threads of a process share the same address space and can access the process's global variables, which can simplify communications between threads.

•	All threads of a process can use open handles to resources such as files and pipes.

For both multiple threads and multiple processes, there are costs and dangers to be considered. The system consumes memory for the structures required by both processes and threads. Keeping track of a large number of threads consumes CPU time. With multiple threads accessing the same resources, you must synchronize the threads to avoid conflicts. This is true for system resources (such as communications ports or disk drives), handles to resources shared by multiple processes (such as file or pipe handles), or the resources of a single process (such as global variables accessed by multiple threads). Failure to synchronize multiple threads properly (in the same or in different processes) can lead to program problems such as deadlock and race conditions. The Win32 API provides a set of synchronization objects and functions you can use to coordinate multiple threads. For more information about synchronization, see Synchronizing Execution of Multiple Threads and Synchronization.

The Win32 API also provides alternative ways to execute multiple tasks that, in some cases, make multithreaded processes unnecessary. The most significant of these are overlapped I/O and the ability to wait for multiple events.

Overlapped I/O enables a single thread to initiate multiple time consuming I/O requests that can run concurrently. This asynchronous I/O can be performed on files, pipes, serial communications devices, or tape devices. For more information about files, see Files. For more information about pipes, see Pipes. For more information about serial communication devices, see Communications. For more information about tape devices, see Tape Backup.

Waiting for multiple events enables a single thread to block its execution while waiting for any one of several events to occur. This is much more efficient than using multiple threads, each waiting for a single event, or using a single thread that consumes CPU time by continually checking for an event of interest. For more information about waiting for multiple events, see Synchronization.


 Scheduling

The system scheduler controls multitasking by determining which of the competing threads receives the next slice of the processor's time. Each time slice consists of a fixed number of clock ticks. The Windows scheduler is preemptive, gaining control whenever a clock interrupt occurs and decrementing the count of clock ticks remaining in the time slice of the currently executing thread. If the count goes to zero, the scheduler determines which thread runs next. The scheduler maintains a queue of executable threads at each priority level. When the highest priority is shared by more than one executable thread, the next time slice goes to the thread at the head of the priority queue. The thread that just finished executing is placed at the end of the queue of threads with its priority. Threads that are suspended or blocked (for example, waiting for a semaphore object or waiting for input) are not executable, so until they become unblocked, the scheduler does not allocate any processor time to them, regardless of their priority. When the scheduler awards the next time slice to a different thread, the context of the currently executing thread is saved, and the machine state is set according to the context of the next executable thread.


 Scheduling Priorities

The scheduling priority of each thread is determined by the following criteria:

•	The priority class of its process (high, normal, or idle)

•	The priority level of the thread within the priority class of its process (lowest, below normal, normal, above normal, highest)

•	The dynamic priority boost, if any, the system applies to the thread's base priority

By default, the priority class of a process is set to normal. The CreateProcess function allows a parent process to specify the priority class of its child processes. Use SetPriorityClass to change the priority class of a process and GetPriorityClass to determine the current priority class of a process.

There are five priority levels within each priority class. The levels range from lowest (−2) to highest (2). All threads are started with normal (0) priority. The SetThreadPriority function enables you to change the priority level of a thread to any of the five levels. Use the GetThreadPriority function to determine the current priority level of a thread.

The base priority of each thread is the thread's priority level within the priority class of its process. The scheduler uses this base priority to determine a thread's dynamic priority, which it uses to make scheduling decisions. A thread's dynamic priority is never less than its base priority. The scheduler raises and lowers the dynamic priority of a thread to enhance its responsiveness when significant things happen to the thread. For example, whenever a window receives input (such as timer messages, mouse move messages, keyboard input), the scheduler boosts the priorities of all threads within the process that owns the window. In some cases, the dynamic priority of a waiting thread is raised when a wait is satisfied. For example, a wait associated with disk or keyboard I/O results in a dynamic boost when the input occurs.

After raising a thread's dynamic priority, the scheduler reduces that priority by one level each time the thread completes a time slice, until the thread drops back to its base priority.

In addition to these dynamic priority boosts, the scheduler raises the priority class of the process associated with the foreground window, so it is greater than or equal to the priority class of any background processes. The process's priority class returns to its original setting when it is no longer in the foreground. A user can always make a given window lose the foreground priority boost by clicking on another window or by using the ALT+TAB or CTRL+ESC key combination.

The priority classes are intended to be used as follows.

Priority	Meaning
HIGH_PRIORITY_CLASS	Indicates a process that performs time-critical tasks that must be executed immediately for it to run correctly. The threads of a high-priority class process preempt the threads of normal or idle priority class processes. An example is Windows Task List, which must respond quickly when called by the user, regardless of the load on the operating system. Use extreme care when using the high-priority class, because a high-priority class CPU-bound application can use nearly all available cycles.
IDLE_PRIORITY_CLASS	Indicates a process whose threads run only when the system is idle and are preempted by the threads of any process running in a higher priority class. An example is a screen saver. The idle priority class is inherited by child processes.
NORMAL_PRIORITY_CLASS	Indicates a normal process with no special scheduling needs.
REALTIME_PRIORITY_CLASS	Indicates a process that has the highest possible priority. The threads of a real-time priority class process preempt the threads of all other processes, including operating system processes performing important tasks. For example, a real-time process that executes for more than a very brief interval can cause disk caches not to flush or cause the mouse to be unresponsive.
Use the high-priority class with extreme care. If a thread runs at the highest priority level for extended periods, other threads in the system will be starved for CPU time. If several threads are set at high priority at the same time, the effect of the high priority is neutralized. The high-priority class should be reserved for threads that must respond to time critical events. If your application has a task that requires the high-priority class while most of its functions are normal priority, use SetPriorityClass to raise the priority class temporarily; then reduce it once the time-critical task has been completed. Another strategy is to create a high-priority process that is blocked most of the time, awakening only when the critical task is needed. The important point is that a thread should be high priority and executable only for a brief period, when it has time-critical work to perform.

Having selected a priority class for a multithreaded process, use SetThreadPriority to adjust the relative priority of its threads. A typical strategy is to use a higher priority level for the process's input thread, to ensure responsiveness to the user. Other threads, particularly those that are CPU intensive, can be set to a lower relative priority, to ensure that they can be preempted when necessary. However, if you have a higher priority thread waiting for a lower priority thread to complete some task, be sure to block the execution of the waiting thread (using a wait function, critical section, or the Sleep function) rather than having it iterate in a loop. Otherwise, the process will deadlock, because the lower priority thread will never get scheduled.


 Creating Threads

The CreateThread function creates a new thread for a process. The creating thread must specify the starting address of the code that the new thread is to execute. Typically, the starting address is the name of a function defined in the program's code. A process can have multiple threads simultaneously executing the same function. The function called by the thread takes a single 32-bit parameter and returns a doubleword result.

The following example illustrates the creation of a new thread that executes the locally defined ThreadFunc function.

DWORD ThreadFunc(LPDWORD lpdwParam) {

    printf("ThreadFunc:  thread parameter=%d\n", *lpdwParam);

    return 0;

}

DWORD main(VOID) {

    DWORD dwThreadId, dwThrdParam = 1;

    HANDLE hThread;

    hThread = CreateThread(

        NULL,                        /* no security attributes        */

        0,                           /* use default stack size        */

        (LPTHREAD_START_ROUTINE) ThreadFunc, /* thread function       */

        &dwThrdParam,                /* argument to thread function   */

        0,                           /* use default creation flags    */

        &dwThreadId);                /* returns the thread identifier */

    /* Check the return value for success. */

    if (hThread == NULL)

        ErrorExit("CreateThread error\n");

For simplicity, this example passes a pointer to dwThrdParam as an argument to the thread function. This could be a pointer to any type of data or structure, or it could be omitted altogether by passing a NULL pointer and deleting the references to the parameter in ThreadFunc. It is risky to pass the address of the local variable if the creating thread exits before the new thread, because the pointer becomes invalid. Instead, either pass dynamically allocated parameters or make the creating thread wait for the new thread to terminate. Data can also be passed from the creating thread to the new thread using global variables. With global variables, it is usually necessary to synchronize access by multiple threads. For more information about synchronizing, see Synchronizing Execution of Multiple Threads.

Using the thread function's argument to pass data to the new thread is particularly useful in processes where the main thread might create multiple threads to execute the same code. In this case, it is inconvenient to use global variables. For example, a process that enables the user to open several files at the same time can create a new thread for each file, with each of the threads executing the same thread function. The creating thread can pass as an argument the unique information (such as the filename) required by each instance of the thread function.

The creating thread can use the arguments to CreateThread to specify the following:

•	The security attributes for the handle of the new thread. These security attributes include an inheritance flag that determines whether the handle can be inherited by child processes. The security attributes also include a security descriptor, which the system uses to perform access checks on all subsequent uses of the thread's handle before access is granted. For more information about security attributes, see Security.

•	The initial stack size of the new thread. The thread's stack is allocated automatically in the memory space of the process; it can grow as needed and it is freed when the thread terminates.

•	A creation flag that enables you to create the thread in a suspended state. When suspended, the thread does not run until the ResumeThread function is called.

The handle returned by CreateThread has full-access rights to the new thread. Subject to security checks, the handle can be used in any of the Win32 API functions that accepts a handle to a thread object. The handle can be duplicated by DuplicateHandle, which enables you to create a thread handle with a subset of the access rights.

A thread can also be created with the CreateRemoteThread function. This is used by debugger processes to create a thread that runs in the address space of another process.


 Suspending Thread Execution

A thread can suspend and resume the execution of another thread using the SuspendThread and ResumeThread functions. While a thread is suspended, it is not scheduled for time on the processor.

SuspendThread is not particularly useful for synchronization because it does not control the point in the code at which the thread's execution is suspended. However, you might want to suspend a thread in a situation where you are confirming a user's input that would terminate the work of the thread. If confirmed, the thread is terminated; otherwise, it resumes.

If a thread is created in a suspended state, it does not begin to run until ResumeThread is called with a handle to the suspended thread. This can be useful for initializing the thread's state before it begins to run. See Using a Multithreaded Multiple Document Interface Application for an example that uses this method to modify the thread's priority before it can run. Suspending a thread at creation can be useful for one-time synchronization, because ResumeThread ensures that the suspended thread will resume running at the starting point of its code.

A thread can temporarily suspend its own execution for a specified interval by calling the Sleep or SleepEx functions. This is useful particularly in cases where the thread responds to user interaction, as it can delay execution long enough to enable the users to observe the results of their actions. During the sleep interval, the thread is not scheduled for time on the processor.


 Synchronizing Execution of Multiple Threads

To avoid conflicts, it is necessary to synchronize access by multiple threads to shared resources. Synchronization is also necessary to ensure that interdependent code is executed in the proper sequence.

The Win32 API provides a number of objects whose handles can be used to synchronize multiple threads. These objects include:

•	Synchronization objects: mutex, semaphore, and event handles

•	File handles

•	Named pipe handles

•	Console input buffer handles

•	Communication device handles

•	Process handles

•	Thread handles

The state of each of these objects is either signaled or not signaled. When a handle to any of these objects is specified by a call to one of the wait functions — WaitForSingleObject, WaitForMultipleObjects, WaitForSingleObjectEx, or WaitForMultipleObjectsEx — the execution of the calling thread is blocked until the state of the specified object is signaled. As with a suspended thread, a waiting thread consumes very little processor time.

Some of these objects are useful in blocking a thread until some event occurs. For example, a console input buffer handle is signaled when there is unread input, such as a keystroke or mouse button press. Process and thread handles are signaled when the process or thread terminates. This allows a process, for example, to create a child process and then block its own execution until the new process has terminated.

Other objects are useful in protecting shared resources from simultaneous access. For example, multiple threads can each have a handle to a mutex object. Before accessing a shared resource, the threads must call one of the wait functions to wait for the state of the mutex to be signaled. When the mutex becomes signaled, only one waiting thread is released to access the resource. The state of the mutex is immediately reset to not signaled so any other waiting threads remain blocked. When the thread is finished with the resource, it must set the state of the mutex to signaled to free other threads to access the resource.

For the threads of a single process, critical-section objects provide another (and slightly more efficient) means of synchronization. A critical section is used like a mutex to enable only one thread at a time to use the protected resource. A thread uses the EnterCriticalSection function to request ownership of a critical section. If it is already owned by another thread, the requesting thread is blocked. After it receives ownership, the thread is free to use the protected resource. The execution of the other threads of the process is not affected unless they attempt to enter the same critical section.

The WaitForInputIdle function makes a thread wait until a specified process is initialized and waiting for user input with no input pending. This can be useful for synchronizing parent and child processes, because CreateProcess returns without waiting for the child process to complete its initialization.

For more about critical sections and synchronization, see Synchronization.


 Thread Local Storage

All threads of a process share the virtual address space and the global variables of that process. Sometimes it is desirable to have static storage that is local to each thread. Of course, the local variables of a thread function are local to each thread that runs the function. But when a thread invokes another function, the static or global variables used by that function store the same value for all threads. With thread local storage (TLS), one thread allocates an index that can be used by any thread of the process to store and retrieve a different value for each thread.

The following is a typical TLS scenario:

1.	The TlsAlloc function is used during process or dynamic-link library (DLL) initialization to allocate a TLS index.

2.	Each thread that needs to use the TLS index allocates dynamic storage, then uses the TlsSetValue function to associate the index with a pointer to the dynamic storage.

3.	When a thread needs to access its storage, it specifies the TLS index in a call to the TlsGetValue function to retrieve the pointer.

4.	Each thread frees the dynamic storage that it has associated with a TLS index when it is no longer needed. When all threads have finished using a TLS index, the TlsFree function frees the index.

The constant TLS_MINIMUM_AVAILABLE defines the minimum number of TLS indexes available in each process. This minimum is guaranteed to be at least 64 for all systems.

TLS can be useful with DLLs. The DllEntryPoint function performs the initial TLS operations in the context of the process or thread the DLL is attaching to or detaching from. When the DLL attaches to a new process, the entry-point function calls TlsAlloc to allocate a TLS index for that process. When the DLL attaches to a new thread of that process, the entry-point function allocates dynamic memory for that thread and uses TlsSetValue to save private data to the index. The DLL stores the TLS index in a global variable that is private to each attached process. The functions of the DLL can use the TLS index in a call to TlsGetValue to access the private data for the calling thread.

For an example illustrating the use of thread local storage, see Using Thread Local Storage.


 Terminating a Thread

A thread runs until one of the following events occurs:

•	It calls the ExitThread function.

•	The thread function returns. This results in an implicit call to the ExitProcess function for a primary thread, or to the ExitThread function for other threads.

•	ExitProcess is invoked explicitly or implicitly by any thread of the process.

•	The TerminateThread function is called with a handle to the thread.

•	The TerminateProcess function is called with a handle to the thread's process.

When a thread terminates, the state of the thread object changes to signaled, releasing any other threads that had been waiting for the thread to terminate. Then its termination status changes from STILL_ACTIVE to the exit value of the thread.

If a thread is terminated by ExitThread, the entry-point function of all attached DLLs is invoked with a value indicating that the thread is detaching from the DLL. If a thread is terminated by ExitProcess, the DLL entry-point functions are invoked once, to indicate that the process is detaching. DLLs are not notified when a thread is terminated by TerminateThread or TerminateProcess. For more information about DLLs, see Dynamic-Link Libraries.

The GetExitCodeThread function returns the termination status of a thread. While a thread is executing, its termination status is STILL_ACTIVE. When a thread terminates, its termination status is the exit value of the thread, which is the value specified in the call to ExitThread, ExitProcess, or TerminateThread, or the value returned by the thread function.


 Multiple Threads and Graphics Device Interface Objects

To enhance performance, access to graphics device interface (GDI) objects (such as palettes, device contexts (DC), regions, and the like) is not serialized. This creates a potential danger for processes that have multiple threads sharing these objects. For example, if one thread deletes a GDI object while another thread is using it, the results are unpredictable. This danger can be avoided simply by not sharing GDI objects. If sharing is unavoidable (or desirable), the application must provide its own mechanisms for synchronizing access. For more information about synchronizing access, see Synchronizing Execution of Multiple Threads.


 Creating Processes

The CreateProcess function creates a new process, which runs independently of the creating process. The function provides two methods for identifying the program to be executed. The most common method is to specify the image file's path and filename. If the lpszImageName parameter is NULL, the program is identified in the lpszCommandLine parameter.

If CreateProcess succeeds, it returns a PROCESS_INFORMATION structure containing handles and identification numbers for the new process and its primary thread. The thread and process handles are created with full access rights, although access can be restricted if a security descriptor is specified.


 Inheritance

A child process can inherit a number of properties and resources from its parent process. You can also prevent a child process from inheriting anything from its parent process. The following can be inherited:

•	Any inheritable open handle returned by the CreateFile function. This includes handles to files, console input buffers, console screen buffers, named pipes, serial communication devices, and mailslots.

•	Inheritable open handles to process, thread, mutex, event, semaphore, named pipe, anonymous pipe, and file mapping objects.

•	Environment variables.

•	The current directory.

•	The console of parent process, unless the process is detached or a new console is created. A child console process also inherits the parent's standard handles, as well as access to the input buffer and the active screen buffer. For more about console processes, see Consoles and Character-Mode Support.

The fInheritHandles parameter of CreateProcess determines whether the inheritable handles of the parent process are inherited by the child process. The inheritability of the handles is specified in the functions used to create, open, or duplicate the handles. This allows a child process to inherit some of its parent's handles, while not inheriting others. For each of these object types there is a creation function (such as CreateProcess or CreateFile) that takes a security attributes argument via a flag determines whether the handle can be inherited. If the security attributes argument is NULL, the handle is not inherited.

Some of these objects have an open function (such as OpenMutex or OpenEvent) with an inherit flag parameter that determines inheritability.

Any of these handles can be duplicated using the DuplicateHandle function by which you can specify whether the handle can be inherited. This can be useful if a process has an inheritable open handle that you do not want to be inherited by the child process. In this case, use DuplicateHandle to open a noninheritable duplicate of the handle, then use the CloseHandle function to close the inheritable handle. DuplicateHandle can also open an inheritable duplicate of a noninheritable handle.

An inherited handle has the same value and access privileges as the parent process's handle. To use a handle, the child process must retrieve the handle and know the object to which it refers. For most handles, the parent process must communicate this information to the child process. This can be done using the command line or any of the other methods for interprocess communication (such as pipes or shared memory).

An inherited handle refers to the same object as the parent process's handle does. When one process changes the state of the object, the change affects both processes. With file handles, for example, if one process uses a handle to read from a file, the current file position is moved for all processes using the same handle.

A child process inherits the environment variables and current directory of its parent process by default. However, CreateProcess enables the parent process to specify a different current directory or block of environment variables. For more information about environment variables, see Environment Variables

The child process does not inherit the following:

•	Priority class.

•	Memory handles.

•	Pseudohandles, as in the handles returned by the GetCurrentProcess or GetCurrentThread function. These handles are valid only for the calling process. For more information about these functions, see Process and Thread Handles and Identifiers.

•	DLL module handles returned by the LoadLibrary function.

•	GDI or USER handles, such as HBITMAP or HMENU. Refer to WINDEF.H for a complete list of these handles.


 Environment Variables

Every process has an environment block that contains a set of environment variables and their values. The command processor for Microsoft® Windows NT™ (called CMD.EXE) provides the set command to display its environment block or to create new environment variables. Programs started by the command processor inherit the command processor's environment variables.

By default, a child process inherits the environment variables of its parent process. However, you can specify a different environment for the child process by creating a new environment block and passing a pointer to it as a parameter to the CreateProcess function.

The GetEnvironmentStrings function returns a pointer to the environment block of the calling process. This should be treated as a read-only block; do not modify it directly. Instead, use the SetEnvironmentVariable function to change an environment variable. The GetEnvironmentVariable function determines whether a specified variable is defined in the environment of the calling process, and, if so, what its value is. For more information about environments, see the examples in Changing Environment Variables.


 Setting Window Properties Using STARTUPINFO

A parent process can specify properties associated with the main window of its child process. A pointer to a STARTUPINFO structure is passed as a parameter to the CreateProcess function. The members of this structure can be used to specify more than a dozen different characteristics of the child's main window. The dwFlags member contains a bit field that determines whether the other members of the structure are used. This allows the creating process to specify values for any subset of the window properties. Default values are used for the properties not specified by dwFlags. The dwFlags member can also force a feedback cursor to be displayed during the initialization of the new process. A process can use the GetStartupInfo function to retrieve the STARTUPINFO structure specified when it was created.

For GUI processes, the STARTUPINFO structure specifies the default values to be used the first time the new process calls the CreateWindow and ShowWindow functions to create and display an overlapped window. The following default values can be specified:

•	The width and height, in pixels, of the window created by CreateWindow.

•	The location in screen coordinates of the window created by CreateWindow.

•	The nCmdShow parameter of ShowWindow.

For console processes, use the STARTUPINFO specifications only when a new console is created either by CreateProcess with CREATE_NEW_CONSOLE specified, or by the AllocConsole function. For more about console processes, see Consoles and Character-Mode Support. STARTUPINFO can specify the following console window properties:

•	The size, in character cells, and the location in screen coordinates of the new console window.

•	The size, in character cells, of the new console's screen buffer.

•	The text and background color attributes of the new console's screen buffer.

•	The title of the new console's window.


 Terminating a Process

A process terminates when one of the following occurs:

•	Any thread of the process calls the ExitProcess function.

•	The primary thread of the process returns. This results in an implicit call to ExitProcess.

•	The last thread of the process terminates.

•	The TerminateProcess function is called with a handle to the process.

When a process terminates, the following events occur:

•	Open handles to files or other resources are closed automatically. Note that the objects referenced by these handles exist until all open handles are closed. This means that an object remains valid after a process closes, if another process has a handle to it.

•	The state of the process object becomes signaled, satisfying any threads that are waiting for the process to terminate. For more about synchronization, see Synchronizing Execution of Multiple Threads.

•	The termination status of the process changes from STILL_ACTIVE to the exit value of the process.

Child processes are not automatically terminated when a parent process terminates.

ExitProcess is the preferred way to terminate a process, because it notifies all attached DLLs of the termination, and it ensures that all threads of the process are terminated. If a process is terminated by ExitProcess, the entry-point function of all attached DLLs is invoked with a value indicating that the process is detaching from the DLL. DLLs are not notified when a process is terminated by TerminateProcess. For more information about DLLs, see Dynamic-Link Libraries.

When a process is terminated by ExitProcess or TerminateProcess, all threads of the process are terminated immediately with no chance to run additional code (except for the DLL process detach code if ExitProcess is called). This means that the process does not execute code in termination handler blocks such as the finally block of the try-finally termination handler supported by Microsoft compilers. For more information about handlers, see Structured Exception Handling.

The primary thread of a process differs from the other threads of a process in that ExitProcess (rather than the ExitThread function) is invoked implicitly when a primary thread returns. Alternatively, the primary thread can avoid terminating other threads by explicitly calling ExitThread before it exits. In this case, one of the remaining threads explicitly calls ExitProcess, to ensure that all threads of the process are terminated. For example, it is possible for an attached DLL to create a thread that does not terminates unless ExitProcess is invoked.

ExitProcess can be invoked implicitly by the system. For most unhandled exceptions, the system's default action is to call ExitProcess. For console processes, ExitProcess is called by the default handler function that can be invoked when a CTRL+C or CTRL+BREAK signal is received. For more about console application, see Consoles and Character-Mode Support. Note that this default handling of console interrupt signals can terminate parent and child processes, because all processes attached to a console receive the signal. An interrupt signal received by a console window is propagated only to attached console processes. Detached processes and processes that have created new console windows are not affected. GUI processes are not affected by CTRL+C or CTRL+BREAK signals.

The GetExitCodeProcess function returns the termination status of a process. While a process is running, its termination status is STILL_ACTIVE. When a process terminates, its termination status is the exit value of the process, which is the value specified in the call to ExitProcess or TerminateProcess, or the value returned by the main or WinMain function of the process. If a process is terminated in some other way (for example, by a fatal, unhandled exception or a CTRL+C signal) the process's termination value is the exception value that caused the termination. The process's exit value is also used as the exit value of all of the threads that had not previously terminated.


 Process and Thread Handles and Identifiers

When a new thread is created by the CreateThread or CreateRemoteThread function, a handle of the thread is returned. Similarly, when a new process is created by the CreateProcess function, handles of the new process and its primary thread are returned. These handles are created with full access rights, and — subject to security access checking — can be used in any of the functions that accepts a thread or process handle. These handles can be inherited by child processes, depending on the inheritance flag specified when they are created. The handles are valid until closed, even after the process or thread they represent is terminated.

The OpenProcess function opens a handle to a process specified by its process identifier. OpenProcess enables you to specify the handle's access rights and inheritability.

A process can use the GetCurrentProcess function to retrieve a pseudohandle of its own process object; a thread can use the GetCurrentThread function to retrieve a pseudohandle to its own thread object. These pseudohandles are valid only for the calling process; they cannot be inherited or duplicated for use by other processes.

The functions that create a process or thread also return an identifier that uniquely identifies the process or thread throughout the system. A process can use the GetCurrentProcessId function to get its own process identifier. Similarly, a thread can use the GetCurrentThreadId function to get its own thread identifier. The identifiers are valid from the time the thread or process is created until the thread or process terminates.


 Using Processes and Threads

•	Using a multithreaded multiple document interface application

•	Creating a child process with redirected input and output

•	Changing environment variables

•	Using thread local storage


 Using a Multithreaded Multiple Document Interface Application

The following example shows how to use multiple threads in a multiple document interface (MDI) process. The process has a single main window, but can have any number of child windows. The primary thread of the process performs initialization and also handles messages to all windows through the application-defined MainWndProc and ChildWndProc functions.

Each time a child window is created, a new thread is also created. In this example, the new thread only checks continually to see if it is time to terminate. In a real application, the new thread could be used to draw the contents of the window or to carry out the functions associated with the window.

The ThreadFunc function is specified in the CreateThread function as the code for the new thread to execute. The handle of the child window associated with the thread is passed as a parameter to ThreadFunc. The child window's handle is also a parameter to ChildWndProc when a message is dispatched to the child window. A handle is necessary for any communication between a child window and its corresponding thread. Both ThreadFunc and ChildWndProc use the window handle in the SetWindowLong function to access the 32-bit value that is reserved for application use in each window structure. In this example, the 32-bit value is a termination flag. When ChildWndProc gets the WM_CLOSE message, it sets the flag; ThreadFunc checks the flag each time through its loop.

This example shows how to use normal priority for the primary thread and below-normal priority for the other threads. Because the primary thread passes all messages for both the main window and the child windows, its higher relative priority ensures responsiveness to user input. (Even when the child threads are left at normal priority, the scheduler automatically boosts the priority of the input thread when necessary.)

When the user terminates the process by closing the main window, a global Boolean parameter is set to terminate the child threads. At this point, the primary thread waits for each child thread to terminate before proceeding. This is necessary only if you want the threads to clean up, save changes to a file, or detach from DLLs before closing. Without waiting, the primary thread terminates the process by returning before the lower priority threads were able to run any additional code.

#include <windows.h>

#include <stdio.h>

#include <stdlib.h>

#define MM_NEWWIN       8001

typedef struct _PTHREADLIST {

  HANDLE hThread;

  LPVOID lpvNext;

} THREADLIST, *PTHREADLIST;

/* Globals */

HANDLE hModule;            /* handle to .EXE file for this process */

HWND   hwndMain = NULL;    /* handle to main window                */

BOOL fKillAll = FALSE;     /* sets TRUE to terminate all threads   */

PTHREADLIST pHead = NULL;  /* head of linked list of thread info.  */

/* Forward declarations */

BOOL InitializeApp(VOID);

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

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

DWORD ThreadFunc(HWND);

VOID AddThreadToList(HANDLE);

VOID ErrorExit(LPSTR);

/* Primary thread:  Initialize the application and dispatch messages. */

int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInst,

        LPSTR lpszCmdLn, int nShowCmd) {

    MSG msg;

    hModule = GetModuleHandle(NULL);

    if (! InitializeApp())

        ErrorExit("InitializeApp failure!");

    while (GetMessage(&msg, NULL, 0, 0)) {

      TranslateMessage(&msg);

      DispatchMessage(&msg);

    }

    return 1;

    UNREFERENCED_PARAMETER(hInst);

    UNREFERENCED_PARAMETER(hPrevInst);

    UNREFERENCED_PARAMETER(lpszCmdLn);

    UNREFERENCED_PARAMETER(nShowCmd);

}

/* Register window classes and create the main window. */

BOOL InitializeApp(VOID) {

    HMENU hmenuMain, hmenuPopup;

    WNDCLASS wc;

    /* Register a window class for the main window. */

    wc.style            = CS_OWNDC;

    wc.lpfnWndProc      = MainWndProc;

    wc.cbClsExtra       = 0;

    wc.cbWndExtra       = 0;

    wc.hInstance        = hModule;

    wc.hIcon            = LoadIcon(NULL,IDI_APPLICATION);

    wc.hCursor          = LoadCursor(NULL, IDC_ARROW);

    wc.hbrBackground    = (HBRUSH)(COLOR_BACKGROUND+1);

    wc.lpszMenuName     = NULL;

    wc.lpszClassName    = "MainWindowClass";

    if (! RegisterClass(&wc))

        return FALSE;

    /* Register a window class for child windows. */

    wc.lpfnWndProc      = ChildWndProc;

    wc.lpszClassName    = "ThreadWindowClass";

    if (! RegisterClass(&wc))

        return FALSE;

    /* Create a menu for the main window. */

    hmenuMain = CreateMenu();

    hmenuPopup = CreateMenu();

    if (! AppendMenu(hmenuPopup, MF_STRING, MM_NEWWIN, "&New Window"))

        return FALSE;

    if (! AppendMenu(hmenuMain, MF_POPUP, (UINT) hmenuPopup, "&Threads"))

        return FALSE;

    /* Create the main window. */

    hwndMain = CreateWindow("MainWindowClass", "Primary Window",

        WS_OVERLAPPED | WS_CAPTION | WS_BORDER | WS_THICKFRAME |

        WS_MAXIMIZEBOX | WS_MINIMIZEBOX | WS_CLIPCHILDREN |

        WS_VISIBLE | WS_SYSMENU, CW_USEDEFAULT, CW_USEDEFAULT,

        CW_USEDEFAULT, CW_USEDEFAULT, NULL, hmenuMain, hModule,

        NULL);

    if (hwndMain == NULL)

        return FALSE;

    /* Set the initial focus. */

    SetFocus(hwndMain);

    return TRUE;

}

/* Main window procedure: Handle messages for the main window. */

LRESULT CALLBACK MainWndProc(HWND hwnd, UINT uiMessage,

        WPARAM wParam, LPARAM lParam) {

    static HWND hwndClient;

    static DWORD dwCount = 1;

    CLIENTCREATESTRUCT ccsClientCreate;

    HWND hwndChildWnd;

    DWORD IDThread;

    PTHREADLIST pNode;

    switch (uiMessage) {

       /* Create a client window to receive child window messages. */

       case WM_CREATE:

           ccsClientCreate.hWindowMenu = NULL;

           ccsClientCreate.idFirstChild = 1;

           hwndClient = CreateWindow("MDICLIENT", NULL,

               WS_CHILD | WS_CLIPCHILDREN | WS_VISIBLE, 0, 0, 0, 0,

               hwnd, NULL, hModule, (LPVOID)&ccsClientCreate);

           return 0L;

       /*

        * Close the main window.  First set fKillAll to TRUE to

        * terminate all threads.  Then wait for the threads to exit

        * before passing a close message to a default handler.  If you

        * don't wait for threads to terminate, process terminates

        * with no chance for thread cleanup.

        */

       case WM_CLOSE:

           fKillAll = TRUE;

           pNode = pHead;

           while (pNode) {

               DWORD dwRes;

               SetThreadPriority(pNode->hThread,

                   THREAD_PRIORITY_HIGHEST);

               dwRes = WaitForSingleObject(pNode->hThread,

                   INFINITE);

               pNode = (PTHREADLIST) pNode->lpvNext;

           }

           return DefFrameProc(hwnd, hwndClient, uiMessage,

               wParam, lParam);

       /* Terminate the process. */

       case WM_DESTROY:

           PostQuitMessage(0);

           return 0L;

       /* Handle the menu commands. */

       case WM_COMMAND:

           switch (LOWORD(wParam)) {

           /* Create a child window and start a thread for it. */

             case MM_NEWWIN: {

               HANDLE hThrd;

               MDICREATESTRUCT mdicCreate;

               TCHAR tchTitleBarText[32];

               LONG lPrev;

               sprintf(tchTitleBarText, "Thread Window %d", dwCount);

               mdicCreate.szClass = "ThreadWindowClass";

               mdicCreate.szTitle = tchTitleBarText;

               mdicCreate.hOwner  = hModule;

               mdicCreate.x = mdicCreate.y =

               mdicCreate.cx = mdicCreate.cy = CW_USEDEFAULT;

               mdicCreate.style = mdicCreate.lParam = 0L;

               /*

                * Send a "create child window" message to the

                * client window.

                */

               hwndChildWnd = (HWND) SendMessage(hwndClient,

                   WM_MDICREATE, 0L, (LONG)&mdicCreate);

               if (hwndChildWnd == NULL)

                   ErrorExit("Failed in Creating Thread Window!");

               /*

                * Window structure used to pass a quit message to

                * the thread.

                */

               lPrev = SetWindowLong(hwndChildWnd, GWL_USERDATA, 0);

               /* Create suspended, alter priority before resuming. */

               hThrd = CreateThread(NULL,  /* no security attributes */

                         0,                /* use default stack size */

                         (LPTHREAD_START_ROUTINE) ThreadFunc,

                         (LPVOID)hwndChildWnd, /* param to thrd func */

                         CREATE_SUSPENDED, /* creation flag          */

                         &IDThread);       /* returns thread id      */

               if (hThrd == NULL)

                   ErrorExit("CreateThread Failed!");

               AddThreadToList(hThrd);

               dwCount++;

               /*

                * Set the priority lower than the primary (input)

                * thread, so that the process is responsive to user

                * input.  Then resume the thread.

                */

               if (! SetThreadPriority(hThrd,

                       THREAD_PRIORITY_BELOW_NORMAL))

                   ErrorExit("SetThreadPriority failed!");

               if ((ResumeThread(hThrd)) == -1)

                   ErrorExit("ResumeThread failed!");

               return 0L;

             }

             default:

               return DefFrameProc(hwnd, hwndClient, uiMessage,

                              wParam, lParam);

           }

       default:

           return DefFrameProc(hwnd, hwndClient, uiMessage,

                          wParam, lParam);

    }

}

/* Handle messages for the child windows. */

LRESULT CALLBACK ChildWndProc(HWND hwnd, UINT uiMessage, WPARAM wParam,

 LPARAM lParam) {

    LONG lPrevLong;

    switch (uiMessage) {

        /* Use a window structure to pass "close" message to thread. */

        case WM_CLOSE:

            lPrevLong = SetWindowLong(hwnd, GWL_USERDATA, 1);

            return DefMDIChildProc(hwnd, uiMessage, wParam, lParam);

        case WM_DESTROY:

            return 0L;

        default:

            return DefMDIChildProc(hwnd, uiMessage, wParam, lParam);

    }

}

/*

 * Each child window has a thread that can be used to perform tasks

 * associated with that window--for example, drawing its contents.

 */

DWORD ThreadFunc(HWND hwnd) {

    LONG lKillMe = 0L;

    while (TRUE) {

        lKillMe = GetWindowLong(hwnd, GWL_USERDATA);

        if (fKillAll || lKillMe) break;

        /* Perform tasks. */

    }

        /* Perform actions needed before thread termination. */

    return 0;

}

VOID AddThreadToList(HANDLE hThread) {

    PTHREADLIST pNode;

    pNode = (PTHREADLIST) LocalAlloc(LPTR, sizeof(PTHREADLIST));

    if (pNode == NULL)

        ErrorExit("malloc Failed!");

    pNode->hThread = hThread;

    pNode->lpvNext = (LPVOID) pHead;

    pHead = pNode;

}

VOID ErrorExit(LPSTR lpszMessage) {

    MessageBox(hwndMain, lpszMessage, "Error", MB_OK);

    ExitProcess(0);

}


 Creating a Child Process with Redirected Input and Output

The following example shows the creation of a child process by a console process and illustrates a technique for using anonymous pipes to redirect the child process's standard input and output. If you have a program that can read its input from the standard input (STDIN) or write its results to the standard output (STDOUT), redirected I/O enables you to execute the program as a child process while controlling its input and receiving its output.

The example shows how to use a SECURITY_ATTRIBUTES structure to create handles that can be inherited by the child process. The structure is used in the CreatePipe function to create inheritable handles to the read and write ends of two pipes. The read end of one pipe serves as standard input for the child process, and the write end of the other pipe is the child's standard output. These pipe handles are specified in the SetStdHandle function, which makes them the standard handles inherited by the child process. After the child process is created, SetStdHandle is used again to restore the original standard handles for the parent process.

The parent process uses the other ends of the pipes to write to the child's input and read the child's output. The handles to these ends of the pipe are also inheritable. However, the handle must not be inherited. Before creating the child process, the parent process must use DuplicateHandle to create a noninheritable duplicate of the application-defined hChildStdinWr global variable. It then uses CloseHandle to close the inheritable handle. This leaves the parent process with a pipe handle it can use, but which the child process does not inherit. For more information about pipes, see Pipes.

The following is the parent process.

#include <stdio.h>

#include <windows.h>

#define BUFSIZE 4096

HANDLE hChildStdinRd, hChildStdinWr, hChildStdinWrDup,

    hChildStdoutRd, hChildStdoutWr,

    hInputFile, hSaveStdin, hSaveStdout;

BOOL CreateChildProcess(VOID);

VOID WriteToPipe(VOID);

VOID ReadFromPipe(VOID);

VOID ErrorExit(LPTSTR);

VOID ErrMsg(LPTSTR, BOOL);

DWORD main(int argc, char *argv[]) {

    SECURITY_ATTRIBUTES saAttr;

    BOOL fSuccess;

    /* Set the bInheritHandle flag so pipe handles are inherited. */

    saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);

    saAttr.bInheritHandle = TRUE;

    saAttr.lpSecurityDescriptor = NULL;

    /*

     * The steps for redirecting child's STDOUT:

     *     1.  Save current STDOUT, to be restored later.

     *     2.  Create anonymous pipe to be STDOUT for child.

     *     3.  Set STDOUT of parent to be write handle of pipe, so

     *         it is inherited by child.

     */

    /* Save the handle to the current STDOUT. */

    hSaveStdout = GetStdHandle(STD_OUTPUT_HANDLE);

    /* Create a pipe for the child's STDOUT. */

    if (! CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 0))

        ErrorExit("Stdout pipe creation failed\n");

    /* Set a write handle to the pipe to be STDOUT. */

    if (! SetStdHandle(STD_OUTPUT_HANDLE, hChildStdoutWr))

        ErrorExit("Redirecting STDOUT failed");

    /*

     * The steps for redirecting child's STDIN:

     *     1.  Save current STDIN, to be restored later.

     *     2.  Create anonymous pipe to be STDIN for child.

     *     3.  Set STDIN of parent to be read handle of pipe, so

     *         it is inherited by child.

     *     4.  Create a noninheritable duplicate of write handle,

     *         and close the inheritable write handle.

     */

    /* Save the handle to the current STDIN. */

    hSaveStdin = GetStdHandle(STD_INPUT_HANDLE);

    /* Create a pipe for the child's STDIN. */

    if (! CreatePipe(&hChildStdinRd, &hChildStdinWr, &saAttr, 0))

        ErrorExit("Stdin pipe creation failed\n");

    /* Set a read handle to the pipe to be STDIN. */

    if (! SetStdHandle(STD_INPUT_HANDLE, hChildStdinRd))

        ErrorExit("Redirecting Stdin failed");

    /* Duplicate the write handle to the pipe so it is not inherited. */

    fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdinWr,

        GetCurrentProcess(), &hChildStdinWrDup, 0,

        FALSE,       /* not inherited */

        DUPLICATE_SAME_ACCESS);

    if (! fSuccess)

        ErrorExit("DuplicateHandle failed");

    CloseHandle(hChildStdinWr);

    /* Now create the child process. */

    if (! CreateChildProcess())

        ErrorExit("Create process failed");

    /* After process creation, restore the saved STDIN and STDOUT. */

    if (! SetStdHandle(STD_INPUT_HANDLE, hSaveStdin))

        ErrorExit("Re-redirecting Stdin failed\n");

    if (! SetStdHandle(STD_OUTPUT_HANDLE, hSaveStdout))

        ErrorExit("Re-redirecting Stdout failed\n");

    /* Get a handle to the parent's input file. */

    if (argc > 1)

        hInputFile = CreateFile(argv[1], GENERIC_READ, 0, NULL,

            OPEN_EXISTING, FILE_ATTRIBUTE_READONLY, NULL);

    else

        hInputFile = hSaveStdin;

    if (hInputFile == INVALID_HANDLE_VALUE)

        ErrorExit("no input file\n");

    /* Write to pipe that is the standard input for a child process. */

    WriteToPipe();

    /* Read from pipe that is the standard output for child process. */

    ReadFromPipe();

    return 0;

}

BOOL CreateChildProcess() {

    PROCESS_INFORMATION piProcInfo;

    STARTUPINFO siStartInfo;

    /* Set up members of STARTUPINFO structure. */

    siStartInfo.cb = sizeof(STARTUPINFO);

    siStartInfo.lpReserved = NULL;

    siStartInfo.lpReserved2 = NULL;

    siStartInfo.cbReserved2 = 0;

    siStartInfo.lpDesktop = NULL;

    siStartInfo.dwFlags = 0;

    /* Create the child process. */

    return CreateProcess(NULL,

        "child",       /* command line                       */

        NULL,          /* process security attributes        */

        NULL,          /* primary thread security attributes */

        TRUE,          /* handles are inherited              */

        0,             /* creation flags                     */

        NULL,          /* use parent's environment           */

        NULL,          /* use parent's current directory     */

        &siStartInfo,  /* STARTUPINFO pointer                */

        &piProcInfo);  /* receives PROCESS_INFORMATION       */

VOID WriteToPipe(VOID) {

    DWORD dwRead, dwWritten;

    CHAR chBuf[BUFSIZE];

    /* Read from a file and write its contents to a pipe. */

    for (;;) {

        if (! ReadFile(hInputFile, chBuf, BUFSIZE, &dwRead, NULL) ||

            dwRead == 0) break;

        if (! WriteFile(hChildStdinWrDup, chBuf, dwRead,

            &dwWritten, NULL)) break;

    }

    /* Close the pipe handle so the child stops reading. */

    if (! CloseHandle(hChildStdinWrDup))

        ErrorExit("Close pipe failed\n");

}

VOID ReadFromPipe(VOID) {

    DWORD dwRead, dwWritten;

    CHAR chBuf[BUFSIZE];

    HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);

    /*

     * Close the write end of the pipe before reading from the

     * read end of the pipe.

     */

    if (! CloseHandle(hChildStdoutWr))

        ErrorExit("Closing handle failed");

    /* Read output from child, and write it to parent's STDOUT. */

    for (;;) {

        if (! ReadFile(hChildStdoutRd, chBuf, BUFSIZE, &dwRead, NULL) ||

            dwRead == 0) break;

        if (! WriteFile(hSaveStdout, chBuf, dwRead, &dwWritten, NULL))

            break;

    }

}

VOID ErrorExit (LPTSTR lpszMessage) {

    fprintf(stderr, "%s\n", lpszMessage);

    ExitProcess(0);

}

Here's the child process:

#include <windows.h>

#define BUFSIZE 4096

VOID main(VOID) {

    CHAR chBuf[BUFSIZE];

    DWORD dwRead, dwWritten;

    HANDLE hStdin, hStdout;

    BOOL fSuccess;

    hStdout = GetStdHandle(STD_OUTPUT_HANDLE);

    hStdin = GetStdHandle(STD_INPUT_HANDLE);

    if ((hStdout == INVALID_HANDLE_VALUE) ||

        (hStdin == INVALID_HANDLE_VALUE))

        ExitProcess(1);

    for (;;) {

      /* Read from standard input. */

      fSuccess = ReadFile(hStdin, chBuf, BUFSIZE, &dwRead, NULL);

      if (! fSuccess || dwRead == 0)

          break;

      /* Write to standard output. */

      fSuccess = WriteFile(hStdout, chBuf, dwRead, &dwWritten, NULL);

      if (! fSuccess)

          break;

    }

}


 Changing Environment Variables

The environment block consists of a null-terminated block of null-terminated strings (that is, two null bytes at the end of the block), where each string is in the form:

name=value

Because the equal sign is a separator, it must not be used in the name of an environment variable. The following example creates a new environment block to pass to a child process.

TCHAR tchNewEnv[BUFSIZE];

LPTSTR lpszCurrentVariable;

BOOL fSuccess;

/* Copy name=value environment variable pairs into environment block. */

lpszCurrentVariable = tchNewEnv;

if (lstrcpy(lpszCurrentVariable, "OperatingSystem=Windows") == NULL)

    ErrorExit("lstrcpy failed");

lpszCurrentVariable += lstrlen(lpszCurrentVariable) + 1;

if (lstrcpy(lpszCurrentVariable, "API=Win32") == NULL)

    ErrorExit("lstrcpy failed");

/* Terminate the block with a NULL byte. */

lpszCurrentVariable += lstrlen(lpszCurrentVariable) + 1;

*lpszCurrentVariable = '\0';

/* Create the child process, specifying a new environment block. */

fSuccess = CreateProcess(NULL, "childenv", NULL, NULL, TRUE, 0,

    (LPVOID) tchNewEnv,     /* new environment block */

    NULL, &siStartInfo, &piProcInfo);

if (! fSuccess)

    ErrorExit("CreateProcess failed");

If you want the child process to inherit most of the parent's environment with only a few changes, save the current values, make changes for the child to inherit, and then restore the saved values for example.

LPTSTR lpszOldValue;

TCHAR tchBuf[BUFSIZE];

BOOL fSuccess;

/*

 * lpszOldValue gets current value of "varname", or NULL if "varname"

 * environment variable does not exist. Set "varname" to new value,

 * create child process, then use SetEnvironmentVariable to restore

 * original value of "varname". If lpszOldValue is NULL, the "varname"

 * variable will be deleted.

 */

lpszOldValue = ((GetEnvironmentVariable("varname",

    tchBuf, BUFSIZE) > 0) ? tchBuf : NULL);

/* Set a value for the child to inherit. */

if (! SetEnvironmentVariable("varname", "newvalue"))

    ErrorExit("SetEnvironmentVariable failed");

/* Create a child process. */

fSuccess = CreateProcess(NULL, "childenv", NULL, NULL, TRUE, 0,

    NULL,     /* inherit parent's environment */

    NULL, &siStartInfo, &piProcInfo);

if (! fSuccess)

    ErrorExit("CreateProcess failed");

/* Restore the parent's environment. */

if (! SetEnvironmentVariable("varname", lpszOldValue))

    ErrorExit("SetEnvironmentVariable failed");

The following example, taken from a console process, prints the contents of the process's environment block.

LPTSTR lpszVariable;

LPVOID lpvEnv;

/* Get a pointer to the environment block. */

lpvEnv = GetEnvironmentStrings();

/*

 * Variable strings are separated by NULL byte, and the block is

 * terminated by a NULL byte.

 */

for (lpszVariable = (LPTSTR) lpvEnv; *lpszVariable; lpszVariable++) {

    while (*lpszVariable)

        putchar(*lpszVariable++);

    putchar('\n');

}


 Using Thread Local Storage

Thread local storage (TLS) enables multiple threads of the same process to use an index allocated by the TlsAlloc function to store and retrieve a value that is local to the thread. In this example, an index is allocated when the process starts. When each thread starts, it allocates a block of dynamic memory and stores a pointer to this memory by using the TLS index. The TLS index is used by the locally defined CommonFunc function to access the data local to the calling thread. Before each thread terminates, it releases its dynamic memory.

#include <stdio.h>

#include <windows.h>

#define THREADCOUNT 4

DWORD dwTlsIndex;

VOID ErrorExit(LPTSTR);

VOID CommonFunc(VOID) {

  LPVOID lpvData;

    /* Retrieve a data pointer for the current thread. */

    lpvData = TlsGetValue(dwTlsIndex);

    if ((lpvData == 0) && (GetLastError() != 0))

        ErrorExit("TlsGetValue error");

    /*

     *    Use the data stored for the current thread.

     */

    printf("common: thread %d: lpvData=%lx\n",

        GetCurrentThreadId(), lpvData);

    Sleep(5000);

}

DWORD ThreadFunc(VOID) {

    LPVOID lpvData;

    /* Initialize the TLS index for this thread. */

    lpvData = (LPVOID) LocalAlloc(LPTR, 256);

    if (! TlsSetValue(dwTlsIndex, lpvData))

        ErrorExit("TlsSetValue error");

    printf("thread %d: lpvData=%lx\n", GetCurrentThreadId(), lpvData);

    CommonFunc();

    /* Release the dynamic memory before the thread returns. */

    lpvData = TlsGetValue(dwTlsIndex);

    if (lpvData != 0)

        LocalFree((HLOCAL) lpvData);

    return 0;

}

DWORD main(VOID) {

    DWORD IDThread;

    HANDLE hThread[THREADCOUNT];

    int i;

    /* Allocate a TLS index. */

    if ((dwTlsIndex = TlsAlloc()) == 0xFFFFFFFF)

        ErrorExit("TlsAlloc failed");

    /* Create multiple threads. */

    for (i = 0; i < THREADCOUNT; i++) {

        hThread[i] = CreateThread(NULL,/* no security attributes    */

            0,                       /* use default stack size      */

            (LPTHREAD_START_ROUTINE) ThreadFunc, /* thread function */

            NULL,                    /* no thread function argument */

            0,                       /* use default creation flags  */

            &IDThread);              /* returns thread identifier   */

        /* Check the return value for success. */

        if (hThread[i] == NULL)

            ErrorExit("CreateThread error\n");

    }

    for (i = 0; i < THREADCOUNT; i++)

        WaitForSingleObject(hThread[i], INFINITE);

    return 0;

}

VOID ErrorExit (LPTSTR lpszMessage) {

    fprintf(stderr, "%s\n", lpszMessage);

    ExitProcess(0);

}


 Process and Thread Functions

Following are the functions used with processes and threads.

AttachThreadInput
CommandLineToArgvW
CreateProcess
CreateRemoteThread
CreateThread
ExitProcess
ExitThread
FreeEnvironmentStrings
GetCommandLine
GetCurrentProcess
GetCurrentProcessId
GetCurrentThread
GetCurrentThreadId
GetEnvironmentStrings
GetEnvironmentVariable
GetExitCodeProcess
GetExitCodeThread
GetPriorityClass
GetProcessAffinityMask
GetProcessShutdownParameters
GetProcessTimes
GetProcessVersion
GetProcessWorkingSetSize
GetStartupInfo
GetThreadPriority
GetThreadTimes
OpenProcess
ResumeThread
SetEnvironmentVariable
SetPriorityClass
SetProcessShutdownParameters
SetThreadAffinityMask
SetThreadPriority
Sleep
SleepEx
SetProcessWorkingSetSize
SuspendThread
TerminateProcess
TerminateThread
TlsAlloc
TlsFree
TlsGetValue
TlsSetValue
WaitForInputIdle
WinExec

Obsolete or Deleted Functions

Yield


 Registry

The registry is a system-defined database that applications and Microsoft® Windows® system components use to store and retrieve configuration data.


 About the Registry

The registry stores data in binary files. To manipulate registry data, an application must use the registry functions. This overview describes the registry and the functions that applications use to access and manipulate the data stored there. The data stored in the registry varies according to the Windows platform that is used. This overview contains a description of registry entries that can exist on any platform.


 Structure of the Registry

The registry stores data in a hierarchically structured tree. Each node in the tree is called a key. Each key can contain both subkeys and data entries called values. Sometimes, the presence of a key is all the data that an application requires; other times, an application opens a key and uses the values associated with the key. A key can have any number of values, and the values can be in any form.

Each key has a name consisting of one or more printable ANSI characters — that is, characters ranging from values 32 through 127. Key names cannot include a space, a backslash (\), or a wildcard character (* or ?). Key names beginning with a period (.) are reserved. The name of each subkey is unique with respect to the key that is immediately above it in the hierarchy. Key names are not localized into other languages, although values may be.


 Registry Storage Space

Although there are few technical limits to the type and size of data an application can store in the registry, certain practical guidelines exist to promote system efficiency. An application should store configuration and initialization data in the registry, but other kinds of data should be stored elsewhere.

Generally, data consisting of more than one or two kilobytes (K) should be stored as a file and referred to by using a key in the registry rather than being stored as a value. Instead of duplicating large pieces of data in the registry, an application should save the data as a file and refer to the file. Executable binary code should never be stored in the registry.

A value entry uses much less registry space than a key. To save space, an application should group similar data together as a structure and store the structure as a value rather than storing each of the structure members as a separate key. (Storing the data in binary form allows an application to store data in one value that would otherwise be made up of several incompatible types.)


 Predefined Keys

An application must open a key before it can add data to the registry. To open a key, an application must supply the handle of another key in the registry that is already open. The system defines standard handles that are always open. An application can use these predefined handles as entry points to the registry.

The system provides two predefined keys at the root of the registry: HKEY_LOCAL_MACHINE and HKEY_USERS. In addition, the system defines two subkeys: HKEY_CLASSES_ROOT (a subkey of HKEY_LOCAL_MACHINE) and HKEY_CURRENT_USER (a subkey of HKEY_USERS). These registry handles are valid for all Win32 implementations of the registry, although the use of the handles may vary from platform to platform.

Predefined keys help an application navigate in the registry and make it possible to develop tools that allow a system administrator to manipulate categories of data. Applications that add data to the registry should always work within the framework of predefined keys, so administrative tools can find and use the new data.

These predefined keys are used as entry points to the registry.

Entry point	Use
HKEY_CLASSES_ROOT	Registry entries subordinate to this key define types (or classes) of documents and the properties associated with those types. Data stored under this key is used by Windows shell applications and by object linking and embedding (OLE) applications.
HKEY_CURRENT_USER	Registry entries subordinate to this key define the preferences of the current user. These preferences include the settings of environment variables, data about program groups, colors, printers, network connections, and application preferences.
HKEY_LOCAL_MACHINE	Registry entries subordinate to this key define the physical state of the computer, including data about the bus type, system memory, and installed hardware and software.
HKEY_USERS	Registry entries subordinate to this key define the default user configuration for new users on the local computer and the user configuration for the current user.
The use of HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, and HKEY_USERS varies depending on the implementation of the registry. In addition, other predefined handles have been defined for specific Windows platforms.


 Categories of Data

Before putting data into the registry, an application should divide the data into two categories: computer-specific data and user-specific data. By making this distinction, an application can support multiple users, and yet locate user-specific data over a network and use that data in different locations, allowing location-independent user profile data. (A user profile is a set of configuration data saved for every user.)

When the application is installed, it should record the computer-specific data under the HKEY_LOCAL_MACHINE key. In particular, it should create keys for the company name, product name, and version number, as shown in the following example:

HKEY_LOCAL_MACHINE\Software\MyCompany\MyProduct\1.0

If the application supports OLE, it should record that data under HKEY_LOCAL_MACHINE\Software\Classes.

An application should record user-specific data under the HKEY_CURRENT_USER key, as shown in the following example:

HKEY_CURRENT_USER\Software\MyCompany\MyProduct\1.0\...


 Opening, Creating, and Closing Keys

Before an application can add data to the registry, it must create or open a key. To create or open a key, an application always refers to the key as a subkey of a currently open key. The four predefined keys (HKEY_LOCAL_MACHINE, HKEY_CLASSES_ROOT, HKEY_USERS, and HKEY_CURRENT_USER) are always open. An application uses the RegOpenKey or RegOpenKeyEx function to open a key and the RegCreateKey or RegCreateKeyEx function to create a key.

An application can use the RegCloseKey function to close a key and write the data it contains into the registry. RegCloseKey does not necessarily write the data to the registry before returning; it can take as much as several seconds for the cache to be flushed to the hard disk. If an application must explicitly write registry data to the hard disk, it can use the RegFlushKey function. RegFlushKey, however, uses many system resources and should be called only when absolutely necessary.


 Writing and Deleting Registry Data

An application can use either the RegSetValue or RegSetValueEx function to associate a value and its data with a key. RegSetValue works only with strings (values having the REG_SZ type). RegSetValueEx, however, can write values with any type of data. Either of these functions can create a key and its value at the same time.

To delete a value from a key, an application can use the RegDeleteValue function. To delete a key, it can use the RegDeleteKey function. A deleted key is not removed until the last handle to it has been closed. Subkeys and values cannot be created under a deleted key.

To change a key's security information, an application can use the RegSetKeySecurity function.


 Retrieving Data from the Registry

To retrieve data from the registry, an application typically enumerates the subkeys of a key until it finds a particular one and then retrieves data from the value or values associated with it. An application can call either the RegEnumKey or RegEnumKeyEx function to enumerate the subkeys of a given key. RegEnumKeyEx returns a subkey and its class, but RegEnumKey returns only the subkey, not the class.

To retrieve detailed data about a particular subkey, an application can call the RegQueryInfoKey function. The RegGetKeySecurity function retrieves a copy of the security descriptor protecting a key.

An application can use the RegEnumValue function to enumerate the values for a given key, and the RegQueryValue or RegQueryValueEx function to retrieve a particular value for a key. An application typically calls RegEnumValue to determine the value names and then RegQueryValueEx to retrieve the data for the names.

RegQueryValue and RegQueryValueEx differ in how they treat unexpanded references to environment variables. If an unnamed value contains an unexpanded environment variable (for example, %PATH%), RegQueryValue expands the variable into the storage buffer provided as one of its parameters. RegQueryValueEx, however, does not expand these references. (Applications can also use the ExpandEnvironmentStrings function to expand environment variables.)


 Registry Files

Applications can save part of the registry in a file and then load the contents of the file back into the registry. A registry file is useful when a large amount of data is being manipulated, when many entries are being made in the registry, or when the data is transitory and must be loaded and then unloaded again. Applications that back up and restore parts of the registry are likely to use registry files.

To save a key and its subkeys and values to a registry file, an application can call the RegSaveKey function. To write the registry file back to the registry, an application can use the RegLoadKey, RegReplaceKey, or RegRestoreKey function.

RegLoadKey loads registry data from a specified file into a specified subkey under HKEY_USERS or HKEY_LOCAL_MACHINE on the calling application's computer or on a remote computer. The function creates the specified subkey if it does not already exist. After calling this function, an application can use the RegUnLoadKey function to restore the registry to its previous state.

RegReplaceKey replaces a key and all its subkeys and values in the registry with the data contained in a specified file. The new data takes effect the next time the system is started.

RegRestoreKey loads registry data from a specified file into a specified key on the calling application's computer or on a remote computer. This function replaces the subkeys and values below the specified key with the subkeys and values that follow the top-level key in the file.


 Using the Registry

The following example demonstrates the use of the RegQueryInfoKey, RegEnumKey, and RegEnumValue functions. The hKey parameter passed to each function is the handle of an open key. This key must be opened before the function call and closed afterward.

// QueryKey - enumerates the subkeys of a given key and the associated

//     values and then copies the information about the keys and values

//     into a pair of edit controls and list boxes.

// hDlg - dialog box that contains the edit controls and list boxes

// hKey - key whose subkeys and values are to be enumerated

VOID QueryKey(HWND hDlg, HANDLE hKey)

{

    CHAR     achKey[MAX_PATH];

    CHAR     achClass[MAX_PATH] = "";  /* buffer for class name   */

    DWORD    cchClassName = MAX_PATH;  /* length of class string  */

    DWORD    cSubKeys;                 /* number of subkeys       */

    DWORD    cbMaxSubKey;              /* longest subkey size     */

    DWORD    cchMaxClass;              /* longest class string    */

    DWORD    cValues;              /* number of values for key    */

    DWORD    cchMaxValue;          /* longest value name          */

    DWORD    cbMaxValueData;       /* longest value data          */

    DWORD    cbSecurityDescriptor; /* size of security descriptor */

    FILETIME ftLastWriteTime;      /* last write time             */

    DWORD i, j;

    DWORD retCode, retValue;

    CHAR  achValue[MAX_VALUE_NAME];

    DWORD cchValue = MAX_VALUE_NAME;

    CHAR  achBuff[80];

    // Get the class name and the value count.

    RegQueryInfoKey(hKey,        /* key handle                    */

        achClass,                /* buffer for class name         */

        &cchClassName,           /* length of class string        */

        NULL,                    /* reserved                      */

        &cSubKeys,               /* number of subkeys             */

        &cbMaxSubKey,            /* longest subkey size           */

        &cchMaxClass,            /* longest class string          */

        &cValues,                /* number of values for this key */

        &cchMaxValue,            /* longest value name            */

        &cbMaxValueData,         /* longest value data            */

        &cbSecurityDescriptor,   /* security descriptor           */

        &ftLastWriteTime);       /* last write time               */

    SetDlgItemText(hDlg, IDE_CLASS, achClass);

    SetDlgItemInt(hDlg, IDE_CVALUES, cValues, FALSE);

    SendMessage(GetDlgItem(hDlg, IDL_LISTBOX),

        LB_ADDSTRING, 0, (LONG) "..");

    // Enumerate the child keys, looping until RegEnumKey fails. Then

    // get the name of each child key and copy it into the list box.

    SetCursor(LoadCursor(NULL, IDC_WAIT));

    for (i = 0, retCode = ERROR_SUCCESS;

            retCode == ERROR_SUCCESS; i++) {

        retCode = RegEnumKey(hKey, i, achKey, MAX_PATH);

        if (retCode == (DWORD)ERROR_SUCCESS)

            SendMessage(GetDlgItem(hDlg, IDL_LISTBOX),

                LB_ADDSTRING, 0, (LONG) achKey);

    }

    SetCursor(LoadCursor (NULL, IDC_ARROW));

    // Enumerate the key values.

    SetCursor(LoadCursor(NULL, IDC_WAIT));

    if (cValues)

        for (j = 0, retValue = ERROR_SUCCESS;

                j < cValues; j++) {

            cchValue = MAX_VALUE_NAME;

            achValue[0] = '\0';

            retValue = RegEnumValue(hKey, j, achValue,

                &cchValue,

                NULL,

                NULL,    /* &dwType, */

                NULL,    /* &bData,  */

                NULL);   /* &bcData  */

            if (retValue != (DWORD) ERROR_SUCCESS &&

                    retValue != ERROR_INSUFFICIENT_BUFFER) {

                wsprintf (achBuff,

                    "Line:%d 0 based index = %d, retValue = %d, "

                     "ValueLen = %d",

                     __LINE__, j, retValue, cchValue);

                MessageBox (hDlg, achBuff, "Debug", MB_OK);

            }

            achBuff[0] = '\0';

            // Add each value to a list box.

            if (!lstrlen(achValue))

                lstrcpy(achValue, "<NO NAME>");

            wsprintf(achBuff, "%d) %s ", j, achValue);

            SendMessage(GetDlgItem(hDlg,IDL_LISTBOX2),

                LB_ADDSTRING, 0, (LONG) achBuff);

        }

    SetCursor(LoadCursor(NULL, IDC_ARROW));

}


 Registry Functions

Following are the functions used with the registry:

RegCloseKey
RegConnectRegistry
RegCreateKey
RegCreateKeyEx
RegDeleteKey
RegDeleteValue
RegEnumKey
RegEnumKeyEx
RegEnumValue
RegFlushKey
RegGetKeySecurity
RegLoadKey
RegNotifyChangeKeyValue
RegOpenKey
RegOpenKeyEx
RegQueryInfoKey
RegQueryValue
RegQueryValueEx
RegReplaceKey
RegRestoreKey
RegSaveKey
RegSetKeySecurity
RegSetValue
RegSetValueEx
RegUnLoadKey


 Remote Access Service

Remote Access Service (RAS) lets users at remote locations work as if connected directly to a computer network, accessing one or more RAS servers.


 About Remote Access Service

Win32 RAS support enables a RAS client application to start a RAS connection operation, get information about existing RAS connections, and end a RAS connection.

Microsoft® Win32® application programming interface (API) does not currently provide support for applications to administer the Remote Access Server.

This overview discusses the following topics:

•	Types of RAS connection operations

•	Phonebook files and the information needed to establish a connection

•	Connection states during a connection operation

•	Notification handlers for tracking the progress of a connection operation

•	Paused states during a connection operation that enable the RAS client to collect additional information from the user

•	Support for connection operations that require a callback from the remote server

•	Ending a RAS connection


 RAS Connection Operations

A RAS client application uses the RasDial function to establish a connection to a RAS server. The RasDial function starts the connection operation, which is then carried out by the Remote Access Connection Manager.

The Remote Access Connection Manager is a service that handles the details of establishing the connection to the remote server. This service also provides the client with status information during the connection operation. The Remote Access Connection Manager starts automatically when an application loads the RASAPI32.DLL.

The RasDial call specifies the following information when it starts a connection operation:

•	The connection information that the Remote Access Connection Manager needs to establish the connection.

•	An optional notification handler that receives progress notifications during the connection operation. If the RasDial call specifies a notification handler, the call is asynchronous; otherwise, it is synchronous.

•	An optional RASDIALEXTENSIONS structure to enable or disable extensions to the RasDial operation. The extensions permit a RAS client to directly enable some modem settings, to control whether RAS uses the prefixes and suffixes in a phonebook entry, and to support paused states during the connection operation.


 Synchronous Operations

When RasDial is invoked as a synchronous operation, the function does not return until the connection has been established or an error occurs. Synchronous mode provides a simple way for a RAS client to establish a connection. The client can simply call RasDial, wait for the function to return, and then call the RasGetConnectStatus function to determine whether the connection operation was successful. Once the connection has been established, the client application can terminate without breaking the connection. If an error occurs, the client application must shut down the connection operation before terminating.

The disadvantage of synchronous mode is that the client does not receive progress notifications as the connection operation proceeds. As a workaround for this lack of progress notifications, a synchronous mode client can use a separate thread that calls RasGetConnectStatus to poll for and display the current state. However, for RAS clients that want to receive progress information, the preferred technique is to invoke RasDial asynchronously.


 Asynchronous Operations

When RasDial is invoked as an asynchronous operation, the function returns immediately. In asynchronous mode, the RasDial call must specify a notification handler that the Remote Access Connection Manager uses to inform the client whenever the connection operation changes states or an error occurs.

The notification handler can be a window to receive messages, or a RasDialFunc or RasDialFunc1 callback function. The Remote Access Connection Manager makes its asynchronous notifications in the context of the thread that made the RasDial call. For this reason, the calling thread must not terminate until the connection operation has been successfully established or an error occurs. As in synchronous mode, the client application can safely terminate once the connection has been established, and it must shut down the connection operation if an error occurs.


 Phonebook Files and Connection Information

A RasDial call must specify the information that the Remote Access Connection Manager needs to establish the connection. Typically, the RasDial call provides the connection information by specifying a phonebook entry in a phonebook file. The connection information in a phonebook entry includes phone numbers, bps rates, user authentication information, and other connection information.

A RAS client uses the parameters of the RasDial function to specify a phonebook file and an entry in that file. The lpszPhonebookPath parameter can specify the name of a phonebook file, or it can be NULL to indicate that the default phonebook file should be used. The lpRasDialParams parameter points to a RASDIALPARAMS structure that specifies the name of the phonebook entry to use.

To display a list of phonebook entries from which the user can select a connection, a RAS client can call the RasEnumEntries function to enumerate the entries in a phonebook file.

To make a connection without using a phonebook entry, the RasDial call can specify an empty string for the szEntryName member of the RASDIALPARAMS structure. The RASDIALPARAMS.szPhoneNumber member must contain the number to call. In this case, the Remote Access Connection Manager uses the first available modem port and default values for all other settings.


 Phonebook Files

Phonebook files provide a standard way to collect and specify the information that the Remote Access Connection Manager needs to establish a remote connection. A phonebook file is a text file that associates entry names with information such as phone numbers, COM ports, and modem settings. Each phonebook entry contains the information needed to establish a RAS connection.

The Win32 API does not currently provide support for creating a phonebook file.

Windows 95: Dial-up networking stores phonebook entries in the registry rather than in a phonebook file. A user or administrator can use the Dial-Up Networking folder to create and edit phonebook entries. You can use the RasCreatePhonebookEntry and RasEditPhonebookEntry functions to create or edit a phonebook entry. These functions display a dialog box in which the user can specify information about the phonebook entry. You can use the RasGetEntryDialParams and RasSetEntryDialParams functions to set or retrieve the connection parameters for a phonebook entry.

Windows NT:  The functions for creating and editing a phonebook entry are not supported. Microsoft's remote access application, RASPHONE.EXE, creates a default phonebook file called RASPHONE.PBK, and can also create personal phonebook files. A user or administrator can use RASPHONE.EXE to create and edit entries in a phonebook file. Using RASPHONE.EXE is currently the only safe way to create a phonebook file or to create or edit a phonebook entry.


 User Authentication Information

The Remote Access Connection Manager service on the client computer sends a user name and password to the RAS server on the remote computer. Before it will establish a connection, the remote server uses this information to authenticate the user. By default, the Remote Access Connection Manager sends the user name and password of the currently logged-on user. The RAS client can use the RASDIALPARAMS structure specified in the RasDial call to specify a different user name and password.

If the remote server cannot authenticate the user with the specified information, it can allow the connection operation to enter a paused state to enable the RAS client to collect different authentication data from the user.


 Other Connection Information

The members of the RASDIALPARAMS structure can also specify the following connection information:

•	A phone number to override the number in the phonebook entry.

•	A callback phone number that the remote server can call back to establish the connection.

•	The name of the remote network domain on which the authentication is to occur.

For the callback number and the domain, the RASDIALPARAMS members can either indicate that RAS should use the information in the phonebook entry, or it can provide information that overrides the phonebook data.

A RAS client can use the lpRasDialExtensions parameter of the RasDial function to control whether RAS uses a phone number prefix or suffix specified in a phonebook entry.


 Connection States

During the process of connecting to a remote server, the Remote Access Connection Manager and the RAS server on the remote computer perform several steps to establish the connection. Each of these steps is identified by a connection state. The RASCONNSTATE enumeration is a set of values that correspond to these connection states. The connection states can be divided into the following three groups:

Running states	The running states are the parts of the connection operation that RAS handles automatically, such as connecting to the necessary devices, authenticating the user, and waiting for a callback from the remote server. Unless an error occurs, the RAS client need take no action other than to pass the notification on to the user.
Paused states	The paused states occur when the remote server pauses the connection operation to get additional input from the user. During a paused state, the user can type a callback number, a different user name and password if the user authentication fails, or a new password if the old one has expired.
Terminal states	The terminal states occur when the connection has been successfully established, the connection operation has failed, or the connection has been broken by a RasHangUp call.
There are several mechanisms that a RAS client can use to determine the current state of a connection operation. When a RAS client executes the RasDial function asynchronously, the Remote Access Connection Manager sends progress notifications to the client's notification handler whenever the connection state changes. In addition, the client can use the RasGetConnectStatus function to get the current state of any RAS connection operation.


 Notification Handlers

An asynchronous RasDial call must specify a notification handler. During an asynchronous connection operation, the Remote Access Connection Manager uses the notification handler to inform the RAS client whenever the connection state changes or an error occurs.

The actions performed by a notification handler can be divided into the following categories:

•	Handling errors.

•	Providing feedback to the user as the connection operation proceeds through the various connection states. See Informational Notifications.

•	Handling paused states.

•	Signaling the RAS client application when the connection operation has been completed. See Completion Notifications.

There are three types of notification handlers, each of which receives the same basic information: the current connection state and an error code that is nonzero only if an error has occurred.

RasDialFunc	A callback function prototype that receives only the current connection state and error code information.
RasDialFunc1	A callback function prototype that receives the HRASCONN connection handle and extended error information in addition to the basic information. The connection handle parameter makes RasDialFunc1 useful for client applications that support multiple simultaneous connection operations. This allows the client to specify the same callback function for all operations, and enables the callback function to determine which connection is changing states.
Window handle	A window handle to which RAS sends WM_RASDIALEVENT messages containing the current connection state and error code information. Use this method if your source code must be compatible with 16-bit Windows, because 16-bit Windows does not support either of the callback functions.
The Remote Access Connection Manager suspends the connection operation until the notification handler returns. For this reason, the handler should return as soon as possible unless an error has occurred.

The RasDial function should not be called from within a notification handler. The other remote access functions (RasGetConnectStatus, RasEnumEntries, RasEnumConnections, RasGetErrorString, and RasHangUp) can be called from within a handler.


 Handling RAS Errors

When an error occurs, the Remote Access Connection Manager invokes the client's notification handler. The notification indicates the connection state when the error occurred, and a code that identifies the error. In these cases, the notification handler should call RasHangUp to end the RAS connection.

The RAS client can use the RasGetErrorString function to get a display string describing the error.


 Informational Notifications

For the connection states known as running states, no action is required of the notification handler unless an error occurs. Running states occur during the parts of the connection operation that RAS handles automatically, such as connecting to the necessary devices, authenticating the user, and waiting for a callback from the remote server. The notification is simply a progress report to the client.

The client can choose to pass these informational notifications on to the user. In some running states, the client may want to display additional information. For example, a notification handler that receives a RASCS_ConnectDevice notification can call the RasGetConnectStatus function to get the name and type of the device being connected to. Another example is when the client receives a RASCS_Projected notification. This occurs when the RAS projection phase of the connection operation has been completed. The client can call the RasGetProjectionInfo function to get additional information about the projection. The client can use this information to notify the user as to which network protocols can be used by this connection.

You should avoid writing code that depends on the order or occurrence of particular informational states, because this may vary between platforms.


 Completion Notifications

The Remote Access Connection Manager continues progress notifications until the connection operation has been completed. This occurs in the following situations:

•	The connection is established. The handler receives a RASCS_Connected notification. The RAS client application can exit without breaking the connection.

•	An error occurs. The handler receives a notification indicating the error and the connection state when the error occurred.

•	The connection operation is interrupted by a RasHangUp call.


 Paused States

During a connection operation, there can be times when the remote server cannot proceed without additional information from the local user. Beginning with Microsoft® Windows NT™ version 3.5, the RasDial function supports paused states. A paused state allows the Remote Access Connection Manager to suspend a connection operation so the RAS client application can collect information from the user.

Paused states are useful in the following situations:

•	When the user needs to provide a callback number.

•	When the user authentication fails, the user can type in a different user name and password.

•	When the user's password has expired, the user can provide a new password.

By default, paused state support is disabled. RAS clients that want to support paused states must set the RDEOPTS_PausedStates flag in the RASDIALEXTENSIONS structure passed as a parameter to RasDial.

When a paused state occurs, the Remote Access Connection Manager invokes the client's notification handler. If paused state support is disabled, the notification message indicates an error, and the connection operation fails. If it is enabled, the Connection Manager pauses the connection operation to wait for the RAS client's response. The RAS client can resume the connection operation by a second RasDial call, or terminate it by calling the RasHangUp function.

After getting the user's input, the RAS client restarts the connection operation by calling RasDial again. This second RasDial call must specify the following information:

•	The connection handle that was returned by the original RasDial call.

•	The same notification handler as the original RasDial call.

•	The user's input in the appropriate members of the RASDIALPARAMS structure. Other members of the RASDIALPARAMS structure should have the same information as specified in the original RasDial call.

The second RasDial call cannot be made from within the notification handler.


 Callback Connections

RAS supports connections in which the remote server hangs up and then calls back to the client to establish the connection.

For each user that can connect to a RAS server, the server stores a callback attribute that controls how the connection is made. The default attribute is No Callback, which means that the user can connect to the RAS server without a callback. Alternatively, the administrator of the RAS server can assign to a user either the Preset or Set By Caller callback attribute.


 Preset

For a user assigned the Preset restriction, the administrator specifies a phone number that the RAS server must call back to establish a connection. The user cannot specify a different number, and the connection cannot be made without a callback.

A Preset callback operation is handled automatically by the Remote Access Connection Manager and the remote server. The RAS client application does not need to do anything other than provide feedback to the user when the notification handler is called during the various states of the callback operation.


 Set by Caller

A user assigned the Set By Caller privilege can choose to connect either with or without a callback. The RasDial call uses the szCallBackNumber member of the RASDIALPARAMS structure to indicate the choice.

The szCallBackNumber member can simply specify the callback number; or, to establish the connection without a callback, szCallBackNumber can point to an empty string, "". In either of these cases, the Remote Access Connection Manager handles the connection operation automatically. As with a Preset callback operation, the RAS client does not need to perform any action other than to provide feedback to the user.

If the RasDial call enables paused states, szCallBackNumber can point to an asterisk string, "*", to indicate that the connection operation should enter a paused state to allow the user to type in the callback number. In this case, the connection operation for a Set By Caller user enters a paused state after the remote server has authenticated the user. During the paused state, the RAS client gets the callback number input from the user. The client then resumes the connection operation by making a second RasDial call in which szCallBackNumber specifies the number supplied by the user.

Note that if paused states are not enabled there is a different meaning when szCallBackNumber points to an asterisk string, "*". In this case, the asterisk indicates that the callback number is stored in the phonebook file specified by the RasDial call.


 Disconnecting

When a RAS client application starts a connection operation, the RasDial call receives an HRASCONN connection handle to identify the connection. If the returned handle is not NULL, the client must eventually call the RasHangUp function to end the connection. If an error occurs during the connection operation, the client must call RasHangUp even though the connection was never established.

The application that calls RasHangUp should not exit immediately, because the Remote Access Connection Manager needs time to properly terminate the connection. Instead, the application should wait until the RasGetConnectStatus function returns ERROR_INVALID_HANDLE, indicating that the connection has been deleted.

A RAS client application might need to end a connection even though it does not have the handle returned by RasDial. For example, the application that called RasDial might have exited once the connection was successfully established. In this case, the disconnecting application can use the RasEnumConnections function to get all the current connections. For each connection, RasEnumConnections returns a RASCONN structure containing the HRASCONN connection handle and the phonebook entry name or phone number specified when the connection operation was started. This information can be used to display a list of connections from which the user can select the connection to end.


 Using Remote Access Service

The following topic explains how to use Remote Access Service features in an application.

•	Linking to the remote access DLL


 Linking to the Remote Access DLL

If an application links statically to the RASAPI32 DLL, the application will fail to load if Remote Access Service is not installed. A RAS application can load when RAS is not installed by using LoadLibrary to load the DLL, and GetProcAddress to obtain pointers to the RAS functions.

The Win32 RAS functions are in RASAPI32.DLL. The import library for these functions is RASAPI32.LIB. To use the RAS functions, your programs must include the following files:

File	Description
RAS.H	Contains the RAS function prototypes, constants, and structure definitions.
RASERROR.H	Contains the RAS error codes.


 Remote Access Service Reference

The following functions, strucures, messages, and enumeration types are associated with remote access service.


 Remote Access Service Functions

Use these functions to implement Remote Access Service functionality:

RasCreatePhonebookEntry
RasDial
RasDialFunc
RasDialFunc1
RasEditPhonebookEntry
RasEnumConnections
RasEnumEntries
RasGetConnectStatus
RasGetEntryDialParams
RasGetErrorString
RasGetProjectionInfo
RasHangUp
RasSetEntryDialParams


 Remote Access Service Structures

Use these structures to implement Remote Access Service functionality:

RASAMB
RASCONN
RASCONNSTATUS
RASDIALEXTENSIONS
RASDIALPARAMS
RASENTRYNAME
RASPPPIP
RASPPPIPX
RASPPPNBF


 Remote Access Service Messages

Use this message to implement Remote Access Service functionality:

WM_RASDIALEVENT


 Remote Access Service Enumeration Types

Use these enumeration types to implement Remote Access Service functionality:

RASCONNSTATE
RASPROJECTION


 Resources

A resource is binary data that a resource compiler or developer adds to an application's executable file. A resource can be either standard or defined. The data in a standard resource describes an icon, cursor, menu, dialog box, bitmap, enhanced metafile, font, accelerator table, message-table entry, string-table entry, or version. An application-defined resource, also called a custom resource, contains any data required by a specific application.


 About Resources

This overview describes the functions that enable applications to find a resource in a module; load a resource into memory; add, delete or replace a resource in an executable file; and generate a list of the resources contained in a module. For specific information about the organization of resource data within executable files, refer to the resource formats documentation.

For information about how to create standard resources, refer to the following table.

Resource	Topic
Accelerator table	Keyboard Accelerators
Bitmap	Bitmaps
Cursor	Cursors
Dialog box	Dialog Boxes
Enhanced metafile	Metafiles
Font	Fonts and Text
Icon	Icons
Menu	Menus (Windows NT)
Message-table entry	Your message-compiler documentation
String-table entry	String Manipulation
Version information	File Installation Library
For information about how to include resource data in a Microsoft® Windows® 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, Windows 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, Windows 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 Windows 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 Windows 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.


 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.	The LoadLibrary function loads the executable file HAND.EXE.

2.	The FindResource and LoadResource functions locate and load the dialog box resource named If from the file.

3.	The LockResource function returns a pointer to the dialog box resource data.

4.	The BeginUpdateResource function opens an update handle FOOT.EXE.

5.	The UpdateResource function copies the dialog box resource from HAND.EXE to FOOT.EXE.

6.	The EndUpdateResource function completes the update.

The following code implements these steps.

HRSRC hResLoad;     // handle to loaded resource

HANDLE hExe;        // handle to existing .EXE file

HRSRC hRes;         // handle/ptr. to res. info. in hExe

HANDLE hUpdateRes;  // update resource handle

char *lpResLock;    // pointer to resource data

BOOL result;

// Load the .EXE file that contains the dialog box you want to copy.

hExe = LoadLibrary("hand.exe");

if (hExe == NULL) {

    ErrorHandler("Could not load exe.");

}

// Locate the dialog box resource in the .EXE file.

hRes = FindResource(hExe, "AboutBox", RT_DIALOG);

if (hRes == NULL) {

    ErrorHandler("Could not locate dialog box.");

}

// Load the dialog box into global memory.

hResLoad = LoadResource(hExe, hRes);

if (hResLoad == NULL) {

    ErrorHandler("Could not load dialog box.");

}

// Lock the dialog box into global memory.

lpResLock = LockResource(hRes);

if (lpResLock == NULL) {

    ErrorHandler("Could not lock dialog box.");

}

// Open the file to which you want to add the dialog box resource.

hUpdateRes = BeginUpdateResource("foot.exe", FALSE);

if (hUpdateRes == NULL) {

    ErrorHandler("Could not open file for writing.");

}

// Add the dialog box resource to the update list.

result = UpdateResource(hUpdateRes,       // update resource handle

             RT_DIALOG,                   // change dialog box resource

             "AboutBox",                  // dialog box name

             MAKELANGID(LANG_NEUTRAL,

                 SUBLANG_NEUTRAL),        // neutral language ID

             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 Functions

Following are the functions used with resources.

BeginUpdateResource
CopyImage
EndUpdateResource
EnumResLangProc
EnumResNameProc
EnumResourceLanguages
EnumResourceNames
EnumResourceTypes
EnumResTypeProc
FindResource
FindResourceEx
LoadImage
LoadResource
LockResource
SizeofResource
UpdateResource

Obsolete or Deleted Functions

FreeResource
SetResourceHandler
UnlockResource


 Security

The security provisions of Microsoft® Windows NT™ are available to Windows-based applications automatically. Every application running on the system is subject to the security imposed by the particular configuration of the local implementation of Windows NT.


 About Security

The security functions in the Microsoft Win32® application programming interface (API) allow an application to selectively grant and deny access to an object. An application can specify many different kinds of access for particular users and groups of users. The operating system grants or denies access to an object based on a comparison of the security provisions stored with an object with the access rights specified in a token associated with the process or thread requesting the access. These security functions allow an application to query and manipulate the security features of both an object and a process or thread.

The impact of Windows security on most Windows functions is minimal, and a Windows-based application not requiring security functionality usually does not need to incorporate any special code. However, a developer can use the security features of Windows NT to provide a number of services in a Windows-based application. Generally, any application that manipulates a system-wide resource such as the system time, must use the security system to gain access to that resource. A security-aware application might allow the user to query the security attributes of a file, provide specialized feedback when access to a secure file is denied, or customize the security attributes of a file or group of files so that only a subset of other users on a network has access to the information.

Windows NT is designed to support C2-level security as defined by the US Department of Defense. Some of the most important requirements of C2-level security are shown in the following list.

•	It must be possible to control access to a resource. This access control must include or exclude individual users or named groups of users.

•	Memory must be protected so its contents cannot be read after it is freed by a process.

•	Users must identify themselves in a unique manner when they log on. All auditable actions must identify the user performing the action.

•	System administrators must be able to audit security-related events. Access to this audit data must be limited to authorized administrators.

•	The system must protect itself from external interference or tampering, such as modification of the running system or of system files stored on disk.


 Security Model

All named objects in Windows NT, and some unnamed objects, can be secured. The security attributes of each securable object in Windows are described by a security descriptor, that contains information about the owner of the object and by an access-control list (ACL), identifying the users and groups allowed or denied access to the object. An ACL contains an entry for each user, global group, or local group (alias) being allowed or denied access to the object. Each of these entries is an access-control entry (ACE).

At logon, a user is assigned an access token containing identifiers that represent the user and any groups to which the user belongs. Every process run on behalf of this user will have a copy of this particular access token. When a process attempts to use an object, the system compares the security attributes listed in the access token with the ACEs in the object's ACL. The system compares the access token with each ACE until access is either granted or denied or until there are no more ACEs to check. Conceivably, several ACEs could apply to a token. And, if this occurs, the access rightsaccess rights granted by each ACE accumulate. For example, if one ACE grants read access to a group in an access token and another ACE grants write access to the user, who is also a member of the group, the user will have both read and write access to the object when the access check is complete.

The following illustration shows the relationship between these blocks of security information:

Typically, the application protecting an object is a server in that it defines the users and groups with access to the object. The application interacts with clients when they attempt to gain access to the object. Users and groups are identified by security identifiers (SIDs). An SID is a structure of variable length that uniquely identifies a user or group. SIDs are stored in a security database that an application can query by calling Win32 functions. With one exception, an SID is used to identify a user or group is never reassigned to another user or group. For a given account, the only SID that will not be the same from logon to logon is the logon-identifier SID. In the model represented by the preceding illustration, SIDs would be used to identify the following:

•	The owner and group in the security descriptor

•	The recipient of the access being granted by each ACE

•	The user and groups in the access token

Security descriptors, SIDs, and ACLs are treated by applications as opaque structures and are intended to be manipulated only by using Win32 functions. This helps ensure that these structures remain syntactically accurate and prevents future enhancements to the security system from breaking existing code.

Pointers to doubleword values or structures must be aligned on doubleword boundaries. However, the exception is strings, for which alignment is not critical. All Win32 memory-allocation functions return handles of doubleword-aligned memory objects.


 Access Tokens

When a user logs on, the system verifies the user's password by comparing it with information stored in a security database. If the password is authenticated, the system produces an access token and attaches it to the user's process. This access token identifies the user in all subsequent interactions with securable objects and contains the following information about a process:

•	The user's SID

•	Group SIDs

•	Privileges

•	An owner SID

•	The SID for the primary group

•	The default discretionary access-control list (ACL)

•	The source of the access token

•	Whether the token is a primary or impersonation token

•	Current impersonation levels

•	Other statistics

Every process must have an access token, but even a thread can have one assigned to it. When a thread has an access token, it supersedes the token of the process that owns the thread. This allows individual threads of a server process to impersonate clients by associating a client's access token with the thread. The only exception to this is any action requiring the SE_TCB_NAME privilege. This privilege is always checked against the process token, even if the current thread has an impersonation token.

For more information about privileges, see Privileges. For more information about security identifiers (SIDs), see Security Identifiers (SIDs). For more information about discretionary ACLs, see Access-control Lists (ACLs). For more information about the components of an access token, see the following token structures and enumerated types.

Structure or type	Specifies
TOKEN_CONTROL	Information useful in identifying an access token.
TOKEN_DEFAULT_DACL	The default discretionary ACL for an access token.
TOKEN_GROUPS	Specifies the SIDs of the access token's groups and whether any privileges are enabled.
TOKEN_INFORMATION_CLASS	Information being set in or retrieved from an access token.
TOKEN_OWNER	The SID of an access token's owner.
TOKEN_PRIMARY_GROUP	The SID of the access token's primary group.
TOKEN_PRIVILEGES	The privileges associated with an access token and whether the privileges are enabled.
TOKEN_SOURCE	The source of an access token.
TOKEN_STATISTICS	Statistics associated with an access token.
TOKEN_TYPE	Whether an access token is being used as an impersonation token.
TOKEN_USER	The SID of an access token's user.
Following are the functions an application can use to manipulate access tokens.

Function	Description
AdjustTokenGroups	Changes the group information in an access token.
AdjustTokenPrivileges	Changes the privileges in an access token.
GetTokenInformation	Retrieves information about a token.
OpenProcessToken	Retrieves the handle of the access token for a process.
OpenThreadToken	Retrieves the handle of the access token for a thread.
SetTokenInformation	Changes a token's owner, primary group, or default discretionary ACL.


 Security Descriptors

A security descriptor contains the security information associated with an object. This information can include an owner, a primary group, a discretionary access-control list, and a system access-control list. This information is stored in the form of security identifiers (SIDs) and access-control lists (ACLs). For more information about access-control lists, see Access-control Lists (ACLs).

There are five groups of Win32 functions that manipulate security descriptors, corresponding to five different kinds of objects:

•	Files

•	User Objects (also called window-management objects)

•	Kernel objects

•	Registry objects

•	Private objects

To manipulate security descriptors for files and directories, an application can use the GetFileSecurity and SetFileSecurity functions. These functions identify files and directories by using character strings, instead of using the handles required by other security functions.

Kernel objects and user objects are manipulated by two pairs of functions: GetKernelObjectSecurity and SetKernelObjectSecurity, and GetUserObjectSecurity and SetUserObjectSecurity. Kernel and user objects are separated in this way because it is possible for a file handle and a window handle to have the same value. An application can use these functions to ensure that the correct object referenced.

An application can use the RegGetKeySecurity and RegSetKeySecurity functions to retrieve and set security descriptors for keys in the registry.

The functions that manipulate private objects allow an application, usually a server, to associate a security descriptor with its own object type. The functions provide the ability to retrieve default information from an access token, support inheritance, and manipulate specific parts of the security descriptor. These functions are CreatePrivateObjectSecurity, GetPrivateObjectSecurity, SetPrivateObjectSecurity, and DestroyPrivateObjectSecurity.

The Win32 functions in the following table enable an application to query a security descriptor or set specific information in it.

Function	Description
GetSecurityDescriptorControl	Retrieves revision and control information.
GetSecurityDescriptorDacl	Retrieves the discretionary ACL.
GetSecurityDescriptorGroup	Retrieves primary group information.
GetSecurityDescriptorLength	Returns the length of a security descriptor.
GetSecurityDescriptorOwner	Retrieves the owner of a security descriptor.
GetSecurityDescriptorSacl	Retrieves the system ACL.
SetSecurityDescriptorDacl	Sets discretionary ACL information.
SetSecurityDescriptorGroup	Sets primary group information.
SetSecurityDescriptorOwner	Sets the owner of the security descriptor.
SetSecurityDescriptorSacl	Sets system ACL information.
To check the revision level and structural integrity of a security descriptor, an application can call the IsValidSecurityDescriptor function.

A security descriptor can be in either an absolute or self-relative format. In absolute format, a security descriptor contains pointers to its information, not the information itself. This format is useful when default settings for the owner, group, and discretionary ACL are available, because an application can simply call the InitializeSecurityDescriptor function to initialize a SECURITY_DESCRIPTOR structure and then point to preexisting components, such as SIDs and ACLs.

A security descriptor in self-relative format contains information in a contiguous block of memory. In this format, a SECURITY_DESCRIPTOR structure always starts the information, but the other components of the security descriptor can follow the structure in any order. Instead of using memory addresses, the security descriptor's components are identified by offsets from the beginning of the descriptor. This format is useful when a security descriptor must be stored on disk, transmitted by means of a communications protocol, or copied in memory.

All security descriptors provided by the operating system as the result of calls to Win32 API functions are in self-relative format. Security descriptors passed back to the operating system can be in either form, depending on the situation.

A server that copies secured objects to various media can use the MakeSelfRelativeSD function to create a self-relative security descriptor from an absolute security descriptor. The MakeAbsoluteSD function can create an absolute security descriptor from a self-relative security descriptor.


 Access-control Lists (ACLs)

Part of the security descriptor for each securable object is a list specifying users and groups, and the access to the object each is granted or denied. This list is an access-control list (ACL). An ACL consists of two parts. The first is a header in the form of an ACL structure. This structure contains information pertaining to the entire ACL, such as its revision level and size. The second part is an ordered list of access-control entries (ACEs). Each ACE identifies a user, group, or local group, and the access each of them is allowed.

There are two types of ACLs: discretionary and system.

A discretionary ACL is controlled by the owner of an object and specifies the access particular users or groups can have to an object. For example, the owner of a file can use a discretionary ACL to control who can and cannot have access to the file.

When an object's discretionary ACL contains no access-control entries, no access rights have been explicitly granted. Therefore, access to the object is implicitly denied. However, when an object has no discretionary ACL, no protection is assigned to the object and any access request is granted. For information about setting no ACL for an object, see Allowing Access.

An object may also have system-level security information associated with it, in the form of a system ACL. System ACLs are controlled by system administrators. A system ACL can enable the system administrator to audit any attempts to gain access to an object. In future releases, a system ACL will also be able to raise an alarm when an unauthorized user attempts to gain access to an object.

An application can use Win32 functions to retrieve, initialize, query, and modify ACLs.

Function	Description
GetAclInformation	Retrieves revision or size information about an ACL.
GetSecurityDescriptorDacl	Retrieves a discretionary ACL from a specified security descriptor.
GetSecurityDescriptorSacl	Retrieves a system ACL from a specified security descriptor.
InitializeAcl	Initializes an ACL by creating an empty ACL structure.
IsValidAcl	Determines whether an ACL's revision level and structure are valid.
SetAclInformation	Changes the revision information in an ACL.
SetSecurityDescriptorDacl	Puts a discretionary ACL into a specified security descriptor, superseding any preexisting discretionary ACL.
SetSecurityDescriptorSacl	Puts a system access-control list into a specified security descriptor, superseding any preexisting system ACL.
To change a security descriptor's ACL, an application generally initializes a new ACL, adds ACEs to it, then uses either the SetSecurityDescriptorDacl or SetSecurityDescriptorSacl function to add the new ACL to the security descriptor. GetSecurityDescriptorDacl and GetSecurityDescriptorSacl retrieve a pointer to a preexisting ACL in a security descriptor so an application can copy information from the previous ACL as it creates a new one.


 Access-control Entries (ACEs)

Each of the entries in an access-control list (ACL) is an access-control entry (ACE). Each ACE consists of three parts:

•	A header in the form of an ACE_HEADER structure structure

•	An access mask for the specified ACE type

•	A security identifier (SID)

The ACE_HEADER structure gives information such as the type of the ACE and its size. The access mask is a 32-bit value that specifies the rights being granted, denied, or monitored. The security identifier is in the form of an SID structure and it specifies the user or group to which the ACE applies.

Discretionary ACLs have two types of ACE defined in the AceType member of the ACE_HEADER structure. They are shown in the following table.

Type	Description
ACCESS_ALLOWED_ACE_TYPE	This ACE grants the specified rights to the user or group identified by the security identifier. It is defined by an ACCESS_ALLOWED_ACE structure.
ACCESS_DENIED_ACE_TYPE	This ACE denies the specified rights to the user or group identified by the security identifier. It is defined by an ACCESS_DENIED_ACE structure.
Only one type of ACE, SYSTEM-AUDIT-ACE-TYPE, is currently supported for system ACLs. It specifies what types of access cause system-level audits. This ACE is defined by a SYSTEM_AUDIT_ACE structure.

The SYSTEM_ALARM_ACE_TYPE is not supported in the current version of Windows NT.

Security auditing is used to keep a log of security-significant events, such as which users access a secured file. The SYSTEM_AUDIT_ACE_TYPE ACE is used to generate security audit messages and causes them to be entered into a system audit log for later processing. An administrator can view this log by using Event Viewer (EVENTVWR.EXE) and can manipulate the log by using the event-logging functions.

The order of ACEs in an ACL is important. An access token is checked against the ACEs in an ACL until it either accumulates the access rights it needs, it is explicitly denied access in an access-denied ACE, or it reaches the end of the ACL and is implicitly denied access. If a user is a member of several groups represented by ACEs in the ACL, the rights granted to each group apply to the user. For example, a user may request read and write access to an object protected by an ACE that grants one group read access only. Another ACE may provide protection that grants write access. If the user belongs to both groups, the request will succeed. An ACL typically denies access to specific users or groups of users and allows access to more general categories of users. Although the ACEs in an ACL can be in any order, the security menu items in File Manager and Registry Editor (REGEDT32.EXE) only work with ACLs in which access-denied ACEs precede access-allowed ACEs.

To change a security descriptor's ACL, an application usually initializes a new ACL, adds ACEs to it, and then adds the ACL to the security descriptor. The AddAccessAllowedAce and AddAccessDeniedAce functions add an ACE at the end of a discretionary ACL. The AddAuditAccessAce function adds an ACE at the end of a system ACL. The AddAce function allows an application to specify the position of a new ACE in an ACL, and the DeleteAce function allows an application to remove an ACE from a specified position in one. The GetAce and FindFirstFreeAce functions are especially useful when copying information from a preexisting ACL to a new one.


 Access Masks and Access Rights

An access right defines a particular set of abilities that can be granted or denied to a process when it attempts to use an object. For example, if an application attempts to create a subkey in the registry but does not have the KEY_CREATE_SUB_KEY access right, the system does not carry out the operation. An application usually requests a set of access rights when it opens an object, and in the case of registry keys, it makes that request when it calls the RegOpenKeyEx function.

An access mask is the component of an access-control entry (ACE) that contains the specific rights, standard rights, and generic rights defining the access a user or group has to an object. Access masks are also used to request access rights when an object is opened. For example, an application that needs to set values, create subkeys, and query values in the registry can open a key using an access mask that combines the KEY_WRITE and KEY_QUERY_VALUE access rights.

An access mask is a single 32-bit value. The first 16 bits are the specific rights and apply only to the object type associated with the access mask. Bits 16 through 23 are the standard rights applying to all objects. Bits 28 through 31 are the generic rights mapped to specific and standard rights when access to an object is requested.

Generic access rights are broad types of access whose exact implementation is determined by the application defining an object. These rights are used when protecting an object. For example, an application that defines a voice-annotation object might define specific access rights by using VOICE_PLAY and VOICE_EDIT for playing and editing the object. It might set up a GENERIC_MAPPING structure in which GENERIC_EXECUTE maps to VOICE_PLAY and GENERIC_WRITE maps to both VOICE_PLAY and VOICE_EDIT.

The following are the generic rights that have been defined.

Constant	Meaning
GENERIC_ALL	Read, write, and execute access
GENERIC_EXECUTE	Execute access
GENERIC_READ	Read access
GENERIC_WRITE	Write access
If an application receives GENERIC_WRITE access to a file, for example, it has specific rights allowing it to write and append data to the file, write file attributes, and write extended attributes. In addition, the application has the STANDARD_RIGHTS_WRITE and SYNCHRONIZE standard access rights.

The following constants are masks for the standard access rights.

Constant	Meaning
DELETE	Delete access.
READ_CONTROL	Read access to the security descriptor not including the system ACL.
STANDARD_RIGHTS_ALL	Combines DELETE, READ_CONTROL, WRITE_DAC, WRITE_OWNER, and SYNCHRONIZE access.
STANDARD_RIGHTS_EXECUTE	Currently defined to equal READ_CONTROL.
STANDARD_RIGHTS_READ	Currently defined to equal READ_CONTROL.
STANDARD_RIGHTS_REQUIRED	Combines DELETE, READ_CONTROL, WRITE_DAC, and WRITE_OWNER access.
STANDARD_RIGHTS_WRITE	Currently defined to equal READ_CONTROL.
SYNCHRONIZE	Synchronize access. Allows a thread to wait for the object. This access type is not supported by all object types.
WRITE_DAC	Write access to the discretionary ACL.
WRITE_OWNER	Write access to the owner.
The SPECIFIC_RIGHTS_ALL constant denotes all of the specific rights, even those not be defined for an object.

The system validates each requested access against the process's access token, so requests for broad access can require a great deal of validation time. Therefore, it is generally better for applications to avoid requesting the broadest possible access to an object except when such access is actually required. Certain rights are commonly used in an ACL to deny access to an object, but they are rarely used in requests to open an object. In particular, requesting any of the access rights in the following list has a negative impact on system performance:

EVENT_ALL_ACCESS	SECTION_ALL_ACCESS
FILE_MAP_ALL_ACCESS	SEMAPHORE_ALL_ACCESS
GENERIC_ALL	SERVICE_ALL_ACCESS
KEY_ALL_ACCESS	SPECIFIC_RIGHTS_ALL
MUTEX_ALL_ACCESS	STANDARD_RIGHTS_ALL
PROCESS_ALL_ACCESS	THREAD_ALL_ACCESS
SC_MANAGER_ALL_ACCESS	TOKEN_ALL_ACCESS
The MAXIMUM_ALLOWED constant specifies that an object is to be opened by using all the access rights that are valid for the given user. An additional access type, ACCESS_SYSTEM_SECURITY, is needed to manipulate an object's system ACL. Neither MAXIMUM_ALLOWED nor ACCESS_SYSTEM_SECURITY can be used in an DACL. However, you can use ACCESS_SYSTEM_SECURITY in a SACL to audit use of that bit in an access attempt.

The MapGenericMask function maps a series of generic rights specified in a GENERIC_MAPPING structure to specific and standard rights in an access mask. An application can use the GENERIC_MAPPING structure to specify the access rights for an object when it is created. When a client process requests access to the object, the server can use MapGenericMask to translate the client's requested access into the standard and specific rights for that object.

To discover whether a client process has the proper access rights to an object, a server can call the AccessCheck or AccessCheckAndAuditAlarm function. The AreAllAccessesGranted and AreAnyAccessesGranted functions compare a requested access mask with a granted access mask.


 Security Identifiers (SIDs)

A security identifier (SID) is a unique value of variable length used to identify a user or group. The SID assigned to a user when he or she logs on becomes part of the access token that accompanies any process begun by that user. Except for the logon SID, an SID is always unique. When it has been used to identify a user or group, it cannot be used again, at any time, to identify another user or group.

SIDs identify several separate elements. These include the owner and group in security descriptors, the recipient of the access being granted by access-control entries (ACEs), and the user, as well as groups of which the user is a member in access tokens.

An SID also contains the following information.

•	A 48-bit identifier authority value

•	A revision level

•	A variable number of subauthority values (relative identifiers)

The identifier authority value actually contains two values and is the most important piece of information in an SID. It contains a value identifying the agency that issued the SID, usually representing a Microsoft® Server™ domain, and a 32-bit relative identifier (RID) value, to uniquely identify the user or group in that agency. Joining these values ensures that no two SIDs will be the same, even if two different SID-issuing authorities issue the same RID. Each SID-issuing authority issues a given RID only once.

A standardized shorthand notation for SIDs makes it simpler to visualize their components:

S-R-I-S-S...

In the notation shown above, S identifies the series of digits as an SID, R is the revision level, I is the identifier-authority value, and S is the subauthority value. An SID could be written in this notation as follows:

S-1−4138−86

In this example, the SID has a revision level of 1, an identifier-authority value of 4138, and one subauthority value of 86.

An application is never required to manipulate an SID directly. The following Win32 functions provide all the functionality required to work with SIDs.

Function	Description
AllocateAndInitializeSid	Allocates and initializes an SID with the specified number of subauthorities.
CopySid	Copies a source SID to a buffer.
EqualPrefixSid	Tests two SID prefix values for equality. An SID prefix is the entire SID except for the last subauthority value.
EqualSid	Tests two SIDs for equality. They must match exactly to be considered equal.
FreeSid	Frees an SID previously allocated by using the AllocateAndInitializeSid function.
GetLengthSid	Retrieves the length of an SID.
GetSidIdentifierAuthority	Retrieves a pointer to an SID's identifier authority.
GetSidLengthRequired	Retrieves the size of the buffer required to store an SID with a specified number of subauthorities.
GetSidSubAuthority	Retrieves a pointer to a specified subauthority in an SID.
GetSidSubAuthorityCount	Retrieves the number of subauthorities in an SID.
InitializeSid	Initializes an SID structure.
IsValidSid	Tests the validity of an SID by verifying that the revision number is within a known range and that the number of subauthorities is less than the maximum.
LookupAccountName	Retrieves the SID corresponding to a specified account name. Use the GetUserName function to retrieve the user name for the current thread.
LookupAccountSid	Retrieves the account name corresponding to a specified SID.
Some identifier authorities are predefined, as shown in the following table.

Identifier authority	SID Value
SECURITY_NULL_SID_AUTHORITY	0
SECURITY_WORLD_SID_AUTHORITY	1
SECURITY_LOCAL_SID_AUTHORITY	2
SECURITY_CREATOR_SID_AUTHORITY	3
SECURITY_NT_AUTHORITY	5
The following RID values are also defined.

Relative identifier authority	Value	Superior authority
SECURITY_NULL_RID	0	S-1−0
SECURITY_WORLD_RID	0	S-1−1
SECURITY_LOCAL_RID	0	S-1−2
SECURITY_CREATOR_OWNER_RID	0	S-1−3
SECURITY_CREATOR_GROUP_RID	1	S-1−3
An application can combine an identifier authority and one of these RID values to create an SID that is meaningful on all installations. For example, S-1−1−0 (SECURITY_WORLD_SID_AUTHORITY and SECURITY_WORLD_RID) always identifies the special group representing all users. These security identifiers are universal well-known SIDs. A universal well-known SID is meaningful on all secure systems using this security model, including systems not running Windows NT. The AllocateAndInitializeSid function provides a simple method of combining an identifier authority and an RID.

The following are some universal well-known SIDs.

Universal well-known SID	Value	Identifies
Null SID	(S-1−0−0)	A group with no members. This is often used when an SID value is not known.
World	(S-1−1−0)	A group that includes all users.
Local	(S-1−2−0)	Users who log on to terminals locally (physically) connected to the system.
Creator Owner ID	(S-1−3−0)	A security identifier to be replaced by the security identifier of the user who created a new object. This SID is used in inheritable ACLs.
Creator Group ID	(S-1−3−1)	Identifies a security identifier to be replaced by the primary-group SID of the user who created a new object. Use this SID in inheritable ACLs.
Another predefined identifier authority is SECURITY_NT_AUTHORITY (S-1−5). This identifier authority produces SIDs that are not universal but are meaningful only on Windows NT installations. An application can use the following RID values with SECURITY_NT_AUTHORITY to create well-known SIDs.

Constant	Identifies
SECURITY_DIALUP_RID (S-1−5−1)
	Users who log on to terminals using a dialup modem. This is a group identifier.
SECURITY_NETWORK_RID (S-1−5−2)
	Users who log on across a network. This is a group identifier.
SECURITY_BATCH_RID (S-1−5−3)
	Users who log on using a batch queue facility. This is a group identifier.
SECURITY_INTERACTIVE_RID (S-1−5−4)
	Users who log on for interactive operation. This is a group identifier.
SECURITY_LOGON_IDS_RID (S-1−5−5-X-Y)
	A logon session. This is used to ensure that only processes in a given logon session can gain access to the window-station objects for that session. The X and Y values for these SIDs are different for each logon session. The value SECURITY_LOGON_IDS_RID_COUNT is the number of RIDs in this identifier (5-X-Y).
SECURITY_SERVICE_RID (S-1−5−6)
	An account authorized to perform security services.
SECURITY_LOCAL_SYSTEM_RID (S-1−5−0x12)
	The user account used by the operating system.
SECURITY_BUILTIN_DOMAIN_RID (S-1−5−0x20)
	The built-in system domain.
The following RIDs are relative to each domain.

RID	Identifies
DOMAIN_USER_RID_ADMIN	The administrative user account in a domain.
DOMAIN_USER_RID_GUEST	The guest-user account in a domain. This account can be logged onto automatically by users who do not have an account.
DOMAIN_GROUP_RID_ADMINS	The domain administrator's group. This account exists only on systems running Microsoft® LAN Manager for Windows NT™, not Windows NT systems.
DOMAIN_GROUP_RID_USERS	A group containing all user accounts in a domain. All users are automatically added to this group.
An alias is a local group and is similar to a global group, but it can contain members from other domains. Its members can be users or other groups. Some domain-relative RIDs, such as the following, can be used to form well-known SIDs used as local groups.

RID	Identifies
DOMAIN_ALIAS_RID_ADMINS	A local group used for administration of the domain.
DOMAIN_ALIAS_RID_USERS	A local group representing all users in the domain.
DOMAIN_ALIAS_RID_GUESTS	A local group representing guests of the domain.
DOMAIN_ALIAS_RID_POWER_USERS	A local group used to represent a user or set of users that expect to treat a system as if it were their personal computer rather than a multiuser workstation.
DOMAIN_ALIAS_RID_ACCOUNT_OPS	A local group existing only on systems running Microsoft LAN Manager for Windows NT. This local group permits control over non-administrator accounts.
DOMAIN_ALIAS_RID_SYSTEM_OPS	A local group existing only on systems running Microsoft LAN Manager for Windows NT. This local group performs system administrative functions, not including security functions. It establishes network shares, controls printers, unlocks workstations, and performs other operations.
DOMAIN_ALIAS_RID_PRINT_OPS	A local group existing only on systems running Microsoft LAN Manager for Windows NT. This local group controls printers and print queues.
DOMAIN_ALIAS_RID_BACKUP_OPS	A local group used for controlling assignment of file backup-and-restore privileges.
DOMAIN_ALIAS_RID_REPLICATOR	A local group responsible for copying security databases from the primary domain controller to the backup domain controllers.


 Privileges

A privilege is used to control access to an object or service more strictly than is normal with discretionary access control. A system manager uses privileges to control which users are able to manipulate system resources. An application uses privileges when it changes a system resource, such as when it changes the system time or shuts down the system.

A privilege is a locally unique identifier (LUID) identified by a character string. This 64-bit value is guaranteed to be unique on the operating system that generated it until the system is restarted. For example, SE_SYSTEMTIME_NAME is a string identifying an LUID. A privilege has three representations, as shown below.

•	A string name, meaningful across systems, called a global program name (for example, SE_SYSTEMTIME_NAME).

•	A readable name that can be displayed to the user when necessary. For example, "Change the system time."

•	A local representation that differs from computer to computer.

Privileges provide access to services rarely needed by most users. An account usually has privileges that are disabled, and they must be enabled to be used. For example, to set the time on the local computer, an application has to set the SE_PRIVILEGE_ENABLED attribute for the SE_SYSTEMTIME_NAME privilege. For security reasons, disable an enabled privilege when it is no longer needed.

The following privileges are defined by Windows NT.

Privilege	Description
SE_ASSIGNPRIMARYTOKEN_NAME	Required to assign the primary token of a process.
SE_AUDIT_NAME	Required to generate audit-log entries. Give this privilege to secure servers.
SE_BACKUP_NAME	Required to perform backup operations.
SE_CHANGE_NOTIFY_NAME	Required to receive notifications of changes to files or directories. This privilege also causes the system to skip all traversal access checks. It is enabled by default for all users.
SE_CREATE_PAGEFILE_NAME	Required to create a paging file.
SE_CREATE_PERMANENT_NAME	Required to create a permanent object.
SE_CREATE_TOKEN_NAME	Required to create a primary token.
SE_DEBUG_NAME	Required to debug a process.
SE_INC_BASE_PRIORITY_NAME	Required to increase the base priority of a process.
SE_INCREASE_QUOTA_NAME	Required to increase the quota assigned to a process.
SE_LOAD_DRIVER_NAME	Required to load or unload a device driver.
SE_LOCK_MEMORY_NAME	Required to lock physical pages in memory.
SE_PROF_SINGLE_PROCESS_NAME	Required to gather profiling information for a single process.
SE_REMOTE_SHUTDOWN_NAME	Required to shut down a system using a network request.
SE_RESTORE_NAME	Required to perform restore operations.
SE_SECURITY_NAME	Required to perform a number of security-related functions, such as controlling and viewing audit messages. This privilege identifies its holder as a security operator.
SE_SHUTDOWN_NAME	Required to shut down a local system.
SE_SYSTEM_ENVIRONMENT_NAME	Required to modify the non-volatile RAM of systems that use this type of memory to store configuration information.
SE_SYSTEM_PROFILE_NAME	Required to gather profiling information for the entire system.
SE_SYSTEMTIME_NAME	Required to modify the system time.
SE_TAKE_OWNERSHIP_NAME	Required to take ownership of an object without being granted discretionary access. This privilege allows the owner value to be set only to those values that the holder may legitimately assign as the owner of an object.
SE_TCB_NAME	This privilege identifies its holder as part of the trusted computer base. Some trusted protected subsystems are granted this privilege.
SE_UNSOLICITED_INPUT_NAME	Required to read unsolicited input from a terminal device.
The following functions are provided for working with privileges.

Function	Description
LookupPrivilegeValue	Allows an application to retrieve the LUID corresponding to a privilege on the local system. This is the local representation of that privilege and an application can set it in the TOKEN_PRIVILEGES and LUID_AND_ATTRIBUTES structures.
LookupPrivilegeDisplayName	Retrieves a displayable privilege name. For example, "Force shutdown from a remote system."
LookupPrivilegeName	Retrieves a programmatic privilege name.
PrivilegeCheck	Determines whether a client application has the privileges required to gain access to an object, such as, SE_REMOTE_SHUTDOWN_NAME.


 Impersonation

Impersonation is the ability of a process to take on the security attributes of another process. Typically, a server thread impersonates a client thread to act on behalf of that client to access objects or validate access to its own objects. For example, when a client in a DDE conversation requests information from a DDE server, the server can impersonate the client so the system can verify that the client is allowed access to the information.

Currently, there are three impersonation levels:

Impersonation Level	Meaning
SecurityAnonymous	Indicates the client does not want the server to obtain identification information about the client.
SecurityIdentification	Allows the server to obtain information about the client, such as security identifiers and privileges, without being able to impersonate the client. This is useful for servers who export their own objects, such as tables and views exported by a database product. Using the retrieved client security information, the server is able to make access-validation decisions for itself even though it is unable to use other services as the client.
SecurityImpersonation	Allows the server to impersonate the client's security context on its local system. The server cannot impersonate the client on remote systems.
A fourth level, SecurityDelegation, is not supported in this release of Windows NT.

A DDE server application can impersonate a client by calling the DdeImpersonateClient function. When it has finished the task requiring the impersonation, the DDE server application can revert to its own security information by calling the RevertToSelf function. Similarly, a named-pipe server can use the ImpersonateNamedPipeClient and RevertToSelf functions. The DuplicateToken function creates an impersonation token that duplicates an existing token.

The ImpersonateSelf function enables a thread to generate a copy of its own access token. This is useful when an application needs to change the security attributes of a single thread. For example, sometimes only one thread of a process requires a special privilege.


 Security in New Objects

When an application creates an object, any values explicitly provided in a security descriptor are assigned to the object. If a security descriptor is not explicitly provided, the system searches for security information in different places, depending on the information required.

This guide describes the algorithms for security attribute assignments to newly created objects.


 Assignment of Owner

To assign an owner to a new object when a security descriptor is not provided, the system checks the creator's access token for a default value. If no default value is found, the creator's user identifier (from the access token) is assigned as the object's owner. Even when an owner is provided in a security descriptor, the system checks these values in the access token to make sure the specified owner can be assigned ownership of the object.


 Assignment of Group

To assign a primary group to a new object when a security descriptor is not provided, the system uses the primary group in the creator's access token.


 Assignment of Discretionary ACL

To assign a discretionary access-control list (ACL) to a new object when a security descriptor is not provided, the system checks the parent's discretionary ACL for inheritable access-control entries (ACEs) and creates an ACL from any it finds. If there are no inheritable ACEs, the system checks the creator's security descriptor for a default discretionary ACL. If none is found in the security descriptor, the system looks in the creator's access token. If none of these sources provides a discretionary ACL, the object is created without one, and universal unconditional access to the object is granted.


 Assignment of System ACL

To assign a system ACL to a new object when a security descriptor is not provided, the system checks the parent's system ACL for inheritable ACEs and creates an ACL from any it finds. If there are no inheritable ACEs, the system checks the creator's security descriptor for a default system ACL. When a system ACL is provided explicitly or by default in a security descriptor, the creator of the object must have the SE_SECURITY_NAME privilege, although this privilege is not required if the system ACL is acquired by inheritance. If none of these sources provides a system ACL, the object is created without one.


 Security Attributes Inheritance

The security attributes of an object can be passed from process to process through the mechanism of handle inheritance. In addition, individual ACEs can be inherited in an ACL by new objects.


 Handle Inheritance

If a new process inherits a handle, it also inherits the security attributes associated with that handle. A pointer to a SECURITY_ATTRIBUTES structure is used as a parameter in most Win32 kernel and window-management functions that return object handles. The bInheritHandle member of this structure specifies whether the returned handle is inherited when a new process is created. The security attributes of the inherited handle are identical to those of the original handle.


 ACE Inheritance

Each ACE in an ACL begins with an ACE_HEADER structure structure specifying how that ACE is inherited. Among other things, the flags in an ACE_HEADER structure specify whether the ACE is inherited by container objects (directories or registry keys) or by non-container objects, such as files.

ACE Inheritance in Container Objects

This section outlines the rules governing the inheritance of ACEs by container objects.

If the CONTAINER_INHERIT_ACE flag is set in the ACE_HEADER structure of the parent ACE, a copy of the ACE is added to the end of the inherited ACL and the following actions are performed on the inherited ACE:

•	All inheritance flags in the inherited ACE are cleared.

•	If the ACE contains an access mask and any generic access flags are set, the generic rights are mapped to the standard and specific rights for the child object type.

If neither the CONTAINER_INHERIT_ACE flag nor the NO_PROPAGATE_INHERIT_ACE flag is set, the OBJECT_INHERIT_ACE and INHERIT_ONLY_ACE flags are set. If both the CONTAINER_INHERIT_ACE and the NO_PROPAGATE_INHERIT_ACE are set, the ACE is added to the end of the inherited ACL.

If neither the NO_PROPAGATE_INHERIT_ACE nor the CONTAINER_INHERIT_ACE flag is set in the ACE_HEADER structure of the parent ACE, a copy of the ACE is added to the end of the inherited ACL and its INHERIT_ONLY_ACE flag is set.

Otherwise, the ACE is not inherited.

ACE Inheritance in Non-container Objects

The following rules govern the inheritance of ACEs in objects other than containers.

If the OBJECT_INHERIT_ACE flag is set in the ACE_HEADER structure of the parent ACE, the ACE is copied to the end of the inherited ACL and:

•	The INHERIT_ONLY_ACE flag in the inherited ACE is cleared.

•	The NO_PROPAGATE_INHERIT_ACE, OBJECT_INHERIT_ACE, and CONTAINER_INHERIT_ACE flags in the inherited ACE are cleared.

•	If the ACE contains an access mask and, if any generic access flags are set, the generic rights are mapped to the standard and specific rights for the child object type.

Otherwise, the ACE is not inherited.


 Duplicating Handles

Among cooperating processes, any one process is only as restricted as the least restricted process. For example, a process can call the DuplicateHandle function to duplicate an object handle belonging to a second (source) process into a third (target) process. If the access rights requested for the target process are greater than the rights held by the source process, the system checks the requested access rights against the security context of the process calling DuplicateHandle. If the calling process has the required access rights, the handle is duplicated, and the target process has greater access to the object than the source process.


 Audit Generation

C2-level security requirements specify that system administrators must be able to audit security-related events and that access to this audit data must be limited to authorized administrators. The Win32 API provides functions enabling an administrator to monitor security-related events.

The system access-control list (ACL) contains audit access-control entries (ACEs) for an object. An application can use the GetSecurityDescriptorSacl and SetSecurityDescriptorSacl functions to retrieve an existing system ACL or to set a new one. The AddAuditAccessAce function adds an ACE to a system ACL that causes the system to record specified access attempts in a security log. This security log can be read by using the Microsoft Windows Event Viewer (EVENTVWR.EXE), and can be manipulated by using the event-logging functions discussed in Event Logging. For more information about system ACLs, see Access-control Lists (ACLs).

An application can use the ObjectPrivilegeAuditAlarm function to generate audit and alarm messages whenever a process attempts to complete a privileged operation. The PrivilegedServiceAuditAlarm generates audit and alarm messages whenever a process attempts to perform a privileged system-service operation.

The ObjectCloseAuditAlarm generates audit messages when an object is deleted. The ObjectOpenAuditAlarm function generates audit messages when a process attempts to open or gain access to an object.


 Securable Objects

The kernel and window-management systems contain securable objects. This term refers to an object that has a security descriptor.

All named objects are securable. Some unnamed objects, such as unnamed process and thread objects, have security descriptors also.

You can use Win32 functions to query and set the security attributes of securable objects. The following are types of securable objects and the functions an application can use to manipulate their security attributes.

Object type	Functions
Files and directories	GetFileSecurity, SetFileSecurity
Mailslots	GetFileSecurity, SetFileSecurity
Pipes	GetFileSecurity, SetFileSecurity
Kernel objects (processes, threads, access tokens, and file-mapping objects)	SetKernelObjectSecurity, GetKernelObjectSecurity
Window-management objects (window stations and desktops)	GetUserObjectSecurity, SetUserObjectSecurity
Registry objects	RegGetKeySecurity, RegSetKeySecurity
Service objects	QueryServiceObjectSecurity, SetServiceObjectSecurity
Synchronization objects	SetKernelObjectSecurity, GetKernelObjectSecurity
Private objects (objects private to the creating application)	CreatePrivateObjectSecurity, DestroyPrivateObjectSecurity, GetPrivateObjectSecurity, SetPrivateObjectSecurity


 File and Directory Objects

File and directory objects can be secured only when the New Technology file system (NTFS) is in use.

The access rights for files and directories must be manipulated by using the generic access rights.

For file objects, the handle returned by the CreateFile function has SYNCHRONIZE access and the right to read file attributes, in addition to the access rights specified in the call (GENERIC_READ, GENERIC_WRITE, or both).

GENERIC_READ access for file objects combines STANDARD_RIGHTS_READ and SYNCHRONIZE with rights that allow the process to read data from the file, read file attributes, and read extended attributes.

GENERIC_WRITE access for file objects combines STANDARD_RIGHTS_WRITE and SYNCHRONIZE with rights that allow the process to write data to the file, append data to it, write file attributes, and write extended attributes.

An application cannot use an access-denied ACE to deny only GENERIC_READ or GENERIC_WRITE access to a file. If an application denies GENERIC_WRITE access to a file, SYNCHRONIZE access is implicitly denied. When the CreateFile function is used in an attempt to open the file for read access, the function requests SYNCHRONIZE access and the operation fails. Instead of denying read or write access to a file, an application can explicitly allow the permitted access rights.

For directory objects, the handle returned by the CreateDirectory function has SYNCHRONIZE access and the right to list the contents of the directory.

For more information about files and directories, see Files.


 Mailslot Objects

The handle returned by the CreateMailslot function has GENERIC_READ, SYNCHRONIZE, and WRITE_DAC access to the mailslot object.

GENERIC_READ access for a mailslot combines STANDARD_RIGHTS_READ with rights allowing the process to read data from the mailslot, read mailslot attributes, and read extended attributes.

For more information about mailslots, see Mailslots.


 Pipe Objects

The security attributes of named pipes differ slightly from those of anonymous pipes.


 Access Rights to Named Pipes

The handle returned by the CreateNamedPipe function always has SYNCHRONIZE access. It also has GENERIC_READ, GENERIC_WRITE, or both, depending on the open mode of the pipe. The following are the access rights for each open mode.

Open mode	Access rights
PIPE_ACCESS_DUPLEX	GENERIC_READ, GENERIC_WRITE, and SYNCHRONIZE
PIPE_ACCESS_INBOUND	GENERIC_READ and SYNCHRONIZE
PIPE_ACCESS_OUTBOUND	GENERIC_WRITE  and SYNCHRONIZE
GENERIC_READ access for a named pipe combines STANDARD_RIGHTS_READ access with rights that allow the process to read data from the named pipe and to read named-pipe attributes.

GENERIC_WRITE access for a named pipe combines STANDARD_RIGHTS_WRITE with rights that allow the process to write data to the named pipe and to write named-pipe attributes.


 CreatePipe Function and Anonymous Pipes

The handles returned by the CreatePipe function have GENERIC_READ, GENERIC_WRITE, and SYNCHRONIZE access to the anonymous pipe, in addition to the right to write the attributes of the pipe. GENERIC_READ and GENERIC_WRITE access map to the same access rights as for named pipes.

For more information about pipes, see Pipes.


 Special Access Kernel Objects

The following are the kernel objects for which the system defines special access rights:

•	Processes

•	Threads

•	Access tokens

•	File mapping


 Process Objects

The valid access rights for process objects are STANDARD_RIGHTS_REQUIRED and the rights given in the following table.

Value	Meaning
PROCESS_ALL_ACCESS	Specifies all possible access rights for a process object.
PROCESS_CREATE_PROCESS	Required to create a process.
PROCESS_CREATE_THREAD	Required to create a thread.
PROCESS_DUP_HANDLE	Required to duplicate a handle.
PROCESS_QUERY_INFORMATION	Required to retrieve certain information about a process, such as its priority class.
PROCESS_SET_INFORMATION	Required to set certain information about a process, such as its priority class.
PROCESS_TERMINATE	Required to terminate a process.
PROCESS_VM_OPERATION	Required to perform an operation on the address space of a process.
PROCESS_VM_READ	Required to read memory in a process.
PROCESS_VM_WRITE	Required to write to memory in a process.
SYNCHRONIZE	Required to wait for the process to terminate.
The handle returned by the CreateProcess function has PROCESS_ALL_ACCESS access to the process object.

For more information about processes, see Processes and Threads.


 Thread Objects

The valid access rights for thread objects are STANDARD_RIGHTS_REQUIRED and the rights given in the following table.

Value	Meaning
SYNCHRONIZE	Required to wait for the thread to exit.
THREAD_ALL_ACCESS	Specifies all possible access rights for a thread object. A thread created with THREAD_ALL_ACCESS access is created with its execution suspended.
THREAD_DIRECT_IMPERSONATION	Required for a server thread that impersonates a client.
THREAD_GET_CONTEXT	Required to read the context of a thread using GetThreadContext.
THREAD_IMPERSONATE	Required to use a thread's security information directly without calling it by using a communication mechanism that provides impersonation services.
THREAD_QUERY_INFORMATION	Required to read certain information from the thread object.
THREAD_SET_CONTEXT	Required to write the context of a thread.
THREAD_SET_INFORMATION	Required to set certain information in the thread object.
THREAD_SET_THREAD_TOKEN	Required to set the impersonation token for a thread.
THREAD_SUSPEND_RESUME	Required to suspend or resume a thread.
THREAD_TERMINATE	Required to terminate a thread.
The handle returned by the CreateThread function has THREAD_ALL_ACCESS access to the thread object.

For more information about threads, see Processes and Threads.


 Access-token Objects

A process or thread cannot wait on an access-token object because the access-token object type does not support the SYNCHRONIZE standard access type.

The access rights defined for access-token objects are STANDARD_RIGHTS_REQUIRED and the rights given in the following table.

Value	Meaning
TOKEN_ADJUST_DEFAULT	Required to adjust default information, such as the owner, primary group, and default ACL in an access token.
TOKEN_ADJUST_GROUPS	Required to adjust the groups in an access token.
TOKEN_ADJUST_PRIVILEGES	Required to adjust the privileges in an access token.
TOKEN_ASSIGN_PRIMARY	Required to attach a primary token to a process. The SE_CREATE_TOKEN_NAME privilege is also required to accomplish this task.
TOKEN_DUPLICATE	Required to duplicate an access token.
TOKEN_EXECUTE	Combines STANDARD_RIGHTS_EXECUTE and TOKEN_IMPERSONATE.
TOKEN_IMPERSONATE	Required to attach an impersonation access token to a process.
TOKEN_QUERY	Required to query an access token.
TOKEN_QUERY_SOURCE	Required to query the source of an access token.
TOKEN_READ	Combines STANDARD_RIGHTS_READ and TOKEN_QUERY.
TOKEN_WRITE	Combines STANDARD_RIGHTS_WRITE, TOKEN_ADJUST_PRIVILEGES, TOKEN_ADJUST_GROUPS, and TOKEN_ADJUST_DEFAULT.
The TOKEN_ALL_ACCESS access right combines all possible access rights for a token.

The access rights for tokens are typically specified in calls to the OpenProcessToken and OpenThreadToken functions.


 File Mapping Objects

A process or thread cannot wait on an access-token object because the access-token object type does not support the SYNCHRONIZE standard access type.

The access rights defined for file mapping objects are STANDARD_RIGHTS_REQUIRED and the rights given in the following table.

Value	Meaning
FILE_MAP_READ	Read access to the file-mapping object is requested. This allows a readable view of the file to be mapped.
FILE_MAP_WRITE	Write access to the file mapping object is requested. This allows a writable view of the file to be mapped. If the file mapping access rights do not include PAGE_READWRITE, this access type does not allow writing the mapped file.
SECTION_EXTEND_SIZE	Required to extend the size of a file mapping object.
SECTION_MAP_EXECUTE	Required to complete an operation in a file mapping object.
SECTION_MAP_READ	Equivalent to FILE_MAP_READ.
SECTION_MAP_WRITE	Equivalent to FILE_MAP_WRITE.
SECTION_QUERY	Required to query a file mapping object.
If the call to the CreateFileMapping function specifies the PAGE_READWRITE protection flag, the handle to the file mapping object has SECTION_QUERY | SECTION_MAP_READ | SECTION_MAP_WRITE access. If the call to CreateFileMapping specifies PAGE_READONLY, the handle of the file mapping object has SECTION_QUERY | SECTION_MAP_READ access.

The FILE_MAP_ALL_ACCESS access right specifies all possible access rights for the file mapping object. The SECTION_ALL_ACCESS access right is equivalent to it.

For more information about file-mapping objects, see File Mapping.


 Window-management Objects

The following are the securable window-management objects.

Securable Object	Description
Window station	An 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 display device, keyboard, and mouse. Window stations provide the first level of security for a work station and are the source of inheritable security for desktop objects.
Desktop	An object that has a display surface and contains windows, menus, and hooks. A desktop object is a subobject of a window-station object, from which it inherits security.


Window-station Objects
 Window Station Objects

The following are the window station access rights and their meanings.

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
An application can call the GetProcessWindowStation function to retrieve a handle of its assigned window station. The security attributes of the window station can be retrieved and set by using this handle in calls to the GetUserObjectSecurity and SetUserObjectSecurity functions. An application can use the GetUserObjectInformation and SetUserObjectInformation functions to get and set information about a window-station object. For more information on window-station objects, see Window Stations and Desktops.


 Desktop Objects

A new desktop inherits its security descriptor from its parent window station.

The following are the desktop access rights and their meanings.

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
An application can call the GetThreadDesktop function to retrieve a handle of the desktop for a given thread. The desktop's security attributes can be retrieved and set by using this handle in calls to GetUserObjectSecurity and SetUserObjectSecurity. An application can use the GetUserObjectInformation and SetUserObjectInformation functions to get and set information about a desktop object. For more information on desktop objects, see Window Stations and Desktops.


 Registry Key Objects

The following are the registry-key access rights and their meanings.

Value	Meaning
KEY_ALL_ACCESS	Combines the STANDARD_RIGHTS_REQUIRED, KEY_QUERY_VALUE, KEY_SET_VALUE, KEY_CREATE_SUB_KEY, KEY_ENUMERATE_SUB_KEYS, KEY_NOTIFY, and KEY_CREATE_LINK values.
KEY_CREATE_LINK	Required to create a link to a registry-key object.
KEY_CREATE_SUB_KEY	Required to create a subkey of a registry-key object.
KEY_ENUMERATE_SUB_KEYS	Required to enumerate the subkeys of a registry-key object.
KEY_EXECUTE	Equivalent to KEY_READ.
KEY_NOTIFY	Required to request change notifications for a registry key or for subkeys of a registry key.
KEY_QUERY_VALUE	Required to query a value of a registry-key object.
KEY_READ	Combines the STANDARD_RIGHTS_READ, KEY_QUERY_VALUE, KEY_ENUMERATE_SUB_KEYS, and KEY_NOTIFY values.
KEY_SET_VALUE	Required to create or set a value of a registry-key object.
KEY_WRITE	Combines the STANDARD_RIGHTS_WRITE, KEY_SET_VALUE, and KEY_CREATE_SUB_KEY values.
For more information about registry objects, see Registry.


 Service Objects

The access rights and generic mappings for service-control manager objects and service objects are given in the reference materials for the OpenService and OpenSCManager functions. For information about service objects, see Services.


 Synchronization Objects

There are three kinds of securable synchronization objects: semaphores, events, and mutexes. The fourth type of synchronization object is critical sections. Because they are per-process objects and not kernel objects, they are not securable.


 Semaphore Objects

The valid access rights for semaphore objects are STANDARD_RIGHTS_REQUIRED and the rights given in the following table.

Value	Meaning
SEMAPHORE_ALL_ACCESS	Specifies all possible access rights for a semaphore object.
SEMAPHORE_MODIFY_STATE	Specifies modify state (release) access.
SYNCHRONIZE	Specifies synchronization (wait) access.
The handle returned by the CreateSemaphore function has SEMAPHORE_ALL_ACCESS access to the semaphore object.


 Event Objects

The valid access rights for event objects are STANDARD_RIGHTS_REQUIRED and the rights given in the following table.

Value	Meaning
EVENT_ALL_ACCESS	Specifies all possible access rights for an event object.
EVENT_MODIFY_STATE	Specifies modify state (release) access.
SYNCHRONIZE	Specifies synchronization (wait or release) access.
The handle returned by the CreateEvent function has EVENT_ALL_ACCESS access to the semaphore object.


 Mutex Objects

The valid access rights for mutex objects are STANDARD_RIGHTS_REQUIRED and the rights given in the following table.

Value	Meaning
MUTEX_ALL_ACCESS	Specifies all possible access rights for a mutex object.
MUTEX_MODIFY_STATE	Specifies modify state (release) access.
SYNCHRONIZE	Specifies synchronization (wait or release) access.
The handle returned by the CreateMutex function has MUTEX_ALL_ACCESS access to the mutex object.


 Using Security

The following topics demonstrate some practical applications of the Win32 API security functions and structures. As noted in File and Directory Objects, file objects can be secured only when the NTFS file system is in use.

•	Denying all access

•	Allowing access

•	Setting privileges

•	Security editor

•	Designing a protected server


 Denying All Access

The following example demonstrates adding an empty discretionary access-control list (ACL) to a file's security descriptor. An empty ACL implicitly denies all access to the file.

PSECURITY_DESCRIPTOR pSD;

PACL pACL;

DWORD cbACL = 1024;

/* Initialize a security descriptor. */

pSD = (PSECURITY_DESCRIPTOR) LocalAlloc(LPTR,

    SECURITY_DESCRIPTOR_MIN_LENGTH);   /* defined in WINNT.H */

if (pSD == NULL) {

    ErrorHandler("LocalAlloc");

    return FALSE;

}

if (!InitializeSecurityDescriptor(pSD,

        SECURITY_DESCRIPTOR_REVISION)) { /* defined in WINNT.H */

    ErrorHandler("InitializeSecurityDescriptor");

    goto Cleanup;

}

/* Initialize a DACL. */

pACL = (PACL) LocalAlloc(LPTR, cbACL);

if (pACL == NULL) {

    ErrorHandler("LocalAlloc");

    goto Cleanup;

}

if (!InitializeAcl(pACL, cbACL, ACL_REVISION2)) {

    ErrorHandler("InitializeAcl");

    goto Cleanup;

}

/* Add an empty ACL to the SD to deny access. */

if (!SetSecurityDescriptorDacl(pSD,

        TRUE,     /* fDaclPresent flag  */

        pACL,

        FALSE)) { /* not a default DACL */

    ErrorHandler("SetSecurityDescriptorDacl");

    goto Cleanup;

}

/* Use the new SD as the file's security info. */

if (!SetFileSecurity(lpszTestFile,

        DACL_SECURITY_INFORMATION,

        pSD)) {

    ErrorHandler("SetFileSecurity");

    goto Cleanup;

}

Cleanup:

    if(pSD != NULL)

        LocalFree((HLOCAL) pSD);

    if(pACL != NULL)

        LocalFree((HLOCAL) pACL);


 Allowing Access

The following example demonstrates adding a NULL discretionary ACL to a file's security descriptor. A NULL ACL implicitly allows all access to the file.

Note: It is fine to write code like this that builds security descriptors from scratch. It is, however, a good practice for people who write code that builds or manipulates security descriptors to first write code that explores the default security descriptors that Windows NT places on objects. For example, if Windows NT by default includes in a DACL an ACE granting the Local Logon SID certain access, it's good to know that, so that a decision not to grant any access to the Local Logon SID would be a conscious decision.

PSECURITY_DESCRIPTOR pSD;

/* Initialize a security descriptor. */

pSD = (PSECURITY_DESCRIPTOR) LocalAlloc(LPTR,

    SECURITY_DESCRIPTOR_MIN_LENGTH);   /* defined in WINNT.H */

if (pSD == NULL) {

    ErrorHandler("LocalAlloc");

    return FALSE;

}

if (!InitializeSecurityDescriptor(pSD,

        SECURITY_DESCRIPTOR_REVISION)) { /* defined in WINNT.H */

    ErrorHandler("InitializeSecurityDescriptor");

    goto Cleanup;

}

/* Add a NULL disc. ACL to the security descriptor. */

if (!SetSecurityDescriptorDacl(pSD,

        TRUE,     /* specifying a disc. ACL  */

        (PACL) NULL,

        FALSE)) { /* not a default disc. ACL */

    ErrorHandler("SetSecurityDescriptorDacl");

    goto Cleanup;

}

/* Add the security descriptor to the file. */

if (!SetFileSecurity(lpszTestFile,

        DACL_SECURITY_INFORMATION,

        pSD)) {

    ErrorHandler("SetFileSecurity");

    goto Cleanup;

}

Cleanup:

    if(pSD != NULL)

        LocalFree((HLOCAL) pSD);

Rather than allowing all access by using a NULL ACL, applications generally allow access to an object by adding access-control entries (ACEs) to an ACL. The following example demonstrates finding a security identifier (SID) for a particular account and adding an access-allowed ACE for that account.

    PSECURITY_DESCRIPTOR pSD;

    PACL pACLNew;

    DWORD cbACL = 1024;

    PSID pSID;

    DWORD cbSID = 1024;

    LPSTR lpszAccount = "UserABC";

    LPSTR lpszDomain;

    DWORD cchDomainName = 80;

    PSID_NAME_USE psnuType;

    /* Initialize a new security descriptor. */

    pSD = (PSECURITY_DESCRIPTOR) LocalAlloc(LPTR,

        SECURITY_DESCRIPTOR_MIN_LENGTH);  /* defined in WINNT.H  */

    if (pSD == NULL) {

        ErrorHandler("LocalAlloc");

        return FALSE;

    }

    if (!InitializeSecurityDescriptor(pSD,

            SECURITY_DESCRIPTOR_REVISION)) {

        ErrorHandler("InitializeSecurityDescriptor");

        goto Cleanup;

    }

    /* Initialize a new ACL.                 */

    pACLNew = (PACL) LocalAlloc(LPTR, cbACL);

    if (pACLNew == NULL) {

        ErrorHandler("LocalAlloc");

        goto Cleanup;

    }

    if (!InitializeAcl(pACLNew, cbACL, ACL_REVISION2)) {

        ErrorHandler("InitializeAcl");

        goto Cleanup;

    }

    /* Retrieve the SID for UserABC.         */

    pSID = (PSID) LocalAlloc(LPTR, cbSID);

    psnuType = (PSID_NAME_USE) LocalAlloc(LPTR, 1024);

    lpszDomain = (LPSTR) LocalAlloc(LPTR, cchDomainName);

    if (pSID == NULL || psnuType == NULL ||

        lpszDomain == NULL) {

        ErrorHandler("LocalAlloc");

        goto Cleanup;

    }

    if (!LookupAccountName((LPSTR) NULL, /* local name */

            lpszAccount,

            pSID,

            &cbSID,

            lpszDomain,

            &cchDomainName,

            psnuType)) {

        ErrorHandler("LookupAccountName");

        goto Cleanup;

    }

    if (!IsValidSid(pSID))

        TextOut(hdc, 10, yIncrement += 18,

            "SID is not valid.", 17);

    else

        TextOut(hdc, 10, yIncrement += 18,

            "SID is valid.", 13);

    /* Allow read but not write access to the file. */

    if (!AddAccessAllowedAce(pACLNew,

            ACL_REVISION2,

            GENERIC_READ,

            pSID)) {

        ErrorHandler("AddAccessAllowedAce");

        goto Cleanup;

    }

    /* Add a new ACL to the security descriptor.          */

    if (!SetSecurityDescriptorDacl(pSD,

            TRUE,              /* fDaclPresent flag  */

            pACLNew,

            FALSE)) {          /* not a default disc. ACL */

        ErrorHandler("SetSecurityDescriptorDacl");

        goto Cleanup;

    }

    /* Apply the new security descriptor to the file. */

    if (!SetFileSecurity("d:\\ntfs_sample_file",

            DACL_SECURITY_INFORMATION,

            pSD)) {

        ErrorHandler("SetFileSecurity");

        goto Cleanup;

    }

    TextOut(hdc, 10, yIncrement += 18,

        "Successfully added access-allowed ACE to file's DACL.", 53);

    Cleanup:

        FreeSid(pSID);

        if(pSD != NULL)

            LocalFree((HLOCAL) pSD);

        if(pACLNew != NULL)

            LocalFree((HLOCAL) pACLNew);

        if(psnuType != NULL)

            LocalFree((HLOCAL) psnuType);

        if(lpszDomain != NULL)

            LocalFree((HLOCAL) lpszDomain);


 Setting Privileges

The following example removes the discretionary ACL from a file. If necessary, ownership of the file is given to the Administrator account. If required, the SE_TAKE_OWNERSHIP_NAME privilege is enabled for the account.

LPSTR lpszOwnFile = "d:\\ntfs_sample_file";

PSID pSIDAliasAdmins = NULL;

static SID_IDENTIFIER_AUTHORITY

    siaNTAuthority = SECURITY_NT_AUTHORITY;

BOOL FAR PASCAL TakeOwnership()

{

    SECURITY_DESCRIPTOR sd;

    /*

     * Initialize a security descriptor and assign it a NULL

     * discretionary ACL to allow unrestricted access.

     * Assign the security descriptor to a file.

     */

    if (!InitializeSecurityDescriptor(&sd,

            SECURITY_DESCRIPTOR_REVISION)) {

        ErrorHandler("InitializeSecurityDescriptor");

        return FALSE;

    }

    if (!SetSecurityDescriptorDacl(&sd,

            TRUE,

            (PACL) NULL,

            FALSE)) {

        ErrorHandler("SetSecurityDescriptorDacl");

        return FALSE;

    }

    if (SetFileSecurity(lpszOwnFile,

            DACL_SECURITY_INFORMATION,

            &sd))

        return TRUE;

    else

        ErrorHandler("SetFileSecurity1");

    /*

     * If the preceding call to SetFileSecurity fails, create

     * an Administrator SID and use it to set the owner of

     * the security descriptor.

     */

    if (!AllocateAndInitializeSid(&siaNTAuthority,

            2,                     /* subauthority count  */

                                   /* first subauthority */

            SECURITY_BUILTIN_DOMAIN_RID,

                                   /* second subauthority */

            DOMAIN_ALIAS_RID_ADMINS,

            0, 0, 0, 0, 0, 0,

            &pSIDAliasAdmins)) {

        ErrorHandler("AllocateAndInitializeSid");

        return FALSE;

    }

    if (!SetSecurityDescriptorOwner(&sd,

            pSIDAliasAdmins,

            FALSE)) {

        ErrorHandler("SetSecurityDescriptorOwner");

        FreeSid(pSIDAliasAdmins);

        return FALSE;

    }

    /*

     * If the following call to SetFileSecurity fails,

     * enable SE_TAKE_OWNERSHIP_NAME in the access token for

     * the current process and try again.

     */

    if (!SetFileSecurity(lpszOwnFile,

            OWNER_SECURITY_INFORMATION,

            &sd)) {

        ErrorHandler("SetFileSecurity2");

        if (!AssertTakeOwnership(TRUE)) {   /* local */

            MessageBox(NULL, "Must be logged on as Administrator",

                "AssertTakeOwnership", MB_OK);

            FreeSid(pSIDAliasAdmins);

            return FALSE;

        }

        if (!SetFileSecurity(lpszOwnFile,

                OWNER_SECURITY_INFORMATION,

                &sd)) {

            MessageBox(NULL, "Must be logged on as Administrator",

                "SetFileSecurity", MB_OK);

            FreeSid(pSIDAliasAdmins);

            return FALSE;

        }

    }

    /*

     * The Administrator is now the owner of the file.

     * Try again to assign a NULL ACL.

     */

    if (SetFileSecurity(lpszOwnFile,

            DACL_SECURITY_INFORMATION,

            &sd)) {

        MessageBox(NULL, "Added NULL DACL; protection removed",

            "SetFileSecurity", MB_OK);

        AssertTakeOwnership(FALSE);

        return TRUE;

    }

    else {

        AssertTakeOwnership(FALSE);

        ErrorHandler("SetFileSecurity3");

        return FALSE;

    }

}

BOOL FAR PASCAL AssertTakeOwnership(BOOL fEnable)

{

    HANDLE hToken;

    LUID TakeOwnershipValue;

    TOKEN_PRIVILEGES tkp;

    /* Retrieve a handle of the access token.           */

    if (!OpenProcessToken(GetCurrentProcess(),

            TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,

            &hToken)) {

        ErrorHandler("OpenProcessToken");

        return FALSE;

    }

    /*

     * Enable the SE_TAKE_OWNERSHIP_NAME privilege or

     * disable all privileges, depending on the fEnable

     * flag.

     */

    if(fEnable) {

        if (!LookupPrivilegeValue((LPSTR) NULL,

                SE_TAKE_OWNERSHIP_NAME,

                &TakeOwnershipValue)) {

            ErrorHandler("LookupPrivilegeValue");

            return FALSE;

        }

        tkp.PrivilegeCount = 1;

        tkp.Privileges[0].Luid = TakeOwnershipValue;

        tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

        AdjustTokenPrivileges(hToken,

            FALSE,

            &tkp,

            sizeof(TOKEN_PRIVILEGES),

            (PTOKEN_PRIVILEGES) NULL,

            (PDWORD) NULL);

        /*

         * The return value of AdjustTokenPrivileges cannot

         * be tested.

         */

        if (GetLastError() != ERROR_SUCCESS) {

            ErrorHandler("AdjustTokenPrivileges");

            return FALSE;

        }

    }

    else {

        AdjustTokenPrivileges(hToken,

            TRUE,               /* disable all privileges */

            (PTOKEN_PRIVILEGES) NULL,

            (DWORD) 0,

            (PTOKEN_PRIVILEGES) NULL,

            (PDWORD) NULL);

        /*

         * The return value of AdjustTokenPrivileges cannot

         * be tested.

         */

        if (GetLastError() != ERROR_SUCCESS) {

            ErrorHandler("AdjustTokenPrivileges");

            return FALSE;

        }

    }

    return TRUE;

}


 Security Editor

Both File Manager and the Microsoft Windows NT Registry Editor (REGEDT32.EXE) include a security editor that allows a user with the appropriate privileges and access rights to change the security attributes of files and registry keys. This security editor imposes guidelines on the form of the security information. Applications that modify the security of files, directories, or registry keys can follow these guidelines so the security editor will function correctly after the modifications.

The security editor accepts discretionary ACLs having either zero or more ACCESS_DENIED_ACE access-control entries (ACEs) or zero or more ACCESS_ALLOWED_ACE ACEs. The two ACE types cannot be mixed in a discretionary ACL. Neither does the security editor accept ACCESS_DENIED_ACE ACEs that deny only partial access. For example, it would reject an ACE that denies only read access to a file.

The security editor also imposes a requirement on inheritance flags. These flags are ignored for noncontainer objects, such as files, but are important for container objects, such as directories and registry keys. For container objects that support permissions on objects in the container, make sure that each security identifier (SID) has an ACE inherited by objects and an ACE inherited by containers. Accordingly, the discretionary ACL should contain ACEs in which the AceFlags member of the ACE_HEADER structure structure contains the OBJECT_INHERIT_ACE and CONTAINER_INHERIT_ACE flags. Sometimes these flags can be combined in a single ACE. For example, a discretionary ACL that grants read access to a directory can contain a CONTAINER_INHERIT_ACE ACE that grants GENERIC_READ access to the user or group as well as an ACE with the OBJECT_INHERIT_ACE and INHERIT_ONLY_ACE flags that also grants GENERIC_READ access. In this case, the required flags could be combined into an ACE that grants GENERIC_READ access and combines the CONTAINER_INHERIT_ACE and OBJECT_INHERIT_ACE flags.

The same rules for inheritance flags apply to system ACLs. The security editor does not support the SYSTEM_ALARM_ACE type and will not edit a system ACL containing one. As noted earlier, this ACE type is not supported by the current version of Windows NT.


 Designing a Protected Server

The designer of a server application that assigns security to private object types must make many decisions about the design of the security interface, such as those in the following list:

•	Define object.

•	Determine the types of objects and the access types required, including whether to support SYNCHRONIZE.

•	Determine whether an object is a container or noncontainer, as well as the appropriate inheritance flags. For more information about container objects, see Networks.

•	Define appropriate access types and generic mappings.

•	Determine impersonation characteristics.

•	Develop security descriptor for the initial object and for new objects assembled from the parent's security descriptor and the client's access token.

•	Consider string- versus handle-based object-manipulation functions.

•	Resolve potential conflicts in access rights. For example, decide what is to be done if an administrator and a user both have delete access to an object.

For example, the designer of a protected print server might choose to define a server object, a printer object, and a document object. The three access rights in the following table are likely to be required:

Access right	Description
Administrate	Allows the holder to add objects to and delete them from another object. This right applies to the server, the printers, and the documents.
Enumerate	Allows the holder to list a container object's contents. This right applies to the server and to the printers.
Use	Allow the holder to add items to a print queue. This right applies to the printers.


 Security Functions

Following are the functions used to control security.

AccessCheck
AccessCheckAndAuditAlarm
AddAccessAllowedAce
AddAccessDeniedAce
AddAce
AddAuditAccessAce
AdjustTokenGroups
AdjustTokenPrivileges
AllocateAndInitializeSid
AllocateLocallyUniqueId
AreAllAccessesGranted
AreAnyAccessesGranted
CopySid
CreatePrivateObjectSecurity
DdeImpersonateClient
DeleteAce
DestroyPrivateObjectSecurity
DuplicateToken
EqualPrefixSid
EqualSid
FindFirstFreeAce
FreeSid
GetAce
GetAclInformation
GetFileSecurity
GetKernelObjectSecurity
GetLengthSid
GetPrivateObjectSecurity
GetProcessWindowStation
GetSecurityDescriptorControl
GetSecurityDescriptorDacl
GetSecurityDescriptorGroup
GetSecurityDescriptorLength
GetSecurityDescriptorOwner
GetSecurityDescriptorSacl
GetSidIdentifierAuthority
GetSidLengthRequired
GetSidSubAuthority
GetSidSubAuthorityCount
GetTokenInformation
GetUserObjectSecurity
ImpersonateNamedPipeClient
ImpersonateSelf
InitializeAcl
InitializeSecurityDescriptor
InitializeSid
IsValidAcl
IsValidSecurityDescriptor
IsValidSid
LookupAccountName
LookupAccountSid
LookupPrivilegeDisplayName
LookupPrivilegeName
LookupPrivilegeValue
MakeAbsoluteSD
MakeSelfRelativeSD
MapGenericMask
ObjectCloseAuditAlarm
ObjectOpenAuditAlarm
ObjectPrivilegeAuditAlarm
OpenProcessToken
OpenThreadToken
PrivilegeCheck
PrivilegedServiceAuditAlarm
RevertToSelf
SetAclInformation
SetFileSecurity
SetKernelObjectSecurity
SetPrivateObjectSecurity
SetSecurityDescriptorDacl
SetSecurityDescriptorGroup
SetSecurityDescriptorOwner
SetSecurityDescriptorSacl
SetThreadToken
SetTokenInformation
SetUserObjectSecurity


 Services

In the Microsoft® Win32® application programming interface (API), a service is an executable object that is installed in a registry database maintained by the service control manager.


 About Services

The services database includes information that determines whether each installed service is started on demand or is started automatically when the system starts. The database can also contain logon and security information for a service so that a service can run even though no user is logged on. It also enables system administrators to customize security requirements for each service and thereby control access to the service. No more than one instance of a service can be running at a time.

Services can be divided into these two groups: Win32 services that conform to the interface rules of the service control manager, and driver services that conform to the device driver protocols for Microsoft Windows NT™.


 Service Control Manager

A service control manager provides a unified and secure means of controlling services. Each machine that is running Windows NT has a service control manager process started by the system at system startup. The service control manager is a remote procedure call (RPC) server. The functions in the Win32 API that access a service control manager are provided through an RPC server so that service configuration and service control processes can manipulate services on remote machines.

The Win32 API includes a set of functions that provide a programmer's interface for the following tasks performed by the service control manager:

•	Using the registry to maintain a database of installed service objects.

•	Starting services either when the system is starting up or upon demand.

•	Maintaining status information on running services.

•	Transmitting control requests to running services.

Three types of programs use these functions:

Type	Description
Win32 service process
	A process that provides executable code for one or more services. Win32 services use functions that connect to the service control manager and send status information to it. Driver services do not use these functions.
Service configuration program
	A program that queries or modifies a service control manager database. Service configuration programs use functions that open a database, install or delete services in a database, and query or modify the configuration and security parameters of installed services. The functions are used to manipulate Win32 services and driver services.
Service control program
	A program that starts a service and controls a running service. Service control programs use functions that send requests to the service control manager, which starts the requested service or sends the control request to the specified service.


 Database of Installed Services

The service control manager maintains a ServicesActive database in the registry. This is the currently active database that was used to start the system. The following is the registry path to this database.

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services

In this directory, there is a ServiceName key for each installed Win32 service or driver service. The ServiceName key is the name of the service specified by the CreateService function when the service was installed.

The database includes the following information about each installed service:

•	The type of service. For Win32 services, the service type indicates whether the service executes in its own process or shares a process with other Win32 services. For driver services, it indicates whether the service is a kernel driver or a file system driver.

•	The start type of the service. The start type indicates whether the service is started automatically at system startup or whether the service control manager starts it when requested by a service control process. The start type can also indicate whether the service is disabled, in which case it cannot be started.

•	A fully qualified path of the service's executable file. The filename extension is .EXE for Win32 services and .SYS for driver services.

•	Optional information used by the service control manager to determine the proper order for starting services. This information can include a list of services that must be running before the service can start, the name of a load ordering group that the service is part of, and a tag identifier that indicates the start order of the service in its load ordering group.

•	For Win32 services, an optional logon account name in which the service process runs and an optional password for this account. If no account is specified, the service runs in the LocalSystem account.

•	For driver services, an optional driver object name (for example, \FileSystem\Rdr or \Driver\Xns), used by the I/O system to load the device driver. If no name is specified, the I/O system creates a default name based on the service name.


 Win32 Service Processes

A Win32 service process contains executable code for one or more services. To conform to the interface requirements of the service control manager, it must include:

•	A main function that immediately calls the StartServiceCtrlDispatcher function to connect the main thread of the process to the service control manager.

•	An entry point function, ServiceMain, for each service that can run in the process.

•	A control handler function, Handler, for each service that can run in the process.

For simplicity, the discussions in this section use the term service to mean Win32 service. The information in this section does not apply to driver services.


 Main Function

When the service control manager starts a service process, it waits for the process to call the StartServiceCtrlDispatcher function. If a service does not share a process with other services (SERVICE_WIN32_OWN_PROCESS services), the main thread of a service process should make this call immediately, leaving all initialization tasks to be performed by the ServiceMain function after the service starts. For services where multiple services share a process (SERVICE_WIN32_SHARE_PROCESS services) and where some common process-wide initialization needs to be done before any ServiceMain function is called, the main thread can do the work before calling StartServiceCtrlDispatcher, as long as it takes less than 30 seconds. Otherwise, another thread must be created to do the process-wide initialization, while the main thread calls StartServiceCtrlDispatcher. Any service specific initialization should still be done by the individual ServiceMain functions.

If StartServiceCtrlDispatcher succeeds, it connects the calling thread to the service control manager and does not return until all running services in the process have terminated. The service control manager uses this connection to send control and service start requests to the main thread of the service process. The main thread acts as a dispatcher by calling the appropriate Handler function to handle control requests or by creating a new thread to execute the appropriate ServiceMain function when a new service is started.

The StartServiceCtrlDispatcher function specifies a dispatch table containing an entry for each service that can run in the calling process. Each entry specifies the ServiceMain function for that service. For SERVICE_WIN32_SHARE_PROCESS services, each entry must contain the name of a service. This name is the service name that was specified by the CreateService function when the service was installed. For SERVICE_WIN32_OWN_PROCESS services, the service name in the table entry is ignored.


 ServiceMain Function

The ServiceMain function is the entry point for a service. When a service control program calls the StartService function and the service process for this service is not yet running, the service control manager starts the process and sends a start request to the dispatcher in the service's main thread. The dispatcher creates a new thread to execute the ServiceMain function for the service.

A ServiceMain function should perform the following tasks:

1.	Call the RegisterServiceCtrlHandler function immediately to register a Handler function to handle control requests for the service. The return value of RegisterServiceCtrlHandler is a SERVICE_STATUS_HANDLE type that identifies the service in calls to the SetServiceStatus function. A service calls SetServiceStatus to inform the service control manager of its status.

2.	Perform initialization. If the execution time of the initialization code is expected to be very short (less than one second), initialization can be performed directly in ServiceMain.

If the initialization time is expected to be longer than one second, call SetServiceStatus, specifying SERVICE_START_PENDING as the current service state. As initialization continues, the service should make additional calls to SetServiceStatus to report progress. Sending multiple SetServiceStatus calls is useful for both service debugging and product support.

The following members of the SERVICE_STATUS structure passed in SetServiceStatus calls should change as the initialization progresses:

Member	Value
dwCurrentState	Set this value to SERVICE_START_PENDING during initialization. Set it to SERVICE_RUNNING when initialization is complete.
dwControlsAccepted	You can disable control codes during initialization and enable them when initialization is complete.
dwCheckPoint	Increment this value each time SetServiceStatus.  is called. That informs the service control manager of the progress of a lengthy initialization.
dwWaitHint	This value is an estimate of how long it will take to complete the next initialization step. It should reflect a worst-case estimate of the amount of time, in milliseconds, that will elapse before the next pending call to SetServiceStatus. If this interval elapses and dwCheckPoint has not been incremented, the service control manager or service control program can assume that an error has occurred.
3.	When initialization is complete, call SetServiceStatus to specify the current state as SERVICE_RUNNING. The ServiceMain function can then go on to perform the service tasks, or, if there are no pending tasks, it can return. Any change in the state of the service warrants a call to SetServiceStatus to report new status information. If the service stops due to an error, the service should use the dwServiceSpecificExitCode and dwWin32ExitCode members of the SERVICE_STATUS structure to identify the error.


 The Control Handler Function

Each Win32 service has a control handler function, the Handler function, that is invoked by the main thread's dispatcher when the service process receives a control request. Control requests are generated by application programs that call the ControlService function. To register a Handler function, the service's ServiceMain function calls RegisterServiceCtrlHandler.

Whenever a service's Handler function is invoked, the service must call the SetServiceStatus function to report its status to the service control manager. This call must be done regardless of whether the status changed.

There is a set of standard control codes that the ControlService function can specify. All services must accept and process the SERVICE_CONTROL_INTERROGATE control code. Any of the other standard control codes can be enabled or disabled by calling SetServiceStatus. Services can also handle additional user-defined control codes, which must be in the range 128 to 255.

The standard control codes are listed below:

Control	Meaning
SERVICE_CONTROL_STOP
	Requests the service to stop.
SERVICE_CONTROL_PAUSE
	Requests the service to pause.
SERVICE_CONTROL_CONTINUE
	Requests the paused service to resume.
SERVICE_CONTROL_INTERROGATE
	Requests the service to immediately update its current status information to the service control manager.
SERVICE_CONTROL_SHUTDOWN
	Requests the service to perform cleanup tasks, because the system is shutting down. Due to the extremely limited time available for shutdown, this control code should be used only by services that must perform a specific cleanup operation that takes a minimal amount of time before the system shuts down. The Event Log and Server services are examples of services that handle SERVICE_CONTROL_SHUTDOWN. The Event Log service needs to clear a dirty bit in the files that it maintains. The Server service needs to shutdown to prevent future network connections to a system that is shut down.
	To respond quickly to the SERVICE_CONTROL_SHUTDOWN code, the service may send a SERVICE_STOP_PENDING message and allow another thread to complete the shutdown operation. Service shutdown is complete when the SERVICE_STOPPED message is sent. The system gives the service control manager a limited amount of time (about 20 seconds) to complete service shutdown, after which time system shutdown proceeds regardless of whether service shutdown is complete. .


 Service Configuration Programs

Service configuration programs are used by programmers or system administrators to query or modify a service control manager database. These databases are maintained in the registry, so they can also be accessed by using the registry functions or a registry editor. It is, however, safer to use the service control manager's configuration functions, which ensure that the service is installed and configured properly.

Service control manager databases and services are implemented as objects that should only be accessed through the service control manager's configuration functions. A database of installed services is represented by an SCManager object, and an installed service is represented by a service object. An SCManager object is a container object that holds service objects.

The handle type of both SCManager objects and service objects is SC_HANDLE. The OpenSCManager function returns a handle to an SCManager object on a specified machine. The CreateService and OpenService functions return a handle to a service object installed in a specified SCManager object. The CloseServiceHandle function closes SC_HANDLE to either an SCManager object or a service object.

The functions that return SC_HANDLE can request different types of access to the SCManager or service object. The requested access is granted or denied depending on the access token of the calling process and the security descriptor associated with the SCManager or service object.

A configuration program uses the CreateService function to install a new service in an service control manager database. This function specifies the name of the service and provides the service's configuration information that is stored in the database. For a description of the information stored in the database for each service, see Database of Installed Services.The DeleteService function removes an installed service from its database.

The following functions are available to determine the current configuration of a service control manager database:

Function	Description
QueryServiceConfig
	Fills in a buffer with a QUERY_SERVICE_CONFIG structure, containing the current configuration information for a specified service object.
QueryServiceObjectSecurity
	Fills in a buffer with the SECURITY_DESCRIPTOR structure of a specified SCManager or service object.
EnumDependentServices
	Fills in a buffer with an array of ENUM_SERVICE_STATUS structures, containing the name and current status of all services that are dependent on a specified service object.
EnumServicesStatus
	Fills in a buffer with an array of ENUM_SERVICE_STATUS structures, containing the name and current status of all services in a specified SCManager object.
To modify the configuration information for a service object, a configuration program uses the ChangeServiceConfig function. To modify the security descriptor for either an SCManager object or a service object, a configuration program uses the SetServiceObjectSecurity function.

Before using either of these functions to reconfigure a service object, a program should use the LockServiceDatabase function. This function tries to acquire a lock on the specified service control manager database and, if successful, prevents the service control manager from starting a service while the database is being reconfigured. A lock should also be acquired before using the registry functions to reconfigure a service object. Note, however, that failure to acquire a lock does not prevent a configuration program from successfully reconfiguring a service object. The only effect of a lock is to prevent the service control manager from starting a service in the locked database. To release the lock on the database when the reconfiguration is complete, use the UnlockServiceDatabase function. To determine whether the database is locked, use the QueryServiceLockStatus function.


 Service Control Programs

A service control program performs the following actions:

•	Starts a Win32 service or a driver service, if the service's start type is SERVICE_DEMAND_START.

•	Sends control requests to a running service.

•	Queries the current status of a running service.

The program must have an open handle to any service object that it wants to start or control. To do this, it must perform these steps:

1.	Use the OpenSCManager function to open a handle to a service control manager database on a specified machine.

2.	Use the OpenService or CreateService function to open a handle to the desired service object.


 Service Startup

To start a service, use the StartService function. For Win32 services, the calling process can use the parameters of this function to specify an array of arguments that are passed to the ServiceMain function of the service. This function fails if the service control manager database is locked. If this occurs, the service control program can wait a few seconds and call StartService again. It can check the current lock status of the database by calling the QueryServiceLockStatus function.

When starting a driver service, StartService returns after the device driver has completed its initialization.

When starting a Win32 service, StartService returns after the ServiceMain function thread for the new service has been created. During its initialization, a service specifies a SERVICE_STATUS structure in calls to the SetServiceStatus function to report its progress to the service control manager. The service control program can retrieve this status information by calling the QueryServiceStatus function. During initialization, the dwCurrentState member of the SERVICE_STATUS structure should be SERVICE_START_PENDING. The service should increment the dwCheckPoint member at regular intervals during initialization. The dwWaitHint member is a time interval, in milliseconds, that indicates how long the service control program should wait before calling QueryServiceStatus again. When the initialization is complete, the service changes the dwCurrentState member to SERVICE_RUNNING.


 Service Control Requests

To send control requests to a running service, use the ControlService function. This function specifies a control value that is passed to the Handler function of the specified service. This control value can be a user-defined code, or it can be one of the standard codes that enable the calling program to perform the following actions:

•	Stops or pauses a service.

•	Resumes a paused service.

•	Gets updated status information from a service.

Each service specifies the control values that it will accept and process. To determine which of the standard control values are accepted by a service, use the QueryServiceStatus function or specify the SERVICE_CONTROL_INTERROGATE control value in a call to the ControlService function. The dwControlsAccepted member of the SERVICE_STATUS structure returned by these functions indicates whether the service can be stopped and whether it can be paused and resumed. All services accept the SERVICE_CONTROL_INTERROGATE control value, which requests the service to immediately report its current status.

Note, however, that the QueryServiceStatus function reports the service control manager's most recent status for a specified service, but does not get an updated status from the service itself. Using the SERVICE_CONTROL_INTERROGATE control value in a call to ControlService ensures that the status information returned is current.


 Service Security

When a process uses the OpenSCManager function to open a handle to a service control manager database, the system performs a security check before granting the requested access. All processes are permitted SC_MANAGER_CONNECT, SC_MANAGER_ENUMERATE_SERVICE, and SC_MANAGER_QUERY_LOCK_STATUS access to all service control manager databases. This access enables any process to open a service control manager database handle that it can use for the OpenService, EnumServicesStatus, and QueryServiceLockStatus functions. Only processes with Administrator privileges are able to open a database handle that can be used by the CreateService and LockServiceDatabase functions.

Security for service objects is provided by an access check performed when a process uses the OpenService function. The access permitted to different users depends on the SECURITY_DESCRIPTOR structure associated with the service object. The service control manager creates a service object's security descriptor when the service is installed by the CreateService function. You can use the QueryServiceObjectSecurity and SetServiceObjectSecurity functions to query and set the security descriptor of a service object. The default security descriptor of a service object permits the following access:

•	All users have SERVICE_QUERY_CONFIG, SERVICE_QUERY_STATUS, SERVICE_ENUMERATE_DEPENDENTS, SERVICE_INTERROGATE, and SERVICE_USER_DEFINED_CONTROL access.

•	Local users have SERVICE_START access in addition to those listed above.

•	LocalSystem users and PowerUsers have SERVICE_START, SERVICE_PAUSE_CONTINUE, and SERVICE_STOP access in addition to those listed above.

•	Administrators have SERVICE_ALL_ACCESS access.


 Win32 Service User Accounts

Each Win32 service runs in a user account. The user name and password of an account are specified by the CreateService function at the time the service is installed. The user name and password can be changed by using the ChangeServiceConfig function. You can use the QueryServiceConfig function to get the user name (but not the password) of a service object.

When starting a service process, the service control manager logs on to the account associated with the service. If the log on is successful, the system produces an access token and attaches it to the new service process. This token identifies the service process in all subsequent interactions with securable objects (objects that have a security descriptor associated with them). For example, if the service tries to open a handle to a pipe, the system compares the service's access token to the pipe's security descriptor before granting access.

A SERVICE_WIN32_OWN_PROCESS service that runs in a process by itself can have an account from either the built-in (local), primary, or trusted domain. A SERVICE_WIN32_SHARE_PROCESS service that can share a process with multiple services must be installed to run in the LocalSystem account. This restriction exists because different services in the same process must run under the same security context.

The service control manager does not try to maintain the passwords of service user accounts. If a password is expired, the logon fails and the service fails to start. The system administrator who assigns accounts to services can create accounts with passwords that never expire. The administrator can also manage accounts with passwords that expire by using a service configuration program to periodically change the passwords.

If a service needs to recognize another service before sharing its information, the second service can either use the same account as the first service, or it can run in an account belonging to an alias that is recognized by the first service. Services that need to run in a distributed manner across the network should run in domain-wide accounts.


 Interactive Services

An interactive service is a Win32 service that allows the user's desktop to interact with the service. Interactive services run in the LocalSystem account. Services are configured to be interactive when the dwServiceType parameter in a CreateService call is set to include the SERVICE_INTERACTIVE_PROCESS bit flag. SERVICE_INTERACTIVE_PROCESS may be used only with the SERVICE_WIN32_OWN_PROCESS or SERVICE_WIN32_SHARE_PROCESS flags. This bit flag affects only the service process when it is created (that is, when the first service in the process is started).

The following key in the registry contains a value called NoInteractiveServices that controls the effect of the SERVICE_INTERACTIVE_PROCESS flag:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Windows

The NoInteractiveServices value defaults to 0, which means that services marked with the SERVICE_INTERACTIVE_PROCESS flag will be allowed to be interactive. When the NoInteractiveServices value is set to nonzero, any service started thereafter, regardless of whether it has been configured with SERVICE_INTERACTIVE_PROCESS, will not be allowed to run interactively. Setting NoInteractiveServices to nonzero completely guarantees a secure system.


 Using Services

•	Writing a Win32 service process's main function

•	Writing a ServiceMain function

•	Writing a control handler function

•	Opening an SCManager database

•	Installing a service

•	Deleting a service

•	Changing a service configuration

•	Querying a service's configuration

•	Starting a service

•	Sending control requests to a service


 Writing a Win32 Service Process's main Function

The main function of a Win32 service process calls the StartServiceCtrlDispatcher function to connect to the service control manager and start the control dispatcher thread. The dispatcher thread loops, waiting for incoming control requests for the services specified in the dispatch table. This thread does not return unless there is an error or all of the services in the process have terminated. When all services in a process have terminated, the service control manager sends a control request to the dispatcher thread telling it to shut down. The thread can then return from the StartServiceCtrlDispatcher call and the process can terminate.

The example provided in this section demonstrates a service process that supports only one service. Service processes with a single service call StartServiceCtrlDispatcher immediately because its entry-point function, ServiceMain, can perform all necessary initialization.

If your service process supports multiple services, the implementation of the main function may differ slightly. The names of the additional services are added to the dispatch table so they can be monitored by the dispatcher thread. Some multiple service processes may need to perform process-wide initialization tasks before starting any of the services with the StartServiceCtrlDispatcher call. If this is the case and the initialization is brief (less than 30 seconds), the main thread can take care of it before calling StartServiceCtrlDispatcher. If this initialization typically lasts longer than 30 seconds, one of the following strategies can be used:

•	Call CreateThread to create a thread to perform the process-wide initialization.

•	Use a global flag that each service checks during its initialization so that the first service to start up performs the tasks that are process-wide.

The following example calls a local function, SvcDebugOut, to print informational messages and errors to the debugger, and a Win32 function, GetLastError, to retrieve a detailed error code when RegisterServiceCtrlHandler fails. SvcDebugOut takes two parameters: a single string that can contain one formatted output character and a numeric value to be used as the formatted character.

/* Globals */

SERVICE_STATUS          MyServiceStatus;

SERVICE_STATUS_HANDLE   MyServiceStatusHandle;

/* Function Prototypes */

VOID  MyServiceStart (DWORD   argc, LPTSTR  *argv);

VOID  MyServiceCtrlHandler (IN  DWORD opcode);

DWORD MyServiceInitialization(DWORD argc, LPTSTR  *argv,
        DWORD  *specificError);

VOID _CRTAPI1 main(void)

{

    SERVICE_TABLE_ENTRY   DispatchTable[] = {

        { TEXT("MyService"),    MyServiceStart      },

        { NULL,                 NULL                }

    };

    if (!StartServiceCtrlDispatcher( DispatchTable)) {

        SvcDebugOut(" [MY_SERVICE] StartServiceCtrlDispatcher error =
                    %d\n", GetLastError());

    }

}

VOID SvcDebugOut(LPSTR String, DWORD Status)

{

    CHAR  Buffer[1024];

    if (strlen(String) < 1000)  {

        sprintf(Buffer, String, Status);

        OutputDebugStringA(Buffer);

    }

}


 Writing a ServiceMain Function

The MyServiceStart function in the following example is the service's entry point. When the control dispatcher is told to start a service, it creates a thread that will begin executing at this point. MyServiceStart has access to command-line arguments in the same manner as does the typical main function. The first parameter contains the number of arguments being passed to the service. There will always be at least one argument. The second parameter is a pointer to an array of string pointers. The first item in the array always points to the service name.

MyServiceStart first fills in the SERVICE_STATUS structure including the control codes that it will accept. Note that although this service accepts PAUSE_CONTINUE, it does nothing significant when told to pause. PAUSE_CONTINUE was included for illustration purposes only; if pausing does not add value to your service, do not support it. The dwCheckPoint, dwWaitHint, and the exit code fields are all initialized to zero.

MyServiceStart then calls the RegisterServiceCtrlHandler function to register MyService as the service's Handler function and begin initialization. The following sample initialization function, MyServiceInitialization, is included for illustration purposes; it does not perform any initialization tasks such as creating additional threads. If your service's initialization performs tasks that are expected to take longer than one second, your code must call SetServiceStatus periodically to send out wait hints and check points indicating that progress is being made.

When initialization has completed successfully, a call to SetServiceStatus with a status of SERVICE_RUNNING is made and the service can continue with its work. If an error has occurred in initialization, MyServiceStart reports SERVICE_STOPPED with the SetServiceStatus call and returns.

Since this sample service does not do anything, MyServiceStart simply returns control to the caller. However, a real service should use this thread to do whatever work it was designed to do. The ServiceMain function for a service that does not need a thread to do its work, such as a service that processes only RPC requests, should return control to the caller. It is important to return, rather than call the ExitThread function, because returning allows for cleanup of the memory allocated for the arguments.

To output debugging information, MyServiceStart calls SvcDebugOut. The source code for SvcDebugOut is listed in Writing a Win32 Service Process's main Function.

void MyServiceStart (DWORD   argc, LPTSTR  *argv)

{

    DWORD   status;

    DWORD   specificError;

    MyServiceStatus.dwServiceType        = SERVICE_WIN32;

    MyServiceStatus.dwCurrentState       = SERVICE_START_PENDING;

    MyServiceStatus.dwControlsAccepted   = SERVICE_ACCEPT_STOP |

        SERVICE_ACCEPT_PAUSE_CONTINUE;

    MyServiceStatus.dwWin32ExitCode      = 0;

    MyServiceStatus.dwServiceSpecificExitCode = 0;

    MyServiceStatus.dwCheckPoint         = 0;

    MyServiceStatus.dwWaitHint           = 0;

    MyServiceStatusHandle = RegisterServiceCtrlHandler(

                            TEXT("MyService"),

                            MyServiceCtrlHandler);

    if (MyServiceStatusHandle == (SERVICE_STATUS_HANDLE)0) {

        SvcDebugOut(" [MY_SERVICE] RegisterServiceCtrlHandler
                    failed %d\n", GetLastError());

        return;

    }

    // Initialization code goes here.

    status = MyServiceInitialization(argc,argv, &specificError);

    // Handle error condition

    if (status != NO_ERROR) {

        MyServiceStatus.dwCurrentState       = SERVICE_STOPPED;

        MyServiceStatus.dwCheckPoint         = 0;

        MyServiceStatus.dwWaitHint           = 0;

        MyServiceStatus.dwWin32ExitCode      = status;

        MyServiceStatus.dwServiceSpecificExitCode = specificError;

        SetServiceStatus (MyServiceStatusHandle, &MyServiceStatus);

        return;

    }

    // Initialization complete - report running status

    MyServiceStatus.dwCurrentState       = SERVICE_RUNNING;

    MyServiceStatus.dwCheckPoint         = 0;

    MyServiceStatus.dwWaitHint           = 0;

    if (!SetServiceStatus (MyServiceStatusHandle, &MyServiceStatus)) {

        status = GetLastError();

        SvcDebugOut(" [MY_SERVICE] SetServiceStatus error
            %ld\n",status);

    }

    // This is where the service does its work.     //

    SvcDebugOut(" [MY_SERVICE] Returning the Main Thread \n",0);

    return;

}

/* stub initialization function */

DWORD MyServiceInitialization(DWORD   argc, LPTSTR  *argv,
        DWORD *specificError)

{

    argv;

    argc;

    specificError;

    return(0);

}


 Writing a Control Handler Function

The MyServiceCtrlHandler function in the following example is the service's Handler function. When this function is called by the dispatcher thread, it handles the control code passed in the parameter Opcode and then calls the SetServiceStatus function to update the service's status. Every time a Handler function receives a control code, it is appropriate to return status with a call to SetServiceStatus regardless of whether the service operates on the control.

The Handler function executes in the context of the dispatcher thread. Therefore, this function should not perform time-consuming operations. If an operation such as a stop request is going to take a long time, the Handler function should send the SERVICE_STOP_PENDING message in a call to SetServiceStatus and then signal the other service thread(s), if necessary, that a stop operation is in progress. Then the function should return so that the dispatcher can service more requests. One of the other service threads becomes responsible for sending further wait hints and the final SERVICE_STOPPED message.

Note that when the pause control is received, MyServiceCtrlHandler simply sets the dwCurrentState field in the SERVICE_STATUS structure to SERVICE_PAUSED. Likewise, when the continue control is received, the state is set to SERVICE_RUNNING. Note that MyServiceCtrlHandler is not presented as an accurate example of how to handle the pause and continue controls. Since MyServiceCtrlHandler is a template for a Handler function, code for the pause and continue controls is included for completeness. A real service that supports either the pause or continue control should handle these controls in whatever way makes sense for that service. Many services support neither the pause or continue control. If the service indicates that it does not support pause or continue with the dwControlsAccepted parameter, then the service control manager will not send pause or continue controls to the service's Handler function.

When handling the stop request for a service that will take a long time, the current thread should create another thread or ask an existing one to handle the stop process. The current thread should simply call SetServiceStatus with the SERVICE_STOP_PENDING message and return to the caller.

To output debugging information, MyServiceCtrlHandler calls SvcDebugOut. The source code SvcDebugOut is listed in Writing a Win32 Service Process's main Function.

VOID MyServiceCtrlHandler ( IN  DWORD   Opcode)

{

    DWORD   status;

    switch(Opcode) {

    case SERVICE_CONTROL_PAUSE:

        /* Do whatever it takes to pause here.

        MyServiceStatus.dwCurrentState = SERVICE_PAUSED;

        break;

    case SERVICE_CONTROL_CONTINUE:

        /* Do whatever it takes to continue here.

        MyServiceStatus.dwCurrentState = SERVICE_RUNNING;

        break;

    case SERVICE_CONTROL_STOP:

        /* Do whatever it takes to stop here.

        MyServiceStatus.dwWin32ExitCode = 0;

        MyServiceStatus.dwCurrentState  = SERVICE_STOPPED;

        MyServiceStatus.dwCheckPoint    = 0;

        MyServiceStatus.dwWaitHint      = 0;

        if (!SetServiceStatus (MyServiceStatusHandle, &MyServiceStatus))
        {

            status = GetLastError();

            SvcDebugOut(" [MY_SERVICE] SetServiceStatus error
                %ld\n",status);

        }

        SvcDebugOut(" [MY_SERVICE] Leaving MyService \n",0);

        return;

    case SERVICE_CONTROL_INTERROGATE:

        /* fall through to send current status

        break;

    default:

        SvcDebugOut(" [MY_SERVICE] Unrecognized opcode %ld\n", Opcode);

    }

    /* Send current status.

    if (!SetServiceStatus (MyServiceStatusHandle,  &MyServiceStatus)) {

        status = GetLastError();

        SvcDebugOut(" [MY_SERVICE] SetServiceStatus error
            %ld\n",status);

    }

    return;

}


 Opening an SCManager Database

The examples in the following sections require an open handle to an SCManager database object. Different operations on a service control manager database require different levels of access, and you should only request the minimum access required. If SC_MANAGER_ALL_ACCESS is requested, the OpenSCManager function fails if the calling process does not have administrator privileges. The following example shows how to request full access to the ServicesActive database on the local machine.

/* Open a handle to the SC Manager database. */

schSCManager = OpenSCManager(

     NULL,                   /* local machine           */

     NULL,                   /* ServicesActive database */

     SC_MANAGER_ALL_ACCESS); /* full access rights      */

if (schSCManager == NULL)

    MyErrorExit("OpenSCManager");


 Installing a Service

A service configuration program uses the CreateService function to install a service in a service control manager database. The application-defined schSCManager handle must have SC_MANAGER_CREATE_SERVICE access to the SCManager object. The following example shows how to install a service.

VOID CreateSampleService() {

LPCTSTR lpszBinaryPathName =

          TEXT("%SystemRoot%\\system\\testserv.exe");

  schService = CreateService(

       schSCManager,              /* SCManager database      */

       TEXT("Sample_Srv"),        /* name of service         */

        lpszDisplayName,          /* service name to display */

       SERVICE_ALL_ACCESS,        /* desired access          */

       SERVICE_WIN32_OWN_PROCESS, /* service type            */

       SERVICE_DEMAND_START,      /* start type              */

       SERVICE_ERROR_NORMAL,      /* error control type      */

       lpszBinaryPathName,        /* service's binary        */

       NULL,                      /* no load ordering group  */

       NULL,                      /* no tag identifier       */

       NULL,                      /* no dependencies         */

       NULL,                      /* LocalSystem account     */

       NULL);                     /* no password             */

  if (schService == NULL)

      MyErrorExit("CreateService");

  else

      printf("CreateService SUCCESS\n");

  CloseServiceHandle(schService);

}


 Deleting a Service

In the following example, a service configuration program uses the OpenService function to get a handle with DELETE access to an installed service object. The program then uses the service object handle in the DeleteService function to remove the service from the service control manager database.

VOID DeleteSampleService() {

  schService = OpenService(

       schSCManager,       /* SCManager database      */

       TEXT("Sample_Srv"), /* name of service         */

       DELETE);            /* only need DELETE access */

  if (schService == NULL)

      MyErrorExit("OpenService");

  if (! DeleteService(schService) )

      MyErrorExit("DeleteService");

  else

      printf("DeleteService SUCCESS\n");

  CloseServiceHandle(schService);

}


 Changing a Service Configuration

In the following example, a service configuration program uses the ChangeServiceConfig function to change the configuration parameters of an installed service. The program first tries to lock the database, to prevent the service control manager from starting a service while it is being reconfigured. If it successfully locks the database, the program opens a handle to the service object, modifies its configuration, unlocks the database, and then closes the service  object handle. If the program does not successfully in lock the database, it uses the QueryServiceLockStatus function to retrieve information about the lock.

VOID ReconfigureSampleService(BOOL fDisable) {

SC_LOCK sclLock;

LPQUERY_SERVICE_LOCK_STATUS lpqslsBuf;

DWORD dwBytesNeeded, dwStartType;

  /* Need to acquire database lock before reconfiguring. */

  sclLock = LockServiceDatabase(schSCManager);

  /* If the database cannot be locked, report the details. */

  if (sclLock == NULL) {

      /* Exit if the database is not locked by another process. */

      if (GetLastError() != ERROR_SERVICE_DATABASE_LOCKED)

          MyErrorExit("LockServiceDatabase");

      /* Allocate a buffer to get details about the lock. */

      lpqslsBuf = (LPQUERY_SERVICE_LOCK_STATUS) LocalAlloc(

          LPTR, sizeof(QUERY_SERVICE_LOCK_STATUS)+256);

      if (lpqslsBuf == NULL)

          MyErrorExit("LocalAlloc");

      /* Get and print the lock status information. */

      if (! QueryServiceLockStatus(

          schSCManager,

          lpqslsBuf,

          sizeof(QUERY_SERVICE_LOCK_STATUS)+256,

          &dwBytesNeeded) )

          MyErrorExit("QueryServiceLockStatus");

      if (lpqslsBuf->fIsLocked)

          printf("Locked by: %s, duration: %d seconds\n",

              lpqslsBuf->lpLockOwner,

              lpqslsBuf->dwLockDuration);

      else

          printf("No longer locked\n");

      LocalFree(lpqslsBuf);

      MyErrorExit("Could not lock database");

  }

  /* The database is locked, so it is safe to make changes. */

  /* Open a handle to the service. */

  schService = OpenService(

       schSCManager,           /* SCManager database */

       TEXT("Sample_Srv"),     /* name of service    */

       SERVICE_CHANGE_CONFIG); /* need CHANGE access */

  if (schService == NULL)

      MyErrorExit("OpenService");

  dwStartType = (fDisable) ? SERVICE_DISABLED :

                             SERVICE_DEMAND_START;

  if (! ChangeServiceConfig(

       schService,        /* handle of service            */

       SERVICE_NO_CHANGE, /* service type: no change      */

       dwStartType,       /* *change* service start type  */

       SERVICE_NO_CHANGE, /* error control: no change     */

       NULL,              /* binary path: no change       */

       NULL,              /* load order group: no change  */

       NULL,              /* tag ID: no change            */

       NULL,              /* dependencies: no change      */

       NULL,              /* account name: no change      */

       NULL) )            /* password: no change          */

      MyErrorExit("ChangeServiceConfig");

  else

      printf("ChangeServiceConfig SUCCESS\n");

  /* Release the database lock. */

  UnlockServiceDatabase(sclLock);

  /* Close the handle to the service. */

  CloseServiceHandle(schService);

}


 Querying a Service's Configuration

In the following example, a service configuration program uses the OpenService function to get a handle with SERVICE_QUERY_CONFIG access to an installed service object. Then the program uses the service object handle in the QueryServiceConfig function to retrieve the current configuration of the service.

VOID GetSampleServiceConfig() {

LPQUERY_SERVICE_CONFIG lpqscBuf;

DWORD dwBytesNeeded;

  /* Open a handle to the service. */

  schService = OpenService(

       schSCManager,           /* SCManager database  */

       TEXT("Sample_Srv"),     /* name of service     */

       SERVICE_QUERY_CONFIG);  /* need QUERY access   */

  if (schService == NULL)

      MyErrorExit("OpenService");

  /* Allocate a buffer for the information configuration. */

  lpqscBuf = (LPQUERY_SERVICE_CONFIG) LocalAlloc(

                                       LPTR, 4096);

  if (lpqscBuf == NULL)

      MyErrorExit("LocalAlloc");

  /* Get and print the information configuration. */

  if (! QueryServiceConfig(

      schService,

      lpqscBuf,

      4096,

      &dwBytesNeeded) )

      MyErrorExit("QueryServiceConfig");

  printf("\nSample_Srv configuration: \n");

  printf("  Type: 0x%x\n", lpqscBuf->dwServiceType);

  printf("  Start Type: 0x%x\n", lpqscBuf->dwStartType);

  printf("  Err Control: 0x%x\n", lpqscBuf->dwErrorControl);

  printf("  Binary path: %s\n", lpqscBuf->lpBinaryPathName);

  if (lpqscBuf->lpLoadOrderGroup != NULL)

      printf("  Load order group: %s\n",

                 lpqscBuf->lpLoadOrderGroup);

  if (lpqscBuf->dwTagId != 0)

      printf("  Tag ID: %d\n", lpqscBuf->dwTagId);

  if (lpqscBuf->lpDependencies != NULL)

      printf("  Dependencies: %s\n", lpqscBuf->lpDependencies);

  if (lpqscBuf->lpServiceStartName != NULL)

      printf("  Start Name: %s\n",

                 lpqscBuf->lpServiceStartName);

  LocalFree(lpqscBuf);

}


 Starting a Service

To start a service, the following example opens a handle to an installed database and then specifies the handle in a call to the StartService function. StartService can be used to start either a Win32 service or a driver service, but this example assumes that a Win32 service is being started. After starting the service, the program uses the members of the SERVICE_STATUS structure returned by the QueryServiceStatus function to track the progress of the Win32 service.

VOID StartSampleService() {

SERVICE_STATUS ssStatus;

DWORD dwOldCheckPoint;

  schService = OpenService(

       schSCManager,          /* S. C. Manager database */

       TEXT("Sample_Srv"),    /* name of service        */

       SERVICE_ALL_ACCESS);

     //  SERVICE_START |        /* need START access  */

     //  SERVICE_QUERY_CONFIG); /* and QUERY access   */

  if (schService == NULL)

      MyErrorExit("OpenService");

  if (! StartService(schService, /* handle of service   */

            0,                   /* number of arguments */

            NULL) )              /* no arguments        */

      MyErrorExit("StartService");

  else

      printf("Service start pending\n");

  /* Check the status until the service is running. */

  if (! QueryServiceStatus(

      schService,   /* handle of service       */

      &ssStatus) )  /* address of status info  */

      MyErrorExit("QueryServiceStatus");

  while (ssStatus.dwCurrentState != SERVICE_RUNNING) {

      /* Save the current checkpoint. */

      dwOldCheckPoint = ssStatus.dwCheckPoint;

      /* Wait for the specified interval. */

      Sleep(ssStatus.dwWaitHint);

      /* Check the status again. */

      if (! QueryServiceStatus(

              schService,   /* handle of service       */

              &ssStatus) )  /* address of status info  */

          break;

      /* Break if the checkpoint has not been incremented. */

      if (dwOldCheckPoint >= ssStatus.dwCheckPoint)

          break;

  }

  if (ssStatus.dwCurrentState == SERVICE_RUNNING)

      printf("StartService SUCCESS\n");

  else {

      printf("\nService not started: \n");

      printf("  Current State: %d\n",

                   ssStatus.dwCurrentState);

      printf("  Exit Code: %d\n", ssStatus.dwWin32ExitCode);

      printf("  Service Specific Exit Code: %d\n",

                   ssStatus.dwServiceSpecificExitCode);

      printf("  Check Point: %d\n", ssStatus.dwCheckPoint);

      printf("  Wait Hint: %d\n", ssStatus.dwWaitHint);

  }

  CloseServiceHandle(schService);

}


 Sending Control Requests to a Service

The following example uses the ControlService function to send a control value to a running service. Different control values require different levels of access to the service object. For example, a service object handle must have SERVICE_STOP access to send the SERVICE_CONTROL_STOP code. When ControlService returns, a SERVICE_STATUS structure contains the latest status information for the service.

VOID ControlSampleService(DWORD fdwControl) {

SERVICE_STATUS ssStatus;

DWORD fdwAccess;

  /* The required service object access depends on the control. */

  switch (fdwControl) {

      case SERVICE_CONTROL_STOP:

          fdwAccess = SERVICE_STOP;

          break;

      case SERVICE_CONTROL_PAUSE:

      case SERVICE_CONTROL_CONTINUE:

          fdwAccess = SERVICE_PAUSE_CONTINUE;

          break;

      case SERVICE_CONTROL_INTERROGATE:

          fdwAccess = SERVICE_INTERROGATE;

          break;

      default:

          fdwAccess = SERVICE_INTERROGATE;

  }

  /* Open a handle to the service. */

  schService = OpenService(

       schSCManager,        /* SCManager database */

       TEXT("Sample_Srv"),  /* name of service    */

       fdwAccess);          /* specify access     */

  if (schService == NULL)

      MyErrorExit("OpenService");

  /* Send a control value to the service. */

  if (! ControlService(

      schService,   /* handle of service       */

      fdwControl,   /* control value to send    */

      &ssStatus) )  /* address of status info  */

      MyErrorExit("ControlService");

  /* Print the service status. */

  printf("\nStatus of Sample_Srv: \n");

  printf("  Service Type: 0x%x\n", ssStatus.dwServiceType);

  printf("  Current State: 0x%x\n", ssStatus.dwCurrentState);

  printf("  Controls Accepted: 0x%x\n",

               ssStatus.dwControlsAccepted);

  printf("  Exit Code: %d\n", ssStatus.dwWin32ExitCode);

  printf("  Service Specific Exit Code: %d\n",

               ssStatus.dwServiceSpecificExitCode);

  printf("  Check Point: %d\n", ssStatus.dwCheckPoint);

  printf("  Wait Hint: %d\n", ssStatus.dwWaitHint);

  return;

}


 Service Functions

Following are the Win32 functions used by services and by programs that control or configure services:

ChangeServiceConfig
CloseServiceHandle
ControlService
CreateService
DeleteService
EnumDependentServices
EnumServicesStatus
GetServiceDisplayName
GetServiceKeyName
Handler
LockServiceDatabase
NotifyBootConfigStatus
OpenSCManager
OpenService
QueryServiceConfig
QueryServiceLockStatus
QueryServiceObjectSecurity
QueryServiceStatus
RegisterServiceCtrlHandler
ServiceMain
SetServiceBits
SetServiceObjectSecurity
SetServiceStatus
StartService
StartServiceCtrlDispatcher
UnlockServiceDatabase


 String Manipulation

The overview describes the string manipulation functions and explains how to use them in your Win32-based applications.


 About String Manipulation

The string manipulation functions give applications developed for the Win32 application programming interface (API) 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 manipulation 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.


 String Manipulation in Windows

Many Windows functions duplicate or enhance familiar string-manipulation functions from the standard C library. Many of the enhancements enable Windows functions to work with Unicode or extended character sets. For example, the Windows functions in the following table are identical to standard C functions except that the Windows functions are enhanced for use with Unicode.

Windows function	Standard C function
lstrcat	strcat
lstrcmp	strcmp
lstrcmpi	strcmpi
lstrcpy	strcpy
lstrlen	strlen
The strlen standard C function, for example, always returns the number of bytes in a string, but the lstrlen function returns the number of characters, regardless of whether the characters are 1 or 2 bytes wide.

The following Windows 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, a Windows-based 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 Windows 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. The Windows 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, a developer 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.

Windows 32-bit 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.


 Obsolete Functions

The AnsiLower function is obsolete. Win32-based applications should use the CharLower function.

The AnsiLowerBuff function is obsolete. Win32-based applications should use the CharLowerBuff function.

The AnsiNext function is obsolete. Win32-based applications should use the CharNext function.

The AnsiPrev function is obsolete. Win32-based applications should use the CharPrev function.

The AnsiUpper function is obsolete. Win32-based applications should use the CharUpper function.

The AnsiUpperBuff function is obsolete. Win32-based applications should use the CharUpperBuff function.

OemToAnsi
OemToAnsiBuff


 String Manipulation Reference

This section provides detailed reference information for the string manipulation functions, structures, and messages.


 String Manipulation Functions

Following are the functions used with string manipulation.

CharLower
CharLowerBuff
CharNext
CharPrev
CharToOem
CharToOemBuff
CharUpper
CharUpperBuff
CompareString
ConvertDefaultLocale
EnumCalendarInfo
EnumCalendarInfoProc
EnumCodePagesProc
EnumDateFormats
EnumDateFormatsProc
EnumLocalesProc
EnumSystemCodePages
EnumSystemLocales
EnumTimeFormats
EnumTimeFormatsProc
FoldString
FormatMessage
GetACP
GetCPInfo
GetCurrencyFormat
GetDateFormat
GetNumberFormat
GetLocaleInfo
GetOEMCP
GetStringTypeA
GetStringTypeEx
GetStringTypeW
GetSystemDefaultLangID
GetSystemDefaultLCID
GetThreadLocale
GetTimeFormat
GetUserDefaultLangID
GetUserDefaultLCID
IsCharAlpha
IsCharAlphaNumeric
IsCharLower
IsCharUpper
IsDBCSLeadByte
IsTextUnicode
IsValidCodePage
IsValidLocale
LCMapString
LoadString
lstrcat
lstrcmp
lstrcmpi
lstrcpy
lstrcpyn
lstrlen
MultiByteToWideChar
OemToChar
OemToCharBuff
SetLocaleInfo
SetThreadLocale
WideCharToMultiByte
wsprintf
wvsprintf


 String Manipulation Constants

This section describes the constants used with the string manipulation functions.


 Character Type Information Values

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 limited to 16 bits of representation per character can 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 fdwInfoType 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 letter
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
Printable	Graphic characters and blank
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	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 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. These types are supported in the current version of Microsoft® Windows NT™. A combination of these values is returned when fdwInfoType is set to CT_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)
Not applicable:
C3_NOTAPPLICABLE	0x0	Not applicable


 Format Specifications

%[-][#][0][width][.precision]type

Format specifications always begin with a percent sign (%). Each field is a single character or a number signifying a particular format option. 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.

%

Required. Marks the beginning of the format specification. If the 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).

−

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

#

Optional. Prefix hexadecimal values with 0x (lowercase) or 0X (uppercase).

0

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

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

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

Required. Determines whether the associated argument is interpreted as a character, a string, or a number. Can be one of these character sequences:

c	A single character. The functions ignore character arguments with a numeric value of zero. This sequence is interpreted as type WCHAR when the calling application uses the #define UNICODE compile flag and as type CHAR otherwise.
C	A single character. This sequence is interpreted as type CHAR when the calling application uses the #define UNICODE compile flag and as type WCHAR otherwise.
d	A signed decimal integer argument. This sequence is equivalent to the i sequence.
hc, hC	A single character. The functions ignore character arguments with a numeric value of zero. This sequence is always interpreted as type CHAR, even when the calling application uses the #define UNICODE compile flag.
hs, hS	A string. This sequence is always interpreted as type LPSTR, even when the calling application uses the #define UNICODE compile flag.
i	A signed decimal integer. This sequence is equivalent to the d sequence.
lc, lC	A single character. The functions ignore character arguments with a numeric value of zero. This sequence is always interpreted as type WCHAR, even when the calling application does not use the #define UNICODE compile flag.
ld	A long signed decimal integer. This sequence is equivalent to the li sequence.
li	A long signed decimal integer. This sequence is equivalent to the ld sequence.
ls, lS	A string. This sequence is always interpreted as type LPWSTR, even when the calling application does not use the #define UNICODE compile flag. This sequence is equivalent to the ws sequence.
lu	A long unsigned integer.
lx, lX	A long unsigned hexadecimal integer in lowercase or uppercase.
s	A string. This sequence is interpreted as type LPWSTR when the calling application uses the #define UNICODE compile flag and as type LPSTR otherwise.
S	A string. This sequence is interpreted as type LPSTR when the calling application uses the #define UNICODE compile flag and as type LPWSTR otherwise.
u	An unsigned integer argument.
x, X	An unsigned hexadecimal integer in lowercase or uppercase.


 Structured Exception Handling

An exception is an event that occurs during the execution of a program, and that requires the execution of software outside the normal flow of control. Hardware exceptions can result from the execution of certain instruction sequences, such as division by zero or an attempt to access an invalid memory address. A software routine can also initiate an exception explicitly.

The Microsoft® Win32® application programming interface (API) supports structured exception handling, a mechanism for handling hardware- and software-generated exceptions.


 About Structured Exception Handling

Structured exception handling gives developers complete control over the handling of exceptions, provides support for debuggers, and is usable across all programming languages and machines.

The Win32 API also supports termination handling, which enables developers to ensure that whenever a guarded body of code is executed, a specified block of termination code is also executed. The termination code is executed regardless of how the flow of control leaves the guarded body. For example, a termination handler can guarantee that clean-up tasks are performed even if an exception or some other error occurs while the guarded body of code is being executed.

Structured exception and termination handling is an integral part of the Win32 API; it enables a robust implementation of the system software. Developers can use these mechanisms to create consistently robust and reliable applications.

Structured exception handling is made available to developers primarily through compiler support. For example, the Microsoft compilers provided with the Win32 software development kit support the try keyword that identifies a guarded body of code, and the except and finally keywords that identify an exception handler and a termination handler, respectively. Although this topic uses examples from the support available in Microsoft compilers, other compiler vendors can provide this support as well.


 Exception Handling

Exceptions can be initiated by hardware or software, and can occur in kernel-mode as well as user-mode code. Win32-based structured exception handling provides a single mechanism for the handling of kernel-mode and user-mode exceptions, both hardware- and software-generated.

The execution of certain instruction sequences can result in exceptions that are initiated by hardware. For example, an access violation is generated by the hardware when a process attempts to read from or write to a virtual address to which it does not have the appropriate access.

Events that require exception handling may also occur during execution of a software routine (for example, when an invalid parameter value is specified). When this happens, a thread can initiate an exception explicitly by calling the RaiseException function. This function enables the calling thread to specify information that describes the exception.


 Exception Dispatching

When a hardware or software exception occurs, the processor stops execution at the point at which the exception occurred and transfers control to the system. First, the system saves both the machine state of the current thread and information that describes the exception. The system then attempts to find an exception handler to handle the exception.

The machine state of the thread in which the exception occurred is saved in a CONTEXT structure. This information (called the context record) enables the system to continue execution at the point of the exception if the exception is successfully handled. The description of the exception (called the exception record) is saved in an EXCEPTION_RECORD structure. Because it stores the machine-dependent information of the context record separately from the machine-independent information of the exception record, the exception-handling mechanism is portable to different platforms. The information in both the context and exception records is available by means of the GetExceptionInformation function, and can be made available to any exception handlers that are executed as a result of the exception. The exception record includes the following information.

•	An exception code that identifies the type of exception.

•	Flags indicating whether the exception is continuable. Any attempt to continue execution after a noncontinuable exception generates another exception.

•	A pointer to another exception record. This facilitates creation of a linked list of exceptions if nested exceptions occur.

•	The address at which the exception occurred.

•	An array of 32-bit arguments that provide additional information about the exception.

When an exception occurs in user-mode code, the system goes through the following search for an exception handler:

1.	The system first attempts to notify the process's debugger, if any.

2.	If the process is not being debugged, or if the associated debugger does not handle the exception, the system attempts to locate a frame-based exception handler by searching the stack frames of the thread in which the exception occurred. The system searches the current stack frame first, then proceeds backward through preceding stack frames.

3.	If no frame-based handler can be found, or no frame-based handler handles the exception, the system makes a second attempt to notify the process's debugger.

4.	If the process is not being debugged, or if the associated debugger does not handle the exception, the system provides default handling based on the exception type. For most exceptions, the default action is to call the ExitProcess function.

When an exception occurs in kernel-mode code, the system searches the stack frames of the kernel stack in an attempt to locate an exception handler. If a handler cannot be located or no handler handles the exception, the system is shut down as if the ExitWindows function had been called.


 Debugger Support

The system's handling of user-mode exceptions provides support for sophisticated debuggers. If the process in which an exception occurs is being debugged, the system generates a debug event. If the debugger is using the WaitForDebugEvent function, the debug event causes that function to return with a pointer to a DEBUG_EVENT structure. This structure contains the process and thread identifiers that the debugger can use to access the thread's context record. The structure also contains an EXCEPTION_DEBUG_INFO structure that includes a copy of the exception record.

The system's search for an exception handler includes two attempts to notify a process's debugger. The first notification attempt provides the debugger with an opportunity to handle breakpoint or single-step exceptions. The user can then issue debugger commands to manipulate the process's environment before any exception handlers are executed. The second attempt to notify the debugger occurs only if the system is unable to find a frame-based exception handler that handles the exception.

At each notification attempt, the debugger uses the ContinueDebugEvent function to return control to the system. Before returning control, the debugger can handle the exception and modify the thread state as appropriate, or it can choose not to handle the exception. Using ContinueDebugEvent, the debugger can indicate that it has handled the exception, in which case the machine state is restored and thread execution is continued at the point at which the exception occurred. The debugger can also indicate that it did not handle the exception, which causes the system to continue its search for an exception handler.


 Frame-based Exception Handling

A frame-based exception handler is a mechanism by which a developer deals with the possibility that an exception may occur in a certain sequence of code. A frame-based exception handler consists of the following elements.

•	A guarded body of code

•	A filter expression

•	An exception-handler block

Frame-based exception handlers are declared in language-specific syntax. For example, in the Microsoft® C Optimizing Compiler, they are implemented by the try-except statement. For more information about the Microsoft C exception-handling syntax, see Syntax.

The guarded body of code is a set of one or more statements for which the filter expression and the exception-handler block provide exception-handling protection. The guarded body can be a block of code, a set of nested blocks, or an entire procedure or function. In Microsoft C, a guarded body is enclosed by braces ({}) following the try keyword.

The filter expression of a frame-based exception handler is an expression that is evaluated by the system when an exception occurs within the guarded body. This evaluation results in one of the following actions by the system.

•	The system stops its search for an exception handler, restores the machine state, and continues thread execution at the point at which the exception occurred.

•	The system continues its search for an exception handler.

•	The system transfers control to the exception handler, and thread execution continues sequentially in the stack frame in which the exception handler is found. If the handler is not in the stack frame in which the exception occurred, the system unwinds the stack, leaving the current stack frame and any other stack frames until it is back to the exception handler's stack frame. Before an exception handler is executed, termination handlers are executed for any guarded bodies of code that terminated as a result of the transfer of control to the exception handler. For more information about termination handlers, refer to Termination Handling.

The filter expression can be a simple expression, or it can invoke a filter function that attempts to handle the exception. You can call the GetExceptionCode and GetExceptionInformation functions from within a filter expression to get information about the exception being filtered. GetExceptionCode returns a code that identifies the type of exception, and GetExceptionInformation returns a pointer to an EXCEPTION_POINTERS structure that contains pointers to CONTEXT and EXCEPTION_RECORD structures.

These functions cannot be called from within a filter function, but their return values can be passed as parameters to a filter function. GetExceptionCode can be used within the exception-handler block, but GetExceptionInformation cannot because the information it points to is typically on the stack and is destroyed when control is transferred to an exception handler. However, an application can copy the information to safe storage to make it available to the exception handler.

The advantage of a filter function is that it can handle an exception and return a value that causes the system to continue execution from the point at which the exception occurred. With an exception-handler block, in contrast, execution continues sequentially from the exception handler rather than from the point of the exception.

Handling an exception may be as simple as noting an error and setting a flag that will be examined later, printing a warning or error message, or taking some other limited action. If execution can be continued, it may also be necessary to change the machine state by modifying the context record. For an example of a filter function that handles a page fault exception, see Memory Management.

The UnhandledExceptionFilter function can be used as a filter function in a filter expression. It returns EXCEPTION_EXECUTE_HANDLER unless the process is being debugged, in which case it returns EXCEPTION_CONTINUE_SEARCH.


 Termination Handling

A termination handler is a mechanism by which a developer ensures that a specific block of code is executed whenever flow of control leaves a particular guarded body of code. A termination handler consists of the following elements.

•	A guarded body of code

•	A block of termination code to be executed when the flow of control leaves the guarded body

Termination handlers are declared in language-specific syntax. In Microsoft C, they are implemented by the try-finally statement. For more information about the Microsoft C exception-handling syntax, see Syntax.

The guarded body of code can be a block of code, a set of nested blocks, or an entire procedure or function. Whenever the guarded body is executed, the block of termination code will be executed. The only exception to this is when the thread terminates during execution of the guarded body (for example, if the ExitThread or ExitProcess function is called from within the guarded body).

The termination block is executed when the flow of control leaves the guarded body, regardless of whether the guarded body terminated normally or abnormally. The guarded body is considered to have terminated normally when the last statement in the block is executed and control proceeds sequentially into the termination block. Abnormal termination occurs when the flow of control leaves the guarded body due to an exception, or due to a control statement such as return, goto, break, or continue. The AbnormalTermination function can be called from within the termination block to determine whether the guarded body terminated normally.


 Syntax

This section describes the syntax and usage of structured exception handling as implemented in Microsoft C. The following keywords are interpreted by the Microsoft C compiler as part of the structured exception-handling mechanism.

Keyword	Description
try	Begins a guarded body of code. Used with the except keyword to construct an exception handler, or with the finally keyword to construct a termination handler.
except	Begins a block of code that is executed only when an exception occurs within its associated try block.
finally	Begins a block of code that is executed whenever the flow of control leaves its associated try block.
The compiler also interprets the GetExceptionCode, GetExceptionInformation, and AbnormalTermination functions as keywords, and their use outside the appropriate exception-handling syntax generates a compiler error. Following are brief descriptions of these functions.

Function	Description
GetExceptionCode	Returns a code that identifies the type of exception. This function can be called only from within the filter expression or exception-handler block of a try-except exception handler.
GetExceptionInformation	Returns a pointer to an EXCEPTION_POINTERS structure containing pointers to the context record and the exception record. This function can be called only from within the filter expression of a try-except exception handler.
AbnormalTermination	Indicates whether the flow of control left the associated try block sequentially after executing the last statement in the block. This function can be called only from within the finally block of a try-finally termination handler.


 Exception-Handler Syntax

The try and except keywords are used to construct a frame-based exception handler. The following example shows the structure of a try-except exception handler.

try {

    // guarded body of code

}

except (filter-expression) {

    // exception-handler block

}

Note that the try block and the exception-handler block require braces ({}). Using a goto statement to jump into the body of a try block or into an exception-handler block is not permitted. This rule applies to both try-except and try-finally statements.

The try block contains the guarded body of code that the exception handler protects. A function can have any number of try-except statements, and these exception-handling statements can be nested within the same function or in different functions. If an exception occurs within the try block, the system takes control and begins the search for an exception handler. For a detailed description of this search, see Exception Handling.

The exception handler receives only exceptions that occur within a single thread. This means that if a try block contains a call to the CreateProcess or CreateThread function, exceptions that occur within the new process or thread are not dispatched to this handler.

The system evaluates the filter expression of each exception handler guarding the code in which the exception occurred until either the exception is handled or there are no more handlers. A filter expression must be evaluated as one of the three following values.

Value	Meaning
EXCEPTION_EXECUTE_HANDLER
	The system transfers control to the exception handler, and execution continues in the stack frame in which the handler is found.
EXCEPTION_CONTINUE_SEARCH
	The system continues to search for a handler.
EXCEPTION_CONTINUE_EXECUTION
	The system stops its search for a handler and returns control to the point at which the exception occurred. If the exception is noncontinuable, this results in a EXCEPTION_NONCONTINUABLE_EXCEPTION exception.
The filter expression is evaluated in the context of the function in which the try-except statement is located, even though the exception may have occurred in a different function. This means that the filter expression can access the function's local variables. Similarly, the exception-handler block can access the local variables of the function in which it is located.

For more information about filter expressions and filter functions, see Frame-based Exception Handling.


 Termination-Handler Syntax

The try and finally keywords are used to construct a termination handler. The following example shows the structure of a try-finally termination handler.

try {

    // guarded body of code

}

finally {

    // finally block

}

As with the try-except statement, both the try block and the finally block require braces ({}), and using a goto statement to jump into either block is not permitted.

The try block contains the guarded body of code that is protected by the termination handler. A function can have any number of try-finally statements, and these termination handling structures can be nested within the same function or in different functions.

The finally block is executed whenever the flow of control leaves the try block. However, the finally block is not executed if either the ExitProcess or ExitThread function is called from within the try block.

If execution of the try block terminates because of an exception that invokes the exception-handling block of a frame-based exception handler, the finally block is executed before the exception-handling block is executed. Similarly, a call to the standard C longjmp function from the try block causes execution of the finally block before execution resumes at the target of the longjmp operation. If try block execution terminates due to a normal control statement (return, break, continue, or goto), the finally block is executed.

The AbnormalTermination function can be used within the finally block to determine whether the try block terminated sequentially — that is, whether it reached the closing brace (}). Leaving the try block because of a call to longjmp, a jump to an exception handler, or a return, break, continue, or goto statement, is considered an abnormal termination. Note that failure to terminate sequentially causes the system to search backward through all stack frames to determine whether any termination handlers must be called. This can result in performance degradation due to the execution of hundreds of instructions.

Execution of the finally block can terminate by any of the following means.

•	Execution of the last statement in the block and continuation to the next instruction

•	Use of a normal control statement (return, break, continue, or goto)

•	Use of longjmp or a jump to an exception handler

The finally block is executed in the context of the function in which the try-finally statement is located. This means that the finally block can access that function's local variables.


 Using Structured Exception Handling

•	Using an Exception Handler

•	Using a Termination Handler


 Using an Exception Handler

The following example shows a version of the standard C strcpy function that can handle an invalid pointer and return NULL if one is encountered.

Note that this exception handler is intended to handle an access-violation exception, but is inappropriate if some other type of exception occurs. Therefore, the filter expression in the example uses the GetExceptionCode function to check the exception type before executing the handler. This enables the system to continue its search for an appropriate handler if some other type of exception occurs.

Note also that there is no problem with using a return statement in the try block of a try-except statement. This differs from the use of return in the try block of a try-finally statement, which causes an abnormal termination of the try block.

LPTSTR SafeStrcpy(LPTSTR lpszString1, LPTSTR lpszString2) {

    try {

        return strcpy(string1, string2);

    }

    except (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ?

                EXCEPTION_EXECUTE_HANDLER :

                EXCEPTION_CONTINUE_SEARCH ) {

        return NULL;

    }

}

The following example shows the interaction of nested try-finally and try-except statements. The RaiseException function causes an exception in the guarded body of a try-finally termination handler that is inside the guarded body of a try-except exception handler. The exception causes the system to evaluate the FilterFunction function, whose return value in turn causes the exception handler to be invoked. However, before the exception-handler block is executed, the finally block of the termination handler is executed because the flow of control has left the try block of the termination handler.

DWORD FilterFunction() {

    printf("1 ");                     // printed first

    return EXCEPTION_EXECUTE_HANDLER;

}

VOID main(VOID) {

    try {

        try {

            RaiseException(1,         // exception code

                0,                    // continuable exception

                0, NULL);             // no arguments

        }

        finally {

            printf("2 ")              // this is printed second

        }

    }

    except ( FilterFunction() ) {

        printf("3\n");                // this is printed last

    }

}


 Using a Termination Handler

The following example shows how a try-finally statement is used to ensure that resources are released when execution of a guarded body of code terminates. In this case, a thread uses the EnterCriticalSection function to wait for ownership of a critical section object. When the thread is finished executing the code that is protected by the critical section, it must call the LeaveCriticalSection function to make the critical section object available to other threads. Using a try-finally statement guarantees that this will happen.

For more information about critical section objects, see Synchronization.

LPTSTR lpBuffer = NULL;

CRITICAL_SECTION csCriticalSection;

try {

     // EnterCriticalSection synchronizes code

     // with other threads.

    EnterCriticalSection(&CriticalSection);

    // Perform a task that may cause an exception.

    lpBuffer = (LPTSTR) LocalAlloc(LPTR, 10);

    strcpy(lpBuffer,"Hello");  // possible access violation

    printf("%s\n",lpBuffer);

    LocalFree(lpBuffer);

}

 // LeaveCriticalSection is called even if

 // an exception occurred.

finally {

    LeaveCriticalSection(&CriticalSection);

}


 Structured Exception Handling Functions

Following are the functions used in structured exception handling.

AbnormalTermination
GetExceptionCode
GetExceptionInformation
RaiseException
SetUnhandledExceptionFilter
UnhandledExceptionFilter

Obsolete or Deleted Functions

Catch
Throw


 Synchronization

The Microsoft® Win32® application programming interface (API) provides a variety of ways to coordinate multiple threads of execution.


 About Synchronization

The functions described in this overview provide synchronization mechanisms, such as wait functions and synchronization objects, and overlapped input and output (I/O) operations. The synchronization mechanisms also include critical section objects and interlocked variable access


 Wait Functions

The Win32 API provides a set of wait functions that enable a thread to block its own execution. These functions do not return until a set of conditions specified by the wait function's parameters have been satisfied. These parameters include a time-out interval and handles of one or more synchronization objects. For more information about synchronization objects, see Synchronization Objects Overview.

When a wait function is called, it checks the state of the specified synchronization object (or objects) and any other conditions that could cause it to return. If this initial state does not satisfy the specified conditions and the time-out interval has not elapsed, the calling thread enters an efficient wait state, consuming very little processor time while waiting for the conditions to be satisfied. The time-out interval can be set to INFINITE to cause an indefinite wait.

The WaitForSingleObject and WaitForSingleObjectEx functions require a handle of one synchronization object. These functions return when the state of the object is signaled, or when the time-out interval elapses. (The state of a synchronization object is either signaled or nonsignaled.)

The WaitForMultipleObjects, WaitForMultipleObjectsEx, and MsgWaitForMultipleObjects functions enable the calling thread to specify an array containing one or more synchronization object handles. These functions can be set to return when the state of any one of the specified objects is signaled, in which case the return value indicates the array index of the object that caused the function to return. Alternatively, the functions can be set to return only when the state of all objects is signaled at the same time, in which case the return value simply indicates that the specified conditions were satisfied.

When waiting for all objects to be signaled, these multiple-object functions do not modify the state of the specified objects until all objects are signaled simultaneously. For example, a mutex can be signaled, but the calling thread does not get ownership of it until the other objects are also signaled. In the meantime, some other thread may get ownership of the mutex, thereby delaying satisfaction of all specified conditions.

The WaitForSingleObjectEx and WaitForMultipleObjectsEx functions differ from the other wait functions in that they can optionally perform an alertable wait. In an alertable wait, the function can return when the specified conditions are satisfied, but it can also return if the system queues a completion routine for execution by the waiting thread. For more information about alertable waits and I/O completion routines, see Synchronization and Overlapped Input and Output.

The MsgWaitForMultipleObjects function is identical to WaitForMultipleObjects, except that it can also return when a specified type of input is available in the calling thread's input queue. For example, a thread could use MsgWaitForMultipleObjects to block its execution until either the state of a specified object is signaled, or there is mouse input available in the thread's input queue. When input is available, the thread can use the GetMessage or PeekMessage function to retrieve it.

Before returning, a wait function modifies the state of some types of synchronization objects. Modification occurs only for the object or objects whose signaled state caused the function to return. A wait function can modify the state of synchronization objects as follows:

•	The count of a semaphore object decreases by one, with the semaphore's state changing to nonsignaled if its count is zero.

•	The state of mutex, auto-reset event, and change notification objects changes to nonsignaled.

•	The state of manual-reset event, process, thread, and console input objects is not affected by a wait function.


 Synchronization Objects Overview

A synchronization object is an object whose handle can be specified in one of the wait functions to coordinate the execution of multiple threads. The state of a synchronization object is either signaled, which can allow the wait function to return, or nonsignaled, which can prevent the function from returning. More than one process can have a handle of the same synchronization object, making interprocess synchronization possible.

The Win32 API provides the following three object types intended exclusively for synchronization.

Type	Description
Event	Notifies one or more waiting threads that an event has occurred.
Mutex	Can be owned by only one thread at a time, enabling threads to coordinate mutually exclusive access to a shared resource.
Semaphore	Maintains a count between zero and some maximum value, limiting the number of threads that are simultaneously accessing a shared resource.
Though available for other uses, the following objects can also be used for synchronization.

Object	Description
Change notification	Created by the FindFirstChangeNotification function, its state is signaled when a specified type of change occurs within a specified directory or directory tree. For more information, see Files.
Console input	Created when a console is created, when a handle to console input is returned by the CreateFile function when CONIN$ is specified, or by the GetStdHandle function. Its state is signaled when there is unread input in the console's input buffer, and nonsignaled when the input buffer is empty. For more information about consoles, see Consoles and Character-Mode Support.
Process	Created when a new process is created by calling the CreateProcess function, its state is nonsignaled while the process is running, and signaled when the process terminates. For more information about processes, see Processes and Threads.
Thread	Created when a new thread is created by calling the CreateProcess, CreateThread, or CreateRemoteThread function, its state is nonsignaled while the thread is running, and signaled when the thread terminates. For more information about threads, see Processes and Threads.
In some circumstances, you can also use a file, named pipe, or communications device as a synchronization object; however, their use for this purpose is discouraged. For additional information about I/O operations on files, named pipes, or communications, see Synchronization and Overlapped Input and Output.


 Mutex Objects Overview

A mutex object is a synchronization object whose state is signaled when it is not owned by any thread, and nonsignaled when it is owned. Only one thread at a time can own a mutex, whose name comes from the fact that it is useful in coordinating mutually exclusive access to a shared resource. For example, to prevent two threads from writing to shared memory at the same time, each thread waits for ownership of a mutex before executing the code that accesses the memory. After writing to the shared memory, the thread releases the mutex.

A thread uses the CreateMutex function to create a mutex object. The creating thread can request immediate ownership of the mutex and can also specify a name for the mutex object. Threads in other processes can open a handle of an existing mutex object by specifying its name in a call to the OpenMutex function. For additional information about names for mutex, event, and semaphore objects, see Interprocess Synchronization.

Any thread with a handle of a mutex object can use one of the wait functions to request ownership of the mutex. If the mutex is owned by another thread, the wait function blocks the execution of the requesting thread until the owning thread releases the mutex using the ReleaseMutex function. The return value of the wait function indicates whether the function returned for some reason other than the state of the mutex being signaled.

Once a thread owns a mutex, it can specify the same mutex in repeated wait-function calls without blocking its execution. This prevents a thread from deadlocking itself while waiting for a mutex that it already owns. To release its ownership under such circumstances, the thread must call ReleaseMutex once for each time that the mutex satisfied the conditions of a wait function.

If a thread terminates without releasing its ownership of a mutex object, the mutex is considered to be abandoned. A waiting thread can acquire ownership of an abandoned mutex, but the wait function's return value indicates that the mutex is abandoned. It is best to assume that an abandoned mutex indicates that an error has occurred and that any shared resource being protected by the mutex is in an undefined state. If the thread proceeds normally, as though the mutex had not been abandoned, the mutex's abandoned flag is cleared when the thread releases its ownership. This restores normal mutex behavior if the mutex is subsequently specified in a wait function.


 Semaphore Objects Overview

A semaphore object is a synchronization object that maintains a count between zero and a specified maximum value. A semaphore's state is signaled when its count is greater than zero, and nonsignaled when its count is zero.

The semaphore object is useful in controlling a shared resource that can support a limited number of users. It acts like a gate that counts the threads as they enter and exit a controlled area and limits the number of threads sharing the resource to a specified maximum number. For example, an application might want to place a limit on the number of windows that it creates. It uses a semaphore with a maximum count equal to the window limit, decrementing the count whenever a window is created and incrementing it whenever a window is closed. The application specifies the semaphore object in a wait function before each window is created. When the count is zero — indicating that the window limit has been reached — the wait function blocks execution of the window-creation code.

A thread uses the CreateSemaphore function to create a semaphore object. The creating thread specifies the initial count and the maximum count of the object. The initial count must be neither less than zero nor greater than the maximum count. The creating thread can also specify a name for the semaphore object. Threads in other processes can open a handle of an existing semaphore object by specifying its name in a call to the OpenSemaphore function. For additional information about names for mutex, event, and semaphore objects, see Interprocess Synchronization.

Each time that a wait function returns because of a semaphore's signaled state, the count of the semaphore is decreased by one. The ReleaseSemaphore function increases a semaphore's count by a specified amount. The count can never be less than zero or greater than the maximum count.

The initial count of a semaphore is typically set to the maximum value. The count is then decremented from that level as the protected resource is consumed. Alternatively, a semaphore can be created with an initial count of zero to block access to the protected resource while the application is being initialized. After initialization, you would use ReleaseSemaphore to increment the count to the maximum.

Threads do not acquire ownership of semaphore objects as they do with mutex objects. A thread that owns a mutex can wait repeatedly for the same mutex object without its execution becoming blocked. A thread that waits repeatedly for the same semaphore object, however, decrements the semaphore's count each time a wait is satisfied; its execution is blocked when the count gets to zero. Similarly, only the thread that owns a mutex can successfully call the ReleaseMutex function, though any thread can use ReleaseSemaphore to increase the count of a semaphore object, even if the thread never used a wait function to decrement the count.

A thread can decrement a semaphore's count more than once by repeatedly specifying the same semaphore object in calls to any of the wait functions. However, calling the WaitForMultipleObjects function with an array that contains multiple handles of the same semaphore does not perform multiple decrements.


 Event Objects Overview

An event object is a synchronization object whose state can be explicitly set to signaled by use of the SetEvent or PulseEvent function. Following are the two types of event object.

Object	Description
Manual-reset event	An event object whose state remains signaled until it is explicitly reset to nonsignaled by the ResetEvent function. While it is signaled, any number of waiting threads, or threads that subsequently specify the same event object in one of the wait functions, can be released.
Auto-reset event	An event object whose state remains signaled until a single waiting thread is released, at which time the system automatically sets the state to nonsignaled. If no threads are waiting, the event object's state remains signaled.
The event object is useful in signaling a thread that a particular event has occurred. For example, in overlapped input and output, the system sets a specified event object to the signaled state when the overlapped operation has been completed. A single thread can specify different event objects in several simultaneous overlapped operations, then use the WaitForMultipleObjects function to wait for the state of any one of the event objects to be signaled.

A thread uses the CreateEvent function to create an event object. The creating thread specifies the initial state of the object and whether it is a manual-reset or auto-reset event object. The creating thread can also specify a name for the event object. Threads in other processes can open a handle of an existing event object by specifying its name in a call to the OpenEvent function. For additional information about names for mutex, event, and semaphore objects, see Interprocess Synchronization.

A thread can use the PulseEvent function to set an event object's state to signaled and then reset it to nonsignaled after releasing the appropriate number of waiting threads. For a manual-reset event object, all waiting threads that can be released immediately are released. For an auto-reset event object, the function releases only a single waiting thread, even if multiple threads are waiting. If no threads are waiting, or if no thread can be released immediately, PulseEvent simply sets the event object's state to nonsignaled and returns.


 Interprocess Synchronization

Multiple processes can have handles of the same mutex, semaphore, or event object, so these objects can be used to accomplish interprocess synchronization. The process that creates an object can use the handle returned by the creation function (CreateEvent, CreateMutex, or CreateSemaphore). Other processes can open a handle of the object by using its name, or through inheritance or duplication.


 Object Names

Named objects provide an easy way for processes to share object handles. The name specified by the creating process is limited to MAX_PATH characters, and can include any character except the backslash path-separator character (\). Once a process has created a named event, mutex, or semaphore object, other processes can use the name to call the appropriate function (OpenEvent, OpenMutex, or OpenSemaphore) to open a handle of the object. Name comparison is case sensitive. The names of event, semaphore, mutex, and file-mapping objects share the same name space, so an error occurs if a specified name matches the name of an existing object of a different type. When creating named objects, therefore, use unique names and be sure to check function return values for duplicate-name errors.

If the name specified in a call to the CreateMutex function matches the name of an existing mutex object, the function returns a handle of the existing object. In this case, the call to CreateMutex is equivalent to a call to the OpenMutex function. (The CreateEvent and CreateSemaphore functions work the same way with existing named event and semaphore objects, respectively.) Having multiple processes use CreateMutex for the same mutex is therefore equivalent to having one process that calls CreateMutex while the other processes call OpenMutex, except that it eliminates the need to ensure that the creating process is started first. When using this technique for mutex objects, however, none of the calling processes should request immediate ownership of the mutex. If multiple processes do request immediate ownership, it can be difficult to predict which process actually gets the initial ownership.


 Object Inheritance

A child process created by the CreateProcess function can inherit a handle of a mutex, event, or semaphore if the SECURITY_ATTRIBUTES structure — specified when the object was created — enabled inheritance. The handle inherited by the child process has the same access to the object as the parent's handle. The inherited handle appears in the handle table of the child process, but for the child process to be able to use the handle, the parent process must communicate the handle's value to the child process. The parent can do this by specifying the value as a command-line argument when it calls the CreateProcess function. The child process can then use the GetCommandLine function to retrieve the command-line string and convert the handle argument into a usable handle. For more information about object inheritance, see Processes and Threads.


 Object Duplication

The DuplicateHandle function creates a duplicate handle that can be used by another specified process. This method of sharing object handles is more complex than using named objects or inheritance. It requires communication between the creating process and the process into which the handle is duplicated. The necessary information (the handle value and process identifier) can be communicated by any of the interprocess communication methods (for example, named pipe, shared file, shared memory). For more information about object duplication, see Processes and Threads.


 Synchronization and Overlapped Input and Output

The Win32 API supports both synchronous and asynchronous (or overlapped) I/O operations on files, named pipes, and serial communications devices. The WriteFile, ReadFile, DeviceIoControl, WaitCommEvent, ConnectNamedPipe, and TransactNamedPipe functions can be performed either synchronously or asynchronously. The ReadFileEx and WriteFileEx functions can be performed asynchronously only.

When a function is executed synchronously, it does not return until the operation has been completed. This means that the execution of the calling thread can be blocked for an indefinite period while it waits for a time-consuming operation to finish. Functions called for overlapped operation can return immediately, even though the operation has not been completed. This enables a time-consuming I/O operation to be executed in the background while the calling thread is free to perform other tasks. For example, a single thread can perform simultaneous I/O operations on different handles, or even simultaneous read and write operations on the same handle. To synchronize its execution with the completion of the overlapped operation, the calling thread uses the GetOverlappedResult function or one of the wait functions to determine when the operation has been completed.

Overlapped operations require a file, named pipe, or communications device that was created with the FILE_FLAG_OVERLAPPED flag. To call a function as an overlapped operation, the calling thread must specify a pointer to an OVERLAPPED structure. If this pointer is NULL, the operation is performed synchronously, even though the handle was created with FILE_FLAG_OVERLAPPED enabled. The OVERLAPPED structure must contain a handle to a manual-reset — not an auto-reset — event object. The system sets the state of the event object to nonsignaled when a call to the I/O function returns before the operation has been completed. The system sets the state of the event object to signaled when the operation has been completed.

When a function is called as an overlapped operation, the operation may have been completed before the function returns. When this happens, the results are handled as if the operation had been performed synchronously. If the operation has not yet been completed, however, the function's return value is FALSE, and the GetLastError function returns ERROR_IO_PENDING.

A thread can manage overlapped operations by either of two methods. It can use the GetOverlappedResult function to wait for the overlapped operation to be completed. Alternatively, it can specify a handle of the OVERLAPPED structure's manual-reset event object in one of the wait functions and then call GetOverlappedResult after the wait function returns. GetOverlappedResult returns the results of the completed overlapped operation, and for functions in which such information is appropriate, it reports the actual number of bytes that were transferred.

When performing multiple simultaneous overlapped operations, the calling thread must specify a separate OVERLAPPED structure with its own manual-reset event object for each operation. The thread can then specify handles of the different event objects in the handle-array parameter of the WaitForMultipleObjects function (or one of the other multiple-object wait functions) to wait for any one of the overlapped operations to be completed. The return value of the multiple-object wait function indicates which event object was signaled, so the thread can determine which operation was completed.

If no event object is specified in the OVERLAPPED structure, the system signals the state of the file, named pipe, or communications device when the overlapped operation has been completed. Thus, you can specify these handles as synchronization objects in a wait function, though their use for this purpose can be difficult to manage. When performing simultaneous overlapped operations on the same file, named pipe, or communications device, there is no way to know which operation caused the object's state to be signaled. It is safer to use a separate event object for each overlapped operation.

For examples that illustrate the use of overlapped operations, completion routines, and the GetOverlappedResult function, see Pipes.


 Critical Section Objects

Critical section objects provide synchronization similar to that provided by mutex objects, except that critical section objects can be used only by the threads of a single process. Event, mutex, and semaphore objects can also be used in a single-process application, but critical section objects provide a slightly faster, more efficient mechanism for mutual-exclusion synchronization. Like a mutex object, a critical section object can be owned by only one thread at a time, which makes it useful for protecting a shared resource from simultaneous access. For example, a process could use a critical section object to prevent more than one thread at a time from modifying a global data structure.

The process is responsible for allocating the memory used by a critical section object. Typically, this is done by simply declaring a variable of type CRITICAL_SECTION. Before the threads of the process can use it, the critical section object must be initialized by using the InitializeCriticalSection function.

A thread uses the EnterCriticalSection function to request ownership and the LeaveCriticalSection function to release its ownership. If the critical section object is currently owned by another thread, EnterCriticalSection waits indefinitely for ownership. This differs from the use of a mutex object for mutual exclusion, where the wait functions accept a specified time-out interval.

Once a thread owns a critical section object, it can make additional calls to EnterCriticalSection without blocking its execution. This prevents a thread from deadlocking itself while waiting for a critical section object that it already owns. To release its ownership, the thread must call LeaveCriticalSection once for each time that it entered the critical section.

Any thread of the process can use the DeleteCriticalSection function to release the system resources that were allocated when the critical section object was initialized. After this function has been called, the critical section object can no longer be used for synchronization.

When a critical section object is owned, the only other threads affected are those that are waiting for ownership in a call to EnterCriticalSection. Threads that are not waiting are free to continue their normal execution.


 Interlocked Variable Access

The InterlockedIncrement and InterlockedDecrement functions provide a simple mechanism for synchronizing access to a specified 32-bit variable that is shared by multiple threads in the same or in different processes. These functions combine the operations of incrementing or decrementing the variable and checking the resulting value. This is useful in a multitasking operating system, in which the system can interrupt one thread's execution to grant a slice of processor time to another thread. Without such synchronization, one thread could increment a variable but be interrupted by the system before it can check the resulting value of the variable. A second thread could then increment the same variable. When the first thread receives its next timeslice, it will check the value of the variable, which has now been incremented not once but twice. The interlocked variable-access functions protect against this kind of error.

The threads of different processes can use this mechanism if the variable is in shared memory.


 Using Synchronization

•	Using named objects

•	Waiting for multiple objects

•	Using mutex objects

•	Using semaphore objects

•	Using event objects

•	Using critical section objects


 Using Named Objects

This example illustrates the use of an object name to let two processes open handles of the same mutex object.

The first process uses the CreateMutex function to create the mutex object. Note that the function succeeds even if there is an existing object with the same name.

/* One process creates the mutex object. */

HANDLE hMutex;

DWORD dwErr;

hMutex = CreateMutex(

    NULL,                  /* no security descriptor */

    FALSE,                 /* mutex not owned        */

    "NameOfMutexObject");  /* object name            */

if (hMutex == NULL)

    printf("CreateMutex error: %d\n", GetLastError() );

else

    if ( GetLastError() == ERROR_ALREADY_EXISTS )

        printf("CreateMutex opened existing mutex\n");

    else

        printf("CreateMutex created new mutex\n");

The second process uses the OpenMutex function to open a handle of the existing mutex. This function fails if a mutex object with the specified name does not exist. The access parameter requests full access to the mutex object, which is necessary for the handle to be used in any of the wait functions.

/* Another process opens a handle of the existing mutex. */

HANDLE hMutex;

hMutex = OpenMutex(

    MUTEX_ALL_ACCESS,      /* request full access    */

    FALSE,                 /* handle not inheritable */

    "NameOfMutexObject");  /* object name            */

if (hMutex == NULL)

    printf("OpenMutex error: %d\n", GetLastError() );

The following example uses the CreateSemaphore function to illustrate a named-object creation operation that fails if the object already exists.

HANDLE CreateNewSemaphore(LPSECURITY_ATTRIBUTES lpsa,

    LONG cInitial, LONG cMax, LPTSTR lpszName) {

HANDLE hSem;

/* Create or open a named semaphore. */

hSem = CreateSemaphore(

    lpsa,         /* security attributes */

    cInitial,     /* initial count       */

    cMax,         /* maximum count       */

    lpszName);    /* semaphore name      */

/* Close handle, and return NULL if existing semaphore opened. */

if (hSem != NULL &&

        GetLastError() == ERROR_ALREADY_EXISTS) {

    CloseHandle(hSem);

    return NULL;

}

/* If new semaphore was created, return the handle. */

return hSem;

}


 Waiting for Multiple Objects

This example uses the CreateEvent function to create two event objects. It then uses the WaitForMultipleObjects function to wait for one of them to be signaled.

HANDLE hEvents[2];

DWORD i, dwEvent;

/* Create two event objects. */

for (i = 0; i < 2; i++) {

    hEvents[i] = CreateEvent(

        NULL,   /* no security attributes        */

        FALSE,  /* auto-reset event object       */

        FALSE,  /* initial state is nonsignaled  */

        NULL);  /* unnamed object                */

    if (hEvents[i] == NULL) {

        printf("CreateEvent error: %d\n", GetLastError() );

        ExitProcess(0);

    }

}

/*

 * The creating thread waits for other threads or processes

 * to signal the event objects.

 */

dwEvent = WaitForMultipleObjects(

    2,           /* number of objects in array */

    hEvents,     /* array of objects           */

    FALSE,       /* wait for any               */

    INFINITE);   /* indefinite wait            */

/* Return value indicates which event is signaled. */

switch (dwEvent) {

    /* hEvent[0] was signaled. */

    case WAIT_OBJECT_0 + 0:

        /* Perform tasks required by this event. */

        break;

    /* hEvent[1] was signaled. */

    case WAIT_OBJECT_0 + 1:

        /* Perform tasks required by this event. */

        break;

    /* Return value is invalid. */

    default:

        printf("Wait error: %d\n", GetLastError());

        ExitProcess(0);

}


 Using Mutex Objects

You can use a mutex object to protect a shared resource from simultaneous access by multiple threads or processes. Each thread must wait for ownership of the mutex before it can execute the code that accesses the shared resource. For example, if several threads share access to a database, the threads can use a mutex object to permit only one thread at a time to write to the database.

In the following example, a process uses the CreateMutex function to create a named mutex object or open a handle of an existing mutex object.

HANDLE hMutex;

/* Create a mutex with no initial owner. */

hMutex = CreateMutex(

    NULL,                       /* no security attributes */

    FALSE,                      /* initially not owned      */

    "MutexToProtectDatabase");  /* name of mutex          */

if (hMutex == NULL) {

    /* check for error */

}

When a thread of this process writes to the database, as in the next example, it first requests ownership of the mutex. If it gets ownership, the thread writes to the database and then releases its ownership.

The example uses the try-finally structured exception-handling syntax to ensure that the thread properly releases the mutex. The finally block of code is executed no matter how the try block terminates (unless the try block includes a call to the TerminateThread function). This prevents the mutex from being abandoned inadvertently.

BOOL FunctionToWriteToDatabase(HANDLE hMutex) {

DWORD dwWaitResult;

/* Request ownership of mutex. */

dwWaitResult = WaitForSingleObject(

        hMutex,   /* handle of mutex           */

        5000L);   /* five-second time-out interval */

switch (dwWaitResult) {

    /* The thread got mutex ownership. */

    case WAIT_OBJECT_0:

        try {

            .

            . /* Write to the database. */

            .

        }

        finally {

            /* Release ownership of the mutex object. */

            if (! ReleaseMutex(hMutex)) {

                /* Deal with error. */

            }

            break;

        }

    /* Cannot get mutex ownership due to time-out. */

    case WAIT_TIMEOUT:

        return FALSE;

    /* Got ownership of the abandoned mutex object. */

    case WAIT_ABANDONED:

        return FALSE;

}

return TRUE;

}


 Using Semaphore Objects

In the following example, a process uses a semaphore object to limit the number of windows it creates. First, it uses the CreateSemaphore function to create the semaphore and to specify initial and maximum counts.

HANDLE hSemaphore;

LONG cMax = 10;

LONG cPreviousCount;

/* Create a semaphore with initial and max. counts of 10. */

hSemaphore = CreateSemaphore(

    NULL,   /* no security attributes */

    cMax,   /* initial count          */

    cMax,   /* maximum count          */

    NULL);  /* unnamed semaphore      */

if (hSemaphore == NULL) {

    /* Check for error. */

}

Before any thread of the process creates a new window, it uses the WaitForSingleObject function to determine whether the semaphore's current count permits the creation of additional windows. The wait function's time-out parameter is set to zero, so the function returns immediately if the semaphore is nonsignaled.

DWORD dwWaitResult;

/* Try to enter the semaphore gate. */

dwWaitResult = WaitForSingleObject(

        hSemaphore,   /* handle of semaphore          */

        0L);          /* zero-second time-out interval */

switch (dwWaitResult) {

    /* The semaphore object was signaled. */

    case WAIT_OBJECT_0:

        .

        . /* OK to open another window. */

        .

        break;

    /* Semaphore was nonsignaled, so a time-out occurred. */

    case WAIT_TIMEOUT:

        .

        . /* Cannot open another window. */

        .

        break;

}

When a thread closes a window, it uses the ReleaseSemaphore function to increment the semaphore's count.

/* Increment the count of the semaphore. */

if (! ReleaseSemaphore(

        hSemaphore,  /* handle of semaphore              */

        1,           /* increase count by one            */

        NULL) ) {    /* not interested in previous count */

    /* Deal with the error. */

}


 Using Event Objects

The Win32 API uses event objects in a number of situations to notify a waiting thread of the occurrence of an event. For example, overlapped I/O operations on files, named pipes, and communications devices use an event object to signal their completion. For more information about the use of event objects in overlapped I/O operations, see Synchronization and Overlapped Input and Output.

In the following example, an application uses event objects to prevent several threads from reading from a shared memory buffer while a master thread is writing to that buffer. First, the master thread uses the CreateEvent function to create a manual-reset event object. The master thread sets the event object to nonsignaled when it is writing to the buffer and then resets the object to signaled when it has finished writing. Then it creates several reader threads and an auto-reset event object for each thread. Each reader thread sets its event object to signaled when it is not reading from the buffer.

#define NUMTHREADS 4

HANDLE hGlobalWriteEvent;

void CreateEventsAndThreads(void) {

HANDLE hReadEvents[NUMTHREADS], hThread;

DWORD i, IDThread;

/*

 * Create a manual-reset event object. The master thread sets

 * this to nonsignaled when it writes to the shared buffer.

 */

hGlobalWriteEvent = CreateEvent(

    NULL,        /* no security attributes    */

    TRUE,        /* manual-reset event        */

    TRUE,        /* initial state is signaled */

    "WriteEvent" /* object name               */

    );

if (hGlobalWriteEvent == NULL) {

    /* error exit */

}

/*

 * Create multiple threads and an auto-reset event object

 * for each thread. Each thread sets its event object to

 * signaled when it is not reading from the shared buffer.

 */

for(i = 1; i <= NUMTHREADS; i++) {

    /* Create the auto-reset event. */

    hReadEvents[i] = CreateEvent(

        NULL,     /* no security attributes    */

        FALSE,    /* auto-reset event          */

        TRUE,     /* initial state is signaled */

        NULL);    /* object not named          */

    if (hReadEvents[i] == NULL) {

        /* error exit */

    }

    hThread = CreateThread(NULL, 0,

            (LPTHREAD_START_ROUTINE) ThreadFunction,

            &hReadEvents[i], /* pass event handle  */

            0, &IDThread);

    if (hThread == NULL) {

        /* error exit */

    }

}

}

Before the master thread writes to the shared buffer, it uses the ResetEvent function to set the state of hGlobalWriteEvent (an application-defined global variable) to nonsignaled. This blocks the reader threads from starting a read operation. The master then uses the WaitForMultipleObjects function to wait for all reader threads to finish any current read operations. When WaitForMultipleObjects returns, the master thread can safely write to the buffer. After it has finished, it sets hGlobalWriteEvent and all the reader-thread events to signaled, enabling the reader threads to resume their read operations.

VOID WriteToBuffer(VOID) {

DWORD dwWaitResult, i;

/* Reset hGlobalWriteEvent to nonsignaled, to block readers. */

if (! ResetEvent(hGlobalWriteEvent) ) {

        /* error exit */

}

/* Wait for all reading threads to finish reading. */

dwWaitResult = WaitForMultipleObjects(

        NUMTHREADS,   /* number of handles in array   */

        hReadEvents,  /* array of read-event handles  */

        TRUE,         /* wait until all are signaled  */

        INFINITE);    /* indefinite wait              */

switch (dwWaitResult) {

    /* All read-event objects were signaled. */

    case WAIT_OBJECT_0:

        .

        . /* Write to the shared buffer. */

        .

        break;

    /* An error occurred. */

    default:

        printf("Wait error: %d\n", GetLastError());

        ExitProcess(0);

}

/* Set hGlobalWriteEvent to signaled. */

if (! SetEvent(hGlobalWriteEvent) ) {

        /* error exit */

}

/* Set all read events to signaled. */

for(i = 1; i <= NUMTHREADS; i++)

    if (! SetEvent(hReadEvents[i]) ) {

            /* error exit */

    }

}

Before starting a read operation, each reader thread uses WaitForMultipleObjects to wait for the application-defined global variable hGlobalWriteEvent and its own read event to be signaled. When WaitForMultipleObjects returns, the reader thread's auto-reset event has been reset to nonsignaled. This blocks the master thread from writing to the buffer until the reader thread uses the SetEvent function to set the event's state back to signaled.

VOID ThreadFunction(LPVOID lpParam) {

DWORD dwWaitResult, i;

HANDLE hEvents[2];

hEvents[0] = (HANDLE) *lpParam;  /* thread's read event */

hEvents[1] = hGlobalWriteEvent;

dwWaitResult = WaitForMultipleObjects(

        2,            /* number of handles in array   */

        hEvents,      /* array of event handles       */

        TRUE,         /* wait till all are signaled   */

        INFINITE);    /* indefinite wait              */

switch (dwWaitResult) {

    /* Both event objects were signaled. */

    case WAIT_OBJECT_0:

        .

        . /* Read from the shared buffer. */

        .

        break;

    /* An error occurred. */

    default:

        printf("Wait error: %d\n", GetLastError());

        ExitThread(0);

}

/* Set the read event to signaled. */

if (! SetEvent(hEvents[0]) ) {

        /* error exit */

}

}


 Using Critical Section Objects

The following example shows how a thread initializes, enters, and leaves a critical section. As with the mutex example (see Using Mutex Objects), this example uses the try-finally structured exception-handling syntax to ensure that the thread calls the LeaveCriticalSection function to release its ownership of the critical section object.

CRITICAL_SECTION GlobalCriticalSection;

/* Initialize the critical section. */

InitializeCriticalSection(&GlobalCriticalSection);

/* Request ownership of the critical section. */

try {

    EnterCriticalSection(&GlobalCriticalSection);

        .

        . /* Access the shared resource. */

        .

}

finally {

    /* Release ownership of the critical section. */

    LeaveCriticalSection(&GlobalCriticalSection);

}


 Synchronization Functions

Following are the functions used in synchronization.

CreateEvent
CreateMutex
CreateSemaphore
DeleteCriticalSection
EnterCriticalSection
GetOverlappedResult
InitializeCriticalSection
InterlockedDecrement
InterlockedExchange
InterlockedIncrement
LeaveCriticalSection
MsgWaitForMultipleObjects
OpenEvent
OpenMutex
OpenSemaphore
PulseEvent
ReleaseMutex
ReleaseSemaphore
ResetEvent
SetEvent
WaitForMultipleObjects
WaitForMultipleObjectsEx
WaitForSingleObject
WaitForSingleObjectEx


 System Information

The Microsoft® Win32® application programming interface (API) includes functions that describe the current system configuration.


 About System Information

The functions described in this overview retrieve a variety of data, such as the computer name, user name, settings of environment variables, processor type, system colors, and so on. The Win32 API also includes functions that can change the system configuration, shut down the system, and start the Microsoft® Windows™ Help application.


 System Configuration

Several of the functions in the Win32 API are specifically intended to describe or change the system configuration. At startup, for example, a computer is assigned the name listed in the registry. An application can retrieve this name by using the GetComputerName function and can change the name by using the SetComputerName function. SetComputerName changes the registry, not the current computer name. As a result, the new name is not assigned until the computer is restarted. For more information about the registry, see Registry.

The GetUserName function retrieves the name of the user currently logged onto the system. The user name is either the logon name or the user's full name, if the latter is included in the registry.

The GetSystemInfo function retrieves processor and memory information, such as the page size, original equipment manufacturer (OEM) identifier, number and type of processors, application address range, and so on. The GetVersion function retrieves the major and minor revision numbers of the installed version of Microsoft Windows. The GetKeyboardType function retrieves such information as the type of keyboard and the number of function keys on the current keyboard.

The SystemParametersInfo function retrieves or sets various system attributes, such as double-click time, screen saver time-out, window border width, and desktop pattern. When an application uses SystemParametersInfo to set a parameter, the change takes place immediately. This function also enables applications to update the user profile, so changes to the system will be preserved when the system is restarted.

The GetThreadDesktop function retrieves a handle of the desktop for a given thread. This handle can be used in calls to functions that retrieve and set security attributes.

The Windows directory is the directory that contains Windows-based applications, initialization files, and Help files. The GetWindowsDirectory function retrieves the path to this directory. Applications that create files should do so in the Windows directory. This is the only directory guaranteed to be private to a user running a shared version of Windows.

The system directory is the directory that contains Windows libraries, drivers, and font files. The GetSystemDirectory function retrieves the path to this directory.

An environment variable is a symbolic variable that represents some element of the system, such as a path, a filename, or other literal data. For example, the environment variable PATH represents the directories in which to search for executable files. When a user logs on, the system initializes environment variables based on the environment section of the registry. The ExpandEnvironmentStrings function retrieves the values of specified environment variables.

System metrics are the dimensions of various Windows display elements. (Display elements are the parts of a window and the Windows display that appear on the system display screen.) Typical system metrics include the window border width, icon height, and so on. System metrics also describe other aspects of the system, such as whether a mouse is installed, double-byte characters are supported, or a debugging version of Windows is installed. The GetSystemMetrics function retrieves a specified system metric.

Applications can also retrieve and set the color of window elements such as menus, scroll bars, and buttons by using the GetSysColor and SetSysColors functions, respectively.


 System Shutdown

The Win32 API also provides a way for an application to shut down a local or remote computer. This is particularly useful for system administrators who update system software on remote computers. The InitiateSystemShutdown function starts a timer and displays a dialog box that prompts the user to log off. While the dialog box is displayed, the AbortSystemShutdown function can stop the timer and prevent the computer from shutting down. However, if the timer expires, the computer is shut down. InitiateSystemShutdown can also restart the computer following shutdown.


 Using System Information

•	Getting system configuration information

•	Getting hardware information

•	Changing the colors of window elements

•	Shutting down the system


 Getting System Configuration Information

The following example uses the GetComputerName, GetUserName, GetSystemDirectory, GetWindowsDirectory, and ExpandEnvironmentStrings functions to get information that describes the system configuration. This example displays the information in a window's client area.

LPTSTR lpszSystemInfo;    /* ptr. to system info. string */

DWORD cchBuff = 256;     /* size of comp. or user name   */

TCHAR tchBuffer2[BUFFER];   /* buffer for concat'd. str. */

DWORD dwResult;               /* function return value */

SYSTEM_INFO siSysInfo;     /* struct. for hardware info. */

int aTabs[1] = {260};    /* tab stop for TabbedTextOut */

TCHAR tchBuffer[BUFFER]; /* buffer for expanded string */

int nSize;                           /* size of string */

lpszSystemInfo = tchBuffer2;

/* Get and display the name of the computer. */

GetComputerName(lpszSystemInfo, &cchBuff);

nSize = sprintf(tchBuffer, "Computer name:  %s",

    lpszSystemInfo);

TextOut(hdc, 15, 20, tchBuffer, nSize);

/* Get and display the user name. */

GetUserName(lpszSystemInfo, &cchBuff);

nSize = sprintf(tchBuffer, "User name:  %s",

    lpszSystemInfo);

TextOut(hdc, 15, 40, tchBuffer, nSize);

/* Get and display the system directory. */

nSize = GetSystemDirectory(lpszSystemInfo, MAX_PATH);

nSize = sprintf(tchBuffer, "System directory:  %s",

    lpszSystemInfo);

TextOut(hdc, 15, 60, tchBuffer, nSize);

/* Get and display the Windows directory. */

nSize = GetWindowsDirectory(lpszSystemInfo, MAX_PATH);

nSize = sprintf(tchBuffer, "Windows directory:  %s",

    lpszSystemInfo);

TextOut(hdc, 15, 80, tchBuffer, nSize);

/* Display the "environment variables" header. */

nSize = sprintf(tchBuffer,

    "Environment variables (partial list):");

TextOut(hdc, 15, 105, tchBuffer, nSize);

/* Expand the OS and NTVERSION environment variables. */

dwResult = ExpandEnvironmentStrings(

               "OS=%OS%     NTVERSION=%NTVERSION%",

               lpszSystemInfo,

               BUFFER);

TextOut(hdc, 25, 120, (LPCTSTR) lpszSystemInfo,

    dwResult - 1);

/* Expand the PATH environment variable. */

dwResult = ExpandEnvironmentStrings(

               "PATH=%PATH%",

               lpszSystemInfo,

               BUFFER);

TextOut(hdc, 25, 135, (LPCTSTR) lpszSystemInfo,

    dwResult - 1);

/* Expand the LIBPATH environment variable. */

dwResult = ExpandEnvironmentStrings(

               "LIBPATH=%LIBPATH%",

               lpszSystemInfo,

               BUFFER);

TextOut(hdc, 25, 150, (LPCTSTR) lpszSystemInfo,

    dwResult - 1);

/* Expand the TMP environment variable. */

dwResult = ExpandEnvironmentStrings(

               "TMP=%TMP%",

               lpszSystemInfo,

               BUFFER);

TextOut(hdc, 25, 165, (LPCTSTR) lpszSystemInfo,

    dwResult - 1);

The next example uses the GetVersion function to obtain the current version of Windows and then displays the version number in a message box.

DWORD dwResult;               /* function return value */

TCHAR tchBuffer[BUFFER]; /* buffer for expanded string */

int nSize;                           /* size of string */

dwResult = GetVersion();

nSize = sprintf(tchBuffer, "Windows version %d.%d\n",

    LOBYTE(LOWORD(dwResult)),

    HIBYTE(LOWORD(dwResult)));

MessageBox(NULL, tchBuffer, "GetVersion", MB_ICONINFORMATION);


 Getting Hardware Information

The following example uses the GetSystemInfo function to obtain hardware information such as the OEM identifier, processor type, page size, and so on. The example displays the information in a window's client area.

SYSTEM_INFO siSysInfo;     /* struct. for hardware info. */

int aTabs[1] = {260};    /* tab stop for TabbedTextOut */

TCHAR tchBuffer[BUFFER]; /* buffer for expanded string */

int nSize;                           /* size of string */

/* Display the "hardware information" header. */

nSize = sprintf(tchBuffer,

    "Hardware information:");

TextOut(hdc, 15, 20, tchBuffer, nSize);

/* Copy the hardware information to the SYSTEM_INFO structure. */

GetSystemInfo(&siSysInfo);

/* Display the contents of the SYSTEM_INFO structure. */

nSize = sprintf(tchBuffer,

    "OEM ID: %u\tNumber of Processors: %u",

    siSysInfo.dwOemId,

    siSysInfo.dwNumberOfProcessors);

TabbedTextOut(hdc, 25, 40, tchBuffer,

    nSize, 1, aTabs, 25);

nSize = sprintf(tchBuffer,

    "Page size: %u\tProcessor Type: %u",

    siSysInfo.dwPageSize,

    siSysInfo.dwProcessorType);

TabbedTextOut(hdc, 25, 60, tchBuffer,

    nSize, 1, aTabs, 25);

nSize = sprintf(tchBuffer,

    "Minimum app address: %lx\tMaximum app address: %lx",

    siSysInfo.lpMinimumApplicationAddress,

    siSysInfo.lpMaximumApplicationAddress);

TabbedTextOut(hdc, 25, 80, tchBuffer,

    nSize, 1, aTabs, 25);

nSize = sprintf(tchBuffer,

    "Active processor mask: %u",

    siSysInfo.dwActiveProcessorMask);

TextOut(hdc, 25, 100, tchBuffer, nSize);

The following example uses the GetSystemMetrics function to determine whether a mouse is installed and whether the mouse buttons are swapped. The example also uses the SystemParametersInfo function to retrieve the mouse threshold and speed. It displays the information in a message box.

TCHAR tchBuffer[BUFFER]; /* buffer for expanded string */

int nSize;                           /* size of string */

BOOL fResult;                  /* system shutdown flag */

int aMouseInfo[3];             /* array for mouse info. */

/* Is there a mouse? */

fResult = GetSystemMetrics(SM_MOUSEPRESENT);

if (fResult == 0) {

    /* Indicate if there is no mouse. */

    nSize = sprintf(tchBuffer, "No mouse installed.");

} else {

    /*

     * If there is a mouse, determine whether

     * its buttons are swapped.

     */

    fResult = GetSystemMetrics(SM_SWAPBUTTON);

    if (fResult == 0) {

        nSize = sprintf(tchBuffer, "Buttons not swapped.\r");

    } else {

        nSize = sprintf(tchBuffer, "Buttons swapped.\r");

    }

    /* Get the mouse speed and the threshold values. */

    SystemParametersInfo(SPI_GETMOUSE, /* get mouse info.   */

        NULL,                          /* not used          */

        &aMouseInfo,                   /* holds mouse info. */

        NULL);                         /* not used          */

    nSize += sprintf(tchBuffer + nSize,

        "Speed: %d\r", aMouseInfo[2]);

    sprintf(tchBuffer + nSize,

        "Threshold (x,y): %d,%d",

        aMouseInfo[0], aMouseInfo[1]);

}

/* Display the mouse information. */

MessageBox(NULL, tchBuffer, "Mouse information",

    MB_ICONINFORMATION);

This next example uses SystemParametersInfo to double the mouse speed and update the MouseSpeed value in the WIN.INI file.

TCHAR tchBuffer[BUFFER]; /* buffer for expanded string */

int nSize;                           /* size of string */

int aMouseInfo[3];             /* array for mouse info. */

/* Get the current mouse speed. */

SystemParametersInfo(SPI_GETMOUSE, /* get mouse info.   */

    NULL,                          /* not used          */

    &aMouseInfo,                   /* holds mouse info. */

    NULL);                         /* not used          */

/* Double it. */

aMouseInfo[2] = 2 * aMouseInfo[2];

/* Change the mouse speed to the new value and update WIN.INI. */

SystemParametersInfo(SPI_SETMOUSE, /* set mouse info.    */

    NULL,                          /* not used           */

    aMouseInfo,                    /* mouse info. to set */

    SPIF_UPDATEINIFILE);           /* update win.ini     */


 Changing the Colors of Window Elements

The following example uses the SetSysColors function to change the color of active window borders to dark purple, of active title bars to dark cyan, and of the window background to light gray.

                          /* window elements to change */

int aiElements[3] = {COLOR_ACTIVEBORDER,

                     COLOR_ACTIVECAPTION,

                     COLOR_WINDOW};

DWORD aColors[3];               /* array of RGB values */

/* Define the new colors. */

aColors[0] = RGB(0x80, 0x00, 0x80);  /* dark purple */

aColors[1] = RGB(0x00, 0x80, 0x80);  /* dark cyan   */

aColors[2] = RGB(0xC0, 0xC0, 0xC0);  /* light gray  */

/*

 * Set the window elements in aiElements to the colors

 * specified in aColors.

 */

SetSysColors(3, aiElements, aColors);

The next example uses the GetSysColor function to retrieve the color of the window background and displays the red, green, blue (RGB) value, in hexadecimal notation, in a message box.

DWORD dwResult;               /* function return value */

TCHAR tchBuffer[BUFFER]; /* buffer for expanded string */

int nSize;                           /* size of string */

/* Get the color of the window background. */

dwResult = GetSysColor(COLOR_WINDOW);

nSize = sprintf(tchBuffer,

    "Window color: {%x, %x, %x}",

    GetRValue(dwResult),

    GetGValue(dwResult),

    GetBValue(dwResult));

MessageBox(NULL, tchBuffer, "GetSysColor", MB_ICONINFORMATION);


 Shutting Down the System

The following example uses the InitiateSystemShutdown function to begin the system shutdown process on the local computer. Note that the application must first enable the SE_SHUTDOWN_NAME privilege to shut down the computer the user is logged onto.

HANDLE hToken;              /* handle to process token */

TOKEN_PRIVILEGES tkp;        /* ptr. to token structure */

BOOL fResult;                  /* system shutdown flag */

/*

 * Get the current process token handle

 * so we can get shutdown privilege.

 */

if (!OpenProcessToken(GetCurrentProcess(),

        TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))

    ErrorHandler("OpenProcessToken failed.");

/* Get the LUID for shutdown privilege. */

LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME,

        &tkp.Privileges[0].Luid);

tkp.PrivilegeCount = 1;  /* one privilege to set    */

tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

/* Get shutdown privilege for this process. */

AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,

    (PTOKEN_PRIVILEGES) NULL, 0);

/* Cannot test the return value of AdjustTokenPrivileges. */

if (GetLastError() != ERROR_SUCCESS)

    ErrorHandler("AdjustTokenPrivileges enable failed.");

/* Display the shutdown dialog box and start the time-out countdown. */

fResult = InitiateSystemShutdown(

    NULL,            /* shut down local computer */

    "Click on the main window and press \

     the Escape key to cancel shutdown.",

                                 /* msg. to user */

    20,                       /* time-out period */

    FALSE,         /* prompt user to close apps. */

    TRUE);             /* reboot after shutdown  */

if (!fResult) {

    ErrorHandler("InitiateSystemShutdown failed.");

}

/* Disable shutdown privilege. */

tkp.Privileges[0].Attributes = 0;

AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,

        (PTOKEN_PRIVILEGES) NULL, 0);

if (GetLastError() != ERROR_SUCCESS)

    ErrorHandler("AdjustTokenPrivileges disable failed.");

If the AbortSystemShutdown function is executed in the time-out period specified by InitiateSystemShutdown, the system does not shut down. The following example enables the user to prevent the system from shutting down by clicking on the application's main window and pressing the ESC key. As noted earlier, your application must enable the SE_SHUTDOWN_NAME privilege to stop the system shutdown.

HANDLE hToken;              /* handle to process token */

TOKEN_PRIVILEGES tkp;        /* ptr. to token structure */

BOOL fResult;                  /* system shutdown flag */

case WM_KEYDOWN:

    /* Process only the Escape key. */

    if (wParam != VK_ESCAPE) {

        break;

    }

    /*

     * Get the current process token handle

     * so we can get shutdown privilege.

     */

    if (!OpenProcessToken(GetCurrentProcess(),

            TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))

        ErrorHandler("OpenProcessToken failed.");

    /* Get the LUID for shutdown privilege. */

    LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME,

            &tkp.Privileges[0].Luid);

    tkp.PrivilegeCount = 1;  /* one privilege to set    */

    tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

    /* Get shutdown privilege for this process. */

    AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,

        (PTOKEN_PRIVILEGES)NULL, 0);

    /* Cannot test the return value of AdjustTokenPrivileges. */

    if (GetLastError() != ERROR_SUCCESS)

        ErrorHandler("AdjustTokenPrivileges enable failed.");

    /* Prevent the system from shutting down. */

    fResult = AbortSystemShutdown(NULL);

    if (!fResult) {

        ErrorHandler("AbortSystemShutdown failed.");

    }

    /* Disable shutdown privilege. */

    tkp.Privileges[0].Attributes = 0;

    AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,

        (PTOKEN_PRIVILEGES) NULL, 0);

    if (GetLastError() != ERROR_SUCCESS)

        ErrorHandler("AdjustTokenPrivileges disable failed.");

    break;


 System Information Functions

Following are the functions used to retrieve or set system information, shut down the system, or start Windows Help.

AbortSystemShutdown
ExpandEnvironmentStrings
GetComputerName
GetKeyboardType
GetSysColor
GetSystemDirectory
GetSystemInfo
GetSystemMetrics
GetThreadDesktop
GetUserName
GetVersion
GetVersionEx
GetWindowsDirectory
InitiateSystemShutdown
SetComputerName
SetSysColors
SystemParametersInfo
WinHelp

Obsolete or Deleted Functions

DOS3Call
GetCurrentPDB
GetCurrentTask
GetDOSEnvironment
GetWinFlags
IsTask


 System Messages

System messages provide the way to uniformly notify all applications and other components in the system of changes that may affect their operation and access to resources. Applications and other components use and process system messages to take advantage of new resources when they become available and to prevent loss of data when existing resources become unavailable.


 About System Messages

The Windows operating system provides two predefined classes of system messages: device messages and power messages. Device messages notify applications and installable drivers of device change events; power messages notify these of power management events. Applications and other components can also define and use their own system messages to provide for notification of other types of events.

This overview describes system messages, system-message broadcasts, and the specific class of system messages called device messages. For more information about power messages, see Power Management.


 System Messages and System-Message Broadcasts

Each system message consists of a message identifier and two 32-bit 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 often a notification value that further specifies the message purpose.

A system-message broadcast is simply the sending of a system message to components in the system. You broadcast a system message by using the BroadcastSystemMessage function and 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, Windows-based network drivers, and system-level device drivers. BroadcastSystemMessage sends messages to all members of each type you specify.

Most applications do not broadcast system messages. Instead, they process system messages sent by other components. The operating system typically broadcasts system messages in response to changes that usually take place within system-level device drivers. The device driver or related component generates the system message and broadcasts it to applications and other components to notify them of the change. For example, the subsystem responsible for disk drives generates and broadcasts a system 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.

Applications receive system messages through the window procedure of their top-level windows. System messages are not sent to child windows. The action an application takes in response to a system message depends on the message. Some system messages, called query messages, require the application to respond by returning either TRUE or FALSE to indicate whether the system should continue to broadcast the message to other recipients.


 Custom System Messages

You can create your own system messages and use them to coordinate activities between 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 system messages can carry information to and from your driver and the applications that use the driver.

You broadcast custom system messages using the BroadcastSystemMessage function.(System-level device drivers use a related, system-level function.) The function sends the messages to these recipients in this order: system-level device drivers, Windows-based 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 system message. Within a given recipient type, no driver is guaranteed to receive a given message before any other driver. This means a system message intended for a specific driver must have an globally-unique message identifier so that no other driver unintentionally processes it.

Query messages are a useful way to poll recipients for permission to carry out a given action. You can generate your own a 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 FALSE, the broadcast ends immediately and the function returns 0.

You can create installable drivers that broadcast and process system messages. An installable driver is a dynamic-link library (DLL) that exports a DriverProc function. The driver receives system 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-based network drivers are dynamic-link libraries that provide the underlying support for applications that use the Windows network functions to connect to and browse network resources. System-level device drivers are operating-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 book.


 Device Messages and Device Change Events

Device messages are system messages that notify applications and other components of device change events. These events occur whenever the system detects a change to the system hardware such as when the user docks or undocks a laptop computer, or inserts or removes a device such as a PCMCIA card. Change events can occur while the system is running or when the system resumes operation after temporarily being suspended.

To help ensure that applications and installable drivers do not lose data when devices become unavailable, the operating system monitors the hardware configuration and sends device message to the applications and installable drivers to notify them of the changes and to give them the opportunity to prepare for the changes before they occur.

For each event, the system broadcasts a WM_DEVICECHANGE message to all applications and installable drivers. In this message, the wParam parameter identifies the event type and the lParam parameter is usually the address of event-specific data.

The event-specific data identifies the device and provides additional detail about the event. The format of this data depends on the device type, but the first few bytes always has the same format as the DEV_BROADCAST_HDR structure. This means you can always check the dbch_devicetype member in the data to determine the device type.

The system sends a DBT_DEVICEARRIVAL message (that is, a WM_DEVICECHANGE message with wParam set to DBT_DEVICEARRIVAL) whenever a device has been inserted and is available for use. Applications typically check the device type and begin using the device immediately if appropriate.

The system sends a DBT_DEVICEQUERYREMOVE to request permission to remove a device. If an application determines that it needs the device, it can deny this request and cancel the removal by returning FALSE. To determine whether it needs the device, an application can display a dialog box to prompt the user for instructions. If the application does not need the device, it must return TRUE. The system immediately sends a DBT_DEVICEQUERYREMOVEFAILED message if any application or driver canceled a previous request to remove a device.

The system sends a DBT_DEVICEREMOVEPENDING message as a last warning before a device is removed. At this point, the application cannot cancel the removal, so if it is using the device it must prepare for its removal to prevent loss of data. This is especially important when a network connection is being removed. The application must determine whether any of its open files or pipes are on that connection. It can do this by comparing the network resource identifier in the event-specific data of the message with the resource identifiers previously obtained for the files and pipes. The system sends a DBT_DEVICEREMOVECOMPLETE when a device has been removed and is no longer available.

The system sends DBT_DEVICETYPESPECIFIC message whenever a device-specific event occurs. It sends a DBT_CONFIGCHANGED message if current configuration has changed, such as when the operational parameters of a device have been changed by the user.


 Using System Messages

•	Processing a Request to Remove a Device


 Processing a Request to Remove a Device

An application receives a DBT_DEVICEQUERYREMOVE message when a component in the system has decided to remove a given device. When the application receives this message, it should determine whether it is using the given device and either cancel or prepare for the removal. In the following example, the application processes the message by checking the type of device that is to be removed.

PDEV_BROADCAST_HDR pdbch;
PDEV_BROADCAST_VOLUME pdbcv;

case WM_DEVICECHANGE:
    pdbch = (PDEV_BROADCAST_HDR) lParam;
    switch (pdbch->dbch_devicetype) {
    case DBT_DEVTYP_VOLUME:
        pdbcv = (PDEV_BROADCAST_VOLUME) pdbch;
        if (pdbcv->dbcv_flags == DBTF_MEDIA)
            // pdbcv->dbcv_unitmask identifies which logical drive
        }
        return TRUE;
    default:
        return TRUE;
    }


 System Message Reference

This section describes the functions, messages, and structures that support system messages.


 System Message Functions

This section describes the functions that support system messages.

BroadcastSystemMessage


 System Messages Reference

This section describes the device messages.

DBT_CONFIGCHANGED
DBT_DEVICEARRIVAL
DBT_DEVICEQUERYREMOVE
DBT_DEVICEQUERYREMOVEFAILED
DBT_DEVICEREMOVECOMPLETE
DBT_DEVICEREMOVEPENDING
DBT_DEVICETYPESPECIFIC
WM_DEVICECHANGE


 System Message Structures

This section describes the structures associated with device messages.

_DEV_BROADCAST_USERDEFINED
DEV_BROADCAST_HDR
DEV_BROADCAST_OEM
DEV_BROADCAST_PORT
DEV_BROADCAST_VOLUME


 Tape Backup

The tape functions provided in the Microsoft® Win32® application programming interface (API) enable backup applications to read from and write to a tape, initialize a tape, and retrieve tape or tape drive information.


 About Tape Backup

In Microsoft® Windows™, a tape volume consists of a recording medium and its physical carrier. The entire length of tape in a volume is not available for recording data. Short sections at the beginning and the end of the tape are reserved for attaching the tape to the hubs in the carrier. The first position on the tape where data can be recorded is the called the beginning-of-medium marker, and the last position is called the end-of-medium marker.

Every tape volume has one or more partitions. A partition is a portion of the volume, containing its own beginning and ending points, that does not overlap with any other portion of the volume. Each partition has three predefined positions. The first position in a partition where you can record data is called the beginning-of-partition marker, and the last is called end-of-partition marker. The early-warning position is located immediately before the end-of-partition marker. The early-warning position notifies tape applications to transfer buffered data to the tape before reaching the end-of-partition marker.

The area between a partition's beginning and ending points is typically divided into sections by filemarks or setmarks. Filemarks and setmarks are special recorded elements that do not contain user data; they simply divide the partition into smaller areas to provide an address scheme. Filemarks and setmarks serve similar purposes, but setmarks provide faster positioning on high-capacity tape drives.

Typically, tape devices support filemarks and setmarks. Support of both enables tape data to be formatted such that setmarks separate data from different disk volumes and filemarks separate data from individual files on a disk volume.

Another recorded element that denotes locations on the tape is an erase gap, an area of erased tape or a pattern that the device does not recognize as a mark or as user data.

There are three types of filemarks. A short filemark contains a short erase gap that cannot be overwritten unless the write operation is performed from the beginning of the partition or from an earlier long filemark. A long filemark contains a long erase gap that enables an application to position the tape at the beginning of the filemark and to overwrite the filemark and the erase gap. A normal filemark does not contain an erase gap. Tape devices that use filemarks support either short and long filemarks or normal filemarks, but not all three.

The area on a partition between setmarks or filemarks is available for recording data. A unit of data written to or read from a tape is referred to as a block.


 Tape Initialization

An application must use the CreateFile function to create a handle of a tape device. This handle is used in subsequent operations on the tape in the device.

Before an application writes to a tape, the tape must be formatted according to the needs of the application and the capabilities of the tape drive being used. The CreateTapePartition function reformats a tape, creating on it a given number of partitions of a specified size.

The PrepareTape function prepares a tape to be accessed or removed. This function can load, unload, lock, or unlock a tape. This function can also tension the tape by moving the tape to the end of the tape and back to the beginning.

To retrieve and set information about a tape and tape drive, an application uses the GetTapeParameters, SetTapeParameters, and GetTapeStatus functions.

GetTapeParameters retrieves information that describes a tape or a tape drive. The tape information includes the tape's type, density, and block size; the number of partitions on the tape; the amount of tape remaining; and so on. The tape drive information includes the drive's default block size, the maximum partition count, and the features that are supported.

SetTapeParameters either sets the tape block size or sets the tape drive flags that indicate whether the drive supports hardware error correction, data compression, data padding, or any combination of the three.

GetTapeStatus indicates whether the tape drive is ready to process tape commands.


 Tape Input and Output

The Win32 API provides several functions that applications can use to perform input and output (I/O) on a tape drive. Tape I/O is similar to I/O performed on a communications device.

When performing tape I/O, some tape drives store tape firmware information in the first few blocks on a tape, typically using some portion of the first 100 blocks. Applications should not use those blocks. More specific information on this subject is available from individual tape system manufacturers. In general, an application that skips the first 100 blocks on a tape will avoid tape drive idiosyncracies.

The GetTapePosition and SetTapePosition functions retrieve and move the current tape position. The WriteTapemark function writes a specified number of setmarks, filemarks, short filemarks, and long filemarks. The EraseTape function erases all or part of a tape.

The ReadFile and WriteFile functions read and write file data from and to the tape. The data is read and written in complete blocks. If the tape's block size is 512 bytes, all read and write operations must use buffers that are simple integer multiples of that block size: 512, 1024, 1536, 2048, and so on. Most, if not all, drives only allow a write operation after the tape is rewound or after a read operation produces an end-of-data error message.

If ReadFile encounters a filemark, the data up to the filemark is read and the function fails. (The GetLastError function returns an error code indicating the type of filemark that was encountered.) To continue reading beyond the filemark, an application must move the tape past the filemark and call ReadFile again.

ReadFile and WriteFile read and write only the data stream. The BackupRead and BackupWrite functions read and write all the streams associated with a file. These include data, extended attributes, security, and alternative data streams. The security and alternate data streams are relevant only on the new technology file system (NTFS) partition.

The BackupSeek function seeks forward in a file initially accessed by BackupRead or BackupWrite. This function enables an application to skip information that causes access errors.

If an application needs to access only the file data, it should use ReadFile and WriteFile. These functions can also read alternative data streams if the streams were created by using the CreateFile function.

A tape-backup application must use BackupRead and BackupWrite to copy all information pertaining to a file. However, these functions do not read or write file characteristics such as attributes, file creation time, and so on. Applications must use the file input and output functions, such as GetFileAttributes and SetFileAttributes, to retrieve and set those values.


 Using Tape Backup

•	Creating a backup application

•	Backing up and restoring Posix file links


 Creating a Backup Application

To perform any input or output on a tape, a backup application must first obtain a handle of the tape device. The following code sample shows how to use the CreateFile function to open a tape device.

HANDLE hTape;   /* handle to tape device */

hTape = CreateFile(

    "\\\\.\\TAPE0",     /* name of tape device to open */

    GENERIC_READ | GENERIC_WRITE, /* read-write access */

    0,                    /* not used                  */

    0,                    /* not used                  */

    OPEN_EXISTING,        /* required for tape devices */

    0,                    /* not used                  */

    NULL);                /* not used                  */

To back up a directory tree to a tape, an application must use the FindFirstFile and FindNextFile functions to traverse the directory tree. Each time a file is found, the application should get the file's attributes by using the GetFileAttributes function. If there are hard links, the application should determine the number of links and save the file's unique identifier in a table for future comparisons. The first time a file is found, the application should use CreateFile to open the file and the BackupRead function to begin the backup. Then it can use the WriteFile function repeatedly to transfer all the information in the buffer filled by BackupRead to the tape. The second time a file is found (checked against the table of file identifiers when there are hard links), the application can simply write the general file information to the tape, followed by a stream whose identifier is BACKUP_LINK.

When restoring files from tape to disk, an application must use the CreateFile, BackupWrite, and ReadFile functions. For each file on the tape, the application should use CreateFile to create a new file on disk and BackupWrite to begin restoring the file. Then it should use ReadFile repeatedly until all the information for the file has been read from the tape into the buffer filled by BackupWrite. If one of the streams in the BackupWrite buffer has a BACKUP_LINK stream identifier, the application must establish a hard link. If the data needed to establish the link does not exist, BackupWrite fails. The application can use a preexisting catalog to locate and restore the original data, or it can notify the user that the file data to be restored is in a different location.


 Backing Up and Restoring Posix File Links

A backup application can use the BackupWrite function to recreate Posix file links.

The BackupRead function does not return Posix file link data. A backup application must maintain the link information itself. The following pseudocode presents algorithms for backing up and restoring Posix file link data along with other file information.

PseudoCode Algorithm for Backing Up Posix File Links

1.  Initialize and empty a list of known links.

2.  While there are more files to back up

3.     Read the disk and get the next file.

4.     Open the file for read.

5.     Call GetFileInformationByHandle() to get the

          NumberOfLinks and the FileIndex.

6.     If the NumberOfLinks is greater than 1

7.        Search the list of know links looking for

             the same FileIndex.

8.           If a match is NOT found

9.              add the full path of the file and the

                   FileIndex to the list.

10.             Call BackupRead() to copy all data to

                   your backup media.

10.          Else

11.             Mark the data as a LINK on your backup media

11.             store the full path from the list

                   to your backup media.

12.          Endif

13.    Else

14.       Call BackupRead() to copy all data to your

             backup media.

15.    Endif

16. EndWhile

PseudoCode Algorithm for Restoring Posix File Links

1.  While there are more files to restore

2.     If the file is a LINK

3.        use the full path which was saved as data

             to open the file.

4.        Initialize a WIN32_STREAM_ID structure with

             dwStreamId equal to BACKUP_LINK.

5.        Initialize the dwStreamAttributes to 0.

6.        Initialize the dwStreamNameSize to 0.

7.        Initialize a buffer containing the full path

             of the file you are restoring in UNICODE.

8.        Initialize the dwStreamSizeHigh to 0.

9.        Initialize the dwStreamSizeLow to the size

             in bytes of the buffer     containing the full path.

10.       Call BackupWrite() with the WIN32_STREAM_ID

11.       Call BackupWrite() with the buffer containing

             the full path.

13.          Else

14.       Call BackupWrite() with the data stored on

             your backup media.

15.    Endif

16. EndWhile


 Tape Backup Functions

Following are the functions used for tape backup.

BackupRead
BackupSeek
BackupWrite
CreateTapePartition
EraseTape
GetTapeParameters
GetTapePosition
GetTapeStatus
PrepareTape
SetTapeParameters
SetTapePosition
WriteTapemark


 Time

The Microsoft® Win32® application programming interface (API) provides a variety of date and time functions, structures, and messages to retrieve and set the date and time for the system, files, and the local time zone.


 About Time

This overview describes various functions, structures, and messages and explains how to use them to examine and modify dates and times.

For information about related topics, see the following overviews:

•	Files

•	File Systems


 System Time

System time is the current date and time of day. Windows keeps system time so that your applications have ready access to accurate time. When Windows first starts, it sets the system time to a value based on the real-time clock of the computer and thereafter regularly updates the time.

Windows bases system time on coordinated universal time (UTC). UTC-based time is loosely defined as the current date and time of day in Greenwich, England. You can retrieve the system time by using the GetSystemTime function. GetSystemTime copies the time to a SYSTEMTIME structure that contains individual members for month, day, year, weekday, hour, minute, second, and milliseconds.

Because system time is UTC-based, the time copied to the SYSTEMTIME structure may not be the same as the local time—the date and time of day for your time zone. You can retrieve the local time by using the GetLocalTime function. GetLocalTime converts the system time to a local time based on the current time-zone settings and copies the result to a SYSTEMTIME structure.

The current time-zone settings control how Windows converts between UTC and local time. You can retrieve the current time-zone settings by using the GetTimeZoneInformation function. The function copies the setting to a TIME_ZONE_INFORMATION structure and returns a value indicating whether local time is currently in standard or daylight-savings time. You can set the time-zone settings by using the SetTimeZoneInformation function.

You can set the system time by using the SetSystemTime or SetLocalTime function. SetSystemTime assumes you have specified a UTC-based time; SetLocalTime assumes local time and converts to UTC before setting the system time. If you change the system time, you should send the WM_TIMECHANGE message to all top-level windows by using the SendMessage function.


 Windows Time

Windows time is the number of milliseconds elapsed since Windows started running. To ensure that applications designed for earlier versions of Windows continue to run successfully, the GetTickCount and GetCurrentTime functions return the current Windows time. However, if your application requires the current date and time of day, you should use the GetSystemTime or GetLocalTime function whenever possible.

Because GetTickCount and GetCurrentTime are identical in operation, you should use GetTickCount to retrieve Windows time.You typically use GetTickCount to compare the current Windows time with the time returned by the GetMessageTime function. GetMessageTime returns the Windows time when the given message was created.

Windows time is stored as a 32-bit value, which means Windows can record no more than 2^32 millisecond intervals before the 32-bit value overflows to zero. This is approximately 49.7 days. If you use Windows time, check for the overflow condition when comparing times.


 File Times

A file time represents the specific date and time at which a given file was created, last accessed, or last written to. Windows records file times whenever applications create, access, and write to files. Windows records the times using a 64-bit value specifying the number of 100-nanosecond intervals that have elapsed since 12:00 A.M. January 1, 1601 (UTC). Writing to a file changes the last write time; writing to or reading from the file (including running an executable file) changes the last access time.

Note  Not all file systems can record creation and last access time. In particular, the file allocation table (FAT) file system records only last-write times.

You can retrieve the file times for a given file by using the GetFileTime function. GetFileTime copies the creation, last access, and last write times to individual FILETIME structures. Each structure consists of two 32-bit values that combine to form the single 64-bit value. You can also retrieve the file times by using the FindFirstFile and FindNextFile functions. These functions copy the times to FILETIME structures in a WIN32_FIND_DATA structure.

You can set the file times for a file by using the SetFileTime function. This function lets you modify creation, last access, and last write times without changing the content of the file. You can compare the times of different files by using the CompareFileTime function. The function compares two file times and returns a value indicating which time is greater or returns zero if the times are equal.

To make a file time more meaningful to a user, you can extract the month, day, year, and time of day from a file time by using the FileTimeToSystemTime function. FileTimeToSystemTime converts the file time and copies the individual values for date and time of day to a SYSTEMTIME structure.

Windows records all file times in UTC-based times, but you can convert a file time to the local time for your time zone by using the FileTimeToLocalFileTime function. Before displaying a file time to a user, applications typically convert the file time to local time, then extract the month, day, year and time of day using FileTimeToSystemTime.

If you plan to modify file times for given files, you can convert a date and time of day to a file time by using the SystemTimeToFileTime function. If the original date and time of day are given in the local time for your time zone, you can convert the resulting file time to UTC by using the LocalFileTimeToFileTime function. Always make sure the file times you set using SetFileTime are valid UTC-based times.


 MS-DOS Date and Time

MS-DOS date and MS-DOS time are packed 16-bit values that specify the month, day, year, and time of day an MS-DOS file was last written to. MS-DOS records the date and time whenever an MS-DOS application creates or writes to a file. MS-DOS applications retrieve this date and time using MS-DOS functions. When you use the GetFileTime function to retrieve the file times for files that were created by MS-DOS, GetFileTime automatically converts MS-DOS dates and times to UTC-based times.

If you encounter an MS-DOS date and time that has not been converted, you can convert it to a UTC-based time by using the DosDateTimeToFileTime function. This function copies the converted date and time to a FILETIME structure. You can convert the value back to an MS-DOS date and time by using the FileTimeToDosDateTime function.


 Using Time

•	Retrieving the last-write time

•	Changing a file time to the current time

•	Setting the system time


 Retrieving the Last-Write Time

The following example retrieves the last-write time for a file, converts it to local time based on the current time-zone settings, and creates a date and time string that can be shown to the user.

// GetLastWriteTime - retrieves the last-write time and converts the
//                      time to a string
// Return value - TRUE if successful, FALSE otherwise
// hFile      - must be a valid file handle
// lpszString - address of buffer to receive string

BOOL GetLastWriteTime(HANDLE hFile, LPSTR lpszString)
{
    FILETIME ftCreate, ftAccess, ftWrite, ftLocal;
    SYSTEMTIME stCreate;

    // Retrieve the file times for the file.
    if (!GetFileTime(hFile, &ftCreate, &ftAccess, &ftWrite))
        return FALSE;

    // Convert the last-write time to local time.
    if (!FileTimeToLocalFileTime(&ftWrite, &ftLocal))
        return FALSE;

    // Convert the local file time from UTC to system time.
    FileTimeToSystemTime(&ftLocal, &stCreate);

    // Build a string showing the date and time.
    wsprintf(lpszString, "%02d/%02d/%d  %02d:%02d",
        stCreate.wDay, stCreate.wMonth, stCreate.wYear,
        stCreate.wHour, stCreate.wMinute);

    return TRUE;
}


 Changing a File Time to the Current Time

The following example sets the last-write time for a file to the current system time.

// SetFileToCurrentTime - sets last write time to current system time
// Return value - TRUE if successful, FALSE otherwise
// hFile  - must be a valid file handle

BOOL SetFileToCurrentTime(HANDLE hFile)
{
    FILETIME ft;
    SYSTEMTIME st;
    BOOL f;

    GetSystemTime(&st);              // gets current time
    SystemTimeToFileTime(&st, &ft);  // converts to file time format
    f = SetFileTime(hf,              // sets last-write time for file
        (LPFILETIME) NULL, (LPFILETIME) NULL, &ft);

    return f;
}


 Setting the System Time

The following example sets the system time.

// SetNewTime - sets system time
// Return value - TRUE if successful, FALSE otherwise
// hour     - new hour (0-23)
// minutes  - new minutes (0-59)

BOOL SetNewTime(WORD hour, WORD minutes)
{
    SYSTEMTIME st;
    char *pc;

    GetSystemTime(&st);       // gets current time
    st.wHour = hour;          // adjusts hours
    st.wMinute = minutes;     // and minutes
    if (!SetSystemTime(&st))  // sets system time
        return FALSE;
    return TRUE;
}


Date and Time Functions
 Time Functions

Following are the functions used with time formats.

CompareFileTime
DosDateTimeToFileTime
FileTimeToDosDateTime
FileTimeToLocalFileTime
FileTimeToSystemTime
GetCurrentTime
GetFileTime
GetLocalTime
GetSystemTime
GetSystemTimeAdjustment
GetSystemTimeAsFileTime
GetTickCount
GetTimeZoneInformation
LocalFileTimeToFileTime
SetFileTime
SetLocalTime
SetSystemTime
SetSystemTimeAdjustment
SetTimeZoneInformation
SystemTimeToFileTime
SystemTimeToTZSpecificLocalTime


 Window Stations and Desktops

This overview describes the new window station and desktop functionality, and is primarily intended for developers of Win32 services. Developers of typical applications that will be run by the logged-on user do not need to be concerned about window stations and desktops.

Beginning with Microsoft® Windows NT™ version 3.5, the Win32® API provides new window station and desktop functionality that enables Win32 services to call USER32 and GDI32 functions regardless of the logon account in which the service is running. This new functionality enables Win32 services 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 Win32 services use the window station and desktop support, see Interactive Services.


 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	Returns a handle of 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 of 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 of 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 Win32 services 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 of 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 of 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 Win32 service attempts to connect to Win32 and no window station exists for the process' logon session, Win32 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) that must go to the Win32 server. The Win32 server 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 Win32 server attempts to open for MAXIMUM_ACCESS and connect to a window station as follows:

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

b.	Otherwise, if the process is running in the logon session of the interactive user, the process connects to the interactive window station.

c.	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, Win32 tries to create the window station and a default desktop.


 Thread Connection to a Desktop

After a process connects to a window station, the Win32 server assigns a desktop to the thread making the connection to Win32. The desktop assigned during this connection process cannot be closed by calling the CloseDesktop function. The Win32 server 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 Win32 server attempts to open for MAXIMUM_ACCESS and connect to a desktop as follows:

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

b.	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 Win32 server searches the process's handle table for inherited handles. The Win32 server 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 Win32 server 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.


 Using Window Stations and Desktops

•	Creating an interactive process

•	Interacting with the user by a win32 service

•	Handling logoff events


 Creating an Interactive Process

The following code fragment shows how a Win32 service process 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 Win32 service 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 Win32 service.

To create an interactive process as shown in this example, a Win32 service 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 by a Win32 Service

For a noninteractive Win32 service 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 Win 32 services 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 future versions of Windows NT that may 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

Win32 services that interact with the user should be prepared to handle logoff events. When a logoff event occurs, the Win32 service 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 functions and structures are associated with window station and desktop features.


 Window Station and Desktop Functions

Use the following functions to implement window station and desktop features:

CloseDesktop
CloseWindowStation
CreateDesktop
CreateWindowStation
EnumDesktops
EnumDesktopWindows
EnumWindowStations
GetProcessWindowStation
GetThreadDesktop
GetUserObjectInformation
GetUserObjectSecurity
OpenDesktop
OpenInputDesktop
OpenWindowStation
SetProcessWindowStation
SetThreadDesktop
SetUserObjectInformation
SetUserObjectSecurity
SwitchDesktop


 Window Station and Desktop Structures

Use the following structure to manipulate window station and desktop objects:

USEROBJECTFLAGS


 End User Defined Characters

End-user-defined characters (EUDC) are customized characters that users install for viewing and printing documents.

This overview discusses the TrueType fonts that support end-user-defined characters and describes the functions used to access and manage these characters in Win32-based applications.


 About End User Defined Characters

End-user-defined characters give users a way to form names and other words using characters that are not available in standard screen and printer fonts.

End-user-defined characters are available only in Asian-language versions of the Microsoft Windows operating system.


 Character Sets and Fonts

An end-user-defined character is always associated with a double-byte character set (DBCS) and a TrueType font. Applications identify the specified character by using the character's assigned DBCS character value, and the operating system uses this value to locate shape and style information in a corresponding TrueType font. The shape and style information specifies how the character is drawn on the screen or printed page.

The DBCS character values that can be assigned depend on the specified character set. Each set has at least one range of reserved values for use as end-user-defined characters. The system or applications explicitly define these ranges by setting appropriate values under the EUDCCodeRange key in the registry. In the registry, each character set is identified by a unique code-page number.

To create an end-user-defined character, the user chooses a character value that is within the specified range and adds the shape and style information to the TrueType font in the entry that corresponds to that character value. Users create the shape and style information using an EUDC editor or by purchasing end-user-defined font packages from font vendors. Any DBCS TrueType font can contain end-user-defined characters. The font is called a "separate" EUDC font if it contains only end-user-defined characters. The font is an "integrated" EUDC font if it contains standard characters as well as end-user-defined characters.

Separate EUDC fonts are said to be either "typeface-aware" or "typeface-unaware." A typeface-unaware font is designed to be a general purpose font that can be used with fonts of different typeface styles and of different implementations, such as GDI raster, WIFE, device, and TrueType fonts. A typeface-aware font is designed for use with a specific TrueType font.

The system default EUDC font is a typeface-unaware font that the system automatically associates with all DBCS fonts except those TrueType fonts that have explicitly associated typeface-aware fonts. Applications set the system default EUDC font by setting the value of the SystemDefaultEUDCFont name under the EUDC key in the registry. Similarly, applications can associate typeface-aware fonts with corresponding TrueType fonts by specifying a typeface name and associated font file under the EUDC key. Separate EUDC fonts cannot be associated with integrated EUDC fonts.

The system "hides" the system default EUDC and typeface-aware fonts. This means applications cannot enumerate or otherwise examine these fonts using GDI functions. Applications, such as EUDC editors and Control Panel, must use the registry entries to add, modify, and delete EUDC fonts.

End-user-defined characters can also be used in Unicode-enabled applications. The reserved ranges for each character set are mapped to corresponding values in the Unicode private use area (values 0xE000 and higher). There are mappings for both Japanese and Chinese character sets. For a list of these mappings, see Japanese EUDC Ranges and Chinese EUDC Ranges.


 Writing, Mapping, and Sorting Characters

Applications write end-user-defined characters to the screen or printer the same way as writing other characters, by using output functions such as TextOut and ExtTextOut. These functions automatically retrieve character information from EUDC fonts if EUDC is enabled. When writing end-user-defined characters, the action of the text output function depends on the currently selected font. If the selected font is an integrated EUDC font, the function retrieves character information from that font. If the selected font is a DBCS TrueType font that has an associated typeface-aware EUDC font, the function retrieves information from the specified typeface-aware font. If the selected font does not have an associated typeface-aware font, the function retrieves information from the system default EUDC font. If the character is not in the system default EUDC font or there is no system default EUDC font, the function writes the default character defined by the selected font.

Applications can map end-user-defined characters to and from Unicode by using the MultiByteToWideChar and WideCharToMultiByte functions. The MultiByteToWideChar function maps an end-user-defined character to a character position in the Unicode private use area. The WideCharToMultiByte function maps a character in the private use area to its multibyte character counterpart, if such a mapping exists. The code page specified in this function must contain an EUDC code range for the mapping to occur. If it does not, the function returns the default character for any characters in the Unicode private use area.

Both MultiByteToWideChar and WideCharToMultiByte preserve the "round trip" mapping of end-user-defined characters from a code page to Unicode and back to the original code page. But these functions do not necessarily preserve mapping to other code pages. For example, if a character from code page 932 is mapped to Unicode, then mapped from Unicode to another code page with an EUDC range, it is likely that the original character will be mapped to a different end-user-defined character in the destination code page. Similarly, mapping a Unicode string to a code page that has an EUDC range may have unintended results. If the Unicode string contains a private-use code point, that code point may be mapped to an end-user-defined character whether or not the code point actually represents such a character.

Applications can compare strings that contain end-user-defined characters by using the CompareStringA function. The function maps the characters to the Unicode end user zone before comparing character values. Applications can create a sort key for the string by using the LCMapStringA function and the LCMAP_SORTKEY value. This function maps characters to Unicode first. All characters in the private use area are sorted after all other Unicode characters. Within the area, characters are sorted in numerical order. If an application attempts to retrieve CTYPE ifnormation for an end-user-defined character by using the GetStringTypeA function, the function returns NULL for each character.


 End User Defined Character Reference

This section provides reference information on:

•	Registry entries.

•	End user defined character constants.


 Registry Entries

The following registry information shows the appropriate entries for use with end user defined characters.


 EUDCCodeRange

EUDCCodeRange
    CodePage=FromTo[,FromTo]

The EUDCCodeRange registry entry contains entries that define end-user-defined characters (EUDC) code ranges for the various code pages (character sets).

EUDCCodeRange Key

The EUDCCodeRange key has the following location in the registry:

HKEY_LOCAL_MACHINE\ 	System\CurrentControlSet\Control\NLS\CodePage\EUDCCodeRange

The key contains one or more values specifying the range of character values within a codepage that are available for end-user-defined characters. Under this key, a value name is one of these code-page values:

Value	Meaning
932	Japan
936	Simplified Chinese
949	Unified Hangeul Code (Hangeul TongHabHyung Code)
950	Traditional Chinese
1361	Johab
The value associated with each name is a string consisting of one or more pairs of 4-digit hexadecimal numbers, with the numbers in each pair separated by a hyphen (-) and each pair separated from any preceding pair by a comma (,). The following example illustrates this format:

HKEY_LOCAL_MACHINE\

System\CurrentControlSet\Control\NLS\CodePage\EUDCCodeRange

923=F040-F9FC

950=FA40-FEFE, 8E40-A0FE, 8140-8DFE, C6A1-C8FE

CodePage

A user-defined value name that identifies the code page. It must be the letters "CP" followed by 5 decimal digits specifying the code page.

FromTo

A string value consisting of a pair of 4-digit hexadecimal values separated by a hyphen (-). Multiple FromTo values may be specified, but each must be separated from the previous by a comma (,).

The following examples show possible EUDC ranges for code pages 923 and 950:

CP00923=F040-F9FC
CP00950=FA40-FEFE,8E40-A0FE,8140-8DFE,C6A1-C8FE


 EUDC

EUDC
    SystemDefaultEUDCFont=TrueTypeEUDCFontFileName
    TrueTypeFontTypeface=TrueTypeEUDCFontFileName

EUDC Key

The EUDC registry key has the following location in the registry:

HKEY_CURRENT_USER\EUDC

The EUDC key contains one or more subkeys with each subkey containing values defining the fonts associated with end-user-defined characters for a given code page. Under the EUDC, a subkey name can be one of these code-page numbers:

Value	Meaning
932	Japan
936	Simplified Chinese
949	Unified Hangeul Code (Hangeul TongHabHyung Code)
950	Traditional Chinese
1361	Johab
One value under the subkey has the name SystemDefaultEUDCFont. Other values, if any, have names that identify a typeface. The values associated with these names are strings specifying the name of TrueType font file containing the given font. The following example shows the EUDC key for code page 932:

HKEY_CURRENT_USER\EUDC\932

SystemDefaultEUDCFont=EUDC.TTF

MS Mincho=MINEUDC.TTF

MS Gothic=GTEUDC.TTF

SystemDefaultEUDCFont

Predefined value name used to set the system default font. The corresponding value must be a string that identifies a typeface-unaware EUDC font. There is no system default EUDC font unless this entry is explicitly specified.

TrueTypeFontTypeface

A user-defined value name that identifies the typeface name associated with a TrueType font. The corresponding value must be a string that identifies a typeface-aware EUDC font.

TrueTypeEUDCFontFileName

A string value consisting of the filename of a "separate" EUDC font file.

The following example sets the system default EUDC font to be EUDC.TTF and associates the typeface-aware fonts, MINEUDC.TTF and GOTEUDC.TTF, with the typeface names "MS Mincho" and "MS Gothic":

SystemDefaultEUDCFont=EUDC.TTF
MS Mincho=MINEUDC.TTF
MS Gothic=GOTEUDC.TTF


 End User Defined Character Constants

The following constants are used with end user defined characters in the following Far Eastern languages.


 Japanese EUDC Ranges

The following table shows the mapping between the Japanese Microsoft Standard Character Set (ShiftJIS) and Unicode.

Shift JIS	Unicode
F040	U+E000
F041	U+E001
F042	U+E002
:	:
F9FA	U+E755
F9FB	U+E756
F9FC	U+E757


 Chinese EUDC Ranges

The following table shows the mapping between the Chinese character sets (BIG-5 and GB 2312-80) and Unicode.

BIG-5	Unicode
FA40 - FEFE	U+E000 - U+E310
8E40 - A0FE	U+E311 - U+EEB7
8140 - 8DFE	U+EEB8 - U+F6B0
C6A1 - C8FE	U+F6B1 - U+F8FF
GB 2312-80	Unicode
F8A1 - FEFE	U+E000 - U+E29F
AAA1 - AFFE	U+E2A0 - U+E4DF


 Korean EUDC Ranges

The following table shows the mapping from Korean EUDC characters (Unified Hangeul Code) and Unicode.

Unified Hangeul	Unicode
C9A1 - C9FE	U+E000 - U+E05D
FEA1 - FEFE	U+E05E - U+E0BB


 Input Method Editor

The input method editor (IME), available in Asian versions of the Microsoft Windows operating system, helps minimize the effort needed by users to enter text containing characters from Unicode and double-byte character sets.

This overview describes the IME and explains how to use the input method manager functions to create and manage IME windows.


 About Input Method Editor

The input method editor relieves users of the need to remember all possible character values. Instead, the IME monitors the user's keystrokes, anticipates the characters the user may want, and presents a list of candidate characters from which to choose.

By default, the IME provides an IME window through which users enter keystrokes and view and select candidates. Applications developed for the Win32 application programming interface (API) can use the input method manager (IMM) functions and messages to create and manage their own IME windows, providing a custom interface while using the conversion capabilities of the IME.


 Status, Composition, and Candidates Windows

The status, composition, and candidates windows form the user interface for the IME. The status window indicates that the IME is open and provides the user the means to set the conversion modes. The composition window appears when the user enters text and, depending on the conversion mode, either displays the text as entered or displays converted text. The candidates window appears in conjunction with the composition window. It contains a list of "candidates" (alternative characters) for the selected character or characters in the composition window. The user can scroll through the candidates list and select the desired character(s), then return to the composition window. The user can compose the desired text in this way until the composition string is finalized and the window is closed. The IME sends the composed characters to the application in the form of WM_IME_CHAR or WM_IME_COMPOSITION/GCS_RESULT messages. If the application does not process these messages, the DefWindowProc function translates them into one or more WM_CHAR messages.

By default, the system automatically creates and manages status, composition, and candidates windows for all windows that require text input. For many applications, this default processing is sufficient. These applications rely entirely on the system for IME support and are said to be IME-unaware because they are unaware of the many tasks the system carries out to manage the IME windows.

An IME-aware application, on the other hand, participates in the creation and management of IME windows. Such applications control the operation, position, and appearance of the default windows by sending messages to and by intercepting and processing messages intended for these windows. In some cases, applications create their own IME windows and provide complete processing for their custom status, composition and candidates windows.


 IME Window Class

The "IME" window class is a predefined system global class that defines the appearance and behavior of the standard IME windows. The class is similar to common control classes in that you create a window of this class by using the CreateWindowEx function. Like static controls, an IME window does not respond to user input by itself. Instead, it notifies the IME of user input actions and processes control messages sent to it by the IME or applications to carry out a response to the user action.

IME-aware applications sometimes create their own IME windows using the IME class. This allows the application to take advantage of the default processing of the IME window while having control of the positioning of the window.


 IME Messages

The system sends IME window messages to the window procedure of the application when certain event occur that affect the IME windows. For example, the system sends the WM_IME_SETCONTEXT message to the application when a window is activated. IME-unaware application pass these messages to the DefWindowProc function which sends them to the corresponding default IME window. IME-aware applications either process these messages or forward them the their own IME windows.

You can direct an IME window to carry out an action, such as change the position of composition window, by using the WM_IME_CONTROL message. The IME notifies the application about changes to the composition string by using the WM_IME_COMPOSITION message and about general changes to the status of the IME windows by sending the WM_IME_NOTIFY message.


 Input Context

An input context is an internal structure, maintained by the IME, that contains information about the status of the IME and is used by IME windows. By default, the system creates and assigns an input context to each thread. Within the thread, this default input context is a shared resource and is associated with each newly created window.

To retrieve or set information in the IME, an application must first retrieve a handle to the input context associated with a given window. You retrieve the handle by using the ImmGetContext function. You can use the retrieved handle in subsequent calls to the input method manager functions to retrieve and set IME values, such as the composition window style, the composition style, and the status window position. Once you have finished using the context, you must release it using the ImmReleaseContext function.

Because the default input context is a shared resource, any changes you make to it apply to all windows in the thread. However, you can override this default behavior by creating and associating your own input context to one or more window of the thread. The changes you make to your own input context apply only to the windows with which it is associated.

You can create an input context by using the ImmCreateContext function. You assign the context to a window by using the ImmAssociateContext function. This function returns the handle of the previously associated input context. If you have not associated an input context with the window before, the returned handle is for the default input context. You should save this handle and later reassociate with the window if you no longer want to use your own input context.

Once an input context is associated with a window, the system automatically selects that context when the window is activated and receives the input focus. The style and other information in the input context affects subsequent keyboard input for that window, determining whether and how the IME operates.

You must destroy any input context you create before terminating your application. You destroy an input context by using the ImmDestroyContext function. Before destroying it, you must remove the input context from any association it has with windows in the thread by using the ImmAssociateContext function.


 Composition String

The composition string is the current text in the composition window. This is the text that the IME converts to final characters. Each composition string consists of one or more clauses, where a clause is the smallest combination of characters that the IME can convert to a final character. You can get and set the composition string and get and set the composition string by using the ImmGetCompositionString and ImmSetCompositionString functions.

As the user enters text in the composition window, the IME tracks the status of the composition string. This status includes attribute information, clause information, typing information, and cursor position. You can retrieve the composition status by using the ImmGetCompositionString function.

In the attribute information array, all characters of one clause must have the same attribute. The attribute information is an array of 8-bit values that specifies the status of characters in the composition string. There is one value for each byte in the string, including one byte each for the lead and second bytes of any double-byte characters in the string. For each value in the array, bits 0 through 3 can be one combination of these values:

ATTR_INPUT
	Character being entered by the user. It is yet to be converted by the IME.
ATTR_INPUT_ERROR
	Character is the error character and cannot be converted by the IME.
ATTR_TARGET_CONVERTED
	Character converted by the IME. The user has selected this character and the IME has converted it.
ATTR_CONVERTED
	A converted character. The IME has already converted this character.
ATTR_TARGET_NOTCONVERTED
	Character being converted. The user has selected this character but the IME has not yet converted it.
All other values are reserved. In Japanese, any unconverted character having the ATTR_INPUT attribute is a Hiragana, Katakana, or alphanumeric character. In Korean, this character is a Hangeul character that is not converted by IME yet. In Traditional and Simplified Chinese, each IME may limit its character in some range.

You can retrieve the composition status by using the ImmGetCompositionString function.

The clause information is an array of 32-bit values that specify the positions of the clauses in the composition string. There is one value for each clause and a final value that specifies the length of the full string. Each value in the array specifies the offset, in bytes, from the beginning of the string to the clause. The first value is always 0 because the first clause always starts at the beginning of the string. For example, if a string has two clauses, the clause information has three values: the first value is 0, the second value is the offset of the second clause, and the third value is the length of the string.

The typing information a null-terminated character string representing the characters entered at the keyboard.

The cursor position is a value indicating the position of the cursor relative to the characters in the composition string. The value is the offset, in bytes, from the beginning of the string. If this value is 0, the cursor is immediately before the first character in the string. If the value is equal to the length of the string, the cursor is immediately after the last character. If -1, the cursor is not present.

You can set the composition string or elements of the composition status by using the ImmSetCompositionString function. To ensure that the composition window updates it appearance based on these changes, the function allows for generating a notification message to be sent to the window. Applications that set a combination of composition status elements typically set the fNotify parameter to FALSE for all but the last call to this function so that only one notification message is generated for the composition window.


 Candidate Lists

A candidate list is a CANDIDATELIST structure consisting of an array of strings that specify the characters or character strings that the user may choose from. You can retrieve the candidate lists by using the ImmGetCandidateListCount and ImmGetCandidateList functions.


 Hot Keys

Hot keys give the user a way to quickly change the input mode of the IME or to switch to another IME. Although applications cannot add hot keys to the system, they can initiate the same action as a hot key by using the ImmSimulateHotKey function.


 Using Input Method Editor

•	Processing the WM_IME_COMPOSITION message


 Processing the WM_IME_COMPOSITION Message

Applications that process the WM_IME_COMPOSITION message test the bits in lParam parameter and call the ImmGetCompositionString function to retrieve the indicated string or data. The following example checks for the result string, allocates sufficient memory for the string, and retrieves the result string from the IME:

HIMC hIMC;
HWND hWnd;
DWORD dwSize;
HGLOBAL hstr;
LPSTR lpstr;

case WM_IME_COMPOSITION:
    if (lParam & GCS_RESULTSTR) {
        hIMC = ImmGetContext(hWnd);

        If (!hIMC)
            MyError(ERROR_NULLCONTEXT);

        // Get the size of the result string.
        dwSize = ImmGetCompositionString(hIMC, GCS_RESULTSTR, NULL, 0);

        // increase buffer size for NULL terminator,
        //   maybe it is in UNICODE
        dwSize += sizeof(WCHAR);

        hstr = GlobalAlloc(GHND,dwSize);
        if (hstr == NULL)
             MyError(ERROR_GLOBALALLOC);

        lpstr = GlobalLock(hstr);
        if (lpstr == NULL)
             MyError(ERROR_GLOBALLOCK);

        // Get the result strings that is generated by IME into lpstr.
        ImmGetCompositionString(hIMC, GCS_RESULTSTR, lpstr, dwSize);
        ImmReleaseContext(hWnd, hIMC);

        // add this string into text buffer of application

        GlobalUnlock(hstr);
        GlobalFree(hstr);
    }


 Input Method EditorReference

This section contains an alphabetical list of the input method editor functions, messages, and structures.


 Input Method Editor Functions

This section describes the input method editor functions.

EnumRegisterWordProc
ImmAssociateContext
ImmConfigureIME
ImmCreateContext
ImmDestroyContext
ImmEnumRegisterWord
ImmEscape
ImmGetCandidateList
ImmGetCandidateListCount
ImmGetCandidateWindow
ImmGetCompositionFont
ImmGetCompositionString
ImmGetCompositionWindow
ImmGetContext
ImmGetConversionList
ImmGetConversionStatus
ImmGetDefaultIMEWnd
ImmGetDescription
ImmGetGuideLine
ImmGetIMEFileName
ImmGetOpenStatus
ImmGetProperty
ImmGetRegisterWordStyle
ImmGetStatusWindowPos
ImmGetVirtualKey
ImmInstallIME
ImmIsIME
ImmIsUIMessage
ImmNotifyIME
ImmRegisterWord
ImmReleaseContext
ImmSetCandidateWindow
ImmSetCompositionFont
ImmSetCompositionString
ImmSetCompositionWindow
ImmSetConversionStatus
ImmSetOpenStatus
ImmSetStatusWindowPos
ImmSimulateHotKey
ImmUnregisterWord


 Input Method Editor Messages

This section describes the input method editor messages.

IMC_GETCANDIDATEPOS
IMC_GETCOMPOSITIONFONT
IMC_GETCOMPOSITIONWINDOW
IMC_GETCONVERSIONMODE
IMC_GETOPENSTATUS
IMC_GETSENTENCEMODE
IMC_GETSTATUSWINDOWPOS
IMC_SETCANDIDATEPOS
IMC_SETCOMPOSITIONFONT
IMC_SETCOMPOSITIONWINDOW
IMC_SETCONVERSIONMODE
IMC_SETOPENSTATUS
IMC_SETSENTENCEMODE
IMC_SETSTATUSWINDOWPOS
IMN_CHANGECANDIDATE
IMN_CLOSECANDIDATE
IMN_CLOSESTATUSWINDOW
IMN_GUIDELINE
IMN_OPENCANDIDATE
IMN_OPENSTATUSWINDOW
IMN_SETCANDIDATEPOS
IMN_SETCOMPOSITIONFONT
IMN_SETCOMPOSITIONWINDOW
IMN_SETCONVERSIONMODE
IMN_SETOPENSTATUS
IMN_SETSENTENCEMODE
IMN_SETSTATUSWINDOWPOS
WM_IME_CHAR
WM_IME_COMPOSITION
WM_IME_COMPOSITIONFULL
WM_IME_CONTROL
WM_IME_ENDCOMPOSITION
WM_IME_NOTIFY
WM_IME_SELECT
WM_IME_SETCONTEXT
WM_IME_STARTCOMPOSITION


 Input Method Editor Structures

This section describes the structures used with input method editor functions and messages.

CANDIDATEFORM
CANDIDATELIST
COMPOSITIONFORM
STYLEBUF


 Input Method Editor Constants

This section describes the constants used by the input method editor functions and messages.


 IME Conversion Mode Values

Bit	Meaning
IME_CMODE_CHARCODE	Set to 1 if character code input mode; 0 if not.
IME_CMODE_EUDC	Set to 1 if EUDC conversion mode; 0 if not.
IME_CMODE_FULLSHAPE	Set to 1 if full shape mode; 0 if half shape mode.
IME_CMODE_HANJACONVERT	Set to 1 if HANJA convert mode; 0 if not.
IME_CMODE_KATAKANA	Set to 1 if KATAKANA mode; 0 if HIRAGANA mode.
IME_CMODE_NATIVE	Set to 1 if NATIVE mode; 0 if ALPHANUMERIC mode.
IME_CMODE_NOCONVERSION	Set to 1 to prevent processing of conversions by IME; 0 if not.
IME_CMODE_ROMAN	Set to 1 if ROMAN input mode; 0 if not.
IME_CMODE_SOFTKBD	Set to 1 if Soft Keyboard mode; 0 if not.
All other bits are reserved.


 IME Composition String Values

Value	Description
GCR_ERRORSTR	Retrieves or updates the error string.
GCR_INFORMATIONSTR	Retrieves or updates the information string.
GCS_COMPATTR	Retrieves or updates the attribute of the composition string.
GCS_COMPCLAUSE	Retrieves or updates clause information of the composition string.
GCS_COMPREADATTR	Retrieves or updates the attributes of the reading string of the current composition.
GCS_COMPREADCLAUSE	Retrieves or updates the clause information of the reading string of the composition string.
GCS_COMPREADSTR	Retrieves or updates the reading string of the current composition.
GCS_COMPSTR	Retrieves or updates the current composition string.
GCS_CURSORPOS	Retrieves or updates the cursor position in composition string.
GCS_DELTASTART	Retrieves or updates the starting position of any changes in composition string.
GCS_RESULTCLAUSE	Retrieves or updates clause information of the result string.
GCS_RESULTREADCLAUSE	Retrieves or updates clause information of the reading string.
GCS_RESULTREADSTR	Retrieves or updates the reading string.
GCS_RESULTSTR	Retrieves or updates the string of the composition result.
GCS_TYPINGINFO	Retrieves or updates the typing information of reading string. In contrast to reading information, this shows raw key strokes that the end user types.


 IME Hot Key Identifiers

IME_CHOTKEY_IME_NONIME_TOGGLE	(Simplified Chinese) Toggles between IME and non-IME operation.
IME_CHOTKEY_SHAPE_TOGGLE	(Simplified Chinese) Toggles the shape conversion mode of IME.
IME_CHOTKEY_SYMBOL_TOGGLE	(Simplified Chinese) Toggles the symbol conversion mode of IME. Symbol mode indicates that the user can input Chinese punctuation and symbols by mapping to the punctuation and symbols on the keyboard.
IME_JHOTKEY_CLOSE_OPEN	(Japanese) Alternately opens and closes the IME.
IME_KHOTKEY_ENGLISH	(Korean) Switches to English.
IME_KHOTKEY_SHAPE_TOGGLE	(Korean) Toggles the shape conversion mode of IME.
IME_KHOTKEY_HANJACONVERT	(Korean) Switches to Hanja converision.
IME_THOTKEY_IME_NONIME_TOGGLE	(Traditional Chinese) Toggles between IME and non-IME operation.
IME_THOTKEY_SHAPE_TOGGLE	(Traditional Chinese) Toggles the shape conversion mode of IME.
IME_THOTKEY_SYMBOL_TOGGLE	(Traditional Chinese) Toggles the symbol conversion mode of IME.


 IME Sentence Mode Values

Constant	Definition
IME_SMODE_AUTOMATIC	The IME carries out conversion processing in automatic mode.
IME_SMODE_NONE	No information for sentence.
IME_SMODE_PHRASEPREDICT	The IME uses phrase information to predict the next character.
IME_SMODE_PLURALCLAUSE	The IME uses plural clause information to carry out conversion processing.
IME_SMODE_SINGLECONVERT	The IME carries out conversion processing in single character mode.
Bits 16 through 31 are reserved for IME use.


 IME Escapes

Escape	Description
IME_ESC_GET_EUDC_DICTIONARY	Retrieves the path of the EUDC dictionary file. On input, the lpData parameter must be the pointer to the buffer to receive the path. This buffer must be no less than 80 characters in length. On return, the buffer contains the null-terminated string specifying the full path. For use by the Chinese EUDC editor; do not use in other applications.
IME_ESC_HANJA_MODE	Converts from Hangeul to Hanja. On input, lpData must be the pointer to the buffer that contains the Hangeul character to convert; on output, it receives the converted Hanja as a null-terminated string. For use by the Korean editor; do not use in other applications.
IME_ESC_IME_NAME	Retrieves the name of the IME. On input, the lpData parameter must be the pointer to the buffer to receive the name. This buffer must be no less than 64 characters in length. On return, the buffer contains the null-terminated string specifying the IME name. For use by the Chinese EUDC editor; do not use in other applications.
IME_ESC_MAX_KEY	Returns the maximum number of key stokes for an EUDC character. For use by the Chinese EUDC editor; do not use in other applications.
IME_ESC_QUERY_SUPPORT	Checks for implementation. Returns zero if the escape is not implemented.
IME_ESC_SEQUENCE_TO_INTERNAL	Returns the character code that matches the given sequence code. On input, the lpData parameter is the pointer to a 32-bit variable that contains the sequence code. For use by the Chinese EUDC editor; do not use in other applications. Normally, the Chinese IME will encode its reading character codes into sequence 1 to n.
IME_ESC_SET_EUDC_DICTIONARY	Sets the EUDC dictionary file. On input, the lpData parameter is the pointer to a null-terminated string specifying the full path. For use by the Chinese EUDC editor; do not use in other applications.
The system reserves the escapes in the range IME_ESC_RESERVED_FIRST to IME_ESC_RESERVED_LAST for its own use.

The system reserves the escapes in the range IME_ESC_PRIVATE_FIRST to IME_ESC_PRIVATE_LAST for private use by IMEs.


 National Language Support

National language support functions help applications developed for the Win32 application programming interface (API) adapt to the differing language- and location-specific needs of users around the world.

This overview describes the national language support functions and explains how to use them in your Win32-based applications.


 About National Language Support

The national language support functions let applications set the locale for the user, identifying the language in which the user carries out work, and retrieve strings, representing times, dates and other information, that are correctly formatted for the given language and location of the world.

National language support also includes support for keyboard layouts and language-specific fonts. For more information about these topics, see Keyboard Input and Fonts and Text.


 Locales

A locale is a collection of language-related, user preference information represented as a list of values. Each system has at least one installed locale and usually has many locales from which the user may choose. Each locale has a unique locale identifier (LCID), a 32-bit value that consists in part of a language identifier. The language identifier is a standard international numeric abbreviation for a country or geographical region.

The system assigns a locale to each thread. Initially, the system assigns the system default locale to the thread. This default locale is set by the user when the system is installed or through the International applet of the Control Panel. If a thread is run in a process belonging to a user, the system assigns the user default locale to the thread. An application can override either default by using the the SetThreadLocale function to explicitly set the locale for a thread.

There are two predefined locale identifiers: LOCALE_SYSTEM_DEFAULT, which identifies the system default locale, and LOCALE_USER_DEFAULT, which identifies the locale of the current user. An application can retrieve the current locale identifiers by using the GetSystemDefaultLCID and GetUserDefaultLCID functions. Similarly, an application can retrieve the current language identifiers by using the GetSystemDefaultLangID and GetUserDefaultLangID functions.

An application can retrieve specific information about any available language or locale. This can be important for handling language- and locale-specific strings. An application can retrieve information about a locale by using the GetLocaleInfo function. Each element of locale information has a unique LCTYPE value that identifies a specific information type. Applications use these values to retrieve the information they need.

All LCTYPE values are mutually-exclusive, so only one type of information can be retrieved at a time. An exception is the LOCALE_NOUSEROVERRIDE which can be used to bypasses user overrides and retrieve the system default values for the requested locale.

Locale information is always stored and manipulated as a null-terminated string. No binary data is allowed; any numeric values must be specified as text. Each type of information has a particular format. Also, several of types are linked together, such that changing one changes the value of the other as well.

Although a given locale identifier may be supported, it is not available for use by an application unless it is also installed.


 Time and Date

You can retrieve strings for any given time or date in a format that is appropriate for the current locale by using the GetTimeFormat and GetDateFormat functions.

For GetTimeFormat, the time values in the SYSTEMTIME structure pointed to by lpTime must be valid. The function checks each of the time values to determine that it is within the appropriate range of values. If any of the time values are outside the correct range, the function fails, and sets the last-error to ERROR_INVALID_PARAMETER.

The function ignores the date portions of the SYSTEMTIME structure pointed to by lpTime: wYear, wMonth, wDayOfWeek, and wDay.

If a time marker exists and the TIME_NOTIMEMARKER flag is not set, the function localizes the time marker based on the specified locale identifier. Examples of time markers are "AM" and "PM" for US English, "de." and "du." for Mexican Spanish.

If TIME_NOMINUTESORSECONDS or TIME_NOSECONDS is specified, the function removes the separator(s) preceding the minutes and/or seconds element(s).

If TIME_NOTIMEMARKER is specified, the function removes the separator(s) preceding and following the time marker.

If TIME_FORCE24HOURFORMAT is specified, the function displays any existing time marker, unless the TIME_NOTIMEMARKER flag is also set.

The function does not include milliseconds as part of the formatted time string.

To use the LOCALE_NOUSEROVERRIDE flag, lpFormat must be NULL.

No errors are returned for a bad format string. The function simply forms the best time string that it can. If more than two hour, minute, second, or time marker format pictures are passed in, then the function defaults to two. For example, the only time marker pictures that are valid are L"t" and L"tt" (the 'L' indicates a Unicode (16-bit characters) string). If L"ttt" is passed in, the function assumes L"tt".

For GetDateFormat, the date values in the SYSTEMTIME structure pointed to by lpDate must be valid. The function checks each of the date values: year, month, day, and day of week. If the day of the week is incorrect, the function uses the correct value, and returns no error. If any of the other date values are outside the correct range, the function fails, and sets the last-error to ERROR_INVALID_PARAMETER.

The day name, abbreviated day name, month name, and abbreviated month name are all localized based on the given locale identifier. The function ignores the time portions of the SYSTEMTIME structure pointed to by lpDate: wHour, wMinute, wSecond, and wMilliseconds.

The flag DATE_USE_ALT_CALENDAR will always use the format defined as the default format for that alternate calendar, rather than using any user overrides.  The user overrides will only be used in the event that there is no default format for the alternate calendar specified.

The DATE_SHORTDATE and DATE_LONGDATE flag options are mutually exclusive. If neither one is specified and lpFormat is NULL, then DATE_SHORTDATE is the default.

If the lpFormat parameter is not NULL, the dwFlags parameter must be zero. None of the flags make sense when the format string is specified.

No errors are returned for a bad format string. The function simply forms the best date string that it can. For example, the only year pictures that are valid are L"yyyy" and L"yy" (the 'L' indicates a Unicode (16-bit characters) string). If L"y" is passed in, the function  assumes L"yy". If L"yyy" is passed in, the function assumes L"yyyy". If more than 4 date (L"dddd") or 4 month (L"MMMM") pictures are passed in, then the function defaults to L"dddd" or L"MMMM".

Any text that should remain in its exact form in the date string should be enclosed within single quotes in the date format picture. The single quote may also be used as an escape character to allow the single quote itself to be displayed in the date string. However, the escape sequence must be enclosed within two single quotes.  For example, to display the date as "May '93", the format string would be:  L"MMMM ''''yy " The first and last single quotes are the enclosing quotes.  The second and third single quotes are the escape sequence to allow the single quote to be displayed before the century.


 Date and Calendar

Most locales use the standard Gregorian calendar and a set number of date formats. These "default choices" for date formats are available for display by using the EnumDateFormats function. There are other locales which require special considerations when creating a complete list of format choices. Some of these require text strings to be inserted within the date format string, others require a completely different method of computation of the values. These special requirements are addressed by the addition of new LCTYPE and CALTYPE values.

Each locale identifier has a default calendar type associated with it. A locale identifier can also have an alternate calendar type, which can be set using the LOCALE_IOPTIONALCALENDAR type for this locale.


 Localization and the Shell Font

Windows NT is available in localized editions of many different languages, but the U.S. English edition can also be used to run applications written in other languages. This is true even when the base character sets are different, such as when applications are written in the Central and Eastern European languages, or in Greek. These applications require a user interface (UI) with dialog boxes, icons, and applets that provide information in the application's language, which may be different than the language being used in the current Windows NT UI.

To enable the U.S. English Windows NT user interface, as well as characters outside the Windows character set for the US and Western Europe (code page 1252), to display correctly within applications and in system edit controls, Windows NT uses intelligent font switching based on the currently selected locale. This allows currently shipping localized applications to run on the U.S. English version of Windows NT without modifying the application in any way.

An example of the problem being addressed here is that the U.S. English Windows NT shell font is MS Sans Serif but the shell font for Greek Windows 3.1 is MS Sans Serif Greek. These character sets cannot be directly mapped to each other so simply replacing the MS Sans Serif font with the MS Sans Serif Greek font when the locale is set to Greek does not allow existing applications with this kind of difference to run adequately or to display Greek characters in system menus, dialogs and edit controls. To resolve this problem at run time, Microsoft has defined a new font face name, MS Shell Dlg. It is mapped by an entry in the registry to the appropriate shell font for the currently active locale.


 MS Shell Dlg

MS Shell Dlg is a mapping mechanism that enables U.S. English Windows NT to support non-code page 1252 locales. It is not a font but only a face name for a nonexistent font. It can be specified in either the Windows NT Setup file during the installation process or when customizing a local system by double-clicking on the Control Panel's International icon. When you double-click on the icon, select the appropriate Country and Language in the International dialog box, and then reboot the system, the appropriate change occurs in the Registry under the following key:

HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\Current Version\FontSubstitutes

An added benefit of this new means of font mapping in the registry is that you can change the font for the entire shell by simply changing one .inf file entry. For example, Far East localization is much easier because you can change the .inf file entry, instead of changing every instance of MS Sans Serif in every .rc and .dlg file, and the change is complete without rebuilding any binaries.

Windows NT applications can also take advantage of this feature. It is very helpful when your application contains multiple language resources that cross character-set boundaries. It is also useful when you have an English application in which supporting multiple languages and character sets is important.


 Windows 95 and MS Shell Dlg

Windows 95 does not support the concept of switching Windows character sets so the role of MS Shell Dlg is more limited. It does, however, facilitate localization in that Windows 95 is equipped with a static entry to replace the standard system font. For example, the system font, MS San Serif, is easily replaced with MS San Serif Greek or another language. This also ensures compatibility with the applets provided with Windows NT.


 When MS Shell Dlg Should Not Be Used

At this time, MS Shell Dlg is not intended for use when you are working with a static, non-English UI application that you want to run when the user has chosen a locale with a different Windows base character set. This is because the application's UI language may not be supported with the font that is substituted for MS Shell Dlg. For example, if you are using a German localized version of Windows NT and want to install a non-Unicode, Greek application, you can use the Control Panel's International applet to change the locale to Greek. This will reset MS Shell Dlg to be a Greek font but this font does not contain all of the glyphs necessary to display German. Therefore, any non-ASCII characters in your German UI will not be displayed properly. To support this scenario, you would have to set MS Shell Dlg to a font that contains both the Western European and the Greek glyphs.


 National Language Support Reference

This section provides detailed reference information for the national language support functions, structures, and messages. The information is separated into the following functional groups.


 National Language Support Functions

This section describes the national language support functions. Many national language support functions generate extended error information on errors. Use the GetLastError function to get this information.

SetLocaleInfo


 National Language Support Macros

This section describes the macros used with the national language support functions.

LANGIDFROMLCID
MAKELANGID
MAKELCID


 National Language Support Constants

This section describes the constants used with the national language support functions.


 Locale Information

LOCALE_ILANGUAGE

Language identifier indicating the language. The maximum number of characters allowed for this string is 5.

LOCALE_SLANGUAGE

Full localized name of the language.

LOCALE_SENGLANGUAGE

Full English name of the language from the International Organization for Standardization (ISO) Standard 639. This is always restricted to characters mappable into the ASCII 127-character subset.

LOCALE_SABBREVLANGNAME

Abbreviated name of the language, created by taking the 2-letter language abbreviation from the ISO Standard 639 and adding a third letter, as appropriate, to indicate the sublanguage.

LOCALE_SNATIVELANGNAME

Native name of the language.

LOCALE_ICOUNTRY

Country code, based on international phone codes, also referred to as IBM country codes. The maximum number of characters allowed for this string is 6.

LOCALE_SCOUNTRY

Full localized name of the country.

LOCALE_SENGCOUNTRY

Full English name of the country. This is always restricted to characters mappable into the ASCII 127-character subset.

LOCALE_SABBREVCTRYNAME

Abbreviated name of the country from the ISO Standard 3166.

LOCALE_SNATIVECTRYNAME

Native name of the country.

LOCALE_IDEFAULTLANGUAGE

Language identifier for the principal language spoken in this locale. This is provided so that partially specified locales can be completed with default values. The maximum number of characters allowed for this string is 5.

LOCALE_IDEFAULTCOUNTRY

Country code for the principal country in this locale. This is provided so that partially specified locales can be completed with default values. The maximum number of characters allowed for this string is 6.

LOCALE_IDEFAULTANSICODEPAGE

American National Standards Institute (ANSI) code page associated with this locale. The maximum number of characters allowed for this string is 6.

LOCALE_IDEFAULTOEMCODEPAGE

Original equipment manufacturer (OEM) code page associated with the locale. The maximum number of characters allowed for this string is 6.

LOCALE_IDEFAULTCODEPAGE

Original equipment manufacturer (OEM) code page associated with the country. The maximum number of characters allowed for this string is 6.

LOCALE_SLIST

Character(s) used to separate list items. For example, a comma is used in many locales.

LOCALE_IMEASURE

System of measurement. This value is 0 if the metric system (Systéme International d'Unités, or S.I.) is used and 1 if the U.S. system is used. The maximum number of characters allowed for this string is 2.

LOCALE_SDECIMAL

Character(s) used as the decimal separator.

LOCALE_STHOUSAND

Character(s) used to separate groups of digits to the left of the decimal.

LOCALE_SGROUPING

Sizes for each group of digits to the left of the decimal. An explicit size is needed for each group; sizes are separated by semicolons. If the last value is zero, the preceding value is repeated. To group thousands, specify 3;0, for example.

LOCALE_IDIGITS

Number of fractional digits. The maximum number of characters allowed for this string is 3.

LOCALE_ILZERO

Specifier for leading zeros in decimal fields. The maximum number of characters allowed for this string is 2. The specifier can be one of the following values:

0	No leading zeros
1	Leading zeros
LOCALE_INEGNUMBER

Negative number mode. The mode can be one of these values:

0	(1.1)
1	-1.1
2	- 1.1
3	1.1-
4	1.1 -
LOCALE_SNATIVEDIGITS

Native equivalents to ASCII 0 through 9.

LOCALE_SCURRENCY

String used as the local monetary symbol.

LOCALE_SINTLSYMBOL

Three characters of the international monetary symbol specified in ISO 4217, "Codes for the Representation of Currencies and Funds," followed by the character separating this string from the amount.

LOCALE_SMONDECIMALSEP

Character(s) used as the monetary decimal separator.

LOCALE_SMONTHOUSANDSEP

Character(s) used as the monetary separator between groups of digits to the left of the decimal.

LOCALE_SMONGROUPING

Sizes for each group of monetary digits to the left of the decimal. An explicit size is needed for each group; sizes are separated by semicolons. If the last value is zero, the preceding value is repeated. To group thousands, specify 3;0, for example.

LOCALE_ICURRDIGITS

Number of fractional digits for the local monetary format. The maximum number of characters allowed for this string is 3.

LOCALE_IINTLCURRDIGITS

Number of fractional digits for the international monetary format. The maximum number of characters allowed for this string is 3.

LOCALE_ICURRENCY

Positive currency mode. The maximum number of characters allowed for this string is 2. The mode can be one of the following values:

0	Prefix, no separation
1	Suffix, no separation
2	Prefix, 1-char. separation
3	Suffix, 1-char. separation
LOCALE_INEGCURR

Negative currency mode. The maximum number of characters allowed for this string is 3. The mode can be one of the following values:

0	($1.1)
1	−$1.1
2	$−1.1
3	$1.1−
4	(1.1$)
5	−1.1$
6	1.1−$
7	1.1$−
8	−1.1 $ (space before $)
9	−$ 1.1 (space after $)
10	1.1 $− (space before $)
11	$ 1.1− (space after $)
12	$ −1.1 (space after $)
13	1.1− $ (space before $)
14	($ 1.1) (space after $)
15	(1.1 $) (space before $)
LOCALE_SDATE

Character(s) for the date separator.

LOCALE_STIME

Character(s) for the time separator.

LOCALE_STIMEFORMAT

Time formatting strings for this locale. The string can consist of a combination of the hour, minute, and second format pictures defined in in the Hour, Minute, and Second Format Pictures table in National Language Support Constants.

LOCALE_SSHORTDATE

Short date formatting string for this locale. The string can consist of a combination of day, month, and year format pictures defined in in Day, Month, Year, and Era Format Pictures table in National Language Support Constants.

LOCALE_SLONGDATE

Long date formatting string for this locale. The string can consist of a combination of day, month, and year format pictures defined in in the Day, Month, Year, and Era Format Pictures table in National Language Support Constantsand any string of characters enclosed in single quotes. Characters in single quotes remain as given.

LOCALE_IDATE

Short date format-ordering specifier. The maximum number of characters allowed for this string is 2. The specifier can be one of the following values:

0	Month-Day-Year
1	Day-Month-Year
2	Year-Month-Day
LOCALE_ILDATE

Long date format-ordering specifier. The maximum number of characters allowed for this string is 2. The specifier can be one of the following values:

0	Month-Day-Year
1	Day-Month-Year
2	Year-Month-Day
LOCALE_ITIME

Time format specifier. The maximum number of characters allowed for this string is 2. The specifier can be one of the following values:

0	AM / PM 12-hour format
1	24-hour format
LOCALE_ICENTURY

Specifier for full 4-digit century. The maximum number of characters allowed for this string is 2. The specifier can be one of the following values:

0	Abbreviated 2-digit century
1	Full 4-digit century
LOCALE_ITLZERO

Specifier for leading zeros in time fields. The maximum number of characters allowed for this string is 2. The specifier can be one of the following values:

0	No leading zeros for hours
1	Leading zeros for hours
LOCALE_IDAYLZERO

Specifier for leading zeros in day fields. The maximum number of characters allowed for this string is 2. The specifier can be one of the following values:

0	No leading zeros for days
1	Leading zeros for days
LOCALE_IMONLZERO

Specifier for leading zeros in month fields. The maximum number of characters allowed for this string is 2. The specifier can be one of the following values:

0	No leading zeros for months
1	Leading zeros for months
LOCALE_S1159

String for the AM designator.

LOCALE_S2359

String for the PM designator.

LOCALE_ICALENDARTYPE

Current calendar type. This type can be one of these values:

1	Gregorian (as in United States)
2	Gregorian (English strings always)
3	Era: Year of the Emperor (Japan)
4	Era: Year of the Republic of China
5	Tangun Era (Korea)
LOCALE_IOPTIONALCALENDAR

Additional calendar types. This can be a zero-separated list of one or more of these calendars type values:

0	No additional types valid
1	Gregorian (as in United States)
2	Gregorian (English strings always)
3	Era: Year of the Emperor (Japan)
4	Era: Year of the Republic of China
5	Tangun Era (Korea)
LOCALE_IFIRSTDAYOFWEEK

Specifier for the first day in a week. The specifier can be one of these values:

0	LOCALE_SDAYNAME1
1	LOCALE_SDAYNAME2
2	LOCALE_SDAYNAME3
3	LOCALE_SDAYNAME4
4	LOCALE_SDAYNAME5
5	LOCALE_SDAYNAME6
6	LOCALE_SDAYNAME7
LOCALE_IFIRSTWEEKOFYEAR

Specifier for the first week of the year. The specifier can be one of these values:

0	Week containing 1/1 is the first week of that year.
1	First full week following 1/1 is the first week of that year.
2	First week containing at least 4 days is the first week of that year.
LOCALE_SDAYNAME1

Native long name for Monday.

LOCALE_SDAYNAME2

Native long name for Tuesday.

LOCALE_SDAYNAME3

Native long name for Wednesday.

LOCALE_SDAYNAME4

Native long name for Thursday.

LOCALE_SDAYNAME5

Native long name for Friday.

LOCALE_SDAYNAME6

Native long name for Saturday.

LOCALE_SDAYNAME7

Native long name for Sunday.

LOCALE_SABBREVDAYNAME1

Native abbreviated name for Monday.

LOCALE_SABBREVDAYNAME2

Native abbreviated name for Tuesday.

LOCALE_SABBREVDAYNAME3

Native abbreviated name for Wednesday.

LOCALE_SABBREVDAYNAME4

Native abbreviated name for Thursday.

LOCALE_SABBREVDAYNAME5

Native abbreviated name for Friday.

LOCALE_SABBREVDAYNAME6

Native abbreviated name for Saturday.

LOCALE_SABBREVDAYNAME7

Native abbreviated name for Sunday.

LOCALE_SMONTHNAME1

Native long name for January.

LOCALE_SMONTHNAME2

Native long name for February.

LOCALE_SMONTHNAME3

Native long name for March.

LOCALE_SMONTHNAME4

Native long name for April.

LOCALE_SMONTHNAME5

Native long name for May.

LOCALE_SMONTHNAME6

Native long name for June.

LOCALE_SMONTHNAME7

Native long name for July.

LOCALE_SMONTHNAME8

Native long name for August.

LOCALE_SMONTHNAME9

Native long name for September.

LOCALE_SMONTHNAME10

Native long name for October.

LOCALE_SMONTHNAME11

Native long name for November.

LOCALE_SMONTHNAME12

Native long name for December.

LOCALE_SMONTHNAME13

Native name for 13th month, if exists.

LOCALE_SABBREVMONTHNAME1

Native abbreviated name for January.

LOCALE_SABBREVMONTHNAME2

Native abbreviated name for February.

LOCALE_SABBREVMONTHNAME3

Native abbreviated name for March.

LOCALE_SABBREVMONTHNAME4

Native abbreviated name for April.

LOCALE_SABBREVMONTHNAME5

Native abbreviated name for May.

LOCALE_SABBREVMONTHNAME6

Native abbreviated name for June.

LOCALE_SABBREVMONTHNAME7

Native abbreviated name for July.

LOCALE_SABBREVMONTHNAME8

Native abbreviated name for August.

LOCALE_SABBREVMONTHNAME9

Native abbreviated name for September.

LOCALE_SABBREVMONTHNAME10

Native abbreviated name for October.

LOCALE_SABBREVMONTHNAME11

Native abbreviated name for November.

LOCALE_SABBREVMONTHNAME12

Native abbreviated name for December.

LOCALE_SABBREVMONTHNAME13

Native abbreviated name for 13th month, if exists.

LOCALE_SPOSITIVESIGN

String value for the positive sign.

LOCALE_SNEGATIVESIGN

String value for the negative sign.

LOCALE_IPOSSIGNPOSN

Formatting index for positive values. The maximum number of characters allowed for this string is 2. The index can be one of the following values:

0	Parentheses surround the amount and the monetary symbol.
1	The sign string precedes the amount and the monetary symbol.
2	The sign string succeeds the amount and the monetary symbol.
3	The sign string immediately precedes the monetary symbol.
4	The sign string immediately succeeds the monetary symbol.
LOCALE_INEGSIGNPOSN

Formatting index for negative values. This index uses the same values as LOCALE_IPOSSIGNPOSN. The maximum number of characters allowed for this string is 2.

LOCALE_IPOSSYMPRECEDES

Position of monetary symbol in a positive monetary value. This value is 1 if the monetary symbol precedes the positive amount, 0 if it follows it. The maximum number of characters allowed for this string is 2.

LOCALE_IPOSSEPBYSPACE

Separation of monetary symbol in a positive monetary value. This value is 1 if the monetary symbol is separated by a space from a positive amount, 0 if it is not. The maximum number of characters allowed for this string is 2.

LOCALE_INEGSYMPRECEDES

Position of monetary symbol in a negative monetary value. This value is 1 if the monetary symbol precedes the negative amount, 0 if it follows it. The maximum number of characters allowed for this string is 2.

LOCALE_INEGSEPBYSPACE

Separation of monetary symbol in a negative monetary value. This value is 1 if the monetary symbol is separated by a space from the negative amount, 0 if it is not. The maximum number of characters allowed for this string is 2.

LOCALE_NOUSEROVERRIDE

Can be combined with other LOCALE values to bypass any user override and return the system default value for the given locale information.

Many of the locale types listed above are closely related, such that changing one affects the value of others. The following shows the relationships between these types.

LOCALE_ICURRENCY

LOCALE_IPOSSEPBYSPACE, LOCALE_IPOSSYMPRECEDES

LOCALE_INEGCURR

LOCALE_INEGSEPBYSPACE, LOCALE_INEGSYMPRECEDES, LOCALE_INEGSIGNPOSN, LOCALE_IPOSSIGNPOSN

LOCALE_SSHORTDATE

LOCALE_SDATE, LOCALE_IDATE

LOCALE_SLONGDATE

LOCALE_ILDATE

LOCALE_STIMEFORMAT

LOCALE_STIME, LOCALE_ITIME, LOCALE_ITLZERO


 Day, Month, Year, and Era Format Pictures

The format picture for a date string consists of a combination of null-terminated strings.

Day
d	Day of the month as digits without leading zeros for single digit days.
dd	Day of the month as digits with leading zeros for single digit days
ddd	Day of the week as a 3-letter abbreviation as given by a LOCALE_SABBREVDAYNAME value.
dddd	Day of the week as given by a LOCALE_SDAYNAME value.
Month
M	Month as digits without leading zeros for single digit months.
MM	Month as digits with leading zeros for single digit months
MMM	Month as a three letter abbreviation as given by a LOCALE_SABBREVMONTHNAME value.
MMMM	Month as given by a LOCALE_SMONTHNAME value.
Year
y	Year represented only be the last digit.
yy	Year represented only be the last two digits.
yyyy	Year represented by the full 4 digits.
Period/Era
gg	Period/era string as given by the CAL_SERASTRING value.
The "gg" format picture in a date string is ignored if there is no associated era string.


 Hour, Minute, and Second Format Pictures

The format picture for a time string consists of a combination of one string from each of these format types:

Hours
h	Hours without leading zeros for single digit hours (12 hour clock)
hh	Hours with leading zeros for single digit hours (12 hour clock)
H	Hours without leading zeros for single digit hours (24 hour clock)
HH	Hours with leading zeros for single digit hours (24 hour clock)
Minutes
m	Minutes without leading zeros for single digit minutes
mm	Minutes with leading zeros for single digit minutes
Seconds
s	Seconds without leading zeros for single digit seconds
ss	Seconds with leading zeros for single digit seconds
Time Marker
t	One character time marker string
tt	Multi-character time marker string


 Primary Language Identifiers

0x00	Neutral
0x36	Afrikaans
0x1c	Albanian
0x01	Arabic
0x2d	Basque
0x02	Bulgarian
0x23	Byelorussian
0x03	Catalan
0x04	Chinese
0x05	Czech
0x06	Danish
0x13	Dutch
0x09	English
0x25	Estonian
0x29	Farsi
0x0b	Finnish
0x0c	French
0x07	German
0x08	Greek
0x0d	Hebrew
0x0e	Hungarian
0x0f	Icelandic
0x21	Indonesian
0x10	Italian
0x11	Japanese
0x2c	Kampuchean
0x12	Korean
0x2b	Laotian
0x26	Latvian
0x27	Lithuanian
0x2f	Macedonian
0x28	Maori
0x14	Norwegian
0x15	Polish
0x16	Portuguese
0x17	Rhaeto Roman
0x18	Romanian
0x19	Russian
0x1a	Serbo Croatian
0x1b	Slovak
0x24	Slovenian
0x2e	Sorbian
0x0a	Spanish
0x30	Sutu
0x1d	Swedish
0x1e	Thai
0x31	Tsonga
0x32	Tswana
0x1f	Turkish
0x22	Ukrainian
0x20	Urdu
0x33	Venda
0x2a	Vietnamese
0x34	Xhosa
0x35	Zulu


 Secondary Language Identifiers

0x00	Neutral
0x01	Default
0x02	System Default
0x01	Arabic (Saudi Arabia)
0x02	Arabic (Iraq)
0x03	Arabic (Egypt)
0x04	Arabic (Libya)
0x05	Arabic (Algeria)
0x06	Arabic (Morocco)
0x07	Arabic (Tunisia)
0x08	Arabic (Oman)
0x09	Arabic (Yemen)
0x10	Arabic (Syria)
0x11	Arabic (Jordan)
0x12	Arabic (Lebanon)
0x13	Arabic (Kuwait)
0x14	Arabic (U.A.E.)
0x15	Arabic (Bahrain)
0x16	Arabic (Qatar)
0x01	Chinese (Taiwan)
0x02	Chinese (PRC)
0x03	Chinese (Hong Kong)
0x04	Chinese (Singapore)
0x01	Dutch
0x02	Dutch (Belgian)
0x01	English (US)
0x02	English (UK)
0x03	English (Australian)
0x04	English (Canadian)
0x05	English (New Zealand)
0x06	English (Ireland)
0x01	French
0x02	French (Belgian)
0x03	French (Canadian)
0x04	French (Swiss)
0x05	French (Luxembourg)
0x01	German
0x02	German (Swiss)
0x03	German (Austrian)
0x04	German (Luxembourg)
0x05	German (Liechtenstein)
0x04	Hebrew (Israel)
0x01	Italian
0x02	Italian (Swiss)
0x01	Norwegian (Bokmal)
0x02	Norwegian (Nynorsk)
0x01	Portuguese (Brazilian)
0x02	Portuguese
0x01	Serbo Croatian (Latin)
0x02	Serbo Croatian (Cyrillic)
0x01	Spanish (Traditional Sort)
0x02	Spanish (Mexican)
0x03	Spanish (Modern Sort)


 Language Identifiers

Identifier	Locale
0x0436	Afrikaans
0x041C	Albania
0x1401	Algeria
0x0409	American
0x0C09	Australian
0x0C07	Austrian
0x3C01	Bahrain
0x042D	Basque
0x080C	Belgian
0x0813	Belgian (Flemish)
0x0809	British
0x0402	Bulgaria
0x0423	Byelorussia
0x1009	Canadian
0x0403	Catalan
0x041A	Croatian
0x0405	Czech
0x0406	Danish
0x0413	Dutch (Standard)
0x0C01	Egypt
0x0425	Estonia
0x0429	Farsi
0x040B	Finnish
0x040C	French (Standard)
0x0C0C	French Canadian
0x0407	German (Standard)
0x042E	Germany
0x0408	Greek
0x0C04	Hong Kong
0x040E	Hungarian
0x040F	Icelandic
0x0421	Indonesia
0x0801	Iraq
0x1809	Ireland
0x040D	Israel
0x0410	Italian (Standard)
0x0411	Japan
0x2C01	Jordan
0x0412	Korea
0x3401	Kuwait
0x0426	Latvia
0x3001	Lebanon
0x1001	Libya
0x1407	Liechtenstein
0x0427	Lithuania
0x140C	Luxembourg (French)
0x1007	Luxembourg (German)
0x042f	Macedonia
0x080A	Mexican
0x0818	Moldavia
0x0819	Moldavia
0x1801	Morocco
0x1409	New Zealand
0x0414	Norwegian (Bokmal)
0x0814	Norwegian (Nynorsk)
0x2001	Oman
0x0415	Polish
0x0416	Portuguese (Brazilian)
0x0816	Portuguese (Standard)
0x0804	PRC
0x4001	Qatar
0x0417	Rhaeto-Romanic
0x0418	Romania
0x0419	Russian
0x0401	Saudi Arabia
0x081A	Serbian
0x1004	Singapore
0x041B	Slovak
0x0424	Slovenia
0x0C0A	Spanish (Modern Sort)
0x040A	Spanish (Traditional Sort)
0x0430	Sutu
0x041D	Swedish
0x100C	Swiss (French)
0x0807	Swiss (German)
0x0810	Swiss (Italian)
0x2801	Syria
0x0404	Taiwan
0x041E	Thailand
0x0431	Tsonga
0x0432	Tswana
0x1C01	Tunisia
0x041f	Turkish
0x3801	U.A.E.
0x0422	Ukraine
0x0420	Urdu
0x0433	Venda
0x0435	Xhosa
0x2401	Yemen
0x0436	Zulu


 Calendar Type Information

CAL_ICALINTVALUE

An integer value indicating the calendar type of the alternate calendar.

CAL_IYEAROFFSETRANGE

One or more null-terminated strings that specify the year offsets for each of the era ranges. The last string has an extra terminating null character.

CAL_SABBREVDAYNAME1

Abbreviated native name of the first day of the week.

CAL_SABBREVDAYNAME2

Abbreviated native name of the second day of the week.

CAL_SABBREVDAYNAME3

Abbreviated native name of the third day of the week.

CAL_SABBREVDAYNAME4

Abbreviated native name of the fourth day of the week.

CAL_SABBREVDAYNAME5

Abbreviated native name of the fifth day of the week.

CAL_SABBREVDAYNAME6

Abbreviated native name of the sixth day of the week.

CAL_SABBREVDAYNAME7

Abbreviated native name of the seventh day of the week.

CAL_SABBREVMONTHNAME1

Abbreviated native name of the first month of the year.

CAL_SABBREVMONTHNAME2

Abbreviated native name of the second month of the year.

CAL_SABBREVMONTHNAME3

Abbreviated native name of the third month of the year.

CAL_SABBREVMONTHNAME4

Abbreviated native name of the fourth month of the year.

CAL_SABBREVMONTHNAME5

Abbreviated native name of the fifth month of the year.

CAL_SABBREVMONTHNAME6

Abbreviated native name of the sixth month of the year.

CAL_SABBREVMONTHNAME7

Abbreviated native name of the seventh month of the year.

CAL_SABBREVMONTHNAME8

Abbreviated native name of the eighth month of the year.

CAL_SABBREVMONTHNAME9

Abbreviated native name of the ninth month of the year.

CAL_SABBREVMONTHNAME10

Abbreviated native name of the tenth month of the year.

CAL_SABBREVMONTHNAME11

Abbreviated native name of the eleventh month of the year.

CAL_SABBREVMONTHNAME12

Abbreviated native name of the twelfth month of the year.

CAL_SABBREVMONTHNAME13

Abbreviated native name of the thirteenth month of the year, if it exists.

CAL_SCALNAME

The native name of the alternate calendar.

CAL_SDAYNAME1

Native name of the first day of the week.

CAL_SDAYNAME2

Native name of the second day of the week.

CAL_SDAYNAME3

Native name of the third day of the week.

CAL_SDAYNAME4

Native name of the fourth day of the week.

CAL_SDAYNAME5

Native name of the fifth day of the week.

CAL_SDAYNAME6

Native name of the sixth day of the week.

CAL_SDAYNAME7

Native name of the seventh day of the week.

CAL_SERASTRING

One or more null-terminated strings that specify each of the Unicode codepoints specifying the era associated with the given CAL_IYEAROFFSETRANGE. The last string has an extra terminating null character. See example below.

CAL_SLONGDATE

Long date formats for this calendar type.

CAL_SMONTHNAME1

Native name of the first month of the year.

CAL_SMONTHNAME2

Native name of the second month of the year.

CAL_SMONTHNAME3

Native name of the fifth month of the year.

CAL_SMONTHNAME4

Native name of the fourth month of the year.

CAL_SMONTHNAME5

Native name of the fifth month of the year.

CAL_SMONTHNAME6

Native name of the sixth month of the year.

CAL_SMONTHNAME7

Native name of the seventh month of the year.

CAL_SMONTHNAME8

Native name of the eighth month of the year.

CAL_SMONTHNAME9

Native name of the ninth month of the year.

CAL_SMONTHNAME10

Native name of the tenth month of the year.

CAL_SMONTHNAME11

Native name of the eleventh month of the year.

CAL_SMONTHNAME12

Native name of the twelfth month of the year.

CAL_SMONTHNAME13

Native name of the thirteenth month of the year, if it exists.

CAL_SSHORTDATE

Short date formats for this calendar type.

If the native name for the day of the week or for a month is an empty string, that name is identical to the name given in the corresponding locale information and therefore is not duplicated here.

The CAL_IYEAROFFSETRANGE and CAL_SERASTRING values vary in format depending on the type of optional calendar. The following example shows the values for these types (for each supported alternate calendar type) along with the formula for how to use the CAL_IYEAROFFSETRANGE value to compute the correct year given the Gregorian current year value Y:

CAL_ICALINTVALUE = "1"
CAL_IYEAROFFSETRANGE = ""
CAL_SERASTRING = ""

CAL_ICALINTVALUE = "2"
CAL_IYEAROFFSETRANGE = ""
CAL_SERASTRING = ""

CAL_ICALINTVALUE = "3"
CAL_IYEAROFFSETRANGE = "1989\01926\01912\01868\0"
CAL_SERASTRING = "Ux337B\0Ux337C\0Ux337D\0Ux337E\0"
if (Y>=1989) { Y = (Y-1989)+1; }
if (Y>=1926 && Y<1989) { Y = (Y-1926)+1; }
if (Y>=1912 && Y<1926) { Y = (Y-1912)+1; }
if (Y>=1868 && Y<1912) { Y = (Y-1868)+1; }
if (Y<1868) { Y = Y; }

CAL_ICALINTVALUE = "4"
CAL_IYEAROFFSETRANGE = "1912\0"
CAL_SERASTRING = "Ux4E2D\0Ux83EF\0Ux6C11\0Ux570B\0"
if (Y>=1912) { Y = (Y-1912)+1; }
if (Y<1912) { Y = Y; }

CAL_ICALINTVALUE = "5"
CAL_IYEAROFFSETRANGE = "2333\0"
CAL_SERASTRING = ""
Y = Y+2333;


 Language Code and Scripts

Language/Locale	Code	Script
Greek	ELL	Other
Russian	RUS	Cyrillic
Turkish	TRK	Latin 2
Polish	PLK	Latin 2
Czech	CSY	Latin 2
Slovak	SKY	Latin 2
Hungarian	HUN	Latin 2
Danish	DAN	Latin 1
Dutch (Standard)	NLD	Latin 1
Belgian (Flemish)	NLB	Latin 1
English (American)	ENU	Latin 1
English (British)	ENG	Latin 1
English (Australian)	ENA	Latin 1
English (Canadian)	ENC	Latin 1
English (New Zealand)	ENZ	Latin 1
English (Ireland)	ENI	Latin 1
Finnish	FIN	Latin 1
French (Standard)	FRA	Latin 1
French (Belgian)	FRB	Latin 1
French (Canadian)	FRC	Latin 1
French (Swiss)	FRS	Latin 1
German (Standard)	DEU	Latin 1
German (Swiss)	DES	Latin 1
German (Austrian)	DEA	Latin 1
Icelandic	ISL	Latin 1
Italian (Standard)	ITA	Latin 1
Italian (Swiss)	ITS	Latin 1
Norwegian (Bokmal)	NOR	Latin 1
Norwegian (Nynorsk)	NON	Latin 1
Portuguese (Brazilian)	PTB	Latin 1
Portuguese (Standard)	PTG	Latin 1
Swedish	SVE	Latin 1
Spanish (Standard/Traditional)	ESP	Latin 1
Spanish (Mexican)	ESM	Latin 1
Spanish (Modern)	ESN	Latin 1


 Unicode and Character Sets

Unicode and traditional character sets give the Microsoft Windows operating system the means to support the many different written languages of the international marketplace. Unicode is a worldwide character-encoding standard that uses 16-bit character values to represent all the characters used in modern computing, including technical symbols and special characters used in publishing. Traditional character sets are previous character-encoding standards, such as the Windows ANSI character set, that use 8-bit character values or combinations of 8-bit values to represent the characters used in a specific language or geographical region.

This overview describes the character set functions and explains how to use them in your Win32-based applications.


 About Unicode and Character Sets

Because the world's character-based data has been developed using both Unicode and traditional characters sets, the Win32 application programming interface (API) provides character set functions that help Win32-based applications convert the character-based data from its original character set to Unicode or another traditional character set. Because not all operating systems support Unicode, these character set functions also help Win32-based applications create character-based data that may be transferred to and used on any operating system.

For details about Unicode beyond the scope of this overview, see The Unicode™ Standard: Worldwide Character Encoding, Version 1.0, Volumes 1 and 2, Addison-Wesley Publishing Company: 1991, 1992, ISBN 0201567881.


 Unicode and Character Set Reference

This section provides detailed reference information for the character set functions, structures, and messages. The information is separated into the following functional groups.


 Character Sets

A character set is a mapping of characters to their identifying numeric values. Most of the character sets commonly used in computers are single-byte character sets in which each character is identified by a value one byte wide. The large number of characters in Asian languages led to the development of multibyte character sets, in particular the double-byte character set (DBCS). Microsoft® Windows NT™ incorporates a new global standard for character encoding: Unicode.


 Single-byte Character Sets

A single-byte character set is a mapping of 256 individual characters to their identifying numeric values. The character codes 0x20 through 0x7E represent standardized displayable characters, but the characters represented by the remaining codes vary among character sets. The ASCII character set covers the range 0x00 through 0x7F.

In Windows, the ANSI character set is used in window manager and graphics device interface (GDI), but the MS-DOS file allocation table (FAT) file system uses a character set called the original equipment manufacturer (OEM) character set. Variations on the character sets, called code pages, include different special characters, typically customized for a language or group of languages. The OEM code page generally used in the United States is code page 437.

Applications that use the Microsoft® Win32® application programming interface (API) can use Unicode to avoid the inconsistencies of varied code pages and as an aid in developing easily localized applications.

An application can use the GetACP function to retrieve the ANSI code-page identifier for the system or use the GetOEMCP function to retrieve the OEM code-page identifier.

The OemToChar and OemToCharBuff functions allow an application to convert a character or string from the OEM code page to either the ANSI code page or Unicode. To convert in the other direction, you can use either the CharToOem or CharToOemBuff function. In addition, an application can use the MultiByteToWideChar and WideCharToMultiByte functions to map single-byte character set (SBCS) strings to Unicode and Unicode strings to SBCS strings.

The GetCPInfo function fills a CPINFO structure with information that includes the size, in bytes, of the largest character in the code page and the default character used when a character code is entered that has no corresponding entry in the code page.


 Double-byte Character Sets

The double-byte character set (DBCS) is called an expanded 8-bit character set because its smallest unit is a byte. It can be thought of as the ANSI character set for some Asian versions of Windows (particularly the Japanese version). Win32 functions for the Japanese version of Windows accept DBCS strings for the ANSI versions of the functions. However, unlike the handling of Unicode, DBCS character handling requires detailed changes in the character-processing algorithms throughout an application's source code.

An application can use the IsDBCSLeadByte function to determine whether a given character is the first byte in a 2-byte character; this helps identify double-byte character sets. In addition, an application can use the MultiByteToWideChar and WideCharToMultiByte functions to map DBCS strings to Unicode and Unicode strings to DBCS strings.


 Unicode

Unicode is a worldwide character-encoding standard. Windows uses it exclusively at the system level for character and string manipulation. Unicode simplifies localization of software and improves multilingual text processing. By implementing it in an application, a developer can enable the application with universal data exchange capabilities for global marketing, using a single binary file for every possible character code.

Unicode defines semantics for each character, standardizes script behavior, provides a standard algorithm for bidirectional text, and defines cross-mappings to other standards. Among the scripts supported by Unicode are Latin, Greek, Han, Hiragana, and Katakana. Supported languages include, but are not limited to, German, French, English, Greek, Chinese, and Japanese.

Unicode can represent all the world's characters in modern computer use, including technical symbols and special characters used in publishing. Because each Unicode character is 16 bits wide, it is possible to have separate values for up to 65,536 characters. Unicode-enabled functions are often referred to as "wide-character" functions.

Win32 functions support applications that use either Unicode or the regular ANSI character set. Mixed use in the same application is also possible. Adding Unicode support to an application is easy, and a developer can even maintain a single set of sources from which to compile an application that supports either Unicode or the Windows ANSI character set.

Win32 functions support Unicode by assigning its strings a specific data type and providing a separate set of entry points and messages to support this new data type. A series of macros and naming conventions make transparent migration to Unicode, or even compiling both non-Unicode and Unicode versions of an application from the same set of sources, a straightforward matter.

Implementing Unicode as a separate data type also enables the compiler's type checking to ensure that only Unicode parameters are used with functions expecting Unicode strings.


 Unicode in Windows

Win32 API elements that use characters are generally implemented in one of three formats:

•	A generic version that can be compiled for either ANSI or Unicode

•	An ANSI version

•	A Unicode version

This guide dicsusses Unicode data types and how they are used in functions and messages; the use of resources, filenames, and command-line arguments; and methods of translating between different types of strings.


 Data Types

Most string operations for Unicode can be written by using the same logic used for handling the Windows ANSI character set, except that the basic unit of operation is a 16-bit character instead of an 8-bit byte. The header files provide a number of type definitions that make it easy to create sources that can be compiled for Unicode or for the ANSI character set.

The following example shows the method used in the Win32 header files to define three sets of data types: a set of generic type definitions that can compile for either ANSI or Unicode, and two sets of specific type definitions. The first set of specific type definitions is for use with the existing Windows (ANSI) character set, and the other is for use with Unicode (or wide) characters.

/* Generic types */

#ifdef UNICODE

 typedef wchar_t TCHAR;

#else

 typedef unsigned char TCHAR;

#endif

typedef TCHAR * LPTSTR, *LPTCH;

/* 8-bit character specific */

typedef unsigned char CHAR;

typedef CHAR *LPSTR, *LPCH;

/* Unicode specific (wide characters) */

typedef unsigned wchar_t WCHAR;

typedef WCHAR *LPWSTR, *LPWCH;

The letter T preceding a type definition designates a generic type that can be compiled for either ANSI or Unicode. The letter W preceding a type definition designates a wide-character (Unicode) type. For the actual implementation of this method, see the WINNT.H header file.

An application using generic data types can be compiled for Unicode simply by defining UNICODE before the include statements for the header files. To compile the code for ANSI, omit the UNICODE definition.

Developers are encouraged to use the generic data types, but the specific types exist for applications that require mixed-type control.


 Function Prototypes

Function prototypes are also provided in generic, ANSI, and Unicode varieties, as shown below. The generic function prototype consists of the standard function name implemented as a macro. The preprocessor expands each macro into one of the specific function prototypes, depending on whether UNICODE is defined. The letters A (ANSI) and W (wide) are added at the end of the function names in the specific function prototypes. In this example, the generic prototype uses the generic type LPTSTR for the text parameter, but the A and W prototypes use the LPCSTR and LPCWSTR character types, respectively.

SetWindowText(HWND hwnd, LPTSTR lpText);

SetWindowTextA(HWND hwnd, LPCSTR lpText);

SetWindowTextW(HWND hwnd, LPCWSTR lpText);

An application can use the generic function and make Unicode dependent on whether the UNICODE option is used to compile the code, or it can make mixed calls by using the explicit function names ending with A and W.

This three-prototype approach applies to all functions with text arguments. Always use a generic function prototype with the generic string and character types. All function names that end with an uppercase W take wide-character arguments.

Some functions exist only in wide-character versions and can be used only with the appropriate data type.

The reference material for each Unicode-enabled function is labeled with a Unicode icon. If the function exists as a macro that the preprocessor must expand into an ANSI or Unicode form, only the macro form is documented.

Note  Whenever a function has a length parameter for a character string, the length should be given as a count of characters (TCHAR units) in the string. However, functions that require or return pointers to untyped memory blocks, such as the GlobalAlloc function, are exceptions.


 Message Translation

Although applications generally use the same window class, messages between windows of different classes are transparently translated by the system.

Even though a window function is implemented to receive messages in Unicode or ANSI format, the window procedure can still send messages or call functions of either type.

The following messages have text arguments and are subject to automatic text translation. (For information about automatic translation, see Subclassing and Automatic Message Translation.)

CB_ADDSTRING	WM_ASKCBFORMATNAME
CB_DIR	WM_CHAR
CB_FINDSTRING	WM_CHARTOITEM
CB_GETLBTEXT	WM_CREATE
CB_INSERTSTRING	WM_DEADCHAR
CB_SELECTSTRING	WM_DEVMODECHANGE
	WM_GETTEXT
EM_GETLINE	WM_MDICREATE
EM_REPLACESEL	WM_MENUCHAR
EM_SETPASSWORDCHAR	WM_NCCREATE
	WM_SETTEXT
LB_ADDFILE	WM_SYSCHAR
LB_ADDSTRING	WM_SYSDEADCHAR
LB_DIR	WM_WININICHANGE
LB_FINDSTRING
LB_GETTEXT
LB_INSERTSTRING
LB_SELECTSTRING


 String Functions

All of the string functions listed in this section exist in ANSI and Unicode implementations to support ANSI and Unicode arguments. There are, however, subtle differences among some of them.

The following string functions do not require special comment; their ANSI and Unicode implementations work identically.

CharNext
CharPrev
lstrcat
lstrcpy
lstrlen

The value returned by the lstrlen function is always the number of characters, regardless of whether the ANSI or Unicode form is used.

The following string functions are sensitive to the locale of the current thread (as derived from the locale the user selects in Control Panel). The lstrcmp and lstrcmpi functions do not perform byte comparisons like their ANSI C namesakes; they compare strings according to the rules of the selected locale.

CharLower
CharLowerBuff
CharUpper
CharUpperBuff
lstrcmp
lstrcmpi

The following functions convert between the OEM character set and either ANSI or Unicode, depending on which version is used.

CharToOem
CharToOemBuff
OemToChar
OemToCharBuff

The print function wsprintf supports Unicode by providing the following new and changed data types in its format specifications. These format specifications affect the way the wsprintf function interprets the corresponding passed-in parameter.

Format specification	ANSI version	Unicode version
c	CHAR	WCHAR
C	WCHAR	CHAR
hc, hC	CHAR	CHAR
hs, hS	LPSTR	LPSTR
lc, lC	WCHAR	WCHAR
ls, lS	LPWSTR	LPWSTR
s	LPSTR	LPWSTR
S	LPWSTR	LPSTR
The data type for the output text always depends on the version of the function. Where the data type of the passed-in parameter and of the output text do not agree, wsprintf will perform a conversion from Unicode to ANSI, or vice versa, as required.

For the Unicode version of wsprintf, the format string is Unicode, as is the output text.


 Standard C Functions

The standard C libraries contain wide-character versions of the ANSI string functions that begin with the letters str. The wide-character versions of the functions start with the letters wcs (or sometimes _wcs). The Unicode data type is compatible with the wide-character data type wchar_t in ANSI C; this allows access to the wide-character string functions.

Generic functions exist for all standard C string functions. They start with the letters _tcs and are listed in the TCHAR.H header file. These functions use the generic data types TCHAR and TCHAR*

An application must add the following lines to its program in order to use the generic functions and compile for Unicode:

     #define _UNICODE

     #include <tchar.h>

     #include <wchar.h>

Note that both the TCHAR.H and WCHAR.H are required, and that the leading underscore on the _UNICODE variable is also required.

The wcstombs and mbstowcs functions can convert from the character set supported by the standard C library to Unicode and back, with some limitations. For more information about translating strings to and from Unicode, see Translation Between String Types.

The printf function defined in TCHAR.H supports the same format specifications as wsprintf; for details, see String Functions. Similarly, TCHAR.H contains a wprintf function, in which the format string itself is a Unicode string.


 Filenames

In Windows, the ANSI character set is used in window manager and GDI; the MS-DOS FAT file system uses the OEM character set. Windows applications that create MS-DOS files have sometimes had to use the CharToOem and OemToChar functions to translate between these character sets. However, the New Technology file system (NTFS) file system is capable of storing filenames in Unicode; no translation is necessary with NTFS.

With Unicode implementations of the file-system functions, it is not necessary to perform translations to and from ANSI and OEM character sets. Instead, a developer can use a single source file to compile non-Unicode versions of an application by providing macros for functions that are not invoked when compiling for Unicode, such as CharToOem and OemToChar.

The special filename characters in MS-DOS are unchanged in Unicode filenames:

"\," "/," ".," "?," "*."

These special characters are in the ASCII range of characters (0x00 through 0x7F) and their Unicode equivalents are simply the same values in a 2-byte form: 0x0000 through 0x007F.


 Translation Between String Types

The following Win32 functions translate character strings from one string type to another.

Function	Description
FoldString	Translates one character string to another.
LCMapString	Maps a character string by locale.
ToUnicode	Translates a virtual-key code into a Unicode character.
MultiByteToWideChar	Maps a multibyte string into a wide-character string.
WideCharToMultiByte	Maps a wide-character string into a multibyte string.
The WideCharToMultiByte and MultiByteToWideChar functions are particularly useful for applications that support several string types. ANSI C also defines the conversion functions wcstombs and mbstowcs, but they can only convert to and from the character set supported by the standard C library.


 Command-line Arguments

An application can use the GetCommandLine function to retrieve Unicode command-line arguments by calling it as a Unicode function.


 Using Strings and Unicode

•	Using generic data types

•	Registering window classes

•	Subclassing and automatic message translation

•	Using special characters in Unicode

•	Using functions that have no Unicode equivalents


 Using Generic Data Types

If you use generic data types in your code, it can be compiled for Unicode simply by defining UNICODE before the include statements for the header files. To compile the code for ANSI, omit the UNICODE definition.

To convert code that processes strings so it can be compiled for either ANSI or Unicode, follow these steps.

1.	Change all character and string types used for text to TCHAR, LPTSTR, or LPTCH.

2.	Be sure that pointers to nontext data buffers or binary byte arrays are coded with the LPBYTE type and not mistakenly with the LPTSTR or LPTCH type. Declare pointers of indeterminate type explicitly as void pointers by using LPVOID, as appropriate.

3.	Make pointer arithmetic type-independent. Using units of TCHAR size yields variables that are two bytes if UNICODE is defined, and one byte if UNICODE is not defined. Using pointer arithmetic always returns the number of elements pointed to by the pointer, whether the elements are one or two bytes in size. The following expression always returns the number of elements, regardless of whether UNICODE is defined:

cCount = lpEnd - lpStart;

The following expression determines the number of bytes used:

cByteCount = (lpEnd - lpStart) * sizeof(TCHAR);

There is no need to change a statement like the following one, because the pointer increment points to the next character element.

chNext = *++lpText;

4.	Replace literal strings and manifest character constants with macros. Change expressions like the following one.

    while(*lpFileName++ != '\\') {

/* .

/* .

/* .

    }

Use the TEXT macro as follows in this expression.

    while(*lpFileName++ != TEXT('\\')) {

        ./*

        ./*

        ./*

    }

Precede a literal string in the Unicode form of a function by the letter L. The TEXT macro causes strings to be evaluated as L"string" when UNICODE is defined, and to "string" otherwise. The following call to the Unicode version of lstrlen demonstrates the use of the L identifier.

cch == lstrlenW(L"hello world");

For easier management, move literal strings into resources, especially if they contain characters outside the ASCII range (that is, 0x00 through 0x7F).

5.	Call only the Unicode versions of the standard C library string functions, as listed in Standard C Functions.

6.	Change any code that relies on 255 as the largest value for a character.

When you compile code that you have changed as outlined above, the compiler creates the same binary file as it did before you made the changes. When you compile the code using the UNICODE option, however, it is compiled as a Unicode application.


 Registering Window Classes

A window class is supported by a window procedure. You can register a window class by using either the RegisterClassA or RegisterClassW function. 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.

The following example shows how to register an ANSI window class and a Unicode window class and how to write the window procedures for both cases. For the purposes of this example, all functions and structures are shown with the specific A or W data types. Using the techniques explained in Using Generic Data Types, you could alternatively write this example by using generic data types, so that it could be compiled as either ANSI or Unicode, depending on whether UNICODE is defined.

/* Register an ANSI window class. */

WNDCLASSA AnsiWndCls;

AnsiWndCls.style         = CS_DBLCLKS | CS_PARENTDC;

AnsiWndCls.lpfnWndProc   = (WNDPROC)AnsiWndProc;

AnsiWndCls.cbClsExtra    = 0;

AnsiWndCls.cbWndExtra    = 0;

AnsiWndCls.hInstance     = hmodUser;

AnsiWndCls.hIcon         = NULL;

AnsiWndCls.hCursor       = LoadCursor(NULL, (LPTSTR)IDC_IBEAM);

AnsiWndCls.hbrBackground = NULL;

AnsiWndCls.lpszMenuName  = NULL;

AnsiWndCls.lpszClassName = "TestAnsi";

RegisterClassA(&AnsiWndCls);

/* Register a Unicode window class. */

WNDCLASSW UnicodeWndCls;

UnicodeWndCls.style         = CS_DBLCLKS | CS_PARENTDC;

UnicodeWndCls.lpfnWndProc   = (WNDPROC)UniWndProc;

UnicodeWndCls.cbClsExtra    = 0;

UnicodeWndCls.cbWndExtra    = 0;

UnicodeWndCls.hInstance     = hmodUser;

UnicodeWndCls.hIcon         = NULL;

UnicodeWndCls.hCursor       = LoadCursor(NULL,(LPTSTR)IDC_IBEAM);

UnicodeWndCls.hbrBackground = NULL;

UnicodeWndCls.lpszMenuName  = NULL;

UnicodeWndCls.lpszClassName = L"TestUnicode";

RegisterClassW(&UnicodeWndCls);

The following example shows the difference between handling the WM_CHAR message in an ANSI window procedure and a Unicode window procedure.

/* ANSI Window Procedure */

LONG AnsiWndProc(HWND hwnd, UINT message,

                 WPARAM wParam, LPARAM lParam)

{

    /* Dispatch the messages that can be received. */

    switch (message) {

        case WM_CHAR:

            /*

             * wParam - the value of the key

             * lParam - (not used in this example)

             */

            if (lstrcmpA("Q", (LPCSTR) wParam)) {

                 /*.

                 /*.

                 /*.

            }

            else {

                 ./*

                 /*.

                 /*.

            }

            break;

        ./*

        ./* process other messages */

        ./*

    }

}

/* Unicode Window Procedure */

LONG UniWndProc(HWND hwnd, UINT message,

    WPARAM wParam, LPARAM lParam)

{

    /* Dispatch the messages that can be received. */

    switch (message) {

        case WM_CHAR:

            /*

             * wParam - the value of the key

             * lParam - (not used in this example)

             */

            if (lstrcmpW(L"Q", (LPCWSTR) wParam)) {

                 /*.

                 /*.

                 /*.

            }

            else {

                 /*.

                 /* .

                 /* .

            }

            break;

        /* .

        /* process other messages */

        /* .

    }

}

All text in messages received by AnsiWndProc will be composed of ANSI characters, and all text in messages received by UniWndProc will be composed of Unicode characters.


 Subclassing and Automatic Message Translation

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. The system automatically translates messages into ANSI or Unicode form, depending on the form of the function that subclassed the window procedure.

The following call to the SetWindowLongA function subclasses the current window procedure associated with the window identified by the hwnd parameter. The new window procedure, NewWndProc, will receive messages with text in ANSI format.

OldWndProc = (WNDPROC) SetWindowLongA(hwnd,

    GWL_WNDPROC, (LONG)NewWndProc);

When NewWndProc has finished processing a message, it uses the CallWindowProc function as follows to pass the message to OldWndProc.

CallWindowProc(OldWndProc, hwnd, uMessage, wParam, lParam);

If OldWndProc was created with a class style of UNICODE, messages will be translated from the ANSI form received by NewWndProc into Unicode.

Similarly, a call to the SetWindowLongW function would subclass the current window procedure with a window procedure that expects Unicode text messages. Message translation, if necessary, is performed during the processing of the CallWindowProc function.

For more information about subclassing, see Window Procedures.


 Using Special Characters in Unicode

There are a few special characters and characters with unusual meanings in Unicode text strings. To avoid unexpected problems with these characters, use the rules provided in the following topics.

•	Null-terminated strings

•	Byte-order mark

•	Escape sequences and control characters

•	Line and paragraph separators

•	ASCII control codes 0x000D and 0x000A

•	Nonspacing characters and diacritics


 Null-terminated Strings

Always cast zero to TCHAR when using null-terminated strings. The code 0x0000 is the Unicode string terminator for null-terminated strings. A single null byte is not sufficient for this code, because many Unicode characters contain null bytes as either the high or the low byte. An example is the letter A, for which the character code is 0x0041.


 Byte-order Mark

Always prefix a Unicode plain text file with a byte-order mark. Because Unicode plain text is a sequence of 16-bit codes, it is sensitive to the byte ordering used when the text was written.

A byte-order mark is not a control character that selects the byte order of the text; it simply informs an application receiving the file that the file is byte ordered.

Ideally, all Unicode text would follow only one set of byte-ordering rules. This is not possible, however, because microprocessors differ in the position of the least significant byte: Intel® and MIPS® processors have the least significant byte first; Motorola processors (and byte-reversed Unicode files) have it last. With only a single set of byte-ordering rules, users of one type of microprocessor would be forced to swap the byte order every time a plain text file is read from or written to, even if the file is never transferred to another system based on a different microprocessor.

The preferred place to specify byte order is in a file header, but text files do not have headers. Therefore, Unicode has defined a character (0xFEFF) and a noncharacter (0xFFFE) as byte-order marks. They are mirror byte-images of each other.

Since the sequence 0xFEFF is exceedingly rare at the outset of regular non-Unicode text files, it can serve as an implicit marker or signature to identify the file as a Unicode file. Applications written to read both Unicode and non-Unicode text files should use the presence of this sequence as a near-certain indicator that the file is a Unicode file. (Compare this technique to using the MS-DOS EOF marker to terminate text files.)

When an application finds 0xFEFF at the beginning of a text file, it typically processes the file as though it were a Unicode file, although it may also perform further heuristic checks to verify that this is true. Such a check could be as simple as a test of whether the variation in the low-order bytes is much higher than the variation in the high-order bytes. For example, if ASCII text is converted to Unicode text, every second byte is zero. Also, checking both for the linefeed and carriage-return characters (0x000A and 0x000D) and for even or odd file size can provide a strong indicator of the nature of the file.

When an application finds 0xFFFE at the beginning of a text file, it interprets it to mean the file is a byte-reversed Unicode file. The application can either swap the order of the bytes or alert the user that an error has occurred.

The Unicode byte-order mark character is not found in any code page, so it disappears if data is converted to ANSI. Unlike other Unicode characters, it is not replaced by a default character when it is converted. If a byte-order mark is found in the middle of a file, it is not interpreted as a Unicode character and has no effect on text output.

The Unicode value 0xFFFF is illegal in plain text files and cannot be passed between Windows functions. The value 0xFFFF is reserved for an application's private use.


 Escape Sequences and Control Characters

Translate escape sequences character by character into Unicode. When an ASCII plain text file is converted to Unicode, there is a chance that it will subsequently be converted back to ASCII. Converting escape sequences into Unicode on a character-by-character basis, rather than as a single 2-byte characters makes it possible to perform the reverse conversion without recognizing and parsing the escape sequences as such. For example, ESC+A should become 0x001B (ESC), 0x0041 (A), rather than 0x411B.

The first 32 sixteen-bit characters in Unicode are intended for the 32 control characters. This approach supports the existing use of control characters for formatting purposes — that is, Unicode applications can treat these control characters in exactly the same way as they treat their ASCII equivalents.


 Line and Paragraph Separators

Use the line-separator character (0x2028) and the paragraph-separator character (0x2029) to divide plain text. A new line is begun after each line separator. A new paragraph is begun after each paragraph separator.

Because these are separator codes, it is not necessary to start the first line or paragraph in the file with them, or to end the last line or paragraph with them. (Doing so would indicate that there is an empty line or paragraph in that location.)

The line separator can be used to indicate an unconditional end of line. However, line separators do not correspond to the carriage-return and linefeed characters, or to the carriage-return−linefeed character combination; they must be processed separately from carriage return and linefeed characters.

The paragraph separator can be inserted between paragraphs of text. This allows plain text files to be created that can be formatted with different line widths on different systems. The receiving system can ignore any line breaks and break paragraphs only at the paragraph separators.


 ASCII Control Codes 0x000D and 0x000A

The Unicode standard does not prescribe a specific meaning for the control codes 0x000D (carriage return) and 0x000A (linefeed). There is no requirement that these codes be used in combination, and if used individually, either code may represent either itself only or both codes together. It is entirely up to the application to determine what these codes represent. (Applications have always had to interpret these control codes in ASCII; the Unicode policy is not a change in their use.)


 Nonspacing Characters and Diacritics

When breaking lines or otherwise separating text, be sure to keep nonspacing characters with their base characters. Many scripts contain characters that visually combine with other characters on output — for example, the diacritical marks (or "floating accents"). In Unicode, nonspacing characters follow their base character.


 Using Functions That Have No Unicode Equivalents

Windows functions that have not been exported in a Unicode version have typically been replaced by more powerful or extended functions that do support Unicode. If you are porting code that calls the OpenFile function, for example, you can support Unicode by using the CreateFile or CreateFileEx function instead.

If a function has no Unicode equivalent, you can map characters to and from 8-bit character sets before and after the function call. For example, the number-formatting functions atoi and itoa use only the digits 0 through 9. Normally, mapping Unicode to 8-bit characters could cause loss of data, but you can avoid this by making your code type independent and conditionalizing the expressions. For example, the following statements are type dependent and should be changed to support Unicode.

    char str[4];

    num = atoi(str);

These statements could be rewritten as follows to make them type independent.

    TCHAR tstr[4];

    CHAR strTmp[SIZE];

    #ifdef UNICODE

    wcstombs(strTmp, (const wchar_t *) tstr, sizeof(strTmp));

    num = atoi(strTmp);

    #else

    num = atoi(tstr);

    #endif

In this example, the wcstombs function is the standard C function that translates Unicode to ASCII. The example relies on the fact that the digits 0 through 9 can always be translated from Unicode to ASCII, even if some of the surrounding text cannot. The atoi function stops at any character that is not a digit. You can use the LCMapString function if you need to process text that includes the native digits provided for some of the scripts in Unicode.


 Unicode and Character Set Functions

This section describes the character set functions. On errors, some of these functions set an extended error value. Use the GetLastError function to retrieve this value.

IsDBCSLeadByteEx
TranslateCharsetInfo
WideCharToMultiByte


 Obsolete Unicode Functions

The AnsiToOem function is obsolete. Use the CharToOem function.

The AnsiToOemBuff function is obsolete. Use the CharToOemBuff function.

The OemToAnsi function is obsolete. Use the OemToChar function.

The OemToAnsiBuff function is obsolete. Use the OemToCharBuff function.


 Unicode and Character Set Structures

This section describes the structures used by the character set functions.

CHARSETINFO
FONTSIGNATURE
LOCALESIGNATURE


 Unicode and Character Set Constants

This section describes the constants used with the character set functions.


ANSI Code Page Identifiers
 ANSI Code-Page Identifiers

Identifier	Meaning
874	Thai
932	Japan
936	Chinese (PRC, Singapore)
949	Korean
950	Chinese (Taiwan, Hong Kong)
1200	Unicode (BMP of ISO 10646)
1250	Windows 3.1 Eastern European
1251	Windows 3.1 Cyrillic
1252	Windows 3.1 Latin 1 (US, Western Europe)
1253	Windows 3.1 Greek
1254	Windows 3.1 Turkish
1255	Hebrew
1256	Arabic
1257	Baltic


OEM Code Page Identifiers
 OEM Code-Page Identifiers

Identifier	Meaning
437	MS-DOS United States
708	Arabic (ASMO 708)
709	Arabic (ASMO 449+, BCON V4)
710	Arabic (Transparent Arabic)
720	Arabic (Transparent ASMO)
737	Greek (formerly 437G)
775	Baltic
850	MS-DOS Multilingual (Latin I)
852	MS-DOS Slavic (Latin II)
855	IBM Cyrillic (primarily Russian)
857	IBM Turkish
860	MS-DOS Portuguese
861	MS-DOS Icelandic
862	Hebrew
863	MS-DOS Canadian-French
864	Arabic
865	MS-DOS Nordic
866	MS-DOS Russian (former USSR)
869	IBM Modern Greek
874	Thai
932	Japan
936	Chinese (PRC, Singapore)
949	Korean
950	Chinese (Taiwan, Hong Kong)
1361	Korean (Johab)


Code Page Identifiers
 Code-Page Identifiers

Identifier	Meaning
037	EBCDIC
437	MS-DOS  United States
500	EBCDIC "500V1"
708	Arabic (ASMO 708)
709	Arabic (ASMO 449+, BCON V4)
710	Arabic (Transparent Arabic)
720	Arabic (Transparent ASMO)
737	Greek (formerly 437G)
775	Baltic
850	MS-DOS  Multilingual (Latin I)
852	MS-DOS  Slavic (Latin II)
855	IBM Cyrillic (primarily Russian)
857	IBM Turkish
860	MS-DOS  Portuguese
861	MS-DOS Icelandic
862	Hebrew
863	MS-DOS Canadian-French
864	Arabic
865	MS-DOS Nordic
866	MS-DOS Russian
869	IBM Modern Greek
874	Thai
875	EBCDIC
932	Japan
936	Chinese (PRC, Singapore)
949	Korean
950	Chinese (Taiwan, Hong Kong)
1026	EBCDIC
1200	Unicode (BMP of ISO 10646)
1250	Windows 3.1 Eastern European
1251	Windows 3.1 Cyrillic
1252	Windows 3.1 US (ANSI)
1253	Windows 3.1 Greek
1254	Windows 3.1 Turkish
1255	Hebrew
1256	Arabic
1257	Baltic
1361	Korean (Johab)
10000	Macintosh Roman
10001	Macintosh Japanese
10006	Macintosh Greek I
10007	Macintosh Cyrillic
10029	Macintosh Latin 2
10079	Macintosh Icelandic
10081	Macintosh Turkish


Codepage Bitfields
 Code-Page Bitfields

Bit	Code page	Description
ANSI
0	1252	Latin 1
1	1250	Latin 2: Eastern Europe
2	1251	Cyrillic
3	1253	Greek
4	1254	Turkish
5	1255	Hebrew
6	1256	Arabic
7	1257	Baltic
8 - 16		Reserved for ANSI
ANSI and OEM
17	874	Thai
18	932	JIS/Japan
19	936	Chinese: Simplified chars--PRC and Singapore
20	949	Korean Unified Hangeul Code (Hangeul TongHabHyung Code)
21	950	Chinese: Traditional chars--Taiwan and Hong Kong
22 - 29		Reserved for alternate ANSI and OEM
30 - 31		Reserved by system.
OEM
32 - 47		Reserved for OEM
48	869	IBM Greek
49	866	MS-DOS Russian
50	865	MS-DOS Nordic
51	864	Arabic
52	863	MS-DOS Canadian French
53	862	Hebrew
54	861	MS-DOS Icelandic
55	860	MS-DOS Portuguese
56	857	IBM Turkish
57	855	IBM Cyrillic; primarily Russian
58	852	Latin 2
59	775	Baltic
60	737	Greek; former 437 G
61	708	Arabic; ASMO 708
62	850	WE/Latin 1
63	437	US


 Networks

An application written for Microsoft® Windows® can use the network functions in the Microsoft® Win32® application programming interface (API) to implement networking capabilities without making allowances for a particular network provider or physical network implementation.


 About Networks

Win32 network functions are network independent. Applications can use these functions to add and cancel network connections and to retrieve information about the current configuration of the network. In addition, the Win32 API implements a version of the NetBIOS network interface for applications that require it.

In addition to using the network functions, processes can also use the Win32 API implementations of mailslots and named pipes to communicate with one another. For more information about these subjects, see Mailslots and Pipes.

The following figure shows the structure of a typical network.

In the preceding figure, the hierarchy for Microsoft Advanced Server resources is given in detail as Network provider #1. Network resources from other providers have different hierarchical systems. An application does not need information about the hierarchy before it begins to work with a network. It can proceed from the network root (that is, the topmost container resource) and retrieve information about the network's resources as the information is required.

Network resources that contain other resources are called containers. Container resources are in boxes in the preceding figure.

Resources that do not contain other resources are objects. Sharepoint #1 and Sharepoint #2 in the figure are objects. A sharepoint is an object that is accessible across the network, such as a printer or a shared directory.


 Network-Independent Functions

Windows version 3.1 included the following network-independent network functions:

WNetAddConnection
WNetCancelConnection
WNetGetConnection

The Win32 API supports these functions and has added the following network and network enumeration functions:

WNetAddConnection2	WNetEnumResource
WNetCancelConnection2	WNetGetLastError
WNetCloseEnum	WNetGetUser
WNetConnectionDialog	WNetOpenEnum
WNetDisconnectDialog
Many of these functions use a NETRESOURCE structure, which is also part of the Win32 API. WNetAddConnection and WNetCancelConnection are supported for compatibility with earlier versions of Windows. However, new applications typically use WNetAddConnection2 and WNetCancelConnection2 instead.

An application can use the network functions to browse, add, or cancel network connections anywhere in the hierarchy. By starting at the network root, the resources from all network providers can be enumerated.

A persistent connection is a network connection that Windows automatically restores when the user logs on. Using WNetAddConnection2 and WNetCancelConnection2, an application can control whether a network connection is persistent from one session to the next.


 The Netbios Function

The Netbios function is provided primarily for applications that were written for the NetBIOS interface and need to be ported to Windows. Applications not requiring compatibility with NetBIOS can usually use other interfaces, such as mailslots and named pipes, to accomplish tasks similar to those supported by Netbios.

Netbios in the Win32 API takes one parameter: a pointer to a structure describing a network control block (NCB). The NCB structure contains information about the network environment and a pointer to a buffer that is used for messages or for further data about the network.


 Windows NetBios Enhancements

The Win32 implementation of the Netbios function includes the following enhancements that are not part of the NetBIOS 3.0 specification:

•	POST routines can be called from the C programming language by means of the ncb_post member of the NCB structure.

•	Each asynchronous network control block can supply an event (in the ncb_event member of the NCB structure) set to the signaled state when the NCB completes.

•	An application can enumerate all available LAN adapters by using the NCBENUM command in the ncb_command member of the NCB structure.


 Differences Between Windows and NetBIOS

In addition to the enhancements listed in the preceding section, the following differences exist between the Win32 implementation of the Netbios function and the NetBIOS 3.0 specification:

•	The system does not monitor the number of outstanding NCB commands specified when the NCBRESET command is issued. The memory quota limits for Windows are used to limit the total resources an application can use.

•	Asynchronous commands on invalid sessions are rejected when they are submitted.

•	The numbers of the network names (the ncb_num member of the NCB structure) are assigned on a per-process basis.

•	Requests for the status of the local adapter retrieve only the names that were added by the process making the request.

•	The value 1 for the ncb_lana_num member of the NCB structure is not exclusive when the NCBRESET command is issued. All MS-DOS and 16-bit Windows-based applications also share access to name number 1.


 Using Networks

The Windows network functions enable your application to query and control network connections directly or to give direct control of the network connections to the user. To use these functions, you must link to the multiple-provider router library (MPR.LIB). This section discusses how to use the network functions in your application.

•	Using the connections dialog box

•	Enumerating network resources

•	Adding a network connection

•	Retrieving the connection name

•	Retrieving the user name

•	Canceling a network connection

•	Retrieving network errors


 Using the Connections Dialog Box

The WNetConnectionDialog function creates a dialog box that allows the user to browse and connect to network resources. Conversely, the WNetDisconnectDialog function creates a dialog box that allows the user to disconnect from them.

The following example shows how to use the WNetConnectionDialog function to create a dialog box that displays disk resources.

DWORD dwResult;

dwResult = WNetConnectionDialog(hwnd,

    RESOURCETYPE_DISK);

if(dwResult != NO_ERROR) {

    /*

     * An application-defined error handler is demonstrated in the

     * section titled "Retrieving Network Errors."

     */

    NetErrorHandler(hwnd, dwResult, (LPSTR)"WNetConnectionDialog");

    return FALSE;

}


 Enumerating Network Resources

To enumerate a network container resource, your application should pass the address of a NETRESOURCE structure to the WNetOpenEnum function. WNetOpenEnum creates a handle to the resource described by the NETRESOURCE structure. The application then passes this handle to the WNetEnumResource function, which returns information about the resource in the form of an array of NETRESOURCE structures. When the handle is no longer needed, the application can close it by calling the WNetCloseEnum function.

Your application can continue enumerating any container resource described in the array of NETRESOURCE structures retrieved by WNetEnumResource. If the dwUsage member of the NETRESOURCE structure is RESOURCEUSAGE_CONTAINER, the application can pass the address of that structure to WNetOpenEnum to open the container and continue the enumeration. If dwUsage is RESOURCEUSAGE_CONNECTABLE, the application can pass the structure's address to the WNetAddConnection2 function.

The following example illustrates an application-defined function (EnumerateFunc) that enumerates all the resources on a network. When calling this function, specify NULL for the pointer to the NETRESOURCE structure. When WNetOpenEnum receives the NULL pointer, it retrieves a handle to the root of the network. Whenever a NETRESOURCE structure retrieved by WNetEnumResource is RESOURCEUSAGE_CONTAINER, the EnumerateFunc function calls itself and uses a pointer to that structure in its call to WNetOpenEnum.

BOOL FAR PASCAL EnumerateFunc(hwnd, hdc, lpnr)

HWND hwnd;

HDC hdc;

LPNETRESOURCE lpnr;

{

    DWORD dwResult, dwResultEnum;

    HANDLE hEnum;

    DWORD cbBuffer = 16384; /* 16K is reasonable size                 */

    DWORD cEntries = 0xFFFFFFFF; /* enumerate all possible entries    */

    LPNETRESOURCE lpnrLocal;     /* pointer to enumerated structures  */

    DWORD i;

    dwResult = WNetOpenEnum(RESOURCE_GLOBALNET,

        RESOURCETYPE_ANY,

        0,                 /* enumerate all resources                 */

        lpnr,              /* NULL first time this function is called */

        &hEnum);           /* handle to resource                      */

    if (dwResult != NO_ERROR) {

        /*

         * An application-defined error handler is demonstrated in the

         * section titled "Retrieving Network Errors."

         */

        NetErrorHandler(hwnd, dwResult, (LPSTR)"WNetOpenEnum");

        return FALSE;

    }

    do {

        /* Allocate memory for NETRESOURCE structures. */

        lpnrLocal = (LPNETRESOURCE) GlobalAlloc(GPTR, cbBuffer);

        dwResultEnum = WNetEnumResource(hEnum, /* resource handle     */

            &cEntries,               /* defined locally as 0xFFFFFFFF */

            lpnrLocal,               /* LPNETRESOURCE                 */

            &cbBuffer);              /* buffer size                   */

        if (dwResultEnum == NO_ERROR) {

            for(i = 0; i < cEntries; i++) {

                /*

                 * Following is an application-defined function for

                 * displaying contents of NETRESOURCE structures.

                 */

                DisplayStruct(hdc, &lpnrLocal[i]);

                /*

                 * If this NETRESOURCE is a container, call the function

                 * recursively.

                 */

                if(RESOURCEUSAGE_CONTAINER ==

                        (lpnrLocal[i].dwUsage & RESOURCEUSAGE_CONTAINER))

                    if(!EnumerateFunc(hwnd, hdc, &lpnrLocal[i]))

                        TextOut(hdc, 10, 10,

                            "EnumerateFunc returned FALSE.", 29);

            }

        }

        else if (dwResultEnum != ERROR_NO_MORE_ITEMS) {

            NetErrorHandler(hwnd, dwResultEnum, (LPSTR)"WNetEnumResource");

            break;

        }

    }

    while(dwResultEnum != ERROR_NO_MORE_ITEMS);

    GlobalFree((HGLOBAL) lpnrLocal);

    dwResult = WNetCloseEnum(hEnum);

    if(dwResult != NO_ERROR) {

        NetErrorHandler(hwnd, dwResult, (LPSTR)"WNetCloseEnum");

        return FALSE;

    }

    return TRUE;

}


 Adding a Network Connection

To make a connection to a network resource described by a NETRESOURCE structure, an application can call the WNetAddConnection2 function, as shown in the following example.

DWORD dwResult;

NETRESOURCE nr;

dwResult = WNetAddConnection2(&nr, /* NETRESOURCE from enumeration */

    (LPSTR) NULL,             /* no password                       */

    (LPSTR) NULL,             /* logged-in user                    */

    CONNECT_UPDATE_PROFILE);  /* update profile with connect info  */

if (dwResult == ERROR_ALREADY_ASSIGNED) {

    TextOut(hdc, 10, 10, "Already connected to specified resource.", 40);

    return FALSE;

}

else if (dwResult == ERROR_DEVICE_ALREADY_REMEMBERED) {

    TextOut(hdc, 10, 10,

        "Attempted reassignment of remembered device.", 44);

    return FALSE;

}

else if(dwResult != NO_ERROR) {

    /*

     * An application-defined error handler is demonstrated in the

     * section titled "Retrieving Network Errors."

     */

    NetErrorHandler(hwnd, dwResult, (LPSTR)"WNetAddConnection2");

    return FALSE;

}

TextOut(hdc, 10, 10, "Connected to specified resource.", 32);

return TRUE;

The WNetAddConnection function is supported for compatibility with earlier versions of Windows. For new applications, use WNetAddConnection2.


 Retrieving the Connection Name

To retrieve the name of the network resource associated with a local device, an application can use the WNetGetConnection function, as shown in the following example.

CHAR szDeviceName[80];

DWORD dwResult, cchBuff = sizeof(szDeviceName);

dwResult = WNetGetConnection("z:",

    (LPSTR) szDeviceName,

    &cchBuff);

switch (dwResult) {

    case NO_ERROR:

        TextOut(hdc, 10, 10, (LPSTR) szDeviceName,

            lstrlen((LPSTR) szDeviceName));

        break;

    case ERROR_NOT_CONNECTED:

        TextOut(hdc, 10, 10, "Device z: not connected.", 24);

    case ERROR_CONNECTION_UNAVAIL:

        /* A connection is remembered but not connected. */

        TextOut(hdc, 10, 10, "Connection unavailable.", 23);

    default:

        /*

         * An application-defined error handler is demonstrated in the

         * section titled "Retrieving Network Errors."

         */

        NetErrorHandler(hwnd, dwResult, (LPSTR)"WNetGetConnection");

        return FALSE;

}


 Retrieving the User Name

To retrieve the name of the user associated either with a local device connected to a network resource or with the name of a network, an application can call the WNetGetUser function. The following example uses the device name to retrieve the name of the user.

CHAR szUserName[80];

DWORD dwResult, cchBuff = 80;

dwResult = WNetGetUser("z:",

    (LPSTR) szUserName,

    &cchBuff);

if(dwResult == NO_ERROR)

    TextOut(hdc, 10, 10,

        (LPSTR) szUserName,

        lstrlen((LPSTR) szUserName));

else {

    /*

     * An application-defined error handler is demonstrated in the

     * section titled "Retrieving Network Errors."

     */

    NetErrorHandler(hwnd, dwResult, (LPSTR)"WNetGetUser");

    return FALSE;

}


 Canceling a Network Connection

To cancel a connection to a network resource, an application can call the WNetCancelConnection2 function, as shown in the following example.

DWORD dwResult;

dwResult = WNetCancelConnection2("z:",

    CONNECT_UPDATE_PROFILE, /* remove connection from profile */

    FALSE);               /* fail if open files or jobs       */

if (dwResult == ERROR_NOT_CONNECTED) {

    TextOut(hdc, 10, 10, "Drive z: not connected.", 23);

    return FALSE;

}

else if(dwResult != NO_ERROR) {

    /*

     * An application-defined error handler is demonstrated in the

     * section titled "Retrieving Network Errors."

     */

    NetErrorHandler(hwnd, dwResult, (LPSTR)"WNetCancelConnection2");

    return FALSE;

}

TextOut(hdc, 10, 10, "Connection closed for z:.", 25);

The WNetCancelConnection function is supported for compatibility with earlier versions of Windows. For new applications, use WNetCancelConnection2.


 Retrieving Network Errors

When one of the Windows network functions returns WN_EXTENDED_ERROR, an application can call the WNetGetLastError function to get more information about the error that occurred. This information is usually specific to the network provider.

The following example illustrates an application-defined error-handling function (NetErrorHandler) that takes three arguments: a window handle, the error code returned by one of the Windows network functions, and the name of the function that produced the error. If the error code is WN_EXTENDED_ERROR, NetErrorHandler calls WNetGetLastError to get extended error information.

BOOL WINAPI NetErrorHandler(hwnd, dwErrorCode, lpszFunction)

HWND  hwnd;

DWORD dwErrorCode;

LPSTR lpszFunction;

{

    DWORD dwWNetResult, dwLastError;

    CHAR szError[256];

    CHAR szCaption[256];

    CHAR szDescription[256];

    CHAR szProvider[256];

    /* The following code performs standard error-handling. */

    if (dwErrorCode != ERROR_EXTENDED_ERROR) {

        wsprintf((LPSTR) szError, "%s failed; \nResult is %ld",

            lpszFunction, dwErrorCode);

        wsprintf((LPSTR) szCaption, "%s error", lpszFunction);

        MessageBox(hwnd, (LPSTR) szError, (LPSTR) szCaption, MB_OK);

        return TRUE;

    }

    /*

     * The following code performs error-handling when the

     * ERROR_EXTENDED_ERROR return value indicates that WNetGetLastError

     * can retrieve additional information.

     */

    else {

        dwWNetResult = WNetGetLastError(&dwLastError,

            (LPSTR) szDescription,  /* buffer for error description  */

            sizeof(szDescription),

            (LPSTR) szProvider,     /* buffer for provider name      */

            sizeof(szProvider));

        if(dwWNetResult != NO_ERROR) {

            wsprintf((LPSTR) szError,

                "WNetGetLastError failed; error %ld", dwWNetResult);

            MessageBox(hwnd, (LPSTR) szError,

                "WNetGetLastError", MB_OK);

            return FALSE;

        }

        wsprintf((LPSTR) szError,

            "%s failed with code %ld;\n%s",

            (LPSTR) szProvider, dwLastError, (LPSTR) szDescription);

        wsprintf((LPSTR) szCaption, "%s error", lpszFunction);

        MessageBox(hwnd, (LPSTR) szError, (LPSTR) szCaption, MB_OK);

        return TRUE;

    }

}


 Network Functions

Following are the functions used with networks.

Netbios
WNetAddConnection
WNetAddConnection2
WNetAddConnection3
WNetCancelConnection
WNetCancelConnection2
WNetCloseEnum
WNetConnectionDialog
WNetDisconnectDialog
WNetEnumResource
WNetGetConnection
WNetGetLastError
WNetGetUniversalName
WNetGetUser
WNetOpenEnum


  LAN Manager Functions

Overview of Windows Networking Functions

For OS/2®-based servers the Microsoft® LAN Manager functions provided much of the functionality required for a network operating system; this functionality was missing from the local operating system. The Microsoft® Windows NT™ operating system will provide this missing functionality in the base. However, in order to make the migration of existing 16-bit applications as easy as possible, it is necessary to still define 32-bit equivalents of some of the LAN Manager functions.

The Windows networking functions specified in this online help are designed to provide some of the API functionality that was available in LAN Manager 2.x. They are not the base Windows NT networking functions. Windows NT takes some of the functionality that was previously supplied by the networking software, and moves this into the base functions (such as error and audit logging, printing). Windows NT also provides a network-independent set of network functions (the WNet functions) that allow network functions to work across different network vendors' products. If a base function or WNet function exists that could be used by your application, you should convert from the Windows networking function to the public Windows NT equivalent. There are at least three reasons to make the change now:

1.	The WNet functions are network independent, while the Windows networking functions only work on LAN Manager networks.

2.	Some of the Windows networking functions specified in this document may not be supported in future releases of Windows NT if they have been superseded by base functions or WNet functions. (Of course Microsoft does not plan to remove specific Windows networking functions unless equivalent or better functionality is available from other functions.)

3.	The Windows networking functions may not be supported on some other future Microsoft platforms, since they are not part of the Microsoft® Win32® application programming interface (API).

In this documentation, equivalent Win32 functions will be listed that could be used in place of the Windows networking function. If at all possible, this is the function that your application should use.

This documentation assumes that you are familiar with the existing set of 16-bit LAN Manager functions. The 32-bit widening of the API data structures is specified here, but the description of the functionality for each field is not covered unless the functionality has changed from that specified in the LAN Manager 2.x Programmer's Reference.


  API Buffers

The RPC run times will allocate the buffers required to remote the APIs. This is a requirement for both efficiency and interoperability. Using the RPC run times to allocate the API transmission buffers results in the two significant differences between a LAN Manager 2.x API and windows networking function.

•	For a set type function (data to the server) the function caller specifies a buffer containing the information structure relevant to the function level but does not specify the buffer length.

•	For a get type function (data returned from the server) the caller does not pre-allocate a buffer for the return information. The caller passes a LPBYTE * to the function on input. On successful return the buffer pointer will contain a pointer to a buffer containing the return information. When the caller has finished processing the returned information NetApiBufferFree must be called. This simplifies the calling code, because the caller does not need to guess at the size of the buffer required and will not need to resize and reissue the function as was the case with the LAN Manager 2.x functions.


  API Data Alignment

All data structures specified for the Windows networking functions will be 32-bit word aligned. The base size for an API structure element will be a DWORD.


  Enumeration Buffer Lengths

Enumeration functions will take an advisory maximum data length parameter, prefmaxlen, which allows a control on the number of bytes returned from an enumeration call. The prefered length is specified in units of 8-bit bytes. The actual function may return more than the prefered maximum length.

A Windows networking function enumeration call will not return partial entries.


  Parameter Error Reporting

Add and SetInfo functions will return an index for a parameter in error. The caller may pass a NULL pointer for the parm_err parameter indicating that the field should not be set by the function. For remoted functions to downlevel servers this field will be returned as PARM_ERROR_UNKNOWN by the RpcXlate conversion layer.


  Parmnum for SetInfo

To reduce the number of RPC interfaces we need for each SetInfo function, there will be no Parmnum parameter for the 32-bit SetInfo functions. Instead, the fields that can be set in the information structures will be set using additional infolevels. Although this will increase the number of information levels for a specified function, it will be easier to program to them. In an attempt to keep the mapping to and from downlevel calls simple, the new information levels will be easily mapped to the old parmnum values. By subtracting a specific number like PARMNUM_BASE_INFOLEVEL (whose value will be 1000).


  Parmnum for GetInfo

There will be no addition of a parmnum field for the GetInfo function.


  Embedded Strings

Windows networking function info structures will not contain embedded strings. This improves the alignability of the info structures and allows for OEM flexibility in the core functions. This does not change the feel of the LAN Manager 2.x functions that support string pointers. Code porting merely requires a pointer assignment rather than a string copy.

Any API information field that is returned in an enumeration call that can be subsequently used as a key for a GetInfo call is guaranteed to be present in the enumeration buffer. If the variable length information string that would specify the key field value will not fit then the entire fixed length structure for the entry is not returned. Other variable-length fields will be returned as a NULL pointer for the case where the string will not fit as with LAN Manager 2.x.


  Enumeration Resume Handles

Enumeration resume handles will be identifiers for the actual resume key contained in the instance data for the function. This is required for security, interoperabilty and to simplify the caller code for the function.

If a NULL is passed for the pointer to the resume handle, then no handle is stored and the ennumeration search cannot be continued. This is useful in cases where the application does not want to enumerate all the items.

If an error is returned from an enumeration call, the resume handle must be treated as invalid and not used for any subsequent enumeration calls. For example, the enumeration should be restarted from the beginning.


  User-Specific Information

The LAN Manager 2.x functions assumed that there would only be one user per computer. Therefore, some functions have that assumption built in, such as the NetSession functions. Since this assumption is not valid on Windows NT, the functions have had to be modified to take a user name as an additional parameter in order to be able to uniquely identify the information being queried or set.


  Enumeration Functions

The enumeration functions all return the number of entries read, the total entries that could have been returned if the buffer was big enough, a buffer with the entries, and a return code. The following table details what an application can expect for the various parameters (M is less than N):

Condition	entriesread	totalentries	buffer	returncode
No entries	0	0	NULL	SUCCESS
>= 1 entry	N	N	NOT NULL	SUCCESS
>= 1 entry	M	N	NOT NULL ERROR_MORE_DATA
Failure	?	?	?	Error Code
The caller must first examine the returned status before proceeding to examine any of the other parameters for data.

Note that "totalentries" is the total number of entries that would have been returned if the return buffer was big enough. For example, the total number of entries that were available for entries, using the current resume handle, if any, when the function was called. The one exception to this occurs in the NetUserEnum function when receiving data from a downlevel (OS/2 LANMAN) computer. In this case, the total entries always reflects the total number of entries in the database, no matter where it is in the resume sequence.


  SetInfo Functions

All the SetInfo functions take a structure that contains the new information to be set. If any of the pointer fields in the structure are NULL pointers, then the corresponding field is not changed by the call. This is consistent with LAN Manager 2.x functionality.

In addition, the information levels that allow GUEST access to query information do not allow callers with GUEST access to set the fields. For example, a caller with GUEST that calls the SetInfo function will probably get an error back from the SetInfo call.


  Windows Networking Functions

Function Status

Windows networking functions will use the LAN Manager 2.x error reporting convention. For example, a successful function call returns 0, a nonzero return code indicates an error in the range of the LAN Manager 2.x API/OS2 errors.

An extended error range will be added for Windows NT specific errors.

Since the Windows networking functions will use RPC, the API error definition will also be extended to include RPC error codes.


  RPC Buffer Allocation Errors

Since the RPC run time will allocate memory for send and receive buffers, the function should expect to see RPC allocation errors. In the event of an RPC allocation error, a resumable API handle is invalidated. This is a requirement since resumable functions are not rewindable.


  Obsolete Information Fields

Many of the information fields in the core information structures will be obsolete in the Windows NT service implementation. These fields will remain in the information structure for compatibility with 16-bit versions of Windows and will be returned with an intelligent default on Windows NT systems.


  NLS Support

There are only Unicode versions of the Windows networking functions. If you use these functions, you MUST define Unicode in your source file before including any of the LM include files.


  Windows Networking Function Definitions

The Windows networking functions are 'stdcall' calling convention functions that return a DWORD API status:

#define NET_API_STATUS DWORD

#define NET_API_FUNCTION __stdcall


  Buffer Manipulation Functions

For remotable functions that return information to the caller, the RPC run time will allocate the buffer containing the return information. When the caller has finished processing the returned information, NetApiBufferFree must be called. Additional buffer manipulation functions are also supported.

The buffer manipulation functions are:

NetApiBufferAllocate

NetApiBufferFree

NetApiBufferReallocate

NetApiBufferSize


  Service Functions

Note  A complete set of service functions are provided in the Win32 API. These should be used in place of the NetService functions, unless you have a requirement to control services on a downlevel server. For more details, see Services.

Service functions control services. A service is an application that an administrator can control using the Service Controller interfaces.

Services allow administrators to control applications on the network and maintain the integrity of users' data. On a typical network, applications are shared by many users. If an administrator terminates an application running on a server, a user who has not finished working with that application can lose important data. When an application is implemented as a service, the service controller checks the status before changing the state of the service. Windows NT Networking provides several standard services, such as the Workstation, Server, and Messenger services.

A service can be started using the service functions. At startup time, the service defines whether it can be stopped, paused, and continued.

NetServiceControl controls the operations of network services, and it can provide time hints to controlling applications. NetServiceEnum retrieves information about all started services. NetServiceGetInfo retrieves information about a particular started service. NetServiceInstall starts a network service. NetServiceStatus sets status and code information for a network service.

The service functions provide service information at three levels:

typedef struct _SERVICE_INFO_0 {
LPWSTR	svci0_name;	/* service name */
} SERVICE_INFO_0, *PSERVICE_INFO_0, *LPSERVICE_INFO_0;

typedef struct _SERVICE_INFO_1 {
LPWSTR	svci1_name;
DWORD	svci1_status;
DWORD	svci1_code;
DWORD	svci1_pid;
} SERVICE_INFO_1, *PSERVICE_INFO_1, *LPSERVICE_INFO_1;

typedef struct _SERVICE_INFO_2 {
LPWSTR	svci2_name;
DWORD	svci2_status;
DWORD	svci2_code;
DWORD	svci2_pid;
LPWSTR	svci2_text;

DWORD	svci2_specific_error;
} SERVICE_INFO_2, *PSERVICE_INFO_2, *LPSERVICE_INFO_2;

The service functions are:

NetServiceControl

NetServiceEnum

NetServiceGetInfo

NetServiceInstall


  Server Functions

Server functions perform administrative tasks on a local or remote server. Any user or application with admin group membership on a local or remote server can perform administrative tasks on that server to control its operation, user access, and resource sharing. The low-level parameters that affect a server's operation can be examined and modified by calling NetServerGetInfo and NetServerSetInfo.

The LAN Manager 2.x server API included several fields that logically belong to other LAN Manager services and core Windows NT components. For this reason the server information levels available in LAN Manager 2.x are no longer available in Windows networking functions. The server specific information is available in 3 levels starting at base level 100.


  Server System Information

Level 100 available with guest access:

typedef struct _SERVER_INFO_100 {
DWORD	sv100_platform_id;
LPWSTR	sv100_name;
} SERVER_INFO_100, *PSERVER_INFO_100, *LPSERVER_INFO_100;

Level 101 available with User access:

typedef struct _SERVER_INFO_101 {
DWORD	sv101_platform_id;
LPWSTR	sv101_name;
DWORD	sv101_version_major;
DWORD	sv101_version_minor;
DWORD	sv101_type;
LPWSTR	sv101_comment;
} SERVER_INFO_101, *PSERVER_INFO_101, *LPSERVER_INFO_101;

Level 102 available with Admin access:

typedef struct SERVER_INFO_102 {
DWORD	sv102_platform_id;
LPWSTR	sv102_name;
DWORD	sv102_version_major;
DWORD	sv102_version_minor;
DWORD	sv102_type;
LPWSTR	sv102_comment;
DWORD	sv102_users;
DWORD	sv102_disc;
BOOL	sv102_hidden;
DWORD	sv102_announce;
DWORD	sv102_anndelta;
LPWSTR	sv102_userpath;
} SERVER_INFO_102, *PSERVER_INFO_102, *LPSERVER_INFO_102;

Level 400-499 OS/2 Server information.

Level 402 available with Admin access:

typedef struct _SERVER_INFO_402 {
DWORD	sv402_ulist_mtime;
DWORD	sv402_glist_mtime;
DWORD	sv402_alist_mtime;
LPWSTR	sv402_alerts;
DWORD	sv402_security;
DWORD	sv402_numadmin;
DWORD	sv402_lanmask;
LPWSTR	sv402_guestacct;
DWORD	sv402_chdevs;
DWORD	sv402_chdevq;
DWORD	sv402_chdevjobs;
DWORD	sv402_connections;
DWORD	sv402_shares;
DWORD	sv402_openfiles;
DWORD	sv402_sessopens;
DWORD	sv402_sessvcs;
DWORD	sv402_sessreqs;
DWORD	sv402_opensearch;
DWORD	sv402_activelocks;
DWORD	sv402_numreqbuf;
DWORD	sv402_sizreqbuf;
DWORD	sv402_numbigbuf;
DWORD	sv402_numfiletasks;
DWORD	sv402_alertsched;
DWORD	sv402_erroralert;
DWORD	sv402_logonalert;
DWORD	sv402_accessalert;
DWORD	sv402_diskalert;
DWORD	sv402_netioalert;
DWORD	sv402_maxauditsz;
LPWSTR	sv402_srvheuristics;
} SERVER_INFO_402, *PSERVER_INFO_402, *LPSERVER_INFO_402;

Level 403 available with Admin access:

typedef struct _SERVER_INFO_403 {
DWORD	sv403_ulist_mtime;
DWORD	sv403_glist_mtime;
DWORD	sv403_alist_mtime;
LPWSTR	sv403_alerts;
DWORD	sv403_security;
DWORD	sv403_numadmin;
DWORD	sv403_lanmask;
LPWSTR	sv403_guestacct;
DWORD	sv403_chdevs;
DWORD	sv403_chdevq;
DWORD	sv403_chdevjobs;
DWORD	sv403_connections;
DWORD	sv403_shares;
DWORD	sv403_openfiles;
DWORD	sv403_sessopens;
DWORD	sv403_sessvcs;
DWORD	sv403_sessreqs;
DWORD	sv403_opensearch;
DWORD	sv403_activelocks;
DWORD	sv403_numreqbuf;
DWORD	sv403_sizreqbuf;
DWORD	sv403_numbigbuf;
DWORD	sv403_numfiletasks;
DWORD	sv403_alertsched;
DWORD	sv403_erroralert;
DWORD	sv403_logonalert;
DWORD	sv403_accessalert;
DWORD	sv403_diskalert;
DWORD	sv403_netioalert;
DWORD	sv403_maxauditsz;
LPWSTR	sv403_srvheuristics;
DWORD	sv403_auditedevents;
DWORD	sv403_autoprofile;
LPWSTR	sv403_autopath;
} SERVER_INFO_403, *PSERVER_INFO_403, *LPSERVER_INFO_403;

Level 500-599 Windows NT Server information.

Level 502 available with Admin access:

typedef struct _SERVER_INFO_502 {
DWORD	sv502_sessopens;
DWORD	sv502_sessvcs;
DWORD	sv502_opensearch;
DWORD	sv502_sizreqbuf;
DWORD	sv502_initworkitems;
DWORD	sv502_maxworkitems;
DWORD	sv502_rawworkitems;
DWORD	sv502_irpstacksize;
DWORD	sv502_maxrawbuflen;
DWORD	sv502_sessusers;
DWORD	sv502_sessconns;
DWORD	sv502_maxpagedmemoryusage;
DWORD	sv502_maxnonpagedmemoryusage;
BOOL	sv502_enablesoftcompat;
BOOL	sv502_enableforcedlogoff;
BOOL	sv502_timesource;
BOOL	sv502_acceptdownlevelapis;
BOOL	sv502_lmannounce;
} SERVER_INFO_502, *PSERVER_INFO_502, *LPSERVER_INFO_502;

Level 503 available with Admin access:

typedef struct _SERVER_INFO_503 {
DWORD	sv503_sessopens;
DWORD	sv503_sessvcs;
DWORD	sv503_opensearch;
DWORD	sv503_sizreqbuf;
DWORD	sv503_initworkitems;
DWORD	sv503_maxworkitems;
DWORD	sv503_rawworkitems;
DWORD	sv503_irpstacksize;
DWORD	sv503_maxrawbuflen;
DWORD	sv503_sessusers;
DWORD	sv503_sessconns;
DWORD	sv503_maxpagedmemoryusage;
DWORD	sv503_maxnonpagedmemoryusage;
BOOL	sv503_enablesoftcompat;
BOOL	sv503_enableforcedlogoff;
BOOL	sv503_timesource;
BOOL	sv503_acceptdownlevelapis;
BOOL	sv503_lmannounce;
LPTSTR	sv503_domain;
DWORD	sv503_maxcopyreadlen;
DWORD	sv503_maxcopywritelen;
DWORD	sv503_minkeepsearch;
DWORD	sv503_maxkeepsearch;
DWORD	sv503_minkeepcomplsearch;
DWORD	sv503_maxkeepcomplsearch;
DWORD	sv503_threadcountadd;
DWORD	sv503_numblockthreads;
DWORD	sv503_scavtimeout;
DWORD	sv503_minrcvqueue;
DWORD	sv503_minfreeworkitems;
DWORD	sv503_xactmemsize;
DWORD	sv503_threadpriority;
DWORD	sv503_maxmpxct;
DWORD	sv503_oplockbreakwait;
DWORD	sv503_oplockbreakresponsewait;
BOOL	sv503_enableoplocks;
BOOL	sv503_enableoplockforceclose;
BOOL	sv503_enablefcbopens;
BOOL	sv503_enableraw;
BOOL	sv503_enabledpc;
BOOL	sv503_enablemdlio;
BOOL	sv503_enablefastio;
} SERVER_INFO_503, *PSERVER_INFO_503, *LPSERVER_INFO_503;

The following information levels are only valid for NetServerSetInfo and replace the older way of passing in a Parmnum to set a specific field.

The following are supported on downlevel systems (for example, LAN Manager 2.x) as well:

typedef struct _SERVER_INFO_1005 {
DWORD	sv1005_comment;
} SERVER_INFO_1005, *PSERVER_INFO_1005, *LPSERVER_INFO_1005;

typedef struct _SERVER_INFO_1107 {
DWORD	sv1107_users;
} SERVER_INFO_1107, *PSERVER_INFO_1107, *LPSERVER_INFO_1107;

typedef struct _SERVER_INFO_1010 {
DWORD	sv1010_disc;
} SERVER_INFO_1010, *PSERVER_INFO_1010, *LPSERVER_INFO_1010;

typedef struct _SERVER_INFO_1016 {
BOOL	sv1016_hidden;
} SERVER_INFO_1016, *PSERVER_INFO_1016, *LPSERVER_INFO_1016;

typedef struct _SERVER_INFO_1017 {
DWORD	sv1017_announce;
} SERVER_INFO_1017, *PSERVER_INFO_1017, *LPSERVER_INFO_1017;

typedef struct _SERVER_INFO_1018 {
DWORD	sv1018_anndelta;
} SERVER_INFO_1018, *PSERVER_INFO_1018, *LPSERVER_INFO_1018;

typedef struct _SERVER_INFO_1037 {
DWORD	sv1037_alertsched;
} SERVER_INFO_1037, *PSERVER_INFO_1037, *LPSERVER_INFO_1037;

typedef struct _SERVER_INFO_1038 {
DWORD	sv1038_erroralert;
} SERVER_INFO_1038, *PSERVER_INFO_1038, *LPSERVER_INFO_1038;

typedef struct _SERVER_INFO_1039 {
DWORD	sv1039_logonalert;
} SERVER_INFO_1039, *PSERVER_INFO_1039, *LPSERVER_INFO_1039;

typedef struct _SERVER_INFO_1040 {
DWORD	sv1040_accessalert;
} SERVER_INFO_1040, *PSERVER_INFO_1040, *LPSERVER_INFO_1040;

typedef struct _SERVER_INFO_1041 {
DWORD	sv1041_diskalert;
} SERVER_INFO_1041, *PSERVER_INFO_1041, *LPSERVER_INFO_1041;

typedef struct _SERVER_INFO_1042 {
DWORD	sv1042_netioalert;
} SERVER_INFO_1042, *PSERVER_INFO_1042, *LPSERVER_INFO_1042;

typedef struct _SERVER_INFO_1043 {
DWORD	sv1043_maxauditsz;
} SERVER_INFO_1043, *PSERVER_INFO_1043, *LPSERVER_INFO_1043;

The following do not do anything on downlevel systems (for example, LAN Manager 2.x) since they cannot be modified on the fly on those systems:

typedef struct _SERVER_INFO_1009 {
DWORD	sv1009_users;
} SERVER_INFO_1009, *PSERVER_INFO_1009, *LPSERVER_INFO_1009;

typedef struct _SERVER_INFO_1021 {
LPWSTR	sv1021_userpath;
} SERVER_INFO_1021, *PSERVER_INFO_1021, *LPSERVER_INFO_1021;

typedef struct _SERVER_INFO_1022 {
DWORD	sv1022_chdevs;
} SERVER_INFO_1022, *PSERVER_INFO_1022, *LPSERVER_INFO_1022;

typedef struct _SERVER_INFO_1028 {
DWORD	sv1028_sessopens;
} SERVER_INFO_1028, *PSERVER_INFO_1028, *LPSERVER_INFO_1028;

typedef struct _SERVER_INFO_1029 {
DWORD	sv1029_opensearch;
} SERVER_INFO_1029, *PSERVER_INFO_1029, *LPSERVER_INFO_1029;

The following are not supported on downlevel systems (for example, LAN Manager 2.x) since these are Windows NT − only fields:

typedef struct _SERVER_INFO_1001 {
DWORD	sv1001_maxworkitems;
} SERVER_INFO_1001, *PSERVER_INFO_1001, *LPSERVER_INFO_1001;

typedef struct _SERVER_INFO_1002 {
DWORD	sv1002_maxrawbuflen;
} SERVER_INFO_1002, *PSERVER_INFO_1002, *LPSERVER_INFO_1002;

typedef struct _SERVER_INFO_1003 {
DWORD	sv1003_sessusers;
} SERVER_INFO_1003, *PSERVER_INFO_1003, *LPSERVER_INFO_1003;

typedef struct _SERVER_INFO_1004 {
DWORD	sv1004_sesscons;
} SERVER_INFO_1004, *PSERVER_INFO_1004, *LPSERVER_INFO_1004;

typedef struct _SERVER_INFO_1006 {
DWORD	sv1006_enablesoftcompat;
} SERVER_INFO_1006, *PSERVER_INFO_1006, *LPSERVER_INFO_1006;

For NetServerSetInfo, parmnum values refer to the fields in the _SERVER_INFO structures as follows. These values are used when indicating an error in a specific parameter via parm_err.

parmnum value	Field in server_info struct
SV_NAME_PARMNUM	sv_name
SV_VERSION_MAJOR_PARMNUM	sv_version_major
SV_VERSION_MINOR_PARMNUM	sv_version_minor
SV_TYPE_PARMNUM	sv_type
SV_COMMENT_PARMNUM	sv_comment
SV_USERS_PARMNUM	sv_users
SV_DISC_PARMNUM	sv_disc
SV_HIDDEN_PARMNUM	sv_hidden
SV_ANNOUNCE_PARMNUM	sv_announce
SV_ANNDELTA_PARMNUM	sv_anndelta
SV_USERPATH_PARMNUM	sv_userpath
SV_ULIST_MTIME_PARMNUM	sv_ulist_mtime
SV_GLIST_MTIME_PARMNUM	sv_glist_mtime
SV_ALIST_MTIME_PARMNUM	sv_alist_mtime
SV_ALERTS_PARMNUM	sv_alerts
SV_SECURITY_PARMNUM	sv_security
SV_NUMADMIN_PARMNUM	sv_numadmin
SV_LANMASK_PARMNUM	sv_lanmask
SV_GUESTACC_PARMNUM	sv_guestacc
SV_CHDEVS_PARMNUM	sv_chdevs
SV_CHDEVQ_PARMNUM	sv_chdevq
SV_CHDEVJOBS_PARMNUM	sv_chdevjobs
SV_CONNECTIONS_PARMNUM	sv_connections
SV_SHARES_PARMNUM	sv_shares
SV_OPENFILES_PARMNUM	sv_openfiles
SV_SESSOPENS_PARMNUM	sv_sessopens
SV_SESSVCS_PARMNUM	sv_sessvcs
SV_SESSREQS_PARMNUM	sv_sessreqs
SV_OPENSEARCH_PARMNUM	sv_opensearch
SV_ACTIVELOCKS_PARMNUM	sv_activelocks
SV_NUMREQBUF_PARMNUM	sv_numreqbuf
SV_SIZREQBUF_PARMNUM	sv_sizreqbuf
SV_NUMBIGBUF_PARMNUM	sv_numbigbuf
SV_NUMFILETASKS_PARMNUM	sv_numfiletasks
SV_ALERTSCHED_PARMNUM	sv_alertsched
SV_ERRORALERT_PARMNUM	sv_erroralert
SV_LOGONALERT_PARMNUM	sv_logonalert
SV_ACCESSALERT_PARMNUM	sv_accessalert
SV_DISKALERT_PARMNUM	sv_diskalert
SV_NETIOALERT_PARMNUM	sv_netioalert
SV_MAXAUDITSZ_PARMNUM	sv_maxauditsz
SV_SRVHEURISTICS_PARMNUM	sv_srvheuristics
SV_AUDITEDEVENTS_PARMNUM	sv_auditedevents
SV_AUTOPROFILE_PARMNUM	sv_autoprofile
SV_MAXWORKITEMS_PARMNUM	sv_maxworkitems
SV_RAWWORKITEMS_PARMNUM	sv_rawworkitems
SV_IRPSTACKSIZE_PARMNUM	sv_irpstacksize
SV_SESSUSERS_PARMNUM	sv_sessusers
SV_SESSCONNS_PARMNUM	sv_sessconns
SV_MAXNONPAGEDMEMORYUSAGE_PARMNUM	sv_maxnonpagedmemoryusage
SV_MAXPAGEDMEMORYUSAGE_PARMNUM	sv_maxpagedmmeoryusage
SV_ENABLEOFTCOMPAT_PARMNUM	sv_enablesoftcompat
The server functions are:

NetServerGetInfo

NetServerSetInfo.


  Workstation and Workstation User Functions

Workstation functions perform administrative tasks on a local or remote workstation. Any user or application with admin group membership on a local or remote server can perform administrative tasks on that workstation to control its operation, user access, and resource sharing. The low-level parameters that affect a workstation's operation can be examined and modified by calling NetWkstaGetInfo and NetWkstaSetInfo.

The workstation API data structures are restructured from those of LAN Man 2.x to allow the information to be grouped by type and security accesses. The LAN Manager 2.x workstation information format is discontinued due to the following problems:

•	The base level (0 and 1) were not grouped by accessibility such that a non superset level (level 10) was required to allow guest access to the information.

•	Platform specific implementation information was included in the base levels such that every platform had to return all information including a default for non-relevant fields. This grew the size of the information structures unneccessarily, making the function cumbersome to use.

The workstation functions allow access to two discrete groups of workstation information:

•	System information.

•	Platform specific information (Windows NT, OS/2, MS-DOS, and so on)

The Workstation User functions allow access to user-specific information. The user-specific information is separated from the workstation information because there can be more than one user on a workstation.

Within each group the fields are categorized by security access such that the guest accessible fields are a subset of the user accessible fields that are a subset of the admin accessible fields.

The system information structure contains a platform base number that identifies the levels and format of the platform specific information structures.

The workstation function information structures are:

System Information −

Level 100 available with guest access −

typedef struct _WKSTA_INFO_100 {
DWORD	wki100_platform_id;
LPWSTR	wki100_computername;
LPWSTR	wki100_langroup;
DWORD	wki100_ver_major;
DWORD	wki100_ver_minor;
} WKSTA_INFO_100, *PWKSTA_INFO_100, *LPWKSTA_INFO_100;

Level 101 available with User access:

typedef struct _WKSTA_INFO_101 {
DWORD	wki101_platform_id;
LPWSTR	wki101_computername;
LPWSTR	wki101_langroup;
DWORD	wki101_ver_major;
DWORD	wki101_ver_minor;
LPWSTR	wki101_lanroot;
} WKSTA_INFO_101, *PWKSTA_INFO_101, *LPWKSTA_INFO_101;

Level 102 available with Admin access:

typedef struct _WKSTA_INFO_102 {
DWORD	wki102_platform_id;
LPWSTR	wki102_computername;
LPWSTR	wki102_langroup;
DWORD	wki102_ver_major;
DWORD	wki102_ver_minor;
LPWSTR	wki102_lanroot;
DWORD	wki102_logged_on_users;
} WKSTA_INFO_102, *PWKSTA_INFO_102, *LPWKSTA_INFO_102;

Platform Specific Information

Level 300-399 MS-DOS Workstation information.

Level 300 available with guest access:

Level 302 available with Admin access:

typedef struct _WKSTA_INFO_302 {
DWORD	wki302_char_wait;
DWORD	wki302_collection_time;
DWORD	wki302_maximum_collection_count;
DWORD	wki302_keep_conn;
DWORD	wki302_keep_search;
DWORD	wki302_max_cmds;
DWORD	wki302_num_work_buf;
DWORD	wki302_siz_work_buf;
DWORD	wki302_max_wrk_cache;
DWORD	wki302_sess_timeout;
DWORD	wki302_siz_error;
DWORD	wki302_num_alerts;
DWORD	wki302_num_services;
DWORD	wki302_errlog_sz;
DWORD	wki302_print_buf_time;
DWORD	wki302_num_char_buf;
DWORD	wki302_siz_char_buf;
LPWSTR	wki302_wrk_heuristics;
DWORD	wki302_mailslots;
DWORD	wki302_num_dgram_buf;
} WKSTA_INFO_302, *PWKSTA_INFO_302, *LPWKSTA_INFO_302;

Level 400-499 OS/2 Workstation information.

Level 402 available with Admin access:

typedef struct _WKSTA_INFO_402 {
DWORD	wki402_char_wait;
DWORD	wki402_collection_time;
DWORD	wki402_maximum_collection_count;
DWORD	wki402_keep_conn;
DWORD	wki402_keep_search;
DWORD	wki402_max_cmds;
DWORD	wki402_num_work_buf;
DWORD	wki402_siz_work_buf;
DWORD	wki402_max_wrk_cache;
DWORD	wki402_sess_timeout;
DWORD	wki402_siz_error;
DWORD	wki402_num_alerts;
DWORD	wki402_num_services;
DWORD	wki402_errlog_sz;
DWORD	wki402_print_buf_time;
DWORD	wki402_num_char_buf;
DWORD	wki402_siz_char_buf;
LPWSTR	wki402_wrk_heuristics;
DWORD	wki402_mailslots;
DWORD	wki402_num_dgram_buf;
DWORD	wki402_max_threads;
} WKSTA_INFO_402, *PWKSTA_INFO_402, *LPWKSTA_INFO_402;

Level 500-599 Windows NT Workstation information.

Level 502 available with Admin access:

typedef struct _WKSTA_INFO_502 {
DWORD	wki502_char_wait;
DWORD	wki502_collection_time;
DWORD	wki502_maximum_collection_count;
DWORD	wki502_keep_conn;
DWORD	wki502_max_cmds;
DWORD	wki502_sess_timeout;
DWORD	wki502_siz_char_buf;
DWORD	wki502_max_threads;
DWORD	wki502_lock_quota;
DWORD	wki502_lock_increment;
DWORD	wki502_lock_maximum;
DWORD	wki502_pipe_increment;
DWORD	wki502_pipe_maximum;
DWORD	wki502_cache_file_timeout;
DWORD	wki502_dormant_file_limit;
DWORD	wki502_read_ahead_throughput;
DWORD	wki502_num_mailslot_buffers;
DWORD	wki502_num_srv_announce_buffers;
DWORD	wki502_dgreceiver_threads;
BOOL	wki502_use_opportunistic_locking;
BOOL	wki502_use_unlock_behind;
BOOL	wki502_use_close_behind;
BOOL	wki502_buf_named_pipes;
BOOL	wki502_use_lock_read_unlock;
BOOL	wki502_utilize_nt_caching;
BOOL	wki502_use_raw_read;
BOOL	wki502_use_raw_write;
BOOL	wki502_use_write_raw_data;
BOOL	wki502_use_encryption;
BOOL	wki502_buf_files_deny_write;
BOOL	wki502_buf_read_only_files;
BOOL	wki502_force_core_create_mode;
BOOL	wki502_use_512_byte_max_transfer;
} WKSTA_INFO_502, *PWKSTA_INFO_502, *LPWKSTA_INFO_502;

This format of workstation information allows for a more logical future extension. When new information is to be added to any set of guest,user and admin information a new set of levels is created to include the current infromation plus the new information.

The following information levels are only valid for NetWkstaSetInfo and replace the older way of passing in a Parmnum to set a specific field.

The following are supported on downlevel systems (for example, LAN Manager 2.x) as well:

typedef struct _WKSTA_INFO_1010 {
DWORD	wki1010_char_wait;
} WKSTA_INFO_1010, *PWKSTA_INFO_1010, *LPWKSTA_INFO_1010;

typedef struct _WKSTA_INFO_1011 {
DWORD	wki1011_collection_time;
} WKSTA_INFO_1011, *PWKSTA_INFO_1011, *LPWKSTA_INFO_1011;

typedef struct _WKSTA_INFO_1012 {
DWORD	wki1012_maximum_collection_count;
} WKSTA_INFO_1012, *PWKSTA_INFO_1012, *LPWKSTA_INFO_1012;

typedef struct _WKSTA_INFO_1027 {
DWORD	wki1027_errlog_sz;
} WKSTA_INFO_1027, *PWKSTA_INFO_1027, *LPWKSTA_INFO_1027;

typedef struct _WKSTA_INFO_1028 {
DWORD	wki1028_print_buf_time;
} WKSTA_INFO_1028, *PWKSTA_INFO_1028, *LPWKSTA_INFO_1028;

typedef struct _WKSTA_INFO_1032 {
DWORD	wki1032_wrk_heuristics;
} WKSTA_INFO_1032, *PWKSTA_INFO_1032, *LPWKSTA_INFO_1032;

typedef struct _WKSTA_INFO_1035 {
LPWSTR	wki1035_oth_domains;
} WKSTA_INFO_1035, *PWKSTA_INFO_1035, *LPWKSTA_INFO_1035;

The following do nothing on downlevel systems (for example, LAN Manager 2.x) since these fields cannot be set on them:

typedef struct _WKSTA_INFO_1013 {
DWORD	wki1013_keep_conn;
} WKSTA_INFO_1013, *PWKSTA_INFO_1013, *LPWKSTA_INFO_1013;

typedef struct _WKSTA_INFO_1018 {
DWORD	wki1018_sess_timeout;
} WKSTA_INFO_1018, *PWKSTA_INFO_1018, *LPWKSTA_INFO_1018;

typedef struct _WKSTA_INFO_1023 {
DWORD	wki1023_siz_char_buf;
} WKSTA_INFO_1023, *PWKSTA_INFO_1023, *LPWKSTA_INFO_1023;

typedef struct _WKSTA_INFO_1033 {
DWORD	wki1033_max_threads;
} WKSTA_INFO_1033, *PWKSTA_INFO_1033, *LPWKSTA_INFO_1033;

The following are not supported on downlevel systems (for example, LAN Manager 2.x):

typedef struct _WKSTA_INFO_1041 {
DWORD	wki1041_lock_quota;
} WKSTA_INFO_1041, *PWKSTA_INFO_1041, *LPWKSTA_INFO_1041;

typedef struct _WKSTA_INFO_1042 {
DWORD	wki1042_lock_increment;
} WKSTA_INFO_1042, *PWKSTA_INFO_1042, *LPWKSTA_INFO_1042;

typedef struct _WKSTA_INFO_1043 {
DWORD	wki1043_lock_maximum;
} WKSTA_INFO_1043, *PWKSTA_INFO_1043, *LPWKSTA_INFO_1043;

typedef struct _WKSTA_INFO_1044 {
DWORD	wki1044_pipe_increment;
} WKSTA_INFO_1044, *PWKSTA_INFO_1044, *LPWKSTA_INFO_1044;

typedef struct _WKSTA_INFO_1045 {
DWORD	wki1045_pipe_maximum;
} WKSTA_INFO_1045, *PWKSTA_INFO_1045, *LPWKSTA_INFO_1045;

typedef struct _WKSTA_INFO_1046 {
DWORD	wki1046_dormant_file_limit;
} WKSTA_INFO_1046, *PWKSTA_INFO_1046, *LPWKSTA_INFO_1046;

typedef struct _WKSTA_INFO_1047 {
DWORD	wki1047_cache_file_timeout;
} WKSTA_INFO_1047, *PWKSTA_INFO_1047, *LPWKSTA_INFO_1047;

typedef struct _WKSTA_INFO_1048 {
BOOL	wki1048_use_opportunity_locking;
} WKSTA_INFO_1048, *PWKSTA_INFO_1048, *LPWKSTA_INFO_1048;

typedef struct _WKSTA_INFO_1049 {
BOOL	wki1049_use_unlock_behind;
} WKSTA_INFO_1049, *PWKSTA_INFO_1049, *LPWKSTA_INFO_1049;

typedef struct _WKSTA_INFO_1050 {
BOOL	wki1050_use_close_behind;
} WKSTA_INFO_1050, *PWKSTA_INFO_1050, *LPWKSTA_INFO_1050;

typedef struct _WKSTA_INFO_1051 {
BOOL	wki1051_buf_named_pipes;
} WKSTA_INFO_1051, *PWKSTA_INFO_1051, *LPWKSTA_INFO_1051;

typedef struct _WKSTA_INFO_1052 {
BOOL	wki1052_use_lock_read_unlock;
} WKSTA_INFO_1052, *PWKSTA_INFO_1052, *LPWKSTA_INFO_1052;

typedef struct _WKSTA_INFO_1053 {
BOOL	wki1053_utilize_nt_caching;
} WKSTA_INFO_1053, *PWKSTA_INFO_1053, *LPWKSTA_INFO_1053;

typedef struct _WKSTA_INFO_1054 {
BOOL	wki1054_use_raw_read;
} WKSTA_INFO_1054, *PWKSTA_INFO_1054, *LPWKSTA_INFO_1054;

typedef struct _WKSTA_INFO_1055 {
BOOL	wki1055_use_raw_write;
} WKSTA_INFO_1055, *PWKSTA_INFO_1055, *LPWKSTA_INFO_1055;

typedef struct _WKSTA_INFO_1056 {
BOOL	wki1056_use_write_raw_data;
} WKSTA_INFO_1056, *PWKSTA_INFO_1056, *LPWKSTA_INFO_1056;

typedef struct _WKSTA_INFO_1057 {
BOOL	wki1057_use_encryption;
} WKSTA_INFO_1057, *PWKSTA_INFO_1057, *LPWKSTA_INFO_1057;

typedef struct _WKSTA_INFO_1058 {
BOOL	wki1058_buf_files_deny_write;
} WKSTA_INFO_1058, *PWKSTA_INFO_1058, *LPWKSTA_INFO_1058;

typedef struct _WKSTA_INFO_1059 {
BOOL	wki1059_buf_read_only_files;
} WKSTA_INFO_1059, *PWKSTA_INFO_1059, *LPWKSTA_INFO_1059;

typedef struct _WKSTA_INFO_1060 {
BOOL	wki1060_force_core_create_mode;
} WKSTA_INFO_1060, *PWKSTA_INFO_1060, *LPWKSTA_INFO_1060;

typedef struct _WKSTA_INFO_1061 {
BOOL	wki1061_use_512_byte_max_transfer;
} WKSTA_INFO_1061, *PWKSTA_INFO_1061, *LPWKSTA_INFO_1061;

typedef struct _WKSTA_INFO_1062 {
DWORD	wki1062_read_ahead_throughput;
} WKSTA_INFO_1062, *PWKSTA_INFO_1062, *LPWKSTA_INFO_1062;

The Workstation User function information structures are:

Level 0 and 1 available with User access:

typedef struct _WKSTA_USER_INFO_0 {
LPWSTR	wkui0_username;
} WKSTA_USER_INFO_0, *PWKSTA_USER_INFO_0, *LPWKSTA_USER_INFO_0;

typedef struct _WKSTA_USER_INFO_1 {
LPWSTR	wkui1_username;
LPWSTR	wkui1_logon_domain;
LPWSTR	wkui1_logon_server;

LPWSTR	wkui1_oth_domains;
} WKSTA_USER_INFO_1, *PWKSTA_USER_INFO_1, *LPWKSTA_USER_INFO_1;

typedef struct _WKSTA_USER_INFO_1101 {
LPTSTR	wkui1101_oth_domains;
} WKSTA_USER_INFO_1101, *PWKSTA_USER_INFO_1101,
 *LPWKSTA_USER_INFO_1101;

For NetWkstaSetInfo, parmnum values refer to the fields in the workstation info structure as follows. These values are used when indicating an error in a specific parameter via parm_err.

parmnum value	Field in wksta_info struct
WKSTA_PLATFORM_ID_PARMNUM	wki_platform_id
WKSTA_COMPUTERNAME_PARMNUM	wki_computername
WKSTA_LANGROUP_PARMNUM	wki_langroup
WKSTA_OTH_DOMAINS_PARMNUM	wki_oth_domains
WKSTA_VER_MAJOR_PARMNUM	wki_ver_major
WKSTA_VER_MINOR_PARMNUM	wki_ver_minor
WKSTA_LOGGED_ON_USERS_PARMNUM	wki_logged_on_users
WKSTA_LANROOT_PARMNUM	wki_lanroot
WKSTA_LOGON_DOMAIN_PARMNUM	wki_logon_domain
WKSTA_LOGON_SERVER_PARMNUM	wki_logon_server
WKSTA_CHARWAIT_PARMNUM	wki_char_wait
WKSTA_CHARTIME_PARMNUM	wki_collection_time
WKSTA_CHARCOUNT_PARMNUM	wki_maximum_collection_count
WKSTA_KEEPCONN_PARMNUM	wki_keep_conn
WKSTA_KEEPSEARCH_PARMNUM	wki_keep_search
WKSTA_MAXCMDS_PARMNUM	wki_max_cmds
WKSTA_NUMWORKBUF_PARMNUM	wki_num_work_buf
WKSTA_MAXWRKCACHE_PARMNUM	wki_max_wrk_cache
WKSTA_SESSTIMEOUT_PARMNUM	wki_sess_timeout
WKSTA_SIZERROR_PARMNUM	wki_siz_error
WKSTA_NUMALERTS_PRAMNUM	wki_num_alerts
WKSTA_NUMSERVICES_PARMNUM	wki_num_services
WKSTA_ERRLOGSZ_PARMNUM	wki_errlog_sz
WKSTA_PRINTBUFTIME_PARMNUM	wki_print_buf_time
WKSTA_NUMCHARBUF_PARMNUM	wki_num_char_buf
WKSTA_SIZCHARBUF_PARMNUM	wki_siz_char_buf
WKSTA_WRKHEURISTICS_PARMNUM	wki_wrk_heuristics
WKSTA_MAILSLOTS_PRAMNUM	wki_mailslots
WKSTA_MAXTHREADS_PARMNUM	wki_max_threads
WKSTA_SIZWORKBUF_PARMNUM	wki_siz_work_buf
WKSTA_DORMANTTIMEOUT_PARMNUM	wki_dormant_timeout
WKSTA_LOCKQUOTA_PARMNUM	wki_lock_quota
WKSTA_LOCKINCREMENT_PARMNUM	wki_lock_increment
WKSTA_LOCKMAXIMUM_PARMNUM	wki_lock_maximum
WKSTA_PIPEINCREMENT_PRAMNUM	wki_pipe_increment
WKSTA_PIPEMAXIMUM_PARMNUM	wki_pipe_maximum
WKSTA_RAWREADTHRESHOLD_PARMNUM	wki_raw_read_threshold
WKSTA_USEOPLOCKING_PARMNUM	wki_use_opportunistic_locking
WKSTA_USEOPBATCH_PARMNUM	wki_use_op_batch
WKSTA_USEUNLOCKBEHIND_PARMNUM	wki_use_unlock_behind
WKSTA_USECLOSEBEHIND_PARMNUM	wki_use_close_behind
WKSTA_BUFNAMEDPIPES_PARMNUM	wksta_buf_named_pipes
WKSTA_USELOCKANDREADANDUNLOCK _PARMNUM	wki_use_lock_and_read_and _unlock
WKSTA_UTILIZENTCACHING_PARMNUM	wki_utilize_nt_caching
WKSTA_USERAWREAD_PARMNUM	wki_use_raw_read
WKSTA_USEWRITERAWWITHDATA_PARMNUM	wki_use_write_raw_with_data
WKSTA_USEENCRYPTION_PARMNUM	wki_use_encryption
WKSTA_BUFFILESWITHDENYWRITE _PARMNUM	wki_buf_files_with_deny_write
WKSTA_BUFREADONLYFILES_PRAMNUM	wki_buf_read_only_files
WKSTA_FORCECORECREATEMODE_PARMNUM	wki_force_core_create_mode
WKSTA_USE512BYTESMAXTRANSFER _PARMNUM	wki_use_512_bytes_max_transfer
The workstation functions are:

NetWkstaGetInfo

NetWkstaSetInfo

The Workstation User functions are:

NetWkstaUserEnum

NetWkstaUserGetInfo

NetWkstaUserSetInfo


  Use Functions

Note  The WNetAddConnection2 and WNetCancelConnection2 functions should be used instead of the NetUse functions.

Use functions examine or control connections (uses) between workstations and servers. Connections are distinguished from sessions: a session is established the first time a workstation makes a connection to a shared resource on the server; all further connections between the workstation and the server are part of this same session until the session ends. Two types of connections can be made: device-name connections (which can only be explicit) and universal-naming convention (UNC) connections (which can be explicit or implicit).

Connections are made on a per-user basis. A connection made by a user is deleted when that user logs off. For this reason the NetUse functions are local only, since a connection set up by a remote user would not be accessible to any other users, even the user that was interactively logged onto that computer.

NetUseAdd creates a device-name connection or an explicit UNC connection. Implicit UNC connections are made by the function responsible for the connection.

NetUseAdd establishes an explicit connection between the local computer and a resource shared on a server by redirecting a local device name to the share name of a remote server resource (\\servername\sharename). Once a device-name connection is made, users or applications can use the remote resource by specifying the local device name. To establish an implicit UNC connection, an application passes the share name of a resource to any function that accepts UNC paths. The function accepts the UNC name and makes a connection to the specified share name. All further requests on this connection require the full share name.

NetUseDel ends a connection to a shared resource. NetUseEnum enumerates all current connections between the local computer and resources on remote servers. NetUseGetInfo returns information about a connection to a shared resource.

The use functions are available at three information levels.

typedef struct _USE_INFO_0 {
LPWSTR	ui0_local;
LPWSTR	ui0_remote;
} USE_INFO_0, *PUSE_INFO_0, *LPUSE_INFO_0;

typedef struct _USE_INFO_1 {
LPWSTR	ui1_local;
LPWSTR	ui1_remote;
LPWSTR	ui1_password;
DWORD	ui1_status;
DWORD	ui1_asg_type;
DWORD	ui1_refcount;
DWORD	ui1_usecount;
} USE_INFO_1, *PUSE_INFO_1, *LPUSE_INFO_1;

Information level 2 is not available if the function is remoted to a downlevel system — ERROR_NOT_SUPPORTED will be returned in that case.

typedef struct _USE_INFO_2 {
LPWSTR	ui2_local;
LPWSTR	ui2_remote;
LPWSTR	ui2_password;
DWORD	ui2_status;
DWORD	ui2_asg_type;
DWORD	ui2_refcount;
DWORD	ui2_usecount;
LPWSTR	ui2_username;

LPWSTR	ui2_domainname;
} USE_INFO_2, *PUSE_INFO_2, *LPUSE_INFO_2;

The use functions are:

NetUseAdd

NetUseDel

NetUseEnum

NetUseGetInfo


  Share Functions

Share functions control shared resources. A shared resource is a local resource on a server (for example, a disk directory, print device, or named pipe) that can be accessed by users and applications on the network.

NetShareAdd allows a user or application to share a resource of a specific type using the specified share name. NetShareAdd requires the share name and local device name to share the resource. A user or application must have an account on the server to access the resource.

You may also specify a Security Descriptor to be associated with a share, which specifies which users will be allowed to access files through this share, and with what type of access.

LAN Manager defines three types of special share names for interprocess communication (IPC) and remote administration of the server:

•	IPC$, reserved for interprocess communication.

•	ADMIN$, reserved for remote administration.

•	A$, B$, C$ (and other local disk names followed by a dollar sign), assigned to local disk devices.

Share functions are available at four information levels.

typedef struct _SHARE_INFO_0 {
LPWSTR	shi0_netname;
} SHARE_INFO_0, *PSHARE_INFO_0, *LPSHARE_INFO_0;

typedef struct _SHARE_INFO_1 {
LPWSTR	shi1_netname;
DWORD	shi1_type;
LPWSTR	shi1_remark;
} SHARE_INFO_1, *PSHARE_INFO_1, *LPSHARE_INFO_1;

typedef struct _SHARE_INFO_2 {
LPWSTR	shi2_netname;
DWORD	shi2_type;
LPWSTR	shi2_remark;
DWORD	shi2_permissions;
DWORD	shi2_max_uses;
DWORD	shi2_current_uses;
LPWSTR	shi2_path;
LPWSTR	shi2_passwd;
} SHARE_INFO_2, *PSHARE_INFO_2, *LPSHARE_INFO_2;

typedef struct _SHARE_INFO_502 {
LPTSTR	shi502_netname;
DWORD	shi502_type;
LPTSTR	shi502_remark;
DWORD	shi502_permissions;
DWORD	shi502_max_uses;
DWORD	shi502_current_uses;
LPTSTR	shi502_path;
LPTSTR	shi502_passwd;
DWORD	shi502_reserved;
PSECURITY_DESCRIPTOR	shi502_security_descriptor;
} SHARE_INFO_502, *PSHARE_INFO_502, *LPSHARE_INFO_502;

The following information levels are valid only for NetShareSetInfo and replace the older way of passing in a Parmnum to set a specific field.

The following are supported on downlevel systems (for example, LAN Manager 2.x) as well:

typedef struct _SHARE_INFO_1004 {
LPWSTR	shi1004_remark;
} SHARE_INFO_1004, *PSHARE_INFO_1004, *LPSHARE_INFO_1004;

typedef struct _SHARE_INFO_1006 {
DWORD	shi1006_max_uses;
} SHARE_INFO_1006, *PSHARE_INFO_1006, *LPSHARE_INFO_1006;

The following is only supported on Windows NT.

typedef struct _SHARE_INFO_1501 {
DWORD	shi1501_reserved;
PSECURITY_DESCRIPTOR	shi1501_security_descriptor;
} SHARE_INFO_1501, *PSHARE_INFO_1501, *LPSHARE_INFO_1501;

For NetShareSetInfo, parmnum values refer to the fields in the share_info structure as follows. These values are used when indicating an error in a specific parameter via parm_err.

parmnum value	Field in share_info struct
SHARE_NETNAME_PARMNUM	shi_netname
SHARE_TYPE_PARMNUM	shi_type
SHARE_REMARK_PARMNUM	shi_remark
SHARE_PERMISSIONS_PARMNUM	shi_permissions
SHARE_MAX_USES_PARMNUM	shi_max_uses
SHARE_CURRENT_USES_PARMNUM	shi_current_uses
SHARE_PATH_PARMNUM	shi_path
SHARE_PASSWD_PARMNUM	shi_passwd
SHARE_FILE_SD_PARMNUM	shi_security_descriptor
The share functions are:

NetShareAdd

NetShareCheck

NetShareDel

NetShareEnum

NetShareGetInfo

NetShareSetInfo


  Session Functions

Session functions control network sessions established between workstations and servers. They require that the Server service be started on the specified server. A session is a link between a workstation and a server. It is established the first time a workstation makes a connection with a shared resource on the server. Until the session ends, all further connections between the workstation and the server are part of this same session. To end a session, an application on the server end of a connection calls NetSessionDel. This deletes all current connections between the workstation and the server. NetSessionEnum returns information about all sessions established for a server. NetSessionGetInfo returns information about a particular session.

Per-user information is managed by the NetSession functions through the use of the username parameter. Since there can be multiple users per session, this parameter is necessary in order to access the user-specific information for the session.

Session functions are available at four information levels.

typedef struct _SESSION_INFO_0 {
LPWSTR	sesi0_cname;
} SESSION_INFO_0, *PSESSION_INFO_0, *LPSESSION_INFO_0;

typedef struct _SESSION_INFO_1 {
LPWSTR	sesi1_cname;
LPWSTR	sesi1_username;
DWORD	sesi1_num_opens;
DWORD	sesi1_time;
DWORD	sesi1_idle_time;
DWORD	sesi1__flags;
} SESSION_INFO_1, *PSESSION_INFO_1, *LPSESSION_INFO_1;

typedef struct _SESSION_INFO_2 {
LPWSTR	sesi2_cname;
LPWSTR	sesi2_username;
DWORD	sesi2_num_opens;
DWORD	sesi2_time;
DWORD	sesi2_idle_time;
DWORD	sesi2_flags;
LPWSTR	sesi2_cltype_name;
} SESSION_INFO_2, *PSESSION_INFO_2, *LPSESSION_INFO_2;

typedef struct _SESSION_INFO_10 {
LPWSTR	sesi10_cname;
LPWSTR	sesi10_username;
DWORD	sesi10_time;
DWORD	sesi10_idle_time;
} SESSION_INFO_10, *PSESSION_INFO_10, *LPSESSION_INFO_10;

sesi_username cannot be NULL. sesi1_flags and sesi2_flags can take the following bits:

SESS_GUEST	0x00000001
SESS_NONENCRYPTION	0x00000002

The session functions are:

NetSessionDel

NetSessionEnum

NetSessionGetInfo


  File Functions

File functions provide a way to monitor and close the file, device, and pipe resources open on a server. NetFileClose forces a server resource closed. This function can be used when a system error prevents normal closure. NetFileEnum returns information about resources open on a server. A file can be opened one or more times by one or more applications. Each file opening is uniquely identified. NetFileEnum returns an entry for each file opening. NetFileGetInfo returns information about one particular opening of a resource.

File functions are available at information levels 2 and 3 only. Levels 0 and 1 are not supported.

typedef struct _FILE_INFO_2 {
DWORD	fi2_id;
} FILE_INFO_2, *PFILE_INFO_2, *LPFILE_INFO_2;

typedef struct _FILE_INFO_3 {
DWORD	fi3_id;
DWORD	fi3_permissions;
DWORD	fi3_num_locks;
LPWSTR	fi3_pathname;
LPWSTR	fi3_username;
} FILE_INFO_3, *PFILE_INFO_3, *LPFILE_INFO_3;

The file functions are:

NetFileClose

NetFileEnum

NetFileGetInfo


  Message Functions

Message functions send and receive messages and manipulate message aliases. A message is a buffer of text data sent to a user or application on the network. To receive a message, a user or application must register a message alias in a computer's table of message names. This can be done by using NetMessageNameAdd. A message name table contains a list of registered message aliases (users and applications) permitted to receive messages.

The aliases registered in the message name table are case insensitive. NetMessageNameDel deletes a specific message alias from the message name table. NetMessageNameEnum lists all the aliases stored in the message name table. NetMessageNameGetInfo retrieves information about a particular message alias in the message name table.

To send a message, an application calls NetMessageBufferSend. Applications can also send broadcast messages to all users in a domain or to all computers on a network using NetMessageBufferSend.

Message functions are available at two information levels.

MSG_INFO_1 exists only for compatability. The Windows NT messenger will not forward names or allow names to be forwarded to it.

typedef struct _MSG_INFO_0 {
LPWSTR	msgi0_name;
} MSG_INFO_0, *PMSG_INFO_0, *LPMSG_INFO_0;

typedef struct _MSG_INFO_1 {
LPWSTR	msgi1_name;
DWORD	msgi1_forward_flag;
LPWSTR	msgi1_forward;
} MSG_INFO_1, *PMSG_INFO_1, *LPMSG_INFO_1;

The message functions are:

NetMessageBufferSend

NetMessageNameAdd

NetMessageNameDel

NetMessageNameEnum

NetMessageNameGetInfo


  Remote Utility Function

The remote utility function enables applications to access the time-of-day information on a remote server.

NetRemoteTOD returns time-of-day information from a remote server.


  Security Account Functions

User Functions

User functions control a user's account in the security database. Each user or application that accesses resources must have an account in the security database. The Windows NT Security system (SAM) uses this user account to verify that the user or application has permission to use a resource. When a user or an application requests access to a resource, the security system checks for an appropriate user account or group account to permit the access.

NetUserEnum can be used to list all user accounts in a domain. An application can verify the groups to which a user belongs by calling NetUserGetGroups, which returns a list of global group names. The NetUserGetLocalGroups function does the same for local groups. When a user account is no longer needed, use NetUserDel to delete the account from the server. Once the account is removed, the user can no longer access the server, except by using the guest account. Because the user's password is confidential, it is not returned by NetUserEnum or NetUserGetInfo. The password is initially assigned when NetUserAdd is called. NetUserSetInfo sets the password and other elements of a user account.

User account information is available at five levels:

typedef struct _USER_INFO_0 {
LPWSTR	usri0_name;
} USER_INFO_0, *PUSER_INFO_0, *LPUSER_INFO_0;

typedef struct _USER_INFO_1 {
LPWSTR	usri1_name;
LPWSTR	usri1_password;
DWORD	usri1_password_age;
DWORD	usri1_priv;
LPWSTR	usri1_home_dir;
LPWSTR	usri1_comment;
DWORD	usri1_flags;
LPWSTR	usri1_script_path;
} USER_INFO_1, *PUSER_INFO_1, *LPUSER_INFO_1;

typedef struct _USER_INFO_2 {
LPWSTR	usri2_name;
LPWSTR	usri2_password;
DWORD	usri2_password_age;
DWORD	usri2_priv;
LPWSTR	usri2_home_dir;
LPWSTR	usri2_comment;
DWORD	usri2_flags;
LPWSTR	usri2_script_path;
DWORD	usri2_auth_flags;
LPWSTR	usri2_full_name;
LPWSTR	usri2_usr_comment;
LPWSTR	usri2_parms;
LPWSTR	usri2_workstations;
DWORD	usri2_last_logon;
DWORD	usri2_last_logoff;
DWORD	usri2_acct_expires;
DWORD	usri2_max_storage;
DWORD	usri2_units_per_week;
LPBYTE	usri2_logon_hours;
DWORD	usri2_bad_pw_count;
DWORD	usri2_num_logons;
LPWSTR	usri2_logon_server;
DWORD	usri2_country_code;
DWORD	usri2_code_page;
} USER_INFO_2, *PUSER_INFO_2, *LPUSER_INFO_2;

typedef struct _USER_INFO_3 {
LPWSTR	usri3_name;
LPWSTR	usri3_password;
DWORD	usri3_password_age;
DWORD	usri3_priv;
LPWSTR	usri3_home_dir;
LPWSTR	usri3_comment;
DWORD	usri3_flags;
LPWSTR	usri3_script_path;
DWORD	usri3_auth_flags;
LPWSTR	usri3_full_name;
LPWSTR	usri3_usr_comment;
LPWSTR	usri3_parms;
LPWSTR	usri3_workstations;
DWORD	usri3_last_logon;
DWORD	usri3_last_logoff;
DWORD	usri3_acct_expires;
DWORD	usri3_max_storage;
DWORD	usri3_units_per_week;
PBYTE	usri3_logon_hours;
DWORD	usri3_bad_pw_count;
DWORD	usri3_num_logons;
LPWSTR	usri3_logon_server;
DWORD	usri3_country_code;
DWORD	usri3_code_page;
DWORD	usri3_user_id;
DWORD	usri3_primary_group_id;
LPWSTR	usri3_profile;
LPWSTR	usri3_home_dir_drive;
DWORD	usri3_password_expired;
}USER_INFO_3, *PUSER_INFO_3, *LPUSER_INFO_3;

typedef struct _USER_INFO_10 {
LPWSTR	usri10_name;
LPWSTR	usri10_comment;
LPWSTR	usri10_usr_comment;
LPWSTR	usri10_full_name;
} USER_INFO_10, *PUSER_INFO_10, *LPUSER_INFO_10;

typedef struct _USER_INFO_11 {
LPWSTR	usri11_name;
LPWSTR	usri11_comment;
LPWSTR	usri11_usr_comment;
LPWSTR	usri11_full_name;
DWORD	usri11_priv;
DWORD	usri11_auth_flags;
DWORD	usri11_password_age;
LPWSTR	usri11_home_dir;
LPWSTR	usri11_parms;
DWORD	usri11_last_logon;
DWORD	usri11_last_logoff;
DWORD	usri11_bad_pw_count;
DWORD	usri11_num_logons;
LPWSTR	usri11_logon_server;
DWORD	usri11_country_code;
LPWSTR	usri11_workstations;
DWORD	usri11_max_storage;
DWORD	usri11_units_per_week;
LPBYTE	usri11_logon_hours;
DWORD	usri11_code_page;
} USER_INFO_11, *PUSER_INFO_11, *LPUSER_INFO_11;

typedef struct _USER_INFO_20 {
LPWSTR	usri20_name;
LPWSTR	usri20_full_name;
LPWSTR	usri20_comment;
DWORD	usri20_flags;
DWORD	usri20_user_id;
}USER_INFO_20, *PUSER_INFO_20, *LPUSER_INFO_20;

The following information levels are valid only for NetUserSetInfo and replace the older way of passing in a Parmnum to set a specific field.

The following are supported on downlevel systems (for example, LAN Manager 2.x) as well:

typedef struct _USER_INFO_1003 {
LPWSTR	usri1003_password;
} USER_INFO_1003, *PUSER_INFO_1003, *LPUSER_INFO_1003;

typedef struct _USER_INFO_1005 {
DWORD	usri1005_priv;
} USER_INFO_1005, *PUSER_INFO_1005, *LPUSER_INFO_1005;

typedef struct _USER_INFO_1006 {
LPWSTR	usri1006_home_dir;
} USER_INFO_1006, *PUSER_INFO_1006, *LPUSER_INFO_1006;

typedef struct _USER_INFO_1007 {
LPWSTR	usri1007_comment;
} USER_INFO_1007, *PUSER_INFO_1007, *LPUSER_INFO_1007;

typedef struct _USER_INFO_1008 {
DWORD	usri1008_flags;
} USER_INFO_1008, *PUSER_INFO_1008, *LPUSER_INFO_1008;

typedef struct _USER_INFO_1009 {
LPWSTR	usri1009_script_path;
} USER_INFO_1009, *PUSER_INFO_1009, *LPUSER_INFO_1009;

typedef struct _USER_INFO_1010 {
DWORD	usri1010_auth_flags;
} USER_INFO_1010, *PUSER_INFO_1010, *LPUSER_INFO_1010;

typedef struct _USER_INFO_1011 {
LPWSTR	usri1011_full_name;
} USER_INFO_1011, *PUSER_INFO_1011, *LPUSER_INFO_1011;

typedef struct _USER_INFO_1012 {
LPWSTR	usri1012_usr_comment;
} USER_INFO_1012, *PUSER_INFO_1012, *LPUSER_INFO_1012;

typedef struct _USER_INFO_1013 {
LPWSTR	usri1013_parms;
} USER_INFO_1013, *PUSER_INFO_1013, *LPUSER_INFO_1013;

typedef struct _USER_INFO_1014 {
LPWSTR	usri1014_workstations;
} USER_INFO_1014, *PUSER_INFO_1014, *LPUSER_INFO_1014;

typedef struct _USER_INFO_1017 {
DWORD	usri1017_acct_expires;
} USER_INFO_1017, *PUSER_INFO_1017, *LPUSER_INFO_1017;

typedef struct _USER_INFO_1018 {
DWORD	usri1018_max_storage;
} USER_INFO_1018, *PUSER_INFO_1018, *LPUSER_INFO_1018;

typedef struct _USER_INFO_1020 {

DWORD	usri1020_units_per_week;
LPBYTE	usri1020_logon_hours;
} USER_INFO_1020, *PUSER_INFO_1020, *LPUSER_INFO_1020;

typedef struct _USER_INFO_1023 {
LPWSTR	usri1023_logon_server;
} USER_INFO_1023, *PUSER_INFO_1023, *LPUSER_INFO_1023;

typedef struct _USER_INFO_1024 {
DWORD	usri1024_country_code;
} USER_INFO_1024, *PUSER_INFO_1024, *LPUSER_INFO_1024;

typedef struct _USER_INFO_1025 {
DWORD	usri1025_code_page;
} USER_INFO_1025, *PUSER_INFO_1025, *LPUSER_INFO_1025;

typedef struct _USER_INFO_1051 {

DWORD	usri1051_primary_group_id;

} USER_INFO_1051, *PUSER_INFO_1051, *LPUSER_INFO_1051;

typedef struct _USER_INFO_1052 {

LPWSTR	usri1052_profile;

} USER_INFO_1052, *PUSER_INFO_1052, *LPUSER_INFO_1052;

typedef struct _USER_INFO_1053 {

LPWSTR	usri1053_home_dir_drive;

} USER_INFO_1053, *PUSER_INFO_1053, *LPUSER_INFO_1053;

For NetUserSetInfo, parmnum values refer to the fields in the user_info structure as follows. These values are used when indicating an error in a specific parameter via parm_err.

parmnum value	Field in user_info struct
USER_NAME_PARMNUM	usri_name
USER_PASSWORD_PARMNUM	usri_password
USER_PASSWORD_AGE_PARMNUM	usri_password_age
USER_PRIV_PARMNUM	usri_priv
USER_HOME_DIR_PARMNUM	usri_home_dir
USER_COMMENT_PARMNUM	usri_comment
USER_FLAGS_PARMNUM	usri_flags
USER_SCRIPT_PATH_PARMNUM	usri_script_path
USER_AUTH_FLAGS_PARMNUM	usri_auth_flags
USER_FULL_NAME_PARMNUM	usri_full_name
USER_USR_COMMENT_PARMNUM	usri_usr_comment
USER_PARMS_PARMNUM	usri_parms
USER_WORKSTATIONS_PARMNUM	usri_workstations
USER_LAST_LOGON_PARMNUM	usri_last_logon
USER_LAST_LOGOFF_PARMNUM	usri_last_logoff
USER_ACCT_EXPIRES_PARMNUM	usri_acct_expires
USER_MAX_STORAGE_PARMNUM	usri_max_storage
USER_UNITS_PER_WEEK_PARMNUM	usri_units_per_week
USER_LOGON_HOURS_PARMNUM	usri_logon_hours
USER_PAD_PW_COUNT_PARMNUM	usri_bad_pw_count
USER_NUM_LOGONS_PARMNUM	usri_num_logons
USER_LOGON_SERVER_PARMNUM	usri_logon_server
USER_COUNTRY_CODE_PARMNUM	usri_country_code
USER_CODE_PAGE_PARMNUM	usri_code_page
USER_PRIMARY_GROUP_PARMNUM	usri_primary_group_id
USER_PROFILE	usri_profile
USER_HOME_DIR_DRIVE_PARMNUM	usri_home_dir_drive
The user functions are:

NetUserAdd

NetUserDel

NetUserEnum

NetUserGetGroups

NetUserGetInfo

NetUserGetLocalGroups

NetUserSetGroups

NetUserSetInfo


  User Modal Functions

The user modal functions control the system-wide parameters that affect the Windows NT Security system behavior.

User modal information is available at three levels:

typedef struct _USER_MODALS_INFO_0 {
DWORD	usrmod0_min_passwd_len;
DWORD	usrmod0_max_passwd_age;
DWORD	usrmod0_min_passwd_age;
DWORD	usrmod0_force_logoff;
DWORD	usrmod0_password_hist_len;
} USER_MODALS_INFO_0, *PUSER_MODALS_INFO_0, LPUSER_MODALS_INFO_0;

typedef struct _USER_MODALS_INFO_1 {
DWORD	usrmod1_role;
LPWSTR	usrmod1_primary;
} USER_MODALS_INFO_1, *PUSER_MODALS_INFO_1, *LPUSER_MODALS_INFO_1;

typedef struct _USER_MODALS_INFO_2 {
LPWSTR	usrmod2_domain_name;
PSID	usrmod2_domain_id;
}USER_MODALS_INFO_2, *PUSER_MODALS_INFO_2, *LPUSER_MODALS_INFO_2;

The following information levels are valid only for NetUserModalsSet and replace the older way of passing in a Parmnum to set a specific field.

The following are supported on downlevel systems (for example, LAN Manager 2.x) as well. Note that the mapping from the old parmnum to the information level does not apply to the role and primary fields.

typedef struct _USER_MODALS_INFO_1001 {
DWORD	usrmod1001_min_passwd_len;
} USER_MODALS_INFO_1001, *PUSER_MODALS_INFO_1001, *LPUSER_MODALS_INFO_1001;

typedef struct _USER_MODALS_INFO_1002 {
DWORD	usrmod1002_max_passwd_age;
} USER_MODALS_INFO_1002, *PUSER_MODALS_INFO_1002, *LPUSER_MODALS_INFO_1002;

typedef struct _USER_MODALS_INFO_1003 {
DWORD	usrmod1003_min_passwd_age;
} USER_MODALS_INFO_1003, *PUSER_MODALS_INFO_1003, *LPUSER_MODALS_INFO_1003;

typedef struct _USER_MODALS_INFO_1004 {
DWORD	usrmod1004_force_logoff;
} USER_MODALS_INFO_1004, *PUSER_MODALS_INFO_1004, *LPUSER_MODALS_INFO_1004;

typedef struct _USER_MODALS_INFO_1005 {
DWORD	usrmod1005_password_hist_len;
} USER_MODALS_INFO_1005, *PUSER_MODALS_INFO_1005, *LPUSER_MODALS_INFO_1005;

typedef struct _USER_MODALS_INFO_1006 {
DWORD	usrmod1006_role;
} USER_MODALS_INFO_1006, *PUSER_MODALS_INFO_1006, *LPUSER_MODALS_INFO_1006;

typedef struct _USER_MODALS_INFO_1007 {
LPWSTR	usrmod1007_primary;
} USER_MODALS_INFO_1007, *PUSER_MODALS_INFO_1007, *LPUSER_MODALS_INFO_1007;

For NetUserModalsSet, parmnum values refer to the fields in the modals_info structure as follows. These values are used when indicating an error in a specific parameter via parm_err.

parmnum value	Field in modals_info struct
MODALS_MIN_PASSWD_LEN_PARMNUM	usrmod_min_passwd_len
MODALS_MAX_PASSWD_AGE_PARMNUM	usrmod_max_passwd_age
MODALS_MIN_PASSWD_AGE_PARMNUM	usrmod_min_passwd_age
MODALS_FORCE_LOGOFF_PARMNUM	usrmod_force_logoff
MODALS_PASSWD_HIST_LIST_PARMNUM	usrmod_passwd_hist_list
MODALS_ROLE_PARMNUM	usrmod_role
MODALS_PRIMARY_PARMNUM	usrmod_primary
MODALS_DOMAIN_NAME_PARMNUM	usrmod_domain_name
MODALS_DOMAIN_ID_PARMNUM	usrmod_domain_id
The user modal functions are:

NetUserModalsGet

NetUserModalsSet


  Global Group functions

The global group functions control global groups of users in a way that can be used across domains. A global group is a set of users who share common permissions in the security database. Group functions create or delete global groups, and review or adjust the membership of the global groups. The global group has a group name that specifies the user names of global group members.

To create a global group, an application calls NetGroupAdd, supplying a group name. Initially, the global group has no members. To assign members to the global group, call NetGroupSetUsers. To add a user to an existing global group, call NetGroupAddUser. To set general information about the global group, call NetGroupSetInfo.

NetGroupDelUser deletes a specified user name from a global group, and NetGroupDel disbands a global group. NetGroupDel works whether or not the global group has any members.

Three group functions retrieve information about the global groups on a server: NetGroupEnum produces a list of all global groups; NetGroupGetUsers lists all members of a specified global group; and NetGroupGetInfo returns general information about the global group.Each user account automatically belongs to one of the special global groups Domain Users or None, according to the user's Security Requirements. Membership of these global groups is indirectly controlled by the NetUserAdd, NetUserDel, and NetUserSetInfo functions. Group functions control groups of users.

Group account information is available at two levels:

typedef struct _GROUP_INFO_0 {
LPWSTR	grpi0_name;
} GROUP_INFO_0, *PGROUP_INFO_0, *LPGROUP_INFO_0;

typedef struct _GROUP_INFO_1 {
LPWSTR	grpi1_name;
LPWSTR	grpi1_comment;
} GROUP_INFO_1, *PGROUP_INFO_1, *LPGROUP_INFO_1;

typedef struct _GROUP_INFO_2 {
LPWSTR	grpi2_name;
LPWSTR	grpi2_comment;
DWORD	grpi2_group_id;
DWORD	grpi2_attributes;
}GROUP_INFO_2, *PGROUP_INFO_2;

The groups to which a user belongs may be obtained at one information level.

typedef struct _GROUP_USERS_INFO_0 {
LPWSTR	grui0_name;
} GROUP_USERS_INFO_0, *PGROUP_USERS_INFO_0, *LPGROUP_USERS_INFO_0;

typedef struct _GROUP_USERS_INFO_1 {
LPWSTR	grui1_name;
DWORD	grui1_attributes;
} GROUP_USERS_INFO_1, *PGROUP_USERS_INFO_1, *LPGROUP_USERS_INFO_1;

The following information levels are valid only for NetGroupSetInfo and replace the older way of passing in a Parmnum to set a specific field.

The following are supported on downlevel systems (for example, LAN Manager 2.x) as well:

typedef struct _GROUPINFO_1002 {
LPWSTR	grpi1002_comment;
} GROUP_USERS_INFO_1002, *PGROUP_USERS_INFO_1002, *LPGROUP_USERS_INFO_1002;

typedef struct _GROUP_INFO_1005 {
DWORD	grpi1005_attributes;
} GROUP_INFO_1005, *PGROUP_INFO_1005, *LPGROUP_INFO_1005;

For NetGroupSetInfo, parmnum values refer to the fields in the group_info structure as follows. These values are used when indicating an error in a specific parameter via parm_err.

parmnum value	Field in group_info struct
GROUP_NAME_PARMNUM	grpi_name
GROUP_COMMENT_PARMNUM	grpi_comment
GROUP_ATTRIBUTES_PARMNUM	grpi_attributes
The group functions are:

NetGroupAdd

NetGroupAddUser

NetGroupDel

NetGroupDelUser

NetGroupEnum

NetGroupGetInfo

NetGroupGetUsers

NetGroupSetInfo

NetGroupSetUsers


  Local Group Functions

A local group is a set of users who share common permissions in the security database. A local group can have members that are either users or global groups (global groups can contain only users). The local group functions control members of local groups in a way that can be used only by the systems within a "cluster". A "cluster" is the individual workstation if the system is a Windows NT system, but it contains all the Windows NT Servers of a domain if the system is a Windows NT Server. Thus, a local group defined on a workstation can be used only on that workstation, but a local group defined on a Windows NT Server can be used by any other Windows NT Server within the same domain. The local Group functions create or delete local groups, and review or adjust the memberships of local groups.

A member can be added to a local group by specifying the security identifier (SID) of the member. The Win32 LookupAccountName function can be used to translate a member account name to a SID.

To create a local group, an application calls NetLocalGroupAdd, supplying a local group name. Initially, the local group has no members. To assign members to the local group, call NetLocalGroupSetMembers. To add a member to an existing local group, call NetLocalGroupAddMember. To set general information about the local group, call NetLocalGroupSetInfo.

NetLocalGroupDelMember deletes a specified member from a local group, and NetLocalGroupDel disbands a local group, deleting all existing members of the local group first.

Three local group functions retrieve information about the local groups on a server: NetLocalGroupEnum produces a list of all local groups; NetLocalGroupGetMembers lists all members of a specified local group; and NetLocalGroupGetInfo returns general information about the local group.

Group account information is available at three levels:

typedef struct _LOCALGROUP_INFO_0 {
LPWSTR	lgrpi0_name;
} LOCALGROUP_INFO_0, *PLOCALGROUP_INFO_0, LPLOCALGROUP_INFO_0;

typedef struct _LOCALGROUP_INFO_1 {
LPWSTR	lgrpi1_name;
LPWSTR	lgrpi1_comment;
} LOCALGROUP_INFO_1, *PLOCALGROUP_INFO_1, LPLOCALGROUP_INFO_1;

typedef struct _LOCALGROUP_INFO_1002 {
LPWSTR	lgrpi1002_comment;
} LOCALGROUP_INFO_1002, *PLOCALGROUP_INFO_1002, LPLOCALGROUP_INFO_1002;

The local group to which a member belongs may be obtained at two information level.

typedef struct _LOCALGROUP_MEMBERS_INFO_0 {
PSID	lgrmi0_sid;
} LOCALGROUP_MEMBERS_INFO_0, *PLOCALGROUP_MEMBERS_INFO_0, *LPLOCALGROUP_MEMBERS_INFO_0;

typedef struct _LOCALGROUP_MEMBERS_INFO_0 {
PSID	lgrmi0_sid;
} LOCALGROUP_MEMBERS_INFO_0, *PLOCALGROUP_MEMBERS_INFO_0, *LPLOCALGROUP_MEMBERS_INFO_0;

typedef struct _LOCALGROUP_MEMBERS_INFO_1 {
PSID	lgrmi1_sid;
SID_NAME_USE	lgrmi1_sidusage;
LPWSTR	lgrmi1_name;
} LOCALGROUP_MEMBERS_INFO_1, *PLOCALGROUP_MEMBERS_INFO_1, *LPLOCALGROUP_MEMBERS_INFO_1;

typedef struct _LOCALGROUP_USERS_INFO_0 {
LPWSTR	lgrui0_name;
} LOCALGROUP_USERS_INFO_0, *PLOCALGROUP_USERS_INFO_0, *LPLOCALGROUP_USERS_INFO_0;

For NetLocalGroupSetInfo, parmnum values refer to the fields in the group_info structure as follows. These values are used when indicating an error in a specific parameter via parm_err.

parmnum value	Field in group_info struct
LOCALGROUP_NAME_PARMNUM	lgrpi_name
LOCALGROUP_COMMENT_PARMNUM	lgrpi_comment
The local group functions are:

NetLocalGroupAdd

NetLocalGroupAddMember

NetLocalGroupDel

NetLocalGroupDelMember

NetLocalGroupEnum

NetLocalGroupGetInfo

NetLocalGroupGetMembers

NetLocalGroupSetInfo

NetLocalGroupSetMembers


  Access Functions

Note  A full set of access setting functions exist in Win32. These should be used in place of the NetAccess functions. The NetAccess functions work only when remoted to a downlevel system.

Access permissions functions examine or modify user or group access permissions for specified resources. An access control list (ACL) contains the name of a resource, an audit attribute field, and a list of access control entries. An access control entry (ACE) is a user name or group name and its corresponding access permissions.

The audit attribute field defines what type of events will be audited for that resource. It is possible to audit various types of events, depending on whether the resource is a file or a directory. It is possible to audit events such as opening, writing, and deleting a file; creating or deleting a directory; and changing the ACL of the resource.

NetAccessAdd creates an ACL for a resource and sets user name or group name access permissions. NetAccessDel deletes the ACL for a resource. NetAccessGetInfo returns the ACL for a particular resource. NetAccessEnum returns information about all ACLs.

Only users or applications with admin group membership or special permission for the resource can define or examine access permissions. Users have special permissions for a resource when they are granted ACCESS_PERM permission for that resource; this is also known as P permission.

NetAccessCheck verifies whether a user has permission to perform a specified operation on a particular resource. If access permission is needed, you can use NetAccessSetInfo to change the ACL. NetAccessGetUserPerms returns a specified user's or group's permission for a specified resource.

Access permission information is available at two levels:

typedef struct _ACCESS_INFO_0 {
LPWSTR	acc0_resource_name;
} ACCESS_INFO_0, *PACCESS_INFO_0, *LPACCESS_INFO_0;

typedef struct _ACCESS_INFO_1 {
LPWSTR	acc1_resource_name;
DWORD	acc1_attr;
DWORD	acc1_count;
} ACCESS_INFO_1, *PACCESS_INFO_1, *LPACCESS_INFO_1;

Access list information is available at one levels:

typedef struct _ACCESS_LIST {
LPWSTR	acl_ugname;
DWORD	acl_access;
} ACCESS_LIST, *PACCESS_LIST, *LPACCESS_LIST;

The following information levels are valid only for NetAccessSetInfo and replace the older way of passing in a Parmnum to set a specific field.

The following are supported on downlevel systems (for example, LAN Manager 2.x) as well:

typedef struct _ACCESS_INFO_1002 {
DWORD	acc1002_attr;
} ACCESS_INFO_1002, *PACCESS_INFO_1002, *LPACCESS_INFO_1002;

For NetAccessSetInfo, parmnum values refer to the fields in the access_info structure as follows. These values are used when indicating an error in a specific parameter via parm_err.

parmnum value	Field in access_info struct
ACCESS_RESOURCE_NAME_PARMNUM	acc_resource_name
ACCESS_ATTR_PARMNUM	acc_attr
ACCESS_COUNT_PARMNUM	acc_count
ACCESS_ACCESS_LIST_PARMNUM	array following acc1_count
The following are defined for the bits in the acc1_attr field of _ACCESS_INFO_1:

Value	Constant
ACCESS_AUDIT	0x001
ACCESS_SUCCESS_OPEN	0x010
ACCESS_SUCCESS_WRITE	0x020
ACCESS_SUCCESS_DELETE	0x040
ACCESS_SUCCESS_ACL	0x080
ACCESS_SUCCESS_MASK	0x0F0
ACCESS_FAIL_OPEN	0x100
ACCESS_FAIL_WRITE	0x200
ACCESS_FAIL_DELETE	0x400
ACCESS_FAIL_ACL	0x800
ACCESS_FAIL_MASK	0xF00
ACCESS_FAIL_SHIFT	0x004
The access permission functions are:

NetAccessAdd

NetAccessCheck

NetAccessDel

NetAccessEnum

NetAccessGetInfo

NetAccessGetUserPerms

NetAccessSetInfo


  Domain Functions

Domain functions retrieve information about a domain. They require that the workstation service be started.

The domain functions are:

NetGetDCName

NetServerTransportAdd

NetServerTransportDel

NetServerTransportEnum

NetWkstaTransportAdd

NetWkstaTransportDel

NetWkstaTransportEnum


  Transport Functions

Transport functions handle binding and unbinding of transports to and from the server and redirector, and also enumerate the transports used by a component. The server transport functions deal with transports managed by the server, and the workstation transport functions deal with transports managed by the redirector.

NetServerTransportAdd allows the user to bind the transport to the server. NetServerTransportDel allows the user to unbind the server from the transport. NetServerTransportEnum enumerates the transports that are managed by the server.

The NetWkstaTransportAdd/Del/Enum functions perform equivalent operations for the workstation.

Server transport functions are available at one information level.

typedef struct _SERVER_TRANSPORT_INFO_0 {
DWORD	svti0_number_of_vcs;
LPWSTR	svti0_transport_name;
LPBYTE	svti0_transport_address;
DWORD	svti0_transportaddresslength;
LPWSTR	svti0_networkaddress;
} SERVER_TRANSPORT_INFO_0, *PSERVER_TRANSPORT_INFO_0, *LPSERVER_TRANSPORT_INFO_0;

Workstation transport functions are available at one information level.

typedef struct _WKSTA_TRANSPORT_INFO_0 {
DWORD	wkti0_quality_of_service;
DWORD	wkti0_number_of_vcs;
LPWSTR	wkti0_transport_name;
LPWSTR	wkti0_transport_address;
} WKSTA_TRANSPORT_INFO_0, *PWKSTA_TRANSPORT_INFO_0, *LPWKSTA_TRANSPORT_INFO_0;

The transport functions are:

NetServerTransportAdd

NetServerTransportDel

NetServerTransportEnum


  Alert Functions

Alert functions notify network service programs and applications of network events. An event is a particular instance of a process or state of hardware as defined by an application. The alert functions allow applications to indicate when predefined events occur.

NetAlertRaise is used to indicate that an event has occurred.

The fixed-length header contains the standard alert data structure. The STD_ALERT data structure has the following format:

typedef struct _STD_ALERT {
DWORD	alrt_timestamp;
WCHAR	alrt_eventname[EVLEN+1];
WCHAR	alrt_servicename[SNLEN+1];
} STD_ALERT, *PSTD_ALERT, *LPSTD_ALERT;

The ADMIN_OTHER_INFO data structure has the following format:

typedef struct _ADMIN_OTHER_INFO {
DWORD	alrtad_errcode;
DWORD	alrtad_numstrings;
} ADMIN_OTHER_INFO, *PADMIN_OTHER_INFO, *LPADMIN_OTHER_INFO;

/* Followed by consecutive Unicode strings; the count
is in the alrtad_numstrings element. */
WCHAR	mergestrings[];

The ERRLOG_OTHER_INFO data structure has the following format:

typedef struct _ERRLOG_OTHER_INFO {
DWORD	alrter_errcode;
DWORD	alrter_offset;
} ERRLOG_OTHER_INFO, *PERRLOG_OTHER_INFO, *LPERRLOG_OTHER_INFO;

The PRINT_OTHER_INFO data structure has the following format:

typedef struct _PRINT_OTHER_INFO {
DWORD	alrtpr_jobid;
DWORD	alrtpr_status;
DWORD	alrtpr_submitted;
DWORD	alrtpr_size;
} PRINT_OTHER_INFO, *PPRINT_OTHER_INFO, *LPPRINT_OTHER_INFO;
/* Followed by consecutive Unicode strings. */
WCHAR	computername[];
WCHAR	username[];
WCHAR	queuename[];
WCHAR	destname[];
WCHAR	status_string[];

The USER_OTHER_INFO data structure has the following format:

typedef struct _USER_OTHER_INFO {
DWORD	alrtus_errcode;
DWORD	alrtus_numstrings;
} USER_OTHER_INFO, *PUSER_OTHER_INFO, *LPUSER_OTHER_INFO;
/*
 * Followed by a number of consecutive Unicode strings;
 * the count is in the alrtus_numstrings element. */
 */
WCHAR	mergestrings[];

/* Further followed by two more consecutive Unicode strings. */
WCHAR	username[];
WCHAR	computername[];

The alert functions are:

NetAlertRaise

NetAlertRaiseEx


  Error Logging Functions

Note  Use the error logging functions only for remoting to downlevel. For Windows NT use the Event Logging functions.

Windows NT uses an integrated Event Logging mechanism for reporting both errors and audits. The NetError and NetAudit functions are provided to access downlevel LAN Manager logs. They will report ERROR_NOT_SUPPORTED if called to an Windows NT system.

The error log is a file that stores error messages (in binary format). It contains information about LAN Manager software internal errors, MS OS/2 and MS-DOS internal errors, and network service errors.

NetErrorLogRead reads entries from the error log; and NetErrorLogClear clears the error log and, optionally, saves the entries in a backup file.

NetErrorLogRead uses the ERROR_LOG data structure to read entries from and write entries to the error log. An entry consists of a fixed-length data structure. The data structure can be followed by Unicode strings (el_text) that describe the error message, and a block of raw data (el_data) related to the cause of the error. Because of the variable lengths and structures of the el_data and el_text portions of the entry, only the fixed-length data structure is defined in the ERROR_LOG data structure.

The error log entry has the following format:

typedef struct _ERROR_LOG {
DWORD	el_len;
DWORD	el_reserved;
DWORD	el_time;
DWORD	el_error;
LPWSTR	el_name
LPWSTR	el_text;

LPBYTE	el_data;

DWORD	el_data_size;
DWORD	el_nstrings;
} ERROR_LOG, *PERROR_LOG, *LPERROR_LOG;

/*
 * Variable-length raw data specific to the error. el_len will be preceded by pad bytes

 * as required for proper alignment. There may also be pad bytes after the end of the

 * fixed length structure, before el_data. Use the pointer in the fixed length structure

 * to reference this data.
 */
BYTE	el_data[];	/* Raw data	 */
DWORD	el_len2;

The error log handle is defined as follows:

typedef struct _HLOG {
DWORD	time;
DWORD	last_flags;
DWORD	offset;
DWORD	rec_offset;
} HLOG, *PHLOG, *LPHLOG;

The error log functions are:

NetErrorLogClear

NetErrorLogRead


  Configuration Functions

Note  The configuration functions are only for downlevel support. Use the registry functions to retrieve configuration information on Windows NT.

Configuration functions retrieve network configuration information.

Configuration functions are available at one information level.

typedef struct _CONFIG_INFO_0 {
LPWSTR	cfgi0_key;
LPWSTR	cfgi0_data;
} CONFIG_INFO_0, *PCONFIG_INFO_0, *LPCONFIG_INFO_0;

The configuration functions are:

NetConfigGet

NetConfigGetAll

NetConfigSet


  Statistics Functions

LAN Manager accumulates a set of operating statistics for workstations and servers from the time that the Workstation or Server service is started. NetStatisticsGet is called to get those statistics. The statistics function, NetStatisticsGet, retrieves the operating statistics for workstations and servers. Since Windows NT and downlevel workstations collect a different set of statistics, the caller must know whether the server is Windows NT or downlevel (which can be discovered using the NetServerGetInfo function) and interpret the returned buffer accordingly.

NetStatisticsGet returns a STAT_WORKSTATION_0 data structure when workstation statistics are requested; it returns a STAT_SERVER_0 data structure when server statistics are requested.

The downlevel STAT_WORKSTATION_0 data structure has the following format:

typedef struct _STAT_WORKSTATION_0 {
DWORD	stw0_start;
DWORD	stw0_numNCB_r;
DWORD	stw0_numNCB_s;
DWORD	stw0_numNCB_a;
DWORD	stw0_fiNCB_r;
DWORD	stw0_fiNCB_s;
DWORD	stw0_fiNCB_a;
DWORD	stw0_fcNCB_r;
DWORD	stw0_fcNCB_s;
DWORD	stw0_fcNCB_a;
DWORD	stw0_sesstart;
DWORD	stw0_sessfailcon;
DWORD	stw0_sessbroke;
DWORD	stw0_uses;
DWORD	stw0_usefail;
DWORD	stw0_autorec;
DWORD	stw0_bytessent_r_hi;
DWORD	stw0_bytessent_r_lo;
DWORD	stw0_bytesrcvd_r_hi;
DWORD	stw0_bytesrcvd_r_lo;
DWORD	stw0_bytessent_s_hi;
DWORD	stw0_bytessent_s_lo;
DWORD	stw0_bytesrcvd_s_hi;
DWORD	stw0_bytesrcvd_s_lo;
DWORD	stw0_bytessent_a_hi;
DWORD	stw0_bytessent_a_lo;
DWORD	stw0_bytesrcvd_a_hi;
DWORD	stw0_bytesrcvd_a_lo;
DWORD	stw0_reqbufneed;
DWORD	stw0_bigbufneed;
} STAT_WORKSTATION_0, *PSTAT_WORKSTATION_0, *LPSTAT_WORKSTATION_0;

The Windows NT STAT_WORKSTATION_0 data structure has the following format:

typedef struct _STAT_WORKSTATION_0 {
LARGE_INTEGER	StatisticsStartTime;
LARGE_INTEGER	BytesReceived;
LARGE_INTEGER	SmbsReceived;
LARGE_INTEGER	PagingReadBytesRequested;
LARGE_INTEGER	NonPagingReadBytesRequested;
LARGE_INTEGER	CacheReadBytesRequested;
LARGE_INTEGER	NetworkReadBytesRequested;
LARGE_INTEGER	BytesTransmitted;
LARGE_INTEGER	SmbsTransmitted;
LARGE_INTEGER	PagingWriteBytesRequested;
LARGE_INTEGER	NonPagingWriteBytesRequested;
LARGE_INTEGER	CacheWriteBytesRequested;
LARGE_INTEGER	NetworkWriteBytesRequested;
DWORD	InitiallyFailedOperations;
DWORD	FailedCompletionOperations;
DWORD	ReadOperations;
DWORD	RandomReadOperations;
DWORD	ReadSmbs;
DWORD	LargeReadSmbs;
DWORD	SmallReadSmbs;
DWORD	WriteOperations;
DWORD	RandomWriteOperations;
DWORD	WriteSmbs;
DWORD	LargeWriteSmbs;
DWORD	SmallWriteSmbs;
DWORD	RawReadsDenied;
DWORD	RawWritesDenied;
DWORD	NetworkErrors;
// Connection	/Session counts
DWORD	Sessions;
DWORD	FailedSessions;
DWORD	Reconnects;
DWORD	CoreConnects;
DWORD	Lanman20Connects;
DWORD	Lanman21Connects;
DWORD	LanmanNtConnects;
DWORD	ServerDisconnects;
DWORD	HungSessions;
DWORD	UseCount;
DWORD	FailedUseCount;
//
// Queue Leng	ths (updates protected by RdrMpxTableSpinLock NOT
// RdrStatisticsSpinlock)
//
DWORD	CurrentCommands;
} STAT_WORKSTATION_0, *PSTAT_WORKSTATION_0, *LPSTAT_WORKSTATION_0;

The STAT_SERVER_0 data structure has the following format:

typedef struct _STAT_SERVER_0 {
DWORD	sts0_start;
DWORD	sts0_fopens;
DWORD	sts0_devopens;
DWORD	sts0_jobsqueued;
DWORD	sts0_sopens;
DWORD	sts	0_stimedout;
DWORD	sts0_serrorout;
DWORD	sts0_pwerrors;
DWORD	sts0_permerrors;
DWORD	sts0_syserrors;
DWORD	sts0_bytessent_low;
DWORD	sts0_bytessent_high;
DWORD	sts0_bytesrcvd_low;
DWORD	sts0_bytesrcvd_high;
DWORD	sts0_avresponse;
DWORD	sts0_reqbufneed;
DWORD	sts0_bigbufneed;
} STAT_SERVER_0, *PSTAT_SERVER_0, *LPSTAT_SERVER_0;

The statistics function is:

NetStatisticsGet


  Auditing Functions

Note  The auditing functions are for downlevel only. Windows NT automatically records audits on failed accesses when AccessCheckAndAudit is used. To read audits, use the ReadEventLog function.

Windows NT uses an integrated event logging mechanism for reporting both errors and audits. The NetError and NetAudit functions are provided to access downlevel LAN Manager logs. They will report ERROR_NOT_SUPPORTED if called to an Windows NT system.

Auditing functions control the audit log. Auditing functions monitor operations on the specified server. If auditing is enabled, each monitored operation generates an audit entry. For example, when a user establishes a connection to the server, a single audit entry is generated.

Audit entries are stored in a binary file called an audit trail or audit log. All Auditing functions perform their operations on this file. LAN Manager defines many types of audit entries.

NetAuditRead reads the audit log. NetAuditClear clears the audit log.

Data Structures

All audit entries include a fixed-length header used in conjunction with variable-length data specific to the entry type. Because of the variable lengths and structures of the ae_data element of the audit entry (it is possible for ae_data to be zero bytes), only the fixed header is defined in the audit_entry data structure.

The variable-length portion of the audit entry can contain an offset to a variable-length Unicode string. The offset values are DWORDs. To determine the value of the pointer to this string, add the offset value to the address of the ae_data data structure.

The following example illustrates this procedure. Assume that pAE points to a buffer that contains a complete audit entry and that the ae_type element of the audit_entry data structure contains the value AE_CONNSTOP, which specifies the predefined AE_CONNSTOP data structure. To point the variable pszComputerName to the Unicode string that contains the name of the client whose connection was stopped, an application would perform the following algorithm:

PAUDIT_ENTRY	pAE;	/* Fixed part of audit entry */
LPAE_CONNSTOP	pAEvar;	/* Variable-length structure */
LPWSTR	pszComputerName;	/* Pointer to var-length string*/

/* Calculate the offset to the variable-length structure. */
pAEvar = (_LPAE_CONNSTOP) (((LPBYTE) pAE) + pAE->ae_data_offset);

/* Calculate the offset to the computername. */
pszComputerName = ((LPBYTE) pAEvar) + pAEvar->ae_cp_compname;

Fixed-Length Header

The audit_entry data structure has the following format:

typedef struct _AUDIT_ENTRY {
DWORD	ae_len;
DWORD	ae_reserved;
DWORD	ae_time;
DWORD	ae_type;
DWORD	ae_data_offset;	/* Offset from beginning
   address of audit_entry */

DWORD	ae_data_size;
} AUDIT_ENTRY, *PAUDIT_ENTRY, *LPAUDIT_ENTRY;

/* Variable-length data specific to type of audit entry. There may be
   pad bytes after 	ae_data_size for alignment purposes.

*/
BYTE	ae_data[];

/* Terminating length indicator. Preceded by pad bytes for proper alignment.*/
DWORD	ae_len2;

where

ae_len and ae_len2

Specify the length of the audit entry. Both have the same value. The ae_len element is included at the beginning and at the end of the audit entry to enable both backward and forward scanning of the log.

ae_reserved

Reserved.

ae_time

Specifies when the audit entry was generated. The value is stored as the number of seconds elapsed since 00:00:00, January 1, 1970.

ae_type

Specifies the type of audit entry. Type values from 0x0000 through 0x07FF are reserved. OEMs and other applications programmers can reserve values from 0x0800 through 0xFFFF.

ae_data_offset

Specifies the byte offset from the beginning of the audit entry to the beginning of the variable-length portion (ae_data) of the audit entry.

ae_data

Specifies the variable-length portion of the audit entry; it differs depending on the type of entry specified by ae_type. The information begins at ae_data_offset bytes from the top of the audit entry. For information about the structure of each entry type defined by LAN Manager, see Variable-Length Data.


  Variable-Length Data

The following data structures are specific to the audit entry type The structures follow the audit_entry header, but they are not necessarily contiguous.

The _AE_SRVSTATUS data structure is associated with an audit entry of type AE_SRVSTATUS.

typedef struct _AE_SRVSTATUS {
DWORD	ae_sv_status;
}AE_SRVSTATUS , * PAE_SRVSTATUS ;

The _AE_SESSLOGON data structure is associated with an audit entry of type AE_SESSLOGON.

typedef struct _AE_SESSLOGON {
DWORD	ae_so_compname;
DWORD	ae_so_username;
DWORD	ae_so_privilege;
}AE_SESSLOGON , * PAE_SESSLOGON ;

The _AE_SESSLOGOFF data structure is associated with an audit entry of type AE_SESSLOGOFF.

typedef struct AE_SESSLOGOFF {
DWORD	ae_sf_compname;
DWORD	ae_sf_username;
DWORD	ae_sf_reason;
}AE_SESSLOGOFF , * PAE_SESSLOGOFF;

The _AE_SESSPWERR data structure is associated with an audit entry of type AE_SESSPWERR.

typedef struct _AE_SESSPWERR {
DWORD	ae_sp_compname;
DWORD	ae_sp_username;
}AE_SESSPWERR , * PAE_SESSPWERR ;

The _AE_CONNSTART data structure is associated with an audit entry of type AE_CONNSTART.

typedef struct _AE_CONNSTART {
DWORD	ae_ct_compname;
DWORD	ae_ct_username;
DWORD	ae_ct_netname;
DWORD	ae_ct_connid;
}AE_CONNSTART , * PAE_CONNSTART ;

The _AE_CONNSTOP data structure is associated with an audit entry of type AE_CONNSTOP.

typedef struct _AE_CONNSTOP {
DWORD	ae_cp_compname;
DWORD	ae_cp_username;
DWORD	ae_cp_netname;
DWORD	ae_cp_connid;
DWORD	ae_cp_reason;
}AE_CONNSTOP , * PAE_CONNSTOP ;

The _AE_CONNREJ data structure is associated with an audit entry of type AE_CONNREJ.

typedef struct _AE_CONNREJ {
DWORD	ae_cr_compname;
DWORD	ae_cr_username;
DWORD	ae_cr_netname;
DWORD	ae_cr_reason;
}AE_CONNREJ , * PAE_CONNREJ ;

The _AE_RESACCESS data structure is associated with an audit entry of type AE_RESACCESS.

typedef struct _AE_RESACCESS {
DWORD	ae_ra_compname;
DWORD	ae_ra_username;
DWORD	ae_ra_resname;
DWORD	ae_ra_operation;
DWORD	ae_ra_returncode;
DWORD	ae_ra_restype;
DWORD	ae_ra_fileid;
}AE_RESACCESS , * PAE_RESACCESS ;

The _AD_RESACCESSREJ data structure is associated with an audit entry of type AE_RESACCESSREJ.

typedef struct _AE_RESACCESSREJ {
DWORD	ae_rr_compname;
DWORD	ae_rr_username;
DWORD	ae_rr_resname;
DWORD	ae_rr_operation;
}AE_RESACCESSREJ , * PAE_RESACCESSREJ ;

The _AD_CLOSEFILE data structure is associated with an audit entry of type AE_CLOSEFILE.

typedef struct _AE_CLOSEFILE {
DWORD	ae_cf_compname;
DWORD	ae_cf_username;
DWORD	ae_cf_resname;
DWORD	ae_cf_fileid;
DWORD	ae_cf_duration
DWORD	ae_cf_reason;
}AE_CLOSEFILE , * PAE_CLOSEFILE ;

The _AE_SERVICESTAT data structure is associated with an audit entry of type AE_SERVICESTAT.

typedef struct _AE_SERVICESTAT {
DWORD	ae_ss_compname;
DWORD	ae_ss_username;
DWORD	ae_ss_svcname;
DWORD	ae_ss_status;
DWORD	ae_ss_code;
DWORD	ae_ss_text;
DWORD	ae_ss_returnval;
}AE_SERVICESTAT , * PAE_SERVICESTAT ;

The _AE_ACLMOD data structure is associated with audit entries of type AE_ACLMOD and AE_ACLMODFAIL.

struct _AE_ACLMOD {
DWORD	ae_am_compname;
DWORD	ae_am_username;
DWORD	ae_am_resname;
DWORD	ae_am_action;
DWORD	ae_am_datalen;
}AE_ACLMOD, * PAE_ACLMOD;

The _AE_UASMOD data structure is associated with an audit entry of type AE_UASMOD.

typedef struct _AE_UASMOD {
DWORD	ae_um_compname;
DWORD	ae_um_username;
DWORD	ae_um_resname;
DWORD	ae_um_rectype;
DWORD	ae_um_action;
DWORD	ae_um_datalen;
}AE_UASMOD , * PAE_UASMOD ;

The _AE_NETLOGON data structure is associated with an audit entry of type AE_NETLOGON.

typedef struct _AE_NETLOGON {
DWORD	ae_no_compname;
DWORD	ae_no_username;
DWORD	ae_no_privilege;
DWORD	ae_no_authflags;
}AE_NETLOGON , * PAE_NETLOGON ;

The _AE_NETLOGOFF data structure is associated with an audit entry of type AE_NETLOGOFF.

typedef struct _AE_NETLOGOFF {
DWORD	ae_nf_compname;
DWORD	ae_nf_username;
DWORD	ae_nf_reserved1;
DWORD	ae_nf_reserved2;
}AE_NETLOGOFF , * PAE_NETLOGOFF ;

The _AE_ACCLIM data structure is associated with an audit entry of type AE_ACCLIMITEXCD.

typedef struct _AE_ACCLIM {
DWORD	ae_al_compname;
DWORD	ae_al_username;
DWORD	ae_al_resname;
DWORD	ae_al_limit;
}AE_ACCLIM , * PAE_ACCLIM ;

The _AE_LOCKOUT data structure is associated with an audit entry of type AE_LOCKOUT.

typedef struct AE_LOCKOUT {
DWORD	ae_lk_compname;
DWORD	ae_lk_username;
DWORD	ae_lk_action;
DWORD	ae_lk_bad_pw_count;
}AE_LOCKOUT , PAE_LOCKOUT ;

The _AE_GENERIC data structure is associated with an audit entry of type AE_GENERIC.

typedef struct _AE_GENERIC {
DWORD	ae_ge_msgfile;
DWORD	ae_ge_msgnum;
DWORD	ae_ge_params;
DWORD	ae_ge_param1;
DWORD	ae_ge_param2;
DWORD	ae_ge_param3;
DWORD	ae_ge_param4;
DWORD	ae_ge_param5;
DWORD	ae_ge_param6;
DWORD	ae_ge_param7;
DWORD	ae_ge_param8;
DWORD	ae_ge_param9;
}AE_GENERIC , * PAE_GENERIC ;

The audit log handle is defined as follows:

typedef struct _HLOG {
DWORD	time;
DWORD	last_flags;
DWORD	offset;
DWORD	rec_offset;
} HLOG, *PHLOG, *LPHLOG;

The auditing functions are:

NetAuditClear

NetAuditRead


  Replicator Functions

The Windows NT replicator functions control how the Windows NT Replicator service updates selective directories from an export server to one or more clients. In addition to providing compatible LAN Manager 2.x functionality in a well-defined manner, this new set of LAN Manager functions allow for specific API (operation) security checking.

The change from the file system based control on LAN Manager 2.x to replicator function control on Windows NT has the following implications:

•	Applications can no longer delete a directory in the import path of a client to stop receiving updates from its master.

•	Applications can no longer use the REPL.INI file in each replicated directory on a master to control the method of replication.

•	Applications can no longer lock or unlock a directory on a master from being replicated by creating or deleting the USERLOCK.* file(s).

•	Applications can no longer lock or unlock a directory on a client from receiving updates from its master by creating or deleting the USERLOCK.* file(s).

•	Applications that depend on the LAN Manager 2.x behavior of ignoring locks for file integrity trees will need to be modified. (Windows NT policy differs from LAN Manager 2.x policy; under Windows NT the locks are always respected.)

Each of the intended operations listed preceding can be specified to the Windows NT replicator service through an appropriate function.

Any user or application that belongs to the admin or server operator group on a local or remote export server can modify the parameters that control the replication master.

There are three categories of replicator functions:

•	Replicator configuration functions

•	Replicator export directory functions

•	Replicator import directory functions


  Replicator Configuration Functions

The configuration parameters of the replicator service can be examined using NetReplGetInfo. They can be modified using NetReplSetInfo.

The replicator service configuration parameters are:

role

Role of the Replicator service, which is either REPL_ROLE_IMPORT (client), REPL_ROLE_EXPORT (master), or REPL_ROLE_BOTH. On a Windows NT Server, any of these values are allowed. Under Windows NT systems, only REPL_ROLE_IMPORT is allowed.

exportpath

Fully qualified path to the master tree in which directories are created and replicated from. This path must include the drive letter.

exportlist

List of computer and domain names to send update announcements to. If this list is not provided, then update announcements will be sent to the server's domain. The list entries are separated by semicolons; computer names in the list must not have leading backslashes.

importpath

Fully qualified path to the client tree in which directories are created to receive the replicas of the master. This path must include the drive letter.

importlist

List of computers and domain names to receive updates from. If this list is not provided, then update announcements are received from the server's domain. The list entries are separated by semicolons; computer names in the list must not have leading backslashes.

logonusername

User account name belonging to the replicator group with which the client logs on to read files from its master(s). This field is ignored by the Windows NT replicator, but is provided for possible future use.

interval

Time in minutes within which the master checks for changes in all the replicated directories. This field may be ignored by the Windows NT replicator, but is provided for possible future use.

pulse

Time in number of intervals within which the master notifies its clients of the current replica version when no updates are necessary. This field may be ignored by the Windows NT replicator, but is provided for possible future use.

guardtime

Time in minutes that a REPL_INTEGRITY_TREE level integrity directory must be stable before a client is allowed to update from it. (See the explanation of integrity in Replicator Export Directory Functions). The default guard time is 2 minutes.

random

A value in seconds sent by a master to its clients so that the clients can use the 0 random range to generate a random time to wait on before updating from the master.

The configuration parameters (except importpath and exportpath) values can all be dynamically set.

These functions can be called whether the replicator service is running or not. If the replicator service is already running, any modification (except to importpath and exportpath) to the replication configuration takes effect immediately, and is persistent after the replicator service has been stopped. If the replicator service is not started, the parameters are stored as persistent information and will take effect when the replicator service starts up. The service must be stopped to set the importpath and exportpath values.

The replicator configuration information structures are:

typedef struct _REPL_INFO_0 {
DWORD	rp0_role;
LPWSTR	rp0_exportpath;
LPWSTR	rp0_exportlist;
LPWSTR	rp0_importpath;
LPWSTR	rp0_importlist;
LPWSTR	rp0_logonusername;
DWORD	rp0_interval;
DWORD	rp0_pulse;
DWORD	rp0_guardtime;
DWORD	rp0_random;
} REPL_INFO_0, *PREPL_INFO_0, *LPREPL_INFO_0;

typedef struct _REPL_INFO_1000 {
DWORD	rp1000_interval;
} REPL_INFO_1000, *PREPL_INFO_1000, *LPREPL_INFO_1000;

typedef struct _REPL_INFO_1001 {
DWORD	rp1001_pulse;
} REPL_INFO_1001, *PREPL_INFO_1001, *LPREPL_INFO_1001;

typedef struct _REPL_INFO_1002 {
DWORD	rp1002_guardtime;
} REPL_INFO_1002, *PREPL_INFO_1002, *LPREPL_INFO_1002;

typedef struct _REPL_INFO_1003 {
DWORD	rp1003_random;
} REPL_INFO_1003, *PREPL_INFO_1003, *LPREPL_INFO_1003;


  Replicator Export Directory Functions

The replicator export directory functions control top-level directories under the export path on the master. A user can create a new directory under the export path and the Replicator service will automatically replicate that directory. Or, a directory under the export path can be registered using NetReplExportDirAdd. When adding a directory to be replicated using these functions, the replication controls (integrity and extent) are specified via the NetReplExportDirAdd function. If the directory is created in the file system and no replicator functions are called, then the directory is treated as having file integrity and tree extent.

Integrity determines when a master updates a client. When integrity is REPL_INTEGRITY_FILE, the client gets a replica of a file within the directory when it is not in use (being changed or replicated). When integrity is set to REPL_INTEGRITY_TREE, every file and directory within the replicated directory must be stable for the amount of time specified by the guardtime parameter before the client is updated. Extent determines whether the entire tree within the directory is replicated (REPL_EXTENT_TREE) or only the files in the first-level directory is replicated (REPL_EXTENT_FILE).

The replication controls of each replicated directory can be examined using NetReplExportDirGetInfo, and dynamically modified using NetReplExportDirSetInfo. These control fields used to be specified in the REPL.INI file within each replicated directory on LAN Manager 2.x, and they were not dynamically settable. On Windows NT, the REPL.INI file is not used and will be ignored in the replication process.

NetReplExportDirEnum returns a list of directories that are currently replicated. NetReplExportDirDel deregisters a directory so that it is no longer replicated.

The lock status information is returned in two fields: lockcount and locktime. Lockcount indicates the number of outstanding locks on a directory. Locktime is the time (in seconds since 1970, GMT) when the directory was first locked, or is 0 if the directory is not locked at the present time.

NetReplExportDirLock locks a directory so that it is not replicated, by incrementing a lock reference count for the directory. A lock on a directory can be unlocked using NetReplExportDirUnlock. The replication does not resume unless all outstanding locks on that directory are released, and the lock reference count is returned to 0. (The locktime field is automatically set to 0 when lockcount is 0.)

The replicator export directory functions can be called whether the Replicator service is running or not. If the Replicator service is running as a master, any modification to the directory controls takes effect immediately, and is persistent after the Replicator service has been stopped. If the Replicator service is not started, the controls for the directory is stored as persistent information and will take effect when the Replicator service starts up.

The replicator export directory functions are available at the following information levels:

typedef struct _REPL_EDIR_INFO_0 {
LPWSTR	rped0_dirname;
} REPL_EDIR_INFO_0, *PREPL_EDIR_INFO_0, *LPREPL_EDIR_INFO_0;

typedef struct _REPL_EDIR_INFO_1 {
LPWSTR	rped1_dirname;
DWORD	rped1_integrity;
DWORD	rped1_extent;
} REPL_EDIR_INFO_1, *PREPL_EDIR_INFO_1, *LPREPL_EDIR_INFO_1;

typedef struct _REPL_EDIR_INFO_2 {
LPWSTR	rped2_dirname;
DWORD	rped2_integrity;
DWORD	rped2_extent;
DWORD	rped2_lockcount;
DWORD	rped2_locktime;
} REPL_EDIR_INFO_2, *PREPL_EDIR_INFO_2, *LPREPL_EDIR_INFO_2;

typedef struct _REPL_EDIR_INFO_1000 {
DWORD	rped1000_integrity;
} REPL_EDIR_INFO_1000, *PREPL_EDIR_INFO_1000, *LPREPL_EDIR_INFO_1000;

typedef struct _REPL_EDIR_INFO_1001 {
DWORD	rped1001_extent;
} REPL_EDIR_INFO_1001, *PREPL_EDIR_INFO_1001, *LPREPL_EDIR_INFO_1001;

The replicator export directory functions are:

NetReplExportDirAdd

NetReplExportDirDel

NetReplExportDirEnum

NetReplExportDirGetInfo

NetReplExportDirSetInfo

NetReplExportDirLock

NetReplExportDirUnlock


  Replicator Import Directory Functions

The replicator import directory functions designate the top-level directories under the import path to receive updates on. They also return status information about a replicated directory on the client. On LAN Manager 2.x, a user must create a directory under the import path and the Replicator service automatically replicates to it. On Windows NT, import directories are automatically added if they are exported by an export server from which importer is importing. Another way to register a directory in advance of it being exported, is to use the NetReplImportDirAdd functions. This function does not create the directory itself. This is useful if you wish to modify some of the properties of the import directory (for example, to lock it) prior to it first beginning to import this directory.

NetReplImportDirDel deregisters a directory. This is used to clean up a directory that is no longer being exported. It will not stop replication if there is an active exporter, since it will be re-registered the next time the exporter tells the importer what directories it is exporting. If you wish to prevent importing of an actively exported directory, use the NetReplImportDirLock function.

NetReplImportDirEnum lists all the directories that are replicated to a client, and NetReplImportDirGetInfo returns the status of a specified directory.

The status information of a directory consists of the replication state, the UNC computer name of the master (mastername), and the time (in seconds since 1970, GMT) when the directory was last updated (last_update_time). If the state is REPL_STATE_OK, the directory currently has a master, and is receiving regular update notices from it. If the state is REPL_STATE_NO_MASTER, the directory is not supported by any master, and it is normally empty. If the state is REPL_STATE_NO_SYNC, the directory has a master, but the master has not sent any update notices within the interval time period. This may be due to a communication failure, the master crashing, the directory being locked, files in the client directory being opened at update time, or an unstable REPL_INTEGRITY_TREE integrity directory on the master. If the client Replicator service is not started the state is REPL_STATE_NEVER_REPLICATED, mastername is a NULL string, and last_update_time is 0.NetReplImportDirLock locks a directory so that it does not receive updates, by incrementing a lock reference count for the directory. A lock on a directory can be unlocked using NetReplImportDirUnlock. The directory is not updated unless all outstanding locks on that directory are released, and the lock reference count is returned to 0.

The lock status information is returned in two fields: lockcount and locktime. Lockcount indicates the number of outstanding locks on a directory. Locktime is the time (in seconds since 1970, GMT) when the directory was first locked. (locktime is set to 0 whenever lockcount goes to 0.)

The replicator import directory functions can be called whether the Replicator service is running or not. If the Replicator service is running as a client, directory adds or deletes take effect immediately, and is persistent after the Replicator service has been stopped. If the Replicator service is not started, any added directory will receive updates when the Replicator service starts up (if there exists a master that exports the directory).

The replicator import directory function are available at the following information levels:

typedef struct _REPL_IDIR_INFO_0 {
LPWSTR	rpid0_dirname;
} REPL_IDIR_INFO_0, *PREPL_IDIR_INFO_0, *LPREPL_IDIR_INFO_0;

typedef struct _REPL_IDIR_INFO_1 {
LPWSTR	rpid1_dirname;
DWORD	rpid1_state;
LPWSTR	rpid1_mastername;
DWORD	rpid1_last_update_time;
DWORD	rpid1_lockcount;
DWORD	rpid1_locktime;
} REPL_IDIR_INFO_1, *PREPL_IDIR_INFO_1, *LPREPL_IDIR_INFO_1;

The replicator import directory functions are:

NetReplImportDirAdd

NetReplImportDirDel

NetReplImportDirEnum

NetReplImportDirGetInfo

NetReplImportDirLock


  Schedule Service Functions

Schedule service functions are used to submit and manage jobs to be executed at a given computer at a given time or times in future. Jobs can be commands and programs. Jobs can be managed at remote and local computers provided schedule service is running at a given computer.

Schedule service functions were designed to support old AT command functionality, but they extend this functionality so that new AT command may submit and manage jobs at remote as well as local computers. Schedule service functions are also known as "Job" and "AT command" functions.

Schedule service functions are job submittal (NetScheduleJobAdd), job cancellation (NetScheduleJobDel), job enumeration (NetScheduleJobEnum) and retrieving information about a particular job (NetScheduleJobGetInfo). In order for these functions to succeed, a caller must have administrator's privilege at a computer where Schedule service is running.

Data Structures

AT_INFO data structure is used by NetScheduleJobAdd( ) to specify a job to be added, and by NetScheduleJobGetInfo( ) to return information about an already submitted job. AT_ENUM data structure is used by NetScheduleJobEnum( ) to enumerate and return information about an entire queue of already submitted jobs.

typedef struct _AT_INFO {
DWORD	JobTime;
DWORD	DaysOfMonth;
UCHAR	DaysOfWeek;
UCHAR	Flags;
LPWSTR	Command;
} AT_INFO, *PAT_INFO, *LPAT_INFO;

typedef struct _AT_ENUM {
DWORD	JobId;
DWORD	JobTime;
DWORD	DaysOfMonth;
UCHAR	DaysOfWeek;
UCHAR	Flags;
LPWSTR	Command;
} AT_ENUM, *PAT_ENUM, *LPAT_ENUM;

JobId

Job identifier of an already submitted job.

JobTime

Time of day when a job is scheduled to run. Time is a local time at a computer where Schedule service is running. Time is measured from midnight and is expressed in milliseconds.

DaysOfMonth

Bitmask for days of month when a job is scheduled to run. The bitmask is NULL if a job was scheduled to run only once at the first occurrence of JobTime. For each bit that is set in the bitmask a job will run at JobTime on a corresponding day of the month. Bit 0 corresponds to first day of the month, etc.

DaysOfWeek

Bitmask for days of week when this job is scheduled to run. The bitmask is NULL if a job was scheduled to run only once at the first occurrence of JobTime. For each bit that is set in the bitmask a job will run at JobTime on a corresponding day of the week. Bit 0 corresponds to Monday (first day of the week), etc.

Flags

Bitmask describing job properties. For job submission (NetScheduleJobAdd) possible values are:

JOB_RUN_PERIODICALLY

If this flag bit is set then job runs on every day where corresponding bits in DaysOfMonth or DaysOfWeek are set. If this flag bit is clear then job runs only once for each bit that was set in DaysOfMonth and/or DaysOfWeek at the time of job submission.

JOB_ADD_CURRENT_DATE

When this flag bit is set then job will also execute at the first occurrence of JobTime at the computer where job is submitted to. In other words, setting this flag bit is equivalent to setting the corresponding day bit in DaysOfMonth bitmask.

For job information retrieval (NetScheduleJobEnum and NetScheduleJobGetInfo) possible values are:

JOB_RUN_PERIODICALLY

This flag bit is equal to the original value of this flag bit when a job was submitted.

JOB_EXEC_ERROR

This flag bit is set whenever Schedule service failed to execute successfully this job the last time this job was supposed to run.

JOB_RUNS_TODAY

This flag bit is set if JobId is larger than the current time of day at the computer where this job is queued at.

Command

Points to a Unicode string that contains the name of command, batch program or binary file to execute.

The schedule service functions are:

NetScheduleJobAdd

NetScheduleJobDel

NetScheduleJobEnum

NetScheduleJobGetInfo


Lanman Functions Not Supported in Windows NT
  LAN Manager Functions Not Supported in Windows NT

The following section lists the 16-bit LAN Manager functions that are no longer supported in the Win32 API. In general, the rule we have followed is to not support anything that was marked as obsolete in LAN Manager 2.x. In addition, there are some functions that no longer make sense in Windows NT, and those have been removed as well. Another set of functions has been folded into the Windows NT base or Win32 API.


  Functions with No 32-bit Net Equivalents

•	NetAlertStop, NetAlertStart

•	NetAuditWrite

•	NetBiosClose, NetBiosEnum, NetBiosGetInfo, NetBiosOpen, NetBiosSubmit

•	NetCharDev and NetCharDevQ

•	NetErrorLogWrite

•	NetLogonEnum

•	NetHandleGetInfo levels 2 and 3

•	NetMessageFileSend, NetMessageLogFileGet, NetMessageLogFileSet, NetMessageNameFwd, NetMessageNameUnFwd

•	NetRemoteCopy, NetRemoteExec, NetRemoteMove

•	NetServerAdminCommand

•	NetWkstaSetUID


  Functions That Only Have Support for Remoting to Downlevel

•	NetAccess functions

•	NetAudit functions

•	NetConfig functions

•	NetError functions


Requests from 16-Bit LANMan Clients
  Requests from 16-bit LAN Manager Clients

Windows NT provides support for most remote functions called from downlevel clients. However, the following calls are not supported when remoted from a downlevel client to a Windows NT server. In some of the following, there is a more current "2" version of the function that is supported (such as NetServerEnum).

•	NetFileEnum

•	NetFileGetInfo

•	NetFileClose

•	NetServerAdminCommand

•	NetAuditOpen

•	NetAuditClear

•	NetErrorLogOpen

•	NetErrorLogClear

•	NetMessageNameFwd

•	NetMessageNameUnFwd

•	NetMessageFileSend

•	NetMessageLogFileSet

•	NetMessageLogFileGet

•	NetUserAdd

•	NetUserSetInfo

•	NetWkstaSetUID

•	NetUseEnum

•	NetUseAdd

•	NetUseDel

•	NetUseGetInfo

•	NetProfileSave

•	NetProfileLoad

•	NetStatisticsGet

•	NetStatisticsClear

•	NetNetBiosEnum

•	NetNetBiosGetInfo

•	NetServerEnum

•	NetConfigGet2

•	NetConfigGetAll2

•	NetHandleGetInfo

•	NetHandleSetInfo

•	NetAuditRead

•	NetUserValidate2

•	NetAccessCheck

•	NetAlertRaise

•	NetAlertStart

•	NetAlertStop

•	NetAuditWrite

•	NetServiceStatus

•	DosPrintDriverEnum

•	DosPrintQProcessorEnum

•	DosPrintPortEnum

•	DosPrintDest

•	NetConfigSet


Calling 16-bit LANMan Servers
  Calling 16-bit LAN Manager Servers

When an RPC-based function fails to connect to the appropriate interface, the client-side stub may attempt to initiate a down-level function request to the server selected. For most of the Windows networking functions specified in this document, and any API where the functionality and data formats are changed only for 32-bit usage, the conversion is straightforward. For components that offer new functionality the caller of the function should generally be aware of the destination type. When the new function offers a superset of the functionality of the down-level station the same function is used for both destinations, but the new function fields must have either a reserved value of an associated field to inform the conversion layer the field may be ignored if going downlevel. This is required so that a function caller is not misled as to the action performed when the function was called.


Network Dynamic Data Exchange
 Network DDE

The Micrsoft® Win32® application programming interface (API) provides network dynamic data exchange (network DDE) services.


 About Network DDE

Dynamic data exchange lets a process establish data conversations with other processes executing on the same computer. Network DDE lets a process establish data conversations with other processes executing on other computers over a network.


 Network DDE Reference

The following functions and structures are associated with network dynamic data exchange.


 Network DDE Functions

Use these functions to implement network DDE functionality:

NDdeGetErrorString
NDdeGetShareSecurity
NDdeGetTrustedShare
NDdeIsValidAppTopicList
NDdeIsValidShareName
NDdeSetShareSecurity
NDdeSetTrustedShare
NDdeShareAdd
NDdeShareDel
NDdeShareEnum
NDdeShareGetInfo
NDdeShareSetInfo
NDdeTrustedShareEnum


 Network DDE Structures

Use this structure to implement network DDE functionality:

NDDESHAREINFO


 Windows Sockets


 Introduction to Windows Sockets


  What is Windows Sockets?

The Windows Sockets documentation defines a network programming interface for Microsoft® Windows® based on the "socket" paradigm popularized in the Berkeley Software Distribution (BSD) from the University of California at Berkeley. It encompasses both familiar Berkeley socket style routines and a set of Windows-specific extensions designed to allow the programmer to take advantage of the message-driven nature of Windows.

The Windows Sockets documentation is intended to provide a single application programming interface (API) to which application developers can program and multiple network software vendors can conform. Furthermore, in the context of a particular version of Microsoft Windows, it defines a binary interface (ABI) such that an application written using the Windows Sockets API can work with a conformant protocol implementation from any network software vendor. This specification thus defines the library calls and associated semantics to which an application developer can program and which a network software vendor can implement.

Network software that conforms to this Windows Sockets specification will be considered "Windows Sockets compliant." Suppliers of interfaces that are Windows Sockets compliant shall be referred to as "Windows Sockets Suppliers." To be Windows Sockets compliant, a vendor must implement 100% of this Windows Sockets specification.

Applications capable of operating with any Windows Sockets-compliant protocol implementation will be considered to have a "Windows Sockets Interface" and will be referred to as "Windows Sockets Applications."

This version of the Windows Sockets specification defines and documents the use of the API in conjunction with the Internet Protocol Suite (IPS, generally referred to as TCP/IP). Specifically, all Windows Sockets implementations support both stream (TCP) and datagram (UDP) sockets.

While the use of this API with alternative protocol stacks is not precluded (and is expected to be the subject of future revisions of the specification), such usage is beyond the scope of this version of the specification.


  Berkeley Sockets

The Windows Sockets Specification has been built on the Berkeley Sockets programming model, which is the de facto standard for TCP/IP networking. It is intended to provide a high degree of familiarity for programmers who are used to programming with sockets in UNIX and other environments, and to simplify the task of porting existing sockets-based source code. The Windows Sockets API is consistent with release 4.3 of the Berkeley Software Distribution (4.3BSD).

Portions of the Windows Sockets specification are derived from material that is Copyright © 1982-1986 by the Regents of the University of California. All rights are reserved. The Berkeley Software License Agreement specifies the terms and conditions for redistribution.


  Microsoft Windows and Windows-Specific Extensions

This API is intended to be usable within all implementations and versions of Microsoft Windows from Microsoft Windows version 3.0 onwards. It thus provides for Windows Sockets implementations and Windows Sockets applications in both 16- and 32-bit operating environments.

Windows Sockets makes provisions for multithreaded Windows processes. A process contains one or more threads of execution. In the Windows 3.1 non-multithreaded world, a task corresponds to a process with a single thread. All references to threads in this document refer to actual "threads" in multithreaded Windows environments. In non-multithreaded environments (such as Windows 3.0), use of the term "thread" refers to a Windows process.

The Microsoft Windows extensions included in Windows Sockets are provided to allow application developers to create software that conforms to the Windows programming model. It is expected that this will facilitate the creation of robust and high-performance applications, and will improve the cooperative multitasking of applications within nonpreemptive versions of Windows. With the exception of WSAStartup and WSACleanup, their use is not mandatory.


  The Status of This Specification

Windows Sockets is an independent specification that was created for the benefit of application developers and network vendors and, indirectly, computer users. Discussion of this documentation and suggested improvements continue and are welcomed. Such discussion occurs mainly via the Internet news group alt.winsock.


 Programming with Sockets


  Windows Sockets Stack Installation Checking

To detect the presence of one (or many) Windows Sockets implementations on a system, an application that has been linked with the Windows Sockets Import Library may simply call the WSAStartup function. A more sophisticated application can examine the $PATH environment variable and search for instances of Windows Sockets implementations (WINSOCK.DLL). For each instance, it can issue a LoadLibrary call and use the WSAStartup function to discover implementation-specific data.

This version of the Windows Sockets specification does not attempt to address explicitly the issue of multiple concurrent Windows Sockets implementations. Nothing in the specification should be interpreted as restricting multiple Windows Sockets DLLs from being present and used concurrently by one or more Windows Sockets applications.

For further details of where to obtain Windows Sockets components, see Windows Sockets Components.


  Sockets

The material in this guide is derived from the document "An Advanced 4.3BSD Interprocess Communication Tutorial," by Samuel J. Leffler, Robert S. Fabry, William N. Joy, Phil Lapsley, Steve Miller, and Chris Torek.


  Socket Basic Concepts

The basic building block for communication is the socket. A socket is an endpoint of communication to which a name can be bound. Each socket in use has a type and an associated process. Sockets exist within communication domains. A communication domain is an abstraction introduced to bundle common properties of threads communicating through sockets. Sockets typically exchange data only with sockets in the same domain (it may be possible to cross domain boundaries, but only if some translation process is performed). The Windows Sockets facilities support a single communication domain: the Internet domain, which is used by processes that communicate using the Internet Protocol Suite. (Future versions of this specification may include additional domains.)

Sockets are typed according to the communication properties visible to a user. Applications are presumed to communicate only between sockets of the same type, although there is nothing that prevents communication between sockets of different types should the underlying communication protocols support this.

Two types of sockets are currently available to a user. A stream socket provides for the bidirectional, reliable, sequenced, and unduplicated flow of data without record boundaries.

A datagram socket supports bidirectional flow of data that is not promised to be sequenced, reliable, or unduplicated. That is, a process receiving messages on a datagram socket may find messages duplicated, and possibly, in an order different from the order in which it was sent. An important characteristic of a datagram socket is that record boundaries in data are preserved. Datagram sockets closely model the facilities found in many contemporary packet-switched networks such as Ethernet.


  Client-Server Model

The paradigm most commonly used in constructing distributed applications is the client-server model. In this scheme, client applications request services from a server application. This implies an asymmetry in establishing communication between the client and server.

The client and server require a well-known set of conventions before service may be rendered (and accepted). These conventions constitute a protocol that must be implemented at both ends of a connection. Depending on the situation, the protocol may be symmetric or asymmetric. In a symmetric protocol, either side may play the master or slave roles. In an asymmetric protocol, one side is immutably recognized as the master, with the other as the slave. An example of a symmetric protocol is the TELNET protocol used in the Internet for remote terminal emulation. An example of an asymmetric protocol is the Internet file transfer protocol, FTP. No matter whether the specific protocol used in obtaining a service is symmetric or asymmetric, when accessing a service there is a "client process" and a "server process."

A server application typically listens at a well-known address for service requests. That is, the server process remains dormant until a connection is requested by a client's connection to the server's address. At such a time, the server process "wakes up" and services the client, performing whatever appropriate actions the client requests of it. While connection-based services are the norm, some services are based on the use of datagram sockets.


  Out-of-Band Data

Note  The following discussion of out-of-band data, also referred to as TCP Urgent data, follows the model used in the Berkeley software distribution. Users and implementors should be aware of the fact that there are at present two conflicting interpretations of RFC 793 (in which the concept is introduced), and that the implementation of out-of-band data in the Berkeley Software Distribution does not conform to the Host Requirements laid down in RFC 1122. To minimize interoperability problems, application developers are advised not to use out-of-band data unless this is required in order to interoperate with an existing service. Windows Sockets suppliers are urged to document the out-of-band semantics (BSD or RFC 1122) that their product implements. It is beyond the scope of this specification to mandate a particular set of semantics for out-of-band data handling.

The stream socket abstraction includes the notion of "out of band" data. Out-of-band data is a logically independent transmission channel associated with each pair of connected stream sockets. Out-of-band data is delivered to the user independently of normal data. The abstraction defines that the out-of-band data facilities must support the reliable delivery of at least one out-of-band message at a time. This message may contain at least one byte of data, and at least one message may be pending delivery to the user at any one time. For communications protocols that support only in-band signaling (that is, the urgent data is delivered in sequence with the normal data), the system typically extracts the data from the normal data stream and stores it separately. This allows users to choose between receiving the urgent data in order and receiving it out of sequence without having to buffer all the intervening data. It is possible to "peek" at out-of-band data.

An application may prefer to process out-of-band data "in-line," as part of the normal data stream. This is achieved by setting the socket option SO_OOBINLINE (see setsockopt). In this case, the application may wish to determine whether any of the unread data is "urgent" (the term usually applied to in-line out-of-band data). To facilitate this, the Windows Sockets implementation will maintain a logical "mark" in the data stream to indicate the point at which the out-of-band data was sent. An application can use the SIOCATMARK ioctlsocket command to determine whether there is any unread data preceding the mark. For example, the application might use this to resynchronize with its peer by ensuring that all data up to the mark in the data stream is discarded when appropriate.

The WSAAsyncSelect function is particularly well suited to handling notification of the presence of out-of-band data.


  Broadcasting

By using a datagram socket, it is possible to send broadcast packets on many networks supported by the system. The network itself must support broadcast: the system provides no simulation of broadcast in software. Broadcast messages can place a high load on a network, since they force every host on the network to service them. Consequently, the ability to send broadcast packets has been limited to sockets that are explicitly marked as allowing broadcasting. Broadcast is typically used for one of two reasons: it is needed to find a resource on a local network without prior knowledge of its address, or important functions such as routing require that information be sent to all accessible neighbors.

The destination address of the message to be broadcast depends on the network(s) on which the message is to be broadcast. The Internet domain supports a shorthand notation for broadcast on the local network, the address INADDR_BROADCAST. Received broadcast messages contain the sender's address and port, because datagram sockets must be bound before use.

Some types of network support the notion of different types of broadcast. For example, the IEEE 802.5 token ring architecture supports the use of link-level broadcast indicators, which control whether broadcasts are forwarded by bridges. The Windows Sockets specification does not provide any mechanism whereby an application can determine the type of underlying network, nor any way to control the semantics of broadcasting.


  Byte Ordering

The Intel byte ordering is like that of the DEC VAX™, and therefore differs from the Internet and 68000-type processor byte ordering. Thus, care must be taken to ensure correct orientation.

Any reference to IP addresses or port numbers passed to or from a Windows Sockets function must be in network order. This includes the IP address and port fields of a struct sockaddr_in (but not the sin_family field).

Consider an application that typically contacts a server on the TCP port corresponding to the "time" service, but provides a mechanism for the user to specify that an alternative port is to be used. The port number returned by getservbyname is already in network order, which is the format required when constructing an address, so no translation is required. However, if the user elects to use a different port, entered as an integer, the application must convert this from host order to network order (using the htons function) before using it to construct an address. Conversely, if the application is to display the number of the port within an address (returned using, for example, getpeername), the port number must be converted from network order to host order (using ntohs) before it can be displayed.

Since the Intel and Internet byte orders are different, the conversions described preceding are unavoidable. Application writers are cautioned that they should use the standard conversion functions provided as part of the Windows Sockets API rather than writing their own conversion code, since future implementations of Windows Sockets are likely to run on systems for which the host order is identical to the network byte order. Only applications that use the standard conversion functions are likely to be portable.


  Socket Options

The socket options supported by Windows Sockets are listed in setsockopt and getsockopt. A Windows Sockets implementation must recognize all of these options, and (for getsockopt) return plausible values for each. The default value for each option is shown in the following table.

Value	Type	Meaning	Default	Note
SO_ACCEPTCONN	BOOL	Socket is in listen mode.	FALSE unless a listen has been performed
SO_BROADCAST	BOOL	Socket is configured for the transmission of broadcast messages.	FALSE
SO_DEBUG	BOOL	Debugging is enabled.	FALSE	(i)
SO_DONTLINGER	BOOL	If true, the SO_LINGER option is disabled.	TRUE
SO_DONTROUTE	BOOL	Routing is disabled.	FALSE	(i)
SO_ERROR	int	Retrieve error status and clear.	0
SO_KEEPALIVE	BOOL	Keepalive messages are being sent.	FALSE
SO_LINGER	struct linger FAR *	Returns the current linger options.	l_onoff is 0
SO_OOBINLINE	BOOL	Out-of-band data is being received in the normal data stream.	FALSE
SO_RCVBUF	int	Buffer size for recv operations.	Implementation dependent	(i)
SO_REUSEADDR	BOOL	The address to which this socket is bound can be used by others.	FALSE
SO_SNDBUF	int	Buffer size for send operations.	Implementation dependent	(i)
SO_TYPE	int	The type of the socket (for example, SOCK_STREAM).	As created using socket
TCP_NODELAY	BOOL	Disables the Nagle algorithm for send coalescing.	Implementation dependent
Notes:

(i)  An implementation may silently ignore this option on setsockopt and return a constant value for getsockopt, or it may accept a value for setsockopt and return the corresponding value in getsockopt without using the value in any way.


  Database Files

The getXbyY and WSAAsyncGetXByY classes of routines are provided for retrieving network-specific information. (This specification uses the function name getXbyY to represent the set of routines gethostbyaddr, gethostbyname, and so on. Similarly WSAAsyncGetXByY represents WSAAsyncGetHostByAddr, and so on.) The getXbyY routines were originally designed (in the first Berkeley UNIX releases) as mechanisms for looking up information in text databases. Although the information may be retrieved by the Windows Sockets implementation in different ways, a Windows Sockets application requests such information in a consistent manner through either the getXbyY or the WSAAsyncGetXByY class of routines.


  Deviation from Berkeley Sockets

There are a few limited instances in which the Windows Sockets API has had to divert from strict adherence to the Berkeley conventions, usually because of difficulties of implementation in a Windows environment.


  Socket Data Type and Error Values

A new data type, SOCKET, has been defined. The definition of this type was necessary for future enhancements to the Windows Sockets specification, such as being able to use sockets as file handles in Windows NT. Definition of this type also facilitates porting applications to a Win32 environment, because the type will automatically be promoted from 16 to 32 bits.

In UNIX, all handles, including socket handles, are small, non-negative integers, and some applications make assumptions that this will be true. Windows Sockets handles have no restrictions, other than that the value INVALID_SOCKET is not a valid socket. Socket handles may take any value in the range 0 to INVALID_SOCKET − 1.

Because the SOCKET type is unsigned, compiling existing source code from, for example, a UNIX environment may lead to compiler warnings about signed/unsigned data type mismatches.

This means, for example, that checking for errors when the socket and accept routines return should not be done by comparing the return value with  − 1, or seeing if the value is negative (both approaches are common and legal in BSD). Instead, an application should use the manifest constant INVALID_SOCKET as defined in WINSOCK.H. For example:

TYPICAL BSD STYLE:

s = socket(...);

if (s == -1)    /* or s < 0 */

    {...}

PREFERRED STYLE:

s = socket(...);

if (s == INVALID_SOCKET)

    {...}


select and FD_*
  select and FD_XXX

Because a SOCKET is no longer represented by the UNIX-style "small non-negative integer," the implementation of the select function was changed in the Windows Sockets API. Each set of sockets is still represented by the fd_set type, but instead of being stored as a bitmask the set is implemented as an array of SOCKETs. To avoid potential problems, applications must adhere to the use of the FD_XXX macros to set, initialize, clear, and check the fd_set structures.


  Error Codes - errno, h_errno & WSAGetLastError

Error codes set by the Windows Sockets implementation are not made available via the errno variable. Additionally, for the getXbyY class of functions, error codes are NOT made available via the h_errno variable. Instead, error codes are accessed by using the WSAGetLastError . This function is provided in Windows Sockets as a precursor (and eventually an alias) for the Win32 function GetLastError. This is intended to provide a reliable way for a thread in a multithreaded process to obtain per-thread error information.

For compatibility with BSD, an application may choose to include a line of the form:

#define errno WSAGetLastError

This will allow networking code that was written to use the global errno to work correctly in a single-threaded environment. There are, obviously, some drawbacks. If a source file includes code that inspects errno for both socket and nonsocket functions, this mechanism cannot be used. Furthermore, it is not possible for an application to assign a new value to errno. (In Windows Sockets the function WSASetLastError can be used for this purpose.)

TYPICAL BSD STYLE:

r = recv(...);

if (r == -1

 && errno == EWOULDBLOCK)

    {...}

PREFERRED STYLE:

r = recv(...);

if (r == -1 /* (but see below) */

 && WSAGetLastError == EWOULDBLOCK)

    {...}

Although error constants consistent with 4.3 Berkeley Sockets are provided for compatibility purposes, applications should, where possible, use the "WSA" error code definitions. For example, a more accurate version of the preceding source code fragment is:

r = recv(...);

if (r == -1 /* (but see below) */

 && WSAGetLastError == WSAEWOULDBLOCK)

    {...}


  Pointers

All pointers used by applications with Windows Sockets should be FAR. To facilitate this, data type definitions such as LPHOSTENT are provided.


  Renamed Functions

In two cases it was necessary to rename functions that are used in Berkeley Sockets to avoid clashes with other functions.

close & closesocket

In Berkeley Sockets, sockets are represented by standard file descriptors, and so the close function can be used to close sockets as well as regular files. While nothing in Windows Sockets prevents an implementation from using regular file handles to identify sockets, nothing requires it either. Socket descriptors are not presumed to correspond to regular file handles, and file operations such as read, write, and close cannot be assumed to work correctly when applied to sockets. Sockets must be closed by using the closesocket function. Using the close function to close a socket is incorrect and the effects of doing so are undefined by this specification.

ioctl & ioctlsocket

Various C-language run-time systems use the ioctl function for purposes unrelated to Windows Sockets. For this reason we have defined the function ioctlsocket, which is used to handle socket functions that in the Berkeley Software Distribution are performed using ioctl and fcntl.


Blocking routines & EINPROGRESS
  Blocking Routines and EINPROGRESS

Although blocking operations on sockets are supported under Windows Sockets, their use is strongly discouraged. Programmers who are constrained to use blocking mode — for example, as part of an existing application that is to be ported — should be aware of the semantics of blocking operations in Windows Sockets. For more details, see Blocking/Nonblocking and Data Volatility.


  Maximum Number of Sockets Supported

The maximum number of sockets supported by a particular Windows Sockets supplier is implementation specific. An application should make no assumptions about the availability of a certain number of sockets. This topic is addressed further in WSAStartup. However, the number of sockets supported by a particular implementation is independent of the issue of the maximum number of sockets an application can actually make use of.

The maximum number of sockets a Windows Sockets application can make use of is determined at compile time by the manifest constant FD_SETSIZE. This value is used in constructing the fd_set structures used in select. The default value in WINSOCK.H is 64. If an application is designed to be capable of working with more than 64 sockets, the implementor should define the manifest FD_SETSIZE in every source file before including WINSOCK.H. One way of doing this is to include the definition within the compiler options in the makefile, for example adding -DFD_SETSIZE=128 as an option to the compiler command line for Microsoft C. It must be emphasized that defining FD_SETSIZE as a particular value has no effect on the actual number of sockets provided by a Windows Sockets implementation.


  Include Files

For ease of portability of existing Berkeley sockets based source code, a number of standard Berkeley include files are supported. However, these Berkeley header files merely include the WINSOCK.H include file, and it is therefore sufficient (and recommended) that Windows Sockets application source files should simply include WINSOCK.H.


  Return Values on Function Failure

The manifest constant SOCKET_ERROR is provided for checking function failure. Although use of this constant is not mandatory, it is recommended. The following example illustrates the use of the SOCKET_ERROR constant:

TYPICAL BSD STYLE:

r = recv(...);

if (r == -1     /* or r < 0 */

 && errno == EWOULDBLOCK)

    {...}

PREFERRED STYLE:

r = recv(...);

if (r == SOCKET_ERROR && WSAGetLastError == WSAEWOULDBLOCK)

    {...}


  Raw Sockets

The Windows Sockets specification does not mandate that a Windows Sockets DLL support raw sockets, that is, sockets opened with SOCK_RAW. However, a Windows Sockets DLL is allowed and encouraged to supply raw socket support. A Windows Sockets-compliant application that needs to use raw sockets should attempt to open the socket with the socket call, and if it fails either attempt to use another socket type or indicate the failure to the user.


  Windows Sockets in Multithreaded Versions of Windows

The Windows Sockets interface is designed to work for both single-threaded versions of Windows (such as Windows 3.1) and preemptive multithreaded versions of Windows (such as Windows NT). In a multithreaded environment the sockets interface is basically the same, but the author of a multithreaded application must be aware that it is the responsibility of the application, not the Windows Sockets implementation, to synchronize access to a socket between threads. This is the same rule that applies to other forms of I/O such as file I/O. Failure to synchronize calls on a socket leads to unpredictable results; for example if there are two simultaneous calls to send, there is no guarantee as to the order in which the data will be sent.

Closing a socket in one thread that has an outstanding blocking call on the same socket in another thread will cause the blocking call to fail with WSAEINTR, just as if the operation were canceled. This also applies if there is a select call outstanding and the application closes one of the sockets being selected.

There is no default blocking hook installed in preemptive multithreaded versions of Windows. This is because the computer will not be blocked if a single application is waiting for an operation to complete and hence not calling PeekMessage or GetMessage, which cause the application to yield in nonpreemptive Windows. However, for backwards compatibility, the WSASetBlockingHook call is implemented in multithreaded versions of Windows, and applications whose behavior depends on the default blocking hook can install their own blocking hook that duplicates the default hook's semantics.


  Socket Functions

In each routine it is indicated that the header file WINSOCK.H must be included. The Berkeley-compatible header files that are supported are provided for compatibility purposes only, and each of them will simply include WINSOCK.H. The Windows header file WINDOWS.H is also needed, but WINSOCK.H will include it if necessary.

The Windows Sockets specification includes the following Berkeley-style socket functions:

accept*	An incoming connection is acknowledged and associated with an immediately created socket. The original socket is returned to the listening state.
bind	Assign a local name to an unnamed socket.
closesocket*	Remove a socket from the per-process object reference table. Only blocks if SO_LINGER is set.
connect*	Initiate a connection on the specified socket.
getpeername	Retrieve the name of the peer connected to the specified socket.
getsockname	Retrieve the current name for the specified socket
getsockopt	Retrieve options associated with the specified socket.
htonl	Convert a 32-bit quantity from host byte order to network byte order.
htons	Convert a 16-bit quantity from host byte order to network byte order.
inet_addr	Converts a character string representing a number in the Internet standard "." notation to an Internet address value.
inet_ntoa	Converts an Internet address value to an ASCII string in "." notation (for example, "a.b.c.d").
ioctlsocket	Provide control for sockets.
listen	Listen for incoming connections on a specified socket.
ntohl	Convert a 32-bit quantity from network byte order to host byte order.
ntohs	Convert a 16-bit quantity from network byte order to host byte order.
recv*	Receive data from a connected socket.
recvfrom*	Receive data from either a connected or unconnected socket.
select*	Perform synchronous I/O multiplexing.
send*	Send data to a connected socket.
sendto*	Send data to either a connected or unconnected socket.
setsockopt	Store options associated with the specified socket.
shutdown	Shut down part of a full-duplex connection.
socket	Create an endpoint for communication and return a socket.
* The function can block if acting on a blocking socket.


  Blocking/Nonblocking and Data Volatility

One major issue in porting applications from a Berkeley sockets environment to a Windows environment involves "blocking"; that is, invoking a function that does not return until the associated operation is completed. The problem arises if the operation takes an arbitrarily long time to complete: an obvious example is a recv that may block until data has been received from the peer system. The default behavior within the Berkeley sockets model is for a socket to operate in a blocking mode unless the programmer explicitly requests that operations be treated as nonblocking.

Note  It is strongly recommended that programmers use the nonblocking (asynchronous) operations if at all possible, because they work significantly better within the nonpreemptive Windows environment. Use blocking operations only if absolutely necessary, and carefully read and understand this topic if you must use blocking operations.

Even on a blocking socket, some operations (for example, bind, getsockopt, getpeername) can be completed immediately. For such operations there is no difference between blocking and nonblocking operation. Other operations (for example, recv) may be completed immediately or may take an arbitrary time to complete, depending on various transport conditions. When applied to a blocking socket, these operations are referred to as blocking operations. All functions that can block are listed with an asterisk in the tables in Socket Functions and Socket Database Functions.

Within a Windows Sockets implementation, a blocking operation that cannot be completed immediately is handled as follows. The DLL initiates the operation, and then enters a loop in which it dispatches any Windows messages (yielding the processor to another thread if necessary) and then checks for the completion of the Windows Sockets function. If the function has completed, or if WSACancelBlockingCall has been invoked, the blocking function completes with an appropriate result. Refer to WSASetBlockingHook for a complete description of this mechanism, including pseudocode for the various functions.

If a Windows message is received for a process for which a blocking operation is in progress, there is a risk that the application will attempt to issue another Windows Sockets call. Because of the difficulty of managing this condition safely, the Windows Sockets specification does not support such application behavior. Two functions are provided to assist you in this situation. WSAIsBlocking may be called to determine whether or not a blocking Windows Sockets call is in progress. WSACancelBlockingCall may be called to cancel an in-progress blocking call, if any. Any other Windows Sockets function that is called in this situation will fail with the error WSAEINPROGRESS. It should be emphasized that this restriction applies to both blocking and nonblocking operations.

Although this mechanism is sufficient for simple applications, it cannot support the complex message-dispatching requirements of more advanced applications (for example, those using the MDI model). For such applications, Windows Sockets includes the function WSASetBlockingHook, which allows the programmer to define a special function that will be called instead of the default message dispatch function previously described.

The Windows Sockets DLL calls the blocking hook only if all of the following are true: the function is one that is defined as being able to block, the specified socket is a blocking socket, and the request cannot be completed immediately. (A socket is set to blocking by default, but the IOCTL FIONBIO and WSAAsyncSelect both set a socket to nonblocking mode.) If an application uses only nonblocking sockets and uses the WSAAsyncSelect and/or the WSAAsyncGetXByY routines instead of select and the getXbyY routines, then the blocking hook will never be called and the application does not need to handle reentrancy.

If an application invokes an asynchronous or nonblocking operation that takes a pointer to a memory object (for example, a buffer, or a global variable) as an argument, the application must ensure that the object is available to the Windows Sockets implementation throughout the operation. The application must not invoke any Windows function that might affect the mapping or addressability of the memory involved. In a multithreaded system, the application is also responsible for coordinating access to the object using appropriate synchronization mechanisms. A Windows Sockets implementation cannot, and will not, address these issues. The possible consequences of failing to observe these rules are beyond the scope of this specification.


  Socket Database Functions

The Windows Sockets specification defines the following database functions. As noted earlier, a Windows Sockets supplier may choose to implement these in a manner that does not depend on local database files. The pointer returned by certain database functions such as gethostbyname points to a structure allocated by the Windows Sockets library. The data pointed to is volatile and is good only until the next Windows Sockets function call from that thread. Additionally, the application must never attempt to modify this structure or to free any of its components. Only one copy of this structure is allocated for a thread, and so the application should copy any information it needs before issuing any other Windows Sockets function calls.

gethostbyaddr*	Retrieves the name(s) and address corresponding to a network address.
gethostbyname*	Retrieves the name(s) and address corresponding to a host name.
gethostname	Retrieves the name of the local host.
getprotobyname*	Retrieves the protocol name and number corresponding to a protocol name.
getprotobynumber*	Retrieves the protocol name and number corresponding to a protocol number.
getservbyname*	Retrieves the service name and port corresponding to a service name.
getservbyport*	Retrieves the service name and port corresponding to a port.
* The function can block under some circumstances.


  Microsoft Windows-Specific Extension Functions

Windows Sockets provides a number of extensions to the standard set of Berkeley Sockets functions. Principally, these extended functions allow message-based, asynchronous access to network events. While use of this extended function set is not mandatory for socket-based programming (with the exception of WSAStartup and WSACleanup), it is recommended for conformance with the Microsoft Windows programming paradigm.

The following functions provide asynchronous versions of the standard Berkeley getXbyY functions. For example, the WSAAsyncGetHostByName function provides an asynchronous message-based implementation of the standard Berkeley gethostbyname function.

WSAAsyncGetHostByAddr

WSAAsyncGetHostByName

WSAAsyncGetProtoByName

WSAAsyncGetProtoByNumber

WSAAsyncGetServByName

WSAAsyncGetServByPort

WSAAsyncSelect	Performs asynchronous version of select.
WSACancelAsyncRequest	Cancels an outstanding instance of a WSAAsyncGetXByY function.
WSACancelBlockingCall	Cancels an outstanding "blocking" function call.
WSACleanup	Signs off from the underlying Windows Sockets DLL.
WSAGetLastError	Obtains details of last Windows Sockets function error.
WSAIsBlocking	Determines if the underlying Windows Sockets DLL is already blocking an existing call for this thread.
WSASetBlockingHook	"Hooks" the blocking method used by the underlying Windows Sockets implementation.
WSASetLastError	Sets the error to be returned by a subsequent call to WSAGetLastError.
WSAStartup	Initializes the underlying Windows Sockets DLL.
WSAUnhookBlockingHook	Restores the original blocking function.


  Asynchronous Select Mechanism

The WSAAsyncSelect function allows an application to register an interest in one or many network events. This function is provided to supersede the need to do polled network I/O. Any situation in which select or nonblocking I/O routines (such as send and recv) are either already used or are being considered is usually a candidate for the WSAAsyncSelect function. When declaring interest in such condition(s), you supply a window handle to be used for notification. The corresponding window then receives message-based notification of the conditions in which you declared an interest.

WSAAsyncSelect allows interest to be declared in the following conditions for a particular socket:

•	Socket readiness for reading

•	Socket readiness for writing

•	Out-of-band data ready for reading

•	Socket readiness for accepting incoming connection

•	Completion of nonblocking connect operation

•	Connection closure


  Asynchronous Support Routines

The asynchronous "database" functions allow applications to request information in an asynchronous manner. Some network implementations or configurations perform network-based operations to resolve such requests. The WSAAsyncGetXByY functions allow application developers to request services that would otherwise block the operation of the whole Windows environment if the standard Berkeley function were used. The WSACancelAsyncRequest function allows an application to cancel any outstanding asynchronous request.


  Hooking Blocking Methods

As noted in Blocking/Nonblocking and Data Volatility, Windows Sockets implements blocking operations in such a way that Windows message processing can continue, which may result in the application that issued the call receiving a Windows message. In certain situations, an application may need to influence or change the way in which this pseudo-blocking process is implemented. The WSASetBlockingHook function provides the ability to substitute a named function that the Windows Sockets implementation is to use when relinquishing the processor during a "blocking" operation.


  Error Handling

For compatibility with thread-based environments, details of function errors are obtained through the WSAGetLastError function. Although the accepted Berkeley-style mechanism for obtaining socket-based network errors is by using errno, this mechanism cannot guarantee the integrity of an error ID in a multithreaded environment. WSAGetLastError allows you to retrieve an error code on a per-thread basis.

WSAGetLastError returns error codes that avoid conflict with standard Microsoft C error codes. Certain error codes returned by certain Windows Sockets routines fall into the standard range of error codes as defined by Microsoft C. If you are NOT using an application development environment that defines error codes consistent with Microsoft C, you should use the Windows Sockets error codes prefixed by "WSA" to ensure accurate error code detection.

Note that this specification defines a recommended set of error codes, and lists the possible errors that may be returned as a result of each function. It may be the case in some implementations that other Windows Sockets error codes will be returned in addition to those listed, and applications should be prepared to handle errors other than those enumerated under each function description. However, a Windows Sockets implementation must not return any value that is not enumerated in the table of legal Windows Sockets errors given in Error Codes.


Accessing a Windows Sockets DLL from an Intermediate DLL
  Accessing a Windows Sockets DLL from an Intermediate DLL (16-bit Applications)

A Windows Sockets DLL can be accessed both directly from an application and through an "intermediate" DLL. An example of such an intermediate DLL would be a virtual network API layer that supports generalized network functionality for applications and uses Windows Sockets. Such a DLL could be used by several applications simultaneously, and the DLL must take special precautions with respect to the WSAStartup and WSACleanup calls to ensure that these routines are called in the context of each task that will make Windows Sockets calls. This is because the Windows Sockets DLL will need a call to WSAStartup for each task in order to set up task-specific data structures, and a call to WSACleanup to free any resources allocated for the task.

There are (at least) two ways to accomplish this. The simplest method is for the intermediate DLL to have calls similar to WSAStartup and WSACleanup that applications call as appropriate. The DLL would then call WSAStartup or WSACleanup from within these routines. Another mechanism is for the intermediate DLL to build a table of task handles, which are obtained from the GetCurrentTask Windows function, and at each entry point into the intermediate DLL check whether WSAStartup has been called for the current task, then call WSAStartup if necessary.

If a DLL makes a blocking call and does not install its own blocking hook, then the DLL author must be aware that control may be returned to the application either by an application-installed blocking hook or by the default blocking hook. Thus, it is possible that the application will cancel the DLL's blocking operation via WSACancelBlockingCall. If this occurs, the DLL's blocking operation will fail with the error code WSAEINTR, and the DLL must return control to the calling task as quickly as possible, because the user has likely pressed a Cancel or Close button and the task has requested control of the CPU. It is recommended that DLLs that make blocking calls install their own blocking hooks with WSASetBlockingHook to prevent unforeseen interactions between the application and the DLL.

Note that this is not necessary for DLLs in Windows NT because of its different process and DLL structure. Under Windows NT, the intermediate DLL could simply call WSAStartup in its DLL initialization routine, which is called whenever a new process which uses the DLL starts.


  Internal Use of Messages by Windows Sockets Implementations

To implement Windows Sockets purely as a DLL, it may be necessary for the DLL to post messages internally for communication and timing. This is perfectly legal; however, a Windows Sockets DLL must not post messages to a window handle opened by a client application except for those messages requested by the application. A Windows Sockets DLL that needs to use messages for its own purposes must open a hidden window and post any necessary messages to the handle for that window.


  Private API Interfaces

The WINSOCK.DEF file in DLL Ordinal Numbers lists the ordinals defined for the Windows Sockets functions. In addition to the ordinal values listed, all ordinals 999 and below are reserved for future Windows Sockets use. It may be convenient for a Windows Sockets implementation to export additional, private interfaces from the Windows Sockets DLL. This is perfectly acceptable, as long as the ordinals for these exports are above 1000. Note that any application that uses a particular Windows Sockets DLL's private functions will most likely not work on any other vendor's Windows Sockets implementation. Only the functions defined in this document are guaranteed to be present in every Windows Sockets implementation.

If an application uses private interfaces of a particular vendor's Windows Sockets DLL, it is recommended that the DLL not be statically linked with the application but rather dynamically loaded with the Windows routines LoadLibrary and GetProcAddress. This allows the application to give an informative error message if it is run on a system with a Windows Sockets DLL that does not support the same set of extended functionality.


  Error Codes and Header Files

The following topics list the error codes and header files.

Error Codes

Header Files


  Error Codes

The following is a list of possible error codes returned by the WSAGetLastError function, along with their explanations. The error numbers are consistently set across all Windows Sockets-compliant implementations.

Windows Sockets code	Berkeley equivalent	Error	Interpretation
WSAEINTR	EINTR	10004	As in standard C
WSAEBADF	EBADF	10009	As in standard C
WSAEACCES	EACCES	10013	As in standard C
WSAEDISCON	None	10101	The message terminated gracefully. Used only for message-oriented protocols.
WSAEFAULT	EFAULT	10014	As in standard C
WSAEINVAL	EINVAL	10022	As in standard C
WSAEMFILE	EMFILE	10024	As in standard C
WSAEWOULDBLOCK	EWOULDBLOCK	10035	As in BSD
WSAEINPROGRESS	EINPROGRESS	10036	This error is returned if anyWindows Sockets function is called while a blocking function is in progress.
WSAEALREADY	EALREADY	10037	As in BSD
WSAENOTSOCK	ENOTSOCK	10038	As in BSD
WSAEDESTADDRREQ	EDESTADDRREQ	10039	As in BSD
WSAEMSGSIZE	EMSGSIZE	10040	As in BSD
WSAEPROTOTYPE	EPROTOTYPE	10041	As in BSD
WSAENOPROTOOPT	ENOPROTOOPT	10042	As in BSD
WSAEPROTONOSUPPORT	EPROTONOSUPPORT	10043	As in BSD
WSAESOCKTNOSUPPORT	ESOCKTNOSUPPORT	10044	As in BSD
WSAEOPNOTSUPP	EOPNOTSUPP	10045	As in BSD
WSAEPFNOSUPPORT	EPFNOSUPPORT	10046	As in BSD
WSAEAFNOSUPPORT	EAFNOSUPPORT	10047	As in BSD
WSAEADDRINUSE	EADDRINUSE	10048	As in BSD
WSAEADDRNOTAVAIL	EADDRNOTAVAIL	10049	As in BSD
WSAENETDOWN	ENETDOWN	10050	As in BSD. This error may be reported at any time if the Windows Sockets implementation detects an underlying failure.
WSAENETUNREACH	ENETUNREACH	10051	As in BSD
WSAENETRESET	ENETRESET	10052	As in BSD
WSAECONNABORTED	ECONNABORTED	10053	As in BSD
WSAECONNRESET	ECONNRESET	10054	As in BSD
WSAENOBUFS	ENOBUFS	10055	As in BSD
WSAEISCONN	EISCONN	10056	As in BSD
WSAENOTCONN	ENOTCONN	10057	As in BSD
WSAESHUTDOWN	ESHUTDOWN	10058	As in BSD
WSAETOOMANYREFS	ETOOMANYREFS	10059	As in BSD
WSAETIMEDOUT	ETIMEDOUT	10060	As in BSD
WSAECONNREFUSED	ECONNREFUSED	10061	As in BSD
WSAELOOP	ELOOP	10062	As in BSD
WSAENAMETOOLONG	ENAMETOOLONG	10063	As in BSD
WSAEHOSTDOWN	EHOSTDOWN	10064	As in BSD
WSAEHOSTUNREACH	EHOSTUNREACH	10065	As in BSD
WSASYSNOTREADY	None	10091	Returned by WSAStartup, indicating that the network subsystem is unusable.
WSAVERNOTSUPPORTED	None	10092	Returned by WSAStartup, indicating that the Windows Sockets DLL cannot support this app.
WSANOTINITIALISED	None	10093	Returned by any function except WSAStartup, indicating that a successful WSAStartup, has not yet been performed.
WSAHOST_NOT_FOUND	HOST_NOT_FOUND	11001	As in BSD
WSATRY_AGAIN	TRY_AGAIN	11002	As in BSD
WSANO_RECOVERY	NO_RECOVERY	11003	As in BSD
WSANO_DATA	NO_DATA	11004	As in BSD
The first set of definitions is present to resolve contentions between standard C error codes, which may be defined inconsistently between various C compilers.

The second set of definitions provides Windows Sockets versions of regular Berkeley Sockets error codes.

The third set of definitions consists of extended Windows Sockets-specific error codes.

The fourth set of errors are returned by Windows Sockets getXbyY and WSAAsyncGetXByY functions, and correspond to the errors that in Berkeley software would be returned in the h_errno variable. They correspond to various failures that may be returned by the Domain Name Service. If the Windows Sockets implementation does not use the DNS, it will use the most appropriate code. In general, a Windows Sockets application should interpret WSAHOST_NOT_FOUND and WSANO_DATA as indicating that the key (name, address, and so on) was not found, while WSATRY_AGAIN and WSANO_RECOVERY suggest that the name service itself is nonoperational.

The error numbers are derived from the WINSOCK.H header file and are based on the fact that Windows Sockets error numbers are computed by adding 10000 to the "normal" Berkeley error number.

Note that this table does not include all of the error codes defined in WINSOCK.H. This is because it includes only errors that might reasonably be returned by a Windows Sockets implementation. WINSOCK.H, on the other hand, includes a full set of BSD definitions to ensure compatibility with ported software.


 Header Files


  Berkeley Header Files

A Windows Sockets supplier who provides a development kit to support the development of Windows Sockets applications must supply a set of vestigial header files with names that match a number of the header files in the Berkeley software distribution. These files are provided for source code compatibility only, and each consists of three lines:

#ifndef _WINSOCKAPI_

#include <winsock.h>

#endif

The header files provided for compatibility are:

NETDB.H
ARPA/INET.H
SYS/TIME.H
SYS/SOCKET.H
NETINET/IN.H

The file WINSOCK.H contains all of the type and structure definitions, constants, macros, and function prototypes used by the Windows Sockets specification. You may choose to ignore the compatibility headers and include WINSOCK.H in each source file.


Windows Sockets Header File - winsock.h
  Windows Sockets Header File — WINSOCK.H

The WINSOCK.H header file includes a number of types and definitions from the standard Windows header file WINDOWS.H. The WINDOWS.H file in the Windows 3.0 SDK (Software Developer's Kit) lacks a #include guard, so if you need to include WINDOWS.H as well as WINSOCK.H, you should define the symbol _INC_WINDOWS before #including WINSOCK.H, as follows:

#include <windows.h>

#define _INC_WINDOWS

#include <winsock.h>

Users of the SDK for Windows 3.1 and later need not do this.

A Windows Sockets DLL vendor must not make any modifications to this header file that could impact binary compatibility of Windows Sockets applications. The constant values, function parameters, return codes, and the like must remain consistent across all Windows Sockets DLL vendors.

/* WINSOCK.H--definitions to be used with the WINSOCK.DLL

 *

 * This header file corresponds to version 1.1 of the Windows Sockets specification.

 *

 * This file includes parts which are Copyright (c) 1982-1986 Regents

 * of the University of California. All rights reserved. The

 * Berkeley Software License Agreement specifies the terms and

 * conditions for redistribution.

 */

#ifndef _WINSOCKAPI_

#define _WINSOCKAPI_

/*

 * Pull in WINDOWS.H if necessary

 */

#ifndef _INC_WINDOWS

#include <windows.h>

#endif /* _INC_WINDOWS */

/*

 * Basic system type definitions, taken from the BSD file sys/types.h.

 */

typedef unsigned char u_char;

typedef unsigned short u_short;

typedef unsigned int u_int;

typedef unsigned long u_long;

/*

 * The new type to be used in all

 * instances which refer to sockets.

 */

typedef u_int  SOCKET;

/*

 * Select uses arrays of SOCKETs. These macros manipulate such

 * arrays. FD_SETSIZE may be defined by the user before including

 * this file, but the default here should be >= 64.

 *

 * CAVEAT IMPLEMENTOR and USER: THESE MACROS AND TYPES MUST BE

 * INCLUDED IN WINSOCK.H EXACTLY AS SHOWN HERE.

 */

#ifndef FD_SETSIZE

#define FD_SETSIZE 64

#endif /* FD_SETSIZE */

typedef struct fd_set {

 u_short fd_count;  /* how many are SET? */

 SOCKET fd_array[FD_SETSIZE]; /* an array of SOCKETs */

} fd_set;

extern int PASCAL FAR __WSAFDIsSet(SOCKET, fd_set FAR *);

#define FD_CLR(fd, set) do { \

 u_int __i; \

 for (__i = 0; __i < ((fd_set FAR *)(set))->fd_count ; __i++) { \

 if (((fd_set FAR *)(set))->fd_array[__i] == fd) { \

  while (__i < ((fd_set FAR *)(set))->fd_count-1) { \

  ((fd_set FAR *)(set))->fd_array[__i] = \

   ((fd_set FAR *)(set))->fd_array[__i+1]; \

  __i++; \

  } \

  ((fd_set FAR *)(set))->fd_count--; \

  break; \

 } \

 } \

} while(0)

#define FD_SET(fd, set) do { \

 if (((fd_set FAR *)(set))->fd_count < FD_SETSIZE) \

 ((fd_set FAR *)(set))->fd_array[((fd_set FAR *)(set))->fd_count++]=fd;\

} while(0)

#define FD_ZERO(set) (((fd_set FAR *)(set))->fd_count=0)

#define FD_ISSET(fd, set) __WSAFDIsSet((SOCKET)fd, (fd_set FAR *)set)

/*

 * Structure used in select call, taken from the BSD file sys/time.h.

 */

struct timeval {

 long tv_sec;  /* seconds */

 long tv_usec; /* and microseconds */

};

/*

 * Operations on timevals.

 *

 * NB: timercmp does not work for >= or <=.

 */

#define timerisset(tvp)  ((tvp)->tv_sec || (tvp)->tv_usec)

#define timercmp(tvp, uvp, cmp) \

 ((tvp)->tv_sec cmp (uvp)->tv_sec || \

  (tvp)->tv_sec == (uvp)->tv_sec && (tvp)->tv_usec cmp (uvp)->tv_usec)

#define timerclear(tvp)  (tvp)->tv_sec = (tvp)->tv_usec = 0

/*

 * Commands for ioctlsocket, taken from the BSD file fcntl.h.

 *

 *

 * Ioctl's have the command encoded in the lower word,

 * and the size of any in or out parameters in the upper

 * word. The high 2 bits of the upper word are used

 * to encode the in/out status of the parameter; for now

 * we restrict parameters to at most 128 bytes.

 */

#define IOCPARM_MASK 0x7f  /* parameters must be < 128 bytes */

#define IOC_VOID 0x20000000 /* no parameters */

#define IOC_OUT  0x40000000 /* copy out parameters */

#define IOC_IN  0x80000000 /* copy in parameters */

#define IOC_INOUT (IOC_IN|IOC_OUT)

     /* 0x20000000 distinguishes new &

      old ioctl's */

#define _IO(x,y) (IOC_VOID|(x<<8)|y)

#define _IOR(x,y,t) (IOC_OUT|(((long)sizeof(t)&IOCPARM_MASK)<<16)|(x<<8)|y)

#define _IOW(x,y,t) (IOC_IN|(((long)sizeof(t)&IOCPARM_MASK)<<16)|(x<<8)|y)

#define FIONREAD _IOR('f', 127, u_long) /* get # bytes to read */

#define FIONBIO _IOW('f', 126, u_long) /* set/clear non-blocking i/o */

#define FIOASYNC _IOW('f', 125, u_long) /* set/clear async i/o */

/* Socket I/O Controls */

#define SIOCSHIWAT _IOW('s', 0, u_long) /* set high watermark */

#define SIOCGHIWAT _IOR('s', 1, u_long) /* get high watermark */

#define SIOCSLOWAT _IOW('s', 2, u_long) /* set low watermark  */

#define SIOCGLOWAT _IOR('s', 3, u_long) /* get low watermark  */

#define SIOCATMARK _IOR('s', 7, u_long) /* at oob mark?       */

/*

 * Structures returned by network database library, taken from the

 * BSD file netdb.h. All addresses are supplied in host order, and

 * returned in network order (suitable for use in system calls).

 */

struct hostent {

 char FAR * h_name;            /* official name of host        */

 char FAR * FAR * h_aliases;   /* alias list                   */

 short h_addrtype;             /* host address type            */

 short h_length;               /* length of address            */

 char FAR * FAR * h_addr_list; /* list of addresses            */

#define h_addr h_addr_list[0]  /* address, for backward compat */

};

/*

 * It is assumed here that a network number

 * fits in 32 bits.

 */

struct netent {

 char FAR * n_name;  /* official name of net */

 char FAR * FAR * n_aliases; /* alias list */

 short n_addrtype;  /* net address type */

 u_long n_net;   /* network # */

};

struct servent {

 char FAR * s_name;  /* official service name */

 char FAR * FAR * s_aliases; /* alias list */

 short s_port;   /* port # */

 char FAR * s_proto;  /* protocol to use */

};

struct protoent {

 char FAR * p_name;  /* official protocol name */

 char FAR * FAR * p_aliases; /* alias list */

 short p_proto;  /* protocol # */

};

/*

 * Constants and structures defined by the Internet system,

 * Per RFC 790, September 1981, taken from the BSD file netinet/in.h.

 */

/*

 * Protocols

 */

#define IPPROTO_IP  0  /* dummy for IP */

#define IPPROTO_ICMP  1  /* control message protocol */

#define IPPROTO_GGP  2  /* gateway^2 (deprecated) */

#define IPPROTO_TCP  6  /* tcp */

#define IPPROTO_PUP  12  /* pup */

#define IPPROTO_UDP  17  /* user datagram protocol */

#define IPPROTO_IDP  22  /* xns idp */

#define IPPROTO_ND  77  /* UNOFFICIAL net disk proto */

#define IPPROTO_RAW  255  /* raw IP packet */

#define IPPROTO_MAX  256

/*

 * Port/socket numbers: network standard functions

 */

#define IPPORT_ECHO  7

#define IPPORT_DISCARD  9

#define IPPORT_SYSTAT  11

#define IPPORT_DAYTIME  13

#define IPPORT_NETSTAT  15

#define IPPORT_FTP  21

#define IPPORT_TELNET  23

#define IPPORT_SMTP  25

#define IPPORT_TIMESERVER 37

#define IPPORT_NAMESERVER 42

#define IPPORT_WHOIS  43

#define IPPORT_MTP  57

/*

 * Port/socket numbers: host specific functions

 */

#define IPPORT_TFTP  69

#define IPPORT_RJE  77

#define IPPORT_FINGER  79

#define IPPORT_TTYLINK  87

#define IPPORT_SUPDUP  95

/*

 * UNIX TCP sockets

 */

#define IPPORT_EXECSERVER 512

#define IPPORT_LOGINSERVER 513

#define IPPORT_CMDSERVER 514

#define IPPORT_EFSSERVER 520

/*

 * UNIX UDP sockets

 */

#define IPPORT_BIFFUDP  512

#define IPPORT_WHOSERVER 513

#define IPPORT_ROUTESERVER 520

     /* 520+1 also used */

/*

 * Ports < IPPORT_RESERVED are reserved for

 * privileged processes (e.g. root).

 */

#define IPPORT_RESERVED  1024

/*

 * Link numbers

 */

#define IMPLINK_IP  155

#define IMPLINK_LOWEXPER 156

#define IMPLINK_HIGHEXPER 158

/*

 * Internet address (old style... should be updated)

 */

struct in_addr {

 union {

  struct { u_char s_b1,s_b2,s_b3,s_b4; } S_un_b;

  struct { u_short s_w1,s_w2; } S_un_w;

  u_long S_addr;

 } S_un;

#define s_addr S_un.S_addr

    /* can be used for most tcp & ip code */

#define s_host S_un.S_un_b.s_b2

    /* host on imp */

#define s_net S_un.S_un_b.s_b1

    /* network */

#define s_imp S_un.S_un_w.s_w2

    /* imp */

#define s_impno S_un.S_un_b.s_b4

    /* imp # */

#define s_lh S_un.S_un_b.s_b3

    /* logical host */

};

/*

 * Definitions of bits in internet address integers.

 * On subnets, the decomposition of addresses to host and net parts

 * is done according to subnet mask, not the masks here.

 */

#define IN_CLASSA(i)  (((long)(i) & 0x80000000) == 0)

#define IN_CLASSA_NET  0xff000000

#define IN_CLASSA_NSHIFT 24

#define IN_CLASSA_HOST  0x00ffffff

#define IN_CLASSA_MAX  128

#define IN_CLASSB(i)  (((long)(i) & 0xc0000000) == 0x80000000)

#define IN_CLASSB_NET  0xffff0000

#define IN_CLASSB_NSHIFT 16

#define IN_CLASSB_HOST  0x0000ffff

#define IN_CLASSB_MAX  65536

#define IN_CLASSC(i)  (((long)(i) & 0xc0000000) == 0xc0000000)

#define IN_CLASSC_NET  0xffffff00

#define IN_CLASSC_NSHIFT 8

#define IN_CLASSC_HOST  0x000000ff

#define INADDR_ANY  (u_long)0x00000000

#define INADDR_LOOPBACK  0x7f000001

#define INADDR_BROADCAST (u_long)0xffffffff

#define INADDR_NONE  0xffffffff

/*

 * Socket address, internet style.

 */

struct sockaddr_in {

 short sin_family;

 u_short sin_port;

 struct in_addr sin_addr;

 char sin_zero[8];

};

#define WSADESCRIPTION_LEN 256

#define WSASYS_STATUS_LEN 128

typedef struct WSAData {

 WORD   wVersion;

 WORD   wHighVersion;

 char   szDescription[WSADESCRIPTION_LEN+1];

 char   szSystemStatus[WSASYS_STATUS_LEN+1];

 unsigned short  iMaxSockets;

 unsigned short  iMaxUdpDg;

 char FAR *  lpVendorInfo;

} WSADATA;

typedef WSADATA FAR *LPWSADATA;

/*

 * Options for use with [gs]etsockopt at the IP level.

 */

#define IP_OPTIONS 1  /* set/get IP per-packet options */

/*

 * Definitions related to sockets: types, address families, options,

 * taken from the BSD file sys/socket.h.

 */

/*

 * This is used instead of -1, since the

 * SOCKET type is unsigned.

 */

#define INVALID_SOCKET (SOCKET)(~0)

#define SOCKET_ERROR  (-1)

/*

 * Types

 */

#define SOCK_STREAM 1  /* stream socket */

#define SOCK_DGRAM 2  /* datagram socket */

#define SOCK_RAW 3  /* raw-protocol interface */

#define SOCK_RDM 4  /* reliably-delivered message */

#define SOCK_SEQPACKET 5  /* sequenced packet stream */

/*

 * Option flags per-socket.

 */

#define SO_DEBUG 0x0001  /* turn on debugging info recording */

#define SO_ACCEPTCONN 0x0002  /* socket has had listen */

#define SO_REUSEADDR 0x0004  /* allow local address reuse */

#define SO_KEEPALIVE 0x0008  /* keep connections alive */

#define SO_DONTROUTE 0x0010  /* just use interface addresses */

#define SO_BROADCAST 0x0020  /* permit sending of broadcast msgs */

#define SO_USELOOPBACK 0x0040  /* bypass hardware when possible */

#define SO_LINGER 0x0080  /* linger on close if data present */

#define SO_OOBINLINE 0x0100  /* leave received OOB data in line */

#define SO_DONTLINGER (u_int)(~SO_LINGER)

/*

 * Additional options.

 */

#define SO_SNDBUF 0x1001  /* send buffer size */

#define SO_RCVBUF 0x1002  /* receive buffer size */

#define SO_SNDLOWAT 0x1003  /* send low-water mark */

#define SO_RCVLOWAT 0x1004  /* receive low-water mark */

#define SO_SNDTIMEO 0x1005  /* send timeout */

#define SO_RCVTIMEO 0x1006  /* receive timeout */

#define SO_ERROR 0x1007  /* get error status and clear */

#define SO_TYPE  0x1008  /* get socket type */

/*

 * TCP options.

 */

#define TCP_NODELAY 0x0001

/*

 * Address families.

 */

#define AF_UNSPEC 0  /* unspecified */

#define AF_UNIX  1  /* local to host (pipes, portals) */

#define AF_INET  2  /* internetwork: UDP, TCP, etc. */

#define AF_IMPLINK 3  /* arpanet imp addresses */

#define AF_PUP  4  /* pup protocols: e.g. BSP */

#define AF_CHAOS 5  /* mit CHAOS protocols */

#define AF_NS  6  /* XEROX NS protocols */

#define AF_ISO  7  /* ISO protocols */

#define AF_OSI  AF_ISO  /* OSI is ISO */

#define AF_ECMA  8  /* european computer manufacturers */

#define AF_DATAKIT 9  /* datakit protocols */

#define AF_CCITT 10  /* CCITT protocols, X.25 etc */

#define AF_SNA  11  /* IBM SNA */

#define AF_DECnet 12  /* DECnet */

#define AF_DLI  13  /* Direct data link interface */

#define AF_LAT  14  /* LAT */

#define AF_HYLINK 15  /* NSC Hyperchannel */

#define AF_APPLETALK 16  /* AppleTalk */

#define AF_NETBIOS 17  /* NetBios-style addresses */

#define AF_MAX  18

/*

 * Structure used by kernel to store most

 * addresses.

 */

struct sockaddr {

 u_short sa_family;  /* address family */

 char sa_data[14];  /* up to 14 bytes of direct address */

};

/*

 * Structure used by kernel to pass protocol

 * information in raw sockets.

 */

struct sockproto {

 u_short sp_family;  /* address family */

 u_short sp_protocol;  /* protocol */

};

/*

 * Protocol families, same as address families for now.

 */

#define PF_UNSPEC AF_UNSPEC

#define PF_UNIX  AF_UNIX

#define PF_INET  AF_INET

#define PF_IMPLINK AF_IMPLINK

#define PF_PUP  AF_PUP

#define PF_CHAOS AF_CHAOS

#define PF_NS  AF_NS

#define PF_ISO  AF_ISO

#define PF_OSI  AF_OSI

#define PF_ECMA  AF_ECMA

#define PF_DATAKIT AF_DATAKIT

#define PF_CCITT AF_CCITT

#define PF_SNA  AF_SNA

#define PF_DECnet AF_DECnet

#define PF_DLI  AF_DLI

#define PF_LAT  AF_LAT

#define PF_HYLINK AF_HYLINK

#define PF_APPLETALK AF_APPLETALK

#define PF_MAX  AF_MAX

/*

 * Structure used for manipulating linger option.

 */

struct linger {

 u_short l_onoff;  /* option on/off */

 u_short l_linger;  /* linger time */

};

/*

 * Level number for (get/set)sockopt to apply to socket itself.

 */

#define SOL_SOCKET 0xffff  /* options for socket level */

/*

 * Maximum queue length specifiable by listen.

 */

#define SOMAXCONN 5

#define MSG_OOB  0x1  /* process out-of-band data */

#define MSG_PEEK 0x2  /* peek at incoming message */

#define MSG_DONTROUTE 0x4  /* send without using routing tables */

#define MSG_MAXIOVLEN 16

/*

 * Define constant based on rfc883, used by gethostbyxxxx calls.

 */

#define MAXGETHOSTSTRUCT 1024

/*

 * Define flags to be used with the WSAAsyncSelect call.

 */

#define FD_READ  0x01

#define FD_WRITE 0x02

#define FD_OOB  0x04

#define FD_ACCEPT 0x08

#define FD_CONNECT 0x10

#define FD_CLOSE 0x20

/*

 * All Windows Sockets error constants are biased by WSABASEERR from

 * the "normal"

 */

#define WSABASEERR  10000

/*

 * Windows Sockets definitions of regular Microsoft C error constants

 */

#define WSAEINTR  (WSABASEERR+4)

#define WSAEBADF  (WSABASEERR+9)

#define WSAEACCES  (WSABASEERR+13)

#define WSAEFAULT  (WSABASEERR+14)

#define WSAEINVAL  (WSABASEERR+22)

#define WSAEMFILE  (WSABASEERR+24)

/*

 * Windows Sockets definitions of regular Berkeley error constants

 */

#define WSAEWOULDBLOCK  (WSABASEERR+35)

#define WSAEINPROGRESS  (WSABASEERR+36)

#define WSAEALREADY  (WSABASEERR+37)

#define WSAENOTSOCK  (WSABASEERR+38)

#define WSAEDESTADDRREQ  (WSABASEERR+39)

#define WSAEMSGSIZE  (WSABASEERR+40)

#define WSAEPROTOTYPE  (WSABASEERR+41)

#define WSAENOPROTOOPT  (WSABASEERR+42)

#define WSAEPROTONOSUPPORT (WSABASEERR+43)

#define WSAESOCKTNOSUPPORT (WSABASEERR+44)

#define WSAEOPNOTSUPP  (WSABASEERR+45)

#define WSAEPFNOSUPPORT  (WSABASEERR+46)

#define WSAEAFNOSUPPORT  (WSABASEERR+47)

#define WSAEADDRINUSE  (WSABASEERR+48)

#define WSAEADDRNOTAVAIL (WSABASEERR+49)

#define WSAENETDOWN  (WSABASEERR+50)

#define WSAENETUNREACH  (WSABASEERR+51)

#define WSAENETRESET  (WSABASEERR+52)

#define WSAECONNABORTED  (WSABASEERR+53)

#define WSAECONNRESET  (WSABASEERR+54)

#define WSAENOBUFS  (WSABASEERR+55)

#define WSAEISCONN  (WSABASEERR+56)

#define WSAENOTCONN  (WSABASEERR+57)

#define WSAESHUTDOWN  (WSABASEERR+58)

#define WSAETOOMANYREFS  (WSABASEERR+59)

#define WSAETIMEDOUT  (WSABASEERR+60)

#define WSAECONNREFUSED  (WSABASEERR+61)

#define WSAELOOP  (WSABASEERR+62)

#define WSAENAMETOOLONG  (WSABASEERR+63)

#define WSAEHOSTDOWN  (WSABASEERR+64)

#define WSAEHOSTUNREACH  (WSABASEERR+65)

#define WSAENOTEMPTY  (WSABASEERR+66)

#define WSAEPROCLIM  (WSABASEERR+67)

#define WSAEUSERS  (WSABASEERR+68)

#define WSAEDQUOT  (WSABASEERR+69)

#define WSAESTALE  (WSABASEERR+70)

#define WSAEREMOTE  (WSABASEERR+71)

/*

 * Extended Windows Sockets error constant definitions

 */

#define WSASYSNOTREADY  (WSABASEERR+91)

#define WSAVERNOTSUPPORTED (WSABASEERR+92)

#define WSANOTINITIALISED (WSABASEERR+93)

/*

 * Error return codes from gethostbyname and gethostbyaddr

 * (when using the resolver). Note that these errors are

 * retrieved via WSAGetLastError and must therefore follow

 * the rules for avoiding clashes with error numbers from

 * specific implementations or language run-time systems.

 * For this reason the codes are based at WSABASEERR+1001.

 * Note also that [WSA]NO_ADDRESS is defined only for

 * compatibility purposes.

 */

#define h_errno  WSAGetLastError

/* Authoritative Answer: Host not found */

#define WSAHOST_NOT_FOUND (WSABASEERR+1001)

#define HOST_NOT_FOUND  WSAHOST_NOT_FOUND

/* Non-Authoritative: Host not found, or SERVERFAIL */

#define WSATRY_AGAIN  (WSABASEERR+1002)

#define TRY_AGAIN  WSATRY_AGAIN

/* Non recoverable errors, FORMERR, REFUSED, NOTIMP */

#define WSANO_RECOVERY  (WSABASEERR+1003)

#define NO_RECOVERY  WSANO_RECOVERY

/* Valid name, no data record of requested type */

#define WSANO_DATA  (WSABASEERR+1004)

#define NO_DATA   WSANO_DATA

/* no address, look for MX record */

#define WSANO_ADDRESS  WSANO_DATA

#define NO_ADDRESS  WSANO_ADDRESS

/*

 * Windows Sockets errors redefined as regular Berkeley error constants

 */

#define EWOULDBLOCK  WSAEWOULDBLOCK

#define EINPROGRESS  WSAEINPROGRESS

#define EALREADY  WSAEALREADY

#define ENOTSOCK  WSAENOTSOCK

#define EDESTADDRREQ  WSAEDESTADDRREQ

#define EMSGSIZE  WSAEMSGSIZE

#define EPROTOTYPE  WSAEPROTOTYPE

#define ENOPROTOOPT  WSAENOPROTOOPT

#define EPROTONOSUPPORT  WSAEPROTONOSUPPORT

#define ESOCKTNOSUPPORT  WSAESOCKTNOSUPPORT

#define EOPNOTSUPP  WSAEOPNOTSUPP

#define EPFNOSUPPORT  WSAEPFNOSUPPORT

#define EAFNOSUPPORT  WSAEAFNOSUPPORT

#define EADDRINUSE  WSAEADDRINUSE

#define EADDRNOTAVAIL  WSAEADDRNOTAVAIL

#define ENETDOWN  WSAENETDOWN

#define ENETUNREACH  WSAENETUNREACH

#define ENETRESET  WSAENETRESET

#define ECONNABORTED  WSAECONNABORTED

#define ECONNRESET  WSAECONNRESET

#define ENOBUFS   WSAENOBUFS

#define EISCONN   WSAEISCONN

#define ENOTCONN  WSAENOTCONN

#define ESHUTDOWN  WSAESHUTDOWN

#define ETOOMANYREFS  WSAETOOMANYREFS

#define ETIMEDOUT  WSAETIMEDOUT

#define ECONNREFUSED  WSAECONNREFUSED

#define ELOOP   WSAELOOP

#define ENAMETOOLONG  WSAENAMETOOLONG

#define EHOSTDOWN  WSAEHOSTDOWN

#define EHOSTUNREACH  WSAEHOSTUNREACH

#define ENOTEMPTY  WSAENOTEMPTY

#define EPROCLIM  WSAEPROCLIM

#define EUSERS   WSAEUSERS

#define EDQUOT   WSAEDQUOT

#define ESTALE   WSAESTALE

#define EREMOTE   WSAEREMOTE

/* Socket function prototypes */

#ifdef __cplusplus

extern "C" {

#endif

SOCKET PASCAL FAR accept (SOCKET s, struct sockaddr FAR *addr,

    int FAR *addrlen);

int PASCAL FAR bind (SOCKET s, const struct sockaddr FAR *addr, int namelen);

int PASCAL FAR closesocket (SOCKET s);

int PASCAL FAR connect (SOCKET s, const struct sockaddr FAR *name, int namelen);

int PASCAL FAR ioctlsocket (SOCKET s, long cmd, u_long FAR *argp);

int PASCAL FAR getpeername (SOCKET s, struct sockaddr FAR *name,

    int FAR * namelen);

int PASCAL FAR getsockname (SOCKET s, struct sockaddr FAR *name,

    int FAR * namelen);

int PASCAL FAR getsockopt (SOCKET s, int level, int optname,

    char FAR * optval, int FAR *optlen);

u_long PASCAL FAR htonl (u_long hostlong);

u_short PASCAL FAR htons (u_short hostshort);

unsigned long PASCAL FAR inet_addr (const char FAR * cp);

char FAR * PASCAL FAR inet_ntoa (struct in_addr in);

int PASCAL FAR listen (SOCKET s, int backlog);

u_long PASCAL FAR ntohl (u_long netlong);

u_short PASCAL FAR ntohs (u_short netshort);

int PASCAL FAR recv (SOCKET s, char FAR * buf, int len, int flags);

int PASCAL FAR recvfrom (SOCKET s, char FAR * buf, int len, int flags,

    struct sockaddr FAR *from, int FAR * fromlen);

int PASCAL FAR select (int nfds, fd_set FAR *readfds, fd_set FAR *writefds,

   fd_set FAR *exceptfds, const struct timeval FAR *timeout);

int PASCAL FAR send (SOCKET s, const char FAR * buf, int len, int flags);

int PASCAL FAR sendto (SOCKET s, const char FAR * buf, int len, int flags,

   const struct sockaddr FAR *to, int tolen);

int PASCAL FAR setsockopt (SOCKET s, int level, int optname,

    const char FAR * optval, int optlen);

int PASCAL FAR shutdown (SOCKET s, int how);

SOCKET PASCAL FAR socket (int af, int type, int protocol);

/* Database function prototypes */

struct hostent FAR * PASCAL FAR gethostbyaddr(const char FAR * addr,

      int len, int type);

struct hostent FAR * PASCAL FAR gethostbyname(const char FAR * name);

int PASCAL FAR gethostname (char FAR * name, int namelen);

struct servent FAR * PASCAL FAR getservbyport(int port, const char FAR * proto);

struct servent FAR * PASCAL FAR getservbyname(const char FAR * name,

      const char FAR * proto);

struct protoent FAR * PASCAL FAR getprotobynumber(int proto);

struct protoent FAR * PASCAL FAR getprotobyname(const char FAR * name);

/* Microsoft Windows Extension function prototypes */

int PASCAL FAR WSAStartup(WORD wVersionRequired, LPWSADATA lpWSAData);

int PASCAL FAR WSACleanup(void);

void PASCAL FAR WSASetLastError(int iError);

int PASCAL FAR WSAGetLastError(void);

BOOL PASCAL FAR WSAIsBlocking(void);

int PASCAL FAR WSAUnhookBlockingHook(void);

FARPROC PASCAL FAR WSASetBlockingHook(FARPROC lpBlockFunc);

int PASCAL FAR WSACancelBlockingCall(void);

HANDLE PASCAL FAR WSAAsyncGetServByName(HWND hWnd, u_int wMsg,

     const char FAR * name,

     const char FAR * proto,

     char FAR * buf, int buflen);

HANDLE PASCAL FAR WSAAsyncGetServByPort(HWND hWnd, u_int wMsg, int port,

     const char FAR * proto, char FAR * buf,

     int buflen);

HANDLE PASCAL FAR WSAAsyncGetProtoByName(HWND hWnd, u_int wMsg,

      const char FAR * name, char FAR * buf,

      int buflen);

HANDLE PASCAL FAR WSAAsyncGetProtoByNumber(HWND hWnd, u_int wMsg,

      int number, char FAR * buf,

      int buflen);

HANDLE PASCAL FAR WSAAsyncGetHostByName(HWND hWnd, u_int wMsg,

     const char FAR * name, char FAR * buf,

     int buflen);

HANDLE PASCAL FAR WSAAsyncGetHostByAddr(HWND hWnd, u_int wMsg,

     const char FAR * addr, int len, int type,

     const char FAR * buf, int buflen);

int PASCAL FAR WSACancelAsyncRequest(HANDLE hAsyncTaskHandle);

int PASCAL FAR WSAAsyncSelect(SOCKET s, HWND hWnd, u_int wMsg,

    long lEvent);

#ifdef __cplusplus

}

#endif

/* Microsoft Windows Extended data types */

typedef struct sockaddr SOCKADDR;

typedef struct sockaddr *PSOCKADDR;

typedef struct sockaddr FAR *LPSOCKADDR;

typedef struct sockaddr_in SOCKADDR_IN;

typedef struct sockaddr_in *PSOCKADDR_IN;

typedef struct sockaddr_in FAR *LPSOCKADDR_IN;

typedef struct linger LINGER;

typedef struct linger *PLINGER;

typedef struct linger FAR *LPLINGER;

typedef struct in_addr IN_ADDR;

typedef struct in_addr *PIN_ADDR;

typedef struct in_addr FAR *LPIN_ADDR;

typedef struct fd_set FD_SET;

typedef struct fd_set *PFD_SET;

typedef struct fd_set FAR *LPFD_SET;

typedef struct hostent HOSTENT;

typedef struct hostent *PHOSTENT;

typedef struct hostent FAR *LPHOSTENT;

typedef struct servent SERVENT;

typedef struct servent *PSERVENT;

typedef struct servent FAR *LPSERVENT;

typedef struct protoent PROTOENT;

typedef struct protoent *PPROTOENT;

typedef struct protoent FAR *LPPROTOENT;

typedef struct timeval TIMEVAL;

typedef struct timeval *PTIMEVAL;

typedef struct timeval FAR *LPTIMEVAL;

/*

 * Windows message parameter composition and decomposition

 * macros.

 *

 * WSAMAKEASYNCREPLY is intended for use by the Windows Sockets implementation

 * when constructing the response to a WSAAsyncGetXByY routine.

 */

#define WSAMAKEASYNCREPLY(buflen,error) MAKELONG(buflen,error)

/*

 * WSAMAKESELECTREPLY is intended for use by the Windows Sockets implementation

 * when constructing the response to WSAAsyncSelect.

 */

#define WSAMAKESELECTREPLY(event,error) MAKELONG(event,error)

/*

 * WSAGETASYNCBUFLEN is intended for use by the Windows Sockets application

 * to extract the buffer length from the lParam in the response

 * to a WSAGetXByY.

 */

#define WSAGETASYNCBUFLEN(lParam)  LOWORD(lParam)

/*

 * WSAGETASYNCERROR is intended for use by the Windows Sockets application

 * to extract the error code from the lParam in the response

 * to a WSAGetXByY.

 */

#define WSAGETASYNCERROR(lParam)  HIWORD(lParam)

/*

 * WSAGETSELECTEVENT is intended for use by the Windows Sockets application

 * to extract the event code from the lParam in the response

 * to a WSAAsyncSelect.

 */

#define WSAGETSELECTEVENT(lParam)  LOWORD(lParam)

/*

 * WSAGETSELECTERROR is intended for use by the Windows Sockets application

 * to extract the error code from the lParam in the response

 * to a WSAAsyncSelect.

 */

#define WSAGETSELECTERROR(lParam)  HIWORD(lParam)

#endif /* _WINSOCKAPI_ */


 Notes for Windows Sockets Suppliers


  Introduction to Notes for Windows Sockets Suppliers

A WINSOCK.DLL or WINSOCK32.DLL must implement ALL the functionality described in the Windows Sockets documentation.

Windows Sockets version 1.1 implementations must support both TCP and UDP type sockets. An implementation may support raw sockets (of type SOCK_RAW), but their use is deprecated.

Certain functions documented in this Help file have special notes for Windows Sockets implementors. A Windows Sockets implementation shoul conform to the function as documented. The special notes are provided for assistance and clarification.


 Windows Sockets Components


  Development Components

The Windows Sockets development components for use by Windows Sockets application developers will be provided by each Windows Sockets supplier. These Windows Sockets development components are:

Component	Description
Windows Sockets Documentation	This document
WINSOCK.LIB file	Windows Sockets API Import Library
WINSOCK.H file	Windows Sockets Header File
NETDB.H file	Berkeley Compatible Header File
ARPA/INET.H file	Berkeley Compatible Header File
SYS/TIME.H file	Berkeley Compatible Header File
SYS/SOCKET.H file	Berkeley Compatible Header File
NETINET/IN.H file	Berkeley Compatible Header File
Run-Time Components

The run-time component provided by each Windows Sockets supplier is:

Component	Description
WINSOCK.DLL	The Windows Sockets API implementation DLL


  Multithreadedness and Blocking Routines

Data areas returned by, for example, the functions in the getXbyY family (gethostbyaddr, and so on) MUST be on a per-thread basis.

Note that an application must be prevented from making multiple nested Windows Sockets function calls. Only one outstanding function call will be allowed for a particular task. Any Windows Sockets call performed when an existing blocking call is already outstanding will fail with an error code of WSAEINPROGRESS. There are two exceptions to this restriction: WSACancelBlockingCall and WSAIsBlocking may be called at any time. Windows Sockets suppliers should note that although preliminary drafts of this specification indicated that the restriction only applied to blocking function calls, and that it would be permissible to make nonblocking calls while a blocking call was in progress, this is no longer true.

Regarding the implementation of blocking routines, the solution in Windows Sockets is to simulate the blocking mechanism by having each routine call PeekMessage as it waits for the completion of its operation. In anticipation of this, the function WSASetBlockingHook is provided to allow you to define a special routine to be called instead of the default PeekMessage loop.


  Database Files Implementation

The database routines in the getXbyY family (gethostbyaddr, and so on.) were originally designed (in the first Berkeley UNIX releases) as mechanisms for looking up information in text databases. A Windows Sockets supplier may choose to employ local files OR a name service to provide some or all of this information. If local files exist, the format of the files must be identical to that used in BSD UNIX, allowing for the differences in text file formats.


  FD_ISSET

It is necessary to implement the FD_ISSET Berkeley macro using a supporting function: __WSAFDIsSet. It is the responsibility of a Windows Sockets implementation to make this available as part of the Windows Sockets API. Unlike the other functions exported by a Windows Sockets DLL, however, this function is not intended to be invoked directly by Windows Sockets applications: It should be used only to support the FD_ISSET macro. The source code for this function is:

int FAR

__WSAFDIsSet(SOCKET fd, fd_set FAR *set)

{

    int i = set->fd_count;

    while (i--)

        if (set->fd_array[i] == fd)

            return 1;

    return 0;

}


  Error Codes Returned by WSAGetLastError

To avoid conflict between various compiler environments, Windows Sockets implementations MUST return the error codes listed in the API specification, using the manifest constants beginning with "WSA". The Berkeley-compatible error code definitions are provided solely for compatibility purposes for applications being ported from other platforms.


  DLL Ordinal Numbers

The WINSOCK.DEF file for use by every Windows Sockets implementation is as follows. Ordinal values starting at 1000 are reserved for Windows Sockets implementors to use for exporting private interfaces to their DLLs. A Windows Sockets implementation must not use any ordinals 999 and below except for those functions listed following. An application that is to work with any Windows Sockets DLL must use only those routines listed follwoing; using a private export makes an application dependent on a particular Windows Sockets implementation.

;

;  File: winsock.def

; System: MS-Windows 3.x

; Summary: Module definition file for Windows Sockets DLL.

;

LIBRARY  WINSOCK  ; Application's module name

DESCRIPTION 'BSD Socket API for Windows'

EXETYPE  WINDOWS  ; required for all windows applications

STUB  'WINSTUB.EXE' ; generates error message if application

    ; is run without Windows

;CODE can be FIXED in memory because of potential upcalls

CODE  PRELOAD  FIXED

;DATA must be SINGLE and at a FIXED location since this is a DLL

DATA  PRELOAD  FIXED  SINGLE

HEAPSIZE 1024

STACKSIZE 16384

; All functions that will be called by any Windows routine

; must be exported. Any additional exports beyond those defined

; here must have ordinal numbers 1000 or above.

EXPORTS

 accept    @1

 bind    @2

 closesocket   @3

 connect   @4

 getpeername   @5

 getsockname   @6

 getsockopt   @7

 htonl    @8

 htons    @9

 inet_addr   @10

 inet_ntoa   @11

 ioctlsocket   @12

 listen    @13

 ntohl    @14

 ntohs    @15

 recv    @16

 recvfrom   @17

 select    @18

 send    @19

 sendto    @20

 setsockopt   @21

 shutdown   @22

 socket    @23

 gethostbyaddr   @51

 gethostbyname   @52

 getprotobyname   @53

 getprotobynumber  @54

 getservbyname   @55

 getservbyport   @56

 gethostname   @57

 WSAAsyncSelect   @101

 WSAAsyncGetHostByAddr  @102

 WSAAsyncGetHostByName  @103

 WSAAsyncGetProtoByNumber @104

 WSAAsyncGetProtoByName  @105

 WSAAsyncGetServByPort  @106

 WSAAsyncGetServByName  @107

 WSACancelAsyncRequest  @108

 WSASetBlockingHook  @109

 WSAUnhookBlockingHook  @110

 WSAGetLastError  @111

 WSASetLastError  @112

 WSACancelBlockingCall  @113

 WSAIsBlocking   @114

 WSAStartup   @115

 WSACleanup   @116

 __WSAFDIsSet   @151

 WEP    @500 RESIDENTNAME

;eof


  Validation Suite

The Windows Sockets API Tester (WSAT) to ensure Windows Sockets compatibility between Windows Sockets DLL implementations is currently in beta test. This beta version includes functionality testing of the Windows Sockets interface and is supported by a comprehensive scripting language. The final version of WSAT will be available in Spring 1993. If you wish to receive the tester or more information on the beta, send email to wsat@microsoft.com.


  For Further Reference

This documentation is intended to cover the Windows Sockets interface to TCP/IP in detail. Many details of TCP/IP and Windows, however, are intentionally omitted in the interest of brevity, and this specification often assumes background knowledge of these topics. For more information, the following references may be helpful:

Braden, R.[1989], RFC 1122, Requirements for Internet Hosts — Communication Layers, Internet Engineering Task Force.

Comer, D. [1991], Internetworking with TCP/IP Volume I: Principles, Protocols, and Architecture, Prentice Hall, Englewood Cliffs, New Jersey.

Comer, D. and Stevens, D. [1991], Internetworking with TCP/IP Volume II: Design, Implementation, and Internals, Prentice Hall, Englewood Cliffs, New Jersey.

Comer, D. and Stevens, D. [1991], Internetworking with TCP/IP Volume III: Client-Server Programming and Applications, Prentice Hall, Englewood Cliffs, New Jersey.

Leffler, S. et al., An Advanced 4.3BSD Interprocess Communication Tutorial.

Petzold, C. [1992], Programming Windows 3.1, Microsoft Press, Redmond, Washington.

Stevens, W.R. [1990], Unix Network Programming, Prentice Hall, Englewood Cliffs, New Jersey.


 Background Information


  Legal Status of Windows Sockets

The copyright for the Windows Sockets specification is owned by the specification authors listed on the title page. Permission is granted to redistribute this specification in any form, provided that the contents of the specification are not modified. Windows Sockets implementors are encouraged to include this specification with their product documentation.

The Windows Sockets logo on the title page of this document is meant for use on both Windows Sockets implementations and for applications that use the Windows Sockets interface. Use of the logo is encouraged on packaging, documentation, collateral, and advertising. The logo is available on microdyne.com in pub/winsock as WINSOCK.BMP. The suggested color for the logo's title bar is blue, the electrical socket grey, and the text and outline black.

UNIX is a trademark of Unix System Laboratories, Inc.

VAX is a trademark of Digital Equipment Corporation.

Windows is a trademark of Microsoft Corporation

68000 is a trademark of Motorola, Inc.

NT and Windows/NT are trademarks of Microsoft Corporation.


  Windows Sockets for Windows NT

Microsoft® Windows NT™ fully supports the Windows Sockets functions as defined in the Win32 SDK (Software Development Kit). However, Windows NT has some additional features available through its Windows Sockets interface that are not described in the Windows Sockets specification. This document describes the extended features of the Windows Sockets interface in Windows NT, a superset of the Windows Sockets functionality.

Some of the features described in this document were not implemented in the initial release of Windows NT but are available in Windows NT version 3.5. The most notable new features are the SO_SNDTIMEO, SO_RCVTIMEO, and SO_OPENTYPE socket options and support for NetBIOS providers.


  Support for 32-bit Applications

Included with the Windows NT release disks is the WINSOCK.DLL file, which provides the functions necessary for 16-bit applications to use Windows Sockets through 16-bit subsystem of Windows NT. Win32-based applications use a different DLL, WSOCK32.DLL, which exports routines that take exclusively 32-bit arguments.

The 32-bit versions of the Windows Sockets functions take all the same parameters, with the notable exception that all int and SOCKET parameters are widened from 16 bits to 32 bits. This widening is of no concern if you are writing applications to be portable between 16-bit and 32-bit environments, since the compiler performs the necessary steps automatically.


  Windows NT Socket Handles

From a developer's standpoint, perhaps the most notable aspect of the Windows Sockets support in Windows NT is that the handles returned from the socket and accept functions are native Windows NT system handles that have been opened, by default, as "asynchronous" or "overlapped" handles. This allows an application to use the handles as arguments to system routines in addition to the Windows Sockets routines and also to share the handles between threads and processes.


  Sharing Sockets Between Threads

Because a handle value is global to all threads in a process, a handle can be accessed in any thread, even threads that did not open the handle. For example, one thread can call the socket function, which returns a socket handle. A different thread in the same process can make other Windows Sockets calls with the returned socket handle. No special action is required to enable the second thread to use the handle; it just needs to obtain the handle value.

It is also possible for multiple threads to access a single socket simultaneously, but an application that does this must synchronize important actions. For example, if one thread performs a bind operation on a socket at the same time another thread is performing a getsockname operation, then because of the preemptive scheduling of Windows NT there are no guarantees that the getsockname operation will execute before the bind operation. It could happen that getsockname returns WSAEINVAL because the socket is not yet bound.

Another important example of simultaneous access in multiple threads to a single socket is data transfer. An application can have one thread calling send on a socket and another thread calling recv with no adverse effects whatsoever. However, if multiple threads call send on a socket, there are no guarantees as to the order of data delivery. The only guarantee is that the data in each send operation will be sent as a contiguous chunk — there is no possibility of intermixing data from different send calls. The analagous situation exists for multiple simultaneous recv calls — there is no guarantee as to which will finish first, but the data returned to any given recv operation is contiguous.

Making multiple simultaneous calls from different threads will not in any way damage the internal state of the socket maintained by Windows Sockets. Windows Sockets internally synchronizes the socket state whenever it changes in any way. Therefore, you need not worry about synchronizing calls for the sake of preserving the internal state of Windows Sockets.


  Sharing Sockets Between Processes

Handles in Windows NT can also be shared between processes. However, since each process has its own handle table, it is more work to share handles between processes than between threads. There are two mechanisms for sharing handles between processes: inheritance and duplication.

In inheritance, a process (called the "parent process") creates another process (called the "child process") using the Win32 function CreateProcess with the fInheritHandles parameter set to TRUE. This causes the system to map into the child's process table all the inheritable handles of the parent process. Note that while not all Win32 handles are inheritable (inheritance requires opening a handle in a special manner), all socket handles are inheritable.

Once you create the child process, it must be given the values of the handles it needs to access. When it has the handle values, it can pass the handles to Windows Sockets or other functions.

In duplication, a process can pass a handle to another existing process with the Win32 function DuplicateHandle. This function allows one process to map a handle into the process table of another process, although the specific handle value may be different in the receiving process.

When sharing sockets between processes, the same synchronization issues exist as when sharing sockets between threads. In addition, you must be aware of two other special properties of sharing sockets between processes.

First, since both processes have a view of the socket handle, both processes must call closesocket before the system closes the socket. The process that first calls closesocket only takes the socket out of its internal handle table. The first closesocket call does not affect the second process's access to the socket in any way. The second closesocket does the actual cleanup of the socket, including initiating the protocol-level virtual circuit termination if the socket is connected. If the socket sharing is really a "hand-off" from one process to another, it is best to close the socket in the first process immediately after the CreateProcess or DuplicateHandle call.

Second, some socket options, such as SO_LINGER, are kept on a per-process basis. Therefore, after a socket handle has been passed to a second process, changes in socket options by one process may not be reflected in the other process. For this reason it is advisable to set up any socket options that both processes will need before sharing the socket handle.

Many Unix® services that use sockets make use of child process creation and inheritance to handle multiple simultaneous clients. This is typically done by a "master" process creating a socket, calling listen on the socket, and using accept to accept incoming connections. Then this process creates a "slave" process that actually services the client while the master immediately closes the accepted socket. This is useful in Unix, where multiple threads are generally not available, and this algorithm will work in Windows NT. However, processes use more memory than threads. Context switches between processes use about twice the CPU instructions used in context switches between threads within a single process. In addition, threads can share information much more easily than processes, so it is usually easier in the long run to use threads rather than processes. For all these reasons, it is strongly recommended that you write a service that handles multiple clients simultaneously so that it uses one thread per client rather than one process per client. It is even better to use multiple clients per thread. This technique is discussed in Accessing Sockets Through the Win32 I/O Functions.


  Using Sockets as Standard I/O Handles

A special case of sharing sockets between processes is using sockets as standard input, output, or errors for a child process created with CreateProcess. This is useful for causing a process to unwittingly read input from a socket and to write output to a socket. Such a child process may "know" absolutely nothing about sockets or even networks; it just reads from its standard input and writes to its standard output.

There are two key steps in making this possible. First, a socket must be opened for "synchronous" access (that is, not overlapped) with the SO_OPENTYPE socket option described following. Second, the socket must be connected with either the connect or accept Windows Sockets function calls. After these steps, making a socket handle accessible as a standard I/O handle is just like doing so for other handles: Specify the handle value in the hStdInput, hStdOutput, and/or hStdError fields of the STARTUPINFO structure passed to CreateProcess Win32 function. The created process will read from and write to the socket without ever knowing it is a socket.


  Accessing Sockets Through the Win32 I/O Functions

Since Windows NT socket handles are system socket handles, it is possible to use Windows NT socket handles as parameters to several of the Win32 functions. The most useful Win32 functions for sockets are the ReadFile and WriteFile functions since these allow an application to perform aynchronous I/O on a handle by means of the lpOverlapped parameter. In overlapped I/O, the request is started with the initial call but the call does not block waiting for the request to be completed. For example, if an application makes an overlapped ReadFile call when no data exists to be read on a socket, the calling thread will regain control immediately rather than waiting for data to arrive on the socket. The application will be notified when the request has been completed via the lpOverlapped parameter.

Overlapped I/O differs from the socket concept of nonblocking I/O in that overlapped I/O actually performs the I/O eventually if it cannot be completed immediately. In nonblocking I/O, if the I/O cannot be performed immediately, then it fails with the error code WSAEWOULDBLOCK and the application must reissue the request at a later point.

Overlapped I/O is especially useful in a service that handles multiple sockets. A single thread can be used to perform I/O on all of the sockets without the overhead of the select call. Also, the use of overlapped I/O allows an application to mix different types of I/O in a single thread; for example, I/O on named pipes and I/O on sockets.

Because Windows NT socket handles are, by default, opened as overlapped handles, an application must specify the lpOverlapped parameter on calls to ReadFile and WriteFile. However, an application can also use the SO_OPENTYPE socket option to open sockets that are not overlapped.


  Accessing Sockets Through the C Run-time Libraries

The C run-time libraries (CRTs) provide useful functionality for input and output formatting through routines such as fprintf, fscanf, and so on. It may also be useful to access socket handles through these routines in existing code that uses C run-time calls such as _read and _write.

The C run-time libraries take two different inputs to identify a file: a CRT handle (different from a system handle such as a socket) and a file pointer. The low-level I/O routines, such as _read, take CRT handles, while the more sophisticated formatting routines, such as fprintf, take file pointers.

To access sockets through the C run-time routines, an application must perform several steps:

1.	Use the SO_OPENTYPE socket option described following so that any opened socket handles are synchronous.

2.	Open a connected socket by calling either socket and connect or by calling accept. It is legal to use datagram sockets, although their inherent unreliability may make them unsuitable for C run-time access in many applications.

3.	Obtain a CRT socket handle with the _open_osf_handle C run-time API. If the application intends to use only the low-level C run-time calls, the handle returned by this call is sufficient and the application is ready to make C run-time calls.

4.	If the application wants to use the higher-level C run-time calls that do data formatting, the application must obtain a file pointer (FILE *) by using the _fdopen C run-time call.


  Socket Options Specific to Windows NT

Windows NT supplies several socket options beyond those included in the Windows Sockets specification. Because these options are not currently part of the formal Windows Sockets specification, an application that uses these options is not compatible with Windows Sockets. However, for applications written exclusively for Windows NT, these options can be very useful.


  SO_SNDTIMEO and SO_RCVTIMEO

These two options set up timeouts for the send, sendto, recv, and recvfrom functions. You can obtain the same functionality by calling select with a timeout just before the I/O call, but these options offer a significant improvement in performance by avoiding a kernel transition and the other overhead of the select call. For any code whose performance is very critical, applications should use these timeout options rather than select.

You can set these options on any type of socket in any state. The default value for these options is zero, which refers to an infinite timeout. Any other setting is the timeout, in milliseconds. It is legal to set the timeout to any value, but values less than 500 milliseconds (half a second) are interpreted to be 500 milliseconds.

To set a send timeout, use

int timeout = TIMEOUT_VALUE;

int err;

SOCKET s;

s = socket( ... );

err = setsockopt(

        s,

        SOL_SOCKET,

        SO_SNDTIMEO,

        (char *)&timeout,

        sizeof(timeout));

if (err != NO_ERROR) {

    /* failed for some reason... */

}

where TIMEOUT_VALUE is the needed timeout in milliseconds. To set a receive timeout, substitute SO_RCVTIMEO for SO_SNDTIMEO in the preceding example.

After setting one of these options to a nonzero value, I/O through the Windows Sockets calls fails with the error WSAETIMEDOUT if the request cannot be satisfied within the specified timeout. If a request times out, an application has no guarantees as to how much data was actually sent or received in the I/O call.


  SO_OPENTYPE

By default, all socket handles are opened as overlapped handles so that asynchronous I/O can be performed on them. However, in many situations it is preferable to have nonoverlapped (synchronous) socket handles. For example, only nonoverlapped handles can be used with the C run-time libraries or used as standard I/O handles for a process. The SO_OPENTYPE socket option allows an application to open nonoverlapped socket handles.

The SO_OPENTYPE option must be set on a per-thread basis since it affects how each thread opens sockets, and it must be set before a socket handle is opened in order to affect the socket. The default value for this option is zero, which opens sockets as overlapped handles. Other possible values for this option are SO_SYNCHRONOUS_ALERT and SO_SYNCHRONOUS_NONALERT. SO_SYNCHRONOUS_ALERT allows operations performed on the socket handle to be alerted by an APC routine (software interrupt), while SO_SYNCHRONOUS_NONALERT blocks APCs from being delivered to threads waiting on requests on socket handles. Typically, it does not matter which of these options is chosen: either makes socket handles nonoverlapped.

Use the following to open a nonoverlapped socket handle:

SOCKET s;

int optionValue = SO_SYNCHRONOUS_NONALERT;

int err;

err = setsockopt(

        INVALID_SOCKET,

        SOL_SOCKET,

        SO_OPENTYPE,

        (char *)&optionValue,

        sizeof(optionValue));

if (err != NO_ERROR) {

    /* failed for some reason... */

}

s = socket( ... );

Note that the socket handle passed to setsockopt is ignored for this option.

The SO_OPENTYPE socket option affects both the socket and accept Windows Sockets calls. The setting of SO_OPENTYPE is preserved throughout the lifetime of the thread in which it is set, so it is not necessary to set its value before each socket opens. However, it is necessary to set this option for every thread that opens sockets if the nondefault behavior is desired. Also, if different layers of an application open sockets and have different expectations of the type of handles opened, it is advisable to use getsockopt before the setsockopt call to obtain the original setting of SO_OPENTYPE, then reset SO_OPENTYPE to the original value after opening the socket. For example,

SOCKET s;

int originalValue;

int optionValue = SO_SYNCHRONOUS_ALERT;

int err;

int optionLength = sizeof(originalValue);

/* Get the original setting of SO_OPENTYPE. */

err = getsockopt(

        INVALID_SOCKET,

        SOL_SOCKET,

        SO_OPENTYPE,

        (char *)&originalValue,

        optionLength);

if (err != NO_ERROR) {

    /* failed for some reason... */

}

/* Set SO_OPENTYPE so that we get a synchronous socket handle. */

err = setsockopt(

        INVALID_SOCKET,

        SOL_SOCKET,

        SO_OPENTYPE,

        (char *)&optionValue,

        sizeof(optionValue));

if (err != NO_ERROR) {

    /* failed for some reason... */

}

s = socket( ... );

/* Reset the SO_OPENTYPE setting to its original value. */

err = setsockopt(

        INVALID_SOCKET,

        SOL_SOCKET,

        SO_OPENTYPE,

        (char *)&optionValue,

        sizeof(optionValue));

if (err != NO_ERROR) {

    /* failed for some reason... */

}

This technique is especially useful in DLLs that use synchronous sockets.

There are some Windows Sockets features that you cannot use with synchronous sockets. The WSAAsyncSelect call cannot be used with synchronous sockets and will fail with the error WSAEINVAL. It is also not possible to set the SO_SNDTIMEO and SO_RCVTIMEO socket options on synchronous sockets; setsockopt with these options on synchronous sockets fails with WSAEINVAL as well.


  Multiple Protocol Support

In addition to TCP/IP, Windows NT supports several additional transport protocols through its Windows Sockets interface. Although these protocols are not explicitly addressed in the Windows Sockets specification, the interface to Windows Sockets over different transport protocols is quite feasible. This is because the fundamental job of a transport protocol is data transfer, along with the fact that Windows Sockets provides a rich interface for low-level data transfer in applications. Having a common, well-known interface allows applications to be ported quickly between different transport protocols, and there are several successful examples of this.

Because of the architecture of the Windows Sockets component of Windows NT, all supported transport protocols are accessed through the same DLL, WSOCK32.DLL. In fact, a single application can simultaneously use sockets of different transport protocols.

An application uses the parameters to the socket function to specify the protocol it will use. For example, a TCP socket is opened with

s_tcp = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );

while an SPX socket is opened with

s_spx = socket( AF_IPX, SOCK_SEQPACKET, NSPROTO_SPX );

After opening a socket for a specific protocol, all actions performed on the socket go through the specified protocol. In the preceding example, if the application did a listen on the s_tcp socket but not on the s_spx socket, it would receive incoming connects through TCP but not receive incoming connects through SPX.


  Protocol Characteristics

It is important to understand the different characteristics of transport protocols when designing an application that uses them. While all transport protocols share the same fundamental purpose of bidirectional data transfer, many details of the data transfer differ. The following sections list key characteristics of transport protocols that apply to Windows Sockets applications.


  Addressing

The most obvious difference between different transport protocols is the way each uses transport addresses, called "socket addresses" in Windows Sockets terms. Virtually all transport protocols expose different address formats to applications, the one exception being NetBIOS protocols, which all use the same address format.

A number of Windows Sockets functions take socket addresses as input or output parameters, including bind, accept, sendto, recvfrom, getsockname, and getpeername. For all these functions a socket address is really two arguments: a pointer to the socket address structure itself and a length integer that gives the number of bytes in the socket address. For many transport protocols the length of a socket address is always the same, but socket address lengths can differ between transport protocols. For example, a TCP/IP socket address has 16 bytes and an IPX/SPX socket address has 14 bytes.

The format of socket address structures used by a transport protocol is specified in the af, or "address family" argument to the socket function. All TCP/IP sockets (including both TCP and UDP sockets) are opened with the AF_INET address family, while IPX/SPX sockets are opened with AF_IPX. Other transport protocols use different address family values as defined in the header file WINSOCK.H.

An application must fill in a socket address when binding to a local address or connecting to a remote address, and also to interpret the socket addresss returned from the accept, sendto, recvfrom, getpeername, and getsockname functions.


  Connection-Oriented vs. Connectionless Transport

In a connection-oriented transport protocol, applications are required to establish a virtual circuit (sometimes abbreviated to "VC") before data transfer can take place. Virtual circuit establishment is assymetrical. One side, the server, must indicate to the transport protocol that it can receive incoming connections via the listen function. The other side, the client, initiates the circuit with the connect function, and the server can obtain a socket for the circuit with the accept function. Once the circuit is established, data transfer takes place with the send and recv functions. Protocol-level activity results from this circuit establishment, and more protocol activity tears down the circuit when the sockets are closed. TCP and SPX are examples of connection-oriented transport protocols.

In a connectionless transport protocol, circuit establishment is not required for data transfer. An application need only open and bind a socket, after which it can use the sendto and recvfrom functions to send and receive data. Of course, in order to specify the remote address for sending data or the address from which received data was sent, you must specify a socket address to these routines. UDP and IPX are examples of connectionless transport protocols.

It is possible to use the connect function on sockets opened for connectionless protocols. This is merely an application convenience, allowing the application to use the send and recv functions, and this does not result in any protocol activity. If a socket is connected in this manner, it will receive only packets sent from the connected address; other packets destined for the socket are silently discarded.


  Reliable vs. Unreliable Data Delivery

Most physical networks are inherently unreliable. They can drop data, corrupt it, deliver it out of order, and deliver multiple copies of it. Some transport protocols hide this unreliability from applications by using protocol-level mechanisms to ensure that data is delivered in the correct order, without loss, corruption, or duplication. Other transport protocols do not make these guarantees; they simply make a best effort to get the data to its intended recipient, but physical network failures can lead to data integrity problems.

Because they require fewer system resources and less processing, unreliable protocols often provide better performance, especially for applications that send small amounts of data in a request-response (transaction) format. However, applications that use connectionless protocols must guarantee reliability, which makes applications more complicated. Reliable protocols are usually simpler for the application at the expense of a higher cost in system resources and performance.

Typically, connection-oriented protocols are reliable, while connectionless protocols are unreliable. While this is true of all the transport protocols supported by Windows NT, there are exceptions.


  Terminating a Virtual Circuit

For a connection-oriented transport protocol, there are two ways to terminate a virtual circuit: orderly and abortive. In an orderly release, both sides get a chance to indicate that they have sent all the data they intend to send, and only when both sides have finished is the actual circuit terminated. For such a release, one side can use the shutdown function to indicate that it has finished sending, while the other side continues sending. In an abortive termination of a virtual circuit, one side decides that it is time to terminate the circuit and unilaterally ends the connection. If the other side attempts to use the connected socket, the request fails.

By default, closesocket also attempts an orderly release of the connection. However, under several circumstances, such as pending unreceived, outstanding send calls, and more, a closesocket will result in an abortive close.

All transport protocols support the concept of an abortive release, but not all protocols support orderly release. If an application attempts an orderly release on a transport protocol that does not support orderly release, the connection is terminated abortively. TCP supports orderly release, while SPX supports only abortive release.


  Message-Oriented vs. Stream-Oriented

Connection-oriented transport protocols can be either message-oriented or stream-oriented. In a message-oriented transport protocol, each block of data is sent and received as a single block. An individual message is never broken down when received, although a transport protocol can be forced to break down a message if it is larger than the physical network's maximum transmission unit (MTU). However, this is transparent to the application.

In a stream-oriented transport protocol, data is sent and received as a continuous stream, without any message boundaries. The transport protocol is free to coalesce data from discrete send calls and deliver it to a single recv call, as well as to break down the data buffer given to a single send call and deliver it to several recv calls. An application cannot control how these breakdowns occur, and gets no notification of how data was sent. If an application needs to communicate in discrete messages, it must frame them, for example, by preceding message data with the length of the message until the specified length arrives.

Some message-oriented protocols support stream semantics in addition to message semantics. If an application opens a socket with SOCK_STREAM on such a transport protocol, then the transport ignores all message boundaries when transmitting and receiving data. It simply delivers data as it becomes available, regardless of whether the data is a complete message. This feature is handy for maximizing application portability. Note, however, that stream-oriented transport protocols cannot implement message-oriented semantics due to lack of information.


  Expedited Data

Some connection-oriented transport protocols support expedited data, also referred to as "urgent data" or "out-of-band data." Data sent with the MSG_OOB flag in the send function is sent as expedited data, and the transport protocol makes every effort to deliver the data as quickly as possible. Often the data is delivered out of order so that it can get to the other application as quickly as possible. For maximum portability, avoid expedited data since it is not supported by all transport protocols.


  Connect and Disconnect Data

A few transport protocols support connect and disconnect data, in which a small amount of data is sent by each side when a virtual circuit is established or terminated. This data can be anything, but is often negotiation information about the version of software connecting, and so on. Again, for protocol portability, avoid this feature since it is not universally supported.


  Broadcasts

Most connectionless transport protocols support broadcasts in the same fashion, in which any bound socket can send a broadcast if the SO_BROADCAST option is set, and broadcasts sent to the appropriate local endpoint are received without any additional work on the part of the application. NetBIOS transport protocols, however, handle broadcasts somewhat differently. In order to receive broadcasts, an application must bind to the NetBIOS broadcast address, which is an asterisk ("*") followed by 15 blank spaces (ASCII character 0x20). This means two things: A socket must be specially bound to receive broadcasts, and applications cannot depend on receiving broadcasts intended only for a specific application, since all NetBIOS broadcasts are delivered to this address. In other protocols such as UDP/IP and IPX, broadcasts are delivered to a socket only if the broadcast was sent to the same port to which the socket was bound.


  Extended Support for Message-Oriented Protocols

The Berkeley Software Distribution (BSD) sockets interface was originally designed to support primarily TCP/IP, and the Windows Sockets interface is based on BSD sockets. This interface is not sufficiently rich for message-oriented transport protocols, however, so Windows NT includes some minor extensions of the interface so that applications can fully exploit message-oriented transport protocols.


  MSG_PARTIAL Flag

Under some circumstances, applications may not have available in a single, contiguous data buffer all the data that make up a single message to be sent. The message can be very large, for example, or can be composed of discrete parts in an application's virtual address space. To allow an application to send this message without having to allocate a buffer and copy all the data into the buffer, Windows NT allows the application to specify the MSG_PARTIAL bit in the flags parameter of the send function. This bit tells the transport protocol that the data in the send operation is just part of a larger message, and that the protocol should take whatever action is necessary to deliver the data as a partial message.


  WSARecvEx Function

By default, for message-oriented transport protocols the Windows Sockets recv function receives a single message in each call to the API. This works fine for most cases, but there are two situations in which this is insufficient: when the application's data buffer is smaller than the message, and when the message is large and arrives in several pieces.

When the buffer is smaller than the data, as much of the message as will fit is copied into the user's buffer and recv returns with the error code WSAEMSGSIZE. A subsequent call to recv will get the next part of the message. Applications written for message-oriented transport protocols should be coded for this possibility if message sizing is not guaranteed by the application's data transfer protocol. If an application gets this error code, then the entire data buffer is filled with data.

It is more complicated when a very large message arrives a little at a time. For example, if an application sends a 1-megabyte message, the transport protocol must break up the message in order to send it over the physical network. It is theoretically possible for the transport protocol on the receiving side to buffer all the data in the message, but this would be quite expensive in terms of resources.

It would be better to allow a recv call to complete with only a partial message and some indication to the application that the data is only a partial message. However, the Windows Sockets recv function has only one output parameter: the number of bytes received. Therefore, Windows NT supplies the WSARecvEx function, which is identical to the recv function except that the flags parameter is an in-out parameter:

int

PASCAL

FAR

WSARecvEx (

        SOCKET s,

        char FAR * buf,

        int len,

        int *flags

        );

On return from WSARecvEx, if a partial message was received, the MSG_PARTIAL bit is set in the flags parameter. If a complete message was received, MSG_PARTIAL is not set in flags. For a stream-oriented transport protocol, MSG_PARTIAL is never set on return from WSARecvEx; for stream transport protocols, this function behaves identically to the Windows Sockets recv function.


  WSAEDISCON Error Code

After a virtual circuit is gracefully terminated on a stream-oriented transport protocol and all data has been received, the recv and WSARecvEx functions return zero to indicate that there will never be any more data to read on the connection. However, most message-oriented transport procotols support the concept of a zero-length message. Applications therefore need a mechanism to distinguish a zero-length message and graceful circuit termination.

The Windows Sockets interface in Windows NT uses the WSAEDISCON error code to solve this problem. When the circuit is gracefully terminated, this error code is returned to the application, and a return value of zero is used to indicate a message of length zero.

Following is an example of client-side code that establishes an SPX connection, and receives and processes messages until the connection is terminated.

SOCKET s;

SOCKADDR_IPX sockaddrIpx;

INT err;

INT bytesReceived;

INT flags;

/* open the SPX socket handle */

s = socket( AF_IPX, SOCK_SEQPACKET, NSPROTO_SPX );

/* initialize the sockaddr for the remote machine */

sockaddrIpx.sa_family = AF_IPX;

sockaddrIpx.sa_netnum = 0;

sockaddrIpx.sa_nodenum = 123;  /* substitute real nodenum here */

sockaddrIpx.sa_socket = 1; /*substitute real socket number here */

/* connect the socket */

err = connect(

        s,

        (PSOCKADDR)&sockaddrIpx,

        sizeof(sockaddrIpx) );

if ( err != 0 ) {

    /* indicate connection failure */

}

/* receive data until the connection terminates */

while ( TRUE ) {

    /* use WSARecvEx to receive data */

    flags = 0;

    bytesReceived = WSARecvEx( s, buffer, buflen, &flags );

    /* check for error or graceful termination */

    if ( bytesReceived < 0 ) {

        if ( WSAGetLastError( ) == WSAEDISCON ) {

            /* graceful termination */

            break;

        }

        /* some other error, indicate to user */

        break;

    }

    /* check for partial message */

    if ( (flags & MSG_PARTIAL) != 0 ) {

        /* a partial message; handle specially */

    }

    /* check for 0-length message */

    if ( bytesReceived == 0 ) {

        /* 0-length message, process */

    } else {

        /* message contained data */

    }

}

/* circuit terminated or error, close socket */

closesocket( s );


  Windows NT Support for Connect and Disconnect Data

Some transport protocols, such as DECNet and OSI TP4, support the concept of connect and disconnect data. This is additional data, not in the normal data stream, that is sent on the wire along with connect or disconnect requests and is typically used for things like application-level version negotiation. The TDI interface provides support for connect and disconnect data through the TDI_CONNECTION_INFORMATION structure, which has fields for UserDataLength, UserData, OptionsLength, and Options and is passed on TDI connect, accept, and disconnect requests.

The sockets interface, however, does not provide input parameters for connect data on the connect function or for disconnect data on the shutdown and closesocket functions. However, it is relatively natural to use the setsockopt function to specify connect and disconnect data to send, and to use the getsockopt function to retrieve connect and disconnect data sent by the remote side. To support this, the following socket options are included with the Windows NT version of the Windows Sockets header file (WINSOCK.H):

/*

 * Options for connect and disconnect data and options. Used only by

 * non-TCP/IP transports such as DECNet, OSI TP4, etc.

 */

#define SO_CONNDATA     0x7000

#define SO_CONNOPT      0x7001

#define SO_DISCDATA     0x7002

#define SO_DISCOPT      0x7003

#define SO_CONNDATALEN  0x7004

#define SO_CONNOPTLEN   0x7005

#define SO_DISCDATALEN  0x7006

#define SO_DISCOPTLEN   0x7007

How an application uses these options in conjunction with getsockopt and setsockopt depends on the type of application, server or client, and how it will use connect data. Each case is explained following.

Connect and disconnect options are semantically the same as connect and disconnect data, from the standpoint of the Windows Sockets interface. The "options" are really just a buffer of data that is passed to the transport protocol prior to the connect or disconnect, and a buffer that is retrieved following a connect or disconnect. Therefore, an application uses connect or disconnect options in much the same manner it uses connect or disconnect data. The only difference is the option names used on the getsockopt and setsockopt calls; for example, use SO_CONNOPT in place of SO_CONNDATA.


  Client Applications and Connect Data

A Windows Sockets client application written for a transport protocol that supports connect data should call setsockopt with SOL_SOCKET as the level, SO_CONNDATA as the option name, and a buffer in the option value field that contains the connect data it intends to send. This call must be made before calling the connect function. The specified connect data is then sent on the connect request.

Two steps are required to retrieve response connect data. First, before the connect call, the application must inform the Windows Sockets DLL how much space to reserve for the response connect data. This is done by calling setsockopt with option level SOL_SOCKET, option name SO_CONNDATALEN, and having the option value parameter point to an integer that contains the maximum number of connect data bytes expected. The Windows Sockets DLL will set aside a buffer of this size to contain connect data sent by the server application.

After the connect has completed successfully, the application can call getsockopt with an option level of SOL_SOCKET, an option name of SO_CONNDATA, and a buffer in the option value parameter large enough to hold the response connect data. The Windows Sockets DLL then copies the response connect data into the caller's buffer.

Note that the Windows Sockets DLL keeps the response connect data buffer valid for the lifetime of the socket. Therefore, an application can retrieve the response connect data for the socket at any time after the socket is connected and before it is closed.


  Server Applications and Connect Data

A server application's use of connect data implicitly differs in two important ways from a client application's use. First, a server application receives the client's connect data before it sends its own. Second, because the socket's interface does not support the concept of delayed accept, a server application is limited to sending the same response connect data to all clients.

A server application that is to receive connect data should use setsockopt with the SO_CONNDATALEN option to force the Windows Sockets DLL to reserve buffer space into which to receive connect data for incoming connect requests. The specified amount of connect data buffer space is used for all incoming connects, but each connect gets a separate buffer. After a new connected socket is accepted with accept the application calls getsockopt with the SO_CONNDATA option and a buffer large enough to hold expected response data. The Windows Sockets DLL fills in this buffer with the connect data sent by the client.

To send connect data, a server application calls setsockopt with the SO_CONNDATA option and a buffer of data before incoming connections are accepted (typically before listen). Thereafter, any client that connects to the server will receive the specified connect data. The connect data sent by a server can be changed at any time with another setsockopt call, which discards the previous data and replaces it with new connect data.


  Disconnect Data

Client and server applications send and receive disconnect data in a manner similar to the way a client application sends and receives connect data. To send disconnect data the application calls setsockopt with the SO_DISCDATA option and a buffer of disconnect data to send. The data will then be sent either when the application calls shutdown to disconnect the send side of the socket or when the application calls closesocket on the socket.

To receive disconnect data, an application must call setsockopt with the SO_DISCDATALEN option before a remote closes the connection. This option specifies the amount of disconnect data the application expects to receive.

After the remote has disconnected, the SO_DISCDATA option on getsockopt retrieves the disconnect data sent by the remote. The application passes in a buffer large enough to hold all the disconnect data, and the Windows Sockets DLL copies the received disconnect data into the buffer.


  Additional Items

The following topics provide details on additional items in Windows Sockets.

•	Blocking Sockets Calls

•	WSAGetLastError vs. GetLastError

•	Closing Sockets: Graceful vs. Abortive

•	Notes on Performance

•	Windows NT Extensions to WINSOCK.H


  Blocking Sockets Calls

The Windows Sockets specification defines a "blocking hook" mechanism, accessed through the WSASetBlockingHook, WSAUnhookBlockingHook, WSAIsBlocking, and WSACancelBlockingCall functions. The blocking hook works by polling for Windows messages while a Windows Sockets function call is blocking on network activity and calling back into the application when a message arrives. This mechanism allows a measure of multitasking to occur within the nonpreemptive Windows environment. In fact, an application that makes blocking calls gets a "default blocking hook" installed, which can result in reentrance to the application if the application makes any calls that must block.The blocking hook is useful for promoting multitasking, but Windows NT, being a fully preemptive, multitasking operating system, doesn't need any help from applications to do multitasking. Additionally, programming Windows applications that use the blocking is complex, requiring special attention to reentrance issues. Therefore, 32-bit applications for Windows NT do not get a default blocking hook installed. If a thread makes a blocking call, the thread simply blocks, and the system schedules other threads as appropriate, waking up the blocked thread when the I/O completes.

If a 32-bit application really does require the blocking hook semantics, such an application can use WSASetBlockingHook to install any blocking hook on a per-thread basis. This blocking hook will operate exactly as specified in the Windows Sockets specification. Note that the fact that the blocking hook is per-thread means two things for multithreaded applications: If they need blocking hooks, they must install a blocking hook for every thread that makes blocking Windows Sockets calls; and they can install a different blocking hook in different threads of their process, allowing different blocking hook behavior in different threads.

If a 16-bit application is ported to Win32 and depends on the behavior of the default blocking hook, the application can install as a blocking hook code that performs the same actions as the default blocking hook:

BOOL

DefaultBlockingHook (

    VOID

    )

{

    MSG msg;

    BOOLEAN retrievedMessage;

    //

    // Get the next message, if any.

    //

    retrievedMessage = PeekMessage(&msg, NULL, 0, 0, PM_REMOVE);

    //

    // Process the message if we got one.

    //

    if (retrievedMessage) {

        TranslateMessage((CONST MSG *)&msg);

        DispatchMessage((CONST MSG *)&msg);

    }

    //

    // If we got a message, indicate that we want to be called again.

    //

    return retrievedMessage;

} // DefaultBlockingHook

Note that 16-bit Windows Sockets applications running in the 16-bit subsystem of Windows NT do get the default blocking hook semantics as described in the Windows Sockets specification, so there is no need to modify 16-bit applications to take advantage of the blocking hook behavior.


  WSAGetLastError vs. GetLastError

Windows Sockets applications use the WSAGetLastError function to retrieve specific error information on failed function calls. For 32-bit applications under Windows NT, the WSAGetLastError function is just a call through to theWin32 GetLastError call, which provides identical functionality. Therefore, if an application makes a Windows Sockets call that fails, then a Win32 function call that also fails, the result of WSAGetLastError will give the error code for the Win32 function failure. In addition, some C run-time calls, specifically printf, reset the thread's last error to zero, so a call to WSAGetLastError after one of these function calls can return the value zero rather than the actual failure code. It is strongly recommended that applications be written to call WSAGetLastError (or GetLastError) immediately after a failed Windows Sockets call is detected without any intervening function calls.

Note also that WSASetLastError is just a call through to SetLastError, so calling WSASetLastError will reset the error obtained by GetLastError.


  Closing Sockets: Graceful vs. Abortive

For transport protocols that support graceful close, Windows NT has been carefully designed to perform graceful closes when appropriate, and to perform abortive close operations when appropriate. By default, closing a connected socket with closesocket results in a graceful close of the virtual circuit. In addition, using shutdown on the send side of a socket initiates a graceful close. If an application is to force an abortive close, it should set the SO_LINGER option on the socket to have a timeout of zero.

Windows NT uses an abortive close to indicate to the remote end that a connection was terminated in an ungraceful manner. There are several causes for this:

•	Closing a socket when there is unreceived data buffered on the socket.

•	Exiting a process without calling closesocket on all connected sockets.

•	Data arrives after the graceful close has been initiated.

•	The SO_LINGER option is nonzero, but some data remains unsent after the timeout expires.

To ensure a graceful close on a virtual circuit, an application must receive all data on the socket and manually call closesocket on the socket. To do this properly, some application protocols require the shutdown function to initiate graceful close in conjunction with recv or WSARecvEx to ensure that all data sent by the remote is received locally.


  Notes on Performance

Application performance can be tuned so that data can be transferred as quickly as possible with minimal burden on the system CPU. There are several general guidelines that can help you tune your code. Many of these simple guidelines will seem obvious, but it is surprising how often they are overlooked.

First, send and receive data in chunks as large as possible, up to approximately 64 kilobytes. There is a certain amount of unavoidable overhead in each send or recv call, and sending and receiving large chunks of data spreads the overhead over fewer calls.

Second, do as little in performance paths as possible. Do not include any extraneous calls, either Windows Sockets or Win32. If you need to send a lot of data, do it in a tight loop without any calls other than send. If you must specify a timeout on the send, do not use the select function, which has the inherent overhead of a kernel transition. Instead, set the SO_SNDTIMEO option on the socket and use send only. If you're handling several sockets in your application, use threads so that you can avoid calls to select (but be careful not to use too many threads — threads cost memory and introduce context switching overhead).

It is possible to achieve very high data transfer rates with the Windows Sockets interface in Windows NT. With TCP/IP on a 10-megabit-per-second ethernet, we have seen rates of more than a megabyte per second, which is close to the theoretical maximum for the medium, and the system CPUs were not fully saturated. This demonstrates that in a carefully coded and tuned application it is possible to achieve excellent performance through Windows Sockets.


  Windows NT Extensions to WINSOCK.H

To support some of the features unique to Windows NT described in this document, the WINSOCK.H header file that is included with the Win32 SDK contains some additional information, as shown:

/*

 * Options for connect and disconnect data and options. Used only by

 * non-TCP/IP transports such as DECNet, OSI TP4, etc.

 */

#define SO_CONNDATA     0x7000

#define SO_CONNOPT      0x7001

#define SO_DISCDATA     0x7002

#define SO_DISCOPT      0x7003

#define SO_CONNDATALEN  0x7004

#define SO_CONNOPTLEN   0x7005

#define SO_DISCDATALEN  0x7006

#define SO_DISCOPTLEN   0x7007

/*

 * Option for opening sockets for synchronous access.

 */

#define SO_OPENTYPE     0x7008

#define SO_SYNCHRONOUS_ALERT    0x10

#define SO_SYNCHRONOUS_NONALERT 0x20

#define WSAEDISCON              (WSABASEERR+101)

int PASCAL FAR WSARecvEx (SOCKET s, char FAR * buf, int len, int *flags);


  Windows Sockets Service Registration and Name Resolution

The service registration and resolution functionality helps you write client server applications. Using this functionality, a service can register its existence with a name space (registration), and a client can find a service within a name space (resolution).


  Service Registration and Resolution Definitions

The following functions and structures let you implement service registration and resolution functionality.


  Service Registration and Resolution Functions

Use these functions to implement service registration and resolution functionality:

EnumProtocols
GetAddressByName
GetNameByType
GetService
GetTypeByName
SetService


  Service Registration and Resolution Structures

Use these structures to implement service registration and resolution functionality:

BLOB
CSADDR_INFO
NS_SERVICE_INFO
PROTOCOL_INFO
SERVICE_ADDRESS
SERVICE_ADDRESSES
SERVICE_INFO
SERVICE_TYPE_INFO_ABS
SERVICE_TYPE_VALUE_ABS


 Introduction to Audio

Microsoft® Windows® provides several different types and levels of audio services. You should become familiar with these types and levels so you can choose the services appropriate for your application. This overview assumes you have a basic knowledge of digital audio and Musical Instrument Digital Interface (MIDI).


 About Audio Services

This overview covers the following topics:

•	Types of audio services

•	Levels of audio services

•	Windows audio architecture

•	Audio file formats

•	Further reading


 Types of Audio Services

Different types of audio services require different formats for the audio information and different technologies to reproduce audio. Windows offers the following types of audio services:

•	Waveform audio services provide playback and recording support for digital audio hardware. Waveform audio is useful for reproducing nonmusical audio material such as sound effects and voice-over narration. Waveform audio has moderate storage-space and data-transfer rate requirements — as low as 11 kilobytes per second of audio.

•	MIDI audio services provide support for MIDI-file and MIDI-event playback (through internal or external synthesizers) and MIDI-event recording. MIDI audio is useful with music-related applications such as music composition and MIDI sequencer programs. Because they require less storage space and a lower data-transfer rate than waveform audio, you may want to use MIDI audio services to provide introductory and background music in your applications.

•	Compact disc (CD) audio services provide support for playback of Red Book audio information on CDs by means of the CD-ROM drive on multimedia computers. CD audio offers the highest quality reproduction of musical material but has the highest storage-space requirements — 176 kilobytes per second of audio. You cannot read from the CD-ROM drive while playing CD audio.


 Levels of Audio Services

The different levels of audio services let you choose services appropriate to the requirements of your application and to your programming ability. Windows offers two levels of audio services:

•	High-level audio services allow you to play and record audio files by using as little as one function call. Compared with low-level audio services, high-level services are easier to use and require less programming. High-level services also meet the audio requirements of most applications.

•	Low-level audio services allow you to communicate directly with audio device drivers to manage playback and recording. Low-level audio services require more programming than high-level services but give you more control over audio playback and recording.

The easiest way to play and record audio is to use high-level audio services. If the high-level audio services do not meet the audio needs of your application, you can use low-level audio services to write your own routines to manage audio playback and recording.


 Windows Audio Architecture

Windows provides audio services through high-level audio functions, Media Control Interface (MCI) device drivers, low-level audio functions, the MIDI Mapper, and low-level audio device drivers. The following illustration shows the relationship between an application and the elements of Windows that provide audio support.


 High-Level Audio Support

MCI functions, along with MCI device drivers, provide high-level audio support for MIDI, waveform, and CD audio devices. MCI drivers can play disk-resident (hard disk and CD-ROM) audio files in the background while an application runs in the foreground. In addition to MCI, Windows provides high-level audio support with three special-purpose functions that play waveform sounds: MessageBeep, PlaySound, and sndPlaySound. You can also use these functions to play waveform sounds associated with system alerts and sounds identified by entries in the registry.

High-level audio functions should meet the audio requirements of most applications. For information about using MCI and the MessageBeep, PlaySound, and sndPlaySound functions, see High-Level Audio.


 Low-Level Audio Support

Low-level audio functions provide a device-independent interface to audio hardware in multimedia computers. These functions supply low-level audio services by letting applications communicate directly with the audio device drivers. MCI drivers and the MessageBeep, PlaySound, and sndPlaySound functions use these low-level functions to provide high-level audio services.

Low-level audio functions are provided for applications — such as audio tools programs — that have special-purpose audio requirements. For example, a MIDI sequencer application would use low-level audio functions to record and play MIDI data. For information about using low-level audio services, see Low-Level Audio.


 The MIDI Mapper

The MIDI Mapper provides standard patch services for device-independent playback of MIDI files. Standard patch services ensure that different MIDI synthesizers use the same instrument sounds to reproduce the music in a MIDI file.

The MIDI Mapper translates and redirects messages sent to it by low-level MIDI output functions. Because the high-level MIDI services use low-level MIDI output functions, the MIDI Mapper can be used with high-level as well as low-level MIDI services. For information about the architecture of the MIDI Mapper and how to use the MIDI Mapper with high-level audio services, see High-Level Audio. For information about using the MIDI Mapper with low-level audio services, see Low-Level Audio. MIDI files must follow certain authoring guidelines to use the standard patch services provided by the MIDI Mapper. For details about these authoring guidelines, see High-Level Audio.


 Audio File Formats

Windows supports a tagged file structure called the Resource Interchange File Format (RIFF). There are two RIFF file formats currently defined for audio files.

RIFF type	Filename extension	Description
RMID	.RMI	MIDI audio file
WAVE	.WAV	Waveform audio file
The WAVE file format supports a number of digital audio data formats. All multimedia computers support pulse code modulated (PCM) formats of 8-bit monaural data at sample rates of 11.025 kilohertz (kHz) and 22.05 kHz.

In addition to Resource Interchange File Format MIDI (RMID) files, the MCI MIDI sequencer plays standard MIDI files in the format defined by the International MIDI Association in the "Standard MIDI Files 1.0" specification. For information about how to obtain this specification, see Further Reading. RMID files are standard MIDI files with a RIFF header.


 Using RIFF Files

The multimedia file input and output (I/O) services include functions for working with RIFF files. For information about using these functions, see Multimedia File Input/Output.


 Further Reading

For more information on digital audio, digital-signal processing, and computer music, see the following books:

Boom, Michael. Music Through MIDI. Redmond: Microsoft Press, 1987.

Chamberlin, Hal. Musical Applications of Microprocessors. Hasbrouk Heights: Hayden Book Company, Inc., 1985.

Pohlmann, Ken. Principles of Digital Audio. Indianapolis: Howard W. Sams & Co., 1985.

Roads, Curtis, and John Strawn. Foundations of Computer Music. Cambridge: The MIT Press, 1985.

Strawn, John F. Digital Audio Engineering, An Anthology. Los Altos: William Kaufmann, Inc., 1985.

Strawn, John F. Digital Audio Signal Processing, An Anthology. Los Altos: William Kaufmann, Inc., 1985.

For information about MIDI and standard MIDI files, see the following MIDI specifications:

MIDI 1.0 Detailed Specification

Standard MIDI Files 1.0 Specification

These specifications are available from the International MIDI Association at the following address:

International MIDI Association
5316 West 57th Street
Los Angeles, CA 90056


 High-Level Audio

This overview explains how to use the high-level audio services of Microsoft® Windows® to add sound to applications. For an overview of the audio services, see Introduction to Audio.

This overview covers the following topics:

•	Playing waveform sounds

•	Playing and Recording Audio Using the Media Control Interface

•	Opening waveform and MIDI sequencer devices

•	Authoring MIDI files

The topics in this overview assume you have a basic knowledge of digital audio and MIDI. For additional information on these subjects, see Further Reading.


 Function Prefixes

High-level audio function names begin with the following prefixes:

Prefix	Function group
snd	System-alert sound functions
mci	MCI functions


 Playing Waveform Sounds

One basic way to use sound is to associate a sound with a user action or with a warning or alert message. These sounds tend to be short in duration and are often played repeatedly. Windows provides three functions to play waveform sounds.

Function	Description
MessageBeep	Plays the sound that corresponds to a given system-alert level.
PlaySound	Plays the sound that corresponds to the given filename or registry entry.
sndPlaySound	Plays the sound that corresponds to the given filename or registry entry.
These functions provide methods of playing the following waveform sounds:

•	WAVE files stored on a hard disk or CD-ROM

•	In-memory WAVE resources

•	WAVE files specified by entries in the registry

•	WAVE files associated with system-alert levels


 Restrictions in Playing Waveform Sounds

There are some restrictions to using the MessageBeep, PlaySound, and sndPlaySound function to play waveform sounds:

•	The entire sound must fit in available physical memory.

•	The sound must be in a data format playable by one of the installed waveform audio device drivers.

Use MessageBeep, PlaySound, and sndPlaySound to play WAVE files that are relatively small in size — up to about 100 kilobytes. For larger sound files, use the MCI services. For information about using MCI, see Playing and Recording Audio Using the Media Control Interface.


 Using the PlaySound and sndPlaySound Functions

The PlaySound and sndPlaySound functions can be used to perform the following tasks:

•	Playing WAVE files

•	Looping High-Level Audio Sounds

•	Playing High-Level Audio WAVE Resources

•	Playing High-Level Audio Sounds Specified in the Registry

Although the examples shown in these topics use the sndPlaySound function, most of the sample code works with the PlaySound function as well.


 Playing WAVE Files

The following statement plays the C:\SOUNDS\BELLS.WAV file.

sndPlaySound("C:\\SOUNDS\\BELLS.WAV", SND_SYNC);

If the specified file does not exist or does not fit into the available physical memory, sndPlaySound plays the default system sound specified by the SystemDefault entry in the [sounds] section of the registry. If there is no SystemDefault entry, sndPlaySound fails without producing any sound. If you don't want the default system sound to play, specify the SND_NODEFAULT flags in the following example.

sndPlaySound("C:\\SOUNDS\\BELLS.WAV", SND_SYNC | SND_NODEFAULT);


 Looping High-Level Audio Sounds

If you specify the SND_LOOP and SND_ASYNC flags for the wFlags parameter of the sndPlaySound function, as in the following example, the sound continues to play repeatedly.

sndPlaySound("C:\\SOUNDS\\BELLS.WAV", SND_LOOP | SND_ASYNC);

If you want to "loop" a sound, you must play it asynchronously. You cannot use the SND_SYNC flag with the SND_LOOP flag. A looped sound continues to play until sndPlaySound is called to play another sound. To stop playing a looped or asynchronous sound without playing another sound, use the following statement.

sndPlaySound(NULL, 0);


 Playing High-Level Audio WAVE Resources

You can also build WAVE files into an application as resources and use the sndPlaySound function to play these sounds by specifying the SND_MEMORY flag. The SND_MEMORY flag indicates that the lpszSoundName parameter is a pointer to an in-memory image of the WAVE file. To include a WAVE file as a resource in an application, add the following entry to the application's resource script (.RC) file.

soundName WAVE c:\sounds\bells.wav

The name soundName is a placeholder for a name that you supply to refer to this WAVE resource. WAVE resources are loaded and accessed just like other application-defined Windows resources. The function in the following example plays a specified WAVE resource.

/* Plays a specified WAVE resource. */

BOOL PlayResource(LPSTR lpName)

{

    BOOL bRtn;

    LPSTR lpRes;

    HANDLE hResInfo, hRes;

    /* Find the WAVE resource. */

    hResInfo = FindResource(hInst, lpName, "WAVE");

    if (hResInfo == NULL)

        return FALSE;

    /* Load the WAVE resource. */

    hRes = LoadResource(hInst, hResInfo);

    if (hRes == NULL)

        return FALSE;

    /* Lock the WAVE resource and play it. */

    lpRes = LockResource(hRes);

    if (lpRes != NULL) {

        bRtn = sndPlaySound(lpRes, SND_MEMORY | SND_SYNC |

            SND_NODEFAULT);

        UnlockResource(hRes);

    }

    else

        bRtn = 0;

    /* Free the WAVE resource and return success or failure. */

    FreeResource(hRes);

    return bRtn;

}

To play a WAVE resource by using this function, pass to the function a pointer to a string containing the name of the resource, as shown in the following example.

PlayResource("soundName");


 Playing High-Level Audio Sounds Specified in the Registry

The sndPlaySound function also plays waveform sounds referred to by a key-name in the [sounds] section of the registry. This enables users to assign their own sounds to system alerts and warnings, or to user actions such as mouse-button click. For example, the [sounds] section of the registry might look like the following.

[sounds]

SystemDefault=C:\SOUNDS\BUMMER.WAV, Says BUMMER

SystemAsterisk=C:\SOUNDS\WHALES.WAV, Whale sounds

SystemExclamation=C:\SOUNDS\LASER.WAV, Laser gun sounds

SystemHand=C:\SOUNDS\OHOH.WAV, Says OH-OH

SystemQuestion=C:\SOUNDS\JIBERISH.WAV, Person mumbling

SystemStart=C:\SOUNDS\CHORD.WAV, Plays a chord

MouseClick=C:\SOUNDS\CLICK.WAV, Recording of a clicking sound

To play a sound identified by a registry entry, call sndPlaySound with the lpszSoundName parameter pointing to a string that contains the name of the entry that identifies the sound. For example, to play the sound associated with the MouseClick entry in the [sounds] section of the registry and wait for the sound to finish before returning, use the following statement.

sndPlaySound("MouseClick", SND_SYNC);

If the specified registry entry or the waveform file it identifies does not exist, or if the sound does not fit into the available physical memory, sndPlaySound plays the default system sound specified by the SystemDefault entry. If there is no SystemDefault entry, sndPlaySound fails without producing any sound. If you don't want the default system sound to play, specify the SND_NODEFAULT flag, as in the following example.

sndPlaySound("MouseClick", SND_SYNC | SND_NODEFAULT);

Note  The sndPlaySound function always searches the [sounds] section of the registry for a keyname matching the lpszSoundName parameter before attempting to load a file with this name.

The [sounds] section of the registry includes an optional string following the waveform filename for descriptive text about the sound in the file. This descriptive text is displayed in the Sound option of the Control Panel.


 Playing System-Alert Sounds

The MessageBeep function uses the waveform audio hardware to produce a variety of user-selectable sounds.

When you call MessageBeep, it searches the [sounds] section of the registry for the WAVE file that corresponds to the specified alert level. Following are the registry entries for system-alert sounds.

Registry Entry	Description
SystemDefault	Identifies the sound produced when the MessageBeep function is called with the wAlert  parameter set to an invalid alert level or when the requested alert sound can't be found. This is called the default system sound.
SystemAsterisk	Identifies the sound produced when MessageBeep is called with wAlert set to MB_ICONASTERISK.
SystemExclamation	Identifies the sound produced when MessageBeep is called with wAlert set to MB_ICONEXCLAMATION.
SystemHand	Identifies the sound produced when MessageBeep is called with wAlert set to MB_ICONHAND.
SystemQuestion	Identifies the sound produced when MessageBeep is called with wAlert set to MB_ICONQUESTION.
If MessageBeep is called with wAlert set to zero, it plays the default system sound. If wAlert is set to −1, MessageBeep uses the computer speaker to produce a standard beep sound. If MessageBeep can't play the requested sound, it plays the default system sound. If it can't play the default system sound, then it produces a beep sound using the computer speaker.

The Sound option of the Control Panel enables users to set these registry entries to customize their environment for system-alert sounds. It also enables users to disable these alert sounds.


 Playing and Recording Audio Using the Media Control Interface

The Media Control Interface (MCI) provides a high-level interface for controlling both internal and external media devices. It provides support for playing wave- form, MIDI, and compact disc audio and for recording waveform audio. MCI is the easiest way for multimedia applications to play and record audio.

MCI uses device drivers to interpret and execute high-level MCI commands. MCI device drivers can stream digital audio and MIDI data directly from a storage device to the appropriate device driver, allowing applications to play files too large to fit in available physical memory. This data streaming takes place in the background while an application is running. The application is responsible only for setting up MCI and telling it to start playing or recording.

MCI provides two types of interface: command-message and command-string. This section explains how to use the command-message interface for waveform, MIDI, and compact disc audio devices. For an introduction to MCI and for information about the command-string interface, see Media Control Interface.


 MCI Audio Data Types

The MMSYSTEM.H header file defines data types and function prototypes for MCI. You must include this header file in any source-code module that uses MCI functions.

Following are the data types for structures used with extended MCI commands related to audio.

Type	Description
MCI_SEQ_SET_PARMS	Specifies a structure for the MCI_SET command message for MIDI sequencer devices.
MCI_WAVE_DELETE_PARMS	Specifies a structure for the MCI_DELETE command message for waveform audio devices.
MCI_WAVE_OPEN_PARMS	Specifies a structure for the MCI_OPEN command message for waveform audio devices.
MCI_WAVE_SET_PARMS	Specifies a structure for the MCI_SET command message for waveform audio devices.


 MCI Audio Commands

MCI provides a standard set of commands applying to all types of media devices. Some of these commands can be extended to accommodate unique features of a particular type of device.

Following are the MCI command messages that perform common audio playback and recording tasks.

MCI command message	Audio task
MCI_OPEN	Open an audio device.
MCI_CLOSE	Close an audio device.
MCI_PLAY	Play all or part of audio selection; resume playback from pause.
MCI_STOP	Stop playback.
MCI_PAUSE	Pause playback.
MCI_SEEK	Change current location.
MCI_CUE	Cue a device so playback or recording begins with minimum delay.
MCI_RECORD	Begin recording on a waveform audio device.
MCI_SAVE	Save a recorded waveform audio file.
MCI_INFO	Query device information such as the product name and the name of the device element currently associated with the device (returns information in string format).
MCI_GETDEVCAPS	Query device capabilities such as the device name and number of inputs and outputs (if the device can record).
MCI_STATUS	Query device status such as current playback position, media length, media format, time format, record level, CD audio track, and MIDI sequencer tempo.
MCI_SET	Set device parameters such as time format, waveform data format, and MIDI sequencer tempo.


 Opening MCI Audio Devices

MCI requires that audio devices be opened before they can be accessed. Use the MCI_OPEN command message along with the MCI_OPEN_PARMS structure to open an audio device and obtain an MCI device identifier. Subsequent commands use this device identifier to identify the device to receive the command.

The MCI device identifier is returned in the wDeviceID member. Always check the return value of the mciSendCommand function after sending an MCI_OPEN command message before using this device identifier. A nonzero return value indicates that there was an error in opening the device and that the returned device identifier is not valid.

For waveform audio devices, you can use an extended structure, MCI_WAVE_OPEN_PARMS. This structure has a dwBufferSeconds member to specify the number of seconds of buffering used by the MCI waveform device driver. If you use this member, you must specify the MCI_WAVE_OPEN_BUFFER flag for the dwParam1 parameter of mciSendCommand to validate the member.

If you do not want to specify the number of seconds of buffering for the driver to use, you can use the MCI_WAVE_OPEN_PARMS structure when you open waveform audio devices.

When you open a simple device, such as a compact disc audio device, you must specify the device name. When you open a compound device, such as a waveform or MIDI sequencer device, the device name is optional. Use the lpstrDeviceType member of the MCI_OPEN_PARMS structure to specify the device name. MCI lets you use a string or a constant for this member. Following are the strings and constants for MCI audio devices.

Device	String	Constant
Compact disc	cdaudio	MCI_DEVTYPE_CD_AUDIO
Waveform	waveaudio	MCI_DEVTYPE_WAVEFORM_AUDIO
MIDI sequencer	sequencer	MCI_DEVTYPE_SEQUENCER
A string is the default format for specifying device names. If you use a constant to specify the device name, you must specify the MCI_OPEN_TYPE_ID flag in addition to the MCI_OPEN_TYPE flag.


 Opening Waveform and MIDI Sequencer Devices

Waveform and MIDI sequencer devices are compound devices. Compound devices require an associated device element — a WAVE or MIDI file. There are three ways to open compound devices:

•	Specify only the device name.

•	Specify only the device element and let MCI select the device associated with the file extension of the device element.

•	Specify both the device name and the device element.

Specify only the device name when opening a device to query its capabilities with the MCI_GETDEVCAPS command message and when you plan to use the device to play more than one device element.

If you don't specify a device name when you open a compound device, MCI chooses an appropriate device type by comparing the file extension of the device element with entries in the [mci extensions] section of the registry. The following example uses this technique to open a MIDI sequencer device to play a MIDI file named CHOPIN.RMI.

UINT wDeviceID;

MCI_OPEN_PARMS mciOpenParms;

.ifdef REF

    .

    .

    .

.endif

/* Open the device by specifying only the device element. */

mciOpenParms.lpstrElementName = "CHOPIN.RMI";

if (mciSendCommand(0,                           /* device ID */

        MCI_OPEN,                               /* command   */

        MCI_OPEN_ELEMENT,                       /* flags     */

        (DWORD) (LPVOID) &mciOpenParms))  /* parameter block */

    /* Error, unable to open device. */

    return FALSE;

else

    /* Device opened successfully. Get the device ID. */

    wDeviceID = mciOpenParms.wDeviceID;

Instead of letting MCI choose the device, you can specify the device name when you open the device. The following example uses this technique to open a waveform audio device to play the BELLS.WAV file. This example uses a string to specify the device name. For an example using a constant to specify the device name, see Opening Compact Disc Devices.

UINT wDeviceID;

MCI_OPEN_PARMS mciOpenParms;

.ifdef REF

    .

    .

    .

.endif

/*

 * Open the device by specifying both the device

 * element and the device name.

 */

mciOpenParms.lpstrDeviceType = "waveaudio";

mciOpenParms.lpstrElementName = "C:\\SOUNDS\\BELLS.WAV";

if (mciSendCommand(0,                           /* device ID */

        MCI_OPEN,                               /* command   */

        MCI_OPEN_ELEMENT | MCI_OPEN_TYPE,       /* flags     */

        (DWORD) (LPVOID) &mciOpenParms))  /* parameter block */

    /* Error, unable to open device. */

    return FALSE;

else

    /* Device opened successfully. Get the device ID. */

    wDeviceID = mciOpenParms.wDeviceID;


 Using the MIDI Mapper With the MCI Sequencer

The MIDI Mapper is the default output device for the MCI MIDI sequencer. It provides standard patch services for device-independent playback of MIDI files. Applications that use the MCI sequencer to play MIDI files should use the MIDI Mapper. For details about the MIDI Mapper, see The MIDI Mapper. For information about authoring device-independent MIDI files, see Authoring MIDI Files.

When you open the MCI MIDI sequencer, MCI attempts to select the MIDI Mapper as the output device. If the MIDI Mapper is unavailable because it is already in use, MCI selects another MIDI output device.

Note  The MIDI Mapper currently supports only one client at a time in the current versions of Microsoft Windows NT.

After opening the sequencer, you should check to see if the MIDI Mapper was available and was selected as the output device. The following example uses the MCI_STATUS command message to verify that the MIDI Mapper is the output device for the MCI sequencer.

UINT wDeviceID;

DWORD dwReturn;

MCI_STATUS_PARMS mciStatusParms;

.ifdef REF

    .

    .

    .

.endif

/* Make sure the opened device is the MIDI Mapper. */

mciStatusParms.dwItem = MCI_SEQ_STATUS_PORT;

if (dwReturn = mciSendCommand(wDeviceID, MCI_STATUS,

        MCI_STATUS_ITEM, (DWORD)(LPVOID) &mciStatusParms)) {

    /* Error sending MCI_STATUS command. */

}

if (LOWORD(mciStatusParms.dwReturn) == MIDI_MAPPER) {

    /* The MIDI Mapper is the output device. */

}

else {

    /* The MIDI Mapper is not the output device. */

}

MCI also provides a command message that explicitly selects the MIDI Mapper as the output device for the sequencer. The following example uses the MCI_SET command message to select the MIDI Mapper as the output device for the MCI sequencer.

UINT wDeviceID;

DWORD dwReturn;

MCI_SEQ_SET_PARMS mciSeqSetParms;

.ifdef REF

    .

    .

    .

.endif

/* Set the MIDI Mapper as the output port for the open device. */

mciSeqSetParms.dwPort = MIDI_MAPPER;

if (dwReturn = mciSendCommand(wDeviceID, MCI_SET, MCI_SEQ_SET_PORT,

                              (DWORD)(LPVOID) &mciSeqSetParms)) {

    /* Error, unable to set Mapper as output port. */

}

Before querying the sequencer or setting an output port, you must successfully open the sequencer. Both of the previous examples assume that the wDeviceID parameter contains a valid device identifier for the sequencer.


 Opening Compact Disc Devices

Because a compact disc audio device is a simple device, you need only specify the device name when opening it by using either a string or a constant device identifier. The following example opens a compact disc device by using a constant device identifier to specify the device name.

UINT wDeviceID;

MCI_OPEN_PARMS mciOpenParms;

.ifdef REF

    .

    .

    .

.endif

/* Open the device by specifying a constant device ID. */

mciOpenParms.lpstrDeviceType = (LPCSTR) MCI_DEVTYPE_CD_AUDIO;

if (mciSendCommand(0,                           /* device ID */

        MCI_OPEN,                               /* command   */

        MCI_OPEN_TYPE | MCI_OPEN_TYPE_ID,       /* flags     */

        (DWORD) (LPVOID) &mciOpenParms))  /* parameter block */

    /* Error, unable to open device. */

    return FALSE;

else

    /* Device opened successfully. Get the device ID. */

    wDeviceID = mciOpenParms.wDeviceID;


 Handling High-Level Audio MCI Errors

Always check the return value of the mciSendCommand function. If it indicates an error, you can use the mciGetErrorString function to get a textual description of the error. You can also interpret the error code yourself; MMSYSTEM.H defines constants for MCI error return codes.

Note  To interpret an error return value from mciSendCommand yourself, mask the high-order word; the low-order word contains the error code. However, if you pass the error return value to the mciGetErrorString function, you must pass the entire doubleword value.

The following example function takes the MCI error code specified by dwError, passes it to mciGetErrorString, and displays the resulting textual error description by using the MessageBox function.

/*

 * Uses mciGetErrorString to get a

 * text description of an MCI error.

 * Displays the error description by using MessageBox.

 */

void showError(DWORD dwError)

{

    char szErrorBuf[MAXERRORLENGTH];

    MessageBeep(MB_ICONEXCLAMATION);

    if(mciGetErrorString(dwError, (LPSTR) szErrorBuf,

            MAXERRORLENGTH))

        MessageBox(hMainWnd, szErrorBuf,

                "MCI Error", MB_ICONEXCLAMATION);

    else

        MessageBox(hMainWnd, "Unknown Error", "MCI Error",

                MB_ICONEXCLAMATION);

}


 Starting Playback

Once you successfully open an MCI audio device, you can use the MCI_PLAY command message along with the MCI_PLAY_PARMS structure to begin playback. MMSYSTEM.H defines MCI_PLAY_PARMS as follows.

typedef struct {

        DWORD   dwCallback; /* callback for MCI_NOTIFY flag */

        DWORD   dwFrom;     /* playback begin position */

        DWORD   dwTo;       /* playback end position */

} MCI_PLAY_PARMS;

Playback begins at the current position in the device element. When a device element is opened, the current position is set to the beginning of the medium. After a device element is played, the current position is at the end of the medium. You can use the MCI_SEEK command message to change the current position. For more information about MCI_SEEK, see Changing the Current Position.

You can also set beginning and ending positions for playback by specifying the MCI_FROM and MCI_TO flags with the MCI_PLAY command message. If you specify one of these flags, you must fill in the corresponding dwFrom or dwTo member in the MCI_PLAY_PARMS structure with the desired beginning or ending time. If you are using a time format other than the default time format, you must set the time format before specifying a beginning or ending time with MCI_PLAY.


 Example: Playing a WAVE File

The following example function opens a waveform device and plays the WAVE file specified by the lpszWAVEFileName parameter.

/*

 * Plays a given WAVE file by using MCI_OPEN, MCI_PLAY.

 * Returns when playback

 * begins. Returns 0L on success;

 * otherwise returns an MCI error code.

 */

DWORD playWAVEFile(HWND hWndNotify, LPSTR lpszWAVEFileName)

{

    UINT wDeviceID;

    DWORD dwReturn;

    MCI_OPEN_PARMS mciOpenParms;

    MCI_PLAY_PARMS mciPlayParms;

    /*

     * Open the device by specifying the

     * device name and device element.

     * MCI will choose a device capable

     * of playing the given file.

     */

    mciOpenParms.lpstrDeviceType = "waveaudio";

    mciOpenParms.lpstrElementName = lpszWAVEFileName;

    if (dwReturn = mciSendCommand(0, MCI_OPEN,

            MCI_OPEN_TYPE | MCI_OPEN_ELEMENT,

            (DWORD)(LPVOID) &mciOpenParms)) {

        /*

         * Failed to open device;

         * don't close it, just return error.

         */

        return dwReturn;

    }

    /* Device opened successfully. Get the device ID. */

    wDeviceID = mciOpenParms.wDeviceID;

    /*

     * Begin playback. The window-procedure function

     * for the parent window is notified with an

     * MM_MCINOTIFY message when playback is

     * complete. The window procedure then

     * closes the device.

     */

    mciPlayParms.dwCallback = (DWORD) hWndNotify;

    if (dwReturn = mciSendCommand(wDeviceID, MCI_PLAY,

            MCI_NOTIFY, (DWORD)(LPVOID) &mciPlayParms)) {

        mciSendCommand(wDeviceID, MCI_CLOSE, 0, NULL);

        return dwReturn;

    }

    return 0;

}


 Example: Playing a MIDI File

The following example function opens a MIDI sequencer device, verifies that the MIDI Mapper was selected as the output port, plays the MIDI file specified by the lpszMIDIFileName parameter, and closes the device after playback is complete.

/*

 * Plays a given MIDI file using MCI_OPEN, MCI_PLAY.

 * Returns as soon as playback begins. The window

 * procedure function for the given window is notified

 * when playback is complete. Returns 0L on success;

 * otherwise returns an MCI error code.

 */

DWORD playMIDIFile(HWND hWndNotify, LPSTR lpszMIDIFileName)

{

    UINT wDeviceID;

    DWORD dwReturn;

    MCI_OPEN_PARMS mciOpenParms;

    MCI_PLAY_PARMS mciPlayParms;

    MCI_STATUS_PARMS mciStatusParms;

    /*

     * Open the device by specifying the

     * device name and device element.

     * MCI will attempt to choose the

     * MIDI Mapper as the output port.

     */

    mciOpenParms.lpstrDeviceType = "sequencer";

    mciOpenParms.lpstrElementName = lpszMIDIFileName;

    if (dwReturn = mciSendCommand(NULL, MCI_OPEN,

            MCI_OPEN_TYPE | MCI_OPEN_ELEMENT,

            (DWORD)(LPVOID) &mciOpenParms)) {

        /*

         * Failed to open device;

         * don't close it, just return error.

         */

        return dwReturn;

    }

    /* Device opened successfully. Get the device ID. */

    wDeviceID = mciOpenParms.wDeviceID;

    /* See if the output port is the MIDI Mapper. */

    mciStatusParms.dwItem = MCI_SEQ_STATUS_PORT;

    if (dwReturn = mciSendCommand(wDeviceID, MCI_STATUS,

            MCI_STATUS_ITEM,

            (DWORD)(LPVOID) &mciStatusParms)) {

        mciSendCommand(wDeviceID, MCI_CLOSE, 0, NULL);

        return dwReturn;

    }

    /*

     * The output port is not the MIDI Mapper.

     * Ask if user wants to continue.

     */

    if (LOWORD(mciStatusParms.dwReturn) != MIDI_MAPPER) {

        if (MessageBox(hMainWnd,

                "The MIDI Mapper is not available. Continue?",

                "", MB_YESNO) == IDNO) {

            /*

             * User does not want to continue. Not an error;

             * just close the device and return.

             */

            mciSendCommand(wDeviceID, MCI_CLOSE, 0, NULL);

            return 0;

        }

    }

    /*

     * Begin playback. The window procedure function

     * for the parent window is notified with an

     * MM_MCINOTIFY message when playback is complete.

     * The window procedure then closes the device.

     */

    mciPlayParms.dwCallback = (DWORD) hWndNotify;

    if (dwReturn = mciSendCommand(wDeviceID, MCI_PLAY,

            MCI_NOTIFY, (DWORD)(LPVOID) &mciPlayParms)) {

        mciSendCommand(wDeviceID, MCI_CLOSE, 0, NULL);

        return dwReturn;

    }

    return 0;

}


 Example: Playing a Compact Disc Track

The following example function opens a compact disc device, plays the track specified by the wTrack parameter, and closes the device after playback is complete.

/*

 * Plays a given compact disc track using

 * MCI_OPEN, MCI_PLAY. Returns as

 * soon as playback begins. The window procedure

 * function for the given window will be notified

 * when playback is complete. Returns 0L on

 * success; otherwise, it returns an MCI error code.

 */

DWORD playCDTrack(HWND hWndNotify, BYTE bTrack)

{

    UINT wDeviceID;

    DWORD dwReturn;

    MCI_OPEN_PARMS mciOpenParms;

    MCI_SET_PARMS mciSetParms;

    MCI_PLAY_PARMS mciPlayParms;

    /*

     * Open the compact disc device by specifying

     * the device name.

     */

    mciOpenParms.lpstrDeviceType = "cdaudio";

    if (dwReturn = mciSendCommand(NULL, MCI_OPEN,

            MCI_OPEN_TYPE, (DWORD)(LPVOID) &mciOpenParms)) {

        /*

         * Failed to open device;

         * don't close it, just return error.

         */

        return dwReturn;

    }

    /* Device opened successfully, get the device ID. */

    wDeviceID = mciOpenParms.wDeviceID;

    /* Set the time format to track/minute/second/frame. */

    mciSetParms.dwTimeFormat = MCI_FORMAT_TMSF;

    if (dwReturn = mciSendCommand(wDeviceID, MCI_SET,

            MCI_SET_TIME_FORMAT, (DWORD)(LPVOID) &mciSetParms)) {

        mciSendCommand(wDeviceID, MCI_CLOSE, 0, NULL);

        return dwReturn;

    }

    /*

     * Begin playback from the given track and play

     * until the beginning of the next track. The window

     * procedure function for the parent window will be

     * notified with an MM_MCINOTIFY message when playback

     * is complete. Unless the play command fails, the

     * window procedure closes the device.

     */

    mciPlayParms.dwFrom = MCI_MAKE_TMSF(bTrack, 0, 0, 0);

    mciPlayParms.dwTo = MCI_MAKE_TMSF(bTrack + 1, 0, 0, 0);

    mciPlayParms.dwCallback = (DWORD) hWndNotify;

    if (dwReturn = mciSendCommand(wDeviceID, MCI_PLAY,

            MCI_FROM | MCI_TO | MCI_NOTIFY,

            (DWORD)(LPVOID) &mciPlayParms)) {

        mciSendCommand(wDeviceID, MCI_CLOSE, 0, NULL);

        return dwReturn;

    }

    return 0;

}

To specify a track-relative position with a compact disc device, you must use the track/minute/second/frame time format. For details, see Setting the Time Format.


 Changing the Current Position

To change the current position in a device element, use the MCI_SEEK command message along with the MCI_TO flag and the MCI_SEEK_PARMS structure. MMSYSTEM.H defines MCI_SEEK_PARMS as follows.

typedef struct {

        DWORD   dwCallback; /* callback for MCI_NOTIFY flag */

        DWORD   dwTo;       /* seek position */

} MCI_SEEK_PARMS;

If you use the dwTo member to specify a seek position with MCI_SEEK, you should query the time format and set it, if necessary.

In addition to specifying a position with the dwTo member, you can specify the MCI_SEEK_TO_START or MCI_SEEK_TO_END flags for the dwParam1 parameter of the mciSendCommand function to find the starting and ending positions of the device element. If you use one of these flags, don't specify the MCI_TO flag.


 Setting the Time Format

Use the MCI_SET command message along with the MCI_SET_PARMS structure to set the time format for an open device. Set the dwTimeFormat member to one of the following constants.

Constant	Time format
MCI_FORMAT_BYTES	Bytes (in pulse code modulated [PCM] format files)
MCI_FORMAT_MILLISECONDS	Milliseconds
MCI_FORMAT_MSF	Minute/second/frame
MCI_FORMAT_SAMPLES	Samples
MCI_FORMAT_SMPTE_24	SMPTE, 24 frame
MCI_FORMAT_SMPTE_25	SMPTE, 25 frame
MCI_FORMAT_SMPTE_30	SMPTE, 30 frame
MCI_FORMAT_SMPTE_30DROP	SMPTE, 30 frame drop
MCI_FORMAT_TMSF	Track/minute/second/frame
MCI_SEQ_FORMAT_SONGPTR	MIDI song pointer
The following example sets the time format to milliseconds on the device specified by wDeviceID:

UINT wDeviceID;

MCI_SET_PARMS mciSetParms;

.ifdef REF

    .

    .

    .

.endif

/* Set time format to milliseconds. */

mciSetParms.dwTimeFormat = MCI_FORMAT_MILLISECONDS;

if (mciSendCommand(wDeviceID, MCI_SET, MCI_SET_TIME_FORMAT,

                   (DWORD) &mciSetParms))

    /* Error, unable to set time format. */

    return FALSE;

else

    /* Time format set successfully. */

    return TRUE;


 Using the Minute/Second/Frame Time Format

In the minute/second/frame time format specified with the MCI_FORMAT_MSF constant, the time is relative to the beginning of the medium. The time is packed into a double as follows.

Word	Byte	Contents
High-order word	High-order byte	Unused
	Low-order byte	Frames
Low-order word	High-order byte	Seconds
	Low-order byte	Minutes
The MMSYSTEM.H header file defines the following macros to get and set elements of a minute/second/frame packed doubleword.

Macro	Description
MCI_MSF_MINUTE	Gets minute value in a minute/second/frame doubleword.
MCI_MSF_SECOND	Gets second value in a minute/second/frame doubleword.
MCI_MSF_FRAME	Gets frame value in a minute/second/frame doubleword.
MCI_MAKE_MSF	Sets minute, second, and frame values in a minute/second/frame doubleword.
Note  The first few seconds of audio compact discs contain table-of-contents data. To play from the beginning of a disc using the minute/second/frame time format, use the MCI_STATUS command message to get the position of the first track and play from that position.


 Using the Track/Minute/Second/Frame Time Format

In the track/minute/second/frame time format specified with the MCI_FORMAT_TMSF constant, the time is relative to the beginning of the specified track. The time is packed into a doubleword, as follows.

Word	Byte	Contents
High-order word	High-order byte	Frames
	Low-order byte	Seconds
Low-order word	High-order byte	Minutes
	Low-order byte	Track
The MMSYSTEM.H header file defines the following macros to get and set elements of a track/minute/second/frame packed doubleword.

Macro	Description
MCI_TMSF_TRACK	Gets track value in a track/minute/second/frame doubleword.
MCI_TMSF_MINUTE	Gets minute value in a track/minute/second/frame doubleword.
MCI_TMSF_SECOND	Gets second value in a track/minute/second/frame doubleword.
MCI_TMSF_FRAME	Gets frame value in a track/minute/second/frame doubleword.
MCI_MAKE_TMSF	Sets track, minute, second, and frame values in a track/minute/second/frame doubleword.


 Using the SMPTE Time Formats

Society of Motion Picture and Television Engineers (SMPTE) time formats are based on standard time formats developed for the motion picture and television industries. For SMPTE time formats, the time is packed into a doubleword, as shown in the following table follows.

Word	Byte	Contents
High-order word	High-order byte	Frames
	Low-order byte	Seconds
Low-order word	High-order byte	Minutes
	Low-order byte	Hours


 Closing MCI Audio Devices

After you finish using an MCI device, you must use the MCI_CLOSE command messages to close the device. If you are playing a compound device, such as a waveform or MIDI device, and want to play a different device element using the same device, close the device and reopen it using the new device element.

Note  If you're playing multiple device elements with the same device, you'll get better performance if you open the device by explicitly specifying its name, then open, play, and close the individual device elements separately. Don't close the device until you have finished playing all of the device elements. Otherwise, the driver is reloaded each time you open the device.


 Getting Information About Devices and Media

Use the MCI_STATUS command message along with the MCI_STATUS_PARMS structure to get information about the status of an open device and its associated device element.

Before using the MCI_STATUS command message, you must identify the status item to query for by putting a constant in the dwItem member of the structure. Select a topic below to view the constants and their corresponding status items for the different audio device types.

All Audio Devices
Waveform Devices
Compact Disc Devices
MIDI Sequencer Devices


 All Audio Devices

Constant	Status item
MCI_STATUS_LENGTH	Length of the medium
MCI_STATUS_POSITION	Current position
MCI_STATUS_MODE	Current mode
MCI_STATUS_TIME_FORMAT	Time format
MCI_STATUS_READY	Ready state


 Waveform Devices

Constant	Status item
MCI_WAVE_STATUS_BLOCKALIGN	Block alignment
MCI_WAVE_STATUS_FORMATTAG	Format tag
MCI_WAVE_STATUS_CHANNELS	Number of channels
MCI_WAVE_STATUS_SAMPLESPERSEC	Sample rate
MCI_WAVE_STATUS_AVGBYTESPERSEC	Average bytes per second
MCI_WAVE_STATUS_BITSPERSAMPLE	Bits per sample (in PCM format files)
MCI_WAVE_STATUS_LEVEL	Record level


 Compact Disc Devices

Constant	Status item
MCI_STATUS_NUMBER_OF_TRACKS	Number of tracks
MCI_STATUS_MEDIA_PRESENT	Media present
MCI_STATUS_CURRENT_TRACK	Current track


 MIDI Sequencer Devices

Constant	Status item
MCI_SEQ_STATUS_TEMPO	Tempo
MCI_SEQ_STATUS_PORT	Port
MCI_SEQ_STATUS_OFFSET	SMPTE offset
MCI_SEQ_STATUS_DIVTYPE	Division type of file


 Getting Track-Relative Information for Compact Disc Devices

For compact disc devices, you can get the starting position and length of a track by specifying the MCI_TRACK flag and setting the dwTrack member of the MCI_STATUS_PARMS structure to the desired track number. To get the starting position of a track, set the dwItem member to MCI_STATUS_POSITION. To get the length of a track, set dwItem to MCI_STATUS_LENGTH. The following function gets the number of tracks on the disc and the starting position of each track. It then uses the MessageBox function to report the starting positions of the tracks.

/*

 * Uses the MCI_STATUS command to get and

 * display the starting times for the tracks

 * on a compact disc. Returns 0L on success;

 * otherwise, it returns an MCI error code.

 */

DWORD getCDTrackStartTimes(void)

{

    UINT wDeviceID;

    int i, iNumTracks;

    DWORD dwReturn;

    DWORD *pMem;

    char szTempString[64];

    char szTimeString[512] = "\0"; /* enough for 20 tracks */

    MCI_OPEN_PARMS mciOpenParms;

    MCI_SET_PARMS mciSetParms;

    MCI_STATUS_PARMS mciStatusParms;

    /* Open the compact disc device by specifying the device name.

     */

    mciOpenParms.lpstrDeviceType = "cdaudio";

    if (dwReturn = mciSendCommand(NULL, MCI_OPEN,

            MCI_OPEN_TYPE,

            (DWORD)(LPVOID) &mciOpenParms)) {

        /*

         * Failed to open device.

         * Don't have to close it; just return error.

         */

        return dwReturn;

    }

    /* Device opened successfully. Get the device ID. */

    wDeviceID = mciOpenParms.wDeviceID;

    /* Set the time format to minute/second/frame format. */

    mciSetParms.dwTimeFormat = MCI_FORMAT_MSF;

    if (dwReturn = mciSendCommand(wDeviceID, MCI_SET,

            MCI_SET_TIME_FORMAT,

            (DWORD)(LPVOID) &mciSetParms)) {

        mciSendCommand(wDeviceID, MCI_CLOSE, 0, NULL);

        return dwReturn;

    }

    /* Get the number of tracks; limit to number

     * we can display (20).

     */

    mciStatusParms.dwItem = MCI_STATUS_NUMBER_OF_TRACKS;

    if (dwReturn = mciSendCommand(wDeviceID, MCI_STATUS,

            MCI_STATUS_ITEM,

            (DWORD)(LPVOID) &mciStatusParms)) {

        mciSendCommand(wDeviceID, MCI_CLOSE, 0, NULL);

        return dwReturn;

    }

    iNumTracks = mciStatusParms.dwReturn;

    iNumTracks = min(iNumTracks, 20);

    /* Allocate memory to hold starting positions. */

    pMem = (DWORD *)LocalAlloc(LPTR, iNumTracks * sizeof(DWORD));

    if (pMem == NULL) {

        mciSendCommand(wDeviceID, MCI_CLOSE, 0, NULL);

        return 0xFFFFFFFF;

    }

    /*

     * For each track, get and save the starting position and

     * build a string containing starting positions.

     */

    for(i = 1; i <= iNumTracks; i++) {

        mciStatusParms.dwItem = MCI_STATUS_POSITION;

        mciStatusParms.dwTrack = i;

        if (dwReturn = mciSendCommand(wDeviceID, MCI_STATUS,

                MCI_STATUS_ITEM | MCI_TRACK,

                (DWORD)(LPVOID) &mciStatusParms)) {

            mciSendCommand(wDeviceID, MCI_CLOSE, 0, NULL);

            return dwReturn;

        }

        pMem[i-1] = mciStatusParms.dwReturn;

        wsprintf(szTempString, "Track %2d - %02d:%02d:%02d\n",

                 i, MCI_MSF_MINUTE(pMem[i-1]),

                 MCI_MSF_SECOND(pMem[i-1]),

                 MCI_MSF_FRAME(pMem[i-1]));

        lstrcat(szTimeString, szTempString);

    }

    /* Use MessageBox to display starting times. */

    MessageBox(hMainWnd, szTimeString, "Track Starting Position",

               MB_ICONINFORMATION);

    /* Free memory and close the device. */

    LocalFree((HANDLE) pMem);

    if (dwReturn = mciSendCommand(wDeviceID,

            MCI_CLOSE, 0, NULL)) {

            return dwReturn;

    }

    return 0;

}


 Recording With Waveform Audio Devices

MCI supports recording with waveform audio devices. You can insert or overwrite recorded information in an existing file or record into a new file. To open an existing file for recording, open a waveform device and device element as you would open them for playback. To record into a new file, open the device but specify a zero-length filename for the device element.

When MCI creates a new file for recording, the waveform data format is set to a default format specified by the device driver. To use a format other than the default format, you can use the MCI_SET command message to change the format.

To begin recording, use the MCI_RECORD command message along with the MCI_RECORD_PARMS structure.

If you record to an existing file, you can use the MCI_TO and MCI_FROM flags to specify beginning and ending points for recording. For example, if you record to an existing file 20 seconds long, and you begin recording at 5 seconds and end recording at 10 seconds, you will have a recording 25 seconds long. It will contain 5 seconds of the original recording followed by the 5 seconds of new recording, and will end with the remaining 15 seconds of the original recording.

If you don't specify an ending position, recording continues until you send an MCI_STOP command message, or until the driver runs out of free disk space. If you record to a new file, you can omit the MCI_FROM flag or set it to 0 to start recording at the beginning of a new file. You can specify an ending position to terminate recording when recording to a new file.

If you record in overwrite mode to an existing file, you can use the MCI_TO and MCI_FROM flags to specify beginning and ending points of the waveform section that is to be overwritten. For example, if you record to an existing file 20 seconds long, and you begin recording at 5 seconds and end recording at 10 seconds, you still have a recording 20 seconds long. However, the section beginning at 5 seconds and ending at 10 seconds has been replaced.


 Saving a Recorded File

When recording is complete, use the MCI_SAVE command message along with the MCI_SAVE_PARMS structure to save the recording before closing the device.

If you close the device without saving, the recorded data is lost.


 Checking Input Levels on PCM Devices

To get the level of the input signal before recording on a pulse code modulated (PCM) waveform input device, use the MCI_STATUS command message. Specify the MCI_STATUS_ITEM flag and set the dwItem member in the MCI_STATUS_PARMS structure to MCI_WAVE_STATUS_LEVEL. The average input signal level is returned in the dwReturn member of the MCI_STATUS_PARMS structure. The left-channel value is in the high-order word, and the right- or mono-channel value is in the low-order word.

The input level is represented as an unsigned value. For 8-bit samples, this value is in the range 0 through 127 (0x7F). For 16-bit samples, it is in the range 0 through 32,767 (0x7FFF).


 Example of Recording With a Waveform Audio Device

The following example function opens a waveform audio device with a new file, records for the specified time, plays the recording, and prompts the user to specify whether the recording should be saved as a file.

/*

 * Uses the MCI_OPEN, MCI_RECORD, MCI_SAVE commands to record and

 * save a waveform audio file. Returns 0L on success; otherwise,

 * returns an MCI error code.

 */

DWORD recordWAVEFile(DWORD dwMilliSeconds)

{

    UINT wDeviceID;

    DWORD dwReturn;

    MCI_OPEN_PARMS mciOpenParms;

    MCI_RECORD_PARMS mciRecordParms;

    MCI_SAVE_PARMS mciSaveParms;

    MCI_PLAY_PARMS mciPlayParms;

    /*

     * Open a waveform device with a new file for recording.

     */

    mciOpenParms.lpstrDeviceType = "waveaudio";

    mciOpenParms.lpstrElementName = "";

    if (dwReturn = mciSendCommand(0, MCI_OPEN,

            MCI_OPEN_ELEMENT | MCI_OPEN_TYPE,

            (DWORD)(LPVOID) &mciOpenParms)) {

        /*

         * Failed to open device. Don't close it; just return

         * error.

         */

        return dwReturn;

    }

    /* Device opened successfully. Get the device ID. */

    wDeviceID = mciOpenParms.wDeviceID;

    /*

     * Begin recording and record for the specified number

     * of milliseconds. Wait for recording to complete before

     * continuing. Assume the default time format for the

     * waveform device (milliseconds).

     */

    mciRecordParms.dwTo = dwMilliSeconds;

    if (dwReturn = mciSendCommand(wDeviceID, MCI_RECORD,

            MCI_TO | MCI_WAIT, (DWORD)(LPVOID) &mciRecordParms)) {

        mciSendCommand(wDeviceID, MCI_CLOSE, 0, NULL);

        return dwReturn;

    }

    /* Play the recording and query user to save the file. */

    mciPlayParms.dwFrom = 0;

    if (dwReturn = mciSendCommand(wDeviceID, MCI_PLAY,

            MCI_FROM | MCI_WAIT,

            (DWORD)(LPVOID) &mciPlayParms)) {

        mciSendCommand(wDeviceID, MCI_CLOSE, 0, NULL);

        return dwReturn;

    }

    if (MessageBox(hMainWnd, "Do you want to save this recording?",

            "", MB_YESNO) == IDNO) {

        mciSendCommand(wDeviceID, MCI_CLOSE, 0, NULL);

        return 0;

    }

    /*

     * Save the recording to a file named TEMPFILE.WAV. Wait for

     * the operation to finish before continuing.

     */

    mciSaveParms.lpfilename = "tempfile.wav";

    if (dwReturn = mciSendCommand(wDeviceID, MCI_SAVE,

            MCI_SAVE_FILE | MCI_WAIT,

            (DWORD)(LPVOID) &mciSaveParms)) {

        mciSendCommand(wDeviceID, MCI_CLOSE, 0, NULL);

        return dwReturn;

    }

    return 0;

}


 Using the MCI MIDI Sequencer with High-Level Audio

The MCI MIDI sequencer plays standard MIDI files and Resource Interchange File Format (RIFF) MIDI files (RMID files). Standard MIDI files conform to the "Standard MIDI Files 1.0" specification. For information about this specification, see Introduction to Audio. Because RMID files are standard MIDI files with a RIFF header, information about standard MIDI files also applies to RMID files.

There are currently three variations of standard MIDI files. The MCI sequencer plays only two of these: format 0 and format 1 MIDI files.

Note  When the MCI MIDI sequencer encounters a MIDI file not marked as being authored for Windows, it displays a dialog box informing the user. MIDI files authored for Windows should be marked with the MARKMIDI utility program. For additional information about MARKMIDI, see Using the MARKMIDI Utility.

•	Querying for sequence division types

•	Querying and Setting the MIDI Tempo

•	Changing sequencer synchronization


 Querying for Sequence Division Types

The division type of a MIDI sequence refers to the technique used to represent the time between MIDI events in the sequence. Use the MCI_STATUS command message and set the dwItem member of the MCI_STATUS_PARMS structure to MCI_SEQ_STATUS_DIVTYPE to determine the division type of a sequence.

If the MCI_STATUS command message succeeds, the dwReturn member of the MCI_STATUS_PARMS structure contains one of the following values to indicate the division type.

Value	Division type
MCI_SEQ_DIV_PPQN	PPQN (parts per quarter-note)
MCI_SEQ_DIV_SMPTE_24	SMPTE, 24 frames per second (fps)
MCI_SEQ_DIV_SMPTE_25	SMPTE, 25 fps
MCI_SEQ_DIV_SMPTE_30	SMPTE, 30 fps
MCI_SEQ_DIV_SMPTE_30DROP	SMPTE, 30 fps drop frame
You must know the division type of a sequence to change or query its tempo. You can't change the division type of a sequence by using the MCI sequencer.


 Querying and Setting the MIDI Tempo

Use the MCI_STATUS command message and set the dwItem member of the MCI_STATUS_PARMS structure to MCI_SEQ_STATUS_TEMPO to get the tempo of a sequence. If the MCI_STATUS command message succeeds, the dwReturn member of the MCI_STATUS_PARMS structure contains the current tempo.

To change tempo, use the MCI_SET command message with the MCI_SEQ_SET_PARMS structure. Specify the MCI_SEQ_SET_TEMPO flag and set the value of the dwTempo member of the structure to the desired tempo.

The way tempo is represented depends on the division type of the sequence. If the division type is PPQN, the tempo is represented in beats per minute. If the division type is one of the SMPTE division types, the tempo is represented in frames per second. For information about determining the division type of a sequence, Querying for Sequence Division Types.


 Changing Sequencer Synchronization

To change the synchronization mode of a sequencer device, use the MCI_SET command message with the MCI_SEQ_SET_MASTER and MCI_SEQ_SET_SLAVE flags. Two members in the MCI_SEQ_SET_PARMS structure, dwMaster and dwSlave, are used to specify the master and slave synchronization modes.

The master synchronization mode controls synchronization information sent by the sequencer to an output port. The slave synchronization mode controls where the sequencer gets its timing information to play a MIDI file. Following are the constants for the dwMaster member and their corresponding master synchronization modes.

Constant	Synchronization mode
MCI_SEQ_MIDI	MIDI Synchronization. Send timing information to output port using MIDI timing clock messages.
MCI_SEQ_SMPTE	SMPTE Synchronization. Send timing information to output port using MIDI quarter-frame messages.
MCI_SEQ_NONE	No Synchronization. Send no timing information.
Following are the constants for the dwSlave member and their corresponding slave synchronization modes.

Constant	Synchronization mode
MCI_SEQ_FILE	File Synchronization. Get timing information from MIDI file.
MCI_SEQ_MIDI	MIDI Synchronization. Get timing information from input port using MIDI timing clock messages.
MCI_SEQ_SMPTE	SMPTE Synchronization. Get timing information from input port using MIDI quarter-frame messages.
MCI_SEQ_NONE	No Synchronization. Get timing information from MCI commands only and ignore timing information (such as tempo changes) that are in the MIDI file.
Note  Currently, for master synchronization, the MCI MIDI sequencer supports only the No Synchronization mode (MCI_SEQ_NONE). For slave synchronization, it supports only the File Synchronization mode (MCI_SEQ_FILE) and the No Synchronization mode (MCI_SEQ_NONE).


 The MIDI Mapper

The MIDI Mapper's standard patch services provide device-independent MIDI file playback for applications. You don't need to understand exactly how the MIDI Mapper works to use these services. The MIDI Mapper can be used with the MCI MIDI sequencer or with low-level MIDI output services.

To learn more about the MIDI Mapper or about authoring standard MIDI files for Windows, press the browse button (>>) to view more topics about how the MIDI Mapper works. For specific information about how to use the MIDI Mapper, see Using the MCI MIDI Sequencer or Low-Level Audio.


 MIDI Notational Conventions

Unless stated otherwise, all references to MIDI channel numbers use the logical channel numbers 1 through 16. These logical channel numbers correspond to the physical channel numbers 0 through 15 that are actually part of the MIDI message. All references to MIDI program-change and key values use the physical values 0 through 127. All numbers are decimal unless preceded by 0x prefix, in which case they are hexadecimal.

In the discussion of the MIDI Mapper, the term source refers to the input side of the MIDI Mapper. The term destination refers to the output side of the MIDI Mapper. For example, a source channel is the MIDI channel of a message sent to the MIDI Mapper, and a destination channel is the MIDI channel of a message sent from the MIDI Mapper to an output device.


 The MIDI Mapper and Windows

The MIDI Mapper is part of the system software. The following illustration shows how the MIDI Mapper relates to other elements of the audio services.

From the viewpoint of an application, the MIDI Mapper looks like another MIDI output device. The MIDI Mapper receives messages sent to it by the low-level MIDI output functions midiOutShortMsg and midiOutLongMsg. The MIDI Mapper modifies these messages and redirects them to a MIDI output device according to the current MIDI setup map. The current MIDI setup map is selected by the user by means of the MIDI Control Panel option. Only the user can select the current setup map; applications cannot change the current setup map.


 The MIDI Mapper Architecture

The MIDI Mapper uses a MIDI setup map to determine how to translate and redirect messages it receives. A MIDI setup map consists of the following types of maps.

•	Channel map

•	Patch map

•	Key map

The following illustration shows the roles of channel, patch, and key maps in a MIDI setup map.


 The Channel Map

The channel map affects all MIDI channel messages. MIDI channel messages include note-on, note-off, polyphonic-key-aftertouch, control-change, program- change, channel-aftertouch, and pitch-bend-change messages. The MIDI Mapper uses a single channel map with an entry for each of the 16 MIDI channels. Each channel-map entry specifies the following:

•	A destination channel for the MIDI message

•	A destination output device for the MIDI message

•	An optional patch map specifying other possible modifications for the MIDI message

The destination channel is set to one of the 16 MIDI channels. MIDI messages are modified to reflect each new channel assignment. For example, if the destination channel entry for MIDI channel 4 is set to 6, all MIDI messages sent to channel 4 will be mapped to channel 6, as shown in the following illustration.

In this example, the MIDI status byte 0x93 is mapped to 0x95. The low-order of a MIDI status byte specify the channel number. Source channels are set to either active or inactive. Messages sent to inactive source channels are ignored, so an inactive channel is in effect muted or turned off.

The destination output device is set to one of the available MIDI output devices. A MIDI output device can be an internal synthesizer or a physical MIDI output port.

MIDI system messages are MIDI messages (with status bytes) from 0xF0 to 0xFF. There is no channel associated with MIDI system messages, so they can't be mapped. MIDI system messages are sent to all MIDI output devices listed in a channel map.


 Patch Maps

Each channel map entry can have an associated patch map. Patch maps affect MIDI program-change and volume-controller messages. Program-change messages tell a synthesizer to change the instrument sound (patch) for a specified channel. Volume-controller messages set the volume for a channel.

A patch map has a translation table with an entry for each of the 128 program-change values. Each patch map specifies the following:

•	A destination program-change value

•	A volume scalar

•	An optional key map

When program-change messages are received by the MIDI Mapper, the destination program-change value is substituted for the program-change value in the message. For example, if the destination program-change value for program-change 16 is 18, the MIDI Mapper modifies the MIDI program-change message as shown in the following illustration.


 The Volume Scalar

The purpose of the volume scalar is to allow adjustments between the relative output levels of different patches on a synthesizer. For example, if the bass patch on a synthesizer is too loud compared with its piano patch, you can change the setup map to scale the bass volume down or the piano volume up.

The volume scalar specifies a percentage value for changing all MIDI main-volume controller messages that follow an associated program-change message. For example, if the volume scalar value is 50%, the MIDI Mapper modifies MIDI main-volume controller messages as shown in the following illustration:


 Key Maps

Each entry in the patch-map translation table can have an associated key map. Key maps affect note-on, note-off, and polyphonic-key-aftertouch messages. A key map has a translation table with an entry for each of the 128 MIDI key values. For example, if the entry for key value 60 is 72, the MIDI Mapper modifies MIDI note-on messages as shown in the following illustration.

Key maps are useful with synthesizers that have key-based percussion instruments with a particular percussion sound assigned to each key. Key maps are usually assigned to the first patch in the patch maps on the percussion channels (10 and 16).


 Summary of Maps and MIDI Messages

Following are the status bytes for MIDI messages and the map types that affect each message.

MIDI status	Description	Map types
0x80−0x8F	Note-off	Channel maps, key maps
0x90−0x9F	Note-on	Channel maps, key maps
0xA0−0xAF	Polyphonic-key-aftertouch	Channel maps, key maps
0xB0−0xBF	Control-change	Channel maps, patch maps
0xC0−0xCF	Program-change	Channel maps, patch maps
0xD0−0xDF	Channel-aftertouch	Channel maps
0xE0−0xEF	Pitch-bend-change	Channel maps
0xF0−0xFF	System	Not mapped
•	The high-order four bits represent the status value. The low-order four bits represent the channel information.

•	Patch maps affect only controller 7 (main volume).

•	System messages are sent to all devices listed in a channel map.


 Authoring MIDI Files

The "MIDI 1.0 Detailed Specification" does not define any standard patch assignments for synthesizers. Therefore, when you create a MIDI file, it won't be reproduced correctly unless it is played back on the same MIDI synthesizer setup used to create it. For example, if you create a piano concerto for your Yamaha® DX7 and try to play it back on a Roland® LAPC-1, it may be played with a flute instead of a piano.

To enable MIDI files to be a viable format for representing music in multimedia computing, Windows provides MIDI authoring guidelines. These guidelines include a list of standard patch assignments and standard key assignments for percussion instruments. Using the MIDI Mapper, MIDI files authored in accordance with these guidelines can be played on any multimedia computer with internal or external MIDI synthesizers.


 About Base-Level and Extended Synthesizers

Although it is difficult to clearly quantify distinctions between synthesizers, it is important to have some guidelines so you can create MIDI files that will play on all multimedia computers. The terms used to distinguish synthesizers for the purpose of authoring MIDI files are base-level synthesizer and extended synthesizer.

The distinctions between base-level and extended synthesizers are made solely on the number of instruments and notes the synthesizer can play, not on the quality or the cost of the synthesizer. Following are the minimum capabilities of base-level and extended synthesizers.

Synthesizer	Melodic instruments		Percussive instruments
	Number	Polyphony	Number	Polyphony
Base-level	3 instruments	6 notes	3 instruments	3 notes
Extended	9 instruments	16 notes	8 instruments	16 notes
Polyphony is the number of notes the synthesizer can play simultaneously. The polyphony expressed above applies to each group of instruments — melodic and percussive. For example, a base-level synthesizer is capable of playing six notes distributed among three melodic instruments and three notes distributed among three percussive instruments. Each melodic instrument is on a different MIDI channel; the percussive instruments are key-based — all on a single MIDI channel.

All multimedia computers provide at least a base-level synthesizer. Users can enhance their computer by adding internal or external synthesizers, which can be either base-level or extended synthesizers. When adding a synthesizer, the user must configure the MIDI Mapper to use the new device. If the MIDI Mapper is not configured, the instrument sounds will be incorrect when MIDI files are played, unless the application has the ability to send output directly to an internal synthesizer or output port. The MIDI Control Panel option allows a user to configure the MIDI Mapper as needed.


 Authoring Guidelines for MIDI Files

Follow these guidelines to author device-independent MIDI files for Windows:

•	Author for both base-level and extended synthesizer setups.

•	Use MIDI channels 13 through 16 for base-level synthesizer data (reserve channel 16 for key-based percussion instruments).

•	Use MIDI channels 1 through 10 for extended synthesizer data (reserve channel 10 for key-based percussion instruments).

•	Prioritize MIDI data by putting crucial data in the lower-numbered channels.

•	Limit the polyphony of nonpercussive channels to a total of 6 notes for base-level data and 16 notes for extended data.

•	Limit the polyphony of percussive channels to a total of 3 notes for base-level data and 16 notes for extended data.

•	Use the standard MIDI patch assignments and key assignments.

•	Always send a program-change message to a channel to select a patch before sending other messages to that channel. For the two percussion channels (10 and 16), select program number 0.

•	Always follow a MIDI program-change message with a MIDI main-volume controller message (controller number 7) to set the relative volume of the patch.

•	Use a value of 80 (0x50) for the main-volume controller for normal listening levels. For quieter or louder levels, you can use lower or higher values.

•	Use only the following MIDI messages: note-on with velocity, note-off, program change, pitch bend, main volume (controller 7), and damper pedal (controller 64). Internal synthesizers are required to respond to these messages and most MIDI musical instruments respond to them as well.

•	Use the MARKMIDI utility program to mark MIDI files authored for Windows.

The following illustration summarizes the use of the 16 MIDI channels in a standard MIDI file authored for Windows.


 Prioritizing MIDI Data

Synthesizers don't always fall cleanly into the base-level and extended designations defined earlier. It's up to the user to determine how to use synthesizers that are capable of more than the base-level requirements but do not fully meet the extended requirements. For this reason, it's important to prioritize the melodic data by putting the most critical data in lower-numbered channels. For example, a user may have a synthesizer capable of playing six melodic instruments with 12-note polyphony. The user can use this device as an extended synthesizer by setting up the MIDI Mapper to play only the first six melodic channels and ignore any information on channels 7, 8, and 9.


 Standard MIDI Patch Assignments

The standard MIDI patch assignments for authoring MIDI files for use with Windows are based on the MIDI Manufacturers Association (MMA) General MIDI Mode specification. Following are the standard MIDI patch assignments.

Piano	Chromatic Percussion	Organ
0 Acoustic grand piano	8 Celesta	16 Hammond organ
1 Bright acoustic piano	9 Glockenspiel	17 Percussive organ
2 Electric grand piano	10 Music box	18 Rock organ
3 Honky-tonk piano	11 Vibraphone	19 Church organ
4 Rhodes piano	12 Marimba	20 Reed organ
5 Chorused piano	13 Xylophone	21 Accordion
6 Harpsichord	14 Tubular bells	22 Harmonica
7 Clavinet	15 Dulcimer	23 Tango accordion
Guitar	Bass	Strings
24 Acoustic guitar (nylon)	32 Acoustic bass	40 Violin
25 Acoustic guitar (steel)	33 Electric bass (finger)	41 Viola
26 Electric guitar (jazz)	34 Electric bass (pick)	42 Cello
27 Electric guitar (clean)	35 Fretless bass	43 Contrabass
28 Electric guitar (muted)	36 Slap bass 1	44 Tremolo strings
29 Overdriven guitar	37 Slap bass 2	45 Pizzicato strings
30 Distortion guitar	38 Synth bass 1	46 Orchestral harp
31 Guitar harmonics	39 Synth bass 2	47 Timpani
Ensemble	Brass	Reed
48 String ensemble 1	56 Trumpet	64 Soprano sax
49 String ensemble 2	57 Trombone	65 Alto sax
50 Synth. strings 1	58 Tuba	66 Tenor sax
51 Synth. strings 2	59 Muted trumpet	67 Baritone sax
52 Choir Aahs	60 French horn	68 Oboe
53 Voice Oohs	61 Brass section	69 English horn
54 Synth voice	62 Synth. brass 1	70 Bassoon
55 Orchestra hit	63 Synth. brass 2	71 Clarinet
Pipe	Synth Lead	Synth Pad
72 Piccolo	80 Lead 1 (square)	88 Pad 1 (new age)
73 Flute	81 Lead 2 (sawtooth)	89 Pad 2 (warm)
74 Recorder	82 Lead 3 (calliope lead)	90 Pad 3 (polysynth)
75 Pan flute	83 Lead 4 (chiff lead)	91 Pad 4 (choir)
76 Bottle blow	84 Lead 5 (charang)	92 Pad 5 (bowed)
77 Shakuhachi	85 Lead 6 (voice)	93 Pad 6 (metallic)
78 Whistle	86 Lead 7 (fifths)	94 Pad 7 (halo)
79 Ocarina	87 Lead 8 (brass + lead)	95 Pad 8 (sweep)
Sound Effects
120 Guitar fret noise
121 Breath noise
122 Seashore
123 Bird tweet
124 Telephone ring
125 Helicopter
126 Applause
127 Gunshot


 Standard MIDI Key Assignments

The standard MIDI key assignments for percussion instruments are based on the MMA General MIDI Mode specification. The following illustration shows the standard key assignments for MIDI files authored for Windows.


 Using the MARKMIDI Utility

The MARKMIDI utility program marks MIDI files as following the authoring guidelines for Windows MIDI files. The program does not verify that the file is authored correctly; it only marks the file by adding a sequencer-specific meta-event to the first track chunk. MARKMIDI has the following command syntax.

MARKMIDI src-filename dest-filename

If the MCI MIDI sequencer is used to play a MIDI file not marked by MARKMIDI, it displays a dialog box informing the user that the file is not authored for Windows.

Note  Do not use MARKMIDI to mark MIDI files unless the files were authored according to the guidelines presented in this guide. If your application uses MIDI files not authored to these guidelines, the application must instruct users to install or create the proper maps by using the MIDI Mapper Control Panel application. For example, if your application uses MIDI files following the General MIDI channel recommendations, your users should create or install a General MIDI map for their synthesizers.


 High-Level Audio Functions

Following are the functions used with high-level audio services.

mciGetCreatorTask
mciGetDeviceID
mciGetErrorString
mciGetYieldProc
mciSendCommand
mciSendString
mciSetYieldProc
PlaySound
sndPlaySound


 Low-Level Audio

This overview explains how to use the low-level audio services of Microsoft® Windows® to manage playback and recording of waveform and Musical Instrument Digital Interface (MIDI) audio.

For an overview of Windows audio services, see Introduction to Audio. For a discussion of high-level audio services, see High-Level Audio.

This overview covers the following topics:

•	Using low-level audio services

•	Playing waveform audio

•	Recording waveform audio

•	Playing MIDI audio

•	Recording MIDI audio

•	Using auxiliary audio devices

•	Using audio clipboard formats

You should have a basic knowledge of digital audio and MIDI before reading this overview. If you need additional information on these subjects, see Introduction to Audio.


 Function Prefixes

Low-level audio function names begin with the following prefixes.

Prefix	Description
aux	Auxiliary audio functions
midi	MIDI audio functions
wave	Waveform audio functions


 Using Low-Level Audio Services

Low-level audio services control different types of audio devices, including waveform, MIDI, and auxiliary audio devices. Many of the concepts for using low-level services apply to more than one type of device. The following topics present general information on using low-level audio services:

•	Querying audio devices

•	Opening and closing device drivers

•	Allocating and preparing audio data blocks

•	Managing audio data blocks

•	Using the MMTIME structure

•	Handling errors with audio functions

Subsequent topics in this overview discuss the use of specific types of audio devices.


 Querying Audio Devices

Before playing or recording audio, you must determine the capabilities of the audio hardware present in the system. Audio capability can vary from one multimedia computer to the next; applications should not make assumptions about the audio hardware present in a given system.


 Getting the Number of Devices

The Win32 application programming interface (API) provides the following functions to determine how many devices of a certain type are available in a given system.

Function	Description
auxGetNumDevs	Retrieves the number of auxiliary audio devices present in the system.
midiInGetNumDevs	Retrieves the number of MIDI input devices present in the system.
midiOutGetNumDevs	Retrieves the number of MIDI output devices present in the system.
waveInGetNumDevs	Retrieves the number of waveform input devices present in the system.
waveOutGetNumDevs	Retrieves the number of waveform output devices present in the system.
Audio devices are identified by a device identifier. The device identifier is determined implicitly from the number of devices present in a given system. Device identifiers range from zero to one less than the number of devices present. For example, if there are two MIDI output devices in a system, valid device identifiers are 0 and 1.


 Getting the Capabilities of a Device

After you determine how many devices of a certain type are present in a system, you can inquire about the capabilities of each device. The Win32 API provides the following functions to determine the capabilities of audio devices.

Function	Description
auxGetDevCaps	Retrieves the capabilities of a given auxiliary audio device.
midiInGetDevCaps	Retrieves the capabilities of a given MIDI input device.
midiOutGetDevCaps	Retrieves the capabilities of a given MIDI output device.
waveInGetDevCaps	Retrieves the capabilities of a given waveform input device.
waveOutGetDevCaps	Retrieves the capabilities of a given waveform output device.
Each of these functions takes a pointer to a structure that it fills with information on the capabilities of a specified device. Following are the structures that correspond to each of the device-inquiry functions.

Function	Structure
auxGetDevCaps	AUXCAPS
midiInGetDevCaps	MIDIINCAPS
midiOutGetDevCaps	MIDIOUTCAPS
waveInGetDevCaps	WAVEINCAPS
waveOutGetDevCaps	WAVEOUTCAPS


 Opening and Closing Low-Level Audio Device Drivers

After getting the capabilities of an audio device, you must open the device before you can use it. Audio devices aren't guaranteed to be shareable, so a particular device might not be available when you request it. If this happens, you should notify the user and allow the user to try to open the device again. When you open an audio device, be sure to close it as soon as you finish using it.

The Win32 API provides the following functions to open and close different types of audio devices.

Function	Description
midiInOpen	Opens a specified MIDI input device for recording.
midiInClose	Closes a specified MIDI input device.
midiOutOpen	Opens a MIDI output device for playback.
midiOutClose	Closes a specified MIDI output device.
waveInOpen	Opens a waveform input device for recording.
waveInClose	Closes a specified waveform input device.
waveOutOpen	Opens a waveform output device for playback.
waveOutClose	Closes a specified waveform output device.
These functions are discussed in detail later in this section.


 About Device Handles

Each function that opens an audio device takes as parameters a device identifier, a pointer to a memory location, and some parameters unique to each type of device. The memory location is filled with a device handle. Use this device handle of identify the open audio device when calling other audio functions.

The distinction between audio-device identifiers and audio-device handles is subtle, but very important. Don't confuse the two in your application. Following are the differences between device identifiers and device handles.

•	Device identifiers are determined implicitly from the number of devices present in a system, which is obtained by using the device-numbering functions (auxGetNumDevs, midiInGetNumDevs, and so on).

•	Device handles are returned when device drivers are opened by using the device-opening functions (midiInOpen, midiOutOpen, and so on)

•	The only functions that take device identifiers as parameters are the device-capabilities functions (waveOutGetDevCaps, midiInGetDevCaps, and so on), the device-opening functions, and volume functions (waveOutGetVolume, waveOutSetVolume, and so on). All other functions take device handles.

There are no functions for opening and closing auxiliary audio devices. Auxiliary audio devices don't need to be opened and closed like MIDI and waveform devices because there is no continuous data transfer associated with them. All auxiliary audio functions take device identifiers to identify devices.


 Allocating and Preparing Audio Data Blocks

Some low-level audio functions require applications to allocate data blocks to pass to the device drivers for playback or recording purposes. Each of these functions uses a structure (or header) to describe its data block. The following table identifies these functions and their associated header structures. (The MMSYSTEM.H file defines the data structures for these headers.)

Function	Header structure	Purpose
waveOutWrite	WAVEHDR	Waveform playback
waveInAddBuffer	WAVEHDR	Waveform recording
midiOutLongMsg	MIDIHDR	MIDI system-exclusive playback
midiInAddBuffer	MIDIHDR	MIDI system-exclusive recording
Before you use one of the functions listed above to pass a data block to a device driver, you must allocate memory for the data block according to the guidelines discussed in the following topics.


 Allocating Memory for Audio Data Blocks

Before preparing a data block, you must allocate memory for the data block and the header structure that describes the data block.

To allocate memory, use the GlobalAlloc function with the GMEM_MOVEABLE flag to get a handle of the memory object. Then pass this handle of the GlobalLock function to get a pointer to the memory object.

To free a data block, use GlobalUnlock and GlobalFree.


 Preparing Audio Data Blocks

Before you pass an audio data block to a device driver, you must prepare the data block by passing it to a header-preparation function. When the device driver is finished with the data block and returns it, you must clean up this preparation by passing the data block to a header clean-up function before any allocated memory can be freed.

Windows provides the following functions for preparing and cleaning up audio data blocks.

Function	Description
midiInPrepareHeader	Prepares a MIDI-input data block.
midiInUnprepareHeader	Cleans up the preparation on a MIDI-input data block.
midiOutPrepareHeader	Prepares a MIDI-output data block.
midiOutUnprepareHeader	Cleans up the preparation on a MIDI-output data block.
waveInPrepareHeader	Prepares a waveform-input data block.
waveInUnprepareHeader	Cleans up the preparation on a waveform-input data block.
waveOutPrepareHeader	Prepares a waveform-output data block.
waveOutUnprepareHeader	Cleans up the preparation on a waveform-output data block.


 Managing Audio Data Blocks

Unless the audio data is small enough to be contained in a single data block, applications must continually supply the device driver with data blocks until playback or recording is complete. This is true for waveform input and output, and for MIDI system-exclusive input messages. Regular MIDI channel messages don't require data blocks for input or output.

Even if a single data block is used, applications must be able to determine when a device driver is finished with the data block so the application can free the memory associated with the data block and header structure. There are three ways to determine when a device driver is finished with a data block:

•	Specify a window to receive a message sent by the driver when it is finished with a data block.

•	Specify a callback function to receive a message sent by the driver when it is finished with a data block.

•	Poll a bit in the dwFlags member of the WAVEHDR or MIDIHDR data structure sent with each data block.

If an application doesn't get a data block to the device driver when needed, there can be an audible gap in playback or a loss of incoming recorded information. Use a double-buffering scheme to stay at least one data block ahead of the device driver.

Note  To get time-stamped MIDI input data, you must use a callback function.


 Using a Window to Process Driver Messages

The easiest type of callback function to use to process driver messages is a window callback. To use a window callback, specify the CALLBACK_WINDOW flag in the dwFlags parameter and a window handle as the dwCallback parameter of the device-opening function. Driver messages will be sent to the window-procedure function for the window identified by the handle in dwCallback.

Messages sent to the window function are specific to the audio device type used. For details on these messages, see the topics later in this section on using window messages for each specific audio device type.


 Using a Callback Function to Process Low-Level Audio Driver Messages

You can also write your own low-level callback function to process messages sent by the device driver. To use a low-level callback function, specify the CALLBACK_FUNCTION flag in the dwFlags parameter and the address of the callback in the dwCallback parameter of the device-opening function.

Messages sent to a callback function are similar to messages sent to a window, except that they have two doubleword parameters instead of one unsigned-integer and one doubleword parameter. For details on these messages, see the sections later in this section about using low-level callbacks for each specific audio device type.

Callback functions for the low-level audio services are often called from another thread running asynchronously from the application's thread. It is therefore important to use critical sections to protect data shared between the callback routine and the rest of the application. For more information about critical sections, see Synchronization.

There are several differences between callback functions for the low-level audio services under Windows NT and under Windows 3.1:

•	Under Windows 3.1, a low-level audio callback function is called at interrupt time. The call to a low-level audio callback function occurs on a separate thread under Windows NT.

•	Under Windows 3.1, a low-level audio callback function has to be in a dynamic-link library. Under Windows NT, there is no such restriction.

•	Under Windows 3.1, a low-level audio callback function must be exported in a .DEF file. Under Windows NT, that is not necessary.

If source code must be compatible with Windows 3.1, it should follow the Windows 3.1 rules as noted briefly above and specified more fully in the Windows 3.1 documentation.

One other item should be noted carefully. There is a limited set of APIs that a Windows 3.1 low-level audio callback function may call. In Win32, that strict limitation has been removed. However, it is strongly recommended that a Windows NT low-level audio callback function restrain its calls to a similar set of APIs. Here is the Windows NT recommended list:

EnterCriticalSection	ReleaseSemaphore
LeaveCriticalSection	SetEvent
midiOutLongMsg	timeGetSystemTime
midiOutShortMsg	timeGetTime
OutputDebugString	timeKillEvent
PostMessage	timeSetEvent
PostThreadMessage
If an application's low-level audio callback function does stray from this list, it should be careful not to call APIs that take a long time to complete.

In particular, calling wave and midi APIs may result in a deadlock.

If a Win32 low-level audio callback shares data with other code, a Critical Section  or similar mutual exclusion mechanism should be used to protect the integrity of the data.

Use one of the following techniques to pass instance data from an application to a low-level callback function residing in a dynamic link library:

•	Pass the instance data using the dwInstance parameter of the function that opens the device driver.

•	Pass the instance data using the dwUser member of the WAVEHDR and MIDIHDR structures that identify an audio data block being sent to a device driver.

If you need more than 32 bits of instance data, pass a pointer to a structure containing the additional information.


 Managing Low-Level Audio Data Blocks by Polling

In addition to using a callback function, you can poll the dwFlags member of a WAVEHDR or MIDIHDR structure to determine when an audio device is finished with a data block. There are times when it's better to poll dwFlags rather than wait for a window to receive messages from the drivers. For example, immediately after you call the waveOutReset function to release pending data blocks, you can poll to be sure that the data blocks are indeed done before proceeding to call the waveOutUnprepareHeader function and free the memory for the data block.

MMSYSTEM.H defines two flags for testing the dwFlags member: WHDR_DONE for a WAVEHDR structure, and MHDR_DONE for a MIDIHDR structure.


 Using the MMTIME Structure

Windows uses a structure called MMTIME to represent time. Low-level audio functions that use MMTIME include waveInGetPosition and waveOutGetPosition. The timeGetSystemTime function also uses MMTIME to represent system time.


 Setting the Time Format

MMTIME can represent time in one or more different formats including milliseconds, samples, Society of Motion Picture and Television Engineers (SMPTE), and MIDI song-pointer formats. The wType member specifies the format used to represent time. Before calling a function that uses the MMTIME structure, you must set the wType member to indicate your requested time format. Be sure to check wType after the call to see if the requested time format is supported. If the requested time format is not supported, the time is specified in an alternate time format selected by the device driver and the wType member is changed to indicate the selected time format. MMSYSTEM.H defines the following flags for the wType member of the MMTIME structure.

Flag	Description
TIME_MS	Milliseconds
TIME_SAMPLES	Number of waveform audio samples
TIME_BYTES	Number of waveform audio bytes
TIME_SMPTE	SMPTE time
TIME_MIDI	MIDI song-position pointer
For details on using MMTIME with the waveOutGetPosition function, seeGetting the Current Playback Position.


 Getting the System Time

Use the timeGetSystemTime or timeGetTime function to get the system time. System time is defined as the time (in milliseconds) since Windows was started. For more information on timeGetSystemTime and timeGetTime, see Multimedia Timer and Joystick Services.


 Handling Errors with Low-Level Audio Functions

Low-level audio functions return a nonzero error code. A set of functions convert these error codes into a textual description of the error. The application must still look at the error value itself to determine how to proceed, but textual descriptions of errors can be used in dialog boxes describing errors to users.

The following functions can be used to get textual descriptions of low-level audio errors.

Function	Description
midiInGetErrorText	Retrieves a textual description of a specified MIDI input error.
midiOutGetErrorText	Retrieves a textual description of a specified MIDI output error.
waveInGetErrorText	Retrieves a textual description of a specified waveform input error.
waveOutGetErrorText	Retrieves a textual description of a specified waveform output error.
The only low-level audio functions that don't return error codes are the device-numbering functions (auxGetNumDevs, midiInGetNumDevs, and so on). These functions return a value of zero if no devices are present in a system, or if any errors are encountered by the function.


 Playing Waveform Audio

If your application plays waveform audio, you can use the Media Control Interface (MCI) to control waveform output devices. If the MCI waveform playback services don't meet the needs of your application, you can manage waveform playback by using the low-level waveform services.


 Waveform Output Data Types

The MMSYSTEM.H header file defines data types and function prototypes for all of the audio functions. You must include this header file in any source-code module that uses these functions. MMSYSTEM.H defines the following data types for the waveform output functions.

Type	Description
HKL	Handle to a keyboard layout.
HWAVEOUT	Handle to an audio  waveform output device.
WAVEOUTCAPS	Structure used to inquire about the capabilities of a particular waveform output device.
WAVEFORMAT	Structure that specifies the data formats supported by a particular waveform output device. This structure is also used for waveform input devices.
WAVEHDR	Structure that is a header for a block of waveform output data. This structure is also used for waveform input devices.


 Querying Waveform Output Devices

Before playing a waveform, call the waveOutGetDevCaps function to determine the waveform output capabilities of the playback device as described earlier in this section. This function takes a pointer to a WAVEOUTCAPS structure, which it fills with information about the capabilities of a given device. This information includes the manufacturer and product identifiers, a product name for the device, and the version number of the device driver.

In addition, the WAVEOUTCAPS structure provides information on the standard waveform formats and features supported by the device driver.


 Determining Standard Format Support

The dwFormats member of the WAVEOUTCAPS structure specifies the standard waveform formats supported by a device. The MMSYSTEM.H header file defines the following standard waveform format identifiers for the dwFormats member.

Format identifier	Waveform format
WAVE_FORMAT_1M08	8-bit mono at 11.025 kHz
WAVE_FORMAT_1S08	8-bit stereo at 11.025 kHz
WAVE_FORMAT_1M16	16-bit mono at 11.025 kHz
WAVE_FORMAT_1S16	16-bit stereo at 11.025 kHz
WAVE_FORMAT_2M08	8-bit mono at 22.05 kHz
WAVE_FORMAT_2S08	8-bit stereo at 22.05 kHz
WAVE_FORMAT_2M16	16-bit mono at 22.05 kHz
WAVE_FORMAT_2S16	16-bit stereo at 22.05 kHz
WAVE_FORMAT_4M08	8-bit mono at 44.1 kHz
WAVE_FORMAT_4S08	8-bit stereo at 44.1 kHz
WAVE_FORMAT_4M16	16-bit mono at 44.1 kHz
WAVE_FORMAT_4S16	16-bit stereo at 44.1 kHz
The value of the dwFormats member is the result of a logical OR operation on the flags listed above.

This information on standard-format support also applies to the WAVEINCAPS structure used with waveform input devices. For information about the WAVEINCAPS structure, see Querying Waveform Input Devices.

To determine whether a specific format is supported by a device, use the waveOutOpen function with the WAVE_FORMAT_QUERY flag as shown in the next section.


 Determining Low-Level Audio Nonstandard Format Support

Waveform devices can support nonstandard formats not listed in the preceding table. To see whether a particular format (standard or nonstandard) is supported by a device, you can call the waveOutOpen function with the WAVE_FORMAT_QUERY flag. The WAVE_FORMAT_QUERY flag tells waveOutOpen to check whether the requested format is supported. The wave device is not actually opened. The requested format is specified by the structure pointed to by the lpFormat parameter passed to waveOutOpen. For information about setting up this structure, see Specifying Waveform Data Formats. The following example uses this technique to determine whether a given waveform device supports a given format.

/*

 * Determines whether the given waveform output device supports

 * a given wave-form format. Returns 0 if the format is supported,

 * WAVEERR_BADFORMAT if the format is not supported, and one of

 * the MMSYSERR_ error codes if there are other errors in opening

 * the given waveform device.

 */

UINT IsFormatSupported(LPPCMWAVEFORMAT lpPCMWaveFormat,

    UINT wDeviceID)

{

    return (waveOutOpen(

            NULL,                           // NULL for query

            wDeviceID,                      // device identifier

            (LPWAVEFORMAT)lpPCMWaveFormat,  // requested format

            NULL,                           // no callback

            NULL,                           // no instance data

            WAVE_FORMAT_QUERY));            // query only

}

This technique to determine nonstandard format support also applies to waveform input devices. The only difference is that the waveInOpen function is used in place of waveOutOpen to query for format support.

Note  To determine whether a particular waveform-data format is supported by any of the waveform devices in a system, use the technique illustrated in the previous example, but specify the WAVE_MAPPER constant for the wDeviceID parameter. For more information about using the WAVE_MAPPER constant, see Selecting a Waveform Output Device.


 Determining Capabilities of Waveform Output Devices

Waveform output devices vary in the capabilities they support. The dwSupport member of the WAVEOUTCAPS structure indicates whether a given device supports capabilities such as volume and pitch changes. MMSYSTEM.H defines the following flags for the dwSupport member.

Flag	Description
WAVECAPS_PITCH	Pitch-change support
WAVECAPS_PLAYBACKRATE	Playback-rate-change support
WAVECAPS_VOLUME	Volume-control support
WAVECAPS_LRVOLUME	Individual volume-control support for both left and right channels
The dwSupport member is a logical OR of the flags listed in the preceding table.

For more information about playback volume levels, see Changing Waveform Playback Volume. For more information about pitch and playback rates, see Changing Pitch and Playback Rate.


 Opening Waveform Output Devices

Use the waveOutOpen function to open a waveform output device for playback. This function opens the device associated with the specified device identifier and returns a handle of the open device by writing the handle of a specified memory location.


 Selecting a Waveform Output Device

Some multimedia computers have multiple waveform output devices. Unless you know you want to open a specific waveform output device in a system, you should use the WAVE_MAPPER constant for the device identifier when you open a device. The waveOutOpen function chooses the device in the system best capable of playing the given data format.


 Specifying Waveform Data Formats

When you call the waveOutOpen function to open a device driver for playback or determine whether the driver supports a particular data format, use the lpFormat parameter to specify a pointer to a structure containing the requested waveform data format.

The WAVEFORMAT structure specifies format information common to all types of waveform data formats. Currently the only format supported is pulse code modulated (PCM), but in the future other types such as adaptive differential pulse code modualtion (ADPCM) may be supported.

In addition to the general information in the WAVEFORMAT structure, specific information is needed to describe a PCM waveform data format completely. For PCM waveform data, the PCMWAVEFORMAT structure includes a WAVEFORMAT structure along with an additional member containing PCM-specific information.


 Using the PCMWAVEFORMAT Structure

For PCM audio data, use the PCMWAVEFORMAT structure to specify the data format. The following example shows how to set up a PCMWAVEFORMAT structure for 11.025 kilohertz (kHz) 8-bit mono and for 44.1 kHz 16-bit stereo. After setting up PCMWAVEFORMAT, the example calls the IsFormatSupported function to verify that the PCM waveform output device supports the format. The source code for IsFormatSupported is given in an example in "Determining Nonstandard Format Support."

UINT wReturn;

PCMWAVEFORMAT pcmWaveFormat;

/* Set up PCMWAVEFORMAT for 11 kHz 8-bit mono. */

pcmWaveFormat.wf.wFormatTag = WAVE_FORMAT_PCM;

pcmWaveFormat.wf.nChannels = 1;

pcmWaveFormat.wf.nSamplesPerSec = 11025L;

pcmWaveFormat.wf.nAvgBytesPerSec = 11025L;

pcmWaveFormat.wf.nBlockAlign = 1;

pcmWaveFormat.wBitsPerSample = 8;

/* See if format is supported by any device in system. */

wReturn = IsFormatSupported(&pcmWaveFormat, WAVE_MAPPER);

/* Report results. */

if (wReturn == 0)

     MessageBox(hMainWnd, "11 kHz 8-bit mono is supported.",

       "", MB_ICONINFORMATION);

else if (wReturn == WAVERR_BADFORMAT)

     MessageBox(hMainWnd, "11 kHz 8-bit mono NOT supported.",

       "", MB_ICONINFORMATION);

else

     MessageBox(hMainWnd, "Error opening waveform device.",

       "Error", MB_ICONEXCLAMATION);

/* Set up PCMWAVEFORMAT for 44.1 kHz 16-bit stereo. */

pcmWaveFormat.wf.wFormatTag = WAVE_FORMAT_PCM;

pcmWaveFormat.wf.nChannels = 2;

pcmWaveFormat.wf.nSamplesPerSec = 44100L;

pcmWaveFormat.wf.nAvgBytesPerSec = 176400L;

pcmWaveFormat.wf.nBlockAlign = 4;

pcmWaveFormat.wBitsPerSample = 32;

/* See if format is supported by any device in the system. */

wReturn = IsFormatSupported(&pcmWaveFormat, WAVE_MAPPER);

/* Report results. */

if (wReturn == 0)

    MessageBox(hMainWnd, "44.1 kHz 16-bit stereo is supported.",

      "", MB_ICONINFORMATION);

else if (wReturn == WAVERR_BADFORMAT)

    MessageBox(hMainWnd, "44.1 kHz 16-bit stereo NOT supported.",

      "", MB_ICONINFORMATION);

else

    MessageBox(hMainWnd, "Error opening waveform device.",

      "Error", MB_ICONEXCLAMATION);


 Getting Format Information from a WAVE File

The easiest way to get waveform-format information from a WAVE file is by using the multimedia file input and output (I/O) services. To do this, use the mmioDescend function to locate the "fmt" chunk containing the format information and the mmioRead function to read the format chunk directly into the proper format structure. (Chunks are the basic building blocks of RIFF files.) The following example illustrates this technique. For more information about multimedia file I/O, see Multimedia File Input/Output.

void GetFormatInfo(void)

{

    HMMIO       hmmio;

    MMCKINFO    mmckinfoParent;

    MMCKINFO    mmckinfoSubchunk;

    DWORD       dwFmtSize;

    HANDLE      hFormat;

    WAVEFORMAT  *pFormat;

.ifdef REF

        .

        .

        .

.endif

    /* Open the given file for reading using buffered I/O. */

.ifdef REF

        ...

.endif

    /*

     * Locate a "RIFF" chunk with a "WAVE" form type

     * to make sure it's a WAVE file.

     */

.ifdef REF

        ...

.endif

    /*

     * Now, find the format chunk (form type "fmt "). It should be

     * a subchunk of the "RIFF" parent chunk.

     */

    mmckinfoSubchunk.ckid = mmioFOURCC('f', 'm', 't', ' ');

    if (mmioDescend(hmmio, &mmckinfoSubchunk, &mmckinfoParent,

            MMIO_FINDCHUNK)) {

        MessageBox(hwndApp, "WAVE file is corrupted.",

            NULL, MB_OK | MB_ICONEXCLAMATION);

        mmioClose(hmmio, 0);

        return;

    }

    /*

     * Get the size of the format chunk;

     * allocate and lock memory for it.

     */

    dwFmtSize = mmckinfoSubchunk.cksize;

    hFormat = LocalAlloc(LMEM_MOVEABLE, dwFmtSize);

    if (hFormat == NULL) {

        MessageBox(hwndApp, "Out of memory.",

            NULL, MB_OK | MB_ICONEXCLAMATION);

        mmioClose(hmmio, 0);

        return;

    }

    pFormat = (WAVEFORMAT *) LocalLock(hFormat);

    if (pFormat == NULL) {

        MessageBox(hwndApp, "Failed to lock memory for format chunk.",

            NULL, MB_OK | MB_ICONEXCLAMATION);

        LocalFree(hFormat);

        mmioClose(hmmio, 0);

        return;

    }

    /* Read the format chunk. */

    if (mmioRead(hmmio, (LPSTR)pFormat,

                dwFmtSize) != (LRESULT)dwFmtSize) {

        MessageBox(hwndApp, "Failed to read format chunk.",

            NULL, MB_OK | MB_ICONEXCLAMATION);

        LocalUnlock(hFormat);

        LocalFree(hFormat);

        mmioClose(hmmio, 0);

        return;

    }

    /* Make sure it's a PCM file. */

    if (pFormat->wFormatTag != WAVE_FORMAT_PCM) {

        LocalUnlock(hFormat);

        LocalFree(hFormat);

        mmioClose(hmmio, 0);

        MessageBox(hwndApp, "The file is not a PCM file.",

            NULL, MB_OK | MB_ICONEXCLAMATION);

        return;

    }

    /*

     * Make sure the system has a waveform output

     * device capable of playing this format.

     */

    if (waveOutOpen(&hWaveOut, WAVE_MAPPER, (LPWAVEFORMAT)pFormat,

                NULL, 0L, WAVE_FORMAT_QUERY)) {

        LocalUnlock(hFormat);

        LocalFree(hFormat);

        mmioClose(hmmio, 0);

        MessageBox(hwndApp,

            "The waveform device can't play this format.",

            NULL, MB_OK | MB_ICONEXCLAMATION);

        return;

    }

.ifdef REF

    .

    .

    .

.endif

}


 Writing Waveform Data

After successfully opening a waveform output device driver, you can begin waveform playback.

The waveOutWrite function writes a data block to a waveform output device. Use the WAVEHDR structure to specify the waveform data block you are sending. This structure contains a pointer to a locked data block, the length of the data block, and assorted flags.

After you send a data block to an output device by using waveOutWrite, you must wait until the device driver is finished with the data block before freeing it. If you are sending multiple data blocks, you must monitor the system for the completion of each data block so that you know when to send additional blocks. For details about different techniques for monitoring data block completion, see Managing Audio Data Blocks.


 Example of Writing Waveform Data

The following example illustrates the steps required to allocate and set up a WAVEHDR data structure and write a block of data to a waveform output device.

/*

 * Global variables. Must be visible to window-procedure function

 *  so it can unlock and free the data block after it has been played.

 */

HANDLE hData  = NULL; // handle of waveform data memory

HPSTR  lpData = NULL; // pointer to waveform data memory

void WriteWaveData(void)

{

    HWAVEOUT    hWaveOut;

    HGLOBAL     hWaveHdr;

    LPWAVEHDR   lpWaveHdr;

    HMMIO       hmmio;

    UINT        wResult;

    HANDLE      hFormat;

    WAVEFORMAT  *pFormat;

    DWORD       dwDataSize;

.ifdef REF

        .

        .

        .

.endif

    /* Open a waveform device for output using window callback. */

    if (waveOutOpen((LPHWAVEOUT)&hWaveOut, WAVE_MAPPER,

                    (LPWAVEFORMAT)pFormat,

                    (LONG)hwndApp, 0L, CALLBACK_WINDOW)) {

        MessageBox(hwndApp,

                   "Failed to open waveform output device.",

                   NULL, MB_OK | MB_ICONEXCLAMATION);

        LocalUnlock(hFormat);

        LocalFree(hFormat);

        mmioClose(hmmio, 0);

        return;

    }

    /*

     * Allocate and lock memory for the waveform data. The memory

     * for waveform data must be globally allocated with

     * GMEM_MOVEABLE and GMEM_SHARE flags.

     */

    hData = GlobalAlloc(GMEM_MOVEABLE | GMEM_SHARE, dwDataSize );

    if (!hData)

    {

        MessageBox(hwndApp, "Out of memory.",

                   NULL, MB_OK | MB_ICONEXCLAMATION);

        mmioClose(hmmio, 0);

        return;

    }

    if ((lpData = GlobalLock(hData)) == NULL) {

        MessageBox(hwndApp, "Failed to lock memory for data chunk.",

                   NULL, MB_OK | MB_ICONEXCLAMATION);

        GlobalFree(hData);

        mmioClose(hmmio, 0);

        return;

    }

    /* Read the waveform data subchunk. */

    if(mmioRead(hmmio, (HPSTR) lpData, dwDataSize) != (LRESULT)dwDataSize) {

        MessageBox(hwndApp, "Failed to read data chunk.",

                   NULL, MB_OK | MB_ICONEXCLAMATION);

        GlobalUnlock(hData);

        GlobalFree(hData);

        mmioClose(hmmio, 0);

        return;

    }

    /*

     * Allocate and lock memory for the header. This memory must

     * also be globally allocated with GMEM_MOVEABLE and

     * GMEM_SHARE flags.

     */

    hWaveHdr = GlobalAlloc(GMEM_MOVEABLE | GMEM_SHARE,

        (DWORD) sizeof(WAVEHDR));

    if (hWaveHdr == NULL) {

        GlobalUnlock(hData);

        GlobalFree(hData);

        MessageBox(hwndApp, "Not enough memory for header.",

            NULL, MB_OK | MB_ICONEXCLAMATION);

        return;

    }

    lpWaveHdr = (LPWAVEHDR) GlobalLock(hWaveHdr);

    if (lpWaveHdr == NULL) {

        GlobalUnlock(hData);

        GlobalFree(hData);

        MessageBox(hwndApp,

            "Failed to lock memory for header.",

            NULL, MB_OK | MB_ICONEXCLAMATION);

        return;

    }

    /* After allocation, set up and prepare header. */

    lpWaveHdr->lpData = lpData;

    lpWaveHdr->dwBufferLength = dwDataSize;

    lpWaveHdr->dwFlags = 0L;

    lpWaveHdr->dwLoops = 0L;

    waveOutPrepareHeader(hWaveOut, lpWaveHdr, sizeof(WAVEHDR));

    /*

     * Now the data block can be sent to the output device. The

     * waveOutWrite function returns immediately and waveform

     * data is sent to the output device in the background.

     */

    wResult = waveOutWrite(hWaveOut, lpWaveHdr, sizeof(WAVEHDR));

    if (wResult != 0) {

        waveOutUnprepareHeader(hWaveOut, lpWaveHdr,

                               sizeof(WAVEHDR));

        GlobalUnlock( hData);

        GlobalFree(hData);

        MessageBox(hwndApp, "Failed to write block to device",

                   NULL, MB_OK | MB_ICONEXCLAMATION);

        return;

    }

.ifdef REF

    .

    .

    .

.endif

}


 PCM Waveform Data Format

The lpData member in the WAVEHDR structure points to the waveform data samples. For 8-bit PCM data, each sample is represented by a single unsigned data byte. For 16-bit PCM data, each sample is represented by a 16-bit signed value. The following table summarizes the maximum, minimum, and midpoint values for PCM waveform data.

Data format	Maximum value	Minimum value	Midpoint value
8-bit PCM	255 (0xFF)	0	128 (0x80)
16-bit PCM	32767 (0x7FFF)	-32768 (0x8000)	0
The order of the data bytes varies between 8-bit and 16-bit, and between mono and stereo formats. The following tables show data packing for the first four words of different PCM waveform data formats.

Data packing for 8-bit mono PCM:

Sample 1	Sample 2	Sample 3	Sample 4
Channel 0	Channel 0	Channel 0	Channel 0
Data packing for 8-bit stereo PCM:

Sample 1		Sample 2
Channel 0 (left)	Channel 1 (right)	Channel 0 (left)	"Channel 1 (right)"
Low-order byte	High-order byte	Low-order byte	High-order byte
Data packing for 16-bit mono PCM:

Sample 1		Sample 2
Channel 0 low byte	Channel 0 high byte	Channel 0 low byte	Channel 0 high byte
Data packing for 16-bit stereo PCM:

Sample 1
Channel 0 (left) byte	Channel 0 (left) byte	Channel 1 (right) byte	Channel 1 (right) byte


 Waveform Looping

Waveform looping is controlled by the dwLoops and dwFlags members in the WAVEHDR structures passed to the device with waveOutWrite. Use the WHDR_BEGINLOOP and WHDR_ENDLOOP flags in the dwFlags member to specify the beginning and ending data blocks for looping.

To loop on a single block, specify both flags for the same block. To specify the number of loops, use the dwLoops member in the WAVEHDR structure for the first block in the loop.

You can stop waveform looping with the waveOutBreakLoop function. The blocks making up the loop are played to the end before the loop is stopped.


 Using Window Messages to Manage Waveform Playback

The following messages can be sent to a window-procedure function for managing waveform playback.

Message	Description
MM_WOM_CLOSE	Sent when the device is closed using waveOutClose.
MM_WOM_DONE	Sent when the device driver is finished with a data block sent using waveOutWrite.
MM_WOM_OPEN	Sent when the device is opened using waveOutOpen.
A wParam and lParam parameter is associated with each of these messages. The wParam parameter always specifies a handle of the open waveform device. For the MM_WOM_DONE message, lParam specifies a pointer to a WAVEHDR structure identifying the completed data block. The lParam parameter is unused for the MM_WOM_CLOSE and MM_WOM_OPEN messages.

The most useful message is MM_WOM_DONE. When this message signals that playback of a data block is complete, you can clean up and free the data block. Unless you need to allocate memory or initialize variables, you probably don't need to process the MM_WOM_OPEN and MM_WOM_CLOSE messages.

The following example shows how to process the MM_WOM_DONE message. The example assumes the application does not play multiple data blocks, so it can close the output device after playing a single data block.

/* WndProc--Main window-procedure function. */

LRESULT WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)

{

    switch (msg) {

.ifdef REF

        .

        .

        .

.endif

        case MM_WOM_DONE:

        /* A data block has been played and can now be freed. */

            waveOutUnprepareHeader((HWAVEOUT) wParam,

                (LPWAVEHDR) lParam, sizeof(WAVEHDR) );

            GlobalUnlock(hData);

            GlobalFree(hData);

            waveOutClose((HWAVEOUT) wParam);

            break;

    }

    return DefWindowProc(hWnd,msg,wParam,lParam);

}


 Using a Low-Level Callback Function to Manage Waveform Playback

The syntax of the low-level callback function for waveform output devices is as follows:

void CALLBACK waveOutCallback(hWaveOut, wMsg,
     dwInstance, dwParam1, dwParam2)

The following messages can be sent in the wMsg parameter of waveform output callback functions.

Message	Description
WOM_CLOSE	Sent when the device is closed using the waveOutClose function.
WOM_DONE	Sent when the device driver is finished with a data block sent using the waveOutWrite function.
WOM_OPEN	Sent when the device is opened using the waveOutOpen function.
These messages are similar to the messages sent to window-procedure functions, the parameters are different. A handle of the open waveform device is passed as a parameter to the callback function, along with the doubleword of instance data that was passed using waveOutOpen.

The callback function has two message-specific parameters: dwParam1 and dwParam2. For the WOM_DONE message, dwParam1 specifies a pointer to a WAVEHDR structure identifying the completed data block and dwParam2 is not used. For the WOM_OPEN and WOM_CLOSE messages, neither of the parameters is used.

After the driver is finished with a data block, you can clean up and free the data block, as described in "Allocating and Preparing Audio Data Blocks." Because of the suggested restrictions on low-level audio callback functions, it is better to not do this from within the callback. See Using a Callback Function to Process Driver Messages for details about suggested restrictions on using callback functions.


 Getting the Current Playback Position

While a waveform is playing, you can monitor the current playback position within the waveform. The Win32 API provides the waveOutGetPosition function for this purpose.

This function takes three parameters: a handle of a waveform output device, a pointer to an MMTIME structure, and an unsigned integer specifying the size of the MMTIME structure.

For waveform devices, the preferred time format in which to represent the current position is samples. Thus the current position of a waveform device is specified as the number of samples for one channel from the beginning of the waveform.

To query the current position of a waveform device, set the wType member of the MMTIME structure to TIME_SAMPLES and pass the structure to waveOutGetPosition.


 Stopping, Pausing, and Restarting Playback

You can stop or pause playback while a waveform is playing. Once playback has been paused, you can restart it. The Win32 API provides the following functions for controlling waveform playback.

Function	Description
waveOutPause	Pauses playback on a waveform output device.
waveOutReset	Stops playback on a waveform output device and marks all pending data blocks as done.
waveOutRestart	Resumes playback on a paused waveform output device.
Use the waveOutPause function to pause a waveform device that is currently playing. To resume playback on a paused device, use the waveOutRestart function. These functions take a single parameter: the waveform output device handle returned by the waveOutOpen function. Pausing a waveform device may not be instantaneous — the driver can finish playing the current block before pausing playback.

Typically, as soon as the first waveform data block is sent by using the waveOutWrite function, the waveform device begins playing. If you don't want the waveform to start playing immediately, call waveOutPause before calling waveOutWrite. When you want to begin playing the waveform, call waveOutRestart.

To stop a waveform from playing, use the waveOutReset function. This function differs from waveOutPause in that it also marks all pending data blocks as being done. You can not use waveOutRestart to restart a device that has been stopped by using waveOutReset. You must use waveOutWrite to send the first data block to resume playback on the device.


 Closing Waveform Output Devices

After waveform playback is complete, call the waveOutClose function to close the waveform device. If waveOutClose is called while a waveform is playing, the close operation fails and the function returns an error code indicating that the device was not closed. If you don't want to wait for playback to end before closing the device, call the waveOutReset function before closing. This stops playback and allows the device to be closed. Be sure to clean up the preparation on all data blocks before closing the waveform output device.


 Changing Waveform Playback Volume

Windows provides the following functions to query and set the volume level of waveform output devices.

Function	Description
waveOutGetVolume	Gets the volume level of the specified waveform device.
waveOutSetVolume	Sets the volume level of the specified waveform device.
Not all waveform devices support volume changes. Some devices support individual volume control on both the left and right channels. For information about how to determine the volume-control capabilities of waveform devices, see Determining Capabilities of Waveform Output Devices.

Note  Unless your application is designed to be a master volume-control application providing the user with volume control for all audio devices in a system, be sure that your application opens an audio device before changing its volume. Also, be sure your application queries the volume level before changing it and restores the volume level to its previous level as soon as possible.

Volume is specified in a doubleword value of which the high-order 16 bits specify the relative volume of the right channel, and the low-order 16 bits specify the relative volume of the left (or mono) channel.

For devices that don't support left- and right-channel volume control, the low-order 16 bits specify the volume level, and the high-order 16 bits are ignored. Volume-level values range from 0x0 (silence) to 0xFFFF (maximum volume) and are interpreted logarithmically. The perceived volume increase is the same when increasing the volume level from 0x5000 to 0x6000 as it is from 0x4000 to 0x5000.

The waveOutGetVolume function returns the volume as a doubleword value at an address specified by a pointer parameter.


 Changing Pitch and Playback Rate

Some waveform output devices can vary the pitch and the playback rate of waveform data. Not all waveform devices support pitch and playback-rate changes. For information about how to determine if a particular waveform device supports pitch and playback-rate changes, see Determining Capabilities of Waveform Output Devices.

Following are the differences between changing pitch and playback rate:

•	Changing the playback rate is performed by the device driver and does not require specialized hardware. The sample rate is not changed, but the driver interpolates by skipping or synthesizing samples. For example, if the playback rate is changed by a factor of two, the driver skips every other sample.

•	Changing the pitch requires specialized hardware. The playback rate and sample rate are not changed.

Windows provides the following functions to query and set waveform pitch and playback rates.

Function	Description
waveOutGetPitch	Gets the pitch for the specified waveform output device.
waveOutGetPlaybackRate	Gets the playback rate for the specified waveform output device.
waveOutSetPitch	Sets the pitch for the specified waveform output device.
waveOutSetPlaybackRate	Sets the playback rate for the specified waveform output device.
The pitch and playback rates are changed by a factor specified with a fixed-point number packed into a doubleword value. The high-order 16 bits specify the integer part, and the low-order 16 bits specify the fractional part of the number. For example, the value 1.5 is represented as 0x00018000L. The value 0.75 is represented as 0x0000C000L. A value of 1.0 (0x00010000) means the pitch or playback rate is unchanged.


 Recording Low-Level Waveform Audio

If the MCI waveform-recording services don't meet the needs of your application, you can handle waveform recording using the low-level waveform services.


 Waveform Input Data Types

The MMSYSTEM.H header file defines data types and function prototypes for all of the audio functions. You must include this header file in any source-code module that uses these functions. MMSYSTEM.H defines the following data types for waveform-input functions.

Type	Description
HWAVEIN	Handle of an open waveform input device.
WAVEINCAPS	Data structure used to inquire about the capabilities of a particular waveform input device.
WAVEFORMAT	Structure that specifies the data formats supported by a particular waveform input device. This structure is also used for waveform output devices.
WAVEHDR	Structure that is a header for a block of waveform input data. This structure is also used for waveform output devices.


 Querying Waveform Input Devices

Before recording a waveform, you should call the waveInGetDevCaps function to determine the waveform input capabilities of the system. This function takes a pointer to a WAVEINCAPS structure that it fills with information about the capabilities of a given device. This information includes the manufacturer and product identifiers, a product name for the device, and the version number of the device driver. In addition, the WAVEINCAPS structure provides information about the standard waveform formats that the device supports.


 Opening Waveform Input Devices

Use the waveInOpen function to open a waveform input device for recording. This function opens the device associated with the specified device identifier and returns a handle of the open device by writing the handle of a specified memory location.


 Selecting a Waveform Input Device

Some multimedia computers will have multiple waveform input devices. Unless you know you want to open a specific waveform input device in a system, you should use the WAVE_MAPPER constant for the device identifier when you open a device. The waveOutOpen function will choose the device in the system best able to record in the given data format.


 Managing Waveform Recording

Once you open a waveform input device, you can begin recording waveform data. Waveform data is recorded into application-supplied buffers specified by a WAVEHDR structure. This is the same structure used for waveform playback described in Writing Waveform Data. Memory for the WAVEHDR structure and its accompanying data buffer must be allocated and prepared, as shown in Allocating and Preparing Audio Data Blocks.

Windows provides the following functions to manage waveform recording:

Function	Description
waveInAddBuffer	Sends a buffer to the device driver so it can be filled with recorded waveform data.
waveInReset	Stops waveform recording and marks all pending buffers as done.
waveInStart	Starts waveform recording.
waveInStop	Stops waveform recording.
Use the waveInAddBuffer function to send data buffers to the device driver. As the buffers are filled with recorded waveform data, the application is notified with either a window message or with a callback message, depending on the flag specified when the device was opened.

Use the waveInStart function to begin recording. Before beginning to record, send at least one buffer to the driver or incoming data may be lost. To stop waveform recording, use the waveInStop function.

Before closing the device by using the waveOutClose function, call the waveOutReset function to mark any pending data blocks as being done.


 Using Window Messages to Manage Waveform Recording

The following messages can be sent to a window-procedure function for managing waveform recording.

Message	Description
MM_WIM_CLOSE	Sent when the device is closed using the waveInClose function.
MM_WIM_DATA	Sent when the device driver is finished with a data buffer sent using the waveInAddBuffer function.
MM_WIM_OPEN	Sent when the device is opened using the waveInOpen function.
There is a wParam and lParam parameter associated with each of these messages. The wParam parameter always specifies a handle of the open waveform device. The lParam parameter is unused for the MM_WIM_CLOSE and MM_WIM_OPEN messages.

For the MM_WIM_DATA message, lParam specifies a pointer to a WAVEHDR structure that identifies the data buffer. This data buffer may not be completely filled with waveform data, because recording can stop before the buffer is filled. Use the dwBytesRecorded member of the WAVEHDR structure to determine the amount of valid data present in the buffer.

The most useful message is MM_WIM_DATA. Unless you need to allocate memory or initialize variables, you probably don't need to use the MM_WIM_OPEN and MM_WIM_CLOSE messages. When the device driver is finished with a data block, you can clean up and free the data block as described in Allocating and Preparing Audio Data Blocks.


 Using a Low-Level Callback Function to Manage Waveform Recording

The syntax of the low-level callback function for waveform input devices is as follows.

void CALLBACK waveInCallback(hWaveIn, wMsg,
    dwInstance, dwParam1, dwParam2)

The following messages can be sent in the wMsg parameter of waveform input callback functions.

Message	Description
WIM_CLOSE	Sent when the device is closed using the waveInClose function.
WIM_OPEN	Sent when the device is opened using the waveInOpen function.
These messages resemble messages sent to window-procedure functions, but their parameters are different. A handle of an open waveform device is passed as a parameter to the callback function, along with the doubleword value of instance data that was passed using waveInOpen.

The callback function has two message-specific parameters: dwParam1 and dwParam2. For the WIM_CLOSE and WIM_OPEN messages, these parameters are not used. For the WIM_DONE message, dwParam1 specifies a pointer to a WAVEHDR structure identifying the completed data block and dwParam2 is not used.

After the driver is finished with a data block, you can clean up and free the data block. Because of the suggested restrictions of low-level audio callback functions, it is better not to do this within the callback function. It is better to set events or semaphores and do this outside the callback function. For details about the suggested restrictions on using callback functions, see Using a Callback Function to Process Driver Messages.


 Playing MIDI Audio

To play MIDI files, use the MCI sequencer. If the MCI sequencer services don't meet the needs of your application, you can manage MIDI playback using the low-level MIDI services.


 Low-Level Audio MIDI Output Data Types

The MMSYSTEM.H header file defines data types and function prototypes for all low-level audio functions. You must include this header file in any source module that uses these functions. MMSYSTEM.H defines the following data types for low-level MIDI output function:

Type	Description
HMIDIOUT	Handle of a MIDI output device.
MIDIHDR	Structure is a header for a block of MIDI system-exclusive data. This structure is used for input as well as output.
MIDIOUTCAPS	Structure used to inquire about the capabilities of a particular MIDI output device.


 Querying Low-Level MIDI Output Devices

Before playing MIDI audio, you should call the midiOutGetDevCaps function to determine the capabilities of the MIDI output hardware present in the system. This function takes a pointer to a MIDIOUTCAPS structure that it fills with information about the capabilities of a given device. This information includes the manufacturer and product identifiers, a product name for the device, and the version number of the device driver. In addition, the MIDIOUTCAPS structure provides information on the device technology, the number of voices and notes supported, the MIDI channels that the device responds to, and features supported by the driver.


 Determining the Technology of the Device

MIDI output devices can be either internal synthesizers or external MIDI output ports. The wTechnology member specifies the technology of the device. MMSYSTEM.H defines the following flags to identify device technology.

Flag	Description
MOD_MIDIPORT	The device is an external MIDI output port.
MOD_SQSYNTH	Device is an internal square-wave synthesizer.
MOD_FMSYNTH	Device is an internal FM synthesizer.
MOD_SYNTH	Device is an internal synthesizer (generic).
MOD_MAPPER	Device is the MIDI Mapper.


 Determining Capabilities of Internal Synthesizers

If the device is an internal synthesizer, additional device information is available in the wVoices, wNotes, and wChannelMask members of the MIDIOUTCAPS structure. If the device is an external output port, these members are unused.

The wVoices member specifies the number of voices the device supports. Each voice can have a different sound or timbre. Voices are differentiated by MIDI channel. For example, a four-voice synthesizer uses four MIDI channels. The wNotes member specifies the polyphony of the device — the maximum number of notes that can be played simultaneously. The wChannelMask member is a bit representation of the MIDI channels that the device responds to. For example, if the device responds to the first eight MIDI channels, wChannelMask is 0x00FF.

The dwSupport member of the MIDIOUTCAPS structure indicates whether the device driver supports volume changes and patch caching. MMSYSTEM.H defines the following flags for the dwSupport member.

Flag	Description
MIDICAPS_VOLUME	Indicates the driver supports volume control.
MIDICAPS_LRVOLUME	Indicates the driver supports individual volume control for the left and right channels.
MIDICAPS_CACHE	Indicates the driver supports patch caching.
Volume changes are only supported by internal synthesizer devices. External MIDI output ports don't support volume changes. For information about changing volume, see Changing Internal MIDI Synthesizer Volume.


 Opening Low-Level Audio MIDI Output Devices

Use the midiOutOpen function to open a MIDI output device for playback. This function opens the device associated with the specified device identifier and returns a handle of the open device by writing the handle of a specified memory location.


 Sending MIDI Messages

Once you open a MIDI output device, you can begin sending it MIDI messages by using the following functions.

Function	Description
midiOutLongMsg	Sends a buffer of MIDI data to the specified MIDI output device. Use this function to send multiple MIDI events, including system-exclusive messages, to a MIDI device.
midiOutShortMsg	Sends a MIDI message to a specified MIDI output device. This function can use running status by omitting the status byte.
midiOutReset	Turns off all notes on all channels for a specified MIDI output device. Any pending system-exclusive buffers are marked as done and returned to the application.
Use midiOutShortMsg to send any MIDI message (except for system-exclusive messages). This function takes an HMIDIOUT parameter specifying the MIDI output device to which to send the message, and a doubleword value for the MIDI message. The message is packed into the doubleword value as follows.

Word	Byte	Contents
High-order word	High-order byte	Not used
	Low-order byte	MIDI data 2 (optional)
Low-order word	High-order Byte	MIDI data 1 (optional)
	Low-order byte	MIDI status
The two MIDI data bytes are optional, depending on the MIDI status byte. The following example uses midiOutShortMsg to send a given MIDI event to a given MIDI output device.

/* Sends a given MIDI event to the given output device */

UINT sendMIDIEvent(hMidiOut, bStatus, bData1, bData2)

HMIDIOUT hMidiOut;      // handle of the output device

BYTE bStatus;           // MIDI status byte

BYTE bData1;            // first MIDI data byte

BYTE bData2;            // second MIDI data byte

{

    union {

        DWORD dwData;

        BYTE bData[4];

    } u;

    /* Construct the MIDI message */

    u.bData[0] = bStatus;

    u.bData[1] = bData1;

    u.bData[2] = bData2;

    u.bData[3] = 0;

    /* Send the message */

    return midiOutShortMsg(hMidiOut, u.dwData);

}

Note  MIDI output drivers are not required to verify data before sending it to an output port. It is up to applications to ensure that only valid data is sent using the midiOutShortMsg function.


 Sending Buffered Messages

MIDI system-exclusive messages are the only MIDI messages that will not fit into a single doubleword value. System exclusive messages can be any length. Windows provides the midiOutLongMsg function for sending one or more messages, including system-exclusive messages, to MIDI output devices.

Use the MIDIHDR structure to specify MIDI system-exclusive data blocks. This structure contains a pointer to a locked data block, the data-block length, and assorted flags.

Memory for the MIDIHDR structure and the data block pointed to by lpData must be allocated and prepared, as shown in "Allocating and Preparing Audio Data Blocks."

After you send a system-exclusive data block using midiOutLongMsg, you must wait until the device driver is finished with the data block before freeing it. If you are sending multiple data blocks, you must monitor the completion of each data block so you know when to send additional blocks. (If your application uses a callback function or callback window, it will receive the MOM_DONE message when the driver finishes with the data block.) For information on different techniques for monitoring data-block completion, see Managing Audio Data Blocks.

Note  Any MIDI status byte other than a system-real-time message will terminate a system-exclusive message. If you are using multiple data blocks to send a single system-exclusive message, do not send any MIDI messages other than system-real-time messages between data blocks.


 Using Window Messages to Manage Buffered Playback

The following messages can be sent to a window-procedure function for managing MIDI system-exclusive playback.

Message	Description
MM_MOM_CLOSE	Sent when the device is closed using the midiOutClose function.
MM_MOM_DONE	Sent when the device driver is finished with a data block sent using the midiOutLongMsg function.
MM_MOM_OPEN	Sent when the device is opened using the midiOutOpen function.
A wParam and lParam parameter is associated with each of these messages. The wParam parameter always specifies a handle of the open MIDI device. For the MM_MOM_DONE message, lParam specifies a pointer to a MIDIHDR structure identifying the completed data block. The lParam parameter is unused for the MM_MOM_CLOSE and MM_MOM_OPEN messages.

The most useful message is the MM_MOM_DONE message. Unless you need to allocate memory or initialize variables, you probably don't need to process the MM_MOM_OPEN and MM_MOM_CLOSE messages. When playback of a data block is completed, you can clean up and free the data block as described in Allocating and Preparing Audio Data Blocks.


 Using a Callback to Manage Buffered Playback

This syntax of the low-level callback function for MIDI output devices is as follows.

void CALLBACK midiOutCallback(hMidiOut, wMsg,
    dwInstance, dwParam1, dwParam2)

The following messages can be sent to the wMsg parameter of MIDI output callback functions.

Message	Description
MOM_CLOSE	Sent when the device is closed using the midiOutClose function.
MOM_DONE	Sent when the device driver is finished with a data block sent using the midiOutLongMsg function.
MOM_OPEN	Sent when the device is opened using the midiOutOpen function.
These messages are similar to those sent to window-procedure functions, but the parameters are different. A handle of the open MIDI device is passed as a parameter to the callback function along with the doubleword value of instance data passed using midiOutOpen.

The callback function has two message-specific parameters: dwParam1 and dwParam2. For the MOM_OPEN and MOM_CLOSE messages, these parameters are not used. For the MOM_DONE message, dwParam1 specifies a pointer to a MIDIHDR structure identifying the completed data block and dwParam2 is not used.

After the driver is finished with a data block, you can clean up and free the data block. Because of the suggested restrictions on low-level audio callback functions, it is better not to do this from within the callback function. For details about the suggested restrictions on using callback functions, see Using a Callback Function to Process Driver Messages.


 Sending MIDI Messages Using Running-Status

The MIDI 1.0 Specification allows the use of running-status when a message has the same status byte as the previous message. When running status is used, the status byte of subsequent messages can be omitted. You can send MIDI messages using running status by using the midiOutShortMsg function by packing the message into a doubleword value as follows.

Word	Byte	Contents
High-order word	High-order byte	Not used
	Low-order byte	Not used
Low-order word	High-order Byte	MIDI data 2 (optional)
	Low-order byte	MIDI data 1


 Resetting Low-Level Audio MIDI Output

The midiOutReset function will turn off all notes, and mark any pending system-exclusive buffers as done and return them to the application. It may be useful in an application that uses MIDI output to provide the user with the ability to reset MIDI output.

Note  Terminating a system-exclusive message without sending an EOX (end-of-exclusive) byte may cause problems for the receiving device. The midiOutReset function does not send an EOX byte when it terminates a system-exclusive message; applications are responsible for doing this.


 Changing Low-Level Audio Internal MIDI Synthesizer Volume

Windows provides the following functions to query and set the volume level of internal MIDI synthesizer devices.

Function	Description
midiOutGetVolume	Gets the volume level of the specified internal MIDI synthesizer device.
midiOutSetVolume	Sets the volume level of the specified internal MIDI synthesizer device.
Not all MIDI output devices support volume changes. Some devices can support individual volume changes on both the left and the right channels. For information about how to determine whether a particular device supports volume change, see Determining Capabilities of Waveform Output Devices.

Note  Unless your application is designed to be a master volume-control application providing the user with volume control for all audio devices in a system, be sure your application opens an audio device before changing its volume. Also be sure your application queries the volume level before changing it and restore the volume level to its previous level as soon as possible.

Volume is specified in a doubleword value; the high-order 16 bits specify the relative volume of the right channel, and the low-order 16 bits specify the relative volume of the left channel.

For devices that don't support individual volume changes on both the left and right channels, the low-order 16 bits specify the volume level, and the high-order 16 bits are ignored. Values for the volume level range from 0x0 (silence) to 0xFFFF (maximum volume) and are interpreted logarithmically. The perceived volume increase is the same from volume level 0x5000 to 0x6000 as it is from 0x4000 to 0x5000.

When querying volume levels using midiOutGetVolume, the volume is returned in a doubleword location specified by a pointer parameter.


 Preloading Low-Level Audio Patches With Internal MIDI Synthesizers

Some internal MIDI synthesizer devices can't keep all of their patches loaded simultaneously. These devices must preload their patch data.

Windows provides the following functions to request that a synthesizer preload and cache specified patches.

Function	Description
midiOutCachePatches	Requests that an internal MIDI synthesizer device preload and cache specified melodic patches.
midiOutCacheDrumPatches	Requests that an internal MIDI synthesizer device preload and cache specified key-based percussion patches.
The midiOutCachePatches function takes a pointer to a PATCHARRAY to indicate the patches to be cached.

Each element in the array corresponds to a patch with each of the 16 bits representing one of the 16 MIDI channels. Bits are set for each of the channels that use that particular patch. For example, if patch number 0 is used by physical MIDI channels 0 and 8, set element 0 of the array to 0x0101.

The midiOutCacheDrumPatches function takes a pointer to a KEYARRAY to indicate the key-based percussion patches to be cached.

Each element in the array corresponds to a key-based percussion patch with each of the 16 bits representing one of the 16 MIDI channels. Bits are set for each of the channels that use that particular patch. For example, if the percussion patch for key number 60 is used by physical MIDI channels 9 and 15, set element 60 of the array to 0x8200.


 Using the MIDI Mapper with Low-Level MIDI Functions

The MIDI Mapper provides standard patch services for device-independent playback of MIDI files. Applications that use MIDI files for audio should use the MIDI Mapper. For information about the MIDI Mapper and about authoring device-independent MIDI files, see High-Level Audio.

To use the MIDI Mapper, open it by using the midiOutOpen function with the wDeviceID parameter set to the constant MIDIMAPPER. You can then send MIDI messages to the MIDI Mapper by using the midiOutShortMsg or midiOutLongMsg function.


 Recording Low-Level MIDI Audio

To record MIDI audio data, you must use low-level MIDI input functions. MCI does not currently provide a device handler for recording MIDI audio.


 Low-Level Audio MIDI Input Data Types

The MMSYSTEM.H header file defines data types and function prototypes for all of the low-level audio functions. MMSYSTEM.H defines the following data types for low-level MIDI input functions.

Type	Description
HMIDIIN	A handle of a MIDI input device.
MIDIHDR	A structure that is a header for a block of MIDI system-exclusive data. This structure is used for input as well as output.
MIDIINCAPS	A structure used to inquire about the capabilities of a MIDI input device.


 Querying MIDI Input Devices for Low-Level Audio

Before recording MIDI audio, you should call the midiInGetDevCaps function to determine the capabilities of the MIDI input hardware present in the system. This function takes a pointer to a MIDIINCAPS structure that it fills with information about the capabilities of a given device. This information includes the manufacturer and product identifiers, a product name for the device, and the version number of the device driver.


 Opening Low-Level MIDI Input Devices

Use the midiInOpen function to open a MIDI input device for recording. This function opens the device associated with the specified device identifier and returns a handle of the open device by writing the handle of a specified memory location.


 Managing MIDI Recording of Low-Level Audio

Once you open a MIDI input device, you can begin recording MIDI data. Win32 provides the following functions for managing MIDI recording.

Function	Description
midiInAddBuffer	Sends a buffer to the device driver so it can be filled with recorded MIDI data.
midiInReset	Stops MIDI recording and marks all pending buffers as done.
midiInStart	Starts MIDI recording and resets the time stamp to zero.
midiInStop	Stops MIDI recording.
Use the midiInAddBuffer function to send data buffers to the device driver for recording system-exclusive messages. Before you use midiInAddBuffer, you must allocate and prepare memory for the MIDIHDR data structure and the data block pointed to by the lpData member. For information about allocating and preparing this memory, see Allocating and Preparing Audio Data Blocks.

Use the midiInStart function to begin recording. To record system-exclusive messages, send at least one buffer to the driver with midiInAddBuffer before starting to record. As the buffers are filled with recorded data, the application is notified by one of the techniques discussed in "Managing Audio Data Blocks."

To stop recording, use the midiInStop function. Before closing the device by using the midiInClose function, call midiInReset to mark any pending data blocks as being done. Before freeing the memory used by a data block, call the midiInUnprepareHeader function to clean up the preparation performed previously.

You must use either a window-procedure function or a low-level callback function to receive MIDI data. If you want time-stamped data, you must use a low-level callback function.

To record system-exclusive messages, you must supply the device driver with data buffers. These buffers are specified by a MIDIHDR structure. This is the same structure used for MIDI buffered playback as described in "Sending Buffered Messages." Memory for the MIDIHDR structure and its accompanying data buffer must be allocated and prepared as shown in Allocating and Preparing Audio Data Blocks.


 Using Window Messages to Manage MIDI Recording

The following messages can be sent to a window-procedure function for managing MIDI recording.

Message	Description
MM_MIM_CLOSE	Sent when the device is closed using the midiInClose function.
MM_MIM_DATA	Sent when a complete MIDI message is received (this message is used for all MIDI messages except system-exclusive messages).
MM_MIM_ERROR	Sent when an invalid MIDI message is received (this message is used for all MIDI messages except system-exclusive messages).
MM_MIM_LONGDATA	Sent when either a complete MIDI system-exclusive message is received, or when a data buffer sent using the midiInAddBuffer function is filled with system-exclusive data.
MM_MIM_LONGERROR	Sent when an invalid MIDI system-exclusive message is received.
MM_MIM_OPEN	Sent when the device is opened using the midiInOpen function.
A wParam and an lParam parameter are associated with each of these messages. The wParam parameter always specifies a handle of the open MIDI device. The lParam parameter is unused for the MM_MIM_CLOSE and MM_MIM_OPEN messages.

For the MM_MIM_DATA message, lParam specifies the received MIDI data. This data is packed into a doubleword value as follows.

Word	Byte	Contents
High-order word	High-order byte
	Low-order byte	MIDI data 2 (optional)
Low-order word	High-order Byte	MIDI data 1 (optional)
	Low-order byte	MIDI status
For the MM_MIM_LONGDATA message, lParam specifies a pointer to a MIDIHDR structure that identifies the data buffer for system-exclusive messages. The data buffer might not be completely filled — you usually don't know the size of the system-exclusive messages before recording them, so you must allocate a buffer large enough for the largest expected message. Use the dwBytesRecorded member of the MIDIHDR structure to determine the amount of valid data present in the buffer.


 Using a Low-Level Callback Function to Manage MIDI Recording

This syntax of the low-level callback function for MIDI input devices is as follows:

void CALLBACK midiInCallback(hMidiIn, wMsg,
    dwInstance, dwParam1, dwParam2)

The following messages can be sent in the wMsg parameter of MIDI input callback functions.

Message	Description
MIM_CLOSE	Sent when the device is closed using the midiInClose function.
MIM_DATA	Sent when a complete MIDI message is received (this message is used for all MIDI messages except system-exclusive messages).
MIM_ERROR	Sent when an invalid MIDI message is received (this message is used for all MIDI messages except system-exclusive messages).
MIM_LONGERROR	Sent when an invalid MIDI system-exclusive message is received.
MIM_LONGDATA	Sent when either a complete MIDI system-exclusive message is received, or when a data buffer is filled with system-exclusive data.
MIM_OPEN	Sent when the device is opened using the midiInOpen function.
These messages are similar to those sent to window-procedure functions, but the parameters are different. A handle of the open MIDI device is passed as a parameter to the callback, along with the doubleword value of instance data that was passed using the midiInOpen value.

The callback has two message-specific parameters: dwParam1 and dwParam2. For the MIM_OPEN and MIM_CLOSE messages, these parameters are unused.

For the MIM_DATA message, dwParam1 specifies the received MIDI data and dwParam2 specifies a time stamp for the data. The data is packed into a doubleword value, as shown in the previous section on using window messages.

For the MIM_LONGDATA message, dwParam1 specifies a pointer to a MIDIHDR structure that identifies the data buffer for system-exclusive messages. As with the MIM_DATA message, dwParam2 specifies a time stamp for the data. The data buffer may not be completely filled. Use the dwBytesRecorded member of the MIDIHDR structure to determine the amount of valid data present in the buffer.

After the device driver is finished with a data block, you can clean up and free the data block. Because of the suggested restrictions on low-level audio callback functions, it is better not to do this from within the callback function. It is better to set events or semaphores and do this outside of the callback function. See Using a Callback Function to Process Driver Messages for details about the suggested restrictions on using callback functions.


 Receiving Time-Stamped MIDI Messages

Because of the delay between when the device driver receives a MIDI message and the time the application receives the message, MIDI input device drivers time-stamp the MIDI message with the time the message was received. MIDI time stamps are defined as the time the first byte of the message was received and are specified in milliseconds. The midiInStart function resets the time stamps for a device to zero.

As stated earlier, to receive time stamps with MIDI input, you must use a low-level callback function. The dwParam2 parameter of the callback function specifies the time stamp for data associated with the MIM_DATA and MIM_LONGDATA messages.


 Receiving Running-Status Messages

The MIDI 1.0 specification allows the use of running-status when a message has the same status byte as the previous message. When running status is used, the status byte of subsequent messages can be omitted. All MIDI input device drivers are required to expand messages using running status to complete messages — you always receive complete MIDI messages from a MIDI input device driver.


 Auxiliary Audio Devices

Auxiliary audio devices are audio devices whose output is mixed with the MIDI and waveform output devices in a multimedia computer. An example of an auxiliary audio device is the compact disc audio output from a CD-ROM drive.

Control for auxiliary audio devices is provided by a software-controlled audio mixer. The mixer can reside on the motherboard of a multimedia computer, or it can be on an add-in sound card. The following illustration shows the conceptual audio-signal routing in a multimedia computer.

In this multimedia computer, there are two auxiliary audio devices: the CD-ROM and the external audio input. The external audio input is an input jack that allows the user to connect other audio devices.


 Querying Low-Level Auxiliary Audio Devices

Not all multimedia systems have auxiliary audio support. You can use the auxGetNumDevs function to determine the number of controllable auxiliary devices present in a system.

To get information on a particular auxiliary audio device, use the auxGetDevCaps function. This function takes a pointer to an AUXCAPS structure that it fills with information about the capabilities of a given device.


 Determining Auxiliary Audio Device Types

The MMSYSTEM.H header file defines the following flags for the wTechnology member of the AUXCAPS structure to determine the device type of an auxiliary audio device.

Flag	Description
AUXCAPS_CDAUDIO	The device is an internal CD-ROM drive.
AUXCAPS_AUXIN	The device is an auxiliary audio input jack.


 Determining Capabilities of Auxiliary Audio Devices

The dwSupport member of the AUXCAPS structure indicates whether the device driver supports volume changes. The MMSYSTEM.H header file defines the following flags for the dwSupport member.

Flag	Description
AUXCAPS_VOLUME	Volume-control support
AUXCAPS_LRVOLUME	Individual volume-control support for both the left and right channels


 Changing Auxiliary Audio-Device Volume

Windows provides the following functions to query and set the volume for auxiliary audio devices.

Function	Description
auxGetVolume	Gets the volume level of the specified auxiliary audio device.
auxSetVolume	Sets the volume level of the specified auxiliary audio device.
Not all auxiliary audio devices support volume changes. Some devices can support individual volume changes on both the left and the right channels. For information about how to determine whether a particular device supports volume changes, see Determining Capabilities of Waveform Output Devices.

Note  Unless your application is designed to be a master volume-control application providing the user with volume control for all audio devices in a system, you should open an audio device before changing its volume. Also be sure your application queries the volume level before changing it and restores the volume level to its previous level as soon as possible.

The volume level is specified (as it was in the waveform and MIDI volume-control functions) in a doubleword value with the high-order 16 bits specifying the relative volume of the right channel and the low-order 16 bits specifying the relative volume of the left channel. For devices that don't support individual volume control on both the left and right channels, the low-order 16 bits specify the volume level, and the high-order 16 bits are ignored.

Values for the volume level range from 0x0 (silence) to 0xFFFF (maximum volume) and are interpreted logarithmically. This means the perceived volume increase is the same from volume level 0x5000 to 0x6000 as it is from 0x4000 to 0x5000.

When querying volume levels with the auxGetVolume function, the volume is returned in a doubleword location specified by a pointer parameter.


 Audio Clipboard Formats

In addition to the standard and nonstandard waveform formats previously presented in this section, there are two Clipboard formats that can be used to represent audio data: CF_WAVE and CF_RIFF. Use the CF_WAVE format to represent data in one of the standard formats, such as 11 kHz or 22 kHz PCM. Use the CF_RIFF format to represent more complex data formats that cannot be represented as standard wave files.


 Low-Level Audio Functions

Following are the functions used with low-level audio services.

auxGetDevCaps
auxGetNumDevs
auxGetVolume
auxOutMessage
auxSetVolume
midiInAddBuffer
midiInClose
midiInGetDevCaps
midiInGetErrorText
midiInGetID
midiInGetNumDevs
midiInMessage
midiInOpen
midiInPrepareHeader
midiInReset
midiInStart
midiInStop
midiInUnprepareHeader
midiOutCacheDrumPatches
midiOutCachePatches
midiOutClose
midiOutGetDevCaps
midiOutGetErrorText
midiOutGetID
midiOutGetNumDevs
midiOutGetVolume
midiOutLongMsg
midiOutMessage
midiOutOpen
midiOutPrepareHeader
midiOutReset
midiOutSetVolume
midiOutShortMsg
midiOutUnprepareHeader
MidiProc
waveInAddBuffer
waveInClose
waveInGetDevCaps
waveInGetErrorText
waveInGetID
waveInGetNumDevs
waveInGetPosition
waveInMessage
waveInOpen
waveInPrepareHeader
waveInReset
waveInStart
waveInStop
waveInUnprepareHeader
waveOutBreakLoop
waveOutClose
waveOutGetDevCaps
waveOutGetErrorText
waveOutGetID
waveOutGetNumDevs
waveOutGetPitch
waveOutGetPlaybackRate
waveOutGetPosition
waveOutGetVolume
waveOutMessage
waveOutOpen
waveOutPause
waveOutPrepareHeader
waveOutReset
waveOutRestart
waveOutSetPitch
waveOutSetPlaybackRate
waveOutSetVolume
waveOutUnprepareHeader
waveOutWrite
WaveProc


 Media Control Interface

The Media Control Interface (MCI) provides applications written for Microsoft® Windows® with device-independent capabilities for controlling media devices such as audio hardware, videodisc players, and animation players. This overview presents an introduction to MCI and shows how to begin using it in Windows-based applications.


 About the Media Control Interface

MCI provides a device-independent, extensible interface for controlling virtually any type of media device. Because of the high level of device independence provided by MCI, you are encouraged to use MCI rather than low-level functions to access the multimedia capabilities of Windows.

Click on a topic below to view it:

•	The Architecture of MCI

•	The MCI Command Set

•	MCI Programming Interfaces

•	The Command-Message interface

•	The Command-String Interface (an introduction)

For more information about using MCI to control different types of audio devices, see High-Level Audio.


 The Architecture of MCI

To provide extensibility, MCI is designed around an architecture that uses special MCI device drivers to interpret and execute MCI commands.

MCI device drivers can control media hardware directly or through the low-level multimedia functions provided by Windows. Most commonly used devices, such as waveform audio and Musical Instrument Digital Interface (MIDI) devices, are controlled through the low-level multimedia functions.


 The MCI Programming Interfaces

MCI provides two programming interfaces: command string and command message.


 The Command-String Interface

The command-string interface allows you to use English-language commands to communicate with MCI devices. For example, the following command string plays a WAVE file named TIMPANI.WAV.

play timpani.wav

The command-string interface is designed for use with high-level programming and authoring environments such as Microsoft® Visual Basic® and Asymetrix® ToolBook®. Use the command-string interface for applications that provide a text-based interface to let users control MCI devices.


 The Command-Message Interface

The command-message interface uses a message-passing paradigm to communicate with MCI devices. The following example performs the same operation as the command-string example in The Command-String Interface.

WORD wDeviceID;

MCI_PLAY_PARMS mciPlayParms;

mciSendCommand(wDeviceID,            /* device identifier */

    MCI_PLAY,                        /* command message   */

    0,                               /* flags             */

    (DWORD) (LPVOID) &mciPlayParms); /* structure         */

The command-message interface is designed to be used by applications requiring a C-language interface to control multimedia devices. Use the command-message interface for applications that directly control multimedia devices.


 The MCI Command Set

The MCI command set provides a generic core set of commands to control different types of media devices. For example, MCI uses the same command to begin playback of a waveform audio file, a videodisc track, and an animation sequence. Some devices have unique capabilities, such as the capability of an animation player to use a frame-based time format. For such devices, MCI provides extended commands that are unique to a particular type of device.

The commands in the command-string interface provide a good overview of the MCI command set. Each of these commands is represented by a similar command message in the command-message interface. For example, the close command string is the equivalent of the MCI_CLOSE command message.

Following are some commonly used commands.

Command	Description
capability	Requests information about the capabilities of a device.
close	Closes a device after it has been used.
info	Requests information about a device (for example, a description of the hardware associated with the device).
open	Opens and initializes a device.
pause	Pauses playing or recording on a device.
play	Begins playing on a device.
record	Begins recording on a device.
resume	Resumes playing or recording on a paused device.
seek	Changes the current position in the media.
set	Changes control settings, such as the time format the device is using.
status	Requests information about the status of a device (for example, whether the device is playing or paused).
stop	Stops playing or recording on a device.


 About MCI Devices

MCI device drivers can be classified as either simple devices or compound devices. Simple devices do not require a data file for playback. Videodisc players and compact disc (CD) audio players are examples of simple devices. Compound devices require a data file for playback. MIDI sequencers and waveform audio players are examples of compound devices. The data file associated with a compound device is known as a device element. Examples of device elements are MIDI files and WAVE files.


 Standard MCI Device Types

A device type identifies a class of MCI devices that responds to a common set of commands. Following are the currently defined device types.

Device type	Description
animation	Animation device
cdaudio	CD audio player
dat	Digital audio tape player
digitalvideo	Digital video in a window (not based on graphics device interface)
other	Undefined MCI device
overlay	Overlay device (analog video in a window)
scanner	Image scanner
sequencer	MIDI sequencer
videodisc	Videodisc player
waveaudio	Audio device that plays digitized waveform files


 MCI Device Names

For any given device type, there might be several MCI drivers that share the command set but operate on different data formats. For example, for animation devices there are several MCI drivers that use the same command set but use different file formats. To uniquely identify an MCI driver, MCI uses device names.

Device names are identified in the [mci32] section of the registry. This section identifies all MCI device drivers to Windows. The following is part of a typical [mci] section.

[mci32]

WaveAudio=mciwave.dll

Sequencer=mciseq.dll

AVIVideo=mciavi.dll

CDAudio=mcicda.dll

The key name (on the left side of the equal sign) is the device name. The value corresponding to the key name (on the right side of the equal sign) identifies the filename of the MCI driver. The device name is often the same as the device type for the driver, as is the case for the WaveAudio, Sequencer, and CDAudio devices in the preceding example. The AVIVideo device is a digital video device, but it uses a unique device name.

If an MCI driver is installed using a device name that already exists in the [mci32] section, Windows appends an integer to the device name of the new driver, creating a unique device name. In the preceding example, a driver installed using the cdaudio device name would be assigned device name cdaudio1. A subsequent cdaudio device would be assigned device name cdaudio2.


 Opening MCI Devices

Before using an MCI device, you must initialize it by opening it. Opening a device loads its driver into memory (if it isn't already loaded) and establishes a device identifier to identify the device in subsequent commands. (The device identifier is not used in the command-string interface.) There are several ways to specify the device you want to open:

•	With simple devices, you can open the device by specifying the device name.

•	With compound devices, you can open the device by specifying the device name, the device element, or both.

For example, the following command string opens a CD audio device (a simple device) by specifying the device name.

open cdaudio

The next command string opens a waveform audio device (a compound device) by specifying the device name and a device element.

open bells.wav type waveaudio

You can also open a compound device by specifying only the device element, as shown in the following example.

open bells.wav

If you specify only a device element when opening a compound device, MCI uses the filename extension of the device element filename to determine which device to open. The registry contains an [mci extensions] section that associates filename extensions and corresponding MCI device types. The following is part of an [mci extensions] section.

[mci extensions]

Wav=WaveAudio

Mid=Sequencer

rmi=Sequencer

avi=avivideo


 Using the Command-Message Interface

Applications that require a C-language interface to MCI should use the command-message interface. The following topics provide background and detailed information about using this interface.

About Command Messages
Summary of MCI Command Messages
Sending MCI Command Messages
Opening an MCI Device
Closing an MCI Device
Using the Wait and Notify Flags
Using MCI_SYSINFO to Obtain MCI System Information
About the Command-String Interface
Sending MCI Command Strings
Additional Information About Command Strings


 About Command Messages

MCI command messages consist of the following three elements:

•	A constant message value

•	A structure (parameter block) specifying additional parameters for the command

•	A set of flags specifying options for the command and validating members in the structure

Commands are sent by using the mciSendCommand function, which has parameters for the message, flags, and a pointer to the structure. For more information about the mciSendCommand function, see Sending MCI Command Messages.


 Command-Message Example

For an example of an MCI command message, consider MCI_PLAY. The MMSYSTEM.H header file defines the MCI_PLAY command message, the MCI_NOTIFY, MCI_WAIT, MCI_FROM, and MCI_TO flags, and the MCI_PLAY_PARMS structure. The MCI_PLAY_PARMS structure has the following form.

typedef struct {

    DWORD   dwCallback;

    DWORD   dwFrom;

    DWORD   dwTo;

} MCI_PLAY_PARMS;

The MCI_WAIT and MCI_NOTIFY flags are option flags. MCI_WAIT tells the driver to wait until the command is complete before returning control to the application. MCI_NOTIFY tells the driver to notify the application when the command is complete. For more information on using these flags, see Using the Wait and Notify Flags.

The MCI_FROM and MCI_TO flags validate the dwFrom and dwTo members in the MCI_PLAY_PARMS structure. These members specify beginning and ending positions for the play operation. Both flags are optional. If either flag is specified, the driver takes the value from the corresponding member in the structure as a beginning or ending position; otherwise, the members are ignored.

Note  Members in a structure are ignored unless corresponding flags are specified to validate the members.


 Items in Query Commands

Two command messages that query devices for information, MCI_GETDEVCAPS and MCI_STATUS, extend the command-message paradigm by adding a dwItem member to the structure and defining item constants for the member. Item constants specify which item of information is being requested. For example, MMSYSTEM.H defines the MCI_STATUS_PARMS structure for the MCI_STATUS command message as follows.

typedef struct {

    DWORD   dwCallback;

    DWORD   dwReturn;

    DWORD   dwItem;

    DWORD   dwTrack;

} MCI_STATUS_PARMS;

If you use the MCI_STATUS_ITEM flag to validate the dwItem member, make sure that dwItem contains a constant defined by MMSYSTEM.H to indicate the exact status information requested. The MCI_STATUS command message uses the following constants for dwItem:

MCI_STATUS_CURRENT_TRACK
MCI_STATUS_LENGTH
MCI_STATUS_MEDIA_PRESENT
MCI_STATUS_MODE
MCI_STATUS_NUMBER_OF_TRACKS
MCI_STATUS_POSITION
MCI_STATUS_READY
MCI_STATUS_TIME_FORMAT


 Summary of MCI Command Messages

MCI defines four classifications of command messages. The command messages and options in the following two classifications are defined as the minimum command set for any MCI driver:

•	System command messages are handled directly by MCI rather than by the driver.

•	Required command messages are handled by the driver. All drivers should support the required command messages and options.

Regardless of the specific driver you use, you should be able to assume that the command messages and options in the two preceding groups are available.

The command messages in the following two classifications are not supported by all drivers:

•	Basic (or optional) command messages are used by some devices. If a device supports a basic command message, it must support a defined set of options for the command message.

•	Extended command messages are specific to certain device types or drivers. They include new command messages (for example, the MCI_PUT and MCI_WHERE command messages for the animation device type) and extensions to existing command messages (for example, the MCI_ANIM_GETDEVCAPS_CAN_STRETCH option added to the MCI_STATUS command message for the animation device type).

If you need to use a basic or extended command message or option, you should query the device driver before trying to use the command message or option (that is, unless you are certain that the MCI driver you have used during development is the same one that will be available on the delivery system). The following tables summarize the specific command messages in each category.

MCI directly processes the following system command messages, rather than passing them to MCI device drivers.

Command	Description
MCI_BREAK	Sets a break key for an MCI device.
MCI_SYSINFO	Returns information about MCI devices.
Required command messages must be supported by all MCI device drivers. The following table lists the required command messages.

Command	Description
MCI_CLOSE	Closes the device.
MCI_GETDEVCAPS	Obtains the capabilities of a device.
MCI_INFO	Obtains textual information from a device.
MCI_OPEN	Initializes the device.
MCI_STATUS	Obtains status information from the device.
Following are the basic command messages. The use of these command messages by a device is optional.

Command	Description
MCI_LOAD	Loads data from a file.
MCI_PAUSE	Stops playing.
MCI_PLAY	Starts transmitting output data.
MCI_RECORD	Starts recording data.
MCI_RESUME	Resumes playing or recording on a paused device.
MCI_SAVE	Saves data to a file.
MCI_SEEK	Seeks forward or backward.
MCI_SET	Sets the operating state of the device.
MCI_STATUS	Obtains status information about the device. (Supplements the required MCI_STATUS command message with options for devices using linear media with identifiable positions.)
MCI_STOP	Stops playing or recording.
Some MCI devices have additional command messages or add options to existing command messages. Although some extended command messages apply only to a specific device driver, most of them apply to all drivers of a particular device type. For example, the sequencer command set extends the MCI_SET command message to add time formats that are needed by MIDI sequencers.

Unless you are certain that the specific MCI driver you use during development will be available on the delivery system, do not assume that the device supports the extended command messages or options. You can use the MCI_GETDEVCAPS command message to determine whether a specific feature is supported. Applications should be ready to handle an MCIERR_UNSUPPORTED_FUNCTION return value.

The following extended command messages are available with certain device types.

Command Message	Device types	Description
MCI_CUE	waveaudio	Prepares for playing or recording.
MCI_DELETE	waveaudio	Deletes a data segment from the media element.
MCI_ESCAPE	videodisc	Sends custom information to a device.
MCI_FREEZE	overlay	Disables video acquisition to the frame buffer.
MCI_PUT	animation overlay	Defines the source, destination, and frame windows.
MCI_REALIZE	animation	Tells the device to select and realize its palette into a display context of the displayed window.
MCI_SPIN	videodisc	Starts the disc spinning or stops the disc from spinning.
MCI_STEP	animation, videodisc	Steps the play one or more frames forward or reverse.
MCI_UNFREEZE	overlay	Enables the frame buffer to acquire video data.
MCI_UPDATE	animation	Repaints the current frame into the display context.
MCI_WHERE	animation, overlay	Obtains the rectangle specifying the source, destination, or frame area.
MCI_WINDOW	animation, overlay	Controls display window options such as caption text.


 Sending MCI Command Messages

Windows provides the following functions to send command messages to devices and to query devices for error information.

Function	Description
mciSendCommand	Sends a command message to an MCI device.
mciGetErrorString	Returns the error string corresponding to an error number.


 The MCI Device Identifier

MCI returns a device identifier when you open a device by using the MCI_OPEN command message. Use this identifier to identify the opened device when sending subsequent commands.

MMSYSTEM.H defines a special constant, MCI_ALL_DEVICE_ID, to indicate that a command message is to be sent to all of the MCI devices that an application has opened. You can use MCI_ALL_DEVICE_ID with any command message that does not return information. For instance, the following example closes all of the MCI devices that have been opened by an application.

DWORD dwReturn;

/*

 * Closes all MCI devices opened by this application.

 * Waits until devices are closed before returning.

 */

if (dwReturn = mciSendCommand(MCI_ALL_DEVICE_ID, MCI_CLOSE,

        MCI_WAIT, NULL))

    /* Error, unable to close all devices. */

    return FALSE;

Note  Although using the MCI_ALL_DEVICE_ID identifier is a convenient way to broadcast a command to all your devices, don't rely on it to synchronize devices; the timing between messages can vary.


 Opening an MCI Device

Before using a device, you must initialize it by using the MCI_OPEN command message. The variations of this command message make it one of the most complex of all MCI commands.


 The MCI_OPEN_PARMS Structure

Like all MCI command messages, MCI_OPEN has an associated structure. The default structure for MCI_OPEN is the MCI_OPEN_PARMS structure. Certain devices, such as waveaudio, animation, and overlay devices, have extended structures to accommodate additional optional parameters. Unless you need to use these additional parameters, you can use the MCI_OPEN_PARMS structure with any MCI device.

MCI uses the wDeviceID member of this structure to return the device identifier to the application. You should check the return value of the mciSendCommand function before using the device identifier, to be sure that it is valid. A nonzero return value indicates that an error occurred during the opening of the device process.

Note  You can also determine the device identifier by specifying the device name in a call to the mciGetDeviceID function.

Other members used in opening a device correspond to the following flags for the command message.

Flag	Meaning
MCI_OPEN_ALIAS	The lpstrAlias member of the structure contains a pointer to a device alias.
MCI_OPEN_ELEMENT	The lpstrElementName member of the structure contains a pointer to the element name.
MCI_OPEN_SHAREABLE	The device or element was opened as shareable.
MCI_OPEN_TYPE	The lpstrDeviceType member of the structure contains a pointer to the device-type identifier.
MCI_OPEN_TYPE_ID	The lpstrDeviceType member of the structure contains an integer device-type identifier.


 Opening Simple Devices

To open a simple device such as a CD audio or videodisc device, use the lpstrDeviceType member in the MCI_OPEN_PARMS structure to identify the device to open. There are three ways to identify devices:

•	Specify a pointer to a null-terminated string containing the device name.

•	Specify a device-type constant.

•	Specify the actual name of the device driver.

Regardless of which method you use to identify the device, you must specify the MCI_OPEN_TYPE flag to validate the lpstrDeviceType member. For instance, the following example opens a CD audio device by specifying the device name.

UINT wDeviceID;

DWORD dwReturn;

MCI_OPEN_PARMS mciOpenParms;

/* Open a compact disc device by specifying the device name. */

mciOpenParms.lpstrDeviceType = "cdaudio";

if (dwReturn = mciSendCommand(0, MCI_OPEN, MCI_OPEN_TYPE,

        (DWORD)(LPVOID) &mciOpenParms))

    /* Error, unable to open device. */

    return FALSE;

/* Device opened successfully. Get the device ID. */

wDeviceID = mciOpenParms.wDeviceID;

You can also open a device by specifying a device-type constant. To be opened by means of a device-type constant, device drivers must be installed in the [mci] section of the registry by using the following device types.

Device type	Device-type constant
animation	MCI_DEVTYPE_ANIMATION
cdaudio	MCI_DEVTYPE_CD_AUDIO
dat	MCI_DEVTYPE_DAT
digitalvideo	MCI_DEVTYPE_DIGITAL_VIDEO
other	MCI_DEVTYPE_OTHER
overlay	MCI_DEVTYPE_OVERLAY
scanner	MCI_DEVTYPE_SCANNER
sequencer	MCI_DEVTYPE_SEQUENCER
videodisc	MCI_DEVTYPE_VIDEODISC
waveaudio	MCI_DEVTYPE_WAVEFORM_AUDIO
If you open a device by specifying a device-type constant, you must specify the MCI_OPEN_TYPE_ID flag in addition to the MCI_OPEN_TYPE flag. The following example opens a CD audio device by specifying a device-type constant.

UINT wDeviceID;

DWORD dwReturn;

MCI_OPEN_PARMS mciOpenParms;

/*

* Open a compact disc device by

* specifying a device-type constant.

*/

mciOpenParms.lpstrDeviceType = (LPCSTR) MCI_DEVTYPE_CD_AUDIO;

if (dwReturn = mciSendCommand(0, MCI_OPEN,

        MCI_OPEN_TYPE | MCI_OPEN_TYPE_ID,

        (DWORD)(LPVOID) &mciOpenParms))

    /* Error, unable to open device. */

    return FALSE;

/* Device opened successfully. Get the device ID. */

wDeviceID = mciOpenParms.wDeviceID;

When you open a device by specifying a device-type constant, MCI uses the high-order word of the lpstrDeviceType member to distinguish between multiple occurrences of the device type in the registry.

For example, if the registry lists entries for waveaudio1 and waveaudio2, the following statement sets the lpstrDeviceType member to specify the device identified by waveaudio2.

LPSTR lpstrDeviceType;

lpstrDeviceType = (LPSTR)MAKELONG(MCI_DEVTYPE_WAVEFORM_AUDIO, 2);

Similarly, to specify the device identified by waveaudio1, set the high-order word of lpstrDeviceType to 0 or 1. (Setting the high-order word to 0 tells MCI to use an unnumbered device or the lowest-numbered device.)

You can also open a device by specifying the filename of the device driver in the lpstrDeviceType member of the MCI_OPEN_PARMS structure. You don't need to specify the complete path or the filename extension — MCI assumes that drivers are located in the Windows system directory and have a filename extension of .DRV.

Note  Opening MCI devices by specifying the filename of the device driver may be useful during development and testing. However, this technique is not recommended for applications because it makes them device dependent. Applications that open MCI devices by filename may not work in all systems.


 Opening Compound Devices

There are three ways to open a compound device:

•	Specify only the device (by using the device name, a device-type constant, or the filename of the device driver).

•	Specify both the device and the device element.

•	Specify only the device element.

The first method — specifying only the device — is useful for determining the capabilities of a device by using the MCI_GETDEVCAPS command message. To actually control a media device, you must specify a device element when you open the device.

To specify a device element, fill the lpstrElementName member of the MCI_OPEN_PARMS structure with a pointer to a null-terminated string containing the filename of the device element. You must also validate the lpstrElementName member by specifying the MCI_OPEN_ELEMENT flag in the dwFlags parameter of the mciSendCommand function.

You can specify the device in the same manner used for simple devices: by device name, by device-type constant, or by the filename of the driver. The following example opens the waveaudio device with a WAVE file named TIMPANI.WAV.

UINT wDeviceID;

DWORD dwReturn;

MCI_OPEN_PARMS mciOpenParms;

/*

 * Open a waveaudio device by specifying

 * the device name and device element.

 */

mciOpenParms.lpstrDeviceType = "waveaudio";

mciOpenParms.lpstrElementName = "timpani.wav";

if (dwReturn = mciSendCommand(0, MCI_OPEN,

        MCI_OPEN_TYPE | MCI_OPEN_ELEMENT,

        (DWORD)(LPVOID) &mciOpenParms))

    /* Error, unable to open device. */

    return FALSE;

/* Device opened successfully. Get the device ID. */

wDeviceID = mciOpenParms.wDeviceID;

You can also open a device by specifying just a device element. MCI uses the filename extension of the given device element along with the [mci extensions] section of the registry to select the device to open. For more information about opening devices by specifying only a device element, see Opening MCI Devices.


 Closing an MCI Device

The MCI_CLOSE command message releases access to a device or device element. MCI frees a device when all processes using a device have closed it. To help MCI manage devices, applications should explicitly close each device or device element when they are finished using it.

Note  It is very important that applications close all opened MCI devices before terminating. You can close all devices with a single command message by specifying the MCI_ALL_DEVICE_ID constant as the device identifier.


 Using the Wait and Notify Flags

Typically, MCI returns control to the application immediately, even if it takes several seconds to complete the action initiated by a command. For example, after a CD audio device receives a seek command, control returns to the application before the seek operation is complete. You can use the following two flags to request that MCI wait until a command is complete before returning control to the application, or that MCI notify the application when the command is complete.

Flag	Description
MCI_NOTIFY	Directs the device to return control immediately and post the MM_MCINOTIFY message when the requested action is complete.
MCI_WAIT	Directs the device to wait until the requested action is complete before returning control to the application.


 Using the Notify Flag

The MCI_NOTIFY flag directs MCI to post the MM_MCINOTIFY message when the device completes an action. The application specifies the handle of the destination window for the message in the dwCallBack member of the structure sent with the command message. Every structure associated with a command message contains this member.

Note  MCI can have only one pending notification message for each device.

When MCI posts the MM_MCINOTIFY message, it sets the low-order word of the lParam parameter of the window procedure to the identifier of the device initiating the callback. The wParam parameter of the window procedure contains one of the following constants specifying the notification status of the callback.

Flag	Meaning
MCI_NOTIFY_SUCCESSFUL	The conditions required for initiating the callback are satisfied and the command finished without interruption.
MCI_NOTIFY_SUPERSEDED	MCI had a notification pending and received another notify request. MCI resets the callback conditions to correspond to the notify request of the new command.
MCI_NOTIFY_ABORTED	The application sent a new command that prevented the callback conditions set by a previous command from being satisfied. If an application interrupts a command that requested notification, MCI does not inform the window procedure of the notify command being aborted.
MCI_NOTIFY_FAILURE	A device error occurred while a device was executing the command. For example, MCI posts this message when a hardware error occurs during a play command.


 Using the Wait Flag and Break Command Message

Specifying the MCI_WAIT flag with a command message causes MCI to wait until the command has finished before returning control to the application. Using the wait flag with commands that take a long time essentially disables a system from receiving any user input until the command is complete.

MCI supports a break key to interrupt the wait operation and return control to the application. The break key does not interrupt the command, but by returning control to the application, it allows the application to monitor user input.

By default, MCI defines the break key as CTRL+BREAK. Applications can redefine this key by using the MCI_BREAK command message. MCI_BREAK uses the MCI_BREAK_PARMS structure.

The following flags validate members in the MCI_BREAK_PARMS structure:

Flag	Description
MCI_BREAK_HWND	Validates the hwndBreak member, which specifies the window that must have the focus to enable break detection.
MCI_BREAK_KEY	Validates the nVirtKey member, which specifies the virtual-key code to be used for the break key.
MCI_BREAK_OFF	Disables any existing break key.


 Using MCI_SYSINFO to Obtain MCI System Information

The MCI_SYSINFO command message obtains system information about MCI devices. MCI handles this message without relaying it to any MCI device. MCI returns the system information in the MCI_SYSINFO_PARMS structure.

The MCI_SYSINFO command message has the following flags.

Flag	Meaning
MCI_SYSINFO_QUANTITY	MCI returns the number of devices of a given type listed in the [mci] section of the registry. When this flag is used with the MCI_SYSINFO_OPEN flag, the number of open devices is returned.
MCI_SYSINFO_NAME	MCI returns the name of a device that satisfies the query. When this flag is used with the MCI_SYSINFO_OPEN flag, only the names of open devices are returned.
MCI_SYSINFO_OPEN	MCI returns the number or names of open devices.
MCI_SYSINFO_INSTALLNAME	MCI returns the name listed in the registry entry used to install the device.
You use the MCI_SYSINFO_QUANTITY flag to determine the number of devices for a particular type listed in the [mci] section of the registry. For this flag, set the wDeviceType member of the structure to the device type. When requesting the number of devices, set the wDeviceID parameter to NULL. MCI returns the number of devices as a doubleword in the lpstrReturn member of the structure. If you combine the MCI_SYSINFO_QUANTITY flag with the MCI_SYSINFO_OPEN flag, MCI returns the number of devices of that type opened by the process.

Once you have the number of devices, you can enumerate the names of the devices by using the MCI_SYSINFO_NAME flag. To get information by using this flag, you must create a buffer for the return name. In the structure, specify a pointer to the buffer, the size of the buffer, the index number corresponding to the device (1 is the first device), and the device type. This information is entered in the lpstrReturn, dwRetSize, dwNumber, and wDeviceType members. MCI returns the device name in the buffer. When requesting the name of a particular device, set the wDeviceID parameter to NULL. To restrict the names to open devices, use the MCI_SYSINFO_OPEN flag with MCI_SYSINFO_NAME.

To retrieve information on all devices in the system, you can assign the MCI_ALL_DEVICE_ID constant to the wDeviceID parameter. When you use this identifier, MCI ignores the contents of the wDeviceType member and returns information on all MCI devices listed in the registry. When you use the MCI_SYSINFO_OPEN flag with the MCI_ALL_DEVICE_ID identifier, MCI returns information about the devices opened by the task.

You can retrieve the installation name of an open device by using the MCI_SYSINFO_INSTALLNAME flag. To get the installation name, you must create a buffer for the return name. In the structure, specify a pointer to the buffer and the size of the buffer in the lpstrReturn and dwRetSize members. MCI places the device that corresponds to the wDeviceID parameter name in the buffer.


 About the Command-String Interface

This section presents an introduction to the MCI command-string interface. MCI provides the following functions for working with command strings.

Function	Description
mciSendString	Sends a command string to an MCI device driver. This function also has parameters for callback functions and return strings.
mciGetErrorString	Returns the error string corresponding to an error number.


 Sending MCI Command Strings

Use the mciSendString function to send command strings to a device. The following statement passes the "play to 500" command string to a waveaudio device driver.

DWORD dwErrorCode;

dwErrorCode = mciSendString("play waveaudio to 500", NULL, 0, 0L);

If the mciSendString function succeeds, it returns zero. If the function fails, it returns an error code. To get extended error information, use the mciGetErrorString function.


 Additional Information About Command Strings

The MCITEST application contains examples of using the mciSendString and mciGetErrorString functions. You can use this application to experiment with MCI devices and command strings.


 Multimedia File Input/Output

Most multimedia applications require file input/output (I/O) — the ability to create, read, and write disk files. The multimedia file I/O services provided by the Microsoft® Win32® application programming interface (API) offer buffered and unbuffered file I/O and support for standard Resource Interchange File Format (RIFF) files. The services are extensible with custom I/O procedures.


 About the Multimedia File Input/Output Services

Most applications need only the basic file I/O services and the RIFF file I/O services. Applications sensitive to file I/O performance, such as applications that stream data from a CD-ROM in real time, can optimize performance by using services to directly access the file I/O buffer. Applications that access custom storage systems can provide their own I/O procedure that reads and writes elements of the storage system. A storage system is a method of physically storing data in a file, such as a file-archival system or a database storage system.

This section covers the following topics:

•	Using basic file I/O services

•	Performing buffered file I/O

•	Working with RIFF files

•	Directly accessing a file I/O buffer

•	Using memory files

•	Writing a custom I/O procedure

The multimedia file I/O services provide support for the following file I/O operations:

•	Basic unbuffered and buffered file I/O

•	RIFF file I/O

•	Direct access to the file I/O buffer

•	Memory files

•	Custom storage system I/O using application-supplied I/O procedures


 Comparison With Other File I/O

You might ask why you need another set of file I/O services, when you already have the services of the C run-time and Win32 API libraries. The multimedia file I/O services offer the following advantages over other file I/O services:

•	They are a part of the system software, so they don't increase the size of your application, like linking to the C run-time libraries

•	They provide more functionality than the Win32 services, such as support for buffered I/O, RIFF files, memory files, and custom storage systems

In addition, the multimedia file I/O services are optimized for performance-intensive applications.


 Function Prefixes

All multimedia file I/O function names begin with the mmio prefix. Similarly, all multimedia file I/O message names begin with the MMIOM_ prefix.


 Data Types

The MMSYSTEM.H header file defines data types and function prototypes for all multimedia file I/O functions. You must include this header file in any source-code module that uses these functions. MMSYSTEM.H depends on declarations made in WINDOWS.H, so you must first include the WINDOWS.H header file. MMSYSTEM.H defines the following data types for the multimedia file I/O functions.

Type	Description
FOURCC	A four-character code identifying an element of a RIFF file.
HMMIO	A handle of an open file.
MMCKINFO	A structure containing information about a chunk in a RIFF file.
MMIOINFO	A structure used to maintain the current state of a file accessed using the multimedia file I/O services.
MMIOPROC	A custom multimedia file I/O procedure.


 Performing Basic File Input/Output

Using the basic I/O services is similar to using the C run-time file I/O services. Files must be opened before they can be read or written. After reading or writing, the file must be closed. You can change the current read/write location by seeking to a specified position in an open file. The following table lists the basic file I/O functions.

Function	Description
mmioClose	Closes an open file.
mmioOpen	Opens a file for reading or writing or both and returns a handle of the open file.
mmioRead	Reads a specified number of bytes from an open file.
mmioSeek	Changes the current position for reading or writing in an open file.
mmioWrite	Writes a specified number of bytes to an open file.
These file I/O functions provide the core of the multimedia file I/O services — you can use them for buffered and unbuffered I/O, as well as for I/O to RIFF files, memory files, and custom storage systems.


 Opening a Multimedia File

Before doing any I/O operations to a file, you must first open the file by using the mmioOpen function. The mmioOpen function returns a file handle that you use to identify the open file when calling other file I/O functions.

Note  Do not use HMMIO file handles with Windows or C run-time file I/O functions.

There are options you can use with the mmioOpen function for operations beyond basic file I/O. By specifying an MMIOINFO structure with the lpmmioinfo parameter you can open memory files, specify a custom I/O procedure, or supply a buffer for buffered I/O. These topics are discussed later in this section. First, this section discusses the most basic use of mmioOpen — opening files for basic unbuffered file I/O.

To open a file for basic I/O operations, set the lpmmioinfo parameter of mmioOpen to NULL. For example, the following example opens a file named C:\SAMPLES\SAMPLE1.TXT for reading, and checks the return value for errors.

HMMIO hFile;

.ifdef REF

    .

    .

    .

.endif

if ((hFile = mmioOpen("C:\\SAMPLES\\SAMPLE1.TXT",

        NULL, MMIO_READ)) != NULL) /* File opened successfully */

    return TRUE;

else

        /* File cannot be opened. */

    return FALSE;


 Options for Opening a File

When you open a file, you must specify whether you are opening the file for reading, writing, or both reading and writing. In addition, you can specify other options, such as to create or delete a new file. Use the dwFlags parameter of mmioOpen to specify options for opening a file.

Following are the basic options for opening a file using mmioOpen:

Flag	Description
MMIO_READ	Opens a file for reading only.
MMIO_WRITE	Opens a file for writing only.
MMIO_READWRITE	Opens a file for reading and writing.
MMIO_CREATE	Creates a new file (if the file already exists, it truncates it to zero length).
MMIO_DELETE	Deletes a file.
MMIO_ALLOCBUF	Opens a file for buffered I/O.
The MMIO_READ, MMIO_WRITE, and MMIO_READWRITE flags are read/write privilege flags. These flags are mutually exclusive — specify only one when opening a file. If you don't specify one of these flags, mmioOpen opens the file for reading only.

The MMIO_CREATE and MMIO_DELETE flags are also mutually exclusive. You can specify one of the read/write privilege flags with the MMIO_CREATE flag. You can't specify any additional flags with the MMIO_DELETE flag.

For information on using the MMIO_ALLOCBUF flag, see Performing Buffered File Input/Output.

In addition to the basic options for opening a file, there are sharing options you can use for opening files so they can be opened and accessed by more than one process. Following are the sharing options for opening a file using mmioOpen.

Flag	Description
MMIO_COMPAT	Opens a file in compatibility mode.
MMIO_EXCLUSIVE	Opens a file in exclusive mode.
MMIO_DENYWRITE	Opens a file and denies other processes write access to the file.
MMIO_DENYREAD	Opens a file and denies other processes read access to the file.
MMIO_DENYNONE	Opens a file without denying other processes read or write access to the file.


 Creating and Deleting Files

To create a new file, specify the MMIO_CREATE option with the mmioOpen function. For example, the following example creates a new file and opens it for both reading and writing.

HMMIO hFile;

.ifdef REF

    .

    .

    .

.endif

hFile = mmioOpen("NEWFILE.TXT",

                  NULL, MMIO_CREATE | MMIO_READWRITE);

if (hFile != NULL)

        /* File created successfully. */

    return TRUE;

else

        /* File could not be created. */

    return FALSE;

Note  If the file you are creating already exists, it will be truncated to zero length.

To delete a file, specify the MMIO_DELETE flag with the mmioOpen function. Once you delete a file, it can't be recovered. If the file deletion is the result of a request from a user, always query the user to be sure the user wants to delete the specified file before you actually delete it.


 Reading and Writing a File

To read and write to open files, use the mmioRead and mmioWrite functions. Each of these functions takes an HMMIO file handle, a pointer to a buffer, and a parameter specifying the number of bytes to read or write.

For an example using mmioRead to read from a file, see Example of RIFF File I/O.


 Seeking to a New Position in a Multimedia File

The current position or file pointer in a file is the location where the next read or write operation will occur. To change the current position in an open file, use the mmioSeek function.

The return value is the new position, specified in bytes from the beginning of the file. If an error occurs, the return value is −1. If you seek to an invalid location in a file, such as past the end of the file, mmioSeek may not return an error, but subsequent I/O operations can fail.


 Performing Buffered File Input/Output

Most of the overhead in file I/O involves accessing the media (the physical device). If you are reading or writing many small blocks of information, the media device can spend a lot of time seeking the physical location on the media for each read or write operation. In this case, better performance is achieved by using buffered file I/O. With buffered I/O, the file I/O manager maintains an intermediate buffer larger than the blocks of information you are reading or writing. It only accesses the media when the buffer must be filled from or written to the disk.


 Deciding When to Use Buffered File I/O

It's difficult to provide exact metrics telling you when you need to use buffered I/O. It depends on how many read and write operations you perform on a file, and on the size of these read and write operations. A general guideline is to use buffered I/O if you are doing many small I/O operations (less than 2 kilobytes each). But this rule isn't absolute — it's best to understand exactly how your program uses file I/O and experiment to optimize file I/O for your program's requirements.


 Opening a File for Buffered File I/O

The multimedia file I/O manager provides several ways to set up and use buffered file I/O. The main distinction between these different approaches is whether the file I/O manager or the application allocates the buffer — either the file I/O manager or the application can allocate the I/O buffer. Unless you want to access the I/O buffer directly or open a memory file, let the file I/O manager allocate the buffer. For more information about accessing an I/O buffer directly and using memory files, see Directly Accessing a File Input/Output Buffer and Performing File Input/Output on Memory Files.

A buffer allocated by the file I/O manager is called an internal buffer. To open a file for buffered I/O using an internal buffer, specify the MMIO_ALLOCBUF flag with the mmioOpen function when you open the file. Once a file is opened for buffered I/O, the buffer is essentially transparent to the application. You can read, write, and seek the same way as with unbuffered I/O.


 I/O Buffer Control Functions

The multimedia file I/O services also include some functions that give you more control over the file I/O buffer. Using the following functions, you can force the contents of an I/O buffer to be written to disk, enable buffered I/O on a file opened for unbuffered I/O, change the size of an I/O buffer, and supply your own I/O buffer.

Function	Description
mmioFlush	Writes the contents of the I/O buffer to disk.
mmioSetBuffer	Changes the size of the I/O buffer, and allows applications to supply their own buffer.


 Flushing an I/O Buffer

Flushing an I/O buffer means writing the contents of the buffer to disk. You don't have to call the mmioFlush function to flush an I/O buffer — the buffer is automatically flushed when you close a file using the mmioClose function. If you don't close a file immediately after writing to it, you flush the buffer to ensure the information is written to disk.

Note  If you run out of disk space, mmioFlush may fail, even if the preceding mmioWrite calls were successful. Similarly, mmioClose may fail when it is flushing its I/O buffer.


 Changing the Size of the Internal I/O Buffer

The default size of the internal I/O buffer is 8K. If this size is not adequate, you can use the mmioSetBuffer function to change the size of the buffer. You can also use mmioSetBuffer to enable buffering on a file opened for unbuffered I/O.

The following example opens a file named SAMPLE.TXT for unbuffered I/O, and then enables buffered I/O with an internal 16K buffer.

HMMIO hFile;

.ifdef REF

    .

    .

    .

.endif

if ((hFile = mmioOpen("SAMPLE.TXT", NULL, MMIO_READ)) != NULL) {

    /* File opened successfully; request an I/O buffer */

    if (mmioSetBuffer(hFile, NULL, 16384L, 0))

            /* Buffer cannot be allocated. */

        return FALSE;

    else

            /* Buffer allocated successfully. */

        return TRUE;

}

else

        /* File cannot be opened. */

    return FALSE;


 Supplying Your Own I/O Buffer

You can also use mmioSetBuffer to supply your own buffer for use as a memory file. For details on using memory files, see Performing File Input/Output on Memory Files.


 Working With RIFF Files

The preferred format for multimedia files is the Resource Interchange File Format (RIFF). The RIFF format is a tagged-file structure.

The multimedia file I/O services provide the following functions to support file I/O to RIFF files.

Function	Description
mmioAscend	Ascends out of a RIFF file chunk to the next chunk in the file.
mmioCreateChunk	Creates a new chunk in a RIFF file.
mmioDescend	Descends into a RIFF file chunk beginning at the current file position, or searches for a specified chunk.
mmioFOURCC	Converts four individual characters into a four-character code.
mmioStringToFOURCC	Converts a null-terminated string into a four-character code.
These functions work with the basic buffered and unbuffered file I/O services — you can open, read, and write RIFF files the same as other file types.


 About RIFF Files

The basic building block of a RIFF file is called a chunk. Each chunk consists of the following fields:

•	A four-character code specifying the chunk identifier

•	A doubleword specifying the size of the data field in the chunk

•	A data field

The only chunks allowed to contain other chunks (subchunks) are those with a chunk identifier of "RIFF" or "LIST". The first chunk in a RIFF file must be a "RIFF" chunk. All other chunks in the file are subchunks of the "RIFF" chunk.


 "RIFF" Chunks

"RIFF" chunks include an additional field in the first four bytes of the data field. This additional field provides the form type of the field. The form type is a four-character code identifying the format of the data stored in the file. For example, Microsoft waveform audio files (WAVE files) have a form type of "WAVE". The following illustration shows a "RIFF" chunk containing two subchunks.


 "LIST" Chunks

"LIST" chunks also include an additional field in the first four bytes of the data field. This additional field contains the list type of the field. The list type is a four-character code identifying the contents of the list. For example, a "LIST" chunk with a list type of "INFO" can contain "ICOP" and "ICRD" chunks providing copyright and creation date information. The following illustration shows a "RIFF" chunk containing a "LIST" chunk and one other subchunk (the "LIST" chunk contains two subchunks).


 Generating Four-Character Codes

A four-character code is a 32-bit quantity representing a sequence of one to four ASCII alphanumeric characters, padded on the right with blank characters. The data type for a four-character code is FOURCC. Use the mmioFOURCC function to convert four characters to a four-character code, as shown in the following example, which generates a four-character code for "WAVE":

FOURCC fourccID;

.ifdef REF

    .

    .

    .

.endif

fourccID = mmioFOURCC('W', 'A', 'V', 'E');

To convert a null-terminated string into a four-character code, use the mmioStringToFOURCC function, as shown in the following example, which also generates a four-character code for "WAVE":

FOURCC fourccID;

.ifdef REF

    .

    .

    .

.endif

fourccID = mmioStringToFOURCC("WAVE", 0);

The second parameter in mmioStringToFOURCC specifies options for converting the string to a four-character code. If you specify the MMIO_TOUPPER flag, mmioStringToFOURCC converts all alphabetic characters in the string to uppercase. This is useful when you need to specify a four-character code to identify a custom I/O procedure (four-character codes identifying file-extension names must be all uppercase).


 Creating RIFF Chunks

To create a new chunk, use the mmioCreateChunk function to write a chunk header at the current position in an open file.

The following example creates a new chunk with a chunk ID of "RIFF" and a form type of "RDIB".

HMMIO    hmmio;

MMCKINFO mmckinfo;

.ifdef REF

    .

    .

    .

.endif

mmckinfo.fccType = mmioFOURCC('R', 'D', 'I', 'B');

mmioCreateChunk(hmmio, &mmckinfo, MMIO_CREATERIFF);

If you're creating a "RIFF" or "LIST" chunk, you must specify the form type in the fccType field of the MMCKINFO structure. In the previous example, the form type is "RDIB".

If you know the size of the data field in a new chunk, you can set the cksize member in the MMCKINFO structure when you create the chunk. This value will be written to the data size field in the new chunk. If this value is not correct when you call the mmioAscend function to mark the end of the chunk, it will be rewritten automatically to reflect the correct size of the data field.

After you create a new chunk using mmioCreateChunk, the file position is set to the data field of the chunk (8 bytes from the beginning of the chunk). If the chunk is a "RIFF" or "LIST" chunk, the file position is set to the location following the form type or list type (12 bytes from the beginning of the chunk).


 Navigating RIFF Files

RIFF files consist of nested chunks of data. Multimedia file I/O services include two functions you can use to navigate between chunks in a RIFF file: mmioAscend and mmioDescend. You might think of these functions as high-level seek functions. When you descend into a chunk, the file position is set to the data field of the chunk (8 bytes from the beginning of the chunk). For "RIFF" and "LIST" chunks, the file position is set to the location following the form type or list type (12 bytes from the beginning of the chunk). When you ascend out of a chunk, the file position is set to the location following the end of the chunk.


 Descending Into a Chunk

The mmioDescend function descends into a chunk or searches for a chunk, beginning at the current file position.

The mmioDescend function fills an MMCKINFO structure with information on the chunk. This information includes the chunk identifier, the size of the data field, and the form type, or list type if the chunk is a "RIFF" or "LIST" chunk.


 Searching for a Chunk

To search for a chunk in an open RIFF file, specify the MMIO_FINDCHUNK flag in the wFlags parameter of mmioDescend. Set the ckid member of the MMCKINFO structure referenced by lpck to the four-character code of the chunk you want to search for.

If you are searching for a "RIFF" or "LIST" chunk, you don't need to set the ckid member of the MMCKINFO structure — mmioDescend sets this member for you. Set the fccType member to the four-character code of the form type or list type of the chunk.

The following example searches for a "RIFF" chunk with a form type of "WAVE" to verify that the file that has just been opened is a WAVE waveform audio file.

HMMIO    hmmio;

MMCKINFO mmckinfoParent;

MMCKINFO mmckinfoSubchunk;

.ifdef REF

    .

    .

    .

.endif

/*

 * Locate a "RIFF" chunk with a "WAVE" form type

 * to make sure the file is a WAVE file.

 */

mmckinfoParent.fccType = mmioFOURCC('W', 'A', 'V', 'E');

if (mmioDescend(hmmio, (LPMMCKINFO) &mmckinfoParent,

                NULL, MMIO_FINDRIFF))

        /* The file is not a WAVE file. */

    return FALSE;

else

        /* The file is a WAVE file. */

    return TRUE;

If the chunk you are searching for is a subchunk enclosed by a parent chunk (as are all chunks other than "RIFF" chunks), you should identify the parent chunk with the lpckParent parameter. In this case, mmioDescend will only search within the specified parent chunk.

The following example searches for the "fmt " chunk in the "RIFF" chunk descended into by the previous example.

/*

 * Find the format chunk (form type "fmt "); it should be

 * a subchunk of the "RIFF" parent chunk.

 */

mmckinfoSubchunk.ckid = mmioFOURCC('f', 'm', 't', ' ');

if (mmioDescend(hmmio, &mmckinfoSubchunk, &mmckinfoParent,

        MMIO_FINDCHUNK)) {

        /* Error, cannot find the "fmt " chunk. */

    return FALSE;

}

else {

        /* "fmt " chunk found. */

    return TRUE;

}

If you do not specify a parent chunk, the current file position should be at the beginning of a chunk before you call mmioDescend to search for a chunk. If you do specify a parent chunk, the current file position can be anywhere in the parent chunk.

If the search for a subchunk fails, the current file position is undefined. You can use the mmioSeek function and the dwDataOffset field of the MMCKINFO structure for the enclosing parent chunk to seek back to the beginning of the parent chunk, as in the following example:

mmioSeek(hmmio, mmckinfoParent.dwDataOffset + 4, SEEK_SET);

Since the dwDataOffset member specifies the offset to the beginning of the data portion of the chunk, you must seek four bytes past dwDataOffset to set the file position to be after the form type.


 Ascending Out of a Chunk

After you descend into a chunk and read the data in the chunk, you can move the file position to the beginning of the next chunk by ascending out of the chunk by using the mmioAscend function.

For example, the following statement ascends out of the "fmt " subchunk descended into by the previous example, illustrating searching for a subchunk:

/* Ascend out of the "fmt " subchunk.

 */

mmioAscend(hmmio, &mmckinfoSubchunk, 0);


 Example of RIFF File I/O

The following example shows how to open a RIFF file for buffered I/O, as well as how to descend, ascend, and read RIFF chunks.

/* ReversePlay--Plays a WAVE waveform audio file backwards. */

void ReversePlay(void)

{

    char        szFileName[128];           /* filename of file to open */

    HMMIO       hmmio;                    /* file handle for open file */

    MMCKINFO    mmckinfoParent;  /* parent chunk information structure */

    MMCKINFO    mmckinfoSubchunk; /* subchunk information structure    */

    DWORD       dwFmtSize;        /* size of "fmt" chunk               */

    DWORD       dwDataSize;       /* size of "data" chunk              */

    WAVEFORMAT  *pFormat;         /* pointer to memory for "fmt" chunk */

.ifdef REF

    ...

.endif

    /* Get the filename from the edit control. */

.ifdef REF

     ...

.endif

    /*

     * Open the given file for reading with buffered I/O

     * using the default internal buffer.

     */

    hmmio = mmioOpen(szFileName, NULL, MMIO_READ | MMIO_ALLOCBUF);

    if(hmmio == NULL){

        Error("Failed to open file.");

        return;

    }

    /*

     * Locate a "RIFF" chunk with a "WAVE" form type

     * to make sure the file is a WAVE file.

     */

    mmckinfoParent.fccType = mmioFOURCC('W', 'A', 'V', 'E');

    if (mmioDescend(hmmio, (LPMMCKINFO) &mmckinfoParent, NULL,

                    MMIO_FINDRIFF)) {

        Error("This is not a WAVE file.");

        mmioClose(hmmio, 0);

        return;

    }

    /*

     * Find the "fmt " chunk (form type "fmt "); it must be

     * a subchunk of the "RIFF" parent chunk.

     */

    mmckinfoSubchunk.ckid = mmioFOURCC('f', 'm', 't', ' ');

    if (mmioDescend(hmmio, &mmckinfoSubchunk, &mmckinfoParent,

                    MMIO_FINDCHUNK)) {

        Error("WAVE file has no \"fmt\" chunk");

        mmioClose(hmmio, 0);

        return;

    }

    /*

     * Get the size of the "fmt " chunk--allocate and lock memory for it.

     */

    dwFmtSize = mmckinfoSubchunk.cksize;

.ifdef REF

    ...

.endif

    /* Read the "fmt " chunk. */

    if (mmioRead(hmmio, (HPSTR) pFormat, dwFmtSize) != (LRESULT)dwFmtSize){

        Error("Failed to read format chunk.");

.ifdef REF

        ...

.endif

        mmioClose(hmmio, 0);

        return;

    }

    /* Ascend out of the "fmt " subchunk. */

    mmioAscend(hmmio, &mmckinfoSubchunk, 0);

    /*

     * Find the data subchunk. The current file position

     * should be at the beginning of the data chunk.

     */

    mmckinfoSubchunk.ckid = mmioFOURCC('d', 'a', 't', 'a');

    if (mmioDescend(hmmio, &mmckinfoSubchunk, &mmckinfoParent,

                    MMIO_FINDCHUNK)) {

        Error("WAVE file has no data chunk.");

.ifdef REF

        ...

.endif

        mmioClose(hmmio, 0);

        return;

    }

    /* Get the size of the data subchunk. */

    dwDataSize = mmckinfoSubchunk.cksize;

    if (dwDataSize == 0L) {

        Error("The data chunk contains no data.");

.ifdef REF

        ...

.endif

        mmioClose(hmmio, 0);

        return;

    }

    /* Open a waveform output device. */

.ifdef REF

    ...

.endif

    /* Allocate and lock memory for the waveform data. */

.ifdef REF

    ...

.endif

    /* Read the waveform data subchunk. */

    if(mmioRead(hmmio, (HPSTR) lpData,

            dwDataSize) != (LRESULT)dwDataSize) {

        Error("Failed to read data chunk.");

.ifdef REF

        ...

.endif

        mmioClose(hmmio, 0);

        return;

    }

    /* Close the file. */

    mmioClose(hmmio, 0);

    /* Reverse the sound and play it. */

.ifdef REF

    ...

.endif

}


 Directly Accessing a File Input/Output Buffer

Applications that are performance sensitive, such as applications that must stream data in real time from a CD-ROM, can optimize file I/O performance by accessing the file I/O buffer directly. Exercise care if you choose to do this — by accessing the file I/O buffer directly, you bypass some of the safeguards and error checking provided by the file I/O manager.

The multimedia file I/O services provide the following functions to support direct I/O buffer access.

Function	Description
mmioAdvance	Fills and/or flushes the I/O buffer of a file set up for direct I/O buffer access.
mmioGetInfo	Retrieves information on the file I/O buffer of a file opened for buffered I/O.
mmioSetInfo	Changes information on the file I/O buffer of a file opened for buffered I/O.
To access a file I/O buffer directly, open the file for buffered I/O as described in "Performing Buffered File I/O." You can use the internal file I/O buffer or supply your own buffer by using the mmioSetBuffer function.


 Getting Information on the File I/O Buffer

Use the mmioGetInfo function to get information on a file I/O buffer, such as the buffer size and address.


 Reading and Writing the File I/O Buffer

There are three members in the MMIOINFO structure used for reading and writing the file I/O buffer: pchNext, pchEndRead, and pchEndWrite. The pchNext field points to the next location in the buffer to read or write. You must increment pchNext as you read and write the buffer. The pchEndRead field identifies the last valid character you can read from the buffer. Likewise, pchEndWrite identifies the last location in the buffer you can write. To be precise, both pchEndRead and pchEndWrite point to the memory location following the last valid data in the buffer.


 Advancing the File I/O Buffer

When you reach the end of the file I/O buffer, you must advance the buffer to fill it from the disk (if you are reading), and flush it to the disk (if you are writing). Use the mmioAdvance function to advance a file I/O buffer.

The mmioAdvance function advances the buffer by (pchNext − cchBuffer) bytes. All data in the buffer before pchNext is assumed to have been read already, while all data from pchNext to pchEndRead will be considered unread. So, when mmioAdvance is called, all data before pchNext will be overwritten. The buffer must not be treated as an array and pchNext must be incremented until pchNext equals pchEndRead.

The following illustrations show how the file I/O buffer is advanced as a file is read or written.


 Using the mmioAdvance Function

To fill a file I/O buffer from disk, call mmioAdvance with the MMIO_READ flag. If there is not enough data remaining in the file to fill the buffer, the pchEndRead member in the MMIOINFO structure points to the location following the last valid byte in the buffer.

To flush a buffer to disk, first set the MMIO_DIRTY flag in the dwFlags member of the MMIOINFO structure. Then call mmioAdvance with the MMIO_WRITE flag.


 Example of Accessing a File I/O Buffer

The following example is based on the ReversePlay example function discussed earlier in this section. In this example, direct-buffer access is used to read waveform data from a file.

HMMIO    hmmio;

MMIOINFO mmioinfo;

DWORD    dwDataSize;

DWORD    dwCount;

HPSTR    hptr;

.ifdef REF

    .

    .

    .

.endif

/* Get information on the file I/O buffer. */

if (mmioGetInfo(hmmio, &mmioinfo, 0)) {

    Error("Failed to get I/O buffer info");

    mmioClose(hmmio, 0);

    return FALSE;

}

/*

 * Read the entire file by directly reading the file I/O buffer.

 * When the end of the I/O buffer is reached, advance the buffer.

 */

for (dwCount = dwDataSize, hptr = lpData; dwCount > 0; dwCount--) {

    /* Check to see if the I/O buffer must be advanced. */

    if (mmioinfo.pchNext == mmioinfo.pchEndRead) {

        if(mmioAdvance(hmmio, &mmioinfo, MMIO_READ)) {

            Error("Failed to advance buffer.");

            mmioClose(hmmio, 0);

            return FALSE;

        }

    }

    /* Get a character from the buffer. */

    *hptr++ = *mmioinfo.pchNext++;

}

/* End direct buffer access and close the file. */

mmioSetInfo(hmmio, &mmioinfo, 0);

mmioClose(hmmio, 0);


 Ending Direct Access of a File I/O Buffer

When you finish accessing a file I/O buffer, pass the MMIOINFO structure filled by the mmioGetInfo function to the mmioSetInfo function to stop direct-buffer access. If you wrote to the buffer, set the MMIO_DIRTY flag in the dwFlags member of the MMIOINFO structure before calling mmioSetInfo. Otherwise, the buffer will not be flushed to disk.


 Performing File Input/Output on Memory Files

The multimedia file I/O services let you to treat a block of memory as a file. This can be useful if you already have a file image in memory. Memory files let you reduce the number of special-case conditions in your code because, for I/O purposes, you can treat file memory images as if they were disk-based files. You can also use memory files with the Clipboard.


 Opening Memory Files

Like I/O buffers, memory files can use memory allocated by the application or by the file I/O manager. In addition, memory files can be either expandable or non-expandable. When the file I/O manager reaches the end of an expandable memory file, it expands the memory file by a predefined increment.

To open a memory file, use mmioOpen with the szFileName parameter set to NULL and the MMIO_READWRITE flag set in the dwOpenFlags parameter. Set the lpmmioinfo parameter to point to an MMIOINFO structure as follows:

•	Set the pIOProc member to NULL.

•	Set the fccIOProc member to FOURCC_MEM.

•	Set the pchBuffer member to point to the memory block. To request that the file I/O manager allocate the memory block, set pchBuffer to NULL.

•	Set the cchBuffer member to the initial size of the memory block.

•	Set the adwInfo[0] member to the minimum expansion size of the memory block. For a non-expandable memory file, set adwInfo[0] to NULL.

•	Set all other members to zero.


 Allocating Memory for Memory Files

There are no restrictions on allocating memory for use as a non-expandable memory file. You can use static memory or stack memory, or you can use locally allocated or globally allocated memory. For expandable memory files, you must use memory allocated using the GlobalAlloc function and locked using the GlobalLock function.


 Using Custom Input/Output Procedures

Multimedia file I/O services use I/O procedures to handle the physical input and output associated with reading and writing to different types of storage systems, such as file-archival systems and database-storage systems. There are predefined I/O procedures for standard Microsoft® Windows® files and for memory files. In the future, there will be a predefined I/O procedure for accessing elements of compound files. Compound files consist of a number of individual files, called file elements, bound together in one physical file.

You can supply a custom I/O procedure for accessing a unique storage system such as a database or file archive. This I/O procedure is private to your application.

The multimedia file I/O services provide the following functions to support custom I/O procedures:

Function	Description
mmioInstallIOProc	Installs, removes, or locates an I/O procedure.
mmioSendMessage	Sends a custom message to the I/O procedure associated with a file.
•	Opening a file using a custom I/O procedure

•	Writing an I/O procedure

•	Installing an I/O procedure


 Opening a File Using a Custom I/O Procedure

Before learning about how to write an I/O procedure, it's helpful to understand how to use one. To open a file using a custom I/O procedure, use the mmioOpen function as you would to open any other file. Use a plus sign (+) in the filename to separate the name of the physical file from the name of the element of the file you want to open. For example, the following statement opens a file element named "element" from a file named FILENAME.ARC:

mmioOpen("filename.arc+element", NULL, MMIO_READ);

When the file I/O manager encounters a plus sign in a filename, it looks at the preceding filename extension to determine which I/O procedure to associate with the file. In the previous example, the file I/O manager will attempt to use the I/O procedure associated with the .ARC filename extension. If no I/O procedure is installed, the mmioOpen function returns an error.


 Writing an I/O Procedure

An I/O procedure is a message-processing function supplied by an application. An I/O procedure function has the following syntax:

LRESULT IOProc(lpmmioinfo, wMsg, lParam1, lParam2)

The lpmmioinfo parameter specifies a pointer to an MMIOINFO structure associated with the file being accessed.

The wMsg parameter is of type UINT and specifies the message being sent by the file I/O manager to the I/O procedure.

The lParam1 parameter is of type LPARAM and specifies 32 bits of message-specific information.

The lParam2 parameter is of type LPARAM and specifies 32 bits of message-specific information.

The return value is message-specific. If the I/O procedure does not recognize a message, it should return zero.


 I/O Procedure Messages

I/O procedures must respond to the MMIOM_CLOSE, MMIOM_OPEN, MMIOM_READ, MMIOM_WRITE, MMIOM_SEEK, and MMIOM_WRITEFLUSH messages. Each of these messages has two parameters.

You can also create custom messages and send them to your I/O procedure using the mmioSendMessage function. If you define your own messages, be sure they are defined at or above the MMIOM_USER message. For example, the following example defines a message named MMIOM_MYMESSAGE:

#define   MMIOM_MYMESSAGE         MMIOM_USER + 0


 Using the MMIOINFO Structure

In addition to processing messages, an I/O procedure must maintain the lDiskOffset member in the MMIOINFO structure referenced by the lpmmioinfo parameter. The lDiskOffset member must always contain the file offset to the location that the next MMIOM_READ or MMIOM_WRITE message will access. The offset is specified in bytes and is relative to the beginning of the file. The I/O procedure can use the adwInfo[] member to maintain any required state information. The I/O procedure should not modify any other members in the MMIOINFO structure.


 Installing an I/O Procedure

Use mmioInstallIOProc to install, remove, or locate an I/O procedure.

For example, to install an I/O procedure associated with the filename extension ARC, use the following statement:

mmioInstallIOProc (mmioFOURCC('A', 'R', 'C', ' '),

                   (LPMMIOPROC)lpmmioproc, MMIO_INSTALLPROC);

Note  Be sure to remove any I/O procedures you've installed before closing your application.


 Installing an I/O Procedure Using MmioOpen

When you install an I/O procedure by using the mmioInstallIOProc function, the procedure remains installed until you remove it. The I/O procedure will be used for any file you open if the file has the appropriate filename extension. You can also temporarily install an I/O procedure by using the mmioOpen function. In this case, the I/O procedure is only used with a file opened by mmioOpen and is removed when the file is closed by using the mmioClose function.

To specify an I/O procedure when you open a file using mmioOpen, use the lpmmioinfo parameter to reference an MMIOINFO structure as follows:

•	Set the fccIOProc member to NULL.

•	Set the pIOProc member to the procedure-instance address of the I/O procedure.

•	Set all other members to zero (unless you are opening a memory file, or directly reading or writing to the file I/O buffer).


 File Input/Output Functions

Following are the functions used with file input/output.

mmioAdvance
mmioAscend
mmioClose
mmioCreateChunk
mmioDescend
mmioFlush
mmioFOURCC
mmioGetInfo
mmioInstallIOProc
mmioOpen
MMIOProc
mmioRead
mmioRename
mmioSeek
mmioSendMessage
mmioSetBuffer
mmioSetInfo
mmioStringToFOURCC
mmioWrite
mmsystemGetVersion


 Introduction to Multimedia Services

Microsoft® Windows® provides developers with high-level and low-level services for developing multimedia applications that use the extended capabilities of a multimedia personal computer.


 About Windows Multimedia Services

Windows provides the following multimedia services:

•	A Media Control Interface (MCI) for controlling media devices.

•	Extensible string-based and message-based interfaces for communicating with MCI device drivers.

•	MCI device drivers for playing and recording waveform audio, playing Musical Instrument Digital Interface (MIDI) files, and playing compact disc audio from a CD-ROM drive.

•	Low-level application programming interface (API) support for multimedia-related services.

•	Low-level support for playing and recording audio with waveform and MIDI audio devices.

•	Low-level support for precision timer services.

•	Multimedia file input and output (I/O) services that provide buffered and unbuffered file I/O and support for standard Resource Interchange File Format (RIFF) files. The services are extensible by means of custom I/O procedures.

•	A MIDI Mapper supporting standard MIDI patch services. This allows MIDI files to be authored independently of users' MIDI synthesizer setups.

•	Control Panel options that let users change display drivers, set up a screen saver, install multimedia device drivers, assign waveform sounds to system alerts, and configure the MIDI Mapper.

This overview covers the following topics:

•	The software architecture of the multimedia services

•	The design philosophy and implementation of the multimedia services

•	Basic information about developing applications that use the multimedia services


 Architecture of Windows Multimedia Services

Although the multimedia services are provided by a number of files, the overall architecture can be viewed as consisting of just three software modules:

•	The WINMM library, which provides the MCI services and low-level multimedia support functions

•	Multimedia device drivers, which provide communication between the low-level WINMM functions and multimedia devices, such as waveform, MIDI, and timer hardware

•	Drivers for MCI, which provide high-level control of media devices


 Windows Multimedia Design Philosophy

The architecture of the multimedia services is designed around the concepts of extensibility and device independence. Extensibility allows the software architecture to accommodate advances in technology easily, without changes to the architecture itself. Device independence makes it easy to develop multimedia applications that will run on a wide range of hardware providing different levels of multimedia support. Three design elements of the system software provide extensibility and device independence:

•	A translation layer (WINMM) that isolates applications from device drivers and centralizes device-independent code

•	Run-time linking that allows the translation layer to link to the drivers it needs

•	A well-defined and consistent driver interface that minimizes special-case code and makes the installation and upgrade process easier


 Building a Multimedia Application

Before writing a multimedia application, you should be familiar with programming in the Windows environment.

When using the multimedia services, you must include the MMSYSTEM.H header file in all source-code files that call multimedia functions. This header file depends on declarations made in the WINDOWS.H header file, so you must first include WINDOWS.H. The MMSYSTEM.H header file provides function prototypes as well as definitions of multimedia data types and constants.

In addition to linking the normal Windows libraries, you must also link to the WINMM.LIB import library when linking an application that uses multimedia functions.


 Multimedia Timer and Joystick Services

This overview shows you how to add joystick input capabilities to your application and how to control event timing.


 About Multimedia Timers

The joystick services can receive control signals from up to two joysticks. Timer services provide improved timer resolution and accuracy. Intel®-based systems have an accuracy of up to 16 milliseconds and MIPS®-based systems have an accuracy of up to 10 milliseconds.

The functions and data structures associated with the joystick and timer-interrupt services are defined in MMSYSTEM.H and WINMM.LIB.


 Timer Services

The multimedia timer services provided with the Microsoft® Win32® application programming interface (API) let applications schedule timed periodic or one-time asynchronous events. Unlike the timer services that post WM_TIMER messages to a message queue, the multimedia timer services call a callback function.


 Timer Data Types

The MMSYSTEM.H header file defines data types and function prototypes for timer functions. You must include this header file in any source-code module that uses timer services. MMSYSTEM.H defines the following new data types.

Type	Description
MMTIME	A structure for representing time in one of several formats.
TIMECAPS	A structure for querying timer capabilities.


 Using Timer Services

Timer services let an application request and receive timer messages at application-specified intervals. Real-time multimedia applications can use the following functions to control the pace of data and synchronized presentations.

Function	Description
timeBeginPeriod	Establishes the minimum timer resolution an application will use.
timeEndPeriod	Clears a minimum timer resolution previously set using timeBeginPeriod.
timeGetDevCaps	Returns information about the capabilities of the timer services.
timeGetTime	Returns the system time in milliseconds.
timeGetSystemTime	Fills an MMTIME structure with the system time in milliseconds.
timeSetEvent	Creates a timer event that executes a specific action at a specific time or at periodic intervals.
timeKillEvent	Cancels a timer event previously created using timeSetEvent.


 Getting the System Time

An application can get the current system time using the timeGetTime or timeGetSystemTime function. The system time is the count of milliseconds since the Microsoft® Windows® operating system was started. The timeGetTime function returns the system time, and the timeGetSystemTime function fills an MMTIME structure with the system time.


 Determining Maximum and Minimum Event Periods

You can use the timeGetDevCaps function to determine the minimum and maximum timer-event periods provided by the timer services. These values vary across computers and can vary depending on the mode in which Windows is running.


 Establishing Minimum Timer Resolution

Before starting timer events, your application must establish the minimum timer resolution that it intends to use. It must clear this value after finishing with the timer-event services.

Use the timeBeginPeriod and timeEndPeriod functions to set and clear the minimum timer-event resolution for your application. You must match a call to timeBeginPeriod with a corresponding call to timeEndPeriod, specifying the same minimum resolution in both calls. An application can make multiple timeBeginPeriod calls, as long as each call is matched with a call to timeEndPeriod.


 Starting Timer Events

To initialize and start timer events, use the timeSetEvent function. This function returns a timer identifier that can be used to stop or identify timer events.

The timeSetEvent function returns a timer identifier if successful or NULL if unsuccessful. Interrupt timers are a scarce resource, and periodic timers with resolution less than 100 milliseconds consume a significant portion of CPU time. For periodic timers, you must pair calls to timeSetEvent with calls to timeKillEvent. For more information, see Canceling a Timer Event.

The lpFunction parameter contains the address of the function to be called when the timer event takes place.

Since the callback function is accessed at interrupt time, it must adhere to strict programming guidelines. Timer-callback functions follow the same programming guidelines as callback functions for the low-level audio services. For information about writing low-level audio callback functions, see Low-Level Audio. For more information about timer callback functions, see TimeProc.


 Canceling a Multimedia Timer Event

You can cancel an active timer event at any time. Be sure to cancel any outstanding timers before freeing the module containing the callback function. To cancel a timer event, use the timeKillEvent function.


 Using Timer Callbacks

This topic describes how an application can use the timer services. First, the application calls the timeGetDevCaps function to determine the minimum and maximum resolution supported by the timer services. Before setting up any timer events, the application uses the timeBeginPeriod function to establish the minimum timer resolution it will use, as shown in the following example:

#define TARGET_RESOLUTION 1  /* Try for 1-millisecond accuracy. */

TIMECAPS tc;

UINT     wTimerRes;

if(timeGetDevCaps(&tc, sizeof(TIMECAPS)) != TIMERR_NOERROR) {

    /* Error; application can't continue. */

}

wTimerRes = min(max(tc.wPeriodMin, TARGET_RESOLUTION),

    tc.wPeriodMax);

timeBeginPeriod(wTimerRes);

To start the timer event, the application specifies the amount of time before the callback occurs, the required resolution, the address of the callback function, and user data to supply with the callback. The application can use a function like the following to start a one-time timer event.

UINT SetTimerCallback(NPSEQ npSeq,           /* Sequencer data */

                      UINT msInterval)       /* Event interval */

{

    npSeq->wTimerID = timeSetEvent(

         msInterval,           /* Delay                        */

         wTimerRes,            /* Resolution (global variable) */

         (LPTIMECALLBACK) OneShotTimer, /* Callback function   */

         (DWORD) npSeq,               /* User data             */

         TIME_ONESHOT);               /* Event type (one-time) */

    if (npSeq->wTimerID != 0)

        return TIMERR_NOCANDO;

    else

        return TIMERR_NOERROR;

}

The following callback function is used for the one-shot timer.

void PASCAL OneShotTimer(UINT wTimerID, UINT msg,

    DWORD dwUser, DWORD dw1, DWORD dw2)

{

    NPSEQ npSeq;            /* Pointer to sequencer data   */

    npSeq = (NPSEQ) dwUser;

    npSeq->wTimerID = 0;    /* Invalidate unused timer id  */

    TimerIntRoutine(npSeq); /* Handle interrupt-time tasks */

    UNREFERENCED_PARAMETER(dw1);

    UNREFERENCED_PARAMETER(dw2);

    UNREFERENCED_PARAMETER(msg);

    UNREFERENCED_PARAMETER(wTimerID);

}

Before freeing the dynamic-link library (DLL) that contains the callback function, the application cancels any outstanding timers. To cancel one timer event, it can call the following function.

void DestroyTimer(NPSEQ npSeq)

{

    if (npSeq->wTimerID) {      /* If timer event is pending */

        timeKillEvent(npSeq->wTimerID);  /* Cancel the event */

        npSeq->wTimerID = 0;

    }

}

Finally, to cancel the minimum timer resolution it established, the application calls timeEndPeriod as follows.

timeEndPeriod(wTimerRes);


 Joystick Services

The joystick is an input device that provides position information. It is an additional supported input device, not a replacement for the mouse. All absolute-position devices, including touch screens, digitizing tablets, and light pens, can use the joystick services to provide position and button information to applications.

The joystick services are loaded when Windows is started. The joystick services can monitor two joysticks, each with two- or three-axis movement, and up to four buttons. Applications access the joystick services through the set of functions described in this section.

Note  The driver for the IBM® Game Adapter supports two 2-axis joysticks or one 3-axis joystick.


 Joystick Data Types

The MMSYSTEM.H header file defines new data types and function prototypes for joystick functions. MMSYSTEM.H defines the following new data types.

Type	Description
JOYCAPS	A structure that contains joystick capability information.
JOYINFO	A structure that contains joystick position and button information.


 Using Joystick Services

Joystick services include functions to query each joystick for its capabilities, to poll each joystick for position and button information, and to receive messages in response to joystick events. Your application can use the following joystick functions to accept input from one or two joysticks.

Function	Description
joyGetNumDevs	Returns the number of joysticks supported by the joystick services.
joyGetDevCaps	Returns joystick capabilities.
joyGetPos	Returns joystick position and button information.
joySetCapture	Causes joystick input to be sent to a specified window at regular intervals or when the joystick state changes.
joyReleaseCapture	Releases the joystick captured using joySetCapture.
joyGetThreshold	Returns the movement threshold of a joystick.
joySetThreshold	Sets the movement threshold of a joystick.


 Determining Joystick Capabilities

The various joysticks in use today can support two or three axes and a variety of button configurations. Also, joysticks support different ranges of motion and polling frequencies. Joystick drivers can support either one or two joysticks. Two functions allow you to determine the capabilities of the joystick services and joystick devices installed on a system.


 Getting the Joystick Driver Capabilities

You can use the joyGetNumDevs function to determine the number of joystick devices supported by the joystick services. This function returns the number of joysticks, or zero if there is no joystick support. The value returned is not necessarily the number of joysticks attached to the system. To determine whether a joysticf supportek is attached, call the joyGetPos function for the device. The function returns JOYERR_UNPLUGGED if the specified device is disconnected.

The following example determines whether the joystick services are available and then determines if a joystick is attached to one of the ports:

JOYINFO joyinfo;

UINT wNumDevs, wDeviceID;

BOOL bDev1Attached, bDev2Attached;

    if((wNumDevs = joyGetNumDevs()) == 0)

        return ERR_NODRIVER;

    bDev1Attached =

            joyGetPos(JOYSTICKID1,&joyinfo) != JOYERR_UNPLUGGED;

    bDev2Attached =

            wNumDevs == 2 &&

            joyGetPos(JOYSTICKID2,&joyinfo) != JOYERR_UNPLUGGED;

    /* Decide which joystick to use */

    if(bDev1Attached || bDev2Attached)

        wDeviceID = bDev1Attached ? JOYSTICKID1 : JOYSTICKID2;

    else

        return ERR_NODEVICE;


 Getting the Joystick Capabilities

You can use the joyGetDevCaps function to obtain the specific capabilities of each joystick attached to a given system. This function fills a JOYCAPS structure with the range of each axis on the joystick, the number of buttons, and the maximum and minimum polling frequency.


 Methods for Checking Joystick Status

An application can receive information from the joystick in one of two ways:

•	By processing joystick messages from a captured joystick

•	By polling the joystick directly

The message-processing method can be simpler to use; your application is sent messages that indicate the position of the stick and the state of the buttons (pressed or released).


 Capturing Joystick Messages to a Window Function

You can capture joystick input to a window function; your application then receives joystick messages at specified intervals or when the user manipulates the joystick. The messages are described in the following topic.

Only one application can capture joystick messages from a given joystick. Capturing joystick messages does not, however, prevent your application (or other applications) from polling the joystick using joyGetPos. If joyGetPos is called while joystick input is captured, joystick events occurring close to the time of the joyGetPos call may not be accurately reported to the capture window.

The joySetCapture function captures joystick input to a window function you specify. To release the joystick, call the joyReleaseCapture function.

To capture messages from two joysticks attached to the system, you must call joySetCapture twice, once for each joystick. Your window then receives separate messages for each device.

You cannot capture an unplugged joystick. The joySetCapture function returns zero if successful; it returns JOYERR_UNPLUGGED if the specified device is unplugged.

Note  The joystick services set up a Windows timer event with each call to joySetCapture.

Set the period parameter for joySetCapture to a value that falls within the minimum and maximum resolution range for the joystick. To determine the minimum and maximum resolution of the joystick, call the joyGetDevCaps function, which fills the wPeriodMin and wPeriodMax members in the JOYCAPS structure.

If the specified period value is outside the range of valid resolution values for the joystick, the joystick services use the minimum or maximum resolution value, whichever is closer to the specified period.


 Processing Multimedia Timer Joystick Messages

The following joystick messages can be sent to a window function. Numerals 1 and 2 in these messages correspond to the joystick initiating the message. MM_JOY1 messages are sent to the window function if your application requests input from the first joystick, and MM_JOY2 messages are sent if your application requests input from the second joystick. All messages report nonexistent buttons as released.

Messages	Description
MM_JOY1MOVE, MM_JOY2MOVE	Report a change in the x-axis and/or y-axis position of the joystick. The wParam parameter contains a combination of JOY_BUTTON bit flags specifying which buttons were pressed. The low-order word of lParam contains the x-position of the joystick, and the high-order word contains the y-position.
MM_JOY1ZMOVE, MM_JOY2ZMOVE	Report a change in the z-axis position of a 3-axis joystick. The wParam parameter contains a combination of JOY_BUTTON bit flags specifying which buttons were pressed. The low-order word of lParam contains the x-position of the joystick, and the high-order word contains the y-position.
MM_JOY1BUTTONUP, MM_JOY2BUTTONUP, MM_JOY1BUTTONDOWN, MM_JOY2BUTTONDOWN	Report that a joystick button has been pressed or released. The wParam parameter contains one JOY_BUTTONCHG bit flag specifying which button changed state and a combination of JOY_BUTTON bit flags specifying the current button states. The low-order word of lParam contains the x-position of the joystick, and the high-order word contains the y-position.
The joystick services use the following bit flags, passed in the wParam parameter of the window function, to report the state of the joystick buttons.

Flag	Description
JOY_BUTTON1	Set when button 1 is pressed.
JOY_BUTTON1CHG	Set when button 1 has changed state.
JOY_BUTTON2	Set when button 2 is pressed.
JOY_BUTTON2CHG	Set when button 2 has changed state.
JOY_BUTTON3	Set when button 3 is pressed.
JOY_BUTTON3CHG	Set when button 3 has changed state.
JOY_BUTTON4	Set when button 4 is pressed.
JOY_BUTTON4CHG	Set when button 4 has changed state.
The MM_JOY*MOVE messages use the JOY_BUTTON flags to report the state (pressed or released) of all buttons on the specified joystick.

The MM_JOY*BUTTONUP and MM_JOY*BUTTONDOWN messages use the JOY_BUTTON flags to report the state (pressed or released) of all buttons on the specified joystick. Also, they use JOY_BUTTONCHG flags to indicate which button changed state, thereby generating the message.

For example, if the user presses and holds buttons 1 and 2 and then moves the stick, a window function may receive the following messages.

Message	wParam Flags
MM_JOY1BUTTONDOWN	JOY_BUTTON1 | JOY_BUTTON1CHG
MM_JOY1BUTTONDOWN	JOY_BUTTON1 | JOY_BUTTON2 | JOY_BUTTON2CHG
MM_JOY1MOVE	JOY_BUTTON1 | JOY_BUTTON2
A window function may receive the following messages when the user presses and releases button 3 without moving the stick.

Message	wParam Flags
MM_JOY1BUTTONDOWN	JOY_BUTTON3 | JOY_BUTTON3CHG
MM_JOY1BUTTONUP	JOY_BUTTON3CHG


 Releasing the Joystick

When your application no longer needs to receive periodic joystick messages, it should release the joystick by using the joyReleaseCapture function. If your application does not release the joystick before ending, the joystick is released shortly after the capture window is destroyed.


 Setting the Movement Threshold

You can change the movement threshold of the joystick by calling the joySetThreshold function. The movement threshold is the number of device units that the stick must be moved before an MM_JOY*MOVE message is sent to the window that has captured the device.


 Polling the Joystick

You can poll the joystick for position and button information. For example, an application may poll the joystick to get baseline position values; the Joystick Control Panel application uses this technique when calibrating the joystick. The joyGetPos function allows you to poll the joystick for position and button information.

Note  Calling joyGetPos while joystick input is captured can prevent the joystick services from accurately reporting joystick events to the capture window.


 Using Joystick Messages

The remainder of this topic presents examples from a simple joystick game that performs the useful function of shooting holes in the desktop: it gets position and button-state information from the joystick services and, when a user presses the joystick buttons, plays waveform resources and paints bullet holes on the screen.

Most of the joystick-control code is in the main window function. In the following WM_CREATE case of the message handler, the application captures input from joystick 1.

case WM_CREATE:

    if(joySetCapture(hWnd, JOYSTICKID1,  NULL, FALSE)) {

        MessageBeep(MB_ICONEXCLAMATION);

        MessageBox(hWnd, "Couldn't capture the joystick.", NULL,

                        MB_OK | MB_ICONEXCLAMATION);

        PostMessage(hWnd,WM_CLOSE,0,0L);

    }

    break;

In response to the MM_JOY1MOVE messages, the application changes the position of the cursor and, if either button is pressed, draws a hole in the desktop.

case MM_JOY1MOVE :

    if((UINT) wParam & (JOY_BUTTON1 | JOY_BUTTON2))

        DrawFire(hWnd);

    DrawSight(lParam);  /* Calculate new cursor position */

    break;

In response to the MM_JOY1BUTTONDOWN messages, the application uses sndPlaySound to play a waveform audio file.

case MM_JOY1BUTTONDOWN :

    if((UINT) wParam & JOY_BUTTON1) {

        sndPlaySound(lpButton1,

                     SND_LOOP | SND_ASYNC | SND_MEMORY);

        DrawFire(hWnd);

    }

    else if(wParam & JOY_BUTTON2) {

        sndPlaySound(lpButton2,

                     SND_ASYNC | SND_MEMORY |  SND_LOOP);

        DrawFire(hWnd);

    }

    break;

By specifying the SND_LOOP and SND_ASYNC flags with sndPlaySound, the JOYTOY application repeats the waveform playback until the button is released.

When a button is released, the window function receives a MM_JOY1BUTTONUP message, and handles it with the following statement.

case MM_JOY1BUTTONUP:

    sndPlaySound(NULL, 0);

    break;

This sequence stops the waveform-audio playback.


 Multimedia Timer and Joystick Functions

Following are the functions used with joystick services.

joyGetDevCaps
joyGetNumDevs
joyGetPos
joyGetThreshold
joyReleaseCapture
joySetCapture
joySetThreshold

Following are the functions used with timer services.

timeBeginPeriod
timeEndPeriod
timeGetDevCaps
timeGetSystemTime
timeGetTime
timeKillEvent
TimeProc
timeSetEvent


_hread
 _hread  QuickInfo  Overview  Group

The _hread function reads data from the specified file. This function is provided for compatibility with 16-bit versions of Windows. Win32-based applications should use the ReadFile function.

long _hread(

HFILE  hFile,	// handle of file
LPVOID  lpBuffer,	// address of buffer for read data
long  lBytes	// length, in bytes, of data buffer
);
Parameters

hFile

Identifies the specified file.

lpBuffer

Points to a buffer that contains the data read from the file.

lBytes

Specifies the number of bytes to be read from the file.

Return Value

The return value indicates the number of bytes actually read from the file. If the number of bytes read is less than lBytes, the function has reached the end of file (EOF) before reading the specified number of bytes.

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

See Also

_hwrite, ReadFile


_hwrite
 _hwrite  QuickInfo  Overview  Group

The _hwrite function writes data to the specified file. This function is provided for compatibility with 16-bit versions of Windows. Win32-based applications should use the WriteFile function.

long _hwrite(

HFILE  hFile,	// handle of file
LPCSTR  lpBuffer,	// address of buffer for data to be written
long  lBytes	// number of bytes to write
);
Parameters

hFile

Identifies the specified file.

lpBuffer

Points to a buffer that contains the data to be written to the file.

lBytes

Specifies the number of bytes to be written to the file.

Return Value

If the function succeeds, the return value indicates the number of bytes actually written to the file.

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

See Also

_hread, WriteFile


_lclose
 _lclose  QuickInfo  Overview  Group

The _lclose function closes the specified file so that it is no longer available for reading or writing. This function is provided for compatibility with 16-bit versions of Windows. Win32-based applications should use the CloseHandle function.

HFILE _lclose(

HFILE  hFile	// handle of file to close
);
Parameters

hFile

Identifies the file to be closed. This handle is returned by the function that created or last opened the file.

Return Value

If the function succeeds, the return value is zero.

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

See Also

CloseHandle, CreateFile, _lopen


_lcreat
 _lcreat  QuickInfo  Overview  Group

The _lcreat function creates or opens a specified file. This function is provided for compatibility with 16-bit versions of Windows. Win32-based applications should use the CreateFile function.

HFILE _lcreat(

LPCSTR  lpPathName,	// address of name of file to open
int  iAttribute	// file attribute
);
Parameters

lpPathName

Points to a null-terminated string that names the file to be opened. The string must consist of characters from the Windows ANSI character set.

iAttribute

Specifies the file attributes. This parameter must be one of the following values:

Value	Meaning
0	Normal (can be read from or written to without restriction).
1	Read only (cannot be opened for write)
2	Hidden (not found by directory search)
4	System (not found by directory search)
Return Value

If the function succeeds, the return value is a file handle.

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

Remarks

If the file does not exist, _lcreat creates a new file and opens it for writing. If the file exists, _lcreat truncates the file size to zero and opens it for reading and writing. When the function opens the file, the pointer is set to the beginning of the file.

The _lcreat function should be used carefully. It can open any file, even one already opened by another function.

See Also

CreateFile, _lopen


_llseek
 _llseek  QuickInfo  Overview  Group

The _llseek function repositions the file pointer in a previously opened file. This function is provided for compatibility with 16-bit versions of Windows. Win32-based applications should use the SetFilePointer function.

LONG _llseek(

HFILE  hFile,	// handle of file
LONG  lOffset,	// number of bytes to move
int  iOrigin	// position to move from
);
Parameters

hFile

Identifies the file.

lOffset

Specifies the number of bytes the file pointer is to be moved.

iOrigin

Specifies the starting position and direction of the file pointer. This parameter must be one of the following values:

Value	Meaning
FILE_BEGIN	Moves the file pointer lOffset bytes from the beginning of the file.
FILE_CURRENT	Moves the file pointer lOffset bytes from its current position.
FILE_END	Moves the file pointer lOffset bytes from the end of the file.
Return Value

If the function succeeds, the return value specifies the new offset of the pointer, in bytes, from the beginning of the file.

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

Remarks

When a file is initially opened, the file pointer is set to the beginning of the file. The _llseek function moves the pointer an arbitrary amount without reading data, which facilitates random access to the file's contents.

See Also

_lopen, SetFilePointer


_lopen
 _lopen  QuickInfo  Overview  Group

The _lopen function opens an existing file and sets the file pointer to the beginning of the file. This function is provided for compatibility with 16-bit versions of Windows. Win32-based applications should use the CreateFile function.

HFILE _lopen(

LPCSTR  lpPathName,	// address of name of file to open
int  iReadWrite	// file access mode
);
Parameters

lpPathName

Points to a null-terminated string that names the file to open. The string must consist of characters from the Windows ANSI character set.

iReadWrite

Specifies the modes in which to open the file. This parameter consists of one access mode and an optional share mode. The access mode must be one of the following values:

Value	Meaning
OF_READ	Opens the file for reading only.
OF_READWRITE	Opens the file for reading and writing.
OF_WRITE	Opens the file for writing only.
The share mode can be one of the following values:

Value	Meaning
OF_SHARE_COMPAT	Opens the file in compatibility mode, enabling any process on a given computer to open the file any number of times. If the file has been opened by using any of the other share modes, _lopen fails.
OF_SHARE_DENY_NONE	Opens the file without denying other processes read or write access to the file. If the file has been opened in compatibility mode by any other process, _lopen fails.
OF_SHARE_DENY_READ	Opens the file and denies other processes read access to the file. If the file has been opened in compatibility mode or for read access by any other process, _lopen fails.
OF_SHARE_DENY_WRITE	Opens the file and denies other processes write access to the file. If the file has been opened in compatibility mode or for write access by any other process, _lopen fails.
OF_SHARE_EXCLUSIVE	Opens the file in exclusive mode, denying other processes both read and write access to the file. If the file has been opened in any other mode for read or write access, even by the current process, _lopen fails.
Return Value

If the function succeeds, the return value is a file handle.

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

See Also

CreateFile


_lread
 _lread  QuickInfo  Overview  Group

The _lread function reads data from the specified file. This function is provided for compatibility with 16-bit versions of Windows. Win32-based applications should use the ReadFile function.

UINT _lread(

HFILE  hFile,	// handle of file
LPVOID  lpBuffer,	// address of buffer for read data
UINT  uBytes	// length, in bytes, of data buffer
);
Parameters

hFile

Identifies the specified file.

lpBuffer

Points to a buffer that contains the data read from the file.

uBytes

Specifies the number of bytes to be read from the file.

Return Value

The return value indicates the number of bytes actually read from the file. If the number of bytes read is less than uBytes, the function has reached the end of file (EOF) before reading the specified number of bytes.

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

See Also

_lwrite, ReadFile


_lwrite
 _lwrite  QuickInfo  Overview  Group

The _lwrite function writes data to the specified file. This function is provided for compatibility with 16-bit versions of Windows. Win32-based applications should use the WriteFile function.

UINT _lwrite(

HFILE  hFile,	// handle of file
LPCSTR  lpBuffer,	// address of buffer for data to be written
UINT  uBytes	// number of bytes to write
);
Parameters

hFile

Identifies the specified file.

lpBuffer

Points to a buffer that contains the data to write to the file.

uBytes

Specifies the number of bytes to be written to the file.

Return Value

If the function succeeds, the return value indicates the number of bytes actually written to the file.

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

See Also

_lread, WriteFile


AbnormalTermination
 AbnormalTermination  QuickInfo  Overview  Group

The AbnormalTermination function indicates whether the try block of a try-finally statement terminated normally. The function can be called only from within the finally block of a try-finally statement.

BOOL AbnormalTermination(VOID)

Parameters

This function has no parameters.

Return Value

If the try block of the try-finally statement terminated abnormally, the return value is TRUE; otherwise, it is FALSE.

Remarks

The try block terminates normally only if execution leaves the block sequentially after executing the last statement in the block. Statements (such as return, goto, continue, or break) that cause execution to leave the try block result in abnormal termination of the block. This is the case even if such a statement is the last statement in the try block.

Abnormal termination of a try block causes the system to search backward through all stack frames to determine whether any termination handlers must be called. This can result in the execution of hundreds of instructions, so it is important to avoid abnormal termination of a try block due to a return, goto, continue, or break statement. Note that these statements do not generate an exception, even though the termination is abnormal.


AbortDoc
 AbortDoc  QuickInfo  Overview  Group

The AbortDoc function stops the current print job and erases everything drawn since the last call to the StartDoc function. This function replaces the ABORTDOC printer escape.

int AbortDoc(

HDC  hdc	// handle of device context
);
Parameters

hdc

Identifies the device context for the print job.

Return Value

If the function succeeds, the return value is greater than zero.

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

Remarks

Applications should call the AbortDoc function to stop a print job if an error occurs, or to stop a print job after the user cancels that job. To end a successful print job, an application should call the EndDoc function.

If Windows Print Manager was used to start the print job, calling the AbortDoc function erases the entire spool job, so that the printer receives nothing. If Print Manager was not used to start the print job, the data may already have been sent to the printer. In this case, the printer driver resets the printer (when possible) and ends the print job.

See Also

EndDoc, SetAbortProc, StartDoc


AbortPath
 AbortPath  QuickInfo  Overview  Group

The AbortPath function closes and discards any paths in the specified device context.

BOOL AbortPath(

HDC  hdc	// handle of device context
);
Parameters

hdc

Identifies the device context from which a path will be discarded.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

If there is an open path bracket in the given device context, the path bracket is closed and the path is discarded. If there is a closed path in the device context, the path is discarded.

See Also

BeginPath, EndPath


AbortPrinter
 AbortPrinter  QuickInfo  Overview  Group

The AbortPrinter function deletes a printer's spool file if the printer is configured for spooling.

BOOL AbortPrinter(

HANDLE  hPrinter	// handle of printer object
);
Parameters

hPrinter

Identifies the printer from which the spool file is deleted.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

If the printer is not configured for spooling, AbortPrinter has no effect.

The printer handle identified by the hPrinter parameter is returned by the OpenPrinter function.

See Also

OpenPrinter


AbortProc
 AbortProc  QuickInfo  Overview  Group

The AbortProc function is an application-defined callback function that is called when a print job is to be canceled during spooling.

BOOL CALLBACK AbortProc(

HDC  hdc,	// handle of device context
int  iError	// error value
);
Parameters

hdc

Identifies the device context for the print job.

iError

Specifies whether an error has occurred. This parameter is zero if no error has occurred; it is SP_OUTOFDISK if Windows Print Manager is currently out of disk space and more disk space will become available if the application waits.

Return Value

The callback function should return TRUE to continue the print job or FALSE to cancel the print job.

Remarks

An application installs this callback function by calling the SetAbortProc function. AbortProc is a placeholder for the application-defined function name.

If the iError parameter is SP_OUTOFDISK, the application need not cancel the print job. If it does not cancel the job, it must yield to Print Manager by calling the PeekMessage or GetMessage function.

See Also

GetMessage, PeekMessage, SetAbortProc


AbortSystemShutdown
 AbortSystemShutdown  QuickInfo  Overview  Group

The AbortSystemShutdown function stops a system shutdown started by using the InitiateSystemShutdown function.

BOOL AbortSystemShutdown(

LPTSTR  lpMachineName	// address of name of computer to stop shutting down
);
Parameters

lpMachineName

Points to the null-terminated string that specifies the network name of the computer where the shutdown is to be stopped. If lpMachineName is NULL or points to an empty string, the function stops the shutdown on the local computer.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The InitiateSystemShutdown function displays a dialog box that notifies the user that the system is shutting down. During the InitiateSystemShutdown time-out period, the AbortSystemShutdown function can prevent the system from shutting down.

To stop the local computer from shutting down, the calling process must have the SE_SHUTDOWN_NAME privilege. To stop a remote computer from shutting down, the calling process must have the SE_REMOTE_SHUTDOWN_NAME privilege on the remote computer. By default, users can enable the SE_SHUTDOWN_NAME privilege on the computer they are logged onto, and administrators can enable the SE_REMOTE_SHUTDOWN_NAME privilege on remote computers.

Failures of this function are typically due to an invalid computer name, an inaccessible computer, or insufficient privilege.

See Also

InitiateSystemShutdown


accept
 accept  QuickInfo

The Windows Sockets accept function accepts a connection on a socket.

SOCKET accept (

SOCKET  s,
struct sockaddr FAR  * addr,
int FAR  * addrlen
);
Parameters

s

A descriptor identifying a socket that is in listen mode.

addr

An optional pointer to a buffer which receives the address of the connecting entity, as known to the communications layer. The exact format of the addr argument is determined by the address family established when the socket was created.

addrlen

An optional pointer to an integer which contains the length of the address addr.

Return Value

If no error occurs, accept returns a value of type SOCKET, which is a descriptor for the accepted packet. Otherwise, a value of INVALID_SOCKET is returned, and a specific error code may be retrieved by calling WSAGetLastError.

The integer referred to by addrlen initially contains the amount of space pointed to by addr. On return it will contain the actual length, in bytes, of the address returned.

Error Codes

WSANOTINITIALISED	A successful WSAStartup must occur before using this function.
WSAENETDOWN	The Windows Sockets implementation has detected that the network subsystem has failed.
WSAEFAULT	The addrlen argument is too small (less than the size of a sockets address structure).
WSAEINTR	The (blocking) call was canceled using WSACancelBlockingCall.
WSAEINPROGRESS	A blocking Windows Sockets call is in progress.
WSAEINVAL	The listen function was not invoked before accept.
WSAEMFILE	The queue is empty upon entry to accept and there are no descriptors available.
WSAENOBUFS	No buffer space is available.
WSAENOTSOCK	The descriptor is not a socket.
WSAEOPNOTSUPP	The referenced socket is not a type that supports connection-oriented service.
WSAEWOULDBLOCK	The socket is marked as nonblocking and no connections are present to be accepted.
Remarks

This function extracts the first connection on the queue of pending connections on s, creates a new socket with the same properties as s and returns a handle to the new socket. If no pending connections are present on the queue, and the socket is not marked as nonblocking, accept blocks the caller until a connection is present. If the socket is marked nonblocking and no pending connections are present on the queue, accept returns an error as described following. The accepted socket may not be used to accept more connections. The original socket remains open.

The argument addr is a result parameter that is filled in with the address of the connecting entity, as known to the communications layer. The exact format of the addr parameter is determined by the address family in which the communication is occurring. The addrlen is a value-result parameter; it should initially contain the amount of space pointed to by addr; on return it will contain the actual length (in bytes) of the address returned. This call is used with connection-based socket types such as SOCK_STREAM. If addr and/or addrlen are equal to NULL, then no information about the remote address of the accepted socket is returned.

See Also

bind, connect, listen, select, socket, WSAAsyncSelect, WSACancelBlockingCall, WSAStartup


AccessCheck
 AccessCheck  QuickInfo  Overview  Group

The AccessCheck function is used by a server application to check a client's access to an object against the access control associated with the object.

BOOL AccessCheck(

PSECURITY_DESCRIPTOR  pSecurityDescriptor,	// address of security descriptor
HANDLE  ClientToken,	// handle of client access token
DWORD  DesiredAccess,	// access mask to request
PGENERIC_MAPPING  GenericMapping,	// address of generic-mapping structure
PPRIVILEGE_SET  PrivilegeSet,	// address of privilege-set structure
LPDWORD  PrivilegeSetLength,	// size of privilege-set structure
LPDWORD  GrantedAccess,	// address of granted access mask
LPBOOL  AccessStatus	// address of flag indicating whether access granted
);
Parameters

pSecurityDescriptor

Points to a SECURITY_DESCRIPTOR structure against which access is checked.

ClientToken

Identifies an access token representing a client attempting to gain access.

This handle must be obtained from a communications session layer — for instance, a named pipe — to prevent possible security policy violations.

DesiredAccess

Specifies the access mask to be requested. This mask must have been mapped by the MapGenericMask function to contain no generic access rights.

GenericMapping

Points to the GENERIC_MAPPING structure associated with the object for which access is being checked.

PrivilegeSet

Points to a PRIVILEGE_SET structure that the function fills with any privileges used to perform the access validation. If no privileges were used, the buffer contains a privilege set consisting of zero privileges.

PrivilegeSetLength

Specifies the size, in bytes, of the buffer pointed to by the PrivilegeSet parameter.

GrantedAccess

Points to a variable the function fills with an access mask indicating which access rights were granted. If the function fails, this access mask is not supplied.

AccessStatus

Points to a flag indicating the success or failure of the access check. If AccessStatus is TRUE, the access token has the requested access to the object. If AccessStatus is FALSE, the access token does not have the requested access. When this parameter is FALSE, the application can use the GetLastError function to get extended error information.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The AccessCheck function compares the specified security descriptor with the specified access token and indicates, in the AccessStatus parameter, whether access is granted or denied. If access is granted, the requested access mask becomes the object's granted access mask.

Only the discretionary access-control list is examined during an access check.

See Also

AccessCheckAndAuditAlarm, AreAllAccessesGranted, AreAnyAccessesGranted, GENERIC_MAPPING, MapGenericMask, PrivilegeCheck, PRIVILEGE_SET, SECURITY_DESCRIPTOR


AccessCheckAndAuditAlarm
 AccessCheckAndAuditAlarm  QuickInfo  Overview  Group

The AccessCheckAndAuditAlarm function performs an access validation and generates corresponding audit messages. An application can also use this function to determine whether necessary privileges are held by a client process. This function is generally used by a server application impersonating a client process. Alarms are not supported in the current version of Windows NT.

BOOL AccessCheckAndAuditAlarm(

LPCTSTR  SubsystemName,	// address of string for subsystem name
LPVOID  HandleId,	// address of handle identifier
LPTSTR  ObjectTypeName,	// address of string for object type
LPTSTR  ObjectName,	// address of string for object name
PSECURITY_DESCRIPTOR  SecurityDescriptor,	// address of security descriptor
DWORD  DesiredAccess,	// mask for requested access rights
PGENERIC_MAPPING  GenericMapping,	// address of GENERIC_MAPPING
BOOL  ObjectCreation,	// object-creation flag
LPDWORD  GrantedAccess,	// address of mask for granted rights
LPBOOL  AccessStatus,	// address of flag for results
LPBOOL  pfGenerateOnClose	// address of flag for audit generation
);
Parameters

SubsystemName

Points to a null-terminated string specifying the name of the subsystem calling the function — for example, "DEBUG" or "WIN32."

HandleId

Points to a unique 32-bit value representing the client's handle of the object. If the access is denied, this value is ignored and may be reused.

ObjectTypeName

Points to a null-terminated string specifying the type of object being created or accessed. This string appears in the audit log for the object.

ObjectName

Points to a null-terminated string specifying the name of the object being created or accessed. This string appears in the audit log for the object.

SecurityDescriptor

Points to the SECURITY_DESCRIPTOR structure against which access is checked.

DesiredAccess

Specifies an access mask giving the requested access rights. This mask must have been mapped to contain no generic access rights by the MapGenericMask function.

GenericMapping

Points to the GENERIC_MAPPING structure associated with the type of object being examined.

ObjectCreation

Specifies a flag that determines whether the calling application will create a new object when access is granted. If this flag is TRUE, the application creates a new object; if it is FALSE, the application opens an existing object.

GrantedAccess

Points to a buffer that receives an access mask indicating which access rights were granted, if the function succeeds.

AccessStatus

Points to a flag that the function sets to indicate the success or failure of the access check. If access is granted, this flag is TRUE; otherwise, it is FALSE.

pfGenerateOnClose

Points to a flag set by the audit-generation routine when the function returns. This flag must be passed to the ObjectCloseAuditAlarm function when the object handle is closed.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The AccessCheckAndAuditAlarm function compares the specified security descriptor with the impersonation access token of the calling process and indicates whether access is granted or denied. If access is granted, the requested access mask becomes the granted access mask for the object. This function also generates any necessary audit messages as a result of the access attempt.

This function requires the calling process to have the SE_AUDIT_NAME privilege. The test for this privilege is performed against the primary token of the calling process, not the impersonation token of the thread.

See Also

AccessCheck, AreAllAccessesGranted, AreAnyAccessesGranted, GENERIC_MAPPING, MapGenericMask, ObjectCloseAuditAlarm, ObjectOpenAuditAlarm, ObjectPrivilegeAuditAlarm, PrivilegeCheck, PrivilegedServiceAuditAlarm, SECURITY_DESCRIPTOR


 AccessResource

The AccessResource function is not implemented in the Win32 API. Win32-based applications should use the LoadResource, LockResource, and FindResource functions.


AcsLan
 AcsLan  QuickInfo

The AcsLan function is used to communicate with other computers or network peripheral devices, such as printers, using the data link control (DLC) protocol. The caller submits requests by filling in a command control block (CCB) and then calling AcsLan.

Commands submitted through AcsLan can complete synchronously or asynchronously. The DLC driver, not the caller, determines how a command completes. This is unlike the Netbios function, for example, which has commands complete synchronously or asynchronously as requested by the caller.

There are some differences between NT DLC and the CCB2 interface. The most notable difference is that the buffer pool must be specified on an open adapter instance basis and not specified per-SAP (service-access point). After an adapter has been opened using the DIR.OPEN.ADAPTER command, a buffer pool must be given to the DLC driver using BUFFER.CREATE.

ACSLAN_STATUS AcsLan(

PLLC_CCB  pCcb,	// address of command control block
PLLC_CCB * ppBadCcb	// address of pointer for invalid CCB
);
Parameters

pCcb

Points to an LLC_CCB structure describing the function being performed. For information about this structure, see documentation for IBM LAN.

ppBadCcb

Points to a pointer to an LLC_CCB structure. This parameter is used when a chain of LLC_CCB structures is submitted. If the parameter is not NULL on input, this pointer will contain a pointer to the first invalid LLC_CCB structure discovered in the chain.

Return Value

The function returns an ACSLAN_STATUS value. ACSLAN_STATUS is an enumerated type. The following values are defined:

Value	Meaning
ACSLAN_STATUS_COMMAND_ACCEPTED	The request has been processed and passed to the DLC driver. The command may or may not have already completed, depending on whether it is a synchronous or asynchronous command and depending on other timing considerations. This value does not mean that the command completed successfully. The caller must check the uchDlcStatus member in the LLC_CCB structure to determine whether the request succeeded or failed.
ACSLAN_STATUS_INVALID_CCB_POINTER	A pointer in the the LLC_CCB structure, or the parameter table is invalid.
ACSLAN_STATUS_CCB_IN_ERROR	A problem was detected with the LLC_CCB structure. The caller should check the values in the structure and resubmit it.
ACSLAN_STATUS_CHAINED_CCB_IN_ERROR	A problem was detected with an LLC_CCB structure in a chain of LLC_CCB structures.
ACSLAN_STATUS_SYSTEM_ERROR	This value is not used.
ACSLAN_STATUS_SYSTEM_STATUS	This value is not used.
ACSLAN_STATUS_INVALID_COMMAND	The command in the uchDlcCommand member of the LLC_CCB structure is unrecognized.
See Also

Netbios


ActivateKeyboardLayout
 ActivateKeyboardLayout  QuickInfo  Overview  Group

The implementations of ActivateKeyboardLayout in Windows 95 and Windows NT are substantially different. To accommodate these differences, this reference page first presents the Windows 95 implementation in its entirety, followed by the Windows NT version.

Windows 95:

The ActivateKeyboardLayout function sets the input language for the current thread. This function accepts a keyboard layout handle that identifies a locale as well as the physical layout of the keyboard.

HKL ActivateKeyboardLayout(

HKL  hkl,	// handle of keyboard layout
UINT  Flags	// keyboard layout flags
);
Parameters

hkl

Handle of a keyboard layout or a zero-extended locale identifier. This parameter can be any valid keyboard layout handle obtained using the LoadKeyboardLayout or GetKeyboardLayoutList function or one of the following values:

Value	Meaning
HKL_NEXT	Selects the next layout in the keyboard layouts list maintained by the system.
HKL_PREV	Selects the previous layout in the keyboards layout list maintained by the system.
Flags

Specifies the keyboard layout flags. The value of this parameter can be:

Value	Meaning
KLF_REORDER	Reorders the keyboard layouts list by moving the given keyboard layout handle to the head of the list. If this value is not given, the list is rotated without a change of order. For example, if a user had an English layout active, as well as having French, German and Spanish layouts loaded (in that order), then activating the German layout with the KLF_REORDER bit set would produce the following order: German, English, French, Spanish. Activating the German layout without the KLF_REORDER value set would produce the following order: German, Spanish, English, French.
Return Value

If the function succeeds, the return value is the previous keyboard layout handle. Otherwise, it is zero. To get extended error information, use the GetLastError function.

Remarks

Several keyboard layouts can be loaded at any one time, but only one is active at a time. Loading multiple keyboard layouts makes it possible to rapidly switch between layouts.

An application can create a valid keyboard layout handle by setting the high word to zero and the low word to a locale identifier. Using such keyboard layout handles changes the input language without affecting the physical layout.

When multiple input method editors (IMEs) are allowed for each locale, passing in a keyboard layout handle in which the high word (the device handle) is zero activates the first IME in the list "belonging" to the locale.

See Also

LoadKeyboardLayout, GetKeyboardLayoutName, UnloadKeyboardLayout

Windows NT:

The ActivateKeyboardLayout function activates a different keyboard layout and sets the active keyboard layout for the entire system rather than the calling thread.

BOOL ActivateKeyboardLayout(

HKL  hkl,	// handle of keyboard layout
UINT  Flags	// keyboard layout flags
);
Parameters

hkl

Identifies the keyboard layout to be activated. The layout must have been loaded by a previous call to the LoadKeyboardLayout function. This parameter must be either the handle of a keyboard layout or one of the following values:

Value	Meaning
HKL_NEXT	Selects the next layout in the circular list of loaded layouts maintained by the system.
HKL_PREV	Selects the previous layout in the circular list of loaded layouts maintained by the system.
Flags

Specifies how the keyboard layout is to be activated. This parameter can be one of the following values:

Value	Meaning
KLF_REORDER	If this bit is set, the system's circular list of loaded keyboard layouts is reordered. If this bit is not set, the list is rotated without a change of order. For example, if a user had an English layout active, as well as having French, German and Spanish layouts loaded (in that order), then activating the German layout with the KLF_REORDER bit set would produce the following order: German, English, French, Spanish. Activating the German layout without the KLF_REORDER bit set would produce the following order: German, Spanish, English, French. If less than three keyboard layouts are loaded, the value of this flag is irrelevant.
KLF_UNLOADPREVIOUS	The previously active layout is unloaded.
Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

Several keyboard layouts can be loaded at any one time, but only one is active at a time. Loading multiple keyboard layouts makes it possible to rapidly switch between layouts.

See Also

LoadKeyboardLayout, GetKeyboardLayoutName, UnloadKeyboardLayout


AddAccessAllowedAce
 AddAccessAllowedAce  QuickInfo  Overview  Group

The AddAccessAllowedAce function adds an access-allowed ACE to an ACL. The access is granted to a specified SID.

An ACE is an access-control entry. An ACL is an access-control list. A SID is a security identifier.

BOOL AddAccessAllowedAce(

PACL  pAcl,	// address of access-control list
DWORD  dwAceRevision,	// ACL revision level
DWORD  AccessMask,	// access mask
PSID  pSid	// address of security identifier
);
Parameters

pAcl

Points to an ACL structure. This function adds an access-allowed ACE to this ACL. The ACE is in the form of an ACCESS_ALLOWED_ACE structure.

dwAceRevision

Specifies the revision level of the ACL being modified. Currently, this value must be ACL_REVISION.

AccessMask

Specifies the mask of access rights to be granted to the specified SID.

pSid

Points to the SID structure representing a process being granted access.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The addition of an access-allowed ACE to an ACL is the most common form of ACL modification.

The ACE_HEADER structure placed in the ACE by this function specifies a type and size, but provides no inheritance and no ACE flags.

See Also

ACCESS_ALLOWED_ACE, ACE_HEADER, ACL, AddAccessDeniedAce, AddAce, AddAuditAccessAce, DeleteAce, GetAce


AddAccessDeniedAce
 AddAccessDeniedAce  QuickInfo  Overview  Group

The AddAccessDeniedAce function adds an access-denied ACE to an ACL. The access is denied to a specified SID.

An ACE is an access-control entry. An ACL is an access-control list. A SID is a security identifier.

BOOL AddAccessDeniedAce(

PACL  pAcl,	// address of access-control list
DWORD  dwAceRevision,	// ACL revision level
DWORD  AccessMask,	// access mask
PSID  pSid	// address of security identifier
);
Parameters

pAcl

Points to an ACL structure. This function adds an access-denied ACE to this ACL. The ACE is in the form of an ACCESS_DENIED_ACE structure.

dwAceRevision

Specifies the revision level of the ACL being modified. Currently, this value must be ACL_REVISION.

AccessMask

Specifies the mask of access rights being denied to the specified SID.

pSid

Points to the SID structure representing the process being denied access.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The ACE_HEADER structure placed in the ACE by this function specifies a type and size, but provides no ACE flags.

See Also

ACCESS_DENIED_ACE, ACE_HEADER, ACL, AddAccessAllowedAce, AddAce, AddAuditAccessAce, DeleteAce, GetAce


AddAce
 AddAce  QuickInfo  Overview  Group

The AddAce function adds one or more ACEs to a specified ACL.

An ACE is an access-control entry. An ACL is an access-control list.

BOOL AddAce(

PACL  pAcl,	// address of access-control list
DWORD  dwAceRevision,	// ACL revision level
DWORD  dwStartingAceIndex,	// index of ACE position in ACL
LPVOID  pAceList,	// address of one or more ACEs
DWORD  nAceListLength	// size of buffer for ACEs
);
Parameters

pAcl

Points to an ACL structure. This function adds an ACE to this ACL.

dwAceRevision

Specifies the revision level of the ACL being modified. Currently, this value must be ACL_REVISION.

dwStartingAceIndex

Specifies the position in the ACL's list of ACEs at which to add new ACEs. A value of zero inserts the ACEs at the beginning of the list. A value of MAXDWORD appends the ACEs to the end of the list.

pAceList

Points to a list of one or more ACEs to be added to the specified ACL. The ACEs in the list must be stored contiguously.

nAceListLength

Specifies the size, in bytes, of the input buffer pointed to by the pAceList parameter.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

Applications frequently use the FindFirstFreeAce and GetAce functions when using the AddAce function to manipulate an ACL. In addition, the ACL_SIZE_INFORMATION structure retrieved by the GetAclInformation function contains the size of the ACL and the number of ACEs it contains.

See Also

ACL, ACL_SIZE_INFORMATION, AddAccessAllowedAce, AddAccessDeniedAce, AddAuditAccessAce, DeleteAce, FindFirstFreeAce, GetAce, GetAclInformation


AddAtom
 AddAtom  QuickInfo  Overview  Group

The AddAtom function adds a character string to the local atom table and returns a unique value (an atom) identifying the string.

ATOM AddAtom(

LPCTSTR  lpString	// address of string to add
);
Parameters

lpString

Points to the null-terminated string to be added. The string can have a maximum size of 255 bytes. Strings differing only in case are considered identical. The case of the first string added is preserved and returned by the GetAtomName function.

Return Value

If the function succeeds, the return value is the newly created atom.

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

Remarks

The AddAtom function stores no more than one copy of a given string in the atom table. If the string is already in the table, the function returns the existing atom and, in the case of a string atom, increments the string's reference count.

The MAKEINTATOM macro can be used to convert a WORD value into a string that can be added to the atom table by using the AddAtom function.

AddAtom returns a string atom whose value is in the range 0xC000 through 0xFFFF.

If lpString has the form "#1234", AddAtom returns an integer atom whose value is the 16-bit representation of the decimal number specified in the string (0x04D2, in this example). If the decimal value specified is 0x0000 or a value in the range 0xC000 through 0xFFFF, the return value is zero, indicating an error. If lpString is in the range 0x0001 through 0xBFFF, the return value is the low-order word of lpString.

See Also

DeleteAtom, FindAtom, GetAtomName, GlobalAddAtom, GlobalDeleteAtom, GlobalFindAtom, GlobalGetAtomName, MAKEINTATOM


AddAuditAccessAce
 AddAuditAccessAce  QuickInfo  Overview  Group

The AddAuditAccessAce function adds a system-audit ACE to a system ACL. The access of a specified SID is audited.

An ACE is an access-control entry. An ACL is an access-control list. A SID is a security identifier.

BOOL AddAuditAccessAce(

PACL  pAcl,	// address of access-control list
DWORD  dwAceRevision,	// ACL revision level
DWORD  dwAccessMask,	// access mask
PSID  pSid,	// address of security identifier
BOOL  bAuditSuccess,	// flag for auditing successful access
BOOL  bAuditFailure	// flag for auditing unsuccessful access attempts
);
Parameters

pAcl

Points to an ACL structure. This function adds a system-audit ACE to this ACL. The ACE is in the form of an SYSTEM_AUDIT_ACE structure.

dwAceRevision

Specifies the revision level of the ACL being modified. Currently, this value must be ACL_REVISION.

dwAccessMask

Specifies the mask of access rights to be audited for the specified SID.

pSid

Points to the SID structure representing the process whose access is being audited.

bAuditSuccess

Specifies whether successful access attempts are to be audited. Set this flag to TRUE to enable auditing; otherwise, set it to FALSE.

bAuditFailure

Specifies whether unsuccessful access attempts are to be audited. Set this flag to TRUE to enable auditing; otherwise, set it to FALSE.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The ACE_HEADER structure placed in the ACE by this function specifies a type and size, but provides no ACE flags.

See Also

ACE_HEADER, ACL, AddAccessAllowedAce, AddAccessDeniedAce, AddAce, DeleteAce, GetAce, SID, SYSTEM_AUDIT_ACE


AddFontResource
 AddFontResource  QuickInfo  Overview  Group

The AddFontResource function adds the font resource from the specified file to the Windows font table. The font can subsequently be used for text output by any Windows-based application.

int AddFontResource(

LPCTSTR  lpszFilename	// address of font-resource filename
);
Parameters

lpszFilename

Points to a null-terminated character string that contains a valid font file filename. The filename may specify either a .FON font resource file, a .FNT raw bitmap font file, a .TTF raw TrueType file, or a .FOT TrueType resource file.

Return Value

If the function succeeds, the return value specifies the number of fonts added.

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

Remarks

Any application that adds or removes fonts from the Windows font table should notify other windows of the change by sending a WM_FONTCHANGE message to all top-level windows in the operating system. The application should send this message by calling the SendMessage function and setting the hwnd parameter to HWND_BROADCAST.

When an application no longer needs a font resource that it loaded by calling the AddFontResource function, it must remove the resource by calling the RemoveFontResource function.

See Also

RemoveFontResource, SendMessage


AddForm [New - Windows NT]
 AddForm  QuickInfo  Overview  Group

[New - Windows NT]

The AddForm function adds a form to the list of available forms that can be selected for the specified printer.

BOOL AddForm(

HANDLE  hPrinter,	// handle of printer object
DWORD  Level,	// data-structure level
LPBYTE  pForm	// address of form info. data structure
);
Parameters

hPrinter

Identifies the printer that supports printing with the specified form.

Level

Specifies the level of the structure to which pForm points. This value must be 1.

pForm

Points to a FORM_INFO_1 structure.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The printer handle identified by the hPrinter parameter is returned by the OpenPrinter function.

An application can determine which forms are available for a printer by calling the EnumForms function.

See Also

EnumForms, FORM_INFO_1, OpenPrinter


AddJob
 AddJob  QuickInfo  Overview  Group

The AddJob function obtains a path string that specifies a file that you can use to store a spooled print job.

BOOL AddJob(

HANDLE  hPrinter,	// specifies printer for the print job
DWORD  Level,	// specifies version of print job information data structure
LPBYTE  pData,	// points to buffer to receive print job information data
DWORD  cbBuf,	// specifies size of buffer pointed to by pData
LPDWORD  pcbNeeded	// points to variable to receive size of print job information data
);
Parameters

hPrinter

Handle that specifies the printer for the print job. This must be a local printer that is configured as a spooled printer. If hPrinter is a handle to a remote printer connection, or if the printer is configured for direct printing, the AddJob function fails.

Level

Specifies the version of the print job information data structure that the function stores into the buffer pointed to by pData. Set this parameter to one.

pData

Points to a buffer to receive an ADDJOB_INFO_1 data structure and a path string.

cbBuf

Specifies the size, in bytes, of the buffer pointed to by pData. The buffer needs to be large enough to contain an ADDJOB_INFO_1 structure and a path string.

pcbNeeded

Points to a variable to receive the total size, in bytes, of the ADDJOB_INFO_1 data structure plus the path string. If this value is less than or equal to cbBuf and the function succeeds, this is the actual number of bytes written to the buffer pointed to by pData. If this number is greater than cbBuf, the buffer is too small, and you must call the function again with a buffer size at least as large as *pcbNeeded.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

You can call the CreateFile function to open the spool file specified by the Path member of the ADDJOB_INFO_1 structure, and then call the WriteFile function to write print job data to it. Once that is done, call ScheduleJob to notify the print spooler that the print job can now be scheduled by the spooler for printing.

See Also

ADDJOB_INFO_1, CreateFile, OpenPrinter, ScheduleJob, WriteFile


AddMonitor
 AddMonitor  QuickInfo  Overview  Group

The AddMonitor function installs a local printer monitor and links the configuration, data, and monitor files. Future releases of Windows NT may allow remote installation of printer monitors.

BOOL AddMonitor (

LPTSTR  pName,	// address of server name
DWORD  Level,	// monitor info. structure level
LPBYTE  pMonitors	// address of monitor info structure
);
Parameters

pName

Points to a null-terminated string that specifies the name of the server on which the monitor should be installed. For this release of Windows NT,  monitors may only be installed locally, so this string should be NULL.

Level

Specifies the version of the structure to which pMonitors points. This value must be 2.

pMonitors

Points to a MONITOR_INFO_2 structure.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

Before an application calls AddMonitor, all files required by the monitor must be copied to the SYSTEM32 directory.

An application can determine which printer monitors are currently installed by calling the EnumMonitors function.

A monitor added by AddMonitor may be removed by calling DeleteMonitor.

See Also

DeleteMonitor, EnumMonitors, MONITOR_INFO_2


AddPort
 AddPort  QuickInfo  Overview  Group

The AddPort function adds the name of a port to the list of supported ports.

BOOL AddPort(

LPTSTR  pName,	// address of a server name
HWND  hWnd,	// handle of parent window
LPTSTR  pMonitorName	// address of a monitor name
);
Parameters

pName

Points to a null-terminated string that specifies the name of the server to which the port is connected. If this string is NULL, the port is local.

hWnd

Identifies the parent window of the AddPort dialog box.

pMonitorName

Points to a null-terminated string that specifies the monitor associated with the port.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The monitor name specified in pMonitorName can be retrieved by calling the EnumMonitors function.

An application can determine which ports are currently supported by calling the EnumPorts function.

See Also

EnumMonitors, EnumPorts


AddPrinter
 AddPrinter  QuickInfo  Overview  Group

The AddPrinter function adds a printer to the list of supported printers for a specified server.

HANDLE AddPrinter(

LPTSTR  pName,	// address of server name
DWORD  Level,	// printer info. structure level
LPBYTE  pPrinter	// address of structure
);
Parameters

pName

Points to a null-terminated string that specifies the name of the server on which the printer's print processor should be installed. If this string is NULL, the print processor is installed locally.

Level

Specifies the version of the structure to which pPrinter points. This value must be 2.

pPrinter

Points to a PRINTER_INFO_2 structure that contains information about the printer. You must set the pPrinterName, pPortName, pDriverName, pPrintProcessor, and pDatatype members of this structure before calling AddPrinter.

Return Value

If the function succeeds, the return value is the handle of a new printer object.

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

Remarks

The following list identifies the members of the PRINTER_INFO_2 structure that can be set before this function is called.

Attributes	pPrintProcessor
DefaultPriority	Priority
pComment	pSecurityDescriptor
pDatatype	pSepFile
pDevMode	pShareName
pLocation	StartTime
pParameters	UntilTime
The Status, cJobs, and AveragePPM members of the PRINTER_INFO_2 structure are reserved for use by the GetPrinter function. They must not be set before calling AddPrinter.

If pSecurityDescriptor is NULL, the system assigns a default security descriptor to the printer.

After an application creates a printer object with the AddPrinter function, it must use the PrinterProperties function to specify the correct settings for the printer driver associated with the printer object.

The AddPrinter function returns an error if a printer object with the same name already exists, unless that object is marked as pending deletion. In that case, the existing printer will not be deleted, and the AddPrinter creation parameters will be used to change the existing printer settings (as if the application had used the SetPrinter function).

Windows NT:The caller of the AddPrinter function must have SERVER_ACCESS_ADMINISTER access to the server on which the printer is to be created. The handle returned by the function will have PRINTER_ALL_ACCESS permission, and can be used to perform administrative operations on the printer.

Windows 95: This access validation is not supported in Windows 95.

Use the EnumPrintProcessors function to enumerate the set of print processors installed on a server. Use the EnumPrintProcessorDatatypes function to enumerate the set of datatypes that a print processor supports.

See Also

ClosePrinter, DeletePrinter, EnumPrintProcessors, EnumPrintProcessorDatatypes, GetPrinter, PRINTER_INFO_2, PrinterProperties, SetPrinter


AddPrinterConnection [New - Windows NT]
 AddPrinterConnection  Overview  Group

[New - Windows NT]

The AddPrinterConnection function adds a connection to the specified printer for the current user.

BOOL AddPrinterConnection (

LPTSTR  pName	// address of printer name
);
Parameters

pName

Points to a null-terminated string that specifies the name of a printer that the current user wishes to establish a connection to.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

When Windows NT makes a connection to a printer, it may need to copy printer driver files to the workstation. If the user does not have permission to copy files to the appropriate location, the AddPrinterConnection function fails, and GetLastError returns ERROR_ACCESS_DENIED.

A printer connection established by calling AddPrinterConnection will be enumerated when EnumPrinters is called with dwType set to PRINTER_ENUM_CONNECTION.

See Also

ConnectToPrinterDlg, DeletePrinterConnection, EnumPrinters


AddPrinterDriver
 AddPrinterDriver  QuickInfo  Overview  Group

The AddPrinterDriver function installs a local or remote printer driver and links the configuration, data, and driver files.

BOOL AddPrinterDriver(

LPTSTR  pName,	// address of server name
DWORD  Level,	// printer info. structure level
LPBYTE  pDriverInfo	// address of printer info. structure
);
Parameters

pName

Points to a null-terminated string that specifies the name of the server on which the driver should be installed. If the driver will be installed locally, this string should be NULL.

Level

Specifies the version of the structure to which pDriverInfo points.

Windows 95: This value can be either 2 or 3.

Windows NT: This value must be 2.

pDriverInfo

Points to either a DRIVER_INFO_2 structure or a DRIVER_INFO_3 structure. If dwlevel is 2, this parameter receives a DRIVER_INFO_2 structure. If dwlevel is 3, this parameter receives a DRIVER_INFO_3 structure.

If the pEnvironment member of the structure pointed to by pDriverInfo is NULL, the current environment of the caller/client (not of the destination/server) is used.

Windows 95: This structure can be either DRIVER_INFO_2 or DRIVER_INFO_3.

Windows NT: This structure must be DRIVER_INFO_2.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

Before an application calls AddPrinterDriver, all files required by the driver must be copied to the system's printer-driver directory. An application can retrieve the name of this directory by calling the GetPrinterDriverDirectory function.

An application can determine which printer drivers are currently installed by calling the EnumPrinterDrivers function.

See Also

DRIVER_INFO_2, EnumPrinterDrivers, GetPrinterDriverDirectory


AddPrintProcessor
 AddPrintProcessor  QuickInfo  Overview  Group

The AddPrintProcessor function installs a print processor on the specified server and adds the print-processor name to an internal list of supported print processors.

BOOL AddPrintProcessor(

LPTSTR  pName,	// address of server name
LPTSTR  pEnvironment,	// address of environment name
LPTSTR  pPathName,	// address of path
LPTSTR  pPrintProcessorName	// address of print-processor name
);
Parameters

pName

Points to a null-terminated string that specifies the name of the server on which the print processor should be installed. If this parameter is NULL, the print processor is installed locally.

pEnvironment

Points to a null-terminated string that specifies the environment. For example, "Windows x86" specifies Windows running on an Intel 80386 or 80486 processor. If this parameter is NULL, the current environment of the caller/client (not of the destination/server) is used.

pPathName

Points to a null-terminated string that specifies the name of the file that contains the print processor. This file must be in the system print-processor directory.

pPrintProcessorName

Points to a null-terminated string that specifies the name of the print processor.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

Before calling this function, an application should verify that the file containing the print processor is stored in the system print-processor directory. An application can retrieve the name of the system print-processor directory by calling the GetPrintProcessorDirectory function.

An application can determine the name of existing print processors by calling the EnumPrintProcessors function.

See Also

EnumPrintProcessors, GetPrintProcessorDirectory


AddPrintProvidor
 AddPrintProvidor  QuickInfo  Overview  Group

The AddPrintProvidor function installs a local printer provider and links the configuration, data, and provider files. Future releases of Windows may allow remote installation of printer providers.

BOOL AddPrintProvidor (

LPTSTR  pName,	// address of server name
DWORD  Level,	// provider information structure level
LPBYTE  pProvidorInfo	// address of provider information structure
);
Parameters

pName

Points to a null-terminated string that specifies the name of the server on which the provider should be installed. For this release of Windows 95 and Windows NT, providers may only be installed locally, so this parameter should be NULL.

Level

Specifies the level of the structure to which pProvidorInfo points. This value must be 1.

pProvidorInfo

Points to a PROVIDOR_INFO_1 structure.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

Before an application calls this function, all files required by the provider must be copied to the SYSTEM32 directory.

A provider added by AddPrintProvidor may be removed by calling DeletePrintProvidor.

See Also

DeletePrintProvidor, PROVIDOR_INFO_1


AddPropSheetPageProc [New - Windows NT]
 AddPropSheetPageProc  QuickInfo  Overview  Group

[New - Windows NT]

The AddPropSheetPageProc function specifies an application-defined callback function that a property sheet extension uses to add a page to a property sheet.

BOOL CALLBACK AddPropSheetPageProc(

HPROPSHEETPAGE  hpage,
LPARAM  lParam
);
Parameters

hpage

Handle to a property sheet page.

lParam

Application-defined 32-bit value.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.


AdjustTokenGroups
 AdjustTokenGroups  QuickInfo  Overview  Group

The AdjustTokenGroups function adjusts groups in the specified access token. TOKEN_ADJUST_GROUPS access is required to enable or disable groups in an access token.

BOOL AdjustTokenGroups(

HANDLE  TokenHandle,	// handle of token that contains groups
BOOL  ResetToDefault,	// flag for default settings
PTOKEN_GROUPS  NewState,	// address of new group information
DWORD  BufferLength,	// size of buffer for previous information
PTOKEN_GROUPS  PreviousState,	// address of previous group information
PDWORD  ReturnLength	// address of required buffer size
);
Parameters

TokenHandle

Identifies the access token containing the groups to be modified.

ResetToDefault

Specifies whether the groups are to be set to their default enabled and disabled states. If this value is TRUE, the groups are set to their default states and the NewState parameter is ignored. If this value is FALSE, the groups are set according to the information pointed to by the NewState parameter.

NewState

Points to a TOKEN_GROUPS structure containing the groups whose states are to be set. If the ResetToDefault parameter is FALSE, the function sets each of the groups to the value of that group's SE_GROUP_ENABLED flag in the TOKEN_GROUPS structure. If ResetToDefault is TRUE, this parameter is ignored.

BufferLength

Specifies the size, in bytes, of the buffer pointed to by the PreviousState parameter. This parameter can be NULL if the PreviousState parameter is NULL.

PreviousState

Points to a buffer receiving a TOKEN_GROUPS structure containing the previous state of any groups the function modifies. The token must be open for TOKEN_QUERY access to use this parameter. This parameter can be NULL.

If a buffer is specified but it does not contain enough space to receive the complete list of modified groups, no group states are changed and the function fails. In this case, the function sets the variable pointed to by the ReturnLength parameter to the number of bytes required to hold the complete list of modified groups.

ReturnLength

Points to a variable set by the function that contains the actual number of bytes needed for the buffer pointed to by the PreviousState parameter. This parameter can be NULL and is ignored if PreviousState is NULL.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The information retrieved in the PreviousState parameter is formatted as a TOKEN_GROUPS structure. This means a pointer to the buffer can be passed as the NewState parameter in a subsequent call to the AdjustTokenGroups function, restoring the original state of the groups.

The NewState parameter can list groups to be changed that are not present in the access token. This does not affect the successful modification of the groups in the token.

Mandatory groups cannot be disabled. They are identified by the SE_GROUP_MANDATORY flag in the TOKEN_GROUPS structure. If an attempt is made to disable any mandatory groups, AdjustTokenGroups fails and leaves the state of all groups unchanged.

See Also

AdjustTokenPrivileges, GetTokenInformation, OpenProcessToken, OpenThreadToken, SetTokenInformation, TOKEN_GROUPS


AdjustTokenPrivileges
 AdjustTokenPrivileges  QuickInfo  Overview  Group

The AdjustTokenPrivileges function adjusts privileges in the specified access token. Enabling or disabling privileges in an access token requires TOKEN_ADJUST_PRIVILEGES access.

BOOL AdjustTokenPrivileges(

HANDLE  TokenHandle,	// handle of token that contains privileges
BOOL  DisableAllPrivileges,	// flag for disabling all privileges
PTOKEN_PRIVILEGES  NewState,	// address of new privilege information
DWORD  BufferLength,	// size of previous information buffer
PTOKEN_PRIVILEGES  PreviousState,	// address of previous information
PDWORD  ReturnLength	// address of required buffer size
);
Parameters

TokenHandle

Identifies the access token that contains the privileges to be modified.

DisableAllPrivileges

Specifies whether the function is to disable all of the token's privileges. If this value is TRUE, the privileges are disabled, and the NewState parameter is ignored. If it is FALSE, the function modifies privileges based on the information pointed to by the NewState parameter.

NewState

Points to a TOKEN_PRIVILEGES structure containing the privileges to be changed. If the DisableAllPrivileges parameter is FALSE, the function sets each of the token's privileges to the value of that privilege's SE_PRIVILEGE_ENABLED flag in the TOKEN_PRIVILEGES structure. If DisableAllPrivileges is TRUE, this parameter is ignored.

BufferLength

Specifies the size, in bytes, of the buffer pointed to by the PreviousState parameter. This parameter can be NULL if the PreviousState parameter is NULL.

PreviousState

Points to a buffer the function fills with a TOKEN_PRIVILEGES structure containing the previous state of any privileges the function modifies. The token must be open for TOKEN_QUERY access to use this parameter. This parameter can be NULL.

If a buffer is specified but does not contain enough space to receive the complete list of modified privileges, no privileges are changed and the function fails. In this case, the function sets the variable pointed to by the ReturnLength parameter to the number of bytes required to hold the complete list of modified privileges.

ReturnLength

Points to a variable receiving the actual number of bytes needed for the buffer pointed to by the PreviousState parameter. This parameter can be NULL and is ignored if PreviousState is NULL.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The information retrieved in the PreviousState parameter is formatted as a TOKEN_PRIVILEGES structure. This means that a pointer to the buffer can be passed as the NewState parameter in a subsequent call to the AdjustTokenPrivileges function, restoring the original state of the privileges.

The NewState parameter can list privileges to be changed that are not present in the access token. This does not affect the successful modification of the privileges in the token.

See Also

AdjustTokenGroups, GetTokenInformation, OpenProcessToken, OpenThreadToken, SetTokenInformation, TOKEN_PRIVILEGES


AdjustWindowRect
 AdjustWindowRect  QuickInfo  Overview  Group

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 CreateWindowEx function to create a window whose client area is the desired size.

BOOL AdjustWindowRect(

LPRECT  lpRect,	// address of client-rectangle structure
DWORD  dwStyle,	// window styles
BOOL  bMenu	// menu-present flag
);
Parameters

lpRect

Points to a RECT structure that contains the coordinates of the top-left and bottom-right corners of the desired client area. When the function returns, the structure contains the coordinates of the top-left and bottom-right corners of the window to accommodate the desired client area.

dwStyle

Specifies the window styles of the window whose required size is to be calculated.

bMenu

Specifies whether the window has a menu.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. 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 a window.

The AdjustWindowRect function also does not add extra rows when a menu bar wraps to two or more rows.

See Also

AdjustWindowRectEx, CreateWindowEx, RECT


AdjustWindowRectEx
 AdjustWindowRectEx  QuickInfo  Overview  Group

The AdjustWindowRectEx function calculates the required size of the rectangle of a window with extended style based on the desired client-rectangle size. 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,	// address of client-rectangle structure
DWORD  dwStyle,	// window styles
BOOL  bMenu,	// menu-present flag
DWORD  dwExStyle	// extended style
);
Parameters

lpRect

Points to a RECT structure that contains the coordinates of the top-left and bottom-right corners of the desired client area. When the function returns, the structure contains the coordinates of the top-left and bottom-right corners of the window to accommodate the desired client area.

dwStyle

Specifies the window styles of the window whose required size is to be calculated.

bMenu

Specifies whether the window has a menu.

dwExStyle

Specifies the extended style of the window whose required size is to be calculated.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. 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 a window.

The AdjustWindowRectEx function also does not add extra space when a menu bar wraps to two or more rows.

See Also

AdjustWindowRect, CreateWindowEx, RECT


AdvancedDocumentProperties
 AdvancedDocumentProperties  QuickInfo  Overview  Group

The AdvancedDocumentProperties function displays a printer-configuration dialog box for the specified printer, allowing the user to configure that printer.

LONG AdvancedDocumentProperties(

HWND  hWnd,	// handle of dialog box's parent window
HANDLE  hPrinter,	// handle of printer object
LPTSTR  pDeviceName,	// address of driver name
PDEVMODE  pDevModeOutput,	// address of modified device mode structure
PDEVMODE  pDevModeInput	// address of original device mode structure
);
Parameters

hWnd

Identifies the parent window of the printer-configuration dialog box.

hPrinter

Identifies a printer object.

pDeviceName

Points to a null-terminated string specifying the name of the device for which a printer-configuration dialog box should be displayed.

pDevModeOutput

Points to a DEVMODE structure that will contain the configuration data specified by the user. An application can retrieve the number of bytes required for this structure by calling the AdvancedDocumentProperties function and setting pDevModeOutput to NULL.

pDevModeInput

Points to a DEVMODE structure that contains the configuration data used to initialize the controls of the printer-configuration dialog box.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

An application can obtain the printer handle identified by the hPrinter parameter by calling the OpenPrinter or AddPrinter function.

An application can obtain the name pointed to by the pDeviceName parameter by calling the GetPrinter function and then examining the pPrinterName member of the PRINTER_INFO_2 structure.

See Also

AddPrinter, DEVMODE, GetPrinter, OpenPrinter, PRINTER_INFO_2


AllocateAndInitializeSid
 AllocateAndInitializeSid  QuickInfo  Overview  Group

The AllocateAndInitializeSid function allocates and initializes a security identifier (SID) with up to eight subauthorities.

BOOL AllocateAndInitializeSid(

PSID_IDENTIFIER_AUTHORITY  pIdentifierAuthority,	// address of identifier authority
BYTE  nSubAuthorityCount,	// count of subauthorities
DWORD  dwSubAuthority0,	// subauthority 0
DWORD  dwSubAuthority1,	// subauthority 1
DWORD  dwSubAuthority2,	// subauthority 2
DWORD  dwSubAuthority3,	// subauthority 3
DWORD  dwSubAuthority4,	// subauthority 4
DWORD  dwSubAuthority5,	// subauthority 5
DWORD  dwSubAuthority6,	// subauthority 6
DWORD  dwSubAuthority7,	// subauthority 7
PSID  *pSid	// address of pointer to SID
);
Parameters

pIdentifierAuthority

Points to an SID_IDENTIFIER_AUTHORITY structure, giving the top-level identifier authority value to set in the SID.

nSubAuthorityCount

Specifies the number of subauthorities to place in the SID. This parameter also identifies how many of the subauthority parameters have meaningful values. This parameter must contain a value from 1 through 8.

For example, a value of 3 indicates that the subauthority values specified by the dwSubAuthority0, dwSubAuthority1, and dwSubAuthority2 parameters have meaningful values and to ignore the remainder.

dwSubAuthority0 through dwSubAuthority7

Specify subauthority values to place in the SID.

pSid

Points to a variable that receives the address of the allocated and initialized SID structure.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

An SID allocated with this function must be freed by using the FreeSid function.

See Also

FreeSid, GetSidIdentifierAuthority, InitializeSid, SID_IDENTIFIER_AUTHORITY


AllocateLocallyUniqueId
 AllocateLocallyUniqueId  QuickInfo  Overview  Group

The AllocateLocallyUniqueId function allocates a locally unique identifier (LUID).

BOOL AllocateLocallyUniqueId(

PLUID  Luid	// address of locally unique identifier
);
Parameters

Luid

Points to a buffer that receives the allocated LUID.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

An LUID is unique only within a single session. The same LUID value can be used on different computers or on the same computer after it has been restarted.

See Also

LookupPrivilegeValue


AllocConsole
 AllocConsole  QuickInfo  Overview  Group

The AllocConsole function allocates a new console for the calling process.

BOOL AllocConsole(VOID)

Parameters

This function has no parameters.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

A process can only be associated with one console, so AllocConsole fails if the calling process already has a console. A process can use the FreeConsole function to detach itself from its current console, and then it can call AllocConsole to create a new console. If the calling process creates a child process, the child inherits the new console.

AllocConsole also sets up standard input, standard output, and standard error handles for the new console. The standard input handle is a handle to the console's input buffer, and the standard output and standard error handles are handles to the console's screen buffer. To retrieve these handles, use the GetStdHandle function.

This function is primarily used by graphics applications to create a console window. Graphics applications are initialized without a console. Console applications are normally initialized with a console, unless they are created as detached processes (by calling the CreateProcess function with the DETACHED_PROCESS flag).

See Also

CreateProcess, FreeConsole, GetStdHandle


 AllocDStoCSAlias

The AllocDStoCSAlias function is obsolete. This function has no meaning in the 32-bit environment.


 AllocResource

The AllocResource function is not implemented in the Win32 API. Win32-based applications should use the LoadResource, LockResource, and FindResource functions.


 AllocSelector

The AllocSelector function is not implemented in the Win32 API. Win32-based applications should use the VirtualLock and VirtualUnlock functions.


AngleArc
 AngleArc  QuickInfo  Overview  Group

The AngleArc function draws a line segment and an arc. The line segment is drawn from the current position to the beginning of the arc. The arc is drawn along the perimeter of a circle with the given radius and center. The length of the arc is defined by the given start and sweep angles.

BOOL AngleArc(

HDC  hdc,	// handle of device context
int  X,	// x-coordinate of circle's center
int  Y,	// y-coordinate of circle's center
DWORD  dwRadius,	// circle's radius
FLOAT  eStartAngle,	// arc's start angle
FLOAT  eSweepAngle	// arc's sweep angle
);
Parameters

hdc

Identifies a device context.

X

Specifies the logical x-coordinate of the center of the circle.

Y

Specifies the logical y-coordinate of the center of the circle.

dwRadius

Specifies the radius, in logical units, of the circle. This value must be positive.

eStartAngle

Specifies the start angle, in degrees, relative to the x-axis.

eSweepAngle

Specifies the sweep angle, in degrees, relative to the starting angle.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

The AngleArc function moves the current position to the ending point of the arc.

The arc drawn by this function may appear to be elliptical, depending on the current transformation and mapping mode. Before drawing the arc, AngleArc draws the line segment from the current position to the beginning of the arc.

The arc is drawn by constructing an imaginary circle around the specified center point with the specified radius. The starting point of the arc is determined by measuring counterclockwise from the x-axis of the circle by the number of degrees in the start angle. The ending point is similarly located by measuring counterclockwise from the starting point by the number of degrees in the sweep angle.

If the sweep angle is greater than 360 degrees, the arc is swept multiple times.

This function draws lines by using the current pen. The figure is not filled.

See Also

Arc, ArcTo, MoveToEx


AnimatePalette
 AnimatePalette  QuickInfo  Overview  Group

The AnimatePalette function replaces entries in the specified logical palette.

BOOL AnimatePalette(

HPALETTE  hpal,	// handle of logical color palette
UINT  iStartIndex,	// first entry in logical palette
UINT  cEntries,	// count of entries in logical palette
CONST PALETTEENTRY  *ppe	// address of first replacement
);
Parameters

hpal

Identifies the logical palette.

iStartIndex

Specifies the first logical palette entry to be replaced.

cEntries

Specifies the number of entries to be replaced.

ppe

Points to the first member of an array of PALETTEENTRY structures used to replace the current entries.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

An application can determine whether a device supports palette operations by calling the GetDeviceCaps function and specifying the RASTERCAPS constant.

The AnimatePalette function only changes entries with the PC_RESERVED flag set in the corresponding palPalEntry member of the LOGPALETTE structure.

If the given palette is associated with the active window, the colors in the palette are replaced immediately.

See Also

CreatePalette, GetDeviceCaps, LOGPALETTE, PALETTEENTRY


AnsiLower
 AnsiLower  QuickInfo

The AnsiLower function is obsolete.

For compatibility with 16-bit versions of Windows, this function is implemented as a macro that calls the CharLower function, which should be used for new Win32-based applications.


AnsiLowerBuff
 AnsiLowerBuff  QuickInfo

The AnsiLowerBuff function is obsolete.

For compatibility with 16-bit versions of Windows, this function is implemented as a macro that calls the CharLowerBuff function, which should be used for new Win32-based applications.


AnsiNext
 AnsiNext  QuickInfo

The AnsiNext function is obsolete.

For compatibility with 16-bit versions of Windows, this function is implemented as a macro that calls the CharNext function, which should be used for new Win32-based applications.


AnsiPrev
 AnsiPrev  QuickInfo

The AnsiPrev function is obsolete.

For compatibility with 16-bit versions of Windows, this function is implemented as a macro that calls the CharPrev function, which should be used for new Win32-based applications.


AnsiToOem
 AnsiToOem  QuickInfo  Overview  Group

The AnsiToOem function is obsolete.

For compatibility with 16-bit versions of Windows, this function is implemented as a macro that calls the CharToOem function, which should be used for new Win32-based applications.


AnsiToOemBuff
 AnsiToOemBuff  QuickInfo  Overview  Group

The AnsiToOemBuff function is obsolete.

For compatibility with 16-bit versions of Windows, this function is implemented as a macro that calls the CharToOemBuff function, which should be used for new Win32-based applications.


AnsiUpper
 AnsiUpper  QuickInfo

The AnsiUpper function is obsolete.

For compatibility with 16-bit versions of Windows, this function is implemented as a macro that calls the CharUpper function, which should be used for new Win32-based applications.


AnsiUpperBuff
 AnsiUpperBuff  QuickInfo

The AnsiUpperBuff function is obsolete.

For compatibility with 16-bit versions of Windows, this function is implemented as a macro that calls the CharUpperBuff function, which should be used for new Win32-based applications.


AnyPopup
 AnyPopup  QuickInfo  Overview  Group

The AnyPopup function indicates whether an owned, visible, top-level pop-up, or overlapped window exists on the screen. The function searches the entire Windows screen, not just the calling application's client area.

BOOL AnyPopup(VOID)

Parameters

This function has no parameters.

Return Value

If a pop-up window exists, the return value is TRUE even if the pop-up window is completely covered by other windows. Otherwise, it is FALSE.

Remarks

AnyPopup is a Windows version 1.x function and is retained for compatibility purposes. It is generally not useful.

This function does not detect unowned pop-up windows or windows that do not have the WS_VISIBLE style bit set.

See Also

GetLastActivePopup, ShowOwnedPopups


AppendMenu
 AppendMenu  QuickInfo  Overview  Group

The AppendMenu function appends a new item to the end of the specified menu. An application can use this function to specify the content, appearance, and behavior of the menu item.

BOOL AppendMenu(

HMENU hMenu,	// handle of menu
UINT uFlags,	// menu item flags
UINT uIDNewItem,	// menu item identifier or pop-up menu handle
LPCTSTR lpNewItem	// menu item content
);
Parameters

hMenu

Identifies the menu to be changed.

uFlags

Specifies flags to control the appearance and behavior of the new menu item. This parameter can be a combination of the values listed in the following Remarks section.

uIDNewItem

Specifies either the identifier of the new menu item or, if the uFlags parameter is set to MF_POPUP, the handle of the pop-up menu.

lpNewItem

Specifies the content of the new menu item. The interpretation of lpNewItem depends on whether the uFlags parameter includes the MF_BITMAP, MF_OWNERDRAW, or MF_STRING flag, as follows:

Value	Description
MF_BITMAP	Contains a bitmap handle.
MF_OWNERDRAW	Contains a 32-bit value supplied by the application that can be used to maintain additional data related to the menu item. The value is in the itemData member of the structure pointed to by the lparam parameter of the WM_MEASURE or WM_DRAWITEM message sent when the menu is created or its appearance is updated.
MF_STRING	Contains a pointer to a null-terminated string.
Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. 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 flags must be set in the uFlags parameter:

Value	Description
MF_BITMAP	Uses a bitmap as the item. The lpNewItem parameter contains the handle of the bitmap.
MF_CHECKED	Places a check mark next to the 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 it cannot be selected.
MF_MENUBARBREAK	Functions the same as the MF_MENUBREAK flag except for pop-up menus, where the new column is separated from the old column by a vertical line.
MF_MENUBREAK	Places the item on a new line (for menu bars) or in a new column (for pop-up menus) 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 is a pop-up item; that is, selecting it activates a pop-up menu. The uIDNewItem parameter specifies the handle of the pop-up menu. This flag is used to add a pop-up item to a menu bar or to a pop-up menu.
MF_SEPARATOR	Draws a horizontal dividing line. This flag is only used in a pop-up menu. The line cannot be grayed, disabled, or highlighted. The lpNewItem and uIDNewItem parameters are ignored.
MF_STRING	Specifies that the menu item is a text string; the lpNewItem parameter points to the string.
MF_UNCHECKED	Does not place a check mark next to the item (default). If the application supplies check mark bitmaps (see SetMenuItemBitmaps), this flag displays the unchecked bitmap next to the menu item.
The following list shows groups of flags that cannot be used together:

•	MF_DISABLED, MF_ENABLED, and MF_GRAYED

•	MF_BITMAP, MF_STRING, and MF_OWNERDRAW

•	MF_MENUBARBREAK and MF_MENUBREAK

•	MF_CHECKED and MF_UNCHECKED

See Also

CreateMenu, DeleteMenu, DestroyMenu, DrawMenuBar, InsertMenu, MF_BITMAP, MF_OWNERDRAW, ModifyMenu, RemoveMenu, SetMenuItemBitmaps


Arc
 Arc  QuickInfo  Overview  Group

The Arc function draws an elliptical arc.

BOOL Arc(

HDC  hdc,	// handle of device context
int  nLeftRect,	// x-coordinate of bounding rectangle's upper-left corner
int  nTopRect,	// y-coordinate of bounding rectangle's upper-left corner
int  nRightRect,	// x-coordinate of bounding rectangle's lower-right corner
int  nBottomRect,	// y-coordinate of bounding rectangle's lower-right corner
int  nXStartArc,	// first radial ending point
int  nYStartArc,	// first radial ending point
int  nXEndArc,	// second radial ending point
int  nYEndArc	// second radial ending point
);
Parameters

hdc

Identifies the device context where drawing takes place.

nLeftRect

Specifies the logical x-coordinate of the upper-left corner of the bounding rectangle.

Windows 95: The sum of nLeftRect plus nRightRect must be less than 32768.

nTopRect

Specifies the logical y-coordinate of the upper-left corner of the bounding rectangle.

Windows 95: The sum of nTopRect plus nBottomRect must be less than 32768.

nRightRect

Specifies the logical x-coordinate of the lower-right corner of the bounding rectangle.

Windows 95: The sum of nLeftRect plus nRightRect must be less than 32768.

nBottomRect

Specifies the logical y-coordinate of the lower-right corner of the bounding rectangle.

Windows 95: The sum of nTopRect plus nBottomRect must be less than 32768.

nXStartArc

Specifies the logical x-coordinate of the ending point of the radial line defining the starting point of the arc.

nYStartArc

Specifies the logical y-coordinate of the ending point of the radial line defining the starting point of the arc.

nXEndArc

Specifies the logical x-coordinate of the ending point of the radial line defining the ending point of the arc.

nYEndArc

Specifies the logical y-coordinate of the ending point of the radial line defining the ending point of the arc.

Return Value

If the arc is drawn, the return value is TRUE; otherwise, it is FALSE.

Remarks

The points (nLeftRect, nTopRect) and (nRightRect, nBottomRect) specify the bounding rectangle. An ellipse formed by the given bounding rectangle defines the curve of the arc. The arc extends in the current drawing direction from the point where it intersects the radial from the center of the bounding rectangle to the (nXStartArc, nYStartArc) point. The arc ends where it intersects the radial from the center of the bounding rectangle to the (nXEndArc, nYEndArc) point. If the starting point and ending point are the same, a complete ellipse is drawn.

The arc is drawn using the current pen; it is not filled.

The current position is neither used nor updated by Arc.

Windows 95: The drawing direction is always counterclockwise.

Windows NT: Use the GetArcDirection and SetArcDirection functions to get and set the current drawing direction for a device context. The default drawing direction is counterclockwise.

Windows 95 only: The sum of the coordinates of the bounding rectangle cannot exceed 32,767. The sum of nLeftRect and nRightRect or nTopRect and nBottomRect parameters cannot exceed 32,767.

See Also

AngleArc, ArcTo, Chord, Ellipse, GetArcDirection, Pie, SetArcDirection


ArcTo
 ArcTo  QuickInfo  Overview  Group

The ArcTo function draws an elliptical arc.

BOOL ArcTo(

HDC  hdc,	// handle of device context
int  nLeftRect,	// x-coordinate of bounding rectangle's upper-left corner
int  nTopRect,	// y-coordinate of bounding rectangle's upper-left corner
int  nRightRect,	// x-coordinate of bounding rectangle's lower-right corner
int  nBottomRect,	// y-coordinate of bounding rectangle's lower-right corner
int  nXRadial1,	// x-coordinate of the first radial ending point
int  nYRadial1,	// y-coordinate of the first radial ending point
int  nXRadial2,	// x-coordinate of the second radial ending point
int  nYRadial2	// y-coordinate of the second radial ending point
);
Parameters

hdc

Identifies the device context where drawing takes place.

nLeftRect

Specifies the logical x-coordinate of the upper-left corner of the bounding rectangle.

nTopRect

Specifies the logical y-coordinate of the upper-left corner of the bounding rectangle.

nRightRect

Specifies the logical x-coordinate of the lower-right corner of the bounding rectangle.

nBottomRect

Specifies the logical y-coordinate of the lower-right corner of the bounding rectangle.

nXRadial1

Specifies the logical x-coordinate of the endpoint of the radial defining the starting point of the arc.

nYRadial1

Specifies the logical y-coordinate of the endpoint of the radial defining the starting point of the arc.

nXRadial2

Specifies the logical x-coordinate of the endpoint of the radial defining the ending point of the arc.

nYRadial2

Specifies the logical y-coordinate of the endpoint of the radial defining the ending point of the arc.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

ArcTo is similar to the Arc function, except that the current position is updated.

The points (nLeftRect, nTopRect) and (nRightRect, nBottomRect) specify the bounding rectangle. An ellipse formed by the given bounding rectangle defines the curve of the arc. The arc extends counterclockwise from the point where it intersects the radial line from the center of the bounding rectangle to the (nXRadial1, nYRadial1) point. The arc ends where it intersects the radial line from the center of the bounding rectangle to the (nXRadial2, nYRadial2) point. If the starting point and ending point are the same, a complete ellipse is drawn.

A line is drawn from the current position to the starting point of the arc. If no error occurs, the current position is set to the ending point of the arc.

The arc is drawn using the current pen; it is not filled.

See Also

AngleArc, Arc, SetArcDirection


AreAllAccessesGranted
 AreAllAccessesGranted  QuickInfo  Overview  Group

The AreAllAccessesGranted function checks whether a set of requested access rights has been granted. The access rights are represented as bit flags in a 32-bit access mask.

BOOL AreAllAccessesGranted(

DWORD  GrantedAccess,	// access mask for granted access rights
DWORD  DesiredAccess	// access mask for requested access rights
);
Parameters

GrantedAccess

An access mask that specifies the access rights that have been granted.

DesiredAccess

An access mask that specifies the access rights that have been requested. This mask must have been mapped from generic to specific and standard access rights, usually by calling the MapGenericMask function.

Return Value

If all the requested access rights have been granted, the return value is TRUE; otherwise, it is FALSE.

Remarks

The AreAllAccessesGranted function is commonly used by a server application to check the access rights of a client attempting to gain access to an object. When the bits set in the DesiredAccess parameter match the bits set in the GrantedAccess parameter, all requested rights have been granted.

See Also

AccessCheck, AreAnyAccessesGranted, MapGenericMask


AreAnyAccessesGranted
 AreAnyAccessesGranted  QuickInfo  Overview  Group

The AreAnyAccessesGranted function tests whether any of a set of requested access rights has been granted. The access rights are represented as bit flags in a 32-bit access mask.

BOOL AreAnyAccessesGranted(

DWORD  GrantedAccess,	// access mask for granted access rights
DWORD  DesiredAccess	// access mask for access rights requested
);
Parameters

GrantedAccess

Specifies the granted access mask.

DesiredAccess

Specifies the access mask to be requested. This mask must have been mapped from generic to specific and standard access rights, usually by calling the MapGenericMask function.

Return Value

If any of the requested access rights have been granted, the return value is TRUE; otherwise, it is FALSE.

Remarks

The AreAnyAccessesGranted function is often used by a server application to check the access rights of a client attempting to gain access to an object. When any of the bits set in the DesiredAccess parameter match the bits set in the GrantedAccess parameter, at least one of the requested access rights has been granted.

See Also

AccessCheck, AreAllAccessesGranted, MapGenericMask


AreFileApisANSI
 AreFileApisANSI  QuickInfo  Overview  Group

The AreFileApisANSI function determines whether a set of Win32 file functions is using the ANSI or OEM character set code page. This function is useful for 8-bit console input and output operations.

BOOL AreFileApisANSI (VOID)

Parameters

This function has no parameters.

Return Value

If the set of Win32 file functions is using the ANSI code page, the return value is TRUE.

If the set of Win32 file functions is using the OEM code page, the return value is FALSE.

Remarks

The SetFileApisToOEM function causes a set of Win32 file functions to use the OEM code page. The SetFileApisToANSI function causes the same set of Win32 file functions to use the ANSI code page. Use the AreFileApisANSI function to determine which code page the set of file functions is currently using. For a discussion of their usage, please refer to the Remarks sections of SetFileApisToOEM and SetFileApisToANSI.

The following is the set of Win32 file functions whose code page is ascertained by the AreFileApisANSI function:

_lopen	GetDriveType	LoadLibrary
CopyFile	GetFileAttributes	LoadLibraryEx
CreateDirectory	GetFullPathName	MoveFile
CreateFile	GetModuleFileName	MoveFileEx
CreateProcess	GetModuleHandle	OpenFile
DeleteFile	GetSystemDirectory	RemoveDirectory
FindFirstFile	GetTempFileName	SearchPath
FindNextFile	GetTempPath	SetCurrentDirectory
GetCurrentDirectory	GetVolumeInformation	SetFileAttributes
GetDiskFreeSpace	GetWindowsDirectory
See Also

SetFileApisToANSI, SetFileApisToOEM


ArrangeIconicWindows
 ArrangeIconicWindows  QuickInfo  Overview  Group

The ArrangeIconicWindows function arranges all the minimized (iconic) child windows of the specified parent window.

UINT ArrangeIconicWindows(

HWND  hWnd	// handle of parent window
);
Parameters

hWnd

Identifies the parent window.

Return Value

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 ArrangeIconicWindows to arrange icons in a parent window. This function can also arrange icons on the desktop. To retrieve the window handle of 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.

See Also

CloseWindow, GetDesktopWindow


AttachThreadInput
 AttachThreadInput  QuickInfo  Overview  Group

The AttachThreadInput function attaches the input processing mechanism of one thread to that of another thread.

BOOL AttachThreadInput(

DWORD  idAttach,	// thread to attach
DWORD  idAttachTo,	// thread to attach to
BOOL  fAttach	// attach or detach
);
Parameters

idAttach

Specifies the identifier of the thread to be attached to another thread.

idAttachTo

Specifies the identifier of the thread to be attached to.

fAttach

Specifies whether to attach or detach the threads. If this parameter is TRUE, the two threads are attached. If the parameter is FALSE, the threads are detached.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

Normally, windows created in different threads process input independently of each other. That is, they have their own input states (focus, active, capture windows, key state, queue status, and so on), and they are not synchronized with the input processing of other threads. By using this function, a thread can attach its input processing to another thread. This also allows a thread to share its input states, so they can call the SetFocus function to set the keyboard focus to a window of a different thread; this also allows threads to get key state information. These capabilities are not normally possible.

AttachThreadInput fails if either of the specified threads 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.

Please note that key state, which can be ascertained by calls to the GetKeyState or GetKeyboardState function, is reset after a call to AttachThreadInput.

See Also

GetCurrentThreadId, GetKeyState, GetKeyboardState, GetWindowThreadProcessId, SetFocus


BackupEventLog
 BackupEventLog  QuickInfo  Overview  Group

The BackupEventLog function saves the specified event log to a backup file. The function does not clear the event log.

BOOL BackupEventLog(

HANDLE  hEventLog,	// handle to event log
LPCTSTR  lpBackupFileName	// name of backup file
);
Parameters

hEventLog

Identifies the open event log. This handle is returned by the OpenEventLog or OpenBackupEventLog function.

lpBackupFileName

Points to a null-terminated string that names the backup file. The backup filename may contain a server name to save the backup file on a remote server.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

If the backup filename specifies a remote server, the event log handle must identify a log on the local computer. You cannot back up an event logfile from a remote server to a file on a remote server (even if the backup file and the original log are on the same server).

See Also

OpenBackupEventLog, OpenEventLog


BackupRead
 BackupRead  QuickInfo  Overview  Group

The BackupRead function reads data associated with a specified file or directory into a buffer. You use this function to back up a file or directory.

BOOL BackupRead(

HANDLE  hFile,	// handle to file or directory
LPBYTE  lpBuffer,	// pointer to buffer to read to
DWORD  nNumberOfBytesToRead,	// number of bytes to read
LPDWORD  lpNumberOfBytesRead,	// pointer to variable to receive number of bytes read
BOOL  bAbort,	// termination type
BOOL  bProcessSecurity,	// process security flag
LPVOID  *lpContext	// pointer to pointer to internal context information
);
Parameters

hFile

Handle to the file or directory being backed up. The function reads data associated with this file. You obtain this handle by calling the CreateFile function.

The BackupRead function fails if CreateFile was called with the flag FILE_FLAG_NO_BUFFERING. In this case, the GetLastError function returns the value ERROR_INVALID_PARAMETER.

lpBuffer

Pointer to a buffer that the function writes data to.

nNumberOfBytesToRead

Specifies the length of the buffer.  The buffer size must be greater than the size of a WIN32_STREAM_ID structure.

lpNumberOfBytesRead

Pointer to a variable that, when the function returns, contains the number of bytes read.

If the function return value is TRUE, and the variable pointed to by lpNumberOfBytesRead is zero, then all the data associated with the file handle has been read.

bAbort

Indicates whether BackupRead terminated abnormally. If this value is TRUE, the operation terminates abnormally and all buffers are deallocated.

bProcessSecurity

Indicates whether the function will restore the access-control list (ACL) data for the file or directory.

If bProcessSecurity is TRUE, the ACL data will be backed up.

lpContext

Pointer to a variable that receives and holds a pointer to an internal data structure used by BackupRead to maintain context information during a backup operation.

You must set the variable pointed to by lpContext to NULL before the first call to BackupRead for the specified file or directory. The function allocates memory for the data structure, and then sets the variable to point to that structure. You must not change lpContext  or the variable that it points to between calls to BackupRead.

To release the memory used by the data structure, call BackupRead with the bAbort parameter set to TRUE when the backup operation is complete.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE, indicating that an I/O error occurred. To get extended error information, call GetLastError.

Remarks

BackupRead processes all of the data pertaining to an opened object as a series of discrete byte streams. Each stream is preceded by a 32-bit aligned WIN32_STREAM_ID structure.

Streams must be processed in the same order in which they were written to the tape. This ordering enables applications to compare the data backed up against the data on the source device. The data returned by BackupRead is to be used only as input to the BackupWrite function. This data is returned as one large data stream divided into substreams. The substreams are separated by WIN32_STREAM_ID headers.

If an error occurs while BackupRead is reading, the calling process can skip the bad data by calling the BackupSeek function.

See Also

BackupWrite, BackupSeek, WIN32_STREAM_ID


BackupSeek
 BackupSeek  QuickInfo  Overview  Group

The BackupSeek function seeks forward in a data stream initially accessed by using the BackupRead or BackupWrite function.

BOOL BackupSeek(

HANDLE  hFile,	// handle of open file
DWORD  dwLowBytesToSeek,	// low-order 32 bits of number of bytes
DWORD  dwHighBytesToSeek,	// high-order 32 bits of number of bytes
LPDWORD  lpdwLowByteSeeked,	// address of number of bytes function seeks
LPDWORD  lpdwHighByteSeeked,	// address of number of bytes function seeks
LPVOID *  lpContext	//address of internal context information
);
Parameters

hFile

Identifies the file or directory being backed up. This handle is created by using the CreateFile function.

dwLowBytesToSeek

Specifies the low-order 32 bits of the number of bytes to seek.

dwHighBytesToSeek

Specifies the high-order 32 bits of the number of bytes to seek.

lpdwLowByteSeeked

Points to a doubleword that, when the function returns, contains the low-order 32 bits of the number of bytes the function actually seeks.

lpdwHighByteSeeked

Points to a doubleword that, when the function returns, contains the high-order 32 bits of the number of bytes the function actually seeks.

lpContext

Points to an internal data structure used by the function. This structure must be the same structure that was initialized by the BackupRead function. An application must not touch the contents of this structure.

Return Value

If the function could seek the requested amount, the function returns TRUE. Otherwise, it is FALSE.

Remarks

Applications use BackUpSeek to skip portions of a data stream that cause errors. This function does not seek across stream headers. If an application attempts to seek past the end of a substream, the function fails, the lpdwLowByteSeeked and lpdwHighByteSeeked parameters indicate the actual number of bytes the function seeks, and the file position is placed at the start of the next stream header.

See Also

BackupRead, BackupWrite, CreateFile


BackupWrite
 BackupWrite  QuickInfo  Overview  Group

The BackupWrite function writes a stream of data from a buffer to a specified file or directory. The data must be divided into substreams separated by WIN32_STREAM_ID structures. You use this function to restore a file or directory that has been backed up.

BOOL BackupWrite(

HANDLE  hFile,	// handle to file or directory
LPBYTE  lpBuffer,	// pointer to buffer containing data to write
DWORD  nNumberOfBytesToWrite,	// number of bytes to write
LPDWORD  lpNumberOfBytesWritten,	// pointer to variable to receive number of bytes written
BOOL  bAbort,	// termination type
BOOL  bProcessSecurity,	// process security
LPVOID  *lpContext	// pointer to pointer to internal context information
);
Parameters

hFile

Handle to the file or directory being restored. The function writes data to this file. You obtain this handle by calling the CreateFile function.

The BackupWrite function fails if CreateFile was called with the flag FILE_FLAG_NO_BUFFERING. In this case, the GetLastError function returns the value ERROR_INVALID_PARAMETER.

lpBuffer

Pointer to a buffer that the function writes data from.

nNumberOfBytesToWrite

Specifies the length of the buffer.  The buffer size must be greater than the size of a WIN32_STREAM_ID structure.

lpNumberOfBytesWritten

Pointer to a variable that, when the function returns, contains the number of bytes written.

bAbort

Specifies whether BackupWrite terminated abnormally. If this value is TRUE, the operation terminated abnormally and all buffers were deallocated.

bProcessSecurity

Specifies whether the function will restore the access-control list (ACL) data for the file or directory.

If bProcessSecurity is TRUE, you need to have specified  WRITE_OWNER and WRITE_DAC access when opening the file or directory handle. If the handle does not have those access rights, the operating system denies access to the ACL data, and ACL data restoration will not occur.

lpContext

Pointer to a variable that receives and holds a pointer to an internal data structure used by BackupWrite to maintain context information during a restore operation.

You must set the variable pointed to by lpContext to NULL before the first call to BackupWrite for the specified file or directory. The function allocates memory for the data structure, and then sets the variable to point to that structure. You must not change lpContext or the variable that it points to between calls to BackupWrite.

To release the memory used by the data structure, call BackupWrite with the bAbort parameter set to TRUE when the restore operation is complete.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE, indicating that an I/O error occurred. To get extended error information, call GetLastError.

Remarks

The BACKUP_LINK stream type lets you restore files with hard links.

Data obtained by the BackupRead function should only be used as input to the BackupWrite function.

See Also

BackupRead, BackupSeek, CreateFile, WIN32_STREAM_ID


Beep
 Beep  QuickInfo  Overview  Group

The Beep function generates simple tones on the speaker.

BOOL Beep(

DWORD  dwFreq,	// sound frequency, in hertz
DWORD  dwDuration	// sound duration, in milliseconds
);
Parameters

dwFreq

Windows NT:

Specifies the frequency, in hertz, of the sound. This parameter must be in the range 37 through 32,767 (0x25 through 0x7FFF).

Windows 95:

The parameter is ignored.

dwDuration

Windows NT:

Specifies the duration, in milliseconds, of the sound.

One value has a special meaning: If dwDuration is  − 1, the function operates asynchronously and produces sound until called again.

Windows 95:

The parameter is ignored.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

Windows NT:

The Beep function is synchronous in all but one case; the function does not generally return control to its caller until the sound finishes. The exception to this occurs when dwDuration has the value  − 1. In that case, Beep is asynchronous, returning control immediately to its caller while the sound continues playing. The sound continues until the next call to Beep.

Windows 95:

The Beep function ignores the dwFreq and dwDuration parameters. On computers with a sound card, the function plays the default sound event. On computers without a sound card, the function plays the standard system beep.


BeginDeferWindowPos
 BeginDeferWindowPos  QuickInfo  Overview  Group

The BeginDeferWindowPos function allocates memory for a multiple-window − position structure and returns the handle of the structure.

HDWP BeginDeferWindowPos(

int  nNumWindows	// number of windows
);
Parameters

nNumWindows

Specifies the initial number of windows for which to store position information. The DeferWindowPos function increases the size of the structure, if necessary.

Return Value

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.

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 of 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 Windows 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, Windows 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.

See Also

DeferWindowPos, EndDeferWindowPos, SetWindowPos


BeginPaint
 BeginPaint  QuickInfo  Overview  Group

The BeginPaint function prepares the specified window for painting and fills a PAINTSTRUCT structure with information about the painting.

HDC BeginPaint(

HWND  hwnd,	// handle of window
LPPAINTSTRUCT  lpPaint	// address of structure for paint information
);
Parameters

hwnd

Identifies the window to be repainted.

lpPaint

Points to the PAINTSTRUCT structure that will receive painting information.

Return Value

If the function succeeds, the return value is the handle of a display device context (DC) for the given window.

If the function fails, the return value is NULL, indicating that no display DC is available.

Remarks

BeginPaint automatically sets the clipping region of the DC to exclude any area outside the update region. The update region is set by the InvalidateRect or InvalidateRgn function and by the system after sizing, moving, creating, scrolling, or any other operation that affects the client area. If the update region is marked for erasing, BeginPaint sends a WM_ERASEBKGND message to the window.

An application should not call BeginPaint except in response to a WM_PAINT message. Each call to BeginPaint must have a corresponding call to the EndPaint function.

If the caret is in the area to be painted, BeginPaint automatically hides the caret to prevent it from being erased.

If the window's class has a background brush, BeginPaint uses that brush to erase the background of the update region before returning.

See Also

EndPaint, InvalidateRect, InvalidateRgn, PAINTSTRUCT, ValidateRect, ValidateRgn


BeginPath
 BeginPath  QuickInfo  Overview  Group

The BeginPath function opens a path bracket in the specified device context (DC).

BOOL BeginPath(

HDC  hdc	// handle of device context
);
Parameters

hdc

Identifies the DC.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

After a path bracket is open, an application can begin calling GDI drawing functions to define the points that lie in the path. An application can close an open path bracket by calling the EndPath function.

When an application calls BeginPath for a DC, any previous paths are discarded from that DC.

Windows NT:

The following drawing functions define points in a path:

AngleArc	LineTo	Polyline
Arc	MoveToEx	PolylineTo
ArcTo	Pie	PolyPolygon
Chord	PolyBezier	PolyPolyline
CloseFigure	PolyBezierTo	Rectangle
Ellipse	PolyDraw	RoundRect
ExtTextOut	Polygon	TextOut
Windows 95:

When constructing a path, only the CloseFigure, ExtTextOut, LineTo, MoveToEx, PolyBezier, PolyBezierTo, Polygon, Polyline, PolylineTo, PolyPolygon, PolyPolyline, and TextOut functions are recorded.

See Also

EndPath, FillPath, PathToRegion, SelectClipPath, StrokeAndFillPath, StrokePath, WidenPath


BeginUpdateResource
 BeginUpdateResource  QuickInfo  Overview  Group

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,	// address of file in which to update resources
BOOL  bDeleteExistingResources	// deletion option
);
Parameters

pFileName

Points to a null-terminated string that specifies a Windows 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, Windows searches for the file in the current directory.

bDeleteExistingResources

Specifies whether to delete the pFileName parameter's existing resources. If this parameter is TRUE, existing resources are deleted and the updated executable file includes only resources added with the UpdateResource function. If this parameter is FALSE, the updated executable file includes existing resources unless they are explicitly deleted or replaced by using UpdateResource.

Return Value

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.

See Also

EndUpdateResource, UpdateResource


bind
 bind  QuickInfo

The Windows Sockets bind function associates a local address with a socket.

int bind (

SOCKET s,
const struct sockaddr FAR * addr,
int namelen
);
Parameters

s

A descriptor identifying an unbound socket.

addr

The address to assign to the socket. The sockaddr structure is defined as follows:

    struct sockaddr {

        u_short    sa_family;

        char       sa_data[14];

    };

namelen

The length of the addr.

Return Value

If no error occurs, bind returns zero. Otherwise, it returns SOCKET_ERROR, and a specific error code may be retrieved by calling WSAGetLastError.

Error Codes

WSANOTINITIALISED	A successful WSAStartup must occur before using this function.
WSAENETDOWN	The Windows Sockets implementation has detected that the network subsystem has failed.
WSAEADDRINUSE	The specified address is already in use. (See the SO_REUSEADDR socket option under setsockopt.)
WSAEFAULT	The namelen argument is too small (less than the size of a struct sockaddr).
WSAEINPROGRESS	A blocking Windows Sockets call is in progress.
WSAEAFNOSUPPORT	The specified address family is not supported by this protocol.
WSAEINVAL	The socket is already bound to an address.
WSAENOBUFS	Not enough buffers available, too many connections.
WSAENOTSOCK	The descriptor is not a socket.
Remarks

This function is used on an unconnected datagram or stream socket, before subsequent calls to the connect or listen functions. When a socket is created with socket, it exists in a name space (address family), but it has no name assigned. The bind function establishes the local association (host address/port number) of the socket by assigning a local name to an unnamed socket.

In the Internet address family, a name consists of several components. For SOCK_DGRAM and SOCK_STREAM, the name consists of three parts: a host address, the protocol number (set implicitly to UDP or TCP, respectively), and a port number which identifies the application. If an application does not care what address is assigned to it, it may specify an Internet address equal to INADDR_ANY, a port equal to 0, or both. If the Internet address is equal to INADDR_ANY, any appropriate network interface will be used; this simplifies application programming in the presence of multi-homed hosts. If the port is specified as 0, the Windows Sockets implementation will assign a unique port to the application with a value between 1024 and 5000. The application may use getsockname after bind to learn the address that has been assigned to it, but note that getsockname will not necessarily fill in the Internet address until the socket is connected, since several Internet addresses may be valid if the host is multi-homed.

If an application needs to bind to an arbitrary port outside of the range 1024 to 5000, code similar to the following can be used:

SOCKADDR_IN sin;

SOCKET s;

u_short alport = IPPORT_RESERVED;

sin.sin_family = AF_INET;

sin.sin_addr.s_addr = 0;

for (;;) {

    sin.sin_port = htons(alport);

    if (bind(s, (LPSOCKADDR)&sin, sizeof (sin)) == 0) {

        /* it worked */

    }

    if ( GetLastError != WSAEADDRINUSE) {

        /* fail */

    }

    alport--;

    if (alport == IPPORT_RESERVED/2 ) {

        /* fail--all unassigned reserved ports are */

        /* in use. */

    }

}

See Also

connect, listen, getsockname, setsockopt, socket, WSACancelBlockingCall, WSAStartup


BitBlt
 BitBlt  QuickInfo  Overview  Group

The BitBlt function performs a bit-block transfer of the color data corresponding to a rectangle of pixels from the specified source device context into a destination device context.

BOOL BitBlt(

HDC  hdcDest,	// handle of destination device context
int  nXDest,	// x-coordinate of destination rectangle's upper-left corner
int  nYDest,	// x-coordinate of destination rectangle's upper-left corner
int  nWidth,	// width of destination rectangle
int  nHeight,	// height of destination rectangle
HDC  hdcSrc,	// handle of source device context
int  nXSrc,	// x-coordinate of source rectangle's upper-left corner
int  nYSrc,	// y-coordinate of source rectangle's upper-left corner
DWORD  dwRop	// raster operation code
);
Parameters

hdcDest

Identifies the destination device context.

nXDest

Specifies the logical x-coordinate of the upper-left corner of the destination rectangle.

nYDest

Specifies the logical y-coordinate of the upper-left corner of the destination rectangle.

nWidth

Specifies the logical width of the source and destination rectangles.

nHeight

Specifies the logical height of the source and the destination rectangles.

hdcSrc

Identifies the source device context.

nXSrc

Specifies the logical x-coordinate of the upper-left corner of the source rectangle.

nYSrc

Specifies the logical y-coordinate of the upper-left corner of the source rectangle.

dwRop

Specifies a raster-operation code. These codes define how the color data for the source rectangle is to be combined with the color data for the destination rectangle to achieve the final color.

The following list shows some common raster operation codes:

Value	Description
BLACKNESS	Fills the destination rectangle using the color associated with index 0 in the physical palette. (This color is black for the default physical palette.)
DSTINVERT	Inverts the destination rectangle.
MERGECOPY	Merges the colors of the source rectangle with the specified pattern by using the Boolean AND operator.
MERGEPAINT	Merges the colors of the inverted source rectangle with the colors of the destination rectangle by using the Boolean OR operator.
NOTSRCCOPY	Copies the inverted source rectangle to the destination.
NOTSRCERASE	Combines the colors of the source and destination rectangles by using the Boolean OR operator and then inverts the resultant color.
PATCOPY	Copies the specified pattern into the destination bitmap.
PATINVERT	Combines the colors of the specified pattern with the colors of the destination rectangle by using the Boolean XOR operator.
PATPAINT	Combines the colors of the pattern with the colors of the inverted source rectangle by using the Boolean OR operator. The result of this operation is combined with the colors of the destination rectangle by using the Boolean OR operator.
SRCAND	Combines the colors of the source and destination rectangles by using the Boolean AND operator.
SRCCOPY	Copies the source rectangle directly to the destination rectangle.
SRCERASE	Combines the inverted colors of the destination rectangle with the colors of the source rectangle by using the Boolean AND operator.
SRCINVERT	Combines the colors of the source and destination rectangles by using the Boolean XOR operator.
SRCPAINT	Combines the colors of the source and destination rectangles by using the Boolean OR operator.
WHITENESS	Fills the destination rectangle using the color associated with index 1 in the physical palette. (This color is white for the default physical palette.)
Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

If a rotation or shear transformation is in effect in the source device context, BitBlt returns an error. If other transformations exist in the source device context (and a matching transformation is not in effect in the destination device context), the rectangle in the destination device context is stretched, compressed, or rotated as necessary.

If the color formats of the source and destination device contexts do not match, the BitBlt function converts the source color format to match the destination format.

When an enhanced metafile is being recorded, an error occurs if the source device context identifies an enhanced-metafile device context.

Not all devices support the BitBlt function. For more information, see the RC_BITBLT raster capability entry in GetDeviceCaps.

BitBlt returns an error if the source and destination device contexts represent different devices.

See Also

GetDeviceCaps, MaskBlt, PlgBlt, StretchBlt


BringWindowToTop
 BringWindowToTop  QuickInfo  Overview  Group

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 of window
);
Parameters

hWnd

Identifies the window to bring to the top of the Z order.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

Use BringWindowToTop to uncover any window that is partially or completely obscured by other windows.

Calling this function is similar to calling the SetWindowPos function to change a window's position in the Z order. BringWindowToTop does not make a window a top-level window.

If an application is not in the foreground and wants to be in the foreground, it should call the SetForegroundWindow function.

See Also

SetWindowPos, SetActiveWindow, SetForegroundWindow


BroadcastSystemMessage [New - Windows 95]
 BroadcastSystemMessage  QuickInfo  Overview  Group

[New - Windows 95]

The BroadcastSystemMessage function sends a message to the given recipients. The recipients can be applications, installable drivers, Windows-based network drivers, system-level device drivers, or any combination of these system components.

long BroadcastSystemMessage(

DWORD  dwFlags,
LPDWORD  lpdwRecipients,
UINT  uiMessage,
WPARAM  wParam,
LPARAM  lParam
);
Parameters

dwFlags

Option flags. Can be a combination of the following values:

Value	Meaning
BSF_FLUSHDISK	Flush the disk after each recipient processes the message.
BSF_FORCEIFHUNG	Wait for the time-out period to elapse before returning, if a recipient appears to be in a hung state.
BSF_IGNORECURRENTTASK	Do not send the message to windows that belong to the current task. This prevents an application from receiving its own message.
BSF_LPARAMPOINTER	The lParam parameter is the address of a buffer.
BSF_NOHANG	Return without waiting for the time-out period to elapse if a recipient appears to be in a hung state.
BSF_POSTMESSAGE	Post the message. Do not use in combination with BSF_LPARAMPOINTER or BSF_QUERY.
BSF_QUERY	Send the message to one recipient at a time, sending to a subsequent recipient only if the current recipient returns TRUE.
lpdwRecipients

Address of a 32-bit variable that contains and receives information about the recipients of the message. The variable can be a combination of the following values:

Value	Meaning
BSM_ALLCOMPONENTS	Broadcast to all system components.
BSM_APPLICATIONS	Broadcast to applications.
BSM_INSTALLABLEDRIVERS	Broadcast to installable drivers.
BSM_NETDRIVER	Broadcast to Windows-based network drivers.
BSM_VXDS	Broadcast to all system-level device drivers.
When the function returns, this variable receives a combination of these values identifying which recipients actually received the message.

If this parameter is NULL, the function broadcasts to all components.

uiMessage

Identifier of the system message.

wParam

32-bit message-specific value.

lParam

32-bit message-specific value. If the lpdwRecipients parameter specifies the BSF_LPARAMPOINTER value, the lParam parameter must be the address of a buffer, and the first 16-bit value in the buffer must specify the total size of the buffer, in bytes.

Return Value

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 FALSE to the corresponding message, the return value is zero.

Remarks

If BSF_QUERY is not given, the function sends the given message to all requested recipients, ignoring values returned by those recipients.

If BSF_LPARAMPOINTER is given, the function may modify the address given by the lParam parameter to make the buffer available to requested recipients. It is recommended that the buffer itself contain no addresses, because these addresses will not be modified and may not be accessible to all requested recipients.


BrowseCallbackProc
 BrowseCallbackProc  QuickInfo

Specifies an application-defined callback function used with the SHBrowseForFolder function. The browse dialog box calls this function to notify it about events. The BFFCALLBACK type defines a pointer to this callback function.

int BrowseCallbackProc(

HWND  hwnd,
UINT  uMsg,
LPARAM  lParam,
LPARAM  lpData
);
Parameters

hwnd

Handle of the browse dialog box. The callback function can send the following messages to this window:

BFFM_ENABLEOK	Enables the OK button if the wParam parameter is nonzero or disables it if wParam is zero.
BFFM_SETSELECTION	Selects the specified folder. The lParam parameter is the PIDL of the folder to select if wParam is FALSE, or it is the path of the folder otherwise.
BFFM_SETSTATUSTEXT	Sets the status text to the null-terminated string specified by the lParam parameter.
uMsg

Value identifying the event. This parameter can be one of the following values:

BFFM_INITIALIZED	The browse dialog box has finished initializing. lpData is NULL.
BFFM_SELCHANGED	The selection has changed. lpData is a pointer to the item identifier list for the newly selected folder.
lParam

Message-specific value. For more information, see the description of uMsg.

lpData

Application-defined value that was specified in the lParam member of the BROWSEINFO structure.

Return Value

Returns zero.

See Also

BROWSEINFO


BuildCommDCB
 BuildCommDCB  QuickInfo  Overview  Group

The BuildCommDCB function fills a specified DCB structure with values specified in a device-control string. The device-control string uses the syntax of the mode command.

BOOL BuildCommDCB(

LPCTSTR  lpDef,	// pointer to device-control string
LPDCB  lpDCB	// pointer to device-control block
);
Parameters

lpDef

Pointer to a null-terminated string that specifies device-control information. The string must have the same form as the Windows NT or MS-DOS mode command's command-line arguments. For example, the following string specifies a baud rate of 1200, no parity, 8 data bits, and 1 stop bit:

baud=1200 parity=N data=8 stop=1

The device name is ignored if it is included in the string, but it must specify a valid device, as follows:

COM1: baud=1200 parity=N data=8 stop=1

Refer to the Windows NT or MS-DOS end-user documentation for further information on mode command syntax.

lpDCB

Pointer to a DCB structure to be filled in.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The BuildCommDCB function adjusts only those members of the DCB structure that are specifically affected by the lpDef parameter, with the following exceptions:

•	If the specified baud rate is 110, the function sets the stop bits to 2 to remain compatible with the Windows NT or MS-DOS mode command.

•	By default, BuildCommDCB disables XON/XOFF and hardware flow control. To enable flow control, you must explicitly set the appropriate members of the DCB structure.

The BuildCommDCB function only fills in the members of the DCB structure. To apply these settings to a serial port, use the SetCommState function.

There are older and newer forms of the mode command syntax. The BuildCommDCB function supports both forms. However, you cannot mix the two forms together.

The newer form of the mode command syntax lets you explicitly set the values of the flow control members of the DCB structure. If you use an older form of the mode syntax, the BuildCommDCB function sets the flow control members of the DCB structure, as follows:

•	For a string such as 96,n,8,1 or any other older-form mode string that doesn't end with an x or a p:

fInX, fOutX,fOutXDsrFlow,and fOutXCtsFlow are all set to FALSE

fDtrControl is set to DTR_CONTROL_ENABLE

fRtsControl is set to RTS_CONTROL_ENABLE

•	For a string such as 96,n,8,1,x or any other older-form mode string that finishes with an x:

fInX, fOutX are both set to TRUE

fOutXDsrFlow,fOutXCtsFlow are both set to FALSE.

fDtrControl is set to DTR_CONTROL_ENABLE

fRtsControl is set to RTS_CONTROL_ENABLE

•	For a string such as 96,n,8,1,p or any other older-form mode string that finishes with a p:

fInX, fOutX are both set to FALSE

fOutXDsrFlow,fOutXCtsFlow are both set to TRUE.

fDtrControl is set to DTR_CONTROL_HANDSHAKE

fRtsControl is set to RTS_CONTROL_HANDSHAKE

See Also

DCB, SetCommState


BuildCommDCBAndTimeouts
 BuildCommDCBAndTimeouts  QuickInfo  Overview  Group

The BuildCommDCBAndTimeouts function translates a device-definition string into appropriate device-control block codes and then places these codes into a device control block. The function can also set up time-out values, including the possibility of no time-outs, for a device; the function's behavior in this regard varies based on the contents of the device-definition string.

BOOL BuildCommDCBAndTimeouts(

LPCTSTR  lpDef,	// address of the device-control string
LPDCB  lpDCB,	// address of the device-control block
LPCOMMTIMEOUTS  lpCommTimeouts	// address of comm. time-out structure
);
Parameters

lpDef

Points to a null-terminated string that specifies device-control information for the device. The function takes this string, parses it, and then sets appropriate values in the DCB structure pointed to by lpDCB.

lpDCB

Points to a DCB structure that the function fills with information from the device-control information string pointed to by lpDef. This DCB structure defines the control settings for a communications device.

lpCommTimeouts

Points to a COMMTIMEOUTS structure that the function can use to set device time-out values.

The BuildCommDcbAndTimeouts function modifies its time-out setting behavior based on the presence or absence of a "TO=xxx" substring in the string specified by lpDef:

•	If that string contains the substring "TO=ON", the function sets up total read and write time-out values for the device based on the time-out structure pointed to by lpCommTimeouts.

•	If that string contains the substring "TO=OFF", the function sets up the device with no time-outs.

•	If that string contains neither of the aforementioned "TO=xxx" substrings, the function ignores the time-out structure pointed to by lpCommTimeouts. The time-out structure will not be accessed.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

BuildCommDCB, COMMTIMEOUTS, DCB, GetCommTimeouts, SetCommTimeouts


CallMsgFilter
 CallMsgFilter  QuickInfo  Overview  Group

The CallMsgFilter function passes the specified message and hook code to the hook procedures associated with the WH_SYSMSGFILTER and zhooks. A WH_SYSMSGFILTER or WH_MSGFILTER hook procedure is an application-defined callback function that examines and, optionally, modifies messages for a dialog box, message box, menu, or scroll bar.

BOOL CallMsgFilter(

LPMSG  lpMsg,	// address of structure with message data
int  nCode	// hook code
);
Parameters

lpMsg

Points to an MSG structure that contains the message to be passed to the hook procedures.

nCode

Specifies an application-defined code used by the hook procedure to determine how to process the message. The code must not have the same value as system-defined hook codes (MSGF_ and HC_) associated with the WH_SYSMSGFILTER and WH_MSGFILTER hooks.

Return Value

If the application should process the message further, the return value is zero; otherwise, it is nonzero.

Remarks

Windows calls CallMsgFilter to enable applications to examine and control the flow of messages during internal processing of dialog boxes, message boxes, menus, and scroll bars, or when the user activates a different window by pressing the ALT+TAB key combination.

An application installs a hook procedure by using the SetWindowsHookEx function.

See Also

MessageProc, MSG, SetWindowsHookEx, SysMsgProc


CallNamedPipe
 CallNamedPipe  QuickInfo  Overview  Group

The CallNamedPipe function connects to a message-type pipe (and waits if an instance of the pipe is not available), writes to and reads from the pipe, and then closes the pipe.

BOOL CallNamedPipe(

LPCTSTR  lpNamedPipeName,	// address of pipe name
LPVOID  lpInBuffer,	// address of write buffer
DWORD  nInBufferSize,	// size, in bytes, of write buffer
LPVOID  lpOutBuffer,	// address of read buffer
DWORD  nOutBufferSize,	// size, in bytes, of read buffer
LPDWORD  lpBytesRead,	// address of number of bytes read
DWORD  nTimeOut	// time-out time, in milliseconds
);
Parameters

lpNamedPipeName

Points to a null-terminated string specifying the pipe name.

lpInBuffer

Points to the buffer containing the data written to the pipe.

nInBufferSize

Specifies the size, in bytes, of the write buffer.

lpOutBuffer

Points to the buffer that receives the data read from the pipe.

nOutBufferSize

Specifies the size, in bytes, of the read buffer.

lpBytesRead

Points to a 32-bit variable that receives the number of bytes read from the pipe.

nTimeOut

Specifies the number of milliseconds to wait for the named pipe to be available. In addition to numeric values, the following special values can be specified:

Value	Meaning
NMPWAIT_NOWAIT	Does not wait for the named pipe. If the named pipe is not available, the function returns an error.
NMPWAIT_WAIT_FOREVER	Waits indefinitely.
NMPWAIT_USE_DEFAULT_WAIT	Uses the default time-out specified in a call to the CreateNamedPipe function.
Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

Calling CallNamedPipe is equivalent to calling the CreateFile (or WaitNamedPipe, if CreateFile cannot open the pipe immediately), TransactNamedPipe, and CloseHandle functions. CreateFile is called with an access flag of GENERIC_READ | GENERIC_WRITE, an inherit handle flag of FALSE, and a share mode of zero (indicating no sharing of this pipe instance).

If the message written to the pipe by the server process is longer than nOutBufferSize, CallNamedPipe returns FALSE, and GetLastError returns ERROR_MORE_DATA. The remainder of the message is discarded, because CallNamedPipe closes the handle to the pipe before returning.

CallNamedPipe fails if the pipe is a byte-type pipe.

See Also

CloseHandle, CreateFile, CreateNamedPipe, TransactNamedPipe, WaitNamedPipe


CallNextHookEx
 CallNextHookEx  QuickInfo  Overview  Group

The CallNextHookEx function passes the hook information to the next hook procedure in the current hook chain. This function supersedes the DefHookProc function.

LRESULT CallNextHookEx(

HHOOK  hhk,	// handle of current hook
int  nCode,	// hook code passed to hook procedure
WPARAM  wParam,	// value passed to hook procedure
LPARAM  lParam	// value passed to hook procedure
);
Parameters

hhk

Identifies the current hook. An application receives this handle as a result of a previous call to the SetWindowsHookEx function.

nCode

Specifies the hook code passed to the current hook procedure. The next hook procedure uses this code to determine how to process the hook information.

wParam

Specifies the wParam value passed to the current hook procedure. The meaning of this parameter depends on the type of hook associated with the current hook chain.

lParam

Specifies the lParam value passed to the current hook procedure. The meaning of this parameter depends on the type of hook associated with the current hook chain.

Return Value

If the function succeeds, the return value is the value returned by the next hook procedure in the chain. The current hook procedure must also return this value. The meaning of the return value depends on the hook type. For more information, see the descriptions of the individual hook procedures.

Remarks

Hook procedures are installed in chains for particular hook types. CallNextHookEx calls the next hook in the chain.

Calling CallNextHookEx is optional. A hook procedure can call this function either before or after processing the hook information. If a hook procedure does not call CallNextHookEx, Windows does not call the hook procedures installed before the current hook procedure was installed.

See Also

SetWindowsHook, SetWindowsHookEx, UnhookWindowsHook, UnhookWindowsHookEx


CallWindowProc
 CallWindowProc  QuickInfo  Overview  Group

The CallWindowProc function passes message information to the specified window procedure.

LRESULT CallWindowProc(

WNDPROC  lpPrevWndFunc,	// address of previous procedure
HWND  hWnd,	// handle of window
UINT  Msg,	// message
WPARAM  wParam,	// first message parameter
LPARAM  lParam	// second message parameter
);
Parameters

lpPrevWndFunc

Pointer to the previous window procedure.

If this value is obtained by calling the GetWindowLong function with the nIndex parameter set to GWL_WNDPROC or DWL_DLGPROC, it is actually either the address of a window or dialog box procedure, or a handle representing that address.

hWnd

Identifies the window procedure to receive the message.

Msg

Specifies the message.

wParam

Specifies additional message-specific information. The contents of this parameter depend on the value of the Msg parameter.

lParam

Specifies additional message-specific information. The contents of this parameter depend on the value of the Msg parameter.

Return Value

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 Windows to call the new window procedure instead of the previous one. An application must pass any messages not processed by the new window procedure to the previous window procedure by calling CallWindowProc. This allows the application to create a chain of window procedures.

If STRICT is defined, the lpPrevWndFunc parameter has the data type WNDPROC. The WNDPROC type is declared as follows:

LRESULT (CALLBACK* WNDPROC) (HWND, UINT, WPARAM, LPARAM);

If STRICT is not defined, the lpPrevWndFunc parameter has the data type FARPROC. The FARPROC type is declared as follows:

int (FAR WINAPI * FARPROC) ()

In C, the FARPROC declaration indicates a callback function that has an unspecified parameter list. In C++, however, the empty parameter list in the declaration indicates that a function has no parameters. This subtle distinction can break careless code. Following is one way to handle this situation:

#ifdef STRICT

  WNDPROC MyWindowProcedure

#else

  FARPROC MyWindowProcedure

#endif

...

    lResult = CallWindowProc(MyWindowProcedure, ...) ;

For further information about functions declared with empty argument lists, refer to The C++ Programming Language, Second Edition, by Bjarne Stroustrup.

Windows NT: The CallWindowProc function handles Unicode-to-ANSI conversion. You don't get the conversion if you call the window procedure directly.

See Also

FARPROC, GetWindowLong, SetClassLong, SetWindowLong, WNDPROC


CallWndProc
 CallWndProc  QuickInfo  Overview  Group

The CallWndProc hook procedure is an application-defined or library-defined callback function that the system calls whenever the SendMessage function is called. Before passing the message to the destination window procedure, the system passes the message to the hook procedure. The hook procedure can examine the message; it cannot modify it.

LRESULT CALLBACK CallWndProc(

int  nCode,	// hook code
WPARAM  wParam,	// current-process flag
LPARAM  lParam	// address of structure with message data
);
Parameters

nCode

Specifies whether the hook procedure must process the message. If nCode is HC_ACTION, the hook procedure must process the message. If nCode is less than zero, the hook procedure must pass the message to the CallNextHookEx function without further processing and should return the value returned by CallNextHookEx.

wParam

Specifies whether the message is sent by the current process. If the message is sent by the current process, it is nonzero; otherwise, it is NULL.

lParam

Points to a CWPSTRUCT structure that contains details about the message.

Return Value

The return value should be zero.

Remarks

The CallWndProc hook procedure can examine the message, but it cannot modify it. After the hook procedure returns control to the system, the message is passed to the window procedure.

An application installs the hook procedure by specifying the WH_CALLWNDPROC hook type and the address of the hook procedure in a call to the SetWindowsHookEx function.

CallWndProc is a placeholder for the application-defined or library-defined function name.

See Also

CallNextHookEx, CWPSTRUCT, SendMessage, SetWindowsHookEx


CallWndRetProc [New - Windows 95]
 CallWndRetProc  QuickInfo

[New - Windows 95]

The CallWndRetProc hook procedure is an application-defined or library-defined callback function the system calls after the SendMessage function is called. After passing the message to the destination window procedure, the system passes the message to the hook procedure. The hook procedure can examine the message; it cannot modify it.

LRESULT CALLBACK CallWndRetProc(

int  nCode,	// hook code
WPARAM  wParam,	// current-process flag
LPARAM  lParam	// address of structure with message data
);
Parameters

nCode

Specifies whether the hook procedure must process the message. If nCode is HC_ACTION, the hook procedure must process the message. If nCode is less than zero, the hook procedure must pass the message to the CallNextHookEx function without further processing and should return the value returned by CallNextHookEx.

wParam

Specifies whether the message is sent by the current process. If the message is sent by the current process, it is nonzero; otherwise, it is NULL.

lParam

Points to a CWPRETSTRUCT structure that contains details about the message.

Return Value

The return value should be zero.

Remarks

An application installs the hook procedure by specifying the WH_CALLWNDPROCRET hook type and the address of the hook procedure in a call to the SetWindowsHookEx function.

CallWndRetProc is a placeholder for the application-defined or library-defined function name.

See Also

CallNextHookEx, CallWndProc, CWPRETSTRUCT, SendMessage, SetWindowsHookEx


CancelDC
 CancelDC  QuickInfo  Overview  Group

The CancelDC function cancels any pending operation on the specified device context (DC).

BOOL CancelDC(

HDC  hdc	// handle of device context
);
Parameters

hdc

Identifies the DC.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

The CancelDC function is used by multithreaded applications to cancel lengthy drawing operations. If thread A initiates a lengthy drawing operation, thread B may cancel that operation by calling this function.

If an operation is canceled, the affected thread returns an error and the result of its drawing operation is undefined. The results are also undefined if no drawing operation was in progress when the function was called.

See Also

CreateThread, GetCurrentThread


CascadeWindows [New - Windows 95]
 CascadeWindows  QuickInfo

[New - Windows 95]

The CascadeWindows function cascades the specified windows or the child windows of the specified parent window.

WORD WINAPI CascadeWindows(

HWND hwndParent,	// handle of parent window
UINT wHow,	// types of windows not to arrange
CONST RECT * lpRect,	// rectangle to arrange windows in
UINT cKids,	// number of windows to arrange
const HWND FAR * lpKids	// array of window handles
);
Parameters

hwndParent

Identifies the parent window. If this parameter is NULL, the desktop window is assumed.

wHow

Specifies a cascade flag. The only flag currently available, MDITILE_SKIPDISABLED, prevents disabled MDI child windows from being cascaded.

lpRect

Points to a SMALL_RECT structure that specifies the rectangular area, in screen coordinates, within which the windows are arranged. This parameter can be NULL, in which case the client area of the parent window is used.

cKids

Specifies the number of elements in the array specified by the lpKids parameter. This parameter is ignored if lpKids is NULL.

lpKids

Points to an array of window handles identifying the windows to arrange. If this parameter is NULL, the child windows of the specified parent window (or of the desktop window) are arranged.

Return Value

If the function succeeds, the return value is the number of windows arranged.

If the function fails, the return value is zero.

See Also

SMALL_RECT


Catch
 Catch  Overview  Group

The Catch function is not implemented in the Win32 API.

Structured exception handling is built into the Win32 API. For more information about structured exception handling, see Structured Exception Handling.


CBTProc
 CBTProc  QuickInfo  Overview  Group

The CBTProc hook procedure is an application-defined or library-defined callback function that the system calls before activating, creating, destroying, minimizing, maximizing, moving, or sizing a window; before completing a system command; before removing a mouse or keyboard event from the system message queue; before setting the keyboard focus; or before synchronizing with the system message queue. The value returned by the hook procedure determines whether Windows allows or prevents one of these operations. A computer-based training (CBT) application uses this hook procedure to receive useful notifications from the system.

LRESULT CALLBACK CBTProc(

int  nCode,	// hook code
WPARAM  wParam,	// depends on hook code
LPARAM  lParam	// depends on hook code
);
Parameters

nCode

Specifies a code that the hook procedure uses to determine how to process the message. This parameter can be one of the following values:

Value	Meaning
HCBT_ACTIVATE	The system is about to activate a window.
HCBT_CLICKSKIPPED	The system has removed a mouse message from the system message queue. Upon receiving this hook code, a CBT application must install a WH_JOURNALPLAYBACK hook procedure in response to the mouse message.
HCBT_CREATEWND	A window is about to be created. The system calls the hook procedure before sending the WM_CREATE or WM_NCCREATE message to the window. If the hook procedure returns a nonzero value, the system destroys the window; the CreateWindow function returns NULL, but the WM_DESTROY message is not sent to the window. If the hook procedure returns zero, the window is created normally.
	At the time of the HCBT_CREATEWND notification, the window has been created, but its final size and position may not have been determined and its parent window may not have been established. It is possible to send messages to the newly created window, although it has not yet received WM_NCCREATE or WM_CREATE messages. It is also possible to change the position in the Z order of the newly created window by modifying the hwndInsertAfter member of the CBT_CREATEWND structure.
HCBT_DESTROYWND	A window is about to be destroyed.
HCBT_KEYSKIPPED	The system has removed a keyboard message from the system message queue. Upon receiving this hook code, a CBT application must install a WH_JOURNALPLAYBACK hook procedure in response to the keyboard message.
HCBT_MINMAX	A window is about to be minimized or maximized.
HCBT_MOVESIZE	A window is about to be moved or sized.
HCBT_QS	The system has retrieved a WM_QUEUESYNC message from the system message queue.
HCBT_SETFOCUS	A window is about to receive the keyboard focus.
HCBT_SYSCOMMAND	A system command is about to be carried out. This allows a CBT application to prevent task switching by means of hot keys.
If nCode is less than zero, the hook procedure must pass the message to the CallNextHookEx function without further processing and should return the value returned by CallNextHookEx.

wParam

Depends on the nCode parameter. For details, see the following Remarks section.

lParam

Depends on the nCode parameter. For details, see the following Remarks section.

Return Value

For operations corresponding to the following CBT hook codes, the return value must be 0 to allow the operation, or 1 to prevent it:

HCBT_ACTIVATE
HCBT_CREATEWND
HCBT_DESTROYWND
HCBT_MINMAX
HCBT_MOVESIZE
HCBT_SETFOCUS
HCBT_SYSCOMMAND

For operations corresponding to the following CBT hook codes, the return value is ignored:

HCBT_CLICKSKIPPED
HCBT_KEYSKIPPED
HCBT_QS

Remarks

The hook procedure should not install a WH_JOURNALPLAYBACK hook procedure except in the situations described in the preceding list of hook codes.

This hook procedure must be in a dynamic-link library (DLL). An application installs the hook procedure by specifying the WH_CBT hook type and the address of the hook procedure in a call to the SetWindowsHookEx function.

The following table describes the wParam and lParam parameters for each HCBT_ hook code:

Value	wParam	lParam
HCBT_ACTIVATE	Specifies the handle of the window about to be activated.	Specifies a long pointer to a CBTACTIVATESTRUCT structure containing the handle of the active window and specifies whether the activation is changing because of a mouse click.
HCBT_CLICKSKIPPED	Identifies the mouse message removed from the system message queue.	Specifies a long pointer to a MOUSEHOOKSTRUCT structure containing the hit-test code and the handle of the window for which the mouse message is intended.  The HCBT_CLICKSKIPPED value is sent to a CBTProc hook procedure only if a WH_MOUSE hook is installed. For a list of hit-test codes, see WM_NCHITTEST .
HCBT_CREATEWND	Specifies the handle of the new window.	Specifies a long pointer to a CBT_CREATEWND structure containing initialization parameters for the window. The parameters include the coordinates and dimensions of the window. By changing these parameters, a CBTProc hook procedure can set the initial size and position of the window.
HCBT_DESTROYWND	Specifies the handle of the window about to be destroyed.	Is undefined and must be set to zero.
HCBT_KEYSKIPPED	Identifies the virtual-key code.	Specifies the repeat count, scan code, key-transition code, previous key state, and context code. The HCBT_KEYSKIPPED value is sent to a CBTProc hook procedure only if a WH_KEYBOARD hook is installed. For more information, see the WM_KEYUP or WM_KEYDOWN message.
HCBT_MINMAX	Specifies the handle of the window being minimized or maximized.	Specifies, in the low-order word, a show-window value (SW_) specifying the operation. For a list of show-window values, see the ShowWindow. The high-order word is undefined.
HCBT_MOVESIZE	Specifies the handle of the window to be moved or sized.	Specifies a long pointer to a RECT structure containing the coordinates of the window. By changing the values in the structure, a CBTProc hook procedure can set the final coordinates of the window.
HCBT_QS	Is undefined and must be zero.	Is undefined and must be zero.
HCBT_SETFOCUS	Specifies the handle of the window gaining the keyboard focus.	Specifies the handle of the window losing the keyboard focus.
HCBT_SYSCOMMAND	Specifies a system-command value (SC_) specifying the system command. For more information about system-command values, see WM_SYSCOMMAND.	Contains the same data as the lParam value of a WM_SYSCOMMAND message: If a system menu command is chosen with the mouse, the low-order word contains the x-coordinate of the cursor, in screen coordinates, and the high-order word contains the y-coordinate; otherwise, the parameter is not used.
CBTProc is a placeholder for the application-defined or library-defined function name.

See Also

CallNextHookEx, CreateWindow, SetWindowsHookEx, WM_SYSCOMMAND


ChangeClipboardChain
 ChangeClipboardChain  QuickInfo  Overview  Group

The ChangeClipboardChain function removes a specified window from the chain of clipboard viewers.

BOOL ChangeClipboardChain(

HWND  hWndRemove,	// handle of window to remove
HWND  hWndNewNext	// handle of next window
);
Parameters

hWndRemove

Identifies the window to be removed from the chain. The handle must have been passed to the SetClipboardViewer function.

hWndNewNext

Identifies the window that follows the hWndRemove window in the clipboard viewer chain. (This is the handle returned by SetClipboardViewer, unless the sequence was changed in response to a WM_CHANGECBCHAIN message.)

Return Value

The return value indicates the result of passing the WM_CHANGECBCHAIN message to the windows in the clipboard viewer chain. Because a window in the chain typically returns FALSE when it processes WM_CHANGECBCHAIN, the return value from ChangeClipboardChain is typically FALSE. If there is only one window in the chain, the return value is typically TRUE.

Remarks

The window identified by hWndNewNext replaces the hWndRemove window in the chain. The SetClipboardViewer function sends a WM_CHANGECBCHAIN message to the first window in the clipboard viewer chain.

See Also

SetClipboardViewer, WM_CHANGECBCHAIN


ChangeDisplaySettings
 ChangeDisplaySettings  QuickInfo  Overview  Group

The ChangeDisplaySettings function changes the display settings to the specified graphics mode.

LONG ChangeDisplaySettings(

LPDEVMODE  lpDevMode,
DWORD  dwflags
);
Parameters

lpDevMode

Points to a DEVMODE structure that describes the graphics mode to switch to. The dmSize member must be initialized to the size, in bytes, of the DEVMODE structure. The following fields in the DEVMODE structure are used:

Member	Meaning
dmBitsPerPel	Bits per pixel
dmPelsWidth	Pixel width
dmPelsHeight	Pixel height
dmDisplayFlags	Mode flags
dmDisplayFrequency	Mode frequency
In addition to setting a value in one or more of the preceding DEVMODE members, you must also set the appropriate flags in the dmFields member. The flags indicate which members of the DEVMODE structure are used for the display settings change. If the appropriate bit is not set in dmFields, the display setting will not be changed. Set one or more of the following flags:

Flag	Meaning
DM_BITSPERPEL	Use the dmBitsPerPel value.
DM_PELSWIDTH	Use the dmPelsWidth value.
DM_PELSHEIGHT	Use the dmPelsHeight value.
DM_DISPLAYFLAGS	Use the dmDisplayFlags value.
DM_DISPLAYFREQENCY	Use the dmDisplayFrequency value.
If lpDevMode is NULL, all the values currently in the registry will be used for the display setting. Passing NULL for the lpDevMode parameter is the easiest way to return to the default mode after a dynamic mode change.

dwflags

Indicates how the graphics mode should be changed. May be one of the following:

Flag	Meaning
0	The graphics mode for the current screen will be changed dynamically.
CDS_UPDATEREGISTRY	The graphics mode for the current screen will be changed dynamically and the graphics mode will be updated in the registry. The mode information is stored in the USER profile.
CDS_TEST	The system tests if the requested graphics mode could be set.
If CDS_UPDATEREGISTRY is specified and it is possible to change the graphics mode dynamically, the information is stored in the registry and DISP_CHANGE_SUCCESSFUL is returned. If it is not possible to change the graphics mode dynamically, the information is stored in the registry and DISP_CHANGE_RESTART is returned. If the information could not be stored in the registry, the graphics mode is not changed and DISP_CHANGE_NOTUPDATED is returned.

Specifying CDS_TEST allows an application to determine which graphics modes are actually valid, without causing the system to change to that graphics mode.

Return Value

Returns one of the following values:

Value	Meaning
DISP_CHANGE_SUCCESSFUL	The settings change was successful.
DISP_CHANGE_RESTART	The computer must be restarted in order for the graphics mode to work.
DISP_CHANGE_BADFLAGS	An invalid set of flags was passed in.
DISP_CHANGE_FAILED	The display driver failed the specified graphics mode.
DISP_CHANGE_BADMODE	The graphics mode is not supported.
DISP_CHANGE_NOTUPDATED	Unable to write settings to the registry.
Remarks

Using the DEVMODE returned by the EnumDisplaySettings function ensures that the DEVMODE passed to ChangeDisplaySettings is valid and contains only values supported by the display driver.

When the display mode is changed dynamically, the WM_DISPLAYCHANGE message is sent to all running applications with the following message parameters:

Parameter	Meaning
wParam	New bits per pixel
LOWORD(lParam)	New pixel width
HIWORD(lParam)	New pixel height
See Also

CreateDC, DEVMODE, EnumDisplaySettings, WM_DISPLAYCHANGE


ChangeMenu
 ChangeMenu  QuickInfo  Overview  Group

The ChangeMenu function has been replaced by the following specialized functions, which are available on both Windows NT and Windows 95:

Function	Description
AppendMenu	Appends a menu item to the end of a menu.
InsertMenu	Inserts a menu item into a menu.
ModifyMenu	Modifies a menu item in a menu.
RemoveMenu	Removes a menu item from a menu; if it is a pop-up item, the corresponding pop-up menu is not destroyed.
Windows 95 only:

Instead of using AppendMenu, InsertMenu, and ModifyMenu, applications written exclusively for Window 95 should use the following new functions, which are available only on Windows 95.

Function	Description
GetMenuItemInfo	Windows 95 only: Gets information about a menu item.
InsertMenuItem	Windows 95 only: Inserts a new menu item at the specified position in a menu bar or pop-up menu.
SetMenuItemInfo	Windows 95 only: Changes information about a menu item.
Applications written for versions earlier than Windows 3.0 can continue to call ChangeMenu . Applications written for Windows versions 3.0 and later should call these new functions.


ChangeSelector
 ChangeSelector  Overview  Group

The ChangeSelector function is not implemented in the Win32 API. Win32-based applications running on Windows NT can use the VirtualLock and VirtualUnlock functions.


ChangeServiceConfig
 ChangeServiceConfig  QuickInfo  Overview  Group

The ChangeServiceConfig function changes the configuration parameters of a service.

BOOL ChangeServiceConfig(

SC_HANDLE  hService,	// handle of service
DWORD  dwServiceType,	// type of service
DWORD  dwStartType,	// when to start service
DWORD  dwErrorControl,	// severity if service fails to start
LPCTSTR  lpBinaryPathName,	// address of service binary file name
LPCTSTR  lpLoadOrderGroup,	// address of load ordering group name
LPDWORD  lpdwTagId,	// address of variable to get tag identifier
LPCTSTR  lpDependencies,	// address of array of dependency names
LPCTSTR  lpServiceStartName,	// address of account name of service
LPCTSTR  lpPassword,	// address of password for service account
LPCTSTR  lpDisplayName	// address of display name
);
Parameters

hService

Identifies the service. This handle is returned by the OpenService or CreateService function and must have SERVICE_CHANGE_CONFIG access.

dwServiceType

A set of bit flags that specify the type of service. Specify SERVICE_NO_CHANGE if you are not changing the existing service type; otherwise, specify one of the following service type flags to indicate the service type. In addition, if you specify either of the SERVICE_WIN32 flags, you can also specify the SERVICE_INTERACTIVE_PROCESS flag to enable the service process to interact with the desktop.

Value	Meaning
SERVICE_WIN32_OWN_PROCESS	A service type flag that specifies a Win32 service that runs in its own process.
SERVICE_WIN32_SHARE_PROCESS	A service type flag that specifies a Win32 service that shares a process with other services.
SERVICE_KERNEL_DRIVER	A service type flag that specifies a Windows NT device driver.
SERVICE_FILE_SYSTEM_DRIVER	A service type flag that specifies a Windows NT file system driver.
SERVICE_INTERACTIVE_PROCESS	A flag that enables a Win32 service process to interact with the desktop.
dwStartType

Specifies when to start the service. This value can be the service type SERVICE_NO_CHANGE if the existing start type is not modified, or one of the following values can be specified:

Value	Meaning
SERVICE_BOOT_START	Specifies a device driver started by the operating system loader. This value is valid only if the service type is SERVICE_KERNEL_DRIVER or SERVICE_FILE_SYSTEM_DRIVER.
SERVICE_SYSTEM_START	Specifies a device driver started by the IoInitSystem function. This value is valid only if the service type is SERVICE_KERNEL_DRIVER or SERVICE_FILE_SYSTEM_DRIVER.
SERVICE_AUTO_START	Specifies a device driver or Win32 service started by the service control manager automatically during system startup.
SERVICE_DEMAND_START	Specifies a device driver or Win32 service started by the service control manager when a process calls the StartService function.
SERVICE_DISABLED	Specifies a device driver or Win32 service that can no longer be started.
dwErrorControl

Specifies the severity of the error if this service fails to start during startup, and determines the action taken by the startup program if failure occurs. One of the following values can be specified:

Value	Meaning
SERVICE_ERROR_IGNORE	The startup (boot) program logs the error but continues the startup operation.
SERVICE_ERROR_NORMAL	The startup program logs the error and puts up a message box pop-up but continues the startup operation.
SERVICE_ERROR_SEVERE	The startup program logs the error. If the last-known-good configuration is being started, the startup operation continues. Otherwise, the system is restarted with the last-known-good configuration.
SERVICE_ERROR_CRITICAL	The startup program logs the error, if possible. If the last-known-good configuration is being started, the startup operation fails. Otherwise, the system is restarted with the last-known good configuration.
SERVICE_NO_CHANGE	The existing StartType value is not to be changed.
lpBinaryPathName

Points to a null-terminated string that contains the fully qualified path to the service binary file. If the pointer is NULL, the path is not modified.

lpLoadOrderGroup

Points to a null-terminated string that names the load ordering group of which this service is a member. If the pointer is NULL, the group is not modified. If it points to an empty string, the service does not belong to a group.

The registry has a list of load ordering groups located at

HKEY_LOCAL_MACHINES\System\CurrentControlSet
\Control\ServiceGroupOrder.

The startup program uses this list to load groups of services in a specified order with respect to the other groups in the list. You can place a service in a group so that another service can depend on the group.

The order in which a service starts is determined by the following criteria:

1.	The order of groups in the registry's load-ordering group list. Services in groups in the load-ordering group list are started first, followed by services in groups not in the load-ordering group list, and then services that do not belong to a group.

2.	The service's dependencies listed in the lpDependencies parameter and the dependencies of other services dependent on the service.

lpdwTagId

Points to a 32-bit variable that receives a unique tag value for this service in the group specified in the lpLoadOrderGroup parameter. If no tag is requested, this parameter can be NULL.

You can use a tag for ordering service startup within a load ordering group by specifying a tag order vector in the registry located at

HKEY_LOCAL_MACHINE\System\CurrentControlSet
\Control\GroupOrderList.

Tags are only evaluated for SERVICE_KERNEL_DRIVER and SERVICE_FILE_SYSTEM_DRIVER type services that have SERVICE_BOOT_START or SERVICE_SYSTEM_START start types.

lpDependencies

Points to an array of null-separated names of services or load ordering groups that must start before this service. The array is double null-terminated. If the pointer is NULL, the dependencies are not modified. If it points to an empty string, the service has no dependencies. If a group name is specified, it must be prefixed by the SC_GROUP_IDENTIFIER character (defined in the WINSVC.H files) to differentiate it from a service name, because services and service groups share the same name space. Dependency on a service means that this service can only run if the service it depends on is running. Dependency on a group means that this service can run if at least one member of the group is running after an attempt to start all members of the group.

lpServiceStartName

Points to a null-terminated string. If NULL is specified, the name is not modified. If the service type is SERVICE_WIN32_OWN_PROCESS, this name is the account name in the form of "DomainName\Username", which the service process will be logged on as when it runs. If the account belongs to the built-in domain, ".\Username" can be specified. Services of type SERVICE_WIN32_SHARE_PROCESS are not allowed to specify an account other than LocalSystem.

If the service type is SERVICE_KERNEL_DRIVER or SERVICE_FILE_SYSTEM_DRIVER, this name is the Windows NT driver object name (that is, \FileSystem\Rdr or \Driver\Xns), which the input and output (I/O) system uses to load the device driver. If NULL is specified, the driver is run with a default object name created by the I/O system, based on the service name.

lpPassword

Points to a null-terminated string that contains the password to the account name specified by the lpServiceStartName parameter if the service type is SERVICE_WIN32_OWN_PROCESS or SERVICE_WIN32_SHARE_PROCESS. If the pointer is NULL, the password is not modified. If it points to an empty string, the service has no password. If the service type is SERVICE_KERNEL_DRIVER or SERVICE_FILE_SYSTEM_DRIVER, this parameter is ignored.

lpDisplayName

Points to a null-terminated string that is to be used by user interface programs to identify the service. This string has a maximum length of 256 characters. The name is case-preserved in the Service Control Manager. Display name comparisons are always case-insensitive.

Return Value

If the function succeeds, the return value is TRUE.

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

Errors

The following error codes may be set by the service control manager. Other error codes may be set by the registry functions that are called by the service control manager.

Value	Meaning
ERROR_ACCESS_DENIED
	The specified handle was not opened with SERVICE_CHANGE_CONFIG access.
ERROR_CIRCULAR_DEPENDENCY
	A circular service dependency was specified.
ERROR_DUP_NAME
	The display name already exists in the service controller's database, either as a service name or as another display name.
ERROR_INVALID_HANDLE
	The specified handle is invalid.
ERROR_INVALID_PARAMETER
	A parameter that was specified is invalid.
ERROR_INVALID_SERVICE_ACCOUNT
	The account name does not exist, or a service is specified to share the same binary file as an already installed service but with an account name that is not the same as the installed service.
ERROR_SERVICE_MARKED_FOR_DELETE
	The service has been marked for deletion.
Remarks

The ChangeServiceConfig function changes the configuration information for the specified service in the service control manager database. This configuration information is initially specified by the CreateService function and can be queried (except for the password parameter) by using the QueryServiceConfig function.

Any of the configuration parameters specified for this function can be left unchanged by specifying NULL for a string parameter or SERVICE_NO_CHANGE for a doubleword parameter.

If the configuration is changed for a service that is running, with the exception of lpDisplayName, the changes do not take effect until the service is stopped.

See Also

CreateService, OpenService, QueryServiceConfig, StartService


CharLower
 CharLower  QuickInfo  Overview  Group

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. This function supersedes the AnsiLower function.

LPTSTR CharLower(

LPTSTR  lpsz	// single character or address of string
);
Parameters

lpsz

Points 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 Value

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.

Remarks

Windows NT: To make the conversion, the function uses the language driver for the current language selected by the user at setup or by using the Control Panel. If no language has been selected, Windows completes the conversion by using internal default mapping. The conversion is made based on the code page associated with the process locale.

Windows 95: 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 the Control Panel. Windows 95 does not have language drivers.

See Also

CharLowerBuff, CharUpper, CharUpperBuff


CharLowerBuff
 CharLowerBuff  QuickInfo  Overview  Group

The CharLowerBuff function converts uppercase characters in a buffer to lowercase characters. The function converts the characters in place. The function supersedes the AnsiLowerBuff function.

DWORD CharLowerBuff(

LPTSTR  lpsz,	// points to buffer containing characters to process
DWORD  cchLength	// number of bytes or characters to process
);
Parameters

lpsz

Points to a buffer containing one or more characters to process.

cchLength

Specifies the size, in bytes (ANSI version) or characters (Unicode version), of the buffer pointed to by lpsz.

The function examines each character, and converts uppercase characters to lowercase characters. The function examines the number of bytes or characters indicated by cchLength, even if one or more characters are null characters.

Return Value

If the function succeeds, the return value is the number of bytes (ANSI version) or characters (Unicode version) processed.

For example, if CharLowerBuff("Acme of Operating Systems", 10) succeeds, the return value is 10.

Remarks

Windows NT: To make the conversion, the function uses the language driver for the current language selected by the user at setup or by using the Control Panel. If no language has been selected, Windows completes the conversion by using internal default mapping. The conversion is made based on the code page associated with the process locale.

Windows 95: 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 the Control Panel. Windows 95 does not have language drivers.

See Also

CharLower, CharUpper, CharUpperBuff


CharNext
 CharNext  QuickInfo  Overview  Group

The CharNext function returns a pointer to the next character in a string. This function supersedes the AnsiNext function.

LPTSTR CharNext(

LPCTSTR  lpsz	// address of current character
);
Parameters

lpsz

Points to a character in a null-terminated string.

Return Value

If the function succeeds, 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 lpsz points to the terminating null character, the return value is equal to lpsz.

See Also

CharNextExA, CharPrev


CharNextExA
 CharNextExA  QuickInfo

The CharNextExA function retrieves the address of the next character in a string. This function can handle strings consisting of either single- or multi-byte characters.

LPSTR CharNextExA(

WORD    CodePage,	// identifier of the code page
LPCSTR  lpCurrentChar ,	// address of current character
DWORD   dwFlags	// reserved; must be zero
);
Parameters

CodePage

Identifier of the code page to use to check lead-byte ranges. Can be one of the code-page values given 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

Pointer to a character in a null-terminated string.

dwFlags

Reserved; must be zero.

Return Value

If the function succeeds, 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.

See Also

CharNext, CharPrevExA


CharPrev
 CharPrev  QuickInfo  Overview  Group

The CharPrev function returns a pointer to the preceding character in a string. This function supersedes the AnsiPrev function.

LPTSTR CharPrev(

LPCTSTR  lpszStart,	// address of first character
LPCTSTR  lpszCurrent	// address of current character
);
Parameters

lpszStart

Points to the beginning of the string.

lpszCurrent

Points to a character in a null-terminated string.

Return Value

If the function succeeds, 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.

See Also

CharNext, CharPrevExA


CharPrevExA
 CharPrevExA  QuickInfo

The CharPrevExA function retrieves the address of 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,	// address of first character
LPCSTR  lpCurrentChar,	// address of current character
DWORD   dwFlags	// reserved; must be zero
);
Parameters

CodePage

Identifier of the code page to use to check lead-byte ranges. Can be one of the code-page values given 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

Pointer to the beginning of the string.

lpCurrentChar

Pointer to a character in a null-terminated string.

dwFlags

Reserved; must be zero.

Return Value

If the function succeeds, 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.

See Also

CharNextExA, CharPrev


CharToOem
 CharToOem  QuickInfo  Overview  Group

The CharToOem function translates a string into the OEM-defined character set. (OEM stands for original equipment manufacturer.) This function supersedes the AnsiToOem function.

BOOL CharToOem(

LPCTSTR  lpszSrc,	// address of string to translate
LPSTR  lpszDst	// address of translated string
);
Parameters

lpszSrc

Points to the null-terminated string to translate.

lpszDst

Points 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 Value

The return value is always TRUE.

See Also

CharToOemBuff, OemToChar, OemToCharBuff


CharToOemBuff
 CharToOemBuff  QuickInfo  Overview  Group

The CharToOemBuff function translates a specified number of characters in a string into the OEM-defined character set. (OEM stands for original equipment manufacturer.) This function supersedes the AnsiToOemBuff function.

BOOL CharToOemBuff(

LPCTSTR  lpszSrc,	// address of string to translate
LPSTR  lpszDst,	// address of translated string
DWORD  cchDstLength	// length of string to translate, in characters
);
Parameters

lpszSrc

Points to the null-terminated string to translate.

lpszDst

Points 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

Specifies the number of characters to translate in the string identified by the lpszSrc parameter.

Return Value

The return value is always TRUE.

See Also

CharToOem, OemToChar, OemToCharBuff


CharUpper
 CharUpper  QuickInfo  Overview  Group

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. This function supersedes the AnsiUpper function.

LPTSTR CharUpper(

LPTSTR  lpsz	// single character or address of string
);
Parameters

lpsz

Points 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 Value

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.

Remarks

Windows NT: To make the conversion, the function uses the language driver for the current language selected by the user at setup or by using the Control Panel. If no language has been selected, Windows completes the conversion by using internal default mapping. The conversion is made based on the code page associated with the process locale.

Windows 95: 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 the Control Panel. Windows 95 does not have language drivers.

See Also

CharLower, CharLowerBuff, CharUpperBuff


CharUpperBuff
 CharUpperBuff  QuickInfo  Overview  Group

The CharUpperBuff function converts lowercase characters in a buffer to uppercase characters. The function converts the characters in place. The function supersedes the AnsiUpperBuff function.

DWORD CharUpperBuff(

LPTSTR  lpsz,	// points to buffer containing characters to process
DWORD  cchLength	// number of characters to process
);
Parameters

lpsz

Points to a buffer containing one or more characters to process.

cchLength

Specifies the size, in bytes (ANSI version) or characters (Unicode version), of the buffer pointed to by lpsz.

The function examines each character, and converts lowercase characters to uppercase characters. The function examines the number of bytes or characters indicated by cchLength, even if one or more characters are null characters.

Return Value

If the function succeeds, the return value is the number of bytes (ANSI version) or characters (Unicode version) processed.

For example, if CharUpperBuff("Zenith of API Sets", 10) succeeds, the return value is 10.

Remarks

Windows NT: To make the conversion, the function uses the language driver for the current language selected by the user at setup or by using the Control Panel. If no language has been selected, Windows completes the conversion by using internal default mapping. The conversion is made based on the code page associated with the process locale.

Windows 95: 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 the Control Panel. Windows 95 does not have language drivers.

See Also

CharLower, CharLowerBuff, CharUpper


CheckColorsInGamut [New - Windows 95]
 CheckColorsInGamut  QuickInfo  Overview  Group

[New - Windows 95]

The CheckColorsInGamut function indicates whether the specified color values are within the gamut of the specified device.

BOOL CheckColorsInGamut(

HDC  hdc,
LPVOID  lpaRGBQuad,
LPVOID  lpResult,
DWORD  nCount
);
Parameters

hdc

Handle to a device context.

lpaRGBQuad

Pointer to an array of RGBQUAD structures that contains the color values to check.

lpResult

Pointer to an array of bytes that receives the results of the color checking.

nCount

Count of elements in the array.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

For each specified color value, CheckColorsInGamut sets the corresponding byte in the results buffer to either CM_IN_GAMUT or CM_OUT_OF_GAMUT.

See Also

RGBQUAD


CheckDlgButton
 CheckDlgButton  QuickInfo  Overview  Group

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

BOOL CheckDlgButton(

HWND  hDlg,	// handle of dialog box
int  nIDButton,	// button-control identifier
UINT  uCheck	// check state
);
Parameters

hDlg

Identifies the dialog box that contains the button.

nIDButton

Identifies the button to modify.

uCheck

Specifies the check state of the button. This parameter can be one of the following values:

Value	Meaning
0	Sets the button state to unchecked. Same as the Windows 95 constant BST_UNCHECKED.
1	Sets the button state to checked. Same as the Windows 95 constant BST_CHECKED.
2	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. Same as the Windows 95 constant BST_INDETERMINATE.
BST_CHECKED	Windows 95 only: Sets the button state to checked.
BST_INDETERMINATE	Windows 95 only: 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	Windows 95 only: Sets the button state to unchecked
Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

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

See Also

CheckRadioButton, IsDlgButtonChecked


CheckMenuItem
 CheckMenuItem  QuickInfo  Overview  Group

The CheckMenuItem function sets the state of the specified menu item's check mark attribute to either checked or unchecked.

DWORD CheckMenuItem(

HMENU hmenu,	// handle of menu
UINT uIDCheckItem,	// menu item to check or uncheck
UINT uCheck	// menu item flags
);
Parameters

hmenu

Identifies the menu of interest.

uIDCheckItem

Specifies the menu item whose check-mark attribute is to be set, as determined by the uCheck parameter.

uCheck

Specifies flags that control the interpretation of the uIDCheckItem parameter and the state of the menu item's check-mark attribute. This parameter can be a combination of either MF_BYCOMMAND or MF_BYPOSITION and MF_CHECKED or MF_UNCHECKED.

Value	Meaning
MF_BYCOMMAND	Indicates that the uIDCheckItem parameter gives the identifier of the menu item. The MF_BYCOMMAND flag is the default, if neither the MF_BYCOMMAND nor MF_BYPOSITION flag is specified.
MF_BYPOSITION	Indicates that the uIDCheckItem parameter gives the zero-based relative position of the menu item.
MF_CHECKED	Sets the check-mark attribute to the checked state.
MF_UNCHECKED	Sets the check-mark attribute to the unchecked state.
Return Value

The return value specifies the previous state of the menu item (either MF_CHECKED or MF_UNCHECKED). If the menu item does not exist, the return value is 0xFFFFFFFF.

Remarks

An item in a menu bar cannot have a check mark.

The uIDCheckItem parameter identifies a pop-up item or a command item. For a pop-up item, the uIDCheckItem parameter must specify the position of the item, because a pop-up item does not have an identifier. For a command item, the uIDCheckItem parameter can specify either the item's position or its identifier.

See Also

EnableMenuItem, GetMenuCheckMarkDimensions, GetMenuItemID, SetMenuItemBitmaps


CheckMenuRadioItem [New - Windows 95]
 CheckMenuRadioItem  QuickInfo  Overview  Group

[New - Windows 95]

The CheckMenuRadioItem function checks a specified menu item and makes it a radio item. At the same time, the function unchecks all other menu items in the associated group and clears the radio-item type flag for those items.

BOOL API CheckMenuRadioItem(

HMENU  hmenu,
UINT  idFirst,
UINT  idLast,
UINT  idCheck,
UINT  uFlags
);
Parameters

hmenu

Handle to the menu that contains the group of menu items.

idFirst

Identifier or position of the first menu item in the group.

idLast

Identifier or position of the last menu item in the group.

idCheck

Identifier or position of the menu item to check.

uFlags

Value specifying the meaning of idFirst, idLast, and idCheck. If this parameter is MF_BYCOMMAND, the other parameters specify menu item identifiers. If it is MF_BYPOSITION, the other parameters specify the menu item positions.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To get extended error information, use the GetLastError function.

Remarks

The CheckMenuRadioItem function sets the MFT_RADIOCHECK type flag and the MFS_CHECKED state for the item specified by idCheck and, at the same time, clears both flags for all other items in the group. The checked item is displayed using a bullet bitmap instead of a check-mark bitmap.

For more information about menu item type and state flags, see the MENUITEMINFO structure.

See Also

MENUITEMINFO


CheckRadioButton
 CheckRadioButton  QuickInfo  Overview  Group

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 of dialog box
int  nIDFirstButton,	// identifier of first radio button in group
int  nIDLastButton,	// identifier of last radio button in group
int  nIDCheckButton	// identifier of radio button to select
);
Parameters

hDlg

Identifies the dialog box that contains the radio button.

nIDFirstButton

Specifies the identifier of the first radio button in the group.

nIDLastButton

Specifies the identifier of the last radio button in the group.

nIDCheckButton

Specifies the identifier of the radio button to select.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. 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.

See Also

BM_SETCHECK, CheckDlgButton, IsDlgButtonChecked


ChildWindowFromPoint
 ChildWindowFromPoint  QuickInfo  Overview  Group

The ChildWindowFromPoint function determines which, if any, of the child windows belonging to a parent window contains the specified point.

HWND ChildWindowFromPoint(

HWND  hWndParent,	// handle of parent window
POINT  Point	// structure with point coordinates
);
Parameters

hWndParent

Identifies the parent window.

Point

Specifies a POINT structure that defines the client coordinates of the point to be checked.

Return Value

If the function succeeds, the return value is the handle of 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 the handle of the parent window.

Remarks

Windows 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 given point, Windows returns the handle of the first window in the list that contains the point.

See Also

ChildWindowFromPointEx, POINT, WindowFromPoint


ChildWindowFromPointEx [New - Windows 95]
 ChildWindowFromPointEx  QuickInfo

[New - Windows 95]

The ChildWindowFromPointEx function determines which, if any, of the child windows belonging to the given parent window contains the specified point. The function can ignore invisible, disabled, and transparent child windows.

HWND ChildWindowFromPointEx(

HWND  hwndParent,	// handle of parent window
POINT  pt,	// structure with point coordinates
UINT  uFlags	// skipping flags
);
Parameters

hwndParent

Identifies the parent window.

pt

Specifies a POINT structure that defines the client coordinates of the point to be checked.

uFlags

Specifies which child windows to skip. This parameter can be a combination of the following values:

Value	Meaning
CWP_ALL	Do not skip any child windows
CWP_SKIPINVISIBLE	Skip invisible child windows
CWP_SKIPDISABLED	Skip disabled child windows
CWP_SKIPTRANSPARENT	Skip transparent child windows
Return Value

If the function succeeds, the return value is the handle of 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 the handle of the parent window. If the point lies outside the parent window or if the function fails, the return value is NULL.

Remarks

Windows 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 given point, Windows returns the handle of the first window in the list that contains the point and meets the criteria specified by uFlags.

See Also

ChildWindowFromPoint, POINT, WindowFromPoint


ChooseColor
 ChooseColor  QuickInfo  Overview  Group

The ChooseColor function creates a system-defined dialog box from which the user can select a color.

BOOL ChooseColor(

LPCHOOSECOLOR  lpcc	// address of structure with initialization data
);
Parameters

lpcc

Points to a CHOOSECOLOR structure that, when the function is called, contains information necessary to initialize the dialog box. When ChooseColor returns, this structure contains information about the user's color selection.

Return Value

If the user selects a color, the return value is TRUE. It is FALSE if an error occurs, the user chooses the Cancel button, or the user chooses the Close command on the System menu (often called the Control menu) to close the dialog box.

The CommDlgExtendedError function can be used to get extended error information, which may be one of the following values:

CDERR_FINDRESFAILURE	CDERR_MEMLOCKFAILURE
CDERR_INITIALIZATION	CDERR_NOHINSTANCE
CDERR_LOCKRESFAILURE	CDERR_NOHOOK
CDERR_LOADRESFAILURE	CDERR_NOTEMPLATE
CDERR_LOADSTRFAILURE	CDERR_STRUCTSIZE
CDERR_MEMALLOCFAILURE
Remarks

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

If the hook function (to which the lpfnHook member of the CHOOSECOLOR structure points) processes the WM_CTLCOLORDLG message, ChooseColor must return a handle for the brush that should be used to paint the control background.

See Also

CommDlgExtendedError, WM_CTLCOLORDLG, CHOOSECOLOR


ChooseFont
 ChooseFont  QuickInfo  Overview  Group

The ChooseFont function creates a system-defined dialog box from which the user can select a font, a font style (such as bold or italic), a point size, an effect (such as strikeout or underline), and a text color.

BOOL ChooseFont(

LPCHOOSEFONT  lpcf	// address of structure with initialization data
);
Parameters

lpcf

Points to a CHOOSEFONT structure that, when the structure is called, contains information necessary to initialize the dialog box. When ChooseFont returns, this structure contains information about the user's font selection.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

The CommDlgExtendedError function can be used to get extended error information, which may be one of the following values:

CDERR_FINDRESFAILURE	CDERR_NOHINSTANCE
CDERR_INITIALIZATION	CDERR_NOHOOK
CDERR_LOCKRESFAILURE	CDERR_NOTEMPLATE
CDERR_LOADRESFAILURE	CDERR_STRUCTSIZE
CDERR_LOADSTRFAILURE	CFERR_MAXLESSTHANMIN
CDERR_MEMALLOCFAILURE	CFERR_NOFONTS
CDERR_MEMLOCKFAILURE
Remarks

If the hook function (to which the lpfnHook member of the CHOOSEFONT structure points) processes the WM_CTLCOLORDLG message, ChooseFont must return a handle for the brush that should be used to paint the control background.

An application can use the WM_CHOOSEFONT_GETLOGFONT message to retrieve a LOGFONT structure for the current logical font while the Font dialog box is open.

See Also

CommDlgExtendedError, WM_CHOOSEFONT_GETLOGFONT, WM_CTLCOLORDLG, CHOOSEFONT, LOGFONT


Chord
 Chord  QuickInfo  Overview  Group

The Chord function draws a chord (a region bounded by the intersection of an ellipse and a line segment, called a "secant"). The chord is outlined by using the current pen and filled by using the current brush.

BOOL Chord(

HDC  hdc,	// handle of device context
int  nLeftRect,	// x-coordinate of the upper-left corner of the bounding rectangle
int  nTopRect,	// y-coordinate of the upper-left corner of the bounding rectangle
int  nRightRect,	// x-coordinate of the lower-right corner of the bounding rectangle
int  nBottomRect,	// y-coordinate of the lower-right corner of the bounding rectangle
int  nXRadial1,	// x-coordinate of the first radial's endpoint
int  nYRadial1,	// y-coordinate of the first radial's endpoint
int  nXRadial2,	// x-coordinate of the second radial's endpoint
int  nYRadial2	// y-coordinate of the second radial's endpoint
);
Parameters

hdc

Identifies the device context in which the chord appears.

nLeftRect

Specifies the x-coordinate of the upper-left corner of the bounding rectangle.

nTopRect

Specifies the y-coordinate of the upper-left corner of the bounding rectangle.

nRightRect

Specifies the x-coordinate of the lower-right corner of the bounding rectangle.

nBottomRect

Specifies the y-coordinate of the lower-right corner of the bounding rectangle.

nXRadial1

Specifies the x-coordinate of the endpoint of the radial defining the beginning of the chord.

nYRadial1

Specifies the y-coordinate of the endpoint of the radial defining the beginning of the chord.

nXRadial2

Specifies the x-coordinate of the endpoint of the radial defining the end of the chord.

nYRadial2

Specifies the y-coordinate of the endpoint of the radial defining the end of the chord.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The curve of the chord is defined by an ellipse that fits the specified bounding rectangle. The curve begins at the point where the ellipse intersects the first radial and extends counterclockwise to the point where the ellipse intersects the second radial. (A radial is a line segment drawn from the center of the ellipse to a specified endpoint on the ellipse.) The chord is closed by drawing a line from the intersection of the first radial and the curve to the intersection of the second radial and the curve.

If the starting point and ending point of the curve are the same, a complete ellipse is drawn.

The current position is neither used nor updated by Chord.

Windows 95 only: The sum of the coordinates of the bounding rectangle cannot exceed 32,767. The sum of nLeftRect and nRightRect or nTopRect and nBottomRect parameters cannot exceed 32,767.

See Also

AngleArc, Arc, ArcTo, Pie


ClearCommBreak
 ClearCommBreak  QuickInfo  Overview  Group

The ClearCommBreak function restores character transmission for a specified communications device and places the transmission line in a nonbreak state.

BOOL ClearCommBreak(

HANDLE  hFile	// handle of communications device
);
Parameters

hFile

Identifies the communications device. The CreateFile function returns this handle.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

A communications device is placed in a break state by the SetCommBreak or EscapeCommFunction function. Character transmission is then suspended until the break state is cleared by calling ClearCommBreak.

See Also

ClearCommError, CreateFile, EscapeCommFunction, SetCommBreak


ClearCommError
 ClearCommError  QuickInfo  Overview  Group

The ClearCommError function retrieves information about a communications error and reports the current status of a communications device. The function is called when a communications error occurs, and it clears the device's error flag to enable additional input and output (I/O) operations.

BOOL ClearCommError(

HANDLE  hFile,	// handle of communications device
LPDWORD  lpErrors,	// address of variable to receive error codes
LPCOMSTAT  lpStat	// address of buffer for communications status
);
Parameters

hFile

Identifies the communications device. The CreateFile function returns this handle.

lpErrors

Points to a 32-bit variable to be filled with a mask indicating the type of error. This parameter can be one or more of the following error values:

Value	Meaning
CE_BREAK	The hardware detected a break condition.
CE_DNS	Windows 95 only: A parallel device is not selected.
CE_FRAME	The hardware detected a framing error.
CE_IOE	An I/O error occurred during communications with the device.
CE_MODE	The requested mode is not supported, or the hFile parameter is invalid. If this value is specified, it is the only valid error.
CE_OOP	Windows 95 only: A parallel device signaled that it is out of paper.
CE_OVERRUN	A character-buffer overrun has occurred. The next character is lost.
CE_PTO	Windows 95 only: A time-out occurred on a parallel device.
CE_RXOVER	An input buffer overflow has occurred. There is either no room in the input buffer, or a character was received after the end-of-file (EOF) character.
CE_RXPARITY	The hardware detected a parity error.
CE_TXFULL	The application tried to transmit a character, but the output buffer was full.
lpStat

Points to a COMSTAT structure in which the device's status information is returned. If lpStat is NULL, no status information is returned.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

If a communications port has been set up with a TRUE value for the fAbortOnError member of the setup DCB structure, the communications software will terminate all read and write operations on the communications port when a communications error occurs. No new read or write operations will be accepted until the application acknowledges the communications error by calling the ClearCommError function.

The ClearCommError function fills the status buffer pointed to by the lpStat parameter with the current status of the communications device specified by the hFile parameter.

See Also

ClearCommBreak, COMSTAT, CreateFile, DCB


ClearEventLog
 ClearEventLog  QuickInfo  Overview  Group

The ClearEventLog function clears the specified event log, and optionally saves the current copy of the logfile to a backup file.

BOOL ClearEventLog(

HANDLE  hEventLog,	// handle to event log
LPCTSTR  lpBackupFileName	// name of backup file
);
Parameters

hEventLog

Identifies the event log to be cleared. This handle is returned by the OpenEventLog function.

lpBackupFileName

Points to the null-terminated string specifying the name of a file in which a current copy of the event logfile will be placed. If this file already exists, the function fails.

The backup filename may contain a server name to save the backup file on a remote server.

If the lpBackupFileName parameter is NULL, the current event logfile is not backed up.

Return Value

If the function succeeds, the return value is TRUE. The given event log has been backed up (if lpBackupFileName is not NULL) and then cleared.

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

Remarks

This function fails if the event log is empty.

After this function returns, any handles that reference the cleared event log cannot be used to read the log.

If the backup filename specifies a remote server, the event log handle must identify a log on the local computer. You cannot back up an event logfile from a remote server to a file on a remote server (even if the backup file and the original log are on the same server).

ClearEventLog is used to optionally back up an existing logfile of the module represented by hEventLog. The function backs up the logfile to another file, and then clears the existing logfile. The caller must have write permission for the path specified, and must also have permission to move the current logfile. If a file already exists with the same name as lpBackupFileName, ClearEventLog fails.

See Also

OpenEventLog


ClientToScreen
 ClientToScreen  QuickInfo  Overview  Group

The ClientToScreen function converts the client coordinates of a specified point to screen coordinates.

BOOL ClientToScreen(

HWND  hWnd,	// window handle for source coordinates
LPPOINT  lpPoint	// address of structure containing screen coordinates
);
Parameters

hWnd

Identifies the window whose client area is used for the conversion.

lpPoint

Points to a POINT structure that contains the client coordinates to be converted. The new screen coordinates are copied into this structure if the function succeeds.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

The ClientToScreen function replaces the client coordinates in the POINT structure with the screen coordinates. The screen coordinates are relative to the upper-left corner of the screen.

See Also

MapWindowPoints, POINT, ScreenToClient


ClipCursor
 ClipCursor  QuickInfo  Overview  Group

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, Windows automatically adjusts the position to keep the cursor inside the rectangular area.

BOOL ClipCursor(

CONST RECT * lpRect	// address of structure with rectangle
);
Parameters

lprc

Points 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 Value

If the function succeeds, the return value is TRUE.

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

Remarks

The cursor is a shared resource. If an application confines the cursor, it must release the cursor by using ClipCursor before relinquishing control to another application.

The calling process must have WINSTA_WRITEATTRIBUTES access to the window station.

See Also

GetClipCursor, GetCursorPos, RECT, SetCursorPos


CloseClipboard
 CloseClipboard  QuickInfo  Overview  Group

The CloseClipboard function closes the clipboard.

BOOL CloseClipboard(VOID)

Parameters

This function has no parameters.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

When the window has finished examining or changing the clipboard, close the clipboard by calling CloseClipboard. This enables other windows to access the clipboard.

Do not place an object on the clipboard after calling CloseClipboard.

See Also

GetOpenClipboardWindow, OpenClipboard


CloseDesktop [New - Windows NT]
 CloseDesktop  QuickInfo  Overview  Group

[New - Windows NT]

The CloseDesktop function closes an open handle of 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 of desktop to close
);
Parameters

hDesktop

Identifies the desktop to be closed. This handle is returned by the CreateDesktop and OpenDesktop functions.

Return Value

If the function succeeds, the return value is TRUE.

If the functions fails, the return value is FALSE. 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.

See Also

CreateDesktop, OpenDesktop


CloseEnhMetaFile
 CloseEnhMetaFile  QuickInfo  Overview  Group

The CloseEnhMetaFile function closes an enhanced-metafile device context and returns a handle that identifies an enhanced-format metafile.

HENHMETAFILE CloseEnhMetaFile(

HDC  hdc	// handle of an enhanced-metafile device context
);
Parameters

hdc

Identifies an enhanced-metafile device context.

Return Value

If the function succeeds, the return value is a handle of an enhanced metafile.

If the function fails, the return value is NULL.

Remarks

An application can use the enhanced-metafile handle returned by this function to perform the following tasks:

•	Display a picture stored in an enhanced metafile

•	Create copies of the enhanced metafile

•	Enumerate, edit, or copy individual records in the enhanced metafile

•	Retrieve an optional description of the metafile contents from the enhanced-metafile header

•	Retrieve a copy of the enhanced-metafile header

•	Retrieve a binary copy of the enhanced metafile

•	Enumerate the colors in the optional palette

•	Convert an enhanced-format metafile into a Windows-format metafile

When the application no longer needs the enhanced metafile handle, it should release the handle by calling the DeleteEnhMetaFile function.

See Also

CopyEnhMetaFile, CreateEnhMetaFile, DeleteEnhMetaFile, EnumEnhMetaFile, GetEnhMetaFileBits, GetWinMetaFileBits, PlayEnhMetaFile


CloseEventLog
 CloseEventLog  QuickInfo  Overview  Group

The CloseEventLog function closes the specified event log.

BOOL CloseEventLog(

HANDLE  hEventLog	// handle to event log
);
Parameters

hEventLog

Identifies the event log to be closed. This handle is returned by the OpenEventLog function.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

OpenEventLog


CloseFigure
 CloseFigure  QuickInfo  Overview  Group

The CloseFigure function closes an open figure in a path.

BOOL CloseFigure(

HDC  hdc	// handle of device context
);
Parameters

hdc

Identifies the device context in which the figure will be closed.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The CloseFigure function closes the figure by drawing a line from the current position to the first point of the figure (usually, the point specified by the most recent call to the MoveTo function) and then connects the lines by using the line join style. If a figure is closed by using the LineTo function instead of CloseFigure, end caps are used to create the corner instead of a join.

The CloseFigure function should only be called if there is an open path bracket in the specified device context.

A figure in a path is open unless it is explicitly closed by using this function. (A figure can be open even if the current point and the starting point of the figure are the same.)

After a call to CloseFigure, adding a line or curve to the path starts a new figure.

See Also

BeginPath, EndPath, ExtCreatePen, LineTo, MoveTo


CloseHandle
 CloseHandle  QuickInfo  Overview  Group

The CloseHandle function closes an open object handle.

BOOL CloseHandle(

HANDLE  hObject	// handle of object to close
);
Parameters

hObject

Identifies an open object handle.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The CloseHandle function closes handles to the following objects:

•	Console input or output

•	Event file

•	File mapping

•	Mutex

•	Named pipe

•	Process

•	Semaphore

•	Thread

CloseHandle invalidates the specified object handle, decrements the object's handle count, and performs object retention checks. Once the last handle of an object is closed, the object is removed from the operating system.

This function does not close module objects.

CloseHandle is used to close handles returned by calls to the CreateFile function.

See Also

CreateFile, DeleteFile


CloseMetaFile
 CloseMetaFile  QuickInfo  Overview  Group

The CloseMetaFile function closes a metafile device context and returns a handle that identifies a Windows-format metafile.

This function is provided for compatibility with earlier versions of Microsoft Windows. Win32-based applications should use the CloseEnhMetaFile function.

HMETAFILE CloseMetaFile(

HDC  hdc	// handle of metafile device context
);
Parameters

hdc

Identifies a metafile device context used to create a Windows-format metafile.

Return Value

If the function succeeds, the return value is a handle of a Windows-format metafile.

If the function fails, the return value is NULL.

Remarks

A Windows-format metafile does not support the new curve, path, and transformation functions, such as PolyBezier, BeginPath, and SetWorldTransform. Applications that use these new functions and use metafiles to store pictures created by these functions should call the enhanced-format metafile functions.

To convert a Windows-format metafile into a new enhanced-format metafile, use the SetWinMetaFileBits function.

When an application no longer needs the Windows-format metafile handle, it should delete the handle by calling the DeleteMetaFile function.

See Also

BeginPath, CloseEnhMetaFile, CopyMetaFile, CreateMetaFile, DeleteMetaFile, EnumMetaFile, GetMetaFileBitsEx, PlayMetaFile, PolyBezier, SetWinMetaFileBits, SetWorldTransform


ClosePrinter
 ClosePrinter  QuickInfo  Overview  Group

The ClosePrinter function closes the specified printer object.

BOOL ClosePrinter(

HANDLE  hPrinter	// handle of printer object
);
Parameters

hPrinter

Identifies the printer object to be closed.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

AddPrinter, OpenPrinter


CloseServiceHandle
 CloseServiceHandle  QuickInfo  Overview  Group

The CloseServiceHandle function closes a handle to a service control manager database as returned by the OpenSCManager function, or it closes a handle to a service object as returned by either the OpenService or CreateService function.

BOOL CloseServiceHandle(

SC_HANDLE  hSCObject	// handle of service or service control manager database
);
Parameters

hSCObject

Identifies the service control manager database or the service object to close.

Return Value

If the function succeeds, the return value is TRUE.

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

Errors

The following error code may be set by the service control manager. Other error codes may be set by registry functions that are called by the service control manager.

Value	Meaning
ERROR_INVALID_HANDLE	The specified handle is invalid.
Remarks

The CloseServiceHandle function does not destroy the service control manager object referred to by the handle. A service control manager object cannot be destroyed. A service object can be destroyed by calling the DeleteService function.

See Also

CreateService, DeleteService, OpenSCManager, OpenService


closesocket
 closesocket  QuickInfo

The Windows Sockets closesocket function closes a socket.

int closesocket (

SOCKET s
);
Parameters

s

A descriptor identifying a socket.

Return Value

If no error occurs, closesocket returns zero. Otherwise, a value of SOCKET_ERROR is returned, and a specific error code may be retrieved by calling WSAGetLastError.

Error Codes

WSANOTINITIALISED	A successful WSAStartup must occur before using this function.
WSAENETDOWN	The Windows Sockets implementation has detected that the network subsystem has failed.
WSAENOTSOCK	The descriptor is not a socket.
WSAEINPROGRESS	A blocking Windows Sockets call is in progress.
WSAEINTR	The (blocking) call was canceled using WSACancelBlockingCall.
WSAEWOULDBLOCK	The socket is marked as nonblocking and SO_LINGER is set to a nonzero timeout value.
Remarks

This function closes a socket. More precisely, it releases the socket descriptor s, so that further references to s will fail with the error WSAENOTSOCK. If this is the last reference to the underlying socket, the associated naming information and queued data are discarded.

The semantics of closesocket are affected by the socket options SO_LINGER and SO_DONTLINGER as follows:

Option	Interval	Type of close	Wait for close?
SO_DONTLINGER	Don't care	Graceful	No
SO_LINGER	Zero	Hard	No
SO_LINGER	Nonzero	Graceful	Yes
If SO_LINGER is set (that is, if the l_onoff field of the linger structure is nonzero; see setsockopt) with a zero timeout interval (l_linger is zero), closesocket is not blocked even if queued data has not yet been sent or acknowledged. This is called a "hard" or "abortive" close, because the socket's virtual circuit is reset immediately, and any unsent data is lost. Any recv call on the remote side of the circuit will fail with WSAECONNRESET.

If SO_LINGER is set with a nonzero timeout interval, the closesocket call blocks until the remaining data has been sent or until the timeout expires. This is called a "graceful disconnect." Note that if the socket is set to nonblocking and SO_LINGER is set to a nonzero timeout, the call to closesocket will fail with an error of WSAEWOULDBLOCK.

If SO_DONTLINGER is set on a stream socket (that is, the l_onoff field of the linger structure is zero), the closesocket call will return immediately. However, any data queued for transmission will be sent if possible before the underlying socket is closed. This is also called a graceful disconnect. Note that in this case the Windows Sockets implementation may not release the socket and other resources for an arbitrary period, which may affect applications that expect to use all available sockets.

See Also

accept, socket, ioctlsocket, setsockopt, WSAAsyncSelect, WSACancelBlockingCall, WSAStartup


 CloseSound

The CloseSound function has been deleted.

See Also

Beep, MessageBeep


CloseWindow
 CloseWindow  QuickInfo  Overview  Group

The CloseWindow function minimizes (but does not destroy) the specified window.

BOOL CloseWindow(

HWND  hWnd	// handle of window to minimize
);
Parameters

hWnd

Identifies the window to be minimized.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. 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. Windows 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.

See Also

ArrangeIconicWindows, DestroyWindow, IsIconic, OpenIcon


CloseWindowStation [New - Windows NT]
 CloseWindowStation  QuickInfo  Overview  Group

[New - Windows NT]

The CloseWindowStation function closes an open window station handle.

BOOL CloseWindowStation(

HWINSTA hWinSta	// handle of window station to close
);
Parameters

hWinSta

Identifies the window station to be closed. This handle is returned by the CreateWindowStation and OpenWindowStation functions.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. 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.

See Also

SetProcessWindowStation


ColorMatchToTarget [New - Windows 95]
 ColorMatchToTarget  QuickInfo  Overview  Group

[New - Windows 95]

The ColorMatchToTarget function enables or disables preview for the specified device context. When preview is enabled, colors in subsequent output to the specified device context are displayed as they would appear on the target device. This is useful for checking how well the target maps the specified colors in an image. To enable preview, image color matching must be enabled for both the target and the preview device context.

BOOL ColorMatchToTarget(

HDC  hdc,
HDC  hdcTarget,
DWORD  uiAction
);
Parameters

hdc

Handle to the device context to use for preview, typically the display.

hdcTarget

Handle to the target device context, typically a printer.

uiAction

This parameter can have one of the following values:

Value	Meaning
CS_ENABLE	Enable preview; start matching colors through the target before displaying.
CS_DISABLE	Disable preview; stop matching colors through the target and restore the previous method for the preview device.
CS_DELETE_TRANSFORM	Disable preview and delete the color transformation used for previewing.
Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

If you use ColorMatchToTarget to enable preview, your next call to this function must be to disable preview; you must not nest calls to enable preview. While preview is enabled, any changes you make to the color space or gamut matching method are temporarily ignored, but take effect when preview is disabled.

This function creates a color transformation that translates colors for the target device first, then translates colors for the preview device. You need not delete the color transformation using CS_DELETE_TRANSFORM because the system deletes the transformation when either of the devices is removed from the system, or when the color space is deleted. However, if the transform is not going to be used again, an application can free up the space taken by it.


CombineRgn
 CombineRgn  QuickInfo  Overview  Group

The CombineRgn function combines two regions and stores the result in a third region. The two regions are combined according to the specified mode.

int CombineRgn(

HRGN  hrgnDest,	// handle of destination region
HRGN  hrgnSrc1,	// handle of source region
HRGN  hrgnSrc2,	// handle of source region
int  fnCombineMode	// region combining mode
);
Parameters

hrgnDest

Identifies a new region with dimensions defined by combining two other regions. (This region must exist before CombineRgn is called.)

hrgnSrc1

Identifies the first of two regions to be combined.

hrgnSrc2

Identifies the second of two regions to be combined.

fnCombineMode

Specifies a mode indicating how the two regions will be combined. This parameter can be one of the following values:

Value	Description
RGN_AND	Creates the intersection of the two combined regions.
RGN_COPY	Creates a copy of the region identified by hrgnSrc1.
RGN_DIFF	Combines the parts of hrgnSrc1 that are not part of hrgnSrc2.
RGN_OR	Creates the union of two combined regions.
RGN_XOR	Creates the union of two combined regions except for any overlapping areas.
Return Value

The return value specifies the type of the resulting region. It can be one of the following values:

Value	Meaning
NULLREGION	The region is empty.
SIMPLEREGION	The region is a single rectangle.
COMPLEXREGION	The region is more than a single rectangle.
ERROR	No region is created.
Remarks

The three regions need not be distinct. For example, the hrgnSrc1 parameter can equal the hrgnDest parameter.

See Also

CreateEllipticRgn, CreateEllipticRgnIndirect, CreatePolygonRgn, CreatePolyPolygonRgn, CreateRectRgn, CreateRectRgnIndirect, CreateRoundRectRgn


CombineTransform
 CombineTransform  QuickInfo  Overview  Group

The CombineTransform function concatenates two world-space to page-space transformations.

BOOL CombineTransform(

LPXFORM  lpxformResult,	// address of combined transformation
CONST XFORM *  lpxform1,	// address of first transformation
CONST XFORM *  lpxform2	// address of second transformation
);
Parameters

lpxformResult

Points to an XFORM structure that receives the combined transformation.

lpxform1

Points to an XFORM structure that identifies the first transformation.

lpxform2

Points to an XFORM structure that identifies the second transformation.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

Applying the combined transformation has the same effect as applying the first transformation and then applying the second transformation.

The three transformations need not be distinct. For example, lpxform1 can point to the same XFORM structure as lpxformResult.

See Also

GetWorldTransform, ModifyWorldTransform, SetWorldTransform, XFORM


CommandLineToArgvW
 CommandLineToArgvW  QuickInfo  Overview  Group

The CommandLineToArgvW function parses a wide-character Unicode command-line string. It returns a pointer to a set of wide-character Unicode argument strings and a count of arguments, similar to the standard C run-time argv and argc values. The function provides a way to obtain a Unicode set of argv and argc values from a Unicode command-line string.

LPWSTR *  CommandLineToArgvW(

LPCWSTR   lpCmdLine,	// pointer to a command-line string
int *     pNumArgs	// pointer to a variable that receives the argument count
);
Parameters

lpCmdLine

Pointer to a null-terminated Unicode command-line string. An application will usually directly pass on the value returned by a call to GetCommandLineW.

*pNumArgs

Pointer to an integer variable that the function sets to the count of arguments parsed.

Return Value

If the function succeeds, the return value is a non-NULL pointer to the constructed argument list, which is a set of Unicode wide-character argument strings. It is the caller's responsibility to free the argument list's memory when it is no longer needed.

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

See Also

GetCommandLine


CommConfigDialog [New - Windows 95]
 CommConfigDialog  QuickInfo  Overview  Group

[New - Windows 95]

The CommConfigDialog function displays a driver-supplied configuration dialog box.

BOOL CommConfigDialog(

LPTSTR lpszName,	// address of device name string
HWND hWnd,	// handle of window
LPCOMMCONFIG lpCC,	// address of comm. configuration structure
);
Parameters

lpszName

Points to a null-terminated string specifying the name of the device for which a dialog box should be displayed.

hWnd

Identifies the window that owns the dialog box. This parameter can be any valid window handle, or it should be NULL if the dialog box is to have no owner.

lpCC

Points to a COMMCONFIG structure. This structure contains initial settings for the dialog box before the call, and changed values after the call.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

This function requires a dynamic-link library (DLL) provided by the communications hardware vendor.

See Also

COMMCONFIG


CommDlgExtendedError
 CommDlgExtendedError  QuickInfo  Overview  Group

The CommDlgExtendedError function identifies the cause of the most recent error that has occurred during the execution of one of the following common dialog box functions:

ChooseColor	GetOpenFileName
ChooseFont	GetSaveFileName
FindText	PrintDlg
GetFileTitle	ReplaceText
DWORD CommDlgExtendedError(VOID)

Parameters

This function has no parameters.

Return Value

If the previous call to a common dialog box procedure succeeds, the return value is undefined. The return value is CDERR_DIALOGFAILURE if the dialog box could not be created. Otherwise, the return value is a nonzero integer that identifies an error condition.

Remarks

Following are the possible CommDlgExtendedError return values and their meanings:

Value	Meaning
CDERR_CHOOSECOLORCODES	Error codes for the Color common dialog box. these errors are in the range 0x5000 through 0x5FFF.
CDERR_DIALOGFAILURE	The common dialog box procedure'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 procedure failed to find a specified resource.
CDERR_GENERALCODES	General error codes for common dialog boxes. These errors are in the range 0x0000 through 0x0FFF.
CDERR_INITIALIZATION	The common dialog box procedure failed during initialization. This error often occurs when insufficient memory is available.
CDERR_LOADRESFAILURE	The common dialog box procedure failed to load a specified resource.
CDERR_LOADSTRFAILURE	The common dialog box procedure failed to load a specified string.
CDERR_LOCKRESFAILURE	The common dialog box procedure failed to lock a specified resource.
CDERR_MEMALLOCFAILURE	The common dialog box procedure was unable to allocate memory for internal structures.
CDERR_MEMLOCKFAILURE	The common dialog box procedure was unable to lock the memory associated with a handle.
CDERR_NOHINSTANCE	The ENABLETEMPLATE flag was specified in the Flags member of a structure for the corresponding common dialog box, but the application failed to provide a corresponding instance handle.
CDERR_NOHOOK	The ENABLEHOOK flag was specified in the Flags member of a structure for the corresponding common dialog box, but the application failed to provide a pointer to a corresponding hook function.
CDERR_NOTEMPLATE	The ENABLETEMPLATE flag was specified in the Flags member of a structure for the corresponding common dialog box, but the application failed to provide a corresponding template.
CDERR_REGISTERMSGFAIL	The RegisterWindowMessage function returned an error value when it was called by the common dialog box procedure.
CDERR_STRUCTSIZE	The lStructSize member of a structure for the corresponding common dialog box is invalid.
CFERR_CHOOSEFONTCODES	Error codes for the Font common dialog box. These errors are in the range 0x2000 through 0x2FFF.
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.
FNERR_BUFFERTOOSMALL	The buffer for a filename is too small. (This buffer is pointed to by the lpstrFile member of the structure for a common dialog box.)
FNERR_FILENAMECODES	Error codes for the Open and Save As common dialog boxes. these errors are in the range 0x3000 through 0x3FFF.
FNERR_INVALIDFILENAME	A filename is invalid.
FNERR_SUBCLASSFAILURE	An attempt to subclass a list box failed because insufficient memory was available.
FRERR_BUFFERLENGTHZERO	A member in a structure for the corresponding common dialog box points to an invalid buffer.
FRERR_FINDREPLACECODES	Error codes for the Find and Replace common dialog boxes. these errors are in the range 0x4000 through 0x4FFF.
PDERR_CREATEICFAILURE	The PrintDlg function failed when it attempted to create an information context.
PDERR_DEFAULTDIFFERENT	An application 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 happens when an application stores the DEVNAMES structure and the user changes the default printer by using Control Panel.)
	To use the printer described by the DEVNAMES structure, the application should clear the DN_DEFAULTPRN flag and call the PrintDlg function again. To use the default printer, the application should replace the DEVNAMES structure (and the DEVMODE structure, if one exists) with NULL; this sets the default printer automatically.
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 value applies only to printer drivers written for Windows versions 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_PRINTERCODES	Error codes for the Print common dialog box. These errors are in the range 0x1000 through 0x1FFF.
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 nonzero.
PDERR_SETUPFAILURE	The PrintDlg function failed to load the required resources.
See Also

ChooseColor, CHOOSECOLOR, ChooseFont, CHOOSEFONT, DEVMODE, DEVNAMES, DialogBox, FINDREPLACE, FindText, GetFileTitle, GetOpenFileName, GetSaveFileName, OPENFILENAME, PrintDlg, PRINTDLG, RegisterWindowMessage, ReplaceText


CompareFileTime
 CompareFileTime  QuickInfo  Overview  Group

The CompareFileTime function compares two 64-bit file times.

LONG CompareFileTime(

CONST FILETIME *  lpFileTime1,	// address of first file time
CONST FILETIME *  lpFileTime2	// address of second file time
);
Parameters

lpFileTime1

Points to a FILETIME structure that specifies the first 64-bit file time.

lpFileTime2

Points to a FILETIME structure that specifies the second 64-bit file time.

Return Value

If the function succeeds, the return value is one of the following values:

Value	Meaning
−1	First file time is less than second file time.
0	First file time is equal to second file time.
+1	First file time is greater than second file time.
See Also

GetFileTime, FILETIME


CompareString
 CompareString  QuickInfo  Overview  Group

The CompareString function compares two character strings, using the locale specified by the given identifier as the basis for the comparison.

int CompareString(

LCID  Locale,	// locale identifier
DWORD  dwCmpFlags,	// comparison-style options
LPCTSTR  lpString1,	// address of first string
int  cchCount1,	// size, in bytes or characters, of first string
LPCTSTR  lpString2,	// address of second string
int  cchCount2	// size, in bytes or characters, of second string
);
Parameters

Locale

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

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

Points to the first string to be compared.

cchCount1

Specifies the size, in bytes (ANSI version) or characters (Unicode version), of the string pointed to by the lpString1 parameter. If this parameter is  − 1, the string is assumed to be null terminated and the length is calculated automatically.

lpString2

Points to the second string to be compared.

cchCount2

Specifies the size, in bytes (ANSI version) or characters (Unicode version), of the string pointed to by the lpString2 parameter. If this parameter is  − 1, the string is assumed to be null terminated and the length is calculated automatically.

Return Value

If the function succeeds, the return value is one of the following values:

Value	Meaning
1	The string pointed to by the lpString1 parameter is less in lexical value than the string pointed to by the lpString2 parameter.
2	The string pointed to by lpString1 is equal in lexical value to the string pointed to by lpString2.
3	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 2, 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 non-zero return value. The meaning of < 0, ==0 and > 0 is then consistent with the C runtimes.

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

Normally, strings are compared using what is called a "word sort" technique. In a word sort, all punctuation marks and other non-alphanumeric characters, except for the hyphen and the apostrophe, come before any alphanumeric character. The hyphen and the apostrophe are treated differently than the other non-alphanumeric 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 non-alphanumeric 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.

See Also

FoldString, GetSystemDefaultLCID, GetUserDefaultLCID, LCMapString, lstrcmp, lstrcmpi,MAKELCID


ConfigurePort
 ConfigurePort  QuickInfo  Overview  Group

The ConfigurePort function displays the port-configuration dialog box for a port on the specified server.

BOOL ConfigurePort(

LPTSTR  pName,	// address of server name
HWND  hWnd,	// handle of parent window of the dialog box
LPTSTR  pPortName	// address of port name
);
Parameters

pName

Points to a null-terminated string that specifies the name of the server on which the given port exists. If this parameter is NULL, the port is local.

hWnd

Identifies the parent window of the port-configuration dialog box.

pPortName

Points to a null-terminated string that specifies the name of the port to be configured.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

Before calling this function, an application should call the EnumPorts function to determine valid port names.

See Also

EnumPorts


connect
 connect  QuickInfo

The Windows Sockets connect function establishes a connection to a peer.

int connect (

SOCKET s,
const struct sockaddr FAR * name,
int namelen
);
Parameters

s

A descriptor identifying an unconnected socket.

name

The name of the peer to which the socket is to be connected.

namelen

The length of the name.

Return Value

If no error occurs, connect returns zero. Otherwise, it returns SOCKET_ERROR, and a specific error code may be retrieved by calling WSAGetLastError.

On a blocking socket, the return value indicates success or failure of the connection attempt.

On a nonblocking socket, if the return value is SOCKET_ERROR, an application should call WSAGetLastError. If this indicates an error code of WSAEWOULDBLOCK, then your application can do one of the following:

•	Use select to determine the completion of the connection request by checking if the socket is writeable.

•	If your application is using the message-based WSAAsyncSelect to indicate interest in connection events, then your application will receive an FD_CONNECT message when the connect operation is complete.

Error Codes

WSANOTINITIALISED	A successful WSAStartup must occur before using this function.
WSAENETDOWN	The Windows Sockets implementation has detected that the network subsystem has failed.
WSAEADDRINUSE	The specified address is already in use.
WSAEINTR	The (blocking) call was canceled using WSACancelBlockingCall.
WSAEINPROGRESS	A blocking Windows Sockets call is in progress.
WSAEADDRNOTAVAIL	The specified address is not available from the local computer.
WSAEAFNOSUPPORT	Addresses in the specified family cannot be used with this socket.
WSAECONNREFUSED	The attempt to connect was forcefully rejected.
WSAEDESTADDREQ	A destination address is required.
WSAEFAULT	The namelen argument is incorrect.
WSAEINVAL	The socket is not already bound to an address.
WSAEISCONN	The socket is already connected.
WSAEMFILE	No more file descriptors are available.
WSAENETUNREACH	The network can't be reached from this host at this time.
WSAENOBUFS	No buffer space is available. The socket cannot be connected.
WSAENOTSOCK	The descriptor is not a socket.
WSAETIMEDOUT	Attempt to connect timed out without establishing a connection.
WSAEWOULDBLOCK	The socket is marked as nonblocking and the connection cannot be completed immediately. It is possible to select the socket while it is connecting by selecting it for writing.
Remarks

This function is used to create a connection to the specified foreign association. The parameter s specifies an unconnected datagram or stream socket If the socket is unbound, unique values are assigned to the local association by the system, and the socket is marked as bound. Note that if the address field of the name structure is all zeroes, connect will return the error WSAEADDRNOTAVAIL.

For stream sockets (type SOCK_STREAM), an active connection is initiated to the foreign host using name (an address in the name space of the socket). When the socket call completes successfully, the socket is ready to send and receive data.

For a datagram socket (type SOCK_DGRAM), a default destination is set, which will be used on subsequent send and recv calls.

See Also

accept, bind, getsockname, recv, socket, select, send, WSAAsyncSelect, WSACancelBlockingCall, WSAStartup


ConnectNamedPipe
 ConnectNamedPipe  QuickInfo  Overview  Group

The ConnectNamedPipe function enables a named pipe server process to wait for a client process to connect to an instance of a named pipe. A client process connects by calling either the CreateFile or CallNamedPipe function.

BOOL ConnectNamedPipe(

HANDLE  hNamedPipe,	// handle of named pipe to connect
LPOVERLAPPED  lpOverlapped	// address of overlapped structure
);
Parameters

hNamedPipe

Identifies the server end of a named pipe instance. This handle is returned by the CreateNamedPipe function.

lpOverlapped

Points to an OVERLAPPED structure. This parameter can be NULL if an overlapped operation is not desired. For a description of how the wait mode and the overlapped mode of the hNamedPipe handle affect the behavior of this function, see the following Remarks section.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

A named pipe server process can use ConnectNamedPipe with a newly created pipe instance. It can also be used with an instance that was previously connected to another client process; in this case, the server process must first call the DisconnectNamedPipe function to disconnect the handle from the previous client before the handle can be reconnected to a new client. Otherwise, ConnectNamedPipe returns FALSE, and GetLastError returns ERROR_NO_DATA if the previous client has closed its handle or ERROR_PIPE_CONNECTED if it has not closed its handle.

The behavior of ConnectNamedPipe depends on two conditions: whether the pipe handle's wait mode is set to blocking or nonblocking and whether the function is set to execute synchronously or in overlapped mode. A server initially specifies a pipe handle's wait mode in the CreateNamedPipe function, and it can be changed by using the SetNamedPipeHandleState function. The function is executed as an overlapped operation if FILE_FLAG_OVERLAPPED was specified when the pipe handle was created and if the lpOverlapped parameter is not NULL. Otherwise, the function is executed synchronously. If an overlapped operation is used, the OVERLAPPED structure pointed to by lpOverlapped must contain a handle to a manual-reset event object (which the server can create by using the CreateEvent function).

If the lpOverlapped parameter is NULL, the system attempts to execute the operation synchronously. If the attempt succeeds, the function does not return until a client is connected or an error occurs. If the attempt fails, the function may fail in unpredictable ways. Successful synchronous operations result in the function returning TRUE if a client connects after the function is called. If a client connects before the function is called, the function returns FALSE and GetLastError returns ERROR_PIPE_CONNECTED. This can happen if a client connects in the interval between the call to CreateNamedPipe and the call to ConnectNamedPipe. In this situation, there is a good connection between client and server, even though the function returns FALSE.

If lpOverlapped is not NULL, the operation executes asynchronously. The function returns immediately with a return value of FALSE. If a client process connects before the function is called, GetLastError returns ERROR_PIPE_CONNECTED. Otherwise, GetLastError returns ERROR_IO_PENDING, which indicates that the operation is executing in the background. When this happens, the event object in the OVERLAPPED structure is set to the nonsignaled state before ConnectNamedPipe returns, and it is set to the signaled state when a client connects to this instance of the pipe. The server process can use any of the wait functions — WaitForSingleObject, WaitForMultipleObjects, WaitForSingleObjectEx, WaitForMultipleObjectsEx, or SleepEx — to determine when the state of the event object is signaled, and it can then use the GetOverlappedResult function to determine the results of the ConnectNamedPipe operation.

If the specified pipe handle is in nonblocking mode, ConnectNamedPipe always returns immediately. In nonblocking mode, ConnectNamedPipe returns TRUE the first time it is called for a pipe instance that is disconnected from a previous client. This indicates that the pipe is now available to be connected to a new client process. In all other situations when the pipe handle is in nonblocking mode, ConnectNamedPipe returns FALSE. In these situations, GetLastError returns ERROR_PIPE_LISTENING if no client is connected, ERROR_PIPE_CONNECTED if a client is connected, and ERROR_NO_DATA if a previous client has closed its pipe handle but the server has not disconnected. Note that a good connection between client and server exists only after the ERROR_PIPE_CONNECTED error is received.

Note that nonblocking mode is supported for compatibility with Microsoft LAN Manager version 2.0, and it should not be used to achieve asynchronous input and output (I/O) with named pipes.

See Also

CallNamedPipe, CreateEvent, CreateFile, CreateNamedPipe, DisconnectNamedPipe, GetOverlappedResult, SetNamedPipeHandleState, SleepEx, WaitForMultipleObjects, WaitForMultipleObjectsEx, WaitForSingleObject, WaitForSingleObjectEx, OVERLAPPED


ConnectToPrinterDlg
 ConnectToPrinterDlg  QuickInfo  Overview  Group

The ConnectToPrinterDlg function displays a dialog box that lets users browse and connect to printers on a network. If the user selects a printer, the function attempts to create a connection to it; if a suitable driver is not installed on the server, the user is given the option of creating a printer locally.

HANDLE ConnectToPrinterDlg (

HWND  hwnd,	// handle of parent window of dialog box
DWORD  Flags	// reserved for future use, must be zero
);
Parameters

hwnd

Specifies the parent window of the dialog box.

Flags

This parameter is reserved for future use. Set it to zero.

Return Value

If the function succeeds and the user selects a printer, the return value is a handle to the selected printer.

If the function fails, or the user cancels the dialog box without selecting a printer, the return value is NULL.

Remarks

The ConnectToPrinterDlg function attempts to create a connection to the selected printer. However, if the server on which the printer resides does not have a suitable driver installed, the function offers the user the option of creating a printer locally. A calling application can determine whether the function has created a printer locally by calling GetPrinter with a PRINTER_INFO_2 structure, then examining that structure's Attributes member.

An application should call DeletePrinter to delete a local printer. An application should call DeletePrinterConnection to delete a connection to a printer.

See Also

AddPrinterConnection, ClosePrinter, DeletePrinter, DeletePrinterConnection, GetPrinter, PRINTER_INFO_2


ContinueDebugEvent
 ContinueDebugEvent  QuickInfo  Overview  Group

The ContinueDebugEvent function enables a debugger to continue a thread that previously reported a debugging event.

BOOL ContinueDebugEvent(

DWORD  dwProcessId,	// process to continue
DWORD  dwThreadId,	// thread to continue
DWORD  dwContinueStatus	// continuation status
);
Parameters

dwProcessId

Identifies the process to continue.

dwThreadId

Identifies the thread to continue. The combination of process identifier and thread identifier must identify a thread that has previously reported a debugging event.

dwContinueStatus

Specifies how to continue the thread that reported the debugging event.

If the DBG_CONTINUE flag is specified for this parameter and the thread specified by the dwThreadId parameter previously reported an EXCEPTION_DEBUG_EVENT debugging event, the function stops all exception processing and continues the thread. For any other debugging event, this flag simply continues the thread.

If the DBG_EXCEPTION_NOT_HANDLED flag is specified for this parameter and the thread specified by dwThreadId previously reported an EXCEPTION_DEBUG_EVENT debugging event, the function continues exception processing. If this is a first-chance exception event, the search and dispatch logic of the structured exception handler is used; otherwise, the process is terminated. For any other debugging event, this flag simply continues the thread.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

Only the thread that created dwProcessId with the CreateProcess function can call ContinueDebugEvent.

After this function succeeds, the specified thread continues. Depending on the debugging event previously reported by the thread, different actions occur. If the continued thread previously reported an EXIT_THREAD_DEBUG_EVENT debugging event, ContinueDebugEvent closes the handle the debugger has to the thread. If the continued thread previously reported an EXIT_PROCESS_DEBUG_EVENT debugging event, ContinueDebugEvent closes the handles the debugger has to the process and to the thread.

See Also

CreateProcess


ControlService
 ControlService  QuickInfo  Overview  Group

The ControlService function sends a control code to a Win32 service.

BOOL ControlService(

SC_HANDLE  hService,	// handle of service
DWORD  dwControl,	// control code
LPSERVICE_STATUS  lpServiceStatus	// address of service status structure
);
Parameters

hService

Identifies the service. This handle is returned by the OpenService or CreateService function. The access required for this handle depends on the dwControl code requested.

dwControl

Specifies the requested control code. This value can be one of the standard control codes in the table, or it can be a user-defined control code in the range of 128 to 255, inclusive. For user-defined control codes, the hService handle must have SERVICE_USER_DEFINE_CONTROL access, and the service defines the action associated with the control code.

Value	Meaning
SERVICE_CONTROL_STOP
	Requests the service to stop. The hService handle must have SERVICE_STOP access.
SERVICE_CONTROL_PAUSE
	Requests the service to pause. The hService handle must have SERVICE_PAUSE_CONTINUE access.
SERVICE_CONTROL_CONTINUE
	Requests the paused service to resume. The hService handle must have SERVICE_PAUSE_CONTINUE access.
SERVICE_CONTROL_INTERROGATE
	Requests the service to update immediately its current status information to the service control manager. The hService handle must have SERVICE_INTERROGATE access.
SERVICE_CONTROL_SHUTDOWN
	The ControlService function fails if this control code is specified.
lpServiceStatus

Points to a SERVICE_STATUS structure where the latest status information of the service is returned. The information returned reflects the most recent status reported by the service to the service control manager.

Return Value

If the function succeeds, the return value is TRUE.

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

Errors

The following error codes may be set by the service control manager. Other error codes may be set by the registry functions that are called by the service control manager.

Value	Meaning
ERROR_ACCESS_DENIED
	The specified handle was not opened with the necessary access.
ERROR_DEPENDENT_SERVICES_RUNNING
	The service cannot be stopped because other running services are dependent on it.
ERROR_INVALID_SERVICE_CONTROL
	The requested control code is not valid, or it is unacceptable to the service.
ERROR_SERVICE_CANNOT_ACCEPT_CTRL
	The requested control code cannot be sent to the service because the state of the service is SERVICE_STOPPED, SERVICE_START_PENDING, or SERVICE_STOP_PENDING.
ERROR_SERVICE_NOT_ACTIVE
	The service has not been started.
ERROR_SERVICE_REQUEST_TIMEOUT
	The service did not respond to the start request in a timely fashion.
Remarks

The ControlService function asks the service control manager to send the requested control code to the service. The service control manager sends the code if the service accepts the control and if the service is in a controllable state. The QueryServiceStatus or ControlService function returns a SERVICE_STATUS structure whose dwCurrentState and dwControlsAccepted members indicate the current state and controls accepted by a running Win32 service.

All running services accept the SERVICE_CONTROL_INTERROGATE control code by default. Each service specifies the other control codes that it accepts when it calls the SetServiceStatus function to report its status.

The following table shows the action of the service control manager in each of the possible service states:

Service state	Stop	Other controls
STOPPED	(c)	(c)
STOP_PENDING	(b)	(b)
START_PENDING	(a)	(b)
RUNNING	(a)	(a)
CONTINUE_PENDING	(a)	(a)
PAUSE_PENDING	(a)	(a)
PAUSED	(a)	(a)
(a) If the service accepts this control code, send the request to the service; otherwise, ControlService returns FALSE and GetLastError returns ERROR_INVALID_SERVICE_CONTROL.
(b) The service is not in a controllable state, so ControlService returns FALSE and GetLastError returns ERROR_SERVICE_CANNOT_ACCEPT_CTRL.
(c) The service is not in a controllable state, so ControlService returns FALSE and GetLastError returns ERROR_SERVICE_NOT_ACTIVE.
See Also

CreateService, OpenService, QueryServiceStatus, SetServiceStatus, SERVICE_STATUS


ConvertDefaultLocale
 ConvertDefaultLocale  QuickInfo  Overview  Group

The ConvertDefaultLocale function converts a special default locale value to an actual locale identifier.

LCID ConvertDefaultLocale(

LCID  Locale	// special default locale value to be converted
);
Parameters

Locale

A special default locale value that the function converts to an actual locale identifier.

The following list shows the special default locale values:

Value	Description
LOCALE_SYSTEM_DEFAULT	The system's default locale.
LOCALE_USER_DEFAULT	The current user's default locale.
zero	The language-neutral default locale. This is equivalent to the locale identifier created by calling the MAKELCID macro with a language identifier consisting of the LANG_NEUTRAL and SUBLANG_NEUTRAL values.
Any sublanguage neutral default locale	A locale identifier constructed by calling MAKELCID with a language identifier consisting of a primary language value, such as LANG_ENGLISH, and the SUBLANG_NEUTRAL value.
Return Value

If the function succeeds, the return value is the appropriate actual locale identifier.

If the function fails, the return value is the Locale parameter. The function fails when Locale is not one of the special default locale values listed above.

Remarks

A call to ConvertDefaultLocale(LOCALE_SYSTEM_DEFAULT) is equivalent to a call to GetSystemDefaultLCID. A call to ConvertDefaultLocale(LOCALE_USER_DEFAULT) is equivalent to a call to GetUserDefaultLCID.

For more information about locale identifiers, see Locales and Language Identifiers.

See Also

GetSystemDefaultLCID, GetUserDefaultLCID


CopyAcceleratorTable
 CopyAcceleratorTable  QuickInfo  Overview  Group

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 of accelerator table to copy
LPACCEL  lpAccelDst,	// address of structure receiving copy
int  cAccelEntries	// number of entries in table being copied
);
Parameters

hAccelSrc

Identifies the accelerator table to copy.

lpAccelDst

Points to an array of ACCEL structures where the accelerator-table information is to be copied.

cAccelEntries

Specifies the number of ACCEL structures to copy to the buffer pointed to by the lpAccelDst parameter.

Return Value

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.

See Also

ACCEL, CreateAcceleratorTable, DestroyAcceleratorTable, LoadAccelerators, TranslateAccelerator


CopyCursor
 CopyCursor  QuickInfo  Overview  Group

The CopyCursor function copies a cursor.

HCURSOR CopyCursor(

HCURSOR  pcur	// handle of cursor to copy
);
Parameters

pcur

Identifies the cursor to be copied.

Return Value

If the function succeeds, the return value is the handle of the duplicate cursor.

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

Remarks

CopyCursor enables an application or dynamic-link library (DLL) to obtain the handle of a cursor shape owned by another module. Then if the other module is freed, the application is still able to use the cursor shape.

See Also

CopyIcon, GetCursor, SetCursor, ShowCursor


CopyEnhMetaFile
 CopyEnhMetaFile  QuickInfo  Overview  Group

The CopyEnhMetaFile function copies the contents of an enhanced-format metafile to a specified file.

HENHMETAFILE CopyEnhMetaFile(

HENHMETAFILE  hemfSrc,	// handle of an enhanced metafile
LPCTSTR  lpszFile	// address of a filename string
);
Parameters

hemfSrc

Identifies the source-enhanced metafile.

lpszFile

Points to the name of the destination file. If this parameter is NULL, the source metafile is copied to memory.

Return Value

If the function succeeds, the return value is a handle of the copy of the enhanced metafile.

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

Remarks

Where text arguments must use Unicode characters, use this function as a wide-character function. Where text arguments must use characters from the Windows 3.x character set, use this function as an ANSI function.

Applications can use metafiles stored in memory for temporary operations.

When the application no longer needs the enhanced-metafile handle, it should delete the handle by calling the DeleteEnhMetaFile function.

See Also

DeleteEnhMetaFile


CopyFile
 CopyFile  QuickInfo  Overview  Group

The CopyFile function copies an existing file to a new file.

BOOL CopyFile(

LPCTSTR  lpExistingFileName,	// address of name of an existing file
LPCTSTR  lpNewFileName,	// address of filename to copy to
BOOL  bFailIfExists	// flag for operation if file exists
);
Parameters

lpExistingFileName

Points to a null-terminated string that specifies the name of an existing file.

lpNewFileName

Points to a null-terminated string that specifies the name of the new file.

bFailIfExists

Specifies how this operation is to proceed if a file of the same name as that specified by lpNewFileName already exists. If this parameter is TRUE and the new file already exists, the function fails. If this parameter is FALSE and the new file already exists, the function overwrites the existing file and succeeds.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

Security attributes for the existing file are not copied to the new file.

File attributes (FILE_ATTRIBUTE_*) for the existing file are copied to the new file. For example, if an existing file has the FILE_ATTRIBUTE_READONLY file attribute, a copy created through a call to CopyFile will also have the FILE_ATTRIBUTE_READONLY file attribute. For further information on file attributes, see CreateFile.

See Also

CreateFile, MoveFile


CopyIcon
 CopyIcon  QuickInfo  Overview  Group

The CopyIcon function copies the specified icon from another module to the current module.

HICON CopyIcon(

HICON  hIcon	// handle of icon to copy
);
Parameters

hIcon

Identifies the icon to be copied.

Return Value

If the function succeeds, the return value is the handle of 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 of an icon owned by another module. If the other module is freed, the application icon will still be able to use the icon.

See Also

CopyCursor, DrawIcon, DrawIconEx


CopyImage [New - Windows 95]
 CopyImage  QuickInfo  Overview  Group

The CopyImage function creates a new image (icon, cursor, or bitmap) and copies the attributes of the given 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 of the image to copy
UINT  uType,	// type of image to copy
int  cxDesired,	// desired width of new image
int  cyDesired,	// desired height of new image
UINT  fuFlags	// copy flags
);
Parameters

hinst

Identifies an instance of the module that contains the image to be copied.

uType

Specifies the type of image to be copied. This parameter can be one of the following values:

Value	Meaning
IMAGE_BITMAP	Copies a bitmap.
IMAGE_CURSOR	Copies a cursor.
IMAGE_ICON	Copies an icon.
cxDesired

Specifies the desired width, in pixels, of the image.

cyDesired

Specifies the desired height, in pixels, of the image.

fuFlags

Specifies a combination of the following values:

Value	Meaning
LR_COPYDELETEORG	Deletes the original image after creating the copy.
LR_COPYRETURNORG	Creates an exact copy of the image, ignoring the cxDesired and cyDesired parameters.
LR_MONOCHROME	Creates a new monochrome image.
LR_COPYFROMRESOURCE	Windows 95 only: Tries to reload an icon or cursor resource from the original resource file rather than simply copying the current image. This is useful for creating a different-sized copy when the resource file contains multiple sizes of the resource. Without this flag, CopyImage stretches the original image to the new size. If this flag is set, CopyImage uses the size in the resource file closest to the desired size. This will succeed only if hImage was loaded by LoadIcon or LoadCursor, or by LoadImage with the LR_SHARED flag.
Return Value

If the function succeeds, the return value is the handle of the newly created image.

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

See Also

LoadImage


CopyLZFile
 CopyLZFile  QuickInfo  Overview  Group

The CopyLZFile function is obsolete. It is provided only for compatibility with 16-bit versions of Windows. For Win32-based applications, use the LZCopy function.


CopyMemory
 CopyMemory  QuickInfo  Overview  Group

The CopyMemory function copies a block of memory from one location to another.

VOID CopyMemory (

PVOID  Destination,	// address of copy destination
CONST VOID *  Source,	// address of block to copy
DWORD  Length	// size, in bytes, of block to copy
);
Parameters

Destination

Points to the starting address of the copied block's destination.

Source

Points to the starting address of the block of memory to copy.

Length

Specifies the size, in bytes, of the block of memory to copy.

Return Value

This function has no return value.

Remarks

If the source and destination blocks overlap, the results are undefined. For overlapped blocks, use the MoveMemory function.

See Also

FillMemory, MoveMemory, ZeroMemory


CopyMetaFile
 CopyMetaFile  QuickInfo  Overview  Group

The CopyMetaFile function copies the content of a Windows-format metafile to the specified file.

This function is provided for compatibility with 16-bit versions of Windows. Win32-based applications should use the CopyEnhMetaFile function.

HMETAFILE CopyMetaFile(

HMETAFILE  hmfSrc,	// handle of a Windows-format metafile
LPCTSTR  lpszFile	// address of a filename string
);
Parameters

hmfSrc

Identifies the source Windows-format metafile.

lpszFile

Points to the name of the destination file. If this parameter is NULL, the source metafile is copied to memory.

Return Value

If the function succeeds, the return value is a handle of the copy of the Windows-format metafile.

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

Remarks

The CopyMetaFile function supports only applications designed for Windows version 3.x. It does not record or play back the new graphics device interface functions, such as PolyBezier.

Where text arguments must use Unicode characters, use this function as a wide-character function. Where text arguments must use characters from the Windows 3.x character set, use this function as an ANSI function.

When the application no longer needs the Windows-format metafile handle, it should delete the handle by calling the DeleteMetaFile function.

See Also

DeleteMetaFile


CopyRect
 CopyRect  QuickInfo  Overview  Group

The CopyRect function copies the coordinates of one rectangle to another.

BOOL CopyRect(

LPRECT  lprcDst,	// address of structure for destination rectangle
CONST RECT  *lprcSrc	// address of structure with source rectangle
);
Parameters

lprcDst

Points to the RECT structure that will receive the logical coordinates of the source rectangle.

lprcSrc

Points to the RECT structure whose coordinates are to be copied.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

RECT, SetRect, SetRectEmpty


CopySid
 CopySid  QuickInfo  Overview  Group

The CopySid function copies a security identifier (SID) to a buffer.

BOOL CopySid(

DWORD  nDestinationSidLength,	// size of buffer for copied SID
PSID  pDestinationSid,	// address of buffer for copied SID
PSID  pSourceSid	// address of source SID
);
Parameters

nDestinationSidLength

Specifies the length, in bytes, of the buffer receiving the copy of the SID.

pDestinationSid

Points to a buffer receiving a copy of the source SID structure.

pSourceSid

Points to a SID structure the function copies to the buffer pointed to by the pDestinationSid parameter.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

An application can use the CopySid function to make a copy of a SID in an access token (in a TOKEN_GROUPS structure, for instance) to use in an access-control entry.

See Also

AllocateAndInitializeSid, EqualSid, GetLengthSid, GetSidIdentifierAuthority, GetSidLengthRequired, GetSidSubAuthority, GetSidSubAuthorityCount, InitializeSid, IsValidSid, SID


CountClipboardFormats
 CountClipboardFormats  QuickInfo  Overview  Group

The CountClipboardFormats function retrieves the number of different data formats currently on the clipboard.

int CountClipboardFormats(VOID)

Parameters

This function has no parameters.

Return Value

If the function succeeds, the return value is the number of different data formats currently on the clipboard.

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

See Also

EnumClipboardFormats, RegisterClipboardFormat


 CountVoiceNotes

The CountVoiceNotes function has been deleted.

See Also

Beep, MessageBeep


CPlApplet
 CPlApplet  Overview  Group

The CPlApplet function is a library-defined callback function that serves as the entry point for a Control Panel application.

LONG APIENTRY CPlApplet(

HWND  hwndCPl,	// handle of Control Panel window
UINT  uMsg,	// message
LONG  lParam1,	// first message parameter
LONG  lParam2	// second message parameter
);
Parameters

hwndCPl

Identifies the main window of the controlling application.

uMsg

Specifies the message being sent to the Control Panel application.

lParam1

Specifies additional message-specific information.

lParam2

Specifies additional message-specific information.

Return Value

The return value depends on the message. For more information, see the descriptions of the individual Control Panel messages.

Remarks

Use the hwndCPl parameter for dialog boxes or other windows that require a handle of a parent window.


CreateAcceleratorTable
 CreateAcceleratorTable  QuickInfo  Overview  Group

The CreateAcceleratorTable function creates an accelerator table.

HACCEL CreateAcceleratorTable(

LPACCEL  lpaccl,	// address of structure array with accelerator data
int  cEntries	// number of structures in the array
);
Parameters

lpaccl

Points to an array of ACCEL structures that describes the accelerator table.

cEntries

Specifies the number of ACCEL structures in the array.

Return Value

If the function succeeds, the return value is the handle of the created accelerator table; otherwise, it is NULL.

Remarks

Before an application closes, it must use the DestroyAcceleratorTable function to destroy each accelerator table that it created by using the CreateAcceleratorTable function.

See Also

ACCEL, CopyAcceleratorTable, DestroyAcceleratorTable, LoadAccelerators, TranslateAccelerator


CreateBitmap
 CreateBitmap  QuickInfo  Overview  Group

The CreateBitmap function creates a bitmap with the specified width, height, and color format (color planes and bits per pixel).

HBITMAP CreateBitmap(

int  nWidth,	// bitmap width, in pixels
int  nHeight,	// bitmap height, in pixels
UINT  cPlanes,	// number of color planes used by device
UINT  cBitsPerPel,	// number of bits required to identify a color
CONST VOID  *lpvBits	// address of array containing color data
);
Parameters

nWidth

Specifies the bitmap width, in pixels.

nHeight

Specifies the bitmap height, in pixels.

cPlanes

Specifies the number of color planes used by the device.

cBitsPerPel

Specifies the number of bits required to identify the color of a single pixel.

lpvBits

Points to an array of color data used to set the colors in a rectangle of pixels. Each scan line in the rectangle must be word aligned (scan lines that are not word aligned must be padded with zeros). If this parameter is NULL, the new bitmap is undefined.

Return Value

If the function succeeds, the return value is a handle of a bitmap.

If the function fails, the return value is NULL.

Remarks

After a bitmap is created, it can be selected into a device context by calling the SelectObject function.

While the CreateBitmap function can be used to create color bitmaps, for performance reasons applications should use CreateBitmap to create monochrome bitmaps and CreateCompatibleBitmap to create color bitmaps. When a color bitmap returned from CreateBitmap is selected into a device context, Windows must ensure that the bitmap matches the format of the device context it is being selected into. Since CreateCompatibleBitmap takes a device context, it returns a bitmap that has the same format as the specified device context. Because of this, subsequent calls to SelectObject are faster than with a color bitmap returned from CreateBitmap.

If the bitmap is monochrome, zeros represent the foreground color and ones represent the background color for the destination device context.

If an application sets the nWidth or nHeight parameters to zero, CreateBitmap returns the handle of a 1- by 1-pixel, monochrome bitmap.

When you no longer need the bitmap, call the DeleteObject function to delete it.

See Also

CreateBitmapIndirect, CreateCompatibleBitmap, CreateDIBitmap, DeleteObject, GetBitmapBits, SelectObject, SetBitmapBits


CreateBitmapIndirect
 CreateBitmapIndirect  QuickInfo  Overview  Group

The CreateBitmapIndirect function creates a bitmap with the specified width, height, and color format (color planes and bits per pixel).

HBITMAP CreateBitmapIndirect(

CONST BITMAP *lpbm	// address of the bitmap data
);
Parameters

lpbm

Points to a BITMAP structure that contains information about the bitmap. If an application sets the bmWidth or bmHeight members to zero, CreateBitmapIndirect returns the handle of a 1- by 1-pixel, monochrome bitmap.

Return Value

If the function succeeds, the return value is a handle of the bitmap.

If the function fails, the return value is NULL.

Remarks

After a bitmap is created, it can be selected into a device context by calling the SelectObject function.

While the CreateBitmapIndirect function can be used to create color bitmaps, for performance reasons applications should use CreateBitmapIndirect to create monochrome bitmaps and CreateCompatibleBitmap to create color bitmaps. When a color bitmap returned from CreateBitmapIndirect is selected into a device context, Windows must ensure that the bitmap matches the format of the device context it is being selected into. Since CreateCompatibleBitmap takes a device context, it returns a bitmap that has the same format as the specified device context. Because of this, subsequent calls to SelectObject are faster than with a color bitmap returned from CreateBitmapIndirect.

If the bitmap is monochrome, zeros represent the foreground color and ones represent the background color for the destination device context.

When you no longer need the bitmap, call the DeleteObject function to delete it.

See Also

BitBlt, BITMAP, CreateBitmap, CreateCompatibleBitmap, CreateDIBitmap, DeleteObject, SelectObject


CreateBrushIndirect
 CreateBrushIndirect  QuickInfo  Overview  Group

The CreateBrushIndirect function creates a logical brush that has the specified style, color, and pattern.

HBRUSH CreateBrushIndirect(

CONST LOGBRUSH *  lplb	// address of structure describing brush
);
Parameters

lplb

Points to a LOGBRUSH structure that contains information about the brush.

Return Value

If the function succeeds, the return value identifies a logical brush.

If the function fails, the return value is NULL.

Remarks

A brush is a bitmap that Windows uses to paint the interiors of filled shapes.

After an application creates a brush by calling CreateBrushIndirect, it can select it into any device context by calling the SelectObject function.

A brush created by using a monochrome bitmap (one color plane, one bit per pixel) is drawn using the current text and background colors. Pixels represented by a bit set to 0 are drawn with the current text color; pixels represented by a bit set to 1 are drawn with the current background color.

If the lbStyle member of the LOGBRUSH structure pointed to by lplb is BS_PATTERN, the bitmap pointed to by the lbHatch member of that structure cannot be a DIB section. A DIB section is a bitmap created by CreateDibSection. If that bitmap is a DIB section, the CreateBrushIndirect function fails.

When you no longer need the brush, call the DeleteObject function to delete it.

See Also

CreateDibSection, DeleteObject, GetBrushOrgEx, LOGBRUSH, SelectObject, SetBrushOrgEx


CreateCaret
 CreateCaret  QuickInfo  Overview  Group

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 of owner window
HBITMAP  hBitmap,	// handle of bitmap for caret shape
int  nWidth,	// caret width
int  nHeight	// caret height
);
Parameters

hWnd

Identifies the window that owns the caret.

hBitmap

Identifies the bitmap that defines the caret shape. If this parameter is NULL, the caret is solid. If this parameter is (HBITMAP) 1, the caret is gray. If this parameter is a bitmap handle, the caret is the specified bitmap. The bitmap handle must have been created by the CreateBitmap, CreateDIBitmap, or LoadBitmap function.

If hBitmap is a bitmap handle, CreateCaret ignores the nWidth and nHeight parameters; the bitmap defines its own width and height.

nWidth

Specifies the width of the caret in logical units. If this parameter is zero, the width is set to the system-defined window border width. If hBitmap is a bitmap handle, CreateCaret ignores this parameter.

nHeight

Specifies the height, in logical units, of the caret. If this parameter is zero, the height is set to the system-defined window border height. If hBitmap is a bitmap handle, CreateCaret ignores this parameter.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. 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 caret is a shared resource; there is only one caret in the system. 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.

See Also

CreateBitmap, CreateDIBitmap, DestroyCaret, GetSystemMetrics, HideCaret, LoadBitmap, ShowCaret


CreateColorSpace [New - Windows 95]
 CreateColorSpace  QuickInfo  Overview  Group

[New - Windows 95]

The CreateColorSpace function creates a logical color space.

HCOLORSPACE CreateColorSpace(

LPLOGCOLORSPACE  lpLogColorSpace
);
Parameters

lpLogColorSpace

Pointer to the LOGCOLORSPACE structure.

Return Value

If the function succeeds, the return value is a handle that identifies a logical color space.

If the function fails, the return value is NULL.

Remarks

When you no longer need the color space, call the DeleteObject function to delete it.

See Also

DeleteObject, LOGCOLORSPACE


CreateCompatibleBitmap
 CreateCompatibleBitmap  QuickInfo  Overview  Group

The CreateCompatibleBitmap function creates a bitmap compatible with the device that is associated with the specified device context.

HBITMAP CreateCompatibleBitmap(

HDC  hdc,	// handle of device context
int  nWidth,	// width of bitmap, in pixels
int  nHeight	// height of bitmap, in pixels
);
Parameters

hdc

Identifies a device context.

nWidth

Specifies the bitmap width, in pixels.

nHeight

Specifies the bitmap height, in pixels.

Return Value

If the function succeeds, the return value is a handle of the bitmap.

If the function fails, the return value is NULL.

Remarks

The color format of the bitmap created by this function matches the color format of the device identified by the hdc parameter. This bitmap can be selected into any memory device context that is compatible with the original device.

Because memory device contexts allow both color and monochrome bitmaps, the format of the bitmap returned by the CreateCompatibleBitmap function differs when the specified device context is a memory device context. However, a compatible bitmap that was created for a nonmemory device context always possesses the same color format and uses the same color palette as the specified device context.

If an application sets the nWidth or nHeight parameters to zero, CreateCompatibleBitmap returns the handle of a 1- by 1-pixel, monochrome bitmap.

If a DIB section, which is a bitmap created by the CreateDIBSection function, is selected into the device context identified by the hdc parameter, the CreateCompatibleBitmap function creates a DIB section.

When you no longer need the bitmap, call the DeleteObject function to delete it.

See Also

CreateDIBSection, DeleteObject, SelectObject


CreateCompatibleDC
 CreateCompatibleDC  QuickInfo  Overview  Group

The CreateCompatibleDC function creates a memory device context (DC) compatible with the specified device.

HDC CreateCompatibleDC(

HDC  hdc	// handle of memory device context
);
Parameters

hdc

Identifies the device context. If this handle is NULL, the function creates a memory device context compatible with the application's current screen.

Return Value

If the function succeeds, the return value is the handle of a memory device context.

If the function fails, the return value is NULL.

Remarks

Before an application can use a memory device context for drawing operations, it must select a bitmap of the correct width and height into the device context. Once a bitmap has been selected, the device context can be used to prepare images that will be copied to the screen or printed.

This function can only be used with devices that support raster operations. An application can determine whether a device supports these operations by calling the GetDeviceCaps function.

When you no longer need the memory device context, call the DeleteDC function to delete it.

See Also

CreateCompatibleBitmap, DeleteDC, GetDeviceCaps


CreateConsoleScreenBuffer
 CreateConsoleScreenBuffer  QuickInfo  Overview  Group

The CreateConsoleScreenBuffer function creates a console screen buffer and returns a handle of it.

HANDLE CreateConsoleScreenBuffer(

DWORD  dwDesiredAccess,	// access flag
DWORD  dwShareMode,	// buffer share mode
LPSECURITY_ATTRIBUTES  *lpSecurityAttributes,	// address of security attributes
DWORD  dwFlags,	// type of buffer to create
LPVOID  lpScreenBufferData	// reserved
);
Parameters

dwDesiredAccess

Specifies the desired access to the console screen buffer. This parameter can be one or both of the following values:

Value	Meaning
GENERIC_READ	Requests read access to the console screen buffer, enabling the process to read data from the buffer.
GENERIC_WRITE	Requests write access to the console screen buffer, enabling the process to write data to the buffer.
dwShareMode

Specifies how this console screen buffer can be shared. This parameter can be zero, indicating that the buffer cannot be shared, or it can be one or both of the following two values:

Value	Meaning
FILE_SHARE_READ	Other open operations can be performed on the console screen buffer for read access.
FILE_SHARE_WRITE	Other open operations can be performed on the console screen buffer for write access.
*lpSecurityAttributes

Points to a SECURITY_ATTRIBUTES structure that specifies the security attributes for the console screen buffer.

dwFlags

Specifies the type of console screen buffer to create. The only currently supported screen buffer type is CONSOLE_TEXTMODE_BUFFER.

lpScreenBufferData

Reserved for possible future use; should be NULL.

Return Value

If the function succeeds, the return value is a handle of the new console screen buffer.

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

Remarks

A console can have multiple screen buffers but only one active screen buffer. Inactive screen buffers can be accessed for reading and writing, but only the active screen buffer is displayed. To make the new screen buffer the active screen buffer, use the SetConsoleActiveScreenBuffer function.

The calling process can use the returned handle in any function that requires a handle of a console screen buffer, subject to the limitations of access specified by the dwDesiredAccess parameter.

The calling process can use the DuplicateHandle function to create a duplicate screen buffer handle that has different access or inheritability from the original handle. However, DuplicateHandle cannot be used to create a duplicate that is valid for a different process (except through inheritance).

To close the screen buffer handle, use the CloseHandle function.

See Also

CloseHandle, DuplicateHandle, GetConsoleScreenBufferInfo, SECURITY_ATTRIBUTES, SetConsoleActiveScreenBuffer, SetConsoleScreenBufferSize


CreateCursor
 CreateCursor  QuickInfo  Overview  Group

The CreateCursor function creates a cursor having the specified size, bit patterns, and hot spot.

HCURSOR CreateCursor(

HINSTANCE  hInst,	// handle of application instance
int  xHotSpot,	// horizontal position of hot spot
int  yHotSpot,	// vertical position of hot spot
int  nWidth,	// cursor width
int  nHeight,	// cursor height
CONST VOID  *pvANDPlane,	// address of AND bitmask array
CONST VOID  *pvXORPlane	// address of XOR bitmask array
);
Parameters

hInst

Identifies the current instance of the application creating the cursor.

xHotSpot

Specifies the horizontal position of the cursor's hot spot.

yHotSpot

Specifies the vertical position of the cursor's hot spot.

nWidth

Specifies the width, in pixels, of the cursor.

nHeight

Specifies the height, in pixels, of the cursor.

pvANDplane

Points to an array of bytes that contains the bit values for the AND bitmask of the cursor, as in a device-dependent monochrome bitmap.

pvXORplane

Points to an array of bytes that contains the bit values for the XOR bitmask of the cursor, as in a device-dependent monochrome bitmap.

Return Value

If the function succeeds, the return value identifies the cursor.

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

Remarks

The nWidth and nHeight parameters must specify a width and height that are supported by the current display driver, because the system cannot create cursors of other sizes. To determine the width and height supported by the display driver, use the GetSystemMetrics function, specifying the SM_CXCURSOR or SM_CYCURSOR value.

Before closing, an application must call the DestroyCursor function to free any system resources associated with the cursor.

See Also

CreateIcon, DestroyCursor, GetModuleHandle, GetSystemMetrics, SetCursor


CreateDC
 CreateDC  QuickInfo  Overview  Group

The CreateDC function creates a device context (DC) for a device by using the specified name.

HDC CreateDC(

LPCTSTR  lpszDriver,	// address of string specifying driver name
LPCTSTR  lpszDevice,	// address of string specifying device name
LPCTSTR  lpszOutput,	// do not use; set to NULL
CONST DEVMODE  *lpInitData	// address of optional printer data
);
Parameters

lpszDriver

Applications written for earlier versions of Windows used this parameter to specify the filename (without extension) of the device driver.

Windows 95: In Win32-based applications, this parameter is ignored and should be NULL, with one exception: You may obtain a display device context by specifying the null-terminated string "DISPLAY". If this parameter is "DISPLAY", all other parameters must be NULL.

Windows NT: Points to a null-terminated character string that specifies either "DISPLAY" for a display driver, or the name of a printer driver, which is usually "WINSPOOL".

lpszDevice

Points to a null-terminated character string that specifies the name of the specific output device being used, as shown by the Print Manager (for example, "Epson FX-80"). It is not the printer model name. The lpszDevice parameter must be used.

lpszOutput

This parameter is ignored. Do not use it in a Win32 application. Win32-based applications should set this parameter to NULL. It exists to provide compatibility for applications written for earlier versions of Windows. For more information, see the following Remarks section.

lpInitData

Points to a DEVMODE structure containing device-specific initialization data for the device driver. The DocumentProperties function retrieves this structure filled in for a given device. The lpInitData parameter must be NULL if the device driver is to use the default initialization (if any) specified by the user.

Return Value

If the function succeeds, the return value is the handle of a device context for the specified device.

If the function fails, the return value is NULL.

Remarks

Applications written for earlier versions of Windows used the lpszOutput parameter to specify a port name or to print to a file. Win32-based applications do not need to specify a port name. Win32-based applications can print to a file by calling the StartDoc function with a DOCINFO structure whose lpszOutput member specifies the path of the output filename.

When you no longer need the device context, call the DeleteDC function to delete it.

See Also

DeleteDC, DEVMODE, DOCINFO, DocumentProperties, StartDoc


CreateDesktop [New - Windows NT]
 CreateDesktop  QuickInfo  Overview  Group

[New - Windows NT]

The CreateDesktop function creates a new desktop on the window station associated with the calling process. It returns 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 the new desktop
LPCTSTR lpszDevice,	// name of display device to assign to the desktop
LPDEVMODE pDevMode,	// reserved; must be NULL
DWORD dwFlags,	// flags to control interaction with other applications
DWORD dwDesiredAccess,	// specifies access of returned handle
LPSECURITY_ATTRIBUTES lpsa	// specifies security attributes of the desktop
);
Parameters

lpszDesktop

Points 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

If specified, points to a null-terminated string specifying the name of the display device to assign to the desktop. The name must begin with a backslash character (\). If lpszDevice is NULL, the default display driver loaded at boot time is used.

pDevMode

Reserved; must be NULL.

dwFlags

A bit flag parameter that controls how the calling application will cooperate with other applications on the desktop. This parameter can specify 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

Specifies the type of access to the desktop. This parameter can be one or more of the following values:

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

Points to a SECURITY_ATTRIBUTES structure that specifies the security attributes for the desktop.

If either lpsa or lpsa->lpSecurityDescriptor is NULL, the desktop inherits its security descriptor from the parent window station, and the resulting handle is not inheritable.

Return Value

If the function succeeds, the return value is a handle of the newly created desktop.

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.

See Also

SECURITY_ATTRIBUTES, SetProcessWindowStation, SwitchDesktop


CreateDialog
 CreateDialog  QuickInfo  Overview  Group

The CreateDialog function creates a modeless dialog box from a dialog box template resource.

HWND CreateDialog(

HINSTANCE  hInstance,	// handle of application instance
LPCTSTR  lpTemplate,	// identifies dialog box template name
HWND  hWndParent,	// handle of owner window
DLGPROC  lpDialogFunc	// address of dialog box procedure
);
Parameters

hInstance

Identifies an instance of the module whose executable file contains the dialog box template.

lpTemplate

Identifies the dialog box template. This parameter is either the address of a null-terminated character string that specifies the name of the dialog box template or an integer value that specifies the resource identifier of the dialog box template. If the parameter specifies a resource identifier, its high-order word must be zero and its low-order word must contain the identifier. You can use the MAKEINTRESOURCE macro to create this value.

hWndParent

Identifies the window that owns the dialog box.

lpDialogFunc

Points to the dialog box procedure. For more information about the dialog box procedure, see DialogProc.

Return Value

If the function succeeds, the return value is the handle of the dialog box.

If the function fails, the return value is NULL.

Remarks

The CreateDialog function uses the CreateWindowEx function to create the dialog box. CreateDialog then sends a WM_INITDIALOG message (and a WM_SETFONT message if the template specifies the DS_SETFONT style) to the dialog box procedure. The function displays the dialog box if the template specifies the WS_VISIBLE style. Finally, CreateDialog returns the window handle of the dialog box.

After CreateDialog returns, the application displays the dialog box (if it is not already displayed) by using the ShowWindow function. The application destroys the dialog box by using the DestroyWindow function.

Windows 95 only: The system can support a maximum of 16,364 window handles.

See Also

CreateDialogIndirect, CreateDialogIndirectParam, CreateDialogParam, CreateWindowEx, DestroyWindow, DialogBox, DialogProc, ShowWindow, WM_INITDIALOG, WM_SETFONT


CreateDialogIndirect
 CreateDialogIndirect  QuickInfo  Overview  Group

The CreateDialogIndirect function creates a modeless dialog box from a dialog box template in memory.

HWND CreateDialogIndirect(

HINSTANCE  hInstance,	// handle of application instance
LPCDLGTEMPLATE  lpName,	// address of dialog box template
HWND  hWndParent,	// handle of owner window
DLGPROC  lpDialogFunc	// address of dialog box procedure
);
Parameters

hInstance

Identifies the instance of the module that creates the dialog box.

lpName

Points to a global memory object that contains a dialog box template used to create the dialog box. This template is in the form of a DLGTEMPLATE structure followed by one or more DLGITEMTEMPLATE structures.

hWndParent

Identifies the window that owns the dialog box.

lpDialogFunc

Points to the dialog box procedure. For more information about the dialog box procedure, see DialogProc.

Return Value

If the function succeeds, the return value is the window handle of the dialog box.

If the function fails, the return value is NULL.

Remarks

The CreateDialogIndirect function uses the CreateWindowEx function to create the dialog box. CreateDialogIndirect then sends a WM_INITDIALOG message (and a WM_SETFONT message if the template specifies the DS_SETFONT style) to the dialog box procedure. The function displays the dialog box if the template specifies the WS_VISIBLE style. Finally, CreateDialogIndirect returns the window handle of the dialog box.

After CreateDialogIndirect returns, the application displays the dialog box (if it is not already displayed) by using the ShowWindow function. The application destroys the dialog box by using the DestroyWindow function.

Windows 95 only: The system can support a maximum of 16,364 window handles.

See Also

CreateDialog, CreateDialogIndirectParam, CreateDialogParam, CreateWindowEx, DestroyWindow, DialogProc, DLGITEMTEMPLATE, DLGTEMPLATE, ShowWindow, WM_INITDIALOG, WM_SETFONT


CreateDialogIndirectParam
 CreateDialogIndirectParam  QuickInfo  Overview  Group

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 of application instance
LPCDLGTEMPLATE  lpTemplate,	// address of dialog box template
HWND  hWndParent,	// handle of owner window
DLGPROC  lpDialogFunc,	// address of dialog box procedure
LPARAM  lParamInit	// initialization value
);
Parameters

hInstance

Identifies the instance of the module that will create the dialog box.

lpTemplate

Points to a global memory object that contains a dialog box template used to create the dialog box. This template is in the form of a DLGTEMPLATE structure followed by one or more DLGITEMTEMPLATE structures.

hWndParent

Identifies the window that owns the dialog box.

lpDialogFunc

Points to the dialog box procedure. For more information about the dialog box procedure, see DialogProc.

lParamInit

Specifies the value to pass to the dialog box in the lParam parameter of the WM_INITDIALOG message.

Return Value

If the function succeeds, the return value is the window handle of the dialog box.

If the function fails, the return value is NULL.

Remarks

The CreateDialogIndirectParam function uses the CreateWindowEx function to create the dialog box. CreateDialogIndirectParam then sends a WM_INITDIALOG message (and a WM_SETFONT message if the template specifies the DS_SETFONT style) to the dialog box procedure. The function displays the dialog box if the template specifies the WS_VISIBLE style. Finally, CreateDialogIndirectParam returns the window handle of the dialog box.

After CreateDialogIndirectParam returns, the application displays the dialog box (if it is not already displayed) by using the ShowWindow function. The application destroys the dialog box by using the DestroyWindow function.

Windows 95 only: The system can support a maximum of 16,364 window handles.

See Also

CreateDialog, CreateDialogIndirect, CreateDialogParam, CreateWindowEx, DestroyWindow, DLGITEMTEMPLATE, DLGTEMPLATE, DialogProc, ShowWindow, WM_INITDIALOG, WM_SETFONT


CreateDialogParam
 CreateDialogParam  QuickInfo  Overview  Group

The CreateDialogParam function creates a modeless dialog box from a dialog box template resource. Before displaying the dialog box, the function passes an application-defined value to the dialog box procedure as the lParam parameter of the the WM_INITDIALOG message. An application can use this value to initialize dialog box controls.

HWND CreateDialogParam(

HINSTANCE  hInstance,	// handle of application instance
LPCTSTR  lpTemplateName,	// identifies dialog box template
HWND  hWndParent,	// handle of owner window
DLGPROC  lpDialogFunc,	// address of dialog box procedure
LPARAM  dwInitParam	// initialization value
);
Parameters

hInstance

Identifies an instance of the module whose executable file contains the dialog box template.

lpTemplateName

Identifies the dialog box template. This parameter is either the address of a null-terminated character string that specifies the name of the dialog box template or an integer value that specifies the resource identifier of the dialog box template. If the parameter specifies a resource identifier, its high-order word must be zero and low-order word must contain the identifier. You can use the MAKEINTRESOURCE macro to create this value.

hWndParent

Identifies the window that owns the dialog box.

lpDialogFunc

Points to the dialog box procedure. For more information about the dialog box procedure, see DialogProc .

dwInitParam

Specifies the value to pass to the dialog box procedure in the lParam parameter in the WM_INITDIALOG message.

Return Value

If the function succeeds, the return value is the window handle of the dialog box.

If the function fails, the return value is NULL.

Remarks

The CreateDialogParam function uses the CreateWindowEx function to create the dialog box. CreateDialogParam then sends a WM_INITDIALOG message (and a WM_SETFONT message if the template specifies the DS_SETFONT style) to the dialog box procedure. The function displays the dialog box if the template specifies the WS_VISIBLE style. Finally, CreateDialogParam returns the window handle of the dialog box.

After CreateDialogParam returns, the application displays the dialog box (if it is not already displayed) by using the ShowWindow function. The application destroys the dialog box by using the DestroyWindow function.

Windows 95 only: The system can support a maximum of 16,364 window handles.

See Also

CreateDialog, CreateDialogIndirect, CreateDialogIndirectParam, CreateWindowEx, DestroyWindow, DialogProc, MAKEINTRESOURCE, ShowWindow, WM_INITDIALOG, WM_SETFONT


CreateDIBitmap
 CreateDIBitmap  QuickInfo  Overview  Group

The CreateDIBitmap function creates a device-dependent bitmap (DDB) from a device-independent bitmap (DIB) and, optionally, sets the bitmap bits.

HBITMAP CreateDIBitmap(

HDC  hdc,	// handle of device context
CONST BITMAPINFOHEADER *  lpbmih,	// address of bitmap size and format data
DWORD  fdwInit,	// initialization flag
CONST VOID  *lpbInit,	// address of initialization data
CONST BITMAPINFO *  lpbmi,	// address of bitmap color-format data
UINT  fuUsage	// color-data usage
);
Parameters

hdc

Identifies a device context.

lpbmih

Points to a BITMAPINFOHEADER structure.

If fdwInit is CBM_INIT, the function uses the BITMAPINFOHEADER structure to obtain the desired width and height of the bitmap as well as other information. Note that a positive value for the height indicates a bottom-up DIB while a negative value for the height indicates a top-down DIB. This scenario is compatible with the CreateDIBitmap function.

fdwInit

A set of bit flags that specify how the operating system initializes the bitmap's bits.

The following bit flag constant is defined:

Value	Meaning
CBM_INIT	If this flag is set, the operating system uses the data pointed to by the lpbInit and lpbmi parameters to initialize the bitmap's bits. If this flag is clear, the data pointed to by those parameters is not used.
If fdwInit is zero, the operating system does not initialize the bitmap's bits.

lpbInit

Points to an array of bytes containing the initial bitmap data. The format of the data depends on the biBitCount member of the BITMAPINFO structure to which the lpbmi parameter points.

lpbmi

Points to a BITMAPINFO structure that describes the dimensions and color format of the array pointed to by the lpbInit parameter.

fuUsage

Specifies whether the bmiColors member of the BITMAPINFO structure was initialized and, if so, whether bmiColors contains explicit red, green, blue (RGB) values or palette indices. The fuUsage parameter must be one of the following values:

Value	Meaning
DIB_PAL_COLORS	A color table is provided and consists of an array of 16-bit indices into the logical palette of the device context into which the bitmap is to be selected.
DIB_RGB_COLORS	A color table is provided and contains literal RGB values.
Return Value

If the function succeeds, the return value is a handle of the bitmap.

If the function fails, the return value is NULL.

Remarks

The CBM_CREATDIB flag for the fdwInit parameter is no longer supported.

When you no longer need the bitmap, call the DeleteObject function to delete it.

See Also

BITMAPINFOHEADER, BITMAPINFO, DeleteObject, GetDeviceCaps, GetSystemPaletteEntries, SelectObject


CreateDIBPatternBrush
 CreateDIBPatternBrush  QuickInfo  Overview  Group

The CreateDIBPatternBrush function creates a logical brush that has the pattern specified by the specified device-independent bitmap (DIB). The brush can subsequently be selected into any device context that is associated with a device that supports raster operations.

This function is provided only for compatibility with applications written for versions of Windows earlier than 3.0. For Win32-based applications, use the CreateDIBPatternBrushPt function.

HBRUSH CreateDIBPatternBrush(

HGLOBAL  hglbDIBPacked,	// handle of device-independent bitmap
UINT  fuColorSpec	// color table data
);
Parameters

hglbDIBPacked

Identifies a global memory object containing a packed DIB, which consists of a BITMAPINFO structure immediately followed by an array of bytes defining the pixels of the bitmap.

fuColorSpec

Specifies whether the bmiColors member of the BITMAPINFO structure is initialized and, if so, whether this member contains explicit red, green, blue (RGB) values or indices into a logical palette. The fuColorSpec parameter must be one of the following values:

Value	Meaning
DIB_PAL_COLORS	A color table is provided and consists of an array of 16-bit indices into the logical palette of the device context into which the brush is to be selected.
DIB_RGB_COLORS	A color table is provided and contains literal RGB values.
Return Value

If the function succeeds, the return value identifies a logical brush.

If the function fails, the return value is NULL.

Remarks

When an application selects a two-color DIB pattern brush into a monochrome device context, Windows does not acknowledge the colors specified in the DIB; instead, it displays the pattern brush using the current background and foreground colors of the device context. Pixels mapped to the first color of the DIB (offset 0 in the DIB color table) are displayed using the foreground color; pixels mapped to the second color (offset 1 in the color table) are displayed using the background color.

When you no longer need the brush, call the DeleteObject function to delete it.

Windows 95: Creating brushes from bitmaps or DIBs larger than 8x8 pixels is not supported. If a larger bitmap is given, only a portion of the bitmap is used.

See Also

BITMAPINFO, CreateDIBPatternBrushPt, CreateHatchBrush, CreatePatternBrush, CreateSolidBrush, DeleteObject, SetBkColor, SetTextColor


CreateDIBPatternBrushPt
 CreateDIBPatternBrushPt  QuickInfo  Overview  Group

The CreateDIBPatternBrushPt function creates a logical brush that has the pattern specified by the device-independent bitmap (DIB).

HBRUSH CreateDIBPatternBrushPt(

CONST VOID *  lpPackedDIB,	// address of structure and bitmap bits
UINT  iUsage	// usage flags
);
Parameters

lpPackedDIB

Points to a packed DIB consisting of a BITMAPINFO structure immediately followed by an array of bytes defining the pixels of the bitmap.

iUsage

Specifies whether the bmiColors member of the BITMAPINFO structure contains a valid color table and, if so, whether the entries in this color table contain explicit red, green, blue (RGB) values or palette indices. The iUsage parameter must be one of the following values:

Value	Meaning
DIB_PAL_COLORS	A color table is provided and consists of an array of 16-bit indices into the logical palette of the device context into which the brush is to be selected.
DIB_RGB_COLORS	A color table is provided and contains literal RGB values.
Return Value

If the function succeeds, the return value identifies a logical brush.

If the function fails, the return value is NULL.

Remarks

A brush is a bitmap that Windows uses to paint the interiors of filled shapes.

After an application creates a brush by calling CreateDIBPatternBrushPt, it can select that brush into any device context by calling the SelectObject function.

When you no longer need the brush, call the DeleteObject function to delete it.

Windows 95: Creating brushes from bitmaps or DIBs larger than 8x8 pixels is not supported. If a larger bitmap is given, only a portion of the bitmap is used.

See Also

BITMAPINFO, CreateDIBPatternBrush, CreateHatchBrush, CreatePatternBrush, CreateSolidBrush, DeleteObject, GetBrushOrgEx, SelectObject, SetBrushOrgEx


CreateDIBSection
 CreateDIBSection  QuickInfo  Overview  Group

The CreateDIBSection function creates a device-independent bitmap (DIB) that applications can write to directly. The function gives you a pointer to the location of the bitmap's bit values. You can supply a handle to a file mapping object that the function will use to create the bitmap, or you can let the operating system allocate the memory for the bitmap.

HBITMAP CreateDIBSection(

HDC hdc,	// handle of device context
CONST BITMAPINFO *pbmi,	// address of structure containing bitmap size, format, and color data
UINT iUsage,	// color data type indicator: RGB values or palette indices
VOID **ppvBits,	// pointer to variable to receive a pointer to the bitmap's bit values
HANDLE hSection,	// optional handle to a file mapping object
DWORD dwOffset	// offset to the bitmap bit values within the file mapping object
);
Parameters

hdc

Handle to a device context. If the value of iUsage is DIB_PAL_COLORS, the function uses this device context's logical palette to initialize the device-independent bitmap's colors.

pbmi

Points to a BITMAPINFO structure that specifies various attributes of the device-independent bitmap, including the bitmap's dimensions and colors.

iUsage

Specifies the type of data contained in the bmiColors array member of the BITMAPINFO structure pointed to by pbmi: logical palette indices or literal RGB values. The following values are defined:

Value	Meaning
DIB_PAL_COLORS	The bmiColors member is an array of 16-bit indices into the logical palette of the device context specified by hdc.
DIB_RGB_COLORS	The BITMAPINFO structure contains an array of literal RGB values.
ppvBits

Points to a variable that receives a pointer to the location of the device-independent bitmap's bit values.

hSection

Handle to a file mapping object that the function will use to create the device-independent bitmap. This parameter can be NULL.

If hSection is not NULL, it must be a handle to a file mapping object created by calling the CreateFileMapping function. Handles created by other means will cause CreateDIBSection to fail.

If hSection is not NULL, the CreateDIBSection function locates the bitmap's bit values at offset dwOffset in the file mapping object referred to by hSection. An application can later retrieve the hSection handle by calling the GetObject function with the HBITMAP returned by CreateDIBSection.

If hSection is NULL, the operating system allocates memory for the device-independent bitmap. In this case, the CreateDIBSection function ignores the dwOffset parameter. An application cannot later obtain a handle to this memory: the dshSection member of the DIBSECTION structure filled in by calling the GetObject function will be NULL.

dwOffset

Specifies the offset from the beginning of the file mapping object referenced by hSection where storage for the bitmap's bit values is to begin. This value is ignored if hSection is NULL. The bitmap's bit values are aligned on doubleword boundaries, so dwOffset must be a multiple of the size of a DWORD.

Return Value

If the function succeeds, the return value is a handle to the newly created device-independent bitmap, and *ppvBits points to the bitmap's bit values.

If the function fails, the return value is NULL, and *ppvBits is NULL. To get extended error information, call GetLastError.

Remarks

As noted above, if hSection is NULL, the operating system allocates memory for the device-independent bitmap. The operating system closes the handle to that memory when you later delete the device-independent bitmap by calling the DeleteObject function. If hSection is not NULL, you must close the hSection memory handle yourself after calling DeleteObject to delete the bitmap.

Windows NT: You need to guarantee that the GDI subsystem has completed any drawing to a bitmap created by CreateDIBSection before you draw to the bitmap yourself. Access to the bitmap must be synchronized. Do this by calling the GdiFlush function. This applies to any use of the pointer to the bitmap's bit values, including passing the pointer in calls to functions such as SetDIBits.

See Also

BITMAPINFO, CreateFileMapping, DeleteObject, DIBSECTION, GetDIBColorTable, GetObject, GdiFlush, HBITMAP, SetDIBits SetDIBColorTable


CreateDirectory
 CreateDirectory  QuickInfo  Overview  Group

The CreateDirectory function creates a new directory. If the underlying file system supports security on files and directories, the function applies a specified security descriptor to the new directory. Note that CreateDirectory does not have a template parameter, while CreateDirectoryEx does.

BOOL CreateDirectory(

LPCTSTR  lpPathName,	// pointer to a directory path string
LPSECURITY_ATTRIBUTES  lpSecurityAttributes	// pointer to a security descriptor
);
Parameters

lpPathName

Points to a null-terminated string that specifies the path of the directory to be created.

There is a default string size limit for paths of MAX_PATH characters. This limit is related to how the CreateDirectory function parses paths.

Windows NT: An application can transcend this limit and send in paths longer than MAX_PATH characters by calling the wide (W) version of CreateDirectory and prepending "\\?\" to the path. The "\\?\" tells the function to turn off path parsing; it lets paths longer than MAX_PATH be used with CreateDirectoryW. This also works with UNC names. The "\\?\" is ignored as part of the path. For example, "\\?\C:\myworld\private" is seen as "C:\myworld\private", and "\\?\UNC\bill_g_1\hotstuff\coolapps" is seen as "\\bill_g_1\hotstuff\coolapps".

lpSecurityAttributes

Points to a SECURITY_ATTRIBUTES structure that specifies the security attributes for the directory to be created. The file system must support this parameter for it to have an effect.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

Windows NT

Some file systems, such as NTFS, support compression for individual files and directories. On volumes formatted for such a file system, a new directory inherits the compression attribute of its parent directory.

An application can obtain a handle to a directory by calling CreateFile with the FILE_FLAG_BACKUP_SEMANTICS flag set. For a code example, see CreateFile.

See Also

CreateDirectoryEx, CreateFile, RemoveDirectory, SECURITY_ATTRIBUTES


CreateDirectoryEx
 CreateDirectoryEx  QuickInfo  Overview  Group

The CreateDirectoryEx function creates a new directory with a specified path that retains the attributes of a specified template directory. If the underlying file system supports security on files and directories, the function applies a specified security descriptor to the new directory. The new directory retains the other attributes of the specified template directory. Note that CreateDirectoryEx has a template parameter, while CreateDirectory does not.

BOOL CreateDirectoryEx(

LPCTSTR  lpTemplateDirectory,	// pointer to path string of template directory
LPCTSTR  lpNewDirectory,	// pointer to path string of directory to create
LPSECURITY_ATTRIBUTES  lpSecurityAttributes	// pointer to security descriptor
);
Parameters

lpTemplateDirectory

Points to a null-terminated string that specifies the path of the directory to use as a template when creating the new directory.

lpNewDirectory

Points to a null-terminated string that specifies the path of the directory to be created.

lpSecurityAttributes

Points to a SECURITY_ATTRIBUTES structure that supplies a security descriptor for the new directory. This parameter is optional. The target file system must support security on files and directories for this parameter to have an effect.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The CreateDirectoryEx function allows you to create directories that inherit stream information from other directories. This function is useful, for example, when dealing with Macintosh directories, which have a resource stream that is needed to properly identify directory contents as an attribute.

Windows NT

Some file systems, such as NTFS, support compression for individual files and directories. On volumes formatted for such a file system, a new directory inherits the compression attribute of its parent directory.

You can obtain a handle to a directory by calling CreateFile with the FILE_FLAG_BACKUP_SEMANTICS flag set. See CreateFile for a code example.

See Also

CreateDirectory, CreateFile, RemoveDirectory, SECURITY_ATTRIBUTES


CreateDiscardableBitmap
 CreateDiscardableBitmap  QuickInfo  Overview  Group

The CreateDiscardableBitmap function creates a discardable bitmap that is compatible with the specified device. The bitmap has the same bits-per-pixel format and the same color palette as the device. An application can select this bitmap as the current bitmap for a memory device that is compatible with the specified device.

The CreateDiscardableBitmap function is included only for compatibility with earlier versions of Windows. For Win32-based applications, use the CreateCompatibleBitmap function.

HBITMAP CreateDiscardableBitmap(

HDC  hdc,	// handle of device context
int  nWidth,	// bitmap width
int  nHeight	// bitmap height
);
Parameters

hdc

Identifies a device context.

nWidth

Specifies the width, in bits, of the bitmap.

nHeight

Specifies the height, in bits, of the bitmap.

Return Value

If the function succeeds, the return value is a handle of the bitmap.

If the function fails, the return value is NULL.

Remarks

When you no longer need the bitmap, call the DeleteObject function to delete it.

See Also

CreateCompatibleBitmap, DeleteObject


CreateEllipticRgn
 CreateEllipticRgn  QuickInfo  Overview  Group

The CreateEllipticRgn function creates an elliptical region.

HRGN CreateEllipticRgn(

int  nLeftRect,	// x-coordinate of the upper-left corner of the bounding rectangle
int  nTopRect,	// y-coordinate of the upper-left corner of the bounding rectangle
int  nRightRect,	// x-coordinate of the lower-right corner of the bounding rectangle
int  nBottomRect	// y-coordinate of the lower-right corner of the bounding rectangle
);
Parameters

nLeftRect

Specifies the x-coordinate of the upper-left corner of the bounding rectangle of the ellipse.

nTopRect

Specifies the y-coordinate of the upper-left corner of the bounding rectangle of the ellipse.

nRightRect

Specifies the x-coordinate of the lower-right corner of the bounding rectangle of the ellipse.

nBottomRect

Specifies the y-coordinate of the lower-right corner of the bounding rectangle of the ellipse.

Return Value

If the function succeeds, the return value is the handle of the region.

If the function fails, the return value is NULL.

Remarks

A bounding rectangle defines the size, shape, and orientation of the region: The long sides of the rectangle define the length of the ellipse's major axis; the short sides define the length of the ellipse's minor axis; and the center of the rectangle defines the intersection of the major and minor axes.

The coordinates of the bounding rectangle are specified in logical units.

See Also

CreateEllipticRgnIndirect, DeleteObject, SelectObject


CreateEllipticRgnIndirect
 CreateEllipticRgnIndirect  QuickInfo  Overview  Group

The CreateEllipticRgnIndirect function creates an elliptical region.

HRGN CreateEllipticRgnIndirect(

CONST RECT  *lprc	// address of structure defining bounding rectangle
);
Parameters

lprc

Points to a RECT structure that contains the coordinates of the upper-left and lower-right corners of the bounding rectangle of the ellipse.

Return Value

If the function succeeds, the return value is the handle of the region.

If the function fails, the return value is NULL.

Remarks

A bounding rectangle defines the size, shape, and orientation of the region: The long sides of the rectangle define the length of the ellipse's major axis; the short sides define the length of the ellipse's minor axis; and the center of the rectangle defines the intersection of the major and minor axes.

The coordinates of the bounding rectangle are specified in logical units.

See Also

CreateEllipticRgn, DeleteObject, RECT, SelectObject


CreateEnhMetaFile
 CreateEnhMetaFile  QuickInfo  Overview  Group

The CreateEnhMetaFile function creates a device context for an enhanced-format metafile. This device context can be used to store a device-independent picture.

HDC CreateEnhMetaFile(

HDC  hdcRef,	// handle of a reference device context
LPCTSTR  lpFilename,	// address of a filename string
CONST RECT *  lpRect,	// address of a bounding rectangle
LPCTSTR  lpDescription	// address of an optional description string
);
Parameters

hdcRef

Identifies a reference device for the enhanced metafile.

lpFilename

Points to the filename for the enhanced metafile to be created. If this parameter is NULL, the enhanced metafile is memory based and its contents are lost when it is deleted by using the DeleteEnhMetaFile function.

lpRect

Points to a RECT structure that specifies the dimensions (in .01-millimeter units) of the picture to be stored in the enhanced metafile.

lpDescription

Points to a string that specifies the name of the application that created the picture, as well as the picture's title.

Return Value

If the function succeeds, the return value is a handle of the device context for the enhanced metafile.

If the function fails, the return value is NULL.

Remarks

Where text arguments must use Unicode characters, use this function as a wide-character function. Where text arguments must use characters from the Windows 3.x character set, use this function as an ANSI function.

Windows uses the reference device identified by the hdcRef parameter to record the resolution and units of the device on which a picture originally appeared. If the hdcRef parameter is NULL, it uses the current display device for reference.

The left and top members of the RECT structure pointed to by the lpRect parameter must be less than the right and bottom members, respectively. Points along the edges of the rectangle are included in the picture. If lpRect is NULL, the graphics device interface (GDI) computes the dimensions of the smallest rectangle that surrounds the picture drawn by the application. The lpRect parameter should be provided where possible.

The string pointed to by the lpDescription parameter must contain a null character between the application name and the picture name and must terminate with two null characters — for example, "XYZ Graphics Editor\0Bald Eagle\0\0", where \0 represents the null character. If lpDescription is NULL, there is no corresponding entry in the enhanced-metafile header.

Applications use the device context created by this function to store a graphics picture in an enhanced metafile. The handle identifying this device context can be passed to any GDI function.

After an application stores a picture in an enhanced metafile, it can display the picture on any output device by calling the PlayEnhMetaFile function. When displaying the picture, Windows uses the rectangle pointed to by the lpRect parameter and the resolution data from the reference device to position and scale the picture.

The device context returned by this function contains the same default attributes associated with any new device context.

Applications must use the GetWinMetaFileBits function to convert an enhanced metafile to the older Windows metafile format.

The filename for the enhanced metafile should use the .EMF extension.

See Also

CloseEnhMetaFile, DeleteEnhMetaFile, GetEnhMetaFileDescription, GetEnhMetaFileHeader, GetWinMetaFileBits, PlayEnhMetaFile, RECT


CreateEvent
 CreateEvent  QuickInfo  Overview  Group

The CreateEvent function creates a named or unnamed event object.

HANDLE CreateEvent(

LPSECURITY_ATTRIBUTES  lpEventAttributes,	// address of security attributes
BOOL  bManualReset,	// flag for manual-reset event
BOOL  bInitialState,	// flag for initial state
LPCTSTR  lpName	// address of event-object name
);
Parameters

lpEventAttributes

Points to a SECURITY_ATTRIBUTES structure that specifies the security attributes for the event object.

If lpEventAttributes is NULL, the event object is created with a default security descriptor and the resulting handle is not inheritable.

bManualReset

Specifies whether a manual-reset or auto-reset event object is created. If TRUE, then you must use the ResetEvent function to manually reset the state to nonsignaled. If FALSE, Windows automatically resets the state to nonsignaled after a single waiting thread has been released.

bInitialState

Specifies the initial state of the event object. If TRUE, the initial state is signaled; otherwise, it is nonsignaled.

lpName

Points to a null-terminated string specifying the name of the event object. The name is limited to MAX_PATH characters and can contain any character except the backslash path-separator character (\). Name comparison is case sensitive.

If lpName matches the name of an existing named event object, this function requests EVENT_ALL_ACCESS access to the existing object. In this case, the bManualReset and bInitialState parameters are ignored because they have already been set by the creating process. If the lpEventAttributes parameter is not NULL, it determines whether the handle can be inherited, but its security-descriptor member is ignored.

If lpName is NULL, the event object is created without a name.

If lpName matches the name of an existing semaphore, mutex, or file-mapping object, the function fails and the GetLastError function returns ERROR_INVALID_HANDLE. This occurs because event, mutex, semaphore, and file-mapping objects share the same name space.

Return Value

If the function succeeds, the return value is a handle of the event object. If the named event object existed before the function call, the GetLastError function returns ERROR_ALREADY_EXISTS. Otherwise, GetLastError returns zero.

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

Remarks

The handle returned by CreateEvent has EVENT_ALL_ACCESS access to the new event object and can be used in any function that requires a handle of an event object.

Any thread of the calling process can specify the event-object handle in a call to one of the wait functions (MsgWaitForMultipleObjects, WaitForSingleObject, WaitForMultipleObjects, WaitForSingleObjectEx, or WaitForMultipleObjectsEx). The single-object wait functions return when the state of the specified object is signaled. The multiple-object wait functions can be instructed to return either when any one or when all of the specified objects are signaled. When a wait function returns, the waiting thread is released to continue its execution.

The initial state of the event object is specified by the bInitialState parameter. Use the SetEvent function to set the state of an event object to signaled. Use the ResetEvent function to reset the state of an event object to nonsignaled.

When the state of a manual-reset event object is signaled, it remains signaled until it is explicitly reset to nonsignaled by the ResetEvent function. Any number of waiting threads, or threads that subsequently begin wait operations for the specified event object, can be released while the object's state is signaled.

When the state of an auto-reset event object is signaled, it remains signaled until a single waiting thread is released; the system then automatically resets the state to nonsignaled. If no threads are waiting, the event object's state remains signaled.

Multiple processes can have handles of the same event object, enabling use of the object for interprocess synchronization. The following object-sharing mechanisms are available:

•	A child process created by the CreateProcess function can inherit a handle of an event object if the lpEventAttributes parameter of CreateEvent enabled inheritance.

•	A process can specify the event-object handle in a call to the DuplicateHandle function to create a duplicate handle that can be used by another process.

•	A process can specify the name of an event object in a call to the OpenEvent or CreateEvent function.

Use the CloseHandle function to close the handle. The system closes the handle automatically when the process terminates. The event object is destroyed when its last handle has been closed.

See Also

CloseHandle, CreateProcess, DuplicateHandle, MsgWaitForMultipleObjects, OpenEvent, ResetEvent, SECURITY_ATTRIBUTES, SetEvent, WaitForMultipleObjects, WaitForMultipleObjectsEx, WaitForSingleObject, WaitForSingleObjectEx


CreateFile
 CreateFile  QuickInfo  Overview  Group

The CreateFile function creates, opens, or truncates a file, pipe, communications resource, disk device, or console. It returns a handle that can be used to access the object. It can also open and return a handle to a directory.

HANDLE CreateFile(

LPCTSTR  lpFileName,	// address of name of the file
DWORD  dwDesiredAccess,	// access (read-write) mode
DWORD  dwShareMode,	// share mode
LPSECURITY_ATTRIBUTES  lpSecurityAttributes,	// address of security descriptor
DWORD  dwCreationDistribution,	// how to create
DWORD  dwFlagsAndAttributes,	// file attributes
HANDLE  hTemplateFile	// handle of file with attributes to copy
);
Parameters

lpFileName

Points to a null-terminated string that specifies the name of the file, pipe, communications resource, disk device, or console to create, open, or truncate.

If *lpFileName is a path, there is a default string size limit of MAX_PATH characters. This limit is related to how the CreateFile function parses paths.

Windows NT: You can transcend this limit and send in paths longer than MAX_PATH characters by calling the wide (W) version of CreateFile and prepending "\\?\" to the path. The "\\?\" tells the function to turn off path parsing. This lets you use paths that are nearly 32k Unicode characters long. You must use fully-qualified paths with this technique. This also works with UNC names. The "\\?\" is ignored as part of the path. For example, "\\?\C:\myworld\private" is seen as "C:\myworld\private", and "\\?\UNC\tom_1\hotstuff\coolapps" is seen as "\\tom_1\hotstuff\coolapps".

dwDesiredAccess

Specifies the type of access to the file or other object. An application can obtain read access, write access, read-write access, or device query access. You can use the following flag constants to build a value for this parameter. Both GENERIC_READ and GENERIC_WRITE must be set to obtain read-write access:

Value	Meaning
0	Allows an application to query device attributes without actually accessing the device.
GENERIC_READ	Specifies read access to the file. Data can be read from the file and the file pointer can be moved.
GENERIC_WRITE	Specifies write access to the file. Data can be written to the file and the file pointer can be moved.
dwShareMode

Specifies how this file can be shared. This parameter must be some combination of the following values:

Value	Meaning
0	Prevents the file from being shared.
FILE_SHARE_READ	Other open operations can be performed on the file for read access. If the CreateFile function is opening the client end of a mailslot, this flag is specified.
FILE_SHARE_WRITE	Other open operations can be performed on the file for write access.
lpSecurityAttributes

Points to a SECURITY_ATTRIBUTES structure that specifies the security attributes for the file. The file system must support this parameter for it to have an effect.

dwCreationDistribution

Specifies which action to take on files that exist, and which action to take when files do not exist. For more information about this parameter, see the following Remarks section. This parameter must be one of the following values:

Value	Meaning
CREATE_NEW	Creates a new file. The function fails if the specified file already exists.
CREATE_ALWAYS	Creates a new file. The function overwrites the file if it exists.
OPEN_EXISTING	Opens the file. The function fails if the file does not exist.
	See the "Remarks" section, following, for a discussion of why you should use the OPEN_EXISTING flag if you are using the CreateFile function for a device, including the console.
OPEN_ALWAYS	Opens the file, if it exists. If the file does not exist, the function creates the file as if dwCreationDistribution were CREATE_NEW.
TRUNCATE_EXISTING	Opens the file. Once opened, the file is truncated so that its size is zero bytes. The calling process must open the file with at least GENERIC_WRITE access. The function fails if the file does not exist.
dwFlagsAndAttributes

Specifies the file attributes and flags for the file.

Any combination of the following attributes is acceptable, except all other file attributes override FILE_ATTRIBUTE_NORMAL.

Attribute	Meaning
FILE_ATTRIBUTE_ARCHIVE	The file is an archive file. Applications use this attribute to mark files for backup or removal.
FILE_ATTRIBUTE_COMPRESSED	The file or directory is compressed. For a file, this means that all of the data in the file is compressed. For a directory, this means that compression is the default for newly created files and subdirectories.
FILE_ATTRIBUTE_NORMAL	The file has no other attributes set. This attribute is valid only if used alone.
FILE_ATTRIBUTE_HIDDEN	The file is hidden. It is not to be included in an ordinary directory listing.
FILE_ATTRIBUTE_READONLY	The file is read only. Applications can read the file but cannot write to it or delete it.
FILE_ATTRIBUTE_SYSTEM	The file is part of or is used exclusively by the operating system.
Any combination of the following flags is acceptable.

Flag	Meaning
FILE_FLAG_WRITE_THROUGH
	Instructs the operating system to write through any intermediate cache and go directly to the file. The operating system can still cache write operations, but cannot lazily flush them.
FILE_FLAG_OVERLAPPED
	Instructs the operating system to initialize the file, so ReadFile, WriteFile, ConnectNamedPipe, and TransactNamedPipe operations that take a significant amount of time to process return ERROR_IO_PENDING. When the operation is finished, an event is set to the signaled state.
	When you specify FILE_FLAG_OVERLAPPED, the ReadFile and WriteFile functions must specify an OVERLAPPED structure. That is, when FILE_FLAG_OVERLAPPED is specified, an application must perform overlapped reading and writing.
	When FILE_FLAG_OVERLAPPED is specified, the operating system does not maintain the file pointer. The file position must be passed as part of the lpOverlapped parameter (pointing to an OVERLAPPED structure) to the ReadFile and WriteFile functions.
	This flag also enables more than one operation to be performed simultaneously with the handle (a simultaneous read and write operation, for example).
FILE_FLAG_NO_BUFFERING
	Instructs the operating system to open the file with no intermediate buffering or caching. This can provide performance gains in some situations.  An application must meet certain requirements when working with files opened with FILE_FLAG_NO_BUFFERING: • File access must begin at offsets within the file that are integer multiples of the volume's sector size.  • File access must be for numbers of bytes that are integer multiples of the volume's sector size. For example, if the sector size is 512 bytes, an application can request reads and writes of 512, 1024, or 2048 bytes, but not of 335, 981, or 7171 bytes.  • Buffer addresses for read and write operations must be aligned on addresses in memory that are integer multiples of the volume's sector size.  An application can determine a volume's sector size by calling the GetDiskFreeSpace function.
FILE_FLAG_RANDOM_ACCESS
	Indicates that the file is accessed randomly. Windows uses this flag to optimize file caching.
FILE_FLAG_SEQUENTIAL_SCAN
	Indicates that the file is to be accessed sequentially from beginning to end. Windows uses this flag to optimize file caching. If an application moves the file pointer for random access, optimum caching may not occur; however, correct operation is still guaranteed.
	Specifying this flag can increase performance for applications that read large files using sequential access. Performance gains can be even more noticeable for applications that read large files mostly sequentially, but occasionally skip over small ranges of bytes.
FILE_FLAG_DELETE_ON_CLOSE
	Indicates that the operating system is to delete the file immediately after all of its handles have been closed. If you use this flag when you call CreateFile, then open the file again, and then close the handle for which you specified FILE_FLAG_DELETE_ON_CLOSE, the file will not be deleted until after you have closed the second and any other handle to the file.
FILE_FLAG_BACKUP_SEMANTICS
	Windows NT only: Indicates that the file is being opened or created for a backup or restore operation. The operating system ensures that the calling process overrides file security checks, provided it has the necessary permission to do so. The relevant permissions are SE_BACKUP_NAME and SE_RESTORE_NAME. A Windows NT application can also set this flag to obtain a handle to a directory. A directory handle can be passed to some Win32 functions in place of a file handle.
FILE_FLAG_POSIX_SEMANTICS
	Indicates that the file is to be accessed according to POSIX rules. This includes allowing multiple files with names, differing only in case, for file systems that support such naming. Use care when using this option because files created with this flag may not be accessible by applications written for MS-DOS, Windows 3.x, or Windows NT.
If the CreateFile function opens the client side of a named pipe, the dwFlagsAndAttributes parameter can also contain Security Quality of Service information. When the calling application specifies the SECURITY_SQOS_PRESENT flag, the dwFlagsAndAttributes parameter can contain one or more of the following values:

Value	Meaning
SECURITY_ANONYMOUS	Specifies to impersonate the client at the Anonymous impersonation level.
SECURITY_IDENTIFICATION	Specifies to impersonate the client at the Identification impersonation level.
SECURITY_IMPERSONATION	Specifies to impersonate the client at the Impersonation impersonation level.
SECURITY_DELEGATION	Specifies to impersonate the client at the Delegation impersonation level.
SECURITY_CONTEXT_TRACKING	Specifies that the security tracking mode is dynamic. If this flag is not specified, Security Tracking Mode is static.
SECURITY_EFFECTIVE_ONLY	Specifies that only the enabled aspects of the client's security context are available to the server. If you do not specify this flag, all aspects of the client's security context are available. This flag allows the client to limit the groups and privileges that a server can use while impersonating the client.
For more information, see Security.

hTemplateFile

Specifies a handle with GENERIC_READ access to a template file. The template file supplies extended attributes for the file being created.

Return Value

If the function succeeds, the return value is an open handle of the specified file. If the specified file exists before the function call and dwCreationDistribution is CREATE_ALWAYS or OPEN_ALWAYS, a call to GetLastError returns ERROR_ALREADY_EXISTS (even though the function has succeeded). If the file does not exist before the call, GetLastError returns zero.

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

Remarks

When creating a new file, the CreateFile function performs the following actions:

•	Combines the file attributes and flags specified by dwFlagsAndAttributes with FILE_ATTRIBUTE_ARCHIVE.

•	Sets the file length to zero.

•	Copies the extended attributes supplied by the template file to the new file if the hTemplateFile parameter is specified.

When opening an existing file, CreateFile performs the following actions:

•	Combines the file flags specified by dwFlagsAndAttributes with existing file attributes. CreateFile ignores the file attributes specified by dwFlagsAndAttributes.

•	Sets the file length according to the value of dwCreationDistribution.

•	Ignores the hTemplateFile parameter.

•	Ignores the lpSecurityDescriptor member of the SECURITY_ATTRIBUTES structure if the lpSecurityAttributes parameter is not NULL. The other structure members are valid. The bInheritHandle member is the only way to indicate whether the file handle can be inherited.

If CreateFile opens the client end of a named pipe, the function uses any instance of the named pipe that is in the listening state. The opening process can duplicate the handle as many times as required but, once opened, the named pipe instance cannot be opened by another client. The access specified when a pipe is opened must be compatible with the access specified in the dwOpenMode parameter of the CreateNamedPipe function. For more information about pipes, see Pipes.

If CreateFile opens the client end of a mailslot, the function always returns a valid handle, even if the mailslot does not exist. In other words, there is no relationship between opening the client end and opening the server end of the mailslot. For more information about mailslots, see Mailslots.

CreateFile can create a handle to a communications resource, such as the serial port COM1. For communications resources, the dwCreationDistribution parameter must be OPEN_EXISTING, and the hTemplate parameter must be NULL. Read, write, or read-write access can be specified, and the handle can be opened for overlapped I/O. For more information about communications, see Communications.

CreateFile can create a handle to console input (CONIN$). If the process has an open handle to it as a result of inheritance or duplication, it can also create a handle to the active screen buffer (CONOUT$).

The calling process must be attached to an inherited console or one allocated by the AllocConsole function. For console handles, set the CreateFile parameters as follows:

Parameter	Value
lpFileName	Use the CONIN$ value to specify console input and the CONOUT$ value to specify console output.
	CONIN$ gets a handle of the console's input buffer, even if the SetStdHandle function redirected the standard input handle. To get the standard input handle, use the GetStdHandle function.
	CONOUT$ gets a handle of the active screen buffer, even if SetStdHandle redirected the standard output handle. To get the standard output handle, use GetStdHandle.
dwDesiredAccess	GENERIC_READ | GENERIC_WRITE is preferred, but either one can limit access.
dwShareMode	If the calling process inherited the console or if a child process should be able to access the console, this parameter must be FILE_SHARE_READ | FILE_SHARE_WRITE.
lpSecurityAttributes	If you want the console to be inherited, the bInheritHandle member of the SECURITY_ATTRIBUTES structure must be TRUE.
dwCreationDistribution	The user should specify OPEN_EXISTING when using CreateFile to open the console.
dwFlagsAndAttributes	Ignored.
hTemplateFile	Ignored.
The following list shows the effects of various settings of fwdAccess and lpFileName.

lpFileName	fwdAccess	Result
CON	GENERIC_READ	Opens console for input.
CON	GENERIC_WRITE	Opens console for output.
CON	GENERIC_READ\ GENERIC_WRITE	Windows 95: Causes CreateFile to fail; GetLastError returns ERROR_PATH_NOT_FOUND. Windows NT:  Causes CreateFile to fail; GetLastError returns ERROR_FILE_NOT_FOUND.
You can use the CreateFile function to open a disk drive or a partition on a disk drive. The function returns a handle to the disk device; that handle can be used with the DeviceIOControl function. The following requirements must be met in order for such a call to succeed:

•	The caller must have administrative privileges for the operation to succeed on a hard disk drive.

•	The lpFileName string should be of the form \\.\PHYSICALDRIVEx to open the hard disk x. Hard disk numbers start at zero. For example:

String	Meaning
\\.\PHYSICALDRIVE2	Obtains a handle to the third physical drive on the user's computer.
•	The lpFileName string should be \\.\x: to open a floppy drive x or a partition x on a hard disk. For example:

String	Meaning
\\.\A:	Obtains a handle to drive A on the user's computer.
\\.\C:	Obtains a handle to drive C on the user's computer.
Windows 95: This technique does not work for opening a logical drive. In Windows 95, specifying a string in this form causes CreateFile to return an error.

•	The dwCreationDistribution parameter must have the OPEN_EXISTING value.

•	When opening a floppy disk or a partition on a hard disk, you must set the FILE_SHARE_WRITE flag in the dwShareMode parameter.

The CloseHandle function is used to close a handle returned by CreateFile.

As noted above, specifying zero for dwDesiredAccess allows an application to query device attributes without actually accessing the device. This type of querying is useful, for example, if an application wants to determine the size of a floppy disk drive and the formats it supports without having a floppy in the drive.

As previously noted, if an application opens a file with FILE_FLAG_NO_BUFFERING set, buffer addresses for read and write operations must be aligned on memory addresses that are integer multiples of the volume's sector size. One way to do this is to use VirtualAlloc to allocate the buffer. The VirtualAlloc function allocates memory that is aligned on addresses that are integer multiples of the operating system's memory page size. Since both memory page and volume sector sizes are powers of 2, and memory pages are larger than volume sectors, this memory is also aligned on addresses that are integer multiples of a volume's sector size.

An application cannot create a directory with CreateFile; it must call CreateDirectory or CreateDirectoryEx to create a directory.

Windows NT:

You can obtain a handle to a directory by setting the FILE_FLAG_BACKUP_SEMANTICS flag. A directory handle can be passed to some Win32 functions in place of a file handle.

Some file systems, such as NTFS, support compression for individual files and directories. On volumes formatted for such a file system, a new directory inherits the compression attribute of its parent directory.

See Also

AllocConsole, CloseHandle, ConnectNamedPipe, CreateDirectory, CreateDirectoryEx, CreateNamedPipe, DeviceIOControl, GetDiskFreeSpace, GetOverlappedResult, GetStdHandle, OpenFile, OVERLAPPED, ReadFile, SECURITY_ATTRIBUTES, SetStdHandle TransactNamedPipe, VirtualAlloc, WriteFile


CreateFileMapping
 CreateFileMapping  QuickInfo  Overview  Group

The CreateFileMapping function creates a named or unnamed file-mapping object for the specified file.

HANDLE CreateFileMapping(

HANDLE  hFile,	// handle of file to map
LPSECURITY_ATTRIBUTES  lpFileMappingAttributes,	// optional security attributes
DWORD  flProtect,	// protection for mapping object
DWORD  dwMaximumSizeHigh,	// high-order 32 bits of object size
DWORD  dwMaximumSizeLow,	// low-order 32 bits of object size
LPCTSTR  lpName	// name of file-mapping object
);
Parameters

hFile

Identifies the file from which to create a mapping object. The file must be opened with an access mode compatible with the protection flags specified by the flProtect parameter. It is recommended, though not required, that files you intend to map be opened for exclusive access.

If hFile is (HANDLE)0xFFFFFFFF, the calling process must also specify a mapping object size in the dwMaximumSizeHigh and dwMaximumSizeLow parameters. The function creates a file-mapping object of the specified size backed by the operating-system paging file rather than by a named file in the file system. The file-mapping object can be shared through duplication, through inheritance, or by name.

lpFileMappingAttributes

Points to a SECURITY_ATTRIBUTES structure that specifies the security attributes for the mapping object.

If lpFileMappingAttributes is NULL, the file-mapping object is created with a default security descriptor and the resulting handle is not inherited.

flProtect

Specifies the protection desired for the file view, when the file is mapped. This parameter can be one of the following values:

Value	Description
PAGE_READONLY	Gives read-only access to the committed region of pages. An attempt to write to or execute the committed region results in an access violation. The file specified by the hFile parameter must have been created with GENERIC_READ access.
PAGE_READWRITE	Gives read-write access to the committed region of pages. The file specified by hFile must have been created with GENERIC_READ and GENERIC_WRITE access.
PAGE_WRITECOPY	Gives copy on write access to the committed region of pages. The files specified by the hFile parameter must have been created with GENERIC_READ and GENERIC_WRITE access.
In addition, an application can specify certain section attributes by combining (using the bitwise OR operator) one or more of the following section attribute values with one of the preceding page protection values:

Value	Description
SEC_COMMIT	Allocates physical storage in memory or in the paging file on disk for all pages of a section. This is the default setting.
SEC_IMAGE	The file specified for a section's file mapping is an executable image file. Because the mapping information and file protection are taken from the image file, no other attributes are valid with SEC_IMAGE.
SEC_NOCACHE	All pages of a section are to be set as non-cacheable. This attribute is intended for architectures requiring various locking structures to be in memory that is never fetched into the processor's. On 80x86 and MIPS machines, using the cache for these structures only slows down the performance as the hardware keeps the caches coherent. Some device drivers require noncached data so that programs can write through to the physical memory. SEC_NOCACHE requires either the SEC_RESERVE or SEC_COMMIT to also be set.
SEC_RESERVE	Reserves all pages of a section without allocating physical storage. The reserved range of pages cannot be used by any other allocation operations until it is released. Reserved pages can be committed in subsequent calls to the VirtualAlloc function. This attribute is valid only if the hFile parameter is (HANDLE)0xFFFFFFFF; that is, a file mapping object backed by the operating sytem paging file.
dwMaximumSizeHigh

Specifies the high-order 32 bits of the maximum size of the file-mapping object.

dwMaximumSizeLow

Specifies the low-order 32 bits of the maximum size of the file-mapping object. If this parameter and dwMaximumSizeHig are zero, the maximum size of the file-mapping object is equal to the current size of the file identified by hFile.

lpName

Points to a null-terminated string specifying the name of the mapping object. The name can contain any character except the backslash character (\).

If this parameter matches the name of an existing named mapping object, the function requests access to the mapping object with the protection specified by flProtect.

If this parameter is NULL, the mapping object is created without a name.

Return Value

If the function succeeds, the return value is a handle of the file-mapping object. If the object existed before the function call, the GetLastError function returns ERROR_ALREADY_EXISTS, and the return value is a valid handle to the existing file-mapping object (with its current size, not the new specified size. If the mapping object did not exist, GetLastError returns zero.

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

Remarks

After a file-mapping object has been created, the size of the file must not exceed the size of the file-mapping object; if it does, not all of the file's contents will be available for sharing.

If an application specifies a size for the file-mapping object that is larger than the size of the actual named file on disk, the file on disk is grown to match the specified size of the file-mapping object.

The handle that CreateFileMapping returns has full access to the new file-mapping object. It can be used with any function that requires a handle to a file-mapping object. File-mapping objects can be shared either through process creation, through handle duplication, or by name. For information on duplicating handles, see DuplicateHandle. For information on opening a file-mapping object by name, see OpenFileMapping.

Windows 95: File handles that have been used to create file-mapping objects must not be used in subsequent calls to file I/O functions, such as ReadFile and WriteFile. In general, if a file handle has been used in a successful call to the CreateFileMapping function, do not use that handle unless you first close the corresponding file-mapping object.

Creating a file-mapping object creates the potential for mapping a view of the file but does not map the view. The MapViewOfFile and MapViewOfFileEx functions map a view of a file into a process's address space.

With one important exception, file views derived from a single file-mapping object are coherent, or identical, at a given time. If multiple processes have handles of the same file-mapping object, they see a coherent view of the data when they map a view of the file.

The exception has to do with remote files. Although CreateFileMapping works with remote files, it does not keep them coherent. For example, if two computers both map a file as writable, and both change the same page, each computer will only see its own writes to the page. When the data gets updated on the disk, it is not merged.

A mapped file and a file accessed by means of the input and output (I/O) functions (ReadFile and WriteFile) are not necessarily coherent.

To fully close a file mapping object, an application must unmap all mapped views of the file mapping object by calling UnmapViewOfFile, and close the file mapping object handle by calling CloseHandle. The order in which these functions are called does not matter. The call to UnmapViewOfFile is necessary because mapped views of a file mapping object maintain internal open handles to the object, and a file mapping object will not close until all open handles to it are closed.

Example

To implement a mapping-object creation function that fails if the object already exists, an application can use the following code.

hMap = CreateFileMapping(...);

if (hMap != NULL && GetLastError() == ERROR_ALREADY_EXISTS) {

    CloseHandle(hMap);

    hMap = NULL;

}

return hMap;

See Also

CloseHandle, DuplicateHandle, MapViewOfFile, MapViewOfFileEx, OpenFileMapping, ReadFile, SECURITY_ATTRIBUTES, UnmapViewOfFile, VirtualAlloc, WriteFile


CreateFont
 CreateFont  QuickInfo  Overview  Group

The CreateFont function creates a logical font that has specific characteristics. The logical font can subsequently be selected as the font for any device.

HFONT CreateFont(

int  nHeight,	// logical height of font
int  nWidth,	// logical average character width
int  nEscapement,	// angle of escapement
int  nOrientation,	// base-line orientation angle
int  fnWeight,	// font weight
DWORD  fdwItalic,	// italic attribute flag
DWORD  fdwUnderline,	// underline attribute flag
DWORD  fdwStrikeOut,	// strikeout attribute flag
DWORD  fdwCharSet,	// character set identifier
DWORD  fdwOutputPrecision,	// output precision
DWORD  fdwClipPrecision,	// clipping precision
DWORD  fdwQuality,	// output quality
DWORD  fdwPitchAndFamily,	// pitch and family
LPCTSTR  lpszFace	// address of typeface name string
);
Parameters

nHeight

Specifies the height, in logical units, of the font's character cell or character. The character height value (also known as the em height) is the character cell height value minus the internal-leading value. The font mapper interprets the value specified in nHeight in the following manner:

Value	Meaning
> 0	The font mapper transforms this value into device units and matches it against the cell height of the available fonts.
0	The font mapper uses a default height value when it searches for a match.
< 0	The font mapper transforms this value into device units and matches its absolute value against the character height of the available fonts.
For all height comparisons, the font mapper looks for the largest font that does not exceed the requested size.

This mapping occurs when the font is used for the first time.

For the MM_TEXT mapping mode, you can use the following formula to specify a height for a font with a given point size:

nHeight = -MulDiv(PointSize, GetDeviceCaps(hDC, LOGPIXELSY), 72);

nWidth

Specifies the average width, in logical units, of characters in the requested font. If this value is zero, the font mapper chooses a "closest match" value. The "closest match" value is determined by comparing the absolute values of the difference between the current device's aspect ratio and the digitized aspect ratio of available fonts.

nEscapement

Specifies the angle, in tenths of degrees, between the escapement vector and the x-axis of the device. The escapement vector is parallel to the base line of a row of text.

Windows NT:

When the graphics mode is set to GM_ADVANCED, you can specify the escapement angle of the string independently of the orientation angle of the string's characters.

When the graphics mode is set to GM_COMPATIBLE, nEscapement specifies both the escapement and orientation. You should set nEscapement and nOrientation to the same value.

Windows 95:

The nEscapement parameter specifies both the escapement and orientation. You should set nEscapement and nOrientation to the same value.

nOrientation

Specifies the angle, in tenths of degrees, between each character's base line and the x-axis of the device.

fnWeight

Specifies the weight of the font in the range 0 through 1000. For example, 400 is normal and 700 is bold. If this value is zero, a default weight is used.

The following values are defined for convenience:

Value	Weight
FW_DONTCARE	0
FW_THIN	100
FW_EXTRALIGHT	200
FW_ULTRALIGHT	200
FW_LIGHT	300
FW_NORMAL	400
FW_REGULAR	400
FW_MEDIUM	500
FW_SEMIBOLD	600
FW_DEMIBOLD	600
FW_BOLD	700
FW_EXTRABOLD	800
FW_ULTRABOLD	800
FW_HEAVY	900
FW_BLACK	900
fdwItalic

Specifies an italic font if set to TRUE.

fdwUnderline

Specifies an underlined font if set to TRUE.

fdwStrikeOut

Specifies a strikeout font if set to TRUE.

fdwCharSet

Specifies the character set. The following values are predefined:

ANSI_CHARSET
DEFAULT_CHARSET
SYMBOL_CHARSET
SHIFTJIS_CHARSET
GB2312_CHARSET
HANGEUL_CHARSET
CHINESEBIG5_CHARSET
OEM_CHARSET

Windows 95 only:

JOHAB_CHARSET
HEBREW_CHARSET
ARABIC_CHARSET
GREEK_CHARSET
TURKISH_CHARSET
THAI_CHARSET
EASTEUROPE_CHARSET
RUSSIAN_CHARSET
MAC_CHARSET
BALTIC_CHARSET

The OEM_CHARSET value specifies a character set that is operating-system dependent.

You can use the DEFAULT_CHARSET value to allow the name and size of a font to fully describe the logical font. If the specified font name does not exist, a font from any character set can be substituted for the specified font, so you should use DEFAULT_CHARSET sparingly to avoid unexpected results.

Fonts with other character sets may exist in the operating system. If an application uses a font with an unknown character set, it should not attempt to translate or interpret strings that are rendered with that font.

This parameter is important in the font mapping process. To ensure consistent results, specify a specific character set. If you specify a typeface name in the lpszFace parameter, make sure that the fdwCharSet value matches the character set of the typeface specified in lpszFace.

fdwOutputPrecision

Specifies the output precision. The output precision defines how closely the output must match the requested font's height, width, character orientation, escapement, pitch, and font type. It can be one of the following values:

Value	Meaning
OUT_CHARACTER_PRECIS	Not used.
OUT_DEFAULT_PRECIS	Specifies the default font mapper behavior.
OUT_DEVICE_PRECIS	Instructs the font mapper to choose a Device font when the system contains multiple fonts with the same name.
OUT_OUTLINE_PRECIS	Windows NT: This value instructs the font mapper to choose from TrueType and other outline-based fonts. Windows 95: This value is not used.
OUT_RASTER_PRECIS	Instructs the font mapper to choose a raster font when the system contains multiple fonts with the same name.
OUT_STRING_PRECIS	This value is not used by the font mapper, but it is returned when raster fonts are enumerated.
OUT_STROKE_PRECIS	Windows NT: This value is not used by the font mapper, but it is returned when TrueType, other outline-based fonts, and vector fonts are enumerated.  Windows 95: This value is used to map vector fonts, and is returned when TrueType or vector fonts are enumerated.
OUT_TT_ONLY_PRECIS	Instructs the font mapper to choose from only TrueType fonts. If there are no TrueType fonts installed in the system, the font mapper returns to default behavior.
OUT_TT_PRECIS	Instructs the font mapper to choose a TrueType font when the system contains multiple fonts with the same name.
Applications can use the OUT_DEVICE_PRECIS, OUT_RASTER_PRECIS, and OUT_TT_PRECIS values to control how the font mapper chooses a font when the operating system contains more than one font with a given name. For example, if an operating system contains a font named Symbol in raster and TrueType form, specifying OUT_TT_PRECIS forces the font mapper to choose the TrueType version. Specifying OUT_TT_ONLY_PRECIS forces the font mapper to choose a TrueType font, even if it must substitute a TrueType font of another name.

fdwClipPrecision

Specifies the clipping precision. The clipping precision defines how to clip characters that are partially outside the clipping region. It can be one or more of the following values:

Value	Meaning
CLIP_DEFAULT_PRECIS	Specifies default clipping behavior.
CLIP_CHARACTER_PRECIS	Not used.
CLIP_STROKE_PRECIS	Not used by the font mapper, but is returned when raster, vector, or TrueType fonts are enumerated. Windows NT: For compatibility, this value is always returned when enumerating fonts.
CLIP_MASK	Not used.
CLIP_EMBEDDED	You must specify this flag to use an embedded read-only font.
CLIP_LH_ANGLES	When this value is used, the rotation for all fonts depends on whether the orientation of the coordinate system is left-handed or right-handed.  If not used, device fonts always rotate counterclockwise, but the rotation of other fonts is dependent on the orientation of the coordinate system. For more information about the orientation of coordinate systems, see the description of the nOrientation parameter
CLIP_TT_ALWAYS	Not used.
fdwQuality

Specifies the output quality. The output quality defines how carefully GDI must attempt to match the logical-font attributes to those of an actual physical font. It can be one of the following values:

Value	Meaning
DEFAULT_QUALITY	Appearance of the font does not matter.
DRAFT_QUALITY	Appearance of the font is less important than when the PROOF_QUALITY value is used. For GDI raster fonts, scaling is enabled, which means that more font sizes are available, but the quality may be lower. Bold, italic, underline, and strikeout fonts are synthesized if necessary.
PROOF_QUALITY	Character quality of the font is more important than exact matching of the logical-font attributes. For GDI raster fonts, scaling is disabled and the font closest in size is chosen. Although the chosen font size may not be mapped exactly when PROOF_QUALITY is used, the quality of the font is high and there is no distortion of appearance. Bold, italic, underline, and strikeout fonts are synthesized if necessary.
fdwPitchAndFamily

Specifies the pitch and family of the font. The two low-order bits specify the pitch of the font and can be one of the following values:

DEFAULT_PITCH
FIXED_PITCH
VARIABLE_PITCH

The four high-order bits specify the font family and can be one of the following values:

Value	Description
FF_DECORATIVE	Novelty fonts. Old English is an example.
FF_DONTCARE	Don't care or don't know.
FF_MODERN	Fonts with constant stroke width, with or without serifs. Pica, Elite, and Courier New® are examples.
FF_ROMAN	Fonts with variable stroke width and with serifs. MS® Serif is an example.
FF_SCRIPT	Fonts designed to look like handwriting. Script and Cursive are examples.
FF_SWISS	Fonts with variable stroke width and without serifs. MS Sans Serif is an example.
An application can specify a value for the fdwPitchAndFamily parameter by using the Boolean OR operator to join a pitch constant with a family constant.

Font families describe the look of a font in a general way. They are intended for specifying fonts when the exact typeface requested is not available.

lpszFace

Points to a null-terminated string that specifies the typeface name of the font. The length of this string must not exceed 32 characters, including the null terminator. The EnumFontFamilies function can be used to enumerate the typeface names of all currently available fonts.

If lpszFace is NULL or points to an empty string, GDI uses the first font that matches the other specified attributes.

Return Value

If the function succeeds, the return value is a handle of a logical font.

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

Remarks

When you no longer need the font, call the DeleteObject function to delete it.

To help protect the copyrights of vendors who provide fonts for Windows operating systems, applications should always report the exact name of a selected font. Because available fonts can vary from system to system, do not assume that the selected font is always the same as the requested font. For example, if you request a font named "Palatino," but no such font is available on the system, the font mapper will substitute a font that has similar attributes but a different name. Always report the name of the selected font to the user.

See Also

DeleteObject, SelectObject, EnumFontFamilies


CreateFontIndirect
 CreateFontIndirect  QuickInfo  Overview  Group

The CreateFontIndirect function creates a logical font that has the characteristics specified in the specified structure. The font can subsequently be selected as the current font for any device context.

HFONT CreateFontIndirect(

CONST LOGFONT  *lplf	// address of logical font structure
);
Parameters

lplf

Points to a LOGFONT structure that defines the characteristics of the logical font.

Return Value

If the function succeeds, the return value is a handle of a logical font.

If the function fails, the return value is NULL.

Remarks

The CreateFontIndirect function creates a logical font with the characteristics specified in the LOGFONT structure. When this font is selected by using the SelectObject function, GDI's font mapper attempts to match the logical font with an existing physical font. If it fails to find an exact match, it provides an alternative whose characteristics match as many of the requested characteristics as possible.

When you no longer need the font, call the DeleteObject function to delete it.

See Also

DeleteObject, LOGFONT, SelectObject


CreateHalftonePalette
 CreateHalftonePalette  QuickInfo  Overview  Group

The CreateHalftonePalette function creates a halftone palette for the specified device context.

HPALETTE CreateHalftonePalette(

HDC  hdc	// handle of device context
);
Parameters

hdc

Identifies the device context.

Return Value

If the function succeeds, the return value identifies a logical halftone palette.

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

Remarks

An application should create a halftone palette when the stretching mode of a device context is set to HALFTONE. The logical halftone palette returned by CreateHalftonePalette should then be selected and realized into the device context before the StretchBlt or StretchDIBits function is called.

When you no longer need the palette, call the DeleteObject function to delete it.

See Also

DeleteObject, RealizePalette, SelectPalette, SetStretchBltMode, StretchDIBits, StretchBlt


CreateHatchBrush
 CreateHatchBrush  QuickInfo  Overview  Group

The CreateHatchBrush function creates a logical brush that has the specified hatch pattern and color.

HBRUSH CreateHatchBrush(

int  fnStyle,	// hatch style
COLORREF  clrref	// color value
);
Parameters

fnStyle

Specifies the hatch style of the brush. This parameter can be any one of the following values:

Value	Meaning
HS_BDIAGONAL	45-degree downward left-to-right hatch
HS_CROSS	Horizontal and vertical crosshatch
HS_DIAGCROSS	45-degree crosshatch
HS_FDIAGONAL	45-degree upward left-to-right hatch
HS_HORIZONTAL	Horizontal hatch
HS_VERTICAL	Vertical hatch
clrref

Specifies the foreground color of the brush that is used for the hatches.

Return Value

If the function succeeds, the return value identifies a logical brush.

If the function fails, the return value is NULL.

Remarks

A brush is a bitmap that Windows uses to paint the interiors of filled shapes.

After an application creates a brush by calling CreateHatchBrush, it can select that brush into any device context by calling the SelectObject function.

If an application uses a hatch brush to fill the backgrounds of both a parent and a child window with matching color, it may be necessary to set the brush origin before painting the background of the child window. You can do this by having your application call the SetBrushOrgEx function. Your application can retrieve the current brush origin by calling the GetBrushOrgEx function.

When you no longer need the brush, call the DeleteObject function to delete it.

See Also

CreateDIBPatternBrush, CreateDIBPatternBrushPt, CreatePatternBrush, CreateSolidBrush, DeleteObject, GetBrushOrgEx, SelectObject, SetBrushOrgEx


CreateIC
 CreateIC  QuickInfo  Overview  Group

The CreateIC function creates an information context for the specified device. The information context provides a fast way to get information about the device without creating a device context.

HDC CreateIC(

LPCTSTR  lpszDriver,	// address of string specifying driver name
LPCTSTR  lpszDevice,	// address of string specifying device name
LPCTSTR  lpszOutput,	// address of string specifying port or file name
CONST DEVMODE *  lpdvmInit	// address of optional initialization data
);
Parameters

lpszDriver

Points to a null-terminated character string that specifies the name of the device driver (for example, "Epson").

lpszDevice

Points to a null-terminated character string that specifies the name of the specific output device being used, as shown by the Print Manager (for example, "Epson FX-80"). It is not the printer model name. The lpszDevice parameter must be used.

lpszOutput

Points to a null-terminated character string that specifies the file or device name for the physical output medium (file or output port). This parameter is ignored; it is present only to keep the function prototype identical with Windows version 3.1.

lpdvmInit

Points to a DEVMODE structure containing device-specific initialization data for the device driver. The DocumentProperties function retrieves this structure filled in for a given device. The lpdvmInit parameter must be NULL if the device driver is to use the default initialization (if any) specified by the user.

Return Value

If the function succeeds, the return value is the handle of an information context.

If the function fails, the return value is NULL.

Remarks

An error occurs if an application calls a GDI drawing function and supplies a handle identifying an information context.

When you no longer need the information device context, call the DeleteDC function to delete it.

See Also

DeleteDC, DocumentProperties, DEVMODE, GetDeviceCaps


CreateIcon
 CreateIcon  QuickInfo  Overview  Group

The CreateIcon function creates an icon that has the specified size, colors, and bit patterns.

HICON CreateIcon(

HINSTANCE  hInstance,	// handle of application instance
int  nWidth,	// icon width
int  nHeight,	// icon height
BYTE  cPlanes,	// number of planes in XOR bitmask
BYTE  cBitsPixel,	// number of bits per pixel in XOR bitmask
CONST BYTE  *lpbANDbits,	// address of AND bitmask array
CONST BYTE  *lpbXORbits	// address of XOR bitmask array
);
Parameters

hInstance

Identifies the instance of the module creating the icon.

nWidth

Specifies the width, in pixels, of the icon.

nHeight

Specifies the height, in pixels, of the icon.

cPlanes

Specifies the number of planes in the XOR bitmask of the icon.

cBitsPixel

Specifies the number of bits per pixel in the XOR bitmask of the icon.

lpbANDbits

Points to an array of bytes that contains the bit values for the AND bitmask of the icon. This bitmask describes a monochrome bitmap.

lpbXORbits

Points 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 Value

If the function succeeds, the return value is the handle of 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
Before closing, an application must call the DestroyIcon function to free system resources associated with the icon.

See Also

DestroyIcon, GetSystemMetrics


CreateIconFromResource
 CreateIconFromResource  QuickInfo  Overview  Group

The CreateIconFromResource function creates an icon or cursor from resource bits describing the icon.

HICON CreateIconFromResource(

PBYTE  presbits,	// address of icon or cursor bits
DWORD  dwResSize,	// number of bytes in bit buffer
BOOL  fIcon,	// icon or cursor flag
DWORD  dwVer	// Windows format version
);
Parameters

presbits

Points to a buffer containing the icon or cursor resource bits. These bits are typically loaded by calls to the LookupIconIdFromDirectory (in Windows 95 you can also call LookupIconIdFromDirectoryEx) and LoadResource functions.

dwResSize

Specifies the size, in bytes, of the set of bits pointed to by the presbits parameter.

fIcon

Specifies whether an icon or a cursor is to be created. If this parameter is TRUE, an icon is to be created. If it is FALSE, a cursor is to be created.

dwVer

Specifies the version number of the icon or cursor format for the resource bits pointed to by the presbits parameter. This parameter can be one of the following values:

Format	dwVer
Windows 2.x	0x00020000
Windows 3.x	0x00030000
All Microsoft Win32-based applications use the Windows 3.x format for icons and cursors.

Return Value

If the function succeeds, the return value is the handle of the icon or cursor.

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

Remarks

The CreateIconFromResource, CreateIconIndirect, GetIconInfo, and LookupIconIdFromDirectory functions (and in Windows 95 the CreateIconFromResourceEx and LookupIconIdFromDirectoryEx functions) allow shell applications and icon browsers to examine and use resources from throughout the system.

See Also

CreateIconFromResource, CreateIconFromResourceEx, CreateIconIndirect, GetIconInfo, LoadResource, LookupIconIdFromDirectory LookupIconIdFromDirectoryEx


CreateIconFromResourceEx [New - Windows 95]
 CreateIconFromResourceEx  QuickInfo

[New - Windows 95]

The CreateIconFromResourceEx function creates an icon or cursor from resource bits describing the icon.

HICON CreateIconFromResourceEx(

PBYTE  pbIconBits,	// address of icon or cursor bits
DWORD  cbIconBits,	// number of bytes in bit buffer
BOOL  fIcon,	// icon or cursor flag
DWORD  dwVersion,	// Windows format version
int  cxDesired,	// desired width of icon or cursor
int  cyDesired,	// desired height of icon or cursor
UINT  uFlags	// load resource flags
);
Parameters

pbIconBits

Points to a buffer containing the icon or cursor resource bits. These bits are typically loaded by calls to the LookupIconIdFromDirectoryEx and LoadResource functions.

cbIconBits

Specifies the size, in bytes, of the set of bits pointed to by the pbIconBits parameter.

fIcon

Specifies whether an icon or a cursor is to be created. If this parameter is TRUE, an icon is to be created. If it is FALSE, a cursor is to be created.

dwVersion

Specifies the version number of the icon or cursor format for the resource bits pointed to by the pbIconBits parameter. This parameter can be one of the following values:

Format	dwVersion
Windows 2.x	0x00020000
Windows 3.x	0x00030000
All Win32-based applications use the Windows 3.x format for icons and cursors.

cxDesired

Specifies the desired width, in pixels, of the icon or cursor. If this parameter is zero and uFlags does not include LR_LOADREALSIZE, the function uses the SM_CXICON or SM_CXCURSOR system metric value to set the width.

cyDesired

Specifies the desired height, in pixels, of the icon or cursor. If this parameter is zero and uFlags does not include LR_LOADREALSIZE, the function uses the SM_CYICON or SM_CYCURSOR system metric value to set the height.

uFlags

Specifies a combination of the following values:

Value	Meaning
LR_DEFAULTCOLOR	Uses the default color format.
LR_LOADREALSIZE	Sets the width and height as specified by the biWidth and biHeight members of the BITMAPINFOHEADER structure that defines the icon or cursor. The cxDesired and cyDesired parameters are ignored.
LR_MONOCHROME	Creates a monochrome icon or cursor.
Return Value

If the function succeeds, the return value is the handle of the icon or cursor.

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

Remarks

The CreateIconFromResourceEx, CreateIconFromResource, CreateIconIndirect, GetIconInfo, and LookupIconIdFromDirectoryEx functions allow shell applications and icon browsers to examine and use resources from throughout the system.

See Also

BITMAPINFOHEADER, CreateIconFromResource, CreateIconIndirect, GetIconInfo, LoadResource, LookupIconIdFromDirectoryEx


CreateIconIndirect
 CreateIconIndirect  QuickInfo  Overview  Group

The CreateIconIndirect function creates an icon or cursor from an ICONINFO structure.

HICON CreateIconIndirect(

PICONINFO  piconinfo	// address of icon information structure
);
Parameters

piconinfo

Points to an ICONINFO structure the function uses to create the icon or cursor.

Return Value

If the function succeeds, the return value is the handle of 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. The application must continue to manage the original bitmaps and delete them when they are no longer necessary.

See Also

CreateIcon, CreateIconFromResource, DestroyIcon, DrawIcon, GetIconInfo, ICONINFO, LoadIcon, LookupIconIdFromDirectory


CreateIoCompletionPort
 CreateIoCompletionPort  QuickInfo  Overview  Group

The CreateIoCompletionPort function associates an instance of an opened file with a newly created or an existing input/output completion port.

Associating an instance of an opened file with an input/output completion port lets an application receive notification of the completion of asynchronous input/output operations involving that file.

Windows NT only:

CreateIoCompletionPort can create an input/output completion port without associating it with a file.

HANDLE CreateIoCompletionPort (

HANDLE FileHandle,	// file handle to associate with I/O completion port
HANDLE ExistingCompletionPort,	// optional handle to existing I/O completion port
DWORD CompletionKey,	// per-file completion key for I/O completion packets
DWORD NumberOfConcurrentThreads	// number of threads allowed to execute concurrently
);
Parameters

FileHandle

Handle to a file opened for overlapped input/output completion. You must specify the FILE_FLAG_OVERLAPPED flag to obtain such a handle.

The CreateIoCompletionPort function associates the file with an existing input/output completion port, or with one that the function creates.

Once an instance of an open file is associated with an I/O completion port, it cannot be used in ReadFileEx or WriteFileEx operations.

It is best not to share such an associated file through either handle inheritance or a call to the DuplicateHandle function. Input/output operations done with such duplicate handles will generate completion notifications.

Windows NT:

If FileHandle specifies INVALID_HANDLE_VALUE, CreateIoCompletionPort creates an input/output completion port without associating it with a file. In this case, the ExistingCompletionPort parameter must be NULL, and the CompletionKey parameter is ignored.

Windows 95:

Does not support specifying INVALID_HANDLE_VALUE for the FileHandle parameter.

ExistingCompletionPort

Handle to an existing I/O completion port. This parameter can be NULL.

If this parameter is not NULL, it specifies an existing completion port that the function is to associate with the file specified by FileHandle.

If this parameter is NULL, the function creates a new input/output completion port that it associates with the specified file.

CompletionKey

Specifies a per-file completion key that will be included in every input/output completion packet for the specified file.

NumberOfConcurrentThreads

Specifies the number of threads that are allowed to execute concurrently.

If one of the threads enters a wait state, then another thread is allowed to proceed. There may be brief periods when the number of active threads exceeds the specified value, but the operating system quickly brings the number back down.

A value of 0 for this parameter tells the operating system to allow as many threads as there are processors in the system.

Return Value

If the function succeeds, the return value is the handle of the I/O completion port that is associated with the specified file. This return value is not NULL.

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

Remarks

The Win32 I/O system can be instructed to send I/O completion notification packets to input/output completion ports, where they are queued up. The CreateIoCompletionPort function provides a mechanism for this.

When you perform an input/output operation with a file handle that has an associated input/output completion port, the I/O system sends a completion notification packet to the completion port when the I/O operation completes. The I/O completion port places the completion packet in a first-in-first-out queue. Use the GetQueuedCompletionStatus function to retrieve these queued I/O completion packets.

You can create an I/O completion port without an associated instance of an open file. To do this, just specify the INVALID_HANDLE_VALUE flag in FileHandle. Use PostQueuedCompletionStatus to write I/O completion notification packets to the port and GetQueuedCompletionStatus to retrieve the packets. This provides a means for different threads within a process to communicate with each other.

See Also

DuplicateHandle, GetQueuedCompletionStatus, PostQueuedCompletionStatus, ReadFileEx, WriteFileEx


CreateMailslot
 CreateMailslot  QuickInfo  Overview  Group

The CreateMailslot function creates a mailslot with the specified name and returns a handle that a mailslot server can use to perform operations on the mailslot. The mailslot is local to the computer that creates it. An error occurs if a mailslot with the specified name already exists.

HANDLE CreateMailslot(

LPCTSTR  lpName,	// address of string for mailslot name
DWORD  nMaxMessageSize,	// maximum message size
DWORD  lReadTimeout,	// milliseconds before read time-out
LPSECURITY_ATTRIBUTES  lpSecurityAttributes	// address of security structure
);
Parameters

lpName

Points to a null-terminated string specifying the name of the mailslot. This name must have the following form:

\\.\mailslot\[path]name

The name field must be unique. The name may include multiple levels of pseudodirectories separated by backslashes. For example, both \\.\mailslot\example_mailslot_name and \\.\mailslot\abc\def\ghi are valid names.

nMaxMessageSize

Specifies the maximum size, in bytes, of a single message that can be written to the mailslots. To specify that the message can be of any size, set this value to zero.

lReadTimeout

Specifies the amount of time, in milliseconds, a read operation can wait for a message to be written to the mailslot before a time-out occurs. The following values have special meanings:

Value	Meaning
0	Returns immediately if no message is present. (The system does not treat an immediate return as an error.)
MAILSLOT_WAIT_FOREVER	Waits forever for a message.
This time-out value applies to all subsequent read operations and all inherited mailslot handles.

lpSecurityAttributes

Points to a SECURITY_ATTRIBUTES structure specifying the security attributes for the mailslot.

If lpSecurityAttributes is NULL, the mailslot is created with a default security descriptor, and the resulting handle is not inherited.

Return Value

If the function succeeds, the return value is a handle to the mailslot, for use in server mailslot operations.

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

Remarks

The mailslot exists until one of the following conditions is true:

•	The last (possibly inherited or duplicated) handle to it is closed using the CloseHandle function.

•	The process owning the last (possibly inherited or duplicated) handle exits.

Both Windows NT and Windows 95 use the second method to destroy mailslots.

To write a message to a mailslot, a process uses the CreateFile function, specifying the mailslot name by using one of the following formats:

Format	Usage
\\.\mailslot\name	Retrieves a client handle to a local mailslot.
\\computername\mailslot\name	Retrieves a client handle to a remote mailslot.
\\domainname\mailslot\name	Retrieves a client handle to all mailslots with the given name in the specified domain.
\\*\mailslot\name	Retrieves a client handle to all mailslots with the given name in the system's primary domain.
If CreateFile specifies a domain or uses the asterisk format to specify the system's primary domain, the application cannot write more than 400 bytes at a time to the mailslot. If the application attempts to do so, the WriteFile function fails and GetLastError returns ERROR_BAD_NETPATH.

An application must specify the FILE_SHARE_READ flag when using CreateFile to retrieve a client handle to a mailslot.

See Also

CloseHandle, CreateFile, GetMailslotInfo, SECURITY_ATTRIBUTES, SetMailslotInfo, WriteFile


CreateMappedBitmap [New - Windows NT]
 CreateMappedBitmap  QuickInfo  Overview  Group

[New - Windows NT]

The CreateMappedBitmap function creates a bitmap for use in a toolbar.

HBITMAP CreateMappedBitmap(

HINSTANCE  hInstance,
int  idBitmap,
UINT  wFlags,
LPCOLORMAP lpColorMap,
int  iNumMaps
);
Parameters

hInstance

Handle to the module instance with the executable file that contains the bitmap resource.

idBitmap

Resource identifier of the bitmap resource.

wFlags

Bitmap flag. This parameter can be zero or the following value:

Value	Meaning
CMB_MASKED	Uses a bitmap as a mask.
lpColorMap

Pointer to a COLORMAP structure that contains the color information needed to map the bitmaps. If this parameter is NULL, the function uses the default color map.

iNumMaps

Number of color maps pointed to by lpColorMap.

Return Value

If the function succeeds, the return value is the handle to the bitmap.

If the function fails, the return value is NULL.

Remarks

The function creates a new bitmap using the bitmap data and colors specified by the given bitmap resource and the color mapping information.

See Also

COLORMAP


CreateMDIWindow
 CreateMDIWindow  QuickInfo  Overview  Group

The CreateMDIWindow function creates a multiple document interface (MDI) child window.

HWND CreateMDIWindow(

LPTSTR  lpClassName,	// address of registered child class name
LPTSTR  lpWindowName,	// address of window name
DWORD  dwStyle,	// window style
int  X,	// horizontal position of window
int  Y,	// vertical position of window
int  nWidth,	// width of window
int  nHeight,	// height of window
HWND  hWndParent,	// handle of parent window (MDI client)
HINSTANCE  hInstance,	// handle of application instance
LPARAM  lParam	// application-defined value
);
Parameters

lpClassName

Points 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 RegisterClass function.

lpWindowName

Points to a null-terminated string that represents the window name. Windows displays the name in the title bar of the child window.

dwStyle

Specifies the style of the MDI child window. If the MDI client window is created with the MDIS_ALLCHILDSTYLES window style, this parameter can be any combination of the window styles listed in the description of the CreateWindow function. Otherwise, this parameter can be one or more of the following values:

Value	Meaning
WS_MINIMIZE	Creates an MDI child window that is initially minimized.
WS_MAXIMIZE	Creates an MDI child window that is initially maximized.
WS_HSCROLL	Creates an MDI child window that has a horizontal scroll bar.
WS_VSCROLL	Creates an MDI child window that has a vertical scroll bar.
X

Specifies the initial horizontal position, in client coordinates, of the MDI child window. If this parameter is CW_USEDEFAULT, the MDI child window is assigned the default horizontal position.

Y

Specifies the initial vertical position, in client coordinates, of the MDI child window. If this parameter is CW_USEDEFAULT, the MDI child window is assigned the default vertical position.

nWidth

Specifies the initial width, in device units, of the MDI child window. If this parameter is CW_USEDEFAULT, the MDI child window is assigned the default width.

nHeight

Specifies the initial height, in device units, of the MDI child window. If this parameter is set to CW_USEDEFAULT, the MDI child window is assigned the default height.

hWndParent

Identifies the MDI client window that will be the parent of the new MDI child window.

hInstance

Identifies the instance of the application creating the MDI child window.

lParam

Specifies an application-defined value.

Return Value

If the function succeeds, the return value is the handle of the created window.

If the function fails, the return value is NULL.

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 only: The system can support a maximum of 16,364 window handles.

See Also

CreateWindow, RegisterClass, WM_MDICREATE


CreateMenu
 CreateMenu  QuickInfo  Overview  Group

The CreateMenu function creates a menu. The menu is initially empty, but it can be filled with menu items by using the AppendMenu and InsertMenu functions.

HMENU CreateMenu(VOID)

Parameters

This function has no parameters.

Return Value

If the function succeeds, the return value is the handle of the newly created menu.

If the function fails, the return value is NULL.

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 only: The system can support a maximum of 16,364 menu handles.

See Also

AppendMenu, DestroyMenu, InsertMenu, SetMenu


CreateMetaFile
 CreateMetaFile  QuickInfo  Overview  Group

The CreateMetaFile function creates a device context for a Windows-format metafile.

This function is provided for compatibility with earlier 16-bit versions of Microsoft Windows. Win32-based applications should use the CreateEnhMetaFile function.

HDC CreateMetaFile(

LPCTSTR  lpszFile	// address of filename string
);
Parameters

lpszFile

Points to the filename for the Windows-format metafile to be created. If this parameter is NULL, the Windows-format metafile is memory based and its contents are lost when it is deleted by using the DeleteMetaFile function.

Return Value

If the function succeeds, the return value is a handle of the device context for the Windows-format metafile.

If the function fails, the return value is NULL.

Remarks

Where text arguments must use Unicode characters, use this function as a wide-character function. Where text arguments must use characters from the Windows 3.x character set, use this function as an ANSI function.

CreateMetaFile is a Windows-format metafile function. This function supports only applications designed for Microsoft Windows version 3.x. It does not record or play back the new Win32 graphics device interface (GDI) functions such as PolyBezier.

The device context created by this function can be used to record GDI output functions in a Windows-format metafile. It cannot be used with GDI query functions such as GetTextColor. When the device context is used with a GDI output function, the return value of that function becomes TRUE if the function is recorded and FALSE otherwise. When an object is selected by using the SelectObject function, only a copy of the object is recorded. The object still belongs to the application.

To create a scalable Windows-format metafile, record the graphics output in the MM_ANISOTROPIC mapping mode. The file cannot contain functions that modify the viewport origin and extents, nor can it contain device-dependent functions such as the SelectClipRgn function. Once created, the Windows metafile can be scaled and rendered to any output device-format by defining the viewport origin and extents of the picture before playing it.

See Also

CloseMetaFile, CreateEnhMetaFile, DeleteMetaFile, GetTextColor, PolyBezier, SelectClipRgn, SelectObject


CreateMutex
 CreateMutex  QuickInfo  Overview  Group

The CreateMutex function creates a named or unnamed mutex object.

HANDLE CreateMutex(

LPSECURITY_ATTRIBUTES  lpMutexAttributes,	// address of security attributes
BOOL  bInitialOwner,	// flag for initial ownership
LPCTSTR  lpName	// address of mutex-object name
);
Parameters

lpMutexAttributes

Points to a SECURITY_ATTRIBUTES structure that specifies the security attributes for the mutex object.

If lpMutexAttributes is NULL, the mutex object is created with a default security descriptor and the resulting handle is not inheritable.

bInitialOwner

Specifies the initial owner of the mutex object. If TRUE, the calling thread requests immediate ownership of the mutex object. Otherwise, the mutex is not owned.

lpName

Points to a null-terminated string specifying the name of the mutex object. The name is limited to MAX_PATH characters and can contain any character except the backslash path-separator character (\). Name comparison is case sensitive.

If lpName matches the name of an existing named mutex object, this function requests MUTEX_ALL_ACCESS access to the existing object. In this case, the bInitialOwner parameter is ignored because it has already been set by the creating process. If the lpMutexAttributes parameter is not NULL, it determines whether the handle can be inherited, but its security-descriptor member is ignored.

If lpName is NULL, the mutex object is created without a name.

If lpName matches the name of an existing event, semaphore, or file-mapping object, the function fails and the GetLastError function returns ERROR_INVALID_HANDLE. This occurs because event, mutex, semaphore, and file-mapping objects share the same name space.

Return Value

If the function succeeds, the return value is a handle of the mutex object. If the named mutex object existed before the function call, the GetLastError function returns ERROR_ALREADY_EXISTS. Otherwise, GetLastError returns zero.

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

Remarks

The handle returned by CreateMutex has MUTEX_ALL_ACCESS access to the new mutex object and can be used in any function that requires a handle of a mutex object.

Any thread of the calling process can specify the mutex-object handle in a call to one of the wait functions (MsgWaitForMultipleObjects, WaitForSingleObject, WaitForMultipleObjects, WaitForSingleObjectEx, or WaitForMultipleObjectsEx). The single-object wait functions return when the state of the specified object is signaled. The multiple-object wait functions can be instructed to return either when any one or when all of the specified objects are signaled. When a wait function returns, the waiting thread is released to continue its execution.

The state of a mutex object is signaled when it is not owned by any thread. The creating thread can use the bInitialOwner flag to request immediate ownership of the mutex. Otherwise, a thread must use one of the wait functions to request ownership. When the mutex's state is signaled, one waiting thread is granted ownership, the mutex's state changes to nonsignaled, and the wait function returns. Only one thread can own a mutex at any given time. The owning thread uses the ReleaseMutex function to release its ownership.

The thread that owns a mutex can specify the same mutex in repeated wait function calls without blocking its execution. Typically, you would not wait repeatedly for the same mutex, but this mechanism prevents a thread from deadlocking itself while waiting for a mutex that it already owns. However, to release its ownership, the thread must call ReleaseMutex once for each time that the mutex satisfied a wait.

Two or more processes can call CreateMutex to create the same named mutex. The first process actually creates the mutex, and subsequent processes open a handle of the existing mutex. This enables multiple processes to get handles of the same mutex, while relieving the user of the responsibility of ensuring that the creating process is started first. When using this technique, you should set the bInitialOwner flag to FALSE; otherwise, it can be difficult to be certain which process has initial ownership.

Multiple processes can have handles of the same mutex object, enabling use of the object for interprocess synchronization. The following object-sharing mechanisms are available:

•	A child process created by the CreateProcess function can inherit a handle of a mutex object if the lpMutexAttributes parameter of CreateMutex enabled inheritance.

•	A process can specify the mutex-object handle in a call to the DuplicateHandle function to create a duplicate handle that can be used by another process.

•	A process can specify the name of a mutex object in a call to the OpenMutex or CreateMutex function.

Use the CloseHandle function to close the handle. The system closes the handle automatically when the process terminates. The mutex object is destroyed when its last handle has been closed.

See Also

CloseHandle, CreateProcess, DuplicateHandle, MsgWaitForMultipleObjects, OpenMutex, ReleaseMutex, SECURITY_ATTRIBUTES, WaitForMultipleObjects, WaitForMultipleObjectsEx, WaitForSingleObject, WaitForSingleObjectEx


CreateNamedPipe
 CreateNamedPipe  QuickInfo  Overview  Group

The CreateNamedPipe function creates an instance of a named pipe and returns a handle for subsequent pipe operations. A named pipe server process uses this function either to create the first instance of a specific named pipe and establish its basic attributes or to create a new instance of an existing named pipe.

HANDLE CreateNamedPipe(

LPCTSTR  lpName,	// address of pipe name
DWORD  dwOpenMode,	// pipe open mode
DWORD  dwPipeMode,	// pipe-specific modes
DWORD  nMaxInstances,	// maximum number of instances
DWORD  nOutBufferSize,	// output buffer size, in bytes
DWORD  nInBufferSize,	// input buffer size, in bytes
DWORD  nDefaultTimeOut,	// time-out time, in milliseconds
LPSECURITY_ATTRIBUTES  lpSecurityAttributes	// address of security attributes structure
);
Parameters

lpName

Points to the null-terminated string that uniquely identifies the pipe. The string must have the following form:

\\.\pipe\pipename

The pipename part of the name can include any character other than a backslash, including numbers and special characters. The entire pipe name string can be up to 256 characters long. Pipe names are not case sensitive.

dwOpenMode

Specifies the pipe access mode, the overlapped mode, the write-through mode, and the security access mode of the pipe handle.

This parameter must specify one of the following pipe access mode flags. The same mode must be specified for each instance of the pipe:

Mode	Description
PIPE_ACCESS_DUPLEX	The pipe is bidirectional; both server and client processes can read from and write to the pipe. This mode gives the server the equivalent of GENERIC_READ | GENERIC_WRITE access to the pipe. The client can specify GENERIC_READ or GENERIC_WRITE, or both, when it connects to the pipe using the CreateFile function.
PIPE_ACCESS_INBOUND	The flow of data in the pipe goes from client to server only. This mode gives the server the equivalent of GENERIC_READ access to the pipe. The client must specify GENERIC_WRITE access when connecting to the pipe.
PIPE_ACCESS_OUTBOUND	The flow of data in the pipe goes from server to client only. This mode gives the server the equivalent of GENERIC_WRITE access to the pipe. The client must specify GENERIC_READ access when connecting to the pipe.
This parameter can also include either or both of the following flags, which enable write-through mode and overlapped mode. These modes can be different for different instances of the same pipe.

Mode	Description
FILE_FLAG_WRITE_THROUGH
	Write-through mode is enabled. This mode affects only write operations on byte-type pipes and, then, only when the client and server processes are on different computers. If this mode is enabled, functions writing to a named pipe do not return until the data written is transmitted across the network and is in the pipe's buffer on the remote computer. If this mode is not enabled, the system enhances the efficiency of network operations by buffering data until a minimum number of bytes accumulate or until a maximum time elapses.
FILE_FLAG_OVERLAPPED
	Overlapped mode is enabled. If this mode is enabled, functions performing read, write, and connect operations that may take a significant time to be completed can return immediately. This mode enables the thread that started the operation to perform other operations while the time-consuming operation executes in the background. For example, in overlapped mode, a thread can handle simultaneous input and output (I/O) operations on multiple instances of a pipe or perform simultaneous read and write operations on the same pipe handle. If overlapped mode is not enabled, functions performing read, write, and connect operations on the pipe handle do not return until the operation is finished. The ReadFileEx and WriteFileEx functions can only be used with a pipe handle in overlapped mode. The ReadFile, WriteFile, ConnectNamedPipe, and TransactNamedPipe functions can execute either synchronously or as overlapped operations.
This parameter can include any combination of the following security access mode flags. These modes can be different for different instances of the same pipe. They can be specified without concern for what other dwOpenMode modes have been specified.

Mode	Description
WRITE_DAC	The caller will have write access to the named pipe's discretionary access control list (ACL).
WRITE_OWNER	The caller will have write access to the named pipe's owner.
ACCESS_SYSTEM_SECURITY	The caller will have write access to the named pipe's system ACL.
dwPipeMode

Specifies the type, read, and wait modes of the pipe handle.

One of the following type mode flags can be specified. The same type mode must be specified for each instance of the pipe. If you specify zero, the parameter defaults to byte-type mode.

Mode	Description
PIPE_TYPE_BYTE	Data is written to the pipe as a stream of bytes. This mode cannot be used with PIPE_READMODE_MESSAGE.
PIPE_TYPE_MESSAGE	Data is written to the pipe as a stream of messages. This mode can be used with either PIPE_READMODE_MESSAGE or PIPE_READMODE_BYTE.
One of the following read mode flags can be specified. Different instances of the same pipe can specify different read modes. If you specify zero, the parameter defaults to byte-read mode.

Mode	Description
PIPE_READMODE_BYTE	Data is read from the pipe as a stream of bytes. This mode can be used with either PIPE_TYPE_MESSAGE or PIPE_TYPE_BYTE.
PIPE_READMODE_MESSAGE	Data is read from the pipe as a stream of messages. This mode can be only used if PIPE_TYPE_MESSAGE is also specified.
One of the following wait mode flags can be specified. Different instances of the same pipe can specify different wait modes. If you specify zero, the parameter defaults to blocking mode.

Mode	Description
PIPE_WAIT	Blocking mode is enabled. When the pipe handle is specified in the ReadFile, WriteFile, or ConnectNamedPipe function, the operations are not completed until there is data to read, all data is written, or a client is connected. Use of this mode can mean waiting indefinitely in some situations for a client process to perform an action.
PIPE_NOWAIT	Nonblocking mode is enabled. In this mode, ReadFile, WriteFile, and ConnectNamedPipe always return immediately. Note that nonblocking mode is supported for compatibility with Microsoft LAN Manager version 2.0 and should not be used to achieve asynchronous I/O with named pipes.
nMaxInstances

Specifies the maximum number of instances that can be created for this pipe. The same number must be specified for all instances. Acceptable values are in the range 1 through PIPE_UNLIMITED_INSTANCES. If this parameter is PIPE_UNLIMITED_INSTANCES, the number of pipe instances that can be created is limited only by the availability of system resources.

nOutBufferSize

Specifies the number of bytes to reserve for the output buffer. For a discussion on sizing named pipe buffers, see the following Remarks section.

nInBufferSize

Specifies the number of bytes to reserve for the input buffer. For a discussion on sizing named pipe buffers, see the following Remarks section.

nDefaultTimeOut

Specifies the default time-out value, in milliseconds, if the WaitNamedPipe function specifies NMPWAIT_USE_DEFAULT_WAIT. Each instance of a named pipe must specify the same value.

lpSecurityAttributes

Points to a SECURITY_ATTRIBUTES structure that specifies the security attributes for the pipe. Since named pipes are implemented as a file system and that file system supports this parameter, this parameter will always have an effect when specified.

If this parameter is NULL, the pipe is created with a default security descriptor, and the resulting handle is not inherited.

Note that access to some security attributes can be granted by setting particular flags in the dwOpenMode parameter.

Return Value

If the function succeeds, the return value is a handle to the server end of a named pipe instance.

If the function fails, the return value is INVALID_HANDLE_VALUE. To get extended error information, call GetLastError. The return value is ERROR_INVALID_PARAMETER if nMaxInstances is greater than PIPE_UNLIMITED_INSTANCES.

Remarks

To create an instance of a named pipe by using CreateNamedPipe, the user must have FILE_CREATE_PIPE_INSTANCE access to the named pipe object. If a new named pipe is being created, the access control list (ACL) from the security attributes parameter defines the discretionary access control for the named pipe.

All instances of a named pipe must specify the same pipe type (byte-type or message-type), pipe access (duplex, inbound, or outbound), instance count, and time-out value. If different values are used, this function fails and GetLastError returns ERROR_ACCESS_DENIED.

The input and output buffer sizes are advisory. The actual buffer size reserved for each end of the named pipe is either the system default, the system minimum or maximum, or the specified size rounded up to the next allocation boundary.

An instance of a named pipe is always deleted when the last handle to the instance of the named pipe is closed.

See Also

ConnectNamedPipe, CreateFile, ReadFile, ReadFileEx, SECURITY_ATTRIBUTES, TransactNamedPipe, WaitNamedPipe, WriteFile, WriteFileEx


CreatePalette
 CreatePalette  QuickInfo  Overview  Group

The CreatePalette function creates a logical color palette.

HPALETTE CreatePalette(

CONST LOGPALETTE  *lplgpl	// address of logical color palette
);
Parameters

lplgpl

Points to a LOGPALETTE structure that contains information about the colors in the logical palette.

Return Value

If the function succeeds, the return value is a handle that identifies a logical palette.

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

Remarks

An application can determine whether a device supports palette operations by calling the GetDeviceCaps function and specifying the RASTERCAPS constant.

Once an application creates a logical palette, it can select that palette into a device context by calling the SelectPalette function. A palette selected into a device context can be realized by calling the RealizePalette function.

When you no longer need the palette, call the DeleteObject function to delete it.

See Also

DeleteObject, GetDeviceCaps, LOGPALETTE, RealizePalette, SelectPalette


CreatePatternBrush
 CreatePatternBrush  QuickInfo  Overview  Group

The CreatePatternBrush function creates a logical brush with the specified bitmap pattern. The bitmap cannot be a DIB section bitmap, which is created by the CreateDIBSection function.

HBRUSH CreatePatternBrush(

HBITMAP  hbmp	// handle of bitmap
);
Parameters

hbmp

Identifies the bitmap to be used to create the logical brush.

Return Value

If the function succeeds, the return value identifies a logical brush.

If the function fails, the return value is NULL.

Remarks

A pattern brush is a bitmap that Windows uses to paint the interiors of filled shapes.

After an application creates a brush by calling CreatePatternBrush, it can select that brush into any device context by calling the SelectObject function.

You can delete a pattern brush without affecting the associated bitmap by using the DeleteObject function. Therefore, you can then use this bitmap to create any number of pattern brushes.

A brush created by using a monochrome (1 bit per pixel) bitmap has the text and background colors of the device context to which it is drawn. Pixels represented by a 0 bit are drawn with the current text color; pixels represented by a 1 bit are drawn with the current background color.

The bitmap identified by hbmp cannot be a DIB section, which is a bitmap created by the CreateDIBSection function. If the bitmap is a DIB section, the CreatePatternBrush function fails.

Windows 95: Creating brushes from bitmaps or DIBs larger than 8x8 pixels is not supported. If a larger bitmap is given, only a portion of the bitmap is used.

See Also

CreateBitmap, CreateBitmapIndirect, CreateCompatibleBitmap, CreateDIBPatternBrush, CreateDIBPatternBrushPt, CreateDIBSection, CreateHatchBrush, DeleteObject, GetBrushOrgEx, LoadBitmap, SelectObject, SetBrushOrgEx


CreatePen
 CreatePen  QuickInfo  Overview  Group

The CreatePen function creates a logical pen that has the specified style, width, and color. The pen can subsequently be selected into a device context and used to draw lines and curves.

HPEN CreatePen(

int  fnPenStyle,	// pen style
int  nWidth,	// pen width
COLORREF  crColor	// pen color
);
Parameters

fnPenStyle

Specifies the pen style. It can be any one of the following values:

Style	Description
PS_SOLID	Pen is solid.
PS_DASH	Pen is dashed. This style is valid only when the pen width is one or less in device units.
PS_DOT	Pen is dotted. This style is valid only when the pen width is one or less in device units.
PS_DASHDOT	Pen has alternating dashes and dots. This style is valid only when the pen width is one or less in device units.
PS_DASHDOTDOT	Pen has alternating dashes and double dots. This style is valid only when the pen width is one or less in device units.
PS_NULL	Pen is invisible.
PS_INSIDEFRAME	Pen is solid. When this pen is used in any graphics device interface (GDI) drawing function that takes a bounding rectangle, the dimensions of the figure are shrunk so that it fits entirely in the bounding rectangle, taking into account the width of the pen. This applies only to geometric pens.
nWidth

Specifies the width of the pen, in logical units. If nWidth is zero, the pen is a single pixel wide, regardless of the current transformation.

crColor

Specifies a color reference for the pen color.

Return Value

If the function succeeds, the return value is a handle that identifies a logical pen.

If the function fails, the return value is NULL.

Remarks

After an application creates a logical pen, it can select that pen into a device context by calling the SelectObject function. After a pen is selected into a device context, it can be used to draw lines and curves.

If the value specified by the nWidth parameter is zero, a line drawn with the created pen will always be a single pixel wide regardless of the current transformation.

If the value specified by nWidth is greater than 1, the fnPenStyle parameter must be PS_NULL, PS_SOLID, or PS_INSIDEFRAME.

If the value specified by nWidth is greater than 1 and fnPenStyle is PS_INSIDEFRAME, the line associated with the pen is drawn inside the frame of all primitives except polygons and polylines.

If the value specified by nWidth is greater than 1, fnPenStyle is PS_INSIDEFRAME, and the color specified by the crColor parameter does not match one of the entries in the logical palette, Windows draws lines by using a dithered color. Dithered colors are not available with solid pens.

When you no longer need the pen, call the DeleteObject function to delete it.

See Also

CreatePenIndirect, DeleteObject, ExtCreatePen, GetObject, RGB, SelectObject


CreatePenIndirect
 CreatePenIndirect  QuickInfo  Overview  Group

The CreatePenIndirect function creates a logical cosmetic pen that has the style, width, and color specified in a structure.

HPEN CreatePenIndirect(

CONST LOGPEN *  lplgpn	// address of LOGPEN structure
);
Parameters

lplgpn

Points to the LOGPEN structure that specifies the pen's style, width, and color.

Return Value

If the function succeeds, the return value is a handle that identifies a logical cosmetic pen.

If the function fails, the return value is NULL.

Remarks

After an application creates a logical pen, it can select that pen into a device context by calling the SelectObject function. After a pen is selected into a device context, it can be used to draw lines and curves.

When you no longer need the pen, call the DeleteObject function to delete it.

See Also

CreatePen, DeleteObject, ExtCreatePen, GetObject, LOGPEN, RGB, SelectObject


CreatePipe
 CreatePipe  QuickInfo  Overview  Group

The CreatePipe function creates an anonymous pipe, and returns handles to the read and write ends of the pipe.

BOOL CreatePipe(

PHANDLE  hReadPipe,	// address of variable for read handle
PHANDLE  hWritePipe,	// address of variable for write handle
LPSECURITY_ATTRIBUTES  lpPipeAttributes,	// address of security attributes
DWORD  nSize	// number of bytes reserved for pipe
);
Parameters

hReadPipe

Points to the variable that receives the read handle for the pipe.

hWritePipe

Points to the variable that receives the write handle for the pipe.

lpPipeAttributes

Points to a SECURITY_ATTRIBUTES structure that specifies the security attributes for the pipe. The file system must support this parameter for it to have an effect.

If lpPipeAttributes is NULL, the pipe is created with a default security descriptor, and the resulting handle is not inherited.

nSize

Specifies the buffer size for the pipe. The size is only a suggestion; the system uses the value to calculate an appropriate buffering mechanism. If this parameter is zero, the system uses the default buffer size.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

CreatePipe creates the pipe, assigning the specified pipe size to the storage buffer. CreatePipe also creates handles that the process uses to read from and write to the buffer in subsequent calls to the ReadFile and WriteFile functions.

When a process uses WriteFile to write to an anonymous pipe, the write operation is not completed until all bytes are written. If the pipe buffer is full before all bytes are written, WriteFile does not return until another process or thread uses ReadFile to make more buffer space available.

See Also

ReadFile, SECURITY_ATTRIBUTES, WriteFile


CreatePolygonRgn
 CreatePolygonRgn  QuickInfo  Overview  Group

The CreatePolygonRgn function creates a polygonal region.

HRGN CreatePolygonRgn(

CONST POINT  *lppt,	// address of array of points
int  cPoints,	// number of points in array
int  fnPolyFillMode	// polygon-filling mode
);
Parameters

lppt

Points to an array of POINT structures that define the vertices of the polygon. The polygon is presumed closed. Each vertex can be specified only once.

cPoints

Specifies the number of points in the array.

fnPolyFillMode

Specifies the fill mode used to determine which pixels are in the region. This parameter can be one of the following values:

Value	Meaning
ALTERNATE	Selects alternate mode (fills area between odd-numbered and even-numbered polygon sides on each scan line).
WINDING	Selects winding mode (fills any region with a nonzero winding value).
For more information about these modes, see the SetPolyFillMode function.

Return Value

If the function succeeds, the return value is the handle of the region.

If the function fails, the return value is NULL.

See Also

CreatePolyPolygonRgn, DeleteObject, POINT, SelectObject, SetPolyFillMode


CreatePolyPolygonRgn
 CreatePolyPolygonRgn  QuickInfo  Overview  Group

The CreatePolyPolygonRgn function creates a region consisting of a series of polygons. The polygons can overlap.

HRGN CreatePolyPolygonRgn(

CONST POINT  *lppt,	// address of array of points
CONST INT  *lpPolyCounts,	// address of array that contains vertex counts
int  nCount,	// number of integers in array of vertex counts
int  fnPolyFillMode	// polygon fill mode
);
Parameters

lppt

Points to an array of POINT structures that define the vertices of the polygons. The polygons are specified consecutively. Each polygon is presumed closed and each vertex is specified only once.

lpPolyCounts

Points to an array of integers, each of which specifies the number of points in one of the polygons in the array pointed to by lppt.

nCount

Specifies the total number of integers in the array pointed to by lpPolyCounts.

fnPolyFillMode

Specifies the fill mode used to determine which pixels are in the region. This parameter can be one of the following values:

Value	Meaning
ALTERNATE	Selects alternate mode (fills area between odd-numbered and even-numbered polygon sides on each scan line).
WINDING	Selects winding mode (fills any region with a nonzero winding value).
For more information about these modes, see the SetPolyFillMode function.

Return Value

If the function succeeds, the return value is the handle of the region.

If the function fails, the return value is zero.

See Also

CreatePolygonRgn, DeleteObject, POINT, SelectObject, SetPolyFillMode


CreatePopupMenu
 CreatePopupMenu  QuickInfo  Overview  Group

The CreatePopupMenu function creates a pop-up menu. The menu is initially empty, but it can be filled with menu items by using the AppendMenu and InsertMenu functions (in Windows 95 you can also use the InsertMenuItem function to both append and insert menu items).

HMENU CreatePopupMenu(VOID)

Parameters

This function has no parameters.

Return Value

If the function succeeds, the return value is the handle of the newly created pop-up menu.

If the function fails, the return value is NULL.

Remarks

The application can add the pop-up menu to an existing menu or pop-up menu, or it can display a floating pop-up menu by calling the TrackPopupMenu function.

Resources associated with a pop-up menu that is assigned to a window are freed automatically. If the pop-up 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 only: The system can support a maximum of 16,364 menu handles.

See Also

AppendMenu, CreateMenu, DestroyMenu, InsertMenu, SetMenu, TrackPopupMenu


CreatePrivateObjectSecurity
 CreatePrivateObjectSecurity  QuickInfo  Overview  Group

The CreatePrivateObjectSecurity function allocates and initializes a self-relative security descriptor for a new protected server's object. This function is called when a new protected server object is being created.

BOOL CreatePrivateObjectSecurity(

PSECURITY_DESCRIPTOR  ParentDescriptor,	// address of parent directory SD
PSECURITY_DESCRIPTOR  CreatorDescriptor,	// address of creator SD
PSECURITY_DESCRIPTOR *  NewDescriptor,	// address of pointer to new SD
BOOL  IsDirectoryObject,	// container flag for new SD
HANDLE  Token,	// handle of client's access token
PGENERIC_MAPPING  GenericMapping	// address of access-rights structure
);
Parameters

ParentDescriptor

Points to the security descriptor for the parent directory in which a new object is being created. If there is no parent directory, this parameter can be NULL.

CreatorDescriptor

Points to a security descriptor provided by the creator of the object. If the object's creator does not explicitly pass security information for the new object, this parameter is intended to be NULL.

lppsdNew

Points to a pointer to the newly allocated security descriptor created when the function returns.

IsDirectoryObject

Specifies whether the new object is a container. A value of TRUE indicates the object contains other objects, such as a directory.

Token

Identifies the access token for the client process on whose behalf the object is being created. If this is an impersonation token, it must be at SecurityIdentification level or higher. For a full description of the SecurityIdentification impersonation level, see the SECURITY_IMPERSONATION_LEVEL enumerated type

A client token is used to retrieve default security information for the new object, such as its default owner, primary group, and discretionary access-control list. The token must be open for TOKEN_QUERY access.

GenericMapping

Points to a GENERIC_MAPPING structure that specifies the mapping from each generic right to specific rights for the object.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

If a system access-control list, or SACL, is specified in the SECURITY_DESCRIPTOR specified by CreatorDescriptor, Token must have SeSecurityPrivilege enabled, and the caller's token must have SeAuditPrivilege enabled. The CreatePrivateObjectSecurity function performs access/privilege checks to ensure this, and may generate audits during the process.

The CreatePrivateObjectSecurity function may send many messages to port objects. This can result in a significant delay before the function returns. Be sure to take this potential delay into account when designing an application that calls CreatePrivateObjectSecurity. An application that uses mutexes to lock structures, for example, usually seeks to avoid such potentially-long lockups.

See Also

DestroyPrivateObjectSecurity, GENERIC_MAPPING, GetPrivateObjectSecurity, GetTokenInformation, OpenProcessToken, SECURITY_DESCRIPTOR, SECURITY_IMPERSONATION_LEVEL, SetPrivateObjectSecurity


CreateProcess
 CreateProcess  QuickInfo  Overview  Group

The CreateProcess function creates a new process and its primary thread. The new process executes the specified executable file.

BOOL CreateProcess(

LPCTSTR  lpApplicationName,	// pointer to name of executable module
LPTSTR  lpCommandLine,	// pointer to command line string
LPSECURITY_ATTRIBUTES  lpProcessAttributes,	// pointer to process security attributes
LPSECURITY_ATTRIBUTES  lpThreadAttributes,	// pointer to thread security attributes
BOOL  bInheritHandles,	// handle inheritance flag
DWORD  dwCreationFlags,	// creation flags
LPVOID  lpEnvironment,	// pointer to new environment block
LPCTSTR  lpCurrentDirectory,	// pointer to current directory name
LPSTARTUPINFO  lpStartupInfo,	// pointer to STARTUPINFO
LPPROCESS_INFORMATION  lpProcessInformation	// pointer to PROCESS_INFORMATION
);
Parameters

lpApplicationName

Pointer to a null-terminated string that specifies the module to execute.

The string can specify the full path and filename of the module to execute.

The string can specify a partial name. In that case, the function uses the current drive and current directory to complete the specification.

The lpApplicationName parameter can be NULL. In that case, the module name must be the first white space-delimited token in the lpCommandLine string.

The specified module can be a Win32-based application. It can be some other type of module (for example, MS-DOS or OS/2) if the appropriate subsystem is available on the local computer.

Windows NT : If the executable module is a 16-bit application, lpApplicationName should be NULL, and the string pointed to by lpCommandLine should specify the executable module. A 16-bit application is one that executes as a VDM or WOW process.

lpCommandLine

Pointer to a null-terminated string that specifies the command line to execute.

The lpCommandLine parameter can be NULL. In that case, the function uses the string pointed to by lpApplicationName as the command line.

If both lpApplicationName and lpCommandLine are non-NULL, *lpApplicationName specifies the module to execute, and *lpCommandLine specifies the command line. The new process can use GetCommandLine to retrieve the entire command line. C runtime processes can use the argc and argv arguments.

If lpApplicationName is NULL, the first white space-delimited token of the command line specifies the module name. If the filename does not contain an extension, .EXE is assumed. If the filename ends in a period (.) with no extension, or the filename contains a path, .EXE is not appended. If the filename does not contain a directory path, Windows searches for the executable file in the following sequence:

1.	The directory from which the application loaded.

2.	The current directory for the parent process.

3.	Windows 95: The Windows system directory. Use the GetSystemDirectory function to get the path of this directory.

Windows NT: The 32-bit Windows system directory. Use the GetSystemDirectory function to get the path of this directory. The name of this directory is SYSTEM32.

4.	Windows NT only: The 16-bit Windows system directory. There is no Win32 function that obtains the path of this directory, but it is searched. The name of this directory is SYSTEM.

5.	The Windows directory. Use the GetWindowsDirectory function to get the path of this directory.

6.	The directories that are listed in the PATH environment variable.

If the process to be created is an MS-DOS - based or Windows-based application, lpCommandLine should be a full command line in which the first element is the application name. Because this also works well for Win32-based applications, it is the most robust way to set lpCommandLine.

lpProcessAttributes

Points to a SECURITY_ATTRIBUTES structure that specifies the security attributes for the created process.

If lpProcessAttributes is NULL, the process is created with a default security descriptor, and the resulting handle is not inherited.

lpThreadAttributes

Points to a SECURITY_ATTRIBUTES structure that specifies the security attributes for the primary thread of the new process. If lpThreadAttributes is NULL, the process is created with a default security descriptor, and the resulting handle is not inherited.

bInheritHandles

Indicates whether the new process inherits handles from the calling process. If TRUE, each inheritable open handle in the calling process is inherited by the new process. Inherited handles have the same value and access privileges as the original handles.

dwCreationFlags

Specifies additional flags that control the priority class and the creation of the process. The following creation flags can be specified in any combination, except as noted:

Value	Meaning
CREATE_DEFAULT_ERROR_MODE
	The new process does not inherit the error mode of the calling process. Instead, CreateProcess gives the new process the current default error mode. An application sets the current default error mode by calling SetErrorMode. This flag is particularly useful for multi-threaded shell applications that run with hard errors disabled.  The default behavior for CreateProcess is for the new process to inherit the error mode of the caller. Setting this flag changes that default behavior.
CREATE_NEW_CONSOLE
	The new process has a new console, instead of inheriting the parent's console. This flag cannot be used with the DETACHED_PROCESS flag.
CREATE_NEW_PROCESS_GROUP
	The new process is the root process of a new process group. The process group includes all processes that are descendants of this root process. The process ID of the new process group is the same as the process ID, which is returned in the lpProcessInformation parameter. Process groups are used by the GenerateConsoleCtrlEvent function to enable sending a CTRL+C or CTRL+BREAK signal to a group of console processes.
CREATE_SEPARATE_WOW_VDM
	This flag is only valid only launching a 16-bit Windows program.  If set, the new process is run in a private Virtual DOS Machine (VDM).  By default, all 16-bit Windows programs are run in a single, shared VDM.  The advantage of running separately is that a crash only kills the single VDM; any other programs running in distinct VDMs continue to function normally.  Also, 16-bit Windows applications which are run in separate VDMs have separate input queues. That means that if one application hangs momentarily, applications in separate VDMs continue to receive input.
CREATE_SHARED_WOW_VDM
	Windows NT: The flag is valid only when launching a 16-bit Windows program. If the DefaultSeparateVDM switch in the Windows section of WIN.INI is TRUE, this flag causes the CreateProcess function to override the switch and run the new process in the shared Virtual DOS Machine.
CREATE_SUSPENDED
	The primary thread of the new process is created in a suspended state, and does not run until the ResumeThread function is called.
CREATE_UNICODE_ENVIRONMENT
	If set, the environment block pointed to by lpEnvironment uses Unicode characters. If clear, the environment block uses ANSI characters.
DEBUG_PROCESS
	If this flag is set, the calling process is treated as a debugger, and the new process is a process being debugged. The system notifies the debugger of all debug events that occur in the process being debugged. If you create a process with this flag set, only the calling thread (the thread that called CreateProcess) can call the WaitForDebugEvent function.
DEBUG_ONLY_THIS_PROCESS
	If not set and the calling process is being debugged, the new process becomes another process being debugged by the calling process's debugger. If the calling process is not a process being debugged, no debugging-related actions occur.
DETACHED_PROCESS
	For console processes, the new process does not have access to the console of the parent process. The new process can call the AllocConsole function at a later time to create a new console. This flag cannot be used with the CREATE_NEW_CONSOLE flag.
The dwCreationFlags parameter also controls the new process's priority class, which is used in determining the scheduling priorities of the process's threads. If none of the following priority class flags is specified, the priority class defaults to NORMAL_PRIORITY_CLASS unless the priority class of the creating process is IDLE_PRIORITY_CLASS. In this case the default priority class of the child process is IDLE_PRIORITY_CLASS. One of the following flags can be specified:

Priority	Meaning
HIGH_PRIORITY_CLASS	Indicates a process that performs time-critical tasks that must be executed immediately for it to run correctly. The threads of a high-priority class process preempt the threads of normal-priority or idle-priority class processes. An example is Windows Task List, which must respond quickly when called by the user, regardless of the load on the operating system. Use extreme care when using the high-priority class, because a high-priority class CPU-bound application can use nearly all available cycles.
IDLE_PRIORITY_CLASS	Indicates a process whose threads run only when the system is idle and are preempted by the threads of any process running in a higher priority class. An example is a screen saver. The idle priority class is inherited by child processes.
NORMAL_PRIORITY_CLASS	Indicates a normal process with no special scheduling needs.
REALTIME_PRIORITY_CLASS	Indicates a process that has the highest possible priority. The threads of a real-time priority class process preempt the threads of all other processes, including operating system processes performing important tasks. For example, a real-time process that executes for more than a very brief interval can cause disk caches not to flush or cause the mouse to be unresponsive.
lpEnvironment

Points to an environment block for the new process. If this parameter is NULL, the new process uses the environment of the calling process.

An environment block consists of a null-terminated block of null-terminated strings. Each string is in the form:

name=value

Because the equal sign is used as a separator, it must not be used in the name of an environment variable.

If an application provides an environment block, rather than passing NULL for this parameter, the current directory information of the system drives is not automatically propagated to the new process. For a discussion of this situation and how to handle it, see the following Remarks section.

An environment block can contain Unicode or ANSI characters. If the environment block pointed to by lpEnvironment contains Unicode characters, the dwCreationFlags field's CREATE_UNICODE_ENVIRONMENT flag will be set. If the block contains ANSI characters, that flag will be clear.

Note that an ANSI environment block is terminated by two zero bytes: one for the last string, one more to terminate the block. A Unicode environment block is terminated by four zero bytes: two for the last string, two more to terminate the block.

lpCurrentDirectory

Points to a null-terminated string that specifies the current drive and directory for the child process. The string must be a full path and filename that includes a drive letter. If this parameter is NULL, the new process is created with the same current drive and directory as the calling process. This option is provided primarily for shells that need to start an application and specify its initial drive and working directory.

lpStartupInfo

Points to a STARTUPINFO structure that specifies how the main window for the new process should appear.

lpProcessInformation

Points to a PROCESS_INFORMATION structure that receives identification information about the new process.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The CreateProcess function is used to run a new program. The WinExec and LoadModule functions are still available, but they are implemented as calls to CreateProcess.

In addition to creating a process, CreateProcess also creates a thread object. The thread is created with an initial stack whose size is described in the image header of the specified program's executable file. The thread begins execution at the image's entry point.

The new process and the new thread handles are created with full access rights. For either handle, if a security descriptor is not provided, the handle can be used in any function that requires an object handle of that type. When a security descriptor is provided, an access check is performed on all subsequent uses of the handle before access is granted. If the access check denies access, the requesting process is not able to use the handle to gain access to the thread.

The process is assigned a 32-bit process identifier. The ID is valid until the process terminates. It can be used to identify the process, or specified in the OpenProcess function to open a handle to the process. The initial thread in the process is also assigned a 32-bit thread identifier. The ID is valid until the thread terminates and can be used to uniquely identify the thread within the system. These identifiers are returned in the PROCESS_INFORMATION structure.

When specifying an application name in the lpApplicationName or lpCommandLine strings, it doesn't matter whether the application name includes the filename extension, with one exception: an MS-DOS − based or Windows-based application whose filename extension is .COM must include the .COM extension.

The calling thread can use the WaitForInputIdle function to wait until the new process has finished its initialization and is waiting for user input with no input pending. This can be useful for synchronization between parent and child processes, because CreateProcess returns without waiting for the new process to finish its initialization. For example, the creating process would use WaitForInputIdle before trying to find a window associated with the new process.

The preferred way to shut down a process is by using the ExitProcess function, because this function notifies all dynamic-link libraries (DLLs) attached to the process of the approaching termination. Other means of shutting down a process do not notify the attached DLLs. Note that when a thread calls ExitProcess, other threads of the process are terminated without an opportunity to execute any additional code (including the thread termination code of attached DLLs).

ExitProcess, ExitThread, CreateThread, CreateRemoteThread, and a process that is starting (as the result of a call by CreateProcess) are serialized between each other within a process. Only one of these events can happen in an address space at a time. This means the following restrictions hold:

•	During process startup and DLL initialization routines, new threads can be created, but they do not begin execution until DLL initialization is done for the process.

•	Only one thread in a process can be in a DLL initialization or detach routine at a time.

•	The ExitProcess function does not return until no threads are in their DLL initialization or detach routines.

The created process remains in the system until all threads within the process have terminated and all handles to the process and any of its threads have been closed through calls to CloseHandle. The handles for both the process and the main thread must be closed through calls to CloseHandle. If these handles are not needed, it is best to close them immediately after the process is created.

When the last thread in a process terminates, the following events occur:

•	All objects opened by the process are implicitly closed.

•	The process's termination status (which is returned by GetExitCodeProcess) changes from its initial value of STILL_ACTIVE to the termination status of the last thread to terminate.

•	The thread object of the main thread is set to the signaled state, satisfying any threads that were waiting on the object.

•	The process object is set to the signaled state, satisfying any threads that were waiting on the object.

If the current directory on drive C is \MSVC\MFC, there is an environment variable called =C: whose value is C:\MSVC\MFC. As noted in the previous description of lpEnvironment, such current directory information for a system's drives does not automatically propagate to a new process when the CreateProcess function's lpEnvironment parameter is non-NULL. An application must manually pass the current directory information to the new process. To do so, the application must explicitly create the =X environment variable strings, get them into alphabetical order (because Windows NT and Windows 95 use a sorted environment), and then put them into the environment block specified by lpEnvironment. Typically, they will go at the front of the environment block, due to the previously mentioned environment block sorting.

One way to obtain the current directory variable for a drive X is to call GetFullPathName("X:",. .). That avoids an application having to scan the environment block. If the full path returned is X:\, there is no need to pass that value on as environment data, since the root directory is the default current directory for drive X of a new process.

The handle returned by the CreateProcess function has PROCESS_ALL_ACCESS access to the process object.

When a process is created with CREATE_NEW_PROCESS_GROUP specified, an implicit call to SetConsoleCtrlHandler(NULL,TRUE) is made on behalf of the new process; this means that the new process has CTRL-C disabled. This lets good shells handle CTRL-C themselves, and selectively pass that signal on to sub-processes. CTRL-BREAK is not disabled, and may be used to interrupt the process/process group.

The current directory specified by the lpcurrentDirectory parameter is the current directory for the child process. The current directory specified in item 2 under the lpCommandLine parameter is the current directory for the parent process.

See Also

AllocConsole, CloseHandle, CreateRemoteThread, CreateThread, ExitProcess, ExitThread, GenerateConsoleCtrlEvent, GetCommandLine, GetEnvironmentStrings, GetExitCodeProcess, GetFullPathName, GetStartupInfo, GetSystemDirectory, GetWindowsDirectory, LoadModule, OpenProcess, PROCESS_INFORMATION, ResumeThread, SECURITY_ATTRIBUTES, SetConsoleCtrlHandler, SetErrorMode, STARTUPINFO, TerminateProcess, WaitForInputIdle, WaitForDebugEvent, WinExec


CreateProcessAsUser [New - Windows NT]
 CreateProcessAsUser  QuickInfo

[New - Windows NT]

The CreateProcessAsUser function creates a new process and its primary thread. The new process then executes a specified executable file. The CreateProcessAsUser function behaves just like the CreateProcess function, with one important difference: the created process runs in a context in which the system sees the user represented by the hToken parameter as if that user had logged on to the system and then called the CreateProcess function.

BOOL CreateProcessAsUser(

HANDLE hToken	// handle to a token that represents a logged-on user
LPCTSTR  lpApplicationName,	// pointer to name of executable module
LPTSTR  lpCommandLine,	// pointer to command line string
LPSECURITY_ATTRIBUTES  lpProcessAttributes,	// pointer to process security attributes
LPSECURITY_ATTRIBUTES  lpThreadAttributes,	// pointer to thread security attributes
BOOL  bInheritHandles,	// new process inherits handles
DWORD  dwCreationFlags,	// creation flags
LPVOID  lpEnvironment,	// pointer to new environment block
LPCTSTR  lpCurrentDirectory,	// pointer to current directory name
LPSTARTUPINFO  lpStartupInfo,	// pointer to STARTUPINFO
LPPROCESS_INFORMATION  lpProcessInformation	// pointer to PROCESS_INFORMATION
);
Parameters

hToken

Handle to a token that represents a user. You obtain such a token by calling the LogonUser function. The user represented by the token must have read and execute access to the application specified by the lpApplicationName or the lpCommandLine parameter.

The other parameters of the CreateProcessAsUser function behave just like the analogous parameters of the CreateProcess function.

lpApplicationName

Points to a null-terminated string specifying the full path and filename of the module to execute. If a partial name is specified, the current drive and current directory are used by default. If this parameter is NULL, the module name must be the first white space-delimited token in the lpCommandLine string. The specified module can be a Win32-based application, or it can be some other type of module (for example, MS-DOS or OS/2) if the appropriate subsystem is available on the local computer.

lpCommandLine

Points to a null-terminated string specifying the command line for the application to be executed. If this parameter is NULL, the lpApplicationName string is used as the command line. If both lpApplicationName and lpCommandLine are non-NULL, lpApplicationName specifies the module to execute and lpCommandLine is used as the command line. The new process can use GetCommandLine to retrieve the entire command line; or C runtime processes can use the argc/argv mechanism.

If lpApplicationName is NULL, the first white space-delimited token of the command line specifies the module name. If the filename does not contain an extension, .EXE is assumed. If the filename ends in a period (.) with no extension, or the filename contains a path, .EXE is not appended. If the filename does not contain a directory path, Windows searches for the executable file in the following sequence:

1.	The directory from which the application loaded.

2.	The current directory.

3.	Windows 95: The Windows system directory. Use the GetSystemDirectory function to get the path of this directory.

Windows NT: The 32-bit Windows system directory. Use the GetSystemDirectory function to get the path of this directory. The name of this directory is SYSTEM32.

4.	Windows NT only: The 16-bit Windows system directory. There is no Win32 function that obtains the path of this directory, but it is searched. The name of this directory is SYSTEM.

5.	The Windows directory. Use the GetWindowsDirectory function to get the path of this directory.

6.	The directories that are listed in the PATH environment variable.

If the process to be created is an MS-DOS − based or Windows-based application, lpCommandLine should be a full command line in which the first element is the application name. Because this also works well for Win32-based applications, it is the most robust way to set lpCommandLine.

lpProcessAttributes

Points to a SECURITY_ATTRIBUTES structure that specifies the security attributes for the created process.

If lpProcessAttributes is NULL, the process is created with a default security descriptor, and the resulting handle is not inherited.

lpThreadAttributes

Points to a SECURITY_ATTRIBUTES structure that specifies the security attributes for the primary thread of the new process. If lpThreadAttributes is NULL, the process is created with a default security descriptor, and the resulting handle is not inherited.

bInheritHandles

Indicates whether the new process inherits handles from the calling process. If TRUE, each inheritable open handle in the calling process is inherited by the new process. Inherited handles have the same value and access privileges as the original handles.

dwCreationFlags

Specifies additional flags that control the priority class and the creation of the process. The following creation flags can be specified in any combination, except as noted:

Value	Meaning
CREATE_DEFAULT_ERROR_MODE
	The new process does not inherit the error mode of the calling process. Instead, CreateProcessAsUser gives the new process the current default error mode. An application sets the current default error mode by calling SetErrorMode. This flag is particularly useful for multi-threaded shell applications that run with hard errors disabled.  The default behavior for CreateProcessAsUser is for the new process to inherit the error mode of the caller. Setting this flag changes that default behavior.
CREATE_NEW_CONSOLE
	The new process has a new console, instead of inheriting the parent's console. This flag cannot be used with the DETACHED_PROCESS flag.
CREATE_NEW_PROCESS_GROUP
	The new process is the root process of a new process group. The process group includes all processes that are descendants of this root process. The process ID of the new process group is the same as the process ID, which is returned in the lpProcessInformation parameter. Process groups are used by the GenerateConsoleCtrlEvent function to enable sending a CTRL+C or CTRL+BREAK signal to a group of console processes.
CREATE_SEPARATE_WOW_VDM
	This flag is only valid only launching a 16-bit Windows program.  If set, the new process is run in a private Virtual DOS Machine (VDM).  By default, all 16-bit Windows programs are run in a single, shared VDM.  The advantage of running separately is that a crash only kills the single VDM; any other programs running in distinct VDMs continue to function normally.  Also, 16-bit Windows applications which are run in separate VDMs have separate input queues. That means that if one application hangs momentarily, applications in separate VDMs continue to receive input.
CREATE_SUSPENDED
	The primary thread of the new process is created in a suspended state, and does not run until the ResumeThread function is called.
CREATE_UNICODE_ENVIRONMENT
	If set, the environment block pointed to by lpEnvironment uses Unicode characters. If clear, the environment block uses ANSI characters.
DEBUG_PROCESS
	If set, the calling process is treated as a debugger, and the new process is a process being debugged. The system notifies the debugger of all debug events that occur in the process being debugged.
DEBUG_ONLY_THIS_PROCESS
	If not set and the calling process is being debugged, the new process becomes another process being debugged by the calling process's debugger. If the calling process is not a process being debugged, no debugging-related actions occur.
DETACHED_PROCESS
	For console processes, the new process does not have access to the console of the parent process. The new process can call the AllocConsole function at a later time to create a new console. This flag cannot be used with the CREATE_NEW_CONSOLE flag.
The dwCreationFlags parameter also controls the new process's priority class, which is used in determining the scheduling priorities of the process's threads. If none of the following priority class flags is specified, the priority class defaults to NORMAL_PRIORITY_CLASS unless the priority class of the creating process is IDLE_PRIORITY_CLASS. In this case the default priority class of the child process is IDLE_PRIORITY_CLASS. One of the following flags can be specified:

Priority	Meaning
HIGH_PRIORITY_CLASS	Indicates a process that performs time-critical tasks that must be executed immediately for it to run correctly. The threads of a high-priority class process preempt the threads of normal-priority or idle-priority class processes. An example is Windows Task List, which must respond quickly when called by the user, regardless of the load on the operating system. Use extreme care when using the high-priority class, because a high-priority class CPU-bound application can use nearly all available cycles.
IDLE_PRIORITY_CLASS	Indicates a process whose threads run only when the system is idle and are preempted by the threads of any process running in a higher priority class. An example is a screen saver. The idle priority class is inherited by child processes.
NORMAL_PRIORITY_CLASS	Indicates a normal process with no special scheduling needs.
REALTIME_PRIORITY_CLASS	Indicates a process that has the highest possible priority. The threads of a real-time priority class process preempt the threads of all other processes, including operating system processes performing important tasks. For example, a real-time process that executes for more than a very brief interval can cause disk caches not to flush or cause the mouse to be unresponsive.
lpEnvironment

Points to an environment block for the new process. If this parameter is NULL, the new process uses the environment of the calling process.

An environment block consists of a null-terminated block of null-terminated strings. Each string is in the form:

name=value

Because the equal sign is used as a separator, it must not be used in the name of an environment variable.

If an application provides an environment block, rather than passing NULL for this parameter, the current directory information of the system drives is not automatically propagated to the new process. For a discussion of this situation and how to handle it, see the following Remarks section.

An environment block can contain Unicode or ANSI characters. If the environment block pointed to by lpEnvironment contains Unicode characters, the dwCreationFlags field's CREATE_UNICODE_ENVIRONMENT flag will be set. If the block contains ANSI characters, that flag will be clear.

Note that an ANSI environment block is terminated by two zero bytes: one for the last string, one more to terminate the block. A Unicode environment block is terminated by four zero bytes: two for the last string, two more to terminate the block.

lpCurrentDirectory

Points to a null-terminated string that specifies the current drive and directory for the new process. The string must be a full path and filename that includes a drive letter. If this parameter is NULL, the new process is created with the same current drive and directory as the calling process. This option is provided primarily for shells that need to start an application and specify its initial drive and working directory.

lpStartupInfo

Points to a STARTUPINFO structure that specifies how the main window for the new process should appear.

lpProcessInformation

Points to a PROCESS_INFORMATION structure that receives identification information about the new process.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

This function requires the SeAssignPrimary and SeIncreaseQuota privileges. If they are not already enabled, CreateProcessAsUser will enable them for the duration of the call.

The process created will not run on the application desktop. Rather, Windows will create a separate desktop on which it can run. This desktop can never be made visible so any interactive operations will never get a response. This function should be used for processes that do not require a GUI.

In addition to creating a process, CreateProcessAsUser also creates a thread object. The thread is created with an initial stack whose size is described in the image header of the specified program's executable file. The thread begins execution at the image's entry point.

The new process and the new thread handles are created with full access rights. For either handle, if a security descriptor is not provided, the handle can be used in any function that requires an object handle of that type. When a security descriptor is provided, an access check is performed on all subsequent uses of the handle before access is granted. If the access check denies access, the requesting process is not able to use the handle to gain access to the thread.

If the lpProcessAttributes parameter is NULL, the default security descriptor for the user referenced in the hToken parameter will be used. This security descriptor may not allow access for the caller, in which case the process may not be opened again once it is run. The handle returned in the PROCESS_INFORMATION is valid and will continue to have all access. This is also true for thread attributes.

The process is assigned a 32-bit process identifier. The ID is valid until the process terminates. It can be used to identify the process, or specified in the OpenProcess function to open a handle to the process. The initial thread in the process is also assigned a 32-bit thread identifier. The ID is valid until the thread terminates and can be used to uniquely identify the thread within the system. These identifiers are returned in the PROCESS_INFORMATION structure.

When specifying an application name in the lpApplicationName or lpCommandLine strings, it doesn't matter whether the application name includes the filename extension, with one exception: an MS-DOS − based or Windows-based application whose filename extension is .COM must include the .COM extension.

The calling thread can use the WaitForInputIdle function to wait until the new process has finished its initialization and is waiting for user input with no input pending. This can be useful for synchronization between parent and child processes, because CreateProcessAsUser returns without waiting for the new process to finish its initialization. For example, the creating process would use WaitForInputIdle before trying to find a window associated with the new process.

The preferred way to shut down a process is by using the ExitProcess function, because this function notifies all dynamic-link libraries (DLLs) attached to the process of the approaching termination. Other means of shutting down a process do not notify the attached DLLs. Note that when a thread calls ExitProcess, other threads of the process are terminated without an opportunity to execute any additional code (including the thread termination code of attached DLLs).

ExitProcess, ExitThread, CreateThread, CreateRemoteThread, and a process that is starting (as the result of a call by CreateProcessAsUser) are serialized between each other within a process. Only one of these events can happen in an address space at a time. This means the following restrictions hold:

•	During process startup and DLL initialization routines, new threads can be created, but they do not begin execution until DLL initialization is done for the process.

•	Only one thread in a process can be in a DLL initialization or detach routine at a time.

•	The ExitProcess function does not return until no threads are in their DLL initialization or detach routines.

The created process remains in the system until all threads within the process have terminated and all handles to the process and any of its threads have been closed through calls to CloseHandle. The handles for both the process and the main thread must be closed through calls to CloseHandle. If these handles are not needed, it is best to close them immediately after the process is created.

When the last thread in a process terminates, the following events occur:

•	All objects opened by the process are implicitly closed.

•	The process's termination status (which is returned by GetExitCodeProcess) changes from its initial value of STILL_ACTIVE to the termination status of the last thread to terminate.

•	The thread object of the main thread is set to the signaled state, satisfying any threads that were waiting on the object.

•	The process object is set to the signaled state, satisfying any threads that were waiting on the object.

If the current directory on drive C is \MSVC\MFC, there is an environment variable called =C: whose value is C:\MSVC\MFC. As noted in the previous description of lpEnvironment, such current directory information for a system's drives does not automatically propagate to a new process when the CreateProcessAsUser function's lpEnvironment parameter is non-NULL. An application must manually pass the current directory information to the new process. To do so, the application must explicitly create the =X environment variable strings, get them into alphabetical order (because Windows NT uses a sorted environment), and then put them into the environment block specified by lpEnvironment. Typically, they will go at the front of the environment block, due to the previously mentioned Windows NT environment block sorting.

One way to obtain the current directory variable for a drive X is to call GetFullPathName("X:",. .). That avoids an application having to scan the environment block. If the full path returned is X:\, there is no need to pass that value on as environment data, since the root directory is the default current directory for drive X of a new process.

The handle returned by the CreateProcessAsUser function has PROCESS_ALL_ACCESS access to the process object.

When a process is created with CREATE_NEW_PROCESS_GROUP specified, an implicit call to SetConsoleCtrlHandler(NULL,TRUE) is made on behalf of the new process; this means that the new process has CTRL-C disabled. This lets good shells handle CTRL-C themselves, and selectively pass that signal on to sub-processes. CTRL-BREAK is not disabled, and may be used to interrupt the process/process group.

See Also

AllocConsole, CloseHandle, CreateProcess, CreateRemoteThread, CreateThread, ExitProcess, ExitThread, GenerateConsoleCtrlEvent, GetCommandLine, GetEnvironmentStrings, GetExitCodeProcess, GetFullPathName, GetStartupInfo, GetSystemDirectory, GetWindowsDirectory, ImpersonateLoggedOnUser, LoadModule, LogonUser, OpenProcess, PROCESS_INFORMATION, ResumeThread, SECURITY_ATTRIBUTES, SetConsoleCtrlHandler, SetErrorMode, STARTUPINFO, TerminateProcess, WaitForInputIdle, WinExec


CreatePropertySheetPage [New - Windows NT]
 CreatePropertySheetPage  QuickInfo  Overview  Group

[New - Windows NT]

The CreatePropertySheetPage function creates a new page for a property sheet.

HPROPSHEETPAGE CreatePropertySheetPage(

LPCPROPSHEETPAGE  lppsp
);
Parameters

lppsp

Pointer to a PROPSHEETPAGE structure that defines a page to be included in a property sheet.

Return Value

If the function succeeds, the return value is the handle to the new property sheet.

If the function fails, the return value is NULL.

Remarks

An application uses the PropertySheet function to create a property sheet that includes the new page or uses the PSM_ADDPAGE message to add the new page to an existing property sheet.

Windows 95 only: The system can support a maximum of 16,364 window handles.

PropertySheet, PROPSHEETPAGE, PSM_ADDPAGE


CreateRectRgn
 CreateRectRgn  QuickInfo  Overview  Group

The CreateRectRgn function creates a rectangular region.

HRGN CreateRectRgn(

int  nLeftRect,	// x-coordinate of region's upper-left corner
int  nTopRect,	// y-coordinate of region's upper-left corner
int  nRightRect,	// x-coordinate of region's lower-right corner
int  nBottomRect	// y-coordinate of region's lower-right corner
);
Parameters

nLeftRect

Specifies the x-coordinate of the upper-left corner of the region.

nTopRect

Specifies the y-coordinate of the upper-left corner of the region.

nRightRect

Specifies the x-coordinate of the lower-right corner of the region.

nBottomRect

Specifies the y-coordinate of the lower-right corner of the region.

Return Value

If the function succeeds, the return value is the handle of the region.

If the function fails, the return value is NULL.

Remarks

The region will be exclusive of the bottom and right edges.

See Also

CreateRectRgnIndirect, CreateRoundRectRgn, DeleteObject, SelectObject


CreateRectRgnIndirect
 CreateRectRgnIndirect  QuickInfo  Overview  Group

The CreateRectRgnIndirect function creates a rectangular region.

HRGN CreateRectRgnIndirect(

CONST RECT  *lprc	// address of the rectangle
);
Parameters

lprc

Points to a RECT structure that contains the coordinates of the upper-left and lower-right corners of the rectangle that defines the region.

Return Value

If the function succeeds, the return value is the handle of the region.

If the function fails, the return value is NULL.

Remarks

The region will be exclusive of the bottom and right edges.

See Also

CreateRectRgn, CreateRoundRectRgn, DeleteObject, RECT, SelectObject


CreateRemoteThread
 CreateRemoteThread  QuickInfo  Overview  Group

The CreateRemoteThread function creates a thread that runs in the address space of another process.

HANDLE CreateRemoteThread(

HANDLE  hProcess,	// handle to process to create thread in
LPSECURITY_ATTRIBUTES  lpThreadAttributes,	// address of thread security attributes
DWORD  dwStackSize,	// initial thread stack size, in bytes
LPTHREAD_START_ROUTINE  lpStartAddress,	// address of thread function
LPVOID  lpParameter,	// address of argument for new thread
DWORD  dwCreationFlags,	// creation flags
LPDWORD  lpThreadId	// address of returned thread identifier
);
Parameters

hProcess

Identifies the process in which the thread is to be created. The handle must have PROCESS_CREATE_THREAD access.

lpThreadAttributes

Points to a SECURITY_ATTRIBUTES structure that specifies the security attributes for the thread.

If lpThreadAttributes is NULL, the thread is created with a default security descriptor, and the resulting handle is not inherited.

dwStackSize

Specifies the size, in bytes, of the stack for the new thread. If this value is zero, the stack size defaults to the same size as that of the primary thread of the process. The stack is allocated automatically in the memory space of the process and is freed when the thread terminates. Note that the stack size grows as necessary.

lpStartAddress

Points to the starting address of the new thread. The address is logically a procedure that never returns and that accepts a single 32-bit pointer as an argument.

lpParameter

Points to a single 32-bit value passed to the thread.

dwCreationFlags

Specifies additional flags that control the creation of the thread. If the CREATE_SUSPENDED flag is specified, the thread is created in a suspended state and will not run until the ResumeThread function is called. If this value is zero, the thread runs immediately after creation.

lpThreadId

Points to a 32-bit variable that receives the thread identifier.

Return Value

If the function succeeds, the return value is a handle to the new thread.

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

Remarks

CreateRemoteThread causes a new thread of execution to begin in the address space of the specified process. The thread has access to all objects opened by the process.

The new thread handle is created with full access to the new thread. If a security descriptor is not provided, the handle may be used in any function that requires a thread object handle. When a security descriptor is provided, an access check is performed on all subsequent uses of the handle before access is granted. If the access check denies access, the requesting process cannot use the handle to gain access to the thread.

The thread execution begins at the function specified by the lpStartAddress parameter. If this function returns, the results are unspecified.

CreateRemoteThread may succeed even if lpStartAddress points to data, code, or is not accessible. If the start address is invalid when the thread runs, an exception occurs, and the thread terminates. Thread termination due to a invalid start address is handled as an error exit for the thread's process. This behavior is similar to the asynchronous nature of CreateProcess, where the process is created even if it refers to invalid or missing dynamic-link libraries (DLLs).

The thread is created with a thread priority of THREAD_PRIORITY_NORMAL. Use the GetThreadPriority and SetThreadPriority functions to get and set the priority value of a thread.

When a thread terminates, the thread object attains a signaled state, satisfying any threads that were waiting for the object.

The thread object remains in the system until the thread has terminated and all handles to it have been closed through a call to CloseHandle.

The ExitProcess, ExitThread, CreateThread, CreateRemoteThread functions, and a process that is starting (as the result of a CreateProcess call) are serialized between each other within a process. Only one of these events can happen in an address space at a time. This means the following restrictions hold:

•	During process startup and DLL initialization routines, new threads can be created, but they do not begin execution until DLL initialization is done for the process.

•	Only one thread in a process can be in a DLL initialization or detach routine at a time.

•	ExitProcess does not return until no threads are in their DLL initialization or detach routines.

See Also

CloseHandle, CreateProcess, CreateThread, ExitProcess, ExitThread, GetThreadPriority, ResumeThread, SECURITY_ATTRIBUTES, SetThreadPriority


CreateRoundRectRgn
 CreateRoundRectRgn  QuickInfo  Overview  Group

The CreateRoundRectRgn function creates a rectangular region with rounded corners.

HRGN CreateRoundRectRgn(

int  nLeftRect,	// x-coordinate of the region's  upper-left corner
int  nTopRect,	// y-coordinate of the region's upper-left corner
int  nRightRect,	// x-coordinate of the region's lower-right corner
int  nBottomRect,	// y-coordinate of the region's lower-right corner
int  nWidthEllipse,	// height of ellipse for rounded corners
int  nHeightEllipse	// width of ellipse for rounded corners
);
Parameters

nLeftRect

Specifies the x-coordinate of the upper-left corner of the region.

nTopRect

Specifies the y-coordinate of the upper-left corner of the region.

nRightRect

Specifies the x-coordinate of the lower-right corner of the region.

nBottomRect

Specifies the y-coordinate of the lower-right corner of the region.

nWidthEllipse

Specifies the width of the ellipse used to create the rounded corners.

nHeightEllipse

Specifies the height of the ellipse used to create the rounded corners.

Return Value

If the function succeeds, the return value is the handle of the region.

If the function fails, the return value is NULL.

See Also

CreateRectRgn, CreateRectRgnIndirect, DeleteObject, SelectObject


CreateScalableFontResource
 CreateScalableFontResource  QuickInfo  Overview  Group

The CreateScalableFontResource function creates a font resource file for a scalable font.

BOOL CreateScalableFontResource(

DWORD  fdwHidden,	// flag for read-only embedded font
LPCTSTR  lpszFontRes,	// address of filename for font resource
LPCTSTR  lpszFontFile,	// address of filename for scalable font
LPCTSTR  lpszCurrentPath	// address of path to font file
);
Parameters

fdwHidden

Specifies whether the font is a read-only embedded font. This parameter can be one of the following values:

Value	Meaning
0	The font has read-write permission.
1	The font has read-only permission and should be hidden from other applications in the system. When this flag is set, the font is not enumerated by the EnumFonts or EnumFontFamilies function.
lpszFontRes

Points to a null-terminated string specifying the name of the font resource file that this function creates.

lpszFontFile

Points to a null-terminated string specifying the name of the scalable font file that this function uses to create the font resource file.

lpszCurrentPath

Points to a null-terminated string specifying the path to the scalable font file.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The CreateScalableFontResource function is used by applications that install TrueType fonts. An application uses the CreateScalableFontResource function to create a font resource file (typically with a .FOT filename extension) and then uses the AddFontResource function to install the font. The TrueType font file (typically with a .TTF filename extension) must be in the SYSTEM subdirectory of the WINDOWS directory to be used by the AddFontResource function.

The CreateScalableFontResource function currently supports only TrueType-technology scalable fonts.

When the lpszFontFile parameter specifies only a filename and extension, the lpszCurrentPath parameter must specify a path. When the lpszFontFile parameter specifies a full path, the lpszCurrentPath parameter must be NULL or a pointer to NULL.

When only a filename and extension are specified in the lpszFontFile parameter and a path is specified in the lpszCurrentPath parameter, the string in lpszFontFile is copied into the .FOT file as the .TTF file that belongs to this resource. When the AddFontResource function is called, the operating system assumes that the .TTF file has been copied into the SYSTEM directory (or into the main Windows directory in the case of a network installation). The .TTF file need not be in this directory when the CreateScalableFontResource function is called, because the lpszCurrentPath parameter contains the directory information. A resource created in this manner does not contain absolute path information and can be used in any Windows installation.

When a path is specified in the lpszFontFile parameter and NULL is specified in the lpszCurrentPath parameter, the string in lpszFontFile is copied into the .FOT file. In this case, when the AddFontResource function is called, the .TTF file must be at the location specified in the lpszFontFile parameter when the CreateScalableFontResource function was called; the lpszCurrentPath parameter is not needed. A resource created in this manner contains absolute references to paths and drives and does not work if the .TTF file is moved to a different location.

See Also

AddFontResource, EnumFonts, EnumFontFamilies


CreateSemaphore
 CreateSemaphore  QuickInfo  Overview  Group

The CreateSemaphore function creates a named or unnamed semaphore object.

HANDLE CreateSemaphore(

LPSECURITY_ATTRIBUTES  lpSemaphoreAttributes,	// address of security attributes
LONG  lInitialCount,	// initial count
LONG  lMaximumCount,	// maximum count
LPCTSTR  lpName	// address of semaphore-object name
);
Parameters

lpSemaphoreAttributes

Points to a SECURITY_ATTRIBUTES structure that specifies the security attributes for the semaphore object.

If lpSemaphoreAttributes is NULL, the semaphore object is created with a default security descriptor and the resulting handle is not inheritable.

lInitialCount

Specifies an initial count for the semaphore object. This value must be greater than or equal to zero and less than or equal to lMaximumCount. The state of a semaphore is signaled when its count is greater than zero and nonsignaled when it is zero. The count is decreased by one whenever a wait function releases a thread that was waiting for the semaphore. The count is increased by a specified amount by calling the ReleaseSemaphore function.

lMaximumCount

Specifies the maximum count for the semaphore object. This value must be greater than zero.

lpName

Points to a null-terminated string specifying the name of the semaphore object. The name is limited to MAX_PATH characters, and can contain any character except the backslash path-separator character (\). Name comparison is case sensitive.

If lpName matches the name of an existing named semaphore object, this function requests SEMAPHORE_ALL_ACCESS access to the existing object. In this case, the lInitialCount and lMaximumCount parameters are ignored because they have already been set by the creating process. If the lpSemaphoreAttributes parameter is not NULL, it determines whether the handle can be inherited, but its security-descriptor member is ignored.

If lpName is NULL, the semaphore object is created without a name.

If lpName matches the name of an existing event, mutex, or file-mapping object, the function fails and the GetLastError function returns ERROR_INVALID_HANDLE. This occurs because event, mutex, semaphore, and file-mapping objects share the same name space.

Return Value

If the function succeeds, the return value is a handle of the semaphore object. If the named semaphore object existed before the function call, the GetLastError function returns ERROR_ALREADY_EXISTS. Otherwise, GetLastError returns zero.

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

Remarks

The handle returned by CreateSemaphore has SEMAPHORE_ALL_ACCESS access to the new semaphore object and can be used in any function that requires a handle of a semaphore object.

Any thread of the calling process can specify the semaphore-object handle in a call to one of the wait functions (MsgWaitForMultipleObjects, WaitForSingleObject, WaitForMultipleObjects, WaitForSingleObjectEx, or WaitForMultipleObjectsEx). The single-object wait functions return when the state of the specified object is signaled. The multiple-object wait functions can be instructed to return either when any one or when all of the specified objects are signaled. When a wait function returns, the waiting thread is released to continue its execution.

The state of a semaphore object is signaled when its count is greater than zero, and nonsignaled when its count is equal to zero. The lInitialCount parameter specifies the initial count. Each time a waiting thread is released because of the semaphore's signaled state, the count of the semaphore is decreased by one. Use the ReleaseSemaphore function to increment a semaphore's count by a specified amount. The count can never be less than zero or greater than the value specified in the lMaximumCount parameter.

Multiple processes can have handles of the same semaphore object, enabling use of the object for interprocess synchronization. The following object-sharing mechanisms are available:

•	A child process created by the CreateProcess function can inherit a handle of a semaphore object if the lpSemaphoreAttributes parameter of CreateSemaphore enabled inheritance.

•	A process can specify the semaphore-object handle in a call to the DuplicateHandle function to create a duplicate handle that can be used by another process.

•	A process can specify the name of a semaphore object in a call to the OpenSemaphore or CreateSemaphore function.

Use the CloseHandle function to close the handle. The system closes the handle automatically when the process terminates. The semaphore object is destroyed when its last handle has been closed.

See Also

CloseHandle, CreateProcess, DuplicateHandle, OpenSemaphore, ReleaseSemaphore, SECURITY_ATTRIBUTES, WaitForMultipleObjects, WaitForMultipleObjectsEx, WaitForSingleObject, WaitForSingleObjectEx


CreateService
 CreateService  QuickInfo  Overview  Group

The CreateService function creates a service object and adds it to the specified service control manager database.

SC_HANDLE CreateService(

SC_HANDLE  hSCManager,	// handle of service control manager database
LPCTSTR  lpServiceName,	// address of name of service to start
LPCTSTR  lpDisplayName,	// address of display name
DWORD  dwDesiredAccess,	// type of access to service
DWORD  dwServiceType,	// type of service
DWORD  dwStartType,	// when to start service
DWORD  dwErrorControl,	// severity if service fails to start
LPCTSTR  lpBinaryPathName,	// address of name of binary file
LPCTSTR  lpLoadOrderGroup,	// address of name of load ordering group
LPDWORD  lpdwTagId,	// address of variable to get tag identifier
LPCTSTR  lpDependencies,	// address of array of dependency names
LPCTSTR  lpServiceStartName,	// address of account name of service
LPCTSTR  lpPassword	// address of password for service account
);
Parameters

hSCManager

Identifies the service control manager database. The OpenSCManager function returns this handle which must have SC_MANAGER_CREATE_SERVICE access.

lpServiceName

Points to a null-terminated string that names the service to install. The maximum string length is 256 characters. The service control manager database preserves the case of the characters, but service name comparisons are always case insensitive. Forward-slash (/) and back-slash (\) are invalid service name characters.

lpDisplayName

Points to a null-terminated string that is to be used by user interface programs to identify the service. This string has a maximum length of 256 characters. The name is case-preserved in the service control manager. Display name comparisons are always case-insensitive.

dwDesiredAccess

Specifies the access to the service. Before granting the requested access, the system checks the access token of the calling process. Any or all of the following service object access types can be specified:

Access	Description
SERVICE_ALL_ACCESS	Includes STANDARD_RIGHTS_REQUIRED in addition to all of the access types listed in this table.
SERVICE_CHANGE_CONFIG	Enables calling of the ChangeServiceConfig function to change the service configuration.
SERVICE_ENUMERATE_DEPENDENTS	Enables calling of the EnumDependentServices function to enumerate all the services dependent on the service.
SERVICE_INTERROGATE	Enables calling of the ControlService function to ask the service to report its status immediately.
SERVICE_PAUSE_CONTINUE	Enables calling of the ControlService function to pause or continue the service.
SERVICE_QUERY_CONFIG	Enables calling of the QueryServiceConfig function to query the service configuration.
SERVICE_QUERY_STATUS	Enables calling of the QueryServiceStatus function to ask the service control manager about the status of the service.
SERVICE_START	Enables calling of the StartService function to start the service.
SERVICE_STOP	Enables calling of the ControlService function to stop the service.
SERVICE_USER_DEFINE_CONTROL	Enables calling of the ControlService function to specify a user-defined control code.
The STANDARD_RIGHTS_REQUIRED constant (defined in the WINNT.H file) enables the following service object access types:

Standard rights	Description
DELETE	Enables calling of the DeleteService function to delete the service.
READ_CONTROL	Enables calling of the QueryServiceObjectSecurity function to query the security descriptor of the service object.
WRITE_DAC|WRITE_OWNER	Enables calling of the SetServiceObjectSecurity function to modify the security descriptor of the service object.
The dwDesiredAccess parameter can specify any or all of the following generic access types:

Generic access	Service access
GENERIC_READ	Combines the following accesses: STANDARD_RIGHTS_READ, SERVICE_QUERY_CONFIG, SERVICE_QUERY_STATUS, and SERVICE_ENUMERATE_DEPENDENTS.
GENERIC_WRITE	Combines the following accesses: STANDARD_RIGHTS_WRITE and SERVICE_CHANGE_CONFIG.
GENERIC_EXECUTE	Combines the following accesses: STANDARD_RIGHTS_EXECUTE, SERVICE_START, SERVICE_STOP, SERVICE_PAUSE_CONTINUE, SERVICE_INTERROGATE, and SERVICE_USER_DEFINED_CONTROL.
dwServiceType

A set of bit flags that specify the type of service. You must specify one of the following service type flags to indicate the service type. In addition, if you specify either of the SERVICE_WIN32 flags, you can also specify the SERVICE_INTERACTIVE_PROCESS flag to enable the service process to interact with the desktop.

Value	Meaning
SERVICE_WIN32_OWN_PROCESS	A service-type flag that specifies a Win32 service that runs in its own process.
SERVICE_WIN32_SHARE_PROCESS	A service-type flag that specifies a Win32 service that shares a process with other services.
SERVICE_KERNEL_DRIVER	A service-type flag that specifies a Windows NT device driver.
SERVICE_FILE_SYSTEM_DRIVER	A service-type flag that specifies a Windows NT file system driver.
SERVICE_INTERACTIVE_PROCESS	A flag that enables a Win32 service process to interact with the desktop.
dwStartType

Specifies when to start the service. This member can be one of the following values:

Value	Meaning
SERVICE_BOOT_START	Specifies a device driver started by the operating system loader. This value is valid only if the service type is SERVICE_KERNEL_DRIVER or SERVICE_FILE_SYSTEM_DRIVER.
SERVICE_SYSTEM_START	Specifies a device driver started by the IoInitSystem function. This value is valid only if the service type is SERVICE_KERNEL_DRIVER or SERVICE_FILE_SYSTEM_DRIVER.
SERVICE_AUTO_START	Specifies a device driver or Win32 service started by the service control manager automatically during system startup.
SERVICE_DEMAND_START	Specifies a device driver or Win32 service started by the service control manager when a process calls the StartService function.
SERVICE_DISABLED	Specifies a device driver or Win32 service that can no longer be started.
dwErrorControl

Specifies the severity of the error if this service fails to start during startup, and determines the action taken by the startup program if failure occurs. One of the following values can be specified:

Value	Meaning
SERVICE_ERROR_IGNORE	The startup (boot) program logs the error but continues the startup operation.
SERVICE_ERROR_NORMAL	The startup program logs the error and displays a message but continues the startup operation.
SERVICE_ERROR_SEVERE	The startup program logs the error. If the last-known-good configuration is being started, the startup operation continues. Otherwise, the system is restarted with the last-known-good configuration.
SERVICE_ERROR_CRITICAL	The startup program logs the error, if possible. If the last-known-good configuration is being started, the startup operation fails. Otherwise, the system is restarted with the last-known-good configuration.
lpBinaryPathName

Points to a null-terminated string that contains the fully qualified path to the service binary file.

lpLoadOrderGroup

Points to a null-terminated string that names the load ordering group of which this service is a member. If the pointer is NULL or if it points to an empty string, the service does not belong to a group. The registry has a list of load ordering groups located at:

HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control
\ServiceGroupOrder.

The startup program uses this list to load groups of services in a specified order with respect to the other groups in the list. You can place a service in a group so that another service can depend on the group.

The order in which a service starts is determined by the following criteria:

1.	The order of groups in the registry's load-ordering group list. Services in groups in the load-ordering group list are started first, followed by services in groups not in the load-ordering group list and then services that do not belong to a group.

2.	The service's dependencies listed in the lpDependencies parameter and the dependencies of other services dependent on the service.

lpdwTagId

Points to a 32-bit variable that receives a unique tag value for this service in the group specified in the lpLoadOrderGroup parameter. If no tag is requested, this parameter can be NULL.

You can use a tag for ordering service startup in a load ordering group by specifying a tag order vector in the registry located at:

HKEY_LOCAL_MACHINE\System\ CurrentControlSet
\Control\GroupOrderList.

Tags are only evaluated for SERVICE_KERNEL_DRIVER and SERVICE_FILE_SYSTEM_DRIVER type services that have SERVICE_BOOT_START or SERVICE_SYSTEM_START start types.

lpDependencies

Points to an array of null-separated names of services or load ordering groups that must start before this service. The array is double null-terminated. If the pointer is NULL or if it points to an empty string, the service has no dependencies. If a group name is specified, it must be prefixed by the SC_GROUP_IDENTIFIER character (defined in the WINSVC.H file) to differentiate it from a service name, because services and service groups share the same name space. Dependency on a service means that this service can only run if the service it depends on is running. Dependency on a group means that this service can run if at least one member of the group is running after an attempt to start all members of the group.

lpServiceStartName

Points to a null-terminated string. If the service type is SERVICE_WIN32_OWN_PROCESS, this name is the account name in the form of "DomainName\Username", which the service process will be logged on as when it runs. If the account belongs to the built-in domain, ".\Username" can be specified. Services of type SERVICE_WIN32_SHARE_PROCESS are not allowed to specify an account other than LocalSystem. If NULL is specified, the service will be logged on as the "LocalSystem" account, in which case, the lpPassword parameter must be NULL.

If the service type is SERVICE_KERNEL_DRIVER or SERVICE_FILE_SYSTEM_DRIVER, this name is the Windows NT driver object name (that is, \FileSystem\Rdr or \Driver\Xns), which the input and output (I/O) system uses to load the device driver. If NULL is specified, the driver is run with a default object name created by the I/O system, based on the service name.

lpPassword

Points to a null-terminated string that contains the password to the account name specified by the lpServiceStartName parameter, if the service type is SERVICE_WIN32_OWN_PROCESS or SERVICE_WIN32_SHARE_PROCESS. If the pointer is NULL or if it points to an empty string, the service has no password. If the service type is SERVICE_KERNEL_DRIVER or SERVICE_FILE_SYSTEM_DRIVER, this parameter is ignored.

Return Value

If the function succeeds, the return value is a handle to the service.

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

Errors

The following error codes can be set by the service control manager. Other error codes can be set by the registry functions that are called by the service control manager.

Value	Meaning
ERROR_ACCESS_DENIED	The handle to the specified service control manager database does not have SC_MANAGER_CREATE_SERVICE access.
ERROR_CIRCULAR_DEPENDENCY	A circular service dependency was specified.
ERROR_DUP_NAME	The display name already exists in the service control manager database either as a service name or as another display name.
ERROR_INVALID_HANDLE	The handle to the specified service control manager database is invalid.
ERROR_INVALID_NAME	The specified service name is invalid.
ERROR_INVALID_PARAMETER	A parameter that was specified is invalid.
ERROR_INVALID_SERVICE_ACCOUNT	The user account name specified in the lpServiceStartName parameter does not exist.
ERROR_SERVICE_EXISTS	The specified service already exists in this database.
Remarks

The CreateService function creates a service object and installs it in the service control manager database by creating a service name key in the registry with the following form:

HKEY_LOCAL_MACHINE\System\CurrentControlSet
\Services\lpServiceName

where lpServiceName is the service name specified for this function. Information specified for this function is saved as values under this key. Setup programs and the service itself can create any subkey under this service name key for any service specific information.

If the appropriate access rights are enabled, the calling process can use the returned handle to identify the newly created service in the following functions:

ChangeServiceConfig, ControlService, DeleteService, QueryServiceConfig, QueryServiceObjectSecurity, QueryServiceStatus, SetServiceObjectSecurity, StartService

The returned handle is only valid for the process that called CreateService. It can be closed by calling the CloseServiceHandle function.

See Also

ChangeServiceConfig, CloseServiceHandle, ControlService, DeleteService, EnumDependentServices, OpenSCManager, QueryServiceConfig, QueryServiceObjectSecurity, QueryServiceStatus, SetServiceObjectSecurity, StartService


CreateSolidBrush
 CreateSolidBrush  QuickInfo  Overview  Group

The CreateSolidBrush function creates a logical brush that has the specified solid color.

HBRUSH CreateSolidBrush(

COLORREF  crColor	// brush color value
);
Parameters

crColor

Specifies the color of the brush.

Return Value

If the function succeeds, the return value identifies a logical brush.

If the function fails, the return value is NULL.

Remarks

A solid brush is a bitmap that Windows uses to paint the interiors of filled shapes.

After an application creates a brush by calling CreateSolidBrush, it can select that brush into any device context by calling the SelectObject function.

See Also

CreateDIBPatternBrush, CreateDIBPatternBrushPt, CreateHatchBrush, CreatePatternBrush, DeleteObject, SelectObject


CreateStatusWindow [New - Windows NT]
 CreateStatusWindow  QuickInfo  Overview  Group

[New - Windows NT]

The CreateStatusWindow function creates a status window, which is typically used to display the status of an application. The window generally appears at the bottom of the parent window, and it contains the specified text.

HWND CreateStatusWindow(

LONG style,
LPCTSTR lpszText,
HWND hwndParent,
UINT wID
);
Parameters

style

Window styles for the status window. This parameter must include the WS_CHILD style and should also include the WS_VISIBLE style.

lpszText

Pointer to a null-terminated string that specifies the status text for the first part.

hwndParent

Handle to the parent window.

wID

Control identifier for the status window. The window procedure uses this value to identify messages it sends to the parent window.

Return Value

If the function succeeds, the return value is the handle for the status window.

If the function fails, the return value is NULL.

Remarks

The CreateStatusWindow function calls the CreateWindow function to create the window. It passes the parameters to CreateWindow without modification and sets the position, width, and height parameters to default values.

Windows 95 only: The system can support a maximum of 16,364 window handles.

See Also

CreateWindow


CreateTapePartition
 CreateTapePartition  QuickInfo  Overview  Group

The CreateTapePartition function reformats a tape.

DWORD CreateTapePartition(

HANDLE  hDevice,	// handle of open device
DWORD  dwPartitionMethod,	// type of new partition
DWORD  dwCount,	// number of new partitions to create
DWORD  dwSize	// size of new partition, in megabytes
);
Parameters

hDevice

Identifies the device where the new partition is to be created. This handle is created by using the CreateFile function.

dwPartitionMethod

Specifies the type of partition to create. To determine what type of partitions your device supports, see the documentation for your hardware. This parameter can have one of the following values:

Value	Description
TAPE_FIXED_PARTITIONS	Partitions the tape based on the device's default definition of partitions. The dwCount and dwSize parameters are ignored.
TAPE_INITIATOR_PARTITIONS	Partitions the tape into the number and size of partitions specified by dwCount and dwSize, respectively, except for the last partition. The size of the last partition is the remainder of the tape.
TAPE_SELECT_PARTITIONS	Partitions the tape into the number of partitions specified by dwCount. The dwSize parameter is ignored. The size of the partitions is determined by the device's default partition size. For more specific information, refer to the documentation for your tape device.
dwCount

Specifies the number of partitions to create. The GetTapeParameters function provides the maximum number of partitions a tape can support.

dwSize

Specifies the size, in megabytes, of each partition. This value is ignored if the dwPartitionMethod parameter is TAPE_SELECT_PARTITIONS.

Return Value

If the function succeeds, the return value is NO_ERROR.

If the function fails, it may return one of the following error codes:

Error	Description
ERROR_BEGINNING_OF_MEDIA	An attempt to access data before the beginning-of-medium marker failed.
ERROR_BUS_RESET	A reset condition was detected on the bus.
ERROR_END_OF_MEDIA	The end-of-tape marker was reached during an operation.
ERROR_FILEMARK_DETECTED	A filemark was reached during an operation.
ERROR_SETMARK_DETECTED	A setmark was reached during an operation.
ERROR_NO_DATA_DETECTED	The end-of-data marker was reached during an operation.
ERROR_PARTITION_FAILURE	The tape could not be partitioned.
ERROR_INVALID_BLOCK_LENGTH	The block size is incorrect on a new tape in a multivolume partition.
ERROR_DEVICE_NOT_PARTITIONED	The partition information could not be found when a tape was being loaded.
ERROR_MEDIA_CHANGED	The tape that was in the drive has been replaced or removed.
ERROR_NO_MEDIA_IN_DRIVE	There is no media in the drive.
ERROR_NOT_SUPPORTED	The tape driver does not support a requested function.
ERROR_UNABLE_TO_LOCK_MEDIA	An attempt to lock the ejection mechanism failed.
ERROR_UNABLE_TO_UNLOAD_MEDIA	An attempt to unload the tape failed.
ERROR_WRITE_PROTECT	The media is write protected.
Remarks

Creating partitions reformats the tape. All previous information recorded on the tape is destroyed.

See Also

CreateFile, GetTapeParameters


CreateToolbarEx [New - Windows NT]
 CreateToolbarEx  QuickInfo  Overview  Group

[New - Windows NT]

The CreateToolbarEx function creates a toolbar window and adds the specified buttons to the toolbar.

HWND CreateToolbarEx(

HWND  hwnd,
DWORD  ws,
UINT  wID,
int  nBitmaps,
HINSTANCE  hBMInst,
UINT  wBMID,
LPCTBBUTTON  lpButtons,
int  iNumButtons,
int dxButton,
int dyButton,
int  dxBitmap,
int  dyBitmap,
UINT  uStructSize
);
Parameters

hwnd

Handle to the parent window for the toolbar.

ws

Window styles for the toolbar. This parameter must specify at least the WS_CHILD style. It can also include a combination of styles as discussed in Toolbars and related topics.

wID

Control identifier for the toolbar.

nBitmaps

Number of button images contained in the bitmap specified by hBMInst and wBMID.

hBMInst

Module instance with the executable file that contains the bitmap resource.

wBMID

Resource identifier for the bitmap resource. If hBMInst is NULL, this parameter must be a valid bitmap handle.

lpButtons

Pointer to an array of TBBUTTON structures that contains information about the buttons to add to the toolbar.

iNumButtons

Number of buttons to add to the toolbar.

dxButton

Width, in pixels, of the buttons to add to the toolbar.

dyButton

Height, in pixels, of the buttons to add to the toolbar.

dxBitmap

Width, in pixels, of the button images to add to the buttons in the toolbar.

dyBitmap

Height, in pixels, of the button images to add to the buttons in the toolbar.

uStructSize

Size of a TBBUTTON structure.

Return Value

If the function succeeds, the return value is the window handle to the toolbarl

If the function fails, the return value is NULL.

Remarks

Windows 95 only: The system can support a maximum of 16,364 window handles.

See Also

TBBUTTON


CreateThread
 CreateThread  QuickInfo  Overview  Group

The CreateThread function creates a thread to execute within the address space of the calling process.

HANDLE CreateThread(

LPSECURITY_ATTRIBUTES  lpThreadAttributes,	// address of thread security attributes
DWORD  dwStackSize,	// initial thread stack size, in bytes
LPTHREAD_START_ROUTINE  lpStartAddress,	// address of thread function
LPVOID  lpParameter,	// argument for new thread
DWORD  dwCreationFlags,	// creation flags
LPDWORD  lpThreadId	// address of returned thread identifier
);
Parameters

lpThreadAttributes

Points to a SECURITY_ATTRIBUTES structure that specifies the security attributes for the thread.

If lpThreadAttributes is NULL, the thread is created with a default security descriptor, and the resulting handle is not inherited.

dwStackSize

Specifies the size, in bytes, of the stack for the new thread. If 0 is specified, the stack size defaults to the same size as that of the primary thread of the process. The stack is allocated automatically in the memory space of the process and it is freed when the thread terminates. Note that the stack size grows, if necessary.

CreateThread tries to commit the number of bytes specified by dwStackSize, and fails if the size exceeds available memory.

lpStartAddress

Points to the application-supplied function to be executed by the thread and represents the starting address of the thread. The function accepts a single 32-bit argument and returns a 32-bit exit value.

lpParameter

Specifies a single 32-bit parameter value passed to the thread.

dwCreationFlags

Specifies additional flags that control the creation of the thread. If the CREATE_SUSPENDED flag is specified, the thread is created in a suspended state, and will not run until the ResumeThread function is called. If this value is zero, the thread runs immediately after creation.

lpThreadId

Points to a 32-bit variable that receives the thread identifier.

Return Value

If the function succeeds, the return value is a handle to the new thread.

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

Windows 95 only: CreateThread succeeds only when it is called in the context of a 32-bit program. A 32-bit DLL cannot create an additional thread when that DLL is being called by a 16-bit program.

Remarks

The new thread handle is created with full access to the new thread. If a security descriptor is not provided, the handle can be used in any function that requires a thread object handle. When a security descriptor is provided, an access check is performed on all subsequent uses of the handle before access is granted. If the access check denies access, the requesting process cannot use the handle to gain access to the thread.

The thread execution begins at the function specified by the lpStartAddress parameter. If this function returns, the DWORD return value is used to terminate the thread in an implicit call to the ExitThread function. Use the GetExitCodeThread function to get the thread's return value.

The CreateThread function may succeed even if lpStartAddress points to data, code, or is not accessible. If the start address is invalid when the thread runs, an exception occurs, and the thread terminates. Thread termination due to a invalid start address is handled as an error exit for the thread's process. This behavior is similar to the asynchronous nature of CreateProcess, where the process is created even if it refers to invalid or missing dynamic-link libraries (DLLs).

The thread is created with a thread priority of THREAD_PRIORITY_NORMAL. Use the GetThreadPriority and SetThreadPriority functions to get and set the priority value of a thread.

When a thread terminates, the thread object attains a signaled state, satisfying any threads that were waiting on the object.

The thread object remains in the system until the thread has terminated and all handles to it have been closed through a call to CloseHandle.

The ExitProcess, ExitThread, CreateThread, CreateRemoteThread functions, and a process that is starting (as the result of a call by CreateProcess) are serialized between each other within a process. Only one of these events can happen in an address space at a time. This means that the following restrictions hold:

•	During process startup and DLL initialization routines, new threads can be created, but they do not begin execution until DLL initialization is done for the process.

•	Only one thread in a process can be in a DLL initialization or detach routine at a time.

•	ExitProcess does not return until no threads are in their DLL initialization or detach routines.

A thread that uses functions from the C run-time libraries should use the beginthread and endthread C run-time functions for thread management rather than CreateThread and ExitThread. Failure to do so results in small memory leaks when ExitThread is called.

See Also

CloseHandle, CreateProcess, CreateRemoteThread, ExitProcess, ExitThread, GetExitCodeThread, GetThreadPriority, ResumeThread, SetThreadPriority, SECURITY_ATTRIBUTES


CreateUpDownControl [New - Windows NT]
 CreateUpDownControl  QuickInfo  Overview  Group

[New - Windows NT]

The CreateUpDownControl function creates an up-down control.

HWND CreateUpDownControl(

DWORD  dwStyle,
int  x,
int  y,
int  cx,
int cy,
HWND  hParent,
int  nID,
HINSTANCE  hInst
HWND  hBuddy,
int  nUpper,
int  nLower,
int  nPos
);
Parameters

dwStyle

Window styles for the control. This parameter should include the WS_CHILD, WS_BORDER, and WS_VISIBLE styles, and it may include any of the window styles specific to the up-down control.

x

Horizontal coordinate, in client coordinates, of the upper-left corner of the control.

y

Vertical coordinate, in client coordinates, of the upper-left corner of the control.

cx

Width, in pixels, of the up-down control.

cy

Height, in pixels, of the up-down control.

hParent

Handle to the parent window of the up-down control

nID

Identifier for the up-down control.

hInst

Handle to the module instance of the application creating the up-down control.

hBuddy

Handle to the window associated with the up-down control. If this parameter is NULL, the control has no buddy window.

nUpper

Upper limit (range) of the up-down control.

nLower

Lower limit (range) of the up-down control.

nPos

Position of the control.

Return Value

If the function succeeds, the return value is the window handle of the up-down control.

If the function fails, the return value is NULL.

Remarks

Windows 95 only: The system can support a maximum of 16,364 window handles.


CreateWindow
 CreateWindow  QuickInfo  Overview  Group

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.

HWND CreateWindow(

LPCTSTR  lpClassName,	// address of registered class name
LPCTSTR  lpWindowName,	// address of 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 of parent or owner window
HMENU  hMenu,	// handle of menu or child-window identifier
HANDLE  hInstance,	// handle of application instance
LPVOID  lpParam	// address of window-creation data
);
Parameters

lpClassName

Points to a null-terminated string or is an integer atom. If this parameter is an atom, it must be a global atom created by a previous call to the GlobalAddAtom function. The atom, a 16-bit value less than 0xC000, must be in the low-order word of lpClassName; the high-order word must be zero.

If lpClassName is a string, it specifies the window class name. The class name can be any name registered with the RegisterClass function or any of the predefined control-class names. For a complete list, see the following Remarks section.

lpWindowName

Points to a null-terminated string that specifies the window name.

dwStyle

Specifies the style of the window being created. This parameter can be a combination of the window styles and control styles listed in the following Remarks section.

x

Specifies the initial horizontal position of the window. For an overlapped or pop-up window, the x parameter is the initial x-coordinate of the window's upper-left corner, in screen coordinates. For a child window, x is the x-coordinate of the upper-left corner of the window relative to the upper-left corner of the parent window's client area.

If this parameter is set to CW_USEDEFAULT, Windows selects the default position for the window's upper-left corner and ignores the y parameter. CW_USEDEFAULT is valid only for overlapped windows; if it is specified for a pop-up or child window, the x and y parameters are set to zero.

y

Specifies the initial vertical position of the window. For an overlapped or pop-up window, the y parameter is the initial y-coordinate of the window's upper-left corner, in screen coordinates. For a child window, y is the initial y-coordinate of the upper-left corner of the child window relative to the upper-left corner of the parent window's client area. For a list box, y is the initial y-coordinate of the upper-left corner of the list box's client area relative to the upper-left corner of the parent window's client area.

If an overlapped window is created with the WS_VISIBLE style bit set and the x parameter is set to CW_USEDEFAULT, Windows ignores the y parameter.

nWidth

Specifies the width, in device units, of the window. For overlapped windows, nWidth is either the window's width, in screen coordinates, or CW_USEDEFAULT. If nWidth is CW_USEDEFAULT, Windows selects a default width and height for the window; the default width extends from the initial x-coordinate to the right edge of the screen, and the default height extends from the initial y-coordinate to the top of the icon area. CW_USEDEFAULT is valid only for overlapped windows; if CW_USEDEFAULT is specified for a pop-up or child window, nWidth and nHeight are set to zero.

nHeight

Specifies the height, in device units, of the window. For overlapped windows, nHeight is the window's height, in screen coordinates. If nWidth is set to CW_USEDEFAULT, Windows ignores nHeight.

hWndParent

Identifies the parent or owner window of the window being created. A valid window handle must be supplied when a child window or an owned window is created. A child window is confined to the client area of its parent window. An owned window is an overlapped window that is destroyed when its owner window is destroyed or hidden when its owner is minimized; it is always displayed on top of its owner window. Although this parameter must specify a valid handle if the dwStyle parameter includes the WS_CHILD style, it is optional if dwStyle includes the WS_POPUP style.

hMenu

Identifies 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

Identifies the instance of the module to be associated with the window.

lpParam

Points to a value passed to the window through the CREATESTRUCT structure referenced by the lParam parameter of 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 Value

If the function succeeds, the return value is the handle of the new window.

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

Remarks

Before returning, CreateWindow sends a WM_CREATE message to the window procedure.

For overlapped, pop-up, and child windows, CreateWindow sends WM_CREATE, WM_GETMINMAXINFO, and WM_NCCREATE messages to the window. The lParam parameter of the WM_CREATE message contains a pointer to a CREATESTRUCT structure. If the WS_VISIBLE style is specified, CreateWindow sends the window all the messages required to activate and show the window.

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.

The following predefined control classes can be specified in the lpClassName 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.
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.
	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 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.
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.
	Edit controls use the variable-pitch system font and display characters from the ANSI character set. The WM_SETFONT message can also be sent to the edit control to change the default font.
	Edit controls expand tab characters into as many space characters as are required to move the caret to the next tab stop. Tab stops are assumed to be at every eighth character position.
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. Use a vertical or horizontal scroll bar with a list box to scroll lists that are too long for the control window. The list box automatically hides or shows the scroll bar, as needed.
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.
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. Scroll bar controls have the same appearance and function as scroll bars used in ordinary windows. Unlike scroll bars, however, scroll bar controls can be positioned anywhere in a window for use whenever scrolling input is needed for a window.
	The scroll bar class also includes size box controls. A size box is a small rectangle the user can expand to change the size of the window.
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.
The following window styles can be specified in the dwStyle parameter:

Style	Meaning
WS_BORDER	Creates a window that has a thin-line border.
WS_CAPTION	Creates a window that has a title bar (includes the WS_BORDER style).
WS_CHILD	Creates a child window. This style cannot be used with the WS_POPUP style.
WS_CHILDWINDOW	Same as the WS_CHILD style.
WS_CLIPCHILDREN	Excludes the area occupied by child windows when drawing occurs within the parent window. This style is used when creating the parent window.
WS_CLIPSIBLINGS	Clips child windows relative to each other; that is, when a particular child window receives a WM_PAINT message, the WS_CLIPSIBLINGS style clips all other overlapping child windows out of the region of the child window to be updated. If WS_CLIPSIBLINGS is not specified and child windows overlap, it is possible, when drawing within the client area of a child window, to draw within the client area of a neighboring child window.
WS_DISABLED	Creates a window that is initially disabled. A disabled window cannot receive input from the user.
WS_DLGFRAME	Creates a window that has a border of a style typically used with dialog boxes. A window with this style cannot have a title bar.
WS_GROUP	Specifies the first control of a group of controls. The user can change the keyboard focus from one control in the group to the next by using the direction keys. All controls defined with the WS_GROUP style after the first control belong to the same group. The next control with the WS_GROUP style ends the group and starts the next group.
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.
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.
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 System 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 System-menu box in its title bar. The WS_CAPTION style must also be specified.
WS_TABSTOP	Specifies a control that can receive the keyboard focus when the user presses the TAB key. Pressing the TAB key changes the keyboard focus to the next control with the WS_TABSTOP style.
WS_THICKFRAME	Creates a window that has a sizing border. Same as the WS_SIZEBOX style.
WS_TILED	Creates an overlapped window. An overlapped window has a title bar and a border. Same as the WS_OVERLAPPED style.
WS_TILEDWINDOW	Creates an overlapped window with the WS_OVERLAPPED, WS_CAPTION, WS_SYSMENU, WS_THICKFRAME, WS_MINIMIZEBOX, and WS_MAXIMIZEBOX styles. Same as the WS_OVERLAPPEDWINDOW style.
WS_VISIBLE	Creates a window that is initially visible.
WS_VSCROLL	Creates a window that has a vertical scroll bar.
The following button styles (in the BUTTON class) can be specified in the dwStyle parameter:

Style	Meaning
BS_3STATE	Creates a button that is the same as a check box, except that the box can be grayed as well as checked or unchecked. Use the grayed state to show that the state of the check box is not determined.
BS_AUTO3STATE	Creates a button that is the same as a three-state check box, except that the box changes its state when the user selects it. The state cycles through checked, grayed, and unchecked.
BS_AUTOCHECKBOX	Creates a button that is the same as a check box, except that the check state automatically toggles between checked and unchecked each time the user selects the check box.
BS_AUTORADIOBUTTON	Creates a button that is the same as a radio button, except that when the user selects it, Windows automatically sets the button's check state to checked and automatically sets the check state for all other buttons in the same group to unchecked.
BS_CHECKBOX	Creates a small, empty check box with text. By default, the text is displayed to the right of the check box. To display the text to the left of the check box, combine this flag with the BS_LEFTTEXT style (or on Windows 95 only, 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 Windows 95 BS_RIGHTBUTTON style.
BS_OWNERDRAW	Creates an owner-drawn button. The owner window receives a WM_MEASUREITEM message when the button is created and a WM_DRAWITEM message when a visual aspect of the button has changed. Do not combine the BS_OWNERDRAW style with any other button styles.
BS_PUSHBUTTON	Creates a push button that posts a WM_COMMAND message to the owner window when the user selects the button.
BS_RADIOBUTTON	Creates a small circle with text. By default, the text is displayed to the right of the circle. To display the text to the left of the circle, combine this flag with the BS_LEFTTEXT style (or on Windows 95 only, 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	Windows 95 only: Specifies that the button displays a bitmap.
BS_BOTTOM	Windows 95 only: Places text at the bottom of the button rectangle.
BS_CENTER	Windows 95 only: Centers text horizontally in the button rectangle.
BS_ICON	Windows 95 only: Specifies that the button displays an icon.
BS_LEFT	Windows 95 only: 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	Windows 95 only: 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	Windows 95 only: Enables a button to send BN_DBLCLK, BN_KILLFOCUS, and BN_SETFOCUS notification messages to its parent window. Note that buttons send the BN_CLICKED notification message regardless of whether it has this style.
BS_PUSHLIKE	Windows 95 only: 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	Windows 95 only: 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	Windows 95 only: 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	Windows 95 only: Specifies that the button displays text.
BS_TOP	Windows 95 only: Places text at the top of the button rectangle.
BS_VCENTER	Windows 95 only: Places text in the middle (vertically) of the button rectangle.
The following combo box styles (in the COMBOBOX class) can be specified in the dwStyle parameter:

Style	Meaning
CBS_AUTOHSCROLL	Automatically scrolls the text in an edit control to the right when the user types a character at the end of the line. If this style is not set, only text that fits within the rectangular boundary is allowed.
CBS_DISABLENOSCROLL	Shows a disabled vertical scroll bar in the list box when the box does not contain enough items to scroll. Without this style, the scroll bar is hidden when the list box does not contain enough items.
CBS_DROPDOWN	Similar to CBS_SIMPLE, except that the list box is not displayed unless the user selects an icon next to the edit control.
CBS_DROPDOWNLIST	Similar to CBS_DROPDOWN, except that the edit control is replaced by a static text item that displays the current selection in the list box.
CBS_HASSTRINGS	Specifies that an owner-drawn combo box contains items consisting of strings. The combo box maintains the memory and address for the strings, so the application can use the CB_GETLBTEXT message to retrieve the text for a particular item.
CBS_LOWERCASE	Converts to lowercase any uppercase characters entered into the edit control of a combo box.
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, Windows sizes a combo box so that it does not display partial items.
CBS_OEMCONVERT	Converts text entered in the combo box 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 combo box to OEM characters. This style is most useful for combo boxes that contain filenames and applies only to combo boxes created with the CBS_SIMPLE or CBS_DROPDOWN style.
CBS_OWNERDRAWFIXED	Specifies that the owner of the list box is responsible for drawing its contents and that the items in the list box are all the same height. The owner window receives a WM_MEASUREITEM message when the combo box is created and a WM_DRAWITEM message when a visual aspect of the combo box has changed.
CBS_OWNERDRAWVARIABLE	Specifies that the owner of the list box is responsible for drawing its contents and that the items in the list box are variable in height. The owner window receives a WM_MEASUREITEM message for each item in the combo box when you create the combo box; the owner window receives 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 entered into the list box.
CBS_UPPERCASE	Converts to uppercase any lowercase characters entered into the edit control of a combo box.
The following edit control styles (in the EDIT class) can be specified in the dwStyle parameter:

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	Centers text in a multiline edit control.
ES_LEFT	Left-aligns text.
ES_LOWERCASE	Converts all characters to lowercase as they are typed into the edit control.
ES_MULTILINE	Designates a multiline edit control. The default is single-line edit control.
	When the multiline edit control is in a dialog box, the default response to pressing the ENTER key is to activate the default button. To use the ENTER key as a carriage return, use the ES_WANTRETURN style.
	When the multiline edit control is not in a dialog box and the ES_AUTOVSCROLL style is specified, the edit control shows as many lines as possible and scrolls vertically when the user presses the ENTER key. If you do not specify ES_AUTOVSCROLL, the edit control shows as many lines as possible and beeps if the user presses the ENTER key when no more lines can be displayed.
	If you specify the ES_AUTOHSCROLL style, the multiline edit control automatically scrolls horizontally when the caret goes past the right edge of the control. To start a new line, the user must press the ENTER key. If you do not specify ES_AUTOHSCROLL, the control automatically wraps words to the beginning of the next line when necessary. A new line is also started if the user presses the ENTER key. The window size determines the position of the word wrap. If the window size changes, the word wrapping position changes and the text is redisplayed.
	Multiline edit controls can have scroll bars. An edit control with scroll bars processes its own scroll bar messages. Note that edit controls without scroll bars scroll as described in the previous paragraphs and process any scroll messages sent by the parent window.
ES_NOHIDESEL	Negates the default behavior for an edit control. The default behavior hides the selection when the control loses the input focus and inverts the selection when the control receives the input focus. If you specify ES_NOHIDESEL, the selected text is inverted, even if the control does not have the focus.
ES_NUMBER	Windows 95 only: Allows only digits to be entered into the edit control.
ES_OEMCONVERT	Converts text entered in the edit control. The text is converted from the Windows character set to the OEM character set and then back to the Windows set. This ensures proper character conversion when the application calls the CharToOem function to convert a Windows string in the edit control to OEM characters. This style is most useful for edit controls that contain filenames.
ES_PASSWORD	Displays an asterisk (*) for each character typed into the edit control. You can use the EM_SETPASSWORDCHAR message to change the character that is displayed.
ES_READONLY	Prevents the user from typing or editing text in the edit control.
ES_RIGHT	Right-aligns text in a multiline edit control.
ES_UPPERCASE	Converts all characters to uppercase as they are typed into the edit control.
ES_WANTRETURN	Specifies that a carriage return be inserted when the user presses the ENTER key while entering text into a multiline edit control in a dialog box. If you do not specify this style, pressing the ENTER key has the same effect as pressing the dialog box's default push button. This style has no effect on a single-line edit control.
The following list box control styles (in the LISTBOX class) can be specified in the dwStyle parameter:

Style	Meaning
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 the application can use the LB_GETTEXT message to retrieve the text for a particular item. By default, all list boxes except owner-drawn list boxes have this style. You can create an owner-drawn list box either with or without this style.
LBS_MULTICOLUMN	Specifies a multicolumn list box that is scrolled horizontally. The LB_SETCOLUMNWIDTH message sets the width of the columns.
LBS_MULTIPLESEL	Turns string selection on or off each time the user clicks or double-clicks a string in the list box. The user can select any number of strings.
LBS_NODATA	Specifies a no-data list box. Specify this style when the count of items in the list box will exceed one thousand. A no-data list box must also have the LBS_OWNERDRAWFIXED style, but must not have the LBS_SORT or LBS_HASSTRINGS style.
	A no-data list box resembles an owner-drawn list box except that it contains no string or bitmap data for an item. Commands to add, insert, or delete an item always ignore any given item data; requests to find a string within the list box always fail. Windows 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, Windows sizes a list box so that the list box does not display partial items.
LBS_NOREDRAW	Specifies that the list box's appearance is not updated when changes are made. You can change this style at any time by sending a WM_SETREDRAW message.
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. The default tab positions are 32 dialog box units. A dialog box unit is a horizontal or vertical distance. One horizontal dialog box unit is equal to one-fourth of the current dialog box base-width unit. Windows calculates these units based on the height and width of the current system font. The GetDialogBaseUnits function returns the current dialog box base units in pixels.
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.
The following scroll bar styles (in the SCROLLBAR class) can be specified in the dwStyle parameter:

Style	Meaning
SBS_BOTTOMALIGN	Aligns the bottom edge of the scroll bar with the bottom edge of the rectangle defined by the CreateWindow parameters x, y, nWidth, and nHeight. 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 parameters of CreateWindow.
SBS_LEFTALIGN	Aligns the left edge of the scroll bar with the left edge of the rectangle defined by the parameters of CreateWindow. 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 parameters of CreateWindow. 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 parameters of CreateWindow.
SBS_SIZEBOXBOTTOMRIGHTALIGN	Aligns the lower-right corner of the size box with the lower-right corner of the rectangle specified by the parameters of CreateWindow. 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 parameters of CreateWindow. The size box has the default size for system size boxes. Use this style with the SBS_SIZEBOX style.
SBS_SIZEGRIP	Windows 95 only: 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 parameters of CreateWindow. 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 parameters of CreateWindow.
The following static control styles (in the STATIC class) can be specified in the dwStyle parameter. A static control can have only one of these styles:

Style	Description
SS_BITMAP	Specifies a bitmap is to be displayed in the static control. The given text is the name of a bitmap (not a filename) defined elsewhere in the resource file. The style ignores the nWidth and nHeight parameters; the control automatically sizes itself to accommodate the bitmap.
SS_BLACKFRAME	Specifies a box with a frame drawn in the same color as the window frames. This color is black in the default Windows color scheme.
SS_BLACKRECT	Specifies a rectangle filled with the current window frame color. This color is black in the default Windows color scheme.
SS_CENTER	Specifies a simple rectangle and centers the given text in the rectangle. The text is formatted before it is displayed. Words that extend past the end of a line are automatically wrapped to the beginning of the next centered line.
SS_CENTERIMAGE	Specifies that the midpoint of a static control with the SS_BITMAP or SS_ICON style is to remain fixed when the control is resized. The four sides are adjusted to accommodate a new bitmap or icon. If a static control has the SS_BITMAP style and the bitmap is smaller than the control's client area, the client area is filled with the color of the pixel in the upper-left corner of the bitmap. If a static control has the SS_ICON style, the icon does not appear to paint the client area.
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 Windows color scheme.
SS_GRAYRECT	Specifies a rectangle filled with the current screen background color. This color is gray in the default Windows color scheme.
SS_ICON	Specifies an icon displayed in the dialog box. The given text is the name of an icon (not a filename) defined elsewhere in the resource file. The style ignores the nWidth and nHeight parameters; the icon automatically sizes itself.
SS_LEFT	Specifies a simple rectangle and left-aligns the given text in the rectangle. The text is formatted before it is displayed. Words that extend past the end of a line are automatically wrapped to the beginning of the next left-aligned line.
SS_LEFTNOWORDWRAP	Specifies a simple rectangle and left-aligns the given text in the rectangle. Tabs are expanded but words are not wrapped. Text that extends past the end of a line is clipped.
SS_METAPICT	Specifies a metafile picture is to be displayed in the static control. The given text is the name of a metafile picture (not a filename) defined elsewhere in the resource file. A metafile static control has a fixed size; the metafile picture is scaled to fit the static control's client area.
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.
	An application can combine SS_NOPREFIX with other styles by using the bitwise OR (|) operator. 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 and STN_DBLCLK notification messages when the user clicks or double clicks the control.
SS_RIGHT	Specifies a simple rectangle and right-aligns the given text in the rectangle. The text is formatted before it is displayed. Words that extend past the end of a line are automatically wrapped to the beginning of the next right-aligned line.
SS_RIGHTIMAGE	Specifies that the bottom-right corner of a static control with the SS_BITMAP or SS_ICON style is to remain fixed when the control is resized. Only the top and left sides are adjusted to accommodate a new bitmap or icon.
SS_SIMPLE	Specifies a simple rectangle and displays a single line of left-aligned text in the rectangle. The text line cannot be shortened or altered in any way. The control's parent window or dialog box must not process the WM_CTLCOLORSTATIC message.
SS_WHITEFRAME	Specifies a box with a frame drawn with the same color as the window backgrounds. This color is white in the default Windows color scheme.
SS_WHITERECT	Specifies a rectangle filled with the current window background color. This color is white in the default Windows color scheme.
The following dialog box styles can be specified in the dwStyle parameter:

Style	Meaning
DS_3DLOOK	Windows 95 only: Gives the dialog box a nonbold font and draws three-dimensional borders around control windows in the dialog box. The DS_3DLOOK style is not required by Win32-based applications that are marked with version number 4.0 or greater; the system automatically applies the three dimensional look to dialog boxes created by these applications.
DS_ABSALIGN	Indicates that the coordinates of the dialog box are screen coordinates; otherwise, Windows assumes they are client coordinates.
DS_CENTER	Windows 95 only: Centers the dialog box in the working area; that is, the area not obscured by the tray.
DS_CENTERMOUSE	Windows 95 only: Centers the mouse cursor in the dialog box.
DS_CONTEXTHELP	Includes a question mark in the title bar of the dialog box. When the user clicks the question mark, the cursor changes to a question mark with a pointer. If the user then clicks a control in the dialog box, the control receives a WM_HELP message. The control should pass the message to the dialog procedure, which should call the WinHelp function using the HELP_WM_HELP command. The Help application displays a pop-up window that typically contains help for the control. Note that DS_CONTEXTHELP is just 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.
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	Windows 95 only: Use SYSTEM_FIXED_FONT instead of SYSTEM_FONT.
DS_LOCALEDIT	Applies to 16-bit applications only. This style directs edit controls in the dialog box to allocate memory from the application's data segment. Otherwise, edit controls allocate storage from a global memory object.
DS_MODALFRAME	Creates a dialog box with a modal dialog-box frame that can be combined with a title bar and System menu by specifying the WS_CAPTION and WS_SYSMENU styles.
DS_NOFAILCREATE	Windows 95 only: 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 Windows would otherwise send to the owner of the dialog box while the dialog box is displayed.
DS_RECURSE	Dialog box style for control-like dialog boxes.
DS_SETFONT	Indicates that the dialog box template (the DLGTEMPLATE structure) contains two additional members specifying a font name and point size. The corresponding font is used to display text within the dialog box client area and within the dialog box controls. Windows passes the handle of the font to the dialog box and to each control by sending them the WM_SETFONT message.
DS_SETFOREGROUND	Does not apply to 16-bit versions of Microsoft Windows. This style brings the dialog box to the foreground. Internally, Windows calls the SetForegroundWindow function for the dialog box.
DS_SYSMODAL	Creates a system-modal dialog box. This style causes the dialog box to have the WS_EX_TOPMOST style, but otherwise has no effect on the dialog box or the behavior of other windows in the system when the dialog box is displayed.
Windows 95 only: The system can support a maximum of 16,364 window handles.

See Also

CharToOem, CLIENTCREATESTRUCT, CreateDialog, CREATESTRUCT, CreateWindowEx, DialogBox, DLGTEMPLATE, DRAWITEMSTRUCT, GetDialogBaseUnits, GlobalAddAtom, LB_GETTEXT, LB_SETCOLUMNWIDTH, MessageBox, RegisterClass, SetForegroundWindow, WM_COMMAND, WM_CREATE, WM_DELETEITEM, WM_DRAWITEM, WM_ENTERIDLE, WM_GETMINMAXINFO, WM_MEASUREITEM, WM_NCCREATE, WM_PAINT, WM_SETFONT, WM_SETREDRAW, WM_VKEYTOITEM


CreateWindowEx
 CreateWindowEx  QuickInfo  Overview  Group

The CreateWindowEx function creates an overlapped, pop-up, or child window with an extended style; otherwise, this function is identical to the CreateWindow function. For more information about creating a window and for full descriptions of the other parameters of CreateWindowEx, see CreateWindow.

HWND CreateWindowEx(

DWORD  dwExStyle,	// extended window style
LPCTSTR  lpClassName,	// address of registered class name
LPCTSTR  lpWindowName,	// address of 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 of parent or owner window
HMENU  hMenu,	// handle of menu, or child-window identifier
HINSTANCE  hInstance,	// handle of application instance
LPVOID  lpParam	// address of window-creation data
);
Parameters

dwExStyle

Specifies the extended style of the window. This parameter can be one of the following values:

Style	Meaning
WS_EX_ABSPOSITION	Specifies that a window has an absolute position. That is, the window does not move when the working area moves.
WS_EX_ACCEPTFILES	Specifies that a window created with this style accepts drag-drop files.
WS_EX_APPWINDOW	Windows 95 only: Forces a top-level window onto the application taskbar when the window is minimized.
WS_EX_CLIENTEDGE	Specifies that a window has a border with a sunken edge.
WS_EX_CONTEXTHELP	Includes a question mark in the title bar of the window. When the user clicks the question mark, the cursor changes to a question mark with a pointer. If the user then clicks a child window, the child receives a WM_HELP message. The child window should pass the message to the parent window procedure, which should call the WinHelp function using the HELP_WM_HELP command. The Help application displays a pop-up window that typically contains help for the child window.
WS_EX_CONTROLPARENT	Windows 95 only: Allows the user to navigate among the child windows of the window by using the TAB key.
WS_EX_DLGMODALFRAME	Creates a window that has a double border; the window can, optionally, be created with a title bar by specifying the WS_CAPTION style in the dwStyle parameter.
WS_EX_LEFT	Windows 95 only: Window has generic "left-aligned" properties. This is the default.
WS_EX_LEFTSCROLLBAR	Windows 95 only: If the shell language is Hebrew, Arabic, or another language that supports reading order alignment, the vertical scroll bar (if present) is to the left of the client area. For other languages, the style is ignored and not treated as an error.
WS_EX_LTRREADING	Windows 95 only: The window text is displayed using Left to Right reading-order properties. This is the default.
WS_EX_MDICHILD	Creates an MDI child window.
WS_EX_NOPARENTNOTIFY	Specifies that a child window created with this style does not send the WM_PARENTNOTIFY message to its parent window when it is created or destroyed.
WS_EX_OVERLAPPEDWINDOW	Windows 95 only: Combines the WS_EX_CLIENTEDGE and WS_EX_WINDOWEDGE styles.
WS_EX_PALETTEWINDOW	Windows 95 only: Combines the WS_EX_WINDOWEDGE, WS_EX_TOOLWINDOW, and WS_EX_TOPMOST styles.
WS_EX_RIGHT	Windows 95 only: Window has generic "right-aligned" properties. This depends on the window class. This style has an effect only if the shell language is Hebrew, Arabic, or another language that supports reading order alignment; otherwise, the style is ignored and not treated as an error.
WS_EX_RIGHTSCROLLBAR	Windows 95 only: Vertical scroll bar (if present) is to the right of the client area. This is the default.
WS_EX_RTLREADING	Windows 95 only: If the shell language is Hebrew, Arabic, or another language that supports reading order alignment, the window text is displayed using Right to Left reading-order properties. For other languages, the style is ignored and not treated as an error.
WS_EX_STATICEDGE	Windows 95 only: Creates a window with a three-dimensional border style intended to be used for items that do not accept user input.
WS_EX_TOOLWINDOW	Windows 95 only: Creates a tool window; that is, a window intended to be used as a floating toolbar. A tool window has a title bar that is shorter than a normal title bar, and the window title is drawn using a smaller font. A tool window does not appear in the task bar or in the window that appears when the user presses ALT+TAB.
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 is to be transparent. That is, any windows that are beneath the window are not obscured by the window. A window created with this style receives WM_PAINT messages only after all sibling windows beneath it have been updated.
WS_EX_WINDOWEDGE	Windows 95 only: Specifies that a window has a border with a raised edge.
Windows 95 only: 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

Points to a null-terminated string or is an integer atom. If lpClassName is an atom, it must be a global atom created by a previous call to GlobalAddAtom. The atom, a 16-bit value less than 0xC000, must be in the low-order word of lpClassName; the high-order word must be zero.

If lpClassName is a string, it specifies the window class name. The class name can be any name registered with the RegisterClass function or any of the predefined control-class names.

lpWindowName

Points to a null-terminated string that specifies the window name.

dwStyle

Specifies the style of the window being created. For a list of the window styles that can be specified in dwStyle, see CreateWindow.

x

Specifies the initial horizontal position of the window. For an overlapped or pop-up window, the x parameter is the initial x-coordinate of the window's upper-left corner, in screen coordinates. For a child window, x is the x-coordinate of the upper-left corner of the window relative to the upper-left corner of the parent window's client area.

If x is set to CW_USEDEFAULT, Windows selects the default position for the window's upper-left corner and ignores the y parameter. CW_USEDEFAULT is valid only for overlapped windows; if it is specified for a pop-up or child window, the x and y parameters are set to zero.

y

Specifies the initial vertical position of the window. For an overlapped or pop-up window, the y parameter is the initial y-coordinate of the window's upper-left corner, in screen coordinates. For a child window, y is the initial y-coordinate of the upper-left corner of the child window relative to the upper-left corner of the parent window's client area. For a list box, y is the initial y-coordinate of the upper-left corner of the list box's client area relative to the upper-left corner of the parent window's client area.

If an overlapped window is created with the WS_VISIBLE style bit set and the x parameter is set to CW_USEDEFAULT, Windows ignores the y parameter.

nWidth

Specifies the width, in device units, of the window. For overlapped windows, nWidth is the window's width, in screen coordinates, or CW_USEDEFAULT. If nWidth is CW_USEDEFAULT, Windows selects a default width and height for the window; the default width extends from the initial x-coordinates to the right edge of the screen; the default height extends from the initial y-coordinate to the top of the icon area. CW_USEDEFAULT is valid only for overlapped windows; if CW_USEDEFAULT is specified for a pop-up or child window, the nWidth and nHeight parameter are set to zero.

nHeight

Specifies the height, in device units, of the window. For overlapped windows, nHeight is the window's height, in screen coordinates. If the nWidth parameter is set to CW_USEDEFAULT, Windows ignores nHeight.

hWndParent

Identifies the parent or owner window of the window being created. A valid window handle must be supplied when a child window or an owned window is created. A child window is confined to the client area of its parent window. An owned window is an overlapped window that is destroyed when its owner window is destroyed or hidden when its owner is minimized; it is always displayed on top of its owner window. Although this parameter must specify a valid handle if the dwStyle parameter includes the WS_CHILD style, it is optional if dwStyle includes the WS_POPUP style.

hMenu

Identifies 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

Identifies the instance of the module to be associated with the window.

lpParam

Points to a value passed to the window through the CREATESTRUCT structure referenced by the lParam parameter of the WM_CREATE message. If an application calls CreateWindow to create a multiple document interface client window, lpParam must point to a CLIENTCREATESTRUCT structure.

Return Value

If the function succeeds, the return value is the handle of the new window.

If the function fails, the return value is NULL.

Remarks

The CreateWindowEx function sends WM_NCCREATE, WM_NCCALCSIZE, and WM_CREATE messages to the window being created.

For information about the window control classes, window styles, and control styles used with this function, see the description of the CreateWindow function.

Windows 95 only: The system can support a maximum of 16,364 window handles.

See Also

CLIENTCREATESTRUCT, CREATESTRUCT, CreateWindow, GlobalAddAtom, RegisterClass, SetWindowPos, WM_CREATE, WM_NCCALCSIZE, WM_NCCREATE, WM_PAINT, WM_PARENTNOTIFY


CreateWindowStation [New - Windows NT]
 CreateWindowStation  QuickInfo  Overview  Group

[New - Windows NT]

The CreateWindowStation function creates a window station object. It returns 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,	// name of the new window station
DWORD dwReserved,	// reserved; must be NULL
DWORD dwDesiredAccess	// specifies access of returned handle
LPSECURITY_ATTRIBUTES lpsa,	// specifies security attributes of the window station
);
Parameters

lpwinsta

Optionally points 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 NULL.

dwDesiredAccess

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

Points to a SECURITY_ATTRIBUTES structure that specifies the security attributes for the window station.

If either lpsa or lpsa->lpSecurityDescriptor is NULL, the window station is assigned a security descriptor that grants GENERIC_ALL access to all users for the window station and any desktops created within the window station, and the resulting handle is not inheritable.

Return Value

If the function succeeds, the return value is the handle to the newly created window station.

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

See Also

GetUserObjectInformation, OpenWindowStation


DdeAbandonTransaction
 DdeAbandonTransaction  QuickInfo  Overview  Group

The DdeAbandonTransaction function abandons the specified asynchronous transaction and releases all resources associated with the transaction.

BOOL DdeAbandonTransaction(

DWORD  idInst,	// instance identifier
HCONV  hConv,	// handle of conversation
DWORD  idTransaction	// transaction identifier
);
Parameters

idInst

Specifies the application instance identifier obtained by a previous call to the DdeInitialize function.

hConv

Identifies the conversation in which the transaction was initiated. If this parameter is 0L, all transactions are abandoned (that is, the idTransaction parameter is ignored).

idTransaction

Specifies the identifier of the transaction to abandon. If this parameter is 0L, all active transactions in the specified conversation are abandoned.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Errors

The DdeGetLastError function can be used to get the error value, which may be one of the following values:

DMLERR_DLL_NOT_INITIALIZED
DMLERR_INVALIDPARAMETER
DMLERR_NO_ERROR
DMLERR_UNFOUND_QUEUE_ID

Remarks

Only a dynamic data exchange (DDE) client application should call DdeAbandonTransaction. If the server application responds to the transaction after the client has called DdeAbandonTransaction, the system discards the transaction results. This function has no effect on synchronous transactions.

See Also

DdeClientTransaction, DdeInitialize, DdeQueryConvInfo


DdeAccessData
 DdeAccessData  QuickInfo  Overview  Group

The DdeAccessData function provides access to the data in the specified dynamic data exchange (DDE) object. An application must call the DdeUnaccessData function when it has finished accessing the data in the object.

LPBYTE DdeAccessData(

HDDEDATA  hData,	// handle of DDE object
LPDWORD  pcbDataSize	// address of variable that receives data length
);
Parameters

hData

Identifies the DDE object to access.

pcbDataSize

Points to a variable that receives the size, in bytes, of the DDE object identified by the hData parameter. If this parameter is NULL, no size information is returned.

Return Value

If the function succeeds, the return value is a pointer to the first byte of data in the DDE object.

If the function fails, the return value is NULL.

Errors

The DdeGetLastError function can be used to get the error value, which may be one of the following values:

DMLERR_DLL_NOT_INITIALIZED
DMLERR_INVALIDPARAMETER
DMLERR_NO_ERROR

Remarks

If the hData parameter has not been passed to a Dynamic Data Exchange Management Library (DDEML) function, an application can use the pointer returned by DdeAccessData for read-write access to the DDE object. If hData has already been passed to a DDEML function, the pointer should be used only for read access to the memory object.

See Also

DdeAddData, DdeCreateDataHandle, DdeFreeDataHandle, DdeUnaccessData


DdeAddData
 DdeAddData  QuickInfo  Overview  Group

The DdeAddData function adds data to the specified dynamic data exchange (DDE) object. An application can add data starting at any offset from the beginning of the object. If new data overlaps data already in the object, the new data overwrites the old data in the bytes where the overlap occurs. The contents of locations in the object that have not been written to are undefined.

HDDEDATA DdeAddData(

HDDEDATA  hData,	// handle of DDE data object
LPBYTE  pSrc,	// address of source buffer
DWORD  cb,	// length of data
DWORD  cbOff	// offset within DDE data object
);
Parameters

hData

Identifies the DDE object that receives additional data.

pSrc

Points to a buffer containing the data to add to the DDE object.

cb

Specifies the length, in bytes, of the data to be added to the DDE object.

cbOff

Specifies an offset, in bytes, from the beginning of the DDE object. The additional data is copied to the object beginning at this offset.

Return Value

If the function succeeds, the return value is a new handle of the DDE object. The new handle is used in all references to the object.

If the function fails, the return value is zero.

Errors

The DdeGetLastError function can be used to get the error value, which may be one of the following values:

DMLERR_DLL_NOT_INITIALIZED
DMLERR_INVALIDPARAMETER
DMLERR_MEMORY_ERROR
DMLERR_NO_ERROR

Remarks

After a data handle has been used as a parameter in another Dynamic Data Exchange Management Library function or has been returned by a DDE callback function, the handle may be used only for read access to the DDE object identified by the handle.

If the amount of memory originally allocated is less than is needed to hold the added data, DdeAddData reallocates a global memory object of the appropriate size.

See Also

DdeAccessData, DdeCreateDataHandle, DdeUnaccessData


DdeCallback
 DdeCallback  QuickInfo  Overview  Group

The DdeCallback function is an application-defined callback function that processes dynamic data exchange (DDE) transactions sent to the function in response to Dynamic Data Exchange Management Library (DDEML) calls by other applications.

HDDEDATA CALLBACK DdeCallback(

UINT  uType,	// transaction type
UINT  uFmt,	// clipboard data format
HCONV  hconv,	// handle of the conversation
HSZ  hsz1,	// handle of a string
HSZ  hsz2,	// handle of a string
HDDEDATA  hdata,	// handle of a global memory object
DWORD  dwData1,	// transaction-specific data
DWORD  dwData2	// transaction-specific data
);
Parameters

uType

Specifies the type of the current transaction. This parameter consists of a combination of transaction class flags and transaction type flags. The following table describes each of the transaction classes and provides a list of the transaction types in each class. For information about a specific transaction type, see the individual description of that type.

Class	Meaning
XCLASS_BOOL	A DDE callback function should return TRUE or FALSE when it finishes processing a transaction that belongs to this class. The XCLASS_BOOL transaction class consists of the following types:
	XTYP_ADVSTART XTYP_CONNECT
XCLASS_DATA	A DDE callback function should return a DDE handle, the CBR_BLOCK return code, or NULL when it finishes processing a transaction that belongs to this class. The XCLASS_DATA transaction class consists of the following types:
	XTYP_ADVREQ XTYP_REQUEST XTYP_WILDCONNECT
XCLASS_FLAGS	A DDE callback function should return DDE_FACK, DDE_FBUSY, or DDE_FNOTPROCESSED when it finishes processing a transaction that belongs to this class. The XCLASS_FLAGS transaction class consists of the following types:
	XTYP_ADVDATA XTYP_EXECUTE XTYP_POKE
XCLASS_NOTIFICATION	The transaction types that belong to this class are for notification purposes only. The return value from the callback function is ignored. The XCLASS_NOTIFICATION transaction class consists of the following types: XTYP_ADVSTOP XTYP_CONNECT_CONFIRM XTYP_DISCONNECT XTYP_ERROR XTYP_MONITOR XTYP_REGISTER XTYP_XACT_COMPLETE XTYP_UNREGISTER
uFmt

Specifies the format in which data is sent or received.

hconv

Identifies the conversation associated with the current transaction.

hsz1

Identifies a string. The meaning of this parameter depends on the type of the current transaction. For the meaning of this parameter, see the description of the transaction type.

hsz2

Identifies a string. The meaning of this parameter depends on the type of the current transaction. For the meaning of this parameter, see the description of the transaction type.

hdata

Identifies DDE data. The meaning of this parameter depends on the type of the current transaction. For the meaning of this parameter, see the description of the transaction type.

dwData1

Specifies transaction-specific data. For the meaning of this parameter, see the description of the transaction type.

dwData2

Specifies transaction-specific data. For the meaning of this parameter, see the description of the transaction type.

Return Value

The return value depends on the transaction class. For more information about the return values, see descriptions of the individual transaction types.

Remarks

The callback function is called asynchronously for transactions that do not involve the creation or termination of conversations. An application that does not frequently accept incoming messages will have reduced DDE performance because the DDEML uses messages to initiate transactions.

An application must register the callback function by specifying a pointer to the function in a call to the DdeInitialize function.

DdeCallback is a placeholder for the application-defined or library-defined function name.

See Also

DdeEnableCallback, DdeInitialize


DdeClientTransaction
 DdeClientTransaction  QuickInfo  Overview  Group

The DdeClientTransaction function begins a data transaction between a client and a server. Only a dynamic data exchange (DDE) client application can call this function, and the application can use it only after establishing a conversation with the server.

HDDEDATA DdeClientTransaction(

LPBYTE  pData,	// address of data to pass to server
DWORD  cbData,	// length of data
HCONV  hConv,	// handle of conversation
HSZ  hszItem,	// handle of item name string
UINT  wFmt,	// clipboard data format
UINT  wType,	// transaction type
DWORD  dwTimeout,	// time-out duration
LPDWORD  pdwResult	// address of transaction result
);
Parameters

pData

Points to the beginning of the data the client must pass to the server.

Optionally, an application can specify the data handle (HDDEDATA) to pass to the server and in that case the cbData parameter should be set to 0xFFFFFFFF. This parameter is required only if the wType parameter is XTYP_EXECUTE or XTYP_POKE. Otherwise, this parameter should be NULL.

For the optional usage of this parameter, XTYP_POKE transactions where pData is a data handle, the handle must have been created by a previous call to the DdeCreateDataHandle function, employing the same data format specified in the wFmt parameter.

cbData

Specifies the length, in bytes, of the data pointed to by the pData parameter. A value of 0xFFFFFFFF indicates that pData is a data handle that identifies the data being sent.

hConv

Identifies the conversation in which the transaction is to take place.

hszItem

Identifies the data item for which data is being exchanged during the transaction. This handle must have been created by a previous call to the DdeCreateStringHandle function. This parameter is ignored (and should be set to 0L) if the wType parameter is XTYP_EXECUTE.

wFmt

Specifies the standard clipboard format in which the data item is being submitted or requested.

If the transaction specified by the wType parameter does not pass data or is XTYP_EXECUTE, this parameter should be zero.

If the transaction specified by the wType parameter references non-execute DDE data (XTYP_POKE, XTYP_ADVSTART, XTYP_ADVSTOP, XTYP_REQUEST), the wFmt value must be either a valid predefined (CF_) DDE format or a valid registered clipboard format.

wType

Specifies the transaction type. This parameter can be one of the following types:

Type	Meaning
XTYP_ADVSTART	Begins an advise loop. Any number of distinct advise loops can exist within a conversation. An application can alter the advise loop type by combining the XTYP_ADVSTART transaction type with one or more of the following flags:
Flag	Meaning
XTYPF_NODATA	Instructs the server to notify the client of any data changes without actually sending the data. This flag gives the client the option of ignoring the notification or requesting the changed data from the server.
XTYPF_ACKREQ	Instructs the server to wait until the client acknowledges that it received the previous data item before sending the next data item. This flag prevents a fast server from sending data faster than the client can process it.
XTYP_ADVSTOP	Ends an advise loop.
XTYP_EXECUTE	Begins an execute transaction.
XTYP_POKE	Begins a poke transaction.
XTYP_REQUEST	Begins a request transaction.
dwTimeout

Specifies the maximum length of time, in milliseconds, that the client will wait for a response from the server application in a synchronous transaction. This parameter should be TIMEOUT_ASYNC for asynchronous transactions.

pdwResult

Points to a variable that receives the result of the transaction. An application that does not check the result can use NULL for this value. For synchronous transactions, the low-order word of this variable contains any applicable DDE_ flags resulting from the transaction. This provides support for applications dependent on DDE_APPSTATUS bits. It is, however, recommended that applications no longer use these bits because they may not be supported in future versions of the Dynamic Data Exchange Management Library (DDEML). For asynchronous transactions, this variable is filled with a unique transaction identifier for use with the DdeAbandonTransaction function and the XTYP_XACT_COMPLETE transaction.

Return Value

If the function succeeds, the return value is a data handle that identifies the data for successful synchronous transactions in which the client expects data from the server. The return value is nonzero for successful asynchronous transactions and for synchronous transactions in which the client does not expect data. The return value is zero for all unsuccessful transactions.

Errors

The DdeGetLastError function can be used to get the error value, which may be one of the following values:

DMLERR_ADVACKTIMEOUT
DMLERR_BUSY
DMLERR_DATAACKTIMEOUT
DMLERR_DLL_NOT_INITIALIZED
DMLERR_EXECACKTIMEOUT
DMLERR_INVALIDPARAMETER
DMLERR_MEMORY_ERROR
DMLERR_NO_CONV_ESTABLISHED
DMLERR_NO_ERROR
DMLERR_NOTPROCESSED
DMLERR_POKEACKTIMEOUT
DMLERR_POSTMSG_FAILED
DMLERR_REENTRANCY
DMLERR_SERVER_DIED
DMLERR_UNADVACKTIMEOUT

Remarks

When an application has finished using the data handle returned by DdeClientTransaction, the application should free the handle by calling the DdeFreeDataHandle function.

Transactions can be synchronous or asynchronous. During a synchronous transaction, DdeClientTransaction does not return until the transaction either completes successfully or fails. Synchronous transactions cause a client to enter a modal loop while waiting for various asynchronous events. Because of this, a client application can still respond to user input while waiting on a synchronous transaction, but the application cannot begin a second synchronous transaction because of the activity associated with the first. DdeClientTransaction fails if any instance of the same task has a synchronous transaction already in progress.

During an asynchronous transaction, DdeClientTransaction returns after the transaction has begun, passing a transaction identifier for reference. When the server's DDE callback function finishes processing an asynchronous transaction, the system sends an XTYP_XACT_COMPLETE transaction to the client. This transaction provides the client with the results of the asynchronous transaction that it initiated by calling DdeClientTransaction. A client application can choose to abandon an asynchronous transaction by calling the DdeAbandonTransaction function.

See Also

DdeAbandonTransaction, DdeAccessData, DdeConnect, DdeConnectList, DdeCreateDataHandle, DdeCreateStringHandle, DdeFreeDataHandle, XTYP_ADVSTART, XTYP_ADVSTOP, XTYP_EXECUTE, XTYP_POKE, XTYP_REQUEST


DdeCmpStringHandles
 DdeCmpStringHandles  QuickInfo  Overview  Group

The DdeCmpStringHandles function compares the values of two string handles. The value of a string handle is not related to the case of the associated string.

int DdeCmpStringHandles(

HSZ  hsz1,	// handle of first string
HSZ  hsz2	// handle of second string
);
Parameters

hsz1

Identifies the first string.

hsz2

Identifies the second string.

Return Value

The return value can be one of the following values:

Value	Meaning
−1	The value of hsz1 is either 0 or less than the value of hsz2.
0	The values of hsz1 and hsz2 are equal (both can be 0).
1	The value of hsz2 is either 0 or less than the value of hsz1.
Remarks

An application that must do a case-sensitive comparison of two string handles should compare the string handles directly. An application should use DdeCmpStringHandles for all other comparisons to preserve the case-insensitive nature of dynamic data exchange (DDE).

DdeCmpStringHandles cannot be used to sort string handles alphabetically.

See Also

DdeAccessData, DdeCreateStringHandle, DdeFreeStringHandle


DdeConnect
 DdeConnect  QuickInfo  Overview  Group

The DdeConnect function establishes a conversation with a server application that supports the specified service name and topic name pair. If more than one such server exists, the system selects only one.

HCONV DdeConnect(

DWORD  idInst,	// instance identifier
HSZ  hszService,	// handle of service name string
HSZ  hszTopic,	// handle of topic name string
PCONVCONTEXT  pCC	// address of structure with context data
);
Parameters

idInst

Specifies the application instance identifier obtained by a previous call to the DdeInitialize function.

hszService

Identifies the string that specifies the service name of the server application with which a conversation is to be established. This handle must have been created by a previous call to the DdeCreateStringHandle function. If this parameter is 0L, a conversation is established with any available server.

hszTopic

Identifies the string that specifies the name of the topic on which a conversation is to be established. This handle must have been created by a previous call to DdeCreateStringHandle. If this parameter is 0L, a conversation on any topic supported by the selected server is established.

pCC

Points to the CONVCONTEXT structure that contains conversation context information. If this parameter is NULL, the server receives the default CONVCONTEXT structure during the XTYP_CONNECT or XTYP_WILDCONNECT transaction.

Return Value

If the function succeeds, the return value is the handle of the established conversation.

If the function fails, the return value is 0L.

Errors

The DdeGetLastError function can be used to get the error value, which may be one of the following values:

DMLERR_DLL_NOT_INITIALIZED
DMLERR_INVALIDPARAMETER
DMLERR_NO_CONV_ESTABLISHED
DMLERR_NO_ERROR

Remarks

The client application cannot make assumptions regarding the server selected. If an instance-specific name is specified in the hszService parameter, a conversation is established with only the specified instance. Instance-specific service names are passed to an application's dynamic data exchange (DDE) callback function during the XTYP_REGISTER and XTYP_UNREGISTER transactions.

All members of the default CONVCONTEXT structure are set to zero except cb, which specifies the size of the structure, and iCodePage, which specifies CP_WINANSI (the default code page) or CP_WINUNICODE, depending on whether the ANSI or Unicode version of the DdeInitialize function was called by the client application.

See Also

CONVCONTEXT, DdeConnectList, DdeCreateStringHandle, DdeDisconnect, DdeDisconnectList, DdeInitialize, XTYP_REGISTER, XTYP_UNREGISTER


DdeConnectList
 DdeConnectList  QuickInfo  Overview  Group

The DdeConnectList function establishes a conversation with all server applications that support the specified service name and topic name pair. An application can also use this function to obtain a list of conversation handles by passing the function an existing conversation handle. The Dynamic Data Exchange Management Library removes the handles of any terminated conversations from the conversation list. The resulting conversation list contains the handles of all currently established conversations that support the specified service name and topic name.

HCONVLIST DdeConnectList(

DWORD  idInst,	// instance identifier
HSZ  hszService,	// handle of service name string
HSZ  hszTopic,	// handle of topic name string
HCONVLIST  hConvList,	// handle of conversation list
PCONVCONTEXT  pCC	// address of structure with context data
);
Parameters

idInst

Specifies the application instance identifier obtained by a previous call to the DdeInitialize function.

hszService

Identifies the string that specifies the service name of the server application with which a conversation is to be established. If this parameter is 0L, the system attempts to establish conversations with all available servers that support the specified topic name.

hszTopic

Identifies the string that specifies the name of the topic on which a conversation is to be established. This handle must have been created by a previous call to the DdeCreateStringHandle function. If this parameter is 0L, the system will attempt to establish conversations on all topics supported by the selected server (or servers).

hConvList

Identifies the conversation list to be enumerated. This parameter should be 0L if a new conversation list is to be established.

pCC

Points to the CONVCONTEXT structure that contains conversation-context information. If this parameter is NULL, the server receives the default CONVCONTEXT structure during the XTYP_CONNECT or XTYP_WILDCONNECT transaction.

Return Value

If the function succeeds, the return value is the handle of a new conversation list.

If the function fails, the return value is 0L. The handle of the old conversation list is no longer valid.

Errors

The DdeGetLastError function can be used to get the error value, which may be one of the following values:

DMLERR_DLL_NOT_INITIALIZED
DMLERR_INVALID_PARAMETER
DMLERR_NO_CONV_ESTABLISHED
DMLERR_NO_ERROR
DMLERR_SYS_ERROR

Remarks

An application must free the conversation list handle returned by this function, regardless of whether any conversation handles within the list are active. To free the handle, an application can call the DdeDisconnectList function.

All members of the default CONVCONTEXT structure are set to zero except cb, specifying the size of the structure, and iCodePage, specifying CP_WINANSI (the default code page) or CP_WINUNICODE, depending on whether the ANSI or Unicode version of the DdeInitialize function was called by the client application.

See Also

CONVCONTEXT, DdeConnect, DdeCreateStringHandle, DdeDisconnect, DdeDisconnectList, DdeInitialize, DdeQueryNextServer


DdeCreateDataHandle
 DdeCreateDataHandle  QuickInfo  Overview  Group

The DdeCreateDataHandle function creates a dynamic data exchange (DDE) object and fills the object with data from the specified buffer. A DDE application uses this function during transactions that involve passing data to the partner application.

HDDEDATA DdeCreateDataHandle(

DWORD  idInst,	// instance identifier
LPBYTE  pSrc,	// address of source buffer
DWORD  cb,	// length of DDE object
DWORD  cbOff,	// offset from beginning of source buffer
HSZ  hszItem,	// handle of item name string
UINT  wFmt,	// clipboard data format
UINT  afCmd	// creation flags
);
Parameters

idInst

Specifies the application instance identifier obtained by a previous call to the DdeInitialize function.

pSrc

Points to a buffer that contains data to be copied to the DDE object. If this parameter is NULL, no data is copied to the object.

cb

Specifies the amount of memory, in bytes, to allocate for the DDE object. If this parameter is zero, the pSrc parameter is ignored.

cbOff

Specifies an offset, in bytes, from the beginning of the buffer pointed to by the pSrc parameter. The data beginning at this offset is copied from the buffer to the DDE object.

hszItem

Identifies the string that specifies the data item corresponding to the DDE object. This handle must have been created by a previous call to the DdeCreateStringHandle function. If the data handle is to be used in an XTYP_EXECUTE transaction, this parameter must be 0L.

wFmt

Specifies the standard clipboard format of the data.

afCmd

Specifies the creation flags. This parameter can be HDATA_APPOWNED, which specifies that the server application calling the DdeCreateDataHandle function owns the data handle this function creates. This flag enables the application to share the data handle with other Dynamic Data Exchange Management Library (DDEML) applications rather than creating a separate handle to pass to each application. If this flag is specified, the application must eventually free the shared memory object associated with the handle by using the DdeFreeDataHandle function. If this flag is not specified, the handle becomes invalid in the application that created the handle after the data handle is returned by the application's DDE callback function or is used as a parameter in another DDEML function.

Return Value

If the function succeeds, the return value is a data handle.

If the function fails, the return value is 0L.

Errors

The DdeGetLastError function can be used to get the error value, which may be one of the following values:

DMLERR_DLL_NOT_INITIALIZED
DMLERR_INVALIDPARAMETER
DMLERR_MEMORY_ERROR
DMLERR_NO_ERROR

Remarks

Any unfilled locations in the DDE object are undefined.

After a data handle has been used as a parameter in another DDEML function or has been returned by a DDE callback function, the handle may be used only for read access to the DDE object identified by the handle.

See Also

DdeAccessData, DdeCreateStringHandle, DdeFreeDataHandle, DdeGetData, DdeInitialize


DdeCreateStringHandle
 DdeCreateStringHandle  QuickInfo  Overview  Group

The DdeCreateStringHandle function creates a handle that identifies the string pointed to by the psz parameter. A dynamic data exchange (DDE) client or server application can pass the string handle as a parameter to other Dynamic Data Exchange Management Library (DDEML) functions.

HSZ DdeCreateStringHandle(

DWORD  idInst,	// instance identifier
LPTSTR  psz,	// address of null-terminated string
int  iCodePage	// code page identifier
);
Parameters

idInst

Specifies the application instance identifier obtained by a previous call to the DdeInitialize function.

psz

Points to a buffer that contains the null-terminated string for which a handle is to be created. This string may be of any length.

iCodePage

Specifies the code page used to render the string. This value should be either CP_WINANSI (the default code page) or CP_WINUNICODE, depending on whether the ANSI or Unicode version of DdeInitialize was called by the client application.

Return Value

If the function succeeds, the return value is a string handle.

If the function fails, the return value is 0L.

Errors

The DdeGetLastError function can be used to get the error value, which may be one of the following values:

DMLERR_INVALIDPARAMETER
DMLERR_NO_ERROR
DMLERR_SYS_ERROR

Remarks

The value of a string handle is not related to the case of the string it identifies.

When an application either creates a string handle or receives one in the callback function and then uses the DdeKeepStringHandle function to keep it, the application must free that string handle when it is no longer needed.

An instance-specific string handle cannot be mapped from string handle to string and back to string handle. This is shown in the following example, in which the DdeQueryString function creates a string from a string handle and DdeCreateStringHandle creates a string handle from that string, but the two handles are not the same:

DWORD idInst;

DWORD cb;

HSZ hszInst, hszNew;

PSZ pszInst;

DdeQueryString(idInst, hszInst, pszInst, cb, CP_WINANSI);

hszNew = DdeCreateStringHandle(idInst, pszInst, CP_WINANSI);

// hszNew != hszInst !

See Also

DdeAccessData, DdeCmpStringHandles, DdeFreeStringHandle, DdeInitialize, DdeKeepStringHandle, DdeQueryString


DdeDisconnect
 DdeDisconnect  QuickInfo  Overview  Group

The DdeDisconnect function terminates a conversation started by either the DdeConnect or DdeConnectList function and invalidates the specified conversation handle.

BOOL DdeDisconnect(

HCONV  hConv	// handle of conversation
);
Parameters

hConv

Identifies the active conversation to be terminated.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Errors

The DdeGetLastError function can be used to get the error value, which may be one of the following values:

DMLERR_DLL_NOT_INITIALIZED
DMLERR_NO_CONV_ESTABLISHED
DMLERR_NO_ERROR

Remarks

Any incomplete transactions started before calling DdeDisconnect are immediately abandoned. The XTYP_DISCONNECT transaction is sent to the dynamic data exchange (DDE) callback function of the partner in the conversation. Generally, only client applications must terminate conversations.

See Also

DdeConnect, DdeConnectList, DdeDisconnectList, XTYP_DISCONNECT


DdeDisconnectList
 DdeDisconnectList  QuickInfo  Overview  Group

The DdeDisconnectList function destroys the specified conversation list and terminates all conversations associated with the list.

BOOL DdeDisconnectList(

HCONVLIST  hConvList	// handle of conversation list
);
Parameters

hConvList

Identifies the conversation list. This handle must have been created by a previous call to the DdeConnectList function.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Errors

The DdeGetLastError function can be used to get the error value, which may be one of the following values:

DMLERR_DLL_NOT_INITIALIZED
DMLERR_INVALIDPARAMETER
DMLERR_NO_ERROR

Remarks

An application can use the DdeDisconnect function to terminate individual conversations in the list.

See Also

DdeConnect, DdeConnectList, DdeDisconnect


DdeEnableCallback
 DdeEnableCallback  QuickInfo  Overview  Group

The DdeEnableCallback function enables or disables transactions for a specific conversation or for all conversations currently established by the calling application.

After disabling transactions for a conversation, the operating system places the transactions for that conversation in a transaction queue associated with the application. The application should reenable the conversation as soon as possible to avoid losing queued transactions.

BOOL DdeEnableCallback(

DWORD  idInst,	// instance identifier
HCONV  hConv,	// handle of conversation
UINT  wCmd	// enable or disable function code
);
Parameters

idInst

Specifies the application-instance identifier obtained by a previous call to the DdeInitialize function.

hConv

Identifies the conversation to enable or disable. If this parameter is NULL, the function affects all conversations.

wCmd

Specifies the function code. This parameter can be one of the following values:

Value	Meaning
EC_ENABLEALL	Enables all transactions for the specified conversation.
EC_ENABLEONE	Enables one transaction for the specified conversation.
EC_DISABLE	Disables all blockable transactions for the specified conversation. A server application can disable the following transactions: XTYP_ADVSTART XTYP_ADVSTOP XTYP_EXECUTE XTYP_POKE XTYP_REQUEST A client application can disable the following transactions: XTYP_ADVDATA XTYP_XACT_COMPLETE
EC_QUERYWAITING	Determines whether any transactions are in the queue for the specified conversation.
Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

If the wCmd parameter is EC_QUERYWAITING, and the application transaction queue contains one or more unprocessed transactions that are not being processed, the return value is TRUE; otherwise, it is FALSE.

Errors

Use the DdeGetLastError function to retrieve the error value, which may be one of the following:

DMLERR_DLL_NOT_INITIALIZED
DMLERR_NO_ERROR
DMLERR_INVALIDPARAMETER

Remarks

An application can disable transactions for a specific conversation by returning the CBR_BLOCK return code from its dynamic data exchange (DDE) callback function. When you reenable the conversation by using the DdeEnableCallback function, the operating system generates the same transaction that was in process when the conversation was disabled.

Using the EC_QUERYWAITING flag does not change the enable state of the conversation and does not cause transactions to be issued within the context of the call to DdeEnableCallback.

If DdeEnableCallback is called with EC_QUERYWAITING and the return value is TRUE, an application should try to quickly allow message processing, return from its callback, or enable callbacks. Such a result does not guarantee that subsequent callbacks will be made. Calling DdeEnableCallback with EC_QUERYWAITING lets an application with blocked callbacks determine whether there are any transactions pending on the blocked conversation. Of course, even if such a call returns false, an application should always process messages in a timely manner.

See Also

DdeConnect, DdeConnectList, DdeDisconnect, DdeInitialize


DdeFreeDataHandle
 DdeFreeDataHandle  QuickInfo  Overview  Group

The DdeFreeDataHandle function frees a dynamic data exchange (DDE) object and deletes the data handle associated with the object.

BOOL DdeFreeDataHandle(

HDDEDATA  hData	// handle of DDE object
);
Parameters

hData

Identifies the DDE object to be freed. This handle must have been created by a previous call to the DdeCreateDataHandle function or returned by the DdeClientTransaction function.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Errors

The DdeGetLastError function can be used to get the error value, which may be one of the following values:

DMLERR_INVALIDPARAMETER
DMLERR_NO_ERROR

Remarks

An application must call DdeFreeDataHandle under the following circumstances:

•	To free a DDE object that the application allocated by calling the DdeCreateDataHandle function if the object's data handle was never passed by the application to another Dynamic Data Exchange Management Library (DDEML) function

•	To free a DDE object that the application allocated by specifying the HDATA_APPOWNED flag in a call to DdeCreateDataHandle

•	To free a DDE object whose handle the application received from the DdeClientTransaction function

The system automatically frees an unowned object when its handle is returned by a DDE callback function or is used as a parameter in a DDEML function.

See Also

DdeAccessData, DdeCreateDataHandle, DdeClientTransaction


DdeFreeStringHandle
 DdeFreeStringHandle  QuickInfo  Overview  Group

The DdeFreeStringHandle function frees a string handle in the calling application.

BOOL DdeFreeStringHandle(

DWORD  idInst,	// instance identifier
HSZ  hsz	// handle of string
);
Parameters

idInst

Specifies the application instance identifier obtained by a previous call to the DdeInitialize function.

hsz

Identifies the string handle to be freed. This handle must have been created by a previous call to the DdeCreateStringHandle function.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

An application can free string handles it creates with DdeCreateStringHandle but should not free those that the system passed to the application's dynamic data exchange (DDE) callback function or those returned in the CONVINFO structure by the DdeQueryConvInfo function.

See Also

CONVINFO, DdeCmpStringHandles, DdeCreateStringHandle, DdeInitialize, DdeKeepStringHandle, DdeQueryConvInfo, DdeQueryString


DdeGetData
 DdeGetData  QuickInfo  Overview  Group

The DdeGetData function copies data from the specified dynamic data exchange (DDE) object to the specified local buffer.

DWORD DdeGetData(

HDDEDATA  hData,	// handle of DDE  object
LPBYTE  pDst,	// address of destination buffer
DWORD  cbMax,	// amount of data to copy
DWORD  cbOff	// offset to beginning of data
);
Parameters

hData

Identifies the DDE object that contains the data to copy.

pDst

Points to the buffer that receives the data. If this parameter is NULL, the DdeGetData function returns the amount of data, in bytes, that would be copied to the buffer.

cbMax

Specifies the maximum amount of data, in bytes, to copy to the buffer pointed to by the pDst parameter. Typically, this parameter specifies the length of the buffer pointed to by pDst.

cbOff

Specifies an offset within the DDE object. Data is copied from the object beginning at this offset.

Return Value

If the pDst parameter points to a buffer, the return value is the size, in bytes, of the memory object associated with the data handle or the size specified in the cbMax parameter, whichever is lower.

If the pDst parameter is NULL, the return value is the size, in bytes, of the memory object associated with the data handle.

Errors

The DdeGetLastError function can be used to get the error value, which may be one of the following values:

DMLERR_DLL_NOT_INITIALIZED
DMLERR_INVALIDPARAMETER
DMLERR_NO_ERROR

See Also

DdeAccessData, DdeCreateDataHandle, DdeFreeDataHandle


DdeGetLastError
 DdeGetLastError  QuickInfo  Overview  Group

The DdeGetLastError function returns the most recent error value set by the failure of a Dynamic Data Exchange Management Library (DDEML) function and resets the error value to DMLERR_NO_ERROR.

UINT DdeGetLastError(

DWORD  idInst	// instance identifier
);
Parameters

idInst

Specifies the application instance identifier obtained by a previous call to the DdeInitialize function.

Return Value

If the function succeeds, the return value is the last error value. Following are the possible DDEML error values:

Value	Meaning
DMLERR_ADVACKTIMEOUT	A request for a synchronous advise transaction has timed out.
DMLERR_BUSY	The response to the transaction caused the DDE_FBUSY flag to be set.
DMLERR_DATAACKTIMEOUT	A request for a synchronous data transaction has timed out.
DMLERR_DLL_NOT_INITIALIZED	A DDEML function was called without first calling the DdeInitialize function, or an invalid instance identifier was passed to a DDEML function.
DMLERR_DLL_USAGE	An application initialized as APPCLASS_MONITOR has attempted to perform a dynamic data exchange (DDE) transaction, or an application initialized as APPCMD_CLIENTONLY has attempted to perform server transactions.
DMLERR_EXECACKTIMEOUT	A request for a synchronous execute transaction has timed out.
DMLERR_INVALIDPARAMETER	A parameter failed to be validated by the DDEML. Some of the possible causes follow:
	The application used a data handle initialized with a different item name handle than was required by the transaction. The application used a data handle that was initialized with a different clipboard data format than was required by the transaction. The application used a client-side conversation handle with a server-side function or vice versa. The application used a freed data handle or string handle. More than one instance of the application used the same object.
DMLERR_LOW_MEMORY	A DDEML application has created a prolonged race condition (in which the server application outruns the client), causing large amounts of memory to be consumed.
DMLERR_MEMORY_ERROR	A memory allocation has failed.
DMLERR_NO_CONV_ESTABLISHED	A client's attempt to establish a conversation has failed.
DMLERR_NOTPROCESSED	A transaction has failed.
DMLERR_POKEACKTIMEOUT	A request for a synchronous poke transaction has timed out.
DMLERR_POSTMSG_FAILED	An internal call to the PostMessage function has failed.
DMLERR_REENTRANCY	An application instance with a synchronous transaction already in progress attempted to initiate another synchronous transaction, or the DdeEnableCallback function was called from within a DDEML callback function.
DMLERR_SERVER_DIED	A server-side transaction was attempted on a conversation terminated by the client, or the server terminated before completing a transaction.
DMLERR_SYS_ERROR	An internal error has occurred in the DDEML.
DMLERR_UNADVACKTIMEOUT	A request to end an advise transaction has timed out.
DMLERR_UNFOUND_QUEUE_ID	An invalid transaction identifier was passed to a DDEML function. Once the application has returned from an XTYP_XACT_COMPLETE callback, the transaction identifier for that callback function  is no longer valid.
See Also

DdeEnableCallback, DdeInitialize, PostMessage


DdeImpersonateClient
 DdeImpersonateClient  QuickInfo  Overview  Group

The DdeImpersonateClient function impersonates a dynamic data exchange (DDE) client application in a DDE client conversation.

BOOL DdeImpersonateClient(

HCONV  hConv	// handle of DDE conversation
);
Parameters

hConv

Identifies the DDE client conversation to be impersonated.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

Impersonation is the ability of a process to take on the security attributes of another process. When a client in a DDE conversation requests information from a DDE server, the server impersonates the client. When the server requests access to an object, the system verifies the access against the client's security attributes.

When the impersonation is complete, the server normally calls the RevertToSelf function.

See Also

ImpersonateNamedPipeClient, RevertToSelf


DdeInitialize
 DdeInitialize  QuickInfo  Overview  Group

The DdeInitialize function registers an application with the Dynamic Data Exchange Management Library (DDEML). An application must call this function before calling any other DDEML function.

UINT DdeInitialize(

LPDWORD  pidInst,	// address of instance identifier
PFNCALLBACK  pfnCallback,	// address of callback function
DWORD  afCmd,	// set of command and filter flags
DWORD  ulRes	// reserved
);
Parameters

pidInst

Points to the application instance identifier. At initialization, this parameter should point to 0. If the function succeeds, this parameter points to the instance identifier for the application. This value should be passed as the idInst parameter in all other DDEML functions that require it. If an application uses multiple instances of the DDEML dynamic-link library (DLL), the application should provide a different callback function for each instance.

If pidInst points to a nonzero value, reinitialization of the DDEML is implied. In this case, pidInst must point to a valid application-instance identifier.

pfnCallback

Points to the application-defined dynamic data exchange (DDE) callback function. This function processes DDE transactions sent by the system. For more information, see the DdeCallback callback function.

afCmd

Specifies a set of APPCMD_, CBF_, and MF_ flags. The APPCMD_ flags provide special instructions to DdeInitialize. The CBF_ flags specify filters that prevent specific types of transactions from reaching the callback function. The MF_ flags specify the types of DDE activity that a DDE monitoring application monitors. Using these flags enhances the performance of a DDE application by eliminating unnecessary calls to the callback function.

This parameter can be a combination of the following filter flags:

Flag	Meaning
APPCLASS_MONITOR	Makes it possible for the application to monitor DDE activity in the system. This flag is for use by DDE monitoring applications. The application specifies the types of DDE activity to monitor by combining one or more monitor flags with the APPCLASS_MONITOR flag. For details, see the following Remarks section.
APPCLASS_STANDARD	Registers the application as a standard (nonmonitoring) DDEML application.
APPCMD_CLIENTONLY	Prevents the application from becoming a server in a DDE conversation. The application can only be a client. This flag reduces consumption of resources by the DDEML. It includes the functionality of the CBF_FAIL_ALLSVRXACTIONS flag.
APPCMD_FILTERINITS	Prevents the DDEML from sending XTYP_CONNECT and XTYP_WILDCONNECT transactions to the application until the application has created its string handles and registered its service names or has turned off filtering by a subsequent call to the DdeNameService or DdeInitialize function. This flag is always in effect when an application calls DdeInitialize for the first time, regardless of whether the application specifies the flag. On subsequent calls to DdeInitialize, not specifying this flag turns off the application's service-name filters, but specifying it turns on the application's service name filters.
CBF_FAIL_ALLSVRXACTIONS	Prevents the callback function from receiving server transactions. The system returns DDE_FNOTPROCESSED to each client that sends a transaction to this application. This flag is equivalent to combining all CBF_FAIL_ flags.
CBF_FAIL_ADVISES	Prevents the callback function from receiving XTYP_ADVSTART and XTYP_ADVSTOP transactions. The system returns DDE_FNOTPROCESSED to each client that sends an XTYP_ADVSTART or XTYP_ADVSTOP transaction to the server.
CBF_FAIL_CONNECTIONS	Prevents the callback function from receiving XTYP_CONNECT and XTYP_WILDCONNECT transactions.
CBF_FAIL_EXECUTES	Prevents the callback function from receiving XTYP_EXECUTE transactions. The system returns DDE_FNOTPROCESSED to a client that sends an XTYP_EXECUTE transaction to the server.
CBF_FAIL_POKES	Prevents the callback function from receiving XTYP_POKE transactions. The system returns DDE_FNOTPROCESSED to a client that sends an XTYP_POKE transaction to the server.
CBF_FAIL_REQUESTS	Prevents the callback function from receiving XTYP_REQUEST transactions. The system returns DDE_FNOTPROCESSED to a client that sends an XTYP_REQUEST transaction to the server.
CBF_FAIL_SELFCONNECTIONS	Prevents the callback function from receiving XTYP_CONNECT transactions from the application's own instance. This flag prevents an application from establishing a DDE conversation with its own instance. An application should use this flag if it needs to communicate with other instances of itself but not with itself.
CBF_SKIP_ALLNOTIFICATIONS	Prevents the callback function from receiving any notifications. This flag is equivalent to combining all CBF_SKIP_ flags.
CBF_SKIP_CONNECT_CONFIRMS	Prevents the callback function from receiving XTYP_CONNECT_CONFIRM notifications.
CBF_SKIP_DISCONNECTS	Prevents the callback function from receiving XTYP_DISCONNECT notifications.
CBF_SKIP_REGISTRATIONS	Prevents the callback function from receiving XTYP_REGISTER notifications.
CBF_SKIP_UNREGISTRATIONS	Prevents the callback function from receiving XTYP_UNREGISTER notifications.
MF_CALLBACKS	Notifies the callback function whenever a transaction is sent to any DDE callback function in the system.
MF_CONV	Notifies the callback function whenever a conversation is established or terminated.
MF_ERRORS	Notifies the callback function whenever a DDE error occurs.
MF_HSZ_INFO	Notifies the callback function whenever a DDE application creates, frees, or increments the usage count of a string handle or whenever a string handle is freed as a result of a call to the DdeUninitialize function.
MF_LINKS	Notifies the callback function whenever an advise loop is started or ended.
MF_POSTMSGS	Notifies the callback function whenever the system or an application posts a DDE message.
MF_SENDMSGS	Notifies the callback function whenever the system or an application sends a DDE message.
ulRes

Reserved; must be set to zero.

Return Value

If the function succeeds, the return value is DMLERR_NO_ERROR.

If the function fails, the return value is one of the following values:

DMLERR_DLL_USAGE
DMLERR_INVALIDPARAMETER
DMLERR_SYS_ERROR

Remarks

An application that uses multiple instances of the DDEML must not pass DDEML objects between instances.

A DDE monitoring application should not attempt to perform DDE operations (establish conversations, issue transactions, and so on) within the context of the same application instance.

A synchronous transaction fails with a DMLERR_REENTRANCY error if any instance of the same task has a synchronous transaction already in progress.

The CBF_FAIL_ALLSVRACTIONS flag causes the DDEML to filter all server transactions and can be changed by a subsequent call to DdeInitialize. The APPCMD_CLIENTONLY flag prevents the DDEML from creating key resources for the server and cannot be changed by a subsequent call to DdeInitialize.

There is an ANSI version and a Unicode version of this function. The version called determines the type of the window procedures used to control DDE conversations (ANSI or Unicode), and the default value for the iCodePage member of the CONVCONTXT structure (CP_WINANSI or CP_WINUNICODE).

See Also

DdeClientTransaction, DdeConnect, DdeCreateDataHandle, DdeEnableCallback, DdeNameService, DdePostAdvise, DdeUninitialize XTYP_ADVSTART, XTYP_ADVSTOP, XTYP_CONNECT, XTYP_CONNECT_CONFIRM, XTYP_DISCONNECT, XTYP_EXECUTE, XTYP_POKE, XTYP_REGISTER, XTYP_REQUEST, XTYP_WILDCONNECT


DdeKeepStringHandle
 DdeKeepStringHandle  QuickInfo  Overview  Group

The DdeKeepStringHandle function increments the usage count associated with the specified handle. This function enables an application to save a string handle passed to the application's dynamic data exchange (DDE) callback function. Otherwise, a string handle passed to the callback function is deleted when the callback function returns. This function should also be used to keep a copy of a string handle referenced by the CONVINFO structure returned by the DdeQueryConvInfo function.

BOOL DdeKeepStringHandle(

DWORD  idInst,	// instance identifier
HSZ  hsz	// handle of string
);
Parameters

idInst

Specifies the application instance identifier obtained by a previous call to the DdeInitialize function.

hsz

Identifies the string handle to be saved.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

See Also

CONVINFO, DdeCreateStringHandle, DdeFreeStringHandle, DdeInitialize, DdeQueryConvInfo, DdeQueryString


DdeNameService
 DdeNameService  QuickInfo  Overview  Group

The DdeNameService function registers or unregisters the service names a dynamic data exchange (DDE) server supports. This function causes the system to send XTYP_REGISTER or XTYP_UNREGISTER transactions to other running Dynamic Data Exchange Management Library (DDEML) client applications.

A server application should call this function to register each service name that it supports and to unregister names it previously registered but no longer supports. A server should also call this function to unregister its service names just before terminating.

HDDEDATA DdeNameService(

DWORD  idInst,	// instance identifier
HSZ  hsz1,	// handle of service name string
HSZ  hsz2,	// reserved
UINT  afCmd	// service name flags
);
Parameters

idInst

Specifies the application instance identifier obtained by a previous call to the DdeInitialize function.

hsz1

Identifies the string that specifies the service name the server is registering or unregistering. An application that is unregistering all of its service names should set this parameter to 0L.

hsz2

Reserved; should be set to 0L.

afCmd

Specifies the service name flags. This parameter can be one of the following flags:

Flag	Meaning
DNS_REGISTER	Registers the given service name.
DNS_UNREGISTER	Unregisters the given service name. If the hsz1 parameter is 0L, all service names registered by the server will be unregistered.
DNS_FILTERON	Turns on service name initiation filtering. The filter prevents a server from receiving XTYP_CONNECT transactions for service names it has not registered. This is the default setting for this filter.
	If a server application does not register any service names, the application cannot receive XTYP_WILDCONNECT transactions.
DNS_FILTEROFF	Turns off service name initiation filtering. If this flag is specified, the server receives an XTYP_CONNECT transaction whenever another DDE application calls the DdeConnect function, regardless of the service name.
Return Value

If the funcion succeeds, it returns a nonzero value. That value is not a true HDDEDATA value, merely a Boolean indicator of success. The function is typed HDDEDATA to allow for possible future expansion of the function and a more sophisticated return value.

If the function fails, the return value is 0L.

Errors

The DdeGetLastError function can be used to get the error value, which may be one of the following values:

DMLERR_DLL_NOT_INITIALIZED
DMLERR_DLL_USAGE
DMLERR_INVALIDPARAMETER
DMLERR_NO_ERROR

Remarks

The service name identified by the hsz1 parameter should be a base name (that is, the name should contain no instance-specific information). The system generates an instance-specific name and sends it along with the base name during the XTYP_REGISTER and XTYP_UNREGISTER transactions. The receiving applications can then connect to the specific application instance.

See Also

DdeConnect, DdeConnectList, DdeInitialize, XTYP_REGISTER, XTYP_UNREGISTER


DdePostAdvise
 DdePostAdvise  QuickInfo  Overview  Group

The DdePostAdvise function causes the system to send an XTYP_ADVREQ transaction to the calling (server) application's dynamic data exchange (DDE) callback function for each client with an active advise loop on the specified topic and item. A server application should call this function whenever the data associated with the topic name or item name pair changes.

BOOL DdePostAdvise(

DWORD  idInst,	// instance identifier
HSZ  hszTopic,	// handle of topic name string
HSZ  hszItem	// handle of item name string
);
Parameters

idInst

Specifies the application instance identifier obtained by a previous call to the DdeInitialize function.

hszTopic

Identifies a string that specifies the topic name. To send notifications for all topics with active advise loops, an application can set this parameter to 0L.

hszItem

Identifies a string that specifies the item name. To send notifications for all items with active advise loops, an application can set this parameter to 0L.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Errors

The DdeGetLastError function can be used to get the error value, which may be one of the following values:

DMLERR_DLL_NOT_INITIALIZED
DMLERR_DLL_USAGE
DMLERR_NO_ERROR

Remarks

A server that has nonenumerable topics or items should set the hszTopic and hszItem parameters to NULL so that the system generates transactions for all active advise loops. The server's DDE callback function returns NULL for any advise loops that must not be updated.

If a server calls DdePostAdvise with a topic, item, and format name set that includes the set currently being handled in an XTYP_ADVREQ callback, a stack overflow may result.

See Also

DdeInitialize, XTYP_ADVREQ


DdeQueryConvInfo
 DdeQueryConvInfo  QuickInfo  Overview  Group

The DdeQueryConvInfo function obtains information about a dynamic data exchange (DDE) transaction and about the conversation in which the transaction takes place.

UINT DdeQueryConvInfo(

HCONV  hConv,	// handle of conversation
DWORD  idTransaction,	// transaction identifier
PCONVINFO  pConvInfo	// address of structure with conversation data
);
Parameters

hConv

Identifies the conversation.

idTransaction

Specifies the transaction. For asynchronous transactions, this parameter should be a transaction identifier returned by the DdeClientTransaction function. For synchronous transactions, this parameter should be QID_SYNC.

pConvInfo

Points to the CONVINFO structure that receives information about the transaction and conversation. The cb member of the CONVINFO structure must specify the length of the buffer allocated for the structure.

Return Value

If the function succeeds, the return value is the number of bytes copied into the CONVINFO structure.

If the function fails, the return value is FALSE.

Errors

The DdeGetLastError function can be used to get the error value, which may be one of the following values:

DMLERR_DLL_NOT_INITIALIZED
DMLERR_NO_CONV_ESTABLISHED
DMLERR_NO_ERROR
DMLERR_UNFOUND_QUEUE_ID

Remarks

An application should not free a string handle referenced by the CONVINFO structure. If an application must use one of these string handles, it should call the DdeKeepStringHandle function to create a copy of the handle.

If the idTransaction parameter is set to QID_SYNC, the hUser member of the CONVINFO structure is associated with the conversation and can be used to hold data associated with the conversation. If idTransaction is the identifier of an asynchronous transaction, the hUser member is associated only with the current transaction and is valid only for the duration of the transaction.

See Also

CONVINFO, DdeClientTransaction, DdeConnect, DdeConnectList, DdeKeepStringHandle, DdeQueryNextServer


DdeQueryNextServer
 DdeQueryNextServer  QuickInfo  Overview  Group

The DdeQueryNextServer function obtains the next conversation handle in the specified conversation list.

HCONV DdeQueryNextServer(

HCONVLIST  hConvList,	// handle of conversation list
HCONV  hConvPrev	// previous conversation handle
);
Parameters

hConvList

Identifies the conversation list. This handle must have been created by a previous call to the DdeConnectList function.

hConvPrev

Identifies the conversation handle previously returned by this function. If this parameter is 0L, the function returns the first conversation handle in the list.

Return Value

If the list contains any more conversation handles, the return value is the next conversation handle in the list; otherwise, it is 0L.

See Also

DdeConnectList, DdeDisconnectList


DdeQueryString
 DdeQueryString  QuickInfo  Overview  Group

The DdeQueryString function copies text associated with a string handle into a buffer.

DWORD DdeQueryString(

DWORD  idInst,	// instance identifier
HSZ  hsz,	// handle of string
LPTSTR  psz,	// address of destination buffer
DWORD  cchMax,	// length of buffer
int  iCodePage	// code page identifier
);
Parameters

idInst

Specifies the application instance identifier obtained by a previous call to the DdeInitialize function.

hsz

Identifies the string to copy. This handle must have been created by a previous call to the DdeCreateStringHandle function.

psz

Points to a buffer that receives the string. To obtain the length of the string, this parameter should be set to NULL.

cchMax

Specifies the length, in characters, of the buffer pointed to by the psz parameter. If the string is longer than (cchMax − 1), it will be truncated. If the psz parameter is set to NULL, this parameter is ignored.

iCodePage

Specifies the code page used to render the string. This value should be either CP_WINANSI or CP_WINUNICODE.

Return Value

If the psz parameter specified a valid pointer, the return value is the length, in characters, of the returned text (not including the terminating null character). If the psz parameter specified a NULL pointer, the return value is the length of the text associated with the hsz parameter (not including the terminating null character). If an error occurs, the return value is 0L.

Remarks

The string returned in the buffer is always null-terminated. If the string is longer than (cchMax − 1), only the first (cchMax − 1) characters of the string are copied.

If the psz parameter is NULL, this function obtains the length, in bytes, of the string associated with the string handle. The length does not include the terminating null character.

See Also

DdeCmpStringHandles, DdeCreateStringHandle, DdeFreeStringHandle, DdeInitialize


DdeReconnect
 DdeReconnect  QuickInfo  Overview  Group

The DdeReconnect function allows a client Dynamic Data Exchange Management Library (DDEML) application to attempt to reestablish a conversation with a service that has terminated a conversation with the client. When the conversation is reestablished, the DDEML attempts to reestablish any preexisting advise loops.

HCONV DdeReconnect(

HCONV  hConv	// handle of conversation to reestablish
);
Parameters

hConv

Identifies the conversation to be reestablished. A client must have obtained the conversation handle by a previous call to the DdeConnect function or from an XTYP_DISCONNECT transaction.

Return Value

If the function succeeds, the return value is the handle of the reestablished conversation.

If the function fails, the return value is 0L.

Errors

The DdeGetLastError function can be used to get the error value, which may be one of the following values:

DMLERR_DLL_NOT_INITIALIZED
DMLERR_INVALIDPARAMETER
DMLERR_NO_CONV_ESTABLISHED
DMLERR_NO_ERROR

See Also

DdeConnect, DdeDisconnect


DdeSetQualityOfService
 DdeSetQualityOfService  QuickInfo  Overview  Group

The DdeSetQualityOfService function specifies the quality of service a raw DDE application desires for future DDE conversations it initiates. The specified quality of service applies to any conversations started while those settings are in place. A DDE conversation's quality of service lasts for the duration of the conversation; calls to the DdeSetQualityOfService function during a given conversation do not affect that conversation's quality of service.

BOOL DdeSetQualityOfService(

HWND  hwndClient,	// handle of DDE client window that will start DDE conversations
CONST SECURITY_QUALITY_OF_SERVICE *  pqosNew,	// desired quality of service
PSECURITY_QUALITY_OF_SERVICE  pqosPrev	// prior quality of service
);
Parameters

hwndClient

Identifies the DDE client window that specifies the source of WM_DDE_INITIATE messages a client will send to start DDE conversations.

pqosNew

Points to a SECURITY_QUALITY_OF_SERVICE structure for the desired quality of service values.

pqosPrev

Points to a SECURITY_QUALITY_OF_SERVICE structure that the function will fill with the previous quality of service values associated with the window identified by hwndClient.

This parameter is optional. If an application has no interest in hwndClient's previous qos values, it should set pqosPrev to NULL.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The settings associated with a given hwndClient affect any conversation started subsequent to calling the DdeSetQualityOfService function. The settings remain in effect for the duration of any DDE conversation started under them. Once an application starts a DDE conversation using a particular quality of service value, it must terminate the conversation and restart the conversation in order to have a different value take effect. If a quality of service has not been specified for a given hwndClient prior to sending a WM_DDE_INITIATE with the wParam set to hwndClient, the system uses the following default quality of service values:

{

Length = sizeof(SECURITY_QUALITY_OF_SERVICE);

ImpersonationLevel = SecurityImpersonation;

ContextTrackingMode = SECURITY_STATIC_TRACKING;

EffectiveOnly = TRUE;

}

See Also

DdeConnect, DdeConnectList, DdeImpersonateClient, ImpersonateDdeClientWindow, SECURITY_QUALITY_OF_SERVICE, WM_DDE_INITIATE


DdeSetUserHandle
 DdeSetUserHandle  QuickInfo  Overview  Group

The DdeSetUserHandle function associates an application-defined 32-bit value with a conversation handle or a transaction identifier. This is useful for simplifying the processing of asynchronous transactions. An application can use the DdeQueryConvInfo function to retrieve this value.

BOOL DdeSetUserHandle(

HCONV  hConv,	// handle of conversation
DWORD  id,	// transaction identifier
DWORD  hUser	// handle of application-defined value
);
Parameters

hConv

Identifies the conversation.

id

Specifies the transaction identifier to associate with the value specified by the hUser parameter. An application should set this parameter to QID_SYNC to associate hUser with the conversation identified by the hConv parameter.

hUser

Identifies the value to associate with the conversation handle.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Errors

The DdeGetLastError function can be used to get the error value, which may be one of the following values:

DMLERR_DLL_NOT_INITIALIZED
DMLERR_INVALIDPARAMETER
DMLERR_NO_ERROR
DMLERR_UNFOUND_QUEUE_ID

See Also

DdeQueryConvInfo


DdeUnaccessData
 DdeUnaccessData  QuickInfo  Overview  Group

The DdeUnaccessData function unaccesses a dynamic data exchange (DDE) object. An application must call this function after it has finished accessing the object.

BOOL DdeUnaccessData(

HDDEDATA  hData	// handle of DDE object
);
Parameters

hData

Identifies the DDE object.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Errors

The DdeGetLastError function can be used to get the error value, which may be one of the following values:

DMLERR_DLL_NOT_INITIALIZED
DMLERR_INVALIDPARAMETER
DMLERR_NO_ERROR

See Also

DdeAccessData, DdeAddData, DdeCreateDataHandle, DdeFreeDataHandle


DdeUninitialize
 DdeUninitialize  QuickInfo  Overview  Group

The DdeUninitialize function frees all Dynamic Data Exchange Management Library (DDEML) resources associated with the calling application.

BOOL DdeUninitialize(

DWORD  idInst	// instance identifier
);
Parameters

idInst

Specifies the application instance identifier obtained by a previous call to the DdeInitialize function.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

DdeUninitialize terminates any conversations currently open for the application.

See Also

DdeDisconnect, DdeDisconnectList, DdeInitialize


DebugActiveProcess
 DebugActiveProcess  QuickInfo  Overview  Group

The DebugActiveProcess function allows a debugger to attach to an active process and then debug it.

BOOL DebugActiveProcess(

DWORD  dwProcessId	// process to be debugged
);
Parameters

dwProcessId

Specifies the identifier for the process to be debugged. The debugger gets debugging access to the process as if it created the process with the DEBUG_ONLY_THIS_PROCESS flag.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The debugger must have appropriate access to the target process; it must be able to open the process for PROCESS_ALL_ACCESS access. In the Win32 application programming interface (API) for Windows 95, this is always true if the process identifier is valid. However, In the Win32 API for Windows NT, DebugActiveProcess can fail if the target process was created with a security descriptor that denies the debugger appropriate access.

After the system checks the process identifier and determines that a valid debugging attachment is being made, the function returns TRUE. The debugger is then expected to wait for debugging events by using the WaitForDebugEvent function. The system suspends all threads in the process and sends the debugger events representing the current state of the process.

The system sends the debugger a single CREATE_PROCESS_DEBUG_EVENT debugging event representing the process specified by the dwProcessId parameter. The lpStartAddress member of the CREATE_PROCESS_DEBUG_INFO structure is NULL.

For each thread currently part of the process, the system sends a CREATE_THREAD_DEBUG_EVENT debugging event. The lpStartAddress member of the CREATE_THREAD_DEBUG_INFO structure is NULL.

For each dynamic-link library (DLL) currently loaded into the address space of the target process, the system sends a LOAD_DLL_DEBUG_EVENT debugging event. The system arranges for the first thread in the process to execute a breakpoint instruction after it resumes. Continuing this thread causes it to return to whatever it was doing before the debugger was attached.

After all of this has been done, the system resumes all threads in the process. When the first thread in the process resumes, it executes a breakpoint instruction that causes an EXCEPTION_DEBUG_EVENT debugging event to be sent to the debugger. All future debugging events are sent to the debugger by using the normal mechanism and rules.

See Also

CreateProcess, CREATE_PROCESS_DEBUG_INFO, CREATE_THREAD_DEBUG_INFO, WaitForDebugEvent


DebugBreak
 DebugBreak  QuickInfo  Overview  Group

The DebugBreak function causes a breakpoint exception to occur in the current process so that the calling thread can signal the debugger and force it to take some action. If the process is not being debugged, the search logic of a standard exception handler is used. In most cases, this causes the calling process to terminate because of an unhandled breakpoint exception.

VOID DebugBreak(VOID)

Parameters

This function has no parameters.

Return Value

This function does not return a value.

See Also

DebugActiveProcess


DebugProc
 DebugProc  QuickInfo  Overview  Group

The DebugProc hook procedure is an application-defined or library-defined callback function that Windows calls before calling the hook procedures associated with any other type of hook. The system passes information about the hook to be called to the DebugProc hook procedure, which examines the information and determines whether to allow the hook to be called.

LRESULT CALLBACK DebugProc(

int  nCode,	// hook code
WPARAM  wParam,	// type of hook about to be called
LPARAM  lParam	// address of structure with debugging information
);
Parameters

nCode

Specifies whether the hook procedure must process the message. If nCode is HC_ACTION, the hook procedure must process the message. If nCode is less than zero, the hook procedure must pass the message to the CallNextHookEx function without further processing and should return the value returned by CallNextHookEx.

wParam

Specifies the type of hook about to be called. This parameter can be one of the following values:

Value	Description
WH_CALLWNDPROC	Installs a hook procedure that monitors messages sent to a window procedure. For more information, see the description of the CallWndProc hook procedure.
WH_CALLWNDPROCRET	Windows 95 only: Installs a hook procedure that monitors messages that have just been processed by a window procedure. For more information, see the description of the CallWndRetProc hook procedure.
WH_CBT	Installs a hook procedure that receives notifications useful to a computer-based training (CBT) application. For more information, see the description of the CBTProc hook procedure.
WH_DEBUG	Installs a hook procedure useful for debugging other hook procedures. For more information, see the description of the DebugProc hook procedure.
WH_GETMESSAGE	Installs a hook procedure that monitors messages posted to a message queue. For more information, see the description of the GetMsgProc hook procedure.
WH_JOURNALPLAYBACK	Installs a hook procedure that posts messages previously recorded by a WH_JOURNALRECORD hook procedure. For more information, see the description of the JournalPlaybackProc hook procedure.
WH_JOURNALRECORD	Installs a hook procedure that records input messages posted to the system message queue. This hook is useful for recording macros. For more information, see the description of the JournalRecordProc hook procedure.
WH_KEYBOARD	Installs a hook procedure that monitors keystroke messages. For more information, see the description of the KeyboardProc hook procedure.
WH_MOUSE	Installs a hook procedure that monitors mouse messages. For more information, see the description of the MouseProc hook procedure.
WH_MSGFILTER	Installs a hook procedure that monitors messages generated as a result of an input event in a dialog box, message box, menu, or scroll bar. The hook procedure monitors these messages only for the application that installed the hook procedure. For more information, see the description of the MessageProc hook procedure.
WH_SHELL	Installs a hook procedure that receives notifications useful to a shell application. For more information, see the description of the ShellProc hook procedure.
WH_SYSMSGFILTER	Installs a hook procedure that monitors messages generated as a result of an input event in a dialog box, message box, menu, or scroll bar. The hook procedure monitors these messages for all applications in the system. For more information, see the description of the SysMsgProc hook procedure.
lParam

Points to a DEBUGHOOKINFO structure that contains the parameters to be passed to the destination hook procedure.

Return Value

To prevent the system from calling the hook, the return value must be a nonzero value. Otherwise, the hook procedure must pass the hook information to the CallNextHookEx function.

Remarks

An application installs this hook procedure by specifying the WH_DEBUG hook type and the address of the hook procedure in a call to the SetWindowsHookEx function.

CallWndProc is a placeholder for the application-defined or library-defined function name.

See Also

CallNextHookEx, CallWndProc, CBTProc, DEBUGHOOKINFO, GetMsgProc, JournalPlaybackProc, JournalRecordProc, KeyboardProc, MessageProc, MouseProc, SetWindowsHookEx, ShellProc, SysMsgProc


DefDlgProc
 DefDlgProc  QuickInfo  Overview  Group

The DefDlgProc function carries out default message processing for a window procedure belonging to an application-defined dialog box class.

LRESULT DefDlgProc(

HWND  hDlg,	// handle of dialog box
UINT  Msg,	// message
WPARAM  wParam,	// first message parameter
LPARAM  lParam	// second message parameter
);
Parameters

hDlg

Identifies the dialog box.

Msg

Specifies the message number.

wParam

Specifies additional message-specific information.

lParam

Specifies additional message-specific information.

Return Value

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 this function instead of the DefWindowProc 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 the WNDCLASS structure for a custom dialog box class must be set to at least DLGWINDOWEXTRA.

DefDlgProc must not be called by a dialog box procedure; doing so results in recursive execution.

See Also

DefWindowProc, GetClassInfo, RegisterClass, WNDCLASS


DeferWindowPos
 DeferWindowPos  QuickInfo  Overview  Group

The DeferWindowPos function updates the specified multiple-window − position structure for the specified window. The function then returns the handle of 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 of internal structure
HWND  hWnd,	// handle of window to position
HWND  hWndInsertAfter,	// placement-order handle
int  x,	// horizontal position
int  y,	// vertical position
int  cx,	// width
int  cy,	// height
UINT  uFlags	// window-positioning flags
);
Parameters

hWinPosInfo

Identifies 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

Identifies the window for which update information is stored in the structure.

hWndInsertAfter

Identifies the window that precedes the positioned window in the Z order. This parameter must be a window handle or one of the following values:

Value	Meaning
HWND_BOTTOM	Places the window at the bottom of the Z order. If the hWnd parameter identifies a topmost window, the window loses its topmost status and is placed at the bottom of all other windows.
HWND_NOTOPMOST	Places the window above all non-topmost windows (that is, behind all topmost windows). This flag has no effect if the window is already a non-topmost window.
HWND_TOP	Places the window at the top of the Z order.
HWND_TOPMOST	Places the window above all non-topmost windows. The window maintains its topmost position even when it is deactivated.
This parameter is ignored if the SWP_NOZORDER flag is set in the uFlags parameter.

x

Specifies the x-coordinate of the window's upper-left corner.

y

Specifies the y-coordinate of the window's upper-left corner.

cx

Specifies the window's new width, in pixels.

cy

Specifies the window's new height, in pixels.

uFlags

Specifies a combination of the following values that affect the size and position of the window:

Value	Meaning
SWP_DRAWFRAME	Draws a frame (defined in the window's class description) around the window.
SWP_HIDEWINDOW	Hides the window.
SWP_NOACTIVATE	Does not activate the window.
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 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 needs to be redrawn.
SWP_NOREPOSITION	Currently the same as the SWP_NOOWNERZORDER flag.
SWP_NOSENDCHANGING	Windows 95 only: 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 Value

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.

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, Windows 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, Windows places the hWnd window at the top of the Z order. If hWndInsertAfter is set to HWND_BOTTOM, Windows 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.

See Also

BeginDeferWindowPos, EndDeferWindowPos, ShowWindow


DefFrameProc
 DefFrameProc  QuickInfo  Overview  Group

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 of MDI frame window
HWND  hWndMDIClient,	// handle of MDI client window
UINT  uMsg,	// message
WPARAM  wParam,	// first message parameter
LPARAM  lParam	// second message parameter
);
Parameters

hWnd

Identifies the MDI frame window.

hWndMDIClient

Identifies the MDI client window.

uMsg

Specifies the message to be processed.

wParam

Specifies additional message-specific information.

lParam

Specifies additional message-specific information.

Return Value

The return value specifies the result of the message processing and depends on the message. 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 System 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.
See Also

DefMDIChildProc, DefWindowProc, WM_SETTEXT


DefHookProc
 DefHookProc  QuickInfo  Overview  Group

The DefHookProc function is obsolete. It is provided only for compatibility with 16-bit versions of Windows. Win32-based applications should use the CallNextHookEx function.


DefineDosDevice
 DefineDosDevice  QuickInfo  Overview  Group

The DefineDosDevice function lets an application define, redefine, or delete MS-DOS device names.

MS-DOS device names are stored as symbolic links in the object name space in 32-bit versions of Windows. The code that converts an MS-DOS path into a corresponding path in 32-bit versions of Windows uses these symbolic links to map MS-DOS devices and drive letters. The DefineDosDevice function provides a mechanism whereby a Win32-based application can modify the symbolic links used to implement the MS-DOS device name space.

BOOL DefineDosDevice(

DWORD  dwFlags,	// flags specifying aspects of device definition
LPCTSTR  lpDeviceName,	// address of MS-DOS device name string
LPCTSTR  lpTargetPath	// address of MS-DOS or path string for 32-bit Windows
);
Parameters

dwFlags

Specifies several controllable aspects of the DefineDosDevice function. One or more of the following values can be used:

Value	Meaning
DDD_RAW_TARGET_PATH	If this value is specified, the function does not convert the lpTargetPath string from an MS-DOS path to a path for a 32-bit version of Windows, but takes it as is.
DDD_REMOVE_DEFINITION	If this value is specified, the function removes the specified definition for the specified device. To determine which definition to remove, the function walks the list of mappings for the device, looking for a match of lpTargetPath against a prefix of each mapping associated with this device. The first mapping that matches is the one removed, and then the function returns. If lpTargetPath is NULL or a pointer to a NULL string, the function will remove the first mapping associated with the device and pop the most recent one pushed. If there is nothing left to pop, the device name will be removed. If this value is NOT specified, the string pointed to by the lpTargetPath parameter will become the new mapping for this device.
DDD_EXACT_MATCH_ON_REMOVE	If this value is specified along with DDD_REMOVE_DEFINITION, the function will use an exact match to determine which mapping to remove. Use this value to insure that you do not delete something that you did not define.
lpDeviceName

Points to an MS-DOS device name string specifying the device the function is defining, redefining, or deleting. The device name string must not have a trailing colon, unless a drive letter (C or D, for example) is being defined, redefined, or deleted.

lpTargetPath

Points to a path string that will implement this device. Points to an MS-DOS path string unless the DDD_RAW_TARGET_PATH flag is specified, in which case this parameter points to a path string for a 32-bit version of Windows.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

As stated in this function's introductory summary, the DefineDosDevice function provides a means whereby a Win32-based application can create and modify the symbolic links used to implement the MS-DOS device namespace. To retrieve the current mapping for a particular MS-DOS device name or to obtain a list of all MS-DOS devices known to the system, use the QueryDosDevice function.

MS-DOS Device names are global. Once defined, an MS-DOS device name remains visible to all processes until either it is explicitly removed or the system reboots.

Note that drive letters and device names defined at system boot time are protected from redefinition and deletion unless a user is running in administrative mode (ADMIN).

See Also

QueryDosDevice


DefineHandleTable
 DefineHandleTable  QuickInfo  Overview  Group

The DefineHandleTable function is obsolete. It is provided as a macro to simplify porting of 16-bit Windows-based applications. It expands to TRUE after evaluating its argument. It has no other effect.


DefMDIChildProc
 DefMDIChildProc  QuickInfo  Overview  Group

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 of MDI child window
UINT  uMsg,	// message
WPARAM  wParam,	// first message parameter
LPARAM  lParam	// second message parameter
);
Parameters

hWnd

Identifies the MDI child window.

uMsg

Specifies the message to be processed.

wParam

Specifies additional message-specific information.

lParam

Specifies additional message-specific information.

Return Value

The return value specifies the result of the message processing and depends on the message.

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 System menu commands: SC_NEXTWINDOW, SC_PREVWINDOW, SC_MOVE, SC_SIZE, and SC_MAXIMIZE.
See Also

DefFrameProc, DefWindowProc, WM_CHILDACTIVATE, WM_GETMINMAXINFO, WM_MENUCHAR, WM_MOVE, WM_SETFOCUS, WM_SETTEXT, WM_SIZE, WM_SYSCOMMAND


DefScreenSaverProc
 DefScreenSaverProc  QuickInfo  Overview  Group

The DefScreenSaverProc function provides default processing for any messages that a screen saver application does not process.

LONG DefScreenSaverProc(

HWND  hWnd,	// handle of screen saver window
UINT  msg,	// message
WPARAM  wParam,	// first message parameter
LPARAM  lParam	// second message parameter
);
Parameters

hWnd

Identifies the screen saver window.

msg

Specifies the message to be processed. The DefScreenSaverProc function responds to messages that affect the screen saver's operation, as detailed in the Remarks section.

If a screen saver application must perform a different action in response to any of these messages, the application's ScreenSaverProc window procedure should process the message.

wParam

Specifies additional message-specific information.

lParam

Specifies additional message-specific information.

Return Value

The return value specifies the result of the message processing and depends on the message sent.

Remarks

A screen saver application's ScreenSaverProc window procedure should use DefScreenSaverProc instead of the DefWindowProc function to provide default message processing. The DefScreenSaverProc function passes any messages that do not affect screen saver operation to DefWindowProc.

The following table describes how the DefScreenSaverProc processes a variety of window messages:

Message	Action
WM_ACTIVATE, WM_ACTIVATEAPP, WM_NCACTIVATE	Closes the screen saver if the wParam parameter is FALSE. A wParam value of FALSE indicates that the screen saver is losing the input focus. The screen saver is closed by sending a WM_CLOSE message.
WM_SETCURSOR	Removes the cursor from the screen by setting the cursor to NULL.
WM_LBUTTONDOWN, WM_RBUTTONDOWN, WM_MBUTTONDOWN, WM_KEYDOWN, WM_KEYUP, WM_MOUSEMOVE	Calls the PostQuitMessage function to close the screen saver.
WM_DESTROY	Posts a WM_CLOSE message to close the screen saver window.
WM_SYSCOMMAND	Returns FALSE if the wParam parameter of WM_SYSCOMMAND is either SC_CLOSE or SC_SCREENSAVE.
See Also

DefWindowProc, PostQuitMessage, ScreenSaverProc, WM_ACTIVATE, WM_ACTIVATEAPP, WM_CLOSE, WM_DESTROY, WM_KEYDOWN, WM_KEYUP, WM_LBUTTONDOWN, WM_MBUTTONDOWN, WM_MOUSEMOVE, WM_NCACTIVATE, WM_RBUTTONDOWN, WM_SETCURSOR, WM_SYSCOMMAND


DefWindowProc
 DefWindowProc  QuickInfo  Overview  Group

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 of window
UINT  Msg,	// message identifier
WPARAM  wParam,	// first message parameter
LPARAM  lParam	// second message parameter
);
Parameters

hWnd

Identifies the window procedure that received the message.

Msg

Specifies the message.

wParam

Specifies additional message information. The content of this parameter depends on the value of the Msg parameter.

lParam

Specifies additional message information. The content of this parameter depends on the value of the Msg parameter.

Return Value

The return value is the result of the message processing and depends on the message.

See Also

CallWindowProc, DefDlgProc, WindowProc


DeleteAce
 DeleteAce  QuickInfo  Overview  Group

The DeleteAce function deletes an ACE from an ACL.

An ACE is an access-control entry. An ACL is an access-control list.

BOOL DeleteAce(

PACL  pAcl,	// address of access-control list
DWORD  dwAceIndex	// index of ACE position in ACL
);
Parameters

pAcl

Points to an ACL structure. The ACE specified by the dwAceIndex parameter is removed from this ACL.

dwAceIndex

Specifies the ACE to delete. A value of 0 corresponds to the first ACE in the ACL, 1 to the second ACE, and so on.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

An application can use the ACL_SIZE_INFORMATION structure retrieved by the GetAclInformation function to discover the size of the ACL and the number of ACEs it contains. The GetAce function retrieves information about an individual ACE.

See Also

ACL, ACL_SIZE_INFORMATION, AddAccessAllowedAce, AddAccessDeniedAce, AddAce, AddAuditAccessAce, GetAce, GetAclInformation


DeleteAtom
 DeleteAtom  QuickInfo  Overview  Group

The DeleteAtom function decrements the reference count of a local string atom. If the atom's reference count is reduced to zero, DeleteAtom removes the string associated with the atom from the local atom table.

ATOM DeleteAtom(

ATOM  nAtom	// atom to delete
);
Parameters

nAtom

Identifies the atom and character string to be deleted.

Return Value

If the function succeeds, the return value is zero.

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

Remarks

A string atom's reference count specifies the number of times the atom has been added to or removed from the atom table. The AddAtom function increments the count on each call. DeleteAtom decrements the count on each call but removes the string only if the atom's reference count is zero.

The only way to ensure that an atom has been deleted from the atom table is to call this function repeatedly until it fails. When the reference count is reduced to zero, the next call to the FindAtom or DeleteAtom function fails.

DeleteAtom has no effect on an integer atom (an atom created by using the MAKEINTATOM macro). The function always returns zero for an integer atom.

See Also

AddAtom, FindAtom, GlobalAddAtom, GlobalDeleteAtom, GlobalFindAtom, MAKEINTATOM


DeleteColorSpace [New - Windows 95]
 DeleteColorSpace  QuickInfo  Overview  Group

[New - Windows 95]

The DeleteColorSpace function deletes the specified color space, freeing all internal resources associated with it.

BOOL DeleteColorSpace(

HCOLORSPACE hColorSpace
);
Parameters

hColorSpace

Handle to the color space to delete.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.


DeleteCriticalSection
 DeleteCriticalSection  QuickInfo  Overview  Group

The DeleteCriticalSection function releases all resources used by an unowned critical section object.

VOID DeleteCriticalSection(

LPCRITICAL_SECTION  lpCriticalSection	// address of critical section object
);
Parameters

lpCriticalSection

Points to the critical section object.

Return Value

This function does not return a value.

Remarks

Deleting a critical section object releases all system resources used by the object. Once deleted, the critical section object cannot be specified in the EnterCriticalSection or LeaveCriticalSection function.

See Also

EnterCriticalSection, InitializeCriticalSection, LeaveCriticalSection


DeleteDC
 DeleteDC  QuickInfo  Overview  Group

The DeleteDC function deletes the specified device context (DC).

BOOL DeleteDC(

HDC  hdc	// handle of device context
);
Parameters

hdc

Identifies the device context.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

An application must not delete a device context whose handle was obtained by calling the GetDC function. Instead, it must call the ReleaseDC function to free the device context.

See Also

CreateDC, GetDC, ReleaseDC


DeleteEnhMetaFile
 DeleteEnhMetaFile  QuickInfo  Overview  Group

The DeleteEnhMetaFile function deletes an enhanced-format metafile or an enhanced-format metafile handle.

BOOL DeleteEnhMetaFile(

HENHMETAFILE  hemf	// handle of an enhanced metafile
);
Parameters

hemf

Identifies an enhanced metafile.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

If the hemf parameter identifies an enhanced metafile stored in memory, this function deletes the metafile. If hemf identifies a metafile stored on a disk, the function deletes the metafile handle but does not destroy the actual metafile. An application can retrieve the file by calling the GetEnhMetaFile function.

See Also

CopyEnhMetaFile, CreateEnhMetaFile, GetEnhMetaFile


DeleteFile
 DeleteFile  QuickInfo  Overview  Group

The DeleteFile function deletes an existing file.

BOOL DeleteFile(

LPCTSTR  lpFileName	// address of name of file to delete
);
Parameters

lpFileName

Points to a null-terminated string that specifies the file to be deleted.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

If an application attempts to delete a file that does not exist, the DeleteFile function fails.

Windows 95: This function deletes a file even if it is open for normal I/O or as a memory-mapped file. To prevent loss of data, close files before attempting to delete them.

Windows NT: This function fails if an application attempts to delete a file that is open for normal I/O or as a memory-mapped file.

To close an open file, use the CloseHandle function.

See Also

CloseHandle, CreateFile


DeleteForm
 DeleteForm  QuickInfo  Overview  Group

The DeleteForm function removes a form name from the list of supported forms.

BOOL DeleteForm(

HANDLE  hPrinter,	// handle of printer object
LPTSTR  pFormName	// address of form name
);
Parameters

hPrinter

Indicates the open printer handle that this function is to be performed upon.

pFormName

Points to the form name to be removed.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The printer handle is obtained by calling the OpenPrinter function. DeleteForm can only delete form names that were added by using the AddForm function.

See Also

AddForm, OpenPrinter


DeleteMenu
 DeleteMenu  QuickInfo  Overview  Group

The DeleteMenu function deletes an item from the specified menu. If the menu item invokes a pop-up menu, this function destroys the handle of the pop-up menu and frees the memory used by the pop-up menu.

BOOL DeleteMenu(

HMENU  hMenu,	// handle of menu
UINT  uPosition,	// menu item identifier or position
UINT  uFlags	// menu item flag
);
Parameters

hMenu

Identifies the menu to be changed.

uPosition

Specifies the menu item to be deleted, as determined by the uFlags parameter.

uFlags

Specifies how the uPosition parameter is interpreted. This parameter must be one of the following values:

Value	Meaning
MF_BYCOMMAND	Indicates that uPosition gives the identifier of the menu item. The MF_BYCOMMAND flag is the default flag if neither the MF_BYCOMMAND nor MF_BYPOSITION flag is specified.
MF_BYPOSITION	Indicates that uPosition gives the zero-based relative position of the menu item.
Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. 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.

See Also

DrawMenuBar, RemoveMenu


DeleteMetaFile
 DeleteMetaFile  QuickInfo  Overview  Group

The DeleteMetaFile function deletes a Windows-format metafile or Windows-format metafile handle.

This function is provided for compatibility with 16-bit versions of Windows. Win32-based applications should use the DeleteEnhMetaFile function.

BOOL DeleteMetaFile(

HMETAFILE  hmf	// handle of Windows-format metafile
);
Parameters

hmf

Identifies a Windows-format metafile.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

A Windows-format metafile does not support the new curve, path, and transformation functions, such as PolyBezier, BeginPath, and SetWorldTransform. Applications that use these new functions and use metafiles to store pictures created by these functions should use the enhanced format metafile functions.

If the metafile identified by the hmf parameter is stored in memory (rather than on a disk), its content is lost when it is deleted by using the DeleteMetaFile function.

See Also

BeginPath, CopyMetaFile, CreateMetaFile, DeleteEnhMetaFile, GetMetaFile, PolyBezier, SetWorldTransform


DeleteMonitor
 DeleteMonitor  QuickInfo  Overview  Group

The DeleteMonitor function removes a printer monitor added by the AddMonitor function.

BOOL DeleteMonitor(

LPTSTR  pName,	// address of server name
LPTSTR  pEnvironment,	// address of environment string
LPTSTR  pMonitorName	// address of monitor name
);
Parameters

pName

Points to a null-terminated string that specifies the name of the server from which the monitor is to be removed. If this parameter is NULL, the printer monitor is removed locally.

pEnvironment

Points to a null-terminated string that specifies the environment from which the monitor is to be removed (for example, "Windows NT x86", "Windows NT R4000", "Windows NT Alpha_AXP", or "Windows 4.0"). If this parameter is NULL, the monitor is removed from the current environment of the calling application and client machine (not of the destination application and print server).

pMonitorName

Points to a null-terminated string that specifies the name of the monitor to be removed.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

AddMonitor


DeleteObject
 DeleteObject  QuickInfo  Overview  Group

The DeleteObject function deletes a logical pen, brush, font, bitmap, region, or palette, freeing all system resources associated with the object. After the object is deleted, the specified handle is no longer valid.

BOOL DeleteObject(

HGDIOBJ  hObject	// handle of graphic object
);
Parameters

hObject

Identifies a logical pen, brush, font, bitmap, region, or palette.

Return Value

If the function succeeds, the return value is TRUE.

If the given handle is not valid or is currently selected into a device context (DC), the return value is FALSE.

Remarks

Do not delete a drawing object (pen or brush) while it is still selected into a DC.

When a pattern brush is deleted, the bitmap associated with the brush is not deleted. The bitmap must be deleted independently.

See Also

SelectObject


DeletePort
 DeletePort  QuickInfo  Overview  Group

The DeletePort function displays a dialog box that allows the user to delete a port name.

BOOL DeletePort(

LPTSTR  pName,	// address of server name
HWND  hWnd,	// handle of window that displays dialog box
LPTSTR  pPortName	// address of port name
);
Parameters

pName

Points to a null-terminated string that specifies the name of the server for which the port should be deleted. If this parameter is NULL, a local port is deleted.

hWnd

Identifies the parent window of the port-deletion dialog box.

pPortName

Points to a null-terminated string that specifies the name of the port that should be deleted.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

An application can retrieve the names of valid ports by calling the EnumPorts function.

The DeletePort function returns an error if a printer is currently connected to the specified port.

See Also

AddPort, EnumPorts


DeletePrinter
 DeletePrinter  QuickInfo  Overview  Group

The DeletePrinter function deletes the specified printer object.

BOOL DeletePrinter(

HANDLE  hPrinter	// handle of printer object
);
Parameters

hPrinter

Identifies a printer object that will be deleted.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The printer handle hPrinter is obtained by calling the OpenPrinter or AddPrinter function. Most users will use OpenPrinter.

If there are print jobs remaining to be processed for the given printer, DeletePrinter marks the printer for pending deletion, and then deletes it when all the print jobs have been printed. No print jobs can be added to a printer that is marked for pending deletion.

A printer marked for pending deletion cannot be held, but its print jobs can be held, resumed, and restarted. If the printer is held and there are jobs for the printer, DeletePrinter fails with an InvalidState error.

See Also

AddPrinter, EnumPrinters, OpenPrinter


DeletePrinterConnection
 DeletePrinterConnection  Overview  Group

The DeletePrinterConnection function deletes a connection to a printer that was established by a call to AddPrinterConnection or ConnectToPrinterDlg.

BOOL DeletePrinterConnection (

LPTSTR  pName	// address of printer name
);
Parameters

pName

Points to a null-terminated string that specifies the name of the printer connection to delete.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The DeletePrinterConnection function does not delete any printer drivers copied to the server on which the printer resides when the printer connection was established.

See Also

AddPrinterConnection, ConnectToPrinterDlg


DeletePrinterDriver
 DeletePrinterDriver  QuickInfo  Overview  Group

The DeletePrinterDriver function removes the specified printer-driver name from the list of names of supported drivers for a server.

BOOL DeletePrinterDriver(

LPTSTR  pName,	// address of server name
LPTSTR  pEnvironment,	// address of environment
LPTSTR  pDriverName	// address of driver name
);
Parameters

pName

Points to a null-terminated string that specifies the name of the server from which the driver is to be deleted. If this parameter is NULL, the printer-driver name will be removed locally.

pEnvironment

Points to a null-terminated string that specifies the environment from which the driver is to be deleted (for example, "Windows NT x86", "Windows NT R4000", "Windows NT Alpha_AXP", or "Windows 4.0"). If this parameter is NULL, the driver name is deleted from the current environment of the calling application and client machine (not of the destination application and print server).

pDriverName

Points to a null-terminated string specifying the name of the driver that should be deleted.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The DeletePrinterDriver function does not delete the associated files, it merely removes the driver name from the list returned by the EnumPrinterDrivers function.

See Also

EnumPrinterDrivers


DeletePrintProcessor
 DeletePrintProcessor  QuickInfo  Overview  Group

The DeletePrintProcessor function removes a printer processor added by the AddPrintProcessor function.

BOOL DeletePrintProcessor (

LPTSTR  pName,	// address of server name
LPTSTR  pEnvironment,	// address of environment string
LPTSTR  pPrintProcessorName	// address of processor name
);
Parameters

pName

Points to a null-terminated string that specifies the name of the server from which the processor is to be removed. If this parameter is NULL, the printer processor is removed locally.

pEnvironment

Points to a null-terminated string that specifies the environment from which the processor is to be removed (for example, "Windows NT x86", "Windows NT R4000", "Windows NT Alpha_AXP", or "Windows 4.0"). If this parameter is NULL, the processor is removed from the current environment of the calling application and client machine (not of the destination application and print server). NULL is the recommended value, as it provides maximum portability.

pPrintProcessorName

Points to a null-terminated string that specifies the name of the processor to be removed.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

AddPrintProcessor


DeletePrintProvidor
 DeletePrintProvidor  QuickInfo  Overview  Group

The DeletePrintProvidor function removes a printer provider added by the AddPrintProvidor function.

BOOL DeletePrintProvidor (

LPTSTR  pName,	// address of server name
LPTSTR  pEnvironment,	// address of environment string
LPTSTR  pPrintProvidorName	// address of provider name
);
Parameters

pName

Points to a null-terminated string that specifies the name of the server from which the provider is to be removed. If this parameter is NULL, the printer provider is removed locally.

pEnvironment

Points to a null-terminated string that specifies the environment from which the provider is to be removed (for example, "Windows NT x86", "Windows NT R4000", "Windows NT Alpha_AXP", or "Windows 4.0"). If this parameter is NULL, the provider is removed from the current environment of the calling application and client machine (not of the destination application and print server). NULL is the recommended value because it provides maximum portability.

pPrintProvidorName

Points to a null-terminated string that specifies the name of the provider to be removed.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

AddPrintProvidor


DeleteService
 DeleteService  QuickInfo  Overview  Group

The DeleteService function marks the specified service for deletion from the service control manager database.

BOOL DeleteService(

SC_HANDLE  hService	// handle of service
);
Parameters

hService

Identifies the service. This handle is returned by the OpenService or CreateService function, and it must have DELETE access.

Return Value

If the function succeeds, the return value is TRUE.

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

Errors

The following error codes may be set by the service control manager. Others may be set by the registry functions that are called by the service control manager.

Value	Meaning
ERROR_ACCESS_DENIED	The specified handle was not opened with DELETE access.
ERROR_INVALID_HANDLE	The specified handle is invalid.
ERROR_SERVICE_MARKED_FOR_DELETE	The specified service has already been marked for deletion.
Remarks

The DeleteService function marks a service for deletion from the service control manager database. The database entry is not removed until all open handles to the service have been closed by calls to the CloseServiceHandle function, and the service is not running. A running service is stopped by a call to the ControlService function with the SERVICE_CONTROL_STOP control code. If the service cannot be stopped, the database entry is removed when the system is restarted.

The service control manager deletes the service by deleting the service key and its subkeys from the registry.

See Also

CloseServiceHandle, ControlService, CreateService, OpenService


DeregisterEventSource
 DeregisterEventSource  QuickInfo  Overview  Group

The DeregisterEventSource function closes a handle returned by the RegisterEventSource function.

BOOL DeregisterEventSource(

HANDLE  hEventLog	// handle to event log
);
Parameters

hEventLog

Identifies the event log whose handle was returned by RegisterEventSource.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

RegisterEventSource


DestroyAcceleratorTable
 DestroyAcceleratorTable  QuickInfo  Overview  Group

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 of accelerator table
);
Parameters

hAccel

Identifies the accelerator table to destroy. This handle must have been created by a call to the CreateAcceleratorTable function.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

CopyAcceleratorTable, CreateAcceleratorTable, LoadAccelerators, TranslateAccelerator


DestroyCaret
 DestroyCaret  QuickInfo  Overview  Group

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 Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. 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 caret is a shared resource; there is only one caret in the system. 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.

See Also

CreateCaret, HideCaret, ShowCaret


DestroyCursor
 DestroyCursor  QuickInfo  Overview  Group

The DestroyCursor function destroys a cursor created by the CreateCursor function and frees any memory the cursor occupied. Do not use this function to destroy a cursor that was not created with the CreateCursor function.

BOOL DestroyCursor(

HCURSOR  hCursor	// handle of cursor to destroy
);
Parameters

hCursor

Identifies the cursor to be destroyed. The cursor must not be in use.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

CreateCursor


DestroyIcon
 DestroyIcon  QuickInfo  Overview  Group

The DestroyIcon function destroys an icon and frees any memory the icon occupied.

BOOL DestroyIcon(

HICON  hIcon	// handle of icon to destroy
);
Parameters

hIcon

Identifies the icon to be destroyed. The icon must not be in use.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

CreateIcon


DestroyMenu
 DestroyMenu  QuickInfo  Overview  Group

The DestroyMenu function destroys the given menu and frees any memory that the menu occupies.

BOOL DestroyMenu(

HMENU  hMenu	// handle of menu to destroy
);
Parameters

hMenu

Identifies the menu to be destroyed.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

Before closing, an application must use this 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.

See Also

CreateMenu, DeleteMenu, RemoveMenu


DestroyPrivateObjectSecurity
 DestroyPrivateObjectSecurity  QuickInfo  Overview  Group

The DestroyPrivateObjectSecurity function deletes a protected server object's security descriptor. This security descriptor must have been created by a call to the CreatePrivateObjectSecurity function.

BOOL DestroyPrivateObjectSecurity(

PSECURITY_DESCRIPTOR  * ObjectDescriptor	// address of pointer to SECURITY_DESCRIPTOR
);
Parameters

ObjectDescriptor

Points to a pointer to the SECURITY_DESCRIPTOR structure to be deleted.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

CreatePrivateObjectSecurity, GetPrivateObjectSecurity, SECURITY_DESCRIPTOR, SetPrivateObjectSecurity


DestroyPropertySheetPage [New - Windows NT]
 DestroyPropertySheetPage  QuickInfo  Overview  Group

[New - Windows NT]

The DestroyPropertySheetPage function destroys a property sheet page. An application must call this function for pages that have not been passed to the PropertySheet function.

BOOL DestroyPropertySheetPage(

HPROPSHEETPAGE  hPSPage
);
Parameters

hPSPage

Handle to the property sheet page to delete.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

See Also

PropertySheet


DestroyWindow
 DestroyWindow  QuickInfo  Overview  Group

The DestroyWindow function destroys the given 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 given 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 of window to destroy
);
Parameters

hWnd

Identifies the window to be destroyed.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. 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.

See Also

CreateDialog, CreateWindow, CreateWindowEx, WM_DESTROY, WM_NCDESTROY, WM_PARENTNOTIFY


DeviceCapabilities
 DeviceCapabilities  Overview  Group

The DeviceCapabilities function retrieves the capabilities of a printer device driver.

DWORD DeviceCapabilities(

LPCTSTR  pDevice,	// pointer to a printer-name string
LPCTSTR  pPort,	// pointer to a port-name string
WORD  fwCapability,	// device capability to query
LPTSTR  pOutput,	// pointer to the output
CONST DEVMODE *  pDevMode	// pointer to structure with device data
);
Parameters

pDevice

Pointer to a null-terminated string that contains the name of the printer. Note that this is the name of the printer, not of the printer driver.

pPort

Pointer to a null-terminated string that contains the name of the port to which the device is connected, such as "LPT1".

fwCapability

Specifies the capabilities to query. This parameter can be one of the following values:

Value	Meaning
DC_BINADJUST	Windows 95 only: Retrieves the page positioning for the paper source specified in the DEVMODE structure pointed to by pdevMode. The return value can be one of the following:
	DCBA_FACEUPNONE
	DCBA_FACEUPCENTER
	DCBA_FACEUPLEFT
	DCBA_FACEUPRIGHT
	DCBA_FACEDOWNNONE
	DCBA_FACEDOWNCENTER
	....DCBA_FACEDOWNLEFT
	DCBA_FACEDOWNRIGHT
DC_BINNAMES	Copies an array containing a list of the names of the paper bins. This array is in the form char PaperNames[cBinMax][cchBinName] where cchBinName is 24. If the pOutput parameter is NULL, the return value is the number of bin entries required. Otherwise, the return value is the number of bins copied.
DC_BINS	Retrieves a list of available bins. The function copies the list to the pOutput parameter as a WORD array. If pOutput is NULL, the function returns the number of supported bins to allow the application the opportunity to allocate a buffer with the correct size. For more information about these bins, see the description of the dmDefaultSource member of the DEVMODE structure.
DC_COPIES	Returns the number of copies the device can print.
DC_DRIVER	Returns the version number of the printer driver.
DC_DATATYPE_PRODUCED	Windows 95 only: The return value is the number of datatypes supported by the printer driver. If the function returns -1, the driver understands the "RAW" datatype only. The names of the supported datatypes are copied to an array. Use the names in the DOCINFO structure when calling the StartDoc function to specify the datatype.
DC_DUPLEX	Returns the level of duplex support. The function returns 1 if the printer is capable of duplex printing. Otherwise, the return value is zero.
DC_EMF_COMPLIANT	Windows 95 only: Determines if a printer driver supports enhanced metafile (EMF). A return value of 1 means the driver supports EMF. A return value of -1 means that the driver does not support EMF
DC_ENUMRESOLUTIONS	Returns a list of available resolutions. If pOutput is NULL, the function returns the number of available resolution configurations. Resolutions are represented by pairs of LONG integers representing the horizontal and vertical resolutions (specified in dots per inch).
DC_EXTRA	Returns the number of bytes required for the device-specific portion of the DEVMODE structure for the printer driver.
DC_FIELDS	Returns the dmFields member of the printer driver's DEVMODE structure. The dmFields member indicates which members in the device-independent portion of the structure are supported by the printer driver.
DC_FILEDEPENDENCIES	Returns a list of files that also need to be loaded when a driver is installed. If the pOutput parameter is NULL, the function returns the number of files. Otherwise, pOutput points to an array of filenames in the form char[chFileName, 64]. Each filename is a null-terminated string.
DC_MAXEXTENT	Returns a POINT structure containing the maximum paper size that the dmPaperLength and dmPaperWidth members of the printer driver's DEVMODE structure can specify.
DC_MINEXTENT	Returns a POINT structure containing the minimum paper size that the dmPaperLength and dmPaperWidth members of the printer driver's DEVMODE structure can specify.
DC_ORIENTATION	Returns the relationship between portrait and landscape orientations for a device, in terms of the number of degrees that portrait orientation is rotated counterclockwise to produce landscape orientation. The return value can be one of the following:
Value	Meaning
0	No landscape orientation.
90	Portrait is rotated 90 degrees to produce landscape. (For example, Hewlett-Packard PCL printers.)
270	Portrait is rotated 270 degrees to produce landscape. (For example, dot-matrix printers.)
DC_PAPERNAMES	Retrieves a list of supported paper names (for example, Letter or Legal). If the pOutput parameter is NULL, the function returns the number of paper sizes available. Otherwise, pOutput points to an array for the paper names in the form char[cPaperNames, 64]. Each paper name is a null-terminated string.
DC_PAPERS	Retrieves a list of supported paper sizes. The function copies the list to pOutput as a WORD array and returns the number of entries in the array. If pOutput is NULL, the function returns the number of supported paper sizes to allow the application the opportunity to allocate a buffer with the correct size. For more information on paper sizes, see the description of the dmPaperSize member of the DEVMODE structure.
DC_PAPERSIZE	Copies the dimensions of all supported paper sizes, in tenths of a millimeter, to an array of POINT structures pointed to by the pOutput parameter. The width (x-dimension) and length (y-dimension) of a paper size are returned as if the paper were in the DMORIENT_PORTRAIT orientation.
DC_SIZE	Returns the dmSize member of the printer driver's DEVMODE structure.
DC_TRUETYPE	Retrieves the abilities of the driver to use TrueType fonts. For DC_TRUETYPE, the pOutput parameter should be NULL. The return value can be one or more of the following:
Value	Meaning
DCTT_BITMAP	Device can print TrueType fonts as graphics. (For example, dot-matrix and PCL printers.)
DCTT_DOWNLOAD	Device can download TrueType fonts. (For example, PCL and PostScript printers.)
DCTT_DOWNLOAD_ OUTLINE	Windows 95 only: Device can download outline TrueType fonts.
DCTT_SUBDEV	Device can substitute device fonts for TrueType fonts. (For example, PostScript printers.)
DC_VERSION	Returns the specification version to which the printer driver conforms.
pOutput

Pointer to an array of bytes. The format of the array depends on the setting of the fwCapability parameter. If pOutput is zero, DeviceCapabilities returns the number of bytes required for the output data.

pDevMode

Pointer to a DEVMODE structure. If this parameter is NULL, DeviceCapabilities retrieves the current default initialization values for the specified printer driver. Otherwise, the function retrieves the values contained in the structure to which pDevMode points.

Return Value

If the function succeeds, the return value depends on the setting of the fwCapability parameter.

If the function fails, the return value is −1.

Remarks

In previous versions of Windows, the DeviceCapabilities function was implemented in the printer driver and you needed to call the LoadLibrary and GetProcAddress functions to get a pointer to the function. This is no longer necessary since DeviceCapabilities is part of the Win32 API and you can call it directly. You should not call LoadLibrary on the printer driver.

The DEVMODE structure pointed to by the pDevMode parameter may be obtained by calling the DocumentProperties function.

See Also

DEVMODE, DocumentProperties, GetDeviceCaps, GetProcAddress, LoadLibrary, POINT


DeviceIoControl
 DeviceIoControl  QuickInfo  Overview  Group

The DeviceIoControl function sends a control code directly to a specified device driver, causing the corresponding device to perform the specified operation.

BOOL DeviceIoControl(

HANDLE  hDevice,	// handle to device of interest
DWORD  dwIoControlCode,	// control code of operation to perform
LPVOID  lpInBuffer,	// pointer to buffer to supply input data
DWORD  nInBufferSize,	// size of input buffer
LPVOID  lpOutBuffer,	// pointer to buffer to receive output data
DWORD  nOutBufferSize,	// size of output buffer
LPDWORD  lpBytesReturned,	// pointer to variable to receive output byte count
LPOVERLAPPED  lpOverlapped	// pointer to overlapped structure for asynchronous operation
);
Parameters

hDevice

Handle to the device that is to perform the operation. Call the CreateFile function to obtain a device handle.

dwIoControlCode

Specifies the control code for the operation. This value identifies the specific operation to be performed and the type of device on which the operation is to be performed. The following values are defined:

Value	Meaning
FSCTL_DISMOUNT_VOLUME	Dismounts a volume.
FSCTL_GET_COMPRESSION	Obtains the compression state of a file or directory
FSCTL_LOCK_VOLUME	Locks a volume.
FSCTL_READ_COMPRESSION	Reserved for future use.
FSCTL_SET_COMPRESSION	Sets the compression state of a file or directory.
FSCTL_UNLOCK_VOLUME	Unlocks a volume.
FSCTL_WRITE_COMPRESSION	Reserved for future use.
IOCTL_DISK_CHECK_VERIFY	Checks for change in a removable-media device.
IOCTL_DISK_EJECT_MEDIA	Ejects media from a SCSI device.
IOCTL_DISK_FORMAT_TRACKS	Formats a contiguous set of disk tracks.
IOCTL_DISK_GET_DRIVE_GEOMETRY	Obtains information on the physical disk's geometry.
IOCTL_DISK_GET_DRIVE_LAYOUT	Provides information about each partition on a disk.
IOCTL_DISK_GET_MEDIA_TYPES	Obtains information about media support.
IOCTL_DISK_GET_PARTITION_INFO	Obtains disk partition information.
IOCTL_DISK_LOAD_MEDIA	Loads media into a device.
IOCTL_DISK_MEDIA_REMOVAL	Enables or disables the media eject mechanism.
IOCTL_DISK_PERFORMANCE	Provides disk performance information.
IOCTL_DISK_REASSIGN_BLOCKS	Maps disk blocks to spare-block pool.
IOCTL_DISK_SET_DRIVE_LAYOUT	Partitions a disk.
IOCTL_DISK_SET_PARTITION_INFO	Sets the disk partition type.
IOCTL_DISK_VERIFY	Performs logical format of a disk extent.
IOCTL_SERIAL_LSRMST_INSERT	Enables or disables placement of a line and modem status data into the data stream.
For more detailed information on each control code, see its topic. In particular, each topic provides details on the usage of the lpInBuffer, nInBufferSize, lpOutBuffer, nOutBufferSize, and lpBytesReturned parameters.

lpInBuffer

Pointer to a buffer that contains the data required to perform the operation.

This parameter can be NULL if the dwIoControlCode parameter specifies an operation that does not require input data.

nInBufferSize

Specifies the size, in bytes, of the buffer pointed to by lpInBuffer.

lpOutBuffer

Pointer to a buffer that receives the operation's output data.

This parameter can be NULL if the dwIoControlCode parameter specifies an operation that does not produce output data.

nOutBufferSize

Specifies the size, in bytes, of the buffer pointed to by lpOutBuffer.

lpBytesReturned

Pointer to a variable that receives the size, in bytes, of the data stored into the buffer pointed to by lpOutBuffer.

This parameter cannot be NULL. Even when an operation produces no output data, and lpOutBuffer can be NULL, the DeviceIoControl function makes use of the variable pointed to by lpBytesReturned. After such an operation, the value of the variable is without meaning.

lpOverlapped

Pointer to an OVERLAPPED structure to be used for asynchronous operations.

This parameter is ignored if the handle identified by hDevice was opened without specifying the FILE_FLAG_OVERLAPPED flag.

This parameter can be NULL if an overlapped (asynchronous) operation is not desired.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

If the lpOverlapped parameter is NULL or the handle identified by hDevice was opened without specifying the FILE_FLAG_OVERLAPPED flag, the DeviceIoControl function does not return until the operation has been completed, or an error occurs.

If the lpOverlapped parameter points to an OVERLAPPED structure and the FILE_FLAG_OVERLAPPED flag was specified when the hDevice handle was opened, DeviceIoControl is performed as an overlapped (asynchronous) operation. In this case, the OVERLAPPED structure must contain a handle to a manual-reset event object (created by using the CreateEvent function). For more information on manual-reset event objects, see Synchronization.

If the overlapped operation cannot be completed immediately, the function returns FALSE, and GetLastError returns the ERROR_IO_PENDING value, indicating that the operation is executing in the background. When this happens, the operating system sets the event object in the OVERLAPPED structure to the nonsignaled state before DeviceIoControl returns. The system then sets the event object to the signaled state when the operation has been completed. The calling thread can use any of the wait functions to determine the state of the event object, then use the GetOverlappedResult function to determine the results of the operation. The GetOverlappedResult function reports the success or failure of the operation and the number of bytes returned in the lpOutBuffer buffer.

See Also

CreateEvent, CreateFile, GetOverlappedResult, OVERLAPPED, WaitForMultipleObjects, WaitForSingleObject


DialogBox
 DialogBox  QuickInfo  Overview  Group

The DialogBox function 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.

int DialogBox(

HANDLE  hInstance,	// handle of application instance
LPCTSTR  lpTemplate,	// identifies dialog box template
HWND  hWndParent,	// handle of owner window
DLGPROC  lpDialogFunc	// address of dialog box procedure
);
Parameters

hInstance

Identifies an instance of the module whose executable file contains the dialog box template.

lpTemplate

Identifies the dialog box template. This parameter is either the address of a null-terminated character string that specifies the name of the dialog box template or an integer value that specifies the resource identifier of the dialog box template. If the parameter specifies a resource identifier, its high-order word must be zero and its low-order word must contain the identifier. You can use the MAKEINTRESOURCE macro to create this value.

hWndParent

Identifies the window that owns the dialog box.

lpDialogFunc

Points to the dialog box procedure. For more information about the dialog box procedure, see the DialogProc callback function.

Return Value

If the function succeeds, the return value is the nResult parameter in the call to the EndDialog function used to terminate the dialog box.

If the function fails, the return value is −1.

Remarks

The DialogBoxIndirect function uses the CreateWindowEx function to create the dialog box. DialogBox then sends a WM_INITDIALOG message (and a WM_SETFONT message if the template specifies the DS_SETFONT style) to the dialog box procedure. The function displays the dialog box (regardless of whether the template specifies the WS_VISIBLE style), disables the owner window, and starts its own message loop to retrieve and dispatch messages for the dialog box.

When the dialog box procedure calls the EndDialog function, DialogBox destroys the dialog box, ends the message loop, enables the owner window (if previously enabled), and returns the nResult parameter given by the dialog box procedure when it called EndDialog.

Windows 95 only: The system can support a maximum of 16,364 window handles.

See Also

CreateDialog, CreateWindowEx, DialogBoxIndirect, DialogBoxIndirectParam, DialogBoxParam, DialogProc, EndDialog, MAKEINTRESOURCE, WM_INITDIALOG, WM_SETFONT


DialogBoxIndirect
 DialogBoxIndirect  QuickInfo  Overview  Group

The DialogBoxIndirect function creates a modal dialog box from a dialog box template in memory. The DialogBoxIndirect function does not return control until the specified callback function terminates the modal dialog box by calling the EndDialog function.

int DialogBoxIndirect(

HANDLE  hInstance,	// handle of application instance
LPDLGTEMPLATE  lpTemplate,	// identifies dialog box template
HWND  hWndParent,	// handle of owner window
DLGPROC  lpDialogFunc	// address of dialog box procedure
);
Parameters

hInstance

Identifies the instance of the module that creates the dialog box.

lpTemplate

Specifies the address of a global memory object that contains a dialog box template used to create the dialog box. The template is in the form of a DLGTEMPLATE structure followed by one or more DLGITEMTEMPLATE structures.

hWndParent

Identifies the window that owns the dialog box.

lpDialogFunc

Points to the dialog box procedure. For more information about the dialog box procedure, see the description of the DialogProc callback function.

Return Value

If the function succeeds, the return value is the nResult parameter given in the call to the EndDialog function used to terminate the dialog box.

If the function fails, the return value is −1.

Remarks

The DialogBoxIndirect function uses the CreateWindowEx function to create the dialog box. DialogBoxIndirect then sends a WM_INITDIALOG message (and a WM_SETFONT message if the template specifies the DS_SETFONT style) to the dialog box procedure. The function displays the dialog box (regardless of whether the template specifies the WS_VISIBLE style), disables the owner window, and starts its own message loop to retrieve and dispatch messages for the dialog box.

When the dialog box procedure calls the EndDialog function, DialogBoxIndirect destroys the dialog box, ends the message loop, enables the owner window (if previously enabled), and returns the nResult parameter given by the dialog box procedure when it called EndDialog.

Windows 95 only: The system can support a maximum of 16,364 window handles.

See Also

CreateWindowEx, DialogBox, DialogBoxIndirectParam, DialogBoxParam, DialogProc, DLGTEMPLATE, DLGITEMTEMPLATE, EndDialog, WM_INITDIALOG, WM_SETFONT


DialogBoxIndirectParam
 DialogBoxIndirectParam  QuickInfo  Overview  Group

The DialogBoxIndirectParam function creates a modal dialog box from a dialog box template in memory. Before displaying the dialog box, the function passes an application-defined value to the dialog box procedure as the lParam parameter of the WM_INITDIALOG message. An application can use this value to initialize dialog box controls.

int DialogBoxIndirectParam(

HINSTANCE  hInstance,	// handle of application instance
LPCDLGTEMPLATE  hDialogTemplate,	// identifies dialog box template
HWND  hWndParent,	// handle of owner window
DLGPROC  lpDialogFunc,	// address of dialog box procedure
LPARAM  dwInitParam	// initialization value
);
Parameters

hInstance

Identifies the instance of the module that creates the dialog box.

hDialogTemplate

Specifies the address of a global memory object that contains a dialog box template used to create the dialog box. The template is in the form of a DLGTEMPLATE structure followed by one or more DLGITEMTEMPLATE structures.

hWndParent

Identifies the window that owns the dialog box.

lpDialogFunc

Points to the dialog box procedure. For more information about the dialog box procedure, see the DialogProc callback function.

dwInitParam

Specifies the value to pass to the dialog box in the lParam parameter of the WM_INITDIALOG message.

Return Value

If the function succeeds, the return value is the nResult parameter given in the call to the EndDialog function used to terminate the dialog box.

If the function fails, the return value is −1.

Remarks

The DialogBoxIndirectParam function uses the CreateWindowEx function to create the dialog box. DialogBoxIndirectParam then sends a WM_INITDIALOG message (and a WM_SETFONT message if the template specifies the DS_SETFONT style) to the dialog box procedure. The function displays the dialog box (regardless of whether the template specifies the WS_VISIBLE style), disables the owner window, and starts its own message loop to retrieve and dispatch messages for the dialog box.

When the dialog box procedure calls the EndDialog function, DialogBoxIndirectParam destroys the dialog box, ends the message loop, enables the owner window (if previously enabled), and returns the nResult parameter given by the dialog box procedure when it called EndDialog.

Windows 95 only: The system can support a maximum of 16,364 window handles.

See Also

CreateWindowEx, DialogBox, DialogBoxIndirect, DialogBoxParam, DialogProc, DLGTEMPLATE, DLGITEMTEMPLATE, EndDialog, WM_INITDIALOG, WM_SETFONT


DialogBoxParam
 DialogBoxParam  QuickInfo  Overview  Group

The DialogBoxParam function creates a modal dialog box from a dialog box template resource. Before displaying the dialog box, the function passes an application-defined value to the dialog box procedure as the lParam parameter of the WM_INITDIALOG message. An application can use this value to initialize dialog box controls.

int DialogBoxParam(

HINSTANCE  hInstance,	// handle of application instance
LPCTSTR  lpTemplateName,	// identifies dialog box template
HWND  hWndParent,	// handle of owner window
DLGPROC  lpDialogFunc,	// address of dialog box procedure
LPARAM  dwInitParam	// initialization value
);
Parameters

hInstance

Identifies an instance of the module whose executable file contains the dialog box template.

lpTemplateName

Identifies the dialog box template. This parameter is either the address of a null-terminated character string that specifies the name of the dialog box template or an integer value that specifies the resource identifier of the dialog box template. If the parameter specifies a resource identifier, its high-order word must be zero and its low-order word must contain the identifier. You can use the MAKEINTRESOURCE macro to create this value.

hWndParent

Identifies the window that owns the dialog box.

lpDialogFunc

Points to the dialog box procedure. For more information about the dialog box procedure, see the DialogProc callback function.

dwInitParam

Specifies the value to pass to the dialog box in the lParam parameter of the WM_INITDIALOG message.

Return Value

If the function succeeds, the return value is the value of the nResult parameter given in the call to the EndDialog function used to terminate the dialog box.

If the function fails, the return value is −1.

Remarks

The DialogBoxParam function uses the CreateWindowEx function to create the dialog box. DialogBoxParam then sends a WM_INITDIALOG message (and a WM_SETFONT message if the template specifies the DS_SETFONT style) to the dialog box procedure. The function displays the dialog box (regardless of whether the template specifies the WS_VISIBLE style), disables the owner window, and starts its own message loop to retrieve and dispatch messages for the dialog box.

When the dialog box procedure calls the EndDialog function, DialogBoxParam destroys the dialog box, ends the message loop, enables the owner window (if previously enabled), and returns the nResult parameter given by the dialog box procedure when it called EndDialog.

Windows 95 only: The system can support a maximum of 16,364 window handles.

See Also

CreateWindowEx, DialogBox, DialogBoxIndirect, DialogBoxIndirectParam, DialogProc, EndDialog, MAKEINTRESOURCE, WM_INITDIALOG, WM_SETFONT


DialogProc
 DialogProc  QuickInfo  Overview  Group

The DialogProc function is an application-defined callback function that processes messages sent to a modal or modeless dialog box.

BOOL CALLBACK DialogProc(

HWND  hwndDlg,	// handle of dialog box
UINT  uMsg,	// message
WPARAM  wParam,	// first message parameter
LPARAM  lParam	// second message parameter
);
Parameters

hwndDlg

Identifies the dialog box.

uMsg

Specifies the message.

wParam

Specifies additional message-specific information.

lParam

Specifies additional message-specific information.

Return Value

Except in response to the WM_INITDIALOG message, the dialog box procedure should return nonzero if it processes the message, and zero if it does not. In response to a WM_INITDIALOG message, the dialog box procedure should return zero if it calls the SetFocus function to set the focus to one of the controls in the dialog box. Otherwise, it should return nonzero, in which case the system sets the focus to the first control in the dialog box that can be given the focus.

Remarks

You should use the dialog box procedure only if you use the dialog box class for the dialog box. This is the default class and is used when no explicit class is given 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.

DialogProc is a placeholder for the application-defined function name.

See Also

CreateDialog, CreateDialogIndirect, CreateDialogIndirectParam, CreateDialogParam, DefWindowProc, DialogBox, DialogBoxIndirect, DialogBoxIndirectParam, DialogBoxParam, SetFocus, WM_INITDIALOG


DisableThreadLibraryCalls
 DisableThreadLibraryCalls  QuickInfo  Overview  Group

The DisableThreadLibraryCalls function disables the DLL_THREAD_ATTACH and DLL_THREAD_DETACH notifications for the dynamic-link library (DLL) specified by hLibModule. This can reduce the size of the working code set for some applications.

BOOL DisableThreadLibraryCalls(

HMODULE  hLibModule	// dynamic-link library for which calls are to be disabled
);
Parameters

hLibModule

Specifies the dynamic-link library module for which the DLL_THREAD_ATTACH and DLL_THREAD_DETACH notifications are to be disabled.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. The DisableThreadLibraryCalls function fails if the DLL specified by hLibModule has active static thread local storage, or if hLibModule is an invalid module handle. To get extended error information, call GetLastError.

Remarks

The DisableThreadLibraryCalls function lets a DLL disable the DLL_THREAD_ATTACH and DLL_THREAD_DETACH notification calls. This can be a useful optimization for multithreaded applications that have many DLLs, frequently create and delete threads, and whose DLLs do not need these thread-level notifications of attachment/detachment. A remote procedure call (RPC) server application is an example of such an application. In these sorts of applications, DLL initialization routines often remain in memory to service DLL_THREAD_ATTACH and DLL_THREAD_DETACH notifications. By disabling the notifications, the DLL initialization code is not paged in because a thread is created or deleted, thus reducing the size of the application's working code set. To implement the optimization, modify a DLL's DLL_PROCESS_ATTACH code to call DisableThreadLibraryCalls.

See Also

FreeLibraryAndExitThread


DisconnectNamedPipe
 DisconnectNamedPipe  QuickInfo  Overview  Group

The DisconnectNamedPipe function disconnects the server end of a named pipe instance from a client process.

BOOL DisconnectNamedPipe(

HANDLE  hNamedPipe	// handle of named pipe
);
Parameters

hNamedPipe

Identifies an instance of a named pipe. This handle must be created by the CreateNamedPipe function.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

If the client end of the named pipe is open, the DisconnectNamedPipe function forces that end of the named pipe closed. The client receives an error the next time it attempts to access the pipe. A client that is forced off a pipe by DisconnectNamedPipe must still use the CloseHandle function to close its end of the pipe.

When the server process disconnects a pipe instance, any unread data in the pipe is discarded. Before disconnecting, the server can make sure data is not lost by calling the FlushFileBuffers function, which does not return until the client process has read all the data.

The server process must call DisconnectNamedPipe to disconnect a pipe handle from its previous client before the handle can be connected to another client by using the ConnectNamedPipe function.

See Also

CloseHandle, ConnectNamedPipe, CreateNamedPipe, FlushFileBuffers


DispatchMessage
 DispatchMessage  QuickInfo  Overview  Group

The DispatchMessage function dispatches a message to a window procedure. It is typically used to dispatch a message retrieved by the GetMessage function.

LONG DispatchMessage(

CONST MSG  * lpmsg	// address of structure with message
);
Parameters

lpmsg

Points to an MSG structure that contains the message.

Return Value

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.

See Also

GetMessage, MSG, PeekMessage, PostAppMessage, PostMessage, TranslateMessage, WM_TIMER


DlgDirList
 DlgDirList  QuickInfo  Overview  Group

The DlgDirList function fills the specified list box with the names of all files matching the specified path or filename.

int DlgDirList(

HWND  hDlg,	// handle of dialog box with list box
LPTSTR  lpPathSpec,	// address of path or filename string
int  nIDListBox,	// identifier of list box
int  nIDStaticPath,	// identifier of static control
UINT  uFileType	// file attributes to display
);
Parameters

hDlg

Identifies the dialog box that contains the list box.

lpPathSpec

Points to a null-terminated string that contains the path or filename. DlgDirList modifies this string, which should be long enough to contain the modifications. For more information about this parameter, see the Remarks section.

nIDListBox

Specifies the identifier of a list box. If this parameter is zero, DlgDirList assumes that no list box exists and does not attempt to fill one.

nIDStaticPath

Specifies the identifier of the static control used for displaying the current drive and directory. If this parameter is zero, DlgDirList assumes that no such control is present.

uFileType

Specifies attributes of the filenames to be displayed. This parameter must be one or more of the following values:

Value	Description
DDL_ARCHIVE	Includes archived files.
DDL_DIRECTORY	Includes subdirectories. Subdirectory names are enclosed in square brackets ([ ]).
DDL_DRIVES	Includes drives. Drives are listed in the form [-x-], where x is the drive letter.
DDL_EXCLUSIVE	Includes only files with the specified attributes. By default, read-write files are listed even if DDL_READWRITE is not specified.
DDL_HIDDEN	Includes hidden files.
DDL_READONLY	Includes read-only files.
DDL_READWRITE	Includes read-write files with no additional attributes.
DDL_SYSTEM	Includes system files.
DDL_POSTMSGS	Posts messages to the application's message queue. By default, DlgDirList sends messages directly to the dialog box procedure.
Return Value

If a listing is made — even an empty listing — the return value is nonzero. If the input string does not contain a valid search path, the return value is zero.

Remarks

If you specify a zero-length string for the lpPathSpec parameter or if you specify only a directory name with no filename, the string will be changed to *.*

The lpPathSpec parameter has the following form:

[drive:] [[\u]directory[\idirectory]\u] [filename]

In this example, drive is a drive letter, directory is a valid directory name, and filename is a valid filename that must contain at least one wildcard (? or *).

If lpPathSpec includes a drive or directory name, or both, the current drive and directory are changed to the specified drive and directory before the list box is filled. The static control identified by the nIDStaticPath parameter is also updated with the new drive or directory name, or both.

After the list box is filled, DlgDirList updates lpPathSpec by removing the drive or directory portion, or both, of the path and filename.

DlgDirList sends the LB_RESETCONTENT and LB_DIR messages to the list box.

See Also

DlgDirListComboBox, DlgDirSelectComboBoxEx, DlgDirSelectEx


DlgDirListComboBox
 DlgDirListComboBox  QuickInfo  Overview  Group

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

int DlgDirListComboBox(

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

hDlg

Identifies the dialog box that contains the combo box.

lpPathSpec

Points to a null-terminated string of the following form:

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

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

nIDComboBox

Specifies the identifier of a combo box control in a dialog box. If nIDComboBox is zero, the DlgDirListComboBox function assumes no combo box exists and does not attempt to fill it.

nIDStaticPath

Specifies the identifier of the static text control in which the DlgDirListComboBox function is to display the current directory. If nIDStaticPath is zero, DlgDirListComboBox assumes no such control is present.

uFiletype

Specifies the attributes of the files to be displayed. It can be any combination of the following values:

Value	Meaning
DDL_ARCHIVE	Includes archived files.
DDL_DIRECTORY	Includes subdirectories. Subdirectory names are enclosed in square brackets ([ ]).
DDL_DRIVES	Includes drives. Drives are listed in the form [-x-], where x is the drive letter.
DDL_EXCLUSIVE	Includes only files with the specified attributes. By default, read-write files are listed even if DDL_READWRITE is not specified.
DDL_HIDDEN	Includes hidden files.
DDL_READONLY	Includes read-only files.
DDL_READWRITE	Includes read-write files with no additional attributes.
DDL_SYSTEM	Includes system files.
DDL_POSTMSGS	Posts messages to the application's message queue. By default, the DlgDirList function sends messages directly to the dialog box procedure.
Return Value

If the function succeeds, the return value is nonzero.

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

Remarks

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

Windows NT:

The directory listing displays long filenames, if any.

Windows 95:

The directory listing displays short filenames (the 8.3 form). You can use the SHGetFileInfo or GetFullPathName functions to get the corresponding long filename.

See Also

DlgDirList, DlgDirSelectComboBoxEx, GetFullPathName, SHGetFileInfo


DlgDirSelect
 DlgDirSelect  Overview  Group

The DlgDirSelect function is not implemented in the Win32 API. Win32-based applications should use the DlgDirSelectEx function.


DlgDirSelectComboBox
 DlgDirSelectComboBox  Overview  Group

The DlgDirSelectComboBox function is not implemented in the Win32 API. Win32-based applications should use the DlgDirSelectComboBoxEx function.


DlgDirSelectComboBoxEx
 DlgDirSelectComboBoxEx  QuickInfo  Overview  Group

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

hDlg

Identifies the dialog box that contains the combo box.

lpString

Points to the buffer that is to receive the selected path.

nCount

Specifies the length, in characters, of the buffer pointed to by the lpString parameter.

nIDComboBox

Specifies the integer identifier of the combo box control in the dialog box.

Return Value

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

Remarks

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

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

DlgDirSelectComboBoxEx sends CB_GETCURSEL and CB_GETLBTEXT messages to the combo box.

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

See Also

CB_GETCURSEL, CB_GETLBTEXT DlgDirListComboBox, DlgDirSelectEx


DlgDirSelectEx
 DlgDirSelectEx  QuickInfo  Overview  Group

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 of dialog box with list box
LPTSTR  lpString,	// address of buffer for path string
int  nCount,	// number of characters in path string
int  nIDListBox	// identifier of list box
);
Parameters

hDlg

Identifies the dialog box that contains the list box.

lpString

Points to a buffer that is to receive the selected path.

nCount

Specifies the length, in characters, of the buffer pointed to by lpString.

nIDListBox

Specifies the integer identifier of a list box in the dialog box.

Return Value

If the current selection is a directory name, the return value is nonzero; otherwise, it 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.

See Also

DlgDirList, DlgDirListComboBox, DlgDirSelectComboBoxEx, LB_GETCURSEL, LB_GETTEXT


DllEntryPoint
 DllEntryPoint  QuickInfo  Overview  Group

The DllEntryPoint function is an optional method of entry into a dynamic-link library (DLL). If the function is used, it is called by the system when processes and threads are initialized and terminated, or upon calls to the LoadLibrary and FreeLibrary functions. DllEntryPoint is a placeholder for the library-defined function name. The actual name must be specified on the linker command line by the -entry switch.

BOOL WINAPI DllEntryPoint(

HINSTANCE  hinstDLL,	// handle of DLL module
DWORD  fdwReason,	// reason for calling function
LPVOID  lpvReserved	// reserved
);
Parameters

hinstDLL

Identifies a handle to the DLL. This handle can be used in subsequent calls to the GetModuleFileName function and other module functions.

fdwReason

Specifies a flag indicating why the DLL entry-point function is being called. This parameter can be one of the following values:

Value	Meaning
DLL_PROCESS_ATTACH
	Indicates that the DLL is attaching to the address space of the current process as a result of the process starting up or as a result of a call to LoadLibrary. DLLs can use this opportunity to initialize any instance data or to use the TlsAlloc function to allocate a thread local storage (TLS) index.
	During initial process startup or after a call to LoadLibrary, the operating system scans the list of loaded DLLs for the process. For each DLL that has not already been called with the DLL_PROCESS_ATTACH value, the system calls the DLL's entry-point function. This call is made in the context of the thread that caused the process address space to change, such as the primary thread of the process or the thread that called LoadLibrary.
DLL_THREAD_ATTACH
	Indicates that the current process is creating a new thread. When this occurs, the system calls the entry-point function of all DLLs currently attached to the process. The call is made in the context of the new thread. DLLs can use this opportunity to initialize a TLS slot for the thread. A thread calling the DLL entry-point function with the DLL_PROCESS_ATTACH value does not call the DLL entry-point function with the DLL_THREAD_ATTACH value.
	Note that a DLL's entry-point function is called with this value only by threads created after the DLL is attached to the process. When a DLL is attached by LoadLibrary, existing threads do not call the entry-point function of the newly loaded DLL.
DLL_THREAD_DETACH
	Indicates that a thread is exiting cleanly. If the DLL has stored a pointer to allocated memory in a TLS slot, it uses this opportunity to free the memory. The operating system calls the entry-point function of all currently loaded DLLs with this value. The call is made in the context of the exiting thread. There are cases in which the entry-point function is called for a terminating thread even if the DLL never attached to the thread — for example, the entry-point function was never called with the DLL_THREAD_ATTACH value in the context of the thread in either of these two situations:
•	The thread was the initial thread in the process, so the system called the entry-point function with the DLL_PROCESS_ATTACH value.

•	The thread was already running when a call to the LoadLibrary function was made, so the system never called the entry-point function for it.

DLL_PROCESS_DETACH
	Indicates that the DLL is detaching from the address space of the calling process as a result of either a clean process exit or of a call to FreeLibrary. The DLL can use this opportunity to call the TlsFree function to free any TLS indices allocated by using TlsAlloc and to free any thread local data. When a DLL detaches from a process as a result of process termination or as a result of a call to FreeLibrary, the operating system does not call the DLL's entry-point function with the DLL_THREAD_DETACH value for the individual threads of the process. The DLL is only given DLL_PROCESS_DETACH notification. DLLs can take this opportunity to clean up all resources for all threads attached and known to the DLL.
lpvReserved

Specifies further aspects of DLL initialization and cleanup.

If fdwReason is DLL_PROCESS_ATTACH, lpvReserved is NULL for dynamic loads and non-NULL for static loads.

If fdwReason is DLL_PROCESS_DETACH, lpvReserved is NULL if DllEntryPoint has been called by using FreeLibrary and non-NULL if DllEntryPoint has been called during process termination.

Return Value

When the system calls the DllEntryPoint function with the DLL_PROCESS_ATTACH value, the function returns TRUE if it succeeds or FALSE if initialization fails. If the return value is FALSE when DllEntryPoint is called because the process uses the LoadLibrary function, LoadLibrary returns NULL. If the return value is FALSE when DllEntryPoint is called during process initialization, the process terminates with an error. To get extended error information, call GetLastError.

When the system calls the DllEntryPoint function with any value other than DLL_PROCESS_ATTACH, the return value is ignored.

See Also

FreeLibrary, GetModuleFileName, LoadLibrary, TlsAlloc, TlsFree


DocumentProperties
 DocumentProperties  QuickInfo  Overview  Group

The DocumentProperties function retrieves or modifies printer initialization information or displays a printer-configuration dialog box for the specified printer.

LONG DocumentProperties(

HWND  hWnd,	// handle of window that displays dialog box
HANDLE  hPrinter,	// handle of printer object
LPTSTR  pDeviceName,	// address of device name
PDEVMODE  pDevModeOutput,	// address of modified device mode structure
PDEVMODE  pDevModeInput,	// address of original device mode structure
DWORD  fMode	// mode flag
);
Parameters

hWnd

Identifies the parent window of the printer-configuration dialog box.

hPrinter

Identifies a printer object.

pDeviceName

Points to a null-terminated string that specifies the name of the device for which the printer-configuration dialog box should be displayed.

pDevModeOutput

Points to a DEVMODE structure that receives the printer configuration data specified by the user.

pDevModeInput

Points to a DEVMODE structure used to initialize the dialog box controls.

fMode

Specifies a mask of values that determines the operations the function performs. If this parameter is zero, the DocumentProperties function returns the number of bytes required by the printer driver's DEVMODE data structure. Otherwise, use one or more of the following constants to construct a value for this parameter; note, however, that in order to change the print settings, an application must specify at least one input value and one output value:

Value	Meaning
DM_IN_BUFFER	Input value. Before prompting, copying, or updating, the function merges the printer driver's current print settings with the settings in the DEVMODE structure specified by the pDevModeInput parameter. The function updates the structure only for those members specified by the DEVMODE structure's dmFields member. This value is also defined as DM_MODIFY. In cases of conflict during the merge, the settings in the DEVMODE structure specified by pDevModeInput override the printer driver's current print settings.
DM_IN_PROMPT	Input value. The function presents the printer driver's Print Setup dialog box and then changes the settings in the printer's DEVMODE data structure to those values specified by the user. This value is also defined as DM_PROMPT.
DM_OUT_BUFFER	Output value. The function writes the printer driver's current print settings, including private data, to the DEVMODE data structure specified by the pDevModeOutput parameter. The caller must allocate a buffer sufficiently large to contain the information. If the bit DM_OUT_BUFFER sets is clear, the pDevModeOutput parameter can be NULL. This value is also defined as DM_COPY.
Return Value

If the fMode parameter is zero, the return value is the size of the buffer required to contain the printer driver initialization data. Note that this buffer can be larger than a DEVMODE structure if the printer driver appends private data to the structure.

If the function displays the initialization dialog box, the return value is either IDOK or IDCANCEL, depending on which button the user selects.

If the function does not display the dialog box and is successful, the return value is IDOK.

If the function fails, the return value is less than zero.

Remarks

The printer object handle identified by the hPrinter parameter can be obtained by calling the OpenPrinter function.

The string pointed to by the pDeviceName parameter can be obtained by calling the GetPrinter function.

Note that the DEVMODE structure actually used by a printer driver contains the device-independent part (as defined above) followed by a driver-specific part that varies in size and content with each driver and driver version. Because of this driver dependence, it is very important for applications to query the driver for the correct size of the DEVMODE structure before allocating a buffer for it.

To make changes to print settings that are local to an application, an application should follow these steps:

1.	Get the number of bytes required for the full DEVMODE structure by calling DocumentProperties and specifying zero in the fMode parameter.

2.	Allocate memory for the full DEVMODE structure.

3.	Get the current printer settings by calling DocumentProperties. Pass a pointer to the DEVMODE structure allocated in Step 2 as the pDevModeOutput parameter and specify the DM_OUT_BUFFER value.

4.	Modify the appropriate members of the returned DEVMODE structure and indicate which members were changed by setting the corresponding bits in the dmFields member of the DEVMODE.

5.	Call DocumentProperties and pass the modified DEVMODE structure back as both the pDevModeInput and pDevModeOutput parameters and specify both the DM_IN_BUFFER and DM_OUT_BUFFER values (which are combined using the OR operator).

The DEVMODE structure returned by the third call to DocumentProperties can be used as an argument in a call to the CreateDC function.

To create a handle of a printer-device context using the current printer settings, you only need to call DocumentProperties twice, as described above. The first call gets the size of the full DEVMODE and the second call initializes the DEVMODE with the current printer settings. Pass the initialized DEVMODE to CreateDC to obtain the handle of the printer device context.

See Also

AdvancedDocumentProperties, CreateDC, DEVMODE, GetPrinter, OpenPrinter


DOS3Call
 DOS3Call  Overview  Group

The DOS3Call function is not implemented in the Win32 API. Win32-based applications cannot call MS-DOS directly.


DosDateTimeToFileTime
 DosDateTimeToFileTime  QuickInfo  Overview  Group

The DosDateTimeToFileTime function converts MS-DOS date and time values to a 64-bit file time.

BOOL DosDateTimeToFileTime(

WORD  wFatDate,	// 16-bit MS-DOS date
WORD  wFatTime,	// 16-bit MS-DOS time
LPFILETIME  lpFileTime	// address of buffer for 64-bit file time
);
Parameters

wFatDate

Specifies the MS-DOS date. The date is a packed 16-bit value with the following format:

Bits	Contents
0−4	Day of the month (1−31)
5−8	Month (1 = January, 2 = February, and so on)
9−15	Year offset from 1980 (add 1980 to get actual year)
wFatTime

Specifies the MS-DOS time. The time is a packed 16-bit value with the following format:

Bits	Contents
0−4	Second divided by 2
5−10	Minute (0−59)
11−15	Hour (0−23 on a 24-hour clock)
lpFileTime

Points to a FILETIME structure to receive the converted 64-bit file time.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

FILETIME, FileTimeToDosDateTime, FileTimeToSystemTime, SystemTimeToFileTime


DPtoLP
 DPtoLP  QuickInfo  Overview  Group

The DPtoLP function converts device coordinates into logical coordinates. The conversion depends on the mapping mode of the device context (DC), the settings of the origins and extents for the window and viewport, and the world transformation.

BOOL DPtoLP(

HDC  hdc,	// handle of device context
LPPOINT  lpPoints,	// address of array of points
int  nCount	// count of points
);
Parameters

hdc

Identifies the DC.

lpPoints

Points to an array of POINT structures. The x- and y-coordinates contained in each POINT structure will be transformed.

nCount

Specifies the number of points in the array.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

This function fails if the device coordinates exceed 27 bits, or if the converted logical coordinates exceed 32 bits. In the case of such an overflow, the results for all the points are undefined.

See Also

LPtoDP, POINT


DragAcceptFiles
 DragAcceptFiles  QuickInfo  Overview  Group

The DragAcceptFiles function registers whether a window accepts dropped files.

VOID DragAcceptFiles(

HWND  hWnd,	// handle of the registering window
BOOL  fAccept	// acceptance option
);
Parameters

hWnd

Identifies the window registering whether it accepts dropped files.

fAccept

Specifies whether the window identified by the hWnd parameter accepts dropped files. This value is TRUE to accept dropped files; it is FALSE to discontinue accepting dropped files.

Return Value

This function does not return a value.

Remarks

An application that calls DragAcceptFiles with the fAccept parameter set to TRUE has identified itself as able to process the WM_DROPFILES message from File Manager.

See Also

WM_DROPFILES


DragDetect
 DragDetect  QuickInfo  Overview  Group

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 given point. The width and height of the drag rectangle are specified by the SM_CXDRAG and SM_CYDRAG values returned by the GetSystemMetrics function.

BOOL DragDetect(

HWND  hwnd,
POINT  pt
);
hwnd

Handle of the window receiving mouse input.

pt

Initial position of the mouse, in screen coordinates. The function determines the coordinates of the drag rectangle by using this point.

Return Value

If the user moved the mouse outside of the drag rectangle while holding the left button down, the return value is TRUE.

If the user did not move the mouse outside of the drag rectangle while holding the left button down, the return value is FALSE.

Remarks

The system metrics for the drag rectangle are configurable, allowing for larger or smaller drag rectangles.

See Also

GetSystemMetrics


DragFinish
 DragFinish  QuickInfo  Overview  Group

The DragFinish function releases memory that Windows allocated for use in transferring filenames to the application.

VOID DragFinish(

HDROP  hDrop	// handle of memory to free
);
Parameters

hDrop

Identifies the structure describing dropped files. This handle is retrieved from the wParam parameter of the WM_DROPFILES message.

Return Value

This function does not return a value.

See Also

WM_DROPFILES


DragQueryFile
 DragQueryFile  QuickInfo  Overview  Group

The DragQueryFile function retrieves the filenames of dropped files.

UINT DragQueryFile(

HDROP  hDrop,	// handle of structure for dropped files
UINT  iFile,	// index of file to query
LPTSTR  lpszFile,	// buffer for returned filename
UINT  cch	// size of buffer for filename
);
Parameters

hDrop

Identifies the structure containing the filenames of the dropped files.

iFile

Specifies the index of the file to query. If the value of the iFile parameter is 0xFFFFFFFF, DragQueryFile returns a count of the files dropped. If the value of the iFile parameter is between zero and the total number of files dropped, DragQueryFile copies the filename with the corresponding value to the buffer pointed to by the lpszFile parameter.

lpszFile

Points to a buffer to receive the filename of a dropped file when the function returns. This filename is a null-terminated string. If this parameter is NULL, DragQueryFile returns the required size, in characters, of the buffer.

cch

Specifies the size, in characters, of the lpszFile buffer.

Return Value

When the function copies a filename to the buffer, the return value is a count of the characters copied, not including the terminating null character.

If the index value is 0xFFFFFFFF, the return value is a count of the dropped files.

If the index value is between zero and the total number of dropped files and the lpszFile buffer address is NULL, the return value is the required size, in characters, of the buffer, not including the terminating null character.

See Also

DragQueryPoint


DragQueryPoint
 DragQueryPoint  QuickInfo  Overview  Group

The DragQueryPoint function retrieves the position of the mouse pointer at the time a file was dropped.

BOOL DragQueryPoint(

HDROP  hDrop,	// handle of structure for dropped file
LPPOINT  lppt	// address of structure for mouse coordinates
);
Parameters

hDrop

Identifies the structure describing the dropped file.

lppt

Points to a POINT structure that the function fills with the coordinates of the mouse pointer at the time the file was dropped.

Return Value

If the drop occurred in the client area of the window, the return value is TRUE; otherwise, it is FALSE.

The DragQueryPoint function fills the POINT structure with the coordinates of the mouse pointer at the time the user released the left mouse button. The window for which coordinates are returned is the window that received the WM_DROPFILES message.

See Also

DragQueryFile, POINT, WM_DROPFILES


DrawAnimatedRects [New - Windows 95]
 DrawAnimatedRects  QuickInfo  Overview  Group

[New - Windows 95]

The DrawAnimatedRects function draws a wire-frame rectangle and animates it to indicate the opening of an icon or the minimizing or maximizing of a window.

BOOL WINAPI DrawAnimatedRects(

HWND hwnd,	// handle of clipping window
int idAni,	// type of animation
CONST RECT * lprcFrom,	// address of rectangle coordinates (minimized)
CONST RECT * lprcTo	// address of rectangle coordinates (restored)
);
Parameters

hwnd

Handle of the window to which the rectangle is clipped. If this parameter is NULL, the working area of the screen is used.

idAni

Windows 95: This parameter is reserved and must be zero.

Windows NT: Specifies the type of animation to perform. This parameter can be one of these values:

Value	Meaning
IDANI_OPEN	Draws the animated rectangle beginning with the position specified by the lprcFrom parameter and ending with the position specified by the lprcTo parameter.
IDANI_CLOSE	Draws the animated rectangle beginning with the position specified by the lprcTo parameter and ending with the position specified by the lprcFrom parameter.
lprcFrom

Points to a SMALL_RECT structure specifying the location and size of the icon or minimized window. Coordinates are relative to the rectangle specified by the lprcClip parameter.

lprcTo

Points to a SMALL_RECT structure specifying the location and size of the restored window. Coordinates are relative to the rectangle specified by the lprcClip parameter.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

See Also

SMALL_RECT


DrawCaption [New - Windows 95]
 DrawCaption  QuickInfo  Overview  Group

[New - Windows 95]

The DrawCaption function draws a window caption.

void WINAPI DrawCaption(

HDC hdc,	// handle of device context
LPRECT lprc,	// address of bounding rectangle coordinates
HFONT hfont,	// handle of font for caption
HICON hicon,	// handle of icon in caption
LPSTR lpszText,	// address of caption string
WORD wFlags	// drawing options
);
Parameters

hdc

Identifies the device context.

lprc

Points to a RECT structure specifying the bounding rectangle for the window caption.

hfont

Identifies the font to use for caption text. To use the standard font, specify NULL for this parameter.

hicon

Identifies the icon to display in the caption. This parameter can be NULL.

lpszText

Points to a null-terminated string containing the caption text. This parameter can be NULL.

wFlags

Specifies drawing options. This parameter can be zero or more of the following values:

Value	Meaning
DC_ACTIVE	Uses the colors for an active caption.
DC_SMALLCAP	Draws a small caption. Uses the current small caption font if the hfont parameter is NULL.
If DC_SMALLCAP is specified, the function draws a normal window caption.

Return Value

This function does not return a value.

See Also

RECT


DrawEdge [New - Windows NT]
 DrawEdge  QuickInfo  Overview  Group

[New - Windows NT]

The DrawEdge function draws one or more edges of rectangle.

BOOL DrawEdge(

HDC hdc,	// handle of device context
LPRECT qrc,	// address of rectangle coordinates
UINT edge,	// type of inner and outer edge to draw
UINT grfFlags	// type of border
);
Parameters

hdc

Identifies the device context.

qrc

Points to a RECT structure that contains the logical coordinates of the rectangle.

edge

Specifies the type of inner and outer edge to draw. This parameter must be a combination of one inner-border flag and one outer-border flag. The inner-border flags are as follows:

Value	Meaning
BDR_RAISEDINNER	Raised inner edge.
BDR_SUNKENINNER	Sunken inner edge.
The outer-border flags are as follows:

Value	Meaning
BDR_RAISEDOUTER	Raised outer edge.
BDR_SUNKENOUTER	Sunken outer edge.
Alternatively, the edge parameter can specify one of the following flags:

Value	Meaning
EDGE_BUMP	Combination of BDR_RAISEDOUTER and BDR_SUNKENINNER.
EDGE_ETCHED	Combination of BDR_SUNKENOUTER and BDR_RAISEDINNER.
EDGE_RAISED	Combination of BDR_RAISEDOUTER and BDR_RAISEDINNER.
EDGE_SUNKEN	Combination of BDR_SUNKENOUTER and BDR_SUNKENINNER.
grfFlags

Specifies the type of border. This parameter can be a combination of these values:

Value	Meaning
BF_ADJUST	Rectangle to be adjusted to leave space for client area.
BF_BOTTOM	Bottom of border rectangle.
BF_BOTTOMLEFT	Bottom and left side of border rectangle.
BF_BOTTOMRIGHT	Bottom and right side of border rectangle.
BF_DIAGONAL	Diagonal border.
BF_DIAGONAL_ENDBOTTOMLEFT	Diagonal border. The end point is the bottom-left corner of the rectangle; the origin is top-right corner.
BF_DIAGONAL_ENDBOTTOMRIGHT	Diagonal border. The end point is the bottom-right corner of the rectangle; the origin is top-left corner.
BF_DIAGONAL_ENDTOPLEFT	Diagonal border. The end point is the top-left corner of the rectangle; the origin is bottom-right corner.
BF_DIAGONAL_ENDTOPRIGHT	Diagonal border. The end point is the top-right corner of the rectangle; the origin is bottom-left corner.
BF_FLAT	Flat border.
BF_LEFT	Left side of border rectangle.
BF_MIDDLE	Interior of rectangle to be filled.
BF_MONO	One-dimensional border.
BF_RECT	Entire border rectangle.
BF_RIGHT	Right side of border rectangle.
BF_SOFT	Soft buttons instead of tiles.
BF_TOP	Top of border rectangle.
BF_TOPLEFT	Top and left side of border rectangle.
BF_TOPRIGHT	Top and right side of border rectangle.
Return Value

If the function succeeds, the return value is TRUE.

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

See Also

RECT


DrawEscape
 DrawEscape  QuickInfo  Overview  Group

The DrawEscape function accesses drawing capabilities of a video display that are not directly available through the graphics device interface (GDI).

int DrawEscape(

HDC  hdc,	// handle of device context
int  nEscape,	// specifies escape function
int  cbInput,	// size of structure for input
LPCSTR  lpszInData	// address of structure for input
);
Parameters

hdc

Identifies the device context for the specified video display.

nEscape

Specifies the escape function to be performed.

cbInput

Specifies the number of bytes of data pointed to by the lpszInData parameter.

lpszInData

Points to the input structure required for the specified escape.

Return Value

The return value specifies the outcome of the function. It is greater than zero if the function is successful, except for the QUERYESCSUPPORT draw escape, which checks for implementation only. The return value is zero if the escape is not implemented. The return value is less than zero if an error occurred. To get extended error information, call GetLastError.

Remarks

When an application calls the DrawEscape function, the data identified by cbInput and lpszInData is passed directly to the specified display driver.


DrawFocusRect
 DrawFocusRect  QuickInfo  Overview  Group

The DrawFocusRect function draws a rectangle in the style used to indicate that the rectangle has the focus.

BOOL DrawFocusRect(

HDC  hDC,	// handle of device context
CONST RECT  * lprc	// address of structure for rectangle
);
Parameters

hDC

Identifies the device context.

lprc

Points to a RECT structure that specifies the logical coordinates of the rectangle.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

Because DrawFocusRect is an XOR function, calling it a second time with the same rectangle removes the rectangle from the screen.

This function draws a rectangle that cannot be scrolled. To scroll an area containing a rectangle drawn by this function, call DrawFocusRect to remove the rectangle from the screen, scroll the area, and then call DrawFocusRect again to draw the rectangle in the new position.

See Also

FrameRect, RECT


DrawFrameControl [New - Windows NT]
 DrawFrameControl  QuickInfo  Overview  Group

[New - Windows NT]

The DrawFrameControl function draws a frame control of the specified type and style.

BOOL DrawFrameControl(

HDC  hdc,	// handle of device context
LPRECT  lprc,	// address of bounding rectangle
UINT  uType,	// frame-control type
UINT  uState	// frame-control state
);
Parameters

hdc

Identifies the device context of the window in which to draw the control.

lprc

Points to a RECT structure that contains the logical coordinates of the bounding rectangle for frame control.

uType

Specifies the type of frame control to draw. This parameter can be one of the following values:

Value	Meaning
DFC_BUTTON	Standard button
DFC_CAPTION	Title bar
DCF_MENU	Menu
DFC_SCROLL	Scroll bar
uState

Specifies the initial state of the frame control. If uType is DFC_BUTTON, uState can be one of the following values:

Value	Meaning
DFCS_BUTTON3STATE	Three-state button
DFCS_BUTTONCHECK	Check box
DFCS_BUTTONPUSH	Push button
DFCS_BUTTONRADIO	Radio button
DFCS_BUTTONRADIOIMAGE	Image for radio button (nonsquare needs image)
DFCS_BUTTONRADIOMASK	Mask for radio button (nonsquare needs mask)
If uType is DFC_CAPTION, uState can be one of the following values:

Value	Meaning
DFCS_CAPTIONCLOSE	Close button
DFCS_CAPTIONHELP	Windows 95 only: Help button
DFCS_CAPTIONMAX	Maximize button
DFCS_CAPTIONMIN	Minimize button
DFCS_CAPTIONRESTORE	Restore button
If uType is DFC_MENU, uState can be one of the following values:

Value	Meaning
DFCS_MENUARROW	Submenu arrow
DFCS_MENUBULLET	Bullet
DFCS_MENUCHECK	Check mark
If uType is DFC_SCROLL, uState can be one of the following values:

Value	Meaning
DFCS_SCROLLCOMBOBOX	Combo box scroll bar
DFCS_SCROLLDOWN	Down arrow of scroll bar
DFCS_SCROLLLEFT	Left arrow of scroll bar
DFCS_SCROLLRIGHT	Right arrow of scroll bar
DFCS_SCROLLSIZEGRIP	Size grip in bottom-right corner of window
DFCS_SCROLLUP	Up arrow of scroll bar
The following style can be used to adjust the bounding rectangle of the push button:

Value	Meaning
DFCS_ADJUSTRECT	Bounding rectangle is adjusted to exclude the surrounding edge of the push button.
One or more of the following values can be used to set the state of the control to be drawn:

Value	Meaning
DFCS_CHECKED	Button is checked.
DFCS_FLAT	Button has a flat border.
DFCS_INACTIVE	Button is inactive (grayed).
DFCS_MONO	Button has a monochrome border.
DFCS_PUSHED	Button is pushed.
Return Value

If the function succeeds, the return value is TRUE.

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

See Also

RECT


DrawIcon
 DrawIcon  QuickInfo  Overview  Group

The DrawIcon function draws an icon in the client area of the window of the specified device context.

BOOL DrawIcon(

HDC  hDC,	// handle of device context
int  X,	// x-coordinate of upper-left corner
int  Y,	// y-coordinate of upper-left corner
HICON  hIcon	// handle of icon to draw
);
Parameters

hDC

Identifies the device context for a window.

X

Specifies the logical x-coordinate of the upper-left corner of the icon.

Y

Specifies the logical y-coordinate of the upper-left corner of the icon.

hIcon

Identifies the icon to be drawn.

Windows NT: The icon resource must have been previously loaded by using the LoadIcon function.

Windows 95: The icon resource must have been previously loaded by using the LoadIcon or LoadImage functions.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. 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.

See Also

CreateIcon, DrawIconEx, LoadIcon


DrawIconEx [New - Windows NT]
 DrawIconEx  QuickInfo  Overview  Group

The DrawIconEx function draws an icon or cursor in the client area of the window of the given device context, performing the specified raster operations, and stretching or compressing the icon or cursor as specified.

BOOL DrawIconEx(

HDC  hdc,	// handle of device context
int  xLeft,	// x-coordinate of upper left corner
int  yTop,	// y-coordinate of upper left corner
HICON  hIcon,	// handle of icon to draw
int  cxWidth,	// width of the icon
int  cyWidth,	// height of the icon
UINT  istepIfAniCur,	// index of frame in animated cursor
HBRUSH  hbrFlickerFreeDraw,	// handle of background brush
UINT  diFlags	// icon-drawing flags
);
Parameters

hdc

Identifies the device context for a window.

xLeft

Specifies the logical x-coordinate of the upper-left corner of the icon or cursor.

yTop

Specifies the logical y-coordinate of the upper-left corner of the icon or cursor.

hIcon

Identifies the icon or cursor to be drawn. This parameter can identify an animated cursor. The icon or cursor resource must have been previously loaded by using the LoadImage function.

cxWidth

Specifies the logical width of the icon or cursor.

cyWidth

Specifies the logical height of the icon or cursor.

istepIfAniCur

Specifies the index of the frame to draw, if hIcon identifies an animated cursor. This parameter is ignored if hIcon does not identify an animated cursor.

hbrFlickerFreeDraw

Identifies a brush that the system uses for flicker-free drawing. If hbrBkgnd is a valid brush handle, the system creates an offscreen bitmap using the given 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 hbrBkgnd is NULL, the system draws the icon or cursor directly into the device context.

diFlags

Specifies the drawing flags. This parameter can be one of the following values:

Value	Meaning
DI_COMPAT	Draws the icon or cursor using the system default image rather than the user-specified image.
DI_DEFAULTSIZE	Draws the icon or cursor in its default width, ignoring the cxWidth and cyWidth parameters.
DI_IMAGE	Performs the raster operation specified by ropImage.
DI_MASK	Performs the raster operation specified by ropMask.
DI_NORMAL	Combination of DI_IMAGE and DI_MASK.
Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

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

See Also

CopyImage, DrawIcon, LoadImage


DrawInsert [New - Windows NT]
 	 DrawInsert  QuickInfo  Overview  Group

[New - Windows NT]

The DrawInsert function draws the insert icon in the parent window of the specified drag list box.

void DrawInsert(

HWND  handParent,
HWND  hLB,
int  nItem
);
Parameters

handParent

Handle to the parent window of the drag list box.

hLB

Handle to the drag list box.

nItem

Identifier of the icon item to be drawn.

Return Value

This function does not return a value.


DrawMenuBar
 DrawMenuBar  QuickInfo  Overview  Group

The DrawMenuBar function redraws the menu bar of the specified window. If the menu bar changes after Windows has created the window, this function must be called to draw the changed menu bar.

BOOL DrawMenuBar(

HWND  hWnd	// handle of window with menu bar to redraw
);
Parameters

hWnd

Identifies the window whose menu bar needs redrawing.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

DeleteMenu, InsertMenuItem, RemoveMenu, SetMenuItemInfo


DrawState [New - Windows 95]
 DrawState  QuickInfo  Overview  Group

[New - Windows 95]

The DrawState function displays an image and applies a visual effect to indicate a state, such as a disabled or default state.

BOOL WINAPI DrawState(

HDC hdc,	// handle of device context
HBRUSH hbr,	// handle of brush
DRAWSTATEPROC lpOutputFunc,	// address of callback function
LPARAM lData,	// image information
WPARAM wData,	// more image information
int x,	// horizontal location of image
int y,	// vertical location of image
int cx,	// width of image
int cy,	// height of image
UINT fuFlags	// image type and state
);
Parameters

hdc

Identifies the device context to draw in.

hbr

Identifies the brush used to draw the image, if the state specified by the fuFlags parameter is DSS_MONO. This parameter is ignored for other states.

lpOutputFunc

Points to an application-defined callback function used to render the image. This parameter is required if the image type in fuFlags is DST_COMPLEX. It is optional and can be NULL if the image type is DST_TEXT. For all other image types, this parameter is ignored. For more information about the callback function, see the DrawStateProc function.

lData

Specifies information about the image. The meaning of this parameter depends on the image type.

wData

Specifies information about the image. The meaning of this parameter depends on the image type. It is, however, zero extended for use with the DrawStateProc function.

x

Specifies the horizontal location at which to draw the image.

y

Specifies the vertical location at which to draw the image.

cx

Specifies the width of the image, in device units. This parameter is required if the image type is DST_COMPLEX. Otherwise, it can be zero to calculate the width of the image.

cy

Specifies the height of the image, in device units. This parameter is required if the image type is DST_COMPLEX. Otherwise, it can be zero to calculate the height of the image.

fuFlags

Specifies the image type and state. The type can be one of these values:

Value (type)	Meaning
DST_BITMAP	The image is a bitmap. The low-order word of the lData parameter is the bitmap handle.
DST_COMPLEX	The image is application defined. To render the image, DrawState calls the callback function specified by the lpOutputFunc parameter.
DST_ICON	The image is an icon. The low-order word of lData is the icon handle.
DST_PREFIXTEXT	The image is text that may contain an accelerator mnemonic. DrawState interprets the ampersand (&) prefix character as a directive to underscore the character that follows. The lData parameter specifies the address of the string, and the wData parameter specifies the length. If wData is zero, the string must be null-terminated.
DST_TEXT	The image is text. The lData parameter specifies the address of the string, and the wData parameter specifies the length. If wData is zero, the string must be null-terminated.
The state can be one of these values:

Value (state)	Meaning
DSS_NORMAL	Draws the image without any modification.
DSS_UNION	Dithers the image.
DSS_DISABLED	Embosses the image.
DSS_DEFAULT	Makes the image bold.
DSS_MONO	Draws the image using the brush specified by the hbr parameter.
For all states except DSS_NORMAL, the image is converted to monochrome before the visual effect is applied.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

See Also

DrawStateProc


DrawStateProc [New - Windows 95]
 DrawStateProc  QuickInfo  Overview  Group

[New - Windows 95]

The DrawStateProc function is an application-defined callback function that renders a complex image for the DrawState function.

BOOL CALLBACK DrawStateProc(

HDC hdc,	// handle of device context
LPARAM lData,	// image information
WPARAM wData,	// more image information
int cx,	// width of image
int cy	// height of image
);
Parameters

hdc

Identifies the device context to draw in. The device context is a memory device context with a bitmap selected, the dimensions of which are at least as great as those specified by the cx and cy parameters.

lData

Specifies information about the image, which the application passed to DrawState.

wData

Specifies information about the image, which the application passed to DrawState.

cx

Specifies the image width, in device units, as specified by the call to DrawState.

cy

Specifies the image height, in device units, as specified by the call to DrawState.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

See Also

DrawState


DrawStatusText [New - Windows NT]
 DrawStatusText  QuickInfo  Overview  Group

[New - Windows NT]

The DrawStatusText function draws the specified text in the style of a status window with borders.

void DrawStatusText(

HDC hdc,
LPRECT  lprc,
LPCTSTR  pszText,
UINT  uFlags
);
Parameters

hdc

Handle to the display context for the window.

lprc

Pointer to a RECT structure that contains the position, in client coordinates, of the rectangle in which the text is drawn. The function draws the borders just inside of the edges of the specified rectangle.

pszText

Pointer to a null-terminated string that specifies the text to display. Tab characters in the string determine whether the string is left-aligned, right-aligned, or centered.

uFlags

Text drawing flags. This parameter can be a combination of these values:

Value	Meaning
SBT_NOBORDERS	Prevents borders from being drawn around the specified text.
SBT_POPOUT	Draws highlighted borders that make the text stand out.
SBT_RTLREADING	Windows 95 only: Displays text using right-to-left reading order on Hebrew or Arabic systems.
Return Value

This function does not return a value.

See Also

RECT


DrawText
 DrawText  QuickInfo  Overview  Group

The DrawText function draws formatted text in the specified rectangle. It formats the text according to the specified method (expanding tabs, justifying characters, breaking lines, and so forth).

int DrawText(

HDC  hDC,	// handle of device context
LPCTSTR  lpString,	// address of string to draw
int  nCount,	// string length, in characters
LPRECT  lpRect,	// address of structure with formatting dimensions
UINT  uFormat	// text-drawing flags
);
Parameters

hDC

Identifies the device context.

lpString

Points to the string to be drawn. If the nCount parameter is −1, the string must be null-terminated.

nCount

Specifies the number of characters in the string. If nCount is −1, then the lpString parameter is assumed to be a pointer to a null-terminated string and DrawText computes the character count automatically.

lpRect

Points to a RECT structure that contains the rectangle (in logical coordinates) in which the text is to be formatted.

uFormat

Specifies the method of formatting the text. It can be any combination of the following values:

Value	Description
DT_BOTTOM	Bottom-justifies text. This value must be combined with DT_SINGLELINE.
DT_CALCRECT	Determines the width and height of the rectangle. If there are multiple lines of text, DrawText uses the width of the rectangle pointed to by the lpRect parameter and extends the base of the rectangle to bound the last line of text. If there is only one line of text, DrawText modifies the right side of the rectangle so that it bounds the last character in the line. In either case, DrawText returns the height of the formatted text but does not draw the text.
DT_CENTER	Centers text horizontally.
DT_EXPANDTABS	Expands tab characters. The default number of characters per tab is eight.
DT_EXTERNALLEADING	Includes the font external leading in line height. Normally, external leading is not included in the height of a line of text.
DT_LEFT	Aligns text to the left.
DT_NOCLIP	Draws without clipping. DrawText is somewhat faster when DT_NOCLIP is used.
DT_NOPREFIX	Turns off processing of prefix characters. Normally, DrawText interprets the mnemonic-prefix character & as a directive to underscore the character that follows, and the mnemonic-prefix characters && as a directive to print a single &. By specifying DT_NOPREFIX, this processing is turned off.
DT_RIGHT	Aligns text to the right.
DT_SINGLELINE	Displays text on a single line only. Carriage returns and linefeeds do not break the line.
DT_TABSTOP	Sets tab stops. Bits 15−8 (high-order byte of the low-order word) of the uFormat parameter specify the number of characters for each tab. The default number of characters per tab is eight.
DT_TOP	Top-justifies text (single line only).
DT_VCENTER	Centers text vertically (single line only).
DT_WORDBREAK	Breaks words. Lines are automatically broken between words if a word would extend past the edge of the rectangle specified by the lpRect parameter. A carriage return-linefeed sequence also breaks the line.
Note that the DT_CALCRECT, DT_EXTERNALLEADING, DT_INTERNAL, DT_NOCLIP, and DT_NOPREFIX values cannot be used with the DT_TABSTOP value.

Return Value

If the function succeeds, the return value is the height of the text.

Remarks

The DrawText function uses the device context's selected font, text color, and background color to draw the text. Unless the DT_NOCLIP format is used, DrawText clips the text so that it does not appear outside the given rectangle. All formatting is assumed to have multiple lines unless the DT_SINGLELINE format is specified.

If the selected font is too large for the specified rectangle, the DrawText function does not attempt to substitute a smaller font.

See Also

GrayString, TabbedTextOut, TextOut, RECT


DrawTextEx [New - Windows 95]
 DrawTextEx  QuickInfo  Overview  Group

[New - Windows 95]

The DrawTextEx function draws formatted text in the specified rectangle.

int DrawTextEx(

HDC hdc,	// handle of device context
LPTSTR lpchText,	// address of string to draw
int cchText,	// length of string to draw
LPRECT lprc,	// address of rectangle coordinates
UINT dwDTFormat,	// formatting options
LPDRAWTEXTPARAMS lpDTParams	// address of structure for more options
);
Parameters

hdc

Identifies the device context to draw in.

lpchText

Points to the string to draw. The string must be null-terminated if the cchText parameter is  −1.

cchText

Specifies the length, in characters, of the string specified by the lpchText parameter. If the string is null-terminated, this parameter can be  −1 to calculate the length.

lprc

Points to a RECT structure that contains the rectangle, in logical coordinates, in which the text is to be formatted.

dwDTFormat

Specifies formatting options. This parameter can be one or more of these values:

Value	Meaning
DT_BOTTOM	Justifies the text to the bottom pf the rectangle. This value must be combined with DT_SINGLELINE.
DT_CALCRECT	Determines the width and height of the rectangle. If there are multiple lines of text, DrawTextEx uses the width of the rectangle pointed to by the lprc parameter and extends the base of the rectangle to bound the last line of text. If there is only one line of text, DrawTextEx modifies the right side of the rectangle so that it bounds the last character in the line. In either case, DrawTextEx returns the height of the formatted text, but does not draw the text.
DT_CENTER	Centers text horizontally in the rectangle.
DT_EDITCONTROL	Duplicates the text-displaying characteristics of a multiline edit control. Specifically, the average character width is calculated in the same manner as for an edit control, and the function does not display a partially visible last line.
DT_END_ELLIPSIS or DT_PATH_ELLIPSIS	Replaces part of the given string with ellipses, if necessary, so that the result fits in the specified  rectangle. The given string is not modified unless the DT_MODIFYSTRING flag is specified. You can specify DT_END_ELLIPSIS to replace characters at the end of the string, or DT_PATH_ELLIPSIS to replace characters in the middle of the string. If the string contains backslash (\) characters, DT_PATH_ELLIPSIS preserves as much as possible of the text after the last backslash.
DT_EXPANDTABS	Expands tab characters. The default number of characters per tab is 8.
DT_EXTERNALLEADING	Includes the font external leading in line height. Normally, external leading is not included in the height of a line of text.
DT_LEFT	Aligns text to the left.
DT_MODIFYSTRING	Modifies the given string to match the displayed text. This flag has no effect unless the DT_END_ELLIPSIS or DT_PATH_ELLIPSIS flag is specified.
DT_NOCLIP	Draws without clipping. DrawTextEx is somewhat faster when DT_NOCLIP is used.
DT_NOPREFIX	Turns off processing of prefix characters. Normally, DrawTextEx interprets the ampersand (&) mnemonic-prefix character as a directive to underscore the character that follows, and the double ampersand (&&) mnemonic-prefix characters as a directive to print a single ampersand. By specifying DT_NOPREFIX, this processing is turned off.
DT_RIGHT	Aligns text to the right.
DT_RTLREADING	Layout in right to left reading order for bi-directional text when the font selected into the hdc is a Hebrew or Arabic. The default reading order for all text is left to right.
DT_SINGLELINE	Displays text on a single line only. Carriage returns and linefeeds do not break the line.
DT_TABSTOP	Sets tab stops. The DRAWTEXTPARAMS structure pointed to by the lpDTParams parameter specifies the number of average character widths per tab stop.
DT_TOP	Top justifies text (single line only).
DT_VCENTER	Centers text vertically (single line only).
DT_WORDBREAK	Breaks words. Lines are automatically broken between words if a word extends past the edge of the rectangle specified by the lprc parameter. A carriage return-linefeed sequence also breaks the line.
dwDTParams

Points to a DRAWTEXTPARAMS structure that specifies additional formatting options. This parameter can be NULL.

Return Value

If the function succeeds, the return value is the text height.

If the function fails, the return value is zero.

See Also

DrawText, DRAWTEXTPARAMS


DuplicateHandle
 DuplicateHandle  QuickInfo  Overview  Group

The DuplicateHandle function duplicates an object handle.

BOOL DuplicateHandle(

HANDLE  hSourceProcessHandle,	// handle of process with handle to duplicate
HANDLE  hSourceHandle,	// handle to duplicate
HANDLE  hTargetProcessHandle,	// handle of process to duplicate to
LPHANDLE  lpTargetHandle,	// address of duplicate handle
DWORD  dwDesiredAccess,	// access for duplicate handle
BOOL  bInheritHandle,	// handle inheritance flag
DWORD  dwOptions	// optional actions
);
Parameters

hSourceProcessHandle

Identifies the process containing the handle to duplicate. The handle must have PROCESS_DUP_HANDLE access.

hSourceHandle

Identifies the handle to duplicate. This is an open object handle that is valid in the context of the source process. For a list of objects whose handles can be duplicated, see the following Remarks section.

hTargetProcessHandle

Identifies the process that is to receive the duplicated handle. The handle must have PROCESS_DUP_HANDLE access.

lpTargetHandle

Points to a variable receiving the value of the duplicate handle. This handle value is valid in the context of the target process. If lpTargetHandle is NULL, the function duplicates the handle, but does not return the duplicate handle value to the caller.

dwDesiredAccess

Specifies the access requested for the new handle. This parameter is ignored if the dwOptions parameter specifies the DUPLICATE_SAME_ACCESS flag. Otherwise, the flags that can be specified depend on the type of object whose handle is being duplicated. For the flags that can be specified for each object type, see the following Remarks section. Note that the new handle can have more access than the original handle.

bInheritHandle

Indicates whether the handle is inheritable. If TRUE, the duplicate handle can be inherited by new processes created by the target process. If FALSE, the new handle cannot be inherited.

dwOptions

Specifies optional actions. This parameter can be zero, or any combination of the following flags:

Value	Meaning
DUPLICATE_CLOSE_SOURCE	Closes the source handle. This occurs regardless of any error status returned.
DUPLICATE_SAME_ACCESS	Ignores the dwDesiredAccess parameter. The duplicate handle has the same access as the source handle.
Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

DuplicateHandle can be called by either the source process or the target process. It can also be invoked where the source and target process are the same. For example, a process can use DuplicateHandle to create a noninheritable duplicate of an inheritable handle, or a handle with different access than the original handle.

The duplicating process uses the GetCurrentProcess function to get a handle of itself. To get the other process handle, it may be necessary to use some form of interprocess communication (for example, named pipe or shared memory) to communicate the process identifier to the duplicating process. This identifier is then used in the OpenProcess function to open a handle.

If the process that calls DuplicateHandle is not the target process, the duplicating process must use interprocess communication to pass the value of the duplicate handle to the target process.

The duplicate handle is the same object handle as the source handle. This means that the state of the object is the same for both handles. For example, the current file mark for a file handle is always the same for both handles.

DuplicateHandle can duplicate handles to the following types of objects:

Object	Description
Console input	The handle is returned by the CreateFile function when CONIN$ is specified, or by the GetStdHandle function when STD_INPUT_HANDLE is specified. Console handles can be duplicated for use only in the same process.
Console screen buffer	The handle is returned by the CreateFile function when CONOUT$ is specified, or by the GetStdHandle function when STD_OUTPUT_HANDLE is specified. Console handles can be duplicated for use only in the same process.
Event	The handle is returned by the CreateEvent or OpenEvent function.
File or communications device	The handle is returned by the CreateFile function.
File mapping	The handle is returned by the CreateFileMapping function.
Mutex	The handle is returned by the CreateMutex or OpenMutex function.
Pipe	A named pipe handle is returned by the CreateNamedPipe or CreateFile function. An anonymous pipe handle is returned by the CreatePipe function.
Process	The handle is returned by the CreateProcess or OpenProcess function.
Registry key	The handle is returned by the RegCreateKey, RegCreateKeyEx, RegOpenKey, or RegOpenKeyEx function. Note that registry key handles returned by the RegConnectRegistry function cannot be used in a call to DuplicateHandle.
Semaphore	The handle is returned by the CreateSemaphore or OpenSemaphore function.
Thread	The handle is returned by the CreateProcess, CreateThread, or CreateRemoteThread function.
In addition to STANDARD_RIGHTS_REQUIRED, the following access flags can be specified in the dwDesiredAccess parameter for the different object types. Note that the new handle can have more access than the original handle. However, in some cases DuplicateHandle cannot create a duplicate handle with more access permission than the original handle. For example, a file handle created with GENERIC_READ access cannot be duplicated so that it has both GENERIC_READ and GENERIC_WRITE access.

Any combination of the following access flags is valid for handles to communications devices, console input, console screen buffers, files, and pipes:

Access	Description
GENERIC_READ	Enables read access.
GENERIC_WRITE	Enables write access.
Any combination of the following access flags is valid for file-mapping objects:

Access	Description
FILE_MAP_ALL_ACCESS	Specifies all possible access flags for the file-mapping object.
FILE_MAP_READ	Enables mapping the object into memory that permits read access.
FILE_MAP_WRITE	Enables mapping the object into memory that permits write access. For write access, PAGE_READWRITE protection must have been specified when the file-mapping object was created by the CreateFileMapping function.
Any combination of the following access flags is valid for mutex objects:

Access	Description
MUTEX_ALL_ACCESS	Specifies all possible access flags for the mutex object.
SYNCHRONIZE	Windows NT: Enables use of the mutex handle in any of the wait functions to acquire ownership of the mutex, or in the ReleaseMutex function to release ownership.
Any combination of the following access flags is valid for semaphore objects:

Access	Description
SEMAPHORE_ALL_ACCESS	Specifies all possible access flags for the semaphore object.
SEMAPHORE_MODIFY_STATE	Enables use of the semaphore handle in the ReleaseSemaphore function to modify the semaphore's count.
SYNCHRONIZE	Windows NT: Enables use of the semaphore handle in any of the wait functions to wait for the semaphore's state to be signaled.
Any combination of the following access flags is valid for event objects:

Access	Description
EVENT_ALL_ACCESS	Specifies all possible access flags for the event object.
EVENT_MODIFY_STATE	Enables use of the event handle in the SetEvent and ResetEvent functions to modify the event's state.
SYNCHRONIZE	Windows NT: Enables use of the event handle in any of the wait functions to wait for the event's state to be signaled.
Any combination of the following access flags is valid for handles to registry keys:

Value	Meaning
KEY_ALL_ACCESS	Specifies all possible flags for the registry key.
KEY_CREATE_LINK	Enables using the handle to create a link to a registry-key object.
KEY_CREATE_SUB_KEY	Enables using the handle to create a subkey of a registry-key object.
KEY_ENUMERATE_SUB_KEYS	Enables using the handle to enumerate the subkeys of a registry-key object.
KEY_EXECUTE	Equivalent to KEY_READ.
KEY_NOTIFY	Enables using the handle to request change notifications for a registry key or for subkeys of a registry key.
KEY_QUERY_VALUE	Enables using the handle to query a value of a registry-key object.
KEY_READ	Combines the STANDARD_RIGHTS_READ, KEY_QUERY_VALUE, KEY_ENUMERATE_SUB_KEYS, and KEY_NOTIFY values.
KEY_SET_VALUE	Enables using the handle to create or set a value of a registry-key object.
KEY_WRITE	Combines the STANDARD_RIGHTS_WRITE, KEY_SET_VALUE, and KEY_CREATE_SUB_KEY values.
Any combination of the following access flags is valid for process objects:

Access	Description
PROCESS_ALL_ACCESS	Specifies all possible access flags for the process object.
PROCESS_CREATE_PROCESS	Used internally.
PROCESS_CREATE_THREAD	Enables using the process handle in the CreateRemoteThread function to create a thread in the process.
PROCESS_DUP_HANDLE	Enables using the process handle as either the source or target process in the DuplicateHandle function to duplicate a handle.
PROCESS_QUERY_INFORMATION	Enables using the process handle in the GetExitCodeProcess and GetPriorityClass functions to read information from the process object.
PROCESS_SET_INFORMATION	Enables using the process handle in the SetPriorityClass function to set the process's priority class.
PROCESS_TERMINATE	Enables using the process handle in the TerminateProcess function to terminate the process.
PROCESS_VM_OPERATION	Enables using the process handle in the VirtualProtectEx and WriteProcessMemory functions to modify the virtual memory of the process.
PROCESS_VM_READ	Enables using the process handle in the ReadProcessMemory function to read from the virtual memory of the process.
PROCESS_VM_WRITE	Enables using the process handle in the WriteProcessMemory function to write to the virtual memory of the process.
SYNCHRONIZE	Windows NT: Enables using the process handle in any of the wait functions to wait for the process to terminate.
Any combination of the following access flags is valid for thread objects:

Access	Description
SYNCHRONIZE	Windows NT: Enables using the thread handle in any of the wait functions to wait for the thread to terminate.
THREAD_ALL_ACCESS	Specifies all possible access flags for the thread object.
THREAD_DIRECT_IMPERSONATION	Used internally.
THREAD_GET_CONTEXT	Enables using the thread handle in the GetThreadContext function to read the thread's context.
THREAD_IMPERSONATE	Used internally.
THREAD_QUERY_INFORMATION	Enables using the thread handle in the GetExitCodeThread, GetThreadPriority, and GetThreadSelectorEntry functions to read information from the thread object.
THREAD_SET_CONTEXT	Enables using the thread handle in the SetThreadContext function to set the thread's context.
THREAD_SET_INFORMATION	Enables using the thread handle in the SetThreadPriority function to set the thread's priority.
THREAD_SET_THREAD_TOKEN	Used internally.
THREAD_SUSPEND_RESUME	Enables using the thread handle in the SuspendThread or ResumeThread functions to suspend or resume a thread.
THREAD_TERMINATE	Enables using the thread handle in the TerminateThread function to terminate the thread.
See Also

CloseHandle, CreateEvent, CreateFile, CreateFileMapping, CreateMutex, CreateNamedPipe, CreatePipe, CreateProcess, CreateRemoteThread, CreateSemaphore, CreateThread, GetCurrentProcess, GetExitCodeProcess, GetExitCodeThread, GetPriorityClass, GetStdHandle, GetThreadContext, GetThreadPriority, GetThreadSelectorEntry, OpenEvent, OpenMutex, OpenProcess, OpenSemaphore, ReadProcessMemory, RegConnectRegistry, RegCreateKey, RegCreateKeyEx, RegOpenKey, RegOpenKeyEx, ReleaseMutex, ReleaseSemaphore, ResetEvent, ResumeThread, SetEvent, SetPriorityClass, SetThreadContext, SetThreadPriority, SuspendThread, TerminateProcess, TerminateThread, VirtualProtectEx, WriteProcessMemory


DuplicateToken
 DuplicateToken  QuickInfo  Overview  Group

The DuplicateToken function creates a new access token that duplicates one already in existence.

BOOL DuplicateToken(

HANDLE  ExistingTokenHandle,	// handle of token to duplicate
SECURITY_IMPERSONATION_LEVEL  ImpersonationLevel,	// impersonation level
PHANDLE  DuplicateTokenHandle	// handle of duplicated token
);
Parameters

ExistingTokenHandle

Identifies an access token opened with TOKEN_DUPLICATE access.

ImpersonationLevel

Specifies a SECURITY_IMPERSONATION_LEVEL enumerated type that supplies the impersonation level of the new token.

DuplicateTokenHandle

Identifies the duplicate access token when the function returns. This handle has TOKEN_IMPERSONATE and TOKEN_QUERY access to the new token.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

Impersonation is the ability of a process to take on the security attributes of another process. Usually, a server process impersonates a client process to complete a task involving objects to which the client normally has no access. If a client does not have an account on the server's domain, for example, the server must impersonate the client to gain access to secured objects.

See Also

DdeImpersonateClient, ImpersonateNamedPipeClient, RevertToSelf, SECURITY_IMPERSONATION_LEVEL


EditWordBreakProc
 EditWordBreakProc  QuickInfo  Overview  Group

An EditWordBreakProc function is an application-defined callback function. A value of type EDITWORDBREAKPROC is a pointer to such a function.

Windows NT: A multiline edit control calls an EditWordBreakProc function whenever the control must break a line of text.

Windows 95: A multiline edit control or a rich edit control calls an EditWordBreakProc function whenever the control must break a line of text.

int CALLBACK EditWordBreakProc(

LPTSTR  lpch,	// address of edit text
int  ichCurrent,	// index of starting point
int  cch,	// length in characters of edit text
int  code	// action to take
);
Parameters

lpch

Points to the text of the edit control.

ichCurrent

Specifies an index to a character position in the buffer of text that identifies the point at which the function should begin checking for a word break.

cch

Specifies the number of characters in the edit control text.

code

Specifies the action to be taken by the callback function. This parameter can be one of the following values:

Value	Action
WB_ISDELIMITER	Checks whether the character at the current position is a delimiter.
WB_LEFT	Looks for the beginning of a word to the left of the current position.
WB_RIGHT	Looks for the beginning of a word to the right of the current position. (This is useful in right-aligned edit controls.)
Windows 95: Additional values for the code parameter are defined for rich edit controls. For a list of these values, see the description of the EM_FINDWORDBREAK message.

Return Value

If the code parameter specifies WB_ISDELIMITER, the return value is nonzero (TRUE) if the character at the current position is a delimiter, or zero if it is not. Otherwise, the return value is an index to the beginning of a word in the buffer of text.

Remarks

A carriage return followed by a linefeed must be treated as a single word by the callback function. Two carriage returns followed by a linefeed also must be treated as a single word.

An application must install the callback function by specifying the address of the callback function in an EM_SETWORDBREAKPROC message.

EditWordBreakProc is a placeholder for an application-defined function name.

See Also

SendMessage, EM_FINDWORDBREAK, EM_SETWORDBREAKPROC


EditWordBreakProcEx
 EditWordBreakProcEx  QuickInfo  Overview  Group

An application-supplied callback function that determines the character index of the word break, or the character class and word break flags of the characters in the given text.

LONG EditWordBreakProcEx(

char  *pchText,
LONG  cchText,
BYTE  bCharSet,
INT  code
);
Parameters

pchText

Address of the text at the current position. If code specifies movement to the left, the text is in the elements pchText[-1] through pchText[-cchText] and pchText[0] is undefined. For all other actions, the text is in the elements pchText[0] through pchText[cchText - 1].

cchText

Number of characters in the buffer in the direction specified by code.

bCharSet

Character set of the text.

code

Wordbreak action to take. Can be one of the values described for the code parameter in the EM_FINDWORDBREAK message.

Return Value

Returns the character index of the word break, unless the code parameter is the WB_CLASSIFY or WB_ISDELIMITER value.

See Also

EM_FINDWORDBREAK


Ellipse
 Ellipse  QuickInfo  Overview  Group

The Ellipse function draws an ellipse. The center of the ellipse is the center of the given bounding rectangle. The ellipse is outlined by using the current pen and is filled by using the current brush.

BOOL Ellipse(

HDC  hdc,	// handle of device context
int  nLeftRect,	// x-coord. of bounding rectangle's upper-left corner
int  nTopRect,	// y-coord. of bounding rectangle's upper-left corner
int  nRightRect,	// x-coord. of bounding rectangle's lower-right corner
int  nBottomRect	// y-coord. bounding rectangle's f lower-right corner
);
Parameters

hdc

Identifies the device context.

nLeftRect

Specifies the x-coordinate of the upper-left corner of the bounding rectangle.

nTopRect

Specifies the y-coordinate of the upper-left corner of the bounding rectangle.

nRightRect

Specifies the x-coordinate of the lower-right corner of the bounding rectangle.

nBottomRect

Specifies the y-coordinate of the lower-right corner of the bounding rectangle.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The current position is neither used nor updated by Ellipse.

Windows 95 only: The sum of the coordinates of the bounding rectangle cannot exceed 32,767. The sum of nLeftRect and nRightRect or nTopRect and nBottomRect parameters cannot exceed 32,767.

See Also

Arc, ArcTo


EmptyClipboard
 EmptyClipboard  QuickInfo  Overview  Group

The EmptyClipboard function empties the clipboard and frees handles to data in the clipboard. The function then assigns ownership of the clipboard to the window that currently has the clipboard open.

BOOL EmptyClipboard(VOID)

Parameters

This function has no parameters.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

Before calling EmptyClipboard, an application must open the clipboard by using the OpenClipboard function. If the application specifies a NULL window handle when opening the clipboard, EmptyClipboard succeeds but sets the clipboard owner to NULL.

See Also

OpenClipboard, SetClipboardData, WM_DESTROYCLIPBOARD


 EnableEUDC

The EnableEUDC function enables or disables end-user-defined characters (EUDC). Enabling EUDC allows text output functions to retrieve information about end-user-defined characters from EUDC fonts. Disabling EUDC prevents output functions from accessing these fonts.

BOOL EnableEUDC(

BOOL  fEnableEUDC
);
Parameters

fEnableEUDC

Action flag. Can be TRUE to enable EUDC or FALSE to disable it.

Return Value

Returns TRUE if successful, FALSE otherwise.

Remarks

Applications call this function before and after adding, modifying, or deleting EUDC fonts. An application must disable EUDC before modifying a EUDC font or before adding or deleting a font from the registry. Application must enable EUDC after these changes to allow functions access to them.

See Also

ImmRegisterWord, ImmUnregisterWord


EnableMenuItem
 EnableMenuItem  QuickInfo  Overview  Group

The EnableMenuItem function enables, disables, or grays the given menu item.

BOOL EnableMenuItem(

HMENU  hMenu,	// handle of menu
UINT  uIDEnableItem,	// menu item to enable, disable, or gray
UINT  uEnable	// menu item flags
);
Parameters

hMenu

Identifies the menu.

uIDEnableItem

Specifies the menu item to be enabled, disabled, or grayed, as determined by the uEnable parameter. This parameter specifies an item in a menu bar or in a pop-up menu.

uEnable

Specifies flags that control the interpretation of the uIDEnableItem parameter and indicate whether the menu item is enabled, disabled, or grayed. This parameter must be a combination of either MF_BYCOMMAND or MF_BYPOSITION and MF_ENABLED, MF_DISABLED, or MF_GRAYED.

Value	Meaning
MF_BYCOMMAND	Indicates that uIDEnableItem gives the identifier of the menu item. If neither the MF_BYCOMMAND nor MF_BYPOSITION flag is specified, the MF_BYCOMMAND flag is the default flag.
MF_BYPOSITION	Indicates that uIDEnableItem gives the zero-based relative position of the menu item.
MF_DISABLED	Indicates that the menu item is disabled, but not grayed, so it cannot be selected.
MF_ENABLED	Indicates that the menu item is enabled and restored from a grayed state so that it can be selected.
MF_GRAYED	Indicates that the menu item is disabled and grayed so that it cannot be selected.
Return Value

The return value specifies the previous state of the menu item (it is either MF_DISABLED, MF_ENABLED, or MF_GRAYED). If the menu item does not exist, the return value is 0xFFFFFFFF.

Remarks

An application must use the MF_BYPOSITION flag to specify the correct menu handle. If the menu handle of 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 pop-up or nested pop-up menu by position, an application must specify the handle of the pop-up menu.

When an application specifies the MF_BYCOMMAND flag, Windows checks all pop-up items that are subordinate to the menu identified by the specified menu handle. Therefore, unless duplicate menu items are present, specifying the menu handle of the menu bar is sufficient.

Windows NT: The CreateMenu, InsertMenu, ModifyMenu, and LoadMenuIndirect functions can also set the state (enabled, disabled, or grayed) of a menu item.

Windows 95: The CreateMenu, InsertMenuItem, SetMenuItemInfo, and LoadMenuIndirect functions can also set the state (enabled, disabled, or grayed) of a menu item.

See Also

CreateMenu, GetMenuItemID, InsertMenu, InsertMenuItem, LoadMenuIndirect, ModifyMenu, SetMenuItemInfo, WM_SYSCOMMAND


EnableScrollBar
 EnableScrollBar  QuickInfo  Overview  Group

The EnableScrollBar function enables or disables one or both scroll bar arrows.

BOOL EnableScrollBar(

HWND  hWnd,	// handle of window or scroll bar
UINT  wSBflags,	// scroll bar type flag
UINT  wArrows	// scroll bar arrow flag
);
Parameters

hWnd

Identifies a window or a scroll bar control, depending on the value of the wSBflags parameter.

wSBflags

Specifies the scroll bar type. This parameter can be one of the following values:

Value	Meaning
SB_BOTH	Enables or disables the arrows on the horizontal and vertical scroll bars associated with the given window. The hWnd parameter must be the handle of the window.
SB_CTL	Identifies the scroll bar as a scroll bar control. The hWnd parameter must be the handle of the scroll bar control.
SB_HORZ	Enables or disables the arrows on the horizontal scroll bar associated with the given window. The hWnd parameter must be the handle of the window.
SB_VERT	Enables or disables the arrows on the vertical scroll bar associated with the given window. The hWnd parameter must be the handle of the window.
wArrows

Specifies whether the scroll bar arrows are enabled or disabled and indicates which arrows are enabled or disabled. This parameter can be one of the following values:

Value	Meaning
ESB_DISABLE_BOTH	Disables both arrows on a scroll bar.
ESB_DISABLE_DOWN	Disables the down arrow on a vertical scroll bar.
ESB_DISABLE_LEFT	Disables the left arrow on a horizontal scroll bar.
ESB_DISABLE_LTUP	Disables the left arrow on a horizontal scroll bar or the up arrow of a vertical scroll bar.
ESB_DISABLE_RIGHT	Disables the right arrow on a horizontal scroll bar.
ESB_DISABLE_RTDN	Disables the right arrow on a horizontal scroll bar or the down arrow of a vertical scroll bar.
ESB_DISABLE_UP	Disables the up arrow on a vertical scroll bar.
ESB_ENABLE_BOTH	Enables both arrows on a scroll bar.
Return Value

If the arrows are enabled or disabled as specified, the return value is TRUE. If the arrows are already in the requested state or an error occurs, the return value is FALSE.

See Also

ShowScrollBar


EnableWindow
 EnableWindow  QuickInfo  Overview  Group

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 of window
BOOL  bEnable	// flag for enabling or disabling input
);
Parameters

hWnd

Identifies the window to be enabled or disabled.

bEnable

Specifies whether to enable or disable the window. If this parameter is TRUE, the window is enabled. If the parameter is FALSE, the window is disabled.

Return Value

If the window was previously disabled, the return value is TRUE; otherwise, the return value is FALSE. To get extended error information, call GetLastError.

Remarks

If the enabled state of a window is changing, a WM_ENABLE message is sent before this function returns. If a window is already disabled, all its child windows are implicitly disabled, although they are not sent a WM_ENABLE message.

A window must be enabled before it can be activated. For example, if an application is displaying a modeless dialog box and has disabled its main window, the application must enable the main window before destroying the dialog box. Otherwise, another window will receive the keyboard focus and be activated. If a child window is disabled, it is ignored when Windows 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 the EnableWindow function 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 access it.

See Also

CreateWindow, CreateWindowEx, IsWindowEnabled, WM_ENABLE


EndDeferWindowPos
 EndDeferWindowPos  QuickInfo  Overview  Group

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 of internal structure
);
Parameters

hWinPosInfo

Identifies 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 Value

If the function succeeds, the return value is TRUE.

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

Remarks

This function sends the WM_WINDOWPOSCHANGING and WM_WINDOWPOSCHANGED messages to each window identified in the internal structure.

See Also

BeginDeferWindowPos, DeferWindowPos, WM_WINDOWPOSCHANGED, WM_WINDOWPOSCHANGING


EndDialog
 EndDialog  QuickInfo  Overview  Group

The EndDialog function destroys a modal dialog box, causing the system to end any processing for the dialog box.

BOOL EndDialog(

HWND  hDlg,	// handle of dialog box
int  nResult	// value to return
);
Parameters

hDlg

Identifies the dialog box to be destroyed.

nResult

Specifies the value to be returned to the application from the function that created the dialog box.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

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.

See Also

DialogBox, DialogBoxIndirect, DialogBoxIndirectParam, DialogBoxParam, WM_INITDIALOG


EndDoc
 EndDoc  QuickInfo  Overview  Group

The EndDoc function ends a print job. This function replaces the ENDDOC printer escape.

int EndDoc(

HDC  hdc	// handle of device context
);
Parameters

hdc

Identifies the device context for the print job.

Return Value

If the function succeeds, the return value is greater than zero.

If the function fails, the return value is less than or equal to zero. To get extended error information, call GetLastError.

Remarks

Applications should call EndDoc immediately after finishing a print job.

See Also

StartDoc


EndDocPrinter
 EndDocPrinter  QuickInfo  Overview  Group

The EndDocPrinter function ends a print job for the given printer.

BOOL EndDocPrinter(

HANDLE  hPrinter	// handle of printer object
);
Parameters

hPrinter

Identifies a printer for which the print job should be ended.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

This function returns an error if the print job was not started by calling the StartDocPrinter function.

See Also

StartDocPrinter


EndPage
 EndPage  QuickInfo  Overview  Group

The EndPage function informs the device that the application has finished writing to a page. This function is typically used to direct the device driver to advance to a new page. This function replaces the NEWFRAME printer escape.

int EndPage(

HDC  hdc	// handle of device context
);
Parameters

hdc

Identifies the device context for the print job.

Return Value

If the function succeeds, the return value is greater than zero.

If the function fails, the return value is less than or equal to zero. To get extended error information, call GetLastError.

Remarks

Use the ResetDC function to change the device mode, if necessary, after calling the EndPage function. Note that a call to ResetDC resets all device context attributes back to default values.

Windows 3.x: EndPage resets the device context attributes back to default values. You must re-select objects and set up the mapping mode again before printing the next page.

Windows 95: EndPage does not reset the device context attributes. However, the next StartPage call does reset the device context attributes to default values. At that time, you must re-select objects and set up the mapping mode again before printing the next page.

Windows NT: Beginning with Windows NT Version 3.5, neither EndPage or StartPage resets the device context attributes. Device context attributes remain constant across subsequent pages. You do not need to re-select objects and set up the mapping mode again before printing the next page; however, doing so will produce the same results and reduce code differences between Windows 95 and Windows NT.

See Also

ResetDC, StartPage


EndPagePrinter
 EndPagePrinter  QuickInfo  Overview  Group

The EndPagePrinter function indicates the end of one page and the beginning of the next page for the specified printer.

BOOL EndPagePrinter(

HANDLE  hPrinter	// handle of printer object
);
Parameters

hPrinter

Identifies the printer for which the page will be concluded.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The printer-object handle hPrinter is obtained by calling the OpenPrinter function.

Each page in a print job begins with a StartPagePrinter function call and ends with an EndPagePrinter function call. The data for each page is written to the print file by using the WritePrinter function.

See Also

OpenPrinter, StartPagePrinter, WritePrinter


EndPaint
 EndPaint  QuickInfo  Overview  Group

The EndPaint function marks the end of painting in the given window. This function is required for each call to the BeginPaint function, but only after painting is complete.

BOOL EndPaint(

HWND  hWnd,	// handle of window
CONST PAINTSTRUCT  *lpPaint	// address of structure for paint data
);
Parameters

hWnd

Identifies the window that has been repainted.

lpPaint

Points to a PAINTSTRUCT structure that contains the painting information retrieved by BeginPaint.

Return Value

This function always returns TRUE.

Remarks

If the caret was hidden by BeginPaint, EndPaint restores the caret to the screen.

See Also

BeginPaint, PAINTSTRUCT


EndPath
 EndPath  QuickInfo  Overview  Group

The EndPath function closes a path bracket and selects the path defined by the bracket into the specified device context.

BOOL EndPath(

HDC  hdc	// handle of device context
);
Parameters

hdc

Identifies the device context into which the new path is selected.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To get extended error information, call GetLastError. GetLastError may return one of the following error codes:

ERROR_CAN_NOT_COMPLETE
ERROR_INVALID_PARAMETER

See Also

BeginPath


EndUpdateResource
 EndUpdateResource  QuickInfo  Overview  Group

The EndUpdateResource function ends a resource update in an executable file.

BOOL EndUpdateResource(

HANDLE  hUpdate,	// update-file handle
BOOL  fDiscard	// write flag
);
Parameters

hUpdate

Specifies an update handle. This handle is returned by the BeginUpdateResource function.

fDiscard

Specifies whether to write resource updates to an executable file. If this parameter is TRUE, no changes are made to the executable file. If it is FALSE, the changes are made.

Return Value

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

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

See Also

BeginUpdateResource, UpdateResource


EnhMetaFileProc
 EnhMetaFileProc  QuickInfo  Overview  Group

The EnhMetaFileProc function is an application-defined callback function that processes enhanced-format metafile records. This function is called by the EnumEnhMetaFile function.

int CALLBACK EnhMetaFileProc(

HDC  hDC,	// handle of device context
HANDLETABLE FAR  *lpHTable,	// address of metafile handle table
ENHMETARECORD FAR  *lpEMFR,	// address of metafile record
int  nObj,	// count of objects
LPARAM  lpData	// address of optional data
);
Parameters

hDC

Identifies the device context passed to EnumEnhMetaFile.

lpHTable

Points to a table of handles associated with the graphics objects (pens, brushes, and so on) in the metafile. The first entry contains the enhanced-metafile handle.

lpEMFR

Points to one of the records in the metafile. This record should not be modified. (If modification is necessary, it should be performed on a copy of the record.)

nObj

Specifies the number of objects with associated handles in the handle table.

lpData

Points to any application-supplied data.

Return Value

This function must return a nonzero value to continue enumeration; to stop enumeration, it must return zero.

Remarks

An application must register the callback function by passing its address to the EnumEnhMetaFile function.

EnhMetaFileProc is a placeholder for the application-supplied function name.

See Also

EnumEnhMetaFile


EnterCriticalSection
 EnterCriticalSection  QuickInfo  Overview  Group

The EnterCriticalSection function waits for ownership of the specified critical section object. The function returns when the calling thread is granted ownership.

VOID EnterCriticalSection(

LPCRITICAL_SECTION  lpCriticalSection	// address of critical section object
);
Parameters

lpCriticalSection

Points to the critical section object.

Return Value

This function does not return a value.

Remarks

The threads of a single process can use a critical section object for mutual-exclusion synchronization. The process is responsible for allocating the memory used by a critical section object, which it can do by declaring a variable of type CRITICAL_SECTION. Before using a critical section, some thread of the process must call the InitializeCriticalSection function to initialize the object.

To enable mutually exclusive access to a shared resource, each thread calls EnterCriticalSection to request ownership of the critical section before executing any section of code that accesses the protected resource. If another thread currently owns the critical section object, EnterCriticalSection blocks the execution of the calling thread indefinitely until the other thread releases its ownership. If the critical section object is currently unowned, the system grants ownership to the requesting thread so it can access the resource. When it has finished executing the protected code, the thread uses the LeaveCriticalSection function to relinquish ownership, enabling another thread to become owner and access the protected resource.

Once a thread has ownership of a critical section, it can make additional calls to EnterCriticalSection without blocking its execution. This prevents a thread from deadlocking itself while waiting for a critical section that it already owns. To release its ownership, the thread must call LeaveCriticalSection once for each time that it entered the critical section.

For similar synchronization between the threads of different processes, use a mutex object.

See Also

CreateMutex, DeleteCriticalSection, InitializeCriticalSection, LeaveCriticalSection


EnumCalendarInfo
 EnumCalendarInfo  QuickInfo  Overview  Group

The EnumCalendarInfo function enumerates calendar information for a specified locale. The CalType parameter specifies the type of calendar information to enumerate. The function returns the specified calendar information for all applicable calendars for the locale, or for a single requested calendar, depending on the value of the Calendar parameter.

The EnumCalendarInfo function enumerates the calendar information by calling an application-defined callback function. It passes the callback function a pointer to a string buffer containing the requested calendar information. This continues until either the last applicable calendar is found or the callback function returns FALSE.

BOOL EnumCalendarInfo(

CALINFO_ENUMPROC  lpCalInfoEnumProc,	// pointer to enumeration callback function
LCID  Locale,	// locale whose calendar information is of interest
CALID  Calendar,	// calendar whose information is of interest
CALTYPE  CalType	// type of calendar information of interest
);
Parameters

lpCalInfoEnumProc

Points to an application-defined callback function. For more information, see the EnumCalendarInfoProc callback function.

Locale

Specifies the locale to retrieve calendar information for. This parameter can be a locale identifier created by the MAKELCID macro, or one of the following predefined values:

LOCALE_SYSTEM_DEFAULT	Default system locale.
LOCALE_USER_DEFAULT	Default user locale.
Calendar

Specifies the calendar for which information is requested. The following values are defined:

Value	Meaning
ENUM_ALL_CALENDARS	Enumerate all applicable calendars for the locale specified by Locale.
1	Gregorian (localized)
2	Gregorian (English strings always)
3	Japanese era
4	Year of the Republic of China
5	Tangun Era (Korea)
CalType

Indicates the type of calendar information to be returned.  Note that only one CALTYPE value can be specified per call of this function.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To get extended error information, call GetLastError. GetLastError may return one of the following error codes:

ERROR_BADDB
ERROR_INVALID_FLAGS
ERROR_INVALID_PARAMETER

See Also

EnumCalendarInfoProc, EnumDateFormats


EnumCalendarInfoProc
 EnumCalendarInfoProc  QuickInfo  Overview  Group

An EnumCalendarInfoProc function is an application-defined callback function. It is called as a result of a call to the EnumCalendarInfo function, and receives a pointer to a string buffer containing a calendar information string.

BOOL CALLBACK EnumCalendarInfoProc(

LPTSTR  lpCalendarInfoString	// pointer to calendar information string
);
Parameters

lpCalendarInfoString

Pointer to a string buffer containing a null-terminated calendar information string. This string is formatted according to the CALTYPE value passed to EnumCalendarInfo. Note that lpCalendarInfoString should be an LPWSTR for the Unicode (W) version of EnumCalendarInfo, and an LPSTR for the ANSI (A) version of EnumCalendarInfo.

Return Value

To continue enumeration, the callback function should return TRUE.

To stop enumeration, the callback function should return FALSE.

Remarks

EnumCalendarInfoProc is a placeholder for an application-defined function name.

An EnumCalendarInfoProc function can carry out any desired task.

An application registers an EnumCalendarInfoProc function by passing its address to the EnumCalendarInfo function.

A value of type CALINFO_ENUMPROC is a pointer to an EnumCalendarInfoProc function.

See Also

EnumCalendarInfo


EnumChildProc
 EnumChildProc  QuickInfo  Overview  Group

The EnumChildProc function is an application-defined callback function that receives child window handles as a result of a call to the EnumChildWindows function.

BOOL CALLBACK EnumChildProc(

HWND  hwnd,	// handle of child window
LPARAM  lParam	// application-defined value
);
Parameters

hwnd

Identifies a child window of the parent window specified in EnumChildWindows.

lParam

Specifies the application-defined value given in EnumChildWindows.

Return Value

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. EnumChildProc is a placeholder for the application-defined function name.

See Also

EnumChildWindows


EnumChildWindows
 EnumChildWindows  QuickInfo  Overview  Group

The EnumChildWindows function enumerates the child windows that belong to the specified parent window by passing the handle of 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 of parent window
WNDENUMPROC  lpEnumFunc,	// address of callback function
LPARAM  lParam	// application-defined value
);
Parameters

hWndParent

Identifies the parent window whose child windows are to be enumerated.

lpEnumFunc

Points to an application-defined callback function. For more information about the callback function, see the EnumChildProc callback function.

lParam

Specifies a 32-bit, application-defined value to be passed to the callback function.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

EnumChildWindows does not enumerate top-level windows owned by the given window, nor does it enumerate any other owned windows.

If a child window has created child windows of its own, this function 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.

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.

See Also

EnumChildProc, EnumThreadWindows, EnumWindows, GetWindow


EnumClipboardFormats
 EnumClipboardFormats  QuickInfo  Overview  Group

The EnumClipboardFormats function lets you enumerate the data formats that are currently available on the clipboard.

Clipboard data formats are stored in an ordered list. To perform an enumeration of clipboard data formats, you make a series of calls to the EnumClipboardFormats function. For each call, the format parameter specifies an available clipboard format, and the function returns the next available clipboard format.

UINT EnumClipboardFormats(

UINT  format	// specifies a known available clipboard format
);
Parameters

format

Specifies a clipboard format that is known to be available.

To start an enumeration of clipboard formats, set format to zero. When format is zero, the function retrieves the first available clipboard format. For subsequent calls during an enumeration, set format to the result of the previous EnumClipboardFormat call.

Return Value

If the function succeeds, the return value is the clipboard format that follows the specified format. In other words, the next available clipboard format.

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

If there are no more clipboard formats to enumerate, the return value is zero. In this case, the GetLastError function returns the value NO_ERROR. This lets you distinguish between function failure and the end of enumeration.

Remarks

You must open the clipboard before enumerating its formats. Use the OpenClipboard function to open the clipboard. The EnumClipboardFormats function fails if the clipboard is not open.

The EnumClipboardFormats function enumerates formats in the order that they were placed on the clipboard. If you are copying information to the clipboard, add clipboard objects in order from the most descriptive clipboard format to the least descriptive clipboard format. If you are pasting information from the clipboard, retrieve the first clipboard format that you can handle. That will be the most descriptive clipboard format that you can handle.

The operating system provides automatic type conversions for certain clipboard formats. In the case of such a format, this function enumerates the given format, then enumerates the formats to which it can be converted. For more information about clipboard formats and automatic clipboard format type conversions, see the GetClipboardData and SetClipboardData functions.

See Also

CountClipboardFormats, GetClipboardData, OpenClipboard, RegisterClipboardFormat, SetClipboardData


EnumCodePagesProc
 EnumCodePagesProc  QuickInfo  Overview  Group

An EnumCodePagesProc function is an application-defined callback function. It is called as a result of a call to the EnumSystemCodePages function, and receives a pointer to a string buffer containing a code page identifier.

BOOL CALLBACK EnumCodePagesProc(

LPTSTR  lpCodePageString	// pointer to code page identifier string
);
Parameters

lpCodePageString

Pointer to a string buffer containing a null-terminated code page identifier string.

Return Value

To continue enumeration, the callback function should return TRUE.

To stop enumeration, the callback function should return FALSE.

Remarks

EnumCodePagesProc is a placeholder for an application-defined function name.

An EnumCodePagesProc function can carry out any desired task.

An application registers an EnumCodePagesProc function by passing its address to the EnumSystemCodePages function.

A value of type CODEPAGE_ENUMPROC is a pointer to an EnumCodePagesProc function.

See Also

EnumSystemCodePages


EnumDateFormats
 EnumDateFormats  QuickInfo  Overview  Group

The EnumDateFormats function enumerates the long or short date formats that are available for a specified locale, including date formats for any alternate calendars. The value of the dwFlags parameter determines whether the long or short date formats are enumerated. The function enumerates the date formats by passing date format string pointers, one at a time, to the specified application-defined callback function. This continues until the last date format is found or the callback function returns FALSE.

BOOL EnumDateFormats(

DATEFMT_ENUMPROC  lpDateFmtEnumProc,	// pointer to enumeration callback function
LCID  Locale,	// locale whose date formats are of interest
DWORD  dwFlags	// date formats to enumerate
);
Parameters

lpDateFmtEnumProc

Points to an application-defined callback function. The EnumDateFormats function enumerates date formats by making repeated calls to this callback function. For more information, see the EnumDateFormatsProc callback function.

Locale

Specifies the locale to retrieve date format information for. This parameter can be a locale identifier created by the MAKELCID macro, or one of the following predefined values:

LOCALE_SYSTEM_DEFAULT	Default system locale.
LOCALE_USER_DEFAULT	Default user locale.
dwFlags

Specifies the date formats that are of interest. Use one of the following values:

Value	Meaning
DATE_SHORTDATE	Return short date formats.
DATE_LONGDATE	Return long date formats.
Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To get extended error information, call GetLastError. GetLastError may return one of the following error codes:

ERROR_INVALID_PARAMETER
ERROR_BADDB
ERROR_INVALID FLAGS

Remarks

The DATE_SHORTDATE and DATE_LONGDATE flags are mutually exclusive. Use one or the other, but not both.

See Also

EnumDateFormatsProc, EnumCalendarInfo, EnumTimeFormats


EnumDateFormatsProc
 EnumDateFormatsProc  QuickInfo  Overview  Group

An EnumDateFormatsProc function is an application-defined callback function. It is called as a result of a call to the EnumDateFormats function, and receives a pointer to a string buffer containing a date format string.

BOOL CALLBACK EnumDateFormatsProc(

LPTSTR  lpDateFormatString	// pointer to date format string
);
Parameters

lpDateFormatString

Pointer to a string buffer containing a null-terminated date format string. This string is a long or short date format, depending on the value of the dwFlags parameter passed to EnumDateFormats. Note that lpDateFormatString should be an LPWSTR for the Unicode (W) version of EnumDateFormats, and an LPSTR for the ANSI (A) version of EnumDateFormats.

Return Value

To continue enumeration, the callback function should return TRUE.

To stop enumeration, the callback function should return FALSE.

Remarks

EnumDateFormatsProc is a placeholder for an application-defined function name.

An EnumDateFormatsProc function can carry out any desired task.

An application registers an EnumDateFormatsProc function by passing its address to the EnumDateFormats function.

A value of type DATEFMT_ENUMPROC is a pointer to an EnumDateFormatsProc function.

See Also

EnumDateFormats


EnumDependentServices
 EnumDependentServices  QuickInfo  Overview  Group

The EnumDependentServices function enumerates services that depend on another specified service; that is, the specified service must be running before the enumerated services can run. The name and status of each dependent service are provided.

BOOL EnumDependentServices(

SC_HANDLE  hService,	// handle of service
DWORD  dwServiceState,	// state of services to enumerate
LPENUM_SERVICE_STATUS  lpServices,	// address of service status buffer
DWORD  cbBufSize,	// size of service status buffer
LPDWORD  pcbBytesNeeded,	// address of variable for bytes needed
LPDWORD  lpServicesReturned	// address of variable for number returned
);
Parameters

hService

Handle that identifies the service. This handle is returned by the OpenService or CreateService function, and it must have SERVICE_ENUMERATE_DEPENDENTS access.

dwServiceState

Specifies the services to enumerate based on their running state. It must be one or both of the following values:

Value	Meaning
SERVICE_ACTIVE	Enumerates services that are in the following states: SERVICE_START_PENDING, SERVICE_STOP_PENDING, SERVICE_RUNNING, SERVICE_CONTINUE_PENDING, SERVICE_PAUSE_PENDING, and SERVICE_PAUSED.
SERVICE_INACTIVE	Enumerates services that are in the SERVICE_STOPPED state.
lpServices

Pointer to an array of ENUM_SERVICE_STATUS structures. Each structure receives name and service status information for a dependent service. The order of the services in this array is the reverse of the start order of the services. In other words, the first dependent service in the array is the one that would be started last, and the last service in the array is the one that would be started first.

cbBufSize

Specifies the size, in bytes, of the buffer pointed to by the lpServices parameter.

pcbBytesNeeded

Pointer to a variable that receives the number of bytes needed to store the array of service entries. The variable only receives this value if the buffer pointed to by lpServices is too small, indicated by function failure and the ERROR_MORE_DATA error; otherwise, the contents of *pcbBytesNeeded are undefined.

lpServicesReturned

Pointer to a variable that receives the number of service entries returned.

Return Value

If the function succeeds, the return value is TRUE.

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

Errors

The following error codes may be set by the service control manager. Other error codes may be set by the registry functions that are called by the service control manager.

Value	Meaning
ERROR_ACCESS_DENIED
	The specified handle was not opened with SERVICE_ENUMERATE_DEPENDENTS access.
ERROR_INVALID_HANDLE
	The specified handle is invalid.
ERROR_INVALID_PARAMETER
	A parameter that was specified is invalid.
ERROR_MORE_DATA
	The buffer pointed to by lpServices is not large enough. The function sets the variable pointed to by lpServicesReturned to the actual number of service entries stored into the buffer. The function sets the variable pointed to by pcbBytesNeeded to the number of bytes required to store all of the service entries.
Remarks

The returned services entries are ordered in the reverse order of the start order, with group order taken into account. If you need to stop the dependent services, you can use the order of entries written to the lpServices buffer to stop the dependent services in the proper order.

See Also

CreateService, ENUM_SERVICE_STATUS, EnumServicesStatus, OpenService


EnumDesktopProc [New - Windows NT]
 EnumDesktopProc  QuickInfo

[New - Windows NT]

The EnumDesktopProc function is an application-defined callback function that receives a desktop name as a result of a call to the EnumDesktops function.

BOOL CALLBACK EnumDesktopProc(

LPCSTR lpszDesktop,	// name of a desktop
LPARAM lParam	// value specified in EnumDesktops call
);
Parameters

lpszDesktop

Points to the null-terminated name of a desktop.

lParam

Specifies the application-defined value given in the EnumDesktops function.

Return Value

To continue enumeration, the callback function must return TRUE. To stop enumeration, it must return FALSE.

Remarks

The EnumDesktopProc function is a placeholder for the application-defined function name.

See Also

EnumDesktops


EnumDesktops [New - Windows NT]
 EnumDesktops  QuickInfo  Overview  Group

[New - Windows NT]

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 of window station to enumerate
DESKTOPENUMPROC lpEnumFunc,	// points to application's callback function
LPARAM lParam	// 32-bit value to pass to the callback function
);
Parameters

hwinsta

Specifies the handle of the window station whose desktops are to be enumerated. The CreateWindowStation, GetProcessWindowStation, and OpenWindowStation functions return a window station handle.

lpEnumFunc

Points to an application-defined EnumDesktopProc callback function.

dwDesiredAccess

Specifies a 32-bit application-defined value to be passed to the callback function.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. 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.

See Also

CreateWindowStation, EnumDesktopProc, GetProcessWindowStation, OpenWindowStation


EnumDesktopWindows [New - Windows NT]
 EnumDesktopWindows  QuickInfo  Overview  Group

[New - Windows NT]

The EnumDesktopWindows function enumerates all windows in a desktop by passing the handle of each window, in turn, to an application-defined callback function.

BOOL EnumDesktopWindows(

HDESK hDesktop,	// handle of desktop to enumerate
WNDENUMPROC lpfn,	// points to application's callback function
LPARAM lParam	// 32-bit value to pass to the callback function
);
Parameters

hDesktop

Specifies the handle of the desktop whose windows are to be enumerated. The CreateDesktop, OpenDesktop, and GetThreadDesktop functions return a desktop handle.

lpfn

Points to an application-defined EnumWindowsProc callback function.

lParam

Specifies a 32-bit application-defined value to be passed to the callback function.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The EnumDesktopWindows function repeatedly invokes the lpfn callback function until the last window is enumerated or the callback function returns FALSE.

See Also

CreateDesktop, EnumWindowsProc, GetThreadDesktop, OpenDesktop


EnumDisplaySettings [New - Windows NT]
 EnumDisplaySettings  QuickInfo  Overview  Group

[New - Windows NT]

The EnumDisplaySettings function obtains information about one of a display device's graphics modes. You can obtain information for all of a display device's graphics modes by making a series of calls to this function.

BOOL EnumDisplaySettings(

LPCTSTR lpszDeviceName,	// specifies the display device
DWORD iModeNum,	// specifies the graphics mode
LPDEVMODE lpDevMode	// points to structure to receive settings
);
Parameters

lpszDeviceName

Pointer to a null-terminated string that specifies the display device whose graphics mode the function will obtain information about.

This parameter can be NULL. A NULL value specifies the current display device on the computer that the calling thread is running on.

If lpszDeviceName is not NULL, the string must be of the form \\.\DisplayX, where X can have the values 1, 2, or 3.

Windows 95: lpszDeviceName must be NULL.

iModeNum

Index value that specifies the graphics mode for which information is to be obtained.

Graphics mode indexes start at zero. To obtain information for all of a display device's graphics modes, make a series of calls to EnumDisplaySettings, as follows: Set iModeNum to zero for the first call, and increment iModeNum by one for each subsequent call. Continue calling the function until the return value is FALSE.

When you call EnumDisplaySettings with iModeNum set to zero, the operating system initializes and caches information about the display device. When you call EnumDisplaySettings with iModeNum set to a non-zero value, the function returns the information that was cached the last time the function was called with iModeNum set to zero.

lpDevMode

Pointer to a DEVMODE structure into which the function stores information about the specified graphics mode.

The EnumDisplaySettings function sets values for the following five DEVMODE members:

dmBitsPerPel
dmPelsWidth
dmPelsHeight
dmDisplayFlags
dmDisplayFrequency

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

The function fails if iModeNum is greater than the index of the display device's last graphics mode. As noted in the description of the iModeNum parameter, you can use this behavior to enumerate all of a display device's graphics modes.

See Also

CreateDC, CreateDesktop, DEVMODE


EnumEnhMetaFile
 EnumEnhMetaFile  QuickInfo  Overview  Group

The EnumEnhMetaFile function enumerates the records within an enhanced-format metafile by retrieving each record and passing it to the specified callback function. The application-supplied callback function processes each record as required. The enumeration continues until the last record is processed or when the callback function returns zero.

BOOL EnumEnhMetaFile(

HDC  hdc,	// handle of device context
HENHMETAFILE  hemf,	// handle of enhanced metafile
ENHMFENUMPROC  lpEnhMetaFunc,	// address of callback function
LPVOID  lpData,	// address of callback-function data
CONST RECT *  lpRect	// address of bounding rectangle
);
Parameters

hdc

Identifies a device context. This handle is passed to the callback function.

hemf

Identifies an enhanced metafile.

lpEnhMetaFunc

Points to the application-supplied callback function. For more information, see the EnhMetaFileProc function.

lpData

Points to optional callback-function data.

lpRect

Points to a RECT structure that specifies the coordinates of the picture's upper-left and lower-right corners. The dimensions of this rectangle are specified in logical units.

Return Value

If the callback function successfully enumerates all the records in the enhanced metafile, the return value is TRUE; otherwise, it is FALSE.

Remarks

Points along the edge of the rectangle pointed to by the lpRect parameter are included in the picture. If the hdc parameter is NULL, Windows ignores lpRect.

If the callback function calls the PlayEnhMetaFileRecord function, hdc must identify a valid device context. Windows uses the device context's transformation and mapping mode to transform the picture displayed by the PlayEnhMetaFileRecord function.

You can use the EnumEnhMetaFile function to embed one enhanced-metafile within another.

See Also

EnhMetaFileProc, PlayEnhMetaFile, PlayEnhMetaFileRecord, RECT


EnumFontFamExProc [New - Windows 95]
 EnumFontFamExProc  QuickInfo

[New - Windows 95]

The EnumFontFamExProc function is an application-supplied callback function that processes the fonts enumerated by the EnumFontFamiliesEx function. The system calls this callback function once for each enumerated font.

int CALLBACK EnumFontFamExProc(

ENUMLOGFONTEX * lpelfe,	// address of logical-font data
NEWTEXTMETRICEX * lpntme,	// address of physical-font data
int FontType,	// type of font
LPARAM lParam	// application-defined data
);
Parameters

lpelfe

Points to an ENUMLOGFONTEX structure that contains information about the logical attributes of the font.

lpntme

Points to a structure that contains information about the physical attributes of a font. The function uses the NEWTEXTMETRICEX structure for TrueType fonts; and the TEXTMETRIC structure for other fonts.

Windows 95: The NEWTEXTMETRICEX structure is not implemented. Use NEWTEXTMETRIC instead.

FontType

Specifies the type of the font. This parameter can be a combination of these values:

DEVICE_FONTTYPE
RASTER_FONTTYPE
TRUETYPE_FONTTYPE
lParam

Specifies the application-defined data passed by the EnumFontFamiliesEx function.

Return Value

The return value must be a nonzero value to continue enumeration; to stop enumeration, the return value must be zero.

Remarks

Unlike the EnumFontFamProc callback function, EnumFontFamExProc receives extended information about a font. The ENUMLOGFONTEX structure includes the localized name of the script (character set) and the NEWTEXTMETRICEX structure includes a font-coverage signature.

See Also

EnumFontFamiliesEx, EnumFontFamProc, ENUMLOGFONTEX, NEWTEXTMETRICEX, TEXTMETRIC


EnumFontFamilies
 EnumFontFamilies  QuickInfo  Overview  Group

The EnumFontFamilies function enumerates the fonts in a specified font family that are available on a specified device. This function supersedes the EnumFonts function.

int EnumFontFamilies(

HDC  hdc,	// handle of device control
LPCTSTR  lpszFamily,	// address of family-name string
FONTENUMPROC  lpEnumFontFamProc,	// address of callback function
LPARAM  lParam	// address of application-supplied data
);
Parameters

hdc

Identifies the device context.

lpszFamily

Points to a null-terminated string that specifies the family name of the desired fonts. If lpszFamily is NULL, EnumFontFamilies randomly selects and enumerates one font of each available type family.

lpEnumFontFamProc

Specifies the procedure-instance address of the application-defined callback function. For information about the callback function, see the EnumFontFamProc function.

lParam

Points to application-supplied data. The data is passed to the callback function along with the font information.

Return Value

If the function succeeds, the return value is the last value returned by the callback function. Its meaning is implementation specific.

Remarks

The EnumFontFamilies function differs from the EnumFonts function in that it retrieves the style names associated with a TrueType font. With EnumFontFamilies, information can be retrieved about unusual font styles (for example, Outline) that could not be enumerated by using the EnumFonts function. Win32-based applications should use EnumFontFamilies instead of EnumFonts.

For each font having the typeface name specified by the lpszFamily parameter, the EnumFontFamilies function retrieves information about that font and passes it to the function pointed to by the lpEnumFontFamProc parameter. The application-defined callback function can process the font information as desired. Enumeration continues until there are no more fonts or the callback function returns zero.

See Also

EnumFontFamProc, EnumFonts


EnumFontFamiliesEx [New - Windows 95]
 EnumFontFamiliesEx  QuickInfo

[New - Windows 95]

The EnumFontFamiliesEx function enumerates all fonts in the system that match the font characteristics given by the the LOGFONT structure. EnumFontFamiliesEx enumerates fonts based on typeface name, character set, or both. It is recommended that Win32-based applications use this function rather than EnumFontFamilies to enumerate fonts.

int EnumFontFamiliesEx(

HDC hdc,	// handle of device context
LPLOGFONT lpLogfont,	// address of logical font information
FONTENUMPROC lpEnumFontFamExProc,	// address of callback function
LPARAM lParam,	// application-supplied data
DWORD dwFlags	// reserved; must be zero
);
Parameters

hdc

Identifies the device context.

lpLogfont

Points to a LOGFONT structure that contains information about the fonts to enumerate. The function examines these members:

Member	Description
lfCharset	If set to DEFAULT_CHARSET, the function enumerates all fonts in all character sets. If set to a valid character set value, the function enumerates only fonts in the given character set.
lfFaceName	If set to an empty string, the function enumerates one font in each available typeface name. If set to a valid typeface name, the function enumerates all fonts with the specified name.
lfPitchAndFamily	Must be set to zero for all language versions of the operating system except Hebrew and Arabic. For these languages, set IfPitchAndFamily to MONO_FONT to enumerate only fonts that provide all codepage characters within the font.
lpEnumFontFamExProc

Points to the application-defined callback function. For more information about the callback function, see the EnumFontFamExProc function.

lParam

Specifies a 32-bit application-defined value. The function passes this value to the callback function along with font information.

dwFlags

Reserved; must be zero.

Return Value

If the function succeeds, the return value is the last value returned by the callback function. This value depends on which font families are available for the given device.

Remarks

EnumFontFamiliesEx does not use "tagged" typeface names to identify character sets. Instead, it always passes the correct typeface name and a separate character set value to the callback function. The function enumerates fonts based on the the values of the lfCharset and lfFacename members in the LOGFONT structure.

If lfCharset is DEFAULT_CHARSET and lfFaceName is an empty string, the function enumerates one font in every face in every character set. If lfFaceName is not empty, the function enumerates every font in the specified typeface regardless of character set.

If lfCharset is a valid character set value and lfFaceName is an empty string, the function enumerates every font in the specified character set. If lfFaceName is not empty, the function enumerates every font having the specified typeface and character set.

See Also

EnumFontFamilies, EnumFontFamExProc, LOGFONT


EnumFontFamProc
 EnumFontFamProc  QuickInfo  Overview  Group

The EnumFontFamProc function is an application-defined callback function that retrieves data describing available fonts.

int CALLBACK EnumFontFamProc(

ENUMLOGFONT FAR*  lpelf,	// address of logical-font data
NEWTEXTMETRIC FAR*  lpntm,	// address of physical-font data
int  FontType,	// type of font
LPARAM  lParam	// address of application-defined data
);
Parameters

lpelf

Points to an ENUMLOGFONT structure that contains information about the logical attributes of the font. This structure is locally defined.

lpntm

Points to a NEWTEXTMETRIC structure that contains information about the physical attributes of the font, if the font is a TrueType font. If the font is not a TrueType font, this parameter points to a TEXTMETRIC structure.

FontType

Specifies the type of the font. This parameter can be a combination of the following values:

DEVICE_FONTTYPE
RASTER_FONTTYPE
TRUETYPE_FONTTYPE

lParam

Points to the application-defined data passed by the EnumFontFamilies function.

Return Value

The return value must be a nonzero value to continue enumeration; to stop enumeration, it must return zero.

Remarks

An application must register this callback function by passing its address to the EnumFontFamilies function.

The EnumFontFamProc function is a placeholder for the application-defined function name.

The AND (&) operator can be used with the RASTER_FONTTYPE, DEVICE_FONTTYPE, and TRUETYPE_FONTTYPE constants to determine the font type. If the RASTER_FONTTYPE bit is set, the font is a raster font. If the TRUETYPE_FONTTYPE bit is set, the font is a TrueType font. If neither bit is set, the font is a vector font. DEVICE_FONTTYPE is set when a device (for example, a laser printer) supports downloading TrueType fonts or when the font is a device-resident font; it is zero if the device is a display adapter, dot-matrix printer, or other raster device. An application can also use DEVICE_FONTTYPE to distinguish graphics device interface (GDI)-supplied raster fonts from device-supplied fonts. GDI can simulate bold, italic, underline, and strikeout attributes for GDI-supplied raster fonts, but not for device-supplied fonts.

See Also

EnumFontFamilies, EnumFontFamProc, EnumFonts, ENUMLOGFONT, NEWTEXTMETRIC, TEXTMETRIC


EnumFonts
 EnumFonts  QuickInfo  Overview  Group

The EnumFonts function enumerates the fonts available on a specified device. For each font with the specified typeface name, the EnumFonts function retrieves information about that font and passes it to the application-defined callback function. This callback function can process the font information as desired. Enumeration continues until there are no more fonts or the callback function returns zero.

This function is provided for compatibility with earlier versions of Microsoft Windows. Win32-based applications should use the EnumFontFamilies function.

int EnumFonts(

HDC  hdc,	// handle of device context
LPCTSTR  lpFaceName,	// address of font typeface name string
FONTENUMPROC  lpFontFunc,	// address of callback function
LPARAM  lParam	// address of application-supplied data
);
Parameters

hdc

Identifies the device context.

lpFaceName

Points to a null-terminated character string that specifies the typeface name of the desired fonts. If lpFaceName is NULL, EnumFonts randomly selects and enumerates one font of each available typeface.

lpFontFunc

Points to the application-defined callback function. For more information about the callback function, see the EnumFontsProc function.

lParam

Points to any application-defined data. The data is passed to the callback function along with the font information.

Return Value

If the function succeeds, the return value is the last value returned by the callback function. Its meaning is defined by the application.

Remarks

Use EnumFontFamilies instead of EnumFonts. The EnumFontFamilies function differs from the EnumFonts function in that it retrieves the style names associated with a TrueType font. With EnumFontFamilies, you can retrieve information about unusual font styles (for example, Outline) that cannot be enumerated using the EnumFonts function.

See Also

EnumFontFamilies, EnumFontsProc, GetDeviceCaps


EnumFontsProc
 EnumFontsProc  QuickInfo  Overview  Group

The EnumFontsProc function is an application-defined callback function that processes font data from the EnumFonts function.

int CALLBACK EnumFontsProc(

lplf  lplf,	// address of logical-font data
lptm  lptm,	// address of physical-font data
DWORD  dwType,	// font type
LPARAM  lpData	// address of application-defined data
);
Parameters

lplf

Points to a LOGFONT structure that contains information about the logical attributes of the font.

lptm

Points to a TEXTMETRIC structure that contains information about the physical attributes of the font.

dwType

Specifies the type of the font. This parameter can be a combination of the following values:

DEVICE_FONTTYPE
RASTER_FONTTYPE
TRUETYPE_FONTTYPE

lpData

Points to the application-defined data passed by EnumFonts.

Return Value

The return value must be a nonzero value to continue enumeration; to stop enumeration, it must be zero.

Remarks

The AND (&) operator can be used with the RASTER_FONTTYPE and DEVICE_FONTTYPE constants to determine the font type. The RASTER_FONTTYPE bit of the FontType parameter specifies whether the font is a raster or vector font. If the bit is one, the font is a raster font; if zero, it is a vector font. The DEVICE_FONTTYPE bit of FontType specifies whether the font is a device-based or graphics device interface (GDI)-based font. If the bit is one, the font is a device-based font; if zero, it is a GDI-based font.

If the device is capable of text transformations (scaling, italicizing, and so on) only the base font is enumerated. The user must inquire into the device's text-transformation abilities to determine which additional fonts are available directly from the device.

An application must register the EnumFontsProc function by passing its address to the EnumFonts function.

EnumFontsProc is a placeholder for the application-defined function name.

See Also

EnumFonts, LOGFONT, TEXTMETRIC


EnumForms
 EnumForms  QuickInfo  Overview  Group

The EnumForms function enumerates the forms supported by the specified printer.

BOOL EnumForms(

HANDLE  hPrinter,	// handle of printer object
DWORD  Level,	// data-structure level
LPBYTE  pForm,	// points to buffer that receives form info. structure array
DWORD  cbBuf,	// count of bytes in buffer
LPDWORD  pcbNeeded,	// points to variable to receive count of bytes copied or required
LPDWORD  pcReturned	// points to variable to receive count of structures copied
);
Parameters

hPrinter

Identifies the printer for which the forms should be enumerated.

Level

Specifies the version of the structure to which pForm points. This value must be 1.

pForm

Points to a FORM_INFO_1 structure.

cbBuf

Specifies the size, in bytes, of the buffer to which pForm points.

pcbNeeded

Points to a variable that receives the number of bytes copied to or the number of bytes required for the array to which pForm points. If cbBuf is too small, this value specifies the number of bytes required; otherwise, this value specifies the number of bytes copied.

pcReturned

Points to a variable that receives the number of FORM_INFO_1 structures copied into the array to which pForm points.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The printer-object handle hPrinter is normally obtained by calling the OpenPrinter function. The AddPrinter function can also be used.

See Also

AddPrinter, FORM_INFO_1, OpenPrinter


EnumICMProfiles [New - Windows 95]
 EnumICMProfiles  QuickInfo  Overview  Group

[New - Windows 95]

The EnumICMProfiles function enumerates the different color profiles that the system supports for the specified device context.

int EnumICMProfiles(

HDC hdc,
ICMENUMPROC  lpICMEnumFunc,
LPARAM  lParam
);
Parameters

hdc

Handle to the device context.

lpICMEnumFunc

Pointer to the application-defined callback function. For more information, see the EnumICMProfilesProc function.

lParam

Application-supplied data. The data is passed to the callback function along with the color profile information.

Return Value

Returns −1 if there are no color profiles to enumerate or image color matching is not enabled. Otherwise, it returns the last value returned by the callback function, which may be zero if the callback interrupted the enumeration.

See Also

EnumICMProfilesProc


EnumICMProfilesProc [New - Windows 95]
 EnumICMProfilesProc  QuickInfo  Overview  Group

[New - Windows 95]

The EnumICMProfilesProc function is an application-defined callback function that processes color profile data from the EnumICMProfiles function.

int CALLBACK EnumICMProfilesProc(

LPTSTR lpszFilename,
LPARAM  lParam
);
Parameters

lpszFilename

Pointer to a null-terminated string specifying the name of the color profile file.

lParam

Application-supplied data passed by the EnumICMProfiles function.

Return Value

Returns a positive value to continue enumeration, or 0 to stop enumeration. The function must not return a negative value.

See Also

EnumICMProfiles


EnumJobs
 EnumJobs  QuickInfo  Overview  Group

The EnumJobs function initializes an array of either JOB_INFO_1 or JOB_INFO_2 structures with data describing the specified print jobs for the specified printer.

BOOL EnumJobs(

HANDLE  hPrinter,	// handle of printer object
DWORD  FirstJob,	// location of first job in print queue to enumerate
DWORD  NoJobs,	// number of jobs to enumerate
DWORD  Level,	// structure level
LPBYTE  pJob,	// address of structure array
DWORD  cbBuf,	// size of array, in bytes
LPDWORD  pcbNeeded,	// addr. of variable with no. of bytes copied (or required)
LPDWORD  pcReturned	// addr. of variable with no. of job info. structures copied
);
Parameters

hPrinter

Handle to the printer object whose print jobs the function will enumerate.

FirstJob

Specifies the zero-based position within the print queue of the first print job to enumerate. For example, a value of 0 specifies that enumeration should begin at the first print job in the print queue; a value of 9 specifies that enumeration should begin at the tenth print job in the print queue.

NoJobs

Specifies the total number of print jobs to enumerate.

Level

Specifies whether the function should use JOB_INFO_1 or JOB_INFO_2 structures to store data for the enumerated jobs. A value of 1 specifies that the JOB_INFO_1 structure should be used; a value of 2 specifies that the JOB_INFO_2 structure should be used.

pJob

Points to an array of either JOB_INFO_1 or JOB_INFO_2 structures.

cbBuf

Specifies the size, in bytes, of the array pJob.

pcbNeeded

Points to a variable that receives the number of bytes copied if the function succeeds. If the function fails, the variable receives the number of bytes required.

pcReturned

Points to a variable that receives the number of JOB_INFO_1 or JOB_INFO_2 structures that were initialized.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The handle hPrinter is obtained by calling the OpenPrinter function.

The JOB_INFO_1 structure contains general print-job information; the JOB_INFO_2 structure has much more detailed information.

See Also

GetJob, JOB_INFO_1, JOB_INFO_2, OpenPrinter, SetJob


EnumLocalesProc
 EnumLocalesProc  QuickInfo  Overview  Group

An EnumLocalesProc function is an application-defined callback function. It is called as a result of a call to the EnumSystemLocales function, and receives a pointer to a string buffer containing a locale identifier.

BOOL CALLBACK EnumLocalesProc(

LPTSTR  lpLocaleString	// pointer to locale identifier string
);
Parameters

lpLocaleString

Pointer to a string buffer containing a null-terminated locale identifier string. Note that lpLocaleString should be an LPWSTR for the Unicode (W) version of EnumLocalesProc, and an LPSTR for the ANSI (A) version of EnumLocalesProc.

Return Value

To continue enumeration, the callback function should return TRUE.

To stop enumeration, the callback function should return FALSE.

Remarks

EnumLocalesProc is a placeholder for an application-defined function name.

An application registers an EnumLocalesProc function by passing its address to the EnumSystemLocales function.

A value of type LOCALE_ENUMPROC is a pointer to an EnumLocalesProc function.

See Also

EnumSystemLocales


EnumMetaFile
 EnumMetaFile  QuickInfo  Overview  Group

The EnumMetaFile function enumerates the records within a Windows-format metafile by retrieving each record and passing it to the specified callback function. The application-supplied callback function processes each record as required. The enumeration continues until the last record is processed or when the callback function returns zero.

This function is provided for compatibility with earlier versions of Microsoft Windows. Win32-based applications should use the EnumEnhMetaFile function.

BOOL EnumMetaFile(

HDC  hdc,	// handle of device context
HMETAFILE  hmf,	// handle of Windows-format metafile
MFENUMPROC  lpMetaFunc,	// address of callback function
LPARAM  lParam	// address of callback function data
);
Parameters

hdc

Identifies a device context. This handle is passed to the callback function.

hmf

Identifies a Windows-format metafile.

lpMetaFunc

Points to an application-supplied callback function. For more information, see the EnumMetaFileProc callback function.

lParam

Points to optional callback-function data.

Return Value

If the callback function successfully enumerates all the records in the Windows-format metafile, the return value is TRUE; otherwise, it is FALSE.

Remarks

A Windows-format metafile does not support the new curve, path, and transformation functions, such as PolyBezier, BeginPath, and SetWorldTransform. Applications that use these new functions and use metafiles to store pictures created by these functions should use the enhanced-format metafile functions.

To convert a Windows-format metafile into an enhanced-format metafile, use the SetWinMetaFileBits function.

You can use the EnumMetaFile function to embed one Windows-format metafile within another.

See Also

BeginPath, EnumEnhMetaFile, EnumMetaFileProc, PlayMetaFile, PlayMetaFileRecord, PolyBezier, SetWinMetaFileBits, SetWorldTransform


EnumMetaFileProc
 EnumMetaFileProc  QuickInfo  Overview  Group

The EnumMetaFileProc function is an application-defined callback function that processes Windows-format metafile records. This function is called by the EnumMetaFile function.

This function is provided for compatibility with earlier versions of Microsoft Windows. Win32-based applications should use the EnhMetaFileProc and EnumEnhMetaFile functions.

int CALLBACK EnumMetaFileProc(

HDC  hDC,	// handle of device context
HANDLETABLE FAR  *lpHTable,	// address of metafile handle table
METARECORD FAR  *lpMFR,	// address of metafile record
int  nObj,	// count of objects
LPARAM  lpClientData	// address of optional data
);
Parameters

hDC

Identifies the device context passed to EnumMetaFile.

lpHTable

Points to a table of handles associated with the graphics objects (pens, brushes, and so on) in the metafile.

lpMFR

Points to one of the records in the metafile. This record should not be modified. (If modification is necessary, it should be performed on a copy of the record.)

nObj

Specifies the number of objects with associated handles in the handle table.

lpClientData

Points to any application-supplied data.

Return Value

This function must return a nonzero value to continue enumeration; to stop enumeration, it must return zero.

Remarks

An application must register the callback function by passing its address to the EnumMetaFile function.

EnumMetaFileProc is a placeholder for the application-supplied function name.

See Also

EnhMetaFileProc, EnumEnhMetaFile, EnumMetaFile


EnumMonitors
 EnumMonitors  QuickInfo  Overview  Group

The EnumMonitors function initializes an array of MONITOR_INFO_1 structures with data describing the monitors for the specified server.

BOOL EnumMonitors(

LPTSTR  pName,	// address of server name
DWORD  Level,	// structure level
LPBYTE  pMonitors,	// address of structure array
DWORD  cbBuf,	// size, in bytes, of buffer
LPDWORD  pcbNeeded,	// addr. of variable with no. of bytes copied (or required)
LPDWORD  pcReturned	// addr. of variable with no. of job info. structures copied
);
Parameters

pName

Points to a null-terminated string that specifies the name of the server on which the monitors reside. If this parameter is NULL, the local monitors are enumerated.

Level

Specifies the version of the structure pointed to by pMonitors.

pMonitors

Points to an array of MONITOR_INFO_1 structures.

cbBuf

Specifies the size, in bytes, of the buffer pointed to by pMonitors.

pcbNeeded

Points to a variable that receives the number of bytes copied if the function succeeds or the number of bytes required if cbBuf is too small.

pcReturned

Points to a variable that receives the number of MONITOR_INFO_1 structures that were returned in the buffer pointed to by pMonitors.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

MONITOR_INFO_1


EnumObjects
 EnumObjects  QuickInfo  Overview  Group

The EnumObjects function enumerates the pens or brushes available for the specified device context. This function calls the application-defined callback function once for each available object, supplying data describing that object. EnumObjects continues calling the callback function until the callback function returns zero or until all of the objects have been enumerated.

int EnumObjects(

HDC  hdc,	// handle of device context
int  nObjectType,	// object-type identifier
GOBJENUMPROC  lpObjectFunc,	// address of callback function
LPARAM  lParam	// address of application-supplied data
);
Parameters

hdc

Identifies the device context.

nObjectType

Specifies the object type. This parameter can be OBJ_BRUSH or OBJ_PEN.

lpObjectFunc

The address of the application-defined callback function. For more information about the callback function, see the EnumObjectsProc function.

lParam

Points to the application-defined data. The data is passed to the callback function along with the object information.

Return Value

The return value specifies the last value returned by the callback function. Its meaning is user-defined. The return value is -1 if there are too many objects to enumerate. In this case, the callback function is not called.

See Also

EnumObjectsProc, GetObject


EnumObjectsProc
 EnumObjectsProc  QuickInfo  Overview  Group

The EnumObjectsProc function is an application-defined callback function that processes object data supplied by the EnumObjects function.

VOID CALLBACK EnumObjectsProc(

LPVOID  lpLogObject,	// address of graphic-object structure
LPARAM  lpData	// address of application-defined data
);
Parameters

lpLogObject

Points to a LOGPEN or LOGBRUSH structure describing the attributes of the object.

lpData

Points to the application-defined data passed by the EnumObjects function.

Return Value

This function does not return a value.

Remarks

An application must register this function by passing its address to the EnumObjects function. EnumObjectsProc is a placeholder for the application-defined function name.

See Also

EnumObjects, GlobalAlloc, GlobalLock, LOGPEN, LOGBRUSH


EnumPorts
 EnumPorts  QuickInfo  Overview  Group

The EnumPorts function enumerates the ports that are available for printing on a specified server.

BOOL EnumPorts(

LPTSTR  pName,	// pointer to server name
DWORD  Level,	// specifies type of port info structure
LPBYTE  pPorts,	// pointer to buffer to receive array of port info. structures
DWORD  cbBuf,	// specifies size, in bytes, of buffer
LPDWORD  pcbNeeded,	// pointer to number of bytes stored into buffer (or required  // buffer size)
LPDWORD  pcReturned	// pointer to number of PORT_INFO_*. structures stored into buffer
);
Parameters

pName

Pointer to a null-terminated string that specifies the name of the server whose printer ports you wish to enumerate.

If pName is NULL, the function enumerates the local machine's printer ports.

Level

Specifies the type of data structures pointed to by pPorts.

Windows 95: This value can be 1 or 2.

Windows NT: This value must be 1.

pPorts

Pointer to a buffer that receives an array of PORT_INFO_1 or PORT_INFO_2 structures. Each structure contains data that describes an available printer port. The value of Level specifies the type of structure. A Level value of 1 specifies PORT_INFO_1 structures. A Level value of 2 specifies PORT_INFO_2 structures.

Windows 95: The buffer can receive either type of data structure.

Windows NT: The buffer can receive only PORT_INFO_1 data structures.

cbBuf

Specifies the size, in bytes, of the buffer pointed to by pPorts.

pcbNeeded

Pointer to a variable that the function sets to the size, in bytes, of the data that enumerates the printer ports. If cbBuf is smaller than this value, EnumPorts fails, GetLastError returns ERROR_INSUFFICIENT_BUFFER, and the variable pointed to by pcbNeeded represents the required buffer size. If cbBuf is equal to or greater than this value, the variable pointed to by pcbNeeded represents the number of bytes stored into the buffer.

pcReturned

Pointer to a variable that the function sets to the number of PORT_INFO_* structures that it stores into the buffer pointed to by pPorts. This is the number of printer ports that are available on the specified server.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The EnumPorts function can succeed even if the server specified by pName does not have a printer defined.

See Also

AddPort, DeletePort, PORT_INFO_1


EnumPrinterDrivers
 EnumPrinterDrivers  QuickInfo  Overview  Group

The EnumPrinterDrivers function enumerates all of the printer drivers installed on the specified printer server.

BOOL EnumPrinterDrivers(

LPTSTR  pName,	// pointer to server name
LPTSTR  pEnvironment,	// pointer to environment name
DWORD  Level,	// structure level
LPBYTE  pDriverInfo,	// pointer to an array of structures
DWORD  cbBuf,	// size, in bytes, of array
LPDWORD  pcbNeeded,	// pointer to number of bytes copied (or required)
LPDWORD  pcReturned	// pointer to number of DRIVER_INFO. structures
);
Parameters

pName

Pointer to a null-terminated string that specifies the name of the server on which the printer drivers should be enumerated.

If pName is NULL, the function enumerates the local machine's printer drivers.

pEnvironment

Pointer to a null-terminated string that specifies the environment. For example, "Windows NT x86" specifies Windows NT running on an Intel 80386 or 80486 processor. If this parameter is NULL, the function uses the current environment of the caller/client (not of the destination/server).

Level

Specifies the type of DRIVER_INFO_* structures pointed to by pDriverInfo. This value must be 1, 2, or 3.

Windows NT: The value must be 1 or 2.

pDriverInfo

Pointer to a buffer that receives an array of DRIVER_INFO_1, DRIVER_INFO_2, or DRIVER_INFO_3 structures. Each structure contains data that describes an available printer driver.

Windows NT: The structures must be either DRIVER_INFO_1 or DRIVER_INFO_2.

cbBuf

Specifies the size, in bytes, of the buffer pointed to by pDriverInfo.

pcbNeeded

Pointer to a value that the function sets to the size in bytes of the data that enumerates the printer drivers. If cbBuf is smaller than this value, EnumPrinterDrivers fails, and the variable pointed to by pcbNeeded represents the required buffer size. If cbBuf is equal to or greater than this value, the variable pointed to by pcbNeeded represents the number of bytes stored into the buffer.

pcReturned

Pointer to a value that specifies the number of DRIVER_INFO_* structures that it stores into the buffer pointed to by pDriverInfo. This is the number of printer drivers installed on the specified print server.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

AddPrinterDriver, DRIVER_INFO_1, DRIVER_INFO_2, DRIVER_INFO_3, GetPrinterDriver


EnumPrinters
 EnumPrinters  QuickInfo  Overview  Group

The EnumPrinters function enumerates available printers, print servers, domains, or print providers.

BOOL EnumPrinters(

DWORD  Flags,	// types of printer objects to enumerate
LPTSTR  Name,	// name of printer object
DWORD  Level,	// specifies type of printer info structure
LPBYTE  pPrinterEnum,	// pointer to buffer to receive printer info structures
DWORD  cbBuf,	// size, in bytes, of array
LPDWORD  pcbNeeded,	// pointer to variable with no. of bytes copied (or required)
LPDWORD  pcReturned	// pointer to variable with no. of printer info. structures copied
);
Parameters

Flags

Specifies the types of print objects that the function should enumerate. This value can be a combination of the following constants:

Value	Meaning
PRINTER_ENUM_LOCAL	The function ignores the Name parameter, and enumerates the locally installed printers. Windows 95 only: The function will also enumerate network printers because they are handled by the local print provider.
PRINTER_ENUM_NAME	The function enumerates the printer identified by Name. This can be a server, a domain, or a print provider. If Name is NULL, the function enumerates available print providers.
PRINTER_ENUM_SHARED	The function enumerates printers that have the shared attribute. Cannot be used in isolation; use an OR operation to combine with another PRINTER_ENUM type.
PRINTER_ENUM_CONNECTIONS	Windows NT only: The function enumerates the list of printers to which the user has made previous connections.
PRINTER_ENUM_NETWORK	Windows NT only: The function enumerates network printers in the computer's domain. This value is valid only if Level is 1.
PRINTER_ENUM_REMOTE	Windows NT only: The function enumerates network printers and print servers in the computer's domain. This value is valid only if Level is 1.
If Level is 4, you can only use the PRINTER_ENUM_CONNECTIONS and PRINTER_ENUM_LOCAL constants.

Name

If Level is 1, Flags contains PRINTER_ENUM_NAME, and Name is non-NULL, Name points to a null-terminated string that specifies the name of the object to enumerate. This string can be the name of a server, a domain, or a print provider.

If Level is 1, Flags contains PRINTER_ENUM_NAME, and Name is NULL, the function enumerates the available print providers.

If Level is 1, Flags contains PRINTER_ENUM_REMOTE, and Name is NULL, the function enumerates the printers in the user's domain.

If Level is 2 or 5, Name points to a null-terminated string that specifies the name of a server whose printers are to be enumerated. If this string is NULL, the function enumerates the printers installed on the local machine.

If Level is 4, Name should be NULL. The function always queries on the local machine.

When Name is NULL, it enumerates printers that are installed on the local machine. These printers include those that are physically attached to the local machine as well as remote printers to which it has a network connection.

Level

Specifies the type of data structures pointed to by pPrinterEnum. Legal values are 1, 2, 4, and 5, which correspond to the PRINTER_INFO_1, PRINTER_INFO_2,  PRINTER_INFO_4, and PRINTER_INFO_5 data structures.

Windows 95: This value may be 1, 2, or 5.

Windows NT: This value may be 1, 2, or 4.

pPrinterEnum

Pointer to a buffer that receives an array of PRINTER_INFO_1, PRINTER_INFO_2, PRINTER_INFO_4, or PRINTER_INFO_5 structures. Each structure contains data that describes an available print object. If Level is 1, the array contains PRINTER_INFO_1 structures. If Level is 2, the array contains PRINTER_INFO_2 structures. If Level is 4, the array contains PRINTER_INFO_4 structures. If Level is 5, the array contains PRINTER_INFO_5 structures.

Windows 95: The buffer cannot receive PRINTER_INFO_4 structures. It can receive any of the other types.

Windows NT: The buffer cannot receive PRINTER_INFO_5 structures. It can receive any of the other types.

cbBuf

Specifies the size, in bytes, of the array pointed to by pPrinterEnum.

pcbNeeded

Pointer to a value that receives the number of bytes copied if the function succeeds or the number of bytes required if cbBuf is too small.

pcReturned

Pointer to a value that receives the number of PRINTER_INFO_1, PRINTER_INFO_2, PRINTER_INFO_4, or PRINTER_INFO_5 structures that the function returns in the array to which pPrinterEnum points.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

If EnumPrinters returns a PRINTER_INFO_1 structure in which PRINTER_ENUM_CONTAINER is specified, this indicates that there is a hierarchy of printer objects. An application can enumerate the hierarchy by calling EnumPrinters again, setting Name to the value of the PRINTER_INFO_1 structure's pName member.

The EnumPrinters function does not retrieve security information. If PRINTER_INFO_2 structures are returned in the array pointed to by pPrinterEnum, their pSecurityDescriptor members will be set to NULL.

To get information about the default printer, call the GetProfileString function with the section name string set to "windows" and the key name string set to "device". The returned string contains the name of the default printer, the name of the printer DRV file, and the port to which the printer is attached.

Windows NT:

The PRINTER_INFO_4 structure provides an easy and extremely fast way to retrieve the names of the printers installed on a local machine, as well as the remote connections that a user has established. When EnumPrinters is called with a PRINTER_INFO_4 data structure, that function queries the registry for the specified information, then returns immediately. This differs from the behavior of EnumPrinters when called with other levels of PRINTER_INFO_* data structures. In particular, when EnumPrinters is called with a level 2 (PRINTER_INFO_2) data structure, it performs an OpenPrinter call on each remote connection. If a remote connection is down, or the remote server no longer exists, or the remote printer no longer exists, the function must wait for RPC to time out and consequently fail the OpenPrinter call. This can take a while. Passing a PRINTER_INFO_4 structure lets an application retrieve a bare minimium of required information; if more detailed information is desired, a subsequent EnumPrinter level 2 call can be made.

Windows 95:

To quickly enumerate local and network printers, use the PRINTER_INFO_5 structure. This causes EnumPrinters to query the registry rather than make remote calls, and is similar to using the PRINTER_INFO_4 structure on Windows NT as described in the preceding paragraph.

Examples

The following table shows the EnumPrinters output for various Flags values when the Level parameter is set to 1.

In the Name parameter column of the table, you should substitute an appropriate name for Print Provider, Domain, and Machine. For example, for Print Provider, you could use the name of the Windows NT network print provider: "Windows NT Remote Printers", or the name of the Windows 95 local print provider: "Windows 95 Local Print Provider". To get print provider names, call EnumPrinters with Name set to NULL.

Flags parameter	Name parameter	Result
PRINTER_ENUM_LOCAL	The Name parameter is ignored.	All local printers. Windows 95 only: Also enumerates network printers because they are installed locally.
PRINTER_ENUM_NAME	"Print Provider"	All domain names
PRINTER_ENUM_NAME	Windows NT only:  "Print Provider!Domain"	All printers and print servers in the computer's domain
PRINTER_ENUM_NAME	Windows NT only:  "Print Provider!!\\Machine"	All printers shared at \\Machine
PRINTER_ENUM_NAME	Windows NT: An empty string, "" Windows 95: The name of the local machine or the local print provider.	All local printers. Windows 95 only: Also enumerates network printers because they are installed locally.
PRINTER_ENUM_NAME	NULL	All print providers in the computer's domain
Windows NT only:  PRINTER_ENUM_CONNECTIONS	The Name parameter is ignored.	All connected remote printers
Windows NT only:  PRINTER_ENUM_NETWORK	The Name parameter is ignored.	All printers in the computer's domain
Windows NT only:  PRINTER_ENUM_REMOTE	An empty string, ""	All printers and print servers in the computer's domain
Windows NT only:  PRINTER_ENUM_REMOTE	"Print Provider"	Same as PRINTER_ENUM_NAME
Windows NT only:  PRINTER_ENUM_REMOTE	"Print Provider!Domain"	All printers and print servers in computer's domain, regardless of Domain specified.
See Also

AddPrinter, DeletePrinter, GetPrinter, GetProfileString, PRINTER_INFO_1, PRINTER_INFO_2, PRINTER_INFO_4, PRINTER_INFO_5, SetPrinter


EnumPrintProcessorDatatypes
 EnumPrintProcessorDatatypes  QuickInfo

The EnumPrintProcessorDatatypes function enumerates the data types that a specifed print processor supports.

BOOL EnumPrintProcessorDatatypes(

LPTSTR  pName,	// points to server name string
LPTSTR  pPrintProcessorName,	// points to print processor name string
DWORD  Level,	// specifies version of print processor data type structures
LPBYTE  pDatatypes,	// points to buffer to receive print processor data type structures
DWORD   cbBuf,	// specifies size, in bytes, of buffer
LPDWORD  pcbNeeded,	// points to number of bytes copied (or required)
LPDWORD  pcReturned	// points to number of data structures obtained
);
Parameters

pName

Points to a null-terminated string that specifies the name of the server on which the print processor resides. If this parameter is NULL, the data types for the local print processor are enumerated.

pPrintProcessorName

Points to a null-terminated string that specifies the name of the print processor whose data types are to be enumerated.

Level

Specifies the version of the print-processor data type structures to be stored in the buffer pointed to by pDatatypes. This parameter must be 1.

pDatatypes

Points to an array of DATATYPES_INFO_1 structures. One structure is created for each available data type.

cbBuf

Specifies the size, in bytes, of the buffer pointed to by pDatatypes.

pcbNeeded

Points to a variable to receive the total size, in bytes, of the array of DATATYPES_INFO_1 structures.

If this value is less than or equal to cbBuf and the function succeeds, this is the number of bytes stored in the buffer pointed to by pDatatypes. If this number is greater than cbBuf, the buffer is too small, and you must call the function again with a buffer size at least as large as *pcbNeeded.

pcReturned

Points to a variable that the function sets to the number of data structures stored in the buffer pointed to by pDatatypes.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

DATATYPES_INFO_1, EnumPrintProcessors


EnumPrintProcessors
 EnumPrintProcessors  QuickInfo  Overview  Group

The EnumPrintProcessors function enumerates the print processors installed on the specified server.

BOOL EnumPrintProcessors(

LPTSTR  pName,	// points to server name
LPTSTR  pEnvironment,	// points to environment name
DWORD  Level,	// structure level
LPBYTE  pPrintProcessorInfo,	// points to structure array
DWORD  cbBuf,	// array length in bytes
LPDWORD  pcbNeeded,	// points to number of bytes copied (or required)
LPDWORD  pcReturned	// points to number of job info. structures copied
);
Parameters

pName

Points to a null-terminated string that specifies the name of the server on which the print processors reside. If this parameter is NULL, the local print processors are enumerated.

pEnvironment

Points to a null-terminated string that specifies the environment. For example, "Windows NT x86" specifies Windows NT running on an Intel 80386 or 80486 processor. If this parameter is NULL, the current environment of the calling application and client machine (not of the destination application and print server) is used.

Level

Specifies the version of the structure to which pPrintProcessorInfo points. This value must be 1.

pPrintProcessorInfo

Points to an array of PRINTPROCESSOR_INFO_1 structures. One structure is created for each available print processor.

cbBuf

Specifies the size, in bytes, of the buffer pointed to by pPrintProcessorInfo.

pcbNeeded

Points to a value that specifies the number of bytes copied if the function succeeds or the number of bytes required if cbBuf is too small.

pcReturned

Points to a value that specifies the number of PRINTPROCESSOR_INFO_1 structures that returned in the array to which pPrintProcessorInfo points.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

AddPrintProcessor, EnumPrintProcessorDatatypes, PRINTPROCESSOR_INFO_1


EnumProps
 EnumProps  QuickInfo  Overview  Group

The EnumProps function enumerates all entries in the property list of a window by passing them, one by one, to the specified callback function. EnumProps continues until the last entry is enumerated or the callback function returns FALSE.

int EnumProps(

HWND  hWnd,	// handle of window
PROPENUMPROC  lpEnumFunc	// address of callback function
);
Parameters

hWnd

Identifies the window whose property list is to be enumerated.

lpEnumFunc

Points to the callback function. For more information about the callback function, see the PropEnumProc function.

Return Value

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

See Also

EnumPropsEx, GetProp, PropEnumProc, RemoveProp, SetProp


EnumPropsEx
 EnumPropsEx  QuickInfo  Overview  Group

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 of window
PROPENUMPROCEX  lpEnumFunc,	// address of callback function
LPARAM  lParam	// application-defined data
);
Parameters

hWnd

Identifies the window whose property list is to be enumerated.

lpEnumFunc

Points to the callback function. For more information about the callback function, see the PropEnumProcEx function.

lParam

Contains application-defined data to be passed to the callback function.

Return Value

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

See Also

EnumProps, GetProp, PropEnumProcEx, RemoveProp, SetProp


EnumProtocols
 EnumProtocols  QuickInfo  Overview  Group

The EnumProtocols function obtains information about a specified set of network protocols that are active on a local host.

INT EnumProtocols(

LPDWORD  lpiProtocols,	// points to array of protocol identifiers
LPVOID  lpProtocolBuffer,	// points to buffer to receive protocol information
LPDWORD  lpdwBufferLength	// points to variable that specifies the size of the receiving buffer
);
Parameters

lpiProtocols

Points to a null-terminated array of protocol identifiers. The EnumProtocols function obtains information about the protocols specified by this array.

If lpiProtocols is NULL, the function obtains information about all available protocols.

The following protocol identifier values are defined:

Value	Protocol
IPPROTO_TCP	TCP/IP, a connection/stream-oriented protocol
IPPROTO_UDP	User Datagram Protocol (UDP/IP), a connectionless datagram protocol
ISOPROTO_TP4	ISO connection-oriented transport protocol
NSPROTO_IPX	IPX
NSPROTO_SPX	SPX
NSPROTO_SPXII	SPX II
lpProtocolBuffer

Points to a buffer that the function fills with an array of PROTOCOL_INFO data structures.

lpdwBufferLength

Points to a variable that, on input, specifies the size, in bytes, of the buffer pointed to by lpProtocolBuffer.

On output, the function sets this variable to the minimum buffer size needed to retrieve all of the requested information. For the function to succeed, the buffer must be at least this size.

Return Value

If the function succeeds, the return value is the number of PROTOCOL_INFO data structures written to the buffer pointed to by lpProtocolBuffer.

If the function fails, the return value is SOCKET_ERROR ( − 1). To get extended error information, call GetLastError. GetLastError may return the following extended error value:

Value	Meaning
ERROR_INSUFFICIENT_BUFFER	The buffer pointed to by lpProtocolBuffer was too small to receive all of the relevant PROTOCOL_INFO structures. Call the function with a buffer at least as large as the value returned in *lpdwBufferLength.
Remarks

In the following sample code, the EnumProtocols function obtains information about all protocols that are available on a system. The code then examines each of the protocols in greater detail.

SOCKET

OpenConnection (

    PTSTR ServiceName,

    PGUID ServiceType,

    BOOL Reliable,

    BOOL MessageOriented,

    BOOL StreamOriented,

    BOOL Connectionless,

    PINT ProtocolUsed

    )

{

    // local variables

    INT protocols[MAX_PROTOCOLS+1];

    BYTE buffer[2048];

    DWORD bytesRequired;

    INT err;

    PPROTOCOL_INFO protocolInfo;

    PCSADDR_INFO csaddrInfo;

    INT protocolCount;

    INT addressCount;

    INT i;

    DWORD protocolIndex;

    SOCKET s;

    // First look up the protocols installed on this machine.

    //

    bytesRequired = sizeof(buffer);

    err = EnumProtocols( NULL, buffer, &bytesRequired );

    if ( err <= 0 )

        return INVALID_SOCKET;

    // Walk through the available protocols and pick out the ones which

    // support the desired characteristics.

    //

    protocolCount = err;

    protocolInfo = (PPROTOCOL_INFO)buffer;

    for ( i = 0, protocolIndex = 0;

        i < protocolCount && protocolIndex < MAX_PROTOCOLS;

        i++, protocolInfo++ ) {

        // If connection-oriented support is requested, then check if

        // supported by this protocol.  We assume here that connection-

        // oriented support implies fully reliable service.

        //

        if ( Reliable ) {

            // Check to see if the protocol is reliable.  It must

            // guarantee both delivery of all data and the order in

            // which the data arrives.

            //

            if ( (protocolInfo->dwServiceFlags &

                    XP_GUARANTEED_DELIVERY) == 0

                ||

                    (protocolInfo->dwServiceFlags &

                    XP_GUARANTEED_ORDER) == 0 ) {

                continue;

                }

            // Check to see that the protocol matches the stream/message

            // characteristics requested.

            //

            if ( StreamOriented &&

                (protocolInfo->dwServiceFlags & XP_MESSAGE_ORIENTED)

                    != 0 &&

                (protocolInfo->dwServiceFlags & XP_PSEUDO_STREAM)

                     == 0 ) {

                continue;

                }

            if ( MessageOriented &&

                    (protocolInfo->dwServiceFlags & XP_MESSAGE_ORIENTED)

                              == 0 ) {

                continue;

                }

            }

        else if ( Connectionless ) {

            // Make sure that this is a connectionless protocol.

            //

            if ( (protocolInfo->dwServiceFlags & XP_CONNECTIONLESS)

                     != 0 )

                continue;

            }

        // This protocol fits all the criteria.  Add it to the list of

        // protocols in which we're interested.

        //

        protocols[protocolIndex++] = protocolInfo->iProtocol;

        }

See Also

GetAddressByName, PROTOCOL_INFO


EnumRegisterWordProc [New - Windows 95]
 EnumRegisterWordProc  QuickInfo  Overview  Group

[New - Windows 95]

The EnumRegisterWordProc function is an application-defined callback function that process data of register string from the ImmEnumRegisterWord function.

UINT CALLBACK EnumRegisterWordProc(

LPCTSTR  lpReading,
DWORD  dwStyle,
LPCTSTR  lpszString,
LPVOID  lpData
);
Parameters

lpszReading

Pointer to a null-terminated string specifying the matched reading string.

dwStyle

Style of register string.

lpszString

Pointer to a null-terminated string specifying the matched register string.

lpData

Application-supplied data.

Return Value

Returns a nonzero value to continue enumeration; zero to stop enumeration.

See Also

ImmEnumRegisterWord


EnumResLangProc
 EnumResLangProc  QuickInfo  Overview  Group

The EnumResLangProc function is an application-defined callback function that receives resource languages as a result of a call to the EnumResourceLanguages function.

BOOL CALLBACK EnumResLangProc(

HANDLE  hModule,	// resource-module handle
LPCTSTR  lpszType,	// address of resource type
LPCTSTR  lpszName,	// address of resource name
WORD  wIDLanguage,	// resource language identifier
LONG  lParam	// application-defined parameter
);
Parameters

hModule

Identifies 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

Points to a null-terminated string specifying the type name of the resource for which the language is being enumerated. For standard resource types, this parameter should be one of the following values:

Value	Meaning
RT_ACCELERATOR	Accelerator table
RT_BITMAP	Bitmap resource
RT_DIALOG	Dialog box
RT_FONT	Font resource
RT_FONTDIR	Font directory resource
RT_MENU	Menu resource
RT_RCDATA	Application-defined resource (raw data)
RT_STRING	String-table entry
RT_MESSAGETABLE	Message-table entry
RT_CURSOR	Hardware-dependent cursor resource
RT_GROUP_CURSOR	Hardware-independent cursor resource
RT_ICON	Hardware-dependent icon resource
RT_GROUP_ICON	Hardware-independent icon resource
RT_VERSION	Version resource
lpszName

Points to a null-terminated string specifying the name of the resource for which the language is being enumerated.

wIDLanguage

Specifies the language identifier for the resource for which the language is being enumerated. The EnumResourceLanguages function provides this value. For a list of the primary language identifiers and sublanguage identifiers that constitute a language identifier, see the MAKELANGID macro.

lParam

Specifies the application-defined parameter passed to the EnumResourceLanguages function. This parameter can be used in error checking.

Return Value

This callback function should return TRUE to continue enumeration; otherwise, it should return FALSE to stop enumeration.

Remarks

The EnumResLangProc function is a placeholder for the application-defined or library-defined function name.

See Also

EnumResourceLanguages, MAKELANGID


EnumResNameProc
 EnumResNameProc  QuickInfo  Overview  Group

The EnumResNameProc function is an application-defined callback function that receives resource names as a result of a call to the EnumResourceNames function.

BOOL CALLBACK EnumResNameProc(

HANDLE  hModule,	// resource-module handle
LPCTSTR  lpszType,	// address of resource type
LPTSTR  lpszName,	// address of resource name
LONG  lParam	// application-defined parameter
);
Parameters

hModule

Identifies the module whose executable file contains the resources for which the names are being enumerated. If this parameter is NULL, the function enumerates the resource names in the module used to create the current process.

lpszType

Points to a null-terminated string specifying the type name of the resource for which the name is being enumerated. For standard resource types, this parameter should be one of the following values:

Value	Meaning
RT_ACCELERATOR	Accelerator table
RT_BITMAP	Bitmap resource
RT_DIALOG	Dialog box
RT_FONT	Font resource
RT_FONTDIR	Font directory resource
RT_MENU	Menu resource
RT_RCDATA	Application-defined resource (raw data)
RT_STRING	String-table entry
RT_MESSAGETABLE	Message-table entry
RT_CURSOR	Hardware-dependent cursor resource
RT_GROUP_CURSOR	Hardware-independent cursor resource
RT_ICON	Hardware-dependent icon resource
RT_GROUP_ICON	Hardware-independent icon resource
RT_VERSION	Version resource
lpszName

Points to a null-terminated string specifying the name of the resource for which the name is being enumerated.

lParam

Specifies the application-defined parameter passed to the EnumResourceNames function. This parameter can be used in error checking.

Return Value

This callback function should return TRUE to continue enumeration; otherwise, it should return FALSE to stop enumeration.

Remarks

The EnumResNameProc function is a placeholder for the application-defined or library-defined function name.

See Also

EnumResourceNames


EnumResourceLanguages
 EnumResourceLanguages  QuickInfo  Overview  Group

The EnumResourceLanguages function searches a module for each resource of the specified type and name and passes the language of each resource it locates to a defined callback function.

BOOL EnumResourceLanguages(

HMODULE  hModule,	// resource-module handle
LPCTSTR  lpType,	// address of resource type
LPCTSTR  lpName,	// address of resource name
ENUMRESLANGPROC  lpEnumFunc,	// address of callback function
LONG  lParam	// application-defined parameter
);
Parameters

hModule

Identifies 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

Points to a null-terminated string specifying the type of the resource for which the language is being enumerated. For standard resource types, this parameter can be one of the following values:

Value	Meaning
RT_ACCELERATOR	Accelerator table
RT_BITMAP	Bitmap resource
RT_DIALOG	Dialog box
RT_FONT	Font resource
RT_FONTDIR	Font directory resource
RT_MENU	Menu resource
RT_RCDATA	Application-defined resource (raw data)
RT_STRING	String-table entry
RT_MESSAGETABLE	Message-table entry
RT_CURSOR	Hardware-dependent cursor resource
RT_GROUP_CURSOR	Hardware-independent cursor resource
RT_ICON	Hardware-dependent icon resource
RT_GROUP_ICON	Hardware-independent icon resource
RT_VERSION	Version resource
lpName

Points to a null-terminated string specifying the name of the resource for which the language is being enumerated.

lpEnumFunc

Points to the callback function to be called for each enumerated resource language. For more information, see the EnumResLangProc function.

lParam

Specifies an application-defined value passed to the callback function. This parameter may be used in error checking.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The EnumResourceLanguages function continues to enumerate resource languages until the callback function returns FALSE or all resource languages have been enumerated.

See Also

EnumResLangProc, EnumResourceNames, EnumResourceTypes


EnumResourceNames
 EnumResourceNames  QuickInfo  Overview  Group

The EnumResourceNames function searches a module for each resource of the specified type and passes the name of each resource it locates to an application-defined callback function.

BOOL EnumResourceNames(

HINSTANCE  hModule,	// resource-module handling
LPCTSTR  lpszType,	// address of resource type
ENUMRESNAMEPROC  lpEnumFunc,	// address of callback function
LONG  lParam	// application-defined parameter
);
Parameters

hModule

Identifies the module whose executable file contains the resources for which the names are to be enumerated. If this parameter is NULL, the function enumerates the resource names in the module used to create the current process.

lpszType

Points to a null-terminated string specifying the type name of the resource for which the name is being enumerated. For standard resource types, this parameter can be one of the following values:

Value	Meaning
RT_ACCELERATOR	Accelerator table
RT_BITMAP	Bitmap resource
RT_DIALOG	Dialog box
RT_FONT	Font resource
RT_FONTDIR	Font directory resource
RT_MENU	Menu resource
RT_RCDATA	Application-defined resource (raw data)
RT_STRING	String-table entry
RT_MESSAGETABLE	Message-table entry
RT_CURSOR	Hardware-dependent cursor resource
RT_GROUP_CURSOR	Hardware-independent cursor resource
RT_ICON	Hardware-dependent icon resource
RT_GROUP_ICON	Hardware-independent icon resource
RT_VERSION	Version resource
lpEnumFunc

Points to the callback function to be called for each enumerated resource name. For more information, see the EnumResNameProc function.

lParam

Specifies an application-defined value passed to the callback function. This parameter can be used in error checking.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The EnumResourceNames function continues to enumerate resource names until the callback function returns FALSE or all resource names have been enumerated.

See Also

EnumResNameProc, EnumResourceLanguages, EnumResourceTypes


EnumResourceTypes
 EnumResourceTypes  QuickInfo  Overview  Group

The EnumResourceTypes function searches a module for resources and passes each resource type it finds to an application-defined callback function.

BOOL EnumResourceTypes(

HMODULE  hModule,	// resource-module handle
ENUMRESTYPEPROC  lpEnumFunc,	// address of callback function
LONG  lParam	// application-defined parameter
);
Parameters

hModule

Identifies 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

Points to the callback function to be called for each enumerated resource type. For more information, see the EnumResTypeProc function.

lParam

Specifies an application-defined value passed to the callback function.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. 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.

See Also

EnumResourceLanguages, EnumResourceNames, EnumResTypeProc


EnumResTypeProc
 EnumResTypeProc  QuickInfo  Overview  Group

The EnumResTypeProc function is an application-defined callback function that receives resource types as a result of a call to the EnumResourceTypes function.

BOOL CALLBACK EnumResTypeProc(

HANDLE  hModule,	// resource-module handle
LPTSTR  lpszType,	// address of resource type
LONG  lParam	// application-defined parameter
);
Parameters

hModule

Identifies 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

Points to a null-terminated string specifying the type name of the resource for which the type is being enumerated. For standard resource types, this parameter can be one of the following values:

Value	Meaning
RT_ACCELERATOR	Accelerator table
RT_BITMAP	Bitmap resource
RT_DIALOG	Dialog box
RT_FONT	Font resource
RT_FONTDIR	Font directory resource
RT_MENU	Menu resource
RT_RCDATA	Application-defined resource (raw data)
RT_STRING	String-table entry
RT_MESSAGETABLE	Message-table entry
RT_CURSOR	Hardware-dependent cursor resource
RT_GROUP_CURSOR	Hardware-independent cursor resource
RT_ICON	Hardware-dependent icon resource
RT_GROUP_ICON	Hardware-independent icon resource
RT_VERSION	Version resource
lParam

Specifies the application-defined parameter passed to the EnumResourceTypes function. This parameter can be used in error checking.

Return Value

The callback function should return TRUE to continue enumeration; otherwise, it should return FALSE to stop enumeration.

Remarks

The EnumResTypeProc function is a placeholder for the application-defined or library-defined function name.

See Also

EnumResourceTypes


EnumServicesStatus
 EnumServicesStatus  QuickInfo  Overview  Group

The EnumServicesStatus function enumerates services in the specified service control manager database. The name and status of each service are provided.

BOOL EnumServicesStatus(

SC_HANDLE  hSCManager,	// handle of service control manager database
DWORD  dwServiceType,	// type of services to enumerate
DWORD  dwServiceState,	// state of services to enumerate
LPENUM_SERVICE_STATUS  lpServices,	// address of service status buffer
DWORD  cbBufSize,	// size of service status buffer
LPDWORD  pcbBytesNeeded,	// address of variable for bytes needed
LPDWORD  lpServicesReturned,	// address of variable for number returned
LPDWORD  lpResumeHandle	// address of variable for next entry
);
Parameters

hSCManager

Identifies the service control manager database. The OpenSCManager function returns this handle which must have SC_MANAGER_ENUMERATE_SERVICE access.

dwServiceType

Specifies the type of services to enumerate. It must be one or both of the following values:

Value	Meaning
SERVICE_WIN32	Enumerates services of type SERVICE_WIN32_OWN_PROCESS and SERVICE_WIN32_SHARE_PROCESS.
SERVICE_DRIVER	Enumerates services of type SERVICE_KERNEL_DRIVER and SERVICE_FILE_SYSTEM_DRIVER.
dwServiceState

Specifies the services to enumerate based on their running state. It must be one or both of the following values:

Value	Meaning
SERVICE_ACTIVE	Enumerates services that are in the following states: SERVICE_START_PENDING, SERVICE_STOP_PENDING, SERVICE_RUNNING, SERVICE_CONTINUE_PENDING, SERVICE_PAUSE_PENDING, and SERVICE_PAUSED.
SERVICE_INACTIVE	Enumerates services that are in the SERVICE_STOPPED state.
lpServices

Points to an array of ENUM_SERVICE_STATUS structures in which the name and service status information for each service in the database is returned.

cbBufSize

Specifies the size, in bytes, of the buffer pointed to by the lpServices parameter.

pcbBytesNeeded

Points to a variable that receives the number of bytes needed to return the remaining service entries.

lpServicesReturned

Points to a variable that receives the number of service entries returned.

lpResumeHandle

Points to a 32-bit variable that, on input, specifies the starting point of enumeration. The first time this function is called, the variable's value is set to zero. On output, the variable's value is zero if the function succeeds. If the function returns FALSE and the GetLastError function returns ERROR_MORE_DATA, the variable's value is used to indicate the next unread service entry when the function is called again to retrieve the additional data.

Return Value

If the function succeeds, the return value is TRUE.

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

Errors

The following error codes may be set by the service control manager. Other error codes may be set by the registry functions that are called by the service control manager.

Value	Meaning
ERROR_ACCESS_DENIED
	The specified handle was not opened with SC_MANAGER_ENUMERATE_SERVICE access.
ERROR_INVALID_HANDLE
	The specified handle is invalid.
ERROR_INVALID_PARAMETER
	A parameter that was specified is invalid.
ERROR_MORE_DATA
	There are more service entries than would fit into the lpServices buffer. The actual number of service entries written to lpServices is returned in the lpServicesReturned parameter. The number of bytes required to get the remaining entries is returned in the pcbBytesNeeded parameter. The remaining services can be enumerated by additional calls to EnumServicesStatus with the lpResumeHandle parameter indicating the next service to read.
See Also

EnumDependentServices, ENUM_SERVICE_STATUS, OpenSCManager


EnumSystemCodePages
 EnumSystemCodePages  QuickInfo  Overview  Group

The EnumSystemCodePages function enumerates the code pages that are either installed on or supported by a system. The dwFlags parameter determines whether the function enumerates installed or supported code pages. The function enumerates the code pages by passing code page identifiers, one at a time, to the specified application-defined callback function. This continues until all of the installed or supported code page identifiers have been passed to the callback function, or the callback function returns FALSE.

BOOL EnumSystemCodePages(

CODEPAGE_ENUMPROC  lpCodePageEnumProc,	// pointer to enumeration callback function
DWORD  dwFlags	// indicates which code pages to enumerate
);
Parameters

lpCodePageEnumProc

Points to an application-defined callback function. The EnumSystemCodePages function enumerates code pages by making repeated calls to this callback function. For more information, see the EnumCodePagesProc callback function.

dwFlags

Specifies the code pages to enumerate. This parameter can be one of the following values:

Value	Meaning
CP_INSTALLED	Enumerate only installed code pages.
CP_SUPPORTED	Enumerate all supported code pages.
Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To get extended error information, call GetLastError. GetLastError may return one of the following error codes:

ERROR_INVALID_PARAMETER
ERROR_BADDB
ERROR_INVALID FLAGS

Remarks

The CP_INSTALLED and CP_SUPPORTED flags are mutually exclusive.

See Also

EnumCodePagesProc


EnumSystemLocales
 EnumSystemLocales  QuickInfo  Overview  Group

The EnumSystemLocales function enumerates the locales that are either installed on or supported by a system. The dwFlags parameter determines whether the function enumerates installed or supported system locales. The function enumerates locales by passing locale identifiers, one at a time, to the specified application-defined callback function. This continues until all of the installed or supported locale identifiers have been passed to the callback function or the callback function returns FALSE.

BOOL EnumSystemLocales(

LOCALE_ENUMPROC  lpLocaleEnumProc,	// pointer to enumeration callback function
DWORD  dwFlags	// indicates which locales to enumerate
);
Parameters

lpLocaleEnumProc

Points to an application-defined callback function. The EnumSystemLocales function enumerates locales by making repeated calls to this callback function. For more information, see the EnumLocalesProc callback function.

dwFlags

Specifies the locale identifiers to enumerate. This parameter can be one of the following values:

Value	Meaning
LCID_INSTALLED	Enumerate only installed locale identifiers.
LCID_SUPPORTED	Enumerate all supported locale identifiers.
Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To get extended error information, call GetLastError. GetLastError may return one of the following error codes:

ERROR_INVALID_PARAMETER
ERROR_BADDB
ERROR_INVALID FLAGS

Remarks

The LCID_INSTALLED and LCID_SUPPORTED flags are mutually exclusive.

See Also

EnumLocalesProc


EnumTaskWindows
 EnumTaskWindows  QuickInfo  Overview  Group

The EnumTaskWindows function is now obsolete. It has been superseded by the EnumThreadWindows function.

To maintain compatibility for 16-bit applications, EnumTaskWindows has been replaced with a macro that calls EnumThreadWindows. Earlier applications can continue to call EnumTaskWindows as previously documented, but new applications should use EnumThreadWindows.


EnumThreadWindows
 EnumThreadWindows  QuickInfo  Overview  Group

The EnumThreadWindows function enumerates all nonchild windows associated with a thread by passing the handle of 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. This function supersedes the EnumTaskWindows function.

BOOL EnumThreadWindows(

DWORD  dwThreadId,	// thread identifier
WNDENUMPROC  lpfn,	// address of callback function
LPARAM  lParam	// application-defined value
);
Parameters

dwThreadId

Identifies the thread whose windows are to be enumerated.

lpfn

Points to an application-defined callback function. For more information about the callback function, see the EnumThreadWndProc callback function.

lParam

Specifies a 32-bit, application-defined value to be passed to the callback function.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

See Also

EnumChildWindows, EnumThreadWndProc, EnumWindows


EnumThreadWndProc
 EnumThreadWndProc  QuickInfo  Overview  Group

The EnumThreadWndProc function is an application-defined callback function that receives the window handles associated with a thread as a result of a call to the EnumThreadWindows function.

BOOL CALLBACK EnumThreadWndProc(

HWND  hwnd,	// handle of window
LPARAM  lParam	// application-defined value
);
Parameters

hwnd

Identifies a window associated with the thread specified in the EnumThreadWindows function.

lParam

Specifies the application-defined value given in the EnumThreadWindows function.

Return Value

To continue enumeration, the callback function must return TRUE; to stop enumeration, it must return FALSE.

Remarks

The callback function can perform any desired task.

An application must register this callback function by passing its address to the EnumThreadWindows function. EnumThreadWndProc is a placeholder for the application-defined function name.

See Also

EnumThreadWindows


EnumTimeFormats
 EnumTimeFormats  QuickInfo  Overview  Group

The EnumTimeFormats function enumerates the time formats that are available for a specified locale. The function enumerates the time formats by passing a pointer to a string buffer containing a time format to an application-defined callback function. It continues to do so until the last time format is found or the callback function returns FALSE.

BOOL EnumTimeFormats(

TIMEFMT_ENUMPROC  lpTimeFmtEnumProc,	// pointer to enumeration callback function
LCID  Locale,	// locale whose time formats are of interest
DWORD  dwFlags	// currently unused
);
Parameters

lpTimeFmtEnumProc

Points to an application-defined callback function. See the EnumTimeFormatsProc callback function for further details.

Locale

Specifies the locale to retrieve time format information for. This parameter can be a locale identifier created by the MAKELCID macro, or one of the following predefined values:

LOCALE_SYSTEM_DEFAULT	Default system locale.
LOCALE_USER_DEFAULT	Default user locale.
dwFlags

Currently unused. Must be zero.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To get extended error information, call GetLastError. GetLastError may return one of the following error codes:

ERROR_INVALID_PARAMETER
ERROR_BADDB
ERROR_INVALID FLAGS

See Also

EnumTimeFormatsProc, EnumCalendarInfo, EnumDateFormats


EnumTimeFormatsProc
 EnumTimeFormatsProc  QuickInfo  Overview  Group

An EnumTimeFormatsProc function is an application-defined callback function. It is called as a result of a call to the EnumTimeFormats function, and receives a pointer to a string buffer containing a time format string.

BOOL CALLBACK EnumTimeFormatsProc(

LPTSTR  lpTimeFormatString	// pointer to time format string
);
Parameters

lpTimeFormatString

Pointer to a string buffer containing a null-terminated time format string. Note that lpTimeFormatString should be an LPWSTR for the Unicode (W) version of EnumTimeFormatsProc, and an LPSTR for the ANSI (A) version of EnumTimeFormatsProc.

Return Value

To continue enumeration, the callback function should return TRUE.

To stop enumeration, the callback function should return FALSE.

Remarks

EnumTimeFormatsProc is a placeholder for an application-defined function name.

An EnumTimeFormatsProc function can carry out any task

An application registers an EnumTimeFormatsProc function by passing its address to the EnumTimeFormats function.

A value of type TIMEFMT_ENUMPROC is a pointer to an EnumTimeFormatsProc function.

See Also

EnumTimeFormats


EnumWindows
 EnumWindows  QuickInfo  Overview  Group

The EnumWindows function enumerates all top-level windows on the screen by passing the handle of 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,	// address of callback function
LPARAM  lParam	// application-defined value
);
Parameters

lpEnumFunc

Points to an application-defined callback function. For more information, see the EnumWindowsProc callback function.

lParam

Specifies a 32-bit, application-defined value to be passed to the callback function.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

The EnumWindows function does not enumerate child windows.

This function is more reliable than calling the GetWindow function in a loop. An application that calls GetWindow to perform this task risks being caught in an infinite loop or referencing a handle of a window that has been destroyed.

See Also

EnumChildWindows, EnumWindowsProc, GetWindow


EnumWindowsProc
 EnumWindowsProc  QuickInfo  Overview  Group

The EnumWindowsProc function is an application-defined callback function that receives top-level window handles as a result of a call to the EnumWindows function.

BOOL CALLBACK EnumWindowsProc(

HWND  hwnd,	// handle of parent window
LPARAM  lParam	// application-defined value
);
Parameters

hwnd

Identifies a top-level window.

lParam

Specifies the application-defined value given in EnumWindows.

Return Value

To continue enumeration, the callback function must return TRUE; to stop enumeration, it must return FALSE.

Remarks

The callback function can perform any desired task.

An application must register this callback function by passing its address to EnumWindows. EnumWindowsProc is a placeholder for the application-defined function name.

See Also

EnumWindows


EnumWindowStationProc [New - Windows NT]
 EnumWindowStationProc  QuickInfo

[New - Windows NT]

The EnumWindowStationProc function is an application-defined callback function that receives a window station name as a result of a call to the EnumWindowStations function.

BOOL EnumWindowStationProc(

LPTSTR lpszWindowStation	// name of a window station
LPARAM lParam	// value specified in EnumWindowStations call
);
Parameters

lpszWindowStation

Points to the null-terminated name of a window station.

lParam

Specifies the application-defined value given in the EnumWindowStations function.

Return Value

To continue enumeration, the callback function must return TRUE. To stop enumeration, it must return FALSE.

See Also

EnumWindowStations


EnumWindowStations [New - Windows NT]
 EnumWindowStations  QuickInfo  Overview  Group

[New - Windows NT]

The EnumWindowStations function enumerates all windowstations in the system by passing the name of each window station, in turn, to an application-defined callback function.

BOOL EnumWindowStations(

WINSTAENUMPROC lpEnumFunc,	// points to application's callback function
LPARAM lParam	// 32-bit value to pass to the callback function
);
Parameters

lpEnumFunc

Points to an application-defined EnumWindowStationProc callback function.

lParam

Specifies a 32-bit application-defined value to be passed to the callback function.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails the return value is FALSE. 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.

See Also

EnumWindowStationProc


EqualPrefixSid
 EqualPrefixSid  QuickInfo  Overview  Group

The EqualPrefixSid function tests two security-identifier (SID) prefix values for equality. An SID prefix is the entire SID except for the last subauthority value.

BOOL EqualPrefixSid(

PSID  pSid1,	// address of first SID to compare
PSID  pSid2	// address of second SID to compare
);
Parameters

pSid1

Points to the first SID structure to compare. This structure is assumed to be valid.

pSid2

Points to the second SID structure to compare. It also is assumed to be valid.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The EqualPrefixSid function enables a server application in one domain to verify an attempt by a user to log on to another domain. For example, if a user attempts to log on to RemoteDomain from a workstation in LocalDomain, the server for LocalDomain can request the SIDs for the user and the user's groups from RemoteDomain. The domain controller for RemoteDomain responds with the relevant SIDs.

All SIDs for a given domain necessarily have the same prefix. When the server receives the user's SIDs, it can call the EqualPrefixSid function for each SID, comparing the user or group SID against the SID for RemoteDomain. If any of the SID prefixes are not equal, the server refuses the logon attempt.

It is advisable to modify the SID for a domain before comparing it with a group or user SID. If the SID for RemoteDomain is S-1−1234−8, each group or user SID for that domain will have S-1−1234−8 as its prefix. To compare the SIDs by using the EqualPrefixSid function, an application copies the domain SID and adds any subauthority (RID) value to the copy, thereby creating an SID in the form S-1−1234−8−0. The application then uses the modified domain SID as a template against which the group and user SIDs are compared.

See Also

CopySid, EqualSid, IsValidSid, SID


EqualRect
 EqualRect  QuickInfo  Overview  Group

The EqualRect function determines whether the two specified rectangles are equal by comparing the coordinates of their upper-left and lower-right corners.

BOOL EqualRect(

CONST RECT  *lprc1,	// address of structure with first rectangle
CONST RECT  *lprc2	// address of structure with second rectangle
);
Parameters

lprc1

Points to a RECT structure that contains the logical coordinates of the first rectangle.

lprc2

Points to a RECT structure that contains the logical coordinates of the second rectangle.

Return Value

If the two rectangles are identical, the return value is TRUE; otherwise, it is FALSE. To get extended error information, call GetLastError.

See Also

IsRectEmpty, PtInRect, RECT


EqualRgn
 EqualRgn  QuickInfo  Overview  Group

The EqualRgn function checks the two specified regions to determine whether they are identical. The function considers two regions identical if they are equal in size and shape.

BOOL EqualRgn(

HRGN  hSrcRgn1,	// handle of first region
HRGN  hSrcRgn2	// handle of second region
);
Parameters

hSrcRgn1

Identifies a region.

hSrcRgn2

Identifies a region.

Return Value

If the two regions are equal, the return value is TRUE; otherwise, it is FALSE. A return value of ERROR means at least one of the region handles is invalid.

See Also

CreateRectRgn, CreateRectRgnIndirect


EqualSid
 EqualSid  QuickInfo  Overview  Group

The EqualSid function tests two security identifier (SID) values for equality. Two SIDs must match exactly to be considered equal.

BOOL EqualSid(

PSID  pSid1,	// address of first SID to compare
PSID  pSid2	// address of second SID to compare
);
Parameters

pSid1

Points to the first SID structure to compare. This structure is assumed to be valid.

pSid2

Points to the second SID structure to compare. It also is assumed to be valid.

Return Value

If the SID structures are equal, the return value is TRUE; otherwise, it is FALSE. To get extended error information, call GetLastError.

If either SID structure is invalid, the return value is undefined.

See Also

EqualPrefixSid, IsValidSid, SID


EraseTape
 EraseTape  QuickInfo  Overview  Group

The EraseTape function erases all or part of a tape.

DWORD EraseTape(

HANDLE  hDevice,	// handle of open device
DWORD  dwEraseType,	// type of erasure to perform
BOOL  bImmediate	// return after erase operation begins
);
Parameters

hDevice

Identifies the device where the tape is to be erased. This handle is created by using the CreateFile function.

dwEraseType

Specifies the erasing technique. This parameter can be one of the following values:

Value	Description
TAPE_ERASE_LONG	Erases the tape from the current position to the end of the current partition.
TAPE_ERASE_SHORT	Writes an erase gap or end-of-data marker at the current position.
bImmediate

Specifies whether to return as soon as the erase operation begins. If this parameter is TRUE, the function returns immediately; if it is FALSE, the function does not return until the erase operation has been completed.

Return Value

If the function succeeds, the return value is NO_ERROR.

If the function fails, the return value is one of the following error codes:

Error code	Description
ERROR_BEGINNING_OF_MEDIA	An attempt to access data before the beginning-of-medium marker failed.
ERROR_BUS_RESET	A reset condition was detected on the bus.
ERROR_END_OF_MEDIA	The end-of-tape marker was reached during an operation.
ERROR_FILEMARK_DETECTED	A filemark was reached during an operation.
ERROR_SETMARK_DETECTED	A setmark was reached during an operation.
ERROR_NO_DATA_DETECTED	The end-of-data marker was reached during an operation.
ERROR_PARTITION_FAILURE	The tape could not be partitioned.
ERROR_INVALID_BLOCK_LENGTH	The block size is incorrect on a new tape in a multivolume partition.
ERROR_DEVICE_NOT_PARTITIONED	The partition information could not be found when a tape was being loaded.
ERROR_MEDIA_CHANGED	The tape that was in the drive has been replaced or removed.
ERROR_NO_MEDIA_IN_DRIVE	There is no media in the drive.
ERROR_NOT_SUPPORTED	The tape driver does not support a requested function.
ERROR_UNABLE_TO_LOCK_MEDIA	An attempt to lock the ejection mechanism failed.
ERROR_UNABLE_TO_UNLOAD_MEDIA	An attempt to unload the tape failed.
ERROR_WRITE_PROTECT	The media is write protected.
Remarks

Some tape devices do not support certain tape operations. To determine your tape device's capabilities, see your tape device documentation and use the GetTapeParameters function.

See Also

CreateFile, GetTapeParameters


Escape
 Escape  QuickInfo  Overview  Group

The Escape function allows applications to access capabilities of a particular device not directly available through GDI. Escape calls made by an application are translated and sent to the driver.

int Escape(

HDC  hdc,	// handle of device context
int  nEscape,	// escape function
int  cbInput,	// number of bytes in input structure
LPCSTR  lpvInData,	// address of input structure
LPVOID  lpvOutData	// address of output structure
);
Parameters

hdc

Identifies the device context.

nEscape

Specifies the escape function to be performed. This parameter must be one of the predefined escape values. Use the ExtEscape function if your application defines a private escape value.

cbInput

Specifies the number of bytes of data pointed to by the lpvInData parameter.

lpvInData

Points to the input structure required for the specified escape.

lpvOutData

Points to the structure that receives output from this escape. This parameter should be NULL if no data is returned.

Return Value

If the function succeeds, the return value is greater than zero, except with the QUERYESCSUPPORT printer escape, which checks for implementation only. If the escape is not implemented, the return value is zero.

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

Errors

If the function fails, the return value is one of the following values.

Value	Meaning
SP_ERROR	General error. If SP_ERROR is returned, Escape may set the last error value to: ERROR_INVALID_PARAMETER ERROR_DISK_FULL ERROR_NOT_ENOUGH_MEMORY ERROR_PRINT_CANCELLED
SP_OUTOFDISK	Not enough disk space is currently available for spooling, and no more space will become available.
SP_OUTOFMEMORY	Not enough memory is available for spooling.
SP_USERABORT	The user terminated the job through Windows Print Manager.
Remarks

The Win32 API provides six new functions that supersede some printer escapes:

Function	Description
AbortDoc	Terminates a print job. Supersedes the ABORTDOC escape.
EndDoc	Ends a print job. Supersedes the ENDDOC escape.
EndPage	Ends a page. Supersedes the NEWFRAME escape. Unlike NEWFRAME, this function is always called after printing a page.
SetAbortProc	Sets the abort function for a print job. Supersedes the SETABORTPROC escape.
StartDoc	Starts a print job. Supersedes the STARTDOC escape.
StartPage	Prepares printer driver to receive data.
The Win32 API provides six new indexes for the GetDeviceCaps function that supersede some printer escapes:

Index	Description
PHYSICALWIDTH	Width, in pixels, of the physical page. (Supersedes the GETPHYSPAGESIZE escape.)
PHYSICALHEIGHT	Height, in pixels, of the physical page. (Supersedes the GETPHYSPAGESIZE escape.)
PHYSICALOFFSETX	Offset in the x direction, in pixels, from the upper-left corner of the physical page where the actual printing or drawing begins. (Supersedes the GETPRINTINGOFFSET escape.)
PHYSICALOFFSETY	Offset in the y direction, in pixels, from the upper-left corner of the physical page where the actual printing or drawing begins. (Supersedes the GETPRINTINGOFFSET escape.)
SCALINGFACTORX	Scaling factor for the x-axis of a printer. (Supersedes the GETSCALINGFACTOR escape.)
SCALINGFACTORY	Scaling factor for the y-axis of a printer. (Supersedes the GETSCALINGFACTOR escape.)
Of the original printer escapes, only the following can be used by Win32-based application:

Escape	Description
QUERYYESCSUPPORT	Determines whether a particular escape is implemented by the device driver.
Following is a list of the obsolete printer escapes that are supported only for compatibility with 16-bit versions of Windows:

Escape	Description
ABORTDOC	Stops the current print job and erases everything the application has written to the device since the last ENDDOC escape.
ENDDOC	Ends a print job started by the STARTDOC escape.
GETPHYSPAGESIZE	Retrieves the physical page size and copies it to the specified location.
GETPRINTINGOFFSET	Retrieves the offset from the upper-left corner of the physical page where the actual printing or drawing begins.
GETSCALINGFACTOR	Retrieves the scaling factors for the x-axis and the y-axis of a printer.
NEWFRAME	Informs the printer that the application has finished writing to a page.
NEXTBAND	Informs the printer that the application has finished writing to a band.
PASSTHROUGH	Allows the application to send data directly to a printer.
SETABORTPROC	Sets the Abort function for a print job.
STARTDOC	Informs a printer driver that a new print job is starting.
See Also

AbortDoc, EndDoc, EndPage, ExtEscape, SetAbortProc, StartDoc, StartPage, ResetDC,


EscapeCommFunction
 EscapeCommFunction  QuickInfo  Overview  Group

The EscapeCommFunction function directs a specified communications device to perform an extended function.

BOOL EscapeCommFunction(

HANDLE  hFile,	// handle of communications device
DWORD  dwFunc	// extended function to perform
);
Parameters

hFile

Identifies the communications device. The CreateFile function returns this handle.

dwFunc

Specifies the code of the extended function to perform. This parameter can be one of the following values:

Value	Meaning
CLRDTR	Clears the DTR (data-terminal-ready) signal.
CLRRTS	Clears the RTS (request-to-send) signal.
SETDTR	Sends the DTR (data-terminal-ready) signal.
SETRTS	Sends the RTS (request-to-send) signal.
SETXOFF	Causes transmission to act as if an XOFF character has been received.
SETXON	Causes transmission to act as if an XON character has been received.
SETBREAK	Suspends character transmission and places the transmission line in a break state until the ClearCommBreak function is called (or EscapeCommFunction is called with the CLRBREAK extended function code). The SETBREAK extended function code is identical to the SetCommBreak function. Note that this extended function does not flush data that has not been transmitted.
CLRBREAK	Restores character transmission and places the transmission line in a nonbreak state. The CLRBREAK extended function code is identical to the ClearCommBreak function.
Return Value

If the function succeeds, the return value is TRUE.

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

See Also

ClearCommBreak, CreateFile, SetCommBreak


ExcludeClipRect
 ExcludeClipRect  QuickInfo  Overview  Group

The ExcludeClipRect function creates a new clipping region that consists of the existing clipping region minus the specified rectangle.

int ExcludeClipRect(

HDC  hdc,	// handle of device context
int  nLeftRect,	// x-coordinate of upper-left corner of rectangle
int  nTopRect,	// y-coordinate of upper-left corner of rectangle
int  nRightRect,	// x-coordinate of lower-right corner of rectangle
int  nBottomRect	// y-coordinate of lower-right corner of rectangle
);
Parameters

hdc

Identifies the device context.

nLeftRect

Specifies the logical x-coordinate of the upper-left corner of the rectangle.

nTopRect

Specifies the logical y-coordinate of the upper-left corner of the rectangle.

nRightRect

Specifies the logical x-coordinate of the lower-right corner of the rectangle.

nBottomRect

Specifies the logical y-coordinate of the lower-right corner of the rectangle.

Return Value

If the function succeeds, the return value specifies the new clipping region's complexity and can be any one of the following values:

Value	Meaning
NULLREGION	Region is empty.
SIMPLEREGION	Region is a single rectangle.
COMPLEXREGION	Region is more than one rectangle.
ERROR	No region was created.
Remarks

The lower and right edges of the given rectangle are not excluded from the clipping region.

See Also

IntersectClipRect


ExcludeUpdateRgn
 ExcludeUpdateRgn  QuickInfo  Overview  Group

The ExcludeUpdateRgn function prevents drawing within invalid areas of a window by excluding an updated region in the window from a clipping region.

int ExcludeUpdateRgn(

HDC  hDC,	// handle of device context
HWND  hWnd	// handle of window
);
Parameters

hDC

Identifies the device context associated with the clipping region.

hWnd

Identifies the window to update.

Return Value

The return value specifies the complexity of the excluded region; it can be any one of the following values:

Value	Meaning
COMPLEXREGION	Region consists of more than one rectangle.
ERROR	An error occurred.
NULLREGION	Region is empty.
SIMPLEREGION	Region is a single rectangle.
See Also

BeginPaint, GetUpdateRect, GetUpdateRgn, UpdateWindow


ExitProcess
 ExitProcess  QuickInfo  Overview  Group

The ExitProcess function ends a process and all its threads.

VOID ExitProcess(

UINT  uExitCode	// exit code for all threads
);
Parameters

uExitCode

Specifies the exit code for the process, and for all threads that are terminated as a result of this call. Use the GetExitCodeProcess function to retrieve the process's exit value. Use the GetExitCodeThread function to retrieve a thread's exit value.

Return Value

This function does not return a value.

Remarks

ExitProcess is the preferred method of ending a process. This function provides a clean process shutdown. This includes calling the entry-point function of all attached dynamic-link libraries (DLLs) with a value indicating that the process is detaching from the DLL. If a process terminates by calling TerminateProcess, the DLLs that the process is attached to are not notified of the process termination.

After all attached DLLs have executed any process termination value, this function terminates the current process.

Terminating a process causes the following:

1.	All of the object handles opened by the process are closed.

2.	All of the threads in the process terminate their execution.

3.	The state of the process object becomes signaled, satisfying any threads that had been waiting for the process to terminate.

4.	The states of all threads of the process become signaled, satisfying any threads that had been waiting for the threads to terminate.

5.	The termination status of the process changes from STILL_ACTIVE to the exit value of the process.

Terminating a process does not cause child processes to be terminated.

Terminating a process does not necessarily remove the process object from the operating system. A process object is deleted when the last handle to the process is closed.

The ExitProcess, ExitThread, CreateThread, CreateRemoteThread functions, and a process that is starting (as the result of a call by CreateProcess) are serialized between each other within a process. Only one of these events can happen in an address space at a time. This means the following restrictions hold:

•	During process startup and DLL initialization routines, new threads can be created, but they do not begin execution until DLL initialization is done for the process.

•	Only one thread in a process can be in a DLL initialization or detach routine at a time.

•	ExitProcess does not return until no threads are in their DLL initialization or detach routines.

See Also

CreateProcess, CreateRemoteThread, CreateThread, ExitThread, GetExitCodeProcess, GetExitCodeThread, OpenProcess, TerminateProcess


ExitThread
 ExitThread  QuickInfo  Overview  Group

The ExitThread function ends a thread.

VOID ExitThread(

DWORD  dwExitCode	// exit code for this thread
);
Parameters

dwExitCode

Specifies the exit code for the calling thread. Use the GetExitCodeThread function to retrieve a thread's exit code.

Return Value

This function does not return a value.

Remarks

ExitThread is the preferred method of exiting a thread. When this function is called (either explicitly or by returning from a thread procedure), the current thread's stack is deallocated and the thread terminates. The entry-point function of all attached dynamic-link libraries (DLLs) is invoked with a value indicating that the thread is detaching from the DLL.

If the thread is the last thread in the process when this function is called, the thread's process is also terminated.

The state of the thread object becomes signaled, releasing any other threads that had been waiting for the thread to terminate. The thread's termination status changes from STILL_ACTIVE to the value of the dwExitCode parameter.

Terminating a thread does not necessarily remove the thread object from the operating system. A thread object is deleted when the last handle to the thread is closed.

The ExitProcess, ExitThread, CreateThread, CreateRemoteThread functions, and a process that is starting (as the result of a CreateProcess call) are serialized between each other within a process. Only one of these events can happen in an address space at a time. This means the following restrictions hold:

•	During process startup and DLL initialization routines, new threads can be created, but they do not begin execution until DLL initialization is done for the process.

•	Only one thread in a process can be in a DLL initialization or detach routine at a time.

•	ExitProcess does not return until no threads are in their DLL initialization or detach routines.

A thread that uses functions from the C run-time libraries should use the _beginthread and _endthread C run-time functions for thread management rather than CreateThread and ExitThread. Failure to do so results in small memory leaks when ExitThread is called.

See Also

CreateProcess, CreateRemoteThread, CreateThread, ExitProcess, FreeLibraryAndExitThread, GetExitCodeThread, TerminateThread


ExitWindows
 ExitWindows  QuickInfo  Overview  Group

The ExitWindows function logs the current user off.

BOOL ExitWindows(

DWORD  dwReserved,	// reserved
UINT  uReserved	// reserved
);
Parameters

dwReserved

Reserved; must be zero.

uReserved

Reserved; must be zero.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

Windows NT: The ExitWindows function asks applications if they want to terminate by sending the WM_QUERYENDSESSION message to the main window of all running applications.

Windows 95: The ExitWindows function sends the WM_QUERYENDSESSION message to all applications except the one that called ExitWindows.

An application agrees to terminate by returning TRUE when it receives this message (or by allowing the DefWindowProc function to process the message). If any application returns FALSE when it receives the WM_QUERYENDSESSION message, the shutdown is canceled.

After Windows processes the results of the WM_QUERYENDSESSION message, it sends the WM_ENDSESSION message with the wParam parameter set to TRUE if the system is shutting down and to FALSE if it is not.

Windows does not allow new applications to start up during the shutdown process.

See Also

DefWindowProc, ExitWindowsEx


ExitWindowsEx
 ExitWindowsEx  QuickInfo  Overview  Group

The ExitWindowsEx function either logs off, shuts down, or shuts down and restarts the system.

BOOL ExitWindowsEx(

UINT  uFlags,	// shutdown operation
DWORD  dwReserved	// reserved
);
Parameters

uFlags

Specifies the type of shutdown. This parameter must be some combination of the following values:

Value	Meaning
EWX_FORCE	Forces processes to terminate. Instead of bringing up the "application not responding" dialog box for the user, this value forces an application to terminate if it does not respond.
EWX_LOGOFF	Shuts down all processes running in the security context of the process that called the ExitWindowsEx function. Then it logs the user off.
EWX_POWEROFF	Shuts down the system and turns off the power. The application must have the SE_SHUTDOWN_NAME privilege (for more information, see the Remarks section) and the system must support the power-off feature.
EWX_REBOOT	Shuts down the system and then restarts the system. The application must have the SE_SHUTDOWN_NAME privilege (for more information, see the Remarks section).
EWX_SHUTDOWN	Shuts down the system to a point at which it is safe to turn off the power. All file buffers have been flushed to disk, and all running processes have stopped. The application must have the SE_SHUTDOWN_NAME privilege (for more information, see the Remarks section).
dwReserved

Reserved; this parameter is ignored.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

To shut down or restart the system, the calling process must use the AdjustTokenPrivileges function to enable the SE_SHUTDOWN_NAME privilege. For more information about security privileges, see Security.

This function returns as soon as it has initiated the shutdown. The shutdown or logoff then proceeds asynchronously.

During a shutdown or log-off operation, applications that are shut down are allowed a specific amount of time to respond to the shutdown request. If the time expires, Windows displays a dialog box that allows the user to forcibly shut down the application, to retry the shutdown, or to cancel the shutdown request. If the EWX_FORCE value is specified, Windows always forces applications to close and does not display the dialog box.

The ExitWindowsEx function sends a separate notification message, CTRL_SHUTDOWN_EVENT or CTRL_LOGOFF_EVENT as the situation warrants, to console processes. A console process routes these messages to its HandlerRoutine functions, which are added and removed by calls to the SetConsoleCtrlHandler function. ExitWindowsEx sends these notification messages asynchronously; thus, an application cannot assume that the console notification messages have been handled when a call to ExitWindowsEx returns.

See Also

AdjustTokenPrivileges, ExitWindows, HandlerRoutine, SetConsoleCtrlHandler


ExpandEnvironmentStrings
 ExpandEnvironmentStrings  QuickInfo  Overview  Group

The ExpandEnvironmentStrings function expands environment-variable strings and replaces them with their defined values.

DWORD ExpandEnvironmentStrings(

LPCTSTR  lpSrc,	// address of string with environment variables
LPTSTR  lpDst,	// address of string with expanded environment variables
DWORD  nSize	// maximum characters in expanded string
);
Parameters

lpSrc

Points to a null-terminated string that might contain references to environment-variable strings of the form:

%variableName%

For each such reference, the %variableName% portion is replaced with the current value of that environment variable.

The replacement rules are the same as those used by the command interpreter. Case is ignored when looking up the environment-variable name. If the name is not found, the %variableName% portion is left undisturbed.

lpDst

Points to a buffer to receive a copy of the source buffer, after all environment-variable name substitutions have been performed.

nSize

Specifies the maximum number of characters that can be stored in the buffer pointed to by the lpDst parameter, including the terminating null character.

Return Value

If the function succeeds, the return value is the number of characters stored in the destination buffer. If the number of characters is greater than the size of the destination buffer, the return value is the size of the buffer required to hold the expanded strings.

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


ExtCreatePen
 ExtCreatePen  QuickInfo  Overview  Group

The ExtCreatePen function creates a logical cosmetic or geometric pen that has the specified style, width, and brush attributes.

HPEN ExtCreatePen(

DWORD  dwPenStyle,	// pen style
DWORD  dwWidth,	// pen width
CONST LOGBRUSH *  lplb,	// address of structure for brush attributes
DWORD  dwStyleCount,	// length of array containing custom style bits
CONST DWORD *  lpStyle	// optional array of custom style bits
);
Parameters

dwPenStyle

Specifies a combination of type, style, end cap, and join attributes. The values from each category are combined by using the bitwise OR operator (|).

The pen type can be one of the following values:

Type	Description
PS_GEOMETRIC	Pen is geometric.
PS_COSMETIC	Pen is cosmetic.
The pen style can be any one of the following values:

Style	Description
PS_ALTERNATE	Windows NT: Pen sets every other pixel. (This style is applicable only for cosmetic pens.) Windows 95: Not supported.
PS_SOLID	Pen is solid.
PS_DASH	Pen is dashed. Windows 95 only: This style is not supported for geometric lines.
PS_DOT	Pen is dotted. Windows 95 only: This style is not supported for geometric lines.
PS_DASHDOT	Pen has alternating dashes and dots. Windows 95 only: This style is not supported for geometric lines.
PS_DASHDOTDOT	Pen has alternating dashes and double dots. Windows 95 only: This style is not supported for geometric lines.
PS_NULL	Pen is invisible.
PS_USERSTYLE	Windows NT: Pen uses a styling array supplied by the user. Windows 95: Not supported.
PS_INSIDEFRAME	Pen is solid. When this pen is used in any graphics device interface (GDI) drawing function that takes a bounding rectangle, the dimensions of the figure are shrunk so that it fits entirely in the bounding rectangle, taking into account the width of the pen. This applies only to geometric pens.
The end cap is only specified for geometric pens. The end cap can be one of the following values:

End cap	Description
PS_ENDCAP_ROUND	End caps are round.
PS_ENDCAP_SQUARE	End caps are square.
PS_ENDCAP_FLAT	End caps are flat.
The join is only specified for geometric pens. The join can be one of the following values:

Line join	Description
PS_JOIN_BEVEL	Joins are beveled.
PS_JOIN_MITER	Joins are mitered when they are within the current limit set by the SetMiterLimit function. If it exceeds this limit, the join is beveled.
PS_JOIN_ROUND	Joins are round.
Windows 95 only: The PS_ENDCAP_ROUND, PS_ENDCAP_SQUARE, PS_ENDCAP_FLAT, PS_JOIN_BEVEL, PS_JOIN_MITER, and PS_JOIN_ROUND styles are supported only for geometric pens when used to draw paths.

dwWidth

Specifies the width of the pen. If the dwPenStyle parameter is PS_GEOMETRIC, the width is given in logical units. If dwPenStyle is PS_COSMETIC, the width must be set to 1.

lplb

Points to a LOGBRUSH structure. If dwPenStyle is PS_COSMETIC, the lbColor member specifies the color of the pen and the lbStyle member must be set to BS_SOLID. If dwPenStyle is PS_GEOMETRIC, all members must be used to specify the brush attributes of the pen.

dwStyleCount

Specifies the length, in doubleword units, of the lpStyle array. This value must be zero if dwPenStyle is not PS_USERSTYLE.

lpStyle

Points to an array of doubleword values. The first value specifies the length of the first dash in a user-defined style, the second value specifies the length of the first space, and so on. This pointer must be NULL if dwPenStyle is not PS_USERSTYLE.

Return Value

If the function succeeds, the return value is a handle that identifies a logical pen.

If the function fails, the return value is zero.

Remarks

A geometric pen can have any width and can have any of the attributes of a brush, such as dithers and patterns. A cosmetic pen can only be a single pixel wide and must be a solid color, but cosmetic pens are generally faster than geometric pens.

The width of a geometric pen is always specified in world units. The width of a cosmetic pen is always 1.

End cap and join are only specified for geometric pens.

After an application creates a logical pen, it can select that pen into a device context by calling the SelectObject function. After a pen is selected into a device context, it can be used to draw lines and curves.

If dwPenStyle is PS_COSMETIC and PS_USERSTYLE, the entries in the lpStyle array specify lengths of dashes and spaces in style units. A style unit is defined by the device where the pen is used to draw a line.

If dwPenStyle is PS_GEOMETRIC and PS_USERSTYLE, the entries in the lpStyle array specify lengths of dashes and spaces in logical units.

If dwPenStyle is PS_ALTERNATE, the style unit is ignored and every other pixel is set.

If the lbStyle member of the LOGBRUSH structure pointed to by lplb is BS_PATTERN, the bitmap pointed to by the lbHatch member of that structure cannot be a dib section. A dib section is a bitmap created by CreateDibSection. If that bitmap is a dib section, the ExtCreatePen function fails.

When an application no longer requires a given pen, it should call the DeleteObject function to delete the pen.

See Also

CreatePen, CreateDibSection, CreatePenIndirect, DeleteObject, GetObject, LOGBRUSH, SelectObject, SetMiterLimit


ExtCreateRegion
 ExtCreateRegion  QuickInfo  Overview  Group

The ExtCreateRegion function creates a region from the specified region and transformation data.

HRGN ExtCreateRegion(

CONST XFORM *  lpXform,	// address of transformation data
DWORD  nCount,	// size of structure containing region data
CONST RGNDATA *  lpRgnData	// address of region data
);
Parameters

lpXform

Points to an XFORM structure that defines the transformation to be performed on the region. If this pointer is NULL, the identity transformation is used.

nCount

Specifies the number of bytes pointed to by lpRgnData.

lpRgnData

Points to a RGNDATA structure that contains the region data.

Return Value

If the function succeeds, the return value is the value of the region.

If the function fails, the return value is NULL.

Remarks

An application can retrieve data for a region by calling the GetRegionData function.

Windows 95 only: Regions are no longer limited to the 64K heap.

Windows 95 only: World transforms that involve either shearing or rotations are not supported. ExtCreateRegion fails if the transformation matrix is anything other than a scaling or translation of the region.

See Also

GetRegionData, RGNDATA, XFORM


 ExtDeviceMode

The ExtDeviceMode function is not implemented in the Win32 API. Win32-based applications should use the DocumentProperties function.

See Also

GetRegionData, RGNDATA, XFORM


ExtensionPropSheetPageProc [New - Windows NT]
 ExtensionPropSheetPageProc  QuickInfo  Overview  Group

[New - Windows NT]

The ExtensionPropSheetPageProc function specifies an application-defined callback function that receives the address of the AddPropSheetPageProc function, which resides in the module that creates a property sheet. A property sheet extension must export the ExtensionPropSheetPageProc function.

BOOL CALLBACK ExtensionPropSheetPageProc(

LPVOID lpv,
LPFNADDPROPSHEETPAGE  lpfnAddPropSheetPageProc,
LPARAM  lParam
);
Parameters

lpv

Pointer to an application-defined value that describes an item for which a property sheet page is to be created. This parameter can be NULL.

lpfnAddPropSheetPageProc

Pointer to the AddPropSheetPageProc function. The extension dynamic-link library (DLL) calls this function to add a page to the property sheet.

lParam

Application-defined 32-bit value.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

See Also

AddPropSheetPageProc


ExtEscape
 ExtEscape  QuickInfo  Overview  Group

The ExtEscape function allows applications to access capabilities of a particular device that are not available through GDI.

int ExtEscape(

HDC  hdc,	// handle of device context
int  nEscape,	// escape function
int  cbInput,	// number of bytes in input structure
LPCSTR  lpszInData,	// address of input structure
int  cbOutput,	// number of bytes in output structure
LPSTR  lpszOutData	// address of output structure
);
Parameters

hdc

Identifies the device context.

nEscape

Specifies the escape function to be performed.

cbInput

Specifies the number of bytes of data pointed to by the lpszInData parameter.

lpszInData

Points to the input structure required for the specified escape.

cbOutput

Specifies the number of bytes of data pointed to by the lpszOutData parameter.

lpszOutData

Points to the structure that receives output from this escape. This parameter must not be NULL if ExtEscape is called as a query function. If no data is to be returned in this structure, set cbOutput to 0.

Return Value

The return value specifies the outcome of the function. It is greater than zero if the function is successful, except for the QUERYESCSUPPORT printer escape, which checks for implementation only. The return value is zero if the escape is not implemented. A return value less than zero indicates an error. To get extended error information, call GetLastError.

Remarks

Use this function to pass a driver-defined escape value to a device.

Use the Escape function to pass one of the escape values defined by Windows to a device. ExtEscape might not work properly with the escapes defined by Windows. In particular, escapes in which lpszInData points to a structure that contains a member that is a pointer will fail.

See Also

Escape, GetDeviceCaps


ExtFloodFill
 ExtFloodFill  QuickInfo  Overview  Group

The ExtFloodFill function fills an area of the display surface with the current brush.

BOOL ExtFloodFill(

HDC  hdc,	// handle of device context
int  nXStart,	// x-coordinate where filling begins
int  nYStart,	// y-coordinate where filling begins
COLORREF  crColor,	// fill color
UINT  fuFillType	// fill type
);
Parameters

hdc

Identifies a device context.

nXStart

Specifies the logical x-coordinate of the point where filling is to begin.

nYStart

Specifies the logical y-coordinate of the point where filling is to begin.

crColor

Specifies the color of the boundary or of the area to be filled. The interpretation of crColor depends on the value of the fuFillType parameter.

fuFillType

Specifies the type of fill operation to be performed. It must be one of the following values:

Value	Meaning
FLOODFILLBORDER	The fill area is bounded by the color specified by the crColor parameter. This style is identical to the filling performed by the FloodFill function.
FLOODFILLSURFACE	The fill area is defined by the color that is specified by crColor. Filling continues outward in all directions as long as the color is encountered. This style is useful for filling areas with multicolored boundaries.
Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

Following are some of the reasons this function might fail:

•	The filling could not be completed.

•	The given point has the boundary color specified by the crColor parameter (if FLOODFILLBORDER was requested).

•	The given point does not have the color specified by crColor (if FLOODFILLSURFACE was requested).

•	The point is outside the clipping region — that is, it is not visible on the device.

If the fuFillType parameter is FLOODFILLBORDER, Windows assumes that the area to be filled is completely bounded by the color specified by the crColor parameter. The function begins filling at the point specified by the nXStart and nYStart parameters and continues in all directions until it reaches the boundary.

If fuFillType is FLOODFILLSURFACE, Windows assumes that the area to be filled is a single color. The function begins to fill the area at the point specified by nXStart and nYStart and continues in all directions, filling all adjacent regions containing the color specified by crColor.

Only memory device contexts and devices that support raster-display operations support the ExtFloodFill function. To determine whether a device supports this technology, use the GetDeviceCaps function.

See Also

FloodFill, GetDeviceCaps


ExtractAssociatedIcon
 ExtractAssociatedIcon  QuickInfo  Overview  Group

The ExtractAssociatedIcon function returns the handle of an indexed icon found in a file or an icon found in an associated executable file.

HICON ExtractAssociatedIcon(

HINSTANCE  hInst,	// application instance handle
LPTSTR  lpIconPath,	// path and filename of file for which icon is wanted
LPWORD  lpiIcon	// pointer to icon index
);
Parameters

hInst

Specifies the instance of the application calling the function.

lpIconPath

Points to a string that specifies the full path and filename of the file for which an icon is desired. The function extracts the icon handle from that file, or from an executable file associated with that file.

If the icon handle is obtained from an executable file, the function stores the full path and filename of that executable in the string pointed to by lpIconPath.

lpiIcon

Points 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 Value

If the function succeeds, the return value is an icon handle. If the icon is extracted from an associated executable file, the function stores the full path and filename of the executable file in the string pointed to by lpIconPath, and stores the icon's identifier in the WORD pointed to by lpiIcon.

If the function fails, the return value is NULL.

Remarks

The ExtractAssociatedIcon function first looks for the indexed icon in the file specified by lpIconPath. If the function cannot obtain the icon handle from that file, and the file has an associated executable file, it looks in that executable file for an icon. Associations with executable files are based on filename extensions, are stored in the per-user part of the registry, and can be defined using File Manager's Associate command.

See Also

ExtractIcon


ExtractIcon
 ExtractIcon  QuickInfo  Overview  Group

The ExtractIcon function retrieves the handle of an icon from the given executable file, dynamic-link library (DLL), or icon file.

HICON ExtractIcon(

HINSTANCE  hInst,	// instance handle
LPCTSTR  lpszExeFileName,	// filename of file with icon
UINT  nIconIndex	// index of icon to extract
);
Parameters

hInst

Identifies the instance of the application calling the function.

lpszExeFileName

Points to a null-terminated string specifying the name of an executable file, DLL, or icon file.

nIconIndex

Specifies the index of the icon to retrieve. If this value is 0, the function returns the handle of the first icon in the specified file. If this value is −1, the function returns the total number of icons in the specified file.

Return Value

If the function succeeds, the return value is the handle of 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.


ExtSelectClipRgn
 ExtSelectClipRgn  QuickInfo  Overview  Group

The ExtSelectClipRgn function combines the specified region with the current clipping region by using the specified mode.

int ExtSelectClipRgn(

HDC  hdc,	// handle of device context
HRGN  hrgn,	// handle of region
int  fnMode	// region-selection mode
);
Parameters

hdc

Identifies the device context.

hrgn

Identifies the region to be selected. This handle can only be NULL when the RGN_COPY mode is specified.

fnMode

Specifies the operation to be performed. It must be one of the following values:

Value	Meaning
RGN_AND	The new clipping region combines the overlapping areas of the current clipping region and the region identified by hrgn.
RGN_COPY	The new clipping region is a copy of the region identified by hrgn. This is identical to SelectClipRgn. If the region identified by hrgn is NULL, the new clipping region is the default clipping region (the default clipping region is a null region).
RGN_DIFF	The new clipping region combines the areas of the current clipping region with those areas excluded from the region identified by hrgn.
RGN_OR	The new clipping region combines the current clipping region and the region identified by hrgn.
RGN_XOR	The new clipping region combines the current clipping region and the region identified by hrgn but excludes any overlapping areas.
Return Value

If the function succeeds, the return value specifies the new clipping region's complexity and can be any one of the following values:

Value	Meaning
NULLREGION	Region is empty.
SIMPLEREGION	Region is a single rectangle.
COMPLEXREGION	Region is more than one rectangle.
ERROR	An error occurred.
Remarks

If an error occurs when this function is called, the previous clipping region for the given device context is not affected.

The ExtSelectClipRgn function assumes that the coordinates for the given region are specified in device units.

Only a copy of the region identified by the hrgn parameter is used. The region itself can be reused after this call or it can be deleted.

See Also

SelectClipRgn


ExtTextOut
 ExtTextOut  QuickInfo  Overview  Group

The ExtTextOut function draws a character string by using the currently selected font. An optional rectangle may be provided, to be used for clipping, opaquing, or both.

BOOL ExtTextOut(

HDC  hdc,	// handle of device context
int  X,	// x-coordinate of reference point
int  Y,	// y-coordinate of reference point
UINT  fuOptions,	// text-output options
CONST RECT  *lprc,	// optional clipping and/or opaquing rectangle
LPCTSTR  lpString,	// points to string
UINT  cbCount,	// number of characters in string
CONST INT *  lpDx	// address of array of intercharacter spacing values
);
Parameters

hdc

Identifies the device context.

X

Specifies the logical x-coordinate of the reference point used to position the string.

Y

Specifies the logical y-coordinate of the reference point used to position the string.

fuOptions

Specifies how to use the application-defined rectangle. This parameter can be a combination of the following values:

Value	Meaning
ETO_CLIPPED	The text will be clipped to the rectangle.
ETO_GLYPH_INDEX	Windows 95: The lpString array refers to an array returned from GetCharacterPlacement and should be parsed directly by GDI as no further language-specific processing is required. Glyph indexing only applies to TrueType fonts, but the flag can be used for Windows bitmap and vector fonts to indicate no further language processing is necessary and GDI should process the string directly. Note that all glyph indices are 16-bit values even though the string is assumed to be an array of 8-bit values for raster fonts.
ETO_OPAQUE	The current background color should be used to fill the rectangle.
ETO_RTLREADING	Windows 95: If this value is given and a Hebrew or Arabic font is selected into the device context, the string is output using right-to-left reading order. If this value is not given, the string is output in left- to-right order. The same effect can be achieved by setting the TA_RTLREADING value in SetTextAlign. This value is preserved for backward compatability.
The ETO_GLYPH_INDEX and ETO_RTLREADING values cannot be used together. Because ETO_GLYPH_INDEX implies that all language processing has been completed, the function ignores the ETO_RTLREADING flag if also given.

lprc

Points to an optional RECT structure that specifies the dimensions of a rectangle that is used for clipping, opaquing, or both.

lpString

Points to the character string to be drawn. The string does not need to be zero-terminated, since cbCount specifies the length of the string.

cbCount

Specifies the number of characters in the string.

lpDx

Points to an optional array of values that indicate the distance between origins of adjacent character cells. For example, lpDx[i] logical units separate the origins of character cell i and character cell i + 1.

Return Value

If the string is drawn, the return value is TRUE.

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

Remarks

The current text-alignment settings for the specified DC determine how the reference point is used to position the text. The text-alignment settings are retrieved by calling the GetTextAlign function. The text-alignment settings are altered by calling the SetTextAlign function.

If the lpDx parameter is NULL, the function uses the default spacing between characters. The character-cell origins and the contents of the array pointed to by the lpDx parameter are given in logical units. A character-cell origin is defined as the upper-left corner of the character cell.

By default, the current position is not used or updated by this function. However, an application can call the SetTextAlign function with the fMode parameter set to TA_UPDATECP to permit Windows to use and update the current position each time the application calls ExtTextOut for a given device context. When this flag is set, Windows ignores the X and Y parameters on subsequent ExtTextOut calls.

See Also

GetTextAlign, RECT, SetTextAlign


FatalAppExit
 FatalAppExit  QuickInfo  Overview  Group

The FatalAppExit function displays a message box and terminates the application when the message box is closed. If Windows is running with a kernel debugger, the message box gives the user the opportunity to terminate the application or to cancel the message box and return to the application that called FatalAppExit.

VOID FatalAppExit(

UINT  uAction,	// reserved
LPCTSTR  lpMessageText	// address of string to display in message box
);
Parameters

uAction

Reserved; must be zero.

lpMessageText

Points to a null-terminated string that is displayed in the message box. The message is displayed on a single line. To accommodate low-resolution screens, the string should be no more than 35 characters in length.

Return Value

This function does not return a value.

Remarks

An application calls FatalAppExit only when it is not capable of terminating any other way. FatalAppExit may not always free an application's memory or close its files, and it may cause a general failure of Windows. An application that encounters an unexpected error should terminate by freeing all its memory and returning from its main message loop.

See Also

FatalExit


FatalExit
 FatalExit  QuickInfo  Overview  Group

The FatalExit function transfers execution control to the debugger. The behavior of the debugger thereafter is specific to the type of debugger used.

VOID FatalExit(

int  ExitCode	// error code
);
Parameters

ExitCode

Specifies the error code associated with the exit.

Return Value

This function does not return a value.

Remarks

An application should only use FatalExit for debugging purposes. It should not call the function in a retail version of the application because doing so will terminate the application.

See Also

FatalAppExit


FileIOCompletionRoutine
 FileIOCompletionRoutine  QuickInfo  Overview  Group

The FileIOCompletionRoutine function is called when an asynchronous input and output (I/O) function (ReadFileEx or WriteFileEx) is completed and the calling thread is in an alertable wait (using the SleepEx, WaitForSingleObjectEx, or WaitForMultipleObjectsEx function with the fAlertable flag set to TRUE).

VOID WINAPI FileIOCompletionRoutine(

DWORD  dwErrorCode,	// completion code
DWORD  dwNumberOfBytesTransfered,	// number of bytes transferred
LPOVERLAPPED  lpOverlapped	// address of structure with I/O information
);
Parameters

dwErrorCode

Specifies the I/O completion status. This parameter may be one of the following values:

Value	Meaning
0	The I/O was successful.
ERROR_HANDLE_EOF	The ReadFileEx function tried to read past the end of the file.
dwNumberOfBytesTransfered

Specifies the number of bytes transferred. If an error occurs, this parameter is zero.

lpOverlapped

Points to the OVERLAPPED structure specified by the asynchronous I/O function.

Windows does not use the hEvent member of the OVERLAPPED structure; the calling application may use this member to pass information to the completion routine. Windows does not use the OVERLAPPED structure after the completion routine is called, so the completion routine can deallocate the memory used by the overlapped structure.

Return Value

This function does not return a value.

Remarks

FileIOCompletionRoutine is a placeholder for an application-defined or library-defined function name.

Returning from this function allows another pending I/O completion routine to be called. All waiting completion routines are called before the alertable thread's wait is satisfied with a return code of WAIT_IO_COMPLETION. Windows may call the waiting completion routines in any order. They may or may not be called in the order the I/O functions are completed.

Each time Windows calls a completion routine, it uses some of the application's stack. If the completion routine does additional asynchronous I/O and alertable waits, the stack may grow.

See Also

OVERLAPPED, ReadFileEx, SleepEx, WaitForMultipleObjectsEx, WaitForSingleObjectEx, WriteFileEx


FileTimeToDosDateTime
 FileTimeToDosDateTime  QuickInfo  Overview  Group

The FileTimeToDosDateTime function converts a 64-bit file time to MS-DOS date and time values.

BOOL FileTimeToDosDateTime(

CONST FILETIME *  lpFileTime,	// address of 64-bit file time
LPWORD  lpFatDate,	// address of variable for MS-DOS date
LPWORD  lpFatTime	// address of variable for MS-DOS time
);
Parameters

lpFileTime

Points to a FILETIME structure containing the 64-bit file time to convert to MS-DOS date and time format. The FILETIME structure has the following form:

typedef struct _FILETIME { // ft

    DWORD dwLowDateTime;

    DWORD dwHighDateTime;

} FILETIME;

lpFatDate

Points to a variable to receive the MS-DOS date. The date is a packed 16-bit value with the following format:

Bits	Contents
0−4	Day of the month (1−31)
5−8	Month (1 = January, 2 = February, etc.)
9−15	Year offset from 1980 (add 1980 to get actual year)
lpFatTime

Points to a variable to receive the MS-DOS time. The time is a packed 16-bit value with the following format:

Bits	Contents
0−4	Second divided by 2
5−10	Minute (0−59)
11−15	Hour (0−23 on a 24-hour clock)
Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The MS-DOS date format can represent only dates between 1/1/1980 and 12/31/2107; this conversion fails if the input file time is outside this range.

See Also

DosDateTimeToFileTime, FileTimeToSystemTime, SystemTimeToFileTime


FileTimeToLocalFileTime
 FileTimeToLocalFileTime  QuickInfo  Overview  Group

The FileTimeToLocalFileTime function converts a file time based on the Coordinated Universal Time (UTC) to a local file time.

BOOL FileTimeToLocalFileTime(

CONST FILETIME *  lpFileTime,	// address of UTC file time to convert
LPFILETIME  lpLocalFileTime	// address of converted file time
);
Parameters

lpFileTime

Points to a FILETIME structure containing the UTC-based file time to be converted into a local file time.

lpLocalFileTime

Points to a FILETIME structure to receive the converted local file time. This parameter cannot be the same as the lpFileTime parameter.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

FILETIME, LocalFileTimeToFileTime


FileTimeToSystemTime
 FileTimeToSystemTime  QuickInfo  Overview  Group

The FileTimeToSystemTime function converts a 64-bit file time to system time format.

BOOL FileTimeToSystemTime(

CONST FILETIME *  lpFileTime,	// pointer to file time to convert
LPSYSTEMTIME  lpSystemTime	// pointer to structure to receive system time
);
Parameters

lpFileTime

Pointer to a FILETIME structure containing the file time to convert to system date and time format.

The FileTimeToSystemTime function only works with FILETIME values that are less than 0x8000000000000000. The function fails with values equal to or greater than that.

lpSystemTime

Pointer to a SYSTEMTIME structure to receive the converted file time.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

As noted above, the function fails for FILETIME values that are equal to or greater than 0x8000000000000000.

See Also

DosDateTimeToFileTime, FILETIME, FileTimeToDosDateTime, SYSTEMTIME, SystemTimeToFileTime


FillConsoleOutputAttribute
 FillConsoleOutputAttribute  QuickInfo  Overview  Group

The FillConsoleOutputAttribute function sets the text and background color attributes for a specified number of character cells, beginning at the specified coordinates in a screen buffer.

BOOL FillConsoleOutputAttribute(

HANDLE  hConsoleOutput,	// handle of screen buffer
WORD  wAttribute,	// color attribute to write
DWORD  nLength,	// number of character cells to write to
COORD  dwWriteCoord,	// x- and y-coordinates of first cell
LPDWORD  lpNumberOfAttrsWritten	// address of number of cells written to
);
Parameters

hConsoleOutput

Identifies a screen buffer. The handle must have GENERIC_WRITE access.

wAttribute

Specifies the foreground and background color attributes to write to the screen buffer. Any combination of the following values can be specified: FOREGROUND_BLUE, FOREGROUND_GREEN, FOREGROUND_RED, FOREGROUND_INTENSITY, BACKGROUND_BLUE, BACKGROUND_GREEN, BACKGROUND_RED, and BACKGROUND_INTENSITY. For example, the following combination of values produces white text on a black background:

FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE

nLength

Specifies the number of character cells to be set to the specified color attributes.

dwWriteCoord

Specifies a COORD structure containing the screen buffer coordinates of the first cell whose attributes are to be set.

lpNumberOfAttrsWritten

Points to the variable that receives the number of character cells whose attributes were actually set.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

If the number of character cells whose attributes are to be set extends beyond the end of the specified row in the screen buffer, the cells of the next row are set. If the number of cells to write to extends beyond the end of the screen buffer, the cells are written up to the end of the screen buffer.

The character values at the positions written to are not changed.

See Also

COORD, FillConsoleOutputCharacter, SetConsoleTextAttribute, WriteConsoleOutputAttribute


FillConsoleOutputCharacter
 FillConsoleOutputCharacter  QuickInfo  Overview  Group

The FillConsoleOutputCharacter function writes a character to the screen buffer a specified number of times, beginning at the specified coordinates.

BOOL FillConsoleOutputCharacter(

HANDLE  hConsoleOutput,	// handle of screen buffer
TCHAR  cCharacter,	// character to write
DWORD  nLength,	// number of character cells to write to
COORD  dwWriteCoord,	// x- and y-coordinates of first cell
LPDWORD  lpNumberOfCharsWritten	// address of number of cells written to
);
Parameters

hConsoleOutput

Identifies a screen buffer. The handle must have GENERIC_WRITE access.

cCharacter

Specifies the character to write to the screen buffer.

nLength

Specifies the number of character cells to write the character to.

dwWriteCoord

Specifies a COORD structure containing the screen buffer coordinates of the first cell to write the character to.

lpNumberOfCharsWritten

Points to the variable that receives the number of characters actually written to the screen buffer.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

If the number of characters to write to extends beyond the end of the specified row in the screen buffer, characters are written to the next row. If the number of characters to write to extends beyond the end of the screen buffer, the characters are written up to the end of the screen buffer.

The attribute values at the positions written are not changed.

See Also

COORD, FillConsoleOutputAttribute, WriteConsoleOutputCharacter


FillMemory
 FillMemory  QuickInfo  Overview  Group

The FillMemory function fills a block of memory with a specified value.

VOID FillMemory (

PVOID  Destination,	// address of block to fill
DWORD  Length,	// size, in bytes, of block to fill
BYTE  Fill	// the byte value with which to fill
);
Parameters

Destination

Points to the starting address of the block of memory to fill.

Length

Specifies the size, in bytes, of the block of memory to fill.

Fill

Specifies the byte value with which to fill the memory block.

Return Value

This function has no return value.

See Also

CopyMemory, MoveMemory, ZeroMemory


FillPath
 FillPath  QuickInfo  Overview  Group

The FillPath function closes any open figures in the current path and fills the path's interior by using the current brush and polygon-filling mode.

BOOL FillPath(

HDC  hdc	// handle of device context
);
Parameters

hdc

Identifies a device context (DC) that contains a valid path.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To get extended error information, call GetLastError. GetLastError may return one of the following error codes:

ERROR_CAN_NOT_COMPLETE
ERROR_INVALID_PARAMETER
ERROR_NOT_ENOUGH_MEMORY

Remarks

After its interior is filled, the path is discarded from the DC identified by the hdc parameter.

See Also

BeginPath, SetPolyFillMode, StrokeAndFillPath, StrokePath


FillRect
 FillRect  QuickInfo  Overview  Group

The FillRect function fills a rectangle by using the specified brush. This function includes the left and top borders, but excludes the right and bottom borders of the rectangle.

int FillRect(

HDC  hDC,	// handle of device context
CONST RECT  *lprc,	// address of structure with rectangle
HBRUSH  hbr	// handle of brush
);
Parameters

hDC

Identifies the device context.

lprc

Points to a RECT structure that contains the logical coordinates of the rectangle to be filled.

hbr

Identifies the brush used to fill the rectangle.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The brush identified by the hbr parameter may be either a handle to a logical brush or a color value. If specifying a handle to a logical brush, call one of the following functions to obtain the handle: CreateHatchBrush, CreatePatternBrush, or CreateSolidBrush. Additionally, you may retrieve a handle to one of the stock brushes by using the GetStockObject function. If specifying a color value for the hbr parameter, it must be one of the standard system colors (the value 1 must be added to the chosen color). For example:

FillRect(hdc, &rect, (HBRUSH) (COLOR_ENDCOLORS+1));

For a list of all the standard system colors, see GetSysColor.

When filling the specified rectangle, FillRect does not include the rectangle's right and bottom sides. GDI fills a rectangle up to, but not including, the right column and bottom row, regardless of the current mapping mode.

See Also

CreateHatchBrush, CreatePatternBrush, CreateSolidBrush, GetStockObject, RECT


FillRgn
 FillRgn  QuickInfo  Overview  Group

The FillRgn function fills a region by using the specified brush.

BOOL FillRgn(

HDC  hdc,	// handle of device context
HRGN  hrgn,	// handle of region to be filled
HBRUSH  hbr	// handle of brush used to fill the region
);
Parameters

hdc

Identifies the device context.

hrgn

Identifies the region to be filled. The region's coordinates are presumed to be in logical units.

hbr

Identifies the brush to be used to fill the region.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

See Also

CreateBrushIndirect, CreateDIBPatternBrush, CreateHatchBrush, CreatePatternBrush, CreateSolidBrush, PaintRgn


FindAtom
 FindAtom  QuickInfo  Overview  Group

The FindAtom function searches the local atom table for the specified character string and retrieves the atom associated with that string.

ATOM FindAtom(

LPCTSTR  lpString	// address of string to find
);
Parameters

lpString

Points to the null-terminated character string to search for.

Return Value

If the function succeeds, the return value is the atom associated with the given string.

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

Remarks

Even though Windows preserves the case of a string in an atom table, the search performed by the FindAtom function is not case sensitive.

See Also

AddAtom, DeleteAtom, GlobalAddAtom, GlobalDeleteAtom, GlobalFindAtom


FindClose
 FindClose  QuickInfo  Overview  Group

The FindClose function closes the specified search handle. The FindFirstFile and FindNextFile functions use the search handle to locate files with names that match a given name.

BOOL FindClose(

HANDLE  hFindFile	// file search handle
);
Parameters

hFindFile

Identifies the search handle. This handle must have been previously opened by the FindFirstFile function.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

After the FindClose function is called, the handle specified by the hFindFile parameter cannot be used in subsequent calls to either the FindNextFile or FindClose function.

See Also

FindFirstFile, FindNextFile


FindCloseChangeNotification
 FindCloseChangeNotification  QuickInfo  Overview  Group

The FindCloseChangeNotification function stops change notification handle monitoring.

BOOL FindCloseChangeNotification(

HANDLE  hChangeHandle	// handle of change notification to close
);
Parameter

hChangeHandle

Identifies a change notification handle created by the FindFirstChangeNotification function.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

After the FindCloseChangeNotification function is called, the handle specified by the hChangeHandle parameter cannot be used in subsequent calls to either the FindNextChangeNotification or FindCloseChangeNotification function.

See Also

FindFirstChangeNotification, FindNextChangeNotification, WaitForMultipleObjects, WaitForSingleObject


FindClosePrinterChangeNotification
 FindClosePrinterChangeNotification  QuickInfo  Overview  Group

The FindClosePrinterChangeNotification function closes a change notification object created by calling the FindFirstPrinterChangeNotification function. The printer or print server associated with the change notification object will no longer be monitored by that object.

BOOL FindClosePrinterChangeNotification(

HANDLE  hChange	// handle of change notification object to close
);
Parameter

hChange

Handle to the change notification object to be closed. This is a handle created by calling the FindFirstPrinterChangeNotification function.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

After calling the FindClosePrinterChangeNotification function, you cannot use the hChange handle in subsequent calls to either FindFirstPrinterChangeNotification or FindNextPrinterChangeNotification.

The three Find*PrinterChangeNotification functions, in combination with the wait functions, provide an asynchronous, more resource-efficient alternative to the WaitForPrinterChange function.

See Also

FindFirstPrinterChangeNotification, FindNextPrinterChangeNotification, WaitForMultipleObjects, WaitForMultipleObjectsEx, WaitForPrinterChange, WaitForSingleObject, WaitForSingleObjectEx


FindExecutable
 FindExecutable  QuickInfo  Overview  Group

The FindExecutable function retrieves the name and handle of the executable (.EXE) file associated with the specified filename.

HINSTANCE FindExecutable(

LPCTSTR  lpFile,	// address of string for filename
LPCTSTR  lpDirectory,	// address of string for default directory
LPTSTR  lpResult	// address of buffer for string for executable file on return
);
Parameters

lpFile

Points to a null-terminated string specifying a filename. This can be a document or executable file.

lpDirectory

Points to a null-terminated string specifying the default directory.

lpResult

Points to a buffer to receive the filename when the function returns. This filename is a null-terminated string specifying the executable file started when an "open" association is run on the file specified in the lpFile parameter.

Return Value

The return value for the FindExecutable function if valid only if the function fails. If it does fail, the return value is less than or equal to 32. Possible error values are listed in the Remarks section.

Remarks

When FindExecutable returns, the lpResult parameter may contain the path to the DDE server started if no server responds to a request to initiate a DDE conversation.

The FindExecutable function returns 31 if there is no association for the specified file type. Following are the other possible error values:

Value	Meaning
0	The system is out of memory or resources.
ERROR_FILE_NOT_FOUND	The specified file was not found.
ERROR_PATH_NOT_FOUND	The specified path was not found.
ERROR_BAD_FORMAT	The .EXE file is invalid (non-Win32 .EXE or error in .EXE image).
See Also

ShellExecute


FindFirstChangeNotification
 FindFirstChangeNotification  QuickInfo  Overview  Group

The FindFirstChangeNotification function creates a change notification handle and sets up initial change notification filter conditions. A wait on a notification handle succeeds when a change matching the filter conditions occurs in the specified directory or subtree.

HANDLE FindFirstChangeNotification(

LPCTSTR  lpPathName,	// address of name of directory to watch
BOOL  bWatchSubtree,	// flag for monitoring directory or directory tree
DWORD  dwNotifyFilter	// filter conditions to watch for
);
Parameters

lpPathName

Points to a null-terminated string that specifies the path of the directory to watch.

bWatchSubtree

Specifies whether the function will monitor the directory or the directory tree. If this parameter is TRUE, the function monitors the directory tree rooted at the specified directory; if it is FALSE, it monitors only the specified directory.

dwNotifyFilter

Specifies the filter conditions that satisfy a change notification wait. This parameter can be one or more of the following values:

Value	Meaning
FILE_NOTIFY_CHANGE_FILE_NAME
	Any filename change in the watched directory or subtree satisfies a change notification wait. Changes include renames, creations, and deletions.
FILE_NOTIFY_CHANGE_DIR_NAME
	Any directory-name change in the watched directory or subtree satisfies a change notification wait. Changes include directory creations and deletions.
FILE_NOTIFY_CHANGE_ATTRIBUTES
	Any attribute change in the watched directory or subtree satisfies a change notification wait.
FILE_NOTIFY_CHANGE_SIZE
	Any file-size change in the watched directory or subtree satisfies a change notification wait. The operating system detects a change in file size only when the file is written to the disk. For operating systems that use extensive caching, detection occurs only when the cache is sufficiently flushed.
FILE_NOTIFY_CHANGE_LAST_WRITE
	Any change to the last write-time of files in the watched directory or subtree satisfies a change notification wait. The operating system detects a change to the last write-time only when the file is written to the disk. For operating systems that use extensive caching, detection occurs only when the cache is sufficiently flushed.
FILE_NOTIFY_CHANGE_SECURITY
	Any security-descriptor change in the watched directory or subtree satisfies a change notification wait.
Return Value

If the function succeeds, the return value is a handle of a find change notification object.

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

Remarks

The WaitForSingleObject and WaitForMultipleObjects functions monitor the specified directory or subtree by using the handle returned by the FindFirstChangeNotification function. A wait is satisfied when one of the filter conditions occurs in the monitored directory or subtree.

After the wait has been satisfied, the application can respond to this condition and continue monitoring the directory by calling the FindNextChangeNotification function and the appropriate wait function. When the handle is no longer needed, it can be closed by using the FindCloseChangeNotification function.

See Also

FindCloseChangeNotification, FindNextChangeNotification, WaitForMultipleObjects, WaitForSingleObject


FindFirstFile
 FindFirstFile  QuickInfo  Overview  Group

The FindFirstFile function searches a directory for a file whose name matches the specified filename. FindFirstFile examines subdirectory names as well as filenames.

HANDLE FindFirstFile(

LPCTSTR  lpFileName,	// address of name of file to search for
LPWIN32_FIND_DATA  lpFindFileData	// address of returned information
);
Parameters

lpFileName

Windows 95: Points to a null-terminated string that specifies a valid directory or path and filename, which can contain wildcard characters (* and ?). This string must not exceed MAX_PATH characters.

Windows NT: Points to a null-terminated string that specifies a valid directory or path and filename, which can contain wildcard characters (* and ?).

There is a default string size limit for paths of MAX_PATH characters. This limit is related to how the FindFirstFile function parses paths. An application can transcend this limit and send in paths longer than MAX_PATH characters by calling the wide (W) version of FindFirstFile and prepending "\\?\" to the path. The "\\?\" tells the function to turn off path parsing; it lets paths longer than MAX_PATH be used with FindFirstFileW. This also works with UNC names. The "\\?\" is ignored as part of the path. For example, "\\?\C:\myworld\private" is seen as "C:\myworld\private", and "\\?\UNC\bill_g_1\hotstuff\coolapps" is seen as "\\bill_g_1\hotstuff\coolapps".

lpFindFileData

Points to the WIN32_FIND_DATA structure that receives information about the found file or subdirectory. The structure can be used in subsequent calls to the FindNextFile or FindClose function to refer to the file or subdirectory.

Return Value

If the function succeeds, the return value is a search handle used in a subsequent call to FindNextFile or FindClose.

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

Remarks

The FindFirstFile function opens a search handle and returns information about the first file whose name matches the specified pattern. Once the search handle is established, you can use the FindNextFile function to search for other files that match the same pattern. When the search handle is no longer needed, close it by using the FindClose function.

This function searches for files by name only; it cannot be used for attribute-based searches.

See Also

FindClose, FindNextFile, GetFileAttributes, SetFileAttributes, WIN32_FIND_DATA


FindFirstFreeAce
 FindFirstFreeAce  QuickInfo  Overview  Group

The FindFirstFreeAce function retrieves a pointer to the first free byte in an access-control list (ACL).

BOOL FindFirstFreeAce(

PACL  pAcl,	// address of access-control list
LPVOID  *pAce	// address of pointer to first free byte
);
Parameters

pAcl

Points to an ACL structure.

pAce

Points to a pointer to the first free position in the ACL created when the function returns. If the ACL is invalid, this parameter is NULL. If the ACL is full, this parameter points to the byte immediately following the ACL.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

ACL, GetAce, GetAclInformation


FindFirstPrinterChangeNotification
 FindFirstPrinterChangeNotification  QuickInfo  Overview  Group

The FindFirstPrinterChangeNotification function creates a change notification object and returns a handle to the object. You can then use this handle in a call to one of the wait functions to monitor changes to the printer or print server.

The FindFirstPrinterChangeNotification call specifies the type of changes to be monitored. You can specify a set of conditions to monitor for changes, a set of printer information fields to monitor, or both.

A wait operation on the change notification handle succeeds when one of the specified changes occurs in the specified printer or print server. You then call the FindNextPrinterChangeNotification function to retrieve information about the change, and to reset the change notification object for use in the next wait operation.

HANDLE FindFirstPrinterChangeNotification(

HANDLE  hPrinter,	// handle to printer or print server to monitor for changes
DWORD  fdwFlags,	// flags that specify the conditions to monitor
DWORD  fdwOptions,	// reserved, must be zero
LPVOID  pPrinterNotifyOptions	// pointer to structure specifying printer information to monitor
);
Parameters

hPrinter

Handle to the printer or print server that you want to monitor. This handle is obtained by calling the OpenPrinter function.

fdwFlags

A set of bit flags that specify the conditions that will cause the change notification object to enter a signaled state. A change notification occurs when one or more of the specified conditions are met. The fdwFlags parameter can be zero if pPrinterNotifyOptions is non-NULL.

You can set one or more of the following change notification constants:

Value	Meaning
PRINTER_CHANGE_FORM
	Notify of any changes to a form. You can set this general flag or one or more of the following specific flags: PRINTER_CHANGE_ADD_FORM PRINTER_CHANGE_SET_FORM PRINTER_CHANGE_DELETE_FORM
PRINTER_CHANGE_JOB
	Notify of any changes to a job. You can set this general flag or one or more of the following specific flags: PRINTER_CHANGE_ADD_JOB PRINTER_CHANGE_SET_JOB PRINTER_CHANGE_DELETE_JOB PRINTER_CHANGE_WRITE_JOB
PRINTER_CHANGE_PORT
	Notify of any changes to a port. You can set this general flag or one or more of the following specific flags: PRINTER_CHANGE_ADD_PORT PRINTER_CHANGE_CONFIGURE_PORT PRINTER_CHANGE_DELETE_PORT
PRINTER_CHANGE_PRINT_PROCESSOR
	Notify of any changes to a print processor. You can set this general flag or one or more of the following specific flags: PRINTER_CHANGE_ADD_PRINT_PROCESSOR PRINTER_CHANGE_DELETE_PRINT_PROCESSOR
PRINTER_CHANGE_PRINTER
	Notify of any changes to a printer. You can set this general flag or one or more of the following specific flags:  PRINTER_CHANGE_ADD_PRINTER PRINTER_CHANGE_SET_PRINTER PRINTER_CHANGE_DELETE_PRINTER PRINTER_CHANGE_FAILED_CONNECTION_PRINTER
PRINTER_CHANGE_PRINTER_DRIVER
	Notify of any changes to a printer driver. You can set this general flag or one or more of the following specific flags: PRINTER_CHANGE_ADD_PRINTER_DRIVER PRINTER_CHANGE_SET_PRINTER_DRIVER PRINTER_CHANGE_DELETE_PRINTER_DRIVER
PRINTER_CHANGE_ALL
	Notify if any of the preceding changes occur.
For descriptions of the more specific flags in the preceding table, see the FindNextPrinterChangeNotification function.

fdwOptions

Reserved; must be zero.

pPrinterNotifyOptions

Pointer to a PRINTER_NOTIFY_OPTIONS structure. The pTypes member of this structure points to an array of one or more PRINTER_NOTIFY_OPTIONS_TYPE structures, each of which specifies a printer information field to monitor. A change notification occurs when one or more of the specified fields changes. When a change occurs, the FindNextPrinterChangeNotification function can retrieve the new printer information. This parameter can be NULL if fdwFlags is nonzero.

For a list of fields that can be monitored, see PRINTER_NOTIFY_OPTIONS_TYPE.

Return Value

If the function succeeds, the return value is a handle to a change notification object associated with the specified printer or print server.

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

Remarks

To monitor a printer or print server, call the FindFirstPrinterChangeNotification function, then use the returned change notification object handle in a call to one of the wait functions:WaitForSingleObject, WaitForSingleObjectEx, WaitForMultipleObjects, or WaitForMultipleObjectsEx. A wait operation on a change notification object is satisfied when the change notification object enters the signaled state. The system signals the object when one or more of the changes specified by fdwFlags or pPrinterNotifyOptions occurs in the monitored printer or print server.

When you call FindFirstPrinterChangeNotification, either fdwFlags must be nonzero or pPrinterNotifyOptions must be non-NULL. If both are specified, notifications will occur for both.

When a wait operation on a printer change notification object is satisfied, call the FindNextPrinterChangeNotification function to determine the cause of the notification. For a condition specified by fdwFlags, FindNextPrinterChangeNotification reports the condition or conditions that changed. For a printer information field specified by pPrinterNotifyOptions , FindNextPrinterChangeNotification reports the field or fields that changed as well as the new information for these fields. FindNextPrinterChangeNotification also resets the change notification object to the nonsignaled state so you can use it in another wait operation to continue monitoring the printer or print server.

Do not call the FindNextPrinterChangeNotification function if the change notification object is not in the signaled state. If the wait function returns the value WAIT_TIMEOUT, the change object is not in the signaled state. Call the FindNextPrinterChangeNotification function only if the wait function succeeds without timing out.

When you no longer need the change notification object, close it by calling the FindClosePrinterChangeNotification function.

The three Find*PrinterChangeNotification functions, in combination with the wait functions, provide an asynchronous and resource-efficient alternative to the WaitForPrinterChange function.

See Also

FindClosePrinterChangeNotification, FindNextPrinterChangeNotification, OpenPrinter, PRINTER_NOTIFY_OPTIONS, PRINTER_NOTIFY_OPTIONS_TYPE, WaitForMultipleObjects, WaitForMultipleObjectsEx, WaitForPrinterChange, WaitForSingleObject, WaitForSingleObjectEx


FindNextChangeNotification
 FindNextChangeNotification  QuickInfo  Overview  Group

The FindNextChangeNotification function requests that the operating system signal a change notification handle the next time it detects an appropriate change.

BOOL FindNextChangeNotification(

HANDLE  hChangeHandle	// handle of change notification to signal
);
Parameters

hChangeHandle

Identifies a change notification handle created by the FindFirstChangeNotification function.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

After the FindNextChangeNotification function returns successfully, the application can wait for notification that a change has occurred by using the WaitForSingleObject or WaitForMultipleObjects function.

If a change occurs after a call to FindFirstChangeNotification but before a call to FindNextChangeNotification, the operating system records the change. When FindNextChangeNotification is executed, the recorded change immediately satisfies a wait for the change notification.

FindNextChangeNotification should not be used more than once on the same handle without using either WaitForSingleObject or WaitForMultipleObjects. An application may miss a change notification if it uses FindNextChangeNotification when there is a change request outstanding.

When hChangeHandle is no longer needed, close it by using the FindCloseChangeNotification function.

See Also

FindCloseChangeNotification, FindFirstChangeNotification, WaitForMultipleObjects, WaitForSingleObject


FindNextFile
 FindNextFile  QuickInfo  Overview  Group

The FindNextFile function continues a file search from a previous call to the FindFirstFile function.

BOOL FindNextFile(

HANDLE  hFindFile,	// handle of search
LPWIN32_FIND_DATA  lpFindFileData	// address of structure for data on found file
);
Parameters

hFindFile

Identifies a search handle returned by a previous call to the FindFirstFile function.

lpFindFileData

Points to the WIN32_FIND_DATA structure that receives information about the found file or subdirectory. The structure can be used in subsequent calls to FindNextFile to refer to the found file or directory.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To get extended error information, call GetLastError. If no matching files can be found, the GetLastError function returns ERROR_NO_MORE_FILES.

Remarks

The FindNextFile function searches for files by name only; it cannot be used for attribute-based searches.

See Also

FindClose, FindFirstFile, GetFileAttributes, SetFileAttributes, WIN32_FIND_DATA


FindNextPrinterChangeNotification
 FindNextPrinterChangeNotification  QuickInfo  Overview  Group

The FindNextPrinterChangeNotification function retrieves information about the most recent change notification for a change notification object associated with a printer or print server. Call this function when a wait operation on the change notification object is satisfied.

The function also resets the change notification object to the not-signaled state. You can then use the object in another wait operation to continue monitoring the printer or print server. The operating system will set the object to the signaled state the next time one of a specified set of changes occurs to the printer or print server. The FindFirstPrinterChangeNotification function creates the change notification object and specifies the set of changes to be monitored.

BOOL FindNextPrinterChangeNotification(

HANDLE  hChange,	// handle to change notification object of interest
PDWORD  pdwChange	// pointer to a value that indicates the condition that changed
LPVOID  pPrinterNotifyOptions,	// pointer to a structure that specifies a refresh flag
LPVOID  *ppPrinterNotifyInfo,	// pointer to a pointer that receives printer information buffer
);
Parameters

hChange

Handle to a change notification object associated with a printer or print server. You obtain such a handle by calling the FindFirstPrinterChangeNotification function. The operating system sets this change notification object to the signaled state when it detects one of the changes specified in the object's change notification filter.

pdwChange

Pointer to a doubleword variable whose bits are set to indicate the changes that occurred to cause the most recent notification. The bit flags that might be set correspond to those specified in the fdwFlags parameter of the FindFirstPrinterChangeNotification call. The system sets one or more of the following bit flags:

Value	Meaning
PRINTER_CHANGE_ADD_FORM
	A form was added to the server.
PRINTER_CHANGE_ADD_JOB
	A print job was sent to the printer.
PRINTER_CHANGE_ADD_PORT
	A port or monitor was added to the server.
PRINTER_CHANGE_ADD_PRINT_PROCESSOR
	A print processor was added to the server.
PRINTER_CHANGE_ADD_PRINTER
	A printer was added to the server.
PRINTER_CHANGE_ADD_PRINTER_DRIVER
	A printer driver was added to the server.
PRINTER_CHANGE_CONFIGURE_PORT
	A port was configured on the server.
PRINTER_CHANGE_DELETE_FORM
	A form was deleted from the server.
PRINTER_CHANGE_DELETE_JOB
	A job was deleted.
PRINTER_CHANGE_DELETE_PORT
	A port or monitor was deleted from the server.
PRINTER_CHANGE_DELETE_PRINT_PROCESSOR
	A print processor was deleted from the server.
PRINTER_CHANGE_DELETE_PRINTER
	A printer was deleted.
PRINTER_CHANGE_DELETE_PRINTER_DRIVER
	A printer driver was deleted from the server.
PRINTER_CHANGE_FAILED_CONNECTION_PRINTER
	A printer connection has failed.
PRINTER_CHANGE_SET_FORM
	A form was set on the server.
PRINTER_CHANGE_SET_JOB
	A job was set.
PRINTER_CHANGE_SET_PRINTER
	A printer was set.
PRINTER_CHANGE_SET_PRINTER_DRIVER
	A printer driver was set.
PRINTER_CHANGE_WRITE_JOB
	Job data was written.
pPrinterNotifyOptions

Pointer to a PRINTER_NOTIFY_OPTIONS structure. Set the Flags member of this structure to PRINTER_NOTIFY_OPTIONS_REFRESH, to cause the function to return the current data for all monitored printer information fields. The function ignores all other members of the structure. This parameter can be NULL.

ppPrinterNotifyInfo

Pointer to a pointer variable that receives the address of a system-allocated, read-only buffer. Call the FreePrinterNotifyInfo function to free the buffer when you are finished with it. This parameter can be NULL if no information is required.

The buffer contains a PRINTER_NOTIFY_INFO structure, which contains an array of PRINTER_NOTIFY_INFO_DATA structures. Each element of the array contains information about one of the fields specified in the pPrinterNotifyOptions parameter of the FindFirstPrinterChangeNotification call. Typically, the function provides data only for the fields that changed to cause the most recent notification. However, if the structure pointed to by the pPrinterNotifyOptions parameter specifies PRINTER_NOTIFY_OPTIONS_REFRESH, the function provides data for all monitored fields.

If the PRINTER_NOTIFY_INFO_DISCARDED bit is set in the Flags member of the PRINTER_NOTIFY_INFO structure, an overflow or error occurred, and notifications may have been lost. In this case, no additional notifications will be sent until you make a second FindNextPrinterChangeNotification call that specifies PRINTER_NOTIFY_OPTIONS_REFRESH.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

Call the FindNextPrinterChangeNotification function after a wait operation on a notification object created by FindFirstPrinterChangeNotification has been satisfied. Calling FindNextPrinterChangeNotification lets you obtain information about the change that satisfied the wait operation, and resets the notification object so it can be signaled when the next change occurs.

Do not call the FindNextPrinterChangeNotification function if the change notification object is not in the signaled state. If a wait function returns the value WAIT_TIMEOUT, the change object is not in the signaled state. Call the FindNextPrinterChangeNotification function only if the wait function succeeds without timing out.

To continue monitoring the printer or print server for changes, repeat the cycle of calling one of the wait functions, and then calling the FindNextPrinterChangeNotification function to examine the change and reset the notification object. The wait functions are WaitForSingleObject, WaitForSingleObjectEx, WaitForMultipleObjects, and WaitForMultipleObjectsEx.

FindNextPrinterChangeNotification may combine multiple changes to the same printer information field into a single notification. When this occurs, the function typically collapses all changes for the field into a single entry in the array of PRINTER_NOTIFY_INFO_DATA structures in ppPrinterNotifyInfo; the single entry reports only the most current information. However, for some job and printer information fields, the function can return multiple array entries for the same field. In this case, the last array entry for the field reports the current data, and the earlier entries contain the data for the intermediate stages.

When you no longer need the change notification object, close it by calling the FindClosePrinterChangeNotification function.

The three Find*PrinterChangeNotification functions, in combination with the wait functions, provide an asynchronous, more resource-efficient alternative to the WaitForPrinterChange function.

See Also

FindClosePrinterChangeNotification, FindFirstPrinterChangeNotification, PRINTER_NOTIFY_INFO, PRINTER_NOTIFY_INFO_DATA, PRINTER_NOTIFY_OPTIONS, WaitForMultipleObjects, WaitForMultipleObjectsEx, WaitForPrinterChange, WaitForSingleObject, WaitForSingleObjectEx


FindResource
 FindResource  QuickInfo  Overview  Group

The FindResource function determines the location of a resource with the specified type and name in the specified module.

HRSRC FindResource(

HMODULE  hModule,	// resource-module handle
LPCTSTR  lpName,	// address of resource name
LPCTSTR  lpType	// address of resource type
);
Parameters

hModule

Identifies the module whose executable file contains the resource.

lpName

Specifies the name of the resource. For more information, see the Remarks section.

lpType

Specifies the resource type. For more information, see the Remarks section. For standard resource types, this parameter can be one of the following values:

Value	Meaning
RT_ACCELERATOR	Accelerator table
RT_BITMAP	Bitmap resource
RT_DIALOG	Dialog box
RT_FONT	Font resource
RT_FONTDIR	Font directory resource
RT_MENU	Menu resource
RT_RCDATA	Application-defined resource (raw data)
RT_STRING	String-table entry
RT_MESSAGETABLE	Message-table entry
RT_CURSOR	Hardware-dependent cursor resource
RT_GROUP_CURSOR	Hardware-independent cursor resource
RT_ICON	Hardware-dependent icon resource
RT_GROUP_ICON	Hardware-independent icon resource
RT_VERSION	Version resource
Return Value

If the function succeeds, the return value is a handle to the specified resource's info block. To obtain a handle to the resource, pass this handle to the LoadResource function.

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

Remarks

If the high-order word of the lpName or lpType parameter is zero, the low-order word specifies the integer identifier of the name or type of the given resource. Otherwise, those parameters are long pointers to null-terminated strings. If the first character of the string is a pound sign (#), the remaining characters represent a decimal number that specifies the integer identifier of the resource's name or type. For example, the string "#258" represents the integer identifier 258.

An application should reduce the amount of memory required for the resources by referring to them by integer identifier instead of by name.

An application can use FindResource to find any type of resource, but this function should be used only if the application must access the binary resource data when making subsequent calls to LoadLibrary and LockResource.

To use a resource immediately, an application should use one of the following resource-specific functions to find and load the resources in one call:

Function	Action
FormatMessage	Loads and formats a message-table entry.
LoadAccelerators	Loads an accelerator table.
LoadBitmap	Loads a bitmap resource.
LoadCursor	Loads a cursor resource.
LoadIcon	Loads an icon resource.
LoadMenu	Loads a menu resource.
LoadString	Loads a string-table entry.
For example, an application can use the LoadIcon function to load an icon for display on the screen. However, the application should use FindResource and LoadResource if it is loading the icon to copy its data to another application.

See Also

FindResourceEx, FormatMessage, LoadAccelerators, LoadBitmap, LoadCursor, LoadIcon, LoadMenu, LoadResource, LoadString, LockResource, SizeofResource


FindResourceEx
 FindResourceEx  QuickInfo  Overview  Group

The FindResourceEx function determines the location of the resource with the specified type, name, and language in the specified module.

HRSRC FindResourceEx(

HMODULE  hModule,	// resource-module handle
LPCTSTR  lpType,	// address of resource type
LPCTSTR  lpName,	// address of resource name
WORD  wLanguage	// resource language
);
Parameters

hModule

Identifies 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

Points to a null-terminated string specifying the type name of the resource. For more information, see the Remarks section. For standard resource types, this parameter can be one of the following values:

Value	Meaning
RT_ACCELERATOR	Accelerator table
RT_BITMAP	Bitmap resource
RT_DIALOG	Dialog box
RT_FONT	Font resource
RT_FONTDIR	Font directory resource
RT_MENU	Menu resource
RT_RCDATA	Application-defined resource (raw data)
RT_STRING	String-table entry
RT_MESSAGETABLE	Message-table entry
RT_CURSOR	Hardware-dependent cursor resource
RT_GROUP_CURSOR	Hardware-independent cursor resource
RT_ICON	Hardware-dependent icon resource
RT_GROUP_ICON	Hardware-independent icon resource
RT_VERSION	Version resource
lpName

Points to a null-terminated string specifying the name of the resource. For more information, see the Remarks section.

wLanguage

Specifies the language of the resource. If this parameter is MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), the current language associated with the calling thread is used.

To specify a language other than the current language, use the MAKELANGID macro to create this parameter. For more information, see the MAKELANGID macro.

Return Value

If the function succeeds, the return value is a handle to the specified resource's info block. To obtain a handle to the resource, pass this handle to the LoadResource function.

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

Remarks

If the high-word of the lpType or lpName parameter is zero, the low-word specifies the integer identifier of the type or name of the given resource. Otherwise, those parameters are pointers to null-terminated strings. If the first character of the string is a pound sign (#), the remaining characters represent a decimal number that specifies the integer identifier of the resource's name or type. For example, the string "#258" represents the integer identifier 258.

Applications should reduce the amount of memory required for the resources by referring to them by integer identifier instead of by name.

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 the LoadLibrary and LockResource functions.

To use a resource immediately, an application should use the following resource-specific functions to find and load the resources in one call:

Function	Action
FormatMessage	Loads and formats a message-table entry.
LoadAccelerators	Loads an accelerator table.
LoadBitmap	Loads a bitmap resource.
LoadCursor	Loads a cursor resource.
LoadIcon	Loads an icon resource.
LoadMenu	Loads a menu resource.
LoadString	Loads a string-table entry.
For example, an application can use the LoadIcon function to load an icon for display on the screen. However, the application should use FindResource and LoadResource if it is loading the icon to copy its data to another application.

See Also

FindResource, FormatMessage, LoadAccelerators, LoadBitmap, LoadCursor, LoadIcon, LoadMenu, LoadString, LoadResource, MAKELANGID


FindText
 FindText  QuickInfo  Overview  Group

The FindText function creates a system-defined modeless dialog box that enables the user to find text within a document.

HWND FindText(

LPFINDREPLACE  lpfr	// address of structure with initialization data
);
Parameter

lpfr

Points to a FINDREPLACE structure that contains information used to initialize the dialog box. When the user makes a selection in the dialog box, the system fills this structure with data that describes the user's selection and then sends a message to the application. This message contains a pointer to the FINDREPLACE structure.

Return Value

If the function succeeds, the return value is the window handle of the dialog box.

If the function fails, the return value is NULL. To get extended error information, call CommDlgExtendedError. 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

FindText does not perform a search operation; it simply returns a string typed by the user (as well as related data such as the direction in which the search should occur). An application must perform the search by using this string.

An application can use the window handle returned by the function to communicate with or to close the dialog box.

The dialog box procedure for the Find dialog box passes user requests to the application by sending special messages. The lParam parameter of each of these messages contains a pointer to a FINDREPLACE structure. The procedure sends the messages to the window identified by the hwndOwner member of the FINDREPLACE structure. An application can register the identifier for these messages by specifying the "commdlg_FindReplace" string in a call to the RegisterWindowMessage function.

For the TAB key to function correctly, any application that calls FindText must also call the IsDialogMessage function in its main message loop. IsDialogMessage returns a value that indicates whether messages are intended for the Find dialog box.

If the hook function (pointed to by the lpfnHook member of the FINDREPLACE structure) processes the WM_CTLCOLORDLG message, the function must return a handle of the brush that should be used to paint the control background.

See Also

CommDlgExtendedError, FINDREPLACE, IsDialogMessage, RegisterWindowMessage, ReplaceText, WM_CTLCOLORDLG,


FindWindow
 FindWindow  QuickInfo  Overview  Group

The FindWindow function retrieves the handle of the top-level window whose class name and window name match the specified strings. This function does not search child windows.

HWND FindWindow(

LPCTSTR  lpClassName,	// address of class name
LPCTSTR  lpWindowName	// address of window name
);
Parameters

lpClassName

Points to a null-terminated string that specifies the class name or is an atom that identifies the class-name string. If this parameter is an atom, it must be a global atom created by a previous call to the GlobalAddAtom function. The atom, a 16-bit value, must be placed in the low-order word of lpClassName; the high-order word must be zero.

lpWindowName

Points to a null-terminated string that specifies the window name (the window's title). If this parameter is NULL, all window names match.

Return Value

If the function succeeds, the return value is the handle of 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.

See Also

EnumWindows, FindWindowEx, GetClassName, GlobalAddAtom


FindWindowEx [New - Windows 95]
 FindWindowEx  QuickInfo

[New - Windows 95]

The FindWindowEx function retrieves the handle of a window whose class name and window name match the specified strings. The function searches child windows, beginning with the one following the given child window.

HWND FindWindowEx(

HWND  hwndParent,	// handle of parent window
HWND  hwndChildAfter,	// handle of a child window
LPCTSTR  lpszClass,	// address of class name
LPCTSTR  lpszWindow	// address of window name
);
Parameters

hwndParent

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

hwndChildAfter

Identifies a child window. The search begins with the next child window in the Z order. hwndChildAfter 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 windows.

lpszClass

Points to a null-terminated string that specifies the class name or is an atom that identifies the class-name string. If this parameter is an atom, it must be a global atom created by a previous call to the GlobalAddAtom function. The atom, a 16-bit value, must be placed in the low-order word of lpszClass; the high-order word must be zero.

lpszWindow

Points to a null-terminated string that specifies the window name (the window's title). If this parameter is NULL, all window names match.

Return Value

If the function succeeds, the return value is the handle of 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.

See Also

EnumWindows, FindWindow, GetClassName, GlobalAddAtom


FixBrushOrgEx
 FixBrushOrgEx  QuickInfo  Overview  Group

The FixBrushOrgEx function is not implemented in the Win32 API. It is provided for compatibility with Win32s. If called, the function does nothing, and returns FALSE.

See Also

GetBrushOrgEx, SetBrushOrgEx


FlashWindow
 FlashWindow  QuickInfo  Overview  Group

The FlashWindow function flashes the specified window once.

BOOL FlashWindow(

HWND  hWnd,	// handle of window to flash
BOOL  bInvert	// flash status
);
Parameters

hWnd

Identifies the window to be flashed. The window can be either open or minimized (iconic).

bInvert

Specifies whether the window is to be flashed or returned to its original state. The window is flashed from one state to the other if this parameter is TRUE. If it is FALSE, the window is returned to its original state (either active or inactive).

Windows NT: If the window is iconic, this parameter is ignored.

Windows 95: When an application is iconic, the fInvert parameter is not ignored. If this parameter is TRUE, the taskbar icon window flashes active/inactive.

Return Value

The return value specifies the window's state before the call to the FlashWindow function. If the window was active before the call, it is TRUE; otherwise, it is FALSE.

Remarks

Flashing a window means changing the appearance of its caption bar as if the window were changing from inactive to active status, or vice versa. (An inactive caption bar changes to an active caption bar; an active caption bar changes to an inactive caption bar.)

Typically, a window is flashed to inform the user that the window requires attention but that it does not currently have the keyboard focus.

The FlashWindow function flashes the window only once; for repeated flashing, the application should create a system timer.

Windows 95: If the application is iconic, the fInvet parameter is NOT ignored. If the fInvert parameter is TRUE, the taskbar icon window flashes activ/inactive. If fInvert is FALSE, the taskbar icon window flashes inactive meaning that it does not change colors. It flashes, as if it were being redrawn, but it does not provide the visual invert clue to the user.

Windows NT: This function always returns TRUE for iconic windows. If the window is iconic, FlashWindow simply flashes the icon; the bInvert parameter is ignored for iconic windows.


FlattenPath
 FlattenPath  QuickInfo  Overview  Group

The FlattenPath function transforms any curves in the path that is selected into the current device context (DC), turning each curve into a sequence of lines.

BOOL FlattenPath(

HDC  hdc	// handle of device context
);
Parameters

hdc

Identifies a DC that contains a valid path.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To get extended error information, call GetLastError. GetLastError may return one of the following error codes:

ERROR_CAN_NOT_COMPLETE
ERROR_INVALID_PARAMETER
ERROR_NOT_ENOUGH_MEMORY

See Also

WidenPath


FloodFill
 FloodFill  QuickInfo  Overview  Group

The FloodFill function fills an area of the display surface with the current brush. The area is assumed to be bounded as specified by the crFill parameter.

The FloodFill function is included only for compatibility with earlier versions of Windows. For Win32-based applications, use the ExtFloodFill function with FLOODFILLBORDER specified.

BOOL FloodFill(

HDC  hdc,	// handle of device context
int  nXStart,	// x-coordinate, where fill begins
int  nYStart,	// y-coordinate, where fill begins
COLORREF  crFill	// fill color
);
Parameters

hdc

Identifies a device context.

nXStart

Specifies the logical x-coordinate of the point where filling is to begin.

nYStart

Specifies the logical y-coordinate of the point where filling is to begin.

crFill

Specifies the color of the boundary or of the area to be filled.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

Following are reasons this function might fail:

•	The fill could not be completed.

•	The given point has the boundary color specified by the crFill parameter.

•	The given point lies outside the current clipping region — that is, it is not visible on the device.

See Also

ExtFloodFill


FlushConsoleInputBuffer
 FlushConsoleInputBuffer  QuickInfo  Overview  Group

The FlushConsoleInputBuffer function flushes the console input buffer. All input records currently in the input buffer are discarded.

BOOL FlushConsoleInputBuffer(

HANDLE  hConsoleInput	// handle of console input buffer
);
Parameters

hConsoleInput

Identifies the console input buffer. The handle must have GENERIC_WRITE access.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

GetNumberOfConsoleInputEvents, PeekConsoleInput, ReadConsoleInput, WriteConsoleInput


FlushFileBuffers
 FlushFileBuffers  QuickInfo  Overview  Group

The FlushFileBuffers function clears the buffers for the specified file and causes all buffered data to be written to the file.

BOOL FlushFileBuffers(

HANDLE  hFile	// open handle to file whose buffers are to be flushed
);
Parameters

hFile

An open file handle. The function flushes this file's buffers. The file handle must have GENERIC_WRITE access to the file.

If hFile is a handle to a communications device, the function only flushes the transmit buffer.

If hFile is a handle to the server end of a named pipe, the function does not return until the client has read all buffered data from the pipe.

Windows NT: The function fails if hFile is a handle to console output. That is because console output is not buffered. The function returns FALSE, and GetLastError returns ERROR_INVALID_HANDLE.

Windows 95: The function does nothing if hFile is a handle to console output. That is because console output is not buffered. The function returns TRUE, but it does nothing.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The WriteFile and WriteFileEx functions typically write data to an internal buffer that the operating system writes to disk on a regular basis. The FlushFileBuffers function writes all of the buffered information for the specified file to disk.

You can pass the same file handle used with the _lread, _lwrite, _lcreat, and related functions to FlushFileBuffers.

See Also

_lread, _lwrite, _lcreat, WriteFile, WriteFileEx


FlushInstructionCache
 FlushInstructionCache  QuickInfo  Overview  Group

The FlushInstructionCache function flushes the instruction cache for the specified process.

BOOL FlushInstructionCache(

HANDLE  hProcess,	// handle of process with cache to flush
LPCVOID  lpBaseAddress,	// address of region to flush
DWORD  dwSize	// length of region to flush
);
Parameters

hProcess

Identifies the process that has an instruction cache to flush.

lpBaseAddress

Points to the base of the region to be flushed. This parameter can be NULL.

dwSize

Specifies the length of the region to be flushed if the lpBaseAddress parameter is not NULL.

Return Value

If the function succeeds, the return value is TRUE.

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

Windows 95: The FlushInstructionCache function always returns TRUE. windows 95 supports single-processor machines only.


FlushViewOfFile
 FlushViewOfFile  QuickInfo  Overview  Group

The FlushViewOfFile function writes to the disk a byte range within a mapped view of a file.

BOOL FlushViewOfFile(

LPCVOID  lpBaseAddress,	// start address of byte range to flush
DWORD  dwNumberOfBytesToFlush	// number of bytes in range
);
Parameters

lpBaseAddress

Points to the base address of the byte range to be flushed to the disk representation of the mapped file.

dwNumberOfBytesToFlush

Specifies the number of bytes to flush.

If dwNumberOfBytesToFlush is zero, the file is flushed from the base address to the end of the mapping.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

Flushing a range of a mapped view causes any dirty pages within that range to be written to the disk. Dirty pages are those whose contents have changed since the file view was mapped.

See Also

MapViewOfFile, UnmapViewOfFile


FMExtensionProc
 FMExtensionProc  QuickInfo  Overview  Group

The FMExtensionProc function is an application-defined callback function that processes menu commands and messages sent to a File Manager extension dynamic-link library (DLL).

LONG WINAPI FMExtensionProc(

HWND  hwnd,	// handle of extension window
WORD  wEvent,	// menu-item identifier, or message
LONG  lParam	// additional message information
);
Parameters

hwnd

Identifies the File Manager window. An extension DLL should use this handle to specify the owner for any dialog box or message box that the DLL may display and to send request messages to File Manager.

wEvent

Specifies the message. This parameter can be one of the following values:

Value	Meaning
1−99	The user selected the menu item identified by this number.
FMEVENT_INITMENU	User selected the extension's menu.
FMEVENT_LOAD	File Manager is loading the extension DLL.
FMEVENT_SELCHANGE	Selection changed in File Manager's directory window or in Search Results window.
FMEVENT_UNLOAD	File Manager is unloading the extension DLL.
FMEVENT_USER_REFRESH	User chose the Refresh command from the Window menu.
lParam

Specifies 32 bits of additional message-specific information.

Return Value

The callback function should return the result of the message processing. The actual return value depends on the message processed.

Remarks

Whenever File Manager calls the FMExtensionProc function, it waits to refresh its directory windows (for changes in the file system) until after the function returns. This allows the extension to perform large numbers of file operations without excessive repainting by File Manager. It is not necessary for the extension to send the FM_REFRESH_WINDOWS message to notify File Manager to repaint its windows.


FoldString
 FoldString  QuickInfo  Overview  Group

The FoldString function maps one string to another, performing a specified transformation option.

int FoldString(

DWORD  dwMapFlags,	// mapping transformation options
LPCTSTR  lpSrcStr,	// address of source string
int  cchSrc,	// size of source string, in bytes or characters
LPTSTR  lpDestStr,	// address of destination buffer
int  cchDest	// size of destination buffer, in bytes or characters
);
Parameters

dwMapFlags

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 bit-flag constants:

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

Points to the string to be mapped.

cchSrc

Specifies the size, in bytes (ANSI version) or characters (Unicode version), of the lpSrcStr buffer. If cchSrc is −1, lpSrcStr is assumed to be null-terminated, and the length is calculated automatically.

lpDestStr

Points to the buffer to store the mapped string.

cchDest

Specifies the size, in bytes (ANSI version) or characters (Unicode version), of the lpDestStr buffer. If cchDest is zero, the function returns the number of bytes or characters required to hold the mapped string, and the buffer pointed to by lpDestStr is not used.

Return Value

If the function succeeds, the return value is the number of bytes (ANSI version) or characters (Unicode version) written to the destination buffer, or if the cchDest parameter is zero, the number of bytes or characters required to hold the mapped string.

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.

See Also

LCMapString, CompareString


ForegroundIdleProc
 ForegroundIdleProc  QuickInfo

The ForegroundIdleProc hook procedure is an application-defined callback function the system calls whenever the 32-bit foreground thread is about to become idle.

DWORD ForegroundIdleProc(

int  code,	// hook code
DWORD  wParam,	// not used
LONG  lParam	// not used
);
Parameters

code

Specifies whether the hook procedure must process the message. If code is HC_ACTION, the hook procedure must process the message. If code is less than zero, the hook procedure must pass the message to the CallNextHookEx function without further processing and should return the value returned by CallNextHookEx.

wParam

Not used.

lParam

Not used.

Remarks

An application installs this hook procedure by specifying the WH_FOREGROUNDIDLE hook type and the address of the hook procedure in a call to the SetWindowsHookEx function.

ForegroundIdleProc is a placeholder for the application-defined function name.

This is a thread-specific hook.

See Also

CallNextHookEx, SetWindowsHookEx


FormatMessage
 FormatMessage  QuickInfo  Overview  Group

The FormatMessage function formats a message string. The function requires a message definition as input. The message definition can come from a buffer passed into the function. It can come from a message table resource in an already-loaded module. Or the caller can ask the function to search the system's message table resource(s) for the message definition. The function finds the message definition in a message table resource based on a message identifier and a language identifier. The function copies the formatted message text to an output buffer, processing any embedded insert sequences if requested.

DWORD FormatMessage(

DWORD  dwFlags,	// source and processing options
LPCVOID  lpSource,	// address of  message source
DWORD  dwMessageId,	// requested message identifier
DWORD  dwLanguageId,	// language identifier for requested message
LPTSTR  lpBuffer,	// address of message buffer
DWORD  nSize,	// maximum size of message buffer
va_list *  Arguments	// address of array of message inserts
);
Parameters

dwFlags

Contains a set of bit flags that specify aspects of the formatting process and how to interpret the lpSource parameter. The low-order byte of dwFlags specifies how the function handles line breaks in the output buffer. The low-order byte can also specify the maximum width of a formatted output line.

You can specify a combination of the following bit flags:

Value	Meaning
FORMAT_MESSAGE_ALLOCATE_BUFFER
	Specifies that the lpBuffer parameter is a pointer to a PVOID pointer, and that the nSize parameter specifies the minimum number of bytes (ANSI version) or characters (Unicode version) to allocate for an output message buffer. The function allocates a buffer large enough to hold the formatted message, and places a pointer to the allocated buffer at the address specified by lpBuffer. The caller should use the LocalFree function to free the buffer when it is no longer needed.
FORMAT_MESSAGE_IGNORE_INSERTS
	Specifies that insert sequences in the message definition are to be ignored and passed through to the output buffer unchanged. This flag is useful for fetching a message for later formatting. If this flag is set, the Arguments parameter is ignored.
FORMAT_MESSAGE_FROM_STRING
	Specifies that lpSource is a pointer to a null-terminated message definition. The message definition may contain insert sequences, just as the message text in a message table resource may. Cannot be used with FORMAT_MESSAGE_FROM_HMODULE or FORMAT_MESSAGE_FROM_SYSTEM.
FORMAT_MESSAGE_FROM_HMODULE
	Specifies that lpSource is a module handle containing the message-table resource(s) to search. If this lpSource handle is NULL, the current process's application image file will be searched. Cannot be used with FORMAT_MESSAGE_FROM_STRING.
FORMAT_MESSAGE_FROM_SYSTEM
	Specifies that the function should search the system message-table resource(s) for the requested message. If this flag is specified with FORMAT_MESSAGE_FROM_HMODULE, the function searches the system message table if the message is not found in the module specified by lpSource. Cannot be used with FORMAT_MESSAGE_FROM_STRING. If this flag is specified, an application can pass the result of the GetLastError function to retrieve the message text for a system-defined error.
FORMAT_MESSAGE_ARGUMENT_ARRAY
	Specifies that the Arguments parameter is not a va_list structure, but instead is just a pointer to an array of 32-bit values that represent the arguments.
The low-order byte of dwFlags can specify the maximum width of a formatted output line. Use the FORMAT_MESSAGE_MAX_WIDTH_MASK constant and bitwise Boolean operations to set and retrieve this maximum width value.

The following table shows how FormatMessage interprets the value of the low-order byte.

Value	Meaning
0	There are no output line width restrictions. The function stores line breaks that are in the message definition text into the output buffer.
a nonzero value other than FORMAT_MESSAGE_MAX_WIDTH_MASK	The nonzero value is the maximum number of characters in an output line. The function ignores regular line breaks in the message definition text. The function never splits a string delimited by white space across a line break. The function stores hard-coded line breaks in the message definition text into the output buffer. Hard-coded line breaks are coded with the %n escape sequence.
FORMAT_MESSAGE_MAX_WIDTH_MASK	The function ignores regular line breaks in the message definition text. The function stores hard-coded line breaks in the message definition text into the output buffer. The function generates no new line breaks.
lpSource

Specifies the location of the message definition. The type of this parameter depends upon the settings in the dwFlags parameter.

dwFlags Setting	Parameter Type
FORMAT_MESSAGE_FROM_HMODULE	lpSource is an hModule of the module that contains the message table to search.
FORMAT_MESSAGE_FROM_STRING	lpSource is an LPTSTR that points to unformatted message text. It will be scanned for inserts and formatted accordingly.
If neither of these flags is set in dwFlags, then lpSource is ignored.

dwMessageId

Specifies the 32-bit message identifier for the requested message. This parameter is ignored if dwFlags includes FORMAT_MESSAGE_FROM_STRING.

dwLanguageId

Specifies the 32-bit language identifier for the requested message. This parameter is ignored if dwFlags includes FORMAT_MESSAGE_FROM_STRING.

lpBuffer

Points to a buffer for the formatted (and null-terminated) message. If dwFlags includes FORMAT_MESSAGE_ALLOCATE_BUFFER, the function allocates a buffer using the LocalAlloc function, and places the address of the buffer at the address specified in lpBuffer.

nSize

If the FORMAT_MESSAGE_ALLOCATE_BUFFER flag is not set, this parameter specifies the maximum number of bytes (ANSI version) or characters (Unicode version) that can be stored in the output buffer. If FORMAT_MESSAGE_ALLOCATE_BUFFER is set, this parameter specifies the minimum number of bytes or characters to allocate for an output buffer.

Arguments

Points to an array of 32-bit values that are used as insert values in the formatted message. %1 in the format string indicates the first value in the Arguments array; %2 indicates the second argument; and so on.

The interpretation of each 32-bit value depends on the formatting information associated with the insert in the message definition. The default is to treat each value as a pointer to a null-terminated string.

By default, the Arguments parameter is of type va_list*, which is a language- and implementation-specific data type for describing a variable number of arguments. If you do not have a pointer of type va_list*, then specify the FORMAT_MESSAGE_ARGUMENT_ARRAY flag and pass a pointer to an array of 32-bit values; those values are input to the message formatted as the insert values.

Return Value

If the function succeeds, the return value is the number of bytes (ANSI version) or characters (Unicode version) stored in the output buffer, excluding the terminating null character.

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

Remarks

Each insert must have a corresponding element in the array pointed to by the Arguments parameter.

Within the message text, several escape sequences are supported for dynamically formatting the message. These escape sequences and their meanings are shown in the following table. All escape sequences start with the percent character (%).

Escape Sequence	Meaning
%0	Terminates a message text line without a trailing newline character. This escape sequence can be used to build up long lines or to terminate the message itself without a trailing newline character. It is useful for prompt messages.
%n!printf format string!	Identifies an insert. The value of n can be in the range 1 through 99. The printf format string (which must be bracketed by exclamation marks) is optional and defaults to !s! if not specified.
	The printf format string can contain the * specifier for either the precision or the width component. If * is specified for one component, the FormatMessage function uses insert %n+1; it uses %n+2 if * is specified for both components.
	Floating-point printf format specifiers  —  e, E, f, and g  —  are not supported. The workaround is to to use the sprintf function to format the floating-point number into a temporary buffer, then use that buffer as the insert string.
Any other nondigit character following a percent character is formatted in the output message without the percent character. Following are some examples:

Format string	Resulting output
%%	A single percent sign in the formatted message text.
%n	A hard line break when the format string occurs at the end of a line. This format string is useful when FormatMessage is supplying regular line breaks so the message fits in a certain width.
%space	A space in the formatted message text. This format string can be used to ensure the appropriate number of trailing spaces in a message text line.
%.	A single period in the formatted message text. This format string can be used to include a single period at the beginning of a line without terminating the message text definition.
%!	A single exclamation point in the formatted message text. This format string can be used to include an exclamation point immediately after an insert without its being mistaken for the beginning of a printf format string.
See Also

LoadString, LocalFree


FrameRect
 FrameRect  QuickInfo  Overview  Group

The FrameRect function draws a border around the specified rectangle by using the specified brush. The width and height of the border are always one logical unit.

int FrameRect(

HDC  hDC,	// handle of device context
CONST RECT  * lprc,	// address of rectangle coordinates
HBRUSH  hbr	// handle of brush
);
Parameters

hDC

Identifies the device context in which the border is drawn.

lprc

Points to a RECT structure that contains the logical coordinates of the upper-left and lower-right corners of the rectangle.

hbr

Identifies the brush used to draw the border.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The brush identified by the hbr parameter must have been created by using the CreateHatchBrush, CreatePatternBrush, or CreateSolidBrush function, or retrieved by using the GetStockObject function.

If the bottom member of the RECT structure is less than or equal to the top member, or if the right member is less than or equal to the left member, the function does not draw the rectangle.

See Also

CreateHatchBrush, CreatePatternBrush, CreateSolidBrush, GetStockObject, RECT


FrameRgn
 FrameRgn  QuickInfo  Overview  Group

The FrameRgn function draws a border around the specified region by using the specified brush.

BOOL FrameRgn(

HDC  hdc,	// handle of device context
HRGN  hrgn,	// handle of region to be framed
HBRUSH  hbr,	// handle of brush used to draw border
int  nWidth,	// width of region frame
int  nHeight	// height of region frame
);
Parameters

hdc

Identifies the device context.

hrgn

Identifies the region to be enclosed in a border. The region's coordinates are presumed to be in logical units.

hbr

Identifies the brush to be used to draw the border.

nWidth

Specifies the width, in logical units, of vertical brush strokes.

nHeight

Specifies the height, in logical units, of horizontal brush strokes.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

See Also

FillRgn, PaintRgn


FreeConsole
 FreeConsole  QuickInfo  Overview  Group

The FreeConsole function detaches the calling process from its console.

BOOL FreeConsole(VOID)

Parameters

This function has no parameters.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

If other processes share the console, the console is not destroyed, but the calling process cannot refer to it.

A process can use FreeConsole to detach itself from its current console, and then it can call the AllocConsole function to create a new console.

See Also

AllocConsole


FreeDDElParam
 FreeDDElParam  QuickInfo  Overview  Group

The FreeDDElParam function frees the memory specified by the lParam parameter of a posted DDE message. An application receiving a posted DDE message should call this function after it has used the UnpackDDElParam function to unpack the lParam value.

BOOL FreeDDElParam(

UINT  msg,	// posted DDE message
LONG  lParam	// lParam of message
);
Parameters

msg

Specifies the posted DDE message.

lParam

Specifies the lParam parameter of the posted DDE message.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

An application should call this function only for posted DDE messages.

This function frees the memory specified by the lParam parameter. It does not free the contents of lParam.

See Also

PackDDElParam, ReuseDDElParam, UnpackDDElParam


FreeEnvironmentStrings
 FreeEnvironmentStrings  QuickInfo  Overview  Group

The FreeEnvironmentStrings function frees a block of environment strings.

BOOL FreeEnvironmentStrings(

LPTSTR  lpszEnvironmentBlock	// pointer to a block of environment strings
);
Parameters

lpszEnvironmentBlock

Pointer to a block of environment strings. The pointer to the block must be obtained by calling the GetEnvironmentStrings function.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

When GetEnvironmentStrings is called, it allocates memory for a block of environment strings. When the block is no longer needed, it should be freed by calling FreeEnvironmentStrings.

See Also

GetEnvironmentStrings


FreeLibrary
 FreeLibrary  QuickInfo  Overview  Group

The FreeLibrary function decrements the reference count of the loaded dynamic-link library (DLL) module. When the reference count reaches zero, the module is unmapped from the address space of the calling process and the handle is no longer valid. This function supersedes the FreeModule function.

BOOL FreeLibrary(

HMODULE  hLibModule	// handle of loaded library module
);
Parameters

hLibModule

Identifies the loaded library module. The LoadLibrary or GetModuleHandle function returns this handle.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

Each process maintains a reference count for each loaded library module. This reference count is incremented each time LoadLibrary is called and is decremented each time FreeLibrary is called. A DLL module loaded at process initialization due to load-time dynamic linking has a reference count of one. This count is incremented if the same module is loaded by a call to LoadLibrary.

Before unmapping a library module, the system enables the DLL to detach from the process by calling the DLL's DllEntryPoint function, if it has one, with the DLL_PROCESS_DETACH value. Doing so gives the DLL an opportunity to clean up resources allocated on behalf of the current process. After the entry-point function returns, the library module is removed from the address space of the current process.

Calling FreeLibrary does not affect other processes using the same library module.

See Also

DllEntryPoint, FreeLibraryAndExitThread, FreeModule, GetModuleHandle, LoadLibrary


FreeLibraryAndExitThread
 FreeLibraryAndExitThread  QuickInfo  Overview  Group

The FreeLibraryAndExitThread function decrements the reference count of a loaded dynamic-link library (DLL) by one, and then calls ExitThread to terminate the calling thread. The function does not return.

The FreeLibraryAndExitThread function gives threads that are created and executed within a dynamic-link library an opportunity to safely unload the DLL and terminate themselves.

VOID FreeLibraryAndExitThread(

HMODULE  hLibModule,	// dynamic-link library whose reference count is to decrement
DWORD  dwExitCode	// exit code for thread
);
Parameters

hLibModule

Specifies the dynamic-link library module whose reference count the function decrements.

dwExitCode

Specifies the exit code for the calling thread.

Return Value

The function has no return value. The function does not return. Invalid hLibModule handles are ignored.

Remarks

The FreeLibraryAndExitThread function is implemented as:

    FreeLibrary(hLibModule);

    ExitThread(dwExitCode);

Refer to the reference pages for FreeLibrary and ExitThread for further information on those functions.

See Also

FreeLibrary, ExitThread, DisableThreadLibraryCalls


FreeModule
 FreeModule  QuickInfo  Overview  Group

The FreeModule function is obsolete.

This function is provided only for compatibility with 16-bit versions of Windows. Win32-based applications should use the FreeLibrary function.


FreePrinterNotifyInfo
 FreePrinterNotifyInfo  Overview  Group

The FreePrinterNotifyInfo function frees a system-allocated buffer that was returned by the FindNextPrinterChangeNotification function.

BOOL FreePrinterNotifyInfo(

PPRINTER_NOTIFY_INFO  pPrinterNotifyInfo	// pointer to a PRINTER_NOTIFY_INFO buffer
);
Parameters

pPrinterNotifyInfo

Pointer to a PRINTER_NOTIFY_INFO buffer returned from a call to the FindNextPrinterChangeNotification function. FreePrinterNotifyInfo deallocates this buffer.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

FindNextPrinterChangeNotification, PRINTER_NOTIFY_INFO


FreeProcInstance
 FreeProcInstance  QuickInfo  Overview  Group

The FreeProcInstance function is obsolete.

This function is provided only for compatibility with 16-bit versions of Windows. Win32-based applications should not use this function; it has no meaning in the 32-bit environment.


FreeResource
 FreeResource  QuickInfo  Overview  Group

The FreeResource function is obsolete. It is provided to simplify porting of 16-bit Windows-based applications. It is not necessary for Win32-based applications to free resources loaded by using the LoadResource function.

See Also

LoadResource, LockResource


FreeSelector
 FreeSelector  Overview  Group

The FreeSelector function has been deleted.


FreeSid
 FreeSid  QuickInfo  Overview  Group

The FreeSid function frees a security identifier (SID) previously allocated by using the AllocateAndInitializeSid function.

PVOID FreeSid(

PSID  pSid	// address of SID to free
);
Parameters

pSid

Points to the SID structure to free.

Return Value

This function does not return a value.

See Also

AllocateAndInitializeSid, SID


FSCTL_DISMOUNT_VOLUME
 FSCTL_DISMOUNT_VOLUME  QuickInfo  Overview  Group

dwIoControlCode = FSCTL_DISMOUNT_VOLUME;   // operation code

lpvInBuffer = NULL; // address of input buffer; not used; must be NULL

cbInBuffer = 0;     // size of input buffer; not used; must be zero

lpvOutBuffer ;      // address of output buffer; not used; must be NULL

cbOutBuffer ;       // size of output buffer; not used; must be zero

lpcbBytesReturned ; // address of actual bytes of output; not used; must be NULL

The FSCTL_DISMOUNT_VOLUME DeviceIoControl operation dismounts a volume.

Parameters

lpvInBuffer

Points to an input buffer. Not used with this operation. Set to NULL.

cbInBuffer

Specifies the size, in bytes, of the buffer pointed to by lpvInBuffer. Not used with this operation. Set to zero.

lpvOutBuffer

Points to an output buffer. Not used with this operation. Set to NULL.

cbOutBuffer

Specifies the size, in bytes, of the buffer pointed to by lpvOutBuffer. Not used with this operation. Set to zero.

lpcbBytesReturned

Points to a DWORD that receives the actual size, in bytes, of the data stored into lpvOutBuffer. Not used with this operation. Set to NULL.

Return Value

If the operation succeeds, DeviceIoControl returns TRUE.

If the operation fails, DeviceIoControl returns FALSE. To get extended error information, call GetLastError.

Remarks

The hDevice handle passed to DeviceIoControl must be a handle to a volume, opened for direct access. An application can obtain such a handle by calling CreateFile with lpszName set to a string that looks like this:

\\.\X:

where X is a hard-drive partition letter, floppy disk drive, or CD-ROM drive. The application must also specify the FILE_SHARE_READ and FILE_SHARE_WRITE flags in the fdwShareMode parameter of CreateFile.

If the specified volume is locked, the operation fails.

A dismounted volume has the following properties:

•	There are no open files.

•	The operating system does not "know" about the volume.

The operating system tries to mount an unmounted volume as soon as any attempt is made to access it. For example, a call to GetLogicalDrives triggers the operating system to mount any unmounted volumes.

Dismounting a volume is useful whenever a volume needs to disappear for a while. For example, an application that changes a volume's file system from FAT to NTFS might follow these steps:

1.	Open the volume

2.	Lock the volume

3.	Format the volume

4.	Unlock the volume

5.	Dismount the volume

6.	Close the volume handle

A dismounting operation removes the volume from the FAT file system's "awareness." When the operating system mounts the volume, it appears as an NTFS volume.

See Also

CreateFile, DeviceIoControl, ExitThread, GetLogicalDrives


FSCTL_GET_COMPRESSION [New - Windows NT]
 FSCTL_GET_COMPRESSION  QuickInfo

[New - Windows NT]

dwIoControlCode = FSCTL_GET_COMPRESSION;   // operation code

lpvInBuffer = NULL; // address of input buffer; not used; must be NULL

cbInBuffer = 0;     // size of input buffer; not used; must be zero

lpvOutBuffer ;      // address of output buffer

cbOutBuffer ;       // size of output buffer

lpcbBytesReturned ; // address of actual bytes of output

The FSCTL_GET_COMPRESSION DeviceIoControl operation obtains the current compression state of a file or directory on a volume whose file system supports per-stream compression.

Parameters

lpvInBuffer

Points to an input buffer. Not used with this operation. Set to NULL.

cbInBuffer

Specifies the size, in bytes, of the buffer pointed to by lpvInBuffer. Not used with this operation. Set to zero.

lpvOutBuffer

Points to a buffer that receives a USHORT indicating the current compression state of the file or directory.

The following values are defined:

Value	Meaning
COMPRESSION_FORMAT_NONE	The file or directory is not compressed.
COMPRESSION_FORMAT_LZNT1	The file or directory is compressed, using the LZNT1 compression format.
all other values	Reserved for future use.
cbOutBuffer

Specifies the size, in bytes, of the buffer pointed to by lpvOutBuffer. The buffer  must be large enough to contain one USHORT value.

lpcbBytesReturned

Points to a DWORD value that receives the actual size, in bytes, of the data stored into the buffer pointed to by lpvOutBuffer.

Return Value

If the operation succeeds, DeviceIoControl returns TRUE.

If the operation fails, DeviceIoControl returns FALSE. To get extended error information, call GetLastError.

Remarks

On this release, LZNT1 is the only compression algorithm implemented. Future releases may have additional compression methods.

COMPRESSION_FORMAT_DEFAULT is not a compression state so it is not included in the table under the lpvOutBuffer parameter. This value is only used with the FSCTL_SET_COMPRESSION operation

If the file system of the volume containing the specified file or directory does not support per-file or per-directory compression, the FSCTL_GET_COMPRESSION operation fails.

Windows NT version 3.51 supports file compression on volumes formatted with the NTFS file system.

You can set the compression state of a file or directory by using the FSCTL_SET_COMPRESSION DeviceIoControl operation. You can also compress or uncompress a file with that operation.

You can obtain the compression attribute of a file or directory by calling the GetFileAttributes function. The compression attribute indicates whether a file or directory is compressed. The compression state indicates whether a file or directory is compressed, and, if it is, the format of the compressed data.

See Also

DeviceIoControl, FSCTL_SET_COMPRESSION, GetFileAttributes


FSCTL_LOCK_VOLUME
 FSCTL_LOCK_VOLUME  QuickInfo  Overview  Group

dwIoControlCode = FSCTL_LOCK_VOLUME;   // operation code

lpvInBuffer = NULL; // address of input buffer; not used; must be NULL

cbInBuffer = 0;     // size of input buffer; not used; must be zero

lpvOutBuffer ;      // address of output buffer; not used; must be NULL

cbOutBuffer ;       // size of output buffer; not used; must be zero

lpcbBytesReturned ; // address of actual bytes of output; not used; must be NULL

The FSCTL_LOCK_VOLUME DeviceIoControl operation locks a volume. A locked volume can be accessed only through handles to the file object (*hDevice) that locks the volume.

Parameters

lpvInBuffer

Points to an input buffer. Not used with this operation. Set to NULL.

cbInBuffer

Specifies the size, in bytes, of the buffer pointed to by lpvInBuffer. Not used with this operation. Set to zero.

lpvOutBuffer

Points to an output buffer. Not used with this operation. Set to NULL.

cbOutBuffer

Specifies the size, in bytes, of the buffer pointed to by lpvOutBuffer. Not used with this operation. Set to zero.

lpcbBytesReturned

Points to a DWORD that receives the actual size, in bytes, of the data stored in lpvOutBuffer. Not used with this operation. Set to NULL.

Return Value

If the operation succeeds, DeviceIoControl returns TRUE.

If the operation fails, DeviceIoControl returns FALSE. To get extended error information, call GetLastError.

Remarks

The hDevice handle passed to DeviceIoControl must be a handle to a volume, opened for direct access. An application can obtain such a handle by calling CreateFile with lpszName set to a string that looks like this:

\\.\X:

where X is a hard-drive partition letter, floppy disk drive, or CD-ROM drive. The application must also specify the FILE_SHARE_READ and FILE_SHARE_WRITE flags in the fdwShareMode parameter of CreateFile.

The FSCTL_LOCK_VOLUME operation fails if there are any open files on the volume. Conversely, success of this operation indicates there are no open files.

The operation is useful for applications that need exclusive access to a volume for a period of time—for example, disk utility programs.

A locked volume remains locked until one of the following occurs:

•	The application invokes the FSCTL_UNLOCK_VOLUME DeviceIoControl operation to unlock the volume.

•	The handle closes, either directly through CloseHandle, or indirectly when a process terminates.

The system flushes all cached data to the volume before locking it. For example, any data held in a lazy-write cache is written to the volume.

See Also

CloseHandle, CreateFile, DeviceIoControl, FSCTL_UNLOCK_VOLUME


FSCTL_SET_COMPRESSION [New - Windows NT]
 FSCTL_SET_COMPRESSION  QuickInfo

[New - Windows NT]

dwIoControlCode = FSCTL_SET_COMPRESSION;   // operation code

lpvInBuffer ; 	        // address of input buffer

cbInBuffer ;         // size of input buffer

lpvOutBuffer = NULL; // address of output buffer; not used; must be NULL

cbOutBuffer = 0;     // size of output buffer; not used; must be zero

lpcbBytesReturned ;  // pointer to result of operation

The FSCTL_SET_COMPRESSION DeviceIoControl operation sets the compression state of a file or directory on a volume whose file system supports per-file and per-directory compression. You can use this operation to compress or uncompress a file or directory on such a volume.

Parameters

lpvInBuffer

Points to a buffer that contains a USHORT that specifies a new compression state for the file or directory.

The following values are defined:

Value	Meaning
COMPRESSION_FORMAT_NONE	Uncompress the file or directory.
COMPRESSION_FORMAT_DEFAULT	Compress the file or directory, using the default compression format.
COMPRESSION_FORMAT_LZNT1	Compress the file or directory, using the LZNT1 compression format.
all other values	Reserved for future use.
cbInBuffer

Specifies the size, in bytes, of the buffer pointed to by lpvInBuffer. The buffer must be large enough to contain one USHORT value.

lpvOutBuffer

Points to an output buffer. Not used with this operation. Set to NULL.

cbOutBuffer

Specifies the size, in bytes, of the buffer pointed to by lpvOutBuffer. Not used with this operation. Set to zero.

lpcbBytesReturned

Points to a DWORD that receives the result of the I/O control operation.

Return Value

If the operation succeeds, DeviceIoControl returns TRUE.

If the operation fails, DeviceIoControl returns FALSE. To get extended error information, call GetLastError.

Remarks

On this release, LZNT1 is the only compression algorithm implemented. As a result, LZNT1 will be used as the DEFAULT compression method. Future releases may have additional compression methods which may be used as the DEFAULT.

If the file system of the volume containing the specified file or directory does not support per-file or per-directory compression, the FSCTL_SET_COMPRESSION operation fails.

Windows NT release 3.51 supports file compression on volumes formatted with the NTFS file system.

The compression state change of the file or directory occurs synchronously with the call to DeviceIoControl.

You can obtain the compression state of a file or directory by using the FSCTL_GET_COMPRESSION DeviceIoControl operation.

You can obtain the compression attribute of a file or directory by calling the GetFileAttributes function. The compression attribute indicates whether a file or directory is compressed. The compression state indicates whether a file or directory is compressed and, if it is, the format of the compressed data.

See Also

DeviceIoControl, FSCTL_GET_COMPRESSION, GetFileAttributes


FSCTL_UNLOCK_VOLUME
 FSCTL_UNLOCK_VOLUME  QuickInfo  Overview  Group

dwIoControlCode = FSCTL_UNLOCK_VOLUME;   // operation code

lpvInBuffer = NULL; // address of input buffer; not used; must be NULL

cbInBuffer = 0;     // size of input buffer; not used; must be zero

lpvOutBuffer ;      // address of output buffer; not used; must be NULL

cbOutBuffer ;       // size of output buffer; not used; must be zero

lpcbBytesReturned ; // address of actual bytes of output; not used; must be NULL

The FSCTL_UNLOCK_VOLUME DeviceIoControl operation unlocks a volume.

Parameters

lpvInBuffer

Points to an input buffer. Not used with this operation. Set to NULL.

cbInBuffer

Specifies the size, in bytes, of the buffer pointed to by lpvInBuffer. Not used with this operation. Set to zero.

lpvOutBuffer

Points to an output buffer. Not used with this operation. Set to NULL.

cbOutBuffer

Specifies the size, in bytes, of the buffer pointed to by lpvOutBuffer. Not used with this operation. Set to zero.

lpcbBytesReturned

Points to a DWORD that receives the actual size, in bytes, of the data stored in lpvOutBuffer. Not used with this operation. Set to NULL.

Return Value

If the operation succeeds, DeviceIoControl returns TRUE.

If the operation fails, DeviceIoControl returns FALSE. To get extended error information, call GetLastError.

Remarks

An application can call the FSCTL_LOCK_VOLUME DeviceIoControl operation to lock a volume.

The hDevice handle passed to DeviceIoControl must be a handle to a volume, opened for direct access. An application can obtain such a handle by calling CreateFile with lpszName set to a string that looks like this:

\\.\X:

where X is a hard-drive partition letter, floppy disk drive, or CD-ROM drive. The application must also specify the FILE_SHARE_READ and FILE_SHARE_WRITE flags in the fdwShareMode parameter of CreateFile.

See Also

CreateFile, DeviceIoControl, FSCTL_LOCK_VOLUME


GdiComment
 GdiComment  QuickInfo  Overview  Group

The GdiComment function copies a comment from a buffer into a specified enhanced-format metafile.

BOOL GdiComment(

HDC  hdc,	// handle of a device context
UINT  cbSize,	// size of text buffer
CONST BYTE *  lpData	// address of text buffer
);
Parameters

hdc

Identifies an enhanced-metafile device context.

cbSize

Specifies the length of the comment buffer, in bytes.

lpData

Points to the buffer that contains the comment.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

A comment can include any kind of private information — for example, the source of a picture and the date it was created. A comment should begin with an application signature, followed by the data.

Comments should not contain application-specific or position-specific data. Position-specific data specifies the location of a record, and it should not be included because one metafile may be embedded within another metafile.

A public comment is a comment that begins with the comment signature identifier GDICOMMENT_IDENTIFIER. The following public comments are defined:

Comment	Description
GDICOMMENT_WINDOWS_METAFILE
	The GDICOMMENT_WINDOWS_METAFILE public comment contains a Windows-format metafile that is equivalent to an enhanced-format metafile. This comment is written only by the SetWinMetaFileBits function. The comment record, if given, follows the ENHMETAHEADER metafile record. The comment has the following form:
DWORD ident;         // This contains GDICOMMENT_IDENTIFIER.

DWORD iComment;      // This contains GDICOMMENT_WINDOWS_METAFILE.

DWORD nVersion;      // This contains the version number of the

                     // Windows-format metafile.

DWORD nChecksum;     // This is the additive DWORD checksum for

                     // the enhanced metafile.  The checksum

                     // for the enhanced metafile data including

                     // this comment record must be zero.

                     // Otherwise, the enhanced metafile has been

                     //  modified and the Windows-format

                     // metafile is no longer valid.

DWORD fFlags;        // This must be zero.

DWORD cbWinMetaFile; // This is the size, in bytes. of the

                     // Windows-format metafile data that follows.

GDICOMMENT_BEGINGROUP
	The GDICOMMENT_BEGINGROUP public comment identifies the beginning of a group of drawing records. It identifies an object within an enhanced metafile. The comment has the following form:
DWORD   ident;         // This contains GDICOMMENT_IDENTIFIER.

DWORD   iComment;      // This contains GDICOMMENT_BEGINGROUP.

RECTL   rclOutput;     // This is the bounding rectangle for the

                       // object in logical coordinates.

DWORD   nDescription;  // This is the number of characters in the

                       // optional Unicode description string that

                       // follows. This is zero if there is no

                       // description string.

GDICOMMENT_ENDGROUP
	The GDICOMMENT_ENDGROUP public comment identifies the end of a group of drawing records. The GDICOMMENT_BEGINGROUP comment and the GDICOMMENT_ENDGROUP comment must be included in a pair and may be nested. The comment has the following form:
DWORD   ident;       // This contains GDICOMMENT_IDENTIFIER.

DWORD   iComment;    // This contains GDICOMMENT_ENDGROUP.

GDICOMMENT_MULTIFORMATS
	The GDICOMMENT_MULTIFORMATS public comment allows multiple definitions of a picture to be included in an enhanced metafile. Using this comment, for example, an application can include an encapsulated PostScript definition as well as an enhanced metafile definition of a picture. When the record is played back, GDI selects and renders the first format recognized by the device. The comment has the following form:
DWORD   ident;          // This contains GDICOMMENT_IDENTIFIER.

DWORD   iComment;       // This contains GDICOMMENT_MULTIFORMATS.

RECTL   rclOutput;      // This is the bounding rectangle for the

                        // picture in logical coordinates.

DWORD   nFormats;       // This contains the number of formats in

                        // the comment.

EMRFORMAT aemrformat[1];// This is an array of EMRFORMAT structures

                        // in the order of preference.  The data

                        // for each format follows the last

                        // EMRFORMAT structure.

The EMRFORMAT structure has the following form:

typedef struct tagEMRFORMAT   {

    DWORD   dSignature;

    DWORD   nVersion;

    DWORD   cbData;

    DWORD   offData;

} EMRFORMAT;

See Also

CreateEnhMetaFile, EMRFORMAT, SetWinMetaFileBits


GdiFlush
 GdiFlush  QuickInfo  Overview  Group

The GdiFlush function flushes the calling thread's current batch.

BOOL GdiFlush(VOID)

Parameters

This function has no parameters.

Return Value

If all functions in the current batch succeed, the return value is TRUE; otherwise, it is FALSE, indicating that at least one function returned an error.

Remarks

Batching enhances drawing performance by minimizing the amount of time needed to call GDI drawing functions that return Boolean values. The system accumulates the parameters for calls to these functions in the current batch and then calls the functions when the batch is flushed by any of the following means:

•	Calling the GdiFlush function

•	Reaching or exceeding the batch limit set by the GdiSetBatchLimit function

•	Filling the batching buffers

•	Calling any GDI function that does not return a Boolean value

The return value for GdiFlush applies only to the functions in the batch at the time GdiFlush is called. Errors that occur when the batch is flushed by any other means are never reported.

The GdiGetBatchLimit function returns the batch limit.

Note that the batch limit is maintained for each thread separately. In order to completely disable batching, call GdiSetBatchLimit(1) during the initialization of each thread.

An application should call GdiFlush before a thread goes away if there is a possibility that there are pending function calls in the graphics batch queue. The operating system does not execute such batched functions when a thread goes away.

A multithreaded application that serializes access to GDI objects with a mutex must ensure flushing the GDI batch queue by calling GdiFlush as each thread releases ownership of the GDI object. This prevents collisions of the GDI objects (device contexts, metafiles, and so on).

See Also

GdiGetBatchLimit, GdiSetBatchLimit


GdiGetBatchLimit
 GdiGetBatchLimit  QuickInfo  Overview  Group

The GdiGetBatchLimit function returns the maximum number of function calls that can be accumulated in the calling thread's current batch. The system flushes the current batch whenever this limit is exceeded.

DWORD GdiGetBatchLimit(VOID)

Parameters

This function has no parameters.

Return Value

If the function succeeds, the return value is the batch limit.

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

Remarks

The batch limit is set by using the GdiSetBatchLimit function. Setting the limit to 1 effectively disables batching.

Only GDI drawing functions that return Boolean values can be batched; calls to any other GDI functions immediately flush the current batch. Exceeding the batch limit or calling the GdiFlush function also flushes the current batch.

When the system batches a function call, the function returns TRUE. The actual return value for the function is reported only if GdiFlush is used to flush the batch.

Note that the batch limit is maintained for each thread separately. In order to completely disable batching, call GdiSetBatchLimit(1) during the initialization of each thread.

See Also

GdiFlush, GdiSetBatchLimit


GdiSetBatchLimit
 GdiSetBatchLimit  QuickInfo  Overview  Group

The GdiSetBatchLimit function sets the maximum number of functions that can be accumulated in the calling thread's current batch. The system flushes the current batch whenever this limit is exceeded.

DWORD GdiSetBatchLimit(

DWORD  dwLimit	// batch limit
);
Parameters

dwLimit

Specifies the batch limit to be set. A value of 0 sets the default limit. A value of 1 disables batching.

Return Value

If the function succeeds, the return value is the previous batch limit.

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

Remarks

Only GDI drawing functions that return Boolean values can be accumulated in the current batch; calls to any other GDI functions immediately flush the current batch. Exceeding the batch limit or calling the GdiFlush function also flushes the current batch.

When the system accumulates a function, the function returns TRUE to indicate it is in the batch. When the system flushes the current batch and executes the function for the second time, the return value is either TRUE or FALSE, depending on whether the function succeeds. This second return value is reported only if GdiFlush is used to flush the batch.

Note that the batch limit is maintained for each thread separately. In order to completely disable batching, call GdiSetBatchLimit(1) during the initialization of each thread.

See Also

GdiFlush, GdiGetBatchLimit


GenerateConsoleCtrlEvent
 GenerateConsoleCtrlEvent  QuickInfo  Overview  Group

The GenerateConsoleCtrlEvent function sends a specified signal to a console process group that shares the console associated with the calling process.

BOOL GenerateConsoleCtrlEvent(

DWORD  dwCtrlEvent,	// signal to generate
DWORD  dwProcessGroupId	// process group to get signal
);
Parameters

dwCtrlEvent

Specifies the type of signal to generate. One of the following values is specified:

Value	Meaning
CTRL_C_EVENT	Generates a CTRL+C signal.
CTRL_BREAK_EVENT	Generates a CTRL+BREAK signal.
dwProcessGroupId

Specifies the identifier of the process group that receives the signal. A process group is created when the CREATE_NEW_PROCESS_GROUP flag is specified in a call to the CreateProcess function. The process identifier of the new process is also the process group identifier of a new process group. The process group includes all processes that are descendants of the root process. Only those processes in the group that share the same console as the calling process receive the signal. In other words, if a process in the group creates a new console, that process does not receive the signal, nor do its descendants.

If this parameter is zero, the signal is generated in all processes that share the console of the calling process.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

GenerateConsoleCtrlEvent causes the control handler functions of processes in the target group to be called. All console processes have a default handler function that calls the ExitProcess function. A console process can use the SetConsoleCtrlHandler function to install or remove other handler functions.

SetConsoleCtrlHandler can also enable an inheritable attribute that causes the calling process to ignore CTRL+C signals. If GenerateConsoleCtrlEvent sends a CTRL+C signal to a process for which this attribute is enabled, the handler functions for that process are not called. CTRL+BREAK signals always cause the handler functions to be called.

See Also

CreateProcess, ExitProcess, SetConsoleCtrlHandler


GetAce
 GetAce  QuickInfo  Overview  Group

The GetAce function obtains a pointer to an ACE in an ACL.

An ACE is an access control entry. An ACL is an access control list.

BOOL GetAce(

PACL  pAcl,	// address of access-control list
DWORD  dwAceIndex,	// index of ACE to retrieve
LPVOID  *pAce	// address of pointer to ACE
);
Parameters

pAcl

Points to an ACL structure containing the ACE to be retrieved.

dwAceIndex

Specifies the ACE to which a pointer is retrieved. A value of 0 corresponds to the first ACE in the ACL, 1 to the second ACE, and so on.

pAce

Points to a pointer the function sets to the address of the ACE.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

ACL, AddAccessAllowedAce, AddAccessDeniedAce, AddAce, AddAuditAccessAce, GetAclInformation, InitializeAcl


GetAclInformation
 GetAclInformation  QuickInfo  Overview  Group

The GetAclInformation function retrieves information about an access-control list (ACL).

BOOL GetAclInformation(

PACL  pAcl,	// address of access-control list
LPVOID  pAclInformation,	// address of ACL information
DWORD  nAclInformationLength,	// size of ACL information
ACL_INFORMATION_CLASS  dwAclInformationClass	// class of requested information
);
Parameters

pAcl

Points to an ACL structure. The function retrieves information about this ACL.

pAclInformation

Points to a buffer receiving the requested information. The structure put into the buffer depends on the information class requested in the dwAclInformationClass parameter.

nAclInformationLength

Specifies the size, in bytes, of the buffer pointed to by the pAclInformation parameter.

dwAclInformationClass

Specifies an ACL_INFORMATION_CLASS enumerated type that gives the class of information requested. This parameter can be one of two values from this enumerated type. If the value is AclRevisionInformation, the function fills the buffer pointed to by the pAclInformation parameter with an ACL_REVISION_INFORMATION structure.

If the value is AclSizeInformation, the function fills the buffer pointed to by the pAclInformation parameter with an ACL_SIZE_INFORMATION structure.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

ACL, ACL_REVISION_INFORMATION, ACL_SIZE_INFORMATION, GetAce, InitializeAcl, IsValidAcl, SetAclInformation


GetACP
 GetACP  QuickInfo  Overview  Group

The GetACP function retrieves the current ANSI code-page identifier for the system.

UINT GetACP(VOID)

Parameters

This function has no parameters.

Return Value

If the function succeeds, the return value is the current ANSI code-page identifier for the system, or a default identifier if no code page is current.

Remarks

Following are the ANSI code-page identifiers:

Identifier	Meaning
874	Thai
932	Japan
936	Chinese (PRC, Singapore)
949	Korean
950	Chinese (Taiwan, Hong Kong)
1200	Unicode (BMP of ISO 10646)
1250	Windows 3.1 Eastern European
1251	Windows 3.1 Cyrillic
1252	Windows 3.1 Latin 1 (US, Western Europe)
1253	Windows 3.1 Greek
1254	Windows 3.1 Turkish
1255	Hebrew
1256	Arabic
1257	Baltic
See Also

GetCPInfo, GetOEMCP


GetActiveWindow
 GetActiveWindow  QuickInfo  Overview  Group

The GetActiveWindow function retrieves the window handle of the active window associated with the thread that calls the function.

HWND GetActiveWindow(VOID)

Parameters

This function has no parameters.

Return Value

If the function succeeds, the return value is the handle of the active window associated with the thread that calls the function. If the calling thread does not have an active window, the return value is NULL.

See Also

SetActiveWindow


GetAddressByName [New - Windows NT]
 GetAddressByName  QuickInfo  Overview  Group

[New - Windows NT]

The GetAddressByName function queries a name space, or a set of default name spaces, in order to obtain network address information for a specified network service. This process is known as service name resolution. A network service can also use the function to obtain local address information that it can use with the bind function.

INT GetAddressByName(

DWORD  dwNameSpace,	// name space to query for service address information
LPGUID  lpServiceType,	// the type of the service
LPTSTR  lpServiceName,	// the name of the service
LPINT  lpiProtocols,	// points to array of protocol identifiers
DWORD  dwResolution,	// set of bit flags that specify aspects of name resolution
LPSERVICE_ASYNC_INFO  lpServiceAsyncInfo,	// reserved for future use, must be NULL
LPVOID  lpCsaddrBuffer,	// points to buffer to receive address information
LPDWORD  lpdwBufferLength,	// points to variable with address buffer size information
LPTSTR  lpAliasBuffer,	// points to buffer to receive alias information
LPDWORD  lpdwAliasBufferLength	// points to variable with alias buffer size information
);
Parameters

dwNameSpace

Specifies the name space, or a set of default name spaces, that the operating system will query for network address information.

Use one of the following constants to specify a name space:

Value	Name Space
NS_DEFAULT	A set of default name spaces. The function queries each name space within this set. The set of default name spaces typically includes all the name spaces installed on the system. System administrators, however, can exclude particular name spaces from the set. This is the value that most applications should use for dwNameSpace.
NS_DNS	The Domain Name System used in the Internet for host name resolution.
NS_NETBT	The NetBIOS over TCP/IP layer. All Windows NT systems register their computer names with NetBIOS. This name space is used to convert a computer name to an IP address that uses this registration. Note that NS_NETBT may access a WINS server to perform the resolution.
NS_SAP	The Netware Service Advertising Protocol. This may access the Netware bindery if appropriate. NS_SAP is a dynamic name space that allows registration of services.
NS_TCPIP_HOSTS	Lookup value in the <systemroot>\system32\drivers\etc\hosts file.
NS_TCPIP_LOCAL	Local TCP/IP name resolution mechanisms, including comparisons against the local host name and looks up host names and IP addresses in cache of host to IP address mappings.
Most calls to GetAddressByName should use the special value NS_DEFAULT. This lets a client get by with no knowledge of which name spaces are available on an internetwork. The system administrator determines name space access. Name spaces can come and go without the client having to be aware of the changes.

lpServiceType

Points to a globally unique identifier (GUID) that specifies the type of the network service. The header file SVCGUID.H includes definitions of several GUID service types, and macros for working with them.

lpServiceName

Points to a zero-terminated string that uniquely represents the service name. For example, "MY SNA SERVER".

Setting lpServiceName to NULL is the equivalent of setting dwResolution to RES_SERVICE. The function operates in its second mode, obtaining the local address to which a service of the specified type should bind. The function stores the local address within the LocalAddr member of the CSADDR_INFO structures stored into *lpCsaddrBuffer.

If dwResolution is set to RES_SERVICE, the function ignores the lpServiceName parameter.

If dwNameSpace is set to NS_DNS, *lpServiceName is the name of the host.

lpiProtocols

Points to a zero-terminated array of protocol identifiers. The function restricts a name resolution attempt to name space providers that offer these protocols. This lets the caller limit the scope of the search.

If lpiProtocols is NULL, the function obtains information on all available protocols.

dwResolution

A set of bit flags that specify aspects of the service name resolution process. The following bit flags are defined:

Value	Meaning
RES_SERVICE	If this flag is set, the function obtains the address to which a service of the specified type should bind. This is the equivalent of setting lpServiceName to NULL. If this flag is clear, normal name resolution occurs.
RES_FIND_MULTIPLE	If this flag is set, the operating system performs an extensive search of all name spaces for the service. It will ask every appropriate name space to resolve the service name. If this flag is clear, the operating system stops looking for service addresses as soon as one is found.
RES_SOFT_SEARCH	This flag is valid if the name space supports multiple levels of searching. If this flag is valid and set, the operating system performs a simple and quick search of the name space. This is useful if an application only needs to obtain easy-to-find addresses for the service. If this flag is valid and clear, the operating system performs a more extensive search of the name space.
lplpServiceAsyncInfo

Reserved for future use; must be set to NULL.

lpCsaddrBuffer

Points to a buffer to receive one or more CSADDR_INFO data structures. The number of structures written to the buffer depends on the amount of information found in the resolution attempt. You should assume that multiple structures will be written, although in many cases there will only be one.

lpdwBufferLength

Points to a variable that, upon input, specifies the size, in bytes, of the buffer pointed to by lpCsaddrBuffer.

Upon output, this variable contains the total number of bytes required to store the array of CSADDR_INFO structures. If this value is less than or equal to the input value of *lpdwBufferLength, and the function is successful, this is the number of bytes actually stored in the buffer. If this value is greater than the input value of *lpdwBufferLength, the buffer was too small, and the output value of *lpdwBufferLength is the minimal required buffer size.

lpAliasBuffer

Points to a buffer to receive alias information for the network service.

If a name space supports aliases, the function stores an array of zero-terminated name strings into the buffer pointed to by lpAliasBuffer. There is a double zero-terminator at the end of the list. The first name in the array is the service's primary name. Names that follow are aliases. An example of a name space that supports aliases is DNS.

If a name space does not support aliases, it stores a double zero-terminator into the buffer.

This parameter is optional, and can be set to NULL.

lpdwAliasBufferLength

Points to a variable that, upon input, specifies the size, in bytes, of the buffer pointed to by lpAliasBuffer.

Upon output, this variable contains the total number of bytes required to store the array of name strings. If this value is less than or equal to the input value of *lpdwAliasBufferLength, and the function is successful, this is the number of bytes actually stored in the buffer. If this value is greater than the input value of *lpdwAliasBufferLength, the buffer was too small, and the output value of *lpdwAliasBufferLength is the minimal required buffer size.

If lpAliasBuffer is NULL, lpdwAliasBufferLength is meaningless and can also be NULL.

Return Value

If the function succeeds, the return value is the number of CSADDR_INFO data structures written to the buffer pointed to by lpCsaddrBuffer.

If the function fails, the return value is SOCKET_ERROR( − 1). To get extended error information, call GetLastError. GetLastError may return the following extended error value:

Value	Meaning
ERROR_INSUFFICIENT_BUFFER	The buffer pointed to by lpCsaddrBuffer was too small to receive all of the relevant CSADDR_INFO structures. Call the function with a buffer at least as large as the value returned in *lpdwBufferLength.
Remarks

This function is a more powerful version of the Windows Sockets function gethostbyname The GetAddressByName function works with multiple name services.

The GetAddressByName function lets a client obtain a Windows Sockets address for a network service. The client specifies the service of interest by its service type and service name.

Many name services support a default prefix or suffix that the name service provider considers when resolving service names. For example, in the DNS name space, if a domain is named "nt.microsoft.com", and "ftp millikan" is provided as input, the DNS software fails to resolve "millikan", but successfully resolves "millikan.nt.microsoft.com".

Note that the GetAddressByName function can search for a service address in two ways: within a particular name space, or within a set of default name spaces. Using a default name space, an administrator can specify that certain name spaces will be searched for service addresses only if specified by name. An administrator or name space setup program can also control the ordering of name space searches.

See Also

gethostbyname, CSADDR_INFO


GetArcDirection
 GetArcDirection  QuickInfo  Overview  Group

The GetArcDirection function returns the current arc direction for the specified device context. Arc and rectangle functions use the arc direction.

int GetArcDirection(

HDC  hdc	// handle of device context
);
Parameters

hdc

Identifies the device context.

Return Value

If the function succeeds, the return value specifies the current arc direction. Following are the valid return values:

Value	Meaning
AD_COUNTERCLOCKWISE	Arcs and rectangles are drawn counterclockwise.
AD_CLOCKWISE	Arcs and rectangles are drawn clockwise.
If an error occurs, the return value is zero.

See Also

SetArcDirection


GetAspectRatioFilter
 GetAspectRatioFilter  Overview  Group

The GetAspectRatioFilter function is not implemented in the Win32 API. Win32-based applications should use the GetAspectRatioFilterEx function.


GetAspectRatioFilterEx
 GetAspectRatioFilterEx  QuickInfo  Overview  Group

The GetAspectRatioFilterEx function retrieves the setting for the current aspect-ratio filter.

BOOL GetAspectRatioFilterEx(

HDC  hdc,	// handle of device context
LPSIZE  lpAspectRatio	// address of aspect-ratio filter
);
Parameters

hdc

Identifies a device context.

lpAspectRatio

Points to a SIZE structure that receives the current aspect-ratio filter.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The aspect ratio is the ratio formed by the width and height of a pixel on a given device.

Windows provides a special filter, the aspect-ratio filter, to select fonts that were designed for a particular device. An application can specify that Windows should only retrieve fonts matching the specified aspect ratio by calling the SetMapperFlags function.

See Also

SetMapperFlags, SIZE


GetAsyncKeyState
 GetAsyncKeyState  QuickInfo  Overview  Group

The GetAsyncKeyState function determines whether a key is up or down at the time the function is called, and whether the key was pressed after a previous call to GetAsyncKeyState.

SHORT GetAsyncKeyState(

int  vKey	// virtual-key code
);
Parameters

vKey

Specifies one of 256 possible virtual-key codes.

Windows NT: You can use left- and right-distinguishing constants to specify certain keys. See the Remarks section for further information.

Windows 95: Windows 95 does not support the left- and right-distinguishing constants available on Windows NT.

Return Value

If the function succeeds, the return value specifies whether the key was pressed since the last call to GetAsyncKeyState, and whether the key is currently up or down. If the most significant bit is set, the key is down, and if the least significant bit is set, the key was pressed after the previous call to GetAsyncKeyState. The return value is zero if a window in another thread or process currently has the keyboard focus.

Windows 95: Windows 95 does not support the left- and right-distinguishing constants. If you call GetAsyncKeyState on the Windows 95 platform with these constants, the return value is zero.

Remarks

You can use the virtual-key code constants VK_SHIFT, VK_CONTROL, and VK_MENU as values for the vKey parameter. This gives the state of the SHIFT, CTRL, or ALT keys without distinguishing between left and right.

Windows NT: You can use the following virtual-key code constants as values for vKey to distinguish between the left and right instances of those keys:

VK_LSHIFT	VK_RSHIFT
VK_LCONTROL	VK_RCONTROL
VK_LMENU	VK_RMENU
These left- and right-distinguishing constants are only available when you call the GetKeyboardState, SetKeyboardState, GetAsyncKeyState, GetKeyState, and MapVirtualKey functions.

Windows 95: Windows 95 does not support the left- and right-distinguishing constants, and returns 0 when you use these constants.

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, which may 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.

See Also

GetKeyboardState, GetKeyState, GetSystemMetrics, MapVirtualKey, SetKeyboardState


GetAtomHandle
 GetAtomHandle  Overview  Group

The GetAtomHandle function is not implemented in the Win32 API. This function is provided for compatibility with 16-bit versions of Windows. Win32-based applications should use the GetAtomName function.


GetAtomName
 GetAtomName  QuickInfo  Overview  Group

The GetAtomName function retrieves a copy of the character string associated with the specified local atom. This function replaces the GetAtomHandle function.

UINT GetAtomName(

ATOM  nAtom,	// atom identifying character string
LPTSTR  lpBuffer,	// address of buffer for atom string
int  nSize	// size of buffer
);
Parameters

nAtom

Specifies the local atom that identifies the character string to be retrieved.

lpBuffer

Points to the buffer for the character string.

nSize

Specifies the size, in characters, of the buffer.

Return Value

If the function succeeds, the return value is the length of the string copied to the buffer, in characters, not including the terminating null character.

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

Remarks

The string returned for an integer atom (an atom created by the MAKEINTATOM macro) is a null-terminated string in which the first character is a pound sign (#) and the remaining characters represent the unsigned integer originally passed to MAKEINTATOM.

See Also

AddAtom, DeleteAtom, FindAtom, GlobalAddAtom, GlobalDeleteAtom, GlobalFindAtom, GlobalGetAtomName, MAKEINTATOM


GetBinaryType
 GetBinaryType  QuickInfo  Overview  Group

The GetBinaryType function determines whether a file is executable, and if so, what type of executable file it is. That last property determines which subsystem an executable file runs under.

BOOL GetBinaryType (

LPCTSTR  lpApplicationName,	// points to fully qualified path of file to test
LPDWORD  lpBinaryType	// points to variable to receive binary type information
);
Parameters

lpApplicationName

Points to a null-terminated string that contains the fully qualified path of the file whose binary type the function shall determine.

lpBinaryType

Points to a variable to receive information about the executable type of the file specified by lpApplicationName. The function adjusts a set of bit flags in this variable. The following bit flag constants are defined:

Value	Description
SCS_32BIT_BINARY	A Win32-based application
SCS_DOS_BINARY	An MS-DOS − based application
SCS_OS216_BINARY	A 16-bit OS/2-based application
SCS_PIF_BINARY	A PIF file that executes an MS-DOS − based application
SCS_POSIX_BINARY	A POSIX − based application
SCS_WOW_BINARY	A 16-bit Windows-based application
Return Value

If the file is executable, the return value is TRUE. The function sets the variable pointed to by lpBinaryType to indicate the file's executable type.

If the function is not executable, or if the function fails, the return value is FALSE.


GetBitmapBits
 GetBitmapBits  QuickInfo  Overview  Group

The GetBitmapBits function copies the bitmap bits of a specified bitmap into a buffer.

The GetBitmapBits function is not implemented in the Win32 API. This function is provided for compatibility with 16-bit versions of Windows. Win32-based applications should use the GetDIBits function.

LONG GetBitmapBits(

HBITMAP  hbmp,	// handle to bitmap
LONG  cbBuffer,	// number of bytes to copy to buffer
LPVOID  lpvBits	// address of buffer for bitmap bits
);
Parameters

hbmp

Identifies the bitmap of interest.

cbBuffer

Specifies the number of bytes to be copied.

lpvBits

Points to a buffer to receive the bitmap bits. This is stored as an array of byte values.

Return Value

If the function succeeds, the return value is the actual number of bytes in the bitmap.

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

Remarks

The bits in the destination buffer must be word-aligned. In other words, the buffer must begin at an even address in memory.

See Also

GetDIBits


GetBitmapDimension
 GetBitmapDimension  Overview  Group

The GetBitmapDimension function is not implemented in the Win32 SDK. This function is provided for compatibility with 16-bit versions of Windows. Win32-based applications should use the GetBitmapDimensionEx function.


GetBitmapDimensionEx
 GetBitmapDimensionEx  QuickInfo  Overview  Group

The GetBitmapDimensionEx function retrieves the dimensions of a bitmap. The retrieved dimensions must have been set by the SetBitmapDimensionEx function. The GetMapDimensionEx function replaces the GetMapDimension function.

BOOL GetBitmapDimensionEx(

HBITMAP  hBitmap,	// handle of bitmap
LPSIZE  lpDimension	// address of structure receiving dimensions
);
Parameters

hBitmap

Identifies the bitmap.

lpDimension

Points to a SIZE structure to receive the bitmap dimensions.

Return Value

If the function was successful, the return value is TRUE.

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

Remarks

The function returns a data structure that contains fields for the height and width of the bitmap. If those dimensions have not yet been set, the structure that is returned will have zeroes in those fields.

See Also

SetBitmapDimensionEx, SIZE


GetBkColor
 GetBkColor  QuickInfo  Overview  Group

The GetBkColor function returns the current background color for the specified device context.

COLORREF GetBkColor(

HDC  hdc	// handle of device context
);
Parameters

hdc

Identifies the device context whose background color is to be returned.

Return Value

If the function succeeds, the return value is a COLORREF value for the current background color.

If the function fails, the return value is CLR_INVALID.

See Also

GetBkMode, SetBkColor


GetBkMode
 GetBkMode  QuickInfo  Overview  Group

The GetBkMode function returns the current background mix mode for a specified device context. The background mix mode of a device context affects text, hatched brushes, and pen styles that are not solid lines.

int GetBkMode(

HDC  hdc	// handle to device context of interest
);
Parameters

hdc

Identifies the device context whose background mode is to be returned.

Return Value

If the function succeeds, the return value specifies the current background mix mode, either OPAQUE or TRANSPARENT.

If the function fails, the return value is zero.

See Also

GetBkColor, SetBkMode


GetBoundsRect
 GetBoundsRect  QuickInfo  Overview  Group

The GetBoundsRect function obtains the current accumulated bounding rectangle for a specified device context.

Windows maintains an accumulated bounding rectangle for each application. An application can retrieve and set this rectangle.

UINT GetBoundsRect(

HDC  hdc,	// handle to device context of interest
LPRECT  lprcBounds,	// points to structure to receive bounding rectangle
UINT  flags	// specifies function options
);
Parameters

hdc

Identifies the device context whose bounding rectangle the function will return.

lprcBounds

Points to the RECT structure that will receive the current bounding rectangle. The application's rectangle is returned in logical coordinates, and the Windows rectangle is returned in screen coordinates.

flags

Specifies aspects of how the GetBoundsRect function will operate on a given call. This parameter can be the following value:

Value	Meaning
DCB_RESET	Clears the bounding rectangle after returning it. If this flag is not set, the bounding rectangle will not be cleared.
Return Value

The return value specifies the state of the accumulated bounding rectangle; it can be one of the following values:

Value	Meaning
0	An error occurred. The given device context handle is invalid.
DCB_DISABLE	Boundary accumulation is off.
DCB_ENABLE	Boundary accumulation is on.
DCB_RESET	The bounding rectangle is empty.
DCB_SET	The bounding rectangle is not empty.
Remarks

The DCB_SET value is a combination of the bit values DCB_ACCUMULATE and DCB_RESET. Applications that check the DCB_RESET bit to determine whether the bounding rectangle is empty must also check the DCB_ACCUMULATE bit. The bounding rectangle is empty only if the DCB_RESET bit is 1 and the DCB_ACCUMULATE bit is 0.

See Also

SetBoundsRect


 GetBrushOrg

The GetBrushOrg function is not implemented in the Win32 API. This function is provided for compatibility with 16-bit versions of Windows. Win32-based applications should use the GetBrushOrgEx function.


GetBrushOrgEx
 GetBrushOrgEx  QuickInfo  Overview  Group

The GetBrushOrgEx function retrieves the current brush origin for the specified device context. This function replaces the GetBrushOrg function.

BOOL GetBrushOrgEx(

HDC  hdc,	// handle of device context
LPPOINT  lppt	// address of structure of coordinates
);
Parameters

hdc

Identifies the device context.

lppt

Points to a POINT structure that receives the brush origin, in device coordinates.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

A brush is a bitmap that Windows uses to paint the interiors of filled shapes.

The brush origin is a set of coordinates with values between 0 and 7, specifying the location of one pixel in the bitmap. The default brush origin coordinates are (0,0). For horizontal coordinates, the value 0 corresponds to the leftmost column of pixels; the value 7 corresponds to the rightmost column. For vertical coordinates, the value 0 corresponds to the uppermost row of pixels; value 7 corresponds to the lowermost row. When Windows positions the brush at the start of any painting operation, it maps the origin of the brush to the location in the window's client area specified by the brush origin. For example, if the origin is set to (2,3), Windows maps the origin of the brush (0,0) to the location (2,3) on the window's client area.

If an application uses a brush to fill the backgrounds of both a parent and a child window with matching colors, it may be necessary to set the brush origin after painting the parent window but before painting the child window.

Windows NT: The operating system automatically tracks the origin of all window-managed device contexts and adjusts their brushes as necessary to maintain an alignment of patterns on the surface.

Windows 95: Automatic tracking of the brush origin is not supported. Applications must use the UnrealizeObject, SetBrushOrgEx, and SelectObject functions to align the brush before using it.

See Also

POINT, SelectObject, SetBrushOrgEx, UnrealizeObject


GetCapture
 GetCapture  QuickInfo  Overview  Group

The GetCapture function retrieves the handle of the window (if any) that has captured the mouse. Only one window at a time can capture the mouse; this window receives mouse input whether or not the cursor is within its borders.

HWND GetCapture(VOID)

Parameters

This function has no parameters.

Return Value

If the function succeeds, the return value is the handle of the capture window associated with the current thread. If no window in the thread has captured the mouse, the return value is NULL.

Remarks

A NULL return value does not mean no other thread or process in the system has captured the mouse; it just means the current thread has not captured the mouse.

See Also

ReleaseCapture, SetCapture


GetCaretBlinkTime
 GetCaretBlinkTime  QuickInfo  Overview  Group

The GetCaretBlinkTime function returns the elapsed time, in milliseconds, required to invert the caret's pixels.

UINT GetCaretBlinkTime(VOID)

Parameters

This function has no parameters.

Return Value

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.

See Also

SetCaretBlinkTime


GetCaretPos
 GetCaretPos  QuickInfo  Overview  Group

The GetCaretPos function copies the caret's position, in client coordinates, to the specified POINT structure.

BOOL GetCaretPos(

LPPOINT  lpPoint	// address of structure to receive coordinates
);
Parameters

lpPoint

Points to the POINT structure that is to receive the client coordinates of the caret.

Return Value

If the function succeeds, the return value is TRUE

If the function fails, the return value is FALSE. 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.

See Also

SetCaretPos, POINT


GetCharABCWidths
 GetCharABCWidths  QuickInfo  Overview  Group

The GetCharABCWidths function retrieves the widths, in logical units, of consecutive characters in a given range from the current TrueType font. This function succeeds only with TrueType fonts.

BOOL GetCharABCWidths(

HDC  hdc,	// handle of device context
UINT  uFirstChar,	// first character in range to query
UINT  uLastChar,	// last character in range to query
LPABC  lpabc	// address of character-width structure
);
Parameters

hdc

Identifies the device context.

uFirstChar

Specifies the first character in the group of consecutive characters from the current font.

uLastChar

Specifies the last character in the group of consecutive characters from the current font.

lpabc

Points to an array of ABC structures that receive the character widths when the function returns. This array must contain at least as many ABC structures as there are characters in the range specified by the uFirstChar and uLastChar parameters.

Return Value

If the function succeeds, the return value is TRUE

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

Remarks

The TrueType rasterizer provides ABC character spacing after a specific point size has been selected. "A" spacing is the distance added to the current position before placing the glyph. "B" spacing is the width of the black part of the glyph. "C" spacing is the distance added to the current position to provide white space to the right of the glyph. The total advanced width is given by A+B+C.

When the GetCharABCWidths function retrieves negative "A" or "C" widths for a character, that character includes underhangs or overhangs.

To convert the ABC widths to font design units, an application should use the value stored in the otmEMSquare member of a OUTLINETEXTMETRIC structure. This value can be retrieved by calling the GetOutlineTextMetrics function.

The ABC widths of the default character are used for characters outside the range of the currently selected font.

To retrieve the widths of characters in non-TrueType fonts, applications should use the GetCharWidth function.

See Also

GetCharWidth, GetOutlineTextMetrics, OUTLINETEXTMETRIC, ABC


GetCharABCWidthsFloat
 GetCharABCWidthsFloat  QuickInfo  Overview  Group

The GetCharABCWidthsFloat function retrieves the widths, in logical units, of consecutive characters in a specified range from the current font.

BOOL GetCharABCWidthsFloat(

HDC  hdc,	// handle of device context
UINT  iFirstChar,	// first character in range to query
UINT  iLastChar,	// last character in range to query
LPABCFLOAT  lpABCF	// address of character-width structure
);
Parameters

hdc

Identifies the device context.

iFirstChar

Specifies the code point of the first character in the group of consecutive characters where the ABC widths are sought.

iLastChar

Specifies the code point of the last character in the group of consecutive characters where the ABC widths are sought. This range is inclusive. An error is returned if the specified last character precedes the specified first character.

lpABCF

Points to an application-defined buffer with an array of ABCFLOAT structures to receive the character widths when the function returns.

Return Value

If the function succeeds, the return value is TRUE

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

Remarks

Unlike the GetCharABCWidths function that returns widths only for TrueType fonts, the GetCharABCWidthsFloat function retrieves widths for any font. The widths returned by this function are in the IEEE floating-point format.

If the current world-to-device transformation is not identified, the returned widths may be noninteger values, even if the corresponding values in the device space are integers.

"A" spacing is the distance added to the current position before placing the glyph. "B" spacing is the width of the black part of the glyph. "C" spacing is the distance added to the current position to provide white space to the right of the glyph. The total advanced width is given by A+B+C.

The ABC spaces are measured along the character base line of the selected font.

The ABC widths of the default character are used for characters outside the range of the currently selected font.

See Also

ABCFLOAT, GetCharABCWidths, GetCharWidth, GetCharWidthFloat


GetCharacterPlacement [New - Windows 95]
 GetCharacterPlacement  QuickInfo  Overview  Group

[New - Windows 95]

The GetCharacterPlacement function retrieves information about a character string, such as character widths, caret positioning, ordering within the string, and glyph rendering. The type of information returned depends on the dwFlags parameter and is based on the currently selected font in the given display context. The function copies the information to the specified GCP_RESULTS structure or to one or more arrays specified by the structure.

DWORD GetCharacterPlacement(

HDC  hdc,	// handle to device context
LPCTSTR  lpString,	// pointer to string
int  nCount,	// number of characters in string
int  nMaxExtent,	// maximum extent for displayed string
LPGCP_RESULTS  *lpResults,	// pointer to buffer for placement result
DWORD  dwFlags	// placement flags
);
Parameters

hdc

Identifies the device context.

lpString

Points to the character string to process.

nCount

Specifies the number of characters in the string.

nMaxExtent

Specifies the maximum extent (in logical units) to which the string is processed. Characters that, if processed, would exceed this extent are ignored. Computations for any required ordering or glyph arrays apply only to the included characters. This parameter is used only if the GCP_MAXEXTENT value is given in the dwFlags parameter. As the function processes the input string, each character and its extent is added to the output, extent, and other arrays only if the total extent has not yet exceeded the maximum. Once the limit is reached, processing will stop.

lpResults

Points to a GCP_RESULTS structure that receives the results of the function.

dwFlags

Specifies how to process the string into the required arrays. This parameter can be one or more of the following values:

Value	Meaning
GCP_CLASSIN	Specifies that the lpClass array contains preset classifications for characters. The classifications may be the same as on output. If the particular classification for a character is not known, the corresponding location in the array must be set to zero. for more information about the classifications, see GCP_RESULTS. This is useful only if GetFontLanguageInfo returned the GCP_REORDER flag.
GCP_DIACRITIC	Determines how diacritics in the string are handled. If this value is not set, diacritics are treated as zero-width characters. For example, a Hebrew string may contain diacritics, but you may not want to display them.  Use GetFontLanguageInfo to determine whether a font supports diacritics. If it does, you can use or not use the GCP_DIACRITIC flag in the call to GetCharacterPlacement, depending on the needs of your application.
GCP_DISPLAYZWG	For languages that need reordering or different glyph shapes depending on the positions of the characters within a word, nondisplayable characters often appear in the codepage. For example, in the Hebrew codepage, there are Left-To-Right and Right-To-Left markers, to help determine the final positioning of characters within the output strings. Normally these are not displayed and are removed from the lpGlyphs and lpDx arrays. You can use the GCP_DISPLAYZWG flag to display these characters.
GCP_GLYPHSHAPE	Specifies that some or all characters in the string are to be displayed using shapes other than the standard shapes defined in the currently selected font for the current code page. Some languages, such as Arabic, cannot support glyph creation unless this value is given. As a general rule, if GetFontLanguageInfo returns this value for a string, this value must be used with GetCharacterPlacement.
GCP_JUSTIFY	Adjusts the extents in the lpDx array so that the string length is the same as nMaxExtent. GCP_JUSTIFY may only be used in conjunction with GCP_MAXEXTENT.
GCP_JUSTIFYIN	Specifies that the lpDx array contains justification weights on input. Normally, a justification weight can be either 0 or 1, where 1 indicates that the width of the given character can be adjusted for justification. For languages in which GetFontLanguageInfo returns the GCP_KASHIDA flag, the justification weight can be one of the GCP_ARAJUST_* values.
GCP_KASHIDA	Use Kashidas as well as, or instead of, adjusted extents to modify the length of the string so that it is equal to the value given by nMaxExtent. In the lpDx array, a Kashida is indicated by a negative justification index. GCP_KASHIDA may be used only in conjunction with GCP_JUSTIFY and only if the font (and language) support Kashidas. Use GetFontLanguageInfo to determine whether the current font supports Kashidas. Using Kashidas to justifiy the string can result in the number of glyphs required being greater than the number of characters in the input string. Because of this, when Kashidas are used, the application cannot assume that setting the arrays to be the size of the input string will be sufficient. (The maximum possible will be approximately dxPageWidth/dxAveCharWidth, where dxPageWidth is the width of the document and dxAveCharWidth is the average character width as returned from a GetTextMetrics call). Note that just because GetFontLanguageInfo returns the GCP_KASHIDA flag does not mean that it has to be used in the call to GetCharacterPlacement, just that the option is available.
GCP_LIGATE	Use ligations wherever characters ligate. A ligation occurs where one glyph is used for two or more characters. For example, the letters "a" and "e" can ligate to "æ". For this to be used, however , both the language support and the font must support the required glyphs (the example given will NOT be processed by default in English).  Use GetFontLanguageInfo to determine whether the current font supports ligation. If it does and a specific maximum is required for the number of characters that will ligate, set the number in the first element of the lpGlyphs array. If normal ligation is required, set this value to zero. If GCP_LIGATE is not given, no ligation will take place. See GCP_RESULTS for more information. If the GCP_REORDER value is usually required for the character set but is not given, the output will be meaningless unless the string being passed in is already in visual ordering (that is, the result that gets put into lpGcpResults->lpOutString in one call to GetCharacterPlacement is the input string of a second call).  Note that just because GetFontLanguageInfo returns the GCP_LIGATE flag does not mean that it has to be used in the call to GetCharacterPlacement, just that the option is available.
GCP_MAXEXTENT	Compute extents of the string only as long as the resulting extent, in logical units, does not exceed the values given by the nMaxExtent parameter.
GCP_NEUTRALOVERRIDE	Certain languages only. Override the normal handling of neutrals and treat them as strong characters that match the strings reading order. Useful only with the GCP_REORDER flag.
GCP_NUMERICOVERRIDE	Certain languages only. Override the normal handling of numerics and treat them as strong characters that match the strings reading order. Useful only with the GCP_REORDER flag.
GCP_NUMERICSLATIN	Arabic/Thai only. Use standard Latin glyphs for numbers and override the system default. To determine if this option is available in the language of the font, use GetStringTypeEx to see if the language supports more than one number format.
GCP_NUMERICSLOCAL	Arabic/Thai only. Use local glyphs for numeric characters and override the system default. To determine if this option is available in the language of the font, use GetStringTypeEx to see if the language supports more than one number format.
GCP_REORDER	Reorder the string. Use for languages that are not SBCS and left-to-right reading order. If this value is not given, the string is assumed to be in display order already.  If this flag is set for Semitic languages and the lpClass array is used, the first two elements of the array are used to specify the reading order beyond the bounds of the string. GCP_CLASS_PREBOUNDRTL and GCP_CLASS_PREBOUNDLTR can be used to set the order. If no preset order is required, set the values to zero. These values can be combined with other values if theGCPCLASSIN flag is set. If the GCP_REORDER value is not given, the lpString parameter is taken to be visual ordered for languages where this is used, and the lpOutString and lpOrder fields are ignored. Use GetFontLanguageInfo to determine whether the current font supports reordering.
GCP_SYMSWAPOFF	Semitic languages only. Specifies that swappable characters are not reset. For example, in a right-to-left string, the '(' and ')' are not reversed.
GCP_USEKERNING	Use kerning pairs in the font (if any) when creating the widths arrays. Use GetFontLanguageInfo to determine whether the current font supports kerning pairs. Note that just because GetFontLanguageInfo returns the GCP_USEKERNING flag does not mean that it has to be used in the call to GetCharacterPlacement, just that the option is available. Most TrueType fonts have a kerning table, but you do not have to use it.
It is recommended that an application use the GetFontLanguageInfo function to determine whether the GCP_DIACRITIC, GCP_DBCS, GCP_USEKERNING, GCP_LIGATE, GCP_REORDER, GCP_GLYPHSHAPE, and GCP_KASHIDA values are valid for the currently selected font. If not valid, GetCharacterPlacement ignores the value.

The GCP_NODIACRITICS value is no longer defined and should not be used.

Return Value

If the function succeeds, the return value is the same as the return value from GetTextExtentPoint32, the width and height of the string.

If the function fails, the return value is zero.

Remarks

GetCharacterPlacement ensures that an application can correctly process text regardless of the international setting and type of fonts available. Applications use this function before using the ExtTextOut function and in place of the GetTextExtentPoint32 function (and occasionally in place of the GetCharWidth32 and GetCharABCWidths functions).

Using GetCharacterPlacement to retrieve intercharacter spacing and index arrays is not always necessary unless justification or kerning is required. For non-Latin fonts, applications can improve the speed at which the ExtTextOut function renders text by using GetCharacterPlacement to retrieve the intercharacter spacing and index arrays before calling ExtTextOut. This is especially useful when rendering the same text repeatedly or when using intercharacter spacing to position the caret. If the lpGlyphs output array is used in the call to ExtTextOut, the ETO_GLYPH_INDEX flag must be set.

GetCharacterPlacement checks the lpOrder, lpDx, lpCaretPos, lpOutString, and lpGlyphs members of the GCP_RESULTS structure and fills the corresponding arrays if these members are not set to NULL. If GetCharacterPlacement cannot fill an array, it sets the corresponding member to NULL. To ensure retrieval of valid information, the application is responsible for setting the member to a valid address before calling the function and for checking the value of the member after the call. If the GCP_JUSTIFY or GCP_USEKERNING values are given, the lpDx and/or lpCaretPos members must have valid addresses. Also, the lpDx member must have a valid address if GCP_JUSTIFYIN is given.

When computing justification, if the trailing characters in the string are spaces, the function reduces the length of the string and removes the spaces prior to computing the justification. If the array consists of only spaces, the function returns an error.

See Also

ExtTextOut, GCP_RESULTS, GetCharABCWidths, GetCharWidth32, GetFontLanguageInfo, GetStringTypeEx, GetTextExtentPoint32, GetTextMetrics


GetCharWidth
 GetCharWidth  QuickInfo  Overview  Group

The GetCharWidth function retrieves the widths, in logical coordinates, of consecutive characters in a specified range from the current font.

GetCharWidth is maintained for compatibility with 16-bit versions of Windows. Win32-based applications should call the GetCharWidth32 function, which provides more accurate results.

BOOL GetCharWidth(

HDC  hdc,	// handle of device context
UINT  iFirstChar,	// first character in range to query
UINT  iLastChar,	// last character in range to query
LPINT  lpBuffer	// address of buffer for widths
);
Parameters

hdc

Identifies the device context.

iFirstChar

Specifies the first character in the group of consecutive characters.

iLastChar

Specifies the last character in the group of consecutive characters, which must not precede the specified first character.

lpBuffer

Points to a buffer to receive the widths.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The range is inclusive; that is, the returned widths include the widths of the characters specified by the iFirstChar and iLastChar parameters.

If a character does not exist in the current font, it is assigned the width of the default character.

See Also

GetCharABCWidths, GetCharABCWidthsFloat, GetCharWidth32, GetCharWidthFloat


GetCharWidth32
 GetCharWidth32  QuickInfo  Overview  Group

The GetCharWidth32 function retrieves the widths, in logical coordinates, of consecutive characters in a specified range from the current font. This function supersedes the GetCharWidth function.

BOOL GetCharWidth32(

HDC  hdc,	// handle of device context
UINT  iFirstChar,	// first character in range to query
UINT  iLastChar,	// last character in range to query
LPINT  lpBuffer	// address of buffer for widths
);
Parameters

hdc

Identifies the device context.

iFirstChar

Specifies the first character in the group of consecutive characters.

iLastChar

Specifies the last character in the group of consecutive characters, which must not precede the specified first character.

lpBuffer

Points to a buffer to receive the widths.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The range is inclusive; that is, the returned widths include the widths of the characters specified by the iFirstChar and iLastChar parameters.

If a character does not exist in the current font, it is assigned the width of the default character.

See Also

GetCharABCWidths, GetCharABCWidthsFloat, GetCharWidth, GetCharWidthFloat


GetCharWidthFloat
 GetCharWidthFloat  QuickInfo  Overview  Group

The GetCharWidthFloat function retrieves the fractional widths of consecutive characters in a specified range from the current font.

BOOL GetCharWidthFloat(

HDC  hdc,	// handle of device context
UINT  iFirstChar,	// first-character code point
UINT  iLastChar,	// last-character code point
PFLOAT  pxBuffer	// address of buffer that receives width-values
);
Parameters

hdc

Identifies the device context.

iFirstChar

Specifies the code point of the first character in the group of consecutive characters.

iLastChar

Specifies the code point of the last character in the group of consecutive characters.

pxBuffer

Points to a buffer to receive the character widths.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The returned widths are in the 32-bit IEEE floating-point format. (The widths are measured along the base line of the characters.)

If the iFirstChar parameter identifies the letter a and the iLastChar parameter identifies the letter z, GetCharWidthFloat retrieves the widths of all lowercase characters.

If a character does not exist in the current font, it is assigned the width of the default character.

See Also

GetCharABCWidths, GetCharABCWidthsFloat, GetCharWidth32


GetClassInfo
 GetClassInfo  QuickInfo  Overview  Group

The GetClassInfo function retrieves information about a window class.

BOOL GetClassInfo(

HINSTANCE  hInstance,	// handle of application instance
LPCTSTR  lpClassName,	// address of class name string
LPWNDCLASS  lpWndClass	// address of structure for class data
);
Parameters

hInstance

Identifies the instance of the application that created the class. To retrieve information about classes defined by Windows (such as buttons or list boxes), set this parameter to NULL.

lpClassName

Points to a null-terminated string containing the class name. The name must be that of a preregistered class or a class registered by a previous call to the RegisterClass function. Alternatively, this parameter can be an integer atom. If so, it must be a global atom created by a previous call to the GlobalAddAtom function. The atom, a 16-bit value less than 0xC000, must be in the low-order word of lpClassName; the high-order word must be zero.

lpWndClass

Points to a WNDCLASS structure that receives the information about the class.

Return Value

If the function finds a matching class and successfully copies the data, the return value is TRUE.

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

See Also

GetClassLong, GetClassName, GetClassWord, GlobalAddAtom, RegisterClass, WNDCLASS


GetClassInfoEx
 GetClassInfoEx  QuickInfo  Overview  Group

The GetClassInfoEx function retrieves information about a window class, including the handle of the small icon associated with the window class. GetClassInfo does not retrieve the handle of the small icon.

BOOL GetClassInfoEx(

HINSTANCE  hinst,	// handle of application instance
LPCTSTR  lpszClass,	// address of class name string
LPWNDCLASSEX  lpwcx,	// address of structure for class data
);
Parameters

hinst

Identifies the instance of the application that created the class. To retrieve information about classes defined by Windows (such as buttons or list boxes), set this parameter to NULL.

lpszClass

Points to a null-terminated string containing the class name. The name must be that of a preregistered class or a class registered by a previous call to the RegisterClass function. Alternatively, this parameter can be an integer atom. If this parameter is an integer atom, it must be a global atom created by a previous call to the GlobalAddAtom function. The atom, a 16-bit value less than 0xC000, must be in the low-order word of lpszClass; the high-order word must be zero.

lpwcx

Points to a WNDCLASSEX structure that receives the information about the class.

Windows NT: With Windows NT the hIconSm member of the WNDCLASSEX structure is always NULL.

Return Value

If the function finds a matching class and successfully copies the data, the return value is TRUE; otherwise, it is FALSE. To get extended error information, call GetLastError.

See Also

GetClassLong, GetClassName, GetClassWord, GlobalAddAtom, RegisterClassEx


GetClassLong
 GetClassLong  QuickInfo  Overview  Group

The GetClassLong function retrieves the specified 32-bit (long) value from the WNDCLASS structure associated with the specified window.

DWORD GetClassLong(

HWND  hWnd,	// handle of window
int  nIndex	// offset of value to retrieve
);
Parameters

hWnd

Identifies the window and, indirectly, the class to which the window belongs.

nIndex

Specifies the 32-bit value to retrieve. To retrieve a 32-bit value from the extra class memory, specify the positive, zero-based byte offset of the value to be retrieved. Valid values are in the range zero through the number of bytes of extra class memory, minus four; for example, if you specified 12 or more bytes of extra class memory, a value of 8 would be an index to the third 32-bit integer. To retrieve any other value from the WNDCLASS 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 RegisterClass 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 and GetWindowWord .
GCL_HBRBACKGROUND	Retrieves the handle of the background brush associated with the class.
GCL_HCURSOR	Retrieves the handle of the cursor associated with the class.
GCL_HICON	Retrieves the handle of the icon associated with the class.
GCL_HICONSM	Windows 95: Retrieves the handle of the small icon associated with the class. Windows NT: This constant is not valid for Windows NT.
GCL_HMODULE	Retrieves the handle of the module that registered the class.
GCL_MENUNAME	Retrieves the address of the menu name string. The string identifies the menu resource associated with the class.
GCL_STYLE	Retrieves the window-class style bits.
GCL_WNDPROC	Retrieves the address of the window procedure associated with the class.
Return Value

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 WNDCLASS structure used with the RegisterClass function.

See Also

GetClassWord, GetWindowLong, GetWindowWord, RegisterClass, SetClassLong, SetClassWord, WNDCLASS


GetClassName
 GetClassName  QuickInfo  Overview  Group

The GetClassName function retrieves the name of the class to which the specified window belongs.

int GetClassName(

HWND  hWnd,	// handle of window
LPTSTR  lpClassName,	// address of buffer for class name
int  nMaxCount	// size of buffer, in characters
);
Parameters

hWnd

Identifies the window and, indirectly, the class to which the window belongs.

lpClassName

Points to the buffer that is to receive the class name string.

nMaxCount

Specifies the length, in characters, of the buffer pointed to by the lpClassName parameter. The class name string is truncated if it is longer than the buffer.

Return Value

If the function succeeds, the return value is the number of characters copied to the specified buffer.

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

See Also

FindWindow, GetClassInfo, GetClassLong, GetClassWord


GetClassWord
 GetClassWord  QuickInfo  Overview  Group

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.

WORD GetClassWord(

HWND  hWnd,	// handle of window
int  nIndex	// offset of value to retrieve
);
Parameters

hWnd

Identifies the window and, indirectly, the class to which the window belongs.

nIndex

Specifies the zero-based byte offset of the value to be retrieved. Valid values are in the range zero through the number of bytes of class memory, minus two; for example, if you specified 10 or more bytes of extra class memory, a value of eight would be an index to the fifth 16-bit integer. There is an additional valid value:

Value	Action
GCW_ATOM	Retrieves an ATOM value that uniquely identifies the window class. This is the same atom that the RegisterClass function returns.
GCW_HICONSM	Windows 95: Retrieves the handle of the small icon associated with the window. Windows NT: This constant is not valid for Windows NT.
Return Value

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.

Other than GCW_ATOM and GCW_HICONSM, the GCW_ values are obsolete in the Win32 API. You must use the GetClassLong function to retrieve the class values of a window.

See Also

GetClassLong, RegisterClass, SetClassLong, SetClassWord, WNDCLASS


GetClientRect
 GetClientRect  QuickInfo  Overview  Group

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 of window
LPRECT  lpRect	// address of structure for client coordinates
);
Parameters

hWnd

Identifies the window whose client coordinates are to be retrieved.

lpRect

Points 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 Value

If the function succeeds, the return value is TRUE.

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

See Also

GetWindowRect, RECT


GetClipboardData
 GetClipboardData  QuickInfo  Overview  Group

The GetClipboardData function retrieves data from the clipboard in a specified format. The clipboard must have been opened previously.

HANDLE GetClipboardData(

UINT  uFormat	// clipboard format
);
Parameters

uFormat

Specifies a clipboard format. For a description of the clipboard formats, see the SetClipboardData function.

Return Value

If the function succeeds, the return value is the handle of a clipboard object in the specified format.

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

Remarks

An application can enumerate the available formats in advance by using the EnumClipboardFormats function.

The clipboard controls the handle that the GetClipboardData function returns, not the application. The application should copy the data immediately. The application cannot rely on being able to make long-term use of the handle. The application must not free the handle nor leave it locked.

The operating system performs implicit data format conversions between certain clipboard formats when an application calls the GetClipboardData function. For example, if the CF_OEMTEXT format is on the clipboard, a window can retrieve data in the CF_TEXT format. The format on the clipboard is converted to the requested format on demand. The following table shows the clipboard data type conversions that are available. Note that some of these automatic type conversions are not available on all platforms.

Clipboard Format	Conversion Format	Platform Support
CF_BITMAP	CF_DIB	Windows 95
CF_DIB	CF_BITMAP	Windows 95
CF_DIB	CF_PALETTE	Windows 95
CF_ENHMETAFILE	CF_METAFILEPICT	Windows 95, Windows NT
CF_METAFILEPICT	CF_ENHMETAFILE	Windows 95, Windows NT
CF_OEMTEXT	CF_TEXT	Windows 95, Windows NT
CF_OEMTEXT	CF_UNICODETEXT	Windows NT
CF_TEXT	CF_OEMTEXT	Windows 95, Windows NT
CF_TEXT	CF_UNICODETEXT	Windows NT
CF_UNICODETEXT	CF_OEMTEXT	Windows NT
CF_UNICODETEXT	CF_TEXT	Windows NT
If the operating system provides an automatic type conversion for a particular clipboard format, there is no advantage to placing the conversion format(s) on the clipboard.

If the system provides an automatic type conversion for a particular clipboard format, and you call EnumClipboardFormats to enumerate the clipboard data formats, the operating system first enumerates the format that is on the clipboard, followed by the formats to which it can be converted.

If the clipboard contains data in the CF_PALETTE format, the application should use the SelectPalette and RealizePalette functions to realize any other data in the clipboard against that logical palette.

See SetClipboardData for further information on specific clipboard data formats.

See Also

EnumClipboardFormats, SetClipboardData, RealizePalette, SelectPalette


GetClipboardFormatName
 GetClipboardFormatName  QuickInfo  Overview  Group

The GetClipboardFormatName function retrieves from the clipboard the name of the specified registered format. The function copies the name to the specified buffer.

int GetClipboardFormatName(

UINT  format,	// clipboard format to retrieve
LPTSTR  lpszFormatName,	// address of buffer for name
int  cchMaxCount	// length of name string in characters
);
Parameters

format

Specifies the type of format to be retrieved. This parameter must not specify any of the predefined clipboard formats.

lpszFormatName

Points to the buffer that is to receive the format name.

cchMaxCount

Specifies the maximum length, in characters, of the string to be copied to the buffer. If the name exceeds this limit, it is truncated.

Return Value

If the function succeeds, the return value is the length, in characters, of the string copied to the buffer.

If the function fails, the return value is zero, indicating that the requested format does not exist or is predefined. To get extended error information, call GetLastError.

See Also

EnumClipboardFormats, RegisterClipboardFormat


GetClipboardOwner
 GetClipboardOwner  QuickInfo  Overview  Group

The GetClipboardOwner function retrieves the window handle of the current owner of the clipboard.

HWND GetClipboardOwner(VOID)

Parameters

This function has no parameters.

Return Value

If the function succeeds, the return value is the handle of the window that owns the clipboard.

If the clipboard is not owned, the return value is NULL. To get extended error information, call GetLastError.

Remarks

The clipboard can still contain data even if the clipboard is not currently owned.

In general, the clipboard owner is the window that last placed data in clipboard. The EmptyClipboard function assigns clipboard ownership.

See Also

EmptyClipboard, GetClipboardViewer


GetClipboardViewer
 GetClipboardViewer  QuickInfo  Overview  Group

The GetClipboardViewer function retrieves the handle of the first window in the clipboard viewer chain.

HWND GetClipboardViewer(VOID)

Parameters

This function has no parameters.

Return Value

If the function succeeds, the return value is the handle of the first window in the clipboard viewer chain.

If there is no clipboard viewer, the return value is NULL. To get extended error information, call GetLastError.

See Also

GetClipboardOwner, SetClipboardViewer


GetClipBox
 GetClipBox  QuickInfo  Overview  Group

The GetClipBox function retrieves the dimensions of the tightest bounding rectangle that can be drawn around the current visible area on the device. The visible area is defined by the current clipping region or clip path, as well as any overlapping windows.

int GetClipBox(

HDC  hdc,	// handle of the device context
LPRECT  lprc	// address of structure with rectangle
);
Parameters

hdc

Identifies the device context.

lprc

Points to a RECT structure that is to receive the rectangle dimensions.

Return Value

If the function succeeds, the return value specifies the clipping box's complexity and can be any one of the following values:

Value	Meaning
NULLREGION	Region is empty.
SIMPLEREGION	Region is a single rectangle.
COMPLEXREGION	Region is more than one rectangle.
ERROR	An error occurred.
GetClipBox returns logical coordinates based on the given device context.

See Also

RECT


GetClipCursor
 GetClipCursor  QuickInfo  Overview  Group

The GetClipCursor function retrieves the screen coordinates of the rectangular area to which the cursor is confined.

BOOL GetClipCursor(

LPRECT  lpRect	// address of structure for rectangle
);
Parameters

lpRect

Points 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 Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. 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.

See Also

ClipCursor, GetCursorPos, RECT


GetClipRgn
 GetClipRgn  QuickInfo  Overview  Group

The GetClipRgn function retrieves a handle identifying the current application-defined clipping region for the specified device context.

int GetClipRgn(

HDC  hdc,	// handle of device context
HRGN  hrgn	// handle of region
);
Parameters

hdc

Identifies the device context.

hrgn

Identifies an existing region before the function is called. After the function returns, this parameter identifies a copy of the current clipping region.

Return Value

If the function succeeds and there is no clipping region for the given device context, the return value is zero. If the function succeeds and there is a clipping region for the given device context, the return value is 1. If an error occurs, the return value is − 1.

Remarks

An application-defined clipping region is a clipping region identified by the SelectClipRgn function. It is not a clipping region created when the application calls the BeginPaint function.

If the function succeeds, the hrgn parameter identifies a copy of the current clipping region. Subsequent changes to this copy will not affect the current clipping region.

See Also

BeginPaint, SelectClipRgn


GetCodeHandle
 GetCodeHandle  Overview  Group

The GetCodeHandle function is not implemented in the Win32 API. Win32-based applications should use the VirtualLock and VirtualUnlock functions.


GetCodeInfo
 GetCodeInfo  Overview  Group

The GetCodeInfo function is not implemented in the WIN32 SDK. This function is included for compatability with 16-bit versions of Windows.


GetColorAdjustment
 GetColorAdjustment  QuickInfo  Overview  Group

The GetColorAdjustment function retrieves the color adjustment values for the specified device context.

BOOL GetColorAdjustment(

HDC  hdc,	// handle of device context
LPCOLORADJUSTMENT  lpca	// address of COLORADJUSTMENT structure
);
Parameters

hdc

Identifies the device context.

lpca

Points to a COLORADJUSTMENT structure that receives the color adjustment values.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

SetColorAdjustment, COLORADJUSTMENT


GetColorSpace [New - Windows 95]
 GetColorSpace  QuickInfo  Overview  Group

[New - Windows 95]

The GetColorSpace function retrieves the current handle to the logical color space from the specified device context.

HANDLE GetColorSpace(

HDC  hdc
);
Parameters

hdc

Handle to a device context.

Return Value

If the function succeeds, the return value is the current handle to the logical color space.

If the function fails, the return value is NULL.


GetCommandLine
 GetCommandLine  QuickInfo  Overview  Group

The GetCommandLine function returns a pointer to the command-line string for the current process.

LPTSTR GetCommandLine(VOID)

Parameters

This function has no parameters.

Return Value

The return value is a pointer to the command-line string for the current process.

Remarks

Non-Unicode console processes written in C can use the argc and argv arguments to access the command-line arguments. The parameters of the command-line string, excluding the program name, are also available to such non-Unicode applications as a parameter of the WinMain function. The reason for the Unicode exclusion from these options is that WinMain, argc, and argv use the LPSTR data type for parameters, not the LPTSTR datatype.

See Also

CreateProcess, WinMain


GetCommConfig [New - Windows 95]
 GetCommConfig  QuickInfo  Overview  Group

[New - Windows 95]

The GetCommConfig function gets the current configuration of a communications device.

BOOL GetCommConfig(

HANDLE hCommDev,	// handle of communications service
LPCOMMCONFIG lpCC,	// address of comm.configuration structure
LPDWORD lpdwSize	// address of size of buffer
);
Parameters

hCommDev

Identifies the open communications device.

lpCC

Points to the buffer that receives the COMMCONFIG structure.

lpdwSize

Points to a 32-bit variable that specifies the size, in bytes, of the buffer pointed to by lpCC. When the function returns, the variable contains the number of bytes copied if the function succeeds, or the number of bytes required if the buffer was too small.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To get extended error information, use the GetLastError function.

Remarks

An application can determine the maximum size of a device's configuration structure by calling the GetCommProperties function.

See Also

COMMCONFIG, GetCommProperties


GetCommMask
 GetCommMask  QuickInfo  Overview  Group

The GetCommMask function retrieves the value of the event mask for a specified communications device.

BOOL GetCommMask(

HANDLE  hFile,	// handle of communications device
LPDWORD  lpEvtMask	// address of variable to get event mask
);
Parameters

hFile

Identifies the communications device. The CreateFile function returns this handle.

lpEvtMask

Points to the 32-bit variable to be filled with a mask of events that are currently enabled. This parameter can be one or more of the following values:

Value	Meaning
EV_BREAK	A break was detected on input.
EV_CTS	The CTS (clear-to-send) signal changed state.
EV_DSR	The DSR (data-set-ready) signal changed state.
EV_ERR	A line-status error occurred. Line-status errors are CE_FRAME, CE_OVERRUN, and CE_RXPARITY.
EV_EVENT1	An event of the first provider-specific type occured.
EV_EVENT2	An event of the second provider-specific type occured.
EV_PERR	A printer error occured.
EV_RING	A ring indicator was detected.
EV_RLSD	The RLSD (receive-line-signal-detect) signal changed state.
EV_RX80FULL	The receive buffer is 80 percent full.
EV_RXCHAR	A character was received and placed in the input buffer.
EV_RXFLAG	The event character was received and placed in the input buffer. The event character is specified in the device's DCB structure, which is applied to a serial port by using the SetCommState function.
EV_TXEMPTY	The last character in the output buffer was sent.
Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The GetCommMask function uses a 32-bit mask variable to indicate the set of events that can be monitored for a particular communications resource. A handle to the communications resource can be specified in a call to the WaitCommEvent function, which waits for one of the events to occur. To modify the event mask of a communications resource, use the SetCommMask function.

See Also

CreateFile, DCB, SetCommMask, WaitCommEvent,


GetCommModemStatus
 GetCommModemStatus  QuickInfo  Overview  Group

The GetCommModemStatus function retrieves modem control-register values.

BOOL GetCommModemStatus(

HANDLE  hFile,	// handle of communications device
LPDWORD  lpModemStat	// address of control-register values
);
Parameters

hFile

Identifies the communications device. The CreateFile function returns this handle.

lpModemStat

Points to a 32-bit variable that specifies the current state of the modem control-register values. This parameter can be a combination of the following values:

Value	Meaning
MS_CTS_ON	The CTS (clear-to-send) signal is on.
MS_DSR_ON	The DSR (data-set-ready) signal is on.
MS_RING_ON	The ring indicator signal is on.
MS_RLSD_ON	The RLSD (receive-line-signal-detect) signal is on.
Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The GetCommModemStatus function is useful when you are using the WaitCommEvent function to monitor the CTS, RLSD, DSR, or ring indicator signals. To detect when these signals change state, use WaitCommEvent and then use GetCommModemStatus to determine the state after a change occurs.

The function fails if the hardware does not support the control-register values.

See Also

CreateFile, WaitCommEvent


GetCommProperties
 GetCommProperties  QuickInfo  Overview  Group

The GetCommProperties function fills a buffer with information about the communications properties for a specified communications device.

BOOL GetCommProperties(

HANDLE  hFile,	// handle of communications device
LPCOMMPROP  lpCommProp	// address of communications properties structure
);
Parameters

hFile

Identifies the communications device. The CreateFile function returns this handle.

lpCommProp

Points to a COMMPROP structure in which the communications properties information is returned. This information can be used in subsequent calls to the SetCommState, SetCommTimeouts, or SetupComm function to configure the communications device.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The GetCommProperties function returns information from a device driver about the configuration settings that are supported by the driver.

See Also

COMMPROP, CreateFile, SetCommState, SetCommTimeouts, SetupComm


GetCommState
 GetCommState  QuickInfo  Overview  Group

The GetCommState function fills in a device-control block (a DCB structure) with the current control settings for a specified communications device.

BOOL GetCommState(

HANDLE  hFile,	// handle of communications device
LPDCB  lpDCB	// address of device-control block structure
);
Parameters

hFile

Identifies the communications device. The CreateFile function returns this handle.

lpDCB

Points to the DCB structure in which the control settings information is returned.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

CreateFile, DCB, SetCommState


GetCommTimeouts
 GetCommTimeouts  QuickInfo  Overview  Group

The GetCommTimeouts function retrieves the time-out parameters for all read and write operations on a specified communications device.

BOOL GetCommTimeouts(

HANDLE  hFile,	// handle of communications device
LPCOMMTIMEOUTS  lpCommTimeouts	// address of comm. time-outs structure
);
Parameters

hFile

Identifies the communications device. The CreateFile function returns this handle.

lpCommTimeouts

Points to a COMMTIMEOUTS structure in which the time-out information is returned.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

For more information about time-out values for communications devices, see the SetCommTimeouts function.

See Also

CreateFile, COMMTIMEOUTS, SetCommTimeouts


GetCompressedFileSize
 GetCompressedFileSize  QuickInfo

The GetCompressedFileSize function obtains the compressed size, in bytes, of a specified file.

The GetCompressedFileSize function obtains the actual number of bytes of disk storage used to store a specified file. If the file is located on a volume that supports compression, and the file is compressed, the value obtained is the compressed size of the specified file. If the file is not located on a volume that supports compression, or if the file is not compressed, the value obtained is the actual file size, the same as the value returned by a call to GetFileSize.

DWORD GetCompressedFileSize(

LPCTSTR  lpFileName,	// pointer to name of file
LPDWORD  lpFileSizeHigh	// pointer to DWORD to receive high-order doubleword of file size
);
Parameters

lpFileName

Pointer to a null-terminated string that specifies the name of the file.

lpFileSizeHigh

Pointer to a DWORD variable that the function sets to the high-order doubleword of the compressed file size. The function's return value is the low-order doubleword of the compressed file size.

This parameter can be NULL if the high-order doubleword of the compressed file size is not needed. Files less than 4 gigabytes in size do not need the high-order doubleword.

Return Value

If the function succeeds, the return value is the low-order doubleword of the actual number of bytes of disk storage used to store the specified file, and if lpFileSizeHigh is non-NULL, the function puts the high-order doubleword of that actual value into the DWORD pointed to by that parameter. This is the compressed file size for compressed files, the actual file size for noncompressed files.

If the function fails, and lpFileSizeHigh is NULL, the return value is 0xFFFFFFFF. To get extended error information, call GetLastError.

If the function fails, and lpFileSizeHigh is non-NULL, the return value is 0xFFFFFFFF, and GetLastError returns a value other than NO_ERROR.

Remarks

Calling the GetCompressedFileSize function with the name of a nonseeking device, such as a pipe or a communications device, has no meaning.

Note that if the return value is 0xFFFFFFFF and lpFileSizeHigh is non-NULL, an application must call GetLastError to determine whether the function has succeeded or failed.

An application can determine whether a volume is compressed by calling GetVolumeInformation, then checking the status of the FS_VOL_IS_COMPRESSED flag in the DWORD pointed to by that function's lpFileSystemFlags parameter.

An application can determine whether a file is compressed by implementing the following pseudocode:

call GetVolumeInformation on the file's volume

if the file's volume is compressed

call GetCompressedFileSize on the file

call GetFileSize on the file

if the sizes don't match

the file is compressed

See Also

GetFileSize, GetVolumeInformation


GetComputerName
 GetComputerName  QuickInfo  Overview  Group

The GetComputerName function retrieves the computer name of the current system. This name is established at system startup, when it is initialized from the registry.

BOOL GetComputerName(

LPTSTR  lpBuffer,	// address of name buffer
LPDWORD  nSize	// address of size of name buffer
);
Parameters

lpBuffer

Points to a buffer to receive the null-terminated character string containing the computer name.

nSize

Points to a variable that specifies the maximum size, in characters, of the buffer. This value should be large enough to contain MAX_COMPUTERNAME_LENGTH + 1 characters.

Return Value

If the function succeeds, the return value is TRUE and the variable at nSize contains the number of characters copied to the destination buffer, not including the terminating null character.

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

See Also

SetComputerName


GetConsoleCP
 GetConsoleCP  QuickInfo  Overview  Group

Windows NT: The GetConsoleCP function returns the identity of the input code page used by the console associated with the calling process. A console uses its input code page to translate keyboard input into the corresponding character value.

Windows 95: On Japanese and Korean implementations of Windows 95, the GetConsoleCP function returns the VM code page, because the OEM code page can be either 437 or DBCS. On all other implementations of Windows 95, the GetConsoleCP function returns the OEM code page.

UINT GetConsoleCP(VOID)

Parameters

This function has no parameters.

Return Value

The return value is a code that identifies the code page.

Remarks

A code page maps 256 character codes to individual characters. Different code pages include different special characters, typically customized for a language or a group of languages.

To set a console's input code page, use the SetConsoleCP function. To set and query a console's output code page, use the SetConsoleOutputCP and GetConsoleOutputCP functions.

See Also

GetConsoleOutputCP, SetConsoleCP, SetConsoleOutputCP


GetConsoleCursorInfo
 GetConsoleCursorInfo  QuickInfo  Overview  Group

The GetConsoleCursorInfo function retrieves information about the size and visibility of the cursor for the specified console screen buffer.

BOOL GetConsoleCursorInfo(

HANDLE  hConsoleOutput,	// handle of console screen buffer
PCONSOLE_CURSOR_INFO  lpConsoleCursorInfo	// address of cursor information
);
Parameters

hConsoleOutput

Identifies a console screen buffer. The handle must have GENERIC_READ access.

lpConsoleCursorInfo

Points to a CONSOLE_CURSOR_INFO structure in which information about the console's cursor is returned.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

CONSOLE_CURSOR_INFO, SetConsoleCursorInfo


GetConsoleMode
 GetConsoleMode  QuickInfo  Overview  Group

The GetConsoleMode function reports the current input mode of a console's input buffer or the current output mode of a console screen buffer.

BOOL GetConsoleMode(

HANDLE  hConsoleHandle,	// handle of console input or screen buffer
LPDWORD  lpMode	// current mode flags
);
Parameters

hConsoleHandle

Identifies a console input buffer or a screen buffer. The handle must have GENERIC_READ access.

lpMode

Points to a 32-bit variable that indicates the current mode of the specified buffer.

If the hConsoleHandle parameter is an input handle, the mode can be a combination of the following values. When a console is created, all input modes except ENABLE_WINDOW_INPUT are enabled by default.

Value	Meaning
ENABLE_LINE_INPUT	The ReadFile or ReadConsole function returns only when a carriage return character is read. If this mode is disabled, the functions return when one or more characters are available.
ENABLE_ECHO_INPUT	Characters read by the ReadFile or ReadConsole function are written to the active screen buffer as they are read. This mode can be used only if the ENABLE_LINE_INPUT mode is also enabled.
ENABLE_PROCESSED_INPUT	CTRL+C is processed by the system and is not placed in the input buffer. If the input buffer is being read by ReadFile or ReadConsole, other control keys are processed by the system and are not returned in the ReadFile or ReadConsole buffer. If the ENABLE_LINE_INPUT mode is also enabled, backspace, carriage return, and linefeed characters are handled by the system.
ENABLE_WINDOW_INPUT	User interactions that change the size of the console screen buffer are reported in the console's input buffer. Information about these events can be read from the input buffer by applications using the ReadConsoleInput function, but not by those using ReadFile or ReadConsole.
ENABLE_MOUSE_INPUT	If the mouse pointer is within the borders of the console window and the window has the keyboard focus, mouse events generated by mouse movement and button presses are placed in the input buffer. These events are discarded by ReadFile or ReadConsole, even when this mode is enabled.
If the hConsoleHandle parameter is a screen buffer handle, the mode can be a combination of the following values. When a screen buffer is created, both output modes are enabled by default.

Value	Meaning
ENABLE_PROCESSED_OUTPUT	Characters written by the WriteFile or WriteConsole function or echoed by the ReadFile or ReadConsole function are parsed for ASCII control sequences, and the correct action is performed. Backspace, tab, bell, carriage return, and linefeed characters are processed.
ENABLE_WRAP_AT_EOL_OUTPUT	When writing with WriteFile or WriteConsole or echoing with ReadFile or ReadConsole, the cursor moves to the beginning of the next row when it reaches the end of the current row. This causes the rows displayed in the console window to scroll up automatically when the cursor advances beyond the last row in the window. It also causes the contents of the screen buffer to scroll up (discarding the top row of the screen buffer) when the cursor advances beyond the last row in the screen buffer. If this mode is disabled, the last character in the row is overwritten with any subsequent characters.
Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

A console consists of an input buffer and one or more screen buffers. The mode of a console buffer determines how the console behaves during input or output (I/O) operations. One set of flag constants is used with input handles, and another set is used with screen buffer (output) handles. Setting the output modes of one screen buffer does not affect the output modes of other screen buffers.

The ENABLE_LINE_INPUT and ENABLE_ECHO_INPUT modes only affect processes that use ReadFile or ReadConsole to read from the console's input buffer. Similarly, the ENABLE_PROCESSED_INPUT mode primarily affects ReadFile and ReadConsole users, except that it also determines whether CTRL+C input is reported in the input buffer (to be read by the ReadConsoleInput function) or is passed to a function defined by the application.

The ENABLE_WINDOW_INPUT and ENABLE_MOUSE_INPUT modes determine whether user interactions involving window resizing and mouse actions are reported in the input buffer or discarded. These events can be read by ReadConsoleInput, but they are always filtered by ReadFile and ReadConsole.

The ENABLE_PROCESSED_OUTPUT and ENABLE_WRAP_AT_EOL_OUTPUT modes only affect processes using ReadFile or ReadConsole and WriteFile or WriteConsole.

To change a console's I/O modes, call SetConsoleMode function.

See Also

ReadConsole, ReadConsoleInput, ReadFile, SetConsoleMode, WriteConsole, WriteFile


GetConsoleOutputCP
 GetConsoleOutputCP  QuickInfo  Overview  Group

Windows NT: The GetConsoleOutputCP function returns the identity of the output code page used by the console associated with the calling process. A console uses its output code page to translate the character values written by the various output functions into the images displayed in the console window.

Windows 95: On Japanese and Korean implementations of Windows 95, the GetConsoleOutputCP function returns the VM code page, because the OEM code page can be either 437 or DBCS. On all other implementations of Windows 95, the GetConsoleOutputCP function returns the OEM code page.

UINT GetConsoleOutputCP(VOID)

Parameters

This function has no parameters.

Return Value

The return value is a code that identifies the code page.

Remarks

A code page maps 256 character codes to individual characters. Different code pages include different special characters, typically customized for a language or a group of languages.

To set a console's output code page, use the SetConsoleOutputCP function. To set and query a console's input code page, use the SetConsoleCP and GetConsoleCP functions.

See Also

GetConsoleCP, SetConsoleCP, SetConsoleOutputCP


GetConsoleScreenBufferInfo
 GetConsoleScreenBufferInfo  QuickInfo  Overview  Group

The GetConsoleScreenBufferInfo function retrieves information about the specified console screen buffer.

BOOL GetConsoleScreenBufferInfo(

HANDLE  hConsoleOutput,	// handle of console screen buffer
PCONSOLE_SCREEN_BUFFER_INFO  lpConsoleScreenBufferInfo	// address of screen buffer info.
);
Parameters

hConsoleOutput

Identifies a console screen buffer. The handle must have GENERIC_READ access.

lpConsoleScreenBufferInfo

Points to a CONSOLE_SCREEN_BUFFER_INFO structure in which the screen buffer information is returned.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The rectangle returned in the srWindow member of the CONSOLE_SCREEN_BUFFER_INFO structure can be modified and then passed to the SetConsoleWindowInfo function to scroll the screen buffer in the window, to change the size of the window, or both.

All coordinates returned in the CONSOLE_SCREEN_BUFFER_INFO structure are in character-cell coordinates, where the origin (0, 0) is at the upper-left corner of the screen buffer.

See Also

CONSOLE_SCREEN_BUFFER_INFO, GetLargestConsoleWindowSize, SetConsoleCursorPosition, SetConsoleScreenBufferSize, SetConsoleWindowInfo


GetConsoleTitle
 GetConsoleTitle  QuickInfo  Overview  Group

The GetConsoleTitle function retrieves the title bar string for the current console window.

DWORD GetConsoleTitle(

LPTSTR  lpConsoleTitle,	// address of buffer for title
DWORD  nSize	// size of the buffer
);
Parameters

lpConsoleTitle

Points to a buffer that receives a null-terminated string containing the text that appears in the title bar of the console window.

nSize

Specifies the size, in characters, of the buffer pointed to by the lpConsoleTitle parameter.

Return Value

If the function succeeds, the return value is the length, in characters, of the string copied to the buffer.

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

Remarks

To set the title bar string for a console window, use the SetConsoleTitle function.

See Also

SetConsoleTitle


GetCPInfo
 GetCPInfo  QuickInfo  Overview  Group

The GetCPInfo function retrieves information about any valid installed or available code page.

BOOL GetCPInfo(

UINT  CodePage,	// code page identifier
LPCPINFO  lpCPInfo	// address of structure for information
);
Parameters

CodePage

Specifies the code page about which information is to be retrieved. You can specify the code page identifier for any installed or available code page, or you can specify one of the following predefined values:

Value	Meaning
CP_ACP	Use the system default ANSI code page
CP_MACCP	Use the system default Macintosh code page
CP_OEMCP	Use the system default OEM code page
lpCPInfo

Points to a CPINFO structure that receives information about the code page.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

If the specified code page is not installed or not available, GetCPInfo sets the last-error value to ERROR_INVALID_PARAMETER.

See Also

GetACP, GetOEMCP, CPINFO


GetCurrencyFormat
 GetCurrencyFormat  QuickInfo  Overview  Group

The GetCurrencyFormat function formats a number string as a currency string for a specified locale.

int GetCurrencyFormat(

LCID  Locale,	// locale for which currency string is to be formatted
DWORD  dwFlags,	// bit flag that controls the function's operation
LPCTSTR  lpValue,	// pointer to input number string
CONST CURRENCYFMT *  lpFormat,	// pointer to a formatting information structure
LPTSTR  lpCurrencyStr,	// pointer to output buffer
int  cchCurrency	// size of output buffer
);
Parameters

Locale

Specifies the locale for which the currency string is to be formatted. If lpFormat is NULL, the function formats the string according to the currency format for this locale. If lpFormat is not NULL, the function uses the locale only for formatting information not specified in the CURRENCYFMT structure (for example, the locale's string value for the negative sign).

This parameter can be a locale identifier created by the MAKELCID macro, or one of the following predefined values:

LOCALE_SYSTEM_DEFAULT	Default system locale.
LOCALE_USER_DEFAULT	Default user locale.
dwFlags

A bit flag that controls the operation of the function. If lpFormat is non-NULL, this parameter must be zero.

If lpFormat is NULL, you can specify the LOCALE_NOUSEROVERRIDE flag to format the string using the system default currency format for the specified locale; or you can specify zero to format the string using any user overrides to the locale's default currency format.

lpValue

Points to a null-terminated string containing the number string to format.

This string can contain only the following characters:

•	Characters '0' through '9'

•	One decimal point (dot) if the number is a floating-point value

•	A minus sign in the first character position if the number is a negative value

All other characters are invalid. The function returns an error if the string pointed to by lpValue deviates from these rules.

lpFormat

Pointer to a CURRENCYFMT structure that contains currency formatting information. All members in the structure pointed to by lpFormat must contain appropriate values.

If lpFormat is NULL, the function uses the currency format of the specified locale.

lpCurrencyStr

Points to a buffer to receive the formatted currency string.

cchCurrency

Specifies the size, in bytes (ANSI version) or characters (Unicode version), of the lpCurrencyStr buffer. If cchCurrency is zero, the function returns the number of bytes or characters required to hold the formatted currency string, and the buffer pointed to by lpCurrencyStr is not used.

Return Value

If the function succeeds, the return value is the number of bytes (ANSI version) or characters (Unicode version) written to the buffer pointed to by lpCurrencyStr, or if the cchCurrency parameter is zero, the number of bytes or characters required to hold the formatted currency string.

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

See Also

GetNumberFormat, CURRENCYFMT


GetCurrentDirectory
 GetCurrentDirectory  QuickInfo  Overview  Group

The GetCurrentDirectory function retrieves the current directory for the current process.

DWORD GetCurrentDirectory(

DWORD  nBufferLength,	// size, in characters, of directory buffer
LPTSTR  lpBuffer	// address of buffer for current directory
);
Parameters

nBufferLength

Specifies the length, in characters, of the buffer for the current directory string. The buffer length must include room for a terminating null character.

lpBuffer

Points to the buffer for the current directory string. This null-terminated string specifies the absolute path to the current directory.

Return Value

If the function succeeds, the return value specifies the number of characters written to the buffer, not including the terminating null character.

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

If the buffer pointed to by lpBuffer is not large enough, the return value specifies the required size of the buffer, including the number of bytes necessary for a terminating null character.

See Also

CreateDirectory, GetSystemDirectory, GetWindowsDirectory, RemoveDirectory, SetCurrentDirectory


GetCurrentObject
 GetCurrentObject  QuickInfo  Overview  Group

The GetCurrentObject function returns the currently selected object of the specified type.

HGDIOBJ GetCurrentObject(

HDC  hdc,	// handle of device context
UINT  uObjectType	// object-type identifier
);
Parameters

hdc

Identifies the device context.

uObjectType

Specifies the object type to be queried. This parameter can be one of the following values:

Value	Meaning
OBJ_PEN	Returns the current selected pen.
OBJ_BRUSH	Returns the current selected brush.
OBJ_PAL	Returns the current selected palette.
OBJ_FONT	Returns the current selected font.
OBJ_BITMAP	Returns the current selected bitmap if hdc is a memory device context.
Return Value

If the function succeeds, the return value is the handle of the specified object.

If the function fails, the return value is NULL.

Remarks

An application can use the GetCurrentObject and GetObject functions to retrieve descriptions of the graphic objects currently selected into the given device context.

See Also

DeleteObject, GetObject, SelectObject


GetCurrentPDB
 GetCurrentPDB  Overview  Group

The GetCurrentPDB function is not implemented in the Win32 API. Win32-based applications should use the GetCommandLine and GetEnvironmentStrings functions.


 GetCurrentPosition

The GetCurrentPosition function is not implemented in the Win32 API. Win32-based applications should use the GetCurrentPositionEx function.


GetCurrentPositionEx
 GetCurrentPositionEx  QuickInfo  Overview  Group

The GetCurrentPositionEx function retrieves the current position in logical coordinates.

BOOL GetCurrentPositionEx(

HDC  hdc,	// handle of device context
LPPOINT  lpPoint	// address of structure receiving current position
);
Parameters

hdc

Identifies the device context.

lpPoint

Points to a POINT structure that receives the coordinates of the current position.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

See Also

MoveToEx, POINT


GetCurrentProcess
 GetCurrentProcess  QuickInfo  Overview  Group

The GetCurrentProcess function returns a pseudohandle for the current process.

HANDLE GetCurrentProcess(VOID)

Parameters

This function has no parameters.

Return Value

The return value is a pseudohandle to the current process.

Remarks

A pseudohandle is a special constant that is interpreted as the current process handle. The calling process can use this handle to specify its own process whenever a process handle is required. Pseudohandles are not inherited by child processes.

This handle has the maximum possible access to the process object. For systems that support security descriptors, this is the maximum access allowed by the security descriptor for the calling process. For systems that do not support security descriptors, this is PROCESS_ALL_ACCESS.

A process can create a "real" handle to itself that is valid in the context of other processes, or that can be inherited by other processes, by specifying the pseudohandle as the source handle in a call to the DuplicateHandle function. A process can also use the OpenProcess function to open a real handle to itself.

The pseudohandle need not be closed when it is no longer needed. Calling the CloseHandle function with a pseudohandle has no effect. If the pseudohandle is duplicated by DuplicateHandle, the duplicate handle must be closed.

See Also

CloseHandle, DuplicateHandle, GetCurrentProcessId, GetCurrentThread, OpenProcess


GetCurrentProcessId
 GetCurrentProcessId  QuickInfo  Overview  Group

The GetCurrentProcessId function returns the process identifier of the calling process.

DWORD GetCurrentProcessId(VOID)

Parameters

This function has no parameters.

Return Value

The return value is the process identifier of the calling process.

Remarks

Until the process terminates, the process identifier uniquely identifies the process throughout the system.

See Also

GetCurrentProcess, OpenProcess


GetCurrentTask
 GetCurrentTask  Overview  Group

The GetCurrentTask function is not implemented in the Win32 API. Win32-based applications should use the GetCurrentThread or GetCurrentProcess function.


GetCurrentThread
 GetCurrentThread  QuickInfo  Overview  Group

The GetCurrentThread function returns a pseudohandle for the current thread.

HANDLE GetCurrentThread(VOID)

Parameters

This function has no parameters.

Return Value

The return value is a pseudohandle for the current thread.

Remarks

A pseudohandle is a special constant that is interpreted as the current thread handle. The calling thread can use this handle to specify itself whenever a thread handle is required. Pseudohandles are not inherited by child processes.

This handle has the maximum possible access to the thread object. For systems that support security descriptors, this is the maximum access allowed by the security descriptor for the calling process. For systems that do not support security descriptors, this is THREAD_ALL_ACCESS.

The function cannot be used by one thread to create a handle that can be used by other threads to refer to the first thread. The handle is always interpreted as referring to the thread that is using it. A thread can create a "real" handle of itself that can be used by other threads, or inherited by other processes, by specifying the pseudohandle as the source handle in a call to the DuplicateHandle function.

The pseudohandle need not be closed when it is no longer needed. Calling the CloseHandle function with this handle has no effect. If the pseudohandle is duplicated by DuplicateHandle, the duplicate handle must be closed.

See Also

CloseHandle, DuplicateHandle, GetCurrentProcess, GetCurrentThreadId


GetCurrentThreadId
 GetCurrentThreadId  QuickInfo  Overview  Group

The GetCurrentThreadId function returns the thread identifier of the calling thread.

DWORD GetCurrentThreadId(VOID)

Parameters

This function has no parameters.

Return Value

The return value is the thread identifier of the calling thread.

Remarks

Until the thread terminates, the thread identifier uniquely identifies the thread throughout the system.

See Also

GetCurrentThread


GetCurrentTime
 GetCurrentTime  QuickInfo  Overview  Group

The GetCurrentTime function retrieves the number of milliseconds that have elapsed since Windows was started.

DWORD GetCurrentTime(VOID)

Parameters

This function has no parameters.

Return Value

If the function succeeds, the return value is the number of milliseconds that have elapsed since Windows was started.

Remarks

The GetCurrentTime function is identical to the GetTickCount function. Applications should use the GetTickCount function because its name matches more closely what the function does.

The GetCurrentTime and GetMessageTime functions return different times. GetMessageTime returns the Windows time when the given message was created, not the current Windows time.

The internal timer wraps around to zero if Windows is run continuously for approximately 49.7 days.

See Also

GetMessageTime, GetSystemTime, GetTickCount, SetSystemTime


GetCursor
 GetCursor  QuickInfo  Overview  Group

The GetCursor function retrieves the handle of the current cursor.

HCURSOR GetCursor(VOID)

Parameters

This function has no parameters.

Return Value

If the function succeeds, the return value is the handle of the current cursor.

If there is no cursor, the return value is NULL.

See Also

SetCursor


GetCursorPos
 GetCursorPos  QuickInfo  Overview  Group

The GetCursorPos function retrieves the cursor's position, in screen coordinates.

BOOL GetCursorPos(

LPPOINT  lpPoint	// address of structure for cursor position
);
Parameters

lpPoint

Points to a POINT structure that receives the screen coordinates of the cursor.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The cursor position is always given in screen coordinates and is not affected by the mapping mode of the window that contains the cursor.

The calling process must have WINSTA_READATTRIBUTES access to the window station.

See Also

ClipCursor, POINT, SetCursor, SetCursorPos, ShowCursor


GetDateFormat
 GetDateFormat  QuickInfo  Overview  Group

The GetDateFormat function formats a date as a date string for a specified locale. The function formats either a specified date or the local system date.

int GetDateFormat(

LCID  Locale,	// locale for which date is to be formatted
DWORD  dwFlags,	// flags specifying function options
CONST SYSTEMTIME *  lpDate,	// date to be formatted
LPCTSTR  lpFormat,	// date format string
LPTSTR  lpDateStr,	// buffer for storing formatted string
int  cchDate	// size of buffer
);
Parameters

Locale

Specifies the locale for which the date string is to be formatted. If lpFormat is NULL, the function formats the string according to the date format for this locale. If lpFormat is not NULL, the function uses the locale only for information not specified in the format picture string (for example, the locale's day and month names).

This parameter can be a locale identifier created by the MAKELCID macro, or one of the following predefined values:

LOCALE_SYSTEM_DEFAULT	Default system locale.
LOCALE_USER_DEFAULT	Default user locale.
dwFlags

A set of bit flags that specify various function options. If lpFormat is non-NULL, this parameter must be zero.

If lpFormat is NULL, you can specify a combination of the following flags:

Flag	Meaning
LOCALE_NOUSEROVERRIDE	If set, the function formats the string using the system default date format for the specified locale. If not set, the function formats the string using any user overrides to the locale's default date format.
DATE_SHORTDATE	Use the short date format. This is the default. Cannot be used with DATE_LONGDATE.
DATE_LONGDATE	Use the long date format. Cannot be used with DATE_SHORTDATE.
DATE_USE_ALT_CALENDAR	Use the alternate calendar, if one exists, to format the date string. If this flag is set, the function uses the default format for that alternate calendar, rather than using any user overrides. The user overrides will be used only in the event that there is no default format for the specified alternate calendar.
lpDate

Pointer to a SYSTEMTIME structure that contains the date information to be formatted. If this pointer is NULL, the function uses the current local system date.

lpFormat

Pointer to a format picture string to use to form the date string. If lpFormat is NULL, the function uses the date format of the specified locale.

Use the following elements to construct a format picture string. If you use spaces to separate the elements in the format string, these spaces will appear in the same location in the output string. The letters must be in uppercase or lowercase as shown in the table (for example, "MM" not "mm"). Characters in the format string that are enclosed in single quotation marks will appear in the same location and unchanged in the output string.

Picture	Meaning
d	Day of month as digits with no leading zero for single-digit days.
dd	Day of month as digits with leading zero for single-digit days.
ddd	Day of week as a three-letter abbreviation. The function uses the LOCALE_SABBREVDAYNAME value associated with the specified locale.
dddd	Day of week as its full name. The function uses the LOCALE_SDAYNAME value associated with the specified locale.
M	Month as digits with no leading zero for single-digit months.
MM	Month as digits with leading zero for single-digit months.
MMM	Month as a three-letter abbreviation. The function uses the LOCALE_SABBREVMONTHNAME value associated with the specified locale.
MMMM	Month as its full name. The function uses the LOCALE_SMONTHNAME value associated with the specified locale.
y	Year as last two digits, but with no leading zero for years less than 10.
yy	Year as last two digits, but with leading zero for years less than 10.
yyyy	Year represented by full four digits.
gg	Period/era string. The function uses the CAL_SERASTRING value associated with the specified locale. This element is ignored if the date to be formatted does not have an associated era or period string.
For example, to get the date string

"Wed, Aug 31 94"

use the following picture string:

"ddd',' MMM dd yy"

lpDateStr

Pointer to a buffer that receives the formatted date string.

cchDate

Specifies the size, in bytes (ANSI version) or characters (Unicode version), of the lpDateStr buffer. If cchDate is zero, the function returns the number of bytes or characters required to hold the formatted date string, and the buffer pointed to by lpDateStr is not used.

Return Value

If the function succeeds, the return value is the number of bytes (ANSI version) or characters (Unicode version) written to the lpDateStr buffer, or if the cchDate parameter is zero, the number of bytes or characters required to hold the formatted date string.

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 day name, abbreviated day name, month name, and abbreviated month name are all localized based on the given locale identifier.

The date values in the SYSTEMTIME structure pointed to by lpDate must be valid. The function checks each of the date values: year, month, day, and day of week. If the day of the week is incorrect, the function uses the correct value, and returns no error. If any of the other date values are outside the correct range, the function fails, and sets the last-error to ERROR_INVALID_PARAMETER.

The function ignores the time portions of the SYSTEMTIME structure pointed to by lpDate: wHour, wMinute, wSecond, and wMilliseconds.

The DATE_SHORTDATE and DATE_LONGDATE flag options are mutually exclusive. If neither one is specified and lpFormat is NULL, then DATE_SHORTDATE is the default.

No errors are returned for a bad format string. The function simply forms the best date string that it can. For example, the only year pictures that are valid are L"yyyy" and L"yy" (the 'L' indicates a Unicode (16-bit characters) string). If L"y" is passed in, the function  assumes L"yy". If L"yyy" is passed in, the function assumes L"yyyy". If more than 4 date (L"dddd") or 4 month (L"MMMM") pictures are passed in, then the function defaults to L"dddd" or L"MMMM".

Any text that should remain in its exact form in the date string should be enclosed within single quotation marks in the date format picture. The single quotation mark may also be used as an escape character to allow the single quotation mark itself to be displayed in the date string. However, the escape sequence must be enclosed within two single quotation marks. For example, to display the date as "May '93", the format string would be:  L"MMMM ''''yy" The first and last single quotation marks are the enclosing quotation marks. The second and third single quotation marks are the escape sequence to allow the single quotation mark to be displayed before the century.

See Also

GetTimeFormat, SYSTEMTIME


GetDC
 GetDC  QuickInfo  Overview  Group

The GetDC function retrieves a handle of a display device context (DC) for the client area of the specified window. The display device context can be used in subsequent GDI functions to draw in the client area of the window.

This function retrieves a common, class, or private device context depending on the class style specified for the specified window. For common device contexts, GetDC assigns default attributes to the device context each time it is retrieved. For class and private device contexts, GetDC leaves the previously assigned attributes unchanged.

HDC GetDC(

HWND  hWnd	// handle of window
);
Parameters

hWnd

Identifies the window whose device context is to be retrieved.

Return Value

If the function succeeds, the return value identifies the device context for the given window's client area.

If the function fails, the return value is NULL.

Remarks

After painting with a common device context, the ReleaseDC function must be called to release the device context. Class and private device contexts do not have to be released. The number of device contexts is limited only by available memory.

See Also

ReleaseDC, GetWindowDC


GetDCEx
 GetDCEx  QuickInfo  Overview  Group

The GetDCEx function retrieves the handle of a display device (DC) context for the specified window. The display device context can be used in subsequent GDI functions to draw in the client area.

This function is an extension to the GetDC function that gives an application more control over how and whether clipping occurs in the client area.

HDC GetDCEx(

HWND  hWnd,	// handle of window
HRGN  hrgnClip,	// handle of clip region
DWORD  flags	// device-context creation flags
);
Parameters

hWnd

Identifies the window where drawing will occur.

hrgnClip

Specifies a clipping region that may be combined with the visible region of the client window.

flags

Specifies how the device context is created. This parameter can be a combination of the following values:

Value	Meaning
DCX_WINDOW	Returns a device context corresponding to the window rectangle rather than the client rectangle.
DCX_CACHE	Returns a device context from the cache, rather than the OWNDC or CLASSDC window. Essentially overrides CS_OWNDC and CS_CLASSDC.
DCX_PARENTCLIP	Uses the visible region of the parent window. The parent's WS_CLIPCHILDREN and CS_PARENTDC style bits are ignored. The device context origin is set to the upper-left corner of the window identified by hWnd.
DCX_CLIPSIBLINGS	Excludes the visible regions of all sibling windows above the window identified by hWnd.
DCX_CLIPCHILDREN	Excludes the visible regions of all child windows below the window identified by hWnd.
DCX_NORESETATTRS	Does not reset the attributes of this device context to the default attributes when this device context is released.
DCX_LOCKWINDOWUPDATE	Allows drawing even if there is a LockWindowUpdate call in effect that would otherwise exclude this window. Used for drawing during tracking.
DCX_EXCLUDERGN	The clipping region identified by hrgnClip is excluded from the visible region of the returned device context.
DCX_INTERSECTRGN	The clipping region identified by hrgnClip is intersected with the visible region of the returned device context.
DCX_VALIDATE	When specified with DCX_INTERSECTUPDATE, causes the device context to be completely validated. Using this function with both DCX_INTERSECTUPDATE and DCX_VALIDATE is identical to using the BeginPaint function.
Return Value

If the function succeeds, the return value is the handle of the device context for the given window.

If the function fails, the return value is NULL. An invalid value for the hWnd parameter will cause the function to fail.

Remarks

Unless the display device context belongs to a window class, the ReleaseDC function must be called to release the device context after painting. Because only five common device contexts are available at any given time, failure to release a device context can prevent other applications from accessing a device context.

A device context belonging to the window's class is returned by the GetDC function if CS_CLASSDC, CS_OWNDC or CS_PARENTDC was specified as a style in the WNDCLASS structure when the class was registered.

See Also

BeginPaint, GetDC, GetWindowDC, ReleaseDC WNDCLASS


 GetDCOrg

The GetDCOrg function is not implemented in the Win32 API. Win32-based applications should use the GetDCOrgEx function.


GetDCOrgEx
 GetDCOrgEx  QuickInfo  Overview  Group

The GetDCOrgEx function obtains the final translation origin for a specified device context (DC). The final translation origin specifies an offset that Windows uses to translate device coordinates into client coordinates (for coordinates in an application's window). This function supersedes the GetDCOrg function.

BOOL GetDCOrgEx(

HDC  hdc,	// device-context handle
LPPOINT  lpPoint	// address of structure that receives translation origin
);
Parameters

hdc

Specifies the device context whose final translation origin is to be retrieved.

lpPoint

Points to a POINT structure that the function will set to the final translation origin, in device coordinates.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

The final translation origin is relative to the physical origin of the screen.

See Also

CreateIC, POINT


GetDefaultCommConfig [New - Windows 95]
 GetDefaultCommConfig  QuickInfo

[New - Windows 95]

The GetDefaultCommConfig function gets the default configuration for a communications device.

BOOL GetDefaultCommConfig(

LPCSTR  lpszName,
LPCOMMCONFIG  lpCC,
LPDWORD  lpdwSize
);
Parameters

lpszName

Points to a null-terminated string specifying the name of the device.

lpCC

Points to the buffer that receives the COMMCONFIG structure.

lpdwSize

Points to a 32-bit variable that specifies the size, in bytes, of the buffer pointed to by lpCC. Upon return, the variable contains the number of bytes copied if the function succeeds, or the number of bytes required if the buffer was too small.

Return value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To get extended error information, use the GetLastError function.

See Also

COMMCONFIG


GetDesktopWindow
 GetDesktopWindow  QuickInfo  Overview  Group

The GetDesktopWindow function returns the handle of the Windows 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 Value

The return value is the handle of the desktop window.

See Also

GetWindow


GetDeviceCaps
 GetDeviceCaps  QuickInfo  Overview  Group

The GetDeviceCaps function retrieves device-specific information about a specified device.

int GetDeviceCaps(

HDC  hdc,	// device-context handle
int  nIndex	// index of capability to query
);
Parameters

hdc

Identifies the device context.

nIndex

Specifies the item to return. This parameter can be one of the following values:

Index	Meaning
DRIVERVERSION	The device driver version.
TECHNOLOGY	Device technology. It can be any one of the following values:
Value	Meaning
DT_PLOTTER	Vector plotter
DT_RASDISPLAY	Raster display
DT_RASPRINTER	Raster printer
DT_RASCAMERA	Raster camera
DT_CHARSTREAM	Character stream
DT_METAFILE	Metafile
DT_DISPFILE	Display file
	If the hdc parameter identifies the device context of an enhanced metafile, the device technology is that of the referenced device as given to the CreateEnhMetaFile function. To determine whether it is an enhanced metafile device context, use the GetObjectType function.
HORZSIZE	Width, in millimeters, of the physical screen.
VERTSIZE	Height, in millimeters, of the physical screen.
HORZRES	Width, in pixels, of the screen.
VERTRES	Height, in raster lines, of the screen.
LOGPIXELSX	Number of pixels per logical inch along the screen width.
LOGPIXELSY	Number of pixels per logical inch along the screen height.
BITSPIXEL	Number of adjacent color bits for each pixel.
PLANES	Number of color planes.
NUMBRUSHES	Number of device-specific brushes.
NUMPENS	Number of device-specific pens.
NUMFONTS	Number of device-specific fonts.
NUMCOLORS	Number of entries in the device's color table.
ASPECTX	Relative width of a device pixel used for line drawing.
ASPECTY	Relative height of a device pixel used for line drawing.
ASPECTXY	Diagonal width of the device pixel used for line drawing.
PDEVICESIZE	Reserved.
CLIPCAPS	Flag that indicates the clipping capabilities of the device. If the device can clip to a rectangle, it is 1. Otherwise, it is 0.
SIZEPALETTE	Number of entries in the system palette. This index is valid only if the device driver sets the RC_PALETTE bit in the RASTERCAPS index and is available only if the driver is compatible with Windows version 3.0 or later.
NUMRESERVED	Number of reserved entries in the system palette. This index is valid only if the device driver sets the RC_PALETTE bit in the RASTERCAPS index and is available only if the driver is compatible with Windows version 3.0 or later.
COLORRES	Actual color resolution of the device, in bits per pixel. This index is valid only if the device driver sets the RC_PALETTE bit in the RASTERCAPS index and is available only if the driver is compatible with Windows version 3.0 or later.
PHYSICALWIDTH	For printing devices: the physical width, in device units.
PHYSICALHEIGHT	For printing devices: the physical height, in device units.
PHYSICALOFFSETX	For printing devices: the physical printable area horizontal margin.
PHYSICALOFFSETY	For printing devices: the physical printable area vertical margin.
SCALINGFACTORX	For printing devices: the scaling factor along the horizontal axis.
SCALINGFACTORY	For printing devices: the scaling factor along the vertical axis.
VREFRESH	Windows NT only: For display devices: the current vertical refresh rate of the device, in cycles per second (Hz).
DESKTOPHORZRES	Windows NT only: Width, in pixels, of the virtual desktop. This value may be larger than HORZRES if the device supports a virtual desktop or multiple displays.
DESKTOPVERTRES	Windows NT only: Height, in pixels, of the virtual desktop. This value may be larger than VERTRES if the device supports a virtual desktop or multiple displays.
BLTALIGNMENT	Windows NT only: Preferred horizontal drawing alignment, expressed as a multiple of pixels. For best drawing performance, windows should be horizontally aligned to a multiple of this value. A value of zero indicates that the device is accelerated, and any alignment may be used.
RASTERCAPS	Value that indicates the raster capabilities of the device, as shown in the following table:
Capability	Meaning
RC_BANDING	Requires banding support.
RC_BITBLT	Capable of transferring bitmaps.
RC_BITMAP64	Capable of supporting bitmaps larger than 64K.
RC_DI_BITMAP	Capable of supporting the SetDIBits and GetDIBits functions.
RC_DIBTODEV	Capable of supporting the SetDIBitsToDevice function.
RC_FLOODFILL	Capable of performing flood fills.
RC_GDI20_OUTPUT	Capable of supporting features of Windows 2.0.
RC_PALETTE	Specifies a palette-based device.
RC_SCALING	Capable of scaling.
RC_STRETCHBLT	Capable of performing the StretchBlt function.
RC_STRETCHDIB	Capable of performing the StretchDIBits function.
CURVECAPS	Value that indicates the curve capabilities of the device, as shown in the following table:
Value	Meaning
CC_NONE	Device does not support curves.
CC_CIRCLES	Device can draw circles.
CC_PIE	Device can draw pie wedges.
CC_CHORD	Device can draw chord arcs.
CC_ELLIPSES	Device can draw ellipses.
CC_WIDE	Device can draw wide borders.
CC_STYLED	Device can draw styled borders.
CC_WIDESTYLED	Device can draw borders that are wide and styled.
CC_INTERIORS	Device can draw interiors.
CC_ROUNDRECT	Device can draw rounded rectangles.
LINECAPS	Value that indicates the line capabilities of the device, as shown in the following table:
Value	Meaning
LC_NONE	Device does not support lines.
LC_POLYLINE	Device can draw a polyline.
LC_MARKER	Device can draw a marker.
LC_POLYMARKER	Device can draw multiple markers.
LC_WIDE	Device can draw wide lines.
LC_STYLED	Device can draw styled lines.
LC_WIDESTYLED	Device can draw lines that are wide and styled.
LC_INTERIORS	Device can draw interiors.
POLYGONALCAPS	Value that indicates the polygon capabilities of the device, as shown in the following table:
Value	Meaning
PC_NONE	Device does not support polygons.
PC_POLYGON	Device can draw alternate-fill polygons.
PC_RECTANGLE	Device can draw rectangles.
PC_WINDPOLYGON	Device can draw winding-fill polygons.
PC_SCANLINE	Device can draw a single scanline.
PC_WIDE	Device can draw wide borders.
PC_STYLED	Device can draw styled borders.
PC_WIDESTYLED	Device can draw borders that are wide and styled.
PC_INTERIORS	Device can draw interiors.
TEXTCAPS	Value that indicates the text capabilities of the device, as shown in the following table:
Bit	Meaning
TC_OP_CHARACTER	Device is capable of character output precision.
TC_OP_STROKE	Device is capable of stroke output precision.
TC_CP_STROKE	Device is capable of stroke clip precision.
TC_CR_90	Device is capable of 90-degree character rotation.
TC_CR_ANY	Device is capable of any character rotation.
TC_SF_X_YINDEP	Device can scale independently in the x- and y-directions.
TC_SA_DOUBLE	Device is capable of doubled character for scaling.
TC_SA_INTEGER	Device uses integer multiples only for character scaling.
TC_SA_CONTIN	Device uses any multiples for exact character scaling.
TC_EA_DOUBLE	Device can draw double-weight characters.
TC_IA_ABLE	Device can italicize.
TC_UA_ABLE	Device can underline.
TC_SO_ABLE	Device can draw strikeouts.
TC_RA_ABLE	Device can draw raster fonts.
TC_VA_ABLE	Device can draw vector fonts.
TC_RESERVED	Reserved; must be zero.
TC_SCROLLBLT	Device cannot scroll using a bit-block transfer. Note that this meaning may be the opposite of what you expect.
Return Value

The return value specifies the value of the desired item.

See Also

CreateEnhMetaFile, CreateIC, DeviceCapabilities, GetDIBits, GetObjectType, SetDIBits, SetDIBitsToDevice, StretchBlt, StretchDIBits


GetDeviceGammaRamp [New - Windows 95]
 GetDeviceGammaRamp  QuickInfo  Overview  Group

[New - Windows 95]

The GetDeviceGammaRamp function retrieves the gamma ramp on direct color display boards.

BOOL GetDeviceGammaRamp(

HDC  hdc,
LPVOID  lpRamp
);
Parameters

hdc

Handle to the device context.

lpRamp

Pointer to a set of three arrays of 256-byte elements. These arrays are the mapping between color values in the frame buffer and DAC values. The first array is red, the next is green, and the final one is blue.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

Direct color display modes do not use color lookup tables. The direct color modes are usually 16-, 24-, or 32-bit. Not all direct color video boards support loadable gamma ramps. This function succeeds only for those drivers that support loadable gamma ramps in hardware.


GetDialogBaseUnits
 GetDialogBaseUnits  QuickInfo  Overview  Group

The GetDialogBaseUnits function returns the dialog box base units used by Windows to create dialog boxes. Both Windows and applications use these units to convert the width and height of dialog boxes and controls from dialog units, as given in dialog box templates, to pixels, and vice versa.

LONG GetDialogBaseUnits(VOID)

Parameters

This function has no parameters.

Return Value

The return value is a 32-bit value that contains the dialog base units. The low-order word of the return value contains the horizontal dialog box base unit, and the high-order word contains the vertical dialog box base unit.

Remarks

The horizontal base unit 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. Furthermore, each horizontal base unit is equal to 4 horizontal dialog units; each vertical base unit is equal to 8 vertical dialog units. Therefore, to convert dialog units to pixels, an application applies the following formulas:

pixelX = (dialogunitX * baseunitX) / 4

pixelY = (dialogunitY * baseunitY) / 8

Similarly, to convert from pixels to dialog units, an application applies the following formulas:

dialogunitX = (pixelX * 4) / baseunitX

dialogunitY = (pixelY * 8) / baseunitY

The multiplication is performed before the division to avoid rounding problems if base units are not divisible by 4 or 8.

See Also

MapDialogRect


GetDIBColorTable
 GetDIBColorTable  QuickInfo  Overview  Group

The GetDIBColorTable function retrieves RGB (red, green, blue) color values from a range of entries in the color table of the DIB section bitmap that is currently selected into a specified device context.

UINT GetDIBColorTable(

HDC hdc,	// handle of device context whose DIB is of interest
UINT uStartIndex,	// color table index of first entry to retrieve
UINT cEntries,	// number of color table entries to retrieve
RGBQUAD *pColors	// pointer to buffer that receives color table entries
);
Parameters

hdc

Specifies a device context. A DIB section bitmap must be selected into this device context.

uStartIndex

A zero-based color table index that specifies the first color table entry to retrieve.

cEntries

Specifies the number of color table entries to retrieve.

pColors

Points to a buffer that receives an array of RGBQUAD data structures containing color information from the DIB's color table. The buffer must be large enough to contain as many RGBQUAD data structures as the value of cEntries.

Return Value

If the function succeeds, the return value is the number of color table entries that the function retrieves.

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

Remarks

The GetDIBColorTable function should be called to retrieve the color table for DIB section bitmaps that use 1, 4, or 8 bits per pixel. The biBitCount member of a bitmap's associated BITMAPINFOHEADER structure specifies the number of bits per pixel. DIB section bitmaps with a biBitCount value greater than 8 do not have a color table, but they do have associated color masks. Call the GetObject function to retrieve those color masks.

See Also

BITMAPINFOHEADER, CreateDIBSection, DIBSECTION, GetObject, RGBQUAD, SetDIBColorTable


GetDIBits
 GetDIBits  QuickInfo  Overview  Group

The GetDIBits function retrieves the bits of the specified bitmap and copies them into a buffer using the specified format.

int GetDIBits(

HDC  hdc,	// handle of device context
HBITMAP  hbmp,	// handle of bitmap
UINT  uStartScan,	// first scan line to set in destination bitmap
UINT  cScanLines,	// number of scan lines to copy
LPVOID  lpvBits,	// address of array for bitmap bits
LPBITMAPINFO  lpbi,	// address of structure with bitmap data
UINT  uUsage	// RGB or palette index
);
Parameters

hdc

Identifies the device context.

hbmp

Identifies the bitmap.

uStartScan

Specifies the first scan line to retrieve.

cScanLines

Specifies the number of scan lines to retrieve.

lpvBits

Points to a buffer to receive the bitmap data. If this parameter is NULL, the function passes the dimensions and format of the bitmap to the BITMAPINFO structure pointed to by the lpbi parameter.

lpbi

Points to a BITMAPINFO structure that specifies the desired format for the device-independent bitmap (DIB) data.

uUsage

Specifies the format of the bmiColors member of the BITMAPINFO structure. It must be one of the following values:

Value	Meaning
DIB_PAL_COLORS	The color table should consist of an array of 16-bit indices into the current logical palette.
DIB_RGB_COLORS	The color table should consist of literal red, green, blue (RGB) values.
Return Value

If the lpvBits parameter is non-NULL and the function succeeds, the return value is the number of scan lines copied from the bitmap.

Windows 95:

If the lpvBits parameter is NULL and GetDIBits successfully fills the BITMAPINFO structure, the return value is the total number of scan lines in the bitmap.

Windows NT:

If the lpvBits parameter is NULL and GetDIBits successfully fills the BITMAPINFO structure, the return value is non-zero.

If the function fails, the return value is zero.

Remarks

If the requested format for the DIB matches its internal format, the RGB values for the bitmap are copied. If the requested format doesn't match the internal format, a color table is synthesized. The following table describes the color table synthesized for each format.

Value	Meaning
1_BPP	The color table consists of a black and a white entry.
4_BPP	The color table consists of a mix of colors identical to the standard VGA palette.
8_BPP	The color table consists of a general mix of 256 colors defined by GDI. (Included in these 256 colors are the 20 colors found in the default logical palette.)
24_BPP	No color table is returned.
If the lpvBits parameter is a valid pointer, the first six members of the BITMAPINFOHEADER structure must be initialized to specify the size and format of the DIB. Note that a bottom-up DIB is specified by setting the height to a positive number, while a top-down DIB is specified by setting the height to a negative number. The bitmap's color table will be appended to the BITMAPINFO structure.

If lpvBits is NULL, GetDIBits examines the first member of the first structure pointed to by lpbi. This member must specify the size, in bytes, of a BITMAPCOREHEADER or a BITMAPINFOHEADER structure. The function uses the specified size to determine how the remaining members should be initialized.

If lpvBits is NULL and the bit count member of BITMAPINFO is initialized to zero, GetDIBits fills in BITMAPINFOHEADER or BITMAPCOREHEADER without the color table. This technique can be used to query bitmap attributes.

The bitmap identified by the hbmp parameter must not be selected into a device context when the application calls this function.

The origin for a bottom-up DIB is the lower-left corner of the bitmap; the origin for a top-down DIB is the upper-left corner.

See Also

BITMAPCOREHEADER, BITMAPINFO, BITMAPINFOHEADER, SetDIBits


GetDiskFreeSpace
 GetDiskFreeSpace  QuickInfo  Overview  Group

The GetDiskFreeSpace function retrieves information about the specified disk, including the amount of free space on the disk.

BOOL GetDiskFreeSpace(

LPCTSTR  lpRootPathName,	// address of root path
LPDWORD  lpSectorsPerCluster,	// address of sectors per cluster
LPDWORD  lpBytesPerSector,	// address of bytes per sector
LPDWORD  lpNumberOfFreeClusters,	// address of number of free clusters
LPDWORD  lpTotalNumberOfClusters	// address of total number of clusters
);
Parameters

lpRootPathName

Points to a null-terminated string that specifies the root directory of the disk to return information about. If lpRootPathName is NULL, the function uses the root of the current directory.

lpSectorsPerCluster

Points to a variable for the number of sectors per cluster.

lpBytesPerSector

Points to a variable for the number of bytes per sector.

lpNumberOfFreeClusters

Points to a variable for the total number of free clusters on the disk.

lpTotalNumberOfClusters

Points to a variable for the total number of clusters on the disk.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

GetDriveType


GetDlgCtrlID
 GetDlgCtrlID  QuickInfo  Overview  Group

The GetDlgCtrlID function returns the identifier of the specified control.

int GetDlgCtrlID(

HWND  hwndCtl	// handle of control
);
Parameters

hwndCtl

Identifies the control.

Return Value

If the function succeeds, the return value is the identifier of the control.

If the function fails, the return value is NULL. An invalid value for the hwndCtl parameter, for example, will cause the function to fail.

Remarks

GetDlgCtrlID accepts child window handles as well as handles of controls in dialog boxes. An application sets the identifier for a child window when it creates the window by assigning the identifier value to the hmenu parameter when calling the CreateWindow or CreateWindowEx function.

Although GetDlgCtrlID may return a value if hwndCtl identifies a top-level window, top-level windows cannot have identifiers and such a return value is never valid.

See Also

CreateWindow, CreateWindowEx, GetDlgItem


GetDlgItem
 GetDlgItem  QuickInfo  Overview  Group

The GetDlgItem function retrieves the handle of a control in the specified dialog box.

HWND GetDlgItem(

HWND  hDlg,	// handle of dialog box
int  nIDDlgItem	// identifier of control
);
Parameters

hDlg

Identifies the dialog box that contains the control.

nIDDlgItem

Specifies the identifier of the control to be retrieved.

Return Value

If the function succeeds, the return value is the window handle of the given control.

If the function fails, the return value is NULL, indicating an invalid dialog box handle or a nonexistent control.

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.

See Also

CreateWindow, CreateWindowEx, GetDlgItemInt, GetDlgItemText


GetDlgItemInt
 GetDlgItemInt  QuickInfo  Overview  Group

The GetDlgItemInt function translates the text of a specified control in a dialog box into an integer value.

UINT GetDlgItemInt(

HWND  hDlg,	// handle to dialog box
int  nIDDlgItem,	// control identifier
BOOL*  lpTranslated,	// points to variable to receive success/failure indicator
BOOL  bSigned	// specifies whether value is signed or unsigned
);
Parameters

hDlg

Handle to the dialog box that contains the control of interest.

nIDDlgItem

Dialog item identifier that specifies the control whose text is to be translated.

lpTranslated

Points to a Boolean variable that receives a function success/failure value. TRUE indicates success, FALSE indicates failure.

This parameter is optional: it can be NULL. In that case, the function returns no information about success or failure.

bSigned

Specifies whether the function should examine the text for a minus sign at the beginning and return a signed integer value if it finds one. TRUE specifies that this should be done, FALSE that it should not.

Return Value

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.

Remarks

The GetDlgItemInt function retrieves the text of the given control by sending the control a WM_GETTEXT message. The function translates the retrieved text by stripping any extra spaces at the beginning of the text and then converting the decimal digits. The function stops translating when it reaches the end of the text or encounters a nonnumeric character.

If the bSigned parameter is TRUE, the GetDlgItemInt function checks for a minus sign (−) at the beginning of the text and translates the text into a signed integer value. Otherwise, the function creates an unsigned integer value.

The GetDlgItemInt function returns zero if the translated value is greater than INT_MAX (for signed numbers) or UINT_MAX (for unsigned numbers).

See Also

GetDlgCtrlID, GetDlgItem, GetDlgItemText, SetDlgItemInt


GetDlgItemText
 GetDlgItemText  QuickInfo  Overview  Group

The GetDlgItemText function retrieves the title or text associated with a control in a dialog box.

UINT GetDlgItemText(

HWND  hDlg,	// handle of dialog box
int  nIDDlgItem,	// identifier of control
LPTSTR  lpString,	// address of buffer for text
int  nMaxCount	// maximum size of string
);
Parameters

hDlg

Identifies the dialog box that contains the control.

nIDDlgItem

Specifies the identifier of the control whose title or text is to be retrieved.

lpString

Points to the buffer to receive the title or text.

nMaxCount

Specifies the maximum length, in characters, of the string to be copied to the buffer pointed to by lpString. If the length of the string exceeds the limit, the string is truncated.

Return Value

If the function succeeds, the return value specifies the number of characters copied to the buffer, not including the terminating null character.

If the function fails, the return value is zero.

Remarks

The GetDlgItemText function sends a WM_GETTEXT message to the control.

See Also

GetDlgItemInt, SetDlgItemInt, SetDlgItemText, WM_GETTEXT


GetDOSEnvironment
 GetDOSEnvironment  Overview  Group

The GetDOSEnvironment function is not implemented in the Win32 API. Win32-based applications should use the GetEnvironmentStrings function.


GetDoubleClickTime
 GetDoubleClickTime  QuickInfo  Overview  Group

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 Value

If the function succeeds, the return value specifies the current double-click time, in milliseconds.

See Also

SetDoubleClickTime


GetDriveType
 GetDriveType  QuickInfo  Overview  Group

The GetDriveType function determines whether a disk drive is a removable, fixed, CD-ROM, RAM disk, or network drive.

UINT GetDriveType(

LPCTSTR  lpRootPathName	// address of root path
);
Parameters

lpRootPathName

Points to a null-terminated string that specifies the root directory of the disk to return information about. If lpRootPathName is NULL, the function uses the root of the current directory.

Return Value

The return value specifies the type of drive. It can be one of the following values:

Value	Meaning
0	The drive type cannot be determined.
1	The root directory does not exist.
DRIVE_REMOVABLE	The drive can be removed from the drive.
DRIVE_FIXED	The disk cannot be removed from the drive.
DRIVE_REMOTE	The drive is a remote (network) drive.
DRIVE_CDROM	The drive is a CD-ROM drive.
DRIVE_RAMDISK	The drive is a RAM disk.
See Also

GetDiskFreeSpace


GetEffectiveClientRect [New - Windows NT]
 GetEffectiveClientRect  QuickInfo  Overview  Group

[New - Windows NT]

The GetEffectiveClientRect function calculates the dimensions of a rectangle in the client area. This function has limited utility.

void GetEffectiveClientRect(

HWND  hWnd,
LPRECT  lprc,
LPINT  lpInfo
);
Parameters

hWnd

Handle to the window that has the client area to check.

lprc

Pointer to a RECT structure that receives the dimensions of the rectangle.

lpInfo

Pointer to an array of 16-bit control identifiers for controls in the client area. Each control requires two array elements. The first element must be nonzero, and the second element must be the control identifier. The last element in the array must be zero.

Return Value

This function does not return a value.

See Also

RECT


GetEnhMetaFile
 GetEnhMetaFile  QuickInfo  Overview  Group

The GetEnhMetaFile function creates a handle that identifies the enhanced-format metafile stored in the specified file.

HENHMETAFILE GetEnhMetaFile(

LPCTSTR  lpszMetaFile	// address of metafile name
);
Parameters

lpszMetaFile

Points to the null-terminated string that specifies the name of an enhanced metafile.

Return Value

If the function succeeds, the return value is a handle of the enhanced metafile.

If the function fails, the return value is NULL.

Remarks

When the application no longer needs an enhanced-metafile handle, it should delete the handle by calling the DeleteEnhMetaFile function.

A Windows-format metafile must be converted to the enhanced format before it can be processed by the GetEnhMetaFile function. To convert the file, use the SetWinMetaFileBits function.

Where text arguments must use Unicode characters, use this function as a wide-character function. Where text arguments must use characters from the Windows 3.x character set, use this function as an ANSI function.

Windows 95 only: The maximum length of the description string for an enhanced metafile is 16,384 bytes.

See Also

DeleteEnhMetaFile, GetEnhMetaFile, SetWinMetaFileBits


GetEnhMetaFileBits
 GetEnhMetaFileBits  QuickInfo  Overview  Group

The GetEnhMetaFileBits function retrieves the contents of the specified enhanced-format metafile and copies them into a buffer.

UINT GetEnhMetaFileBits(

HENHMETAFILE  hemf,	// handle of metafile
UINT  cbBuffer,	// size of data buffer, in bytes
LPBYTE  lpbBuffer	// address of data buffer
);
Parameters

hemf

Identifies the enhanced metafile.

cbBuffer

Specifies the size, in bytes, of the buffer to receive the data.

lpbBuffer

Points to the buffer to receive the metafile data. The buffer must be sufficiently large to contain the data. If lpbBuffer is NULL, the function returns the size necessary to hold the data.

Return Value

If the function succeeds and the buffer pointer is NULL, the return value is the size of the enhanced metafile, in bytes.

If the function succeeds and the buffer pointer is a valid pointer, the return value is the number of bytes copied to the buffer.

If the function fails, the return value is zero.

Remarks

After the enhanced-metafile bits are retrieved, they can be used to create a memory-based metafile by calling the SetEnhMetaFileBits function.

The GetEnhMetaFileBits function does not invalidate the enhanced-metafile handle. The application must call the DeleteEnhMetaFile function to delete the handle when it is no longer needed.

The metafile contents retrieved by this function are in the enhanced format. To retrieve the metafile contents in the Windows format, use the GetWinMetaFileBits function.

See Also

DeleteEnhMetaFile, GetWinMetaFileBits, SetEnhMetaFileBits


GetEnhMetaFileDescription
 GetEnhMetaFileDescription  QuickInfo  Overview  Group

The GetEnhMetaFileDescription function retrieves an optional text description from an enhanced-format metafile and copies the string to the specified buffer.

UINT GetEnhMetaFileDescription(

HENHMETAFILE  hemf,	// handle of enhanced metafile
UINT  cchBuffer,	// size of text buffer, in characters
LPTSTR  lpszDescription	// address of text buffer
);
Parameters

hemf

Identifies the enhanced metafile.

cchBuffer

Specifies the size, in characters, of the buffer to receive the data. Only this many characters will be copied.

lpszDescription

Points to the buffer to receive the optional text description.

Return Value

If the optional text description exists and the buffer pointer is NULL, the return value is the length of the text string, in characters.

If the optional text description exists and the buffer pointer is a valid pointer, the return value is the number of characters copied into the buffer.

If the optional text description does not exist, the return value is zero.

If the function fails, the return value is GDI_ERROR.

Remarks

The optional text description contains two strings, the first identifying the application that created the enhanced metafile and the second identifying the picture contained in the metafile. The strings are separated by a null character and terminated with two null characters — for example, "XYZ Graphics Editor\0Bald Eagle\0\0" where \0 represents the null character.

Where text arguments must use Unicode characters, use this function as a wide-character function. Where text arguments must use characters from the Windows 3.x character set, use this function as an ANSI function.

Windows 95 only: The maximum length of the description string for an enhanced metafile is 16,384 bytes.

See Also

CreateEnhMetaFile


GetEnhMetaFileHeader
 GetEnhMetaFileHeader  QuickInfo  Overview  Group

The GetEnhMetaFileHeader function retrieves the record containing the header for the specified enhanced-format metafile.

UINT GetEnhMetaFileHeader(

HENHMETAFILE  hemf,	// handle of enhanced metafile
UINT  cbBuffer,	// size of buffer, in bytes
LPENHMETAHEADER  lpemh	// address of buffer to receive data
);
Parameters

hemf

Identifies the enhanced metafile for which the header is to be retrieved.

cbBuffer

Specifies the size, in bytes, of the buffer to receive the data. Only this many bytes will be copied.

lpemh

Points to an ENHMETAHEADER structure to receive the header record. If this parameter is NULL, the function returns the size of the header record.

Return Value

If the function succeeds and the structure pointer is NULL, the return value is the size of the record that contains the header; if the structure pointer is a valid pointer, the return value is the number of bytes copied. Otherwise, it is zero.

Remarks

An enhanced-metafile header contains such information as the metafile's size, in bytes; the dimensions of the picture stored in the metafile; the number of records stored in the metafile; the offset to the optional text description; the size of the optional palette, and the resolution of the device on which the picture was created.

The record that contains the enhanced-metafile header is always the first record in the metafile.

Windows 95 only: The maximum length of the description string for an enhanced metafile is 16,384 bytes.

See Also

ENHMETAHEADER, PlayEnhMetaFile


GetEnhMetaFilePaletteEntries
 GetEnhMetaFilePaletteEntries  QuickInfo  Overview  Group

The GetEnhMetaFilePaletteEntries function retrieves optional palette entries from the specified enhanced metafile.

UINT GetEnhMetaFilePaletteEntries(

HENHMETAFILE  hemf,	// handle of enhanced metafile
UINT  cEntries,	// count of palette entries
LPPALETTEENTRY  lppe	// address of palette-entry array
);
Parameters

hemf

Identifies the enhanced metafile.

cEntries

Specifies the number of entries to be retrieved from the optional palette.

lppe

Points to an array of PALETTEENTRY structures to receive the palette colors. The array must contain at least as many structures as there are entries specified by the cEntries parameter.

Return Value

If the array pointer is NULL and the enhanced metafile contains an optional palette, the return value is the number of entries in the enhanced metafile's palette; if the array pointer is a valid pointer and the enhanced metafile contains an optional palette, the return value is the number of entries copied; if the metafile does not contain an optional palette, the return value is zero. Otherwise, the return value is GDI_ERROR.

Remarks

An application can store an optional palette in an enhanced metafile by calling the CreatePalette and SetPaletteEntries functions before creating the picture and storing it in the metafile. By doing this, the application can achieve consistent colors when the picture is displayed on a variety of devices.

An application that displays a picture stored in an enhanced metafile can call the GetEnhMetaFilePaletteEntries function to determine whether the optional palette exists. If it does, the application can call the GetEnhMetaFilePaletteEntries function a second time to retrieve the palette entries and then create a logical palette (by using the CreatePalette function), select it into its device context (by using the SelectPalette function), and then realize it (by using the RealizePalette function). After the logical palette has been realized, calling the PlayEnhMetaFile function displays the picture using its original colors.

See Also

CreatePalette, PALETTEENTRY, PlayEnhMetaFile, RealizePalette, SelectPalette


GetEnvironmentStrings
 GetEnvironmentStrings  QuickInfo  Overview  Group

The GetEnvironmentStrings function returns the address of the environment block for the current process. This function replaces the GetDOSEnvironment function.

LPVOID GetEnvironmentStrings(VOID)

Parameters

This function has no parameters.

Return Value

The return value is a pointer to an environment block for the current process.

Remarks

Do not use the return value of GetEnvironmentStrings to get or set environment variables. Instead, use the GetEnvironmentVariable and SetEnvironmentVariable functions to access the environment variables within this block. When the block is no longer needed, it should be freed by calling FreeEnvironmentStrings.

A process can use this function's return value to specify the environment address used by the CreateProcess function.

See Also

CreateProcess, GetEnvironmentVariable, SetEnvironmentVariable, FreeEnvironmentStrings


GetEnvironmentVariable
 GetEnvironmentVariable  QuickInfo  Overview  Group

The GetEnvironmentVariable function retrieves the value of the specified variable from the environment block of the calling process. The value is in the form of a null-terminated string of characters.

DWORD GetEnvironmentVariable(

LPCTSTR  lpName,	// address of environment variable name
LPTSTR  lpBuffer,	// address of buffer for variable value
DWORD  nSize	// size of buffer, in characters
);
Parameters

lpName

Points to a null-terminated string that specifies the environment variable.

lpBuffer

Points to a buffer to receive the value of the specified environment variable.

nSize

Specifies the size, in characters, of the buffer pointed to by the lpBuffer parameter.

Return Value

If the function succeeds, the return value is the number of characters stored into the buffer pointed to by lpBuffer, not including the terminating null character.

If the specified environment variable name was not found in the environment block for the current process, the return value is zero.

If the buffer pointed to by lpBuffer is not large enough, the return value is the buffer size, in characters, required to hold the value string and its terminating null character.

See Also

GetEnvironmentStrings, SetEnvironmentVariable


GetExceptionCode
 GetExceptionCode  QuickInfo  Overview  Group

The GetExceptionCode function retrieves a code that identifies the type of exception that occurred. The function can be called only from within the filter expression or exception-handler block of a try-except exception handler.

DWORD GetExceptionCode(VOID)

Parameters

This function has no parameters.

Return Value

The return value identifies the type of exception. Following are the exception codes likely to occur due to common programming errors:

Value	Meaning
EXCEPTION_ACCESS_VIOLATION
	The thread attempted to read from or write to a virtual address for which it does not have the appropriate access.
EXCEPTION_BREAKPOINT
	A breakpoint was encountered.
EXCEPTION_DATATYPE_MISALIGNMENT
	The thread attempted to read or write data that is misaligned on hardware that does not provide alignment. For example, 16-bit values must be aligned on 2-byte boundaries, 32-bit values on 4-byte boundaries, and so on.
EXCEPTION_SINGLE_STEP
	A trace trap or other single-instruction mechanism signaled that one instruction has been executed.
EXCEPTION_ARRAY_BOUNDS_EXCEEDED
	The thread attempted to access an array element that is out of bounds, and the underlying hardware supports bounds checking.
EXCEPTION_FLT_DENORMAL_OPERAND
	One of the operands in a floating-point operation is denormal. A denormal value is one that is too small to represent as a standard floating-point value.
EXCEPTION_FLT_DIVIDE_BY_ZERO
	The thread attempted to divide a floating-point value by a floating-point divisor of zero.
EXCEPTION_FLT_INEXACT_RESULT
	The result of a floating-point operation cannot be represented exactly as a decimal fraction.
EXCEPTION_FLT_INVALID_OPERATION
	This exception represents any floating-point exception not included in this list.
EXCEPTION_FLT_OVERFLOW
	The exponent of a floating-point operation is greater than the magnitude allowed by the corresponding type.
EXCEPTION_FLT_STACK_CHECK
	The stack overflowed or underflowed as the result of a floating-point operation.
EXCEPTION_FLT_UNDERFLOW
	The exponent of a floating-point operation is less than the magnitude allowed by the corresponding type.
EXCEPTION_INT_DIVIDE_BY_ZERO
	The thread attempted to divide an integer value by an integer divisor of zero.
EXCEPTION_INT_OVERFLOW
	The result of an integer operation caused a carry out of the most significant bit of the result.
EXCEPTION_PRIV_INSTRUCTION
	The thread attempted to execute an instruction whose operation is not allowed in the current machine mode.
EXCEPTION_NONCONTINUABLE_EXCEPTION
	The thread attempted to continue execution after a noncontinuable exception occurred.
Remarks

The GetExceptionCode function can be called only from within the filter expression or exception-handler block of a try-except statement. The filter expression is evaluated if an exception occurs during execution of the try block, and it determines whether the except block is executed. The following example shows the structure of a try-except statement.

try {

    /* try block */

}

except (filter-expression) {

    /* exception handler block */

}

The filter expression can invoke a filter function. The filter function cannot call GetExceptionCode. However, the return value of GetExceptionCode can be passed as a parameter to a filter function. The return value of the GetExceptionInformation function can also be passed as a parameter to a filter function. GetExceptionInformation returns a pointer to a structure that includes the exception-code information.

In the case of nested try-except statements, each statement's filter expression is evaluated until one is evaluated as EXCEPTION_EXECUTE_HANDLER or EXCEPTION_CONTINUE_EXECUTION. Each filter expression can invoke GetExceptionCode to get the exception code.

The exception code returned is the code generated by a hardware exception, or the code specified in the RaiseException function for a software-generated exception.

See Also

GetExceptionInformation, RaiseException


GetExceptionInformation
 GetExceptionInformation  QuickInfo  Overview  Group

The GetExceptionInformation function retrieves a machine-independent description of an exception, and information about the machine state that existed for the thread when the exception occurred. This function can be called only from within the filter expression of a try-except exception handler.

LPEXCEPTION_POINTERS GetExceptionInformation(VOID)

Parameters

This function has no parameters.

Return Value

The return value is a pointer to an EXCEPTION_POINTERS structure that contains pointers to two other structures: an EXCEPTION_RECORD structure containing a description of the exception, and a CONTEXT structure containing the machine-state information.

Remarks

The filter expression (from which the function is called) is evaluated if an exception occurs during execution of the try block, and it determines whether the except block is executed. The following example shows the structure of a try-except statement.

try {

    /* try block */

}

except (filter-expression) {

    /* exception handler block */

}

The filter expression can invoke a filter function. The filter function cannot call GetExceptionInformation. However, the return value of GetExceptionInformation can be passed as a parameter to a filter function.

To pass the EXCEPTION_POINTERS information to the exception-handler block, the filter expression or filter function must copy the pointer or the data to safe storage that the handler can later access.

In the case of nested try-except statements, each statement's filter expression is evaluated until one is evaluated as EXCEPTION_EXECUTE_HANDLER or EXCEPTION_CONTINUE_EXECUTION. Each filter expression can invoke GetExceptionInformation to get exception information.

See Also

CONTEXT, EXCEPTION_POINTERS, EXCEPTION_RECORD, GetExceptionCode


GetExitCodeProcess
 GetExitCodeProcess  QuickInfo  Overview  Group

The GetExitCodeProcess function retrieves the termination status of the specified process.

BOOL GetExitCodeProcess(

HANDLE  hProcess,	// handle to the process
LPDWORD  lpExitCode	// address to receive termination status
);
Parameters

hProcess

Identifies the process. The handle must have PROCESS_QUERY_INFORMATION access.

lpExitCode

Points to a 32-bit variable to receive the process termination status.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

If the specified process has not terminated, the termination status returned is STILL_ACTIVE. If the process has terminated, the termination status returned may be one of the following:

•	The exit value specified in the ExitProcess or TerminateProcess function.

•	The return value from the main or WinMain function of the process.

•	The exception value for an unhandled exception that caused the process to terminate.

See Also

ExitProcess, ExitThread, TerminateProcess, WinMain


GetExitCodeThread
 GetExitCodeThread  QuickInfo  Overview  Group

The GetExitCodeThread function retrieves the termination status of the specified thread.

BOOL GetExitCodeThread(

HANDLE  hThread,	// handle to the thread
LPDWORD  lpExitCode	// address to receive termination status
);
Parameters

hThread

Identifies the thread. The handle must have THREAD_QUERY_INFORMATION access.

lpExitCode

Points to a 32-bit variable to receive the thread termination status.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

If the specified thread has not terminated, the termination status returned is STILL_ACTIVE. If the thread has terminated, the termination status returned may be one of the following:

•	The exit value specified in the ExitThread or TerminateThread function.

•	The return value from the thread function.

•	The exit value of the thread's process.

See Also

ExitThread, GetExitCodeProcess, TerminateThread


GetExpandedName
 GetExpandedName  QuickInfo  Overview  Group

The GetExpandedName function retrieves the original name of a compressed file, if the file was compressed by using the Microsoft File Compression Utility (COMPRESS.EXE) and the /r option was specified.

INT GetExpandedName(

LPTSTR  lpszSource,	// address of name of compressed file
LPTSTR  lpszBuffer	// address of buffer for original filename
);
Parameters

lpszSource

Points to a string that specifies the name of a compressed file.

lpszBuffer

Points to a buffer that receives the name of the compressed file.

Return Value

If the function succeeds, the return value is 1.

If the function fails, the return value is LZERROR_BADVALUE.

Note that GetExpandedName calls neither SetLastError nor SetLastErrorEx; thus, its failure does not affect a thread's last-error code.

Remarks

The contents of the buffer pointed to by the lpszBuffer parameter is the original filename if the file was compressed by using the /r option. If the /r option was not used, this function duplicates the name in the lpszSource parameter into the lpszBuffer buffer.


GetFileAttributes
 GetFileAttributes  QuickInfo  Overview  Group

The GetFileAttributes function returns attributes for a specified file or directory.

DWORD GetFileAttributes(

LPCTSTR  lpFileName	// address of the name of a file or directory
);
Parameters

lpFileName

Points to a null-terminated string that specifies the name of a file or directory.

Windows NT

There is a default string size limit for paths of MAX_PATH characters. This limit is related to how the GetFileAttributes function parses paths. An application can transcend this limit and send in paths longer than MAX_PATH characters by calling the wide (W) version of GetFileAttributes and prepending "\\?\" to the path. The "\\?\" tells the function to turn off path parsing; it lets paths longer than MAX_PATH be used with GetFileAttributesW. This also works with UNC names. The "\\?\" is ignored as part of the path. For example, "\\?\C:\myworld\private" is seen as "C:\myworld\private", and "\\?\UNC\bill_g_1\hotstuff\coolapps" is seen as "\\bill_g_1\hotstuff\coolapps".

Windows 95

The lpFileName string must not exceed MAX_PATH characters. Windows 95 does not support the "\\?\" prefix.

Return Value

If the function succeeds, the return value contains the attributes of the specified file or directory.

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

The attributes can be one or more of the following values:

Value	Meaning
FILE_ATTRIBUTE_ARCHIVE	The file or directory is an archive file or directory. Applications use this flag to mark files for backup or removal.
FILE_ATTRIBUTE_COMPRESSED	The file or directory is compressed. For a file, this means that all of the data in the file is compressed. For a directory, this means that compression is the default for newly created files and subdirectories.
FILE_ATTRIBUTE_DIRECTORY	The "file or directory" is a directory.
FILE_ATTRIBUTE_HIDDEN	The file or directory is hidden. It is not included in an ordinary directory listing.
FILE_ATTRIBUTE_NORMAL	The file or directory has no other attributes set. This attribute is valid only if used alone.
FILE_ATTRIBUTE_READONLY	The file or directory is read-only. Applications can read the file but cannot write to it or delete it. In the case of a directory, applications cannot delete it.
FILE_ATTRIBUTE_SYSTEM	The file or directory is part of, or is used exclusively by, the operating system.
See Also

DeviceIOControl, FindFirstFile, FindNextFile, SetFileAttributes


GetFileInformationByHandle
 GetFileInformationByHandle  QuickInfo  Overview  Group

The GetFileInformationByHandle function retrieves information about the specified file.

BOOL GetFileInformationByHandle(

HANDLE  hFile,	// handle of file
LPBY_HANDLE_FILE_INFORMATION  lpFileInformation,	// address of structure
);
Parameters

hFile

Identifies the file for which information is returned.

lpFileInformation

Points to a BY_HANDLE_FILE_INFORMATION structure that receives the file information. The structure can be used in subsequent calls to GetFileInformationByHandle to refer to the information about the file.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

Depending on the underlying network components of the operating system and the type of server connected to, the GetFileInformationByHandle function may fail, return partial information, or full information for the given file. In general, you should not use GetFileInformationByHandle unless your application is intended to be run on a limited set of operating system configurations.

See Also

BY_HANDLE_FILE_INFORMATION


GetFileResource
 GetFileResource  Overview  Group

The GetFileResource function is not implemented in the Win32 API.


GetFileResourceSize
 GetFileResourceSize  Overview  Group

The GetFileResourceSize function is is not implemented in the Win32 API.


GetFileSecurity
 GetFileSecurity  QuickInfo  Overview  Group

The GetFileSecurity function obtains specified information about the security of a file or directory. The information obtained is constrained by the caller's access rights and privileges.

BOOL GetFileSecurity(

LPCTSTR  lpFileName,	// address of string for file name
SECURITY_INFORMATION  RequestedInformation,	// requested information
PSECURITY_DESCRIPTOR  pSecurityDescriptor,	// address of security descriptor
DWORD  nLength,	// size of security descriptor buffer
LPDWORD  lpnLengthNeeded	// address of required size of buffer
);
Parameters

lpFileName

Points to a null-terminated string specifying the file or directory for which security information is retrieved.

RequestedInformation

Specifies a SECURITY_INFORMATION structure that identifies the security information being requested.

pSecurityDescriptor

Points to a buffer that receives a copy of the security descriptor of the object specified by the lpFileName parameter. The calling process must have the right to view the specified aspects of the object's security status. The SECURITY_DESCRIPTOR structure is returned in self-relative format.

nLength

Specifies the size, in bytes, of the buffer pointed to by the pSecurityDescriptor parameter.

lpnLengthNeeded

Points to a variable the function sets to zero if the file descriptor is copied successfully. If the buffer is too small for the security descriptor, this variable receives the number of bytes required. If this variable's value is greater than that of the nLength parameter when the function returns, none of the security descriptor is copied to the buffer.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

In order to read the security descriptor of a file or directory, the calling process must have READ_CONTROL access or be the owner of the file or directory. Additionally, the caller must have the SE_SECURITY_NAME privilege to read the system access-control list.

See Also

GetKernelObjectSecurity, GetPrivateObjectSecurity, GetUserObjectSecurity, SECURITY_DESCRIPTOR, SECURITY_INFORMATION, SetFileSecurity


GetFileSize
 GetFileSize  QuickInfo  Overview  Group

The GetFileSize function retrieves the size, in bytes, of the specified file.

DWORD GetFileSize(

HANDLE  hFile,	// handle of file to get size of
LPDWORD  lpFileSizeHigh,	// address of high-order word for file size
);
Parameters

hFile

Specifies an open handle of the file whose size is being returned. The handle must have been created with either GENERIC_READ or GENERIC_WRITE access to the file.

lpFileSizeHigh

Points to the variable where the high-order word of the file size is returned. This parameter can be NULL if the application does not require the high-order word.

Return Value

If the function succeeds, the return value is the low-order doubleword of the file size, and, if lpFileSizeHigh is non-NULL, the function puts the high-order doubleword of the file size into the variable pointed to by that parameter.

If the function fails and lpFileSizeHigh is NULL, the return value is 0xFFFFFFFF. To get extended error information, call GetLastError.

If the function fails and lpFileSizeHigh is non-NULL, the return value is 0xFFFFFFFF and GetLastError will return a value other than NO_ERROR.

Remarks

You cannot use the GetFileSize function with a handle of a nonseeking device such as a pipe or a communications device. To determine the file type for hFile, use the GetFileType function.

The GetFileSize function obtains the uncompressed size of a file. Use the GetCompressedFileSize function to obtain the compressed size of a file.

Note that if the return value is 0xFFFFFFFF and lpFileSizeHigh is non-NULL, an application must call GetLastError to determine whether the function has succeeded or failed. The following sample code illustrates this point:

//

// Case One: calling the function with

//           lpFileSizeHigh == NULL

// Try to obtain hFile's size

dwSize = GetFileSize (hFile, NULL) ;

// If we failed ...

if (dwSize == 0xFFFFFFFF) {

    // Obtain the error code.

    dwError = GetLastError() ;

    // Deal with that failure.

    .

    .

    .

    } // End of error handler

//

// Case Two: calling the function with

//           lpFileSizeHigh != NULL

// Try to obtain hFile's huge size.

dwSizeLow = GetFileSize (hFile, & dwSizeHigh) ;

// If we failed ...

if (dwSizeLow == 0xFFFFFFFF

    &&

    (dwError = GetLastError()) != NO_ERROR ){

    // Deal with that failure.

    .

    .

    .

    } // End of error handler.

See Also

GetCompressedFileSize, GetFileType


GetFileTime
 GetFileTime  QuickInfo  Overview  Group

The GetFileTime function retrieves the date and time that a file was created, last accessed, and last modified.

BOOL GetFileTime(

HANDLE  hFile,	// identifies the file
LPFILETIME  lpCreationTime,	// address of creation time
LPFILETIME  lpLastAccessTime,	// address of last access time
LPFILETIME  lpLastWriteTime	// address of last write time
);
Parameters

hFile

Identifies the files for which to get dates and times. The file handle must have been created with GENERIC_READ access to the file.

lpCreationTime

Points to a FILETIME structure to receive the date and time the file was created. This parameter can be NULL if the application does not require this information.

lpLastAccessTime

Points to a FILETIME structure to receive the date and time the file was last accessed. The last access time includes the last time the file was written to, read from, or, in the case of executable files, run. This parameter can be NULL if the application does not require this information.

lpLastWriteTime

Points to a FILETIME structure to receive the date and time the file was last written to. This parameter can be NULL if the application does not require this information.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The FAT, NTFS, and HPFS file systems all support the file creation, last access, and last write time values.

Windows 95: The precision of the time for a file in a FAT file system is 2 seconds. The time precision for files in other file systems, such as those connected through a network depends on the file system but may also be limited by the remote device.

See Also

FILETIME, GetFileSize, GetFileType, SetFileTime


GetFileTitle
 GetFileTitle  QuickInfo  Overview  Group

The GetFileTitle function returns the name of the file identified by the lpszFile parameter.

short GetFileTitle(

LPCTSTR  lpszFile,	// address of full path and filename for file
LPTSTR  lpszTitle,	// address of buffer that receives filename
WORD  cbBuf	// length of buffer
);
Parameters

lpszFile

Points to the name and location of a file.

lpszTitle

Points to a buffer into which the function is to copy the name of the file.

cbBuf

Specifies the length, in characters, of the buffer pointed to by the lpszTitle parameter.

Return Value

If the function succeeds, the return value is zero. If the filename is invalid, the return value is a negative number. If the buffer pointed to by the lpszTitle parameter is too small, the return value is a positive integer that specifies the required buffer size, in characters.

Remarks

GetFileTitle returns an error value if the buffer pointed to by the lpszFile parameter contains any of the following elements:

•	An empty string

•	A string containing a wildcard (*), opening bracket ([), or closing bracket (])

•	A string that ends with a colon (:), slash mark (/), or backslash (\)

•	A string whose length exceeded the length of the buffer

•	An invalid character (for example, a space or an unprintable character)

The required buffer size includes the terminating null character.

Note that sizes are specified and received as character counts, not bytes for UNICODE; the counts are valid for both the _A and _W versions of the function.

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

Windows 95: On Windows 95, the GetFileTitle function retrieves the same text that the system would compose in displaying a filename to the user. This text is intended to be used for display purposes only and is in accordance with the user's preferences for display of filenames. There are two important implications of this enhancement. First, an application cannot expect to use the resultant text to call file system functions because it is merely a display name. Secondly, in preserving the function's "insufficient buffer" case, the return value for that codepath reflects the size of the text that would be composed in the normal case such that the caller may attempt to allocate sufficient storage and retrieve the result with a subsequent call to GetFileTitle. More generally, there is no guaranteed connection between the resultant text or return value and the characters in the original buffer passed by the application.

In porting applications to Windows 95, developers will need to update any code that relies on such behavior in previous versions of the operating system. The most common case is code that deliberately calls GetFileTitle with a NULL return buffer, passing size 0, and then uses the return value as an index into the original string. This technique is no longer supported. Applications can usually achieve similar results (and superior performance) with runtime library functions such as strrchr, wcsrchr, and _mbsrchr.

See Also

GetOpenFileName, GetSaveFileName


GetFileType
 GetFileType  QuickInfo  Overview  Group

The GetFileType function returns the type of the specified file.

DWORD GetFileType(

HANDLE  hFile	// file handle
);
Parameters

hFile

Identifies an open file handle.

Return Value

The return value is one of the following values:

Value	Meaning
FILE_TYPE_UNKNOWN	The type of the specified file is unknown.
FILE_TYPE_DISK	The specified file is a disk file.
FILE_TYPE_CHAR	The specified file is a character file, typically an LPT device or a console.
FILE_TYPE_PIPE	The specified file is either a named or anonymous pipe.
See Also

GetFileSize, GetFileTime


GetFileVersionInfo
 GetFileVersionInfo  QuickInfo  Overview  Group

The GetFileVersionInfo function returns version information about a specified file.

As with other file installation functions, GetFileVersionInfo works only with Win32 file images. It does not work with 16-bit Windows file images.

BOOL GetFileVersionInfo(

LPTSTR  lptstrFilename,	// pointer to filename string
DWORD  dwHandle,	// ignored
DWORD  dwLen,	// size of buffer
LPVOID  lpData	// pointer to buffer to receive file-version info.
);
Parameters

lptstrFilename

Pointer to a null-terminated filename string that specifies the file of interest.

dwHandle

This parameter is ignored.

dwLen

Specifies the size, in bytes, of the buffer pointed to by lpData.

Call the GetFileVersionInfoSize function to determine the size in bytes of a file's version information. dwLen 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

Pointer to a buffer to receive file-version information.

You can use this value in a subsequent call to the VerQueryValue function.

The file version information is always in Unicode format.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

GetFileVersionInfoSize, VerQueryValue, VS_VERSION_INFO


GetFileVersionInfoSize
 GetFileVersionInfoSize  QuickInfo  Overview  Group

The GetFileVersionInfoSize function determines whether the operating system can obtain version information about a specified file. If version information is available, GetFileVersionInfoSize returns the size in bytes of that information.

As with other file installation functions, GetFileVersionInfo works only with Win32 file images. It does not work with 16-bit Windows file images.

DWORD GetFileVersionInfoSize(

LPTSTR  lptstrFilename,	// pointer to filename string
LPDWORD  lpdwHandle	// pointer to variable to receive zero
);
Parameters

lptstrFilename

Pointer to a null-terminated filename string that specifies the file of interest.

lpdwHandle

Pointer to a variable that the function sets to zero.

Return Value

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

Call the GetFileVersionInfoSize function before calling the GetFileVersionInfo function.

See Also

GetFileVersionInfo, VerQueryValue


GetFocus
 GetFocus  QuickInfo  Overview  Group

The GetFocus function retrieves the handle of the keyboard focus window associated with the thread that called the function.

HWND GetFocus(VOID)

Parameters

This function has no parameters.

Return Value

If the function succeeds, the return value is the handle of the keyboard focus window associated with the calling thread. If the calling thread does not contain a keyboard focus window, the return value is NULL.

Remarks

Although a return value of NULL means the calling thread does not have a keyboard focus window, another thread may have a keyboard focus window.

See Also

GetActiveWindow, GetCapture, SetFocus, WM_KILLFOCUS, WM_SETFOCUS


GetFontData
 GetFontData  QuickInfo  Overview  Group

The GetFontData function retrieves font metric data for a TrueType font.

DWORD GetFontData(

HDC  hdc,	// handle of device context
DWORD  dwTable,	// metric table to query
DWORD  dwOffset,	// offset into table being queried
LPVOID  lpvBuffer,	// address of buffer for returned data
DWORD  cbData	// length of data to query
);
Parameters

hdc

Identifies the device context.

dwTable

Specifies the name of a font metric table from which the font data is to be retrieved. This parameter can identify one of the metric tables documented in the TrueType Font Files specification published by Microsoft Corporation. If this parameter is zero, the information is retrieved starting at the beginning of the font file.

dwOffset

Specifies the offset from the beginning of the font metric table to the location where the function should begin retrieving information. If this parameter is zero, the information is retrieved starting at the beginning of the table specified by the dwTable parameter. If this value is greater than or equal to the size of the table, an error occurs.

lpvBuffer

Points to a buffer to receive the font information. If this parameter is NULL, the function returns the size of the buffer required for the font data.

cbData

Specifies the length, in bytes, of the information to be retrieved. If this parameter is zero, GetFontData returns the size of the data specified in the dwTable parameter.

Return Value

If the function succeeds, the return value is the number of bytes returned.

If the function fails, the return value is GDI_ERROR.

Remarks

An application can sometimes use the GetFontData function to save a TrueType font with a document. To do this, the application determines whether the font can be embedded by checking the otmfsType member of the OUTLINETEXTMETRIC structure. If bit 1 of otmfsType is set, embedding is not permitted for the font. If bit 1 is clear, the font can be embedded. If bit 2 is set, the embedding is read-only. If embedding is permitted, the application can retrieve the entire font file, specifying zero for the dwTable, dwOffset, and cbData parameters.

If an application attempts to use this function to retrieve information for a non-TrueType font, an error occurs.

See Also

GetTextMetrics, OUTLINETEXTMETRIC


GetFontLanguageInfo [New - Windows 95]
 GetFontLanguageInfo  QuickInfo

[New - Windows 95]

The GetFontLanguageInfo function returns information about the currently selected font for the specified display context. Applications typically use this information and the GetCharacterPlacement function to prepare a character string for display.

DWORD GetFontLanguageInfo(

HDC hdc	// handle to a device context
);
Parameters

hdc

Handle to a display context.

Return Value

The return value identifies characteristics of the currently selected font. The function returns 0 if the font is "normalized" and can be treated as a simple Latin font; it returns GCP_ERROR if an error occurs. Otherwise, the function returns a combination of the following values:

Value	Meaning
GCP_DBCS	The character set is DBCS.
GCP_DIACRITIC	The font/language contains diacritic glyphs
FLI_GLYPHS	The font contains extra glyphs not normally accessible using the codepage. Use GetCharacterPlacement to access the glyphs. This value is for information only and is not intended to be passed to GetCharacterPlacement.
GCP_GLYPHSHAPE	The font/language contains multiple glyphs per code point or per code point combination (supports shaping and/or ligation), and the font contains advanced glyph tables to provide extra glyphs for the extra shapes. If this value is given, the lpGlyphs array must be used with the GetCharacterPlacement function and the ETO_GLYPHINDEX value must be passed to the ExtTextOut function when the string is drawn.
GCP_KASHIDA	The font/ language permits Kashidas.
GCP_LIGATE	The font/language contains ligation glyphs which can be substituted for specific character combinations.
GCP_USEKERNING	The font contains a kerning table which can be used to provide better spacing between the characters and glyphs.
GCP_REORDER	The language requires reordering for display--for example, Hebrew or Arabic.
The return value, when masked with FLI_MASK, can be passed directly to the GetCharacterPlacement function.

See Also

ExtTextOut, GetCharacterPlacement


GetForegroundWindow
 GetForegroundWindow  QuickInfo  Overview  Group

The GetForegroundWindow function returns the handle of 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 Value

The return value is the handle of the foreground window.

See Also

SetForegroundWindow


GetForm
 GetForm  QuickInfo  Overview  Group

The GetForm function initializes a FORM_INFO_1 structure with data describing the specified form for a printer.

BOOL GetForm(

HANDLE  hPrinter,	// handle of printer
LPTSTR  pFormName,	// address of form name
DWORD  Level,	// structure level
LPBYTE  pForm,	// address of structure array
DWORD  cbBuf,	// count of bytes in array
LPDWORD  pcbNeeded	// addr. of variable with count of bytes retrieved (or required)
);
Parameters

hPrinter

Identifies the printer.

pFormName

Points to a null-terminated string that specifies the name of the form.

Level

Specifies the version of the structure to which pForm points. This value must be 1.

pForm

Points to an array of bytes that receives the initialized FORM_INFO_1 structure.

cbBuf

Specifies the size, in bytes, of the pForm array.

pcbNeeded

Points to a value that specifies the number of bytes copied if the function succeeds or the number of bytes required if cbBuf is too small.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The printer handle hPrinter is obtained by calling the OpenPrinter function.

See Also

AddForm, DeleteForm, OpenPrinter


GetFreeSpace
 GetFreeSpace  QuickInfo  Overview  Group

The GetFreeSpace function is obsolete. It is provided to simplify porting of 16-bit Windows-based applications. Win32-based applications should use the GlobalMemoryStatus function.

DWORD GetFreeSpace(     WORD  w	// amount of free space
);


GetFullPathName
 GetFullPathName  QuickInfo  Overview  Group

The GetFullPathName function retrieves the full path and filename of a specified file.

DWORD GetFullPathName(

LPCTSTR  lpFileName,	// address of name of file to find path for
DWORD  nBufferLength,	// size, in characters, of path buffer
LPTSTR  lpBuffer,	// address of path buffer
LPTSTR  *lpFilePart	// address of filename in path
);
Parameters

lpFileName

Points to a null-terminated string that specifies a valid filename. This string can use either short (the 8.3 form) or long filenames.

nBufferLength

Specifies the size, in characters, of the buffer for the drive and path.

lpBuffer

Points to a buffer that contains the null-terminated string for the name of the drive and path.

lpFilePart

Points to a variable that receives the address (in lpBuffer) of the final filename component in the path. This filename component is the long filename, if any, rather than the 8.3 form of the filename.

Return Value

If the GetFullPathName function succeeds, the return value is the length, in characters, of the string copied to lpBuffer, not including the terminating null character.

If the lpBuffer buffer is too small, the return value is the size of the buffer, in characters, required to hold the path.

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

Remarks

The GetFullPathName function merges the name of the current drive and directory with the specified filename to determine the full path and filename of the specified file. It also calculates the address of the filename portion of the full path and filename. This function does not verify that the resulting path and filename are valid or that they refer to an existing file on the associated volume.

See Also

GetShortPathName, GetTempPath, SearchPath


GetGlyphOutline
 GetGlyphOutline  QuickInfo  Overview  Group

The GetGlyphOutline function retrieves the outline or bitmap for a character in the TrueType font that is selected into the specified device context.

DWORD GetGlyphOutline(

HDC  hdc,	// handle of device context
UINT  uChar,	// character to query
UINT  uFormat,	// format of data to return
LPGLYPHMETRICS  lpgm,	// address of structure for metrics
DWORD  cbBuffer,	// size of buffer for data
LPVOID  lpvBuffer,	// address of buffer for data
CONST MAT2 *  lpmat2	// address of transformation matrix structure
);
Parameters

hdc

Identifies the device context.

uChar

Specifies the character for which data is to be returned.

uFormat

Specifies the format in which the function returns the data. It can be one of the following values:

Value	Meaning
GGO_BITMAP	Returns the glyph bitmap. For information about memory allocation, see the following Remarks section.
GGO_NATIVE	Returns the curve data points in the rasterizer's native format and uses the font's design units. When this value is specified, any transformation specified in the lpMatrix parameter is ignored.
GGO_METRICS	Returns only the GLYPHMETRICS structure specified by lpgm. The other buffers are ignored. This value affects the meaning of the function's return value upon failure; see the following Return Value section.
lpgm

Points to the GLYPHMETRICS structure describing the placement of the glyph in the character cell.

cbBuffer

Specifies the size of the buffer where the function is to copy information about the outline character. If this value is zero, the function returns the required size of the buffer.

lpvBuffer

Points to the buffer where the function is to copy information about the outline character. If this value is NULL, the function returns the required size of the buffer.

lpmat2

Points to a MAT2 structure specifying a transformation matrix for the character.

Return Value

If GGO_BITMAP or GGO_NATIVE is specified, and the function succeeds, the return value is greater than zero; otherwise, the return value is GDI_ERROR. If one of these flags is specified, and the buffer size or address is zero, the return value specifies the required buffer size, in bytes.

If GGO_METRICS is specified, and the function fails, the return value is GDI_ERROR.

Remarks

The glyph outline returned by the GetGlyphOutline function is for a grid-fitted glyph. (A grid-fitted glyph is a glyph that has been modified so that its bitmapped image conforms as closely as possible to the original design of the glyph.) If an application needs an unmodified glyph outline, it can request the glyph outline for a character in a font whose size is equal to the font's em unit. The value for a font's em unit is stored in the otmEMSquare member of the OUTLINETEXTMETRIC structure.

The glyph bitmap returned by the GetGlyphOutline function when GGO_BITMAP is specified is a doubleword-aligned, row-oriented monochrome bitmap.

An application can rotate characters retrieved in bitmap format by specifying a 2-by-2 transformation matrix in the lpMatrix parameter.

See Also

FORM_INFO_1, GetOutlineTextMetrics, GLYPHMETRICS, MAT2, OUTLINETEXTMETRIC, POINT


GetGraphicsMode
 GetGraphicsMode  QuickInfo  Overview  Group

The GetGraphicsMode function retrieves the current graphics mode for the specified device context.

int GetGraphicsMode(

HDC  hdc	// handle of device context
);
Parameters

hdc

Identifies the device context.

Return Value

If the function succeeds, the return value is the current graphics mode. It can be one of the following values:

Value	Meaning
GM_COMPATIBLE	The current graphics mode is the compatible graphics mode, a mode that is compatible with Windows version 3.1. In this graphics mode, an application cannot set or modify the world transformation for the specified device context. The compatible graphics mode is the default graphics mode.
GM_ADVANCED	Windows NT: The current graphics mode is the advanced graphics mode, a mode that allows world transformations. In this graphics mode, an application can set or modify the world transformation for the specified device context. Windows 95: The GM_ADVANCED value is not supported.
Otherwise, the return value is zero.

Remarks

An application can set the graphics mode for a device context by calling the SetGraphicsMode function.

See Also

SetGraphicsMode


GetHandleInformation [New - Windows NT]
 GetHandleInformation  QuickInfo  Overview  Group

[New - Windows NT]

The GetHandleInformation function obtains information about certain properties of an object handle. The information is obtained as a set of bit flags.

BOOL GetHandleInformation (

HANDLE  hObject,	// handle to an object
LPDWORD  lpdwFlags	// points to variable to receive flags
);
Parameters

hObject

Specifies a handle to an object. The GetHandleInformation function obtains information about this object handle.

lpdwFlags

Points to a variable to receive a set of bit flags that specify properties of the object handle. The following flags are defined:

Value	Meaning
HANDLE_FLAG_INHERIT	If this flag is set, a child process created with the bInheritHandles parameter of CreateProcess set to TRUE will inherit the object handle.
HANDLE_FLAG_PROTECT_FROM_CLOSE	If this flag is set, calling the CloseHandle function will not close the object handle.
Return Value

If the function succeeds, the return value is TRUE.

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

See Also

CloseHandle, CreateProcess, SetHandleInformation


gethostbyaddr
 gethostbyadd  QuickInfor

The Windows Sockets gethostbyaddr function gets host information corresponding to an address.

struct hostent FAR * gethostbyaddr (

const char FAR * addr,
int len,
int type
);
Parameters

addr

A pointer to an address in network byte order.

len

The length of the address, which must be 4 for PF_INET addresses.

type

The type of the address, which must be PF_INET.

Return Value

If the function succeeds, gethostbyaddr returns a pointer to the hostent structure previously described.

If the function fails, it returns a NULL pointer. To get extended error information, call WSAGetLastError.

Error Codes

WSANOTINITIALISED	A successful WSAStartup must occur before using this function.
WSAENETDOWN	The Windows Sockets implementation has detected that the network subsystem has failed.
WSAHOST_NOT_FOUND	Authoritative Answer Host not found.
WSATRY_AGAIN	Non-Authoritative Host not found, or SERVERFAIL.
WSANO_RECOVERY	Nonrecoverable errors: FORMERR, REFUSED, NOTIMP.
WSANO_DATA	Valid name, no data record of requested type.
WSAEINPROGRESS	A blocking Windows Sockets operation is in progress.
WSAEINTR	The (blocking) call was canceled using WSACancelBlockingCall.
Remarks

The gethostbyaddr function returns a pointer to the following structure, which contains the name(s) and address which correspond to the specified address.

struct hostent {

    char FAR *       h_name;

    char FAR * FAR * h_aliases;

    short            h_addrtype;

    short            h_length;

    char FAR * FAR * h_addr_list;

};

The members of this structure are:

Member	Usage
h_name	Official name of the host (PC).
h_aliases	A NULL-terminated array of alternate names.
h_addrtype	The type of address being returned; for Windows Sockets this is always PF_INET.
h_length	The length, in bytes, of each address; for PF_INET, this is always 4.
h_addr_list	A NULL-terminated list of addresses for the host. Addresses are returned in network byte order.
The macro h_addr is defined to be h_addr_list[0] for compatibility with older software.

The pointer that is returned points to a structure allocated by the Windows Sockets implementation. The application must never attempt to modify this structure or to free any of its components. Furthermore, only one copy of this structure is allocated per thread, and so the application should copy any information it needs before issuing any other Windows Sockets function calls.

See Also

gethostbyname, WSAAsyncGetHostByAddr, WSACancelBlockingCall, WSAStartup


gethostbyname
 gethostbynam  QuickInfoe

The Windows Sockets gethostbyname function gets host information corresponding to a host name.

struct hostent FAR * gethostbyname (

const char FAR * name
);
Parameters

name

A pointer to the name of the host.

Return Value

If the function succeeds, gethostbyname returns a pointer to the hostent structure described above.

If the function fails, it returns a NULL pointer. To get extended error information, call WSAGetLastError.

Error Codes

WSANOTINITIALISED	A successful WSAStartup must occur before using this function.
WSAENETDOWN	The Windows Sockets implementation has detected that the network subsystem has failed.
WSAHOST_NOT_FOUND	Authoritative Answer Host not found.
WSATRY_AGAIN	Non-Authoritative Host not found, or SERVERFAIL.
WSANO_RECOVERY	Nonrecoverable errors: FORMERR, REFUSED, NOTIMP.
WSANO_DATA	Valid name, no data record of requested type.
WSAEINPROGRESS	A blocking Windows Sockets operation is in progress.
WSAEINTR	The (blocking) call was canceled using WSACancelBlockingCall.
Remarks

The gethostbyname function returns a pointer to a hostent structure as described under gethostbyaddr. The contents of this structure correspond to the host name name.

The pointer that is returned points to a structure allocated by the Windows Sockets implementation. The application must never attempt to modify this structure or to free any of its components. Furthermore, only one copy of this structure is allocated per thread, and so the application should copy any information which it needs before issuing any other Windows Sockets function calls.

A gethostbyname implementation must not resolve IP address strings passed to it. Such a request should be treated exactly as if an unknown host name were passed. An application with an IP address string to resolve should use inet_addr to convert the string to an IP address, then gethostbyaddr to obtain the hostent structure.

See Also

gethostbyaddr, inet_addr, WSAAsyncGetHostByName, WSACancelBlockingCall, WSAStartup


gethostname
 gethostname  QuickInfo

The Windows Sockets gethostname function returns the standard host name for the local computer.

int PASCAL FAR gethostname (

char FAR * name,
int namelen
);
Parameters

name

A pointer to a buffer that will receive the host name.

namelen

The length of the buffer.

Return Value

If the function succeeds, gethostname returns zero.

If the function fails, it returns SOCKET_ERROR. To get extended error information, call WSAGetLastError.

Error Codes

WSAEFAULT	The namelen parameter is too small.
WSANOTINITIALISED	A successful WSAStartup must occur before using this function.
WSAENETDOWN	The Windows Sockets implementation has detected that the network subsystem has failed.
WSAEINPROGRESS	A blocking Windows Sockets operation is in progress.
Remarks

This function returns the name of the local host into the buffer specified by the name parameter. The host name is returned as a null-terminated string. The form of the host name is dependent on the Windows Sockets implementation — it may be a simple host name, or it may be a fully qualified domain name. However, it is guaranteed that the name returned will be successfully parsed by gethostbyname and WSAAsyncGetHostByName.

See Also

gethostbyname, WSAAsyncGetHostByName, WSAStartup


GetICMProfile [New - Windows 95]
 GetICMProfile  QuickInfo  Overview  Group

[New - Windows 95]

The GetICMProfile function retrieves the name of the color profile file for the device associated with the specified device context.

BOOL GetICMProfile(

HDC  hdc,
DWORD  cbName,
LPTSTR  lpszFilename
);
Parameters

hdc

Handle to the device context.

cbName

Size, in bytes or characters, of the buffer that receives the filename, depending on whether the ANSI or Unicode version of the function is used.

lpszFilename

Pointer to the buffer that receives the null-terminated string specifying the full path of the color profile file.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

GetICMProfile fails if image color matching has not been enabled for the specified device context.


GetIconInfo
 GetIconInfo  QuickInfo  Overview  Group

The GetIconInfo function retrieves information about the specified icon or cursor.

BOOL GetIconInfo(

HICON  hIcon,	// icon handle
PICONINFO  piconinfo	// address of icon structure
);
Parameters

hIcon

Identifies the icon or cursor. To retrieve information about a standard icon or cursor, specify one of the following values:

Value	Meaning
IDC_ARROW	Arrow cursor
IDC_IBEAM	I-beam cursor
IDC_WAIT	Hourglass cursor
IDC_CROSS	Crosshair cursor
IDC_UPARROW	Up arrow cursor
IDC_SIZENWSE	Sizing cursor, points northwest and southeast
IDC_SIZENESW	Sizeing cursor, points northeast and southwest
IDC_SIZEWE	Sizing cursor, points west and east
IDC_SIZENS	Sizing cursor, points north and south
IDC_SIZEALL	Sizing cursor, points north, south, east, and west
IDC_NO	"No" cursor
IDC_APPSTARTING	Application-starting cursor (arrow and hourglass)
IDC_HELP	Help cursor (arrow and question mark)
IDI_APPLICATION	Application icon
IDI_HAND	Stop sign icon
IDI_QUESTION	Question-mark icon
IDI_EXCLAMATION	Exclamation point icon
IDI_ASTERISK	Asterisk icon (letter "i" in a circle)
IDI_WINLOGO	Windows logo icon
piconinfo

Points to an ICONINFO structure. The function fills in the structure's members.

Return Value

If the function succeeds, the return value is TRUE and the function fills in the members of the specified ICONINFO structure.

If the function fails, the return value is FALSE. 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.

See Also

CreateIcon, CreateIconFromResource, CreateIconIndirect, DestroyIcon, DrawIcon, DrawIconEx, ICONINFO, LoadIcon, LookupIconIdFromDirectory


GetInputState
 GetInputState  QuickInfo  Overview  Group

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 Value

If the queue contains one or more new mouse-button or keyboard messages, the return value is TRUE.

If the function fails, the return value is FALSE.

See Also

GetQueueStatus


GetInstanceData
 GetInstanceData  Overview  Group

The GetInstanceData function is not implemented in the Win32 API. Each Win32-based application runs in its own address space.


GetJob
 GetJob  QuickInfo  Overview  Group

The GetJob function retrieves print-job data for the specified printer.

BOOL GetJob(

HANDLE  hPrinter,	// handle of printer
DWORD  JobId,	// job identifier value
DWORD  Level,	// data-structure level
LPBYTE  pJob,	// address of data-structure array
DWORD  cbBuf,	// count of bytes in array
LPDWORD  pcbNeeded	// address of value that contains count of bytes retrieved (or required)
);
Parameters

hPrinter

Identifies the printer for which the print-job data is retrieved.

JobId

Identifies the print job for which data should be retrieved.

Level

Specifies the level of the structure to which pJob points. This value must be either 1 or 2.

pJob

Points to an array that contains either a JOB_INFO_1 or a JOB_INFO_2 structure. If Level is 1, this function stores the data in a JOB_INFO_1 structure; if Level is 2, this function stores the data in a JOB_INFO_2 structure.

cbBuf

Specifies the size, in bytes, of the array.

pcbNeeded

Points to a value that specifies the number of bytes copied if the function succeeds or the number of bytes required if cbBuf is too small.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

AddJob, JOB_INFO_1, JOB_INFO_2, ScheduleJob, SetJob


GetKBCodePage
 GetKBCodePage  QuickInfo  Overview  Group

The GetKBCodePage function is provided for compatibility with earlier versions of Windows. In the Win32 application programming interface (API) it just calls the GetOEMCP function. New applications should use the GetOEMCP function.

UINT GetKBCodePage(VOID)

Parameters

This function has no parameters.

Return Value

If the function succeeds, the return value is an OEM code-page identifier, or it is the default identifier if the registry value is not readable. For a list of OEM code-page identifiers, see GetOEMCP.

See Also

GetACP, GetOEMCP


GetKernelObjectSecurity
 GetKernelObjectSecurity  QuickInfo  Overview  Group

The GetKernelObjectSecurity function retrieves a copy of the security descriptor protecting a kernel object.

BOOL GetKernelObjectSecurity(

HANDLE  Handle,	// handle of object to query
SECURITY_INFORMATION  RequestedInformation,	// requested information
PSECURITY_DESCRIPTOR  pSecurityDescriptor,	// address of security descriptor
DWORD  nLength,	// size of buffer for security descriptor
LPDWORD  lpnLengthNeeded	// address of required size of buffer
);
Parameters

Handle

Identifies a kernel object.

RequestedInformation

Specifies a SECURITY_INFORMATION structure that identifies the security information being requested.

pSecurityDescriptor

Points to a buffer the function fills with a copy of the security descriptor of the specified object. The calling process must have the right to view the specified aspects of the object's security status. The SECURITY_DESCRIPTOR structure is returned in self-relative format.

nLength

Specifies the size, in bytes, of the buffer pointed to by the pSecurityDescriptor parameter.

lpnLengthNeeded

Points to a variable the function sets to zero if the descriptor is copied successfully. If the buffer is too small for the security descriptor, this variable receives the number of bytes required. If this variable's value is greater than the value of the nLength parameter when the function returns, none of the security descriptor is copied to the buffer.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

To read the kernel object's security descriptor, the calling process must be either granted READ_CONTROL access or be the object's owner. In addition, the calling process must have the SE_SECURITY_NAME privilege to read the system access-control list.

See Also

GetFileSecurity, GetPrivateObjectSecurity, GetUserObjectSecurity, SECURITY_DESCRIPTOR, SECURITY_INFORMATION, SetKernelObjectSecurity


GetKerningPairs
 GetKerningPairs  QuickInfo  Overview  Group

The GetKerningPairs function retrieves the character-kerning pairs for the currently selected font for the specified device context.

DWORD GetKerningPairs(

HDC  hdc,	// handle of device context
DWORD  nNumPairs,	// number of kerning-pairs to be retrieved
LPKERNINGPAIR  lpkrnpair	// address of kerning-pair array
);
Parameters

hdc

Identifies the device context.

nNumPairs

Specifies the number of pairs that fit in the lpkrnpair array. If the font has more than nNumPairs kerning pairs, an error is returned.

lpkrnpair

Points to an array of KERNINGPAIR structures to receive the kerning pairs. The array must contain at least as many structures as specified by the nNumPairs parameter. If this parameter is NULL, the function returns the total number of kerning pairs for the font.

Return Value

If the function succeeds, the return value is the number of kerning pairs returned.

If the function fails, the return value is zero.

See Also

KERNINGPAIR


GetKeyboardLayout [New - Windows 95]
 GetKeyboardLayout  QuickInfo

[New - Windows 95]

The GetKeyboardLayout function retrieves the active keyboard layout for a specified thread. If the dwLayout parameter is zero, the layout for the active thread is returned.

HKL GetKeyboardLayout(

DWORD dwLayout	// thread identifier
);
Parameters

dwLayout

Identifies the thread to query or is zero for the current thread.

Return Value

The return value is the keyboard layout handle for the thread. The low word contains a locale identifier identifying the input language and the high word contains a device handle identifying the physical layout of the keyboard.

See Also

ActivateKeyboardLayout, CreateThread, LoadKeyboardLayout


GetKeyboardLayoutList [New - Windows 95]
 GetKeyboardLayoutList  QuickInfo

[New - Windows 95]

The GetKeyboardLayoutList function retrieves the keyboard layout handles corresponding to the current set of input locales in the system. The function copies the handles to the given buffer.

UINT GetKeyboardLayoutList(

int nBuff,	// size of buffer in array element
HKL FAR * lpList	// buffer for keyboard layout handles
);
Parameters

nBuff

Specifies the maximum number of handles that the buffer can hold.

lpList

Points to the buffer, an array, that receives the keyboard layout handles.

Return Value

If the function succeeds, the return value is the number of layout handles copied to the buffer or, if nBuff is zero, the return value is the size, in array elements, of the buffer needed to receive all current layout handles.

See Also

GetKeyboardLayout


GetKeyboardLayoutName
 GetKeyboardLayoutName  QuickInfo  Overview  Group

The GetKeyboardLayoutName function retrieves the name of the active keyboard layout.

BOOL GetKeyboardLayoutName(

LPTSTR  pwszKLID	// address of buffer for layout name
);
Parameters

pwszKLID

Points to the buffer of at least KL_NAMELENGTH characters that is to receive the name of the keyboard layout, including the NULL terminator. This will be a copy of the string provided to the LoadKeyboardLayout function, unless layout substitution took place.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

Windows NT:

GetKeyboardLayoutName gets the name of the active keyboard layout for the system.

Windows 95:

GetKeyboardLayoutName gets the name of the active keyboard layout for the calling thread.

See Also

ActivateKeyboardLayout, LoadKeyboardLayout, UnloadKeyboardLayout


GetKeyboardState
 GetKeyboardState  QuickInfo  Overview  Group

The GetKeyboardState function copies the status of the 256 virtual keys to the specified buffer.

BOOL GetKeyboardState(

PBYTE  lpKeyState	// address of array to receive status data
);
Parameters

lpKeyState

Points to the 256-byte array that will receive the status data for each virtual key.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. 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 message queue.

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.

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.

See Also

GetKeyState, GetAsyncKeyState, MapVirtualKey, SetKeyboardState


GetKeyboardType
 GetKeyboardType  QuickInfo  Overview  Group

The GetKeyboardType function retrieves information about the current keyboard.

int GetKeyboardType(

int  nTypeFlag	// type of information to retrieve
);
Parameters

nTypeFlag

Specifies the type of keyboard information to be retrieved. This parameter can be one of the following values:

Value	Meaning
0	Keyboard type
1	Keyboard subtype
2	Number of function keys on the keyboard
Return Value

If the function succeeds, the return value specifies the requested information.

If the function fails, the return value is zero.

Remarks

The subtype is an original equipment manufacturer (OEM)-dependent value. The type may be one of the following values:

Value	Meaning
1	IBM® PC/XT® ( ) or compatible (83-key) keyboard
2	Olivetti® "ICO" (102-key) keyboard
3	IBM PC/AT® (84-key) or similar keyboard
4	IBM enhanced (101- or 102-key) keyboard
5	Nokia® 1050 and similar keyboards
6	Nokia 9140 and similar keyboards
7	Japanese keyboard
The application can also determine the number of function keys on a keyboard from the keyboard type. Following are the number of function keys for each keyboard type:

Type	Number of function keys
1	10
2	12 (sometimes 18)
3	10
4	12
5	10
6	24
7	Hardware dependent and specified by the OEM


GetKeyNameText
 GetKeyNameText  QuickInfo  Overview  Group

The GetKeyNameText function retrieves a string that represents the name of a key.

int GetKeyNameText(

LONG  lParam,	// second parameter of keyboard message
LPTSTR  lpString,	// address of buffer for key name
int  nSize	// maximum length of key-name string length
);
Parameters

lParam

Specifies the second parameter of the keyboard message (such as WM_KEYDOWN) to be processed. The function interprets the following portions of lParam:

Bits	Meaning
16−23	Scan code.
24	Extended-key flag. Distinguishes some keys on an enhanced keyboard.
25	"Don't care" bit. The application calling this function sets this bit to indicate that the function should not distinguish between left and right CTRL and SHIFT keys, for example.
lpString

Points to a buffer that will receive the key name.

nSize

Specifies the maximum length, in characters, of the key name, including the terminating null character. (This parameter should be equal to the size of the buffer pointed to by the lpString parameter.)

Return Value

If the function succeeds, a null-terminated string is copied into the specified buffer, and the return value is the length of the string, in characters, not counting the terminating null character.

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.


GetKeyState
 GetKeyState  QuickInfo  Overview  Group

The GetKeyState function retrieves the status of the specified virtual key. The status specifies whether the key is up, down, or toggled (on, off — alternating each time the key is pressed).

SHORT GetKeyState(

int  nVirtKey	// virtual-key code
);
Parameters

nVirtKey

Specifies a virtual key. If the desired virtual key is a letter or digit (A through Z, a through z, or 0 through 9), nVirtKey must be set to the ASCII value of that character. For other keys, it must be a virtual-key code.

If a non-English keyboard layout is used, virtual keys with values in the range ASCII A through Z and 0 through 9 are used to specify most of the character keys. For example, for the German keyboard layout, the virtual key of value ASCII O (0x4F) refers to the "o" key, whereas VK_OEM_1 refers to the "o with umlaut" key.

Return Value

If the function succeeds, the return value specifies the status of the given 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.

Remarks

The key status returned from this function changes as a given thread reads key messages from its message queue. The status does not reflect the interrupt-level state associated with the hardware. Use the GetAsyncKeyState function to retrieve that information.

An application calls GetKeyState in response to a keyboard-input message. This function retrieves the state of the key when the input message was generated.

To retrieve state information for all the virtual keys, use the GetKeyboardState function.

An application can use the virtual-key code constants VK_SHIFT, VK_CONTROL, and VK_MENU as values for the nVirtKey parameter. This gives the status of the SHIFT, CTRL, or ALT keys without distinguishing between left and right. An application can also use the following virtual-key code constants as values for nVirtKey to distinguish between the left and right instances of those keys:

VK_LSHIFT	VK_RSHIFT
VK_LCONTROL	VK_RCONTROL
VK_LMENU	VK_RMENU
These left- and right-distinguishing constants are available to an application only through the GetKeyboardState, SetKeyboardState, GetAsyncKeyState, GetKeyState, and MapVirtualKey functions.

See Also

GetAsyncKeyState, GetKeyboardState, MapVirtualKey, SetKeyboardState


GetLargestConsoleWindowSize
 GetLargestConsoleWindowSize  QuickInfo  Overview  Group

The GetLargestConsoleWindowSize function returns the size of the largest possible console window, based on the current font and the size of the display.

COORD GetLargestConsoleWindowSize(

HANDLE  hConsoleOutput	// handle of console screen buffer
);
Parameters

hConsoleOutput

Identifies a console screen buffer.

Return Value

If the function succeeds, the return value is a COORD structure that specifies the number of character cell rows (X member) and columns (Y member) in the largest possible console window. Otherwise, the members of the structure are zero.

To get extended error information, call GetLastError.

Remarks

The function does not take into consideration the size of the screen buffer, which means that the window size returned may be larger than the size of the screen buffer. The GetConsoleScreenBufferInfo function can be used to determine the maximum size of the console window, given the current screen buffer size, the current font, and the display size.

See Also

COORD, GetConsoleScreenBufferInfo, SetConsoleWindowInfo


GetLastActivePopup
 GetLastActivePopup  QuickInfo  Overview  Group

The GetLastActivePopup function determines which pop-up window owned by the specified window was most recently active.

HWND GetLastActivePopup(

HWND  hWnd	// handle of owner window
);
Parameters

hWnd

Identifies the owner window.

Return Value

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.

See Also

AnyPopup, ShowOwnedPopups


GetLastError
 GetLastError  QuickInfo  Overview  Group

The GetLastError function returns the calling thread's last-error code value.

Most Win32 functions set their calling thread's last-error value when they fail; a few functions set it when they succeed.

DWORD GetLastError(VOID)

Parameters

This function has no parameters.

Return Value

The return value is the calling thread's last-error code value. Functions set this value by calling the SetLastError function. The Return Value section of each Win32 function's reference page notes the conditions under which the function sets the last-error code.

Remarks

The extended error codes returned by the GetLastError function are not guaranteed to be the same for all operating systems.

You should call the GetLastError function immediately when a function's return value indicates that such a call will return useful data. That is because some functions call SetLastError(0) when they succeed, wiping out the error code set by the most recently failed function.

As noted, most Win32 functions call SetLastError when they fail. Function failure is typically indicated by a return value error code such as FALSE, NULL, 0xFFFFFFFF, or −1. Some functions call SetLastError under conditions of success; those cases are noted in each function's reference page.

Note that the last-error code is maintained on a per-thread basis. Multiple threads do not overwrite each other's last-error code.

Error codes are 32-bit values (bit 31 is the most significant bit). Bit 29 is reserved for application-defined error codes; no Win32 error code has this bit set. If you are defining an error code for your application, set this bit to one. That indicates that the error code has been defined by an application, and ensures that your error code does not conflict with any error codes defined by the operating system.

See Also

SetLastError, SetLastErrorEx


GetLengthSid
 GetLengthSid  QuickInfo  Overview  Group

The GetLengthSid function returns the length, in bytes, of a valid SID structure. A SID is a security identifier.

DWORD GetLengthSid(

PSID  pSid	// address of SID to query
);
Parameters

pSid

Points to the SID structure whose length is returned. The structure is assumed to be valid.

Return Value

If the function succeeds, the return value is the length, in bytes, of the SID structure. If the SID structure is not valid, the return value is undefined. To get extended error information, call GetLastError.

See Also

GetSidLengthRequired, GetSidSubAuthorityCount, IsValidSid, SID


GetLocaleInfo
 GetLocaleInfo  QuickInfo  Overview  Group

The GetLocaleInfo function retrieves information about a locale.

int GetLocaleInfo(

LCID  Locale,	// locale identifier
LCTYPE  LCType,	// type of information
LPTSTR  lpLCData,	// address of buffer for information
int  cchData	// size of buffer
);
Parameters

Locale

Specifies the locale to retrieve information for. This parameter can be a locale identifier created by the MAKELCID macro, or one of the following predefined values:

LOCALE_SYSTEM_DEFAULT	Default system locale.
LOCALE_USER_DEFAULT	Default user locale.
LCType

Specifies one of the LCTYPE constants to indicate the type of information to be retrieved.

All LCTYPE values are mutually exclusive, with the exception of LOCALE_NOUSEROVERRIDE. An application may use the binary-OR operator to combine LOCALE_NOUSEROVERRIDE with any other LCTYPE value. If passed such an LCType value, the function bypasses user overrides, and returns the system default value for the requested LCID.

lpLCData

Points to a buffer to receive the requested data.

cchData

Specifies the size, in bytes (ANSI version) or characters (Unicode version), of the lpLCData buffer. If cchData is zero, the function returns the number of bytes or characters required to hold the information, and the buffer pointed to by lpLCData is not used.

Return Value

If the function succeeds, the return value is the number of bytes (ANSI version) or characters (Unicode version) written to the destination buffer, or if the cchData parameter is zero, the number of bytes or characters required to hold the locale information.

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 GetLocaleInfo function always retrieves information in text format. If the information is a numeric value, the function converts the number to text using decimal notation.

See Also

GetStringTypeA, GetStringTypeEx, GetStringTypeW, GetSystemDefaultLCID, GetUserDefaultLCID, MAKELCID


GetLocalTime
 GetLocalTime  QuickInfo  Overview  Group

The GetLocalTime function retrieves the current local date and time.

VOID GetLocalTime(

LPSYSTEMTIME  lpSystemTime	// address of system time structure
);
Parameters

lpSystemTime

Points to a SYSTEMTIME structure to receive the current local date and time.

Return Value

This function does not return a value.

See Also

GetSystemTime, SetLocalTime, SYSTEMTIME


GetLogColorSpace [New - Windows 95]
 GetLogColorSpace  QuickInfo  Overview  Group

[New - Windows 95]

The GetLogColorSpace function retrieves information about the logical color space identified by the specified handle.

BOOL GetLogColorSpace(

HCOLORSPACE  hColorSpace,
LPLOGCOLORSPACE  lpbuffer,
DWORD  nSize
);
Parameters

hColorSpace

Handle to the logical color space.

lpBuffer

Pointer to the LOGCOLORSPACE structure that receives the logical color space information.

nSize

Maximum size of the buffer, in bytes.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

GetLogColorSpace copies as much information to the buffer as space allows. To determine the correct size of the buffer to use, applications should check the lcsSize member in the structure.

See Also

LOGCOLORSPACE


GetLogicalDrives
 GetLogicalDrives  QuickInfo  Overview  Group

The GetLogicalDrives function returns a bitmask representing the currently available disk drives.

DWORD GetLogicalDrives(VOID)

Parameters

This function has no parameters.

Return Value

If the function succeeds, the return value is a bitmask representing the currently available disk drives. Bit position 0 (the least-significant bit) is drive A, bit position 1 is drive B, bit position 2 is drive C, and so on.

If the function fails, the return value is zero.

See Also

GetLogicalDriveStrings


GetLogicalDriveStrings
 GetLogicalDriveStrings  QuickInfo  Overview  Group

The GetLogicalDriveStrings function fills a buffer with strings that specify valid drives in the system.

DWORD GetLogicalDriveStrings(

DWORD  nBufferLength,	// size of buffer
LPTSTR  lpBuffer	// address of buffer for drive strings
);
Parameters

nBufferLength

Specifies the maximum size, in characters, of the buffer pointed to by lpBuffer. This size does not include the terminating null character.

lpBuffer

Points to a buffer that receives a series of null-terminated strings, one for each valid drive in the system, that end with a second null character. The following example shows the buffer contents with <null> representing the terminating null character.

c:\<null>d:\<null><null>

Return Value

If the function succeeds, the return value is the length, in characters, of the strings copied to the buffer, not including the terminating null character. Note that an ANSI-ASCII null character uses one byte, but a Unicode null character uses two bytes.

If the buffer is not large enough, the return value is greater than nBufferLength. It is the size of the buffer required to hold the drive strings.

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

Remarks

Each string in the buffer may be used wherever a root directory is required, such as for the GetDriveType and GetDiskFreeSpace functions.

See Also

GetDriveType, GetDiskFreeSpace, GetLogicalDrives


GetMailslotInfo
 GetMailslotInfo  QuickInfo  Overview  Group

The GetMailslotInfo function retrieves information about the specified mailslot.

BOOL GetMailslotInfo(

HANDLE  hMailslot,	// mailslot handle
LPDWORD  lpMaxMessageSize,	// address of maximum message size
LPDWORD  lpNextSize,	// address of size of next message
LPDWORD  lpMessageCount,	// address of number of messages
LPDWORD  lpReadTimeout	// address of read time-out
);
Parameters

hMailslot

Identifies a mailslot. The CreateMailslot function must create this handle.

lpMaxMessageSize

Points to a buffer specifying the maximum message size, in bytes, allowed for this mailslot, when the function returns. This value can be greater than or equal to the value specified in the cbMaxMsg parameter of the CreateMailslot function that created the mailslot. This parameter can be NULL.

lpNextSize

Points to a buffer specifying the size, in bytes, of the next message, when the function returns. The following value has special meaning:

Value	Meaning
MAILSLOT_NO_MESSAGE	There is no next message.
This parameter can be NULL.

lpMessageCount

Points to a buffer specifying the total number of messages waiting to be read, when the function returns. This parameter can be NULL.

lpReadTimeout

Points to a buffer specifying the amount of time, in milliseconds, a read operation can wait for a message to be written to the mailslot before a time-out occurs. This parameter is filled in when the function returns. This parameter can be NULL.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

CreateMailslot, SetMailslotInfo


GetMapMode
 GetMapMode  QuickInfo  Overview  Group

The GetMapMode function retrieves the current mapping mode.

int GetMapMode(

HDC  hdc	// handle of device context
);
Parameters

hdc

Identifies the device context.

Return Value

If the function succeeds, the return value specifies the mapping mode.

If the function fails, the return value is zero.

Remarks

The following list describes the various mapping modes:

Value	Description
MM_ANISOTROPIC	Logical units are mapped to arbitrary units with arbitrarily scaled axes. Use the SetWindowExtEx and SetViewportExtEx functions to specify the units, orientation, and scaling that you want.
MM_HIENGLISH	Each logical unit is mapped to 0.001 inch. Positive x is to the right; positive y is up.
MM_HIMETRIC	Each logical unit is mapped to 0.01 millimeter. Positive x is to the right; positive y is up.
MM_ISOTROPIC	Logical units are mapped to arbitrary units with equally scaled axes; that is, one unit along the x-axis is equal to one unit along the y-axis. Use the SetWindowExtEx and SetViewportExtEx functions to specify the units and the orientation of the axes that you want. Graphics device interface makes adjustments as necessary to ensure the x and y units remain the same size (for example, if you set the window extent, the viewport will be adjusted to keep the units isotropic).
MM_LOENGLISH	Each logical unit is mapped to 0.01 inch. Positive x is to the right; positive y is up.
MM_LOMETRIC	Each logical unit is mapped to 0.1 millimeter. Positive x is to the right; positive y is up.
MM_TEXT	Each logical unit is mapped to one device pixel. Positive x is to the right; positive y is down.
MM_TWIPS	Each logical unit is mapped to one twentieth of a printer's point (1/1440 inch, also called a "twip"). Positive x is to the right; positive y is up.
See Also

SetMapMode, SetWindowExtEx, SetViewportExtEx


GetMenu
 GetMenu  QuickInfo  Overview  Group

The GetMenu function retrieves the handle of the menu assigned to the given window.

HMENU GetMenu(

HWND  hWnd	// handle of window
);
Parameters

hWnd

Identifies the window whose menu handle is retrieved.

Return Value

If the function succeeds, the return value is the handle of the menu. If the given window has no menu, the return value is NULL. If the window is a child window, the return value is undefined.

See Also

GetSubMenu, SetMenu


GetMenuCheckMarkDimensions
 GetMenuCheckMarkDimensions  QuickInfo  Overview  Group

Windows NT: The GetMenuCheckMarkDimensions function returns the dimensions of the default check mark bitmap. Windows displays this bitmap next to checked menu items. Before calling the SetMenuItemBitmaps function to replace the default check mark bitmap for a menu item, an application must determine the correct bitmap size by calling GetMenuCheckMarkDimensions.

Windows 95: This function is obsolete. Use the GetSystemMetrics with the CXMENUCHECK and CYMENUCHECK values to retrieve the bitmap dimensions.

LONG GetMenuCheckMarkDimensions(VOID)

Parameters

This function has no parameters.

Return Value

The return value specifies the height and width, in pixels, of the default check mark bitmap. The high-order word contains the height; the low-order word contains the width.

See Also

SetMenuItemBitmaps


GetMenuContextHelpId [New - Windows NT]
 GetMenuContextHelpId  QuickInfo  Overview  Group

[New - Windows NT]

The GetMenuContextHelpId function retrieves the help context identifier associated with the specified menu.

DWORD GetMenuContextHelpId(

HMENU  hmenu
);
Parameters

hmenu

Handle to the menu for which the help context identifier is to be retrieved.

Return Value

Returns the help context identifier if the menu has one or zero otherwise.


GetMenuDefaultItem [New - Windows 95]
 GetMenuDefaultItem  QuickInfo  Overview  Group

[New - Windows 95]

The GetMenuDefaultItem function determines the default menu item on the specified menu.

UINT WINAPI GetMenuDefaultItem(

HMENU  hMenu,
UINT  fByPos,
UINT  gmdiFlags
);
Parameters

hMenu

Handle to the menu for which to retrieve the default menu item.

fByPos

Value specifying whether to retrieve the menu item's identifier or its position. If this parameter is FALSE, the identifier is returned. Otherwise, the position is returned.

gmdiFlags

Value specifying how the function searches for menu items. This parameter can be zero or more of the following values:

Value	Meaning
GMDI_GOINTOPOPUPS	Specifies that if the default item is a pop-up item, the function is to search recursively in the corresponding pop-up menu. If the pop-up menu has no default item, the return value identifies the pop-up item. By default, the function returns the first default item on the specified menu, regardless of whether it is a pop-up item.
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 Value

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.


GetMenuItemCount
 GetMenuItemCount  QuickInfo  Overview  Group

The GetMenuItemCount function determines the number of items in the specified menu bar or pop-up menu.

int GetMenuItemCount(

HMENU  hMenu	// handle of menu
);
Parameters

hMenu

Identifies the handle of the menu to be examined.

Return Value

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.

See Also

GetMenuItemID


GetMenuItemID
 GetMenuItemID  QuickInfo  Overview  Group

The GetMenuItemID function retrieves the menu item identifier of a menu item located at the specified position in a menu bar or pop-up menu.

UINT GetMenuItemID(

HMENU  hMenu,	// handle of menu
int  nPos	// position of menu item
);
Parameters

hMenu

Identifies the menu bar or pop-up menu that contains the item whose identifier is to be retrieved.

nPos

Specifies the zero-based relative position of the menu item whose identifier is to be retrieved.

Return Value

If the function succeeds, the return value specifies the identifier of the given menu item. If the menu item identifier is NULL or if the specified item invokes a pop-up menu, the return value is 0xFFFFFFFF.

See Also

GetMenuItemCount, GetMenuString


GetMenuItemInfo [New - Windows 95]
 GetMenuItemInfo  QuickInfo  Overview  Group

[New - Windows 95]

The GetMenuItemInfo function retrieves information about a menu item.

BOOL WINAPI GetMenuItemInfo(

HMENU  hMenu,
UINT  uItem,
BOOL  fByPosition,
LPMENUITEMINFO  lpmii
);
Parameters

hMenu

Handle to the menu that contains the menu item.

uItem

Identifier or position of the menu item to get information about. The meaning of this parameter depends on the value of fByPosition.

fByPosition

Value specifying the meaning of uItem. If this parameter is FALSE, uItem is a menu item identifier. Otherwise, it is a menu item position.

lpmii

Pointer to a MENUITEMINFO structure that specifies the information to retrieve and receives information about the menu item.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To get extended error information, use the GetLastError function.

See Also

MENUITEMINFO


GetMenuItemRect [New - Windows 95]
 GetMenuItemRect  QuickInfo  Overview  Group

[New - Windows 95]

The GetMenuItemRect function retrieves the bounding rectangle for the specified menu item.

BOOL WINAPI GetMenuItemRect(

HWND  hWnd,
HMENU  hMenu,
UINT  uItem,
LPRECT  lprcItem
);
Parameters

hWnd

Handle to the window containing the menu bar or pop-up menu.

hMenu

Handle to a menu bar or pop-up menu.

uItem

Zero-based position of the menu item.

lprcItem

Pointer to a RECT structure that receives the bounding rectangle of the specified menu item expressed in screen coordinates.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To get extended error information, use the GetLastError function.

See Also

RECT


GetMenuState
 GetMenuState  QuickInfo  Overview  Group

The GetMenuState function retrieves the menu flags associated with the specified menu item. If the menu item activates a pop-up menu, this function also returns the number of items in the pop-up menu.

UINT GetMenuState(

HMENU hMenu,	// handle of menu
UINT uId,	// menu item to query
UINT uFlags	// menu flags
);
Parameters

hMenu

Identifies the menu that contains the menu item whose flags are to be retrieved.

uId

Specifies the menu item for which the menu flags are to be retrieved, as determined by the uFlags parameter.

uFlags

Specifies how the uId parameter is interpreted. This parameter can be one of the following values:

Value	Description
MF_BYCOMMAND	Indicates that the uId parameter gives the identifier of the menu item. The MF_BYCOMMAND flag is the default if neither the MF_BYCOMMAND nor MF_BYPOSITION flag is specified.
MF_BYPOSITION	Indicates that the uId parameter gives the zero-based relative position of the menu item.
Return Value

If the specified item does not exist, the return value is 0xFFFFFFFF.

If the menu item activates a pop-up menu, 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 pop-up menu activated by the item.

Otherwise, the return value is a mask (Boolean OR) of the menu flags. Following are the menu flags associated with the menu item.

Value	Description
MF_CHECKED	Places a check mark next to the item (pop-up menus only).
MF_DISABLED	Disables the item.
MF_GRAYED	Disables and grays the item.
MF_HILITE	Highlights the item.
MF_MENUBARBREAK	Functions the same as the MF_MENUBREAK flag, except for pop-up menus where the new column is separated from the old column by a vertical line.
MF_MENUBREAK	Places the item on a new line (for menu bars) or in a new column (for pop-up menus) without separating columns.
MF_SEPARATOR	Creates a horizontal dividing line (for pop-up menus only).
See Also

GetMenu, GetMenuItemCount, GetMenuItemID, GetMenuString


GetMenuString
 GetMenuString  QuickInfo  Overview  Group

The GetMenuString function copies the text string of the specified menu item into the specified buffer.

Windows 95: GetMenuString is obsolete; use GetMenuItemInfo instead. For GetMenuString, if nMaxCount is 0 or lpString is NULL, the function returns the length of the menu string.

int GetMenuString(

HMENU  hMenu,	// handle to the menu
UINT  uIDItem,	// menu item identifier
LPTSTR  lpString,	// pointer to the buffer for the string
int  nMaxCount,	// maximum length of the string
UINT  uFlag	// menu flags
);
Parameters

hMenu

Identifies the menu.

uIDItem

Specifies the menu item to be changed, as determined by the uFlag parameter.

lpString

Points to the buffer that is to receive the null-terminated string.

nMaxCount

Specifies the maximum length, in characters, of the string to be copied. If the string is longer than the maximum specified in the nMaxCount parameter, the extra characters are truncated.

uFlag

Specifies how the uIDItem parameter is interpreted. This parameter must be one of the following values:

Value	Meaning
MF_BYCOMMAND	Indicates that uIDItem gives the identifier of the menu item. If neither the MF_BYCOMMAND nor MF_BYPOSITION flag is specified, the MF_BYCOMMAND flag is the default flag.
MF_BYPOSITION	Indicates that uIDItem gives the zero-based relative position of the menu item.
Return Value

If the function succeeds, the return value specifies the number of characters copied to the buffer, not including the terminating null character.

If the function fails, the return value is zero.

Remarks

The nMaxCount parameter must be one larger than the number of characters in the text string to accommodate the terminating null character.

See Also

GetMenuItemID


GetMessage
 GetMessage  QuickInfo  Overview  Group

The GetMessage function retrieves a message from the calling thread's message queue and places it in the specified structure. This function can retrieve both messages associated with a specified window and thread messages posted via the PostThreadMessage function. The function retrieves messages that lie within a specified range of message values. GetMessage does not retrieve messages for windows that belong to other threads or applications.

BOOL GetMessage(

LPMSG  lpMsg,	// address of structure with message
HWND  hWnd,	// handle of window
UINT  wMsgFilterMin,	// first message
UINT  wMsgFilterMax	// last message
);
Parameters

lpMsg

Points to an MSG structure that receives message information from the thread's message queue.

hWnd

Identifies the window whose messages are to be retrieved. One value has a special meaning:

Value	Meaning
NULL	GetMessage retrieves messages for any window that belongs to the calling thread and thread messages posted to the calling thread via PostThreadMessage.
wMsgFilterMin

Specifies the integer value of the lowest message value to be retrieved.

wMsgFilterMax

Specifies the integer value of the highest message value to be retrieved.

Return Value

If the function retrieves a message other than WM_QUIT, the return value is TRUE.

If the function retrieves the WM_QUIT, the return value is FALSE.

If there is an error, the return value is -1. For example, the function fails if hWnd is an invalid window handle.

Remarks

An application typically uses the return value to determine whether to end the main message loop and exit the program.

The GetMessage function only retrieves messages associated with the window identified by the hWnd parameter or any of its children as specified by the IsChild function, and within the range of message values given by the wMsgFilterMin and wMsgFilterMax parameters. If hWnd is NULL, GetMessage retrieves messages for any window that belongs to the calling thread and thread messages posted to the calling thread via PostThreadMessage. GetMessage does not retrieve messages for windows that belong to other threads nor for threads other than the calling thread. Thread messages, posted by the PostThreadmessage function, have a message hWnd value of NULL. If wMsgFilterMin and wMsgFilterMax are both zero, GetMessage returns all available messages (that is, no range filtering is performed).

The WM_KEYFIRST and WM_KEYLAST constants can be used as filter values to retrieve all messages related to keyboard input; the WM_MOUSEFIRST and WM_MOUSELAST constants can be used to retrieve all mouse messages. If the wMsgFilterMin and wMsgFilterMax parameters are both zero, the GetMessage function returns all available messages (that is, without performing any filtering).

GetMessage does not remove WM_PAINT messages from the queue. The messages remain in the queue until processed.

Note that the function return value can be TRUE, FALSE, or -1. Thus, you should avoid code like this:

while (GetMessage( lpMsg, hWnd, 0, 0)) ...

The possibility of a -1 return value means that such code can lead to fatal application errors.

See Also

IsChild, MSG, PeekMessage, PostMessage, PostThreadMessage, WaitMessage


GetMessageExtraInfo
 GetMessageExtraInfo  QuickInfo  Overview  Group

The GetMessageExtraInfo function retrieves extra information associated with the last message retrieved by the GetMessage or PeekMessage function. This information may be added to a message by the driver for a pointing device or keyboard.

LONG GetMessageExtraInfo(VOID)

Parameters

This function has no parameters.

Return Value

If the function succeeds, the return value specifies the extra information. The meaning of the extra information is device specific.

See Also

GetMessage, PeekMessage


GetMessagePos
 GetMessagePos  QuickInfo  Overview  Group

The GetMessagePos function returns a long value that gives the cursor position in screen coordinates. This position is the point occupied by the cursor when the last message retrieved by the GetMessage function occurred.

DWORD GetMessagePos(VOID)

Parameters

This function has no parameters.

Return Value

The return value specifies the x- and y-coordinates of the cursor position. The x coordinate is in the LOWORD and the y coordinate is in the HIWORD.

Remarks

As noted above, the x-coordinate is in the low-order word of the return value; the y-coordinate is in the high-order word. 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 LOWORD or HIWORD macro to extract the x- or y-coordinate.

To determine the current position of the cursor instead of the position when the last message occurred, use the GetCursorPos function.

See Also

GetCursorPos, GetMessage, GetMessageTime, HIWORD, LOWORD, MAKEPOINTS, POINTS


GetMessageTime
 GetMessageTime  QuickInfo  Overview  Group

The GetMessageTime function returns the message time for the last message retrieved by the GetMessage function from the current thread's message queue. The time is a long integer that specifies the elapsed time, in milliseconds, from the time the system was started to the time the message was created (that is, placed in the thread's message queue).

LONG GetMessageTime(VOID)

Parameters

This function has no parameters.

Return Value

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.

See Also

GetMessage, GetMessagePos


GetMetaFile
 GetMetaFile  QuickInfo  Overview  Group

The GetMetaFile function creates a handle that identifies the given Windows-format metafile.

The GetMetaFile function is not implemented in the Win32 API. This function is provided for compatibility with 16-bit versions of Microsoft Windows. Win32-based applications should use the GetEnhMetaFile function.

HMETAFILE GetMetaFile(

LPCTSTR  lpszFile	// address of metafile name
);
Parameters

lpszFile

Points to the null-terminated string that specifies the name of a Windows-format metafile. (The metafile must already exist.)

Return Value

If the function succeeds, the return value is a handle of the Windows-format metafile.

If the function fails, the return value is NULL.

Remarks

A Windows-format metafile does not support the new curve, path, and transformation functions, such as PolyBezier, BeginPath, and SetWorldTransform. Applications that use these new functions and use metafiles to store pictures created by these functions should use the enhanced-format metafile functions.

An application can convert a Windows-format metafile into an enhanced-format metafile, by calling the SetWinMetaFileBits function.

When the application no longer needs the handle returned by GetMetaFile, it should delete the handle by using the DeleteMetaFile function.

Where text arguments must use Unicode characters, use the this function as a wide-character function. Where text arguments must use characters from the Windows 3.x character set, use this function as an ANSI function.

See Also

DeleteMetaFile, GetEnhMetaFile, SetWinMetaFileBits


 GetMetaFileBits

The GetMetaFile function is not implemented in the Win32 API. This function is provided for compatibility with 16-bit versions of Microsoft Windows. Win32-based applications should use the GetMetaFileBitsEx function.


GetMetaFileBitsEx
 GetMetaFileBitsEx  QuickInfo  Overview  Group

The GetMetaFileBitsEx function retrieves the contents of a Windows-format metafile and copies them into the specified buffer.

This function is provided for compatibility with earlier versions of Microsoft Windows. Win32-based applications should use the GetEnhMetaFileBits function.

UINT GetMetaFileBitsEx(

HMETAFILE  hmf,	// handle of metafile
UINT  nSize,	// size of metafile, in bytes
LPVOID  lpvData	// address of metafile data
);
Parameters

hmf

Identifies a Windows-format metafile.

nSize

Specifies the size, in bytes, of the buffer to receive the data.

lpvData

Points to the buffer to receive the metafile data. The buffer must be sufficiently large to contain the data. If lpvData is NULL, the function returns the number of bytes required to hold the data.

Return Value

If the function succeeds and the buffer pointer is NULL, the return value is the number of bytes required for the buffer; if the function succeeds and the buffer pointer is a valid pointer, the return value is the number of bytes copied.

If the function fails, the return value is zero.

Remarks

After the Windows-metafile bits are retrieved, they can be used to create a memory-based metafile by calling the SetMetaFileBitsEx function.

The GetMetaFileBitsEx function does not invalidate the metafile handle. An application must delete this handle by calling the DeleteMetaFile function.

A Windows-format metafile does not support the new curve, path, and transformation functions, such as PolyBezier, BeginPath, and SetWorldTransform. Applications that use these new functions and use metafiles to store pictures created by these functions should use the enhanced format metafile functions.

To convert a Windows-format metafile into an enhanced-format metafile, use the SetWinMetaFileBits function.

See Also

BeginPath, DeleteMetaFile, GetEnhMetaFileBits, PolyBezier, SetMetaFileBitsEx, SetWinMetaFileBits, SetWorldTransform


GetMetaRgn
 GetMetaRgn  QuickInfo  Overview  Group

The GetMetaRgn function retrieves the current metaregion for the specified device context.

int GetMetaRgn(

HDC  hdc,	// handle of device context
HRGN  hrgn	// handle of region
);
Parameters

hdc

Identifies the device context.

hrgn

Identifies an existing region before the function is called. After the function returns, this parameter identifies a copy of the current metaregion.

Return Value

If the function succeeds, the return value is one.

If the function fails, the return value is zero.

Remarks

If the function succeeds, hrgn identifies a copy of the current metaregion. Subsequent changes to this copy will not affect the current metaregion.

The current clipping region of a device context is defined by the intersection of its clipping region and its metaregion.

See Also

SetMetaRgn


GetMiterLimit
 GetMiterLimit  QuickInfo  Overview  Group

The GetMiterLimit function returns the miter limit for the specified device context.

BOOL GetMiterLimit(

HDC  hdc,	// handle of device context
PFLOAT  peLimit	// address of variable receiving miter limit
);
Parameters

hdc

Identifies the device context.

peLimit

Points to a floating-point value where the current miter limit will be returned.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The miter limit is used when drawing geometric lines that have miter joins.

See Also

ExtCreatePen, SetMiterLimit


GetModuleFileName
 GetModuleFileName  QuickInfo  Overview  Group

The GetModuleFileName function retrieves the full path and filename for the executable file containing the specified module.

Windows 95 only: The GetModuleFilename function will return long filenames when an application's version number is greater than or equal to 4.00 and the long filename is available. Otherwise, it returns only 8.3 format filenames.

DWORD GetModuleFileName(

HMODULE  hModule,	// handle to module to find filename for
LPTSTR  lpFilename,	// pointer to buffer for module path
DWORD  nSize	// size of buffer, in characters
);
Parameters

hModule

Identifies the module whose executable filename is being requested. If this parameter is NULL, GetModuleFileName returns the path for the file used to create the calling process.

lpFilename

Points to a buffer that is filled in with the path and filename of the given module.

nSize

Specifies the length, in characters, of the lpFilename buffer. If the length of the path and filename exceeds this limit, the string is truncated.

Return Value

If the function succeeds, the return value is the length, in characters, of the string copied to the buffer.

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

Remarks

If a module is loaded in two processes, its module filename in one process may differ in case from its module filename in the other process.

See Also

GetModuleHandle, LoadLibrary


GetModuleHandle
 GetModuleHandle  QuickInfo  Overview  Group

The GetModuleHandle function returns a module handle for the specified module if the file has been mapped into the address space of the calling process.

HMODULE GetModuleHandle(

LPCTSTR  lpModuleName	// address of module name to return handle for
);
Parameters

lpModuleName

Points to a null-terminated string that names a Win32 module (either a .DLL or .EXE file). If the filename extension is omitted, the default library extension .DLL is appended. The filename string can include a trailing point character (.) to indicate that the module name has no extension. The string does not have to specify a path. The name is compared (case independently) to the names of modules currently mapped into the address space of the calling process.

If this parameter is NULL, GetModuleHandle returns a handle of the file used to create the calling process.

Return Value

If the function succeeds, the return value is a handle to the specified module.

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

Remarks

The returned handle is not global, inheritable, or duplicative, and it cannot be used by another process.

The handles returned by GetModuleHandle and LoadLibrary can be used in the same functions — for example, GetProcAddress, FreeLibrary, or LoadResource. The difference between the two functions involves the reference count. LoadLibrary maps the module into the address space of the calling process, if necessary, and increments the module's reference count, if it is already mapped. GetModuleHandle, however, returns the handle of a mapped module without incrementing its reference count.

Note that the reference count is used in FreeLibrary to determine whether to unmap the function from the address space of the process. For this reason, use care when using a handle returned by GetModuleHandle in a call to FreeLibrary because doing so can cause a dynamic-link library (DLL) module to be unmapped prematurely.

This function must also be used carefully in a multithreaded application. There is no guarantee that the module handle remains valid between the time this function returns the handle and the time it is used by another function. For example, a thread might retrieve a module handle by calling GetModuleHandle. Before the thread uses the handle in another function, a second thread could free the module and the system could load another module, giving it the same handle as the module that was recently freed. The first thread would then be left with a module handle that refers to a module different than the one intended.

See Also

FreeLibrary, GetModuleFileName, GetProcAddress, LoadLibrary, LoadResource


GetModuleUsage
 GetModuleUsage  Overview  Group

The GetModuleUsage function has been deleted. Each Win32-based application runs in its own address space.


GetMsgProc
 GetMsgProc  QuickInfo  Overview  Group

The GetMsgProc hook procedure is an application-defined or library-defined callback function that the system calls whenever the GetMessage function has retrieved a message from an application message queue. Before passing the retrieved message to the destination window procedure, the system passes the message to the hook procedure.

LRESULT CALLBACK GetMsgProc(

int  code,	// hook code
WPARAM  wParam,	// removal flag
LPARAM  lParam	// address of structure with message
);
Parameters

code

Specifies whether the hook procedure must process the message. If code is HC_ACTION, the hook procedure must process the message. If code is less than zero, the hook procedure must pass the message to the CallNextHookEx function without further processing and should return the value returned by CallNextHookEx.

wParam

Specifies whether the message has been removed from the queue. This parameter can be one of the following values:

Value	Meaning
PM_NOREMOVE	Specifies that the message has not been removed from the queue. (An application called the PeekMessage function, specifying the PM_NOREMOVE flag.)
PM_REMOVE	Specifies that the message has been removed from the queue. (An application called GetMessage, or it called the PeekMessage function, specifying the PM_REMOVE flag.)
lParam

Points to an MSG structure that contains details about the message.

Return Value

The return value should be zero.

Remarks

The GetMsgProc hook procedure can examine or modify the message. After the hook procedure returns control to the system, the GetMessage function returns the message, along with any modifications, to the application that originally called it.

An application installs this hook procedure by specifying the WH_GETMESSAGE hook type and the address of the hook procedure in a call to the SetWindowsHookEx function.

GetMsgProc is a placeholder for the application-defined or library-defined function name.

See Also

CallNextHookEx, GetMessage, MSG, PeekMessage, SetWindowsHookEx


GetNameByType
 GetNameByType  QuickInfo  Overview  Group

The GetNameByType function obtains the name of a network service. The network service is specified by its service type.

INT GetNameByType(

LPGUID  lpServiceType,	// points to network service type GUID
LPTSTR  lpServiceName,	// points to buffer to receive name of network service
DWORD  dwNameLength	// points to variable that specifies buffer size
);
Parameters

lpServiceType

Points to a globally unique identifier (GUID) that specifies the type of the network service. The header file SVCGUID.H includes definitions of several GUID service types, and macros for working with them.

lpServiceName

Points to a buffer to receive a zero-terminated string that uniquely represents the name of the network service.

dwNameLength

Points to a variable that, on input, specifies the size of the buffer pointed to by lpServiceName. On output, the variable contains the actual size of the service name string.

Return Value

If the function succeeds, the return value is not SOCKET_ERROR ( −1).

If the function fails, the return value is SOCKET_ERROR ( −1). To get extended error information, call GetLastError.

See Also

GetTypeByName


GetNamedPipeHandleState
 GetNamedPipeHandleState  QuickInfo  Overview  Group

The GetNamedPipeHandleState function retrieves information about a specified named pipe. The information returned can vary during the lifetime of an instance of the named pipe.

BOOL GetNamedPipeHandleState(

HANDLE  hNamedPipe,	// handle of named pipe
LPDWORD  lpState,	// address of flags indicating pipe state
LPDWORD  lpCurInstances,	// address of number of current pipe instances
LPDWORD  lpMaxCollectionCount,	// address of max. bytes before remote transmission
LPDWORD  lpCollectDataTimeout,	// address of max. time before remote transmission
LPTSTR  lpUserName,	// address of user name of client process
DWORD  nMaxUserNameSize	// size, in characters, of user name buffer
);
Parameters

hNamedPipe

Identifies the named pipe for which information is wanted. The handle must have GENERIC_READ access to the named pipe.

lpState

Points to a 32-bit variable that indicates the current state of the handle. This parameter can be NULL if this information is not needed. Either or both of the following values can be specified:

Value	Meaning
PIPE_NOWAIT	The pipe handle is in nonblocking mode. If this flag is not specified, the pipe handle is in blocking mode.
PIPE_READMODE_MESSAGE	The pipe handle is in message-read mode. If this flag is not specified, the pipe handle is in byte-read mode.
lpCurInstances

Points to a 32-bit variable that receives the number of current pipe instances. This parameter can be NULL if this information is not required.

lpMaxCollectionCount

Points to a 32-bit variable that receives the maximum number of bytes to be collected on the client's computer before transmission to the server. This parameter must be NULL if the specified pipe handle is to the server end of a named pipe or if client and server processes are on the same computer. This parameter can be NULL if this information is not required.

lpCollectDataTimeout

Points to a 32-bit variable that receives the maximum time, in milliseconds, that can pass before a remote named pipe transfers information over the network. This parameter must be NULL if the specified pipe handle is to the server end of a named pipe or if client and server processes are on the same computer. This parameter can be NULL if this information is not required.

lpUserName

Points to a buffer that receives the null-terminated string containing the user name string of the client application. This parameter must be NULL if the specified pipe handle is to the client end of a named pipe. This parameter can be NULL if this information is not required.

nMaxUserNameSize

Specifies the size, in characters, of the buffer specified by the lpUserName parameter. This parameter is ignored if lpUserName is NULL.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The GetNamedPipeHandleState function returns successfully even if all of the pointers passed to it are NULL.

To set the pipe handle state, use the SetNamedPipeHandleState function.

See Also

SetNamedPipeHandleState


GetNamedPipeInfo
 GetNamedPipeInfo  QuickInfo  Overview  Group

The GetNamedPipeInfo function retrieves information about the specified named pipe.

BOOL GetNamedPipeInfo(

HANDLE  hNamedPipe,	// handle of named pipe
LPDWORD  lpFlags,	// address of flags indicating type of pipe
LPDWORD  lpOutBufferSize,	// address of size, in bytes, of pipe's output buffer
LPDWORD  lpInBufferSize,	// address of size, in bytes, of pipe's input buffer
LPDWORD  lpMaxInstances	// address of max. number of pipe instances
);
Parameters

hNamedPipe

Identifies the named pipe instance. The handle must have GENERIC_READ access to the named pipe.

lpFlags

Points to a 32-bit variable that indicates the type of the named pipe and specifies whether the handle is to the server or client end of the pipe. This parameter can be NULL if this information is not required. Either or both of the following values can be specified:

Value	Meaning
PIPE_CLIENT_END	Windows 95 only: The handle refers to the client end of a named pipe instance. This is the default.
PIPE_SERVER_END	Windows 95 only: The handle refers to the server end of a named pipe instance. If this value is not specified, the handle refers to the client end of a named pipe instance.
PIPE_TYPE_MESSAGE	The named pipe is a message-type pipe. If this value is not specified, the pipe is a byte-type pipe.
lpOutBufferSize

Points to a 32-bit variable that receives the size, in bytes, of the buffer for outgoing data. If the buffer size is zero, the buffer is allocated as needed. This parameter can be NULL if this information is not required.

lpInBufferSize

Points to a 32-bit variable that receives the size, in bytes, of the buffer for incoming data. If the buffer size is zero, the buffer is allocated as needed. This parameter can be NULL if this information is not required.

lpMaxInstances

Points to a 32-bit variable that receives the maximum number of pipe instances that can be created. If the variable is set to PIPE_UNLIMITED_INSTANCES, the number of pipe instances that can be created is limited only by the availability of system resources. This parameter can be NULL if this information is not required.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

CreateNamedPipe, GetNamedPipeHandleState


GetNearestColor
 GetNearestColor  QuickInfo  Overview  Group

The GetNearestColor function returns a color value identifying a color from the system palette that will be displayed when the specified color value is used.

COLORREF GetNearestColor(

HDC  hdc,	// handle of device context
COLORREF  crColor	// color to be matched
);
Parameters

hdc

Identifies the device context.

crColor

Specifies a color value that identifies a requested color.

Return Value

If the function succeeds, the return value identifies a color from the system palette that corresponds to the given color value.

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

See Also

GetDeviceCaps, GetNearestPaletteIndex, COLORREF


GetNearestPaletteIndex
 GetNearestPaletteIndex  QuickInfo  Overview  Group

The GetNearestPaletteIndex function retrieves the index for the entry in the specified logical palette most closely matching a specified color value.

UINT GetNearestPaletteIndex(

HPALETTE  hpal,	// handle of logical color palette
COLORREF  crColor	// color to be matched
);
Parameters

hpal

Identifies a logical color palette.

crColor

Specifies a color to be matched.

Return Value

If the function succeeds, the return value is the index of an entry in a logical palette.

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

Remarks

An application can determine whether a device supports palette operations by calling the GetDeviceCaps function and specifying the RASTERCAPS constant.

If the given logical palette contains entries with the PC_EXPLICIT flag set, the return value is undefined.

See Also

GetDeviceCaps, GetNearestColor, GetPaletteEntries, GetSystemPaletteEntries, COLORREF


GetNextDlgGroupItem
 GetNextDlgGroupItem  QuickInfo  Overview  Group

The GetNextDlgGroupItem function retrieves the handle of the first control in a group of controls that precedes (or follows) the specified control in a dialog box.

HWND GetNextDlgGroupItem(

HWND  hDlg,	// handle of dialog box
HWND  hCtl,	// handle of control
BOOL  bPrevious	// direction flag
);
Parameters

hDlg

Identifies the dialog box being searched.

hCtl

Identifies the control to be used as the starting point for the search. If this parameter is NULL, the function uses the last (or first) control in the dialog box as the starting point for the search.

bPrevious

Specifies how the function is to search the group of controls in the dialog box. If this parameter is TRUE, the function searches for the previous control in the group. If it is FALSE, the function searches for the next control in the group.

Return Value

If GetNextDlgGroupItem succeeds, the return value is the handle of the previous (or next) control in the group of controls.

Remarks

The GetNextDlgGroupItem function searches controls in the order (or reverse order) they were created in the dialog box template. The first control in the group must have the WS_GROUP style; all other controls in the group must have been consecutively created and must not have the WS_GROUP style.

When searching for the previous control, the function returns the first control it locates that is visible and not disabled. If the control given by hCtl has the WS_GROUP style, the function temporarily reverses the search to locate the first control having the WS_GROUP style, then resumes the search in the original direction, returning the first control it locates that is visible and not disabled, or returning hwndCtrl if no such control is found.

When searching for the next control, the function returns the first control it locates that is visible, not disabled, and does not have the WS_GROUP style. If it encounters a control having the WS_GROUP style, the function reverses the search, locates the first control having the WS_GROUP style, and returns this control if it is visible and not disabled. Otherwise, the function resumes the search in the original direction and returns the first control it locates that is visible and not disabled, or returns hCtl if no such control is found.

See Also

GetNextDlgTabItem


GetNextDlgTabItem
 GetNextDlgTabItem  QuickInfo  Overview  Group

The GetNextDlgTabItem function retrieves the handle of the first control that has the WS_TABSTOP style that precedes (or follows) the specified control.

HWND GetNextDlgTabItem(

HWND  hDlg,	// handle of dialog box
HWND  hCtl,	// handle of known control
BOOL  bPrevious	// direction flag
);
Parameters

hDlg

Identifies the dialog box to be searched.

hCtl

Identifies the control to be used as the starting point for the search. If this parameter is NULL, the function uses the last (or first) control in the dialog box as the starting point for the search.

bPrevious

Specifies how the function is to search the dialog box. If this parameter is TRUE, the function searches for the previous control in the dialog box. If this parameter is FALSE, the function searches for the next control in the dialog box.

Return Value

If the function succeeds, the return value is the window handle of the previous (or next) control that has the WS_TABSTOP style set.

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.

See Also

GetDlgItem, GetNextDlgGroupItem


GetNextWindow
 GetNextWindow  QuickInfo  Overview  Group

The GetNextWindow function retrieves the handle of the next or previous window in the Z order. The next window is below the specified window; the previous window is above. Windows maintains separate Z orders for topmost windows, top-level windows, and child windows. If the specified window is a topmost window, the function retrieves the handle of the next (or previous) topmost window. If the specified window is a top-level window, the function retrieves the handle of the next (or previous) top-level window. If the specified window is a a child window, the function searches for a handle of the next (or previous) child window.

HWND GetNextWindow(

HWND  hWnd,	// handle of current window
UINT  wCmd	// direction flag
);
Parameters

hWnd

Identifies a window. The window handle retrieved is relative to this window, based on the value of the wCmd parameter.

wCmd

Specifies whether the function returns the handle of the next window or of the previous window. This parameter can be either of the following values:

Value	Meaning
GW_HWNDNEXT	Returns the handle of the window below the given window.
GW_HWNDPREV	Returns the handle of the window above the given window.
Return Value

If the function succeeds, the return value is the handle of 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.

See Also

GetTopWindow


GetNumberFormat
 GetNumberFormat  QuickInfo  Overview  Group

The GetNumberFormat function formats a number string as a number string customized for a specified locale.

int GetNumberFormat(

LCID  Locale,	// locale for which number string is to be formatted
DWORD  dwFlags,	// bit flag that controls the function's operation
LPCTSTR  lpValue,	// pointer to input number string
CONST NUMBERFMT *  lpFormat,	// pointer to a formatting information structure
LPTSTR  lpNumberStr,	// pointer to output buffer
int  cchNumber	// size of output buffer
);
Parameters

Locale

Specifies the locale for which the number string is to be formatted. If lpFormat is NULL, the function formats the string according to the number format for this locale. If lpFormat is not NULL, the function uses the locale only for formatting information not specified in the NUMBERFMT structure (for example, the locale's string value for the negative sign).

This parameter can be a locale identifier created by the MAKELCID macro, or one of the following predefined values:

LOCALE_SYSTEM_DEFAULT	Default system locale.
LOCALE_USER_DEFAULT	Default user locale.
dwFlags

Contains a bit flag that controls the operation of the function. If lpFormat is non-NULL, this parameter must be zero.

If lpFormat is NULL, you can specify the LOCALE_NOUSEROVERRIDE flag to format the string using the system default number format for the specified locale; or you can specify zero to format the string using any user overrides to the locale's default number format

lpValue

Points to a null-terminated string containing the number string to format.

This string can only contain the following characters:

•	Characters '0' through '9'

•	One decimal point (dot) if the number is a floating-point value

•	A minus sign in the first character position if the number is a negative value

All other characters are invalid. The function returns an error if the string pointed to by lpValue deviates from these rules.

lpFormat

Pointer to a NUMBERFMT structure that contains number formatting information. All members in the structure pointed to by lpFormat must contain appropriate values.

If lpFormat is NULL, the function uses the number format of the specified locale.

lpNumberStr

Points to a buffer to receive the formatted number string.

cchNumber

Specifies the size, in bytes (ANSI version) or characters (Unicode version), of the lpNumberStr buffer. If cchNumber is zero, the function returns the number of bytes or characters required to hold the formatted number string, and the buffer pointed to by lpNumberStr is not used.

Return Value

If the function succeeds, the return value is the number of bytes (ANSI version) or characters (Unicode version) written to the buffer pointed to by lpNumberStr, or if the cchNumber parameter is zero, the number of bytes or characters required to hold the formatted number string.

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

See Also

GetCurrencyFormat, NUMBERFMT


GetNumberOfConsoleInputEvents
 GetNumberOfConsoleInputEvents  QuickInfo  Overview  Group

The GetNumberOfConsoleInputEvents function retrieves the number of unread input records in the console's input buffer.

BOOL GetNumberOfConsoleInputEvents(

HANDLE  hConsoleInput,	// handle of console input buffer
LPDWORD  lpcNumberOfEvents	// address for number of events
);
Parameters

hConsoleInput

Identifies the console input buffer. The handle must have GENERIC_READ access.

lpcNumberOfEvents

Points to a 32-bit variable that receives the number of unread input records in the console's input buffer.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The GetNumberOfConsoleInputEvents function reports the total number of unread input records in the input buffer, including keyboard, mouse, and window-resizing input records. Processes using the ReadFile or ReadConsole function can only read keyboard input. Processes using the ReadConsoleInput function can read all types of input records.

A process can specify a console input buffer handle in one of the wait functions (that is, the WaitForSingleObject or WaitForMultipleObjects function) to determine when there is unread console input. When the input buffer is not empty, the state of a console input buffer handle is signaled.

To read input records from a console input buffer without affecting the number of unread records, use the PeekConsoleInput function. To discard all unread records in a console's input buffer, use the FlushConsoleInputBuffer function.

See Also

FlushConsoleInputBuffer, PeekConsoleInput, ReadConsole, ReadConsoleInput, ReadFile, WaitForMultipleObjects, WaitForSingleObject


GetNumberOfConsoleMouseButtons
 GetNumberOfConsoleMouseButtons  QuickInfo  Overview  Group

The GetNumberOfConsoleMouseButtons function retrieves the number of buttons on the mouse used by the current console.

BOOL GetNumberOfConsoleMouseButtons(

LPDWORD  lpNumberOfMouseButtons	// address of number of buttons
);
Parameters

lpNumberOfMouseButtons

Points to a 32-bit variable that receives the number of mouse buttons.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

When a console receives mouse input, an INPUT_RECORD structure containing a MOUSE_EVENT_RECORD structure is placed in the console's input buffer. The dwButtonState member of MOUSE_EVENT_RECORD has a bit indicating the state of each mouse button. The bit is 1 if the button is down and 0 if the button is up. To determine the number of bits that are significant, use GetNumberOfConsoleMouseButtons.

See Also

ReadConsoleInput, INPUT_RECORD, MOUSE_EVENT_RECORD


GetNumberOfEventLogRecords
 GetNumberOfEventLogRecords  QuickInfo  Overview  Group

The GetNumberOfEventLogRecords function retrieves the number of records in the specified event log.

BOOL GetNumberOfEventLogRecords(

HANDLE  hEventLog,	// handle to event log
PDWORD  NumberOfRecords	// buffer for number of records
);
Parameters

hEventLog

Identifies the open event log. This handle is returned by the OpenEventLog or OpenBackupEventLog function.

NumberOfRecords

Points to a variable that receives the number of records in the given event log.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

GetOldestEventLogRecord, OpenBackupEventLog, OpenEventLog


GetObject
 GetObject  QuickInfo  Overview  Group

The GetObject function obtains information about a specified graphics object. Depending on the graphics object, the function places a filled-in BITMAP, DIBSECTION, EXTLOGPEN, LOGBRUSH, LOGFONT, or LOGPEN structure, or a count of table entries (for a logical palette), into a specified buffer.

int GetObject(

HGDIOBJ  hgdiobj,	// handle to graphics object of interest
int  cbBuffer,	// size of buffer for object information
LPVOID  lpvObject	// pointer to buffer for object information
);
Parameters

hgdiobj

A handle to the graphics object of interest. This can be a handle to one of the following: a logical bitmap, a brush, a font, a palette, a pen, or a device independent bitmap created by calling the CreateDIBSection function.

cbBuffer

Specifies the number of bytes of information to be written to the buffer.

lpvObject

Points to a buffer that is to receive the information about the specified graphics object.

The following table shows the type of information the buffer receives for each type of graphics object you can specify with hgdiobj:

hgdiobj Type	Data Written to *lpvObject
HBITMAP	BITMAP
HBITMAP returned from a call to CreateDIBSection	DIBSECTION, if cbBuffer is set to sizeof(DIBSECTION), or BITMAP, if cbBuffer is set to sizeof(BITMAP)
HPALETTE	a WORD count of the number of entries in the logical palette
HPEN returned from a call to ExtCreatePen	EXTLOGPEN
HPEN	LOGPEN
HBRUSH	LOGBRUSH
HFONT	LOGFONT
If the lpvObject parameter is NULL, the function return value is the number of bytes required to store the information it writes to the buffer for the specified graphics object.

Return Value

If the function succeeds, and lpvObject is a valid pointer, the return value is the number of bytes stored into the buffer.

If the function succeeds, and lpvObject is NULL, the return value is the number of bytes required to hold the information the function would store into the buffer.

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

Remarks

The buffer pointed to by the lpvObject parameter must be sufficiently large to receive the information about the graphics object.

If hgdiobj identifies a bitmap created by calling CreateDIBSection, and the specified buffer is large enough, the GetObject function returns a DIBSECTION structure. In addition, the bmBits member of the BITMAP structure contained within the DIBSECTION will contain a pointer to the bitmap's bit values.

If hgdiobj identifies a bitmap created by any other means, GetObject returns only the width, height, and color format information of the bitmap. You can obtain the bitmap's bit values by calling the GetDIBits or GetBitmapBits function.

If hgdiobj identifies a logical palette, GetObject retrieves a two-byte integer that specifies the number of entries in the palette. The function does not retrieve the LOGPALETTE structure defining the palette. To retrieve information about palette entries, an application can call the GetPaletteEntries function.

See Also

CreateDIBSection, GetBitmapBits, GetDIBits, GetPaletteEntries, GetRegionData, BITMAP, DIBSECTION, EXTLOGPEN, LOGBRUSH, LOGFONT, LOGPALETTE, LOGPEN


GetObjectType
 GetObjectType  QuickInfo  Overview  Group

The GetObjectType identifies the type of the specified object.

DWORD GetObjectType(

HGDIOBJ  h	// handle of graphic object
);
Parameters

h

Identifies the object.

Return Value

If the function succeeds, the return value identifies the object. This value can be one of the following:

Value	Meaning
OBJ_BITMAP	Bitmap
OBJ_BRUSH	Brush
OBJ_FONT	Font
OBJ_PAL	Palette
OBJ_PEN	Pen
OBJ_EXTPEN	Extended pen
OBJ_REGION	Region
OBJ_DC	Device context
OBJ_MEMDC	Memory device context
OBJ_METAFILE	Metafile
OBJ_METADC	Metafile device context
OBJ_ENHMETAFILE	Enhanced metafile
OBJ_ENHMETADC	Enhanced metafile device context
If the function fails, the return value is zero.

See Also

GetObject, SelectObject


GetOEMCP
 GetOEMCP  QuickInfo  Overview  Group

The GetOEMCP function retrieves the current OEM code-page identifier for the system. (OEM stands for original equipment manufacturer.)

UINT GetOEMCP(VOID)

Parameters

This function has no parameters.

Return Value

If the function succeeds, the return value is the current OEM code-page identifier for the system or a default identifier if no code page is current.

Remarks

Following are the OEM code-page identifiers:

Identifier	Meaning
437	MS-DOS United States
708	Arabic (ASMO 708)
709	Arabic (ASMO 449+, BCON V4)
710	Arabic (Transparent Arabic)
720	Arabic (Transparent ASMO)
737	Greek (formerly 437G)
775	Baltic
850	MS-DOS Multilingual (Latin I)
852	MS-DOS Slavic (Latin II)
855	IBM Cyrillic (primarily Russian)
857	IBM Turkish
860	MS-DOS Portuguese
861	MS-DOS Icelandic
862	Hebrew
863	MS-DOS Canadian-French
864	Arabic
865	MS-DOS Nordic
866	MS-DOS Russian (former USSR)
869	IBM Modern Greek
874	Thai
932	Japan
936	Chinese (PRC, Singapore)
949	Korean
950	Chinese (Taiwan, Hong Kong)
1361	Korean (Johab)
See Also

GetACP


GetOldestEventLogRecord
 GetOldestEventLogRecord  QuickInfo  Overview  Group

The GetOldestEventLogRecord function retrieves the absolute record number of the oldest record in the specified event log.

BOOL GetOldestEventLogRecord(

HANDLE  hEventLog,	// handle to event log
PDWORD  OldestRecord	// buffer for number of oldest record
);
Parameters

hEventLog

Identifies the open event log. This handle is returned by the OpenEventLog or OpenBackupEventLog function.

OldestRecord

Points to the variable that receives the absolute record number of the oldest record in the given event log.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

GetNumberOfEventLogRecords, OpenBackupEventLog, OpenEventLog


GetOpenClipboardWindow
 GetOpenClipboardWindow  QuickInfo  Overview  Group

The GetOpenClipboardWindow function retrieves the handle of the window that currently has the clipboard open.

HWND GetOpenClipboardWindow(VOID)

Parameters

This function has no parameters.

Return Value

If the function succeeds, the return value is the handle of the window that has the clipboard open. If no window has the clipboard open, the return value is NULL. To get extended error information, call GetLastError.

Remarks

If an application or dynamic-link library (DLL) specifies a NULL window handle when calling the OpenClipboard function, the clipboard is opened but is not associated with a window. In such a case, GetOpenClipboardWindow returns NULL.

See Also

GetClipboardOwner, GetClipboardViewer, GetOpenClipboardWindow, OpenClipboard


GetOpenFileName
 GetOpenFileName  QuickInfo  Overview  Group

The GetOpenFileName function creates a system-defined dialog box that enables the user to select a file to open.

BOOL GetOpenFileName(

LPOPENFILENAME  lpofn	// address of structure with initialization data
);
Parameters

lpofn

Points 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 Value

If the user selects a file to open, the return value is TRUE. It is FALSE if an error occurs, the user chooses the Cancel button, the user chooses the Close command on the System menu to close the dialog box, or the buffer identified by the lpstrFile member of the OPENFILENAME structure is too small to contain the string that specifies the selected file.

To get extended error information, call CommDlgExtendedError. CommDlgExtendedError may return one of the following error codes:

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

If the hook function (pointed to by the lpfnHook member of the OPENFILENAME structure) processes the WM_CTLCOLORBTN, WM_CTLCOLORDLG, WM_CTLCOLORLISTBOX, WM_CTLCOLORMSGBOX, WM_CTLCOLORSCROLLBAR, or WM_CTLCOLORSTATIC message, GetOpenFileName must return a handle of the brush that should be used to paint the control background.

Ending the dialog box from within the hook function by calling the EndDialog function prevents the COMDLG32.DLL dynamic link library (DLL) from properly exiting its worker thread. For applications that dynamically load and/or unload COMDLG32.DLL, this type of exiting may result in an access violation during unloading as the worker thread's address space is invalidated.

See Also

CommDlgExtendedError, EndDialog, GetSaveFileName, OPENFILENAME


GetOutlineTextMetrics
 GetOutlineTextMetrics  QuickInfo  Overview  Group

The GetOutlineTextMetrics function retrieves text metrics for TrueType fonts.

UINT GetOutlineTextMetrics(

HDC  hdc,	// handle of device context
UINT  cbData,	// size of metric data array
LPOUTLINETEXTMETRIC  lpOTM	// address of metric data array
);
Parameters

hdc

Identifies the device context.

cbData

Specifies the size, in bytes, of the array in which the text metrics are to be returned.

lpOTM

Points to an array of OUTLINETEXTMETRIC structures. If this parameter is NULL, the function returns the size of the buffer required for the retrieved metric data.

Return Value

If the function succeeds, the return value is TRUE or the size of the required buffer.

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

Remarks

The OUTLINETEXTMETRIC structure contains most of the text metric information provided for TrueType fonts (including a TEXTMETRIC structure). The sizes returned in the OUTLINETEXTMETRIC structures are in logical units; they depend on the current mapping mode.

See Also

GetTextMetrics, OUTLINETEXTMETRIC, TEXTMETRIC


GetOverlappedResult
 GetOverlappedResult  QuickInfo  Overview  Group

The GetOverlappedResult function returns the results of an overlapped operation on the specified file, named pipe, or communications device.

Windows 95: This function works only on serial devices or on files opened by using the DeviceIoControl function.

BOOL GetOverlappedResult(

HANDLE  hFile,	// handle of file, pipe, or communications device
LPOVERLAPPED  lpOverlapped,	// address of overlapped structure
LPDWORD  lpNumberOfBytesTransferred,	// address of actual bytes count
BOOL  bWait	// wait flag
);
Parameters

hFile

Identifies the file, named pipe, or communications device. This is the same handle that was specified when the overlapped operation was started by a call to the ReadFile, WriteFile, ConnectNamedPipe, TransactNamedPipe, DeviceIoControl, or WaitCommEvent function.

lpOverlapped

Points to an OVERLAPPED structure that was specified when the overlapped operation was started.

lpNumberOfBytesTransferred

Points to a 32-bit variable that receives the number of bytes that were actually transferred by a read or write operation. For a TransactNamedPipe operation, this is the number of bytes that were read from the pipe. For a DeviceIoControl operation, this is the number of bytes of output data returned by the device driver. For a ConnectNamedPipe or WaitCommEvent operation, this value is undefined.

bWait

Specifies whether the function should wait for the pending overlapped operation to be completed. If TRUE, the function does not return until the operation has been completed. If FALSE and the operation is still pending, the function returns FALSE and the GetLastError function returns ERROR_IO_INCOMPLETE.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The results reported by the GetOverlappedResult function are those of the specified handle's last overlapped operation to which the specified OVERLAPPED structure was provided, and for which the operation's results were pending. A pending operation is indicated when the function that started the operation returns FALSE, and the GetLastError function returns ERROR_IO_PENDING. When an I/O operation is pending, the function that started the operation resets the hEvent member of the OVERLAPPED structure to the nonsignaled state. Then when the pending operation has been completed, the system sets the event object to the signaled state.

If the bWait parameter is TRUE, GetOverlappedResult determines whether the pending operation has been completed by waiting for the event object to be in the signaled state.

If the hEvent member of the OVERLAPPED structure is NULL, the system uses the state of the hFile handle to signal when the operation has been completed. Use of file, named pipe, or communications-device handles for this purpose is discouraged. It is safer to use an event object because of the confusion that can occur when multiple simultaneous overlapped operations are performed on the same file, named pipe, or communications device. In this situation, there is no way to know which operation caused the object's state to be signaled.

Specify a manual-reset event object in the OVERLAPPED structure. If an auto-reset event object is used, the event handle must not be specified in any other wait operation in the interval between starting the overlapped operation and the call to GetOverlappedResult. For example, the event object is sometimes specified in one of the wait functions to wait for the operation's completion. When the wait function returns, the system sets an auto-reset event's state to nonsignaled, and a subsequent call to GetOverlappedResult with the bWait parameter set to TRUE causes the function to be blocked indefinitely.

See Also

ConnectNamedPipe, CreateEvent, DeviceIoControl, GetLastError, OVERLAPPED, ReadFile, TransactNamedPipe, WaitCommEvent, WriteFile


GetPaletteEntries
 GetPaletteEntries  QuickInfo  Overview  Group

The GetPaletteEntries function retrieves a specified range of palette entries from the given logical palette.

UINT GetPaletteEntries(

HPALETTE  hpal,	// handle of logical color palette
UINT  iStartIndex,	// first entry to retrieve
UINT  nEntries,	// number of entries to retrieve
LPPALETTEENTRY  lppe	// address of array receiving entries
);
Parameters

hpal

Identifies the logical color palette.

iStartIndex

Specifies the first entry in the logical palette to be retrieved.

nEntries

Specifies the number of entries in the logical palette to be retrieved.

lppe

Points to an array of PALETTEENTRY structures to receive the palette entries. The array must contain at least as many structures as specified by the nEntries parameter.

Return Value

If the function succeeds and the handle of the logical color palette is a valid pointer (not NULL), the return value is the number of entries retrieved from the logical palette. If the function succeeds and handle of the logical color palette is NULL, the return value is the number of entries in the given palette.

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

Remarks

An application can determine whether a device supports palette operations by calling the GetDeviceCaps function and specifying the RASTERCAPS constant.

If the nEntries parameter specifies more entries than exist in the palette, the remaining members of the PALETTEENTRY structure are not altered.

See Also

GetDeviceCaps, GetSystemPaletteEntries, PALETTEENTRY


GetParent
 GetParent  QuickInfo  Overview  Group

The GetParent function retrieves the handle of the specified child window's parent window.

HWND GetParent(

HWND  hWnd	// handle of child window
);
Parameters

hWnd

Identifies the window whose parent window handle is to be retrieved.

Return Value

If the function succeeds, the return value is the handle of the parent window. If the window has no parent window, the return value is NULL. To get extended error information, call GetLastError.

See Also

SetParent


GetPath
 GetPath  QuickInfo  Overview  Group

The GetPath function retrieves the coordinates defining the endpoints of lines and the control points of curves found in the path that is selected into the specified device context.

int GetPath(

HDC  hdc,	// handle of device context
LPPOINT  lpPoints,	// address of array receiving path vertices
LPBYTE  lpTypes,	// address of array of path vertex types
int  nSize	// count of points defining path
);
Parameters

hdc

Identifies a device context that contains a closed path.

lpPoints

Points to an array of POINT structures that contains the line endpoints and curve control points.

lpTypes

Points to an array of bytes where the vertex types are placed. Values are one of the following:

Type	Description
PT_MOVETO	Specifies that the corresponding point in the lpPoints parameter starts a disjoint figure.
PT_LINETO	Specifies that the previous point and the corresponding point in lpPoints are the endpoints of a line.
PT_BEZIERTO	Specifies that the corresponding point in lpPoints is a control point or ending point for a Bézier curve.
	PT_BEZIERTO values always occur in sets of three. The point in the path immediately preceding them defines the starting point for the Bézier curve. The first two PT_BEZIERTO points are the control points, and the third PT_BEZIERTO point is the ending (if hard-coded) point.
A PT_LINETO or PT_BEZIERTO value may be combined with the following value (by using the bitwise operator OR) to indicate that the corresponding point is the last point in a figure and the figure should be closed:

Flag	Description
PT_CLOSEFIGURE	Specifies that the figure is automatically closed after the corresponding line or curve is drawn. The figure is closed by drawing a line from the line or curve endpoint to the point corresponding to the last PT_MOVETO.
nSize

Specifies the total number of POINT structures that may be placed in the array pointed to by lpPoints. This value must be the same as the number of bytes that may be placed in the array pointed to by lpTypes.

Return Value

If the nSize parameter is nonzero, the return value is the number of points enumerated. If nSize is 0, the return value is the total number of points in the path (and GetPath writes nothing to the buffers). If nSize is nonzero and is less than the number of points in the path, the return value is −1. To get extended error information, call GetLastError. GetLastError may return one of the following error codes:

ERROR_CAN_NOT_COMPLETE
ERROR_INVALID_PARAMETER
ERROR_BUFFER_OVERFLOW

Remarks

The device context identified by the hdc parameter must contain a closed path.

The points of the path are returned in logical coordinates. Points are stored in the path in device coordinates, so GetPath changes the points from device coordinates to logical coordinates by using the inverse of the current transformation.

The FlattenPath function may be called before GetPath to convert all curves in the path into line segments.

See Also

FlattenPath, POINT, PolyDraw, WidenPath


getpeername
 getpeername  QuickInfo

The Windows Sockets getpeername function gets the address of the peer to which a socket is connected.

int getpeername(

SOCKET s,
struct sockaddr FAR * name,
int FAR * namelen
);
Parameters

s

A descriptor identifying a connected socket.

name

The structure which is to receive the name of the peer.

namelen

A pointer to the size of the name structure.

Return Value

If no error occurs, getpeername returns zero. Otherwise, a value of SOCKET_ERROR is returned, and a specific error code may be retrieved by calling WSAGetLastError.

Error Codes

WSANOTINITIALISED	A successful WSAStartup must occur before using this function.
WSAENETDOWN	The Windows Sockets implementation has detected that the network subsystem has failed.
WSAEFAULT	The namelen argument is not large enough.
WSAEINPROGRESS	A blocking Windows Sockets call is in progress.
WSAENOTCONN	The socket is not connected.
WSAENOTSOCK	The descriptor is not a socket.
Remarks

The getpeername function retrieves the name of the peer connected to the socket s and stores it in the socket address structure identified by name. It is used on a connected datagram or stream socket.

On return, the namelen argument contains the actual size of the name returned in bytes.

See Also

bind, getsockname, socket


GetPixel
 GetPixel  QuickInfo  Overview  Group

The GetPixel function retrieves the red, green, blue (RGB) color value of the pixel at the specified coordinates.

COLORREF GetPixel(

HDC  hdc,	// handle of device context
int  nXPos,	// x-coordinate of pixel
int  nYPos	// y-coordinate of pixel
);
Parameters

hdc

Identifies the device context.

nXPos

Specifies the logical x-coordinate of the pixel to be examined.

nYPos

Specifies the logical y-coordinate of the pixel to be examined.

Return Value

If the function succeeds, the return value is an RGB value. If the pixel is outside of the current clipping region, the return value is CLR_INVALID.

Remarks

The pixel must be within the boundaries of the current clipping region.

Not all devices support GetPixel. An application should call GetDeviceCaps to determine whether a specified device supports this function.

See Also

GetDeviceCaps


GetPolyFillMode
 GetPolyFillMode  QuickInfo  Overview  Group

The GetPolyFillMode function retrieves the current polygon fill mode.

int GetPolyFillMode(

HDC  hdc	// handle of device context
);
Parameters

hdc

Identifies the device context.

Return Value

If the function succeeds, the return value specifies the polygon fill mode, which can be either of the following values:

Value	Meaning
ALTERNATE	Selects alternate mode (fills area between odd-numbered and even-numbered polygon sides on each scan line).
WINDING	Selects winding mode (fills any region with a nonzero winding value).
If an error occurs, the return value is zero.

See Also

SetPolyFillMode


GetPrinter
 GetPrinter  QuickInfo  Overview  Group

The GetPrinter function retrieves information about a specified printer.

BOOL GetPrinter(

HANDLE  hPrinter,	// handle to printer of interest
DWORD  Level,	// version of printer info data structure
LPBYTE  pPrinter,	// pointer to array of bytes that receives printer info. structure
DWORD  cbBuf,	// size, in bytes, of array of bytes
LPDWORD  pcbNeeded	// pointer to variable with count of bytes retrieved (or required)
);
Parameters

hPrinter

Handle to the printer of interest.

Level

Specifies the level, or type, of PRINTER_INFO_* structure that the function stores into the buffer pointed to by pPrinter.

Windows 95: This value can be 1, 2, or 5.

Windows NT: This value can be 1, 2, 3, or 4.

pPrinter

Pointer to a buffer that receives a PRINTER_INFO_* structure. This structure contains information about the specified printer. The type of structure is determined by the value of Level.

Windows 95: The buffer can receive a PRINTER_INFO_1, PRINTER_INFO_2, PRINTER_INFO_5 structure.

Windows NT: The buffer can receive a PRINTER_INFO_1, PRINTER_INFO_2, or PRINTER_INFO_3 or PRINTER_INFO_4, structure.

cbBuf

Specifies the size, in bytes, of the buffer pointed to by pPrinter.

pcbNeeded

Pointer to a variable that the function sets to the size in bytes of the printer information. If cbBuf is smaller than this value, GetPrinter fails, and the value represents the required buffer size. If cbBuf is equal to or greater than this value, GetPrinter succeeds, and the value represents the number of bytes stored into the buffer.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

If the structure returned in the buffer pointed to by the pPrinter parameter contains a pointer to a security descriptor, only those components of the security descriptor that the caller has permission to read will be present. An application that wants to retrieve particular security descriptor components must open the printer with sufficient access permission. The following table shows the security descriptor components that are retrieved for particular access permission values:

Access Permission	Security Descriptor Components Retrieved
READ_CONTROL	Owner, Primary Group, Discretionary access-control list (ACL)
ACCESS_SYSTEM_SECURITY	System ACL
See Also

AbortPrinter, AddPrinter, ClosePrinter, DeletePrinter, EnumPrinters, PRINTER_INFO_1, PRINTER_INFO_2, PRINTER_INFO_3, PRINTER_INFO_4, PRINTER_INFO_5, OpenPrinter, SetPrinter


GetPrinterData
 GetPrinterData  QuickInfo  Overview  Group

The GetPrinterData function retrieves printer-configuration data for the specified printer.

DWORD GetPrinterData(

HANDLE  hPrinter,	// handle of printer object
LPTSTR  pValueName,	// address of data type
LPDWORD  pType,	// reserved
LPBYTE  pData,	// address of array of bytes that receives data
DWORD  nSize,	// size, in bytes, of array
LPDWORD  pcbNeeded	// address of variable with number of bytes retrieved (or required)
);
Parameters

hPrinter

Identifies the printer for which configuration data should be retrieved.

pValueName

Points to a null-terminated string that specifies the type of data that the function should retrieve.

pType

Points to a variable that receives the data type stored by the SetPrinterData function. GetPrinterData passes pType on as the lpdwType parameter of a RegQueryValueEx function call. This parameter may be NULL.

pData

Points to an array of bytes that receives the configuration data.

nSize

Specifies the size, in bytes, of the buffer pointed to by pData.

pcbNeeded

Points to a value that specifies the number of bytes copied if the function succeeds or the number of bytes required if nSize is too small.

Return Value

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is an error value.

Remarks

The printer handle identified by the hPrinter parameter is obtained by calling the OpenPrinter function.

GetPrinterData retrieves printer-configuration data set by the SetPrinter function.

See Also

OpenPrinter, RegQueryValueEx, SetPrinter, SetPrinterData,


GetPrinterDriver
 GetPrinterDriver  QuickInfo  Overview  Group

The GetPrinterDriver function retrieves driver data for the specified printer.

BOOL GetPrinterDriver(

HANDLE  hPrinter,	// printer object
LPTSTR  pEnvironment,	// address of environment
DWORD  Level,	// structure level
LPBYTE  pDriverInfo,	// address of structure array
DWORD  cbBuf,	// size, in bytes, of array
LPDWORD  pcbNeeded	// address of variable with number of bytes retrieved (or required)
);
Parameters

hPrinter

Identifies the printer for which the driver data should be retrieved.

pEnvironment

Points to a null-terminated string that specifies the environment. For example, "Windows NT x86" specifies Windows NT running on an Intel 80386 or 80486 processor. If this parameter is NULL, the current environment of the calling application and client machine (not of the destination application and print server) is used.

Level

Specifies the version of the structure to which lpbForm points. This value must be either 1, 2., or 3.

Windows 95

The value can be 1, 2, or 3.

Windows NT

The value must be either 1 or 2.

pDriverInfo

Points to either a DRIVER_INFO_1, DRIVER_INFO_2, or DRIVER_INFO_3structure. If Level is 1, this array receives a DRIVER_INFO_1 structure; if Level is 2, this array receives a DRIVER_INFO_2 structure, if Level is 3, this array receives a DRIVER_INFO_3 structure.

Windows 95

All three driver-information structures are supported..

Windows NT

DRIVER_INFO_3 structure is not supported.

cbBuf

Specifies the size, in bytes, of the array at which pDriverInfo points.

pcbNeeded

Points to a value that specifies the number of bytes copied if the function succeeds or the number of bytes required if cbBuf is too small.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The printer handle identified by the hPrinter parameter should be retrieved by calling the OpenPrinter function.

The DRIVER_INFO_2 and DRIVER_INFO_3 structures contain a full path and filename specifying the location of the printer driver. An application can use the path and filename to load a printer driver by calling the LoadLibrary function and supplying the path and filename as the single argument.

See Also

AddPrinterDriver, DRIVER_INFO_1, DRIVER_INFO_2, EnumPrinterDrivers, LoadLibrary, OpenPrinter


GetPrinterDriverDirectory
 GetPrinterDriverDirectory  QuickInfo  Overview  Group

The GetPrinterDriverDirectory function retrieves the path of the printer-driver directory.

BOOL GetPrinterDriverDirectory(

LPTSTR  pName,	// address of server name
LPTSTR  pEnvironment,	// address of environment
DWORD  Level,	// address of structure
LPBYTE  pDriverDirectory,	// address of structure array that receives path
DWORD  cbBuf,	// size, in bytes, of array
LPDWORD  pcbNeeded	// address of variable with number of bytes retrieved (or required)
);
Parameters

pName

Points to a null-terminated string that specifies the name of the server on which the printer driver resides. If this parameter is NULL, the local driver-directory path is retrieved.

pEnvironment

Points to a null-terminated string that specifies the environment. For example, "Windows NT x86" specifies Windows NT running on an Intel 80386 or 80486 processor. If this parameter is NULL, the current environment of the calling application and client machine (not of the destination application and print server) is used.

Level

Specifies the structure level. This value must be 1.

pDriverDirectory

Points to an array of bytes that receives the path.

cbBuf

Specifies the size of the array to which pDriverDirectory points.

pcbNeeded

Points to a value that specifies the number of bytes copied if the function succeeds, or the number of bytes required if cbBuf is too small.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

AddPrinterDriver


GetPrintProcessorDirectory
 GetPrintProcessorDirectory  QuickInfo  Overview  Group

The GetPrintProcessorDirectory function retrieves the path for the print processor on the specified server.

BOOL GetPrintProcessorDirectory(

LPTSTR  pName,	// address of server name
LPTSTR  pEnvironment,	// address of environment
DWORD  Level,	// structure level
LPBYTE  pPrintProcessorInfo,	// address of structure array
DWORD  cbBuf,	// size, in bytes, of array
LPDWORD  pcbNeeded	// address of variable with number of bytes retrieved (or required)
);
Parameters

pName

Points to a null-terminated string that specifies the name of the server. If this parameter is NULL, a local path is returned.

pEnvironment

Points to a null-terminated string that specifies the environment. For example, "Windows NT x86" specifies Windows NT running on an Intel 80386 or 80486 processor. If this parameter is NULL, the current environment of the calling application and client machine (not of the destination application and print server) is used.

Level

Specifies the structure level. This value must be 1.

pPrintProcessorInfo

Points to an array of bytes into which the path is copied.

cbBuf

Specifies the size of the buffer pointed to by pPrintProcessorInfo.

pcbNeeded

Points to a value that specifies the number of bytes copied if the function succeeds, or the number of bytes required if cbBuf is too small.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

AddPrintProcessor


GetPriorityClass
 GetPriorityClass  QuickInfo  Overview  Group

The GetPriorityClass function returns the priority class for the specified process. This value, together with the priority value of each thread of the process, determines each thread's base priority level.

DWORD GetPriorityClass(

HANDLE  hProcess	// handle to the process
);
Parameters

hProcess

Identifies the process. The handle must have PROCESS_QUERY_INFORMATION access.

Return Value

If the function succeeds, the return value is the priority class of the specified process.

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

The process's priority class is one of the following values:

Priority	Meaning
HIGH_PRIORITY_CLASS	Indicates a process that performs time-critical tasks that must be executed immediately for it to run correctly. The threads of a high-priority class process preempt the threads of normal or idle priority class processes. An example is Windows Task List, which must respond quickly when called by the user, regardless of the load on the operating system. Use extreme care when using the high-priority class, because a high-priority class CPU-bound application can use nearly all available cycles.
IDLE_PRIORITY_CLASS	Indicates a process whose threads run only when the system is idle and are preempted by the threads of any process running in a higher priority class. An example is a screen saver. The idle priority class is inherited by child processes.
NORMAL_PRIORITY_CLASS	Indicates a normal process with no special scheduling needs.
REALTIME_PRIORITY_CLASS	Indicates a process that has the highest possible priority. The threads of a real-time priority class process preempt the threads of all other processes, including operating system processes performing important tasks. For example, a real-time process that executes for more than a very brief interval can cause disk caches not to flush or cause the mouse to be unresponsive.
Remarks

Every thread has a base priority level determined by the thread's priority value and the priority class of its process. The operating system uses the base priority level of all executable threads to determine which thread gets the next slice of CPU time. Threads are scheduled in a round-robin fashion at each priority level, and only when there are no executable threads at a higher level will scheduling of threads at a lower level take place.

For a table that shows the base priority levels for each combination of priority class and thread priority value, see the SetPriorityClass function.

See Also

GetThreadPriority, SetPriorityClass, SetThreadPriority


GetPriorityClipboardFormat
 GetPriorityClipboardFormat  QuickInfo  Overview  Group

The GetPriorityClipboardFormat function returns the first available clipboard format in the specified list.

int GetPriorityClipboardFormat(

UINT  * paFormatPriorityList,	// address of priority list
int  cFormats	// number of entries in list
);
Parameters

paFormatPriorityList

Points to an array of unsigned integers identifying clipboard formats, in priority order. For a description of the clipboard formats, see the SetClipboardData function.

cFormats

Specifies the number of entries in the paFormatPriorityList array. This value must not be greater than the number of entries in the list.

Return Value

If the function succeeds, the return value is the first clipboard format in the list for which data is available. If the clipboard is empty, the return value is NULL. If the clipboard contains data, but not in any of the specified formats, the return value is −1. To get extended error information, call GetLastError.

See Also

CountClipboardFormats, EnumClipboardFormats, GetClipboardFormatName, IsClipboardFormatAvailable, RegisterClipboardFormat, SetClipboardData


GetPrivateObjectSecurity
 GetPrivateObjectSecurity  QuickInfo  Overview  Group

The GetPrivateObjectSecurity retrieves information from a protected server object's security descriptor.

BOOL GetPrivateObjectSecurity(

PSECURITY_DESCRIPTOR  ObjectDescriptor,	// address of SD to query
SECURITY_INFORMATION  SecurityInformation,	// requested information
PSECURITY_DESCRIPTOR  ResultantDescriptor,	// address of retrieved SD
DWORD  DescriptorLength,	// size of buffer for retrieved SD
PDWORD  ReturnLength	// address of buffer size required for SD
);
Parameters

ObjectDescriptor

Points to a SECURITY_DESCRIPTOR structure. This is the security descriptor to be queried.

SecurityInformation

Specifies a SECURITY_INFORMATION structure that identifies the security information being requested.

ResultantDescriptor

Points to a buffer receiving a copy of the requested information from the specified security descriptor. The SECURITY_DESCRIPTOR structure is returned in self-relative format.

DescriptorLength

Specifies the size, in bytes, of the buffer pointed to by the ResultantDescriptor parameter.

ReturnLength

Points to a variable the function sets to zero if the descriptor is copied successfully. If the buffer is too small for the security descriptor, this variable receives the number of bytes required. If this variable's value is greater than the value of the DescriptorLength parameter when the function returns, the function returns FALSE and none of the security descriptor is copied to the buffer.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

An application must perform appropriate access/privilege checks and audits before calling this function.

See Also

CreatePrivateObjectSecurity, DestroyPrivateObjectSecurity, GetFileSecurity, GetKernelObjectSecurity, GetUserObjectSecurity, SECURITY_DESCRIPTOR, SECURITY_INFORMATION, SetPrivateObjectSecurity


GetPrivateProfileInt
 GetPrivateProfileInt  QuickInfo

The GetPrivateProfileInt function retrieves an integer associated with a key in the specified section of the given initialization file. This function is provided for compatibility with 16-bit Windows-based applications. Win32-based applications should store initialization information in the registry.

UINT GetPrivateProfileInt(

LPCTSTR  lpAppName,	// address of section name
LPCTSTR  lpKeyName,	// address of key name
INT  nDefault,	// return value if key name is not found
LPCTSTR  lpFileName	// address of initialization filename
);
Parameters

lpAppName

Points to a null-terminated string containing the section name in the initialization file.

lpKeyName

Points to the null-terminated string containing the key name whose value is to be retrieved. This value is in the form of a string; the GetPrivateProfileInt function converts the string into an integer and returns the integer.

nDefault

Specifies the default value to return if the key name cannot be found in the initialization file.

lpFileName

Points to a null-terminated string that names the initialization file. If this parameter does not contain a full path to the file, Windows searches for the file in the Windows directory.

Return Value

If the function succeeds, the return value is the integer equivalent of the string following the specified key name in the specified initialization file. If the key is not found, the return value is the specified default value. If the value of the key is less than zero, the return value is zero.

Remarks

The function searches the file for a key that matches the name specified by the lpKeyName parameter under the section name specified by the lpAppName parameter. A section in the initialization file must have the following form:

[section]
key=value
      .
      .
      .

The GetPrivateProfileInt function is not case-sensitive; the strings in lpAppName and lpKeyName can be a combination of uppercase and lowercase letters.

An application can use the GetProfileInt function to retrieve an integer value from the WIN.INI file.

Windows NT: Calls to private profile functions may be mapped to the registry instead of to the specified initialization files. This mapping occurs when the initialization file and section are specified in the registry under the following keys:

HKEY_LOCAL_MACHINE\Software\Microsoft\
        Windows NT\CurrentVersion\IniFileMapping

This mapping is likely if an application modifies system-component initialization files, such as CONTROL.INI, SYSTEM.INI, and WINFILE.INI. In these cases, the GetPrivateProfileInt function retrieves information from the registry, not from the initialization file; the change in the storage location has no effect on the function's behavior.

See Also

GetProfileInt, WritePrivateProfileString


GetPrivateProfileSection
 GetPrivateProfileSection  QuickInfo

The GetPrivateProfileSection function retrieves all of the keys and values for the specified section from an initialization file. This function is provided for compatibility with 16-bit applications written for Windows. Win32-based applications should store initialization information in the registry.

Windows 95

The specified profile section must not exceed 32K.

Windows NT

The specified profile section has no size limit.

DWORD GetPrivateProfileSection(

LPCTSTR  lpAppName,	// address of section name
LPTSTR  lpReturnedString,	// address of return buffer
DWORD  nSize,	// size of return buffer
LPCTSTR  lpFileName	// address of initialization filename
);
Parameters

lpAppName

Points to a null-terminated string containing the section name in the initialization file.

lpReturnedString

Points to a buffer that receives the key name and value pairs associated with the named section. The buffer is filled with one or more null-terminated strings; the last string is followed by a second null character.

nSize

Specifies the size, in characters, of the buffer pointed to by the lpReturnedString parameter.

Windows 95

The maximum buffer size is 32,767 characters.

Windows NT

There is no maximum buffer size.

lpFileName

Points to a null-terminated string that names the initialization file. If this parameter does not contain a full path to the file, Windows searches for the file in the Windows directory.

Return Value

The return value specifies the number of characters copied to the buffer, not including the terminating null character. If the buffer is not large enough to contain all the key name and value pairs associated with the named section, the return value is equal to nSize minus two.

Remarks

The data in the buffer pointed to by the lpReturnedString parameter consists of one or more null-terminated strings, followed by a final null character. Each string has the following format:

key=string

The GetPrivateProfileSection function is not case-sensitive; the string pointed to by the lpAppName parameter can be a combination of uppercase and lowercase letters.

This operation is atomic; no updates to the specified initialization file are allowed while the key name and value pairs for the section are being copied to the buffer pointed to by the lpReturnedString parameter.

Windows NT: Calls to private profile functions may be mapped to the registry instead of to the specified initialization files. This mapping occurs when the initialization file and section are specified in the registry under the following keys:

HKEY_LOCAL_MACHINE\Software\Microsoft\
        Windows NT\CurrentVersion\IniFileMapping

This mapping is likely if an application modifies system-component initialization files, such as CONTROL.INI, SYSTEM.INI, and WINFILE.INI. In these cases, the GetPrivateProfileSection function retrieves information from the registry, not from the initialization file; the change in the storage location has no effect on the function's behavior.

See Also

GetProfileSection, WritePrivateProfileSection


GetPrivateProfileSectionNames [New - Windows NT]
 GetPrivateProfileSectionNames  QuickInfo

[New - Windows NT]

The GetPrivateProfileSectionNames function retrieves the names of all sections in an initialization file. This function is provided for compatibility with 16-bit Windows-based applications. Win32-based applications should store initialization information in the registry.

DWORD GetPrivateProfileSectionNames(

LPTSTR  lpszReturnBuffer,	// address of return buffer
DWORD  nSize,	// size of return buffer
LPCTSTR  lpFileName	// address of initialization filename
);
Parameters

lpszReturnBuffer

Points to a buffer that receives the section names associated with the named file. The buffer is filled with one or more null-terminated strings; the last string is followed by a second null character.

nSize

Specifies the size, in characters, of the buffer pointed to by the lpszReturnBuffer parameter.

lpFileName

Points to a null-terminated string that names the initialization file. If this parameter is NULL, the function searches the WIN.INI file. If this parameter does not contain a full path to the file, Windows searches for the file in the Windows directory.

Return Value

The return value specifies the number of characters copied to the specified buffer, not including the terminating null character. If the buffer is not large enough to contain all the section names associated with the specified initialization file, the return value is equal to the length specified by nSize minus two.

Remarks

This operation is atomic; no updates to the initialization file are allowed while the section names are being copied to the buffer.

Calls to profile functions might be mapped to the registry instead of to the initialization files. When the operation has been mapped, the GetPrivateProfileSectionNames function retrieves information from the registry, not from the initialization file; the change in the storage location has no effect on the function's behavior.

See Also

GetPrivateProfileSection, WritePrivateProfileSection


GetPrivateProfileString
 GetPrivateProfileString  QuickInfo

The GetPrivateProfileString function retrieves a string from the specified section in an initialization file. This function is provided for compatibility with 16-bit Windows-based applications. Win32-based applications should store initialization information in the registry.

DWORD GetPrivateProfileString(

LPCTSTR  lpAppName,	// points to section name
LPCTSTR  lpKeyName,	// points to key name
LPCTSTR  lpDefault,	// points to default string
LPTSTR  lpReturnedString,	// points to destination buffer
DWORD  nSize,	// size of destination buffer
LPCTSTR  lpFileName	// points to initialization filename
);
Parameters

lpAppName

Points to a null-terminated string that specifies the section containing the key name. If this parameter is NULL, the GetPrivateProfileString function copies all section names in the file to the supplied buffer.

lpKeyName

Points to the null-terminated string containing the key name whose associated string is to be retrieved. If this parameter is NULL, all key names in the section specified by the lpAppName parameter are copied to the buffer specified by the lpReturnedString parameter.

lpDefault

Points to a null-terminated string that specifies the default value for the given key if the key cannot be found in the initialization file. This parameter cannot be NULL.

lpReturnedString

Points to the buffer that receives the retrieved string.

nSize

Specifies the size, in characters, of the buffer pointed to by the lpReturnedString parameter.

lpFileName

Points to a null-terminated string that names the initialization file. If this parameter does not contain a full path to the file, Windows searches for the file in the Windows directory.

Return Value

If the function succeeds, the return value is the number of characters copied to the buffer, not including the terminating null character.

If neither lpAppName nor lpKeyName is NULL and the supplied destination buffer is too small to hold the requested string, the string is truncated and followed by a null character, and the return value is equal to nSize minus one.

If either lpAppName or lpKeyName is NULL and the supplied destination buffer is too small to hold all the strings, the last string is truncated and followed by two null characters. In this case, the return value is equal to nSize minus two.

Remarks

The GetPrivateProfileString function searches the specified initialization file for a key that matches the name specified by the lpKeyName parameter under the section heading specified by the lpAppName parameter. If it finds the key, the function copies the corresponding string to the buffer. If the key does not exist, the function copies the default character string specified by the lpDefault parameter. A section in the initialization file must have the following form:

[section]
key=string
      .
      .
      .

If lpAppName is NULL, GetPrivateProfileString copies all section names in the specified file to the supplied buffer. If lpKeyName is NULL, the function copies all key names in the specified section to the supplied buffer. An application can use this method to enumerate all of the sections and keys in a file. In either case, each string is followed by a null character and the final string is followed by a second null character. If the supplied destination buffer is too small to hold all the strings, the last string is truncated and followed by two null characters.

If the string associated with lpKeyName is enclosed in single or double quotation marks, the marks are discarded when the GetPrivateProfileString function retrieves the string.

The GetPrivateProfileString function is not case-sensitive; the strings can be a combination of uppercase and lowercase letters.

To retrieve a string from the WIN.INI file, use the GetProfileString function.

Windows NT: Calls to private profile functions may be mapped to the registry instead of to the specified initialization files. This mapping occurs when the initialization file and section are specified in the registry under the following keys:

HKEY_LOCAL_MACHINE\Software\Microsoft\
        Windows NT\CurrentVersion\IniFileMapping

This mapping is likely if an application modifies system-component initialization files, such as CONTROL.INI, SYSTEM.INI, and WINFILE.INI. In these cases, the GetPrivateProfileString function retrieves information from the registry, not from the initialization file; the change in the storage location has no effect on the function's behavior.

See Also

GetProfileString, WritePrivateProfileString


GetPrivateProfileStruct [New - Windows NT]
 GetPrivateProfileStruct  QuickInfo

[New - Windows NT]

The GetPrivateProfileStruct function retrieves the data associated with the specified key in the given section of an initialization file. As it retrieves the data, the function calculates a checksum and compares it with the checksum calculated by the WritePrivateProfileStruct function when the data was added to the file. This function is provided for compatibility with 16-bit Windows-based applications. Win32-based applications should store initialization information in the registry.

BOOL GetPrivateProfileStruct(

LPCTSTR  lpszSection,	// address of section name
LPCTSTR  lpszKey,	// address of key name
LPVOID  lpStruct,	// address of return buffer
UINT  uSizeStruct,	// size of return buffer
LPCTSTR  szFile	// address of initialization filename
);
Parameters

lpszSection

Points to a null-terminated string containing the section name in the initialization file.

lpszKey

Points to the null-terminated string containing the key name whose data is to be retrieved.

lpStruct

Points to the buffer that receives the data associated with the file, section, and key names.

uSizeStruct

Specifies the size, in bytes, of the buffer pointed to by the lpStruct parameter.

szFile

Points to a null-terminated string that names the initialization file. If this parameter does not contain a full path to the file, Windows searches for the file in the Windows directory.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

A section in the initialization file must have the following form:

[section]
key=data
      .
      .
      .

Calls to private profile functions might be mapped to the registry instead of to the specified initialization files. This mapping is likely if an application modifies system-component initialization files, such as CONTROL.INI, SYSTEM.INI, and WINFILE.INI. In these cases, the GetPrivateProfileStruct function retrieves information from the registry, not from the initialization file; the change in the storage location has no effect on the function's behavior.

See Also

WritePrivateProfileStruct


GetProcAddress
 GetProcAddress  QuickInfo  Overview  Group

The GetProcAddress function returns the address of the specified exported dynamic-link library (DLL) function.

FARPROC GetProcAddress(

HMODULE  hModule,	// handle to DLL module
LPCSTR  lpProcName	// name of function
);
Parameters

hModule

Identifies the DLL module that contains the function. The LoadLibrary or GetModuleHandle function returns this handle.

lpProcName

Points to a null-terminated string containing the function name, or specifies the function's ordinal value. If this parameter is an ordinal value, it must be in the low-order word; the high-order word must be zero.

Return Value

If the function succeeds, the return value is the address of the DLL's exported function.

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

Remarks

The GetProcAddress function is used to retrieve addresses of exported functions in DLLs.

The spelling and case of the function name pointed to by lpProcName must be identical to that in the EXPORTS statement of the source DLL's module-definition (.DEF) file.

The lpProcName parameter can identify the DLL function by specifying an ordinal value associated with the function in the EXPORTS statement. GetProcAddress verifies that the specified ordinal is in the range 1 through the highest ordinal value exported in the .DEF file. The function then uses the ordinal as an index to read the function's address from a function table. If the .DEF file does not number the functions consecutively from 1 to N (where N is the number of exported functions), an error can occur where GetProcAddress returns an invalid, non-NULL address, even though there is no function with the specified ordinal.

In cases where the function may not exist, the function should be specified by name rather than by ordinal value.

See Also

FreeLibrary, GetModuleHandle, LoadLibrary


GetProcessAffinityMask
 GetProcessAffinityMask  QuickInfo  Overview  Group

The GetProcessAffinityMask function obtains a process affinity mask for the specified process and the system affinity mask for the system.

A process affinity mask is a bit vector in which each bit represents the processors that a process is allowed to run on. A system affinity mask is a bit vector in which each bit represents the processors that are configured into a system.

A process affinity mask is a proper subset of a system affinity mask. A process is only allowed to run on the processors configured into a system.

BOOL GetProcessAffinityMask(

HANDLE  hProcess,	// handle to the process of interest
LPDWORD  lpProcessAffinityMask,	// pointer to structure to receive process affinity mask
LPDWORD  lpSystemAffinityMask	// pointer to structure to receive system affinity mask
);
Parameters

hProcess

An open handle to the process whose affinity mask is desired. This handle must have PROCESS_QUERY_INFORMATION access.

lpProcessAffinityMask

Pointer to a DWORD that the function sets to the process affinity mask for the specified process.

lpSystemAffinityMask

Pointer to a DWORD that the function sets to the system affinity mask for the system.

Return Value

If the function succeeds, the return value is TRUE.

Windows 95: The successful function sets the DWORD variables pointed to by lpProcessAffinityMask and lpSystemAffinityMask to the value one.

Windows NT: The successful function sets the DWORD variables pointed to by lpProcessAffinityMask and lpSystemAffinityMask to the appropriate affinity masks.

If the function fails, the return value is FALSE, and the values of the DWORD variables pointed to by lpProcessAffinityMask and lpSystemAffinityMask are undefined.

See Also

SetThreadAffinityMask


GetProcessHeap
 GetProcessHeap  QuickInfo  Overview  Group

The GetProcessHeap function obtains a handle to the heap of the calling process. This handle can then be used in calls to the HeapAlloc, HeapReAlloc, HeapFree, and HeapSize functions.

HANDLE GetProcessHeap(VOID)

Parameters

This function has no parameters.

Return Value

If the function succeeds, the return value is a handle to the calling process's heap.

If the function fails, the return value is NULL.

Remarks

GetProcessHeap allows Win32-based applications to allocate memory from the process heap without having to first create a heap with the HeapCreate function, as shown in this example:

HeapAlloc(GetProcessHeap(), 0, dwBytes);

Note that the handle obtained by calling the function should not be used in calls to the HeapDestroy function.

Note, also, that the HEAP_NO_SERIALIZE flag should not be specified when using the HeapAlloc, HeapFree, HeapReAlloc, and HeapSize functions to access the process heap. The system may create additional threads within the application's process, such as a Ctrl+C handler, that simultaneously access the process heap. For more information about HEAP_NO_SERIALIZE, see the HeapCreate function.

See Also

GetProcessHeaps, HeapAlloc, HeapCreate, HeapDestroy, HeapFree, HeapReAlloc, HeapSize


GetProcessHeaps
 GetProcessHeaps  QuickInfo  Overview  Group

The GetProcessHeaps function obtains handles to all of the heaps that are valid for the calling process.

DWORD GetProcessHeaps(

DWORD  NumberOfHeaps,	// maximum number of heap handles buffer can receive
PHANDLE  ProcessHeaps	// points to buffer to receive array of heap handles
);
Parameters

NumberOfHeaps

Specifies the maximum number of heap handles that can be stored into the buffer pointed to by ProcessHeaps.

ProcessHeaps

Points to a buffer to receive an array of heap handles.

Return Value

The return value is the number of heap handles that are valid for the calling process.

If the return value is less than or equal to NumberOfHeaps, it is also the number of heap handles stored into the buffer pointed to by ProcessHeaps.

If the return value is greater than NumberOfHeaps, the buffer pointed to by ProcessHeaps is too small to hold all the valid heap handles of the calling process.The function will have stored no handles into that buffer. In this situation, use the return value to allocate a buffer that is large enough to receive the handles, and call the function again.

If the return value is zero, the function has failed, because every Win32 process has at least one valid heap, the process heap. To get extended error information, call GetLastError.

Remarks

Use the GetProcessHeap function to obtain a handle to the process heap of the calling process. The GetProcessHeaps function obtains a handle to that heap, plus handles to any additional private heaps created by calling the HeapCreate function.

See Also

GetProcessHeap , HeapCreate


GetProcessShutdownParameters
 GetProcessShutdownParameters  QuickInfo  Overview  Group

The GetProcessShutdownParameters function retrieves shutdown parameters for the currently calling process.

BOOL GetProcessShutdownParameters(

LPDWORD  lpdwLevel,	// shutdown priority
LPDWORD  lpdwFlags	// shutdown flag
);
Parameters

lpdwLevel

Points to a variable that receives the shutdown priority level. Higher levels shut down first. System level shutdown orders are reserved for system components. Higher numbers shut down first. Following are the level conventions:

Value	Meaning
000−0FF	System reserved last shutdown range.
100−1FF	Application reserved last shutdown range.
200−2FF	Application reserved "in between" shutdown range.
300−3FF	Application reserved first shutdown range.
400−4FF	System reserved first shutdown range.
All processes start at shutdown level 0x280.

lpdwFlags

Points to a variable that receives the shutdown flags. It can be the following value:

Value	Meaning
SHUTDOWN_NORETRY	If this process takes longer than the specified timeout to shut down, do not display a retry dialog box for the user. Instead, just cause the process to directly exit.
Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

See Also

SetProcessShutdownParameters


GetProcessTimes
 GetProcessTimes  QuickInfo  Overview  Group

The GetProcessTimes function obtains timing information about a specified process.

BOOL GetProcessTimes(

HANDLE  hProcess,	// specifies the process of interest
LPFILETIME  lpCreationTime,	// when the process was created
LPFILETIME  lpExitTime,	// when the process exited
LPFILETIME  lpKernelTime,	// time the process has spent in kernel mode
LPFILETIME  lpUserTime	// time the process has spent in user mode
);
Parameters

hProcess

An open handle that specifies the process whose timing information is sought. This handle must be created with PROCESS_QUERY_INFORMATION access.

lpCreationTime

Points to a FILETIME structure that receives the creation time of the process.

lpExitTime

Points to a FILETIME structure that receives the exit time of the process. If the process has not exited, the content of this structure is undefined.

lpKernelTime

Points to a FILETIME structure that receives the amount of time that the process has executed in kernel mode. The time that each of the threads of the process has executed in kernel mode is determined, and then all of those times are summed together to obtain this value.

lpUserTime

Points to a FILETIME structure that receives the amount of time that the process has executed in user mode. The time that each of the threads of the process has executed in user mode is determined, and then all of those times are summed together to obtain this value.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

All times are expressed using FILETIME data structures. Such a structure contains two 32-bit values that combine to form a 64-bit count of 100-nanosecond time units.

Process creation and exit times are points in time expressed as the amount of time that has elapsed since midnight on January 1, 1601 at Greenwich, England. The Win32 API provides several functions that an application can use to convert such values to more generally useful forms.

Process kernel mode and user mode times are amounts of time. For example, if a process has spent one second in kernel mode, this function will fill the FILETIME structure specified by lpKernelTime with a 64-bit value of ten million. That is the number of 100-nanosecond units in one second.

See Also

FILETIME, FileTimeToDosDateTime, FileTimeToLocalFileTime, FileTimeToSystemTime


GetProcessVersion [New - Windows NT]
 GetProcessVersion  QuickInfo  Overview  Group

[New - Windows NT]

The GetProcessVersion function obtains the major and minor version numbers of the Windows version on which a specified process expects to run.

DWORD GetProcessVersion(

DWORD  ProcessId	// identifier specifying the process of interest
);
Parameters

ProcessId

Process identifier that specifies the process of interest. A ProcessId value of zero specifies the calling process.

Return Value

If the function succeeds, the return value is the version of Windows on which the process expects to run. The high word of the return value contains the major version number. The low word of the return value contains the minor version number.

If the function fails, the return value is zero. To get extended error information, call GetLastError. The function fails if ProcessId is an invalid value.

Remarks

The GetProcessVersion function performs less quickly when ProcessId is nonzero, specifying a process other than the calling process.

The version number returned by this function is the version number stamped in the image header of the .EXE file the process is running. Linker programs set this value.


GetProcessWindowStation
 GetProcessWindowStation  QuickInfo  Overview  Group

The GetProcessWindowStation function returns a handle of the window station associated with the calling process.

HWINSTA GetProcessWindowStation(VOID)

Parameters

This function has no parameters.

Return Value

If the function succeeds, the return value is a handle of 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. 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.

See Also

GetThreadDesktop, GetUserObjectInformation, GetUserObjectSecurity, SetProcessWindowStation, SetUserObjectInformation, SetUserObjectSecurity


GetProcessWorkingSetSize
 GetProcessWorkingSetSize  QuickInfo  Overview  Group

The GetProcessWorkingSetSize function obtains the minimum and maximum working set sizes of a specified process.

The "working set" of a process is the set of memory pages currently visible to the process in physical RAM memory. These pages are resident and available for an application to use without triggering a page fault. The size of a process' working set is specified in bytes. The minimum and maximum working set sizes affect the virtual memory paging behavior of a process.

BOOL GetProcessWorkingSetSize(

HANDLE  hProcess,	// open handle to the process of interest
LPDWORD  lpMinimumWorkingSetSize,	// points to variable to receive minimum working set size
LPDWORD  lpMaximumWorkingSetSize	// points to variable to receive maximum working set size
);
Parameters

hProcess

An open handle to the process whose working set sizes will be obtained. The handle must have PROCESS_QUERY_INFORMATION access rights.

lpMinimumWorkingSetSize

Points to a variable that receives the minimum working set size of the specified process. The virtual memory manager attempts to keep at least this much memory resident in the process whenever the process is active.

lpMaximumWorkingSetSize

Points to a variable that receives the maximum working set size of the specified process. The virtual memory manager attempts to keep no more than this much memory resident in the process whenever the process is active when memory is in short supply.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

SetProcessWorkingSetSize


GetProfileInt
 GetProfileInt  QuickInfo

The GetProfileInt function retrieves an integer from the specified key name in the given section of the WIN.INI file. This function is provided for compatibility with 16-bit Windows-based applications. Win32-based applications should store initialization information in the registry.

UINT GetProfileInt(

LPCTSTR  lpAppName,	// address of section name
LPCTSTR  lpKeyName,	// address of key name
INT  nDefault	// default value if key name is not found
);
Parameters

lpAppName

Points to a null-terminated string that specifies the section containing the key name.

lpKeyName

Points to the null-terminated string containing the key name whose value is to be retrieved. This value is in the form of a string; the GetProfileInt function converts the string into an integer and returns the integer.

nDefault

Specifies the default value to return if the key name cannot be found in the initialization file..

Return Value

If the function succeeds, the return value is the integer equivalent of the string following the key name in WIN.INI. If the function cannot find the key, the return value is the default value. If the value of the key is less than zero, the return value is zero.

Remarks

If the key name consists of digits followed by characters that are not numeric, the function returns only the value of the digits. For example, the function returns 102 for the following line: KeyName=102abc.

Windows NT: Calls to profile functions may be mapped to the registry instead of to the initialization files. This mapping occurs when the initialization file and section are specified in the registry under the following keys:

HKEY_LOCAL_MACHINE\Software\Microsoft\
        Windows NT\CurrentVersion\IniFileMapping

When the operation has been mapped, the GetProfileInt function retrieves information from the registry, not from the initialization file; the change in the storage location has no effect on the function's behavior.

See Also

GetPrivateProfileInt, WriteProfileString


GetProfileSection
 GetProfileSection  QuickInfo

The GetProfileSection function retrieves all of the keys and values for the specified section of the WIN.INI file. This function is provided for compatibility with 16-bit Windows-based applications. Win32-based applications should store initialization information in the registry.

Windows 95

The specified profile section must not exceed 32K.

Windows NT

The specified profile section has no size limit.

DWORD GetProfileSection(

LPCTSTR  lpAppName,	// address of section name
LPTSTR  lpReturnedString,	// address of return buffer
DWORD  nSize	// size of return buffer
);
Parameters

lpAppName

Points to a null-terminated string containing the section name in the WIN.INI file.

lpReturnedString

Points to a buffer that receives the keys and values associated with the named section. The buffer is filled with one or more null-terminated strings; the last string is followed by a second null character.

nSize

Specifies the size, in characters, of the buffer pointed to by the lpReturnedString parameter.

Windows 95

The maximum buffer size is 32,767 characters.

Windows NT

There is no maximum buffer size.

Return Value

The return value specifies the number of characters copied to the specified buffer, not including the terminating null character. If the buffer is not large enough to contain all the keys and values associated with the named section, the return value is equal to the length specified by nSize minus two.

Remarks

The format of the returned keys and values is one or more null-terminated strings, followed by a final null character. Each string has the following form:

key=string

The GetProfileSection function is not case-sensitive; the strings can be a combination of uppercase and lowercase letters.

This operation is atomic; no updates to the WIN.INI file are allowed while the keys and values for the section are being copied to the buffer.

Windows NT: Calls to profile functions may be mapped to the registry instead of to the initialization files. This mapping occurs when the initialization file and section are specified in the registry under the following keys:

HKEY_LOCAL_MACHINE\Software\Microsoft\
        Windows NT\CurrentVersion\IniFileMapping

When the operation has been mapped, the GetProfileSection function retrieves information from the registry, not from the initialization file; the change in the storage location has no effect on the function's behavior.

See Also

GetPrivateProfileSection, WriteProfileSection


GetProfileString
 GetProfileString  QuickInfo

The GetProfileString function retrieves the string associated with the specified key in the given section of the WIN.INI file. This function is provided for compatibility with 16-bit Windows-based applications. Win32-based applications should store initialization information in the registry.

DWORD GetProfileString(

LPCTSTR  lpAppName,	// address of section name
LPCTSTR  lpKeyName,	// address of key name
LPCTSTR  lpDefault,	// address of default string
LPTSTR  lpReturnedString,	// address of destination buffer
DWORD  nSize	// size of destination buffer
);
Parameters

lpAppName

Points to a null-terminated string that specifies the section containing the key. If this parameter is NULL, the function copies all section names in the file to the supplied buffer.

lpKeyName

Points to a null-terminated string containing the key name whose associated string is to be retrieved. If this parameter is NULL, the function copies all keys in the given section to the supplied buffer. Each string is followed by a null character, and the final string is followed by a second null character.

lpDefault

Points to the default value for the given key if the key cannot be found in the initialization file. This parameter cannot be NULL.

lpReturnedString

Points to a buffer that receives the character string.

nSize

Specifies the size, in characters, of the buffer pointed to by the lpReturnedString parameter.

Return Value

If the function succeeds, the return value is the number of characters copied to the buffer, not including the null-terminating character.

If neither lpAppName nor lpKeyName is NULL and the supplied destination buffer is too small to hold the requested string, the string is truncated and followed by a null character, and the return value is equal to nSize minus one.

If either lpAppName or lpKeyName is NULL and the supplied destination buffer is too small to hold all the strings, the last string is truncated and followed by two null characters. In this case, the return value is equal to nSize minus two.

Remarks

If the string associated with the lpKeyName parameter is enclosed in single or double quotation marks, the marks are discarded when the GetProfileString function returns the string.

The GetProfileString function is not case-sensitive; the strings can contain a combination of uppercase and lowercase letters.

A section in the WIN.INI file must have the following form:

[section]
key=string
      .
      .
      .

An application can use the GetPrivateProfileString function to retrieve a string from a specified initialization file.

The lpDefault parameter must point to a valid string, even if the string is empty (that is, even if its first character is a null character).

Windows NT: Calls to profile functions may be mapped to the registry instead of to the initialization files. This mapping occurs when the initialization file and section are specified in the registry under the following keys:

HKEY_LOCAL_MACHINE\Software\Microsoft\
        Windows NT\CurrentVersion\IniFileMapping

When the operation has been mapped, the GetProfileString function retrieves information from the registry, not from the initialization file; the change in the storage location has no effect on the function's behavior.

See Also

GetPrivateProfileString, WriteProfileString


GetProp
 GetProp  QuickInfo  Overview  Group

The GetProp function retrieves a data handle from the property list of the given window. The given character string identifies the handle to be retrieved. The string and handle must have been added to the property list by a previous call to the SetProp function.

HANDLE GetProp(

HWND  hWnd,	// handle of window
LPCTSTR  lpString	// atom or address of string
);
Parameters

hWnd

Identifies the window whose property list is to be searched.

lpString

Points 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 Value

If the property list contains the given string, the return value is the associated data handle. Otherwise, the return value is NULL.

See Also

EnumProps, GlobalAddAtom, RemoveProp, SetProp


getprotobyname
 getprotobynam  QuickInfoe

The Windows Sockets getprotobyname function gets protocol information corresponding to a protocol name.

struct protoent FAR * PASCAL FAR getprotobyname(

const char FAR * name
);
Parameters

name

A pointer to a protocol name.

Return Value

If the function succeeds, getprotobyname returns a pointer to the protoent structure described previously.

If the function fails, it returns a NULL pointer. To get extended error information, call WSAGetLastError.

Error Codes

WSANOTINITIALISED	A successful WSAStartup must occur before using this function.
WSAENETDOWN	The Windows Sockets implementation has detected that the network subsystem has failed.
WSANO_RECOVERY	Nonrecoverable errors: FORMERR, REFUSED, NOTIMP.
WSANO_DATA	Valid name, no data record of requested type.
WSAEINPROGRESS	A blocking Windows Sockets operation is in progress.
WSAEINTR	The (blocking) call was canceled using WSACancelBlockingCall.
Remarks

The getprotobyname function returns a pointer to the following structure, which contains the name(s) and protocol number that correspond to the given protocol name.

struct protoent {

    char FAR *        p_name;

    char FAR * FAR *  p_aliases;

    short             p_proto;

};

The members of this structure are:

Member	Usage
p_name	Official name of the protocol.
p_aliases	A NULL-terminated array of alternate names.
p_proto	The protocol number, in host byte order.
The pointer that is returned points to a structure allocated by the Windows Sockets library. The application must never attempt to modify this structure or to free any of its components. Furthermore, only one copy of this structure is allocated per thread, and so the application should copy any information it needs before issuing any other Windows Sockets function calls.

See Also

getprotobynumber, WSAAsyncGetProtoByName, WSACancelBlockingCall, WSAStartup


getprotobynumber
 getprotobynumber  QuickInfo

The getprotobynumber function gets protocol information corresponding to a protocol number.

struct protoent FAR * PASCAL FAR getprotobynumber(

int proto
);
Parameters

proto

A protocol number, in host byte order.

Return Value

If the function succeeds, getprotobynumber returns a pointer to the protoent structure described previously.

If the function fails, it returns NULL. To get extended error information, call WSAGetLastError.

Error Codes

WSANOTINITIALISED	A successful WSAStartup must occur before using this function.
WSAENETDOWN	The Windows Sockets implementation has detected that the network subsystem has failed.
WSANO_RECOVERY	Nonrecoverable errors: FORMERR, REFUSED, NOTIMP.
WSANO_DATA	Valid name, no data record of requested type.
WSAEINPROGRESS	A blocking Windows Sockets operation is in progress.
WSAEINTR	The (blocking) call was canceled using WSACancelBlockingCall.
Remarks

This function returns a pointer to a protoent structure as described in getprotobyname. The contents of the structure correspond to the given protocol number.

The pointer that is returned points to a structure allocated by the Windows Sockets implementation. The application must never attempt to modify this structure or to free any of its components. Furthermore, only one copy of this structure is allocated per thread, and so the application should copy any information it needs before issuing any other Windows Sockets function calls.

See Also

getprotobyname, WSAAsyncGetProtoByNumber, WSACancelBlockingCall, WSAStartup,


GetQueuedCompletionStatus
 GetQueuedCompletionStatus  QuickInfo  Overview  Group

The GetQueuedCompletionStatus function attempts to dequeue an I/O completion packet from a specified input/output completion port. If there is no completion packet queued, the function waits for a pending input/output operation associated with the completion port to complete. The function returns when it can dequeue a completion packet, or optionally when the function times out. If the function returns because of an I/O operation completion, it sets several variables that provide information about the operation.

BOOL GetQueuedCompletionStatus(

HANDLE CompletionPort,	// the I/O completion port of interest
LPDWORD lpNumberOfBytesTransferred,	// to receive number of bytes transferred during I/O
LPDWORD lpCompletionKey,	// to receive file's completion key
LPOVERLAPPED * lpOverlapped,	// to receive pointer to OVERLAPPED structure
DWORD dwMilliseconds	// optional timeout value
);
Parameters

CompletionPort

Handle to the input/output completion port of interest. Use the CreateIoCompletionPort function to create I/O completion ports.

lpNumberOfBytesTransferred

Points to a variable that the function sets to the number of bytes transferred during an I/O operation that has completed and is causing the function to return.

lpCompletionKey

Points to a variable that the function sets to the completion key value associated with the file handle whose I/O operation has completed and is causing the function to return. A completion key is a per-file key that is specified in a call to CreateIoCompletionPort.

lpOverlapped

Points to a variable that the function sets to the address of the OVERLAPPED structure that was specified when an input/output operation that has completed was started.

The following functions can be used to start input/output operations that complete using I/O completion ports. You must pass the function an OVERLAPPED structure and a file handle associated (by a call to CreateIoCompletionPort) with an I/O completion port to invoke the I/O completion port mechanism:

•	ConnectNamedPipe

•	DeviceIoControl

•	LockFileEx

•	ReadFile

•	TransactNamedPipe

•	WaitCommEvent

•	WriteFile

Even if both of the preceding conditions (passing the function a file handle associated with a completion port and a valid OVERLAPPED structure) are met, an application can prevent completion port notification. To do this, specify a valid event handle for the hEvent member of the OVERLAPPED structure, and set the low order bit of that event handle. A valid event handle whose low order bit is set keeps I/O completion from being queued to the completion port.

dwMilliseconds

Specifies the number of milliseconds that the caller is willing to wait for an input/output completion packet to appear at the I/O completion port. If a completion packet doesn't appear within the specified time, the function times out, returns FALSE, and sets *lpOverlapped to NULL.

Timing out is optional. If dwMilliseconds is -1, the function will never time out. If dwMilliseconds is zero and there is no I/O operation to dequeue, the function will timeout immediately.

Return Value

The GetQueuedCompletionStatus function's return value is TRUE if the function dequeues an I/O completion packet for a successful I/O operation from the completion port. The function stores valid values into the variables pointed to by lpNumberOfBytesTransferred, lpCompletionKey, and lpOverlapped.

The function's return value is FALSE, and *lpOverlapped is set to NULL, if the function does not dequeue an I/O completion packet from the completion port. The function does not store valid values into the variables pointed to by lpNumberOfBytesTransferred and lpCompletionKey. To get extended error information, call GetLastError.

The function's return value is FALSE, and *lpOverlapped is not NULL, if the function dequeues an I/O completion packet for a failed I/O operation from the completion port. The function stores valid values into the variables pointed to by lpNumberOfBytesTransferred, lpCompletionKey, and lpOverlapped. To get extended error information, call GetLastError.

Remarks

The Win32 I/O system can be instructed to send I/O completion notification packets to input/output completion ports, where they are queued up. The CreateIoCompletionPort function provides a mechanism for this.

When you perform an input/output operation with a file handle that has an associated input/output completion port, the I/O system sends a completion notification packet to the completion port when the I/O operation completes. The I/O completion port places the completion packet in a first-in-first-out queue. The GetQueuedCompletionStatus function retrieves these queued I/O completion packets.

A server application may have several threads calling GetQueuedCompletionStatus for the same completion port. As input operations complete, the operating system queues completion packets to the completion port. If threads are actively waiting in a call to this function, queued requests complete their call.

You can call the PostQueuedCompletionStatus function to post an I/O completion packet to an I/O completion port. The I/O completion packet will satisfy an outstanding call to the GetQueuedCompletionStatus function.

See Also

ConnectNamedPipe, CreateIoCompletionPort, DeviceIoControl, LockFileEx, OVERLAPPED, ReadFile, PostQueuedCompletionStatus, TransactNamedPipe, WaitCommEvent, WriteFile,


GetQueueStatus
 GetQueueStatus  QuickInfo  Overview  Group

The GetQueueStatus function returns flags that indicate the type of messages found in the calling thread's message queue.

DWORD GetQueueStatus(

UINT  flags	// queue-status flags
);
Parameters

flags

Specifies queue-status flags giving the types of messages to check for. This parameter can be a combination of the following values:

Value	Meaning
QS_ALLEVENTS	An input, WM_TIMER, WM_PAINT, WM_HOTKEY, or posted message is in the queue.
QS_ALLINPUT	Any message is in the queue.
QS_HOTKEY	A WM_HOTKEY message is in the queue.
QS_INPUT	An input message is in the queue.
QS_KEY	A WM_KEYUP, WM_KEYDOWN, WM_SYSKEYUP, or WM_SYSKEYDOWN message is in the queue.
QS_MOUSE	A WM_MOUSEMOVE message or mouse-button message (WM_LBUTTONUP, WM_RBUTTONDOWN, and so on).
QS_MOUSEBUTTON	A mouse-button message (WM_LBUTTONUP, WM_RBUTTONDOWN, and so on).
QS_MOUSEMOVE	A WM_MOUSEMOVE message is in the queue.
QS_PAINT	A WM_PAINT message is in the queue.
QS_POSTMESSAGE	A posted message (other than those just listed) is in the queue.
QS_SENDMESSAGE	A message sent by another thread or application is in the queue.
QS_TIMER	A WM_TIMER message is in the queue.
Return Value

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 PeekMessage or GetMessage 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.

See Also

GetInputState, GetMessage, PeekMessage


GetRasterizerCaps
 GetRasterizerCaps  QuickInfo  Overview  Group

The GetRasterizerCaps function returns flags indicating whether TrueType fonts are installed in the system.

BOOL GetRasterizerCaps(

LPRASTERIZER_STATUS  lprs,	// address of rasterizer information structure
UINT  cb	// number of bytes in structure
);
Parameters

lprs

Points to a RASTERIZER_STATUS structure to receive information about the rasterizer.

cb

Specifies the number of bytes to be copied into the structure pointed to by the lprs parameter.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The GetRasterizerCaps function enables applications and printer drivers to determine whether TrueType fonts are installed.

If the TT_AVAILABLE flag is set in the wFlags member of the RASTERIZER_STATUS structure, at least one TrueType font is installed. If the TT_ENABLED flag is set, TrueType is enabled for the system.

The actual number of bytes copied is either the member specified in the cb parameter or the length of the RASTERIZER_STATUS structure, whichever is less.

See Also

GetOutlineTextMetrics, RASTERIZER_STATUS


GetRegionData
 GetRegionData  QuickInfo  Overview  Group

The GetRegionData function fills the specified buffer with data describing a region. This data includes the dimensions of the rectangles that make up the region.

DWORD GetRegionData(

HRGN  hRgn,	// handle of region
DWORD  dwCount,	// size of buffer containing region data
LPRGNDATA  lpRgnData	// address of buffer containing region data
);
Parameters

hRgn

Identifies the region.

dwCount

Specifies the size, in bytes, of the lpRgnData buffer.

lpRgnData

Points to a RGNDATA structure that receives the information. If this parameter is NULL, the return value contains the number of bytes needed for the region data.

Return Value

If the function succeeds and dwCount specifies an adequate number of bytes, the return value is 1. If dwCount is too small or lpRgnData is NULL, the return value is the required number of bytes.

If the function fails, the return value is zero.

Remarks

The GetRegionData function is used in conjunction with the ExtCreateRegion function.

See Also

ExtCreateRegion, RGNDATA


GetRgnBox
 GetRgnBox  QuickInfo  Overview  Group

The GetRgnBox function retrieves the bounding rectangle of the specified region.

int GetRgnBox(

HRGN  hrgn,	// handle of a region
LPRECT  lprc	// address of structure that receives bounding rect.
);
Parameters

hrgn

Identifies the region.

lprc

Points to a RECT structure that receives the bounding rectangle.

Return Value

The return value specifies the region's complexity. It can be one of the following values:

Value	Meaning
NULLREGION	Region is empty.
SIMPLEREGION	Region is a single rectangle.
COMPLEXREGION	Region is more than a single rectangle.
If the hrgn parameter does not identify a valid region, the return value is zero.

See Also

RECT


GetROP2
 GetROP2  QuickInfo  Overview  Group

The GetROP2 function retrieves the foreground mix mode of the specified device context. The mix mode specifies how the pen or interior color and the color already on the screen are combined to yield a new color.

int GetROP2(

HDC  hdc	// handle of device context
);
Parameters

hdc

Identifies the device context.

Return Value

If the function succeeds, the return value specifies the foreground mix mode.

If the function fails, the return value is zero.

Remarks

Following are the foreground mix modes:

Mix mode	Description
R2_BLACK	Pixel is always 0.
R2_COPYPEN	Pixel is the pen color.
R2_MASKNOTPEN	Pixel is a combination of the colors common to both the screen and the inverse of the pen.
R2_MASKPEN	Pixel is a combination of the colors common to both the pen and the screen.
R2_MASKPENNOT	Pixel is a combination of the colors common to both the pen and the inverse of the screen.
R2_MERGENOTPEN	Pixel is a combination of the screen color and the inverse of the pen color.
R2_MERGEPEN	Pixel is a combination of the pen color and the screen color.
R2_MERGEPENNOT	Pixel is a combination of the pen color and the inverse of the screen color.
R2_NOP	Pixel remains unchanged.
R2_NOT	Pixel is the inverse of the screen color.
R2_NOTCOPYPEN	Pixel is the inverse of the pen color.
R2_NOTMASKPEN	Pixel is the inverse of the R2_MASKPEN color.
R2_NOTMERGEPEN	Pixel is the inverse of the R2_MERGEPEN color.
R2_NOTXORPEN	Pixel is the inverse of the R2_XORPEN color.
R2_WHITE	Pixel is always 1.
R2_XORPEN	Pixel is a combination of the colors in the pen and in the screen, but not in both.
See Also

SetROP2


GetSaveFileName
 GetSaveFileName  QuickInfo  Overview  Group

The GetSaveFileName function creates a system-defined dialog box that enables the user to select a file to save.

BOOL GetSaveFileName(

LPOPENFILENAME  lpofn	// address of structure with initialization data
);
Parameters

lpofn

Points 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 Value

If the user selects a file to save, the return value is TRUE.

The return value is FALSE if an error occurs, the user clicks the Cancel button, the user chooses the Close command on the System menu to close the dialog box, or the buffer identified by the lpstrFile member of the OPENFILENAME structure is too small to contain the string that specifies the selected file.

To get extended error information, call CommDlgExtendedError. CommDlgExtendedError may return one of the following error codes:

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

If the hook function (pointed to by the lpfnHook member of the OPENFILENAME structure) processes the WM_CTLCOLORDLG message, GetSaveFileName must return a handle for the brush that should be used to paint the control background.

Ending the dialog box from within the hook function by calling the EndDialog function prevents the COMDLG32.DLL dynamic-link library (DLL) from properly exiting its worker thread. For applications that dynamically load or unload COMDLG32.DLL, this type of exiting may result in an access violation during unloading as the worker thread's address space is invalidated.

See Also

CommDlgExtendedError, GetOpenFilename, OPENFILENAME, WM_CTLCOLORDLG


GetScrollInfo [New - Windows NT]
 GetScrollInfo  QuickInfo

[New - Windows NT]

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 of window with scroll bar
int  fnBar,	// scroll bar flag
LPSCROLLINFO  lpsi	// pointer to structure for scroll parameters
);
Parameters

hwnd

Identifies a scroll bar control or a window with a standard scroll bar, depending on the value of the fnBar parameter.

fnBar

Specifies the type of scroll bar for which to retrieve parameters. This parameter can be one of the following values:

Value	Meaning
SB_CTL	Retrieves the parameters for a scroll bar control. The hwnd parameter must be the handle of the scroll bar control.
SB_HORZ	Retrieves the parameters for the given window's standard horizontal scroll bar.
SB_VERT	Retrieves the parameters for the given window's standard vertical scroll bar.
lpsi

Points to a SCROLLINFO structure whose fMask member, upon entry to the function, specifies the scroll bar parameters to retrieve. Before returning, the function copies the specified parameters to the appropriate members of the structure.

The fMask member can be a combination of the following values:

Value	Meaning
SIF_PAGE	Copies the scroll page to the nPage member of the SCROLLINFO structure pointed to by lpsi.
SIF_POS	Copies the scroll position to the nPos member of the SCROLLINFO structure pointed to by lpsi.
SIF_RANGE	Copies the scroll range to the nMin and nMax members of the SCROLLINFO structure pointed to by lpsi.
Return Value

If the function retrieved any values, the return value is TRUE.

If the function does not retrieve any values, the return value is FALSE.

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.

The limitation on this technique applies to real-time scrolling of a window's contents. An application implements real-time scrolling by processing the WM_HSCROLL or WM_VSCROLL messages that carry the SB_THUMBTRACK notification value, thereby tracking the position of the scroll box (thumb) as the user moves it. Unfortunately, there is no function to retrieve the 32-bit position scroll-box position as the user moves the scroll box. Because GetScrollInfo provides only the static position, an application can obtain only 32-bit position data before or after a scroll operation.

See Also

SCROLLINFO, SetScrollInfo, WM_HSCROLL, WM_VSCROLL


GetScrollPos
 GetScrollPos  QuickInfo  Overview  Group

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.

int GetScrollPos(

HWND  hWnd,	// handle of window with scroll bar
int  nBar	// scroll bar flags
);
Parameters

hWnd

Identifies a scroll bar control or a window with a standard scroll bar, depending on the value of the nBar parameter.

nBar

Specifies the scroll bar to be examined. This parameter can be one of the following values:

Value	Meaning
SB_CTL	Retrieves the position of the scroll box in a scroll bar control. The hWnd parameter must be the handle of 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 Value

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.

The limitation on this technique applies to real-time scrolling of a window's content. An application implements such scrolling by processing the WM_HSCROLL or WM_VSCROLL messages that carry the SB_THUMBTRACK notification message, thereby tracking the position of the scroll box, also known as the thumb, while the user moves it. Unfortunately, there is no function to retrieve the thumb's 32-bit position while the user moves it. GetScrollPos provides static position data only; an application can therefore only obtain 32-bit position data before or after a scroll has taken place.

See Also

GetScrollRange, ScrollDC, ScrollWindow, SetScrollPos, SetScrollRange, WM_HSCROLL, WM_VSCROLL


GetScrollRange
 GetScrollRange  QuickInfo  Overview  Group

The GetScrollRange function retrieves the current minimum and maximum scroll box (thumb) positions for the specified scroll bar.

For Windows 95, the GetScrollRange function exists for compatibility with operating system versions earlier than 4.0. With version 4.0 or later, use the GetScrollInfo function.

BOOL GetScrollRange(

HWND  hWnd,	// handle of window with scroll bar
int  nBar,	// scroll bar flags
LPINT  lpMinPos,	// address of variable that receives minimum position
LPINT  lpMaxPos	// address of variable that receives maximum position
);
Parameters

hWnd

Identifies a scroll bar control or a window with a standard scroll bar, depending on the value of the nBar parameter.

nBar

Specifies the scroll bar from which the positions are retrieved. This parameter can be one of the following values:

Value	Meaning
SB_CTL	Retrieves the positions of a scroll bar control. The hWnd parameter must be the handle of 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

Points to the integer variable that receives the minimum position.

lpMaxPos

Points to the integer variable that receives the maximum position.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. 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 SetScrollPos, SetScrollRange, GetScrollPos, and GetScrollRange support 32-bit scroll bar position data, there is a way to circumvent the 16-bit barrier for the WM_HSCROLL and WM_VSCROLL messages. See the GetScrollPos function for a description of the technique and its limits.

See Also

GetScrollPos, SetScrollPos, SetScrollRange, WM_HSCROLL, WM_VSCROLL


GetSecurityDescriptorControl
 GetSecurityDescriptorControl  QuickInfo  Overview  Group

The GetSecurityDescriptorControl function retrieves a security descriptor's control and revision information.

BOOL GetSecurityDescriptorControl(

PSECURITY_DESCRIPTOR  pSecurityDescriptor,	// address of security descriptor
PSECURITY_DESCRIPTOR_CONTROL  pControl,	// address of  control structure
LPDWORD  lpdwRevision	// address of revision value
);
Parameters

pSecurityDescriptor

Points to a SECURITY_DESCRIPTOR structure whose control and revision information the function retrieves.

pControl

Points to a SECURITY_DESCRIPTOR_CONTROL structure receiving the security descriptor's control information.

lpdwRevision

Points to a variable receiving the security descriptor's revision value. This value is always set, even when GetSecurityDescriptorControl returns an error.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

GetSecurityDescriptorDacl, GetSecurityDescriptorGroup, GetSecurityDescriptorLength, GetSecurityDescriptorOwner, GetSecurityDescriptorSacl, IsValidSecurityDescriptor, SECURITY_DESCRIPTOR, SECURITY_DESCRIPTOR_CONTROL


GetSecurityDescriptorDacl
 GetSecurityDescriptorDacl  QuickInfo  Overview  Group

The GetSecurityDescriptorDacl function retrieves a pointer to the discretionary access-control list (ACL) in a specified security descriptor.

BOOL GetSecurityDescriptorDacl(

PSECURITY_DESCRIPTOR  pSecurityDescriptor,	// address of security descriptor
LPBOOL  lpbDaclPresent,	// address of flag for presence of disc. ACL
PACL  *pDacl,	// address of pointer to ACL
LPBOOL  lpbDaclDefaulted	// address of flag for default disc. ACL
);
Parameters

pSecurityDescriptor

Points to the SECURITY_DESCRIPTOR structure containing the discretionary ACL. The function retrieves a pointer to it.

lpbDaclPresent

Points to a flag the function sets to indicate the presence of a discretionary ACL in the specified security descriptor. If this parameter is TRUE, the security descriptor contains a discretionary ACL, and the remaining output parameters in this function receive valid values. If this parameter is FALSE, the security descriptor does not contain a discretionary ACL, and the remaining output parameters do not receive valid values.

pDacl

Points to a pointer to an ACL structure. If a discretionary ACL exists, the function sets the pointer pointed to by pDacl to the address of the security descriptor's discretionary ACL. If a discretionary ACL does not exist, no value is stored.

If the function stores a NULL value in the pointer pointed to by pDacl, the security descriptor has a NULL discretionary ACL. A NULL discretionary ACL implicitly allows all access to an object.

lpbDaclDefaulted

Points to a flag set to the value of the SE_DACL_DEFAULTED flag in the SECURITY_DESCRIPTOR_CONTROL structure if a discretionary ACL exists for the security descriptor. If this flag is TRUE, the discretionary ACL was retrieved by a default mechanism; if FALSE, the discretionary ACL was explicitly specified by a user.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

ACL, GetSecurityDescriptorControl, GetSecurityDescriptorGroup, GetSecurityDescriptorLength, GetSecurityDescriptorOwner, GetSecurityDescriptorSacl, InitializeSecurityDescriptor, IsValidSecurityDescriptor, SECURITY_DESCRIPTOR, SECURITY_DESCRIPTOR_CONTROL, SetSecurityDescriptorDacl


GetSecurityDescriptorGroup
 GetSecurityDescriptorGroup  QuickInfo  Overview  Group

The GetSecurityDescriptorGroup function retrieves the primary group information from a security descriptor.

BOOL GetSecurityDescriptorGroup(

PSECURITY_DESCRIPTOR  pSecurityDescriptor,	// address of security descriptor
PSID *  pGroup,	// address of pointer to group security identifier (SID)
LPBOOL  lpbGroupDefaulted	// address of flag for default
);
Parameters

pSecurityDescriptor

Points to a SECURITY_DESCRIPTOR structure whose primary group information the function retrieves.

pGroup

Points to a pointer to a SID structure identifying the primary group when the function returns. (A SID is a security identifier.) If the security descriptor does not contain a primary group, the function sets the pointer pointed to by pGroup to NULL and ignores the remaining output parameter, lpbGroupDefaulted. If the security descriptor contains a primary group, the function sets the pointer pointed to by pGroup to the address of the security descriptor's group SID structure and provides a valid value for the variable pointed to by lpbGroupDefaulted.

lpbGroupDefaulted

Points to a flag set to the value of the SE_GROUP_DEFAULTED flag in the SECURITY_DESCRIPTOR_CONTROL structure when the function returns. If the value stored in the variable pointed to by the pGroup parameter is NULL, no value is set.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

GetSecurityDescriptorControl, GetSecurityDescriptorDacl, GetSecurityDescriptorLength, GetSecurityDescriptorOwner, GetSecurityDescriptorSacl, IsValidSecurityDescriptor, SECURITY_DESCRIPTOR, SECURITY_DESCRIPTOR_CONTROL, SetSecurityDescriptorGroup, SID


GetSecurityDescriptorLength
 GetSecurityDescriptorLength  QuickInfo  Overview  Group

The GetSecurityDescriptorLength function returns the length, in bytes, of a structurally valid SECURITY_DESCRIPTOR structure. The length includes the length of all associated structures, such as SID and ACL structures.

DWORD GetSecurityDescriptorLength(

PSECURITY_DESCRIPTOR  pSecurityDescriptor	// address of security descriptor
);
Parameters

pSecurityDescriptor

Points to the SECURITY_DESCRIPTOR structure whose length the function returns. The SECURITY_DESCRIPTOR structure is assumed to be valid.

Return Value

If the function succeeds, the return value is the length, in bytes, of the SECURITY_DESCRIPTOR structure. If the SECURITY_DESCRIPTOR structure is invalid, the return value is undefined.

Remarks

The minimum length of a security descriptor is SECURITY_DESCRIPTOR_MIN_LENGTH. A security descriptor of this length has no associated SID or ACL structures.

See Also

GetSecurityDescriptorControl, GetSecurityDescriptorDacl, GetSecurityDescriptorGroup, GetSecurityDescriptorOwner, GetSecurityDescriptorSacl, IsValidSecurityDescriptor, SECURITY_DESCRIPTOR


GetSecurityDescriptorOwner
 GetSecurityDescriptorOwner  QuickInfo  Overview  Group

The GetSecurityDescriptorOwner function retrieves the owner information from a security descriptor.

BOOL GetSecurityDescriptorOwner(

PSECURITY_DESCRIPTOR  pSecurityDescriptor,	// address of security descriptor
PSID  * pOwner,	// address of pointer to owner security identifier (SID)
LPBOOL  lpbOwnerDefaulted	// address of flag for default
);
Parameters

pSecurityDescriptor

Points to a SECURITY_DESCRIPTOR structure whose owner information the function retrieves.

pOwner

Points to a pointer to a SID structure identifying the owner when the function returns. (A SID is a security identifier.) If the security descriptor does not contain an owner, the function sets the pointer pointed to by pOwner to NULL and ignores the remaining output parameter, lpbOwnerDefaulted. If the security descriptor contains an owner, the function sets the pointer pointed to by pOwner to the address of the security descriptor's owner SID structure and provides a valid value for the variable pointed to by lpbOwnerDefaulted.

lpbOwnerDefaulted

Points to a flag set to the value of the SE_OWNER_DEFAULTED flag in the SECURITY_DESCRIPTOR_CONTROL structure when the function returns. If the value stored in the variable pointed to by the pOwner parameter is NULL, no value is set.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

GetSecurityDescriptorControl, GetSecurityDescriptorDacl, GetSecurityDescriptorGroup, GetSecurityDescriptorLength, GetSecurityDescriptorSacl, IsValidSecurityDescriptor, SECURITY_DESCRIPTOR, SECURITY_DESCRIPTOR_CONTROL, SetSecurityDescriptorOwner, SID


GetSecurityDescriptorSacl
 GetSecurityDescriptorSacl  QuickInfo  Overview  Group

The GetSecurityDescriptorSacl function retrieves a pointer to the system access-control list (ACL) in a specified security descriptor.

BOOL GetSecurityDescriptorSacl(

PSECURITY_DESCRIPTOR  pSecurityDescriptor,	// address of security descriptor
LPBOOL  lpbSaclPresent,	// address of flag for presence of system ACL
PACL  *pSacl,	// address of pointer to ACL
LPBOOL  lpbSaclDefaulted	// address of flag for default system ACL
);
Parameters

pSecurityDescriptor

Points to the SECURITY_DESCRIPTOR structure containing the system ACL to which the function retrieves a pointer to.

lpbSaclPresent

Points to a flag the function sets to indicate the presence of a system ACL in the specified security descriptor. If this parameter is TRUE, the security descriptor contains a system ACL, and the remaining output parameters in this function receive valid values. If this parameter is FALSE, the security descriptor does not contain a system ACL, and the remaining output parameters do not receive valid values.

pSacl

Points to a pointer to an ACL structure. If a system ACL exists, the function sets the pointer pointed to by pSacl to the address of the security descriptor's system ACL. If a system ACL does not exist, no value is stored.

If the function stores a NULL value in the pointer pointed to by pSacl, the security descriptor has a NULL system ACL.

lpbSaclDefaulted

Points to a flag set to the value of the SE_SACL_DEFAULTED flag in the SECURITY_DESCRIPTOR_CONTROL structure if a system ACL exists for the security descriptor.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

ACL, GetSecurityDescriptorControl, GetSecurityDescriptorDacl, GetSecurityDescriptorGroup, GetSecurityDescriptorLength, GetSecurityDescriptorOwner, InitializeSecurityDescriptor, IsValidSecurityDescriptor, SECURITY_DESCRIPTOR, SECURITY_DESCRIPTOR_CONTROL, SetSecurityDescriptorSacl


getservbyname
 getservbynam  QuickInfoe

The Windows Sockets getservbyname function gets service information corresponding to a service name and protocol.

struct servent FAR * getservbyname (

const char FAR * name,
const char FAR * proto
);
Parameters

name

A pointer to a service name.

proto

An optional pointer to a protocol name. If this is NULL, getservbyname returns the first service entry for which the name matches the s_name or one of the s_aliases. Otherwise getservbyname matches both the name and the proto.

Return Value

If the function succeeds, getservbyname returns a pointer to the servent structure described in getservbyname.

If the function fails, it returns NULL. To get extended error information, call WSAGetLastError.

Error Codes

WSANOTINITIALISED	A successful WSAStartup must occur before using this function.
WSAENETDOWN	The Windows Sockets implementation has detected that the network subsystem has failed.
WSANO_RECOVERY	Nonrecoverable errors: FORMERR, REFUSED, NOTIMP.
WSANO_DATA	Valid name, no data record of requested type.
WSAEINPROGRESS	A blocking Windows Sockets operation is in progress.
WSAEINTR	The (blocking) call was canceled using WSACancelBlockingCall.
Remarks

The getservbyname function returns a pointer to the following structure, which contains the name(s) and service number that correspond to the given service name.

struct servent {

    char FAR *        s_name;

    char FAR * FAR *  s_aliases;

    short             s_port;

    char FAR *        s_proto;

};

The members of this structure are:

Members	Usage
s_name	Official name of the service.
s_aliases	A NULL-terminated array of alternate names.
s_port	The port number at which the service may be contacted. Port numbers are returned in network byte order.
s_proto	The name of the protocol to use when contacting the service.
The pointer that is returned points to a structure allocated by the Windows Sockets library. The application must never attempt to modify this structure or to free any of its components. Furthermore, only one copy of this structure is allocated per thread, and so the application should copy any information it needs before issuing any other Windows Sockets function calls.

See Also

getservbyport, WSAAsyncGetServByName, WSACancelBlockingCall, WSAStartup


getservbyport
 getservbyport  QuickInfo

The Windows Sockets getservbyport function gets service information corresponding to a port and protocol.

struct servent FAR * getservbyport (

int port,
const char FAR * proto
);
Parameters

port

The port for a service, in network byte order.

proto

An optional pointer to a protocol name. If this is NULL, getservbyport returns the first service entry that matches the specified port. Otherwise, getservbyport matches both the port and the proto.

Return Value

If the function succeeds, getservbyport returns a pointer to the servent structure described previously.

If the function fails, it returns a NULL pointer. To get extended error information, call WSAGetLastError.

Error Codes

WSANOTINITIALISED	A successful WSAStartup must occur before using this function.
WSAENETDOWN	The Windows Sockets implementation has detected that the network subsystem has failed.
WSANO_RECOVERY	Nonrecoverable errors: FORMERR, REFUSED, NOTIMP.
WSANO_DATA	Valid name, no data record of requested type.
WSAEINPROGRESS	A blocking Windows Sockets operation is in progress.
WSAEINTR	The (blocking) call was canceled using WSACancelBlockingCall.
Remarks

The getservbyport function returns a pointer to a servent structure as described for getservbyname.

The pointer that is returned points to a structure allocated by the Windows Sockets implementation. The application must never attempt to modify this structure or to free any of its components. Furthermore, only one copy of this structure is allocated per thread, and so the application should copy any information it needs before issuing any other Windows Sockets function calls.

See Also

getservbyname, WSAAsyncGetServByPort, WSACancelBlockingCall, WSAStartup


GetService
 GetService  QuickInfo  Overview  Group

The GetService function obtains information about a network service in the context of a set of default name spaces or a specified name space. The network service is specified by its type and name. The information about the service is obtained as a set of NS_SERVICE_INFO data structures.

INT GetService(

DWORD  dwNameSpace,	// specifies name space or spaces to search
PGUID  lpGuid,	// points to GUID service type
LPTSTR  lpServiceName,	// points to service name
DWORD  dwProperties,	// specifies service information to be obtained
LPVOID  lpBuffer,	// points to buffer to receive service information
LPDWORD  lpdwBufferSize,	// points to size of buffer, size of service information
LPSERVICE_ASYNC_INFO  lpServiceAsyncInfo	// reserved for future use, must be NULL
);
Parameters

dwNameSpace

Specifies the name space, or a set of default name spaces, that the operating system will query for information about the specified network service.

Use one of the following constants to specify a name space:

Value	Name Space
NS_DEFAULT	A set of default name spaces. The operating system will query each name space within this set. The set of default name spaces typically includes all the name spaces installed on the system. System administrators, however, can exclude particular name spaces from the set. NS_DEFAULT is the value that most applications should use for dwNameSpace.
NS_DNS	The Domain Name System used in the Internet for host name resolution.
NS_NETBT	The NetBIOS over TCP/IP layer. All Windows NT systems register their computer names with NetBIOS. This name space is used to resolve a computer name into an IP address using this registration. Note that NS_NETBT may access a WINS server to perform the resolution.
NS_SAP	The Netware Service Advertising Protocol. This may access the Netware bindery if appropriate. NS_SAP is a dynamic name space that allows registration of services.
NS_TCPIP_HOSTS	Looks up host names and IP addresses in the <systemroot>\system32\drivers\etc\hosts file.
NS_TCPIP_LOCAL	Local TCP/IP name resolution mechanisms, including comparisons against the local host name and looks up host names and IP addresses in cache of host to IP address mappings.
Most calls to GetService should use the special value NS_DEFAULT. This lets a client get by with no knowledge of which name spaces are available on an internetwork. The system administrator determines name space access. Name spaces can come and go without the client having to be aware of the changes.

lpGuid

Points to a globally unique identifier (GUID) that specifies the type of the network service. The header file SVCGRUID.H includes GUIDs from many well known services within the DNS and SAP name spaces.

lpServiceName

Points to a zero-terminated string that uniquely represents the service name. For example, "MY SNA SERVER".

dwProperties

A set of bit-flags that specify the service information that the function obtains. Each of these bit flag constants, other than PROP_ALL, corresponds to a particular member of the SERVICE_INFO data structure. If the flag is set, the function puts information into the corresponding member of the data structures stored in *lpBuffer. The following bit flags are defined:

Value	Name Space
PROP_COMMENT	If this flag is set, the function stores data in the lpComment member of the data structures stored in *lpBuffer.
PROP_LOCALE	If this flag is set, the function stores data in the lpLocale member of the data structures stored in *lpBuffer.
PROP_DISPLAY_HINT	If this flag is set, the function stores data in the dwDisplayHint member of the data structures stored in *lpBuffer.
PROP_VERSION	If this flag is set, the function stores data in the dwVersion member of the data structures stored in *lpBuffer.
PROP_START_TIME	If this flag is set, the function stores data in the dwTime member of the data structures stored in *lpBuffer.
PROP_MACHINE	If this flag is set, the function stores data in the lpMachineName member of the data structures stored in *lpBuffer.
PROP_ADDRESSES	If this flag is set, the function stores data in the lpServiceAddress member of the data structures stored in *lpBuffer.
PROP_SD	If this flag is set, the function stores data in the ServiceSpecificInfo member of the data structures stored in *lpBuffer.
PROP_ALL	If this flag is set, the function stores data in all of the members of the data structures stored in *lpBuffer.
lpBuffer

Points to a buffer to receive an array of NS_SERVICE_INFO structures and associated service information. Each NS_SERVICE_INFO structure contains service information in the context of a particular name space. Note that if dwNameSpace is NS_DEFAULT, the function stores more than one structure into the buffer; otherwise, just one structure is stored.

Each NS_SERVICE_INFO structure contains a SERVICE_INFO structure. The members of these SERVICE_INFO structures will contain valid data based on the bit-flags that are set in the dwProperties parameter. If a member's corresponding bit-flag is not set in dwProperties, the member's value is undefined.

The function stores the NS_SERVICE_INFO structures in a consecutive array, starting at the beginning of the buffer. The pointers in the contained SERVICE_INFO structures point to information that is stored in the buffer between the end of the NS_SERVICE_INFO structures and the end of the buffer.

lpdwBufferSize

Points to a variable that, on input, contains the size, in bytes, of the buffer pointed to by lpBuffer. On output, this variable contains the number of bytes required to store the requested information. If this output value is greater than the input value, the function has failed due to insufficient buffer size.

lpServiceAsyncInfo

This parameter is reserved for future use. It must be set to NULL.

Return Value

If the function succeeds, the return value is the number of NS_SERVICE_INFO structures stored in *lpBuffer. Zero indicates that no structures were stored.

If the function fails, the return value is SOCKET_ERROR ( − 1). To get extended error information, call GetLastError. GetLastError may return one of the following extended error values:

Value	Meaning
ERROR_INSUFFICIENT_BUFFER	The buffer pointed to by lpBuffer is too small to receive all of the requested information. Call the function with a buffer at least as large as the value returned in *lpdwBufferSize.
ERROR_SERVICE_NOT_FOUND	The specified service was not found, or the specified name space is not in use. The function return value is zero in this case.
See Also

SetService, NS_SERVICE_INFO, SERVICE_INFO


GetServiceDisplayName
 GetServiceDisplayName  QuickInfo  Overview  Group

The GetServiceDisplayName function obtains the display name that is associated with a particular service name. The service name is the same as the service's registry key name.

BOOL GetServiceDisplayName(

SC_HANDLE  hSCManager,	// handle to a service control manager database
LPCTSTR  lpServiceName,	// the service name
LPTSTR  lpDisplayName,	// buffer to receive the service's display name
LPDWORD  lpcchBuffer	// size of display name buffer and display name
);
Parameters

hSCManager

Handle to a machine's service control manager database. This parameter is an RPC server handle as returned by the OpenSCManager function.

lpServiceName

Points to a null-terminated service name string. This name is the same as the service's registry key name.

lpDisplayName

Points to a buffer into which the function stores the service's display name as a null-terminated string. If the function fails, this buffer will contain an empty string.

lpcchBuffer

Points to a DWORD that contains the size, in characters, of the buffer pointed to by lpDisplayName. When the function returns, this DWORD contains the size, in characters, of the service's display name, excluding the NULL terminator.

If the buffer pointed to by lpDisplayName is too small to contain the display name, the function stores no data into it. When the function returns, the DWORD pointed to by lpcchBuffer contains the size in characters of the service's display name, excluding the NULL terminator.

Return Value

If the functions succeeds, the return value is TRUE.

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

Remarks

There are two names for a service: the service name, which is the actual name of the service's key in the registry's Services section, and a more user-friendly display name that appears in the Services Control Panel application and is used with the NET START command. The GetServiceDisplayName and GetServiceKeyName functions let an application map one of these names to the other. An application passes a service's registry key name to GetServiceDisplayName, and obtains the service's user-friendly display name. An application passes a service's display name to GetServiceKeyName, and obtains the service's registry key name.

See Also

GetServiceKeyName, OpenSCManager


GetServiceKeyName
 GetServiceKeyName  QuickInfo  Overview  Group

The GetServiceKeyName function obtains the service name that is associated with a particular service's display name. The service name is the same as the service's registry key name.

BOOL GetServiceKeyName(

SC_HANDLE  hSCManager,	// handle to a service control manager database
LPCTSTR  lpDisplayName,	// the service's display name
LPTSTR  lpServiceName,	// buffer to receive the service name
LPDWORD  lpcchBuffer	// size of service name buffer and service name
);
Parameters

hSCManager

Handle to a computer's service control manager database. This parameter is a remote procedure call (RPC) server handle as returned by OpenSCManager.

lpDisplayName

Points to a null-terminated service display name string.

lpServiceName

Points to a buffer into which the function stores the service name as a null-terminated string. If the function fails, this buffer will contain an empty string.

lpcchBuffer

Points to a DWORD that contains the size in characters of the buffer pointed to by the lpServiceName parameter. When the function returns, this DWORD contains the size, in characters, of the service name, excluding the NULL terminator.

If the buffer pointed to by lpServiceName is too small to contain the service name, the function stores no data in it. When the function returns, the DWORD pointed to by lpcchBuffer contains the size, in characters, of the service name, excluding the NULL terminator.

Return Value

If the functions succeeds, the return value is TRUE.

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

Remarks

There are two names for a service: the service name, which is the actual name of the service's key in the registry's Services section, and a more user-friendly display name that appears in the Services Control Panel application and is used with the NET START command. The GetServiceDisplayName and GetServiceKeyName functions let an application map one of these names to the other. An application passes a service's registry key name to GetServiceDisplayName, and obtains the service's user-friendly display name. An application passes a service's display name to GetServiceKeyName, and obtains the service's registry key name.

See Also

GetServiceDisplayName, OpenSCManager


GetShortPathName
 GetShortPathName  QuickInfo  Overview  Group

The GetShortPathName function obtains the short path form of a specified input path.

DWORD GetShortPathName(

LPCTSTR  lpszLongPath,	// points to a null-terminated path string
LPTSTR   lpszShortPath,	// points to a buffer to receive the null-terminated short form of the path
DWORD  cchBuffer	// specifies the size of the buffer pointed to by lpszShortPath
);
Parameters

lpszLongPath

Points to a null-terminated path string. The function obtains the short form of this path.

lpszShortPath

Points to a buffer to receive the null-terminated short form of the path specified by lpszLongPath.

cchBuffer

Specifies the size, in characters, of the buffer pointed to by lpszShortPath.

Return Value

If the function succeeds, the return value is the length, in characters, of the string stored in *lpszShortPath, not including the terminating null character.

If the function fails due to *lpszShortPath being too small to contain the short path string, the return value is the size, in characters, of the short path string. You need to call the function with a short path buffer that is at least as large as the short path string.

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

Remarks

When an application calls this function and specifies a path on a volume that does not support 8.3 aliases, such as HPFS, the function fails with ERROR_INVALID_PARAMETER if the pathname is longer than 67 bytes.

The path specified by lpszLongPath does not have to be a fully qualified path or a long path. The short form may be longer than the specifed path.

If the specified path is already in its short form, there is no need for any conversion, and the function simply copies the specified path to the buffer for the short path.

You can set lpszShortPath to the same value as lpszLongPath; in other words, you can set the buffer for the short path to the address of the input path string.

See Also

GetFullPathName


GetSidIdentifierAuthority
 GetSidIdentifierAuthority  QuickInfo  Overview  Group

The GetSidIdentifierAuthority function returns the address of the SID_IDENTIFIER_AUTHORITY structure in a specified security identifier (SID).

PSID_IDENTIFIER_AUTHORITY GetSidIdentifierAuthority(

PSID  pSid	// address of SID to query
);
Parameters

pSid

Points to the SID structure for which the address of the SID_IDENTIFIER_AUTHORITY structure is returned.

Return Value

If the function succeeds, the return value is the address of the SID_IDENTIFIER_AUTHORITY structure for the specified SID structure.

If the function fails, the return value is undefined. The function fails if the SID structure pointed to by the pSid parameter is invalid. To get extended error information, call GetLastError.

See Also

GetLengthSid, GetSidLengthRequired, GetSidSubAuthority, GetSidSubAuthorityCount, IsValidSid, SID, SID_IDENTIFIER_AUTHORITY


GetSidLengthRequired
 GetSidLengthRequired  QuickInfo  Overview  Group

The GetSidLengthRequired function returns the length, in bytes, of the buffer required to store a SID structure with a specified number of subauthorities.

DWORD GetSidLengthRequired(

UCHAR  nSubAuthorityCount	// count of subauthorities
);
Parameters

nSubAuthorityCount

Specifies the number of subauthorities to be stored in the SID structure.

Return Value

The return value is the length, in bytes, of the buffer required to store the SID structure. This function cannot fail.

See Also

AllocateAndInitializeSid, GetLengthSid, GetSidIdentifierAuthority, GetSidSubAuthority, GetSidSubAuthorityCount, InitializeSid, IsValidSid, SID


GetSidSubAuthority
 GetSidSubAuthority  QuickInfo  Overview  Group

The GetSidSubAuthority function returns the address of a specified subauthority in a SID structure. The subauthority value is a relative identifier (RID). A SID is a security identifier.

PDWORD GetSidSubAuthority(

PSID  pSid,	// address of security identifier to query
DWORD  nSubAuthority	// index of subauthority to retrieve
);
Parameters

pSid

Points to the SID structure from which the address of a subauthority is to be returned.

nSubAuthority

Specifies an index value identifying the subauthority array element whose address the function will return. The function performs no validation tests on this value. An application can call the GetSidSubAuthorityCount function to discover the range of acceptable values.

Return Value

If the function succeeds, the return value is the address of the specified SID subauthority. To get extended error information, call GetLastError.

If the function fails, the return value is undefined. The function fails if the specified SID structure is invalid or if the index value specified by the nSubAuthority parameter is out of bounds.

See Also

GetLengthSid, GetSidIdentifierAuthority, GetSidLengthRequired, GetSidSubAuthorityCount, IsValidSid, SID


GetSidSubAuthorityCount
 GetSidSubAuthorityCount  QuickInfo  Overview  Group

The GetSidSubAuthorityCount function returns the address of the field in a SID structure containing the subauthority count. A SID is a security identifier.

PUCHAR GetSidSubAuthorityCount(

PSID  pSid	// address of security identifier to query
);
Parameters

pSid

Points to the SID structure from which a pointer to the subauthority count is returned.

Return Value

If the function succeeds, the return value is a pointer to the subauthority count for the specified SID structure.

If the function fails, the return value is undefined. The function fails if the specified SID structure is invalid. To get extended error information, call GetLastError.

See Also

GetLengthSid, GetSidIdentifierAuthority, GetSidLengthRequired, GetSidSubAuthority, IsValidSid, SID


getsockname
 getsockname  QuickInfo

The Windows Sockets getsockname function gets the local name for a socket.

int getsockname (

SOCKET s,
struct sockaddr FAR * name,
int FAR * namelen
);
Parameters

s

A descriptor identifying a bound socket.

name

Receives the address (name) of the socket.

namelen

The size of the name buffer.

Return Value

If no error occurs, getsockname returns zero. Otherwise, a value of SOCKET_ERROR is returned, and a specific error code may be retrieved by calling WSAGetLastError.

Error Codes

WSANOTINITIALISED	A successful WSAStartup must occur before using this function.
WSAENETDOWN	The Windows Sockets implementation has detected that the network subsystem has failed.
WSAEFAULT	The namelen argument is not large enough.
WSAEINPROGRESS	A blocking Windows Sockets operation is in progress.
WSAENOTSOCK	The descriptor is not a socket.
WSAEINVAL	The socket has not been bound to an address with bind.
Remarks

The getsockname function retrieves the current name for the specified socket descriptor in name. It is used on a bound or connected socket specified by the s parameter. The local association is returned. This call is especially useful when a connect call has been made without doing a bind first; this call provides the only means by which you can determine the local association set by the system.

On return, the namelen argument contains the actual size of the name returned in bytes.

If a socket was bound to INADDR_ANY, indicating that any of the host's IP addresses should be used for the socket, getsockname will not necessarily return information about the host IP address, unless the socket has been connected with connect or accept. A Windows Sockets application must not assume that the IP address will be changed from INADDR_ANY unless the socket is connected. This is because for a multi-homed host, the IP address that will be used for the socket is unknown unless the socket is connected.

See Also

accept, bind, connect, getpeername, socket, WSAStartup


getsockopt
 getsockopt  QuickInfo

The Windows Sockets getsockopt function retrieves a socket option.

int getsockopt (

SOCKET s,
int level,
int optname,
char FAR * optval,
int FAR * optlen
);
Parameters

s

A descriptor identifying a socket.

level

The level at which the option is defined; the only supported levels are SOL_SOCKET and IPPROTO_TCP.

optname

The socket option for which the value is to be retrieved.

optval

A pointer to the buffer in which the value for the requested option is to be returned.

optlen

A pointer to the size of the optval buffer.

Return Value

If no error occurs, getsockopt returns 0. Otherwise, a value of SOCKET_ERROR is returned, and a specific error code may be retrieved by calling WSAGetLastError.

Error Codes

WSANOTINITIALISED	A successful WSAStartup must occur before using this function.
WSAENETDOWN	The Windows Sockets implementation has detected that the network subsystem has failed.
WSAEFAULT	The optlen argument was invalid.
WSAEINPROGRESS	A blocking Windows Sockets operation is in progress.
WSAENOPROTOOPT	The option is unknown or unsupported. In particular, SO_BROADCAST is not supported on sockets of type SOCK_STREAM, while SO_ACCEPTCONN, SO_DONTLINGER, SO_KEEPALIVE, SO_LINGER and SO_OOBINLINE are not supported on sockets of type SOCK_DGRAM.
WSAENOTSOCK	The descriptor is not a socket.
Remarks

The getsockopt function retrieves the current value for a socket option associated with a socket of any type, in any state, and stores the result in optval. Options may exist at multiple protocol levels, but they are always present at the uppermost "socket" level. Options affect socket operations, such as whether an operation blocks or not, the routing of packets, out-of-band data transfer, and so on.

The value associated with the selected option is returned in the buffer optval. The integer pointed to by optlen should originally contain the size of this buffer; on return, it will be set to the size of the value returned. For SO_LINGER, this will be the size of a linger structure; for all other options it will be the size of an integer.

If the option was never set with setsockopt, then getsockopt returns the default value for the option.

The following options are supported for getsockopt. The "Type" heading identifies the type of data addressed by optval. The TCP_NODELAY option uses level IPPROTO_TCP; all other options use level SOL_SOCKET.

Value	Type	Meaning
SO_ACCEPTCONN	BOOL	Socket is in listen mode.
SO_BROADCAST	BOOL	Socket is configured for the transmission of broadcast messages.
SO_DEBUG	BOOL	Debugging is enabled.
SO_DONTLINGER	BOOL	If true, the SO_LINGER option is disabled.
SO_DONTROUTE	BOOL	Routing is disabled.
SO_ERROR	int	Retrieve error status and clear.
SO_KEEPALIVE	BOOL	Keepalive messages are being sent.
SO_LINGER	struct linger FAR *	Returns the current linger options.
SO_OOBINLINE	BOOL	Out-of-band data is being received in the normal data stream.
SO_RCVBUF	int	Buffer size for receive operations.
SO_REUSEADDR	BOOL	The socket may be bound to an address that is already in use.
SO_SNDBUF	int	Buffer size for send operations.
SO_TYPE	int	The type of the socket (for example, SOCK_STREAM).
TCP_NODELAY	BOOL	Disables the Nagle algorithm for send coalescing.
BSD options not supported for getsockopt are:

Value	Type	Meaning
SO_RCVLOWAT	int	Receive low-water mark.
SO_RCVTIMEO	int	Receive timeout.
SO_SNDLOWAT	int	Send low-water mark.
SO_SNDTIMEO	int	Send timeout.
IP_OPTIONS		Get options in IP header.
TCP_MAXSEG	int	Get TCP maximum segment size.
Calling getsockopt with an unsupported option will result in an error code of WSAENOPROTOOPT being returned from WSAGetLastError.

See Also

setsockopt, socket, WSAAsyncSelect, WSAStartup


GetStartupInfo
 GetStartupInfo  QuickInfo  Overview  Group

The GetStartupInfo function retrieves the contents of the STARTUPINFO structure that was specified when the calling process was created.

VOID GetStartupInfo(

LPSTARTUPINFO  lpStartupInfo	// address of STARTUPINFO structure
);
Parameters

lpStartupInfo

Points to a STARTUPINFO structure that is filled in by the function.

Return Value

This function does not return a value.

Remarks

The STARTUPINFO structure was specified by the process that created the calling process. It can be used to specify properties associated with the main window of the calling process.

See Also

CreateProcess, STARTUPINFO


GetStdHandle
 GetStdHandle  QuickInfo  Overview  Group

The GetStdHandle function returns a handle for the standard input, standard output, or standard error device.

HANDLE GetStdHandle(

DWORD  nStdHandle	// input, output, or error device
);
Parameters

nStdHandle

Specifies the device for which to return the handle. This parameter can have one of the following values:

Value	Meaning
STD_INPUT_HANDLE	Standard input handle
STD_OUTPUT_HANDLE	Standard output handle
STD_ERROR_HANDLE	Standard error handle
Return Value

If the function succeeds, the return value is a handle of the specified device.

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

Remarks

Handles returned by GetStdHandle can be used by applications that need to read from or write to the console. When a console is created, the standard input handle is a handle of the console's input buffer, and the standard output and standard error handles are handles of the console's active screen buffer. These handles can be used by the ReadFile and WriteFile functions, or by any of the console functions that access the console input buffer or a screen buffer (for example, the ReadConsoleInput, WriteConsole, or GetConsoleScreenBufferInfo functions).

All handles returned by this function have GENERIC_READ and GENERIC_WRITE access unless the SetStdHandle function has been used to set a standard handle to be some handle with a lesser access.

The standard handles of a process may be redirected by a call to SetStdHandle, in which case GetStdHandle returns the redirected handle. If the standard handles have been redirected, you can specify the CONIN$ value in a call to the CreateFile function to get a handle of a console's input buffer. Similarly, you can specify the CONOUT$ value to get a handle of a console's active screen buffer.

See Also

CreateFile, GetConsoleScreenBufferInfo, ReadConsoleInput, ReadFile, SetStdHandle, WriteConsole, WriteFile


GetStockObject
 GetStockObject  QuickInfo  Overview  Group

The GetStockObject function retrieves a handle to one of the predefined stock pens, brushes, fonts, or palettes.

HGDIOBJ GetStockObject(

int  fnObject	// type of stock object
);
Parameters

fnObject

Specifies the type of stock object. This parameter can be any one of the following values:

Value	Meaning
BLACK_BRUSH	Black brush.
DKGRAY_BRUSH	Dark gray brush.
GRAY_BRUSH	Gray brush.
HOLLOW_BRUSH	Hollow brush (equivalent to NULL_BRUSH).
LTGRAY_BRUSH	Light gray brush.
NULL_BRUSH	Null brush (equivalent to HOLLOW_BRUSH).
WHITE_BRUSH	White brush.
BLACK_PEN	Black pen.
NULL_PEN	Null pen.
WHITE_PEN	White pen.
ANSI_FIXED_FONT	Windows fixed-pitch (monospace) system font.
ANSI_VAR_FONT	Windows variable-pitch (proportional space) system font.
DEVICE_DEFAULT_FONT	Windows NT only: Device-dependent font.
DEFAULT_GUI_FONT	Windows 95 only: Default font for user interface objects such as menus and dialog boxes.
OEM_FIXED_FONT	Original equipment manufacturer (OEM) dependent fixed-pitch (monospace) font.
SYSTEM_FONT	System font. By default, Windows uses the system font to draw menus, dialog box controls, and text. In Windows versions 3.0 and later, the system font is a proportionally spaced font; earlier versions of Windows used a monospace system font.
SYSTEM_FIXED_FONT	Fixed-pitch (monospace) system font used in Windows versions earlier than 3.0. This stock object is provided for compatibility with earlier versions of Windows.
DEFAULT_PALETTE	Default palette. This palette consists of the static colors in the system palette.
Return Value

If the function succeeds, the return value identifies the logical object requested.

If the function fails, the return value is NULL.

Remarks

Use the DKGRAY_BRUSH, GRAY_BRUSH, and LTGRAY_BRUSH stock objects only in windows with the CS_HREDRAW and CS_VREDRAW styles. Using a gray stock brush in any other style of window can lead to misalignment of brush patterns after a window is moved or sized. The origins of stock brushes cannot be adjusted.

The HOLLOW_BRUSH and NULL_BRUSH stock objects are equivalent.

The font used by the DEFAULT_GUI_FONT stock object could change. Use this stock object when you want to use the font that menus, dialog boxes, and other user interface objects use.

It is not necessary (but it is not harmful) to delete stock objects by calling DeleteObject.

See Also

DeleteObject, SelectObject


GetStretchBltMode
 GetStretchBltMode  QuickInfo  Overview  Group

The GetStretchBltMode function retrieves the current stretching mode. The stretching mode defines how color data is added to or removed from bitmaps that are stretched or compressed when the StretchBlt function is called.

int GetStretchBltMode(

HDC  hdc	// handle of device context
);
Parameters

hdc

Identifies the device context.

Return Value

If the function succeeds, the return value is the current stretching mode.

If the function fails, the return value is zero.

See Also

SetStretchBltMode, StretchBlt


GetStringTypeA
 GetStringTypeA  QuickInfo  Overview  Group

The GetStringTypeA function returns 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,	// pointer to the source string
int  cchSrc,	// size, in bytes, of the source string
LPWORD  lpCharType	// pointer to the buffer for output
);
Parameters

Locale

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:

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

dwInfoType

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:

CT_CTYPE1	Retrieve character type information.
CT_CTYPE2	Retrieve bidirectional layout information.
CT_CTYPE3	Retrieve text processing information.
lpSrcStr

Points 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

Specifies the size, in bytes, 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

Points 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 Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. 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 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	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 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. These types are supported in the current version of Windows NT. A combination of these values is returned when dwInfoType is set to CT_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)
Not applicable:
C3_NOTAPPLICABLE	0x0	Not applicable
See Also

GetLocaleInfo, GetStringTypeEx, GetStringTypeW


GetStringTypeEx
 GetStringTypeEx  QuickInfo  Overview  Group

The GetStringTypeEx function returns 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 Win32 function.

BOOL GetStringTypeEx(

LCID  Locale,	// locale identifer
DWORD  dwInfoType,	// information-type options
LPCTSTR  lpSrcStr,	// address of source string
int  cchSrc,	// size, in bytes or characters, of source string
LPWORD  lpCharType	// address of buffer for output
);
Parameters

Locale

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:

LOCALE_SYSTEM_DEFAULT	Default system locale
LOCALE_USER_DEFAULT	Default user locale
dwInfoType

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:

CT_CTYPE1	Retrieve character type information.
CT_CTYPE2	Retrieve bidirectional layout information.
CT_CTYPE3	Retrieve text processing information.
lpSrcStr

Points 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 for the W version of this function, and an ANSI string for the A version. Note that for the A  version, this can be a double-byte character set (DBCS) string if the locale is appropriate for DBCS.

cchSrc

Specifies the size, in bytes (ANSI version) or characters (Unicode version), 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

Points 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 Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. 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 Win32 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	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 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. These types are supported in the current version of Windows NT. A combination of these values is returned when dwInfoType is set to CT_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)
Not applicable:
C3_NOTAPPLICABLE	0x0	Not applicable
See Also

GetLocaleInfo, GetStringTypeA, GetStringTypeW


GetStringTypeW
 GetStringTypeW  QuickInfo  Overview  Group

The GetStringTypeW function returns 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,	// address of source string
int  cchSrc,	// number of characters in string
LPWORD  lpCharType	// address of buffer for output
);
Parameters

dwInfoType

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:

CT_CTYPE1	Retrieve character type information.
CT_CTYPE2	Retrieve bidirectional layout information.
CT_CTYPE3	Retrieve text processing information.
lpSrcStr

Points 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

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

Points 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 characters specified in the cchSrc parameter. When the function returns, this array contains one word corresponding to each Unicode character in the source string.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. 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 Win32 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	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 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. These types are supported in the current version of Windows NT. A combination of these values is returned when dwInfoType is set to CT_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)
Not applicable:
C3_NOTAPPLICABLE	0x0	Not applicable
See Also

GetLocaleInfo, GetStringTypeA, GetStringTypeEx


GetSubMenu
 GetSubMenu  QuickInfo  Overview  Group

The GetSubMenu function retrieves the handle of the pop-up menu activated by the specified menu item.

HMENU GetSubMenu(

HMENU  hMenu,	// handle of menu
int  nPos	// menu item position
);
Parameters

hMenu

Identifies the menu.

nPos

Specifies the zero-based relative position in the given menu of an item that activates a pop-up menu.

Return Value

If the function succeeds, the return value is the handle of the pop-up menu activated by the menu item. If the menu item does not activate a pop-up menu, it is NULL.

See Also

CreatePopupMenu, GetMenu


GetSysColor
 GetSysColor  QuickInfo  Overview  Group

The GetSysColor function retrieves the current color of the specified display element. Display elements are the parts of a window and the Windows display that appear on the system display screen.

DWORD GetSysColor(

int  nIndex	// display element
);
Parameters

nIndex

Specifies the display element whose color is to be retrieved. This parameter must be one of the following values:

Value	Meaning
COLOR_3DDKSHADOW	Windows 95 only: Dark shadow for three-dimensional display elements.
COLOR_3DFACE	Windows 95 only: Face color for three-dimensional display elements.
COLOR_3DHILIGHT	Windows 95 only: Highlight color for three-dimensional display elements (for edges facing the light source.)
COLOR_3DLIGHT	Windows 95 only: Light color for three-dimensional display elements (for edges facing the light source.)
COLOR_3DSHADOW	Windows 95 only: Shadow color for three-dimensional display elements (for edges facing away from the light source).
COLOR_ACTIVEBORDER	Active window border.
COLOR_ACTIVECAPTION	Active window caption.
COLOR_APPWORKSPACE	Background color of multiple document interface (MDI) applications.
COLOR_BACKGROUND	Desktop.
COLOR_BTNFACE	Windows NT only: Face shading on push buttons.
COLOR_BTNHILIGHT	Windows 95 only: Highlight color  for buttons (same as COLOR_3DHILIGHT).
COLOR_BTNSHADOW	Edge shading on push buttons.
COLOR_BTNTEXT	Text on push buttons.
COLOR_CAPTIONTEXT	Text in caption, size box, and scroll bar arrow box.
COLOR_GRAYTEXT	Grayed (disabled) text. This color is set to 0 if the current display driver does not support a solid gray color.
COLOR_HIGHLIGHT	Item(s) selected in a control.
COLOR_HIGHLIGHTTEXT	Text of item(s) selected in a control.
COLOR_INACTIVEBORDER	Inactive window border.
COLOR_INACTIVECAPTION	Inactive window caption.
COLOR_INACTIVECAPTIONTEXT	Color of text in an inactive caption.
COLOR_INFOBK	Windows 95 only: Background color for tooltip controls.
COLOR_INFOTEXT	Windows 95 only: Text color for tooltip controls.
COLOR_MENU	Menu background.
COLOR_MENUTEXT	Windows NT only: Text in menus.
COLOR_SCROLLBAR	Scroll bar gray area.
COLOR_WINDOW	Window background.
COLOR_WINDOWFRAME	Window frame.
COLOR_WINDOWTEXT	Text in windows.
Return Value

If the function succeeds, the return value is the red, green, blue (RGB) color value that specifies the color of the given element.

Remarks

System colors for monochrome displays are usually interpreted as shades of gray.

See Also

SetSysColors


GetSysColorBrush [New - Windows 95]
 GetSysColorBrush  QuickInfo  Overview  Group

[New - Windows 95]

The GetSysColorBrush function retrieves a handle identifying a logical brush that corresponds to the specified color index.

HBRUSH GetSysColorBrush(

int  nIndex	// system color index
);
Parameters

nIndex

Specifies a color index. This value corresponds to the color used to paint one of the 21 window elements.

Return Value

If the function succeeds, the return value identifies a logical brush. To get extended error information, call GetLastError.

Remarks

A brush is a bitmap that Windows uses to paint the interiors of filled shapes. An application can retrieve the current system colors by calling the GetSysColor function. An application can set the current system colors by calling the SetSysColors function.

An application must not register a window class for a window using a system brush.

See Also

GetSysColor, SetSysColors


GetSysModalWindow
 GetSysModalWindow  QuickInfo  Overview  Group

The GetSysModalWindow function is not implemented in the Win32 API.


GetSystemDefaultLangID
 GetSystemDefaultLangID  QuickInfo  Overview  Group

The GetSystemDefaultLangID function retrieves the system default language identifier.

LANGID GetSystemDefaultLangID(VOID)

Parameters

This function has no parameters.

Return Value

If the function succeeds, the return value is the system default language identifier.

Remarks

For more information about language identifiers, see Language Identifiers and Locales.

See Also

GetUserDefaultLangID, MAKELANGID


GetSystemDefaultLCID
 GetSystemDefaultLCID  QuickInfo  Overview  Group

The GetSystemDefaultLCID function retrieves the system default locale identifier.

LCID GetSystemDefaultLCID(VOID)

Parameters

This function has no parameters.

Return Value

If the function succeeds, the return value is the system default locale identifier.

Remarks

For more information about locale identifiers, see Locale Identifiers.

See Also

GetLocaleInfo, GetUserDefaultLCID, MAKELCID


 GetSystemDir

The GetSystemDir function is not supported in the Win32 API. For Win32-based applications, use the GetSystemDirectory function to determine the system directory.


GetSystemDirectory
 GetSystemDirectory  QuickInfo  Overview  Group

The GetSystemDirectory function retrieves the path of the Windows system directory. The system directory contains such files as Windows libraries, drivers, and font files.

UINT GetSystemDirectory(

LPTSTR  lpBuffer,	// address of buffer for system directory
UINT  uSize	// size of directory buffer
);
Parameters

lpBuffer

Points to the buffer to receive the null-terminated string containing the path. This path does not end with a backslash unless the system directory is the root directory. For example, if the system directory is named WINDOWS\SYSTEM on drive C, the path of the system directory retrieved by this function is C:\WINDOWS\SYSTEM.

uSize

Specifies the maximum size of the buffer, in characters. This value should be set to at least MAX_PATH.

Return Value

If the function succeeds, the return value is the length, in characters, of the string copied to the buffer, not including the terminating null character. If the length is greater than the size of the buffer, the return value is the size of the buffer required to hold the path.

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

Remarks

Applications should not create files in the system directory. If the user is running a shared version of Windows, the application does not have write access to the system directory. Applications should create files only in the directory returned by the GetWindowsDirectory function.

See Also

GetCurrentDirectory, GetWindowsDirectory, SetCurrentDirectory


GetSystemInfo
 GetSystemInfo  QuickInfo  Overview  Group

The GetSystemInfo function returns information about the current system.

VOID GetSystemInfo(

LPSYSTEM_INFO  lpSystemInfo	// address of system information structure
);
Parameters

lpSystemInfo

Points to a SYSTEM_INFO structure to be filled in by this function.

Return Value

This function does not return a value.

See Also

SYSTEM_INFO


GetSystemMenu
 GetSystemMenu  QuickInfo  Overview  Group

The GetSystemMenu function allows the application to access the System menu (also known as the Control menu) for copying and modifying.

HMENU GetSystemMenu(

HWND  hWnd,	// handle of window to own System menu
BOOL  bRevert	// reset flag
);
Parameters

hWnd

Identifies the window that will own a copy of the System menu.

bRevert

Specifies the action to be taken. If this parameter is FALSE, GetSystemMenu returns the handle of the copy of the System menu currently in use. The copy is initially identical to the System menu, but it can be modified.

If this parameter is TRUE, GetSystemMenu resets the System menu back to the Windows default state. The previous System menu, if any, is destroyed.

Return Value

If the bRevert parameter is FALSE, the return value is the handle of a copy of the System menu. If the bRevert parameter is TRUE, the return value is NULL.

Remarks

Any window that does not use the GetSystemMenu menu to make its own copy of the System menu receives the standard System menu.

The System menu initially contains items with various identifier values, such as SC_CLOSE, SC_MOVE, and SC_SIZE.

Menu items on the System menu send WM_SYSCOMMAND messages.

All predefined System menu items have identifier numbers greater than 0xF000. If an application adds commands to the System menu, it should use identifier numbers less than 0xF000.

Windows automatically grays items on the standard System 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.

See Also

GetMenu, WM_INITMENU, WM_SYSCOMMAND


GetSystemMetrics
 GetSystemMetrics  QuickInfo  Overview  Group

The GetSystemMetrics function retrieves various system metrics and system configuration settings.

System metrics are the dimensions (widths and heights) of Windows display elements. All dimensions retrieved by GetSystemMetrics are in pixels.

int GetSystemMetrics(

int  nIndex	// system metric or configuration setting to retrieve
);
Parameters

nIndex

Specifies the system metric or configuration setting to retrieve. All SM_CX* values are widths. All SM_CY* values are heights. The following values are defined:

Value	Meaning
SM_ARRANGE	Windows 95 only: Flags specifying how the system arranged minimized windows. For more information about minimized windows, see the following Remarks section.
SM_CLEANBOOT	Windows 95 only: Value that specifies how the system was started: 0 Normal boot 1 Fail-safe boot 2 Fail-safe with network boot Fail-safe boot (also called SafeBoot) bypasses the user's startup files.
SM_CMETRICS	Windows 95 only: Number of system metrics and flags.
SM_CMOUSEBUTTONS	Number of buttons on mouse, or zero if no mouse is installed.
SM_CXBORDER,  SM_CYBORDER	Windows NT only: Width and height of window border.  Windows 95 only: Dimensions of a single border, in pixels.
SM_CXCURSOR,  SM_CYCURSOR	Windows NT only: Width and height of cursor. Windows 95 only: Dimensions of standard cursor bitmaps, in pixels.
SM_CXDLGFRAME, SM_CYDLGFRAME	Width and height of window frame for a window that has the WS_DLGFRAME style.  Windows 95 only: Obsolete; use SM_CX_FIXEDFRAME and SM_CYFIXEDFRAME instead.
SM_CXDOUBLECLK,  SM_CYDOUBLECLK	Windows NT only: Width and height of a rectangle around the location of a first click in a double-click sequence. The second click must occur within this rectangle for the system to consider the two clicks a double-click. Windows 95 only: Dimensions, in pixels, of the rectangle within which two successive mouse clicks must fall to generate a double-click. (The two clicks must also occur within a specified time.)
SM_CXFRAME, SM_CYFRAME	Width and height of window frame for a window that can be resized.  Windows 95 only: Obsolete; use SM_CX_FIXEDFRAME and SM_CYFIXEDFRAME instead.
SM_CXFULLSCREEN, SM_CYFULLSCREEN	Width and height of the client area for a full-screen window.
SM_CXHSCROLL,  SM_CYHSCROLL	Width and height of arrow bitmap on horizontal scrollbar.
SM_CXHTHUMB,	Width of horizontal scrollbar thumb box.
SM_CXICON,  SM_CYICON	The default width and height of an icon. These values are typically 32x32, but can vary depending on the installed display hardware. Windows 95 only: The LoadIcon function can only load icons of these dimensions.
SM_CXICONSPACING, SM_CYICONSPACING	Windows NT only: Width and height of rectangular cell that Program Manager uses to position tiled icons. Windows 95 only: Dimensions of a grid cell for items in large icon view, in pixels. Each item fits into a rectangle of this size when arranged. These values are always greater than or equal to SM_CXICON and SM_CYICON.
SM_CXMAXIMIZED, SM_CYMAXIMIZED	Windows 95 only: Default dimensions of a maximized top-level window, in pixels.
SM_CXMAXTRACK, SM_CYMAXTRACK	Windows 95 only: Default maximum dimensions of a window that has a caption and sizing borders. The user cannot drag the window frame to a size larger than these dimensions. A window can override these values by processing the WM_GETMINMAXINFO message.
SM_CXMENUCHECK, SM_CYMENUCHECK	Windows 95 only: Dimensions of the default menu check-mark bitmap, in pixels.
SM_CXMENUSIZE, SM_CYMENUSIZE	Windows 95 only: Dimensions of menu bar buttons (such as multiple document (MIDI) child close), in pixels.
SM_CXMINIMIZED, SM_CYMINIMIZED	Windows 95 only: Dimensions of a normal minimized window, in pixels.
SM_CXMINSPACING SM_CYMINSPACING	Windows 95 only: Dimensions of a grid cell for minimized windows, in pixels. Each minimized window fits into a rectangle this size when arranged. These values are always greater than or equal to SM_CXMINIMIZED and SM_CYMINIMIZED.
SM_CXMINTRACK, SM_CYMINTRACK	Minimum tracking width and height of a window. The user cannot drag the window frame to a size smaller than these dimensions. A window can override these values by processing the WM_GETMINMAXINFO message.
SM_CXSCREEN,  SM_CYSCREEN	Width and height of the screen.
SM_CXSIZE,  SM_CYSIZE	Windows NT only: Width and height of bitmaps contained in title bar. Windows 95 only: Dimensions of caption buttons, in pixels.
SM_CXSIZEFRAME, SM_CYSIXEFRAME	Windows 95 only: Dimensions, in pixels, of the window frame for a window that has the WS_THICKFRAME style. Formerly SM_CXFRAME and SM_CYFRAME.
SM_CXSMICON, SM_CYSICON	Windows 95 only: Recommended dimensions of a small icon, in pixels. Small icons typically appear in window captions and in small icon view.
SM_CXSMSIZE SM_CYSMSIZE	Windows 95 only: Dimensions of small caption buttons, in pixels.
SM_CXVSCROLL SM_CYHSCROLL	Windows 95 only: Width of vertical scrollbar and height of horizontal scrollbar, in pixels.
SM_CXHSCROLL SM_CYVSCROLL	Windows 95 only: Width of the arrow bitmap on a horizontal scrollbar, and height of the arrow bitmap on a vertical scrollbar.
SM_CXVSCROLL,  SM_CYVSCROLL	Windows NT only: Width and height of arrow bitmap on vertical scrollbar.
SM_CYVTHUMB	Height of vertical scrollbar thumb.
SM_CYCAPTION	Height of normal caption area.
SM_CYKANJIWINDOW	For double-byte character set versions of Windows, height of the Kanji window at the bottom of the screen.
SM_CYMENU	Height of single-line menu bar.
SM_CYSMCAPTION	Windows 95 only: Height of a small caption, in pixels.
SM_DBCSENABLED	TRUE or non-zero if the double-byte character set (DBCS) version of USER.EXE is installed; FALSE, or zero otherwise.
SM_DEBUG	TRUE or non-zero if the debugging version of USER.EXE is installed; FALSE, or zero, otherwise.
SM_MENUDROPALIGNMENT	TRUE, or non-zero if pop-up menus are right-aligned relative to the corresponding menu-bar item; FALSE, or zero if they are left-aligned.
SM_MIDEASTENABLED	Windows 95 only: TRUE if the system is enabled for Hebrew/Arabic languages.
SM_MOUSEPRESENT	TRUE or non-zero if a mouse is installed; FALSE, or zero, otherwise.
SM_NETWORK	Windows 95 only: The least significant bit is set if a network is present; otherwise, it is cleared. The other bits are reserved for future use.
SM_PENWINDOWS	TRUE or non-zero if the Microsoft Windows for Pen computing extensions are installed; zero, or FALSE, otherwise.
SM_SECURE	Windows 95 only: TRUE if security is present, FALSE otherwise.
SM_SHOWSOUNDS	TRUE or non-zero if the user requires an application to present information visually in situations where it would otherwise present the information only in audible form; FALSE, or zero, otherwise.
SM_SLOWMACHINE	Windows 95 only: TRUE if the computer has a low-end (slow) processor, FALSE otherwise.
SM_SWAPBUTTON	TRUE or non-zero if the meanings of the left and right mouse buttons are swapped; FALSE, or zero, otherwise.
Return Value

The return value is the requested system metric or configuration setting.

Remarks

System metrics may vary from display to display.

The SM_ARRANGE setting specifies how the system arranges minimized windows, and consists of a starting position and a direction. The starting position can be one of these values:

Value	Meaning
ARW_BOTTOMLEFT	Start at lower-left corner of screen (default position).
ARW_BOTTOMRIGHT	Start at lower-right corner of screen. Equivelant to ARW_STARTRIGHT.
ARW_HIDE	Hide minimized windows by moving them off of the visible area of the screen.
ARW_TOPLEFT	Start at upper-left corner of screen. Equivelant to ARV_STARTTOP.
ARW_TOPRIGHT	Start at upper-right corner of screen. Equivelant to ARW_STARTTOP | SRW_STARTRIGHT.

The direction in which to arrange can be one of these values:

Value	Meaning
ARW_DOWN	Arrange vertically, top to bottom.
ARW_LEFT	Arrange horizontally, left to right.
ARW_RIGHT	Arrange horizontally, right to left.
ARW_UP	Arrange vertically, bottom to top.


GetSystemPaletteEntries
 GetSystemPaletteEntries  QuickInfo  Overview  Group

The GetSystemPaletteEntries function retrieves a range of palette entries from the system palette that is associated with the specified device context.

UINT GetSystemPaletteEntries(

HDC  hdc,	// handle of device context
UINT  iStartIndex,	// index of first entry to be retrieved
UINT  nEntries,	// number of entries to be retrieved
LPPALETTEENTRY  lppe	// array receiving system-palette entries
);
Parameters

hdc

Identifies the device context.

iStartIndex

Specifies the first entry to be retrieved from the system palette.

nEntries

Specifies the number of entries to be retrieved from the system palette.

lppe

Points to an array of PALETTEENTRY structures to receive the palette entries. The array must contain at least as many structures as specified by the nEntries parameter. If this parameter is NULL, the function returns the total number of entries in the palette.

Return Value

If the function succeeds, the return value is the number of entries retrieved from the palette.

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

Remarks

An application can determine whether a device supports palette operations by calling the GetDeviceCaps function and specifying the RASTERCAPS constant.

See Also

GetDeviceCaps, GetPaletteEntries, PALETTEENTRY


GetSystemPaletteUse
 GetSystemPaletteUse  QuickInfo  Overview  Group

The GetSystemPaletteUse function retrieves the current state of the system (physical) palette for the specified device context.

UINT GetSystemPaletteUse(

HDC  hdc	// handle of device context
);
Parameters

hdc

Identifies the device context.

Return Value

If the function succeeds, the return value is the current state of the system palette. It can be any of the following values:

Value	Meaning
SYSPAL_NOSTATIC	The system palette contains no static colors except black and white.
SYSPAL_STATIC	The system palette contains static colors that will not change when an application realizes its logical palette.
SYSPAL_ERROR	The given device context is invalid or does not support a color palette.
To get extended error information, call GetLastError.

Remarks

By default, the system palette contains 20 static colors that are not changed when an application realizes its logical palette. An application can gain access to most of these colors by calling the SetSystemPaletteUse function.

The device context identified by the hdc parameter must represent a device that supports color palettes.

An application can determine whether or not a device supports color palettes by calling the GetDeviceCaps function and specifying the RASTERCAPS constant.

See Also

GetDeviceCaps, SetSystemPaletteUse


GetSystemPowerStatus [New - Windows 95]
 GetSystemPowerStatus  QuickInfo  Overview  Group

[New - Windows 95]

The GetSystemPowerStatus function retrieves the power status of the system. The status indicates whether the system is running on AC or DC power, whether the battery is currently charging, and how much battery life currently remains.

BOOL GetSystemPowerStatus(

LPSYSTEM_POWER_STATUS  lpSystemPowerStatus
);
Parameters

lpSystemPowerStatus

Pointer to a SYSTEM_POWER_STATUS structure that receives status information.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

See Also

SYSTEM_POWER_STATUS


GetSystemTime
 GetSystemTime  QuickInfo  Overview  Group

The GetSystemTime function retrieves the current system date and time. The system time is expressed in Coordinated Universal Time (UTC).

VOID GetSystemTime(

LPSYSTEMTIME  lpSystemTime	// address of system time structure
);
Parameters

lpSystemTime

Points to a SYSTEMTIME structure to receive the current system date and time.

Return Value

This function does not return a value.

Remarks

Windows 95: Early beta implementations of this function return local time rather than UTC.

See Also

GetLocalTime, GetSystemTimeAdjustment, SetSystemTime, SYSTEMTIME


GetSystemTimeAdjustment
 GetSystemTimeAdjustment  QuickInfo  Overview  Group

The GetSystemTimeAdjustment function determines whether the system is applying periodic time adjustments to its time-of-day clock at each clock interrupt, along with the value and period of any such adjustments. Note that the period of such adjustments is equivalent to the time period between clock interrupts.

BOOL GetSystemTimeAdjustment(

PDWORD  lpTimeAdjustment,	// size, in 100-nanosecond units, of a periodic time adjustment
PDWORD  lpTimeIncrement,	// time, in 100-nanosecond units, between periodic time adjustments
PBOOL  lpTimeAdjustmentDisabled	// whether periodic time adjustment is disabled or enabled
);
Parameters

lpTimeAdjustment

Pointer to a DWORD that the function sets to the number of 100-nanosecond units added to the time-of-day clock at each periodic time adjustment.

lpTimeIncrement

Pointer to a DWORD that the function sets to the interval, counted in 100-nanosecond units, between periodic time adjustments. This interval is the time period between a system's clock interrupts.

lpTimeAdjustmentDisabled

Pointer to a BOOL that the function sets to indicate whether periodic time adjustment is in effect.

A value of TRUE indicates that periodic time adjustment is disabled. At each clock interrupt, the system merely adds the interval between clock interrupts to the time-of-day clock. The system is free, however, to adjust its time-of-day clock using other techniques. Such other techniques may cause the time-of-day clock to noticeably jump when adjustments are made.

A value of FALSE indicates that periodic time adjustment is being used to adjust the time-of-day clock. At each clock interrupt, the system adds the time increment specified by SetSystemTimeAdjustment's dwTimeIncrement parameter to the time-of-day clock. The system will not interfere with the time adjustment scheme, and will not attempt to synchronize time of day on its own via other techniques.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The GetSystemTimeAdjustment and SetSystemTimeAdjustment functions support algorithms that want to synchronize the time-of-day clock, reported by GetSystemTime and GetLocalTime, with another time source using a periodic time adjustment applied at each clock interrupt.

When periodic time adjustment is in effect, the system adds an adjusting value to the time-of-day clock at a periodic interval, at each clock interrupt. The GetSystemTimeAdjustment function lets a caller determine whether periodic time adjustment is enabled, and if it is, obtain the amount of each adjustment and the time between adjustments. The SetSystemTimeAdjustment function lets a caller enable or disable periodic time adjustment, and set the value of the adjusting increment.

See Also

SetSystemTimeAdjustment, GetSystemTime, GetLocalTime


GetSystemTimeAsFileTime
 GetSystemTimeAsFileTime  QuickInfo  Overview  Group

The GetSystemTimeAsFileTime function obtains the current system date and time. The information is in Coordinated Universal Time (UTC) format.

VOID GetSystemTimeAsFileTime(

LPFILETIME  lpSystemTimeAsFileTime	// pointer to a file time structure
);
Parameters

lpSystemTimeAsFileTime

Pointer to a FILETIME structure to receive the current system date and time in UTC format.

Return Value

This function does not return a value.

Remarks

The GetSystemTimeAsFileTime function is equivalent to the following code sequence:

FILETIME ft;

SYSTEMTIME st;

GetSystemTime(&st);

SystemTimeToFileTime(&st,&ft);

Windows 95: The GetSystemTimeAsFileTime function is not available on the Windows 95 platform. If you need its functionality, use the preceding code sequence.

See Also

FILETIME, GetSystemTime, SYSTEMTIME, SystemTimeToFileTime


GetTabbedTextExtent
 GetTabbedTextExtent  QuickInfo  Overview  Group

The GetTabbedTextExtent function computes the width and height of a character string. If the string contains one or more tab characters, the width of the string is based upon the specified tab stops. The GetTabbedTextExtent function uses the currently selected font to compute the dimensions of the string.

DWORD GetTabbedTextExtent(

HDC  hDC,	// handle of device context
LPCTSTR  lpString,	// address of character string
int  nCount,	// number of characters in string
int  nTabPositions,	// number of tab positions
LPINT  lpnTabStopPositions	// address of array of tab positions
);
Parameters

hDC

Identifies the device context.

lpString

Points to a character string.

nCount

Specifies the number of characters in the text string.

nTabPositions

Specifies the number of tab-stop positions in the array pointed to by the lpnTabStopPositions parameter.

lpnTabStopPositions

Points to an array containing the tab-stop positions, in device units. The tab stops must be sorted in increasing order; the smallest x-value should be the first item in the array.

Return Value

If the function succeeds, the return value is the dimensions of the string. The height is in the high-order word and the width is in the low-order word.

If the function fails, the return value is 0. GetTabbedTextExtent will fail if hDC is invalid and if nTabPositions is less than 0.

Remarks

The current clipping region does not affect the width and height returned by the GetTabbedTextExtent function.

Because some devices do not place characters in regular cell arrays (that is, they kern the characters), the sum of the extents of the characters in a string may not be equal to the extent of the string.

If the nTabPositions parameter is zero and the lpnTabStopPositions parameter is NULL, tabs are expanded to eight times the average character width.

If nTabPositions is 1, the tab stops are separated by the distance specified by the first value in the array to which lpnTabStopPositions points.

See Also

GetTextExtent, HIWORD, LOWORD, TabbedTextOut


GetTapeParameters
 GetTapeParameters  QuickInfo  Overview  Group

The GetTapeParameters function retrieves information that describes the tape or the tape drive.

DWORD GetTapeParameters(

HANDLE  hDevice,	// handle of open device
DWORD  dwOperation,	// type of information requested
LPDWORD  lpdwSize,	// address of returned information
LPVOID  lpTapeInformation	// tape media or drive information
);
Parameters

hDevice

Identifies the device about which information is sought. This handle is created by using the CreateFile function.

dwOperation

Specifies the type of information requested. This parameter must be one of the following values:

Value	Description
GET_TAPE_MEDIA_INFORMATION	Retrieves information about the tape in the tape device.
GET_TAPE_DRIVE_INFORMATION	Retrieves information about the tape device.
lpdwSize

Points to a variable that receives the size, in bytes, of the buffer specified by the lpTapeInformation parameter. If the buffer is too small, this parameter receives the required size.

lpTapeInformation

Points to a structure that contains the requested information. If the dwOperation parameter is GET_TAPE_MEDIA_INFORMATION, lpTapeInformation points to a TAPE_GET_MEDIA_PARAMETERS structure.

If dwOperation is GET_TAPE_DRIVE_INFORMATION, lpTapeInformation points to a TAPE_GET_DRIVE_PARAMETERS structure.

Return Value

If the function succeeds, the return value is NO_ERROR.

If the function fails, the return value is one of the following error codes:

Error code	Description
ERROR_BEGINNING_OF_MEDIA	An attempt to access data before the beginning-of-medium marker failed.
ERROR_BUS_RESET	A reset condition was detected on the bus.
ERROR_END_OF_MEDIA	The end-of-tape marker was reached during an operation.
ERROR_FILEMARK_DETECTED	A filemark was reached during an operation.
ERROR_SETMARK_DETECTED	A setmark was reached during an operation.
ERROR_NO_DATA_DETECTED	The end-of-data marker was reached during an operation.
ERROR_PARTITION_FAILURE	The tape could not be partitioned.
ERROR_INVALID_BLOCK_LENGTH	The block size is incorrect on a new tape in a multivolume partition.
ERROR_DEVICE_NOT_PARTITIONED	The partition information could not be found when a tape was being loaded.
ERROR_MEDIA_CHANGED	The tape that was in the drive has been replaced or removed.
ERROR_NO_MEDIA_IN_DRIVE	There is no media in the drive.
ERROR_NOT_SUPPORTED	The tape driver does not support a requested function.
ERROR_UNABLE_TO_LOCK_MEDIA	An attempt to lock the ejection mechanism failed.
ERROR_UNABLE_TO_UNLOAD_MEDIA	An attempt to unload the tape failed.
ERROR_WRITE_PROTECT	The media is write protected.
Remarks

The block size range values (maximum and minimum) returned by the GetTapeParameters function called with the dwOperation parameter set to the GET_TAPE_DRIVE_INFORMATION value will indicate system limits, not drive limits. However, it is the tape drive device and the media present in the drive that determine the true block size limits. Thus, an application may not be able to set all the block sizes mentioned in the range obtained by specifying GET_TAPE_DRIVE_INFORMATION in dwOperation.

See Also

CreateFile, SetTapeParameters, TAPE_GET_DRIVE_PARAMETERS, TAPE_GET_MEDIA_PARAMETERS


GetTapePosition
 GetTapePosition  QuickInfo  Overview  Group

The GetTapePosition function retrieves the current address of the tape, in logical or absolute blocks.

DWORD GetTapePosition(

HANDLE  hDevice,	// handle of open device
DWORD  dwPositionType,	// type of address to obtain
LPDWORD  lpdwPartition,	// address of current tape partition
LPDWORD  lpdwOffsetLow,	// address of low-order 32 bits of tape position
LPDWORD  lpdwOffsetHigh	// address of high-order 32 bits of tape position
);
Parameters

hDevice

Identifies the device on which to get the tape position. This handle is created by using CreateFile.

dwPositionType

Specifies the type of address to obtain. This parameter can be one of the following values:

Value	Description
TAPE_ABSOLUTE_POSITION	The lpdwOffsetLow and lpdwOffsetHigh parameters receive the device-specific block address. The dwPartition parameter receives zero.
TAPE_LOGICAL_POSITION	The lpdwOffsetLow and lpdwOffsetHigh parameters receive the logical block address. The dwPartition parameter receives the logical tape partition.
lpdwPartition

Points to a variable that receives the number of the current tape partition. Partitions are numbered logically from 1 through n, where 1 is the first partition on the tape and n is the last. When a device-specific block address is retrieved, or if the device supports only one partition, this parameter receives zero.

lpdwOffsetLow

Points to a variable that receives the low-order 32 bits of the current tape position.

lpdwOffsetHigh

Points to a variable that receives the high-order 32 bits of the current tape position. This parameter can be NULL if the high-order 32 bits are not required.

Return Value

If the function succeeds, the return value is NO_ERROR.

If the function fails, the return value is one of the following error codes:

Error code	Description
ERROR_BEGINNING_OF_MEDIA	An attempt to access data before the beginning-of-medium marker failed.
ERROR_BUS_RESET	A reset condition was detected on the bus.
ERROR_END_OF_MEDIA	The end-of-tape marker was reached during an operation.
ERROR_FILEMARK_DETECTED	A filemark was reached during an operation.
ERROR_SETMARK_DETECTED	A setmark was reached during an operation.
ERROR_NO_DATA_DETECTED	The end-of-data marker was reached during an operation.
ERROR_PARTITION_FAILURE	The tape could not be partitioned.
ERROR_INVALID_BLOCK_LENGTH	The block size is incorrect on a new tape in a multivolume partition.
ERROR_DEVICE_NOT_PARTITIONED	The partition information could not be found when a tape was being loaded.
ERROR_MEDIA_CHANGED	The tape that was in the drive has been replaced or removed.
ERROR_NO_MEDIA_IN_DRIVE	There is no media in the drive.
ERROR_NOT_SUPPORTED	The tape driver does not support a requested function.
ERROR_UNABLE_TO_LOCK_MEDIA	An attempt to lock the ejection mechanism failed.
ERROR_UNABLE_TO_UNLOAD_MEDIA	An attempt to unload the tape failed.
ERROR_WRITE_PROTECT	The media is write protected.
Remarks

A logical block address is relative to a partition. The first logical block address on each partition is zero.

Call the GetTapeParameters function to obtain information about the status, capabilities, and capacities of tape drives and media.

See Also

CreateFile, GetTapeParameters, SetTapePosition


GetTapeStatus
 GetTapeStatus  QuickInfo  Overview  Group

The GetTapeStatus function indicates whether the tape device is ready to process tape commands.

DWORD GetTapeStatus(

HANDLE  hDevice	// handle of open device
);
Parameters

hDevice

Identifies the device for which to get the device status. This handle is created by using the CreateFile function.

Return Value

If the tape device is ready to accept appropriate tape-access commands without returning errors, the return value is NO_ERROR.

If the function fails, the return value is one of the following error codes:

Error code	Description
ERROR_BEGINNING_OF_MEDIA	An attempt to access data before the beginning-of-medium marker failed.
ERROR_BUS_RESET	A reset condition was detected on the bus.
ERROR_END_OF_MEDIA	The end-of-tape marker was reached during an operation.
ERROR_FILEMARK_DETECTED	A filemark was reached during an operation.
ERROR_SETMARK_DETECTED	A setmark was reached during an operation.
ERROR_NO_DATA_DETECTED	The end-of-data marker was reached during an operation.
ERROR_PARTITION_FAILURE	The tape could not be partitioned.
ERROR_INVALID_BLOCK_LENGTH	The block size is incorrect on a new tape in a multivolume partition.
ERROR_DEVICE_NOT_PARTITIONED	The partition information could not be found when a tape was being loaded.
ERROR_MEDIA_CHANGED	The tape that was in the drive has been replaced or removed.
ERROR_NO_MEDIA_IN_DRIVE	There is no media in the drive.
ERROR_NOT_SUPPORTED	The tape driver does not support a requested function.
ERROR_UNABLE_TO_LOCK_MEDIA	An attempt to lock the ejection mechanism failed.
ERROR_UNABLE_TO_UNLOAD_MEDIA	An attempt to unload the tape failed.
ERROR_WRITE_PROTECT	The media is write protected.
See Also

CreateFile


GetTempDrive
 GetTempDrive  Overview  Group

The GetTempDrive function is not implemented in the Win32 API. Win32-based applications should use the GetTempPath function.


GetTempFileName
 GetTempFileName  QuickInfo  Overview  Group

The GetTempFileName function creates a name for a temporary file. The filename is the concatenation of specified path and prefix strings, a hexadecimal string formed from a specified integer, and the .TMP extension.

The specified integer can be nonzero, in which case, the function creates the filename but does not create the file. If you specify zero for the integer, the function creates a unique filename and creates the file in the specified directory.

UINT GetTempFileName(

LPCTSTR  lpPathName,	// address of directory name for temporary file
LPCTSTR  lpPrefixString,	// address of filename prefix
UINT  uUnique,	// number used to create temporary filename
LPTSTR  lpTempFileName	// address of buffer that receives the new filename
);
Parameters

lpPathName

Points to a null-terminated string that specifies the directory path for the filename. This string must consist of characters in the ANSI character set. Applications typically specify a period (.) or the result of the GetTempPath function for this parameter. If this parameter is NULL, the function fails.

lpPrefixString

Points to a null-terminated prefix string. The function uses the first three characters of this string as the prefix of the filename. This string must consist of characters in the ANSI character set.

uUnique

Specifies an unsigned integer that the function converts to a hexadecimal string for use in creating the temporary filename.

If uUnique is nonzero, the function appends the hexadecimal string to lpPrefixString to form the temporary filename. In this case, the function does not create the specified file, and does not test whether the filename is unique.

If uUnique is zero, the function uses a hexadecimal string derived from the current system time. In this case, the function uses different values until it finds a unique filename, and then it creates the file in the lpPathName directory.

lpTempFileName

Points to the buffer that receives the temporary filename. This null-terminated string consists of characters in the ANSI character set. This buffer should be at least the length, in bytes, specified by MAX_PATH to accommodate the path.

Return Value

If the function succeeds, the return value specifies the unique numeric value used in the temporary filename. If the uUnique parameter is nonzero, the return value specifies that same number.

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

Remarks

The GetTempFileName function creates a temporary filename of the following form:

     path\preuuuu.TMP

The following table describes the filename syntax:

Component	Meaning
path	Path specified by the lpPathName parameter
pre	First three letters of the lpPrefixString string
uuuu	Hexadecimal value of uUnique
When Windows shuts down, temporary files whose names have been created by this function are not automatically deleted.

To avoid problems resulting from converting an ANSI character set string to a Windows string, an application should call the CreateFile function to create a temporary file.

If the uUnique parameter is zero, GetTempFileName attempts to form a unique number based on the current system time. If a file with the resulting filename exists, the number is increased by one and the test for existence is repeated. Testing continues until a unique filename is found. GetTempFileName then creates a file by that name and closes it. When uUnique is nonzero, no attempt is made to create and open the file.

See Also

CreateFile, GetTempPath


GetTempPath
 GetTempPath  QuickInfo  Overview  Group

The GetTempPath function retrieves the path of the directory designated for temporary files. This function supersedes the GetTempDrive function.

DWORD GetTempPath(

DWORD  nBufferLength,	// size, in characters, of the buffer
LPTSTR  lpBuffer	// address of buffer for temp. path
);
Parameters

nBufferLength

Specifies the size, in characters, of the string buffer identified by lpBuffer.

lpBuffer

Points to a string buffer that receives the null-terminated string specifying the temporary file path.

Return Value

If the function succeeds, the return value is the length, in characters, of the string copied to lpBuffer, not including the terminating null character. If the return value is greater than nBufferLength, the return value is the size of the buffer required to hold the path.

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

Remarks

The GetTempPath function gets the temporary file path as follows:

1.	The path specified by the TMP environment variable.

2.	The path specified by the TEMP environment variable, if TMP is not defined.

3.	The current directory, if both TMP and TEMP are not defined.

See Also

GetTempFileName


GetTextAlign
 GetTextAlign  QuickInfo  Overview  Group

The GetTextAlign function retrieves the text-alignment setting for the specified device context.

UINT GetTextAlign(

HDC  hdc	// handle of device context
);
Parameters

hdc

Identifies the device context.

Return Value

If the function succeeds, the return value is the status of the text-alignment flags.

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

For a list of status return values, see the Remarks section. The return value is a combination of one or more of the following values:

Value	Meaning
TA_BASELINE	The reference point is on the base line of the text.
TA_BOTTOM	The reference point is on the bottom edge of the bounding rectangle.
TA_TOP	The reference point is on the top edge of the bounding rectangle.
TA_CENTER	The reference point is aligned horizontally with the center of the bounding rectangle.
TA_LEFT	The reference point is on the left edge of the bounding rectangle.
TA_RIGHT	The reference point is on the right edge of the bounding rectangle.
TA_RTLREADING	Windows 95 only: The text is laid out in right to left reading order, as opposed to the default left to right order. This only applies when the font selected into the device context is either Hebrew or Arabic.
TA_NOUPDATECP	The current position is not updated after each text output call.
TA_UPDATECP	The current position is updated after each text output call.
When the current font has a vertical default base line (as with Kanji), the following values are used instead of TA_BASELINE and TA_CENTER:

Value	Meaning
VTA_BASELINE	The reference point is on the base line of the text.
VTA_CENTER	The reference point is aligned vertically with the center of the bounding rectangle.
Remarks

The bounding rectangle is a rectangle bounding all of the character cells in a string of text. Its dimensions can be obtained by calling the GetTextExtent function.

The text-alignment flags determine how the TextOut and ExtTextOut functions align a string of text in relation to the string's reference point provided to TextOut or ExtTextOut.

The text-alignment flags are not necessarily single bit flags and may be equal to zero. The flags must be examined in groups of related flags, as shown in the following list:

TA_LEFT, TA_RIGHT, and TA_CENTER
TA_BOTTOM, TA_TOP, and TA_BASELINE
TA_NOUPDATECP and TA_UPDATECP

If the current font has a vertical default base line, the related flags are as shown in the following list:

TA_LEFT, TA_RIGHT, and VTA_BASELINE
TA_BOTTOM, TA_TOP, and VTA_CENTER
TA_NOUPDATECP and TA_UPDATECP

To verify that a particular flag is set in the return value of this function, the application must perform the following steps:

1.	Apply the bitwise OR operator to the flag and its related flags.

2.	Apply the bitwise AND operator to the result and the return value.

3.	Test for the equality of this result and the flag.

See Also

ExtTextOut, GetTextExtent, SetTextAlign, TextOut


GetTextCharacterExtra
 GetTextCharacterExtra  QuickInfo  Overview  Group

The GetTextCharacterExtra function retrieves the current intercharacter spacing for the specified device context.

int GetTextCharacterExtra(

HDC  hdc	// handle of device context
);
Parameters

hdc

Identifies the device context.

Return Value

If the function succeeds, the return value is the current intercharacter spacing.

If the function fails, the return value is 0x8000000.

Remarks

The intercharacter spacing defines the extra space, in logical units along the base line, that the TextOut or ExtTextOut functions add to each character as a line is written. The spacing is used to expand lines of text.

See Also

ExtTextOut, SetTextCharacterExtra, TextOut


GetTextCharsetInfo [New - Windows 95]
 GetTextCharsetInfo  QuickInfo

[New - Windows 95]

The GetTextCharsetInfo function retrieves information about the character set for the currently selected font.

UINT GetTextCharsetInfo(

HDC hdc,	// handle of device context
LPFONTSIGNATURE * lpSig,	// address of buffer for font-signature data
DWORD dwFlags	// reserved; must be zero
);
Parameters

hdc

Identifies the device context.

lpSig

Points to the buffer that receives the font signature block. The block includes both the Unicode and ANSI sections. This parameter can be NULL if the block is not required. If the font is not a TrueType font, the function sets the font signature to all zeros. In this case, use TranslateCharsetInfo to retrieve the generic signatures for character sets if required.

dwFlags

Reserved; must be zero.

Return Value

If the function succeeds, the return value is the character set of the currently selected font for the given device context.

If the function fails, the return value is DEFAULT_CHARSET.


GetTextColor
 GetTextColor  QuickInfo  Overview  Group

The GetTextColor function retrieves the current text color for the specified device context.

COLORREF GetTextColor(

HDC  hdc	// handle of device context
);
Parameters

hdc

Identifies the device context.

Return Value

If the function succeeds, the return value is the current text color as a COLORREF value.

If the function fails, the return value is CLR_INVALID.

Remarks

The text color defines the foreground color of characters drawn by using the TextOut or ExtTextOut function.

See Also

ExtTextOut, TextOut


GetTextExtent
 GetTextExtent  Overview  Group

The GetTextExtent function is not implemented in the Win32 API. This function is included for compatibility with 16-bit versions of Windows. Win32-based applications should use the GetTextExtentPoint32 function.


GetTextExtentExPoint
 GetTextExtentExPoint  QuickInfo  Overview  Group

The GetTextExtentExPoint function retrieves the number of characters in a specified string that will fit within a specified space and fills an array with the text extent for each of those characters. (A text extent is the distance between the beginning of the space and a character that will fit in the space.) This information is useful for word-wrapping calculations.

BOOL GetTextExtentExPoint(

HDC  hdc,	// handle of device context
LPCTSTR  lpszStr,	// address of character string
int  cchString,	// number of characters in string
int  nMaxExtent,	// maximum width for formatted string
LPINT  lpnFit,	// address of value specifying max. number of chars.
LPINT  alpDx,	// address of array for partial string widths
LPSIZE  lpSize	// address of structure with string dimensions
);
Parameters

hdc

Identifies the device context.

lpszStr

Points to the null-terminated string for which extents are to be retrieved.

cchString

Specifies the number of bytes in the string pointed to by the lpszStr parameter.

nMaxExtent

Specifies the maximum allowable width, in logical units, of the formatted string.

lpnFit

Points to an integer to receive a count of the maximum number of characters that will fit in the space specified by the nMaxExtent parameter. When the lpnFit parameter is NULL, the nMaxExtent parameter is ignored.

alpDx

Points to an array of integers to receive partial string extents. Each element in the array gives the distance, in logical units, between the beginning of the string and one of the characters that fits in the space specified by the nMaxExtent parameter. Although this array should have at least as many elements as characters specified by the cchString parameter, the function fills the array with extents only for as many characters as are given by the lpnFit parameter. If alpDx is NULL, the function does not compute partial string widths.

lpSize

Points to a SIZE structure that contains the dimensions of the string, in logical units when the function returns. This value cannot be NULL.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

If both the lpnFit and alpDx parameters are NULL, calling the GetTextExtentExPoint function is equivalent to calling the GetTextExtentPoint function.

See Also

GetTextExtentPoint, SIZE


GetTextExtentPoint
 GetTextExtentPoint  QuickInfo  Overview  Group

The GetTextExtentPoint function computes the width and height of the specified string of text.

GetTextExtentPoint is provided for compatibility with 16-bit versions of Windows. Win32-based applications should call the GetTextExtentPoint32 function, which provides more accurate results.

BOOL GetTextExtentPoint(

HDC  hdc,	// handle of device context
LPCTSTR  lpString,	// address of text string
int  cbString,	// number of characters in string
LPSIZE  lpSize	// address of structure for string size
);
Parameters

hdc

Identifies the device context.

lpString

Points to the string of text. The string does not need to be zero-terminated, since cbString specifies the length of the string.

cbString

Specifies the number of characters in the string.

lpSize

Points to a SIZE structure in which the dimensions of the string are to be returned.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The GetTextExtentPoint function uses the currently selected font to compute the dimensions of the string. The width and height, in logical units, are computed without considering any clipping.

Because some devices kern characters, the sum of the extents of the characters in a string may not be equal to the extent of the string.

The calculated string width takes into account the intercharacter spacing set by the SetTextCharacterExtra function.

See Also

GetTextExtentPoint32, SetTextCharacterExtra, SIZE


GetTextExtentPoint32
 GetTextExtentPoint32  QuickInfo  Overview  Group

The GetTextExtentPoint32 function computes the width and height of the specified string of text. This function supersedes the GetTextExtentPoint function.

BOOL GetTextExtentPoint32(

HDC  hdc,	// handle of device context
LPCTSTR  lpString,	// address of text string
int  cbString,	// number of characters in string
LPSIZE  lpSize	// address of structure for string size
);
Parameters

hdc

Identifies the device context.

lpString

Points to the string of text. The string does not need to be zero-terminated, since cbString specifies the length of the string.

cbString

Specifies the number of characters in the string.

lpSize

Points to a SIZE structure in which the dimensions of the string are to be returned.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The GetTextExtentPoint32 function uses the currently selected font to compute the dimensions of the string. The width and height, in logical units, are computed without considering any clipping.

Because some devices kern characters, the sum of the extents of the characters in a string may not be equal to the extent of the string.

The calculated string width takes into account the intercharacter spacing set by the SetTextCharacterExtra function.

See Also

GetTextExtentPoint, SetTextCharacterExtra, SIZE


GetTextFace
 GetTextFace  QuickInfo  Overview  Group

The GetTextFace function retrieves the typeface name of the font that is selected into the specified device context.

int GetTextFace(

HDC  hdc,	// handle of device context
int  nCount,	// length of buffer receiving typeface name
LPTSTR  lpFaceName	// address of buffer receiving typeface name
);
Parameters

hdc

Identifies the device context.

nCount

Specifies the size, in characters, of the buffer.

lpFaceName

Points to the buffer that is to receive the typeface name. If this parameter is NULL, the function returns the number of characters in the name, including the terminating null character.

Return Value

If the function succeeds, the return value is the number of characters copied to the buffer.

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

Remarks

The typeface name is copied as a null-terminated character string.

If the name is longer than the number of characters specified by the nCount parameter, the name is truncated.

See Also

GetTextAlign, GetTextColor, GetTextExtentPoint32, GetTextMetrics


GetTextMetrics
 GetTextMetrics  QuickInfo  Overview  Group

The GetTextMetrics function fills the specified buffer with the metrics for the currently selected font.

BOOL GetTextMetrics(

HDC  hdc,	// handle of device context
LPTEXTMETRIC  lptm	// address of text metrics structure
);
Parameters

hdc

Identifies the device context.

lptm

Points to the TEXTMETRIC structure that is to receive the metrics.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

GetTextAlign, GetTextExtent, GetTextFace, SetTextJustification, TEXTMETRIC


GetThreadContext
 GetThreadContext  QuickInfo  Overview  Group

The GetThreadContext function retrieves the context of the specified thread.

BOOL GetThreadContext(

HANDLE  hThread,	// handle of thread with context
LPCONTEXT  lpContext	// address of context structure
);
Parameters

hThread

Identifies an open handle of a thread whose context is to be retrieved. The handle must have THREAD_GET_CONTEXT access to the thread.

lpContext

Points to the address of a CONTEXT structure that receives the appropriate context of the specified thread. The value of the ContextFlags member of this structure specifies which portions of a thread's context are retrieved. The CONTEXT structure is highly computer specific; two versions of the structure currently exist, one version for x86 processors and another for MIPS processors.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

GetThreadContext is used to retrieve the context of the specified thread. The function allows a selective context to be retrieved based on the value of the ContextFlags member of the CONTEXT structure. The thread handle identified by the hThread parameter is typically being debugged, but the function can also operate when it is not being debugged.

See Also

CONTEXT, SetThreadContext


GetThreadDesktop
 GetThreadDesktop  QuickInfo  Overview  Group

The GetThreadDesktop function returns a handle to the desktop associated with a specified thread.

HDESK GetThreadDesktop(

DWORD  dwThreadId	// thread identifier
);
Parameters

dwThreadId

Identifies the thread for which to return the desktop handle. The GetCurrentThreadId and CreateProcess functions return thread identifiers.

Return Value

If the function succeeds, the return value is the handle of the desktop associated with the specified thread.

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: Windows 95 does not support multiple desktops, so GetThreadDesktop always returns the same value.

See Also

GetCurrentThreadId, GetProcessWindowStation, GetUserObjectInformation, GetUserObjectSecurity, SetProcessWindowStation, SetThreadDesktop, SetUserObjectInformation, SetUserObjectSecurity


GetThreadLocale
 GetThreadLocale  QuickInfo  Overview  Group

The GetThreadLocale function returns the calling thread's current locale.

LCID GetThreadLocale(VOID)

Parameters

This function has no parameters.

Return Value

The function returns the calling thread's 32-bit LCID locale identifier.

Remarks

When a thread is created, it is given the system default thread locale. The system reads the system default thread locale from the registry when the system boots. This system default can be modified for future process and thread creation using Control Panel's International application.

See Also

SetThreadLocale, GetSystemDefaultLCID, GetUserDefaultLCID


GetThreadPriority
 GetThreadPriority  QuickInfo  Overview  Group

The GetThreadPriority function returns the priority value for the specified thread. This value, together with the priority class of the thread's process, determines the thread's base-priority level.

int GetThreadPriority(

HANDLE  hThread	// handle to thread
);
Parameters

hThread

Identifies the thread. The handle must have THREAD_QUERY_INFORMATION access.

Return Value

If the function succeeds, the return value is the thread's priority level.

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

The thread's priority level is one of the following values:

Priority	Meaning
THREAD_PRIORITY_ABOVE_NORMAL
	Indicates 1 point above normal priority for the priority class.
THREAD_PRIORITY_BELOW_NORMAL
	Indicates 1 point below normal priority for the priority class.
THREAD_PRIORITY_HIGHEST
	Indicates 2 points above normal priority for the priority class.
THREAD_PRIORITY_IDLE
	Indicates a base-priority level of 1 for IDLE_PRIORITY_CLASS, NORMAL_PRIORITY_CLASS, or HIGH_PRIORITY_CLASS processes, and a base-priority level of 16 for REALTIME_PRIORITY_CLASS processes.
THREAD_PRIORITY_LOWEST
	Indicates 2 points below normal priority for the priority class.
THREAD_PRIORITY_NORMAL
	Indicates normal priority for the priority class.
THREAD_PRIORITY_TIME_CRITICAL
	Indicates a base-priority level of 15 for IDLE_PRIORITY_CLASS, NORMAL_PRIORITY_CLASS, or HIGH_PRIORITY_CLASS processes, and a base-priority level of 31 for REALTIME_PRIORITY_CLASS processes.
Remarks

Every thread has a base-priority level determined by the thread's priority value and the priority class of its process. The operating system uses the base-priority level of all executable threads to determine which thread gets the next slice of CPU time. Threads are scheduled in a round-robin fashion at each priority level, and only when there are no executable threads at a higher level will scheduling of threads at a lower level take place.

For a table that shows the base-priority levels for each combination of priority class and thread priority value, refer to the SetPriorityClass function.

See Also

GetPriorityClass, SetPriorityClass, SetThreadPriority


GetThreadSelectorEntry
 GetThreadSelectorEntry  QuickInfo  Overview  Group

The GetThreadSelectorEntry function retrieves a descriptor table entry for the specified selector and thread.

BOOL GetThreadSelectorEntry(

HANDLE  hThread,	// handle of thread that contains selector
DWORD  dwSelector,	// number of selector value to look up
LPLDT_ENTRY  lpSelectorEntry	// address of selector entry structure
);
Parameters

hThread

Identifies a handle of the thread containing the specified selector. The handle must have THREAD_QUERY_INFORMATION access.

dwSelector

Specifies the global or local selector value to look up in the thread's descriptor tables.

lpSelectorEntry

Points to a structure that receives a copy of the descriptor table entry if the specified selector has an entry in the specified thread's descriptor table. This information can be used to convert a segment-relative address to a linear virtual address.

Return Value

If the function succeeds, the return value is TRUE. In that case, the structure pointed to by the lpSelectorEntry parameter receives a copy of the specified descriptor table entry.

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

Remarks

GetThreadSelectorEntry is only functional on x86-based systems. For systems that are not x86-based, the function returns FALSE.

Debuggers use this function to convert segment-relative addresses to linear virtual addresses. The ReadProcessMemory and WriteProcessMemory functions use linear virtual addresses.

See Also

ReadProcessMemory, WriteProcessMemory


GetThreadTimes
 GetThreadTimes  QuickInfo  Overview  Group

The GetThreadTimes function obtains timing information about a specified thread.

BOOL GetThreadTimes(

HANDLE  hThread,	// specifies the thread of interest
LPFILETIME  lpCreationTime,	// when the thread was created
LPFILETIME  lpExitTime,	// when the thread was destroyed
LPFILETIME  lpKernelTime,	// time the thread has spent in kernel mode
LPFILETIME  lpUserTime	// time the thread has spent in user mode
);
Parameters

hThread

An open handle that specifies the thread whose timing information is sought. This handle must be created with THREAD_QUERY_INFORMATION access.

lpCreationTime

Points to a FILETIME structure that receives the creation time of the thread.

lpExitTime

Points to a FILETIME structure that receives the exit time of the thread. If the thread has not exited, the content of this structure is undefined.

lpKernelTime

Points to a FILETIME structure that receives the amount of time that the thread has executed in kernel mode.

lpUserTime

Points to a FILETIME structure that receives the amount of time that the thread has executed in user mode.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

All times are expressed using FILETIME data structures. Such a structure contains two 32-bit values that combine to form a 64-bit count of 100-nanosecond time units.

Thread creation and exit times are points in time expressed as the amount of time that has elapsed since midnight on January 1, 1601 at Greenwich, England. The Win32 API provides several functions that an application can use to convert such values to more generally useful forms; see Time and Date Functions, and the functions noted in the following See Also section.

Thread kernel mode and user mode times are amounts of time. For example, if a thread has spent one second in kernel mode, this function will fill the FILETIME structure specified by lpKernelTime with a 64-bit value of ten million. That is the number of 100-nanosecond units in one second.

See Also

FILETIME, FileTimeToDosDateTime, FileTimeToLocalFileTime, FileTimeToSystemTime


 GetThresholdEvent

The GetThresholdEvent function is not implemented in the Win32 API.

See Also

Beep, MessageBeep


 GetThresholdStatus

The GetThresholdStatus function is not implemented in the Win32 API.

See Also

Beep, MessageBeep


GetTickCount
 GetTickCount  QuickInfo  Overview  Group

The GetTickCount function retrieves the number of milliseconds that have elapsed since Windows was started.

DWORD GetTickCount(VOID)

Parameters

This function has no parameters.

Return Value

If the function succeeds, the return value is the number of milliseconds that have elapsed since Windows was started.

Remarks

The GetTickCount function is identical to the GetCurrentTime function. Applications should use the GetTickCount function because its name matches more closely what the function does.

The GetTickCount and GetMessageTime functions return different times. GetMessageTime returns the Windows time when the given message was created, not the current Windows time.

The internal timer wraps around to zero if Windows is run continuously for approximately 49.7 days.

See Also

GetCurrentTime, GetMessageTime, GetSystemTime, SetSystemTime


GetTimeFormat
 GetTimeFormat  QuickInfo  Overview  Group

The GetTimeFormat function formats a time as a time string for a specified locale. The function formats either a specified time or the local system time.

int GetTimeFormat(

LCID  Locale,	// locale for which time is to be formatted
DWORD  dwFlags,	// flags specifying function options
CONST SYSTEMTIME *  lpTime,	// time to be formatted
LPCTSTR  lpFormat,	// time format string
LPTSTR  lpTimeStr,	// buffer for storing formatted string
int  cchTime	// size, in bytes or characters, of the buffer
);
Parameters

Locale

Specifies the locale for which the time string is to be formatted. If lpFormat is NULL, the function formats the string according to the time format for this locale. If lpFormat is not NULL, the function uses the locale only for information not specified in the format picture string (for example, the locale's time markers).

This parameter can be a locale identifier created by the MAKELCID macro, or one of the following predefined values:

LOCALE_SYSTEM_DEFAULT	Default system locale.
LOCALE_USER_DEFAULT	Default user locale.
dwFlags

A set of bit flags that specify various function options. You can specify a combination of the following flags:

Flag	Meaning
LOCALE_NOUSEROVERRIDE	If set, the function formats the string using the system default time format for the specified locale. If not set, the function formats the string using any user overrides to the locale's default time format. This flag cannot be set if lpFormat is non-NULL.
TIME_NOMINUTESORSECONDS	Do not use minutes or seconds.
TIME_NOSECONDS	Do not use seconds.
TIME_NOTIMEMARKER	Do not use a time marker.
TIME_FORCE24HOURFORMAT	Always use a 24-hour time format.
lpTime

Pointer to a SYSTEMTIME structure that contains the time information to be formatted. If this pointer is NULL, the function uses the current local system time.

lpFormat

Pointer to a format picture to use to form the time string. If lpFormat is NULL, the function uses the time format of the specified locale.

Use the following elements to construct a format picture string. If you use spaces to separate the elements in the format string, these spaces will appear in the same location in the output string. The letters must be in uppercase or lowercase as shown (for example, "ss", not "SS"). Characters in the format string that are enclosed in single quotation marks will appear in the same location and unchanged in the output string.

Picture	Meaning
h	Hours with no leading zero for single-digit hours; 12-hour clock
hh	Hours with leading zero for single-digit hours; 12-hour clock
H	Hours with no leading zero for single-digit hours; 24-hour clock
HH	Hours with leading zero for single-digit hours; 24-hour clock
m	Minutes with no leading zero for single-digit minutes
mm	Minutes with leading zero for single-digit minutes
s	Seconds with no leading zero for single-digit seconds
ss	Seconds with leading zero for single-digit seconds
t	One character time marker string, such as A or P
tt	Multicharacter time marker string, such as AM or PM
For example, to get the time string

"11:29:40 PM"

use the following picture string:

"hh':'mm':'ss tt"

lpTimeStr

Pointer to a buffer that receives the formatted time string.

cchTime

Specifies the size, in bytes (ANSI version) or characters (Unicode version), of the lpTimeStr buffer. If cchTime is zero, the function returns the number of bytes or characters required to hold the formatted time string, and the buffer pointed to by lpTimeStr is not used.

Return Value

If the function succeeds, the return value is the number of bytes (ANSI version) or characters (Unicode version) written to the buffer pointed to by lpTimeStr. If the cchTime parameter is zero, the return value is the number of bytes or characters required to hold the formatted time string.

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

If a time marker exists and the TIME_NOTIMEMARKER flag is not set, the function localizes the time marker based on the specified locale identifier. Examples of time markers are "AM" and "PM" for US English.

The time values in the SYSTEMTIME structure pointed to by lpTime must be valid. The function checks each of the time values to determine that it is within the appropriate range of values. If any of the time values are outside the correct range, the function fails, and sets the last-error to ERROR_INVALID_PARAMETER.

The function ignores the date portions of the SYSTEMTIME structure pointed to by lpTime: wYear, wMonth, wDayOfWeek, and wDay.

If TIME_NOMINUTESORSECONDS or TIME_NOSECONDS is specified, the function removes the separator(s) preceding the minutes and/or seconds element(s).

If TIME_NOTIMEMARKER is specified, the function removes the separator(s) preceding and following the time marker.

If TIME_FORCE24HOURFORMAT is specified, the function displays any existing time marker, unless the TIME_NOTIMEMARKER flag is also set.

The function does not include milliseconds as part of the formatted time string.

To use the LOCALE_NOUSEROVERRIDE flag, lpFormat must be NULL.

No errors are returned for a bad format string. The function simply forms the best time string that it can. If more than two hour, minute, second, or time marker format pictures are passed in, then the function defaults to two. For example, the only time marker pictures that are valid are L"t" and L"tt" (the 'L' indicates a Unicode (16-bit characters) string). If L"ttt" is passed in, the function assumes L"tt".

See Also

GetDateFormat, SYSTEMTIME


GetTimeZoneInformation
 GetTimeZoneInformation  QuickInfo  Overview  Group

The GetTimeZoneInformation function retrieves the current time-zone parameters. These parameters control the translations between Coordinated Universal Time (UTC) and local time.

DWORD GetTimeZoneInformation(

LPTIME_ZONE_INFORMATION  lpTimeZoneInformation	// address of time-zone settings
);
Parameters

lpTimeZoneInformation

Points to a TIME_ZONE_INFORMATION structure to receive the current time-zone parameters.

Return Value

If the function succeeds, the return value is one of the following values:

Value	Meaning
TIME_ZONE_ID_UNKNOWN	The operating system cannot determine the current time zone. This is usually because a previous call to the SetTimeZoneInformation function supplied only the bias (and no transition dates).
TIME_ZONE_ID_STANDARD	The operating system is operating in the range covered by the StandardDate member of the structure pointed to by the lpTimeZoneInformation parameter.
TIME_ZONE_ID_DAYLIGHT	The operating system is operating in the range covered by the DaylightDate member of the structure pointed to by the lpTimeZoneInformation parameter.
If the function fails, the return value is 0xFFFFFFFF. To get extended error information, call GetLastError.

Remarks

All translations between UTC time and local time are based on the following formula:

UTC = local time + bias

The bias is the difference, in minutes, between UTC time and local time.

See Also

SetTimeZoneInformation, TIME_ZONE_INFORMATION


GetTokenInformation
 GetTokenInformation  QuickInfo  Overview  Group

The GetTokenInformation function retrieves a specified type of information about an access token. The calling process must have appropriate access rights to obtain the information.

BOOL GetTokenInformation(

HANDLE  TokenHandle,	// handle of access token
TOKEN_INFORMATION_CLASS  TokenInformationClass,	// type of information to retrieve
LPVOID  TokenInformation,	// address of retrieved information
DWORD  TokenInformationLength,	// size of information buffer
PDWORD  ReturnLength	// address of required buffer size
);
Parameters

TokenHandle

Identifies an access token from which information is retrieved.

TokenInformationClass

Specifies a variable of the TOKEN_INFORMATION_CLASS enumerated type identifying the type of information the function retrieves.

TokenInformation

Points to a buffer the function fills with the requested information. The structure put into this buffer depends upon the type of information specified by the TokenInformationClass parameter, as shown in the following list:

Token Information Class	Structure Returned
TokenUser	TOKEN_USER structure. TOKEN_QUERY access is needed to retrieve this information.
TokenGroups	TOKEN_GROUPS structure. TOKEN_QUERY access is needed to retrieve this information.
TokenPrivileges	TOKEN_PRIVILEGES structure. TOKEN_QUERY access is needed to retrieve this information.
TokenOwner	TOKEN_OWNER structure. TOKEN_QUERY access is needed to retrieve this information.
TokenPrimaryGroup	TOKEN_PRIMARY_GROUP structure. TOKEN_QUERY access is needed to retrieve this information.
TokenDefaultDacl	TOKEN_DEFAULT_DACL structure. TOKEN_QUERY access is needed to retrieve this information.
TokenSource	TOKEN_SOURCE structure. TOKEN_QUERY_SOURCE access is needed to retrieve this information.
TokenType	TOKEN_TYPE enumerated type. TOKEN_QUERY access is needed to retrieve this information.
TokenImpersonationLevel	SECURITY_IMPERSONATION_LEVEL enumerated type. TOKEN_QUERY access is needed to retrieve this information about a token. If the access token is not an impersonation token, the function fails.
TokenStatistics	TOKEN_STATISTICS structure. TOKEN_QUERY access is needed to retrieve this information.
The formats for the retrieved structures and enumerated types are listed in the following Remarks section.

TokenInformationLength

Specifies the size, in bytes, of the buffer pointed to by the TokenInformation parameter.

ReturnLength

Points to a variable receiving the actual number of bytes needed for the buffer pointed to by the TokenInformation parameter. If this value is larger than the value specified in the TokenInformationLength parameter, the function fails and stores no data in the buffer.

If the value of the TokenInformationClass parameter is TokenDefaultDacl and the token has no default access-control list, the function sets the variable pointed to by ReturnLength to zero and stores no data in the buffer.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

AdjustTokenGroups, AdjustTokenPrivileges, OpenProcessToken, OpenThreadToken, SetTokenInformation, SECURITY_IMPERSONATION_LEVEL, TOKEN_DEFAULT_DACL, TOKEN_GROUPS, TOKEN_INFORMATION_CLASS, TOKEN_OWNER, TOKEN_PRIMARY_GROUP, TOKEN_PRIVILEGES, TOKEN_SOURCE, TOKEN_STATISTICS, TOKEN_TYPE, TOKEN_USER


GetTopWindow
 GetTopWindow  QuickInfo  Overview  Group

The GetTopWindow function examines the Z order of the child windows associated with the specified parent window and retrieves the handle of the child window at the top of the Z order.

HWND GetTopWindow(

HWND  hWnd	// handle of parent window
);
Parameters

hWnd

Identifies the parent window whose child windows are to be examined. If this parameter is NULL, the function returns a handle of the window at the top of the Z order.

Return Value

If the function succeeds, the return value is the handle of 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.

See Also

GetNextWindow, GetWindow


GetTypeByName
 GetTypeByName  QuickInfo  Overview  Group

The GetTypeByName function obtains a service type GUID for a network service specified by name.

INT GetTypeByName(

LPTSTR  lpServiceName,	// points to the name of the network service
PGUID  lpServiceType	// points to a variable to receive network service type
);
Parameters

lpServiceName

Points to a zero-terminated string that uniquely represents the name of the service. For example, "MY SNA SERVER".

lpServiceType

Points to a variable to receive a globally unique identifier (GUID) that specifies the type of the network service. The header file SVCGUID.H includes definitions of several GUID service types and macros for working with them.

Return Value

If the function succeeds, the return value is zero.

If the function fails, the return value is SOCKET_ERROR( − 1). To get extended error information, call GetLastError. GetLastError may return the following extended error value:

Value	Meaning
ERROR_SERVICE_DOES_NOT_EXIST	The specified service type is unknown.
See Also

GetNameByType


GetUpdateRect
 GetUpdateRect  QuickInfo  Overview  Group

The GetUpdateRect function retrieves the coordinates of the smallest rectangle that completely encloses the update region of the specified window. If the window was created with the CS_OWNDC style and the mapping mode is not MM_TEXT, GetUpdateRect retrieves the rectangle in logical coordinates. Otherwise, it retrieves the rectangle in client coordinates. If there is no update region, GetUpdateRect retrieves an empty rectangle (sets all coordinates to zero).

BOOL GetUpdateRect(

HWND  hWnd,	// handle of window
LPRECT  lpRect,	// address of update rectangle coordinates
BOOL  bErase	// erase flag
);
Parameters

hWnd

Identifies the window with an update region that is to be retrieved.

lpRect

Points to the RECT structure that receives the coordinates of the enclosing rectangle.

An application can set this parameter to NULL to determine whether an update region exists for the window. If this parameter is NULL, GetUpdateRect returns nonzero if an update region exists, and zero if one does not. This provides a simple and efficient means of determining whether a WM_PAINT message resulted from an invalid area.

bErase

Specifies whether the background in the update region is to be erased. If this parameter is TRUE and the update region is not empty, GetUpdateRect sends a WM_ERASEBKGND message to the specified window to erase the background.

Return Value

If the update region is not empty, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

The update rectangle retrieved by the BeginPaint function is identical to that retrieved by GetUpdateRect.

BeginPaint automatically validates the update region, so any call to GetUpdateRect made immediately after the call to BeginPaint retrieves an empty update region.

See Also

BeginPaint, GetUpdateRgn, InvalidateRect, RECT, UpdateWindow, ValidateRect


GetUpdateRgn
 GetUpdateRgn  QuickInfo  Overview  Group

The GetUpdateRgn function retrieves the update region of a window by copying it into the specified region. The coordinates of the update region are relative to the upper-left corner of the window (that is, they are client coordinates).

int GetUpdateRgn(

HWND  hWnd,	// handle of window
HRGN  hRgn,	// handle of region
BOOL  bErase	// erase background flag
);
Parameters

hWnd

Identifies the window with an update region that is to be retrieved.

hRgn

Identifies the region to receive the update region.

bErase

Specifies whether the window background should be erased and whether nonclient areas of child windows should be drawn. If this parameter is FALSE, no drawing is done.

Return Value

The return value indicates the complexity of the resulting region; it can be one of the following values:

Value	Meaning
COMPLEXREGION	Region consists of more than one rectangle.
ERROR	An error occurred.
NULLREGION	Region is empty.
SIMPLEREGION	Region is a single rectangle.
Remarks

The BeginPaint function automatically validates the update region, so any call to GetUpdateRgn made immediately after the call to BeginPaint retrieves an empty update region.

See Also

GetUpdateRect, InvalidateRgn, UpdateWindow, ValidateRgn


GetUserDefaultLangID
 GetUserDefaultLangID  QuickInfo  Overview  Group

The GetUserDefaultLangID function retrieves the user default language identifier.

LANGID GetUserDefaultLangID(VOID)

Parameters

This function has no parameters.

Return Value

If the function succeeds, the return value is the user default language identifier.

See Also

GetSystemDefaultLangID, MAKELANGID


GetUserDefaultLCID
 GetUserDefaultLCID  QuickInfo  Overview  Group

The GetUserDefaultLCID function retrieves the user default locale identifier.

LCID GetUserDefaultLCID(VOID)

Parameters

This function has no parameters.

Return Value

If the function succeeds, the return value is the user default locale identifier.

Remarks

For more information about locale identifiers, see Locale Identifiers.

See Also

GetLocaleInfo, GetSystemDefaultLCID, MAKELCID


GetUserName
 GetUserName  QuickInfo  Overview  Group

The GetUserName function retrieves the user name of the current thread. This is the name of the user currently logged onto the system.

BOOL GetUserName(

LPTSTR  lpBuffer,	// address of name buffer
LPDWORD  nSize	// address of size of name buffer
);
Parameters

lpBuffer

Points to the buffer to receive the null-terminated string containing the user's logon name. If this buffer is not large enough to contain the entire user name, the function fails.

nSize

Pointer to a DWORD that, on input, specifies the maximum size, in characters, of the buffer specified by the lpBuffer parameter. If this buffer is not large enough to contain the entire user name, the function fails. If the function succeeds, it will place the number of characters copied to the buffer into the DWORD that nSize points to.

Return Value

If the function succeeds, the return value is TRUE, and the variable pointed to by nSize contains the number of characters copied to the buffer specified by lpBuffer, including the terminating null character.

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

Remarks

If the current thread is impersonating another client, the GetUserName function returns the user name of the client that the thread is impersonating.

See Also

LookupAccountName


GetUserObjectInformation [New - Windows NT]
 GetUserObjectInformation  QuickInfo  Overview  Group

[New - Windows NT]

The GetUserObjectInformation function returns information about a window station or desktop object.

BOOL GetUserObjectInformation(

HANDLE hObj	// handle of object to get information for
int nIndex	// type of information to get
PVOID pvInfo	// points to buffer that receives the information
DWORD nLength	// size, in bytes, of pvInfo buffer
LPDWORD lpnLengthNeeded	// receives required size, in bytes, of pvInfo buffer
);
Parameters

hObj

Identifies the window station or desktop object for which to return information. This can be an HDESK or HWINSTA handle (for example, a handle returned by CreateWindowStation, OpenWindowStation, CreateDesktop, or OpenDesktop).

nIndex

Specifies the object information to be retrieved. The parameter must 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.
pvInfo

Points to a buffer to receive the object information.

nLength

Specifies the size, in bytes, of the buffer pointed to by the pvInfo parameter.

lpnLengthNeeded

Points 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 Value

If the function succeeds, the return value is TRUE.

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

See Also

CreateDesktop, CreateWindowStation, GetUserObjectSecurity, OpenDesktop, OpenWindowStation, SetUserObjectInformation, SetUserObjectSecurity, USEROBJECTFLAGS


GetUserObjectSecurity
 GetUserObjectSecurity  QuickInfo  Overview  Group

The GetUserObjectSecurity function retrieves security information for the specified user object.

BOOL GetUserObjectSecurity(

HANDLE  hObj,	// handle of user object
PSECURITY_INFORMATION  pSIRequested,	// address of requested security information
PSECURITY_DESCRIPTOR  pSID,	// address of security descriptor
DWORD  nLength,	// size of buffer for security descriptor
LPDWORD  lpnLengthNeeded	// address of required size of buffer
);
Parameters

hObj

Identifies the user object for which to return security information.

pSIRequested

Points to a SECURITY_INFORMATION structure specifying the security information being requested.

pSID

Points to a SECURITY_DESCRIPTOR structure in self-relative format that contains the requested information when the function returns.

nLength

Specifies the length, in bytes, of the buffer pointed to by the pSID parameter.

lpnLengthNeeded

Points to a variable receiving the number of bytes required to store the complete security descriptor. 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 security descriptor is copied to the buffer. Otherwise, the entire security descriptor is copied.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

CreatePrivateObjectSecurity, GetKernelObjectSecurity, GetPrivateObjectSecurity, SECURITY_DESCRIPTOR, SECURITY_INFORMATION, SetUserObjectSecurity


GetVersion
 GetVersion  QuickInfo  Overview  Group

The GetVersion function returns the current version number of Windows and information about the operating system platform. This function has been superseded by GetVersionEx, which is the preferred method for obtaining system version number information. New applications should use GetVersionEx. The GetVersionEx function was developed because many existing Windows applications err when examining the DWORD return value of a GetVersion function call, transposing the major and minor version numbers packed into that DWORD. The GetVersionEx function forces applications to explicitly examine each element of version information, and allows for future enhancements to that information.

DWORD GetVersion(VOID)

Parameters

This function has no parameters.

Return Value

If the function succeeds, the return value is the major and minor version numbers of Windows and a code specifying the operating system platform. The low-order word contains the version number of Windows. The high-order byte specifies the minor version (revision) number, in hexadecimal notation. The low-order byte specifies the major version number, in hexadecimal notation.

The high-order word contains the information about the operating system platform. The high bit specifies the platform, as follows:

Value	Platform
0	Microsoft Windows NT
1	Microsoft Win32s with Windows 3.1
The remaining bits in the high word are reserved.

Remarks

This function does not return the current version number of MS-DOS.

See Also

GetVersionEx


GetVersionEx
 GetVersionEx  QuickInfo  Overview  Group

The GetVersionEx function obtains extended information about the version of the operating system that is currently running.

BOOL GetVersionEx(

LPOSVERSIONINFO  lpVersionInformation	// points to version information structure
);
Parameters

lpVersionInformation

Points to an OSVERSIONINFO data structure that the function fills with operating system version information.

Before calling the GetVersionEx function, set the dwOSVersionInfoSize member of the OSVERSIONINFO data structure to sizeof(OSVERSIONINFO).

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

The function fails if the value of the dwOSVersionInfoSize member of the passed OSVERSIONINFO structure is too small. A value that is too small indicates that the data structure is not large enough to contain the current version information.

Remarks

The GetVersionEx function supersedes the GetVersion function and is the preferred method for obtaining operating system version number information. New applications should use the GetVersionEx function rather than the GetVersion function.

See Also

OSVERSIONINFO


 GetViewportExt

The GetViewportExt function is not implemented in the Win32 API. This function is included for compatibility with 16-bit versions of Windows. Win32-based applications should use the GetViewportExtEx function.


GetViewportExtEx
 GetViewportExtEx  QuickInfo  Overview  Group

The GetViewportExtEx function retrieves the x-extents and y-extents of the current viewport for the specified device context.

BOOL GetViewportExtEx(

HDC  hdc,	// handle of device context
LPSIZE  lpSize	// address of structure receiving viewport dimensions
);
Parameters

hdc

Identifies the device context.

lpSize

Points to a SIZE structure. The x- and y-extents, in device units, are placed in this structure.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

See Also

GetWindowExtEx, SetViewportExtEx, SetWindowExtEx


 GetViewportOrg

The GetViewportOrg function has is not implemented in the Win32 API. This function is included for compatability with 16-bit versions of Windows. Win32-based applications should use the GetViewportOrgEx function.


GetViewportOrgEx
 GetViewportOrgEx  QuickInfo  Overview  Group

The GetViewportOrgEx function retrieves the x-coordinates and y-coordinates of the viewport origin for the specified device context.

BOOL GetViewportOrgEx(

HDC  hdc,	// handle of device context
LPPOINT  lpPoint	// address of structure receiving the viewport origin
);
Parameters

hdc

Identifies the device context.

lpPoint

Points to a POINT structure that receives the origin coordinates.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

See Also

GetWindowOrgEx, POINT, SetViewportOrgEx, SetWindowOrgEx


GetVolumeInformation
 GetVolumeInformation  QuickInfo  Overview  Group

The GetVolumeInformation function returns information about a file system and volume whose root directory is specified.

BOOL GetVolumeInformation(

LPCTSTR  lpRootPathName,	// address of root directory of the file system
LPTSTR  lpVolumeNameBuffer,	// address of name of the volume
DWORD  nVolumeNameSize,	// length of lpVolumeNameBuffer
LPDWORD  lpVolumeSerialNumber,	// address of volume serial number
LPDWORD  lpMaximumComponentLength,	// address of system's maximum filename length
LPDWORD  lpFileSystemFlags,	// address of file system flags
LPTSTR  lpFileSystemNameBuffer,	// address of name of file system
DWORD  nFileSystemNameSize	// length of lpFileSystemNameBuffer
);
Parameters

lpRootPathName

Points to a string that contains the root directory of the volume to be described. If this parameter is NULL, the root of the current directory is used.

lpVolumeNameBuffer

Points to a buffer that receives the name of the specified volume.

nVolumeNameSize

Specifies the length, in characters, of the volume name buffer. This parameter is ignored if the volume name buffer is not supplied.

lpVolumeSerialNumber

Points to a variable that receives the volume serial number. This parameter can be NULL if the serial number is not required.

lpMaximumComponentLength

Points to a doubleword value that receives the maximum length, in characters, of a filename component supported by the specified file system. A filename component is that portion of a filename between backslashes.

The value stored in variable pointed to by *lpMaximumComponentLength is used to indicate that long names are supported by the specified file system. For example, for a FAT file system supporting long names, the function stores the value 255, rather than the previous 8.3 indicator. Long names can also be supported on systems that use the NTFS and HPFS file systems.

lpFileSystemFlags

Points to a doubleword that receives flags associated with the specified file system. This parameter can be any combination of the following flags, with one exception: FS_FILE_COMPRESSION and FS_VOL_IS_COMPRESSED are mutually exclusive.

Value	Meaning
FS_CASE_IS_PRESERVED	If this flag is set, the file system preserves the case of filenames when it places a name on disk.
FS_CASE_SENSITIVE	If this flag is set, the file system supports case-sensitive filenames.
FS_UNICODE_STORED_ON_DISK	If this flag is set, the file system supports Unicode in filenames as they appear on disk.
FS_PERSISTENT_ACLS	If this flag is set, the file system preserves and enforces ACLs. For example, NTFS preserves and enforces ACLs, HPFS and FAT do not.
FS_FILE_COMPRESSION	The file system supports file-based compression.
FS_VOL_IS_COMPRESSED	The specified volume is a compressed volume; for example, a DoubleSpace volume.
lpFileSystemNameBuffer

Points to a buffer that receives the name of the file system (such as FAT, HPFS, or NTFS).

nFileSystemNameSize

Specifies the length, in characters, of the file system name buffer. This parameter is ignored if the file system name buffer is not supplied.

Return Value

If all the requested information is retrieved, the return value is TRUE; otherwise, it is FALSE. To get extended error information, call GetLastError.

Remarks

The FS_VOL_IS_COMPRESSED flag is the only indicator of volume-based compression. The file system name is not altered to indicate compression. This flag comes back set on a DoubleSpace volume, for example. With volume-based compression, an entire volume is either compressed or not compressed.

The FS_FILE_COMPRESSION flag indicates whether a file system supports file-based compression. With file-based compression, individual files can be compressed or not compressed.

The FS_FILE_COMPRESSION and FS_VOL_IS_COMPRESSED flags are mutually exclusive; both bits cannot come back set.

The maximum component length value, stored in the DWORD variable pointed to by lpMaximumComponentLength, is the only indicator that a volume supports longer-than-normal FAT (or other file system) file names. The file system name is not altered to indicate support for long file names.

The GetCompressedFileSize function obtains the compressed size of a file. The GetFileAttributes function can determine whether an individual file is compressed.

See Also

GetCompressedFileSize, GetFileAttributes, SetVolumeLabel


GetWindow
 GetWindow  QuickInfo  Overview  Group

The GetWindow function retrieves the handle of a window that has the specified relationship to the specified window.

HWND GetWindow(

HWND  hWnd,	// handle of original window
UINT  uCmd	// relationship flag
);
Parameters

hWnd

Identifies a window. The window handle retrieved is relative to this window, based on the value of the uCmd parameter.

uCmd

Specifies the relationship between the specified window and the window whose handle is to be retrieved. This parameter can be one of the following values:

Value	Meaning
GW_CHILD	The retrieved handle identifies the child window at the top of the Z order, if the specified window is a parent window; otherwise, the retrieved handle is NULL. The function examines only child windows of the specified window. It does not examine descendant windows.
GW_HWNDFIRST	The retrieved handle identifies the window at the top of the Z order. If the specified window is a topmost window, the handle identifies the topmost window at the top of the Z order. If the specified window is a top-level window, the handle identifies the top-level window at the top of the Z order. If the specified window is a child window, the handle identifies the sibling window at the top of the Z order.
GW_HWNDLAST	The retrieved handle identifies the window at the bottom of the Z order. If the specified window is a topmost window, the handle identifies the topmost window at the bottom of the Z order. If the specified window is a top-level window, the handle identifies the top-level window at the bottom of the Z order. If the specified window is a child window, the handle identifies the sibling window at the bottom of the Z order.
GW_HWNDNEXT	The retrieved handle identifies the window below the specified window in the Z order. If the specified window is a topmost window, the handle identifies the topmost window below the specified window. If the specified window is a top-level window, the handle identifies the top-level window below the specified window. If the specified window is a child window, the handle identifies the sibling window below the specified window.
GW_HWNDPREV	The retrieved handle identifies the window above the specified window in the Z order. If the specified window is a topmost window, the handle identifies the topmost window above the specified window. If the specified window is a top-level window, the handle identifies the top-level window above the specified window. If the specified window is a child window, the handle identifies the sibling window above the specified window.
GW_OWNER	The retrieved handle identifies the specified window's owner window, if any.
Return Value

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.

See Also

GetActiveWindow, GetNextWindow, GetTopWindow


GetWindowContextHelpId [New - Windows NT]
 GetWindowContextHelpId  QuickInfo  Overview  Group

[New - Windows NT]

The GetWindowContextHelpId function retrieves the help context identifier, if any, associated with the specified window.

DWORD GetWindowContextHelpId(

HWND  hwnd
);
Parameters

hwnd

Handle to the window for which the help context identifier is to be retrieved.

Return Value

Returns the help context identifier if the window has one or zero otherwise.


GetWindowDC
 GetWindowDC  QuickInfo  Overview  Group

The GetWindowDC function retrieves the device context (DC) for the entire window, including title bar, menus, and scroll bars. A window device context permits painting anywhere in a window, because the origin of the device context is the upper-left corner of the window instead of the client area.

GetWindowDC assigns default attributes to the window device context each time it retrieves the device context. Previous attributes are lost.

HDC GetWindowDC(

HWND  hWnd	// handle of window
);
Parameters

hWnd

Identifies the window with a device context that is to be retrieved.

Return Value

If the function succeeds, the return value is the handle of a device context for the specified window.

If the function fails, the return value is NULL, indicating an error or an invalid hWnd parameter.

Remarks

GetWindowDC is intended for special painting effects within a window's nonclient area. Painting in nonclient areas of any window is not recommended.

The GetSystemMetrics function can be used to retrieve the dimensions of various parts of the nonclient area, such as the title bar, menu, and scroll bars.

After painting is complete, the ReleaseDC function must be called to release the device context. Not releasing the window device context has serious effects on painting requested by applications.

See Also

BeginPaint, GetDC, GetSystemMetrics, ReleaseDC


 GetWindowExt

The GetWindowExt function is not implemented in the Win32 API. This function is included for compatability with 16-bit versions of Windows. Win32-based applications should use the GetWindowExtEx function.


GetWindowExtEx
 GetWindowExtEx  QuickInfo  Overview  Group

This function retrieves the x-extents and y-extents of the window for the specified device context.

BOOL GetWindowExtEx(

HDC  hdc,	// handle of device context
LPSIZE  lpSize	// address of structure receiving window extents
);
Parameters

hdc

Identifies the device context.

lpSize

Points to a SIZE structure. The x- and y-extents in page-space units are placed in this structure.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

See Also

GetViewportExtEx, SetViewportExtEx, SetWindowExtEx


GetWindowLong
 GetWindowLong  QuickInfo  Overview  Group

The GetWindowLong function retrieves information about the specified window. The function also retrieves the 32-bit (long) value at the specified offset into the extra window memory of a window.

LONG GetWindowLong(

HWND  hWnd,	// handle of window
int  nIndex	// offset of value to retrieve
);
Parameters

hWnd

Identifies the window and, indirectly, the class to which the window belongs.

nIndex

Specifies the zero-based offset to the value to be retrieved. Valid values are in the range zero through the number of bytes of extra window memory, minus four; for example, if you specified 12 or more bytes of extra memory, a value of 8 would be an index to the third 32-bit integer. To retrieve any other value, specify one of the following values:

Value	Action
GWL_EXSTYLE	Retrieves the extended window styles.
GWL_STYLE	Retrieves the window styles.
GWL_WNDPROC	Retrieves the address of the window procedure, or a handle representing the address of the window procedure. You must use the CallWindowProc function to call the window procedure.
GWL_HINSTANCE	Retrieves the handle of the application instance.
GWL_HWNDPARENT	Retrieves the handle of the parent window, if any.
GWL_ID	Retrieves the identifier of the window.
GWL_USERDATA	Retrieves the 32-bit value associated with the window. Each window has a corresponding 32-bit value intended for use by the application that created the window.
The following values are also available when the hWnd parameter identifies a dialog box:

Value	Action
DWL_DLGPROC	Retrieves the address of the dialog box procedure, or a handle representing the address of the dialog box procedure. You must use the CallWindowProc function to call the dialog box procedure.
DWL_MSGRESULT	Retrieves the return value of a message processed in the dialog box procedure.
DWL_USER	Retrieves extra information private to the application, such as handles or pointers.
Return Value

If the function succeeds, the return value is the requested 32-bit value.

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

Remarks

Reserve extra window memory by specifying a nonzero value in the cbWndExtra member of the WNDCLASS structure used with the RegisterClass function.

See Also

CallWindowProc, GetWindowWord, RegisterClass, SetParent, SetWindowLong, SetWindowWord, WNDCLASS


 GetWindowOrg

The GetWindowOrg function is not implemented in the Win32 API. This function is included for compatability with 16-bit versions of Windows. Win32-based applications should use the GetWindowOrgEx function.


GetWindowOrgEx
 GetWindowOrgEx  QuickInfo  Overview  Group

The GetWindowOrgEx function retrieves the x-coordinates and y-coordinates of the window origin for the specified device context.

BOOL GetWindowOrgEx(

HDC  hdc,	// handle of device context
LPPOINT  lpPoint	// address of structure receiving the window origin
);
Parameters

hdc

Identifies the device context.

lpPoint

Points to a POINT structure that receives the coordinates, in page units, of the window origin.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

See Also

GetViewportOrgEx, SetViewportOrgEx, SetWindowOrgEx


GetWindowPlacement
 GetWindowPlacement  QuickInfo  Overview  Group

The GetWindowPlacement function retrieves the show state and the restored, minimized, and maximized positions of the specified window.

BOOL GetWindowPlacement(

HWND  hWnd,	// handle of window
WINDOWPLACEMENT *  lpwndpl	// address of structure for position data
);
Parameters

hWnd

Identifies the window.

lpwndpl

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

Windows 95 only: GetWindowPlacement fails if lpwndpl->length is not set correctly.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. 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.

See Also

SetWindowPlacement, WINDOWPLACEMENT


GetWindowRect
 GetWindowRect  QuickInfo  Overview  Group

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 of window
LPRECT  lpRect	// address of structure for window coordinates
);
Parameters

hWnd

Identifies the window.

lpRect

Points to a RECT structure that receives the screen coordinates of the upper-left and lower-right corners of the window.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

GetClientRect, RECT


GetWindowRgn [New - Windows NT]
 GetWindowRgn  QuickInfo

[New - Windows NT]

The GetWindowRgn function obtains a copy of the window region of a window. The window region of a window is set by calling the SetWindowRgn function. The window region determines the area within the window where the operating system permits drawing. The operating system does not display any portion of a window that lies outside of the window region

int GetWindowRgn(

HWND  hWnd,	// handle to window whose window region is to be obtained
HRGN  hRgn	// handle to region that receives a copy of the window region
);
Parameters

hWnd

Handle to the window whose window region is to be obtained.

hrgn

Handle to a region. This region receives a copy of the window region.

Return Value

The return value specifies the type of the region that the function obtains. It can be one of the following values:

Value	Meaning
NULLREGION	The region is empty.
SIMPLEREGION	The region is a single rectangle.
COMPLEXREGION	The region is more than one rectangle.
ERROR	An error occurred; the region is unaffected.
Comments

The coordinates of a window's window region are relative to the upper-left corner of the window, not the client area of the window.

To set the window region of a window, call the SetWindowRgn function.

See Also

SetWindowRgn


 GetWindowsDir

The GetWindowsDir function is not implemented in the Win32 API. This function is included for compatability with 16-bit versions of Windows. Win32-based applications should use the GetWindowsDirectory function to determine the Windows directory.


GetWindowsDirectory
 GetWindowsDirectory  QuickInfo  Overview  Group

The GetWindowsDirectory function retrieves the path of the Windows directory. The Windows directory contains such files as Windows-based applications, initialization files, and Help files.

UINT GetWindowsDirectory(

LPTSTR  lpBuffer,	// address of buffer for Windows directory
UINT  uSize	// size of directory buffer
);
Parameters

lpBuffer

Points to the buffer to receive the null-terminated string containing the path. This path does not end with a backslash unless the Windows directory is the root directory. For example, if the Windows directory is named WINDOWS on drive C, the path of the Windows directory retrieved by this function is C:\WINDOWS. If Windows was installed in the root directory of drive C, the path retrieved is C:\.

uSize

Specifies the maximum size, in characters, of the buffer specified by the lpBuffer parameter. This value should be set to at least MAX_PATH to allow sufficient room in the buffer for the path.

Return Value

If the function succeeds, the return value is the length, in characters, of the string copied to the buffer, not including the terminating null character.

If the length is greater than the size of the buffer, the return value is the size of the buffer required to hold the path.

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

Remarks

The Windows directory is the directory where an application should store initialization and help files. If the user is running a shared version of Windows, the Windows directory is guaranteed to be private for each user.

If an application creates other files that it wants to store on a per-user basis, it should place them in the directory specified by the HOMEPATH environment variable. This directory will be different for each user, if so specified by an administrator, via the User Manager administrative tool. HOMEPATH always specifies either the user's home directory, which is guaranteed to be private for each user, or a default directory (for example, C:\USERS\DEFAULT) where the user will have all access.

See Also

GetCurrentDirectory, GetSystemDirectory


GetWindowTask
 GetWindowTask  QuickInfo  Overview  Group

The GetWindowTask function is not implemented in the WIn32 API.

To maintain compatibility with 16-bit applications, GetWindowTask has been replaced with a macro that calls GetWindowThreadProcessId. Earlier applications can continue to call GetWindowTask as previously documented, but new applications should use GetWindowThreadProcessId.

Remarks

GetWindowTask is defined as returning a value with a HANDLE data type. GetWindowThreadProcessId returns a value with a DWORD data type. The macro that maps GetWindowTask to GetWindowThreadProcessId includes a cast to HANDLE, as follows:

#define GetWindowTask(hwnd) \\

    ((HANDLE) GetWindowThreadProcessId(hwnd, NULL))

See Also

GetWindowThreadProcessId


GetWindowText
 GetWindowText  QuickInfo  Overview  Group

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.

int GetWindowText(

HWND  hWnd,	// handle of window or control with text
LPTSTR  lpString,	// address of buffer for text
int  nMaxCount	// maximum number of characters to copy
);
Parameters

hWnd

Identifies the window or control containing the text.

lpString

Points to the buffer that will receive the text.

nMaxCount

Specifies the maximum number of characters to copy to the buffer. If the text exceeds this limit, it is truncated.

Return Value

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

This function causes a WM_GETTEXT message to be sent to the specified window or control.

This function cannot retrieve the text of an edit control in another application.

See Also

GetWindowTextLength, SetWindowText, WM_GETTEXT


GetWindowTextLength
 GetWindowTextLength  QuickInfo  Overview  Group

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.

int GetWindowTextLength(

HWND  hWnd	// handle of window or control with text
);
Parameters

hWnd

Identifies the window or control.

Return Value

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

This function 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 operating 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 flavor of GetWindowTextLength with a window whose window procedure is Unicode, or the Unicode flavor with a window whose window procedure is ANSI.

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

See Also

CB_GETLBTEXT, GetWindowText, LB_GETTEXT, SetWindowText, WM_GETTEXT, WM_GETTEXTLENGTH


GetWindowThreadProcessId
 GetWindowThreadProcessId  QuickInfo  Overview  Group

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. This function supersedes the GetWindowTask function.

DWORD GetWindowThreadProcessId(

HWND  hWnd,	// handle of window
LPDWORD  lpdwProcessId	// address of variable for process identifier
);
Parameters

hWnd

Identifies the window.

lpdwProcessId

Points to a 32-bit value that receives the process identifier. If this parameter is not NULL, GetWindowThreadProcessId copies the identifier of the process to the 32-bit value; otherwise, it does not.

Return Value

The return value is the identifier of the thread that created the window.

Remarks

This function replaces the GetWindowTask function of Windows version 3.x.


GetWindowWord
 GetWindowWord  QuickInfo  Overview  Group

The GetWindowWord function retrieves a 16-bit (word) value at the specified offset into the extra window memory for the specified window.

WORD GetWindowWord(

HWND  hWnd,	// handle of window
int  nIndex	// offset of value to retrieve
);
Parameters

hWnd

Identifies the window and, indirectly, the class to which the window belongs.

nIndex

Specifies the zero-based byte offset of the value to be retrieved. Valid values are in the range zero through the number of bytes of extra window memory, minus two; for example, if you specified 10 or more bytes of extra window memory, a value of 8 would be an index to the fifth 16-bit integer.

Return Value

If the function succeeds, the return value is the requested 16-bit value.

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

Remarks

Reserve extra window memory by specifying a nonzero value in the cbWndExtra member of the WNDCLASS structure used with the RegisterClass function.

The GWW_ values are obsolete in Win32. You must use the GetWindowLong function to retrieve information about the window.

See Also

GetParent, GetWindowLong, RegisterClass, SetParent, SetWindowLong, SetWindowWord, WNDCLASS


GetWinFlags
 GetWinFlags  Overview  Group

The GetWinFlags function is not implemented in the Win32 API. Win32-based applications should use the GetSystemInfo function.


GetWinMetaFileBits
 GetWinMetaFileBits  QuickInfo  Overview  Group

The GetWinMetaFileBits function converts the enhanced-format records from a metafile into Windows-format records and stores the converted records in the specified buffer.

UINT GetWinMetaFileBits(

HENHMETAFILE  hemf,	// handle to the enhanced metafile
UINT  cbBuffer,	// buffer size
LPBYTE  lpbBuffer,	// pointer to buffer
INT  fnMapMode,	// mapping mode
HDC  hdcRef	// handle of reference device context
);
Parameters

hemf

Identifies the enhanced metafile.

cbBuffer

Specifies the size, in bytes, of the buffer into which the converted records are to be copied.

lpbBuffer

Points to the buffer into which the converted records are to be copied. If lpbBuffer is NULL, GetWinMetaFileBits returns the the number of bytes required to store the converted metafile records.

fnMapMode

Specifies the mapping mode to use in the converted metafile.

hdcRef

Identifies the reference device context.

Return Value

If the function succeeds and the buffer pointer is NULL, the return value is the number of bytes required to store the converted records; if the function succeeds and the buffer pointer is a valid pointer, the return value is the size of the metafile data in bytes.

If the function fails, the return value is zero.

Remarks

This function converts an enhanced metafile into a Windows-format metafile so that its picture can be displayed in an application that recognizes the older format.

Windows uses the reference device context to determine the resolution of the converted metafile.

The GetWinMetaFileBits function does not invalidate the enhanced metafile handle. An application should call the DeleteEnhMetaFile function to release the handle when it is no longer needed.

Due to the limitations of the Windows-format metafile, some information can be lost in the retrieved metafile contents. For example, an original call to the PolyBezier function in the enhanced metafile may be converted into a call to the Polyline function in the Windows-format metafile, because there is no equivalent PolyBezier function in the Windows format.

Windows 3.x applications define the viewport origin and extents of a picture stored in a Windows-format metafile. As a result, the Windows-format records created by GetWinMetaFileBits do not contain the SetViewportOrg and SetViewportExt functions. However, GetWinMetaFileBits does create Windows-format records for the SetWindowExt and SetMapMode functions.

To create a scalable Windows-format metafile, specify MM_ANISOTROPIC as the fnMapMode parameter.

The upper-left corner of the metafile picture is always mapped to the origin of the reference device.

See Also

DeleteEnhMetaFile, PolyBezier, Polyline, SetMapMode, SetViewportOrg, SetViewportExt, SetWindowExt


GetWorldTransform
 GetWorldTransform  QuickInfo  Overview  Group

The GetWorldTransform function retrieves the current world-space to page-space transformation.

BOOL GetWorldTransform(

HDC  hdc,	// handle to the device context
LPXFORM  lpXform	// pointer to the structure receiving transformation
);
Parameters

hdc

Identifies the device context.

lpXform

Points to an XFORM structure that receives the current world-space to page-space transformation.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

The precision of the transformation may be altered if an application calls the ModifyWorldTransform function prior to calling GetWorldTransform. (This is because the internal format for storing transformation values uses a higher precision than a FLOAT value.)

See Also

ModifyWorldTransform, SetWorldTransform


GlobalAddAtom
 GlobalAddAtom  QuickInfo  Overview  Group

The GlobalAddAtom function adds a character string to the global atom table and returns a unique value (an atom) identifying the string.

ATOM GlobalAddAtom(

LPCTSTR  lpString	// pointer to the string to add
);
Parameters

lpString

Points to the null-terminated string to be added. The string can have a maximum size of 255 bytes. Strings that differ only in case are considered identical. The case of the first string of this name added to the table is preserved and returned by the GlobalGetAtomName function.

Return Value

If the function succeeds, the return value is the newly created atom.

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

Remarks

If the string already exists in the global atom table, the atom for the existing string is returned and the atom's reference count is incremented.

The string associated with the atom is not deleted from memory until its reference count is zero. For more information, see the GlobalDeleteAtom function.

Global atoms are not deleted automatically when the application terminates. For every call to the GlobalAddAtom function, there must be a corresponding call to the GlobalDeleteAtom function.

GlobalAddAtom returns a string atom whose value is in the range 0xC000 through 0xFFFF.

If the lpString parameter has the form "#1234", GlobalAddAtom returns an integer atom whose value is the 16-bit representation of the decimal number specified in the string (0x04D2, in this example). If the decimal value specified is 0x0000 or a value in the range 0xC000 through 0xFFFF, the return value is zero, indicating an error. If lpString is in the range 0x0001 through 0xBFFF, the return value is the low-order word of lpString.

The MAKEINTATOM macro can be used to convert a WORD value into a string that can be added to the atom table by using the GlobalAddAtom function.

See Also

AddAtom, DeleteAtom, FindAtom, GetAtomName, GlobalDeleteAtom, GlobalFindAtom, GlobalGetAtomName, MAKEINTATOM


GlobalAlloc
 GlobalAlloc  QuickInfo  Overview  Group

The GlobalAlloc function allocates the specified number of bytes from the heap. In the linear Win32 API environment, there is no difference between the local heap and the global heap.

HGLOBAL GlobalAlloc(

UINT  uFlags,	// object allocation attributes
DWORD  dwBytes	// number of bytes to allocate
);
Parameters

uFlags

Specifies how to allocate memory. If zero is specified, the default is GMEM_FIXED. Except for the incompatible combinations that are specifically noted, any combination of the following flags can be used. To indicate whether the function allocates fixed or movable memory, specify one of the first four flags:

Flag	Meaning
GMEM_FIXED	Allocates fixed memory. This flag cannot be combined with the GMEM_MOVEABLE or GMEM_DISCARDABLE flag. The return value is a pointer to the memory block. To access the memory, the calling process simply casts the return value to a pointer.
GMEM_MOVEABLE	Allocates movable memory. This flag cannot be combined with the GMEM_FIXED flag. The return value is the handle of the memory object. The handle is a 32-bit quantity that is private to the calling process. To translate the handle into a pointer, use the GlobalLock function.
GPTR	Combines the GMEM_FIXED and GMEM_ZEROINIT flags.
GHND	Combines the GMEM_MOVEABLE and GMEM_ZEROINIT flags.
GMEM_DDESHARE	Allocates memory to be used by the dynamic data exchange (DDE) functions for a DDE conversation. Unlike Windows version 3. x, this memory is not shared globally. However, this flag is available for compatibility purposes. It may be used by some applications to enhance the performance of DDE operations and should, therefore, be specified if the memory is to be used for DDE.  Only processes that use DDE or the clipboard for interprocess communications should specify this flag.
GMEM_DISCARDABLE	Allocates discardable memory. This flag cannot be combined with the GMEM_FIXED flag. Some Win32-based applications may ignore this flag.
GMEM_LOWER	Ignored. This flag is provided only for compatibility with Windows version 3. x.
GMEM_NOCOMPACT	Does not compact or discard memory to satisfy the allocation request.
GMEM_NODISCARD	Does not discard memory to satisfy the allocation request.
GMEM_NOT_BANKED	Ignored. This flag is provided only for compatibility with Windows version 3. x.
GMEM_NOTIFY	Ignored. This flag is provided only for compatibility with Windows version 3. x.
GMEM_SHARE	Same as the GMEM_DDESHARE flag.
GMEM_ZEROINIT	Initializes memory contents to zero.
dwBytes

Specifies the number of bytes to allocate. If this parameter is zero and the uFlags parameter specifies the GMEM_MOVEABLE flag, the function returns a handle to a memory object that is marked as discarded.

Return Value

If the function succeeds, the return value is the handle of the newly allocated memory object.

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

Remarks

If the heap does not contain sufficient free space to satisfy the request, GlobalAlloc returns NULL.

Because NULL is used to indicate an error, virtual address zero is never allocated. It is, therefore, easy to detect the use of a NULL pointer.

All memory is created with execute access; no special function is required to execute dynamically generated code.

Memory allocated with this function is guaranteed to be aligned on an 8-byte boundary.

The GlobalAlloc and LocalAlloc functions are limited to a combined total of 65,536 handles for GMEM_MOVEABLE and LMEM_MOVEABLE memory per process. This limitation does not apply to GMEM_FIXED or LMEM_FIXED memory.

If this function succeeds, it allocates at least the amount of memory requested. If the actual amount allocated is greater than the amount requested, the process can use the entire amount. To determine the actual number of bytes allocated, use the GlobalSize function.

See Also

GlobalFree, GlobalLock, GlobalReAlloc, GlobalSize, LocalAlloc


GlobalCompact
 GlobalCompact  QuickInfo  Overview  Group

The GlobalCompact function is obsolete. It has no meaning in the 32-bit environment.


GlobalDeleteAtom
 GlobalDeleteAtom  QuickInfo  Overview  Group

The GlobalDeleteAtom function decrements the reference count of a global string atom. If the atom's reference count reaches zero, GlobalDeleteAtom removes the string associated with the atom from the global atom table.

ATOM GlobalDeleteAtom(

ATOM  nAtom	// atom to delete
);
Parameters

nAtom

Identifies the atom and character string to be deleted.

Return Value

If the function succeeds, the return value is zero.

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

Remarks

A string atom's reference count specifies the number of times the string has been added to or removed from the atom table. The GlobalAddAtom function increments the reference count of a string that already exists in the global atom table each time it is called.

The only way to ensure that an atom has been deleted from the atom table is to call this function repeatedly until it fails. When the reference count is decremented to zero, the next GlobalFindAtom or GlobalDeleteAtom function call fails.

GlobalDeleteAtom has no effect on an integer atom (an atom created by using the MAKEINTATOM macro). The function always returns zero for an integer atom.

See Also

AddAtom, DeleteAtom, FindAtom, GlobalAddAtom, GlobalFindAtom, MAKEINTATOM


GlobalDiscard
 GlobalDiscard  QuickInfo  Overview  Group

The GlobalDiscard function discards the specified global memory block. The lock count of the memory object must be zero.

HGLOBAL GlobalDiscard(

HGLOBAL  hglbMem	// handle to the global memory object
);
Parameters

hglbMem

Identifies the global memory object. This handle is returned by either the GlobalAlloc or GlobalReAlloc function.

Return Value

If the function succeeds, the return value is the handle of the memory object.

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

Remarks

GlobalDiscard discards only global objects that the calling process allocated with the GMEM_DISCARDABLE flag. If a process attempts to discard a fixed or locked object, the function fails.

Although GlobalDiscard discards the object's memory block, the handle of the object remains valid. A process can subsequently pass the handle to the GlobalReAlloc function to allocate another global memory block identified by the same handle.

See Also

GlobalAlloc, GlobalReAlloc


GlobalDosAlloc
 GlobalDosAlloc  Overview  Group

The GlobalDosAlloc function has been deleted. Win32-based applications should use the VirtualLock and VirtualUnlock functions.


GlobalDosFree
 GlobalDosFree  Overview  Group

The GlobalDosFree function has been deleted. Win32-based applications should use the VirtualLock and VirtualUnlock functions.


GlobalFindAtom
 GlobalFindAtom  QuickInfo  Overview  Group

The GlobalFindAtom function searches the global atom table for the specified character string and retrieves the global atom associated with that string.

ATOM GlobalFindAtom(

LPCTSTR  lpString	// pointer to the string to find
);
Parameters

lpString

Points to the null-terminated character string to search for.

Return Value

If the function succeeds, the return value is the global atom associated with the given string.

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

Remarks

Even though Windows preserves the case of a string in an atom table as it was originally entered, the search performed by GlobalFindAtom is not case sensitive.

See Also

AddAtom, DeleteAtom, FindAtom, GetAtomName, GlobalAddAtom, GlobalDeleteAtom, GlobalGetAtomName


GlobalFix
 GlobalFix  Overview  Group

The GlobalFix function is obsolete. It has no meaning in the 32-bit environment. Win32-based applications should use the VirtualLock and VirtualUnlock functions.


GlobalFlags
 GlobalFlags  QuickInfo  Overview  Group

The GlobalFlags function returns information about the specified global memory object.

UINT GlobalFlags(

HGLOBAL  hMem	// handle to the global memory object
);
Parameters

hMem

Identifies the global memory object. This handle is returned by either the GlobalAlloc or GlobalReAlloc function.

Return Value

If the function succeeds, the return value is a 32-bit value specifying the allocation flags and the lock count for the memory object.

If the function fails, the return value is the GMEM_INVALID_HANDLE flag, indicating that the global handle is not valid. To get extended error information, call GetLastError.

Remarks

The low-order byte of the low-order word of the return value contains the lock count of the object. To retrieve the lock count from the return value, use the GMEM_LOCKCOUNT mask with the bitwise AND (&) operator. The lock count of memory objects allocated with the GMEM_FIXED flag is always zero.

The high-order byte of the low-order word of the return value indicates the allocation flags of the memory object. It can be zero or any combination of the following flags:

Flag	Meaning
GMEM_DDESHARE	Memory was allocated for use by the dynamic data exchange (DDE) functions. Unlike Windows version  3. x, this memory is not shared globally. However, this flag is available for compatibility purposes and may be used by some applications to enhance the performance of DDE operations. Only processes that use DDE or the clipboard for interprocess communications should specify this flag.
GMEM_DISCARDABLE	The object's memory block can be discarded.
GMEM_DISCARDED	The object's memory block has been discarded.
See Also

GlobalAlloc, GlobalDiscard, GlobalLock, GlobalReAlloc, GlobalUnlock, LocalFlags


GlobalFree
 GlobalFree  QuickInfo  Overview  Group

The GlobalFree function frees the specified global memory object and invalidates its handle.

HGLOBAL GlobalFree(

HGLOBAL  hMem	// handle to the global memory object
);
Parameters

hMem

Identifies the global memory object. This handle is returned by either the GlobalAlloc or GlobalReAlloc function.

Return Value

If the function succeeds, the return value is NULL.

If the function fails, the return value is equal to the handle of the global memory object. To get extended error information, call GetLastError.

Remarks

Heap corruption or an access violation exception (EXCEPTION_ACCESS_VIOLATION) may occur if the process tries to examine or modify the memory after it has been freed.

If the hgblMem parameter is NULL, GlobalFree fails and the system generates an access violation exception.

Both GlobalFree and LocalFree will free a locked memory object. A locked memory object has a lock count greater than zero. The GlobalLock function locks a global memory object and increments the lock count by one. The GlobalUnlock function unlocks it and decrements the lock count by one. To get the lock count of a global memory object, use the GlobalFlags function.

Windows NT: However, if an application is running under a debug (DBG) version of Windows NT, such as the one distributed on the SDK CD-ROM, both GlobalFree and LocalFree enter a breakpoint just before freeing a locked object. This lets a programmer double-check the intended behavior. Typing G while using the debugger in this situation lets the freeing operation occur.

See Also

GlobalAlloc, GlobalFlags, GlobalLock, GlobalReAlloc, GlobalUnlock, LocalFree


GlobalGetAtomName
 GlobalGetAtomName  QuickInfo  Overview  Group

The GlobalGetAtomName function retrieves a copy of the character string associated with the specified global atom.

UINT GlobalGetAtomName(

ATOM  nAtom,	// atom identifier
LPTSTR  lpBuffer,	// pointer to the buffer for the atom string
int  nSize	// size of the buffer
);
Parameters

nAtom

Identifies the global atom associated with the character string to be retrieved.

lpBuffer

Points to the buffer for the character string.

nSize

Specifies the size, in characters, of the buffer.

Return Value

If the function succeeds, the return value is the length of the string copied to the buffer, in characters, not including the terminating null character.

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

Remarks

The string returned for an integer atom (an atom created by the MAKEINTATOM macro) is a null-terminated string in which the first character is a pound sign (#) and the remaining characters represent the unsigned integer originally passed to MAKEINTATOM.

See Also

AddAtom, DeleteAtom, FindAtom, GlobalAddAtom, GlobalDeleteAtom, GlobalFindAtom, MAKEINTATOM


GlobalHandle
 GlobalHandle  QuickInfo  Overview  Group

The GlobalHandle function retrieves the handle associated with the specified pointer to a global memory block.

HGLOBAL GlobalHandle(

LPCVOID  pMem	// pointer to the global memory block
);
Parameters

pMem

Points to the first byte of the global memory block. This pointer is returned by the GlobalLock function.

Return Value

If the function succeeds, the return value is the handle of the specified global memory object.

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

Remarks

When the GlobalAlloc function allocates a memory object with the GMEM_MOVEABLE flag, it returns the handle of the object. The GlobalLock function converts this handle into a pointer to the memory block, and GlobalHandle converts the pointer back into a handle.

See Also

GlobalAlloc, GlobalLock


GlobalLock
 GlobalLock  QuickInfo  Overview  Group

The GlobalLock function locks a global memory object and returns a pointer to the first byte of the object's memory block. The memory block associated with a locked memory object cannot be moved or discarded. For memory objects allocated with the GMEM_MOVEABLE flag, the function increments the lock count associated with the memory object.

LPVOID GlobalLock(

HGLOBAL  hMem	// address of the global memory object
);
Parameters

hMem

Identifies the global memory object. This handle is returned by either the GlobalAlloc or GlobalReAlloc function.

Return Value

If the function succeeds, the return value is a pointer to the first byte of the memory block.

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

Remarks

The internal data structures for each memory object include a lock count that is initially zero. For movable memory objects, GlobalLock increments the count by one, and the GlobalUnlock function decrements the count by one. For each call that a process makes to GlobalLock for an object, it must eventually call GlobalUnlock. Locked memory will not be moved or discarded, unless the memory object is reallocated by using the GlobalReAlloc function. The memory block of a locked memory object remains locked until its lock count is decremented to zero, at which time it can be moved or discarded.

Memory objects allocated with the GMEM_FIXED flag always have a lock count of zero. For these objects, the value of the returned pointer is equal to the value of the specified handle.

If the specified memory block has been discarded or if the memory block has a zero-byte size, this function returns NULL.

Discarded objects always have a lock count of zero.

See Also

GlobalAlloc, GlobalFlags, GlobalReAlloc, GlobalUnlock


GlobalLRUNewest
 GlobalLRUNewest  QuickInfo  Overview  Group

The GlobalLRUNewest function is obsolete. It has no meaning in the 32-bit environment. Win32-based applications should use the VirtualLock and VirtualUnlock functions.


GlobalLRUOldest
 GlobalLRUOldest  QuickInfo  Overview  Group

The GlobalLRUOldest function is obsolete. It has no meaning in the 32-bit environment. Win32-based applications should use the VirtualLock and VirtualUnlock functions.


GlobalMemoryStatus
 GlobalMemoryStatus  QuickInfo  Overview  Group

The GlobalMemoryStatus function retrieves information about current available memory. The function returns information about both physical and virtual memory. This function supersedes the GetFreeSpace function.

VOID GlobalMemoryStatus(

LPMEMORYSTATUS  lpBuffer	// pointer to the memory status structure
);
Parameters

lpBuffer

Points to a MEMORYSTATUS structure in which information about current memory availability is returned. Before calling this function, the calling process should set the dwLength member of this structure.

Return Value

This function does not return a value.

Remarks

An application can use the GlobalMemoryStatus function to determine how much memory it can allocate without severely impacting other applications.

The information returned is volatile, and there is no guarantee that two sequential calls to this function will return the same information.

See Also

MEMORYSTATUS


GlobalNotify
 GlobalNotify  Overview  Group

The GlobalNotify function is not implemented in the Win32 SDK. Win32-based applications should use the GlobalFlags function.


GlobalPageLock
 GlobalPageLock  Overview  Group

The GlobalPageLock function is not implemented in the Win32 API. Win32-based applications should use the VirtualLock and VirtualUnlock functions.


GlobalPageUnlock
 GlobalPageUnlock  Overview  Group

The GlobalPageUnlock function is not implemented in the Win32 API. Win32-based applications should use the VirtualLock and VirtualUnlock functions.


GlobalReAlloc
 GlobalReAlloc  QuickInfo  Overview  Group

The GlobalReAlloc function changes the size or attributes of a specified global memory object. The size can increase or decrease.

HGLOBAL GlobalReAlloc(

HGLOBAL  hMem,	// handle to the global memory object
DWORD  dwBytes,	// new size of the block
UINT  uFlags	// how to reallocate object
);
Parameters

hMem

Identifies the global memory object to be reallocated. This handle is returned by either the GlobalAlloc or GlobalReAlloc function.

dwBytes

Specifies the new size, in bytes, of the memory block. If this parameter is zero and the uFlags parameter specifies the GMEM_MOVEABLE flag, the function returns the handle of a memory object that is marked as discarded. If uFlags specifies the GMEM_MODIFY flag, this parameter is ignored.

uFlags

Specifies how to reallocate the global memory object. If the GMEM_MODIFY flag is specified, this parameter modifies the attributes of the memory object, and the dwBytes parameter is ignored. Otherwise, this parameter controls the reallocation of the memory object.

The GMEM_MODIFY flag can be combined with either or both of the following flags:

Flag	Meaning
GMEM_DISCARDABLE	Allocates discardable memory if the GMEM_MODIFY flag is also specified. This flag is ignored, unless the object was previously allocated as movable or the GMEM_MOVEABLE flag is also specified.
GMEM_MOVEABLE	Windows NT only: Changes a fixed memory object to a movable memory object if the GMEM_MODIFY flag is also specified.
If this parameter does not specify GMEM_MODIFY, it can be any combination of the following flags:

Flag	Meaning
GMEM_MOVEABLE	If dwBytes is zero, discards a previously movable and discardable memory block. If the lock count of the object is not zero or if the block is not movable and discardable, the function fails.  If dwBytes is nonzero, enables the system to move the reallocated block to a new location without changing the movable or fixed attribute of the memory object. If the object is fixed, the handle returned may be different from the handle specified by the hMem parameter. If the object is movable, the block can be moved without invalidating the handle, even if the object is currently locked by a previous call to the GlobalLock function. To get the new address of the memory block, use GlobalLock.
GMEM_NOCOMPACT	Prevents memory from being compacted or discarded to satisfy the allocation request.
GMEM_ZEROINIT	Causes the additional memory contents to be initialized to zero if the memory object is growing in size.
Return Value

If the function succeeds, the return value is the handle of the reallocated memory object.

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

Remarks

If GlobalReAlloc reallocates a movable object, the return value is the handle of the memory object. To convert the handle to a pointer, use the GlobalLock function.

If GlobalReAlloc reallocates a fixed object, the value of the handle returned is the address of the first byte of the memory block. To access the memory, a process can simply cast the return value to a pointer.

If GlobalReAlloc fails, the original memory is not freed, and the original handle and pointer are still valid.

See Also

GlobalAlloc, GlobalFree, GlobalLock


GlobalSize
 GlobalSize  QuickInfo  Overview  Group

The GlobalSize function retrieves the current size, in bytes, of the specified global memory object.

DWORD GlobalSize(

HGLOBAL  hMem	// handle to the global memory object
);
Parameters

hMem

Identifies the global memory object. This handle is returned by either the GlobalAlloc or GlobalReAlloc function.

Return Value

If the function succeeds, the return value is the size, in bytes, of the specified global memory object.

If the specified handle is not valid or if the object has been discarded, the return value is zero. To get extended error information, call GetLastError.

Remarks

The size of a memory block may be larger than the size requested when the memory was allocated.

To verify that the specified object's memory block has not been discarded, use the GlobalFlags function before calling GlobalSize.

See Also

GlobalAlloc, GlobalFlags, GlobalReAlloc


GlobalUnfix
 GlobalUnfix  Overview  Group

The GlobalUnfix function is obsolete. It has no meaning in the 32-bit environment.


GlobalUnlock
 GlobalUnlock  QuickInfo  Overview  Group

The GlobalUnlock function decrements the lock count associated with a memory object that was allocated with the GMEM_MOVEABLE flag. This function has no effect on memory objects allocated with the GMEM_FIXED flag.

BOOL GlobalUnlock(

HGLOBAL  hMem	// handle to the global memory object
);
Parameters

hMem

Identifies the global memory object. This handle is returned by either the GlobalAlloc or GlobalReAlloc function.

Return Value

If the memory object is still locked after decrementing the lock count, the return value is TRUE.

If the function fails, the return value is FALSE. To get extended error information, call GetLastError. If GetLastError returns NO_ERROR, the memory object is unlocked.

Remarks

The internal data structures for each memory object include a lock count that is initially zero. For movable memory objects, the GlobalLock function increments the count by one, and GlobalUnlock decrements the count by one. For each call that a process makes to GlobalLock for an object, it must eventually call GlobalUnlock. Locked memory will not be moved or discarded, unless the memory object is reallocated by using the GlobalReAlloc function. The memory block of a locked memory object remains locked until its lock count is decremented to zero, at which time it can be moved or discarded.

Memory objects allocated with the GMEM_FIXED flag always have a lock count of zero. If the specified memory block is fixed memory, this function returns TRUE.

If the memory object is already unlocked, GlobalUnlock returns FALSE and GetLastError reports ERROR_NOT_LOCKED. Memory objects allocated with the LMEM_FIXED flag always have a lock count of zero and cause the ERROR_NOT_LOCKED error.

A process should not rely on the return value to determine the number of times it must subsequently call GlobalUnlock for a memory object.

See Also

GlobalAlloc, GlobalFlags, GlobalLock, GlobalReAlloc


GlobalUnWire
 GlobalUnWire  Overview  Group

The GlobalUnWire function is obsolete. Applications that need to lock a global memory object should use the GlobalLock and GlobalUnlock functions.

This function is provided only for compatibility with 16-bit versions of Windows. New Win32-based applications should not use this function.


GlobalWire
 GlobalWire  Overview  Group

The GlobalWire function is obsolete. Win32-based applications should use the GlobalLock and GlobalUnlock functions.


GrayString
 GrayString  QuickInfo  Overview  Group

The GrayString function draws gray text at the specified location. The function draws the text by copying it into a memory bitmap, graying the bitmap, and then copying the bitmap to the screen. The function grays the text regardless of the selected brush and background. GrayString uses the font currently selected for the specified device context.

If the lpOutputFunc parameter is NULL, GDI uses the TextOut function, and the lpData parameter is assumed to be a pointer to the character string to be output. If the characters to be output cannot be handled by TextOut (for example, the string is stored as a bitmap), the application must supply its own output function.

BOOL GrayString(

HDC  hDC,	// handle to the device context
HBRUSH  hBrush,	// handle to the brush for graying
GRAYSTRINGPROC  lpOutputFunc,	// pointer to the callback function
LPARAM  lpData,	// pointer to application-defined data
int  nCount,	// number of characters to output
int  X,	// horizontal position
int  Y,	// vertical position
int  nWidth,	// width
int  nHeight	// height
);
Parameters

hDC

Identifies the device context.

hBrush

Identifies the brush to be used for graying. If this parameter is NULL, the text is grayed with the same brush that was used to draw window text.

lpOutputFunc

Points to the application-defined function that will draw the string, or, if TextOut is to be used to draw the string, it is a NULL pointer. For details, see the OutputProc callback function.

lpData

Specifies a pointer to data to be passed to the output function. If the lpOutputFunc parameter is NULL, lpData must be a pointer to the string to be output.

nCount

Specifies the number of characters to be output. If the nCount parameter is zero, GrayString calculates the length of the string (assuming lpData is a pointer to the string). If nCount is −1 and the function pointed to by lpOutputFunc returns FALSE, the image is shown but not grayed.

X

Specifies the device x-coordinate of the starting position of the rectangle that encloses the string.

Y

Specifies the device y-coordinate of the starting position of the rectangle that encloses the string.

nWidth

Specifies the width, in device units, of the rectangle that encloses the string. If this parameter is zero, GrayString calculates the width of the area, assuming lpData is a pointer to the string.

nHeight

Specifies the height, in device units, of the rectangle that encloses the string. If this parameter is zero, GrayString calculates the height of the area, assuming lpData is a pointer to the string.

Return Value

If the string is drawn, the return value is TRUE. If the return value is FALSE, either the TextOut function or the application-defined output function returned FALSE, or there was insufficient memory to create a memory bitmap for graying.

Remarks

Without calling GrayString, an application can draw grayed strings on devices that support a solid gray color. The system color COLOR_GRAYTEXT is the solid-gray system color used to draw disabled text. The application can call the GetSysColor function to retrieve the color value of COLOR_GRAYTEXT. If the color is other than zero (black), the application can call the SetTextColor function to set the text color to the color value and then draw the string directly. If the retrieved color is black, the application must call GrayString to gray the text.

See Also

DrawText, GetSysColor, OutputProc, SetTextColor, TabbedTextOut, TextOut


Handler
 Handler  QuickInfo  Overview  Group

A Handler function is a function that a service process specifies as the control handling function of a particular service. The function can have any application-defined name.

VOID Handler(

DWORD  fdwControl	// requested control code
);
Parameters

fdwControl

Indicates the requested control code. This value can be one of the standard control codes in the table, or it can be a user-defined control code in the range of 128 to 255, inclusive. For user-defined control codes, the service defines the action associated with the control code.

Value	Meaning
SERVICE_CONTROL_STOP
	Requests the service to stop.
SERVICE_CONTROL_PAUSE
	Requests the service to pause.
SERVICE_CONTROL_CONTINUE
	Requests the paused service to resume.
SERVICE_CONTROL_INTERROGATE
	Requests the service to immediately report its current status information to the service control manager.
SERVICE_CONTROL_SHUTDOWN
	Requests the service to perform cleanup tasks, because the system is shutting down. Due to extremely limited time available for shutdown, this control should only be used by services that absolutely need to shut down —  for instance, when the eventlog service needs to clear a dirty bit in the files that it maintains, or when the server service needs to shut down so that network connections aren't made when the system is in the shutdown state. If the service takes time to shut down, and sends out STOP_PENDING status messages, it is highly recommended that these messages include a waithint so that the service controller will know how long to wait before indicating to the system that service shutdown is complete. The system gives the service control manager a limited amount of time (about 20 seconds) to complete service shutdown, after which time system shutdown proceeds regardless of whether service shutdown is complete.
Return Value

This function does not return a value.

Remarks

When a Win32 service is started, its ServiceMain function should immediately call the RegisterServiceCtrlHandler function to specify a Handler function to handle control requests.

Whenever it receives a control request from the service control manager, the control dispatcher in the main thread of a Win32 service process invokes the control handler function for the specified service. After handling the control request, the control handler must call the SetServiceStatus function to report its current status to the service control manager.

See Also

RegisterServiceCtrlHandler, ServiceMain, SetServiceStatus


HandlerRoutine
 HandlerRoutine  QuickInfo  Overview  Group

A HandlerRoutine function is a function that a console process specifies to handle control signals received by the process. The function can have any name.

BOOL HandlerRoutine(

DWORD  dwCtrlType	//  control signal type
);
Parameters

dwCtrlType

Indicates the type of control signal received by the handler. This value is one of the following:

Signal	Description
CTRL_C_EVENT	A CTRL+C signal was received, either from keyboard input or from a signal generated by the GenerateConsoleCtrlEvent function.
CTRL_BREAK_EVENT	A CTRL+BREAK signal was received, either from keyboard input or from a signal generated by GenerateConsoleCtrlEvent.
CTRL_CLOSE_EVENT	A signal that the system sends to all processes attached to a console when the user closes the console (either by choosing the Close command from the console window's System menu, or by choosing the End Task command from the Task List).
CTRL_LOGOFF_EVENT	A signal that the system sends to all console processes when a user is logging off. This signal does not indicate which user is logging off, so no assumptions can be made.
CTRL_SHUTDOWN_EVENT	A signal that the system sends to all console processes when the system is shutting down.
Return Value

If the function handles the control signal, it should return TRUE. If it returns FALSE, the next handler function in the list of handlers for this process is used.

Remarks

Each console process has its own list of HandlerRoutine functions. Initially, this list contains only a default handler function that calls ExitProcess. A console process adds or removes additional handler functions by calling the SetConsoleCtrlHandler function, which does not affect the list of handler functions for other processes. When a console process receives any of the control signals, its handler functions are called on a last-registered, first-called basis until one of the handlers returns TRUE. If none of the handlers returns TRUE, the default handler is called.

The CTRL_CLOSE_EVENT, CTRL_LOGOFF_EVENT, and CTRL_SHUTDOWN_EVENT signals give the process an opportunity to clean up before termination. A HandlerRoutine called to handle any of these signals can do one of the following after performing any cleanup operations:

•	Call the ExitProcess function to terminate the process.

•	Return FALSE. If none of the registered handler functions returns TRUE, the default handler terminates the process.

•	Return TRUE. In this case, no other handler functions are called, and the system displays a pop-up dialog box that asks the user whether to terminate the process. The system also displays the dialog box if the process does not respond within a certain time-out period (5 seconds for CTRL_CLOSE_EVENT, and 20 seconds for CTRL_LOGOFF_EVENT and CTRL_SHUTDOWN_EVENT).

A process can use the SetProcessShutdownParameters function to prevent the CTRL_LOGOFF_EVENT and CTRL_SHUTDOWN_EVENT dialog box from being displayed. In this case, the system just terminates the process when a HandlerRoutine returns TRUE or when the time-out period elapses.

See Also

ExitProcess, GenerateConsoleCtrlEvent, GetProcessShutdownParameters, SetConsoleCtrlHandler, SetProcessShutdownParameters


HeapAlloc
 HeapAlloc  QuickInfo  Overview  Group

The HeapAlloc function allocates a block of memory from a heap. The allocated memory is not movable.

LPVOID HeapAlloc(

HANDLE  hHeap,	// handle to the private heap block
DWORD  dwFlags,	// heap allocation control flags
DWORD  dwBytes	// number of bytes to allocate
);
Parameters

hHeap

Specifies the heap from which the memory will be allocated. This parameter is a handle returned by the HeapCreate or GetProcessHeap function.

dwFlags

Specifies several controllable aspects of heap allocation. Specifying any of these flags will override the corresponding flag specified when the heap was created with HeapCreate. You can specify one or more of the following flags:

Flag	Meaning
HEAP_GENERATE_EXCEPTIONS	Specifies that the operating system will raise an exception to indicate a function failure, such as an out-of-memory condition, instead of returning NULL.
HEAP_NO_SERIALIZE	Specifies that mutual exclusion will not be used while this function is accessing the heap. For more information about HEAP_NO_SERIALIZE, see the Remarks section of HeapCreate.
HEAP_ZERO_MEMORY	Specifies that the allocated memory will be initialized to zero.
dwBytes

Specifies the number of bytes to be allocated.

If the heap specified by the hHeap parameter is a "non-growable" heap, dwBytes must be less than 0x7FFF8. You create a non-growable heap by calling the HeapCreate function with a nonzero value.

Return Value

If the function succeeds, the return value is a pointer to the allocated memory block.

If the function fails and you have not specified HEAP_GENERATE_EXCEPTIONS, the return value is NULL.

If the function fails and you have specified HEAP_GENERATE_EXCEPTIONS, the function may generate the following exceptions:

Value	Meaning
STATUS_NO_MEMORY	The allocation attempt failed because of a lack of available memory or heap corruption.
STATUS_ACCESS_VIOLATION	The allocation attempt failed because of heap corruption or improper function parameters.
Note that heap corruption can lead to either exception. It depends upon the nature of the heap corruption.

If the function fails, it does not call SetLastError. An application cannot call GetLastError for extended error information.

Remarks

If HeapAlloc succeeds, it allocates at least the amount of memory requested. If the actual amount allocated is greater than the amount requested, the process can use the entire amount. To determine the actual size of the allocated block, use the HeapSize function.

To free a block of memory allocated by HeapAlloc, use the HeapFree function.

Memory allocated by HeapAlloc is not movable. Since the memory is not movable, it is possible for the heap to become fragmented.

Note that if HEAP_ZERO_MEMORY is not specified, the allocated memory will not be initialized to zero.

See Also

GetProcessHeap, HeapCreate, HeapDestroy, HeapFree, HeapReAlloc, HeapSize, SetLastError


HeapCompact
 HeapCompact  QuickInfo  Overview  Group

The HeapCompact function attempts to compact a specified heap. It compacts the heap by coalescing adjacent free blocks of memory and decommitting large free blocks of memory.

UINT HeapCompact(

HANDLE  hHeap,	// handle to the heap to compact
DWORD  dwFlags	// bit-flags that control heap access during function operation
);
Parameters

hHeap

Handle to the heap that the function will attempt to compact.

dwFlags

A set of bit flags that control heap access during function operation. The following bit flag has meaning:

Value	Meaning
HEAP_NO_SERIALIZE	If this flag is set, heap access is not serialized while the HeapCompact function accesses the heap; heap access is not mutually exclusive. It is safe to set this flag only in a limited set of specific situations. For a discussion of those situations and heap serialization in general, see the Remarks section of  HeapCreate .  If this flag is clear, heap access is serialized while HeapCompact accesses the heap; heap access is mutually exclusive. This is the safe and simple default condition.
Return Value

If the function succeeds, the return value is the size, in bytes, of the largest committed free block in the heap. This is an unsigned integer value.

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

In the unlikely case that there is absolutely no space available in the heap, the function return value is zero, and GetLastError returns the value NO_ERROR.

Remarks

There is no guarantee that an application can successfully allocate a memory block of the size returned by HeapCompact. Other threads or the commit threshold might prevent such an allocation.

See Also

HeapCreate, HeapValidate


HeapCreate
 HeapCreate  QuickInfo  Overview  Group

The HeapCreate function creates a heap object that can be used by the calling process. The function reserves a contiguous block in the virtual address space of the process and allocates physical storage for a specified initial portion of this block.

HANDLE HeapCreate(

DWORD  flOptions,	// heap allocation flag
DWORD  dwInitialSize,	// initial heap size
DWORD  dwMaximumSize	// maximum heap size
);
Parameters

flOptions

Specifies optional attributes for the new heap. These flags will affect subsequent access to the new heap through calls to the heap functions (HeapAlloc, HeapFree, HeapReAlloc, and HeapSize). You can specify one or more of the following flags:

Flag	Meaning
HEAP_GENERATE_EXCEPTIONS	Specifies that the system will raise an exception to indicate a function failure, such as an out-of-memory condition, instead of returning NULL.
HEAP_NO_SERIALIZE	Specifies that mutual exclusion will not be used when the heap functions allocate and free memory from this heap. The default, occurring when the HEAP_NO_SERIALIZE flag is not specified, is to serialize access to the heap. Serialization of heap access allows two or more threads to simultaneously allocate and free memory from the same heap.
dwInitialSize

Specifies the initial size, in bytes, of the heap. This value determines the initial amount of physical storage that is allocated for the heap. The value is rounded up to the next page boundary. To determine the size of a page on the host computer, use the GetSystemInfo function.

dwMaximumSize

If dwMaximumSize is a nonzero value, it specifies the maximum size, in bytes, of the heap. The HeapCreate function rounds dwMaximumSize up to the next page boundary, and then reserves a block of that size in the process's virtual address space for the heap. If allocation requests made by the HeapAlloc or HeapReAlloc functions exceed the initial amount of physical storage specified by dwInitialSize, the system allocates additional pages of physical storage for the heap, up to the heap's maximum size.

In addition, if dwMaximumSize is nonzero, the heap cannot grow, and an absolute limitation arises: the maximum size of a memory block in the heap is a bit less than 0x7FFF8 bytes. Requests to allocate larger blocks will fail, even if the maximum size of the heap is large enough to contain the block.

If dwMaximumSize is zero, it specifies that the heap is growable. The heap's size is limited only by available memory. Requests to allocate blocks larger than 0x7FFF8 bytes do not automatically fail; the system calls VirtualAlloc to obtain the memory needed for such large blocks. Applications that need to allocate large memory blocks should set dwMaximumSize to zero.

Return Value

If the function succeeds, the return value is a handle of the newly created heap.

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

Remarks

The HeapCreate function creates a private heap object from which the calling process can allocate memory blocks by using the HeapAlloc function. The initial size determines the number of committed pages that are initially allocated for the heap. The maximum size determines the total number of reserved pages. These pages create a contiguous block in the process's virtual address space into which the heap can grow. If requests by HeapAlloc exceed the current size of committed pages, additional pages are automatically committed from this reserved space, assuming that the physical storage is available.

The memory of a private heap object is accessible only to the process that created it. If a dynamic-link library (DLL) creates a private heap, the heap is created in the address space of the process that called the DLL, and it is accessible only to that process.

The system uses memory from the private heap to store heap support structures, so not all of the specified heap size is available to the process. For example, if the HeapAlloc function requests 64 kilobytes (K) from a heap with a maximum size of 64K, the request may fail because of system overhead.

If the HEAP_NO_SERIALIZE flag is not specified (the simple default), the heap will serialize access within the calling process. Serialization ensures mutual exclusion when two or more threads attempt to simultaneously allocate or free blocks from the same heap. There is a small performance cost to serialization, but it must be used whenever multiple threads allocate and free memory from the same heap.

Setting the HEAP_NO_SERIALIZE flag eliminates mutual exclusion on the heap. Without serialization, two or more threads that use the same heap handle might attempt to allocate or free memory simultaneously, likely causing corruption in the heap. The HEAP_NO_SERIALIZE flag can, therefore, be safely used only in the following situations:

•	The process has only one thread.

•	The process has multiple threads, but only one thread calls the heap functions for a specific heap.

•	The process has multiple threads, and the application provides its own mechanism for mutual exclusion to a specific heap.

See Also

GetProcessHeap, GetProcessHeaps, GetSystemInfo, HeapAlloc, HeapDestroy, HeapFree, HeapReAlloc, HeapSize, HeapValidate, VirtualAlloc,


HeapDestroy
 HeapDestroy  QuickInfo  Overview  Group

The HeapDestroy function destroys the specified heap object. HeapDestroy decommits and releases all the pages of a private heap object, and it invalidates the handle of the heap.

BOOL HeapDestroy(

HANDLE  hHeap	// handle to the heap
);
Parameters

hHeap

Specifies the heap to be destroyed. This parameter should be a heap handle returned by the HeapCreate function. A heap handle returned by the GetProcessHeap function should not be used.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

Processes can call HeapDestroy without first calling the HeapFree function to free memory allocated from the heap.

See Also

GetProcessHeap, HeapAlloc, HeapCreate, HeapFree, HeapReAlloc, HeapSize


HeapFree
 HeapFree  QuickInfo  Overview  Group

The HeapFree function frees a memory block allocated from a heap by the HeapAlloc or HeapReAlloc function.

BOOL HeapFree(

HANDLE  hHeap,	// handle to the heap
DWORD  dwFlags,	// heap freeing flags
LPVOID  lpMem	// pointer to the memory to free
);
Parameters

hHeap

Specifies the heap whose memory block the function frees. This parameter is a handle returned by the HeapCreate or GetProcessHeap function.

dwFlags

Specifies several controllable aspects of freeing a memory block. Only one flag is currently defined; however, all other flag values are reserved for future use. Specifying this flag will override the corresponding flag specified in the flOptions parameter when the heap was created by using the HeapCreate function:

Flag	Meaning
HEAP_NO_SERIALIZE	Specifies that mutual exclusion will not be used while the function is accessing the heap. For more information about HEAP_NO_SERIALIZE, see the Remarks for the HeapCreate function.
lpMem

Points to the memory block to free. This pointer is returned by the HeapAlloc or HeapReAlloc function.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, it returns FALSE and calls SetLastError. An application can call GetLastError for extended error information.

See Also

GetProcessHeap, HeapAlloc, HeapCreate, HeapDestroy, HeapReAlloc, HeapSize, SetLastError


HeapLock
 HeapLock  QuickInfo  Overview  Group

The HeapLock function attempts to acquire the critical section object, or lock, that is associated with a specified heap.

If the function succeeds, the calling thread owns the heap lock. Only the calling thread will be able to allocate or release memory from the heap. The execution of any other thread of the calling process will be blocked if that thread attempts to allocate or release memory from the heap. Such threads will remain blocked until the thread that owns the heap lock calls the HeapUnlock function.

BOOL HeapLock(

HANDLE  hHeap	// handle to the heap to lock for exclusive thread access
);
Parameters

hHeap

Handle to the heap to lock for exclusive access by the calling thread.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The HeapLock function is primarily useful for preventing the allocation and release of heap memory by other threads while the calling thread uses the HeapWalk function.

Each call to HeapLock must be matched by a corresponding call to the HeapUnlock function. Failure to call HeapUnlock will block the execution of any other threads of the calling process that attempt to access the heap.

See Also

HeapUnlock, HeapWalk


HeapReAlloc
 HeapReAlloc  QuickInfo  Overview  Group

The HeapReAlloc function reallocates a block of memory from a heap. This function enables you to resize a memory block and change other memory block properties. The allocated memory is not movable.

LPVOID HeapReAlloc(

HANDLE  hHeap,	// handle to a heap block
DWORD  dwFlags,	// heap reallocation flags
LPVOID  lpMem,	// pointer to the memory to reallocate
DWORD  dwBytes	// number of bytes to reallocate
);
Parameters

hHeap

Specifies the heap from which the memory will be reallocated. This is a handle returned by the HeapCreate or GetProcessHeap function.

dwFlags

Specifies several controllable aspects of heap reallocation. Specifying any of these flags will override the corresponding flag specified in the flOptions parameter when the heap was created by using the HeapCreate function. You can specify one or more of the following flags:

Flag	Meaning
HEAP_GENERATE_EXCEPTIONS	Specifies that the operating-system will raise an exception to indicate a function failure, such as an out-of-memory condition, instead of returning NULL.
HEAP_NO_SERIALIZE	Specifies that mutual exclusion will not be used while this function is accessing the heap. For more information about HEAP_NO_SERIALIZE, see the Remarks section of HeapCreate.
HEAP_REALLOC_IN_PLACE_ONLY	Specifies that there can be no movement when reallocating a memory block to a larger size. If this flag is not specified and the reallocation request is for a larger size, the function may move the block to a new location. If this flag is specified and the block cannot be enlarged without moving, the function will fail, leaving the original memory block unchanged.
HEAP_ZERO_MEMORY	If the reallocation request is for a larger size, this flag specifies that the additional region of memory beyond the original size will be initialized to zero. The contents of the memory block up to its original size are unaffected.
lpMem

Points to the block of memory that the function reallocates. This pointer is returned by an earlier call to the HeapAlloc or HeapReAlloc function.

dwBytes

Specifies the new size of the memory block, in bytes. A memory block's size can be increased or decreased by using this function.

If the heap specified by the hHeap parameter is a "non-growable" heap, dwBytes must be less than 0x7FFF8. You create a non-growable heap by calling the HeapCreate function with a nonzero value.

Return Value

If the function succeeds, the return value is a pointer to the reallocated memory block.

If the function fails and you have not specified HEAP_GENERATE_EXCEPTIONS, the return value is NULL.

If the function fails and you have specified HEAP_GENERATE_EXCEPTIONS, the function may generate the following exceptions:

Value	Meaning
STATUS_NO_MEMORY	The reallocation attempt failed for lack of available memory.
STATUS_ACCESS_VIOLATION	The reallocation attempt failed because of heap corruption or improper function parameters.
If the function fails, it calls SetLastError. An application can call GetLastError for extended error information.

Remarks

If HeapReAlloc succeeds, it allocates at least the amount of memory requested. If the actual amount allocated is greater than the amount requested, the process can use the entire amount. To determine the actual size of the reallocated block, use the HeapSize function.

To free a block of memory allocated by HeapReAlloc, use the HeapFree function.

See Also

GetProcessHeap, HeapAlloc, HeapCreate, HeapDestroy, HeapFree, HeapSize, SetLastError


HeapSize
 HeapSize  QuickInfo  Overview  Group

The HeapSize function returns the size, in bytes, of a memory block allocated from a heap by the HeapAlloc or HeapReAlloc function.

DWORD HeapSize(

HANDLE  hHeap,	// handle to the heap
DWORD dwFlags,	// heap size control flags
LPCVOID  lpMem	// pointer to memory to return size for
);
Parameters

hHeap

Specifies the heap in which the memory block resides. This handle is returned by the HeapCreate or GetProcessHeap function.

dwFlags

Specifies several controllable aspects of accessing the memory block. Only one flag is currently defined; however, all other flag values are reserved for future use. Specifying this flag will override the corresponding flag specified in the flOptions parameter when the heap was created by using the HeapCreate function:

Value	Meaning
HEAP_NO_SERIALIZE	Specifies that mutual exclusion will not be used while the function is accessing the heap. For more information about HEAP_NO_SERIALIZE, see the Remarks for HeapCreate.
lpMem

Points to the memory block whose size the function will obtain. This is a pointer returned by the HeapAlloc or HeapReAlloc function.

Return Value

If the function succeeds, the return value is the size, in bytes, of the allocated memory block.

If the function fails, the return value is 0xFFFFFFFF. The function does not call SetLastError. An application cannot call GetLastError for extended error information.

See Also

GetProcessHeap, HeapAlloc, HeapCreate, HeapDestroy, HeapFree, HeapReAlloc, SetLastError


HeapUnlock
 HeapUnlock  QuickInfo  Overview  Group

The HeapUnlock function releases ownership of the critical section object, or lock, that is associated with a specified heap. The HeapUnlock function reverses the action of the HeapLock function.

BOOL HeapUnlock(

HANDLE  hHeap	// handle to the heap to unlock
);
Parameters

hHeap

Handle to the heap to unlock.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The HeapLock function is primarily useful for preventing the allocation and release of heap memory by other threads while the calling thread uses the HeapWalk function. The HeapUnlock function is the inverse of HeapLock.

Each call to HeapLock must be matched by a corresponding call to the HeapUnlock function. Failure to call HeapUnlock will block the execution of any other threads of the calling process that attempt to access the heap.

See Also

HeapLock, HeapWalk


HeapValidate
 HeapValidate  QuickInfo  Overview  Group

The HeapValidate function attempts to validate a specified heap. The function scans all the memory blocks in the heap, and verifies that the heap control structures maintained by the operating system's heap manager are in a consistent state. You can also use the HeapValidate function to validate a single memory block within a specified heap, without checking the validity of the entire heap.

BOOL HeapValidate(

HANDLE  hHeap,	// handle to the heap of interest
DWORD  dwFlags,	// bit flags that control heap access during function operation
LPCVOID  lpMem	// optional pointer to individual memory block to validate
);
Parameters

hHeap

Handle to the heap of interest. The HeapValidate function attempts to validate this heap, or a single memory block within this heap.

dwFlags

A set of bit flags that control heap access during function operation. The following bit flag has meaning:

Value	Meaning
HEAP_NO_SERIALIZE	If this flag is set, heap access is not serialized while the HeapValidate function accesses the heap; heap access is not mutually exclusive. It is safe to set this flag only in a limited set of specific situations. For a discussion of those situations and heap serialization in general, see the Remarks section of HeapCreate .  If this flag is clear, heap access is serialized while HeapValidate accesses the heap; heap access is mutually exclusive. This is the safe and simple default condition.
lpMem

Points to a memory block within the specified heap. This parameter may be NULL.

If this parameter is NULL, the function attempts to validate the entire heap specified by hHeap.

If this parameter is not NULL, the function attempts to validate the memory block pointed to by lpMem. It does not attempt to validate the rest of the heap.

Return Value

If the specified heap or memory block is valid, the return value is TRUE.

If the specified heap or memory block is invalid, the return value is FALSE. On a system set up for debugging, the HeapValidate function then displays debugging messages that describe the part of the heap or memory block that is invalid, and stops at a hard-coded breakpoint so that you can examine the system to determine the source of the invalidity. The HeapValidate function does not set the thread's last error value.

Remarks

There are heap control structures for each memory block in a heap, and for the heap as a whole. When you use the HeapValidate function to validate a complete heap, it checks all of these control structures for consistency.

When you use HeapValidate to validate a single memory block within a heap, it checks only the control structures pertaining to that element. HeapValidate can only validate allocated memory blocks. Calling HeapValidate on a freed memory block will return FALSE because there are no control structures to validate.

If you want to validate the heap elements enumerated by the HeapWalk function, you should only call HeapValidate on the elements that have the PROCESS_HEAP_ENTRY_BUSY bit flag in the wFlags member of the PROCESS_HEAP_ENTRY structure. HeapValidate returns FALSE for all heap elements that do not have this bit set.

See Also

HeapCreate, HeapWalk, PROCESS_HEAP_ENTRY


HeapWalk
 HeapWalk  QuickInfo

The HeapWalk function enumerates the memory blocks in a specified heap.

BOOL HeapWalk(

HANDLE  hHeap,	// handle to the heap to enumerate
LPPROCESS_HEAP_ENTRY  lpEntry	// points to structure that maintains enumeration state information
);
Parameters

hHeap

Handle to the heap whose memory blocks you wish to enumerate.

dwFlags

Points to a PROCESS_HEAP_ENTRY structure that maintains state informationfor a particular heap enumeration.

If the HeapWalk function succeeds, returning the value TRUE, this structure's members contain information about the next memory block in the heap.

To initiate a heap enumeration, set the lpData field of the PROCESS_HEAP_ENTRY structure to NULL. To continue a particular heap enumeration, call the HeapWalk function repeatedly, with no changes to hHeap, lpEntry, or any of the members of the PROCESS_HEAP_ENTRY structure.

Return Value

If the function succeeds, the return value is TRUE.

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

If the heap enumeration terminates successfully by reaching the end of the heap, the function returns FALSE, and GetLastError returns the error code ERROR_NO_MORE_ITEMS.

Remarks

To initiate a heap enumeration, call HeapWalk with the lpData field of the PROCESS_HEAP_ENTRY structure pointed to by lpEntry set to NULL.

To continue a heap enumeration, call HeapWalk with the same hHeap and lpEntry values, and with the PROCESS_HEAP_ENTRY structure unchanged from the preceding call to HeapWalk. Repeat this process until you have no need for further enumeration, or until the function returns FALSE and GetLastError returns ERROR_NO_MORE_ITEMS, indicating that all of the heap's memory blocks have been enumerated.

No special call of HeapWalk is needed to terminate the heap enumeration, since no enumeration state data is maintained outside the contents of the PROCESS_HEAP_ENTRY structure.

HeapWalk can fail in a multithreaded application if the heap is not locked during the heap enumeration. Use the HeapLock and HeapUnlock functions to control heap locking during heap enumeration.

See Also

HeapLock, HeapUnlock, HeapValidate, PROCESS_HEAP_ENTRY


HideCaret
 HideCaret  QuickInfo  Overview  Group

The HideCaret function removes the caret from the screen. Hiding a caret does not destroy its current shape or invalidate the insertion point.

BOOL HideCaret(

HWND  hWnd	// handle to the window with the caret
);
Parameters

hWnd

Identifies the window that owns the caret. If this parameter is NULL, HideCaret searches the current task for the window that owns the caret.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. 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.

See Also

CreateCaret, DestroyCaret, GetCaretPos, SetCaretPos, ShowCaret


HiliteMenuItem
 HiliteMenuItem  QuickInfo  Overview  Group

The HiliteMenuItem function highlights or removes the highlighting from an item in a menu bar.

BOOL HiliteMenuItem(

HWND  hwnd,	// handle to the window with the menu
HMENU  hmenu,	// handle to the menu
UINT  uItemHilite,	// menu item to highlight or unhighlight
UINT  uHilite	// highlight flags
);
Parameters

hwnd

Identifies the window that contains the menu.

hmenu

Identifies the menu bar that contains the item to be highlighted.

uItemHilite

Specifies the menu item to be highlighted. This parameter is either the identifier of the menu item or the offset of the menu item in the menu bar, depending on the value of the uHilite parameter.

uHilite

Specifies flags that control the interpretation of the uItemHilite parameter and indicates whether the menu item is highlighted. This parameter must be a combination of either MF_BYCOMMAND or MF_BYPOSITION and MF_HILITE or MF_UNHILITE.

Value	Meaning
MF_BYCOMMAND	Indicates that uItemHilite gives the identifier of the menu item.
MF_BYPOSITION	Indicates that uItemHilite gives the zero-based relative position of the menu item.
MF_HILITE	Highlights the menu item. If this flag is not specified, the highlighting is removed from the item.
MF_UNHILITE	Removes highlighting from the menu item.
Return Value

If the menu item is set to the specified highlight state, the return value is TRUE; otherwise, it is FALSE.

Remarks

The MF_HILITE and MF_UNHILITE flags can be used only with the HiliteMenuItem function; they cannot be used with the ModifyMenu function.

See Also

ModifyMenu


htonl
 htonl  QuickInfo

The Windows Sockets htonl function converts a u_long from host to network byte order.

This function takes a 32-bit number in host byte order and returns a 32-bit number in network byte order.

u_long htonl (

u_long hostlong
);
Parameters

hostlong

A 32-bit number in host byte order.

Return Value

The htonl function returns the value in network byte order.

See Also

htons, ntohl, ntohs


htons
 htons  QuickInfo

The Windows Sockets htons function converts a u_short from host byte order to network byte order.

u_short htons (

u_short hostshort
);
Parameters

hostshort

A 16-bit number in host byte order.

Return Value

The htons function returns the value in network byte order.

Remarks

This function takes a 16-bit number in host byte order and returns a 16-bit number in network byte order.

See Also

htonl, ntohl, ntohs


ImageList_Add [New - Windows NT]
 ImageList_Add  QuickInfo  Overview  Group

[New - Windows NT]

The ImageList_Add function adds an image or images to an image list.

int WINAPI ImageList_Add(

HIMAGELIST  himl,	// handle to the image list
HBITMAP  hbmImage,	// handle to the bitmap containing the image
HBITMAP  hbmMask	// handle to the bitmap containing the mask
);
Parameters

himl

Handle to the image list.

hbmImage

Handle to the bitmap that contains the image or images. The number of images is inferred from the width of the bitmap.

hbmMask

Handle to the bitmap that contains the mask. If no mask is used with the image list, this parameter is ignored.

Return Value

If the function succeeds, the return value is the index of the first new image.

If the function fails, the return value is − 1.

Remarks

The ImageList_Add function copies the bitmap to an internal data structure. Be sure to use the DeleteObject function to delete hbmImage and hbmMask after the function returns.

See Also

DeleteObject


ImageList_AddIcon [New - Windows NT]
 ImageList_AddIcon  QuickInfo

[New - Windows NT]

The ImageList_AddIcon macro adds an icon or cursor to an image list. ImageList_AddIcon calls the ImageList_ReplaceIcon function.

int ImageList_AddIcon(

HIMAGELIST  himl,	// handle to the image list
HICON hicon	// handle to the icon or cursor
);
Parameters

himl

Handle to the image list. If this parameter identifies a masked image list, the macro copies both the image and mask bitmaps of the icon or cursor. If this parameter identifies a nonmasked image list, the macro copies only the image bitmap.

hicon

Handle to the icon or cursor that contains the bitmap and mask for the new image.

Return Value

If the macro succeeds, the return value is the index of the new image.

If the macro fails, the return value is  − 1.

Remarks

Because the system does not save hicon, you can destroy it after the macro returns if the icon or cursor was created by the CreateIcon function. You do not need to destroy hicon if it was loaded by the LoadIcon function; the system automatically frees an icon resource when it is no longer needed.

The ImageList_AddIcon macro is defined as follows:

#define  ImageList_AddIcon(himl, hicon) ImageList_ReplaceIcon(himl, -1, hicon)

See Also

CreateIcon, ImageList_ReplaceIcon, LoadIcon


ImageList_AddMasked [New - Windows NT]
 ImageList_AddMasked  QuickInfo  Overview  Group

[New - Windows NT]

The ImageList_AddMasked function adds an image or images to an image list, generating a mask from the specified bitmap.

int WINAPI ImageList_AddMasked(

HIMAGELIST  himl,	// handle to the image list
HBITMAP  hbmImage,	// handle to the bitmap
COLORREF  crMask	// color used to generate mask
);
Parameters

himl

Handle to the image list.

hbmImage

Handle to the bitmap that contains one or more images. The number of images is inferred from the width of the bitmap.

crMask

Color used to generate the mask. Each pixel of this color in the specified bitmap is changed to black, and the corresponding bit in the mask is set to one.

Return Value

If the function succeeds, the return value is the index of the first new image.

If the function fails, the return value is  − 1.

Remarks

The ImageList_AddMasked function copies the bitmap to an internal data structure. Be sure to use the DeleteObject function to delete hbmImage and crMask after the function returns.

See Also

DeleteObject


ImageList_BeginDrag [New - Windows NT]
 ImageList_BeginDrag  QuickInfo  Overview  Group

[New - Windows NT]

The ImageList_BeginDrag function begins dragging an image.

BOOL WINAPI ImageList_BeginDrag(

HIMAGELIST  himlTrack,
int  iTrack,
int  dxHotspot,
int  dyHotspot
);
Parameters

himlTrack

Handle to the image list.

iTrack

Index of the image to drag.

dxHotspot and dyHotspot

Location of the drag position relative to the upper-left corner of the image.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

This function creates a temporary image list that is used for dragging. In response to subsequent WM_MOUSEMOVE messages, you can move the drag image by using the ImageList_DragMove function. To end the drag operation, you can use the ImageList_EndDrag function.

See Also

ImageList_DragMove, ImageList_EndDrag, WM_MOUSEMOVE


ImageList_Create [New - Windows NT]
 ImageList_Create  QuickInfo  Overview  Group

[New - Windows NT]

The ImageList_Create function creates a new image list.

HIMAGELIST WINAPI ImageList_Create(

int  cx,
int  cy,
UINT  flags,
int  cInitial,
int  cGrow
);
Parameters

cx

Specifies the width, in pixels, of each image.

cy

Specifies the height, in pixels, of each image.

flags

Flags specifying the type of image list to create. This parameter can be a combination of the following values:

Value	Meaning
ILC_COLOR	Use the default behavior if none of the other ILC_COLOR* flags is specified. Typically, the default is ILC_COLOR4; but for older display drivers, the default is ILC_COLORDDB.
ILC_COLOR4	Use a 4-bit (16 color) device-independent bitmap (DIB) section as the bitmap for the image list.
ILC_COLOR8	Use an 8-bit DIB section. The colors used for the color table are the same colors as the halftone palette.
ILC_COLOR16	Use a 16-bit  (32/64k color) DIB section.
ILC_COLOR24	Use a 24-bit DIB section.
ILC_COLOR32	Use a 32-bit DIB section.
ILC_COLORDDB	Use a device-dependent bitmap.
ILC_MASK	Uses a mask. The image list contains two bitmaps, one of which is a monochrome bitmap used as a mask. If this value is not included, the image list contains only one bitmap.
ILC_PALETTE	Uses a color palette with the image list.
cInitial

Number of images that the image list initially contains.

cGrow

Amount of images by which the image list can grow when the system needs to resize the list to make room for new images. This parameter represents the number of new images that the resized image list can contain.

Return Value

If the function succeeds, the return value is the handle to the image list.

If the function fails, the return value NULL.


ImageList_Destroy [New - Windows NT]
 ImageList_Destroy  QuickInfo  Overview  Group

[New - Windows NT]

The ImageList_Destroy function destroys an image list.

BOOL WINAPI ImageList_Destroy(

HIMAGELIST  himl
);
Parameters

himl

Handle to the image list to destroy.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.


ImageList_DragEnter [New - Windows NT]
 ImageList_DragEnter  QuickInfo  Overview  Group

[New - Windows NT]

The ImageList_DragEnter function locks updates to the specified window during a drag operation and displays the drag image at the specified position within the window.

BOOL WINAPI ImageList_DragEnter(

HWND  hwndLock,
int  x,
int  y
);
Parameters

hwndLock

Handle to the window that owns the drag image.

x

Specifies the x-coordinate at which to display the drag image. The coordinate is relative to the upper-left corner of the window, not the client area.

y

Specifies the y-coordinate at which to display the drag image. The coordinate is relative to the upper-left corner of the window, not the client area.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

To begin a drag operation, use the ImageList_BeginDrag function.

See Also

ImageList_BeginDrag


ImageList_DragLeave [New - Windows NT]
 ImageList_DragLeave  QuickInfo  Overview  Group

[New - Windows NT]

The ImageList_DragLeave function unlocks the specified window and hides the drag image, allowing the window to be updated.

BOOL WINAPI ImageList_DragLeave(

HWND  hwndLock	//
);
Parameters

hwndLock

Handle to the window that owns the drag image.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.


ImageList_DragMove [New - Windows NT]
 ImageList_DragMove  QuickInfo  Overview  Group

[New - Windows NT]

The ImageList_DragMove function moves the image that is being dragged during a drag-and-drop operation. This function is typically called in response to a WM_MOUSEMOVE message.

BOOL WINAPI ImageList_DragMove(

int  x,	//
int  y	//
);
Parameters

x and y

New drag position.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

To begin a drag operation, use the ImageList_BeginDrag function.

See Also

ImageList_BeginDrag, WM_MOUSEMOVE


ImageList_DragShowNolock [New - Windows NT]
 ImageList_DragShowNolock  QuickInfo  Overview  Group

[New - Windows NT]

The ImageList_DragShowNolock function shows or hides the image being dragged.

BOOL WINAPI ImageList_DragShowNolock(

BOOL  fShow	//
);
Parameters

fShow

Value specifying whether to show or hide the image being dragged. Specify TRUE to show the image, FALSE to hide the image.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.


ImageList_Draw [New - Windows NT]
 ImageList_Draw  QuickInfo  Overview  Group

[New - Windows NT]

The ImageList_Draw function draws an image list item in the specified device context.

BOOL WINAPI ImageList_Draw(

HIMAGELIST  himl,
int  i,
HDC  hdcDst,
int  x,
int  y,
UINT  fStyle
);
Parameters

himl and i

Handle to the image list, and the index of the image to draw.

hdcDst

Handle to the destination device context.

x

Specifies the x-coordinate at which to draw within the specified device context.

y

Specifies the y-coordinate at which to draw within the specified device context.

fStyle

Flag specifying the drawing style. This parameter can be one or more of the following values:

Value	Meaning
ILD_BLEND25,  ILD_FOCUS	Draws the image, blending 25 percent with the system highlight color. This value has no effect if the image list does not contain a mask.
ILD_BLEND50,  ILD_SELECTED,  ILD_BLEND	Draws the image, blending 50 percent with the system highlight color. This value has no effect if the image list does not contain a mask.
ILD_MASK	Draws the mask.
ILD_NORMAL	Draws the image using the background color for the image list. If the background color is the CLR_NONE value, the image is drawn transparently using the mask.
ILD_TRANSPARENT	Draws the image transparently using the mask, regardless of the background color. This value has no effect if the image list does not contain a mask.
Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.


ImageList_DrawEx [New - Windows NT]
 ImageList_DrawEx  QuickInfo  Overview  Group

[New - Windows NT]

The ImageList_DrawEx function draws an image list item in the specified device context. The function uses the specified drawing style and blends the image with the specified color.

BOOL WINAPI ImageList_DrawEx(

HIMAGELIST  himl,
int  i,
int  x,
int  y,
int  dx,
int  dy,
COLORREF  rgbBk,
COLORREF  rgbFg,
UINT  fStyle
);
Parameters

himl

Handle to the image list

i

Index of the image to draw.

hdcDst

Handle to the destination device context.

x

Specifies the x-coordinate at which to draw within the specified device context.

y

Specifies the y-coordinate at which to draw within the specified device context.

dx and dy

Portion of the image to draw, relative to the upper-left corner of the image. If these parameters are zero, the function draws the entire image. The function does not ensure that the parameters are valid.

rgbBk

Background color of the image. This parameter can be an application-defined RGB value or one of the following values:

Value	Meaning
CLR_NONE	No background color. The image is drawn transparently.
CLR_DEFAULT	Default background color. The image is drawn using the background color of the image list.
This parameter is used only if the image list identified by himl was created with the ILC_MASK value.

rgbFg

Foreground color of the image. This parameter can be an application-defined RGB value or one of the following values:

Value	Meaning
CLR_NONE	No blend color. The image is blended with the color of the destination device context.
CLR_DEFAULT	Default foreground color. The image is drawn using the system highlight color as the foreground color.
This parameter is used only if fStyle includes the ILD_BLEND25 or ILD_BLEND50 value.

fStyle

Flag specifying the drawing style. This parameter can be one or more of the following values:

Value	Meaning
ILD_BLEND25,  ILD_FOCUS	Draws the image, blending 25 percent with the blend color specified by rgbFG. This value has no effect if the image list does not contain a mask.
ILD_BLEND50,  ILD_SELECTED,  ILD_BLEND	Draws the image, blending 50 percent with the blend color specified by rgbFG. This value has no effect if the image list does not contain a mask.
ILD_MASK	Draws the mask.
ILD_NORMAL	Draws the image using the background color for the image list. If the background color is the CLR_NONE value, the image is drawn transparently using the mask.
ILD_TRANSPARENT	Draws the image transparently using the mask, regardless of the background color. This value has no effect if the image list does not contain a mask.
See Also

RGB


ImageList_EndDrag [New - Windows NT]
 ImageList_EndDrag  QuickInfo  Overview  Group

[New - Windows NT]

The ImageList_EndDrag function ends a drag operation.

BOOL WINAPI ImageList_EndDrag(VOID)

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.


ImageList_ExtractIcon [New - Windows NT]
 ImageList_ExtractIcon  QuickInfo  Overview  Group

[New - Windows NT]

The ImageList_ExtractIcon function creates an icon or cursor based on an image and mask in an image list. ImageList_ExtractIcon is a macro that calls the ImageList_GetIcon function.

HICON WINAPI ImageList_ExtractIcon(

HINSTANCE  hi,
HIMAGELIST  himl,
int  i
);
Parameters

hi

Ignored; set to zero.

himl

Handle to the image list.

i

Index of the image.

Return Value

If the function succeeds, the return value is the handle of the icon or cursor.

If the function fails, the return value is NULL.

See Also

ImageList_GetIcon


ImageList_GetBkColor [New - Windows NT]
 ImageList_GetBkColor  QuickInfo  Overview  Group

[New - Windows NT]

The ImageList_GetBkColor function retrieves the current background color for an image list.

COLORREF WINAPI ImageList_GetBkColor(

HIMAGELIST  himl
);
Parameters

himl

Handle to the image list.

Return Value

The return value is the background color.


ImageList_GetDragImage [New - Windows NT]
 ImageList_GetDragImage  QuickInfo  Overview  Group

[New - Windows NT]

The ImageList_GetDragImage function retrieves the temporary image list that is used for the drag image. The function also retrieves the current drag position, and the offset of the drag image relative to the drag position.

HIMAGELIST WINAPI ImageList_GetDragImage(

POINT FAR* ppt,
POINT FAR* pptHotspot
);
Parameters

ppt

Pointer to a POINT structure that receives the current drag position. Can be NULL.

pptHotSpot

Pointer to a POINT structure that receives the offset of the drag image relative to the drag position. Can be NULL.

Return Value

If the function succeeds, the return value is the handle of the image list.

If the function fails, the return value is NULL.

Remarks

The temporary image list is destroyed when the ImageList_EndDrag function is called. To begin a drag operation, use the ImageList_BeginDrag function.

See Also

ImageList_BeginDrag, ImageList_EndDrag, POINT


ImageList_GetIcon [New - Windows NT]
 ImageList_GetIcon  QuickInfo  Overview  Group

[New - Windows NT]

The ImageList_GetIcon function creates an icon or cursor based on an image and mask in an image list.

HICON WINAPI ImageList_GetIcon(

HIMAGELIST himl,	//
int  i,	//
UINT  flags	//
);
Parameters

himl

Handle to the image list.

i

Index of the image.

flags

Combination of flags that specify the drawing style. For a list of values, see the description of the ImageList_Draw function.

Return Value

If the function succeeds, the return value is the handle of the icon or cursor.

If the function fails, the return value is NULL.

See Also

ImageList_Draw


ImageList_GetIconSize [New - Windows NT]
 ImageList_GetIconSize  QuickInfo  Overview  Group

[New - Windows NT]

The ImageList_GetIconSize function retrieves the dimensions of images in an image list. All images in an image list have the same dimensions.

BOOL WINAPI ImageList_GetIconSize(

HIMAGELIST  himl,
int FAR  * cx,
int FAR  * cy
);
Parameters

himl

Handle to the image list.

cx

Pointer to integer variable that receives the width, in pixels, of each image.

cy

Pointer to integer variable that receives the height, in pixels, of each image.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.


ImageList_GetImageCount [New - Windows NT]
 ImageList_GetImageCount  QuickInfo  Overview  Group

[New - Windows NT]

The ImageList_GetImageCount function retrieves the number of images in an image list.

int WINAPI ImageList_GetImageCount(;

HIMAGELIST  himl
);
Parameters

himl

Handle to the image list.

Return Value

The ImageList_GetImageCount function returns the number of images.


ImageList_GetImageInfo [New - Windows NT]
 ImageList_GetImageInfo  QuickInfo  Overview  Group

[New - Windows NT]

The ImageList_GetImageInfo function retrieves information about an image.

BOOL WINAPI ImageList_GetImageInfo(

HIMAGELIST  himl,
int  i,
IMAGEINFO FAR*  pImageInfo
);
Parameters

himl

Handle to the image list.

i

Index of the image.

pImageInfo

Pointer to an IMAGEINFO structure that receives information about the image. The information in this structure can be used to directly manipulate the bitmaps for the image.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

See Also

IMAGEINFO


ImageList_LoadBitmap [New - Windows NT]
 ImageList_LoadBitmap  QuickInfo  Overview  Group

[New - Windows NT]

The ImageList_LoadBitmap function creates an image list from the specified bitmap resource. ImageList_LoadBitmap is a macro that calls the ImageList_LoadImage function.

HIMAGELIST WINAPI ImageList_LoadBitmap(

HINSTANCE  hi,
LPCSTR  lpbmp,
int  cx,
int  cGrow,
COLORREF  crMask
);
Parameters

hi

Handle to the instance that contains the bitmap resource.

lpbmp

Name of the resource.

cx

Width of each image. The height of each image and the initial number of images are inferred by the dimensions of the specified bitmap.

cGrow

Amount of images by which the image list can grow when the system needs to resize the list to make room for new images. This parameter represents the number of new images that the resized image list can contain.

crMask

Color used to generate a mask. Each pixel of this color in the specified bitmap is changed to black, and the corresponding bit in the mask is set to one. If this parameter is the CLR_NONE value, no mask is generated.

Return Value

If the function succeeds, the return value is the image list.

If the function fails, the return value is NULL.

See Also

ImageList_LoadImage


ImageList_LoadImage [New - Windows NT]
 ImageList_LoadImage  QuickInfo  Overview  Group

[New - Windows NT]

The ImageList_LoadImage function creates an image list from the specified bitmap, cursor, or icon resource.

HIMAGELIST WINAPI ImageList_LoadImage(

HINSTANCE  hi,
LPCSTR  lpbmp,
int  cx,
int  cGrow,
COLORREF  crMask,
UINT  uType,
UINT   uFlags
);
Parameters

hi

Handle to the instance that contains the resource.

If the hi parameter is zero, the low-order word of this parameter must be the identifier of the OEM image to load. The OEM image identifiers are defined in WINUSER.H. Following are the identifier prefixes and their meanings:

Prefix	Meaning
OBM_	OEM bitmaps
OIC_	OEM icons
OCR_	OEM cursors
lpbmp

Pointer to a null-terminated string that contains the name of the image to load.

If the uFlags parameter specifies the LR_LOADFROMFILE value, the lpbmp parameter must be the name of the file that contains the image.

cx

Width of each image. The height of each image and the initial number of images are inferred by the dimensions of the specified resource.

cGrow

Amount of images by which the image list can grow when the system needs to resize the list to make room for new images. This parameter represents the number of new images that the resized image list can contain.

crMask

Color used to generate a mask. Each pixel of this color in the specified bitmap, cursor, or icon is changed to black, and the corresponding bit in the mask is set to 1. If this parameter is the CLR_NONE value, no mask is generated.

uType

Flag that specifies the type of image to load. 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.
uFlags

Flags that specify how to load the image. This parameter can be a combination of the following values:

Value	Meaning
LR_DEFAULTCOLOR	Uses the color format of the display.
LR_LOADDEFAULTSIZE	Uses the width or height specified by the system metric values for cursors and icons if the cx parameter is set to zero. If this value is not specified and cx is set to zero, the function sets the size to that specified in the resource. If the resource contains multiple images, the function sets the size to that of the first image.
LR_LOADFROMFILE	Loads the image from the file specified by the lpbmp parameter.
LR_LOADMAP3DCOLORS	Searches the color table for the image and replaces the following shades of gray with the corresponding three-dimensional color:
Dk Gray, RGB(128, 128, 128)	COLOR_3DSHADOW
Gray,  RGB(192, 192, 192)	COLOR_3DFACE
Lt Gray,  RGB(223, 223, 223)	COLOR_3DLIGHT
LR_LOADTRANSPARENT	Retrieves the color value of the first pixel in the image and replaces the corresponding entry in the color table with the default window color (the COLOR_WINDOW display color). All pixels in the image that use that entry become the default window value color. This value applies only to images that have corresponding color tables.
LR_MONOCHROME	Loads the image in black and white.
LR_SHARED	Shares the image handle if the image is loaded multiple times. Do not use this value for images that have nontraditional sizes that might change after loading or for images that are loaded from a file.
Return Value

If the function succeeds, the return value is the handle of the image list.

If the function fails, the return value is NULL.

See Also

RGB


ImageList_Merge [New - Windows NT]
 ImageList_Merge  QuickInfo  Overview  Group

[New - Windows NT]

The ImageList_Merge function creates a new image by combining two existing images. The function also creates a new image list to store the image.

HIMAGELIST WINAPI ImageList_Merge(

HIMAGELIST  himl1,
int  i1,
HIMAGELIST  himl2,
int  i2,
int  dx,
int  dy
);
Parameters

himl1

Handle to the first image list.

i1

Index of the first existing image.

himl2

Handle to the second image list.

i2

Index of the second existing image.

dx and dy

Offset of the second image relative to the first image.

Return Value

If the function succeeds, the return value is the handle of the new image list.

If the function fails, the return value is NULL.

Remarks

The new image consists of the second existing image drawn transparently over the first. The mask for the new image is the result of performing a logical OR operation on the masks of the two existing images.


ImageList_Read [New - Windows NT]
 ImageList_Read  QuickInfo  Overview  Group

[New - Windows NT]

The ImageList_Read function reads an image list from a stream.

HIMAGELIST WINAPI ImageList_Read(

LPSTREAM  pstm
);
Parameters

pstm

Pointer to the stream.

Return Value

If the function succeeds, the return value is the image list.

If the function fails, the return value is NULL.


ImageList_Remove [New - Windows NT]
 ImageList_Remove  QuickInfo  Overview  Group

[New - Windows NT]

The ImageList_Remove function removes an image from an image list.

BOOL WINAPI ImageList_Remove(

HIMAGELIST  himl,
int  i
);
// Related macro

BOOL ImageList_RemoveAll(himl);

Parameters

himl

Handle to the image list.

i

Index of the image to remove. If the i parameter is  − 1, the function removes all images.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.


ImageList_Replace [New - Windows NT]
 ImageList_Replace  QuickInfo  Overview  Group

[New - Windows NT]

The ImageList_Replace function replaces an image in an image list with a new image.

BOOL WINAPI ImageList_Replace(

HIMAGELIST  himl,
int  i,
HBITMAP  hbmImage,
HBITMAP  hbmMask
);
Parameters

himl

Handle to the image list.

i

Index of the image to replace.

hbmImage

Handle to the bitmap that contains the image.

hbmMask

Handle to the bitmap that contains the mask. If no mask is used with the image list, this parameter is ignored.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

The ImageList_Replace function copies the bitmap to an internal data structure. Be sure to use the DeleteObject function to delete hbmImage and hbmMask after the function returns.

See Also

DeleteObject


ImageList_ReplaceIcon [New - Windows NT]
 ImageList_ReplaceIcon  QuickInfo  Overview  Group

[New - Windows NT]

The ImageList_ReplaceIcon function replaces an image with an icon or cursor.

int WINAPI ImageList_ReplaceIcon(

HIMAGELIST  himl,
int  i,
HICON  hicon
);
Parameters

himl

Handle to the image list.

i

Index of the image to replace.

hicon

Handle to the icon or cursor that contains the bitmap and mask for the new image.

Return Value

If the function succeeds, the return value is the index of the image.

If the function fails, the return value is  − 1.

Remarks

Because the system does not save hicon, you can destroy it after the function returns if the icon or cursor was created by the CreateIcon function. You do not need to destroy hicon if it was loaded by the LoadIcon function; the system automatically frees an icon resource when it is no longer needed.

See Also

CreateIcon, LoadIcon


ImageList_SetBkColor [New - Windows NT]
 ImageList_SetBkColor  QuickInfo  Overview  Group

[New - Windows NT]

The ImageList_SetBkColor function sets the background color for an image list.

COLORREF WINAPI ImageList_SetBkColor(

HIMAGELIST  himl,	//
COLORREF  clrBk	//
);
Parameters

himl

Handle to the image list.

clrBk

Background color to set. This parameter can be the CLR_NONE value; in that case, images are drawn transparently using the mask.

Return Value

If the function succeeds, the return value is the previous background color.

If the function fails, the return value is the CLR_NONE value.


ImageList_SetDragCursorImage [New - Windows NT]
 ImageList_SetDragCursorImage  QuickInfo  Overview  Group

[New - Windows NT]

The ImageList_SetDragCursorImage function creates a new drag image by combining the specified image (typically a mouse cursor image) with the current drag image.

BOOL WINAPI ImageList_SetDragCursorImage(

HIMAGELIST  himlDrag,
int  iDrag,
int  dxHotspot,
int  dyHotspot
);
Parameters

himlDrag

Handle to the image list that contains the new image to combine with the drag image.

iDrag

Index of the new image to combine with the drag image.

dxHotspot and dyHotspot

Position of the hot spot within the new image.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.


ImageList_SetIconSize [New - Windows NT]
 ImageList_SetIconSize  QuickInfo  Overview  Group

[New - Windows NT]

The ImageList_SetIconSize function sets the dimensions of images in an image list and removes all images from the list.

BOOL WINAPI ImageList_SetIconSize(

HIMAGELIST  himl,
int  cx,
int  cy
);
Parameters

himl

Handle to the image list.

cx

Width, in pixels, of the images in the image list. All images in an image list have the same dimensions.

cy

Height, in pixels, of the images in the image list. All images in an image list have the same dimensions.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.


ImageList_SetOverlayImage [New - Windows NT]
 ImageList_SetOverlayImage  QuickInfo  Overview  Group

[New - Windows NT]

The ImageList_SetOverlayImage function adds the index of an image to the list of images to be used as overlay masks. Up to four indices can be added to the list.

BOOL WINAPI ImageList_SetOverlayImage(

HIMAGELIST  himl,
int  iImage,
int  iOverlay
);
Parameters

himl

Handle to the image list.

iImage

Image to use as an overlay mask.

iOverlay

One-based index of the overlay mask.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

An overlay mask is an image drawn transparently over another image. You draw an overlay mask over an image by using the ImageList_Draw or ImageList_DrawEx function with the index of the overlay mask. The index must be specified by using the INDEXTOOVERLAYMASK macro.

See Also

ImageList_Draw, ImageList_DrawEx, INDEXTOOVERLAYMASK


ImageList_Write [New - Windows NT]
 ImageList_Write  QuickInfo  Overview  Group

[New - Windows NT]

The ImageList_Write function writes an image list to a stream.

HIMAGELIST WINAPI ImageList_Write(

HIMAGELIST  himl,	//
LPSTREAM  pstm	//
);
Parameters

himl

Handle to the image list.

pstm

Pointer to the stream.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.


ImmAssociateContext [New - Windows 95]
 ImmAssociateContext  QuickInfo  Overview  Group

[New - Windows 95]

The ImmAssociateContext function associates the specified input context with the specified window. If hIMC is NULL, the function removes any association the window may have with an input context. By default, the system associates the default input context with each window as it is created.

HIMC ImmAssociateContext(

HWND  hWnd,
HIMC  hIMC
);
Parameters

hWnd

Handle to the window to be associated with the input context.

hIMC

Handle to the input context.

Return Value

Returns the handle to the input context previously associated with the window.

Remarks

If an application associates an input context with a window, the application must remove that association before destroying the input context. One way to do this is to save and reassociate the handle to the default input context with the window.


ImmConfigureIME [New - Windows 95]
 ImmConfigureIME  QuickInfo  Overview  Group

[New - Windows 95]

The ImmConfigureIME function displays the configuration dialog box for the IME.

BOOL ImmConfigureIME(

HKL  hKL,
HWND  hWnd,
DWORD  dwMode,
LPVOID  lpdata
);
Parameters

hKL

Handle to the keyboard layout.

hWnd

Handle to the parent window for the dialog box.

dwMode

Type of dialog box to display. This parameter can be one of the following values:

Value	Meaning
IME_CONFIG_GENERAL	Displays general purpose configuration dialog box.
IME_CONFIG_REGWORD	Displays register word dialog box.
IME_CONFIG_SELECTDICTIONARY	Displays dictionary selection dialog box.
lpData

Pointer to supplemental data. If dwMode is IME_CONFIG_REGWORD, this parameter must be the address of a REGISTERWORD structure.

If dwMode is not IME_CONFIG_REGWORD, this parameter is ignored.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

The ImmConfigureIME function is called by the Control Panel.


ImmCreateContext [New - Windows 95]
 ImmCreateContext  QuickInfo  Overview  Group

[New - Windows 95]

The ImmCreateContext function creates a new input context, allocating memory for the context and initializing it. An application calls this function to prepare its own input context.

HIMC ImmCreateContext(void);

Return Value

If the function succeeds, the return value is the handle to the new input context.

If the function fails, the return value is NULL.


ImmDestroyContext [New - Windows 95]
 ImmDestroyContext  QuickInfo  Overview  Group

[New - Windows 95]

The ImmDestroyContext function releases the input context and frees any memory associated with it.

BOOL ImmDestroyContext(

HIMC  hIMC
);
Parameters

hIMC

Handle to the input context to free.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

Any application that creates an input context by using the ImmCreateContext function must call this function to free the context before it terminates.

See Also

ImmCreateContext


ImmEnumRegisterWord [New - Windows 95]
 ImmEnumRegisterWord  QuickInfo  Overview  Group

[New - Windows 95]

The ImmEnumRegisterWord function enumerates the register strings having the specified reading string, style, and register string.

UINT ImmEnumRegisterWord(

HKL  hKL,
REGISTERWORDENUMPROC  lpfnEnumProc,
LPCTSTR  lpszReading,
DWORD  dwStyle,
LPCTSTR  lpszRegister,
LPVOID  lpData
);
Parameters

hKL

Handle to the keyboard layout.

lpfnEnumProc

Pointer to the callback function. For more information, see EnumRegisterWordProc.

lpszReading

Pointer to the reading string to be enumerated. If NULL, this function enumerates all available reading strings that match with the specified dwStyle and lpszRegister.

dwStyle

Style to be enumerate. If zero, this function enumerates all available styles that match with the specified lpszReading and lpszRegister.

lpszRegister

Pointer to the register string to enumerate. If NULL, this function enumerates all register strings that match with the specified lpszReading and dwStyle.

lpData

Application-supplied data. The function passes this parameter to the callback function.

Return Value

Returns the last value return by the callback function. Its meaning is defined by the application. The function returns zero if it cannot enumerate the register strings.

Remarks

If dwStyle is zero and both lpszReading and lpszRegister are NULL, the ImmEnumRegisterWord function enumerates all register strings in the IME dictionary.

See Also

EnumRegisterWordProc


ImmEscape [New - Windows 95]
 ImmEscape  QuickInfo  Overview  Group

[New - Windows 95]

The ImmEscape function carries out IME-specific subfunctions and is used mainly for country-specific functions.

LRESULT ImmEscape(

HKL  hKL,
HIMC  hIMC,
UINT  uEscape,
LPVOID  lpData
);
Parameters

hKL

Handle to the keyboard layout.

hIMC

Handle to the input context.

uEscape

Index of the subfunction. For more information about the escape, see the "IME Escapes" table in Input Method Editor Constants.

lpData

Subfunction-specific data.

Return Value

Returns zero on error; otherwise, returns an escape-specific value.


ImmGetCandidateList [New - Windows 95]
 ImmGetCandidateList  QuickInfo  Overview  Group

[New - Windows 95]

The ImmGetCandidateList function retrieves a specified candidate list, copying the list to the specified buffer.

DWORD ImmGetCandidateList(

HIMC  hIMC,
DWORD  deIndex,
LPCANDIDATELIST  lpCandList,
DWORD  dwBufLen
);
Parameters

hIMC

Handle to the input context.

deIndex

Zero-based index of the candidate list.

lpCandList

Pointer to the CANDIDATELIST structure that receives the candidate list.

dwBufLen

Size of the buffer, in bytes. If zero, the function returns the size in bytes required to receive the complete candidate list.

Return Value

If the function succeeds, the return value is the number of bytes copied to the specified buffer.

If the function fails, the return value is zero.

See Also

CANDIDATELIST


ImmGetCandidateListCount [New - Windows 95]
 ImmGetCandidateListCount  QuickInfo  Overview  Group

[New - Windows 95]

The ImmGetCandidateListCount function retrieves the size, in bytes, of the candidate lists.

DWORD ImeGetCandidateListCount(

HIMC  hIMC,
LPDWORD  lpdwListCount
);
Parameters

hIMC

Handle to the input context.

lpdwListCount

Pointer to the 32-bit variable that receives the size of the candidate lists.

Return Value

Returns the number of bytes required to receive all candidate lists.

Remarks

Applications typically call this function in response to a IMN_OPENCANDIDATE or IMN_CHANGECANDIDATE message.

See Also

IMN_CHANGECANDIDATE, IMN_OPENCANDIDATE


ImmGetCandidateWindow [New - Windows 95]
 ImmGetCandidateWindow  QuickInfo  Overview  Group

[New - Windows 95]

The ImmGetCandidateWindow function gets information about the candidate list window.

BOOL ImmGetCandidateWindow(

HIMC  hIMC,
DWORD  dwBufLen,
LPCANDIDATEFORM  lpCandidate
);
Parameters

hIMC

Handle to the input context.

dwBufLen

Size, in bytes, of the buffer that receives the information.

lpCandidate

Pointer to the CANDIDATEFORM structure that receives information about the candidate window.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

See Also

CANDIDATEFORM


ImmGetCompositionFont [New - Windows 95]
 ImmGetCompositionFont  QuickInfo  Overview  Group

[New - Windows 95]

The ImmGetCompositionFont function retrieves information about the logical font currently used to display characters in the composition window.

BOOL ImmGetCompositionFont(

HIMC  hIMC,
LPLOGFONT  lplf
);
Parameters

hIMC

Handle to the input context.

lplf

Pointer to a LOGFONT structure that receives the font information.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

See Also

LOGFONT


ImmGetCompositionString [New - Windows 95]
 ImmGetCompositionString  QuickInfo  Overview  Group

[New - Windows 95]

The ImmGetCompositionString function retrieves information about the composition string.

LONG ImmGetCompositionString(

HIMC  hIMC,
DWORD  dwIndex,
LPVOID  lpBuf,
DWORD  dwBufLen
);
Parameters

hIMC

Handle to the input context.

dwIndex

Index of the information to retrieve. This parameter can be one of the values given in the "IME Composition String Values" table in Input Method Editor Constants. For each value except GCS_CURSORPOS and GCS_DELTASTART, the function copies the requested information to the specified buffer. The function returns the cursor and delta position values in the low 16-bits of the return value.

lpBuf

Pointer to the buffer that receives the requested information.

dwBufLen

Size of the buffer, in bytes. If zero, the ImmGetCompositionString function returns the buffer size needed for the complete information.

Return Value

Returns the number of bytes copied to the destination buffer or, if dwBufLen is zero, the buffer size, in bytes, needed to receive all of the requested information. On an error, the function returns one of the following negative error values:

Value	Meaning
IMM_ERROR_NODATA	Composition data is not ready in the input context.
IMM_ERROR_GENERAL	General error detected by IME.
Remarks

An application calls this function in response to the WM_IME_COMPOSITION or WM_IME_STARTCOMPOSITION message. The IMM removes the information when an application calls the ImmReleaseContext function.

See Also

ImmReleaseContext, WM_IME_COMPOSITION


ImmGetCompositionWindow [New - Windows 95]
 ImmGetCompositionWindow  QuickInfo  Overview  Group

[New - Windows 95]

The ImmGetCompositionWindow function gets information about the composition window.

BOOL ImmGetCompositionWindow(

HIMC  hIMC,
LPCOMPOSITIONFORM  lpCompForm
);
Parameters

hIMC

Handle to the input context.

lpCompForm

Pointer to the COMPOSITIONFORM structure that receives information about the composition window.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

See Also

COMPOSITIONFORM


ImmGetContext [New - Windows 95]
 ImmGetContext  QuickInfo  Overview  Group

[New - Windows 95]

The ImmGetContext function retrieves the input context associated with the specified window.

HIMC ImmGetContext(

HWND  hWnd
);
Parameters

hWnd

Handle to the window to retrieve the input context for.

Return Value

Returns the handle to the input context.

Remarks

An application should routinely use this function to retrieve the current input context before attempting to access information in the context.


ImmGetConversionList [New - Windows 95]
 ImmGetConversionList  QuickInfo  Overview  Group

[New - Windows 95]

The ImmGetConversionList function retrieves the list of characters or words from one character or word.

UINT ImmGetConversionList(

HKL  hKL,
HIMC  hIMC,
LPCTSTR  lpSrc,
LPCANDIDATELIST  lpDst,
DWORD  dwBufLen,
UINT  uFlag
);
Parameters

hKL

Handle to the keyboard layout.

hIMC

Handle to the input context.

lpSrc

Pointer to a null-terminated character string.

lpDst

Pointer to the CANDIDATELIST structure that receives the conversion result.

dwBufLen

Size of the destination buffer, in bytes. If zero, the function returns the buffer size needed for the complete conversion result.

uFlag

Action flag. This parameter can be one of the following values:

Value	Meaning
GCL_CONVERSION	Source string is the reading string. The function copies the result string to the destination buffer.
GCL_REVERSECONVERSION	Source string is the result string. The function copies the reading string to the destination buffer.
GCL_REVERSE_LENGTH	Source string is the result string. The function returns the size in bytes of the reading string that would be created if GCL_REVERSECONVERSION were given.
Return Value

Returns the number of bytes copied to the specified buffer or, if dwBufLen is zero, the buffer size needed to receive the list.

See Also

CANDIDATELIST


ImmGetConversionStatus [New - Windows 95]
 ImmGetConversionStatus  QuickInfo  Overview  Group

[New - Windows 95]

The ImmGetConversionStatus function gets the current conversion status.

BOOL ImmGetConversionStatus(

HIMC  hIMC,
LPDWORD  lpfdwConversion,
LPDWORD  lpfdwSentence
);
Parameters

hIMC

Handle to the input context for which to retrieve information.

lpfdwConversion

Pointer to a 32-bit variable that receives a combination of conversion mode values. For more information, see the "IME Conversion Mode Values" table in Input Method Editor Constants.

lpfdwSentence

Pointer to a 32-bit variable that receives a sentence mode value. For more information, see the "IME Sentence Mode Values" table in Input Method Editor Constants.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

Conversion and sentence mode values are set only if the IME supports those modes.


ImmGetDefaultIMEWnd [New - Windows 95]
 ImmGetDefaultIMEWnd  QuickInfo  Overview  Group

[New - Windows 95]

The ImmGetDefaultIMEWnd function gets the default window handle to the IME class.

HWND ImmGetDefaultIMEWnd(

HWND  hWnd
);
Parameters

hWnd

Handle to the window for the application.

Return Value

If the function succeeds, the return value is the default window handle to the IME class.

If the function fails, the return value is NULL.

Remarks

The system creates a default IME window for every thread. The IME window is created based on the IME class. The application can send WM_IME_CONTROL to this window.

See Also

WM_IME_CONTROL


ImmGetDescription [New - Windows 95]
 ImmGetDescription  QuickInfo  Overview  Group

[New - Windows 95]

The ImmGetDescription function copies the description of the IME to the specified buffer.

UINT ImmGetDescription(

HKL  hKL,
LPTSTR  lpszDescription,
UINT  uBufLen
);
Parameters

hKL

Handle to the keyboard layout.

lpszDescription

Pointer to the buffer that receives the null-terminated string describing the IME.

uBufLen

Size of the buffer, in bytes. If zero, the function returns the buffer size needed for the complete description, not including terminating null character.

Return Value

Returns the number of bytes copied to the buffer or, if uBufLen is zero, the buffer size in bytes needed to receive the description. Neither value includes the terminating null character.


ImmGetGuideLine [New - Windows 95]
 ImmGetGuideLine  QuickInfo  Overview  Group

[New - Windows 95]

The ImmGetGuideLine function gets information about errors. Applications use the information to notify users.

DWORD ImmGetGuideLine(dwBufLen

HIMC  hIMC,
DWORD  dwIndex,
LPTSTR  lpBuf,
DWORD  dwBufLen
);
Parameters

hIMC

Handle to the input context.

dwIndex

Type of guideline information to retrieve. Can be one of the following values:

Value	Meaning
GGL_LEVEL	Returns the error level.
GGL_INDEX	Returns the error index.
GGL_STRING	Retrieves the error message string.
GGL_PRIVATE	Returns information about reverse conversion.
lpBuf

Pointer to the buffer that receives the error message string. This parameter can be NULL if dwIndex is not GGL_STRING or GGL_PRIVATE if dwBufLen is zero.

dwBufLen

Size, in bytes, of the buffer pointed to by lpBuf. If zero, the function returns the buffer size needed to receive the error message string, not including the terminating null character.

Return Value

The return value is an error level, an error index, or the size of an error message string, depending on the value of the dwIndex parameter. If dwIndex is GGL_LEVEL, the return value is one of the following:

Value	Meaning
GL_LEVEL_ERROR	Error. The IME may not be able to continue.
GL_LEVEL_FATAL	Fatal error. The IME cannot continue, and data may be lost.
GL_LEVEL_INFORMATION	No error, but information is available for the user.
GL_LEVEL_NOGUIDELINE	No error. Remove previous error message if still visible.
GL_LEVEL_WARNING	Unexpected input or other result. The user should be warned, but the IME can continue.
If dwIndex is GGL_INDEX, the return value is one of the following:

Value	Meaning
GL_ID_CANNOTSAVE	The dictionary or the statistics data cannot be saved.
GL_ID_NOCONVERT	The IME cannot convert any more.
GL_ID_NODICTIONARY	The IME cannot find the dictionary, or the dictionary has an unexpected format.
GL_ID_NOMODULE	The IME can not find the module that IME needs.
GL_ID_READINGCONFLICT	For example, some vowels cannot put together.
GL_ID_TOOMANYSTROKE	There are too many strokes for one character or one clause.
GL_ID_TYPINGERROR	Typing error. The IME can not handle this typing.
GL_ID_UNKNOWN	Unknown error. The application should refer to the error message string.
GL_ID_INPUTREADING	IME accepts reading character input.
GL_ID_INPUTRADICAL	IME accepts radical character input.
GL_ID_INPUTCODE	IME accepts character code input.
GL_ID_CHOOSECANDIDATE	IME accepts candidate string selection.
GL_ID_REVERSECONVERSION	Information about reverse conversion is available.
If dwIndex is GGL_STRING, the return value is the number of bytes of the string copied to the buffer, or if dwBufLen is zero, the return value is the buffer size needed to receive the string.

If dwIndex is GGL_PRIVATE, the return value is the number of bytes of information copied to the buffer. If dwIndex is GGL_PRIVATE and dwBufLen is zero, the return value is the buffer size needed to receive the information.

Remarks

Applications typically call this function after receiving an IMN_GUIDELINE message.


ImmGetIMEFileName [New - Windows 95]
 ImmGetIMEFileName  QuickInfo  Overview  Group

[New - Windows 95]

The ImmGetIMEFileName function gets the filename of the IME associated with the specified keyboard layout.

BOOL ImmGetIMEFileName(

HKL  hKL,
LPTSTR  lpszFileName,
UINT  uBufLen
);
Parameters

hKL

Handle to the keyboard layout.

lpszFileName

Pointer to the buffer that receives the filename.

uBufLen

Size in bytes of the buffer. If zero, the function returns the buffer size in bytes needed to receive the filename, not including the termintaing null character.

Return Value

The return value is the number of bytes in the filename copied to the buffer, or if uBufLen is zero, the return value is the buffer size needed for the filename. In either case, the terminating null character is not included.

Remarks

In the registry, the system stores the filename as the IME name value in HKEY_LOCAL_MACHINE root under the \System\CurrentControlSet\control\keyboard layouts\hKL key.


ImmGetOpenStatus [New - Windows 95]
 ImmGetOpenStatus  QuickInfo  Overview  Group

[New - Windows 95]

The ImmGetOpenStatus function checks whether the IME is open or closed.

BOOL WINAPI ImmGetOpenStatus(

HIMC  hIMC
);
Parameters

hIMC

Handle to the input context.

Return Value

The return value is TRUE if the IME is open, FALSE otherwise.


ImmGetProperty [New - Windows 95]
 ImmGetProperty  QuickInfo  Overview  Group

[New - Windows 95]

The ImmGetProperty function gets the property and capabilities of the IME associated with the specified keyboard layout.

BOOL ImmGetProperty(

HKL  hKL,
DWORD  fdwIndex
);
Parameters

hKL

Handle to the keyboard layout.

fdwIndex

Type of property information to retrieve. This parameter can be one of the following values:

Value	Meaning
IGP_PROPERTY	Property information.
IGP_CONVERSION	Conversion capabilities.
IGP_SENTENCE	Sentence mode capabilities.
IGP_UI	User interface capabilities.
IGP_SETCOMPSTR	Composition string capabilities.
IGP_SELECT	Selection inheritance capabilities.
IGP_GETIMEVERSION	Retrieves the Windows version number for which the specified IME was created.
Return Value

Returns the property or capability value, depending on the value of the dwIndex parameter. If dwIndex is IGP_PROPERTY, returns a combination of the following values:

Value	Meaning
IME_PROP_AT_CARET	If set, conversion window is at the caret position. If clear, the window is near caret position.
IME_PROP_SPECIAL_UI	If set, IME has a nonstandard user interface. The application should not draw in the IME window.
IME_PROP_CANDLIST_START_FROM_1	If set, strings in the candidate list are numbered starting at 1. If clear, strings start at 0.
IME_PROP_UNICODE	If set, strings for the input context have Unicode characters. If clear, strings have single and double-byte characters.
If dwIndex is IGP_UI, the return value is a combination of the following values:

Value	Meaning
UI_CAP_2700	Supports text escapement values of 0 or 2700.
UI_CAP_ROT90	Supports text escapement values of 0, 900, 1800, or 2700.
UI_CAP_ROTANY	Supports any text escapement value.
If dwIndex is IGP_SETCOMPSTR, the return value is a combination of the following values:

Value	Meaning
SCS_CAP_COMPSTR	Can create the composition string by using the SCS_SETSTR value of the ImmSetCompositionString function.
SCS_CAP_MAKEREAD	Can create the reading string from corresponding composition string when using the SCS_SETSTR value of the ImmSetCompositionString function.
If dwIndex is IGP_SELECT, the return value is a combination of the following values:

Value	Meaning
SELECT_CAP_CONVMODE	Inherits conversion mode when a new IME is selected.
SELECT_CAP_SENTENCE	Inherits sentence mode when a new IME is selected.
If dwIndex is IGP_GETIMEVERSION, the return value is one of the following values:

Value	Meaning
IMEVER_0310	The IME was created for Windows 3.1
IMEVER_0400	The IME was created for Windows 95.


ImmGetRegisterWordStyle [New - Windows 95]
 ImmGetRegisterWordStyle  QuickInfo  Overview  Group

[New - Windows 95]

The ImmGetRegisterWordStyle function gets a list of the styles support by the IME associated with the specified keyboard layout.

UINT ImmGetRegisterWordStyle(

HKL  hKL,
UINT  nItem,
LPSTYLEBUF  lpStyleBuf
);
Parameters

hKL

Handle to the keyboard layout.

nItem

Maximum number of styles that the buffer can hold.

lpStyleBuf

Pointer to the STYLEBUF structure that receives the style information.

Return Value

The return value is the number of layout handles copied to the buffer, or if nItems is zero, the return value is the buffer size in array elements needed to receive all available style information.

See Also

STYLEBUF


ImmGetStatusWindowPos [New - Windows 95]
 ImmGetStatusWindowPos  QuickInfo  Overview  Group

[New - Windows 95]

The ImmGetStatusWindowPos function gets the position of the status window.

BOOL ImmGetStatusWindowPos(

HIMC  hIMC,
LPPOINT  lpptPos
);
Parameters

hIMC

Handle to the input context.

lpptPos

Pointer to the POINT structure that receives the position coordinates. These are screen coordinates, relative to the upper-left corner of the screen.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

See Also

POINT


ImmGetVirtualKey [New - Windows 95]
 ImmGetVirtualKey  QuickInfo  Overview  Group

[New - Windows 95]

The ImmGetVirtualKey function recovers the original virtual-key value associated with a key input message that has already been processed by the IME.

UINT ImmGetVirtualKey(

HWND  hWnd
);
Parameters

hWnd

Handle to the window that receives the key message.

Return Value

The return value is the original virtual-key value.

Remarks

Although the IME sets the virtual-key value to VK_PROCESSKEY after processing a key input message, an application can recover the original virtual-key value with the ImmGetVirtualKey function. This function can be used only for key input messages containing the VK_PROCESSKEY value.


ImmInstallIME [New - Windows 95]
 ImmInstallIME  QuickInfo  Overview  Group

[New - Windows 95]

The ImmInstallIME function installs an IME into the system.

HKL ImmInstallIME(

LPCTSTR  lpszIMEFileName,
LPCTSTR  lpszLayoutText
);
Parameters

lpszIMEFileName

Pointer to a null-terminated string that specifies the full path of the IME.

lpszLayoutText

Pointer to a null-terminated string that specifies the name of the IME. This name also specifies the layout text of the IME.

Return Value

The return value is the handle to the keyboard layout for the IME.

Remarks

This function is intended to be used by IME setup programs only.


ImmIsIME [New - Windows 95]
 ImmIsIME  QuickInfo  Overview  Group

[New - Windows 95]

The ImmIsIME function checks whether the specified handle identifies an IME.

BOOL ImmIsIME(

HKL  hKL
);
Parameters

hKL

Handle to the keyboard layout to check.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.


ImmIsUIMessage [New - Windows 95]
 ImmIsUIMessage  QuickInfo  Overview  Group

[New - Windows 95]

The ImmIsUIMessage function checks for messages intended for the IME window and sends those messages to the specified window.

BOOL ImmIsUIMessage(

HWND  hWndIME,
UINT  msg,
WPARAM  wParam,
LPARAM  lParam
);
Parameters

hWndIME

Handle to a window belonging to the IME window class.

msg

Message to check.

wParam

32-bit message-specific parameter.

lParam

32-bit message-specific parameter.

Return Value

If the message is processed by the IME window, the return value is TRUE.

If the message is not processed by the IME window, the return value is FALSE.

Remarks

An application typically uses this function to display any composition string or candidate list specified by IME. If hWndIME is NULL, the function checks whether the message is a user interface message.


ImmNotifyIME [New - Windows 95]
 ImmNotifyIME  QuickInfo  Overview  Group

[New - Windows 95]

The ImmNotifyIME function notifies the IME about changes to the status of the input context.

BOOL ImmNotifyIME(

HIMC  hIMC,
DWORD  dwAction,
DWORD  dwIndex,
DWORD  dwValue
);
Parameters

hIMC

Handle to the input context.

dwAction

Notification code. This parameter can be one of the following values:

Value	Meaning
NI_CHANGECANDIDATELIST	An application changed the current selected candidate; dwIndex is an index of a candidate list to be selected and dwValue is not used.
NI_CLOSECANDIDATE	An application directs the IME to close a candidate list; dwIndex is the index of the list to close; dwValue is not used. The IME sends a IMN_CLOSECANDIDATE message to the application if it closes the list.
NI_COMPOSITIONSTR	An application directs the IME to carry out an action on the composition string; dwValue is not used and dwIndex can be CPS_CANCEL, CPS_COMPLETE, CPS_CONVERT, or CPS_REVERT.
NI_OPENCANDIDATE	An application directs the IME to open a candidate list; dwIndex is the index of the list to open; dwValue is not used. The IME sends a IMN_OPENCANDIDATE message to the application if it opens the list.
NI_SELECTCANDIDATESTR	An application selected one of candidates; dwIndex is an index of a candidate list to be selected and dwValue is an index of a candidate string in the selected candidate list.
NI_SETCANDIDATE_PAGESIZE	The dwIndex parameter specifies the candidate list to be changed and must have a value in the range 0 to 31.
NI_SETCANDIDATE_PAGESTART	The dwIndex parameter specifies the candidate list to be changed and must have a value in the range 0 to 31.
dwIndex

Index of a candidate list or, if dwAction is NI_COMPOSITIONSTR, one of the following values:

Value	Meaning
CPS_CANCEL	Clear the composition string and set the status to no composition string.
CPS_COMPLETE	Set the composition string as the result string.
CPS_CONVERT	Convert the composition string.
CPS_REVERT	Cancel the current composition string and revert to the unconverted string.
dwValue

Index of a candidate string or not used, depending on the value of the dwAction parameter.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.


ImmRegisterWord [New - Windows 95]
 ImmRegisterWord  QuickInfo  Overview  Group

[New - Windows 95]

The ImmRegisterWord function registers a string into the dictionary of the IME associated with the specified keyboard layout.

BOOL ImmRegisterWord(

HKL  hKL,
LPCTSR  lpszReading,
DWORD  dwStyle,
LPCTSTR  lpszRegister
);
Parameters

hKL

Handle to the keyboard layout.

lpszReading

Pointer to a null-terminated string specifying the reading string associated with the string to register.

dwStyle

Style of the register string. This parameter can be IME_REGWORD_STYLE_EUDC to indicate the string is in the EUDC range, or any value in the reserved range IME_REGWORD_STYLE_USER_FIRST to IME_REGWORD_STYLE_USER_LAST to indicate a private style maintained by the specified IME.

lpszRegister

Pointer to a null-terminated string specifying the string to register.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.


ImmReleaseContext [New - Windows 95]
 ImmReleaseContext  QuickInfo  Overview  Group

[New - Windows 95]

The ImmReleaseContext function releases the input context and unlocks the memory associated in the context. An application must call this function for each call to the ImmGetContext function.

BOOL ImmReleaseContext(

HWND  hWnd,
HIMC  hIMC
);
Parameters

hWnd

Handle to the window for which the input context was previously retrieved.

hIMC

Handle to the input context.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

See Also

ImmGetContext


ImmSetCandidateWindow [New - Windows 95]
 ImmSetCandidateWindow  QuickInfo  Overview  Group

[New - Windows 95]

The ImmSetCandidateWindow function sets information about the candidate list window.

BOOL ImmSetCandidateWindow(

HIMC  hIMC,
LPCANDIDATEFORM  lpCandidate
);
Parameters

hIMC

Handle to the input context.

lpCandidate

Pointer to the CANDIDATEFORM structure that contains information about the candidate window.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

ImmSetCandidateWindow causes an IMN_SETCANDIDATEPOS message to be sent to the application.

See Also

CANDIDATEFORM


ImmSetCompositionFont [New - Windows 95]
 ImmSetCompositionFont  QuickInfo  Overview  Group

[New - Windows 95]

The ImmSetCompositionFont function sets the logical font to be used to display characters in the composition window.

BOOL ImmSetCompositionFont(

HIMC  hIMC,
LPLOGFONT  lplf
);
Parameters

hIMC

Handle to the input context.

lplf

Pointer to the LOGFONT structure containing the font information to set.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

Even if an application never uses the composition window, it must set the appropriate font to ensure that characters are displayed properly. This is especially true for vertical writing.

This function causes a IMN_SETCOMPOSITIONFONT message to be sent to the application.

See Also

IMN_SETCOMPOSITIONFONT, LOGFONT


ImmSetCompositionString [New - Windows 95]
 ImmSetCompositionString  QuickInfo  Overview  Group

[New - Windows 95]

The ImmSetCompositionString function sets the characters, attributes, and clauses of the composition and reading strings.

BOOL ImmSetCompositionString(

HIMC  hIMC,
DWORD  dwIndex,
LPCVOID  lpComp,
DWORD  dwCompLen,
LPCVOID  lpRead,
DWORD  dwReadLen
);
Parameters

hIMC

Handle to the input context.

dwIndex

Type of information to set. This parameter can be one of one of the following values:

Value	Meaning
SCS_SETSTR	Sets the composition string, the reading string, or both. At least one of the lpComp and lpRead parameters must point to a valid string. If either string is too long, the IME truncates it.
SCS_CHANGEATTR	Sets attributes for the composition string, the reading string, or both. At least one of the lpComp and lpRead parameters must point to a valid attribute array.
SCS_CHANGECLAUSE	Sets the clause information for the composition string, the reading string, or both. At least one of the lpComp and lpRead parameters must point to a valid clause information array.
lpComp

Pointer to the buffer containing the information to set for the composition string. The information is as specified by the dwIndex value.

dwCompLen

Size in bytes of the information buffer for the composition string.

lpRead

Pointer to the buffer containing the information to set for the reading string. The information is as specified by the dwIndex value.

dwReadLen

Size, in bytes, of the information buffer for the reading string.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

When changing attributes, all characters in a clause must have the same attribute. Converted characters must be either ATTR_CONVERTED or ATTR_TARGET_CONVERTED; unconverted characters either ATTR_INPUT or ATTR_TARGET_NOTCONVERTED.

When changing clause information, only the target clause can be changed and only one boundary of the clause can be changed at a time. The target clause has the ATTR_TARGET_CONVERTED or ATTR_TARGET_NOTCONVERTED attribute.

When the IME completes the changes, it sends a WM_IME_COMPOSITION message to the application notifying it of the changes.

See Also

WM_IME_COMPOSITION


ImmSetCompositionWindow [New - Windows 95]
 ImmSetCompositionWindow  QuickInfo  Overview  Group

[New - Windows 95]

The ImmSetCompositionWindow function sets the position of the composition window.

BOOL ImmSetCompositionWindow(

HIMC  hIMC,
LPCOMPOSITIONFORM  lpCompForm
);
Parameters

hIMC

Handle to the input context.

lpCompForm

Pointer to the COMPOSITIONFORM structure that contains the new position and other related information about the composition window.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

The ImmSetCompositionWindow function causes a IMN_SETSCOMPOSITIONWINDOW message to be sent to the application.

See Also

COMPOSITIONFORM


ImmSetConversionStatus [New - Windows 95]
 ImmSetConversionStatus  QuickInfo  Overview  Group

[New - Windows 95]

The ImmSetConversionStatus function sets the current conversion status.

BOOL ImmSetConversionStatus(

HIMC  hIMC,
DWORD  fdwConversion,
DWORD  fdwSentence
);
Parameters

hIMC

Handle to the input context.

fdwConvStatus

Conversion mode values. For more information, see the "IME Conversion Mode Values" table in Input Method Editor Constants.

fdwSentence

Sentence mode values. For more information, see the "IME Sentence Mode Values" table in Input Method Editor Constants.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

This function sends a IMN_SETCONVERSIONSTATUS message to the application.


ImmSetOpenStatus [New - Windows 95]
 ImmSetOpenStatus  QuickInfo  Overview  Group

[New - Windows 95]

The ImmSetOpenStatus function opens or closes the IME.

BOOL ImmSetOpenStatus(

HIMC  hIMC,
BOOL  fOpen
);
Parameters

hIMC

Handle to the input context.

fOpen

Open flag. If TRUE, the IME is opened; otherwise, it is closed.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

This function causes a IMN_SETOPENSTATUS message to be sent to the application.

See Also

IMN_SETOPENSTATUS


ImmSetStatusWindowPos [New - Windows 95]
 ImmSetStatusWindowPos  QuickInfo  Overview  Group

[New - Windows 95]

The ImmSetStatusWindowPos function sets the position of the status window.

BOOL ImmSetStatusWindowPos(

HIMC  hIMC,
LPPOINT  lpptPos
);
Parameters

hIMC

Handle to the input context.

lpptPos

Pointer to the POINT structure that receives the new position of the status window.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

The ImmSetStatusWindowPos function causes a IMN_SETSTATUSWINDOWPOS message to be sent to the application.

See Also

IMN_SETSTATUSWINDOWPOS, POINT


ImmSimulateHotKey [New - Windows 95]
 ImmSimulateHotKey  QuickInfo  Overview  Group

[New - Windows 95]

The ImmSimulateHotKey function simulates the specified IME hot key, causing the same response as if the user had pressed the hot key in the specified window.

BOOL ImmSimulateHotKey(

HWND  hWnd,
DWORD  dwHotKeyID
);
Parameters

hWnd

Handle to the window.

dwHotKeyID

Identifier of the IME hot key. Can be one of the values specified in the "IME Hot Key Identifiers" table in Input Method Editor Constants.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.


ImmUnregisterWord [New - Windows 95]
 ImmUnregisterWord  QuickInfo  Overview  Group

[New - Windows 95]

The ImmUnregisterWord function removes a register string from the dictionary of the IME associated with the specified keyboard layout.

BOOL ImmUnregisterWord(

HKL  hKL,
LPCTSTR  lpszReading,
DWORD  dwStyle,
LPCTSTR  lpszUnregister
);
Parameters

hKL

Handle to the keyboard layout.

lpszReading

Pointer to a null-terminated string specifying the reading string associated with the string to remove.

dwStyle

Style of the register string. Can be IME_REGWORD_STYLE_EUDC to indicate the string is in the EUDC range, or any value in the reserved range IME_REGWORD_STYLE_USER_FIRST to IME_REGWORD_STYLE_USER_LAST to indicate a private style maintained by the specified IME.

lpszUnregister

Pointer to a null-terminated string specifying the register string to remove.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.


ImpersonateDdeClientWindow
 ImpersonateDdeClientWindow  QuickInfo  Overview  Group

The ImpersonateDdeClientWindow function enables a DDE server application to impersonate a DDE client application's security context in order to protect secure server data from unauthorized DDE clients.

BOOL ImpersonateDdeClientWindow(

HWND  hWndClient,	// handle of DDE client window
HWND  hWndServer	// handle of DDE server window
);
Parameters

hWndClient

Identifies the DDE client window to impersonate. The client window must have established a DDE conversation with the server window identified by the hWndServer parameter.

hWndServer

Identifies the DDE server window. An application must create the server window before calling this function.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

An application should call the RevertToSelf function to undo the impersonation set by the ImpersonateDdeClientWindow function.

A DDEML application should use the DdeImpersonateClient function.

See Also

DdeImpersonateClient, RevertToSelf


ImpersonateLoggedOnUser [New - Windows NT]
 ImpersonateLoggedOnUser  QuickInfo

[New - Windows NT]

The ImpersonateLoggedOnUser function lets the calling thread impersonate a user. The user is represented by a token handle obtained by calling the LogonUser function.

BOOL ImpersonateLoggedOnUser(

HANDLE hToken	// handle to a token that represents a logged-on user
);
Parameters

hToken

Handle to a token that represents a logged-on user. You obtain this token handle by calling the LogonUser function.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The impersonation lasts until the thread exits or until it calls RevertToSelf. Only token handles from LogonUser can be supplied to this function. If a thread opens its token and then tries to use that token in this call, it will fail with ERROR_BAD_TOKEN_TYPE.

See Also

CreateProcessAsUser, LogonUser


ImpersonateNamedPipeClient
 ImpersonateNamedPipeClient  QuickInfo  Overview  Group

The ImpersonateNamedPipeClient function impersonates a named-pipe client application.

BOOL ImpersonateNamedPipeClient(

HANDLE  hNamedPipe	// handle of a named pipe
);
Parameters

hNamedPipe

Identifies a named pipe.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The ImpersonateNamedPipeClient function allows the server end of a named pipe to impersonate the client end. When this function is called, the named-pipe file system changes the thread of the calling process to start impersonating the security context of the last message read from the pipe. Only the server end of the pipe can call this function.

The server can call the RevertToSelf function when the impersonation is complete.

See Also

DdeImpersonateClient, DuplicateToken, RevertToSelf


ImpersonateSelf
 ImpersonateSelf  QuickInfo  Overview  Group

The ImpersonateSelf function obtains an access token that impersonates the security context of the calling process. The token is assigned to the calling thread.

BOOL ImpersonateSelf(

SECURITY_IMPERSONATION_LEVEL  ImpersonationLevel	// impersonation level
);
Parameters

ImpersonationLevel

Specifies a SECURITY_IMPERSONATION_LEVEL enumerated type that supplies the impersonation level of the new token.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The ImpersonateSelf function is used for tasks, such as enabling a privilege for a single thread rather than for the entire process or for changing the default discretionary access-control list for a single thread.

The server can call the RevertToSelf function when the impersonation is complete.

See Also

DuplicateToken, ImpersonateNamedPipeClient, RevertToSelf, SECURITY_IMPERSONATION_LEVEL


inet_addr
 inet_addr  QuickInfo

The Windows Sockets inet_addr function converts a string containing a dotted address into an in_addr.

unsigned long inet_addr (

const char FAR * cp
);
Parameters

cp

A character string representing a number expressed in the Internet standard "." notation.

Return Value

If no error occurs, inet_addr returns an unsigned long containing a suitable binary representation of the Internet address given. If the passed-in string does not contain a legitimate Internet address (for example, if a portion of an "a.b.c.d" address exceeds 255), inet_addr returns the value INADDR_NONE.

Remarks

This function interprets the character string specified by the cp parameter. This string represents a numeric Internet address expressed in the Internet standard "." notation. The value returned is a number suitable for use as an Internet address. All Internet addresses are returned in network order (bytes ordered from left to right).

Internet Addresses

Values specified using the "." notation take one of the following forms:

          a.b.c.d          a.b.c          a.b          a

When four parts are specified, each is interpreted as a byte of data and assigned, from left to right, to the four bytes of an Internet address. Note that when an Internet address is viewed as a 32-bit integer quantity on the Intel architecture, the bytes referred to above appear as "d.c.b.a". That is, the bytes on an Intel processor are ordered from right to left.

Note  The following notations are used only by Berkeley and nowhere else on the Internet. In the interests of compatibility with their software, the Berkeley notations are supported as specified.

When a three-part address is specified, the last part is interpreted as a 16-bit quantity and placed in the right most two bytes of the network address. This makes the three-part address format convenient for specifying Class B network addresses as "128.net.host".

When a two-part address is specified, the last part is interpreted as a 24-bit quantity and placed in the right-most three bytes of the network address. This makes the two-part address format convenient for specifying Class A network addresses as "net.host".

When only one part is given, the value is stored directly in the network address without any byte rearrangement.

See Also

inet_ntoa


inet_ntoa
 inet_ntoa  QuickInfo

The Windows Sockets inet_ntoa function converts a network address into a string in dotted format.

char FAR * inet_ntoa (

struct in_addr in
);
Parameters

in

A structure that represents an Internet host address.

Return Value

If the function succeeds, inet_ntoa returns a char pointer to a static buffer containing the text address in standard "." notation.

If the function fails, it returns NULL. The data should be copied before another Windows Sockets call is made.

Remarks

This function takes an Internet address structure specified by the in parameter. It returns an ASCII string representing the address in "." notation as "a.b.c.d". Note that the string returned by inet_ntoa resides in memory allocated by the Windows Sockets implementation. If the application needs to use the memory differently, it should copy the information to a private application buffer. The data is guaranteed to be valid until the next Windows Sockets function call within the same thread, but no longer.

See Also

inet_addr


InflateRect
 InflateRect  QuickInfo  Overview  Group

The InflateRect function increases or decreases the width and height of the specified rectangle. The InflateRect function adds dx units to the left and right ends of the rectangle and dy units to the top and bottom. The dx and dy parameters are signed values; positive values increase the width and height, and negative values decrease them.

BOOL InflateRect(

LPRECT  lprc,	// address of rectangle
int  dx,	// amount to increase or decrease width
int  dy	// amount to increase or decrease height
);
Parameters

lprc

Points to the RECT structure that increases or decreases in size.

dx

Specifies the amount to increase or decrease the rectangle width. This parameter must be negative to decrease the width.

dy

Specifies the amount to increase or decrease the rectangle height. This parameter must be negative to decrease the height.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

IntersectRect, OffsetRect, RECT, UnionRect


InitAtomTable
 InitAtomTable  QuickInfo  Overview  Group

The InitAtomTable function initializes the local atom table and sets it to the specified size.

BOOL InitAtomTable(

DWORD  nSize	// size of atom table
);
Parameters

nSize

Specifies the size, in table entries, of the atom table. This value should be a prime number.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

An application need not use this function to use a local atom table. The default size of the local and global atom tables is 37 table entries. If an application does use InitAtomTable, however, it should call the function before any other atom-management function.

If an application uses a large number of local atoms, it can reduce the time required to add an atom to the local atom table or to find an atom in the table by increasing the size of the table. However, this increases the amount of memory required to maintain the table.

The size of the global atom table cannot be changed.

See Also

AddAtom, DeleteAtom, FindAtom, GetAtomName, GlobalAddAtom, GlobalDeleteAtom, GlobalFindAtom, GlobalGetAtomName


InitCommonControls [New - Windows NT]
 InitCommonControls  QuickInfo  Overview  Group

[New - Windows NT]

The InitCommonControls function ensures that the common control dynamic-link library (DLL) is loaded.

void InitCommonControls(VOID);

Return Value

This function does not return a value.


InitializeAcl
 InitializeAcl  QuickInfo  Overview  Group

The InitializeAcl function creates a new ACL structure.

An ACL is an access-control list.

BOOL InitializeAcl(

PACL  pAcl,	// address of access-control list
DWORD  nAclLength,	// size of access-control list
DWORD  dwAclRevision	// revision level of access-control list
);
Parameters

pAcl

Points to an ACL structure initialized by this function.

nAclLength

Specifies the length, in bytes, of the buffer pointed to by the pAcl parameter. This value must be large enough to contain the ACL header and all of the access-control entries (ACEs) to be stored in the ACL.

When calculating the size of an ACL, note that each ACE in an ACL gets the SID specified by its SidStart member copied to the ACE structure, starting at the ACE's SidStart member. Thus, each ACE added to the ACL requires room for the ACE plus room for its SID minus the size of the SidStart member (a DWORD).

For example, the size of an ACL buffer large enough to contain a single ACCESS_ALLOWED_ACE is :

    cbAcl =    sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE)

             + GetLengthSid(pSid) - sizeof(DWORD) ;

Another example: the size of an ACL buffer large enough to contain seven ACCESS_DENIED_ACE structures is :

    cbAcl =  sizeof(ACL) +  7 * ( sizeof(ACCESS_DENIED_ACE) - sizeof(DWORD)) +

             GetLengthSid(pSid1) + GetLengthSid(pSid2) + ... + GetLengthSid(pSid7)

dwAclRevision

Specifies the revision level of the ACL. This parameter must be set to the current revision level, defined as ACL_REVISION for this version of Windows.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The ACL initialized by this function contains no ACEs. It is empty, as opposed to being a nonexistent ACL. If an empty ACL is applied to an object, it implicitly denies all access to that object.

See Also

ACCESS_ALLOWED_ACE, ACCESS_DENIED_ACE, ACL, AddAccessAllowedAce, AddAccessDeniedAce, AddAce, AddAuditAccessAce, DeleteAce, GetAce, GetAclInformation, IsValidAcl, SetAclInformation, SID,


InitializeCriticalSection
 InitializeCriticalSection  QuickInfo  Overview  Group

The InitializeCriticalSection function initializes a critical section object.

VOID InitializeCriticalSection(

LPCRITICAL_SECTION  lpCriticalSection	// address of critical section object
);
Parameters

lpCriticalSection

Points to the critical section object.

Return Value

This function does not return a value.

Remarks

The threads of a single process can use a critical section object for mutual-exclusion synchronization. The process is responsible for allocating the memory used by a critical section object, which it can do by declaring a variable of type CRITICAL_SECTION. Before using a critical section, some thread of the process must call the InitializeCriticalSection function to initialize the object.

Once a critical section object has been initialized, the threads of the process can specify the object in the EnterCriticalSection and LeaveCriticalSection functions to provide mutually exclusive access to a shared resource. For similar synchronization between the threads of different processes, use a mutex object.

A critical section object cannot be moved or copied. The process must also not modify the object, but must treat it as logically opaque. Use only the functions provided in the Win32 application programming interface (API) to manage critical section objects.

See Also

CreateMutex, DeleteCriticalSection, EnterCriticalSection, LeaveCriticalSection


InitializeSecurityDescriptor
 InitializeSecurityDescriptor  QuickInfo  Overview  Group

The InitializeSecurityDescriptor function initializes a new security descriptor.

BOOL InitializeSecurityDescriptor(

PSECURITY_DESCRIPTOR  pSecurityDescriptor,	// address of security descriptor
DWORD  dwRevision	// revision level
);
Parameters

pSecurityDescriptor

Points to a SECURITY_DESCRIPTOR structure that the function initializes.

dwRevision

Specifies the revision level to assign to the security descriptor. This must be SECURITY_DESCRIPTOR_REVISION.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The InitializeSecurityDescriptor function initializes a security descriptor in absolute format, rather than self-relative format.

The InitializeSecurityDescriptor function initializes a security descriptor to have no system ACL, no discretionary ACL, no owner, no primary group, and all control flags set to FALSE (NULL). Thus, except for its revision level, it is empty.

See Also

GetSecurityDescriptorControl, GetSecurityDescriptorDacl, GetSecurityDescriptorGroup, GetSecurityDescriptorLength, GetSecurityDescriptorOwner, GetSecurityDescriptorSacl, IsValidSecurityDescriptor, SECURITY_DESCRIPTOR, SetSecurityDescriptorDacl, SetSecurityDescriptorGroup, SetSecurityDescriptorOwner, SetSecurityDescriptorSacl


InitializeSid
 InitializeSid  QuickInfo  Overview  Group

The InitializeSid function initializes a SID structure. An SID is a security identifier.

BOOL InitializeSid(

PSID  Sid,	// address of SID to initialize
PSID_IDENTIFIER_AUTHORITY  pIdentifierAuthority,	// address of identifier authority
BYTE  nSubAuthorityCount	// count of subauthorities
);
Parameters

Sid

Points to a SID structure to be initialized.

pIdentifierAuthority

Points to a SID_IDENTIFIER_AUTHORITY structure to set in the SID structure.

nSubAuthorityCount

Specifies the number of subauthorities to set in the SID. Values of the subauthority must be set separately, as described in the following Remarks section.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

Although the InitializeSid function sets the number of subauthorities for the SID, it does not set the subauthority values. This must be done separately, using functions, such as GetSidSubAuthority.

An application can use the AllocateAndInitializeSid function to initialize a SID and set its subauthority values.

See Also

AllocateAndInitializeSid, GetLengthSid, GetSidIdentifierAuthority, GetSidLengthRequired, GetSidSubAuthority, GetSidSubAuthorityCount, IsValidSid, SID, SID_IDENTIFIER_AUTHORITY


InitiateSystemShutdown
 InitiateSystemShutdown  QuickInfo  Overview  Group

The InitiateSystemShutdown function initiates a shutdown and optional restart of the specified computer.

BOOL InitiateSystemShutdown(

LPTSTR  lpMachineName,	// address of name of computer to shut down
LPTSTR  lpMessage,	// address of message to display in dialog box
DWORD  dwTimeout,	// time to display dialog box
BOOL  bForceAppsClosed,	// force applications with unsaved changes flag
BOOL  bRebootAfterShutdown	// reboot flag
);
Parameters

lpMachineName

Points to the null-terminated string that specifies the network name of the computer to shut down. If lpMachineName is NULL or points to an empty string, the function shuts down the local computer.

lpMessage

Points to a null-terminated string that specifies a message to display in the shutdown dialog box. This parameter can be NULL if no message is required.

dwTimeout

Specifies the time (in seconds) that the dialog box should be displayed. While this dialog box is displayed, the shutdown can be stopped by the AbortSystemShutdown function.

If dwTimeout is not zero, InitiateSystemShutdown displays a dialog box on the specified computer. The dialog box displays the name of the user who called the function, displays the message specified by the lpMessage parameter, and prompts the user to log off. The dialog box beeps when it is created and remains on top of other windows in the system. The dialog box can be moved but not closed. A timer counts down the remaining time before a forced shutdown. If the user logs off, the system shuts down immediately. Otherwise, the computer is shut down when the timer expires.

If dwTimeout is zero, the computer shuts down without displaying the dialog box, and the shutdown cannot be stopped by AbortSystemShutdown.

bForceAppsClosed

Specifies whether applications with unsaved changes are to be forcibly closed. If this parameter is TRUE, such applications are closed. If this parameter is FALSE, a dialog box is displayed prompting the user to close the applications.

bRebootAfterShutdown

Specifies whether the computer is to restart immediately after shutting down. If this parameter is TRUE, the computer is to restart. If this parameter is FALSE, the system flushes all caches to disk, clears the screen, and displays a message indicating that it is safe to power down.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

To shut down the local computer, the calling process must have the SE_SHUTDOWN_NAME privilege. To shut down a remote computer, the calling process must have the SE_REMOTE_SHUTDOWN_NAME privilege on the remote computer. By default, users can enable the SE_SHUTDOWN_NAME privilege on the computer they are logged onto, and administrators can enable the SE_REMOTE_SHUTDOWN_NAME privilege on remote computers.

Common failures include an invalid or inaccessible computer name or insufficient privilege.

See Also

AbortSystemShutdown


InSendMessage
 InSendMessage  QuickInfo  Overview  Group

The InSendMessage function specifies whether the current window procedure is processing a message that was sent from another thread by a call to the SendMessage function.

BOOL InSendMessage(VOID)

Parameters

This function has no parameters.

Return Value

If the window procedure is processing a message sent to it from another thread by the SendMessage function, the return value is TRUE; otherwise, the return value is FALSE.

See Also

PostThreadMessage, ReplyMessage, SendMessage


InsertMenu
 InsertMenu  QuickInfo  Overview  Group

The InsertMenu function inserts a new menu item into a menu, moving other items down the menu.

BOOL InsertMenu(

HMENU hMenu,	// handle of menu
UINT uPosition,	// menu item that new menu item precedes
UINT uFlags,	// menu item flags
UINT uIDNewItem,	// menu item identifier or pop-up menu handle
LPCTSTR lpNewItem	// menu item content
);
Parameters

hMenu

Identifies the menu to be changed.

uPosition

Specifies the menu item before which the new menu item is to be inserted, as determined by the uFlags parameter.

uFlags

Specifies flags that control the interpretation of the uPosition parameter and the content, appearance, and behavior of the new menu item. This parameter must be a combination of one of the following required values and at least one of the values listed in the following Remarks section.

Value	Description
MF_BYCOMMAND	Indicates that the uPosition parameter gives the identifier of the menu item. The MF_BYCOMMAND flag is the default if neither the MF_BYCOMMAND nor MF_BYPOSITION flag is specified.
MF_BYPOSITION	Indicates that the uPosition parameter gives the zero-based relative position of the new menu item. If uPosition is 0xFFFFFFFF, the new menu item is appended to the end of the menu.
uIDNewItem

Specifies either the identifier of the new menu item or, if the uFlags parameter has the MF_POPUP flag set, the handle of the pop-up menu.

lpNewItem

Specifies the content of the new menu item. The interpretation of lpNewItem depends on whether the uFlags parameter includes the MF_BITMAP, MF_OWNERDRAW, or MF_STRING flag, as follows:

Value	Description
MF_BITMAP	Contains a bitmap handle.
MF_OWNERDRAW	Contains a 32-bit value supplied by the application that can be used to maintain additional data related to the menu item. The value is in the itemData member of the structure pointed to by the lparam parameter of the WM_MEASUREITEM or WM_DRAWITEM message sent when the menu item is created or its appearance is updated.
MF_STRING	Contains a pointer to a null-terminated string (the default).
Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The application must call the DrawMenuBar function whenever a menu changes, whether or not the menu is in a displayed window.

The following list describes the flags that can be set in the uFlags parameter:

Value	Description
MF_BITMAP	Uses a bitmap as the menu item. The lpNewItem parameter contains the handle of 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 except for pop-up menus where the new column is separated from the old column by a vertical line.
MF_MENUBREAK	Places the item on a new line (for menu bars) or in a new column (for pop-up menus) 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 is a pop-up item; that is, selecting it activates a pop-up menu. The uIDNewItem parameter specifies the handle of the pop-up menu. This flag is used to add a pop-up item to a menu bar or to a pop-up menu.
MF_SEPARATOR	Draws a horizontal dividing line. This flag is used only in a pop-up menu. The dividing line cannot be grayed, disabled, or highlighted. The lpNewItem and uIDNewItem parameters are ignored.
MF_STRING	Specifies that the menu item is a text string; the lpNewItem parameter points to the string.
MF_UNCHECKED	Does not place a check mark next to the menu item (default). If the application supplies check mark bitmaps (see the SetMenuItemBitmaps function), this flag displays the unchecked bitmap next to the menu item.
The following list shows groups of flags that cannot be used together:

•	MF_BYCOMMAND and MF_BYPOSITION

•	MF_DISABLED, MF_ENABLED, and MF_GRAYED

•	MF_BITMAP, MF_STRING, MF_OWNERDRAW, and MF_SEPARATOR

•	MF_MENUBARBREAK and MF_MENUBREAK

•	MF_CHECKED and MF_UNCHECKED

See Also

AppendMenu, DeleteMenu, DrawMenuBar, ModifyMenu, RemoveMenu, SetMenuItemBitmaps, WM_DRAWITEM, WM_MEASUREITEM


InsertMenuItem [New - Windows 95]
 InsertMenuItem  QuickInfo  Overview  Group

[New - Windows 95]

The InsertMenuItem function inserts a new menu item at the specified position in a menu bar or pop-up menu.

BOOL WINAPI InsertMenuItem(

HMENU  hMenu,
UINT  uItem,
BOOL  fByPosition,
LPMENUITEMINFO  lpmii
);
Parameters

hMenu

Handle to the menu in which the new menu item is inserted.

uItem

Identifier or position of the menu item before which to insert the new item. The meaning of this parameter depends on the value of fByPosition.

fByPosition

Value specifying the meaning of uItem. If this parameter is FALSE, uItem is a menu item identifier. Otherwise, it is a menu item position.

lpmii

Pointer to a MENUITEMINFO structure that contains information about the new menu item.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To get extended error information, use the GetLastError function.

See Also

MENUITEMINFO


Int32x32To64
 Int32x32To64  QuickInfo  Overview  Group

The Int32x32To64 function multiplies two signed 32-bit integers, returning a signed 64-bit integer result. The function performs optimally on all Win32 platforms.

LONGLONG Int32x32To64(

LONG  Multiplier,	// specifies first signed 32-bit integer for the multiplication
LONG  Multiplicand	// specifies second signed 32-bit integer for the multiplication
);
Parameters

Multiplier

Specifies the first signed 32-bit integer for the multiplication.

Multiplicand

Specifies the second signed 32-bit integer for the multiplication.

Return Value

The return value is the signed 64-bit integer result of the multiplication.

Remarks

This function is implemented on all platforms by optimal inline code: a single multiply instruction that returns a 64-bit result.

Please note that the function's return value is a 64-bit value, not a LARGE_INTEGER structure.

See Also

UInt32x32To64


Int64ShllMod32
 Int64ShllMod32  QuickInfo  Overview  Group

The Int64ShllMod32 function performs a left logical shift operation on an unsigned 64-bit integer value. The function provides improved shifting code for left logical shifts where the shift count is in the range 0 − 31.

DWORDLONG Int64ShllMod32(

DWORDLONG  Value,	// specifies unsigned 64-bit integer to shift left logically
DWORD  ShiftCount	// specifies a shift count in the range 0 − 31
);
Parameters

Value

Specifies the unsigned 64-bit integer to be shifted.

ShiftCount

Specifies a shift count in the range 0 − 31.

Return Value

The return value is the unsigned 64-bit integer result of the left logical shift operation.

Remarks

The shift count is the number of bit positions that the value's bits move.

In a left logical shift operation on an unsigned value, the value's bits move to the left, and vacated bits on the right side of the value are set to zero.

A compiler can generate optimal code for a left logical shift operation when the shift count is a constant. However, if the shift count is a variable whose range of values is unknown, the compiler must assume the worst case, leading to non-optimal code: code that calls a subroutine, or code that is inline but branches. By restricting the shift count to the range 0 − 31, the Int64ShllMod32 function lets the compiler generate optimal or near-optimal code.

Please note that the Int64ShllMod32 function's Value parameter and return value are 64-bit values, not LARGE_INTEGER structures.

See Also

Int64ShraMod32, Int64ShrlMod32


Int64ShraMod32
 Int64ShraMod32  QuickInfo  Overview  Group

The Int64ShraMod32 function performs a right arithmetic shift operation on a signed 64-bit integer value. The function provides improved shifting code for right arithmetic shifts where the shift count is in the range 0 − 31.

LONGLONG Int64ShraMod32(

LONGLONG  Value,	// specifies signed 64-bit integer to shift right arithmetically
DWORD  ShiftCount	// specifies a shift count in the range 0 − 31
);
Parameters

Value

Specifies the signed 64-bit integer to be shifted.

ShiftCount

Specifies a shift count in the range 0 − 31.

Return Value

The return value is the signed 64-bit integer result of the right arithmetic shift operation.

Remarks

The shift count is the number of bit positions that the value's bits move.

In a right arithmetic shift operation on a signed value, the value's bits move to the right, and vacated bits on the left side of the value are set to the value of the sign bit.

A compiler can generate optimal code for a right arithmetic shift operation when the shift count is a constant. However, if the shift count is a variable whose range of values is unknown, the compiler must assume the worst case, leading to non-optimal code: code that calls a subroutine, or code that is inline but branches. By restricting the shift count to the range 0 − 31, the Int64ShraMod32 function lets the compiler generate optimal or near-optimal code.

Please note that the Int64ShraMod32 function's Value parameter and return value are 64-bit values, not LARGE_INTEGER structures.

See Also

Int64ShllMod32, Int64ShrlMod32


Int64ShrlMod32
 Int64ShrlMod32  QuickInfo  Overview  Group

The Int64ShrlMod32 function performs a right logical shift operation on an unsigned 64-bit integer value. The function provides improved shifting code for right logical shifts where the shift count is in the range 0 − 31.

DWORDLONG Int64ShrlMod32(

DWORDLONG  Value,	// specifies unsigned 64-bit integer to shift right logically
DWORD  ShiftCount	// specifies a shift count in the range 0 − 31
);
Parameters

Value

Specifies the unsigned 64-bit integer to be shifted.

ShiftCount

Specifies a shift count in the range 0 − 31.

Return Value

The return value is the unsigned 64-bit integer result of the right logical shift operation.

Remarks

The shift count is the number of bit positions that the value's bits move.

In a right logical shift operation on an unsigned value, the value's bits move to the right, and vacated bits on the left side of the value are set to zero.

A compiler can generate optimal code for a right logical shift operation when the shift count is a constant. However, if the shift count is a variable whose range of values is unknown, the compiler must assume the worst case, leading to non-optimal code: code that calls a subroutine, or code that is inline but branches. By restricting the shift count to the range 0 − 31, the Int64ShrlMod32 function lets the compiler generate optimal or near-optimal code.

Please note that the Int64ShrlMod32 function's Value parameter and return value are 64-bit values, not LARGE_INTEGER structures.

See Also

Int64ShllMod32, Int64ShraMod32


InterlockedDecrement
 InterlockedDecrement  QuickInfo  Overview  Group

The InterlockedDecrement function both decrements (decreases by one) the value of the specified 32-bit variable and checks the resulting value. The function prevents more than one thread from using the InterlockedDecrement or InterlockedIncrement function to access the same variable simultaneously.

LONG InterlockedDecrement(

LPLONG  lpAddend	// address of the variable to decrement
);
Parameters

lpAddend

Points to the 32-bit variable to decrement.

Return Value

If the result of the decrement is zero, the return value is zero.

If the result of the decrement is less than zero, the return value is less than zero. If the result of the decrement is greater than zero, the return value is greater than zero. A nonzero return value may not be equal to the result of the decrement.

Remarks

InterlockedDecrement, InterlockedExchange, and InterlockedIncrement provide a simple mechanism for synchronizing access to a variable that is shared by multiple threads. The threads of different processes can use this mechanism if the variable is in shared memory.

The variable pointed to by the lpAddend parameter must be aligned on a 32-bit boundary; otherwise, this function will fail on multiprocessor x86 systems.

See Also

InterlockedExchange, InterlockedIncrement


InterlockedExchange
 InterlockedExchange  QuickInfo  Overview  Group

The InterlockedExchange function atomically exchanges a pair of 32-bit values.

LONG InterlockedExchange(

LPLONG  Target,	// address of 32-bit value to exchange
LONG  Value	// new value for the LONG value pointed to by Target
);
Parameters

Target

Address of the LONG value to exchange. The function sets this LONG value to Value, and returns its prior value.

Value

Specifies a new value for the LONG value pointed to by Target.

Return Value

The function returns the prior value of the LONG value pointed to by Target.

Remarks

InterlockedExchange, InterlockedDecrement, and InterlockedIncrement provide a simple mechanism for synchronizing access to a variable that is shared by multiple threads. The threads of different processes can use this mechanism if the variable is in shared memory.

The variable pointed to by the Target parameter must be aligned on a 32-bit boundary; otherwise, this function will fail on multiprocessor x86 systems.

See Also

InterlockedDecrement, InterlockedIncrement


InterlockedIncrement
 InterlockedIncrement  QuickInfo  Overview  Group

The InterlockedIncrement function both increments (increases by one) the value of the specified 32-bit variable and checks the resulting value. The function prevents more than one thread from using the InterlockedDecrement or InterlockedIncrement function to access the same variable simultaneously.

LONG InterlockedIncrement(

LPLONG  lpAddend	// address of the variable to increment
);
Parameters

lpAddend

Points to the 32-bit variable to increment.

Return Value

If the result of the increment is zero, the return value is zero.

If the result of the increment is less than zero, the return value is less than zero. If the result of the increment is greater than zero, the return value is greater than zero. A nonzero return value may not be equal to the result of the increment.

Remarks

InterlockedDecrement, InterlockedIncrement, and InterlockedExchange provide a simple mechanism for synchronizing access to a variable that is shared by multiple threads. The threads of different processes can use this mechanism if the variable is in shared memory.

The variable pointed to by the lpAddend parameter must be aligned on a 32-bit boundary; otherwise, this function will fail on multiprocessor x86 systems.

See Also

InterlockedDecrement, InterlockedExchange


IntersectClipRect
 IntersectClipRect  QuickInfo  Overview  Group

The IntersectClipRect function creates a new clipping region from the intersection of the current clipping region and the specified rectangle.

int IntersectClipRect(

HDC  hdc,	// handle of device context
int  nLeftRect,	// x-coordinate of upper-left corner of rectangle
int  nTopRect,	// y-coordinate of upper-left corner of rectangle
int  nRightRect,	// x-coordinate of lower-right corner of rectangle
int  nBottomRect	// y-coordinate of lower-right corner of rectangle
);
Parameters

hdc

Identifies the device context.

nLeftRect

Specifies the logical x-coordinate of the upper-left corner of the rectangle.

nTopRect

Specifies the logical y-coordinate of the upper-left corner of the rectangle.

nRightRect

Specifies the logical x-coordinate of the lower-right corner of the rectangle.

nBottomRect

Specifies the logical y-coordinate of the lower-right corner of the rectangle.

Return Value

If the function succeeds, the return value specifies the new clipping region's type and can be any one of the following values:

Value	Meaning
NULLREGION	Region is empty.
SIMPLEREGION	Region is a single rectangle.
COMPLEXREGION	Region is more than one rectangle.
ERROR	An error occurred. (The current clipping region is unaffected.)
Remarks

The lower and rightmost edges of the given rectangle are excluded from the clipping region.

See Also

ExcludeClipRect


IntersectRect
 IntersectRect  QuickInfo  Overview  Group

The IntersectRect function calculates the intersection of two source rectangles and places the coordinates of the intersection rectangle into the destination rectangle. If the source rectangles do not intersect, an empty rectangle (in which all coordinates are set to zero) is placed into the destination rectangle.

BOOL IntersectRect(

LPRECT  lprcDst,	// address of structure for intersection
CONST RECT  * lprcSrc1,	// address of structure with first rectangle
CONST RECT  * lprcSrc2	// address of structure with second rectangle
);
Parameters

lprcDst

Points to the RECT structure that is to receive the intersection of the rectangles pointed to by the lprcSrc1 and lprcSrc2 parameters.

lprcSrc1

Points to the RECT structure that contains the first source rectangle.

lprcSrc2

Points to the RECT structure that contains the second source rectangle.

Return Value

If the rectangles intersect, the return value is TRUE; otherwise, it is FALSE. To get extended error information, call GetLastError.

See Also

InflateRect, OffsetRect, RECT, UnionRect


InvalidateRect
 InvalidateRect  QuickInfo  Overview  Group

The InvalidateRect function adds a rectangle to the specified window's update region. The update region represents the portion of the window's client area that must be redrawn.

BOOL InvalidateRect(

HWND  hWnd,	// handle of window with changed update region
CONST RECT  * lpRect,	// address of rectangle coordinates
BOOL  bErase	// erase-background flag
);
Parameters

hWnd

Identifies the window whose update region has changed. If this parameter is NULL, Windows invalidates and redraws all windows, and sends the WM_ERASEBKGND and WM_NCPAINT messages to the window procedure before the function returns.

lpRect

Points to a RECT structure that contains the client coordinates of the rectangle to be added to the update region. If this parameter is NULL, the entire client area is added to the update region.

bErase

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 Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

The invalidated areas accumulate in the update region until the region is processed when the next WM_PAINT message occurs or until the region is validated by using the ValidateRect or ValidateRgn function.

Windows sends a WM_PAINT message to a window whenever its update region is not empty and there are no other messages in the application queue for that window.

If the bErase parameter is TRUE for any part of the update region, the background is erased in the entire region, not just in the given part.

See Also

BeginPaint, InvalidateRgn, RECT, ValidateRect, ValidateRgn, WM_ERASEBKGND, WM_NCPAINT, WM_PAINT,


InvalidateRgn
 InvalidateRgn  QuickInfo  Overview  Group

The InvalidateRgn function invalidates the client area within the specified region by adding it to the current update region of a window. The invalidated region, along with all other areas in the update region, is marked for painting when the next WM_PAINT message occurs.

BOOL InvalidateRgn(

HWND  hWnd,	// handle of window with changed update region
HRGN  hRgn,	// handle of region to add
BOOL  bErase	// erase-background flag
);
Parameters

hWnd

Identifies the window with an update region that is to be modified.

hRgn

Identifies the region to be added to the update region. The region is assumed to have client coordinates. If this parameter is NULL, the entire client area is added to the update region.

bErase

Specifies whether the background within the update region should be erased when the update region is processed. If this parameter is TRUE, the background is erased when the BeginPaint function is called. If the parameter is FALSE, the background remains unchanged.

Return Value

This function always returns TRUE.

Remarks

Invalidated areas accumulate in the update region until the next WM_PAINT message is processed or until the region is validated by using the ValidateRect or ValidateRgn function.

Windows sends a WM_PAINT message to a window whenever its update region is not empty and there are no other messages in the application queue for that window.

The specified region must have been created by using one of the region functions.

If the bErase parameter is TRUE for any part of the update region, the background in the entire region is erased, not just in the specified part.

See Also

BeginPaint, InvalidateRect, ValidateRect, ValidateRgn, WM_PAINT


InvertRect
 InvertRect  QuickInfo  Overview  Group

The InvertRect function inverts a rectangle in a window by performing a logical NOT operation on the color values for each pixel in the rectangle's interior.

BOOL InvertRect(

HDC  hDC,	// handle of device context
CONST RECT  * lprc	// address of structure with rectangle
);
Parameters

hDC

Identifies the device context.

lprc

Points to a RECT structure that contains the logical coordinates of the rectangle to be inverted.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

On monochrome screens, InvertRect makes white pixels black and black pixels white. On color screens, the inversion depends on how colors are generated for the screen. Calling InvertRect twice for the same rectangle restores the display to its previous colors.

See Also

FillRect, RECT


InvertRgn
 InvertRgn  QuickInfo  Overview  Group

The InvertRgn function inverts the colors in the specified region.

BOOL InvertRgn(

HDC  hdc,	// handle of device context
HRGN  hrgn	// handle of region to be inverted
);
Parameters

hdc

Identifies the device context.

hrgn

Identifies the region for which colors are inverted. The region's coordinates are presumed to be logical coordinates.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

On monochrome screens, the InvertRgn function makes white pixels black and black pixels white. On color screens, this inversion is dependent on the type of technology used to generate the colors for the screen.

See Also

FillRgn, PaintRgn


IOCTL_DISK_CHECK_VERIFY
 IOCTL_DISK_CHECK_VERIFY  QuickInfo  Overview  Group

The IOCTL_DISK_CHECK_VERIFY DeviceIoControl operation determines whether a device's media is accessible; for example, whether the media is in the device.

dwIoControlCode = IOCTL_DISK_CHECK_VERIFY ;   // operation code

lpvInBuffer = NULL;       // address of input buffer; not used; must be NULL

cbInBuffer = 0;           // size of input buffer; not used; must be zero

lpvOutBuffer = NULL;      // address of output buffer; not used; must be NULL

cbOutBuffer = 0;          // size of output buffer; not used; must be zero

lpcbBytesReturned;        // address of actual bytes of output

Parameters

lpvInBuffer

Points to an input buffer. Not used with this operation. Set to NULL.

cbInBuffer

Specifies the size, in bytes, of the buffer pointed to by lpvInBuffer. Not used with this operation. Set to zero.

lpvOutBuffer

Points to an output buffer. Not used with this operation. Set to NULL.

cbOutBuffer

Specifies the size, in bytes, of the buffer pointed to by lpvOutBuffer. Not used with this operation. Set to zero.

lpcbBytesReturned

Points to a DWORD that receives the actual size, in bytes, of the data stored into lpvOutBuffer.

Return Value

If the operation succeeds and the device media is accessible, DeviceIoControl returns TRUE.

If the operation fails, DeviceIoControl returns FALSE.

See Also

DeviceIoControl


IOCTL_DISK_EJECT_MEDIA
 IOCTL_DISK_EJECT_MEDIA  QuickInfo  Overview  Group

The IOCTL_DISK_EJECT_MEDIA DeviceIoControl operation causes media to be ejected from a SCSI device.

dwIoControlCode = IOCTL_DISK_EJECT_MEDIA;   // operation code

lpvInBuffer = NULL;       // address of input buffer; not used; must be NULL

cbInBuffer = 0;           // size of input buffer; not used; must be zero

lpvOutBuffer = NULL;      // address of output buffer; not used; must be NULL

cbOutBuffer = 0;          // size of output buffer; not used; must be zero

lpcbBytesReturned;        // address of actual bytes of output

Parameters

lpvInBuffer

Points to an input buffer. Not used with this operation. Set to NULL.

cbInBuffer

Specifies the size, in bytes, of the buffer pointed to by lpvInBuffer. Not used with this operation. Set to zero.

lpvOutBuffer

Points to an output buffer. Not used with this operation. Set to NULL.

cbOutBuffer

Specifies the size, in bytes, of the buffer pointed to by lpvOutBuffer. Not used with this operation. Set to zero.

lpcbBytesReturned

Points to a DWORD that receives the actual size, in bytes, of the data stored into lpvOutBuffer.

Return Value

If the operation succeeds, DeviceIoControl returns TRUE.

If the operation fails, DeviceIoControl returns FALSE. To get extended error information, call GetLastError.

Remarks

IOCTL_DISK_EJECT_MEDIA may or may not be supported on SCSI devices that support removable media.

See Also

DeviceIoControl, IOCTL_DISK_MEDIA_REMOVAL, IOCTL_DISK_LOAD_MEDIA


IOCTL_DISK_FORMAT_TRACKS
 IOCTL_DISK_FORMAT_TRACKS  QuickInfo  Overview  Group

The IOCTL_DISK_FORMAT_TRACKS DeviceIoControl operation formats a specified, contiguous set of tracks on a disk.

dwIoControlCode = IOCTL_DISK_FORMAT_TRACKS;   // operation code

lpvInBuffer;              // address of input buffer

cbInBuffer;               // size of input buffer

lpvOutBuffer = NULL;      // address of output buffer; not used; must be NULL

cbOutBuffer = 0;          // size of output buffer; not used; must be zero

lpcbBytesReturned;        // address of actual bytes of output

Parameters

lpvInBuffer

Points to a buffer that contains a FORMAT_PARAMETERS data structure.

cbInBuffer

Specifies the size, in bytes, of the buffer pointed to by lpvInBuffer, which must be large enough to contain a FORMAT_PARAMETERS data structure.

lpvOutBuffer

Points to an output buffer. Not used with this operation. Set to NULL.

cbOutBuffer

Specifies the size, in bytes, of the buffer pointed to by lpvOutBuffer. Not used with this operation. Set to zero.

lpcbBytesReturned

Points to a DWORD that receives the actual size, in bytes, of the data stored into lpvOutBuffer.

Return Value

If the operation succeeds, DeviceIoControl returns TRUE.

If the operation fails, DeviceIoControl returns FALSE. To get extended error information, call GetLastError.

Remarks

This device I/O control operation is for floppy disk devices only.

See Also

DeviceIoControl, FORMAT_PARAMETERS


IOCTL_DISK_GET_DRIVE_GEOMETRY
 IOCTL_DISK_GET_DRIVE_GEOMETRY  QuickInfo  Overview  Group

The IOCTL_DISK_GET_DRIVE_GEOMETRY DeviceIoControl operation returns information about the physical disk's geometry: type, number of cylinders, tracks per cylinder, sectors per track, and bytes per sector.

dwIoControlCode = IOCTL_DISK_GET_DRIVE_GEOMETRY;   // operation code

lpvInBuffer = NULL; // address of input buffer; not used; must be NULL

cbInBuffer = 0;     // size of input buffer; not used; must be zero

lpvOutBuffer ;      // address of output buffer

cbOutBuffer ;       // size of output buffer

lpcbBytesReturned ; // address of actual bytes of output

Parameters

lpvInBuffer

Points to an input buffer. Not used with this operation. Set to NULL.

cbInBuffer

Specifies the size, in bytes, of the buffer pointed to by lpvInBuffer. Not used with this operation. Set to zero.

lpvOutBuffer

Points to a buffer that will receive a DISK_GEOMETRY data structure.

cbOutBuffer

Specifies the size, in bytes, of the buffer pointed to by lpvOutBuffer, which must be greater than or equal to the size of a DISK_GEOMETRY data structure.

lpcbBytesReturned

Points to a DWORD that receives the actual size, in bytes, of the data stored into lpvOutBuffer.

Return Value

If the operation succeeds, DeviceIoControl returns TRUE.

If the operation fails, DeviceIoControl returns FALSE. To get extended error information, call GetLastError.

Remarks

This device I/O control operation is for disk devices.

See Also

DeviceIoControl, DISK_GEOMETRY, IOCTL_DISK_GET_MEDIA_TYPES


IOCTL_DISK_GET_DRIVE_LAYOUT
 IOCTL_DISK_GET_DRIVE_LAYOUT  QuickInfo  Overview  Group

The IOCTL_DISK_GET_DRIVE_LAYOUT DeviceIoControl operation returns information about the number of partitions on a disk and the features of each partition.

dwIoControlCode = IOCTL_DISK_GET_DRIVE_LAYOUT;   // operation code

lpvInBuffer = NULL; // address of input buffer; not used; must be NULL

cbInBuffer = 0;     // size of input buffer; not used; must be zero

lpvOutBuffer ;      // address of output buffer

cbOutBuffer ;       // size of output buffer

lpcbBytesReturned ; // address of actual bytes of output

Parameters

lpvInBuffer

Points to an input buffer. Not used with this operation. Set to NULL.

cbInBuffer

Specifies the size, in bytes, of the buffer pointed to by lpvInBuffer. Not used with this operation. Set to zero.

lpvOutBuffer

Points to a buffer that will receive a DRIVE_LAYOUT_INFORMATION structure and a series of PARTITION_INFORMATION structures, one of the latter for each partition on the drive.

cbOutBuffer

Specifies the size, in bytes, of the buffer pointed to by lpvOutBuffer, which must be large enough to contain one DRIVE_LAYOUT_INFORMATION data structure and as many PARTITION_INFORMATION data structures as there are partitions on the drive.

lpcbBytesReturned

Points to a DWORD that receives the actual size, in bytes, of the data stored into lpvOutBuffer.

Return Value

If the operation succeeds, DeviceIoControl returns TRUE.

If the operation fails, DeviceIoControl returns FALSE. To get extended error information, call GetLastError.

Remarks

This device I/O control operation is for disk devices. Floppy disk drivers, however, do not need to handle this operation.

See Also

DeviceIoControl, DRIVE_LAYOUT_INFORMATION, IOCTL_DISK_SET_DRIVE_LAYOUT, PARTITION_INFORMATION


IOCTL_DISK_GET_MEDIA_TYPES
 IOCTL_DISK_GET_MEDIA_TYPES  QuickInfo  Overview  Group

The IOCTL_DISK_GET_MEDIA_TYPES DeviceIoControl operation returns information about the types of media a device driver supports.

dwIoControlCode = IOCTL_DISK_GET_MEDIA_TYPES;   // operation code

lpvInBuffer = NULL; // address of input buffer; not used; must be NULL

cbInBuffer = 0;     // size of input buffer; not used; must be zero

lpvOutBuffer ;      // address of output buffer

cbOutBuffer ;       // size of output buffer

lpcbBytesReturned;  // address of actual bytes of output

Parameters

lpvInBuffer

Points to an input buffer. Not used with this operation. Set to NULL.

cbInBuffer

Specifies the size, in bytes, of the buffer pointed to by lpvInBuffer. Not used with this operation. Set to zero.

lpvOutBuffer

Points to a buffer that will receive an array of DISK_GEOMETRY data structures specifying the media types the device driver supports.

cbOutBuffer

Specifies the size, in bytes, of the buffer pointed to by lpvOutBuffer, which must be large enough to contain as many DISK_GEOMETRY structures as there are media that the driver supports.

lpcbBytesReturned

Points to a DWORD that receives the actual size, in bytes, of the data stored into lpvOutBuffer.

Return Value

If the operation succeeds, DeviceIoControl returns TRUE.

If the operation fails, DeviceIoControl returns FALSE. To get extended error information, call GetLastError.

Remarks

This device I/O control operation is for all class drivers, as well as non-computer system interface (SCSI) hard drives and floppy disk devices.

See Also

DeviceIoControl, DISK_GEOMETRY, IOCTL_DISK_GET_DRIVE_GEOMETRY


IOCTL_DISK_GET_PARTITION_INFO
 IOCTL_DISK_GET_PARTITION_INFO  QuickInfo  Overview  Group

The IOCTL_DISK_GET_PARTITION_INFO DeviceIoControl operation returns information about the type, size, and nature of a disk partition.

dwIoControlCode = IOCTL_DISK_GET_PARTITION_INFO ;   // operation code

lpvInBuffer = NULL;   // address of input buffer; not used; must be NULL

cbInBuffer = 0;       // size of input buffer; not used; must be zero

lpvOutBuffer;         // address of output buffer

cbOutBuffer;          // size of output buffer

lpcbBytesReturned;    // address of actual bytes of output

Parameters

lpvInBuffer

Points to an input buffer. Not used with this operation. Set to NULL.

cbInBuffer

Specifies the size, in bytes, of the buffer pointed to by lpvInBuffer. Not used with this operation. Set to zero.

lpvOutBuffer

Points to a buffer that will receive a PARTITION_INFORMATION data structure.

cbOutBuffer

Specifies the size, in bytes, of the buffer pointed to by lpvOutBuffer, which must be large enough to contain a PARTITION_INFORMATION data structure.

lpcbBytesReturned

Points to a DWORD that receives the actual size, in bytes, of the data stored into lpvOutBuffer.

Return Value

If the operation succeeds, DeviceIoControl returns TRUE.

If the operation fails, DeviceIoControl returns FALSE. To get extended error information, call GetLastError.

Remarks

This device I/O control operation is for disk devices. Floppy disk drivers, however, do not need to handle this operation.

See Also

DeviceIoControl, IOCTL_DISK_SET_PARTITION_INFO, PARTITION_INFORMATION


IOCTL_DISK_LOAD_MEDIA
 IOCTL_DISK_LOAD_MEDIA  QuickInfo  Overview  Group

The IOCTL_DISK_LOAD_MEDIA DeviceIoControl operation causes media to be loaded into a device.

dwIoControlCode = IOCTL_DISK_LOAD_MEDIA;   // operation code

lpvInBuffer = NULL;   // address of input buffer; not used; must be NULL

cbInBuffer = 0;       // size of input buffer; not used; must be zero

lpvOutBuffer = NULL;  // address of output buffer; not used; must be NULL

cbOutBuffer = 0;      // size of output buffer; not used; must be zero

lpcbBytesReturned;    // address of actual bytes of output

Parameters

lpvInBuffer

Points to an input buffer. Not used with this operation. Set to NULL.

cbInBuffer

Specifies the size, in bytes, of the buffer pointed to by lpvInBuffer. Not used with this operation. Set to zero.

lpvOutBuffer

Points to an output buffer. Not used with this operation. Set to NULL.

cbOutBuffer

Specifies the size, in bytes, of the buffer pointed to by lpvOutBuffer. Not used with this operation. Set to zero.

lpcbBytesReturned

Points to a DWORD that receives the actual size, in bytes, of the data stored into lpvOutBuffer.

Remarks

The IOCTL_DISK_LOAD_MEDIA is valid only for devices that support loadable media.

See Also

DeviceIoControl, IOCTL_DISK_EJECT_MEDIA, IOCTL_DISK_MEDIA_REMOVAL


IOCTL_DISK_MEDIA_REMOVAL
 IOCTL_DISK_MEDIA_REMOVAL  QuickInfo  Overview  Group

The IOCTL_DISK_MEDIA_REMOVAL DeviceIoControl operation enables or disables the mechanism that ejects media, for those devices possessing that locking capability.

dwIoControlCode = IOCTL_DISK_MEDIA_REMOVAL;   // operation code

lpvInBuffer;              // address of input buffer

cbInBuffer;               // size of input buffer

lpvOutBuffer = NULL;      // address of output buffer; not used; must be NULL

cbOutBuffer = 0;          // size of output buffer; not used; must be zero

lpcbBytesReturned;        // address of actual bytes of output

Parameters

lpvInBuffer

Points to a buffer that contains a PREVENT_MEDIA_REMOVAL data structure.

A TRUE value for that structure's PreventMediaRemoval member specifies that media removal is prevented (the device is locked). A FALSE value specifies that media removal is allowed.

cbInBuffer

Specifies the size, in bytes, of the buffer pointed to by lpvInBuffer, which must be large enough to contain a PREVENT_MEDIA_REMOVAL data structure.

lpvOutBuffer

Points to an output buffer. Not used with this operation. Set to NULL.

cbOutBuffer

Specifies the size, in bytes, of the buffer pointed to by lpvOutBuffer. Not used with this operation. Set to zero.

lpcbBytesReturned

Points to a DWORD that receives the actual size, in bytes, of the data stored into lpvOutBuffer.

Return Value

If the operation succeeds, DeviceIoControl returns TRUE.

If the operation fails, DeviceIoControl returns FALSE. To get extended error information, call GetLastError.

Remarks

The IOCTL_DISK_MEDIA_REMOVAL operation is valid only for devices that support removable media.

See Also

DeviceIoControl, IOCTL_DISK_EJECT_MEDIA, IOCTL_DISK_LOAD_MEDIA, PREVENT_MEDIA_REMOVAL


IOCTL_DISK_PERFORMANCE
 IOCTL_DISK_PERFORMANCE  QuickInfo  Overview  Group

The IOCTL_DISK_PERFORMANCE DeviceIoControl operation provides disk performance information.

dwIoControlCode = IOCTL_DISK_PERFORMANCE;   // operation code

lpvInBuffer = NULL; // address of input buffer; not used; must be NULL

cbInBuffer = 0;     // size of input buffer; not used; must be zero

lpvOutBuffer;       // address of output buffer

cbOutBuffer;        // size of output buffer

lpcbBytesReturned;  // address of actual bytes of output

Parameters

lpvInBuffer

Points to an input buffer. Not used with this operation. Set to NULL.

cbInBuffer

Specifies the size, in bytes, of the buffer pointed to by lpvInBuffer. Not used with this operation. Set to zero.

lpvOutBuffer

Points to a buffer that will receive a DISK_PERFORMANCE data structure.

cbOutBuffer

Specifies the size, in bytes, of the buffer pointed to by lpvOutBuffer, which must be large enough to contain a DISK_PERFORMANCE data structure.

lpcbBytesReturned

Points to a DWORD that receives the actual size, in bytes, of the data stored into lpvOutBuffer.

Return Value

If the operation succeeds, DeviceIoControl returns TRUE.

If the operation fails, DeviceIoControl returns FALSE. To get extended error information, call GetLastError.

Remarks

This device I/O control operation is for disk devices.

See Also

DeviceIoControl, DISK_PERFORMANCE


IOCTL_DISK_REASSIGN_BLOCKS
 IOCTL_DISK_REASSIGN_BLOCKS  QuickInfo  Overview  Group

The IOCTL_DISK_REASSIGN_BLOCKS DeviceIoControl operation directs the disk device to map one or more blocks to its spare-block pool.

dwIoControlCode = IOCTL_DISK_REASSIGN_BLOCKS;   // operation code

lpvInBuffer;              // address of input buffer

cbInBuffer;               // size of input buffer

lpvOutBuffer = NULL;      // address of output buffer; not used; must be NULL

cbOutBuffer = 0;          // size of output buffer; not used; must be zero

lpcbBytesReturned;        // address of actual bytes of output

Parameters

lpvInBuffer

Points to a buffer that contains a REASSIGN_BLOCKS data structure specifying the blocks to reassign to its spare block pool.

cbInBuffer

Specifies the size, in bytes, of the buffer pointed to by lpvInBuffer, which must be large enough to contain the REASSIGN_BLOCKS data structure. Note that this structure is really a header followed by an array of block specifiers; thus, it varies in size according to the number of blocks to be reassigned; each block after the first adds the size of a DWORD to the overall size.

lpvOutBuffer

Points to an output buffer. Not used with this operation. Set to NULL.

cbOutBuffer

Specifies the size, in bytes, of the buffer pointed to by lpvOutBuffer. Not used with this operation. Set to zero.

lpcbBytesReturned

Points to a DWORD that receives the actual size, in bytes, of the data stored into lpvOutBuffer.

Return Value

If the operation succeeds, DeviceIoControl returns TRUE.

If the operation fails, DeviceIoControl returns FALSE. To get extended error information, call GetLastError.

Remarks

This device I/O control operation is for disk devices.

See Also

DeviceIoControl, REASSIGN_BLOCKS


IOCTL_DISK_SET_DRIVE_LAYOUT
 IOCTL_DISK_SET_DRIVE_LAYOUT  QuickInfo  Overview  Group

The IOCTL_DISK_SET_DRIVE_LAYOUT DeviceIoControl operation partitions a disk as specified by drive layout and partition information data.

dwIoControlCode = IOCTL_DISK_SET_DRIVE_LAYOUT;   // operation code

lpvInBuffer;              // address of input buffer

cbInBuffer;               // size of input buffer

lpvOutBuffer = NULL;      // address of output buffer; not used; must be NULL

cbOutBuffer = 0;          // size of output buffer; not used; must be zero

lpcbBytesReturned;        // address of actual bytes of output

Parameters

lpvInBuffer

Points to a buffer that contains drive layout and partition information data. The data exists as a DRIVE_LAYOUT_INFORMATION data structure and a series of PARTITION_INFORMATION data structures, one of the latter for each proposed partition on the drive.

cbInBuffer

Specifies the size, in bytes, of the buffer pointed to by lpvInBuffer, which must be large enough to contain one DRIVE_LAYOUT_INFORMATION data structure and as many PARTITION_INFORMATION data structures as there are proposed partitions on the drive.

lpvOutBuffer

Points to an output buffer. Not used with this operation. Set to NULL.

cbOutBuffer

Specifies the size, in bytes, of the buffer pointed to by lpvOutBuffer. Not used with this operation. Set to zero.

lpcbBytesReturned

Points to a DWORD that receives the actual size, in bytes, of the data stored into lpvOutBuffer.

Return Value

If the operation succeeds, DeviceIoControl returns TRUE.

If the operation fails, DeviceIoControl returns FALSE. To get extended error information, call GetLastError.

Remarks

This device I/O control operation is for disk devices. Floppy disk drivers, however, need not handle this operation.

See Also

DeviceIoControl, DRIVE_LAYOUT_INFORMATION, IOCTL_DISK_GET_DRIVE_LAYOUT, PARTITION_INFORMATION


IOCTL_DISK_SET_PARTITION_INFO
 IOCTL_DISK_SET_PARTITION_INFO  QuickInfo  Overview  Group

The IOCTL_DISK_SET_PARTITION_INFO DeviceIoControl operation sets the partition type of the specified disk partition.

dwIoControlCode = IOCTL_DISK_SET_PARTITION_INFO;   // operation code

lpvInBuffer;              // address of input buffer

cbInBuffer;               // size of input buffer

lpvOutBuffer = NULL;      // address of output buffer; not used; must be NULL

cbOutBuffer = 0;          // size of output buffer; not used; must be zero

lpcbBytesReturned;        // address of actual bytes of output

Parameters

lpvInBuffer

Points to a buffer that contains the partition data to be set. The data exists as a SET_PARTITION_INFORMATION data structure.

cbInBuffer

Specifies the size, in bytes, of the buffer pointed to by lpvInBuffer, which must be large enough to contain a SET_PARTITION_INFORMATION data structure.

lpvOutBuffer

Points to an output buffer. Not used with this operation. Set to NULL.

cbOutBuffer

Specifies the size, in bytes, of the buffer pointed to by lpvOutBuffer. Not used with this operation. Set to zero.

lpcbBytesReturned

Points to a DWORD that receives the actual size, in bytes, of the data stored into lpvOutBuffer. Not used with this operation. Set to NULL.

Return Value

If the operation succeeds, DeviceIoControl returns TRUE.

If the operation fails, DeviceIoControl returns FALSE. To get extended error information, call GetLastError.

Remarks

This device I/O control operation is for disk devices. Floppy disk drivers, however, need not handle this operation.

See Also

DeviceIoControl, IOCTL_DISK_GET_PARTITION_INFO, SET_PARTITION_INFORMATION


IOCTL_DISK_VERIFY
 IOCTL_DISK_VERIFY  QuickInfo  Overview  Group

The IOCTL_DISK_VERIFY DeviceIoControl operation performs a logical format of a specified extent on a disk.

dwIoControlCode = IOCTL_DISK_VERIFY;   // operation code

lpvInBuffer;          // address of input buffer

cbInBuffer;           // size of input buffer

lpvOutBuffer = NULL;  // address of output buffer; not used; must be NULL

cbOutBuffer = 0;      // size of output buffer; not used; must be zero

lpcbBytesReturned;    // address of actual bytes of output

Parameters

lpvInBuffer

Points to a buffer that contains a VERIFY_INFORMATION data structure.

cbInBuffer

Specifies the size, in bytes, of the buffer pointed to by lpvInBuffer, which must be large enough to contain a VERIFY_INFORMATION data structure.

lpvOutBuffer

Points to an output buffer. Not used with this operation. Set to NULL.

cbOutBuffer

Specifies the size, in bytes, of the buffer pointed to by lpvOutBuffer. Not used with this operation. Set to zero.

lpcbBytesReturned

Points to a DWORD that receives the actual size, in bytes, of the data stored into lpvOutBuffer.

Return Value

If the operation succeeds, DeviceIoControl returns TRUE.

If the operation fails, DeviceIoControl returns FALSE. To get extended error information, call GetLastError.

Remarks

This device I/O control operation is for disk devices. Floppy disk drivers, however, need not handle this operation.

See Also

DeviceIoControl, IOCTL_DISK_CHECK_VERIFY, VERIFY_INFORMATION


IOCTL_SERIAL_LSRMST_INSERT
 IOCTL_SERIAL_LSRMST_INSERT  QuickInfo  Overview  Group

The IOCTL_SERIAL_LSRMST_INSERT DeviceIoControl operation enables or disables the placement of line status and modem status values into the regular data stream that an application acquires through the ReadFile function.

When this line-status and modem-status data placement mode is enabled, status values are preceded in the data stream by an escape character. The user-definable escape character is set by the IOCTL_SERIAL_LSRMST_INSERT operation. Status values consist of 1 to 3 BYTEs. See the Remarks section below for status value details.

dwIoControlCode = IOCTL_SERIAL_LSRMST_INSERT;     // operation code

lpvInBuffer;            // address of input buffer

cbInBuffer;             // size of input buffer

lpvOutBuffer = NULL;    // address of output buffer; not used; must be NULL

cbOutBuffer = 0;        // size of output buffer; not used; must be zero

lpcbBytesReturned;      // address of actual bytes of output

Parameters

lpvInBuffer

Points to a buffer that contains a single BYTE.

If the BYTE is a nonzero value, it is the desired line-status and modem-status value escape character. The operation will turn the LSRMST_INSERT line-status and modem-status data placement mode on.

If the BYTE is zero, the operation will turn the LSRMST_INSERT line-status and modem-status data placement mode off.

The escape character can not be the XON or XOFF character.

cbInBuffer

Specifies the size, in bytes, of the buffer pointed to by lpvInBuffer. For this operation, this value should be 1.

lpvOutBuffer

Points to an output buffer. Not used with this operation. Set to NULL.

cbOutBuffer

Specifies the size, in bytes, of the buffer pointed to by lpvOutBuffer. Not used with this operation. Set to zero.

lpcbBytesReturned

Points to a DWORD that receives the actual size, in bytes, of the data stored into lpvOutBuffer.

Return Value

If the operation succeeds, DeviceIoControl returns TRUE.

If the operation fails, DeviceIoControl returns FALSE. To get extended error information, call GetLastError.

Remarks

Note that an application that uses this scheme must examine each character in the data stream to determine the presence of modem-status or line-status data.

The following values follow the designated escape character in the data stream if the LSRMST_INSERT mode has been turned on :

Value	Meaning
SERIAL_LSRMST_ESCAPE	Indicates the reception of the escape character itself into the data stream.
SERIAL_LSRMST_LSR_DATA	Indicates that a line status change occurred, and data was available in the receive hardware buffer. Following this BYTE is a BYTE value of the line status register is the BYTE present in the receive hardware buffer when the line status change was processed.
SERIAL_LSRMST_LSR_NODATA	Indicates that a line status change occurred, but no data was available in the receive hardware buffer.
SERIAL_LSRMST_MST	Indicates that a modem status change occurred. Following this BYTE is a BYTE that is the value of the modem status register when the modem status change was processed.
See Also

DeviceIoControl, ReadFile


ioctlsocket
 ioctlsocket  QuickInfo

The Windows Sockets ioctlsocket function controls the mode of a socket.

int ioctlsocket (

SOCKET s,
long cmd,
u_long FAR * argp
);
Parameters

s

A descriptor identifying a socket.

cmd

The command to perform on the socket s.

argp

A pointer to a parameter for cmd.

Return Value

If the function succeeds, ioctlsocket returns zero.

If the function fails, a value of SOCKET_ERROR is returned. To get extended error information, call WSAGetLastError.

Error Codes

WSANOTINITIALISED	A successful WSAStartup must occur before using this function.
WSAENETDOWN	The Windows Sockets implementation has detected that the network subsystem has failed.
WSAEINVAL	The cmd parameter is not valid, or argp is not an acceptable parameter for cmd, or the command is not applicable to the type of socket supplied.
WSAEINPROGRESS	A blocking Windows Sockets operation is in progress.
WSAENOTSOCK	The descriptor s is not a socket.
Remarks

This function may be used on any socket in any state. It is used to get or set operating parameters associated with the socket, independent of the protocol and communications subsystem. The following commands are supported:

Command	Semantics
FIONBIO	Enable or disable nonblocking mode on the socket s. argp points at an unsigned long, which is nonzero if nonblocking mode is to be enabled and zero if it is to be disabled. When a socket is created, it operates in blocking mode (that is, nonblocking mode is disabled). This is consistent with BSD sockets.
	The WSAAsyncSelect function automatically sets a socket to nonblocking mode. If WSAAsyncSelect has been issued on a socket, then any attempt to use ioctlsocket to set the socket back to blocking mode will fail with WSAEINVAL. To set the socket back to blocking mode, an application must first disable WSAAsyncSelect by calling WSAAsyncSelect with the lEvent parameter equal to zero.
FIONREAD	Determine the amount of data that can be read atomically from socket s. argp points at an unsigned long in which ioctlsocket stores the result. If s is of type SOCK_STREAM, FIONREAD returns the total amount of data that can be read in a single recv; this is normally the same as the total amount of data queued on the socket. If s is of type SOCK_DGRAM, FIONREAD returns the size of the first datagram queued on the socket.
SIOCATMARK	Determine whether all out-of-band data has been read. This applies only to a socket of type SOCK_STREAM that has been configured for in-line reception of any out-of-band data (SO_OOBINLINE). If no out-of-band data is waiting to be read, the operation returns TRUE. Otherwise, it returns FALSE, and the next recv or recvfrom performed on the socket will retrieve some or all of the data preceding the "mark"; the application should use the SIOCATMARK operation to determine whether any data remains. If there is any normal data preceding the "urgent" (out-of-band) data, it will be received in order. (Note that a recv or recvfrom will never mix out-of-band and normal data in the same call.) argp points at a BOOL in which ioctlsocket stores the result.
Compatibility

This function is a subset of ioctl as used in Berkeley sockets. In particular, there is no command equivalent to FIOASYNC, while SIOCATMARK is the only socket-level command supported.

See Also

getsockopt, socket, setsockopt, WSAAsyncSelect, WSAStartup


IsBadCodePtr
 IsBadCodePtr  QuickInfo  Overview  Group

The IsBadCodePtr function determines whether the calling process has read access to the memory at the specified address.

BOOL IsBadCodePtr(

FARPROC  lpfn	// address of function
);
Parameters

lpfn

Points to an address in memory.

Return Value

If the calling process has read access to the specified memory, the return value is FALSE; otherwise, it is TRUE. To get extended error information, call GetLastError.

Remarks

IsBadCodePtr checks the read access only at the specified address and does not guarantee read access to a range of memory.

In a preemptive multitasking environment, it is possible for some other thread to change the process's access to the memory being tested. Even when the function indicates that the process has read access to the specified memory, you should use structured exception handling when attempting to access the memory. Use of structured exception handling enables the system to notify the process if an access violation exception occurs, giving the process an opportunity to handle the exception.

See Also

IsBadHugeReadPtr, IsBadHugeWritePtr, IsBadReadPtr, IsBadStringPtr, IsBadWritePtr


IsBadHugeReadPtr
 IsBadHugeReadPtr  QuickInfo  Overview  Group

The IsBadHugeReadPtr function verifies that the calling process has read access to the specified range of memory.

BOOL IsBadHugeReadPtr(

CONST VOID  * lp,	// address of memory block
UINT  ucb	// size of block
);
Parameters

lp

Points to the first byte of the memory block.

ucb

Specifies the size, in bytes, of the memory block. If this parameter is zero, the return value is FALSE.

Return Value

If the calling process has read access to all bytes in the specified memory range, the return value is FALSE; otherwise, it is TRUE. To get extended error information, call GetLastError.

Remarks

If the calling process has read access to some, but not all, of the bytes in the specified memory range, the return value is TRUE.

In a preemptive multitasking environment, it is possible for some other thread to change the process's access to the memory being tested. Even when the function indicates that the process has read access to the specified memory, you should use structured exception handling when attempting to access the memory. Use of structured exception handling enables the system to notify the process if an access violation exception occurs, giving the process an opportunity to handle the exception.

IsBadHugeReadPtr is available for compatibility with earlier versions of Windows that distinguish between normal memory allocations and huge allocations occupying multiple segments. In the Win32 API, this function is equivalent to the IsBadReadPtr function.

See Also

IsBadHugeWritePtr, IsBadReadPtr, IsBadStringPtr, IsBadWritePtr


IsBadHugeWritePtr
 IsBadHugeWritePtr  QuickInfo  Overview  Group

The IsBadHugeWritePtr function verifies that the calling process has write access to the specified range of memory.

BOOL IsBadHugeWritePtr(

LPVOID  lp,	// address of memory block
UINT  ucb	// size of block
);
Parameters

lp

Points to the first byte of the memory block.

ucb

Specifies the size, in bytes, of the memory block. If this parameter is zero, the return value is FALSE.

Return Value

If the calling process has write access to all bytes in the specified memory range, the return value is FALSE; otherwise, it is TRUE. To get extended error information, call GetLastError.

Remarks

If the calling process has write access to some, but not all, of the bytes in the specified memory range, the return value is TRUE.

In a preemptive multitasking environment, it is possible for some other thread to change the process's access to the memory being tested. Even when the function indicates that the process has write access to the specified memory, you should use structured exception handling when attempting to access the memory. Use of structured exception handling enables the system to notify the process if an access violation exception occurs, giving the process an opportunity to handle the exception.

IsBadHugeWritePtr is available for compatibility with earlier versions of Windows, which distinguish between normal memory allocations and huge allocations occupying multiple segments. In the Win32 API, this function is equivalent to the IsBadWritePtr function.

See Also

IsBadHugeReadPtr, IsBadReadPtr, IsBadStringPtr, IsBadWritePtr


IsBadReadPtr
 IsBadReadPtr  QuickInfo  Overview  Group

The IsBadReadPtr function verifies that the calling process has read access to the specified range of memory.

BOOL IsBadReadPtr(

CONST VOID  * lp,	// address of memory block
UINT  ucb	// size of block
);
Parameters

lp

Points to the first byte of the memory block.

ucb

Specifies the size, in bytes, of the memory block. If this parameter is zero, the return value is FALSE.

Return Value

If the calling process has read access to all bytes in the specified memory range, the return value is FALSE; otherwise, it is TRUE. To get extended error information, call GetLastError.

Remarks

If the calling process has read access to some, but not all, of the bytes in the specified memory range, the return value is TRUE.

In a preemptive multitasking environment, it is possible for some other thread to change the process's access to the memory being tested. Even when the function indicates that the process has read access to the specified memory, you should use structured exception handling when attempting to access the memory. Use of structured exception handling enables the system to notify the process if an access violation exception occurs, giving the process an opportunity to handle the exception.

See Also

IsBadHugeReadPtr, IsBadHugeWritePtr, IsBadStringPtr, IsBadWritePtr


IsBadStringPtr
 IsBadStringPtr  QuickInfo  Overview  Group

The IsBadStringPtr function verifies that the calling process has read access to a range of memory pointed to by a string pointer.

BOOL IsBadStringPtr(

LPCTSTR  lpsz,	// address of string
UINT  ucchMax	// maximum size of string
);
Parameters

lpsz

Points to a null-terminated string, either Unicode or ASCII.

ucchMax

Specifies the maximum size, in characters, of the string. The function checks for read access in all bytes up to the string's terminating null character or up to the number of bytes specified by this parameter, whichever is smaller. If this parameter is zero, the return value is FALSE.

Return Value

If the calling process has read access to all bytes up to the string's terminating null character or up to the number of bytes specified by ucchMax, the return value is FALSE; otherwise, it is TRUE. To get extended error information, call GetLastError.

Remarks

If the calling process has read access to some, but not all, of the bytes in the specified memory range, the return value is TRUE.

In a preemptive multitasking environment, it is possible for some other thread to change the process's access to the memory being tested. Even when the function indicates that the process has read access to the specified memory, you should use structured exception handling when attempting to access the memory. Use of structured exception handling enables the system to notify the process if an access violation exception occurs, giving the process an opportunity to handle the exception.

See Also

IsBadCodePtr, IsBadHugeReadPtr, IsBadHugeWritePtr, IsBadReadPtr, IsBadWritePtr


IsBadWritePtr
 IsBadWritePtr  QuickInfo  Overview  Group

The IsBadWritePtr function verifies that the calling process has write access to the specified range of memory.

BOOL IsBadWritePtr(

LPVOID  lp,	// address of memory block
UINT  ucb	// size of block
);
Parameters

lp

Points to the first byte of the memory block.

ucb

Specifies the size, in bytes, of the memory block. If this parameter is zero, the return value is FALSE.

Return Value

If the calling process has write access to all bytes in the specified memory range, the return value is FALSE; otherwise, it is TRUE. To get extended error information, call GetLastError.

Remarks

If the calling process has write access to some, but not all, of the bytes in the specified memory range, the return value is TRUE.

In a preemptive multitasking environment, it is possible for some other thread to change the process's access to the memory being tested. Even when the function indicates that the process has write access to the specified memory, you should use structured exception handling when attempting to access the memory. Use of structured exception handling enables the system to notify the process if an access violation exception occurs, giving the process an opportunity to handle the exception.

See Also

IsBadCodePtr, IsBadHugeReadPtr, IsBadHugeWritePtr, IsBadReadPtr


IsCharAlpha
 IsCharAlpha  QuickInfo  Overview  Group

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 by using Control Panel.

BOOL IsCharAlpha(

TCHAR  ch	// character to test
);
Parameters

ch

Specifies the character to be tested.

Return Value

If the character is alphabetic, the return value is TRUE.

If the character is not alphabetic, the return value is FALSE.

To get extended error information, call GetLastError.

See Also

IsCharAlphaNumeric


IsCharAlphaNumeric
 IsCharAlphaNumeric  QuickInfo  Overview  Group

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 by using Control Panel.

BOOL IsCharAlphaNumeric(

TCHAR  ch	// character to test
);
Parameters

ch

Specifies the character to be tested.

Return Value

If the character is alphanumeric, the return value is TRUE.

If the character is not alphanumeric, the return value is FALSE.

To get extended error information, call GetLastError.

See Also

IsCharAlpha


IsCharLower
 IsCharLower  QuickInfo  Overview  Group

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 by using Control Panel.

BOOL IsCharLower(

TCHAR  ch	// character to test
);
Parameters

ch

Specifies the character to be tested.

Return Value

If the character is lowercase, the return value is TRUE.

If the character is not lowercase, the return value is FALSE.

To get extended error information, call GetLastError.

See Also

IsCharUpper


IsCharUpper
 IsCharUpper  QuickInfo  Overview  Group

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 by using Control Panel.

BOOL IsCharUpper(

TCHAR  ch	// character to test
);
Parameters

ch

Specifies the character to be tested.

Return Value

If the character is uppercase, the return value is TRUE.

If the character is not uppercase, the return value is FALSE.

To get extended error information, call GetLastError.

See Also

IsCharLower


IsChild
 IsChild  QuickInfo  Overview  Group

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 of parent window
HWND  hWnd	// handle of window to test
);
Parameters

hWndParent

Identifies the parent window.

hWnd

Identifies the window to be tested.

Return Value

If the window is a child or descendant window of the specified parent window, the return value is TRUE.

If the window is not a child or descendant window of the specified parent window, the return value is FALSE.

See Also

IsWindow, SetParent


IsClipboardFormatAvailable
 IsClipboardFormatAvailable  QuickInfo  Overview  Group

The IsClipboardFormatAvailable function determines whether the clipboard contains data in the specified format.

BOOL IsClipboardFormatAvailable(

UINT  format	// clipboard format
);
Parameters

format

Specifies a standard or registered clipboard format. For a description of the clipboard formats, see the SetClipboardData function.

Return Value

If the clipboard format is available, the return value is TRUE.

If the clipboard is not available, the return value is FALSE. To get extended error information, call GetLastError.

Remarks

Typically, an application that recognizes only one clipboard format would call this function when processing the WM_INITMENU or WM_INITMENUPOPUP message. The application would then enable or disable the Paste menu item, depending on the return value. Applications that recognize more than one clipboard format should use the GetPriorityClipboardFormat function for this purpose.

See Also

CountClipboardFormats, EnumClipboardFormats, GetPriorityClipboardFormat, RegisterClipboardFormat, SetClipboardData, WM_INITMENU, WM_INITMENUPOPUP


IsDBCSLeadByte
 IsDBCSLeadByte  QuickInfo\cs138v_win32_IsDBCSLeadByte_pop  Overview  Group

The IsDBCSLeadByte function determines whether a character is a lead byte — that is, the first byte of a character in a double-byte character set (DBCS).

BOOL IsDBCSLeadByte(

BYTE  TestChar	// character to test
);
Parameters

TestChar

Specifies the character to be tested.

Return Value

If the character is a lead byte, the return value is TRUE.

If the character is not a lead byte, the return value is FALSE.

To get extended error information, call GetLastError.

Remarks

Lead bytes are unique to double-byte character sets. A lead byte introduces a double-byte character. Lead bytes occupy a specific range of byte values. The IsDBCSLeadByte function uses the ANSI code page to check lead-byte ranges.

See Also

MultiByteToWideChar


IsDBCSLeadByteEx [New - Windows NT]
 IsDBCSLeadByteEx  QuickInfo  Overview  Group

[New - Windows NT]

The IsDBCSLeadByteEx function determines whether a character is a lead byte — that is, the first byte of a character in a double-byte character set (DBCS).

BOOL IsDBCSLeadByteEx(

UINT  CodePage,	// identifier of code page
BYTE  TestChar	// character to test
);
Parameters

CodePage

Identifier of the code page to use to check lead-byte ranges. Can be one of the code-page values given 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.
TestChar

Character to test.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.


IsDialogMessage
 IsDialogMessage  QuickInfo  Overview  Group

The IsDialogMessage function determines whether a message is intended for the specified dialog box and, if it is, processes the message.

BOOL IsDialogMessage(

HWND  hDlg,	// handle of dialog box
LPMSG  lpMsg	// address of structure with message
);
Parameters

hDlg

Identifies the dialog box.

lpMsg

Points to an MSG structure that contains the message to be checked.

Return Value

If the message has been processed, the return value is TRUE.

If the message has not been processed, the return value is FALSE.

Remarks

Although the IsDialogMessage function is intended for modeless dialog boxes, you can use it with any window that contains controls, enabling the windows to provide the same keyboard selection as is used in a dialog box.

When IsDialogMessage processes a message, it checks for keyboard messages and converts them into selection commands for the corresponding dialog box. For example, the TAB key, when pressed, selects the next control or group of controls, and the DOWN ARROW key, when pressed, selects the next control in a group.

Because the IsDialogMessage function performs all necessary translating and dispatching of messages, a message processed by IsDialogMessage must not be passed to the TranslateMessage or DispatchMessage function.

IsDialogMessage sends WM_GETDLGCODE messages to the dialog box procedure to determine which keys should be processed.

IsDialogMessage can send DM_GETDEFID and DM_SETDEFID messages to the window. These messages are defined in the WINUSER.H header file as WM_USER and WM_USER + 1, so conflicts are possible with application-defined messages having the same values.

See Also

DispatchMessage, DM_GETDEFID, DM_SETDEFID, MSG, TranslateMessage, WM_GETDLGCODE, WM_USER


IsDlgButtonChecked
 IsDlgButtonChecked  QuickInfo  Overview  Group

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 of dialog box
int  nIDButton	// button identifier
);
Parameters

hDlg

Identifies the dialog box that contains the button control.

nIDButton

Specifies the integer identifier of the button control.

Return Value

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
0	Button is unchecked. Same as the Windows 95 constant BST_UNCHECKED.
1	Button is checked. Same as the Windows 95 constant BST_CHECKED.
2	Button is grayed, indicating an indeterminate state (applies only if the button has the BS_3STATE or BS_AUTO3STATE style). Same as the Windows 95 constant BST_INDETERMINATE.
BST_CHECKED	Windows 95 only: Button is checked.
BST_INDETERMINATE	Windows 95 only: Button is grayed, indicating an indeterminate state (applies only if the button has the BS_3STATE or BS_AUTO3STATE style).
BST_UNCHECKED	Windows 95 only: Button is unchecked
If the button has any other style, the return value is zero.

Remarks

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

See Also

CheckDlgButton


IsIconic
 IsIconic  QuickInfo  Overview  Group

The IsIconic function determines whether the specified window is minimized (iconic).

BOOL IsIconic(

HWND  hWnd	// handle of window
);
Parameters

hWnd

Identifies the window.

Return Value

If the window is iconic, the return value is TRUE.

If the is not iconic, the return value is FALSE.

See Also

IsZoomed


IsMenu
 IsMenu  QuickInfo  Overview  Group

The IsMenu function determines whether a handle is a menu handle.

BOOL IsMenu(

HMENU  hMenu	// handle to test
);
Parameters

hMenu

The handle to be tested.

Return Value

If hMenu is a menu handle, the function returns TRUE; if it is not, the function returns FALSE.


IsRectEmpty
 IsRectEmpty  QuickInfo  Overview  Group

The IsRectEmpty function determines whether the specified rectangle is empty. A empty rectangle is one that has no area; that is, the coordinate of the right side is less than or equal to the coordinate of the left side, or the coordinate of the bottom side is less than or equal to the coordinate of the top side.

BOOL IsRectEmpty(

CONST RECT  * lprc	// address of structure with rectangle
);
Parameters

lprc

Points to a RECT structure that contains the logical coordinates of the rectangle.

Return Value

If the rectangle is empty, the return value is TRUE; otherwise, it is FALSE. To get extended error information, call GetLastError.

See Also

EqualRect, PtInRect, RECT


IsTask
 IsTask  Overview  Group

The IsTask function is not implemented in the WIn32 API.


IsTextUnicode
 IsTextUnicode  QuickInfo  Overview  Group

The IsTextUnicode function determines whether a buffer probably contains a form of Unicode text. The function uses various statistical and deterministic methods to make its determination, under the control of flags passed via lpi. When the function returns, the results of such tests are reported via lpi. If all specified tests are passed, the function returns TRUE; otherwise, it returns FALSE.

DWORD IsTextUnicode(

CONST LPVOID  lpBuffer,	// pointer to an input buffer to be examined
int  cb,	// the size in bytes of the input buffer
LPINT  lpi	// pointer to flags that condition text examination and receive results
);
Parameters

lpBuffer

Pointer to the input buffer to be examined.

cb

Specifies the size, in bytes, of the input buffer pointed to by lpBuffer.

lpi

Pointer to an int that, upon entry to the function, contains a set of flags that specify the tests to be applied to the input buffer text. Upon exit from the function, that same int contains a set of bit flags indicating the results of the specified tests: 1 if the contents of the buffer pass a test, 0 for failure. Only flags that are set upon entry to the function are significant upon exit.

If lpi is NULL, the function uses all available tests to determine whether the data in the buffer is probably Unicode text.

Here are the constants used with *lpi's bit flags:

Value	Meaning
IS_TEXT_UNICODE_ASCII16	The text is Unicode, and contains nothing but zero-extended ASCII values/characters.
IS_TEXT_UNICODE_REVERSE_ASCII16	Same as the preceding, except that the Unicode text is byte-reversed.
IS_TEXT_UNICODE_STATISTICS	The text is probably Unicode, with the determination made by applying statistical analysis. Absolute certainty is not guaranteed. See the note in the following Remarks section.
IS_TEXT_UNICODE_REVERSE_STATISTICS	Same as the preceding, except that the probably-Unicode text is byte-reversed.
IS_TEXT_UNICODE_CONTROLS	The text contains Unicode representations of one or more of these non-printing characters: RETURN, LINEFEED, SPACE, CJK_SPACE, TAB.
IS_TEXT_UNICODE_REVERSE_CONTROLS	Same as the preceding, except that the Unicode characters are byte-reversed.
IS_TEXT_UNICODE_BUFFER_TOO_SMALL	There are too few characters in the buffer for meaningful analysis (fewer than two bytes).
IS_TEXT_UNICODE_SIGNATURE	The text contains the Unicode byte-order mark (BOM) 0xFEFF as its first character.
IS_TEXT_UNICODE_REVERSE_SIGNATURE	The text contains the Unicode byte-reversed byte-order mark (Reverse BOM) 0xFFFE as its first character.
IS_TEXT_UNICODE_ILLEGAL_CHARS	The text contains one of these Unicode-illegal characters: embedded Reverse BOM, UNICODE_NUL, CRLF (packed into one WORD), or 0xFFFF.
IS_TEXT_UNICODE_ODD_LENGTH	The number of characters in the string is odd. A string of odd length cannot (by definition) be Unicode text.
IS_TEXT_UNICODE_NULL_BYTES	The text contains null bytes, which indicate non-ASCII text.
IS_TEXT_UNICODE_UNICODE_MASK	This flag constant is a combination of IS_TEXT_UNICODE_ASCII16, IS_TEXT_UNICODE_STATISTICS, IS_TEXT_UNICODE_CONTROLS, IS_TEXT_UNICODE_SIGNATURE.
IS_TEXT_UNICODE_REVERSE_MASK	This flag constant is a combination of IS_TEXT_UNICODE_REVERSE_ASCII16, IS_TEXT_UNICODE_REVERSE_STATISTICS, IS_TEXT_UNICODE_REVERSE_CONTROLS, IS_TEXT_UNICODE_REVERSE_SIGNATURE.
IS_TEXT_UNICODE_NOT_UNICODE_MASK	This flag constant is a combination of IS_TEXT_UNICODE_ILLEGAL_CHARS, IS_TEXT_UNICODE_ODD_LENGTH, and two currently unused bit flags.
IS_TEXT_UNICODE_NOT_ASCII_MASK	This flag constant is a combination of IS_TEXT_UNICODE_NULL_BYTES and three currently unused bit flags.
Return Value

The function returns TRUE if the data in the buffer passes the specified tests.

The function returns FALSE if the data in the buffer does not pass the specified tests.

In either case, the int pointed to by lpi contains the results of the specific tests the function applied to make its determination.

Remarks

As noted in the preceding table of flag constants, the IS_TEXT_UNICODE_STATISTICS and IS_TEXT_UNICODE_REVERSE_STATISTICS tests use statistical analysis. These tests are not foolproof. The statistical tests assume certain amounts of variation between low and high bytes in a string, and some ASCII strings can slip through. For example, if lpBuffer points to the ASCII string 0x41, 0x0A, 0x0D, 0x1D (A\n\r^Z), the string passes the IS_TEXT_UNICODE_STATISTICS test, though failure would be preferable.


IsValidAcl
 IsValidAcl  QuickInfo  Overview  Group

The IsValidAcl function validates an access-control list (ACL).

BOOL IsValidAcl(

PACL  pAcl	// address of access-control list
);
Parameters

pAcl

Points to an ACL structure validated by this function. This must be a non-NULL value.

Return Value

If the ACL is valid, the return value is TRUE.

If the ACL is not valid, the return value is FALSE.

To get extended error information, call GetLastError.

Remarks

This function checks the revision level of the ACL and verifies that the number of access-control entries (ACEs) specified in the AceCount member of the ACL structure fits the space specified by the AclSize member of the ACL structure.

If pAcl is NULL, the application will fail with an access violation.

See Also

ACL, GetAclInformation, InitializeAcl


IsValidCodePage
 IsValidCodePage  QuickInfo  Overview  Group

The IsValidCodePage determines whether a specified code page is valid.

BOOL IsValidCodePage(

UINT  CodePage	// specifies code page to check
);
Parameters

CodePage

Specifies the code page to check. Each code page is identified by a unique number.

Return Value

If the code page is valid, the return value is TRUE.

If the code page is not valid, the return value is FALSE.

To get extended error information, call GetLastError.

Remarks

A code page is considered valid only if it is installed in the system.

Following are the code-page identifiers:

Identifier	Meaning
037	EBCDIC
437	MS-DOS  United States
500	EBCDIC "500V1"
708	Arabic (ASMO 708)
709	Arabic (ASMO 449+, BCON V4)
710	Arabic (Transparent Arabic)
720	Arabic (Transparent ASMO)
737	Greek (formerly 437G)
775	Baltic
850	MS-DOS  Multilingual (Latin I)
852	MS-DOS  Slavic (Latin II)
855	IBM Cyrillic (primarily Russian)
857	IBM Turkish
860	MS-DOS  Portuguese
861	MS-DOS Icelandic
862	Hebrew
863	MS-DOS Canadian-French
864	Arabic
865	MS-DOS Nordic
866	MS-DOS Russian
869	IBM Modern Greek
874	Thai
875	EBCDIC
932	Japan
936	Chinese (PRC, Singapore)
949	Korean
950	Chinese (Taiwan, Hong Kong)
1026	EBCDIC
1200	Unicode (BMP of ISO 10646)
1250	Windows 3.1 Eastern European
1251	Windows 3.1 Cyrillic
1252	Windows 3.1 US (ANSI)
1253	Windows 3.1 Greek
1254	Windows 3.1 Turkish
1255	Hebrew
1256	Arabic
1257	Baltic
1361	Korean (Johab)
10000	Macintosh Roman
10001	Macintosh Japanese
10006	Macintosh Greek I
10007	Macintosh Cyrillic
10029	Macintosh Latin 2
10079	Macintosh Icelandic
10081	Macintosh Turkish
See Also

GetACP, GetCPInfo, GetOEMCP


IsValidLocale
 IsValidLocale  QuickInfo  Overview  Group

The IsValidLocale function applies a validity test to a locale identifier. The dwFlags parameter determines the nature of the validity test. Currently, the function tests whether a locale identifier is installed or supported on the calling system.

BOOL IsValidLocale(

LCID  Locale	// locale indentifier to validate
DWORD  dwFlags	// specifies validity test
);
Parameters

Locale

Specifies the locale identifier to be validated. You can use the MAKELCID macro to create a locale identifier.

dwFlags

Specifies the validity test to apply to the locale identifier. This parameter can be one of the following values:

Value	Meaning
LCID_INSTALLED	Test whether the locale identifier is both supported and installed.
LCID_SUPPORTED	Test whether the locale identifier is supported.
Return Value

If the locale identifier passes the specified validity test, the return value is TRUE.

If the locale identifier does not pass the specified validity test, the return value is FALSE.

Remarks

If the LCID_INSTALLED flag is specified and this function returns TRUE, the locale identifier is both supported and installed on the system.

If the LCID_SUPPORTED flag is specified and this function returns TRUE, the locale identifier is supported in the release, but not necessarily installed on the system.

See Also

GetLocaleInfo


IsValidSecurityDescriptor
 IsValidSecurityDescriptor  QuickInfo  Overview  Group

The IsValidSecurityDescriptor function validates a SECURITY_DESCRIPTOR structure. Validation is performed by checking the revision level of each component in the security descriptor.

BOOL IsValidSecurityDescriptor(

PSECURITY_DESCRIPTOR  pSecurityDescriptor	// address of security descriptor
);
Parameters

pSecurityDescriptor

Points to a SECURITY_DESCRIPTOR structure that the function validates.

Return Value

If the structure of the security descriptor is valid, the return value is TRUE.

If the structure of the security descriptor is not valid, the return value is FALSE. To get extended error information, call GetLastError.

See Also

GetSecurityDescriptorControl, GetSecurityDescriptorDacl, GetSecurityDescriptorGroup, GetSecurityDescriptorLength, GetSecurityDescriptorOwner, GetSecurityDescriptorSacl, InitializeSecurityDescriptor, SECURITY_DESCRIPTOR, SetSecurityDescriptorDacl, SetSecurityDescriptorGroup, SetSecurityDescriptorOwner, SetSecurityDescriptorSacl


IsValidSid
 IsValidSid  QuickInfo  Overview  Group

The IsValidSid function validates a SID structure by verifying that the revision number is within a known range and that the number of subauthorities is less than the maximum. A SID is a security identifier.

BOOL IsValidSid(

PSID  pSid	// address of SID to query
);
Parameters

pSid

Points to the SID structure to validate. This must be a non-NULL value.

Return Value

If the SID structure is valid, the return value is TRUE.

If the SID structure is not valid, the return value is FALSE. To get extended error information, call GetLastError.

Remarks

If pSid is NULL, the application will fail with an access violation.

See Also

GetLengthSid, GetSidIdentifierAuthority, GetSidLengthRequired, GetSidSubAuthority, GetSidSubAuthorityCount, SID


IsWindow
 IsWindow  QuickInfo  Overview  Group

The IsWindow function determines whether the specified window handle identifies an existing window.

BOOL IsWindow(

HWND  hWnd	// handle of window
);
Parameters

hWnd

Specifies the window handle.

Return Value

If the window handle identifies an existing window, the return value is TRUE; otherwise, it is FALSE.

See Also

IsWindowEnabled, IsWindowVisible


IsWindowEnabled
 IsWindowEnabled  QuickInfo  Overview  Group

The IsWindowEnabled function determines whether the specified window is enabled for mouse and keyboard input.

BOOL IsWindowEnabled(

HWND  hWnd	// handle of window to test
);
Parameters

hWnd

Identifies the window to test.

Return Value

If the window is enabled, the return value is TRUE; otherwise, it is FALSE.

Remarks

A child window receives input only if it is both enabled and visible.

See Also

EnableWindow, IsWindowVisible


IsWindowUnicode
 IsWindowUnicode  QuickInfo  Overview  Group

The IsWindowUnicode function determines whether the specified window is a native Unicode window.

BOOL IsWindowUnicode(

HWND  hWnd	// handle of window
);
Parameters

hWnd

Identifies the window.

Return Value

If the window is a native Unicode window, the return value is TRUE.

If the window is not a native Unicode window, the return value is FALSE.

Remarks

The system does automatic two-way translation (Unicode to ANSI-ASCII) for window messages. For example, if an ANSI-ASCII window message is sent to a Unicode window, the system translates that message into a Unicode message before calling the window procedure. The system calls the IsWindowUnicode function to determine whether to translate the message.

When this function returns FALSE, the window is a native ANSI-ASCII window.


IsWindowVisible
 IsWindowVisible  QuickInfo  Overview  Group

The IsWindowVisible function retrieves the visibility state of the specified window.

BOOL IsWindowVisible(

HWND  hWnd	// handle of window
);
Parameters

hWnd

Identifies the window.

Return Value

If the specified window is visible on the screen (has the WS_VISIBLE style), the return value is TRUE; otherwise, it is FALSE. Because the return value specifies whether the window has the WS_VISIBLE style, it may be TRUE 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.

See Also

ShowWindow


IsZoomed
 IsZoomed  QuickInfo  Overview  Group

The IsZoomed function determines whether a window is maximized.

BOOL IsZoomed(

HWND  hWnd	// handle of window
);
Parameters

hWnd

Identifies the window.

Return Value

If the window is zoomed, the return value is TRUE.

If the window is not zoomed, the return value is FALSE.

See Also

IsIconic


JournalPlaybackProc
 JournalPlaybackProc  QuickInfo  Overview  Group

The JournalPlaybackProc hook procedure is a callback function that inserts mouse and keyboard messages into the system message queue. Typically, an application uses this hook procedure to play back a series of mouse and keyboard messages recorded previously by the JournalRecordProc hook procedure. As long as a JournalPlaybackProc hook procedure is installed, regular mouse and keyboard input is disabled.

LRESULT CALLBACK JournalPlaybackProc(

int  code,	// hook code
WPARAM  wParam,	// undefined
LPARAM  lParam	// address of message being processed
);
Parameters

code

Specifies a code the hook procedure uses to determine how to process the message. This parameter can be one of the following values:

Value	Meaning
HC_GETNEXT	The hook procedure must copy the current mouse or keyboard message to the EVENTMSG structure pointed to by the lParam parameter.
HC_NOREMOVE	An application has called the PeekMessage function with wRemoveMsg set to PM_NOREMOVE, indicating that the message is not removed from the message queue after PeekMessage processing.
HC_SKIP	The hook procedure must prepare to copy the next mouse or keyboard message to the EVENTMSG structure pointed to by lParam. Upon receiving the HC_GETNEXT code, the hook procedure must copy the message to the structure.
HC_SYSMODALOFF	A system-modal dialog box has been destroyed. The hook procedure must resume playing back the messages.
HC_SYSMODALON	A system-modal dialog box is being displayed. Until the dialog box is destroyed, the hook procedure must stop playing back messages.
If code is less than zero, the hook procedure must pass the message to the CallNextHookEx function without further processing and should return the value returned by CallNextHookEx.

wParam

Specifies a NULL value.

lParam

Points to an EVENTMSG structure that represents a message being processed by the hook procedure. This parameter is valid only when the code parameter is HC_GETNEXT.

Return Value

To have the system wait before processing the message, the return value must be the amount of time, in clock ticks, that the system should wait. (This value can be computed by calculating the difference between the time members in the current and previous input messages.) To process the message immediately, the return value should be zero. The return value is used only if the hook code is HC_GETNEXT; otherwise, it is ignored.

Remarks

A JournalPlaybackProc hook procedure should copy an input message to the lParam parameter. The message must have been previously recorded by using a JournalRecordProc hook procedure, which should not modify the message.

To retrieve the same message over and over, the hook procedure can be called several times with the code parameter set to HC_GETNEXT without an intervening call with code set to HC_SKIP.

If code is HC_GETNEXT and the return value is greater than zero, the system sleeps for the number of milliseconds specified by the return value. When the system continues, it calls the hook procedure again with code set to HC_GETNEXT to retrieve the same message. The return value from this new call to JournalPlaybackProc should be zero; otherwise, the system will go back to sleep for the number of milliseconds specified by the return value, call JournalPlaybackProc again, and so on. The system will appear to be hung.

Unlike most other global hook procedures, the JournalRecordProc and JournalPlaybackProc hook procedures are always called in the context of the thread that set the hook.

After the hook procedure returns control to the system, the message continues to be processed. If code is HC_SKIP, the hook procedure must prepare to return the next recorded event message on its next call.

An application installs a JournalPlaybackProc hook procedure by specifying the WH_JOURNALPLAYBACK hook type and the address of the hook procedure in a call to the SetWindowsHookEx function.

A Win32 JournalRecordProc hook procedure does not need to live in a dynamic-link library. A Win32 JournalRecordProc hook procedure can live in the application itself.

If the user presses CTRL+ESCAPE, ALT+ESCAPE, or CTRL+ALT+DEL during journal playback, the system stops the playback, unhooks the journal playback procedure, and posts a WM_CANCELJOURNAL message to the journaling application.

If the hook procedure returns a message in the range WM_KEYFIRST to WM_KEYLAST, the following conditions apply:

•	The paramL member of the EVENTMSG structure specifies the virtual key code of the key that was pressed.

•	The paramH member of the EVENTMSG structure specifies the scan code.

•	There's no way to specify a repeast count. The event is always taken to represent one key event.

JournalPlaybackProc is a placeholder for an application-defined or library-defined function name.

See Also

CallNextHookEx, EVENTMSG, JournalRecordProc, PeekMessage, SetWindowsHookEx, WM_CANCELJOURNAL


JournalRecordProc
 JournalRecordProc  QuickInfo  Overview  Group

The JournalRecordProc hook procedure is a callback function that records messages the system removes from the system message queue. Later, an application can use a JournalPlaybackProc hook procedure to play back the messages.

LRESULT CALLBACK JournalRecordProc(

int  code,	// hook code
WPARAM  wParam,	// undefined
LPARAM  lParam	// address of message being processed
);
Parameters

code

Specifies how to process the message. This parameter can be one of the following values:

Value	Meaning
HC_ACTION	The lParam parameter points to an EVENTMSG structure containing information about a message removed from the system queue. The hook procedure must record the contents of the structure by copying them to a buffer or file.
HC_SYSMODALOFF	A system-modal dialog box has been destroyed. The hook procedure must resume recording.
HC_SYSMODALON	A system-modal dialog box is being displayed. Until the dialog box is destroyed, the hook procedure must stop recording.
If code is less than zero, the hook procedure must pass the message to the CallNextHookEx function without further processing and should return the value returned by CallNextHookEx.

wParam

Specifies a NULL value.

lParam

Points to an EVENTMSG structure that contains the message to be recorded.

Return Value

The return value is ignored.

Remarks

A JournalRecordProc hook procedure must copy but not modify the messages. After the hook procedure returns control to the system, the message continues to be processed.

An application installs a JournalRecordProc hook procedure by specifying the WH_JOURNALRECORD hook type and the address of the hook procedure in a call to the SetWindowsHookEx function.

A Win32 JournalRecordProc hook procedure does not need to live in a dynamic-link library. A Win32 JournalRecordProc hook procedure can live in the application itself.

Unlike most other global hook procedures, the JournalRecordProc and JournalPlaybackProc hook procedures are always called in the context of the thread that set the hook.

An application that has installed a JournalRecordProc hook procedure should watch for the VK_CANCEL virtual keycode (which is implemented as the CTRL+BREAK key combination on most keyboards). This virtual keycode should be interpreted by the application as a signal that the user wishes to stop journal recording. The application should respond by ending the recording sequence and removing the JournalRecordProc hook procedure. Removal is important. It prevents a journaling application from locking up the system by hanging inside a hook procedure.

This role as a signal to stop journal recording means that a CTRL+BREAK key combination cannot itself be recorded. Since the CTRL+C key combination has no such role as a journaling signal, it can be recorded. There are three other key combinations that cannot be recorded: CTRL+ESCAPE, ALT+ESCAPE, and CTRL+ALT+DEL. Those three key combinations cause the system to stop all journaling activities (record or playback), remove all journaling hooks, and post a WM_CANCELJOURNAL message to the journaling application.

JournalRecordProc is a placeholder for an application-defined or library-defined function name.

See Also

CallNextHookEx, EVENTMSG, JournalPlaybackProc, SetWindowsHookEx, WM_CANCELJOURNAL


keybd_event
 keybd_event  QuickInfo  Overview  Group

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.

VOID keybd_event(

BYTE  bVk,	// virtual-key code
BYTE  bScan,	// hardware scan code
DWORD  dwFlags,	// flags specifying various function options
DWORD  dwExtraInfo	// additional data associated with keystroke
);
Parameters

bVk

Specifies a virtual-key code. The code must be a value in the range 1 to 254.

bScan

Specifies a hardware scan code for the key.

dwFlags

A set of flag bits that specify various aspects of function operation. An application can use any combination of the following predefined constant values to set the flags:

Value	Meaning
KEYEVENTF_EXTENDEDKEY	If specified, the scan code was preceded by a prefix byte having the value 0xE0 (224).
KEYEVENTF_KEYUP	If specified, the key is being released. If not specified, the key is being depressed.
dwExtraInfo

Specifies an additional 32-bit value associated with the key stroke.

Return Value

This function has no return value.

Remarks

Although keybd_event passes an OEM-dependent hardware scan code to Windows, applications should not use the scan code. Windows converts scan codes to virtual-key codes internally and clears the up/down bit in the scan code before passing it to applications.

An application can simulate a press of the PRINTSCREEN key in order to obtain a screen snapshot and save it to the Windows clipboard. To do this, call keybd_event with the bVk parameter set to VK_SNAPSHOT, and the bScan parameter set to 0 for a snapshot of the full screen or set bScan to 1 for a snapshot of the active window.

See Also

GetAsyncKeyState, GetKeyState, MapVirtualKey, SetKeyboardState


KeyboardProc
 KeyboardProc  QuickInfo  Overview  Group

The KeyboardProc hook procedure is an application-defined or library-defined callback function the system calls whenever an application calls the GetMessage or PeekMessage function and there is a keyboard message (WM_KEYUP or WM_KEYDOWN) to be processed.

LRESULT CALLBACK KeyboardProc(

int  code,	// hook code
WPARAM  wParam,	// virtual-key code
LPARAM  lParam	// keystroke-message information
);
Parameters

code

Specifies a code the hook procedure uses to determine how to process the message. This parameter can be one of the following values:

Value	Meaning
HC_ACTION	The wParam and lParam parameters contain information about a keystroke message.
HC_NOREMOVE	The wParam and lParam parameters contain information about a keystroke message, and the keystroke message has not been removed from the message queue. (An application called the PeekMessage function, specifying the PM_NOREMOVE flag.)
If code is less than zero, the hook procedure must pass the message to the CallNextHookEx function without further processing and should return the value returned by CallNextHookEx.

wParam

Specifies the virtual-key code of the key that generated the keystroke message.

lParam

Specifies the repeat count, scan code, extended-key flag, context code, previous key-state flag, and transition-state flag. This parameter can be a combination of the following values:

Value	Description
0−15	Specifies the repeat count. The value is the number of times the keystroke is repeated as a result of the user's holding down the key.
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 a function key or a key on the numeric keypad. The value is 1 if the key is an extended key; otherwise, it is 0.
25−28	Reserved.
29	Specifies the context code. The value is 1 if the ALT key is down; otherwise, it is 0.
30	Specifies the previous key state. The value is 1 if the key is down before the message is sent; it is 0 if the key is up.
31	Specifies the transition state. The value is 0 if the key is being pressed and 1 if it is being released.
For more information about the lParam parameter, see Keystroke Message Flags.Return Value

To prevent Windows from passing the message to the rest of the hook chain or to the target window procedure, the return value must be a nonzero value. To allow Windows to pass the message to the target window procedure, bypassing the remaining procedures in the chain, the return value must be zero.

Remarks

An application installs the hook procedure by specifying the WH_KEYBOARD hook type and the address of the hook procedure in a call to the SetWindowsHookEx function.

KeyboardProc is a placeholder for the application-defined or library-defined function name.

See Also

CallNextHookEx, GetMessage, PeekMessage, SetWindowsHookEx, WM_KEYUP, WM_KEYDOWN


KillTimer
 KillTimer  QuickInfo  Overview  Group

The KillTimer function destroys the specified timer. The system searches the message queue for any pending WM_TIMER messages associated with the timer and removes them.

BOOL KillTimer(

HWND  hWnd,	// handle of window that installed timer
UINT  uIDEvent	// timer identifier
);
Parameters

hWnd

Identifies 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

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 Value

If the function succeeds, the return value is TRUE.

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

See Also

SetTimer, WM_TIMER


LBItemFromPt [New - Windows NT]
 LBItemFromPt  QuickInfo  Overview  Group

[New - Windows NT]

The LBItemFromPt function retrieves the index of the item at the specified point in a list box.

int LBItemFromPt(

HWND  hLB,
POINT  pt,
BOOL  bAutoScroll
);
Parameters

hLB

Handle to the list box to check.

pt

POINT structure that contains the screen coordinates to check.

bAutoScroll

Scroll flag. If this parameter is TRUE and the point is directly above or below the list box, the function scrolls the list box by one line and returns  − 1. Otherwise, the function does not scroll the list box.

Return Value

The return value is the item identifier if the point is over a list item, or  − 1 otherwise.

Remarks

The LBItemFromPt function only scrolls the list box if a minimum amount of time has passed since it last did so. Timing prevents the list box from scrolling too quickly if the function is called repeatedly in rapid succession — for example, when DL_DRAGGING notification messages or WM_MOUSEMOVE messages are processed.

If the specified point is outside the client area of the list box and bAutoScroll is TRUE, the function scrolls the list box instead of returning an item identifier.

See Also

DL_DRAGGING, POINT, WM_MOUSEMOVE


LCMapString
 LCMapString  QuickInfo  Overview  Group

The LCMapString function maps one character string to another, performing a specified locale-dependent transformation. The function can also be used to generate a sort key for the input string.

int LCMapString(

LCID  Locale,	// locale identifier
DWORD  dwMapFlags,	// mapping transformation type
LPCTSTR  lpSrcStr,	// address of source string
int  cchSrc,	// number of characters in source string
LPTSTR  lpDestStr,	// address of destination buffer
int  cchDest	// size of destination buffer
);
Parameters

Locale

Specifies a locale identifier. The locale provides a context for the string mapping or sort key generation. An application can use the MAKELCID macro to create a locale identifier.

dwMapFlags

A set of flags that indicate the type of transformation to be used during string mapping or sort key generation. An application can specify more than one of these options on a single transformation, although some combinations are illegal. The following mapping options are defined; restrictions are noted following the table:

Option	Meaning
LCMAP_BYTEREV	Windows NT only: Use byte reversal. For example, if you pass in 0x3450 0x4822 the result is 0x5034 0x2248.
LCMAP_FULLWIDTH	Map single-byte characters to double-byte characters.
LCMAP_HALFWIDTH	Map double-byte characters to single-byte characters.
LCMAP_HIRAGANA	Map double-byte Katakana characters to double-byte Hiragana characters.
LCMAP_KATAKANA	Map double-byte Hiragana characters to double-byte Katakana characters.
LCMAP_LOWERCASE	Use lowercase.
LCMAP_SORTKEY	Produce a normalized wide-character sort key.
LCMAP_UPPERCASE	Use uppercase.
NORM_IGNORECASE	Ignore case.
NORM_IGNOREKANATYPE	Do not differentiate between Hiragana and Katakana characters. Corresponding Hiragana and Katakana will compare as equal.
NORM_IGNORENONSPACE	Ignore nonspacing. This flag also removes Japanese accent 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.
If the LCMAP_SORTKEY flag is not specified, the LCMapString function performs string mapping. In this case the following restrictions apply:

•	LCMAP_LOWERCASE and LCMAP_UPPERCASE are mutually exclusive.

•	LCMAP_HIRAGANA and LCMAP_KATAKANA are mutually exclusive.

•	LCMAP_HALFWIDTH and LCMAP_FULLWIDTH are mutually exclusive.

•	SORT_STRINGSORT, NORM_IGNOREKANATYPE, NORM_IGNOREWIDTH, and NORM_IGNORECASE are not valid.

•	LCMAP_LOWERCASE and LCMAP_UPPERCASE are not valid in combination with any of the following flags: LCMAP_HIRAGANA, LCMAP_KATAKANA, LCMAP_HALFWIDTH, and LCMAP_FULLWIDTH.

When the LCMAP_SORTKEY flag is specified, the LCMapString function generates a sort key. In this case the following restriction applies:

•	All LCMAP_* options are invalid, with the sole exception of LCMAP_BYTEREV. In other words, LCMAP_SORTKEY is mutually exclusive with all other LCMAP_* flags, with the sole exception of LCMAP_BYTEREV. LCMAP_BYTEREV is valid for Windows NT only.

lpSrcStr

Pointer to a source string that the function maps or uses for sort key generation.

cchSrc

Specifies the number of bytes (ANSI version) or characters (Unicode version) in the string pointed to by the lpSrcStr parameter.

This count can include the NULL terminator, or not include it. If the NULL terminator is included in the character count, it does not greatly affect the mapping behavior. That is because NULL is considered to be unsortable, and always maps to itself.

A cchSrc value of −1 specifies that the string pointed to by lpSrcStr is null-terminated. If this is the case, and LCMapString is being used in its string-mapping mode, the function calculates the string's length itself, and null-terminates the mapped string stored into *lpDestStr.

lpDestStr

Pointer to a buffer into which the function stores the mapped string or sort key.

If LCMAP_SORTKEY is specified, LCMapString stores a sort key into the buffer. The sort key is stored as an array of byte values in the following format:

[all Unicode sort weights] 0x01 [all Diacritic weights] 0x01 [all Case weights] 0x01 [all Special weights] 0x00

Note that the sort key is null-terminated. This is true regardless of the value of cchSrc. Also note that, even if some of the sort weights are absent from the sort key, due to the presence of one or more ignore flags in dwMapFlags, the 0x01 separators and the 0x00 terminator are still present.

cchDest

Specifies the size in bytes (ANSI version) or characters (Unicode version) of the buffer pointed to by lpDestStr.

If the function is being used for string mapping, the size is a character count. If space for a NULL terminator is included in cchSrc, then cchDest must also include space for a NULL terminator.

If the function is being used to generate a sort key, the size is a byte count. This byte count must include space for the sort key 0x00 terminator.

If cchDest is zero, the function's return value is the number of characters, or bytes if LCMAP_SORTKEY is specified, required to hold the mapped string or sort key. In this case, the buffer pointed to by lpDestStr is not used.

Return Value

If the function succeeds, and the value of cchDest is nonzero, the return value is the number of characters, or bytes if LCMAP_SORTKEY is specified, written to the buffer. This count includes room for a NULL terminator.

If the function succeeds, and the value of cchDest is zero, the return value is the size of the buffer in characters, or bytes if LCMAP_SORTKEY is specified, required to receive the translated string or sort key. This size includes room for a NULL terminator.

If the function fails, the return value is 0. 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 A version of this function maps strings to and from Unicode based on the specified LCID's default ANSI code page.

If the LCMAP_HIRAGANA flag is specified to map Katakana characters to Hiragana characters, and LCMAP_FULLWIDTH is not specified, the function only maps full-width characters to Hiragana. In this case, any half-width Katakana characters are placed as-is in the output string, with no mapping to Hiragana. An application must specify LCMAP_FULLWIDTH if it wants half-width Katakana characters mapped to Hiragana.

The lpSrcStr and lpDestStr pointers must not be the same. If they are the same, the function fails, and GetLastError returns ERROR_INVALID_PARAMETER.

Even if the wide-character Unicode version of this function is called, the output string is only in WCHAR or CHAR format if the string mapping mode of LCMapString is used. If the sort key generation mode is used, specified by LCMAP_SORTKEY, the output is an array of byte values. An application can compare sort keys by using a byte-by-byte comparison.

An application can call the function with the NORM_IGNORENONSPACE and NORM_IGNORESYMBOLS flags set, and all other options flags cleared, in order to simply strip characters from the input string. If this is done with an input string that is not null-terminated, it is possible for LCMapString to return an empty string and not return an error.

The LCMapString function ignores the Arabic Kashida. If an application calls the function to create a sort key for a string containing an Arabic Kashida, there will be no sort key value for the Kashida.

The function treats the hyphen and apostrophe a bit differently than other punctuation symbols, so that words like coop and co-op stay together in a list. All punctuation symbols other than the hyphen and apostrophe sort before the alphanumeric characters. An application can change this behavior by setting the SORT_STRINGSORT flag. See CompareString for a more detailed discussion of this issue.

When LCMapString is used to generate a sort key, by setting the LC_MAPSORTKEY flag, the sort key stored into *lpDestStr may contain an odd number of bytes. The LCMAP_BYTEREV option (Windows NT only) only reverses an even number of bytes. If both options are chosen, the last (odd-positioned) byte in the sort key is not reversed. If the terminating 0x00 byte is an odd-positioned byte, then it remains the last byte in the sort key. If the terminating 0x00 byte is an even-positioned byte, it exchanges positions with the byte that precedes it.

See Also

CompareString, FoldString, MAKELCID


LeaveCriticalSection
 LeaveCriticalSection  QuickInfo  Overview  Group

The LeaveCriticalSection function releases ownership of the specified critical section object.

VOID LeaveCriticalSection(

LPCRITICAL_SECTION  lpCriticalSection	// address of critical section object
);
Parameters

lpCriticalSection

Points to the critical section object.

Return Value

This function does not return a value.

Remarks

A thread uses the EnterCriticalSection function to acquire ownership of a critical section object. Once a thread owns a critical section, it can make additional calls to EnterCriticalSection without blocking its execution. This prevents a thread from deadlocking itself while waiting for a critical section that it already owns. To release its ownership, the thread must call LeaveCriticalSection once for each time that it entered the critical section.

If a thread calls LeaveCriticalSection when it does not have ownership of the specified critical section object, an error occurs that may cause another thread using EnterCriticalSection to wait indefinitely.

The threads of a single process can use a critical section object to provide mutually exclusive access to a shared resource. For similar synchronization between the threads of different processes, use a mutex object.

See Also

CreateMutex, DeleteCriticalSection, EnterCriticalSection, InitializeCriticalSection


LimitEmsPages
 LimitEmsPages  Overview  Group

The LimitEmsPages function is obsolete.

This function is provided only for compatibility with 16-bit versions of Windows. New Win32-based applications do not require this function.


LineDDA
 LineDDA  QuickInfo  Overview  Group

The LineDDA function determines which pixels should be highlighted for a line defined by the specified starting and ending points.

BOOL LineDDA(

int  nXStart,	// x-coordinate of line's starting point
int  nYStart,	// y-coordinate of line's starting point
int  nXEnd,	// x-coordinate of line's ending point
int  nYEnd,	// y-coordinate of line's ending point
LINEDDAPROC  lpLineFunc,	// address of application-defined callback function
LPARAM  lpData	// address of application-defined data
);
Parameters

nXStart

Specifies the x-coordinate of the line's starting point.

nYStart

Specifies the y-coordinate of the line's starting point.

nXEnd

Specifies the x-coordinate of the line's ending point.

nYEnd

Specifies the y-coordinate of the line's ending point.

lpLineFunc

Specifies the address of an application-defined callback function. For more information, see the LineDDAProc callback function.

lpData

Points to the application-defined data.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

The LineDDA function passes the coordinates for each point along the line, except for the line's ending point, to the application-defined callback function. In addition to passing the coordinates of a point, this function passes any existing application-defined data.

The coordinates passed to the callback function match pixels on a video display only if the default transformations and mapping modes are used.

See Also

LineDDAProc


LineDDAProc
 LineDDAProc  QuickInfo  Overview  Group

A LineDDAProc function is an application-defined callback function that processes coordinates from the LineDDA function. A value of type LINEDDAPROC is a pointer to such a function.

VOID CALLBACK LineDDAProc(

int  X,	// x-coordinate of point being evaluated
int  Y,	// y-coordinate of point being evaluated
LPARAM  lpData	// address of application-defined data
);
Parameters

X

Specifies the x-coordinate of the current point.

Y

Specifies the y-coordinate of the current point.

lpData

Points to the application-defined data.

Remarks

LineDDAProc is a placeholder for an application-defined function name.

An application registers a LineDDAProc function by passing its address to the LineDDA function.

See Also

LineDDA


LineTo
 LineTo  QuickInfo  Overview  Group

The LineTo function draws a line from the current position up to, but not including, the specified point.

BOOL LineTo(

HDC  hdc,	// device context handle
int  nXEnd,	// x-coordinate of line's ending point
int  nYEnd	// y-coordinate of line's ending point
);
Parameters

hdc

Identifies a device context.

nXEnd

Specifies the x-coordinate of the line's ending point.

nYEnd

Specifies the y-coordinate of the line's ending point.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

The coordinates of the line's ending point are specified in logical units.

The line is drawn by using the current pen and, if the pen is a geometric pen, the current brush.

If LineTo succeeds, the current position is set to the specified ending point.

See Also

MoveToEx, Polyline, PolylineTo


listen
 listen  QuickInfo

The Windows Sockets listen function establishes a socket to listen for incoming connection.

int listen (

SOCKET s,
int backlog
);
Parameters

s

A descriptor identifying a bound, unconnected socket.

backlog

The maximum length to which the queue of pending connections may grow.

Remarks

To accept connections, a socket is first created with socket, a backlog for incoming connections is specified with listen, and then the connections are accepted with accept. The listen function applies only to sockets that support connections, in other words, those of type SOCK_STREAM. The socket s is put into "passive" mode where incoming connections are acknowledged and queued pending acceptance by the process.

This function is typically used by servers that could have more than one connection request at a time: if a connection request arrives with the queue full, the client will receive an error with an indication of WSAECONNREFUSED.

The listen function attempts to continue to function correctly when there are no available descriptors. It will accept connections until the queue is emptied. If descriptors become available, a later call to listen or accept will refill the queue to the current or most recent "backlog," if possible, and resume listening for incoming connections.

Compatibility

The backlog parameter is currently limited (silently) to 5. As in 4.3BSD, illegal values (less than 1 or greater than 5) are replaced by the nearest legal value.

Return Value

If the function succeeds, listen returns zero.

If the function failes, a value of SOCKET_ERROR is returned. To get extended error information, call WSAGetLastError.

Error Codes

WSANOTINITIALISED	A successful WSAStartup must occur before using this function.
WSAENETDOWN	The Windows Sockets implementation has detected that the network subsystem has failed.
WSAEADDRINUSE	An attempt has been made to listen on an address in use.
WSAEINPROGRESS	A blocking Windows Sockets operation is in progress.
WSAEINVAL	The socket has not been bound with bind or is already connected.
WSAEISCONN	The socket is already connected.
WSAEMFILE	No more file descriptors are available.
WSAENOBUFS	No buffer space is available.
WSAENOTSOCK	The descriptor is not a socket.
WSAEOPNOTSUPP	The referenced socket is not of a type that supports the listen operation.
See Also

accept, bind, connect, socket, WSAStartup


LoadAccelerators
 LoadAccelerators  QuickInfo  Overview  Group

The LoadAccelerators function loads the specified accelerator table.

HACCEL LoadAccelerators(

HINSTANCE  hInstance,	// handle of application instance
LPCTSTR  lpTableName	// address of table-name string
);
Parameters

hInstance

Identifies an instance of the module whose executable file contains the accelerator table to load.

lpTableName

Points to a null-terminated string that names the accelerator table to load. Alternatively, this parameter can specify the resource identifier of an accelerator-table resource in the low-order word and zero in the high-order word. The MAKEINTRESOURCE macro can be used to create this value.

Return Value

If the function succeeds, the return value is the handle of the loaded accelerator table.

If the function fails, the return value is NULL.

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.

See Also

CopyAcceleratorTable, CreateAcceleratorTable, DestroyAcceleratorTable, MAKEINTRESOURCE


LoadBitmap
 LoadBitmap  QuickInfo  Overview  Group

The LoadBitmap function loads the specified bitmap resource from a module's executable file.

HBITMAP LoadBitmap(

HINSTANCE  hInstance,	// handle of application instance
LPCTSTR  lpBitmapName	// address of bitmap resource name
);
Parameters

hInstance

Identifies the instance of the module whose executable file contains the bitmap to be loaded.

lpBitmapName

Points to a null-terminated string that contains the name of the bitmap 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 be used to create this value.

Return Value

If the function succeeds, the return value is the handle of the specified bitmap.

If the function fails, the return value is NULL.

Remarks

If the bitmap pointed to by the lpBitmapName parameter does not exist or there is insufficient memory to load the bitmap, the function fails.

An application can use the LoadBitmap function to access the predefined bitmaps used by the Win32 API. To do so, the application must set the hInstance parameter to NULL and the lpBitmapName parameter to one of the following values:

OBM_BTNCORNERS	OBM_OLD_RESTORE
OBM_BTSIZE	OBM_OLD_RGARROW
OBM_CHECK	OBM_OLD_UPARROW
OBM_CHECKBOXES	OBM_OLD_ZOOM
OBM_CLOSE	OBM_REDUCE
OBM_COMBO	OBM_REDUCED
OBM_DNARROW	OBM_RESTORE
OBM_DNARROWD	OBM_RESTORED
OBM_DNARROWI	OBM_RGARROW
OBM_LFARROW	OBM_RGARROWD
OBM_LFARROWD	OBM_RGARROWI
OBM_LFARROWI	OBM_SIZE
OBM_MNARROW	OBM_UPARROW
OBM_OLD_CLOSE	OBM_UPARROWD
OBM_OLD_DNARROW	OBM_UPARROWI
OBM_OLD_LFARROW	OBM_ZOOM
OBM_OLD_REDUCE	OBM_ZOOMD
Bitmap names that begin with OBM_OLD represent bitmaps used by Windows versions earlier than 3.0.

For an application to use any of the OBM_ constants, the constant OEMRESOURCE must be defined before the WINDOWS.H header file is included.

The application must call the DeleteObject function to delete each bitmap handle returned by the LoadBitmap function.

See Also

CreateBitmap, DeleteObject, LoadCursor, LoadIcon, MAKEINTRESOURCE


LoadCursor
 LoadCursor  QuickInfo  Overview  Group

The LoadCursor function loads the specified cursor resource from the executable (.EXE) file associated with an application instance.

HCURSOR LoadCursor(

HINSTANCE  hInstance,	// handle of application instance
LPCTSTR  lpCursorName	// name string or cursor resource identifier
);
Parameters

hInstance

Identifies an instance of the module whose executable file contains the cursor to be loaded.

lpCursorName

Points to a null-terminated string that contains the name of the cursor resource to be loaded. Alternatively, this parameter can consist of the resource identifier in the low-order word and zero in the high-order word. The MAKEINTRESOURCE macro can also be used to create this value.

To use one of the Win32 predefined cursors, the application must set the hInstance parameter to NULL and the lpCursorName parameter to one the following values:

Value	Description
IDC_APPSTARTING	Standard arrow and small hourglass
IDC_ARROW	Standard arrow
IDC_CROSS	Crosshair
IDC_IBEAM	Text I-beam
IDC_ICON	Windows NT only: Empty icon
IDC_NO	Slashed circle
IDC_SIZE	Windows NT only: Four-pointed arrow
IDC_SIZEALL	Same as IDC_SIZE
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 Value

If the function succeeds, the return value is the handle of the newly loaded cursor.

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

Remarks

LoadCursor only loads the cursor resource if it has not been loaded; otherwise, it retrieves the handle of the existing resource. This function returns a valid cursor handle only if the lpCursorName parameter points to a cursor resource. If lpCursorName points to any type of resource other than a cursor (such as an icon), the return value is not NULL, even though it is not a valid cursor handle.

The LoadCursor function searches the cursor resource most appropriate for the cursor for the current display device. The cursor resource can be a color or monochrome bitmap.

See Also

LoadImage, MAKEINTRESOURCE, SetCursor, SetCursorPos, ShowCursor


LoadCursorFromFile
 LoadCursorFromFile  QuickInfo  Overview  Group

The LoadCursorFromFile function creates a cursor based on data contained in a file. The file is specified by its name or by a system cursor identifier. The function returns a handle to the newly created cursor. Files containing cursor data may be in either cursor (.CUR) or animated cursor (.ANI) format.

HCURSOR LoadCursorFromFile (

LPCTSTR  lpFileName	// pointer to name of cursor file, or system cursor identifier
);
Parameters

lpFileName

Indicates the source of the file data to be used to create the cursor. The data in the file must be in either .CUR or .ANI format.

If the high-order word of lpszFileName is nonzero, it is a pointer to a string that is a fully qualified name of a file containing cursor data.

If the high-order word of lpszFileName is zero, the low-order word is a system cursor identifier. The function then searches the [Cursors] entry in the WIN.INI file for the file associated with the name of that system cursor. Here is a list of system cursor names and identifiers:

System Cursor Names	System Cursor Identifiers
"Arrow"	OCR_NORMAL
"IBeam"	OCR_IBEAM
"Wait"	OCR_WAIT
"Crosshair"	OCR_CROSS
"UpArrow"	OCR_UP
"Size"	OCR_SIZE
"Icon"	OCR_ICON
"SizeNWSE"	OCR_SIZENWSE
"SizeNESW"	OCR_SIZENESW
"SizeWE"	OCR_SIZEWE
"SizeNS"	OCR_SIZENS
"SizeAll"	OCR_SIZEALL
"No"	OCR_NO
"AppStarting"	OCR_APPSTARTING
For example, if the WIN.INI file contains the following :

[Cursors]

Arrow = "arrow.ani"

Then the call

LoadCursorFromFile((LPWSTR)OCR_NORMAL)

causes the LoadCursorFromFile function to obtain cursor data from the file ARROW.ANI. If the WIN.INI file doesn't contain an entry for the specified system cursor, the function fails and returns NULL.

Return Value

If the function is successful, the return value is a handle to the new cursor.

If the function fails, the return value is NULL. To get extended error information, call GetLastError. GetLastError may return the following value:

Value	Meaning
ERROR_FILE_NOT_FOUND	The specified file could not be found.
See Also

LoadCursor, SetCursor, SetSystemCursor


LoadIcon
 LoadIcon  QuickInfo  Overview  Group

The LoadIcon function loads the specified icon resource from the executable (.EXE) file associated with an application instance.

HICON LoadIcon(

HINSTANCE  hInstance,	// handle of application instance
LPCTSTR  lpIconName	// icon-name string or icon resource identifier
);
Parameters

hInstance

Identifies 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

Points 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 Windows 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	Asterisk (used in informative messages).
IDI_EXCLAMATION	Exclamation point (used in warning messages).
IDI_HAND	Hand-shaped icon (used in serious warning messages).
IDI_QUESTION	Question mark (used in prompting messages).
IDI_WINLOGO	Windows 95 only: Windows logo.
Return Value

If the function succeeds, the return value is the handle of 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.

Windows 95 only: 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.

See Also

CreateIcon, LoadImage, MAKEINTRESOURCE


LoadImage [New - Windows 95]
 LoadImage  QuickInfo  Overview  Group

[New - Windows 95]

The LoadImage function loads an icon, cursor, or bitmap.

HANDLE LoadImage(

HINSTANCE  hinst,	// handle of the instance that contains the image
LPCTSTR  lpszName,	// name or identifier of image
UINT  uType,	// type of image
int  cxDesired,	// desired width
int  cyDesired,	// desired height
UINT  fuLoad	// load flags
);
Parameters

hinst

Identifies an instance of the module that contains the image to be loaded. To load an OEM image, set this parameter to zero.

lpszName

Identifies the image to load.

If the hinst parameter is non-NULL and the fuLoad parameter does not include LR_LOADFROMFILE, lpszName is a pointer to a null-terminated string that contains the name of the image resource in the hinst module.

If hinst is NULL and LR_LOADFROMFILE is not specified, the low-order word of this parameter must be the identifier of the OEM image to load. The OEM image identifiers are defined in WINUSER.H and have the following prefixes:

Prefix	Meaning
OBM_	OEM bitmaps
OIC_	OEM icons
OCR_	OEM cursors
Windows 95: If the fuLoad parameter includes the LR_LOADFROMFILE value, lpszName is the name of the file that contains the image.

Windows NT: LR_LOADFROMFILE is not supported.

uType

Specifies the type of image to be loaded. This parameter can be one of the following values:

Value	Meaning
IMAGE_BITMAP	Loads a bitmap.
IMAGE_CURSOR	Loads a cursor.
IMAGE_ICON	Loads an icon.
cxDesired

Specifies the desired width, in pixels, of the icon or cursor. If this parameter is zero and fuLoad does not include LR_LOADREALSIZE, the function uses the SM_CXICON or SM_CXCURSOR system metric value to set the width.

cyDesired

Specifies the desired height, in pixels, of the icon or cursor. If this parameter is zero and fuLoad does not include LR_LOADREALSIZE, the function uses the SM_CYICON or SM_CYCURSOR system metric value to set the height.

fuLoad

Specifies a combination of the following values:

Value	Meaning
LR_DEFAULTCOLOR	The default flag; it does nothing. All it means is "not LR_MONOCHROME".
LR_LOADREALSIZE	Loads the image without any stretching.
LR_CREATEDIBSECTION	Windows 95 only: 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	Windows 95 only: Uses the width or height specified by the system metric values for cursors and 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 sets the size to that specified in the resource. If the resource contains multiple images, the function sets the size to that of the first image.
LR_LOADFROMFILE	Windows 95 only: 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	Windows 95 only: Searches the color table for the image and replaces the following shades of gray with the corresponding 3D color:
Color	Replaced with
Dk Gray, RGB(128,128,128)	COLOR_3DSHADOW
Gray, RGB(192,192,192)	COLOR_3DFACE
Lt Gray, RGB(223,223,223)	COLOR_3DLIGHT
LR_LOADTRANSPARENT	Windows 95 only: Retrieves the color value of the first pixel in the image and replaces the corresponding entry in the color table with the default window color (COLOR_WINDOW). All pixels in the image that use that entry become the default window color. This value applies only to images that have corresponding color tables.  If fuLoad includes both the LR_LOADTRANSPARENT and LR_LOADMAP3DCOLORS values, LRLOADTRANSPARENT takes precedence. However, the color table entry is replaced with COLOR_3DFACE rather than COLOR_WINDOW.
LR_MONOCHROME	Windows 95 only: Loads the image in black and white.
LR_SHARED	Windows 95 only: Shares the image handle if the image is loaded multiple times. If LR_SHARED is not set, a second call to LoadImage for the same resource will load the image again and return a different handle. Do not use LR_SHARED for images that have non-standard sizes, that may change after loading, or that are loaded from a file.
Return Value

If the function succeeds, the return value is the handle of the newly loaded image.

If the function fails, the return value is NULL.

See Also

CopyImage, GetSystemMetrics, LoadBitmap, LoadCursor, LoadIcon


LoadKeyboardLayout
 LoadKeyboardLayout  QuickInfo  Overview  Group

The implementations of LoadKeyboardLayout in Windows 95 and Windows NT are substantially different. To accommodate these differences, this reference page first presents the Windows 95 implementation in its entirety, followed by the Windows NT version.

Windows 95:

The LoadKeyboardLayout function loads a new keyboard layout into the system. Several keyboard layouts can be loaded at a time, but only one per process is active at a time. Loading multiple keyboard layouts makes it possible to rapidly switch between layouts.

HKL LoadKeyboardLayout(

LPCTSTR  pwszKLID,	// name of layout to load
UINT  Flags	// keyboard layout flags
);
Parameters

pwszKLID

Points to the buffer that specifies the name of the keyboard layout. This name is a string composed from the hexadecimal value of the primary 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. For a list of the primary language identifiers and secondary language identifiers that make up a language identifier, see the MAKELANGID macro.

Flags

Specifies how the keyboard layout is to be loaded. This parameter can be one of the following values:

Value	Meaning
KLF_ACTIVATE	If the given layout is not already loaded, the function loads and activates the layout for the current thread, inserting the layout at the head of the keyboard layouts list in front of the previously active layout. If the layout is already loaded and the KLF_REORDER value is not given, the function simply rotates the keyboard layouts list, making the next layout the active layout.
KLF_NOTELLSHELL	Prevents a ShellProc hook procedure from receiving an HSHELL_LANGUAGE hook code when the new layout is loaded. This value is typically used when an application loads multiple layouts, one after another. Applying this value to all but the last layout delays the shell's processing until all layouts have been added.
KLF_REORDER	Moves the given layout to the head of the keyboard layouts list, making that layout the active layout for the current thread. This value reorders the keyboard layouts list even if KLF_ACTIVATE is not given.
KLF_REPLACELANG	If the new layout has the same language identifier as a current layout, the new layout replaces the current one as the layout for that language. If this value is not given and the layouts have the same language identifiers, the current layout is not replaced and the function returns NULL.
KLF_SUBSTITUTE_OK	Substitues the given keyboard layout with another layout preferred by the user. The substitution occurs only if the registry key HKEY_CURRENT_USER\Keyboard Layout\Substitutes explicitly defines a substitution layout. For example, if the key includes the value name "00000409" with value "00010409", loading the U.S. English layout ("00000409") causes the Dvorak U.S. English layout ("00010409") to be loaded instead. The system uses KLF_SUBSTITUTE_OK when booting and it is recommended that all applications use this value too.
Return Value

If the function succeeds, the return value is the keyboard layout handle of the layout matched with the requested name or NULL if no matching keyboard is available.

Remarks

If a layout is to be loaded with the same language as a previously loaded one and the KLF_REPLACELANG flag is not set, the call fails. Only one loaded layout may be associated with a given language. (It is acceptable for multiple IMEs to be loaded with associations to the same language.)

An application can and will typically want to load the default layout or IME for a language and can do so by specifying only a string version of the language identifier. If an application wants to load a specific layout or IME, it should read the registry to determine the specific layout identifier to pass to LoadKeyboardLayout. In this case, a request to activate the default keyboard layout handle for a locale will activate the first matching one. A specific IME should be activated using an explicit keyboard layout handle returned from one of GetKeyboardLayout, GetKeyboardLayoutList or LoadKeyboardLayout.

See Also

ActivateKeyboardLayout, GetKeyboardLayout, GetKeyboardLayoutName, MAKELANGID, UnloadKeyboardLayout

Windows NT:

The LoadKeyboardLayout function loads a keyboard layout.

HKL LoadKeyboardLayout(

LPCTSTR  pwszKLID,	// address of buffer for layout name
UINT  Flags	// keyboard layout flags
);
Parameters

pwszKLID

Points to the buffer that specifies the name of the keyboard layout. The name should be derived from the hexadecimal value of the language identifier corresponding to the layout. 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. For a list of the primary language identifiers and sub-language identifiers that make up a language identifier, see the MAKELANGID macro.

Flags

Specifies how the keyboard layout is to be loaded. This parameter can be one of the following values:

Value	Meaning
KLF_ACTIVATE	The function loads the layout if it is not already loaded, and activates it. This value activates the layout for the entire system not just the calling thread.
KLF_REORDER	This flag is meaningful only if the KLF_ACTIVATE flag is set and the layout is already loaded. If these conditions are met and the KLF_REORDER bit is set, the function removes the specified layout from its position in the system's circular list of loaded layouts, and places it at the head of the list as the active layout.
	If the KLF_ACTIVATE bit is set and the layout is loaded but the KLF_REORDER bit is not set, the function simply rotates the system's circular list of loaded layouts.
	If the KLF_ACTIVATE flag is set and the layout is not already loaded, it is loaded as the active layout and inserted in the system's circular list of keyboard layouts ahead of the previously active layout.
KLF_SUBSTITUTE_OK	The specified layout is looked up in the user's profile (in the registry under the key HKEY_CURRENT_USER\Keyboard Layout\Substitutes) to find a substitution layout preferred by the user. For example, if there was a value in this section of name "00000409" equal to "00010409", loading the U.S. English layout ("00000409") with the KLF_SUBSTITUTE_OK flag set would cause the Dvorak U.S. English layout ("00010409") to be loaded.
KLF_UNLOADPREVIOUS	If KLF_ACTIVATE is specified, and the layout is loaded and activated successfully, the function unloads the previously active layout. Otherwise, the function ignores this flag.
Return Value

If the function succeeds, the return value is the handle of the keyboard layout.

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

Remarks

Several keyboard layouts can be loaded at a time, but only one at a time is active. Loading multiple keyboard layouts makes it possible to switch rapidly between layouts.

See Also

ActivateKeyboardLayout, GetKeyboardLayoutName, UnloadKeyboardLayout


LoadLibrary
 LoadLibrary  QuickInfo  Overview  Group

The LoadLibrary function maps the specified executable module into the address space of the calling process.

HINSTANCE LoadLibrary(

LPCTSTR  lpLibFileName	// address of filename of executable module
);
Parameters

lpLibFileName

Points to a null-terminated string that names the Win32 module (either a .DLL or .EXE file). The name specified is the filename of the module and is not related to the name stored in the library module itself, as specified by the LIBRARY keyword in the module-definition (.DEF) file.

If the string specifies a path but the file does not exist in the specified directory, the function fails.

If a path is not specified and the filename extension is omitted, the default library extension .DLL is appended. However, the filename string can include a trailing point character (.) to indicate that the module name has no extension. When no path is specified, the function searches for the file in the following sequence:

1.	The directory from which the application loaded.

2.	The current directory.

3.	Windows 95: The Windows system directory. Use the GetSystemDirectory function to get the path of this directory.

Windows NT: The 32-bit Windows system directory. Use the GetSystemDirectory function to get the path of this directory. The name of this directory is SYSTEM32.

4.	Windows NT only: The 16-bit Windows system directory. There is no Win32 function that obtains the path of this directory, but it is searched. The name of this directory is SYSTEM.

5.	The Windows directory. Use the GetWindowsDirectory function to get the path of this directory.

6.	The directories that are listed in the PATH environment variable.

The first directory searched is the one directory containing the image file used to create the calling process (for more information, see the CreateProcess function). Doing this allows private dynamic-link library (DLL) files associated with a process to be found without adding the process's installed directory to the PATH environment variable.

Once the function obtains a fully qualified path to a library module file, the path is compared (case independently) to the full paths of library modules currently loaded into the calling process. These libraries include those loaded when the process was starting up as well as those previously loaded by LoadLibrary but not unloaded by FreeLibrary. If the path matches the path of an already loaded module, the function just increments the reference count for the module and returns the module handle for that library.

Return Value

If the function succeeds, the return value is a handle to the module.

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

Remarks

LoadLibrary can be used to map a DLL module and return a handle that can be used in GetProcAddress to get the address of a DLL function. LoadLibrary can also be used to map other executable modules. For example, the function can specify an .EXE file to get a handle that can be used in FindResource or LoadResource.

Module handles are not global or inheritable. A call to LoadLibrary by one process does not produce a handle that another process can use — for example, in calling GetProcAddress. The other process must make its own call to LoadLibrary for the module before calling GetProcAddress.

If the module is a DLL not already mapped for the calling process, the system calls the DLL's DllEntryPoint function with the DLL_PROCESS_ATTACH value. If the DLL's entry-point function does not return TRUE, LoadLibrary fails and returns NULL.

See Also

DllEntryPoint, FindResource, FreeLibrary, GetProcAddress, GetSystemDirectory, GetWindowsDirectory, LoadResource


LoadLibraryEx
 LoadLibraryEx  QuickInfo  Overview  Group

The LoadLibraryEx function maps a specified executable module into the address space of the calling process. The executable module can be a .DLL or an .EXE file. The specified module may cause other modules to be mapped into the address space.

HINSTANCE LoadLibraryEx(

LPCTSTR  lpLibFileName,	// points to name of executable module
HANDLE  hFile,	// reserved, must be NULL
DWORD  dwFlags	// entry-point execution flag
);
Parameters

lpLibFileName

Points to a null-terminated string that names a Win32 executable module (either a .DLL or an .EXE file). The name specified is the filename of the executable module. This name is not related to the name stored in a library module itself, as specified by the LIBRARY keyword in the module-definition (.DEF) file.

If the string specifies a path, but the file does not exist in the specified directory, the function fails.

If the string does not specify a path, and the filename extension is omitted, the function appends the default library extension .DLL to the filename. However, the filename string can include a trailing point character (.) to indicate that the module name has no extension.

If the string does not specify a path, the function uses a standard search strategy to find the file. See the Remarks for more information.

If mapping the specified module into the address space causes the operating system to map in other, associated executable modules, the function can use either the standard search strategy or an alternate search strategy to find those modules. See the Remarks for more information.

Once the function obtains a fully qualified path to a library module file, the path is compared (in a case-independent manner) to the full paths of library modules that are currently loaded into the calling process. That set of libraries includes those that were loaded when the process was starting up, as well as those previously loaded by calls to LoadLibrary or LoadLibraryEx but not yet unloaded by calls to FreeLibrary. If the path matches the path of an already loaded module, the function just increments the reference count for the module, and returns the module handle for that library.

hFile

This parameter is reserved for future use. It must be NULL.

dwFlags

Specifies the action to take when loading the module. This parameter can be one of the following values:

Flag	Meaning
DONT_RESOLVE_DLL_REFERENCES
	Windows NT only:  If this value is given, and the executable module is a dynamic-link library (DLL), the operating system does not call the DllEntryPoint function for process and thread initialization and termination. Also, the system does not load additional executable modules that are referenced by the specified module. If this value is not given, and the executable module is a DLL, the operating system calls the DllEntryPoint function for process and thread initialization and termination. The system loads additional executable modules that are referenced by the specified module. The behavior of the function is then identical to that of LoadLibrary in this regard.
LOAD_LIBRARY_AS_DATAFILE
	If this value is given, the function does a simple mapping of the file into the address space. Nothing is done relative to executing or preparing to execute the code in the mapped file. The function loads the module as if it were a data file. You can use the module handle that the function returns in this case with the Win32 functions that operate on resources. Use this flag when you want to load a DLL in order to extract messages or resources from it, and have no intention of executing its code. If this value is not given, the function maps the file into the address space in the manner that is normal for an executable module. The behavior of the function is then identical to that of LoadLibrary in this regard.
LOAD_WITH_ALTERED_SEARCH_PATH
	If this value is given, and lpLibFileName specifies a path, the function uses the alternate file search strategy discussed in the Remarks section following to find associated executable modules that the specified module causes to be loaded. If this value is not given, or if lpLibFileName does not specify a path, the function uses the standard search strategy discussed in the Remarks section following to find associated executable modules that the specified module causes to be loaded. The behavior of the function is then identical to that of LoadLibrary in this regard.
Return Value

If the function succeeds, the return value is a handle to the mapped executable module.

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

Remarks

Note that the DONT_RESOLVE_DLL_REFERENCES flag is only implemented on the Windows NT platform. It is not implemented on the Windows 95 platform.

The calling process can use the handle returned by this function to identify the module in calls to the GetProcAddress, FindResource, and LoadResource functions.

The LoadLibraryEx function is very similar to the LoadLibrary function. The differences consist of a set of optional behaviors that LoadLibraryEx provides. First, LoadLibraryEx can map a DLL module without calling the DllEntryPoint function of the DLL. Second, LoadLibraryEx can use either of two file search strategies to find executable modules that are associated with the specified module. Third, LoadLibraryEx can load a module in a way that is optimized for the case where the module will never be executed, loading the module as if it were a data file. You select these optional behaviors by setting the dwFlags parameter; if dwFlags is zero, LoadLibraryEx behaves identically to LoadLibrary.

If no path is specified, the LoadLibraryEx function uses the same standard file search strategy that LoadLibrary, SearchPath, and OpenFile use to find the executable module and any associated executable modules that it causes to be loaded. This standard strategy searches for a file in the following sequence:

1.	The directory from which the application loaded.

2.	The current directory.

3.	Windows 95: The Windows system directory. Use the GetSystemDirectory function to get the path of this directory.

Windows NT: The 32-bit Windows system directory. Use the GetSystemDirectory function to get the path of this directory. The name of this directory is SYSTEM32.

4.	Windows NT only: The 16-bit Windows system directory. There is no Win32 function that obtains the path of this directory, but it is searched. The name of this directory is SYSTEM.

5.	The Windows directory. Use the GetWindowsDirectory function to get the path of this directory.

6.	The directories that are listed in the PATH environment variable.

If a path is specified, and the dwFlags parameter is set to LOAD_WITH_ALTERED_SEARCH_PATH, the LoadLibraryEx function uses an alternate file search strategy to find any executable modules that the specified module causes to be loaded. This alternate strategy searches for a file in the following sequence:

1.	The directory specified by the lpLibFileName path. In other words, the directory that the specified executable module is in.

2.	The current directory.

3.	Windows 95: The Windows system directory. Use the GetSystemDirectory function to get the path of this directory.

Windows NT: The 32-bit Windows system directory. Use the GetSystemDirectory function to get the path of this directory. The name of this directory is SYSTEM32.

4.	Windows NT only: The 16-bit Windows system directory. There is no Win32 function that obtains the path of this directory, but it is searched. The name of this directory is SYSTEM.

5.	The Windows directory. Use the GetWindowsDirectory function to get the path of this directory.

6.	The directories that are listed in the PATH environment variable.

Note that the standard file search strategy and the alternate search strategy differ in just one way: the standard strategy starts its search in the calling application's directory, and the alternate strategy starts its search in the directory of the executable module that LoadLibraryEx is loading.

If you specify the alternate search strategy, its behavior continues until all associated executable modules have been located. Once the system starts processing DLL initialization routines, the system reverts to the standard search strategy.

See Also

DllEntryPoint, FindResource, FreeLibrary, GetProcAddress, GetSystemDirectory, GetWindowsDirectory, LoadLibrary, LoadResource, OpenFile, SearchPath


LoadMenu
 LoadMenu  QuickInfo  Overview  Group

The LoadMenu function loads the specified menu resource from the executable (.EXE) file associated with an application instance.

HMENU LoadMenu(

HINSTANCE  hInstance,	// handle of application instance
LPCTSTR  lpMenuName	// menu name string or menu-resource identifier
);
Parameters

hInstance

Identifies the instance of the module containing the menu resource to be loaded.

lpMenuName

Points 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 Value

If the function succeeds, the return value is the handle of 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.

See Also

LoadMenuIndirect, MAKEINTRESOURCE


LoadMenuIndirect
 LoadMenuIndirect  QuickInfo  Overview  Group

The LoadMenuIndirect function loads the specified menu template in memory.

HMENU LoadMenuIndirect(

CONST MENUTEMPLATE  *lpMenuTemplate	// address of menu template
);
Parameters

lpMenuTemplate

Windows NT: Points to a menu template.

Windows 95: Points 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. In Windows 95, an extended menu template consists of a MENUEX_TEMPLATE_HEADER structure followed by one or more contiguous MENUEX_TEMPLATE_ITEM structures.

Return Value

If the function succeeds, the return value is the handle of 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.

See Also

LoadMenu, MENUITEMTEMPLATE, MENUITEMTEMPLATEHEADER


LoadModule
 LoadModule  QuickInfo  Overview  Group

The LoadModule function loads and executes a Windows-based application or creates a new instance of an existing Windows-based application.

This function is provided for compatibility with earlier versions of Windows. For Win32-based applications, use the CreateProcess function.

DWORD LoadModule(

LPCSTR  lpModuleName,	// address of filename to load
LPVOID  lpParameterBlock	// address of parameter block for new module
);
Parameters

lpModuleName

Points to a null-terminated string that contains the filename of the application to run. If the lpModuleName parameter does not contain a directory path, Windows searches for the executable file in this order:

1.	The directory from which the application loaded.

2.	The current directory.

3.	Windows 95: The Windows system directory. Use the GetSystemDirectory function to get the path of this directory.

Windows NT: The 32-bit Windows system directory. Use the GetSystemDirectory function to get the path of this directory. The name of this directory is SYSTEM32.

4.	Windows NT only: The 16-bit Windows system directory. There is no Win32 function that obtains the path of this directory, but it is searched. The name of this directory is SYSTEM.

5.	The Windows directory. Use the GetWindowsDirectory function to get the path of this directory.

6.	The directories that are listed in the PATH environment variable.

lpParameterBlock

Points to an application-defined LOADPARMS32 structure that defines the new application's parameter block.

Set all unused members to NULL, except for lpCmdLine, which must point to a null-terminated string if it is not used.

Return Value

If the function succeeds, the return value is greater than 31.

If the function fails, the return value is an error value, which may be one of the following:

Value	Meaning
0	The system is out of memory or resources.
ERROR_BAD_FORMAT	The .EXE file is invalid (non-Win32 .EXE or error in .EXE image).
ERROR_FILE_NOT_FOUND	The specified file was not found.
ERROR_PATH_NOT_FOUND	The specified path was not found.
Remarks

Win32-based applications should use the CreateProcess function. In the Win32 API, the implementation of the LoadModule function calls CreateProcess. The following section describes how each parameter for CreateProcess is formed:

CreateProcess parameter	Value
lpszImageName	LoadModule lpModuleName parameter.
lpszCommandLine	LoadModule lpParameterBlock->lpCmdLine.
lpsaProcess	NULL.
lpsaThread	NULL.
fInheritHandles	FALSE.
fdwCreate	0.
lpvEnvironment	LoadModule lpParameterBlock->lpEnvAddress.
lpszCurDir	NULL.
lpsiStartInfo	The structure is initialized to zero. The cb member is set to the size of the structure, and the wShowWindow member is set to the value of the second word of the LoadModule lpParameterBlock->lpCmdShow parameter.
lppiProcInfo.hProcess	The handle is immediately closed.
lppiProcInfo.hThread	The handle is immediately closed.
See Also

CreateProcess, GetSystemDirectory, GetWindowsDirectory, ShowWindow, STARTUPINFO, WinExec


LoadResource
 LoadResource  QuickInfo  Overview  Group

The LoadResource function loads the specified resource into global memory.

HGLOBAL LoadResource(

HMODULE  hModule,	// resource-module handle
HRSRC  hResInfo	// resource handle
);
Parameters

hModule

Identifies the module whose executable file contains the resource. If hModule is NULL, Windows loads the resource from the module that was used to create the current process.

hResInfo

Identifies the resource to be loaded. This handle must be created by using the FindResource or FindResourceEx function.

Return Value

If the function succeeds, the return value is a handle to the global memory block containing the data associated with the resource.

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

Remarks

Windows 95: The system does not automatically free resources loaded using the LoadResource function. Applications must use the FreeResource function function to explicitly discard a resource that is no longer needed.

Windows NT: The system automatically frees resources. Calling the FreeRource function is not necessary to free a resource loaded by using the LoadResource function.

See Also

FindResource, FindResourceEx, LoadLibrary, LoadModule, LockResource


LoadString
 LoadString  QuickInfo  Overview  Group

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 of module containing string resource
UINT  uID,	// resource identifier
LPTSTR  lpBuffer,	// address of buffer for resource
int  nBufferMax	// size of buffer
);
Parameters

hInstance

Identifies an instance of the module whose executable file contains the string resource.

uID

Specifies the integer identifier of the string to be loaded.

lpBuffer

Points to the buffer to receive the string.

nBufferMax

Specifies the size of the buffer in bytes (ANSI version) or characters (Unicode version). The string is truncated and null terminated if it is longer than the number of characters specified.

Return Value

If the function succeeds, the return value is the number of bytes (ANSI version) or characters (Unicode version) 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.

See Also

FormatMessage, LoadAccelerators, LoadBitmap, LoadCursor, LoadIcon, LoadMenu, LoadMenuIndirect


LocalAlloc
 LocalAlloc  QuickInfo  Overview  Group

The LocalAlloc function allocates the specified number of bytes from the heap. In the linear Win32 API environment, there is no difference between the local heap and the global heap.

HLOCAL LocalAlloc(

UINT  uFlags,	// allocation attributes
UINT  uBytes	// number of bytes to allocate
);
Parameters

uFlags

Specifies how to allocate memory. If zero is specified, the default is the LMEM_FIXED flag. Except for the incompatible combinations that are specifically noted, any combination of the following flags can be specified. To indicate whether the function allocates fixed or movable memory, specify one of the first six flags:

Flag	Meaning
LMEM_FIXED
	Allocates fixed memory. This flag cannot be combined with the LMEM_MOVEABLE or LMEM_DISCARDABLE flag. The return value is a pointer to the memory block. To access the memory, the calling process simply casts the return value to a pointer.
LMEM_MOVEABLE
	Allocates movable memory. This flag cannot be combined with the LMEM_FIXED flag. The return value is the handle of the memory object. The handle is a 32-bit quantity that is private to the calling process. To translate the handle into a pointer, use the LocalLock function.
LPTR
	Combines the LMEM_FIXED and LMEM_ZEROINIT flags.
LHND
	Combines the LMEM_MOVEABLE and LMEM_ZEROINIT flags.
NONZEROLHND
	Same as the LMEM_MOVEABLE flag.
NONZEROLPTR
	Same as the LMEM_FIXED flag.
LMEM_DISCARDABLE
	Allocates discardable memory. This flag cannot be combined with the LMEM_FIXED flag. Some Win32-based applications may ignore this flag.
LMEM_NOCOMPACT
	Does not compact or discard memory to satisfy the allocation request.
LMEM_NODISCARD
	Does not discard memory to satisfy the allocation request.
LMEM_ZEROINIT
	Initializes memory contents to zero.
uBytes

Specifies the number of bytes to allocate. If this parameter is zero and the uFlags parameter specifies the LMEM_MOVEABLE flag, the function returns a handle to a memory object that is marked as discarded.

Return Value

If the function succeeds, the return value is the handle of the newly allocated memory object.

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

Remarks

If the heap does not contain sufficient free space to satisfy the request, LocalAlloc returns NULL.

The GlobalAlloc and LocalAlloc functions are limited to a combined total of 65,536 handles for GMEM_MOVEABLE and LMEM_MOVEABLE memory per process. This limitation does not apply to GMEM_FIXED or LMEM_FIXED memory.

If this function succeeds, it allocates at least the amount requested. If the amount allocated is greater than the amount requested, the process can use the entire amount. To determine the actual number of bytes allocated, use the LocalSize function.

See Also

GlobalAlloc, LocalFree, LocalLock, LocalReAlloc, LocalSize


LocalCompact
 LocalCompact  QuickInfo  Overview  Group

The LocalCompact function is not implemented in the Win32 API.


LocalDiscard
 LocalDiscard  QuickInfo  Overview  Group

The LocalDiscard function discards the specified local memory object. The lock count of the memory object must be zero.

HLOCAL LocalDiscard(

HLOCAL  hlocMem	// handle of local memory object
);
Parameters

hlocMem

Identifies the local memory object. This handle is returned by either the LocalAlloc or LocalReAlloc function.

Return Value

If the function succeeds, the return value is the handle of the local memory object.

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

Remarks

LocalDiscard discards only local objects allocated by a process with the LMEM_DISCARDABLE flag. If a process attempts to discard a fixed or locked object, the function fails.

Although LocalDiscard discards the object's memory block, the handle of the object remains valid. A process can subsequently pass the handle to the LocalReAlloc function to allocate another local memory object identified by the same handle.

See Also

LocalAlloc, LocalReAlloc


LocalFileTimeToFileTime
 LocalFileTimeToFileTime  QuickInfo  Overview  Group

The LocalFileTimeToFileTime function converts a local file time to a file time based on the Coordinated Universal Time (UTC).

BOOL LocalFileTimeToFileTime(

CONST FILETIME *  lpLocalFileTime,	// address of local file time to convert
LPFILETIME  lpFileTime	// address of converted file time
);
Parameters

lpLocalFileTime

Points to a FILETIME structure that specifies the local file time to be converted into a UTC-based file time.

lpFileTime

Points to a FILETIME structure to receive the converted UTC-based file time. This parameter cannot be the same as the lpLocalFileTime parameter.

Return Value

If the function succeeds, the return value is TRUE; otherwise, it is FALSE. To get extended error information, use the GetLastError function.

See Also

FILETIME, FileTimeToLocalFileTime


LocalFlags
 LocalFlags  QuickInfo  Overview  Group

The LocalFlags function returns information about the specified local memory object.

UINT LocalFlags(

HLOCAL  hMem	// handle of local memory object
);
Parameters

hMem

Identifies the local memory object. This handle is returned by either the LocalAlloc or LocalReAlloc function.

Return Value

If the function succeeds, the return value is a 32-bit value that specifies the allocation flags and the lock count for the memory object.

If the function fails, the return value is the LMEM_INVALID_HANDLE flag, indicating that the local handle is not valid. To get extended error information, call GetLastError.

Remarks

The low-order byte of the low-order word of the return value contains the lock count of the object. To retrieve the lock count from the return value, use the LMEM_LOCKCOUNT mask with the bitwise AND (&) operator. The lock count of memory objects allocated with the LMEM_FIXED flag is always zero.

The high-order byte of the low-order word of the return value indicates the allocation flags of the memory object. It can be zero or any combination of the following flags:

Value	Description
LMEM_DISCARDABLE	The object's memory block can be discarded.
LMEM_DISCARDED	The object's memory block has been discarded.
See Also

GlobalFlags, LocalAlloc, LocalDiscard, LocalLock, LocalReAlloc, LocalUnlock


LocalFree
 LocalFree  QuickInfo  Overview  Group

The LocalFree function frees the specified local memory object and invalidates its handle.

HLOCAL LocalFree(

HLOCAL  hMem	// handle of local memory object
);
Parameters

hMem

Identifies the local memory object. This handle is returned by either the LocalAlloc or LocalReAlloc function.

Return Value

If the function succeeds, the return value is NULL.

If the function fails, the return value is equal to the handle of the local memory object. To get extended error information, call GetLastError.

Remarks

If the process tries to examine or modify the memory after it has been freed, heap corruption may occur or an access violation exception (EXCEPTION_ACCESS_VIOLATION) may be generated.

If the hMem parameter is NULL, LocalFree ignores the parameter and returns NULL.

LocalFree succeeds even if the memory object is locked by a previous call to the LocalLock function. The LocalLock function locks a local memory object and increments the lock count by one. The LocalUnlock function unlocks it and decrements the lock count by one. To get the lock count of a local memory object, use the LocalFlags function. LocalFree will free a locked memory object. A locked memory object has a lock count greater than zero.

Both GlobalFree and LocalFree will free a locked memory object. However, if you run an application under a debug version of Windows NT or Windows 95, both GlobalFree and LocalFree will issue a message that tells you that this is happening. If you are debugging the application, GlobalFree and LocalFree will enter a hard-coded breakpoint just before freeing a locked object. This lets you double-check the intended behavior.

See Also

GlobalFree, LocalAlloc, LocalFlags, LocalLock, LocalReAlloc, LocalUnlock


LocalHandle
 LocalHandle  QuickInfo  Overview  Group

The LocalHandle function retrieves the handle associated with the specified pointer to a local memory object.

HLOCAL LocalHandle(

LPCVOID  pMem	// address of local memory object
);
Parameters

pMem

Points to the first byte of the local memory object. This pointer is returned by the LocalLock function.

Return Value

If the function succeeds, the return value is the handle of the specified local memory object.

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

Remarks

When the LocalAlloc function allocates a local memory object with the LMEM_MOVEABLE flag, it returns the handle of the object. The LocalLock function converts this handle into a pointer to the object's memory block, and LocalHandle converts the pointer back into a handle.

See Also

LocalAlloc, LocalLock


LocalInit
 LocalInit  Overview  Group

The LocalInit function has been deleted.


LocalLock
 LocalLock  QuickInfo  Overview  Group

The LocalLock function locks a local memory object and returns a pointer to the first byte of the object's memory block. The memory block associated with a locked memory object cannot be moved or discarded. For memory objects allocated with the LMEM_MOVEABLE flag, the function increments the object's lock count.

LPVOID LocalLock(

HLOCAL  hMem	// handle of local memory object
);
Parameters

hMem

Identifies the local memory object. This handle is returned by either the LocalAlloc or LocalReAlloc function.

Return Value

If the function succeeds, the return value is a pointer to the first byte of the memory block.

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

Remarks

The internal data structures for each memory object include a lock count that is initially zero. For movable memory objects, LocalLock increments the count by one, and the LocalUnlock function decrements the count by one. For each call that a process makes to LocalLock for an object, it must eventually call LocalUnlock. Locked memory will not be moved or discarded unless the memory object is reallocated by using the LocalReAlloc function. The memory block of a locked memory object remains locked in memory until its lock count is decremented to zero, at which time it can be moved or discarded.

Memory objects allocated with the LMEM_FIXED flag always have a lock count of zero. For these objects, the value of the returned pointer is equal to the value of the specified handle.

If the specified memory block has been discarded or if the memory block has a zero-byte size, this function returns NULL.

Discarded objects always have a lock count of zero.

See Also

LocalAlloc, LocalFlags, LocalReAlloc, LocalUnlock


LocalReAlloc
 LocalReAlloc  QuickInfo  Overview  Group

The LocalReAlloc function changes the size or the attributes of a specified local memory object. The size can increase or decrease.

HLOCAL LocalReAlloc(

HLOCAL  hMem,	// handle of local memory object
UINT  uBytes,	// new size of block
UINT  uFlags	// how to reallocate object
);
Parameters

hMem

Identifies the local memory object to be reallocated. This handle is returned by either the LocalAlloc or LocalReAlloc function.

uBytes

Specifies the new size, in bytes, of the memory block. If this parameter is zero and the uFlags parameter specifies the LMEM_MOVEABLE flag, the function returns a handle to a memory object that is marked as discarded. If uFlags specifies the LMEM_MODIFY flag, this parameter is ignored.

uFlags

Specifies how to reallocate the local memory object. If the LMEM_MODIFY flag is specified, this parameter modifies the attributes of the memory object, and the uBytes parameter is ignored. Otherwise, this parameter controls the reallocation of the memory object.

The LMEM_MODIFY flag can be combined with either or both of the following flags:

Flag	Meaning
LMEM_DISCARDABLE
	Allocates discardable memory if the LMEM_MODIFY flag is also specified. This flag is ignored, unless the object was previously allocated as movable or the LMEM_MOVEABLE flag is also specified.
LMEM_MOVEABLE
	You cannot combine LMEM_MOVEABLE with LMEM_MODIFY to change a fixed memory object into a movable one. The function returns an error if an application attempts this.
If uFlags does not specify LMEM_MODIFY, this parameter can be any combination of the following flags:

Flag	Meaning
LMEM_MOVEABLE
	If uBytes is zero, discards a previously movable and discardable memory block. If the object's lock count is not zero or the block is not movable and discardable, the function fails.
	If uBytes is nonzero, enables the system to move the reallocated block to a new location without changing the movable or fixed attribute of the memory object. If the object is fixed, the handle returned may be different from the handle specified in the hMem parameter. If the object is movable, the block can be moved without invalidating the handle, even if the object is currently locked by a previous call to the LocalLock function. To get the new address of the memory block, use LocalLock.
LMEM_NOCOMPACT
	Prevents memory from being compacted or discarded to satisfy the allocation request.
LMEM_ZEROINIT
	Causes the additional memory contents to be initialized to zero if the memory object is growing in size.
Return Value

If the function succeeds, the return value is the handle of the reallocated memory object.

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

Remarks

If LocalReAlloc reallocates a movable object, the return value is the handle of the memory object. To convert the handle to a pointer, use the LocalLock function.

If LocalReAlloc reallocates a fixed object, the value of the handle returned is the address of the first byte of the memory block. To access the memory, a process can simply cast the return value to a pointer.

See Also

LocalAlloc, LocalFree, LocalLock


LocalShrink
 LocalShrink  QuickInfo  Overview  Group

The LocalShrink function is obsolete. It has no meaning in the 32-bit envronment.


LocalSize
 LocalSize  QuickInfo  Overview  Group

The LocalSize function returns the current size, in bytes, of the specified local memory object.

UINT LocalSize(

HLOCAL  hMem	// handle of local memory object
);
Parameters

hMem

Identifies the local memory object. This handle is returned by the LocalAlloc, LocalReAlloc, or LocalHandle function.

Return Value

If the function succeeds, the return value is the size, in bytes, of the specified local memory object. If the specified handle is not valid or if the object has been discarded, the return value is zero. To get extended error information, call GetLastError.

Remarks

The size of a memory block may be larger than the size requested when the memory was allocated.

To verify that the specified object's memory block has not been discarded, call the LocalFlags function before calling LocalSize.

See Also

LocalAlloc, LocalFlags, LocalHandle, LocalReAlloc


LocalUnlock
 LocalUnlock  QuickInfo  Overview  Group

The LocalUnlock function decrements the lock count associated with a memory object that was allocated with the LMEM_MOVEABLE flag. This function has no effect on memory objects allocated with the LMEM_FIXED flag.

BOOL LocalUnlock(

HLOCAL  hMem	// handle of local memory object
);
Parameters

hMem

Identifies the local memory object. This handle is returned by either the LocalAlloc or LocalReAlloc function.

Return Value

If the memory object is still locked after decrementing the lock count, the return value is TRUE.

If the function fails, the return value is FALSE. To get extended error information, call GetLastError. If GetLastError returns NO_ERROR, the memory object is unlocked.

Remarks

The internal data structures for each memory object include a lock count that is initially zero. For movable memory objects, the LocalLock function increments the count by one, and LocalUnlock decrements the count by one. For each call that a process makes to LocalLock for an object, it must eventually call LocalUnlock. Locked memory will not be moved or discarded unless the memory object is reallocated by using the LocalReAlloc function. The memory block of a locked memory object remains locked until its lock count is decremented to zero, at which time it can be moved or discarded.

If the memory object is already unlocked, LocalUnlock returns FALSE and GetLastError reports ERROR_NOT_LOCKED. Memory objects allocated with the LMEM_FIXED flag always have a lock count of zero and cause the ERROR_NOT_LOCKED error.

A process should not rely on the return value to determine the number of times it must subsequently call LocalUnlock for the memory block.

See Also

LocalAlloc, LocalFlags, LocalLock, LocalReAlloc


LockFile
 LockFile  QuickInfo  Overview  Group

The LockFile function locks a region in an open file. Locking a region prevents other processes from accessing the region.

BOOL LockFile(

HANDLE  hFile,	// handle of file to lock
DWORD  dwFileOffsetLow,	// low-order word of lock region offset
DWORD  dwFileOffsetHigh,	// high-order word of lock region offset
DWORD  nNumberOfBytesToLockLow,	// low-order word of length to lock
DWORD  nNumberOfBytesToLockHigh	// high-order word of length to lock
);
Parameters

hFile

Identifies the file with a region to be locked. The file handle must have been created with GENERIC_READ or GENERIC_WRITE access to the file (or both).

dwFileOffsetLow

Specifies the low-order word of the starting byte offset in the file where the lock should begin.

dwFileOffsetHigh

Specifies the high-order word of the starting byte offset in the file where the lock should begin.

nNumberOfBytesToLockLow

Specifies the low-order word of the length of the byte range to be locked.

nNumberOfBytesToLockHigh

Specifies the high-order word of the length of the byte range to be locked.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

Locking a region of a file gives the locking process exclusive access to the specified region. File locks are not inherited by processes created by the locking process.

Locking a region of a file denies all other processes both read and write access to the specified region. Locking a region that goes beyond the current end-of-file position is not an error.

Locks may not overlap an existing locked region of the file.

The UnlockFile function unlocks a file region locked by LockFile.

See Also

CreateFile, UnlockFile


LockFileEx
 LockFileEx  QuickInfo  Overview  Group

The LockFileEx function locks a byte range within an open file for shared or exclusive access.

BOOL LockFileEx(

HANDLE  hFile,	// handle of file to lock
DWORD  dwFlags,	// functional behavior modification flags
DWORD  dwReserved,	// reserved, must be set to zero
DWORD  nNumberOfBytesToLockLow,	// low-order 32 bits of length to lock
DWORD  nNumberOfBytesToLockHigh,	// high-order 32 bits of length to lock
LPOVERLAPPED  lpOverlapped	// addr. of structure with lock region start offset
);
Parameters

hFile

Identifies an open handle to a file that is to have a range of bytes locked for shared or exclusive access. The handle must have been created with either GENERIC_READ or GENERIC_WRITE access to the file.

dwFlags

Specifies flags that modify the behavior of this function. This parameter may be one or more of the following values:

Value	Meaning
LOCKFILE_FAIL_IMMEDIATELY	If this value is specified, the function returns immediately if it is unable to acquire the requested lock. Otherwise, it waits.
LOCKFILE_EXCLUSIVE_LOCK	If this value is specified, the function requests an exclusive lock. Otherwise, it requests a shared lock.
dwReserved

Reserved parameter; must be set to zero.

nNumberOfBytesToLockLow

Specifies the low-order 32 bits of the length of the byte range to lock.

nNumberOfBytesToLockHigh

Specifies the high-order 32 bits of the length of the byte range to lock.

lpOverlapped

Points to an OVERLAPPED structure that the function uses with the locking request. This structure, which is required, contains the file offset of the beginning of the lock range.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

Locking a region of a file is used to acquire shared or exclusive access to the specified region of the file. File locks are not inherited by a new process during process creation.

Locking a portion of a file for exclusive access denies all other processes both read and write access to the specified region of the file. Locking a region that goes beyond the current end-of-file position is not an error.

Locking a portion of a file for shared access denies all other processes write access to the specified region of the file, but allows other processes to read the locked region.

If an exclusive lock is requested for a file that is already locked either shared or exclusively by other threads, this call waits until the lock is granted, unless the LOCKFILE_FAIL_IMMEDIATELY flag is specified.

Locks may not overlap an existing locked region of the file.

See Also

CreateFile, LockFile, OVERLAPPED, UnlockFile, UnlockFileEx


LockResource
 LockResource  QuickInfo  Overview  Group

The LockResource function locks the specified resource in memory.

LPVOID LockResource(

HGLOBAL  hResData	// handle to resource to lock
);
Parameters

hResData

Identifies the resource to be locked. The LoadResource function returns this handle.

Return Value

If the loaded resource is locked, the return value is a pointer to the first byte of the resource; otherwise, it is NULL.

Remarks

It is not necessary for Win32-based applications to unlock resources that were locked by the LockResource function.

Trying to lock a resource by using the handle returned by the FindResource or FindResourceEx function will not work. You will get back a value that is incorrect and points to random data.

See Also

FindResource, FindResourceEx, LoadResource


LockSegment
 LockSegment  QuickInfo  Overview  Group

The LockSegment function is obsolete. It has no meaning in the 32-bit envronment.


LockServiceDatabase
 LockServiceDatabase  QuickInfo  Overview  Group

The LockServiceDatabase function locks a specified database.

SC_LOCK LockServiceDatabase(

SC_HANDLE  hSCManager	// handle of service control manager database
);
Parameters

hSCManager

Identifies the service control manager database. The OpenSCManager function returns this handle, which must have SC_MANAGER_LOCK access.

Return Value

If the function succeeds, the return value is a lock to the specified service control manager database.

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

Errors

The following error code may be set by the service control manager. Other error codes may be set by registry functions that are called by the service control manager.

Value	Meaning
ERROR_ACCESS_DENIED	The specified handle was not opened with SC_MANAGER_LOCK access.
ERROR_INVALID_HANDLE	The specified handle is invalid.
ERROR_SERVICE_DATABASE_LOCKED	The database is locked.
Remarks

The LockServiceDatabase function tries to acquire a lock on the specified database. Only one process at a time can have a lock on a database.

A lock is a protocol used by setup and configuration programs and the service control manager to serialize access to the service tree in the registry. The only time the service control manager acquires a lock is when it is starting a service. Setup and configuration programs are expected to acquire a lock before using the ChangeServiceConfig or SetServiceObjectSecurity function to reconfigure a service. They should also acquire a lock before using the registry functions to reconfigure a service. The lock prevents the service control manager from starting a service while it is being reconfigured.

A call to the StartService function to start a service in a locked database fails. All other service control manager functions are not affected by a lock.

The lock is held until the SC_LOCK handle is specified in a subsequent call to the UnlockServiceDatabase function. If a process that is holding a lock terminates, the service control manager automatically cleans up and releases the lock.

See Also

ChangeServiceConfig, OpenSCManager, QueryServiceLockStatus, SetServiceObjectSecurity, StartService, UnlockServiceDatabase


LockWindowUpdate
 LockWindowUpdate  QuickInfo  Overview  Group

The LockWindowUpdate function disables or reenables drawing in the specified window. Only one window can be locked at a time.

BOOL LockWindowUpdate(

HWND  hWndLock	// handle of window to lock
);
Parameters

hWndLock

Specifies the window in which drawing will be disabled. If this parameter is NULL, drawing in the locked window is enabled.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE, indicating that an error occurred or another window was already locked.

Remarks

If an application with a locked window (or any locked child windows) calls the GetDC, GetDCEx, or BeginPaint function, the called function returns a device context with a visible region that is empty. This will occur until the application unlocks the window by calling LockWindowUpdate, specifying a value of NULL for hWndLock.

If an application attempts to draw within a locked window, the system records the extent of the attempted operation in a bounding rectangle. When the window is unlocked, the system invalidates the area within this bounding rectangle, forcing an eventual WM_PAINT message to be sent to the previously locked window and its child windows. If no drawing has occurred while the window updates were locked, no area is invalidated.

LockWindowUpdate does not make the given window invisible and does not clear the WS_VISIBLE style bit.

A locked window cannot be moved.

See Also

BeginPaint, GetDC, GetDCEx, WM_PAINT


LogonUser [New - Windows NT]
 LogonUser  QuickInfo

[New - Windows NT]

The LogonUser function attempts to perform a user logon operation. You specify the user with a user name and domain, and authenticate the user with a clear-text password. If the function succeeds, you receive a handle to a token that represents the logged-on user. You can then use this token handle to impersonate the specified user, or to create a process running in the context of the specified user.

BOOL LogonUser(

LPTSTR lpszUsername,	// string that specifies the user name
LPTSTR lpszDomain,	// string that specifies the domain or servero
LPTSTR lpszPassword,	// string that specifies the password
DWORD dwLogonType,	// specifies the type of logon operation
DWORD dwLogonProvider,	// specifies the logon provider
PHANDLE phToken	// pointer to variable to receive token handle
);
Parameters

lpszUsername

Pointer to a zero-terminated string that specifies the user name. This is the name of the user account to log on to.

lpszDomain

Pointer to a zero-terminated string that specifies the domain or server to log on to.

lpszPasswordc

Pointer to a zero-terminated string that specifies the clear-text password for the user account specified by lpszUsername.

dwLogonType

Specifies the type of logon operation to perform. The following logon types are defined:

Value	Meaning
LOGON32_LOGON_BATCH	Indicates a batch-type logon. For example, this can be a logon without a user present on either the console or at the other end of a network connection.
LOGON32_LOGON_INTERACTIVE	Indicates a logon in which the user has an active connection of some type, either through a console or through a network connection, such as a telnet-style connection.
LOGON32_LOGON_SERVICE	Indicates a service-type logon. The account provided must have the service privilege enabled.
dwLogonProvider

Specifies the logon provider. The following logon providers are defined:

Value	Meaning
LOGON32_PROVIDER_DEFAULT	Use the standard logon provider. This is the recommended value for dwLogonProvider. It gives an application the maximum upward compatibility with future releases of Windows NT.
phToken

Pointer to a HANDLE variable that receives a handle to a token that represents the specified user.

You can use this token handle in calls to the ImpersonateLoggedOnUser and CreateProcessAsUser functions.

When you no longer need this handle, close it by calling the CloseHandle function.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The process that calls LogonUser must have the SeTcbPrivilege privilege. The privilege does not need to be enabled. The LogonUser function enables the privilege as necessary. The function fails if the calling process does not have the SeTcbPrivilege privilege, and GetLastError returns the error code ERROR_PRIVILEGE_NOT_HELD.

A user is considered logged on as long as at least one token exists. If you call CreateProcessAsUser and then close the token, the system considers the user as still logged on until the process (and all child processes) have ended.

See Also

CreateProcessAsUser, ImpersonateLoggedOnUser


LookupAccountName
 LookupAccountName  QuickInfo  Overview  Group

The LookupAccountName function accepts the name of a system and an account as input. It retrieves a security identifier (SID) for the account and the name of the domain on which the account was found.

BOOL LookupAccountName(

LPCTSTR  lpSystemName,	// address of string for system name
LPCTSTR  lpAccountName,	// address of string for account name
PSID  Sid,	// address of security identifier
LPDWORD  cbSid,	// address of size of security identifier
LPTSTR  ReferencedDomainName,	// address of string for referenced domain
LPDWORD  cbReferencedDomainName,	// address of size of domain string
PSID_NAME_USE  peUse	// address of SID-type indicator
);
Parameters

lpSystemName

Points to a null-terminated string specifying the system. This string can be the name of a remote computer. If this string is NULL, the account name is looked up on the local system.

lpAccountName

Points to a null-terminated string specifying the account name.

Sid

Points to a buffer receiving the SID structure that corresponds to the account name pointed to by the lpAccountName parameter.

cbSid

Specifies the size of the buffer pointed to by the Sid parameter. If the specified size is too small, the function sets this variable to the required buffer size.

ReferencedDomainName

Points to a buffer receiving the name of the domain where the account name is found.

cbReferencedDomainName

Specifies the size of the ReferencedDomainName buffer in characters. If the specified size is too small, the function sets this variable to the required buffer size.

peUse

Points to a SID_NAME_USE enumerated type indicating the type of the account when the function returns.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The LookupAccountName function attempts to find a security identifier for the specified name by first checking a list of well-known SIDs. If the name does not correspond to a well-known SID, the function checks built-in and administratively defined local accounts. Next, the function checks the primary domain. If the name is not found there, trusted domains are checked.

See Also

EqualPrefixSid, GetUserName, LookupAccountSid


LookupAccountSid
 LookupAccountSid  QuickInfo  Overview  Group

The LookupAccountSid function accepts a security identifier (SID) as input. It retrieves the name of the account for this SID and the name of the first domain on which this SID is found.

BOOL LookupAccountSid(

LPCTSTR  lpSystemName,	// address of string for system name
PSID  Sid,	// address of security identifier
LPTSTR  Name,	// address of string for account name
LPDWORD  cbName,	// address of size account string
LPTSTR  ReferencedDomainName,	// address of string for referenced domain
LPDWORD  cbReferencedDomainName,	// address of size domain string
PSID_NAME_USE  peUse	// address of structure for SID type
);
Parameters

lpSystemName

Points to a null-terminated string specifying the system. This string can be the name of a remote computer. If this string is NULL, the SID is looked up on the local system.

Sid

Points to a SID structure for which the account name is looked up.

Name

Points to a buffer receiving a null-terminated string representing the account name corresponding to the Sid parameter.

cbName

Specifies the size of the buffer pointed to by the Name parameter. If the specified size is too small, the function sets this variable to the required buffer size.

ReferencedDomainName

Points to a buffer that will receive a null-terminated string giving the name of the domain where the account name was found.

For Windows NT systems, the domain name returned for most accounts in the local computer's security database is the computer's name as of the last start of the system. Backslashes are excluded. If the computer's name changes, the old name continues to be returned as the domain name until the system is restarted.

For Windows NT Server systems, the domain name returned for most accounts in the local computer's security database is the name of the domain for which the Windows NT Server is a domain controller.

Some accounts are predefined by the system. The domain name returned for these accounts is BUILTIN.

cbReferencedDomainName

Specifies the size of the buffer pointed to by the ReferencedDomainName parameter. If the specified size is too small, the function sets this variable to the required buffer size.

peUse

Points to an SID_NAME_USE enumerated type indicating the type of the account when the function returns.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The LookupAccountSid function attempts to find a name for the specified security identifier by first checking a list of well-known SIDs. If the supplied SID does not correspond to a well-known SID, the function checks built-in and administratively defined local accounts. Next, the function checks the primary domain. Security identifiers not recognized by the primary domain are checked against the trusted domains corresponding to their SID prefixes.

See Also

EqualPrefixSid, LookupAccountName


LookupIconIdFromDirectory
 LookupIconIdFromDirectory  QuickInfo  Overview  Group

The LookupIconIdFromDirectory function searches through icon or cursor data for the icon or cursor that best fits the current display device.

int LookupIconIdFromDirectory(

PBYTE  presbits,	// address of resource data
BOOL  fIcon	// look for icon or cursor
);
Parameters

presbits

Points to the icon or cursor directory data. Because this function does not validate the resource data, it causes a general protection (GP) fault or returns an undefined value if presbits is not pointing to valid resource data.

fIcon

Specifies whether an icon or a cursor is sought. If this parameter is TRUE, the function is searching for an icon; if the parameter is FALSE, the function is searching for a cursor.

Return Value

If the function succeeds, the return value is an integer resource identifier for the icon or cursor that best fits the current display device.

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 (in Windows 95) functions use this function to search the specified resource data for the icon or cursor that best fits the current display device.

See Also

CreateIconFromResource, CreateIconIndirect, FindResource, FindResourceEx, GetIconInfo, LoadCursor, LoadIcon, LoadImage, LookupIconIdFromDirectoryEx, MAKEINTRESOURCE


LookupIconIdFromDirectoryEx [New - Windows 95]
 LookupIconIdFromDirectoryEx  QuickInfo

[New - Windows 95]

The LookupIconIdFromDirectoryEx function searches through icon or cursor data for the icon or cursor that best fits the current display device.

int LookupIconIdFromDirectoryEx(

PBYTE  presbits,	// address of resource data
BOOL  fIcon,	// icon or cursor flag
int  cxDesired,	// desired width of icon or cursor
int  cyDesired,	// desired height of icon or cursor
UINT  Flags	// resource flags
);
Parameters

presbits

Points to the icon or cursor directory data. Because this function does not validate the resource data, it causes a general protection (GP) fault or returns an undefined value if presbits is not pointing to valid resource data.

fIcon

Specifies whether an icon or a cursor is sought. If this parameter is TRUE, the function is searching for an icon; if the parameter is FALSE, the function is searching for a cursor.

cxDesired

Specifies the desired width, in pixels, of the icon. If this parameter is zero and Flags does not include LR_LOADREALSIZE, the function uses the SM_CXICON or SM_CXCURSOR system metric value.

cyDesired

Specifies the desired height, in pixels, of the icon. If this parameter is zero and Flags does not include LR_LOADREALSIZE, the function uses the SM_CYICON or SM_CYCURSOR system metric value.

Flags

Specifies a combination of the following values:

Value	Meaning
LR_DEFAULTCOLOR	Uses the default color format.
LR_LOADREALSIZE	Sets the width and height as specified by the biWidth and biHeight members of the BITMAPINFOHEADER structure that defines the icon or cursor. The cxDesired and cyDesired parameters are ignored.
LR_MONOCHROME	Creates a monochrome icon or cursor.
Return Value

If the function succeeds, the return value is an integer resource identifier for the icon or cursor that best fits the current display device.

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.

See Also

CreateIconFromResourceEx, CreateIconIndirect, FindResource, FindResourceEx, GetIconInfo, LoadCursor, LoadIcon, LoadImage, LookupIconIdFromDirectory, MAKEINTRESOURCE


LookupPrivilegeDisplayName
 LookupPrivilegeDisplayName  QuickInfo  Overview  Group

The LookupPrivilegeDisplayName function retrieves a displayable name representing a specified privilege.

BOOL LookupPrivilegeDisplayName(

LPCTSTR  lpSystemName,	// address of string specifying the system
LPCTSTR  lpName,	// address of string specifying the privilege
LPTSTR  lpDisplayName,	// address of string receiving the displayable name
LPDWORD  cbDisplayName,	// address of size of string for displayable name
LPDWORD  lpLanguageId	// address of language identifier
);
Parameters

lpSystemName

Points to a null-terminated string specifying the name of the system on which the displayable privilege name is looked up. If a null string is specified, the function attempts to find the displayable name on the local system.

lpName

Points to a null-terminated string specifying the name of the privilege, as defined in the WINNT.H header file. For example, this string could be SE_REMOTE_SHUTDOWN_NAME.

lpDisplayName

Points to a buffer receiving a null-terminated string giving the privilege's displayable name. For example, if the lpName parameter is SE_REMOTE_SHUTDOWN_NAME, the displayable name is, "Force shutdown from a remote system".

cbDisplayName

Points to a variable specifying the size, in characters, of the lpDisplayName buffer. When the function returns, this parameter contains the length of the displayable privilege name, not including the terminating null character. If the buffer pointed to by the lpDisplayName parameter is too small, this variable contains the required size when the function returns.

lpLanguageId

Points to a variable receiving the language identifier for the returned displayable name.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

For this release of Windows NT, only the privileges specified in the Defined Privileges section of WINNT.H are supported by this function.

See Also

LookupPrivilegeName, LookupPrivilegeValue


LookupPrivilegeName
 LookupPrivilegeName  QuickInfo  Overview  Group

The LookupPrivilegeName function retrieves the name corresponding to the privilege represented on a specific system by a specified locally unique identifier (LUID).

BOOL LookupPrivilegeName(

LPCTSTR  lpSystemName,	// address of string specifying the system
PLUID  lpLuid,	// address of locally unique identifier
LPTSTR  lpName,	// address of string specifying the privilege
LPDWORD  cbName	// address of size of string for displayable name
);
Parameters

lpSystemName

Points to a null-terminated string specifying the name of the system on which the privilege name is looked up. If a null string is specified, the function attempts to find the privilege name on the local system.

lpLuid

Points to the locally unique identifier by which the privilege is known on the target system.

lpName

Points to a buffer receiving a null-terminated string that represents the privilege's name. For example, this string could be SE_SECURITY_NAME.

cbName

Points to a variable specifying the size, in characters, of the lpName buffer. When the function returns, this parameter contains the length of the privilege name, not including the terminating null character. If the buffer pointed to by the lpName parameter is too small, this variable contains the required size when the function returns.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

For this release of Windows NT, only the privileges specified in the Defined Privileges section of WINNT.H are supported by this function.

See Also

LookupPrivilegeDisplayName, LookupPrivilegeValue


LookupPrivilegeValue
 LookupPrivilegeValue  QuickInfo  Overview  Group

The LookupPrivilegeValue function retrieves the locally unique identifier (LUID) used on a specified system to locally represent the specified privilege name.

BOOL LookupPrivilegeValue(

LPCTSTR  lpSystemName,	// address of string specifying the system
LPCTSTR  lpName,	// address of string specifying the privilege
PLUID  lpLuid	// address of locally unique identifier
);
Parameters

lpSystemName

Points to a null-terminated string specifying the name of the system on which the privilege name is looked up. If a null string is specified, the function attempts to find the privilege name on the local system.

lpName

Points to a null-terminated string specifying the privilege's name. For example, this string could be SE_SECURITY_NAME.

lpLuid

Points to a variable receiving the locally unique identifier by which the privilege is known on the system specified by the lpSystemName parameter.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

For this release of Windows NT, only the privileges specified in the Defined Privileges section of WINNT.H are supported by this function.

See Also

LookupPrivilegeDisplayName, LookupPrivilegeName


LPtoDP
 LPtoDP  QuickInfo  Overview  Group

The LPtoDP function converts logical coordinates into device coordinates. The conversion depends on the mapping mode of the device context, the settings of the origins and extents for the window and viewport, and the world transformation.

BOOL LPtoDP(

HDC  hdc,	// handle of device context
LPPOINT  lpPoints,	// array of points
int  nCount	// count of points
);
Parameters

hdc

Identifies the DC.

lpPoints

Points to an array of POINT structures. The x-coordinates and y-coordinates contained in each of the POINT structures will be transformed.

nCount

Specifies the number of points in the array.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

This function fails if the logical coordinates exceed 32 bits, or if the converted device coordinates exceed 27 bits. In the case of such an overflow, the results for all the points are undefined.

See Also

DPtoLP, POINT


lstrcat
 lstrcat  QuickInfo  Overview  Group

The lstrcat function appends one string to another.

LPTSTR lstrcat(

LPTSTR  lpString1,	// address of buffer for concatenated strings
LPCTSTR  lpString2	// address of string to add to string1
);
Parameters

lpString1

Points to a null-terminated string. The buffer must be large enough to contain both strings.

lpString2

Points to the null-terminated string to be appended to the string specified in the lpString1 parameter.

Return Value

If the function succeeds, the return value is a pointer to the buffer.

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

See Also

lstrcmp, lstrcmpi, lstrcpy, lstrlen


lstrcmp
 lstrcmp  QuickInfo  Overview  Group

The lstrcmp function compares two character strings. The comparison is case sensitive.

int lstrcmp(

LPCTSTR  lpString1,	// address of first string
LPCTSTR  lpString2	// address of second string
);
Parameters

lpString1

Points to the first null-terminated string to be compared.

lpString2

Points to the second null-terminated string to be compared.

Return Value

If the function succeeds and 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, it 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 via the control panel, determines which string is greater (or whether the strings are the same). If no language (locale) is selected, Windows performs the comparison by using default values. In the Windows United States language functions, uppercase characters have lower values than lowercase characters.

With a double-byte character set (DBCS) version of Windows, this function can compare two DBCS strings.

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

See Also

CompareString, lstrcat, lstrcmpi, lstrcpy, lstrlen


lstrcmpi
 lstrcmpi  QuickInfo  Overview  Group

The lstrcmpi function compares two character strings. The comparison is not case sensitive.

int lstrcmpi(

LPCTSTR  lpString1,	// address of first string
LPCTSTR  lpString2	// address of second string
);
Parameters

lpString1

Points to the first null-terminated string to be compared.

lpString2

Points to the second null-terminated string to be compared.

Return Value

If the function succeeds and 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, it 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 by using the control panel, determines which string is greater (or whether the strings are the same). If no language (locale) is selected, Windows 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 Windows, this function can compare two DBCS strings.

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

See Also

CompareString, lstrcat, lstrcmp, lstrcpy, lstrlen


lstrcpy
 lstrcpy  QuickInfo  Overview  Group

The lstrcpy function copies a string to a buffer.

LPTSTR lstrcpy(

LPTSTR  lpString1,	// address of buffer
LPCTSTR  lpString2	// address of string to copy
);
Parameters

lpString1

Points 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

Points to the null-terminated string to be copied.

Return Value

If the function succeeds, the return value is a pointer to the buffer.

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

Remarks

With a double-byte character set (DBCS) version of Windows, this function can be used to copy a DBCS string.

See Also

lstrcat, lstrcmp, lstrcmpi, lstrlen


lstrcpyn
 lstrcpyn  QuickInfo  Overview  Group

The lstrcpyn function copies a specified number of characters from a source string into a buffer.

LPTSTR lstrcpyn(

LPTSTR  lpString1,	// address of target buffer
LPCTSTR  lpString2,	// address of source string
int  iMaxLength	// number of bytes or characters to copy
);
Parameters

lpString1

Points to a buffer into which the function copies characters. The buffer must be large enough to contain the number of bytes (ANSI version) or characters (Unicode version) specified by iMaxLength, including room for a terminating null character.

lpString2

Points to a null-terminated string from which the function copies characters.

iMaxLength

Specifies the number bytes (ANSI version) or characters (Unicode version) to be copied from the string pointed to by lpString2 into the buffer pointed to by lpString1, including a terminating null character.

Return Value

If the function succeeds, the return value is a pointer to the buffer.

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

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.

See Also

lstrcat, lstrcmp, lstrcmpi, lstrcpy, lstrlen


lstrlen
 lstrlen  QuickInfo  Overview  Group

The lstrlen function returns the length in bytes (ANSI version) or characters (Unicode version) of the specified string (not including the terminating null character).

int lstrlen(

LPCTSTR  lpString	// address of string to count
);
Parameters

lpString

Points to a null-terminated string.

Return Value

If the function succeeds, the return value specifies the length of the string in bytes (ANSI version) or characters (Unicode version).

See Also

lstrcat, lstrcmp, lstrcmpi, lstrcpy


LZClose
 LZClose  QuickInfo  Overview  Group

The LZClose function closes a file that was opened by using the LZOpenFile function.

VOID LZClose(

INT  hFile	// LZ file handle identifying file to be closed
);
Parameters

hFile

Identifies the source file to be closed.

Return Value

This function does not return a value.

Remarks

The handle identifying the file must be retrieved by calling the LZOpenFile function. If the handle is retrieved by calling the CreateFile or OpenFile function, an error occurs.

If the file is compressed by using the Microsoft File Compression Utility (COMPRESS.EXE) and opened by using LZOpenFile, LZClose frees any global heap space that was allocated to expand the file.

See Also

CreateFile, LZOpenFile, OpenFile


LZCopy
 LZCopy  QuickInfo  Overview  Group

The LZCopy function copies a source file to a destination file. If the source file is compressed with the Microsoft File Compression Utility (COMPRESS.EXE), this function creates a decompressed destination file. If the source file is not compressed, this function duplicates the original file.

LONG LZCopy(

INT  hfSource,	// LZ file handle identifying source file
INT  hfDest	// LZ file handle identifying destination file
);
Parameters

hfSource

Identifies the source file.

hfDest

Identifies the destination file.

Return Value

If the function succeeds, the return value specifies the size, in bytes, of the destination file.

If the function fails, the return value is an LZERROR_* code. These codes have values less than zero. Note that LZCopy calls neither SetLastError nor SetLastErrorEx; thus, its failure does not affect a thread's last-error code.

Here is a list of the LZERROR_* codes that LZCopy can return upon failure:

Value	Meaning
LZERROR_BADINHANDLE	The handle identifying the source file is not valid. The file cannot be read.
LZERROR_BADOUTHANDLE	The handle identifying the destination file is not valid. The file cannot be written.
LZERROR_GLOBALLOC	The maximum number of open compressed files has been exceeded or local memory cannot be allocated.
LZERROR_GLOBLOCK	The LZ file handle cannot be locked down.
LZERROR_READ	The source file format is not valid.
Remarks

The handles identifying the source and destination files must be retrieved by calling the LZInit or LZOpenFile function.

The preferred function to use for copying files is LZCopy. The CopyLZFile function is provided for compatibility with 16-bit versions of Windows.

If the function succeeds, the file identified by the hfDest parameter is always uncompressed.

See Also

CopyLZFile, LZInit, LZOpenFile


LZDone
 LZDone  QuickInfo  Overview  Group

The LZDone function is obsolete. It is provided only for compatibility with 16-bit versions of Windows. Win32-based applications should use the LZOpenFile function.


LZInit
 LZInit  QuickInfo  Overview  Group

The LZInit function allocates memory for the internal data structures required to decompress files, and then creates and initializes them.

INT LZInit(

INT  hfSource	// handle of source file
);
Parameters

hfSource

Identifies the source file.

Return Value

If the function succeeds, the return value is a new LZ file handle.

If the function fails, the return value is an LZERROR_* code. These codes have values less than zero. Note that LZInit calls neither SetLastError nor SetLastErrorEx; thus, its failure does not affect a thread's last-error code.

Here is a list of the LZERROR_* codes that LZInit can return upon failure:

Value	Meaning
LZERROR_BADINHANDLE	The handle identifying the source file is not valid. The file cannot be read.
LZERROR_GLOBALLOC	The maximum number of open compressed files has been exceeded or local memory cannot be allocated.
LZERROR_GLOBLOCK	The LZ file handle cannot be locked down.
LZERROR_UNKNOWNALG	The file is compressed with an unrecognized compression algorithm.
Remarks

A maximum of 16 compressed files can be open at any given time. Similarly, a maximum of 16 uncompressed files can be open at any given time. An application should be careful to close the handle returned by LZInit when it is done using the file; otherwise, the application can inadvertently hit the 16-file limit.

The handle this function returns is compatible only with the functions in LZEXPAND.DLL; it should not be used for other file operations.


LZOpenFile
 LZOpenFile  QuickInfo  Overview  Group

The LZOpenFile function creates, opens, reopens, or deletes the specified file.

INT LZOpenFile(

LPTSTR  lpFileName,	// address of name of file to be opened
LPOFSTRUCT  lpReOpenBuf,	// address of open file structure
WORD  wStyle	// action to take
);
Parameters

lpFileName

Points to a string that specifies the name of a file.

lpReOpenBuf

Points to the OFSTRUCT structure that is to receive information about the file when the file is first opened. The structure can be used in subsequent calls to the LZOpenFile function to refer to the open file.

The szPathName member of this structure contains characters from the original equipment manufacturer (OEM) character set.

wStyle

Specifies the action to take. This parameter can be a combination of the following values:

Value	Meaning
OF_CANCEL	Ignored. In the Win32-based application programming interface (API), the OF_PROMPT style produces a dialog box containing a Cancel button.
OF_CREATE	Directs LZOpenFile to create a new file. If the file already exists, it is truncated to zero length.
OF_DELETE	Deletes the file.
OF_EXIST	Opens the file and then closes it to test for a file's existence.
OF_PARSE	Fills the OFSTRUCT structure but carries out no other action.
OF_PROMPT	Displays a dialog box if the requested file does not exist. The dialog box informs the user that Windows cannot find the file, and it contains Retry and Cancel buttons. Choosing the Cancel button directs LZOpenFile to return a "file not found" error message.
OF_READ	Opens the file for reading only.
OF_READWRITE	Opens the file for reading and writing.
OF_REOPEN	Opens the file using information in the reopen buffer.
OF_SHARE_DENY_NONE	Opens the file without denying other processes read or write access to the file. LZOpenFile fails if the file has been opened in compatibility mode by any other process.
OF_SHARE_DENY_READ	Opens the file and denies other processes read access to the file. LZOpenFile fails if the file has been opened in compatibility mode or has been opened for read access by any other process.
OF_SHARE_DENY_WRITE	Opens the file and denies other processes write access to the file. LZOpenFile fails if the file has been opened in compatibility mode or has been opened for write access by any other process.
OF_SHARE_EXCLUSIVE	Opens the file in exclusive mode, denying other processes both read and write access to the file. LZOpenFile fails if the file has been opened in any other mode for read or write access, even by the current process.
OF_WRITE	Opens the file for writing only.
Return Value

If the function succeeds and the value specified by the wStyle parameter is not OF_READ, the return value is a handle identifying the file. If the file is compressed and opened with wStyle set to OF_READ, the return value is a special file handle.

If the function fails, the return value is an LZERROR_* code. These codes have values less than zero. Note that LZOpenFile calls neither SetLastError nor SetLastErrorEx; thus, its failure does not affect a thread's last-error code.

Here is a list of the LZERROR_* codes that LZOpenFile can return upon failure:

Value	Meaning
LZERROR_BADINHANDLE	The handle identifying the source file is not valid. The file cannot be read.
LZERROR_GLOBALLOC	The maximum number of open compressed files has been exceeded or local memory cannot be allocated.
Remarks

If the wStyle parameter is the OF_READ flag (or OF_READ and any of the OF_SHARE_ flags) and the file is compressed, LZOpenFile calls the LZInit function, which performs the required initialization for the decompression operations.

The handle this function returns is compatible only with the functions in LZEXPAND.DLL; it should not be used for other file operations.

See Also

LZClose, LZInit, LZRead


LZRead
 LZRead  QuickInfo  Overview  Group

The LZRead function reads (at most) the specified number of bytes from a file and copies them into a buffer.

INT LZRead(

INT  hFile,	// LZ file handle of file
LPSTR  lpBuffer,	// address of buffer for bytes
INT  cbRead	// count of bytes
);
Parameters

hFile

Identifies the source file.

lpBuffer

Points to a buffer that receives the bytes read from the file.

cbRead

Specifies the count of bytes to be read.

Return Value

If the function succeeds, the return value specifies the number of bytes read.

If the function fails, the return value is an LZERROR_* code. These codes have values less than zero. Note that LZRead calls neither SetLastError nor SetLastErrorEx; thus, its failure does not affect a thread's last-error code.

Here is a list of the LZERROR_* codes that LZRead can return upon failure:

Value	Meaning
LZERROR_BADINHANDLE	The handle identifying the source file is not valid. The file cannot be read.
LZERROR_BADOUTHANDLE	The handle identifying the destination file is not valid. The file cannot be written.
LZERROR_BADVALUE	One of the input parameters is not valid.
LZERROR_GLOBALLOC	The maximum number of open compressed files has been exceeded or local memory cannot be allocated.
LZERROR_GLOBLOCK	The LZ file handle cannot be locked down.
LZERROR_READ	The source file format is not valid.
LZERROR_WRITE	There is insufficient space for the output file.
Remarks

The handle identifying the file must be retrieved by calling either the LZInit or LZOpenFile function.

If the file is compressed, LZRead emulates the _lread function on an expanded image of the file and copies the bytes of data into the specified buffer.

Applications must call the LZOpenFile, LZSeek, and LZRead functions instead of the OpenFile, _llseek, and _lread functions.

See Also

LZInit, LZOpenFile, LZSeek


LZSeek
 LZSeek  QuickInfo  Overview  Group

The LZSeek function moves a file pointer a number of bytes from a starting position.

LONG LZSeek(

INT  hFile,	// handle of source file
LONG  lOffset,	// number of bytes to move
INT  iOrigin	// starting position
);
Parameters

hFile

Identifies the source file.

lOffset

Specifies the number of bytes by which to move the file pointer.

iOrigin

Specifies the starting position of the pointer. This parameter must be one of the following values:

Value	Meaning
0	Moves the file pointer lOffset bytes from the beginning of the file.
1	Moves the file pointer lOffset bytes from the current position.
2	Moves the file pointer lOffset bytes from the end of the file.
Return Value

If the function succeeds, the return value specifies the offset from the beginning of the file to the new pointer position.

If the function fails, the return value is an LZERROR_* code. These codes have values less than zero. Note that LZSeek calls neither SetLastError nor SetLastErrorEx; thus, its failure does not affect a thread's last-error code.

Upon failure, LZSeek can return the following LZERROR_* codes:

Value	Meaning
LZERROR_BADINHANDLE	The handle identifying the source file is not valid. The file cannot be read.
LZERROR_BADVALUE	One of the parameters is outside the range of acceptable values.
LZERROR_GLOBLOCK	The LZ file handle cannot be locked down.
Remarks

The handle identified by the hFile parameter must be retrieved by calling either the LZInit or LZOpenFile function.

If the file is compressed, LZSeek emulates the _llseek function on an expanded image of the file.

See Also

LZInit, LZOpenFile


LZStart
 LZStart  QuickInfo  Overview  Group

The LZStart function is obsolete. It is provided only for compatibility with 16-bit versions of Windows. Win32-based applications should use the LZCopy function.


MakeAbsoluteSD
 MakeAbsoluteSD  QuickInfo  Overview  Group

The MakeAbsoluteSD function creates a security descriptor in absolute format by using a security descriptor in self-relative format as a template.

BOOL MakeAbsoluteSD(

PSECURITY_DESCRIPTOR  pSelfRelativeSecurityDescriptor,	// address self-relative SD
PSECURITY_DESCRIPTOR  pAbsoluteSecurityDescriptor,	// address of absolute SD
LPDWORD  lpdwAbsoluteSecurityDescriptorSize,	// address of size of absolute SD
PACL  pDacl,	// address of discretionary ACL
LPDWORD  lpdwDaclSize,	// address of size of discretionary ACL
PACL  pSacl,	// address of system ACL
LPDWORD  lpdwSaclSize,	// address of size of system ACL
PSID  pOwner,	// address of owner SID
LPDWORD  lpdwOwnerSize,	// address of size of owner SID
PSID  pPrimaryGroup,	// address of primary-group SID
LPDWORD  lpdwPrimaryGroupSize	// address of size of group SID
);
Parameters

pSelfRelativeSecurityDescriptor

Points to a SECURITY_DESCRIPTOR structure in self-relative format. The function creates an absolute-format version of this security descriptor without modifying the original security descriptor.

pAbsoluteSecurityDescriptor

Points to a buffer that the function fills with the main body of an absolute-format security descriptor. This information is formatted as a SECURITY_DESCRIPTOR structure.

lpdwAbsoluteSecurityDescriptorSize

Points to a variable specifying the size of the buffer pointed to by the pAbsoluteSecurityDescriptor parameter. If the buffer is not large enough for the security descriptor, the function fails and sets this variable to the minimum required size.

pDacl

Points to a buffer the function fills with the discretionary access-control list (ACL) of the absolute-format security descriptor. The main body of the absolute-format security descriptor references this pointer.

lpdwDaclSize

Points to a variable specifying the size of the buffer pointed to by the pDacl parameter. If the buffer is not large enough for the ACL, the function fails and sets this variable to the minimum required size.

pSacl

Points to a buffer the function fills with the system ACL of the absolute-format security descriptor. The main body of the absolute-format security descriptor references this pointer.

lpdwSaclSize

Points to a variable specifying the size of the buffer pointed to by the pSacl parameter. If the buffer is not large enough for the ACL, the function fails and sets this variable to the minimum required size.

pOwner

Points to a buffer the function fills with the security identifier (SID) of the owner of the absolute-format security descriptor. The main body of the absolute-format security descriptor references this pointer.

lpdwOwnerSize

Points to a variable specifying the size of the buffer pointed to by the pOwner parameter. If the buffer is not large enough for the SID, the function fails and sets this variable to the minimum required size.

pPrimaryGroup

Points to a buffer the function fills with the SID of the absolute-format security descriptor's primary group. The main body of the absolute-format security descriptor references this pointer.

lpdwPrimaryGroupSize

Points to a variable specifying the size of the buffer pointed to by the pPrimaryGroup parameter. If the buffer is not large enough for the SID, the function fails and sets this variable to the minimum required size.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

A security descriptor in absolute format contains pointers to the information it contains, rather than the information itself. A security descriptor in self-relative format contains the information in a contiguous block of memory. In a self-relative security descriptor, a SECURITY_DESCRIPTOR structure always starts the information, but the security descriptor's other components can follow the structure in any order. Instead of using memory addresses, the components of the self-relative security descriptor are identified by offsets from the beginning of the security descriptor. This format is useful when an security descriptor must be stored on a floppy disk or transmitted by means of a communications protocol.

A server that copies secured objects to various media can use the MakeAbsoluteSD function to create an absolute security descriptor from a self-relative security descriptor and the MakeSelfRelativeSD function to create a self-relative security descriptor from an absolute security descriptor.

See Also

MakeSelfRelativeSD, SECURITY_DESCRIPTOR


MakeDragList [New - Windows NT]
 MakeDragList  QuickInfo  Overview  Group

[New - Windows NT]

The MakeDragList function changes the specified single-selection list box to a drag list box.

BOOL MakeDragList(

HWND  hLB
);
Parameters

hLB

Handle to the single-selection list box.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.


MakeProcInstance
 MakeProcInstance  QuickInfo  Overview  Group

The MakeProcInstance function is obsolete. Win32 functions can be called directly.

This function is provided only for compatibility with 16-bit versions of Windows. Win32-based applications should not use this function.


MakeSelfRelativeSD
 MakeSelfRelativeSD  QuickInfo  Overview  Group

The MakeSelfRelativeSD function creates a security descriptor in self-relative format by using a security descriptor in absolute format as a template.

BOOL MakeSelfRelativeSD(

PSECURITY_DESCRIPTOR  pAbsoluteSecurityDescriptor,	// address of absolute SD
PSECURITY_DESCRIPTOR  pSelfRelativeSecurityDescriptor,	// address self-relative SD
LPDWORD  lpdwBufferLength	// address of SD size
);
Parameters

pAbsoluteSecurityDescriptor

Points to a SECURITY_DESCRIPTOR structure in absolute format. The function creates a version of this security descriptor in self-relative format without modifying the original.

pSelfRelativeSecurityDescriptor

Points to a buffer the function fills with a security descriptor in self-relative format.

lpdwBufferLength

Points to a variable specifying the size of the buffer pointed to by the pSelfRelativeSecurityDescriptor parameter. If the buffer is not large enough for the security descriptor, the function fails and sets this variable to the minimum required size.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

A security descriptor in absolute format contains pointers to the information it contains, rather than containing the information itself. A security descriptor in self-relative format contains the information in a contiguous block of memory. In a self-relative security descriptor, a SECURITY_DESCRIPTOR structure always starts the information, but the security descriptor's other components can follow the structure in any order. Instead of using memory addresses, the components of the security descriptor are identified by offsets from the beginning of the security descriptor. This format is useful when an security descriptor must be stored on a floppy disk or transmitted by means of a communications protocol.

A server that copies secured objects to various media can use the MakeSelfRelativeSD function to create a self-relative security descriptor from an absolute security descriptor and the MakeAbsoluteSD function to create an absolute security descriptor from a self-relative security descriptor.

See Also

MakeAbsoluteSD, SECURITY_DESCRIPTOR


MapDialogRect
 MapDialogRect  QuickInfo  Overview  Group

The MapDialogRect function converts (maps) the specified dialog box units to screen units (pixels). The function replaces the coordinates in the specified RECT structure with the converted coordinates, which allows the structure to be used to create a dialog box or position a control within a dialog box.

BOOL MapDialogRect(

HWND  hDlg,	// handle of dialog box
LPRECT  lpRect	// address of structure with rectangle
);
Parameters

hDlg

Identifies a dialog box. This function accepts only handles for dialog boxes created by one of the dialog box creation functions; handles for other windows are not valid.

lpRect

Points to a RECT structure that contains the dialog box coordinates to be converted.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

The MapDialogRect function assumes that the initial coordinates in the RECT structure represent dialog box units. To convert these coordinates from dialog box units to pixels, the function retrieves the current horizontal and vertical base units for the dialog box, then applies the following formulas:

left   = (left   * baseunitX) / 4

right  = (right  * baseunitX) / 4

top    = (top    * baseunitY) / 8

bottom = (bottom * baseunitY) / 8

In most cases, the base units for the dialog box are the same as those retrieved by using the GetDialogBaseUnits function. If the dialog box template has the DS_SETFONT style, however, the base units are the average width and height, in pixels, of the characters in the font given by the template.

See Also

CreateDialog, CreateDialogIndirect, CreateDialogIndirectParam, CreateDialogParam, DialogBox, DialogBoxIndirect, DialogBoxIndirectParam, DialogBoxParam, GetDialogBaseUnits, RECT


MapGenericMask
 MapGenericMask  QuickInfo  Overview  Group

The MapGenericMask function maps the generic access rights in an access mask to specific and standard access rights. The function applies a mapping supplied in a GENERIC_MAPPING structure.

VOID MapGenericMask(

PDWORD  AccessMask,	// address of access mask
PGENERIC_MAPPING  GenericMapping	// address of GENERIC_MAPPING structure
);
Parameters

AccessMask

Points to an access mask receiving the specific and standard rights mapped from generic access rights.

GenericMapping

Points to a GENERIC_MAPPING structure specifying a mapping of generic access types to specific and standard access types.

Return Value

This function does not return a value.

Remarks

After calling the MapGenericMask function, the access mask pointed to by the AccessMask parameter has none of its generic bits (GenericRead, GenericWrite, GenericExecute, or GenericAll) or undefined bits set, although it can have other bits set. If bits other than the generic bits are provided on input, this function does not clear them.

See Also

AccessCheck, AreAllAccessesGranted, AreAnyAccessesGranted, GENERIC_MAPPING


MapViewOfFile
 MapViewOfFile  QuickInfo  Overview  Group

The MapViewOfFile function maps a view of a file into the address space of the calling process.

LPVOID MapViewOfFile(

HANDLE  hFileMappingObject,	// file-mapping object to map into address space
DWORD  dwDesiredAccess,	// access mode
DWORD  dwFileOffsetHigh,	// high-order 32 bits of file offset
DWORD  dwFileOffsetLow,	// low-order 32 bits of file offset
DWORD  dwNumberOfBytesToMap	// number of bytes to map
);
Parameters

hFileMappingObject

Identifies an open handle of a file-mapping object. The CreateFileMapping and OpenFileMapping functions return this handle.

dwDesiredAccess

Specifies the type of access to the file view and, therefore, the protection of the pages mapped by the file. This parameter can be one of the following values:

Value	Meaning
FILE_MAP_WRITE	Read-write access. The hFileMappingObject parameter must have been created with PAGE_READWRITE protection. A read-write view of the file is mapped.
FILE_MAP_READ	Read-only access. The hFileMappingObject parameter must have been created with PAGE_READWRITE or PAGE_READ protection. A read-only view of the file is mapped.
FILE_MAP_ALL_ACCESS	Same as FILE_MAP_WRITE.
FILE_MAP_COPY	Copy on write access. If you create the map with PAGE_WRITECOPY and the view with FILE_MAP_COPY, you will receive a view to file. If you write to it, the pages are automatically swappable and the modifications you make will not go to the original data file. Windows 95: You must pass PAGE_WRITECOPY to CreateFileMapping; otherwise, an error will be returned. If you share the mapping between multiple processes using DuplicateHandle or OpenFileMapping and one process writes to a view, the modification is propagated to the other process. The original file does not change. Windows NT: There is no restriction as to how the hFileMappingObject parameter must be created. Copy on write is valid for any type of view.  If you share the mapping between multiple processes using DuplicateHandle or OpenFileMapping and one process writes to a view, the modification is not propagated to the other process. The original file does not change.
dwFileOffsetHigh

Specifies the high-order 32 bits of the file offset where mapping is to begin.

dwFileOffsetLow

Specifies the low-order 32 bits of the file offset where mapping is to begin. The combination of the high and low offsets must specify an offset within the file that matches the system's memory allocation granularity, or the function fails. That is, the offset must be a multiple of the allocation granularity. Use the GetSystemInfo function, which fills in the members of a SYSTEM_INFO structure, to obtain the system's memory allocation granularity.

dwNumberOfBytesToMap

Specifies the number of bytes of the file to map. If dwNumberOfBytesToMap is zero, the entire file is mapped.

Return Value

If the function succeeds, the return value is the starting address of the mapped view.

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

Remarks

Mapping a file makes the specified portion of the file visible in the address space of the calling process.

Multiple views of a file (or a file-mapping object and its mapped file) are said to be "coherent" if they contain identical data at a specified time. This occurs if the file views are derived from the same file-mapping object. A process can duplicate a file-mapping object handle into another process by using the DuplicateHandle function, or another process can open a file-mapping object by name by using the OpenFileMapping function.

A mapped view of a file is not guaranteed to be coherent with a file being accessed by the ReadFile or WriteFile function.

Windows 95 only: MapViewOfFile may require the swapfile to grow. If the swapfile cannot, MapViewOfFile fails.

See Also

CreateFileMapping, DuplicateHandle, GetSystemInfo, MapViewOfFileEx, OpenFileMapping, UnmapViewOfFile, SYSTEM_INFO


MapViewOfFileEx
 MapViewOfFileEx  QuickInfo  Overview  Group

The MapViewOfFileEx function maps a view of a file into the address space of the calling process. This extended function allows the calling process to specify a suggested memory address for the mapped view.

This function is available for Win32-based applications only.

LPVOID MapViewOfFileEx(

HANDLE  hFileMappingObject,	// file-mapping object to map into address space
DWORD  dwDesiredAccess,	// access mode
DWORD  dwFileOffsetHigh,	// high-order 32 bits of file offset
DWORD  dwFileOffsetLow,	// low-order 32 bits of file offset
DWORD  dwNumberOfBytesToMap,	// number of bytes to map
LPVOID  lpBaseAddress	// suggested starting address for mapped view
);
Parameters

hFileMappingObject

Identifies an open handle to a file-mapping object. The CreateFileMapping and OpenFileMapping functions return this handle.

dwDesiredAccess

Specifies the type of access to the file-mapping object and, therefore, the page protection of the pages mapped by the file. This parameter can be one of the following values:

Value	Meaning
FILE_MAP_WRITE	Read-and-write access. The hFileMappingObject parameter must have been created with PAGE_READWRITE protection. A read-write view of the file is mapped.
FILE_MAP_READ	Read-only access. The hFileMappingObject parameter must have been created with PAGE_READWRITE or PAGE_READ protection. A read-only view of the file is mapped.
FILE_MAP_ALL_ACCESS	Same as FILE_MAP_WRITE.
FILE_MAP_COPY	Copy on write access. If you create the map with PAGE_WRITECOPY and the view with FILE_MAP_COPY, you will reeive a view to file. If you write to it, the pages are automatically swappable and the modifications you make will not go to the original data file. Windows 95: You must pass PAGE_WRITECOPY to CreateFileMapping; otherwise, an error will be returned. If you share the mapping between multiple processes using DuplicateHandle or OpenFileMapping and one process writes to a view, the modification is propagated to the other process. The original file does not change. Windows NT: There is no restriction as to how the hFileMappingObject parameter must be created. Copy on write is valid for any type of view.  If you share the mapping between multiple processes using DuplicateHandle or OpenFileMapping and one process writes to a view, the modification is not propagated to the other process. The original file does not change.
dwFileOffsetHigh

Specifies the high-order 32 bits of the file offset where mapping is to begin.

dwFileOffsetLow

Specifies the low-order 32 bits of the file offset where mapping is to begin. The combination of the high and low offsets must specify an offset within the file that matches the system's memory allocation granularity, or the function fails. That is, the offset must be a multiple of the allocation granularity. Use the GetSystemInfo function, which fills in the members of a SYSTEM_INFO structure, to obtain the system's memory allocation granularity.

dwNumberOfBytesToMap

Specifies the number of bytes of the file to map. If dwNumberOfBytesToMap is zero, the entire file is mapped.

lpBaseAddress

Points to the memory address in the calling process's address space where mapping should begin. This must be a multiple of the system's memory allocation granularity, or the function fails. Use the GetSystemInfo function, which fills in the members of a SYSTEM_INFO structure, to obtain the system's memory allocation granularity. If there is not enough address space at the specified address, the function fails.

If lpBaseAddress is NULL, the operating system chooses the mapping address. In this case, this function is equivalent to the MapViewOfFile function.

Return Value

If the function succeeds, the return value is the starting address of the mapped view.

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

Remarks

Mapping a file makes the specified portion of the file visible in the address space of the calling process.

If a suggested mapping address is supplied, the file is mapped at the specified address (rounded down to the nearest 64K boundary) if there is enough address space at the specified address. If there is not, the function fails.

Typically, the suggested address is used to specify that a file should be mapped at the same address in multiple processes. This requires the region of address space to be available in all involved processes. No other memory allocation, including use of the VirtualAlloc function to reserve memory, can take place in the region used for mapping.

Windows 95: If the lpBaseAddress parameter specifies a base offset, the function succeeds only if the same memory region is available for the memory mapped file in all other 32-bit processes.

Windows NT: If the lpBaseAddress parameter specifies a base offset, the function succeeds if the given memory region is not already in use by the calling process. the system does not guarantee that the same memory region is available for the memory mapped file in other 32-bit processes.

Multiple views of a file (or a file-mapping object and its mapped file) are said to be "coherent" if they contain identical data at a specified time. This occurs if the file views are derived from the same file-mapping object. A process can duplicate a file-mapping object handle into another process by using the DuplicateHandle function, or another process can open a file-mapping object by name by using the OpenFileMapping function.

A mapped view of a file is not guaranteed to be coherent with a file being accessed by the ReadFile or WriteFile function.

See Also

CreateFileMapping, DuplicateHandle, GetSystemInfo, MapViewOfFile, OpenFileMapping, ReadFile, UnmapViewOfFile, SYSTEM_INFO, VirtualAlloc, WriteFile


MapVirtualKey
 MapVirtualKey  QuickInfo  Overview  Group

The MapVirtualKey function translates (maps) a virtual-key code into a scan code or character value, or translates a scan code into a virtual-key code.

UINT MapVirtualKey(

UINT  uCode,	// virtual-key code or scan code
UINT  uMapType	// translation to perform
);
Parameters

uCode

Specifies the virtual-key code or scan code for a key. How this value is interpreted depends on the value of the uMapType parameter.

uMapType

Specifies the translation to perform. The value of this parameter depends on the value of the uCode parameter:

Value	Meaning
0	uCode is a virtual-key code and is translated into a scan code. If it is a virtual-key code that does not distinguish between left- and right-hand keys, the left-hand scan code is returned. If there is no translation, the function returns 0.
1	uCode is a scan code and is translated into a virtual-key code that does not distinguish between left- and right-hand keys. If there is no translation, the function returns 0.
2	uCode is a virtual-key code and is translated into an unshifted character value in the low-order word of the return value. Dead keys (diacritics) are indicated by setting the top bit of the return value. If there is no translation, the function returns 0.
3	uCode is a scan code and is translated into a virtual-key code that distinguishes between left- and right-hand keys. If there is no translation, the function returns 0.
Return Value

The return value is either a scan code, a virtual-key code, or a character value, depending on the value of uCode and uMapType. If there is no translation, the return value is zero.

Remarks

An application can use MapVirtualKey to translate scan codes to the virtual-key code constants VK_SHIFT, VK_CONTROL, and VK_MENU, and vice versa. These translations do not distinguish between the left and right instances of the SHIFT, CTRL, or ALT keys. An application can get the scan code corresponding to the left or right instance of one of these keys by calling MapVirtualKey with uCode set to one of the following virtual-key code constants:

VK_LSHIFT	VK_RSHIFT
VK_LCONTROL	VK_RCONTROL
VK_LMENU	VK_RMENU
These left- and right-distinguishing constants are available to an application only through the GetKeyboardState, SetKeyboardState, GetAsyncKeyState, GetKeyState, and MapVirtualKey functions.

See Also

GetAsyncKeyState, GetKeyboardState, GetKeyState, SetKeyboardState


MapVirtualKeyEx [New - Windows 95]
 MapVirtualKeyEx  QuickInfo

[New - Windows 95]

The MapVirtualKeyEx function translates (maps) a virtual-key code into a scan code or character value, or translates a scan code into a virtual-key code. The function translates the codes using the input language and physical keyboard layout identified by the given keyboard layout handle.

UINT MapVirtualKeyEx(

UINT  uCode,	// virtual-key code or scan code
UINT  uMapType,	// translation to perform
HKL  dwhkl	// keyboard layout handle
);
Parameters

uCode

Specifies the virtual-key code or scan code for a key. How this value is interpreted depends on the value of the uMapType parameter.

uMapType

Specifies the translation to perform. The value of this parameter depends on the value of the uCode parameter:

Value	Meaning
0	uCode is a virtual-key code and is translated into a scan code. If it is a virtual-key code that does not distinguish between left- and right-hand keys, the left-hand scan code is returned. If there is no translation, the function returns 0.
1	uCode is a scan code and is translated into a virtual-key code that does not distinguish between left- and right-hand keys. If there is no translation, the function returns 0.
2	uCode is a virtual-key code and is translated into an unshifted character value in the low order word of the return value. Dead keys (diacritics) are indicated by setting the top bit of the return value. If there is no translation, the function returns 0.
3	uCode is a scan code and is translated into a virtual-key code that distinguishes between left- and right-hand keys. If there is no translation, the function returns 0.
dwhkl

Identifies the keyboard layout to use for translating the given code. This parameter can be any keyboard layout handle previously returned by the LoadKeyboardLayout function.

Return Value

The return value is either a scan code, a virtual-key code, or a character value, depending on the value of uCode and uMapType. If there is no translation, the return value is zero.

Remarks

An application can use MapVirtualKeyEx to translate scan codes to the virtual-key code constants VK_SHIFT, VK_CONTROL, and VK_MENU, and vice versa. These translations do not distinguish between the left and right instances of the SHIFT, CTRL, or ALT keys. An application can get the scan code corresponding to the left or right instance of one of these keys by calling MapVirtualKeyEx with uCode set to one of the following virtual-key code constants:

VK_LSHIFT	VK_RSHIFT
VK_LCONTROL	VK_RCONTROL
VK_LMENU	VK_RMENU
These left- and right-distinguishing constants are available to an application only through the GetKeyboardState, SetKeyboardState, GetAsyncKeyState, GetKeyState, MapVirtualKey, and MapVirtualKeyEx functions.

See Also

GetAsyncKeyState, GetKeyboardState, GetKeyState, LoadKeyboardLayout, MapVirtualKey, SetKeyboardState


MapWindowPoints
 MapWindowPoints  QuickInfo  Overview  Group

The MapWindowPoints function converts (maps) a set of points from a coordinate space relative to one window to a coordinate space relative to another window.

int MapWindowPoints(

HWND  hWndFrom,	// handle of window to be mapped from
HWND  hWndTo,	// handle of window to be mapped to
LPPOINT  lpPoints,	// address of structure array with points to map
UINT  cPoints	// number of structures in array
);
Parameters

hWndFrom

Identifies the window from which points are converted. If this parameter is NULL or HWND_DESKTOP, the points are presumed to be in screen coordinates.

hWndTo

Identifies the window to which points are converted. If this parameter is NULL or HWND_DESKTOP, the points are converted to screen coordinates.

lpPoints

Points to an array of POINT structures that contain the set of points to be converted. This parameter can also point to a RECT structure, in which case the cPoints parameter should be set to 2.

cPoints

Specifies the number of POINT structures in the array pointed to by the lpPoints parameter.

Return Value

If the function succeeds, the low-order word of the return value is the number of pixels added to the horizontal coordinate of each source point in order to compute the horizontal coordinate of each destination point; the high-order word is the number of pixels added to the vertical coordinate of each source point in order to compute the vertical coordinate of each destination point.

See Also

ClientToScreen, POINT, RECT, ScreenToClient


MaskBlt
 MaskBlt  QuickInfo  Overview  Group

The MaskBlt function combines the color data for the source and destination bitmaps using the specified mask and raster operation.

BOOL MaskBlt(

HDC  hdcDest,	// handle of destination device context
int  nXDest,	// x-coord. of upper-left corner of destination rectangle
int  nYDest,	// y-coord. of upper-left corner of destination rectangle
int  nWidth,	// width of source and destination rectangles
int  nHeight,	// height of source and destination rectangles
HDC  hdcSrc,	// handle of source device context
int  nXSrc,	// x-coord. of upper-left corner of source rectangle
int  nYSrc,	// y-coord. of upper-left corner of source rectangle
HBITMAP  hbmMask,	// handle of monochrome bit mask
int  xMask,	// horizontal pixel offset into the mask bitmap
int  yMask,	// vertical pixel offset into the mask bitmap
DWORD  dwRop	// raster operation code
);
Parameters

hdcDest

Identifies the destination device context.

nXDest

Specifies the logical x-coordinate of the upper-left corner of the destination rectangle.

nYDest

Specifies the logical y-coordinate of the upper-left corner of the destination rectangle.

nWidth

Specifies the width, in logical units, of the destination rectangle and source bitmap.

nHeight

Specifies the height, in logical units, of the destination rectangle and source bitmap.

hdcSrc

Identifies the device context from which the bitmap is to be copied. It must be zero if the dwRop parameter specifies a raster operation that does not include a source.

nXSrc

Specifies the logical x-coordinate of the upper-left corner of the source bitmap.

nYSrc

Specifies the logical y-coordinate of the upper-left corner of the source bitmap.

hbmMask

Identifies the monochrome mask bitmap combined with the color bitmap in the source device context.

xMask

Specifies the horizontal pixel offset for the mask bitmap specified by the hbmMask parameter.

yMask

Specifies the vertical pixel offset for the mask bitmap specified by the hbmMask parameter.

dwRop

Specifies both foreground and background ternary raster operation codes that the function uses to control the combination of source and destination data. The background raster operation code is stored in the high-order byte of the high-order word of this value; the foreground raster operation code is stored in the low-order byte of the high-order word of this value; the low-order word of this value is ignored, and should be zero. The macro MAKEROP4 creates such combinations of foreground and background raster operation codes.

For a discussion of foreground and background in the context of this function, see the following Remarks section.

For a list of common raster operation codes, see BitBlt .

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

A value of 1 in the mask specified by hbmMask indicates that the foreground raster operation code specified by dwRop should be applied at that location. A value of 0 in the mask indicates that the background raster operation code specified by dwRop should be applied at that location.

If the raster operations require a source, the mask rectangle must cover the source rectangle. If it does not, the function will fail. If the raster operations do not require a source, the mask rectangle must cover the destination rectangle. If it does not, the function will fail.

If a rotation or shear transformation is in effect for the source device context when this function is called, an error occurs. However, other types of transformation are allowed.

If the color formats of the source, pattern, and destination bitmaps differ, this function converts the pattern or source format, or both, to match the destination format.

If the mask bitmap is not a monochrome bitmap, an error occurs.

When an enhanced metafile is being recorded, an error occurs (and the function returns FALSE) if the source device context identifies an enhanced-metafile device context.

Not all devices support the MaskBlt function. An application should call the GetDeviceCaps function to determine whether a device supports this function.

If no mask bitmap is supplied, this function behaves exactly like BitBlt, using the foreground raster operation code.

The pixel offsets in the mask bitmap map to the point (0,0) in the source device context's bitmap. This is useful in cases where a mask bitmap contains a set of masks; an application can easily apply any one of them to a mask-block transfer task by adjusting the pixel offsets and rectangle sizes sent to MaskBlt.

See Also

BitBlt, GetDeviceCaps, PlgBlt, StretchBlt


MenuHelp [New - Windows NT]
 MenuHelp  QuickInfo  Overview  Group

[New - Windows NT]

The MenuHelp function processes WM_MENUSELECT and WM_COMMAND messages and displays help text about the current menu in the specified status window.

void MenuHelp(

UINT uMsg,
WPARAM wParam,
LPARAM lParam,
HMENU hMainMenu,
HINSTANCE hInst,
HWND hwndStatus,
UINT FAR * lpwIDs
);
Parameters

uMsg

WM_MENUSELECT or WM_COMMAND message.

wParam

First message parameter.

lParam

Second message parameter.

hMainMenu

Handle to the application's main menu.

hInst

Handle to the module that contains the string resources.

hwndStatus

Handle to the status window.

lpwIDs

Pointer to an array that contains pairs of string resource identifiers and menu handles. The function searches the array for the handle to the selected menu and, if found, uses the corresponding resource identifier to load the appropriate help string.

Return Value

This function does not return a value.

See Also

WM_COMMAND, WM_MENUSELECT


MenuItemFromPoint [New - Windows 95]
 MenuItemFromPoint  QuickInfo  Overview  Group

[New - Windows 95]

The MenuItemFromPoint function determines which menu item, if any, is at the specified location.

UINT WINAPI MenuItemFromPoint(

HWND  hWnd,
HMENU  hMenu,
POINT  ptScreen
);
Parameters

hWnd

Handle to the window containing the menu bar or pop-up menu.

hMenu

Handle to the menu containing the menu items to hit test.

ptScreen

POINT structure specifying the location to test. If hMenu specifies a menu bar, this parameter is in window coordinates. Otherwise, it is in client coordinates.

Return Value

Returns the zero-based position of the menu item at the specified location or −1 if no menu item is at the specified location.

See Also

POINT


MessageBeep
 MessageBeep  QuickInfo  Overview  Group

The MessageBeep function plays a waveform sound. The waveform sound for each sound type is identified by an entry in the [sounds] section of the registry.

BOOL MessageBeep(

UINT  uType	// sound type
);
Parameters

uType

Specifies the sound type, as identified by an entry in the [sounds] section of the registry. This parameter can be one of the following values:

Value	Sound
0xFFFFFFFF	Standard beep using the computer speaker
MB_ICONASTERISK	SystemAsterisk
MB_ICONEXCLAMATION	SystemExclamation
MB_ICONHAND	SystemHand
MB_ICONQUESTION	SystemQuestion
MB_OK	SystemDefault
Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

After queuing the sound, the MessageBeep function returns control to the calling function and plays the sound asynchronously.

If it cannot play the specified alert sound, MessageBeep attempts to play the system default sound. If it cannot play the system default sound, the function produces a standard beep sound through the computer speaker.

The user can disable the warning beep by using the Control Panel Sound application.

See Also

FlashWindow, MessageBox


MessageBox
 MessageBox  QuickInfo  Overview  Group

The MessageBox function creates, displays, and operates a message box. The message box contains an application-defined message and title, plus any combination of predefined icons and push buttons.

int MessageBox(

HWND  hWnd,	// handle of owner window
LPCTSTR  lpText,	// address of text in message box
LPCTSTR  lpCaption,	// address of title of message box
UINT  uType	// style of message box
);
Parameters

hWnd

Identifies the owner window of the message box to be created. If this parameter is NULL, the message box has no owner window.

lpText

Points to a null-terminated string containing the message to be displayed.

lpCaption

Points to a null-terminated string used for the dialog box title. If this parameter is NULL, the default title Error is used.

uType

Specifies the contents and behavior of the dialog box. This parameter can be a combination of the following values:

Value	Meaning
MB_ABORTRETRYIGNORE	The message box contains three push buttons: Abort, Retry, and Ignore.
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 applications 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 application. All child windows of the parent of the message box are automatically disabled, but popup windows are not.  MB_APPLMODAL is the default value if neither MB_SYSTEMMODAL nor MB_TASKMODAL is specified.
MB_DEFAULT_DESKTOP_ONLY	The desktop currently receiving input must be a default desktop; otherwise, the function fails. A default desktop is one an application runs on after the user has logged on.
MB_DEFBUTTON1	The first button is the default button. Note that the first button is always the default unless MB_DEFBUTTON2, MB_DEFBUTTON3, or MB_DEFBUTTON4 is specified.
MB_DEFBUTTON2	The second button is a default button.
MB_DEFBUTTON3	The third button is a default button.
MB_DEFBUTTON4	The fourth button is a default button.
MB_HELP	Windows 95: Adds a Help button to the message box. Choosing the Help button   or pressing F1 generates a Help event.
MB_ICONASTERISK	Same as MB_ICONINFORMATION.
MB_ICONERROR	Windows 95: Same as MB_ICONHAND.
MB_ICONEXCLAMATION	An exclamation-point icon appears in the message box.
MB_ICONHAND	Same as MB_ICONSTOP.
MB_ICONINFORMATION	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	A stop-sign icon appears in the message box.
MB_ICONWARNING	Windows 95: Same as MB_ICONEXCLAMATION.
MB_OK	The message box contains one push button: OK.
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_RIGHT	Windows 95: The text is right-justified.
MB_RTLREADING	Windows 95: Displays message and caption text using right-to-left reading order on Hebrew and Arabic systems.
MB_SERVICE_NOTIFICATION	Windows NT: The caller is a service notifying the user of an event. The function displays a message box on the current active desktop, even if there is no user logged on to the computer. If this flag is set, the hWnd parameter must be NULL. This is so the message box can appear on a desktop other than the desktop corresponding to the hWnd.
MB_SETFOREGROUND	The message box becomes the foreground window. Internally, Windows calls the SetForegroundWindow function for the message box.
MB_SYSTEMMODAL	All applications are suspended until the user responds to the message box. Unless the application specifies MB_ICONHAND, the message box does not become modal until after it is created; consequently, the owner window and other windows continue to receive messages resulting from its activation. Use system-modal message boxes to notify the user of serious, potentially damaging errors that require immediate attention (for example, running out of memory).
MB_TASKMODAL	Same as MB_APPLMODAL except that all the top-level windows belonging to the current task 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 current application without suspending other applications.
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.
Return Value

The return value is zero if there is not enough memory to create the message box.

If the function succeeds, the return value is one of the following menu-item values returned by the dialog box:

Value	Meaning
IDABORT	Abort button was selected.
IDCANCEL	Cancel button was selected.
IDIGNORE	Ignore button was selected.
IDNO	No button was selected.
IDOK	OK button was selected.
IDRETRY	Retry button was selected.
IDYES	Yes button was selected.
If a message box has a Cancel button, the function returns the IDCANCEL value if either the ESC key is pressed or the Cancel button is selected. If the message box has no Cancel button, pressing ESC has no effect.

Remarks

When you use a system-modal message box to indicate that the system is low on memory, the strings pointed to by the lpText and lpCaption parameters should not be taken from a resource file, because an attempt to load the resource may fail.

When an application calls MessageBox and specifies the MB_ICONHAND and MB_SYSTEMMODAL flags for the uType parameter, Windows displays the resulting message box regardless of available memory. When these flags are specified, Windows limits the length of the message box text to three lines. Windows does not automatically break the lines to fit in the message box, however, so the message string must contain carriage returns to break the lines at the appropriate places.

If you create a message box while a dialog box is present, use the handle of the dialog box as the hWnd parameter. The hWnd parameter should not identify a child window, such as a control in a dialog box.

Windows 95 only: The system can support a maximum of 16,364 window handles.

See Also

FlashWindow, MessageBeep, MessageBoxEx, SetForegroundWindow


MessageBoxEx
 MessageBoxEx  QuickInfo  Overview  Group

The MessageBoxEx function creates, displays, and operates a message box. The message box contains an application-defined message and title, plus any combination of predefined icons and push buttons. The wLanguageId parameter specifies which set of language resources is used for the predefined push buttons. For full descriptions of the other parameters of MessageBoxEx, see  MessageBox .

int MessageBoxEx(

HWND  hWnd,	// handle of owner window
LPCTSTR  lpText,	// address of text in message box
LPCTSTR  lpCaption,	// address of title of message box
UINT  uType,	// style of message box
WORD  wLanguageId	// language identifier
);
Parameters

hWnd

Identifies the owner window of the message box to be created. If this parameter is NULL, the message box has no owner window.

lpCaption

Points to a null-terminated string containing the message to be displayed.

lpszTitle

Points to a null-terminated string used for the dialog box title. If this parameter is NULL, the default title Error is used.

uType

Specifies the contents and behavior of the dialog box. This parameter can be a combination of the following values:

Value	Meaning
MB_ABORTRETRYIGNORE	The message box contains three push buttons: Abort, Retry, and Ignore.
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 applications and work in those windows. MB_APPLMODAL is the default if neither MB_SYSTEMMODAL nor MB_TASKMODAL is specified.
MB_DEFAULT_DESKTOP_ONLY	The desktop currently receiving input must be a default desktop; otherwise, the function fails. A default desktop is one an application runs on after the user has logged on.
MB_DEFBUTTON1	The first button is the default button. Note that the first button is always the default unless MB_DEFBUTTON2, MB_DEFBUTTON3, or MB_DEFBUTTON4 is specified.
MB_DEFBUTTON2	The second button is a default button.
MB_DEFBUTTON3	The third button is a default button.
MB_DEFBUTTON4	The fourth button is a default button.
MB_HELP	Windows 95: Adds a Help button to the message box. Choosing the Help button   or pressing F1 generates a Help event.
MB_ICONASTERISK	Same as MB_ICONINFORMATION.
MB_ICONERROR	Windows 95: Same as MB_ICONHAND.
MB_ICONEXCLAMATION	An exclamation-point icon appears in the message box.
MB_ICONHAND	Same as MB_ICONSTOP.
MB_ICONINFORMATION	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	A stop-sign icon appears in the message box.
MB_ICONWARNING	Windows 95: Same as MB_ICONEXCLAMATION.
MB_OK	The message box contains one push button: OK.
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_RIGHT	Windows 95: The text is right-justified.
MB_RTLREADING	Windows 95: Displays message and caption text using right-to-left reading order on Hebrew and Arabic systems.
MB_SERVICE_NOTIFICATION	Windows NT: The caller is a service notifying the user of an event. The function displays a message box on the current active desktop, even if there is no user logged on to the computer. If this flag is set, the hWnd parameter must be NULL. This is so the message box can appear on a desktop other than the desktop corresponding to the hWnd.
MB_SETFOREGROUND	The message box becomes the foreground window. Internally, Windows calls the SetForegroundWindow function for the message box.
MB_SYSTEMMODAL	All applications are suspended until the user responds to the message box. Unless the application specifies MB_ICONHAND, the message box does not become modal until after it is created; consequently, the owner window and other windows continue to receive messages resulting from its activation. Use system-modal message boxes to notify the user of serious, potentially damaging errors that require immediate attention (for example, running out of memory).
MB_TASKMODAL	Same as MB_APPLMODAL except that all the top-level windows belonging to the current task 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 current application without suspending other applications.
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.
wLanguageId

Specifies the language in which to display the text contained in the predefined push buttons. This value must be in the form returned by the MAKELANGID macro. For this release, the set of values is limited. For a list of the possible primary language identifiers and sublanguage identifiers, and a discussion of current language availability limitations, see the following Remarks section.

Return Value

If the function succeeds, the return value is a nonzero menu-item value returned by the dialog box.

Value	Meaning
IDABORT	Abort button was selected.
IDCANCEL	Cancel button was selected.
IDIGNORE	Ignore button was selected.
IDNO	No button was selected.
IDOK	OK button was selected.
IDRETRY	Retry button was selected.
IDYES	Yes button was selected.
If a message box has a Cancel button, the function returns the IDCANCEL value when either the ESC key or Cancel button is pressed. If the message box has no Cancel button, pressing the ESC key has no effect.

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

Remarks

When you create a system-modal message box to indicate that the system is low on memory, the strings passed as the lpText and lpCaption parameters should not be taken from a resource file, because an attempt to load the resource may fail.

When an application calls the MessageBoxEx function and specifies the MB_ICONHAND and MB_SYSTEMMODAL flags for the uType parameter, the Win32 API displays the resulting message box regardless of available memory. When you specify these flags, Windows limits the length of the message-box text to one line.

If you create a message box while a dialog box is present, use the handle of the dialog box as the hWnd parameter. The hWnd parameter should not identify a child window, such as a dialog box.

The table that follows shows the set of language identifiers and sublanguage identifiers, along with a description of each. Note that each localized release usually contains only resources for that language. 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. However, this may not apply in all cases. You should always enumerate the locales that are installed on a system before using an LCID, whether in this function or any other that requires an LCID.

Primary Language Identifiers and Sublanguage Identifiers

Primary language: LANG_ NEUTRAL
Sublanguage: SUBLANG_ DEFAULT
Description: Default sublanguage

Primary language: LANG_ ALBANIAN
Sublanguage: None
Description: Albanian

Primary language: LANG_ ARABIC
Sublanguage: None
Description: Arabic

Primary language: LANG_ BAHASA
Sublanguage: None
Description: Bahasa (Indonesian)

Primary language: LANG_ BULGARIAN
Sublanguage: None
Description: Bulgarian

Primary language: LANG_ CATALAN
Sublanguage: None
Description: Catalan

Primary language: LANG_ CHINESE
Sublanguage: SUBLANG_ CHINESE_SIMPLIFIED
Description: Simplified Chinese

Primary language: LANG_ CHINESE
Sublanguage: SUBLANG_ CHINESE_TRADITIONAL
Description: Traditional Chinese

Primary language: LANG_ CZECH
Sublanguage: None
Description: Czech

Primary language: LANG_ DANISH
Sublanguage: None
Description: Danish

Primary language: LANG_ DUTCH
Sublanguage: SUBLANG_ DUTCH
Description: Dutch

Primary language: LANG_ DUTCH
Sublanguage: SUBLANG_ DUTCH_BELGIAN
Description: Belgian Dutch

Primary language: LANG_ ENGLISH
Sublanguage: SUBLANG_ ENGLISH_AUS
Description: Australian English

Primary language: LANG_ ENGLISH
Sublanguage: SUBLANG_ ENGLISH_UK
Description: UK English

Primary language: LANG_ ENGLISH
Sublanguage: SUBLANG_ ENGLISH_US
Description: US English

Primary language: LANG_ FINNISH
Sublanguage: None
Description: Finnish

Primary language: LANG_ FRENCH
Sublanguage: SUBLANG_ FRENCH
Description: French

Primary language: LANG_ FRENCH
Sublanguage: SUBLANG_ FRENCH_BELGIAN
Description: Belgian French

Primary language: LANG_ FRENCH
Sublanguage: SUBLANG_ FRENCH_CANADIAN
Description: Canadian French

Primary language: LANG_ FRENCH
Sublanguage: SUBLANG_ FRENCH_SWISS
Description: Swiss French

Primary language: LANG_ GERMAN
Sublanguage: SUBLANG_ GERMAN
Description: German

Primary language: LANG_ GERMAN
Sublanguage: SUBLANG_ GERMAN_SWISS
Description: Swiss German

Primary language: LANG_ GREEK
Sublanguage: None
Description: Greek

Primary language: LANG_ HEBREW
Sublanguage: None
Description: Hebrew

Primary language: LANG_ HUNGARIAN
Sublanguage: None
Description: Hungarian

Primary language: LANG_ ICELANDIC
Sublanguage: None
Description: Icelandic

Primary language: LANG_ ITALIAN
Sublanguage: SUBLANG_ ITALIAN
Description: Italian

Primary language: LANG_ ITALIAN
Sublanguage: SUBLANG_ ITALIAN_SWISS
Description: Swiss Italian

Primary language: LANG_ JAPANESE
Sublanguage: None
Description: Japanese

Primary language: LANG_ KOREAN
Sublanguage: None
Description: Korean

Primary language: LANG_ NORWEGIAN
Sublanguage: SUBLANG_ NORWEGIAN_BOKMAL
Description: Norwegian − Bokmal

Primary language: LANG_ NORWEGIAN
Sublanguage: SUBLANG_ NORWEGIAN_NYNORSK
Description: Norwegian − Nynorsk

Primary language: LANG_ POLISH
Sublanguage: None
Description: Polish

Primary language: LANG_ PORTUGUESE
Sublanguage: SUBLANG_ PORTUGUESE
Description: Portuguese

Primary language: LANG_ PORTUGUESE
Sublanguage: SUBLANG_ PORTUGUESE_BRAZILIAN
Description: Brazilian Portuguese

Primary language: LANG_ RHAETO_ROMAN
Sublanguage: None
Description: Rhaeto-Romanic

Primary language: LANG_ ROMANIAN
Sublanguage: None
Description: Romanian

Primary language: LANG_ RUSSIAN
Sublanguage: None
Description: Russian

Primary language: LANG_ SERBO_CROATIAN
Sublanguage: SUBLANG_ SERBO_CROATIAN_CYRILLIC
Description: Serbo-Croatian (Cyrillic)

Primary language: LANG_ SERBO_CROATIAN
Sublanguage: SUBLANG_ SERBO_CROATIAN_LATIN
Description: Croato-Serbian (Latin)

Primary language: LANG_ SLOVAK
Sublanguage: None
Description: Slovak

Primary language: LANG_ SPANISH
Sublanguage: SUBLANG_ SPANISH
Description: Spanish

Primary language: LANG_ SPANISH
Sublanguage: SUBLANG_ SPANISH_MEXICAN
Description: Spanish Mexican

Primary language: LANG_ SWEDISH
Sublanguage: None
Description: Swedish

Primary language: LANG_ THAI
Sublanguage: None
Description: Thai

Primary language: LANG_ TURKISH
Sublanguage: None
Description: Turkish

Primary language: LANG_ URDU
Sublanguage: None
Description: Urdu

Windows 95 only: The system can support a maximum of 16,364 window handles.

See Also

MAKELANGID, MessageBeep, MessageBox, SetForegroundWindow


MessageBoxIndirect [New - Windows 95]
 MessageBoxIndirect  QuickInfo  Overview  Group

[New - Windows 95]

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.

BOOL API MessageBoxIndirect(

LPMSGBOXPARAMS lpMsgBoxParams	// address of structure for message box parameters
);
Parameters

lpMsgBoxParams

Points to a MSGBOXPARAMS structure that contains information used to display the message box.

Remarks

Windows 95 only: The system can support a maximum of 16,364 window handles.

See Also

MSGBOXPARAMS


MessageProc
 MessageProc  QuickInfo  Overview  Group

The MessageProc hook procedure is an application-defined callback function the system calls after an input event occurs in a dialog box, message box, menu, or scroll bar, but before the message generated by the input event is processed. The hook procedure can monitor messages for a dialog box, message box, menu, or scroll bar created by a particular application or all applications.

LRESULT CALLBACK MessageProc(

int  code,	// hook code
WPARAM  wParam,	// undefined
LPARAM  lParam	// address of structure with message data
);
Parameters

code

Specifies the type of input event that generated the message. This parameter can be one of the following values:

Value	Meaning
MSGF_DDEMGR	The input event occurred while the Dynamic Data Exchange Management Library (DDEML) was waiting for a synchronous transaction to finish. For more information about DDEML, see Dynamic Data Exchange Management Library
MSGF_DIALOGBOX	The input event occurred in a message box or dialog box.
MSGF_MENU	The input event occurred in a menu.
MSGF_NEXTWINDOW	The input event occurred as a result of the user's pressing the ALT+TAB key combination to activate a different window.
MSGF_SCROLLBAR	The input event occurred in a scroll bar.
If code is less than zero, the hook procedure must pass the message to the CallNextHookEx function without further processing and return the value returned by CallNextHookEx.

wParam

Specifies a NULL value.

lParam

Points to an MSG structure.

Return Value

If the hook procedure processes the message, the return value must be a nonzero value. Otherwise, it must be zero.

Remarks

An application installs the hook procedure by specifying the WH_MSGFILTER hook type and the address of the hook procedure in a call to the SetWindowsHookEx function.

If an application that uses the DDEML and performs synchronous transactions must process messages before they are dispatched, it must use the WH_MSGFILTER hook.

MessageProc is a placeholder for the application-defined function name.

See Also

CallNextHookEx, SetWindowsHookEx, MSG


midiInGetID
 midiInGetID  QuickInfo

The midiInGetID function gets the device identifier for a Musical Instrument Digital Interface (MIDI) input device.

MMRESULT midiInGetID(

HMIDIIN  hmi,	// identifier of MIDI input device to query
LPUINT  puDeviceID	// address of buffer for device identifier
);
Parameters

hmi

Identifies a handle of the MIDI input device.

puDeviceID

Points to a variable that will receive the device identifier.

Return Value

If the function succeeds, the return value is zero.

If the function fails, the return value is an error code that can be MMSYSERR_INVALHANDLE, indicating that the hmi parameter specifies an invalid handle.


midiOutGetID
 midiOutGetID  QuickInfo

The midiOutGetID function retrieves the device identifier for the specified Musical Instrument Digital Interface (MIDI) output device.

MMRESULT midiOutGetID(

HMIDIOUT  hmo,	// handle of device to return ID for
PUINT  puDeviceID	// address of buffer for device ID
);
Parameters

hmo

Identifies the MIDI output device.

puDeviceID

Points to a variable that will receive the the device identifier.

Return Value

If the function succeeds, the return value is zero.

If the function fails, the return value is an error code, which can be MMSYSERR_INVALHANDLE, indicating that the hmo parameter specifies an invalid handle.


MidiProc
 MidiProc  QuickInfo  Overview  Group

The MidiProc function is an application-defined callback function that processes Musical Instrument Digital Interface (MIDI) device messages. An application can specify the address of this function when it calls the midiInOpen or midiOutOpen function.

void CALLBACK MidiProc(

HMIDIIN  hMidiIn,	// handle of MIDI device
UINT  uMsg,	// MIDI message
DWORD  dwInstance,	// callback instance data
DWORD  dwParam1,	// application-defined parameter
DWORD  dwParam2	// application-defined parameter
);
Parameters

hMidiIn

Identifies the MIDI device.

uMsg

Specifies a MIDI message.

dwInstance

Specifies the instance data supplied by using the midiInOpen or midiOutOpen function.

dwParam1

Specifies a parameter for the message.

dwParam2

Specifies a parameter for the message.

Return Value

This function does not return a value.

Remarks

MidiProc is a placeholder for the application-defined function name.

There are several differences between MidiProc functions under Windows NT and under Windows 3.1 :

•	Under Windows 3.1, a MidiProc function is called at interrupt time. The call to a MidiProc function occurs on a separate thread under Windows NT.

•	Under Windows 3.1, a MidiProc function has to be in a dynamic link library. Under Windows NT, there is no such restriction.

•	Under Windows 3.1, a MidiProc function must be exported in a .DEF file. Under Windows NT, that is not necessary.

If source code must be compatible with Windows 3.1, it should follow the Windows 3.1 rules as noted briefly above and specified more fully in the Windows 3.1 documentation.

One other item should be noted carefully. There is a limited set of APIs that a Windows 3.1 MidiProc function may call. In Win32, that strict limitation has been removed. However, it is strongly recommended that a Windows NT MidiProc function restrain its calls to APIs in the same set, with the addition of the API SetEvent. Here is the Windows NT recommended list:

EnterCriticalSection	PostThreadMessage
LeaveCriticalSection	SetEvent
midiOutLongMsg	timeGetSystemTime
midiOutShortMsg	timeGetTime
OutputDebugString	timeKillEvent
PostMessage	timeSetEvent
If an application's MidiProc function does stray from this list, it should be careful not to call APIs that take a long time to complete.

If a Win32 MidiProc shares data with other code, a Critical Section or similar mutual exclusion mechanism should be used to protect the integrity of the data.

See Also

midiInOpen, midiOutOpen, TimeProc, WaveProc, MMIOProc


MMIOProc
 MMIOProc  QuickInfo  Overview  Group

An MMIOProc function is a custom input/output (I/O) procedure installed by the mmioInstallIOProc function. It is application-defined, and of type MMIOPROC.

LRESULT CALLBACK MMIOProc(

LPSTR  lpmmioinfo,	// address of structure with file information
UINT  uMsg,	// specifies sent message
LONG  lParam1,	// application-defined parameter
LONG  lParam2	// application-defined parameter
);
Parameters

lpmmioinfo

Points to an MMIOINFO structure containing information about the open file.

The I/O procedure must maintain the lDiskOffset member in this structure to indicate the file offset to the next read or write location. The I/O procedure can use the adwInfo[] member to store state information. The I/O procedure should not modify any other members of the MMIOINFO structure.

uMsg

Specifies a message indicating the requested I/O operation. Messages that can be received include MMIOM_OPEN, MMIOM_CLOSE, MMIOM_READ, MMIOM_SEEK, MMIOM_WRITE, and MMIOM_WRITEFLUSH.

lParam1

Specifies an application-defined parameter for the message.

lParam2

Specifies an application-defined parameter for the message.

Return Value

The return value depends on the message specified by uMsg. If the I/O procedure does not recognize a message, it should return zero.

Remarks

MMIOProc is a placeholder for the application-defined function name.

The four-character code specified by the fccMMIOProc member in the MMIOINFO structure associated with a file identifies a filename extension for a custom storage system. When an application calls mmioOpen with a filename such as "one.xyz+two", the I/O procedure associated with the four-character code "XYZ" is called to open the "two" element of the file "one.xyz".

The mmioInstallIOProc function maintains a separate list of installed I/O procedures for each Windows-based application. Therefore, different applications can use the same I/O procedure identifier for different I/O procedures without conflict. However, installing an I/O procedure globally enables any process to use the procedure.

If an application calls mmioInstallIOProc more than once to register the same I/O procedure, then it must call mmioInstallIOProc to remove the procedure once for each time it installed the procedure.

mmioInstallIOProc will not prevent an application from installing two different I/O procedures with the same identifier, or installing an I/O procedure with one of the predefined identifiers ("DOS ", "MEM "). The most recently installed procedure takes precedence, and the most recently installed procedure is the first one to be removed.

When searching for a specified I/O procedure, local procedures are searched first, then global procedures.

See Also

MMIOINFO, mmioInstallIOProc, MMIOM_OPEN, MMIOM_CLOSE, MMIOM_READ, MMIOM_SEEK, MMIOM_WRITE, MMIOM_WRITEFLUSH, mmioOpen


mmsystemGetVersion
 mmsystemGetVersion  QuickInfo  Overview  Group

The mmsystemGetVersion function is obsolete. It is provided only for compatibility with 16-bit versions of Windows. If it is necessary to obtain a version number, use the Win32 function GetVersionEx.


ModifyMenu
 ModifyMenu  QuickInfo  Overview  Group

The ModifyMenu function changes an existing menu item. This function is used to specify the content, appearance, and behavior of the menu item.

BOOL ModifyMenu(

HMENU hMnu,	// handle of menu
UINT uPosition,	// menu item to modify
UINT uFlags,	// menu item flags
UINT uIDNewItem,	// menu item identifier or pop-up menu handle
LPCTSTR lpNewItem	// menu item content
);
Parameters

hMnu

Identifies the menu to be changed.

uPosition

Specifies the menu item to be changed, as determined by the uFlags parameter.

uFlags

Specifies flags that control the interpretation of the uPosition parameter and the content, appearance, and behavior of the menu item. This parameter must be a combination of one of the following required values and at least one of the values listed in the following Remarks section.

Value	Meaning
MF_BYCOMMAND	Indicates that the uPosition parameter gives the identifier of the menu item. The MF_BYCOMMAND flag is the default if neither the MF_BYCOMMAND nor MF_BYPOSITION flag is specified.
MF_BYPOSITION	Indicates that the uPosition parameter gives the zero-based relative position of the menu item.
uIDNewItem

Specifies either the identifier of the modified menu item or, if uFlags is set to the MF_POPUP flag, the handle of the pop-up menu.

lpNewItem

Points to the content of the changed menu item. The interpretation of this parameter depends on whether the uFlags parameter includes the MF_BITMAP, MF_OWNERDRAW, or MF_STRING flag.

Value	Meaning
MF_BITMAP	Contains a bitmap handle.
MF_OWNERDRAW	Contains a 32-bit value supplied by an application that is used to maintain additional data related to the menu item. The value is in the itemData member of the structure pointed to by the lparam parameter of the WM_MEASUREITEM or WM_DRAWITEM messages sent when the menu item is created or its appearance is updated.
MF_STRING	Contains a pointer to a null-terminated string (the default).
Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

If ModifyMenu replaces a menu item that activates a pop-up menu, the function destroys the old pop-up menu and frees the memory used by it.

The application must call the DrawMenuBar function whenever a menu changes, whether or not the menu is in a displayed window. To change the attributes of existing menu items, it is much faster to use the CheckMenuItem and EnableMenuItem functions.

The following list describes the flags that may be set in the uFlags parameter:

Value	Meaning
MF_BITMAP	Uses a bitmap as the menu item. The lpNewItem parameter contains the handle of the bitmap.
MF_BYCOMMAND	Indicates that the uPosition parameter specifies the identifier of the menu item (the default).
MF_BYPOSITION	Indicates that the uPosition parameter specifies the zero-based relative position of the new menu item.
MF_CHECKED	Places a check mark next to the item. If your application provides check mark bitmaps (see the SetMenuItemBitmaps function), this flag displays a checked bitmap next to the menu item.
MF_DISABLED	Disables the menu item so that it cannot be selected, but this flag does not gray it.
MF_ENABLED	Enables the menu item so that it can be selected and restores it from its grayed state.
MF_GRAYED	Disables the menu item and grays it so that it cannot be selected.
MF_MENUBARBREAK	Functions the same as the MF_MENUBREAK flag, except for pop-up menus where the new column is separated from the old column by a vertical line.
MF_MENUBREAK	Places the item on a new line (for menu bars) or in a new column (for pop-up menus) 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 is a pop-up item; that is, selecting it activates a pop-up menu. The uIDNewItem parameter specifies the handle of the pop-up menu. This flag is used to add a pop-up item to a menu bar or to a pop-up menu.
MF_SEPARATOR	Draws a horizontal dividing line. This flag is used only in a pop-up menu. The dividing line cannot be grayed, disabled, or highlighted. The lpNewItem and uIDNewItem parameters are ignored.
MF_STRING	Specifies that the menu item is a text string; the lpNewItem parameter points to the string.
MF_UNCHECKED	Does not place a check mark next to the item (the default). If your application supplies check mark bitmaps (see the SetMenuItemBitmaps function), this flag displays an unchecked bitmap next to the menu item.
The following list shows groups of flags that cannot be used together:

•	MF_BYCOMMAND and MF_BYPOSITION

•	MF_DISABLED, MF_ENABLED, and MF_GRAYED

•	MF_BITMAP, MF_STRING, MF_OWNERDRAW, and MF_SEPARATOR

•	MF_MENUBARBREAK and MF_MENUBREAK

•	MF_CHECKED and MF_UNCHECKED

See Also

AppendMenu, CheckMenuItem, DrawMenuBar, EnableMenuItem, SetMenuItemBitmaps, WM_DRAWITEM, WM_MEASUREITEM


ModifyWorldTransform
 ModifyWorldTransform  QuickInfo  Overview  Group

The ModifyWorldTransform function changes the world transformation for a device context using the specified mode.

BOOL ModifyWorldTransform(

HDC  hdc,	// handle of device context
CONST XFORM *  lpXform,	// address of transformation data
DWORD  iMode	// modification mode
);
Parameters

hdc

Specifies the device context.

lpXform

Points to an XFORM structure used to modify the world transformation for the given device context.

iMode

Specifies how the transformation data modifies the current world transformation. This parameter must be one of the following values:

Value	Description
MWT_IDENTITY	Resets the current world transformation by using the identity matrix. If this mode is specified, the XFORM structure pointed to by lpXform is ignored.
MWT_LEFTMULTIPLY	Multiplies the current transformation by the data in the XFORM structure. (The data in the XFORM structure becomes the left multiplicand, and the data for the current transformation becomes the right multiplicand.)
MWT_RIGHTMULTIPLY	Multiplies the current transformation by the data in the XFORM structure. (The data in the XFORM structure becomes the right multiplicand, and the data for the current transformation becomes the left multiplicand.)
Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

The ModifyWorldTransform function will fail unless graphics mode for the specified device context has been set to GM_ADVANCED by previously calling the SetGraphicsMode function. Likewise, it will not be possible to reset the graphics mode for the device context to the default GM_COMPATIBLE mode, unless world transform has first been reset to the default identity transform by calling SetWorldTransform or ModifyWorldTransform.

See Also

GetWorldTransform, SetWorldTransform, SetGraphicsMode, XFORM


mouse_event
 mouse_event  QuickInfo  Overview  Group

The mouse_event function synthesizes mouse motion and button clicks.

VOID mouse_event(

DWORD  dwFlags,	// flags specifying various motion/click variants
DWORD  dx,	// horizontal mouse position or position change
DWORD  dy,	// vertical mouse position or position change
DWORD  cButtons,	// unused, reserved for future use, set to zero
DWORD  dwExtraInfo	// 32 bits of application-defined information
);
Parameters

dwFlags

A set of flag bits that specify various aspects of mouse motion and button clicking. The bits in this parameter can be any reasonable combination of the following values:

Value	Meaning
MOUSEEVENTF_ABSOLUTE	Specifies that the dx and dy parameters contain normalized absolute coordinates. If not set, those parameters contain relative data: the change in position since the last reported position. This flag can be set, or not set, regardless of what kind of mouse or mouse-like device, if any, is connected to the system. For further information about relative mouse motion, see the following Remarks section.
MOUSEEVENTF_MOVE	Specifies that movement occurred.
MOUSEEVENTF_LEFTDOWN	Specifies that the left button changed to down.
MOUSEEVENTF_LEFTUP	Specifies that the left button changed to up.
MOUSEEVENTF_RIGHTDOWN	Specifies that the right button changed to down.
MOUSEEVENTF_RIGHTUP	Specifies that the right button changed to up.
MOUSEEVENTF_MIDDLEDOWN	Specifies that the middle button changed to down.
MOUSEEVENTF_MIDDLEUP	Specifies that the middle button changed to up.
The flag bits 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.

dx

Specifies the mouse's absolute position along the x-axis or its amount of motion since the last mouse event was generated, depending on the setting of MOUSEEVENTF_ABSOLUTE. Absolute data is given as the mouse's actual x-coordinate; relative data is given as the number of mickeys moved.

dy

Specifies the mouse's absolute position along the y-axis or its amount of motion since the last mouse event was generated, depending on the setting of MOUSEEVENTF_ABSOLUTE. Absolute data is given as the mouse's actual y-coordinate; relative data is given as the number of mickeys moved.

cButtons

This parameter is currently unused. It is reserved for future use. It must be set to zero.

dwExtraInfo

Specifies an additional 32-bit value associated with the mouse event. An application calls GetMessageExtraInfo to obtain this extra information.

Return Value

This function has no return value.

Remarks

If the mouse has moved, indicated by MOUSEEVENTF_MOVE being set, dx and dy hold information about that motion. The information is given as absolute or relative integer values.

If MOUSEEVENTF_ABSOLUTE value is specified, dx and dy contain normalized absolute coordinates between 0 and 65,535. The event procedure maps these coordinates onto the display surface. Coordinate (0,0) maps onto the upper-left corner of the display surface, (65535,65535) maps onto the lower-right corner.

If the MOUSEEVENTF_ABSOLUTE value is not specified, dx and dy specify relative motions from when the last mouse event was generated (the last reported position). Positive values mean the mouse moved right (or down); negative values mean the mouse moved left (or up).

Relative mouse motion is subject to the effects of the mouse speed and the two mouse threshold values. An end user sets these three values with the Mouse Tracking Speed slider of Control Panel's Mouse option. An application obtains and sets these values with the SystemParametersInfo function. The operating system applies two tests to the specified relative mouse motion. If the specified distance along either the x or y axis is greater than the first mouse threshold value, and the mouse speed is not zero, the operating system doubles the distance. If the specified distance along either the x or y axis is greater than the second mouse threshold value, and the mouse speed is equal to two, the operating system doubles the distance that resulted from applying the first threshold test. It is thus possible for the operating system to multiply relatively-specified mouse motion along the x or y axis by up to four times.

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.

See Also

GetMessageExtraInfo, SystemParametersInfo


MouseProc
 MouseProc  QuickInfo  Overview  Group

The MouseProc hook procedure is an application-defined or library-defined callback function the system calls whenever an application calls the GetMessage or PeekMessage function and there is a mouse message to be processed.

LRESULT CALLBACK MouseProc(

int  nCode,	// hook code
WPARAM  wParam,	// message identifier
LPARAM  lParam	// mouse coordinates
);
Parameters

nCode

Specifies a code the hook procedure uses to determine how to process the message. This parameter can be one of the following values:

Value	Meaning
HC_ACTION	The wParam and lParam parameters contain information about a mouse message.
HC_NOREMOVE	The wParam and lParam parameters contain information about a mouse message, and the mouse message has not been removed from the message queue. (An application called the PeekMessage function, specifying the PM_NOREMOVE flag.)
If nCode is less than zero, the hook procedure must pass the message to the CallNextHookEx function without further processing and should return the value returned by CallNextHookEx.

wParam

Specifies the identifier of the mouse message.

lParam

Points to a MOUSEHOOKSTRUCT structure.

Return Value

To enable the system to process the message, the return value must be zero. To discard the message, the return value must be a nonzero value.

Remarks

The hook procedure must not install a JournalPlaybackProc callback function.

An application installs the hook procedure by specifying the WH_MOUSE hook type and the address of the hook procedure in a call to the SetWindowsHookEx function.

MouseProc is a placeholder for the application-defined or library-defined function name.

See Also

CallNextHookEx, GetMessage, JournalPlaybackProc, MOUSEHOOKSTRUCT, PeekMessage, SetWindowsHookEx


MoveFile
 MoveFile  QuickInfo  Overview  Group

The MoveFile function renames an existing file or a directory (including all its children).

BOOL MoveFile(

LPCTSTR  lpExistingFileName,	// address of name of the existing file
LPCTSTR  lpNewFileName	// address of new name for the file
);
Parameters

lpExistingFileName

Points to a null-terminated string that names an existing file or directory.

lpNewFileName

Points to a null-terminated string that specifies the new name of a file or directory. The new name must not already exist. A new file may be on a different file system or drive. A new directory must be on the same drive.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The MoveFile function will move (rename) either a file or a directory (including all its children) either in the same directory or across directories. The one caveat is that the MoveFile function will fail on directory moves when the destination is on a different volume.

See Also

CopyFile, MoveFileEx


MoveFileEx
 MoveFileEx  QuickInfo  Overview  Group

The MoveFileEx function renames an existing file.

BOOL MoveFileEx(

LPCTSTR  lpExistingFileName,	// address of name of the existing file
LPCTSTR  lpNewFileName,	// address of new name for the file
DWORD  dwFlags	// flag to determine how to move file
);
Parameters

lpExistingFileName

Points to a null-terminated string that names an existing file.

lpNewFileName

Points to a null-terminated string that specifies the new name of lpExistingFileName. When moving a file, the destination can be on a different file system or drive. When moving a directory, the destination must be on the same drive. If dwFlags specifies both MOVEFILE_REPLACE_EXISTING and MOVEFILE_DELAY_UNTIL_REBOOT, lpNewFileName can be NULL. In this case, the function registers the lpExistingFileName file to be deleted when the system reboots.

dwFlags

A set of bit flags that specify how to move the file. You can specify any combination of the following values:

Value	Meaning
MOVEFILE_REPLACE_EXISTING
	If a file of the name specified by lpNewFileName already exists, the function replaces its contents with those specified by lpExistingFileName.
MOVEFILE_COPY_ALLOWED
	If the file is to be moved to a different volume, the function simulates the move by using the CopyFile and DeleteFile functions. Cannot be combined with the MOVEFILE_DELAY_UNTIL_REBOOT flag.
MOVEFILE_DELAY_UNTIL_REBOOT
	Windows NT only: The function does not move the file until the operating system is restarted. The system moves the file immediately after AUTOCHK is executed, but before creating any paging files. Consequently, this parameter enables the function to delete paging files from previous startups.
Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

An application cannot specify both MOVEFILE_DELAY_UNTIL_REBOOT and MOVEFILE_COPY_ALLOWED for dwFlags. Function calls that do so will fail.

Windows NT only: If the dwFlags parameter specifies MOVEFILE_REPLACE_EXISTING and MOVEFILE_DELAY_UNTIL_REBOOT, the function stores entries under the following registry key:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\
Session Manager\FileRenameOperations

The system uses these registry entries to complete the operation at reboot.

See Also

CopyFile, DeleteFile, MoveFile


MoveMemory
 MoveMemory  QuickInfo  Overview  Group

The MoveMemory function moves a block of memory from one location to another.

VOID MoveMemory (

PVOID  Destination,	// address of move destination
CONST VOID *  Source,	// address of block to move
DWORD  Length	// size, in bytes, of block to move
);
Parameters

Destination

Points to the starting address of the destination of the move.

Source

Points to the starting address of the block of memory to move.

Length

Specifies the size, in bytes, of the block of memory to move.

Return Value

This function has no return value.

Remarks

The source and destination blocks may overlap.

See Also

CopyMemory, FillMemory, ZeroMemory


 MoveTo

The MoveTo function is not implemented in the Win32 API. Win32-based applications should use the MoveToEx function.


MoveToEx
 MoveToEx  QuickInfo  Overview  Group

The MoveToEx function updates the current position to the specified point and optionally returns the previous position.

BOOL MoveToEx(

HDC  hdc,	// handle of device context
int  X,	// x-coordinate of new current position
int  Y,	// y-coordinate of new current position
LPPOINT  lpPoint	// address of old current position
);
Parameters

hdc

Identifies a device context.

X

Specifies the x-coordinate of the new position, in logical units.

Y

Specifies the y-coordinate of the new position, in logical units.

lpPoint

Points to a POINT structure in which the previous current position is stored. If this parameter is a NULL pointer, the previous position is not returned.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

The MoveToEx function affects all drawing functions.

See Also

AngleArc, LineTo, POINT, PolyBezierTo, PolylineTo


MoveWindow
 MoveWindow  QuickInfo  Overview  Group

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 of window
int  X,	// horizontal position
int  Y,	// vertical position
int  nWidth,	// width
int  nHeight,	// height
BOOL  bRepaint	// repaint flag
);
Parameters

hWnd

Identifies the window.

X

Specifies the new position of the left side of the window.

Y

Specifies the new position of the top of the window.

nWidth

Specifies the new width of the window.

nHeight

Specifies the new height of the window.

bRepaint

Specifies whether the window is to be repainted. If this parameter is TRUE, the window receives a WM_PAINT message. If the parameter is FALSE, no repainting of any kind occurs. This applies to the client area, the nonclient area (including the title bar and scroll bars), and any part of the parent window uncovered as a result of moving a child window. If this parameter is FALSE, the application must explicitly invalidate or redraw any parts of the window and parent window that need redrawing.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

If the bRepaint parameter is TRUE, Windows 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, Windows places the WM_PAINT message in the message queue associated with the window. The message loop dispatches the WM_PAINT message only after dispatching all other messages in the queue.

MoveWindow sends WM_WINDOWPOSCHANGING, WM_WINDOWPOSCHANGED, WM_MOVE, WM_SIZE, and WM_NCCALCSIZE messages to the window.

See Also

SetWindowPos, UpdateWindow, WM_GETMINMAXINFO, WM_PAINT


MsgWaitForMultipleObjects
 MsgWaitForMultipleObjects  QuickInfo  Overview  Group

The MsgWaitForMultipleObjects function returns when one of the following occurs:

•	Either any one or all of the specified objects are in the signaled state.

•	A specified type of input becomes available in the thread's input queue.

•	The time-out interval elapses.

Note that MsgWaitForMultipleObjects doesn't return if there was previously unread input of the specified type in the queue. It only wakes up when input arrives.

DWORD MsgWaitForMultipleObjects(

DWORD  nCount,	// number of handles in handle array
LPHANDLE  pHandles,	// address of object-handle array
BOOL  fWaitAll,	// wait for all or wait for one
DWORD  dwMilliseconds,	// time-out interval in milliseconds
DWORD  dwWakeMask	// type of input events to wait for
);
Parameters

nCount

Specifies the number of object handles in the array pointed to by pHandles. The maximum number of object handles is MAXIMUM_WAIT_OBJECTS minus one.

pHandles

Points to an array of object handles. For a list of the object types whose handles can be specified, see the following Remarks section. The array can contain handles of objects of different types.

Windows NT: The handles must have SYNCHRONIZE access.

fWaitAll

Specifies the wait type. If TRUE, the function returns when all objects in the pHandles array are signaled at the same time. If FALSE, the function returns when any one of the objects is signaled. In the latter case, the return value indicates the object whose state caused the function to return.

dwMilliseconds

Specifies the time-out interval, in milliseconds. The function returns if the interval elapses, even if the conditions specified by the fWaitAll or dwWakeMask parameter are not satisfied. If dwMilliseconds is zero, the function tests the states of the specified objects and returns immediately. If dwMilliseconds is INFINITE, the function's time-out interval never elapses.

dwWakeMask

Specifies the types of input that will cause the function to return. This parameter can be any combination of the following values:

Value	Meaning
QS_ALLINPUT	Any message is in the queue.
QS_HOTKEY	A WM_HOTKEY message is in the queue.
QS_INPUT	An input message is in the queue.
QS_KEY	A WM_KEYUP, WM_KEYDOWN, WM_SYSKEYUP, or WM_SYSKEYDOWN message is in the queue.
QS_MOUSE	A WM_MOUSEMOVE message or mouse-button message (WM_LBUTTONUP, WM_RBUTTONDOWN, and so on).
QS_MOUSEBUTTON	A mouse-button message (WM_LBUTTONUP, WM_RBUTTONDOWN, and so on).
QS_MOUSEMOVE	A WM_MOUSEMOVE message is in the queue.
QS_PAINT	A WM_PAINT message is in the queue.
QS_POSTMESSAGE	A posted message (other than those just listed) is in the queue.
QS_SENDMESSAGE	A message sent by another thread or application is in the queue.
QS_TIMER	A WM_TIMER message is in the queue.
Return Value

If the function succeeds, the return value indicates the event that caused the function to return. The successful return value is one of the following:

Value	Meaning
WAIT_OBJECT_0 to (WAIT_OBJECT_0 + nCount − 1)	If fWaitAll is TRUE, the return value indicates that the state of all specified objects is signaled. If fWaitAll is FALSE, the return value minus WAIT_OBJECT_0 indicates the pHandles array index of the object that satisfied the wait.
WAIT_OBJECT_0 + nCount	Input of the type specified in the dwWakeMask parameter is available in the thread's input queue.
WAIT_ABANDONED_0 to (WAIT_ABANDONED_0 + nCount − 1)	If fWaitAll is TRUE, the return value indicates that the state of all specified objects is signaled and at least one of the objects is an abandoned mutex object. If fWaitAll is FALSE, the return value minus WAIT_ABANDONED_0 indicates the pHandles array index of an abandoned mutex object that satisfied the wait.
WAIT_TIMEOUT	The time-out interval elapsed and the conditions specified by the fWaitAll and dwWakeMask parameters were not satisfied.
If the function fails, the return valueis 0xFFFFFFFF. To get extended error information, call GetLastError.

Remarks

The MsgWaitForMultipleObjects function determines whether the conditions exist that satisfy the wait. If the wait is not satisfied, the calling thread enters an efficient wait state, using very little processor time while waiting for one of the conditions of the wait to be satisfied.

When fWaitAll is TRUE, the function's wait condition is satisfied only when the state of all objects is signaled at the same time. The function does not modify the state of the specified objects until all objects are simultaneously signaled. For example, a mutex can be signaled, but the thread does not get ownership until the other objects are also signaled. In the meantime, some other thread may get ownership of the mutex, thereby delaying satisfaction of the condition.

The system adjusts the state of some types of objects after the object's signaled state satisfies a wait condition. For example, the count of a semaphore object is decreased by one.

The MsgWaitForMultipleObjects function can specify handles of any of the following object types in the pHandles array:

Object	Description
Change notification	The handle is returned by the FindFirstChangeNotification function. A change notification object's state is signaled when a specified type of change occurs within a specified directory or directory tree.
Console input	The handle is returned by the CreateFile function when CONIN$ is specified, or by the GetStdHandle function. The object's state is signaled when there is unread input in the console's input buffer and it is nonsignaled when the input buffer is empty.
Event	The handle is returned by the CreateEvent or OpenEvent function. An event object's state is set explicitly to signaled by the SetEvent or PulseEvent function. A manual-reset event object's state must be reset explicitly to nonsignaled by the ResetEvent function. For an auto-reset event object, the wait function resets the object's state to nonsignaled before returning. Event objects are also used in overlapped operations, in which the state is set by the system.
Mutex	The handle is returned by the CreateMutex or OpenMutex function. A mutex object's state is signaled when it is not owned by any thread. The wait function requests ownership of the mutex for the calling thread, changing the mutex's state to nonsignaled when ownership is granted.
Process	The handle is returned by the CreateProcess or OpenProcess function. A process object's state is signaled when the process terminates.
Thread	The handle is returned by the CreateProcess, CreateThread, or CreateRemoteThread function. A thread object's state is signaled when the thread terminates.
Semaphore	The handle is returned by the CreateSemaphore or OpenSemaphore function. A semaphore object maintains a count between zero and some maximum value. Its state is signaled when its count is greater than zero and nonsignaled when its count is zero. If the current state is signaled, the wait function decreases the count by one.
In some circumstances, you can specify a handle of a file, named pipe, or communications device as a synchronization object in a wait function. However, their use for this purpose is discouraged. For more information, see Synchronization.

The following code fragment illustrates the use of MsgWaitForMultipleObjects in a main message loop that also needs to wait for one or more objects to become signaled.

int MessageLoop (

  HANDLE* lphObjects,  // handles that need to be waited on

  int     cObjects     // number of handles to wait on

  ){

  // message loop lasts until we get a WM_QUIT message

  // upon which we shall return from the function

  while (TRUE) {

    // block-local variable

    DWORD result ;

    // wait for any message sent or posted to this queue

    // or for one of the passed handles to become signaled

      result = MsgWaitForMultipleObjects(cObjects, lphObjects,

                                 FALSE, INFINITE, QS_ALLINPUT);

      // result tells us the type of event we have:

      // a message or a signaled handle

      // if there are one or more messages in the queue ...

      if (result == (WAIT_OBJECT_0 + cObjects)) {

         // block-local variable

         MSG msg ;

         // read all of the messages in this next loop

         // removing each message as we read it

         while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {

            // if it's a quit message we're out of here

            if (msg.message == WM_QUIT)  return 1;

            // otherwise dispatch it

            DispatchMessage(&msg);

         } // end of PeekMessage while loop

      } else {

         // one of the handles became signaled

         // deal with that

         DoStuff (result - WAIT_OBJECT_0) ;

      } // end of else-clause

   } // end of the always while-loop

} // end of function

See Also

CreateEvent, CreateFile, CreateMutex, CreateProcess, CreateRemoteThread, CreateSemaphore, CreateThread, FindFirstChangeNotification, GetStdHandle, OpenEvent, OpenMutex, OpenProcess, OpenSemaphore, PulseEvent, ResetEvent, SetEvent, Sleep, WaitForMultipleObjects, WaitForMultipleObjectsEx, WaitForSingleObject


MulDiv
 MulDiv  QuickInfo  Overview  Group

The MulDiv function multiplies two 32-bit values and then divides the 64-bit result by a third 32-bit value. The return value is rounded up or down to the nearest integer.

int MulDiv(

int  nNumber,	// 32-bit signed multiplicand
int  nNumerator,	// 32-bit signed multiplier
int  nDenominator	// 32-bit signed divisor
);
Parameters

nNumber

Specifies the multiplicand.

nNumerator

Specifies the multiplier.

nDenominator

Specifies the number by which the result of the multiplication (nNumber * nNumerator) is to be divided.

Return Value

If the function succeeds, the return value is the result of the multiplication and division. If either an overflow occurred or nDenominator was 0, the return value is −1.

See Also

Int32x32To64, UInt32x32To64


MultiByteToWideChar
 MultiByteToWideChar  QuickInfo  Overview  Group

The MultiByteToWideChar function maps a character string to a wide-character (Unicode) string. The character string mapped by this function is not necessarily from a multibyte character set.

int MultiByteToWideChar(

UINT  CodePage,	// code page
DWORD  dwFlags,	// character-type options
LPCSTR  lpMultiByteStr,	// address of string to map
int  cchMultiByte,	// number of characters in string
LPWSTR  lpWideCharStr,	// address of wide-character buffer
int  cchWideChar	// size of buffer
);
Parameters

CodePage

Specifies the code page to be used to perform the conversion. This parameter can be given the value of any codepage that is installed or available in the system. The following values may be used to specify one of the system default code pages:

Value	Meaning
CP_ACP	ANSI code page
CP_MACCP	Macintosh code page
CP_OEMCP	OEM code page
dwFlags

A set of bit flags that indicate whether to translate to precomposed or composite wide characters (if a composite form exists), whether to use glyph characters in place of control characters, and how to deal with invalid characters. You can specify a combination of the following flag constants:

Value	Meaning
MB_PRECOMPOSED	Always use precomposed characters — that is, characters in which a base character and a nonspacing character have a single character value. This is the default translation option. Cannot be used with MB_COMPOSITE.
MB_COMPOSITE	Always use composite characters — that is, characters in which a base character and a nonspacing character have different character values. Cannot be used with MB_PRECOMPOSED.
MB_ERR_INVALID_CHARS	If the function encounters an invalid input character, it fails and GetLastError returns ERROR_NO_UNICODE_TRANSLATION.
MB_USEGLYPHCHARS	Use glyph characters instead of control characters.
A composite character consists of a base character and a nonspacing character, each having different character values. A precomposed character has a single character value for a base/non-spacing character combination. In the character è, the e is the base character and the accent grave mark is the nonspacing character.

The function's default behavior is to translate to the precomposed form. If a precomposed form does not exist, the function attempts to translate to a composite form.

The flags MB_PRECOMPOSED and MB_COMPOSITE are mutually exclusive. The MB_USEGLYPHCHARS flag and the MB_ERR_INVALID_CHARS can be set regardless of the state of the other flags.

lpMultiByteStr

Points to the character string to be converted.

cchMultiByte

Specifies the size in bytes of the string pointed to by the lpMultiByteStr parameter. If this value is −1, the string is assumed to be null terminated and the length is calculated automatically.

lpWideCharStr

Points to a buffer that receives the translated string.

cchWideChar

Specifies the size, in wide characters, of the buffer pointed to by the lpWideCharStr parameter. If this value is zero, the function returns the required buffer size, in wide characters, and makes no use of the lpWideCharStr buffer.

Return Value

If the function succeeds, and cchWideChar is nonzero, the return value is the number of wide characters written to the buffer pointed to by lpWideCharStr.

If the function succeeds, and cchWideChar is zero, the return value is the required size, in wide characters, for a buffer that can receive the translated string.

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

ERROR_NO_UNICODE_TRANSLATION

Remarks

The lpMultiByteStr and lpWideCharStr pointers must not be the same. If they are the same, the function fails, and GetLastError returns the value ERROR_INVALID_PARAMETER.

The function fails if MB_ERR_INVALID_CHARS is set and it encounters an invalid character in the source string.  An invalid character is one that would translate to the default character if MB_ERR_INVALID_CHARS was not set, but is not the default character in the source string, or when a lead byte is found in a string and there is no valid trail byte for DBCS strings. When an invalid character is found, and MB_ERR_INVALID_CHARS is set, the function returns 0 and sets GetLastError with the error ERROR_NO_UNICODE_TRANSLATION.

See Also

WideCharToMultiByte


NDdeGetErrorString
 NDdeGetErrorString  QuickInfo  Overview  Group

The NDdeGetErrorString function is called to convert an error code returned by the NetDDE DSDM interface API into an error string explaining the reason for the returned error.

UINT NDdeGetErrorString (

UINT  uErrorCode,	// Error code to get string for
LPTSTR  lpszErrorString,	// buffer to hold error string
DWORD  cBufSize	// size of buffer
);
Parameters

uErrorCode

Error code to be converted.

lpszErrorString

Address of a buffer to accept the translated error string. Must not be NULL. If the buffer is not large enough to store the complete error string, the string will be truncated.

cBufSize

Defines the size of the buffer allocated to receive the error string.

Return Value

If the function succeeds, the return value is zero.

If the function fails, the return value is a nonzero error code. If the lpszErrorString buffer is not large enough to accept the complete error string, and the string is truncated, the function returns the value NDDE_BUF_TOO_SMALL.


NDdeGetShareSecurity
 NDdeGetShareSecurity  QuickInfo  Overview  Group

The NDdeGetShareSecurity function is called to get the SECURITY_DESCRIPTOR associated with the DDE share. This is done usually for editing.

UINT NDdeGetShareSecurity(

LPTSTR  lpszServer,	// server to execute on
LPTSTR  lpszShareName,	// name of share to delete
SECURITY_INFORMATION  si,	// requested information
PSECURITY_DESCRIPTOR  pSD,	// address of SD buffer
DWORD  cbSD,	// size of SD buffer
LPDWORD  lpcbsdRequired	// address of required size for SD buffer
);
Parameters

lpszServer

Address of the server name on which the DSDM will be modified.

lpszShareName

Address of the share name whose security descriptor is to be retrieved from the DSDM. This parameter should not be NULL.

si

Identifies the SECURITY_INFORMATION to be retrieved from the SECURITY_DESCRIPTOR associated with the share.

pSD

Address of a buffer that will accept the retrieved self-relative SECURITY_DESCRIPTOR. This parameter can be NULL. If this parameter is NULL, the DSDM determines the size of the requested security information and returns the number of bytes needed in the lpcbsdRequired parameter along with the NDDE_BUF_TOO_SMALL error code.

cbSD

Specifies the size of the buffer provided and referenced by the pSD parameter to accept the retrieved security descriptor. It must be 0 if pSD is NULL.

lpcbsdRequired

Address of the variable into which the actual size of the retrieved security descriptor is stored. Must not be NULL.

Return Value

If the function succeeds, the return value is NDDE_NO_ERROR.

If the function fails, the return value is an error code, which can be translated into a text error message by calling NDdeGetErrorString. If the pSD parameter was NULL, it returns NDDE_BUF_TOO_SMALL.

See Also

SECURITY_INFORMATION


NDdeGetTrustedShare
 NDdeGetTrustedShare  QuickInfo  Overview  Group

The NDdeGetTrustedShare function is called to retrieve the options associated with a currently "trusted" DDE share.

UINT NDdeGetTrustedShare (

LPTSTR  lpszServer,	// server to execute on
LPTSTR  lpszShareName,	// name of share to query
LPDWORD  lpdwTrustOptions,	// trust options in effect
LPDWORD  lpdwShareModId0,	// first word of share modify identifier
LPDWORD  lpdwShareModId1	// second word of share modify identifier
);
Parameters

lpszServer

Address of the server name on which the DSDM will be modified.

lpszShareName

Address of the share name whose trusted status is being queried. This parameter should not be NULL.

lpdwTrustOptions

Address of a variable into which the TRUST_SHARE_OPTIONS will be stored. Must not be NULL.

lpdwShareModId0

Address of a variable into which the first word of the trusted share modify identifier will be stored. Must not be NULL.

lpdwShareModId1

Address of a variable into which the second word of the trusted share modify identifier will be stored. Must not be NULL.

Return Value

If the function succeeds, the return value is NDDE_NO_ERROR.

If the function fails, the return value is an error code, which can be translated into a text error message by calling NDdeGetErrorString.

Remarks

The trusted share modify identifier reflects the version of the DDE share in the NetDDE DSDM at the time the DDE share was initially promoted to trust status. The trusted share modify identifier is primarily used to purge obsolete trusted shares. However, the user does not need to purge obsolete trusted shares. The NetDDE Agent purges obsolete shares on the user's behalf.


NDdeIsValidAppTopicList
 NDdeIsValidAppTopicList  QuickInfo  Overview  Group

The NDdeIsValidAppTopicList function is called to validate an application and topic string ("AppName|TopicName") for proper syntax.

BOOL NDdeIsValidAppTopicList (

LPTSTR targetTopic	// points to app and topic string
);
Parameters

targetTopic

Address of the application and topic string  to validate. Must not be NULL.

Return Value

If targetTopic has valid syntax, the return value is TRUE.

If the function fails, the return value is FALSE.


NDdeIsValidShareName
 NDdeIsValidShareName  QuickInfo  Overview  Group

The NDdeIsValidShareName function is called to validate a share name for proper syntax.

BOOL NDdeIsValidShareName (

LPTSTR  shareName	// points to share name to validate
);
Parameters

shareName

Address of a share name to validate. Must not be NULL.

Return Value

If the share name has valid syntax, the return value is TRUE.

If the function fails, the return value is FALSE.


NDdeSetShareSecurity
 NDdeSetShareSecurity  QuickInfo  Overview  Group

The NDdeSetShareSecurity function is called to set the SECURITY_DESCRIPTOR associated with the DDE share. This is done usually after editing the DACL assigned to the DDE share.

UINT NDdeSetShareSecurity(

LPTSTR  lpszServer,	// server to execute on
LPTSTR  lpszShareName,	// name of share to delete
SECURITY_INFORMATION  si,	// type of information
PSECURITY_DESCRIPTOR  pSD	// address of security descriptor to set
);
Parameters

lpszServer

Address of the server name on which the DSDM will be modified.

lpszShareName

Address of the share name whose security descriptor is to be modified in the DSDM. This parameter should not be NULL.

si

Specifies a SECURITY_INFORMATION structure identifying the contents of the security descriptor pointed to by the pSD parameter.

pSD

Address of the SECURITY_DESCRIPTOR that will be the source of the security information modified in the DDE share. This parameter must not be NULL and should point to a valid security descriptor.

Return Value

If the function succeeds, the return value is NDDE_NO_ERROR.

If the function fails, the return value is an error code, which can be translated into a text error message by calling NDdeGetErrorString.

Remarks

To modify the SECURITY_DESCRIPTOR associated with a DDE share in the DSDM, the user must have appropriate privileges; for example, the share creator has such rights.

See Also

SECURITY_INFORMATION


NDdeSetTrustedShare
 NDdeSetTrustedShare  QuickInfo  Overview  Group

The NDdeSetTrustedShare function is called to promote the referenced DDE share to trusted status within the current user's context.

UINT NDdeSetTrustedShare (

LPTSTR  lpszServer,	// server to execute on
LPTSTR  lpszShareName,	// name of share to delete
DWORD  dwTrustOptions	// trust options to apply
);
Parameters

lpszServer

Address of the server name on which the DSDM will be modified.

lpszShareName

Address of the share name being promoted to trusted status. This parameter should not be NULL.

dwTrustOptions

Specifies the options affecting the trusted status of the DDE share. The following TRUST_SHARE_OPTIONS options are available:

Option	Meaning
NDDE_TRUST_SHARE_START	Allow the application to be started in the user's context.
NDDE_TRUST_SHARE_INIT	Allow a client to initiate to the application if it is already running in the user's context.
NDDE_TRUST_SHARE_DEL	Remove the share's trusted status.
NDDE_TRUST_CMD_SHOW	Start the application with CmdShow field defined here overriding the CmdShow specified in the DDE share DSDM.
NDDE_CMD_SHOW_MASK	CmdShow value used to override the DDE share CmdShow if the NDDE_TRUST_CMD_SHOW is set.
Return Value

If the function succeeds, the return value is NDDE_NO_ERROR.

If the function fails, the return value is an error code, which can be translated into a text error message by calling NDdeGetErrorString.

Remarks

If NDdeSetTrustedShare is called with dwTrustOptions set to 0, the trusted share loses its trusted status.


NDdeShareAdd
 NDdeShareAdd  QuickInfo  Overview  Group

The NDdeShareAdd function is called to create and add a new DDE share to the NetDDE Share Database Manager (DSDM).

UINT NDdeShareAdd (

LPTSTR  lpszServer,	// server to execute on
UINT  nLevel,	// info level must be 2
PSECURITY_DESCRIPTOR  pSD,	// initial security descriptor
LPBYTE  lpBuffer,	// address of NDDESHAREINFO
DWORD  cBufSize	// size of supplied buffer
);
Parameters

lpszServer

Address of the server name on which the DSDM will be modified.

nLevel

Must always be 2.

pSD

Address of the SECURITY_DESCRIPTOR that will be associated with this share and against which access checks will be performed on subsequent initiates to this share. This parameter can optionally be NULL, in which case the DSDM creates a default SECURITY_DESCRIPTOR that grants "Full Control" to the CREATOR_OWNER and "Read and Link" to everyone.

lpBuffer

Address of the NDDESHAREINFO structure that defines the ApplicationTopic list associated with the DDE share being created as well as other parameters. This parameter must not be NULL.

cBufSize

Size of the structure identified by lpBuffer. It must not be 0.

Return Value

If the function succeeds, the return value is NDDE_NO_ERROR.

If the function fails, the return value is an error code, which can be translated into a text error message by calling NDdeGetErrorString.

See Also

NDDESHAREINFO


NDdeShareDel
 NDdeShareDel  QuickInfo  Overview  Group

The NDdeShareDel function is called to delete a DDE share from the NetDDE DSDM.

UINT NDdeShareDel (

LPTSTR  lpszServer,	// server to execute on
LPTSTR  lpszShareName,	// name of share to delete
UINT  wReserved	// must be 0
);
Parameters

lpszServer

Address of the server name on which the DSDM will be modified.

lpszShareName

Address of the share name that is to be deleted from the DSDM. This parameter should not be NULL.

wReserved

Must be 0.

Return Value

If the function succeeds, the return value is NDDE_NO_ERROR.

If the function fails, the return value is an error code which can be translated into a text error message by calling NDdeGetErrorString.

Remarks

To delete a DDE share from the DSDM, the user must have appropriate privileges. The share creator has delete rights.


NDdeShareEnum
 NDdeShareEnum  QuickInfo  Overview  Group

The NDdeShareEnum function is called to list the available DDE shares in the NetDDE DSDM.

UINT NDdeShareEnum (

LPTSTR  lpszServer,	// server to execute on
UINT  nLevel,	// must be 0
LPBYTE  lpBuffer,	// pointer to buffer
DWORD  cBufSize,	// size of buffer
LPDWORD  lpnEntriesRead,	// number of names returned
LPDWORD  lpcbTotalAvailable	// number of bytes available
);
Parameters

lpszServer

Address of the server name on which the DSDM will be modified.

nLevel

Must be 0.

lpBuffer

Address of a buffer supplied to accept the list of DDE shares. The list of DDE shares is stored as a sequence of null-separated strings terminating with a double null at the end. This parameter can be NULL. If lpBuffer is NULL, the DSDM returns the size of buffer required to hold the list of shares in the lpcbTotalAvailable field.

cBufSize

Specifies the size of the supplied buffer addressed by lpBuffer. Must be 0 if lpBuffer is NULL.

lpnEntriesRead

Address of a variable to receive the total number of shares being enumerated. Must not be NULL.

lpcbTotalAvailable

Address of a variable to receive the total number of bytes needed in the buffer to store the list of DDE shares. Must not be NULL.

Return Value

If the function succeeds, the return value is NDDE_NO_ERROR.

If the function fails, the return value is an error code, which can be translated into a text error message by calling NDdeGetErrorString. If the lpBuffer parameter is NULL, it returns NDDE_BUF_TOO_SMALL.


NDdeShareGetInfo
 NDdeShareGetInfo  QuickInfo  Overview  Group

The NDdeShareGetInfo function is called to retrieve DDE share information from the NetDDE DSDM. This is usually done for editing.

UINT NDdeShareGetInfo (

LPTSTR  lpszServer,	// server to execute on
LPTSTR  lpszShareName,	// name of share
UINT  nLevel,	// info level must be 2
LPBYTE  lpBuffer,	// contains (NDDESHAREINFO) + data
DWORD  cBufSize,	// size of buffer
LPDWORD  lpnTotalAvailable,	// number of bytes available
LPWORD  lpnItems	// item mask for partial getinfo
);
Parameters

lpszServer

Address of the server name on which the DSDM will be modified.

lpszShareName

Address of the share name whose information is to be retrieved from the DSDM. This parameter should not be NULL.

nLevel

Must be 2.

lpBuffer

Address of a buffer that is to accept the NDDESHAREINFO structure and associated data pointed to by NDDESHAREINFO pointer fields. This field can be NULL. If lpBuffer is NULL, then the DSDM calculates the number of bytes required to store the requested share information and returns that value in the lpnTotalAvailable field along with the NDDE_BUF_TOO_SMALL error.

cBufSize

Defines the size of the buffer addressed by the lpBuffer field. If lpBuffer is NULL, then cBufSize should be 0.

lpnTotalAvailable

Address of a varaible that receives the count of the total number of bytes needed to store the requested share information. Must not be NULL.

lpnItems

Address of an item selection mask for partial share information retrieval. For the first release of Windows NT, the item selection mask must be 0.

Return Value

If the function succeeds, the return value is NDDE_NO_ERROR.

If the function fails, the return value is an error code, which can be translated into a text error message by calling NDdeGetErrorString. If the lpBuffer parameter is NULL, it returns NDDE_BUF_TOO_SMALL.

See Also

NDDESHAREINFO structure


NDdeShareSetInfo
 NDdeShareSetInfo  QuickInfo  Overview  Group

The NDdeShareSetInfo function is called to modify DDE share information stored in the NetDDE DSDM. This is usually done after editing.

UINT NDdeShareSetInfo (

LPTSTR  lpszServer,	// server to execute on
LPTSTR  lpszShareName,	// name of share
UINT  nLevel,	// information level must be 2
LPBYTE  lpBuffer,	// address of NDDESHAREINFO
DWORD  cBufSize,	// size of buffer
WORD  sParmNum	// parameter index
);
Parameters

lpszServer

Address of the server name on which the DSDM will be modified.

lpszShareName

Address of the share name whose information is to be modified in the DSDM. This parameter should not be NULL.

nLevel

Must be 2.

lpBuffer

Address of the NDDESHAREINFO structure that defines the new DDE share information to be stored in the DSDM. Currently the DDE share information is modified as a whole, that is, no partial edits are made. Must not be NULL.

cBufSize

Size of the DDE share information addressed by lpBuffer.

sParmNum

Parameter index being modified. Current implementation does not support partial modification and, hence, it must be 0.

Return Value

If the function succeeds, the return value is NDDE_NO_ERROR.

If the function fails, the return value is an error code, which can be translated into a text error message by calling NDdeGetErrorString.

See Also

NDDESHAREINFO


NDdeTrustedShareEnum
 NDdeTrustedShareEnum  QuickInfo  Overview  Group

The NDdeTrustedShareEnumfunction lists the names of all network DDE shares that are trusted in the context of the calling process.

UINT NDdeTrustedShareEnum (

LPTSTR  lpszServer,	// server to execute on
UINT  nLevel,	// must be 0
LPBYTE  lpBuffer,	// pointer to buffer
DWORD  cBufSize,	// size of buffer
LPDWORD  lpnEntriesRead,	// number of names returned
LPDWORD  lpcbTotalAvailable	// number of bytes available
);
Parameters

lpszServer

Address of the server name on which the DSDM will be modified.

nLevel

Must be 0.

lpBuffer

Address of a buffer supplied to accept the list of trusted DDE shares. The list of trusted DDE shares is stored as a sequence of null-separated strings terminating with a double null at the end. This parameter can be NULL. If the lpBuffer is NULL, the DSDM returns the size of buffer required to hold the list of shares in the lpcbTotalAvailable field.

cBufSize

Specifies the size of the supplied buffer addressed by lpBuffer. Must be 0 if lpBuffer is NULL.

lpnEntriesRead

Address of a variable to receive the total number of trusted shares being enumerated. Must not be NULL.

lpcbTotalAvailable

Address of a variable to receive the total number of bytes needed in the buffer to store the list of trusted DDE shares. Must not be NULL.

Return Value

If the function succeeds, the return value is NDDE_NO_ERROR.

If the function fails, the return value is an error code, which can be translated into a text error message by calling NDdeGetErrorString. If the lpBuffer parameter is NULL, it returns NDDE_BUF_TOO_SMALL.


NetAccessAdd
 NetAccessAdd  QuickInfo

Note  The NetAccessAdd function works only when remoted to a downlevel system. Use Win32 (GetFileSecurity, SetFileSecurity) functions for Windows NT.

NetAccessAdd creates a new Access Control List (ACL) for a resource.

Security Requirements

Admin group membership is required to successfully execute NetAccessAdd.

NET_API_STATUS
NetAccessAdd (

LPTSTR servername,
DWORD level,
LPBYTE buf,
LPDWORD parm_err
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

level

Level of information provided. Must be 1.

buf

A pointer to a buffer containing the access information structure.

parm_err

Optional pointer to a DWORD to return the index of the first parameter in error when ERROR_INVALID_PARAMETER is returned. If NULL the parameter is not returned on error.


NetAccessCheck
 NetAccessCheck  QuickInfo

Note  The NetAccessCheck function works only when remoted to a downlevel system. Use Win32 (AccessCheck) function for Windows NT.

NetAccessCheck verifies that a user has permission to perform a specified operation on a particular resource.

Security Requirements

Admin group membership is required to successfully execute NetAccessCheck.

NET_API_STATUS
NetAccessCheck (

LPWSTR servername,
LPWSTR username,
LPWSTR resource,
DWORD operation,
LPDWORD result
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

username

A pointer to a Unicode string containing the name of the user to check for access to the resource.

resource

A pointer to a Unicode string containing the resource for which to check user permissions.

operation

Points to a DWORD specifying the type of access operation requested.

Symbolic constant	Value	Meaning
ACCESS_READ	0x01	Permission to read data from a resource and, by default, execute the resource.
ACCESS_WRITE	0x02	Permission to write data to the resource.
ACCESS_CREATE	0x04	Permission to create an instance of the resource (for example, a file); data can be written to the resource when creating it.
ACCESS_EXEC	0x08	Permission to execute the resource.
ACCESS_DELETE	0x10	Permission to delete the resource.
ACCESS_ATRIB	0x20	Permission to modify the resource's attributes (for example, the date and time a file was last modified).
ACCESS_PERM	0x40	Permission to modify the permissions (read, write, create, execute, and delete) assigned to a resource for a user, group, or application.
ACCESS_ALL	0x7F	Permission to read, write, create,execute, or delete a resource, or to modify attributes or permissions in which the user permissions for the specified resource are returned.
result

Points to a DWORD in which the result of the access check is returned.


NetAccessDel
 NetAccessDel  QuickInfo

Note  The NetAccessDel function works only when remoted to a downlevel system. Use Win32 (GetFileSecurity, SetFileSecurity) functions for Windows NT.

NetAccessDel deletes the access control list for a particular resource.

Security Requirements

Admin group membership or P permission for the resource is required to successfully execute NetAccessDel.

NET_API_STATUS
NetAccessDel (

LPTSTR servername,
LPTSTR resource
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

resource

A pointer to a Unicode string containing the name of the resource for which to remove the access control entry.


NetAccessEnum
 NetAccessEnum  QuickInfo

Note  The NetAccessEnum function works only when remoted to a downlevel system. Use Win32 (GetFileSecurity, SetFileSecurity) functions for Windows NT.

NetAccessEnum retrieves information about each access permision record.

NetAccessEnum is being phased out and is available only at levels 0 and 1 for Windows networking. It is recommended that NetAccessEnum not be used because it is unlikely to be supported in future releases.

Security Requirements

NetAccessEnum does not require admin group membership to execute but will return only records for entries for which the user has 'P' permission if the caller does not have admin group membership.

NET_API_STATUS
NetAccessEnum (

LPTSTR servername,
LPTSTR BasePath,
DWORD Recursive,
DWORD level,
LPBYTE * bufptr,
DWORD prefmaxlen,
LPDWORD entriesread,
LPDWORD totalentries,
LPDWORD resume_handle
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

BasePath

A pointer to a Unicode string that contains a base path for the resources. A NULL pointer or NULL string means no base path is to be used. The path can be specified as a universal naming convention (UNC) path.

Recursive

A flag to enables or disable recursive searching. If Recursive is 0, NetAccessEnum returns entries only for the resource named as the base path by BasePath and for the resources directly below that base path. If Recursive is nonzero, NetAccessEnum returns entries for all access control lists (ACLs) that have BasePath at the beginning of the resource name.

level

Level of information required. Only 0 and 1 are valid.

bufptr

On return a pointer to the return information structure is returned in the address pointed to by bufptr.

prefmaxlen

Preferred maximum length of returned data (in 8-bit bytes).

entriesread

On return the actual enumerated element count is located in the DWORD pointed to by entriesread.

totalentries

On return the total number of entries that could have been enumerated from the current resume position is located in the DWORD pointed to by totalentries.

resume_handle

On return, a resume handle is stored in the DWORD pointed to by resume_handle, and is used to continue an existing access search. The handle should be zero on the first call and left unchanged for subsequent calls. If resume_handle is NULL, then no resume handle is stored.


NetAccessGetInfo
 NetAccessGetInfo  QuickInfo

Note  The NetAccessGetInfo function works only when remoted to a downlevel system. Use Win32 (GetFileSecurity, SetFileSecurity) functions for Windows NT.

NetAccessGetInfo retrieves the access control information for a specific resource.

Security Requirements

Admin group membership or P permission is required to successfully execute NetAccessGetInfo.

NET_API_STATUS
NetAccessGetInfo (

LPTSTR servername,
LPTSTR resource,
DWORD level,
LPBYTE * bufptr
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

resource

A pointer to a Unicode string containing the name of the resource on which to return access control information.

level

Level of information required. 0 and 1 are valid.

bufptr

A pointer to the return information structure is returned in the address pointed to by bufptr.


NetAccessGetUserPerms
 NetAccessGetUserPerms  QuickInfo

Note  The NetAccessGetUserPerms function works only when remoted to a downlevel system. Use Win32 (GetFileSecurity, SetFileSecurity) functions for Windows NT.

NetAccessGetUserPerms returns a specified user's or group's access permissions for a particular resource.

Security Requirements

Admin group membership or P permission for the resource is required to successfully execute NetAccessGetUserPerms.except when users request their own access permissions to a resource. In this case no special group membership is required.

NET_API_STATUS
NetAccessGetUserPerms (

LPTSTR servername,
LPTSTR UGname,
LPTSTR resource,
LPDWORD Perms
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

UGname

A pointer to a Unicode string containing the name of the user or group to query permissions for.

resource

A pointer to a Unicode string containing the resource for which to query user permissions.

Perms

Points to a DWORD in which the user permissions for the specified resource are returned.


NetAccessSetInfo
 NetAccessSetInfo  QuickInfo

Note  The NetAccessSetInfo functions works only when remoted to a downlevel system. Use Win32 (GetFileSecurity, SetFileSecurity) functions for Windows NT.

NetAccessSetInfo changes the access control list for a resource.

Security Requirements

Admin group membership or P permission for the resource is required to successfully execute NetAccessSetInfo.

NET_API_STATUS
NetAccessSetInfo (

LPTSTR servername,
LPTSTR resource,
DWORD level,
LPBYTE buf,
LPDWORD parm_err
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

resource

A pointer to a Unicode string containing the name of the resource for which the access information should be changed.

level

Level of information to set. Only 1 and 1002 are valid.

buf

A pointer to a buffer containing the access entry information.

parm_err

Optional pointer to a DWORD to return the index of the first parameter in error when ERROR_INVALID_PARAMETER is returned. If NULL the parameter is not returned on error.


NetAlertRaise
 NetAlertRaise  QuickInfo

NetAlertRaise notifies all registered clients that a particular event occurred.

Security Requirements

No special group membership is required to successfully execute NetAlertRaise.

NET_API_STATUS
NetAlertRaise (

LPTSTR AlertEventName,
LPVOID Buffer,
DWORD BufferSize
);
Parameters

AlertEventName

Points to a Unicode string that specifies which type of alert to raise.

Buffer

Points to the data to be sent to the clients listening for this alert. The data should consist of the STD_ALERT data structure followed by any additional alert data.

BufferSize

Specifies the size of the buffer in bytes.


NetAlertRaiseEx
 NetAlertRaiseEx  QuickInfo

NetAlertRaiseEx simplifies the raising of an admin alert.

Security Requirements

No special group membership is required to successfully execute NetAlertRaiseEx.

NET_API_STATUS
NetAlertRaiseEx (

LPTSTR AlertEventName,
LPVOID VariableInfo,
DWORD VariableInfoSize,
LPTSTR ServiceName
);
Parameters

AlertEventName

Points to a Unicode string that specifies which type of alert to raise.

VariableInfo

Information to put into the admin alert.

VariableInfoSize

Number of bytes of variable information.

ServiceName

Name of the service raising the admin alert.


NetApiBufferAllocate
 NetApiBufferAllocate  QuickInfo

NetApiBufferAllocate allocates ByteCount bytes of memory from the heap.

NET_API_STATUS
NetApiBufferAllocate (

DWORD ByteCount,
LPVOID * Buffer
);
Parameters

ByteCount

The number of bytes to allocate.

buffer

A pointer to the location to store the pointer to the allocated buffer.


NetApiBufferFree
 NetApiBufferFree  QuickInfo

NetApiBufferFree frees the memory allocated by NetApiBufferAllocate.

NET_API_STATUS
NetApiBufferFree (

LPVOID Buffer
);
Parameters

Buffer

A pointer to an API information buffer previously returned on an function call.


NetApiBufferReallocate
 NetApiBufferReallocate  QuickInfo

NetApiBufferReallocate changes the size of a buffer allocated with NetApiBufferAllocate.

NET_API_STATUS
NetApiBufferReallocate (

LPVOID OldBuffer,
DWORD NewByteCount,
LPVOID NewBuffer
);
Parameters

OldBuffer

A pointer to the buffer to reallocate.

NewByteCount

The new size of the buffer.

NewBuffer

A pointer to an API information buffer previously returned on an function call.


NetApiBufferSize
 NetApiBufferSize  QuickInfo

NetApiBufferSize returns the size in bytes of the buffer allocated via NetApiBufferAllocate.

NET_API_STATUS
NetApiBufferSize (

LPVOID buffer,
DWORD ByteCount
);
Parameters

buffer

A pointer to an API information buffer previously returned on an function call.

ByteCount

The size of the buffer.


NetAuditClear
 NetAuditClear  QuickInfo

NetAuditClear clears the audit log on a server and, optionally, saves the entries in a backup file.

Security Requirements

Admin group membership is required to successfully execute NetAuditClear.

NET_API_STATUS
NetAuditClear (

LPTSTR server,
LPTSTR backupfile ,
LPTSTR service
);
Parameters

server

Points to a Unicode string that contains the name of the server on which to execute NetAuditClear. A NULL pointer or NULL string specifies the local computer.

backupfile

Points to a Unicode string that contains a name for the optional backup file. The calling application must have create and write permissions for the path specified by backupfile, and the path must already exist. A NULL pointer specifies not to back up the audit log.

service

Points to a Unicode string that contains the name of the service that owns the desired audit log to which the operation is to be performed.


NetAuditRead
 NetAuditRead  QuickInfo

NetAuditRead reads from the audit log on a server.

Security Requirements

Admin or accounts, comm, print, or server operator group membership is required to successfully execute NetAuditRead.

NET_API_STATUS
NetAuditRead (

LPTSTR server,
LPTSTR service,
LPHLOG auditloghandle,
DWORD offset,
LPDWORD reserved1,
DWORD reserved2,
DWORD offsetflag,
LPBYTE * bufptr,
DWORD prefmaxlen,
LPDWORD bytesread,
LPDWORD totalavailable
);
Parameters

server

Points to a Unicode string that contains the name of the server on which to execute NetAuditRead. A NULL pointer or NULL string specifies the local computer.

service

Points to a Unicode string that contains the name of the service that owns the desired audit log to which the operation is to be performed.

auditloghandle

Points to the handle for the audit log. An application calling NetAuditRead for the first time must initialize the audit log handle as follows. The most significant bit (MSB) is the leftmost bit; the least significant bit (LSB) is the rightmost bit. After the first call, each call to NetAuditRead must be given the value for the handle returned by the previous call.

auditloghandle	Value	xxx
4.19.2.1	(MSB) − 64	0
4.19.2.2	− 0 (LSB)	1
offset

Specifies the record offset at which to begin reading. This parameter is ignored unless bit 1 in the offsetflag parameter is set. If offsetflag bit 1 is set, offset is taken as an offset based on the record number (not bytes) at which the returned data should begin. Note that the record offset parameter is zero-based from both directions, depending upon the direction of the read. If reading backward, record 0 is the last record in the log. If reading forward, record 0 is the first record in the log.

reserved1

Reserved. Must be NULL.

reserved2

Reserved. Must be zero.

offsetflag

Specifies the open flags, as follows:

Bit(s)	Meaning
4.19.2.3	If 0, the log is read forward. If 1, the log is read backward and records are returned in the buffer in reverse chronological order (newest records first).
4.19.2.4	If 0, reading proceeds sequentially. If 1, reading proceeds from the nth record from the start of the log, where n is the offset parameter.
4.19.2.5	Reserved; must be 0.
bufptr

On return a pointer to the returned information is returned in the address pointed to by bufptr. After a successful read operation, this buffer contains a sequence of audit entries with the accompanying variable-length data structures.

prefmaxlen

Preferred maximum length of returned data (in 8-bit bytes).

bytesread

On return the actual number of bytes read into the buffer is located in the DWORD pointed to by bytesread.

totalavailable

On return the total bytes available to be read from the log is located in the DWORD pointed to by totalavailable.


Netbios
 Netbios  QuickInfo  Overview  Group

The Netbios function interprets and executes the specified network control block (NCB).

UCHAR Netbios(

PNCB  pncb	// address of network control block
);
Parameters

pncb

Points to an NCB structure describing the network control block to process.

Return Value

For synchronous requests, the return value is the return code of the NCB structure. That value is also returned in the ncb_retcode member of the NCB structure.

There are two return value possibilities for accepted asynchronous requests. If the asynchronous command has already completed when Netbios returns to its caller, the return value is the return code of the NCB structure, just as if it were a synchronous NCB structure. If the asynchronous command is still pending when Netbios returns to its caller, the return value is zero.

If the address specified by the pncb parameter is invalid, the return value is NRC_BADNCB.

Remarks

Netbios is primarily for applications written for the IBM NetBIOS system that need to be ported to Windows. Applications that do not have this requirement typically use other interfaces, such as mailslots and named pipes, instead of Netbios.

Netbios contains extensions to the standard IBM NetBIOS 3.0 specification to allow POST routines to be called from C and to operate efficiently in the Windows environment.

When an asynchronous network control block finishes and the ncb_post member is nonzero, the routine specified in ncb_post is called with a single parameter of type PNCB. This parameter contains the address of the finishing network control block. (In the standard IBM NetBIOS 3.0, the address of the network control block is supplied in a nonportable interface.)

Another extension to the NCB structure is a handle of an event (the ncb_event member). The event is set to the nonsignaled state by the system when an asynchronous NetBIOS command is accepted, and it is set to the signaled state when the asynchronous NetBIOS command finishes.

Using ncb_event to submit asynchronous requests requires fewer system resources than using ncb_post. Also, when ncb_event is nonzero, the pending request is canceled if the thread terminates before the request is processed. This is not true for requests sent by using ncb_post.

Only manual reset events should be used with Netbios. A specified event should not be associated with more than one active asynchronous NetBIOS command.

See Also

NCB


NetConfigGet
 NetConfigGet  QuickInfo

NetConfigGet retrieves the value of a single specified entry for a particular component on the local computer or on a remote server.

Security Requirements

Admin or accounts, comm, print, or server operator group membership is required to successfully execute NetConfigGet on a remote server.

NET_API_STATUS
NetConfigGet (

LPTSTR server,
LPTSTR component,
LPTSTR parameter,
LPBYTE * bufptr
);
Parameters

server

Points to a Unicode string that contains the name of the server on which to execute NetConfigGet. A NULL pointer or NULL string specifies the local computer.

component

Points to a Unicode string that specifies which configuration component to search.

parameter

Points to a Unicode string that specifies the entry for the component specified whose value is to be returned.

bufptr

On return a pointer to the returned information is returned in the address pointed to by bufptr.


NetConfigGetAll
 NetConfigGetAll  QuickInfo

NetConfigGetAll retrieves all the configuration information for a given component on a local or a remote computer.

Security Requirements

Admin or account, comm, print, or server operator group membership is required to successfully execute NetConfigGetAll on a remote server.

NET_API_STATUS
NetConfigGetAll (

LPTSTR server,
LPTSTR component,
LPBYTE * bufptr
);
Parameters

server

Points to a Unicode string that contains the name of the server on which to execute NetConfigGet. A NULL pointer or NULL string specifies the local computer.

component

Points to a Unicode string that specifies which configuration component to search.

bufptr

On return a pointer to the returned information is returned in the address pointed to by bufptr.


NetConfigSet
 NetConfigSet  QuickInfo

NetConfigSet sets the value of a single specified entry for a particular component on the local computer or on a remote server.

Security Requirements

Admin or server operator group membership is required to successfully execute NetConfigSet on a remote server.

NET_API_STATUS
NetConfigSet (

LPTSTR server,
LPTSTR reserved1,
LPTSTR component,
DWORD level,
DWORD reserved2,
LPBYTE buf,
DWORD reserved3
);
Parameters

server

Points to a Unicode string that contains the name of the server on which to execute NetConfigSet. A NULL pointer or NULL string specifies the local computer.

reserved1

Reserved. Must be NULL.

component

Points to a Unicode string that specifies which configuration component to set.

level

Information level of request. Must be zero.

reserved2

Reserved. Must be zero.

buf

Buffer containing a CONFIG_INFO_0 structure.

reserved3

Reserved. Must be zero.


NetConnectionEnum
 NetConnectionEnum  QuickInfo

NetConnectionEnum lists all connections made to a shared resource on the server or all connections established from a particular computer. If there is more than one user using this connection, then it is possible to get more than one structure for the same connection, but with a different user name. The NetConnectionEnum function is obsolete. It is provided only for compatibility with LAN Manager and 16-bit versions of Windows. Win32-based applications should use the WNetEnumResource function.

Security Requirements

Admin or server, print, or comm operator group membership is required to successfully execute NetConnectionEnum.

NET_API_STATUS
NetConnectionEnum (

LPTSTR servername,
LPTSTR qualifier,
DWORD level,
LPBYTE * bufptr,
DWORD prefmaxlen,
LPDWORD entriesread,
LPDWORD totalentries,
LPDWORD resumehandle
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

qualifier

A pointer to a Unicode string containing a share name or computer name for the connections of interest. If it is a share name, then all the connections made to that share name are listed. If it is a computer name (for example, it starts with two backslash characters), then NetConnectionEnum lists all connections made from that computer to the server specified.

level

Level of information required. 0 and 1 are valid.

bufptr

On return a pointer to the return information structure is returned in the address pointed to by bufptr.

prefmaxlen

Prefered maximum length of returned data (in 8-bit bytes).

entriesread

On return the actual enumerated element count is located in the DWORD pointed to by entriesread.

totalentries

On return the total number of entries that could have been enumerated from the current resume position is located in the DWORD pointed to by totalentries.

resume_handle

On return, a resume handle is stored in the DWORD pointed to by resume_handle, and is used to continue an existing connection search. The handle should be zero on the first call and left unchanged for subsequent calls. If resume_handle is NULL, then no resume handle is stored.


NetErrorLogClear
 NetErrorLogClear  QuickInfo

NetErrorLogClear clears the error log and optionally saves the entries in a backup file.

Security Requirements

Admin group membership is required to successfully execute NetErrorLogClear on a remote server.

NET_API_STATUS
NetErrorLogClear (

LPTSTR server,
LPTSTR backupfile,
LPBYTE reserved
);
Parameters

server

Points to a Unicode string that contains the name of the server on which to execute NetErrorLogClear. A NULL pointer or NULL string specifies the local computer.

backupfile

Points to a Unicode string that assigns a name for an optional backup file. The calling application must have write permission for the path specified by backupfile. A NULL pointer indicates not to back up the error log.

reserved

Reserved. Must be NULL.


NetErrorLogRead
 NetErrorLogRead  QuickInfo

NetErrorLogRead reads from the specified error log.

Security Requirements

No special group membership is required to successfully execute NetErrorLogRead.

NET_API_STATUS
NetErrorLogRead (

LPTSTR server,
LPTSTR reserved1,
LPHLOG errloghandle,
DWORD offset,
LPDWORD reserved2,
DWORD reserved3,
DWORD offsetflag,
LPBYTE * bufptr,
DWORD prefmaxlen,
LPDWORD bytesread,
LPDWORD totalbytes
);
Parameters

server

Points to a Unicode string that contains the name of the server on which to execute NetErrorLogClear. A NULL pointer or NULL string specifies the local computer.

reserved1

Reserved. Must be NULL.

errloghandle

Points to the error log handle. An application calling NetErrorLogRead for the first time must initialize the 128-bit error log handle.

offset

Specifies the record offset at which to begin reading. This parameter is ignored unless bit 1 of offsetflag is set. If used, offset is taken as an offset of the record number (not bytes) at which to begin reading. Note that the record offset parameter is zero-based from both directions, depending upon the direction it is read.

reserved2

Reserved. Must be NULL.

reserved3

Reserved. Must be zero.

offsetflag

Specifies the open flags, bitmapped as follows:

Bit(s)	Value
4.16.2.1	If 0, the log is read forward. If 1, the log is read backward and records are returned in reverse chronological order.
4.16.2.2	If 0, the read proceeds normally (sequentially). If 1, the read proceeds from the nth record from the start of the log, where n is the offset parameter.
4.16.2.3	Reserved; must be 0.
bufptr

On return a pointer to the return information buffer is returned in the address pointed to by bufptr.

prefmaxlen

Preferred maximum length of returned data (in 8-bit bytes).

bytesread

On return the actual number of bytes read into the buffer is located in the DWORD pointed to by bytesread.

totalbytes

On return the total bytes available to be read from the log is located in the DWORD pointed to by totalbytes.


NetFileClose
 NetFileClose  QuickInfo

NetFileClose forces a resource to close. This function can be used when an error prevents closure by other means.

Security Requirements

Admin or server operator group membership is required to successfully execute NetFileClose.

NET_API_STATUS
NetFileClose (

LPTSTR servername,
DWORD fileid
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

fileid

The file identifier of the opened resource instance to be closed.


NetFileEnum
 NetFileEnum  QuickInfo

NetFileEnum supplies information about some or all open files on a server, allowing the user to supply a resume handle and get required information through repeated calls to the function.

Security Requirements

Admin or server operator group membership is required to successfully execute NetFileEnum.

NET_API_STATUS
NetFileEnum (

LPTSTR servername,
LPTSTR basepath,
LPTSTR username,
DWORD level,
LPBYTE * bufptr,
DWORD prefmaxlen,
LPDWORD entriesread,
LPDWORD totalentries,
LPDWORD resume_handle
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

basepath

A pointer to a Unicode string containing a qualifier for the returned information. If NULL then all open resources are enumerated, else only resources that have basepath as a prefix are enumerated. A prefix is the path component up to a back-slash.

username

A pointer to a Unicode string that specifies the name of the user. If not NULL, username serves as a qualifier to the enumeration. The files returned are limited to those that have user names matching the qualifier. If username is NULL, no user-name qualifier is used.

level

Level of information required. 2 and 3 are valid.

bufptr

On return a pointer to the return information structure is returned in the address pointed to by bufptr.

prefmaxlen

Prefered maximum length of returned data (in 8-bit bytes).

entriesread

On return the actual enumerated element count is located in the DWORD pointed to by entriesread.

totalentries

On return the total number of entries that could have been enumerated from the current resume position is located in the DWORD pointed to by totalentries.

resume_handle

On return, a resume handle is stored in the DWORD pointed to by resume_handle, and is used to continue an existing file search. The handle should be zero on the first call and left unchanged for subsequent calls. If resume_handle is NULL, then no resume handle is stored.


NetFileGetInfo
 NetFileGetInfo  QuickInfo

NetFileGetInfo retrieves information about a particular opening of a server resource.

Security Requirements

Admin or server operator group membership is required to successfully execute NetFileGetInfo.

NET_API_STATUS
NetFileGetInfo (

LPTSTR servername,
DWORD fileid,
DWORD level,
LPBYTE * bufptr
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

fileid

The file identifier of the open resource to return information on. The fileid value must be that returned in a previous enumeration call.

level

Level of information required. 2 and 3 are valid.

bufptr

On return a pointer to the return information structure is returned in the address pointed to by bufptr.


NetGetDCName
 NetGetDCName  QuickInfo

NetGetDCName returns the name of the Primary Domain Controller for the specified domain.

Security Requirements

No special group membership is required to successfully execute NetGetDCName.

NET_API_STATUS
NetGetDCName (

LPWSTR servername,
LPWSTR domainname,
LPBYTE * bufptr
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

domainname

A pointer to a Unicode string containing the name of the domain. A NULL pointer or string indicates that the name of the domain controller for the primary domain is to be returned.

bufptr

A pointer to the buffer containing the domain controller name is returned in the address pointed to by bufptr.


 NetGetDisplayInformationIndex

The NetGetDisplayInformationIndex function gets the index of the first display information entry whose name begins with or alphabetically follows a specified string. You can use this function to determine a starting index for subsequent calls to the NetQueryDisplayInformation function.

Security Requirements

No special group membership is required to successfully execute NetGetDisplayInformationIndex.

NET_API_STATUS
NetGetDisplayInformationIndex (

LPWSTR   ServerName,	// pointer to name of server to get information from
DWORD    Level,	// level of information to retrieve
LPWSTR   Prefix,	// pointer to prefix string
LPDWORD  Index	// receives index of entry
);
Parameters

ServerName

Points to a null-terminated Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

Level

Specifies one of the following values to indicate the level of information to be queried:

Value	Meaning
1	Query all Local and Global (normal) user accounts.
2	Query all Workstation and Server (BDC) user accounts.
3	Query all Global Groups.
Prefix

Points to a null-terminated Unicode string containing the prefix to search for.

Index

Points to a 32-bit variable that receives the index of the entry.

Return Value

If the function succeeds, the return value is NERR_Success.

If the function fails, the return value is one of the following error codes:

Value	Meaning
ERROR_ACCESS_DENIED	The caller does not have access to the requested information.
ERROR_INVALID_LEVEL	The value specified for the Level parameter is invalid.
See Also

NetQueryDisplayInformation


NetGroupAdd
 NetGroupAdd  QuickInfo

NetGroupAdd creates a global group in the security database.

Security Requirements

Admin or account operator group membership is required to successfully execute NetGroupAdd.

NET_API_STATUS
NetGroupAdd (

LPWSTR servername,
DWORD level,
LPBYTE buf,
LPDWORD parm_err
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

level

Level of information provided. Must be 0 1, or 2.

buf

A pointer to a buffer containing the global group information structure.

parm_err

Optional pointer to a DWORD to return the index of the first parameter in error when ERROR_INVALID_PARAMETER is returned. If NULL the parameter is not returned on error.


NetGroupAddUser
 NetGroupAddUser  QuickInfo

NetGroupAddUser gives an existing user account membership in an existing global group.

Security Requirements

Admin or account operator group membership is required to successfully execute NetGroupAddUser.

NET_API_STATUS
NetGroupAddUser (

LPWSTR servername,
LPWSTR GroupName,
LPWSTR username
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

GroupName

A pointer to a Unicode string containing the name of the global group to which the user is to be given membership.

Username

A pointer to a Unicode string containing the name of the user to be given global group membership.


NetGroupDel
 NetGroupDel  QuickInfo

NetGroupDel deletes a global group account from the accounts database.

Security Requirements

Admin or account operator group membership is required to successfully execute NetGroupDel.

NET_API_STATUS
NetGroupDel (

LPWSTR servername,
LPWSTR groupname
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

groupname

A pointer to a Unicode string containing the name of the global group account to delete.


NetGroupDelUser
 NetGroupDelUser  QuickInfo

NetGroupDelUser removes a user from a particular global group in the user account database.

Security Requirements

Admin or account operator group membership is required to successfully execute NetGroupDelUser.

NET_API_STATUS
NetGroupDelUser (

LPWSTR servername,
LPWSTR GroupName,
LPWSTR Username
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

GroupName

A pointer to a Unicode string containing the name of the global group from which the user membership is to be removed.

Username

A pointer to a Unicode string containing the name of the user to remove from the global group.


NetGroupEnum
 NetGroupEnum  QuickInfo

NetGroupEnum retrieves information about each global group account.

Security Requirements

Admin or account operator group membership is required to successfully execute NetGroupEnum.

NET_API_STATUS
NetGroupEnum (

LPWSTR servername,
DWORD level,
LPBYTE * bufptr,
DWORD prefmaxlen,
LPDWORD entriesread,
LPDWORD totalentries,
LPDWORD resume_handle
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

level

Level of information required. 0 and 1 are valid.

bufptr

On return a pointer to the return information structure is returned in the address pointed to by bufptr.

prefmaxlen

Preferred maximum length of returned data (in 8-bit bytes).

entriesread

On return the actual enumerated element count is located in the DWORD pointed to by entriesread.

totalentries

On return the total number of entries that could have been enumerated from the current resume position is located in the DWORD pointed to by totalentries.

resume_handle

On return, a resume handle is stored in the DWORD pointed to by resume_handle, and is used to continue an existing global group search. The handle should be zero on the first call and left unchanged for subsequent calls. If resume_handle is NULL, then no resume handle is stored.


NetGroupGetInfo
 NetGroupGetInfo  QuickInfo

NetGroupGetInfo retrieves information about a particular global group account on a server.

Security Requirements

Admin or account operator group membership is required to successfully execute NetGroupGetInfo.

NET_API_STATUS
NetGroupGetInfo (

LPWSTR servername,
LPWSTR groupname,
DWORD level,
LPBYTE * bufptr
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

groupname

A pointer to a Unicode string containing the name of the global group account to return information on.

level

Level of information required. 0, 1, and 2 are valid.

bufptr

A pointer to the return information structure is returned in the address pointed to by bufptr.


NetGroupGetUsers
 NetGroupGetUsers  QuickInfo

NetGroupGetUsers retrieves a list of the members of a particular global group in the user account database.

Security Requirements

Admin or account operator group membership is required to successfully execute NetGroupGetUsers except when the request is made by a user who has membership in the specified global group, in which case no special group membership is required.

NET_API_STATUS
NetGroupGetUsers (

LPWSTR servername,
LPWSTR groupname,
DWORD level,
LPBYTE * bufptr,
DWORD prefmaxlen,
LPDWORD entriesread,
LPDWORD totalentries,
LPDWORD ResumeHandle
);
Parameters

servername

pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

groupname

A pointer to a Unicode string containing the name of the global group whose members are to be listed.

level

Level of information required. Only 0 and 1 are valid.

bufptr

On return a pointer to the return information structure is returned in the address pointed to by bufptr.

prefmaxlen

Preferred maximum length of returned data (in 8-bit bytes).

entriesread

On return the actual enumerated element count is located in the DWORD pointed to by entriesread.

totalentries

On return the total number of entries that could have been enumerated from the current resume position is located in the DWORD pointed to by totalentries.

ResumeHandle

On return, a resume handle is stored in the DWORD pointed to by ResumeHandle, and is used to continue an existing usergroup search. The handle should be zero on the first call and left unchanged for subsequent calls. If ResumeHandle is NULL, then no resume handle is stored.


NetGroupSetInfo
 NetGroupSetInfo  QuickInfo

NetGroupSetInfo sets the parameters of a global group account.

Security Requirements

Admin or account operator group membership is required to successfully execute NetGroupSetInfo.

NET_API_STATUS
NetGroupSetInfo (

LPWSTR servername,
LPWSTR groupname,
DWORD level,
LPBYTE buf,
LPDWORD parm_err
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

groupname

A pointer to a Unicode string containing the name of the global group account to set information on.

level

Level of information to set. Only 0, 1, and 2 are valid.

buf

A pointer to a buffer containing the global group information.

parm_err

Optional pointer to a DWORD to return the index of the first parameter in error when ERROR_INVALID_PARAMETER is returned. If NULL the parameter is not returned on error.


NetGroupSetUsers
 NetGroupSetUsers  QuickInfo

NetGroupSetUsers sets the global group membership for the specified global group. Each user specified is made a member of the global group. Users that are not specified but are currently members of the global group will have their membership revoked.

Security Requirements

Admin or account operator group membership is required to successfully execute NetGroupSetUsers on a remote server.

NET_API_STATUS
NetGroupSetUsers (

LPWSTR servername,
LPWSTR groupname,
DWORD level,
LPBYTE buf,
DWORD totalentries
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

groupname

A pointer to a Unicode string containing the name of the global group to which the specified users belong.

level

Level of information supplied. Only 0 is valid.

buf

Points to the buffer in which the data to be set is stored. This data consists of a sequence of _GROUP_USERS_INFO_0 data structures.

totalentries

On return the total number of entries that could have been enumerated from the current resume position is located in the DWORD pointed to by totalentries.


NetLocalGroupAdd
 NetLocalGroupAdd  QuickInfo

NetLocalGroupAdd creates a local group in the security database.

Security Requirements

Admin or account operator group membership is required to successfully execute NetLocalGroupAdd.

NET_API_STATUS
NetLocalGroupAdd (

LPWSTR servername,
DWORD level,
LPBYTE buf,
LPDWORD parm_err
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

level

Level of information provided. Must be 0 or 1.

buf

A pointer to a buffer containing the local group information structure.

parm_err

Optional pointer to a DWORD to return the index of the first parameter in error when ERROR_INVALID_PARAMETER is returned. If NULL the parameter is not returned on error.


NetLocalGroupAddMember
 NetLocalGroupAddMember  QuickInfo

NetLocalGroupAddMember gives an existing user account or global group membership in an existing local group.

Security Requirements

Admin or account operator group membership is required to successfully execute NetLocalGroupAddMember.

NET_API_STATUS
NetLocalGroupAddMember (

LPWSTR servername,
LPWSTR groupname,
PSID membersid
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

groupname

A pointer to a Unicode string containing the name of the local group to which the user or global group is to be given membership.

membersid

A pointer to the SID of a user or global group from the local, primary, or trust domains to be given local group membership.


 NetLocalGroupAddMembers

The NetLocalGroupAddMembers function adds one or more existing user accounts or global groups as members of an existing local group. The function does not change the membership status of users or global groups that are currently members of the local group

Security Requirements

Admin or account operator group membership is required to successfully execute NetLocalGroupAddMembers on a remote server.

NET_API_STATUS
NetLocalGroupAddMembers (

LPWSTR  servername,	// pointer to name of server on which to execute this function
LPWSTR  groupname,	// pointer to name of local group to add members to
DWORD   level,	// level of information provided for new members
LPBYTE  buf,	// pointer to buffer containing information for new members
DWORD   membercount	// number of new members being added
);
Parameters

servername

Points to a null-terminated Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

groupname

Points to a null-terminated Unicode string containing the name of the local group to which the specified users or global groups will be added.

level

Specifies one of the following values to indicate the level of information provided:

Value	Meaning
0	The buf parameter points to an array of LOCALGROUP_MEMBERS_INFO_0 structures.
3	The buf parameter points to an array of LOCALGROUP_MEMBERS_INFO_3 structures.
buf

Points to a buffer containing the data for the new members. This data consists of a sequence of LOCALGROUP_MEMBERS_INFO_0 or LOCALGROUP_MEMBERS_INFO_3 data structures.

membercount

Specifies the number of entries in the buffer pointed to by buf.

Return Value

If the function succeeds, the return value is NERR_Success.

If the function fails, the return value is one of the following error codes:

Value	Meaning
NERR_GroupNotFound	The local group specified by the groupname parameter does not exist.
ERROR_NO_SUCH_MEMBER	One or more of the new members doesn't exist. Therefore, no new members were added.
ERROR_MEMBER_IN_ALIAS	One or more of the members specified were already members of the local group. Therefore, no new members were added.
ERROR_INVALID_MEMBER	One or more of the members cannot be added because it has an invalid account type. Therefore, no new members were added.
Remarks

Use the NetLocalGroupAddMembers function instead of the NetLocalGroupAddMember function, which is obsolete.

See Also

NetLocalGroupAdd, NetLocalGroupDelMembers, NetLocalGroupGetMembers


NetLocalGroupDel
 NetLocalGroupDel  QuickInfo

NetLocalGroupDel deletes a local group account and all its members from the accounts database.

Security Requirements

Admin or account operator group membership is required to successfully execute NetLocalGroupDel.

NET_API_STATUS
NetLocalGroupDel (

LPWSTR servername,
LPWSTR groupname
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

groupname

A pointer to a Unicode string containing the name of the local group account to delete.


NetLocalGroupDelMember
 NetLocalGroupDelMember  QuickInfo

NetLocalGroupDelMember removes a member from a particular local group in the security database.

Security Requirements

Admin or account operator group membership is required to successfully execute NetLocalGroupDelMember.

NET_API_STATUS
NetLocalGroupDelMember (

LPWSTR servername,
LPWSTR groupname,
PSID membersid
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

groupname

A pointer to a Unicode string containing the name of the local group from which the user membership is to be removed.

membersid

A pointer to a SID of a user or global group to remove from the local group.


 NetLocalGroupDelMembers

The NetLocalGroupDelMembers function removes one or more members from an existing local group.

Security Requirements

Admin or account operator group membership is required to successfully execute NetLocalGroupDelMembers on a remote server.

NET_API_STATUS
NetLocalGroupDelMembers (

LPWSTR  servername,	// pointer to name of server on which to execute this function
LPWSTR  groupname,	// pointer to name of local group to delete members from
DWORD   level,	// level of information provided for members to be deleted
LPBYTE  buf,	// pointer to buffer containing information for members
DWORD   membercount	// number of members being deleted
);
Parameters

servername

Points to a null-terminated Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

groupname

Points to a null-terminated Unicode string containing the name of the local group from which the specified users or global groups will be removed.

level

Specifies one of the following values to indicate the level of information provided:

Value	Meaning
0	The buf parameter points to an array of LOCALGROUP_MEMBERS_INFO_0 structures.
3	The buf parameter points to an array of LOCALGROUP_MEMBERS_INFO_3 structures.
buf

Points to the buffer containing data that describes the removed members. This data consists of a sequence of LOCALGROUP_MEMBERS_INFO_0 or LOCAL_GROUP_MEMBERS_INFO_3 data structures.

membercount

Specifies the number of entries in the array pointed to by buf.

Return Value

If the function succeeds, the return value is NERR_Success.

If the function fails, the return value is one of the following error codes:

Value	Meaning
NERR_GroupNotFound	The local group specified by the groupname parameter does not exist.
ERROR_NO_SUCH_MEMBER	One or more of the members doesn't exist. Therefore, no members were deleted.
ERROR_MEMBER_IN_ALIAS	One or more of the members specified were not members of the local group. Therefore, no members were deleted.
Remarks

Use the NetLocalGroupDelMembers function instead of the NetLocalGroupDelMember function, which is obsolete.

See Also

NetLocalGroupAddMembers, NetLocalGroupDel, NetLocalGroupGetMembers


NetLocalGroupEnum
 NetLocalGroupEnum  QuickInfo

NetLocalGroupEnum retrieves information about each local group account.

Security Requirements

Admin or account operator group membership is required to successfully execute NetLocalGroupEnum.

NET_API_STATUS
NetLocalGroupEnum (

LPWSTR servername,
DWORD level,
LPBYTE * bufptr,
DWORD prefmaxlen,
LPDWORD entriesread,
LPDWORD totalentries,
LPDWORD resumehandle
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

level

Level of information required. 0 and 1 are valid.

bufptr

On return a pointer to the return information structure is returned in the address pointed to by bufptr.

prefmaxlen

Preferred maximum length of returned data (in 8-bit bytes).

entriesread

On return the actual enumerated element count is located in the DWORD pointed to by entriesread.

totalentries

On return the total number of entries that could have been enumerated from the current resume position is located in the DWORD pointed to by totalentries.

resumehandle

On return, a resume handle is stored in the DWORD pointed to by resumehandle, and is used to continue an existing local group search. The handle should be zero on the first call and left unchanged for subsequent calls. If resumehandle is NULL, then no resume handle is stored.


NetLocalGroupGetInfo
 NetLocalGroupGetInfo  QuickInfo

NetLocalGroupGetInfo retrieves information about a particular local group account on a server.

Security Requirements

Admin or account operator group membership is required to successfully execute NetLocalGroupGetInfo.

NET_API_STATUS
NetLocalGroupGetInfo (

LPWSTR servername,
LPWSTR groupname,
DWORD level,
LPBYTE * bufptr
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

groupname

A pointer to a Unicode string containing the name of the local group account to return information on.

level

Level of information required. 0 and 1 are valid.

bufptr

A pointer to the return information structure is returned in the address pointed to by bufptr.


NetLocalGroupGetMembers
 NetLocalGroupGetMembers  QuickInfo

NetLocalGroupGetMembers retrieves a list of the members of a particular local group in the security database.

Security Requirements

Admin or account operator group membership is required to successfully execute NetLocalGroupGetMembers except when the request is made by a user who has membership in the specified local group in which case no special group membership is required.

NET_API_STATUS
NetLocalGroupGetMembers (

LPWSTR servername,
LPWSTR localgroupname,
DWORD level,
LPBYTE * bufptr,
DWORD prefmaxlen,
LPDWORD entriesread,
LPDWORD totalentries,
LPDWORD resumehandle
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

localgroupname

A pointer to a Unicode string containing the name of the local group whose members are to be listed.

level

Level of information required. Levels 0 and 1 are valid.

bufptr

On return a pointer to the return information structure is returned in the address pointed to by bufptr.

prefmaxlen

Prefered maximum length of returned data (in 8-bit bytes).

entriesread

On return the actual enumerated element count is located in the DWORD pointed to by entriesread.

totalentries

On return the total number of entries that could have been enumerated from the current resume position is located in the DWORD pointed to by totalentries.

resumehandle

On return, a resume handle is stored in the DWORD pointed to by resumehandle, and is used to continue an existing usergroup search. The handle should be zero on the first call and left unchanged for subsequent calls. If resumehandle is NULL, then no resume handle is stored.


NetLocalGroupSetInfo
 NetLocalGroupSetInfo  QuickInfo

NetLocalGroupSetInfo sets the parameters of a local group.

Security Requirements

Admin or account operator group membership is required to successfully execute NetLocalGroupSetInfo.

NET_API_STATUS
NetLocalGroupSetInfo (

LPWSTR servername,
LPWSTR groupname,
DWORD level,
LPBYTE buf,
LPDWORD parm_err
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

groupname

A pointer to a Unicode string containing the name of the local group account to set information on.

level

Level of information to set. 0, 1, and 1002 are valid.

buf

A pointer to a buffer containing the local group information.

parm_err

Optional pointer to a DWORD to return the index of the first parameter in error when ERROR_INVALID_PARAMETER is returned. If NULL the parameter is not returned on error.


NetLocalGroupSetMembers
 NetLocalGroupSetMembers  QuickInfo

NetLocalGroupSetMembers sets the local group membership for the specified local group. Each user or global group specified is made a member of the local group. Users or global groups that are not specified but are currently members of the local group will have their membership revoked.

Security Requirements

Admin or account operator group membership is required to successfully execute NetLocalGroupSetMembers on a remote server.

NET_API_STATUS
NetLocalGroupSetMembers (

LPWSTR servername,
LPWSTR groupname,
DWORD level,
LPBYTE buf,
DWORD totalentries
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

groupname

A pointer to a Unicode string containing the name of the local group to which the specified users or global groups belong.

level

Level of information supplied. Only 0 is valid.

buf

Points to the buffer in which the data to be set is stored. This data consists of a sequence of LOCALGROUP_MEMBERS_INFO_0 data structures.

totalentries

On return the total number of entries that could have been enumerated from the current resume position is located in the DWORD pointed to by totalentries.


NetMessageBufferSend
 NetMessageBufferSend  QuickInfo

NetMessageBufferSend sends a buffer of information to a registered message alias.

Security Requirements

No special group membership is required to execute NetMessage buffer send locally. Admin, accounts, print, or server operator group membership is required to successfully execute NetMessageBufferSend on a remote server.

NET_API_STATUS
NetMessageBufferSend (

LPTSTR servername,
LPTSTR msgname,
LPTSTR fromname,
LPBYTE buf,
DWORD buflen
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

msgname

A pointer to a Unicode string containing the message name to which the message buffer should be sent.

fromname

A pointer to a Unicode string containing the message name sending the information. fromname is a new parameter for Windows networking. This parameter is needed for sending alerts from the computer name rather than the logged on user. If a NULL is specified the message is send from the logged on user as with LAN Manager 2.x.

buf

A pointer to a buffer of message text.

buflen

The length in bytes of the message text in buf.


NetMessageNameAdd
 NetMessageNameAdd  QuickInfo

NetMessageNameAdd registers a message alias in the message name table. NetMessageNameAdd requires that the Messenger service be started.

Security Requirements

Admin group membership is required to successfully execute NetMessageNameAdd on a remote server.

NET_API_STATUS
NetMessageNameAdd (

LPTSTR servername,
LPTSTR msgname
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

msgname

A pointer to a Unicode string of limit 15 characters containing the message name to be added.

Note  The forward action flag from the LAN Manager 2.x NetMessageNameAdd is no longer a parameter because message forwarding is no longer supported. If the NetMessageNameAdd function detects that a forwarded version of msgname exists on the network, the function will fail with error NERR_Already_Exists.


NetMessageNameDel
 NetMessageNameDel  QuickInfo

NetMessageNameDel deletes a message alias from the table of message aliases on a computer. NetMessageNameDel requires that the Messenger service be started.

Security Requirements

Admin group membership is required to successfully execute NetMessageNameDel on a remote server.

NET_API_STATUS
NetMessageNameDel (

LPTSTR servername,
LPTSTR msgname
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

msgname

A pointer to a Unicode string of limit 15 characters containing the message name to be deleted.


NetMessageNameEnum
 NetMessageNameEnum  QuickInfo

NetMessageNameEnum lists the message aliases that will receive messages on a specified computer. NetMessageNameEnum requires that the Messenger service be started.

Security Requirements

Admin group membership is required to successfully execute NetMessageNameEnum on a remote server.

NET_API_STATUS
NetMessageNameEnum (

LPTSTR servername,
DWORD level,
LPBYTE * bufptr,
DWORD prefmaxlen,
LPDWORD entriesread,
LPDWORD totalentries,
LPDWORD resume_handle
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

level

Level of information required. 0 and 1 are valid.

bufptr

On return a pointer to the return information structure is returned in the address pointed to by bufptr.

prefmaxlen

Prefered maximum length of returned data (in 8-bit bytes).

entriesread

On return the actual enumerated element count is located in the DWORD pointed to by entriesread.

totalentries

On return the total number of entries that could have been enumerated from the current resume position is located in the DWORD pointed to by totalentries.

resume_handle

On return, a resume handle is stored in the DWORD pointed to by resume_handle, and is used to continue an existing message name search. The handle should be zero on the first call and left unchanged for subsequent calls. If resume_handle is NULL, then no resume handle is stored.


NetMessageNameGetInfo
 NetMessageNameGetInfo  QuickInfo

NetMessageNameGetInfo retrieves information about a particular message alias in the message name table. NetMessageNameGetInfo requires that the Messenger service be started.

Security Requirements

Admin group membership is required to successfully execute NetMessageNameGetInfo on a remote server.

NET_API_STATUS
NetMessageNameGetInfo (

LPTSTR servername,
LPTSTR msgname,
DWORD level,
LPBYTE * bufptr
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

msgname

A pointer to a Unicode string containing the message name to return information on.

level

Level of information required. 0 and 1 are valid.

bufptr

On return a pointer to the return information structure is returned in the address pointed to by bufptr.


 NetQueryDisplayInformation

The NetQueryDisplayInformation function returns user, computer, or group account information. Use this function to quickly enumerate account information for display in user interfaces.

Security Requirements

No special group membership is required to successfully execute NetQueryDisplayInformation.

NET_API_STATUS
NetQueryDisplayInformation(

LPWSTR   ServerName,	// pointer to name of server to get information from
DWORD    Level,	// level of information to retrieve
DWORD    Index,	// index of first entry to get information for
DWORD    EntriesRequested,	// number of entries to get information for
DWORD    PreferredMaximumLength,	// preferred maximum size, in bytes, of returned buffer
LPDWORD  ReturnedEntryCount,	// receives number of entries for which information is returned
PVOID    * SortedBuffer	// receives pointer to system-allocated buffer
);
Parameters

ServerName

Points to a null-terminated Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

Level

Specifies one of the following values to indicate the level of information requested:

Value	Meaning
1	Return all Local and Global (normal) user accounts. The returned buffer will contain an array of NET_DISPLAY_USER structures.
2	Return all Workstation and Server (BDC) user accounts. The returned buffer will contain an array of NET_DISPLAY_MACHINE structures.
3	Return all Global Groups. The returned buffer will contain an array of NET_DISPLAY_GROUP structures.
Index

Specifies the index of the first entry to retrieve information for. Specify zero to retrieve account information beginning with the first display information entry. If a call to NetQueryDisplayInformation returns ERROR_MORE_DATA, you can get data for additional entries by setting Index to the value returned in the next_index member of the last entry in SortedBuffer. To retrieve information for entries beginning with a specified prefix, set Index to the index returned by a call to the NetGetDisplayInformationIndex function.

EntriesRequested

Specifies the maximum number of entries to get information for.

PreferredMaximumLength

Specifies the preferred maximum size, in 8-bit bytes, of the system-allocated buffer returned in *SortedBuffer.

ReturnedEntryCount

Points to a 32-bit variable that receives the number of entries in the buffer returned in *SortedBuffer. Zero indicates that there are no entries with an index as large as that specified. Entries may be returned when the function's return value is either NERR_Success or ERROR_MORE_DATA.

SortedBuffer

Points to a variable that receives a pointer to a system-allocated buffer containing a sorted list of the requested information. This buffer contains an array of NET_DISPLAY_USER, NET_DISPLAY_MACHINE or NET_DISPLAY_GROUP structures. Use NetApiBufferFree to deallocate the buffer.

Return Value

If the function returns account information, the return value is one of the following values:

Value	Meaning
NERR_Success	There are no more entries to be returned.
ERROR_MORE_DATA	More entries are available. That is, the last entry returned in the SortedBuffer buffer is not the last entry available. To get information for additional entries, call NetQueryDisplayInformation again with the Index parameter set to the value returned in the next_index member of the last entry in SortedBuffer.
If the function fails, the return value is one of the following error codes:

Value	Meaning
ERROR_ACCESS_DENIED	The caller does not have access to the requested information.
ERROR_INVALID_LEVEL	The Level parameter specifies an invalid value.
Remarks

The NetQueryDisplayInformation function is remotable. The server specified by the Server parameter can be any Windows NT workstation or server; it cannot be a LAN Manager or Windows for Workgroups server.

The NetQueryDisplayInformation and NetGetDisplayInformationIndex functions provide a very efficient mechanism for enumerating User and Global group accounts. When possible, use these functions instead of the NetUserEnum and NetGroupEnum functions.

See Also

NetApiBufferFree, NetGetDisplayInformationIndex, NetGroupEnum, NetUserEnum.


NetRemoteTOD
 NetRemoteTOD  QuickInfo

NetRemoteTOD returns a server's time of day.

Security Requirements

No special group membership is required to successfully execute NetRemoteTOD.

NET_API_STATUS
NetRemoteTOD (

LPTSTR UncServerName,
LPBYTE * BufferPtr
);
Parameters

UncServerName

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

BufferPtr

On return a pointer to the return information structure is returned in the address pointed to by BufferPtr.

Remarks

The remote time-of-day information is available at one information level:

typedef struct _TIME_OF_DAY_INFO {
    DWORD    tod_elapsedt;
    DWORD    tod_msecs;
    DWORD    tod_hours;
    DWORD    tod_mins;
    DWORD    tod_secs;
    DWORD    tod_hunds;
    LONG     tod_timezone;
    DWORD    tod_tinterval;
    DWORD    tod_day;
    DWORD    tod_month;
    DWORD    tod_year;
    DWORD    tod_weekday;
} TIME_OF_DAY_INFO, *PTIME_OF_DAY_INFO, *LPTIME_OF_DAY_INFO;


NetReplExportDirAdd
 NetReplExportDirAdd  QuickInfo

NetReplExportDirAdd registers an existing directory in the export path to be replicated. The default values for locktime and lockcount (both 0) are assumed.

Security Requirements

Admin or server operator group membership is required to successfully execute NetReplExportDirAdd.

NET_API_STATUS
NetReplExportDirAdd (

LPTSTR servername,
DWORD level,
LPBYTE buf,
LPDWORD parm_err
);
Parameters

servername

A pointer to a null-terminated Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

level

Level of information to add. Only level 1 is valid.

buf

A pointer to a buffer containing the directory control information structure.

parm_err

Optional pointer to a DWORD to return the index of the first parameter in error when ERROR_INVALID_PARAMETER is returned. If NULL the parameter is not returned on error.


NetReplExportDirDel
 NetReplExportDirDel  QuickInfo

NetReplExportDirDel deregisters a replicated directory.

Security Requirements

Admin or server operator group membership is required to successfully execute NetReplExportDirDel.

NET_API_STATUS
NetReplExportDirDel (

LPTSTR servername,
LPTSTR dirname
);
Parameters

servername

A pointer to a null-terminated Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

dirname

A pointer to a null-terminated Unicode string containing the name of a replicated directory to deregister.


NetReplExportDirEnum
 NetReplExportDirEnum  QuickInfo

NetReplExportDirEnum lists the replicated directories in the export path.

Security Requirements

No special group membership is required to successfully execute NetReplExportDirEnum.

NET_API_STATUS
NetReplExportDirEnum (

LPTSTR servername,
DWORD level,
LPBYTE * bufptr,
DWORD prefmaxlen,
LPDWORD entriesread,
LPDWORD totalentries,
LPDWORD resumehandle
);
Parameters

servername

A pointer to a null-terminated Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

level

Level of information to return. Levels 0,1, and 2 are valid.

bufptr

On return, an array of the specified information structure is returned in the address pointed to by bufptr.

prefmaxlen

Preferred maximum length of returned data (in 8-bit bytes). A value of 0xFFFFFFFF indicates that all available entries should be returned.

entriesread

On return, the actual enumerated element count is located in the DWORD pointed to by entriesread.

totalentries

On return, the total number of entries that could have been enumerated from the current resume position is located in the DWORD pointed to by totalentries.

resumehandle

On return, a resume handle is stored in the DWORD pointed to by resumehandle, and is used to continue an existing use search. The handle should be zero on the first call and left unchanged for subsequent calls. If resumehandle is NULL, then no resume handle is stored.


NetReplExportDirGetInfo
 NetReplExportDirGetInfo  QuickInfo

NetReplExportDirGetInfo retrieves a replicated directory control information.

Security Requirements

No special group membership is required to successfully execute NetReplExportDirGetInfo.

NET_API_STATUS
NetReplExportDirGetInfo (

LPTSTR servername,
LPTSTR dirname,
DWORD level,
LPBYTE * bufptr
);
Parameters

servername

A pointer to a null-terminated Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

dirname

A pointer to a null-terminated Unicode string containing the directory name to return control information about.

level

Level of information to return. Levels 0, 1, and 2 are valid.

bufptr

On return a pointer to the return information structure is written in the address pointed to by bufptr.


NetReplExportDirLock
 NetReplExportDirLock  QuickInfo

NetReplExportDirLock locks a replicated directory so that replication from it can be suspended. This function increments the lock reference count for the specified directory.

Security Requirements

Admin or server operator group membership is required to successfully execute NetReplExportDirLock.

NET_API_STATUS
NetReplExportDirLock (

LPTSTR servername,
LPTSTR dirname
);
Parameters

servername

A pointer to a null-terminated Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

dirname

A pointer to a null-terminated Unicode string containing the directory name to lock.


NetReplExportDirSetInfo
 NetReplExportDirSetInfo  QuickInfo

NetReplExportDirSetInfo modifies the control information of a replicated directory.

Security Requirements

Admin or server operator group membership is required to successfully execute NetReplExportDirSetInfo.

NET_API_STATUS
NetReplExportDirSetInfo (

LPTSTR servername,
LPTSTR dirname,
DWORD level,
LPBYTE buf,
LPDWORD parm_err
);
Parameters

servername

A pointer to a null-terminated Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

dirname

A pointer to a null-terminated Unicode string containing the directory name to return control information about.

level

Level of information to set. Levels 1, 1000, and 1001 are valid.

buf

A pointer to a buffer containing the control information structure that corresponds to the specified level.

parm_err

Optional pointer to a DWORD to return the identifier of the first parameter in error when ERROR_INVALID_PARAMETER is returned. If NULL the parameter is not returned on error.


NetReplExportDirUnlock
 NetReplExportDirUnlock  QuickInfo

NetReplExportDirUnlock unlocks a directory so that replication from it can resume. This function decrements the lock reference count for the specified directory.

Security Requirements

Admin or server operator group membership is required to successfully execute NetReplExportDirUnlock.

NET_API_STATUS
NetReplExportDirUnlock (

LPTSTR servername,
LPTSTR dirname,
DWORD unlockforce
);
Parameters

servername

A pointer to a null-terminated Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

dirname

A pointer to a null-terminated Unicode string containing the directory name to unlock.

unlockforce

A value that indicates the force level to unlock the directory.

Force levels:

REPL_UNLOCK_NOFORCE

Unlocks the directory by decrementing the lock reference count. The lock reference count may or may not return to 0, so the directory could still be locked.

REPL_UNLOCK_FORCE

Unlocks the directory completely by removing all outstanding locks on the directory. The lock reference count is set to 0.


NetReplGetInfo
 NetReplGetInfo  QuickInfo

NetReplGetInfo retrieves the Replicator service configuration information.

Security Requirements

No special group membership is required to successfully execute NetReplGetInfo.

NET_API_STATUS
NetReplGetInfo (

LPTSTR servername,
DWORD level,
LPBYTE * bufptr
);
Parameters

servername

A pointer to a null-terminated Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

level

Level of information required. Only level 0 is valid.

bufptr

On return a pointer to the return information structure is written in the address pointed to by bufptr.


NetReplImportDirAdd
 NetReplImportDirAdd  QuickInfo

NetReplImportDirAdd registers an existing directory in the import path to receive replication from a master.

Security Requirements

Admin or replicator group membership is required to successfully execute NetReplImportDirAdd.

NET_API_STATUS
NetReplImportDirAdd (

LPTSTR servername,
DWORD level,
LPBYTE buf,
LPDWORD parm_err
);
Parameters

servername

A pointer to a null-terminated Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

level

Level of information to add. Only level 0 is valid.

buf

A pointer to a buffer containing the directory name.

parm_err

Optional pointer to a DWORD to return the index of the first parameter in error when ERROR_INVALID_PARAMETER is returned. If NULL the parameter is not returned on error.


NetReplImportDirDel
 NetReplImportDirDel  QuickInfo

NetReplImportDirDel deregisters directory so that it no longer receives updates from the master. Note that this function does not actually delete the directory from the file system. Also, the directory may be automatically re-registered by the Replicator service at any time. To prevent importing of a directory that is being exported by some Replicator service, use the NetReplImportDirLock function instead.

Security Requirements

Admin or replicator group membership is required to successfully execute NetReplImportDirDel.

NET_API_STATUS
NetReplImportDirDel (

LPTSTR servername,
LPTSTR dirname
);
Parameters

servername

A pointer to a null-terminated Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

dirname

A pointer to a null-terminated Unicode string containing the name of a replicated directory to deregister.


NetReplImportDirEnum
 NetReplImportDirEnum  QuickInfo

NetReplImportDirEnum lists the replicated directories in the import path.

Security Requirements

No special group membership is required to successfully execute NetReplImportDirEnum.

NET_API_STATUS
NetReplImportDirEnum (

LPTSTR servername,
DWORD level,
LPBYTE * bufptr,
DWORD prefmaxlen,
LPDWORD entriesread,
LPDWORD totalentries,
LPDWORD resumehandle
);
Parameters

servername

A pointer to a null-terminated Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

level

Level of information to return. Levels 0 or 1 are valid.

bufptr

On return, an array of the specified information structure is returned in the address pointed to by bufptr.

prefmaxlen

Preferred maximum length of returned data (in 8-bit bytes). A value of 0xFFFFFFFF indicates that all available entries should be returned.

entriesread

On return, the actual enumerated element count is located in the DWORD pointed to by entriesread.

totalentries

On return, the total number of entries that could have been enumerated from the current resume position is located in the DWORD pointed to by totalentries.

resumehandle

On return, a resume handle is stored in the DWORD pointed to by resumehandle, and is used to continue an existing use search. The handle should be zero on the first call and left unchanged for subsequent calls. If resumehandle is NULL, then no resume handle is stored.


NetReplImportDirGetInfo
 NetReplImportDirGetInfo  QuickInfo

NetReplImportDirGetInfo retrieves the status information on a client replicated directory.

Security Requirements

No special group membership is required to successfully execute NetReplImportDirGetInfo.

NET_API_STATUS
NetReplImportDirGetInfo (

LPTSTR servername,
LPTSTR dirname,
DWORD level,
LPBYTE * bufptr
);
Parameters

servername

A pointer to a null-terminated Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

dirname

A pointer to a null-terminated Unicode string containing the directory name to return control information about.

level

Level of information to return. Levels 0 and 1 are valid.

bufptr

On return a pointer to the return information structure is written in the address pointed to by bufptr.


NetReplImportDirLock
 NetReplImportDirLock  QuickInfo

NetReplImportDirLock locks a replicated directory so that replication to it can be suspended. This function increments the lock reference count for the specified directory.

Security Requirements

Admin or replicator group membership is required to successfully execute NetReplImportDirLock.

NET_API_STATUS
NetReplImportDirLock (

LPTSTR servername,
LPTSTR dirname
);
Parameters

servername

A pointer to a null-terminated Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

dirname

A pointer to a null-terminated Unicode string containing the directory name to lock.


NetReplImportDirUnlock
 NetReplImportDirUnlock  QuickInfo

NetReplImportDirUnlock unlocks a directory so that replication to it can resume. This function decrements the lock reference count for the specified directory.

Security Requirements

Admin or replicator group membership is required to successfully execute NetReplImportDirUnlock.

NET_API_STATUS
NetReplImportDirUnlock (

LPTSTR servername,
LPTSTR dirname,
DWORD unlockforce
);
Parameters

servername

A pointer to a null-terminated Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

dirname

A pointer to a null-terminated Unicode string containing the directory name to unlock.

unlockforce

A value that indicates the force level to unlock the directory.

Force levels:

REPL_UNLOCK_NOFORCE

Unlocks the directory by decrementing the lock reference count. The lock reference count may or may not return to 0, so the directory could still be locked.

REPL_UNLOCK_FORCE

Unlocks the directory completely by removing all outstanding locks on the directory. The lock reference count is set to 0.


NetReplSetInfo
 NetReplSetInfo  QuickInfo

NetReplSetInfo modifies the Replicator service configuration information.

Security Requirements

Admin or server operator group membership is required to successfully execute NetReplSetInfo.

NET_API_STATUS
NetReplSetInfo (

LPTSTR servername,
DWORD level,
LPBYTE buf,
LPDWORD parm_err
);
Parameters

servername

A pointer to a null-terminated Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

level

Level of information to set 0, 1000, 1001, 1002, and 1003 are valid levels.

buf

A pointer to a buffer containing the configuration information structure that corresponds to the specified level.

parm_err

Optional pointer to a DWORD to return the identifier of the first parameter in error when ERROR_INVALID_PARAMETER is returned. If NULL the parameter is not returned on error.


NetScheduleJobAdd
 NetScheduleJobAdd  QuickInfo

NetScheduleJobAdd submits a job to run at a computer at a specified time and date in future. NetScheduleJobAdd requires that the Schedule service be started at computer where job is submitted to.

Security Requirements

Admin group membership is required to successfully execute NetScheduleJobAdd on a remote server.

NET_API_STATUS
NetScheduleJobAdd (

LPWSTR Servername,
LPBYTE Buffer,
LPDWORD JobId
);
Parameters

Servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

Buffer

A pointer to a buffer containing AT_INFO data structure describing job to be submitted.

JobId

A pointer to a job identifier for a newly submitted job. This entry is valid only if function returns success.

By choosing values in AT_INFO appropriately one may submit jobs with different types of execution periodicity. If DaysOfMonth and DaysOfWeek are both zero, then job will be executed only once, the first time JobTime at server is reached. After being executed, the job will be deleted.

If one sets bits in DaysOfMonth and/or DaysOfWeek, but does not set the bit flag JOB_RUN_PERIODICALLY, a job will execute at JobTime once for each day listed in days bitmasks. After each execution, the corresponding bit in days bitmasks will be cleared. Once the last bit in days bitmasks is cleared, the job will be deleted.

If one sets bits in DaysOfMonth and/or DaysOfWeek, and at the same time sets the bit flag JOB_RUN_PERIODICALLY, a job will execute at JobTime whenever a day with corresponding bit in days bitmasks is reached. This job is thus executed periodically and does not get deleted as a result of repeated executions. The only way to delete this job is by an explicit call to NetScheduleJobDel( ).


NetScheduleJobDel
 NetScheduleJobDel  QuickInfo

NetScheduleJobDel deletes a range of jobs queued to run at a computer. NetScheduleJobDel requires that the Schedule service be started at computer where job deletion request is being sent to.

Security Requirements

Admin group membership is required to successfully execute NetScheduleJobDel on a remote server.

NET_API_STATUS
NetScheduleJobDel (

LPWSTR Servername,
DWORD MinJobId,
DWORD MaxJobId
);
Parameters

Servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

MinJobId

Minimum job identifier. Jobs with job identifier smaller than MinJobId will not be deleted.

MaxJobId

Maximum job identifier. Jobs with job identifier bigger than MaxJobId will not be deleted.

This function deletes all jobs whose job identifier is in the range MinJobId through MaxJobId. To delete all jobs at the server, one may call this function with MinJobId equal to 0 and MaxJobId equal to (DWORD) − 1. To delete just one particular job, one may choose MinJobId and MaxJobId both equal to that particular job's identifier.


NetScheduleJobEnum
 NetScheduleJobEnum  QuickInfo

NetScheduleJobEnum lists the jobs queued on a specified computer. NetScheduleJobEnum requires that the Schedule service be started.

Security Requirements

Admin group membership is required to successfully execute NetScheduleJobEnum on a remote server.

NET_API_STATUS
NetScheduleJobEnum(

LPWSTR Servername,
LPBYTE * PointerToBuffer,
DWORD PreferredMaximumLength,
LPDWORD EntriesRead,
LPDWORD TotalEntries,
LPDWORD ResumeHandle
);
Parameters

Servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

PointerToBuffer

On return a pointer to the return information structure is returned in the address pointed to by PointerToBuffer. The return information structure is an array of AT_ENUM data structures.

PreferredMaximumLength

Preferred maximum length of returned data (in 8-bit bytes).

EntriesRead

On return the actual enumerated element count is located in the DWORD pointed to by EntriesRead.

TotalEntries

On return the total number of entries that could have been enumerated from the current resume position is located in the DWORD pointed to by TotalEntries.

ResumeHandle

On return, a resume handle is stored in the DWORD pointed to by ResumeHandle, and is used to continue an job enumeration. The handle should be zero on the first call and left unchanged for subsequent calls. If ResumeHandle is NULL, then no resume handle is stored.

Note that each entry returned contains the JobId field of AT_ENUM structure. The value of this field may be used in calls that require job identifier argument, such as in a call to NetScheduleJobDel( ).


NetScheduleJobGetInfo
 NetScheduleJobGetInfo  QuickInfo

NetScheduleJobGetInfo retrieves information about a particular job queued on a specified computer. NetScheduleJobGetInfo requires that the Schedule service be started.

Security Requirements

Admin group membership is required to successfully execute NetScheduleJobGetInfo on a remote server.

NET_API_STATUS
NetScheduleJobGetInfo (

LPWSTR Servername,
DWORD JobId,
LPBYTE * PointerToBuffer
);
Parameters

Servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

JobId

A job identifier of a job in question.

PointerToBuffer

On return a pointer to the buffer containing AT_INFO data structure describing job in question.


NetServerDiskEnum
 NetServerDiskEnum  QuickInfo

NetServerDiskEnum retrieves a list of disk drives on a server.

Security Requirements

Admin or server operator group membership is required to successfully execute NetServerDiskEnum on a remote computer. No special group membership is required for local calls.

NET_API_STATUS
NetServerDiskEnum (

LPTSTR servername,
DWORD level,
LPBYTE * bufptr,
DWORD prefmaxlen,
LPDWORD entriesread,
LPDWORD totalentries,
LPDWORD resume_handle
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

level

Level of information required. 0 is the only valid level.

bufptr

On return a pointer to the return information structure is returned in the address pointed to by bufptr.

prefmaxlen

Prefered maximum length of returned data (in 8-bit bytes).

entriesread

On return the actual enumerated element count is located in the DWORD pointed to by entriesread.

totalentries

On return the total number of entries that could have been enumerated from the current resume position is located in the DWORD pointed to by totalentries.

resume_handle

On return, a resume handle is stored in the DWORD pointed to by resume_handle, and is used to continue an existing server disk search. The handle should be zero on the first call and left unchanged for subsequent calls. If resume_handle is NULL, then no resume handle is stored.


NetServerEnum
 NetServerEnum  QuickInfo

NetServerEnum lists all servers of the specified type(s) that are visible in the specified domain(s). For example, an application can call NetServerEnum to list all domain controllers only or all SQL servers only.

Note  If you require information on the type, name, and comment for a specific server, use the WNetEnumResource function.

Security Requirements

No special group membership is required to successfully execute NetServerEnum.

NET_API_STATUS
NetServerEnum (

LPTSTR servername,
DWORD level,
LPBYTE * bufptr,
DWORD prefmaxlen,
LPDWORD entriesread,
LPDWORD totalentries,
DWORD servertype,
LPTSTR domain,
LPDWORD resume_handle
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

level

Level of information required. 100 and 101 are valid.

bufptr

On return a pointer to the return information structure is returned in the address pointed to by bufptr.

prefmaxlen

Preferred maximum length of returned data (in 8-bit bytes).

entriesread

On return the actual enumerated element count is located in the doubleword pointed to by entriesread.

totalentries

return the total number of entries that could have been enumerated from the current resume position is located in the doubleword pointed to by totalentries.

servertype

A doubleword mask that filters server entries to return from the enumeration. The defined mask bits are:

Symbolic constant	Value	Meaning
SV_TYPE_WORKSTATION	0x00000001	All LAN Manager workstation
SV_TYPE_SERVER	0x00000002	All LAN Manager server
SV_TYPE_SQLSERVER	0x00000004	Any server running with Microsoft SQL Server
SV_TYPE_DOMAIN_CTRL	0x00000008	Primary domain controller
SV_TYPE_DOMAIN_BAKCTRL	0x00000010	Backup domain controller
SV_TYPE_TIMESOURCE	0x00000020	Server running the timesource service
SV_TYPE_AFP	0x00000040	Apple File Protocol servers
SV_TYPE_NOVELL	0x00000080	Novell servers
SV_TYPE_DOMAIN_MEMBER	0x00000100	Domain Member
SV_TYPE_PRINT	0x00000200	Server sharing print queue
SV_TYPE_DIALIN	0x00000400	Server running dialin service
SV_TYPE_XENIX_SERVER	0x00000800	Xenix server
SV_TYPE_NT	0x00001000	Windows NT server
SV_TYPE_WFW	0x00002000	Server running Windows for Workgroups
SV_TYPE_POTENTIAL_BROWSER	0x00010000	Server that can run the browser service
SV_TYPE_BACKUP_BROWSER	0x00020000	Server running a browser service as backup
SV_TYPE_MASTER_BROWSER	0x00040000	Server running the master browser service
SV_TYPE_DOMAIN_MASTER	0x00080000	Server running the domain master browser
SV_TYPE_DOMAIN_ENUM	0x80000000	Domain announcement
SV_TYPE_ALL	0xffffffff	All servers
domain

A pointer to a Unicode string containing the name of the domain for which a list of servers is to returned. The domain must be the primary domain, one of the other domains for the workstation or the logon domain.

resume_handle

 This parameter is reserved. It should be set to zero.


NetServerGetInfo
 NetServerGetInfo  QuickInfo

NetServerGetInfo retrieves information about the specified server.

Security Requirements

Admin or accounts, comm, print, or server operator group membership is required to successfully execute NetServerGetInfo at level 102 or higher. No special group membership is required for level 100 or level 101 calls.

NET_API_STATUS
NetServerGetInfo (

LPTSTR servername,
DWORD level,
LPBYTE * bufptr
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

level

Level of information required. 100, 101, and 102 are valid for all platforms. 302, 402, 403, and 502 are valid for the appropriate platform.

bufptr

On return a pointer to the return information structure is returned in the address pointed to by bufptr.


NetServerSetInfo
 NetServerSetInfo  QuickInfo

NetServerSetInfo sets a server's operating parameters; it can set them individually or collectively. This information is stored such that it remains in effect after the system has been reinitialized.

Security Requirements

Admin or server operator group membership is required to successfully execute NetServerSetInfo.

NET_API_STATUS
NetServerSetInfo (

LPTSTR servername,
DWORD level,
LPBYTE buf,
LPDWORD parm_err
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

level

Level of information to set. 100, 101, and 102 are valid for all platforms. 302, 402, 403, and 502 are valid for the appropriate platform. In addition, 1001 − 1006, 1009 − 1011, 1016 − 1018, 1021, 1022, 1028, 1029, and 1037 − 1043 are valid based on the restrictions for downlevel systems described preceding.

buf

A pointer to a buffer containing the server information.

parm_err

Optional pointer to a DWORD to return the index of the first parameter in error when ERROR_INVALID_PARAMETER is returned. If NULL the parameter is not returned on error.


NetServerTransportAdd
 NetServerTransportAdd  QuickInfo

NetServerTransportAdd binds the server to the transport.

Security Requirements

Admin group membership is required to successfully execute NetServerTransportAdd.

NET_API_STATUS
NetServerTransportAdd (

LPTSTR servername,
DWORD level,
LPBYTE bufptr
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

level

Level of information required. Only 0 is valid.

bufptr

A pointer to a buffer containing the server transport information structure.


NetServerTransportDel
 NetServerTransportDel  QuickInfo

NetServerTransportDel unbinds the transport from the server.

Security Requirements

Admin group membership is required to successfully execute NetServerTransportDel.

NET_API_STATUS
NetServerTransportDel (

LPWSTR servername,
LPWSTR transportname
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

transportname

A pointer to a Unicode string containing the name of the transport from which to unbind.


NetServerTransportEnum
 NetServerTransportEnum  QuickInfo

NetServerTransportEnum supplies information about transports that are managed by the server.

Security Requirements

No special group membership is required to successfully execute NetServerTransportEnum.

NET_API_STATUS
NetServerTransportEnum (

LPTSTR servername,
DWORD level,
LPBYTE * bufptr,
DWORD prefmaxlen,
LPDWORD entriesread,
LPDWORD totalentries,
LPDWORD resumehandle
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

level

Level of information required. Only 0 is valid.

bufptr

On return a pointer to the return information structure is returned in the address pointed to by bufptr.

prefmaxlen

Preferred maximum length of returned data (in 8-bit bytes).

entriesread

On return the actual enumerated element count is located in the DWORD pointed to by entriesread.

totalentries

On return the total number of entries that could have been enumerated from the current resume position is located in the DWORD pointed to by totalentries.

resumehandle

On return, a resume handle is stored in the DWORD pointed to by resumehandle, and is used to continue an existing server transport search. The handle should be zero on the first call and left unchanged for subsequent calls. If resumehandle is NULL, then no resume handle is stored.


NetServiceControl
 NetServiceControl  QuickInfo

NetServiceControl controls the operations of network services.

Security Requirements

Admin, Power User or Server Operator group membership is required to successfully execute NetServiceControl unless the value of the opcode parameter is SERVICE_CTRL_INTERROGATE. In that case, no special group membership is required.

NET_API_STATUS
NetServiceControl (

LPTSTR servername,
LPTSTR service,
DWORD opcode,
DWORD arg,
LPBYTE * bufptr
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

service

A pointer to a Unicode string containing the name of the service to receive the control command.

opcode

Control code to send to service:

Value	Meaning
SERVICE_CTRL_INTERROGATE	Obtain the status of the service
SERVICE_CTRL_PAUSE	Pause the service
SERVICE_CTRL_CONTINUE	Continue the paused service
SERVICE_CTRL_UNINSTALL	Stop the service
arg

Service specific contol argument to send to service

bufptr

A pointer to the return information structure is returned in the address pointed to by bufptr.


NetServiceEnum
 NetServiceEnum  QuickInfo

NetServiceEnum retrieves information about all started services, including paused services.

Security Requirements

No special group membership is required to successfully execute NetServiceEnum.

NET_API_STATUS
NetServiceEnum (

LPTSTR servername,
DWORD level,
LPBYTE * bufptr,
DWORD prefmaxlen,
LPDWORD entriesread,
LPDWORD totalentries,
LPDWORD resume_handle
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

level

Level of information required, 0, 1, and 2 are valid.

bufptr

On return a pointer to the return information structure is returned in the address pointed to by bufptr.

prefmaxlen

Prefered maximum length of returned data (in 8-bit bytes).

entriesread

On return the actual enumerated element count is located in the DWORD pointed to by entriesread.

totalentries

On return the total number of entries that could have been enumerated from the current resume position is located in the DWORD pointed to by totalentries.

resume_handle

On return, a resume handle is stored in the DWORD pointed to by resume_handle, and is used to continue an existing service search. The handle should be zero on the first call and left unchanged for subsequent calls. If resume_handle is NULL, then no resume handle is stored.


NetServiceGetInfo
 NetServiceGetInfo  QuickInfo

NetServiceGetInfo retrieves information about a particular started service.

Security Requirements

No special group membership is required to successfully execute NetServiceGetInfo.

NET_API_STATUS
NetServiceGetInfo (

LPTSTR servername,
LPTSTR service,
DWORD level,
LPBYTE * bufptr
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

service

A pointer to a Unicode string containing the name of the service.

level

Level of information required. 0, 1, and 2 are valid.

bufptr

On return a pointer to the return information structure is returned in the address pointed to by bufptr.


NetServiceInstall
 NetServiceInstall  QuickInfo

NetServiceInstall starts a network service.

Security Requirements

Admin, Power User or Server Operator group membership is required to successfully execute NetServiceInstall.

NET_API_STATUS
NetServiceInstall (

LPTSTR servername,
LPTSTR service,
DWORD argc,
LPTSTR argv[ ],
LPBYTE * bufptr
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

service

A pointer to a Unicode string containing the name of the service to start.

bufptr

On return a pointer to a SERVICE_INFO_2 structure is returned in the address pointed to by bufptr.

cmdargs

A pointer to a set of command line arguments to pass to the starting service as command line arguments.


NetSessionDel
 NetSessionDel  QuickInfo

NetSessionDel ends a session between a server and a workstation.

Security Requirements

Admin or server operator group membership is required to successfully execute NetSessionDel.

NET_API_STATUS
NetSessionDel (

LPTSTR servername,
LPTSTR UncClientName,
LPTSTR username,
DWORD reserved
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

UncClientName

A pointer to a Unicode string containing the computer name of the client to disconnect. If UncClientName is NULL, then all the sessions of the user in username will be deleted on the server specified.

username

A pointer to a Unicode string containing the name of the user whose session is to be terminated. A NULL indicates that all users' sessions from the client name specified are to be terminated.

reserved

Reserved, must be zero.


NetSessionEnum
 NetSessionEnum  QuickInfo

NetSessionEnum provides information about all current sessions.

Security Requirements

Admin or server operator group membership is required to successfully execute NetSessionEnum at level 1 or level 2. No special group membership is required for level 0 or level 10 calls.

NET_API_STATUS
NetSessionEnum (

LPTSTR servername,
LPTSTR UncClientName,
LPTSTR username,
DWORD level,
LPBYTE * bufptr,
DWORD prefmaxlen,
LPDWORD entriesread,
LPDWORD totalentries,
LPDWORD resume_handle
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

UncClientName

A pointer to a Unicode string containing the name of the computer session for which information is to be returned. A NULL pointer or string specifies that all computer sessions on the server are to be enumerated.

username

A pointer to a Unicode string containing the name of the the user for which to enumerate the sessions. A NULL pointer or string specifies that sessions for all users are to be enumerated.

level

Level of information required. 0, 1, 2, and 10 are valid.

bufptr

On return a pointer to the return information structure is returned in the address pointed to by bufptr.

prefmaxlen

Prefered maximum length of returned data (in 8-bit bytes).

entriesread

On return the actual enumerated element count is located in the DWORD pointed to by entriesread.

totalentries

On return the total number of entries that could have been enumerated from the current resume position is located in the DWORD pointed to by totalentries.

resume_handle

On return, a resume handle is stored in the DWORD pointed to by resume_handle, and is used to continue an existing session search. The handle should be zero on the first call and left unchanged for subsequent calls. If resume_handle is NULL, then no resume handle is stored.


NetSessionGetInfo
 NetSessionGetInfo  QuickInfo

NetSessionGetInfo retrieves information about a session established between a particular server and workstation.

Security Requirements

Admin or server operator group membership is required to successfully execute NetSessionGetInfo at level 1 or level 2. No special group membership is required for level 0 or level 10 calls.

NET_API_STATUS
NetSessionGetInfo (

LPTSTR servername,
LPTSTR UncClientName,
LPTSTR username,
DWORD level,
LPBYTE * bufptr
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

UncClientName

A pointer to a Unicode string containing the name of the computer session for which information is to be returned. This field cannot be NULL.

username

A pointer to a Unicode string containing the name of the user whose session information is to be returned. This field cannot be NULL.

level

Level of information required. 0, 1, 2, and 10 are valid.

bufptr

On return a pointer to the return information structure is returned in the address pointed to by bufptr.


NetShareAdd
 NetShareAdd  QuickInfo

NetShareAdd shares a server resource.

Security Requirements

Admin or comm, print, or server operator group membership is required to successfully execute NetShareAdd. The print operator can add only printer queues. The comm operator can add only communication-device queues.

NET_API_STATUS
NetShareAdd (

LPTSTR servername,
DWORD level,
LPBYTE buf,
LPDWORD parm_err
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

level

Level of information provided. Must be 2 or 502.

buf

A pointer to a buffer containing the share information structure.

parm_err

Optional pointer to a DWORD to return the index of the first parameter in error when ERROR_INVALID_PARAMETER is returned. If NULL the parameter is not returned on error.


NetShareCheck
 NetShareCheck  QuickInfo

NetShareCheck checks whether or not a server is sharing a device.

Security Requirements

No special group membership is required to successfully execute NetShareCheck.

NET_API_STATUS
NetShareCheck (

LPTSTR servername,
LPTSTR device,
LPDWORD type
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

device

A pointer to a Unicode string containing the name of the device to check for shared access.

type

On return the address pointed to by the type parameter contains the type of share the device is offered with. This field is set only if success was returned.


NetShareDel
 NetShareDel  QuickInfo

NetShareDel deletes a share name from a server's list of shared resources, disconnecting all connections to the shared resource.

Security Requirements

Admin or comm, print, or server operator group membership is required to successfully execute NetShareDel. The print operator can delete only printer queues. The comm operator can delete only communication-device queues.

NET_API_STATUS
NetShareDel (

LPTSTR servername,
LPTSTR netname,
DWORD reserved
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

netname

A pointer to a Unicode string containing the netname of the share to delete.

reserved

Reserved, must be zero.


NetShareEnum
 NetShareEnum  QuickInfo

NetShareEnum retrieves information about each shared resource on a server. The NetShareEnum function is obsolete. It is provided only for compatibility with LAN Manager and 16-bit versions of Windows. Win32-based applications should use the WNetEnumResource function.

Security Requirements

Admin or comm, print, or server operator group membership is required to successfully execute NetShareEnum at level 2. No special group membership is required for level 0 or level 1 calls.

NET_API_STATUS
NetShareEnum (

LPTSTR servername,
DWORD level,
LPBYTE * bufptr,
DWORD prefmaxlen,
LPDWORD entriesread,
LPDWORD totalentries,
LPDWORD resume_handle
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

level

Level of information required. 0, 1, 2, and 502 are valid.

bufptr

On return a pointer to the return information structure is returned in the address pointed to by bufptr.

prefmaxlen

Prefered maximum length of returned data (in 8-bit bytes).

entriesread

On return the actual enumerated element count is located in the DWORD pointed to by entriesread.

totalentries

On return the total number of entries that could have been enumerated from the current resume position is located in the DWORD pointed to by totalentries.

resume_handle

On return, a resume handle is stored in the DWORD pointed to by resume_handle, and is used to continue an existing share search. The handle should be zero on the first call and left unchanged for subsequent calls. If resume_handle is NULL, then no resume handle is stored.


NetShareGetInfo
 NetShareGetInfo  QuickInfo

NetShareGetInfo retrieves information about a particular shared resource on a server.

Security Requirements

Admin or comm, print, or server operator group membership is required to successfully execute NetShareGetInfo at level 2. No special group membership is required for level 0 or level 1 calls.

NET_API_STATUS
NetShareGetInfo (

LPTSTR servername,
LPTSTR netname,
DWORD level,
LPBYTE * bufptr
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

netname

A pointer to a Unicode string containing the netname of the share to return information on.

level

Level of information required. 0, 1, 2, and 502 are valid.

bufptr

On return a pointer to the return information structure is returned in the address pointed to by bufptr.


NetShareSetInfo
 NetShareSetInfo  QuickInfo

NetShareSetInfo sets the parameters of a shared resource.

Security Requirements

Admin or comm, print, or server operator group membership is required to successfully execute NetShareSetInfo. The print operator can set information only about printer queues. The comm operator can set information only about communication-device queues.

NET_API_STATUS
NetShareSetInfo (

LPTSTR servername,
LPTSTR netname,
DWORD level,
LPBYTE buf,
LPDWORD parm_err
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

netname

A pointer to a Unicode string containing the netname of the share to set information on.

level

Level of information to set. 1, 2, 502, 1004 − 1006, and 1501 are valid.

buf

A pointer to a buffer containing the share information.

parm_err

Optional pointer to a DWORD to return the index of the first parameter in error when ERROR_INVALID_PARAMETER is returned. If NULL the parameter is not returned on error.


NetStatisticsGet
 NetStatisticsGet  QuickInfo

NetStatisticsGet retrieves operating statistics for a service. Currently, only the Workstation and Server services are supported.

Security Requirements

Admin or server operator group membership is required to successfully execute NetStatisticsGet on a remote server.

NET_API_STATUS
NetStatisticsGet (

LPTSTR server,
LPTSTR service,
DWORD level,
DWORD options,
LPBYTE * bufptr
);
Parameters

server

Points to a Unicode string that contains the name of the server on which to execute NetConfigGet. A NULL pointer or NULL string specifies the local computer.

service

Points to a Unicode string that contains the name of the service about which to get the statistics. Only the values SERVER and WORKSTATION are currently allowed.

level

Specifies the level of detail requested; must be 0.

options

Must be 0.

bufptr

On return a pointer to the returned information is returned in the address pointed to by bufptr.


NetUseAdd
 NetUseAdd  QuickInfo

NetUseAdd establishes a connection between a local or NULL device name and a shared resource by redirecting the local or NULL (UNC) device name to the shared resource. The NetUseAdd function is obsolete. It is provided only for compatibility with LAN Manager and 16-bit versions of Windows. Win32-based applications should use the WNetAddConnection2 function.

Security Requirements

No special group membership is required for this call. This function cannot be executed on a remote server.

NET_API_STATUS
NetUseAdd (

LPTSTR UncServerName,
DWORD Level,
LPBYTE Buf,
LPDWORD ParmError
);
Parameters

UncServerName

Must be NULL.

Level

Level of information to set. 1 and 2 are valid.

Buf

A pointer to a buffer containing the use information structure.

ParmError

Optional pointer to a DWORD to return the index of the first parameter in error when ERROR_INVALID_PARAMETER is returned. If NULL the parameter is not returned on error.


NetUseDel
 NetUseDel  QuickInfo

NetUseDel ends a connection to a shared resource. The NetUseDel function is obsolete. It is provided only for compatibility with LAN Manager and 16-bit versions of Windows. Win32-based applications should use the WNetCancelConnection2 function.

Security Requirements

No special group membership is required for this call. This function cannot be executed on a remote server.

NET_API_STATUS
NetUseDel (

LPTSTR UncServerName,
LPTSTR UseName,
DWORD ForceCond
);
Parameters

UncServerName

Must be NULL.

UseName

A pointer to a Unicode string containing the path of the use to delete.

ForceCond

Level of force to use in deleting the use.


NetUseEnum
 NetUseEnum  QuickInfo

NetUseEnum lists all current connections between the local computer and resources on remote servers. The NetUseEnum function is obsolete. It is provided only for compatibility with LAN Manager and 16-bit versions of Windows. Win32-based applications should use the WNetEnumResource function.

Security Requirements

No special group membership is required for this call. This function cannot be executed on a remote server.

NET_API_STATUS
NetUseEnum (

LPTSTR UncServerName,
DWORD Level,
LPBYTE * BufPtr,
DWORD PreferredMaximumSize,
LPDWORD EntriesRead,
LPDWORD TotalEntries,
LPDWORD ResumeHandle
);
Parameters

UncServerName

Must be NULL.

Level

Level of information provided. Must be 0, 1, or 2.

BufPtr

On return a pointer to the return information structure is returned in the address pointed to by BufPtr.

PreferredMaximumSize

Prefered maximum length of returned data (in 8-bit bytes).

EntriesRead

On return the actual enumerated element count is located in the DWORD pointed to by EntriesRead.

TotalEntries

On return the total number of entries that could have been enumerated from the current resume position is located in the DWORD pointed to by TotalEntries.

ResumeHandle

On return, a resume handle is stored in the DWORD pointed to by ResumeHandle, and is used to continue an existing use search. The handle should be zero on the first call and left unchanged for subsequent calls. If ResumeHandle is NULL, then no resume handle is stored.


NetUseGetInfo
 NetUseGetInfo  QuickInfo

NetUseGetInfo retrieves information about a connection to a shared resource. The NetUseGetInfo function is obsolete. It is provided only for compatibility with LAN Manager and 16-bit versions of Windows. Win32-based applications should use the WNetGetConnection function.

Security Requirements

No special group membership is required for this call. This function cannot be executed on a remote server.

NET_API_STATUS
NetUseGetInfo (

LPTSTR UncServerName,
LPTSTR UseName,
DWORD Level,
LPBYTE * BufPtr
);
Parameters

UncServerName

Must be NULL.

UseName

A pointer to a Unicode string containing the local or remote name active use to return information on.

Level

Level of information required. 0, 1, and 2 are valid.

BufPtr

On return a pointer to the return information structure is returned in the address pointed to by BufPtr.


NetUserAdd
 NetUserAdd  QuickInfo

NetUserAdd adds a user account.

Security Requirements

Admin or account operator group membership is required to successfully execute NetUserAdd.

NET_API_STATUS
NetUserAdd (

LPWSTR servername,
DWORD level,
LPBYTE buf,
LPDWORD parm_err
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

level

Level of information provided. Must be 1, 2, or 3.

buf

A pointer to a buffer containing the user information structure.

parm_err

Optional pointer to a DWORD to return the index of the first parameter in error when ERROR_INVALID_PARAMETER is returned. If NULL the parameter is not returned on error.


NetUserChangePassword [New - Windows NT]
 NetUserChangePassword  QuickInfo

[New - Windows NT]

The NetUserChangePassword function changes a user's password for a specified network server or domain.

Security Requirements

A server or domain can be configured to require that a user log on to change the password on a user account. If that is the case, you need administrator or account operator access to change the password for another user acount. If logging on is not required, you can change the password for any user account, so long as you know the current password.

NET_API_STATUS NetUserChangePassword(

LPWSTR  domainname,	// pointer to server or domain name string
LPWSTR  username,	// pointer to user name string
LPWSTR  oldpassword,	// pointer to old password string
LPWSTR  newpassword,	// pointer to new password string
);
Parameters

domainname

Pointer to a null-terminated Unicode string that specifies the name of a remote server or domain. The NetUserChangePassword function changes the user's password on that remote server or domain.

A domainname value of NULL specifies the logon domain of the caller.

username

Pointer to a null-terminated Unicode string that specifies a user name. The NetUserChangePassword function changes the password for that user.

A username value of NULL specifies the logon user name of the caller.

oldpassword

Pointer to a null-terminated Unicode string that specifies the user's old password on the server or domain.

newpassword

Pointer to a null-terminated Unicode string that specifies the user's new password on the server or domain.

Return Value

The function returns a NET_API_STATUS value.


NetUserDel
 NetUserDel  QuickInfo

NetUserDel deletes a user account from the accounts database.

Security Requirements

Admin or account operator group membership is required to successfully execute NetUserDel.

NET_API_STATUS
NetUserDel (

LPWSTR servername,
LPWSTR username
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

username

A pointer to a Unicode string containing the name of the user account to delete.


NetUserEnum
 NetUserEnum  QuickInfo

NetUserEnum provides resumable enumeration of information about each user account in a domain.

Security Requirements

Admin or account operator group membership is required to successfully execute NetUserEnum at levels 1 and 2. No special group membership is required at level 0 or 10.

NET_API_STATUS
NetUserEnum (

LPWSTR servername,
DWORD level,
DWORD filter,
LPBYTE * bufptr,
DWORD prefmaxlen,
LPDWORD entriesread,
LPDWORD totalentries,
LPDWORD resumehandle
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

level

Level of information required. 0, 1, 2, 3, 10, 11, and 20 are valid.

filter

Specifies a filter of account types ot enumerate. 0 implies all account types. Allowable values are:

FILTER_TEMP_DUPLICATE_ACCOUNTS

FILTER_NORMAL_ACCOUNT

FILTER_INTERDOMAIN_TRUST_ACCOUNT

FILTER_WORKSTATION_TRUST_ACCOUNT

FILTER_SERVER_TRUST_ACCOUNT

bufptr

On return a pointer to the return information structure is returned in the address pointed to by bufptr.

prefmaxlen

Preferred maximum length of returned data (in 8-bit bytes).

entriesread

On return the actual enumerated element count is located in the DWORD pointed to by entriesread.

totalentries

On return the total number of entries that could have been enumerated from the current resume position is located in the DWORD pointed to by totalentries. EXCEPTION: If the call is to a computer that is running OS/2 LANMAN, the totalentries will always reflect the total number of entries in the database no matter where it is in the resume sequence.

resumehandle

On return, a resume handle is stored in the DWORD pointed to by resumehandle and is used to continue an existing user search. The handle should be zero on the first call and left unchanged for subsequent calls. If resumehandle is NULL, then no resume handle is stored.


NetUserGetGroups
 NetUserGetGroups  QuickInfo

NetUserGetGroups retrieves a list of global groups to which a specified user belongs.

Security Requirements

Admin or account operator group membership is required to successfully execute NetUserGetGroups.

NET_API_STATUS
NetUserGetGroups (

LPWSTR servername,
LPWSTR username,
DWORD level,
LPBYTE * bufptr,
DWORD prefmaxlen,
LPDWORD entriesread,
LPDWORD totalentries
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

username

A pointer to a Unicode string containing the name of the user to return global group membership for.

level

Level of information required. Only 0 or 1 are valid.

bufptr

On return a pointer to the return information structure is returned in the address pointed to by bufptr. The returned information is an array of GROUP_USERS_INFO_x structures.

prefmaxlen

Prefered maximum length of returned data (in 8-bit bytes).

entriesread

On return the actual enumerated element count is located in the DWORD pointed to by entriesread.

totalentries

On return the total number of entries that could have been enumerated from the current resume position is located in the b pointed to by totalentries.


NetUserGetInfo
 NetUserGetInfo  QuickInfo

NetUserGetInfo retrieves information about a particular user account on a server.

Security Requirements

No special group membership is required to successfully execute NetUserGetInfo. This is a change from LAN Manager, which required administer or account operator privilege to call this function at information levels above 0 (except for the user's own account, which could use level 11).

NET_API_STATUS
NetUserGetInfo (

LPWSTR servername,
LPWSTR username,
DWORD level,
LPBYTE * bufptr
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

username

A pointer to a Unicode string containing the name of the user account on which to return information.

level

Level of information required. 0, 1, 2, 3,10,11, and 20 are valid.

bufptr

A pointer to the return information structure is returned in the address pointed to by bufptr.


NetUserGetLocalGroups
 NetUserGetLocalGroups  QuickInfo

NetUserGetLocalGroups retrieves a list of local groups to which a specified user belongs.

Security Requirements

Admin or account operator group membership is required to successfully execute NetUserGetLocalGroups.

NET_API_STATUS
NetUserGetLocalGroups (

LPWSTR servername,
LPWSTR username,
DWORD level,
DWORD flags,
LPBYTE * bufptr,
DWORD prefmaxlen,
LPDWORD entriesread,
LPDWORD totalentries
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

username

A pointer to a Unicode string containing the name of the user to return global group membership for.

level

Level of information required. Only 0 is valid.

flags

Bitmask of flags. Currently, only LG_INCLUDE_INDIRECT is defined. If this bit is set, the function will also return localgroups the user is a member of indirectly (i.e., by the virtue of being in a globalgroup that itself is a member of one or more localgroups).

bufptr

On return a pointer to the return information structure is returned in the address pointed to by bufptr. The returned information is an array of LOCALGROUP_USERS_INFO_0 structures.

prefmaxlen

Preferred maximum length of returned data (in 8-bit bytes).

entriesread

On return the actual enumerated element count is located in the DWORD pointed to by entriesread.

totalentries

On return the total number of entries that could have been enumerated from the current resume position is located in the DWORD pointed to by totalentries.


NetUserModalsGet
 NetUserModalsGet  QuickInfo

NetUserModalsGet retrieves global information for all users and global groups in the user account database.

Security Requirements

Admin or account operator group membership is required to successfully execute NetUserModalsGet.

NET_API_STATUS
NetUserModalsGet (

LPWSTR servername,
DWORD level,
LPBYTE * bufptr
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

level

Level of information required. 0, 1, and 2 are valid.

bufptr

A pointer to the return information structure is returned in the address pointed to by bufptr.


NetUserModalsSet
 NetUserModalsSet  QuickInfo

NetUserModalsSet sets global information for all users and global groups in the user account database.

Security Requirements

Admin or account operator group membership is required to successfully execute NetUserModalsSet.

NET_API_STATUS
NetUserModalsSet (

LPWSTR servername,
DWORD level,
LPBYTE buf,
LPDWORD parm_err
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

username

A pointer to a Unicode string containing the name of the user account to set information on.

level

Level of information to set. 0, 1, and 2 are valid.

buf

A pointer to a buffer containing the user modals information.

parm_err

Optional pointer to a DWORD to return the index of the first parameter in error when ERROR_INVALID_PARAMETER is returned. If NULL the parameter is not returned on error.


NetUserSetGroups
 NetUserSetGroups  QuickInfo

NetUserSetGroups sets global group memberships for a specified user account.

Security Requirements

Admin or account operator group membership is required to successfully execute NetUserSetGroups.

NET_API_STATUS
NetUserSetGroups (

LPWSTR servername,
LPWSTR username,
DWORD level,
LPBYTE buf,
DWORD num_entries
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

username

A pointer to a Unicode string containing the name of the user to set global group memberships for.

level

Level of information required. Only 0 or 1 are valid.

buf

A pointer to an array of global groups information structures.

num_entries

Number of global group information structures contained in the array pointed to by buf.


NetUserSetInfo
 NetUserSetInfo  QuickInfo

NetUserSetInfo sets the parameters of a user account.

Security Requirements

Admin or account operator group membership is required to successfully execute NetUserSetInfo. A user may call NetUserSetInfo to set certain information on his/her own account.

NET_API_STATUS
NetUserSetInfo (

LPWSTR servername,
LPWSTR username,
DWORD level,
LPBYTE buf,
LPDWORD parm_err
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

username

A pointer to a Unicode string containing the name of the user account to set information on.

level

Level of information to set. 0, 1, 2, 3, or 20.

buf

A pointer to a buffer containing the user information.

parm_err

Optional pointer to a DWORD to return the index of the first parameter in error when ERROR_INVALID_PARAMETER is returned. If NULL the parameter is not returned on error.


NetWkstaGetInfo
 NetWkstaGetInfo  QuickInfo

NetWkstaGetInfo returns information about the configuration elements for a workstation.

Security Requirements

Security requirements are described with the data structures for the information levels above.

NET_API_STATUS
NetWkstaGetInfo (

LPTSTR servername,
DWORD level,
LPBYTE * bufptr
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

level

Level of information required. 100, 101, 102, 302, 402, and 502 are valid.

bufptr

On return a pointer to the return information structure is returned in the address pointed to by bufptr.


NetWkstaSetInfo
 NetWkstaSetInfo  QuickInfo

NetWkstaSetInfo configures a workstation. This information is stored such that it remains in effect after the system has been reinitialized.

Security Requirements

Admin group membership is required to successfully execute NetWkstaSetInfo.

NET_API_STATUS
NetWkstaSetInfo (

LPTSTR servername,
DWORD level,
LPBYTE buf,
LPDWORD parm_err
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

level

Level of information to set. 100, 101, 102, 302, 402, and 502 are valid. In addition, 1010 − 1013, 1018, 1023, 1027, 1028, 1032, 1033, 1035, and 1041-1062 are valid based on the restrictions mentioned preceding.

buf

A pointer to a buffer containing the workstation information.

parm_err

Optional pointer to a DWORD to return the index of the first parameter in error when ERROR_INVALID_PARAMETER is returned. If NULL the parameter is not returned on error.


NetWkstaTransportAdd
 NetWkstaTransportAdd  QuickInfo

NetWkstaTransportAdd binds the redirector to the transport.

Security Requirements

Admin group membership is required to successfully execute NetWkstaTransportAdd.

NET_API_STATUS
NetWkstaTransportAdd (

LPTSTR servername,
DWORD level,
LPBYTE buf
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

level

Level of information required. Only 0 is valid.

buf

A pointer to a buffer containing the server transport information structure.


NetWkstaTransportDel
 NetWkstaTransportDel  QuickInfo

NetWkstaTransportDel unbinds the transport from the redirector.

Security Requirements

Admin group membership is required to successfully execute NetWkstaTransportDel.

NET_API_STATUS
NetWkstaTransportDel (

LPTSTR servername,
LPTSTR transportname,
DWORD ucond
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

transportname

A pointer to a Unicode string containing the name of the transport from which to unbind.

ucond

Force level to delete connections on the transport binding.


NetWkstaTransportEnum
 NetWkstaTransportEnum  QuickInfo

NetWkstaTransportEnum supplies information about transports that are managed by the redirector.

Security Requirements

No special group membership is required to successfully execute NetWkstaTransportEnum.

NET_API_STATUS
NetWkstaTransportEnum (

LPTSTR servername,
DWORD level,
LPBYTE * bufptr,
DWORD prefmaxlen,
LPDWORD entriesread,
LPDWORD totalentries,
LPDWORD resumehandle
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

level

Level of information required. Only 0 is valid.

bufptr

On return a pointer to the return information structure is returned in the address pointed to by bufptr.

prefmaxlen

Preferred maximum length of returned data (in 8-bit bytes).

entriesread

On return the actual enumerated element count is located in the DWORD pointed to by entriesread.

totalentries

On return the total number of entries that could have been enumerated from the current resume position is located in the DWORD pointed to by totalentries.

resumehandle

On return, a resume handle is stored in the DWORD pointed to by resumehandle, and is used to continue an existing workstation transport search. The handle should be zero on the first call and left unchanged for subsequent calls. If resumehandle is NULL, then no resume handle is stored.


NetWkstaUserEnum
 NetWkstaUserEnum  QuickInfo

NetWkstaUserEnum lists information about all current users on the workstation.

Security Requirements

Admin group membership is required to successfully execute NetWkstaUserEnum both locally and on a remote server.

NET_API_STATUS
NetWkstaUserEnum (

LPTSTR servername,
DWORD level,
LPBYTE * bufptr,
DWORD prefmaxlen,
LPDWORD entriesread,
LPDWORD totalentries,
LPDWORD resumehandle
);
Parameters

servername

A pointer to a Unicode string containing the name of the remote server on which the function is to execute. A NULL pointer or string specifies the local computer.

level

Level of information provided. Must be 0 or 1.

bufptr

On return a pointer to the return information structure is returned in the address pointed to by bufptr.

prefmaxlen

Prefered maximum length of returned data (in 8-bit bytes).

entriesread

On return the actual enumerated element count is located in the DWORD pointed to by entriesread.

totalentries

On return the total number of entries that could have been enumerated from the current resume position is located in the DWORD pointed to by totalentries.

resumehandle

On return, a resume handle is stored in the DWORD pointed to by resumehandle, and is used to continue an existing use search. The handle should be zero on the first call and left unchanged for subsequent calls. If resumehandle is NULL, then no resume handle is stored.


NetWkstaUserGetInfo
 NetWkstaUserGetInfo  QuickInfo

NetWkstaUserGetInfo returns the user-specific information about the configuration elements for a workstation.

Security Requirements

Security requirements are described with the data structures for the information levels above. This function only works locally.

NET_API_STATUS
NetWkstaUserGetInfo (

LPTSTR reserved,
DWORD level,
LPBYTE * bufptr
);
Parameters

reserved

This field must be set to NULL.

level

Level of information required. 0 and 1 are valid.

bufptr

On return a pointer to the return information structure is returned in the address pointed to by bufptr.


NetWkstaUserSetInfo
 NetWkstaUserSetInfo  QuickInfo

NetWkstaUserSetInfo sets the user-specific information about the configuration elements for a workstation.

Security Requirements

Security requirements are described with the data structures for the information levels above. This function only works locally.

NET_API_STATUS
NetWkstaUserSetInfo (

LPTSTR reserved,
DWORD level,
LPBYTE * buf,
LPDWORD parm_err
);
Parameters

reserved

This field must be set to zero.

level

Level of information required. 0 and 1 are valid.

buf

On return a pointer to the return information structure is returned in the address pointed to by buf.

parm_err

Optional pointer to a DWORD to return the index of the first parameter in error when ERROR_INVALID_PARAMETER is returned. If NULL the parameter is not returned on error.


NotifyBootConfigStatus
 NotifyBootConfigStatus  QuickInfo  Overview  Group

The NotifyBootConfigStatus function notifies the service control manager as to the acceptability of the configuration that booted the system.

An acceptable configuration triggers the storage of that configuration as the last-known good configuration; an unacceptable configuration triggers a system reboot.

BOOL NotifyBootConfigStatus(

BOOL  BootAcceptable	// indicates acceptability of boot configuration
);
Parameters

BootAcceptable

Specifies whether the configuration that booted the system is acceptable. If this parameter's value is TRUE, the service control manager saves the configuration that booted the system as the last-known good configuration. If the parameter's value is FALSE, the system immediately reboots, using the previously saved last-known good configuration.

Return Value

If the BootAcceptable parameter is FALSE, the function does not return.

If the last-known good configuration was successfully saved, the return value is TRUE.

If an error occurs, the return value is FALSE. To get extended error information, call GetLastError.

Errors

The following error codes may be set by the service control manager. Other error codes may be set by the registry functions that are called by the service control manager to deal with the configuration registry.

Value	Meaning
ERROR_ACCESS_DENIED	The caller does not have permission to perform this operation.  A hard-coded DACL associated with the service control manager object determines who can perform a NotifyBootConfigStatus operation. Only the operating system and members of the local adminstrators group can do so.
Remarks

The NotifyBootConfigStatus function is used to save the configuration from which  a running system was booted. This is a useful thing to do once the configuration has been checked and found to be acceptable. In this way, the latest acceptable modifications to the configuration are saved away as the last-known good configuration.

If the boot configuration is found to be unacceptable, this function can be called to instigate a reboot with the existing last-known good configuration. This function can only be called by a process running in the LocalSystem or the Administrator's security context.


NotifyChangeEventLog
 NotifyChangeEventLog  QuickInfo  Overview  Group

The NotifyChangeEventLog function lets an application receive notification when an event is written to the event log file specified by hEventLog. When the event is written to the event log file, the function causes the event object specified by hEvent to become signaled.

BOOL NotifyChangeEventLog(

HANDLE  hEventLog,	// special default locale value to be converted
HANDLE  hEvent	// special default locale value to be converted
);
Parameters

hEventLog

Handle to an event log file, obtained by calling OpenEventLog. When an event is written to this log file, the event specified by hEvent becomes signaled.

hEvent

A handle to a Win32 event. This is the event that becomes signaled when an event is written to the event log file specified by hEventLog.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The NotifyChangeEventLog function does not work with remote handles. If hEventLog is the handle of an event log on a remote computer, the NotifiyChangeEventLog function returns FALSE, and GetLastError  returns ERROR_INVALID_HANDLE.

See Also

OpenEventLog


ntohl
 ntohl  QuickInfo

The Windows Sockets ntohl function converts a u_long from network byte order to host byte order.

u_long ntohl (

u_long netlong
);
Parameters

netlong

A 32-bit number in network byte order.

Return Value

ntohl returns the value in host byte order.

Remarks

This function takes a 32-bit number in network byte order and returns a 32-bit number in host byte order.

See Also

htonl, htons, ntohs


ntohs
 ntohs  QuickInfo

The Windows Sockets ntohs function converts a u_short from network byte order to host byte order.

u_short ntohs (

u_short netshort
);
Parameters

netshort

A 16-bit number in network byte order.

Return Value

ntohs returns the value in host byte order.

Remarks

This function takes a 16-bit number in network byte order and returns a 16-bit number in host byte order.

See Also

htonl, htons, ntohl


ObjectCloseAuditAlarm
 ObjectCloseAuditAlarm  QuickInfo  Overview  Group

The ObjectCloseAuditAlarm function generates audit messages when a handle of an object is deleted. Alarms are not supported in the current version of Windows NT.

BOOL ObjectCloseAuditAlarm(

LPCTSTR  SubsystemName,	// address of string for subsystem name
LPVOID  HandleId,	// address of handle identifier
BOOL  GenerateOnClose	// flag for audit generation
);
Parameters

SubsystemName

Points to a null-terminated string specifying the name of the subsystem calling the function, for example, "DEBUG" or "WIN32".

HandleId

Specifies a unique 32-bit value representing the client's handle of the object. This should be the same value that was passed to the AccessCheckAndAuditAlarm or ObjectOpenAuditAlarm function.

GenerateOnClose

Specifies a flag set by a call to the AccessCheckAndAuditAlarm or ObjectOpenAuditAlarm function when the object handle is created.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The ObjectCloseAuditAlarm function requires the calling application to have the SE_AUDIT_NAME privilege. The test for this privilege is always performed against the primary token of the calling process, allowing the calling process to impersonate a client.

The ObjectCloseAuditAlarm function may send many messages to port objects. This can result in a significant delay before the function returns. The design of applications calling ObjectCloseAuditAlarm can take this potential delay into account. For example, this consideration may affect the design of an application that uses mutexes to lock structures.

See Also

AccessCheck, AccessCheckAndAuditAlarm, AreAllAccessesGranted, AreAnyAccessesGranted, MapGenericMask, ObjectOpenAuditAlarm, ObjectPrivilegeAuditAlarm, PrivilegeCheck, PrivilegedServiceAuditAlarm


ObjectOpenAuditAlarm
 ObjectOpenAuditAlarm  QuickInfo  Overview  Group

The ObjectOpenAuditAlarm function generates audit messages when a client application attempts to gain access to an object or to create a new one. Alarms are not supported in the current version of Windows NT.

BOOL ObjectOpenAuditAlarm(

LPCTSTR  SubsystemName,	// address of string for subsystem name
LPVOID  HandleId,	// address of handle identifier
LPTSTR  ObjectTypeName,	// address of string for object type
LPTSTR  ObjectName,	// address of string for object name
PSECURITY_DESCRIPTOR  pSecurityDescriptor,	// address of security descriptor
HANDLE  ClientToken,	// handle of client's access token
DWORD  DesiredAccess,	// mask for desired access rights
DWORD  GrantedAccess,	// mask for granted access rights
PPRIVILEGE_SET  Privileges,	// address of privileges
BOOL  ObjectCreation,	// flag for object creation
BOOL  AccessGranted,	// flag for results
LPBOOL  GenerateOnClose	// address of flag for audit generation
);
Parameters

SubsystemName

Points to a null-terminated string specifying the subsystem calling this function, for example, "DEBUG" or "WIN32".

HandleId

Points to a unique 32-bit value representing the client's handle of the object. If the access is denied, this parameter is ignored.

ObjectTypeName

Points to a null-terminated string specifying the type of object to which the client is requesting access. This string appears in the audit log for the object.

ObjectName

Points to a null-terminated string specifying the name of the object to which the client gained access or attempted to gain access. This string appears in the audit log for the object.

pSecurityDescriptor

Points to the SECURITY_DESCRIPTOR structure for the object being accessed.

ClientToken

Identifies an access token representing the client requesting the operation. This handle must be obtained by opening the token of a thread impersonating the client. The token must be open for TOKEN_QUERY access.

DesiredAccess

Specifies the desired access mask. This mask must have been previously mapped by the MapGenericMask function to contain no generic access rights.

GrantedAccess

Specifies an access mask indicating which access rights are granted. This access mask is intended to be the same value set by one of the access-checking functions in its GrantedAccess parameter. Examples of access-checking functions include AccessCheckAndAuditAlarm and AccessCheck.

Privileges

Points to a PRIVILEGE_SET structure that specifies the set of privileges required for the access attempt. This parameter can be NULL.

ObjectCreation

Specifies a flag that determines whether the application creates a new object when access is granted. When this flag is TRUE, the application creates a new object; when it is FALSE, the application opens an existing object.

AccessGranted

Specifies a flag indicating whether access was granted or denied in a previous call to an access-checking function, such as AccessCheck. If access was granted, this flag is TRUE. If not, it is FALSE.

GenerateOnClose

Points to a flag set by the audit-generation routine when the function returns. This flag must be passed to the ObjectCloseAuditAlarm function when the object handle is closed.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The ObjectOpenAuditAlarm function requires the calling application to have the SE_AUDIT_NAME privilege. The test for this privilege is always performed against the primary token of the calling process, not the impersonation token of the thread. This allows the calling process to impersonate a client during the call.

The ObjectOpenAuditAlarm function may send many messages to port objects. This can result in a significant delay before the function returns. The design of applications calling ObjectOpenAuditAlarm can take this potential delay into account. For example, this consideration may affect the design of an application using mutexes to lock structures.

See Also

AccessCheck, AccessCheckAndAuditAlarm, AreAllAccessesGranted, AreAnyAccessesGranted, MapGenericMask, ObjectCloseAuditAlarm, ObjectPrivilegeAuditAlarm, PrivilegeCheck, PrivilegedServiceAuditAlarm, PRIVILEGE_SET, SECURITY_DESCRIPTOR,


ObjectPrivilegeAuditAlarm
 ObjectPrivilegeAuditAlarm  QuickInfo  Overview  Group

The ObjectPrivilegeAuditAlarm function generates audit messages as a result of a client's attempt to perform a privileged operation on a server application object using an already opened handle of that object. Alarms are not supported in the current version of Windows NT.

BOOL ObjectPrivilegeAuditAlarm(

LPCTSTR  lpszSubsystem,	// address of string for subsystem name
LPVOID  lpvHandleId,	// address of handle identifier
HANDLE  hClientToken,	// handle of client's access token
DWORD  dwDesiredAccess,	// mask for desired access rights
PPRIVILEGE_SET  pps,	// address of privileges
BOOL  fAccessGranted	// flag for results
);
Parameters

lpszSubsystem

Points to a null-terminated string specifying the name of the subsystem calling the function; for example, "DEBUG" or "WIN32".

lpvHandleId

Points to a unique 32-bit value representing the client's handle of the object.

hClientToken

Identifies an access token representing the client requesting the operation. This handle must be obtained by opening the token of a thread impersonating the client. The token must be open for TOKEN_QUERY access.

dwDesiredAccess

Specifies an access mask indicating the privileged access types being used or whose use is being attempted. The access mask can be mapped by the MapGenericMask function so it does not contain any generic access types.

pps

Points to a PRIVILEGE_SET structure specifying the set of privileges required for the requested operation. The information in this structure is supplied by a call to the PrivilegeCheck function. This parameter can be NULL.

fAccessGranted

Specifies a flag indicating whether access was granted or denied in a previous call to an access-checking function such as PrivilegeCheck. If access was granted, this flag is TRUE. If not, it is FALSE.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The ObjectPrivilegeAuditAlarm function requires the calling process to have SE_AUDIT_NAME privilege. The test for this privilege is always performed against the primary token of the calling process, not the impersonation token of the thread. This allows the calling process to impersonate a client during the call.

The ObjectPrivilegeAuditAlarm function can send many messages to port objects. This can result in a significant delay before the function returns. The design of applications calling ObjectPrivilegeAuditAlarm can take this potential delay into account. For example, this consideration may affect the design of an application using mutexes to lock structures.

See Also

AccessCheck, AccessCheckAndAuditAlarm, AreAllAccessesGranted, AreAnyAccessesGranted, MapGenericMask, ObjectCloseAuditAlarm, ObjectOpenAuditAlarm, PrivilegeCheck, PrivilegedServiceAuditAlarm, PRIVILEGE_SET


OemKeyScan
 OemKeyScan  QuickInfo  Overview  Group

The OemKeyScan function maps OEM ASCII codes 0 through 0x0FF into the OEM scan codes and shift states. The function provides information that allows a program to send OEM text to another program by simulating keyboard input.

DWORD OemKeyScan(

WORD  wOemChar	// ASCII value of OEM character
);
Parameters

wOemChar

Specifies the ASCII value of the OEM character.

Return Value

If the function succeeds, the low-order word of the return value contains the scan code of the given OEM character, and the high-order word contains the shift state, which can be a combination of the following flag bits:

Bit	Meaning
1	Either SHIFT key is pressed.
2	Either CTRL key is pressed.
4	Either ALT key is pressed.
If the character cannot be produced by a single keystroke using the current keyboard layout, the return value is 0xFFFFFFFF.

Remarks

This function does not provide translations for characters that require CTRL+ALT or dead keys. Characters not translated by this function must be copied by simulating input using the ALT+ keypad mechanism. The NUMLOCK key must be off.

This function does not provide translations for characters that cannot be typed with one keystroke using the current keyboard layout, such as characters with diacritics requiring dead keys. Characters not translated by this function may be simulated using the ALT+ keypad mechanism. The NUMLOCK key must be on.

This function is implemented using the VkKeyScan function.

See Also

VkKeyScan


OemToAnsi
 OemToAnsi  QuickInfo  Overview  Group

The OemToAnsi function is obsolete.

For compatibility with 16-bit versions of Windows, this function is implemented as a macro that calls the OemToChar function, which should be used for new Win32-based applications.


OemToAnsiBuff
 OemToAnsiBuff  QuickInfo  Overview  Group

The OemToAnsiBuff function is obsolete.

For compatibility with 16-bit versions of Windows, this function is implemented as a macro that calls the OemToCharBufffunction, which should be used for Win32-based applications.


OemToChar
 OemToChar  QuickInfo  Overview  Group

The OemToChar function translates a string from the OEM-defined character set into either an ANSI or a wide-character string. (OEM stands for original equipment manufacturer.) This function supersedes the OemToAnsi function.

BOOL OemToChar(

LPCSTR  lpszOemStr,	// address of string to translate
LPTSTR  lpszStr	// address of buffer for translated string
);
Parameters

lpszOemStr

Points to a null-terminated string of characters from the OEM-defined character set.

lpszStr

Points 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 lpszStr parameter to the same address as the lpszOemStr parameter. This cannot be done if OemToChar is being used as a wide-character function.

Return Value

The return value is always TRUE.

See Also

CharToOem, CharToOemBuff, OemToCharBuff


OemToCharBuff
 OemToCharBuff  QuickInfo  Overview  Group

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. (OEM stands for original equipment manufacturer.) This function supersedes the OemToAnsiBuff function.

BOOL OemToCharBuff(

LPCSTR  lpOemStr,	// address of string to translate
LPTSTR  lpszStr,	// address of buffer for translated string
DWORD  cchString	// size of buffer
);
Parameters

lpOemStr

Points to a buffer containing one or more characters from the OEM-defined character set.

lpszStr

Points 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 lpszStr parameter to the same address as the lpOemStr parameter. This cannot be done if the OemToCharBuff function is being used as a wide-character function.

cchString

Specifies the number of characters to translate in the buffer identified by the lpOemStr parameter.

Return Value

The return value is always TRUE.

See Also

CharToOem, CharToOemBuff, OemToChar


OffsetClipRgn
 OffsetClipRgn  QuickInfo  Overview  Group

The OffsetClipRgn function moves the clipping region of a device context by the specified offsets.

int OffsetClipRgn(

HDC  hdc,	// handle of device context
int  nXOffset,	// offset along x-axis
int  nYOffset	// offset along y-axis
);
Parameters

hdc

Identifies the device context.

nXOffset

Specifies the number of logical units to move left or right.

nYOffset

Specifies the number of logical units to move up or down.

Return Value

If the function succeeds, the return value specifies the new region's complexity and can be any one of the following values:

Value	Meaning
NULLREGION	Region is empty.
SIMPLEREGION	Region is a single rectangle.
COMPLEXREGION	Region is more than one rectangle.
ERROR	An error occurred. (The current clipping region is unaffected.)
See Also

SelectClipRgn


OffsetRect
 OffsetRect  QuickInfo  Overview  Group

The OffsetRect function moves the specified rectangle by the specified offsets.

BOOL OffsetRect(

LPRECT  lprc,	// address of structure with rectangle
int  x,	// horizontal offset
int  y	// vertical offset
);
Parameters

lprc

Points to a RECT structure that contains the logical coordinates of the rectangle to be moved.

x

Specifies the amount to move the rectangle left or right. This parameter must be a negative value to move the rectangle to the left.

y

Specifies the amount to move the rectangle up or down. This parameter must be a negative value to move the rectangle up.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

InflateRect, IntersectRect, UnionRect, RECT


OffsetRgn
 OffsetRgn  QuickInfo  Overview  Group

The OffsetRgn function moves a region by the specified offsets.

int OffsetRgn(

HRGN  hrgn,	// handle of region
int  nXOffset,	// offset along x-axis
int  nYOffset	// offset along y-axis
);
Parameters

hrgn

Identifies the region to be moved.

nXOffset

Specifies the number of logical units to move left or right.

nYOffset

Specifies the number of logical units to move up or down.

Return Value

The return value specifies the new region's complexity. It can be one of the following values:

Value	Meaning
NULLREGION	Region is empty.
SIMPLEREGION	Region is a single rectangle.
COMPLEXREGION	Region is more than one rectangle.
ERROR	An error occurred; region is unaffected.


 OffsetViewportOrg

The OffsetViewportOrg function is not implemented in the Win32 API. Win32-based applications should use the OffsetViewportOrgEx function.


OffsetViewportOrgEx
 OffsetViewportOrgEx  QuickInfo  Overview  Group

The OffsetViewportOrgEx function modifies the viewport origin for a device context using the specified horizontal and vertical offsets.

BOOL OffsetViewportOrgEx(

HDC  hdc,	// handle of device context
int  nXOffset,	// horizontal offset
int  nYOffset,	// vertical offset
LPPOINT  lpPoint	// address of structure receiving original origin
);
Parameters

hdc

Identifies the device context.

nXOffset

Specifies the horizontal offset, in device units.

nYOffset

Specifies the vertical offset, in device units.

lpPoint

Points to a POINT structure. The previous viewport origin, in device units, is placed in this structure. If lpPoint is NULL, the previous viewport origin is not returned.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

The new origin is the sum of the current origin and the horizontal and vertical offsets.

See Also

GetViewportOrgEx, OffsetWindowOrgEx, SetViewportOrgEx


 OffsetWindowOrg

The OffsetWindowOrg function is not implemented in the Win32 API. Win32-based applications should use the OffsetWindowOrgEx function.


OffsetWindowOrgEx
 OffsetWindowOrgEx  QuickInfo  Overview  Group

The OffsetWindowOrgEx function modifies the window origin for a device context using the specified horizontal and vertical offsets.

BOOL OffsetWindowOrgEx(

HDC  hdc,	// handle of device context
int  nXOffset,	// horizontal offset
int  nYOffset,	// vertical offset
LPPOINT  lpPoint	// address of structure receiving the original origin
);
Parameters

hdc

Identifies the device context.

nXOffset

Specifies the horizontal offset, in logical units.

nYOffset

Specifies the vertical offset, in logical units.

lpPoint

Points to a POINT structure. The logical coordinates of the previous window origin are placed in this structure. If lpPoint is NULL, the previous origin is not returned.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

GetViewportOrgEx, OffsetViewportOrgEx, POINT


OpenBackupEventLog
 OpenBackupEventLog  QuickInfo  Overview  Group

The OpenBackupEventLog function opens a handle of a backup event log. This handle can be used with the BackupEventLog function.

HANDLE OpenBackupEventLog(

LPCTSTR  lpszUNCServerName,	// backup file server name
LPCTSTR  lpszFileName	// backup filename
);
Parameters

lpszUNCServerName

Points to a null-terminated string that specifies the Universal Naming Convention (UNC) name of the server on which this operation is to be performed. If this parameter is NULL, the operation is performed on the local computer.

lpszFileName

Points to a null-terminated string that specifies the name of the backup file. The backup filename may contain a server name to open a backup file on a remote server (in this case, the lpszUNCServerName parameter must be NULL).

Return Value

If the function succeeds, the return value is a handle of the backup event log.

If the function fails, the return value is NULL.

Remarks

If the backup filename specifies a remote server, lpszUNCServerName must be NULL. You cannot use this function to open a file on a remote server.

See Also

BackupEventLog


OpenClipboard
 OpenClipboard  QuickInfo  Overview  Group

The OpenClipboard function opens the clipboard for examination and prevents other applications from modifying the clipboard content.

BOOL OpenClipboard(

HWND  hwnd	// handle of window opening clipboard
);
Parameters

hwnd

Identifies the window to be associated with the open clipboard. If this parameter is NULL, the open clipboard is associated with the current task.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

OpenClipboard fails if another window has the clipboard open.

An application should call the CloseClipboard function after every successful call to OpenClipboard.

The window identified by the hwnd parameter does not become the clipboard owner unless the EmptyClipboard function is called.

See Also

CloseClipboard, EmptyClipboard


OpenDesktop [New - Windows NT]
 OpenDesktop  QuickInfo  Overview  Group

[New - Windows NT]

The OpenDesktop function returns 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(

LPCTSTR lpszDesktopName	// name of the desktop to open
DWORD dwFlags	// flags to control interaction with other applications
BOOL fInherit	// specifies whether returned handle is inheritable
DWORD dwDesiredAccess	// specifies access of returned handle
);
Parameters

lpszDesktopName

Points to null-terminated string specifying the name of the desktop to be opened. Desktop names are case-insensitive.

dwFlags

A bit flag parameter that controls how the calling application will cooperate with other applications on the desktop. This parameter can specify 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

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

Specifies the type of access to the desktop. This parameter can be one or more of the following values:

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 Value

If the function succeeds, the return value is the handle to the opened desktop.

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.

See Also

CreateDesktop, SetProcessWindowStation, SetThreadDesktop, SwitchDesktop


OpenEvent
 OpenEvent  QuickInfo  Overview  Group

The OpenEvent function returns a handle of an existing named event object.

HANDLE OpenEvent(

DWORD  fdwAccess,	// access flag
BOOL  fInherit,	// inherit flag
LPCTSTR  lpszEventName	// address of event-object name
);
Parameters

fdwAccess

Specifies the requested access to the event object. For systems that support object security, the function fails if the security descriptor of the specified object does not permit the requested access for the calling process.

This parameter can be any combination of the following values:

Access	Description
EVENT_ALL_ACCESS	Specifies all possible access flags for the event object.
EVENT_MODIFY_STATE	Enables use of the event handle in the SetEvent and ResetEvent functions to modify the event's state.
SYNCHRONIZE	Windows NT: Enables use of the event handle in any of the wait functions to wait for the event's state to be signaled.
fInherit

Specifies whether the returned handle is inheritable. If TRUE, a process created by the CreateProcess function can inherit the handle; otherwise, the handle cannot be inherited.

lpszEventName

Points to a null-terminated string that names the event to be opened. Name comparisons are case sensitive.

Return Value

If the function succeeds, the return value is a handle of the event object.

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

Remarks

The OpenEvent function enables multiple processes to open handles of the same event object. The function succeeds only if some process has already created the event by using the CreateEvent function. The calling process can use the returned handle in any function that requires a handle of an event object, subject to the limitations of the access specified in the fdwAccess parameter.

The handle can be duplicated by using the DuplicateHandle function. Use the CloseHandle function to close the handle. The system closes the handle automatically when the process terminates. The event object is destroyed when its last handle has been closed.

See Also

CloseHandle, CreateEvent, CreateProcess, DuplicateHandle, MsgWaitForMultipleObjects, PulseEvent, ResetEvent, SetEvent, WaitForMultipleObjects, WaitForMultipleObjectsEx, WaitForSingleObject, WaitForSingleObjectEx


OpenEventLog
 OpenEventLog  QuickInfo  Overview  Group

The OpenEventLog function opens a handle of an event log.

HANDLE OpenEventLog(

LPCTSTR  lpszUNCServerName,	// address of server name
LPCTSTR  lpszSourceName	// address of source name
);
Parameters

lpszUNCServerName

Points to a null-terminated string that specifies the Universal Naming Convention (UNC) name of the server on which the event log is to be opened. If this parameter is NULL, the log is opened on the local computer.

lpszSourceName

Points to a null-terminated string that specifies the name of the source that the returned handle will reference. The source name must be a subkey of a logfile entry under the EventLog key in the registry. For example, the source name WinApp would be valid if the registry had the following form:

HKEY_LOCAL_MACHINE

  System

    CurrentControlSet

      Services

        EventLog

          Application

            WinApp

          Security

          System

If the source name cannot be found, the event logging service uses the Application logfile with no message files for the event identifier or category.

Return Value

If the function succeeds, the return value is the handle of an event log.

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

See Also

ClearEventLog, CloseEventLog, GetNumberOfEventLogRecords, GetOldestEventLogRecord, ReadEventLog, ReportEvent


OpenFile
 OpenFile  QuickInfo  Overview  Group

The OpenFile function creates, opens, reopens, or deletes a file.

This function is provided for compatibility with 16-bit versions of Windows. In particular, the OpenFile function cannot open a named pipe. Win32-based applications should use the CreateFile function.

HFILE OpenFile(

LPCSTR  lpszFile,	// address of filename
LPOFSTRUCT  lpOpenBuff,	// address of buffer for file information
UINT  fuMode	// action and attributes
);
Parameters

lpszFile

Points to a null-terminated string that names the file to be opened. The string must consist of characters from the Windows 3.x character set. The OpenFile function does not support Unicode filenames.

lpOpenBuff

Points to the OFSTRUCT structure that receives information about the file when it is first opened. The structure can be used in subsequent calls to the OpenFile function to refer to the open file.

The OFSTRUCT structure contains a pathname string member whose length is limited to OFS_MAXPATHNAME characters. OFS_MAXPATHNAME is currently defined to be 128. Because of this, you cannot use the OpenFile function to open a file whose path length exceeds 128 characters. The CreateFile function does not have such a path length limitation.

fuMode

Specifies the action to take. The following values can be combined by using the bitwise OR operator:

Value	Meaning
OF_CANCEL	Ignored. In the Win32 application programming interface (API), the OF_PROMPT style produces a dialog box containing a Cancel button.
OF_CREATE	Creates a new file. If the file already exists, it is truncated to zero length.
OF_DELETE	Deletes the file.
OF_EXIST	Opens the file and then closes it. Used to test for a file's existence.
OF_PARSE	Fills the OFSTRUCT structure but carries out no other action.
OF_PROMPT	Displays a dialog box if the requested file does not exist. The dialog box informs the user that Windows cannot find the file, and it contains Retry and Cancel buttons. Choosing the Cancel button directs OpenFile to return a file-not-found error message.
OF_READ	Opens the file for reading only.
OF_READWRITE	Opens the file for reading and writing.
OF_REOPEN	Opens the file using information in the reopen buffer.
OF_SHARE_COMPAT	For MS-DOS−based file systems using the Win32 API, opens the file with compatibility mode, allowing any process on a specified computer to open the file any number of times. Other efforts to open with any other sharing mode fail. On the Windows NT platform, this flag is mapped to the CreateFile function's FILE_SHARE_READ | FILE_SHARE_WRITE flags.
OF_SHARE_DENY_NONE	Opens the file without denying read or write access to other processes. On MS-DOS-based file systems using the Win32 API, if the file has been opened in compatibility mode by any other process, the function fails. On the Windows NT platform, this flag is mapped to the CreateFile function's FILE_SHARE_READ | FILE_SHARE_WRITE flags.
OF_SHARE_DENY_READ	Opens the file and denies read access to other processes. On MS-DOS-based file systems using the Win32 API, if the file has been opened in compatibility mode or for read access by any other process, the function fails.  On the Windows NT platform, this flag is mapped to the CreateFile function's FILE_SHARE_WRITE flag.
OF_SHARE_DENY_WRITE	Opens the file and denies write access to other processes. On MS-DOS-based file systems using the Win32 API, if the file has been opened in compatibility mode or for write access by any other process, the function fails.  On the Windows NT platform, this flag is mapped to the CreateFile function's FILE_SHARE_WRITE flag.
OF_SHARE_EXCLUSIVE	Opens the file with exclusive mode, denying both read and write access to other processes. If the file has been opened in any other mode for read or write access, even by the current process, the function fails.
OF_VERIFY	Verifies that the date and time of the file are the same as when it was previously opened. This is useful as an extra check for read-only files.
OF_WRITE	Opens the file for writing only.
Return Value

If the function succeeds, the return value specifies a file handle.

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

Remarks

If the lpszFile parameter specifies a filename and extension only, this function searches for a matching file in the following directories, in the order shown:

1.	The directory from which the application loaded.

2.	The current directory.

3.	Windows 95: The Windows system directory. Use the GetSystemDirectory function to get the path of this directory.

Windows NT: The 32-bit Windows system directory. Use the GetSystemDirectory function to get the path of this directory. The name of this directory is SYSTEM32.

4.	Windows NT only: The 16-bit Windows system directory. There is no Win32 function that obtains the path of this directory, but it is searched. The name of this directory is SYSTEM.

5.	The Windows directory. Use the GetWindowsDirectory function to get the path of this directory.

6.	The directories that are listed in the PATH environment variable.

The lpszFile parameter cannot contain wildcard characters.

To close the file after use, call the _lclose function.

See Also

CreateFile, GetSystemDirectory, GetWindowsDirectory, _lclose, OFSTRUCT


OpenFileMapping
 OpenFileMapping  QuickInfo  Overview  Group

The OpenFileMapping function opens a named file-mapping object.

HANDLE OpenFileMapping(

DWORD  dwDesiredAccess,	// access mode
BOOL  bInheritHandle,	// inherit flag
LPCTSTR  lpName	// address of name of file-mapping object
);
Parameters

dwDesiredAccess

Specifies the access to the file-mapping object.

Windows NT:

This access is checked against any security descriptor on the target file-mapping object.

Windows 95:

Windows 95 does not support security descriptors on file mapping objects.

This parameter can be one of the following values:

Value	Meaning
FILE_MAP_WRITE	Read-write access. The target file-mapping object must have been created with PAGE_READWRITE protection. A read-write view of the file is mapped.
FILE_MAP_READ	Read-only access. The target file-mapping object must have been created with PAGE_READWRITE or PAGE_READ protection. A read-only view of the file is mapped.
FILE_MAP_ALL_ACCESS	Same as FILE_MAP_WRITE.
FILE_MAP_COPY	Copy-on-write access. The target file-mapping object must have been created with PAGE_WRITECOPY protection. A copy-on-write view of the file is mapped.
bInheritHandle

Specifies whether the returned handle is to be inherited by a new process during process creation. A value of TRUE indicates that the new process inherits the handle.

lpName

Points to a string that names the file-mapping object to be opened. If there is an open handle to a file-mapping object by this name and the security descriptor on the mapping object does not conflict with the dwDesiredAccess parameter, the open operation succeeds.

Return Value

If the function succeeds, the return value is an open handle to the specified file-mapping object.

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

Remarks

The handle that OpenFileMapping returns can be used with any function that requires a handle to a file-mapping object.

See Also

CreateFileMapping


OpenIcon
 OpenIcon  QuickInfo  Overview  Group

The OpenIcon function restores a minimized (iconic) window to its previous size and position; it then activates the window.

BOOL OpenIcon(

HWND  hwnd	// handle of window
);
Parameters

hwnd

Identifies the window to be restored and activated.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

OpenIcon sends a WM_QUERYOPEN message to the given window.

See Also

CloseWindow, IsIconic, ShowWindow


OpenInputDesktop [New - Windows NT]
 OpenInputDesktop  QuickInfo  Overview  Group

[New - Windows NT]

The OpenInputDesktop function returns 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	// flags to control interaction with other applications
BOOL fInherit	// specifies whether returned handle is inheritable
DWORD dwDesiredAccess	// specifies access of returned handle
);
Parameters

dwFlags

A bit flag parameter that controls how the calling application will cooperate with other applications on the desktop. This parameter can specify 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

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

Specifies the type of access to the desktop. This parameter can be one or more of the following values:

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 Value

If the function succeeds, the return value is a handle of the desktop that receives user input.

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

See Also

SetProcessWindowStation, SwitchDesktop


OpenMutex
 OpenMutex  QuickInfo  Overview  Group

The OpenMutex function returns a handle of an existing named mutex object.

HANDLE OpenMutex(

DWORD  fdwAccess,	// access flag
BOOL  fInherit,	// inherit flag
LPCTSTR  lpszMutexName	// address of mutex-object name
);
Parameters

fdwAccess

Specifies the requested access to the mutex object. For systems that support object security, the function fails if the security descriptor of the specified object does not permit the requested access for the calling process.

This parameter can be any combination of the following values:

Access	Description
MUTEX_ALL_ACCESS	Specifies all possible access flags for the mutex object.
SYNCHRONIZE	Windows NT: Enables use of the mutex handle in any of the wait functions to acquire ownership of the mutex, or in the ReleaseMutex function to release ownership.
fInherit

Specifies whether the returned handle is inheritable. If TRUE, a process created by the CreateProcess function can inherit the handle; otherwise, the handle cannot be inherited.

lpszMutexName

Points to a null-terminated string that names the mutex to be opened. Name comparisons are case sensitive.

Return Value

If the function succeeds, the return value is a handle of the mutex object.

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

Remarks

The OpenMutex function enables multiple processes to open handles of the same mutex object. The function succeeds only if some process has already created the mutex by using the CreateMutex function. The calling process can use the returned handle in any function that requires a handle of a mutex object, subject to the limitations of the access specified in the fdwAccess parameter.

The handle can be duplicated by using the DuplicateHandle function. Use the CloseHandle function to close the handle. The system closes the handle automatically when the process terminates. The mutex object is destroyed when its last handle has been closed.

See Also

CloseHandle, CreateMutex, CreateProcess, DuplicateHandle, MsgWaitForMultipleObjects, ReleaseMutex, WaitForMultipleObjects, WaitForMultipleObjectsEx, WaitForSingleObject, WaitForSingleObjectEx


OpenPrinter
 OpenPrinter  QuickInfo  Overview  Group

The OpenPrinter function retrieves a handle identifying the specified printer or print server.

BOOL OpenPrinter(

LPTSTR  pPrinterName,	// address of printer or server name
LPHANDLE  phPrinter,	// address of printer or server handle
LPPRINTER_DEFAULTS  pDefault	// address of printer defaults structure
);
Parameters

pPrinterName

Points to a null-terminated string that specifies the name of the printer or print server.

phPrinter

Points to a variable that receives the handle identifying the opened printer or print server object.

pDefault

Points to a PRINTER_DEFAULTS structure. This value can be NULL.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The pDefault parameter allows an application to specify the data type and device mode values that are used for printing documents submitted by the StartDocPrinter function. However, these values can be overridden by using the SetJob function once a document has been started.

The DesiredAccess member of the PRINTER_DEFAULTS data structure pointed to by pDefault specifies the accesses that an application wishes to perform using the handle returned by OpenPrinter. If an application wishes to open a printer to perform administrative tasks, such as the SetPrinter function, it should open the printer with PRINTER_ALL_ACCESS access. If an application wishes only to perform basic printing operations, an access value that includes PRINTER_ACCESS_USE is sufficient.

Windows 95: OpenPrinter ignores the DesiredAccess member of PRINTER_DEFAULTS.

An application can determine what permissions a client has on a print server, or obtain a handle to a print server to call WaitForPrinterChange. To do so, it should call OpenPrinter with pPrinterName set to the name of the server and should specify a server access mask value such as SERVER_ALL_ACCESS. The pDatatype and pDevMode members of the PRINTER_DEFAULTS data structure should be set to NULL. The handle returned by such a call may be passed to the ClosePrinter or WaitForPrinterChange function.

If a user does not hold permission to open a specified printer or print server with the desired access, the OpenPrinter call will fail, and GetLastError will return the value ERROR_ACCESS_DENIED.

See Also

ClosePrinter, SetPrinter, StartDocPrinter, WaitForPrinterChange, PRINTER_DEFAULTS


OpenProcess
 OpenProcess  QuickInfo  Overview  Group

The OpenProcess function returns a handle of an existing process object.

HANDLE OpenProcess(

DWORD  fdwAccess,	// access flag
BOOL  fInherit,	// handle inheritance flag
DWORD  IDProcess	// process identifier
);
Parameters

fdwAccess

Specifies the access to the process object. For operating systems that support security checking, this access is checked against any security descriptor for the target process. Any combination of the following access flags can be specified in addition to the STANDARD_RIGHTS_REQUIRED access flags:

Access	Description
PROCESS_ALL_ACCESS	Specifies all possible access flags for the process object.
PROCESS_CREATE_PROCESS	Used internally.
PROCESS_CREATE_THREAD	Enables using the process handle in the CreateRemoteThread function to create a thread in the process.
PROCESS_DUP_HANDLE	Enables using the process handle as either the source or target process in the DuplicateHandle function to duplicate a handle.
PROCESS_QUERY_INFORMATION	Enables using the process handle in the GetExitCodeProcess and GetPriorityClass functions to read information from the process object.
PROCESS_SET_INFORMATION	Enables using the process handle in the SetPriorityClass function to set the priority class of the process.
PROCESS_TERMINATE	Enables using the process handle in the TerminateProcess function to terminate the process.
PROCESS_VM_OPERATION	Enables using the process handle in the VirtualProtectEx and WriteProcessMemory functions to modify the virtual memory of the process.
PROCESS_VM_READ	Enables using the process handle in the ReadProcessMemory function to read from the virtual memory of the process.
PROCESS_VM_WRITE	Enables using the process handle in the WriteProcessMemory function to write to the virtual memory of the process.
SYNCHRONIZE	Windows NT: Enables using the process handle in any of the wait functions to wait for the process to terminate.
fInherit

Specifies whether the returned handle can be inherited by a new process created by the current process. If TRUE, the handle is inheritable.

IDProcess

Specifies the process identifier of the process to open.

Return Value

If the function succeeds, the return value is an open handle of the specified process.

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

Remarks

The handle returned by the OpenProcess function can be used in any function that requires a handle to a process, provided the appropriate access rights were requested.

See Also

CreateProcess, CreateRemoteThread, DuplicateHandle, GetCurrentProcess, GetCurrentProcessId, GetExitCodeProcess, GetPriorityClass, ReadProcessMemory, SetPriorityClass, TerminateProcess, VirtualProtectEx, WriteProcessMemory,


OpenProcessToken
 OpenProcessToken  QuickInfo  Overview  Group

The OpenProcessToken function opens the access token associated with a process.

BOOL OpenProcessToken(

HANDLE  hProcess,	// handle of process
DWORD  dwAccessMask,	// desired access to process
PHANDLE  phToken	// address of handle of open access token
);
Parameters

hProcess

Identifies the process whose access token is opened.

dwAccessMask

Specifies an access mask that specifies the requested types of access to the access token. These requested access types are compared with the token's discretionary access-control list (ACL) to determine which accesses are granted or denied. The following access rights have been defined for access tokens.

Value	Meaning
TOKEN_ADJUST_DEFAULT	Required to change the default ACL, primary group, or owner of an access token.
TOKEN_ADJUST_GROUPS	Required to change the groups specified in an access token.
TOKEN_ADJUST_PRIVILEGES	Required to change the privileges specified in an access token.
TOKEN_ALL_ACCESS	Combines the STANDARD_RIGHTS_REQUIRED standard access rights and all individual access rights for tokens.
TOKEN_ASSIGN_PRIMARY	Required to attach a primary token to a process in addition to the SE_CREATE_TOKEN_NAME privilege.
TOKEN_DUPLICATE	Required to duplicate an access token.
TOKEN_EXECUTE	Combines the STANDARD_RIGHTS_EXECUTE standard access rights and the TOKEN_IMPERSONATE access right.
TOKEN_IMPERSONATE	Required to attach an impersonation access token to a process.
TOKEN_QUERY	Required to query the contents of an access token.
TOKEN_QUERY_SOURCE	Required to query the source of an access token.
TOKEN_READ	Combines the STANDARD_RIGHTS_READ standard access rights and the TOKEN_QUERY access right.
TOKEN_WRITE	Combines the STANDARD_RIGHTS_WRITE standard access rights and the TOKEN_ADJUST_PRIVILEGES, TOKEN_ADJUST_GROUPS, and TOKEN_ADJUST_DEFAULT access rights.
phToken

Points to a handle identifying the newly-opened access token when the function returns.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

AdjustTokenGroups, AdjustTokenPrivileges, GetTokenInformation, OpenThreadToken, SetTokenInformation


OpenSCManager
 OpenSCManager  QuickInfo  Overview  Group

The OpenSCManager function establishes a connection to the service control manager on the specified computer and opens the specified database.

SC_HANDLE OpenSCManager(

LPCTSTR  lpszMachineName,	// address of machine name string
LPCTSTR  lpszDatabaseName,	// address of database name string
DWORD  fdwDesiredAccess	// type of access
);
Parameters

lpszMachineName

Points to a null-terminated string that names the target computer. If the pointer is NULL or if it points to an empty string, the function connects to the service control manager on the local computer.

lpszDatabaseName

Points to a null-terminated string that names the service control manager database to open. This string should specify ServicesActive. If the pointer is NULL, the ServicesActive database is opened by default.

fdwDesiredAccess

Specifies the access to the service control manager. Before granting the requested access, the system checks the access token of the calling process against the discretionary access-control list of the security descriptor associated with the service control manager object. The SC_MANAGER_CONNECT access type is implicitly specified by calling this function. In addition, any or all of the following service control manager object access types can be specified:

Type	Description
SC_MANAGER_ALL_ACCESS
	Includes STANDARD_RIGHTS_REQUIRED, in addition to all of the access types listed in this table.
SC_MANAGER_CONNECT
	Enables connecting to the service control manager.
SC_MANAGER_CREATE_SERVICE
	Enables calling of the CreateService function to create a service object and add it to the database.
SC_MANAGER_ENUMERATE_SERVICE
	Enables calling of the EnumServicesStatus function to list the services that are in the database.
SC_MANAGER_LOCK
	Enables calling of the LockServiceDatabase function to acquire a lock on the database.
SC_MANAGER_QUERY_LOCK_STATUS
	Enables calling of the QueryServiceLockStatus function to retrieve the lock status information for the database.
The fdwDesiredAccess parameter can specify any or all of the following generic access types:

Generic access	Service manager access
GENERIC_READ	Combines the following access: STANDARD_RIGHTS_READ, SC_MANAGER_ENUMERATE_SERVICE, and SC_MANAGER_QUERY_LOCK_STATUS.
GENERIC_WRITE	Combines the following access: STANDARD_RIGHTS_WRITE, SC_MANAGER_CREATE_SERVICE, and SC_MANAGER_MODIFY_BOOT_CONFIG.
GENERIC_EXECUTE	Combines the following access: STANDARD_RIGHTS_EXECUTE, SC_MANAGER_CONNECT, and SC_MANAGER_LOCK.
Return Value

If the function succeeds, the return value is a handle to the specified service control manager database.

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

Errors

The following error codes may be set by the service control manager. Other error codes may be set by the registry functions that are called by the service control manager.

Error code	Meaning
ERROR_ACCESS_DENIED	The requested access was denied.
ERROR_DATABASE_DOES_NOT_EXIST	The specified database does not exist.
ERROR_INVALID_PARAMETER	A parameter that was specified is invalid.
Remarks

When a process uses the OpenSCManager function to open a handle to a service control manager database, the system performs a security check before granting the requested access. All processes are permitted SC_MANAGER_CONNECT, SC_MANAGER_ENUMERATE_SERVICE, and SC_MANAGER_QUERY_LOCK_STATUS access to all service control manager databases. This enables any process to open a service control manager database handle that it can use in the OpenService, EnumServicesStatus, and QueryServiceLockStatus functions. Only processes with Administrator privileges are able to open a database handle used by the CreateService and LockServiceDatabase functions.

The calling process can use the returned handle to identify the database in the following functions, if the appropriate access rights are enabled:

CreateService
EnumServicesStatus
LockServiceDatabase
OpenService
QueryServiceLockStatus

The returned handle is only valid for the process that called the OpenSCManager function. It can be closed by calling the CloseServiceHandle function.

See Also

CloseServiceHandle, CreateService, EnumServicesStatus, LockServiceDatabase, OpenService, QueryServiceLockStatus


OpenSemaphore
 OpenSemaphore  QuickInfo  Overview  Group

The OpenSemaphore function returns a handle of an existing named semaphore object.

HANDLE OpenSemaphore(

DWORD  fdwAccess,	// access flag
BOOL  fInherit,	// inherit flag
LPCTSTR  lpszSemName	// address of semaphore-object name
);
Parameters

fdwAccess

Specifies the requested access to the semaphore object. For systems that support object security, the function fails if the security descriptor of the specified object does not permit the requested access for the calling process.

This parameter can be any combination of the following values:

Access	Description
SEMAPHORE_ALL_ACCESS	Specifies all possible access flags for the semaphore object.
SEMAPHORE_MODIFY_STATE	Enables use of the semaphore handle in the ReleaseSemaphore function to modify the semaphore's count.
SYNCHRONIZE	Windows NT: Enables use of the semaphore handle in any of the wait functions to wait for the semaphore's state to be signaled.
fInherit

Specifies whether the returned handle is inheritable. If TRUE, a process created by the CreateProcess function can inherit the handle; otherwise, the handle cannot be inherited.

lpszSemName

Points to a null-terminated string that names the semaphore to be opened. Name comparisons are case sensitive.

Return Value

If the function succeeds, the return value is a handle of the semaphore object.

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

Remarks

The OpenSemaphore function enables multiple processes to open handles of the same semaphore object. The function succeeds only if some process has already created the semaphore by using the CreateSemaphore function. The calling process can use the returned handle in any function that requires a handle of a semaphore object, subject to the limitations of the access specified in the fdwAccess parameter.

The handle can be duplicated by using the DuplicateHandle function. Use the CloseHandle function to close the handle. The system closes the handle automatically when the process terminates. The semaphore object is destroyed when its last handle has been closed.

See Also

CloseHandle, CreateSemaphore, DuplicateHandle, MsgWaitForMultipleObjects, ReleaseSemaphore, WaitForMultipleObjects, WaitForMultipleObjectsEx, WaitForSingleObject, WaitForSingleObjectEx


OpenService
 OpenService  QuickInfo  Overview  Group

The OpenService function opens a handle to an existing service.

SC_HANDLE OpenService(

SC_HANDLE  schSCManager,	// handle of service control manager database
LPCTSTR  lpszServiceName,	// address of name of service to start
DWORD  fdwDesiredAccess	// type of access to service
);
Parameters

schSCManager

Identifies the service control manager database. The OpenSCManager function returns this handle.

lpszServiceName

Points to a null-terminated string that names the service to open. The maximum string length is 256 characters. The service control manager database preserves the case of the characters, but service name comparisons are always case insensitive. A slash (/), backslash (\), comma, and space are invalid service name characters.

fdwDesiredAccess

Specifies the access to the service. Before granting the requested access, the system checks the access token of the calling process against the discretionary access-control list of the security descriptor associated with the service object. Any or all of the following service object access types can be specified:

Access	Description
SERVICE_ALL_ACCESS
	Includes STANDARD_RIGHTS_REQUIRED in addition to all of the access types listed in this table.
SERVICE_CHANGE_CONFIG
	Enables calling of the ChangeServiceConfig function to change the service configuration.
SERVICE_ENUMERATE_DEPENDENTS
	Enables calling of the EnumDependentServices function to enumerate all the services dependent on the service.
SERVICE_INTERROGATE
	Enables calling of the ControlService function to ask the service to report its status immediately.
SERVICE_PAUSE_CONTINUE
	Enables calling of the ControlService function to pause or continue the service.
SERVICE_QUERY_CONFIG
	Enables calling of the QueryServiceConfig function to query the service configuration.
SERVICE_QUERY_STATUS
	Enables calling of the QueryServiceStatus function to ask the service control manager about the status of the service.
SERVICE_START
	Enables calling of the StartService function to start the service.
SERVICE_STOP
	Enables calling of the ControlService function to stop the service.
SERVICE_USER_DEFINE_CONTROL
	Enables calling of the ControlService function to specify a user-defined control code.
STANDARD_RIGHTS_REQUIRED enables the following service object access types:

Standard rights	Description
DELETE	Enables calling of the DeleteService function to delete the service.
READ_CONTROL	Enables calling of the QueryServiceObjectSecurity function to query the security descriptor of the service object.
WRITE_DAC|WRITE_OWNER	Enables calling of the SetServiceObjectSecurity function to modify the security descriptor of the service object.
The fdwDesiredAccess parameter can specify any or all of the following generic access types:

Generic access	Service access
GENERIC_READ	Combines the following access: STANDARD_RIGHTS_READ, SERVICE_QUERY_CONFIG, SERVICE_QUERY_STATUS, and SERVICE_ENUMERATE_DEPENDENTS.
GENERIC_WRITE	Combines the following access: STANDARD_RIGHTS_WRITE and SERVICE_CHANGE_CONFIG.
GENERIC_EXECUTE	Combines the following access: STANDARD_RIGHTS_EXECUTE, SERVICE_START, SERVICE_STOP, SERVICE_PAUSE_CONTINUE, SERVICE_INTERROGATE, and SERVICE_USER_DEFINED_CONTROL.
Return Value

If the function succeeds, the return value is a handle to the service.

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

Errors

The following error codes can be set by the service control manager. Others can be set by the registry functions that are called by the service control manager.

Error code	Meaning
ERROR_ACCESS_DENIED	The specified service control manager database handle does not have access to the service.
ERROR_INVALID_HANDLE	The specified handle is invalid.
ERROR_INVALID_NAME	The specified service name is invalid.
ERROR_SERVICE_DOES_NOT_EXIST	The specified service does not exist.
Remarks

The calling process can use the returned handle to identify the service in the following functions, if the appropriate access rights are enabled:

ChangeServiceConfig
ControlService
DeleteService
EnumDependentServices
QueryServiceConfig
QueryServiceObjectSecurity
QueryServiceStatus
SetServiceObjectSecurity
StartService

The returned handle is only valid for the process that called OpenService. It can be closed by calling the CloseServiceHandle function.

See Also

ChangeServiceConfig, ControlService, CreateService, DeleteService, EnumDependentServices, OpenSCManager, QueryServiceConfig, QueryServiceObjectSecurity, QueryServiceStatus, SetServiceObjectSecurity, StartService


 OpenSound

The OpenSound function has been deleted.

See Also

Beep, MessageBeep


OpenThreadToken
 OpenThreadToken  QuickInfo  Overview  Group

The OpenThreadToken function opens the access token associated with a thread.

BOOL OpenThreadToken(

HANDLE  hThread,	// handle of thread
DWORD  dwAccessMask,	// access to process
BOOL  fOpenAsSelf,	// flag for process or thread security
PHANDLE  phToken	// address of handle of open access token
);
Parameters

hThread

Identifies the thread whose access token is opened.

dwAccessMask

Specifies an access mask that specifies the requested types of access to the access token. These requested access types are reconciled against the token's discretionary access-control list (ACL) to determine which accesses are granted or denied. The following access rights have been defined for access tokens.

Value	Meaning
TOKEN_ADJUST_DEFAULT	Required to change the default ACL, primary group, or owner of an access token.
TOKEN_ADJUST_GROUPS	Required to change the groups specified in an access token.
TOKEN_ADJUST_PRIVILEGES	Required to change the privileges specified in an access token.
TOKEN_ALL_ACCESS	Combines the STANDARD_RIGHTS_REQUIRED standard access rights and all individual access rights for tokens.
TOKEN_ASSIGN_PRIMARY	Required to attach a primary token to a process in addition to the SE_CREATE_TOKEN_NAME privilege.
TOKEN_DUPLICATE	Required to duplicate an access token.
TOKEN_EXECUTE	Combines the STANDARD_RIGHTS_EXECUTE standard access rights and the TOKEN_IMPERSONATE access right.
TOKEN_IMPERSONATE	Required to attach an impersonation access token to a process.
TOKEN_QUERY	Required to query the contents of an access token.
TOKEN_QUERY_SOURCE	Required to query the source of an access token.
TOKEN_READ	Combines the STANDARD_RIGHTS_READ standard access rights and the TOKEN_QUERY access right.
TOKEN_WRITE	Combines the STANDARD_RIGHTS_WRITE standard access rights and the TOKEN_ADJUST_PRIVILEGES, TOKEN_ADJUST_GROUPS, and TOKEN_ADJUST_DEFAULT access rights.
fOpenAsSelf

Specifies a flag indicating whether the access check is to be made against the security context of the thread calling the OpenThreadToken function or against the security context of the process for the calling thread.

If this parameter is FALSE, the access check is performed using the security context for the calling thread. If the thread is impersonating a client, this security context can be that of a client process. If this parameter is TRUE, the access check is made using the security context of the process for the calling thread.

phToken

Points to a handle identifying the newly opened access token when the function returns.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The fOpenAsSelf parameter allows a server process to open the access token for a client process when the client process has specified the SecurityIdentification impersonation level for the SECURITY_IMPERSONATION_LEVEL enumerated type. Without this parameter, the calling process is not be able to open the client's access token using the client's security context, because it is impossible to open executive-level objects using the SecurityIdentification impersonation level.

See Also

AdjustTokenGroups, AdjustTokenPrivileges, GetTokenInformation, OpenProcessToken, SetThreadToken, SetTokenInformation


OpenWindowStation [New - Windows NT]
 OpenWindowStation  QuickInfo  Overview  Group

[New - Windows NT]

The OpenWindowStation function returns a handle to an existing window station.

HWINSTA OpenWindowStation(

LPCTSTR lpszWinStaName,	// name of the window station to open
BOOL fInherit,	// specifies whether returned handle is inheritable
DWORD dwDesiredAccess	// specifies access of returned handle
);
Parameters

lpszWinStaName

Points to a null-terminated string specifying the name of the window station to be opened. Window station names are case-insensitive.

fInherit

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

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 Value

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.

See Also

ExitWindows, ExitWindowsEx


OutputDebugString
 OutputDebugString  QuickInfo  Overview  Group

The OutputDebugString function sends a string to the debugger for the current application.

VOID OutputDebugString(

LPCTSTR  lpszOutputString	// address of string to be displayed
);
Parameters

lpszOutputString

Points to the null-terminated string to be displayed.

Return Value

This function does not return a value.

Remarks

If the application has no debugger, the system debugger displays the string. If the application has no debugger and the system debugger is not active, OutputDebugString does nothing.


OutputProc
 OutputProc  QuickInfo  Overview  Group

The OutputProc function is an application-defined callback function that draws a string as a result of a call to the GrayString function.

BOOL CALLBACK OutputProc(

HDC  hdc,	// handle of device context
LPARAM  lpData,	// address of string to be drawn
int  cchData	// length of string to be drawn
);
Parameters

hdc

Identifies a device context with a bitmap of at least the width and height specified by the nWidth and nHeight parameters passed to GrayString.

lpData

Points to the string to be drawn.

cchData

Specifies the length, in characters, of the string.

Return Value

If it succeeds, the callback function should return TRUE.

If the function fails, the return value is FALSE.

Remarks

The callback function must draw an image relative to the coordinates (0,0).

OutputProc is a placeholder for the application-defined function name.

See Also

GrayString


PackDDElParam
 PackDDElParam  QuickInfo  Overview  Group

The PackDDElParam function packs a DDE lParam value into an internal structure used for sharing DDE data between processes.

LONG PackDDElParam(

UINT  uMsg,	// DDE message to be posted
UINT  uLow,	// low-order word of lParam of message
UINT  uHigh	// high-order word of lParam of message
);
Parameters

uMsg

Specifies the DDE message to be posted.

uLow

Specifies a value that corresponds to the Windows 3.x low-order word of an lParam parameter for the DDE message being posted.

uHigh

Specifies a value that corresponds to the Windows 3.x high-order word of an lParam parameter for the DDE message being posted.

Return Value

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Remarks

The return value must be posted as the lParam parameter of a DDE message; it must not be used for any other purpose. Once the application posts a return value, it need not perform any action to dispose of the lParam parameter.

PackDDElParam eases the porting of 16-bit DDE applications to 32-bit DDE applications.

An application should call this function only for posted DDE messages.

See Also

FreeDDElParam, ReuseDDElParam, UnpackDDElParam


PageSetupDlg
 PageSetupDlg  Overview  Group

The PageSetupDlg function creates a Page Setup dialog box that enables the user to specify the attributes of a printed page, including the paper size, source, orientation, and margins.

BOOL PageSetupDlg(

LPPAGESETUPDLG  lppsd	pointer to a structure
);
Parameters

lppsd

Pointer to a PAGESETUPDLG structure that contains information used to initialize the dialog box and receives information about the user's selections when the function returns.

Return Value

Returns TRUE if the function sets up the page attributes; otherwise, returns FALSE if an error occurs or the user cancels or closes the dialog box. To get extended error information, use the CommDlgExtendedError function .

See Also

CommDlgExtendedError, PAGESETUPDLG


PaintDesktop [New - Windows 95]
 PaintDesktop  QuickInfo  Overview  Group

[New - Windows 95]

The PaintDesktop function fills the clipping region in the specified device context with the desktop pattern or wallpaper. The function is provided primarily for shell desktops.

BOOL WINAPI PaintDesktop(

HDC hdc	\\
);
Parameters

hdc

Identifies the device context.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.


PaintRgn
 PaintRgn  QuickInfo  Overview  Group

The PaintRgn function paints the specified region by using the brush currently selected into the device context.

BOOL PaintRgn(

HDC  hdc,	// handle of device context
HRGN  hrgn	// handle of region to be painted
);
Parameters

hdc

Identifies the device context.

hrgn

Identifies the region to be filled. The region's coordinates are presumed to be logical coordinates.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

See Also

FillRgn


PatBlt
 PatBlt  QuickInfo  Overview  Group

The PatBlt function paints the given rectangle using the brush that is currently selected into the specified device context. The brush color and the surface color(s) are combined by using the given raster operation.

BOOL PatBlt(

HDC  hdc,	// handle of device context
int  nXLeft,	// x-coord. of upper-left corner of rect. to be filled
int  nYLeft,	// y-coord. of upper-left corner of rect. to be filled
int  nWidth,	// width of rectangle to be filled
int  nHeight,	// height of rectangle to be filled
DWORD  dwRop	// raster operation code
);
Parameters

hdc

Identifies the device context.

nXLeft

Specifies the x-coordinate, in logical units, of the upper-left corner of the rectangle to be filled.

nYLeft

Specifies the y-coordinate, in logical units, of the upper-left corner of the rectangle to be filled.

nWidth

Specifies the width, in logical units, of the rectangle.

nHeight

Specifies the height, in logical units, of the rectangle.

dwRop

Specifies the raster operation code. This code may be one of the following values:

Value	Meaning
PATCOPY	Copies the specified pattern into the destination bitmap.
PATINVERT	Combines the colors of the specified pattern with the colors of the destination rectangle by using the Boolean OR operator.
DSTINVERT	Inverts the destination rectangle.
BLACKNESS	Fills the destination rectangle using the color associated with index 0 in the physical palette. (This color is black for the default physical palette.)
WHITENESS	Fills the destination rectangle using the color associated with index 1 in the physical palette. (This color is white for the default physical palette.)
Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The values of the dwRop parameter for this function are a limited subset of the full 256 ternary raster-operation codes; in particular, an operation code that refers to a source rectangle cannot be used.

Not all devices support the PatBlt function. For more information, see the description of the RC_BITBLT capability in the GetDeviceCaps function.

See Also

GetDeviceCaps


PathToRegion
 PathToRegion  QuickInfo  Overview  Group

The PathToRegion function creates a region from the path that is selected into the specified device context.

HRGN PathToRegion(

HDC  hdc	// handle of device context
);
Parameters

hdc

Identifies a device context that contains a closed path.

Return Value

If the function succeeds, the return value identifies a valid region.

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_CAN_NOT_COMPLETE
ERROR_INVALID_PARAMETER
ERROR_NOT_ENOUGH_MEMORY

Remarks

The device context identified by the hdc parameter must contain a closed path.

After PathToRegion converts a path into a region, Windows discards the closed path from the specified device context.

See Also

BeginPath, EndPath , SetPolyFillMode,


PeekConsoleInput
 PeekConsoleInput  QuickInfo  Overview  Group

The PeekConsoleInput function reads data from the specified console input buffer without removing it from the buffer.

BOOL PeekConsoleInput(

HANDLE  hConsoleInput,	// handle of a console input buffer
PINPUT_RECORD  pirBuffer,	// address of the buffer for peek data
DWORD  cInRecords,	// number of records to read
LPDWORD  lpcRead	// address of number of records read
);
Parameters

hConsoleInput

Identifies the input buffer. The handle must have GENERIC_READ access.

pirBuffer

Points to an INPUT_RECORD buffer that receives the input buffer data.

cInRecords

Specifies the size, in records, of the buffer pointed to by the pirBuffer parameter.

lpcRead

Points to a 32-bit variable that receives the number of input records read.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

If the number of records requested exceeds the number of records available in the buffer, the number available is read. If no data is available, the function returns immediately.

See Also

INPUT_RECORD, ReadConsoleInput, WriteConsoleInput


PeekMessage
 PeekMessage  QuickInfo  Overview  Group

The PeekMessage function checks a thread message queue for a message and places the message (if any) in the specified structure.

BOOL PeekMessage(

LPMSG  lpMsg,	// address of structure for message
HWND  hWnd,	// handle of window
UINT  uMsgFilterMin,	// first message
UINT  uMsgFilterMax,	// last message
UINT  wRemoveMsg	// removal flags
);
Parameters

lpMsg

Points to an MSG structure that contains message information from the Windows-based application queue.

hWnd

Identifies the window whose messages are to be examined.

uMsgFilterMin

Specifies the value of the first message in the range of messages to be examined.

uMsgFilterMax

Specifies the value of the last message in the range of messages to be examined.

wRemoveMsg

Specifies how messages are handled. This parameter can be one of the following values:

Value	Meaning
PM_NOREMOVE	Messages are not removed from the queue after processing by PeekMessage.
PM_REMOVE	Messages are removed from the queue after processing by PeekMessage.
You can optionally combine the value PM_NOYIELD with either PM_NOREMOVE or PM_REMOVE. However, PM_NOYIELD has no effect on 32-bit Windows applications. It is defined in Win32 solely to provide compatibility with applications written for previous versions of Windows, where it was used to prevent the current task from halting and yielding system resources to another task. 32-bit Windows applications always run simultaneously.

Return Value

If a message is available, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

Unlike the GetMessage function, the PeekMessage function does not wait for a message to be placed in the queue before returning.

PeekMessage retrieves only messages associated with the window identified by the hWnd parameter or any of its children as specified by the IsChild function, and within the range of message values given by the uMsgFilterMin and uMsgFilterMax parameters. If hWnd is NULL, PeekMessage retrieves messages for any window that belongs to the current thread making the call. (PeekMessage does not retrieve messages for windows that belong to other threads.) If hWnd is −1, PeekMessage only returns messages with a hWnd value of NULL, as posted by the PostAppMessage function. If uMsgFilterMin and uMsgFilterMax are both zero, PeekMessage returns all available messages (that is, no range filtering is performed).

The WM_KEYFIRST and WM_KEYLAST constants can be used as filter values to retrieve all keyboard messages; the WM_MOUSEFIRST and WM_MOUSELAST constants can be used to retrieve all mouse messages.

The PeekMessage function normally does not remove WM_PAINT messages from the queue. WM_PAINT messages remain in the queue until they are processed. However, if a WM_PAINT message has a null update region, PeekMessage does remove it from the queue.

See Also

GetMessage, IsChild, MSG, PostAppMessage, WaitMessage


PeekNamedPipe
 PeekNamedPipe  QuickInfo  Overview  Group

The PeekNamedPipe function copies data from a named or anonymous pipe into a buffer without removing it from the pipe. It also returns information about data in the pipe.

BOOL PeekNamedPipe(

HANDLE  hPipe,	// handle of pipe to copy from
LPVOID  lpvBuffer,	// address of data buffer
DWORD  cbBuffer,	// size, in bytes, of data buffer
LPDWORD  lpcbRead,	// address of number of bytes read
LPDWORD  lpcbAvail,	// address of total number of bytes available
LPDWORD  lpcbMessage	// address of unread bytes in this message
);
Parameters

hPipe

Identifies the pipe. This parameter can be a handle to a named pipe instance, as returned by the CreateNamedPipe or CreateFile function, or it can be a handle to the read end of an anonymous pipe, as returned by the CreatePipe function. The handle must have GENERIC_READ access to the pipe.

lpvBuffer

Points to a buffer that receives data read from the pipe. This parameter can be NULL if no data is to be read.

cbBuffer

Specifies the size, in bytes, of the buffer specified by the lpvBuffer parameter. This parameter is ignored if lpvBuffer is NULL.

lpcbRead

Points to a 32-bit variable that receives the number of bytes read from the pipe. This parameter can be NULL if no data is to be read.

lpcbAvail

Points to a 32-bit variable that receives the total number of bytes available to be read from the pipe. This parameter can be NULL if no data is to be read.

lpcbMessage

Points to a 32-bit variable that receives the number of bytes remaining in this message. This parameter will be zero for byte-type named pipes or for anonymous pipes. This parameter can be NULL if no data is to be read.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

PeekNamedPipe is similar to the ReadFile function with the following exceptions:

•	The data read from the pipe is not removed from the pipe's buffer.

•	The function always returns immediately, even if there is no data in the pipe. The wait mode of a named pipe handle (blocking or nonblocking) has no effect on the function.

•	The function can return additional information about the contents of the pipe.

If the specified handle is a named pipe handle in byte-read mode, the function reads all available bytes up to the size specified in cbBuffer. For a named pipe handle in message-read mode, the function reads the next message in the pipe. If the message is larger than cbBuffer, the function returns TRUE after reading the specified number of bytes. In this situation, lpcbMessage will receive the number of bytes remaining in the message.

See Also

CreateFile, CreateNamedPipe, CreatePipe, ReadFile, WriteFile


Pie
 Pie  QuickInfo  Overview  Group

The Pie function draws a pie-shaped wedge bounded by the intersection of an ellipse and two radials. The pie is outlined by using the current pen and filled by using the current brush.

BOOL Pie(

HDC  hdc,	// handle of device context
int  nLeftRect,	// x-coord. of bounding rectangle's upper-left corner
int  nTopRect,	// y-coord. of bounding rectangle's upper-left corner
int  nRightRect,	// x-coord. of bounding rectangle's lower-right corner
int  nBottomRect,	// y-coord. of bounding rectangle's lower-right corner
int  nXRadial1,	// x-coord. of first radial's endpoint
int  nYRadial1,	// y-coord. of first radial's endpoint
int  nXRadial2,	// x-coord. of second radial's endpoint
int  nYRadial2	// y-coord. of second radial's endpoint
);
Parameters

hdc

Identifies the device context.

nLeftRect

Specifies the x-coordinate of the upper-left corner of the bounding rectangle.

nTopRect

Specifies the y-coordinate of the upper-left corner of the bounding rectangle.

nRightRect

Specifies the x-coordinate of the lower-right corner of the bounding rectangle.

nBottomRect

Specifies the y-coordinate of the lower-right corner of the bounding rectangle.

nXRadial1

Specifies the x-coordinate of the endpoint of the first radial.

nYRadial1

Specifies the y-coordinate of the endpoint of the first radial.

nXRadial2

Specifies the x-coordinate of the endpoint of the second radial.

nYRadial2

Specifies the y-coordinate of the endpoint of the second radial.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The curve of the pie is defined by an ellipse that fits the specified bounding rectangle. The curve begins at the point where the ellipse intersects the first radial and extends counterclockwise to the point where the ellipse intersects the second radial. (A radial is a line drawn from the center of the ellipse to the specified endpoint on the ellipse.)

The current position is neither used nor updated by the Pie function.

Windows 95 only: The sum of the coordinates of the bounding rectangle cannot exceed 32,767. The sum of nLeftRect and nRightRect or nTopRect and nBottomRect parameters cannot exceed 32,767.

See Also

AngleArc, Arc, ArcTo, Chord


PlayEnhMetaFile
 PlayEnhMetaFile  QuickInfo  Overview  Group

The PlayEnhMetaFile function displays the picture stored in the specified enhanced-format metafile.

BOOL PlayEnhMetaFile(

HDC  hdc,	// handle of a device context
HENHMETAFILE  hemf,	// handle of an enhanced metafile
CONST RECT *  lpRect	// address of bounding rectangle
);
Parameters

hdc

Identifies the device context for the output device on which the picture will appear.

hemf

Identifies the enhanced metafile.

lpRect

Points to a RECT structure that contains the coordinates of the bounding rectangle used to display the picture. The coordinates are specified in logical units.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

When an application calls the PlayEnhMetaFile function, Windows uses the picture frame in the enhanced-metafile header to map the picture onto the rectangle pointed to by the lpRect parameter. (This picture may be sheared or rotated by setting the world transform in the output device before calling PlayEnhMetaFile.) Points along the edges of the rectangle are included in the picture.

An enhanced-metafile picture can be clipped by defining the clipping region in the output device before playing the enhanced metafile.

If an enhanced metafile contains an optional palette, an application can achieve consistent colors by setting up a color palette on the output device before calling PlayEnhMetaFile. To retrieve the optional palette, use the GetEnhMetaFilePaletteEntries function.

An enhanced metafile can be embedded in a newly created enhanced metafile by calling PlayEnhMetaFile and playing the source enhanced metafile into the device context for the new enhanced metafile.

The states of the output device context are preserved by this function. Any object created but not deleted in the enhanced metafile is deleted by this function.

To stop this function, an application can call the CancelDC function from another thread to terminate the operation. In this case, the function returns FALSE.

Windows 95: PlayEnhMetaFile is subject to the limitations of the Windows 95 GDI. For example, Windows 95 supports only 16-bit signed coordinates. For records that contain 32-bit values, Windows 95 fails to play the record if the values are not in the range -32,768 to 32,767.

See Also

CancelDC, GetEnhMetaFileHeader, GetEnhMetaFilePaletteEntries, RECT, SetWorldTransform


PlayEnhMetaFileRecord
 PlayEnhMetaFileRecord  QuickInfo  Overview  Group

The PlayEnhMetaFileRecord function plays an enhanced-metafile record by executing the graphics device interface (GDI) functions identified by the record.

BOOL PlayEnhMetaFileRecord(

HDC  hdc,	// handle of device context
LPHANDLETABLE  lpHandletable,	// address of metafile handle table
CONST ENHMETARECORD *  lpEnhMetaRecord,	// address of metafile record
UINT  nHandles	// count of handles
);
Parameters

hdc

Identifies the device context passed to the EnumEnhMetaFile function.

lpHandletable

Points to a table of handles identifying GDI objects used when playing the metafile. The first entry in this table contains the enhanced-metafile handle.

lpEnhMetaRecord

Points to the enhanced-metafile record to be played.

nHandles

Specifies the number of handles in the handle table.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

This is an enhanced-metafile function.

An application typically uses PlayEnhMetaFileRecord in conjunction with the EnumEnhMetaFile function to process and play an enhanced-format metafile one record at a time.

The hdc, lpHandletable, and nHandles parameters must be exactly those passed to the EnhMetaFileProc callback procedure by the EnumEnhMetaFile function.

If PlayEnhMetaFileRecord does not recognize a record, it ignores the record and returns TRUE.

Windows 95: PlayEnhMetaFileRecord is subject to the limitations of the Windows 95 GDI. For example, Windows 95 supports only 16-bit signed coordinates. For records that contain 32-bit values, Windows 95 fails to play the record if the values are not in the range -32,768 to 32,767.

See Also

EnumEnhMetaFile, PlayEnhMetaFile


PlayMetaFile
 PlayMetaFile  QuickInfo  Overview  Group

The PlayMetaFile function displays the picture stored in the given Windows-format metafile on the specified device.

This function is provided for compatibility with 16-bit versions of Windows. Win32-based applications should use the PlayEnhMetaFile function.

BOOL PlayMetaFile(

HDC  hdc,	// handle of the device context
HMETAFILE  hmf	// handle of the metafile
);
Parameters

hdc

Identifies a device context.

hmf

Identifies a Windows-format metafile.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

A Windows-format metafile does not support the new curve, path, and transformation functions such as PolyBezier, BeginPath, and SetWorldTransform. Applications that use these new functions and use metafiles to store pictures created by these functions should use the enhanced-format metafile functions.

To convert a Windows-format metafile into an enhanced format metafile, use the SetWinMetaFileBits function.

A Windows-format metafile can be played multiple times.

A Windows-format metafile can be embedded in a second Windows-format metafile by calling the PlayMetaFile function and playing the source metafile into the device context for the target metafile.

Any object created but not deleted in the Windows-format metafile is deleted by this function.

To stop this function, an application can call the CancelDC function from another thread to terminate the operation. In this case, the function returns FALSE.

See Also

BeginPath, CancelDC, PolyBezier, SetWinMetaFileBits, SetWorldTransform


PlayMetaFileRecord
 PlayMetaFileRecord  QuickInfo  Overview  Group

The PlayMetaFileRecord function plays a Windows-format metafile record by executing the graphics device interface (GDI) function contained within that record.

This function is provided for compatibility with 16-bit versions of Microsoft Windows. Win32-based applications should use the PlayEnhMetaFileRecord function.

BOOL PlayMetaFileRecord(

HDC  hdc,	// handle of device context
LPHANDLETABLE  lpHandletable,	// address of metafile handle table
LPMETARECORD  lpMetaRecord,	// address of metafile record
UINT  nHandles	// count of handles
);
Parameters

hdc

Identifies a device context.

lpHandletable

Points to a table of handles identifying GDI objects used when playing the metafile.

lpMetaRecord

Points to the Windows-format metafile record.

nHandles

Specifies the number of handles in the handle table.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

A Windows-format metafile does not support the new curve, path, and transformation functions, such as PolyBezier, BeginPath, and SetWorldTransform. Applications that use these new functions and use metafiles to store pictures created by these functions, should use the enhanced format metafile functions.

To convert a Windows-format metafile into an enhanced-format metafile, use the SetWinMetaFileBits function.

An application typically uses PlayMetaFileRecord in conjunction with the EnumMetaFile function to process and play a Windows-format metafile one record at a time.

The lpHandletable and nHandles parameters must be identical to those passed to the EnumMetaFileProc callback procedure by EnumMetaFile.

If the PlayMetaFileRecord function does not recognize a record, it ignores the record and returns TRUE.

See Also

BeginPath, EnumMetaFile, PlayMetaFile, PolyBezier, SetWinMetaFileBits, SetWorldTransform


PlgBlt
 PlgBlt  QuickInfo  Overview  Group

The PlgBlt function performs a bit-block transfer of the bits of color data from the specified rectangle in the source device context to the specified parallelogram in the destination device context. If the given bitmask handle identifies a valid monochrome bitmap, the function uses this bitmap to mask the bits of color data from the source rectangle.

BOOL PlgBlt(

HDC  hdcDest,	// handle of destination device context
CONST POINT *  lpPoint,	// vertices of destination parallelogram
HDC  hdcSrc,	// handle of source device context
int  nXSrc,	// x-coord. of upper-left corner of source rect.
int  nYSrc,	// y-coord. of upper-left corner of source rect.
int  nWidth,	// width of source rectangle
int  nHeight,	// height of source rectangle
HBITMAP  hbmMask,	// handle of bitmask
int  xMask,	// x-coord. of upper-left corner of bitmask rect.
int  yMask	// y-coord. of upper-left corner of bitmask rect.
);
Parameters

hdcDest

Identifies the destination device context.

lpPoint

Points to an array of three points in logical space that identify three corners of the destination parallelogram. The upper-left corner of the source rectangle is mapped to the first point in this array, the upper-right corner to the second point in this array, and the lower-left corner to the third point. The lower-right corner of the source rectangle is mapped to the implicit fourth point in the parallelogram.

hdcSrc

Identifies the source device context.

nXSrc

Specifies the x-coordinate, in logical units, of the upper-left corner of the source rectangle.

nYSrc

Specifies the y-coordinate, in logical units, of the upper-left corner of the source rectangle.

nWidth

Specifies the width, in logical units, of the source rectangle.

nHeight

Specifies the height, in logical units, of the source rectangle.

hbmMask

Identifies an optional monochrome bitmap that is used to mask the colors of the source rectangle.

xMask

Specifies the x-coordinate of the upper-left corner of the the monochrome bitmap.

yMask

Specifies the y-coordinate of the upper-left corner of the the monochrome bitmap.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The fourth vertex of the parallelogram (D) is defined by treating the first three points (A, B, and C) as vectors and computing D = B + C − A.

If the bitmask exists, a value of 1 in the mask indicates that the source pixel color should be copied to the destination. A value of 0 in the mask indicates that the destination pixel color is not to be changed.

If the mask rectangle is smaller than the source and destination rectangles, the function replicates the mask pattern.

Scaling, translation, and reflection transformations are allowed in the source device context; however, rotation and shear transformations are not.

If the mask bitmap is not a monochrome bitmap, an error occurs.

The stretching mode for the destination device context is used to determine how to stretch or compress the pixels, if that is necessary.

When an enhanced metafile is being recorded, an error occurs if the source device context identifies an enhanced-metafile device context.

The destination coordinates are transformed according to the destination device context; the source coordinates are transformed according to the source device context. If the source transformation has a rotation or shear, an error is returned.

If the destination and source rectangles do not have the same color format, PlgBlt converts the source rectangle to match the destination rectangle.

Not all devices support the PlgBlt function. For more information, see the description of the RC_BITBLT raster capability in the GetDeviceCaps function.

If the source and destination device contexts represent incompatible devices, PlgBlt returns an error.

See Also

BitBlt, GetDeviceCaps, MaskBlt, SetStretchBltMode, StretchBlt


PolyBezier
 PolyBezier  QuickInfo  Overview  Group

The PolyBezier function draws one or more Bézier curves.

BOOL PolyBezier(

HDC  hdc,	// handle of device context
CONST POINT *  lppt,	// address of endpoints and control points
DWORD  cPoints	// count of endpoints and control points
);
Parameters

hdc

Identifies a device context.

lppt

Points to an array of POINT structures that contain the endpoints and control points of the curve(s).

cPoints

Specifies the number of points in the lppt array. This value must be one more than three times the number of curves to be drawn, because each Bézier curve requires two control points and an endpoint, and the initial curve requires an additional starting point.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

Th Polybezier function draws cubic Bézier curves by using the endpoints and control points specified by the lppt parameter. The first curve is drawn from the first point to the fourth point by using the second and third points as control points. Each subsequent curve in the sequence needs exactly three more points: the ending point of the previous curve is used as the starting point, the next two points in the sequence are control points, and the third is the ending point.

The current position is neither used nor updated by the PolyBezier function. The figure is not filled.

This function draws lines by using the current pen.

See Also

MoveToEx, POINT, PolyBezierTo


PolyBezierTo
 PolyBezierTo  QuickInfo  Overview  Group

The PolyBezierTo function draws one or more Bézier curves.

BOOL PolyBezierTo(

HDC  hdc,	// handle of device context
CONST POINT *  lppt,	// address of endpoints and control points
DWORD  cCount	// count of endpoints and control points
);
Parameters

hdc

Identifies a device context.

lppt

Points to an array of POINT structures that contains the endpoints and control points.

cCount

Specifies the number of points in the lppt array. This value must be three times the number of curves to be drawn, because each Bézier curve requires two control points and an ending point.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

This function draws cubic Bézier curves by using the control points specified by the lppt parameter. The first curve is drawn from the current position to the third point by using the first two points as control points. For each subsequent curve, the function needs exactly three more points, and uses the ending point of the previous curve as the starting point for the next.

PolyBezierTo moves the current position to the ending point of the last Bézier curve. The figure is not filled.

This function draws lines by using the current pen.

See Also

MoveToEx, POINT, PolyBezier


PolyDraw
 PolyDraw  QuickInfo  Overview  Group

The PolyDraw function draws a set of line segments and Bézier curves.

BOOL PolyDraw(

HDC  hdc,	// handle of a device context
CONST POINT *  lppt,	// address of array of points
CONST BYTE *  lpbTypes,	// address of line and curve identifiers
int  cCount	// count of points
);
Parameters

hdc

Identifies a device context.

lppt

Points to an array of POINT structures that contains the endpoints for each line segment and the endpoints and control points for each Bézier curve.

lpbTypes

Points to an array that specifies how each point in the lppt array is used. Types can be one of the following:

Type	Meaning
PT_MOVETO	Specifies that this point starts a disjoint figure. This point becomes the new current position.
PT_LINETO	Specifies that a line is to be drawn from the current position to this point, which then becomes the new current position.
PT_BEZIERTO	Specifies that this point is a control point or ending point for a Bézier curve.
	PT_BEZIERTO types always occur in sets of three. The current position defines the starting point for the Bézier curve. The first two PT_BEZIERTO points are the control points, and the third PT_BEZIERTO point is the ending point. The ending point becomes the new current position. If there are not three consecutive PT_BEZIERTO points, an error results.
A PT_LINETO or PT_BEZIERTO type can be combined with the following value by using the bitwise operator OR to indicate that the corresponding point is the last point in a figure and the figure is closed:

Value	Meaning
PT_CLOSEFIGURE	Specifies that the figure is automatically closed after the PT_LINETO or PT_BEZIERTO type for this point is done. A line is drawn from this point to the most recent PT_MOVETO or MoveTo point.
	This value is combined with the PT_LINETO type for a line, or with the PT_BEZIERTO type of the ending point for a Bézier curve, by using the bitwise operator OR.
	The current position is set to the ending point of the closing line.
cCount

Specifies the total number of points in the lppt array, the same as the number of bytes in the lpbTypes array.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

The PolyDraw function can be used in place of consecutive calls to MoveTo, LineTo, and PolyBezierTo functions to draw disjoint figures. The lines and curves are drawn using the current pen and figures are not filled. If there is an active path started by calling BeginPath, PolyDraw adds to the path.

The points contained in the lppt array and in the lpbTypes array indicate whether each point is part of a MoveTo, LineTo, or PolyBezierTo operation. It is also possible to close figures.

This function updates the current position.

See Also

BeginPath, EndPath, LineTo, MoveTo, POINT, PolyBezierTo, PolyLine


Polygon
 Polygon  QuickInfo  Overview  Group

The Polygon function draws a polygon consisting of two or more vertices connected by straight lines. The polygon is outlined by using the current pen and filled by using the current brush and polygon fill mode.

BOOL Polygon(

HDC  hdc,	// handle of device context
CONST POINT  *lpPoints,	// address of polygon's vertices
int  nCount	// count of polygon's vertices
);
Parameters

hdc

Identifies the device context.

lpPoints

Points to an array of POINT structures that specify the vertices of the polygon.

nCount

Specifies the number of vertices in the array. This value must be greater than or equal to 2.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The polygon is closed automatically by drawing a line from the last vertex to the first.

The current position is neither used nor updated by the Polygon function.

See Also

GetPolyFillMode, POINT, Polyline, PolylineTo, PolyPolygon, SetPolyFillMode


Polyline
 Polyline  QuickInfo  Overview  Group

The Polyline function draws a series of line segments by connecting the points in the specified array.

BOOL Polyline(

HDC  hdc,	// handle of device context
CONST POINT  *lppt,	// address of array containing endpoints
int  cPoints	// number of points in the array
);
Parameters

hdc

Identifies a device context.

lppt

Points to an array of POINT structures. Each structure in the array identifies a point in logical space.

cPoints

Specifies the number of points in the array. This number must be greater than or equal to two.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

The lines are drawn from the first point through subsequent points by using the current pen. Unlike the LineTo function, the Polyline function neither uses nor updates the current position.

See Also

LineTo, MoveToEx, POINT, PolylineTo, PolyPolyline


PolylineTo
 PolylineTo  QuickInfo  Overview  Group

The PolylineTo function draws one or more straight lines.

BOOL PolylineTo(

HDC  hdc,	// handle of device context
CONST POINT *  lppt,	// address of array of points
DWORD  cCount	// number of points in array
);
Parameters

hdc

Identifies the device context.

lppt

Points to an array of POINT structures that contains the vertices of the line.

cCount

Specifies the number of points in the array.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

A line is drawn from the current position to the first point specified by the lppt parameter by using the current pen. For each additional line, the function draws from the ending point of the previous line to the next point specified by lppt.

PolylineTo moves the current position to the ending point of the last line.

If the line segments drawn by this function form a closed figure, the figure is not filled.

See Also

LineTo, MoveToEx, POINT, Polyline


PolyPolygon
 PolyPolygon  QuickInfo  Overview  Group

The PolyPolygon function draws a series of closed polygons. Each polygon is outlined by using the current pen and filled by using the current brush and polygon fill mode. The polygons drawn by this function can overlap.

BOOL PolyPolygon(

HDC  hdc,	// handle of device context
CONST POINT  *lpPoints,	// points to array of vertices for all polygons
LPINT  lpPolyCounts,	// points to array with count of vertices for each polygon
int  nCount	// count of polygons
);
Parameters

hdc

Identifies the device context.

lpPoints

Points to an array of POINT structures that define the vertices of the polygons. The polygons are specified consecutively. Each polygon is closed automatically by drawing a line from the last vertex to the first. Each vertex should be specified once.

lpPolyCounts

Points to an array of integers, each of which specifies the number of points in the corresponding polygon. Each integer must be greater than or equal to 2.

nCount

Specifies the total number of polygons.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The current position is neither used nor updated by this function.

See Also

GetPolyFillMode, POINT, Polygon, Polyline, PolylineTo, SetPolyFillMode


PolyPolyline
 PolyPolyline  QuickInfo  Overview  Group

The PolyPolyline function draws multiple series of connected line segments.

BOOL PolyPolyline(

HDC  hdc,	// handle of a device context
CONST POINT *  lppt,	// address of an array of points
CONST DWORD *  lpdwPolyPoints,	// address of an array of values
DWORD  cCount	// number of counts in the second array
);
Parameters

hdc

Identifies the device context.

lppt

Points to an array of POINT structures that contains the vertices of the polylines. The polylines are specified consecutively.

lpdwPolyPoints

Points to an array of variables specifying the number of points in the lppt array for the corresponding polygon. Each entry must be greater than or equal to two.

cCount

Specifies the total number of counts in the lpdwPolyPoints array.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

The line segments are drawn by using the current pen. The figures formed by the segments are not filled.

The current position is neither used nor updated by this function.

See Also

POINT, Polyline, PolylineTo


PolyTextOut
 PolyTextOut  QuickInfo  Overview  Group

The PolyTextOut function draws several strings using the font and text colors currently selected in the specified device context.

BOOL PolyTextOut(

HDC  hdc,	// handle of device context
CONST POLYTEXT *  pptxt,	// address of array of structures that identify strings
int  cStrings	// number of structures in array
);
Parameters

hdc

Identifies the device context.

pptxt

Points to an array of POLYTEXT structures describing the strings to be drawn. The array contains one structure for each string to be drawn.

cStrings

Specifies the number of POLYTEXT structures in the pptxt array.

Return Value

If the function is successful, the return value is TRUE.

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

Remarks

Each POLYTEXT structure contains the coordinates of a reference point that Windows uses to align the corresponding string of text. An application can specify how the reference point is used by calling the SetTextAlign function. An application can determine the current text-alignment setting for the specified device context by calling the GetTextAlign function.

To draw a single string of text, the application should call the ExtTextOut function.

See Also

ExtTextOut, GetTextAlign, POLYTEXT, SetTextAlign


PostAppMessage
 PostAppMessage  QuickInfo  Overview  Group

The PostAppMessage function is retained only for compatibility with 16-bit versions of Windows. Win32-based applications should use the PostThreadMessage function.

Remarks

The PostAppMessage function used a process identifier as its first parameter, but its replacement, the PostThreadMessage function, uses a thread identifier as its first parameter.

See Also

PostThreadMessage


PostMessage
 PostMessage  QuickInfo  Overview  Group

The PostMessage function places (posts) a message in the message queue associated with the thread that created the specified window and then returns without waiting for the thread to process the message. Messages in a message queue are retrieved by calls to the GetMessage or PeekMessage function.

BOOL PostMessage(

HWND  hwnd,	// handle of destination window
UINT  uMsg,	// message to post
WPARAM  wParam,	// first message parameter
LPARAM  lParam	// second message parameter
);
Parameters

hwnd

Identifies the window whose window procedure is to receive the message. Two values have special meanings:

Value	Meaning
HWND_BROADCAST	The message is posted to all top-level windows in the system, including disabled or invisible unowned windows, overlapped windows, and pop-up windows. The message is not posted to child windows.
NULL	The function behaves like a call to PostThreadMessage with the dwThreadId parameter set to the identifier of the current thread.
uMsg

Specifies the message to be posted.

wParam

Specifies additional message-specific information.

lParam

Specifies additional message-specific information.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

A 32-bit application should not post messages less than WM_USER that contain pointers.

See Also

GetMessage, PeekMessage, PostThreadMessage, SendDlgItemMessage, SendMessage


PostQueuedCompletionStatus [New - Windows NT]
 PostQueuedCompletionStatus  QuickInfo

[New - Windows NT]

The PostQueuedCompletionStatus function lets you post an I/O completion packet to an I/O completion port. The I/O completion packet will satisfy an outstanding call to the GetQueuedCompletionStatus function. The GetQueuedCompletionStatus function returns with the three values passed as the second, third, and fourth parameters of the call to PostQueuedCompletionStatus.

BOOL PostQueuedCompletionStatus(

HANDLE CompletionPort,	// handle to an I/O completion port
DWORD dwNumberOfBytesTransferred,	// value to return via  //     GetQueuedCompletionStatus'  //     lpNumberOfBytesTranferred
DWORD dwCompletionKey,	// value to return via  //     GetQueuedCompletionStatus'  //     lpCompletionKey
LPOVERLAPPED lpOverlapped	// value to return via  //     GetQueuedCompletionStatus' lpOverlapped
);
Parameters

CompletionPort

Handle to an I/O completion port that you want to post an I/O completion packet to.

dwNumberOfBytesTransferred

Specifies a value to be returned through the lpNumberOfBytesTransferred parameter of the GetQueuedCompletionStatus function.

dwCompletionKey

Specifies a value to be returned through the lpCompletionKey parameter of the GetQueuedCompletionStatus function.

lpOverlapped

Specifies a value to be returned through the lpOverlapped parameter of the GetQueuedCompletionStatus function.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

For more information concerning dwNumberOfBytesTransferred, dwCompletionKey, and lpOverlapped, see GetQueuedCompletionStatus and the descriptions of the parameters those values are returned through.

See Also

CreateIoCompletionPort, GetQueuedCompletionStatus, OVERLAPPED


PostQuitMessage
 PostQuitMessage  QuickInfo  Overview  Group

The PostQuitMessage function indicates to Windows that a thread has made a request to terminate (quit). It is typically used in response to a WM_DESTROY message.

VOID PostQuitMessage(

int  nExitCode	// exit code
);
Parameters

nExitCode

Specifies an application exit code. This value is used as the wParam parameter of the WM_QUIT message.

Return Value

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 Windows. The exit value returned to Windows must be the wParam parameter of the WM_QUIT message.

See Also

GetMessage, PeekMessage, PostMessage, WM_DESTROY, WM_QUIT


PostThreadMessage
 PostThreadMessage  QuickInfo  Overview  Group

The PostThreadMessage function places (posts) a message in the message queue of the specified thread and then returns without waiting for the thread to process the message.

BOOL PostThreadMessage(

DWORD  dwThreadId,	// thread identifier
UINT  uMsg,	// message to post
WPARAM  wParam,	// first message parameter
LPARAM  lParam	// second message parameter
);
Parameters

dwThreadId

Identifies the thread to which the message will be posted.

The function fails if the specified thread does not have a message queue. The system creates a thread's message queue when the thread makes its first call to one of the Win32 USER or GDI functions.

uMsg

Specifies the type of message to be posted.

wParam

Specifies additional message-specific information.

lParam

Specifies additional message-specific information.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

This function replaces the PostAppMessage function. New Win32-based applications should use PostThreadMessage. 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.

See Also

GetCurrentThreadId, GetMessage, GetWindowThreadProcessId, MSG, PeekMessage, PostMessage


PrepareTape
 PrepareTape  QuickInfo  Overview  Group

The PrepareTape function prepares the tape to be accessed or removed.

DWORD PrepareTape(

HANDLE  hDevice,	// handle of open device
DWORD  dwOperation,	// preparation method
BOOL  bImmediate	// return after operation begins
);
Parameters

hDevice

Identifies the device preparing the tape. This handle is created by using the CreateFile function.

dwOperation

Specifies how the tape device is to be prepared. This parameter can be one of the following values:

Value	Meaning
TAPE_FORMAT	Performs a low-level format of the tape. Currently, only the QIC117 device supports this feature.
TAPE_LOAD	Loads the tape and moves the tape to the beginning.
TAPE_LOCK	Locks the tape ejection mechanism so that the tape is not ejected accidentally.
TAPE_TENSION	Adjusts the tension by moving the tape to the end of the tape and back to the beginning. This option is not supported by all devices. This value is ignored if it is not supported.
TAPE_UNLOAD	Moves the tape to the beginning for removal from the device. After a successful unload operation, the device returns errors to applications that attempt to access the tape, until the tape is loaded again.
TAPE_UNLOCK	Unlocks the tape ejection mechanism.
bImmediate

Specifies whether to return as soon as the preparation begins. If this parameter is TRUE, the function returns immediately. If it is FALSE, the function does not return until the operation has been completed.

Return Value

If the function succeeds, the return value is NO_ERROR.

If the function fails, the return value is one of the following error codes:

Error	Description
ERROR_BEGINNING_OF_MEDIA	An attempt to access data before the beginning-of-medium marker failed.
ERROR_BUS_RESET	A reset condition was detected on the bus.
ERROR_END_OF_MEDIA	The end-of-tape marker was reached during an operation.
ERROR_FILEMARK_DETECTED	A filemark was reached during an operation.
ERROR_SETMARK_DETECTED	A setmark was reached during an operation.
ERROR_NO_DATA_DETECTED	The end-of-data marker was reached during an operation.
ERROR_PARTITION_FAILURE	The tape could not be partitioned.
ERROR_INVALID_BLOCK_LENGTH	The block size is incorrect on a new tape in a multivolume partition.
ERROR_DEVICE_NOT_PARTITIONED	The partition information could not be found when a tape was being loaded.
ERROR_MEDIA_CHANGED	The tape that was in the drive has been replaced or removed.
ERROR_NO_MEDIA_IN_DRIVE	There is no media in the drive.
ERROR_NOT_SUPPORTED	The tape driver does not support a requested function.
ERROR_UNABLE_TO_LOCK_MEDIA	An attempt to lock the ejection mechanism failed.
ERROR_UNABLE_TO_UNLOAD_MEDIA	An attempt to unload the tape failed.
ERROR_WRITE_PROTECT	The media is write protected.
Remarks

Some tape devices do not support certain tape operations. See your tape device documentation and use the GetTapeParameters function to determine your tape device's capabilities.

See Also

CreateFile, GetTapeParameters


PrintDlg
 PrintDlg  QuickInfo  Overview  Group

The PrintDlg function displays a Print dialog box or a Print Setup dialog box. The Print dialog box enables the user to specify the properties of a particular print job. The Print Setup dialog box allows the user to select additional job properties and to configure the printer.

BOOL PrintDlg(

LPPRINTDLG  lppd	// address of structure with initialization data
);
Parameters

lppd

Points 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 Value

If the function succeeds in configuring the printer, the return value is TRUE. It is FALSE if an error occurs, the user chooses the Cancel button, or the user chooses the Close command on the System menu to close the dialog box. (The return value is also FALSE if the user chooses the Setup button to display the Print Setup dialog box, chooses the OK button in the Print Setup dialog box, and then chooses the Cancel button in the Print dialog box.)

The CommDlgExtendedError function can be used to get extended error information, which may be one of the following values:

CDERR_FINDRESFAILURE	PDERR_CREATEICFAILURE
CDERR_INITIALIZATION	PDERR_DEFAULTDIFFERENT
CDERR_LOADRESFAILURE	PDERR_DNDMMISMATCH
CDERR_LOADSTRFAILURE	PDERR_GETDEVMODEFAIL
CDERR_LOCKRESFAILURE	PDERR_INITFAILURE
CDERR_MEMALLOCFAILURE	PDERR_LOADDRVFAILURE
CDERR_MEMLOCKFAILURE	PDERR_NODEFAULTPRN
CDERR_NOHINSTANCE	PDERR_NODEVICES
CDERR_NOHOOK	PDERR_PARSEFAILURE
CDERR_NOTEMPLATE	PDERR_PRINTERNOTFOUND
CDERR_STRUCTSIZE	PDERR_RETDEFFAILURE
Remarks

If the hook function (pointed to by the lpfnPrintHook or lpfnSetupHook member of the PRINTDLG structure) processes the WM_CTLCOLORDLG message, the hook function must return a handle for the brush that should be used to paint the control background.

If you specify the PD_RETURNDC value in the Flags member of the PRINTDLG structure and the user selects Print To File from the Print dialog box, you can use the DC returned in the hDC member of the structure to generate output, but only after you prepare the file for output by specifying the name of the file in the lpszOutput member of the DOCINFO structure and calling the StartDoc function.

See Also

CommDlgExtendedError, CreateDC, DOCINFO, PRINTDLG, StartDoc, WM_CTLCOLORDLG


PrinterMessageBox
 PrinterMessageBox  QuickInfo  Overview  Group

The PrinterMessageBox function displays a message box that lets an application that is printing notify the user of a printing job error. If the owner of the job is logged on remotely, the function sends a net popup to the owner. If the user selects Cancel in the message box, the function cancels the print job; otherwise, the function clears the job error status, and the system tries to print the job again.

HPRINTER PrinterMessageBox (

HANDLE  hPrinter,	// handle of printer
DWORD  dwError,	// error identifier
HWND  hwndOwner,	// handle of owner window
LPTSTR  pText,	// pointer to message box text
LPTSTR  pCaption,	// pointer to message box title
DWORD  dwType	// style of message box
);
Parameters

hPrinter

Identifies the printer to which the job was sent.

dwError

Specifies the error that occurred. This parameter can be one of the following values:

Value	Meaning
ERROR_OUT_OF_PAPER	The printer is out of paper.
ERROR_NOT_READY	The printer is not ready.
hwndOwner

Identifies an owner window for the message box the function creates. If this parameter is NULL, the message box has no owner window.

pText

Points to a null-terminated string that specifies the message to be displayed.

pCaption

Points to a null-terminated string that specifies the dialog box title. If this parameter is NULL, the function uses the default title "Error".

dwType

Specifies the contents and behavior of the dialog box. This parameter can be a combination of any of the values accepted by the MessageBox function's fourth parameter; however, it is recommended that an application use the following combination:

   MB_ICONSTOP | MB_RETRYCANCEL | MB_SETFOREGROUND

Return Value

If PrinterMessageBox sends a net popup, the return value is IDOK. Otherwise, the function returns the value returned by the message box the function displays. Two typical return values are the following:

Value	Meaning
IDCANCEL	Cancel button was selected.
IDRETRY	Retry button was selected.
For a more complete list of message box return values, see MessageBox.

See Also

MessageBox


PrinterProperties
 PrinterProperties  QuickInfo  Overview  Group

The PrinterProperties function displays a printer-properties dialog box for the specified printer.

BOOL PrinterProperties(

hwnd  hwnd,	// handle of parent window
HANDLE  hPrinter	// handle of printer object
);
Parameters

hwnd

Identifies the parent window of the dialog box.

hPrinter

Identifies a printer object.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

OpenPrinter


PrivilegeCheck
 PrivilegeCheck  QuickInfo  Overview  Group

The PrivilegeCheck function tests the security context represented by a specific access token to discover whether it contains the specified privileges. This function is typically called by a server application to check the privileges of a client's access token.

BOOL PrivilegeCheck(

HANDLE  hClientToken,	// handle of client's access token
PPRIVILEGE_SET  pps,	// address of privileges
LPBOOL  lpfResult	// address of flag for result
);
Parameters

hClientToken

Identifies an access token representing a client process. This handle must have been obtained by opening the token of a thread impersonating the client. The token must be open for TOKEN_QUERY access.

pps

Points to a PRIVILEGE_SET structure specifying the privileges required.

The specified access token is checked to see which of the specified privileges are present. When a privilege specified in the PRIVILEGE_SET structure is found in the access token, the function sets the SE_PRIVILEGE_USED_FOR_ACCESS attribute for that privilege in the corresponding LUID_AND_ATTRIBUTES structure.

lpfResult

Points to a flag the function sets to indicate whether the access token contains any or all of the specified privileges. If PRIVILEGE_SET_ALL_NECESSARY is specified in the Control member of the PRIVILEGE_SET structure pointed to by the pps parameter, this flag is TRUE only if all requested privileges are present in the access token. If PRIVILEGE_SET_ALL_NECESSARY is not specified, and if any of the privileges are present, this flag is TRUE.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

AccessCheck, AccessCheckAndAuditAlarm, AreAllAccessesGranted, AreAnyAccessesGranted, LookupPrivilegeDisplayName, LookupPrivilegeName, LookupPrivilegeValue, LUID_AND_ATTRIBUTES, ObjectPrivilegeAuditAlarm, PRIVILEGE_SET, PrivilegedServiceAuditAlarm


PrivilegedServiceAuditAlarm
 PrivilegedServiceAuditAlarm  QuickInfo  Overview  Group

The PrivilegedServiceAuditAlarm function generates audit messages when an attempt is made to perform privileged system service operations. Alarms are not supported in the current version of Windows NT.

BOOL PrivilegedServiceAuditAlarm(

LPCTSTR  lpszSubsystem,	// address of string for subsystem name
LPCTSTR  lpszService,	// address of string for service name
HANDLE  hClientToken,	// handle of access token
PPRIVILEGE_SET  pps,	// address of privileges
BOOL  fAccessGranted	// flag for granted access rights
);
Parameters

lpszSubsystem

Points to a null-terminated string specifying the name of the subsystem calling the function, such as "DEBUG" or "WIN32".

lpszService

Points to a null-terminated string specifying the name of the privileged subsystem service. For example, "RESET RUNTIME LOCAL SECURITY POLICY" might be specified by a local security authority service used to update the local security policy database.

hClientToken

Identifies an access token representing the client that requested the operation. This handle must have been obtained by opening the token of a thread impersonating the client. The token must be open for TOKEN_QUERY access.

pps

Points to a PRIVILEGE_SET structure containing the privileges required to perform the operation. The information in this structure is supplied by a call to the PrivilegeCheck function.

fAccessGranted

Specifies a flag indicating whether access was granted or denied in a previous call to an access-checking function, such as PrivilegeCheck. If access is granted, this flag is TRUE. If access is denied, it is FALSE.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The PrivilegedServiceAuditAlarm function requires the calling process to have SE_AUDIT_NAME privilege. The test for this privilege is always performed against the primary token of the calling process. This allows the calling process to impersonate a client during the call.

The PrivilegedServiceAuditAlarm function can send many messages to port objects. This can result in a significant delay before the function returns. The design of applications calling PrivilegedServiceAuditAlarm can take this potential delay into account. For example, this consideration may affect the design of an application that uses mutexes to lock structures.

See Also

AccessCheck, AccessCheckAndAuditAlarm, AreAllAccessesGranted, AreAnyAccessesGranted, MapGenericMask, ObjectCloseAuditAlarm, ObjectOpenAuditAlarm, ObjectPrivilegeAuditAlarm, PrivilegeCheck, PRIVILEGE_SET


ProfClear
 ProfClear  Overview  Group

The ProfClear function is not implemented in the Win32 API.


ProfFinish
 ProfFinish  Overview  Group

The ProfFinish function is not implemented in the Win32 API.


ProfFlush
 ProfFlush  Overview  Group

The ProfFlush function is not implemented in the Win32 API.


ProfInsChk
 ProfInsChk  Overview  Group

The ProfInsChk function is not implemented in the Win32 API.


ProfSampRate
 ProfSampRate  Overview  Group

The ProfSampRate function is not implemented in the Win32 API.


ProfSetup
 ProfSetup  Overview  Group

The ProfSetup function is not implemented in the Win32 API.


ProfStart
 ProfStart  Overview  Group

The ProfStart function is not implemented in the Win32 API.


ProfStop
 ProfStop  Overview  Group

The ProfStop function is not implemented in the Win32 API.


PropEnumProc
 PropEnumProc  QuickInfo  Overview  Group

A PropEnumProc function is an application-defined callback function that receives property entries from a window's property list. A PropEnumProc function is called as a result of a call to the EnumProps function. A value of type PROPENUMPROC is a pointer to a PropEnumProc function.

BOOL CALLBACK PropEnumProc(

HWND  hwnd,	// handle to window whose property list is being enumerated
LPCTSTR  lpszString,	// string component of property
HANDLE  hData	// data handle component of property
);
Parameters

hwnd

Handle to the window whose property list is being enumerated.

lpszString

Pointer to a null-terminated string. This string is the string component of a property list entry. This is the string that was specified, along with a data handle, when the property was added to the window's property list via a call to the SetProp function.

hData

Handle to data. This handle is the data component of a property list entry.

Return Value

The callback function should return TRUE to continue the property list enumeration.

The callback function should 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.

PropEnumProc is a placeholder for the application-defined function name.

See Also

EnumProps, EnumPropsEx, PropEnumProcEx, RemoveProp, SetProp


PropEnumProcEx
 PropEnumProcEx  QuickInfo  Overview  Group

A PropEnumProcEx function is an application-defined callback function that receives property entries from a window's property list. A PropEnumProcEx function is called as a result of a call to the EnumPropsEx function. A value of type PROPENUMPROCEX is a pointer to a PropEnumProcEx function.

BOOL CALLBACK PropEnumProcEx(

HWND  hwnd,	// handle of window with property
LPCTSTR  lpszString,	// string component of property
HANDLE  hData,	// data handle component of property
DWORD  dwData	// application-defined data
);
Parameters

hwnd

Handle to the window whose property list is being enumerated.

lpszString

Pointer to a null-terminated string. This string is the string component of a property list entry. This is the string that was specified, along with a data handle, when the property was added to the window's property list via a call to the SetProp function.

hData

Handle to data. This handle is the data component of a property list entry.

dwData

Application-defined data. This is the value that was specified as the lParam parameter of the call to EnumPropsEx that initiated the enumeration.

Return Value

The callback function should return TRUE to continue the property list enumeration.

The callback function should 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.

PropEnumProcEx is a placeholder for the application-defined function name.

See Also

EnumProps, EnumPropsEx, PropEnumProc, RemoveProp, SetProp


PropertySheet [New - Windows NT]
 PropertySheet  Overview  Group

[New - Windows NT]

The PropertySheet function creates a property sheet and adds the pages defined in the specified property sheet header structure.

int PropertySheet(

LPCPROPSHEETHEADER  lppsph
);
Parameters

lppsph

Pointer to a PROPSHEETHEADER structure that defines the frame and pages of a property sheet.

Return Value

Returns a positive value if successful or − 1 otherwise.

If the dwFlags member of the PROPSHEETHEADER structure specifies the PSH_MODELESS flag, the successful return value is the window handle of the property sheet dialog.

The following return values have a special meaning:

Value	Meaning
ID_PSREBOOTSYSTEM	A page sent the PSM_REBOOTSYSTEM message to the property sheet. The computer must be restarted for the user's changes to take effect.
ID_PSRESTARTWINDOWS	A page sent the PSM_RESTARTWINDOWS message to the property sheet. Windows must be restarted for the user's changes to take effect.
Remarks

By default, PropertySheet creates a modal dialog. If the dwFlags member of the PROPSHEETHEADER structure specifies the PSH_MODELESS flag, PropertySheet creates a modeless dialog and returns immediately after the dialog is created. In this case, the PropertySheet return value is the window handle of the modeless dialog.

For a modeless property sheet, your message loop should use PSM_ISDIALOGMESSAGE to pass messages to the property sheet dialog. Your message loop should use PSM_GETCURRENTPAGEHWND to determine when to destroy the dialog. When the user selects the OK or Cancel button, PSM_GETCURRENTPAGEHWND returns NULL, and you can then use the DestroyWindow function to destroy the dialog.

See Also

DestroyWindow, PROPSHEETHEADER, PSM_GETCURRENTPAGEHWND, PSM_ISDIALOGMESSAGE, PSM_REBOOTSYSTEM, PSM_RESTARTWINDOWS


PropSheetPageProc [New - Windows NT]
 PropSheetPageProc  QuickInfo  Overview  Group

[New - Windows NT]

The PropSheetPageProc function specifies an application-defined callback function that a property sheet calls when a page is created and when it is about to be destroyed. An application can use this function to perform initialization and cleanup operations for the page.

UINT CALLBACK PropSheetPageProc(

HWND  hwnd,
UINT  uMsg,
LPPROPSHEETPAGE  ppsp
);
Parameters

hwnd

Reserved; must be NULL.

uMsg

Action flag. This parameter can be one of the following values:

Value	Meaning
PSPCB_CREATE	A page is being created. Return nonzero to allow the page to be created or zero to prevent it.
PSPCB_RELEASE	A page is being destroyed. The return value is ignored.
ppsp

Pointer to a PROPSHEETPAGE structure that defines the page being created or destroyed.

Return Value

The return value depends on the value of uMsg.

Remarks

An application must specify the address of this callback function in the pfnCallback member of a PROPSHEETPAGE structure before specifying the address of the structure in a call to the CreatePropertySheetPage function.

See Also

CreatePropertySheetPage, PROPSHEETPAGE


PropSheetProc [New - Windows NT]
 PropSheetProc  QuickInfo  Overview  Group

[New - Windows NT]

The PropSheetProc function specifies an application-defined callback function that the system calls when the property sheet is being initialized.

int CALLBACK PropSheetProc(

HWND  hwndDlg,
UINT  uMsg,
LPARAM  lParam
);
Parameters

hwndDlg

Handle to the property sheet dialog box.

uMsg

Action flag. Currently, only the PSCB_INITIALIZED value is defined, which indicates that the property sheet is being initialized.

lParam

Always zero.

Return Value

The function returns zero.

Remarks

An application must specify the address of this callback function in the pfnCallback member of a PROPSHEETHEADER structure before specifying the address of the structure in a call to the PropertySheet function.

See Also

PropertySheet, PROPSHEETHEADER


PtInRect
 PtInRect  QuickInfo  Overview  Group

The PtInRect function determines whether the specified point lies within the specified rectangle. A point is within a rectangle if it lies on the left or top side or is within all four sides. A point on the right or bottom side is considered outside the rectangle.

BOOL PtInRect(

CONST RECT  *lprc,	// address of structure with rectangle
POINT  pt	// structure with point
);
Parameters

lprc

Points to a RECT structure that contains the specified rectangle.

pt

Specifies a POINT structure that contains the specified point.

Return Value

If the specified point lies within the rectangle, the return value is TRUE.

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

See Also

EqualRect, IsRectEmpty, POINT, RECT


PtInRegion
 PtInRegion  QuickInfo  Overview  Group

The PtInRegion function determines whether the specified point is inside the specified region.

BOOL PtInRegion(

HRGN  hrgn,	// handle of region
int  X,	// x-coordinate of point
int  Y	// y-coordinate of point
);
Parameters

hrgn

Identifies the region to be examined.

X

Specifies the x-coordinate of the point.

Y

Specifies the y-coordinate of the point.

Return Value

If the specified point is in the region, the return value is TRUE.

If the function fails, the return value is FALSE.

See Also

RectInRegion


PtVisible
 PtVisible  QuickInfo  Overview  Group

The PtVisible function indicates whether the specified point is within the clipping region of a device context.

BOOL PtVisible(

HDC  hdc,	// handle of device context
int  X,	// x-coordinate of point
int  Y	// y-coordinate of point
);
Parameters

hdc

Identifies the device context.

X

Specifies the logical x-coordinate of the point.

Y

Specifies the logical y-coordinate of the point.

Return Value

If the specified point is within the clipping region of the device context, the return value is TRUE; otherwise, it is FALSE.

See Also

RectVisible


PulseEvent
 PulseEvent  QuickInfo  Overview  Group

The PulseEvent function provides a single operation that sets (to signaled) the state of the specified event object and then resets it (to nonsignaled) after releasing the appropriate number of waiting threads.

BOOL PulseEvent(

HANDLE  hEvent	// handle of event object
);
Parameters

hEvent

Identifies the event object. The CreateEvent or OpenEvent function returns this handle, which must have EVENT_MODIFY_STATE access.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

For a manual-reset event object, all waiting threads that can be released immediately are released. The function then resets the event object's state to nonsignaled and returns.

For an auto-reset event object, the function resets the state to nonsignaled and returns after releasing a single waiting thread, even if multiple threads are waiting.

If no threads are waiting, or if no thread can be released immediately, PulseEvent simply sets the event object's state to nonsignaled and returns.

Note that for a thread using the multiple-object wait functions (WaitForMultipleObjects, WaitForMultipleObjectsEx, and MsgWaitForMultipleObjects) to wait for all specified objects to be signaled, PulseEvent can set the event object's state to signaled and reset it to nonsignaled without causing the wait function to return. This happens if not all of the specified objects are simultaneously signaled.

See Also

CreateEvent, MsgWaitForMultipleObjects, OpenEvent, ResetEvent, SetEvent, WaitForMultipleObjects, WaitForMultipleObjectsEx, WaitForSingleObject, WaitForSingleObjectEx


PurgeComm
 PurgeComm  QuickInfo  Overview  Group

The PurgeComm function can discard all characters from the output or input buffer of a specified communications resource. It can also terminate pending read or write operations on the resource.

BOOL PurgeComm(

HANDLE  hCommDev,	// handle of communications resource
DWORD  fdwAction	// action to perform
);
Parameters

hCommDev

Identifies the communications resource. The CreateFile function returns this handle.

fdwAction

Specifies the action to take. This parameter can be a combination of the following values:

Value	Meaning
PURGE_TXABORT	Terminates all outstanding write operations and returns immediately, even if the write operations have not been completed.
PURGE_RXABORT	Terminates all outstanding read operations and returns immediately, even if the read operations have not been completed.
PURGE_TXCLEAR	Clears the output buffer (if the device driver has one).
PURGE_RXCLEAR	Clears the input buffer (if the device driver has one).
Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

If a thread uses PurgeComm to flush an output buffer, the deleted characters are not transmitted. To empty the output buffer while ensuring that the contents are transmitted, call the FlushFileBuffers function (a synchronous operation). Note, however, that FlushFileBuffers is subject to flow control but not to write time-outs, and it will not return until all pending write operations have been transmitted.

See Also

CreateFile


QueryDosDevice
 QueryDosDevice  QuickInfo  Overview  Group

The QueryDosDevice function lets an application obtain information about MS-DOS device names. The function can obtain the current mapping for a particular MS-DOS device name. The function can also obtain a list of all existing MS-DOS device names.

MS-DOS device names are stored as symbolic links in the Windows NT object name space. The code that converts an MS-DOS path into a corresponding Windows NT path uses these symbolic links to map MS-DOS devices and drive letters. The QueryDosDevice function provides a mechanism whereby a Win32-based application can query the names of the symbolic links used to implement the MS-DOS device namespace as well as the value of each specific symbolic link.

DWORD QueryDosDevice(

LPCTSTR  lpDeviceName,	// address of MS-DOS device name string
LPTSTR  lpTargetPath,	// address of buffer for storing query results
DWORD  ucchMax	// maximum storage capacity of buffer
);
Parameters

lpDeviceName

Pointer to an MS-DOS device name string specifying the target of the query.

This parameter can be NULL. In that case, the QueryDosDevice function will store a list of all existing MS-DOS device names into the buffer pointed to by lpTargetPath.

lpTargetPath

Pointer to a buffer that will receive the result of the query. The function fills this buffer with one or more null-terminated strings. The final null-terminated string is followed by an additional NULL.

If lpDeviceName is non-NULL, the function obtains information about the particular MS-DOS device specified by lpDeviceName. The first null-terminated string stored into the buffer is the current mapping for the device. The other null-terminated strings represent undeleted prior mappings for the device.

If lpDeviceName is NULL, the function obtains a list of all existing MS-DOS device names. Each null-terminated string stored into the buffer is the name of an existing MS-DOS device.

ucchMax

Specifies the maximum number of characters that can be stored into the buffer pointed to by lpTargetPath.

Return Value

If the function succeeds, the return value is the number of characters stored into the buffer pointed to by lpTargetPath.

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

Remarks

The DefineDosDevice function provides a means whereby a Win32-based application can create and modify the symbolic links used to implement the MS-DOS device namespace.

MS-DOS device names are global. Once defined, an MS-DOS device name remains visible to all processes until either it is explicity removed or the system reboots.

See Also

DefineDosDevice


QueryPerformanceCounter
 QueryPerformanceCounter  QuickInfo  Overview  Group

The QueryPerformanceCounter function retrieves the current value of the high-resolution performance counter, if one exists.

BOOL QueryPerformanceCounter(

LARGE_INTEGER  *lpliPerformanceCount	// address of current counter value
);
Parameters

lpliPerformanceCount

Points to a variable that the function sets, in counts, to the current performance-counter value. If the installed hardware does not support a high-resolution performance counter, this parameter can be to zero.

Return Value

If the installed hardware supports a high-resolution performance counter, the return value is TRUE.

If the installed hardware does not support a high-resolution performance counter, the return value is FALSE.

See Also

QueryPerformanceFrequency


QueryPerformanceFrequency
 QueryPerformanceFrequency  QuickInfo  Overview  Group

The QueryPerformanceFrequency function retrieves the frequency of the high-resolution performance counter, if one exists.

BOOL QueryPerformanceFrequency(

LARGE_INTEGER  *lpliPerformanceFreq	// address of current frequency
);
Parameters

lpliPerformanceFreq

Points to a variable that the function sets, in counts per second, to the current performance-counter frequency. If the installed hardware does not support a high-resolution performance counter, this parameter can be to zero.

Return Value

If the installed hardware supports a high-resolution performance counter, the return value is TRUE.

If the installed hardware does not support a high-resolution performance counter, the return value is FALSE. To get extended error information, call GetLastError.

See Also

QueryPerformanceCounter


QueryServiceConfig
 QueryServiceConfig  QuickInfo  Overview  Group

The QueryServiceConfig function retrieves the configuration parameters of the specified service.

BOOL QueryServiceConfig(

SC_HANDLE  schService,	// handle of service
LPQUERY_SERVICE_CONFIG  lpqscServConfig,	// address of service config. structure
DWORD  cbBufSize,	// size of service configuration buffer
LPDWORD  lpcbBytesNeeded	// address of variable for bytes needed
);
Parameters

schService

Identifies the service. This handle is returned by the OpenService or CreateService function, and it must have SERVICE_QUERY_CONFIG access.

lpqscServConfig

Points to a QUERY_SERVICE_CONFIG structure in which the service configuration information is returned.

cbBufSize

Specifies the size, in bytes, of the buffer pointed to by the lpqscServConfig parameter.

lpcbBytesNeeded

Points to a variable that receives the number of bytes needed to return all the configuration information.

Return Value

If the function succeeds, the return value is TRUE.

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

Errors

The following error codes can be set by the service control manager. Others can be set by the registry functions that are called by the service control manager.

Value	Meaning
ERROR_ACCESS_DENIED	The specified handle was not opened with SERVICE_QUERY_CONFIG access.
ERROR_INSUFFICIENT_BUFFER	There is more service configuration information than would fit into the lpqscServConfig buffer. The number of bytes required to get all the information is returned in the lpcbBytesNeeded parameter. Nothing is written to the lpqscServConfig buffer.
ERROR_INVALID_HANDLE	The specified handle is invalid.
Remarks

The QueryServiceConfig function returns the service configuration information kept in the registry for a particular service. This configuration information was first set via the CreateService function, and may have been updated via the ChangeServiceConfig function. If the service was running when the configuration information was last changed, the information returned with the QueryServiceConfig will not reflect the true configuration of the service that is running. Instead, it will reflect the configuration of the service when it is run next. Upon stopping the service, the service control manager database will be updated with the configuration that is stored in the registry. The DisplayName key is an exception to this. When the DisplayName key is changed, it takes effect immediately regardless of whether the service is running.

The lpqscServConfig buffer must be large enough to hold the strings pointed to by the members of the QUERY_SERVICE_CONFIG structure.

See Also

ChangeServiceConfig, CreateService, OpenService, QUERY_SERVICE_CONFIG, QueryServiceObjectSecurity, QueryServiceStatus


QueryServiceLockStatus
 QueryServiceLockStatus  QuickInfo  Overview  Group

The QueryServiceLockStatus function retrieves the lock status of the specified service control manager database.

BOOL QueryServiceLockStatus(

SC_HANDLE  schSCManager,	// handle of svc. ctrl. mgr. database
LPQUERY_SERVICE_LOCK_STATUS  lpqslsLockStat,	// address of lock status structure
DWORD  cbBufSize,	// size of service configuration buffer
LPDWORD  lpcbBytesNeeded	// address of variable for bytes needed
);
Parameters

schSCManager

Identifies the service control manager database. The OpenSCManager function returns this handle, which must have SC_MANAGER_QUERY_LOCK_STATUS access.

lpqslsLockStat

Points to a QUERY_SERVICE_LOCK_STATUS structure in which the lock status of the specified database is returned.

cbBufSize

Specifies the size, in bytes, of the buffer pointed to by the lpqslsLockStat parameter.

lpcbBytesNeeded

Points to a variable that receives the number of bytes needed to return all the lock status information.

Return Value

If the function succeeds, the return value is TRUE.

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

Errors

The following error codes may be set by the service control manager. Other error codes may be set by the registry functions that are called by the service control manager.

Value	Meaning
ERROR_ACCESS_DENIED
	The specified handle was not opened with SC_MANAGER_QUERY_LOCK_STATUS access.
ERROR_INSUFFICIENT_BUFFER
	There is more lock status information than would fit into the lpqslsLockStat buffer. The number of bytes required to get all the information is returned in the lpcbBytesNeeded parameter. Nothing is written to the lpqslsLockStat buffer.
ERROR_INVALID_HANDLE
	The specified handle is invalid.
Remarks

The QueryServiceLockStatus function returns a QUERY_SERVICE_LOCK_STATUS structure that indicates whether the specified database is locked. If the database is locked, the structure provides the account name of the user that holds the lock and the length of time that the lock has been held.

A process calls the LockServiceDatabase function to lock a service control manager database and the UnlockServiceDatabase function to release the lock.

The lpqslsLockStat buffer must be large enough to hold the string pointed to by the lpLockOwner member of the QUERY_SERVICE_LOCK_STATUS structure.

See Also

LockServiceDatabase, OpenSCManager, QUERY_SERVICE_LOCK_STATUS, UnlockServiceDatabase


QueryServiceObjectSecurity
 QueryServiceObjectSecurity  QuickInfo  Overview  Group

The QueryServiceObjectSecurity function retrieves a copy of the security descriptor protecting a service object.

BOOL QueryServiceObjectSecurity(

SC_HANDLE  schService,	// handle of service
SECURITY_INFORMATION  fdwSecurityInfo,	// type of security information requested
PSECURITY_DESCRIPTOR  psdSecurityDesc,	// address of security descriptor
DWORD  cbBufSize,	// size of security descriptor buffer
LPDWORD  lpcbBytesNeeded	// address of variable for bytes needed
);
Parameters

schService

Identifies the service. This handle is returned by the OpenService or CreateService function, and it must have READ_CONTROL access.

fdwSecurityInfo

Specifies the security information being requested. Any or all of the following flags can be specified:

Value	Meaning
OWNER_SECURITY_INFORMATION
	Requests the object's owner security identifier (SID).
GROUP_SECURITY_INFORMATION
	Requests the object's primary group SID.
DACL_SECURITY_INFORMATION
	Requests the object's discretionary access control list (ACL).
SACL_SECURITY_INFORMATION
	Requests the object's system ACL. The calling process must have SeSecurityPrivilege privilege.
psdSecurityDesc

Points to a buffer that receives a copy of the security descriptor of the specified service object. The calling process must have the appropriate access to view the specified aspects of the object's security descriptor. The SECURITY_DESCRIPTOR structure is returned in self-relative format.

cbBufSize

Specifies the size, in bytes, of the buffer pointed to by the psdSecurityDesc parameter.

lpcbBytesNeeded

Points to a variable that receives the number of bytes needed to return all the requested security descriptor information.

Return Value

If the function succeeds, the return value is TRUE.

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

Errors

The following error codes may be set by the service control manager. Other error codes may be set by the registry functions that are called by the service control manager.

Value	Meaning
ERROR_ACCESS_DENIED
	The specified handle was not opened with READ_CONTROL access, or the calling process is not the owner of the object.
ERROR_INVALID_HANDLE
	The specified handle is invalid.
ERROR_INSUFFICIENT_BUFFER
	There is more security descriptor information than would fit into the psdSecurityDesc buffer. The number of bytes required to get all the information is returned in the lpcbBytesNeeded parameter. Nothing is written to the psdSecurityDesc buffer.
ERROR_INVALID_PARAMETER
	The specified security information is invalid.
Remarks

The initial security descriptor of a service object is created by the service control manager, based on the security descriptor of the process that called the CreateService function to create the service. The security descriptor can be changed by calling the SetServiceObjectSecurity function.

See Also

CreateService, OpenService, SECURITY_DESCRIPTOR, SetServiceObjectSecurity


QueryServiceStatus
 QueryServiceStatus  QuickInfo  Overview  Group

The QueryServiceStatus function retrieves the current status of the specified service.

BOOL QueryServiceStatus(

SC_HANDLE  schService,	// handle of service
LPSERVICE_STATUS  lpssServiceStatus	// address of service status structure
);
Parameters

schService

Identifies the service. This handle is returned by the OpenService or the CreateService function, and it must have SERVICE_QUERY_STATUS access.

lpssServiceStatus

Points to a SERVICE_STATUS structure in which the status information is returned.

Return Value

If the function succeeds, the return value is TRUE.

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

Errors

The following error codes may be set by the service control manager. Other error codes may be set by the registry functions that are called by the service control manager.

Value	Meaning
ERROR_ACCESS_DENIED	The specified handle was not opened with SERVICE_QUERY_STATUS access.
ERROR_INVALID_HANDLE	The specified handle is invalid.
Remarks

The QueryServiceStatus function returns the most recent service status information reported to the service control manager. The service may have just changed its status and may not have updated the service control manager yet. Applications can find out the absolutely latest service status by interrogating the service directly by using the ControlService function with the SERVICE_CONTROL_INTERROGATE control code.

See Also

ControlService, CreateService, OpenService, SERVICE_STATUS, SetServiceStatus


RaiseException
 RaiseException  QuickInfo  Overview  Group

The RaiseException function raises an exception in the calling thread.

VOID RaiseException(

DWORD  dwExceptionCode,	// exception code
DWORD  dwExceptionFlags,	// continuable exception flag
DWORD  cArguments,	// number of arguments in array
CONST DWORD *  lpArguments	// address of array of arguments
);
Parameters

dwExceptionCode

Specifies the application-defined exception code of the exception being raised. The filter expression and exception-handler block of an exception handler can use the GetExceptionCode function to retrieve this value.

Note that the system will clear bit 28 of dwExceptionCode. This bit is a reserved exception bit, used by the system for its own purposes. For example, after calling the RaiseException function with a dwExceptionCode value of 0xEFFFFFFF Windows displays a message indicating that the exception number is 0xEFFFFFFF.

dwExceptionFlags

Specifies the exception flags. This can be either zero to indicate a continuable exception, or EXCEPTION_NONCONTINUABLE to indicate a noncontinuable exception. Any attempt to continue execution after a noncontinuable exception causes the EXCEPTION_NONCONTINUABLE_EXCEPTION exception.

cArguments

Specifies the number of arguments in the lpArguments array. This value must not exceed EXCEPTION_MAXIMUM_PARAMETERS. This parameter is ignored if lpArguments is NULL.

lpArguments

Points to an array of 32-bit arguments. This parameter can be NULL. These arguments can contain any application-defined data that needs to be passed to the filter expression of the exception handler.

Return Value

This function does not return a value.

Remarks

The RaiseException function enables a process to use structured exception handling to handle private, software-generated, application-defined exceptions.

Raising an exception causes the exception dispatcher to go through the following search for an exception handler:

1.	The system first attempts to notify the process's debugger, if any.

2.	If the process is not being debugged, or if the associated debugger does not handle the exception, the system attempts to locate a frame-based exception handler by searching the stack frames of the thread in which the exception occurred. The system searches the current stack frame first, then proceeds backward through preceding stack frames.

3.	If no frame-based handler can be found, or no frame-based handler handles the exception, the system makes a second attempt to notify the process's debugger.

4.	If the process is not being debugged, or if the associated debugger does not handle the exception, the system provides default handling based on the exception type. For most exceptions, the default action is to call the ExitProcess function.

The values specified in the dwExceptionCode, dwExceptionFlags, cArguments, and lpArguments parameters can be retrieved in the filter expression of a try-except frame-based exception handler by calling the GetExceptionInformation function. A debugger can retrieve these values by calling the WaitForDebugEvent function.

See Also

ExitProcess, GetExceptionCode, GetExceptionInformation, WaitForDebugEvent


RasCreatePhonebookEntry
 RasCreatePhonebookEntry  Overview  Group

The RasCreatePhonebookEntry function creates a new phonebook entry. The function displays a dialog box in which the user types information about the phonebook entry.

DWORD RasCreatePhonebookEntry(

HWND  hwnd,	// handle to the parent window of the dialog box
LPTSTR  lpszPhonebook	// pointer to the full path and filename of the phonebook file
);
Parameters

hwnd

Handle to the parent window of the dialog box.

lpszPhonebook

Points to a null-terminated string that specifies the full path and filename of the phonebook file. Currently, this parameter is ignored.

Windows 95: Dial-up networking stores phonebook entries in the registry rather than in a phonebook file.

Return Value

If the function succeeds, the return value is zero.

If the function fails, the return value is the following error code:

Value	Description
ERROR_CANNOT_OPEN_PHONEBOOK
	The phonebook is corrupted or missing components.
See Also

RasEditPhonebookEntry, RasGetEntryDialParams, RasSetEntryDialParams


RasDial
 RasDial  QuickInfo  Overview  Group

The RasDial function establishes a Remote Access Service (RAS) connection between a RAS client and a RAS server. The connection data includes callback and user authentication information.

DWORD RasDial(

LPRASDIALEXTENSIONS  lpRasDialExtensions,	// pointer to function extensions data
LPTSTR  lpszPhonebook,	// pointer to full path and filename of phonebook file
LPRASDIALPARAMS  lpRasDialParams,	// pointer to calling parameters data
DWORD  dwNotifierType,	// specifies type of RasDial event handler
LPVOID  lpvNotifier,	// specifies a handler for RasDial events
LPHRASCONN  lphRasConn	// pointer to variable to receive connection handle
);
Parameters

lpRasDialExtensions

Windows NT

Points to a RASDIALEXTENSIONS structure that specifies a set of RasDial extended features to enable. If you do not need to enable any of the extensions, set this parameter to NULL.

Windows 95

This parameter is ignored. On Windows 95, RasDial always uses the default behaviors for the RASDIALEXTENSIONS options.

lpszPhonebook

Windows NT

Points to a string that specifies the full path and filename of the phonebook file. This parameter can be NULL, and typically is; in that case, RasDial uses the default phonebook file RASPHONE.PBK.

Windows 95

This parameter is ignored. Dial-up networking stores phonebook entries in the registry rather than in a phonebook file.

lpRasDialParams

Points to a RASDIALPARAMS structure that specifies calling parameters for the RAS connection.

The caller must set the RASDIALPARAMS structure's dwSize member to the sizeof(RASDIALPARAMS) to identify the version of the structure being passed.

dwNotifierType

Specifies the nature of the lpvNotifier parameter. If lpvNotifier is NULL, dwNotifierType is ignored. If lpvNotifier is not NULL, set dwNotifierType to one of the following values:

Value	Meaning
0xFFFFFFFF	The lpvNotifier parameter is a handle to a window to receive progress notification messages. In a progress notification message, wParam is the equivalent of the rasconnstate parameter of RasDialFunc and RasDialFunc1, and lParam is the equivalent of the dwError parameter of RasDialFunc and RasDialFunc1.  The progress notification message uses a system registered message code. You can obtain the value of this message code as follows:  {UINT unMsg =    RegisterWindowMessageA( RASDIALEVENT );  if (unMsg == 0)        unMsg = WM_RASDIALEVENT;     }
0	The lpvNotifier parameter points to a RasDialFunc callback function.
1	The lpvNotifier parameter points to a RasDialFunc1 callback function.
lpvNotifier

Specifies a window handle or a RasDialFunc or RasDialFunc1 callback function to receive RasDial event notifications. The dwNotifierType parameter specifies the nature of lpvNotifier. Please refer to its description preceding for further detail.

If this parameter is not NULL, RasDial sends the window a message, or calls the callback function, for each RasDial event. Additionally, the RasDial call operates asynchronously: RasDial returns immediately, before the connection is established, and communicates its progress via the window or callback function.

If lpvNotifier is NULL, the RasDial call operates synchronously: RasDial does not return until the connection attempt has completed successfully or failed.

If lpvNotifier is not NULL, notifications to the window or callback function can occur at any time after the initial call to RasDial. Notifications end when one of the following events occurs:

•	The connection is established. In other words, the RAS connection state is RASCS_Connected.

•	The connection fails. In other words, dwError is nonzero.

•	RasHangUp is called on the connection.

The callback notifications are made in the context of a thread captured during the initial call to RasDial.

lphRasConn

Points to a variable of type HRASCONN. You must set the HRASCONN variable to NULL before calling RasDial. If RasDial succeeds, it stores a handle to the RAS connection into *lphRasConn.

Return Value

If the function succeeds, the immediate return value is zero. In addition, the function stores a handle to the RAS connection into the variable pointed to by lphRasConn.

If the function fails, the immediate return value is a nonzero error value, either from the set listed in the RAS header file or ERROR_NOT_ENOUGH_MEMORY.

Remarks

Errors that occur after the immediate return can be detected by RasGetConnectStatus. Data is available until an application calls RasHangUp to hang up the connection.

An application must eventually call RasHangUp whenever a non-NULL connection handle is stored into *lphRasConn. This applies even if RasDial returns a nonzero (error) value.

An application can safely call RasHangUp from a RasDial notifier callback function. If this is done, however, the hangup does not occur until the routine returns.

Windows NT

If the structure pointed to by lpRasDialExtensions enables RDEOPT_PausedStates, the RasDial function pauses whenever it enters a state in which the RASCS_PAUSED bit is set to one. To restart RasDial from such a paused state, call RasDial again, passing the connection handle returned from the original RasDial call in *lphRasConn. The same notifier used in the original RasDial call must be used when restarting from a paused state.

To specify that RasDial should enter a RASCS_CallbackSetByCaller state, set lpRasDialParams->szCallbackNumber to "*" on the initial call to RasDial. When your notification handler is called with this state, you can set the the callback number to a number supplied by the user.

Windows 95

Windows 95 does not support the RASCS_CallbackSetByCaller state or any of the other paused states.

See Also

RasDialFunc, RasDialFunc1, RasGetConnectStatus, RasHangUp, RASDIALEXTENSIONS, RASDIALPARAMS, WM_RASDIALEVENT


RasDialFunc
 RasDialFunc  QuickInfo  Overview  Group

The RasDialFunc function is an application-defined or library-defined callback function that the RasDial function calls when a change of state occurs during a Remote Access Service (RAS) connection process.

VOID RasDialFunc(

UINT  unMsg,	// type of event that has occurred
RASCONNSTATE  rasconnstate,	// connection state about to be entered
DWORD  dwError	// error that may have occurred
);
Parameters

unMsg

Specifies the type of event that has occurred. Currently, the only event defined is WM_RASDIALEVENT.

rasconnstate

Specifies a RASCONNSTATE enumerator value that indicates the state the RasDial remote access connection process is about to enter.

dwError

Indicates the error that has occurred, or zero if no error has occurred.

RasDial calls RasDialFunc with dwError set to zero upon entry to each connection state. If an error occurs within a state, RasDialFunc is called again with a nonzero dwError value.

Remarks

A RasDial connection operation is suspended during a call to a RasDialFunc callback function. For that reason, your RasDialFunc implementation should generally return as quickly as possible. There are two exceptions to that rule. Asynchronous (slow) devices such as modems often have time-out periods measured in seconds rather than milliseconds; a less-than-prompt return from a RasDialFunc function is generally not a problem. The prompt return requirement also does not apply when dwError is nonzero, indicating that an error has occurred. It is safe, for example, to put up an error dialog box and wait for user input.

Your RasDialFunc implementation should not depend on the order or occurrence of particular RASCONNSTATE connection states, because this may vary between platforms.

Do not call the RasDial function from within a RasDialFunc callback function. You can call the RasGetConnectStatus, RasEnumEntries, RasEnumConnections, RasGetErrorString, and RasHangUp functions from within the callback function. For example, calling RasGetConnectStatus from within a callback function would be useful for determining the name and type of the connecting device.

Note that, for convenience, RasHangUp can be called from within a RasDialFunc callback function. However, much of the hang-up processing occurs after the RasDialFunc callback function has returned.

RasDialFunc is a placeholder for the application-defined or library-defined function name.

See Also

RASCONNSTATE, RasDial, RasDialFunc1, RasEnumConnections, RasEnumEntries, RasGetConnectStatus, RasGetErrorString, RasHangUp


RasDialFunc1
 RasDialFunc1  QuickInfo  Overview  Group

A RasDialFunc1 function is an application-defined or library-defined callback function that the RasDial function calls when a change of state occurs during a remote access connection process. A RasDialFunc1 function is comparable to a RasDialFunc function, but is enhanced by the addition of two parameters: a handle to the Remote Access Server (RAS) connection, and an extended error code.

VOID RasDialFunc1(

HRASCONN  hrasconn,	// handle to RAS connection
UINT  unMsg,	// type of event that has occurred
RASCONNSTATE  rascs,	// connection state about to be entered
DWORD  dwError	// error that may have occurred
DWORD  dwExtendedError	// extended error information for some errors
);
Parameters

hrasconn

Provides a handle to the RAS connection, as returned by RasDial.

unMsg

Specifies the type of event that has occurred. Currently, the only event defined is WM_RASDIALEVENT.

rascs

Specifies a RASCONNSTATE enumerator value that indicates the state the RasDial remote access connection process is about to enter.

dwError

Specifies the error that has occurred. If no error has occurred, dwError is zero.

RasDial calls RasDialFunc1 with dwError set to zero upon entry to each connection state. If an error occurs within a state, RasDial calls RasDialFunc1 again with a nonzero dwError value.

In some error cases, the dwExtendedError parameter contains extended error information.

dwExtendedError

Specifies extended error information for certain nonzero values of dwError. For all other values of dwError, dwExtendedError is zero.

The contents of dwExtendedError are defined for values of dwError as follows:

dwError	dwExtendedError
ERROR_SERVER_NOT_RESPONDING	Specifies the NetBIOS error that occurred.
ERROR_NETBIOS_ERROR	Specifies the NetBIOS error that occurred.
ERROR_AUTH_INTERNAL	Specifies an internal diagnostics code.
ERROR_CANNOT_GET_LANA	Specifies a routing error code, which is a RAS error.
Remarks

A RasDial connection operation is suspended during a call to a RasDialFunc1 callback function. For that reason, your RasDialFunc1 implementation should generally return as quickly as possible. There are two exceptions to that rule. Asynchronous (slow) devices such as modems often have time-out periods measured in seconds rather than milliseconds; a less-than-prompt return from a RasDialFunc1 function is generally not a problem. The prompt return requirement also does not apply when dwError is nonzero, indicating that an error has occurred. It is safe, for example, to put up an error dialog box and wait for user input.

Your RasDialFunc1 implementation should not depend on the order or occurrence of particular RASCONNSTATE connection states, because this may vary between platforms.

Do not call the RasDial function from within a RasDialFunc1 callback function. You can call the RasGetConnectStatus, RasEnumEntries, RasEnumConnections, RasGetErrorString, and RasHangUp functions from within the callback function. For example, calling RasGetConnectStatus from within a callback function would be useful for determining the name and type of the connecting device.

Note that, for convenience, RasHangUp can be called from within a RasDialFunc1 callback function. However, much of the hang-up processing occurs after the RasDialFunc1 callback function has returned.

RasDialFunc1 is a placeholder for the application-defined or library-defined function name.

See Also

RasDial, RasDialFunc, RASCONNSTATE, RasEnumConnections, RasEnumEntries, RasGetConnectStatus, RasGetErrorString, RasHangUp


RasEditPhonebookEntry
 RasEditPhonebookEntry  Overview  Group

The RasEditPhonebookEntry function edits an existing phonebook entry. The function displays a dialog box in which the user can modify the existing information.

DWORD RasEditPhonebookEntry(

HWND  hwnd,	// handle to the parent window of the dialog box
LPTSTR  lpszPhonebook,	// pointer to the full path and filename of the phonebook file
LPTSTR  lpszEntryName	// pointer to the phonebook entry name
);
Parameters

hwnd

Handle to the parent window of the dialog box.

lpszPhonebook

Points to a null-terminated string that specifies the full path and filename of the phonebook file. Currently, this parameter is ignored.

Windows 95: Dial-up networking stores phonebook entries in the registry rather than in a phonebook file.

lpszEntryName

Points to a null-terminated string that specifies the name of an existing entry in the phonebook file.

Return Value

If the function succeeds, the return value is zero.

If the function fails, the return value can be one of the following error codes:

Value	Description
ERROR_BUFFER_INVALID
	The phonebook entry buffer is invalid.
ERROR_CANNOT_OPEN_PHONEBOOK
	The phonebook is corrupted or missing components.
ERROR_CANNOT_FIND_PHONEBOOK_ENTRY
	The phonebook entry does not exist.
See Also

RasCreatePhonebookEntry, RasGetEntryDialParams, RasSetEntryDialParams


RasEnumConnections
 RasEnumConnections  QuickInfo  Overview  Group

The RasEnumConnections function lists all active Remote Access Service (RAS) connections. It returns each connection's handle and phonebook entry name.

DWORD RasEnumConnections(

LPRASCONN  lprasconn,	// buffer to receive connections data
LPDWORD  lpcb,	// size in bytes of buffer
LPDWORD  lpcConnections	// number of connections written to buffer
);
Parameters

lprasconn

Points to a buffer that receives an array of RASCONN structures, one for each RAS connection. Before calling the function, an application must set the dwSize member of the first RASCONN structure in the buffer to sizeof(RASCONN) in order to identify the version of the structure being passed.

lpcb

Points to a variable that contains the size, in bytes, of the buffer specified by lprasconn. On return, the function sets this variable to the number of bytes required to enumerate the RAS connections.

lpcConnections

Points to a variable that the function sets to the number of RASCONN structures written to the buffer specified by lprasconn.

Return Value

If the function succeeds, the return value is zero.

If the function fails, the return value is a nonzero error value listed in the RAS header file or one of ERROR_BUFFER_TOO_SMALL or ERROR_NOT_ENOUGH_MEMORY.

Remarks

If a connection was made without specifying a phonebook entry name, the information returned for that connection will give the connection phone number preceded by ".".

See Also

RASCONN, RasEnumEntries, RasGetConnectStatus


RasEnumEntries
 RasEnumEntries  QuickInfo  Overview  Group

The RasEnumEntries function lists all entry names in a remote access phonebook.

DWORD RasEnumEntries (

LPTSTR  reserved,	// reserved, must be NULL
LPTSTR  lpszPhonebook,	// pointer to full path and filename of phonebook file
LPRASENTRYNAME  lprasentryname,	// buffer to receive phonebook entries
LPDWORD  lpcb,	// size in bytes of buffer
LPDWORD  lpcEntries	// number of entries written to buffer
);
Parameters

reserved

Reserved; must be NULL.

lpszPhonebook

Windows NT

Points to a string that specifies the full path and filename of the phonebook file. This parameter can be NULL, and typically is; in that case, RasEnumEntries uses the default phonebook file RASPHONE.PBK.

Windows 95

This parameter is ignored. Dial-up networking stores phonebook entries in the registry rather than in a phonebook file.

lprasentryname

Points to a buffer that receives an array of RASENTRYNAME structures, one for each phonebook entry. Before calling the function, an application must set the dwSize member of the first RASENTRYNAME structure in the buffer to sizeof(RASENTRYNAME) in order to identify the version of the structure being passed.

lpcb

Points to a variable that contains the size, in bytes, of the buffer specified by lprasentryname. On return, the function sets this variable to the number of bytes required to successfully complete the call.

lpcEntries

Points to a variable that the function, if successful, sets to the number of phonebook entries written to the buffer specified by lprasentryname.

Return Value

If the function succeeds, the return value is zero.

If the function fails, the return value is a nonzero error value listed in the RAS header file or one of ERROR_BUFFER_TOO_SMALL or ERROR_NOT_ENOUGH_MEMORY.

See Also

RASENTRYNAME, RasEnumConnections


RasGetConnectStatus
 RasGetConnectStatus  QuickInfo  Overview  Group

The RasGetConnectStatus function retrieves information on the current status of the specified remote access connection. An application can use this call to determine when an asynchronous RasDial call has completed.

DWORD RasGetConnectStatus(

HRASCONN  hrasconn,	// handle to RAS connection of interest
LPRASCONNSTATUS  lprasconnstatus	// buffer to receive status data
);
Parameters

hrasconn

Identifies the remote access connection for which to retrieve the status. This handle must have been obtained from RasDial or RasEnumConnections.

lprasconnstatus

Points to a RASCONNSTATUS structure that the function fills with status information. Before calling the function, an application must set the dwSize member of the structure to sizeof(RASCONNSTATUS) in order to identify the version of the structure being passed.

Return Value

If the function succeeds, the return value is zero.

If the function fails, the return value is a nonzero error value listed in the RAS header file or one of ERROR_BUFFER_TOO_SMALL or ERROR_NOT_ENOUGH_MEMORY.

See Also

RASCONNSTATUS, RasDial, RasEnumConnections


RasGetEntryDialParams
 RasGetEntryDialParams  Overview  Group

The RasGetEntryDialParams function retrieves the connection information saved by the last successful call to the RasDial or RasSetEntryDialParams function for a specified phonebook entry.

DWORD RasGetEntryDialParams(

LPTSTR  lpszPhonebook,	// pointer to the full path and filename of the phonebook file
LPRASDIALPARAMS  lprasdialparams,	// pointer to a structure that receives the connection parameters
LPBOOL  lpfPassword	// indicates whether the user's password was retrieved
);
Parameters

lpszPhonebook

Points to a null-terminated string that specifies the full path and filename of the phonebook file. Currently, this parameter is ignored.

Windows 95: Dial-up networking stores phonebook entries in the registry rather than in a phonebook file.

lprasdialparams

Points to a RASDIALPARAMS structure that receives the connection parameters associated with the phonebook entry specified by the szEntryName member. On entry, the dwSize member must specify the size of the RASDIALPARAMS structure, and the szEntryName member must specify a valid phonebook entry.

lpfPassword

Points to a flag that indicates whether the function retrieved the password associated with the user name for the phonebook entry. The function sets this flag to TRUE if the user's password was returned in the szPassword member of the RASDIALPARAMS structure pointed to by lprasdialparams.

Return Value

If the function succeeds, the return value is zero.

If the function fails, the return value can be one of the following error codes:

Value	Description
ERROR_BUFFER_INVALID
	The lprasdialparams or lpfPassword pointer is invalid, or the lprasdialparams buffer is invalid.
ERROR_CANNOT_OPEN_PHONEBOOK
	The phonebook is corrupted or missing components.
ERROR_CANNOT_FIND_PHONEBOOK_ENTRY
	The phonebook entry does not exist.
See Also

RasDial, RASDIALPARAMS, RasCreatePhonebookEntry, RasEditPhonebookEntry, RasSetEntryDialParams


RasGetErrorString
 RasGetErrorString  QuickInfo  Overview  Group

The RasGetErrorString function obtains an error message string for a specified Remote Access Service (RAS) error value.

DWORD RasGetErrorString (

UINT  uErrorValue,	// error to get string for
LPTSTR  lpszErrorString,	// buffer to hold error string
DWORD  cBufSize	// size, in characters, of buffer
);
Parameters

uErrorValue

Specifies the error value of interest. These are values returned by one of the RAS functions: those listed in the RAS header file.

lpszErrorString

Points to a buffer that the function will write the error string to. This parameter must not be NULL.

cBufSize

Specifies the size, in characters, of the buffer pointed to by lpszErrorString.

Return Value

If the function succeeds, the return value is zero.

If the function fails, the return value is a nonzero error value. This value is ERROR_INVALID_PARAMETER or the GetLastError value returned from the functions GlobalAlloc or LoadString. The function does not set a thread's last error information; that is, there is no GetLastError information set by the RasGetErrorString function.

Remarks

There is no way to determine in advance the exact size in characters of an error message, and thus the size of buffer required. Error messages will generally be 80 characters or fewer in size; a buffer size of 256 characters will always be adequate. A buffer of insufficient size causes the RasGetErrorString function to fail, returning ERROR_INSUFFICIENT_BUFFER. Note that buffer sizes are specified in characters, not bytes; thus, the Unicode version of RasGetErrorString requires a 512 byte buffer to guarantee that every error message will fit.

See Also

GlobalAlloc, LoadString


RasGetProjectionInfo
 RasGetProjectionInfo  QuickInfo  Overview  Group

The RasGetProjectionInfo function obtains information about a remote access projection operation for a specified remote access component protocol.

DWORD RasGetProjectionInfo(

HRASCONN  hrasconn,	// handle that specifies remote access connection of interest
RASPROJECTION  rasprojection,	// specifies type of projection information to obtain
LPVOID  lpprojection,	// points to buffer that receives projection information
LPDWORD  lpcb	// points to variable that specifies buffer size
);
Parameters

hrasconn

Handle to the remote access connection of interest. An application obtains a Remote Access Service (RAS) connection handle from the RasDial or RasEnumConnections function.

rasprojection

A RASPROJECTION enumerated type value that specifies the protocol of interest.

lpprojection

Points to a buffer that will receive the information specified by the rasprojection parameter. The information will be in a structure appropriate to the rasprojection value:

rasprojection value	Data structure
RASP_Amb	RASAMB
RASP_PppNbf	RASPPPNBF
RASP_PppIpx	RASPPPIPX
RASP_PppIp	RASPPPIP
lpcb

Points to a variable that, on entry, specifies the size in bytes of the buffer pointed to by lpprojection. On exit, this variable contains the size of buffer needed to contain the specified projection information.

Return Value

If the function succeeds, the return value is zero.

If the function fails, the return value is an error code. The function may return a nonzero RAS error code, or one of the following error codes:

Value	Meaning
ERROR_BUFFER_TOO_SMALL	The buffer pointed to by lpprojection is not large enough to contain the requested information.
ERROR_INVALID_HANDLE	The hrasconn parameter is not a valid handle.
ERROR_INVALID_PARAMETER	One of the parameters is invalid.
ERROR_INVALID_SIZE	The dwSize member of the structure pointed to by lpprojection specifies an invalid size.
ERROR_PROTOCOL_NOT_CONFIGURED	The control protocol for which information was requested neither succeeded nor failed, because the connection's phonebook entry did not require that an attempt to negotiate the protocol be made. This is a RAS error code.
Remarks

Remote access projection is the process whereby a remote access server and a remote client negotiate network protocol-specific information. A remote access server uses this network protocol-specific information to represent a remote client on the network.

Windows NT: Remote access projection information is not available until the operating system has executed the RasDial RASCS_Projected state on the remote access connection. If RasGetProjectionInfo is called prior to the RASCS_Projected state, it returns ERROR_PROJECTION_NOT_COMPLETE.

Windows 95: Windows 95 Dial-Up Networking does not support the RASCS_Projected state. The projection phase may be done during the RASCS_Authenticate state. If the authentication is successful, the connection operation proceeds to the RASCS_Authenticated state, and projection information is available for successfully configured protocols. If RasGetProjectionInfo is called prior to the RASCS_Authenticated state, it returns ERROR_PROTOCOL_NOT_CONFIGURED.

See Also

RASAMB, RasDial, RasEnumConnections, RASPPPNBF, RASPPPIPX, RASPPPIP, RASPROJECTION


RasHangUp
 RasHangUp  QuickInfo  Overview  Group

The RasHangUp function terminates a remote access connection. The connection is specified with a Remote Access Service (RAS) connection handle. The function releases all RASAPI32.DLL resources associated with the handle.

DWORD RasHangUp(

HRASCONN  hrasconn	// handle to the RAS connection to hang up
);
Parameters

hrasconn

Identifies the remote access connection to terminate. This is a handle returned from a previous call to RasDial or RasEnumConnections.

Return Value

If the function succeeds, the return value is zero.

If the function fails, the return value is a nonzero error value listed in the RAS header file, or ERROR_INVALID_HANDLE.

Remarks

The connection is terminated even if the RasDial call has not yet been completed.

After this call, the hrasconn handle can no longer be used.

An application should not call RasHangUp and then immediately exit. The connection state machine needs time to properly terminate. If the system prematurely terminates the state machine, the state machine may fail to properly close a port, leaving the port in an inconsistent state. A simple way to avoid this problem is to call Sleep(3000) after returning from RasHangUp; after that pause, the application can exit. A more responsive way to avoid the problem is, after returning from RasHangUp, to call RasGetConnectStatus(hrasconn) and Sleep(0) in a loop until RasGetConnectStatus returns ERROR_INVALID_HANDLE.

See Also

RASCONN, RasDial, RasEnumConnections, RasGetConnectStatus, Sleep


RasSetEntryDialParams
 RasSetEntryDialParams  Overview  Group

The RasSetEntryDialParams function changes the connection information saved by the last successful call to the RasDial or RasSetEntryDialParams function for a specified phonebook entry.

DWORD RasSetEntryDialParams(

LPTSTR  lpszPhonebook,	// pointer to the full path and filename of the phonebook file
LPRASDIALPARAMS  lprasdialparams,	// pointer to a structure with the new connection parameters
BOOL    fRemovePassword	// indicates whether to remove password from entry's parameters
);
Parameters

lpszPhonebook

Points to a null-terminated string that specifies the full path and filename of the phonebook file. Currently, this parameter is ignored.

Windows 95: Dial-up networking stores phonebook entries in the registry rather than in a phonebook file.

lprasdialparams

Points to a RASDIALPARAMS structure containing the connection parameters to be associated with the phonebook entry. RasSetEntryDialParams uses the structure's members as follows:

Member	Description
dwSize	Must specify the sizeof(RASDIALPARAMS) to identify the version of the structure.
szEntryName	A null-terminated string that identifies the phonebook entry to set parameters for.
szPhoneNumber	Not used. Set to NULL.
szCallbackNumber	A null-terminated string containing the callback phone number. If szCallbackNumber is an empty string ( "" ), the callback number is not changed.
szUserName	A null-terminated string containing the logon name of the user associated with this entry. If szUserName is an empty string, the user name is not changed.
szPassword	A null-terminated string containing the password for the user specified by szUserName. If szUserName is an empty string, the password is not changed. If szPassword is an empty string and fRemovePassword is FALSE, the password is set to the empty string. If fRemovePassword is TRUE, the password stored in this phonebook entry for the user specified by szUserName is removed regardless of the contents of the szPassword string.
szDomain	A null-terminated string containing the name of the domain to log on to. If szDomain is an empty string, the domain name is not changed.
fRemovePassword

Indicates whether to remove the phonebook entry's stored password for the user specified by lprasdialparams->szUserName. If fRemovePassword is TRUE, the password is removed.

Return Value

If the function succeeds, the return value is zero.

If the function fails, the return value can be one of the following error codes:

Value	Description
ERROR_BUFFER_INVALID
	The address or buffer specified by lprasdialparams is invalid.
ERROR_CANNOT_OPEN_PHONEBOOK
	The phonebook is corrupted or missing components.
ERROR_CANNOT_FIND_PHONEBOOK_ENTRY
	The phonebook entry does not exist.
See Also

RASDIALPARAMS, RasCreatePhonebookEntry, RasEditPhonebookEntry, RasGetEntryDialParams


ReadConsole
 ReadConsole  QuickInfo  Overview  Group

The ReadConsole function reads character input from the console input buffer and removes it from the buffer.

BOOL ReadConsole(

HANDLE  hConsoleInput,	// handle of a console input buffer
LPVOID  lpvBuffer,	// address of buffer to receive data
DWORD  cchToRead,	// number of characters to read
LPDWORD  lpcchRead,	// address of number of characters read
LPVOID  lpvReserved	// reserved
);
Parameters

hConsoleInput

Identifies the console input buffer. The handle must have GENERIC_READ access.

lpvBuffer

Points to a buffer that receives the data read from the console input buffer.

cchToRead

Specifies the number of characters to read. Because the function can read either 2-byte Unicode or 1-byte ANSI characters, the size of the buffer pointed to by the lpvBuffer parameter should be at least cchToRead * sizeof(TCHAR).

lpcchRead

Points to a 32-bit variable that receives the number of characters actually read.

lpvReserved

Reserved; must be NULL.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

ReadConsole reads keyboard input from a console's input buffer. It behaves like the ReadFile function, except that it can read in either Unicode (wide-character) or ANSI mode. To have applications that maintain a single set of sources compatible with both modes, use ReadConsole rather than ReadFile. Although ReadConsole can only be used with a console input buffer handle, ReadFile can be used with other handles (such as files or pipes). ReadConsole fails if used with a standard handle that has been redirected to be something other than a console handle.

All of the input modes that affect the behavior of ReadFile have the same effect on ReadConsole. To retrieve and set the input modes of a console input buffer, use the GetConsoleMode and SetConsoleMode functions.

If the input buffer contains input events other than keyboard events (such as mouse events or window-resizing events), they are discarded. Those events can only be read by using the ReadConsoleInput function.

See Also

GetConsoleMode, ReadConsoleInput, ReadFile, SetConsoleMode, WriteConsole


ReadConsoleInput
 ReadConsoleInput  QuickInfo  Overview  Group

The ReadConsoleInput function reads data from a console input buffer and removes it from the buffer.

BOOL ReadConsoleInput(

HANDLE  hConsoleInput,	// handle of a console input buffer
PINPUT_RECORD  pirBuffer,	// address of the buffer for read data
DWORD  cInRecords,	// number of records to read
LPDWORD  lpcRead	// address of number of records read
);
Parameters

hConsoleInput

Identifies the input buffer. The handle must have GENERIC_READ access.

pirBuffer

Points to an INPUT_RECORD buffer that receives the input buffer data.

cInRecords

Specifies the size, in input records, of the buffer pointed to by the pirBuffer parameter.

lpcRead

Points to a 32-bit variable that receives the number of input records read.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

If the number of records requested in the cInRecords parameter exceeds the number of records available in the buffer, the number available is read. The function does not return until at least one input record has been read.

A process can specify a console input buffer handle in one of the wait functions (for example, the WaitForSingleObject or WaitForMultipleObjects function) to determine when there is unread console input. When the input buffer is not empty, the state of a console input buffer handle is signaled.

To determine the number of unread input records in a console's input buffer, use the GetNumberOfConsoleInputEvents function. To read input records from a console input buffer without affecting the number of unread records, use the PeekConsoleInput function. To discard all unread records in a console's input buffer, use the FlushConsoleInputBuffer function.

See Also

FlushConsoleInputBuffer, GetNumberOfConsoleInputEvents, INPUT_RECORD, PeekConsoleInput, ReadConsole, ReadFile, WaitForSingleObject, WaitForMultipleObjects, WriteConsoleInput


ReadConsoleOutput
 ReadConsoleOutput  QuickInfo  Overview  Group

The ReadConsoleOutput function reads character and color attribute data from a rectangular block of character cells in a console screen buffer, and the function writes the data to a rectangular block at a specified location in the destination buffer.

BOOL ReadConsoleOutput(

HANDLE  hConsoleOutput,	// handle of a console screen buffer
PCHAR_INFO  pchiDestBuffer,	// address of buffer that receives data
COORD  coordDestBufferSize,	// column-row size of destination buffer
COORD  coordDestBufferCoord,	// upper-left cell to write to
PSMALL_RECT  psrctSourceRect	// address of rectangle to read from
);
Parameters

hConsoleOutput

Identifies the screen buffer. The handle must have GENERIC_READ access.

pchiDestBuffer

Points to a destination buffer that receives the data read from the screen buffer. This pointer is treated as the origin of a two-dimensional array of CHAR_INFO structures whose size is specified by the coordDestBufferSize parameter.

coordDestBufferSize

Specifies the size, in character cells, of the pchiDestBuffer parameter. The X member of the COORD structure is the number of columns; the Y member is the number of rows.

coordDestBufferCoord

Specifies the coordinates of the upper-left cell in the pchiDestBuffer parameter that receives the data read from the screen buffer. The X member of the COORD structure is the column, and the Y member is the row.

psrctSourceRect

Points to a SMALL_RECT structure. On input, the structure members specify the upper-left and lower-right coordinates of the screen buffer rectangle from which the function is to read. On output, the structure members specify the actual rectangle that the function copied from.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

ReadConsoleOutput treats the screen buffer and the destination buffer as two-dimensional arrays (columns and rows of character cells). The rectangle pointed to by the psrctSourceRect parameter specifies the size and location of the block to be read from the screen buffer. A destination rectangle of the same size is located with its upper-left cell at the coordinates of the coordDestBufferCoord parameter in the pchiDestBuffer array. Data read from the cells in the screen buffer source rectangle is copied to the corresponding cells in the destination buffer. If the corresponding cell is outside the boundaries of the destination buffer rectangle (whose dimensions are specified by the coordDestBufferSize parameter), the data is not copied.

Cells in the destination buffer corresponding to coordinates that are not within the boundaries of the screen buffer are left unchanged. In other words, these are the cells for which no screen buffer data is available to be read.

Before ReadConsoleOutput returns, it sets the members of the structure pointed to by the psrctSourceRect parameter to the actual screen buffer rectangle whose cells were copied into the destination buffer. This rectangle reflects the cells in the source rectangle for which there existed a corresponding cell in the destination buffer, because ReadConsoleOutput clips the dimensions of the source rectangle to fit the boundaries of the screen buffer.

If the rectangle specified by psrctSourceRect lies completely outside the boundaries of the screen buffer, or if the corresponding rectangle is positioned completely outside the boundaries of the destination buffer, no data is copied. In this case, the function returns with the members of the structure pointed to by the psrctSourceRect parameter set such that the Right member is less than the Left, or the Bottom member is less than the Top. To determine the size of the screen buffer, use the GetConsoleScreenBufferInfo function.

The ReadConsoleOutput function has no effect on the screen buffer's cursor position. The contents of the screen buffer are not changed by the function.

See Also

CHAR_INFO, COORD, ReadConsoleOutputAttribute, ReadConsoleOutputCharacter, SMALL_RECT, WriteConsoleOutput


ReadConsoleOutputAttribute
 ReadConsoleOutputAttribute  QuickInfo  Overview  Group

The ReadConsoleOutputAttribute function copies a specified number of foreground and background color attributes from consecutive cells of a console screen buffer, beginning at a specified location.

BOOL ReadConsoleOutputAttribute(

HANDLE  hConsoleOutput,	// handle of a console screen buffer
LPWORD  lpwAttribute,	// address of buffer to receive attributes
DWORD  cReadCells,	// number of character cells to read from
COORD  coordReadCoord,	// coordinates of first cell to read from
LPDWORD  lpcNumberRead	// address of number of cells read from
);
Parameters

hConsoleOutput

Identifies a console screen buffer. The handle must have GENERIC_READ access.

lpwAttribute

Points to a buffer that receives the attributes read from the screen buffer.

cReadCells

Specifies the number of screen buffer character cells from which to read. The size of the buffer pointed to by the lpwAttribute parameter should be cReadCells * sizeof(WORD).

coordReadCoord

Specifies the coordinates of the first cell in the screen buffer from which to read. The X member of the COORD structure is the column, and the Y member is the row.

lpcNumberRead

Points to a 32-bit variable that receives the number of attributes actually read.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

If the number of attributes to be read from extends beyond the end of the specified screen buffer row, attributes are read from the next row. If the number of attributes to be read from extends beyond the end of the screen buffer, attributes up to the end of the screen buffer are read.

Each attribute specifies the foreground (text) and background colors in which that character cell is drawn. The attribute values are some combination of the following values: FOREGROUND_BLUE, FOREGROUND_GREEN, FOREGROUND_RED, FOREGROUND_INTENSITY, BACKGROUND_BLUE, BACKGROUND_GREEN, BACKGROUND_RED, and BACKGROUND_INTENSITY. For example, the following combination of values produces red text on a white background:

FOREGROUND_RED | BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE

See Also

COORD, ReadConsoleOutput, ReadConsoleOutputCharacter, WriteConsoleOutput, WriteConsoleOutputAttribute, WriteConsoleOutputCharacter


ReadConsoleOutputCharacter
 ReadConsoleOutputCharacter  QuickInfo  Overview  Group

The ReadConsoleOutputCharacter function copies a number of characters from consecutive cells of a console screen buffer, beginning at a specified location.

BOOL ReadConsoleOutputCharacter(

HANDLE  hConsoleOutput,	// handle of a console screen buffer
LPTSTR  lpReadBuffer,	// address of buffer to receive characters
DWORD  cchRead,	// number of character cells to read from
COORD  coordReadCoord,	// coordinates of first cell to read from
LPDWORD  lpcNumberRead	// address of number of cells read from
);
Parameters

hConsoleOutput

Identifies a console screen buffer. The handle must have GENERIC_READ access.

lpReadBuffer

Points to a buffer that receives the characters read from the screen buffer.

cchRead

Specifies the number of screen buffer character cells from which to read. The size of the buffer pointed to by the lpReadBuffer parameter should be cchRead * sizeof(TCHAR).

coordReadCoord

Specifies the coordinates of the first cell in the screen buffer from which to read. The X member of the COORD structure is the column, and the Y member is the row.

lpcNumberRead

Points to a 32-bit variable that receives the number of characters actually read.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

If the number of characters to be read from extends beyond the end of the specified screen buffer row, characters are read from the next row. If the number of characters to be read from extends beyond the end of the screen buffer, characters up to the end of the screen buffer are read.

See Also

COORD, ReadConsoleOutput, ReadConsoleOutputAttribute, WriteConsoleOutput, WriteConsoleOutputAttribute, WriteConsoleOutputCharacter


ReadEventLog
 ReadEventLog  QuickInfo  Overview  Group

The ReadEventLog function reads a whole number of entries from the specified event log. The function can be used to read log entries in forward or reverse chronological order.

BOOL ReadEventLog(

HANDLE  hEventLog,	// handle of event log
DWORD  dwReadFlags,	// specifies how to read log
DWORD  dwRecordOffset,	// number of first record
LPVOID  lpBuffer,	// address of buffer for read data
DWORD  nNumberOfBytesToRead,	// number of bytes to read
DWORD  *pnBytesRead,	// number of bytes read
DWORD  *pnMinNumberOfBytesNeeded	// number of bytes required for next record
);
Parameters

hEventLog

Identifies the event log to read. This handle is returned by the OpenEventLog function.

dwReadFlags

Specifies how the read operation is to proceed. This parameter can be any combination of the following values:

Value	Meaning
EVENTLOG_FORWARDS_READ	The log is read in forward chronological order.
EVENTLOG_BACKWARDS_READ	The log is read in reverse chronological order.
EVENTLOG_SEEK_READ	The read operation proceeds from the record specified by the dwRecordOffset parameter. If this flag is used, dwReadFlags must also specify EVENTLOG_FORWARDS_READ or EVENTLOG_BACKWARDS_READ. If the buffer is large enough, more than one record can be read at the specified seek position; the additional flag indicates the direction for successive read operations.
EVENTLOG_SEQUENTIAL_READ	The read operation proceeds sequentially from the last call to the ReadEventLog function using this handle.
dwRecordOffset

Specifies the log-entry record number at which the read operation should start. This parameter is ignored unless the dwReadFlags parameter includes the EVENTLOG_SEEK_READ flag.

lpBuffer

Points to a buffer for the data read from the event log. This parameter cannot be NULL, even if the nNumberOfBytesToRead parameter is zero.

The buffer will be filled with an EVENTLOGRECORD structure.

nNumberOfBytesToRead

Specifies the size, in bytes, of the buffer. This function will read as many whole log entries as will fit in the buffer; the function will not return partial entries, even if there is room in the buffer.

pnBytesRead

Points to a variable that receives the number of bytes read by the function.

pnMinNumberOfBytesNeeded

Points to a variable that receives the number of bytes required for the next log entry. This count is valid only if ReadEventLog returns zero and GetLastError returns ERROR_INSUFFICIENT_BUFFER.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

When this function returns, the read position in the error log is adjusted by the number of records read. Only a whole number of event log records will be returned.

Note  The configured filename for this source may also be the configured filename for other sources (several sources can exist as subkeys under a single logfile). Therefore, this function may return events that were logged by more than one source.

See Also

ClearEventLog, CloseEventLog, EVENTLOGRECORD, OpenEventLog, ReportEvent


ReadFile
 ReadFile  QuickInfo  Overview  Group

The ReadFile function reads data from a file, starting at the position indicated by the file pointer. After the read operation has been completed, the file pointer is adjusted by the number of bytes actually read, unless the file handle is created with the overlapped attribute. If the file handle is created for overlapped input and output (I/O), the application must adjust the position of the file pointer after the read operation.

BOOL ReadFile(

HANDLE  hFile,	// handle of file to read
LPVOID  lpBuffer,	// address of buffer that receives data
DWORD  nNumberOfBytesToRead,	// number of bytes to read
LPDWORD  lpNumberOfBytesRead,	// address of number of bytes read
LPOVERLAPPED  lpOverlapped	// address of structure for data
);
Parameters

hFile

Identifies the file to be read. The file handle must have been created with GENERIC_READ access to the file.

Windows NT

For asynchronous read operations, hFile can be any handle opened with the FILE_FLAG_OVERLAPPED flag by the CreateFile function, or a socket handle returned by the socket or accept functions.

Windows 95

For asynchronous read operations, hFile can be a communications resource, mailslot, or named pipe handle opened with the FILE_FLAG_OVERLAPPED flag by CreateFile, or a socket handle returned by the socket or accept functions. Windows 95 does not support asynchronous read operations on disk files.

lpBuffer

Points to the buffer that receives the data read from the file.

nNumberOfBytesToRead

Specifies the number of bytes to be read from the file.

lpNumberOfBytesRead

Points to the number of bytes read. ReadFile sets this value to zero before doing any work or error checking. If this parameter is zero when ReadFile returns TRUE on a named pipe, the other end of the message-mode pipe called the WriteFile function with nNumberOfBytesToWrite set to zero.

lpOverlapped

Points to an OVERLAPPED structure. This structure is required if hFile was created with FILE_FLAG_OVERLAPPED.

This parameter should not be NULL if hFile was created with FILE_FLAG_OVERLAPPED. It should point to a valid OVERLAPPED structure. If the file identified by the hFile parameter was created with FILE_FLAG_OVERLAPPED and lpOverlapped is NULL, the function fails in unpredictable ways.

If hFile was not created with FILE_FLAG_OVERLAPPED and lpOverlapped is NULL, the read operation starts at the current file position and ReadFile does not return until the operation has been completed. The function operates synchronously.

If hFile was created with FILE_FLAG_OVERLAPPED and lpOverlapped is not NULL, the read operation starts at the offset specified in the OVERLAPPED structure and ReadFile may return before the read operation has been completed. In this case, ReadFile returns FALSE and the GetLastError function returns ERROR_IO_PENDING. The calling process can continue while the read operation finishes. The event specified in the OVERLAPPED structure is set to the signaled state upon completion of the read operation.

If hFile is not created with FILE_FLAG_OVERLAPPED and lpOverlapped is not NULL, the read operation starts at the offset specified in the OVERLAPPED structure. ReadFile does not return until the read operation has been completed.

Return Value

If the function succeeds, the return value is TRUE. If the return value is TRUE and the number of bytes read is zero, the file pointer was beyond the current end of the file at the time of the read operation.

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

Remarks

If part of the file is locked by another process and the read operation overlaps the locked portion, this function fails.

Applications must not read from nor write to the input buffer that a read operation is using until the read operation completes. A premature access to the input buffer may lead to corruption of the data read into that buffer.

Characters can be read from the console input buffer by using ReadFile with a handle to console input. The console mode determines the exact behavior of the ReadFile function.

If a named pipe is being read in message mode and the next message is longer than the nNumberOfBytesToRead parameter specifies, ReadFile returns FALSE and GetLastError returns ERROR_MORE_DATA. The remainder of the message may be read by a subsequent call to the ReadFile or PeekNamedPipe function.

When reading from a communications device, the behavior of ReadFile is governed by the current communication timeouts as set and retrieved using the SetCommTimeouts and GetCommTimeouts functions. Unpredictable results can occur if you fail to set the timeout values. For more information about communication timeouts, see COMMTIMEOUTS.

If ReadFile attempts to read from a mailslot whose buffer is too small, the function returns FALSE and GetLastError returns ERROR_INSUFFICIENT_BUFFER.

If the anonymous write pipe handle has been closed and ReadFile attempts to read using the corresponding anonymous read pipe handle, the function returns FALSE and GetLastError returns ERROR_BROKEN_PIPE.

The ReadFile function may fail and return ERROR_INVALID_USER_BUFFER or ERROR_NOT_ENOUGH_MEMORY whenever there are too many outstanding asynchronous I/O requests.

If hFile is a handle to a named pipe, the Offset and OffsetHigh members of the OVERLAPPED structure pointed to by lpOverlapped must be zero, or the function will fail.

The ReadFile code to check for the end-of-file condition (eof) differs for synchronous and asynchronous read operations.

When a synchronous read operation reaches the end of a file, ReadFile returns TRUE and sets *lpNumberOfBytesRead to zero. The following sample code tests for end-of-file for a synchronous read operation:

// attempt a synchronous read operation

bResult = ReadFile(hFile, &inBuffer, nBytesToRead, &nBytesRead, NULL) ;

// check for eof

if (bResult &&  nBytesRead == 0, ) {

// we're at the end of the file

}

An asynchronous read operation can encounter the end of a file during the initiating call to ReadFile, or during subsequent asynchronous operation.

If EOF is detected at ReadFile time for an asynchronous read operation, ReadFile returns FALSE and GetLastError returns ERROR_HANDLE_EOF.

If EOF is detected during subsequent asynchronous operation, the call to GetOverlappedResult to obtain the results of that operation returns FALSE and GetLastError returns ERROR_HANDLE_EOF.

The following sample code illustrates testing for end-of-file for an asynchronous read operation:

// set up overlapped structure fields

// to simplify this sample, we'll eschew an event handle

gOverLapped.Offset     = 0;

gOverLapped.OffsetHigh = 0;

gOverLapped.hEvent     = NULL;

// attempt an asynchronous read operation

bResult = ReadFile(hFile, &inBuffer, nBytesToRead, &nBytesRead,

 &gOverlapped) ;

// if there was a problem, or the async. operation's still pending ...

if (!bResult) {

// deal with the error code

switch (dwError = GetLastError()) {

case ERROR_HANDLE_EOF: {

// we're reached the end of the file

// during the call to ReadFile

// code to handle that

}

case ERROR_IO_PENDING: {

// asynchronous i/o is still in progress

// do something else for a while

GoDoSomethingElse() ;

// check on the results of the asynchronous read

bResult = GetOverlappedResult(hFile, &gOverlapped,

&nBytesRead, FALSE) ;

// if there was a problem ...

if (!bResult) {

// deal with the error code

switch (dwError = GetLastError()) {

case ERROR_HANDLE_EOF: {

// we're reached the end of the file

//during asynchronous operation

}

// deal with other error cases

} // end switch

} // end if

} // end case

// deal with other error cases

} // end switch

} // end if

See Also

CreateFile, GetCommTimeouts, GetOverlappedResult, OVERLAPPED, PeekNamedPipe, ReadFileEx, SetCommTimeouts, WriteFile


ReadFileEx
 ReadFileEx  QuickInfo  Overview  Group

The ReadFileEx function reads data from a file asynchronously. It is designed solely for asynchronous operation, unlike the ReadFile function, which is designed for both synchronous and asynchronous operation. ReadFileEx lets an application perform other processing during a file read operation.

The ReadFileEx function reports its completion status asynchronously, calling a specified completion routine when reading is completed and the calling thread is in an alertable wait state.

BOOL ReadFileEx(

HANDLE  hFile,	// handle of file to read
LPVOID  lpBuffer,	// address of buffer
DWORD  nNumberOfBytesToRead,	// number of bytes to read
LPOVERLAPPED  lpOverlapped,	// address of offset
LPOVERLAPPED_COMPLETION_ROUTINE  lpCompletionRoutine	// address of completion routine
);
Parameters

hFile

An open handle that specifies the file entity to be read from. This file handle must have been created with the FILE_FLAG_OVERLAPPED flag and must have GENERIC_READ access to the file.

Windows NT : hFile can be any handle opened with the FILE_FLAG_OVERLAPPED flag by the CreateFile function, or a socket handle returned by the socket or accept functions.

Windows 95 : hFile can be a communications resource, mailslot, or named pipe handle opened with the FILE_FLAG_OVERLAPPED flag by CreateFile, or a socket handle returned by the socket or accept functions. Windows 95 does not support asynchronous operations on disk files.

lpBuffer

Points to a buffer that receives the data read from the file.

This buffer must remain valid for the duration of the read operation. The application should not use this buffer until the read operation is completed.

nNumberOfBytesToRead

Specifies the number of bytes to be read from the file.

lpOverlapped

Points to an OVERLAPPED data structure that supplies data to be used during the asynchronous (overlapped) file read operation.

If the file specified by hFile supports the concept of byte offsets, the caller of ReadFileEx must specify a byte offset within the file at which reading should begin. The caller specifies the byte offset by setting the OVERLAPPED structure's Offset and OffsetHigh members.

If the file entity specified by hFile does not support the concept of byte offsets — for example, if it is a named pipe — the caller must set the Offset and OffsetHigh members to zero, or ReadFileEx fails.

The ReadFileEx function ignores the OVERLAPPED structure's hEvent member. An application is free to use that member for its own purposes in the context of a ReadFileEx call. ReadFileEx signals completion of its read operation by calling, or queueing a call to, the completion routine pointed to by lpCompletionRoutine, so it does not need an event handle.

The ReadFileEx function does use the OVERLAPPED structure's Internal and InternalHigh members. An application should not set these members.

The OVERLAPPED data structure pointed to by lpOverlapped must remain valid for the duration of the read operation. It should not be a variable that can go out of scope while the file read operation is in progress.

lpCompletionRoutine

Points to the completion routine to be called when the read operation is complete and the calling thread is in an alertable wait state. For more information about the completion routine, see FileIOCompletionRoutine.

Return Value

If the function succeeds, the return value is TRUE.

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

If the function succeeds, the calling thread has an asynchronous I/O (input/output) operation pending: the overlapped read operation from the file. When this I/O operation completes, and the calling thread is blocked in an alertable wait state, the system calls the function pointed to by lpCompletionRoutine, and the wait state completes with a return code of WAIT_IO_COMPLETION.

If the function succeeds, and the file reading operation completes, but the calling thread is not in an alertable wait state, the system queues the completion routine call, holding the call until the calling thread enters an alertable wait state. For information about alertable waits and overlapped input/output operations, see Synchronization and Overlapped Input and Output.

If ReadFileEx attempts to read past the end of the file, the function returns FALSE, and GetLastError returns ERROR_HANDLE_EOF.

Remarks

If a portion of the file specified by hFile is locked by another process, and the read operation specified in a call to ReadFileEx overlaps the locked portion, the call to ReadFileEx fails.

If ReadFileEx attempts to read data from a mailslot whose buffer is too small, the function returns FALSE, and GetLastError returns ERROR_INSUFFICIENT_BUFFER.

Applications must not read from nor write to the input buffer that a read operation is using until the read operation completes. A premature access to the input buffer may lead to corruption of the data read into that buffer.

The ReadFileEx function may fail if there are too many outstanding asynchronous I/O requests. In the event of such a failure, GetLastError can return ERROR_INVALID_USER_BUFFER or ERROR_NOT_ENOUGH_MEMORY.

If hFile is a handle to a named pipe or other file entity that doesn't support the byte-offset concept, the Offset and OffsetHigh members of the OVERLAPPED structure pointed to by lpOverlapped must be zero, or ReadFileEx fails.

An application uses the WaitForSingleObjectEx, WaitForMultipleObjectsEx, and SleepEx functions to enter an alertable wait state. For more information about alertable waits and overlapped input/output, refer to those functions' reference and the "Synchronization"  topic mentioned previously.

Windows 95: On this platform, neither ReadFileEx nor WriteFileEx can be used by the comm ports to communicate. However, you can use ReadFile and WriteFile to perform asynchronous communication.

See Also

CreateFile, FileIOCompletionRoutine, OVERLAPPED, ReadFile, SleepEx, WaitForMultipleObjectsEx, WaitForSingleObjectEx, WriteFileEx, Synchronization


ReadPrinter
 ReadPrinter  QuickInfo  Overview  Group

The ReadPrinter function retrieves data from the specified printer.

BOOL ReadPrinter(

HANDLE  hPrinter,	// handle of printer object
LPVOID  lpBuf,	// address of array of bytes that receives data
DWORD  cbBuf,	// size, in bytes, of array
LPDWORD  lpdwBytes	// address of variable with number of bytes retrieved
);
Parameters

hPrinter

Identifies the printer for which to retrieve data.

lpBuf

Points to an array of bytes that receives the printer data.

cbBuf

Specifies the size, in bytes, of the buffer to which lpBuf points.

lpdwBytes

Points to a variable that receives the number of bytes of data copied into the array to which lpBuf points.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

ReadPrinter returns an error if the device or the printer is not bidirectional.

See Also

OpenPrinter


ReadProcessMemory
 ReadProcessMemory  QuickInfo  Overview  Group

The ReadProcessMemory function reads memory in a specified process. The entire area to be read must be accessible, or the operation fails.

BOOL ReadProcessMemory(

HANDLE  hProcess,	// handle of the process whose memory is read
LPCVOID  lpBaseAddress,	// address to start reading
LPVOID  lpBuffer,	// address of buffer to place read data
DWORD  cbRead,	// number of bytes to read
LPDWORD  lpNumberOfBytesRead	// address of number of bytes read
);
Parameters

hProcess

Identifies an open handle of a process whose memory is read. The handle must have PROCESS_VM_READ access to the process.

lpBaseAddress

Points to the base address in the specified process to be read. Before any data transfer occurs, the system verifies that all data in the base address and memory of the specified size is accessible for read access. If this is the case, the function proceeds; otherwise, the function fails.

lpBuffer

Points to a buffer that receives the contents from the address space of the specified process.

cbRead

Specifies the requested number of bytes to read from the specified process.

lpNumberOfBytesRead

Points to the actual number of bytes transferred into the specified buffer. If lpNumberOfBytesRead is NULL, the parameter is ignored.

Return Value

If the function succeeds, the return value is TRUE.

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

The function fails if the requested read operation crosses into an area of the process that is inaccessible.

Remarks

ReadProcessMemory copies the data in the specified address range from the address space of the specified process into the specified buffer of the current process. Any process that has a handle with PROCESS_VM_READ access can call the function. The process whose address space is read is typically, but not necessarily, being debugged.

The entire area to be read must be accessible. If it is not, the function fails as noted previously.

See Also

WriteProcessMemory


RealizePalette
 RealizePalette  QuickInfo  Overview  Group

The RealizePalette function maps palette entries from the current logical palette to the system palette.

UINT RealizePalette(

HDC  hdc	// handle of device context
);
Parameters

hdc

Identifies the device context (DC) into which a logical palette has been selected.

Return Value

If the function succeeds, the return value is the number of entries in the logical palette mapped to the system palette.

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

Remarks

An application can determine whether a device supports palette operations by calling the GetDeviceCaps function and specifying the RASTERCAPS constant.

The RealizePalette function modifies the palette for the device associated with the specified device context. If the device context is a memory DC, the color table for the bitmap selected into the DC is modified. If the device context is a display DC, the physical palette for that device is modified.

A logical color palette is a buffer between color-intensive applications and the system, allowing these applications to use as many colors as needed without interfering with colors displayed by other windows.

When an application's window has the focus and it calls the RealizePalette function, Windows attempts to realize as many of the requested colors as possible. The same is also true for applications with inactive windows.

See Also

CreatePalette, GetDeviceCaps, SelectPalette


Rectangle
 Rectangle  QuickInfo  Overview  Group

The Rectangle function draws a rectangle. The rectangle is outlined by using the current pen and filled by using the current brush.

BOOL Rectangle(

HDC  hdc,	// handle of device context
int  nLeftRect,	// x-coord. of bounding rectangle's upper-left corner
int  nTopRect,	// y-coord. of bounding rectangle's upper-left corner
int  nRightRect,	// x-coord. of bounding rectangle's lower-right corner
int  nBottomRect	// y-coord. of bounding rectangle's lower-right corner
);
Parameters

hdc

Identifies the device context.

nLeftRect

Specifies the logical x-coordinate of the upper-left corner of the rectangle.

nTopRect

Specifies the logical y-coordinate of the upper-left corner of the rectangle.

nRightRect

Specifies the logical x-coordinate of the lower-right corner of the rectangle.

nBottomRect

Specifies the logical y-coordinate of the lower-right corner of the rectangle.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The current position is neither used nor updated by Rectangle.

See Also

RoundRect


RectInRegion
 RectInRegion  QuickInfo  Overview  Group

The RectInRegion function determines whether any part of the specified rectangle is within the boundaries of a region.

BOOL RectInRegion(

HRGN  hrgn,	// handle of region
CONST RECT  *lprc	// address of structure with rectangle
);
Parameters

hrgn

Identifies the region.

lprc

Points to a RECT structure containing the coordinates of the rectangle. The lower and right edges of the rectangle are not included.

Return Value

If any part of the specified rectangle lies within the boundaries of the region, the return value is TRUE.

If the function fails, the return value is FALSE.

See Also

PtInRegion, RECT


RectVisible
 RectVisible  QuickInfo  Overview  Group

The RectVisible function determines whether any part of the specified rectangle lies within the clipping region of a device context.

BOOL RectVisible(

HDC  hdc,	// handle of the device context
CONST RECT  *lprc	// address of rectangle structure
);
Parameters

hdc

Identifies the device context.

lprc

Points to a RECT structure that contains the logical coordinates of the specified rectangle.

Return Value

If some portion of the specified rectangle lies within the clipping region, the return value is TRUE.

If the function fails, the return value is FALSE.

See Also

CreateRectRgn, PtVisible, RECT, SelectClipRgn


recv
 recv  QuickInfo

The Windows Sockets recv function receives data from a socket.

int recv (

SOCKET s,
char FAR * buf,
int len,
int flags
);
Parameters

s

A descriptor identifying a connected socket.

buf

A buffer for the incoming data.

len

The length of buf.

flags

Specifies the way the call is made.

Return Value

If the function succeeds, recv returns the number of bytes received. If the connection has been closed, it returns zero.

If the function fails, a value of SOCKET_ERROR is returned. To get extended error information, call WSAGetLastError.

Error Codes

WSANOTINITIALISED	A successful WSAStartup must occur before using this function.
WSAENETDOWN	The Windows Sockets implementation has detected that the network subsystem has failed.
WSAENOTCONN	The socket is not connected.
WSAEINTR	The (blocking) call was canceled using WSACancelBlockingCall.
WSAEINPROGRESS	A blocking Windows Sockets operation is in progress.
WSAENOTSOCK	The descriptor is not a socket.
WSAEOPNOTSUPP	MSG_OOB was specified, but the socket is not of type SOCK_STREAM.
WSAESHUTDOWN	The socket has been shut down; it is not possible to recv on a socket after shutdown has been invoked with how set to 0 or 2.
WSAEWOULDBLOCK	The socket is marked as nonblocking and the receive operation would block.
WSAEMSGSIZE	The datagram was too large to fit into the specified buffer and was truncated.
WSAEINVAL	The socket has not been bound with bind.
WSAECONNABORTED	The virtual circuit was aborted due to timeout or other failure.
WSAECONNRESET	The virtual circuit was reset by the remote side.
Remarks

This function is used on connected datagram or stream sockets specified by the s parameter and is used to read incoming data.

For sockets of type SOCK_STREAM, as much information as is currently available up to the size of the buffer supplied is returned. If the socket has been configured for in-line reception of out-of-band data (socket option SO_OOBINLINE) and out-of-band data is unread, only out-of-band data will be returned. The application may use the ioctlsocket SIOCATMARK to determine whether any more out-of-band data remains to be read.

For datagram sockets, data is extracted from the first enqueued datagram, up to the size of the buffer supplied. If the datagram is larger than the buffer supplied, the buffer is filled with the first part of the datagram, the excess data is lost, and recv returns the error WSAEMSGSIZE.

If no incoming data is available at the socket, the recv call waits for data to arrive unless the socket is nonblocking. In this case a value of SOCKET_ERROR is returned with the error code set to WSAEWOULDBLOCK. The select or WSAAsyncSelect calls can be used to determine when more data arrives.

If the socket is of type SOCK_STREAM and the remote side has shut down the connection gracefully, a recv will complete immediately with 0 bytes received. If the connection has been reset, a recv will fail with the error WSAECONNRESET.

Flags may be used to influence the behavior of the function invocation beyond the options specified for the associated socket. That is, the semantics of this function are determined by the socket options and the flags parameter. The latter is constructed by using a bitwise OR operation with any of the following values:

Value	Meaning
MSG_PEEK	Peek at the incoming data. The data is copied into the buffer but is not removed from the input queue.
MSG_OOB	Process out-of-band data (See the Remarks section for a discussion of this topic.)
See Also

bind, recvfrom, send, select, shutdown, socket, WSAAsyncSelect, WSACancelBlockingCall, WSAStartup


recvfrom
 recvfrom  QuickInfo

The Windows Sockets recvfrom function receives a datagram and stores the source address.

int recvfrom (

SOCKET s,
char FAR * buf,
int len,
int flags,
struct sockaddr FAR * from,
int FAR * fromlen
);
Parameters

s

A descriptor identifying a bound socket.

buf

A buffer for the incoming data.

len

The length of buf.

flags

Specifies the way the call is made.

from

An optional pointer to a buffer to hold the source address upon return.

fromlen

An optional pointer to the size of the from buffer.

Return Value

If the function succeeds, recvfrom returns the number of bytes received. If the connection has been closed, it returns zero.

If the function fails, a value of SOCKET_ERROR is returned. To get extended error information, call WSAGetLastError.

Error Codes

WSANOTINITIALISED	A successful WSAStartup must occur before using this function.
WSAENETDOWN	The Windows Sockets implementation has detected that the network subsystem has failed.
WSAEFAULT	The fromlen argument was invalid: the from buffer was too small to accommodate the peer address.
WSAEINTR	The (blocking) call was canceled using WSACancelBlockingCall.
WSAEINPROGRESS	A blocking Windows Sockets operation is in progress.
WSAEINVAL	The socket has not been bound with bind.
WSAENOTCONN	The socket is not connected (SOCK_STREAM only).
WSAENOTSOCK	The descriptor is not a socket.
WSAEOPNOTSUPP	MSG_OOB was specified, but the socket is not of type SOCK_STREAM.
WSAESHUTDOWN	The socket has been shut down; it is not possible to recvfrom on a socket after shutdown has been invoked with how set to 0 or 2.
WSAEWOULDBLOCK	The socket is marked as nonblocking and the recvfrom operation would block.
WSAEMSGSIZE	The datagram was too large to fit into the specified buffer and was truncated.
WSAECONNABORTED	The virtual circuit was aborted due to timeout or other failure.
WSAECONNRESET	The virtual circuit was reset by the remote side.
Remarks

This function is used to read incoming data on a (possibly connected) socket and capture the address from which the data was sent.

For sockets of type SOCK_STREAM, as much information as is currently available up to the size of the buffer supplied is returned. If the socket has been configured for in-line reception of out-of-band data (socket option SO_OOBINLINE) and out-of-band data is unread, only out-of-band data will be returned. The application may use the ioctlsocket SIOCATMARK to determine whether any more out-of-band data remains to be read. The from and fromlen parameters are ignored for SOCK_STREAM sockets.

For datagram sockets, data is extracted from the first enqueued datagram, up to the size of the buffer supplied. If the datagram is larger than the buffer supplied, the buffer is filled with the first part of the message, the excess data is lost, and recvfrom returns the error code WSAEMSGSIZE.

If from is nonzero, and the socket is of type SOCK_DGRAM, the network address of the peer that sent the data is copied to the corresponding socket address structure. The value pointed to by fromlen is initialized to the size of this structure, and is modified on return to indicate the actual size of the address stored there.

If no incoming data is available at the socket, the recvfrom call waits for data to arrive unless the socket is nonblocking. In this case a value of SOCKET_ERROR is returned with the error code set to WSAEWOULDBLOCK. The select or WSAAsyncSelect calls may be used to determine when more data arrives.

If the socket is of type SOCK_STREAM and the remote side has shut down the connection gracefully, a recvfrom will complete immediately with zero bytes received. If the connection has been reset, recv will fail with the error WSAECONNRESET.

You can use the flags parameter to influence the behavior of the function invocation beyond the options specified for the associated socket. That is, the semantics of the recvfrom function are determined by the socket options and the flags parameter. The latter is constructed by using a bitwise OR operation with any of the following values:

Value	Meaning
MSG_PEEK	Peek at the incoming data. The data is copied into the buffer but is not removed from the input queue.
MSG_OOB	Process out-of-band data (See the Remarks section for a discussion of this topic.)
See Also

bind, recv, select, send, shutdown, socket, WSAAsyncSelect, WSACancelBlockingCall, WSAStartup


RedrawWindow
 RedrawWindow  QuickInfo  Overview  Group

The RedrawWindow function updates the specified rectangle or region in a window's client area.

BOOL RedrawWindow(

HWND  hwnd,	// handle of window
CONST RECT  *lprcUpdate,	// address of structure with update rectangle
HRGN  hrgnUpdate,	// handle of update region
UINT  afuRedraw	// array of redraw flags
);
Parameters

hwnd

Identifies the window to be redrawn. If this parameter is NULL, the desktop window is updated.

lprcUpdate

Points to a RECT structure containing the coordinates of the update rectangle. This parameter is ignored if the hrgnUpdate parameter identifies a region.

hrgnUpdate

Identifies the update region. If both the hrgnUpdate and lprcUpdate parameters are NULL, the entire client area is added to the update region.

afuRedraw

Specifies one or more redraw flags. This parameter can be a combination of flags that invalidate or validate a window, control repainting, and control which windows are affected by RedrawWindow.

The following flags are used to invalidate the window:

Flag (invalidation)	Description
RDW_ERASE	Causes the window to receive a WM_ERASEBKGND message when the window is repainted. The RDW_INVALIDATE flag must also be specified; otherwise, RDW_ERASE has no effect.
RDW_FRAME	Causes any part of the nonclient area of the window that intersects the update region to receive a WM_NCPAINT message. The RDW_INVALIDATE flag must also be specified; otherwise, RDW_FRAME has no effect. The WM_NCPAINT message is typically not sent during the execution of RedrawWindow unless either RDW_UPDATENOW or RDW_ERASENOW is specified.
RDW_INTERNALPAINT	Causes a WM_PAINT message to be posted to the window regardless of whether any portion of the window is invalid.
RDW_INVALIDATE	Invalidates lprcUpdate or hrgnUpdate (only one may be non-NULL). If both are NULL, the entire window is invalidated.
The following flags are used to validate the window:

Flag (validation)	Description
RDW_NOERASE	Suppresses any pending WM_ERASEBKGND messages.
RDW_NOFRAME	Suppresses any pending WM_NCPAINT messages. This flag must be used with RDW_VALIDATE and is typically used with RDW_NOCHILDREN. RDW_NOFRAME should be used with care, as it could cause parts of a window to be painted improperly.
RDW_NOINTERNALPAINT	Suppresses any pending internal WM_PAINT messages. This flag does not affect WM_PAINT messages resulting from a non-NULL update area.
RDW_VALIDATE	Validates lprcUpdate or hrgnUpdate (only one may be non-NULL). If both are NULL, the entire window is validated. This flag does not affect internal WM_PAINT messages.
The following flags control when repainting occurs. RedrawWindow will not repaint unless one of these flags is specified.

Flag	Description
RDW_ERASENOW	Causes the affected windows (as specified by the RDW_ALLCHILDREN and RDW_NOCHILDREN flags) to receive WM_NCPAINT and WM_ERASEBKGND messages, if necessary, before the function returns. WM_PAINT messages are received at the ordinary time.
RDW_UPDATENOW	Causes the affected windows (as specified by the RDW_ALLCHILDREN and RDW_NOCHILDREN flags) to receive WM_NCPAINT, WM_ERASEBKGND, and WM_PAINT messages, if necessary, before the function returns.
By default, the windows affected by RedrawWindow depend on whether the given window has the WS_CLIPCHILDREN style. Child windows that are not the WS_CLIPCHILDREN style are unaffected; non-WS_CLIPCHILDREN windows are recursively validated or invalidated until a WS_CLIPCHILDREN window is encountered. The following flags control which windows are affected by the RedrawWindow function:

Flag	Description
RDW_ALLCHILDREN	Includes child windows, if any, in the repainting operation.
RDW_NOCHILDREN	Excludes child windows, if any, from the repainting operation.
Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

When RedrawWindow is used to invalidate part of the desktop window, the desktop window does not receive a WM_PAINT message. To repaint the desktop, an application uses the RDW_ERASE flag to generate a WM_ERASEBKGND message.

See Also

GetUpdateRect, GetUpdateRgn, InvalidateRect, InvalidateRgn, RECT, UpdateWindow


RegCloseKey
 RegCloseKey  QuickInfo  Overview  Group

The RegCloseKey function releases the handle of the specified key.

LONG RegCloseKey(

HKEY  hKey	// handle of key to close
);
Parameters

hKey

Identifies the open key to close.

Return Value

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is an error value.

Remarks

The handle for a specified key should not be used after it has been closed, because it will no longer be valid. Key handles should not be left open any longer than necessary.

The RegCloseKey function does not necessarily write information to the registry before returning; it can take as much as several seconds for the cache to be flushed to the hard disk. If an application must explicitly write registry information to the hard disk, it can use the RegFlushKey function. RegFlushKey, however, uses many system resources and should be called only when necessary.

See Also

RegCreateKey, RegCreateKeyEx, RegDeleteKey, RegFlushKey, RegOpenKey, RegOpenKeyEx, RegSetValue, RegSetValueEx


RegConnectRegistry
 RegConnectRegistry  QuickInfo  Overview  Group

The RegConnectRegistry function establishes a connection to a predefined registry handle on another computer.

LONG RegConnectRegistry(

LPTSTR  lpszComputerName,	// address of name of remote computer
HKEY  hKey,	// predefined registry handle
PHKEY  phkResult	// address of buffer for remote registry handle
);
Parameters

lpszComputerName

Points to a null-terminated string containing the name of the remote computer. The string has the following form:

\\computername

If lpszComputerName is NULL, the local computer name is used.

hKey

Specifies the predefined handle of the registry on the remote computer. Currently, the following values can be used:

HKEY_LOCAL_MACHINE
HKEY_USERS

An application cannot specify the HKEY_CLASSES_ROOT or HKEY_CURRENT_USER value for this parameter.

phkResult

Points to a variable that receives a key handle identifying the predefined handle on the remote computer.

Return Value

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is an error value.

Remarks

When a handle returned by RegConnectRegistry is no longer needed, it should be closed by calling RegCloseKey.

See Also

RegCloseKey


RegCreateKey
 RegCreateKey  QuickInfo  Overview  Group

The RegCreateKey function creates the specified key. If the key already exists in the registry, the function opens it. This function is provided for compatibility with Windows version 3.1. Win32-based applications should use the RegCreateKeyEx function.

LONG RegCreateKey(

HKEY  hKey,	// handle of an open key
LPCTSTR  lpszSubKey,	// address of name of subkey to open
PHKEY  phkResult	// address of buffer for opened handle
);
Parameters

hKey

Identifies a currently open key or any of the following predefined reserved handle values:

HKEY_CLASSES_ROOT
HKEY_CURRENT_USER
HKEY_LOCAL_MACHINE
HKEY_USERS

The key opened or created by this function is a subkey of the key identified by hKey.

lpszSubKey

Points to a null-terminated string specifying the name of a key that this function opens or creates. This key must be a subkey of the key identified by the hKey parameter.

If hKey is one of the predefined keys, lpszSubKey may be NULL. In that case, the handle returned by using phkResult is the same hKey handle passed in to the function.

phkResult

Points to a variable that receives the handle of the opened or created key.

Return Value

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is an error value.

Remarks

An application can use the RegCreateKey function to create several keys at once. For example, an application can create a subkey four levels deep at the same time as the three preceding subkeys by specifying a string of the following form for the lpszSubKey parameter:

subkey1\subkey2\subkey3\subkey4

The key identified by the hKey parameter must have been opened with KEY_CREATE_SUB_KEY access (KEY_WRITE access includes KEY_CREATE_SUB_KEY access).

If the lpszSubKey parameter is the address of an empty string, the function opens and then passes back the key identified by the hKey parameter.

See Also

RegCloseKey, RegCreateKeyEx, RegDeleteKey, RegOpenKey, RegOpenKeyEx, RegSetValue


RegCreateKeyEx
 RegCreateKeyEx  QuickInfo  Overview  Group

The RegCreateKeyEx function creates the specified key. If the key already exists in the registry, the function opens it.

LONG RegCreateKeyEx(

HKEY  hKey,	// handle of an open key
LPCTSTR  lpszSubKey,	// address of subkey name
DWORD  dwReserved,	// reserved
LPTSTR  lpszClass,	// address of class string
DWORD  fdwOptions,	// special options flag
REGSAM  samDesired,	// desired security access
LPSECURITY_ATTRIBUTES  lpSecurityAttributes,	// address of key security structure
PHKEY  phkResult,	// address of buffer for opened handle
LPDWORD  lpdwDisposition	// address of disposition value buffer
);
Parameters

hKey

Identifies a currently open key or any of the following predefined reserved handle values:

HKEY_CLASSES_ROOT
HKEY_CURRENT_USER
HKEY_LOCAL_MACHINE
HKEY_USERS

The key opened or created by the RegCreateKeyEx function is a subkey of the key identified by the hKey parameter.

lpszSubKey

Points to a null-terminated string specifying the name of a subkey that this function opens or creates. The subkey specified must be a subkey of the key identified by the hKey parameter. This subkey must not begin with the backslash character ('\'). This parameter cannot be NULL.

dwReserved

Reserved; must be zero.

lpszClass

Points to a null-terminated string that specifies the class (object type) of this key. This parameter is ignored if the key already exists.

fdwOptions

Specifies special options for the key. Currently, this parameter can be one of the following values:

Value	Meaning
REG_OPTION_VOLATILE	Windows 95: This value is ignored in Windows 95. That is, even if REG_OPTION_VOLATILE is specified, the RegCreateKeyEx function creates a nonvolatile key and returns ERROR_SUCCESS. Windows NT: This key is volatile; the information is stored in memory and is not preserved when the system is restarted. The RegSaveKey function does not save volatile keys.
REG_OPTION_NON_VOLATILE	This key is not volatile; the information is stored in a file and is preserved when the system is restarted. The RegSaveKey function saves keys that are not volatile.
By default, keys are not volatile. This option is ignored if the key already exists.

The RegSaveKey function only saves nonvolatile keys. It does not save volatile keys.

samDesired

Specifies an access mask that specifies the desired security access for the new key. This parameter can be a combination of the following values:

Value	Meaning
KEY_ALL_ACCESS	Combination of KEY_QUERY_VALUE, KEY_ENUMERATE_SUB_KEYS, KEY_NOTIFY, KEY_CREATE_SUB_KEY, KEY_CREATE_LINK, and KEY_SET_VALUE access.
KEY_CREATE_LINK	Permission to create a symbolic link.
KEY_CREATE_SUB_KEY	Permission to create subkeys.
KEY_ENUMERATE_SUB_KEYS	Permission to enumerate subkeys.
KEY_EXECUTE	Permission for read access.
KEY_NOTIFY	Permission for change notification.
KEY_QUERY_VALUE	Permission to query subkey data.
KEY_READ	Combination of KEY_QUERY_VALUE, KEY_ENUMERATE_SUB_KEYS, and KEY_NOTIFY access.
KEY_SET_VALUE	Permission to set subkey data.
KEY_WRITE	Combination of KEY_SET_VALUE and KEY_CREATE_SUB_KEY access.
lpSecurityAttributes

Points to a SECURITY_ATTRIBUTES structure that specifies the security attributes for the new key.

If this parameter is NULL, the key receives a default security descriptor. If the operating system does not support security, this parameter is ignored.

phkResult

Points to a variable that receives the handle of the opened or created key.

lpdwDisposition

Points to a variable that receives one of the following disposition values:

Value	Meaning
REG_CREATED_NEW_KEY	The key did not exist and was created.
REG_OPENED_EXISTING_KEY	The key existed and was simply opened without being changed.
Return Value

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is an error value.

Remarks

The key that the RegCreateKeyEx function creates has no values. An application can use the RegSetValue or RegSetValueEx function to set key values.

The key identified by the hKey parameter must have been opened with KEY_CREATE_SUB_KEY access. To open the key, use the RegCreateKeyEx or RegOpenKeyEx function.

An application cannot create a key under HKEY_USERS or HKEY_MACHINE.

An application can use RegCreateKeyEx to temporarily lock a portion of the registry. When the locking process creates a new key, it receives the disposition value REG_CREATED_NEW_KEY, indicating that it "owns" the lock. Another process attempting to create the same key receives the disposition value REG_OPENED_EXISTING_KEY, indicating that another process already owns the lock.

See Also

RegCreateKey, RegDeleteKey, RegOpenKey, RegOpenKeyEx, RegSaveKey, SECURITY_ATTRIBUTES


RegDeleteKey
 RegDeleteKey  QuickInfo  Overview  Group

Windows 95: The RegDeleteKey function deletes a key and all its descendents.

Windows NT: The RegDeleteKey function deletes the specified key. This function cannot delete a key that has subkeys.

LONG RegDeleteKey(

HKEY  hKey,	// handle of open key
LPCTSTR  lpszSubKey	// address of name of subkey to delete
);
Parameters

hKey

Identifies a currently open key or any of the following predefined reserved handle values:

HKEY_CLASSES_ROOT
HKEY_CURRENT_USER
HKEY_LOCAL_MACHINE
HKEY_USERS

The key specified by the lpszSubKey parameter must be a subkey of the key identified by hKey.

lpszSubKey

Points to a null-terminated string specifying the name of the key to delete. This parameter cannot be NULL, and the specified key must not have subkeys.

Return Value

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is an error value.

Remarks

If the function succeeds, RegDeleteKey removes the specified key from the registry. The entire key, including all of its values, is removed.

To open the key, use the RegCreateKeyEx or RegOpenKeyEx function. Do not use the RegCreateKey or RegOpenKey functions.

See Also

RegCloseKey, RegCreateKeyEx, RegOpenKeyEx


RegDeleteValue
 RegDeleteValue  QuickInfo  Overview  Group

The RegDeleteValue function removes a named value from the specified registry key.

LONG RegDeleteValue(

HKEY  hKey,	// handle of key
LPTSTR  lpszValue	// address of value name
);
Parameters

hKey

Identifies a currently open key or any of the following predefined reserved handle values:

HKEY_CLASSES_ROOT
HKEY_CURRENT_USER
HKEY_LOCAL_MACHINE
HKEY_USERS

lpszValue

Points to a null-terminated string that names the value to remove. If this parameter is NULL or points to an empty string, the value set by the RegSetValue function is removed.

Return Value

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is an error value.

Remarks

The key identified by the hKey parameter must have been opened with KEY_SET_VALUE access (KEY_WRITE access includes KEY_SET_VALUE access).

See Also

RegSetValue, RegSetValueEx


RegEnumKey
 RegEnumKey  QuickInfo  Overview  Group

The RegEnumKey function enumerates subkeys of the specified open registry key. The function retrieves the name of one subkey each time it is called. This function is provided for compatibility with Windows version 3.1. Win32-based applications should use the RegEnumKeyEx function.

LONG RegEnumKey(

HKEY  hKey,	// handle of key to query
DWORD  iSubKey,	// index of subkey to query
LPTSTR  lpszName,	// address of buffer for subkey name
DWORD  cchName	// size of subkey buffer
);
Parameters

hKey

Identifies a currently open key or any of the following predefined reserved handle values:

HKEY_CLASSES_ROOT
HKEY_CURRENT_USER
HKEY_LOCAL_MACHINE
HKEY_USERS

The keys returned are relative to the key identified by hKey.

iSubKey

Specifies the index of the subkey to retrieve. This value should be zero for the first call to the RegEnumKey function and then incremented for subsequent calls.

Because subkeys are not ordered, any new subkey will have an arbitrary index. This means that the function may return subkeys in any order.

lpszName

Points to a buffer that receives the name of the subkey, including the terminating null character. This function copies only the name of the subkey, not the full key hierarchy, to the buffer.

cchName

Specifies the size, in characters, of the buffer pointed to by the lpszName parameter, in characters. To determine the required buffer size, use the RegQueryInfoKey function to determine the size of the largest subkey for the key identified by the hKey parameter. The maximum required buffer size is (MAX_PATH + 1) characters.

Return Value

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is an error value.

Remarks

To enumerate subkeys, an application should initially call the RegEnumKey function with the iSubKey parameter set to zero. The application should then increment the iSubKey parameter and call the RegEnumKey function until there are no more subkeys (until the function returns ERROR_NO_MORE_ITEMS).

The application can also set iSubKey to the index of the last key on the first call to the function and decrement the index until the subkey with index 0 is enumerated. To retrieve the index of the last subkey, use the RegQueryInfoKey.

While an application is using the RegEnumKey function, it should not make calls to any registration functions that might change the key being queried.

The key identitied by the hKey parameter must have been opened with KEY_ENUMERATE_SUB_KEYS access (KEY_READ access includes KEY_ENUMERATE_SUB_KEYS access). To open the key, use the RegCreateKeyEx or RegOpenKeyEx function.

See Also

RegCloseKey, RegCreateKeyEx, RegDeleteKey, RegEnumKeyEx, RegOpenKeyEx, RegQueryInfoKey, RegQueryValue


RegEnumKeyEx
 RegEnumKeyEx  QuickInfo  Overview  Group

The RegEnumKeyEx function enumerates subkeys of the specified open registry key. The function retrieves information about one subkey each time it is called. Unlike the RegEnumKey function, RegEnumKeyEx retrieves the class name of the subkey and the time it was last modified.

LONG RegEnumKeyEx(

HKEY  hKey,	// handle of key to enumerate
DWORD  iSubkey,	// index of subkey to enumerate
LPTSTR  lpszName,	// address of buffer for subkey name
LPDWORD  lpcchName,	// address for size of subkey buffer
LPDWORD  lpdwReserved,	// reserved
LPTSTR  lpszClass,	// address of buffer for class string
LPDWORD  lpcchClass,	// address for size of class buffer
PFILETIME  lpftLastWrite	// address for time key last written to
);
Parameters

hKey

Identifies a currently open key or any of the following predefined reserved handle values:

HKEY_CLASSES_ROOT
HKEY_CURRENT_USER
HKEY_LOCAL_MACHINE
HKEY_USERS

The enumerated keys are subkeys of the key identified by hKey.

iSubkey

Specifies the index of the subkey to retrieve. This parameter should be zero for the first call to the RegEnumKeyEx function and then incremented for subsequent calls.

Because subkeys are not ordered, any new subkey will have an arbitrary index. This means that the function may return subkeys in any order.

lpszName

Points to a buffer that receives the name of the subkey, including the terminating null character. The function copies only the name of the subkey, not the full key hierarchy, to the buffer.

lpcchName

Points to a variable that specifies the size, in characters, of the buffer specified by the lpszName parameter. This size should include the terminating null character. When the function returns, the variable pointed to by lpcchName contains the number of characters stored in the buffer. The count returned does not include the terminating null character.

lpdwReserved

Reserved; must be NULL.

lpszClass

Points to a buffer that contains the class of the enumerated subkey when the function returns. This parameter can be NULL if the class is not required.

lpcchClass

Points to a variable that specifies the size, in characters, of the buffer specified by the lpszClass parameter. The size should include the terminating null character. When the function returns, lpcchClass contains the number of characters stored in the buffer. The count returned does not include the terminating null character. This parameter can be NULL only if lpszClass is NULL.

lpftLastWrite

Points to a variable that receives the time the enumerated subkey was last written to.

Return Value

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is an error value.

Remarks

To enumerate subkeys, an application should initially call the RegEnumKeyEx function with the iSubKey parameter set to zero. The application should then increment the iSubKey parameter and call RegEnumKeyEx until there are no more subkeys (until the function returns ERROR_NO_MORE_ITEMS).

The application can also set iSubKey to the index of the last subkey on the first call to the function and decrement the index until the subkey with the index 0 is enumerated. To retrieve the index of the last subkey, use the RegQueryInfoKey function.

While an application is using the RegEnumKeyEx function, it should not make calls to any registration functions that might change the key being enumerated.

The key identified by hKey must have been opened with KEY_ENUMERATE_SUB_KEYS access (KEY_READ includes KEY_ENUMERATE_SUB_KEYS). Use the RegCreateKeyEx or RegOpenKeyEx function to open the key.

See Also

RegCreateKeyEx, RegDeleteKey, RegEnumKey, RegOpenKeyEx, RegQueryInfoKey


RegEnumValue
 RegEnumValue  QuickInfo  Overview  Group

The RegEnumValue function enumerates the values for the specified open registry key. The function copies one indexed value name and data block for the key each time it is called.

LONG RegEnumValue(

HKEY  hKey,	// handle of key to query
DWORD  iValue,	// index of value to query
LPTSTR  lpszValue,	// address of buffer for value string
LPDWORD  lpcchValue,	// address for size of value buffer
LPDWORD  lpdwReserved,	// reserved
LPDWORD  lpdwType,	// address of buffer for type code
LPBYTE  lpbData,	// address of buffer for value data
LPDWORD  lpcbData	// address for size of data buffer
);
Parameters

hKey

Identifies a currently open key or any of the following predefined reserved handle values:

HKEY_CLASSES_ROOT
HKEY_CURRENT_USER
HKEY_LOCAL_MACHINE
HKEY_USERS

The enumerated values are associated with the key identified by hKey.

iValue

Specifies the index of the value to retrieve. This parameter should be zero for the first call to the RegEnumValue function and then be incremented for subsequent calls.

Because values are not ordered, any new value will have an arbitrary index. This means that the function may return values in any order.

lpszValue

Points to a buffer that receives the name of the value, including the terminating null character.

lpcchValue

Points to a variable that specifies the size, in characters, of the buffer pointed to by the lpszValue parameter. This size should include the terminating null character. When the function returns, the variable pointed to by lpcchValue contains the number of characters stored in the buffer. The count returned does not include the terminating null character.

lpdwReserved

Reserved; must be NULL.

lpdwType

Points to a variable that receives the type code for the value entry. The type code can be one of the following values:

Value	Meaning
REG_BINARY	Binary data in any form.
REG_DWORD	A 32-bit number.
REG_DWORD_LITTLE_ENDIAN	A 32-bit number in little-endian format (same as REG_DWORD). In little-endian format, the most significant byte of a word is the high-order word. This is the most common format for computers running Windows NT and Windows 95.
REG_DWORD_BIG_ENDIAN	A 32-bit number in big-endian format. In big-endian format, the most significant byte of a word is the low-order word.
REG_EXPAND_SZ	A null-terminated string that contains unexpanded references to environment variables (for example, "%PATH%"). It will be a Unicode or ANSI string depending on whether you use the Unicode or ANSI functions.
REG_LINK	A Unicode symbolic link.
REG_MULTI_SZ	An array of null-terminated strings, terminated by two null characters.
REG_NONE	No defined value type.
REG_RESOURCE_LIST	A device-driver resource list.
REG_SZ	A null-terminated string. It will be a Unicode or ANSI string, depending on whether you use the Unicode or ANSI functions.
The lpdwType parameter can be NULL if the type code is not required.

lpbData

Points to a buffer that receives the data for the value entry. This parameter can be NULL if the data is not required.

lpcbData

Points to a variable that specifies the size, in bytes, of the buffer pointed to by the lpbData parameter. When the function returns, the variable pointed to by the lpcbData parameter contains the number of bytes stored in the buffer. This parameter can be NULL, only if lpbData is NULL.

Return Value

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is an error value.

Remarks

To enumerate values, an application should initially call the RegEnumValue function with the iValue parameter set to zero. The application should then increment iValue and call the RegEnumValue function until there are no more values (until the function returns ERROR_NO_MORE_ITEMS).

The application can also set iValue to the index of the last value on the first call to the function and decrement the index until the value with index 0 is enumerated. To retrieve the index of the last value, use the RegQueryInfoKey function.

While using RegEnumValue, an application should not call any registration functions that might change the key being queried.

The key identified by the hKey parameter must have been opened with KEY_QUERY_VALUE access. To open the key, use the RegCreateKeyEx or RegOpenKeyEx function.

To determine the maximum size of the name and data buffers, use the RegQueryInfoKey function.

See Also

RegCreateKeyEx, RegEnumKey, RegEnumKeyEx, RegOpenKeyEx, RegQueryInfoKey


RegFlushKey
 RegFlushKey  QuickInfo  Overview  Group

The RegFlushKey function writes all the attributes of the specified open key into the registry.

LONG RegFlushKey(

HKEY  hKey	// handle of key to write
);
Parameters

hKey

Identifies a currently open key or any of the following predefined reserved handle values:

HKEY_CLASSES_ROOT
HKEY_CURRENT_USER
HKEY_LOCAL_MACHINE
HKEY_USERS

Return Value

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is an error value.

Remarks

It is not necessary to call RegFlushKey to change a key. Registry changes are flushed to disk by the registry using its lazy flusher. Registry changes are also flushed to disk at system shutdown.

Unlike RegCloseKey, the RegFlushKey function returns only when all the data has been written to the registry.

The RegFlushKey function may also write out parts of or all of the other keys. Calling this function excessively can have a negative effect on an application's performance.

An application should only call RegFlushKey if it requires absolute certainty that registry changes are on disk. In general, RegFlushKey rarely, if ever, need be used.

See Also

RegCloseKey, RegDeleteKey


RegGetKeySecurity
 RegGetKeySecurity  QuickInfo  Overview  Group

The RegGetKeySecurity function retrieves a copy of the security descriptor protecting the specified open registry key.

LONG RegGetKeySecurity(

HKEY  hKey,	// open handle of key to set
SECURITY_INFORMATION  SecInf,	// descriptor contents
PSECURITY_DESCRIPTOR  pSecDesc,	// address of descriptor for key
LPDWORD  lpcbSecDesc	// address of size of buffer and descriptor
);
Parameters

hKey

Identifies an open key for which to retrieve the security descriptor.

SecInf

Specifies a SECURITY_INFORMATION structure that indicates the requested security information.

pSecDesc

Points to a buffer that receives a copy of the requested security descriptor.

lpcbSecDesc

Points to a variable that specifies the size, in bytes, of the buffer pointed to by the pSecDesc parameter. When the function returns, the variable contains the number of bytes written to the buffer.

Return Value

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is an error value.

Remarks

If the buffer specified by the pSecDesc parameter is too small, the function returns ERROR_INSUFFICIENT_BUFFER and the lpcbSecDesc parameter contains the number of bytes required for the requested security descriptor.

To read the security descriptor for the specified key, the calling process must have been granted READ_CONTROL access when the key was opened, or it must be the owner of the key. (READ_CONTROL access is granted by the KEY_READ, KEY_WRITE, KEY_EXECUTE, and KEY_ALL_ACCESS access rights.) In addition, the caller must have the SE_SECURITY_NAME privilege to read the system access-control list (SACL).

For more information about security, see Security.

See Also

RegDeleteKey, RegOpenKeyEx, RegSetKeySecurity, SECURITY_INFORMATION


RegisterClass
 RegisterClass  QuickInfo  Overview  Group

The RegisterClass function registers a window class for subsequent use in calls to the CreateWindow or CreateWindowEx function.

ATOM RegisterClass(

CONST WNDCLASS  *lpwc	// address of structure with class data
);
Parameters

lpwc

Points to a WNDCLASS structure. You must fill the structure with the appropriate class attributes before passing it to the function.

Return Value

If the function succeeds, the return value is an atom that uniquely identifies the class being registered.

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

Remarks

All window classes that an application registers are unregistered when it terminates.

See Also

CreateWindow, CreateWindowEx, GetClassInfo, GetClassName, UnregisterClass, WindowProc, WNDCLASS


RegisterClassEx [New - Windows 95]
 RegisterClassEx  QuickInfo  Overview  Group

[New - Windows 95]

The RegisterClassEx function registers a window class for subsequent use in calls to the CreateWindow or CreateWindowEx function.

ATOM RegisterClassEx(

CONST WNDCLASSEX FAR  *lpwcx	// address of structure with class data
);
Parameters

lpwcx

Points to a WNDCLASSEX structure. You must fill the structure with the appropriate class attributes before passing it to the function.

Return Value

If the function succeeds, the return value is an atom that uniquely identifies the class being registered.

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

Remarks

All window classes that an application registers are unregistered when it terminates.

See Also

CreateWindow, CreateWindowEx, GetClassInfoEx, GetClassName, UnregisterClass, WindowProc


RegisterClipboardFormat
 RegisterClipboardFormat  QuickInfo  Overview  Group

The RegisterClipboardFormat function registers a new clipboard format. This format can then be used as a valid clipboard format.

UINT RegisterClipboardFormat(

LPCTSTR  lpszFormat	// address of name string
);
Parameters

lpszFormat

Points to a null-terminated string that names the new format.

Return Value

If the function succeeds, the return value identifies the registered clipboard format.

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

Remarks

If a registered format with the specified name already exists, a new format is not registered and the return value identifies the existing format. This enables more than one application to copy and paste data using the same registered clipboard format.

Registered clipboard formats are identified by values in the range 0xC000 through 0xFFFF.

See Also

CountClipboardFormats, EnumClipboardFormats, GetClipboardFormatName


RegisterDialogClasses
 RegisterDialogClasses  QuickInfo  Overview  Group

The RegisterDialogClasses function registers any nonstandard window classes required by a screen saver's configuration dialog box.

BOOL RegisterDialogClasses(

HANDLE  hinst	// handle of application instance
);
Parameters

hinst

Identifies an instance of the module registering the window classes.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The RegisterDialogClasses function should not be exported. It is called by routines defined in the SCRNSAVE.LIB file.

If a screen saver does not register any special window classes for the configuration dialog box, the RegisterDialogClasses function must return TRUE.

See Also

ScreenSaverConfigureDialog


RegisterEventSource
 RegisterEventSource  QuickInfo  Overview  Group

The RegisterEventSource function returns a handle that can be used with the ReportEvent function to log an event.

Any source name can be used; it will be carried in the event log record so that Event Viewer can use it for filtering.

HANDLE RegisterEventSource(

LPCTSTR  lpszUNCServer,	// server name for source
LPCTSTR  lpszSource	// source name for registered handle
);
Parameters

lpszUNCServer

Points to a null-terminated string that specifies the Universal Naming Convention (UNC) name of the server on which this operation is to be performed. If this parameter is NULL, the operation is performed on the local computer.

lpszSource

Points to a null-terminated string that specifies the name of the source referenced by the returned handle. The source name must be a subkey of a logfile entry under the EventLog key in the registry. For example, the source name WinApp would be valid if the registry had the following form:

HKEY_LOCAL_MACHINE

  System

    CurrentControlSet

      Services

        EventLog

          Application

            WinApp

          Security

          System

If the source name cannot be found, the event logging service uses the Application logfile with no message files for the event identifier or category.

Return Value

If the function succeeds, the return value is a handle that can be used with the ReportEvent function.

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

See Also

DeregisterEventSource, ReportEvent


RegisterHotKey
 RegisterHotKey  QuickInfo  Overview  Group

The RegisterHotKey function defines a hot key for the current thread.

BOOL RegisterHotKey(

HWND  hwnd,	// window to receive hot-key notification
int  idHotKey,	// identifier of hot key
UINT  fuModifiers,	// key-modifier flags
UINT  uVirtKey	// virtual-key code
);
Parameters

hwnd

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

idHotKey

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.

fuModifiers

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

Specifies the virtual-key code of the hot key.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

When a key is pressed, the system looks for a match against all thread 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 idHotKey parameter, the new values for the fuModifiers and uVirtKey parameters replace the previously specified values for these parameters.

See Also

GlobalAddAtom, UnregisterHotKey, WM_HOTKEY


RegisterServiceCtrlHandler
 RegisterServiceCtrlHandler  QuickInfo  Overview  Group

The RegisterServiceCtrlHandler function registers a function to handle service control requests for a service.

SERVICE_STATUS_HANDLE RegisterServiceCtrlHandler(

LPCTSTR  lpszServiceName,	// address of name of service
LPHANDLER_FUNCTION  lpHandlerProc	// address of handler function
);
Parameters

lpszServiceName

Points to a null-terminated string that names the service run by the calling thread. This is the service name that was specified in the CreateService function when the service was created.

lpHandlerProc

Points to the Handler function to be registered.

Return Value

If the function succeeds, the return value is a service status handle.

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

Errors

The following error codes may be set by the service control manager. Other error codes may be set by the registry functions that are called by the service control manager.

Value	Meaning
ERROR_INVALID_NAME	The specified service name is invalid.
ERROR_SERVICE_DOES_NOT_EXIST	The specified service does not exist.
Remarks

The ServiceMain function of a new service should immediately call the RegisterServiceCtrlHandler function to register a control handling function with the control dispatcher. This enables the control dispatcher to invoke the specified function when it receives control requests for this service. The threads of the calling process can use the service status handle returned by this function to identify the service in subsequent calls to the SetServiceStatus function.

This function must be called before the first SetServiceStatus call because it returns a service status handle for the caller to use so that no other service can inadvertently set this service's status, which is maintained by the service control manager. It also needs to be called before the first SetServiceStatus so that a control handler is in place to field control requests by the time the service specifies the controls it accepts through the SetServiceStatus function.

When the control handler function is invoked with a control request, it must call SetServiceStatus to notify the service control manager of its latest status, regardless of whether the status of the service has changed.

The service status handle does not have to be closed.

See Also

CreateService, Handler, ServiceMain, SetServiceStatus


RegisterWindowMessage
 RegisterWindowMessage  QuickInfo  Overview  Group

The RegisterWindowMessage function defines a new window message that is guaranteed to be unique throughout the system. The returned message value can be used when calling the SendMessage or PostMessage function.

UINT RegisterWindowMessage(

LPCTSTR  lpsz	// address of message string
);
Parameters

lpsz

Points to a null-terminated string that specifies the message to be registered.

Return Value

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.

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

See Also

PostAppMessage, PostMessage, SendMessage


RegLoadKey
 RegLoadKey  QuickInfo  Overview  Group

The RegLoadKey function creates a subkey under HKEY_USER or HKEY_LOCAL_MACHINE and stores registration information from a specified file into that subkey. This registration information is in the form of a hive. A hive is a discrete body of keys, subkeys, and values that is rooted at the top of the registry hierarchy. A hive is backed by a single file and .LOG file.

LONG RegLoadKey(

HKEY  hKey,	// handle of open key
LPCTSTR  lpszSubKey,	// address of name of subkey
LPCTSTR  lpszFile	// address of filename for registry information
);
Parameters

hKey

Specifies the key where the subkey will be created. This can be a predefined reserved handle value, or a handle returned by a call to RegConnectRegistry. The predefined reserved handle values are:

HKEY_LOCAL_MACHINE
HKEY_USERS

This function always loads information at the top of the registry hierarchy. The HKEY_CLASSES_ROOT and HKEY_CURRENT_USER handle values cannot be specified for this parameter, because they represent subsets of the HKEY_LOCAL_MACHINE and HKEY_USERS handle values, respectively.

lpszSubKey

Points to a null-terminated string that specifies the name of the key to be created under hKey. This subkey is where the registration information from the file will be loaded.

lpszFile

Points to a null-terminated string containing the name of a file that has registration information. This file must have been created with the RegSaveKey function. Under the file allocation table (FAT) file system, the filename may not have an extension.

Return Value

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is an error value.

Remarks

A call to RegLoadKey fails if the calling process does not have the SE_RESTORE_PRIVILEGE privilege.

If hKey is a handle returned by RegConnectRegistry, then the path specified in lpszFile is relative to the remote computer.

See Also

RegConnectRegistry, RegDeleteKey, RegReplaceKey, RegRestoreKey, RegSaveKey, RegUnloadKey


RegNotifyChangeKeyValue
 RegNotifyChangeKeyValue  QuickInfo  Overview  Group

The RegNotifyChangeKeyValue function indicates when a registry key or any of its subkeys has changed.

LONG RegNotifyChangeKeyValue(

HKEY  hKey,	// handle of key to watch
BOOL  fWatchSubTree,	// flag for subkey notification
DWORD  fdwNotifyFilter,	// changes to be reported
HANDLE  hEvent,	// handle of signaled event
BOOL  fAsync	// flag for asynchronous reporting
);
Parameters

hKey

Identifies a currently open key or any of the following predefined reserved handle values:

HKEY_CLASSES_ROOT
HKEY_CURRENT_USER
HKEY_LOCAL_MACHINE
HKEY_USERS

fWatchSubTree

Specifies a flag that indicates whether to report changes in the specified key and all of its subkeys or only in the specified key. If this parameter is TRUE, the function reports changes in the key and its subkeys. If the parameter is FALSE, the function reports changes only in the key.

fdwNotifyFilter

Specifies a set of flags that control which changes should be reported. This parameter can be a combination of the following values:

Value	Meaning
REG_NOTIFY_CHANGE_NAME	Changes to key names that occur in the specified key or in the specified key and its subkeys cause a change notification. This includes key creations and deletions.
REG_NOTIFY_CHANGE_ATTRIBUTES	Attribute changes that occur in a key or in a key and its subkeys cause a change notification.
REG_NOTIFY_CHANGE_LAST_SET	Changes to the last write time that occur in a key or in a key and its subkeys cause a change notification.
REG_NOTIFY_CHANGE_SECURITY	Security-descriptor changes that occur in a key or in a key and its subkeys cause a change notification.
hEvent

Identifies an event. If the fAsync parameter is TRUE, the function returns immediately and changes are reported by signaling this event. If fAsync is FALSE, hEvent is ignored.

fAsync

Specifies a flag that indicates how the function reports changes. If this parameter is TRUE, the function returns immediately and reports changes by signaling the specified event. When this parameter is FALSE, the function does not return until a change has occurred.

If hEvent does not specify a valid event, the fAsync parameter cannot be TRUE.

Return Value

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is an error value.

Remarks

If the key identified by the hKey parameter is closed, the event is signaled. This means that an application should not depend on the key being open after returning from a wait operation on the event.

RegNotifyChangeKeyValue does not work with remote handles. If RegNotifyChangeKeyValue is called with an hKey value that is a remote handle, it returns ERROR_INVALID_HANDLE.

See Also

RegDeleteKey, RegEnumKey, RegEnumKeyEx, RegEnumValue, RegQueryInfoKey, RegQueryValue, RegQueryValueEx


RegOpenKey
 RegOpenKey  QuickInfo  Overview  Group

The RegOpenKey function opens the specified key. This function is provided for compatibility with Windows version 3.1. Win32-based applications should use the RegOpenKeyEx function.

LONG RegOpenKey(

HKEY  hKey,	// handle of open key
LPCTSTR  lpszSubKey,	// address of name of subkey to open
PHKEY  phkResult	// address of handle of open key
);
Parameters

hKey

Identifies a currently open key or any of the following predefined reserved handle values:

HKEY_CLASSES_ROOT
HKEY_CURRENT_USER
HKEY_LOCAL_MACHINE
HKEY_USERS

The key opened by the RegOpenKey function is a subkey of the key identified by hKey.

lpszSubKey

Points to a null-terminated string containing the name of the key to open. This key must be a subkey of the key identified by the hKey parameter. If this parameter is NULL or a pointer to an empty string, the function returns the same handle that was passed in.

phkResult

Points to a variable that receives the handle of the opened key.

Return Value

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is an error value.

Remarks

The RegOpenKey function uses the default security access mask to open a key. If opening the key requires a different mask, the function fails, returning ERROR_ACCESS_DENIED. An application should use the RegOpenKeyEx function to specify an access mask in this situation.

Unlike the RegCreateKey function, RegOpenKey does not create the specified key if the key does not exist in the database.

See Also

RegCreateKey, RegCreateKeyEx, RegDeleteKey, RegOpenKeyEx


RegOpenKeyEx
 RegOpenKeyEx  QuickInfo  Overview  Group

The RegOpenKeyEx function opens the specified key.

LONG RegOpenKeyEx(

HKEY  hKey,	// handle of open key
LPCTSTR  lpszSubKey,	// address of name of subkey to open
DWORD  dwReserved,	// reserved
REGSAM  samDesired,	// security access mask
PHKEY  phkResult	// address of handle of open key
);
Parameters

hKey

Identifies a currently open key or any of the following predefined reserved handle values:

HKEY_CLASSES_ROOT
HKEY_CURRENT_USER
HKEY_LOCAL_MACHINE
HKEY_USERS

lpszSubKey

Points to a null-terminated string containing the name of the subkey to open. If this parameter is NULL or a pointer to an empty string, the function will open a new handle of the key identified by the hKey parameter. In this case, the function will not close the handles previously opened.

dwReserved

Reserved; must be zero.

samDesired

Specifies an access mask that describes the desired security access for the new key. This parameter can be a combination of the following values:

Value	Meaning
KEY_ALL_ACCESS	Combination of KEY_QUERY_VALUE, KEY_ENUMERATE_SUB_KEYS, KEY_NOTIFY, KEY_CREATE_SUB_KEY, KEY_CREATE_LINK, and KEY_SET_VALUE access.
KEY_CREATE_LINK	Permission to create a symbolic link.
KEY_CREATE_SUB_KEY	Permission to create subkeys.
KEY_ENUMERATE_SUB_KEYS	Permission to enumerate subkeys.
KEY_EXECUTE	Permission for read access.
KEY_NOTIFY	Permission for change notification.
KEY_QUERY_VALUE	Permission to query subkey data.
KEY_READ	Combination of KEY_QUERY_VALUE, KEY_ENUMERATE_SUB_KEYS, and KEY_NOTIFY access.
KEY_SET_VALUE	Permission to set subkey data.
KEY_WRITE	Combination of KEY_SET_VALUE and KEY_CREATE_SUB_KEY access.
phkResult

Points to a variable that receives the handle of the opened key.

Return Value

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is an error value.

Remarks

Unlike the RegCreateKeyEx function, the RegOpenKeyEx function does not create the specified key if the key does not exist in the registry.

See Also

RegCreateKeyEx, RegDeleteKey, RegOpenKey


RegQueryInfoKey
 RegQueryInfoKey  QuickInfo  Overview  Group

The RegQueryInfoKey function retrieves information about a specified registry key.

LONG RegQueryInfoKey (

HKEY  hKey,	// handle of key to query
LPTSTR  lpszClass,	// address of buffer for class string
LPDWORD  lpcchClass,	// address of size of class string buffer
LPDWORD  lpdwReserved,	// reserved
LPDWORD  lpcSubKeys,	// address of buffer for number of subkeys
LPDWORD  lpcchMaxSubkey,	// address of buffer for longest subkey name length
LPDWORD  lpcchMaxClass,	// address of buffer for longest class string length
LPDWORD  lpcValues,	// address of buffer for number of value entries
LPDWORD  lpcchMaxValueName,	// address of buffer for longest value name length
LPDWORD  lpcbMaxValueData,	// address of buffer for longest value data length
LPDWORD  lpcbSecurityDescriptor,	// address of buffer for security descriptor length
PFILETIME  lpftLastWriteTime	// address of buffer for last write time
);
Parameters

hKey

Identifies a currently open key or any of the following predefined reserved handle values:

HKEY_CLASSES_ROOT
HKEY_CURRENT_USER
HKEY_LOCAL_MACHINE
HKEY_USERS

lpszClass

Points to a buffer that receives the key's class name.

lpcchClass

Points to a variable that specifies the size, in characters, of the buffer pointed to by the lpszClass parameter. This size should include the terminating null character. When the function returns, this variable contains the length of the class string stored in the buffer. The count returned does not include the terminating null character. If the buffer is not big enough, the function returns ERROR_MORE_DATA, and the variable contains the size of the string, in characters, without counting the null character.

lpdwReserved

Reserved; must be NULL.

lpcSubKeys

Points to a variable that receives the number of subkeys contained by the specified key.

lpcchMaxSubkey

Points to a variable that receives the length, in characters, of the key's subkey with the longest name. The count returned does not include the terminating null character.

lpcchMaxClass

Points to a variable that receives the length, in characters, of the longest string specifying a subkey class. The count returned does not include the terminating null character.

lpcValues

Points to a variable that receives the number of values associated with the key.

lpcchMaxValueName

Points to a variable that receives the length, in characters, of the key's longest value name. The count returned does not include the terminating null character.

lpcbMaxValueData

Points to a variable that receives the length, in bytes, of the longest data component among the key's values.

lpcbSecurityDescriptor

Points to a variable that receives the length, in bytes, of the key's security descriptor.

lpftLastWriteTime

Points to a variable that receives a FILETIME structure, indicating the last time the key or any of its value entries was modified.

Return Value

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is an error value.

Remarks

The key identified by the hKey parameter must have been opened with KEY_QUERY_VALUE access (KEY_READ access includes KEY_QUERY_VALUE access).

Windows 95: If the lpszClass parameter is a valid address, but the lpcchClass parameter is not (for example, it is NULL), the function returns ERROR_SUCCESS instead of ERROR_INVALID_PARAMETER. To ensure compatibility with other platforms, always verify that lpcchClass is valid before calling the function.

See Also

FILETIME, RegDeleteKey, RegEnumKey, RegEnumKeyEx, RegEnumValue, RegQueryValue, RegQueryValueEx


RegQueryMultipleValues
 RegQueryMultipleValues  QuickInfo

The RegQueryMultipleValues function retrieves the type and data for a list of value names associated with an open registry key.

LONG RegQueryMultipleValues(

HKEY  hKey,	// handle of key to query
PVALENT  val_list,	// address of array of value entry structures
DWORD  num_vals,	// size of array of value entry structures
LPTSTR  lpValueBuf,	// address of buffer for value information
LPDWORD  ldwTotsize	// address of size of value buffer
);
Parameters

hKey

Identifies a currently open key or any of the pre-defined reserved handle values:

HKEY_CLASSES_ROOT
HEY_CURRENT_USER
HKEY_LOCAL_MACHINE
HKEY_USERS

val_list

Address of an array of VALENT structures that describe one or more value entries. When the function returns, val_list contains an element for each value entry. The VALENT structure has the following format:

typedef struct value_ent {  /* val */

    LPCTSTR  ve_valuename;

    DWORD    ve_valuelen;

    DWORD    ve_valueptr;

    DWORD    ve_type;

} RECT;

num_vals

Specifies the size, in bytes, of the array pointed to by the val_list parameter. If num_vals is not a multiple of the size of a VALENT structure, the extra space in the array is ignored. If the buffer pointed to by the val_list parameter is too small,the ldwTotsize parameter receives the required size, in bytes, and the buffer is filled to the size specified by num_vals when the function was called; extra bytes are ignored.

lpValueBuf

Pointer to a buffer that receives value names and data. The data in the buffer is doubleword-aligned; padding is inserted as necessary.

ldwTotsize

Pointer to a value that specifies the size of the output buffer pointed to by the lpValueBuf parameter. When the function returns, ldwTotsize contains the number of bytes copied to the buffer, including padding. If the buffer is too small, ldwTotsize receives the required size, in bytes, and the buffer is filled to the size specified by ldwTotsize.

Return Value

If the function succeeds, the return value is ERROR_SUCCESS..

If the function fails, the return value is is an error value that can include one of the following:

Value	Meaning
ERROR_INSUFFICIENT_BUFFER	The buffer pointed to by val_list or lpValueBuf was too small.
ERROR_CANTREAD	RegQueryMultipleValues cannot instantiate or access the provider of the dynamic key.
ERROR_TRANSFER_TOO_LONG	The total length of the requested data (num_vals + ldwTotSize) is more than the system limit of one megabyte. In this case, RegQueryMultipleValues returns only the first one megabyte of data.
Remarks

The RegQueryMultipleValues function allows an application to query one or more values of a static or dynamic key. If the target key is a static key, the system provides all of the values in an atomic fashion. To prevent excessive serialization, the aggregate data returned by the function can not exceed one megabyte.

If the target key is a dynamic key, its provider must provide all the values in an atomic fashion. This means the provider should fill the results buffer synchronously, providing a consistent view of all the values in the buffer while avoiding excessive serialization. The provider can provide at most one megabyte of total output data during an atomic call to this function.

RegQueryMultipleValues is supported remotely; that is, the hKey parameter passed to the function can refer to a remote computer.


RegQueryValue
 RegQueryValue  QuickInfo  Overview  Group

The RegQueryValue function retrieves the value associated with the unnamed value for a specified key in the registry. Values in the registry have name, type, and data components. This function retrieves the data for a key's first value that has a NULL name. This function is provided for compatibility with Windows version 3.1. Win32-based applications should use the RegQueryValueEx function.

LONG RegQueryValue(

HKEY  hKey,	// handle of key to query
LPCTSTR  lpszSubKey,	// address of name of subkey to query
LPTSTR  lpszValue,	// address of buffer for returned string
PLONG  pcbValue	// address of buffer for size of returned string
);
Parameters

hKey

Identifies a currently open key or any of the following predefined reserved handle values:

HKEY_CLASSES_ROOT
HKEY_CURRENT_USER
HKEY_LOCAL_MACHINE
HKEY_USERS

lpszSubKey

Points to a null-terminated string containing the name of the subkey of the hKey parameter for which a value is to be retrieved. If this parameter is NULL or points to an empty string, the function retrieves the value set by the RegSetValue function for the key identified by hKey.

lpszValue

Points to a buffer that receives the value associated with the lpszSubKey parameter. The buffer should be big enough to contain the terminating null character. This parameter can be NULL if the data is not required.

If lpszValue is NULL, and pcbValue is not NULL, the function places the size in bytes of the data referenced by the value key, including the terminating null character, into the variable pointed to by pcbValue. This lets an application determine how to best preallocate a buffer for the value key's data.

pcbValue

Points to a variable specifying the size, in bytes, of the buffer pointed to by the lpszValue parameter. When the function returns, this variable contains the size of the data copied to lpszValue, including the terminating null character.

If the buffer specified by lpszValue parameter is not large enough to hold the data, the function returns the value ERROR_MORE_DATA, and stores the required buffer size, in bytes, into the variable pointed to by pcbValue.

If lpszValue is NULL, the function returns ERROR_SUCCESS, and stores the size of the string, in bytes, into the variable pointed to by pcbValue. This lets an application determine the best way to allocate a buffer for the value key's data.

In all cases the value returned in pcbValue always includes the size of the terminating null character in the string.

Return Value

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is an error value.

Remarks

The key identified by the hKey parameter must have been opened with KEY_QUERY_VALUE access (KEY_READ access includes KEY_QUERY_VALUE access).

If the ANSI version of this function is used (either by explicitly calling RegQueryValue or by not defining Unicode before including the WINDOWS.H file), this function converts the stored Unicode string to an ANSI string before copying it to the buffer specified by the lpszValue parameter.

See Also

RegEnumKey, RegEnumKeyEx, RegEnumValue, RegQueryInfoKey, RegQueryValueEx, RegSetValue, RegSetValueEx


RegQueryValueEx
 RegQueryValueEx  QuickInfo  Overview  Group

The RegQueryValueEx function retrieves the type and data for a specified value name associated with an open registry key.

LONG RegQueryValueEx(

HKEY  hKey,	// handle of key to query
LPTSTR  lpszValueName,	// address of name of value to query
LPDWORD  lpdwReserved,	// reserved
LPDWORD  lpdwType,	// address of buffer for value type
LPBYTE  lpbData,	// address of data buffer
LPDWORD  lpcbData	// address of data buffer size
);
Parameters

hKey

Identifies a currently open key or any of the following predefined reserved handle values:

HKEY_CLASSES_ROOT
HKEY_CURRENT_USER
HKEY_LOCAL_MACHINE
HKEY_USERS

lpszValueName

Points to a null-terminated string containing the name of the value to be queried.

lpdwReserved

Reserved; must be NULL.

lpdwType

Points to a variable that receives the key's value type. The value returned through this parameter will be one of the following:

Value	Meaning
REG_BINARY	Binary data in any form.
REG_DWORD	A 32-bit number.
REG_DWORD_LITTLE_ENDIAN	A 32-bit number in little-endian format (same as REG_DWORD). In little-endian format, the most significant byte of a word is the high-order word. This is the most common format for computers running Windows NT and Windows 95.
REG_DWORD_BIG_ENDIAN	A 32-bit number in big-endian format. In big-endian format, the most significant byte of a word is the low-order word.
REG_EXPAND_SZ	A null-terminated string that contains unexpanded references to environment variables (for example, "%PATH%"). It will be a Unicode or ANSI string depending on whether you use the Unicode or ANSI functions.
REG_LINK	A Unicode symbolic link.
REG_MULTI_SZ	An array of null-terminated strings, terminated by two null characters.
REG_NONE	No defined value type.
REG_RESOURCE_LIST	A device-driver resource list.
REG_SZ	A null-terminated string. It will be a Unicode or ANSI string depending on whether you use the Unicode or ANSI functions.
The lpdwType parameter can be NULL if the type is not required.

lpbData

Points to a buffer that receives the value's data. This parameter can be NULL if the data is not required.

lpcbData

Points to a variable that specifies the size, in bytes, of the buffer pointed to by the lpbData parameter. When the function returns, this variable contains the size of the data copied to lpbData.

If the buffer specified by lpbData parameter is not large enough to hold the data, the function returns the value ERROR_MORE_DATA, and stores the required buffer size, in bytes, into the variable pointed to by lpcbData.

If lpbData is NULL, and lpcbData is non-NULL, the function returns ERROR_SUCCESS, and stores the size of the data, in bytes, in the variable pointed to by lpcbData. This lets an application determine the best way to allocate a buffer for the value key's data.

If the data has the REG_SZ, REG_MULTI_SZ or REG_EXPAND_SZ type, then lpData will also include the size of the terminating null character.

The lpcbData parameter can be NULL only if lpbData is NULL.

Return Value

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is an error value.

Remarks

The key identified by hKey must have been opened with KEY_QUERY_VALUE access. To open the key, use the RegCreateKeyEx or RegOpenKeyEx function.

This function does not expand the environment-variable names in the value data when the value type is REG_EXPAND_SZ. The ExpandEnvironmentStrings function can be used to expand the environment-variable names.

If the value data has the REG_SZ, REG_MULTI_SZ or REG_EXPAND_SZ type, and the ANSI version of this function is used (either by explicitly calling RegQueryValueEx or by not defining Unicode before including the WINDOWS.H file), this function converts the stored Unicode string to an ANSI string before copying it to the buffer pointed to by lpbData.

When calling the RegQueryValueEx function with hKey set to the HKEY_PERFORMANCE_DATA handle and a value string of a specified object, the returned data structure sometimes has unrequested objects. Don't be surprised; this is normal behavior. When calling the RegQueryValueEx function, you should always expect to walk the returned data structure to look for the requested object.

See Also

ExpandEnvironmentStrings, RegCreateKeyEx, RegEnumKey, RegEnumKeyEx, RegEnumValue, RegOpenKeyEx, RegQueryInfoKey, RegQueryValue


RegReplaceKey
 RegReplaceKey  QuickInfo  Overview  Group

The RegReplaceKey function replaces the file backing a key and all its subkeys with another file, so that when the system is next started, the key and subkeys will have the values stored in the new file.

LONG RegReplaceKey(

HKEY  hKey,	// handle of open key
LPCTSTR  lpSubKey,	// address of name of subkey
LPCTSTR  lpNewFile,	// address of filename for file with new data
LPCTSTR  lpOldFile	// address of filename for backup file
);
Parameters

hKey

Identifies a currently open key or any of the following predefined reserved handle values:

HKEY_CLASSES_ROOT
HKEY_CURRENT_USER
HKEY_LOCAL_MACHINE
HKEY_USERS

lpSubKey

Points to a null-terminated string containing the name of a key whose subkeys and values are replaced by this function. This key must be a subkey of the key identified by the hKey parameter. This parameter can be NULL.

The selected key must be the root of a hive; that is, it must be an immediate descendent of HKEY_LOCAL_MACHINE or HKEY_USERS.

lpNewFile

Points to a null-terminated string containing the name of the file with registration information. This file is typically created by using the RegSaveKey function. Under the file allocation table (FAT) file system, the filename may not have an extension.

lpOldFile

Points to a null-terminated string containing the name of a file that receives a backup copy of the registry information being replaced. If this file is created under the FAT file system, it should not have an extension.

Return Value

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is an error value.

Remarks

The file specified by the lpNewFile parameter remains open until the system is restarted.

A process must have the SE_RESTORE_NAME privilege to call this function.

If hKey is a handle returned by RegConnectRegistry, then the paths specified in lpNewFile and lpOldFile are relative to the remote computer.

See Also

RegConnectRegistry, RegDeleteKey, RegLoadKey, RegRestoreKey


RegRestoreKey
 RegRestoreKey  QuickInfo  Overview  Group

The RegRestoreKey function reads the registry information in a specified file and copies it over the specified key. This registry information may be in the form of a key and multiple levels of subkeys.

LONG RegRestoreKey(

HKEY  hKey,	// handle of key where restore begins
LPCTSTR  lpszFile,	// address of filename containing saved tree
DWORD  fdw	// optional flags
);
Parameters

hKey

Identifies a currently open key or any of the following predefined reserved handle values:

HKEY_CLASSES_ROOT
HKEY_CURRENT_USER
HKEY_LOCAL_MACHINE
HKEY_USERS

Any information contained in this key and its descendent keys is overwritten by the information in the file pointed to by the lpszFile parameter.

lpszFile

Points to a null-terminated string containing the name of the file with registry information. This file is typically created by using the RegSaveKey function. Under the file allocation table (FAT) file system, the filename may not have an extension.

fdw

Specifies a flag indicating whether the key is volatile. (A volatile key is valid only until the next time the system is started.) This parameter is optional; if no value is specified, the key is not volatile.

This parameter can be the REG_WHOLE_HIVE_VOLATILE flag set. Instead of restoring the given key, this flag causes a new, volatile (memory only) set of registry information to be created. (A hive is a large set of registry information, typically containing all of the pertinent information for part of the system. For example, HKEY_LOCAL_MACHINE\Hardware is a volatile hive.)

If REG_WHOLE_HIVE_VOLATILE is specified, the key identified by the hKey parameter must be either the HKEY_USERS or HKEY_LOCAL_MACHINE value.

Return Value

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is an error value.

Remarks

If the calling process does not have the SE_RESTORE_NAME privilege or if any subkeys of the hKey parameter are open, RegRestoreKey fails.

This function replaces the keys and values below the specified key with the keys and values that are subsidiary to the top-level key in the file, no matter what the name of the top-level key in the file might be. For example, hKey might identify a key A with subkeys B and C, while the lpszFile parameter specifies a file containing key X with subkeys Y and Z. After a call to RegRestoreKey, the registry would contain key A with subkeys Y and Z. The value entries of A would be replaced by the value entries of X.

The new information in the file specified by lpszFile overwrites the contents of the key specified by the hKey parameter, except for the key name.

If hKey represents a key in a remote computer, the path described by lpszFile is relative to the remote computer.

See Also

RegDeleteKey, RegLoadKey, RegReplaceKey, RegSaveKey


RegSaveKey
 RegSaveKey  QuickInfo  Overview  Group

The RegSaveKey function saves the specified key and all of its subkeys and values to a new file.

LONG RegSaveKey(

HKEY  hKey,	// handle of key where save begins
LPCTSTR  lpszFile,	// address of filename to save to
LPSECURITY_ATTRIBUTES  lpsa	// address of security structure
);
Parameters

hKey

Specifies a handle of the key where the save operation is to begin, or any of the following predefined reserved handle values:

HKEY_CLASSES_ROOT
HKEY_CURRENT_USER
HKEY_LOCAL_MACHINE
HKEY_USERS

lpszFile

Points to a null-terminated string containing the name of the file in which the specified key and subkeys are saved. This file cannot already exist. If this filename includes an extension, it cannot be used on file allocation table (FAT) file systems by the RegLoadKey, RegReplaceKey, or RegRestoreKey function.

lpsa

Points to a SECURITY_ATTRIBUTES structure for the new file. If this parameter is NULL, the file receives a default security descriptor.

Return Value

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is an error value.

Remarks

If hKey represents a key on a remote computer, the path described by lpszFile is relative to the remote computer.

The caller of this function must possess the SeBackupPrivilege security privilege.

The RegSaveKey function saves only nonvolatile keys. It does not save volatile keys. A key is made volatile or nonvolatile at its creation; see RegCreateKeyEx.

See Also

RegCreateKeyEx, RegDeleteKey, RegLoadKey, RegReplaceKey, RegRestoreKey, SECURITY_ATTRIBUTES


RegSetKeySecurity
 RegSetKeySecurity  QuickInfo  Overview  Group

The RegSetKeySecurity function sets the security of an open registry key.

LONG RegSetKeySecurity(

HKEY  hKey,	// open handle of key to set
SECURITY_INFORMATION  si,	// descriptor contents
PSECURITY_DESCRIPTOR  psd	// address of descriptor for key
);
Parameters

hKey

Identifies an open key for which the security descriptor is set.

si

Specifies a SECURITY_INFORMATION structure that indicates the contents of the supplied security descriptor.

Because subkeys are not ordered, any new subkey will have an arbitrary index. This means the function may return subkeys in any order.

psd

Points to a SECURITY_DESCRIPTOR structure that specifies the security attributes to set for the specified key.

Return Value

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is an error value.

Remarks

This function succeeds only if the following conditions are met:

•	If the key's owner or group is being set, the caller must have WRITE_OWNER permission or have the SE_TAKE_OWNERSHIP_NAME privilege.

•	If the key's discretionary access-control list (DACL) is being set, the caller must have WRITE_DAC permission or be the object's owner.

•	If the key's system access-control list (SACL) is being set, the caller must have the SE_SECURITY_NAME privilege.

If hKey is one of the predefined keys, the predefined key should be closed with RegCloseKey. That ensures that the new security information is in effect the next time the predefined key is referenced.

See Also

RegCloseKey, RegDeleteKey, RegGetKeySecurity, SECURITY_INFORMATION


RegSetValue
 RegSetValue  QuickInfo  Overview  Group

The RegSetValue function associates a value with a specified key. This value must be a text string and cannot have a name. This function is provided for compatibility with Windows version 3.1. Win32-based applications should use the RegSetValueEx function, which allows an application to set any number of named values of any data type.

LONG RegSetValue(

HKEY  hKey,	// handle of key to set value for
LPCTSTR  lpSubKey,	// address of subkey name
DWORD  dwType,	// type of value
LPCTSTR  lpData,	// address of value data
DWORD  cbData	// size of value data
);
Parameters

hKey

Identifies a currently open key or any of the following predefined reserved handle values:

HKEY_CLASSES_ROOT
HKEY_CURRENT_USER
HKEY_LOCAL_MACHINE
HKEY_USERS

lpSubKey

Points to a null-terminated string containing the name of the subkey with which a value is associated. This parameter can be null or a pointer to an empty string. In this case, the value will be added to the key identified by the hKey parameter.

dwType

Specifies the type of information to be stored. This parameter must be the REG_SZ type. To store other data types, use the RegSetValueEx function.

lpData

Points to a null-terminated string containing the value to set for the specified key.

cbData

Specifies the length, in characters, of the string pointed to by the lpData parameter, not including the terminating null character.

Return Value

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is an error value.

Remarks

If the key specified by the lpSubKey parameter does not exist, the RegSetValue function creates it.

Value lengths are limited by available memory. Long values (more than 2048 bytes) should be stored as files with the filenames stored in the registry. This helps the registry perform efficiently.

The key identified by the hKey parameter must have been opened with KEY_SET_VALUE access. To open the key, use the RegCreateKeyEx or RegOpenKeyEx function. If the ANSI version of this function is used (either by explicitly calling RegSetValue or by not defining Unicode before including the WINDOWS.H file), the lpData parameter must be an ANSI character string. The string is converted to Unicode before it is stored in the registry.

See Also

RegCreateKeyEx, RegFlushKey, RegOpenKeyEx, RegQueryValue, RegQueryValueEx, RegSetValueEx


RegSetValueEx
 RegSetValueEx  QuickInfo  Overview  Group

The RegSetValueEx function stores data in the value field of an open registry key. It can also set additional value and type information for the specified key.

LONG RegSetValueEx(

HKEY  hKey,	// handle of key to set value for
LPCTSTR  lpValueName,	// address of value to set
DWORD  Reserved,	// reserved
DWORD  dwType,	// flag for value type
CONST BYTE *  lpData,	// address of value data
DWORD  cbData	// size of value data
);
Parameters

hKey

Identifies a currently open key or any of the following predefined reserved handle values:

HKEY_CLASSES_ROOT
HKEY_CURRENT_USER
HKEY_LOCAL_MACHINE
HKEY_USERS

lpValueName

Points to a string containing the name of the value to set. If a value with this name is not already present in the key, the function adds it to the key.

If this parameter is NULL or points to an empty string and the dwType parameter is the REG_SZ type, this function sets the same value the RegSetValue function would set.

Reserved

Reserved; must be zero.

dwType

Specifies the type of information to be stored as the value's data. This parameter can be one of the following values:

Value	Meaning
REG_BINARY	Binary data in any form.
REG_DWORD	A 32-bit number.
REG_DWORD_LITTLE_ENDIAN	A 32-bit number in little-endian format (same as REG_DWORD). In little-endian format, the most significant byte of a word is the high-order word. This is the most common format for computers running Windows NT and Windows 95.
REG_DWORD_BIG_ENDIAN	A 32-bit number in big-endian format. In big-endian format, the most significant byte of a word is the low-order word.
REG_EXPAND_SZ	A null-terminated string that contains unexpanded references to environment variables (for example, "%PATH%"). It will be a Unicode or ANSI string depending on whether you use the Unicode or ANSI functions.
REG_LINK	A Unicode symbolic link.
REG_MULTI_SZ	An array of null-terminated strings, terminated by two null characters.
REG_NONE	No defined value type.
REG_RESOURCE_LIST	A device-driver resource list.
REG_SZ	A null-terminated string. It will be a Unicode or ANSI string depending on whether you use the Unicode or ANSI functions.
lpData

Points to a buffer containing the data to be stored with the specified value name.

cbData

Specifies the size, in bytes, of the information pointed to by the lpData parameter. If the data is of type REG_SZ, REG_EXPAND_SZ, or REG_MULTI_SZ, cbData must include the size of the terminating null character.

Return Value

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is an error value.

Remarks

Value lengths are limited by available memory. Long values (more than 2048 bytes) should be stored as files with the filenames stored in the registry. This helps the registry perform efficiently. Application elements such as icons, bitmaps, and executable files should be stored as files and not be placed in the registry.

The key identified by the hKey parameter must have been opened with KEY_SET_VALUE access. To open the key, use the RegCreateKeyEx or RegOpenKeyEx function.

If dwType is the REG_SZ, REG_MULTI_SZ or REG_EXPAND_SZ type and the ANSI version of this function is used (either by explicitly calling RegSetValueEx or by not defining Unicode before including the WINDOWS.H file), the data pointed to by the lpData parameter must be an ANSI character string. The string is converted to Unicode before it is stored in the registry.

See Also

RegCreateKeyEx, RegFlushKey, RegOpenKeyEx, RegQueryValue, RegQueryValueEx, RegSetValue


RegUnLoadKey
 RegUnLoadKey  QuickInfo  Overview  Group

The RegUnLoadKey function unloads the specified key and subkeys from the registry.

LONG RegUnLoadKey(

HKEY  hKey,	// handle of open key
LPCTSTR  lpszSubKey	// address of name of subkey to unload
);
Parameters

hKey

Specifies the key to be unloaded. This can be a predefined reserved handle value, or a handle returned by a call to RegConnectRegistry. The predefined reserved handle values are:

HKEY_LOCAL_MACHINE
HKEY_USERS

lpszSubKey

Points to a null-terminated string containing the name of the subkey to be unloaded. The key referred to by the lpszSubKey parameter must have been created by using the RegLoadKey function.

Return Value

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is an error value.

Remarks

This function removes a hive from the registry but does not modify the file containing the registry information. A hive is a discrete body of keys, subkeys, and values that is rooted at the top of the registry hierarchy.

Windows NT only: The calling process must have the SE_RESTORE_NAME privilege. For more information about privileges, see Security.

See Also

RegConnectRegistry, RegDeleteKey, RegLoadKey, RegRestoreKey


ReleaseCapture
 ReleaseCapture  QuickInfo  Overview  Group

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 Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

An application calls this function after calling the SetCapture function.

Windows 95 only: Calling this function causes the window that is losing the mouse capture to receive a WM_CAPTURECHANGED message.

See Also

GetCapture, SetCapture


ReleaseDC
 ReleaseDC  QuickInfo  Overview  Group

The ReleaseDC function releases a device context (DC), freeing it for use by other applications. The effect of the ReleaseDC function depends on the type of device context. It frees only common and window device contexts. It has no effect on class or private device contexts.

int ReleaseDC(

HWND  hwnd,	// handle of window
HDC  hdc	// handle of device context
);
Parameters

hwnd

Identifies the window whose device context is to be released.

hdc

Identifies the device context to be released.

Return Value

The return value specifies whether the device context is released. If the device context is released, the return value is 1.

If the device context is not released, the return value is zero.

Remarks

The application must call the ReleaseDC function for each call to the GetWindowDC function and for each call to the GetDC function that retrieves a common device context.

An application cannot use the ReleaseDC function to release a device context that was created by calling the CreateDC function; instead, it must use the DeleteDC function.

See Also

CreateDC, DeleteDC, GetDC, GetWindowDC


ReleaseMutex
 ReleaseMutex  QuickInfo  Overview  Group

The ReleaseMutex function releases ownership of the specified mutex object.

BOOL ReleaseMutex(

HANDLE  hMutex	// handle of mutex object
);
Parameters

hMutex

Identifies the mutex object. The CreateMutex or OpenMutex function returns this handle.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The ReleaseMutex function fails if the calling thread does not own the mutex object.

A thread gets ownership of a mutex by specifying a handle of the mutex in one of the wait functions. The thread that creates a mutex object can also get immediate ownership without using one of the wait functions. When the owning thread no longer needs to own the mutex object, it calls the ReleaseMutex function.

While a thread has ownership of a mutex, it can specify the same mutex in additional wait-function calls without blocking its execution. This prevents a thread from deadlocking itself while waiting for a mutex that it already owns. However, to release its ownership, the thread must call ReleaseMutex once for each time that the mutex satisfied a wait.

See Also

CreateMutex, WaitForMultipleObjects, WaitForMultipleObjectsEx, WaitForSingleObject, WaitForSingleObjectEx


ReleaseSemaphore
 ReleaseSemaphore  QuickInfo  Overview  Group

The ReleaseSemaphore function increases the count of the specified semaphore object by a specified amount.

BOOL ReleaseSemaphore(

HANDLE  hSemaphore,	// handle of the semaphore object
LONG  cReleaseCount,	// amount to add to current count
LPLONG  lplPreviousCount	// address of previous count
);
Parameters

hSemaphore

Identifies the semaphore object. The CreateSemaphore or OpenSemaphore function returns this handle, which must have SEMAPHORE_MODIFY_STATE access.

cReleaseCount

Specifies the amount by which the semaphore object's current count is to be increased. The value must be greater than zero. If the specified amount would cause the semaphore's count to exceed the maximum count that was specified when the semaphore was created, the count is not changed and the function returns FALSE.

lplPreviousCount

Points to a 32-bit variable to receive the previous count for the semaphore. This parameter can be NULL if the previous count is not required.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The state of a semaphore object is signaled when its count is greater than zero and nonsignaled when its count is equal to zero. The process that calls the CreateSemaphore function specifies the semaphore's initial count. Each time a waiting thread is released because of the semaphore's signaled state, the count of the semaphore is decreased by one.

Typically, an application uses a semaphore to limit the number of threads using a resource. Before a thread uses the resource, it specifies the semaphore handle in a call to one of the wait functions. When the wait function returns, it decreases the semaphore's count by one. When the thread has finished using the resource, it calls ReleaseSemaphore to increase the semaphore's count by one.

Another use of ReleaseSemaphore is during an application's initialization. The application can create a semaphore with an initial count of zero. This sets the semaphore's state to nonsignaled and blocks all threads from accessing the protected resource. When the application finishes its initialization, it uses ReleaseSemaphore to increase the count to its maximum value, to permit normal access to the protected resource.

See Also

CreateSemaphore, MsgWaitForMultipleObjects, OpenSemaphore, WaitForMultipleObjects, WaitForMultipleObjectsEx, WaitForSingleObject, WaitForSingleObjectEx


RemoveDirectory
 RemoveDirectory  QuickInfo  Overview  Group

The RemoveDirectory function deletes an existing empty directory.

BOOL RemoveDirectory(

LPCTSTR  lpszDir	// address of directory to remove
);
Parameters

lpszDir

Points to a null-terminated string that specifies the path of the directory to be removed. The path must specify an empty directory, and the calling process must have delete access to the directory.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

CreateDirectory


RemoveFontResource
 RemoveFontResource  QuickInfo  Overview  Group

The RemoveFontResource function removes the fonts in the specified file from the Windows font table.

BOOL RemoveFontResource(

LPCTSTR  lpFileName	// address of font-resource filename
);
Parameters

lpFileName

Points to a null-terminated string that names a font resource file.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

An application that adds or removes fonts from the Windows public font table should notify other windows of the change by sending a WM_FONTCHANGE message to all top-level windows in the system. The application sends this message by calling the SendMessage function with the hwnd parameter set to HWND_BROADCAST.

If there are outstanding references to a font, the associated resource remains loaded until no device context is using it.

See Also

AddFontResource, SendMessage


RemoveMenu
 RemoveMenu  QuickInfo  Overview  Group

The RemoveMenu function deletes a menu item from the specified menu. If the menu item activates a pop-up menu, RemoveMenu does not destroy the pop-up menu or its handle, allowing the menu to be reused. Before this function is called, the GetSubMenu function should retrieve the handle of the pop-up menu.

BOOL RemoveMenu(

HMENU  hmenu,	// handle of menu
UINT  uItem,	// menu item identifier or position
UINT  fuFlags	// menu item flag
);
Parameters

hmenu

Identifies the menu to be changed.

uItem

Specifies the menu item to be deleted, as determined by the fuFlags parameter.

fuFlags

Specifies how the uItem parameter is interpreted. This parameter must be one of the following values:

Value	Meaning
MF_BYCOMMAND	Indicates that uItem 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 uItem gives the zero-based relative position of the menu item.
Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. 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.

See Also

CreatePopupMenu, DeleteMenu, DrawMenuBar, GetSubMenu


RemoveProp
 RemoveProp  QuickInfo  Overview  Group

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 of window
LPCTSTR  lpsz	// atom or address of string
);
Parameters

hwnd

Identifies the window whose property list is to be changed.

lpsz

Points 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 lpsz; the high-order word must be zero.

Return Value

If the function succeeds, the return value identifies the specified string. If the string cannot be found in the specified property list, the return value is NULL.

Remarks

An application must free the data handles associated with entries removed from a property list. The application can remove only those properties it has added. It must not remove properties added by other applications or by Windows itself.

The RemoveProp function returns the data handle associated with the string so that the application can free the data associated with the handle.

See Also

AddAtom, EnumProps, EnumPropsEx, GetProp, SetProp


ReplaceText
 ReplaceText  QuickInfo  Overview  Group

The ReplaceText function creates a system-defined modeless dialog box that enables the user to find and replace text within a document.

HWND ReplaceText(

LPFINDREPLACE  lpfr	// address of structure with initialization data
);
Parameters

lpfr

Points to a FINDREPLACE structure that contains information used to initialize the dialog box. When the user makes a selection in the dialog box, the system fills this structure with information about the user's selection and then sends a message to the application. This message contains a pointer to the FINDREPLACE structure.

Return Value

If the function succeeds, the return value is the window handle of the dialog box. It is NULL if an error occurs.

The CommDlgExtendedError function can be used to get extended error information, which may be one of the following values:

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

ReplaceText does not perform a text replacement operation; it simply returns a string typed by the user (as well as related data). An application must perform the replacement using this string.

An application can use the window handle returned by the function to communicate with or to close the dialog box.

The dialog box procedure for ReplaceText passes user requests to the application by sending special messages. The lParam parameter of each of these messages contains a pointer to a FINDREPLACE structure. The procedure sends the messages to the window identified by the hwndOwner member of the FINDREPLACE structure. An application can register the identifier for these messages by specifying the "commdlg_FindReplace" string in a call to the RegisterWindowMessage function.

For the TAB key to function correctly, any application that calls ReplaceText must also call the IsDialogMessage function in its main message loop. IsDialogMessage returns a value that indicates whether messages are intended for the Replace dialog box.

See Also

CommDlgExtendedError, FINDREPLACE, IsDialogMessage, RegisterWindowMessage, WM_CTLCOLORDLG


ReplyMessage
 ReplyMessage  QuickInfo  Overview  Group

The ReplyMessage function is used to reply to a message sent through the SendMessage function without returning control to the function that called SendMessage.

BOOL ReplyMessage(

LRESULT  lResult	// message-specific reply
);
Parameters

lResult

Specifies the result of the message processing. The possible values are based on the message sent.

Return Value

If the calling thread was processing a message sent from another thread or process, the return value is TRUE; otherwise, it is FALSE.

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.

See Also

InSendMessage, SendMessage


ReportEvent
 ReportEvent  QuickInfo  Overview  Group

The ReportEvent function writes an entry at the end of the specified event log.

BOOL ReportEvent(

HANDLE  hEventSource,	// handle returned by RegisterEventSource
WORD  fwEventType,	// event type to log
WORD  fwCategory,	// event category
DWORD  IDEvent,	// event identifier
PSID  pUserSid,	// user security identifier (optional)
WORD  cStrings,	// number of strings to merge with message
DWORD  cbData,	// size of binary data, in bytes
LPCTSTR  *plpszStrings,	// array of strings to merge with message
LPVOID  lpvData	// address of binary data
);
Parameters

hEventSource

Identifies the event log. This handle is returned by the RegisterEventSource function.

fwEventType

Specifies the type of event being logged. This parameter can be one of the following values:

Value	Meaning
EVENTLOG_ERROR_TYPE	Error event
EVENTLOG_WARNING_TYPE	Warning event
EVENTLOG_INFORMATION_TYPE	Information event
EVENTLOG_AUDIT_SUCCESS	Success Audit event
EVENTLOG_AUDIT_FAILURE	Failure Audit event
For more information about event types, see Event Logging.

fwCategory

Specifies the event category. This is source-specific information; the category can have any value.

IDEvent

Specifies the event identifier. The event identifier specifies the message that goes with this event as an entry in the message file associated with the event source.

pUserSid

Points to the current user's security identifier. This parameter can be NULL if the security identifier is not required.

cStrings

Specifies the number of strings in the array pointed to by the plpszStrings parameter. A value of zero indicates that no strings are present.

cbData

Specifies the number of bytes of event-specific raw (binary) data to write to the log. If this parameter is zero, no event-specific data is present.

plpszStrings

Points to a buffer containing an array of null-terminated strings that are merged into the message before Event Viewer displays the string to the user. This parameter must be a valid pointer (or NULL), even if cStrings is zero.

lpvData

Points to the buffer containing the binary data. This parameter must be a valid pointer (or NULL), even if the cbData parameter is zero.

Return Value

If the function succeeds, the return value is TRUE, indicating that the entry was written to the log.

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

Remarks

This function is used to log an event. The entry is written to the end of the configured logfile for the source identified by the hEventSource parameter. The ReportEvent function adds the time, the user name, the entry's length, and the offsets before storing the entry in the log.

See Also

ClearEventLog, CloseEventLog, OpenEventLog, ReadEventLog, RegisterEventSource


ResetDC
 ResetDC  QuickInfo  Overview  Group

The ResetDC function updates the given printer or plotter device context, based on the information in the specified structure.

HDC ResetDC(

HDC  hdc,	// handle of device context
CONST DEVMODE *  lpInitData	// address of structure with device context information
);
Parameters

hdc

Identifies the device context to update.

lpInitData

Points to a DEVMODE structure containing information about the new device context.

Return Value

If the function succeeds, the return value is the handle of the original device context.

If the function fails, the return value is NULL.

Remarks

An application will typically use the ResetDC function when a window receives a WM_DEVMODECHANGE message. ResetDC can also be used to change the paper orientation or paper bins while printing a document.

The ResetDC function cannot be used to change the driver name, device name, or the output port. When the user changes the port connection or device name, the application must delete the original device context and create a new device context with the new information.

An application can pass an information device context to the ResetDC function. In that situation, ResetDC will always return a printer device context.

See Also

DeviceCapabilities, DEVMODE, Escape


ResetDisplay [New - Windows 95]
 ResetDisplay  QuickInfo  Overview  Group

[New - Windows 95]

The ResetDisplay function informs the system that the display resolution is to be changed. A Control Panel application calls this function after updating the registry.

BOOL API ResetDisplay(VOID)

Parameters

This function has no parameters.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

This function does the following:

1.	Broadcasts a WM_DISPLAYCHANGE message, with wParam = FALSE, indicating the display resolution is about to change.

2.	Changes the display resolution and updates various internal variables.

3.	Moves windows and icons that are no longer visible, if any.

4.	Invalidates the entire desktop to force a repainting.

5.	Broadcasts a WM_DISPLAYCHANGE message, with wParam = TRUE, indicating that the display resolution has changed.

The logical dots per inch and number of colors do not change.

See Also

WM_DISPLAYCHANGE


ResetEvent
 ResetEvent  QuickInfo  Overview  Group

The ResetEvent function sets the state of the specified event object to nonsignaled.

BOOL ResetEvent(

HANDLE  hEvent	// handle of event object
);
Parameters

hEvent

Identifies the event object. The CreateEvent or OpenEvent function returns this handle, which must have EVENT_MODIFY_STATE access.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The state of an event object remains nonsignaled until it is explicitly set to signaled by the SetEvent or PulseEvent function. This nonsignaled state blocks the execution of any threads that have specified the event object in a call to one of the wait functions.

The ResetEvent function is used primarily for manual-reset event objects, which must be set explicitly to the nonsignaled state. Auto-reset event objects automatically change from signaled to nonsignaled after a single waiting thread is released.

See Also

CreateEvent, OpenEvent, PulseEvent, SetEvent


ResetPrinter
 ResetPrinter  QuickInfo  Overview  Group

The ResetPrinter function lets an application specify the data type and device mode values that are used for printing documents submitted by the StartDocPrinter function. These values can be overridden by using the SetJob function once document printing has started.

BOOL ResetPrinter (

HANDLE  hPrinter,	// printer handle
LPPRINTER_DEFAULTS  pDefault	// address of printer defaults structure
);
Parameters

hPrinter

Identifies a printer.

pDefault

Points to a PRINTER_DEFAULTS structure.

The ResetPrinter function ignores the DesiredAccess member of the PRINTER_DEFAULTS structure. Set that member to zero.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

OpenPrinter, PRINTER_DEFAULTS, StartDocPrinter, SetJob


ResizePalette
 ResizePalette  QuickInfo  Overview  Group

The ResizePalette function increases or decreases the size of a logical palette based on the specified value.

BOOL ResizePalette(

HPALETTE  hpal	// handle of logical palette
UINT  nEntries,	// number of entries in logical palette
);
Parameters

hpal

Identifies the palette to be changed.

nEntries

Specifies the number of entries in the palette after it has been resized.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

An application can determine whether a device supports palette operations by calling the GetDeviceCaps function and specifying the RASTERCAPS constant.

If an application calls ResizePalette to reduce the size of the palette, the entries remaining in the resized palette are unchanged. If the application calls ResizePalette to enlarge the palette, the additional palette entries are set to black (the red, green, and blue values are all 0) and their flags are set to zero.

See Also

GetDeviceCaps


RestoreDC
 RestoreDC  QuickInfo  Overview  Group

The RestoreDC function restores a device context (DC) to the specified state. The device context is restored by popping state information off a stack created by earlier calls to the SaveDC function.

BOOL RestoreDC(

HDC  hdc,	// handle of device context
int  nSavedDC	// specifies state to be restored
);
Parameters

hdc

Identifies the device context.

nSavedDC

Specifies the instance of the device context to be restored. If this parameter is positive, nSavedDC represents a specific instance of the device context to be restored. If this parameter is negative, nSavedDC represents an instance relative to the current device context. For example, −1 restores the most recently saved state.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

The stack can contain the state information for several instances of the device context. If the state specified by the given parameter is not at the top of the stack, RestoreDC deletes all state information between the top of the stack and the specified instance.

See Also

SaveDC


ResumeThread
 ResumeThread  QuickInfo  Overview  Group

The ResumeThread function decrements a thread's suspend count. When the suspend count is decremented to zero, the execution of the thread is resumed.

DWORD ResumeThread(

HANDLE  hThread	// identifies thread to restart
);
Parameters

hThread

Specifies a handle for the thread to be restarted. The handle must have THREAD_SUSPEND_RESUME access to the thread.

Return Value

If the function succeeds, the return value is the thread's previous suspend count.

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

Remarks

The ResumeThread function checks the suspend count of the subject thread. If the suspend count is 0, the thread is not currently suspended. Otherwise, the subject thread's suspend count is decremented. If the resulting value is 0, then the execution of the subject thread is resumed.

If the return value is 0, the specified thread was not suspended. If the return value is 1, the specified thread was suspended but was restarted. If the return value is greater than 1, the specified thread is still suspended.

Note that while reporting debug events, all threads within the reporting process are frozen. Debuggers are expected to use the SuspendThread and ResumeThread functions to limit the set of threads that can execute within a process. By suspending all threads in a process except for the one reporting a debug event, it is possible to "single step" a single thread. The other threads are not released by a continue operation if they are suspended.

See Also

SuspendThread


ReuseDDElParam
 ReuseDDElParam  QuickInfo  Overview  Group

The ReuseDDElParam function allows an application to reuse a packed DDE lParam parameter, rather than allocating a new packed lParam. Using this function reduces reallocations for applications that pass packed DDE messages.

LONG ReuseDDElParam(

LONG  lParam,	// posted lParam to be reused
UINT  uMsgIn,	// identifier of received message
UINT  uMsgOut,	// identifier of posted message
UINT  uLow,	// low-order word of new lParam
UINT  uHigh	// high-order word of new lParam
);
Parameters

lParam

Specifies the lParam parameter of the posted DDE message being reused.

uMsgIn

Specifies the identifier of the received DDE message.

uMsgOut

Specifies the identifier of the DDE message to be posted. The DDE message will reuse the packed lParam parameter.

uLow

Specifies the value to be packed into the low-order word of the reused lParam parameter.

uHigh

Specifies the value to be packed into the high-order word of the reused lParam parameter.

Return Value

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Remarks

The return value must be posted as the lParam parameter of a DDE message; it must not be used for any other purpose. Once the return value is posted, the posting application need not perform any action to dispose of the lParam parameter.

Use ReuseDDElParam instead of FreeDDElParam if the lParam parameter will be reused in a responding message. ReuseDDElParam returns the lParam appropriate for reuse.

This function allocates or frees lParam parameters as needed, depending on the packing requirements of the incoming and outgoing messages. This reduces reallocations in passing DDE messages.

See Also

FreeDDElParam, PackDDElParam, UnpackDDElParam


RevertToSelf
 RevertToSelf  QuickInfo  Overview  Group

The RevertToSelf function terminates the impersonation of a client application.

BOOL RevertToSelf(VOID)

Parameters

This function has no parameters.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

It is advisable for a process to call the RevertToSelf function after finishing any impersonation begun by using the DdeImpersonateClient, ImpersonateNamedPipeClient, or ImpersonateSelf function.

See Also

DdeImpersonateClient, ImpersonateNamedPipeClient, ImpersonateSelf


RoundRect
 RoundRect  QuickInfo  Overview  Group

The RoundRect function draws a rectangle with rounded corners. The rectangle is outlined by using the current pen and filled by using the current brush.

BOOL RoundRect(

HDC  hdc,	// handle of device context
int  nLeftRect,	// x-coord. of bounding rectangle's upper-left corner
int  nTopRect,	// y-coord. of bounding rectangle's upper-left corner
int  nRightRect,	// x-coord. of bounding rectangle's lower-right corner
int  nBottomRect,	// y-coord. of bounding rectangle's lower-right corner
int  nWidth,	// width of ellipse used to draw rounded corners
int  nHeight	// height of ellipse used to draw rounded corners
);
Parameters

hdc

Identifies the device context.

nLeftRect

Specifies the x-coordinate of the upper-left corner of the rectangle.

nTopRect

Specifies the y-coordinate of the upper-left corner of the rectangle.

nRightRect

Specifies the x-coordinate of the lower-right corner of the rectangle.

nBottomRect

Specifies the y-coordinate of the lower-right corner of the rectangle.

nWidth

Specifies the width of the ellipse used to draw the rounded corners.

nHeight

Specifies the height of the ellipse used to draw the rounded corners.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The current position is neither used nor updated by this function.

Windows 95 only: The sum of the coordinates of the bounding rectangle cannot exceed 32,767. The sum of nLeftRect and nRightRect or nTopRect and nBottomRect parameters cannot exceed 32,767.

See Also

Rectangle


SaveDC
 SaveDC  QuickInfo  Overview  Group

The SaveDC function saves the current state of the specified device context (DC) by copying data describing selected objects and graphic modes (such as the bitmap, brush, palette, font, pen, region, drawing mode, and mapping mode) to a context stack.

int SaveDC(

HDC  hdc	// handle of device context
);
Parameters

hdc

Identifies the device context to be saved.

Return Value

If the function succeeds, the return value identifies the saved device context.

If the function fails, the return value is zero.

Remarks

The SaveDC function can be used any number of times to save any number of instances of the device context's state.

A saved state can later be restored by using the RestoreDC function.

See Also

RestoreDC


 ScaleViewportExt

The ScaleViewportExt function is not implemented in the Win32 API. Win32-based applications should use the ScaleViewportExtEx function.


ScaleViewportExtEx
 ScaleViewportExtEx  QuickInfo  Overview  Group

The ScaleViewportExtEx function modifies the viewport for a device context (DC) by using the ratios formed by the specified multiplicands and divisors.

BOOL ScaleViewportExtEx(

HDC  hdc,	// handle of device context
int  Xnum,	// horizontal multiplicand
int  Xdenom,	// horizontal divisor
int  Ynum,	// vertical multiplicand
int  Ydenom,	// vertical divisor
LPSIZE  lpSize	// address of previous viewport extents
);
Parameters

hdc

Identifies the device context.

Xnum

Specifies the amount by which to multiply the current horizontal extent.

Xdenom

Specifies the amount by which to divide the current horizontal extent.

Ynum

Specifies the amount by which to multiply the current vertical extent.

Ydenom

Specifies the amount by which to divide the current vertical extent.

lpSize

Points to a SIZE structure. The previous viewport extents (in device units) are placed in this structure. If lpSize is NULL, nothing is returned.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

The viewport extents are modified as follows:

    xNewVE = (xOldVE * Xnum) / Xdenom

    yNewVE = (yOldVE * Ynum) / Ydenom

See Also

GetViewportExtEx, SIZE


 ScaleWindowExt

The ScaleWindowExt function is not implemented in the Win32 API. Win32-based applications should use the ScaleWindowExtEx function.


ScaleWindowExtEx
 ScaleWindowExtEx  QuickInfo  Overview  Group

The ScaleWindowExtEx function modifies the window for a device context using the ratios formed by the specified multiplicands and divisors.

BOOL ScaleWindowExtEx(

HDC  hdc,	// handle of device context
int  Xnum,	// horizontal multiplicand
int  Xdenom,	// horizontal divisor
int  Ynum,	// vertical multiplicand
int  Ydenom,	// vertical divisor
LPSIZE  lpSize	// address of previous window extents
);
Parameters

hdc

Identifies the device context.

Xnum

Specifies the amount by which to multiply the current horizontal extent.

Xdenom

Specifies the amount by which to divide the current horizontal extent.

Ynum

Specifies the amount by which to multiply the current vertical extent.

Ydenom

Specifies the amount by which to divide the current vertical extent.

lpSize

Points to a SIZE structure. The previous window extents (in logical units) are placed in this structure. If lpSize is NULL, nothing is returned.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

The window extents are modified as follows:

    xNewWE = (xOldWE * Xnum) / Xdenom

    yNewWE = (yOldWE * Ynum) / Ydenom

See Also

GetWindowExtEx, SIZE


ScheduleJob
 ScheduleJob  QuickInfo  Overview  Group

The ScheduleJob function requests that the print spooler schedule a specified print job for printing.

BOOL ScheduleJob(

HANDLE  hPrinter,	// specifies printer for the print job
DWORD  dwJobID	// print job identifier
);
Parameters

hPrinter

Handle that specifies a printer for the print job. This must be a local printer that is configured as a spooled printer. If hPrinter is a handle to a remote printer connection, or if the printer is configured for direct printing, the ScheduleJob function fails.

hPrinter must be the same printer handle specifed in the call to AddJob that obtained the dwJobID print job identifer.

dwJobID

Specifies the print job to be scheduled. You obtain this print job identifer by calling the AddJob function.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

You obtain a printer handle by calling the OpenPrinter function.

You must successfully call the AddJob function before calling the ScheduleJob function. AddJob obtains the print job identifer that you pass to ScheduleJob as dwJobID. Both calls must use the same value for hPrinter.

The ScheduleJob function checks for a valid spool file. If there is an invalid spool file, or if it is empty, ScheduleJob deletes both the spool file and the corresponding print job entry in the print spooler.

See Also

AddJob, OpenPrinter


ScreenSaverConfigureDialog
 ScreenSaverConfigureDialog  QuickInfo  Overview  Group

The ScreenSaverConfigureDialog function receives messages sent to a screen saver's configuration dialog box. A screen saver that allows user configuration must support this function.

BOOL ScreenSaverConfigureDialog(

HWND  hwndDlg,	// handle of dialog box
UINT  uMsg,	// message
WPARAM  wParam,	// first message parameter
LPARAM  lParam	// second message parameter
);
Parameters

hwndDlg

Identifies the configuration dialog box.

uMsg

Specifies the message.

wParam

Specifies additional message-specific information.

lParam

Specifies additional message-specific information.

Return Value

If the function processes the message, the return value is TRUE; otherwise, it is FALSE, except in response to a WM_INITDIALOG message. In response to a WM_INITDIALOG message, ScreenSaverConfigureDialog should return FALSE if it calls the SetFocus function to set the keyboard focus to one of the controls in the dialog box. Otherwise, the function should return TRUE, in which case the system sets the keyboard focus to the first control in the dialog box that can be given the focus.

Remarks

The dialog box template for the configuration dialog box must have the DLG_SCRNSAVECONFIGURE identifier.

The dialog box procedure is used only if the application specifies the default window class (WC_DIALOG) for the dialog box. The application uses the default class if no explicit class is given 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 default dialog box procedure.

The ScreenSaverConfigureDialog function must be exported by including it in the EXPORTS statement in the application's module-definition (.DEF) file.

See Also

DefWindowProc, RegisterDialogClasses, SetFocus


ScreenSaverProc
 ScreenSaverProc  QuickInfo  Overview  Group

The ScreenSaverProc function receives messages sent to the specified screen saver window.

LONG ScreenSaverProc(

HWND  hwnd,	// handle of screen saver window
UINT  uMsg,	// message
WPARAM  wParam,	// first message parameter
LPARAM  lParam	// second message parameter
);
Parameters

hwnd

Identifies the window.

uMsg

Specifies the message.

wParam

Specifies additional message-specific information.

lParam

Specifies additional message-specific information.

Return Value

The return value is the result of the message processing and depends on the message sent.

Remarks

A screen saver's ScreenSaverProc window procedure should use the DefScreenSaverProc function instead of the DefWindowProc function to provide default message processing. The DefScreenSaverProc function passes any messages that do not affect screen saver operations to DefWindowProc.

The ScreenSaverProc function must be exported by including it in the EXPORTS statement in the application's module-definition (.DEF) file.

See Also

DefScreenSaverProc, DefWindowProc


ScreenToClient
 ScreenToClient  QuickInfo  Overview  Group

The ScreenToClient function converts the screen coordinates of a specified point on the screen to client coordinates.

BOOL ScreenToClient(

HWND  hwnd,	// window handle for source coordinates
LPPOINT  lpPoint	// address of structure containing coordinates
);
Parameters

hwnd

Identifies the window whose client area will be used for the conversion.

lpPoint

Points to a POINT structure that contains the screen coordinates to be converted.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

The function uses the window identified by the hwnd parameter and the screen coordinates given in the POINT structure to compute client coordinates. It then replaces the screen coordinates with the client coordinates. The new coordinates are relative to the upper-left corner of the specified window's client area.

The ScreenToClient function assumes the specified point is in screen coordinates.

See Also

ClientToScreen, MapWindowPoints, POINT


ScrollConsoleScreenBuffer
 ScrollConsoleScreenBuffer  QuickInfo  Overview  Group

The ScrollConsoleScreenBuffer function moves a block of data in a screen buffer. The effects of the move can be limited by specifying a clipping rectangle, so the contents of the screen buffer outside the clipping rectangle are unchanged.

BOOL ScrollConsoleScreenBuffer(

HANDLE  hConsoleOutput,	// handle of a console screen buffer
PSMALL_RECT  psrctSourceRect,	// address of screen buffer rect. to move
PSMALL_RECT  psrctClipRect,	// address of affected screen buffer rect.
COORD  coordDestOrigin,	// new location of screen buffer rect.
PCHAR_INFO  pchiFill	// address of fill character and color
);
Parameters

hConsoleOutput

Identifies a console screen buffer. The handle must have GENERIC_WRITE access.

psrctSourceRect

Points to a SMALL_RECT structure whose members specify the upper-left and lower-right coordinates of the screen buffer rectangle to be moved.

psrctClipRect

Points to a SMALL_RECT structure whose members specify the upper-left and lower-right coordinates of the screen buffer rectangle that is affected by the scrolling. This pointer can be NULL.

coordDestOrigin

Specifies the upper-left corner of the new location of the psrctSourceRect contents.

pchiFill

Points to a CHAR_INFO structure that specifies the character and color attributes to be used in filling the cells within the intersection of psrctSourceRect and psrctClipRect that were left empty as a result of the move.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

ScrollConsoleScreenBuffer copies the contents of a rectangular region of a screen buffer, specified by the psrctSourceRect parameter, to another area of the screen buffer. The target rectangle has the same dimensions as the psrctSourceRect rectangle with its upper-left corner at the coordinates specified by the coordDestOrigin parameter. Those parts of psrctSourceRect that do not overlap with the target rectangle are filled in with the character and color attributes specified by the pchiFill parameter.

The clipping rectangle applies to changes made in both the psrctSourceRect rectangle and the target rectangle. For example, if the clipping rectangle does not include a region that would have been filled by the contents of pchiFill, the original contents of the region are left unchanged.

If the scroll or target regions extend beyond the dimensions of the screen buffer, they are clipped. For example, if psrctSourceRect is the region contained by (0,0) and (19,19) and coordDestOrigin is (10,15), the target rectangle is the region contained by (10,15) and (29,34). However, if the screen buffer is 50 characters wide and 30 characters high, the target rectangle is clipped to (10,15) and (29,29). Changes to the screen buffer are also clipped according to psrctClipRect, if the parameter specifies a SMALL_RECT structure. If the clipping rectangle is specified as (0,0) and (49,19), only the changes that occur in that region of the screen buffer are made.

See Also

CHAR_INFO, SetConsoleWindowInfo, SMALL_RECT


ScrollDC
 ScrollDC  QuickInfo  Overview  Group

The ScrollDC function scrolls a rectangle of bits horizontally and vertically.

BOOL ScrollDC(

HDC  hdc,	// handle of device context
int  dx,	// horizontal scroll units
int  dy,	// vertical scroll units
CONST RECT  *lprcScroll,	// address of structure for scrolling rectangle
CONST RECT  *lprcClip,	// address of structure for clipping rectangle
HRGN  hrgnUpdate,	// handle of scrolling region
LPRECT  lprcUpdate	// address of structure for update rectangle
);
Parameters

hdc

Identifies the device context that contains the bits to be scrolled.

dx

Specifies the amount, in device units, of horizontal scrolling. This parameter must be a negative value to scroll to the left.

dy

Specifies the amount, in device units, of vertical scrolling. This parameter must be a negative value to scroll up.

lprcScroll

Points to the RECT structure containing the coordinates of the scrolling rectangle.

lprcClip

Points to the RECT structure containing the coordinates of the clipping rectangle. Only device bits within the clipping rectangle are affected. Bits scrolled from the outside of the rectangle to the inside are painted; bits scrolled from the inside of the rectangle to the outside are not painted.

hrgnUpdate

Identifies the region uncovered by the scrolling process. ScrollDC defines this region; it is not necessarily a rectangle.

lprcUpdate

Points to the RECT structure that receives the coordinates of the rectangle bounding the scrolling update region. This is the largest rectangular area that requires repainting. When the function returns, the values in the structure are in client coordinates, regardless of the mapping mode for the specified device context. This allows applications to use the update region in a call to the InvalidateRgn function, if required.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

If the lprcUpdate parameter is NULL, Windows does not compute the update rectangle. If both the hrgnUpdate and lprcUpdate parameters are NULL, Windows does not compute the update region. If hrgnUpdate is not NULL, Windows proceeds as though it contains a valid handle of the region uncovered by the scrolling process (defined by ScrollDC).

When you must scroll the entire client area of a window, use the ScrollWindow function; otherwise, use ScrollDC.

See Also

InvalidateRgn, RECT, ScrollWindow


ScrollWindow
 ScrollWindow  QuickInfo  Overview  Group

The ScrollWindow function scrolls the content of the specified window's client area. This function exists for backward compatibility. For new applications, use the ScrollWindowEx function.

BOOL ScrollWindow(

HWND  hwnd,	// handle of window to scroll
int  dx,	// amount of horizontal scrolling
int  dy,	// amount of vertical scrolling
CONST RECT *  lprcScroll,	// address of structure with scroll rectangle
CONST RECT *  lprcClip	// address of structure with clip rectangle
);
Parameters

hwnd

Identifies the window where the client area is to be scrolled.

dx

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.

dy

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.

lprcScroll

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

lprcClip

Points 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 Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. 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 lprcScroll parameter is NULL, the positions of any child windows in the window are offset by the amount specified by the dx and dy parameters; invalid (unpainted) areas in the window are also offset. ScrollWindow is faster when lprcScroll is NULL.

If lprcScroll 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 lprcScroll is not NULL, call UpdateWindow to repaint the window before calling ScrollWindow.

See Also

RECT, ScrollDC, ScrollWindowEx, UpdateWindow


ScrollWindowEx
 ScrollWindowEx  QuickInfo  Overview  Group

The ScrollWindowEx function scrolls the content of the specified window's client area. This function is similar to the ScrollWindow function, but it has additional features.

int ScrollWindowEx(

HWND  hwnd,	// handle of window to scroll
int  dx,	// amount of horizontal scrolling
int  dy,	// amount of vertical scrolling
CONST RECT  *lprcScroll,	// address of structure with scroll rectangle
CONST RECT  *lprcClip,	// address of structure with clip rectangle
HRGN  hrgnUpdate,	// handle of update region
LPRECT  lprcUpdate,	// address of structure for update rectangle
UINT  fuScroll	// scrolling flags
);
Parameters

hwnd

Identifies the window where the client area is to be scrolled.

dx

Specifies the amount, in device units, of horizontal scrolling. This parameter must be a negative value to scroll to the left.

dy

Specifies the amount, in device units, of vertical scrolling. This parameter must be a negative value to scroll up.

lprcScroll

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

lprcClip

Points to the RECT structure containing the coordinates of the clipping rectangle. Only device bits within the clipping rectangle are affected. Bits scrolled from the outside of the rectangle to the inside are painted; bits scrolled from the inside of the rectangle to the outside are not painted.

hrgnUpdate

Identifies the region that is modified to hold the region invalidated by scrolling. This parameter may be NULL.

lprcUpdate

Points to the RECT structure receiving the boundaries of the rectangle invalidated by scrolling. This parameter may be NULL.

fuScroll

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 lprcScroll parameter. The child windows are scrolled by the number of pixels specified by the dx and dy parameters. Windows sends a WM_MOVE message to all child windows that intersect the lprcScroll rectangle, even if they do not move.
Return Value

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.

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 lprcUpdate 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, Windows 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 lprcScroll, 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 lprcScroll, lprcClip, lprcUpdate, 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.

See Also

DeferWindowPos, DPtoLP, LPtoDP, RECT, RedrawWindow, ScrollDC, ScrollWindow, UpdateWindow


SearchPath
 SearchPath  QuickInfo  Overview  Group

The SearchPath function searches for the specified file.

DWORD SearchPath(

LPCTSTR  lpszPath,	// address of search path
LPCTSTR  lpszFile,	// address of filename
LPCTSTR  lpszExtension,	// address of extension
DWORD  cchReturnBuffer,	// size, in characters, of buffer
LPTSTR  lpszReturnBuffer,	// address of buffer for found filename
LPTSTR  *plpszFilePart	// address of pointer to file component
);
Parameters

lpszPath

Points to a null-terminated string that specifies the path to be searched for the file. If this parameter is NULL, the function searches for a matching file in the following directories in the following sequence:

1.	The directory from which the application loaded.

2.	The current directory.

3.	Windows 95: The Windows system directory. Use the GetSystemDirectory function to get the path of this directory.

Windows NT: The 32-bit Windows system directory. Use the GetSystemDirectory function to get the path of this directory. The name of this directory is SYSTEM32.

4.	Windows NT only: The 16-bit Windows system directory. There is no Win32 function that obtains the path of this directory, but it is searched. The name of this directory is SYSTEM.

5.	The Windows directory. Use the GetWindowsDirectory function to get the path of this directory.

6.	The directories that are listed in the PATH environment variable.

lpszFile

Points to a null-terminated string that specifies the name of the file to search for.

lpszExtension

Points to a null-terminated string that specifies an extension to be added to the filename when searching for the file. The first character of the filename extension must be a period (.). The extension is added only if the specified filename does not end with an extension.

If a filename extension is not required or if the filename contains an extension, this parameter can be NULL.

cchReturnBuffer

Specifies the length, in characters, of the buffer that receives the valid path and filename.

lpszReturnBuffer

Points to the buffer for the valid path and filename of the file found.

plpszFilePart

Points to the address (within lpszReturnBuffer) of the last component of the valid path and filename, which is the address of the character immediately following the final backslash (\) in the path.

Return Value

If the function succeeds, the value returned is the length, in characters, of the string copied to the buffer, not including the terminating null character. If the return value is greater than cchReturnBuffer, the value returned is the size of the buffer required to hold the path.

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

See Also

FindFirstFile, FindNextFile, GetSystemDirectory, GetWindowsDirectory


select
 select  QuickInfo

The Windows Sockets select function determines the status of one or more sockets, waiting if necessary.

int select (

int nfds,
fd_set FAR * readfds,
fd_set FAR * writefds,
fd_set FAR * exceptfds,
const struct timeval FAR * timeout
);
Parameters

nfds

This argument is ignored and included only for the sake of compatibility.

readfds

An optional pointer to a set of sockets to be checked for readability.

writefds

An optional pointer to a set of sockets to be checked for writability

exceptfds

An optional pointer to a set of sockets to be checked for errors.

timeout

The maximum time for select to wait, or NULL for blocking operation.

Return Value

If the function succeeds, select returns the total number of descriptors that are ready and contained in the fd_set structures, or zero if the time limit expired.

If the function fails,a value of SOCKET_ERROR is returned. To get extended error information, call WSAGetLastError.

Error Codes

WSANOTINITIALISED	A successful WSAStartup must occur before using this function.
WSAENETDOWN	The Windows Sockets implementation has detected that the network subsystem has failed.
WSAEINVAL	The timeout value is not valid.
WSAEINTR	The (blocking) call was canceled using WSACancelBlockingCall.
WSAEINPROGRESS	A blocking Windows Sockets operation is in progress.
WSAENOTSOCK	One of the descriptor sets contains an entry that is not a socket.
Remarks

This function is used to determine the status of one or more sockets. For each socket, the caller may request information on read, write, or error status. The set of sockets for which a given status is requested is indicated by an fd_set structure. Upon return, the structure is updated to reflect the subset of these sockets that meet the specified condition, and select returns the number of sockets meeting the conditions. A set of macros is provided for manipulating an fd_set. These macros are compatible with those used in the Berkeley software, but the underlying representation is completely different.

The parameter readfds identifies those sockets that are to be checked for readability. If the socket is currently listening, it will be marked as readable if an incoming connection request has been received, so that an accept is guaranteed to complete without blocking. For other sockets, readability means that queued data is available for reading or, for sockets of type SOCK_STREAM, that the virtual socket corresponding to the socket has been closed, so that a recv or recvfrom is guaranteed to complete without blocking. If the virtual circuit was closed gracefully, then a recv will return immediately with zero bytes read; if the virtual circuit was reset, then a recv will complete immediately with the error code WSAECONNRESET. The presence of out-of-band data will be checked if the socket option SO_OOBINLINE has been enabled (see setsockopt).

The parameter writefds identifies those sockets that are to be checked for writeability. If a socket is connecting (nonblocking), writability means that the connection establishment successfully completed. If the socket is not in the process of connecting, writability means that a send or sendto will complete without blocking. [It is not specified how long this guarantee can be assumed to be valid, particularly in a multithreaded environment.]

The parameter exceptfds identifies those sockets that are to be checked for the presence of out-of-band data or any exceptional error conditions. Note that out-of-band data will only be reported in this way if the option SO_OOBINLINE is FALSE. For a SOCK_STREAM, the breaking of the connection by the peer or due to KEEPALIVE failure will be indicated as an exception. This specification does not define which other errors will be included. If a socket is connecting (nonblocking), failure of the connect attempt is indicated in exceptfds.

Any of readfds, writefds, or exceptfds may be given as NULL if no descriptors are of interest.

Four macros are defined in the header file WINSOCK.H for manipulating the descriptor sets. The variable FD_SETSIZE determines the maximum number of descriptors in a set. (The default value of FD_SETSIZE is 64, which may be modified by #defining FD_SETSIZE to another value before #including WINSOCK.H.) Internally, an fd_set is represented as an array of SOCKETs; the last valid entry is followed by an element set to INVALID_SOCKET. The macros are:

FD_CLR(s, *set)	Removes the descriptor s from set.
FD_ISSET(s, *set)	Nonzero if s is a member of the set, zero otherwise.
FD_SET(s, *set)	Adds descriptor s to set.
FD_ZERO(*set)	Initializes the set to the NULL set.
The parameter timeout controls how long the select may take to complete. If timeout is a null pointer, select will block indefinitely until at least one descriptor meets the specified criteria. Otherwise, timeout points to a timeval structure which specifies the maximum time that select should wait before returning. If the timeval is initialized to {0, 0}, select will return immediately; this is used to "poll" the state of the selected sockets. If this is the case, then the select call is considered nonblocking and the standard assumptions for nonblocking calls apply. For example, the blocking hook must not be called, and the Windows Sockets implementation must not yield.

See Also

accept, connect, recv, recvfrom, send, sendto, setsockopt, WSAAsyncSelect WSACancelBlockingCall, WSAStartup


SelectClipPath
 SelectClipPath  QuickInfo  Overview  Group

The SelectClipPath function selects the current path as a clipping region for a device context, combining the new region with any existing clipping region by using the specified mode.

BOOL SelectClipPath(

HDC  hdc,	// handle of device context
int  iMode	// clipping mode
);
Parameters

hdc

Identifies the device context of the path.

iMode

Specifies the way to use the path. The following values are allowed:

Value	Meaning
RGN_AND	The new clipping region includes the intersection (overlapping areas) of the current clipping region and the current path.
RGN_COPY	The new clipping region is the current path.
RGN_DIFF	The new clipping region includes the areas of the current clipping region with those of the current path excluded.
RGN_OR	The new clipping region includes the union (combined areas) of the current clipping region and the current path.
RGN_XOR	The new clipping region includes the union of the current clipping region and the current path but without the overlapping areas.
Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To get extended error information, call GetLastError. GetLastError may return one of the following error codes:

ERROR_CAN_NOT_COMPLETE
ERROR_INVALID_PARAMETER
ERROR_NOT_ENOUGH_MEMORY

Remarks

The device context identified by the hdc parameter must contain a closed path.

See Also

BeginPath, EndPath


SelectClipRgn
 SelectClipRgn  QuickInfo  Overview  Group

The SelectClipRgn function selects a region as the current clipping region for the specified device context.

int SelectClipRgn(

HDC  hdc,	// handle of device context
HRGN  hrgn	// handle of region to be selected
);
Parameters

hdc

Identifies the device context.

hrgn

Identifies the region to be selected.

Return Value

If the function succeeds, the return value specifies the region's complexity and can be any one of the following values:

Value	Meaning
NULLREGION	Region is empty.
SIMPLEREGION	Region is a single rectangle.
COMPLEXREGION	Region is more than one rectangle.
ERROR	An error occurred. (The previous clipping region is unaffected.)
Remarks

Only a copy of the selected region is used. The region itself can be selected for any number of other device contexts or it can be deleted.

The SelectClipRgn function assumes that the coordinates for a region are specified in device units.

To remove a device-context's clipping region, specify a NULL region handle.

See Also

ExtSelectClipRgn


SelectObject
 SelectObject  QuickInfo  Overview  Group

The SelectObject function selects an object into the specified device context. The new object replaces the previous object of the same type.

HGDIOBJ SelectObject(

HDC  hdc,	// handle of device context
HGDIOBJ  hgdiobj	// handle of object
);
Parameters

hdc

Identifies the device context.

hgdiobj

Identifies the object to be selected. The specified object must have been created by using one of the following functions:

Object	Functions
Bitmap	CreateBitmap, CreateBitmapIndirect, CreateCompatibleBitmap, CreateDIBitmap, CreateDIBSection
	(Bitmaps can be selected for memory device contexts only, and for only one device context at a time.)
Brush	CreateBrushIndirect, CreateDIBPatternBrush, CreateDIBPatternBrushPt, CreateHatchBrush, CreatePatternBrush, CreateSolidBrush
Font	CreateFont, CreateFontIndirect
Pen	CreatePen, CreatePenIndirect
Region	CombineRgn, CreateEllipticRgn, CreateEllipticRgnIndirect, CreatePolygonRgn, CreateRectRgn, CreateRectRgnIndirect
Return Value

If the selected object is not a region and the function succeeds, the return value is the handle of the object being replaced. If the selected object is a region and the function succeeds, the return value is one of the following values:

Value	Meaning
SIMPLEREGION	Region consists of a single rectangle.
COMPLEXREGION	Region consists of more than one rectangle.
NULLREGION	Region is empty.
If an error occurs and the selected object is not a region, the return value is NULL. Otherwise, it is GDI_ERROR.

Remarks

This function returns the previously selected object of the specified type. An application should always replace a new object with the original, default object after it has finished drawing with the new object.

An application cannot select a bitmap into more than one device context at a time.

See Also

CombineRgn, CreateBitmap, CreateBitmapIndirect, CreateBrushIndirect, CreateCompatibleBitmap, CreateDIBitmap, CreateDIBPatternBrush, CreateEllipticRgn, CreateEllipticRgnIndirect, CreateFont, CreateFontIndirect, CreateHatchBrush, CreatePatternBrush, CreatePen, CreatePenIndirect, CreatePolygonRgn, CreateRectRgn, CreateRectRgnIndirect, CreateSolidBrush, SelectClipRgn, SelectPalette


SelectPalette
 SelectPalette  QuickInfo  Overview  Group

The SelectPalette function selects the specified logical palette into a device context.

HPALETTE SelectPalette(

HDC  hdc,	// handle of device context
HPALETTE  hpal,	// handle of logical color palette
BOOL  bForceBackground	// foreground/background mode
);
Parameters

hdc

Identifies the device context.

hpal

Identifies the logical palette to be selected.

bForceBackground

Specifies whether the logical palette is forced to be a background palette. If this value is TRUE, the RealizePalette function causes the logical palette to be mapped to the colors already in the physical palette in the best possible way. This is always done, even if the window for which the palette is realized belongs to a thread without active focus.

If this value is FALSE, RealizePalette causes the logical palette to be copied into the device palette when the application is in the foreground. (If the hdc parameter is a memory device context, this parameter is ignored.)

Return Value

If the function succeeds, the return value identifies the device context's previous logical palette.

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

Remarks

An application can determine whether a device supports palette operations by calling the GetDeviceCaps function and specifying the RASTERCAPS constant.

An application can select a logical palette into more than one device context. However, changes to a logical palette will affect all device contexts for which it is selected.

An application might call the SelectPalette function with the bForceBackground parameter set to TRUE if the child windows of a top-level window each realize their own palettes. However, only the child window that needs to realize its palette must set bForceBackground to TRUE; other child windows must set this value to FALSE.

See Also

CreatePalette, GetDeviceCaps, RealizePalette


send
 send  QuickInfo

The Windows Sockets send function sends data on a connected socket.

int send (

SOCKET s,
const char FAR * buf,
int len,
int flags
);
Parameters

s

A descriptor identifying a connected socket.

buf

A buffer containing the data to be transmitted.

len

The length of the data in buf.

flags

Specifies the way the call is made.

Return Value

If the function succeeds, send returns the total number of characters sent. (Note that this may be less than the number indicated by len.)

If the function fails, a value of SOCKET_ERROR is returned. To get extended error information, call WSAGetLastError.

Error Codes

WSANOTINITIALISED	A successful WSAStartup must occur before using this function.
WSAENETDOWN	The Windows Sockets implementation has detected that the network subsystem has failed.
WSAEACCES	The requested address is a broadcast address, but the appropriate flag was not set.
WSAEINTR	The (blocking) call was canceled using WSACancelBlockingCall.
WSAEINPROGRESS	A blocking Windows Sockets operation is in progress.
WSAEFAULT	The buf argument is not in a valid part of the user address space.
WSAENETRESET	The connection must be reset because the Windows Sockets implementation dropped it.
WSAENOBUFS	The Windows Sockets implementation reports a buffer deadlock.
WSAENOTCONN	The socket is not connected.
WSAENOTSOCK	The descriptor is not a socket.
WSAEOPNOTSUPP	MSG_OOB was specified, but the socket is not of type SOCK_STREAM.
WSAESHUTDOWN	The socket has been shutdown; it is not possible to send on a socket after shutdown has been invoked with how set to 1 or 2.
WSAEWOULDBLOCK	The socket is marked as nonblocking and the requested operation would block.
WSAEMSGSIZE	The socket is of type SOCK_DGRAM, and the datagram is larger than the maximum supported by the Windows Sockets implementation.
WSAEINVAL	The socket has not been bound with bind.
WSAECONNABORTED	The virtual circuit was aborted due to timeout or other failure.
WSAECONNRESET	The virtual circuit was reset by the remote side.
Remarks

The send function is used on connected datagram or stream sockets and is used to write outgoing data on a socket. For datagram sockets, care must be taken not to exceed the maximum IP packet size of the underlying subnets, which is given by the iMaxUdpDg element in the WSAData structure returned by WSAStartup. If the data is too long to pass atomically through the underlying protocol the error WSAEMSGSIZE is returned, and no data is transmitted.

Note that the successful completion of a send does not indicate that the data was successfully delivered.

If no buffer space is available within the transport system to hold the data to be transmitted, send will block unless the socket has been placed in a nonblocking I/O mode. On nonblocking SOCK_STREAM sockets, the number of bytes written may be between 1 and the requested length, depending on buffer availability on both the local and foreign hosts. The select call may be used to determine when it is possible to send more data.

The flags parameter may be used to influence the behavior of the function invocation beyond the options specified for the associated socket. That is, the semantics of this function are determined by the socket options and the flags parameter. The latter is constructed by using a bitwise OR operation with any of the following values:

Value	Meaning
MSG_DONTROUTE	Specifies that the data should not be subject to routing. A Windows Sockets supplier may choose to ignore this flag.
MSG_OOB	Send out-of-band data (SOCK_STREAM only)
See Also

bind, recv, recvfrom, socket, select, sendto, shutdown, WSACancelBlockingCall, WSAStartup,


SendAsyncProc
 SendAsyncProc  QuickInfo  Overview  Group

A SendAsyncProc function is an application-defined callback function that the operating system calls when the SendMessageCallback function is called. The system passes the message to the callback function after passing the message to the destination window procedure. A value of type SENDASYNCPROC is a pointer to such a function.

VOID CALLBACK SendAsyncProc(

HWND  hwnd,	// handle of destination window
UINT  uMsg,	// message
DWORD  dwData,	// application-defined value
LRESULT  lResult	// result of message processing
);
Parameters

hwnd

Identifies the window whose window procedure received the message.

If the SendMessageCallback function was called with its hwnd parameter set to HWND_BROADCAST, the operating system calls the SendAsyncProc function once for each top-level window.

uMsg

Specifies the message.

dwData

Specifies an application-defined value sent from the SendMessageCallback function.

lResult

Specifies the result of the message processing and depends on the message.

Return Value

This callback function does not return a value.

Remarks

SendAsyncProc is a placeholder for an application-defined function name.

You install a SendAsyncProc application-defined callback function by passing a SENDASYNCPROC pointer to the SendMessageCallback function.

See Also

SendMessage, SendMessageCallback


SendDlgItemMessage
 SendDlgItemMessage  QuickInfo  Overview  Group

The SendDlgItemMessage function sends a message to the specified control in a dialog box.

LONG SendDlgItemMessage(

HWND  hwndDlg,	// handle of dialog box
int  idControl,	// identifier of control
UINT  uMsg,	// message to send
WPARAM  wParam,	// first message parameter
LPARAM  lParam	// second message parameter
);
Parameters

hwndDlg

Identifies the dialog box that contains the control.

idControl

Specifies the identifier of the control that receives the message.

uMsg

Specifies the message to be sent.

wParam

Specifies additional message-specific information.

lParam

Specifies additional message-specific information.

Return Value

The return value specifies the result of the message processing and depends on the message sent.

Remarks

The SendDlgItemMessage function does not return until the message has been processed.

Using SendDlgItemMessage is identical to retrieving a handle of the specified control and calling the SendMessage function.

See Also

SendMessage


SendMessage
 SendMessage  QuickInfo  Overview  Group

The SendMessage function sends the specified message to a window or windows. The function calls the window procedure for the specified window and does not return until the window procedure has processed the message. The PostMessage function, in contrast, posts a message to a thread's message queue and returns immediately.

LRESULT SendMessage(

HWND  hwnd,	// handle of destination window
UINT  uMsg,	// message to send
WPARAM  wParam,	// first message parameter
LPARAM  lParam	// second message parameter
);
Parameters

hwnd

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

uMsg

Specifies the message to be sent.

wParam

Specifies additional message-specific information.

lParam

Specifies additional message-specific information.

Return Value

The return value specifies the result of the message processing and depends on the message sent.

Remarks

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, Windows switches to that thread and calls the appropriate window procedure.

See Also

InSendMessage, PostMessage, SendDlgItemMessage


SendMessageCallback
 SendMessageCallback  QuickInfo  Overview  Group

The SendMessageCallback function sends the specified message to a window or windows. The function calls the window procedure for the specified window and returns immediately. After the window procedure processes the message, the system calls the specified callback function, passing the result of the message processing and an application-defined value to the callback function.

BOOL SendMessageCallback(

HWND  hwnd,	// handle of destination window
UINT  uMsg,	// message to send
WPARAM  wParam,	// first message parameter
PARAM  lParam,	// second message parameter
SENDASYNCPROC  lpResultCallBack,	// function to receive message value
DWORD  dwData	// value to pass to callback function
);
Parameters

hwnd

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

uMsg

Specifies the message to be sent.

wParam

Specifies additional message-specific information.

lParam

Specifies additional message-specific information.

lpResultCallBack

Points to a callback function that the system calls after the window procedure processes the message. See SendAsyncProc for information on suitable callback functions.

If  hwnd is HWND_BROADCAST, the operating system calls the SendAsyncProc callback function once for each top-level window.

dwData

Specifies an application-defined value to be sent to the callback function pointed to by the lpfnResultCallBack parameter.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

InSendMessage, PostMessage, SendAsyncProc, SendDlgItemMessage, SendMessage, SendMessageTimeout, SendNotifyMessage


SendMessageTimeout
 SendMessageTimeout  QuickInfo  Overview  Group

The SendMessageTimeout function sends the specified message to a window or windows. The function calls the window procedure for the specified window and, if the specified window belongs to a different thread, does not return until the window procedure has processed the message or the specified time-out period has elapsed. If the window receiving the message belongs to the same queue as the current thread, the window procedure is called directly—the time-out value is ignored.

LRESULT SendMessageTimeout(

HWND  hwnd,	// handle of destination window
UINT  uMsg,	// message to send
WPARAM  wParam,	// first message parameter
LPARAM  lParam,	// second message parameter
UINT  fuFlags,	// how to send the message
UINT  uTimeout,	// time-out duration
LPDWORD  lpdwResult	// return value for synchronous call
);
Parameters

hwnd

Identifies the window whose window procedure will receive the message. If this parameter is HWND_TOPMOST, the message is sent to all top-level windows in the system, including disabled or invisible unowned windows.

uMsg

Specifies the message to be sent.

wParam

Specifies additional message-specific information.

lParam

Specifies additional message-specific information.

fuFlags

Specifies how to send the message. This parameter can be a combination of the following values:

Value	Meaning
SMTO_ABORTIFHUNG	Returns without waiting for the time-out period to elapse if the receiving process appears to be in a "hung" state.
SMTO_BLOCK	Prevents the calling thread from processing any other requests until the function returns.
SMTO_NORMAL	The calling thread is not prevented from processing other requests while waiting for the function to return.
uTimeout

Specifies the duration, in milliseconds, of the time-out period.

lpdwResult

Specifies the result of the message processing and depends on the message sent.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

InSendMessage, PostMessage, SendDlgItemMessage, SendMessage, SendMessageCallback, SendNotifyMessage


SendNotifyMessage
 SendNotifyMessage  QuickInfo  Overview  Group

The SendNotifyMessage function sends the specified message to a window. If the window was created by the calling thread, SendNotifyMessage calls the window procedure for the window and does not return until the window procedure has processed the message. If the window was created by a different thread, SendNotifyMessage passes the message to the window procedure and returns immediately; it does not wait for the window procedure to finish processing the message.

BOOL SendNotifyMessage(

HWND  hwnd,	// handle of destination window
UINT  uMsg,	// message to send
WPARAM  wParam,	// first message parameter
LPARAM  lParam	// second message parameter
);
Parameters

hwnd

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

uMsg

Specifies the message to be sent.

wParam

Specifies additional message-specific information.

lParam

Specifies additional message-specific information.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

PostMessage, PostThreadMessage, SendMessage


sendto
 sendto  QuickInfo

The Windows Sockets sendto function sends data to a specific destination.

int sendto (

SOCKET s,
const char FAR * buf,
int len,
int flags,
const struct sockaddr FAR * to,
int tolen
);
Parameters

s

A descriptor identifying a socket.

buf

A buffer containing the data to be transmitted.

len

The length of the data in buf.

flags

Specifies the way in which the call is made.

to

An optional pointer to the address of the target socket.

tolen

The size of the address in to.

Return Value

If the function succeeds, sendto returns the total number of characters sent. (Note that this may be less than the number indicated by len.)

If the function fails, a value of SOCKET_ERROR is returned. To get extended error information, call WSAGetLastError.

Error Codes

WSANOTINITIALISED	A successful WSAStartup must occur before using this function.
WSAENETDOWN	The Windows Sockets implementation has detected that the network subsystem has failed.
WSAEACCES	The requested address is a broadcast address, but the appropriate flag was not set.
WSAEINTR	The (blocking) call was canceled using WSACancelBlockingCall.
WSAEINPROGRESS	A blocking Windows Sockets operation is in progress.
WSAEFAULT	The buf or to parameters are not part of the user address space, or the to argument is too small (less than the size of a socket address structure).
WSAENETRESET	The connection must be reset because the Windows Sockets implementation dropped it.
WSAENOBUFS	The Windows Sockets implementation reports a buffer deadlock.
WSAENOTCONN	The socket is not connected (SOCK_STREAM only).
WSAENOTSOCK	The descriptor is not a socket.
WSAEOPNOTSUPP	MSG_OOB was specified, but the socket is not of type SOCK_STREAM.
WSAESHUTDOWN	The socket has been shut down; it is not possible to sendto on a socket after shutdown has been invoked with how set to 1 or 2.
WSAEWOULDBLOCK	The socket is marked as nonblocking and the requested operation would block.
WSAEMSGSIZE	The socket is of type SOCK_DGRAM, and the datagram is larger than the maximum supported by the Windows Sockets implementation.
WSAECONNABORTED	The virtual circuit was aborted due to timeout or other failure.
WSAECONNRESET	The virtual circuit was reset by the remote side.
WSAEADDRNOTAVAIL	The specified address is not available from the local computer.
WSAEAFNOSUPPORT	Addresses in the specified family cannot be used with this socket.
WSAEDESTADDRREQ	A destination address is required.
WSAENETUNREACH	The network can't be reached from this host at this time.
Remarks

The sendto function is used on datagram or stream sockets and is used to write outgoing data on a socket. For datagram sockets, care must be taken not to exceed the maximum IP packet size of the underlying subnets, which is given by the iMaxUdpDg element in the WSAData structure returned by WSAStartup. If the data is too long to pass atomically through the underlying protocol, the error WSAEMSGSIZE is returned, and no data is transmitted.

Note that the successful completion of a sendto does not indicate that the data was successfully delivered.

The sendto function is normally used on a SOCK_DGRAM socket to send a datagram to a specific peer socket identified by the to parameter. On a SOCK_STREAM socket, the to and tolen parameters are ignored; in this case the sendto is equivalent to send.

To send a broadcast (on a SOCK_DGRAM only), the address in the to parameter should be constructed using the special IP address INADDR_BROADCAST (defined in WINSOCK.H) together with the intended port number. It is generally inadvisable for a broadcast datagram to exceed the size at which fragmentation may occur, which implies that the data portion of the datagram (excluding headers) should not exceed 512 bytes.

If no buffer space is available within the transport system to hold the data to be transmitted, sendto will block unless the socket has been placed in a nonblocking I/O mode. On nonblocking SOCK_STREAM sockets, the number of bytes written can be between 1 and the requested length, depending on buffer availability on both the local and foreign hosts. The select call can be used to determine when it is possible to send more data.

The flags parameter can be used to influence the behavior of the function invocation beyond the options specified for the associated socket. That is, the semantics of this function are determined by the socket options and the flags parameter. The latter is constructed by using a bitwise OR operation with any of the following values:

Value	Meaning
MSG_DONTROUTE	Specifies that the data should not be subject to routing. A Windows Sockets supplier may choose to ignore this flag.
MSG_OOB	Send out-of-band data (SOCK_STREAM only).
See Also

recv, recvfrom, socket, select, send, shutdown, WSACancelBlockingCall, WSAStartup,


ServiceMain
 ServiceMain  QuickInfo  Overview  Group

A ServiceMain function is a function that a service process specifies as the entry point function of a particular service. The function can have any application-defined name.

VOID ServiceMain(

DWORD  dwArgc,	// number of arguments
LPTSTR  *lpszArgv	// address of array of argument string pointers
);
Parameters

dwArgc

Specifies the number of arguments in the lpszArgv array.

lpszArgv

Points to an array of pointers that point to null-terminated argument strings. The first argument in the array is the name of the service, and subsequent arguments are any strings passed to the service by the process that called the StartService function to start the service.

Return Value

This function does not return a value.

Remarks

A service process can start one or more services. For each service that it can start, a service process has a SERVICE_TABLE_ENTRY structure that specifies the service name and a pointer to the ServiceMain function for that service.

When the service control manager receives a request to start a service, it starts the service process (if it is not already running). The main thread of the service process calls the StartServiceCtrlDispatcher function with a pointer to an array of SERVICE_TABLE_ENTRY structures. Then the service control manager sends a start request to the service control dispatcher for this service process. The service control dispatcher creates a new thread to execute the ServiceMain function of the service being started.

This function should immediately call the RegisterServiceCtrlHandler function to specify a Handler function to handle control requests. Next, it should call the SetServiceStatus function to send status information to the service control manager. After these calls, the function completes the initialization tasks of the service, and then it waits for the service to terminate.

A ServiceMain function does not return until the service is ready to terminate.

See Also

Handler, RegisterServiceCtrlHandler, SetServiceStatus, SERVICE_TABLE_ENTRY, StartServiceCtrlDispatcher


SetAbortProc
 SetAbortProc  QuickInfo  Overview  Group

The SetAbortProc function sets the application-defined abort function that allows a print job to be canceled during spooling. This function replaces the SETABORTPROC printer escape.

int SetAbortProc(

HDC  hdc,	// handle of device context
ABORTPROC  lpAbortProc	// address of abort function
);
Parameters

hdc

Identifies the device context for the print job.

lpAbortProc

Points to the application-defined abort function. For more information about the callback function, see the AbortProc callback function.

Return Value

If the function succeeds, the return value is greater than zero.

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

See Also

AbortDoc, AbortProc


SetAclInformation
 SetAclInformation  QuickInfo  Overview  Group

The SetAclInformation function sets information about an access-control list (ACL).

BOOL SetAclInformation(

PACL  pAcl,	// address of access-control list
LPVOID  lpvAclInfo,	// address of ACL information
DWORD  cbAclInfo,	// size of ACL information
ACL_INFORMATION_CLASS  aclic	// specifies class of requested info
);
Parameters

pAcl

Points to an ACL structure. The function sets information in this ACL.

lpvAclInfo

Points to a buffer containing the information to be set. For the current version of Windows NT, this must be an ACL_REVISION_INFORMATION structure.

cbAclInfo

Specifies the size, in bytes, of the buffer pointed to by the pAclInfo parameter.

aclic

Specifies an ACL_INFORMATION_CLASS enumerated type that gives the class of information requested.

Currently, this parameter can be AclRevisionInformation. This means that the buffer pointed to by the lpvAclInfo parameter contains an ACL_REVISION_INFORMATION structure.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

ACL, ACL_INFORMATION_CLASS, ACL_REVISION_INFORMATION, GetAclInformation, InitializeAcl, IsValidAcl


SetActiveWindow
 SetActiveWindow  QuickInfo  Overview  Group

The SetActiveWindow function makes the specified top-level window associated with the thread calling this function the active window.

HWND SetActiveWindow(

HWND  hwnd	// handle of window to activate
);
Parameters

hwnd

Identifies the top-level window to be activated.

Return Value

If the function succeeds, the return value is the handle of the window that was previously active.

Remarks

Applications must use the SetActiveWindow function carefully, because the function allows an application to arbitrarily take over the active window and keyboard focus. Usually, Windows takes care of all activation.

If the window identified by the hwnd parameter was created by the calling thread, the active window status of the calling thread is set to hwnd. Otherwise, the active window status of the calling thread is set to NULL.

The SetActiveWindow function activates a window, but it only brings the window to the foreground if the window is owned by the thread making the call to SetActiveWindow.

The SetForegroundWindow window function, on the other hand, activates a window and forces the thread that created the window into the foreground. An application should call SetForegroundWindow if it wants to put itself into the foreground.

See Also

GetActiveWindow, SetForegroundWindow, WM_ACTIVATE


SetArcDirection
 SetArcDirection  QuickInfo  Overview  Group

The SetArcDirection sets the drawing direction to be used for arc and rectangle functions.

int SetArcDirection(

HDC  hdc,	// identifies the device context
int  ArcDirection	// specifies the new arc direction
);
Parameters

hdc

Identifies the device context.

ArcDirection

Specifies the new arc direction. This parameter can be one of the following values:

Value	Meaning
AD_COUNTERCLOCKWISE	Figures drawn counterclockwise.
AD_CLOCKWISE	Figures drawn clockwise.
Return Value

If the function succeeds, the return value specifies the old arc direction.

If the function fails, the return value is zero.

Remarks

The default direction is counterclockwise.

The SetArcDirection function specifies the direction in which the following functions draw:

Arc	ArcTo
Chord	Ellipse
Pie	Rectangle
RoundRect


SetBitmapBits
 SetBitmapBits  QuickInfo  Overview  Group

The SetBitmapBits function sets the bits of color data for a bitmap to the specified values.

The SetBitmapBits function is included only for compatibility with earlier versions of Windows. For Win32-based applications, use the SetDIBits function.

LONG SetBitmapBits(

HBITMAP  hbmp,	// handle of bitmap
DWORD  cBytes,	// number of bytes in bitmap array
CONST VOID  *lpBits	// address of array with bitmap bits
);
Parameters

hbmp

Identifies the bitmap to be set.

cBytes

Specifies the number of bytes pointed to by the lpBits parameter.

lpBits

Points to an array of bytes that contain color data for the specified bitmap.

Return Value

If the function succeeds, the return value is the number of bytes used in setting the bitmap bits.

If the function fails, the return value is zero.

Remarks

The array identified by lpBits must be WORD aligned.

See Also

GetBitmapBits, SetDIBits


SetBitmapDimension
 SetBitmapDimension  Overview  Group

The SetBitmapDimension function has been deleted. Win32-based applications should use the SetBitmapDimensionEx function.


SetBitmapDimensionEx
 SetBitmapDimensionEx  QuickInfo  Overview  Group

The SetBitmapDimensionEx function assigns preferred dimensions to a bitmap. These dimensions can be used by applications; however, they are not used by Windows.

BOOL SetBitmapDimensionEx(

HBITMAP  hBitmap,	// handle of bitmap
int  nWidth,	// bitmap width in .01-mm units
int  nHeight,	// bitmap height in .01-mm units
LPSIZE  lpSize	// address of structure for original dimensions
);
Parameters

hBitmap

Identifies the bitmap.  The bitmap cannot be a DIB section bitmap.

nWidth

Specifies the width, in 0.1-millimeter units, of the bitmap.

nHeight

Specifies the height, in 0.1-millimeter units, of the bitmap.

lpSize

Points to a SIZE structure to receive the previous dimensions of the bitmap. This pointer can be NULL.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

An application can retrieve the dimensions assigned to a bitmap with the SetBitmapDimensionEx function by calling the GetBitmapDimensionEx function.

The bitmap identified by hBitmap cannot be a dib section, which is a bitmap created by the CreateDIBSection function. If the bitmap is a dib section, the SetBitmapDimensionEx function fails.

See Also

CreateDIBSection, GetBitmapDimensionEx, SIZE


SetBkColor
 SetBkColor  QuickInfo  Overview  Group

The SetBkColor function sets the current background color to the specified color value, or to the nearest physical color if the device cannot represent the specified color value.

COLORREF SetBkColor(

HDC  hdc,	// handle of device context
COLORREF  crColor	// background color value
);
Parameters

hdc

Identifies the device context.

crColor

Specifies the new background color.

Return Value

If the function succeeds, the return value specifies the previous background color as a COLORREF value.

If the function fails, the return value is CLR_INVALID.

Remarks

This function fills the gaps between styled lines drawn using a pen created by the CreatePen function; it does not fill the gaps between styled lines drawn using a pen created by the ExtCreatePen function.

If the background mode is OPAQUE, the background color is used to fill gaps between styled lines, gaps between hatched lines in brushes, and character cells. The background color is also used when converting bitmaps from color to monochrome and vice versa.

See Also

CreatePen, GetBkMode, SetBkMode, COLORREF, ExtCreatePen


SetBkMode
 SetBkMode  QuickInfo  Overview  Group

The SetBkMode function sets the background mix mode of the specified device context. The background mix mode is used with text, hatched brushes, and pen styles that are not solid lines.

int SetBkMode(

HDC  hdc,	// handle of device context
int  iBkMode	// flag specifying background mode
);
Parameters

hdc

Identifies the device context.

iBkMode

Specifies the background mode. This parameter can be either of the following values:

Value	Description
OPAQUE	Background is filled with the current background color before the text, hatched brush, or pen is drawn.
TRANSPARENT	Background remains untouched.
Return Value

If the function succeeds, the return value specifies the previous background mode.

If the function fails, the return value is zero.

Remarks

The SetBkMode function affects the line styles for lines drawn using a pen created by the CreatePen function. SetBkMode does not affect lines drawn using a pen created by the ExtCreatePen function.

The iBkMode parameter can also be set to driver-specific values. GDI passes such values to the device driver and otherwise ignores them.

See Also

CreatePen, ExtCreatePen, GetBkMode


SetBoundsRect
 SetBoundsRect  QuickInfo  Overview  Group

The SetBoundsRect function controls the accumulation of bounding rectangle information for the specified device context. Windows can maintain a bounding rectangle for all drawing operations. An application can examine and set this rectangle. The drawing boundaries are useful for invalidating bitmap caches.

UINT SetBoundsRect(

HDC  hdc,	// handle of device context
CONST RECT  *lprcBounds,	// address of rectangle coordinates
UINT  flags	// controls rectangle combination
);
Parameters

hdc

Identifies the device context for which to accumulate bounding rectangles.

lprcBounds

Points to a RECT structure used to set the bounding rectangle. Rectangle dimensions are in logical coordinates. This parameter can be NULL.

flags

Specifies how the new rectangle will be combined with the accumulated rectangle. This parameter can be a combination of the following values:

Value	Description
DCB_ACCUMULATE	Adds the rectangle specified by the lprcBounds parameter to the bounding rectangle (using a rectangle union operation). Using both DCB_RESET and DCB_ACCUMULATE sets the bounding rectangle to the rectangle specified by the lprcBounds parameter.
DCB_DISABLE	Turns off boundary accumulation.
DCB_ENABLE	Turns on boundary accumulation, which is disabled by default.
DCB_RESET	Clears the bounding rectangle.
Return Value

If the function succeeds, the return value specifies the previous state of the bounding rectangle. This state can be a combination of the following values:

Value	Meaning
DCB_DISABLE	Boundary accumulation is off.
DCB_ENABLE	Boundary accumulation is on. DCB_ENABLE and DCB_DISABLE are mutually exclusive.
DCB_RESET	Bounding rectangle is empty.
DCB_SET	Bounding rectangle is not empty. DCB_SET and DCB_RESET are mutually exclusive.
Remarks

The DCB_SET value is a combination of the bit values DCB_ACCUMULATE and DCB_RESET. Applications that check the DCB_RESET bit to determine whether the bounding rectangle is empty must also check the DCB_ACCUMULATE bit. The bounding rectangle is empty only if the DCB_RESET bit is 1 and the DCB_ACCUMULATE bit is 0.

See Also

GetBoundsRect, RECT


 SetBrushOrg

The SetBrushOrg function is not implemented in the Win32 API. Win32-based applications should use the SetBrushOrgEx function.


SetBrushOrgEx
 SetBrushOrgEx  QuickInfo  Overview  Group

The SetBrushOrgEx function sets the brush origin that GDI assigns to the next brush an application selects into the specified device context. The function supersedes the SetBrushOrg function.

BOOL SetBrushOrgEx(

HDC  hdc,	// handle of device context
int  nXOrg,	// x-coordinate of new origin
int  nYOrg,	// y-coordinate of new origin
LPPOINT  lppt	// points to previous brush origin
);
Parameters

hdc

Identifies the device context.

nXOrg

Specifies the x-coordinate, in device units, of the new brush origin. This value must be in the range 0 through 7.

nYOrg

Specifies the y-coordinate, in device units, of the new brush origin. This value must be in the range 0 through 7.

lppt

Points to a POINT structure that receives the previous brush origin.

This parameter can be NULL if the previous brush origin is not required.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

A brush is a bitmap that the operating system uses to paint the interiors of filled shapes.

The brush origin is a pair of coordinates with values between 0 and 7, specifying the location of one pixel in the bitmap. The default brush origin coordinates are (0,0). For horizontal coordinates, the value 0 corresponds to the leftmost column of pixels; the value 7 corresponds to the rightmost column. For vertical coordinates, the value 0 corresponds to the uppermost row of pixels; the value 7 corresponds to the lowermost row.

When the operating system positions the brush at the start of any painting operation, it maps the origin of the brush to the location on the window's client area specified by the brush origin. For example, if the brush origin is (2,3), the operating system maps the origin of the brush, (0,0), to the location (2,3) on the window's client area.

The operating system automatically tracks the origin of all window-managed device contexts and adjusts their brushes as necessary to maintain an alignment of patterns on the surface. The brush origin that is set with this call is relative to the upper-left corner of the client area.

An application should call SetBrushOrgEx after setting the bitmap stretching mode to HALFTONE via SetStretchBltMode. This must be done to avoid brush misalignment.

Windows NT: The operating system automatically tracks the origin of all window-managed device contexts and adjusts their brushes as necessary to maintain an alignment of patterns on the surface.

Windows 95: Automatic tracking of the brush origin is not supported. Applications must use the UnrealizeObject, SetBrushOrgEx, and SelectObject functions to align the brush before using it.

See Also

GetBrushOrgEx, POINT, SelectObject, SetStretchBltMode, UnrealizeObject


SetCapture
 SetCapture  QuickInfo  Overview  Group

The SetCapture function sets the mouse capture to the specified window belonging to the current thread. Once a window has captured the mouse, all mouse input is directed to that window, regardless of whether the cursor is within the borders of that window. Only one window at a time can capture the mouse.

If the mouse cursor is over a window created by another thread, the system will direct mouse input to the specified window only if a mouse button is down.

HWND SetCapture(

HWND  hwnd	// handle of window to receive mouse capture
);
Parameters

hwnd

Identifies the window in the current thread that is to capture the mouse.

Return Value

If the function succeeds, the return value is the handle of the window that had previously captured the mouse. If there is no such window, the return value is NULL.

Remarks

Only the foreground window can capture the mouse. When a background window attempts to do so, the window receives messages only for mouse events that occur when the cursor hot spot is within the visible portion of the window. Also, even if the foreground window has captured the mouse, the user can still click another window, bringing it to the foreground.

When the window no longer requires all mouse input, the thread that created the window should call the ReleaseCapture function to release the mouse.

This function cannot be used to capture mouse input meant for another process.

Windows 95 only: Calling this function causes the window that is losing the mouse capture to receive a WM_CAPTURECHANGED message.

See Also

GetCapture, ReleaseCapture


SetCaretBlinkTime
 SetCaretBlinkTime  QuickInfo  Overview  Group

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  wMSeconds	// blink time, in milliseconds
);
Parameters

wMSeconds

Specifies the new blink time, in milliseconds.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The caret is a shared resource; there is only one caret in the system. A window should set the caret blink time only if it owns the caret. The window should restore the previous blink time before losing the keyboard focus or becoming inactive.

See Also

GetCaretBlinkTime


SetCaretPos
 SetCaretPos  QuickInfo  Overview  Group

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  nX,	// horizontal position
int  nY	// vertical position
);
Parameters

nX

Specifies the new x-coordinate of the caret.

nY

Specifies the new y-coordinate of the caret.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

SetCaretPos moves the caret whether or not the caret is hidden.

The caret is a shared resource; there is only one caret in the system. A window can set the caret position only if it owns the caret.

See Also

GetCaretPos, HideCaret, ShowCaret


SetClassLong
 SetClassLong  QuickInfo  Overview  Group

The SetClassLong function replaces the specified 32-bit (long) value at the specified offset into the extra class memory or the WNDCLASS structure for the class to which the specified window belongs.

DWORD SetClassLong(

HWND  hwnd,	// handle of window
int  nIndex,	// index of value to change
LONG  lNewVal	// new value
);
Parameters

hwnd

Identifies the window and, indirectly, the class to which the window belongs.

nIndex

Specifies the 32-bit value to replace. To set a 32-bit value in the extra class memory, specify the positive, zero-based byte offset of the value to be set. Valid values are in the range zero through the number of bytes of extra class memory, minus four; for example, if you specified 12 or more bytes of extra class memory, a value of 8 would be an index to the third 32-bit integer. To set any other value from the WNDCLASS 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 and SetWindowWord.
GCL_HBRBACKGROUND	Replaces the handle of the background brush associated with the class.
GCL_HCURSOR	Replaces the handle of the cursor associated with the class.
GCL_HICON	Replaces the handle of the icon associated with the class.
GCL_HMODULE	Replaces the handle of the module that registered the class.
GCL_MENUNAME	Replaces the address of the menu name string. The string identifies the menu resource associated with the class.
GCL_STYLE	Replaces the window-class style bits.
GCL_WNDPROC	Replaces the address of the window procedure associated with the class.
lNewVal

Specifies the replacement value.

Return Value

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.

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 should not subclass a window created by another process.

Reserve extra class memory by specifying a nonzero value in the cbClsExtra member of the WNDCLASS structure used with the RegisterClass 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.

See Also

GetClassLong, GetClassWord, RegisterClass, SetClassWord, SetWindowLong, SetWindowWord, WindowProc, WNDCLASS


SetClassWord
 SetClassWord  QuickInfo  Overview  Group

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.

WORD SetClassWord(

HWND  hwnd,	// handle of window
int  nIndex,	// index of value to change
WORD  wNewWord	// new value
);
Parameters

hwnd

Identifies the window and, indirectly, the class to which the window belongs.

nIndex

Specifies the zero-based byte offset of the value to be replaced. Valid values are in the range zero through the number of bytes of class memory minus two; for example, if you specified 10 or more bytes of extra class memory, a value of 8 would be an index to the fifth 16-bit integer.

wNewWord

Specifies the replacement value.

Return Value

If the function succeeds, the return value is the previous value of the specified 16-bit integer.

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.

The GCW_ values are obsolete in the Win32 API. You must use the SetClassLong function to set the class values previously set by using the GCW_ values with the SetClassWord function.

See Also

GetClassLong, GetClassWord, RegisterClass, SetClassLong, WNDCLASS


SetClipboardData
 SetClipboardData  QuickInfo  Overview  Group

The SetClipboardData function places data on the clipboard in a specified clipboard format. The window must be the current clipboard owner, and the application must have called the OpenClipboard function. (When responding to the WM_RENDERFORMAT and WM_RENDERALLFORMATS messages, the clipboard owner must not call OpenClipboard before calling SetClipboardData.)

HANDLE SetClipboardData(

UINT  uFormat,	// clipboard format
HANDLE  hData	// data handle
);
Parameters

uFormat

Specifies a clipboard format. This parameter can be a registered format or any of the standard clipboard formats listed in the following Remarks section. For information about registered clipboard formats, see the RegisterClipboardFormat function.

hData

Identifies the data in the specified format. This parameter can be NULL, indicating that the window provides data in the specified clipboard format (renders the format) upon request. If a window delays rendering, it must process the WM_RENDERFORMAT and WM_RENDERALLFORMATS messages.

Once SetClipboardData is called, the system owns the object identified by the hData parameter. The application can read the data, but must not free the handle or leave it locked. If the hData parameter identifies a memory object, the object must have been allocated using the GlobalAlloc function with the GMEM_MOVEABLE and GMEM_DDESHARE flags.

Return Value

If the function succeeds, the return value is the handle of the data.

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

Remarks

The uFormat parameter can identify a registered clipboard format, or it can be one of the following values:

Value	Meaning
CF_BITMAP	A handle to a bitmap (HBITMAP).
CF_DIB	A memory object containing a BITMAPINFO structure followed by the bitmap bits.
CF_DIF	Software Arts' Data Interchange Format.
CF_DSPBITMAP	Bitmap display format associated with a private format. The hData parameter must be a handle of data that can be displayed in bitmap format in lieu of the privately formatted data.
CF_DSPENHMETAFILE	Enhanced metafile display format associated with a private format. The hData parameter must be a handle of data that can be displayed in enhanced metafile format in lieu of the privately formatted data.
CF_DSPMETAFILEPICT	Metafile-picture display format associated with a private format. The hData parameter must be a handle of data that can be displayed in metafile-picture format in lieu of the privately formatted data.
CF_DSPTEXT	Text display format associated with a private format. The hData parameter must be a handle of data that can be displayed in text format in lieu of the privately formatted data.
CF_ENHMETAFILE	A handle of an enhanced metafile (HENHMETAFILE).
CF_GDIOBJFIRST through CF_GDIOBJLAST	Windows 95 only: Range of integer values for application-defined GDI object clipboard formats. Handles associated with clipboard formats in this range are not automatically deleted using the GlobalFree function when the clipboard is emptied. Also, when using values in this range, the hData parameter is not a handle to a GDI object, but is a handle allocated by the GlobalAlloc function with the GMEM_DDESHARE and GMEM_MOVEABLE flags.
CF_HDROP	Windows 95 only: A handle of type HDROP that identifies a list of files. An application can retrieve information about the files by passing the handle to the DragQueryFile functions.
CF_LOCALE	Windows 95 only: The data is a handle to the locale identifier associated with text in the clipboard. When you copy data having the CF_TEXT format to the clipboard, the system automatically sets the CF_LOCALE format to the current input locale. You can use the CF_LOCALE format to associate a different locale with the clipboard text. An application that pastes text from the clipboard can retrieve this format to determine which character set was used to generate the text. Note that the clipboard does not support plain text in multiple character sets. To achieve this, use a fomatted text data type such as RTF instead.
CF_METAFILEPICT	Handle of a metafile picture format as defined by the METAFILEPICT structure. When passing a CF_METAFILEPICT handle by means of dynamic data exchange (DDE), the application responsible for deleting hData should also free the metafile referred to by the CF_METAFILEPICT handle.
CF_OEMTEXT	Text format containing characters in the OEM character set. Each line ends with a carriage return/linefeed (CR-LF) combination. A null character signals the end of the data.
CF_OWNERDISPLAY	Owner-display format. The clipboard owner must display and update the clipboard viewer window, and receive the WM_ASKCBFORMATNAME, WM_HSCROLLCLIPBOARD, WM_PAINTCLIPBOARD, WM_SIZECLIPBOARD, and WM_VSCROLLCLIPBOARD messages. The hData parameter must be NULL.
CF_PALETTE	Handle of a color palette. Whenever an application places data in the clipboard that depends on or assumes a color palette, it should place the palette on the clipboard as well.
	If the clipboard contains data in the CF_PALETTE (logical color palette) format, the application should use the SelectPalette and RealizePalette functions to realize (compare) any other data in the clipboard against that logical palette.
	When displaying clipboard data, Windows clipboard always uses as its current palette any object on the clipboard that is in the CF_PALETTE format.
CF_PENDATA	Data for the pen extensions to the Microsoft Windows for Pen Computing.
CF_PRIVATEFIRST through CF_PRIVATELAST	Range of integer values for private clipboard formats. Handles associated with private clipboard formats are not freed automatically; the clipboard owner must free such handles, typically in response to the WM_DESTROYCLIPBOARD message.
CF_RIFF	Represents audio data more complex than can be represented in a CF_WAVE standard wave format.
CF_SYLK	Microsoft Symbolic Link (SYLK) format.
CF_TEXT	Text format. Each line ends with a carriage return/linefeed (CR-LF) combination. A null character signals the end of the data. Use this format for ANSI text.
CF_WAVE	Represents audio data in one of the standard wave formats, such as 11 kHz or 22 kHz pulse code modulation (PCM).
CF_TIFF	Tagged-image file format.
CF_UNICODETEXT	Windows NT only: Unicode text format. Each line ends with a carriage return/linefeed (CR-LF) combination. A null character signals the end of the data.
The operating system performs implicit data format conversions between certain clipboard formats when an application calls the GetClipboardData function. For example, if the CF_OEMTEXT format is on the clipboard, a window can retrieve data in the CF_TEXT format. The format on the clipboard is converted to the requested format on demand. The following table shows the clipboard data type conversions that are available. Note that some of these automatic type conversions are not available on all platforms.

Clipboard Format	Conversion Format	Platform Support
CF_BITMAP	CF_DIB	Windows 95
CF_DIB	CF_BITMAP	Windows 95
CF_DIB	CF_PALETTE	Windows 95
CF_ENHMETAFILE	CF_METAFILEPICT	Windows 95, Windows NT
CF_METAFILEPICT	CF_ENHMETAFILE	Windows 95, Windows NT
CF_OEMTEXT	CF_TEXT	Windows 95, Windows NT
CF_OEMTEXT	CF_UNICODETEXT	Windows NT
CF_TEXT	CF_OEMTEXT	Windows 95, Windows NT
CF_TEXT	CF_UNICODETEXT	Windows NT
CF_UNICODETEXT	CF_OEMTEXT	Windows NT
CF_UNICODETEXT	CF_TEXT	Windows NT
If the operating system provides an automatic type conversion for a particular clipboard format, there is no advantage to placing the conversion format(s) on the clipboard.

When copying bitmaps, it is best to place only the CF_DIB format on the clipboard. This is because the colors in a device-dependent bitmap (CF_BITMAP) are relative to the system palette, which may change before the bitmap is pasted. If only the CF_DIB format is on the clipboard and a window requests the CF_BITMAP format, the system renders the device-dependent bitmap using the current palette at that time.

If you place the CF_BITMAP format on the clipboard (and not CF_DIB), the system renders the CF_DIB clipboard format as soon as the clipboard is closed. This ensures that the correct palette is used to generate the device-independent bitmap (DIB). Conversions between other clipboard formats occur upon demand.

Windows platforms support two clipboard formats for metafiles: CF_ENHMETAFILE and CF_METAFILEPICT. Specify CF_ENHMETAFILE for enhanced metafiles and CF_METAFILEPICT for Windows metafiles.

See Also

BITMAPINFO, GetClipboardData, GlobalAlloc, GlobalFree, METAFILEPICT, OpenClipboard, RealizePalette, RegisterClipboardFormat, SelectPalette, WM_ASKCBFORMATNAME, WM_DESTROYCLIPBOARD, WM_HSCROLLCLIPBOARD, WM_PAINTCLIPBOARD, WM_RENDERFORMAT, WM_RENDERALLFORMATS, WM_SIZECLIPBOARD, WM_VSCROLLCLIPBOARD


SetClipboardViewer
 SetClipboardViewer  QuickInfo  Overview  Group

The SetClipboardViewer function adds the specified window to the chain of clipboard viewers. Clipboard viewer windows receive a WM_DRAWCLIPBOARD message whenever the content of the clipboard changes.

HWND SetClipboardViewer(

HWND  hwnd	// handle of clipboard viewer window
);
Parameters

hwnd

Identifies the window to be added to the clipboard chain.

Return Value

If the function succeeds, the return value identifies the next window in the clipboard viewer chain. If an error occurs or there are no other windows in the clipboard viewer chain, the return value is NULL. To get extended error information, call GetLastError.

Remarks

The windows that are part of the clipboard viewer chain, called clipboard viewer windows, must process the clipboard messages WM_CHANGECBCHAIN and WM_DRAWCLIPBOARD. Each clipboard viewer window calls the SendMessage function to pass these messages to the next window in the clipboard viewer chain.

A clipboard viewer window must eventually remove itself from the clipboard viewer chain by calling the ChangeClipboardChain function — for example, in response to the WM_DESTROY message.

See Also

ChangeClipboardChain, GetClipboardViewer, SendMessage, WM_CHANGECBCHAIN, WM_DRAWCLIPBOARD


SetColorAdjustment
 SetColorAdjustment  QuickInfo  Overview  Group

The SetColorAdjustment function sets the color adjustment values for a device context using the specified values.

BOOL SetColorAdjustment(

HDC  hdc,	// handle to device context
CONST COLORADJUSTMENT *  lpca	// pointer to COLORADJUSTMENT structure
);
Parameters

hdc

Identifies the device context.

lpca

Points to a COLORADJUSTMENT structure containing the color adjustment values.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The color adjustment values are used to adjust the input color of the source bitmap for calls to the StretchBlt and StretchDIBits functions when HALFTONE mode is set.

See Also

COLORADJUSTMENT, SetStretchBltMode, StretchBlt, StretchDIBits


SetColorSpace [New - Windows 95]
 SetColorSpace  QuickInfo  Overview  Group

[New - Windows 95]

The SetColorSpace function sets the color space for the specified device context, defining the endpoints of the logical RGB space in CIE XYZ space.

BOOL SetColorSpace(

HDC  hdc	// handle to the device context
HCOLORSPACE  hColorSpace	// handle to the logical color space
);
Parameters

hdc

Handle to the device context.

hColorSpace

Handle to the logical color space.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

See Also

RGB


SetCommBreak
 SetCommBreak  QuickInfo  Overview  Group

The SetCommBreak function suspends character transmission for a specified communications device and places the transmission line in a break state until the ClearCommBreak function is called.

BOOL SetCommBreak(

HANDLE  hCommDev	// handle of communications device
);
Parameters

hCommDev

Identifies the communications device. The CreateFile function returns this handle.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The SetCommBreak function does not flush data that has not been transmitted.

See Also

ClearCommBreak, CreateFile


SetCommConfig [New - Windows 95]
 SetCommConfig  QuickInfo  Overview  Group

[New - Windows 95]

The SetCommConfig function sets the current configuration of a communications device.

BOOL SetCommConfig(

HANDLE hCommDev,	// handle of communications device
LPBYTE lpCC,	// address of comm. configuration services
DWORD dwSize	// size of structure
);
Parameters

hCommDev

Identifies the open communications device.

lpCC

Points to a COMMCONFIG structure.

dwSize

Specifies the size, in bytes, of the structure pointed to by lpCC.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

COMMCONFIG


SetCommMask
 SetCommMask  QuickInfo  Overview  Group

The SetCommMask function specifies a set of events to be monitored for a communications device.

BOOL SetCommMask(

HANDLE  hCommDev,	// handle of communications device
DWORD  fdwEvtMask	// mask that identifies enabled events
);
Parameters

hCommDev

Identifies the communications device. The CreateFile function returns this handle.

fdwEvtMask

Specifies the events to be enabled. A value of zero disables all events. This parameter can be a combination of the following values:

Value	Meaning
EV_BREAK	A break was detected on input.
EV_CTS	The CTS (clear-to-send) signal changed state.
EV_DSR	The DSR (data-set-ready) signal changed state.
EV_ERR	A line-status error occurred. Line-status errors are CE_FRAME, CE_OVERRUN, and CE_RXPARITY.
EV_RING	A ring indicator was detected.
EV_RLSD	The RLSD (receive-line-signal-detect) signal changed state.
EV_RXCHAR	A character was received and placed in the input buffer.
EV_RXFLAG	The event character was received and placed in the input buffer. The event character is specified in the device's DCB structure, which is applied to a serial port by using the SetCommState function.
EV_TXEMPTY	The last character in the output buffer was sent.
Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The SetCommMask function specifies the set of events that can be monitored for a particular communications resource. A handle to the communications resource can be specified in a call to the WaitCommEvent function, which waits for one of the events to occur. To get the current event mask of a communications resource, use the GetCommMask function.

If SetCommMask is called for a communications resource while an overlapped wait is pending for that resource, WaitCommEvent returns an error.

See Also

CreateFile, DCB, GetCommMask, SetCommState, WaitCommEvent


SetCommState
 SetCommState  QuickInfo  Overview  Group

The SetCommState function configures a communications device according to the specifications in a device-control block (a DCB structure). The function reinitializes all hardware and control settings, but it does not empty output or input queues.

BOOL SetCommState(

HANDLE  hCommDev,	// handle of communications device
LPDCB  lpdcb	// address of device-control block structure
);
Parameters

hCommDev

Identifies the communications device. The CreateFile function returns this handle.

lpdcb

Points to a DCB structure containing the configuration information for the specified communications device.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The SetCommState function uses a DCB structure to specify the desired configuration. The GetCommState function returns the current configuration.

To set only a few members of the DCB structure, you should modify a DCB structure that has been filled in by a call to GetCommState. This ensures that the other members of the DCB structure have appropriate values.

The SetCommState function fails if the XonChar member of the DCB structure is equal to the XoffChar member.

When SetCommState is used to configure the 8250, the following restrictions apply to the values for the DCB structure's ByteSize and StopBits members:

•	The number of data bits must be 5 to 8 bits.

•	The use of 5 data bits with 2 stop bits is an invalid combination, as are 6, 7, or 8 data bits with 1.5 stop bits.

See Also

BuildCommDCB, CreateFile, DCB, GetCommState


SetCommTimeouts
 SetCommTimeouts  QuickInfo  Overview  Group

The SetCommTimeouts function sets the time-out parameters for all read and write operations on a specified communications device.

BOOL SetCommTimeouts(

HANDLE  hCommDev,	// handle of communications device
LPCOMMTIMEOUTS  lpctmo	// address of communications time-out structure
);
Parameters

hCommDev

Identifies the communications device. The CreateFile function returns this handle.

lpctmo

Points to a COMMTIMEOUTS structure that contains the new time-out values.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

COMMTIMEOUTS, GetCommTimeouts, ReadFile, ReadFileEx, WriteFile, WriteFileEx


SetComputerName
 SetComputerName  QuickInfo  Overview  Group

The SetComputerName function sets the computer name to be used the next time the system is restarted.

BOOL SetComputerName(

LPCTSTR  lpszName	// address of new computer name
);
Parameters

lpszName

Points to a null-terminated character string that specifies the name that will be the computer name the next time the computer is started. The name must not be longer than MAX_COMPUTERNAME_LENGTH characters.

Windows 95: If this string contains one or more characters that are outside the standard character set, those characters are coerced into standard characters.

Windows NT: If this string contains one or more characters that are outside the standard character set, SetComputerName returns ERROR_INVALID_PARAMETER. It does not coerce the characters outside the standard set.

The standard character set includes letters, numbers, and the following symbols: ! @ # $ % ^ & ' ) ( . - _ { } ~ .

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

Applications using this function must have administrator rights.

See Also

GetComputerName


SetConsoleActiveScreenBuffer
 SetConsoleActiveScreenBuffer  QuickInfo  Overview  Group

The SetConsoleActiveScreenBuffer function sets the specified screen buffer to be the currently displayed console screen buffer.

BOOL SetConsoleActiveScreenBuffer(

HANDLE  hConsoleOutput	// handle of console screen buffer
);
Parameters

hConsoleOutput

Identifies a console screen buffer.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

A console can have multiple screen buffers. SetConsoleActiveScreenBuffer determines which one is displayed. You can write to an inactive screen buffer and then use SetConsoleActiveScreenBuffer to display the buffer's contents.

See Also

CreateConsoleScreenBuffer


SetConsoleCP
 SetConsoleCP  QuickInfo  Overview  Group

The SetConsoleCP function sets the input code page used by the console associated with the calling process. A console uses its input code page to translate keyboard input into the corresponding character value.

BOOL SetConsoleCP(

UINT  IDCodePage	// code page to set
);
Parameters

IDCodePage

Specifies the identifier of the code page to set. The identifiers of the code pages available on the local computer are stored in the registry under the following key.

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Nls\CodePage

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

A code page maps 256 character codes to individual characters. Different code pages include different special characters, typically customized for a language or a group of languages.

To determine a console's current input code page, use the GetConsoleCP function. To set and retrieve a console's output code page, use the SetConsoleOutputCP and GetConsoleOutputCP functions.

See Also

GetConsoleCP, GetConsoleOutputCP, SetConsoleOutputCP


SetConsoleCtrlHandler
 SetConsoleCtrlHandler  QuickInfo  Overview  Group

The SetConsoleCtrlHandler function adds or removes an application-defined HandlerRoutine function from the list of handler functions for the calling process. If no handler function is specified, the function sets an inheritable attribute that determines whether the calling process ignores CTRL+C signals.

BOOL SetConsoleCtrlHandler(

PHANDLER_ROUTINE  pHandlerRoutine,	// address of handler function
BOOL  fAdd	// handler to add or remove
);
Parameters

pHandlerRoutine

Points to the application-defined HandlerRoutine function to add or remove. This parameter can be NULL.

fAdd

Specifies whether to add or remove the function pointed to by the pHandlerRoutine parameter from the handler list. If this parameter is TRUE, the handler is added; if it is FALSE, the handler is removed.

If the pHandlerRoutine parameter is NULL, a TRUE value causes the calling process to ignore CTRL+C input, and a FALSE value restores normal processing of CTRL+C input. This attribute of ignoring or processing CTRL+C is inherited by child processes.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

Each console process has its own list of application-defined HandlerRoutine functions that handle CTRL+C and CTRL+BREAK signals. The handler functions also handle signals generated by the system when the user closes the console, logs off, or shuts down the system. Initially, the handler list for each process contains only a default handler function that calls the ExitProcess function. A console process adds or removes additional handler functions by calling the SetConsoleCtrlHandler function, which does not affect the list of handler functions for other processes. When a console process receives any of the control signals, its handler functions are called on a last-registered, first-called basis until one of the handlers returns TRUE. If none of the handlers returns TRUE, the default handler is called.

For console processes, the CTRL+C and CTRL+BREAK key combinations are typically treated as signals (CTRL_C_EVENT and CTRL_C_BREAK_EVENT). When a console window with the keyboard focus receives CTRL+C or CTRL+BREAK, the signal is typically passed to all processes sharing that console.

CTRL+BREAK is always treated as a signal, but typical CTRL+C behavior can be changed in three ways that prevent the handler functions from being called:

•	The SetConsoleMode function can disable the ENABLE_PROCESSED_INPUT mode for a console's input buffer, so CTRL+C is reported as keyboard input rather than as a signal.

•	Calling SetConsoleCtrlHandler with the NULL and TRUE arguments causes the calling process to ignore CTRL+C signals. This attribute is inherited by child processes, but it can be enabled or disabled by any process without affecting existing processes.

•	If a console process is being debugged and CTRL+C signals have not been disabled, the kernel generates a DBG_CONTROL_C exception. This exception is raised only for the benefit of the debugger, and an application should never use an exception handler to deal with it. If the debugger handles the exception, an application will not notice the CTRL+C, with one exception: alertable waits will terminate. If the debugger passes the exception on unhandled, CTRL+C is passed to the console process and treated as a signal, as previously discussed.

A console process can use the GenerateConsoleCtrlEvent function to send a CTRL+C or CTRL+BREAK signal to a console process group.

The system generates CTRL_CLOSE_EVENT, CTRL_LOGOFF_EVENT, and CTRL_SHUTDOWN_EVENT signals when the user closes the console, logs off, or shuts down the system so that the process has an opportunity to clean up before termination. Console functions, or any C run-time functions that call console functions, may not work reliably during processing of any of the three signals mentioned previously. The reason is that some or all of the internal console cleanup routines may have been called before executing the process signal handler.

See Also

ExitProcess, GenerateConsoleCtrlEvent, GetConsoleMode, HandlerRoutine, SetConsoleMode


SetConsoleCursorInfo
 SetConsoleCursorInfo  QuickInfo  Overview  Group

The SetConsoleCursorInfo function sets the size and visibility of the cursor for the specified console screen buffer.

BOOL SetConsoleCursorInfo(

HANDLE  hConsoleOutput,	// handle of console screen buffer
PCONSOLE_CURSOR_INFO  pcci	// address of cursor information
);
Parameters

hConsoleOutput

Identifies a console screen buffer. The handle must have GENERIC_WRITE access.

pcci

Points to a CONSOLE_CURSOR_INFO structure containing the new specifications for the screen buffer's cursor.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

When a screen buffer's cursor is visible, its appearance can vary, ranging from completely filling a character cell to showing up as a horizontal line at the bottom of the cell. The dwSize member of the CONSOLE_CURSOR_INFO structure specifies the percentage of a character cell that is filled by the cursor. If this member is less than 1 or greater than 100, SetConsoleCursorInfo fails.

See Also

CONSOLE_CURSOR_INFO, GetConsoleCursorInfo, SetConsoleCursorPosition


SetConsoleCursorPosition
 SetConsoleCursorPosition  QuickInfo  Overview  Group

The SetConsoleCursorPosition function sets the cursor position in the specified console screen buffer.

BOOL SetConsoleCursorPosition(

HANDLE  hConsoleOutput,	// handle of console screen buffer
COORD  coordCursor	// new cursor position coordinates
);
Parameters

hConsoleOutput

Identifies a console screen buffer. The handle must have GENERIC_WRITE access.

coordCursor

Specifies a COORD structure containing the new cursor position. The coordinates are the column and row of a screen buffer character cell. The coordinates must be within the boundaries of the screen buffer.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The cursor position determines where characters written by the WriteFile or WriteConsole function, or echoed by the ReadFile or ReadConsole function, are displayed. To determine the current position of the cursor, use the GetConsoleScreenBufferInfo function.

If the new cursor position is not within the boundaries of the screen buffer's window, the window origin changes to make the cursor visible.

See Also

GetConsoleCursorInfo, GetConsoleScreenBufferInfo, ReadConsole, ReadFile, SetConsoleCursorInfo, WriteConsole, WriteFile


SetConsoleMode
 SetConsoleMode  QuickInfo  Overview  Group

The SetConsoleMode function sets the input mode of a console's input buffer or the output mode of a console screen buffer.

BOOL SetConsoleMode(

HANDLE  hConsole,	// handle of console input or screen buffer
DWORD  fdwMode	// input or output mode to set
);
Parameters

hConsole

Identifies a console input buffer or a screen buffer. The handle must have GENERIC_WRITE access.

fdwMode

Specifies the input or output mode to set. If the hConsole parameter is an input handle, the mode can be a combination of the following values. When a console is created, all input modes except ENABLE_WINDOW_INPUT are enabled by default.

Value	Meaning
ENABLE_LINE_INPUT	The ReadFile or ReadConsole function returns only when a carriage return character is read. If this mode is disabled, the functions return when one or more characters are available.
ENABLE_ECHO_INPUT	Characters read by the ReadFile or ReadConsole function are written to the active screen buffer as they are read. This mode can be used only if the ENABLE_LINE_INPUT mode is also enabled.
ENABLE_PROCESSED_INPUT	CTRL+C is processed by the system and is not placed in the input buffer. If the input buffer is being read by ReadFile or ReadConsole, other control keys are processed by the system and are not returned in the ReadFile or ReadConsole buffer. If the ENABLE_LINE_INPUT mode is also enabled, backspace, carriage return, and linefeed characters are handled by the system.
ENABLE_WINDOW_INPUT	User interactions that change the size of the console screen buffer are reported in the console's input buffer. Information about these events can be read from the input buffer by applications using the ReadConsoleInput function, but not by those using ReadFile or ReadConsole.
ENABLE_MOUSE_INPUT	If the mouse pointer is within the borders of the console window and the window has the keyboard focus, mouse events generated by mouse movement and button presses are placed in the input buffer. These events are discarded by ReadFile or ReadConsole, even when this mode is enabled.
If the hConsole parameter is a screen buffer handle, the mode can be a combination of the following values. When a screen buffer is created, both output modes are enabled by default.

Value	Meaning
ENABLE_PROCESSED_OUTPUT	Characters written by the WriteFile or WriteConsole function or echoed by the ReadFile or ReadConsole function are examined for ASCII control sequences and the correct action is performed. Backspace, tab, bell, carriage return, and linefeed characters are processed.
ENABLE_WRAP_AT_EOL_OUTPUT	When writing with WriteFile or WriteConsole or echoing with ReadFile or ReadConsole, the cursor moves to the beginning of the next row when it reaches the end of the current row. This causes the rows displayed in the console window to scroll up automatically when the cursor advances beyond the last row in the window. It also causes the contents of the screen buffer to scroll up (discarding the top row of the screen buffer) when the cursor advances beyond the last row in the screen buffer. If this mode is disabled, the last character in the row is overwritten with any subsequent characters.
Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

A console consists of an input buffer and one or more screen buffers. The mode of a console buffer determines how the console behaves during input and output (I/O) operations. One set of flag constants is used with input handles, and another set is used with screen buffer (output) handles. Setting the output modes of one screen buffer does not affect the output modes of other screen buffers.

The ENABLE_LINE_INPUT and ENABLE_ECHO_INPUT modes only affect processes that use ReadFile or ReadConsole to read from the console's input buffer. Similarly, the ENABLE_PROCESSED_INPUT mode primarily affects ReadFile and ReadConsole users, except that it also determines whether CTRL+C input is reported in the input buffer (to be read by the ReadConsoleInput function) or is passed to a HandlerRoutine function defined by the application.

The ENABLE_WINDOW_INPUT and ENABLE_MOUSE_INPUT modes determine whether user interactions involving window resizing and mouse actions are reported in the input buffer or discarded. These events can be read by ReadConsoleInput, but they are always filtered by ReadFile and ReadConsole.

The ENABLE_PROCESSED_OUTPUT and ENABLE_WRAP_AT_EOL_OUTPUT modes only affect processes using ReadFile or ReadConsole and WriteFile or WriteConsole.

To determine the current mode of a console input buffer or a screen buffer, use the GetConsoleMode function.

See Also

GetConsoleMode, HandlerRoutine, ReadConsole, ReadConsoleInput, ReadFile, WriteConsole, WriteFile


SetConsoleOutputCP
 SetConsoleOutputCP  QuickInfo  Overview  Group

The SetConsoleOutputCP function sets the output code page used by the console associated with the calling process. A console uses its output code page to translate the character values written by the various output functions into the images displayed in the console window.

BOOL SetConsoleOutputCP(

UINT  IDCodePage	// code page to set
);
Parameters

IDCodePage

Specifies the identifier of the code page to set. The identifiers of the code pages available on the local computer are stored in the registry under the following key.

   HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Nls\CodePage

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

A code page maps 256 character codes to individual characters. Different code pages include different special characters, typically customized for a language or a group of languages.

To determine a console's current output code page, use the GetConsoleOutputCP function. To set and retrieve a console's input code page, use the SetConsoleCP and GetConsoleCP functions.

See Also

GetConsoleCP, GetConsoleOutputCP, SetConsoleCP


SetConsoleScreenBufferSize
 SetConsoleScreenBufferSize  QuickInfo  Overview  Group

The SetConsoleScreenBufferSize function changes the size of the specified console screen buffer.

BOOL SetConsoleScreenBufferSize(

HANDLE  hConsoleOutput,	// handle of console screen buffer
COORD  coordSize	// new size in character rows and cols.
);
Parameters

hConsoleOutput

Identifies a console screen buffer. The handle must have GENERIC_WRITE access.

coordSize

Specifies a COORD structure containing the new size, in rows and columns, of the screen buffer. The specified width and height cannot be less than the width and height of the screen buffer's window. The specified dimensions also cannot be less than the minimum size allowed by the system. This minimum depends on the current font size for the console (selected by the user) and the SM_CXMIN and SM_CYMIN values returned by the GetSystemMetrics function.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

COORD, GetConsoleScreenBufferInfo, SetConsoleWindowInfo


SetConsoleTextAttribute
 SetConsoleTextAttribute  QuickInfo  Overview  Group

The SetConsoleTextAttribute function sets the foreground (text) and background color attributes of characters written to the screen buffer by the WriteFile or WriteConsole function, or echoed by the ReadFile or ReadConsole function. This function affects only text written after the function call.

BOOL SetConsoleTextAttribute(

HANDLE  hConsoleOutput,	// handle of console screen buffer
WORD  wAttr	// text and background colors
);
Parameters

hConsoleOutput

Identifies a console screen buffer. The handle must have GENERIC_READ access.

wAttr

Specifies the foreground and background color attributes. Any combination of the following values can be specified: FOREGROUND_BLUE, FOREGROUND_GREEN, FOREGROUND_RED, FOREGROUND_INTENSITY, BACKGROUND_BLUE, BACKGROUND_GREEN, BACKGROUND_RED, and BACKGROUND_INTENSITY. For example, the following combination of values produces white text on a black background:

FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

To determine the current color attributes of a screen buffer, call the GetConsoleScreenBufferInfo function.

See Also

GetConsoleScreenBufferInfo, ReadConsole, ReadFile, WriteConsole, WriteFile


SetConsoleTitle
 SetConsoleTitle  QuickInfo  Overview  Group

The SetConsoleTitle function sets the title bar string for the current console window.

BOOL SetConsoleTitle(

LPTSTR  lpszTitle	// address of new title
);
Parameters

lpszTitle

Points to a null-terminated string that contains the string to appear in the title bar of the console window.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

GetConsoleTitle


SetConsoleWindowInfo
 SetConsoleWindowInfo  QuickInfo  Overview  Group

The SetConsoleWindowInfo function sets the current size and position of a console screen buffer's window.

BOOL SetConsoleWindowInfo(

HANDLE  hConsoleOutput,	// handle of console screen buffer
BOOL  fAbsolute,	// coordinate type flag
PSMALL_RECT  psrctWindowRect	// address of new window rectangle
);
Parameters

hConsoleOutput

Identifies a console screen buffer. The handle must have GENERIC_WRITE access.

fAbsolute

Specifies how the coordinates in the structure pointed to by the psrctWindowRect parameter are used. If fAbsolute is TRUE, the coordinates specify the new upper-left and lower-right corners of the window. If it is FALSE, the coordinates are offsets to the current window-corner coordinates.

psrctWindowRect

Points to a SMALL_RECT structure that contains values that determine the new upper-left and lower-right corners of the window.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The function fails if the specified window rectangle extends beyond the boundaries of the screen buffer. This means that the Top and Left members of the psrctWindowRect rectangle (or the calculated top and left coordinates, if fAbsolute is FALSE) cannot be less than zero. Similarly, the Bottom and Right members (or the calculated bottom and right coordinates) cannot be greater than (screen buffer height − 1) and (screen buffer width − 1), respectively. The function also fails if the Right member (or calculated right coordinate) is less than or equal to the Left member (or calculated left coordinate) or if the Bottom member (or calculated bottom coordinate) is less than or equal to the Top member (or calculated top coordinate).

For consoles with more than one screen buffer, changing the window location for one screen buffer does not affect the window locations of the other screen buffers.

To determine the current size and position of a screen buffer's window, use the GetConsoleScreenBufferInfo function. This function also returns the maximum size of the window, given the current screen buffer size, the current font size, and the screen size. The GetLargestConsoleWindowSize function returns the maximum window size given the current font and screen sizes, but it does not consider the size of the screen buffer.

SetConsoleWindowInfo can be used to scroll the contents of the screen buffer by shifting the position of the window rectangle without changing its size.

See Also

GetConsoleScreenBufferInfo, GetLargestConsoleWindowSize, SMALL_RECT, ScrollConsoleScreenBuffer


SetCurrentDirectory
 SetCurrentDirectory  QuickInfo  Overview  Group

The SetCurrentDirectory function changes the current directory for the current process.

BOOL SetCurrentDirectory(

LPCTSTR  lpszCurDir	// address of name of new current directory
);
Parameters

lpszCurDir

Points to a null-terminated string that specifies the path to the new current directory. This parameter may be a relative path or a fully qualified path. In either case, the fully qualified path of the specified directory is calculated and stored as the current directory.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

Each process has a single current directory made up of two parts:

•	A disk designator that is either a drive letter followed by a colon, or a server name and share name (\\servername\sharename)

•	A directory on the disk designator

See Also

GetCurrentDirectory


SetCursor
 SetCursor  QuickInfo  Overview  Group

The SetCursor function establishes the cursor shape.

HCURSOR SetCursor(

HCURSOR  hcur	// handle of cursor
);
Parameters

hcur

Identifies the cursor. The cursor must have been created by the CreateCursor or loaded by one of the following functions:

Windows 95: LoadCursor function or LoadImage

Windows NT: LoadCursor

If this parameter is NULL, the cursor is removed from the screen.

Return Value

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

See Also

CreateCursor, LoadCursor, LoadImage, SetCursorPos, ShowCursor


SetCursorPos
 SetCursorPos  QuickInfo  Overview  Group

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, Windows automatically adjusts the coordinates so that the cursor stays within the rectangle.

BOOL SetCursorPos(

int  X,	// horizontal position
int  Y	// vertical position
);
Parameters

X

Specifies the new x-coordinate, in screen coordinates, of the cursor.

Y

Specifies the new y-coordinate, in screen coordinates, of the cursor.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. 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.

See Also

ClipCursor, GetCursorPos, SetCaretPos, SetCursor, ShowCursor


SetDebugErrorLevel
 SetDebugErrorLevel  QuickInfo  Overview  Group

The SetDebugErrorLevel function sets the minimum error level at which Windows will generate debugging events and pass them to a debugger.

VOID SetDebugErrorLevel(

DWORD  dwLevel	// debugging error level
);
Parameters

dwLevel

Specifies the minimum error level for debugging events. If an error is equal to or above this level, Windows generates a debugging event. This parameter must be one of the following values:

Value	Meaning
0	Does not report any errors. This value is the default error level.
SLE_ERROR	Reports only ERROR level debugging events.
SLE_MINORERROR	Reports only MINORERROR level and ERROR level debugging events.
SLE_WARNING	Reports WARNING level, MINORERROR level, and ERROR level debugging events.
Return Value

This function does not return a value.

Remarks

The debugger calls SetDebugErrorLevel to specify the types of errors that it should be notified about.

If the debugging error level is greater than the error that occurred, the value for the GetLastError function is set, but the kernel does not generate a debugging event.


SetDefaultCommConfig [New - Windows 95]
 SetDefaultCommConfig  QuickInfo

[New - Windows 95]

The SetDefaultCommConfig function sets the default configuration for a communications device.

BOOL SetDefaultCommConfig(

LPCSTR lpszName,	//
LPCOMMCONFIG lpCC,	//
DWORD dwSize	//
);
Parameters

lpszName

Points to a null-terminated string specifying the name of the device.

lpCC

Points to a COMMCONFIG structure. If this parameter is NULL, the default configuration is set to the device driver's defaults.

dwSize

Specifies the size, in bytes, of the structure pointed to by lpCC.

Return value

If the function succeeds, the return value is TRUE.

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

See Also

COMMCONFIG


SetDeviceGammaRamp [New - Windows 95]
 SetDeviceGammaRamp  QuickInfo  Overview  Group

[New - Windows 95]

The SetDeviceGammaRamp function sets the gamma ramp on direct color display boards.

BOOL SetDeviceGammaRamp(

HDC  hdc,
LPVOID  lpRamp
);
Parameters

hdc

Handle to the device context.

lpRamp

Pointer to a set of three arrays of 256-byte elements. These arrays are the mapping between color values in the frame buffer and DAC values. The first array is red, the next is green, and the final one is blue.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

Direct color display modes do not use color look-up tables. The direct color modes are usually 16-, 24-, or 32-bit. Not all direct color video boards support loadable gamma ramps. This function succeeds only for those drivers that support loadable gamma ramps in hardware.


SetDIBColorTable
 SetDIBColorTable  QuickInfo  Overview  Group

The SetDIBColorTable function sets RGB (red, green, blue) color values in a range of entries in the color table of the device-independent bitmap (DIB) that is currently selected into a specified device context.

UINT SetDIBColorTable(

HDC hdc,	// handle of device context whose DIB is of interest
UINT uStartIndex,	// color table index of first entry to set
UINT cEntries,	// number of color table entries to set
RGBQUAD *pColors	// pointer to array of color table entries
);
Parameters

hdc

Specifies a device context. A device-independent bitmap must be selected into this device context.

uStartIndex

A zero-based color table index that specifies the first color table entry to set.

cEntries

Specifies the number of color table entries to set.

pColors

Points to an array of RGBQUAD structures containing new color information for the DIB's color table.

Return Value

If the function succeeds, the return value is the number of color table entries that the function sets.

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

Remarks

This function should be called to set the color table for device-independent bitmaps that use 1, 4, or 8 bits per pixel. The biBitCount member of a bitmap's associated BITMAPINFOHEADER structure specifies the number of bits per pixel. Device-independent bitmaps with a biBitCount value greater than 8 do not have a color table.

See Also

BITMAPINFOHEADER, CreateDIBSection, GetDIBColorTable, GetObject, DIBSECTION, RGBQUAD


SetDIBits
 SetDIBits  QuickInfo  Overview  Group

The SetDIBits function sets the pixels in a bitmap using the color data found in the specified device-independent bitmap (DIB).

int SetDIBits(

HDC  hdc,	// handle of device context
HBITMAP  hbmp,	// handle of bitmap
UINT  uStartScan,	// starting scan line
UINT  cScanLines,	// number of scan lines
CONST VOID *  lpvBits,	// array of bitmap bits
CONST BITMAPINFO *  lpbmi,	// address of structure with bitmap data
UINT  fuColorUse	// type of color indices to use
);
Parameters

hdc

Identifies a device context.

hbmp

Identifies the bitmap that is to be altered using the color data from the specified DIB.

uStartScan

Specifies the starting scan line for the device-independent color data in the array pointed to by the lpvBits parameter.

cScanLines

Specifies the number of scan lines found in the array containing device-independent color data.

lpvBits

Points to the DIB color data, stored as an array of bytes. The format of the bitmap values depends on the biBitCount member of the BITMAPINFO structure pointed to by the lpbmi parameter.

lpbmi

Points to a BITMAPINFO data structure that contains information about the DIB.

fuColorUse

Specifies whether the bmiColors member of the BITMAPINFO structure was provided and, if so, whether bmiColors contains explicit red, green, blue (RGB) values or palette indices. The fuColorUse parameter must be one of the following values:

Value	Meaning
DIB_PAL_COLORS	The color table consists of an array of 16-bit indices into the logical palette of the device context identified by the hdc parameter.
DIB_RGB_COLORS	The color table is provided and contains literal RGB values.
Return Value

If the function succeeds, the return value is the number of scan lines copied.

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

Remarks

Optimal bitmap drawing speed is obtained when the bitmap bits are indices into the system palette.

Applications can retrieve the system palette colors and indices by calling the GetSystemPaletteEntries function. After the colors and indices are retrieved, the application can create the DIB. For more information, see System Palette.

The device context identified by the hdc parameter is used only if the DIB_PAL_COLORS constant is set for the fuColorUse parameter; otherwise it is ignored.

The bitmap identified by the hbmp parameter must not be selected into a device context when the application calls this function.

The origin for bottom-up DIBs is the lower-left corner of the bitmap; the origin for top-down DIBs is the upper-left corner of the bitmap.

See Also

BITMAPINFO, GetSystemPaletteEntries


SetDIBitsToDevice
 SetDIBitsToDevice  QuickInfo  Overview  Group

The SetDIBitsToDevice function sets the pixels in the specified rectangle on the device that is associated with the destination device context using color data from a device-independent bitmap (DIB).

int SetDIBitsToDevice(

HDC  hdc,	// handle of device context
int  XDest,	// x-coordinate of upper-left corner of dest. rect.
int  YDest,	// y-coordinate of upper-left corner of dest. rect.
DWORD  dwWidth,	// source rectangle width
DWORD  dwHeight,	// source rectangle height
int  XSrc,	// x-coordinate of lower-left corner of source rect.
int  YSrc,	// y-coordinate of lower-left corner of source rect.
UINT  uStartScan,	// first scan line in array
UINT  cScanLines,	// number of scan lines
CONST VOID *  lpvBits,	// address of array with DIB bits
CONST BITMAPINFO *  lpbmi,	// address of structure with bitmap info.
UINT  fuColorUse	// RGB or palette indices
);
Parameters

hdc

Identifies the device context.

XDest

Specifies the x-coordinate, in logical units, of the upper-left corner of the destination rectangle.

YDest

Specifies the y-coordinate, in logical units, of the upper-left corner of the destination rectangle.

dwWidth

Specifies the width, in logical units, of the DIB.

dwHeight

Specifies the height, in logical units, of the DIB.

XSrc

Specifies the x-coordinate, in logical units, of the lower-left corner of the DIB.

YSrc

Specifies the y-coordinate, in logical units, of the lower-left corner of the DIB.

uStartScan

Specifies the starting scan line in the DIB.

cScanLines

Specifies the number of DIB scan lines contained in the array pointed to by the lpvBits parameter.

lpvBits

Points to DIB color data stored as an array of bytes.

lpbmi

Points to a BITMAPINFO structure that contains information about the DIB.

fuColorUse

Specifies whether the bmiColors member of the BITMAPINFO structure contains explicit red, green, blue (RGB) values or indices into a palette. The fuColorUse parameter must be one of the following values:

Value	Meaning
DIB_PAL_COLORS	The color table consists of an array of 16-bit indices into the currently selected logical palette.
DIB_RGB_COLORS	The color table contains literal RGB values.
Return Value

If the function succeeds, the return value is the number of scan lines set.

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

Remarks

Optimal bitmap drawing speed is obtained when the bitmap bits are indices into the system palette.

Applications can retrieve the system palette colors and indices by calling the GetSystemPaletteEntries function. After the colors and indices are retrieved, the application can create the DIB. For more information about the system palette, see Colors.

The origin of a bottom-up DIB is the lower-left corner of the bitmap; the origin of a top-down DIB is the upper-left corner.

To reduce the amount of memory required to set bits from a large device-independent bitmap on a device surface, an application can band the output by repeatedly calling SetDIBitsToDevice, placing a different portion of the bitmap into the lpvBits array each time. The values of the uStartScan and cScanLines parameters identify the portion of the bitmap contained in the lpvBits array.

Windows 95: The SetDIBitsToDevice function returns an error if it is called by a process that is running in the background while a full-screen MS-DOS runs in the foreground.

See Also

BITMAPINFO, GetSystemPaletteEntries, SetDIBits, StretchDIBits


SetDlgItemInt
 SetDlgItemInt  QuickInfo  Overview  Group

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  hwndDlg,	// handle of dialog box
int  idControl,	// identifier of control
UINT  uValue,	// value to set
BOOL  fSigned	// signed or unsigned indicator
);
Parameters

hwndDlg

Identifies the dialog box that contains the control.

idControl

Specifies the control to be changed.

uValue

Specifies the integer value used to generate the item text.

fSigned

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 Value

If the function succeeds, the return value is TRUE.

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

Remarks

To set the new text, this function sends a WM_SETTEXT message to the specified control.

See Also

GetDlgItemInt, SetDlgItemText, WM_SETTEXT


SetDlgItemText
 SetDlgItemText  QuickInfo  Overview  Group

The SetDlgItemText function sets the title or text of a control in a dialog box.

BOOL SetDlgItemText(

HWND  hwndDlg,	// handle of dialog box
int  idControl,	// identifier of control
LPCTSTR  lpsz	// text to set
);
Parameters

hwndDlg

Identifies the dialog box that contains the control.

idControl

Identifies the control with a title or text that is to be set.

lpsz

Points to the null-terminated string that contains the text to be copied to the control.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The SetDlgItemText function sends a WM_SETTEXT message to the specified control.

See Also

GetDlgItemInt, GetDlgItemText, SetDlgItemInt, WM_SETTEXT


SetDoubleClickTime
 SetDoubleClickTime  QuickInfo  Overview  Group

The SetDoubleClickTime function sets the double-click time for the mouse. A double-click is a series of two clicks of a mouse button, the second occurring within a specified time after the first. The double-click time is the maximum number of milliseconds that may occur between the first and second clicks of a double-click.

BOOL SetDoubleClickTime(

UINT  uInterval	// double-click interval
);
Parameters

uInterval

Specifies the number of milliseconds that may occur between the first and second clicks of a double-click. If this parameter is set to zero, Windows uses the default double-click time of 500 milliseconds.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

The SetDoubleClickTime function alters the double-click time for all windows in the system.

See Also

GetDoubleClickTime


SetEndOfFile
 SetEndOfFile  QuickInfo  Overview  Group

The SetEndOfFile function moves the end-of-file (EOF) position for the specified file to the current position of the file pointer.

BOOL SetEndOfFile(

HANDLE  hFile	// handle of file whose EOF is to be set
);
Parameters

hFile

Identifies the file to have its EOF position moved. The file handle must have been created with GENERIC_WRITE access to the file.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

This function can be used to truncate or extend a file. If the file is extended, the contents of the file between the old EOF position and the new position are not defined.

If you called CreateFileMapping to create a file-mapping object for hFile, you must first call UnmapViewOfFile to unmap all views and call CloseHandle to close the file-mapping object before you can call SetEndOfFile.

See Also

CloseHandle, CreateFile, CreateFileMapping, UnmapViewOfFile


SetEnhMetaFileBits
 SetEnhMetaFileBits  QuickInfo  Overview  Group

The SetEnhMetaFileBits function creates a memory-based enhanced-format metafile from the supplied data.

HENHMETAFILE SetEnhMetaFileBits(

UINT  cbBuffer,	// buffer size
CONST BYTE *  lpData	// buffer that contains enhanced metafile data
);
Parameters

cbBuffer

Specifies the size, in bytes, of the data provided.

lpData

Points to a buffer that contains enhanced-metafile data. (It is assumed that the data in the buffer was obtained by calling the GetEnhMetaFileBits function.)

Return Value

If the function succeeds, the return value is a handle of a memory-based enhanced metafile.

If the function fails, the return value is NULL.

Remarks

When the application no longer needs the enhanced-metafile handle, it should delete the handle by calling the DeleteEnhMetaFile function.

The SetEnhMetaFileBits function does not accept metafile data in the Windows format. To import Windows-format metafiles, use the SetWinMetaFileBits function.

See Also

DeleteEnhMetaFile, GetEnhMetaFileBits, SetWinMetaFileBits


SetEnvironmentVariable
 SetEnvironmentVariable  QuickInfo  Overview  Group

The SetEnvironmentVariable function sets the value of an environment variable for the current process.

BOOL SetEnvironmentVariable(

LPCTSTR  lpszName,	// address of environment variable name
LPCTSTR  lpszValue	// address of new value for variable
);
Parameters

lpszName

Points to a null-terminated string that specifies the environment variable whose value is being set. The operating system creates the environment variable if it does not exist and lpszValue is not NULL.

lpszValue

Points to a null-terminated string containing the new value of the specified environment variable. If this parameter is NULL, the variable is deleted from the current process's environment.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

GetEnvironmentVariable


SetErrorMode
 SetErrorMode  QuickInfo  Overview  Group

The SetErrorMode function controls how the operating system handles several types of serious errors. You can specify that the operating system will handle these errors or that the application will receive and handle them.

UINT SetErrorMode(

UINT  fuErrorMode	// set of bit flags that specify error-handling properties
);
Parameters

fuErrorMode

A set of bit flags that specify system error-handling properties. The following error mode bit flag constants are defined; you can set any combination of them:

Value	Action
SEM_FAILCRITICALERRORS	If this flag is set, the operating system does not display the critical-error-handler message box when such an error occurs. Instead, the operating system sends the error to the calling process.
SEM_NOALIGNMENTFAULTEXCEPT	If this flag is set, the operating system automatically fixes memory alignment faults and makes them invisible to the application. It does this for the calling process and any descendant processes.  This flag always affects MIPS processors. It has no effect on x86 processors. If the registry value \CurrentControlSet\Control\Session Manager:EnableAlignmentFaultExceptions is set to REG_DWORD 0x0, this key has no effect on ALPHA processors. That is the system default. If the registry key is set to REG_DWORD 0x1, the SEM_NOALIGNMENTFAULTEXCEPT flag does affect ALPHA processors.
SEM_NOGPFAULTERRORBOX	If this flag is set, the operating system does not display the general-protection-fault message box when such an error occurs. This flag should only be set by debugging applications that handle general protection (GP) faults themselves via an appropriate exception handler.
SEM_NOOPENFILEERRORBOX	If this flag is set, the operating system does not display a message box when it fails to find a a file. Instead, the error is returned to the calling process.
Return Value

The return value is the previous state of the error-mode bit flags.

Remarks

A child process inherits the error mode of its parent process.

The default state for the error mode properties set by this function is OFF.

On some non-x86 processors misaligned memory references cause an alignment fault exception. The SEM_NOALIGNMENTFAULTEXCEPT flag lets you control whether the operating system automatically fixes such alignment faults, or makes them visible to an application.

The SEM_NOALIGNMENTFAULTEXCEPT flag always affects MIPS processors. It never affects x86 processors. It affects ALPHA processors only if the registry key \CurrentControlSet\Control\Session Manager:EnableAlignmentFaultExceptions is set to REG_DWORD 0x1. The default setting for that registry key is REG_DWORD 0x0.

On an x86 platform, an application doesn't need to do anything to have the operating system automatically fix misaligned memory references. The operating system does not make alignment faults visible to an application.

On a MIPS platform, an application must explicitly call SetErrorMode, setting the SEM_NOALIGNMENTFAULTEXCEPT flag, to have the operating system automatically fix alignment faults. The default setting is for the operating system to make alignment faults visible to an application.

On an ALPHA platform, the operating system automatically fixes alignment faults, unless the aforementioned registry key is set to REG_DWORD 0x1. When that registry key is set to REG_DWORD 0x1, the operating system makes alignment faults visible to an application, and an application must then call SetErrorMode to have the operating system automatically fix alignment faults.

Specifying the SEM_NOALIGNMENTFAULTEXCEPT flag on x86 systems is not an error, but implementations of Windows NT are free to silently ignore and not properly preserve the flag. This means that code sequences such as the following are not always valid on x86 systems:

SetErrorMode(SEM_NOALIGNMENTFAULTEXCEPT);

fuOldErrorMode = SetErrorMode(0);

ASSERT(fuOldErrorMode == SEM_NOALIGNMENTFAULTEXCEPT);


SetEvent
 SetEvent  QuickInfo  Overview  Group

The SetEvent function sets the state of the specified event object to signaled.

BOOL SetEvent(

HANDLE  hEvent	// handle of event object
);
Parameters

hEvent

Identifies the event object. The CreateEvent or OpenEvent function returns this handle, which must have EVENT_MODIFY_STATE access.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The state of a manual-reset event object remains signaled until it is set explicitly to the nonsignaled state by the ResetEvent function. Any number of waiting threads, or threads that subsequently begin wait operations for the specified event object, can be released while the object's state is signaled.

The state of an auto-reset event object remains signaled until a single waiting thread is released, at which time the system automatically sets the state to nonsignaled. If no threads are waiting, the event object's state remains signaled.

See Also

CreateEvent, MsgWaitForMultipleObjects, OpenEvent, PulseEvent, ResetEvent, WaitForMultipleObjects, WaitForMultipleObjectsEx, WaitForSingleObject, WaitForSingleObjectEx


SetFileApisToANSI
 SetFileApisToANSI  QuickInfo  Overview  Group

The SetFileApisToANSI function causes a set of Win32 file functions to use the ANSI character set code page. This function is useful for 8-bit console input and output operations.

VOID SetFileApisToANSI (VOID)

Parameters

This function has no parameters.

Return Value

This function has no return value.

Remarks

The SetFileApisToANSI function complements the SetFileApisToOEM function, which causes the same set of Win32 file functions to use the OEM character set code page.

The 8-bit console functions use the OEM code page by default. All other functions use the ANSI code page by default. This means that strings returned by the console functions may not be processed correctly by other functions, and vice versa. For example, if the FindFirstFileA function returns a string that contains certain extended ANSI characters, and the 8-bit console functions are set to use the OEM code page, then the WriteConsoleA function will not display the string properly.

Use the AreFileApisANSI function to determine which code page the set of file functions is currently using. Use the SetConsoleCP and SetConsoleOutputCP functions to set the code page for the 8-bit console functions.

To solve the problem of code page incompatibility, it is best to use Unicode for console applications. Console applications that use Unicode are much more versatile than those that use 8-bit console functions. Barring that solution, a console application can call the SetFileApisToOEM function to cause the set of Win32 file functions to use OEM character set strings rather than ANSI character set strings. Use the SetFileApisToANSI function to set those functions back to the ANSI code page.

SetFileApisToANSI and SetFileApisToOEM affect these Win32 functions:

_lopen	GetDriveType	LoadLibrary
CopyFile	GetFileAttributes	LoadLibraryEx
CreateDirectory	GetFullPathName	MoveFile
CreateFile	GetModuleFileName	MoveFileEx
CreateProcess	GetModuleHandle	OpenFile
DeleteFile	GetSystemDirectory	RemoveDirectory
FindFirstFile	GetTempFileName	SearchPath
FindNextFile	GetTempPath	SetCurrentDirectory
GetCurrentDirectory	GetVolumeInformation	SetFileAttributes
GetDiskFreeSpace	GetWindowsDirectory
When dealing with command lines, a console application should obtain the command line in Unicode form, and then convert it to OEM form using the relevant character-to-OEM functions. Note also that the argv function uses the ANSI character set.

See Also

AreFileApisANSI, FindFirstFileA, SetFileApisToOEM, SetConsoleCP, SetConsoleOutputCP, WriteConsoleA,


SetFileApisToOEM
 SetFileApisToOEM  QuickInfo  Overview  Group

The SetFileApisToOEM function causes a set of Win32 file functions to use the OEM character set code page. This function is useful for 8-bit console input and output operations.

VOID SetFileApisToOEM(VOID)

Parameters

This function has no parameters.

Return Value

This function has no return value.

Remarks

The SetFileApisToOEM function is complemented by the SetFileApisToANSI function, which causes the same set of Win32 file functions to use the ANSI character set code page.

The 8-bit console functions use the OEM code page by default. All other functions use the ANSI code page by default. This means that strings returned by the console functions may not be processed correctly by other functions, and vice versa. For example, if the FindFirstFileA function returns a string that contains certain extended ANSI characters, and the 8-bit console functions are set to use the OEM code page, then the WriteConsoleA function will not display the string properly.

Use the AreFileApisANSI function to determine which code page the set of file functions is currently using. Use the SetConsoleCP and SetConsoleOutputCP functions to set the code page for the 8-bit console functions.

To solve the problem of code page incompatibility, it is best to use Unicode for console applications. Console applications that use Unicode are much more versatile than those that use 8-bit console functions. Barring that solution, a console application can call the SetFileApisToOEM function to cause the set of Win32 file functions to use OEM character set strings rather than ANSI character set strings. Use the SetFileApisToANSI function to set those functions back to the ANSI code page.

SetFileApisToANSI and SetFileApisToOEM affect these Win32 functions:

_lopen	GetDriveType	LoadLibrary
CopyFile	GetFileAttributes	LoadLibraryEx
CreateDirectory	GetFullPathName	MoveFile
CreateFile	GetModuleFileName	MoveFileEx
CreateProcess	GetModuleHandle	OpenFile
DeleteFile	GetSystemDirectory	RemoveDirectory
FindFirstFile	GetTempFileName	SearchPath
FindNextFile	GetTempPath	SetCurrentDirectory
GetCurrentDirectory	GetVolumeInformation	SetFileAttributes
GetDiskFreeSpace	GetWindowsDirectory
When dealing with command lines, a console application should obtain the command line in Unicode form, and then convert it to OEM form using the relevant character-to-OEM functions. Note also that the argv function uses the ANSI character set.

See Also

AreFileApisANSI, FindFirstFileA, SetConsoleCP, SetConsoleCP, SetConsoleOutputCP, SetFileApisToANSI, WriteConsoleA,


SetFileAttributes
 SetFileAttributes  QuickInfo  Overview  Group

The SetFileAttributes function sets a file's attributes.

BOOL SetFileAttributes(

LPCTSTR  lpFileName,	// address of filename
DWORD  dwFileAttributes	// address of attributes to set
);
Parameters

lpFileName

Points to a string that specifies the name of the file whose attributes are to be set.

Windows 95: This string must not exceed MAX_PATH characters.

Windows NT: There is a default string size limit for paths of MAX_PATH characters. This limit is related to how the SetFileAttributes function parses paths. An application can transcend this limit and send in paths longer than MAX_PATH characters by calling the wide (W) version of SetFileAttributes and prepending "\\?\" to the path. The "\\?\" tells the function to turn off path parsing; it lets paths longer than MAX_PATH be used with SetFileAttributesW. This also works with UNC names. The "\\?\" is ignored as part of the path. For example, "\\?\C:\myworld\private" is seen as "C:\myworld\private", and "\\?\UNC\bill_g_1\hotstuff\coolapps" is seen as "\\bill_g_1\hotstuff\coolapps".

dwFileAttributes

Specifies the file attributes to set for the file. This parameter can be a combination of the following values. However, all other values override FILE_ATTRIBUTE_NORMAL.

Value	Meaning
FILE_ATTRIBUTE_ARCHIVE	The file is an archive file. Applications use this value to mark files for backup or removal.
FILE_ATTRIBUTE_NORMAL	The file has no other attributes set. This value is valid only if used alone.
FILE_ATTRIBUTE_HIDDEN	The file is hidden. It is not included in an ordinary directory listing.
FILE_ATTRIBUTE_READONLY	The file is read-only. Applications can read the file but cannot write to it or delete it.
FILE_ATTRIBUTE_SYSTEM	The file is part of the operating system or is used exclusively by it.
FILE_ATTRIBUTE_TEMPORARY	The file is being used for temporary storage. File systems attempt to keep all of the data in memory for quicker access rather than flushing the data back to mass storage. A temporary file should be deleted by the application as soon as it is no longer needed.
Windows 95 only: FILE_ATTRIBUTE_ATOMIC_WRITE	Reserved for future use; do not specify.
Windows 95 only: FILE_ATTRIBUTE_XACTION_WRITE	Reserved for future use; do not specify.
Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

You cannot use the SetFileAttribute function to set a file's compression state. Setting FILE_ATTRIBUTE_COMPRESSED in the dwFileAttributes parameter does nothing. Use the DeviceIoControl function and the FSCTL_SET_COMPRESSION operation to set a file's compression state.

See Also

DeviceIoControl, FSCTL_SET_COMPRESSION, GetFileAttributes


SetFilePointer
 SetFilePointer  QuickInfo  Overview  Group

The SetFilePointer function moves the file pointer of an open file.

DWORD SetFilePointer(

HANDLE  hFile,	// handle of file
LONG  lDistanceToMove,	// number of bytes to move file pointer
PLONG  lpDistanceToMoveHigh,	// address of high-order word of distance to move
DWORD  dwMoveMethod	// how to move
);
Parameters

hFile

Identifies the file whose file pointer is to be moved. The file handle must have been created with GENERIC_READ or GENERIC_WRITE access to the file.

lDistanceToMove

Specifies the number of bytes to move the file pointer. A positive value moves the pointer forward in the file and a negative value moves it backward.

lpDistanceToMoveHigh

Points to the high-order word of the 64-bit distance to move. If the value of this parameter is NULL, SetFilePointer can operate only on files whose maximum size is 2^32 − 2. If this parameter is specified, the maximum file size is 2^64 − 2. This parameter also receives the high-order word of the new value of the file pointer.

dwMoveMethod

Specifies the starting point for the file pointer move. This parameter can be one of the following values:

Value	Meaning
FILE_BEGIN	The starting point is zero or the beginning of the file. If FILE_BEGIN is specified, DistanceToMove is interpreted as an unsigned location for the new file pointer.
FILE_CURRENT	The current value of the file pointer is the starting point.
FILE_END	The current end-of-file position is the starting point.
Return Value

If the SetFilePointer function succeeds, the return value is the low-order doubleword of the new file pointer, and if lpDistanceToMoveHigh is not NULL, the function puts the high-order doubleword of the new file pointer into the LONG pointed to by that parameter.

If the function fails and lpDistanceToMoveHigh is NULL, the return value is 0xFFFFFFFF. To get extended error information, call GetLastError.

If the function fails, and lpDistanceToMoveHigh is non-NULL, the return value is 0xFFFFFFFF and GetLastError will return a value other than NO_ERROR.

Remarks

You cannot use the SetFilePointer function with a handle to a nonseeking device, such as a pipe or a communications device. To determine the file type for hFile, use the GetFileType function.

You should be careful when setting the file pointer in a multithreaded application. For example, an application whose threads share a file handle, update the file pointer, and read from the file must protect this sequence by using a critical section object or mutex object. For more information about these objects, see Using Mutex Objects and Critical Section Objects.

If the hFile file handle was opened with the FILE_FLAG_NO_BUFFERING flag set, an application can move the file pointer only to sector-aligned positions. A sector-aligned position is a position that is a whole number multiple of the volume's sector size. An application can obtain a volume's sector size by calling the GetDiskFreeSpace function. If an application calls SetFilePointer with distance-to-move values that result in a position that is not sector-aligned and a handle that was opened with FILE_FLAG_NO_BUFFERING, the function fails, and GetLastError returns ERROR_INVALID_PARAMETER.

Note that if the return value is 0xFFFFFFFF and if lpDistanceToMoveHigh is non-NULL, an application must call GetLastError to determine whether the function has succeeded or failed. The following sample code illustrates this point:

//

// Case One: calling the function with

//           lpDistanceToMoveHigh == NULL

// try to move hFile's file pointer some distance

dwPointer = SetFilePointer (hFile, lDistance,

                            NULL, FILE_BEGIN) ;

// if we failed ...

if (dwPointer == 0xFFFFFFFF) {

    // obtain the error code

    dwError = GetLastError() ;

    // deal with that failure

    .

    .

    .

    } // end of error handler

//

// Case Two: calling the function with

//           lpDistanceToMoveHigh != NULL

// try to move hFile's file pointer some huge distance

dwPointerLow = SetFilePointer (hFile, lDistanceLow,

                               & lDistanceHigh, FILE_BEGIN) ;

// if we failed ...

if (dwPointerLow == 0xFFFFFFFF

    &&

    (dwError = GetLastError()) != NO_ERROR ){

    // deal with that failure

    .

    .

    .

    } // end of error handler

See Also

GetDiskFreeSpace, GetFileType, ReadFile, ReadFileEx, WriteFile, WriteFileEx


SetFileSecurity
 SetFileSecurity  QuickInfo  Overview  Group

The SetFileSecurity function sets the security of a file or directory object.

BOOL SetFileSecurity(

LPCTSTR  lpszFile,	// address of string for filename
SECURITY_INFORMATION  si,	// type of information to set
PSECURITY_DESCRIPTOR  psd	// address of security descriptor
);
Parameters

lpszFile

Points to a null-terminated string specifying the file or directory for which security is set.

si

Specifies a SECURITY_INFORMATION structure identifying the contents of the security descriptor pointed to by the psd parameter.

psd

Points to a SECURITY_DESCRIPTOR structure.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The SetFileSecurity function is successful only if the following conditions are met:

•	If the object's owner is being set, the calling process must have either WRITE_OWNER permission or be the object's owner.

•	If the object's discretionary access-control list (ACL) is being set, the calling process must have either WRITE_DAC permission or be the object's owner.

•	If the object's system ACL is being set, the SE_SECURITY_NAME privilege must be enabled for the calling process.

See Also

GetFileSecurity, SECURITY_DESCRIPTOR, SECURITY_INFORMATION, SetKernelObjectSecurity, SetPrivateObjectSecurity, SetUserObjectSecurity


SetFileTime
 SetFileTime  QuickInfo  Overview  Group

The SetFileTime function sets the date and time that a file was created, last accessed, or last modified.

BOOL SetFileTime(

HANDLE  hFile,	// identifies the file
CONST FILETIME *  lpftCreation,	// time the file was created
CONST FILETIME *  lpftLastAccess,	// time the file was last accessed
CONST FILETIME *  lpftLastWrite	// time the file was last written
);
Parameters

hFile

Identifies the file for which to set the dates and times. The file handle must have been created with GENERIC_WRITE access to the file.

lpftCreation

Points to a FILETIME structure that contains the date and time the file was created. This parameter can be NULL if the application does not need to set this information.

lpftLastAccess

Points to a FILETIME structure that contains the date and time the file was last accessed. The last access time includes the last time the file was written to, read from, or (in the case of executable files) run. This parameter can be NULL if the application does not need to set this information.

lpftLastWrite

Points to a FILETIME structure that contains the date and time the file was last written to. This parameter can be NULL if the application does not want to set this information.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The FAT, NTFS, and HPFS file systems all support the file creation, last access, and last write time values.

See Also

FILETIME, GetFileSize, GetFileTime, GetFileType


SetFocus
 SetFocus  QuickInfo  Overview  Group

The SetFocus function sets the keyboard focus to the specified window. All subsequent keyboard input is directed to this window. The window, if any, that previously had the keyboard focus loses it.

HWND SetFocus(

HWND  hwnd	// handle of window to receive focus
);
Parameters

hwnd

Identifies the window that will receive the keyboard input. If this parameter is NULL, keystrokes are ignored.

Return Value

If the function succeeds, the return value is the handle of the window that previously had the keyboard focus. If there is no such window or if the hwnd parameter is invalid, the return value is NULL.

Remarks

If the window identified by the hwnd parameter was created by the calling thread, the keyboard-focus status of the calling thread is set to hwnd.

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 (that is, no window has 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.

If an application is not in the foreground, and wants to be in the foreground, it should call the SetForegroundWindow function.

See Also

GetActiveWindow, GetFocus, SetActiveWindow, SetCapture, SetForegroundWindow, WM_KILLFOCUS, WM_SETFOCUS, WM_SYSCHAR, WM_SYSKEYDOWN, WM_SYSKEYUP


SetForegroundWindow
 SetForegroundWindow  QuickInfo  Overview  Group

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.

BOOL SetForegroundWindow(

HWND  hwnd	// handle of window to bring to foreground
);
Parameters

hwnd

Identifies the window that should be activated and brought to the foreground.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The foreground window is the window at the top of the Z order. It is the window that the user is working with. The system assigns a slightly higher priority to the thread that created the foreground window than it does to other threads.

SetForegroundWindow activates a window and forces the thread that created the window into the foreground.

An application should call SetForegroundWindow if it wants to put itself into the foreground. A good example is a debugger when it hits a breakpoint.

Unlike SetForegroundWindow, the SetActiveWindow function activates a window, but it only brings the window to the foreground if the window is owned by the thread making the SetActiveWindow call.

See Also

GetForegroundWindow, SetActiveWindow


SetForm
 SetForm  QuickInfo  Overview  Group

The SetForm function sets the form information for the specified printer.

BOOL SetForm(

HANDLE  hPrinter,	// handle of printer object
LPTSTR  lpszForm,	// address of form name
DWORD  dwLevel,	// structure level
LPBYTE  lpbForm	// address of structure array
);
Parameters

hPrinter

Identifies the printer for which the form information is set.

lpszForm

Points to a null-terminated string that specifies the form name for which the form information is set.

dwLevel

Specifies the version of the structure to which lpbForm points. This value must be 1.

lpbForm

Points to a FORM_INFO_1 structure.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The printer handle hPrinter is obtained by calling the OpenPrinter function.

See Also

FORM_INFO_1, OpenPrinter


SetGraphicsMode
 SetGraphicsMode  QuickInfo  Overview  Group

The SetGraphicsMode function sets the graphics mode for the specified device context.

int SetGraphicsMode(

HDC  hdc,	// handle of the device context
int  iMode	// graphics mode
);
Parameters

hdc

Identifies the device context.

iMode

Specifies the graphics mode. This parameter can be one of the following values:

Value	Meaning
GM_COMPATIBLE	Sets the graphics mode that is compatible with Windows version 3.1. This is the default mode. If this value is specified, the application can only modify the world-to-device transform by calling functions that set window and viewport extents and origins, but not by using SetWorldTransform or ModifyWorldTransform; calls to those functions will fail. Examples of functions that set window and viewport extents and origins are SetViewportExtEx and SetWindowExtEx.
GM_ADVANCED	Windows NT: Sets the advanced graphics mode that allows world transformations. This value must be specified if the application will set or modify the world transformation for the specified device context. In this mode all graphics, including text output, fully comforms to the world-to-device transformation specified in the device context. Windows 95: The GM_ADVANCED value is not supported. However, enhanced metafiles are assumed to be played in GM_ADVANCED mode, and Windows 95 ensures that enhanced metafiles on Windows 95 look the same as they do on Windows NT.
Return Value

If the function succeeds, the return value is the old graphics mode.

If the function fails, the return value is zero.

Remarks

There are three areas in which graphics output differs according to the graphics mode:

1.	Text Output: In the GM_COMPATIBLE mode, TrueType (or vector font) text output behaves much the same way as raster font text output with respect to the world-to-device transform in the DC. The TrueType text is always written from left to right and right side up, even if the rest of the graphics will be flipped in the x or y axis. Only the height of the TrueType (or vector font) text is scaled appropriately. The only way to write nonhorizontal text in the GM_COMPATIBLE mode is to specify nonzero escapement and orientation for the logical font selected in this device context.

In the GM_ADVANCED mode, TrueType (or vector font) text output fully conforms to the world-to-device transform in the device context. The raster fonts only have very limited transformation capabilities (stretching by some integer factors). Graphics device interface (GDI) tries to produce the best output it can with raster fonts for non-trivial transforms.

2.	Rectangle Exclusion: If the default GM_COMPATIBLE graphics mode is set, the system excludes bottom and rightmost edges when it draws rectangles.

The GM_ADVANCED graphics mode is required if applications want to draw rectangles that are bottom-right inclusive.

3.	Arc Drawing: If the default GM_COMPATIBLE graphics mode is set, GDI draws arcs using the current arc direction in the device space. With this convention, arcs do not respect page-to-device transforms that require a flip along the x or y axis.

If the GM_ADVANCED graphics mode is set, GDI always draws arcs in the counterclockwise direction in logical space. This is equivalent to the statement that, in the GM_ADVANCED graphics mode, both arc control points and arcs themselves fully respect the device context's world-to-device transform.

See Also

CreateDC, GetArcDirection, GetDC, GetGraphicsMode, ModifyWorldTransform; SetArcDirection, SetViewportExtent, SetViewportExtEx, SetWindowExtent, SetWindowExtEx, SetWorldTransform


SetHandleCount
 SetHandleCount  QuickInfo  Overview  Group

The SetHandleCount function changes the number of file handles available to a process.

The SetHandleCount function is not necessary under the Windows NT implementation of Win32; in fact, it has no effect when called under Windows NT.

The SetHandleCount function may be necessary under other implementations of Win32, such as Win32s, in order to increase the default number of available file handles. Under Win32s, this default is 20.

UINT SetHandleCount(

UINT  cHandles	// number of file handles needed
);
Parameters

cHandles

Specifies the number of file handles needed by the application. The maximum value is implementation-dependent. Under Win32s, the maximum value is 255.

Return Value

Under Windows NT, this function has no effect, and the return value is simply the value of the cHandles parameter.

Under other implementations of Win32, such as Win32s, the return value specifies the number of file handles actually available to the application. It may be fewer than the number specified by the cHandles parameter.

Remarks

Under Windows NT, the maximum number of files that an application can open is determined by the amount of available non-paged memory pool, because each open file handle consumes part of that resource.


SetHandleInformation [New - Windows NT]
 SetHandleInformation  QuickInfo  Overview  Group

[New - Windows NT]

The SetHandleInformation function sets certain properties of an object handle. The information is specified as a set of bit flags.

BOOL GetHandleInformation (

HANDLE  hObject,	// handle to an object
DWORD  dwMask,	// specifies flags to change
DWORD  dwFlags	// specifies new values for flags
);
Parameters

hObject

Specifies a handle to an object. The SetHandleInformation function sets information associated with this object handle.

dwMask

A mask that specifies the bit flags to be changed. Use the same flag constants shown in the description of dwFlags.

dwFlags

A set of bit flags that specify properties of the object handle. The following flags are defined:

Value	Meaning
HANDLE_FLAG_INHERIT	If this flag is set, a child process created with the bInheritHandles parameter of CreateProcess set to TRUE will inherit the object handle.
HANDLE_FLAG_PROTECT_FROM_CLOSE	If this flag is set, calling the CloseHandle function will not close the object handle.
Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

Note that you must set a change mask bit flag in dwMask in order to set or clear the associated bit flag in dwFlags.

See Also

CreateProcess, CloseHandle, GetHandleInformation


SetICMMode [New - Windows 95]
 SetICMMode  QuickInfo  Overview  Group

[New - Windows 95]

The SetICMMode function enables or disables image color matching for the specified device context.

int SetICMMode(

HDC  hdc,
int  fICM
);
Parameters

hdc

Handle to the device context.

fICM

Set to ICM_ON to turn on image color matching; ICM_OFF to turn it off; and ICM_QUERY to return the current mode.

Return Value

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

If ICM_QUERY is specified, the function returns ICM_ON or ICM_OFF to indicate the current mode.

Remarks

This function fails if an appropriate color profile cannot be found for the device.


SetICMProfile [New - Windows 95]
 SetICMProfile  QuickInfo  Overview  Group

[New - Windows 95]

The SetICMProfile function sets the color profile for the specified device context.

BOOL SetICMProfile(

HDC  hdc,
LPTSTR  lpFileName
);
Parameters

hdc

Handle to the device context.

lpFileName

Pointer to a null-terminated string that names the color profile file.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.


SetJob
 SetJob  QuickInfo  Overview  Group

The SetJob function pauses, resumes, cancels, or restarts a print job on the specified printer. The function can also be used to set print job parameters such as the job priority, the document name, and so forth.

BOOL SetJob(

HANDLE  hPrinter,	// handle of printer object
DWORD  dwJob,	// job-identification value
DWORD  dwLevel,	// structure level
LPBYTE  lpbJob,	// address of job info structures
DWORD  dwCommand	// job-command value
);
Parameters

hPrinter

Identifies the printer.

dwJob

Specifies the print job.

dwLevel

Specifies the version of the structure to which lpbJob points. This value must be 0, 1, or 2.

lpbJob

Points to either a JOB_INFO_1 or JOB_INFO_2 structure. If dwLevel is 0, this pointer must be NULL; if dwLevel is 1, the array contains a JOB_INFO_1 structure and if dwLevel is 2, the array contains a JOB_INFO_2 structure.

dwCommand

Specifies the operation which should be performed. This parameter can be one of the following values:

Value	Meaning
JOB_CONTROL_CANCEL	Deletes a print job.
JOB_CONTROL_PAUSE	Pauses a print job.
JOB_CONTROL_RESTART	Restarts a print job. A job can only be restarted if it was printing.
JOB_CONTROL_RESUME	Resumes a paused print job.
Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The SetJob function can be used to set various job parameters by supplying a pointer to a JOB_INFO_1 or JOB_INFO_2 structure that contains the necessary data.

To remove or delete all the print jobs for a particular printer, call the SetPrinter function and set the PRINTER_CONTROL_PURGE value.

The following members of a JOB_INFO_1 or JOB_INFO_2 structure are ignored on a call to SetJob:

JobId, pPrinterName, pMachineName, pDrivername, Size, Submitted, and Time.

A client must have PRINTER_ACCESS_ADMINISTER access permission to a printer in order to change the order of jobs on the printer.

If an application does not wish to set the job position, it should specify the JOB_POSITION_UNSPECIFIED (0) value for the Position member.

See Also

JOB_INFO_1, JOB_INFO_2, OpenPrinter, SetPrinter


SetKernelObjectSecurity
 SetKernelObjectSecurity  QuickInfo  Overview  Group

The SetKernelObjectSecurity function sets the security of a kernel object. For example, this can be a process, thread, or event.

BOOL SetKernelObjectSecurity(

HANDLE  hObject,	// handle of object
SECURITY_INFORMATION  si,	// type of information to set
PSECURITY_DESCRIPTOR  psd	// address of security descriptor
);
Parameters

hObject

Identifies a kernel object for which security information is set.

si

Specifies a SECURITY_INFORMATION structure identifying the contents of the security descriptor pointed to by the psd parameter.

psd

Points to a SECURITY_DESCRIPTOR structure containing the new security information.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The SetKernelObjectSecurity function is successful only if the following conditions are met:

•	If the object's owner is being set, the calling process must have either WRITE_OWNER permission or be the object's owner.

•	If the object's discretionary access-control list (ACL) is being set, the calling process must have either WRITE_DAC permission or be the object's owner.

•	If the object's system ACL is being set, the SE_SECURITY_NAME privilege must be enabled for the calling process.

See Also

GetKernelObjectSecurity, SECURITY_DESCRIPTOR, SECURITY_INFORMATION, SetFileSecurity, SetPrivateObjectSecurity, SetUserObjectSecurity


SetKeyboardState
 SetKeyboardState  QuickInfo  Overview  Group

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  lpbKeyState	// address of array with virtual-key codes
);
Parameters

lpbKeyState

Points to a 256-byte array that contains keyboard key states.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

Because the SetKeyboardState function alters the input state of the calling thread and not the global input state of the system, an application cannot use SetKeyboardState to set the NUM LOCK, CAPS LOCK, or SCROLL LOCK indicator lights on the keyboard.

See Also

GetAsyncKeyState, GetKeyboardState, GetKeyState, MapVirtualKey


SetLastError
 SetLastError  QuickInfo  Overview  Group

The SetLastError function sets the last-error code for the calling thread.

VOID SetLastError(

DWORD  fdwError	// per-thread error code
);
Parameters

fdwError

Specifies the last-error code for the thread.

Remarks

Error codes are 32-bit values (bit 31 is the most significant bit). Bit 29 is reserved for application-defined error codes; no Win32 API error code has this bit set. If you are defining an error code for your application, set this bit to indicate that the error code has been defined by your application and to ensure that your error code does not conflict with any system-defined error codes.

This function is intended primarily for dynamic-link libraries (DLLs). Calling this function after an error occurs lets the DLL emulate the behavior of a Win32 function.

Most Win32 functions call SetLastError when they fail. Function failure is typically indicated by a return value error code such as FALSE, NULL, 0xFFFFFFFF, or −1. Some functions call SetLastError under conditions of success; those cases are noted in each function's reference page.

Applications can retrieve the value saved by this function by using the GetLastError function. The use of GetLastError is optional; an application can call it to find out the specific reason for a function failure.

The last-error code is kept in thread local storage so that multiple threads do not overwrite each other's values.

See Also

GetLastError, SetLastErrorEx, TlsGetValue


SetLastErrorEx
 SetLastErrorEx  QuickInfo  Overview  Group

The SetLastErrorEx function sets the last-error code. In Windows 95 and in Windows NT, this function is identical to the SetLastError function. The second parameter is not implemented.

VOID SetLastErrorEx(

DWORD  fdwError,	// per-thread error code
DWORD  fdwType	// error type
);
Parameters

fdwError

Specifies the last-error code for the thread.

fdwType

Specifies the error type. If this process is being controlled by a debugging process, the debugger may take action based on the error type. This parameter can have one of the following values:

Value	Meaning
SLE_ERROR	Invalid data was passed to the function, and complete failure has occurred.
SLE_MINORERROR	Invalid data was passed to the function, but the function has recovered.
SLE_WARNING	Potentially invalid data was passed to the function, but the function has recovered.
0	The last-error code is set without reporting anything to the debugger. Specifying this value is equivalent to using the SetLastError function.
Remarks

Error codes are 32-bit values (bit 31 is the most significant bit). Bit 29 is reserved for application-defined error codes; no Win32 API error code has this bit set. If you are defining an error code for your application, set this bit to indicate that the error code has been defined by the application and to ensure that your error code does not conflict with any system-defined error codes.

This function is intended primarily for dynamic-link libraries (DLLs). Calling this function after an error occurs allows the DLL to emulate the behavior of the Win32 API.

Most Win32 functions call SetLastError when they fail. Function failure is typically indicated by a return value error code such as FALSE, NULL, 0xFFFFFFFF, or −1. Some functions call SetLastError under conditions of success; those cases are noted in each function's reference page.

Applications can retrieve the value saved by this function by using the GetLastError function.

The last-error code is kept in thread local storage so that multiple threads do not overwrite each other's values.

See Also

GetLastError, SetLastError


SetLocaleInfo
 SetLocaleInfo  QuickInfo  Overview  Group

The SetLocaleInfo function sets an item of locale information. It does so by making an entry in the process portion of the locale table. This setting only affects the user override portion of the locale settings; it does not set the system defaults.

Only certain types of locale information, or LCTYPE values, can be set by this function. See the following Remarks section for a list of valid LCTYPE values.

The locale information is always passed in as a null-terminated Unicode string in the Unicode (W) version of the function, and as a null-terminated ANSI string in the ANSI (A) version. No integers are allowed by this function; any numeric values must be specified as Unicode or ANSI text. Each LCTYPE has a particular format, as noted in Locale Identifiers.

BOOL SetLocaleInfo(

LCID  Locale,	// locale identifier
LCTYPE  LCType,	// type of information to set
LPCTSTR  lpLCData	// pointer to information to set
);
Parameters

Locale

Specifies the locale whose information the function will set.

LCType

Specifies the type of locale information to be set by the function. Note that only one LCTYPE may be specified per call. Not all LCTYPE values are valid; see the list of valid LCTYPE values in the following Remarks section.

lpLCData

Points to a null-terminated string containing the locale information the function will set. This should be an LPWSTR for the Unicode (W) version of the function, and an LPSTR for the ANSI (A) version. The information must be in the specified LCTYPE's particular format.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To get extended error information, call GetLastError. GetLastError may return one of the following error codes:

ERROR_INVALID_ACCESS

ERROR_INVALID_FLAGS

ERROR_INVALID_PARAMETER

Remarks

The following LCTYPE values are valid for this function:

LOCALE_ICALENDARTYPE	LOCALE_SDATE
LOCALE_ICURRDIGITS	LOCALE_SDECIMAL
LOCALE_ICURRENCY	LOCALE_SGROUPING
LOCALE_IDIGITS	LOCALE_SLIST
LOCALE_IFIRSTDAYOFWEEK	LOCALE_SLONGDATE
LOCALE_IFIRSTWEEKOFYEAR	LOCALE_SMONDECIMALSEP
LOCALE_ILZERO	LOCALE_SMONGROUPING
LOCALE_IMEASURE	LOCALE_SMONTHOUSANDSEP
LOCALE_INEGCURR	LOCALE_SNEGATIVESIGN
LOCALE_INEGNUMBER	LOCALE_SPOSITIVESIGN
LOCALE_ITIME	LOCALE_SSHORTDATE
LOCALE_S1159	LOCALE_STHOUSAND
LOCALE_S2359	LOCALE_STIME
LOCALE_SCURRENCY	LOCALE_STIMEFORMAT
See Also

GetLocaleInfo


SetLocalTime
 SetLocalTime  QuickInfo  Overview  Group

The SetLocalTime function sets the current local time and date.

BOOL SetLocalTime(

CONST SYSTEMTIME *  lpst	// address of local time to set
);
Parameters

lpst

Points to a SYSTEMTIME structure that contains the current local date and time.

The wDayOfWeek member of the SYSTEMTIME structure is ignored.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The application must have system-time privilege (the SE_SYSTEMTIME_NAME privilege) for this function to succeed. This privilege is disabled by default. Use the AdjustTokenPrivileges function to enable this privilege and again to disable it after the time has been set.

For more information about security privileges, see Security.

See Also

AdjustTokenPrivileges, GetLocalTime, GetSystemTime, SetSystemTimeAdjustment, SYSTEMTIME


SetMailslotInfo
 SetMailslotInfo  QuickInfo  Overview  Group

The SetMailslotInfo function sets the time-out value used by the specified mailslot for a read operation.

BOOL SetMailslotInfo(

HANDLE  hMailslot,	// mailslot handle
DWORD  dwReadTimeout	// read time-out
);
Parameters

hMailslot

Identifies a mailslot. The CreateMailslot function must create this handle.

dwReadTimeout

Specifies the amount of time, in milliseconds, a read operation can wait for a message to be written to the mailslot before a time-out occurs. The following values have special meanings:

Value	Meaning
0	Returns immediately if no message is present. (The system does not treat an immediate return as an error.)
MAILSLOT_WAIT_FOREVER	Waits forever for a message.
This time-out value applies to all subsequent read operations and to all inherited mailslot handles.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The initial time-out value used by a mailslot for a read operation is typically set by CreateMailslot when the mailslot is created.

See Also

CreateMailslot, GetMailslotInfo


SetMapMode
 SetMapMode  QuickInfo  Overview  Group

The SetMapMode function sets the mapping mode of the specified device context. The mapping mode defines the unit of measure used to transform page-space units into device-space units, and also defines the orientation of the device's x and y axes.

int SetMapMode(

HDC  hdc,	// handle of device context
int  fnMapMode	// new mapping mode
);
Parameters

hdc

Identifies the device context.

fnMapMode

Specifies the new mapping mode. It can be any one of the following values:

Value	Description
MM_ANISOTROPIC	Logical units are mapped to arbitrary units with arbitrarily scaled axes. Use the SetWindowExtEx and SetViewportExtEx functions to specify the units, orientation, and scaling that you want.
MM_HIENGLISH	Each logical unit is mapped to 0.001 inch. Positive x is to the right; positive y is up.
MM_HIMETRIC	Each logical unit is mapped to 0.01 millimeter. Positive x is to the right; positive y is up.
MM_ISOTROPIC	Logical units are mapped to arbitrary units with equally scaled axes; that is, one unit along the x-axis is equal to one unit along the y-axis. Use the SetWindowExtEx and SetViewportExtEx functions to specify the units and the orientation of the axes that you want. Graphics device interface (GDI) makes adjustments as necessary to ensure the x and y units remain the same size (for example, if you set the window extent, the viewport will be adjusted to keep the units isotropic).
MM_LOENGLISH	Each logical unit is mapped to 0.01 inch. Positive x is to the right; positive y is up.
MM_LOMETRIC	Each logical unit is mapped to 0.1 millimeter. Positive x is to the right; positive y is up.
MM_TEXT	Each logical unit is mapped to one device pixel. Positive x is to the right; positive y is down.
MM_TWIPS	Each logical unit is mapped to one twentieth of a printer's point (1/1440 inch, also called a "twip"). Positive x is to the right; positive y is up.
Return Value

If the function succeeds, the return value identifies the previous mapping mode.

If the function fails, the return value is zero.

Remarks

The MM_TEXT mode allows applications to work in device pixels, whose size varies from device to device.

The MM_HIENGLISH, MM_HIMETRIC, MM_LOENGLISH, MM_LOMETRIC, and MM_TWIPS modes are useful for applications drawing in physically meaningful units (such as inches or millimeters).

The MM_ISOTROPIC mode ensures a 1:1 aspect ratio.

The MM_ANISOTROPIC mode allows the x-coordinates and y-coordinates to be adjusted independently.

See Also

GetMapMode, SetViewportExtEx, SetViewportOrgEx, SetWindowExtEx, SetWindowOrgEx


SetMapperFlags
 SetMapperFlags  QuickInfo  Overview  Group

The SetMapperFlags function alters the algorithm the font mapper uses when it maps logical fonts to physical fonts.

DWORD SetMapperFlags(

HDC  hdc,	// handle of device context
DWORD  dwFlag	// font-mapper flag
);
Parameters

hdc

Identifies the device context that contains the font-mapper flag.

dwFlag

Specifies whether the font mapper should attempt to match a font's aspect ratio to the current device's aspect ratio. If bit zero is set, the mapper selects only matching fonts.

Return Value

If the function succeeds, the return value is the previous value of the font-mapper flag.

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

Remarks

If the dwFlag parameter is set and no matching fonts exist, Windows chooses a new aspect ratio and retrieves a font that matches this ratio.

The remaining bits of the dwFlag parameter must be zero.

See Also

GetAspectRatioFilterEx


SetMenu
 SetMenu  QuickInfo  Overview  Group

The SetMenu function assigns a new menu to the specified window.

BOOL SetMenu(

HWND  hwnd,	// handle of window
HMENU  hmenu	// handle of menu
);
Parameters

hwnd

Identifies the window to which the menu is to be assigned.

hmenu

Identifies the new menu. If this parameter is NULL, the window's current menu is removed.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The window is redrawn to reflect the menu change.

The SetMenu function replaces the previous menu, if any, but it does not destroy it. An application should call the DestroyMenu function to accomplish this task.

See Also

DestroyMenu, GetMenu


SetMenuContextHelpId [New - Windows NT]
 SetMenuContextHelpId  QuickInfo  Overview  Group

[New - Windows NT]

The SetMenuContextHelpId function associates a help context identifier with a menu. All items in the menu share this identifier. It is not possible to attach a help context identifier to the individual menu items.

BOOL SetMenuContextHelpId(

HMENU  hmenu,
DWORD  dwContextHelpId
);
Parameters

hmenu

Handle to the menu with which to associate the help context identifier.

dwContextHelpId

Help context identifier.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.


SetMenuDefaultItem [New - Windows 95]
 SetMenuDefaultItem  QuickInfo  Overview  Group

[New - Windows 95]

The SetMenuDefaultItem function sets the default menu item for the specified menu.

BOOL SetMenuDefaultItem(

HMENU  hMenu,
UINT  uItem,
UINT  fByPos
);
Parameters

hMenu

Handle to the menu to set the default item for.

uItem

Identifier or position of the new default menu item or − 1 for no default item. The meaning of this parameter depends on the value of fByPos.

fByPos

Value specifying the meaning of uItem. If this parameter is FALSE, uItem is a menu item identifier. Otherwise, it is a menu item position.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To get extended error information, use the GetLastError function.


SetMenuItemBitmaps
 SetMenuItemBitmaps  QuickInfo  Overview  Group

The SetMenuItemBitmaps function associates the specified bitmap with a menu item. Whether the menu item is checked or unchecked, Windows displays the appropriate bitmap next to the menu item.

BOOL SetMenuItemBitmaps(

HMENU  hmenu,	// handle of menu
UINT  uItem,	// menu item to receive new bitmaps
UINT  fuFlags,	// menu item flags
HBITMAP  hbmUnchecked,	// handle of unchecked bitmap
HBITMAP  hbmChecked	// handle of checked bitmap
);
Parameters

hmenu

Identifies the menu containing the item to receive new check mark bitmaps.

uItem

Specifies the menu item to be changed, as determined by the fuFlags parameter.

fuFlags

Specifies how the uItem parameter is interpreted. The fuFlags parameter must be one of the following values:

Value	Meaning
MF_BYCOMMAND	Indicates that uItem 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 uItem gives the zero-based relative position of the menu item.
hbmUnchecked

Identifies the bitmap displayed when the menu item is not checked.

hbmChecked

Identifies the bitmap displayed when the menu item is checked.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

If either the hbmUnchecked or hbmChecked parameter is NULL, Windows displays nothing next to the menu item for the corresponding check state. If both parameters are NULL, Windows displays the default check mark bitmap when the item is checked and removes the bitmap when the item is not checked.

When the menu is destroyed, these bitmaps are not destroyed; it is up to the application to destroy them.

Windows NT: The GetMenuCheckMarkDimensions function retrieves the dimensions of the default check mark used for menu items. These values are used to determine the appropriate size for the bitmaps supplied with this function.

Windows 95: GetMenuCheckMarkDimensions is obsolete. Use GetsystemMetrics with the CXMENUCHECK and CYMENUCHECK values to retrieve the bitmap dimensions.

See Also

GetMenu, GetMenuCheckMarkDimensions


SetMenuItemInfo [New - Windows 95]
 SetMenuItemInfo  QuickInfo  Overview  Group

[New - Windows 95]

The SetMenuItemInfo function changes information about a menu item.

BOOL WINAPI SetMenuItemInfo(

HMENU  hMenu,
UINT  uItem,
BOOL  fByPosition,
LPMENUITEMINFO  lpmii
);
Parameters

hMenu

Handle to the menu that contains the menu item.

uItem

Identifier or position of the menu item to change. The meaning of this parameter depends on the value of fByPosition.

fByPosition

Value specifying the meaning of uItem. If this parameter is FALSE, uItem is a menu item identifier. Otherwise, it is a menu item position.

lpmii

Pointer to a MENUITEMINFO structure that contains information about the menu item and specifies which menu item attributes to change.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To get extended error information, use the GetLastError function.

See Also

MENUITEMINFO


SetMessageExtraInfo [New - Windows 95]
 SetMessageExtraInfo  QuickInfo  Overview  Group

[New - Windows 95]

The SetMessageExtraInfo function sets the extra message information for the current thread. Extra message information is an application- or driver-defined 32-bit value associated with the current thread's message queue. An application can use the GetMessageExtraInfo function to retrieve a thread's extra message information.

LPARAM SetMessageExtraInfo(

LPARAM  lParam	// application-defined 32-bit value
);
Parameters

lParam

Specifies the 32-bit value to associate with the current thread.

Return Value

The return value is the previous 32-bit value.

See Also

GetMessageExtraInfo


SetMessageQueue
 SetMessageQueue  QuickInfo  Overview  Group

The SetMessageQueue function creates a new message queue. It is useful in Windows version 3.x applications that require a queue that contains more than eight messages (the maximum size of the default queue). It does nothing running with Win32, because queues are expanded dynamically as necessary.

BOOL SetMessageQueue(

int  cMessagesMax	// size of message queue
);


 SetMetaFileBits

The SetMetaFileBits function is not implemented in the Win32 API. Win32-based applications should use the SetMetaFileBitsEx function.


SetMetaFileBitsEx
 SetMetaFileBitsEx  QuickInfo  Overview  Group

The SetMetaFileBitsEx function creates a memory-based Windows-format metafile from the supplied data.

This function is provided for compatibility with earlier versions of Microsoft Windows. Win32-based applications should use the SetEnhMetaFileBits function.

HMETAFILE SetMetaFileBitsEx(

UINT  nSize,	// size of Windows-format metafile
CONST BYTE *  lpData	// address of buffer containing metafile data
);
Parameters

nSize

Specifies the size, in bytes, of the Windows-format metafile.

lpData

Points to a buffer that contains the Windows-format metafile. (It is assumed that the data was obtained by using the GetMetaFileBitsEx function.)

Return Value

If the function succeeds, the return value is a handle of a memory-based Windows-format metafile.

If the function fails, the return value is NULL.

Remarks

A Windows-format metafile does not support the new curve, path, and transformation functions such as PolyBezier, BeginPath, and SetWorldTransform. Applications that use these new functions and use metafiles to store pictures created by these functions should use the enhanced-format metafile functions.

To convert a Windows-format metafile into an enhanced-format metafile, use the SetWinMetaFileBits function.

When the application no longer needs the metafile handle returned by SetMetaFileBitsEx, it should delete it by calling the DeleteMetaFile function.

See Also

BeginPath, DeleteMetaFile, GetMetaFileBitsEx, PolyBezier, SetEnhMetaFileBits, SetWinMetaFileBits, SetWorldTransform


SetMetaRgn
 SetMetaRgn  QuickInfo  Overview  Group

The SetMetaRgn function intersects the current clipping region for the specified device context with the current metaregion and saves the combined region as the new metaregion for the specified device context. The clipping region is reset to a null region.

int SetMetaRgn(

HDC  hdc	// handle of device context
);
Parameters

hdc

Identifies the device context.

Return Value

If the function succeeds, the return value specifies the new clipping region's complexity and can be any one of the following values:

Value	Meaning
NULLREGION	Region is empty.
SIMPLEREGION	Region is a single rectangle.
COMPLEXREGION	Region is more than one rectangle.
ERROR	An error occurred. (The previous clipping region is unaffected.)
Remarks

The current clipping region of a device context is defined by the intersection of its clipping region and its metaregion.

The SetMetaRgn function should only be called after an application's original device context was saved by calling the SaveDC function.

See Also

GetMetaRgn, SaveDC


SetMiterLimit
 SetMiterLimit  QuickInfo  Overview  Group

The SetMiterLimit function sets the limit for the length of miter joins for the specified device context.

BOOL SetMiterLimit(

HDC  hdc,	// handle of device context
FLOAT  eNewLimit,	// new miter limit
PFLOAT  peOldLimit	// previous miter limit
);
Parameters

hdc

Identifies the device context.

eNewLimit

Specifies the new miter limit for the device context.

peOldLimit

Points to a floating-point value that receives the previous miter limit. If this parameter is NULL, the previous miter limit is not returned.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The miter length is defined as the distance from the intersection of the line walls on the inside of the join to the intersection of the line walls on the outside of the join. The miter limit is the maximum allowed ratio of the miter length to the line width.

The default miter limit is 10.0.

See Also

ExtCreatePen


SetNamedPipeHandleState
 SetNamedPipeHandleState  QuickInfo  Overview  Group

The SetNamedPipeHandleState function sets the read mode and the blocking mode of the specified named pipe. If the specified handle is to the client end of a named pipe and if the named pipe server process is on a remote computer, the function can also be used to control local buffering.

BOOL SetNamedPipeHandleState(

HANDLE  hNamedPipe,	// handle of named pipe
LPDWORD  lpdwMode,	// address of new pipe mode
LPDWORD  lpcbMaxCollect,	// address of max. bytes before remote transmission
LPDWORD  lpdwCollectDataTimeout	// address of max. time before remote transmission
);
Parameters

hNamedPipe

Identifies the named pipe instance. This parameter can be a handle to the server end of the pipe, as returned by the CreateNamedPipe function, or to the client end of the pipe, as returned by the CreateFile function. The handle must have GENERIC_WRITE access to the named pipe.

lpdwMode

Points to a 32-bit variable that supplies the new mode. The mode is a combination of a read-mode flag and a wait-mode flag. This parameter can be NULL if the mode is not being set. One of the following read modes can be specified:

Mode	Description
PIPE_READMODE_BYTE	Data is read from the pipe as a stream of bytes. This mode is the default if no read-mode flag is specified.
PIPE_READMODE_MESSAGE	Data is read from the pipe as a stream of messages. The function fails if this flag is specified for a byte-type pipe.
One of the following wait modes can be specified:

Mode	Description
PIPE_WAIT	Blocking mode is enabled. This mode is the default if no wait-mode flag is specified. When a blocking mode pipe handle is specified in the ReadFile, WriteFile, or ConnectNamedPipe function, operations are not finished until there is data to read, all data is written, or a client is connected. Use of this mode can mean waiting indefinitely in some situations for a client process to perform an action.
PIPE_NOWAIT	Nonblocking mode is enabled. In this mode, ReadFile, WriteFile, and ConnectNamedPipe always return immediately. Note that nonblocking mode is supported for compatibility with Microsoft® LAN Manager version 2.0 and should not be used to achieve asynchronous input and output (I/O) with named pipes.
lpcbMaxCollect

Points to a 32-bit variable that specifies the maximum number of bytes collected on the client computer before transmission to the server. This parameter must be NULL if the specified pipe handle is to the server end of a named pipe or if client and server processes are on the same machine. This parameter is ignored if the client process specifies the FILE_FLAG_WRITE_THROUGH flag in the CreateFile function when the handle was created. This parameter can be NULL if the collection count is not being set.

lpdwCollectDataTimeout

Points to a 32-bit variable that specifies the maximum time, in milliseconds, that can pass before a remote named pipe transfers information over the network. This parameter must be NULL if the specified pipe handle is to the server end of a named pipe or if client and server processes are on the same computer. This parameter is ignored if the client process specified the FILE_FLAG_WRITE_THROUGH flag in the CreateFile function when the handle was created. This parameter can be NULL if the collection count is not being set.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

ConnectNamedPipe, CreateFile, CreateNamedPipe, GetNamedPipeHandleState, ReadFile, WriteFile


SetPaletteEntries
 SetPaletteEntries  QuickInfo  Overview  Group

The SetPaletteEntries function sets RGB (red, green, blue) color values and flags in a range of entries in a logical palette.

UINT SetPaletteEntries(

HPALETTE  hpal,	// handle of logical palette
UINT  iStart,	// index of first entry to set
UINT  cEntries,	// number of entries to set
CONST PALETTEENTRY  *lppe	// address of array of structures
);
Parameters

hpal

Identifies the logical palette.

iStart

Specifies the first logical-palette entry to be set.

cEntries

Specifies the number of logical-palette entries to be set.

lppe

Points to the first member of an array of PALETTEENTRY structures containing the RGB values and flags.

Return Value

If the function succeeds, the return value is the number of entries that were set in the logical palette.

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

Remarks

An application can determine whether or not a device supports palette operations by calling the GetDeviceCaps function and specifying the RASTERCAPS constant.

Even if a logical palette has been selected and realized, changes to the palette do not affect the physical palette in the surface. RealizePalette must be called again to set the new logical palette into the surface.

See Also

GetDeviceCaps, RealizePalette, PALETTEENTRY


SetParent
 SetParent  QuickInfo  Overview  Group

The SetParent function changes the parent window of the specified child window.

HWND SetParent(

HWND  hwndChild,	// handle of window whose parent is changing
HWND  hwndNewParent	// handle of new parent window
);
Parameters

hwndChild

Identifies the child window.

hwndNewParent

Identifies the new parent window. If this parameter is NULL, the desktop window becomes the new parent window.

Return Value

If the function succeeds, the return value is the handle of 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, Windows performs the appropriate redrawing and repainting.

See Also

GetParent


SetPixel
 SetPixel  QuickInfo  Overview  Group

The SetPixel function sets the pixel at the specified coordinates to the specified color.

COLORREF SetPixel(

HDC  hdc,	// handle of device context
int  X,	// x-coordinate of pixel
int  Y,	// y-coordinate of pixel
COLORREF  crColor	// pixel color
);
Parameters

hdc

Identifies the device context.

X

Specifies the x-coordinate, in logical units, of the point to be set.

Y

Specifies the y-coordinate, in logical units, of the point to be set.

crColor

Specifies the color to be used to paint the point.

Return Value

If the function succeeds, the return value is the RGB value that the function sets the pixel to. This value may differ from the color specified by crColor; that happens when an exact match for the specified color cannot be found.

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

Remarks

The function fails if the pixel coordinates lie outside of the current clipping region.

Not all devices support the SetPixel function. For more information, see GetDeviceCaps.

See Also

GetDeviceCaps, SetPixelV


SetPixelV
 SetPixelV  QuickInfo  Overview  Group

The SetPixelV function sets the pixel at the specified coordinates to the closest approximation of the specified color. The point must be in the clipping region and the visible part of the device surface.

BOOL SetPixelV(

HDC  hdc,	// handle of device context
int  X,	// x-coordinate of pixel
int  Y,	// y-coordinate of pixel
COLORREF  crColor	// new pixel color
);
Parameters

hdc

Identifies the device context.

X

Specifies the x-coordinate, in logical units, of the point to be set.

Y

Specifies the y-coordinate, in logical units, of the point to be set.

crColor

Specifies the color to be used to paint the point.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

Not all devices support the SetPixelV function. For more information, see the description of the RC_BITBLT capability in the GetDeviceCaps function.

SetPixelV is faster than SetPixel because it does not need to return the color value of the point actually painted.

See Also

GetDeviceCaps, SetPixel


SetPolyFillMode
 SetPolyFillMode  QuickInfo  Overview  Group

The SetPolyFillMode function sets the polygon fill mode for functions that fill polygons.

int SetPolyFillMode(

HDC  hdc,	// handle of device context
int  iPolyFillMode	// polygon fill mode
);
Parameters

hdc

Identifies the device context.

iPolyFillMode

Specifies the new fill mode. This parameter can be either of the following values:

Value	Meaning
ALTERNATE	Selects alternate mode (fills the area between odd-numbered and even-numbered polygon sides on each scan line).
WINDING	Selects winding mode (fills any region with a nonzero winding value).
Return Value

The return value specifies the previous filling mode. If an error occurs, the return value is zero.

Remarks

In general, the modes differ only in cases where a complex, overlapping polygon must be filled (for example, a five-sided polygon that forms a five-pointed star with a pentagon in the center). In such cases, ALTERNATE mode fills every other enclosed region within the polygon (that is, the points of the star), but WINDING mode fills all regions (that is, the points and the pentagon).

When the fill mode is ALTERNATE, GDI fills the area between odd-numbered and even-numbered polygon sides on each scan line. That is, GDI fills the area between the first and second side, between the third and fourth side, and so on.

When the fill mode is WINDING, GDI fills any region that has a nonzero winding value. This value is defined as the number of times a pen used to draw the polygon would go around the region. The direction of each edge of the polygon is important.

See Also

GetPolyFillMode


SetPrinter
 SetPrinter  QuickInfo  Overview  Group

The SetPrinter function sets the specified printer by pausing printing, resuming printing, or clearing all print jobs. The function can also be used to set printer data.

BOOL SetPrinter(

HANDLE  hPrinter,	// handle of printer object
DWORD  dwLevel,	// structure level
LPBYTE  lpbPrinter,	// address of array containing printer data
DWORD  dwCommand	// printer-state command
);
Parameters

hPrinter

Identifies the printer.

dwLevel

Windows 95: Specifies the type of data contained in lpbPrinter. This parameter must be 0, 2, 3, 4, or 5. This parameter must be zero if dwCommand is not equal to zero.

Windows NT: Specifies the type of data contained in lpbPrinter. This parameter must be 0, 2, or 3. This parameter must be zero if dwCommand is not equal to zero.

lpbPrinter

Windows 95: Contains either a DWORD value indicating the printer status or points to an array of bytes that may contain printer data. If dwLevel is 0, and the dwCommand parameter is PRINTER_CONTROL_STATUS, lpbPrinter must contain a DWORD value that specifies the new printer status to set. For a list of the possible status values, see the Status member of the PRINTER_INFO_2 structure. Note that PRINTER_STATUS_PAUSED and PRINTER_STATUS_PENDING_DELETION are not valid status values to set. Otherwise, when dwLevel is 0, this parameter must be NULL. If dwLevel is 2, 3, 4, or 5, lpbPrinter points to an array that contains PRINTER_INFO_2, PRINTER_INFO_3, PRINTER_INFO_4, or PRINTER_INFO_5 structures, respectively.

Windows NT: Contains either a DWORD value indicating the printer status or points to an array of bytes that may contain printer data. For a list of the possible status values, see the Status member of the PRINTER_INFO_2 structure. Note that PRINTER_STATUS_PAUSED and PRINTER_STATUS_PENDING_DELETION are not valid status values to set. Otherwise, when dwLevel is 0, this parameter must be NULL. If dwLevel is 2 or 3, lpbPrinter points to an array that contains PRINTER_INFO_2 or PRINTER_INFO_3 structures, respectively.

dwCommand

Specifies the new printer state. This parameter can be zero or one of the following values. If it is zero, the printer retains its original state and the printer data is reconfigured by using the structure to which lpbPrinter points.

Value	Meaning
PRINTER_CONTROL_PAUSE	Pauses the printer.
PRINTER_CONTROL_PURGE	Deletes all print jobs in the printer.
PRINTER_CONTROL_RESUME	Resumes a paused printer.
PRINTER_CONTROL_SET_STATUS	Windows 95: Sets the printer status.
If dwCommand is any of the above values, dwLevel must be zero.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The handle hPrinter is obtained by calling the OpenPrinter function.

To modify the current printer settings, an application should call GetPrinter to retrieve the current settings into a PRINTER_INFO_2 structure, modify the members of that structure as necessary, and then call the SetPrinter function.

The SetPrinter function ignores the following members of a PRINTER_INFO_2 structure:

pServerName, AveragePPM, Status, and cJobs

Pausing a printer suspends scheduling of all print jobs for that printer, except for the one print job that may be currently printing. Print jobs can be submitted to a paused printer, but no jobs will be scheduled to print on that printer until printing is resumed. If a printer is cleared, all print jobs for that printer are deleted, except for the current print job.

If the printer data structure contains a pointer to a security descriptor, only those components of the security descriptor that the caller has permission to write should be present. An application that wants to write particular security descriptor components must open the printer with sufficient access permission to modify those components. The following table shows the security descriptor components that can be modified for particular access permission values:

Access Permission	Modifiable Security Descriptor Components
WRITE_OWNER	Owner, primary proup
WRITE_DAC	Discretionary access-control list (ACL)
ACCESS_SYSTEM_SECURITY	System ACL
If the calling application lacks a required permission, SetPrinter fails. Those components of a security descriptor that an application does not wish to modify should be NULL or not be present, as appropriate. If you do not want to modify the security descriptor, and are calling SetPrinter with a PRINTER_INFO_2 structure, set the pSecurityDescriptor member of that structure to NULL.

Windows 95: SetPrinter does not update the pShareName member in the PRINTER_INFO_2 structure.

Windows 95: SetPrinter is not supported when called against a Windows NT printer from a Windows 95 machine using the printer's UNC name.

See Also

AddPrinter, GetPrinter, OpenPrinter, PRINTER_INFO_2, PRINTER_INFO_3


SetPrinterData
 SetPrinterData  QuickInfo  Overview  Group

The SetPrinterData function sets the configuration data for a printer.

DWORD SetPrinterData(

HANDLE  hPrinter,	// handle of printer object
LPTSTR  lpszType,	// address of data type
DWORD  dwType,	// flag for value type
LPBYTE  lpbData,	// address of array that specifies printer data
DWORD  cbData	// size, in bytes, of array
);
Parameters

hPrinter

Identifies the printer for which the configuration data should be set.

lpszType

Points to a null-terminated string that specifies the type of data to be set.

dwType

Specifies the type of information to be stored as the value's data. This parameter can be one of the following values:

Value	Meaning
REG_BINARY	Binary data in any form.
REG_DWORD	A 32-bit number.
REG_DWORD_LITTLE_ENDIAN	A 32-bit number in little-endian format (same as REG_DWORD). In little-endian format, the most significant byte of a word is the high-order word. This is the most common format for computers running Windows NT and Windows 95.
REG_DWORD_BIG_ENDIAN	A 32-bit number in big-endian format. In big-endian format, the most significant byte of a word is the low-order word.
REG_EXPAND_SZ	A null-terminated string that contains unexpanded references to environment variables (for example, "%PATH%"). It will be a Unicode or ANSI string depending on whether you use the Unicode or ANSI functions.
REG_LINK	A Unicode symbolic link.
REG_MULTI_SZ	An array of null-terminated strings, terminated by two null characters.
REG_NONE	No defined value type.
REG_RESOURCE_LIST	A device-driver resource list.
REG_SZ	A null-terminated string. It will be a Unicode or ANSI string depending on whether you use the Unicode or ANSI functions.
lpbData

Points to an array of bytes that contains the printer configuration data.

cbData

Specifies the size, in bytes, of the array.

Return Value

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is an error value.

Remarks

The handle hPrinter is obtained by calling the OpenPrinter function.

Existing configuration data for a printer can be retrieved by calling the GetPrinter function.

See Also

GetPrinter, OpenPrinter


SetPriorityClass
 SetPriorityClass  QuickInfo  Overview  Group

The SetPriorityClass function sets the priority class for the specified process. This value together with the priority value of each thread of the process determines each thread's base priority level.

BOOL SetPriorityClass(

HANDLE  hProcess,	// handle to the process
DWORD  fdwPriority	// priority class value
);
Parameters

hProcess

Identifies the process. The handle must have PROCESS_SET_INFORMATION access.

fdwPriority

Specifies the priority class for the process. Specify one of the following values:

Priority	Meaning
HIGH_PRIORITY_CLASS	Indicates a process that performs time-critical tasks that must be executed immediately for it to run correctly. The threads of a high-priority class process preempt the threads of normal or idle priority class processes. An example is Windows Task List, which must respond quickly when called by the user, regardless of the load on the operating system. Use extreme care when using the high-priority class, because a high-priority class CPU-bound application can use nearly all available cycles.
IDLE_PRIORITY_CLASS	Indicates a process whose threads run only when the system is idle and are preempted by the threads of any process running in a higher priority class. An example is a screen saver. The idle-priority class is inherited by child processes.
NORMAL_PRIORITY_CLASS	Indicates a normal process with no special scheduling needs.
REALTIME_PRIORITY_CLASS	Indicates a process that has the highest possible priority. The threads of a real-time priority class process preempt the threads of all other processes, including operating system processes performing important tasks. For example, a real-time process that executes for more than a very brief interval can cause disk caches not to flush or cause the mouse to be unresponsive.
Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

Every thread has a base priority level determined by the thread's priority value and the priority class of its process. The system uses the base priority level of all executable threads to determine which thread gets the next slice of CPU time. Threads are scheduled in a round-robin fashion at each priority level, and only when there are no executable threads at a higher level will scheduling of threads at a lower level take place.

The base priority level of a thread is in the range 1 through 31. Following are the normal base priority levels for each priority class:

Class	Normal base priority
HIGH_PRIORITY_CLASS	13
IDLE_PRIORITY_CLASS	4
NORMAL_PRIORITY_CLASS	9 if the window of the process is in the foreground; and 7 if the window is in the background
REALTIME_PRIORITY_CLASS	24
The SetThreadPriority function enables setting the base priority level of a thread relative to the priority class of its process. For example, specifying THREAD_PRIORITY_HIGHEST in a call to SetThreadPriority for a thread of an IDLE_PRIORITY_CLASS process sets the thread's base priority level to 6.

For IDLE_PRIORITY_CLASS, NORMAL_PRIORITY_CLASS, and HIGH_PRIORITY_CLASS processes, the system dynamically boosts a thread's base priority level when events occur that are important to the thread. REALTIME_PRIORITY_CLASS processes do not receive dynamic boosts.

The initial priority class of a process can be specified in the CreateProcess function. If not specified, the priority class defaults to NORMAL_PRIORITY_CLASS unless the priority class of the creating process is IDLE_PRIORITY_CLASS. In this case, the default priority class of the child process is IDLE_PRIORITY_CLASS.

Be very careful when manipulating priorities to ensure that a high-priority thread does not consume all of the available CPU time. A thread with a base priority level above 11 interferes with the normal operation of the operating system.

The following table shows the base priority levels for each combination of priority class and thread priority value. Note that for IDLE_PRIORITY_CLASS, NORMAL_PRIORITY_CLASS, and HIGH_PRIORITY_CLASS, this base level can receive dynamic boosts.

Base	Priority class/thread priority
1	Idle, normal, or high class, THREAD_PRIORITY_IDLE
2	Idle class, THREAD_PRIORITY_LOWEST
3	Idle class, THREAD_PRIORITY_BELOW_NORMAL
4	Idle class, THREAD_PRIORITY_NORMAL
5	Background normal class, THREAD_PRIORITY_LOWEST Idle class, THREAD_PRIORITY_ABOVE_NORMAL
6	Background normal class, THREAD_PRIORITY_BELOW_NORMAL Idle class, THREAD_PRIORITY_HIGHEST
7	Foreground normal class, THREAD_PRIORITY_LOWEST Background normal class, THREAD_PRIORITY_NORMAL
8	Foreground normal class, THREAD_PRIORITY_BELOW_NORMAL Background normal class, THREAD_PRIORITY_ABOVE_NORMAL
9	Foreground normal class, THREAD_PRIORITY_NORMAL Background normal class, THREAD_PRIORITY_HIGHEST
10	Foreground normal class, THREAD_PRIORITY_ABOVE_NORMAL
11	High class, THREAD_PRIORITY_LOWEST Foreground normal class, THREAD_PRIORITY_HIGHEST
12	High class, THREAD_PRIORITY_BELOW_NORMAL
13	High class, THREAD_PRIORITY_NORMAL
14	High class, THREAD_PRIORITY_ABOVE_NORMAL
15	Idle, normal, or high class, THREAD_PRIORITY_TIME_CRITICAL High class, THREAD_PRIORITY_HIGHEST
16	Real-time class, THREAD_PRIORITY_IDLE
22	Real-time class, THREAD_PRIORITY_LOWEST
23	Real-time class, THREAD_PRIORITY_BELOW_NORMAL
24	Real-time class, THREAD_PRIORITY_NORMAL
25	Real-time class, THREAD_PRIORITY_ABOVE_NORMAL
26	Real-time class, THREAD_PRIORITY_HIGHEST
31	Real-time class, THREAD_PRIORITY_TIME_CRITICAL
See Also

CreateProcess, CreateThread, GetPriorityClass, GetThreadPriority, SetThreadPriority


SetPrivateObjectSecurity
 SetPrivateObjectSecurity  QuickInfo  Overview  Group

The SetPrivateObjectSecurity function modifies a private object's security descriptor.

BOOL SetPrivateObjectSecurity(

SECURITY_INFORMATION  si,	// type of security information
PSECURITY_DESCRIPTOR  psdSource,	// address of SD to apply to object
PSECURITY_DESCRIPTOR  *lppsdTarget,	// address of object's SD
PGENERIC_MAPPING  pgm,	// address of access-mapping structure
HANDLE  hClientToken	// handle of client access token
);
Parameters

si

Specifies a SECURITY_INFORMATION structure identifying the contents of the security descriptor pointed to by the psdSource parameter.

psdSource

Points to a SECURITY_DESCRIPTOR structure to be applied to the object.

lppsdTarget

Points to a pointer to a SECURITY_DESCRIPTOR structure to be altered by this function. This security descriptor must be in self-relative form.

pgm

Points to a GENERIC_MAPPING structure specifying the mapping of generic to specific and standard access types for the object.

hClientToken

Identifies the access token for the client on whose behalf the private object's security is being modified. This parameter is required to ensure that the client has provided a legitimate value for a new owner security identifier (SID). The token must be open for TOKEN_QUERY access.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The object's security descriptor must be in self-relative form.

If necessary, the SetPrivateObjectSecurity function allocates additional memory to produce a larger security descriptor.

The SetPrivateObjectSecurity function is successful only if the following conditions are met:

•	If the object's owner is being set, the calling process must have either WRITE_OWNER permission or be the object's owner.

•	If the object's discretionary access-control list (ACL) is being set, the calling process must have either WRITE_DAC permission or be the object's owner.

•	If the object's system ACL is being set, the SE_SECURITY_NAME privilege must be enabled for the calling process.

The process calling this function must not be impersonating a client.

See Also

CreatePrivateObjectSecurity, DestroyPrivateObjectSecurity, GENERIC_MAPPING, GetPrivateObjectSecurity, SECURITY_DESCRIPTOR, SECURITY_INFORMATION, SetFileSecurity, SetKernelObjectSecurity, SetUserObjectSecurity


SetProcessShutdownParameters
 SetProcessShutdownParameters  QuickInfo  Overview  Group

The SetProcessShutdownParameters function sets shutdown parameters for the currently calling process. This function sets a shutdown order for a process relative to the other processes in the system.

BOOL SetProcessShutdownParameters(

DWORD  dwLevel,	// shutdown priority
DWORD  dwFlags	// shutdown flags
);
Parameters

dwLevel

Specifies the shutdown priority for a process relative to other processes in the system. The system shuts down processes from high dwLevel values to low. The highest and lowest shutdown priorities are reserved for system components. This parameter must be in the following range of values:

Value	Meaning
000−0FF	System reserved last shutdown range.
100−1FF	Application reserved last shutdown range.
200−2FF	Application reserved "in between" shutdown range.
300−3FF	Application reserved first shutdown range.
400−4FF	System reserved first shutdown range.
All processes start at shutdown level 0x280.

dwFlags

Specifies a flags parameter. It can be the following value:

Value	Meaning
SHUTDOWN_NORETRY	Specifies whether to retry the shutdown if the specified time-out period expires. If this flag is specified, the system terminates the process without displaying a retry dialog box for the user.
Return Value

If the function is succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

Applications running in the system security context do not get shut down by the operating system. They get notified of shutdown or logoff through the callback function installable via SetConsoleCtrlHandler. They also get notified in the order specified by the dwLevel parameter.

See Also

GetProcessShutdownParameters, SetConsoleCtrlHandler


SetProcessWindowStation [New - Windows NT]
 SetProcessWindowStation  QuickInfo  Overview  Group

[New - Windows NT]

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 of window station to assign to this process
);
Parameters

hWinSta

Identifies the window station to be assigned to the calling process. This handle is returned by the CreateWindowStation and OpenWindowStation functions.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

CreateWindowStation, OpenWindowStation, SetThreadDesktop


SetProcessWorkingSetSize
 SetProcessWorkingSetSize  QuickInfo  Overview  Group

The SetProcessWorkingSetSize function sets the minimum and maximum working set sizes for a specified process.

The working set of a process is the set of memory pages currently visible to the process in physical RAM memory. These pages are resident and available for an application to use without triggering a page fault. The size of the working set of a process is specified in bytes. The minimum and maximum working set sizes affect the virtual memory paging behavior of a process.

BOOL SetProcessWorkingSetSize(

HANDLE  hProcess,	// open handle to the process of interest
DWORD  dwMinimumWorkingSetSize,	// specifies minimum working set size
DWORD  dwMaximumWorkingSetSize	// specifies maximum working set size
);
Parameters

hProcess

An open handle to the process whose working set sizes will be set. The handle must have PROCESS_QUERY_INFORMATION access rights.

dwMinimumWorkingSetSize

Specifies a minimum working set size for the process. The virtual memory manager attempts to keep at least this much memory resident in the process whenever the process is active.

If both dwMinimumWorkingSetSize and dwMaximumWorkingSetSize have the value 0xffffffff, the function temporarily trims the working set of the specified process to zero. This essentially swaps the process out of physical RAM memory.

dwMaximumWorkingSetSize

Specifies a maximum working set size for the process. The virtual memory manager attempts to keep no more than this much memory resident in the process whenever the process is active and memory is in short supply.

If both dwMinimumWorkingSetSize and dwMaximumWorkingSetSize have the value 0xffffffff, the function temporarily trims the working set of the specified process to zero. This essentially swaps the process out of physical RAM memory.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. Call GetLastError to obtain extended error information.

Remarks

The working set of the specified process can be emptied by specifying the value 0xffffffff for both the minimum and maximum working set sizes.

If the values of either dwMinimumWorkingSetSize or dwMaximumWorkingSetSize are greater than the process' current working set sizes, the specified process must have the SE_INC_BASE_PRIORITY_PRIVILEGE privilege. Users in the Administrators and Power Users groups generally have this privilege.

The operating system allocates working set sizes on a first-come, first-served basis. For example, if an application successfully sets 40 megabytes as its minimum working set size on a 64-megabyte system, and a second application requests a 40-megabyte working set size, the operating system denies the second application's request.

Using the SetProcessWorkingSetSize function to set an application's minimum and maximum working set sizes does not guarantee that the requested memory will be reserved, or that it will remain resident at all times. When the application is idle, or a low-memory situation causes a demand for memory, the operating system can reduce the application's working set. An application can use the VirtualLock function to lock ranges of the application's virtual address space in memory; however, that can potentially degrade the performance of the system.

When you increase the working set size of an application, you are taking away physical memory from the rest of the system. This can degrade the performance of other applications and the system as a whole. It can also lead to failures of operations that require physical memory to be present; for example, creating processes, threads, and kernel pool. Thus, you must use the SetProcessWorkingSetSize function carefully. You must always consider the performance of the whole system when you are designing an application.

See Also

GetProcessWorkingSetSize, VirtualLock


SetProp
 SetProp  QuickInfo  Overview  Group

The SetProp function adds a new entry or changes an existing entry in the property list of the specified window. The function adds a new entry to the list if the specified character string does not exist already in the list. The new entry contains the string and the handle. Otherwise, the function replaces the string's current handle with the specified handle.

BOOL SetProp(

HWND  hwnd,	// handle of window
LPCTSTR  lpsz,	// atom or address of string
HANDLE  hData	// handle of data
);
Parameters

hwnd

Identifies the window whose property list receives the new entry.

lpsz

Points 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 lpsz; the high-order word must be zero.

hData

Identifies data to be copied to the property list. The data handle can identify any value useful to the application.

Return Value

If the data handle and string are added to the property list, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

Before destroying a window (that is, before processing the WM_DESTROY message), an application must remove all entries it has added to the property list. The application must use the RemoveProp function to remove the entries.

See Also

EnumProps, EnumPropsEx, GetProp, GlobalAddAtom, RemoveProp


SetRect
 SetRect  QuickInfo  Overview  Group

The SetRect function sets the coordinates of the specified rectangle. This is equivalent to assigning the left, top, right, and bottom arguments to the appropriate members of the RECT structure.

BOOL SetRect(

LPRECT  lprc,	// address of structure with rectangle to set
int  nLeft,	// left side
int  nTop,	// top side
int  nRight,	// right side
int  nBottom	// bottom side
);
Parameters

lprc

Points to the RECT structure that contains the rectangle to be set.

nLeft

Specifies the x-coordinate of the rectangle's upper-left corner.

nTop

Specifies the y-coordinate of the rectangle's upper-left corner.

nRight

Specifies the x-coordinate of the rectangle's lower-right corner.

nBottom

Specifies the y-coordinate of the rectangle's lower-right corner.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

CopyRect, SetRectEmpty, RECT


SetRectEmpty
 SetRectEmpty  QuickInfo  Overview  Group

The SetRectEmpty function creates an empty rectangle in which all coordinates are set to zero.

BOOL SetRectEmpty(

LPRECT  lprc	// address of structure with rectangle set to empty
);
Parameters

lprc

Points to the RECT structure that contains the coordinates of the rectangle.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

CopyRect, RECT, SetRect


SetRectRgn
 SetRectRgn  QuickInfo  Overview  Group

The SetRectRgn function changes a region into a rectangular region with the specified coordinates.

BOOL SetRectRgn(

HRGN  hrgn,	// handle of region
int  nLeftRect,	// x-coordinate of upper-left corner of rectangle
int  nTopRect,	// y-coordinate of upper-left corner of rectangle
int  nRightRect,	// x-coordinate of lower-right corner of rectangle
int  nBottomRect	// y-coordinate of lower-right corner of rectangle
);
Parameters

hrgn

Identifies the region.

nLeftRect

Specifies the x-coordinate of the upper-left corner of the rectangular region.

nTopRect

Specifies the y-coordinate of the upper-left corner of the rectangular region.

nRightRect

Specifies the x-coordinate of the lower-right corner of the rectangular region.

nBottomRect

Specifies the y-coordinate of the lower-right corner of the rectangular region.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

The region does not include the lower and right boundaries of the rectangle.

See Also

CreateRectRgn


SetResourceHandler
 SetResourceHandler  Overview  Group

The SetResourceHandler function is not implemented in the Win32 API. Calculated resources do not work in the 32-bit environment.


SetROP2
 SetROP2  QuickInfo  Overview  Group

The SetROP2 function sets the current foreground mix mode. GDI uses the foreground mix mode to combine pens and interiors of filled objects with the colors already on the screen. The foreground mix mode defines how colors from the brush or pen and the colors in the existing image are to be combined.

int SetROP2(

HDC  hdc,	// handle of device context
int  fnDrawMode	// drawing mode
);
Parameters

hdc

Identifies the device context.

fnDrawMode

Specifies the new mix mode. This parameter can be any one of the following values:

Mix mode	Description
R2_BLACK	Pixel is always 0.
R2_COPYPEN	Pixel is the pen color.
R2_MASKNOTPEN	Pixel is a combination of the colors common to both the screen and the inverse of the pen.
R2_MASKPEN	Pixel is a combination of the colors common to both the pen and the screen.
R2_MASKPENNOT	Pixel is a combination of the colors common to both the pen and the inverse of the screen.
R2_MERGENOTPEN	Pixel is a combination of the screen color and the inverse of the pen color.
R2_MERGEPEN	Pixel is a combination of the pen color and the screen color.
R2_MERGEPENNOT	Pixel is a combination of the pen color and the inverse of the screen color.
R2_NOP	Pixel remains unchanged.
R2_NOT	Pixel is the inverse of the screen color.
R2_NOTCOPYPEN	Pixel is the inverse of the pen color.
R2_NOTMASKPEN	Pixel is the inverse of the R2_MASKPEN color.
R2_NOTMERGEPEN	Pixel is the inverse of the R2_MERGEPEN color.
R2_NOTXORPEN	Pixel is the inverse of the R2_XORPEN color.
R2_WHITE	Pixel is always 1.
R2_XORPEN	Pixel is a combination of the colors in the pen and in the screen, but not in both.
Return Value

If the function succeeds, the return value specifies the previous mix mode.

If the function fails, the return value is zero.

Remarks

Mix modes define how GDI combines source and destination colors when drawing with the current pen. The mix modes are binary raster operation codes, representing all possible Boolean functions of two variables, using the binary operations AND, OR, and XOR (exclusive OR), and the unary operation NOT. The mix mode is for raster devices only; it is not available for vector devices.

See Also

GetROP2


SetScrollInfo [New - Windows NT]
 SetScrollInfo  QuickInfo

[New - Windows NT]

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 of window with scroll bar
int  fnBar,	// scroll bar flag
LPSCROLLINFO  lpsi,	// pointer to structure with scroll parameters
BOOL  fRedraw	// redraw flag
);
Parameters

hwnd

Identifies a scroll bar control or a window with a standard scroll bar, depending on the value of the fnBar parameter.

fnBar

Specifies the type of scroll bar for which to set parameters. This parameter can be one of the following values:

Value	Meaning
SB_CTL	Sets the parameters of a scroll bar control. The hwnd parameter must be the handle of the scroll bar control.
SB_HORZ	Sets the parameters of the given window's standard horizontal scroll bar.
SB_VERT	Sets the parameters of the given window's standard vertical scroll bar.
lpsi

Points to a SCROLLINFO structure whose fMask member, upon entry to the function, specifies the scroll bar parameters to set.

The fMask member can be a combination of the following values:

Value	Meaning
SIF_DISABLENOSCROLL	Disables the scroll bar instead of removing it, if the scroll bar's new parameters make the scroll bar unnecessary.
SIF_PAGE	Sets the scroll page to the value specified in the nPage member of the SCROLLINFO structure pointed to by lpsi.
SIF_POS	Sets the scroll position to the value specified in the nPos member of the SCROLLINFO structure pointed to by lpsi.
SIF_RANGE	Sets the scroll range to the value specified in the nMin and nMax members of the SCROLLINFO structure pointed to by lpsi.
fRedraw

Specifies whether the scroll bar is redrawn to reflect the changes to the scroll bar. If this parameter is TRUE, the scroll bar is redrawn, otherwise, it is not redrawn.

Return Value

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.

See Also

GetScrollInfo, SCROLLINFO


SetScrollPos
 SetScrollPos  QuickInfo  Overview  Group

The SetScrollPos function sets the position of the scroll box (thumb) in the specified scroll bar and, if requested, redraws the scroll bar to reflect the new position of the scroll box. The SetScrollPos function is provided for compatibility with Windows 3.x. Win32-based applications should use the SetScrollInfo function.

int SetScrollPos(

HWND  hwnd,	// handle of window with scroll bar
int  fnBar,	// scroll bar flag
int  nPos,	// new position of scroll box
BOOL  fRedraw	// redraw flag
);
Parameters

hwnd

Identifies a scroll bar control or a window with a standard scroll bar, depending on the value of the fnBar parameter.

fnBar

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 of the scroll bar control.
SB_HORZ	Sets the position of the scroll box in a window's standard horizontal scroll bar.
SB_VERT	Sets the position of the scroll box in a window's standard vertical scroll bar.
nPos

Specifies the new position of the scroll box. The position must be within the scrolling range. For more information about the scrolling range, see the SetScrollRange function.

fRedraw

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 Value

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 fRedraw 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 SetScrollPos, SetScrollRange, 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 GetScrollPos for a description of the technique and its limits.

See Also

GetScrollPos, GetScrollRange, ScrollDC, ScrollWindow, SetScrollRange


SetScrollRange
 SetScrollRange  QuickInfo  Overview  Group

The SetScrollRange function sets the minimum and maximum position values for the specified scroll bar. It can also be used to hide or show a standard scroll bar.The SetScrollRange function is provided for compatibility with Windows 3.x. Win32-based applications should use the SetScrollInfo function.

BOOL SetScrollRange(

HWND  hwnd,	// handle of window with scroll bar
int  fnBar,	// scroll bar flag
int  nMinPos,	// minimum scrolling position
int  nMaxPos,	// maximum scrolling position
BOOL  fRedraw	// redraw flag
);
Parameters

hwnd

Identifies a scroll bar control or a window with a standard scroll bar, depending on the value of the fnBar parameter.

fnBar

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 of the scroll bar control.
SB_HORZ	Sets the range of a window's standard horizontal scroll bar.
SB_VERT	Sets the range of a window's standard vertical scroll bar.
nMinPos

Specifies the minimum scrolling position.

nMaxPos

Specifies the maximum scrolling position.

fRedraw

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 Value

If the function succeeds, the return value is TRUE.

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

Remarks

An application should not call the SetScrollRange function to hide a scroll bar while processing a scroll bar message.

If the call to SetScrollRange immediately follows a call to the SetScrollPos function, the fRedraw 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 SetScrollPos, SetScrollRange, 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 GetScrollPos for a description of the technique and its limits.

See Also

GetScrollPos, GetScrollRange, SetScrollPos


SetSecurityDescriptorDacl
 SetSecurityDescriptorDacl  QuickInfo  Overview  Group

The SetSecurityDescriptorDacl function sets information in a discretionary access-control list (ACL). If a discretionary ACL is already present in the security descriptor, it is replaced.

BOOL SetSecurityDescriptorDacl(

PSECURITY_DESCRIPTOR  psd,	// address of security descriptor
BOOL  fDaclPresent,	// flag for presence of discretionary ACL
PACL  pAcl,	// address of discretionary ACL
BOOL  fDaclDefaulted	// flag for default discretionary ACL
);
Parameters

psd

Points to the SECURITY_DESCRIPTOR structure to which the function adds the discretionary ACL. This security descriptor must be in absolute format, meaning that its members must be pointers to other structures, rather than offsets to contiguous data.

fDaclPresent

Specifies a flag indicating the presence of a discretionary ACL in the security descriptor. If this parameter is TRUE, the function sets the SE_DACL_PRESENT flag in the SECURITY_DESCRIPTOR_CONTROL structure and uses the values in the pAcl and fDaclDefaulted parameters. If it is FALSE, the function clears the SE_DACL_PRESENT flag, and pAcl and fDaclDefaulted are ignored.

pAcl

Points to an ACL structure specifying the discretionary ACL for the security descriptor. If this parameter is NULL, a NULL discretionary ACL is assigned to the security descriptor, allowing all access to the object. The discretionary ACL is referenced by, not copied into, the security descriptor.

fDaclDefaulted

Specifies a flag indicating the source of the discretionary ACL. If this flag is TRUE, the discretionary ACL has been retrieved by some default mechanism. If FALSE, the discretionary ACL has been explicitly specified by a user. The function stores this value in the SE_DACL_DEFAULTED flag of the SECURITY_DESCRIPTOR_CONTROL structure. If this parameter is not specified, the SE_DACL_DEFAULTED flag is cleared.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

There is an important difference between an empty and a nonexistent discretionary ACL. When a discretionary ACL is empty, it contains no access-control entries and no access rights have been explicitly granted. As a result, access to the object is implicitly denied. When an object has no DACL, on the other hand, no protection is assigned to the object, and any access request is granted.

There are three possible outcomes in different configurations of the fDaclPresent flag and the pAcl parameter:

•	When the pACL parameter points to a discretionary ACL and the fDaclPresent flag is TRUE, a discretionary ACL is specified and it must contain access-allowed ACEs to allow access to the object.

•	When the pACL parameter does not point to a discretionary ACL and the fDaclPresent flag is TRUE, a NULL discretionary ACL is specified. All access is allowed.

•	When the pACL parameter does not point to a discretionary ACL and the fDaclPresent flag is FALSE, a discretionary ACL can be provided for the object through an inheritance or default mechanism.

See Also

ACL, GetSecurityDescriptorDacl, InitializeSecurityDescriptor, IsValidSecurityDescriptor, SECURITY_DESCRIPTOR, SECURITY_DESCRIPTOR_CONTROL, SetSecurityDescriptorGroup, SetSecurityDescriptorOwner, SetSecurityDescriptorSacl


SetSecurityDescriptorGroup
 SetSecurityDescriptorGroup  QuickInfo  Overview  Group

The SetSecurityDescriptorGroup function sets the primary group information of an absolute-format security descriptor, replacing any primary group information already present in the security descriptor.

BOOL SetSecurityDescriptorGroup(

PSECURITY_DESCRIPTOR  psd,	// address of security descriptor
PSID  psidGroup,	// address of SID for group
BOOL  fGroupDefaulted	// flag for default
);
Parameters

psd

Points to the SECURITY_DESCRIPTOR structure whose primary group is set by this function. The function replaces any existing primary group with the new primary group.

psidGroup

Points to a SID structure the function sets as the security descriptor's new primary group. The SID structure is referenced by, not copied into, the security descriptor. If this parameter is NULL, the function clears the security descriptor's primary group information. This marks the security descriptor as having no primary group.

fGroupDefaulted

Specifies a flag indicating whether the primary group information was derived from a default mechanism. If this flag is TRUE, it is default information, and the function stores this value as the SE_GROUP_DEFAULTED flag in the SECURITY_DESCRIPTOR_CONTROL structure. If this parameter is zero, the SE_GROUP_DEFAULTED flag is cleared.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

GetSecurityDescriptorGroup, InitializeSecurityDescriptor, SECURITY_DESCRIPTOR, SECURITY_DESCRIPTOR_CONTROL, SetSecurityDescriptorDacl, SetSecurityDescriptorOwner, SetSecurityDescriptorSacl, SID


SetSecurityDescriptorOwner
 SetSecurityDescriptorOwner  QuickInfo  Overview  Group

The SetSecurityDescriptorOwner function sets the owner information of an absolute-format security descriptor. It replaces any owner information already present in the security descriptor.

BOOL SetSecurityDescriptorOwner(

PSECURITY_DESCRIPTOR  psd,	// address of security descriptor
PSID  psidOwner,	// address of SID for owner
BOOL  fOwnerDefaulted	// flag for default
);
Parameters

psd

Points to the SECURITY_DESCRIPTOR structure whose owner is set by this function. The function replaces any existing owner with the new owner.

psidOwner

Points to a SID structure the function sets as the security descriptor's new primary owner. The SID structure is referenced by, not copied into, the security descriptor. If this parameter is NULL, the function clears the security descriptor's owner information. This marks the security descriptor as having no owner.

fOwnerDefaulted

Specifies a flag indicating whether the owner information is derived from a default mechanism. If this flag is TRUE, it is default information. The function stores this value as the SE_OWNER_DEFAULTED flag in the SECURITY_DESCRIPTOR_CONTROL structure. If this parameter is zero, the SE_OWNER_DEFAULTED flag is cleared.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

GetSecurityDescriptorOwner, InitializeSecurityDescriptor, IsValidSecurityDescriptor, SECURITY_DESCRIPTOR, SECURITY_DESCRIPTOR_CONTROL, SetSecurityDescriptorDacl, SetSecurityDescriptorGroup, SetSecurityDescriptorSacl, SID


SetSecurityDescriptorSacl
 SetSecurityDescriptorSacl  QuickInfo  Overview  Group

The SetSecurityDescriptorSacl function sets information in a system access-control list (ACL). If there is already a system ACL present in the security descriptor, it is replaced.

BOOL SetSecurityDescriptorSacl(

PSECURITY_DESCRIPTOR  psd,	// address of security descriptor
BOOL  fSaclPresent,	// flag for presence of system ACL
PACL  pAcl,	// address of system ACL
BOOL  fSaclDefaulted	// flag for default system ACL
);
Parameters

psd

Points to the SECURITY_DESCRIPTOR structure to which the function adds the system ACL. This security descriptor must be in absolute format, meaning that its members must be pointers to other structures, rather than offsets to contiguous data.

fSaclPresent

Specifies a flag indicating the presence of a system ACL in the security descriptor. If this parameter is TRUE, the function sets the SE_SACL_PRESENT flag in the SECURITY_DESCRIPTOR_CONTROL structure and uses the values in the pAcl and fSaclDefaulted parameters. If it is FALSE, the function does not set the SE_SACL_PRESENT flag, and pAcl and fSaclDefaulted are ignored.

pAcl

Points to an ACL structure that specifies the system ACL for the security descriptor. If this parameter is NULL, a NULL system ACL is assigned to the security descriptor. The system ACL is referenced by, not copied into, the security descriptor.

fSaclDefaulted

Specifies a flag indicating the source of the system ACL. If this flag is TRUE, the system ACL has been retrieved by some default mechanism. If it is FALSE, the system ACL has been explicitly specified by a user. The function stores this value in the SE_SACL_DEFAULTED flag of the SECURITY_DESCRIPTOR_CONTROL structure. If this parameter is not specified, the SE_SACL_DEFAULTED flag is cleared.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

ACL, GetSecurityDescriptorSacl, InitializeSecurityDescriptor, IsValidSecurityDescriptor, SECURITY_DESCRIPTOR, SECURITY_DESCRIPTOR_CONTROL, SetSecurityDescriptorDacl, SetSecurityDescriptorGroup, SetSecurityDescriptorOwner


SetService
 SetService  QuickInfo  Overview  Group

The SetService function registers or deregisters a network service within one or more name spaces. The function can also add or remove a network service type within one or more name spaces.

INT SetService(

DWORD  dwNameSpace,	// specifies name space(s) to operate within
DWORD  dwOperation,	// specifies operation to perform
DWORD  dwFlags,	// set of bit flags that modify function operation
LPSERVICEINFO  lpServiceInfo,	// points to structure containing service information
LPSERVICE_ASYNC_INFO  lpServiceAsyncInfo,	// reserved for future use, must be NULL
LPDWORD  lpdwStatusFlags	// points to set of status bit flags
);
Parameters

dwNameSpace

Specifies the name space, or a set of default name spaces, within which the function will operate.

Use one of the following constants to specify a name space:

Value	Name Space
NS_DEFAULT	A set of default name spaces. The function queries each name space within this set. The set of default name spaces typically includes all the name spaces installed on the system. System administrators, however, can exclude particular name spaces from the set. NS_DEFAULT is the value that most applications should use for dwNameSpace.
NS_DNS	The Domain Name System used in the Internet to resolve the name of the host.
NS_NDS	The NetWare 4 provider.
NS_NETBT	The NetBIOS over TCP/IP layer. All Windows NT and Windows 95 systems register their computer names with NetBIOS. This name space is used to convert a computer name to an IP address that uses this registration.
NS_SAP	The NetWare Service Advertising Protocol. This can access the Netware bindery, if appropriate. NS_SAP is a dynamic name space that enables the registration of services.
NS_TCPIP_HOSTS	Lookup value in the <systemroot>\system32\drivers\etc\posts file.
NS_TCPIP_LOCAL	Local TCP/IP name resolution mechanisms, including comparisons against the local host name and lookup value in the cache of host to IP address mappings.
dwOperation

Specifies the operation that the function will perform. Use one of the following values to specify an operation:

Value	Meaning
SERVICE_REGISTER	Register the network service with the name space. This operation may be used with the SERVICE_FLAG_DEFER and SERVICE_FLAG_HARD bit flags.
SERVICE_DEREGISTER	Deregister the network service from the name space. This operation can be used with the SERVICE_FLAG_DEFER and SERVICE_FLAG_HARD bit flags.
SERVICE_FLUSH	Perform any operation that was called with the SERVICE_FLAG_DEFER bit flag set to one.
SERVICE_ADD_TYPE	Add a service type to the name space.  For this operation, use the ServiceSpecificInfo member of the SERVICE_INFO structure pointed to by lpServiceInfo to pass a SERVICE_TYPE_INFO_ABS structure. You must also set the ServiceType member of the SERVICE_INFO structure. Other SERVICE_INFO members are ignored.
SERVICE_DELETE_TYPE	Remove a service type, added by a previous call specifying the SERVICE_ADD_TYPE operation,  from the name space.
dwFlags

A set of bit flags that modify the function's operation. You can set one or more of the following bit flags:

Value	Name Space
SERVICE_FLAG_DEFER	This bit flag is valid only if the operation is SERVICE_REGISTER or SERVICE_DEREGISTER. If this bit flag is one, and it is valid, the name-space provider should defer the registration or deregistration operation until a SERVICE_FLUSH operation is requested.
SERVICE_FLAG_HARD	This bit flag is valid only if the operation is SERVICE_REGISTER or SERVICE_DEREGISTER. If this bit flag is one, and it is valid, the name-space provider updates any relevant persistent store information when the operation is performed.  For example: If the operation involves deregistration in a name space that uses a persistent store, the name-space provider would remove the relevant persistent store information.
lpService_Info

Points to a SERVICE_INFO structure that contains information about the network service or service type.

lpServiceAsyncInfo

This parameter is reserved for future use. It must be set to NULL.

lpdwStatusFlags

A set of bit flags that receive function status information. The following bit flag is defined:

Value	Meaning
SET_SERVICE_PARTIAL_SUCCESS	One or more name-space providers were unable to successfully perform the requested operation.
Return Value

If the function succeeds, the return value is not SOCKET_ERROR.

If the function fails, the return value is SOCKET_ERROR. To get extended error information, call GetLastError. GetLastError may return the following extended error value:

Value	Meaning
ERROR_ALREADY_REGISTERED	The function tried to register a service that was already registered.
See Also

GetService, SERVICE_INFO, SERVICE_TYPE_INFO_ABS


SetServiceBits
 SetServiceBits  QuickInfo  Overview  Group

The SetServiceBits function registers a service's service type with the Service Control Manager and the Server service. The Server service can then announce the registered service type as one it currently supports. The LAN Manager functions NetServerGetInfo and NetServerEnum obtain a specified machine's supported service types.

A service type is represented as a set of bit flags; the SetServiceBits function sets or clears combinations of those bit flags.

BOOL SetServiceBits (

SERVICE_STATUS_HANDLE  hServiceStatus,	// service status handle
DWORD  dwServiceBits,	// service type bits to set or clear
BOOL  bSetBitsOn,	// flag to set or clear the service type bits
BOOL bUpdateImmediately	// flag to announce server type immediately
);
Parameters

hServiceStatus

A handle to the Service Control Manager's status information structure for a service. A service obtains a SERVICE_STATUS_HANDLE value by calling the RegisterServiceCtrlHandler function. It is the service's handle for making calls to the Service Control Manager.

dwServiceBits

A set of bit flags that specifies a service type.

Certain bit flags (0xC00F3F7B) are reserved for use by Microsoft. The SetServiceBits function fails with the error ERROR_INVALID_DATA if any of these bit flags are set in dwServiceBits. There are 18 of these bit flags:

Bit Flag Constant	Value
SV_TYPE_WORKSTATION	0x00000001
SV_TYPE_SERVER	0x00000002
SV_TYPE_DOMAIN_CTRL	0x00000008
SV_TYPE_DOMAIN_BAKCTRL	0x00000010
SV_TYPE_TIME_SOURCE	0x00000020
SV_TYPE_AFP	0x00000040
SV_TYPE_DOMAIN_MEMBER	0x00000100
SV_TYPE_PRINTQ_SERVER	0x00000200
SV_TYPE_DIALIN_SERVER	0x00000400
SV_TYPE_XENIX_SERVER	0x00000800
SV_TYPE_SERVER_UNIX	0x00000800
SV_TYPE_NT	0x00001000
SV_TYPE_WFW	0x00002000
SV_TYPE_POTENTIAL_BROWSER	0x00010000
SV_TYPE_BACKUP_BROWSER	0x00020000
SV_TYPE_MASTER_BROWSER	0x00040000
SV_TYPE_DOMAIN_MASTER	0x00080000
SV_TYPE_LOCAL_LIST_ONLY	0x40000000
SV_TYPE_DOMAIN_ENUM	0x80000000
Certain bit flags (0x00300084) are defined by Microsoft, but are not specifically reserved for systems software. There are four of these bit flags:

Bit Flag Constant	Value
SV_TYPE_SV_TYPE_SQLSERVER	0x00000004
SV_TYPE_NOVELL	0x00000080
SV_TYPE_DOMAIN_CTRL	0x00100000
SV_TYPE_DOMAIN_BAKCTRL	0x00200000
Certain bit flags (0x3FC0C000) are not defined by Microsoft, and their use is not coordinated by Microsoft. Developers of applications that use these bits should be aware that other applications may also use them, thus creating a conflict. There are 10 of these bit flags:

Value	Value
0x00004000	0x02000000
0x00008000	0x04000000
0x00400000	0x08000000
0x00800000	0x10000000
0x01000000	0x20000000
bSetBitsOn

A BOOLEAN that specifies whether the function is to set or clear the bit flags that are set in dwServiceBit. The value TRUE specifies that the bits are to be set; FALSE specifies clearing.

bUpdateImmediately

A BOOLEAN that specifies whether the Server service is to perform an immediate update, announcing the new service type. The value TRUE specifies an immediate update; FALSE specifies otherwise.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

NetServerGetInfo, NetServerEnum,RegisterServiceCtrlHandler, SetServiceStatus


SetServiceObjectSecurity
 SetServiceObjectSecurity  QuickInfo  Overview  Group

The SetServiceObjectSecurity function sets the security descriptor of a service object.

BOOL SetServiceObjectSecurity(

SC_HANDLE  schService,	// handle of service
SECURITY_INFORMATION  fdwSecurityInfo,	// type of security information requested
PSECURITY_DESCRIPTOR  psdSecurityDesc	// address of security descriptor
);
Parameters

schService

Identifies the service. This handle is returned by the OpenService or CreateService function. The access required for this handle depends on the security information specified in the fdwSecurityInfo parameter.

fdwSecurityInfo

Specifies the security information to be set. Any or all of the following flags can be specified:

Value	Meaning
OWNER_SECURITY_INFORMATION	Sets the object's owner security identifier (SID). The schService handle must have WRITE_OWNER access, or the calling process must be the object's owner.
GROUP_SECURITY_INFORMATION	Sets the object's primary group SID. The schService handle must have WRITE_OWNER access, or the calling process must be the object's owner.
DACL_SECURITY_INFORMATION	Sets the object's discretionary access control list (ACL). The schService handle must have WRITE_DAC access, or the calling process must be the object's owner.
SACL_SECURITY_INFORMATION	Sets the object's system ACL. The calling process must have SeSecurityPrivilege privilege.
psdSecurityDesc

Points to a SECURITY_DESCRIPTOR structure containing the new security information.

Return Value

If the function succeeds, the return value is TRUE.

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

Errors

The following error codes may be set by the service control manager. Other error codes may be set by the registry functions that are called by the service control manager.

Value	Meaning
ERROR_ACCESS_DENIED
	The specified handle was not opened with the required access, or the calling process is not the owner of the object.
ERROR_INVALID_HANDLE
	The specified handle is invalid.
ERROR_INVALID_PARAMETER
	The specified security information or security descriptor is invalid.
ERROR_SERVICE_MARKED_FOR_DELETE
	The specified service has been marked for deletion.
Remarks

The SetServiceObjectSecurity function sets the specified portions of the service object's security descriptor, based on the information specified in the psdSecurityDesc buffer. This function replaces any or all of the security information associated with the service object, according to the flags set in the fdwSecurityInfo parameter and subject to the calling process's access rights.

The initial security descriptor of a service object is created by the service control manager, based on the security descriptor of the process that called the CreateService function to create the service. The security descriptor can be changed by calling the SetServiceObjectSecurity function.

See Also

CreateService, OpenService, QueryServiceObjectSecurity, SECURITY_DESCRIPTOR


SetServiceStatus
 SetServiceStatus  QuickInfo  Overview  Group

The SetServiceStatus function updates the service control manager's status information for the calling service.

BOOL SetServiceStatus(

SERVICE_STATUS_HANDLE  sshServiceStatus,	// service status handle
LPSERVICE_STATUS  lpssServiceStatus	// address of status structure
);
Parameters

sshServiceStatus

Specifies a handle to the service control manager's status information structure for the current service. This handle is returned by the RegisterServiceCtrlHandler function.

lpssServiceStatus

Points to the SERVICE_STATUS structure the contains the latest status information for the calling service.

Return Value

If the function succeeds, the return value is TRUE.

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

Errors

The following error codes may be set by the service control manager. Other error codes may be set by the registry functions that are called by the service control manager.

Value	Meaning
ERROR_INVALID_HANDLE	The specified handle is invalid.
ERROR_INVALID_DATA	The specified service status structure is invalid.
Remarks

A Win32 service's ServiceMain function first calls the RegisterServiceCtrlHandler function to get the service's SERVICE_STATUS_HANDLE. Then it immediately calls the SetServiceStatus function to notify the service control manager of its SERVICE_START_PENDING status.

When a Win32 service receives a control request, the service's Handler function must call this function, even if the service's status did not change. A service can also use this function at any time and by any thread of the service to notify the service control manager of status changes. Examples of such unsolicited status updates include:

•	Checkpoint updates that occur when the service is in transition from one state to another (that is, SERVICE_START_PENDING).

•	An update made necessary by the expected occurrence of a fatal error that causes the service to stop.

A service can call this function only after it has called RegisterServiceCtrlHandler to get a service status handle.

See Also

Handler, RegisterServiceCtrlHandler, SERVICE_STATUS, ServiceMain, SetServiceBits


setsockopt
 setsockopt  QuickInfo

The Windows Sockets setsockopt function sets a socket option.

int setsockopt (

SOCKET s,
int level,
int optname,
const char FAR * optval,
int optlen
);
Parameters

s

A descriptor identifying a socket.

level

The level at which the option is defined; the only supported levels are SOL_SOCKET and IPPROTO_TCP.

optname

The socket option for which the value is to be set.

optval

A pointer to the buffer in which the value for the requested option is supplied.

optlen

The size of the optval buffer.

Return Value

If the function succeeds, setsockopt returns zero.

If the function fails, a value of SOCKET_ERROR is returned. To get extended error information, call WSAGetLastError.

Error Codes

WSANOTINITIALISED	A successful WSAStartup must occur before using this function.
WSAENETDOWN	The Windows Sockets implementation has detected that the network subsystem has failed.
WSAEFAULT	The optval parameter is not in a valid part of the process address space.
WSAEINPROGRESS	A blocking Windows Sockets operation is in progress.
WSAEINVAL	The level parameter is not valid, or the information in optval is not valid.
WSAENETRESET	Connection has timed out when SO_KEEPALIVE is set.
WSAENOPROTOOPT	The option is unknown or unsupported. In particular, SO_BROADCAST is not supported on sockets of type SOCK_STREAM, while SO_DONTLINGER, SO_KEEPALIVE, SO_LINGER and SO_OOBINLINE are not supported on sockets of type SOCK_DGRAM.
WSAENOTCONN	Connection has been reset when SO_KEEPALIVE is set.
WSAENOTSOCK	The descriptor is not a socket.
Remarks

The setsockopt function sets the current value for a socket option associated with a socket of any type, in any state. Although options may exist at multiple protocol levels, this specification only defines options that exist at the uppermost "socket" level. Options affect socket operations, such as whether expedited data is received in the normal data stream, whether broadcast messages can be sent on the socket, and so on.

There are two types of socket options: Boolean options that enable or disable a feature or behavior, and options that require an integer value or structure. To enable a Boolean option, optval points to a nonzero integer. To disable the option, optval points to an integer equal to zero. The optlen parameter should be equal to sizeof(int) for Boolean options. For other options, optval points to the an integer or structure that contains the desired value for the option, and optlen is the length of the integer or structure.

The SO_LINGER option controls the action taken when unsent data is queued on a socket and a closesocket is performed. See closesocket for a description of the way the SO_LINGER settings affect the semantics of closesocket. The application sets the desired behavior by creating a linger structure (pointed to by the optval argument) with the following elements:

struct linger {

int    l_onoff;

int    l_linger;

}

To enable SO_LINGER, the application should set l_onoff to a nonzero value, set l_linger to zero or the desired timeout (in seconds), and call setsockopt. To enable SO_DONTLINGER (i.e. disable SO_LINGER) l_onoff should be set to zero and setsockopt should be called.

By default, a socket cannot be bound (see bind) to a local address that is already in use. On occasions, however, it may be desirable to "re-use" an address in this way. Since every connection is uniquely identified by the combination of local and remote addresses, there is no problem with having two sockets bound to the same local address as long as the remote addresses are different. To inform the Windows Sockets implementation that a bind on a socket should not be disallowed because the desired address is already in use by another socket, the application should set the SO_REUSEADDR socket option for the socket before issuing the bind. Note that the option is interpreted only at the time of the bind: it is therefore unnecessary (but harmless) to set the option on a socket that is not to be bound to an existing address, and setting or resetting the option after the bind has no effect on this or any other socket.

An application can request that the Windows Sockets implementation enable the use of "keep-alive" packets on TCP connections by turning on the SO_KEEPALIVE socket option. A Windows Sockets implementation need not support the use of keepalives: if it does, the precise semantics are implementation-specific but should conform to section 4.2.3.6 of RFC 1122: Requirements for Internet Hosts — Communication Layers. If a connection is dropped as the result of keepalives, the error code WSAENETRESET is returned to any calls in progress on the socket, and any subsequent calls will fail with WSAENOTCONN.

The TCP_NODELAY option disables the Nagle algorithm. The Nagle algorithm is used to reduce the number of small packets sent by a host by buffering unacknowledged send data until a full-size packet can be sent. However, for some applications this algorithm can impede performance, and TCP_NODELAY can be used to turn it off. You should not set TCP_NODELAY unless the impact of doing so is well understood and desired, since setting TCP_NODELAY can have a significant negative impact of network performance. TCP_NODELAY is the only supported socket option that uses level IPPROTO_TCP; all other options use level SOL_SOCKET.

Windows Sockets suppliers are encouraged (but not required) to supply output debug information if the SO_DEBUG option is set by an application. The mechanism for generating the debug information and the form it takes are beyond the scope of this documentation.

The following options are supported for setsockopt. The Type identifies the type of data addressed by optval.

Value	Type	Meaning
SO_BROADCAST	BOOL	Allow transmission of broadcast messages on the socket.
SO_DEBUG	BOOL	Record debugging information.
SO_DONTLINGER	BOOL	Don't block close waiting for unsent data to be sent. Setting this option is equivalent to setting SO_LINGER with l_onoff set to zero.
SO_DONTROUTE	BOOL	Don't route: send directly to interface.
SO_KEEPALIVE	BOOL	Send keepalive messages.
SO_LINGER	struct linger FAR *	Linger on close if unsent data is present.
SO_OOBINLINE	BOOL	Receive out-of-band data in the normal data stream.
SO_RCVBUF	int	Specify buffer size for receives.
SO_REUSEADDR	BOOL	Allow the socket to be bound to an address that is already in use. (See bind.)
SO_SNDBUF	int	Specify buffer size for sends.
TCP_NODELAY	BOOL	Disables the Nagle algorithm for send coalescing.
The following BSD options are not supported for setsockopt.

Value	Type	Meaning
SO_ACCEPTCONN	BOOL	Socket is listening
SO_ERROR	int	Get error status and clear
SO_RCVLOWAT	int	Receive low-water mark
SO_RCVTIMEO	int	Receive timeout
SO_SNDLOWAT	int	Send low-water mark
SO_SNDTIMEO	int	Send timeout
SO_TYPE	int	Type of the socket
IP_OPTIONS		Set options field in IP header.
See Also

bind, getsockopt, ioctlsocket, socket, WSAAsyncSelect, WSAStartup


 SetSoundNoise

The SetSoundNoise function has been deleted.

See Also

Beep, MessageBeep


SetStdHandle
 SetStdHandle  QuickInfo  Overview  Group

The SetStdHandle function is used to set the handle for the standard input, standard output, or standard error device. The specified handle can be used by subsequent calls to the GetStdHandle function to refer to the input, output, or error device.

BOOL SetStdHandle(

DWORD  IDStdHandle,	// input, output, or error device
HANDLE  hHandle	// handle to be a standard handle
);
Parameters

IDStdHandle

Specifies the handle to be set. This parameter can have one of the following values:

Value	Meaning
STD_INPUT_HANDLE	Standard input handle
STD_OUTPUT_HANDLE	Standard output handle
STD_ERROR_HANDLE	Standard error handle
hHandle

Supplies the handle to store as standard input, standard output, or standard error.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The standard handles of a process may have been redirected by a call to SetStdHandle, in which case GetStdHandle will return the redirected handle. If the standard handles have been redirected, you can specify the CONIN$ value in a call to the CreateFile function to get a handle of a console's input buffer. Similarly, you can specify the CONOUT$ value to get a handle of the console's active screen buffer.

See Also

CreateFile, GetStdHandle


SetStretchBltMode
 SetStretchBltMode  QuickInfo  Overview  Group

The SetStretchBltMode function sets the bitmap stretching mode in the specified device context.

int SetStretchBltMode(

HDC  hdc,	// handle of device context
int  iStretchMode	// bitmap stretching mode
);
Parameters

hdc

Identifies the device context.

iStretchMode

Specifies the stretching mode. It can be one of the following values:

Value	Description
BLACKONWHITE	Performs a Boolean AND operation using the color values for the eliminated and existing pixels. If the bitmap is a monochrome bitmap, this mode preserves black pixels at the expense of white pixels.
COLORONCOLOR	Deletes the pixels. This mode deletes all eliminated lines of pixels without trying to preserve their information.
HALFTONE	Maps pixels from the source rectangle into blocks of pixels in the destination rectangle. The average color over the destination block of pixels approximates the color of the source pixels.
	After setting the HALFTONE stretching mode, an application must call the SetBrushOrgEx function to set the brush origin. If it fails to do so, brush misalignment occurs.
STRETCH_ANDSCANS	Windows 95: Same as BLACKONWHITE.
STRETCH_DELETESCANS	Windows 95: Same as COLORONCOLOR.
STRETCH_HALFTONE	Windows 95: Same as HALFTONE.
STRETCH_ORSCANS	Windows 95: Same as WHITEONBLACK.
WHITEONBLACK	Performs a Boolean OR operation using the color values for the eliminated and existing pixels. If the bitmap is a monochrome bitmap, this mode preserves white pixels at the expense of black pixels.
Return Value

If the function succeeds, the return value is the previous stretching mode.

If the function fails, the return value is zero.

Remarks

The stretching mode defines how Windows combines rows or columns of a bitmap with existing pixels on a display device when an application calls the StretchBlt function.

The BLACKONWHITE (STRETCH_ANDSCANS) and WHITEONBLACK (STRETCH_ORSCANS) modes are typically used to preserve foreground pixels in monochrome bitmaps. The COLORONCOLOR (STRETCH_DELETESCANS) mode is typically used to preserve color in color bitmaps.

The HALFTONE mode requires more processing of the source image than the other three modes; it is slower than the others but produces higher quality images. Also note that SetBrushOrgEx must be called after setting the HALFTONE mode to avoid brush misalignment.

Additional stretching modes might also be available depending on the capabilities of the device driver.

See Also

SetBrushOrgEx, StretchBlt


SetSwapAreaSize
 SetSwapAreaSize  QuickInfo  Overview  Group

The SetSwapAreaSize function is obsolete. It has no meaning in the 32-bit environment.


SetSysColors
 SetSysColors  QuickInfo  Overview  Group

The SetSysColors function sets the colors for one or more display elements. Display elements are the various parts of a window and the Windows display that appear on the system display screen.

BOOL WINAPI SetSysColors(

int  cDspElements,	// number of elements to change
CONST INT  *lpnDspElements,	// address of array of elements
CONST COLORREF  *lpdwRgbValues	// address of array of RGB values
);
Parameters

cDspElements

Specifies the number of display elements in the array pointed to by the lpnDspElements parameter.

lpnDspElements

Points to an array of integers that specify the display elements to be changed. For a list of display elements, see the GetSysColor function.

lpdwRgbValues

Points to an array of unsigned long integers that contains the new red, green, blue (RGB) color value for each display element in the array pointed to by the lpnDspElements parameter.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The SetSysColors function sends a WM_SYSCOLORCHANGE message to all windows to inform them of the change in color. It also directs Windows to repaint the affected portions of all currently visible windows.

The SetSysColors function changes the current Windows session only. The new colors are not saved when Windows terminates.

See Also

GetSysColor


SetSysModalWindow
 SetSysModalWindow  QuickInfo  Overview  Group

The SetSysModalWindow function is not implemented in the Win32 API. The new input model does not allow for System Modal windows.


SetSystemCursor
 SetSystemCursor  QuickInfo  Overview  Group

The SetSystemCursor function replaces the contents of the system cursor specified by dwCursorId with the contents of the cursor specified by hCursor, and then destroys hCursor. This function lets an application customize the system cursors.

BOOL SetSystemCursor (

HCURSOR  hCursor,	// set specified system cursor to this cursor's contents,  // then destroy this
DWORD  dwCursorID	// system cursor specified by its identifier
);
Parameters

hCursor

Handle to a cursor. The function replaces the contents of the system cursor specified by dwCursorID with the contents of the cursor handled by hCursor. Then the function destroys hCursor by calling DestroyCursor(hCursor).

dwCursorID

A system cursor identifier. The function replaces the contents of this system cursor with the contents of the cursor handled by hCursor.

Following is a list of system cursor identifiers:

Value	Description
OCR_NORMAL	normal arrow cursor
OCR_IBEAM	I-beam cursor
OCR_WAIT	larger hourglass cursor
OCR_CROSS	crosshair cursor
OCR_UP	up arrow cursor
OCR_SIZE	size cursor
OCR_ICON	icon cursor
OCR_SIZENWSE	NW to SE sizing cursor
OCR_SIZENESW	NE to SW sizing cursor
OCR_SIZEWE	horizontal sizing cursor
OCR_SIZENS	vertical sizing cursor
OCR_SIZEALL	horizontal and vertical sizing cursor
OCR_SIZENO	international no symbol cursor
OCR_APPSTARTING	smaller hourglass with arrow cursor
Return Value

If the function succeeds, the return value is TRUE.

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

See Also

DestroyCursor, LoadCursor, LoadCursorFromFile, SetCursor


SetSystemPaletteUse
 SetSystemPaletteUse  QuickInfo  Overview  Group

The SetSystemPaletteUse function allows an application to specify whether the system palette contains 2 or 20 static colors. The default system palette contains 20 static colors. (Static colors cannot be changed when an application realizes a logical palette.)

UINT SetSystemPaletteUse(

HDC  hdc,	// handle of device context
UINT  uUsage	// palette-usage flag
);
Parameters

hdc

Identifies the device context. This device context must refer to a device that supports color palettes.

uUsage

Specifies the new use of the system palette. This parameter can be one of the following values:

Value	Meaning
SYSPAL_NOSTATIC	The system palette contains two static colors (black and white).
SYSPAL_STATIC	The system palette contains static colors that will not change when an application realizes its logical palette.
Return Value

If the function succeeds, the return value is the previous usage of the system palette (it can be either SYSPAL_NOSTATIC or SYSPAL_STATIC).

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

Remarks

An application can determine whether a device supports palette operations by calling the GetDeviceCaps function and specifying the RASTERCAPS constant.

When an application window moves to the foreground and the SYSPAL_NOSTATIC value is set, the application must call the GetSysColor function to save the current system colors setting. It must also call SetSysColors to set reasonable values using only black and white. When the application returns to the background or terminates, the previous system colors must be restored.

If the function returns SYSPAL_ERROR, the specified device context is invalid or does not support color palettes.

An application must call this function only when its window is maximized and has the input focus.

If an application calls SetSystemPaletteUse with uUsage set to SYSPAL_NOSTATIC, Windows continues to set aside two entries in the system palette for pure white and pure black, respectively.

After calling this function with uUsage set to SYSPAL_NOSTATIC, an application must take the following steps:

1.	Realize the logical palette.

2.	Call the GetSysColor function to save the current system-color settings.

3.	Call the SetSysColors function to set the system colors to reasonable values using black and white. For example, adjacent or overlapping items (such as window frames and borders) should be set to black and white, respectively.

4.	Send the WM_SYSCOLORCHANGE message to other top-level windows to allow them to be redrawn with the new system colors.

When the application's window loses focus or closes, the application must perform the following steps:

1.	Call SetSystemPaletteUse with the uUsage parameter set to SYSPAL_STATIC.

2.	Realize the logical palette.

3.	Restore the system colors to their previous values.

4.	Send the WM_SYSCOLORCHANGE message.

See Also

GetDeviceCaps, GetSysColor, SetSysColors


SetSystemPowerState [New - Windows 95]
 SetSystemPowerState  QuickInfo  Overview  Group

[New - Windows 95]

The SetSystemPowerState function suspends the system by shutting power down. Depending on the ForceFlag parameter, the function either suspends operation immediately or requests permission from all applications and device drivers before doing so.

BOOL SetSystemPowerState(

BOOL  fSuspend,
BOOL  fForce
);
Parameters

fSuspend

Suspension technique. If TRUE, the system suspends using RAM-alive technique. Otherwise, suspends using hibernate technique.

fForce

Forced suspension. If TRUE, the function sends a PBT_APMSUSPEND message to each application and driver, then immediately suspends operation. If FALSE, the function sends a PBT_APMQUERYSUSPEND message to each application to request permission to suspend operation.

Return Value

If power has been suspended and subsequently restored, the return value is TRUE.

If the system did not suspend, the return value is FALSE. To get extended error information, call GetLastError.

Remarks

If any application or driver denies permission to suspend operation, the function sends a PBT_APMQUERYSUSPENDFAILED message to each application and driver. If power is suspended, this function returns only after system operation is resumed and related WM_POWERBROADCAST messages have been sent to all applications and drivers.

See Also

PBT_APMQUERYSUSPEND, PBT_APMQUERYSUSPENDFAILED, PBT_APMSUSPEND, WM_POWERBROADCAST


SetSystemTime
 SetSystemTime  QuickInfo  Overview  Group

The SetSystemTime function sets the current system time and date. The system time is expressed in Coordinated Universal Time (UTC).

BOOL SetSystemTime(

CONST SYSTEMTIME *  lpst	// address of system time to set
);
Parameters

lpst

Points to a SYSTEMTIME structure that contains the current system date and time.

The wDayOfWeek member of the SYSTEMTIME structure is ignored.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The application must have system-time privilege (the SE_SYSTEMTIME_NAME privilege) for this function to succeed. This privilege is disabled by default. Use the AdjustTokenPrivileges function to enable the privilege and again to disable it after the time has been set.

For more information about security privileges, see Security.

See Also

AdjustTokenPrivileges, GetSystemTime, SetSystemTimeAdjustment, SYSTEMTIME, SystemTimeToTzSpecificLocalTime


SetSystemTimeAdjustment
 SetSystemTimeAdjustment  QuickInfo  Overview  Group

The SetSystemTimeAdjustment function tells the system to enable or disable periodic time adjustments to its time of day clock. Such time adjustments are used to synchronize the time of day with some other source of time information. When periodic time adjustments are enabled, they are applied at each clock interrupt.

BOOL SetSystemTimeAdjustment(

DWORD  dwTimeAdjustment,	// size, in 100-nanosecond units, of a periodic time adjustment
PBOOL  bTimeAdjustmentDisabled	// whether periodic time adjustment is to be disabled or enabled
);
Parameters

dwTimeAdjustment

Specifies the number of 100-nanosecond units added to the time-of-day clock at each clock interrupt if periodic time adjustment is enabled.

bTimeAdjustmentDisabled

Specifies the time adjustment mode that the system is to use. Periodic system time adjustments can be disabled or enabled.

A value of TRUE specifies that periodic time adjustment is to be disabled. The system is free to adjust time of day using its own internal mechanisms. The value of dwTimeAdjustment is ignored. The system's internal adjustment mechanisms may cause the time-of-day clock to jump noticeably when adjustments are made.

A value of FALSE specifies that periodic time adjustment is to be enabled, and will be used to adjust the time-of-day clock. The system will not interfere with the time adjustment scheme, and will not attempt to synchronize time of day on its own. The system will add the value of dwTimeAdjustment to the time of day at each clock interrupt.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To get extended error information, call GetLastError. One way the function can fail is if the caller does not possess the SE_SYSTEMTIME_NAME privilege.

Remarks

The GetSystemTimeAdjustment and SetSystemTimeAdjustment functions support algorithms that synchronize the time-of-day clock, reported via GetSystemTime and GetLocalTime, with another time source using a periodic time adjustment.

The SetSystemTimeAdjustment function supports two modes of time synchronization: time-adjustment − disabled and time-adjustment − enabled.

In the first mode, bTimeAdjustmentDisabled is set to FALSE.  At each clock interrupt, the system adds the value of dwTimeAdjustment to the time of day. The clock interrupt rate may be determined by calling GetSystemTimeAdjustment, and looking at the returned value of the DWORD value pointed to by lpTimeIncrement.

In the second mode, bTimeAdjustmentDisabled is set to TRUE.  At each clock interrupt, the system adds the interval between clock interrupts to the time of day. No adjustment to that interval is made. The system is free to periodically refresh the time-of-day clock using other techniques. Such other techniques may cause the time-of-day clock to jump noticeably when adjustments are made.

An application must have system-time privilege (the SE_SYSTEMTIME_NAME privilege) for this function to succeed. The SE_SYSTEMTIME_NAME privilege is disabled by default. Use the AdjustTokenPrivileges function to enable the privilege before calling SetSystemTimeAdjustment, and then to disable the privilege after the SetSystemTimeAdjustment call.

See Also

AdjustTokenPrivileges, GetSystemTimeAdjustment, SetLocalTime, SetSystemTime, SystemTimeToTzSpecificLocalTime


SetTapeParameters
 SetTapeParameters  QuickInfo  Overview  Group

The SetTapeParameters function either specifies the block size of a tape or configures the tape device.

DWORD SetTapeParameters(

HANDLE  hDevice,	// handle of open device
DWORD  dwOperation,	// type of information to set
LPVOID  lpTapeInformation	// address of buffer with information to set
);
Parameters

hDevice

Identifies the device for which to set configuration information. This handle is created by using the CreateFile function.

dwOperation

Specifies the type of information to set. This parameter must be one of the following values:

Value	Description
SET_TAPE_MEDIA_INFORMATION	Sets the tape-specific information specified by the lpTapeInformation parameter.
GET_TAPE_DRIVE_INFORMATION	Sets the device-specific information specified by lpTapeInformation.
lpTapeInformation

Points to a structure that contains the information to set. If the dwOperation parameter is SET_TAPE_MEDIA_INFORMATION, lpTapeInformation points to a TAPE_SET_MEDIA_PARAMETERS structure.

If dwOperation is SET_TAPE_DRIVE_INFORMATION, lpTapeInformation points to a TAPE_SET_DRIVE_PARAMETERS structure.

Return Value

If the function succeeds, the return value is NO_ERROR.

If the function fails, the return value is one of the following error codes:

Error	Description
ERROR_BEGINNING_OF_MEDIA	An attempt to access data before the beginning-of-medium marker failed.
ERROR_BUS_RESET	A reset condition was detected on the bus.
ERROR_END_OF_MEDIA	The end-of-tape marker was reached during an operation.
ERROR_FILEMARK_DETECTED	A filemark was reached during an operation.
ERROR_SETMARK_DETECTED	A setmark was reached during an operation.
ERROR_NO_DATA_DETECTED	The end-of-data marker was reached during an operation.
ERROR_PARTITION_FAILURE	The tape could not be partitioned.
ERROR_INVALID_BLOCK_LENGTH	The block size is incorrect on a new tape in a multivolume partition.
ERROR_DEVICE_NOT_PARTITIONED	The partition information could not be found when a tape was being loaded.
ERROR_MEDIA_CHANGED	The tape that was in the drive has been replaced or removed.
ERROR_NO_MEDIA_IN_DRIVE	There is no media in the drive.
ERROR_NOT_SUPPORTED	The tape driver does not support a requested function.
ERROR_UNABLE_TO_LOCK_MEDIA	An attempt to lock the ejection mechanism failed.
ERROR_UNABLE_TO_UNLOAD_MEDIA	An attempt to unload the tape failed.
ERROR_WRITE_PROTECT	The media is write protected.
See Also

GetTapeParameters, TAPE_SET_DRIVE_PARAMETERS, TAPE_SET_MEDIA_PARAMETERS


SetTapePosition
 SetTapePosition  QuickInfo  Overview  Group

The SetTapePosition sets the tape position on the specified device.

DWORD SetTapePosition(

HANDLE  hDevice,	// handle of open device
DWORD  dwPositionMethod,	// type of positioning to perform
DWORD  dwPartition,	// new tape partition
DWORD  dwOffsetLow,	// low-order 32 bits of tape position
DWORD  dwOffsetHigh,	// high-order 32 bits of tape position
BOOL  bImmediate	// return after operation begins
);
Parameters

hDevice

Identifies the device on which to set the tape position. This handle is created by using the CreateFile function.

dwPositionMethod

Specifies the type of positioning to perform. This parameter must be one of the following values:

Value	Meaning
TAPE_ABSOLUTE_BLOCK	Moves the tape to the device-specific block address specified by the dwOffsetLow and dwOffsetHigh parameters. The dwPartition parameter is ignored.
TAPE_LOGICAL_BLOCK	Moves the tape to the block address specified by dwOffsetLow and dwOffsetHigh in the partition specified by dwPartition.
TAPE_REWIND	Moves the tape to the beginning of the current partition. The dwPartition, dwOffsetLow, and dwOffsetHigh parameters are ignored.
TAPE_SPACE_END_OF_DATA	Moves the tape to the end of the data on the partition specified by dwPartition.
TAPE_SPACE_FILEMARKS	Moves the tape forward (or backward) the number of filemarks specified by dwOffsetLow and dwOffsetHigh in the current partition. The dwPartition parameter is ignored.
TAPE_SPACE_RELATIVE_BLOCKS	Moves the tape forward (or backward) the number of blocks specified by dwOffsetLow and dwOffsetHigh in the current partition. The dwPartition parameter is ignored.
TAPE_SPACE_SEQUENTIAL_FMKS	Moves the tape forward (or backward) to the first occurrence of n filemarks in the current partition, where n is the number specified by dwOffsetLow and dwOffsetHigh. The dwPartition parameter is ignored.
TAPE_SPACE_SEQUENTIAL_SMKS	Moves the tape forward (or backward) to the first occurrence of n setmarks in the current partition, where n is the number specified by dwOffsetLow and dwOffsetHigh. The dwPartition parameter is ignored.
TAPE_SPACE_SETMARKS	Moves the tape forward (or backward) the number of setmarks specified by dwOffsetLow and dwOffsetHigh in the current partition. The dwPartition parameter is ignored.
dwPartition

Specifies the partition to position within. If dwPartition is zero, the current partition is used. Partitions are numbered logically from 1 through n, where 1 is the first partition on the tape and n is the last.

dwOffsetLow

Specifies the low-order 32 bits of the block address or count for the position operation specified by the dwPositionMethod parameter.

dwOffsetHigh

Specifies the high-order 32 bits of the block address or count for the position operation specified by the dwPositionMethod parameter. If the high-order 32 bits are not required, this parameter should be zero.

bImmediate

Indicates whether to return as soon as the move operation begins. If this parameter is TRUE, the function returns immediately; if FALSE, the function does not return until the move operation has been completed.

Return Value

If the function succeeds, the return value is NO_ERROR.

If the function fails, the return value is one of the following error codes:

Error	Description
ERROR_BEGINNING_OF_MEDIA	An attempt to access data before the beginning-of-medium marker failed.
ERROR_BUS_RESET	A reset condition was detected on the bus.
ERROR_END_OF_MEDIA	The end-of-tape marker was reached during an operation.
ERROR_FILEMARK_DETECTED	A filemark was reached during an operation.
ERROR_SETMARK_DETECTED	A setmark was reached during an operation.
ERROR_NO_DATA_DETECTED	The end-of-data marker was reached during an operation.
ERROR_PARTITION_FAILURE	The tape could not be partitioned.
ERROR_INVALID_BLOCK_LENGTH	The block size is incorrect on a new tape in a multivolume partition.
ERROR_DEVICE_NOT_PARTITIONED	The partition information could not be found when a tape was being loaded.
ERROR_MEDIA_CHANGED	The tape that was in the drive has been replaced or removed.
ERROR_NO_MEDIA_IN_DRIVE	There is no media in the drive.
ERROR_NOT_SUPPORTED	The tape driver does not support a requested function.
ERROR_UNABLE_TO_LOCK_MEDIA	An attempt to lock the ejection mechanism failed.
ERROR_UNABLE_TO_UNLOAD_MEDIA	An attempt to unload the tape failed.
ERROR_WRITE_PROTECT	The media is write protected.
Remarks

If the offset specified by dwOffsetLow and dwOffsetHigh specifies the number of blocks, filemarks, or setmarks to move, a positive offset moves the tape forward to the end of the last block, filemark, or setmark. A negative offset moves the tape backward to the beginning of the last block, filemark, or setmark. If the offset is zero, the tape does not move.

To obtain information about the status, capabilities, and capacities of tape drives and media, call the GetTapeParameters function.

See Also

CreateFile, GetTapeParameters, GetTapePosition


SetTextAlign
 SetTextAlign  QuickInfo  Overview  Group

The SetTextAlign function sets the text-alignment flags for the specified device context.

UINT SetTextAlign(

HDC  hdc,	// handle of device context
UINT  fMode	// text-alignment flag
);
Parameters

hdc

Identifies the device context.

fMode

Specifies the text alignment by using a mask of the values in the following list. Only one flag can be chosen from those that affect horizontal and vertical alignment. In addition, only one of the two flags that alter the current position can be chosen.

Value	Meaning
TA_BASELINE	The reference point will be on the base line of the text.
TA_BOTTOM	The reference point will be on the bottom edge of the bounding rectangle.
TA_TOP	The reference point will be on the top edge of the bounding rectangle.
TA_CENTER	The reference point will be aligned horizontally with the center of the bounding rectangle.
TA_LEFT	The reference point will be on the left edge of the bounding rectangle.
TA_RIGHT	The reference point will be on the right edge of the bounding rectangle.
TA_NOUPDATECP	The current position is not updated after each text output call. The reference point is passed to the text output function.
TA_RTLREADING	Windows 95 only: The text is laid out in right to left reading order, as opposed to the default left to right order. This applies only when the font selected into the device context is either Hebrew or Arabic.
TA_UPDATECP	The current position is updated after each text output call. The current position is used as the reference point.
When the current font has a vertical default base line, as with Kanji, the following values must be used instead of TA_BASELINE and TA_CENTER:

Value	Meaning
VTA_BASELINE	The reference point will be on the base line of the text.
VTA_CENTER	The reference point will be aligned vertically with the center of the bounding rectangle.
The default values are TA_LEFT, TA_TOP, and TA_NOUPDATECP.

Return Value

If the function succeeds, the return value is the previous text-alignment setting.

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

Remarks

The TextOut and ExtTextOut functions use the text-alignment flags to position a string of text on a display or other device. The flags specify the relationship between a reference point and a rectangle that bounds the text. The reference point is either the current position or a point passed to a text output function.

The rectangle that bounds the text is formed by the character cells in the text string.

See Also

ExtTextOut, TextOut


SetTextCharacterExtra
 SetTextCharacterExtra  QuickInfo  Overview  Group

The SetTextCharacterExtra function sets the intercharacter spacing. Intercharacter spacing is added to each character, including break characters, when Windows writes a line of text.

int SetTextCharacterExtra(

HDC  hdc,	// handle of device context
int  nCharExtra	// extra-space value
);
Parameters

hdc

Identifies the device context.

nCharExtra

Specifies the amount of extra space, in logical units, to be added to each character. If the current mapping mode is not MM_TEXT, the nCharExtra parameter is transformed and rounded to the nearest pixel.

Return Value

If the function succeeds, the return value is the previous intercharacter spacing.

If the function fails, the return value is 0x80000000.

See Also

DrawText, GetTextCharacterExtra, TextOut


SetTextColor
 SetTextColor  QuickInfo  Overview  Group

The SetTextColor function sets the text color for the specified device context to the specified color.

COLORREF SetTextColor(

HDC  hdc,	// handle of device context
COLORREF  crColor	// text color
);
Parameters

hdc

Identifies the device context.

crColor

Specifies the color of the text.

Return Value

If the function succeeds, the return value is a color reference for the previous text color.

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

Remarks

The text color is used to draw the face of each character written by the TextOut and ExtTextOut functions. The text color is also used in converting bitmaps from color to monochrome and vice versa.

See Also

BitBlt, ExtTextOut, RGB, SetBkColor, StretchBlt, TextOut


SetTextJustification
 SetTextJustification  QuickInfo  Overview  Group

The SetTextJustification function specifies the amount of space Windows should add to the break characters in a string of text. The space is added when an application calls the TextOut or ExtTextOut functions.

BOOL SetTextJustification(

HDC  hdc,	// handle of device context
int  nBreakExtra,	// length of extra space, in logical units
int  nBreakCount	// count of space characters in line of text
);
Parameters

hdc

Identifies the device context.

nBreakExtra

Specifies the total extra space, in logical units, to be added to the line of text. If the current mapping mode is not MM_TEXT, the value identified by the nBreakExtra parameter is transformed and rounded to the nearest pixel.

nBreakCount

Specifies the number of break characters in the line.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The break character is usually the space character (ASCII 32), but it may be defined by a font as some other character. The GetTextMetrics function can be used to retrieve a font's break character.

The TextOut function distributes the specified extra space evenly among the break characters in the line.

The GetTextExtentPoint32 function is always used with the SetTextJustification function. The GetTextExtentPoint32 function computes the width of a given line before justification. This width must be known before an appropriate nBreakExtra value can be computed.

SetTextJustification can be used to justify a line that contains multiple strings in different fonts. In this case, each string must be justified separately.

Because rounding errors can occur during justification, Windows keeps a running error term that defines the current error value. When justifying a line that contains multiple runs, GetTextExtentPoint automatically uses this error term when it computes the extent of the next run, allowing TextOut to blend the error into the new run. After each line has been justified, this error term must be cleared to prevent it from being incorporated into the next line. The term can be cleared by calling SetTextJustification with nBreakExtra set to zero.

See Also

ExtTextOut, GetTextExtentPoint32, GetTextMetrics, TextOut


SetThreadAffinityMask
 SetThreadAffinityMask  QuickInfo  Overview  Group

The SetThreadAffinityMask function sets a processor affinity mask for a specified thread.

A thread affinity mask is a bit vector in which each bit represents the processors that a thread is allowed to run on.

A thread affinity mask must be a proper subset of the process affinity mask for the containing process of a thread. A thread is only allowed to run on the processors its process is allowed to run on.

DWORD SetThreadAffinityMask (

HANDLE  hThread,	// handle to the thread of interest
DWORD  dwThreadAffinityMask	// a thread affinity mask
);
Parameters

hThread

A handle to the thread whose affinity mask the function sets. This handle must have THREAD_SET_INFORMATION access.

dwThreadAffinityMask

Windows 95: This value must be 1.

Windows NT: Specifies an affinity mask for the thread.

Return Value

If the function succeeds, the return value is nonzero.

Windows 95: The return value is 1. To succeed, hThread must be valid and dwThreadAffinityMask must be 1.

Windows NT: The return value is the thread's previous affinity mask.

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

See Also

GetProcessAffinityMask


SetThreadContext
 SetThreadContext  QuickInfo  Overview  Group

The SetThreadContext function sets the context in the specified thread.

BOOL SetThreadContext(

HANDLE  hThread,	// handle of thread with context
CONST CONTEXT *  lpContext	// address of context structure
);
Parameters

hThread

Identifies an open handle of a thread whose context is to be written to. The handle must have THREAD_SET_CONTEXT access to the thread.

lpContext

Points to the address of a CONTEXT structure that contains the context to be set in the specified thread. The value of the ContextFlags member of this structure specifies which portions of a thread's context to set. Some values in the CONTEXT structure that cannot be specified are silently set to the correct value. This includes bits in the CPU status register that specify the privileged processor mode, global enabling bits in the debugging register, and other states that must be controlled by the operating system.

Return Value

If the context was set, the return value is TRUE.

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

Remarks

The function allows the selective context to be set based on the value of the ContextFlags member of the context structure. The thread handle identified by the hThread parameter is typically being debugged, but the function can also operate even when it is not being debugged.

See Also

CONTEXT, GetThreadContext


SetThreadDesktop [New - Windows NT]
 SetThreadDesktop  QuickInfo  Overview  Group

[New - Windows NT]

The SetThreadDesktop function assigns a desktop to the calling thread. All subsequent operations on the desktop use the access rights granted to hDesk.

BOOL SetThreadDesktop(

HDESK hDesk	// handle of the desktop to assign to this thread
);
Parameters

hDesk

Identifies the desktop to be assigned to the calling thread. This handle is returned by the CreateDesktop, GetThreadDesktop, and OpenDesktop functions.

This function will fail if the calling thread has any windows or hooks on its current desktop (unless hDesk is a handle to the current desktop).

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

CreateDesktop, GetThreadDesktop, OpenDesktop, SetProcessWindowStation


SetThreadLocale
 SetThreadLocale  QuickInfo  Overview  Group

The SetThreadLocale function sets the calling thread's current locale.

BOOL SetThreadLocale (

LCID  Locale	// locale identifier
);
Parameters

Locale

Specifies the new locale for the calling thread. This parameter can be a locale identifier created by the MAKELCID macro, or one of the following predefined values:

LOCALE_SYSTEM_DEFAULT	Default system locale.
LOCALE_USER_DEFAULT	Default user locale.
 For more information, see Locale Identifiers..

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

When a thread is created, it is given the system default thread locale. The system reads the system default thread locale from the registry when the system boots. This system default can be modified for future process and thread creation using Control Panel's International application.

See Also

GetThreadLocale, GetSystemDefaultLCID, GetUserDefaultLCID


SetThreadPriority
 SetThreadPriority  QuickInfo  Overview  Group

The SetThreadPriority function sets the priority value for the specified thread. This value, together with the priority class of the thread's process, determines the thread's base priority level.

BOOL SetThreadPriority(

HANDLE  hThread,	// handle to the thread
int  nPriority	// thread priority level
);
Parameters

hThread

Identifies the thread. The handle must have THREAD_SET_INFORMATION access.

nPriority

Specifies the priority value for the thread. This parameter can be one of the following values:

Priority	Meaning
THREAD_PRIORITY_ABOVE_NORMAL	Indicates 1 point above normal priority for the priority class.
THREAD_PRIORITY_BELOW_NORMAL	Indicates 1 point below normal priority for the priority class.
THREAD_PRIORITY_HIGHEST	Indicates 2 points above normal priority for the priority class.
THREAD_PRIORITY_IDLE	Indicates a base priority level of 1 for IDLE_PRIORITY_CLASS, NORMAL_PRIORITY_CLASS, or HIGH_PRIORITY_CLASS processes, and a base priority level of 16 for REALTIME_PRIORITY_CLASS processes.
THREAD_PRIORITY_LOWEST	Indicates 2 points below normal priority for the priority class.
THREAD_PRIORITY_NORMAL	Indicates normal priority for the priority class.
THREAD_PRIORITY_TIME_CRITICAL	Indicates a base priority level of 15 for IDLE_PRIORITY_CLASS, NORMAL_PRIORITY_CLASS, or HIGH_PRIORITY_CLASS processes, and a base priority level of 31 for REALTIME_PRIORITY_CLASS processes.
Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

Every thread has a base priority level determined by the thread's priority value and the priority class of its process. The system uses the base priority level of all executable threads to determine which thread gets the next slice of CPU time. Threads are scheduled in a round-robin fashion at each priority level, and only when there are no executable threads at a higher level does scheduling of threads at a lower level take place.

The SetThreadPriority function enables setting the base priority level of a thread relative to the priority class of its process. For example, specifying THREAD_PRIORITY_HIGHEST in a call to SetThreadPriority for a thread of an IDLE_PRIORITY_CLASS process sets the thread's base priority level to 6. For a table that shows the base priority levels for each combination of priority class and thread priority value, see the SetPriorityClass function.

For IDLE_PRIORITY_CLASS, NORMAL_PRIORITY_CLASS, and HIGH_PRIORITY_CLASS processes, the system dynamically boosts a thread's base priority level when events occur that are important to the thread. REALTIME_PRIORITY_CLASS processes do not receive dynamic boosts.

All threads initially start at THREAD_PRIORITY_NORMAL. Use the GetPriorityClass and SetPriorityClass functions to get and set the priority class of a process. Use the GetThreadPriority function to get the priority value of a thread.

Use the priority class of a process to differentiate between applications that are time critical and those that have normal or below normal scheduling requirements. Use thread priority values to differentiate the relative priorities of the tasks of a process. For example, a thread that handles input for a window could have a higher priority level than a thread that performs intensive calculations for the CPU.

When manipulating priorities, be very careful  to ensure that a high-priority thread does not consume all of the available CPU time. A thread with a base priority level above 11 interferes with the normal operation of the operating system. Using REALTIME_PRIORITY_CLASS may cause disk caches to not flush, hang the mouse, and so on.

See Also

GetPriorityClass, GetThreadPriority, SetPriorityClass


SetThreadToken [New - Windows NT]
 SetThreadToken  QuickInfo  Overview  Group

[New - Windows NT]

The SetThreadToken function assigns an impersonation token to a thread. The function can also cause a thread to stop using an impersonation token.

BOOL SetThreadToken(

PHANDLE  Thread,	// points to a handle to the thread
HANDLE  Token	// handle to the impersonation token
);
Parameters

Thread

Points to a handle to the thread to which the function assigns the impersonation token.

If Thread is NULL, the function assigns the impersonation token to the calling thread.

Token

An open handle to the impersonation token to assign to the thread.

This handle must have been opened with TOKEN_IMPERSONATE access rights.

If Token is NULL, the function causes the thread to stop using an impersonation token.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

OpenThreadToken


SetTimer
 SetTimer  QuickInfo  Overview  Group

The SetTimer function creates a timer with the specified time-out value.

UINT SetTimer(

HWND  hwnd,	// handle of window for timer messages
UINT  idTimer,	// timer identifier
UINT  uTimeout,	// time-out value
TIMERPROC  tmprc	// address of timer procedure
);
Parameters

hwnd

Identifies the window to be associated with the timer. If this parameter is NULL, no window is associated with the timer and the idTimer parameter is ignored.

idTimer

Specifies a nonzero timer identifier. If the hwnd parameter is NULL, this parameter is ignored.

uTimeout

Specifies the time-out value, in milliseconds.

tmprc

Points to the function to be notified when the time-out value elapses. For more information about the function, see the TimerProc callback function.

If tmprc 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 Value

If the function succeeds, the return value is an integer identifying the new timer. An application can pass this value, or the string identifier, if it exists, to the KillTimer function to destroy the timer. If the function fails to create a timer, the return value is zero.

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.

The wParam parameter of the WM_TIMER message contains the value of the idTimer parameter.

See Also

KillTimer, MSG, TimerProc, WM_TIMER


SetTimeZoneInformation
 SetTimeZoneInformation  QuickInfo  Overview  Group

The SetTimeZoneInformation function sets the current time-zone parameters. These parameters control translations from Coordinated Universal Time (UTC) to local time.

BOOL SetTimeZoneInformation(

CONST TIME_ZONE_INFORMATION *  lptzi	// address of time-zone settings
);
Parameters

lptzi

Points to a TIME_ZONE_INFORMATION structure that contains the time-zone parameters to set.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

All translations between UTC and local time are based on the following formula:

UTC = local time + bias

The bias is the difference, in minutes, between UTC and local time.

See Also

GetTimeZoneInformation, TIME_ZONE_INFORMATION


SetTokenInformation
 SetTokenInformation  QuickInfo  Overview  Group

The SetTokenInformation function sets various types of information for a specified access token. The information it sets replaces existing information. The calling process must have appropriate access rights to set the information.

BOOL SetTokenInformation(

HANDLE  hToken,	// handle of access token
TOKEN_INFORMATION_CLASS  tic,	// type of information to set
LPVOID  lpvInformation,	// address of information to set
DWORD  cbInformation	// size of information buffer
);
Parameters

hToken

Identifies the access token for which information is to be set.

tic

Specifies a variable of the TOKEN_INFORMATION_CLASS enumerated type identifying the type of information the function sets. The valid values from TOKEN_INFORMATION_CLASS are TokenOwner, TokenPrimaryGroup, and TokenDefaultDacl. For more information about these values, see the description of the lpvInformation parameter, following.

lpvInformation

Points to a buffer containing the information set in the access token. The structure of this buffer depends on the type of information specified by the tic parameter. The following three values are valid in calls to this function:

Token Information Class	Structure Provided
TokenOwner	TOKEN_OWNER structure. TOKEN_ADJUST_DEFAULT access is needed to set owner information. A valid owner value is a user or group identifier with an attribute allowing assignment as the owner of objects.
TokenPrimaryGroup	TOKEN_PRIMARY_GROUP structure. TOKEN_ADJUST_DEFAULT access is needed to set primary group information.
TokenDefaultDacl	TOKEN_DEFAULT_DACL structure. TOKEN_ADJUST_DEFAULT access is needed to set information in the default discretionary access-control list (ACL). The ACL structure provided as a new default discretionary ACL is not validated for correctness or consistency. If the lpvInformation parameter is NULL, the current default discretionary ACL is removed and no replacement is established.
The formats for the structures this function can set are listed in the following Remarks section.

cbInformation

Specifies the length, in bytes, of the buffer pointed to by lpvInformation.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

To set privilege information, an application can call the AdjustTokenPrivileges function. To set a token's groups, an application can call the AdjustTokenGroups function.

Token-type information can be set only when an access token is created.

See Also

AdjustTokenGroups, AdjustTokenPrivileges, GetTokenInformation, OpenProcessToken, OpenThreadToken, TOKEN_DEFAULT_DACL, TOKEN_INFORMATION_CLASS, TOKEN_OWNER, TOKEN_PRIMARY_GROUP


SetUnhandledExceptionFilter
 SetUnhandledExceptionFilter  QuickInfo  Overview  Group

The SetUnhandledExceptionFilter function lets an application supersede the top-level exception handler that Win32 places at the top of each thread and process.

After calling this function, if an exception occurs in a process that is not being debugged, and the exception makes it to the Win32 unhandled exception filter, that filter will call the exception filter function specified by the lpTopLevelExceptionFilter parameter.

LPTOP_LEVEL_EXCEPTION_FILTER SetUnhandledExceptionFilter(

LPTOP_LEVEL_EXCEPTION_FILTER  lpTopLevelExceptionFilter	// exception filter function
);
Parameters

lpTopLevelExceptionFilter

Supplies the address of a top-level exception filter function that will be called whenever the UnhandledExceptionFilter function gets control, and the process is not being debugged. A value of NULL for this parameter specifies default handling within UnhandledExceptionFilter.

The filter function has syntax congruent to that of UnhandledExceptionFilter: It takes a single parameter of type LPEXCEPTION_POINTERS, and returns a value of type LONG. The filter function should return one of the following values:

Value	Meaning
EXCEPTION_EXECUTE_HANDLER	Return from UnhandledExceptionFilter and execute the associated exception handler. This usually results in process termination.
EXCEPTION_CONTINUE_EXECUTION	Return from UnhandledExceptionFilter and continue execution from the point of the exception. Note that the filter function is free to modify the continuation state by modifying the exception information supplied through its LPEXCEPTION_POINTERS parameter.
EXCEPTION_CONTINUE_SEARCH	Proceed with normal execution of UnhandledExceptionFilter . That means obeying the SetErrorMod flags, or invoking the Application Error pop-up message box.
Return Value

The SetUnhandledExceptionFilter function returns the address of the previous exception filter established with the function. A NULL return value means that there is no current top-level exception handler.

Remarks

Issuing SetUnhandledExceptionFilter replaces the existing top-level exception filter for all existing and all future threads in the calling process.

The exception handler specified by lpTopLevelExceptionFilter is executed in the context of the thread that caused the fault. This can affect the exception handler's ability to recover from certain exceptions, such as an invalid stack.

See Also

UnhandledExceptionFilter


SetupComm
 SetupComm  QuickInfo  Overview  Group

The SetupComm function initializes the communications parameters for a specified communications device.

BOOL SetupComm(

HANDLE  hCommDev,	// handle of communications device
DWORD  cbInQueue,	// size of input buffer
DWORD  cbOutQueue	// size of output buffer
);
Parameters

hCommDev

Identifies the communications device. The CreateFile function returns this handle.

cbInQueue

Specifies the recommended size, in bytes, of the device's internal input buffer.

cbOutQueue

Specifies the recommended size, in bytes, of the device's internal output buffer.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

After a process uses the CreateFile function to open a handle to a communications device, it can call SetupComm to set the communications parameters for the device. If it does not set them, the device uses the default parameters when the first call to another communications function occurs.

The cbInQueue and cbOutQueue parameters specify the recommended sizes for the internal buffers used by the driver for the specified device. For example, YMODEM protocol packets are slightly larger than 1024 bytes. Therefore, a recommended buffer size might be 1200 bytes for YMODEM communications. For Ethernet-based communications, a recommended buffer size might be 1600 bytes, which is slightly larger than a single Ethernet frame.

The device driver receives the recommended buffer sizes, but is free to use any input and output (I/O) buffering scheme, as long as it provides reasonable performance and data is not lost due to overrun (except under extreme circumstances). For example, the function can succeed even though the driver does not allocate a buffer, as long as some other portion of the operating system provides equivalent functionality.

If the device driver determines that the recommended buffer sizes involve transfers beyond its ability to handle, the function can fail.

See Also

CreateFile, SetCommState


SetUserObjectInformation [New - Windows NT]
 SetUserObjectInformation  QuickInfo  Overview  Group

[New - Windows NT]

The SetUserObjectInformation function sets information about a window station or desktop object.

BOOL SetUserObjectInformation(

HANDLE hObject	// handle of the object for which to set information
int nIndex	// type of information to set
PVOID lpvInfo	// points to a buffer that contains the information
DWORD cbInfo	// size, in bytes, of lpvInfo buffer
);
Parameters

hObject

Identifies the window station or desktop object for which to set object information. This value can be an HDESK or HWINSTA handle (for example, a handle returned by CreateWindowStation, OpenWindowStation, CreateDesktop, or OpenDesktop).

nIndex

Specifies the object information to be set. This parameter must specify the following value:

Value	Description
UOI_FLAGS	Sets the object's handle flags. The lpvInfo parameter must point to a USEROBJECTFLAGS structure.
lpvInfo

Points to a buffer containing the object information.

cbInfo

Specifies the size, in bytes, of the information contained in the buffer pointed to by lpvInfo.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

CreateDesktop, CreateWindowStation, GetUserObjectInformation, OpenDesktop,.OpenWindowStation, USEROBJECTFLAGS


SetUserObjectSecurity
 SetUserObjectSecurity  QuickInfo  Overview  Group

The SetUserObjectSecurity function sets the security of a user object. This can be, for example, a window or a DDE conversation.

BOOL SetUserObjectSecurity(

HANDLE  hObject,	// handle of user object
PSECURITY_INFORMATION  psi,	// address of security information
PSECURITY_DESCRIPTOR  psd	// address of security descriptor
);
Parameters

hObject

Identifies a user object for which security information is set.

psi

Points to a SECURITY_INFORMATION structure describing the security information being set.

psd

Points to a SECURITY_DESCRIPTOR structure containing the new security information.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The SetUserObjectSecurity function applies changes specified in a security descriptor to the security descriptor assigned to a user object. The object's security descriptor must be in self-relative form. If necessary, this function allocates additional memory to increase the size of the security descriptor.

The SetUserObjectSecurity function is successful only if the following conditions are met:

•	If the object's owner is being set, the calling process must either have WRITE_OWNER permission or be the object's owner.

•	If the object's discretionary access-control list (ACL) is being set, the calling process must either have WRITE_DAC permission or be the object's owner.

•	If the object's system ACL is being set, the SE_SECURITY_NAME privilege must be enabled for the calling process.

See Also

GetUserObjectSecurity, SECURITY_DESCRIPTOR, SECURITY_INFORMATION, SetFileSecurity, SetKernelObjectSecurity, SetPrivateObjectSecurity


 SetViewportExt

The SetViewportExt function is not implemented in the Win32 API. Win32-based applications should use the SetViewportExtEx function.


SetViewportExtEx
 SetViewportExtEx  QuickInfo  Overview  Group

The SetViewportExtEx function sets the horizontal and vertical extents of the viewport for a device context by using the specified values.

BOOL SetViewportExtEx(

HDC  hdc,	// handle of device context
int  nXExtent,	// new horizontal viewport extent
int  nYExtent,	// new vertical viewport extent
LPSIZE  lpSize	// original viewport extent
);
Parameters

hdc

Identifies the device context.

nXExtent

Specifies the horizontal extent, in device units, of the viewport.

nYExtent

Specifies the vertical extent, in device units, of the viewport.

lpSize

Points to a SIZE structure. The previous viewport extents (in device units) are placed in this structure. If lpSize is NULL, nothing is returned.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

When the following mapping modes are set, calls to the SetWindowExtEx and SetViewportExtEx functions are ignored.

•	MM_HIENGLISH

•	MM_HIMETRIC

•	MM_LOENGLISH

•	MM_LOMETRIC

•	MM_TEXT

•	MM_TWIPS

When MM_ISOTROPIC mode is set, an application must call the SetWindowExtEx function before it calls SetViewportExtEx.

See Also

GetViewportExtEx, SetWindowExtEx, SIZE,


 SetViewportOrg

The SetViewportOrg function is not implemented in the Win32 API. Win32-based applications should use the SetViewportOrgEx function.


SetViewportOrgEx
 SetViewportOrgEx  QuickInfo  Overview  Group

The SetViewportOrgEx function sets the viewport origin of a device context by using the specified coordinates.

BOOL SetViewportOrgEx(

HDC  hdc,	// handle of device context
int  X,	// new x-coordinate of viewport origin
int  Y,	// new y-coordinate of viewport origin
LPPOINT  lpPoint	// address of structure receiving original origin
);
Parameters

hdc

Identifies the device context.

X

Specifies the x-coordinate, in device units, of the new viewport origin.

Y

Specifies the y-coordinate, in device units, of the new viewport origin.

lpPoint

Points to a POINT structure. The previous viewport origin (in device coordinates) is placed in this structure. If lpPoint is NULL, nothing is returned.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

See Also

GetViewportOrgEx, POINT, SetWindowOrgEx


 SetVoiceAccent

The SetVoiceAccent function is not implemented in the Win32 API.

See Also

Beep, MessageBeep


 SetVoiceEnvelope

The SetVoiceEnvelope function is not implemented in the Win32 API.

See Also

Beep, MessageBeep


 SetVoiceNote

The SetVoiceNote function is not implemented in the Win32 API.

See Also

Beep, MessageBeep


 SetVoiceQueueSize

The SetVoiceQueueSize function is not implemented in the Win32 API.

See Also

Beep, MessageBeep


 SetVoiceSound

The SetVoiceSound function is not implemented in the Win32 API.

See Also

Beep, MessageBeep


 SetVoiceThreshold

The SetVoiceThreshold function is not implemented in the Win32 API.

See Also

Beep, MessageBeep


SetVolumeLabel
 SetVolumeLabel  QuickInfo  Overview  Group

The SetVolumeLabel function sets the label of a file system volume.

BOOL SetVolumeLabel(

LPCTSTR  lpRootPathName,	// address of name of root directory for volume
LPCTSTR  lpVolumeName	// name for the volume
);
Parameters

lpRootPathName

Points to a null-terminated string specifying the root directory of a file system volume. This is the volume the function will label. If this parameter is NULL, the root of the current directory is used.

lpVolumeName

Points to a string specifying a name for the volume. If this parameter is NULL, the function deletes the name of the specified volume.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

GetVolumeInformation


SetWindowContextHelpId [New - Windows NT]
 SetWindowContextHelpId  QuickInfo  Overview  Group

[New - Windows NT]

The SetWindowContextHelpId function associates a help context identifier with the specified window.

BOOL SetWindowContextHelpId(

HWND  hwnd,
DWORD  dwContextHelpId
);
Parameters

hwnd

Handle to the window with which to associate the help context identifier.

dwContextHelpId

Help context identifier.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

If a child window does not have a help context identifier, it inherits the identifier of its parent window. Likewise, if an owned window does not have a help context identifier, it inherits the identifier of its owner window. This inheritance of help context identifiers allows an application to set just one identifier for a dialog box and all of its controls.


 SetWindowExt

The SetWindowExt function is not implemented in the Win32 API. Win32-based applications should use the SetWindowExtEx function.


SetWindowExtEx
 SetWindowExtEx  QuickInfo  Overview  Group

The SetWindowExtEx function sets the horizontal and vertical extents of the window for a device context by using the specified values.

BOOL SetWindowExtEx(

HDC  hdc,	// handle of device context
int  nXExtent,	// new horizontal window extent
int  nYExtent,	// new vertical window extent
LPSIZE  lpSize	// original window extent
);
Parameters

hdc

Identifies the device context.

nXExtent

Specifies the window's horizontal extent in logical units.

nYExtent

Specifies the window's vertical extent in logical units.

lpSize

Points to a SIZE structure. The previous window extents (in logical units) are placed in this structure. If lpSize is NULL, nothing is returned.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

When the following mapping modes are set, calls to the SetWindowExtEx and SetViewportExtEx functions are ignored:

•	MM_HIENGLISH

•	MM_HIMETRIC

•	MM_LOENGLISH

•	MM_LOMETRIC

•	MM_TEXT

•	MM_TWIPS

When MM_ISOTROPIC mode is set, an application must call the SetWindowExtEx function before calling SetViewportExtEx.

See Also

GetWindowExtEx, SetViewportExtEx, SIZE


SetWindowLong
 SetWindowLong  QuickInfo  Overview  Group

The SetWindowLong function changes an attribute of the specified window. The function also sets a 32-bit (long) value at the specified offset into the extra window memory of a window.

LONG SetWindowLong(

HWND  hwnd,	// handle of window
int  nIndex,	// offset of value to set
LONG  lNewLong	// new value
);
Parameters

hwnd

Identifies the window and, indirectly, the class to which the window belongs.

nIndex

Specifies the zero-based offset to the value to be set. Valid values are in the range zero through the number of bytes of extra window memory, minus 4; for example, if you specified 12 or more bytes of extra memory, a value of 8 would be an index to the third 32-bit integer. To set any other value, specify one of the following values:

Value	Action
GWL_EXSTYLE	Sets a new extended window style.
GWL_STYLE	Sets a new window style.
GWL_WNDPROC	Sets a new address for the window procedure.
GWL_HINSTANCE	Sets a new application instance handle.
GWL_ID	Sets a new identifier of the window.
GWL_USERDATA	Sets the 32-bit value associated with the window. Each window has a corresponding 32-bit value intended for use by the application that created the window.
The following values are also available when the hwnd parameter identifies a dialog box:

Value	Action
DWL_DLGPROC	Sets the new address of the dialog box procedure.
DWL_MSGRESULT	Sets the return value of a message processed in the dialog box procedure.
DWL_USER	Sets new extra information that is private to the application, such as handles or pointers.
lNewLong

Specifies the replacement value.

Return Value

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

Remarks

The SetWindowLong function fails if the window specified by the hwnd parameter does not belong to the same process as the calling thread.

If you use the SetWindowLong function and 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.

Calling SetWindowLong with the GWL_WNDPROC index creates a subclass of the window class used to create the window. An application should not subclass a window created by another process. The SetWindowLong function creates the window subclass by changing the window procedure associated with a particular window, causing Windows 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 WNDCLASS structure used with the RegisterClass function.

You must not call SetWindowLong with the GWL_HWNDPARENT index to change the parent of a child window. Instead, use the SetParent function.

See Also

CallWindowProc, GetWindowLong, GetWindowWord, RegisterClass, SetParent, SetWindowWord, WindowProc, WNDCLASS


 SetWindowOrg

The SetWindowOrg function is not implemented in the Win32 API. Win32-based applications should use the SetWindowOrgEx function.


SetWindowOrgEx
 SetWindowOrgEx  QuickInfo  Overview  Group

The SetWindowOrgEx function sets the window origin of the device context by using the specified coordinates.

BOOL SetWindowOrgEx(

HDC  hdc,	// handle of device context
int  X,	// new x-coordinate of window origin
int  Y,	// new y-coordinate of window origin
LPPOINT  lpPoint	// address of structure receiving original origin
);
Parameters

hdc

Identifies the device context.

X

Specifies the logical x-coordinate of the new window origin.

Y

Specifies the logical y-coordinate of the new window origin.

lpPoint

Points to a POINT structure. The previous origin of the window is placed in this structure. If lpPoint is NULL, nothing is returned.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

See Also

GetViewportOrgEx, GetWindowOrgEx, POINT, SetViewportOrgEx


SetWindowPlacement
 SetWindowPlacement  QuickInfo  Overview  Group

The SetWindowPlacement function sets the show state and the restored, minimized, and maximized positions of the specified window.

BOOL SetWindowPlacement(

HWND  hwnd,	// handle of window
CONST WINDOWPLACEMENT *  lpwndpl	// address of structure with position data
);
Parameters

hwnd

Identifies the window.

lpwndpl

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

Windows 95 only: SetWindowPlacement fails if lpwndpl->length is not set correctly.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

GetWindowPlacement, WINDOWPLACEMENT


SetWindowPos
 SetWindowPos  QuickInfo  Overview  Group

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 of window
HWND  hwndInsertAfter,	// placement-order handle
int  x,	// horizontal position
int  y,	// vertical position
int  cx,	// width
int  cy,	// height
UINT  fuFlags	// window-positioning flags
);
Parameters

hwnd

Identifies the window.

hwndInsertAfter

Identifies the window to precede the positioned window in the Z order. This parameter must be a window handle or one of the following values:

Value	Meaning
HWND_BOTTOM	Places the window at the bottom of the Z order. If the hwnd parameter identifies a topmost window, the window loses its topmost status and is placed at the bottom of all other windows.
HWND_NOTOPMOST	Places the window above all non-topmost windows (that is, behind all topmost windows). This flag has no effect if the window is already a non-topmost window.
HWND_TOP	Places the window at the top of the Z order.
HWND_TOPMOST	Places the window above all non-topmost windows. The window maintains its topmost position even when it is deactivated.
For more information about how this parameter is used, see the following Remarks section.

x

Specifies the new position of the left side of the window.

y

Specifies the new position of the top of the window.

cx

Specifies the new width of the window, in pixels.

cy

Specifies the new height of the window, in pixels.

fuFlags

Specifies the window sizing and positioning flags. This parameter can be a combination 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_NOSIZE	Retains the current size (ignores the cx and cy parameters).
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_NOZORDER	Retains the current Z order (ignores the hwndInsertAfter parameter).
SWP_SHOWWINDOW	Displays the window.
Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. 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.

All coordinates for child windows are client coordinates (relative to the upper-left corner of the parent window's client area).

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.

See Also

MoveWindow, SetActiveWindow, SetForegroundWindow


SetWindowRgn [New - Windows NT]
 SetWindowRgn  QuickInfo

[New - Windows NT]

The SetWindowRgn function sets the window region of a window. The window region determines the area within the window where the operating system permits drawing. The operating system does not display any portion of a window that lies outside of the window region

int SetWindowRgn(

HWND  hWnd,	// handle to window whose window region is to be set
HRGN  hRgn,	// handle to region
BOOL  bRedraw	// window redraw flag
);
Parameters

hWnd

Handle to the window whose window region is to be set.

hRgn

Handle to a region. The function sets the window region of the window to this region.

If hRgn is NULL, the function sets the window region to NULL.

bRedraw

Boolean value that specifies whether the operating system redraws the window after setting the window region. If bRedraw is TRUE, the operating system does so; otherwise, it does not.

Typically, you set bRedraw to TRUE if the window is visible.

Return Value

If the function succeeds, the return value is non-zero.

If the function fails, the return value is zero.

Comments

If the bRedraw parameter is TRUE, the system sends the WM_WINDOWPOSCHANGING and WM_WINDOWPOSCHANGED messages to the window.

The coordinates of a window's window region are relative to the upper-left corner of the window, not the client area of the window.

After a successful call to SetWindowRgn, the operating system owns the region specified by the region handle hRgn. The operating system does not make a copy of the region. Thus, you should not make any further function calls with this region handle. In particular, do not close this region handle.

To obtain the window region of a window, call the GetWindowRgn function.

See Also

GetWindowRgn, WM_WINDOWPOSCHANGING


SetWindowsHook
 SetWindowsHook  QuickInfo  Overview  Group

The SetWindowsHook function is not implemented in the Win32 API. Win32-based applications should use the SetWindowsHookEx function.


SetWindowsHookEx
 SetWindowsHookEx  QuickInfo  Overview  Group

The SetWindowsHookEx function installs an application-defined hook procedure into a hook chain. An application installs a hook procedure to monitor the system for certain types of events. A hook procedure can monitor events associated either with a specific thread or with all threads in the system. This function supersedes the SetWindowsHook function.

HHOOK SetWindowsHookEx(

int  idHook,	// type of hook to install
HOOKPROC  hkprc,	// address of hook procedure
HINSTANCE  hMod,	// handle of application instance
DWORD  dwThreadID	// identity of thread to install hook for
);
Parameters

idHook

Specifies the type of hook procedure to be installed. This parameter can be one of the following values:

Value	Description
WH_CALLWNDPROC	Installs a hook procedure that monitors messages before the system sends them to the destination window procedure. For more information,  the CallWndProc hook procedure.
WH_CALLWNDPROCRET	Windows 95 only: Installs a hook procedure that monitors messages after they have been processed by the destination window procedure. For more information, see  the CallWndRetProc hook procedure.
WH_CBT	Installs a hook procedure that receives notifications useful to a computer-based training (CBT) application. For more information, see the CBTProc hook procedure.
WH_DEBUG	Installs a hook procedure useful for debugging other hook procedures. For more information, see the DebugProc hook procedure.
WH_GETMESSAGE	Installs a hook procedure that monitors messages posted to a message queue. For more information, see the GetMsgProc hook procedure.
WH_JOURNALPLAYBACK	Installs a hook procedure that posts messages previously recorded by a WH_JOURNALRECORD hook procedure. For more information, see the JournalPlaybackProc hook procedure.
WH_JOURNALRECORD	Installs a hook procedure that records input messages posted to the system message queue. This hook is useful for recording macros. For more information, see the JournalRecordProc hook procedure.
WH_KEYBOARD	Installs a hook procedure that monitors keystroke messages. For more information, see the KeyboardProc hook procedure.
WH_MOUSE	Installs a hook procedure that monitors mouse messages. For more information, see the MouseProc hook procedure.
WH_MSGFILTER	Installs a hook procedure that monitors messages generated as a result of an input event in a dialog box, message box, menu, or scroll bar. For more information, see  the MessageProc hook procedure.
WH_SHELL	Installs a hook procedure that receives notifications useful to shell applications. For more information, see  the ShellProc hook procedure.
WH_SYSMSGFILTER	Installs a hook procedure that monitors messages generated as a result of an input event in a dialog box, message box, menu, or scroll bar. The hook procedure monitors these messages for all applications in the system. For more information, see  the SysMsgProc hook procedure.
hkprc

Points to the hook procedure. If the dwThreadID parameter is zero or specifies the identifier of a thread created by a different process, the hkprc parameter must point to a hook procedure in a dynamic-link library (DLL). Otherwise, hkprc can point to a hook procedure in the code associated with the current process.

hMod

Identifies the DLL containing the hook procedure pointed to by the hkprc parameter. The hMod parameter must be set to NULL if the dwThreadID parameter specifies a thread created by the current process and if the hook procedure is within the code associated with the current process.

dwThreadID

Specifies the identifier of the thread with which the hook procedure is to be associated. If this parameter is zero, the hook procedure is associated with all existing threads.

Return Value

If the function succeeds, the return value is the handle of the hook procedure.

If the function fails, the return value is NULL.

Remarks

An error may occur if the hMod parameter is NULL and the dwThreadId parameter is zero or specifies the identifier of a thread created by another process.

Chaining to the next hook procedure (that is, calling the CallNextHookEx function) is optional. An application or library can call the next hook procedure either before or after any processing in its own hook procedure.

Before terminating, an application must call the UnhookWindowsHookEx function to free system resources associated with the hook.

The scope of a hook depends on the hook type. Some hooks can be set only with system scope; others can also be set for only a specific thread, as shown in the following list:

Hook	Scope
WH_CALLWNDPROC	Thread or system
WH_CBT	Thread or system
WH_DEBUG	Thread or system
WH_GETMESSAGE	Thread or system
WH_JOURNALPLAYBACK	System only
WH_JOURNALRECORD	System only
WH_KEYBOARD	Thread or system
WH_MOUSE	Thread or system
WH_MSGFILTER	Thread or system
WH_SHELL	Thread or system
WH_SYSMSGFILTER	System only
For a specified hook type, thread hooks are called first, then system hooks.

The system hooks are a shared resource, and installing one affects all applications. All system hook functions must be in libraries. System hooks should be restricted to special-purpose applications or to use as a development aid during application debugging. Libraries that no longer need a hook should remove the hook procedure.

See Also

CallNextHookEx, CallWndProc, CBTProc, DebugProc, GetMsgProc, JournalPlaybackProc, JournalRecordProc, KeyboardProc, MouseProc, MessageProc, ShellProc, SysMsgProc, UnhookWindowsHookEx


SetWindowText
 SetWindowText  QuickInfo  Overview  Group

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.

BOOL SetWindowText(

HWND  hwnd,	// handle of window or control
LPCTSTR  lpsz	// address of string
);
Parameters

hwnd

Identifies the window or control whose text is to be changed.

lpsz

Points to a null-terminated string to be used as the new title or control text.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The SetWindowText function causes a WM_SETTEXT message to be sent to the specified window or control. If the window is a list box control created with the WS_CAPTION style, however, SetWindowText sets the text for the control, not for the list box entries.

The SetWindowText function does not expand tab characters (ASCII code 0x09). Tab characters are displayed as vertical bar (|) characters.

See Also

GetWindowText, WM_SETTEXT


SetWindowWord
 SetWindowWord  QuickInfo  Overview  Group

The SetWindowWord function replaces the 16-bit (word) value at the specified offset into the extra window memory for the specified window.

WORD SetWindowWord(

HWND  hwnd,	// handle of window
int  nIndex,	// offset of value to set
WORD  wNewWord	// new value
);
Parameters

hwnd

Identifies the window and, indirectly, the class to which the window belongs.

nIndex

Specifies the zero-based byte offset of the value to be replaced. Valid values are in the range zero through the number of bytes of window memory, minus two; for example, if you specified 10 or more bytes of extra window memory, a value of 8 would be an index to the fifth 16-bit integer.

wNewWord

Specifies the replacement value.

Return Value

If the function succeeds, the return value is the previous value of the specified 16-bit integer.

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

Remarks

Reserve extra window memory by specifying a nonzero value in the cbWndExtra member of the WNDCLASS structure used with the RegisterClass function.

The GWW_ values are obsolete in the Win32 API. You must use the SetWindowLong function to set information about the window.

See Also

GetParent, GetWindowLong, GetWindowWord, RegisterClass, SetParent, SetWindowLong, WNDCLASS


SetWinMetaFileBits
 SetWinMetaFileBits  QuickInfo  Overview  Group

The SetWinMetaFileBits function converts a metafile from the older Windows format to the new enhanced format and stores the new metafile in memory.

HENHMETAFILE SetWinMetaFileBits(

UINT  cbBuffer,	// size of buffer
CONST BYTE *  lpbBuffer,	// address of buffered metafile data
HDC  hdcRef,	// handle of reference device context
CONST METAFILEPICT *  lpmfp	// suggested size of metafile picture
);
Parameters

cbBuffer

Specifies the size, in bytes, of the buffer that contains the Windows-format metafile.

lpbBuffer

Points to a buffer that contains the Windows-format metafile data. (It is assumed that the data was obtained by using the GetMetaFileBitsEx or GetWinMetaFileBits function.)

hdcRef

Identifies a reference device context.

lpmfp

Points to a METAFILEPICT structure that contains the suggested size of the metafile picture and the mapping mode that was used when the picture was created.

Return Value

If the function succeeds, the return value is a handle of a memory-based enhanced metafile.

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

Remarks

Windows uses the reference device context's resolution data and the data in the METAFILEPICT structure to scale a picture. If the hdcRef parameter is NULL, Windows uses resolution data for the current output device. If the lpmfp parameter is NULL, Windows uses the MM_ANISOTROPIC mapping mode to scale the picture so that it fits the entire device surface. The hMF field in the METAFILEPICT structure is not used.

When the application no longer needs the enhanced metafile handle, it should delete it by calling the DeleteEnhMetaFile function.

The handle returned by this function can be used with other enhanced-metafile functions.

If the reference device context is not identical to the device in which the metafile was originally created, some GDI functions that use device units may not draw the picture correctly.

See Also

DeleteEnhMetaFile, GetWinMetaFileBits, GetMetaFileBitsEx, METAFILEPICT, PlayEnhMetaFile


SetWorldTransform
 SetWorldTransform  QuickInfo  Overview  Group

The SetWorldTransform function sets a two-dimensional linear transformation between world space and page space for the specified device context. This transformation can be used to scale, rotate, shear, or translate graphics output.

BOOL SetWorldTransform(

HDC  hdc,	// handle of device context
CONST XFORM *  lpXform	// address of transformation data
);
Parameters

hdc

Identifies the device context.

lpXform

Points to an XFORM structure that contains the transformation data.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

For any coordinates (x, y) in world space, the transformed coordinates in page space (x', y') can be determined by the following algorithm:

x' = x * eM11 + y * eM21 + eDx,

y' = x * eM12 + y * eM22 + eDy,

where the transformation matrix is represented by the following:

| eM11 eM12 0 |

| eM21 eM22 0 |

| eDx  eDy  1 |

The mapping mode (defined by the current window and viewport extents origins) serves to define units and scales.

The world transformation is usually used to scale or rotate logical images in a device-independent way.

The default world transformation is the identity matrix with zero offset.

The SetWorldTransform function will fail unless the graphics mode for the given device context has been set to GM_ADVANCED by previously calling the SetGraphicsMode function. Likewise, it will not be possible to reset the graphics mode for the device context to the default GM_COMPATIBLE mode, unless the world transformation has first been reset to the default identity transformation by calling SetWorldTransform or ModifyWorldTransform.

See Also

GetWorldTransform, ModifyWorldTransform, SetGraphicsMode, SetMapMode, SetViewportExtEx, SetViewportOrgEx, SetWindowExtEx, SetWindowOrgEx, XFORM


SHAddToRecentDocs [New - Windows 95]
 SHAddToRecentDocs  QuickInfo

[New - Windows 95]

Adds a document to the shell's list of recently used documents or clears all documents from the list. The user accesses the list through the Start menu of the Windows taskbar.

WINSHELLAPI void WINAPI SHAddToRecentDocs(

UINT  uFlags,
LPCVOID  pv
);
Parameters

uFlags

Flag that indicates the meaning of the pv parameter. This parameter can be one of the following values:

SHARD_PATH	pv is the address of a path string.
SHARD_PIDL	pv is the address of an item identifier list.
pv

Pointer to a buffer that contains the path and filename of the document, or the address of an ITEMIDLIST structure that contains an item identifier list uniquely identifying the document. If this parameter is NULL, the function clears all documents from the list.

Return Value

No return value.


SHAppBarMessage [New - Windows 95]
 SHAppBarMessage  QuickInfo

[New - Windows 95]

Sends an appbar message to the system.

WINSHELLAPI UINT APIENTRY SHAppBarMessage(

DWORD  dwMessage,
PAPPBARDATA  pabd
);
Parameters

dwMessage

Identifier of the appbar message to send. This parameter can be one of the following values:

ABM_ACTIVATE	Notifies the system that an appbar has been activated.
ABM_GETAUTOHIDEBAR	Retrieves the handle of the autohide appbar associated with a particular edge of the screen.
ABM_GETSTATE	Retrieves the autohide and always-on-top states of the Windows taskbar.
ABM_GETTASKBARPOS	Retrieves the bounding rectangle of the Windows taskbar.
ABM_NEW	Registers a new appbar and specifies the message identifier that the system should use to send notification messages to the appbar.
ABM_QUERYPOS	Requests a size and screen position for an appbar.
ABM_REMOVE	Unregisters an appbar, removing bar from the system's internal list.
ABM_SETAUTOHIDEBAR	Registers or unregisters an autohide appbar for an edge of the screen.
ABM_SETPOS	Sets the size and screen position of an appbar.
ABM_WINDOWPOSCHANGED	Notifies the system when an appbar's position has changed.
pabd

Pointer to an APPBARDATA structure. The content of the structure depends on the value of dwMessage.

Return Value

Returns a message-dependent value. For more information, see the documentation for the individual appbar messages.

See Also

APPBARDATA


SHBrowseForFolder [New - Windows 95]
 SHBrowseForFolder  QuickInfo

[New - Windows 95]

Displays a dialog box that enables the user to select a shell folder.

WINSHELLAPI LPITEMIDLIST WINAPI SHBrowseForFolder(

LPBROWSEINFO  lpbi
);
Parameter

lpbi

Pointer to a BROWSEINFO structure that contains information used to display the dialog box.

Return Value

Returns a pointer to an item identifier list that specifies the location of the selected folder relative to the root of the name space. If the user chooses the Cancel button in the dialog box, the return value is NULL.

The calling application is responsible for freeing the returned item identifier list using the shell's task allocator.

See Also

BROWSEINFO


SHChangeNotify [New - Windows 95]
 SHChangeNotify  QuickInfo

[New - Windows 95]

Notifies the system of an event that an application has performed. An application should use this function if it performs an action that may affect the shell.

WINSHELLAPI void WINAPI SHChangeNotify(

LONG  wEventId,
UINT  uFlags,
LPCVOID  dwItem1,
LPCVOID  dwItem2
);
Parameters

wEventId

Array of flags that specifies the events. This parameter can be a combination of the following values:

SHCNE_ASSOCCHANGED	Changed a file type association.
SHCNE_ATTRIBUTES	Changed a file's attributes.
SHCNE_CREATE	Created a file.
SHCNE_DELETE	Deleted a file.
SHCNE_DRIVEADD	Added a network drive.
SHCNE_DRIVEADDGUI	Added a network drive by way of a graphic user interface.
SHCNE_DRIVEREMOVED	Removed a network drive.
SHCNE_INTERRUPT	Performed the event as a result of a system interrupt.
SHCNE_MEDIAINSERTED	Added removable media, such as a CD-ROM.
SHCNE_MEDIAREMOVED	Removed a removable medium, such as a CD-ROM.
SHCNE_MKDIR	Created a new directory.
SHCNE_NETSHARE	Shared a resource on the network.
SHCNE_NETUNSHARE	Stopped sharing a resource.
SHCNE_RENAMEFOLDER	Renamed a folder.
SHCNE_RENAMEITEM	Renamed an item in a folder.
SHCNE_RMDIR	Removed a directory.
SHCNE_SERVERDISCONNECT	Disconnected a network server.
SHCNE_UPDATEDIR	Updated the contents of a directory.
SHCNE_UPDATEIMAGE	Changed an image in the system global image list.
SHCNE_UPDATEITEM	Changed the properties of a printer or file.
uFlags

Flag that indicates the meaning of dwItem1 and dwItem2. This parameter can be one of the following values:

SHCNF_DWORD	The dwItem1 and dwItem2 parameters are doubleword values.
SHCNF_FLUSH	Flushes the system event buffer. The function does not return until the system is finished processing the given event.
SHCNF_FLUSHNOWAIT	Flushes the system event buffer. The function returns immediately regardless of whether the system is finished processing the given event.
SHCNF_IDLIST	dwItem1 and dwItem2 are the addresses of item identifier lists.
SHCNF_PATH	dwItem1 and dwItem2 are path names.
SHCNF_PRINTER	dwItem1 and dwItem2 are printer "friendly" names.
dwItem1

First event-dependent value.

dwItem2

Second event-dependent value.

Return Value

No return value.


ShellAbout
 ShellAbout  QuickInfo  Overview  Group

The ShellAbout function displays a Shell About dialog box.

int ShellAbout (

HWND  hWnd,	// handle of parent window
LPCTSTR  szApp,	// title bar and first line text
LPCTSTR  szOtherStuff,	// other dialog text
HICON  hIcon	// icon to display
);
Parameters

hWnd

Identifies a parent window. This parameter can be NULL.

szApp

Points to text that the function displays in the title bar of the Shell About dialog box and on the first line of the dialog box after the text "Microsoft Windows" or "Microsoft Windows NT." If the text contains a "#" separator, dividing it into two parts, the function displays the first part in the title bar, and the second part on the first line after the text "Microsoft Windows" or "Microsoft Windows NT."

szOtherStuff

Points to text that the function displays in the dialog box after the version and copyright information.

hIcon

Identifies an icon that the function displays in the dialog box. If this parameter is NULL, the function displays the Microsoft Windows or Microsoft Windows NT icon.

Return Value

If the function succeeds in displaying the dialog box, the return value is TRUE; otherwise the return value is FALSE.

Remarks

Please note that the ShellAbout function dialog box uses text and a default icon that are specific to either Microsoft Windows or Microsoft Windows NT.

An example of a Shell About dialog box can be seen by selecting the About Program Manager command in Program Manager.


ShellExecute
 ShellExecute  QuickInfo  Overview  Group

The ShellExecute function opens or prints a specified file. The file can be an executable file or a document file. See ShellExecuteEx also.

HINSTANCE ShellExecute(

HWND  hwnd,	// handle to parent window
LPCTSTR  lpOperation,	// pointer to string that specifies operation to perform
LPCTSTR  lpFile,	// pointer to filename string
LPTSTR  lpParameters,	// pointer to string that specifies executable-file parameters
LPCTSTR  lpDirectory,	// pointer to string that specifies default directory
INT  nShowCmd	// whether file is shown when opened
);
Parameters

hwnd

Specifies a parent window. This window receives any message boxes that an application produces. For example, an application may report an error by producing a message box.

lpOperation

Pointer to a null-terminated string that specifies the operation to perform. The following operation strings are valid:

String	Meaning
"open"	The function opens the file specified by lpFile. The file can be an executable file or a document file.
"print"	The function prints the file specified by lpFile. The file should be a document file. If the file is an executable file, the function opens the file, as if "open" had been specified.
The lpOperation parameter can be NULL. In that case, the function opens the file specified by lpFile.

lpFile

Pointer to a null-terminated string that specifies the file to open or print. The function can open an executable file or a document file. The function can print a document file.

lpParameters

If lpFile specifies an executable file, lpParameters is a pointer to a null-terminated string that specifies parameters to be passed to the application.

If lpFile specifies a document file, lpParameters should be NULL.

lpDirectory

Pointer to a null-terminated string that specifies the default directory.

nShowCmd

If lpFile specifies an executable file, nShowCmd specifies how the application is to be shown when it is opened.  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, Windows restores it to its original size and position. An application should specify this flag when restoring a minimized window.
SW_SHOW	Activates the window and displays it in its current size and position.
SW_SHOWDEFAULT	Sets the show state based on the SW_ flag specified in the STARTUPINFO structure passed to the CreateProcess function by the program that started the application. An application should call ShowWindow with this flag to set the initial show state of its main window.
SW_SHOWMAXIMIZED	Activates the window and displays it as a maximized window.
SW_SHOWMINIMIZED	Activates the window and displays it as a minimized window.
SW_SHOWMINNOACTIVE	Displays the window as a minimized window. The active window remains active.
SW_SHOWNA	Displays the window in its current state. The active window remains active.
SW_SHOWNOACTIVATE	Displays a window in its most recent size and position. The active window remains active.
SW_SHOWNORMAL	Activates and displays a window. If the window is minimized or maximized, Windows restores it to its original size and position. An application should specify this flag when displaying the window for the first time.
If lpFile specifies a document file, nShowCmd should be zero.

Return Value

If the function succeeds, the return value is the instance handle of the application that was run, or the handle of a dynamic data exchange (DDE) server application.

If the function fails, the return value is an error value that is less than or equal to 32. The following table lists these error values:

Value	Meaning
0	The operating system is out of memory or resources.
ERROR_FILE_NOT_FOUND	The specified file was not found.
ERROR_PATH_NOT_FOUND	The specified path was not found.
ERROR_BAD_FORMAT	The .EXE file is invalid (non-Win32 .EXE or error in .EXE image).
SE_ERR_ACCESSDENIED	Windows 95 only: The operating system denied access to the specified file.
SE_ERR_ASSOCINCOMPLETE	The filename association is incomplete or invalid.
SE_ERR_DDEBUSY	The DDE transaction could not be completed because other DDE transactions were being processed.
SE_ERR_DDEFAIL	The DDE transaction failed.
SE_ERR_DDETIMEOUT	The DDE transaction could not be completed because the request timed out.
SE_ERR_DLLNOTFOUND	Windows 95 only: The specified dynamic-link library was not found.
SE_ERR_FNF	Windows 95 only: The specified file was not found.
SE_ERR_NOASSOC	There is no application associated with the given filename extension.
SE_ERR_OOM	Windows 95 only: There was not enough memory to complete the operation.
SE_ERR_PNF	Windows 95 only: The specified path was not found.
SE_ERR_SHARE	A sharing violation occurred.
Remarks

The file specified by the lpFile parameter can be a document file or an executable file. If the file is a document file, the ShellExecute function opens or prints it, depending on the value of the lpOperation parameter. If the file is an executable file, the ShellExecute function opens it, even if lpOperation specifies printing.

Windows 95: You can use ShellExecute to open or explore a Windows 95 folder. To open a folder, use either of the following calls:

ShellExecute(handle, NULL, "path_to_folder", NULL, NULL, SW_SHOWNORMAL);

or

ShellExecute(handle, "open", "path_to_folder", NULL, NULL, SW_SHOWNORMAL);

To explore a folder, use the following call:

ShellExecute(handle, "explore", "path_to_folder", NULL, NULL, SW_SHOWNORMAL);

If lpOperation is NULL, the function opens the file specified by lpFile. If lpOperation is "open" or "explore", the function will force a open window or explorer.

See Also

FindExecutable, ShellExecuteEx


ShellExecuteEx
 ShellExecuteEx  QuickInfo  Overview  Group

The ShellExecuteEx function performs an action on a file. The file can be an executable file or a document.

WINSHELLAPI BOOL WINAPI ShellExecuteEx(

LPSHELLEXECUTEINFO  lpExecInfo	// pointer to SHELLEXECUTEINFO structure
);
Parameters

lpExecInfo

Pointer to a SHELLEXECUTEINFO structure that contains and receives information about the application to start.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

If the function succeeds, it sets the hInstApp member of the SHELLEXECUTEINFO structure to the instance handle of the application that the function started. If the function fails, hInstApp is one of the SE_ERR_ error values indicating the cause of the failure. (An instance handle will always be greater than 32, and an error value less than 32.) Note that the SE_ERR_ error values are for compatibility with the ShellExecute function; use the GetLastError function to retrieve error information.

Last error values returned by GetLastError correspond to the SE_ERR_ values and may be one of the following:

Value	Meaning
ERROR_FILE_NOT_FOUND	The specified file was not found.
ERROR_PATH_NOT_FOUND	The specified path was not found.
ERROR_DDE_FAIL	The DDE transaction failed.
ERROR_NO_ASSOCIATION	There is no application associated with the given filename extension.
ERROR_ACCESS_DENIED
ERROR_DLL_NOT_FOUND
ERROR_CANCELLED	The function prompted the user for the location of the application, but the user cancelled the request.
ERROR_NOT_ENOUGH_MEMORY
ERROR_SHARING_VIOLATION	A sharing violation occurred.
See Also

ShellExecute, SHELLEXECUTEINFO


ShellProc
 ShellProc  QuickInfo  Overview  Group

The ShellProc hook procedure is an application-defined or library-defined callback function a shell application uses to receive useful notifications from the system.

LRESULT CALLBACK ShellProc(

int  nCode,	// hook code
WPARAM  wParam,	// event-specific information
LPARAM  lParam	// undefined
);
Parameters

nCode

Specifies the hook code. This parameter can be one of the following values:

Value	Meaning
HSHELL_ACTIVATESHELLWINDOW	The shell should activate its main window.
HSHELL_GETMINRECT	Windows 95 only: A window is being minimized or maximized and the system needs the coordinates of the minimized rectangle for the window. The wParam parameter contains the handle of the window, and the lParam parameter contains the address of a RECT structure that receives the coordinates.
HSHELL_LANGUAGE	Windows 95 only: Keyboard language was changed or a new keyboard layout was loaded.
HSHELL_REDRAW	Windows 95 only: The title of a window in the task bar has been redrawn. The wParam parameter contains the handle of the window.
HSHELL_TASKMAN	Windows 95 only: The user has selected the task list. The wParam parameter is undefined and should be ignored. A shell application that provides a task list should return TRUE to prevent Windows from starting its task list.
HSHELL_WINDOWACTIVATED	Windows 95 only: The activation has changed to a different top-level, unowned window. The wParam parameter contains the handle of the window.
HSHELL_WINDOWCREATED	A top-level, unowned window has been created. The window exists when the system calls a ShellProc function.
HSHELL_WINDOWDESTROYED	A top-level, unowned window is about to be destroyed. The window still exists when the system calls a ShellProc function.
If nCode is less than zero, the hook procedure must pass the message to the CallNextHookEx function without further processing and should return the value returned by CallNextHookEx.

wParam

Specifies additional information the shell application may require. If the nCode parameter is HSHELL_ACTIVATESHELLWINDOW, the wParam parameter is not used. If nCode is HSHELL_WINDOWCREATED or HSHELL_WINDOWDESTROYED, wParam specifies the handle of the window being created or destroyed, respectively.

lParam

Windows 95:

Specifies additional information. The exact value depends on the value of the nCode parameter. If nCode is HSHELL_GETMINRECT, lParam is LPRECT. If nCode is HSHELL_WINDOWSACTIVATED, lParam is fFullScreen. If nCode is HSHELL_REDRAW, lParam is fNewFlash.

Windows NT:

This parameter must be zero.

Return Value

The return value should be zero.

Remarks

An application installs the hook procedure by specifying the WH_SHELL hook type and the address of the hook procedure in a call to the SetWindowsHookEx function.

ShellProc is a placeholder for the application-defined or library-defined function name.

See Also

CallNextHookEx, SendMessage, SetWindowsHookEx


SHFileOperation [New - Windows 95]
 SHFileOperation  QuickInfo

[New - Windows 95]

Performs a copy, move, rename, or delete operation on a file system object.

WINSHELLAPI int WINAPI SHFileOperation(

LPSHFILEOPSTRUCT  lpFileOp
);
Parameter

lpFileOp

Pointer to an SHFILEOPSTRUCT structure that contains information the function needs to carry out the operation.

Return Value

Returns zero if successful or nonzero if an error occurs.

See Also

SHFILEOPSTRUCT


SHFreeNameMappings [New - Windows 95]
 SHFreeNameMappings  QuickInfo

[New - Windows 95]

Frees a filename mapping object that was retrieved by the SHFileOperation function.

WINSHELLAPI void WINAPI SHFreeNameMappings(;

HANDLE  hNameMappings
);
Parameter

hNameMappings

Handle of the filename mapping object to free.

Return Value

No return value.


SHGetDesktopFolder [New - Windows 95]
 SHGetDesktopFolder  QuickInfo

[New - Windows 95]

Retrieves the IShellFolder interface for the desktop folder, which is the root of the shell's name space.

WINSHELLAPI HRESULT WINAPI SHGetDesktopFolder(

LPSHELLFOLDER * ppshf
);
Parameter

ppshf

Address that receives an IShellFolder interface pointer for the desktop folder. The calling application is responsible for eventually freeing the interface by calling its Release method.

Return Value

Returns NOERROR if successful or an OLE-defined error result otherwise.

See Also

IShellFolder


SHGetFileInfo [New - Windows 95]
 SHGetFileInfo  QuickInfo

[New - Windows 95]

Retrieves information about an object in the file system, such as a file, a folder, a directory, or a drive root.

WINSHELLAPI DWORD WINAPI SHGetFileInfo(

LPCSTR  pszPath,
DWORD  dwFileAttributes,
SHFILEINFO FAR  *psfi,
UINT  cbFileInfo,
UINT  uFlags
);
Parameters

pszPath

Pointer to a buffer that contains the path and filename. Both absolute and relative paths are valid. If uFlags includes the SHGFI_PIDL, value pszPath must be the address of an ITEMIDLIST structure that contains the list of item identifiers that uniquely identifies the file within the shell's name space.

This string can use either short (the 8.3 form) or long filenames.

dwFileAttributes

Array of file attribute flags (FILE_ATTRIBUTE_ values). If uFlags does not include the SHGFI_USEFILEATTRIBUTES value, this parameter is ignored.

psfi and cbFileInfo

Address and size, in bytes, of the SHFILEINFO structure that receives the file information.

uFlags

Flag that specifies the file information to retrieve. This parameter can be a combination of the following values:

SHGFI_ATTRIBUTES	Retrieves the file attribute flags. The flags are copied to the dwAttributes member of the structure specified by psfi.
SHGFI_DISPLAYNAME	Retrieves the display name for the file. The name is copied to the szDisplayName member of the structure specified by psfi. The returned display name uses the long filename, if any, rather than the 8.3 form of the filename.
SHGFI_EXETYPE	Returns the type of the executable file if pszPath identifies an executable file. For more information, see the comments below.
SHGFI_ICON	Retrieves the handle of the icon that represents the file and the index of the icon within the system image list. The handle is copied to the hIcon member of the structure specified by psfi, and the index is copied to the iIcon member. The return value is the handle of the system image list.
SHGFI_ICONLOCATION	Retrieves the name of the file that contains the icon representing the file. The name is copied to the szDisplayName member of the structure specified by psfi.
SHGFI_LARGEICON	Modifies SHGFI_ICON, causing the function to retrieve the file's large icon.
SHGFI_LINKOVERLAY	Modifies SHGFI_ICON, causing the function to add the link overlay to the file's icon.
SHGFI_OPENICON	Modifies SHGFI_ICON, causing the function to retrieve the file's open icon. A container object displays an open icon to indicate that the container is open.
SHGFI_PIDL	Indicates that pszPath is the address of an ITEMIDLIST structure rather than a path name.
SHGFI_SELECTED	Modifies SHGFI_ICON, causing the function to blend the file's icon with the system highlight color.
SHGFI_SHELLICONSIZE	Modifies SHGFI_ICON, causing the function to retrieve a shell-sized icon. If this flag is not specified, the function sizes the icon according to the system metric values.
SHGFI_SMALLICON	Modifies SHGFI_ICON, causing the function to retrieve the file's small icon.
SHGFI_SYSICONINDEX	Retrieves the index of the icon within the system image list. The index is copied to the iIcon member of the structure specified by psfi. The return value is the handle of the system image list.
SHGFI_TYPENAME	Retrieves the string that describes the file's type. The string is copied to the szTypeName member of the structure specified by psfi.
SHGFI_USEFILEATTRIBUTES	Indicates that the function should use the dwFileAttributes parameter.
To retrieve the executable file type, uFlags must specify only SHGFI_EXETYPE. The return value specifies the type of the executable file:

0	Nonexecutable file or an error condition.
LOWORD = NE or PE HIWORD = 3.0, 3.5, or 4.0	Windows application
LOWORD = MZ HIWORD = 0	MS-DOS .EXE, .COM or .BAT file
LOWORD = PE HIWORD = 0	Win32 console application
Return Value

•	Returns a value whose meaning depends on the uFlags parameter. If uFlags specifies the SHGFI_EXETYPE value, the return value indicates the type of the executable file. For more information, see the comments below.

•	If uFlags includes the SHGFI_ICON or SHGFI_SYSICONINDEX value, the return value is the handle of the system image list that contains the large icon images. If the SHGFI_SMALLICON value is also included, the return value is the handle of the image list that contains the small icon images.

•	If uFlags does not include SHGFI_EXETYPE, SHGFI_ICON, SHGFI_SYSICONINDEX, or SHGFI_SMALLICON, the return value is nonzero the function succeeds, or zero otherwise.


SHGetInstanceExplorer [New - Windows 95]
 SHGetInstanceExplorer  QuickInfo

[New - Windows 95]

Retreives the address of the Explorer's IUnknown interface.

WINSHELLAPI HRESULT WINAPI SHGetInstanceExplorer(

IUnknown  **ppunk
);
Parameter

ppunk

Pointer to a value that receives the address of the Explorer's IUnknown interface.

Return Value

Returns NOERROR if successful or E_FAIL otherwise.


SHGetNameMappingCount [New - Windows 95]
 SHGetNameMappingCount  QuickInfo

[New - Windows 95]

Retrieves the number of SHNAMEMAPPING structures in a filename mapping object.

int SHGetNameMappingCount(

HANDLE  hNameMappings
);
Parameter

hNameMapping

Handle of a filename mapping object retrieved by the SHFileOperation function.

Return Value

Returns the number of SHNAMEMAPPING structures.

The SHGetNameMappingCount macro is defined as follows.

#define SHGetNameMappingCount(_hnm) \
    DSA_GetItemCount(_hnm)

See Also

SHFileOperation, SHNAMEMAPPING


SHGetNameMappingPtr [New - Windows 95]
 SHGetNameMappingPtr  QuickInfo

[New - Windows 95]

Retrieves the address of a SHNAMEMAPPING structure contained in a file mapping object.

lpshnm = SHGetNameMappingPtr(

HANDLE  hNameMappings,
int  iItem
);
Parameters

hNameMapping

Handle of a filename mapping object retrieved by the SHFileOperation function.

iItem

Index of the SHNAMEMAPPING structure to be retrieved.

Return Value

Returns the address of the SHNAMEMAPPING structure specified by iItem.

The SHGetNameMappingPtr macro is defined as follows.

#define SHGetNameMappingPtr(_hnm, _iItem) \
    (LPSHNAMEMAPPING)DSA_GetItemPtr(_hnm, _iItem)

See Also

SHFileOperation, SHNAMEMAPPING


SHGetPathFromIDList [New - Windows 95]
 SHGetPathFromIDList  QuickInfo

[New - Windows 95]

Converts an item identifier list to a file system path.

WINSHELLAPI BOOL WINAPI SHGetPathFromIDList(

LPCITEMIDLIST  pidl,
LPSTR  pszPath
);
Parameters

pidl

Pointer to an item identifier list that specifies a file or directory location relative to the root of the name space (the desktop).

pszPath

Pointer to a buffer that receives the file system path. The size of this buffer is assumed to be MAX_PATH bytes.

Return Value

Returns TRUE if successful or FALSE if an error occurs — for example, if the location specified by the pidl parameter is not part of the file system.


SHGetSpecialFolderLocation [New - Windows 95]
 SHGetSpecialFolderLocation  QuickInfo

[New - Windows 95]

WINSHELLAPI HRESULT WINAPI SHGetSpecialFolderLocation(;

HWND  hwndOwner,
int  nFolder,
LPITEMIDLIST  * ppidl
);
Retrieves the location of a special folder.

Parameters

hwndOwner

Handle of the owner window that the client should specify if it displays a dialog box or message box.

nFolder

Value specifying the folder to retrieve the location of. This parameter can be one of the following values:

CSIDL_BITBUCKET	Recycle bin — file system directory containing file objects in the user's recycle bin. The location of this directory is not in the registry; it is marked with the hidden and system attributes to prevent the user from moving or deleting it.
CSIDL_CONTROLS	Control Panel — virtual folder containing icons for the control panel applications.
CSIDL_DESKTOP	Windows desktop — virtual folder at the root of the name space.
CSIDL_DESKTOPDIRECTORY	File system directory used to physically store file objects on the desktop (not to be confused with the desktop folder itself).
CSIDL_DRIVES	My Computer — virtual folder containing everything on the local computer: storage devices, printers, and Control Panel. The folder may also contain mapped network drives.
CSIDL_FONTS	Virtual folder containing fonts.
CSIDL_NETHOOD	File system directory containing objects that appear in the network neighborhood.
CSIDL_NETWORK	Network Neighborhood — virtual folder representing the top level of the network hierarchy.
CSIDL_PERSONAL	File system directory that serves as a common respository for documents.
CSIDL_PRINTERS	Printers folder — virtual folder containing installed printers.
CSIDL_PROGRAMS	File system directory that contains the user's program groups (which are also file system directories).
CSIDL_RECENT	File system directory that contains the user's most recently used documents.
CSIDL_SENDTO	File system directory that contains Send To menu items.
CSIDL_STARTMENU	File system directory containing Start menu items.
CSIDL_STARTUP	File system directory that corresponds to the user's Startup program group.
CSIDL_TEMPLATES	File system directory that serves as a common repository for document templates.
ppidl

Address that receives a pointer to an item identifier list specifying the folder's location relative to the root of the name space (the desktop).

Return Value

Returns NOERROR if successful or an OLE-defined error result otherwise.


SHLoadInProc [New - Windows 95]
 SHLoadInProc  QuickInfo

[New - Windows 95]

Creates an instance of the specified object class from within the context of the shell's process.

WINSHELLAPI HRESULT WINAPI SHLoadInProc(

REFCLSID  rclsid
);
Parameter

rclsid

CLSID of the object class to be created.

Return Value

Returns NOERROR if successful or an OLE-defined error result otherwise.


ShowCaret
 ShowCaret  QuickInfo  Overview  Group

The ShowCaret function makes the caret visible on the screen at the caret's current position. When the caret becomes visible, it begins flashing automatically.

BOOL ShowCaret(

HWND  hwnd	// handle of window with caret
);
Parameters

hwnd

Identifies the window that owns the caret. If this parameter is NULL, ShowCaret searches the current task for the window that owns the caret.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. 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 caret is a shared resource; there is only one caret in the system. A window should show a caret only when the window has the keyboard focus or is active.

See Also

CreateCaret, DestroyCaret, GetCaretPos, HideCaret, SetCaretPos


ShowCursor
 ShowCursor  QuickInfo  Overview  Group

The ShowCursor function displays or hides the cursor.

int ShowCursor(

BOOL  bShow	// cursor visibility flag
);
Parameters

bShow

Specifies whether the internal display counter is to be incremented or decremented. If bShow is TRUE, the display count is incremented by one. If bShow is FALSE, the display count is decremented by one.

Return Value

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.

See Also

ClipCursor, GetCursorPos, SetCursor, SetCursorPos


ShowHideMenuCtl [New - Windows NT]
 ShowHideMenuCtl  QuickInfo  Overview  Group

[New - Windows NT]

The ShowHideMenuCtl function sets or removes the specified menu item's check-mark attribute, and shows or hides the corresponding control. The function adds a check mark to the specified menu item if it does not have one and then displays the corresponding control. If the menu item already has a check mark, the function removes the check mark and hides the corresponding control.

BOOL ShowHideMenuCtl(

HWND  hWnd,	// handle to MDI child window
UINT  uFlags,	// message
LPINT  lpInfo	// first message parameter
);
Parameters

hWnd

Handle to the window that contains the menu and controls.

uFlags

Identifier of the menu item to receive or lose a check mark.

lpInfo

Pointer to an array that contains pairs of values. The second value in the first pair must be the handle to the application's main menu. Each subsequent pair consists of a menu item identifier and a control window identifier. The function searches the array for a value that matches uFlags and, if the value is found, checks or unchecks the menu item and shows or hides the corresponding control.

Return Value

If the function shows or hides the control, the return value is TRUE.

If the function does not show or hide the control, the return value is FALSE.


ShowOwnedPopups
 ShowOwnedPopups  QuickInfo  Overview  Group

The ShowOwnedPopups function shows or hides all pop-up windows owned by the specified window.

BOOL ShowOwnedPopups(

HWND  hwnd,	// handle of window
BOOL  fShow	// window visibility flag
);
Parameters

hwnd

Identifies the window that owns the pop-up windows to be shown or hidden.

fShow

Specifies whether pop-up windows are to be shown or hidden. If this parameter is TRUE, all hidden pop-up windows are shown. If this parameter is FALSE, all visible pop-up windows are hidden.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. 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.

See Also

IsWindowVisible, ShowWindow


ShowScrollBar
 ShowScrollBar  QuickInfo  Overview  Group

The ShowScrollBar function shows or hides the specified scroll bar.

BOOL ShowScrollBar(

HWND  hwnd,	// handle of window with scroll bar
int  fnBar,	// scroll bar flag
BOOL  fShow	// scroll bar visibility flag
);
Parameters

hwnd

Identifies a scroll bar control or a window with a standard scroll bar, depending on the value of the fnBar parameter.

fnBar

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

Specifies whether the scroll bar is shown or hidden. If this parameter is TRUE, the scroll bar is shown; otherwise, it is hidden.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

While processing a scroll bar message, an application should not call this function to hide a scroll bar.

See Also

GetScrollPos, GetScrollRange, ScrollDC, ScrollWindow, SetScrollPos, SetScrollRange


ShowWindow
 ShowWindow  QuickInfo  Overview  Group

The ShowWindow function sets the specified window's show state.

BOOL ShowWindow(

HWND  hwnd,	// handle of window
int  nCmdShow	// show state of window
);
Parameters

hwnd

Identifies the window.

nCmdShow

Specifies how the window is to be shown. This parameter can be one of the following values:

Value	Meaning
SW_HIDE	Hides the window and activates another window.
SW_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, Windows restores it to its original size and position. An application should specify this flag when restoring a minimized window.
SW_SHOW	Activates the window and displays it in its current size and position.
SW_SHOWDEFAULT	Sets the show state based on the SW_ flag specified in the STARTUPINFO structure passed to the CreateProcess function by the program that started the application. An application should call ShowWindow with this flag to set the initial show state of its main window.
SW_SHOWMAXIMIZED	Activates the window and displays it as a maximized window.
SW_SHOWMINIMIZED	Activates the window and displays it as a minimized window.
SW_SHOWMINNOACTIVE	Displays the window as a minimized window. The active window remains active.
SW_SHOWNA	Displays the window in its current state. The active window remains active.
SW_SHOWNOACTIVATE	Displays a window in its most recent size and position. The active window remains active.
SW_SHOWNORMAL	Activates and displays a window. If the window is minimized or maximized, Windows restores it to its original size and position. An application should specify this flag when displaying the window for the first time.
Return Value

If the window was previously visible, the return value is TRUE. If the window was previously hidden, the return value is FALSE.

Remarks

ShowWindow must be called only once per program with the WinMain function's nCmdShow parameter. Subsequent calls to ShowWindow must use one of the values in the preceding list, instead of the one specified by the WinMain function's nCmdShow parameter.

As noted in the discussion of the nCmdShow parameter, an application should call ShowWindow with nCmdShow set to SW_SHOWDEFAULT to use application startup information that affects how a window is displayed. For example, Program Manager specifies that applications start with a minimized main window. Win32-based applications also use the application startup information when calling ShowWindow for the first time and set nCmdShow to SW_SHOW. This behavior is designed for the following situations:

•	Applications that create their main window by calling CreateWindow with the WS_VISIBLE flag set.

•	Applications that 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.

See Also

CreateProcess, CreateWindow, ShowOwnedPopups, STARTUPINFO, WinMain


ShowWindowAsync [New - Windows 95]
 ShowWindowAsync  QuickInfo

[New - Windows 95]

The ShowWindowAsync function sets the show state of a window created by a different thread.

BOOL ShowWindowAsync(

HWND  hwnd,	// handle of window
int  nCmdShow	// show state of window
);
Parameters

hwnd

Identifies the window.

nCmdShow

Specifies how the window is to be shown. For a list of possible values, see the description of the ShowWindow function.

Return Value

If the window was previously visible, the return value is TRUE.

If the window was previously hidden, the return value is FALSE.

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.

See Also

ShowWindow


shutdown
 shutdown  QuickInfo

The Windows Sockets shutdown function disables send or receive operations on a socket.

int shutdown (

SOCKET s,
int how
);
Parameters

s

A descriptor identifying a socket.

how

A flag that describes what types of operation will no longer be allowed.

Return Value

If the function succeeds, shutdown returns zero.

If the function fails, a value of SOCKET_ERROR is returned. To get extended error information, call WSAGetLastError.

Error Codes

WSANOTINITIALISED	A successful WSAStartup must occur before using this function.
WSAENETDOWN	The Windows Sockets implementation has detected that the network subsystem has failed.
WSAEINVAL	The how parameter is not valid.
WSAEINPROGRESS	A blocking Windows Sockets operation is in progress.
WSAENOTCONN	The socket is not connected (SOCK_STREAM only).
WSAENOTSOCK	The descriptor is not a socket.
Remarks

The shutdown function is used on all types of sockets to disable reception, transmission, or both.

If how is zero, subsequent receives on the socket will be disallowed. This has no effect on the lower protocol layers. For TCP, the TCP window is not changed, and incoming data will be accepted (but not acknowledged) until the window is exhausted. For UDP, incoming datagrams are accepted and queued. In no case will an ICMP error packet be generated.

If how is 1, subsequent sends are disallowed. For TCP sockets, a FIN will be sent.

Setting how to 2 disables both sends and receives as described previously.

Note that shutdown does not close the socket, and resources attached to the socket will not be freed until closesocket is invoked.

The shutdown function does not block, regardless of the SO_LINGER setting on the socket.

An application should not rely on being able to reuse a socket after it has been shut down. In particular, a Windows Sockets implementation is not required to support the use of connect on such a socket.

See Also

closesocket, connect, socket, WSAStartup


SizeofResource
 SizeofResource  QuickInfo  Overview  Group

The SizeofResource function returns the size, in bytes, of the specified resource.

DWORD SizeofResource(

HINSTANCE  hModule,	// resource-module handle
HRSRC  hrsrc	// resource handle
);
Parameters

hModule

Identifies the module whose executable file contains the resource.

hrsrc

Identifies the resource. This handle must be created by using the FindResource or FindResourceEx function.

Return Value

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.

Remarks

The value returned may be larger than the actual resource because of alignment. An application should not rely upon this value for the exact size of a resource.

See Also

FindResource, FindResourceEx , LoadResource, LockResource


Sleep
 Sleep  QuickInfo  Overview  Group

The Sleep function suspends the execution of the current thread for a specified interval.

VOID Sleep(

DWORD  cMilliseconds	// sleep time in milliseconds
);
Parameters

cMilliseconds

Specifies the time, in milliseconds, for which to suspend execution. A value of zero causes the thread to relinquish the remainder of its time slice to any other thread of equal priority that is ready to run. If there are no other threads of equal priority ready to run, the function returns immediately, and the thread continues execution. A value of INFINITE causes an infinite delay.

Return Value

This function does not return a value.

Remarks

A thread can relinquish the remainder of its time slice by calling this function with a sleep time of zero milliseconds.

See Also

SleepEx


SleepEx
 SleepEx  QuickInfo  Overview  Group

The SleepEx function causes the current thread to enter a wait state until the specified interval of time has passed, or until an I/O completion callback function is called.

This function is available only in the Win32 API.

DWORD SleepEx(

DWORD  dwTimeout,	// time-out interval in milliseconds
BOOL  fAlertable	// early completion flag
);
Parameters

dwTimeout

Specifies the time, in milliseconds, that the delay is to occur. A value of zero causes the function to return immediately. A value of INFINITE causes an infinite delay.

fAlertable

Specifies whether the function may terminate early due to an I/O completion callback function. If fAlertable is FALSE, the function does not return until the time-out period has elapsed. If an I/O completion callback occurs, the function does not return and the I/O completion function is not executed.

If fAlertable is TRUE and the thread that called this function is the same thread that called the extended I/O function (ReadFileEx or WriteFileEx), the function returns when either the time-out period has elapsed or when an I/O completion callback function occurs. If an I/O completion callback occurs, the I/O completion function is executed.

Return Value

The return value is zero if the specified time interval expired.

The return value is WAIT_IO_COMPLETION if the function returned due to one or more I/O completion callback functions. This can happen only if fAlertable is TRUE, and if the thread that called the SleepEx function is the same thread that called the extended I/O function.

Remarks

This function can be used with the ReadFileEx or WriteFileEx functions to suspend a thread until an I/O operation has been completed. These functions specify a completion routine that is to be executed when the I/O operation has been completed. For the completion routine to be executed, the thread that called the I/O function must be in an alertable wait state when the completion callback function occurs. A thread goes into an alertable wait state by calling either SleepEx, WaitForSingleObjectEx, or WaitForMultipleObjectsEx with the function's fAlertable parameter set to TRUE.

A thread can relinquish the remainder of its time slice by calling this function with a sleep time of zero milliseconds.

See Also

ReadFileEx, Sleep, WaitForMultipleObjectsEx, WaitForSingleObjectEx, WriteFileEx


socket
 socket  QuickInfo

TheWindows Sockets socket function creates a socket.

SOCKET socket (

int af,
int type,
int protocol
);
Parameters

af

An address format specification. The only format currently supported is PF_INET, which is the ARPA Internet address format.

type

A type specification for the new socket.

protocol

A particular protocol to be used with the socket, or zero if the caller does not wish to specify a protocol.

Return Value

If the function succeeds, socket returns a descriptor referencing the new socket.

If the function fails, a value of INVALID_SOCKET is returned. To get extended error information, call WSAGetLastError.

Error Codes

WSANOTINITIALISED	A successful WSAStartup must occur before using this function.
WSAENETDOWN	The Windows Sockets implementation has detected that the network subsystem has failed.
WSAEAFNOSUPPORT	The specified address family is not supported.
WSAEINPROGRESS	A blocking Windows Sockets operation is in progress.
WSAEMFILE	No more file descriptors are available.
WSAENOBUFS	No buffer space is available. The socket cannot be created.
WSAEPROTONOSUPPORT	The specified protocol is not supported.
WSAEPROTOTYPE	The specified protocol is the wrong type for this socket.
WSAESOCKTNOSUPPORT	The specified socket type is not supported in this address family.
Remarks

The socket function allocates a socket descriptor of the specified address family, data type and protocol, as well as related resources. If a protocol is not specified (that is, equal to zero), the default for the specified connection mode is used.

Only a single protocol exists to support a particular socket type using a given address format. However, the address family may be given as AF_UNSPEC (unspecified), in which case the protocol parameter must be specified. The protocol number to use is particular to the "communication domain" in which communication is to take place.

The following type specifications are supported:

Value	Meaning
SOCK_STREAM	Provides sequenced, reliable, two-way, connection-based byte streams with an out-of-band data transmission mechanism. Uses TCP for the Internet address family.
SOCK_DGRAM	Supports datagrams, which are connectionless, unreliable buffers of a fixed (typically small) maximum length. Uses UDP for the Internet address family.
Sockets of type SOCK_STREAM are full-duplex byte streams. A stream socket must be in a connected state before any data can be sent or received on it. A connection to another socket is created with a connect call. Once connected, data can be transferred using send and recv calls. When a session has been completed, a closesocket must be performed. Out-of-band data can also be transmitted as described in send and received as described in recv.

The communications protocols used to implement a SOCK_STREAM socket ensure that data is not lost or duplicated. If data for which the peer protocol has buffer space cannot be successfully transmitted within a reasonable length of time, the connection is considered broken and subsequent calls will fail with the error code set to WSAETIMEDOUT.

SOCK_DGRAM sockets allow sending and receiving of datagrams to and from arbitrary peers using sendto and recvfrom. If such a socket is connected to a specific peer, datagrams can be sent to that peer send and can be received from (only) this peer using recv.

See Also

accept, bind, closesocket, connect, getsockname, getsockopt, ioctlsocket, listen, recv, recvfrom, select, send, sendto, setsockopt, shutdown, WSAStartup


SoundSentryProc [New - Windows NT]
 SoundSentryProc  QuickInfo

[New - Windows NT]

The SoundSentryProc function is a library-defined callback function that produces a customized visual signal when the SoundSentry accessibility feature is on and a Windows-based application (or a non-Windows-based application running in a window) generates a sound through the computer's built-in speaker.

LRESULT CALLBACK SoundSentryProc(

DWORD  dwMillisec,	// duration of visual signal
DWORD  fdwEffect	// effect-type flag
);
Parameters

dwMillisec

Specifies the duration, in milliseconds, of the visual signal that is displayed when a Windows-based application (or a non-Windows-based application running in a window) generates a sound.

fdwEffect

Specifies the type of visual signal to display. Currently, this value must always be SSWF_CUSTOM.

Return Value

If the visual signal was or will be displayed correctly, the return value is TRUE. If the signal is asynchronous and the status is not available when the function is called, it should return TRUE.

If an error prevented the signal from being displayed, the return value is FALSE. To get extended error information, call GetLastError.

Remarks

The library that contains the SoundSentryProc function must be a 32-bit DLL, and the DLL must export a function with the name "SoundSentryProc."

The SoundSentryProc function is called only after an application or library calls the SystemParametersInfo function, specifying the SPI_SETSOUNDSENTRY value and the address of a SOUNDSENTRY structure whose iWindowsEffect member is set to SSWF_CUSTOM.

See Also

SOUNDSENTRY, SystemParametersInfo


StartDoc
 StartDoc  QuickInfo  Overview  Group

The StartDoc function starts a print job. This function replaces the STARTDOC printer escape.

int StartDoc(

HDC  hdc,	// handle of device context
CONST DOCINFO *  lpdi	// address of structure with file names
);
Parameters

hdc

Identifies the device context for the print job.

lpdi

Points to a DOCINFO structure containing the name of the document file and the name of the output file.

Return Value

If the function succeeds, the return value is greater than zero. This value is the print job identifier for the document.

If the function fails, the return value is less than or equal to zero. To get extended error information, call GetLastError.

Remarks

Applications should call the StartDoc function immediately before beginning a print job. Using this function ensures that multipage documents are not interspersed with other print jobs.

Applications can use the value returned by StartDoc to retrieve or set the priority of a print job. Call the GetJob or SetJob function and supply this value as one of the required arguments.

See Also

DOCINFO, EndDoc, GetJob, SetJob


StartDocPrinter
 StartDocPrinter  QuickInfo  Overview  Group

The StartDocPrinter function informs the print spooler that a document is to be spooled for printing.

DWORD StartDocPrinter(

HANDLE  hPrinter,	// handle of printer object
DWORD  dwLevel,	// structure level
LPBYTE  lpbDocInfo	// address of structure
);
Parameters

hPrinter

Identifies the printer.

dwLevel

Specifies the version of the structure to which lpbDocInfo points. This value must be 1 for Windows NT. For Windows 95, you can also select a value of 2. (See DOC_INFO_2 following.)

lpbDocInfo

Points to a DOC_INFO_1 structure or a DOC_INFO_2 structure. If dwlevel is 1, the function stores the data in a DOC_INFO_1 structure. If dwlevel is 2, the function stores the data in a DOC_INFO_2 structure.

Windows 95 only: The DOC_INFO_2 structure has the following form:

typedef struct _DOC_INFO_2 { // dci2

    LPTSTR pDocName;

    LPTSTR pOutputFile;

    LPTSTR pDatatype;

    DWORD dwMode;

    DWORD JobId;

} DOC_INFO_2;

Return Value

If the function succeeds, the return value identifies the print job.

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

Remarks

The printer handle identified by the hPrinter parameter is obtained by calling the OpenPrinter function.

The return value will never be greater than 2^31 − 1.

See Also

DOC_INFO_1, OpenPrinter


StartPage
 StartPage  QuickInfo  Overview  Group

The StartPage function prepares the printer driver to accept data.

int StartPage(

HDC  hDC	// handle of device context
);
Parameters

hDC

Identifies the device context for the print job.

Return Value

If the function succeeds, the return value is greater than zero.

If the function fails, the return value is less than or equal to zero. To get extended error information, call GetLastError.

Remarks

The system disables the ResetDC function between calls to the StartPage and EndPage functions. This means that an application cannot change the device mode except at page boundaries.

See Also

EndPage, ResetDC


StartPagePrinter
 StartPagePrinter  QuickInfo  Overview  Group

The StartPagePrinter function informs the spooler that a page is about to be printed on the specified printer.

BOOL StartPagePrinter(

HANDLE  hPrinter	// handle of printer object
);
Parameters

hPrinter

Identifies a printer.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The printer handle identified by the hPrinter parameter is obtained by calling the OpenPrinter function.

When an application has finished writing a page, it should call the EndPagePrinter function to inform the spooler that the page is complete.

See Also

EndPagePrinter, OpenPrinter


StartService
 StartService  QuickInfo  Overview  Group

The StartService function starts the execution of a service.

BOOL StartService(

SC_HANDLE  schService,	// handle of service
DWORD  dwNumServiceArgs,	// number of arguments
LPCTSTR  *lpszServiceArgs	// address of array of argument string pointers
);
Parameters

schService

Identifies the service. This handle is returned by the OpenService or CreateService function, and it must have SERVICE_START access.

dwNumServiceArgs

Specifies the number of argument strings in the lpszServiceArgs array. If lpszServiceArgs is NULL, this parameter can be zero.

lpszServiceArgs

Points to an array of pointers that point to null-terminated argument strings passed to a Win32 service. Driver services do not receive these arguments. If no arguments are passed to the service being started, this parameter can be NULL. The new service accesses these arguments through its ServiceMain function. Note that in the array of arguments passed to the ServiceMain function, the first argument (argv[0]) is the name of the service by default, followed by the arguments, if any, in the lpszServiceArgs array.

Return Value

If the function succeeds, the return value is TRUE.

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

Errors

The following error codes can be set by the service control manager. Others can be set by the registry functions that are called by the service control manager.

Value	Meaning
ERROR_ACCESS_DENIED	The specified handle was not opened with SERVICE_START access.
ERROR_INVALID_HANDLE	The specified handle is invalid.
ERROR_PATH_NOT_FOUND	The service binary file could not be found.
ERROR_SERVICE_ALREADY_RUNNING	An instance of the service is already running.
ERROR_SERVICE_DATABASE_LOCKED	The database is locked.
ERROR_SERVICE_DEPENDENCY_DELETED	The service depends on a service that does not exist or has been marked for deletion.
ERROR_SERVICE_DEPENDENCY_FAIL	The service depends on another service that has failed to start.
ERROR_SERVICE_DISABLED	The service has been disabled.
ERROR_SERVICE_LOGON_FAILED	The service could not be logged on.
ERROR_SERVICE_MARKED_FOR_DELETE	The service has been marked for deletion.
ERROR_SERVICE_NO_THREAD	A thread could not be created for the Win32 service.
ERROR_SERVICE_REQUEST_TIMEOUT	The service did not respond to the start request in a timely fashion.
Remarks

When a driver service is started, the StartService function does not return until the device driver has finished initializing.

When a Win32 service is started, the service control manager spawns the service process, if necessary. If the specified service shares a process with other services, the required process may already exist. The StartService function does not wait for the first status update from the new service (which may take a while). Instead, it returns when the service control manager receives notification from the service control dispatcher that the ServiceMain thread for this service was created successfully.

For a Win32 service, the service control manager sets the following default status values before returning from StartService:

•	Current state of the service is set to SERVICE_START_PENDING.

•	Controls accepted is set to none (zero).

•	The CheckPoint value is set to zero.

•	The WaitHint time is set to 2 seconds.

The calling process can determine if the new service has finished its initialization by calling the QueryServiceStatus function periodically to query the service's status.

This function cannot be called from within a service.

See Also

ControlService, CreateService, OpenService, QueryServiceStatus, ServiceMain


StartServiceCtrlDispatcher
 StartServiceCtrlDispatcher  QuickInfo  Overview  Group

The StartServiceCtrlDispatcher function connects the main thread of a service process to the service control manager, which causes the thread to be the service control dispatcher thread for the calling process.

BOOL StartServiceCtrlDispatcher(

LPSERVICE_TABLE_ENTRY  lpsteServiceTable	// address of service table
);
Parameters

lpsteServiceTable

Points to an array of SERVICE_TABLE_ENTRY structures containing one entry for each service that can execute in the calling process. The members of the last entry in the table must have NULL values to designate the end of the table.

Return Value

If the function succeeds, the return value is TRUE.

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

Errors

The following error code can be set by the service control manager. Other error codes can be set by the registry functions that are called by the service control manager.

Value	Meaning
ERROR_INVALID_DATA	The specified dispatch table contains entries that are not in the proper format.
Remarks

When the service control manager starts a service process, it waits for the process to call the StartServiceCtrlDispatcher function. The main thread of a service process should make this call as soon as possible after it starts up. If StartServiceCtrlDispatcher succeeds, it connects the calling thread to the service control manager and does not return until all running services in the process have terminated. The service control manager uses this connection to send control and service start requests to the main thread of the service process. The main thread acts as a dispatcher by invoking the appropriate Handler function to handle control requests, or by creating a new thread to execute the appropriate ServiceMain function when a new service is started.

The lpsteServiceTable parameter contains an entry for each service that can run in the calling process. Each entry specifies the ServiceMain function for that service. For SERVICE_WIN32_SHARE_PROCESS services, each entry must contain the name of a service. This name is the service name that was specified by the CreateService function when the service was installed. For SERVICE_WIN32_OWN_PROCESS services, the service name in the table entry is ignored.

If a service runs in its own process, the main thread of the service process should immediately call StartServiceCtrlDispatcher. All initialization tasks are done in the service's ServiceMain function when the service is started.

If multiple services share a process and some common process-wide initialization needs to be done before any ServiceMain function is called, the main thread can do the work before calling StartServiceCtrlDispatcher, as long as it takes less than 30 seconds. Otherwise, another thread must be created to do the process-wide initialization, while the main thread calls StartServiceCtrlDispatcher and becomes the service control dispatcher. Any service-specific initialization should still be done in the individual service main functions.

See Also

ControlService, Handler, RegisterServiceCtrlHandler, ServiceMain, SERVICE_TABLE_ENTRY


 StartSound

The StartSound function has been deleted.

See Also

Beep, MessageBeep


 StopSound

The StopSound function has been deleted.

See Also

Beep, MessageBeep


StretchBlt
 StretchBlt  QuickInfo  Overview  Group

The StretchBlt function copies a bitmap from a source rectangle into a destination rectangle, stretching or compressing the bitmap to fit the dimensions of the destination rectangle, if necessary. Windows stretches or compresses the bitmap according to the stretching mode currently set in the destination device context.

BOOL StretchBlt(

HDC  hdcDest,	// handle of destination device context
int  nXOriginDest,	// x-coordinate of upper-left corner of dest. rect.
int  nYOriginDest,	// y-coordinate of upper-left corner of dest. rect.
int  nWidthDest,	// width of destination rectangle
int  nHeightDest,	// height of destination rectangle
HDC  hdcSrc,	// handle of source device context
int  nXOriginSrc,	// x-coordinate of upper-left corner of source rectangle
int  nYOriginSrc,	// y-coordinate of upper-left corner of source rectangle
int  nWidthSrc,	// width of source rectangle
int  nHeightSrc,	// height of source rectangle
DWORD  dwRop	// raster operation code
);
Parameters

hdcDest

Identifies the destination device context.

nXOriginDest

Specifies the x-coordinate, in logical units, of the upper-left corner of the destination rectangle.

nYOriginDest

Specifies the y-coordinate, in logical units, of the upper-left corner of the destination rectangle.

nWidthDest

Specifies the width, in logical units, of the destination rectangle.

nHeightDest

Specifies the height, in logical units, of the destination rectangle.

hdcSrc

Identifies the source device context.

nXOriginSrc

Specifies the x-coordinate, in logical units, of the upper-left corner of the source rectangle.

nYOriginSrc

Specifies the y-coordinate, in logical units, of the upper-left corner of the source rectangle.

nWidthSrc

Specifies the width, in logical units, of the source rectangle.

nHeightSrc

Specifies the height, in logical units, of the source rectangle.

dwRop

Specifies the raster operation to be performed. Raster operation codes define how Windows combines colors in output operations that involve a brush, a source bitmap, and a destination bitmap.

See the BitBlt function for a list of common raster operation codes.

Return Value

If the function was successful, the return value is TRUE.

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

Remarks

StretchBlt stretches or compresses the source bitmap in memory and then copies the result to the destination rectangle. The color data for pattern or destination pixels is merged after the stretching or compression occurs.

When an enhanced metafile is being recorded, an error occurs (and the function returns FALSE) if the source device context identifies an enhanced-metafile device context.

If the specified raster operation requires a brush, Windows uses the brush currently selected into the destination device context.

The destination coordinates are transformed by using the transformation currently specified for the destination device context; the source coordinates are transformed by using the transformation currently specified for the source device context.

If the source transformation has a rotation or shear, an error occurs.

If destination, source, and pattern bitmaps do not have the same color format, StretchBlt converts the source and pattern bitmaps to match the destination bitmap.

If StretchBlt must convert a monochrome bitmap to a color bitmap, it sets white bits (1) to the background color and black bits (0) to the foreground color. To convert a color bitmap to a monochrome bitmap, it sets pixels that match the background color to white (1) and sets all other pixels to black (0). The foreground and background colors of the device context with color are used.

StretchBlt creates a mirror image of a bitmap if the signs of the nWidthSrc and nWidthDest parameters or of the nHeightSrc and nHeightDest parameters differ. If nWidthSrc and nWidthDest have different signs, the function creates a mirror image of the bitmap along the x-axis. If nHeightSrc and nHeightDest have different signs, the function creates a mirror image of the bitmap along the y-axis.

Not all devices support the StretchBlt function. For more information, see the GetDeviceCaps function.

See Also

BitBlt, GetDeviceCaps, MaskBlt, PlgBlt, SetStretchBltMode


StretchDIBits
 StretchDIBits  QuickInfo  Overview  Group

The StretchDIBits function copies the color data for a rectangle of pixels in a device-independent bitmap (DIB) to the specified destination rectangle. If the destination rectangle is larger than the source rectangle, this function stretches the rows and columns of color data to fit the destination rectangle. If the destination rectangle is smaller than the source rectangle, this function compresses the rows and columns by using the specified raster operation.

int StretchDIBits(

HDC  hdc,	// handle of device context
int  XDest,	// x-coordinate of upper-left corner of dest. rect.
int  YDest,	// y-coordinate of upper-left corner of dest. rect.
int  nDestWidth,	// width of destination rectangle
int  nDestHeight,	// height of destination rectangle
int  XSrc,	// x-coordinate of upper-left corner of source rect.
int  YSrc,	// y-coordinate of upper-left corner of source rect.
int  nSrcWidth,	// width of source rectangle
int  nSrcHeight,	// height of source rectangle
CONST VOID  *lpBits,	// address of bitmap bits
CONST BITMAPINFO *  lpBitsInfo,	// address of bitmap data
UINT  iUsage,	// usage
DWORD  dwRop	// raster operation code
);
Parameters

hdc

Identifies the destination device context.

XDest

Specifies the x-coordinate, in logical units, of the upper-left corner of the destination rectangle.

YDest

Specifies the y-coordinate, in logical units, of the upper-left corner of the destination rectangle.

nDestWidth

Specifies the width, in logical units, of the destination rectangle.

nDestHeight

Specifies the height, in logical units, of the destination rectangle.

XSrc

Specifies the x-coordinate, in pixels, of the source rectangle in the DIB.

YSrc

Specifies the y-coordinate, in pixels, of the source rectangle in the DIB.

nSrcWidth

Specifies the width, in pixels, of the source rectangle in the DIB.

nSrcHeight

Specifies the height, in pixels, of the source rectangle in the DIB.

lpBits

Points to the DIB bits, which are stored as an array of bytes.

lpBitsInfo

Points to a BITMAPINFO structure that contains information about the DIB.

iUsage

Specifies whether the bmiColors member of the BITMAPINFO structure was provided and, if so, whether bmiColors contains explicit red, green, blue (RGB) values or indices. The iUsage parameter must be one of the following values:

Value	Description
DIB_PAL_COLORS	The array contains 16-bit indices into the logical palette of the source device context.
DIB_RGB_COLORS	The color table contains literal RGB values.
dwRop

Specifies how the source pixels, the destination device context's current brush, and the destination pixels are to be combined to form the new image.

Return Value

If the function succeeds, the return value is the number of scan lines copied.

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

Remarks

The origin of a bottom-up DIB is the bottom-left corner; the origin of a top-down DIB is the upper-left corner.

StretchDIBits creates a mirror image of a bitmap if the signs of the nSrcWidth and nDestWidth parameters, or of the nSrcHeight and nDestHeight parameters differ. If nSrcWidth and nDestWidth have different signs, the function creates a mirror image of the bitmap along the x-axis. If nSrcHeight and nDestHeight have different signs, the function creates a mirror image of the bitmap along the y-axis.

See Also

SetMapMode, SetStretchBltMode, BITMAPINFO


StrokeAndFillPath
 StrokeAndFillPath  QuickInfo  Overview  Group

The StrokeAndFillPath function closes any open figures in a path, strokes the outline of the path by using the current pen, and fills its interior by using the current brush.

BOOL StrokeAndFillPath(

HDC  hdc	// handle of device context
);
Parameters

hdc

Identifies the device context.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To get extended error information, call GetLastError. GetLastError may return one of the following error codes:

ERROR_CAN_NOT_COMPLETE
ERROR_INVALID_PARAMETER
ERROR_NOT_ENOUGH_MEMORY

Remarks

The device context identified by the hdc parameter must contain a closed path.

The StrokeAndFillPath function has the same effect as closing all the open figures in the path, and stroking and filling the path separately, except that the filled region will not overlap the stroked region even if the pen is wide.

See Also

BeginPath, FillPath, SetPolyFillMode, StrokePath


StrokePath
 StrokePath  QuickInfo  Overview  Group

The StrokePath function renders the specified path by using the current pen.

BOOL StrokePath(

HDC  hdc	// handle of device context
);
Parameters

hdc

Identifies a device context that contains a closed path.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To get extended error information, call GetLastError. GetLastError may return one of the following error codes:

ERROR_CAN_NOT_COMPLETE
ERROR_INVALID_PARAMETER
ERROR_NOT_ENOUGH_MEMORY

Remarks

The device context identified by the hdc parameter must contain a closed path.

See Also

BeginPath, EndPath , ExtCreatePen


SubtractRect
 SubtractRect  QuickInfo  Overview  Group

The SubtractRect function obtains the coordinates of a rectangle determined by subtracting one rectangle from another.

BOOL SubtractRect(

LPRECT  lprcDest,	// pointer to destination rectangle
CONST RECT *  lprcSrc1,	// pointer to rectangle to subtract from
CONST RECT *  lprcSrc2	// pointer to rectangle to subtract
);
Parameters

lprcDest

Points to a RECT structure that receives the coordinates of the rectangle determined by subtracting the rectangle pointed to by lprcSrc2 from the rectangle pointed to by lprcSrc1.

lprcSrc1

Points to a RECT structure from which the function subtracts the rectangle pointed to by lprcSrc2.

lprcSrc2

Points to a RECT structure that the function subtracts from the rectangle pointed to by lprcSrc1.

Return Value

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Remarks

The function only subtracts the rectangle specified by lprcSrc2 from the rectangle specified by lprcSrc1 when the rectangles intersect completely in either the x- or y-direction. For example, if *lprcSrc1 has the coordinates (10,10,100,100) and *lprcSrc2 has the coordinates (50,50,150,150), the function sets the coordinates of the rectangle pointed to by lprcDest to (10,10,100,100). If *lprcSrc1 has the coordinates (10,10,100,100) and *lprcSrc2 has the coordinates (50,10,150,150), however, the function sets the coordinates of the rectangle pointed to by lprcDest to (10,10,50,100).

See Also

IntersectRect, RECT, UnionRect


SuspendThread
 SuspendThread  QuickInfo  Overview  Group

The SuspendThread function suspends the specified thread.

DWORD SuspendThread(

HANDLE  hThread	// handle to the thread
);
Parameters

hThread

Identifies the thread. The handle must have THREAD_SUSPEND_RESUME access.

Return Value

If the function succeeds, the return value is the thread's previous suspend count; otherwise, it is 0xFFFFFFFF. To get extended error information, use the GetLastError function.

Remarks

If the function succeeds, execution of the specified thread is suspended and the thread's suspend count is incremented.

Suspending a thread causes the thread to stop executing user-mode (application) code.

Each thread has a suspend count (with a maximum value of MAXIMUM_SUSPEND_COUNT). If the suspend count is greater than zero, the thread is suspended; otherwise, the thread is not suspended and is eligible for execution. Calling SuspendThread causes the target thread's suspend count to be incremented. Attempting to increment past the maximum suspend count causes an error without incrementing the count.

The ResumeThread function decrements the suspend count of a suspended thread.

See Also

ResumeThread


SwapMouseButton
 SwapMouseButton  QuickInfo  Overview  Group

The SwapMouseButton function reverses or restores the meaning of the left and right mouse buttons.

BOOL SwapMouseButton(

BOOL  fSwap	// reverse or restore buttons
);
Parameters

fSwap

Specifies whether the mouse button meanings are reversed or restored. If this parameter is TRUE, the left button generates right-button messages and the right button generates left-button messages. If this parameter is FALSE, the buttons are restored to their original meanings.

Return Value

If the meaning of the mouse buttons was reversed previously, before the function was called, the return value is TRUE.

If the meaning of the mouse buttons was not reversed, the return value is FALSE.

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.

See Also

SetDoubleClickTime


SwitchDesktop [New - Windows NT]
 SwitchDesktop  QuickInfo  Overview  Group

[New - Windows NT]

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 hDesk	// handle of desktop to activate
);
Parameters

hDesk

Identifies the desktop to be made visible and active. This handle is returned by the CreateDesktop and OpenDesktop functions.

The SwitchDesktop function will fail if the desktop belongs to an invisible window station.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

CreateDesktop, OpenDesktop


SwitchStackBack
 SwitchStackBack  Overview  Group

The SwitchStackBack function is not implemented in the Win32 API. Win32-based applications should use the VirtualLock and VirtualUnlock functions.


SwitchStackTo
 SwitchStackTo  Overview  Group

The SwitchStackTo function is not implemented in the Win32 API. Win32-based applications should use the VirtualLock and VirtualUnlock functions.


 SyncAllVoices

The SyncAllVoices function has been deleted.

See Also

Beep, MessageBeep


SysMsgProc
 SysMsgProc  QuickInfo  Overview  Group

The SysMsgProc hook procedure is a library-defined callback function the system calls after an input event occurs in a dialog box, message box, menu, or scroll bar, but before the message generated by the input event is processed. The hook procedure can monitor messages for any dialog box, message box, menu, or scroll bar in the system.

LRESULT CALLBACK SysMsgProc(

int  nCode,	// message flag
WPARAM  wParam,	// undefined
LPARAM  lParam	// address of structure with message data
);
Parameters

nCode

Specifies the type of input event that generated the message. This parameter can be one of the following values:

Value	Meaning
MSGF_DIALOGBOX	The input event occurred in a message box or dialog box.
MSGF_MENU	The input event occurred in a menu.
MSGF_SCROLLBAR	The input event occurred in a scroll bar.
MSGF_NEXTWINDOW	The input event occurred as a result of the user's pressing the ALT+TAB key combination to activate a different window.
If nCode is less than zero, the hook procedure must pass the message to the CallNextHookEx function without further processing and should return the value returned by CallNextHookEx.

wParam

Specifies a NULL value.

lParam

Points to an MSG message structure.

Return Value

If the hook procedure processes the message, the return value must be nonzero. Otherwise, it must be zero.

Remarks

An application installs the hook procedure by specifying the WH_SYSMSGFILTER hook type and the address of the hook procedure in a call to the SetWindowsHookEx function.

SysMsgProc is a placeholder for the library-defined function name.

See Also

CallNextHookEx, MSG, SetWindowsHookEx


SystemParametersInfo
 SystemParametersInfo  QuickInfo  Overview  Group

The SystemParametersInfo function queries or sets systemwide parameters. This function can also update the user profile while setting a parameter.

BOOL SystemParametersInfo(

UINT  uiAction,	// system parameter to query or set
UINT  uiParam,	// depends on action to be taken
PVOID  pvParam,	// depends on action to be taken
UINT  fWinIni	// user profile update flag
);
Parameters

uiAction

Specifies the systemwide parameter to query or set. This parameter can be one of the following values:

Value	Meaning
SPI_GETACCESSTIMEOUT	Retrieves information about the time-out period associated with the accessibility features. The uiParam parameter specifies the size of an ACCESSTIMEOUT structure, and pvParam points to the ACCESSTIMEOUT structure that receives the information.
SPI_GETANIMATION	Windows 95 only: Retrieves the animation effects associated with user actions. The pvParam parameter is the pointer to an ANIMATIONINFO structure that contains the retrieved metrics.
SPI_GETBEEP	Determines whether the warning beeper is on (TRUE) or off (FALSE). The pvParam parameter points to a BOOL variable.
SPI_GETBORDER	Retrieves the border multiplier factor that determines the width of a window's sizing border. The pvParam parameter points to an integer variable.
SPI_GETDEFAULTINPUTLANG	Windows 95 only: Returns the keyboard layout handle for the system default input language. The uiParam is not used. The pvParam parameter points to the 32-bit variable that receives the keyboard layout handle for the default language.
SPI_GETDRAGFULLWINDOWS	Windows 95 only: Determines whether dragging of full windows is enabled. The pvParam parameter points to a BOOL variable that receives TRUE if enabled, or FALSE otherwise.
SPI_GETFASTTASKSWITCH	Determines whether fast task switching is enabled. The pvParam parameter points to a BOOL variable that receives TRUE if enabled, or FALSE otherwise.
SPI_GETFILTERKEYS	Retrieves information about the FilterKeys accessibility feature. The uiParam parameter specifies the size of the FILTERKEYS structure, and pvParam points to the FILTERKEYS structure that receives the information.
SPI_GETGRIDGRANULARITY	Retrieves the current granularity value of the desktop sizing grid. The pvParam parameter points to an integer variable that receives the granularity.
SPI_GETHIGHCONTRAST	Windows 95 only: Retrieves information about the HighContrast accessibility feature. The pvParam parameter is the pointer to the HIGHCONTRAST structure that receives the information.
SPI_GETICONMETRICS	Windows 95 only: Retrieves the metrics associated with icons. The pvParam parameter points to the ICONMETRICS structure to fill in.
SPI_GETICONTITLELOGFONT	Retrieves the logical font information for the current icon-title font. The uiParam parameter specifies the size of a LOGFONT structure, and the pvParam parameter points to the LOGFONT structure to fill in.
SPI_GETICONTITLEWRAP	Determines whether icon-title wrapping is enabled. The pvParam parameter points to a BOOL variable that receives TRUE if enabled, or FALSE otherwise.
SPI_GETKEYBOARDDELAY	Retrieves the keyboard repeat-delay setting. The pvParam parameter points to an integer variable that receives the setting.
SPI_GETKEYBOARDPREF	Windows 95 only: Determines whether the user relies on the keyboard instead of the mouse, and wants applications to display keyboard interfaces that would otherwise be hidden. The uiParam parameter points to a BOOL variable that receives TRUE if the user relies on the keyboard; the variable receives FALSE otherwise.
SPI_GETKEYBOARDSPEED	Retrieves the keyboard repeat-speed setting. The pvParam parameter points to a DWORD variable that receives the setting.
SPI_GETLOWPOWERACTIVE	Windows 95 only: Determines whether the low-power phase of screen saving is enabled or not. The pvParam parameter points to a BOOL variable that receives TRUE if enabled, or FALSE if disabled.
SPI_GETLOWPOWERTIMEOUT	Windows 95 only: Retrieves the time-out value for the low-power phase of screen saving. The pvParam parameter points to an integer value that receives the value.
SPI_GETMENUDROPALIGNMENT	Determines whether pop-up menus are left-aligned or right-aligned, relative to the corresponding menu-bar item. The pvParam parameter points to a BOOL variable that receives TRUE if left-aligned, or FALSE otherwise.
SPI_GETMINIMIZEDMETRICS	Windows 95 only: Retrieves the metrics associated with minimized windows. The uiParam parameter specifies the size of the MINIMIZEDMETRICS structure. The pvParam parameter points to the MINIMIZEDMETRICS structure to fill in.
SPI_GETMOUSE	Retrieves the two mouse threshold values and the mouse speed. The pvParam parameter points to an array of three integers that receives these values. See mouse_event for further information.
SPI_GETMOUSEKEYS	Retrieves information about the MouseKeys accessibility feature. The uiParam parameter specifies the size of a MOUSEKEYS structure, and pvParam points to the MOUSEKEYS structure that receives the information.
SPI_GETNONCLIENTMETRICS	Windows 95 only: Retrieves the metrics associated with the nonclient area of nonminimized windows. The pvParam parameter points to the NONCLIENTMETRICS structure to fill in.
SPI_GETPOWEROFFACTIVE	Windows 95 only: Determines whether the power-off phase of screen saving is enabled or not. The pvParam parameter points to a BOOL variable that receives TRUE if enabled, or FALSE if disabled.
SPI_GETPOWEROFFTIMEOUT	Windows 95 only: Retrieves the time-out value for the power-off phase of screen saving. The pvParam parameter points to an integer value that receives the value.
SPI_GETSCREENREADER	Windows 95 only: Determines whether a screen reviewer utility is running (TRUE) or not (FALSE). A screen reviewer utility directs textual information to an output device, such as a speech synthesizer or Braille display. When this flag is set, an application should provide textual information in situations where it would otherwise present the information graphically. The pvParam parameter points to a BOOL variable.
SPI_GETSCREENSAVEACTIVE	Determines whether screen saving is enabled. The pvParam parameter points to a BOOL variable that receives TRUE if enabled, or FALSE otherwise.
SPI_GETSCREENSAVETIMEOUT	Retrieves the screen saver time-out value, in seconds. The pvParam parameter points to an integer variable that receives the value.
SPI_GETSERIALKEYS	Windows 95 only: Retrieves information about the SerialKeys accessibility feature. The pvParam parameter points to the SERIALKEYS structure that receives the information.
SPI_GETSHOWSOUNDS	Determines whether the user requires an application to present information visually in situations where it would otherwise present the information only in audible form. The uiParam parameter points to a BOOL variable. Using this value is equivalent to calling GetSystemMetrics (SM_GETSHOWSOUNDS). That is the recommended call.
SPI_GETSOUNDSENTRY	Retrieves information about the SoundSentry accessibility feature. The uiParam parameter specifies the size of a SOUNDSENTRY structure, and pvParam points to the SOUNDSENTRY structure that receives the information.
SPI_GETSTICKYKEYS	Retrieves information about the MouseKeys accessibility feature. The uiParam parameter specifies the size of a STICKYKEYS structure, and pvParam points to the STICKYKEYS structure that receives the information.
SPI_GETTOGGLEKEYS	Retrieves information about the ToggleKeys accessibility feature. The uiParam parameter specifies the size of a TOGGLEKEYS structure, and pvParam points to the TOGGLEKEYS structure that receives the information.
SPI_GETWORKAREA	Windows 95 only: Retrieves the size of the working area. The working area is the portion of the screen not obscured by the tray. The pvParam parameter points to the RECT structure that receives the coordinates of the working area.
SPI_ICONHORIZONTALSPACING	Sets the width of an icon cell. The uiParam parameter specifies the width, in pixels.
SPI_ICONVERTICALSPACING	Sets the height of an icon cell. The uiParam parameter specifies the height, in pixels.
SPI_LANGDRIVER	Windows 95: Identifies the language driver. The pvParam parameter points to a character array that receives the filename of the language driver.
SPI_SETACCESSTIMEOUT	Sets the time-out period associated with the accessibility features. The uiParam parameter specifies the size of the ACCESSTIMEOUT structure, and pvParam points to the ACCESSTIMEOUT structure that contains the new parameters.
SPI_SETANIMATION	Windows 95 only: Sets the animation effects associated with user actions. The pvParam parameter points to an ANIMATIONINFO structure that contains the new metrics.
SPI_SETBEEP	Turns the warning beeper on or off. The uiParam parameter specifies TRUE for on, or FALSE for off.
SPI_SETBORDER	Sets the border multiplier factor that determines the width of a window's sizing border. The uiParam parameter specifies the new value.
SPI_SETDEFAULTINPUTLANG	Windows 95 only: Sets the default input language for the system shell and applications. The specified language must be displayable using the current system character set. The uiParam parameter is not used. The pvParam parameter points to a 32-bit variable that contains the keyboard layout handle for the default language.
SPI_SETDESKPATTERN	Sets the current desktop pattern by causing Windows to read the Pattern= setting from the WIN.INI file.
SPI_SETDESKWALLPAPER	Sets the desktop wallpaper. The pvParam parameter points to a null-terminated string containing the name of a bitmap file.
SPI_SETDOUBLECLICKTIME	Sets the double-click time for the mouse to the value of the uiParam parameter. The double-click time is the maximum number of milliseconds that can occur between the first and second clicks of a double-click.
SPI_SETDOUBLECLKHEIGHT	Sets the height of the double-click rectangle to the value of the uiParam parameter. The double-click rectangle is the rectangle within which the second click of a double-click must fall for it to be registered as a double-click.
SPI_SETDOUBLECLKWIDTH	Sets the width of the double-click rectangle to the value of the uiParam parameter. The double-click rectangle is the rectangle within which the second click of a double-click must fall for it to be registered as a double-click.
SPI_SETDRAGFULLWINDOWS	Windows 95 only: Sets dragging of full windows either on or off. The uiParam parameter specifies TRUE for on, or FALSE for off.
SPI_SETDRAGHEIGHT	Windows 95 only: Sets the height, in pixels, of the rectangle used to detect the start of a drag operation.
SPI_SETDRAGWIDTH	Windows 95 only: Sets the width, in pixels, of the rectangle used to detect the start of a drag operation.
SPI_SETFASTTASKSWITCH	Turns fast task switching on or off. The uiParam parameter specifies TRUE for on, or FALSE for off.
SPI_SETFILTERKEYS	Sets the parameters of the FilterKeys accessibility feature. The uiParam parameter specifies the size of the FILTERKEYS structure, and pvParam points to the FILTERKEYS structure that contains the new parameters.
SPI_SETGRIDGRANULARITY	Sets the granularity of the desktop sizing grid to the value of the uiParam parameter.
SPI_SETHIGHCONTRAST	Windows 95 only: Sets the parameters of the HighContrast accessibility feature. The pvParam parameter is the address of the HIGHCONTRAST structure that contains the new parameters.
SPI_SETICONMETRICS	Windows 95 only: Sets the metrics associated with icons. The pvParam parameter points to an ICONMETRICS structure that contains the new metrics.
SPI_SETICONTITLELOGFONT	Sets the font that is used for icon titles. The uiParam parameter specifies the size of a LOGFONT structure, and the lParam parameter points to a LOGFONT structure.
SPI_SETICONTITLEWRAP	Turns icon-title wrapping on or off. The uiParam parameter specifies TRUE for on, or FALSE for off.
SPI_SETKEYBOARDDELAY	Sets the keyboard repeat-delay setting to the value of the uiParam parameter.
SPI_SETKEYBOARDPREF	Windows 95 only: Sets the keyboard preference. The uiParam parameter specifies TRUE if the user relies on the keyboard instead of the mouse, and wants applications to display keyboard interfaces that would otherwise be hidden; uiParam is FALSE otherwise.
SPI_SETKEYBOARDSPEED	Sets the keyboard repeat-speed setting to the value of the uiParam parameter.
SPI_SETLANGTOGGLE	Windows 95 only: Sets the hot key set for switching between input languages. The uiParam and pvParam parameters are not used. The value sets the shortcut keys in the keyboard property sheets by reading the registry again. The registry must be set before this flag is used. the path in the registry is \HKEY_CURRENT_USER\keyboard layout\toggle. Valid values are "1" = ALT+SHIFT, "2" = CTRL+SHIFT, and "3" = none.
SPI_SETLOWPOWERACTIVE	Windows 95 only: Activates or deactivates the low-power phase of screen saving. Set uiParam to 1 to activate, or 0 to deactivate. The pvParam parameter must be NULL.
SPI_SETLOWPOWERTIMEOUT	Windows 95 only: Retrieves the time-out value, in seconds, for the low-power phase of screen saving. The uiParam parameter specifies the new value. The pvParam parameter must be NULL.
SPI_SETMENUDROPALIGNMENT	Sets the alignment value of pop-up menus. The uiParam parameter specifies TRUE for right alignment, or FALSE for left alignment.
SPI_SETMINIMIZEDMETRICS	Windows 95 only: Sets the metrics associated with minimized windows. The pvParam parameter points to a MINIMIZEDMETRICS structure that contains the new metrics.
SPI_SETMOUSE	Sets the two mouse threshold values and the mouse speed. The pvParam parameter points to an array of three integers that specifies these values. See mouse_event for further information.
SPI_SETMOUSEBUTTONSWAP	Swaps or restores the meaning of the left and right mouse buttons. The uiParam parameter specifies TRUE to swap the meanings of the buttons, or FALSE to to restore their original meanings.
SPI_SETMOUSEKEYS	Sets the parameters of the MouseKeys accessibility feature. The uiParam parameter specifies the size of the MOUSEKEYS structure, and pvParam points to the MOUSEKEYS structure that contains the new parameters.
SPI_SETNONCLIENTMETRICS	Windows 95 only: Sets the metrics associated with the nonclient area of nonminimized windows. The pvParam parameter is the address of a NONCLIENTMETRICS structure that contains the new metrics.
SPI_SETPENWINDOWS	Windows 95 only: Specifies that pen windows is being loaded or unloaded. The uiParam parameter is TRUE when loading and FALSE when unloading pen windows. The lParam parameter is NULL.
SPI_SETPOWEROFFACTIVE	Windows 95 only: Activates or deactivates the  power-off phase of screen saving. Set uiParam to 1 to activate, or 0 to deactivate. The pvParam parameter must be NULL.
SPI_SETPOWEROFFTIMEOUT	Windows 95 only: Retrieves the time-out value, in seconds, for the power-off phase of screen saving. The uiParam parameter specifies the new value. The pvParam parameter must be NULL.
SPI_SETSCREENREADER	Windows 95 only: Indicates whether a screen review utility is running. The uiParam parameter specifies TRUE for on, or FALSE for off.
SPI_SETSCREENSAVEACTIVE	Sets the state of the screen saver. The uiParam parameter specifies TRUE to activate screen saving, or FALSE to deactivate it.
SPI_SETSCREENSAVETIMEOUT	Sets the screen saver time-out value to the value of the uiParam parameter. This value is the amount of time, in seconds, that the system must be idle before the screen saver activates.
SPI_SETSERIALKEYS	Windows 95 only: Sets the parameters of the SerialKeys accessibility feature. The pvParam parameter is the address of the SERIALKEYS structure that contains the new parameters.
SPI_SETSHOWSOUNDS	Sets the ShowSounds accessibility feature as on or off. The uiParam parameter specifies TRUE for on, or FALSE for off.
SPI_SETSOUNDSENTRY	Sets the parameters of the SoundSentry accessibility feature. The uiParam parameter specifies the size of the SOUNDSENTRY structure, and pvParam points to the SOUNDSENTRY structure that contains the new parameters.
SPI_SETSTICKYKEYS	Sets the parameters of the StickyKeys accessibility feature. The uiParam parameter specifies the size of the STICKYKEYS structure, and pvParam points to the STICKYKEYS structure that contains the new parameters.
SPI_SETTOGGLEKEYS	Sets the parameters of the ToggleKeys accessibility feature. The uiParam parameter specifies the size of the TOGGLEKEYS structure, and pvParam points to the TOGGLEKEYS structure that contains the new parameters.
SPI_SETWORKAREA	Windows 95 only: Sets the size of the working area. The working area is the portion of the screen not obscured by the tray. The pvParam parameter points to the RECT structure that contains the coordinates of the working area.
uiParam

Depends on the system parameter being queried or set. For more information about systemwide parameters, see the uiAction parameter. If not otherwise indicated, specify zero.

pvParam

Depends on the system parameter being queried or set. For more information about systemwide parameters, see the uiAction parameter. If not otherwise indicated, specify zero.

fWinIni

If a system parameter is being set, specifies whether the user profile is to be updated, and if so, whether the WM_WININICHANGE message is to be broadcast to all top-level windows to notify them of the change. This parameter can be zero or can be one of the following values:

Value	Action
SPIF_UPDATEINIFILE	Writes the new system-wide parameter setting to the user profile.
SPIF_SENDWININICHANGE	Broadcasts the WM_WININICHANGE message after updating the user profile.
Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

This function is intended for use with applications, such as Control Panel, that allow the user to customize the Windows environment.

A keyboard layout name should be derived from the hexadecimal value of the language identifier corresponding to the layout. 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. For a list of the primary language identifiers and sublanguage identifiers that make up a language identifier, see the MAKELANGID macro.

See Also

ACCESSTIMEOUT, ANIMATIONINFO, FILTERKEYS, GetLastError, GetSystemMetrics, HIGHCONTRAST, ICONMETRICS, LOGFONT, MAKELANGID, MINIMIZEDMETRICS, mouse_event, MOUSEKEYS, NONCLIENTMETRICS, RECT, SERIALKEYS, SOUNDSENTRY, STICKYKEYS, TOGGLEKEYS, WM_WININICHANGE


SystemTimeToFileTime
 SystemTimeToFileTime  QuickInfo  Overview  Group

The SystemTimeToFileTime function converts a system time to a file time.

BOOL SystemTimeToFileTime(

CONST SYSTEMTIME *  lpst,	// address of system time to convert
LPFILETIME  lpft	// address of buffer for converted file time
);
Parameters

lpst

Points to a SYSTEMTIME structure that contains the time to be converted.

The wDayOfWeek member of the SYSTEMTIME structure is ignored.

lpft

Points to a FILETIME structure to receive the converted system time.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

DosDateTimeToFileTime, FILETIME, FileTimeToDosDateTime, FileTimeToSystemTime, SYSTEMTIME


SystemTimeToTzSpecificLocalTime
 SystemTimeToTzSpecificLocalTime  QuickInfo  Overview  Group

The SystemTimeToTzSpecificLocalTime function converts a Coordinated Universal Time (UTC) to a specified time zone's corresponding local time.

BOOL SystemTimeToTzSpecificLocalTime (

LPTIME_ZONE_INFORMATION  lpTimeZoneInformation,	// pointer to time zone of interest
LPSYSTEMTIME  lpUniversalTime,	// pointer to universal time of interest
LPSYSTEMTIME  lpLocalTime	// pointer to structure to receive local time
);
Parameters

lpTimeZoneInformation

Pointer to a TIME_ZONE_INFORMATION structure that specifies the time zone of interest.

If lpTimeZoneInformation is NULL, the function uses the currently active time zone.

lpUniversalTime

Pointer to a SYSTEMTIME structure that specifies a UTC. The function converts this universal time to the specified time zone's corresponding local time.

lpLocalTime

Pointer to a SYSTEMTIME structure that receives the local time information.

Return Value

If the function succeeds, the return value is TRUE, and the function sets the members of the SYSTEMTIME structure pointed to by lpLocalTime to the appropriate local time values.

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

Remarks

The SystemTimeToTzSpecificLocalTime function works in Windows NT. If called in Windows 95, the function fails, and returns FALSE.

See Also

GetSystemTime, GetTimeZoneInformation, SYSTEMTIME, TIME_ZONE_INFORMATION


TabbedTextOut
 TabbedTextOut  QuickInfo  Overview  Group

The TabbedTextOut function writes a character string at a specified location, expanding tabs to the values specified in an array of tab-stop positions. Text is written in the currently selected font.

LONG TabbedTextOut(

HDC  hdc,	// handle of device context
int  x,	// x-coordinate of starting position
int  y,	// y-coordinate of starting position
LPCTSTR  lpString,	// address of string
int  nCount,	// number of characters in string
int  nTabPositions,	// number of tabs in array
LPINT  lpnTabStopPositions,	// address of array for tab positions
int  nTabOrigin	// x-coordinate for tab expansion
);
Parameters

hdc

Identifies the device context.

x

Specifies the x-coordinate of the starting point of the string, in logical units.

y

Specifies the y-coordinate of the starting point of the string, in logical units.

lpString

Points to the character string to draw. The string does not need to be zero-terminated, since nCount specifies the length of the string.

nCount

Specifies the number of characters in the string.

nTabPositions

Specifies the number of values in the array of tab-stop positions.

lpnTabStopPositions

Points to an array containing the tab-stop positions, in device units. The tab stops must be sorted in increasing order; the smallest x-value should be the first item in the array.

Windows 95 only: A tab stop can be specified as a negative value, which causes text to be right-aligned on the tab stop rather than left-aligned.

nTabOrigin

Specifies the x-coordinate of the starting position from which tabs are expanded, in logical units.

Return Value

If the function succeeds, the return value is the dimensions, in logical units, of the string. The height is in the high-order word and the width is in the low-order word.

Remarks

If the nTabPositions parameter is zero and the lpnTabStopPositions parameter is NULL, tabs are expanded to eight times the average character width.

If nTabPositions is 1, the tab stops are separated by the distance specified by the first value in the lpnTabStopPositions array.

If the lpnTabStopPositions array contains more than one value, a tab stop is set for each value in the array, up to the number specified by nTabPositions.

The nTabOrigin parameter allows an application to call the TabbedTextOut function several times for a single line. If the application calls TabbedTextOut more than once with the nTabOrigin set to the same value each time, the function expands all tabs relative to the position specified by nTabOrigin.

By default, the current position is not used or updated by the TabbedTextOut function. If an application needs to update the current position when it calls TabbedTextOut, the application can call the SetTextAlign function with the wFlags parameter set to TA_UPDATECP. When this flag is set, Windows ignores the x and y parameters on subsequent calls to the TabbedTextOut function, using the current position instead.

See Also

DrawText, GetTabbedTextExtent, GrayString, SetTextAlign, TextOut


TerminateProcess
 TerminateProcess  QuickInfo  Overview  Group

The TerminateProcess function terminates the specified process and all of its threads.

BOOL TerminateProcess(

HANDLE  hProcess,	// handle to the process
UINT  uExitCode	// exit code for the process
);
Parameters

hProcess

Identifies the process to terminate. The handle must have PROCESS_TERMINATE access.

uExitCode

Specifies the exit code for the process and for all threads terminated as a result of this call. Use the GetExitCodeProcess function to retrieve the process's exit value. Use the GetExitCodeThread function to retrieve a thread's exit value.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The TerminateProcess function is used to unconditionally cause a process to exit. Use it only in extreme circumstances. The state of global data maintained by dynamic-link libraries (DLLs) may be compromised if TerminateProcess is used rather than ExitProcess.

TerminateProcess causes all threads within a process to terminate, and causes a process to exit, but DLLs attached to the process are not notified that the process is terminating.

Terminating a process causes the following:

1.	All of the object handles opened by the process are closed.

2.	All of the threads in the process terminate their execution.

3.	The state of the process object becomes signaled, satisfying any threads that had been waiting for the process to terminate.

4.	The states of all threads of the process become signaled, satisfying any threads that had been waiting for the threads to terminate.

5.	The termination status of the process changes from STILL_ACTIVE to the exit value of the process.

Terminating a process does not cause child processes to be terminated.

Terminating a process does not necessarily remove the process object from the system. A process object is deleted when the last handle to the process is closed.

See Also

ExitProcess, OpenProcess, GetExitCodeProcess, GetExitCodeThread,


TerminateThread
 TerminateThread  QuickInfo  Overview  Group

The TerminateThread function terminates a thread.

BOOL TerminateThread(

HANDLE  hThread,	// handle to the thread
DWORD  dwExitCode	// exit code for the thread
);
Parameters

hThread

Identifies the thread to terminate. The handle must have THREAD_TERMINATE access.

dwExitCode

Specifies the exit code for the thread. Use the GetExitCodeThread function to retrieve a thread's exit value.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

TerminateThread is used to cause a thread to exit. When this occurs, the target thread has no chance to execute any user-mode code and its initial stack is not deallocated. DLLs attached to the thread are not notified that the thread is terminating.

TerminateThread is a dangerous function that should only be used in the most extreme cases. You should call TerminateThread only if you know exactly what the target thread is doing, and you control all of the code that the target thread could possibly be running at the time of the termination. For example, TerminateThread can result in the following problems:

•	If the target thread owns a critical section, the critical section will not be released.

•	If the target thread is executing certain kernel32 calls when it is terminated, the kernel32 state for the thread's process could be inconsistent.

•	If the target thread is manipulating the global state of a shared DLL, the state of the DLL could be destroyed, affecting other users of the DLL.

A thread cannot protect itself against TerminateThread, other than by controlling access to its handles. The thread handle returned by the CreateThread and CreateProcess functions has THREAD_TERMINATE access, so any caller holding one of these handles can terminate your thread.

If the target thread is the last thread of a process when this function is called, the thread's process is also terminated.

The state of the thread object becomes signaled, releasing any other threads that had been waiting for the thread to terminate. The thread's termination status changes from STILL_ACTIVE to the value of the dwExitCode parameter.

Terminating a thread does not necessarily remove the thread object from the system. A thread object is deleted when the last thread handle is closed.

See Also

CreateProcess, CreateThread, ExitThread, GetExitCodeThread


TextOut
 TextOut  QuickInfo  Overview  Group

The TextOut function writes a character string at the specified location, using the currently selected font.

BOOL TextOut(

HDC  hdc,	// handle of device context
int  nXStart,	// x-coordinate of starting position
int  nYStart,	// y-coordinate of starting position
LPCTSTR  lpString,	// address of string
int  cbString	// number of characters in string
);
Parameters

hdc

Identifies the device context.

nXStart

Specifies the logical x-coordinate of the reference point that Windows uses to align the string.

nYStart

Specifies the logical y-coordinate of the reference point that Windows uses to align the string.

lpString

Points to the string to be drawn. The string does not need to be zero-terminated, since cbString specifies the length of the string.

cbString

Specifies the number of characters in the string.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The interpretation of the reference point depends on the current text-alignment mode. An application can retrieve this mode by calling the GetTextAlign function; an application can alter this mode by calling the SetTextAlign function.

By default, the current position is not used or updated by this function. However, an application can call the SetTextAlign function with the fMode parameter set to TA_UPDATECP to permit Windows to use and update the current position each time the application calls TextOut for a specified device context. When this flag is set, Windows ignores the nXStart and nYStart parameters on subsequent TextOut calls.

When the TextOut function is placed inside a path bracket, the system generates a path for the TrueType text that includes each character plus its character box. The region generated is the character box minus the text, rather than the text itself. You can obtain the region enclosed by the outline of the TrueType text by setting the background mode to transparent before placing the TextOut function in the path bracket. Following is sample code that demonstrates this procedure.

// Obtain the window's client rectangle

GetClientRect(hwnd, &r);

// THE FIX: by setting the background mode

// to transparent, the region is the text itself

// SetBkMode(hdc, TRANSPARENT);

// Bracket begin a path

BeginPath(hdc);

// Send some text out into the world

TextOut(hdc, r.left, r.top, "Defenestration can be hazardous", 4);

// Bracket end a path

EndPath(hdc);

// Derive a region from that path

SelectClipPath(hdc, RGN_AND);

// This generates the same result as SelectClipPath()

// SelectClipRgn(hdc, PathToRegion(hdc));

// Fill the region with grayness

FillRect(hdc, &r, GetStockObject(GRAY_BRUSH));

See Also

GetTextAlign, SetTextAlign, TabbedTextOut


Throw
 Throw  Overview  Group

The Throw function is not implemented in the Win32 API.

Structured exception handling is built into the Win32 application programming interface. For more information about structured exception handling, see Structured Exception Handling.


TileWindows [New - Windows 95]
 TileWindows  QuickInfo

[New - Windows 95]

The TileWindows function tiles the specified windows, or the child windows of the specified parent window.

WORD WINAPI TileWindows(

HWND hwndParent,	// handle of parent window
WORD wFlags,	// types of windows not to arrange
LPCRECT lpRect,	// rectangle to arrange windows in
WORD cChildrenb,	// number of windows to arrange
const HWND FAR *ahwndChildren	// array of window handles
);
Parameters

hwndParent

Identifies the parent window. If this parameter is NULL, the desktop window is assumed.

wFlags

Specifies the types of windows not to arrange, and whether to tile vertically or horizontally. This parameter can be one of the following values combined with zero or more of the values listed with the CascadeWindows function:

Value	Meaning
MDITILE_HORIZONTAL	Tiles windows horizontally.
MDITILE_VERTICAL	Tiles windows vertically.
lpRect

Points to a SMALL_RECT structure that specifies the rectangular area, in screen coordinates, within which the windows are arranged. If this parameter is NULL, the client area of the parent window is used.

cChildren

Specifies the number of elements in the array specified by the ahwndChildren parameter. This parameter is ignored if ahwndChildren is NULL.

ahwndChildren

Points to an array of window handles identifying the windows to arrange. If this parameter is NULL, the child windows of the specified parent window (or of the desktop window) are arranged.

Return Value

If the function succeeds, the return value is the number of windows arranged.

If the function fails, the return value is zero.

See Also

CascadeWindows, SMALL_RECT


TimerProc
 TimerProc  QuickInfo  Overview  Group

The TimerProc function is an application-defined callback function that processes WM_TIMER messages.

VOID CALLBACK TimerProc(

HWND  hwnd,	// handle of window for timer messages
UINT  uMsg,	// WM_TIMER message
UINT  idEvent,	// timer identifier
DWORD  dwTime	// current system time
);
Parameters

hwnd

Identifies the window associated with the timer.

uMsg

Specifies the WM_TIMER message.

idEvent

Specifies the timer's identifier.

dwTime

Specifies the system time, in Coordinated Universal Time (UTC) format.

Return Value

This function does not return a value.

Remarks

TimerProc is a placeholder for the application-defined function name.

See Also

KillTimer, SetTimer, WM_TIMER


TlsAlloc
 TlsAlloc  QuickInfo  Overview  Group

The TlsAlloc function allocates a thread local storage (TLS) index. Any thread of the process can subsequently use this index to store and retrieve values that are local to the thread.

DWORD TlsAlloc(VOID)

Parameters

This function has no parameters.

Return Value

If the function succeeds, the return value is a TLS index.

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

Remarks

The threads of the process can use the TLS index in subsequent calls to the TlsFree, TlsSetValue, or TlsGetValue functions.

TLS indexes are typically allocated during process or dynamic-link library (DLL) initialization. Once allocated, each thread of the process can use a TLS index to access its own TLS storage slot. To store a value in its slot, a thread specifies the index in a call to TlsSetValue. The thread specifies the same index in a subsequent call to TlsGetValue, to retrieve the stored value.

The constant TLS_MINIMUM_AVAILABLE defines the minimum number of TLS indexes available in each process. This minimum is guaranteed to be at least 64 for all systems.

TLS indexes are not valid across process boundaries. A DLL cannot assume that an index assigned in one process is valid in another process.

A DLL might use TlsAlloc, TlsSetValue, TlsGetValue, and TlsFree as follows:

1.	When a DLL attaches to a process, the DLL uses TlsAlloc to allocate a TLS index. The DLL then allocates some dynamic storage and uses the TLS index in a call to TlsSetValue to store the address in the TLS slot. This concludes the per-thread initialization for the initial thread of the process. The TLS index is stored in a global or static variable of the DLL.

2.	Each time the DLL attaches to a new thread of the process, the DLL allocates some dynamic storage for the new thread and uses the TLS index in a call to TlsSetValue to store the address in the TLS slot. This concludes the per-thread initialization for the new thread.

3.	Each time an initialized thread makes a DLL call requiring the data in its dynamic storage, the DLL uses the TLS index in a call to TlsGetValue to retrieve the address of the dynamic storage for that thread.

For additional information on thread local storage, see Thread Local Storage.

See Also

TlsFree, TlsGetValue, TlsSetValue


TlsFree
 TlsFree  QuickInfo  Overview  Group

The TlsFree function releases a thread local storage (TLS) index, making it available for reuse.

BOOL TlsFree(

DWORD  dwTlsIndex	// TLS index to free
);
Parameters

dwTlsIndex

Specifies a TLS index that was allocated by the TlsAlloc function.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

If the threads of the process have allocated dynamic storage and used the TLS index to store pointers to this storage, they should free the storage before calling TlsFree. The TlsFree function does not free any dynamic storage that has been associated with the TLS index. It is expected that DLLs call this function (if at all) only during their process detach routine.

For a brief discussion of typical uses of the TLS functions, see the Remarks section of the TlsAlloc function.

See Also

TlsAlloc, TlsGetValue, TlsSetValue


TlsGetValue
 TlsGetValue  QuickInfo  Overview  Group

The TlsGetValue function retrieves the value in the calling thread's thread local storage (TLS) slot for a specified TLS index. Each thread of a process has its own slot for each TLS index.

LPVOID TlsGetValue(

DWORD  dwTlsIndex	// TLS index to retrieve value for
);
Parameters

dwTlsIndex

Specifies a TLS index that was allocated by the TlsAlloc function.

Return Value

If the function succeeds, the return value is the value stored in the calling thread's TLS slot associated with the specified index.

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

Note that the data stored in a TLS slot can have a value of zero. In this case, the return value is zero and GetLastError returns NO_ERROR.

Remarks

TLS indexes are typically allocated by the TlsAlloc function during process or DLL initialization. Once allocated, each thread of the process can use a TLS index to access its own TLS storage slot for that index. The storage slot for each thread is initialized to NULL. A thread specifies a TLS index in a call to TlsSetValue, to store a value in its slot. The thread specifies the same index in a subsequent call to TlsGetValue, to retrieve the stored value.

TlsSetValue and TlsGetValue were implemented with speed as the primary goal. These functions perform minimal parameter validation and error checking. In particular, this function succeeds if dwTlsIndex is in the range 0 through (TLS_MINIMUM_AVAILABLE − 1). It is up to the programmer to ensure that the index is valid.

Win32 functions that return indications of failure call SetLastError when they fail. They generally do not call SetLastError when they succeed. The TlsGetValue function is an exception to this general rule. The TlsGetValue function calls SetLastError to clear a thread's last error when it succeeds. That allows checking for the error-free retrieval of NULL values.

See Also

GetLastError, SetLastError, TlsAlloc, TlsFree, TlsSetValue


TlsSetValue
 TlsSetValue  QuickInfo  Overview  Group

The TlsSetValue function stores a value in the calling thread's thread local storage (TLS) slot for a specified TLS index. Each thread of a process has its own slot for each TLS index.

BOOL TlsSetValue(

DWORD  dwTlsIndex,	// TLS index to set value for
LPVOID  lpvTlsValue	// value to be stored
);
Parameters

dwTlsIndex

Specifies a TLS index that was allocated by the TlsAlloc function.

lpvTlsValue

Specifies the value to be stored in the calling thread's TLS slot specified by dwTlsIndex.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

TLS indexes are typically allocated by the TlsAlloc function during process or DLL initialization. Once allocated, each thread of the process can use a TLS index to access its own TLS storage slot for that index. The storage slot for each thread is initialized to NULL. A thread specifies a TLS index in a call to TlsSetValue, to store a value in its slot. The thread specifies the same index in a subsequent call to TlsGetValue, to retrieve the stored value.

TlsSetValue and TlsGetValue were implemented with speed as the primary goal. These functions perform minimal parameter validation and error checking. In particular, this function succeeds if dwTlsIndex is in the range 0 through (TLS_MINIMUM_AVAILABLE − 1). It is up to the programmer to ensure that the index is valid.

See Also

TlsAlloc, TlsFree, TlsGetValue


ToAscii
 ToAscii  QuickInfo  Overview  Group

The ToAscii function translates the specified virtual-key code and keyboard state to the corresponding Windows character or characters.

int ToAscii(

UINT  uVirtKey,	// virtual-key code
UINT  uScanCode,	// scan code
PBYTE  lpbKeyState,	// address of key-state array
LPWORD  lpwTransKey,	// buffer for translated key
UINT  fuState	// active-menu flag
);
Parameters

uVirtKey

Specifies the virtual-key code to be translated.

uScanCode

Specifies the hardware scan code of the key to be translated. The high-order bit of this value is set if the key is up.

lpbKeyState

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

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.

lpwTransKey

Points to the buffer that will receive the translated Windows character or characters.

fuState

Specifies whether a menu is active. This parameter must be 1 if a menu is active, or 0 otherwise.

Return Value

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

Although NUM LOCK is a toggle key that affects keyboard behavior, ToAscii ignores the toggle setting (the low bit) of lpbKeyState(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).

See Also

OemKeyScan, ToUnicode, VkKeyScan


ToAsciiEx [New - Windows 95]
 ToAsciiEx  QuickInfo

[New - Windows 95]

The ToAsciiEx function translates the specified virtual-key code and keyboard state to the corresponding Windows character or characters. The function translates the code using the input language and physical keyboard layout identified by the given keyboard layout handle.

int ToAsciiEx(

UINT uVirtKey,	// virtual-key code
UINT ScanCode,	// scan code
BYTE *lpbKeyState,	// address of key-state array
DWORD *lpdwTransKey,	// buffer for translated key
UINT fuState,	// active-menu flag
HKL hkl	// keyboard layout handle
);
Parameters

uVirtKey

Specifies the virtual-key code to be translated.

uScanCode

Specifies the hardware scan code of the key to be translated. The high-order bit of this value is set if the key is up (not pressed).

lpbKeyState

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

lpdwTransKey

Points to a doubleword buffer that receives the translated Windows character or characters.

fuState

Specifies whether a menu is active. This parameter must be 1 if a menu is active, zero otherwise.

hkl

Identifies the keyboard layout to use to translate the given code. This parameter can be any keyboard layout handle previously returned by the LoadKeyboardLayout function.

Return Value

If the function succeeds, the return value is the number of characters copied to the translated-key buffer. This number is typically greater than one for a ligated key or for an accent and a dead-key character. The function returns a negative value if the specified key is a dead key and returns zero if no conversion was done.

Remarks

The parameters supplied to the ToAsciiEx function might not be sufficient to translate the virtual-key code, because a previous dead key is stored in the keyboard layout.

Typically, ToAsciiEx performs the translation based on the virtual-key code. In some cases, however, bit 15 of the uScanCode parameter may be used to distinguish between a key press and a key release. The scan code is used for translating ALT+number key combinations.

See Also

LoadKeyboardLayout, MapVirtualKeyEx, OemKeyScan, ToAscii, VkKeyScan


ToUnicode
 ToUnicode  QuickInfo  Overview  Group

The ToUnicode function translates the specified virtual-key code and keyboard state to the corresponding Unicode character or characters.

int ToUnicode(

UINT  wVirtKey,	// virtual-key code
UINT  wScanCode,	// scan code
PBYTE  lpKeyState,	// address of key-state array
LPWSTR  pwszBuff,	// buffer for translated key
int  cchBuff,	// size of translated key buffer
UINT  wFlags	// set of function-conditioning flags
);
Parameters

wVirtKey

Specifies the virtual-key code to be translated.

wScanCode

Specifies the hardware scan code of the key to be translated. The high-order bit of this value is set if the key is up.

lpKeyState

Points 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

Points to the buffer that receives the translated Unicode character or characters.

cchBuff

Specifies the size in characters of the buffer pointed to by the pwszBuff parameter.

wFlags

A set of bit flags that condition the behavior of the function. Set bit 0 if a menu is active. Bits 1 through 31 are reserved.

Return Value

The function returns one of the following values:

Value	Meaning
− 1	The specified virtual key is a dead-key character (accent or diacritic). This value is returned regardless of the keyboard layout, even if several characters have been typed and are stored in the keyboard state. If possible, even with Unicode keyboard layouts, the function has written a spacing version of the dead-key character to the buffer specified by pwszBuffer. For example, the function writes the character SPACING ACUTE (0x00B4), rather than the character NON_SPACING ACUTE (0x0301).
0	The specified virtual key has no translation for the current state of the keyboard. Nothing was written to the buffer specified by pwszBuffer.
1	One character was written to the buffer specified by pwszBuffer.
2 or more	Two or more characters were written to the buffer specified by pwszBuff. The most common cause for this is that a dead-key character (accent or diacritic) stored in the keyboard layout could not be combined with the specified virtual key to form a single character.
Remarks

The parameters supplied to the ToUnicode function might not be sufficient to translate the virtual-key code because a previous dead key is stored in the keyboard layout.

Typically, ToUnicode performs the translation based on the virtual-key code. In some cases, however, bit 15 of the wScanCode parameter can be used to distinguish between a key press and a key release.

See Also

ToAscii, VkKeyScan


TrackPopupMenu
 TrackPopupMenu  QuickInfo  Overview  Group

The TrackPopupMenu function displays a floating pop-up menu at the specified location and tracks the selection of items on the pop-up menu. The floating pop-up menu can appear anywhere on the screen.

BOOL TrackPopupMenu(

HMENU hMenu,	// handle of pop-up menu
UINT uFlags,	// screen-position and mouse-button flags
int x,	// horizontal position, in screen coordinates
int y,	// vertical position, in screen coordinates
int nReserved,	// reserved, must be zero
HWND hWnd,	// handle of owner window
CONST RECT * prcRect	// points to RECT that specifies no-dismissal area
);
Parameters

hMenu

Identifies the pop-up menu to be displayed. The handle can be obtained by calling CreatePopupMenu to create a new pop-up menu, or by calling GetSubMenu to retrieve the handle of a pop-up menu associated with an existing menu item.

uFlags

A set of bit flags that specify function options.

Use one of the following bit flag constants to specify how the function positions the popup menu horizontally:

Value	Meaning
TPM_CENTERALIGN	If this flag is set, the function centers the pop-up menu horizontally relative to the coordinate specified by the x parameter.
TPM_LEFTALIGN	If this flag is set, the function positions the pop-up menu so that its left side is aligned with the coordinate specified by the x parameter.
TPM_RIGHTALIGN	Positions the pop-up menu so that its right side is aligned with the coordinate specified by the x parameter.
Use one of the following bit flag constants to specify which mouse button the pop-up menu tracks:

Value	Meaning
TPM_LEFTBUTTON	If this flag is set, the pop-up menu tracks the left mouse button.
TPM_RIGHTBUTTON	If this flag is set, the pop-up menu tracks the right mouse button
x

Specifies the horizontal location of the pop-up menu, in screen coordinates.

y

Specifies the vertical location of the pop-up menu, in screen coordinates.

nReserved

Reserved; must be zero.

hWnd

Identifies the window that owns the pop-up 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.

prcRect

Points to a RECT structure that specifies the portion of the screen in which the user can select without dismissing the pop-up menu. If this parameter is NULL, the pop-up menu is dismissed if the user clicks outside the pop-up menu.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

CreatePopupMenu, GetSubMenu, RECT, WM_COMMAND


TrackPopupMenuEx [New - Windows 95]
 TrackPopupMenuEx  QuickInfo  Overview  Group

[New - Windows 95]

The TrackPopupMenuEx function displays a floating pop-up menu at the specified location and tracks the selection of items on the pop-up menu. The floating pop-up menu can appear anywhere on the screen.

BOOL TrackPopupMenuEx(

HMENU  hmenu,
UINT  fuFlags,
int  x,
int  y,
HWND  hwnd,
LPTPMPARAMS  lptpm
);
Parameters

hmenu

Handle to the pop-up menu to be displayed. This handle can be obtained by calling the CreatePopupMenu function to create a new pop-up menu or by calling the GetSubMenu function to retrieve the handle to a pop-up menu associated with an existing menu item.

fuFlags

Positioning and other options. This parameter, which can be zero or more of the values listed with the TrackPopupMenu function, may also include one of the following values:

Value	Meaning
TPM_HORIZONTAL	If the menu cannot be shown at the specified location without overlapping the excluded rectangle, the system tries to accommodate the requested horizontal alignment before the requested vertical alignment.
TPM_VERTICAL	If the menu cannot be shown at the specified location without overlapping the excluded rectangle, the system tries to accommodate the requested vertical alignment before the requested horizontal alignment.
The excluded rectangle is a portion of the screen that the menu should not overlap; it is specified by lptpm.

x

Horizontal location of the pop-up menu, in screen coordinates.

y

Vertical location of the pop-up menu, in screen coordinates.

hwnd

Handle to the window that owns the pop-up 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.

lptpm

Pointer to a TPMPARAMS structure that specifies an area of the screen the menu should not overlap. This parameter can be NULL.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To get extended error information, use the GetLastError function.

See Also

CreatePopupMenu, GetSubMenu, TPMPARAMS, TrackPopupMenu, WM_COMMAND


TransactNamedPipe
 TransactNamedPipe  QuickInfo  Overview  Group

The TransactNamedPipe function combines into a single network operation the functions that write a message to and read a message from the specified named pipe.

BOOL TransactNamedPipe(

HANDLE  hNamedPipe,	// handle of named pipe
LPVOID  lpvWriteBuf,	// address of write buffer
DWORD  cbWriteBuf,	// size of the write buffer, in bytes
LPVOID  lpvReadBuf,	// address of read buffer
DWORD  cbReadBuf,	// size of read buffer, in bytes
LPDWORD  lpcbRead,	// address of variable for bytes actually read
LPOVERLAPPED  lpo	// address of overlapped structure
);
Parameters

hNamedPipe

Identifies the named pipe returned by the CreateNamedPipe or CreateFile function.

lpvWriteBuf

Points to the buffer containing the data written to the pipe.

cbWriteBuf

Specifies the size, in bytes, of the write buffer.

lpvReadBuf

Points to the buffer that receives the data read from the pipe.

cbReadBuf

Specifies the size, in bytes, of the read buffer.

lpcbRead

Points to the variable that receives the number of bytes read from the pipe.

lpo

Points to an OVERLAPPED structure. If this parameter is NULL or if the FILE_FLAG_OVERLAPPED flag was not specified in the CreateNamedPipe or CreateFile function when the handle was created, TransactNamedPipe does not return until the operation is finished.

If this parameter is not NULL and FILE_FLAG_OVERLAPPED was specified when the handle was created, TransactNamedPipe is executed as an overlapped operation. The OVERLAPPED structure should contain a manual-reset event object (which can be created by using the CreateEvent function). If the operation cannot be completed immediately, TransactNamedPipe returns FALSE and GetLastError returns ERROR_IO_PENDING. In this situation, the event object is set to the nonsignaled state before TransactNamedPipe returns, and it is set to the signaled state when the transaction has finished. For more information about overlapped operations, see Pipes.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

TransactNamedPipe fails if the server did not create the pipe as a message-type pipe or if the pipe handle is not in message-read mode. A pipe handle can be set to message-read mode with the SetNamedPipeHandleState function. The wait mode of the specified pipe handle (blocking or nonblocking) has no effect on TransactNamedPipe.

The function cannot be completed successfully until data is written into the buffer specified by the lpvReadBuf parameter. The lpo parameter is available to enable the calling thread to perform other tasks while the operation is executing in the background.

If the message to be read is longer than the buffer specified by the cbReadBuf parameter, TransactNamedPipe returns FALSE and the GetLastError function returns ERROR_MORE_DATA. The remainder of the message can be read by a subsequent call to ReadFile, ReadFileEx, or PeekNamedPipe.

See Also

CreateEvent, CreateFile, CreateNamedPipe, PeekNamedPipe, ReadFile, ReadFileEx, SetNamedPipeHandleState, OVERLAPPED


TranslateAccelerator
 TranslateAccelerator  QuickInfo  Overview  Group

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 of destination window
HACCEL  haccl,	// handle of accelerator table
LPMSG  lpmsg	// address of structure with message
);
Parameters

hwnd

Identifies the window whose messages are to be translated.

haccl

Identifies an accelerator table. The accelerator table must have been loaded by a call to the LoadAccelerators function or created by a call to the CreateAcceleratorTable function.

lpmsg

Points to an MSG structure that contains message information retrieved from the calling thread's message queue by using the GetMessage or PeekMessage function.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

To differentiate the message from messages sent by menus or controls, the high-order word of the lParam parameter of the WM_COMMAND or WM_SYSCOMMAND message contains the value 1.

Accelerator key combinations used to select items from the System menu are translated into WM_SYSCOMMAND messages; all other accelerator key combinations are translated into WM_COMMAND messages.

When TranslateAccelerator returns a nonzero value and the message is translated, the application should not use the TranslateMessage function to process the message again.

An accelerator need not correspond to a menu command.

If the accelerator command corresponds to a menu item, the application is sent WM_INITMENU and WM_INITMENUPOPUP messages, as if the user were trying to display the menu. However, these messages are not sent if any of the following conditions exist:

•	The window is disabled.

•	The menu item is disabled.

•	The accelerator key combination does not correspond to an item on the System 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 System menu, the function sends a WM_COMMAND message, even if the window is minimized.

See Also

CreateAcceleratorTable, GetMessage, LoadAccelerators, MSG, PeekMessage, SetCapture, TranslateMessage, WM_COMMAND, WM_INITMENU, WM_INITMENUPOPUP, WM_KEYDOWN, WM_SYSKEYDOWN, WM_SYSCOMMAND


TranslateCharsetInfo [New - Windows 95]
 TranslateCharsetInfo  QuickInfo  Overview  Group

[New - Windows 95]

The TranslateCharsetInfo function translates based on the specified character set, code page, or font signature value, setting all members of the destination structure to appropriate values.

UINT TranslateCharsetInfo(

DWORD FAR * lpSrc,
LPCHARSETINFO lpCs,
DWORD  dwFlags
);
Parameters

lpSrc

Address or value as defined by the dwFlags parameter. If dwFlags is TCI_SRCFONTSIG, this parameter is the address of the fsCsb member of a FONTSIGNATURE structure. Otherwise, this parameter is a 32-bit value.

lpCs

Pointer to a CHARSETINFO structure that receives the translated character set information.

dwFlags

Translation flags. This parameter can be one of the following values:

Value	Meaning
TCI_SRCCHARSET	Source contains the character set value in the low word, and zero in the high word.
TCI_SRCCODEPAGE	Source is a code-page value in the low word and zero in the high word.
TCI_SRCFONTSIG	Source is the code-page bitfield portion of a FONTSIGNATURE structure. On input this should have only one Windows code-page bit set, either for an ANSI code-page value or for a common ANSI and OEM value (for OEM values, bits 32-63 must be clear.). On output this will have only one bit set. If the TCI_SRCFONTSIG value is given, the lpSrc parameter must be the address of the codepage bit field. If any other TCI_ value is given, the lpSrc parameter must be a value not an address.
See Also

CHARSETINFO, FONTSIGNATURE


TranslateMDISysAccel
 TranslateMDISysAccel  QuickInfo  Overview  Group

The TranslateMDISysAccel function processes accelerator keystrokes for System 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 of MDI client window
LPMSG  lpmsg	// address of structure with message data
);
Parameters

hwndClient

Identifies the MDI client window.

lpmsg

Points 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 Value

If TranslateMDISysAccel translates a message into a system command, the return value is TRUE; otherwise, it is FALSE.

See Also

GetMessage, PeekMessage, TranslateAccelerator, MSG, WM_KEYDOWN, WM_KEYUP, WM_SYSCOMMAND


TranslateMessage
 TranslateMessage  QuickInfo  Overview  Group

The TranslateMessage function translates virtual-key messages into character messages. The character messages are posted to the calling thread's message queue, to be read the next time the thread calls the GetMessage or PeekMessage function.

BOOL TranslateMessage(

CONST MSG  *lpmsg	// address of structure with message
);
Parameters

lpmsg

Points to an MSG structure that contains message information retrieved from the calling thread's message queue by using the GetMessage or PeekMessage function.

Return Value

If the message is translated (that is, a character message is posted to the thread's message queue), the return value is TRUE; otherwise, it is FALSE.

Windows NT: The TranslateMessage function returns TRUE for function and arrow keys as well as for character and digit keys.

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

See Also

GetMessage, PeekMessage, TranslateAccelerator, WM_CHAR, WM_DEADCHAR, WM_KEYDOWN, WM_KEYUP, WM_SYSCHAR, WM_SYSDEADCHAR, WM_SYSKEYDOWN, WM_SYSKEYUP


TransmitCommChar
 TransmitCommChar  QuickInfo  Overview  Group

The TransmitCommChar function transmits a specified character ahead of any pending data in the output buffer of the specified communications device.

BOOL TransmitCommChar(

HANDLE  hCommDev,	// handle of communications device
char  chTransmit	// character to transmit
);
Parameters

hCommDev

Identifies the communications device. The CreateFile function returns this handle.

chTransmit

Specifies the character to be transmitted.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The TransmitCommChar function is useful for sending an interrupt character (such as a CTRL+C) to a host system.

If the device is not transmitting, TransmitCommChar cannot be called repeatedly. Once TransmitCommChar places a character in the output buffer, the character must be transmitted before the function can be called again. If the previous character has not yet been sent, TransmitCommChar returns an error.

Character transmission is subject to normal flow control and handshaking. This function can only be called synchronously.

See Also

CreateFile, WaitCommEvent


TransmitFile [New - Windows NT]
 TransmitFile  QuickInfo

[New - Windows NT]

The TransmitFile function transmits file data over a connected socket handle. The function uses the operating system's cache manager to retrieve the file data. This function provides high-performance file data transfer over sockets.

BOOL TransmitFile(

SOCKET  hSocket,	// handle to a connected socket
HANDLE  hFile,	// handle to an open file
DWORD   nNumberOfBytesToWrite,	// number of bytes to transmit
DWORD   nNumberOfBytesPerSend,	// number of bytes per sockets send operation
LPOVERLAPPED  lpOverlapped,	// pointer to overlapped I/O data structure
LPTRANSMIT_FILE_BUFFERS  lpTransmitBuffers,	// pointer to data to send before and after file data
DWORD   dwReserved	// reserved; must be zero
);
Parameters

hSocket

Handle to a connected socket. The function will transmit the file data over this socket.

The socket specified by hSocket must be a virtual circuit socket. A socket of type SOCK_STREAM, SOCK_SEQPACKET, or SOCK_RDM is a virtual circuit socket. The TransmitFile function does not support datagram sockets.

hFile

Handle to an open file. The function transmits this file's data. The operating system reads the file data sequentially. You can improve caching performance by opening the handle with the FILE_FLAG_SEQUENTIAL_SCAN .

nNumberOfBytesToWrite

Specifies the number of bytes to transmit. The function completes when it has sent this many bytes, or an error occurs.

Set this parameter to zero to transmit the entire file.

nNumberOfBytesPerSend

Specifies the size of each socket send operation. This specification is for use by the sockets layer of the operating system.

Set this parameter to zero to indicate that the sockets layer should use an intelligent default send size.

This parameter is useful for message protocols that have limitations on the size of individual send requests.

lpOverlapped

Pointer to an OVERLAPPED structure. If the socket handle has been opened as overlapped, specify this parameter in order to achieve an overlapped (aysnchronous) I/O operation.

Note that, by default, socket handles are opened as overlapped.

Note that you can use this parameter to specify an offset within the file at which to start the file data transfer. You do that by setting the Offset and OffsetHigh fields of the OVERLAPPED structure. If lpOverlapped is NULL, the transmission of data always starts at the current byte offset in the file.

When lpOverlapped is not NULL, the overlapped I/O may not finish before TransmitFile returns. In that case, the TransmitFile function returns FALSE, and GetLastError returns ERROR_IO_PENDING. This lets the caller continue processing while the file transmission operation completes. The operating system will set the event specified by the hEvent field of the OVERLAPPED structure, or the socket specified by hSocket, to the signalled state upon completion of the data transmission request.

lpTransmitBuffers

Pointer to a TRANSMIT_FILE_BUFFERS data structure that contains pointers to data to send before and after the file data is sent.

Set this parameter to NULL if you only want to transmit the file data.

dwReserved

Reserved; must be zero.

Return Value

If the function succeeds, the return value is TRUE.

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

Note that the function returns FALSE if an overlapped I/O operation is not complete before TransmitFile returns. In that case, GetLastError returns ERROR_IO_PENDING.

Remarks

The Windows NT Server optimizes the TransmitFile function for high performance. The Windows NT Workstation optimizes the function for minimum memory and resource utilization. Expect better performance results when using TransmitFile on Windows NT Server.

See Also

OVERLAPPED, TRANSMIT_FILE_BUFFERS


UInt32x32To64
 UInt32x32To64  QuickInfo  Overview  Group

The UInt32x32To64 function multiplies two unsigned 32-bit integers, returning an unsigned 64-bit integer result. The function performs optimally on all Win32 platforms.

DWORDLONG UInt32x32To64(

DWORD  Multiplier,	// specifies first unsigned 32-bit integer for the multiplication
DWORD  Multiplicand	// specifies second unsigned 32-bit integer for the multiplication
);
Parameters

Multiplier

Specifies the first unsigned 32-bit integer for the multiplication.

Multiplicand

Specifies the second unsigned 32-bit integer for the multiplication.

Return Value

The return value is the unsigned 64-bit integer result of the multiplication.

Remarks

This function is implemented on all platforms by optimal inline code: a single multiply instruction that returns a 64-bit result.

Please note that the function's return value is a 64-bit value, not a LARGE_INTEGER structure.

See Also

Int32x32To64


UndeleteFile
 UndeleteFile  QuickInfo  Overview  Group

The UndeleteFile function is an application-defined callback function that File Manager calls when the user chooses the Undelete command from the File Manager File menu.

DWORD APIENTRY UndeleteFile(

HWND  hwndOwner,	// handle of File Manager window
LPSTR  lpszDir	// address of name of initial directory
);
Parameters

hwndOwner

Identifies the File Manager window. An "undelete" dynamic-link library (DLL) should use this handle to specify the owner window for any dialog box or message box the DLL may display.

lpszDir

Points to a null-terminated string that contains the name of the initial directory.

Return Value

If the function succeeds, the return value is one of the following:

Value	Meaning
−l	An error occurred.
IDOK	A file was undeleted. File Manager repaints its windows.
IDCANCEL	No file was undeleted.


UnhandledExceptionFilter
 UnhandledExceptionFilter  QuickInfo  Overview  Group

The UnhandledExceptionFilter function passes unhandled exceptions to the debugger, if the process is being debugged. Otherwise, it optionally displays an Application Error message box and causes the exception handler to be executed. This function can be called only from within the filter expression of a try-except exception handler.

LONG UnhandledExceptionFilter(

STRUCT _EXCEPTION_POINTERS *  lpexpExceptionInfo	// address of exception info
);
Parameters

lpexpExceptionInfo

Points to an EXCEPTION_POINTERS structure containing a description of the exception and the processor context at the time of the exception. This pointer is the return value of a call to the GetExceptionInformation function.

Return Value

The function returns one of the following values:

Value	Meaning
EXCEPTION_CONTINUE_SEARCH	The process is being debugged, so the exception should be passed (as second chance) to the application's debugger.
EXCEPTION_EXECUTE_HANDLER	If the SEM_NOGPFAULTERRORBOX flag was specified in a previous call to SetErrorMode, no Application Error message box is displayed. The function returns control to the exception handler, which is free to take any appropriate action.
Remarks

If the process is not being debugged, the function displays an Application Error message box, depending on the current error mode. The default behavior is to display the dialog box, but this can be disabled by specifying SEM_NOGPFAULTERRORBOX in a call to the SetErrorMode function.

The system uses UnhandledExceptionFilter internally to handle exceptions that occur during process and thread creation.

See Also

EXCEPTION_POINTERS, GetExceptionInformation, SetErrorMode, SetUnhandledExceptionFilter, UnhandledExceptionFilter


UnhookWindowsHook
 UnhookWindowsHook  QuickInfo  Overview  Group

The UnhookWindowsHook function is obsolete, but is provided for compatibility with 16-bit versions of Windows. For Win32-based applications, use the UnhookWindowsHookEx function.

BOOL UnhookWindowsHook(

int  nCode,	// type of hook to remove procedure from
HOOKPROC  hkprc	// address of hook procedure
);


UnhookWindowsHookEx
 UnhookWindowsHookEx  QuickInfo  Overview  Group

The UnhookWindowsHookEx function removes a hook procedure installed in a hook chain by the SetWindowsHookEx function.

BOOL UnhookWindowsHookEx(

HHOOK  hhook	// handle of hook procedure to remove
);
Parameters

hhook

Identifies the hook to be removed. This parameter is a hook handle obtained by a previous call to SetWindowsHookEx.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

The hook procedure can be in the state of being called by another thread even after UnhookWindowsHookEx returns. If the hook procedure is not being called concurrently, the hook procedure is removed immediately before UnhookWindowsHookEx returns.

See Also

SetWindowsHookEx, UnhookWindowsHook


UnionRect
 UnionRect  QuickInfo  Overview  Group

The UnionRect function creates the union of two rectangles. The union is the smallest rectangle that contains both source rectangles.

BOOL UnionRect(

LPRECT  lprcDst,	// address of structure for union
CONST RECT  *lprcSrc1,	// address of structure with first rectangle
CONST RECT  *lprcSrc2	// address of structure with second rectangle
);
Parameters

lprcDst

Points to the RECT structure that will receive a rectangle containing the rectangles pointed to by the lprcSrc1 and lprcSrc2 parameters.

lprcSrc1

Points to the RECT structure that contains the first source rectangle.

lprcSrc2

Points to the RECT structure that contains the second source rectangle.

Return Value

If the specified structure contains a nonempty rectangle, the return value is TRUE; otherwise, it is FALSE. To get extended error information, call GetLastError.

Remarks

Windows ignores the dimensions of an empty rectangle — that is, a rectangle in which all coordinates are set to zero, so that it has no height or no width.

See Also

InflateRect, IntersectRect, OffsetRect, RECT


UnloadKeyboardLayout
 UnloadKeyboardLayout  QuickInfo  Overview  Group

The UnloadKeyboardLayout function removes a keyboard layout.

BOOL UnloadKeyboardLayout(

HKL  hkl	// handle of keyboard layout
);
Parameters

hkl

Identifies the keyboard layout to unload.

Return Value

If the function succeeds, the return value is the handle of the keyboard layout; otherwise, it is NULL. To get extended error information, use the GetLastError function.

Remarks

Windows 95: UnloadKeyboardLayout cannot unload the system default keyboard layout. This ensures that an appropriate character set is always available for the user to type commands for the shell or names for the file system.

Windows NT: UnloadKeyboardLayout can unload the system default keyboard layout.

See Also

ActivateKeyboardLayout, GetKeyboardLayoutName, LoadKeyboardLayout


UnlockFile
 UnlockFile  QuickInfo  Overview  Group

The UnlockFile function unlocks a region in an open file. Unlocking a region enables other processes to access the region.

BOOL UnlockFile(

HANDLE  hFile,	// handle of file to unlock
DWORD  dwFileOffsetLow,	// low-order word of lock region offset
DWORD  dwFileOffsetHigh,	// high-order word of lock region offset
DWORD  cbUnlockLow,	// low-order word of length to unlock
DWORD  cbUnlockHigh	// high-order word of length to unlock
);
Parameters

hFile

Identifies a file that contains a region locked with LockFile. The file handle must have been created with either GENERIC_READ or GENERIC_WRITE access to the file.

dwFileOffsetLow

Specifies the low-order word of the starting byte offset in the file where the locked region begins.

dwFileOffsetHigh

Specifies the high-order word of the starting byte offset in the file where the locked region begins.

cbUnlockLow

Specifies the low-order word of the length of the byte range to be unlocked.

cbUnlockHigh

Specifies the high-order word of the length of the byte range to be unlocked.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

Unlocking a region of a file releases a lock on the file. The region to unlock must correspond exactly to an existing locked region. For example, two adjacent regions of a file cannot be locked separately and then unlocked as a single region that spans both locked regions.

A process should not be terminated with a portion of a file locked and a file that has locked regions should not be closed.

This function works on a file allocation table (FAT) − based file system only if the operating system is running SHARE.EXE.

See Also

CreateFile, LockFile


UnlockFileEx
 UnlockFileEx  QuickInfo  Overview  Group

The UnlockFileEx function unlocks a previously locked byte range in an open file.

BOOL UnlockFileEx(

HANDLE  hFile,	// handle of file to unlock
DWORD  dwReserved,	// reserved, must be set to zero
DWORD  nNumberOfBytesToUnlockLow,	// low order 32-bits of length to unlock
DWORD  nNumberOfBytesToUnlockHigh,	// high order 32-bits of length to unlock
LPOVERLAPPED  lpOverlapped	// addr. of struct. with unlock region start offset
);
Parameters

hFile

Identifies an open handle to a file that is to have an existing locked region unlocked. The handle must have been created with either GENERIC_READ or GENERIC_WRITE access to the file.

dwReserved

Reserved parameter; must be zero.

nNumberOfBytesToUnlockLow

Specifies the low-order 32-bits of the length of the byte range to unlock.

nNumberOfBytesToUnlockHigh

Specifies the high-order 32-bits of the length of the byte range to unlock.

lpOverlapped

Points to an OVERLAPPED structure that the function uses with the unlocking request. This structure contains the file offset of the beginning of the unlock range.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

Unlocking a region of a file releases a previously acquired lock on a file. The region to unlock must correspond exactly to an existing locked region. Two adjacent regions of a file can not be locked separately and then unlocked using a single region that spans both locked regions.

If a process terminates with a portion of a file locked or closes a file that has outstanding locks, the behavior is not specified.

See Also

CreateFile, LockFile, LockFileEx, OVERLAPPED, UnlockFile


UnlockResource
 UnlockResource  QuickInfo  Overview  Group

The UnlockResource function is obsolete. It is not necessary for Win32-based applications to unlock resources.

See Also

LoadResource, LockResource


UnlockSegment
 UnlockSegment  QuickInfo  Overview  Group

The UnlockSegment function is obsolete. Segments have no meaning in the 32-bit environment.


UnlockServiceDatabase
 UnlockServiceDatabase  QuickInfo  Overview  Group

The UnlockServiceDatabase function unlocks a service control manager database by releasing the specified lock.

BOOL UnlockServiceDatabase(

SC_LOCK  sclLock	// service control manager database lock to be released
);
Parameters

sclLock

Specifies a lock obtained from a previous call to the LockServiceDatabase function.

Return Value

If the function succeeds, the return value is TRUE.

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

Errors

The following error codes may be set by the service control manager. Other error codes may be set by the registry functions that are called by the service control manager.

Value	Meaning
ERROR_INVALID_SERVICE_LOCK	The specified lock is invalid.
See Also

LockServiceDatabase, QueryServiceLockStatus


UnmapViewOfFile
 UnmapViewOfFile  QuickInfo  Overview  Group

The UnmapViewOfFile function unmaps a mapped view of a file from the calling process's address space.

BOOL UnmapViewOfFile(

LPVOID  lpBaseAddress	// address where mapped view begins
);
Parameters

lpBaseAddress

Points to the base address of the mapped view of a file that is to be unmapped. This value must be identical to the value returned by a previous call to the MapViewOfFile or MapViewOfFileEx function.

Return Value

If the function succeeds, the return value is TRUE, and all dirty pages within the specified range are written "lazily" to disk.

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

Remarks

Although an application may close the file handle used to create a file mapping object, the system holds the corresponding file open until the last view of the file is unmapped.

Windows 95: Files for which the last view has not yet been unmapped are held open with the same sharing restrictions as the original file handle.

Windows NT: Files for which the last view has not yet been unmapped are held open with no sharing restrictions.

See Also

MapViewOfFile, MapViewOfFileEx


UnpackDDElParam
 UnpackDDElParam  QuickInfo  Overview  Group

The UnpackDDElParam function unpacks a DDE lParam value received from a posted DDE message.

BOOL UnpackDDElParam(

UINT  uMsg,	// posted DDE message
LONG  lParam,	// lParam of posted DDE message
PUINT  puLow,	// address of low-order word of lParam
PUINT  puHigh	// address of high-order word of lParam
);
Parameters

uMsg

Specifies the posted DDE message.

lParam

Specifies the lParam parameter of the posted DDE message that was received. The application must free the memory object specified by the lParam parameter by calling the FreeDDElParam function.

puLow

Points to a value the function will set to the low-order word of lParam.

puHigh

Points to a value the function will set to the high-order word of lParam.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

PackDDElParam eases the porting of 16-bit DDE applications to 32-bit DDE applications.

See Also

FreeDDElParam, PackDDElParam, ReuseDDElParam


UnrealizeObject
 UnrealizeObject  QuickInfo  Overview  Group

The UnrealizeObject function resets a logical palette. It directs the system to realize the palette as though it had not previously been realized. The next time the application calls the RealizePalette function for the specified palette, the system completely remaps the logical palette to the system palette.

If hgdiobj is a brush, UnrealizeObject does nothing, and the function returns TRUE. Use SetBrushOrgEx to set the origin of a brush.

BOOL UnrealizeObject(

HGDIOBJ  hgdiobj	// logical palette handle
);
Parameters

hgdiobj

Identifies the logical palette to be reset.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The UnrealizeObject function should not be used with stock objects. The default palette, obtained by calling GetStockObject(DEFAULT_PALETTE), is a stock object.

A palette identified by hgdiobj can be the currently selected palette of a device context.

See Also

GetStockObject, RealizePalette, SetBrushOrgEx


UnregisterClass
 UnregisterClass  QuickInfo  Overview  Group

The UnregisterClass function removes a window class, freeing the memory required for the class.

BOOL UnregisterClass(

LPCTSTR  lpszClass,	// address of class name string
HINSTANCE  hinst	// handle of application instance
);
Parameters

lpszClass

Points to a null-terminated string or is an integer atom. If this parameter is an integer atom, it must be a global atom created by a previous call to the GlobalAddAtom function. The atom, a 16-bit value less than 0xC000, must be in the low-order word of lpszClass; the high-order word must be zero.

If lpszClass is a string, it specifies the window class name. This class name must have been registered by a previous call to the RegisterClass function. System global classes, such as dialog box controls, cannot be unregistered.

hinst

Identifies the instance of the module that created the class.

Return Value

If the function succeeds, the return value is TRUE. If the class could not be found or if a window still exists that was created with the class, the return value is FALSE. 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.

See Also

GlobalAddAtom, RegisterClass


UnregisterHotKey
 UnregisterHotKey  QuickInfo  Overview  Group

The UnregisterHotKey function frees a hot key previously registered by the calling thread.

BOOL UnregisterHotKey(

HWND  hwnd,	// window associated with hot key
int  idHotKey	// identifier of hot key
);
Parameters

hwnd

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

idHotKey

Specifies the identifier of the hot key to be freed.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

RegisterHotKey, WM_HOTKEY


UpdateColors
 UpdateColors  QuickInfo  Overview  Group

The UpdateColors function updates the client area of the specified device context by remapping the current colors in the client area to the currently realized logical palette.

BOOL UpdateColors(

HDC  hdc	// handle of device context
);
Parameters

hdc

Identifies the device context.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

An application can determine whether a device supports palette operations by calling the GetDeviceCaps function and specifying the RASTERCAPS constant.

An inactive window with a realized logical palette may call UpdateColors as an alternative to redrawing its client area when the system palette changes.

The UpdateColors function typically updates a client area faster than redrawing the area. However, because UpdateColors performs the color translation based on the color of each pixel before the system palette changed, each call to this function results in the loss of some color accuracy.

This function must be called soon after a WM_PALETTECHANGED message is received.

See Also

GetDeviceCaps, RealizePalette


UpdateICMRegKey
 UpdateICMRegKey  Overview  Group

The UpdateICMRegKey function installs, removes, or queries registry entries that identify ICC color profiles or color-matching DLLs. The function carries out the action specified by the nCommand parameter.

BOOL UpdateICMRegKey(

DWORD  dwReserved,
DWORD  CMID,
LPTSTR  lpszFileName,
UINT  nCommand
);
Parameters

dwReserved

Reserved; must be zero.

CMID

Profile identifier of the color-matching DLL to use with the profile.

lpszFileName

Pointer to a zero-terminated string that specifies the filename of an ICC color profile or address of a DEVMODE structure, depending on the value of nCommand.

nCommand

Action flag. This parameter can have one of the following values:

ICM_ADDPROFILE	Adds the ICC profile to the ICM branch in the registry.
ICM_DELETEPROFILE	Deletes the ICC profile from the ICM branch in the registry.
ICM_QUERYPROFILE	Determines if the profile is in the ICM branch of the registry.
ICM_SETDEFAULTPROFILE	Makes the profile first among equals.
ICM_REGISTERICMATCHER	Equates a CMID to a color-matching DLL.
ICM_UNREGISTERICMATCHER	Removes the reference between CMID and a color-matching DLL.
ICM_QUERYMATCH	Determines if a profile exists based on the DEVMODE pointed to by lpszFileName.
Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is NULL.

Remarks

GDI uses the registry to keep track of ICC profiles installed in the system (listed in the registry). Although not required, if ICC profiles are copied to a local directory, they should be placed in the Color directory in the Windows System directory.

See Also

DEVMODE


UpdateResource
 UpdateResource  QuickInfo  Overview  Group

The UpdateResource function adds, deletes, or replaces a resource in an executable file.

BOOL UpdateResource(

HANDLE  hUpdateFile,	// update-file handle
LPCTSTR  lpszType,	// address of resource type to update
LPCTSTR  lpszName,	// address of resource name to update
WORD  IDLanguage,	// language identifier of resource
LPVOID  lpvData,	// address of resource data
DWORD  cbData	// length of resource data, in bytes
);
Parameters

hUpdateFile

Specifies an update-file handle. This handle is returned by the BeginUpdateResource function.

lpszType

Points to a null-terminated string specifying the resource type to be updated. This parameter can also be an integer value passed to the MAKEINTRESOURCE macro, or it can be one of the following predefined resource types:

Value	Meaning
RT_ACCELERATOR	Accelerator table
RT_BITMAP	Bitmap resource
RT_DIALOG	Dialog box
RT_FONT	Font resource
RT_FONTDIR	Font directory resource
RT_MENU	Menu resource
RT_RCDATA	Application-defined resource (raw data)
RT_STRING	String-table entry
RT_MESSAGETABLE	Message-table entry
RT_CURSOR	Hardware-dependent cursor resource
RT_GROUP_CURSOR	Hardware-independent cursor resource
RT_ICON	Hardware-dependent icon resource
RT_GROUP_ICON	Hardware-independent icon resource
RT_VERSION	Version resource
lpszName

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

IDLanguage

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

lpvData

Points 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; lpvData must not point to ANSI data.

If lpvData is NULL, the specified resource is deleted from the executable file.

cbData

Specifies the size, in bytes, of the resource data at lpvData.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. 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.

See Also

BeginUpdateResource, EndUpdateResource, LoadIcon, LoadString, LockResource, MAKEINTRESOURCE, MAKELANGID, SizeofResource


UpdateWindow
 UpdateWindow  QuickInfo  Overview  Group

The UpdateWindow function updates the client area of the specified window by sending a WM_PAINT message to the window if the window's update region is not empty. The function sends a WM_PAINT message directly to the window procedure of the specified window, bypassing the application queue. If the update region is empty, no message is sent.

BOOL UpdateWindow(

HWND  hwnd	// handle of window
);
Parameters

hwnd

Identifies the window to be updated.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

See Also

ExcludeUpdateRgn, GetUpdateRect, GetUpdateRgn, InvalidateRect, InvalidateRgn, WM_PAINT


ValidateRect
 ValidateRect  QuickInfo  Overview  Group

The ValidateRect function validates the client area within a rectangle by removing the rectangle from the update region of the specified window.

BOOL ValidateRect(

HWND  hwnd,	// handle of window
CONST RECT  *lprc	// address of validation rectangle coordinates
);
Parameters

hwnd

Identifies the window whose update region is to be modified. If this parameter is NULL, Windows invalidates and redraws all windows and sends the WM_ERASEBKGND and WM_NCPAINT messages to the window procedure before the function returns.

lprc

Points to a RECT structure that contains the client coordinates of the rectangle to be removed from the update region. If this parameter is NULL, the entire client area is removed.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

The BeginPaint function automatically validates the entire client area. Neither the ValidateRect nor ValidateRgn function should be called if a portion of the update region must be validated before the next WM_PAINT message is generated.

Windows continues to generate WM_PAINT messages until the current update region is validated.

See Also

BeginPaint, InvalidateRect, InvalidateRgn, RECT, ValidateRgn, WM_PAINT


ValidateRgn
 ValidateRgn  QuickInfo  Overview  Group

The ValidateRgn function validates the client area within a region by removing the region from the current update region of the specified window.

BOOL ValidateRgn(

HWND  hwnd,	// handle of window
HRGN  hrgn	// handle of valid region
);
Parameters

hwnd

Identifies the window whose update region is to be modified.

hrgn

Identifies a region that defines the area to be removed from the update region. If this parameter is NULL, the entire client area is removed.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

The specified region must have been created by a region function. The region coordinates are assumed to be client coordinates.

The BeginPaint function automatically validates the entire client area. Neither the ValidateRect nor ValidateRgn function should be called if a portion of the update region must be validated before the next WM_PAINT message is generated.

See Also

BeginPaint, ExcludeUpdateRgn, InvalidateRect, InvalidateRgn, ValidateRect, WM_PAINT


VerFindFile
 VerFindFile  QuickInfo  Overview  Group

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

As with the other file installation functions, VerFindFile will only work with Win32 file images. 16-bit Windows file images are not supported.

DWORD VerFindFile(

DWORD  dwFlags,	// bit flags that condition function behavior
LPTSTR  szFileName,	// file to be installed
LPTSTR  szWinDir,	// Windows directory
LPTSTR  szAppDir,	// directory where related files are being installed
LPTSTR  szCurDir,	// receives path of directory where file is currently installed
PUINT  lpuCurDirLen,	// size of string in szCurDir
LPTSTR  szDestDir,	// receives path of recommended destination directory
PUINT  lpuDestDirLen	// size of string in szDestDir
);
Parameters

dwFlags

Contains a bitmask of flags. 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 values are reserved.

szFileName

Points to the name of the file to be installed. The filename can include only the filename and extension, not a path.

szWinDir

Points to the directory in which Windows is running or will be run. This string is returned by the GetWindowsDirectory function.

szAppDir

Points to 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

Points 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

Points to a variable that contains 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

Points 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

Points to a variable that contains 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 Value

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

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 Windows, the function recommends installing the file in the Windows directory. If the system is running a private copy of Windows, the function recommends installing the file in the system directory.

See Also

GetWindowsDirectory, OpenFile, VerInstallFile


VerInstallFile
 VerInstallFile  QuickInfo  Overview  Group

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.

As with the other file installation functions, VerInstallFile will only work with Win32 file images. 16-bit Windows file images are not supported.

DWORD VerInstallFile(

DWORD  dwFlags,	// bit flags that condition function behavior
LPTSTR  szSrcFileName,	// file to install
LPTSTR  szDestFileName,	// new name of file to install
LPTSTR  szSrcDir,	// source directory of file to install
LPTSTR  szDestDir,	// directory in which to install file
LPTSTR  szCurDir,	// directory where file is currently installed
LPTSTR  szTmpFile,	// receives name of temporary copy of file used during installation
PUINT  lpuTmpFileLen	// size of string in szTmpFile
);
Parameters

dwFlags

Contains a bitmask of flags. 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 values are reserved.

szSrcFileName

Points to 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

Points to 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

Points to a buffer that contains the name of the directory where the new file is found.

szDestDir

Points to a buffer that contains the name of the directory where the new file should be installed. VerFindFile returns this value in its szDestDir parameter.

szCurDir

Points to a buffer that contains the name of the directory where the preexisting version of this file is found. VerFindFile returns this value in its szCurDir parameter.

szTmpFile

Points to a buffer that should be empty upon the initial call to VerInstallFile. The function fills the buffer with 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.

lpuTmpFileLen

Points to a variable that contains the length of the szTmpFile buffer. This pointer must not be NULL.

When the function returns, lpuTmpFileLen contains 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 Value

The return value is a bitmask that indicates exceptions. It can be one or more of the following values:

Value	Meaning
VIF_TEMPFILE	The temporary copy of the new file is in the destination directory. The cause of failure is reflected in other flags.
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_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_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_DIFFCODEPG	The new file requires a code page that cannot be displayed by the version of Windows currently running. This error can be overridden by calling VerInstallFile 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_WRITEPROT	The preexisting file is write protected. This error can be overridden by calling VerInstallFile again with the VIFF_FORCEINSTALL flag set.
VIF_FILEINUSE	The preexisting file is in use by Windows and cannot be deleted.
VIF_OUTOFSPACE	The function cannot create the temporary file due to insufficient disk space on the destination drive.
VIF_ACCESSVIOLATION	A read, create, delete, or rename operation failed due to an access violation.
VIF_SHARINGVIOLATION	A read, create, delete, or rename operation failed due to a sharing violation.
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_CANNOTRENAME	The function cannot rename the temporary file, but already deleted the destination file.
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_CANNOTREADSRC	The function cannot read the source file. This could mean that the path was not specified properly.
VIF_CANNOTREADDST	The function cannot read the destination (existing) files. This prevents the function from examining the file's attributes.
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.
All other values are reserved.

Remarks

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.

See Also

VerFindFile


VerLanguageName
 VerLanguageName  QuickInfo  Overview  Group

The VerLanguageName function converts the specified binary Microsoft language identifier into a text representation of the language.

DWORD VerLanguageName(

DWORD  idLang,	// Microsoft language identifier
LPTSTR  lpszLang,	// address of buffer for language string
DWORD  cbLang	// size of buffer
);
Parameters

idLang

Specifies the binary Microsoft language identifier. For example, VerLanguageName translates 0x040A into Castilian Spanish. If VerLanguageName does not recognize the identifier, the lpszLang parameter points to a default string ("Language-Neutral"). For a complete list of the language identifiers supported by Win32, see the following Remarks section.

lpszLang

Points to the buffer to receive the null-terminated string representing the language specified by the idLang parameter.

cbLang

Indicates the size of the buffer, in characters, pointed to by lpszLang.

Return Value

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

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.

Following are the possible language identifiers and their corresponding languages:

Identifier	Language
0x0000	Language-Neutral
0x0400	Process Default Language
0x0401	Arabic
0x0402	Bulgarian
0x0403	Catalan
0x0404	Traditional Chinese
0x0804	Simplified Chinese
0x0405	Czech
0x0406	Danish
0x0407	German
0x0807	Swiss German
0x0408	Greek
0x0409	U.S. English
0x0809	U.K. English
0x0C09	Australian English
0x1009	Canadian English
0x040A	Castilian Spanish
0x080A	Mexican Spanish
0x0C0A	Modern Spanish
0x040B	Finnish
0x040C	French
0x080C	Belgian French
0x0C0C	Canadian French
0x100C	Swiss French
0x040D	Hebrew
0x040E	Hungarian
0x040F	Icelandic
0x0410	Italian
0x0810	Swiss Italian
0x0411	Japanese
0x0412	Korean
0x0413	Dutch
0x0813	Belgian Dutch
0x0414	Norwegian — Bokmål
0x0814	Norwegian — Nynorsk
0x0415	Polish
0x0416	Brazilian Portuguese
0x0816	Portuguese
0x0417	Rhaeto-Romanic
0x0418	Romanian
0x0419	Russian
0x041A	Croato-Serbian (Latin)
0x081A	Serbo-Croatian (Cyrillic)
0x041B	Slovak
0x041C	Albanian
0x041D	Swedish
0x041E	Thai
0x041F	Turkish
0x0420	Urdu
0x0421	Bahasa
See Also

VerQueryValue


VerQueryValue
 VerQueryValue  QuickInfo  Overview  Group

The VerQueryValue function returns selected version information from the specified version-information resource. To retrieve the appropriate resource, the GetFileVersionInfo function must be called before VerQueryValue.

As with the other file installation functions, VerQueryValue will only work with Win32 file images. 16-bit Windows file images are not supported.

BOOL VerQueryValue(

const LPVOID  pBlock,	// address of buffer for version resource
LPTSTR  lpSubBlock,	// address of value to retrieve
LPVOID  *lplpBuffer,	// address of buffer for version pointer
PUINT  puLen	// address of version-value length buffer
);
Parameters

pBlock

Points to the buffer containing the version-information resource returned by GetFileVersionInfo.

lpSubBlock

Points to a zero-terminated string specifying which version-information value to retrieve. The string consists of names separated by backslashes (\) and can 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 table in the variable information structure. The function retrieves a pointer to an array of language and character-set identifiers. An application uses these identifiers to create the name of a language-specific structure in the version-information resource.
\StringFileInfo\lang-charset\string-name	Specifies a value in a language-specific structure. The lang-charset name is a concatenation of a language and character-set identifier pair found in the translation table for the resource. The lang-charset name must be specified as a hexadecimal string. The string-name name is one of the predefined strings described in the following Remarks section.
lplpBuffer

Points to a buffer that receives a pointer to the version-information value.

puLen

Points to a buffer that receives the length, in characters, of the version-information value.

Return Value

If the specified 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

The Win32 API contains the following predefined version information strings:

CompanyName FileDescription FileVersion InternalName LegalCopyright OriginalFilename ProductName ProductVersion

The following example shows how to retrieve the FileDescription string-value from a block of version information:

VerQueryValue(pBlock,

              TEXT("\\StringFileInfo\\040904E4\\FileDescription"),

              &lpBuffer,

              &dwBytes);

Call the GetFileVersionInfoSize and GetFileVersionInfo functions to properly initialize the pBlock buffer before calling the VerQueryValue function.

See Also

GetFileVersionInfo, GetFileVersionInfoSize, VS_FIXEDFILEINFO, VS_VERSION_INFO


VirtualAlloc
 VirtualAlloc  QuickInfo  Overview  Group

The VirtualAlloc function reserves or commits a region of pages in the virtual address space of the calling process. Memory allocated by this function is automatically initialized to zero.

LPVOID VirtualAlloc(

LPVOID  lpvAddress,	// address of region to reserve or commit
DWORD  cbSize,	// size of region
DWORD  fdwAllocationType,	// type of allocation
DWORD  fdwProtect	// type of access protection
);
Parameters

lpvAddress

Specifies the desired starting address of the region to allocate. If the memory is being reserved, the specified address is rounded down to the next 64-kilobyte boundary. If the memory is already reserved and is being committed, the address is rounded down to the next page boundary. To determine the size of a page on the host computer, use the GetSystemInfo function. If this parameter is NULL, the system determines where to allocate the region.

cbSize

Specifies the size, in bytes, of the region. If the lpvAddress parameter is NULL, this value is rounded up to the next page boundary. Otherwise, the allocated pages include all pages containing one or more bytes in the range from lpvAddress to (lpvAddress+cbSize). This means that a 2-byte range straddling a page boundary causes both pages to be included in the allocated region.

fdwAllocationType

Specifies the type of allocation. You can specify any combination of the following flags:

Flag	Meaning
MEM_COMMIT	Allocates physical storage in memory or in the paging file on disk for the specified region of pages.
	An attempt to commit an already committed page will not cause the function to fail. This means that a range of committed or decommitted pages can be committed without having to worry about a failure.
MEM_RESERVE	Reserves a range of the process's virtual address space without allocating any physical storage. The reserved range cannot be used by any other allocation operations (the malloc function, the LocalAlloc function, and so on) until it is released. Reserved pages can be committed in subsequent calls to the VirtualAlloc function.
MEM_TOP_DOWN	Allocates memory at the highest possible address.
fdwProtect

Specifies the type of access protection. If the pages are being committed, any one of the following flags can be specified, along with the PAGE_GUARD and PAGE_NOCACHE protection modifier flags, as desired:

Flag	Meaning
PAGE_READONLY	Enables read access to the committed region of pages. An attempt to write to the committed region results in an access violation. If the system differentiates between read-only access and execute access, an attempt to execute code in the committed region results in an access violation.
PAGE_READWRITE	Enables both read and write access to the committed region of pages.
PAGE_EXECUTE	Enables execute access to the committed region of pages. An attempt to read or write to the committed region results in an access violation.
PAGE_EXECUTE_READ	Enables execute and read access to the committed region of pages. An attempt to write to the committed region results in an access violation.
PAGE_EXECUTE_READWRITE	Enables execute, read, and write access to the committed region of pages.
PAGE_GUARD	Pages in the region become guard pages. Any attempt to read from or write to a guard page causes the operating system to raise a STATUS_GUARD_PAGE exception and turn off the guard page status. Guard pages thus act as a one-shot access alarm. The PAGE_GUARD flag is a page protection modifier. An application uses it with one of the other page protection flags, with one exception: It cannot be used with PAGE_NOACCESS. When an access attempt leads the operating system to turn off guard page status, the underlying page protection takes over. If a guard page exception occurs during a system service, the service typically returns a failure status indicator.
PAGE_NOACCESS	Disables all access to the committed region of pages. An attempt to read from, write to, or execute in the committed region results in an access violation exception, called a general protection (GP) fault.
PAGE_NOCACHE	Allows no caching of the committed regions of pages. The hardware attributes for the physical memory should be specified as "no cache." This is not recommended for general usage. It is useful for device drivers; for example, mapping a video frame buffer with no caching. This flag is a page protection modifier, only valid when used with one of the page protections other than PAGE_NOACCESS.
Return Value

If the function succeeds, the return value is the base address of the allocated region of pages.

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

Remarks

VirtualAlloc can perform the following operations:

•	Commit a region of pages reserved by a previous call to the VirtualAlloc function.

•	Reserve a region of free pages.

•	Reserve and commit a region of free pages.

You can use VirtualAlloc to reserve a block of pages and then make additional calls to VirtualAlloc to commit individual pages from the reserved block. This enables a process to reserve a range of its virtual address space without consuming physical storage until it is needed.

Each page in the process's virtual address space is in one of three states:

State	Meaning
Free	The page is not committed or reserved and is not accessible to the process. VirtualAlloc can reserve, or simultaneously reserve and commit, a free page.
Reserved	The range of addresses cannot be used by other allocation functions, but the page is not accessible and has no physical storage associated with it. VirtualAlloc can commit a reserved page, but it cannot reserve it a second time. The VirtualFree function can release a reserved page, making it a free page.
Committed	Physical storage is allocated for the page, and access is controlled by a protection code. The system initializes and loads each committed page into physical memory only at the first attempt to read or write to that page. When the process terminates, the system releases the storage for committed pages. VirtualAlloc can commit an already committed page. This means that you can commit a range of pages, regardless of whether they have already been committed, and the function will not fail. VirtualFree can decommit a committed page, releasing the page's storage, or it can simultaneously decommit and release a committed page.
If the lpvAddress parameter is not NULL, the function uses the lpvAddress and cbSize parameters to compute the region of pages to be allocated. The current state of the entire range of pages must be compatible with the type of allocation specified by the fdwAllocationType parameter. Otherwise, the function fails and none of the pages are allocated. This compatibility requirement does not preclude committing an already committed page; see the preceding list.

The PAGE_GUARD protection modifier flag establishes guard pages. Guard pages act as one-shot access alarms. See Guard Pages.

See Also

GlobalAlloc, HeapAlloc, VirtualFree, VirtualLock, VirtualProtect, VirtualQuery


VirtualFree
 VirtualFree  QuickInfo  Overview  Group

The VirtualFree function releases or decommits (or both) a region of pages within the virtual address space of the calling process.

BOOL VirtualFree(

LPVOID  lpvAddress,	// address of region of committed pages
DWORD  cbSize,	// size of region
DWORD  fdwFreeType	// type of free operation
);
Parameters

lpvAddress

Points to the base address of the region of pages to be freed. If the fdwFreeType parameter includes the MEM_RELEASE flag, this parameter must be the base address returned by the VirtualAlloc function when the region of pages was reserved.

cbSize

Specifies the size, in bytes, of the region to be freed. If the fdwFreeType parameter includes the MEM_RELEASE flag, this parameter must be zero. Otherwise, the region of affected pages includes all pages containing one or more bytes in the range from the lpvAddress parameter to (lpvAddress+cbSize). This means that a 2-byte range straddling a page boundary causes both pages to be freed.

fdwFreeType

Specifies the type of free operation. One, but not both, of the following flags can be specified:

Flag	Meaning
MEM_DECOMMIT	Decommits the specified region of committed pages.
	An attempt to decommit an uncommitted page will not cause the function to fail. This means that a range of committed or uncommitted pages can be decommitted without having to worry about a failure.
MEM_RELEASE	Releases the specified region of reserved pages. If this flag is specified, the cbSize parameter must be zero, or the function fails.
Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

VirtualFree can perform one of the following operations:

•	Decommit a region of committed or uncommitted pages.

•	Release a region of reserved pages.

•	Decommit and release a region of committed or uncommitted pages.

To release a region of pages, the entire range of pages must be in the same state (all reserved or all committed) and the entire region originally reserved by the VirtualAlloc function must be released at the same time. If only part of the pages in the original reserved region are committed, you must first call VirtualFree to decommit the committed pages and then call VirtualFree again to release the entire block.

Pages that have been released are free pages available for subsequent allocation operations. Attempting to read from or write to a free page results in an access violation exception.

VirtualFree can decommit an uncommitted page; this means that a range of committed or uncommitted pages can be decommitted without having to worry about a failure. Decommitting a page releases its physical storage, either in memory or in the paging file on disk. If a page is decommitted but not released, its state changes to reserved, and it can be committed again by a subsequent call to VirtualAlloc. Attempting to read from or write to a reserved page results in an access violation exception.

The current state of the entire range of pages must be compatible with the type of free operation specified by the fdwFreeType parameter. Otherwise, the function fails and no pages are released or decommitted.

See Also

GlobalAlloc, GlobalFree, VirtualAlloc


VirtualLock
 VirtualLock  QuickInfo  Overview  Group

The VirtualLock function locks the specified region of the process's virtual address space into memory, ensuring that subsequent access to the region will not incur a page fault.

BOOL VirtualLock(

LPVOID  lpvAddress,	// address of first byte of range to lock
DWORD  cbSize	// number of bytes in range to lock
);
Parameters

lpvAddress

Points to the base address of the region of pages to be locked.

cbSize

Specifies the size, in bytes, of the region to be locked. The region of affected pages includes all pages that contain one or more bytes in the range from the lpvAddress parameter to (lpvAddress+cbSize). This means that a 2-byte range straddling a page boundary causes both pages to be locked.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

All pages in the specified region must be committed. Memory protected with the PAGE_NOACCESS flag cannot be locked.

Locking pages into memory may degrade the performance of the system by reducing the available RAM and forcing the system to swap out other critical pages to the paging file. By default, a process can lock a maximum of 30 pages. The default limit is intentionally small to avoid severe performance degradation. Applications that need to lock larger numbers of pages must first call the SetProcessWorkingSetSize function to increase their minimum and maximum working set sizes. The maximum number of pages that a process can lock is equal to the number of pages in its minimum working set minus a small overhead.

Pages that a process has locked remain resident even when the process is idle for extended periods.

To unlock a region of locked pages, use the VirtualUnlock function. Locked pages are automatically unlocked when the process terminates.

This function is not like the GlobalLock or LocalLock function in that it does not increment a lock count and translate a handle into a pointer. There is no lock count for virtual pages, so multiple calls to the VirtualUnlock function are never required to unlock a region of pages.

Windows 95

On Windows 95, the VirtualLock function is implemented as a stub that has no effect and always returns TRUE.

See Also

GlobalLock, LocalLock, SetProcessWorkingSetSize, VirtualUnlock


VirtualProtect
 VirtualProtect  QuickInfo  Overview  Group

The VirtualProtect function changes the access protection on a region of committed pages in the virtual address space of the calling process. This function differs from VirtualProtectEx, which changes the access protection of any process.

BOOL VirtualProtect(

LPVOID  lpvAddress,	// address of region of committed pages
DWORD  cbSize,	// size of the region
DWORD  fdwNewProtect,	// desired access protection
PDWORD  pfdwOldProtect	// address of variable to get old protection
);
Parameters

lpvAddress

Points to the base address of the region of pages whose access protection attributes are to be changed.

cbSize

Specifies the size, in bytes, of the region whose access protection attributes are to be changed. The region of affected pages includes all pages containing one or more bytes in the range from the lpvAddress parameter to (lpvAddress+cbSize). This means that a 2-byte range straddling a page boundary causes the protection attributes of both pages to be changed.

fdwNewProtect

Specifies the new access protection. You can specify any one of the following flags, along with the PAGE_GUARD and PAGE_NOCACHE protection modifier flags, as necessary:

Value	Meaning
PAGE_READONLY	Enables read access to the committed region of pages. An attempt to write to the committed region results in an access violation. If the system differentiates between read-only access and execute access, an attempt to execute code in the committed region results in an access violation.
PAGE_READWRITE	Enables both read and write access to the committed region of pages.
PAGE_WRITECOPY	Gives copy-on-write access to the committed region of pages.
PAGE_EXECUTE	Enables execute access to the committed region of pages. An attempt to read or write to the committed region results in an access violation.
PAGE_EXECUTE_READ	Enables execute and read access to the committed region of pages. An attempt to write to the committed region results in an access violation.
PAGE_EXECUTE_READWRITE	Enables execute, read, and write access to the committed region of pages.
PAGE_EXECUTE_WRITECOPY	Enables execute, read, and write access to the committed region of pages. The pages are shared read-on-write and copy-on-write.
PAGE_GUARD	Pages in the region become guard pages. Any attempt to access a guard page causes the operating system to raise a STATUS_GUARD_PAGE exception and turn off the guard page status. Guard pages thus act as a one-shot access alarm. The PAGE_GUARD flag is a page protection modifier. An application uses it with one of the other page protection flags, with one exception: it cannot be used with PAGE_NOACCESS. When an access attempt leads the operating system to turn off guard page status, the underlying page protection takes over. If a guard page exception occurs during a system service, the service typically returns a failure status indicator.
PAGE_NOACCESS	Disables all access to the committed region of pages. An attempt to read from, write to, or execute in the committed region results in an access violation exception, called a general protection (GP) fault.
PAGE_NOCACHE	Allows no caching of the committed regions of pages. The hardware attributes for the physical memory should be specified as "no cache." This is not recommended for general usage. It is useful for device drivers; for example, mapping a video frame buffer with no caching. This flag is a page protection modifier, only valid when used with one of the page protections other than PAGE_NOACCESS.
pfdwOldProtect

Points to a variable that the function sets to the previous access protection value of the first page in the specified region of pages. If this parameter is NULL or does not point to a valid variable, the function fails.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

You can set the access protection value on committed pages only. If the state of any page in the specified region is not committed, the function fails and returns without modifying the access protection of any pages in the specified region.

The VirtualProtect function changes the access protection of memory in the calling process, and the VirtualProtectEx function changes the access protection of memory in a specified process.

The PAGE_GUARD protection modifier flag establishes guard pages. Guard pages act as one-shot access alarms. See Guard Pages for further discussion of guard pages.

See Also

VirtualAlloc, VirtualProtectEx


VirtualProtectEx
 VirtualProtectEx  QuickInfo  Overview  Group

The VirtualProtectEx function changes the access protection on a region of committed pages in the virtual address space of a specified process. Note that this function differs from VirtualProtect, which changes the access protection on the calling process only.

BOOL VirtualProtectEx(

HANDLE  hProcess,	// handle of process
LPVOID  lpvAddress,	// address of region of committed pages
DWORD  cbSize,	// size of region
DWORD  fdwNewProtect,	// desired access protection
PDWORD  pfdwOldProtect	// address of variable to get old protection
);
Parameters

hProcess

Identifies the process whose memory protection is to be changed. The handle must have PROCESS_VM_OPERATION access. For more information on PROCESS_VM_OPERATION, see OpenProcess.

lpvAddress

Points to the base address of the region of pages whose access protection attributes are to be changed.

cbSize

Specifies the size, in bytes, of the region whose access protection attributes are changed. The region of affected pages includes all pages containing one or more bytes in the range from the lpvAddress parameter to (lpvAddress+cbSize). This means that a 2-byte range straddling a page boundary causes the protection attributes of both pages to be changed.

fdwNewProtect

Specifies the new access protection. Any one of the following flags can be specified, along with the PAGE_GUARD and PAGE_NOCACHE protection modifier flags, as desired:

Value	Meaning
PAGE_READONLY	Enables read access to the committed region of pages. An attempt to write to the committed region results in an access violation. If the system differentiates between read-only access and execute access, an attempt to execute code in the committed region results in an access violation.
PAGE_READWRITE	Enables both read and write access to the committed region of pages.
PAGE_WRITECOPY	Gives copy-on-write access to the committed region of pages.
PAGE_EXECUTE	Enables execute access to the committed region of pages. An attempt to read or write to the committed region results in an access violation.
PAGE_EXECUTE_READ	Enables execute and read access to the committed region of pages. An attempt to write to the committed region results in an access violation.
PAGE_EXECUTE_READWRITE	Enables execute, read, and write access to the committed region of pages.
PAGE_EXECUTE_WRITECOPY	Enables execute, read, and write access to the committed region of pages. The pages are shared read-on-write and copy-on-write.
PAGE_GUARD	Pages in the region become guard pages. Any attempt to read from or write to a guard page causes the operating system to raise a STATUS_GUARD_PAGE exception, and turn off the guard page status. Guard pages thus act as a one-shot access alarm. The PAGE_GUARD flag is a page protection modifier. An application uses it with one of the other page protection flags, with one exception: it cannot be used with PAGE_NOACCESS. When an access attempt leads the operating system to turn off guard page status, the underlying page protection takes over. If a guard page exception occurs during a system service, the service typically returns a failure status indicator.
PAGE_NOACCESS	Disables all access to the committed region of pages. An attempt to read from, write to, or execute in the committed region results in an access violation exception, called a general protection (GP) fault.
PAGE_NOCACHE	Allows no caching of the committed regions of pages. The hardware attributes for the physical memory should be set to "no cache." This is not recommended for general usage. It is useful for device drivers; for example, mapping a video frame buffer with no caching. This flag is a page protection modifier, only valid when used with one of the page protections other than PAGE_NOACCESS.
pfdwOldProtect

Points to a variable that receives the previous access protection of the first page in the specified region of pages. If this parameter is NULL or does not point to a valid variable, the function fails.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The access protection value can be set only on committed pages. If the state of any page in the specified region is not committed, the function fails and returns without modifying the access protection of any pages in the specified region.

VirtualProtectEx is identical to the VirtualProtect function except that it changes the access protection of memory in a specified process.

The PAGE_GUARD protection modifier flag establishes guard pages. Guard pages act as one-shot access alarms. See Guard Pages. for further discussion of guard pages.

See Also

VirtualAlloc, VirtualProtect, VirtualQueryEx


VirtualQuery
 VirtualQuery  QuickInfo  Overview  Group

The VirtualQuery function provides information about a range of pages in the virtual address space of the calling process.

DWORD VirtualQuery(

LPCVOID  lpvAddress,	// address of region
PMEMORY_BASIC_INFORMATION  pmbiBuffer,	// address of information buffer
DWORD  cbLength	// size of buffer
);
Parameters

lpvAddress

Points to the base address of the region of pages to be queried. This value is rounded down to the next page boundary. To determine the size of a page on the host computer, use the GetSystemInfo function.

pmbiBuffer

Points to a MEMORY_BASIC_INFORMATION structure in which information about the specified page range is returned.

cbLength

Specifies the size, in bytes, of the buffer pointed to by the pmbiBuffer parameter.

Return Value

The return value is the actual number of bytes returned in the information buffer.

Remarks

VirtualQuery provides information about a region of consecutive pages beginning at a specified address that share the following attributes:

•	The state of all pages is the same with the MEM_COMMIT, MEM_RESERVE, MEM_FREE, MEM_PRIVATE, MEM_MAPPED, or MEM_IMAGE flag.

•	If the initial page is not free, all pages in the region are part of the same initial allocation of pages reserved by a call to the VirtualAlloc function.

•	The access of all pages is the same with the PAGE_READONLY, PAGE_READWRITE, PAGE_NOACCESS, PAGE_WRITECOPY, PAGE_EXECUTE, PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE, PAGE_EXECUTE_WRITECOPY, PAGE_GUARD, or PAGE_NOCACHE flag.

The function determines the attributes of the first page in the region and then scans subsequent pages until it scans the entire range of pages or until it encounters a page with a nonmatching set of attributes. The function returns the attributes and the size, in bytes, of the region of pages with matching attributes. For example, if there is a 40 megabyte (MB) region of free memory, and VirtualQuery is called on a page that is 10 MB into the region, the function will obtain a state of MEM_FREE and a size of 30 MB.

This function reports on a region of pages in the memory of the calling process, and the VirtualQueryEx function reports on a region of pages in the memory of a specified process.

See Also

GetSystemInfo, MEMORY_BASIC_INFORMATION, VirtualQueryEx


VirtualQueryEx
 VirtualQueryEx  QuickInfo  Overview  Group

The VirtualQueryEx function provides information about a range of pages within the virtual address space of a specified process.

DWORD VirtualQueryEx(

HANDLE  hProcess,	// handle of process
LPCVOID  lpvAddress,	// address of region
PMEMORY_BASIC_INFORMATION  pmbiBuffer,	// address of information buffer
DWORD  cbLength	// size of buffer
);
Parameters

hProcess

Identifies the process whose memory information is queried. The handle must have PROCESS_QUERY_INFORMATION access.

lpvAddress

Points to the base address of the region of pages to be queried. This value is rounded down to the next page boundary. To determine the size of a page on the host computer, use the GetSystemInfo function.

pmbiBuffer

Points to a MEMORY_BASIC_INFORMATION structure in which information about the specified page range is returned.

cbLength

Specifies the size, in bytes, of the buffer pointed to by the pmbiBuffer parameter.

Return Value

The return value is the actual number of bytes returned in the information buffer.

Remarks

VirtualQueryEx provides information about a region of consecutive pages beginning at a specified address that share the following attributes:

•	The state of all pages is the same with the MEM_COMMIT, MEM_RESERVE, MEM_FREE, MEM_PRIVATE, MEM_MAPPED, or MEM_IMAGE flag.

•	If the initial page is not free, all pages in the region are part of the same initial allocation of pages reserved by a call to the VirtualAlloc function.

•	The access of all pages is the same with the PAGE_READONLY, PAGE_READWRITE, PAGE_NOACCESS, PAGE_WRITECOPY, PAGE_EXECUTE, PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE, PAGE_EXECUTE_WRITECOPY, PAGE_GUARD, or PAGE_NOCACHE flag.

The VirtualQueryEx function determines the attributes of the first page in the region and then scans subsequent pages until it scans the entire range of pages, or until it encounters a page with a nonmatching set of attributes. The function returns the attributes and the size, in bytes, of the region of pages with matching attributes. For example, if there is a 40 megabyte (MB) region of free memory, and VirtualQueryEx is called on a page that is 10 MB into the region, the function will obtain a state of MEM_FREE and a size of 30 MB.

This function is identical to the VirtualQuery function, except that it enables access to information about memory in a specified process.

See Also

GetSystemInfo, MEMORY_BASIC_INFORMATION, VirtualAlloc, VirtualProtectEx, VirtualQuery


VirtualUnlock
 VirtualUnlock  QuickInfo  Overview  Group

The VirtualUnlock function unlocks a specified range of pages in the virtual address space of a process, enabling the system to swap the pages out to the paging file if necessary.

BOOL VirtualUnlock(

LPVOID  lpvAddress,	// address of first byte of range
DWORD  cbSize	// number of bytes in range
);
Parameters

lpvAddress

Points to the base address of the region of pages to be unlocked.

cbSize

Specifies the size, in bytes, of the region being unlocked. The region of affected pages includes all pages containing one or more bytes in the range from the lpvAddress parameter to (lpvAddress+cbSize). This means that a 2-byte range straddling a page boundary causes both pages to be unlocked.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

For the function to succeed, the range specified need not match a range passed to a previous call to the VirtualLock function, but all pages in the range must be locked.

See Also

VirtualLock


VkKeyScan
 VkKeyScan  QuickInfo  Overview  Group

The VkKeyScan function translates a character to the corresponding virtual-key code and shift state for the current keyboard.

SHORT VkKeyScan(

TCHAR  ch	// character to translate
);
Parameters

ch

Specifies the character to be translated into a virtual-key code.

Return Value

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

See Also

GetAsyncKeyState, GetKeyboardState, GetKeyNameText, GetKeyState, SetKeyboardState, WM_KEYDOWN, WM_KEYUP


VkKeyScanEx [New - Windows 95]
 VkKeyScanEx  QuickInfo

[New - Windows 95]

The VkKeyScanEx function translates a character to the corresponding virtual-key code and shift state. The function translates the character using the input language and physical keyboard layout identified by the given keyboard layout handle.

SHORT VkKeyScanEx(

UINT  uChar,	// character to translate
HKL  hkl	// keyboard layout handle
);
Parameters

uChar

Specifies the character to be translated into a virtual-key code.

hkl

Identifies the keyboard layout to use to translate the character. This parameter can be any keyboard layout handle previously returned by the LoadKeyboardLayout function.

Return Value

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.
If the function finds no key that translates to the passed character code, both the low-order and high-order bytes contain −1.

Remarks

For keyboard layouts that use the right-hand ALT key as a shift key (for example, the French keyboard layout), the shift state is represented by the value 6, because the right-hand ALT key is converted internally into CTRL+ALT.

Translations for the numeric keypad (VK_NUMPAD0 through VK_DIVIDE) are ignored. This function is intended to translate characters into keystrokes from the main keyboard section only. For example, the character "7" is translated into VK_7, not VK_NUMPAD7.

VkKeyScanEx is used by applications that send characters by using the WM_KEYUP and WM_KEYDOWN messages.

See Also

GetAsyncKeyState, GetKeyboardState, GetKeyNameText, GetKeyState, LoadKeyboardLayout, SetKeyboardState, ToAsciiEx, VkKeyScan


WaitCommEvent
 WaitCommEvent  QuickInfo  Overview  Group

The WaitCommEvent function waits for an event to occur for a specified communications device. The set of events that are monitored by this function is contained in the event mask associated with the device handle.

BOOL WaitCommEvent(

HANDLE  hCommDev,	// handle of communications device
LPDWORD  lpfdwEvtMask,	// address of variable for event that occurred
LPOVERLAPPED  lpo,	// address of overlapped structure
);
Parameters

hCommDev

Identifies the communications device. The CreateFile function returns this handle.

lpfdwEvtMask

Points to a 32-bit variable that receives a mask indicating the type of event that occurred. If an error occurs, the value is zero; otherwise, it is one of the following values:

Value	Meaning
EV_BREAK	A break was detected on input.
EV_CTS	The CTS (clear-to-send) signal changed state.
EV_DSR	The DSR (data-set-ready) signal changed state.
EV_ERR	A line-status error occurred. Line-status errors are CE_FRAME, CE_OVERRUN, and CE_RXPARITY.
EV_RING	A ring indicator was detected.
EV_RLSD	The RLSD (receive-line-signal-detect) signal changed state.
EV_RXCHAR	A character was received and placed in the input buffer.
EV_RXFLAG	The event character was received and placed in the input buffer. The event character is specified in the device's DCB structure, which is applied to a serial port by using the SetCommState function.
EV_TXEMPTY	The last character in the output buffer was sent.
lpo

Points to an OVERLAPPED structure. This parameter is ignored if the hCommDev handle was opened without specifying the FILE_FLAG_OVERLAPPED flag. If an overlapped operation is not desired, this parameter can be NULL.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The WaitCommEvent function monitors a set of events for a specified communications resource. To set and query the current event mask of a communications resource, use the SetCommMask and GetCommMask functions.

If the lpo parameter is NULL or the hCommDev handle was opened without specifying the FILE_FLAG_OVERLAPPED flag, WaitCommEvent does not return until one of the specified events or an error occurs.

If lpo points to an OVERLAPPED structure and FILE_FLAG_OVERLAPPED was specified when the hCommDev handle was opened, WaitCommEvent is performed as an overlapped operation. In this case, the OVERLAPPED structure must contain a handle to a manual-reset event object (created by using the CreateEvent function).

If the overlapped operation cannot be completed immediately, the function returns FALSE and the GetLastError function returns ERROR_IO_PENDING, indicating that the operation is executing in the background. When this happens, the system sets the hEvent member of the OVERLAPPED structure to the not-signaled state before WaitCommEvent returns, and then it sets it to the signaled state when one of the specified events or an error occurs. The calling process can use a wait function to determine the event object's state and then use the GetOverlappedResult function to determine the results of the WaitCommEvent operation. GetOverlappedResult reports the success or failure of the operation, and the variable pointed to by the lpfdwEvtMask parameter is set to indicate the event that occurred.

If a process attempts to change the device handle's event mask by using the SetCommMask function while an overlapped WaitCommEvent operation is in progress, WaitCommEvent returns immediately. The variable pointed to by the lpfdwEvtMask parameter is set to zero.

See Also

CreateFile, DCB, GetCommMask, GetOverlappedResult, OVERLAPPED, SetCommMask, SetCommState


WaitForDebugEvent
 WaitForDebugEvent  QuickInfo  Overview  Group

The WaitForDebugEvent function waits for a debugging event to occur in a process being debugged.

BOOL WaitForDebugEvent(

LPDEBUG_EVENT  lpde,	// address of structure for event information
DWORD  dwTimeout	// number of milliseconds to wait for event
);
Parameters

lpde

Points to a DEBUG_EVENT structure that is filled with information about the debugging event.

dwTimeout

Specifies the number of milliseconds to wait for a debugging event. If this parameter is zero, the function tests for a debugging event and returns immediately. If the parameter is INFINITE, the function does not return until a debugging event has occurred.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

Only the thread that created the process being debugged can call WaitForDebugEvent.

See Also

ContinueDebugEvent, CreateProcess, DebugActiveProcess, DebugBreak, DEBUG_EVENT, OutputDebugString


WaitForInputIdle
 WaitForInputIdle  QuickInfo  Overview  Group

The WaitForInputIdle function waits until the given process is waiting for user input with no input pending, or until the time-out interval has elapsed.

The WaitForInputIdle function only works with GUI applications. If a console application calls the function, it returns immediately, with no wait.

DWORD WaitForInputIdle(

HANDLE  hProcess,	// handle to process
DWORD  dwTimeout	// time-out interval in milliseconds
);
Parameters

hProcess

Identifies the process.

dwTimeout

Specifies the time-out interval, in milliseconds. If dwTimeout is INFINITE, the function does not return until the process is idle.

Return Value

The following table shows the possible return values:

Value	Meaning
0	The wait was satisfied successfully.
WAIT_TIMEOUT	The wait was terminated because the time-out interval elapsed.
0xFFFFFFFF	An error occurred. To get extended error information, use the GetLastError function.
Remarks

The WaitForInputIdle function enables a thread to suspend its execution until a specified process has finished its initialization and is waiting for user input with no input pending. This can be useful for synchronizing a parent process and a newly created child process. When a parent process creates a child process, the CreateProcess function returns without waiting for the child process to finish its initialization. Before trying to communicate with the child process, the parent process can use WaitForInputIdle to determine when the child's initialization has been completed. For example, the parent process should use WaitForInputIdle before trying to find a window associated with the child process.

The WaitForInputIdle function can be used at any time, not just during application startup.

See Also

CreateProcess


WaitForMultipleObjects
 WaitForMultipleObjects  QuickInfo  Overview  Group

The WaitForMultipleObjects function returns either when any one or when all of the specified objects are in the signaled state, or when the time-out interval elapses.

DWORD WaitForMultipleObjects(

DWORD  cObjects,	// number of handles in handle array
CONST HANDLE *  lphObjects,	// address of object-handle array
BOOL  fWaitAll,	// wait flag
DWORD  dwTimeout	// time-out interval in milliseconds
);
Parameters

cObjects

Specifies the number of object handles in the array pointed to by lphObjects. The maximum number of object handles is MAXIMUM_WAIT_OBJECTS.

lphObjects

Points to an array of object handles. For a list of the object types whose handles can be specified, see the following Remarks section. The array can contain handles of objects of different types.

Windows NT: The handles must have SYNCHRONIZE access.

fWaitAll

Specifies the wait type. If TRUE, the function returns when all objects in the lphObjects array are signaled at the same time. If FALSE, the function returns when any one of the objects is signaled. In the latter case, the return value indicates the object whose state caused the function to return.

dwTimeout

Specifies the time-out interval, in milliseconds. The function returns if the interval elapses, even if the conditions specified by the fWaitAll parameter are not satisfied. If dwTimeout is zero, the function tests the states of the specified objects and returns immediately. If dwTimeout is INFINITE, the function's time-out interval never elapses.

Return Value

If the function succeeds, the return value indicates the event that caused the function to return.

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

The return value upon success is one of the following values:

Value	Meaning
WAIT_OBJECT_0 to (WAIT_OBJECT_0 + cObjects − 1)	If fWaitAll is TRUE, the return value indicates that the state of all specified objects is signaled.  If fWaitAll is FALSE, the return value minus WAIT_OBJECT_0 indicates the lphObjects array index of the object that satisfied the wait. If more than one object became signalled during the call, this is the array index of the signalled object with the smallest index value of all the signalled objects.
WAIT_ABANDONED_0 to (WAIT_ABANDONED_0 + cObjects − 1)	If fWaitAll is TRUE, the return value indicates that the state of all specified objects is signaled and at least one of the objects is an abandoned mutex object.  If fWaitAll is FALSE, the return value minus WAIT_ABANDONED_0 indicates the lphObjects array index of an abandoned mutex object that satisfied the wait.
WAIT_TIMEOUT	The time-out interval elapsed and the conditions specified by the fWaitAll parameter are not satisfied.
Remarks

The WaitForMultipleObjects function determines whether the conditions exist that satisfy the wait. If the wait is not satisfied, the calling thread enters an efficient wait state, consuming very little processor time while waiting for one of the conditions of the wait to be satisfied.

When fWaitAll is TRUE, the function's wait condition is satisfied only when the state of all objects is signaled at the same time. The function does not modify the state of the specified objects until all objects are simultaneously signaled. For example, a mutex can be signaled, but the thread does not get ownership until the other objects are also signaled. In the meantime, some other thread may get ownership of the mutex, thereby delaying satisfaction of the wait condition.

The system adjusts the state of some types of objects after the object's signaled state satisfies a wait condition. For example, the count of a semaphore object is decreased by one.

The WaitForMultipleObjects function can specify handles of any of the following object types in the lphObjects array:

Object	Description
Change notification	The handle is returned by the FindFirstChangeNotification function. A change notification object's state is signaled when a specified type of change occurs within a specified directory or directory tree.
Console input	The handle is returned by the CreateFile function when CONIN$ is specified, or by the GetStdHandle function. The object's state is signaled when there is unread input in the console's input buffer, and it is nonsignaled when the input buffer is empty.
Event	The handle is returned by the CreateEvent or OpenEvent function. An event object's state is set explicitly to signaled by the SetEvent or PulseEvent function. A manual-reset event object's state must be reset explicitly to nonsignaled by the ResetEvent function. For an auto-reset event object, the wait function resets the object's state to nonsignaled before returning. Event objects are also used in overlapped operations, in which the state is set by the system.
Mutex	The handle is returned by the CreateMutex or OpenMutex function. A mutex object's state is signaled when it is not owned by any thread. The wait function requests ownership of the mutex for the calling thread, changing the mutex's state to nonsignaled when ownership is granted.
Process	The handle is returned by the CreateProcess or OpenProcess function. A process object's state is signaled when the process terminates.
Thread	The handle is returned by the CreateProcess, CreateThread, or CreateRemoteThread function. A thread object's state is signaled when the thread terminates.
Semaphore	The handle is returned by the CreateSemaphore or OpenSemaphore function. A semaphore object maintains a count between zero and some maximum value. Its state is signaled when its count is greater than zero and nonsignaled when its count is zero. If the current state is signaled, the wait function decreases the count by one.
An abandoned mutex object is not released by the thread that owned the mutex object before the owning thread terminated. Ownership of the mutex object is granted to the calling thread, and the mutex is set to nonsignaled.

In some circumstances, a wait function can specify a handle of a file, named pipe, or communications device as an object to wait for. However, their use for this purpose is discouraged.

See Also

CreateEvent, CreateFile, CreateMutex, CreateProcess, CreateRemoteThread, CreateSemaphore, CreateThread, FindFirstChangeNotification, GetStdHandle, MsgWaitForMultipleObjects, OpenEvent, OpenMutex, OpenProcess, OpenSemaphore, PulseEvent, ResetEvent, SetEvent, Sleep, WaitForMultipleObjectsEx, WaitForSingleObject


WaitForMultipleObjectsEx
 WaitForMultipleObjectsEx  QuickInfo  Overview  Group

The WaitForMultipleObjectsEx function is an extended wait function that can be used to perform an alertable wait. This enables the function to return when the system queues an I/O completion routine to be executed by the calling thread. The function also returns either when any one or when all of the specified objects are in the signaled state, or when the time-out interval elapses.

DWORD WaitForMultipleObjectsEx(

DWORD  cObjects,	// number of handles in handle array
CONST HANDLE *  lphObjects,	// address of object-handle array
BOOL  fWaitAll,	// wait flag
DWORD  dwTimeout,	// time-out interval in milliseconds
BOOL  fAlertable	// alertable wait flag
);
Parameters

cObjects

Specifies the number of object handles to wait for in the array pointed to by lphObjects. The maximum number of object handles is MAXIMUM_WAIT_OBJECTS.

lphObjects

Points to an array of object handles. For a list of the object types whose handles can be specified, see the following Remarks section. The array can contain handles of objects of different types.

Windows NT: The handles must have SYNCHRONIZE access.

fWaitAll

Specifies the wait type. If TRUE, the function returns when all objects in the lphObjects array are signaled at the same time. If FALSE, the function returns when any one of the objects is signaled. In the latter case, the return value indicates the object whose state caused the function to return.

dwTimeout

Specifies the time-out interval, in milliseconds. The function returns if the interval elapses, even if the conditions specified by the fWaitAll parameter are not satisfied and no completion routines are queued. If dwTimeout is zero, the function tests the states of the specified objects and checks for queued completion routines and then returns immediately. If dwTimeout is INFINITE, the function's time-out interval never elapses.

fAlertable

Specifies whether the function returns when the system queues an I/O completion routine for execution by the calling thread. If TRUE, the function returns and the completion routine is executed. If FALSE, the function does not return and the completion routine is not executed.

A completion routine is queued for execution when the ReadFileEx or WriteFileEx function in which it was specified has been completed. The wait function returns and the completion routine is executed only if fAlertable is TRUE and the calling thread is the thread that initiated the read or write operation.

Return Value

If the function succeeds, the return value indicates the event that caused the function to return.

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

The return value on success is one of the following values:

Value	Meaning
WAIT_OBJECT_0 to (WAIT_OBJECT_0 + cObjects − 1)	If fWaitAll is TRUE, the return value indicates that the state of all specified objects is signaled.  If fWaitAll is FALSE, the return value minus WAIT_OBJECT_0 indicates the lphObjects array index of the object that satisfied the wait. If more than one object became signalled during the call, this is the array index of the signalled object with the smallest index value of all the signalled objects.
WAIT_ABANDONED_0 to (WAIT_ABANDONED_0 + cObjects − 1)	If fWaitAll is TRUE, the return value indicates that the state of all specified objects is signaled, and at least one of the objects is an abandoned mutex object.  If fWaitAll is FALSE, the return value minus WAIT_ABANDONED_0 indicates the lphObjects array index of an abandoned mutex object that satisfied the wait.
WAIT_IO_COMPLETION	One or more I/O completion routines are queued for execution.
WAIT_TIMEOUT	The time-out interval elapsed, the conditions specified by the fWaitAll parameter were not satisfied, and no completion routines are queued.
Remarks

The WaitForMultipleObjectsEx function determines whether the conditions exist that satisfy the wait. If the wait is not satisfied, the calling thread enters an efficient wait state, using very little processor time while waiting for one of the conditions of the wait to be satisfied.

When fWaitAll is TRUE, the function's wait condition is satisfied only when the state of all objects is signaled at the same time. The function does not modify the state of the specified objects until all objects are simultaneously signaled. For example, a mutex can be signaled, but the thread does not get ownership until the other objects are also signaled. In the meantime, some other thread may get ownership of the mutex, thereby delaying satisfaction of the wait condition.

The system adjusts the state of some types of objects after the object's signaled state satisfies a wait condition. For example, the count of a semaphore object is decreased by one.

The WaitForMultipleObjectsEx function can specify handles of any of the following object types in the lphObjects array:

Object	Description
Change notification	The handle is returned by the FindFirstChangeNotification function. A change notification object's state is signaled when a specified type of change occurs within a specified directory or directory tree.
Console input	The handle is returned by the CreateFile function when CONIN$ is specified, or by the GetStdHandle function. The object's state is signaled when there is unread input in the console's input buffer, and it is nonsignaled when the input buffer is empty.
Event	The handle is returned by the CreateEvent or OpenEvent function. An event object's state is set explicitly to signaled by the SetEvent or PulseEvent function. A manual-reset event object's state must be reset explicitly to nonsignaled by the ResetEvent function. For an auto-reset event object, the wait function resets the object's state to nonsignaled before returning. Event objects are also used in overlapped operations, in which the state is set by the system.
Mutex	The handle is returned by the CreateMutex or OpenMutex function. A mutex object's state is signaled when it is not owned by any thread. The wait function requests ownership of the mutex for the calling thread, changing the mutex's state to nonsignaled when ownership is granted.
Process	The handle is returned by the CreateProcess or OpenProcess function. A process object's state is signaled when the process terminates.
Thread	The handle is returned by the CreateProcess, CreateThread, or CreateRemoteThread function. A thread object's state is signaled when the thread terminates.
Semaphore	The handle is returned by the CreateSemaphore or OpenSemaphore function. A semaphore object maintains a count between zero and some maximum value. Its state is signaled when its count is greater than zero and nonsignaled when its count is zero. If the current state is signaled, the wait function decreases the count by one.
An abandoned mutex object is not released by the thread that owned the mutex object before the owning thread terminated. Ownership of the mutex object is granted to the calling thread, and the mutex is set to nonsignaled.

In some circumstances, a wait function can specify a handle of a file, named pipe, or communications device as an object to wait for. However, their use for this purpose is discouraged.

See Also

CreateEvent, CreateFile, CreateMutex, CreateProcess, CreateRemoteThread, CreateSemaphore, CreateThread, FindFirstChangeNotification, GetStdHandle, OpenEvent, OpenMutex, OpenProcess, OpenSemaphore, MsgWaitForMultipleObjects, PulseEvent, ReadFileEx, ResetEvent, SetEvent, SleepEx, WaitForMultipleObjects, WaitForSingleObjectEx, WriteFileEx


WaitForPrinterChange
 WaitForPrinterChange  QuickInfo  Overview  Group

The WaitForPrinterChange function is obsolete. Applications should use the FindFirstPrinterChangeNotification, FindNextPrinterChangeNotification, and FindClosePrinterChangeNotification functions to monitor the occurrence of requested changes on a printer or print server.when one or more requested changes occur on a printer or print server.


WaitForSingleObject
 WaitForSingleObject  QuickInfo  Overview  Group

The WaitForSingleObject function returns when the specified object is in the signaled state or when the time-out interval elapses.

DWORD WaitForSingleObject(

HANDLE  hObject,	// handle of object to wait for
DWORD  dwTimeout	// time-out interval in milliseconds
);
Parameters

hObject

Identifies the object. For a list of the object types whose handles can be specified, see the following Remarks section.

Windows NT: The handle must have SYNCHRONIZE access.

dwTimeout

Specifies the time-out interval, in milliseconds. The function returns if the interval elapses, even if the object's state is nonsignaled. If dwTimeout is zero, the function tests the object's state and returns immediately. If dwTimeout is INFINITE, the function's time-out interval never elapses.

Return Value

If the function succeeds, the return value indicates the event that caused the function to return.

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

The return value on success is one of the following values:

Value	Meaning
WAIT_ABANDONED	The specified object is a mutex object that was not released by the thread that owned the mutex object before the owning thread terminated. Ownership of the mutex object is granted to the calling thread, and the mutex is set to nonsignaled.
WAIT_OBJECT_0	The state of the specified object is signaled.
WAIT_TIMEOUT	The time-out interval elapsed, and the object's state is nonsignaled.
Remarks

The WaitForSingleObject function checks the current state of the specified object. If the object's state is nonsignaled, the calling thread enters an efficient wait state. The thread consumes very little processor time while waiting for one of the conditions of the wait to be satisfied.

The system adjusts the state of some types of objects after the object's signaled state satisfies a wait condition. For example, the count of a semaphore object is decreased by one.

The WaitForSingleObject function can wait for the following objects:

Object	Description
Change notification	The handle is returned by the FindFirstChangeNotification function. A change notification object's state is signaled when a specified type of change occurs within a specified directory or directory tree.
Console input	The handle is returned by the CreateFile function when CONIN$ is specified, or by the GetStdHandle function. The object's state is signaled when there is unread input in the console's input buffer, and it is nonsignaled when the input buffer is empty.
Event	The handle is returned by the CreateEvent or OpenEvent function. An event object's state is set explicitly to signaled by the SetEvent or PulseEvent function. A manual-reset event object's state must be reset explicitly to nonsignaled by the ResetEvent function. For an auto-reset event object, the wait function resets the object's state to nonsignaled before returning. Event objects are also used in overlapped operations, in which the state is set by the system.
Mutex	The handle is returned by the CreateMutex or OpenMutex function. A mutex object's state is signaled when it is not owned by any thread. The wait function requests ownership of the mutex for the calling thread, changing the mutex's state to nonsignaled when ownership is granted.
Process	The handle is returned by the CreateProcess or OpenProcess function. A process object's state is signaled when the process terminates.
Thread	The handle is returned by the CreateProcess, CreateThread, or CreateRemoteThread function. A thread object's state is signaled when the thread terminates.
Semaphore	The handle is returned by the CreateSemaphore or OpenSemaphore function. A semaphore object maintains a count between zero and some maximum value. Its state is signaled when its count is greater than zero and nonsignaled when its count is zero. If the current state is signaled, the wait function decreases the count by one.
In some circumstances, a wait function can specify a handle of a file, named pipe, or communications device as an object to wait for. However, their use for this purpose is discouraged.

See Also

CreateEvent, CreateFile, CreateMutex, CreateProcess, CreateRemoteThread, CreateSemaphore, CreateThread, FindFirstChangeNotification, GetStdHandle, OpenEvent, OpenMutex, OpenProcess, OpenSemaphore, PulseEvent, ResetEvent, SetEvent, Sleep, WaitForMultipleObjects, WaitForSingleObjectEx


WaitForSingleObjectEx
 WaitForSingleObjectEx  QuickInfo  Overview  Group

The WaitForSingleObjectEx function is an extended wait function that can be used to perform an alertable wait. This enables the function to return when the system queues an I/O completion routine to be executed by the calling thread. The function also returns when the specified object is in the signaled state or when the time-out interval elapses.

DWORD WaitForSingleObjectEx(

HANDLE  hObject,	// handle of object to wait for
DWORD  dwTimeout,	// time-out interval in milliseconds
BOOL  fAlertable	// return to execute I/O completion routine if TRUE
);
Parameters

hObject

Identifies the object. For a list of the object types whose handles can be specified, see the following Remarks section.

Windows NT: The handle must have SYNCHRONIZE access.

dwTimeout

Specifies the time-out interval, in milliseconds. The function returns if the interval elapses, even if the object's state is nonsignaled and no completion routines are queued. If dwTimeout is zero, the function tests the object's state and checks for queued completion routines and then returns immediately. If dwTimeout is INFINITE, the function's time-out interval never elapses.

fAlertable

Specifies whether the function returns when the system queues an I/O completion routine for execution by the calling thread. If TRUE, the function returns and the completion routine is executed. If FALSE, the function does not return, and the completion routine is not executed.

A completion routine is queued for execution when the ReadFileEx or WriteFileEx function in which it was specified has been completed. The wait function returns and the completion routine is executed only if fAlertable is TRUE, and the calling thread is the thread that initiated the read or write operation.

Return Value

If the function succeeds, the return value indicates the event that caused the function to return.

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

The successful return value is one of the following:

Value	Meaning
WAIT_OBJECT_0	The state of the specified object is signaled.
WAIT_ABANDONED	The specified object is a mutex object that was not released by the thread that owned the mutex object before the owning thread terminated. Ownership of the mutex object is granted to the calling thread, and the mutex is set to nonsignaled.
WAIT_IO_COMPLETION	One or more I/O completion routines are queued for execution.
WAIT_TIMEOUT	The time-out interval elapsed, and the object's state is nonsignaled.
Remarks

The WaitForSingleObjectEx function determines whether the conditions exist that satisfy the wait. If the wait is not satisfied, the calling thread enters an efficient wait state, consuming very little processor time while waiting for one of the conditions of the wait to be satisfied.

The system adjusts the state of some types of objects after the object's signaled state satisfies a wait condition. For example, the count of a semaphore object is decreased by one.

The WaitForSingleObjectEx function can wait for the following objects:

Object	Description
Change notification	The handle is returned by the FindFirstChangeNotification function. A change notification object's state is signaled when a specified type of change occurs within a specified directory or directory tree.
Console input	The handle is returned by the CreateFile function when CONIN$ is specified, or by the GetStdHandle function. The object's state is signaled when there is unread input in the console's input buffer, and it is nonsignaled when the input buffer is empty.
Event	The handle is returned by the CreateEvent or OpenEvent function. An event object's state is set explicitly to signaled by the SetEvent or PulseEvent function. A manual-reset event object's state must be reset explicitly to nonsignaled by the ResetEvent function. For an auto-reset event object, the wait function resets the object's state to nonsignaled before returning. Event objects are also used in overlapped operations, in which the state is set by the system.
Mutex	The handle is returned by the CreateMutex or OpenMutex function. A mutex object's state is signaled when it is not owned by any thread. The wait function requests ownership of the mutex for the calling thread, changing the mutex's state to nonsignaled when ownership is granted.
Process	The handle is returned by the CreateProcess or OpenProcess function. A process object's state is signaled when the process terminates.
Thread	The handle is returned by the CreateProcess, CreateThread, or CreateRemoteThread function. A thread object's state is signaled when the thread terminates.
Semaphore	The handle is returned by the CreateSemaphore or OpenSemaphore function. A semaphore object maintains a count between zero and some maximum value. Its state is signaled when its count is greater than zero and nonsignaled when its count is zero. If the current state is signaled, the wait function decreases the count by one.
In some circumstances, a wait function can specify a handle of a file, named pipe, or communications device as an object to wait for. However, their use for this purpose is discouraged.

See Also

CreateEvent, CreateFile, CreateMutex, CreateProcess, CreateRemoteThread, CreateSemaphore, CreateThread, FindFirstChangeNotification, GetStdHandle, OpenEvent, OpenMutex, OpenProcess, OpenSemaphore, PulseEvent, ReadFileEx, ResetEvent, SetEvent, SleepEx, WaitForMultipleObjectsEx, WaitForSingleObject, WriteFileEx


WaitMessage
 WaitMessage  QuickInfo  Overview  Group

BOOL WaitMessage(VOID)

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.

Parameters

This function has no parameters.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

GetMessage, PeekMessage


WaitNamedPipe
 WaitNamedPipe  QuickInfo  Overview  Group

The WaitNamedPipe function waits until either a time-out interval elapses or an instance of the specified named pipe is available to be connected to (that is, the pipe's server process has a pending ConnectNamedPipe operation on the pipe).

BOOL WaitNamedPipe(

LPCTSTR  lpszPipeName,	// address of name of pipe to wait for
DWORD  dwTimeout	// time-out interval, in milliseconds
);
Parameters

lpszPipeName

Points to a null-terminated string that specifies the name of the named pipe. The string must include the name of the computer on which the server process is executing. A period may be used for the servername if the pipe is local. The following pipe name format is used:

\\servername\pipe\pipename

dwTimeout

Specifies the number of milliseconds that the function will wait for an instance of the named pipe to be available. One of the following values can be used instead of specifying a number of milliseconds:

Value	Meaning
NMPWAIT_USE_DEFAULT_WAIT	The time-out interval is the default value specified by the server process in the CreateNamedPipe function.
NMPWAIT_WAIT_FOREVER	The function does not return until an instance of the named pipe is available.
Return Value

If an instance of the pipe is available before the time-out interval elapses, the return value is TRUE. Otherwise, it is FALSE. To get extended error information, call GetLastError.

Remarks

If no instances of the specified named pipe exist, the WaitNamedPipe function returns immediately, regardless of the time-out value.

If the function succeeds, the process should use the CreateFile function to open a handle to the named pipe. A return value of TRUE indicates that there is at least one instance of the pipe available. A subsequent CreateFile call to the pipe can fail, because the instance was closed by the server or opened by another client.

See Also

CallNamedPipe, ConnectNamedPipe, CreateFile, CreateNamedPipe


 WaitSoundState

The WaitSoundState function has been deleted.

See Also

Beep, MessageBeep


WaveProc
 WaveProc  QuickInfo  Overview  Group

The WaveProc function is an application-defined callback function that processes messages sent to a waveform device. The address of the WaveProc function can be specified as the callback-address parameter for the waveInOpen or waveOutOpen function.

void CALLBACK WaveProc(

HWAVE  hWave,	// handle of waveform device
UINT  uMsg,	// sent message
DWORD  dwInstance,	// instance data
DWORD  dwParam1,	// application-defined parameter
DWORD  dwParam2	// application-defined parameter
);
Parameters

hWave

Identifies the waveform device associated with the callback.

uMsg

Specifies the message.

dwInstance

Specifies the user instance data specified with waveInOpen or waveOutOpen.

dwParam1

Specifies an application-defined parameter for the message.

dwParam2

Specifies an application-defined parameter for the message.

Return Value

This function does not return a value.

Remarks

WaveProc is a placeholder for the application-defined function name.

There are several differences between WaveProc functions under Windows NT and under Windows 3.1:

•	Under Windows 3.1, a WaveProc function is called at interrupt time. The call to a WaveProc function occurs on a separate thread under Windows NT.

•	Under Windows 3.1, a WaveProc function has to be in a dynamic-link library. Under Windows NT, there is no such restriction.

•	Under Windows 3.1, a WaveProc function must be exported in a .DEF file. Under Windows NT, that is not necessary.

If source code must be compatible with Windows 3.1, it should follow the Windows 3.1 rules as briefly noted earlier and as specified more fully in the Windows 3.1 documentation.

One other item should be noted carefully. There is a limited set of functions that a Windows 3.1 WaveProc function can call. In Win32, that strict limitation has been removed. However, it is strongly recommended that a Windows NT WaveProc function restrain its calls to functions in the same set, with the addition of the function SetEvent. Following is the Windows NT recommended list:

EnterCriticalSection	PostThreadMessage
LeaveCriticalSection	SetEvent
midiOutLongMsg	timeGetSystemTime
midiOutShortMsg	timeGetTime
OutputDebugString	timeKillEvent
PostMessage	timeSetEvent
If an application's WaveProc function does stray from this list, it should be careful not to call functions that take a long time to complete.

A WaveProc function should not call other Wave* functions; if it does, it will probably deadlock.

If a Win32 WaveProc shares data with other code, a Critical Section or similar mutual exclusion mechanism should be used to protect the integrity of the data.

See Also

MidiProc, TimeProc, MMIOProc, SetEvent, WAVEHDR, waveInOpen, waveOutOpen


WideCharToMultiByte
 WideCharToMultiByte  QuickInfo  Overview  Group

The WideCharToMultiByte function maps a wide-character string to a new character string. The new character string is not necessarily from a multibyte character set.

int WideCharToMultiByte(

UINT  CodePage,	// code page
DWORD  dwFlags,	// performance and mapping flags
LPCWSTR  lpWideCharStr,	// address of wide-character string
int  cchWideChar,	// number of characters in string
LPSTR  lpMultiByteStr,	// address of buffer for new string
int  cchMultiByte,	// size of buffer
LPCSTR  lpDefaultChar,	// address of default for unmappable characters
LPBOOL  lpUsedDefaultChar	// address of flag set when default char. used
);
Parameters

CodePage

Specifies the code page used to perform the conversion. This parameter can be given the value of any codepage that is installed or available in the system. The following values may be used to specify one of the system default code pages:

Value	Meaning
CP_ACP	ANSI code page
CP_MACCP	Macintosh code page
CP_OEMCP	OEM code page
dwFlags

A set of bit flags that specify the handling of unmapped characters. The function performs more quickly when none of these flags is set. The following flag constants are defined:

Value	Meaning
WC_COMPOSITECHECK	Convert composite characters to precomposed characters.
WC_DISCARDNS	Discard nonspacing characters during conversion.
WC_SEPCHARS	Generate separate characters during conversion. This is the default conversion behavior.
WC_DEFAULTCHAR	Replace exceptions with the default character during conversion.
When WC_COMPOSITECHECK is specified, the function converts composite characters to precomposed characters. A composite character consists of a base character and a nonspacing character, each having different character values. A precomposed character has a single character value for a base/nonspacing character combination. In the character è, the e is the base character, and the accent grave mark is the nonspacing character.

When an application specifies WC_COMPOSITECHECK, it can use the last 3 flags in this list (WC_DISCARDNS, WC_SEPCHARS, and WC_DEFAULTCHAR) to customize the conversion to precomposed characters. These flags determine the function's behavior when there is no precomposed mapping for a base/nonspace character combination in a wide-character string. These last 3 flags can only be used if the WC_COMPOSITECHECK flag is set.

The function's default behavior is to generate separate characters (WC_SEPCHARS) for unmapped composite characters.

lpWideCharStr

Points to the wide-character string to be converted.

cchWideChar

Specifies the number of characters in the string pointed to by the lpWideCharStr parameter. If this value is −1, the string is assumed to be null-terminated and the length is calculated automatically.

lpMultiByteStr

Points to the buffer to receive the translated string.

cchMultiByte

Specifies the size in characters of the buffer pointed to by the lpMultiByteStr parameter. If this value is zero, the function returns the number of bytes required for the buffer. (In this case, the lpMultiByteStr buffer is not used.)

lpDefaultChar

Points to the character used if a wide character cannot be represented in the specified code page. If this parameter is NULL, a system default value is used. The function is faster when both lpDefaultChar and lpUsedDefaultChar are NULL.

lpUsedDefaultChar

Points to a flag that indicates whether a default character was used. 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 parameter may be NULL. The function is faster when both lpDefaultChar and lpUsedDefaultChar are NULL.

Return Value

If the function succeeds, and cchMultiByte is nonzero, the return value is the number of characters written to the buffer pointed to by lpMultiByteStr.

If the function succeeds, and cchMultiByte is zero, the return value is the required size, in bytes, for a buffer that can receive the translated string.

If the function fails, the return value is FALSE. 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 lpMultiByteStr and lpWideCharStr pointers must not be the same. If they are the same, the function fails, and GetLastError returns ERROR_INVALID_PARAMETER.

An application can use the lpDefaultChar parameter to change the default character used for the conversion.

As noted earlier, the WideCharToMultiByte function operates most efficiently when both lpDefaultChar and lpUsedDefaultChar are NULL. The following table shows the behavior of WideCharToMultiByte for the four combinations of lpDefaultChar and lpUsedDefaultChar :

lpDefaultChar	lpUsedDefaultChar	Result
NULL	NULL	No default checking. This is the most efficient, quick way to use this function.
non-NULL	NULL	Uses the specified default character, but does not set lpUsedDefaultChar
NULL	non-NULL	Uses the system default character and sets lpUsedDefaultChar if necessary.
non-NULL	non-NULL	Uses the specified default character and sets lpUsedDefaultChar if necessary.
See Also

MultiByteToWideChar


WidenPath
 WidenPath  QuickInfo  Overview  Group

The WidenPath function redefines the current path as the area that would be painted if the path were stroked using the pen currently selected into the given device context.

BOOL WidenPath(

HDC  hdc	// handle of device context
);
Parameters

hdc

Identifies a device context that contains a closed path.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To get extended error information, call GetLastError. GetLastError may return one of the following error codes:

ERROR_CAN_NOT_COMPLETE
ERROR_INVALID_PARAMETER
ERROR_NOT_ENOUGH_MEMORY

Remarks

The WidenPath function is successful only if the current pen is a geometric pen created by the ExtCreatePen function, or if the pen is created with the CreatePen function and has a width, in device units, of more than one.

The device context identified by the hdc parameter must contain a closed path.

Any Bézier curves in the path are converted to sequences of straight lines approximating the widened curves. As such, no Bézier curves remain in the path after WidenPath is called.

See Also

BeginPath, CreatePen, EndPath, ExtCreatePen, SetMiterLimit


WindowFromDC
 WindowFromDC  QuickInfo  Overview  Group

The WindowFromDC function returns the handle of the window associated with the given display device context (DC). Output functions that use the given device context draw into this window.

HWND WindowFromDC(

HDC  hdc	// handle of window
);
Parameters

hdc

Identifies the device context from which a handle for the associated window is to be retrieved.

Return Value

If the function succeeds, the return value is the handle of the window associated with the given display device context.

If the function fails, the return value is NULL.

See Also

GetDC, GetDCEx, GetWindowDC


WindowFromPoint
 WindowFromPoint  QuickInfo  Overview  Group

The WindowFromPoint function retrieves the handle of the window that contains the specified point.

HWND WindowFromPoint(

POINT  pt	// structure with point
);
Parameters

pt

Specifies a POINT structure that defines the point to be checked.

Return Value

If the function succeeds, the return value is the handle of the window that contains the point. If no window exists at the given point, the return value is NULL.

Remarks

The WindowFromPoint function does not retrieve the handle of a hidden or disabled window, even if the point is within the window. An application should use the ChildWindowFromPoint function for a nonrestrictive search.

See Also

ChildWindowFromPoint, POINT, WindowFromDC


WindowProc
 WindowProc  QuickInfo  Overview  Group

The WindowProc function is an application-defined callback function that processes messages sent to a window.

LRESULT CALLBACK WindowProc(

HWND  hwnd,	// handle of window
UINT  uMsg,	// message identifier
WPARAM  wParam,	// first message parameter
LPARAM  lParam	// second message parameter
);
Parameters

hwnd

Identifies the window.

uMsg

Specifies the message.

wParam

Specifies additional message information. The contents of this parameter depend on the value of the uMsg parameter.

lParam

Specifies additional message information. The contents of this parameter depend on the value of the uMsg parameter.

Return Value

The return value is the result of the message processing and depends on the message sent.

Remarks

WindowProc is a placeholder for the application-defined function name.

See Also

CallWindowProc, DefWindowProc, RegisterClass


WinExec
 WinExec  QuickInfo  Overview  Group

The WinExec function runs the specified application.

This function is provided for compatibility with earlier versions of Windows. For Win32-based applications, use the CreateProcess function.

UINT WinExec(

LPCSTR  lpszCmdLine,	// address of command line
UINT  fuCmdShow	// window style for new application
);
Parameters

lpszCmdLine

Points to a null-terminated character string that contains the command line (filename plus optional parameters) for the application to be executed. If the name of the executable file in the lpszCmdLine parameter does not contain a directory path, Windows searches for the executable file in this sequence:

1.	The directory from which the application loaded.

2.	The current directory.

3.	The Windows system directory. The GetSystemDirectory function retrieves the path of this directory.

4.	The Windows directory. The GetWindowsDirectory function retrieves the path of this directory.

5.	The directories listed in the PATH environment variable.

fuCmdShow

Specifies how a Windows-based application window is to be shown and is used to supply the wShowWindow member of the STARTUPINFO parameter to the CreateProcess function. For a list of the acceptable values, see the description of the nCmdShow parameter of the ShowWindow function. For a non-Windows − based application, the PIF file, if any, for the application determines the window state.

Return Value

If the function succeeds, the return value is greater than 31.

If the function fails, the return value is one of the following error values:

Value	Meaning
0	The system is out of memory or resources.
ERROR_BAD_FORMAT	The .EXE file is invalid (non-Win32 .EXE or error in .EXE image).
ERROR_FILE_NOT_FOUND	The specified file was not found.
ERROR_PATH_NOT_FOUND	The specified path was not found.
Remarks

Win32-based applications should use the CreateProcess function rather than this function. The WinExec function exists in Win32 to provide compatibility with earlier versions of Windows. For more information about how the WinExec function is implemented, see the Remarks section of the LoadModule function.

In Win32, the WinExec function returns when the launched process calls the GetMessage function or a time-out limit is reached. To avoid waiting for the time out delay, call the GetMessage function as soon as possible in any process launched by a call to WinExec.

See Also

CreateProcess, GetMessage, GetSystemDirectory, GetWindowsDirectory, LoadModule, ShowWindow


WinHelp
 WinHelp  QuickInfo  Overview  Group

The WinHelp function starts Windows Help (WINHELP.EXE) and passes additional data indicating the nature of the help requested by the application. The application specifies the name and, where required, the directory path of the help file to display.

BOOL WinHelp(

HWND  hwnd,	// handle of window requesting Help
LPCTSTR  lpszHelp,	// address of directory-path string
UINT  uCommand,	// type of Help
DWORD  dwData	// additional data
);
Parameters

hwnd

Identifies the window requesting Help. The WinHelp function uses this handle to keep track of which applications have requested Help.

lpszHelp

Points to a null-terminated string containing the path, if necessary, and the name of the Help file that the Help application is to display.

The filename may be followed by an angle bracket (>) and the name of a secondary window if the topic is to be displayed in a secondary window rather than in the primary window. The name of the secondary window must have been defined in the [WINDOWS] section of the Help project (.HPJ) file.

uCommand

Specifies the type of help requested. For a list of possible values and how they affect the value to place in the dwData parameter, see the Remarks section.

dwData

Specifies additional data. The value used depends on the value of the uCommand parameter. For a list of possible values, see the Remarks section.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

Before closing the window that requested Help, the application must call WinHelp with the uCommand parameter set to HELP_QUIT. Until all applications have done this, Windows Help will not terminate. Note that calling WinHelp with the HELP_QUIT command is not necessary if you used the HELP_CONTEXTPOPUP command to start Help

The following table shows the possible values for the uCommand parameter and the corresponding formats of the dwData parameter:

uCommand	Action	dwData
HELP_COMMAND	Executes a Help macro or macro string.	Address of a string that specifies the name of the Help macro(s) to execute. If the string specifies multiple macros names, the names must be separated by semicolons. You must use the short form of the macro name for some macros because Help does not support the long name.
HELP_CONTENTS	Displays the topic specified by the Contents option in the [OPTIONS] section of the .HPJ file. This is for backward compatibility. New applications should provide a .CNT file and use the HELP_FINDER command.	Ignored, set to 0.
HELP_CONTEXT	Displays the topic identified by the specified context identifier defined in the [MAP] section of the .HPJ file.	Unsigned long integer containing the context identifier for the topic.
HELP_CONTEXTPOPUP	Displays, in a pop-up window, the topic identified by the specified context identifier defined in the [MAP] section of the .HPJ file.	Unsigned long integer containing the context identifier for a topic.
HELP_FORCEFILE	Ensures that WinHelp is displaying the correct help file. If the incorrect help file is being displayed, WinHelp opens the correct one; otherwise, there is no action.	Ignored, set to 0.
HELP_HELPONHELP	Displays help on how to use Windows Help, if the WINHELP.HLP file is available.	Ignored, set to 0.
HELP_INDEX	Displays the Index in the Help Topics dialog box. This command is for backward compatibility. New applications should use the HELP_FINDER command.	Ignored, set to 0.
HELP_KEY	Displays the topic in the keyword table that matches the specified keyword, if there is an exact match. If there is more than one match, displays the Index with the topics listed in the Topics Found list box.	Address of a keyword string.
HELP_MULTIKEY	Displays the topic specified by a keyword in an alternative keyword table.	Address of a MULTIKEYHELP structure that specifies a table footnote character and a keyword.
HELP_PARTIALKEY	Displays the topic in the keyword table that matches the specified keyword, if there is an exact match. If there is more than one match, displays the Index tab. To display the Index without passing a keyword (the third result), you should use a pointer to an empty string.	Address of a keyword  string.
HELP_QUIT	Informs the Help application that it is no longer needed. If no other applications have asked for Help, Windows closes the Help application.	Ignored, set to 0.
HELP_SETCONTENTS	Specifies the Contents topic. The Help application displays this topic when the user clicks the Contents button.	Unsigned long integer containing the context identifier for the Contents topic.
HELP_SETINDEX	Specifies a keyword table to be displayed in the Index of the Help Topics dialog box.	Unsigned long integer containing the context identifier for the Index topic.
HELP_SETWINPOS	Displays the Help window, if it is minimized or in memory, and sets its size and position as specified.	Address of a HELPWININFO structure that specifies the size and position of either a primary or secondary Help window.
See Also

HELPWININFO, MULTIKEYHELP


WinMain
 WinMain  QuickInfo  Overview  Group

The WinMain function is called by the system as the initial entry point for a Windows-based application.

int WINAPI WinMain(

HINSTANCE  hInstance,	// handle of current instance
HINSTANCE  hPrevInstance,	// handle of previous instance
LPSTR  lpszCmdLine,	// pointer to command line
int  nCmdShow	// show state of window
);
Parameters

hInstance

Identifies the current instance of the application.

hPrevInstance

Identifies the previous instance of the application. For a Win32-based application, this parameter is always NULL.

lpszCmdLine

Points to a null-terminated string specifying the command line for the application.

nCmdShow

Specifies how the window is to be shown. This parameter can be one of the following values:

Value	Meaning
SW_HIDE	Hides the window and activates another window.
SW_MINIMIZE	Minimizes the specified window and activates the top-level window in the system's list.
SW_RESTORE	Activates and displays a window. If the window is minimized or maximized, Windows restores it to its original size and position (same as SW_SHOWNORMAL).
SW_SHOW	Activates a window and displays it in its current size and position.
SW_SHOWMAXIMIZED	Activates a window and displays it as a maximized window.
SW_SHOWMINIMIZED	Activates a window and displays it as an icon.
SW_SHOWMINNOACTIVE	Displays a window as an icon. The active window remains active.
SW_SHOWNA	Displays a window in its current state. The active window remains active.
SW_SHOWNOACTIVATE	Displays a window in its most recent size and position. The active window remains active.
SW_SHOWNORMAL	Activates and displays a window. If the window is minimized or maximized, Windows restores it to its original size and position (same as SW_RESTORE).
Return Value

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

Remarks

WinMain initializes an application, and then performs a message retrieval-and-dispatch loop that is the top-level control structure for the remainder of the application's execution. The loop terminates when a WM_QUIT message is received. At that point, WinMain exits 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.

See Also

DispatchMessage, GetMessage, PostQuitMessage, TranslateMessage


WNetAddConnection
 WNetAddConnection  QuickInfo  Overview  Group

The WNetAddConnection function enables the calling application to connect a local device to a network resource. A successful connection is persistent, meaning that Windows automatically restores the connection during subsequent logon operations.

This function is provided for compatibility with earlier versions of Microsoft Windows. For new applications, use the WNetAddConnection2 function.

DWORD WNetAddConnection(

LPTSTR  lpszRemoteName,	// address of network device name
LPTSTR  lpszPassword,	// address of password
LPTSTR  lpszLocalName	// address of local device name
);
Parameters

lpszRemoteName

Points to a null-terminated string that specifies the network resource to connect to.

lpszPassword

Points to a null-terminated string that specifies the password to be used to make a connection. This parameter is usually the password associated with the current user.

If this parameter is NULL, the default password is used. If the string is empty, no password is used.

lpszLocalName

Points to a null-terminated string that specifies the name of a local device to be redirected, such as F: or LPT1. The case of the characters in the string is not important. If the string is NULL, a connection to the network resource is made without redirecting the local device.

Return Value

If the function succeeds, the return value is NO_ERROR.

If the function fails, the return value is an error code. To get extended error information, call GetLastError. GetLastError may return one of the following error codes:

Value	Meaning
ERROR_ACCESS_DENIED	Access is denied.
ERROR_ALREADY_ASSIGNED	The device specified in the lpszLocalName parameter is already connected.
ERROR_BAD_DEV_TYPE	The device type and the resource type do not match.
ERROR_BAD_DEVICE	The value specified in lpszLocalName is invalid.
ERROR_BAD_NET_NAME	The value specified in the lpszRemoteName parameter is not valid or cannot be located.
ERROR_BAD_PROFILE	The user profile is in an incorrect format.
ERROR_CANNOT_OPEN_PROFILE	The system is unable to open the user profile to process persistent connections.
ERROR_DEVICE_ALREADY_REMEMBERED	An entry for the device specified in lpszLocalName is already in the user profile.
ERROR_EXTENDED_ERROR	A network-specific error occurred. To get a description of the error, use the WNetGetLastError function.
ERROR_INVALID_PASSWORD	The specified password is invalid.
ERROR_NO_NET_OR_BAD_PATH	The operation cannot be performed because either a network component is not started or the specified name cannot be used.
ERROR_NO_NETWORK	The network is not present.
The function returns error codes and sets the error code values returned by GetLastError.

See Also

WNetAddConnection2, WNetCancelConnection, WNetCancelConnection2, WNetGetConnection, WNetGetLastError


WNetAddConnection2
 WNetAddConnection2  QuickInfo  Overview  Group

The WNetAddConnection2 function makes a connection to a network resource. The function can redirect a local device to the network resource.

The WNetAddConnection2 function supersedes the WNetAddConnection function. If you pass a handle to a window that the provider of network resources can use as an owner window for dialog boxes, use the WNetAddConnection3 function.

DWORD WNetAddConnection2(

LPNETRESOURCE  lpNetResource,	// points to structure that specifies connection details
LPCTSTR  lpPassword,	// points to password string
LPCTSTR  lpUsername,	// points to user name string
DWORD  fdwConnection	// set of bit flags that specify connection options
);
Parameters

lpNetResource

Points to a NETRESOURCE structure that specifies details of the proposed connection: information about the network resource, the local device, and the network resource provider.

You must specify the following members of the NETRESOURCE structure:

Member	Description
dwType	Specifies the type of network resource to connect to. If lpLocalName points to a non-empty string, this member can be RESOURCETYPE_DISK or RESOURCETYPE_PRINT. If lpLocalName is NULL or points to an empty string, dwType can be RESOURCETYPE_DISK, RESOURCETYPE_PRINT, or RESOURCETYPE_ANY.
lpLocalName	Points to a null-terminated string that specifies the name of a local device to be redirected, such as "F:" or "LPT1". The string is treated in a case-insensitive manner. If the string is empty or lpLocalName is NULL, the function makes a connection to the network resource without redirecting a local device.
lpRemoteName	Points to a null-terminated string that specifies the network resource to connect to. The string can be up to MAX_PATH characters in length. The string must follow the network provider's naming conventions.
lpProvider	Points to a null-terminated string that specifies the network provider to connect to. If lpProvider is NULL or points to an empty string, the operating system attempts to determine the correct provider by parsing the string pointed to by lpRemoteName.
	You should set this member only if you know for sure which network provider you want to use. Otherwise, let the operating system determine which provider the network name maps to.
	If this member is not NULL, the operating system attempts to make a connection only to the named network provider.
The WNetAddConnection2 function ignores the other members of the NETRESOURCE structure.

lpPassword

Points to a null-terminated string that specifies a password to be used in making the network connection.

If lpPassword is NULL, the function uses the current default password associated with the user specified by lpUserName.

If lpPassword points to an empty string, the function does not use a password.

lpUsername

Points to a null-terminated string that specifies a user name to be used in making the connection.

If lpUserName is NULL, the function uses the default user name. The user context for the process provides the default user name.

The lpUserName parameter is specified when users want to connect to a network resource for which they have been assigned a user name or account other than the default user name or account.

The user-name string represents a security context. It may be specific to a network provider.

fdwConnection

A set of bit flags that specify connection options. The following bit flag constant is currently defined:

Value	Meaning
CONNECT_UPDATE_PROFILE	The network resource connection should be remembered.  If this bit flag is set, the operating system automatically attempts to restore the connection when the user logs on. The operating system remembers only successful connections that redirect local devices. It does not remember unsuccessful connections or deviceless connections. A deviceless connection occurs when lpLocalName is NULL or points to an empty string. If this bit flag is clear, the operating system will not automatically restore the connection at logon.
Return Value

If the function succeeds, the return value is NO_ERROR.

If the function fails, the return value is an error code. Returning an error code provides compatibility with the behavior of the Windows 3.1 function WNetAddConnection. You can also call the GetLastError function to obtain the (same) error code. One of the following error codes may be returned when WNetAddConnection2 fails:

Value	Meaning
ERROR_ACCESS_DENIED	Access to the network resource was denied.
ERROR_ALREADY_ASSIGNED	The local device specified by lpLocalName is already connected to a network resource.
ERROR_BAD_DEV_TYPE	The type of local device and the type of network resource do not match.
ERROR_BAD_DEVICE	The value specified by lpLocalName is invalid.
ERROR_BAD_NET_NAME	The value specified by lpRemoteName is not acceptable to any network resource provider. The resource name is invalid, or the named resource cannot be located.
ERROR_BAD_PROFILE	The user profile is in an incorrect format.
ERROR_BAD_PROVIDER	The value specified by lpProvider does not match any provider.
ERROR_BUSY	The router or provider is busy, possibly initializing. The caller should retry.
ERROR_CANCELLED	The attempt to make the connection was cancelled by the user through a dialog box from one of the network resource providers, or by a called resource.
ERROR_CANNOT_OPEN_PROFILE	The system is unable to open the user profile to process persistent connections.
ERROR_DEVICE_ALREADY_REMEMBERED	An entry for the device specified in lpLocalName is already in the user profile.
ERROR_EXTENDED_ERROR	A network-specific error occured. Call the WNetGetLastError function to get a description of the error.
ERROR_INVALID_PASSWORD	The specified password is invalid.
ERROR_NO_NET_OR_BAD_PATH	A network component has not started, or the specified name could not be handled.
ERROR_NO_NETWORK	There is no network present.
See Also

WNetAddConnection, WNetAddConnection3, WNetCancelConnection2, WNetGetConnection, WNetGetLastError, NETRESOURCE


WNetAddConnection3
 WNetAddConnection3  QuickInfo  Overview  Group

The WNetAddConnection3 function makes a connection to a network resource. The function can redirect a local device to the network resource.

The WNetAddConnection3 function is similar to the WNetAddConnection2 function. The main difference is that WNetAddConnection3 has an additional parameter, a handle to a window that the provider of network resources can use as an owner window for dialog boxes.

DWORD WNetAddConnection3(

HWND  hwndOwner,	// handle to an owner window for network provider dialog boxes
LPNETRESOURCE  lpNetResource,	// address of structure that specifies connection details
LPTSTR  lpPassword,	// address of password string
LPTSTR  lpUserName,	// address of user name string
DWORD  fdwConnection	// set of bit flags that specify connection options
);
Parameters

hwndOwner

Specifies a window that the provider of network resources can use as an owner window for dialog boxes.

The hwndOwner parameter may be NULL. If it is, a call to WNetAddConnection3 is equivalent to calling the WNetAddConnection2 function.

lpNetResource

Points to a NETRESOURCE data structure that specifies details of the proposed connection: information about the network resource, the local device, and the network resource provider.

You must specify the following members of the NETRESOURCE structure:

Member	Description
dwType	Specifies the type of network resource to connect to. If lpLocalName points to a non-empty string, this member can be RESOURCETYPE_DISK or RESOURCETYPE_PRINT. If lpLocalName is NULL or points to an empty string, dwType can be RESOURCETYPE_DISK, RESOURCETYPE_PRINT, or RESOURCETYPE_ANY.
lpLocalName	Points to a null-terminated string that specifies the name of a local device to be redirected, such as "F:" or "LPT1". The string is treated in a case-insensitive manner. If the string is empty or lpLocalName is NULL, the function makes a connection to the network resource without redirecting a local device.
lpRemoteName	Points to a null-terminated string that specifies the network resource to connect to. The string can be up to MAX_PATH characters in length . The string must follow the network provider's naming conventions.
lpProvider	Points to a null-terminated string that specifies the network provider to connect to. If lpProvider is NULL or points to an empty string, the operating system attempts to determine the correct provider by parsing the string pointed to by lpRemoteName.
	You should set this member only if you know for sure which network provider you want to use. Otherwise, let the operating system determine which network provider the network name maps to.
	If this member is not NULL, the operating system attempts to make a connection only to the named network provider.
The WNetAddConnection3 function ignores the other members of the NETRESOURCE structure.

lpPassword

Points to a null-terminated string that specifies a password to be used in making the network connection.

If lpPassword is NULL, the function uses the current default password associated with the user specified by lpUserName.

If lpPassword points to an empty string, the function does not use a password.

lpUserName

Points to a null-terminated string that specifies a user name to be used in making the connection.

If lpUserName is NULL, the function uses the default user name. The user context for the process provides the default user name.

The lpUserName parameter is specified when users want to connect to a network resource for which they have been assigned a user name or account other than the default user name or account.

The user-name string represents a security context. It may be specific to a network provider.

fdwConnection

A set of bit flags that specify connection options. The following bit flag constants are currently defined:

Value	Meaning
CONNECT_UPDATE_PROFILE	The network resource connection should be remembered.  If this bit flag is set, the operating system automatically attempts to restore the connection when the user logs on. The operating system remembers only successful connections that redirect local devices. It does not remember unsuccessful connections and deviceless connections. A deviceless connection occurs when lpLocalName is NULL or points to an empty string. If this bit flag is clear, the operating system will not automatically restore the connection at logon.
Return Value

If the function succeeds, the return value is NO_ERROR.

If the function fails, the return value is an error code. Returning an error code provides compatibility with the behavior of the Windows 3.1 function WNetAddConnection. You can also call the GetLastError function to obtain the (same) error code. One of the following error codes may be returned when WNetAddConnection3 fails:

Value	Meaning
ERROR_ACCESS_DENIED	Access to the network resource was denied.
ERROR_ALREADY_ASSIGNED	The local device specified by lpLocalName is already connected to a network resource.
ERROR_BAD_DEV_TYPE	The type of local device and the type of network resource do not match.
ERROR_BAD_DEVICE	The value specified by lpLocalName is invalid.
ERROR_BAD_NET_NAME	The value specified by lpRemoteName is not acceptable to any network resource provider. The resource name is invalid, or the named resource cannot be located.
ERROR_BAD_PROFILE	The user profile is in an incorrect format.
ERROR_BAD_PROVIDER	The value specified by lpProvider does not match any provider.
ERROR_BUSY	The router or provider is busy, possibly initializing. The caller should retry.
ERROR_CANCELLED	The attempt to make the connection was cancelled by the user through a dialog box from one of the network resource providers or by a called resource.
ERROR_CANNOT_OPEN_PROFILE	The system is unable to open the user profile to process persistent connections.
ERROR_DEVICE_ALREADY_REMEMBERED	An entry for the device specified in lpLocalName is already in the user profile.
ERROR_EXTENDED_ERROR	A network-specific error occured. Call the WNetGetLastError function to get a description of the error.
ERROR_INVALID_PASSWORD	The specified password is invalid.
ERROR_NO_NET_OR_BAD_PATH	A network component has not started, or the specified name could not be handled.
ERROR_NO_NETWORK	There is no network present.
See Also

NETRESOURCE, WNetAddConnection2, WNetCancelConnection2, WNetGetConnection, WNetGetLastError


WNetCancelConnection
 WNetCancelConnection  QuickInfo  Overview  Group

The WNetCancelConnection function breaks an existing network connection.

The function is provided for compatibility with earlier versions of Microsoft Windows. For new applications, use the WNetCancelConnection2 function.

DWORD WNetCancelConnection(

LPTSTR  lpszName,	// address of resource name to be disconnected
BOOL  fForce	// flag for unconditional disconnect
);
Parameters

lpszName

Points to a null-terminated string that specifies the name of either the redirected local device or the remote network resource to disconnect from. When this parameter specifies a redirected local device, only the specified redirection is broken, and Windows will not restore the connection during subsequent logon operations. When this parameter specifies a remote network resource, the connection to that remote network resource is broken.

fForce

Specifies whether the disconnection is to occur even if there are open files or jobs on the connection. If this parameter is FALSE, the function fails if there are open files or jobs.

Return Value

If the function succeeds, the return value is NO_ERROR.

If the function fails, the return value is an error code. To get extended error information, call GetLastError. GetLastError may return one of the following error codes:

Value	Meaning
ERROR_BAD_PROFILE	The user profile is in an incorrect format.
ERROR_CANNOT_OPEN_PROFILE	The system is unable to open the user profile to process persistent connections.
ERROR_DEVICE_IN_USE	The device is in use by an active process and cannot be disconnected.
ERROR_EXTENDED_ERROR	A network-specific error occurred. To get a description of the error, use the WNetGetLastError function.
ERROR_NOT_CONNECTED	The name specified by the lpszName parameter is not a redirected device, or the system is not currently connected to the device specified by the parameter.
ERROR_OPEN_FILES	There are open files, and the fForce parameter is FALSE.
The function returns error codes for compatibility with Windows version 3.1. For compatibility with the Win32 API, the function also sets the error code value returned by GetLastError.

See Also

WNetAddConnection, WNetAddConnection2, WNetCancelConnection2, WNetGetConnection, WNetGetLastError


WNetCancelConnection2
 WNetCancelConnection2  QuickInfo  Overview  Group

The WNetCancelConnection2 function breaks an existing network connection. It can also be used to remove remembered network connections that are not currently connected. This function supersedes WNetCancelConnection.

DWORD WNetCancelConnection2(

LPTSTR  lpszName,	// address of resource name to disconnect
DWORD  fdwConnection,	// connection type flags
BOOL  fForce	// flag for unconditional disconnect
);
Parameters

lpszName

Points to a null-terminated string that specifies the name of either the redirected local device or the remote network resource to disconnect from. If this parameter specifies a redirected local resource, only the specified redirection is broken; otherwise, all connections to the remote network resource are broken.

fdwConnection

Specifies a bitmask for the connection type. The following values are defined:

Value	Meaning
0	No information about the connection is stored.
CONNECT_UPDATE_PROFILE	The user profile is updated with the information that this is no longer a persistent connection. Windows will not restore this connection during subsequent logon operations. Disconnecting resources using remote names has no effect on persistent connections.
fForce

Specifies whether the disconnection should occur even if there are open files or jobs on the connection. If this parameter is FALSE, the function fails if there are open files or jobs.

Return Value

If the function succeeds, the return value is NO_ERROR.

If the function fails, the return value is an error code. To get extended error information, call GetLastError. GetLastError may return one of the following error codes:

Value	Meaning
ERROR_BAD_PROFILE	The user profile is in an incorrect format.
ERROR_CANNOT_OPEN_PROFILE	The system is unable to open the user profile to process persistent connections.
ERROR_DEVICE_IN_USE	The device is in use by an active process and cannot be disconnected.
ERROR_EXTENDED_ERROR	A network-specific error occurred. To get a description of the error, use the WNetGetLastError function.
ERROR_NOT_CONNECTED	The name specified by the lpszName parameter is not a redirected device, or the system is not currently connected to the device specified by the parameter.
ERROR_OPEN_FILES	There are open files, and the fForce parameter is FALSE.
See Also

WNetAddConnection, WNetAddConnection2, WNetAddConnection3, WNetCancelConnection, WNetGetConnection, WNetGetLastError


WNetCloseEnum
 WNetCloseEnum  QuickInfo  Overview  Group

The WNetCloseEnum function ends a network resource enumeration started by the WNetOpenEnum function.

DWORD WNetCloseEnum(

HANDLE  hEnum	// handle of enumeration
);
Parameters

hEnum

Identifies an enumeration instance. This handle must be returned by the WNetOpenEnum function.

Return Value

If the function succeeds, the return value is NO_ERROR.

If the function fails, the return value is an error code. To get extended error information, call GetLastError. GetLastError may return one of the following error codes:

Value	Meaning
ERROR_NO_NETWORK	A network is not present. This condition is tested before the handle specified in the hEnum parameter is tested for validity.
ERROR_INVALID_HANDLE	hEnum is not a valid handle.
ERROR_EXTENDED_ERROR	A network-specific error occurred. To get a description of the error, use the WNetGetLastError function.
The function returns error codes for compatibility with Windows version 3.1. For compatibility with Windows NT, the function also sets the error code value returned by GetLastError.

See Also

WNetEnumResource, WNetGetLastError, WNetOpenEnum


WNetConnectionDialog
 WNetConnectionDialog  QuickInfo  Overview  Group

The WNetConnectionDialog function starts a general browsing dialog box for connecting to network resources.

DWORD WNetConnectionDialog(

HWND  hwnd,	// handle of window owning dialog box
DWORD  fdwResourceType	// resource type to allow connections to
);
Parameters

hwnd

Identifies the owning window.

fdwResourceType

Specifies the resource type to allow connections to. This parameter can be the following value:

Value	Meaning
RESOURCETYPE_DISK	Connects to disk resources.
Return Value

If the function succeeds, the return value is NO_ERROR. If the user cancels the dialog box, it is 0xFFFFFFFF.

If the function fails, the return value is an error code. To get extended error information, call GetLastError. GetLastError may return one of the following error codes:

Value	Meaning
ERROR_EXTENDED_ERROR	A network-specific error occurred. To get a description of the error, use the WNetGetLastError function.
ERROR_INVALID_PASSWORD	The specified password is invalid.
ERROR_NO_NETWORK	No network is present.
ERROR_NOT_ENOUGH_MEMORY	There is insufficient memory to start the dialog box.
The function returns error codes for compatibility with Windows version 3.1. For compatibility with the Win32 API, the function also sets the error code value returned by the GetLastError function.

Remarks

If the user chooses OK in the dialog box, the requested network connections will have been performed when WNetConnectionDialog returns.

If the function attempts to make a connection and the provider returns the message ERROR_INVALID_PASSWORD, Windows prompts the user to enter a password and uses the new password in another attempt to make the connection.

See Also

WNetAddConnection2, WNetCancelConnection2, WNetDisconnectDialog, WNetGetLastError


WNetDisconnectDialog
 WNetDisconnectDialog  QuickInfo  Overview  Group

The WNetDisconnectDialog function starts a general browsing dialog box for disconnecting from network resources.

DWORD WNetDisconnectDialog(

HWND  hwnd,	// handle of window owning dialog box
DWORD  fdwResourceType	// resource type to disconnect from
);
Parameters

hwnd

Identifies the owning window.

fdwResourceType

Specifies the resource type to disconnect from. This parameter may be one of the following values:

Value	Meaning
RESOURCETYPE_DISK	Disconnects from disk resources.
RESOURCETYPE_PRINT	Disconnects from print resources.
Return Value

If the function succeeds, the return value is NO_ERROR. If the user cancels out of the dialog box, it is 0xFFFFFFFF.

If the function fails, the return value is an error code. To get extended error information, call GetLastError. GetLastError may return one of the following error codes:

Value	Meaning
ERROR_EXTENDED_ERROR	A network-specific error occurred. To get a description of the error, use the WNetGetLastError function.
ERROR_NO_NETWORK	No network is present.
ERROR_NOT_ENOUGH_MEMORY	There is insufficient memory to start the dialog box.
The function returns error codes for compatibility with Windows version 3.1. For compatibility with the Win32 API, the function also sets the error code value returned by GetLastError.

Remarks

If the user chooses OK in the dialog box, the requested network disconnections will have been performed when WNetDisconnectDialog returns.

See Also

WNetAddConnection2, WNetCancelConnection2, WNetConnectionDialog, WNetGetLastError


WNetEnumResource
 WNetEnumResource  QuickInfo  Overview  Group

The WNetEnumResource function continues a network-resource enumeration started by the WNetOpenEnum function.

DWORD WNetEnumResource(

HANDLE  hEnum,	// handle of enumeration
LPDWORD  lpcEntries,	// address of entries to list
LPVOID  lpvBuffer,	// address of buffer for results
LPDWORD  lpcbBuffer	// address of buffer size variable
);
Parameters

hEnum

Identifies an enumeration instance. This handle must be returned by WNetOpenEnum.

lpcEntries

Points to a variable specifying the number of entries requested. If the number requested is 0xFFFFFFFF, the function returns as many entries as possible.

When the function finishes successfully, the variable pointed to by this parameter contains the number of entries actually read.

lpvBuffer

Points to the buffer that receives the enumeration results, which are returned as an array of NETRESOURCE structures. The buffer is valid until the next call using the handle given by the hEnum parameter. The order of NETRESOURCE structures in the array is not predictable.

lpcbBuffer

Points to a variable that specifies the size, in bytes, of the lpvBuffer parameter. If the buffer is too small to receive even one entry, this parameter receives the required size of the buffer.

Return Value

If the function succeeds, the return value is one of the following values:

Value	Meaning
NO_ERROR	The enumeration succeeded, and the buffer contains the requested data. The calling application can continue to call WNetEnumResource to complete the enumeration.
ERROR_NO_MORE_ITEMS	There are no more entries. The buffer contents are undefined.
If the function fails, the return value is an error code. To get extended error information, call GetLastError. GetLastError may return one of the following error codes:

Value	Meaning
ERROR_MORE_DATA	The buffer is too small for even one entry.
ERROR_INVALID_HANDLE	The handle given by the hEnum parameter is not valid.
ERROR_NO_NETWORK	No network is present. This condition is tested before hEnum is tested for validity.
ERROR_EXTENDED_ERROR	A network-specific error occurred. To get a description of the error, use the WNetGetLastError function.
The function returns error codes for compatibility with Windows version 3.1. For compatibility with the Win32 API, the function also sets the error code value returned by GetLastError.

Remarks

An application cannot set the lpvBuffer parameter to NULL and retrieve the required buffer size from the lpcbBuffer parameter. Instead, the application should allocate a buffer of a reasonable size — 16 kilobytes (K) is typical — and use the value of lpcbBuffer for error detection.

See Also

NETRESOURCE, WNetCloseEnum, WNetGetLastError, WNetOpenEnum


WNetGetConnection
 WNetGetConnection  QuickInfo  Overview  Group

The WNetGetConnection function retrieves the name of the network resource associated with a local device.

DWORD WNetGetConnection(

LPTSTR  lpszLocalName,	// address of local name
LPTSTR  lpszRemoteName,	// address of buffer for remote name
LPDWORD  lpcchBuffer	// address of buffer size, in characters
);
Parameters

lpszLocalName

Points to a null-terminated string that specifies the name of the local device to get the network name for.

lpszRemoteName

Points to a buffer that receives the null-terminated remote name used to make the connection.

lpcchBuffer

Points to a variable that specifies the size, in characters, of the buffer pointed to by the lpszRemoteName parameter. If the function fails because the buffer is not big enough, this parameter returns the required buffer size.

Return Value

If the function succeeds, the return value is NO_ERROR.

If the function fails, the return value is an error code. To get extended error information, call GetLastError. GetLastError may return one of the following error codes:

Value	Meaning
ERROR_BAD_DEVICE	The string pointed to by the lpszLocalName parameter is invalid.
ERROR_NOT_CONNECTED	The device specified by lpszLocalName is not redirected.
ERROR_MORE_DATA	The buffer is too small. The lpcchBuffer parameter points to a variable that contains the required buffer size.
ERROR_CONNECTION_UNAVAIL	The device is not currently connected, but it is a persistent connection.
ERROR_NO_NETWORK	No network is present.
ERROR_EXTENDED_ERROR	A network-specific error occurred. To get a description of the error, use the WNetGetLastError function.
ERROR_NO_NET_OR_BAD_PATH	None of the providers recognized this local name as having a connection. However, the network is not available for at least one provider to whom the connection may belong.
The WNetGetConnection function returns error codes for compatibility with Windows version 3.1. For compatibility with the Win32 API, the function also sets the error code value returned by GetLastError.

See Also

WNetAddConnection2, WNetAddConnection3, WNetGetLastError, WNetGetUser


WNetGetLastError
 WNetGetLastError  QuickInfo  Overview  Group

The WNetGetLastError function retrieves the most recent extended error code set by a Windows network function.

DWORD WNetGetLastError(

LPDWORD  lpdwErrorCode,	// address of error code
LPTSTR  lpszDescription,	// address of string describing error
DWORD  cchDescription,	// size of description buffer, in characters
LPTSTR  lpszName,	// address of buffer for provider name
DWORD  cchName	// size of provider name buffer
);
Parameters

lpdwErrorCode

Points to the variable that receives the error code reported by the network provider. The error code is specific to the network provider.

lpszDescription

Points to the buffer that receives the null-terminated string describing the error.

cchDescription

Specifies the size, in characters, of the buffer pointed to by the lpszDescription parameter. If the buffer is too small for the error string, the string is truncated but still null-terminated. A buffer of at least 256 characters is recommended.

lpszName

Points to the buffer that receives the null-terminated string identifying the network provider that raised the error.

cchName

Specifies the size, in characters, of the buffer pointed to by the lpszName parameter. If the buffer is too small for the error string, the string is truncated but still null-terminated.

Return Value

If the function successfully obtains the last error reported by the provider, the return value is NO_ERROR. If the caller supplies an invalid buffer, it is ERROR_INVALID_ADDRESS.

Remarks

WNetGetLastError is used to obtain errors that are specific to a network provider. It should be used when a Windows network function (or the GetLastError function) returns ERROR_EXTENDED_ERROR. Like GetLastError, the function returns extended error information, which is maintained on a per-thread basis. Unlike GetLastError, the WNetGetLastError function can also return a string for reporting errors that are not described by any existing error code.

See Also

GetLastError


 WNetGetResourceInformation

The WNetGetResourceInformation function retrieves enumeration information for a network resource. You typically use this function when the user specifies an object. Call this function in conjunction with WNetGetResourceParent to determine the placement and nature of the resource in the browse hierarchy. Unlike WNetGetResourceParent, WNetGetResourceInformation always tries to determine the network provider that owns the resource and the type of the resource, although it might not currently be accessible (or even exist if the type of the resource was specified by the caller).

DWORD WNetGetResourceInformation(

LPNETRESOURCE lpNetResource,	// specifies the network resource
LPVOID lpBuffer,	// pointer to a buffer for results
LPDWORD cbBuffer,	// size of the buffer
LPTSTR *lplpSystem	// pointer to a string in the buffer
);
Parameters

lpNetResource

Specifies the network resource for which the information is required. The lpRemoteName member of the NETRESOURCE structure specifies the remote name of the network resource. The user typically provides this.

Determining the values of the lpProvider and especially the dwType members of the NETRESOURCE structure is a time-consuming operation. If the calling application has these values, it should fill them in. Otherwise, it should set them to NULL. All other members in the NETRESOURCE structure are ignored.

lpBuffer

Points to the buffer that receives the result. The first field in the buffer is a NETRESOURCE structure. The dwScope, lpRemoteName, lpProvider, dwType, and dwUsage members of the structure are returned; all other members are set to NULL.

The remote name pointed to by lpRemoteName is in the same syntax as that returned from an enumeration, so that the calling application can perform a case-sensitive string comparison to determine whether the lpRemoteName resource is enumerated.

The provider name pointed to by lpProvider is always returned when it is known to which network the resource belongs. If the resource cannot be found on any of the networks, then lpRemoteName is returned as NULL, and lpProvider can be non-NULL if a parent for the resource is known to be on one of the networks.

The dwScope member is returned as RESOURCE_CONTEXT if the network resource is part of the user's network context. Otherwise, it is returned as zero.

cbBuffer

Specifies the size of the buffer passed to WNetGetResourceInformation. If the buffer is too small to receive even one entry, the function returns the required size of the buffer in this variable, as well the value WN_MORE_DATA.

lplpSystem

Points to a string in the buffer pointed to by lpBuffer that specifies the part of the resource that is accessed through system-resource type-specific functions rather than WNet functions.

For example, if the input remote resource name is "\\SERVER\SHARE\DIR", then lpRemoteName is returned pointing to "\\SERVER\SHARE" and lplpSystem points to "\DIR". Both strings are stored in the buffer pointed to by lpBuffer.

Return Value

The WNetGetResourceInformation function returns one of the following values:

Value	Meaning
WN_BAD_NETNAME	The network resource specified by the lpRemoteName member of the NETRESOURCE structure does not exist for any network. If the lpProvider member of the NETRESOURCE structure is not NULL, then a parent of the specified network resource does exist and can be accessed by calls to WNetGetResourceParent.
WN_EXTENDED_ERROR	A network-specific error occurred. Call WNetGetLastError to obtain a description of the error.
WN_MORE_DATA	The buffer is too small for the information. In this case, the function returns the required size of the buffer in cbBuffer.
WN_NO_NETWORK	The network is not present.
WN_SUCCESS	The call is successful.
See Also

NETRESOURCE, WNetCloseEnum, WNetGetLastError, WNetGetResourceParent, WNetOpenEnum


 WNetGetResourceParent

The WNetGetResourceParent function lets you navigate up from a resource. It enables browsing to commence based on the name of a network resource. This function also allows navigating up from a browsed resource to find connectable resources.

You can call WNetGetResourceParent for names that were returned by WNetEnumResource. Unlike WNetGetResourceInformation, if the resource syntactically has a parent, the parent is returned by WNetGetResourceParent, whether or not the parent actually exists.

DWORD WNetGetResourceParent(

LPNETRESOURCE lpNetResource,	// specifies the network resource
LPVOID lpBuffer,	// pointer to a buffer for results
LPDWORD lpBufferSize,	// size, in bytes, of the buffer
);
Parameters

lpNetResource

Specifies the network resource for which the parent name is required. You can obtain the NETRESOURCE structure by calling WNetEnumResource or by constructing it yourself. The lpRemoteName member of the structure specifies the remote name of the network resource.

If the calling application has the values of the lpProvider and dwType members of the NETRESOURCE structure (as it would from a call to WNetGetResourceInformation), it should fill them in. Otherwise, it should set the members to NULL. All other members in the NETRESOURCE structure are ignored.

lpBuffer

Points to the buffer that receives the result, which is a single NETRESOURCE structure for the parent resource. The lpRemoteName, lpProvider, dwType, and dwUsage members are returned; all other members are set to NULL.

The remote name pointed to by lpRemoteName is in the same syntax as that returned from an enumeration, so that the caller can perform a case-sensitive string comparison to determine whether an enumerated resource is this resource.

The provider name pointed to by lpProvider is returned only if it is known to which network the resource belongs. If several networks could own the resource, (as might be the case for a resource such as "\\SERVER"), then lpProvider will be set to NULL. If a resource has no parent on any of the networks, then lpRemoteName is returned as NULL. If it is known that a network owns a parent of the resource, but the resource itself is not valid, then lpProvider is returned as a non-null value, together with a return status of WN_BAD_NETNAME.

Note that if a network shows that the object is on the network, but has no parent (for example, a server that is not part of a workgroup), then WNetGetResourceParent might return with lpRemoteName and lpProvider both set to NULL.

The RESOURCEUSAGE_CONNECTABLE value in the dwUsage member does not indicate that the resource can currently be connected to, but that the resource is connectable when it is available on the network.

lpBufferSize

Specifies the size, in bytes, of the buffer passed to WNetGetResourceParent. If the buffer is too small to hold the NETRESOURCE information, the function returns the required size of the buffer in this variable, as well as the value WN_MORE_DATA.

Return Value

The WNetGetResourceParent function returns one of the following values:

Value	Meaning
WN_ACCESS_DENIED	The user is authenticated to the network, but does not have sufficient permissions (access rights).
WN_BAD_NETNAME	The name pointed to by the lpRemoteName member is not a syntactically valid name for a remote resource for any network.
WN_BAD_PROVIDER	The name pointed to by the lpProvider member does not match any network provider.
WN_MORE_DATA	The buffer is too small for the information. In this case, the function returns the required size of the buffer in lpBufferSize.
WN_NOT_AUTHENTICATED	The caller does not have the necessary permissions to obtain the name of the parent.
WN_SUCCESS	The call is successful.
See Also

NETRESOURCE, WNetCloseEnum, WNetEnumResource, WNetGetLastError, WNetGetResourceInformation,WNetOpenEnum


WNetGetUniversalName
 WNetGetUniversalName  QuickInfo  Overview  Group

The WNetGetUniversalName function takes a drive-based path for a network resource and obtains a data structure that contains a more universal form of the name.

DWORD WNetGetUniversalName(

LPCTSTR  lpLocalPath,	// address of drive-based path for a network resource
DWORD  dwInfoLevel,	// specifies form of universal name to be obtained
LPVOID  lpBuffer,	// address of buffer that receives universal name data structure
LPDWORD  lpBufferSize	// address of variable that specifies size of buffer
);
Parameters

lpLocalPath

Points to a null-terminated string that is a drive-based path for a network resource.

For example, if drive H has been mapped to a network drive share, and the network resource of interest is a file named SAMPLE.DOC in the directory \WIN32\EXAMPLES on that share, the drive-based path is H:\WIN32\EXAMPLES\SAMPLE.DOC.

dwInfoLevel

Specifies the type of data structure that the function will store in the buffer pointed to by lpBuffer. This parameter can be one of the following values:

Value	Meaning
UNIVERSAL_NAME_INFO_LEVEL	The function will store a UNIVERSAL_NAME_INFO data structure in the buffer.
REMOTE_NAME_INFO_LEVEL_	The function will store a REMOTE_NAME_INFO data structure in the buffer.
The UNIVERSAL_NAME_INFO data structure points to a Universal Naming Convention (UNC) name string.

The REMOTE_NAME_INFO data structure points to a UNC name string and two additional connection information strings.

lpBuffer

Points to a buffer that receives the type of data structure specified by the dwInfoLevel parameter.

lpBufferSize

Points to a variable that specifies the size in bytes of the buffer pointed to by lpBuffer.

If the function succeeds, it sets the variable pointed to by lpBufferSize to the size in bytes of the data structure stored in the buffer. If the function fails because the buffer is too small, indicated by the ERROR_MORE_DATA error code, it sets the variable pointed to by lpBufferSize to the required buffer size.

Return Value

If the function succeeds, the return value is NO_ERROR.

If the function fails, the return value is an error code. To get extended error information, call GetLastError. GetLastError may return one of the following error codes:

Value	Meaning
ERROR_BAD_DEVICE	The string pointed to by lpLocalPath is invalid.
ERROR_CONNECTION_UNAVAIL	There is no current connection to the remote device, but there is a remembered (persistent) connection to it.
ERROR_EXTENDED_ERROR	A network-specific error occurred. Use the WNetGetLastError function to obtain a description of the error.
ERROR_MORE_DATA	The buffer pointed to by lpBuffer is too small. The function sets the variable pointed to by lpBufferSize to the required buffer size.
ERROR_NOT_SUPPORTED	The dwInfoLevel parameter was set to UNIVERSAL_NAME_INFO_LEVEL, but the network provider does not support UNC  names. This function is not supported by any of the network providers.
ERROR_NO_NET_OR_BAD_PATH	None of the providers recognized this local name as having a connection. However, the network is not available for at least one provider to whom the connection may belong.
ERROR_NO_NETWORK	There is no network present.
ERROR_NOT_CONNECTED	The device specified by lpLocalPath is not redirected.
Remarks

A universal form of a local drive-based path identifies a network resource in an unambiguous, computer-independent manner. The name can then be passed to processes on other computers, allowing those processes to obtain access to the resource.

The WNetGetUniversalName function currently supports one universal name form: universal naming convention (UNC) names, which look like the following:

\\servername\sharename\path\file

Using the example from the preceding description of the lpLocalPath parameter, if the shared network drive is on a server named COOLSERVER, and the share name is HOTSHARE, the UNC name for the network resource whose drive-based name is H:\WIN32\EXAMPLES\SAMPLE.DOC would be

\\coolserver\hotshare\win32\examples\sample.doc

The UNIVERSAL_NAME_INFO data structure contains a pointer to a UNC name string. The REMOTE_NAME_INFO data structure contains a pointer to a UNC name string. It also includes pointers to two other useful strings. A process can pass the REMOTE_NAME_INFO structure's lpszConnectionInfo member into the WNetAddConnection2 function to connect a local device to the network resource, and then append the string pointed to by the lpszRemainingPath member to the local device string. The resulting string can be passed to Win32 functions that use a drive-based path.

See Also

REMOTE_NAME_INFO, UNIVERSAL_NAME_INFO, WNetAddConnection2, WNetGetLastError


WNetGetUser
 WNetGetUser  QuickInfo  Overview  Group

The WNetGetUser function retrieves the current default user name or the user name used to establish a network connection.

DWORD WNetGetUser(

LPTSTR  lpszLocalName,	// address of local name to get user name for
LPTSTR  lpszUserName,	// address of buffer for user name
LPDWORD  lpcchBuffer	// address of buffer size variable
);
Parameters

lpszLocalName

Points to a null-terminated string that specifies either the name of the local device to return the user name for or the name of a network that the user has made a connection to.

If this parameter is NULL, Windows returns the name of the current user for the process.

If this parameter is a network name and the user is connected to that resource using different names, the network provider may not be able to resolve which user name to return. In this case, the provider may make an arbitrary choice from the possible user names.

lpszUserName

Points to a buffer that receives the null-terminated user name.

lpcchBuffer

Points to a variable that specifies the size, in characters, of the buffer pointed to by lpszUserName. If the call fails because the buffer is not big enough, this variable contains the required buffer size.

Return Value

If the function succeeds, the return value is NO_ERROR.

If the function fails, the return value is an error code. To get extended error information, call GetLastError. GetLastError may return one of the following error codes:

Value	Meaning
ERROR_NOT_CONNECTED	The device specified by lpszLocalName is not a redirected device or a connected network name.
ERROR_MORE_DATA	The buffer is too small.
ERROR_NO_NETWORK	No network is present.
ERROR_EXTENDED_ERROR	A network-specific error occurred. To get a description of the error, use the WNetGetLastError function.
ERROR_NO_NET_OR_BAD_PATH	None of the providers recognized this local name as having a connection. However, the network is not available for at least one provider to whom the connection may belong.
The function returns error codes for compatibility with Windows version 3.1. For compatibility with the Win32 API, the function also sets the error code value returned by GetLastError.

See Also

WNetGetConnection, WNetGetLastError


WNetOpenEnum
 WNetOpenEnum  QuickInfo  Overview  Group

The WNetOpenEnum function starts an enumeration of network resources or existing connections.

DWORD WNetOpenEnum(

DWORD  fdwScope,	// scope of enumeration
DWORD  fdwType,	// resource types to list
DWORD  fdwUsage,	// resource usage to list
LPNETRESOURCE  lpNetResource,	// address of resource structure
LPHANDLE  lphEnum	// address of enumeration handle buffer
);
Parameters

fdwScope

Specifies the scope of the enumeration. This parameter can be one of the following values:

Value	Meaning
RESOURCE_CONNECTED	All currently connected resources (the fdwUsage parameter is ignored).
RESOURCE_GLOBALNET	All resources on the network.
RESOURCE_REMEMBERED	All remembered (persistent) connections (fdwUsage is ignored).
fdwType

Specifies the resource types to enumerate. This parameter can be a combination of the following values:

Value	Meaning
RESOURCETYPE_ANY	All resources (this value cannot be combined with RESOURCETYPE_DISK or RESOURCETYPE_PRINT).
RESOURCETYPE_DISK	All disk resources.
RESOURCETYPE_PRINT	All print resources.
If a network provider cannot distinguish between print and disk resources, it may enumerate all resources.

fdwUsage

Specifies the resource usage to be enumerated. This parameter can be a combination of the following values:

Value	Meaning
0	All resources
RESOURCEUSAGE_CONNECTABLE	All connectable resources
RESOURCEUSAGE_CONTAINER	All container resources
This parameter is ignored if the fdwScope parameter is not RESOURCE_GLOBALNET.

lpNetResource

Points to a NETRESOURCE structure specifying the container to enumerate.

If this parameter is NULL, the root of the network is assumed. Windows organizes a network as a hierarchy; the root is the topmost container in the network. For more information about the Windows network functions, see Networks.

If this parameter is not NULL, it must point to a NETRESOURCE structure. This structure can be filled in by the application or be returned by a call to the WNetEnumResource function. The NETRESOURCE structure must specify a container resource; that is, the RESOURCEUSAGE_CONTAINER value must be specified in the dwUsage member.

To enumerate all network resources, an application can begin the enumeration by calling WNetOpenEnum with lpNetResource set to NULL and then use the returned handle with WNetEnumResource to enumerate resources. If one of the resources in the NETRESOURCE array returned by the WNetEnumResource function is a container resource, WNetOpenEnum can be used to open the resource for further enumeration.

If the fdwScope parameter is not RESOURCE_GLOBALNET, this parameter must be NULL.

lphEnum

Points to a variable filled with an enumeration handle that can be used in a subsequent call to WNetEnumResource.

Return Value

If the function succeeds, the return value is NO_ERROR.

If the function fails, the return value is an error code. To get extended error information, call GetLastError. GetLastError may return one of the following error codes:

Value	Meaning
ERROR_NOT_CONTAINER	The lpNetResource parameter does not point to a container.
ERROR_INVALID_PARAMETER	Either the fdwScope or fdwType parameter is invalid, or there is a bad combination of parameters.
ERROR_NO_NETWORK	No network is present.
ERROR_EXTENDED_ERROR	A network-specific error occurred. To get a description of the error, use the WNetGetLastError function.
The function returns error codes for compatibility with Windows version 3.1. For compatibility with Windows NT, the function also sets the error code value returned by GetLastError.

Remarks

The WNetOpenEnum function is used to begin enumeration of the resources in a single container. The following examples show the hierarchical structure of a Microsoft LAN Manager network and a Novell Netware network:

LanMan (container, in this case the provider)

  ACCOUNTING (container, in this case the domain)

    \\ACCTSPAY (container, in this case the server)

      PAYFILES (disk)

      LASERJET (print)

Netware (container, in this case the provider)

  MARKETING (container, in this case the server)

    SYS (disk, first one on any Netware server)

    ANOTHERVOLUME (disk)

    LASERJET (print)

See Also

NETRESOURCE, WNetCloseEnum, WNetEnumResource, WNetGetLastError


WriteConsole
 WriteConsole  QuickInfo  Overview  Group

The WriteConsole function writes a character string to a console screen buffer beginning at the current cursor location.

BOOL WriteConsole(

HANDLE  hConsoleOutput,	// handle of a console screen buffer
CONST VOID  *lpvBuffer,	// address of buffer to write from
DWORD  cchToWrite,	// number of characters to write
LPDWORD  lpcchWritten,	// address of number of characters written
LPVOID  lpvReserved	// reserved
);
Parameters

hConsoleOutput

Identifies the console screen buffer to be written to. The handle must have GENERIC_WRITE access.

lpvBuffer

Points to a buffer that contains characters to be written to the screen buffer.

cchToWrite

Specifies the number of characters to write.

lpcchWritten

Points to a 32-bit variable that receives the number of characters actually written.

lpvReserved

Reserved; must be NULL.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

WriteConsole writes characters to a console screen buffer. It behaves like the WriteFile function, except it can write in either Unicode (wide-character) or ANSI mode. To create an application that maintains a single set of sources compatible with both modes, use WriteConsole rather than WriteFile. Although WriteConsole can be used only with a console screen buffer handle, WriteFile can be used with other handles (such as files or pipes). WriteConsole fails if used with a standard handle that has been redirected to be something other than a console handle.

Although an application can use WriteConsole in ANSI mode to write ANSI characters, consoles do not support ANSI escape sequences. However, some Win32 functions provide equivalent functionality: for example, SetCursorPos, SetConsoleTextAttribute, and GetConsoleCursorInfo.

WriteConsole writes characters to the screen buffer at the current cursor position. The cursor position advances as characters are written. The SetConsoleCursorPosition function sets the current cursor position.

Characters are written using the foreground and background color attributes associated with the screen buffer. The SetConsoleTextAttribute function changes these colors. To determine the current color attributes and the current cursor position, use GetConsoleScreenBufferInfo.

All of the input modes that affect the behavior of WriteFile have the same effect on WriteConsole. To retrieve and set the output modes of a console screen buffer, use the GetConsoleMode and SetConsoleMode functions.

See Also

GetConsoleCursorInfo, GetConsoleMode, GetConsoleScreenBufferInfo, ReadConsole, SetConsoleCursorPosition, SetConsoleMode, SetConsoleTextAttribute, SetCursorPos, WriteFile


WriteConsoleInput
 WriteConsoleInput  QuickInfo  Overview  Group

The WriteConsoleInput function writes data directly to the console input buffer.

BOOL WriteConsoleInput(

HANDLE  hConsoleInput,	// handle of a console input buffer
PINPUT_RECORD  pirBuffer,	// address of the buffer for write data
DWORD  cInRecords,	// number of records to write
LPDWORD  lpcWritten	// address of number of records written
);
Parameters

hConsoleInput

Identifies the input buffer. The handle must have GENERIC_WRITE access.

pirBuffer

Points to an INPUT_RECORD buffer containing data to be written to the input buffer.

cInRecords

Specifies the number of input records to be written.

lpcWritten

Points to a 32-bit variable that receives the number of input records actually written.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

WriteConsoleInput places input records into the input buffer behind any pending events in the buffer. The input buffer grows dynamically, if necessary, to hold as many events as are written.

See Also

INPUT_RECORD, PeekConsoleInput, ReadConsoleInput


WriteConsoleOutput
 WriteConsoleOutput  QuickInfo  Overview  Group

The WriteConsoleOutput function writes character and color attribute data to a specified rectangular block of character cells in a console screen buffer. The data to be written is taken from a correspondingly sized rectangular block at a specified location in the source buffer.

BOOL WriteConsoleOutput(

HANDLE  hConsoleOutput,	// handle of a console screen buffer
PCHAR_INFO  pchiSrcBuffer,	// address of buffer with data to write
COORD  coordSrcBufferSize,	// column-row size of source buffer
COORD  coordSrcBufferCoord,	// upper-left cell to write from
PSMALL_RECT  psrctDestRect	// address of rectangle to write to
);
Parameters

hConsoleOutput

Identifies the screen buffer. The handle must have GENERIC_WRITE access.

pchiSrcBuffer

Points to a source buffer that contains the data to be written to the screen buffer. This pointer is treated as the origin of a two-dimensional array of CHAR_INFO structures whose size is specified by the coordSrcBufferSize parameter.

coordSrcBufferSize

Specifies the size, in character cells, of the buffer pointed to by the pchiSrcBuffer parameter. The X member of the COORD structure is the number of columns; the Y member is the number of rows.

coordSrcBufferCoord

Specifies the coordinates of the upper-left cell in the buffer pointed to by the pchiSrcBuffer parameter to write data from. The X member of the COORD structure is the column, and the Y member is the row.

psrctDestRect

Points to a SMALL_RECT structure. On input, the structure members specify the upper-left and lower-right coordinates of the screen buffer rectangle to write to. On output, the structure members specify the actual rectangle that was written to.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

WriteConsoleOutput treats the source buffer and the destination screen buffer as two-dimensional arrays (columns and rows of character cells). The rectangle pointed to by the psrctDestRect parameter specifies the size and location of the block to be written to in the screen buffer. A rectangle of the same size is located with its upper-left cell at the coordinates of the coordSrcBufferCoord parameter in the pchiSrcBuffer array. Data from the cells that are in the intersection of this rectangle and the source buffer rectangle (whose dimensions are specified by the coordSrcBufferSize parameter) is written to the destination rectangle.

Cells in the destination rectangle whose corresponding source location are outside the boundaries of the source buffer rectangle are left unaffected by the write operation. In other words, these are the cells for which no data is available to be written.

Before WriteConsoleOutput returns, it sets the members of psrctDestRect to the actual screen buffer rectangle affected by the write operation. This rectangle reflects the cells in the destination rectangle for which there existed a corresponding cell in the source buffer, because WriteConsoleOutput clips the dimensions of the destination rectangle to the boundaries of the screen buffer.

If the rectangle specified by psrctDestRect lies completely outside the boundaries of the screen buffer, or if the corresponding rectangle is positioned completely outside the boundaries of the source buffer, no data is written. In this case, the function returns with the members of the structure pointed to by the psrctDestRect parameter set such that the Right member is less than the Left, or the Bottom member is less than the Top. To determine the size of the screen buffer, use the GetConsoleScreenBufferInfo function.

WriteConsoleOutput has no effect on the cursor position.

See Also

CHAR_INFO, COORD, GetConsoleScreenBufferInfo, ReadConsoleOutput, ReadConsoleOutputAttribute, ReadConsoleOutputCharacter, SMALL_RECT, WriteConsoleOutputAttribute, WriteConsoleOutputCharacter


WriteConsoleOutputAttribute
 WriteConsoleOutputAttribute  QuickInfo  Overview  Group

The WriteConsoleOutputAttribute function copies a number of foreground and background color attributes to consecutive cells of a console screen buffer, beginning at a specified location.

BOOL WriteConsoleOutputAttribute(

HANDLE  hConsoleOutput,	// handle of a console screen buffer
LPWORD  lpwAttribute,	// address of buffer to write attributes from
DWORD  cWriteCells,	// number of character cells to write to
COORD  coordWrite,	// coordinates of first cell to write to
LPDWORD  lpcWritten	// address of number of cells written to
);
Parameters

hConsoleOutput

Identifies the screen buffer. The handle must have GENERIC_WRITE access.

lpwAttribute

Points to a buffer that contains the attributes to write to the screen buffer.

cWriteCells

Specifies the number of screen buffer character cells to write to.

coordWrite

Specifies the column and row coordinates of the first cell in the screen buffer to write to.

lpcWritten

Points to a 32-bit variable that receives the number of attributes actually written to the screen buffer.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

If the number of attributes to be written to extends beyond the end of the specified row in the screen buffer, attributes are written to the next row. If the number of attributes to be written to extends beyond the end of the screen buffer, the attributes are written up to the end of the screen buffer.

The character values at the positions written to are not changed.

Each attribute specifies the foreground (text) and background colors in which that character cell is drawn. The attribute values are some combination of the following values: FOREGROUND_BLUE, FOREGROUND_GREEN, FOREGROUND_RED, FOREGROUND_INTENSITY, BACKGROUND_BLUE, BACKGROUND_GREEN, BACKGROUND_RED, and BACKGROUND_INTENSITY. For example, the following combination of values produces red text on a white background:

FOREGROUND_RED | BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE

See Also

ReadConsoleOutput, ReadConsoleOutputAttribute, ReadConsoleOutputCharacter, WriteConsoleOutput, WriteConsoleOutputCharacter


WriteConsoleOutputCharacter
 WriteConsoleOutputCharacter  QuickInfo  Overview  Group

The WriteConsoleOutputCharacter function copies a number of characters to consecutive cells of a console screen buffer, beginning at a specified location.

BOOL WriteConsoleOutputCharacter(

HANDLE  hConsoleOutput,	// handle of a console screen buffer
LPTSTR  lpWriteBuffer,	// address of buffer to write characters from
DWORD  cchWrite,	// number of character cells to write to
COORD  coordWriteCoord,	// coordinates of first cell to write to
LPDWORD  lpcWritten	// address of number of cells written to
);
Parameters

hConsoleOutput

Identifies the screen buffer. The handle must have GENERIC_WRITE access.

lpWriteBuffer

Points to a buffer that contains the characters to write to the screen buffer.

cchWrite

Specifies the number of screen buffer character cells to write to.

coordWriteCoord

Specifies the column and row coordinates of the first cell in the screen buffer to write to.

lpcWritten

Points to a 32-bit variable that receives the number of characters actually written.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

If the number of characters to be written to extends beyond the end of the specified row in the screen buffer, characters are written to the next row. If the number of characters to be written to extends beyond the end of the screen buffer, characters are written up to the end of the screen buffer.

The attribute values at the positions written to are not changed.

See Also

ReadConsoleOutput, ReadConsoleOutputAttribute, ReadConsoleOutputCharacter, WriteConsoleOutput, WriteConsoleOutputAttribute


WriteFile
 WriteFile  QuickInfo  Overview  Group

The WriteFile function writes data to a file and is designed for both synchronous and asynchronous operation. The function starts writing data to the file at the position indicated by the file pointer. After the write operation has been completed, the file pointer is adjusted by the number of bytes actually written, except when the file is opened with FILE_FLAG_OVERLAPPED. If the file handle was created for overlapped input and output (I/O), the application must adjust the position of the file pointer after the write operation is finished.

BOOL WriteFile(

HANDLE  hFile,	// handle of file to write to
LPCVOID  lpBuffer,	// address of data to write to file
DWORD  nNumberOfBytesToWrite,	// number of bytes to write
LPDWORD  lpNumberOfBytesWritten,	// address of number of bytes written
LPOVERLAPPED  lpOverlapped	// addr. of structure needed for overlapped I/O
);
Parameters

hFile

Identifies the file to be written to. The file handle must have been created with GENERIC_WRITE access to the file.

Windows NT

For asynchronous write operations, hFile can be any handle opened with the FILE_FLAG_OVERLAPPED flag by the CreateFile function, or a socket handle returned by the socket or accept functions.

Windows 95

For asynchronous write operations, hFile can be a communications resource, mailslot, or named pipe handle opened with the FILE_FLAG_OVERLAPPED flag by CreateFile, or a socket handle returned by the socket or accept functions. Windows 95 does not support asynchronous write operations on disk files.

lpBuffer

Points to the buffer containing the data to be written to the file.

nNumberOfBytesToWrite

Specifies the number of bytes to write to the file.

Unlike the MS-DOS operating system, Windows NT interprets a value of zero as specifying a null write operation. A null write operation does not write any bytes but does cause the time stamp to change.

Named pipe write operations across a network are limited to 65535 bytes.

lpNumberOfBytesWritten

Points to the number of bytes written by this function call. WriteFile sets this value to zero before doing any work or error checking.

lpOverlapped

Points to an OVERLAPPED structure. This structure is required if hFile was opened with FILE_FLAG_OVERLAPPED.

This parameter should not be NULL if hFile was opened with FILE_FLAG_OVERLAPPED. It should point to a valid OVERLAPPED structure. If hFile was created with FILE_FLAG_OVERLAPPED and lpOverlapped is NULL, the function fails in unpredictable ways.

If hFile was not created with FILE_FLAG_OVERLAPPED and lpOverlapped is NULL, the write operation starts at the current file position and WriteFile does not return until the operation has been completed.

If hFile was created with FILE_FLAG_OVERLAPPED and lpOverlapped is not NULL, the write operation starts at the offset specified in the OVERLAPPED structure and WriteFile may return before the write operation has been completed. In this case, WriteFile returns FALSE and the GetLastError function returns ERROR_IO_PENDING. This allows the calling process to continue processing while the write operation is being completed. The event specified in the OVERLAPPED structure is set to the signaled state upon completion of the write operation.

If hFile was not created with FILE_FLAG_OVERLAPPED and lpOverlapped is not NULL, the write operation starts at the offset specified in the OVERLAPPED structure and WriteFile does not return until the write operation has been completed.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

If part of the file is locked by another process and the write operation overlaps the locked portion, this function fails.

Applications must not read from nor write to the input buffer that a read operation is using until the read operation completes. A premature access to the input buffer may lead to corruption of the data read into that buffer.

Characters can be written to the screen buffer using WriteFile with a handle to console output. The exact behavior of the function is determined by the console mode. The data is written to the current cursor position. The cursor position is updated after the write operation.

Unlike the MS-DOS operating system, Windows NT interprets zero bytes to write as specifying a null write operation and WriteFile does not truncate or extend the file. To truncate or extend a file, use the SetEndOfFile function.

When writing to a nonblocking, byte-mode pipe handle with insufficient buffer space, WriteFile returns TRUE with *lpNumberOfBytesWritten < nNumberOfBytesToWrite.

When an application uses the WriteFile function to write to a pipe, the write operation may not finish if the pipe buffer is full. The write operation is completed when a read operation (using the ReadFile function) makes more buffer space available.

If the anonymous read pipe handle has been closed and WriteFile attempts to write using the corresponding anonymous write pipe handle, the function returns FALSE and GetLastError returns ERROR_BROKEN_PIPE.

The WriteFile function may fail with ERROR_INVALID_USER_BUFFER or ERROR_NOT_ENOUGH_MEMORY whenever there are too many outstanding asynchronous I/O requests.

If hFile is a handle to a named pipe, the Offset and OffsetHigh members of the OVERLAPPED structure pointed to by lpOverlapped must be zero, or the function will fail.

See Also

CreateFile, GetLastError, GetOverlappedResult, OVERLAPPED, ReadFile, SetEndOfFile, WriteFileEx


WriteFileEx
 WriteFileEx  QuickInfo  Overview  Group

The WriteFileEx function writes data to a file. It is designed solely for asynchronous operation, unlike WriteFile, which is designed for both synchronous and asynchronous operation.

WriteFileEx reports its completion status asynchronously, calling a specified completion routine when writing is completed and the calling thread is in an alertable wait state.

BOOL WriteFileEx(

HANDLE  hFile;	// handle to output file
LPCVOID  lpBuffer;	// pointer to input buffer
DWORD  nNumberOfBytesToWrite;	// number of bytes to write
LPOVERLAPPED  lpOverlapped;	// pointer to async. i/o data
LPOVERLAPPED_COMPLETION_ROUTINE  lpCompletionRoutine;	// ptr. to completion routine
);
Parameters

hFile

An open handle that specifies the file entity to be written to. This file handle must have been created with the FILE_FLAG_OVERLAPPED flag and with GENERIC_WRITE access to the file.

Windows NT : hFile can be any handle opened with the FILE_FLAG_OVERLAPPED flag by the CreateFile function, or a socket handle returned by the socket or accept functions.

Windows 95 : hFile can be a communications resource, mailslot, or named pipe handle opened with the FILE_FLAG_OVERLAPPED flag by CreateFile, or a socket handle returned by the socket or accept functions. Windows 95 does not support asynchronous operations on disk files.

lpBuffer

Points to the buffer containing the data to be written to the file.

This buffer must remain valid for the duration of the write operation. The caller must not use this buffer until the write operation is completed.

nNumberOfBytesToWrite

Specifies the number of bytes to write to the file.

If nNumberOfBtyesToWrite is zero, this function does nothing; in particular, it does not truncate the file. For additional discussion, see the following Remarks section.

lpOverlapped

Points to an OVERLAPPED data structure that supplies data to be used during the overlapped (asynchronous) write operation.

For files that support byte offsets, you must specify a byte offset at which to start writing to the file. You specify this offset by setting the Offset and OffsetHigh members of the OVERLAPPED structure. For files that do not support byte offsets — named pipes, for example — you must set Offset and OffsetHigh to zero, or WriteFileEx fails.

The WriteFileEx function ignores the OVERLAPPED structure's hEvent member. An application is free to use that member for its own purposes in the context of a WriteFileEx call. WriteFileEx signals completion of its writing operation by calling, or queueing a call to, the completion routine pointed to by lpCompletionRoutine, so it does not need an event handle.

The WriteFileEx function does use the Internal and InternalHigh members of the OVERLAPPED structure. You should not change the value of these members.

The OVERLAPPED data structure must remain valid for the duration of the write operation. It should not be a variable that can go out of scope while the write operation is pending completion.

lpCompletionRoutine

Points to a completion routine to be called when the write operation has been completed and the calling thread is in an alertable wait state. For more information about this completion routine, see FileIOCompletionRoutine.

Return Value

If the function succeeds, the return value is TRUE.

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

If the WriteFileEx function succeeds, the calling thread has an asynchronous I/O (input/output) operation pending: the overlapped write operation to the file. When this I/O operation finishes, and the calling thread is blocked in an alertable wait state, the operating system calls the function pointed to by lpCompletionRoutine, and the wait completes with a return code of WAIT_IO_COMPLETION.

If the function succeeds and the file-writing operation finishes, but the calling thread is not in an alertable wait state, the system queues the call to *lpCompletionRoutine, holding the call until the calling thread enters an alertable wait state. See Synchronization for more information about alertable wait states and overlapped input/output operations.

Remarks

If part of the output file is locked by another process, and the specified write operation overlaps the locked portion, the WriteFileEx function fails.

Applications must not read from nor write to the input buffer that a read operation is using until the read operation completes. A premature access to the input buffer may lead to corruption of the data read into that buffer.

The WriteFileEx function may fail, returning the messages ERROR_INVALID_USER_BUFFER or ERROR_NOT_ENOUGH_MEMORY if there are too many outstanding asynchronous I/O requests.

If hFile is a handle to a named pipe, or other file entity that doesn't support byte offsets, the Offset and OffsetHigh members of the OVERLAPPED structure pointed to by lpOverlapped must be zero, or the WriteFileEx function fails.

An application uses the WaitForSingleObjectEx, WaitForMultipleObjectsEx, and SleepEx functions to enter an alertable wait state. Refer to those functions and the overview Synchronization for more information about alertable wait states and overlapped input/output operations.

Windows 95: On this platform, neither WriteFileEx nor ReadFileEx can be used by the comm ports to communicate. However, you can use WriteFile and ReadFile to perform asynchronous communication.

See Also

CreateFile, FileIOCompletionRoutine, OVERLAPPED, ReadFileEx, SetEndOfFile, SleepEx, WaitForMultipleObjectsEx, WaitForSingleObjectEx, WriteFile


WritePrinter
 WritePrinter  QuickInfo  Overview  Group

The WritePrinter function informs the print spooler that data should be written to the specified printer.

BOOL WritePrinter(

HANDLE  hPrinter,	// handle of printer object
LPVOID  pBuf,	// address of array that contains printer data
DWORD  cbBuf,	// size, in bytes, of array
LPDWORD  lpdwWritten	// addr. of variable with count of bytes written
);
Parameters

hPrinter

Identifies the printer.

pBuf

Points to an array of bytes that contains the data that should be written to the printer.

cbBuf

Specifies the size, in bytes, of the array.

lpdwWritten

Points to a value that specifies the number of bytes of data that were written to the printer.

Return Value

If the function succeeds, the return value is TRUE.

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

See Also

OpenPrinter


WritePrivateProfileSection
 WritePrivateProfileSection  QuickInfo

The WritePrivateProfileSection function replaces the keys and values under the specified section in an initialization file.

This function is provided for compatibility with 16-bit Windows-based applications. Win32-based applications should store initialization information in the registry.

BOOL WritePrivateProfileSection(

LPCTSTR  lpszSection,	// address of string with section name
LPCTSTR  lpszKeysAndValues,	// address of string with data
LPCTSTR  lpszFile	// address of string with filename
);
Parameters

lpszSection

Points to a null-terminated string containing the name of the section in which data is written. This section name is typically the name of the calling application.

lpszKeysAndValues

Points to a buffer containing the new key names and associated values that are written to the named section.

lpszFile

Points to a null-terminated string containing the name of the initialization file. If this parameter does not contain a full path for the file, the function searches the Windows directory for the file. If the file does not exist and lpszFile does not contain a full path, the function creates the file in the Windows directory. The function does not create a file if lpszFile contains the full path and filename of a file that does not exist.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

The data in the buffer pointed to by the lpszKeysAndValues parameter consists of one or more null-terminated strings, followed by a final null character. Each string has the following form:

key=string

The WritePrivateProfileSection function is not case-sensitive; the string pointed to by the lpszSection parameter can be a combination of uppercase and lowercase letters.

If no section name matches the string pointed to by the lpszSection parameter, WritePrivateProfileSection creates the section at the end of the specified initialization file and initializes the new section with the specified key name and value pairs.

WritePrivateProfileSection deletes the existing keys and values for the named section and inserts the key names and values in the buffer pointed to by the lpszKeysAndValues parameter. The function does not attempt to correlate old and new key names; if the new names appear in a different order from the old names, any comments associated with preexisting keys and values in the initialization file will probably be associated with incorrect keys and values.

This operation is atomic; no operations that read from or write to the specified initialization file are allowed while the information is being written.

Windows 95

Windows 95 keeps a cached version of WIN.INI to improve performance. If all three parameters are NULL, the function flushes the cache. The function always returns FALSE after flushing the cache, regardless of whether the flush succeeds or fails.

Windows NT

Windows NT maps most .INI file references to the registry, using the mapping defined under the following registry key:

HKEY_LOCAL_MACHINE\Software\Microsoft\
        Windows NT\CurrentVersion\IniFileMapping

This mapping is likely if an application modifies system-component initialization files, such as as CONTROL.INI, SYSTEM.INI, and WINFILE.INI. In this case, the WritePrivateProfileSection function writes information to the registry, not to the initialization file; the change in the storage location has no effect on the function's behavior.

See Also

GetPrivateProfileSection, RegCreateKeyEx, RegSetValueEx, WriteProfileSection


WritePrivateProfileString
 WritePrivateProfileString  QuickInfo

The WritePrivateProfileString function copies a string into the specified section of the specified initialization file.

This function is provided for compatibility with 16-bit Windows-based applications. WIn32-based applications should store initialization information in the registry.

BOOL WritePrivateProfileString(

LPCTSTR  lpszSection,	// address of section name
LPCTSTR  lpszKey,	// address of key name
LPCTSTR  lpszString,	// address of string to add
LPCTSTR  lpszFile	// address of initialization filename
);
Parameters

lpszSection

Points to a null-terminated string containing the name of the section to which the string will be copied. If the section does not exist, it is created. The name of the section is case-independent; the string can be any combination of uppercase and lowercase letters.

lpszKey

Points to the null-terminated string containing the name of the key to be associated with a string. If the key does not exist in the specified section, it is created. If this parameter is NULL, the entire section, including all entries within the section, is deleted.

lpszString

Points to a null-terminated string to be written to the file. If this parameter is NULL, the key pointed to by the lpszKey parameter is deleted.

Windows 95: This platform does not support the use of the TAB (\t) character as part of this parameter.

lpszFile

Points to a null-terminated string that names the initialization file.

Return Value

If the function successfully copies the string to the initialization file, the return value is TRUE.

If the function fails, or if it flushes the cached version of the most recently accessed initialization file, the return value is FALSE. To get extended error information, call GetLastError.

Remarks

Windows 95

Windows 95 keeps a cached version of WIN.INI to improve performance. If all three parameters are NULL, the function flushes the cache. The function always returns FALSE after flushing the cache, regardless of whether the flush succeeds or fails.

A section in the initialization file must have the following form:

[section]
key=string
      .
      .
      .

If the lpszFile parameter does not contain a full path and filename for the file, WritePrivateProfileString searches the Windows directory for the file. If the file does not exist, this function creates the file in the Windows directory.

If lpszFile contains a full path and filename and the file does not exist, WriteProfileString creates the file. The specified directory must already exist.

Windows NT

Windows NT maps most .INI file references to the registry, using the mapping defined under the following registry key:

HKEY_LOCAL_MACHINE\Software\Microsoft\
        Windows NT\CurrentVersion\IniFileMapping

Windows NT keeps a cache for the IniFleMapping registry key. Calling WritePrivateProfileStringW with the value of all arguments set to NULL will cause Windows NT to refresh its cache of the IniFileMappingKey for the specified .INI file.

An application using the WritePrivateProfileStringW function to enter .INI file information into the registry should follow these guidelines:

•	Ensure that no .INI file of the specified name exists on the system.

•	Ensure that there is a key entry in the registry that specifies the .INI file. This entry should be under the path HKEY_LOCAL_MACHINE\SOFTWARE \Microsoft\Windows NT\CurrentVersion\IniFileMapping.

•	Specify a value for that .INI file key entry that specifies a section. That is to say, an application must specify a section name, as it would appear within an .INI file or registry entry. Here is an example: [My Section].

•	For system files, specify SYS for an added value.

•	For application files, specify USR within the added value. Here is an example: "My Section: USR: App Name\Section". And, since USR indicates a mapping under HKEY_CURRENT_USER, the application should also create a key under HKEY_CURRENT_USER that specifies the application name listed in the added value. For the example just given, that would be "App Name".

•	After following the preceding steps, an application setup program should call WritePrivateProfileStringW with the first three parameters set to NULL, and the fourth parameter set to the INI filename. For example:

WritePrivateProfileStringW( NULL, NULL, NULL, L"appname.ini" );

Such a call causes the mapping of an .INI file to the registry to take effect before the next system reboot. The operating system re-reads the mapping information into shared memory. A user will not have to reboot their computer after installing an application in order to have future invocations of the application see the mapping of the .INI file to the registry.

The following sample code illustrates the preceding guidelines and is based on several assumptions:

•	There is an application named "App Name."

•	That application uses an .INI file named "appname.ini."

•	There is a section in the .INI file that we want to look like this:

[Section1]

  FirstKey = It all worked out okay.

  SecondKey = By golly, it works.

  ThirdKey = Another test.

•	The user will not have to reboot the system in order to have future invocations of the application see the mapping of the .INI file to the registry.

Here is the sample code :

// include files

#include <stdio.h>

#include <windows.h>

// a main function

main()

{

  // local variables

  CHAR inBuf[80];

  HKEY  hKey1, hKey2;

  DWORD  dwDisposition;

  LONG   lRetCode;

  // try to create the .INI file key

  lRetCode = RegCreateKeyEx ( HKEY_LOCAL_MACHINE,

                              "SOFTWARE\\Microsoft\\Windows NT

                               \\CurrentVersion\\IniFileMapping\\appname.ini",

                              0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE,

                              NULL, &hKey1,

                              &dwDisposition);

  // if we failed, note it, and leave

  if (lRetCode != ERROR_SUCCESS){

    printf ("Error in creating appname.ini key\n");

    return (0) ;

    }

  // try to set a section value

  lRetCode = RegSetValueEx ( hKey1,

                             "Section1",

                             0,

                             REG_SZ,

                             "USR:App Name\\Section1",

                             20);

  // if we failed, note it, and leave

  if (lRetCode != ERROR_SUCCESS) {

    printf ( "Error in setting Section1 value\n");

    return (0) ;

    }

  // try to create an App Name key

  lRetCode = RegCreateKeyEx ( HKEY_CURRENT_USER,

                              "App Name",

                              0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE,

                              NULL, &hKey2,

                              &dwDisposition);

  // if we failed, note it, and leave

  if (lRetCode != ERROR_SUCCESS) {

    printf ("Error in creating App Name key\n");

    return (0) ;

    }

  // force the operating system to re-read the mapping into shared memory

  //    so that future invocations of the application will see it

  //    without the user having to reboot the system

  WritePrivateProfileStringW( NULL, NULL, NULL, L"appname.ini" );

  // if we get this far, all has gone well

  // let's write some added values

  WritePrivateProfileString ("Section1", "FirstKey",

                             "It all worked out okay.", "appname.ini");

  WritePrivateProfileString ("Section1", "SecondKey",

                             "By golly, it works.", "appname.ini");

  WritePrivateProfileSection ("Section1", "ThirdKey = Another Test.",

                              "appname.ini");

  // let's test our work

  GetPrivateProfileString ("Section1", "FirstKey",

                           "Bogus Value: Get didn't work", inBuf, 80,

                           "appname.ini");

  printf ("%s", inBuf);

  // okay, we are outta here

  return(0);

}

See Also

GetPrivateProfileString, WriteProfileString


WritePrivateProfileStruct [New - Windows NT]
 WritePrivateProfileStruct  QuickInfo

[New - Windows NT]

The WritePrivateProfileStruct function copies data into the specified key in the given section of an initialization file. As it copies the data, the function calculates a checksum and appends it to the end of the data. The GetPrivateProfileStruct function uses the checksum to ensure the integrity of the data. This function is provided for compatibility with 16-bit Windows-based applications. Win32-based applications should store initialization information in the registry.

BOOL WritePrivateProfileStruct(

LPCTSTR  lpszSection,	// address of section name
LPCTSTR  lpszKey,	// address of key name
LPVOID  lpvStruct,	// address of buffer that contains data to add
UINT  uSizeStruct,	// size, in bytes, of the buffer
LPCTSTR  lpszFile	// address of initialization filename
);
Parameters

lpszSection

Points to a null-terminated string containing the name of the section to which the string will be copied. If the section does not exist, it is created. The name of the section is case independent, the string can be any combination of uppercase and lowercase letters.

lpszKey

Points to the null-terminated string containing the name of the key to be associated with a string. If the key does not exist in the specified section, it is created. If this parameter is NULL, the entire section, including all keys and entries within the section, is deleted.

lpvStruct

Points to a buffer that contains the data to copy. If this parameter is NULL, the given key is deleted.

uSizeStruct

Specifies the size, in bytes, of the buffer pointed to by the lpvStruct parameter.

lpszFile

Points to a null-terminated string that names the initialization file. If this parameter is NULL, the given information is copied into the WIN.INI file.

Return Value

If the function successfully copies the string to the initialization file, the return value is TRUE.

If the function fails, or if it flushes the cached version of the most recently accessed initialization file, the return value is FALSE. To get extended error information, call GetLastError.

Remarks

Windows 95 keeps a cached version of WIN.INI to improve performance. If all three parameters are NULL, the function flushes the cache. The function always returns FALSE after flushing the cache, regardless of whether the flush succeeds or fails.

A section in the initialization file must have the following form:

[section]
key=string
      .
      .
      .

If the lpszFile parameter does not contain a full path and filename for the file, WritePrivateProfileString searches the Windows directory for the file. If the file does not exist, this function creates the file in the Windows directory.

If lpszFile contains a full path and filename and the file does not exist, WriteProfileString creates the file. The specified directory must already exist.

See Also

GetPrivateProfileString, WriteProfileString


WriteProcessMemory
 WriteProcessMemory  QuickInfo  Overview  Group

The WriteProcessMemory function writes memory in a specified process. The entire area to be written to must be accessible, or the operation fails.

BOOL WriteProcessMemory(

HANDLE  hProcess,	// handle of process whose memory is written to
LPVOID  lpBaseAddress,	// address to start writing to
LPVOID  lpBuffer,	// address of buffer to write data to
DWORD  cbWrite,	// number of bytes to write
LPDWORD  lpNumberOfBytesWritten	// actual number of bytes written
);
Parameters

hProcess

Identifies an open handle of a process whose memory is to be written to. The handle must have PROCESS_VM_WRITE and PROCESS_VM_OPERATION access to the process.

lpBaseAddress

Points to the base address in the specified process to be written to. Before any data transfer occurs, the system verifies that all data in the base address and memory of the specified size is accessible for write access. If this is the case, the function proceeds; otherwise, the function fails.

lpBuffer

Points to the buffer that supplies data to be written into the address space of the specified process.

cbWrite

Specifies the requested number of bytes to write into the specified process.

lpNumberOfBytesWritten

Points to the actual number of bytes transferred into the specified process. This parameter is optional. If lpNumberOfBytesWritten is NULL, the parameter is ignored.

Return Value

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. To get extended error information, call GetLastError. The function will fail if the requested write operation crosses into an area of the process that is inaccessible.

Remarks

WriteProcessMemory copies the data from the specified buffer in the current process to the address range of the specified process. Any process that has a handle with PROCESS_VM_WRITE and PROCESS_VM_OPERATION access to the process to be written to can call the function. The process whose address space is being written to is typically, but not necessarily, being debugged.

The entire area to be written to must be accessible. If it is not, the function fails as noted previously.

See Also

ReadProcessMemory


WriteProfileSection
 WriteProfileSection  QuickInfo

The WriteProfileSection function replaces the contents of the specified section in the WIN.INI file with the specified keys and values.

This function is provided for compatibility with 16-bit Windows applications. Win32-based applications should store initialization information in the registry.

BOOL WriteProfileSection(

LPCTSTR  lpszSection,	// address of section name
LPCTSTR  lpszKeysAndValues	// address of buffer with data
);
Parameters

lpszSection

Points to a null-terminated string containing the name of the section in which data is written. This section name is typically the name of the calling application.

lpszKeysAndValues

Points to a buffer containing the new key names and associated values that are written to the named section.

Return Value

If the function succeeds, the return value is TRUE.

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

Remarks

Windows 95

If there is no section in WIN.INI that matches the specified section name, WriteProfileSection creates the section at the end of the file and initializes the new section with the key name and value pairs specified in the lpszKeysAndValues parameter.

Keys and values in the lpszKeysAndValues buffer consist of one or more null-terminated strings, followed by a final null character. Each string has the following form:

key=string

The WriteProfileSection function is not case-sensitive; the strings can be a combination of uppercase and lowercase letters.

WriteProfileSection deletes the existing keys and values for the named section and inserts the key names and values in the buffer pointed to by lpszKeysAndValues. The function does not attempt to correlate old and new key names; if the new names appear in a different order from the old names, any comments associated with preexisting keys and values in the initialization file will probably be associated with incorrect keys and values.

This operation is atomic; no other operations that read from or write to the initialization file are allowed while the information is being written.

Windows NT

Windows NT maps most .INI file references to the registry, using the mapping defined under the following registry key:

HKEY_LOCAL_MACHINE\Software\Microsoft\
        Windows NT\CurrentVersion\IniFileMapping

When the operation has been mapped, the WriteProfileSection function writes information to the registry, not to the initialization file; the change in the storage location has no effect on the function's behavior.

See Also

GetProfileSection, WritePrivateProfileSection


WriteProfileString
 WriteProfileString  QuickInfo

The WriteProfileString function copies a string into the specified section of the WIN.INI file.

This function is provided for compatibility with 16-bit Windows-based applications. Win32-based applications should store initialization information in the registry.

BOOL WriteProfileString(

LPCTSTR  lpszSection,	// address of section name
LPCTSTR  lpszKey,	// address of key name
LPCTSTR  lpszString	// address of string to write
);
Parameters

lpszSection

Points to a null-terminated string that specifies the section to which the string is to be copied. If the section does not exist, it is created. The name of the section is not case-sensitive; the string can be any combination of uppercase and lowercase letters.

lpszKey

Points to a null-terminated string containing the key to be associated with the string. If the key does not exist in the specified section, it is created. If this parameter is NULL, the entire section, including all entries in the section, is deleted.

lpszString

Points to a null-terminated string to be written to the file. If this parameter is NULL, the key pointed to by the lpszKey parameter is deleted.

Windows 95: This platform does not support the use of the TAB (\t) character as part of this parameter.

Return Value

If the function successfully copies the string to the WIN.INI file, the return value is TRUE.

If the function fails, or if it flushes the cached version of WIN.INI, the return value is FALSE. To get extended error information, call GetLastError.

Remarks

Windows 95:

Windows 95 keeps a cached version of WIN.INI to improve performance. If all three parameters are NULL, the function flushes the cache. The function always returns FALSE after flushing the cache, regardless of whether the flush succeeds or fails.

A section in the WIN.INI file must have the following form:

[section]
key=string
    .
    .
    .

Windows NT

Windows NT maps most .INI file references to the registry, using the mapping defined under the following registry key:

HKEY_LOCAL_MACHINE\Software\Microsoft\
        Windows NT\CurrentVersion\IniFileMapping

When the operation has been mapped, the WriteProfileString function writes information to the registry, not to the initialization file; the change in the storage location has no effect on the function's behavior.

See Also

GetProfileString, WritePrivateProfileString


WriteTapemark
 WriteTapemark  QuickInfo  Overview  Group

The WriteTapemark function writes a specified number of filemarks, setmarks, short filemarks, or long filemarks to a tape device. These tapemarks divide a tape partition into smaller areas.

DWORD WriteTapemark(

HANDLE  hDevice,	// handle of open device
DWORD  dwTapemarkType,	// type of tapemarks to write
DWORD  dwTapemarkCount,	// number of tapemarks to write
BOOL  bImmediate	// return after write begins
);
Parameters

hDevice

Identifies the device on which to write tapemarks. This handle is created by using the CreateFile function.

dwTapemarkType

Specifies the type of tapemarks to write. This parameter can be one of the following values:

Value	Description
TAPE_FILEMARKS	Writes the number of filemarks specified by the dwTapemarkCount parameter.
TAPE_LONG_FILEMARKS	Writes the number of long filemarks specified by dwTapemarkCount.
TAPE_SETMARKS	Writes the number of setmarks specified by dwTapemarkCount.
TAPE_SHORT_FILEMARKS	Writes the number of short filemarks specified by dwTapemarkCount.
dwTapemarkCount

Specifies the number of tapemarks to write.

bImmediate

Specifies whether to return as soon as the operation begins. If this parameter is TRUE, the function returns immediately; if it is FALSE, the function does not return until the operation has been completed.

Return Value

If the function succeeds, the return value is NO_ERROR.

If the function fails, the return value is one of the following error codes:

Error	Description
ERROR_BEGINNING_OF_MEDIA	An attempt to access data before the beginning-of-medium marker failed.
ERROR_BUS_RESET	A reset condition was detected on the bus.
ERROR_END_OF_MEDIA	The end-of-tape marker was reached during an operation.
ERROR_FILEMARK_DETECTED	A filemark was reached during an operation.
ERROR_SETMARK_DETECTED	A setmark was reached during an operation.
ERROR_NO_DATA_DETECTED	The end-of-data marker was reached during an operation.
ERROR_PARTITION_FAILURE	The tape could not be partitioned.
ERROR_INVALID_BLOCK_LENGTH	The block size is incorrect on a new tape in a multivolume partition.
ERROR_DEVICE_NOT_PARTITIONED	The partition information could not be found when a tape was being loaded.
ERROR_MEDIA_CHANGED	The tape that was in the drive has been replaced or removed.
ERROR_NO_MEDIA_IN_DRIVE	There is no media in the drive.
ERROR_NOT_SUPPORTED	The tape driver does not support a requested function.
ERROR_UNABLE_TO_LOCK_MEDIA	An attempt to lock the ejection mechanism failed.
ERROR_UNABLE_TO_UNLOAD_MEDIA	An attempt to unload the tape failed.
ERROR_WRITE_PROTECT	The media is write protected.
Remarks

Filemarks, setmarks, short filemarks, and long filemarks are special recorded elements that denote the linear organization of the tape. None of these marks contain user data. Filemarks are the most general marks; setmarks provide a hierarchy not available with filemarks.

A short filemark contains a short erase gap that cannot be overwritten unless the write operation is performed from the beginning of the partition or from an earlier long filemark.

A long filemark contains a long erase gap that allows an application to position the tape at the beginning of the filemark and to overwrite the filemark and the erase gap.

See Also

CreateFile


WSAAsyncGetHostByAddr
 WSAAsyncGetHostByAddr  QuickInfo

The Windows Sockets WSAAsyncGetHostByAddr function gets host information corresponding to an address in an asynchronous fashion.

HANDLE WSAAsyncGetHostByAddr (

HWND hWnd,
unsigned int wMsg,
const char FAR * addr,
int len,
int type,
char FAR * buf,
int buflen
);
Parameters

hWnd

The handle of the window that should receive a message when the asynchronous request completes.

wMsg

The message to be received when the asynchronous request completes.

addr

A pointer to the network address for the host. Host addresses are stored in network byte order.

len

The length of the address, which must be 4 for PF_INET.

type

The type of the address, which must be PF_INET.

buf

A pointer to the data area to receive the hostent data. Note that this must be larger than the size of a hostent structure. This is because the data area supplied is used by the Windows Sockets implementation to contain not only a hostent structure but any and all of the data which is referenced by members of the hostent structure. It is recommended that you supply a buffer of MAXGETHOSTSTRUCT bytes.

buflen

The size of data area buf above.

Return Value

The return value specifies whether or not the asynchronous operation was successfully initiated. Note that it does not imply success or failure of the operation itself.

If the operation was successfully initiated, WSAAsyncGetHostByAddr returns a nonzero value of type HANDLE which is the asynchronous task handle for the request. This value can be used in two ways. It can be used to cancel the operation using WSACancelAsyncRequest. It can also be used to match up asynchronous operations and completion messages, by examining the wParam message argument.

If the asynchronous operation could not be initiated, WSAAsyncGetHostByAddr returns a zero value, and a specific error number may be retrieved by calling WSAGetLastError.

Error Codes

The following error codes may be set when an application window receives a message. As previously described, they may be extracted from the lParam in the reply message using the WSAGETASYNCERROR macro.

WSAENETDOWN	The Windows Sockets implementation has detected that the network subsystem has failed.
WSAENOBUFS	Buffer space is insufficient or unavailable.
WSAHOST_NOT_FOUND	Authoritative Answer Host not found.
WSATRY_AGAIN	Non-Authoritative Host not found, or SERVERFAIL.
WSANO_RECOVERY	Nonrecoverable errors: FORMERR, REFUSED, NOTIMP.
WSANO_DATA	Valid name, no data record of requested type.
The following errors may occur at the time of the function call, and indicate that the asynchronous operation could not be initiated.

WSANOTINITIALISED	A successful WSAStartup must occur before using this function.
WSAENETDOWN	The Windows Sockets implementation has detected that the network subsystem has failed.
WSAEINPROGRESS	A blocking Windows Sockets operation is in progress.
WSAEWOULDBLOCK	The asynchronous operation cannot be scheduled at this time due to resource or other constraints within the Windows Sockets implementation.
Remarks

This function is an asynchronous version of gethostbyaddr, and is used to retrieve host name and address information corresponding to a network address. The Windows Sockets implementation initiates the operation and returns to the caller immediately, passing back an asynchronous task handle that the application may use to identify the operation. When the operation is completed, the results (if any) are copied into the buffer provided by the caller and a message is sent to the application's window.

When the asynchronous operation is complete, the application's window hWnd receives message wMsg. The wParam argument contains the asynchronous task handle as returned by the original function call. The high 16 bits of lParam contain any error code. The error code can be any error as defined in WINSOCK.H. An error code of zero indicates successful completion of the asynchronous operation. On successful completion, the buffer supplied to the original function call contains a hostent structure. To access the elements of this structure, the original buffer address should be cast to a hostent structure pointer and accessed as appropriate.

Note that if the error code is WSAENOBUFS, it indicates that the size of the buffer specified by buflen in the original call was too small to contain all the resultant information. In this case, the low 16 bits of lParam contain the size of buffer required to supply ALL the requisite information. If the application decides that the partial data is inadequate, it may reissue the WSAAsyncGetHostByAddr function call with a buffer large enough to receive all the desired information (no smaller than the low 16 bits of lParam).

The error code and buffer length should be extracted from the lParam using the macros WSAGETASYNCERROR and WSAGETASYNCBUFLEN, defined in WINSOCK.H as:

#define WSAGETASYNCERROR(lParam)  HIWORD(lParam)

#define WSAGETASYNCBUFLEN(lParam)  LOWORD(lParam)

The use of these macros will maximize the portability of the source code for the application.

The buffer supplied to this function is used by the Windows Sockets implementation to construct a hostent structure together with the contents of data areas referenced by members of the same hostent structure. To avoid the WSAENOBUFS error previously noted, the application should provide a buffer of at least MAXGETHOSTSTRUCT bytes (as defined in WINSOCK.H).

Notes for Windows Sockets Suppliers

It is the responsibility of the Windows Sockets implementation to ensure that messages are successfully posted to the application. If a PostMessage operation fails, the Windows Sockets implementation must repost that message as long as the window exists.

Windows Sockets suppliers should use the WSAMAKEASYNCREPLY macro when constructing the lParam in the message.

See Also

gethostbyaddr, PostMessage, WSACancelAsyncRequest, WSAStartup


WSAAsyncGetHostByName
 WSAAsyncGetHostByName  QuickInfo

The Windows Sockets WSAAsyncGetHostByName function gets host information corresponding to a host name in an asynchronous fashion.

HANDLE WSAAsyncGetHostByName (

HWND hWnd,
unsigned int wMsg,
const char FAR * name,
char FAR * buf,
int buflen
);
Parameters

hWnd

The handle of the window that should receive a message when the asynchronous request completes.

wMsg

The message to be received when the asynchronous request completes.

name

A pointer to the name of the host.

buf

A pointer to the data area to receive the hostent data. Note that this must be larger than the size of a hostent structure. This is because the data area supplied is used by the Windows Sockets implementation to contain not only a hostent structure but any and all of the data referenced by members of the hostent structure. It is recommended that you supply a buffer of MAXGETHOSTSTRUCT bytes.

buflen

The size of data area buf above.

Return Value

The return value specifies whether the asynchronous operation was successfully initiated. Note that it does not imply success or failure of the operation itself.

If the operation was successfully initiated, WSAAsyncGetHostByName returns a nonzero value of type HANDLE, which is the asynchronous task handle for the request. This value can be used in two ways. It can be used to cancel the operation using WSACancelAsyncRequest. It can also be used to match up asynchronous operations and completion messages, by examining the wParam message argument.

If the asynchronous operation could not be initiated, WSAAsyncGetHostByName returns a zero value, and a specific error number may be retrieved by calling WSAGetLastError.

Error Codes

The following error codes may be set when an application window receives a message. As previously described, they may be extracted from the lParam in the reply message using the WSAGETASYNCERROR macro.

WSAENETDOWN	The Windows Sockets implementation has detected that the network subsystem has failed.
WSAENOBUFS	Buffer space is insufficien or unavailable.
WSAHOST_NOT_FOUND	Authoritative Answer Host not found.
WSATRY_AGAIN	Non-Authoritative Host not found, or SERVERFAIL.
WSANO_RECOVERY	Nonrecoverable errors: FORMERR, REFUSED, NOTIMP.
WSANO_DATA	Valid name, no data record of requested type.
The following errors may occur at the time of the function call, and indicate that the asynchronous operation could not be initiated.

WSANOTINITIALISED	A successful WSAStartup must occur before using this function.
WSAENETDOWN	The Windows Sockets implementation has detected that the network subsystem has failed.
WSAEINPROGRESS	A blocking Windows Sockets operation is in progress.
WSAEWOULDBLOCK	The asynchronous operation cannot be scheduled at this time due to resource or other constraints within the Windows Sockets implementation.
Remarks

This function is an asynchronous version of gethostbyname, and is used to retrieve host name and address information corresponding to a host name. The Windows Sockets implementation initiates the operation and returns to the caller immediately, passing back an asynchronous task handle that the application may use to identify the operation. When the operation is completed, the results (if any) are copied into the buffer provided by the caller and a message is sent to the application's window.

When the asynchronous operation is complete, the application's window hWnd receives message wMsg. The wParam argument contains the asynchronous task handle as returned by the original function call. The high 16 bits of lParam contain any error code. The error code may be any error as defined in WINSOCK.H. An error code of zero indicates successful completion of the asynchronous operation. On successful completion, the buffer supplied to the original function call contains a hostent structure. To access the elements of this structure, the original buffer address should be cast to a hostent structure pointer and accessed as appropriate.

Note that if the error code is WSAENOBUFS, it indicates that the size of the buffer specified by buflen in the original call was too small to contain all the resultant information. In this case, the low 16 bits of lParam contain the size of buffer required to supply ALL the requisite information. If the application needs more data, it may reissue the WSAAsyncGetHostByName function call with a buffer large enough to receive all the desired information (no smaller than the low 16 bits of lParam).

The error code and buffer length should be extracted from the lParam using the macros WSAGETASYNCERROR and WSAGETASYNCBUFLEN, defined in WINSOCK.H as:

#define WSAGETASYNCERROR(lParam)   HIWORD(lParam)

#define WSAGETASYNCBUFLEN(lParam)  LOWORD(lParam)

The use of these macros will maximize the portability of the source code for the application.

The buffer supplied to this function is used by the Windows Sockets implementation to construct a hostent structure together with the contents of data areas referenced by members of the same hostent structure. To avoid the WSAENOBUFS error previously noted, the application should provide a buffer of at least MAXGETHOSTSTRUCT bytes (as defined in WINSOCK.H).

Notes for Windows Sockets Suppliers

It is the responsibility of the Windows Sockets implementation to ensure that messages are successfully posted to the application. If a PostMessage operation fails, the Windows Sockets implementation must repost that message as long as the window exists.

Windows Sockets suppliers should use the WSAMAKEASYNCREPLY macro when constructing the lParam in the message.

See Also

gethostbyname, PostMessage, WSACancelAsyncRequest, WSAStartup


WSAAsyncGetProtoByName
 WSAAsyncGetProtoByName  QuickInfo

The Windows Sockets WSAAsyncGetProtoByName function gets protocol information corresponding to a protocol name in an asynchronous fashion.

HANDLE WSAAsyncGetProtoByName (

HWND hWnd,
unsigned int wMsg,
const char FAR * name,
char FAR * buf,
int buflen
);
Parameters

hWnd

The handle of the window which should receive a message when the asynchronous request completes.

wMsg

The message to be received when the asynchronous request completes.

name

A pointer to the protocol name to be resolved.

buf

A pointer to the data area to receive the protoent data. Note that this must be larger than the size of a protoent structure. This is because the data area supplied is used by the Windows Sockets implementation to contain not only a protoent structure but any and all of the data referenced by members of the protoent structure. It is recommended that you supply a buffer of MAXGETHOSTSTRUCT bytes.

buflen

The size of data area buf above.

Return Value

The return value specifies whether or not the asynchronous operation was successfully initiated. Note that it does not imply success or failure of the operation itself.

If the operation was successfully initiated, WSAAsyncGetProtoByName returns a nonzero value of type HANDLE, which is the asynchronous task handle for the request. This value can be used in two ways. It can be used to cancel the operation using WSACancelAsyncRequest. It can also be used to match up asynchronous operations and completion messages, by examining the wParam message argument.

If the asynchronous operation could not be initiated, WSAAsyncGetProtoByName returns a zero value, and a specific error number may be retrieved by calling WSAGetLastError.

Error Codes

The following error codes may be set when an application window receives a message. As previously described, they may be extracted from the lParam in the reply message using the WSAGETASYNCERROR macro.

WSAENETDOWN	The Windows Sockets implementation has detected that the network subsystem has failed.
WSAENOBUFS	Buffer space is insufficient or unavailable.
WSAHOST_NOT_FOUND	Authoritative Answer Host not found.
WSATRY_AGAIN	Non-Authoritative Host not found, or SERVERFAIL.
WSANO_RECOVERY	Nonrecoverable errors: FORMERR, REFUSED, NOTIMP.
WSANO_DATA	Valid name, no data record of requested type.
The following errors may occur at the time of the function call, and indicate that the asynchronous operation could not be initiated.

WSANOTINITIALISED	A successful WSAStartup must occur before using this function.
WSAENETDOWN	The Windows Sockets implementation has detected that the network subsystem has failed.
WSAEINPROGRESS	A blocking Windows Sockets operation is in progress.
WSAEWOULDBLOCK	The asynchronous operation cannot be scheduled at this time due to resource or other constraints within the Windows Sockets implementation.
Remarks

This function is an asynchronous version of getprotobyname, and is used to retrieve the protocol name and number corresponding to a protocol name. The Windows Sockets implementation initiates the operation and returns to the caller immediately, passing back an asynchronous task handle that the application may use to identify the operation. When the operation is completed, the results (if any) are copied into the buffer provided by the caller and a message is sent to the application's window.

When the asynchronous operation is complete, the application's window hWnd receives message wMsg. The wParam argument contains the asynchronous task handle as returned by the original function call. The high 16 bits of lParam contain any error code. The error code may be any error as defined in WINSOCK.H. An error code of zero indicates successful completion of the asynchronous operation. On successful completion, the buffer supplied to the original function call contains a protoent structure. To access the elements of this structure, the original buffer address should be cast to a protoent structure pointer and accessed as appropriate.

Note that if the error code is WSAENOBUFS, it indicates that the size of the buffer specified by buflen in the original call was too small to contain all the resultant information. In this case, the low 16 bits of lParam contain the size of buffer required to supply ALL the requisite information. If the application decides that the partial data is inadequate, it may reissue the WSAAsyncGetProtoByName function call with a buffer large enough to receive all the desired information (no smaller than the low 16 bits of lParam).

The error code and buffer length should be extracted from the lParam using the macros WSAGETASYNCERROR and WSAGETASYNCBUFLEN, defined in WINSOCK.H as:

#define WSAGETASYNCERROR(lParam)   HIWORD(lParam)

#define WSAGETASYNCBUFLEN(lParam)  LOWORD(lParam)

The use of these macros will maximize the portability of the source code for the application.

The buffer supplied to this function is used by the Windows Sockets implementation to construct a protoent structure together with the contents of data areas referenced by members of the same protoent structure. To avoid the WSAENOBUFS error previously noted, the application should provide a buffer of at least MAXGETHOSTSTRUCT bytes (as defined in WINSOCK.H).

Notes for Windows Sockets Suppliers

It is the responsibility of the Windows Sockets implementation to ensure that messages are successfully posted to the application. If a PostMessage operation fails, the Windows Sockets implementation must repost that message as long as the window exists.

Windows Sockets suppliers should use the WSAMAKEASYNCREPLY macro when constructing the lParam in the message.

See Also

getprotobyname, PostMessage, WSACancelAsyncRequest, WSAStartup


WSAAsyncGetProtoByNumber
 WSAAsyncGetProtoByNumber  QuickInfo

The Windows Sockets WSAAsyncGetProtoByNumber function gets protocol information corresponding to a protocol number in an asynchronous fashion.

HANDLE WSAAsyncGetProtoByNumber (

HWND hWnd,
unsigned int wMsg,
int number,
char FAR * buf,
int buflen
);
Parameters

hWnd

The handle of the window which should receive a message when the asynchronous request completes.

wMsg

The message to be received when the asynchronous request completes.

number

The protocol number to be resolved, in host byte order.

buf

A pointer to the data area to receive the protoent data. Note that this must be larger than the size of a protoent structure. This is because the data area supplied is used by the Windows Sockets implementation to contain not only a protoent structure but any and all of the data which is referenced by members of the protoent structure. It is recommended that you supply a buffer of MAXGETHOSTSTRUCT bytes.

buflen

The size of data area buf above.

Return Value

The return value specifies whether or not the asynchronous operation was successfully initiated. Note that it does not imply success or failure of the operation itself.

If the operation was successfully initiated, WSAAsyncGetProtoByNumber returns a nonzero value of type HANDLE, which is the asynchronous task handle for the request. This value can be used in two ways. It can be used to cancel the operation using WSACancelAsyncRequest. It can also be used to match up asynchronous operations and completion messages, by examining the wParam message argument.

If the asynchronous operation could not be initiated, WSAAsyncGetProtoByNumber returns a zero value, and a specific error number may be retrieved by calling WSAGetLastError.

Error Codes

The following error codes may be set when an application window receives a message. As previously described, they may be extracted from the lParam in the reply message using the WSAGETASYNCERROR macro.

WSAENETDOWN	The Windows Sockets implementation has detected that the network subsystem has failed.
WSAENOBUFS	Buffer space is insufficient or unavailable.
WSAHOST_NOT_FOUND	Authoritative Answer Host not found.
WSATRY_AGAIN	Non-Authoritative Host not found, or SERVERFAIL.
WSANO_RECOVERY	Nonrecoverable errors: FORMERR, REFUSED, NOTIMP.
WSANO_DATA	Valid name, no data record of requested type.
The following errors may occur at the time of the function call, and indicate that the asynchronous operation could not be initiated.

WSANOTINITIALISED	A successful WSAStartup must occur before using this function.
WSAENETDOWN	The Windows Sockets implementation has detected that the network subsystem has failed.
WSAEINPROGRESS	A blocking Windows Sockets operation is in progress.
WSAEWOULDBLOCK	The asynchronous operation cannot be scheduled at this time due to resource or other constraints within the Windows Sockets implementation.
Remarks

This function is an asynchronous version of getprotobynumber, and is used to retrieve the protocol name and number corresponding to a protocol number. The Windows Sockets implementation initiates the operation and returns to the caller immediately, passing back an asynchronous task handle, which the application may use to identify the operation. When the operation is completed, the results (if any) are copied into the buffer provided by the caller and a message is sent to the application's window.

When the asynchronous operation is complete, the application's window hWnd receives message wMsg. The wParam argument contains the asynchronous task handle as returned by the original function call. The high 16 bits of lParam contain any error code. The error code may be any error as defined in WINSOCK.H. An error code of zero indicates successful completion of the asynchronous operation. On successful completion, the buffer supplied to the original function call contains a protoent structure. To access the elements of this structure, the original buffer address should be cast to a protoent structure pointer and accessed as appropriate.

Note that if the error code is WSAENOBUFS, it indicates that the size of the buffer specified by buflen in the original call was too small to contain all the resultant information. In this case, the low 16 bits of lParam contain the size of buffer required to supply ALL the requisite information. If the application decides that the partial data is inadequate, it may reissue the WSAAsyncGetProtoByNumber function call with a buffer large enough to receive all the desired information (no smaller than the low 16 bits of lParam).

The error code and buffer length should be extracted from the lParam using the macros WSAGETASYNCERROR and WSAGETASYNCBUFLEN, defined in WINSOCK.H as:

#define WSAGETASYNCERROR(lParam)   HIWORD(lParam)

#define WSAGETASYNCBUFLEN(lParam)  LOWORD(lParam)

The use of these macros will maximize the portability of the source code for the application.

The buffer supplied to this function is used by the Windows Sockets implementation to construct a protoent structure together with the contents of data areas referenced by members of the same protoent structure. To avoid the WSAENOBUFS error previously noted, the application should provide a buffer of at least MAXGETHOSTSTRUCT bytes (as defined in WINSOCK.H).

Notes for Windows Sockets Suppliers

It is the responsibility of the Windows Sockets implementation to ensure that messages are successfully posted to the application. If a PostMessage operation fails, the Windows Sockets implementation must repost that message as long as the window exists.

Windows Sockets suppliers should use the WSAMAKEASYNCREPLY macro when constructing the lParam in the message.

See Also

getprotobynumber, PostMessage, WSACancelAsyncRequest, WSAStartup


WSAAsyncGetServByName
 WSAAsyncGetServByName  QuickInfo

The Windows Sockets WSAAsyncGetServByName function gets service information corresponding to a service name and port in an asynchronous fashion.

HANDLE WSAAsyncGetServByName (

HWND hWnd,
unsigned int wMsg,
const char FAR * name,
const char FAR * proto,
char FAR * buf,
int buflen
);
Parameters

hWnd

The handle of the window that should receive a message when the asynchronous request completes.

wMsg

The message to be received when the asynchronous request completes.

name

A pointer to a service name.

proto

A pointer to a protocol name. This may be NULL, in which case WSAAsyncGetServByName will search for the first service entry for which s_name or one of the s_aliases matches the given name. Otherwise, WSAAsyncGetServByName matches both name and proto.

buf

A pointer to the data area to receive the servent data. Note that this must be larger than the size of a servent structure. This is because the data area supplied is used by the Windows Sockets implementation to contain not only a servent structure but any and all of the data which is referenced by members of the servent structure. It is recommended that you supply a buffer of MAXGETHOSTSTRUCT bytes.

buflen

The size of data area buf  above.

Return Value

The return value specifies whether or not the asynchronous operation was successfully initiated. Note that it does not imply success or failure of the operation itself.

If the operation was successfully initiated, WSAAsyncGetServByName returns a nonzero value of type HANDLE, which is the asynchronous task handle for the request. This value can be used in two ways. It can be used to cancel the operation using WSACancelAsyncRequest. It can also be used to match up asynchronous operations and completion messages, by examining the wParam message argument.

If the asynchronous operation could not be initiated, WSAAsyncServByName returns a zero value, and a specific error number may be retrieved by calling WSAGetLastError.

Error Codes

The following error codes may be set when an application window receives a message. As previously described, they may be extracted from the lParam in the reply message using the WSAGETASYNCERROR macro.

WSAENETDOWN	The Windows Sockets implementation has detected that the network subsystem has failed.
WSAENOBUFS	Buffer space is insufficient or unavailable.
WSAHOST_NOT_FOUND	Authoritative Answer Host not found.
WSATRY_AGAIN	Non-Authoritative Host not found, or SERVERFAIL.
WSANO_RECOVERY	Nonrecoverable errors: FORMERR, REFUSED, NOTIMP.
WSANO_DATA	Valid name, no data record of requested type.
The following errors may occur at the time of the function call, and indicate that the asynchronous operation could not be initiated.

WSANOTINITIALISED	A successful WSAStartup must occur before using this function.
WSAENETDOWN	The Windows Sockets implementation has detected that the network subsystem has failed.
WSAEINPROGRESS	A blocking Windows Sockets operation is in progress.
WSAEWOULDBLOCK	The asynchronous operation cannot be scheduled at this time due to resource or other constraints within the Windows Sockets implementation.
Remarks

This function is an asynchronous version of getservbyname, and is used to retrieve service information corresponding to a service name. The Windows Sockets implementation initiates the operation and returns to the caller immediately, passing back an asynchronous task handle that the application may use to identify the operation. When the operation is completed, the results (if any) are copied into the buffer provided by the caller and a message is sent to the application's window.

When the asynchronous operation is complete, the application's window hWnd receives message wMsg. The wParam argument contains the asynchronous task handle as returned by the original function call. The high 16 bits of lParam contain any error code. The error code may be any error as defined in WINSOCK.H. An error code of zero indicates successful completion of the asynchronous operation. On successful completion, the buffer supplied to the original function call contains a hostent structure. To access the elements of this structure, the original buffer address should be cast to a hostent structure pointer and accessed as appropriate.

Note that if the error code is WSAENOBUFS, it indicates that the size of the buffer specified by buflen in the original call was too small to contain all the resultant information. In this case, the low 16 bits of lParam contain the size of buffer required to supply ALL the requisite information. If the application decides that the partial data is inadequate, it may reissue the WSAAsyncGetServByName function call with a buffer large enough to receive all the desired information (no smaller than the low 16 bits of lParam).

The error code and buffer length should be extracted from the lParam using the macros WSAGETASYNCERROR and WSAGETASYNCBUFLEN, defined in WINSOCK.H as:

#define WSAGETASYNCERROR(lParam)   HIWORD(lParam)

#define WSAGETASYNCBUFLEN(lParam)  LOWORD(lParam)

The use of these macros will maximize the portability of the source code for the application.

The buffer supplied to this function is used by the Windows Sockets implementation to construct a hostent structure together with the contents of data areas referenced by members of the same hostent structure. To avoid the WSAENOBUFS error noted above, the application should provide a buffer of at least MAXGETHOSTSTRUCT bytes (as defined in WINSOCK.H).

Notes for Windows Sockets Suppliers

It is the responsibility of the Windows Sockets implementation to ensure that messages are successfully posted to the application. If a PostMessage operation fails, the Windows Sockets implementation must repost that message as long as the window exists.

Windows Sockets suppliers should use the WSAMAKEASYNCREPLY macro when constructing the lParam in the message.

See Also

getservbyname, PostMessage, WSACancelAsyncRequest, WSAStartup


WSAAsyncGetServByPort
 WSAAsyncGetServByPort  QuickInfo

The Windows Sockets WSAAsyncGetServByPort function gets service information corresponding to a port and protocol in an asynchronous fashion.

HANDLE WSAAsyncGetServByPort (

HWND hWnd,
unsigned int wMsg,
int port,
const char FAR * proto,
char FAR * buf,
int buflen
);
Parameters

hWnd

The handle of the window that should receive a message when the asynchronous request completes.

wMsg

The message to be received when the asynchronous request completes.

port

The port for the service, in network byte order.

proto

A pointer to a protocol name. This may be NULL, in which case WSAAsyncGetServByPort will search for the first service entry that matches the specified port. Otherwise, WSAAsyncGetServByPort matches both port and proto.

buf

A pointer to the data area to receive the servent data. Note that this must be larger than the size of a servent structure. This is because the data area supplied is used by the Windows Sockets implementation to contain not only a servent structure but any and all of the data referenced by members of the servent structure. It is recommended that you supply a buffer of MAXGETHOSTSTRUCT bytes.

buflen

The size of data area buf  above.

Return Value

The return value specifies whether the asynchronous operation was successfully initiated. Note that it does not imply success or failure of the operation itself.

If the operation was successfully initiated, WSAAsyncGetServByPort returns a nonzero value of type HANDLE, which is the asynchronous task handle for the request. This value can be used in two ways. It can be used to cancel the operation using WSACancelAsyncRequest. It can also be used to match up asynchronous operations and completion messages, by examining the wParam message argument.

If the asynchronous operation could not be initiated, WSAAsyncGetServByPort returns a zero value, and a specific error number may be retrieved by calling WSAGetLastError.

Error Codes

The following error codes may be set when an application window receives a message. As previously described, they may be extracted from the lParam in the reply message using the WSAGETASYNCERROR macro.

WSAENETDOWN	The Windows Sockets implementation has detected that the network subsystem has failed.
WSAENOBUFS	Buffer space is insufficient or unavailable.
WSAHOST_NOT_FOUND	Authoritative Answer Host not found.
WSATRY_AGAIN	Non-Authoritative Host not found, or SERVERFAIL.
WSANO_RECOVERY	Nonrecoverable errors: FORMERR, REFUSED, NOTIMP.
WSANO_DATA	Valid name, no data record of requested type.
The following errors may occur at the time of the function call, and indicate that the asynchronous operation could not be initiated.

WSANOTINITIALISED	A successful WSAStartup must occur before using this function.
WSAENETDOWN	The Windows Sockets implementation has detected that the network subsystem has failed.
WSAEINPROGRESS	A blocking Windows Sockets operation is in progress.
WSAEWOULDBLOCK	The asynchronous operation cannot be scheduled at this time due to resource or other constraints within the Windows Sockets implementation.
Remarks

This function is an asynchronous version of getservbyport, and is used to retrieve service information corresponding to a port number. The Windows Sockets implementation initiates the operation and returns to the caller immediately, passing back an asynchronous task handle that the application may use to identify the operation. When the operation is completed, the results (if any) are copied into the buffer provided by the caller and a message is sent to the application's window.

When the asynchronous operation is complete the application's window hWnd receives message wMsg. The wParam argument contains the asynchronous task handle as returned by the original function call. The high 16 bits of lParam contain any error code. The error code may be any error as defined in WINSOCK.H. An error code of zero indicates successful completion of the asynchronous operation. On successful completion, the buffer supplied to the original function call contains a servent structure. To access the elements of this structure, the original buffer address should be cast to a servent structure pointer and accessed as appropriate.

Note that if the error code is WSAENOBUFS, it indicates that the size of the buffer specified by buflen in the original call was too small to contain all the resultant information. In this case, the low 16 bits of lParam contain the size of buffer required to supply ALL the requisite information. If the application needs more information, it may reissue the WSAAsyncGetServByPort function call with a buffer large enough to receive all the desired information (no smaller than the low 16 bits of lParam).

The error code and buffer length should be extracted from the lParam using the macros WSAGETASYNCERROR and WSAGETASYNCBUFLEN, defined in WINSOCK.H as:

#define WSAGETASYNCERROR(lParam)   HIWORD(lParam)

#define WSAGETASYNCBUFLEN(lParam)  LOWORD(lParam)

The use of these macros will maximize the portability of the source code for the application.

The buffer supplied to this function is used by the Windows Sockets implementation to construct a servent structure together with the contents of data areas referenced by members of the same servent structure. To avoid the WSAENOBUFS error previously noted, the application should provide a buffer of at least MAXGETHOSTSTRUCT bytes (as defined in WINSOCK.H).

Notes for Windows Sockets Suppliers

It is the responsibility of the Windows Sockets implementation to ensure that messages are successfully posted to the application. If a PostMessage operation fails, the Windows Sockets implementation must repost that message as long as the window exists.

Windows Sockets suppliers should use the WSAMAKEASYNCREPLY macro when constructing the lParam in the message.

See Also

getservbyport, PostMessage, WSACancelAsyncRequest, WSAStartup


WSAAsyncSelect
 WSAAsyncSelect  QuickInfo

The Windows Sockets WSAAsyncSelect function requests event notification for a socket.

int WSAAsyncSelect (

SOCKET s,
HWND hWnd,
unsigned int wMsg,
long lEvent
);
Parameters

s

A descriptor identifying the socket for which event notification is required.

hWnd

A handle identifying the window that should receive a message when a network event occurs.

wMsg

The message to be received when a network event occurs.

lEvent

A bitmask which specifies a combination of network events in which the application is interested.

Return Value

The return value is zero if the application's declaration of interest in the network event set was successful. Otherwise, the value SOCKET_ERROR is returned, and a specific error number may be retrieved by calling WSAGetLastError.

Error Codes

WSANOTINITIALISED	A successful WSAStartup must occur before using this function.
WSAENETDOWN	The Windows Sockets implementation has detected that the network subsystem has failed.
WSAEINVAL	Indicates that one of the specified parameters was invalid.
WSAEINPROGRESS	A blocking Windows Sockets operation is in progress.
	Additional error codes may be set when an application window receives a message. This error code is extracted from the lParam in the reply message using the WSAGETSELECTERROR macro. Possible error codes for each network event are listed following:
Event: FD_CONNECT

Error Code	Meaning
WSAEADDRINUSE	The specified address is already in use.
WSAEADDRNOTAVAIL	The specified address is not available from the local computer.
WSAEAFNOSUPPORT	Addresses in the specified family cannot be used with this socket.
WSAECONNREFUSED	The attempt to connect was forcefully rejected.
WSAEDESTADDRREQ	A destination address is required.
WSAEFAULT	The namelen argument is incorrect.
WSAEINVAL	The socket is already bound to an address.
WSAEISCONN	The socket is already connected.
WSAEMFILE	No more file descriptors are available.
WSAENETUNREACH	The network can't be reached from this host at this time.
WSAENOBUFS	No buffer space is available. The socket cannot be connected.
WSAENOTCONN	The socket is not connected.
WSAENOTSOCK	The descriptor is a file, not a socket.
WSAETIMEDOUT	Attempt to connect timed out without establishing a connection
Event: FD_CLOSE

Error Code	Meaning
WSAENETDOWN	The Windows Sockets implementation has detected that the network subsystem has failed.
WSAECONNRESET	The connection was reset by the remote side.
WSAECONNABORTED	The connection was aborted due to timeout or other failure.
Event: FD_READ, Event: FD_WRITE, Event: FD_OOB, Event: FD_ACCEPT

Error Code	Meaning
WSAENETDOWN	The Windows Sockets implementation has detected that the network subsystem has failed.
Notes for Windows Sockets Suppliers

It is the responsibility of the Windows Sockets Supplier to ensure that messages are successfully posted to the application. If a PostMessage operation fails, the Windows Sockets implementation must repost that message as long as the window exists.

Windows Sockets suppliers should use the WSAMAKESELECTREPLY macro when constructing the lParam in the message.

When a socket is closed, the Windows Sockets supplier should purge any messages remaining for posting to the application window. However, the application must be prepared to receive, and discard, any messages that may have been posted prior to the closesocket.

Remarks

This function is used to request that the Windows Sockets DLL should send a message to the window hWnd whenever it detects any of the network events specified by the lEvent parameter. The message that should be sent is specified by the wMsg parameter. The socket for which notification is required is identified by s.

This function automatically sets socket s to nonblocking mode.

The lEvent parameter is constructed by using a bitwise OR operation with any of the values specified in the following list.

Value	Meaning
FD_READ	Want to receive notification of readiness for reading
FD_WRITE	Want to receive notification of readiness for writing
FD_OOB	Want to receive notification of the arrival of out-of-band data
FD_ACCEPT	Want to receive notification of incoming connections
FD_CONNECT	Want to receive notification of completed connection
FD_CLOSE	Want to receive notification of socket closure
Issuing a WSAAsyncSelect for a socket cancels any previous WSAAsyncSelect for the same socket. For example, to receive notification for both reading and writing, the application must call WSAAsyncSelect with both FD_READ and FD_WRITE, as follows:

rc = WSAAsyncSelect(s, hWnd, wMsg, FD_READ|FD_WRITE);

It is not possible to specify different messages for different events. The following code will not work; the second call will cancel the effects of the first, and only FD_WRITE events will be reported with message wMsg2:

rc = WSAAsyncSelect(s, hWnd, wMsg1, FD_READ);

rc = WSAAsyncSelect(s, hWnd, wMsg2, FD_WRITE);

To cancel all notification  — that is, to indicate that the Windows Sockets implementation should send no further messages related to network events on the socket − lEvent should be set to zero.

rc = WSAAsyncSelect(s, hWnd, 0, 0);

Although in this instance WSAAsyncSelect immediately disables event message posting for the socket, it is possible that messages may be waiting in the application's message queue. The application must therefore be prepared to receive network event messages even after cancellation. Closing a socket with closesocket also cancels WSAAsyncSelect message sending, but the same caveat about messages in the queue prior to the closesocket still applies.

Since an accepted socket has the same properties as the listening socket used to accept it, any WSAAsyncSelect events set for the listening socket apply to the accepted socket. For example, if a listening socket has WSAAsyncSelect events FD_ACCEPT, FD_READ, and FD_WRITE, then any socket accepted on that listening socket will also have FD_ACCEPT, FD_READ, and FD_WRITE events with the same wMsg value used for messages. If a different wMsg or events are desired, the application should call WSAAsyncSelect, passing the accepted socket and the desired new information. (Note that there is a timing window between the accept call and the call to WSAAsyncSelect to change the events or wMsg. An application that desires a different wMsg for the listening and accepted sockets should ask for only FD_ACCEPT events on the listening socket, then set appropriate events after the accept. Since FD_ACCEPT is never sent for a connected socket and FD_READ, FD_WRITE, FD_OOB, and FD_CLOSE are never sent for listening sockets, this will not impose difficulties.)

When one of the nominated network events occurs on the specified socket s, the application's window hWnd receives message wMsg. The wParam argument identifies the socket on which a network event has occurred. The low word of lParam specifies the network event that has occurred. The high word of lParam contains any error code. The error code be any error as defined in WINSOCK.H.

The error and event codes may be extracted from the lParam using the macros WSAGETSELECTERROR and WSAGETSELECTEVENT, defined in WINSOCK.H as:

#define WSAGETSELECTERROR(lParam)  HIWORD(lParam)

#define WSAGETSELECTEVENT(lParam)  LOWORD(lParam)

The use of these macros will maximize the portability of the source code for the application.

The possible network event codes that may be returned are as follows:

Value	Meaning
FD_READ	Socket s is ready for reading.
FD_WRITE	Socket s is ready for writing.
FD_OOB	Out-of-band data is ready for reading on socket s.
FD_ACCEPT	Socket s is ready for accepting a new incoming connection.
FD_CONNECT	Connection on socket s completed.
FD_CLOSE	Connection identified by socket s has been closed.
Although WSAAsyncSelect can be called with interest in multiple events, the application window will receive a single message for each network event.

As in the case of the select function, WSAAsyncSelect will frequently be used to determine when a data transfer operation (send or recv) can be issued with the expectation of immediate success. Nevertheless, a robust application must be prepared for the possibility that it may receive a message and issue a Windows Sockets function call which returns WSAEWOULDBLOCK immediately. For example, the following sequence of events is possible:

1.	Data arrives on socket s; Windows Sockets posts WSAAsyncSelect message.

2.	Application processes some other message.

3.	While processing, application issues an ioctlsocket(s, FIONREAD...) and notices that there is data ready to be read.

4.	Application issues a recv(s,...) to read the data.

5.	Application loops to process next message, eventually reaching the WSAAsyncSelect message, indicating that data is ready to read.

6.	Application issues recv(s,...), which fails with the error WSAEWOULDBLOCK.

Other sequences are possible.

The Windows Sockets DLL will not continually flood an application with messages for a particular network event. Having successfully posted notification of a particular event to an application window, no further message(s) for that network event will be posted to the application window until the application makes the function call which implicitly reenables notification of that network event.

Event	Reenabling function
FD_READ	recv or recvfrom
FD_WRITE	send or sendto
FD_OOB	recv
FD_ACCEPT	accept
FD_CONNECT	NONE
FD_CLOSE	NONE
Any call to the reenabling routine, even one that fails, results in reenabling of message posting for the relevant event.

For FD_READ, FD_OOB, and FD_ACCEPT events, message posting is "level-triggered." This means that if the reenabling routine is called and the relevant event is still valid after the call, a WSAAsyncSelect message is posted to the application. This allows an application to be event-driven and not concern itself with the amount of data that arrives at any one time. Consider the following sequence:

1.	Windows Sockets DLL receives 100 bytes of data on socket s and posts an FD_READ message.

2.	The application issues recv( s, buffptr, 50, 0) to read 50 bytes.

3.	The Windows Sockets DLL posts another FD_READ message, since there is still data to be read.

With these semantics, an application need not read all available data in response to an FD_READ message — a single recv in response to each FD_READ message is appropriate. If an application issues multiple recv calls in response to a single FD_READ, it may receive multiple FD_READ messages. Such an application may need to disable FD_READ messages before starting the recv calls by calling WSAAsyncSelect with the FD_READ event not set.

If an event is true when the application initially calls WSAAsyncSelect or when the reenabling function is called, then a message is posted as appropriate. For example, if an application calls listen, a connect attempt is made, then the application calls WSAAsyncSelect specifying FD_ACCEPT, the Windows Sockets implementation posts an FD_ACCEPT message immediately.

The FD_WRITE event is handled slightly differently. An FD_WRITE message is posted when a socket is first connected with connect or accepted with accept, and then after a send or sendto fails with WSAEWOULDBLOCK and buffer space becomes available. Therefore, an application can assume that sends are possible starting from the first FD_WRITE message and lasting until a send returns WSAEWOULDBLOCK. After such a failure, the application will be notified that sends are again possible with an FD_WRITE message.

The FD_OOB event is used only when a socket is configured to receive out-of-band data separately. If the socket is configured to receive out-of-band data in-line, the out-of-band (expedited) data is treated as normal data and the application should register an interest in, and will receive, FD_READ events, not FD_OOB events. An application can set or inspect the way in which out-of-band data is to be handled by using setsockopt or getsockopt for the SO_OOBINLINE option.

The error code in an FD_CLOSE message indicates whether the socket close was graceful or abortive. If the error code is zero, then the close was graceful; if the error code is WSAECONNRESET, then the socket's virtual socket was reset. This applies only to sockets of type SOCK_STREAM.

The FD_CLOSE message is posted when a close indication is received for the virtual circuit corresponding to the socket. In TCP terms, this means that the FD_CLOSE is posted when the connection goes into the FIN WAIT or CLOSE WAIT states. This results from the remote end performing a shutdown on the send side or a closesocket.

Please note your application will receive ONLY an FD_CLOSE message to indicate closure of a virtual circuit. It will NOT receive an FD_READ message to indicate this condition.

See Also

accept, closesocket, getsockopt, ioctlsocket, listen, PostMessage, recv, recvfrom, select, send, sendto, setsockopt, WSAStartup


WSACancelAsyncRequest
 WSACancelAsyncRequest  QuickInfo

The Windows Sockets WSACancelAsyncRequest function cancels an incomplete asynchronous operation.

int WSACancelAsyncRequest(

HANDLE hAsyncTaskHandle
);
Parameters

hAsyncTaskHandle

Specifies the asynchronous operation to be canceled.

Return Value

The value returned by WSACancelAsyncRequest is zero if the operation was successfully canceled. Otherwise the value SOCKET_ERROR is returned, and a specific error number may be retrieved by calling WSAGetLastError.

Error Codes

WSANOTINITIALISED	A successful WSAStartup must occur before using this function.
WSAENETDOWN	The Windows Sockets implementation has detected that the network subsystem has failed.
WSAEINVAL	Indicates that the specified asynchronous task handle was invalid
WSAEINPROGRESS	A blocking Windows Sockets operation is in progress.
WSAEALREADY	The asynchronous routine being canceled has already completed.
Remarks

The WSACancelAsyncRequest function is used to cancel an asynchronous operation initiated by one of the WSAAsyncGetXByY family of functions such as WSAAsyncGetHostByName. The operation to be canceled is identified by the hAsyncTaskHandle parameter, which should be set to the asynchronous task handle as returned by the initiating function.

An attempt to cancel an existing asynchronous WSAAsyncGetXByY operation can fail with an error code of WSAEALREADY for two reasons. First, the original operation has already completed and the application has dealt with the resultant message. Second, the original operation has already completed but the resultant message is still waiting in the application window queue.

Notes for Windows Sockets Suppliers

It is unclear whether the application can usefully distinguish between WSAEINVAL and WSAEALREADY, since in both cases the error indicates that there is no asynchronous operation in progress with the indicated handle. [Trivial exception: zero is always an invalid asynchronous task handle.] The Windows Sockets specification does not prescribe how a conformant Windows Sockets implementation should distinguish between the two cases. For maximum portability, a Windows Sockets application should treat the two errors as equivalent.

See Also

WSAAsyncGetHostByAddr, WSAAsyncGetHostByName, WSAAsyncGetProtoByName, WSAAsyncGetProtoByNumber, WSAAsyncGetServByName, WSAAsyncGetServByPort, WSAStartup


WSACancelBlockingCall
 WSACancelBlockingCall  QuickInfo

The Windows Sockets WSACancelBlockingCall function cancels a blocking call that is currently in progress.

int WSACancelBlockingCall(void);

Return Value

The value returned by WSACancelBlockingCall is zero if the operation was successfully canceled. Otherwise, the value SOCKET_ERROR is returned, and a specific error number may be retrieved by calling WSAGetLastError.

Error Codes

WSANOTINITIALISED	A successful WSAStartup must occur before using this function.
WSAENETDOWN	The Windows Sockets implementation has detected that the network subsystem has failed.
WSAEINVAL	Indicates that there is no outstanding blocking call.
Remarks

This function cancels any outstanding blocking operation for this task. It is typically used in two situations:

1.	An application is processing a message that was received while a blocking call is in progress. In this case, WSAIsBlocking will be true.

2.	A blocking call is in progress, and Windows Sockets has called back to the application's "blocking hook" function (as established by WSASetBlockingHook).

In each case, the original blocking call will terminate as soon as possible with the error WSAEINTR. In (1), the termination will not take place until Windows message scheduling has caused control to revert to the blocking routine in Windows Sockets. In (2), the blocking call will be terminated as soon as the blocking hook function completes.

In the case of a blocking connect operation, the Windows Sockets implementation will terminate the blocking call as soon as possible, but it may not be possible for the socket resources to be released until the connection has completed (and then been reset) or timed out. This is likely to be noticeable only if the application immediately tries to open a new socket (if no sockets are available), or to connect to the same peer.

Canceling an accept or a select call does not adversely impact the sockets passed to these calls. Only the particular call fails; any operation that was legal before the cancel is legal after the cancel, and the state of the socket is not affected in any way.

Canceling any operation other than accept and select can leave the socket in an indeterminate state. If an application cancels a blocking operation on a socket, the only operation that the application can depend on being able to perform on the socket is a call to closesocket, although other operations may work on some Windows Sockets implementations. If an application needs maximum portability, it must not depend on performing operations after a cancel. An application can reset the connection by setting the timeout on SO_LINGER to zero.

If a cancel operation compromised the integrity of a SOCK_STREAM's data stream in any way, the Windows Sockets implementation must reset the connection and fail all future operations other than closesocket with WSAECONNABORTED.

Note that it is possible that the network operation completes before the WSACancelBlockingCall is processed, for example if data is received into the user buffer at interrupt time while the application is in a blocking hook. In this case, the blocking operation will return successfully as if WSACancelBlockingCall had never been called. The WSACancelBlockingCall still succeeds in this case; the only way to know with certainty that an operation was actually canceled is to check for a return code of WSAEINTR from the blocking call.

See Also

accept, closesocket, connect, select, WSAStartup


WSACleanup
 WSACleanup  QuickInfo

The Windows Sockets WSACleanup function terminates use of the Windows Sockets DLL.

int WSACleanup(void);

Return Value

The return value is zero if the operation was successful. Otherwise the value SOCKET_ERROR is returned, and a specific error number may be retrieved by calling WSAGetLastError.

Error Codes

WSANOTINITIALISED	A successful WSAStartup must occur before using this function.
WSAENETDOWN	The Windows Sockets implementation has detected that the network subsystem has failed.
WSAEINPROGRESS	A blocking Windows Sockets operation is in progress.
Remarks

An application or DLL is required to perform a (successful) WSAStartup call before it can use Windows Sockets services. When it has completed the use of Windows Sockets, the application or DLL must call WSACleanup to deregister itself from a Windows Sockets implementation and allow the implementation to free any resources allocated on behalf of the application or DLL. Any open SOCK_STREAM sockets that are connected when WSACleanup is called are reset; sockets that have been closed with closesocket but still have pending data to be sent are not affected — the pending data is still sent.

There must be a call to WSACleanup for every call to WSAStartup made by a task. Only the final WSACleanup for that task does the actual cleanup; the preceding calls simply decrement an internal reference count in the Windows Sockets DLL. A naive application can ensure that WSACleanup was called enough times by calling WSACleanup in a loop until it returns WSANOTINITIALISED.

Attempting to call WSACleanup from within a blocking hook and then failing to check the return code is a common error in Windows Sockets programming. If an application needs to quit while a blocking call is outstanding, the application must first cancel the blocking call with WSACancelBlockingCall then issue the WSACleanup call once control has been returned to the application.

Notes for Windows Sockets Suppliers

Well-behaved Windows Sockets applications will make a WSACleanup call to indicate deregistration from a Windows Sockets implementation. This function can thus, for example, be utilized to free up resources allocated to the specific application.

A Windows Sockets implementation must be prepared to deal with an application that terminates without invoking WSACleanup — for example, as a result of an error.

In a multithreaded environment, WSACleanup terminates Windows Sockets operations for all threads.

A Windows Sockets implementation must ensure that WSACleanup leaves things in a state in which the application can invoke WSAStartup to reestablish Windows Sockets usage.

See Also

WSACancelBlockingCall, WSAStartup,


WSAGetLastError
 WSAGetLastError  QuickInfo

The Windows Sockets WSAGetLastError function gets the error status for the last operation that failed.

int WSAGetLastError(void);

Return Value

The return value indicates the error code for the last Windows Sockets function performed by this thread.

Notes for Windows Sockets Suppliers

The use of the WSAGetLastError function to retrieve the last error code, rather than relying on a global error variable (compare errno), is required in order to provide compatibility with future multithreaded environments.

Note that in a nonpreemptive Windows environment WSAGetLastError is used to retrieve only Windows Sockets function errors. In a preemptive environment, WSAGetLastError will invoke GetLastError, which is used to retrieve the error status for all Win32 functions on a per-thread basis. For portability, an application should use WSAGetLastError immediately after the Windows Sockets function that failed. For more information, see Error Codes.

Remarks

This function returns the last network error that occurred. When a particular Windows Sockets function indicates that an error has occurred, this function should be called to retrieve the appropriate error code.

See Also

GetLastError, WSASetLastError


WSAIsBlocking
 WSAIsBlocking  QuickInfo

The Windows Sockets WSAIsBlocking function determines if a blocking call is in progress.

BOOL WSAIsBlocking(void);

Return Value

The return value is TRUE if there is an outstanding blocking function awaiting completion. Otherwise, it is FALSE.

Remarks

This function allows a task to determine if it is executing while waiting for a previous blocking call to complete.

Although a call issued on a blocking socket appears to an application program as though it "blocks," the Windows Sockets DLL has to relinquish the processor to allow other applications to run. This means that it is possible for the application that issued the blocking call to be reentered, depending on the message(s) it receives. In this instance, the WSAIsBlocking function can be used to ascertain whether the task has been reentered while waiting for an outstanding blocking call to complete. Note that Windows Sockets prohibits more than one outstanding call per thread.

Notes for Windows Sockets Suppliers

A Windows Sockets implementation must prohibit more than one outstanding blocking call per thread.


WSASetBlockingHook
 WSASetBlockingHook  QuickInfo

The Windows Sockets WSASetBlockingHook function establishes an application-specific blocking hook function.

FARPROC WSASetBlockingHook(

FARPROC lpBlockFunc
);
Parameters

lpBlockFunc

A pointer to the procedure instance address of the blocking function to be installed.

Return Value

The return value is a pointer to the procedure-instance of the previously installed blocking function. The application or library that calls the WSASetBlockingHook  function should save this return value so that it can be restored if necessary. (If "nesting" is not important, the application can simply discard the value returned by WSASetBlockingHook and eventually use WSAUnhookBlockingHook to restore the default mechanism.) If the operation fails, a NULL pointer is returned, and a specific error number can be retrieved by calling WSAGetLastError.

Error Codes

WSANOTINITIALISED	A successful WSAStartup must occur before using this function.
WSAENETDOWN	The Windows Sockets implementation has detected that the network subsystem has failed.
WSAEINPROGRESS	A blocking Windows Sockets operation is in progress.
Remarks

This function installs a new function which a Windows Sockets implementation should use to implement blocking socket function calls.

A Windows Sockets implementation includes a default mechanism by which blocking socket functions are implemented. The function WSASetBlockingHook gives the application the ability to execute its own function at blocking time in place of the default function.

When an application invokes a blocking Windows Sockets operation, the Windows Sockets implementation initiates the operation and then enters a loop similar to the following pseudocode:

for(;;) {

    /* flush messages for good user response */

    while (BlockingHook)

        ;

    /* check for WSACancelBlockingCall */

    if(operation_cancelled)

       break;

    /* check to see if operation completed */

    if(operation_complete)

        break;        /* normal completion */

}

Note that Windows Sockets implementations can perform the above steps in a different order; for example, the check for operation completion may occur before calling the blocking hook. The default BlockingHook function is equivalent to:

BOOL DefaultBlockingHook(void)

{

    MSG msg;

    BOOL ret;

    /* get the next message, if any */

    ret = (BOOL) PeekMessage(&msg, NULL, 0, 0, PM_REMOVE);

    /* if we got one, process it */

    if (ret) {

        TranslateMessage(&msg);

        DispatchMessage(&msg);

    }

    /* TRUE if we got a message */

    return ret;

}

The WSASetBlockingHook function is provided to support those applications that require more complex message processing — for example, those employing the MDI (multiple document interface) model. It is not intended as a mechanism for performing general applications functions. In particular, the only Windows Sockets function that can be issued from a custom blocking hook function is WSACancelBlockingCall, which will cause the blocking loop to terminate.

This function must be implemented on a per-task basis for non-multithreaded versions of Windows and on a per-thread basis for multithreaded versions of Windows such as Windows NT. It thus provides for a particular task or thread to replace the blocking mechanism without affecting other tasks or threads.

In multithreaded versions of Windows, there is no default blocking hook — blocking calls block the thread that makes the call. However, an application can install a specific blocking hook by calling WSASetBlockingHook.

This allows easy portability of applications that depend on the blocking hook behavior.

See Also

WSACancelBlockingCall, WSAUnhookBlockingHook


WSASetLastError
 WSASetLastError  QuickInfo

The Windows Sockets WSASetLastError function sets the error code that can be retrieved by WSAGetLastError.

void WSASetLastError(

int iError
);
Parameters

iError

Specifies the error code to be returned by a subsequent WSAGetLastError call.

Return Value

This function does not return a value.

Error Codes

WSANOTINITIALISED	A successful WSAStartup must occur before using this function.
Remarks

This function allows an application to set the error code to be returned by a subsequent WSAGetLastError call for the current thread. Note that any subsequent Windows Sockets function called by the application will override the error code as set by this function.

Notes for Windows Sockets Suppliers

In a Win32 environment, this function will invoke SetLastError.

See Also

SetLastError, WSAGetLastError


WSAStartup
 WSAStartup  QuickInfo

int WSAStartup(

WORD wVersionRequested,
LPWSADATA lpWSAData
);
Parameters

wVersionRequested

The highest version of Windows Sockets support that the caller can use. The high-order byte specifies the minor version (revision) number; the low-order byte specifies the major version number.

lpWSAData

A pointer to the WSADATA data structure that is to receive details of the Windows Sockets implementation.

Return Value

WSAStartup returns zero if successful. Otherwise, it returns one of the error codes listed below. Note that the normal mechanism whereby the application calls WSAGetLastError to determine the error code cannot be used, since the Windows Sockets DLL may not have established the client data area where the "last error" information is stored.

Notes for Windows Sockets Suppliers

Each Windows Sockets application MUST make a WSAStartup call before issuing any other Windows Sockets API calls. This function can thus be used for initialization purposes.

Further issues are discussed in the notes for WSACleanup.

Error Codes

WSASYSNOTREADY	Indicates that the underlying network subsystem is not ready for network communication.
WSAVERNOTSUPPORTED	The version of Windows Sockets support requested is not provided by this particular Windows Sockets implementation.
WSAEINVAL	The Windows Sockets version specified by the application is not supported by this DLL.
Remarks

This function must be the first Windows Sockets function called by an application or DLL. It allows an application or DLL to specify the version of Windows Sockets required and to retrieve details of the specific Windows Sockets implementation. The application or DLL may only issue further Windows Sockets functions after a successful WSAStartup invocation.

In order to support future Windows Sockets implementations and applications that may have functionality differences from Windows Sockets 1.1, a negotiation takes place in WSAStartup. The caller of WSAStartup and the Windows Sockets DLL indicate to each other the highest version that they can support, and each confirms that the other's highest version is acceptable. Upon entry to WSAStartup, the Windows Sockets DLL examines the version requested by the application. If this version is higher than the lowest version supported by the DLL, the call succeeds and the DLL returns in wHighVersion the highest version it supports and in wVersion the minimum of its high version and wVersionRequested. The Windows Sockets DLL then assumes that the application will use wVersion. If the wVersion field of the WSADATA structure is unacceptable to the caller, it should call WSACleanup and either search for another Windows Sockets DLL or fail to initialize.

This negotiation allows both a Windows Sockets DLL and a Windows Sockets application to support a range of Windows Sockets versions. An application can successfully use a Windows Sockets DLL if there is any overlap in the version ranges. The following chart gives examples of how WSAStartup works in conjunction with different application and Windows Sockets DLL versions:

App versions	DLL Versions	wVersionRequested	wVersion	wHighVersion	End Result
1.1	1.1	1.1	1.1	1.1	use 1.1
1.0 1.1	1.0	1.1	1.0	1.0	use 1.0
1.0	1.0 1.1	1.0	1.0	1.1	use 1.0
1.1	1.0 1.1	1.1	1.1	1.1	use 1.1
1.1	1.0	1.1	1.0	1.0	Application fails
1.0	1.1	1.0	---	---	WSAVERNOTSUPPORTED
1.0 1.1	1.0 1.1	1.1	1.1	1.1	use 1.1
1.1 2.0	1.1	2.0	1.1	1.1	use 1.1
2.0	1.1	2.0	1.1	1.1	Application fails
The following code fragment demonstrates how an application that supports only version 1.1 of Windows Sockets makes a WSAStartup call:

WORD wVersionRequested;

WSADATA wsaData;

int err;

wVersionRequested = MAKEWORD(1, 1);

err = WSAStartup(wVersionRequested, &wsaData);

if (err != 0)

    /* Tell the user that we couldn't find a useable */

    /* winsock.dll.     */

    return;

/* Confirm that the Windows Sockets DLL supports 1.1.*/

/* Note that if the DLL supports versions greater */

/* than 1.1 in addition to 1.1, it will still return */

/* 1.1 in wVersion since that is the version we */

/* requested. */

if ( LOBYTE( wsaData.wVersion ) != 1 ||

        HIBYTE( wsaData.wVersion ) != 1 ) {

    /* Tell the user that we couldn't find a useable */

    /* winsock.dll. */

    WSACleanup();

    return;

}

/* The Windows Sockets DLL is acceptable. Proceed. */

This code fragment demonstrates how a Windows Sockets DLL that supports only version 1.1 performs the WSAStartup negotiation:

/* Make sure that the version requested is >= 1.1. */

/* The low byte is the major version and the high */

/* byte is the minor version.   */

if ( LOBYTE( wVersionRequested ) < 1 ||

        ( LOBYTE( wVersionRequested ) == 1 &&

        HIBYTE( wVersionRequested ) < 1 )

    return WSAVERNOTSUPPORTED;

/* Since we only support 1.1, set both wVersion and */

/* wHighVersion to 1.1. */

lpWsaData->wVersion = MAKEWORD( 1, 1 );

lpWsaData->wHighVersion = MAKEWORD( 1, 1 );

Once an application or DLL has made a successful WSAStartup call, it may proceed to make other Windows Sockets calls as needed. When it has finished using the services of the Windows Sockets DLL, the application or DLL must call WSACleanup in order to allow the Windows Sockets DLL to free any resources for the application.

Details of the actual Windows Sockets implementation are described in the WSAData structure defined as follows:

struct WSAData {

    WORD            wVersion;

    WORD            wHighVersion;

    char            szDescription[WSADESCRIPTION_LEN+1];

    char            szSystemStatus[WSASYSSTATUS_LEN+1];

    unsigned short  iMaxSockets;

    unsigned short  iMaxUdpDg;

    char FAR *      lpVendorInfo;

};

The members of this structure are:

Members	Usage
wVersion	The version of the Windows Sockets specification that the Windows Sockets DLL expects the caller to use.
wHighVersion	The highest version of the Windows Sockets specification that this DLL can support (also encoded as shown previously). Typically, this will be the same as wVersion.
szDescription	A null-terminated ASCII string into which the Windows Sockets DLL copies a description of the Windows Sockets implementation, including vendor identification. The text (up to 256 characters in length) may contain any characters, but vendors are cautioned against including control and formatting characters: the most likely use that an application will put this to is to display it (possibly truncated) in a status message.
szSystemStatus	A null-terminated ASCII string into which the Windows Sockets DLL copies relevant status or configuration information. The Windows Sockets DLL should use this field only if the information might be useful to the user or support staff: it should not be considered an extension of the szDescription field.
iMaxSockets	The maximum number of sockets that a single process can open. A Windows Sockets implementation can provide a global pool of sockets for allocation to any process; alternatively, it can allocate per-process resources for sockets. The number may well reflect the way the Windows Sockets DLL or the networking software was configured. Application writers may use this number as a crude indication of whether the Windows Sockets implementation is usable by the application. For example, an X Windows server might check iMaxSockets when first started: if it is less than 8, the application would display an error message instructing the user to reconfigure the networking software. (This is a situation in which the szSystemStatus text might be used.) Obviously, there is no guarantee that a particular application can actually allocate iMaxSockets sockets, since there may be other Windows Sockets applications in use.
iMaxUdpDg	The size, in bytes, of the largest UDP datagram that can be sent or received by a Windows Sockets application. If the implementation imposes no limit, iMaxUdpDg is zero. In many implementations of Berkeley sockets, there is an implicit limit of 8192 bytes on UDP datagrams (which are fragmented if necessary). A Windows Sockets implementation can impose a limit based, for instance, on the allocation of fragment reassembly buffers. The minimum value of iMaxUdpDg for a Windows Sockets-compliant implementation is 512. Note that regardless of the value of iMaxUdpDg, it is inadvisable to attempt to send a broadcast datagram larger than the Maximum Transmission Unit (MTU) for the network. (Windows Sockets does not provide a mechanism to discover the MTU, but it must be no less than 512 bytes.)
lpVendorInfo	A far pointer to a vendor-specific data structure. The definition of this structure (if supplied) is beyond the scope of this documentation.
An application or DLL can call WSAStartup more than once if it needs to obtain the WSAData structure information more than once. However, the wVersionRequired parameter is assumed to be the same on all calls to WSAStartup; that is, an application or DLL cannot change the version of Windows Sockets it expects after the initial call to WSAStartup.

There must be one WSACleanup call corresponding to every WSAStartup call to allow third-party DLLs to make use of a Windows Sockets DLL on behalf of an application. This means, for example, that if an application calls WSAStartup three times, it must call WSACleanup three times. The first two calls to WSACleanup do nothing except decrement an internal counter; the final WSACleanup call for the task deallocates all necessary resources for the task.

See Also

send, sendto, WSACleanup


WSAUnhookBlockingHook
 WSAUnhookBlockingHook  QuickInfo

The Windows Sockets WSAUnhookBlockingHook function restores the default blocking hook function.

int WSAUnhookBlockingHook(

void
);
Remarks

This function removes any previous blocking hook that has been installed and reinstalls the default blocking mechanism.

WSAUnhookBlockingHook will always install the default mechanism, not the previous mechanism. If an application needs to nest blocking hooks — that is, to establish a temporary blocking hook function and then revert to the previous mechanism (whether the default or one established by an earlier WSASetBlockingHook) — it must save and restore the value returned by WSASetBlockingHook; it cannot use WSAUnhookBlockingHook.

In multithreaded versions of Windows such as Windows NT, there is no default blocking hook. Calling WSAUnhookBlockingHook disables any blocking hook installed by the application and any blocking calls made block the thread that made the call.

Return Value

The return value is zero if the operation was successful. Otherwise, the value SOCKET_ERROR is returned, and a specific error number may be retrieved by calling WSAGetLastError.

Error Codes

WSANOTINITIALISED	A successful WSAStartup must occur before using this function.
See Also

WSASetBlockingHook


wsprintf
 wsprintf  QuickInfo  Overview  Group

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,	// address of buffer for output
LPCTSTR  lpFmt	// address of format-control string
...	// optional arguments
);
Parameters

lpOut

Points to a buffer to receive the formatted output.

lpFmt

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

...

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 Value

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 format-control string. 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 character sequences:
Sequence	Insert
c	A single character. The wsprintf function ignores character arguments with a numeric value of zero. This sequence is interpreted as type WCHAR when the calling application uses the #define UNICODE compile flag and as type CHAR otherwise.
C	A single character. This sequence is interpreted as type CHAR when the calling application uses the #define UNICODE compile flag and as type WCHAR otherwise.
d	A signed decimal integer argument. This sequence is equivalent to the i sequence.
hc, hC	A single character. The wsprintf function ignores character arguments with a numeric value of zero. This sequence is always interpreted as type CHAR, even when the calling application uses the #define UNICODE compile flag.
hs, hS	A string. This sequence is always interpreted as type LPSTR, even when the calling application uses the #define UNICODE compile flag.
i	A signed decimal integer. This sequence is equivalent to the d sequence.
lc, lC	A single character. The wsprintf function ignores character arguments with a numeric value of zero. This sequence is always interpreted as type WCHAR, even when the calling application does not use the #define UNICODE compile flag.
ld	A long signed decimal integer. This sequence is equivalent to the li sequence.
li	A long signed decimal integer. This sequence is equivalent to the ld sequence.
ls, lS	A string. This sequence is always interpreted as type LPWSTR, even when the calling application does not use the #define UNICODE compile flag. This sequence is equivalent to the ws sequence.
lu	A long unsigned integer.
lx, lX	A long unsigned hexadecimal integer in lowercase or uppercase.
s	A string. This sequence is interpreted as type LPWSTR when the calling application uses the #define UNICODE compile flag and as type LPSTR otherwise.
S	A string. This sequence is interpreted as type LPSTR when the calling application uses the #define UNICODE compile flag and as type LPWSTR otherwise.
u	An unsigned integer argument.
x, X	An unsigned hexadecimal integer in lowercase or uppercase.
Note  Unlike other Windows functions, wsprintf uses the C calling convention (_cdecl), rather than the Pascal 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.

See Also

wvsprintf


wvsprintf
 wvsprintf  QuickInfo  Overview  Group

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,	// address of buffer for output
LPCTSTR  lpFormat,	// address of format-control string
va_list  arglist	// variable argument list of format-control arguments
);
Parameters

lpOutput

Points to a buffer to receive the formatted output.

lpFormat

Points 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 wsprintf function.

arglist

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 Value

If the function succeeds, the return value is the number of characters stored in the buffer, not counting the terminating null character.

If the function fails, the return value is less than the length of the format-control string. 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.

See Also

wsprintf


Yield
 Yield  Overview  Group

The Yield function is obsolete. In the Win32-based application programming interface (API), this function does nothing.

Threads that contain windows should use the DispatchMessage, PeekMessage, or TranslateMessage functions. The message-loop functions handle message synchronization properly and yield at the appropriate times.

Threads that do not contain windows should use the Sleep function with a sleep time of zero milliseconds to give up the remainder of their current time slice.

See Also

DispatchMessage, PeekMessage, Sleep, TranslateMessage


ZeroMemory
 ZeroMemory  QuickInfo  Overview  Group

The ZeroMemory function fills a block of memory with zeros.

VOID ZeroMemory(

PVOID  Destination	// address of block to fill with zeros
DWORD  Length	// size, in bytes, of block to fill with zeros
);
Parameters

Destination

Points to the starting address of the block of memory to fill with zeros.

Length

Specifies the size, in bytes, of the block of memory to fill with zeros.

Return Value

This function has no return value.

See Also

CopyMemory, FillMemory, MoveMemory


 Interfaces

The following interfaces are arranged in alphabetical order by interface name. The methods are listed following their interfaces.

The shell interfaces and methods are used with shell extensions, shell links, name spaces, and appbars. The rich edit OLE interfaces and methods are used with rich text edit controls.

•	Shell Library Interfaces

IContextMenu
ICopyHook
IEnumIDList
IExtractIcon
IShellExtInit
IShellFolder
IShellLink
IShellPropSheetExt

•	Rich Edit OLE Interfaces

IRichEditOle
IRichEditOleCallback


IContextMenu [New - Windows 95]
 IContextMenu

[New - Windows 95]

Designates an interface that enables the shell to retrieve extensions to context menus.

Methods in Vtable Order

IUnknown Methods	Description
QueryInterface	Returns pointers to supported interfaces.
AddRef	Increments reference count.
Release	Decrements reference count.
IContextMenu Methods	Description
QueryContextMenu	Adds commands to a context menu.
InvokeCommand	Carries out a menu command, either in response to user input or otherwise. For an example, see IExtractIcon.
GetCommandString	Retrieves the language-independent name of a menu command or the help text for a menu command.


IContextMenu::GetCommandString [New - Windows 95]
 IContextMenu::GetCommandString  QuickInfo

[New - Windows 95]

Retrieves the language-independent command string or the help text for a context menu item.

HRESULT STDMETHODCALLTYPE GetCommandString(

LPCONTEXTMENU pIface,
UINT idCmd,
UINT uFlags,
UINT *pwReserved,
LPSTR pszName,
UINT cchMax
);
Parameters

pIface

Pointer to the IContextMenu interface. In C++, this parameter is implicit.

idCmd

Menu item identifier offset.

uFlags

Flag specifying the information to retrieve. This parameter can be one of the following values:

Value	Meaning
GCS_HELPTEXT	Returns the help text for the menu item.
GCS_VALIDATE	Validates that the menu item exists.
GCS_VERB	Returns the language-independent command name for the menu item.
pwReserved

Reserved. Applications must specify NULL when calling this method, and handles must ignore this parameter when called.

pszName and cchMax

Address and size of the buffer that receives the null-terminated string.

Return Value

Returns NOERROR if successful or an OLE-defined error code otherwise.

The language-independent command name is a name that can be passed to the IContextMenu::InvokeCommand method to activates a command by an application. The help text is a description that the Explorer displays in its status bar; it should be reasonably short (under 40 characters).

See Also

IContextMenu


IContextMenu::InvokeCommand [New - Windows 95]
 IContextMenu::InvokeCommand  QuickInfo

[New - Windows 95]

Carries out the command associated with a context menu item.

HRESULT STDMETHODCALLTYPE InvokeCommand(

LPCONTEXTMENU pIface,
LPCMINVOKECOMMANDINFO lpici
);
Parameters

pIface

Pointer to the IContextMenu interface. In C++, this parameter is implicit.

lpici

Pointer to a CMINVOKECOMMANDINFO structure containing information about the command.

Return Value

Returns NOERROR if successful or an OLE-defined error code otherwise.

The shell calls this method when the user chooses a command that the handler added to a context menu. This method may also be called by an application without any corresponding user action.

See Also

CMINVOKECOMMANDINFO, IContextMenu


IContextMenu::QueryContextMenu [New - Windows 95]
 IContextMenu::QueryContextMenu  QuickInfo

[New - Windows 95]

Adds menu items to the specified menu. The menu items should be inserted at a given position in the menu, and their menu item identifiers must be in a given range.

HRESULT STDMETHODCALLTYPE QueryContextMenu(

LPCONTEXTMENU pIface,
HMENU hmenu,
UINT indexMenu,
UINT idCmdFirst,
UINT idCmdLast,
UINT uFlags
);
Parameters

pIface

Pointer to the IContextMenu interface. In C++, this parameter is implicit.

hmenu

Handle of the menu. The handler should specify this handle when calling the InsertMenu or InsertMenuItem function.

indexMenu

Zero-based position at which to insert the first menu item.

idCmdFirst and idCmdLast

Minimum and maximum values that the handler can specify for menu item identifiers. The actual identifier of each menu item should be idCmdFirst plus a menu identifier offset in the range zero through (idCmdLast − idCmdFirst).

uFlags

Flag specifying zero or more of the following values:

CMF_DEFAULTONLY	The user is activating the default action, typically by double-clicking. A context menu extension or drag and drop handler should not add any menu items if this value is specified. A name space extension should add only the default item (if any).
CMF_EXPLORER	Context menu handlers should ignore this value. This value is specified if the context menu is for an object in the left pane of the explorer.
CMF_NORMAL	Indicates normal operation. A context menu extension, name space extension, or drag and drop handler can add any menu items.
CMF_VERBSONLY	Context menu handlers should ignore this value. This value is specified if the context menu is for a shortcut object.
The remaining bits of the low-order word are reserved by the system. The high-order word may be used for context-specific communications.

Return Value

Returns an HRESULT structure in which, if the method is successful, the code member contains the menu identifier offset of the last menu item added.

See Also

IContextMenu, InsertMenu, InsertMenuItem


ICopyHook [New - Windows 95]
 ICopyHook

[New - Windows 95]

Designates an interface that allows a copy hook handler to prevent a folder or printer object from being copied, moved, deleted, or renamed. The shell calls a copy hook handler whenever file system directories are about to be copied, moved, deleted, or renamed, as well as whenever the status of a printer is about to change.

The shell initializes the copy hook handler interface directly — that is, without using the IShellExtInit interface first. A folder object can have multiple copy hook handlers. A copy hook handler interface has one method, CopyCallBack.

Methods in Vtable Order

IUnknown Methods	Description
QueryInterface	Returns pointers to supported interfaces.
AddRef	Increments reference count.
Release	Decrements reference count.
IContextMenu Methods	Description
CopyCallBack	Carries out a move, copy, delete, or rename operation on a folder object, or prevents the shell from carrying out the operation.


ICopyHook::CopyCallback [New - Windows 95]
 ICopyHook::CopyCallback  QuickInfo

[New - Windows 95]

Either allows the shell to carry out a move, copy, delete, or rename operation on a folder object, or prevents the shell from carrying out the operation. The shell calls each copy hook handler registered for a folder object until either all the handlers have been called or any handler returns IDCANCEL.

HRESULT STDMETHODCALLTYPE CopyCallback(

ICopyHook FAR * pCopyHook,
HWND hwnd,
UINT wFunc,
UINT wFlags,
LPCSTR pszSrcFile,
DWORD dwSrcAttribs,
LPCSTR pszDestFile,
DWORD dwDestAttribs
);
Parameters

pCopyHook

Pointer to the ICopyHook interface. In C++, this parameter is implicit.

hwnd

Handle of the window that the copy hook handler should use as the parent window for any user interface elements the handler may need to display. If FOF_SILENT is specified, the method should ignore this parameter.

wFunc

Operation to perform. This parameter can be one of the following values:

FO_COPY	Copies the file specified by pszSrcFile to the location specified by pszDestFile.
FO_DELETE	Deletes the file specified by pszSrcFile.
FO_MOVE	Moves the file specified by pszSrcFile to the location specified by pszDestFile.
FO_RENAME	Renames the file specified by pszSrcFile.
PO_DELETE	Deletes the printer specified by pszSrcFile.
PO_PORTCHANGE	Changes the printer port. The pszSrcFile and pszDestFile parameters contain double null-terminated lists of strings. Each list contains the printer name followed by the port name. The port name in pszSrcFile is the current printer port, and the port name in pszDestFile is the new printer port.
PO_RENAME	Renames the printer specified by pszSrcFile.
PO_REN_PORT	Combination of PO_RENAME and PO_PORTCHANGE.
wFlags

Flags that control the operation. This parameter can be a combination of the following values:

FOF_ALLOWUNDO	Preserves undo information (if possible).
FOF_CONFIRMMOUSE	Not implemented.
FOF_FILESONLY	Not implemented. The shell calls a copy hook handler only for folder objects, not files.
FOF_MULTIDESTFILES	The SHFileOperation function specified multiple destination files (one for each source file) rather than one directory where all the source files are to be deposited. A copy hook handler typically ignores this value.
FOF_NOCONFIRMATION	Responds with "yes to all" for any dialog box that is displayed.
FOF_NOCONFIRMMKDIR	Does not confirm the creation of any needed directories if the operation requires a new directory to be created.
FOF_RENAMEONCOLLISION	Gives the file being operated on a new name (such as, "Copy #1 of ...") in a copy, move, or rename operation if a file of the target name already exists.
FOF_SILENT	Displays no progress dialog box.
FOF_SIMPLEPROGRESS	Displays a progress dialog box, but the dialog box does not show the names of the files.
pszSrcFile

Pointer to a string that contains the name of the source file.

dwSrcAttribs

Attributes of the source file. This parameter can be a combination of any of the file attribute flags (FILE_ATTRIBUTE_*) defined in the Windows header files.

pszDestFile

Pointer to a string that contains the name of the destination file.

dwDestAttribs

Attributes of the source file. This parameter can be a combination of any of the file attribute flags (FILE_ATTRIBUTE_*) defined in the Windows header files.

Return Value

Returns an integer value that indicates whether the shell should perform the operation. It can be one of the following values:

IDYES	Allows the operation.
IDNO	Prevents the operation on this file, but continues with any other operations (for example, a batch copy operation).
IDCANCEL	Prevents the current operation and cancels any pending operations.
See Also

ICopyHook


IEnumIDList [New - Windows 95]
 IEnumIDList

[New - Windows 95]

Designates an interface used to enumerate item identifiers. The IShellFolder::EnumObjects method creates an IEnumIDList interface.

Methods in Vtable Order

IUnknown Methods	Description
QueryInterface	Returns pointers to supported interfaces.
AddRef	Increments reference count.
Release	Decrements reference count.
IEnumIDList Methods	Description
Clone	Creates a new item enumeration object having the same contents and state as the given one.
Next	Retrieves one or more item identifiers and advances the current position.
Reset	Returns to the beginning of the enumeration sequence.
Skip	Skips over one or more items in the enumeration sequence.


IEnumIDList::Clone [New - Windows 95]
 IEnumIDList::Clone  QuickInfo

[New - Windows 95]

Creates a new item enumeration object with the same contents and state as the current one.

HRESULT STDMETHODCALLTYPE Clone(

IEnumIDList FAR * pEnumIDList,
IEnumIDList **ppenum
);
Parameters

pEnumIDList

Pointer to the IEnumIDList interface. In C++, this parameter is implicit.

ppenum

Address that receives a pointer to the new enumeration object. The calling application must eventually free the new object by calling its Release method.

Return Value

Returns NOERROR if successful or an OLE-defined error value otherwise.

This method makes it possible to record a particular point in the enumeration sequence and then return to that point at a later time.

See Also

IEnumIDList


IEnumIDList::Next [New - Windows 95]
 IEnumIDList::Next  QuickInfo

[New - Windows 95]

Retrieves the specified number of item identifiers in the enumeration sequence and advances the current position.

HRESULT STDMETHODCALLTYPE Next(

EnumIDList FAR * pEnumIDList,
LONG celt,
PITEMIDLIST *rgelt,
LONG *pceltFetched
);
Parameters

EnumIDList

Address of the IEnumIDList interface. In C++, this parameter is implicit.

celt

Number of item identifiers to retrieve. If the number of identifiers requested is more than remains in the sequence, only the remaining elements are retrieved.

rgelt

Address of an array in which to return the item identifiers. The calling application is responsible for freeing the returned item identifier lists by using the shell's allocator.

pceltFetched

Pointer to a value that receives a count of the item identifiers actually returned in rgelt. This parameter can be NULL if (and only if) celt is one.

Return Value

Returns NOERROR if successful, S_FALSE if there are no more items in the enumeration sequence, or an OLE-defined error value if an error occurs.

If this method returns any value other than NOERROR, no entries in the rgelt array are valid on exit. They are all in an indeterminate state.

See Also

IEnumIDList


IEnumIDList::Reset [New - Windows 95]
 IEnumIDList::Reset  QuickInfo

[New - Windows 95]

Returns to the beginning of the enumeration sequence.

HRESULT STDMETHODCALLTYPE Reset(

IEnumIDList FAR * pEnumIDList
);
Parameter

pEnumIDList

Pointer to the IEnumIDList interface. In C++, this parameter is implicit.

Return Value

Returns NOERROR if successful or an OLE-defined error value otherwise.

See Also

IEnumIDList


IEnumIDList::Skip [New - Windows 95]
 IEnumIDList::Skip  QuickInfo

[New - Windows 95]

Skips over the specified number of elements in the enumeration sequence.

HRESULT STDMETHODCALLTYPE Skip(

IEnumIDList FAR * pEnumIDList,
ULONG celt
);
Parameters

pEnumIDList

Pointer to the IEnumIDList interface. In C++, this parameter is implicit.

celt

Number of item identifiers to skip.

Return Value

Returns NOERROR if successful or an OLE-defined error value otherwise.

See Also

IEnumIDList


IExtractIcon [New - Windows 95]
 IExtractIcon

[New - Windows 95]

Designates an interface that enables the shell to retrieve icons for file objects or folders.

Methods in Vtable Order

IUnknown Methods	Description
QueryInterface	Returns pointers to supported interfaces.
AddRef	Increments reference count.
Release	Decrements reference count.
IExtractIcon Methods	Description
GetIconLocation	Retrieves the icon location for a file object.
ExtractIcon	Extracts an icon from the specified location.


IExtractIcon::Extract [New - Windows 95]
 IExtractIcon::Extract  QuickInfo

[New - Windows 95]

Extracts an icon image from the specified location.

HRESULT STDMETHODCALLTYPE Extract(

LPEXTRACTICON pIface,
LPCSTR pszFile,
UINT nIconIndex,
HICON *phiconLarge,
HICON *phiconSmall,
UINT nIconSize
);
Parameters

pIface

Pointer to the IExtractIcon interface. In C++, this parameter is implicit.

pszFile

Pointer to a null-terminated string specifying the icon location.

nIconIndex

Icon index.

phiconLarge and phiconSmall

Addresses of variables that receive the handles of the large and small icons, respectively.

nIconSize

Value specifying the size, in pixels, of the large icon required. The size specified can be the width or height. The width of an icon always equals its height.

Return Value

Returns NOERROR if the function extracted the icon or S_FALSE if the calling application should extract the icon.

The icon location and index are the same values returned by the IExtractIcon::GetIconLocation method. If this function returns S_FALSE, these values must specify an icon filename and index. If this function does not return S_FALSE, the calling application should make no assumptions about the meanings of the pszFile and nIconIndex parameters.

See Also

IExtractIcon, IExtractIcon::GetIconLocation


IExtractIcon::GetIconLocation [New - Windows 95]
 IExtractIcon::GetIconLocation  QuickInfo

[New - Windows 95]

Retrieves the location and index of an icon.

HRESULT STDMETHODCALLTYPE GetIconLocation(

LPEXTRACTICON pIface,
UINT uFlags,
LPSTR szIconFile,
INT cchMax,
int *piIndex,
UINT *pwFlags
);
Parameters

pIface

Pointer to the IExtractIcon interface. In C++, this parameter is implicit.

uFlags

Flags. This parameter can be zero or the following values:

GIL_FORSHELL	The icon is to be displayed in a shell folder.
GIL_OPENICON	The icon is for a folder that is open.
szIconFile and cchMax

Address and size of the buffer that receives the icon location. The icon location is a null-terminated string that typically specifies the name of an icon file.

piIndex

Pointer to an integer that receives the icon index.

pwFlags

Pointer to an unsigned integer that receives zero or more of the following values:

GIL_DONTCACHE	The icon should not be cached.
GIL_NOTFILENAME	The location is not a filename. To extract the icon from the location, use the IExtractIcon::Extract method.
GIL_PERCLASS	All file objects of this class have the same icon.
GIL_PERINSTANCE	Each file object of this class has its own icon.
GIL_SIMULATEDOC	The shell should create a document icon using the specified icon.
Return Value

Returns NOERROR if the function returned a valid location or S_FALSE if the shell should use a default icon.

See Also

IExtractIcon, IExtractIcon::Extract


IRichEditOle [New - Windows NT]
 IRichEditOle

[New - Windows NT]

Specifies an interface used by the client of a rich text edit control to carry out OLE-related operations. The IRichEditOle interface has the following methods:

Methods in Vtable Order

IUnknown Methods	Description
QueryInterface	Returns pointers to supported interfaces.
AddRef	Increments reference count.
Release	Decrements reference count.
IRichEditOle Methods	Description
GetClientSite	Retrieves an IOleClientSite interface to use when creating a new object.
GetObjectCount	Returns the number of objects contained in a rich edit control.
GetLinkCount	Returns the number of objects in a rich edit control that are links.
GetObject	Returns information from a REOBJECT structure about an object in a rich edit control.
InsertObject	Inserts an object into a rich edit control.
ConvertObject	Converts an object to a new type.
ActivateAs	Unloads objects of the old class, telling OLE to treat those objects as objects of the new class, and reloading the objects.
SetHostNames	Sets the "host names" to be given to objects as they are inserted to a rich edit control.
SetLinkAvailable	Sets the value of the link available bit in the object's flags.
SetDvaspect	Sets the aspect that a rich edit control uses to draw an object.
HandsOffStorage	Tells a rich edit control to release its reference to the storage interface associated with the specified object.
SaveCompleted	Tells a rich edit control that the most recent save operation has been completed, and that it should hold on to a different storage for the object.
InPlaceDeactivate	Tells a rich edit control to deactivate the currently active in-place object, if any.
ContextSensitiveHelp	Tells a rich edit control to transition into or out of context-sensitive help mode.
GetClipboardData	Retrieves a clipboard object for a range in an edit control.
ImportDataObject	Imports a clipboard object into a rich edit control, replacing the current selection.


IRichEditOle::ActivateAs [New - Windows NT]
 IRichEditOle::ActivateAs

[New - Windows NT]

Handles OLE "Activate As" behavior by unloading all objects of the old class, telling OLE to treat those objects as objects of the new class, and reloading the objects. If objects cannot be reloaded, they are deleted.

HRESULT ActivateAs(

REFCLSID rclsid,
REFCLSID rclsidAs
);
Parameters

rclsid

Class identifier of the old class.

rclsidAs

Class identifier of the new class.

Return Value

Returns success status. Use GetScode to retrieve an SCODE. Can be S_OK on success or an SCODE returned from OLE.

See Also

IRichEditOle


IRichEditOle::ContextSensitiveHelp [New - Windows NT]
 IRichEditOle::ContextSensitiveHelp

[New - Windows NT]

Tells a rich edit control that it should transition into or out of context sensitive help mode. A rich edit control calls the ContextSensitiveHelp method of any in place object which is currently active if a state change is occuring.

HRESULT ContextSensitiveHelp(

BOOL fEnterMode
);
Parameter

fEnterMode

TRUE if entering context sensitive help mode; otherwise, FALSE.

Return Value

Returns success status. Can use GetScode to retrieve an SCODE. Can be S_OK on success or some other value returned by OLE.

See Also

IRichEditOle


IRichEditOle::ConvertObject [New - Windows NT]
 IRichEditOle::ConvertObject

[New - Windows NT]

Converts an object to a new type. This call does reload the object but does not force an update; the caller must do this.

HRESULT ConvertObject(

LONG iob,
REFCLSID rclsidNew,
LPCSTR lpstrUserTypeNew
);
Parameters

iob

Index of the object to convert. If this parameter is REO_IOB_SELECTION, the selected object is to be converted.

rclsidNew

Class identifier of the class to which the object is to be converted.

szUserTypeNew

User-visible type name of the class to which the object is to be converted.

Return Value

Returns success status. Use GetScode to retrieve an SCODE. Can be S_OK on success or E_INVALIDARG if the index is invalid, or an SCODE returned from OLE.

See Also

IRichEditOle


IRichEditOle::GetClientSite [New - Windows NT]
 IRichEditOle::GetClientSite

[New - Windows NT]

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
);
Parameter

lplpoleclientsite

Pointer to the pointer variable that receives the address of the IOleClientSite interface.

Return Value

Returns success status. Use GetScode to retrieve an SCODE. Can be S_OK on success or E_OUTOFMEMORY if memory could not be allocated for the client site.

See Also

IRichEditOle


IRichEditOle::GetClipboardData [New - Windows NT]
 IRichEditOle::GetClipboardData

[New - Windows NT]

Retrieves a clipboard object for a range in an edit control.

HRESULT GetClipboardData(

CHARRANGE FAR * lpchrg,
DWORD reco,
LPDATAOBJECT FAR * lplpdataobj
);
Parameters

lpchrg

Pointer to the CHARRANGE structure specifying the range to create the clipboard object for.

reco

Clipboard operation flag. Can be one of these values.

RECO_COPY	Copy to the clipboard.
RECO_CUT	Cut to the clipboard.
RECO_DRAG	Drag operation (drag and drop)
RECO_DROP	Drop operation (drag and drop).
RECO_PASTE	Paste from the clipboard.
lplpdataobj

Pointer to the DATAOBJECT structure that receives the clipboard object representing the range specified in the lpchrg parameter.

Return Value

Returns success status.

See Also

CHARRANGE, IRichEditOle


IRichEditOle::GetLinkCount [New - Windows NT]
 IRichEditOle::GetLinkCount

[New - Windows NT]

Returns the number of objects in a rich edit control that are links.

LONG GetLinkCount();

Return Value

Returns the number of links.

See Also

IRichEditOle


IRichEditOle::GetObject [New - Windows NT]
 IRichEditOle::GetObject

[New - Windows NT]

Returns information from a REOBJECT structure about an object in a rich edit control.

HRESULT GetObject(

LONG iob,
REOBJECT FAR * lpreobject,
DWORD dwFlags
);
Parameters

iob

Zero-based index specifying which object to return information about. If this parameter is REO_IOB_USE_CP, information about the object at the character position specified by the REOBJECT structure is returned.

lpreobject

Pointer to a REOBJECT structure that receives information about the object. The reference count of the interfaces returned in this structure has been incremented; it is the responsibility of the caller to use the Release function to decrement the count.

dwFlags

Operation flags specifying which interfaces to return in the structure. Can be a combination of these values:

REO_GETOBJ_POLEOBJ	Get OLE object interface.
REO_GETOBJ_PSTG	Get Storage interface.
REO_GETOBJ_POLESITE	Get OLE site interface.
REO_GETOBJ_NO_INTERFACES	Get no interfaces.
REO_GETOBJ_ALL_INTERFACES	Get all interfaces.
Return Value

Returns success status. Use GetScode to retrieve an SCODE. Can be S_OK on success or E_INVALIDARG if no buffer for the REOBJECT structure was given, or the iob or character position is invalid.

See Also

IRichEditOle, REOBJECT


IRichEditOle::GetObjectCount [New - Windows NT]
 IRichEditOle::GetObjectCount

[New - Windows NT]

Returns the number of objects currently contained in a rich edit control.

LONG GetObjectCount();

Return Value

Returns the number of objects.

See Also

IRichEditOle


IRichEditOle::HandsOffStorage [New - Windows NT]
 IRichEditOle::HandsOffStorage

[New - Windows NT]

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
);
Parameter

iob

Index of the object whose storage is to be released. If this parameter is REO_IOB_SELECTION, the selected object's storage is to be released.

Return Value

Returns success status. Use GetScode to retrieve an SCODE. Can be S_OK on success or E_INVALIDARG if the index is invalid.

See Also

IPersistStorage::HandsOffStorage, IRichEditOle


IRichEditOle::ImportDataObject [New - Windows NT]
 IRichEditOle::ImportDataObject

[New - Windows NT]

Imports a clipboard object into a rich edit control, replacing the current selection.

HRESULT ImportDataObject(

LPDATAOBJECT lpdataobj,
CLIPFORMAT cf,
HGLOBAL hMetaPict
);
Parameters

lpdataobj

Pointer to a DATAOBJECT structure specifying the clipboard object to import.

cf

Clipboard format to use or zero to use the best available format.

hMetaPict

Handle to a metafile containing the icon view of an object. Used only if the DVASPECT_ICON display aspect is required by Paste Special command.

Return Value

Returns success status.

See Also

IRichEditOle


IRichEditOle::InPlaceDeactivate [New - Windows NT]
 IRichEditOle::InPlaceDeactivate

[New - Windows NT]

Tells a rich edit control to deactivate the currently active in-place object, if any.

HRESULT InPlaceDeactivate();

Return Value

Returns success status. Can use GetScode to retrieve an SCODE. Can be S_OK on success or some other value returned by OLE. No error is returned if there is no active in-place object.

See Also

IRichEditOle


IRichEditOle::InsertObject [New - Windows NT]
 IRichEditOle::InsertObject

[New - Windows NT]

Inserts an object into a rich edit control.

HRESULT InsertObject(

REOBJECT FAR * lpreobject
);
Parameter

lpreobject

Pointer to a REOBJECT structure containing the object information and interfaces. The rich edit control automatically increments the reference count for the interfaces if it holds onto them, so the caller can safely release the interfaces if not needed.

Return Value

Returns success status. Use GetScode to retrieve an SCODE. Can be S_OK on success or E_OUTOFMEMORY if memory could not be allocated to insert the object.

If the cp member of the REOBJECT structure is REO_CP_SELECTION, the selection is replaced with the specified object.

See Also

IRichEditOle, REOBJECT


IRichEditOle::SaveCompleted [New - Windows NT]
 IRichEditOle::SaveCompleted

[New - Windows NT]

Tells a rich edit control that the most recent save operation has been completed, and that it should hold on to a different storage for the object.

HRESULT SaveCompleted(

LONG iob,
LPSTORAGE lpstg
);
Parameters

iob

Index of the object whose storage is being specified. If this parameter is REO_IOB_SELECTION, the selected object is used.

pstg

New storage for the object. If the storage is not NULL, the rich edit control releases any storage it is currently holding for the object, and uses this new storage instead.

Return Value

Returns success status. Use GetScode to retrieve an SCODE. Can be S_OK on success or E_INVALIDARG if the index is invalid.

See Also

IRichEditOle


IRichEditOle::SetDvaspect [New - Windows NT]
 IRichEditOle::SetDvaspect

[New - Windows NT]

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 Value

Returns success status. Use GetScode to retrieve an SCODE. Can be S_OK on success or E_INVALIDARG if the index is invalid.

See Also

IRichEditOle


IRichEditOle::SetHostNames [New - Windows NT]
 IRichEditOle::SetHostNames

[New - Windows NT]

Sets the "host names" to be given to objects as they are inserted to a rich edit control. The host names are used in the user interface of servers to describe the container context of opened objects.

HRESULT SetHostNames(

LPCSTR lpstrContainerApp,
LPCSTR lpstrContainerObj
);
Parameters

szContainerApp

Null-terminated name of the container application.

szContainerObj

Null-terminated name of the container document or object.

Return Value

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.

See Also

IRichEditOle


IRichEditOle::SetLinkAvailable [New - Windows NT]
 IRichEditOle::SetLinkAvailable

[New - Windows NT]

Sets the value of the link available bit in the object's flags. The link available bit defaults to TRUE. It should be set to FALSE if any errors occur on the link which would indicate problems connecting to the linked object or application. When those problems are repaired, the bit should be set to TRUE again.

HRESULT SetLinkAvailable(

LONG iob,
BOOL fAvailable
);
Parameters

iob

Index of object whose bit is to be set. If this parameter is REO_IOB_SELECTION, the bit on the selected object is to be set.

fAvailable

Value to set the bit to. Can be TRUE or FALSE.

Return Value

Returns success status. Use GetScode to retrieve an SCODE. Can be S_OK on success or E_INVALIDARG if the index is invalid.

See Also

IRichEditOle


IRichEditOleCallback [New - Windows NT]
 IRichEditOleCallback

[New - Windows NT]

Specifies an interface used by a rich text edit control to retrieve OLE-related information from its client. A rich edit control's client is responsible for implementing this interface and assigning it to the control by using the EM_SETOLEINTERFACE message. The IRichEditOleCallback interface has the following methods:

Methods in Vtable Order

IUnknown Methods	Description
QueryInterface	Returns pointers to supported interfaces.
AddRef	Increments reference count.
Release	Decrements reference count.
IRichEditOleCallback Methods	Description
GetNewStorage	Provides storage for a new object pasted from the clipboard or read in from an RTF stream.
GetInPlaceContext	Provides the application and document level interfaces and information required to support in-place activation.
ShowContainerUI	Tells the application whether to display its container user interface.
QueryInsertObject	Queries the application as to whether an object should be inserted.
DeleteObject	Notification that an object is about to be deleted from a rich edit control.
QueryAcceptData	Called on a paste or drag to determine if the data pasted/dragged should be accepted.
ContextSensitiveHelp	Tells the application that it should transition into or out of context sensitive help mode.
GetClipboardData	Allows the client to supply its own clipboard object.
GetDragDropEffect	Allows the client to specify the effects of a drop operation.
GetContextMenu	Queries the application for a context menu to use on a right mouse button down event.


IRichEditOleCallback::ContextSensitiveHelp [New - Windows NT]
 IRichEditOleCallback::ContextSensitiveHelp

[New - Windows NT]

Tells the application that it should transition into or out of context sensitive help mode. This member should implement the functionality described for IOleInPlaceSite::ContextSensitiveHelp (as described in the OLE documentation).

HRESULT ContextSensitiveHelp(

BOOL fEnterMode
);
Parameter

fEnterMode

TRUE if entering context sensitive help mode; otherwise, FALSE.

Return Value

Returns success status.

See Also

IRichEditOleCallback


IRichEditOleCallback::DeleteObject [New - Windows NT]
 IRichEditOleCallback::DeleteObject

[New - Windows NT]

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
);
Parameter

lpoleobj

Pointer to the OLEOBJECT structure specifying the object that is being deleted.

Return Value

No return value.

See Also

IRichEditOleCallback


IRichEditOleCallback::GetClipboardData [New - Windows NT]
 IRichEditOleCallback::GetClipboardData

[New - Windows NT]

Allows the client to supply its own clipboard object.

HRESULT GetClipboardData(

CHARRANGE FAR * lpchrg,
DWORD reco,
LPDATAOBJECT FAR * lplpdataobj
);
Parameters

lpchrg

Pointer to the CHARRANGE structure specifying the range the clipboard object is for.

reco

Clipboard operation flag. Can be one of these values.

RECO_COPY	Copy to the clipboard.
RECO_CUT	Cut to the clipboard.
RECO_DRAG	Drag operation (drag and drop)
RECO_DROP	Drop operation (drag and drop).
RECO_PASTE	Paste from the clipboard.
lplpdataobj

Pointer to the pointer variable that receives the address of the IDataObject implementation representing the range specified in the lpchrg parameter. The value of lppdataobj is ignored if an error is returned.

Return Value

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.

See Also

CHARRANGE, IDataObject, IRichEditOleCallback


IRichEditOleCallback::GetContextMenu [New - Windows NT]
 IRichEditOleCallback::GetContextMenu

[New - Windows NT]

Queries the application for a context menu to use on a right mouse down.

HRESULT GetContextMenu(

WORD seltyp,
LPOLEOBJECT lpoleobj,
CHARRANGE FAR * lpchrg,
HMENU FAR * lphmenu
);
Parameters

seltype

selection type

lpoleobj

Pointer to a OLEOBJECT structure specifying the first selected OLE object if the selection contains one or more objects NULL otherwise. The caller must use AddRef to increment the object reference count if it holds onto it.

lpchrg

Pointer to a CHARRANGE structure containing the current selection.

lphmenu

Pointer to a variable containing the handle of a context menu to use. This parameter is ignored if an error is returned. A rich edit control destroys the menu when it is finished with it so the client should not.

Return Value

Returns success status.

See Also

CHARRANGE, IRichEditOleCallback


IRichEditOleCallback::GetDragDropEffect [New - Windows NT]
 IRichEditOleCallback::GetDragDropEffect

[New - Windows NT]

Allows the client to specify the effects of a drop operation.

HRESULT GetDragDropEffect(

BOOL fDrag,
DWORD grfKeyState,
LPDWORD pdwEffect
);
Parameters

fDrag

TRUE if the query is for a IDropTarget::DragEnter or IDropTarget::DragOver FALSE if the query is for IDropTarget::Drop.

grfKeyState

Key state as defined by OLE.

pdwEffect

Pointer to the variable that contains the effect normally used by a rich edit control. On return, the variable is set to the effect to use.

Return Value

No return value.

See Also

IDropTarget::DragEnter, IDropTarget::DragOver, IDropTarget::Drop IRichEditOleCallback


IRichEditOleCallback::GetInPlaceContext [New - Windows NT]
 IRichEditOleCallback::GetInPlaceContext

[New - Windows NT]

Provides the application and document level interfaces and information required to support in-place activation.

HRESULT GetInPlaceContext(

LPOLEINPLACEFRAME FAR * lplpFrame,
LPOLEINPLACEUIWINDOW FAR * lplpDoc,
LPOLEINPLACEFRAMEINFO lpFrameInfo
);
Parameters

lplpframe

Pointer to the pointer variable that receives the address of the IOleInPlaceFrame interface that represents the frame window of the a rich edit control client. Use the AddRef method to increment the reference count the rich edit control releases the interface when it no longer needed.

lplpDoc

Pointer to the pointer variable that receives the address of the IOleInPlaceUIWindow interface that represents the document window of the rich edit control client. An interface need not be returned if the frame and document windows are the same. Use the AddRef method to increment the reference count the rich edit control releases the interface when it no longer needed.

lpFrameInfo

Pointer to the OLEINPLACEFRAMEINFO structure that receives the accelerator information.

Return Value

Returns success status.

See Also

IOleInPlaceFrame, IRichEditOleCallback, OLEINPLACEFRAMEINFO


IRichEditOleCallback::GetNewStorage [New - Windows NT]
 IRichEditOleCallback::GetNewStorage

[New - Windows NT]

Provides storage for a new object pasted from the clipboard or read in from an RTF stream.

HRESULT GetNewStorage(

LPSTORAGE FAR * lplpstg
);
Parameter

lplpstg

Address to the pointer variable that receives the address of the IStorage interface created for the new object.

Return Value

Returns success status.

This method must be implemented to allow cut/copy/paste and drag and drop of OLE objects.

See Also

IRichEditOleCallback, IStorage


IRichEditOleCallback::QueryAcceptData [New - Windows NT]
 IRichEditOleCallback::QueryAcceptData

[New - Windows NT]

Called on a paste or drag to determine if the data pasted/dragged should be accepted.

HRESULT QueryAcceptData(

LPDATAOBJECT lpdataobj,
CLIPFORMAT FAR * lpcfFormat,
DWORD reco,
BOOL fReally,
HGLOBAL hMetaPict
);
Parameters

lpdataobj

Pointer to the DATAOBJECT structure specifying the data object being pasted or dragged.

lpcfFormat

Pointer to the clipboard format that will be used for the paste or drop operation. If the value pointed to by lpcfFormat is zero, the best available format will be used. If the callback changes the value pointed to by lpcfFormat, the rich edit control only uses that format and the operation will fail if the format is not available.

reco

Clipboard operation flag. Can be one of these values.

RECO_DROP	Drop operation (drag and drop).
RECO_PASTE	Paste from the clipboard.
fReally

Nonzero if the paste or drop is actually happening, zero if this is just a query, such as for EM_CANPASTE.

hMetaPict

Handle to a metafile containing the icon view of an object if DVASPECT_ICON is being imposed on a object by Paste Special.

Return Value

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.

See Also

IRichEditOleCallback


IRichEditOleCallback::QueryInsertObject [New - Windows NT]
 IRichEditOleCallback::QueryInsertObject

[New - Windows NT]

Queries the application as to whether an object should be inserted. This member is called when pasting and when reading RTF.

HRESULT QueryInsertObject(

LPCLSID lpclsid,
LPSTORAGE lpstg,
LONG cp
);
Parameters

lpclsid

Class identifier of the object to be inserted.

lpstg

Storage containing the object.

cp

Character position at which the object will be inserted.

Return Value

Returns success status. If the SCODE of the result is not S_OK, the object is not inserted.

See Also

IRichEditOleCallback


IRichEditOleCallback::ShowContainerUI [New - Windows NT]
 IRichEditOleCallback::ShowContainerUI

[New - Windows NT]

Tells the application whether to display its container user interface. The rich edit control looks ahead for doubleclicks and defers the call if appropriate (as described in the OLE documentation). Applications may defer hiding adornments until an IOleInPlaceFrame::SetBorderSpace call is received.

HRESULT ShowContainerUI(

BOOL fShow
);
Parameters

fShow

Show container UI flag. TRUE to show, FALSE otherwise.

Return Value

Returns success status.

This function is called by the OnUIActivate and OnUIDeActivate methods of the IOleInPlaceSite interface.

See Also

IRichEditOleCallback, OnUIActivate, OnUIDeActivate


IShellExtInit [New - Windows 95]
 IShellExtInit

[New - Windows 95]

Designates an interface used to initialize a property sheet extension, context menu extension, or drag and drop handler.

Methods in Vtable Order

IUnknown Methods	Description
QueryInterface	Returns pointers to supported interfaces.
AddRef	Increments reference count.
Release	Decrements reference count.
IShellExtInit Method	Description
Initialize	Initializes the shell extension.


IShellExtInit::Initialize [New - Windows 95]
 IShellExtInit::Initialize  QuickInfo

[New - Windows 95]

Initializes a property sheet extension, context menu extension, or drag and drop handler.

HRESULT STDMETHODCALLTYPE Initialize(

LPSHELLEXTINIT pIface,
LPCITEMIDLIST pidlFolder,
LPDATAOBJECT lpdobj,
HKEY hkeyProgID
);
Parameters

pIface

Pointer to the IShellExtInit interface. In C++, this parameter is implicit.

pidlFolder

Pointer to an structure ITEMIDLIST (item identifier list) that uniquely identifies a folder. This parameter is NULL for property sheet extensions and context menu extensions. For non-default drag and drop menu extensions, this parameter must specify the target folder.

lpdobj

Pointer to an IDataObject interface object that can be used to retrieve the objects being acted upon.

hkeyProgID

Registry key for the file object or folder type.

Return Value

Returns NOERROR if successful or an OLE-defined error value otherwise.

This is the first method that the shell calls after it creates an instance of a property sheet extension, context menu extension, or drag and drop handler.

The meanings of some parameters depend on the extension type. For drag and drop handlers, the item identifier list specifies the destination folder (the drop target), the IDataObject interface identifies the items being dropped, and the registry key specifies the file class of the destination folder.

For property sheet extensions and context menu extensions, the item identifier list specifies the folder that contains the selected file objects, the IDataObject interface identifies the selected file objects, and the registry key specifies the file class of the file object that has the focus.

See Also

IShellExtInit, ITEMIDLIST


IShellFolder [New - Windows 95]
 IShellFolder

[New - Windows 95]

Designates an interface implemented by the shell and used to determine the contents of a folder.

Methods in Vtable Order

IUnknown Methods	Description
QueryInterface	Returns pointers to supported interfaces.
AddRef	Increments reference count.
Release	Decrements reference count.
IShellFolder Methods	Description
ParseDisplayName	Translates a display name into an item identifier list.
EnumObjects	Enumerates the objects in the folder.
BindToObject	Retrieves the IShellFolder interface for the specified subfolder.
BindToStorage	Reserved; this function is not currently implemented.
CompareIDs	Compares two item identifier lists and returns the result.
CreateViewObject	Reserved for use by the shell; do not use.
GetAttributesOf	Retrieves the attributes of the specified file object or subfolder.
GetUIObjectOf	Creates an OLE interface that can be used to carry out operations on a file object or subfolder.
GetDisplayNameOf	Retreives the display name of a file object or subfolder.
SetNameOf	Sets the display name of the specified file object or subfolder and changes its identifier accordingly.


IShellFolder::BindToObject [New - Windows 95]
 IShellFolder::BindToObject  QuickInfo

[New - Windows 95]

Creates an IShellFolder object for a subfolder.

HRESULT STDMETHODCALLTYPE BindToObject(

LPSHELLFOLDER pIface,
LPCITEMIDLIST pidl,
LPBC pbcReserved,
REFIID riid,
LPVOID *ppvOut
);
Parameters

pIface

Pointer to the IShellFolder interface. In C++, this parameter is implicit.

pidl

Pointer to an ITEMIDLIST structure that identifies the subfolder relative to its parent folder.

pbcReserved

Reserved; applications should specify NULL for this parameter.

riid

Identifier of the interface to return. This parameter must point to the IID_IShellFolder interface identifier.

ppvOut

Address that receives the interface pointer. If an error occurs, a NULL pointer is returned in this address.

Return Value

Returns NOERROR if successful or an OLE-defined error value otherwise.

See Also

IShellFolder, ITEMIDLIST


IShellFolder::BindToStorage [New - Windows 95]
 IShellFolder::BindToStorage  QuickInfo

[New - Windows 95]

This method is reserved for future use and is not currently implemented.


IShellFolder::CompareIDs [New - Windows 95]
 IShellFolder::CompareIDs  QuickInfo

[New - Windows 95]

Determines the relative ordering of two file objects or folders, given their item identifier lists.

HRESULT STDMETHODCALLTYPE CompareIDs(

LPSHELLFOLDER pIface,
LPARAM lParam,
LPCITEMIDLIST pidl1,
LPCITEMIDLIST pidl2
);
Parameters

pIface

Pointer to the IShellFolder interface. In C++, this parameter is implicit.

lParam

Value specifying the type of comparison to perform. The calling application should always specify zero, indicating that the two items should be sorted by name.

pidl1 and pidl2

Addresses of two ITEMIDLIST structures that uniquely identify the items to be compared. Both item identifier lists are relative to the parent folder.

Return Value

Returns a handle to a result code. If this method is successful, the CODE field of the status code (SCODE) has the following meaning:

CODE field	Meaning
Less than zero	The first item should precede the second (pidl1 < pidl2).
Greater than zero	The first item should follow the second (pidl1 > pidl2)
Zero	The two items are the same (pidl1 = pidl2).
See Also

IShellFolder, ITEMIDLIST


IShellFolder::CreateViewObject [New - Windows 95]
 IShellFolder::CreateViewObject  QuickInfo

[New - Windows 95]

This method is reserved for use by the shell and should not be called by applications.


IShellFolder::EnumObjects [New - Windows 95]
 IShellFolder::EnumObjects  QuickInfo

[New - Windows 95]

Creates an item enumeration object (an IEnumIDList interface) that can be used to enumerate the contents of a folder.

HRESULT STDMETHODCALLTYPE EnumObjects(

LPSHELLFOLDER pIface,
HWND hwndOwner,
DWORD grfFlags,
LPENUMIDLIST *ppenumIDList
);
Parameters

pIface

Pointer to the IShellFolder interface. In C++, this parameter is implicit.

hwndOwner

Handle of the owner window that the client should specify if it displays a dialog box or message box.

grfFlags

Flags determining which items to enclude in the enumeration. For a list of possible values, see the description of the SHCONTF type.

ppenumIDList

Address that receives a pointer to the IEnumIDList interface created by this method. If an error occurs, a NULL pointer is returned in this address.

Return Value

Returns NOERROR if successful or an OLE-defined error value otherwise.

Remarks

The calling application must free the returned IEnumIDList object by calling its Release method.

This method is similar to the IOleContainer::EnumObjects method defined by OLE.

See Also

IEnumIDList, IShellFolder


IShellFolder::GetAttributesOf [New - Windows 95]
 IShellFolder::GetAttributesOf  QuickInfo

[New - Windows 95]

Retrieves the attributes of one or more file objects or subfolders.

HRESULT STDMETHODCALLTYPE GetAttributesOf(

LPSHELLFOLDER pIface,
UINT cidl,
LPCITEMIDLIST *apidl,
ULONG *rgfInOut
);
Parameters

pIface

Pointer to the IShellFolder interface. In C++, this parameter is implicit.

cidl

Number of file objects to get the attributes of.

apidl

Pointer to an array of pointers to ITEMIDLIST structures, each of which uniquely identifies a file object relative to the parent folder. Each ITEMIDLIST structure must contain exactly one SHITEMID structure followed by a terminating zero.

rgfInOut

Address of an array of values that specify file object attributes. The calling application should initialize each array element by specifying which file object attributes to retrieve.

Return Value

Returns NOERROR if successful or an OLE-defined error value otherwise.

This method returns the actual attributes of each file object in the corresponding array element; it may return all attributes or just the requested attributes.

The following tables list the attribute flags that may be returned by this method. File object attributes include capability flags, display attributes, contents flags, and miscellaneous attributes.

A file object's capability flags may include zero or more of the following values:

SFGAO_CANCOPY	The specified file objects or folders can be copied (same value as the DROPEFFECT_COPY flag).
SFGAO_CANDELETE	The specified file objects or folders can be deleted.
SFGAO_CANLINK	It is possible to create shortcuts for the specified file objects or folders (same value as the DROPEFFECT_LINK flag).
SFGAO_CANMOVE	The specified file objects or folders can be moved (same value as the DROPEFFECT_MOVE flag).
SFGAO_CANRENAME	The specified file objects or folders can be renamed.
SFGAO_CAPABILITYMASK	Mask for the capability flags.
SFGAO_DROPTARGET	The specified file objects or folders are drop targets.
SFGAO_HASPROPSHEET	The specified file objects or folders have property sheets.
A file object's display attributes may include zero or more of the following values:

SFGAO_DISPLAYATTRMASK	Mask for the display attributes.
SFGAO_GHOSTED	The specified file objects or folders should be displayed using a ghosted icon.
SFGAO_LINK	The specified file objects are shortcuts.
SFGAO_READONLY	The specified file objects or folders are read-only.
SFGAO_SHARE	The specified folders are shared.
A file object's contents flags may include zero or more of the following values:

SFGAO_CONTENTSMASK	Mask for the contents attributes.
SFGAO_HASSUBFOLDER	The specified folders have subfolders (and are, therefore, expandable in the left pane of Windows Explorer).
A file object may have zero or more of the following miscellaneous attributes:

SFGAO_FILESYSTEM	The specified folders or file objects are part of the file system (that is, they are files, directories, or root directories).
SFGAO_FILESYSANCESTOR	The specified folders contain one or more file system folders.
SFGAO_FOLDER	The specified items are folders.
SFGAO_REMOVABLE	The specified file objects or folders are on removable media.
SFGAO_VALIDATE	Validate cached information.
See Also

IShellFolder, ITEMIDLIST, SHITEMID


IShellFolder::GetDisplayNameOf [New - Windows 95]
 IShellFolder::GetDisplayNameOf  QuickInfo

[New - Windows 95]

Retrieves the display name for the specified file object or subfolder.

HRESULT STDMETHODCALLTYPE GetDisplayNameOf(

LPSHELLFOLDER pIface,
LPCITEMIDLIST pidl,
DWORD uFlags,
LPSTRRET lpName
);
Parameters

pIface

Pointer to the IShellFolder interface. In C++, this parameter is implicit.

pidl

Pointer to an ITEMIDLIST structure that uniquely identifes the file object or subfolder relative to the parent folder.

uFlags

Value indicating the type of display name to return. For a list of possible values, see the description of the SHGNO enumerated type.

lpName

Pointer to a STRRET structure in which to return the display name. The string returned in this structure depends on the type of display name requested.

Return Value

Returns NOERROR if successful or an OLE-defined error value otherwise.

See Also

IShellFolder, ITEMIDLIST, STRRET


IShellFolder::GetUIObjectOf [New - Windows 95]
 IShellFolder::GetUIObjectOf  QuickInfo

[New - Windows 95]

Returns an interface that can be used to carry out actions on the specified file objects or folders — typically, to create context menus or carry out drag and drop operations.

HRESULT STDMETHODCALLTYPE GetUIObjectOf(

LPSHELLFOLDER pIface,
HWND hwndOwner,
UINT cidl,
LPCITEMIDLIST *apidl,
REFIID riid,
UINT *prgfReserved,
LPVOID *ppvOut
);
Parameters

pIface

Pointer to the IShellFolder interface. In C++, this parameter is implicit.

hwndOwner

Handle of the owner window that the client should specify if it displays a dialog box or message box.

cidl

Number of file objects or subfolders specified by apidl.

apidl

Pointer to an array of pointers to ITEMIDLIST structures, each of which uniquely identifies a file object or subfolder relative to the parent folder. Each item identifier list must contain exactly one SHITEMID structure followed by a terminating zero.

riid

Identifier of the interface to return. This parameter can be a pointer to the IID_IExtractIcon, IID_IContextMenu, IID_IDataObject, or IID_IDropTarget interface identifier.

prgfReserved

Reserved for future versions of Windows; must be NULL.

ppvOut

Address that receives the interface pointer. If an error occurs, a NULL pointer is returned in this address.

Return Value

Returns NOERROR if successful or an OLE-defined error value otherwise.

See Also

IShellFolder, ITEMIDLIST, SHITEMID


IShellFolder::ParseDisplayName [New - Windows 95]
 IShellFolder::ParseDisplayName  QuickInfo

[New - Windows 95]

Translates a file object or folder's display name into an item identifier.

HRESULT STDMETHODCALLTYPE IShellFolder::ParseDisplayName(

LPSHELLFOLDER pIface,
WND hwndOwner,
LPBC pbcReserved,
LPWSTR lpwszDisplayName,
ULONG *pchEaten,
LPITEMIDLIST *ppidl,
ULONG *pdwAttributes
);
Parameters

pIface

Pointer to the IShellFolder interface. In C++, this parameter is implicit.

hwndOwner

Handle of the owner window that the client should specify if it displays a dialog box or message box.

pbcReserved

Reserved; this parameter is always NULL.

lpwszDisplayName

Pointer to a null-terminated Unicode string specifying the display name. This parameter must be a display name for parsing — that is, a display name retrieved using the SHGDN_FORPARSING value.

pchEaten

Pointer to an unsigned long value that receives the number of characters of the display name that were parsed.

ppidl

Address that receives a pointer to the new item identifier list for the object. If an error occurs, a NULL is returned in this address.

The returned item identifier list specifies the relative path (from the parent folder) that corresponds to the specified display name. It contains only one SHITEMID structure followed by a terminating zero.

pdwAttributes

Address that receives the attributes of the file object.

Return Value

Returns NOERROR if successful or an OLE-defined error value otherwise.

Remarks

This method is similar to the 	IParseDisplayName::ParseDisplayName method defined by OLE.

See Also

IParseDisplayName::ParseDisplayName, IShellFolder, IShellLink, SHITEMID


IShellFolder::SetNameOf [New - Windows 95]
 IShellFolder::SetNameOf  QuickInfo

[New - Windows 95]

Changes the name of a file object or subfolder, changing its item identifier in the process.

HRESULT STDMETHODCALLTYPE SetNameOf(

LPSHELLFOLDER pIface,
HWND hwndOwner,
LPCITEMIDLIST pidl,
LPCOLESTR lpszName,
DWORD uFlags,
LPITEMIDLIST *ppidlOut
);
Parameters

pIface

Pointer to the IShellFolder interface. In C++, this parameter is implicit.

hwndOwner

Handle of the owner window that the client should specify if it displays a dialog box or message box.

pidl

Pointer to an ITEMIDLIST structure that uniquely identifies the file object or subfolder relative to the parent folder.

lpszName

Pointer to a null-terminated string that specifies the new display name.

uFlags

Value indicating the type of name specified by the lpszName parameter. For a list of possible values, see the description of the SHCONTF enumerated type.

ppidlOut

Address in which the method returns a pointer to the new ITEMIDLIST structure. This parameter can be NULL, and in that case, the method does not return the new ITEMIDLIST for the object.

If this parameter is not NULL, this method frees the specified ITEMIDLIST structure and allocates a new one using the task allocator. The calling application is responsible for freeing the new ITEMIDLIST structure. If an error occurs, the method returns NULL in this address.

Return Value

Returns NOERROR if successful or an OLE-defined error value otherwise.

See Also

IShellFolder, ITEMIDLIST


IShellLink [New - Windows 95]
 IShellLink

[New - Windows 95]

Designates an interface that allows an application to create and resolve shell links.

Methods in Vtable Order

IUnknown Methods	Description
QueryInterface	Returns pointers to supported interfaces.
AddRef	Increments reference count.
Release	Decrements reference count.
IShellLink Methods	Description
GetArguments	Retrieves the command-line arguments associated with a shell link object.
GetDescription	Retrieves the description string for a shell link object.
GetHotkey	Retrieves the hot key for a shell link object.
GetIconLocation	Retrieves the location (path and index) of the icon for a shell link object.
GetIDList	Retrieves the list of item identifiers for a shell link object.
GetPath	Retrieves the path and filename of a shell link object.
GetShowCmd	Retrieves the show (SW_) command for a shell link object.
GetWorkingDirectory	Retrieves the name of the working directory for a shell link object.
Resolve	Resolves a shell link by searching for the shell link object and updating the shell link path and its list of identifiers (if necessary).
SetArguments	Sets the command-line arguments associated with a shell link object.
SetDescription	Sets the description string for a shell link object.
SetHotkey	Sets the hot key for a shell link object.
SetIconLocation	Sets the location (path and index) of the icon for a shell link object.
SetIDList	Sets the list of item identifiers for a shell link object.
SetPath	Sets the path and filename of a shell link object.
SetRelativePath	Sets the relative path for a shell link object.
SetShowCmd	Sets the show (SW_) command for a shell link object.
SetWorkingDirectory	Sets the name of the working directory for a shell link object.


IShellLink::GetArguments [New - Windows 95]
 IShellLink::GetArguments  QuickInfo

[New - Windows 95]

Retrieves the command-line arguments associated with a shell link object.

HRESULT STDMETHODCALLTYPE GetArguments(

ISHELLLINK FAR * pShlLnk,
LPSTR pszArgs,
int cchMaxPath
);
Parameters

pShlLnk

Pointer to the IShellLink interface. In C++, this parameter is implicit.

pszArgs

Pointer to a buffer that receives the command-line arguments.

cchMaxPath

Maximum number of characters to copy to the buffer pointed to by pszArgs.

Return Value

Returns NOERROR if successful or an OLE-defined error value otherwise.

See Also

IShellLink


IShellLink::GetDescription [New - Windows 95]
 IShellLink::GetDescription  QuickInfo

[New - Windows 95]

Retrieves the description string for a shell link object.

RESULT STDMETHODCALLTYPE GetDescription(

ISHELLLINK FAR * pShlLnk,
LPSTR pszName,
int cchMaxName
);
Parameters

pShlLnk

Pointer to the IShellLink interface. In C++, this parameter is implicit.

pszName

Pointer to a buffer that receives the description string.

cchMaxName

Maximum number of characters to copy to the buffer pointed to by pszName.

Return Value

Returns NOERROR if successful or an OLE-defined error value otherwise.

See Also

IShellLink


IShellLink::GetHotkey [New - Windows 95]
 IShellLink::GetHotkey  QuickInfo

[New - Windows 95]

Retrieves the hot key for a shell link object.

HRESULT STDMETHODCALLTYPE GetHotkey(

ISHELLLINK FAR * pShlLnk,
WORD *pwHotkey
);
Parameters

pShlLnk

Pointer to the IShellLink interface. In C++, this parameter is implicit.

pwHotkey

Pointer to the hot key. The virtual-key code is in the low-order byte, and the modifier flags are in the high-order byte. The modifier flags can be a combination of the following values:

HOTKEYF_ALT	ALT key
HOTKEYF_CONTROL	CTRL key
HOTKEYF_EXT	Extended key
HOTKEYF_SHIFT	SHIFT key
Return Value

Returns NOERROR if successful or an OLE-defined error value otherwise.

See Also

IShellLink


IShellLink::GetIconLocation [New - Windows 95]
 IShellLink::GetIconLocation  QuickInfo

[New - Windows 95]

Retrieves the location (path and index) of the icon for a shell link object.

HRESULT STDMETHODCALLTYPE GetIconLocation(

ISHELLLINK FAR * pShlLnk,
LPSTR pszIconPath,
int cchIconPath,
int *piIcon
);
Parameters

pShlLnk

Pointer to the IShellLink interface. In C++, this parameter is implicit.

pszIconPath

Pointer to a buffer that receives the path of the file containing the icon.

cchIconPath

Maximum number of characters to copy to the buffer pointed to by pszIconPath.

piIcon

Pointer to a value that receives the index of the icon.

Return Value

Returns NOERROR if successful or an OLE-defined error value otherwise.

See Also

IShellLink


IShellLink::GetIDList [New - Windows 95]
 IShellLink::GetIDList  QuickInfo

[New - Windows 95]

Retrieves the list of item identifiers for a shell link object.

HRESULT STDMETHODCALLTYPE GetIDList(

ISHELLLINK FAR * pShlLnk,
LPITEMIDLIST * ppidl
);
Parameters

pShlLnk

Pointer to the IShellLink interface. In C++, this parameter is implicit.

ppidl

Pointer to a pointer to a list of item identifiers.

Return Value

Returns NOERROR if successful or an OLE-defined error value otherwise.

See Also

IShellLink


IShellLink::GetPath [New - Windows 95]
 IShellLink::GetPath  QuickInfo

[New - Windows 95]

Retrieves the path and filename of a shell link object.

HRESULT STDMETHODCALLTYPE GetPath(

IShellLink FAR * pShlLnk,
LPSTR pszFile,
int cchMaxPath,
WIN32_FIND_DATA *pfd,
DWORD fFlags
);
Parameters

pShlLnk

Pointer to the IShellLink interface. In C++, this parameter is implicit.

pszFile

Pointer to a buffer that receives the path and filename of the shell link object.

cchMaxPath

Maximum number of bytes to copy to the buffer pointed to by pszFile.

pfd

Pointer to a WIN32_FIND_DATA structure that contains information about the shell link object.

fFlags

Flags that specify the type of path information to retrieve. This parameter can be a combination of the following values:

SLGP_SHORTPATH	Retrieves the standard short (8.3) filename.
SLGP_UNCPRIORITY	Retrieves the Universal Naming Convention (UNC) path name of the file.
Return Value

Returns NOERROR if successful or an OLE-defined error value otherwise.

See Also

IShellLink, WIN32_FIND_DATA


IShellLink::GetShowCmd [New - Windows 95]
 IShellLink::GetShowCmd  QuickInfo

[New - Windows 95]

Retrieves the show command for a shell link object.

HRESULT STDMETHODCALLTYPE GetShowCmd(

ISHELLLINK FAR * pShlLnk,
int *piShowCmd
);
Parameters

pShlLnk

Pointer to the IShellLink interface. In C++, this parameter is implicit.

piShowCmd

Pointer to the show command. For a list of show commands, see the description of the ShowWindow function.

Return Value

Returns NOERROR if successful or an OLE-defined error value otherwise.

See Also

IShellLink, ShowWindow


IShellLink::GetWorkingDirectory [New - Windows 95]
 IShellLink::GetWorkingDirectory  QuickInfo

[New - Windows 95]

Retrieves the name of the working directory for a shell link object.

HRESULT STDMETHODCALLTYPE GetWorkingDirectory(

ISHELLLINK FAR * pShlLnk,
LPSTR pszDir,
int cchMaxPath
);
Parameters

pShlLnk

Pointer to the IShellLink interface. In C++, this parameter is implicit.

pszDir

Pointer to a buffer that receives the name of the working directory.

cchMaxPath

Maximum number of characters to copy to the buffer pointed to by pszDir. The name of the working directory is truncated if it is longer than the maximum specified by this parameter.

Return Value

Returns NOERROR if successful or an OLE-defined error value otherwise.

See Also

IShellLink


IShellLink::Resolve [New - Windows 95]
 IShellLink::Resolve  QuickInfo

[New - Windows 95]

Resolves a shell link. The system searches for the shell link object and updates the shell link path and its list of identifiers (if necessary).

HRESULT STDMETHODCALLTYPE Resolve(

ISHELLLINK FAR * pShlLnk,
HWND hwnd,
DWORD fFlags
);
Parameters

pShlLnk

Pointer to the IShellLink interface. In C++, this parameter is implicit.

hwnd

Handle of a window that the shell uses as the parent window for a dialog box. The shell displays the dialog box if it needs to prompt the user for more information while resolving a shell link.

fFlags

Action flags. This parameter can be a combination of the following values:

SLR_ANY_MATCH	Resolves the link, displaying a dialog box if the system needs information from the user.
SLR_NO_UI	Prevents the shell from displaying a dialog box if it cannot resolve the shell link. When this flag is specified, the high-order word of fFlags specifies a timeout duration, in milliseconds. The function returns if the link cannot be resolved within the timeout duration. If the high-order word is set to zero, the timeout duration defaults to 3000 milliseconds (3 seconds).
SLR_UPDATE	Directs the shell to update the path to the link and the list of identifiers if the link object has been changed. If this value is used, it is not necessary to call the IPersistFile::IsDirty method to determine whether the link object has changed.
Return Value

Returns NOERROR if successful or an OLE-defined error value otherwise.

Remarks

When this method is called, the system retrieves the path associated with the current link object and searches for the object in that path. If the system finds the object, it resolves the link. If the system cannot find the object, it looks in the same directory for an object with the same file creation time and attributes, but with a different name. This type of search resolves a link to an object that has been renamed.

If the system still cannot find the link object, it searches the subdirectories of the current directory. It does a recursive search of the directory tree looking for a match with either the same name or creation time. If it does not find a match after that, the shell displays a dialog box prompting the user for a location. An application can suppress the dialog box by specifying the SLR_NO_UI value in a call to this method.

See Also

IShellLink


IShellLink::SetArguments [New - Windows 95]
 IShellLink::SetArguments  QuickInfo

[New - Windows 95]

Sets the command-line arguments for a shell link object.

HRESULT STDMETHODCALLTYPE SetArguments(

ISHELLLINK FAR * pShlLnk,
LPCSTR pszArgs
);
Parameters

pShlLnk

Pointer to the IShellLink interface. In C++, this parameter is implicit.

pszArgs

Pointer to a buffer that contains the new command-line arguments.

Return Value

Returns NOERROR if successful or an OLE-defined error value otherwise.

This method is useful when creating a link to an application that takes special flags as arguments, such as a compiler.

See Also

IShellLink


IShellLink::SetDescription [New - Windows 95]
 IShellLink::SetDescription  QuickInfo

[New - Windows 95]

Sets the description for a shell link object. The description can be any application-defined string.

HRESULT STDMETHODCALLTYPE SetDescription(

ISHELLLINK FAR * pShlLnk,
LPCSTR pszName
);
Parameters

pShlLnk

Pointer to the IShellLink interface. In C++, this parameter is implicit.

pszName

Pointer to a buffer containing the new description string.

Return Value

Returns NOERROR if successful or an OLE-defined error value otherwise.

See Also

IShellLink


IShellLink::SetHotkey [New - Windows 95]
 IShellLink::SetHotkey  QuickInfo

[New - Windows 95]

Sets a hot key for a shell link object.

HRESULT STDMETHODCALLTYPE SetHotkey(

ISHELLLINK FAR * pShlLnk,
WORD wHotkey
);
Parameters

pShlLnk

Pointer to the IShellLink interface. In C++, this parameter is implicit.

wHotkey

Hot key. The virtual-key code is in the low-order byte, and the modifier flags are in the high-order byte. The modifier flags can be a combination of the values specified in the description of the IShellLink::GetHotkey method.

Return Value

Returns NOERROR if successful or an OLE-defined error value otherwise.

Setting a hot key allows the user to activate the object by pressing a particular combination of keys.

See Also

IShellLink, IShellLink::GetHotkey


IShellLink::SetIconLocation [New - Windows 95]
 IShellLink::SetIconLocation  QuickInfo

[New - Windows 95]

Sets the location (path and index) of the icon for a shell link object.

HRESULT STDMETHODCALLTYPE SetIconLocation(

ISHELLLINK FAR * pShlLnk,
LPCSTR pszIconPath,
int iIcon
);
Parameters

pShlLnk

Pointer to the IShellLink interface. In C++, this parameter is implicit.

pszIconPath

Pointer to a buffer that contains the path of the file containing the icon.

iIcon

Index of the icon.

Return Value

Returns NOERROR if successful or an OLE-defined error value otherwise.

See Also

IShellLink


IShellLink::SetIDList [New - Windows 95]
 IShellLink::SetIDList  QuickInfo

[New - Windows 95]

Sets the list of item identifiers for a shell link object.

HRESULT STDMETHODCALLTYPE SetIDList(

ISHELLLINK FAR * pShlLnk,
LPCITEMIDLIST pidl
);
Parameters

pShlLnk

Pointer to the IShellLink interface. In C++, this parameter is implicit.

pidl

Pointer to a list of item identifiers.

Return Value

Returns NOERROR if successful or an OLE-defined error value otherwise.

This method is useful when an application needs to set a shell link to an object that is not a file, such as a Control Panel application, a printer, or another computer.

See Also

IShellLink


IShellLink::SetPath [New - Windows 95]
 IShellLink::SetPath  QuickInfo

[New - Windows 95]

Sets the path and filename of a shell link object.

HRESULT STDMETHODCALLTYPE SetPath(

ISHELLLINK FAR * pShlLnk,
LPCSTR pszFile
);
Parameters

pShlLnk

Pointer to the IShellLink interface. In C++, this parameter is implicit.

pszFile

Pointer to a buffer that contains the new path.

Return Value

Returns NOERROR if successful or an OLE-defined error value otherwise.

See Also

IShellLink


IShellLink::SetRelativePath [New - Windows 95]
 IShellLink::SetRelativePath  QuickInfo

[New - Windows 95]

Sets the relative path to the shell link object.

HRESULT STDMETHODCALLTYPE SetRelativePath(

ISHELLLINK FAR * pShlLnk,
LPCSTR pszPathRel,
LPCITEMIDLIST pidlRel
);
Parameters

pShlLnk

Pointer to the IShellLink interface. In C++, this parameter is implicit.

pszPathRel

Pointer to a buffer that contains the new relative path.

pidlRel

Pointer to a list of item identifiers that identify the object.

Return Value

Returns NOERROR if successful or an OLE-defined error value otherwise.

See Also

IShellLink


IShellLink::SetShowCmd [New - Windows 95]
 IShellLink::SetShowCmd  QuickInfo

[New - Windows 95]

Sets the show command for a shell link object. The show command sets the initial show state of the window.

HRESULT STDMETHODCALLTYPE SetShowCmd(

ISHELLLINK FAR * pShlLnk,
int iShowCmd
);
Parameters

pShlLnk

Pointer to the IShellLink interface. In C++, this parameter is implicit.

iShowCmd

Show command. For a list of the show commands, see the description of the ShowWindow function.

Return Value

Returns NOERROR if successful or an OLE-defined error value otherwise.

See Also

IShellLink, ShowWindow


IShellLink::SetWorkingDirectory [New - Windows 95]
 IShellLink::SetWorkingDirectory  QuickInfo

[New - Windows 95]

Sets the name of the working directory for a shell link object.

HRESULT STDMETHODCALLTYPE SetWorkingDirectory(

ISHELLLINK FAR * pShlLnk,
LPCSTR pszDir
);
Parameters

pShlLnk

Pointer to the IShellLink interface. In C++, this parameter is implicit.

pszDir

Pointer to a buffer that contains the name of the new working directory.

Return Value

Returns NOERROR if successful or an OLE-defined error value otherwise.

The working directory must be set only if the object requires it to be set. For example, if an application creates a shell link to a Microsoft Word document that uses a template that resides in a different directory, the application would use this method to set the working directory.

See Also

IShellLink


IShellPropSheetExt [New - Windows 95]
 IShellPropSheetExt

[New - Windows 95]

Designates an interface that allows a property sheet handler to add or replace pages in the property sheet for a file object.

Methods in Vtable Order

IUnknown Methods	Description
QueryInterface	Returns pointers to supported interfaces.
AddRef	Increments reference count.
Release	Decrements reference count.
i

IShellPropSheetExt Methods	Description
AddPages	Adds one or more pages to a property sheet for a file object.
ReplacePage	Replaces a page in a property sheet for a control panel object.


IShellPropSheetExt::AddPages [New - Windows 95]
 IShellPropSheetExt::AddPages  QuickInfo

[New - Windows 95]

Adds one or more pages to a property sheet that the shell displays for a file object. When it is about to display the property sheet, the shell calls the AddPages method of each property sheet handler registered to the file type.

HRESULT STDMETHODCALLTYPE AddPages(

IShellPropSheetExt FAR * pProp,
LPFNADDPROPSHEETPAGE lpfnAddPage,
LPARAM lParam
);
Parameters

pProp

Pointer to the IShellPropSheetExt interface. In C++, this parameter is implicit.

lpfnAddPage

Pointer to a function that the property sheet handler calls to add a page to the property sheet. The function takes a property sheet handle returned by the CreatePropertySheetPage function and the lParam parameter passed to the AddPages method.

lParam

Parameter to pass to the function specified by lpfnAddPage.

Return Value

Returns NOERROR if successful or an OLE-defined error value otherwise.

For each page it needs to add to a property sheet, a property sheet handler fills a PROPSHEETPAGE structure, calls CreatePropertySheetPage, and then calls the function specified by lpfnAddPage.

See Also

CreatePropertySheetPage, IShellPropSheetExt, PROPSHEETPAGE


IShellPropSheetExt::ReplacePage [New - Windows 95]
 IShellPropSheetExt::ReplacePage  QuickInfo

[New - Windows 95]

Replaces a page in a property sheet for a control panel object.

HRESULT STDMETHODCALLTYPE ReplacePage(

IShellPropSheetExt FAR * pProp,
UINT uPageID,
LPFNADDPROPSHEETPAGE lpfnReplacePage,
LPARAM lParam
);
Parameters

pProp

Pointer to the IShellPropSheetExt interface. In C++, this parameter is implicit.

uPageID

Identifier of the page to replace. The values for this parameter for control panels can be found in the CPLEXT.H header file.

lpfnReplacePage

Pointer to a function that the property sheet handler calls to replace a page to the property sheet. The function takes a property sheet handle returned by the CreatePropertySheetPage function and the lParam parameter passed to the ReplacePage method.

lParam

Parameter to pass to the function specified by lpfnReplacePage.

Return Value

Returns NOERROR if successful or an OLE-defined error value otherwise.

To replace a page, a property sheet handler fills a PROPSHEETPAGE structure, calls CreatePropertySheetPage, and then calls the function specified by lpfnReplacePage.

See Also

CreatePropertySheetPage, IShellPropSheetExt, PROPSHEETPAGE


ABM_ACTIVATE
 ABM_ACTIVATE  QuickInfo

SHAppBarMessage(ABM_ACTIVATE, pabd);

Notifies the system that an appbar has been activated. An appbar should call this message in response to the WM_ACTIVATE message.

Parameter

pabd

Pointer to an APPBARDATA structure that identifies the appbar to activate. You must specify the cbSize and hWnd members when sending this message; all other members are ignored.

Return Value

Always returns TRUE.

Remarks

This message is ignored if the hWnd member of the structure pointed to by pabd identifies an autohide appbar. The system automatically sets the Z order for an autohide appbar.

See Also

APPBARDATA


ABM_GETAUTOHIDEBAR
 ABM_GETAUTOHIDEBAR  QuickInfo

hwndAutoHide = (HWND) SHAppBarMessage(ABM_GETAUTOHIDEBAR, pabd);

Retrieves the handle of the autohide appbar associated with an edge of the screen.

Parameter

pabd

Pointer to an APPBARDATA structure that specifies the screen edge. You must specify the cbSize, hWnd, and uEdge members when sending this message; all other members are ignored.

Return Value

Returns the handle of the autohide appbar. The return value is NULL if an error occurs or if no autohide appbar is associated with the given edge.

See Also

APPBARDATA


ABM_GETSTATE
 ABM_GETSTATE  QuickInfo

fuState = (UINT) SHAppBarMessage(ABM_GETSTATE, pabd);

Retrieves the autohide and always-on-top states of the Windows taskbar.

Parameter

pabd

Pointer to an APPBARDATA structure. You must specify the cbSize and hWnd members when sending this message; all other members are ignored.

Return Value

Returns zero if the taskbar is not in the autohide or always-on-top state. Otherwise, the return value is one or both of the following values:

ABS_ALWAYSONTOP	The taskbar is in the always-on-top state.
ABS_AUTOHIDE	The taskbar is in the autohide state.
See Also

APPBARDATA


ABM_GETTASKBARPOS
 ABM_GETTASKBARPOS  QuickInfo

fResult = (BOOL) SHAppBarMessage(ABM_GETTASKBARPOS, pabd);

Retrieves the bounding rectangle of the Windows taskbar.

Parameter

pabd

Pointer to an APPBARDATA structure whose rc member receives the bounding rectangle, in screen coordinates, of the taskbar. You must specify the cbSize and hWnd when sending this message; all other members are ignored.

Return Value

Returns TRUE if successful or FALSE otherwise.

See Also

APPBARDATA


ABM_NEW
 ABM_NEW  QuickInfo

fRegistered = (BOOL) SHAppBarMessage(ABM_NEW, pabd);

Registers a new appbar and specifies the message identifier that the system should use to send notification messages to the appbar. An appbar should send this message before sending any other appbar messages.

Parameter

pabd

Pointer to an APPBARDATA structure that contains the new appbar's window handle and message identifier. You must specify the cbSize, hWnd, and uCallbackMessage members when sending this message; all other members are ignored.

Return Value

Returns TRUE if successful or FALSE if an error occurs or the appbar is already registered.

See Also

APPBARDATA


ABM_QUERYPOS
 ABM_QUERYPOS  QuickInfo

SHAppBarMessage(ABM_QUERYPOS, pabd);

Requests a size and screen position for an appbar. The message proposes a screen edge and a bounding rectangle for the appbar. The system adjusts the bounding rectangle so that the appbar does not interfere with the Windows taskbar or any other appbars. An appbar should send this message before sending the ABM_SETPOS message.

Parameter

pabd

Pointer to an APPBARDATA structure. The uEdge member specifies a screen edge, and the rc member contains the proposed bounding rectangle. When the SHAppBarMessage function returns, rc contains the approved bounding rectangle. You must specify the cbSize, hWnd, uEdge, and rc members when sending this message; all other members are ignored.

Return Value

Always returns TRUE.

See Also

APPBARDATA


ABM_REMOVE
 ABM_REMOVE  QuickInfo

SHAppBarMessage(ABM_REMOVE, pabd);

Unregisters an appbar, removing it from the system's internal list. The system no longer sends notification messages to the appbar nor prevents other applications from using the screen area occupied by the appbar.

Parameter

pabd

Pointer to an APPBARDATA structure that contains the handle of the appbar to unregister. You must specify the cbSize and hWnd members when sending this message; all other members are ignored.

Return Value

Always returns TRUE.

This message causes the system to send the ABN_POSCHANGED notification message to all appbars.

See Also

APPBARDATA


ABM_SETAUTOHIDEBAR
 ABM_SETAUTOHIDEBAR  QuickInfo

fSuccess = (BOOL) SHAppBarMessage(ABM_SETAUTOHIDEBAR, pabd);

Registers or unregisters an autohide appbar for an edge of the screen. The system allows only one autohide appbar for each edge on a first come, first served basis.

Parameter

pabd

Pointer to an APPBARDATA structure. The uEdge member specifies the screen edge. The lParam parameter is set to TRUE to register the appbar or FALSE to unregister it. You must specify the cbSize, hWnd, uEdge, and lParam members when sending this message; all other members are ignored.

Return Value

Returns TRUE if successful or FALSE if an error occurs or an autohide appbar is already registered for the given edge.

See Also

APPBARDATA


ABM_SETPOS
 ABM_SETPOS  QuickInfo

SHAppBarMessage(ABM_SETPOS, pabd);

Sets the size and screen position of an appbar. The message specifies a screen edge to and the bounding rectangle for the appbar. The system may adjust the bounding rectangle so that the appbar does not interfere with the Windows taskbar or any other appbars.

Parameters

pabd

Pointer to an APPBARDATA structure. The uEdge member specifies a screen edge, and the rc member contains the bounding rectangle. When the SHAppBarMessage function returns, rc contains the approved bounding rectangle. You must specify the cbSize, hWnd, uEdge, and rc members when sending this message; all other members are ignored.

Return Value

Always returns TRUE.

This message causes the system to send the ABN_POSCHANGED notification message to all appbars.

See Also

APPBARDATA


ABM_WINDOWPOSCHANGED
 ABM_WINDOWPOSCHANGED  QuickInfo

SHAppBarMessage(ABM_WINDOWPOSCHANGED, pabd);

Notifies the system when an appbar's position has changed. An appbar should call this message in response to the WM_WINDOWPOSCHANGED message.

Parameter

pabd

Pointer to an APPBARDATA structure that identifies the appbar to activate. You must specify the cbSize and hWnd members when sending this message; all other members are ignored.

Return Value

Always returns TRUE.

Remarks

This message is ignored if the hWnd member of the structure pointed to by pabd identifies an autohide appbar.

See Also

APPBARDATA


ABN_FULLSCREENAPP
 ABN_FULLSCREENAPP  QuickInfo

ABN_FULLSCREENAPP

fOpen = (BOOL) lParam;

Notifies an appbar when a full-screen application is opening or closing. When a full-screen application is opening, an appbar must drop to the bottom of the Z order. When it is closing, the appbar should restore its Z order position. This notification is sent in the form of an application-defined message that is set by the ABM_NEW message.

Parameter

fOpen

Flag specifying whether a full screen application is opening or closing. This parameter is TRUE if opening or FALSE if closing.

Return Value

No return value.


ABN_POSCHANGED
 ABN_POSCHANGED  QuickInfo

Notifies an appbar when an event has occurred that may effect the appbar's size and position. Events include changes in the taskbar's size, position, and visibility state, as well as the addition, removal, or resizing of another appbar on the same side of the screen.

Return Value

No return value.

Remarks

An appbar should respond to this notification message by sending the ABM_QUERYPOS and ABM_SETPOS messages. If its position has changed, the appbar should call the MoveWindow function to move itself to the new position.

See Also

MoveWindow


ABN_STATECHANGE
 ABN_STATECHANGE  QuickInfo

ABN_STATECHANGE

Notifies an appbar that the taskbar's autohide or always-on-top state has changed — that is, the user has checked or unchecked the "Always on top" or "Auto hide" check box on the taskbar's property sheet. An appbar can use this notification message to set its state to conform to that of the taskbar, if desired.

Return Value

No return value.


ABN_WINDOWARRANGE
 ABN_WINDOWARRANGE  QuickInfo

ABN_WINDOWARRANGE

fBeginning = (BOOL) lParam;

Notifies an appbar that the user has selected the Cascade, Tile Horizontally, or Tile Vertically command from the taskbar's context menu.

Parameter

fBeginning

Flag specifying whether the cascade or tile operation is beginning. This parameter is TRUE if the operation is beginning and the windows have not yet been moved. It is FALSE if the operation has completed.

Return Value

No return value.

Remarks

The system sends this notification message twice — first with lParam set to TRUE and then with lParam set to FALSE. The first notification is sent before the windows are cascaded or tiled, and the second is sent after the cascade or tile operation has occurred.


ACM_OPEN [New - Windows NT]
 ACM_OPEN  QuickInfo  Overview  Group

[New - Windows NT]

ACM_OPEN

wParam = 0;

lParam = (LPARAM) (LPSTR) lpszName;

// Corresponding macro

BOOL Animate_Open(hwnd, lpszName);

// Related macro

BOOL Animate_Close(hwnd);

The ACM_OPEN message opens an AVI clip and displays its first frame in an animation control.

Parameters

hwnd

Handle to the animation control.

lpszName

Pointer to a buffer that contains the path of the .AVI file or the name of an AVI resource. Alternatively, this parameter can consist of the AVI resource identifier in the low-order word and zero in the high-order word. To create this value, use the MAKEINTRESOURCE macro. If this parameter is NULL, the system closes the .AVI file that was previously opened for the specified animation control, if any.

The AVI file or resource specified by lpszName must not contain audio. It must be silent.

Return Value

If the operation succeeds, the return value is TRUE.

If the operation fails, the return value is FALSE.

Remarks

You can only open silent AVI clips. AVI files or resources containing audio will not load. ACM_OPEN and Animate_Open fail if lpszSource specifies a non-silent AVI clip.

You can use Animate_Close to close an .AVI file or AVI resource that was previously opened for the specified animation control.

The Animate_Open macro is defined as follows:

#define Animate_Open(hwnd, szName)   \

    (BOOL)SendMessage(hwnd, ACM_OPEN, 0, (LPARAM)(LPTSTR)(szName))

The Animate_Close macro is defined as follows:

#define Animate_Close(hwnd)                 Animate_Open(hwnd, NULL)

The Animate_Close macro always returns FALSE.

See Also

MAKEINTRESOURCE


ACM_PLAY [New - Windows NT]
 ACM_PLAY  QuickInfo  Overview  Group

[New - Windows NT]

ACM_PLAY

wParam = (WPARAM) (UINT) cRepeat;

lParam = (LPARAM) MAKELONG(wFrom, wTo);

// Corresponding macro

BOOL Animate_Play(hwndAnim, wFrom, wTo, cRepeat);

// Related macro

BOOL Animate_Seek(hwndAnim, wFrame);

The ACM_PLAY message plays an AVI clip in an animation control. The control plays the clip in the background while the thread continues executing.

Parameters

cRepeat

Number of times to replay the AVI clip. A value of  − 1 means replay the clip indefinitely.

hwndAnim

Handle to the animation control in which to play the AVI clip.

wFrom

Zero-based index of the frame where playing begins. The value must be less than 65,536. A value of zero means begin with the first frame in the AVI clip.

wTo

Zero-based index of the frame where playing ends. The value must be less than 65,536. A value of  − 1 means end with the last frame in the AVI clip.

wFrame

Zero-based index of the frame to display.

Return Value

If the operation succeeds, the return value is TRUE.

If the operation fails, the return value is FALSE.

Remarks

You can use Animate_Seek to direct the animation control to display a particular frame of the AVI clip.

The Animate_Play macro is defined as follows:

#define Animate_Play(hwnd, from, to, rep)   \

    (BOOL)SendMessage(hwnd, ACM_PLAY, (WPARAM)(UINT)(rep),  \

        (LPARAM)MAKELONG(from, to))

The Animate_Seek macro is defined as follows:

#define Animate_Seek(hwnd, frame)           Animate_Play(hwnd, frame, frame, 1)


ACM_STOP [New - Windows NT]
 ACM_STOP  QuickInfo  Overview  Group

[New - Windows NT]

ACM_STOP

wParam = 0;

lParam = 0;

// Corresponding macro

BOOL Animate_Stop(hwnd);

The ACM_STOP message stops playing an AVI clip in an animation control.

Parameters

hwnd

Handle to the animation control.

Return Value

If the operation succeeds, the return value is TRUE.

If the operation fails, the return value is FALSE.


ACN_START [New - Windows NT]
 ACN_START  QuickInfo  Overview  Group

[New - Windows NT]

ACN_START

The ACN_START notification message notifies an animation control's parent window that the associated AVI clip has started playing. This notification message is sent in the form of a WM_COMMAND message.

Return Value

No return value.

See Also

WM_COMMAND


ACN_STOP [New - Windows NT]
 ACN_STOP  QuickInfo  Overview  Group

[New - Windows NT]

ACN_STOP

The ACN_STOP notification message notifies an animation control's parent window that the associated AVI clip has stopped playing. This notification message is sent in the form of a WM_COMMAND message.

Return Value

No return value.

See Also

WM_COMMAND


BM_CLICK
 BM_CLICK  QuickInfo  Overview  Group

BM_CLICK

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

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

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

Parameters

This message has no parameters.

Return Value

This message does not return a value.

See Also

BN_CLICKED, WM_LBUTTONDOWN, WM_LBUTTONUP


BM_GETCHECK
 BM_GETCHECK  QuickInfo  Overview  Group

BM_GETCHECK

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

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

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

Parameters

This message has no parameters.

Return Value

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
0	Button is unchecked. Same as the Windows 95 constant BST_UNCHECKED.
1	Button is checked. Same as the Windows 95 constant BST_CHECKED.
2	Button is grayed, indicating an indeterminate state (applies only if the button has the BS_3STATE or BS_AUTO3STATE style). Same as the Windows 95 constant BST_INDETERMINATE.
BST_CHECKED	Windows 95 only: Button is checked.
BST_INDETERMINATE	Windows 95 only: Button is grayed, indicating an indeterminate state (applies only if the button has the BS_3STATE or BS_AUTO3STATE style).
BST_UNCHECKED	Windows 95 only: Button is unchecked
If the button has any other style, the return value is zero.

See Also

BM_GETSTATE, BM_SETCHECK


BM_GETIMAGE [New - Windows 95]
 BM_GETIMAGE

[New - Windows 95]

BM_GETIMAGE

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

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

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

Parameters

This message has no parameters.

Return Value

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

See Also

BM_SETIMAGE


BM_GETSTATE
 BM_GETSTATE  QuickInfo  Overview  Group

BM_GETSTATE

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

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

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

Parameters

This message has no parameters.

Return Value

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

Value	Meaning
0x0003	Specifies the check state (radio buttons and check boxes only). A value of zero indicates the button is unchecked; a value of 1 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 2 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.
0x0004	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. Same as the Windows 95 constant BST_PUSHED.
0x0008	Specifies the focus state. A nonzero value indicates that the button has the keyboard focus. Same as the Windows 95 constant BST_FOCUS.
BST_CHECKED	Windows 95 only: Indicates the button is checked. Same as the Windows NT return value of 1.
BST_FOCUS	Windows 95 only: Indicates the button has the keyboard focus. Same as the Windows NT return value of 0x0008.
BST_INDETERMINATE	Windows 95 only: 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. Same as the Windows NT return value of 2.
BST_PUSHED	Windows 95 only: Indicates the button is highlighted as if the user had pushed it. Same as the Windows NT return value of 0x0004.
BST_UNCHECKED	Windows 95 only: Indicates the button is unchecked. Same as the Windows NT return value of zero.
See Also

BM_GETCHECK, BM_SETSTATE


BM_SETCHECK
 BM_SETCHECK  QuickInfo  Overview  Group

BM_SETCHECK

wParam = (WPARAM) fCheck; // check state

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

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

Parameters

fCheck

Value of wParam. Specifies the check state. This parameter can be one of the following values:

Value	Meaning
0	Sets the button state to unchecked. Same as the Windows 95 constant BST_UNCHECKED.
1	Sets the button state to checked. Same as the Windows 95 constant BST_CHECKED.
2	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. Same as the Windows 95 constant BST_INDETERMINATE.
BST_CHECKED	Windows 95 only: Sets the button state to checked.
BST_INDETERMINATE	Windows 95 only: 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	Windows 95 only: Sets the button state to unchecked
Return Value

This message always returns zero.

Remarks

The BM_SETCHECK message has no effect on push buttons.

See Also

BM_GETCHECK, BM_GETSTATE, BM_SETSTATE


BM_SETIMAGE [New - Windows 95]
 BM_SETIMAGE

[New - Windows 95]

BM_SETIMAGE

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

lParam = (LPARAM) (HANDLE) hImage;  // handle of the image

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

Parameters

hImage

Value of lParam. Identifies the image to associate with the button.

Return Value

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

See Also

BM_GETIMAGE


BM_SETSTATE
 BM_SETSTATE  QuickInfo  Overview  Group

BM_SETSTATE

wParam = (WPARAM) fState;   // highlight state

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

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.

Parameters

fState

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

Return Value

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.

See Also

BM_GETSTATE, BM_SETCHECK


BM_SETSTYLE
 BM_SETSTYLE  QuickInfo  Overview  Group

BM_SETSTYLE

wParam =  (WPARAM) LOWORD(dwStyle); // style

lParam =  MAKELPARAM(fRedraw, 0);   // redraw flag

An application sends a BM_SETSTYLE message to change the style of a button.

Parameters

dwStyle

Value of wParam. Specifies the button style. For an explanation of button styles, see the following Remarks section.

fRedraw

Value of the low-order word of lParam. Specifies whether the button is to be redrawn. A value of TRUE redraws the button; a value of FALSE does not redraw the button.

Return Value

This message always returns zero.

Remarks

Following are the available 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 unchecked. Use the grayed state to show that the state of the check box is not determined.
BS_AUTO3STATE	Creates a button that is the same as a three-state check box, except that the box changes its state when the user selects it. The state cycles through checked, grayed, and unchecked.
BS_AUTOCHECKBOX	Creates a button that is the same as a check box, except that the check state automatically toggles between checked and unchecked each time the user selects the check box.
BS_AUTORADIOBUTTON	Creates a button that is the same as a radio button, except that when the user selects it, Windows automatically sets the button's check state to checked and automatically sets the check state for all other buttons in the same group to unchecked.
BS_CHECKBOX	Creates a small, empty check box with text. By default, the text is displayed to the right of the check box. To display the text to the left of the check box, combine this flag with the BS_LEFTTEXT style (or on Windows 95 only, 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 Windows 95 BS_RIGHTBUTTON style.
BS_OWNERDRAW	Creates an owner-drawn button. The owner window receives a WM_MEASUREITEM message when the button is created and a WM_DRAWITEM message when a visual aspect of the button has changed. Do not combine the BS_OWNERDRAW style with any other button styles.
BS_PUSHBUTTON	Creates a push button that posts a WM_COMMAND message to the owner window when the user selects the button.
BS_RADIOBUTTON	Creates a small circle with text. By default, the text is displayed to the right of the circle. To display the text to the left of the circle, combine this flag with the BS_LEFTTEXT style (or on Windows 95 only, 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	Windows 95 only: Specifies that the button displays a bitmap.
BS_BOTTOM	Windows 95 only: Places text at the bottom of the button rectangle.
BS_CENTER	Windows 95 only: Centers text horizontally in the button rectangle.
BS_ICON	Windows 95 only: Specifies that the button displays an icon.
BS_LEFT	Windows 95 only: 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	Windows 95 only: 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	Windows 95 only: Enables a button to send BN_DBLCLK, BN_KILLFOCUS, and BN_SETFOCUS notification messages to its parent window. Note that buttons send the BN_CLICKED notification message regardless of whether it has this style.
BS_PUSHLIKE	Windows 95 only: 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	Windows 95 only: 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	Windows 95 only: 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	Windows 95 only: Specifies that the button displays text.
BS_TOP	Windows 95 only: Places text at the top of the button rectangle.
BS_VCENTER	Windows 95 only: Places text in the middle (vertically) of the button rectangle.
See Also

WM_COMMAND, WM_DRAWITEM, WM_MEASUREITEM


BN_CLICKED
 BN_CLICKED  QuickInfo  Overview  Group

BN_CLICKED

idButton = (int) LOWORD(wParam);    // identifier of button

hwndButton = (HWND) lParam;         // handle of button

The BN_CLICKED notification message is sent when the user clicks a mouse button. The parent window of the button receives this notification message through the WM_COMMAND message. Unlike the other button notification messages, this message is intended for applications written for any version of Windows.

Remarks

A disabled button does not send a BN_CLICKED notification message to its parent window.

See Also

WM_COMMAND


BN_DBLCLK [New - Windows 95]
 BN_DBLCLK  QuickInfo  Overview  Group

[New - Windows 95]

BN_DBLCLK

idButton = (int) LOWORD(wParam);    // identifier of button

hwndButton = (HWND) lParam;         // handle of button

The BN_DBLCLK notification message is sent when the user double-clicks a button that has the BS_OWNERDRAW or BS_RADIOBUTTON style. The parent window of the button receives this notification message through a WM_COMMAND message.

BN_DBLCLK is the same as the BN_DOUBLECLICKED notification message.

This notification is provided for compatibility with applications written for versions of Windows earlier than version 3.0. New applications should use the BS_OWNERDRAW button style and the DRAWITEMSTRUCT structure for this task.

See Also

BN_CLICKED, BN_DOUBLECLICKED, WM_COMMAND


BN_DISABLE
 BN_DISABLE  QuickInfo  Overview  Group

BN_DISABLE

The BN_DISABLE notification message is sent when a button is disabled. The parent window of the button receives this notification message through the WM_COMMAND message.

This notification message is provided for compatibility with applications written for versions of Windows earlier than version 3.0. New applications should use the BS_OWNERDRAW button style and the DRAWITEMSTRUCT structure for this task.

See Also

DRAWITEMSTRUCT, WM_COMMAND, WM_DRAWITEM


BN_DOUBLECLICKED
 BN_DOUBLECLICKED  QuickInfo  Overview  Group

BN_DOUBLECLICKED

The BN_DOUBLECLICKED notification message is sent when the user double-clicks a button that has the BS_OWNERDRAW or BS_RADIOBUTTON style. The parent window of the button receives this notification message through the WM_COMMAND message.

BN_DOUBLECLICKED is the same as the Windows 95 BN_DBLCLK notification message.

This notification is provided for compatibility with applications written for versions of Windows earlier than version 3.0. New applications should use the BS_OWNERDRAW button style and the DRAWITEMSTRUCT structure for this task.

See Also

BN_DBLCLK, DRAWITEMSTRUCT, WM_COMMAND, WM_DRAWITEM


BN_HILITE
 BN_HILITE  QuickInfo  Overview  Group

BN_HILITE

The BN_HILITE notification message is sent when the user selects a button. The parent window of the button receives this notification message through the WM_COMMAND message.

This notification message is provided for compatibility with applications written for versions of Windows earlier than version 3.0. New applications should use the BS_OWNERDRAW button style and the DRAWITEMSTRUCT structure for this task.

BN_HILITE is the same as the Windows 95 BN_PUSHED notification message.

See Also

BN_PUSHED, BN_UNHILITE, DRAWITEMSTRUCT, WM_COMMAND, WM_DRAWITEM


BN_KILLFOCUS [New - Windows 95]
 BN_KILLFOCUS  QuickInfo  Overview  Group

[New - Windows 95]

BN_KILLFOCUS

The BN_KILLFOCUS notification message is sent when a button loses the keyboard focus. The button must have the BS_NOTIFY style to send this notification message. The parent window of the button receives this notification message through the WM_COMMAND message.

See Also

BN_SETFOCUS, WM_COMMAND


BN_PAINT
 BN_PAINT  QuickInfo  Overview  Group

BN_PAINT

The BN_PAINT notification message is sent when a button should be painted. The parent window of the button receives this notification message through the WM_COMMAND message.

This notification message is provided for compatibility with applications written for versions of Windows earlier than version 3.0. New applications should use the BS_OWNERDRAW button style and the DRAWITEMSTRUCT structure for this task.

See Also

DRAWITEMSTRUCT, WM_COMMAND, WM_DRAWITEM


BN_PUSHED [New - Windows 95]
 BN_PUSHED  QuickInfo

[New - Windows 95]

BN_PUSHED

The BN_PUSHED notification message is sent when the push state of a button is set to pushed. The parent window of the button receives this notification message through the WM_COMMAND message.

BN_PUSHED is the same as the BN_HILITE notification message.

This notification message is provided for compatibility with applications written for versions of Windows earlier than version 3.0. New applications should use the BS_OWNERDRAW button style and the DRAWITEMSTRUCT structure for this task.

See Also

BN_HILITE, BN_UNPUSHED, DRAWITEMSTRUCT, WM_COMMAND, WM_DRAWITEM


BN_SETFOCUS [New - Windows 95]
 BN_SETFOCUS  QuickInfo  Overview  Group

[New - Windows 95]

BN_SETFOCUS

The BN_SETFOCUS notification message is sent when a button receives the keyboard focus. The button must have the BS_NOTIFY style to send this notification message. The parent window of the button receives this notification message through the WM_COMMAND message.

See Also

BN_KILLFOCUS, WM_COMMAND


BN_UNHILITE
 BN_UNHILITE  QuickInfo  Overview  Group

BN_HILITE

The BN_UNHILITE notification message is sent when the highlight should be removed from a button. The parent window of the button receives this notification message through the WM_COMMAND message.

BN_UNHILITE is the same as the Windows 95 BN_UNPUSHED notification message.

This notification message is provided for compatibility with applications written for versions of Windows earlier than version 3.0. New applications should use the BS_OWNERDRAW button style and the DRAWITEMSTRUCT structure for this task.

See Also

BN_HILITE, BN_UNPUSHED, DRAWITEMSTRUCT, WM_COMMAND, WM_DRAWITEM


BN_UNPUSHED [New - Windows 95]
 BN_UNPUSHED  QuickInfo

[New - Windows 95]

BN_PUSHED

The BN_UNPUSHED notification message is sent when the push state of a button is set to unpushed. The parent window of the button receives this notification message through the WM_COMMAND message.

BN_UNPUSHED is the same as the BN_UNHILITE notification message.

This notification message is provided for compatibility with applications written for versions of Windows earlier than version 3.0. New applications should use the BS_OWNERDRAW button style and the DRAWITEMSTRUCT structure for this task.

See Also

BN_PUSHED, DRAWITEMSTRUCT, WM_COMMAND, WM_DRAWITEM


CB_ADDSTRING
 CB_ADDSTRING  QuickInfo  Overview  Group

CB_ADDSTRING

wParam = 0;                         // not used; must be zero

lParam = (LPARAM) (LPCTSTR) lpsz;    // address of string to add

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.

Parameters

lpsz

Value of lParam. Points to the null-terminated string to be added. If you create the combo box with an owner-drawn style but without the CBS_HASSTRINGS style, the value of the lpsz parameter is stored as item data rather than the string it would otherwise point to. The item data can be retrieved or modified by sending the CB_GETITEMDATA or CB_SETITEMDATA message.

Return Value

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.

See Also

CB_DIR, CB_INSERTSTRING, WM_COMPAREITEM


CB_DELETESTRING
 CB_DELETESTRING  QuickInfo  Overview  Group

CB_DELETESTRING

wParam = (WPARAM) index;  // item to delete

lParam = 0;               // not used; must be zero

An application sends a CB_DELETESTRING message to delete a string in the list box of a combo box.

Parameters

index

Value of wParam. Specifies the zero-based index of the string to delete.

Return Value

The return value is a count of the strings remaining in the list. If the index parameter specifies an index greater than the number of items in the list, the return value is CB_ERR.

Remarks

If you create the combo box with an owner-drawn style but without the CBS_HASSTRINGS style, Windows sends a WM_DELETEITEM message to the owner of the combo box so the application can free any additional data associated with the item.

See Also

CB_RESETCONTENT, WM_DELETEITEM


CB_DIR
 CB_DIR  QuickInfo  Overview  Group

CB_DIR

wParam = (WPARAM) (UINT) uAttrs;          // file attributes

lParam = (LPARAM) (LPCTSTR) lpszFileSpec; // address of filename

An application sends a CB_DIR message to add a list of filenames to the list box of a combo box.

Parameters

uAttrs

Value of wParam. Specifies the attributes of the files to be added to the list box. It can be any combination of the following values:

Value	Meaning
DDL_ARCHIVE	Includes archived files.
DDL_DIRECTORY	Includes subdirectories. Subdirectory names are enclosed in square brackets ([ ]).
DDL_DRIVES	Includes drives. Drives are listed in the form [-x-], where x is the drive letter.
DDL_EXCLUSIVE	Includes only files with the specified attributes. By default, read-write files are listed even if DDL_READWRITE is not specified.
DDL_HIDDEN	Includes hidden files.
DDL_READONLY	Includes read-only files.
DDL_READWRITE	Includes read-write files with no additional attributes.
DDL_SYSTEM	Includes system files.
lpszFileSpec

Value of lParam. Points to the null-terminated string that specifies the filename to add to the list. If the filename contains any wildcards (for example, *.*), all files that match and have the attributes specified by the uAttrs parameter are added to the list.

Return Value

The return value is the zero-based index of the last filename added to the list. If an error occurs, the return value is CB_ERR. If insufficient space is available to store the new strings, it is CB_ERRSPACE.

See Also

CB_ADDSTRING, CB_INSERTSTRING, DlgDirList, DlgDirListComboBox


CB_FINDSTRING
 CB_FINDSTRING  QuickInfo  Overview  Group

CB_FINDSTRING

wParam = (WPARAM) indexStart;        // item before start of search

lParam = (LPARAM) (LPCSTR) lpszFind  // prefix string address

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.

Parameters

indexStart

Value of wParam. Specifies the zero-based index of the item preceding the first item to be searched. When the search reaches the bottom of the list box, it continues from the top of the list box back to the item specified by the indexStart parameter. If indexStart is −1, the entire list box is searched from the beginning.

lpszFind

Value of lParam. Points to the null-terminated string that contains the prefix to search for. The search is not case sensitive, so this string can contain any combination of uppercase and lowercase letters.

Return Value

The return value is the zero-based index of the matching item. If the search is unsuccessful, it is CB_ERR.

Remarks

If you create the combo box with an owner-drawn style but without the CBS_HASSTRINGS style, what the CB_FINDSTRING message does depends on whether your application uses the CBS_SORT style. If you use the CBS_SORT style, WM_COMPAREITEM messages are sent to the owner of the combo box to determine which item matches the specified string. If you do not use the CBS_SORT style, the CB_FINDSTRING message searches for a list item that matches the value of the lpszFind parameter.

See Also

CB_FINDSTRINGEXACT, CB_SELECTSTRING, CB_SETCURSEL, WM_COMPAREITEM


CB_FINDSTRINGEXACT
 CB_FINDSTRINGEXACT  QuickInfo  Overview  Group

CB_FINDSTRINGEXACT

wParam = (WPARAM) indexStart;      // item before start of search

lParam = (LPARAM)(LPCSTR)lpszFind; // address of string to search for

An application sends a CB_FINDSTRINGEXACT message to find the first list box string in a combo box that matches the string specified in the lpszFind parameter.

Parameters

indexStart

Value of wParam. Specifies the zero-based index of the item preceding the first item to be searched. When the search reaches the bottom of the list box, it continues from the top of the list box back to the item specified by the indexStart parameter. If indexStart is −1, the entire list box is searched from the beginning.

lpszFind

Value of lParam. Points to the null-terminated string to search for. This string can contain a complete filename, including the extension. The search is not case sensitive, so this string can contain any combination of uppercase and lowercase letters.

Return Value

The return value is the zero-based index of the matching item. If the search is unsuccessful, it is CB_ERR.

Remarks

If you create the combo box with an owner-drawn style but without the CBS_HASSTRINGS style, what the CB_FINDSTRINGEXACT message does depends on whether your application uses the CBS_SORT style. If you use the CBS_SORT style, WM_COMPAREITEM messages are sent to the owner of the combo box to determine which item matches the specified string. If you do not use the CBS_SORT style, the CB_FINDSTRINGEXACT message searches for a list item that matches the value of the lpszFind parameter.

See Also

CB_FINDSTRING, CB_SELECTSTRING, WM_COMPAREITEM


CB_GETCOUNT
 CB_GETCOUNT  QuickInfo  Overview  Group

CB_GETCOUNT

wParam = 0;     // not used; must be zero

lParam = 0;     // not used; must be zero

An application sends a CB_GETCOUNT message to retrieve the number of items in the list box of a combo box.

Parameters

This message has no parameters.

Return Value

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.


CB_GETCURSEL
 CB_GETCURSEL  QuickInfo  Overview  Group

CB_GETCURSEL

wParam = 0;     // not used; must be zero

lParam = 0;     // not used; must be zero

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.

Parameters

This message has no parameters.

Return Value

The return value is the zero-based index of the currently selected item. If no item is selected, it is CB_ERR.

See Also

CB_SELECTSTRING, CB_SETCURSEL


CB_GETDROPPEDCONTROLRECT
 CB_GETDROPPEDCONTROLRECT  QuickInfo  Overview  Group

CB_GETDROPPEDCONTROLRECT

wParam = 0;                         // not used; must be zero

lParam = (LPARAM) (RECT FAR*) lprc; // address of RECT structure

An application sends a CB_GETDROPPEDCONTROLRECT message to retrieve the screen coordinates of the drop-down list box of a combo box.

Parameters

lprc

Value of lParam. Points to the RECT structure that is to receive the coordinates.

Return Value

This message always returns CB_OKAY.

See Also

RECT


CB_GETDROPPEDSTATE
 CB_GETDROPPEDSTATE  QuickInfo

CB_GETDROPPEDSTATE

wParam = 0;     // not used; must be zero

lParam = 0;     // not used; must be zero

An application sends a CB_GETDROPPEDSTATE message to determine whether the list box of a combo box is dropped down.

Parameters

This message has no parameters.

Return Value

If the list box is visible, the return value is TRUE; otherwise, it is FALSE.

See Also

CB_SHOWDROPDOWN


CB_GETDROPPEDWIDTH [New - Windows 95]
 CB_GETDROPPEDWIDTH  QuickInfo

[New - Windows 95]

CB_GETDROPPEDWIDTH

wParam = 0;     // not used, must be zero

lParam = 0;     // not used, must be zero

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.

Parameters

This message has no parameters.

Return Value

If the message succeeds, the return value is the width, in pixels.

If the message fails, the return value is CB_ERR.

Remarks

By default, the minimum allowable width of the drop-down list box is 0. The width of the list box is either the minimum allowable width or the combo box width, whichever is larger.

See Also

CB_SETDROPPEDWIDTH


CB_GETEDITSEL
 CB_GETEDITSEL  QuickInfo  Overview  Group

CB_GETEDITSEL

wParam = (WPARAM) (LPDWORD) lpdwStart; // receives starting position

lParam = (LPARAM) (LPDWORD) lpdwEnd;   // receives ending position

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.

Parameters

lpdwStart

Value of wParam. Points to a 32-bit value that receives the starting position of the selection. This parameter can be set to NULL.

lpdwEnd

Value of lParam. Points to a 32-bit value that receives the ending position of the selection. This parameter can be set to NULL.

Return Value

The return value is a zero-based 32-bit value with the starting position of the selection in the low-order word and with the ending position of the first character after the last selected character in the high-order word.

See Also

CB_SETEDITSEL


CB_GETEXTENDEDUI
 CB_GETEXTENDEDUI  QuickInfo  Overview  Group

CB_GETEXTENDEDUI

wParam = 0;     // not used; must be zero

lParam = 0;     // not used; must be zero

An application sends a CB_GETEXTENDEDUI message to determine whether a combo box has the default user interface or the extended user interface.

Parameters

This message has no parameters.

Return Value

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.

See Also

CB_SETEXTENDEDUI


CB_GETHORIZONTALEXTENT [New - Windows 95]
 CB_GETHORIZONTALEXTENT  QuickInfo

[New - Windows 95]

CB_GETHORIZONTALEXTENT

wParam = 0;     // not used, must be zero

lParam = 0;     // not used, must be zero

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.

Parameters

This message has no parameters.

Return Value

The return value is the scrollable width, in pixels.

See Also

CB_SETHORIZONTALEXTENT


CB_GETITEMDATA
 CB_GETITEMDATA  QuickInfo  Overview  Group

CB_GETITEMDATA

wParam = (WPARAM) index;  // item index

lParam = 0;               // not used; must be zero

An application sends a CB_GETITEMDATA message to a combo box to retrieve the application-supplied 32-bit value associated with the specified item in the combo box.

Parameters

index

Value of wParam. Specifies the zero-based index of the item.

Return Value

The return value is the 32-bit value associated with the item. If an error occurs, it is CB_ERR.

If the item is in an owner-drawn combo box created without the CBS_HASSTRINGS style, the return value is the 32-bit value contained in the lParam parameter of the CB_ADDSTRING or CB_INSERTSTRING message that added the item to the combo box. If the CBS_HASSTRINGS style was not used, the return value is the lParam parameter contained in a CB_SETITEMDATA message.

See Also

CB_ADDSTRING, CB_INSERTSTRING, CB_SETITEMDATA


CB_GETITEMHEIGHT
 CB_GETITEMHEIGHT  QuickInfo  Overview  Group

CB_GETITEMHEIGHT

wParam = (WPARAM) index;  // item index

lParam = 0;               // not used; must be zero

An application sends a CB_GETITEMHEIGHT message to determine the height of list items or the selection field in a combo box.

Parameters

index

Value of wParam. Specifies the combo box component whose height is to be retrieved.

This parameter must be −1 to retrieve the height of the selection field. It must be zero to retrieve the height of list items, unless the combo box has the CBS_OWNERDRAWVARIABLE style. In that case, the index parameter is the zero-based index of a specific list item.

Return Value

The return value is the height, in pixels, of the list items in a combo box. If the combo box has the CBS_OWNERDRAWVARIABLE style, it is is the height of the item specified by the index parameter. If index is −1, the return value is the height of the edit control (or static-text) portion of the combo box. If an error occurs, the return value is CB_ERR.

See Also

CB_SETITEMHEIGHT, WM_MEASUREITEM


CB_GETLBTEXT
 CB_GETLBTEXT  QuickInfo  Overview  Group

CB_GETLBTEXT

wParam = (WPARAM) index;                // item index

lParam = (LPARAM) (LPCSTR) lpszBuffer;  // address of buffer

An application sends a CB_GETLBTEXT message to retrieve a string from the list of a combo box.

Parameters

index

Value of wParam. Specifies the zero-based index of the string to retrieve.

lpszBuffer

Value of lParam. Points to the buffer that receives the string. The buffer must have sufficient space for the string and a terminating null character. You can send a CB_GETLBTEXTLEN message prior to the CB_GETLBTEXT message to retrieve the length, in bytes, of the string.

Return Value

The return value is the length of the string, in bytes, excluding the terminating null character. If the index parameter does not specify a valid index, the return value is CB_ERR.

Remarks

If you create the combo box with an owner-drawn style but without the CBS_HASSTRINGS style, the buffer pointed to by the lpszBuffer parameter of the message receives the 32-bit value associated with the item (the item data).

See Also

CB_GETLBTEXTLEN


CB_GETLBTEXTLEN
 CB_GETLBTEXTLEN  QuickInfo  Overview  Group

CB_GETLBTEXTLEN

wParam = (WPARAM) index;  // item index

lParam = 0;               // not used; must be zero

An application sends a CB_GETLBTEXTLEN message to retrieve the length, in characters, of a string in the list of a combo box.

Parameters

index

Value of wParam. Specifies the zero-based index of the string.

Return Value

The return value is the length of the string, in characters, excluding the terminating null character. Under certain conditions, this value may actually be greater than the length of the text. For more information, see the following Remarks section.

If the index parameter does not specify a valid index, the return value is CB_ERR.

Remarks

Under certain conditions, the return value is larger than the actual length of the text. This occurs with certain mixtures of ANSI and Unicode, and is due to the operating system allowing for the possible existence of double-byte character set (DBCS) characters within the text. The return value, however, will always be at least as large as the actual length of the text; so you can always use it to guide buffer allocation. This behavior can occur when an application uses both ANSI functions and common dialogs, which use Unicode.

To obtain the exact length of the text, use the WM_GETTEXT, LB_GETTEXT, or CB_GETLBTEXT messages, or the GetWindowText function.

See Also

CB_GETLBTEXT, GetWindowText, LB_GETTEXT, WM_GETTEXT


CB_GETLOCALE
 CB_GETLOCALE  QuickInfo  Overview  Group

CB_GETLOCALE

wParam = 0; // not used; must be zero

lParam = 0; // not used; must be zero

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.

Parameters

This message has no parameters.

Return Value

The return value is a 32-bit value that specifies the current locale of the combo box. The high word contains the country code and the low-order word contains the language identifier.

Remarks

The language identifier is made up of a sublanguage identifier and a primary language identifier. The PRIMARYLANGID macro obtains the primary language identifier and the SUBLANGID macro obtains the sublanguage identifier.

See Also

CB_ADDSTRING, CB_SETLOCALE, PRIMARYLANGID, SUBLANGID


CB_GETTOPINDEX [New - Windows 95]
 CB_GETTOPINDEX  QuickInfo

[New - Windows 95]

CB_GETTOPINDEX

wParam = 0;     // not used, must be zero

lParam = 0;     // not used, must be zero

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.

Parameters

This message has no parameters.

Return Value

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.

See Also

CB_SETTOPINDEX


CB_INITSTORAGE [New - Windows 95]
 CB_INITSTORAGE  QuickInfo

[New - Windows 95]

CB_INITSTORAGE

wParam = (WPARAM) (int) cItems;     // number of items to add

lParam = (LPARAM) (DWORD) cb;       // amount of memory to allocate, in bytes

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.

Parameters

cItems

Specifies the number of items to add.

cb

Specifies the amount of memory to allocate for item strings, in bytes.

Return Value

If the message is successful, the return value is the maximum number of items that the memory object can store.

If the message fails, the return value is CB_ERR.

Remarks

This message helps speed up the initialization of combo boxes that have a large number of items (over 100). It preallocates the specified amount of memory so that subsequent CB_ADDSTRING, CB_INSERTSTRING and CB_DIR messages take the shortest possible time. You can use estimates for the cItems and cb parameters. If you overestimate, some extra memory is allocated, if you underestimate, the normal allocation is used for items that exceed the preallocated amount.

See Also

CB_ADDSTRING, CB_DIR, CB_INSERTSTRING


CB_INSERTSTRING
 CB_INSERTSTRING  QuickInfo  Overview  Group

CB_INSERTSTRING

wParam = (WPARAM) index;         // item index

lParam = (LPARAM) (LPCTSTR) lpsz; // address of string to insert

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.

Parameters

index

Value of wParam. Specifies the zero-based index of the position at which to insert the string. If this parameter is −1, the string is added to the end of the list.

lpsz

Value of lParam. Points to the null-terminated string to be inserted. If you create the combo box with an owner-drawn style but without the CBS_HASSTRINGS style, the value of the lpsz parameter is stored rather than the string it would otherwise point to.

Return Value

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.

See Also

CB_ADDSTRING, CB_DIR


CB_LIMITTEXT
 CB_LIMITTEXT  QuickInfo  Overview  Group

CB_LIMITTEXT

wParam = (WPARAM) cchLimit;   // maximum number of characters

lParam = 0;                   // not used; must be zero

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.

Parameters

cchLimit

Value of wParam. Specifies the maximum number of characters the user can enter. If this parameter is zero, the text length is set to 0x7FFFFFFE characters.

Return Value

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.


CB_RESETCONTENT
 CB_RESETCONTENT  QuickInfo  Overview  Group

CB_RESETCONTENT

wParam = 0;     // not used; must be zero

lParam = 0;     // not used; must be zero

An application sends a CB_RESETCONTENT message to remove all items from the list box and edit control of a combo box.

Parameters

This message has no parameters.

Return Value

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.

See Also

CB_DELETESTRING, WM_DELETEITEM


CB_SELECTSTRING
 CB_SELECTSTRING  QuickInfo  Overview  Group

CB_SELECTSTRING

wParam = (WPARAM) indexStart;          // item before first selection

lParam = (LPARAM) (LPCSTR) lpszSelect; // address of prefix string

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.

Parameters

indexStart

Value of wParam. Specifies the zero-based index of the item preceding the first item to be searched. When the search reaches the bottom of the list, it continues from the top of the list back to the item specified by the indexStart parameter. If indexStart is −1, the entire list is searched from the beginning.

lpszSelect

Value of lParam. Points to the null-terminated string that contains the prefix to search for. The search is not case sensitive, so this string can contain any combination of uppercase and lowercase letters.

Return Value

If the string is found, the return value is the index of the selected item. If the search is unsuccessful, the return value is CB_ERR and the current selection is not changed.

Remarks

A string is selected only if the characters from the starting point match the characters in the prefix string.

If you create the combo box with an owner-drawn style but without the CBS_HASSTRINGS style, what the CB_SELECTSTRING message does depends on whether you use the CBS_SORT style. If the CBS_SORT style is used, the system sends WM_COMPAREITEM messages to the owner of the combo box to determine which item matches the specified string. If you do not use the CBS_SORT style, CB_SELECTSTRING attempts to match the DWORD value against the value of the lpszSelect parameter.

See Also

CB_FINDSTRING, CB_FINDSTRINGEXACT, CB_SETCURSEL, WM_COMPAREITEM


CB_SETCURSEL
 CB_SETCURSEL  QuickInfo  Overview  Group

CB_SETCURSEL

wParam = (WPARAM) index;  // item index

lParam = 0;               // not used; must be zero

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.

Parameters

index

Value of wParam. Specifies the zero-based index of the string to select. If the index parameter is −1, any current selection in the list is removed and the edit control is cleared.

Return Value

If the message is successful, the return value is the index of the item selected. If index is greater than the number of items in the list or if index is set to −1, the return value is CB_ERR and the selection is cleared.

See Also

CB_FINDSTRING, CB_GETCURSEL, CB_SELECTSTRING


CB_SETDROPPEDWIDTH [New - Windows 95]
 CB_SETDROPPEDWIDTH  QuickInfo

[New - Windows 95]

CB_SETDROPPEDWIDTH

wParam = (WPARAM) wWidth,     // width of list box, in pixels

lParam = 0,                   // not used, must be zero

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.

Parameters

wWidth

Specifies the width of the list box, in pixels.

Return Value

If the message is successful, The return value is the new width of the list box.

If the message fails, the return value is CB_ERR.

Remarks

By default, the minimum allowable width of the drop-zdown list box is 0. The width of the list box is either the minimum allowable width or the combo box width, whichever is larger.

See Also

CB_GETDROPPEDWIDTH


CB_SETEDITSEL
 CB_SETEDITSEL  QuickInfo  Overview  Group

CB_SETEDITSEL

wParam = 0;                                // not used; must be zero

lParam = MAKELPARAM((ichStart), (ichEnd);  // start and end position

An application sends a CB_SETEDITSEL message to select characters in the edit control of a combo box.

Parameters

ichStart

Value of the low-order word of lParam; this specifies the starting position. If this parameter is set to −1, the selection, if any, is removed.

ichEnd

Value of the high-order word of lParam; this specifies the ending position. If this parameter is set to −1, all text from the starting position to the last character in the edit control is selected.

Return Value

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.

See Also

CB_GETEDITSEL


CB_SETEXTENDEDUI
 CB_SETEXTENDEDUI  QuickInfo  Overview  Group

CB_SETEXTENDEDUI

wParam = (WPARAM) (BOOL) fExtended;    // extended user interface flag

lParam = 0;                            // not used; must be zero

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.

Parameters

fExtended

Value of wParam. Specifies whether the combo box uses the extended user interface or the default user interface. A value of TRUE selects the extended user interface; a value of FALSE selects the standard user interface.

Return Value

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.

See Also

CB_GETEXTENDEDUI


CB_SETHORIZONTALEXTENT [New - Windows 95]
 CB_SETHORIZONTALEXTENT  QuickInfo

[New - Windows 95]

CB_SETHORIZONTALEXTENT

wParam = (WPARAM) cxExtent;            // scrollable width of list box, in pixels

lParam = 0;                            // not used, must be zero

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.

Parameters

cxExtent

Specifies the scrollable width of the list box, in pixels.

Return Value

No return value.

See Also

CB_GETHORIZONTALEXTENT


CB_SETITEMDATA
 CB_SETITEMDATA  QuickInfo  Overview  Group

CB_SETITEMDATA

wParam = (WPARAM) index;            // item index

lParam = (LPARAM) (DWORD) dwData;   // item data

An application sends a CB_SETITEMDATA message to set the 32-bit value associated with the specified item in a combo box.

Parameters

index

Value of wParam. Specifies the item's zero-based index.

dwData

Value of lParam. Specifies the new value to be associated with the item.

Return Value

If an error occurs, the return value is CB_ERR.

Remarks

If the specified item is in an owner-drawn combo box created without the CBS_HASSTRINGS style, this message replaces the 32-bit value in the lParam parameter of the CB_ADDSTRING or CB_INSERTSTRING message that added the item to the combo box.

See Also

CB_ADDSTRING, CB_GETITEMDATA, CB_INSERTSTRING


CB_SETITEMHEIGHT
 CB_SETITEMHEIGHT  QuickInfo  Overview  Group

CB_SETITEMHEIGHT

wParam = (WPARAM) index;        // item index

lParam = (LPARAM) (int) height; // item height

An application sends a CB_SETITEMHEIGHT message to set the height of list items or the selection field in a combo box.

Parameters

index

Value of wParam. Specifies the component of the combo box for which to set the height.

This parameter must be −1 to set the height of the selection field. It must be zero to set the height of list items, unless the combo box has the CBS_OWNERDRAWVARIABLE style. In that case, the index parameter is the zero-based index of a specific list item.

height

Value of lParam. Specifies the height, in pixels, of the combo box component identified by index.

Return Value

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.

See Also

CB_GETITEMHEIGHT, WM_MEASUREITEM


CB_SETLOCALE
 CB_SETLOCALE  QuickInfo  Overview  Group

CB_SETLOCALE

wParam = (WPARAM) (WORD) wLocaleID; // locale identifier

lParam = 0;                         // not used; must be zero

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.

Parameters

wLocaleID

Value of wParam. Specifies the locale identifier for the combo box to use for sorting when adding text.

Return Value

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.

See Also

CB_ADDSTRING, CB_GETLOCALE, MAKELANGID, MAKELCID


CB_SETTOPINDEX [New - Windows 95]
 CB_SETTOPINDEX  QuickInfo

[New - Windows 95]

CB_SETTOPINDEX

wParam = (WPARAM) index;            // zero-based index of item list

lParam = 0;                         // not used, must be zero

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.

Parameters

index

Specifies the zero-based index of the list item.

Return Value

If the message is successful, the return value is zero.

If the message fails, the return value is CB_ERR.

See Also

CB_GETTOPINDEX


CB_SHOWDROPDOWN
 CB_SHOWDROPDOWN  QuickInfo  Overview  Group

CB_SHOWDROPDOWN

wParam = (WPARAM) (BOOL) fShow;     // the show/hide flag

lParam = 0;                         // not used; must be zero

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.

Parameters

fShow

Value of wParam. Specifies whether the drop-down list box is to be shown or hidden. A value of TRUE shows the list box; a value of FALSE hides it.

Return Value

The return value is always TRUE.

Remarks

This message has no effect on a combo box created with the CBS_SIMPLE style.

See Also

CB_GETDROPPEDSTATE


CBN_CLOSEUP
 CBN_CLOSEUP  QuickInfo  Overview  Group

CBN_CLOSEUP

idComboBox = (int) LOWORD(wParam);  // identifier of combo box

hwndComboBox = (HWND) lParam;       // handle of combo box

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.

Remarks

This notification message is not sent to a combo box that has the CBS_SIMPLE style.

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.

See Also

CBN_DROPDOWN, CBN_SELCHANGE, WM_COMMAND


CBN_DBLCLK
 CBN_DBLCLK  QuickInfo  Overview  Group

CBN_DBLCLK

idComboBox = (int) LOWORD(wParam);  // identifier of combo box

hwndComboBox = (HWND) lParam;       // handle of combo box

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.

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.

See Also

CBN_SELCHANGE, WM_COMMAND


CBN_DROPDOWN
 CBN_DROPDOWN  QuickInfo  Overview  Group

CBN_DROPDOWN

idComboBox = (int) LOWORD(wParam);  // identifier of combo box

hwndComboBox = (HWND) lParam;       // handle of combo box

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.

Remarks

This notification message can occur only for a combo box with the CBS_DROPDOWN or CBS_DROPDOWNLIST style.

See Also

CBN_CLOSEUP, WM_COMMAND


CBN_EDITCHANGE
 CBN_EDITCHANGE  QuickInfo  Overview  Group

CBN_EDITCHANGE

idComboBox = (int) LOWORD(wParam);  // identifier of combo box

hwndComboBox = (HWND)lParam;        // handle of combo box

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 Windows updates the screen. The parent window of the combo box receives this notification message through the WM_COMMAND message.

Remarks

If the combo box has the CBS_DROPDOWNLIST style, this notification message does not occur.

See Also

CBN_EDITUPDATE, WM_COMMAND


CBN_EDITUPDATE
 CBN_EDITUPDATE  QuickInfo  Overview  Group

CBN_EDITUPDATE

idComboBox = (int) LOWORD(wParam);  // identifier of combo box

hwndComboBox = (HWND) lParam;       // handle of combo box

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.

Remarks

If the combo box has the CBS_DROPDOWNLIST style, this notification message does not occur.

See Also

CBN_EDITCHANGE, WM_COMMAND


CBN_ERRSPACE
 CBN_ERRSPACE  QuickInfo  Overview  Group

CBN_ERRSPACE

idComboBox = (int) LOWORD(wParam);  // identifier of combo box

hwndComboBox = (HWND) lParam;       // handle of combo box

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.

See Also

WM_COMMAND


CBN_KILLFOCUS
 CBN_KILLFOCUS  QuickInfo  Overview  Group

CBN_KILLFOCUS

idComboBox = (int) LOWORD(wParam);  // identifier of combo box

hwndComboBox = (HWND) lParam;       // handle of combo box

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.

See Also

CBN_SETFOCUS, WM_COMMAND


CBN_SELCHANGE
 CBN_SELCHANGE  QuickInfo  Overview  Group

CBN_SELCHANGE

idComboBox = (int) LOWORD(wParam);  // identifier of combo box

hwndComboBox = (HWND) lParam;       // handle of combo box

The CBN_SELCHANGE notification message is sent when the selection in the list box of a combo box is about to be changed as a result of the user either clicking in the list box or changing the selection by using the arrow keys. The parent window of the combo box receives this message through the WM_COMMAND message.

See Also

CBN_DBLCLK, WM_COMMAND


CBN_SELENDCANCEL
 CBN_SELENDCANCEL  QuickInfo  Overview  Group

CBN_SELENDCANCEL

idComboBox = (int) LOWORD(wParam);  // identifier of combo box

hwndComboBox = (HWND) lParam;       // handle of combo box

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.

Remarks

In a combo box with the CBS_SIMPLE style, the CBN_SELENDCANCEL notification message is not sent. The CBN_SELENDOK notification message is sent immediately before every CBN_SELCHANGE notification message.

If the WS_EX_NOPARENTNOTIFY extended window style is specified for the combo box, the CBN_SELENDCANCEL notification message is not sent.

See Also

CBN_SELCHANGE, CBN_SELENDOK, WM_COMMAND


CBN_SELENDOK
 CBN_SELENDOK  QuickInfo  Overview  Group

CBN_SELENDOK

idComboBox = (int) LOWORD(wParam);  // identifier of combo box

hwndComboBox = (HWND) lParam;       // handle of combo box

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.

Remarks

In a combo box with the CBS_SIMPLE style, the CBN_SELENDOK notification message is sent immediately before every CBN_SELCHANGE notification message.

If the WS_EX_NOPARENTNOTIFY extended window style is specified for the combo box, the CBN_SELENDOK notification message is not sent.

See Also

CBN_SELCHANGE, CBN_SELENDCANCEL, WM_COMMAND


CBN_SETFOCUS
 CBN_SETFOCUS  QuickInfo  Overview  Group

CBN_SETFOCUS

idComboBox = (int) LOWORD(wParam);  // identifier of combo box

hwndComboBox = (HWND) lParam;       // handle of combo box

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.

See Also

CBN_KILLFOCUS, WM_COMMAND


CDM_GETFILEPATH
 CDM_GETFILEPATH  Overview  Group

CDM_GETFILEPATH

wParam = (WPARAM) cbBufSize;

lParam = (LPARAM) (LPTSTR) lpszFileBuf;

// Corresponding macro

int CommDlg_OpenSave_GetFilePath(hwndDlg, lpszFileBuf, cbBufSize);

Retrieves the path and filename of the selected file in the common Open or Save As dialog box. The common dialog box must have been created with the OFN_EXPLORER flag; otherwise, the message fails.

Parameters

hwndDlg

Handle of the common dialog box to receive the message.

lpszFileBuf

Address of the buffer that receives the filename and path.

cbBufSize

Size, in bytes, of the buffer.

Return Value

Returns the number of bytes copied to the buffer specified by lpszFileBuf, including the terminating NULL character. If the buffer is too small, the return value is the required size, in bytes, of the buffer. If the message fails, the return value is zero.


CDM_GETFOLDERIDLIST
 CDM_GETFOLDERIDLIST  Overview  Group

CDM_GETFOLDERIDLIST

wParam = (WPARAM) cbBufSize;

lParam = (LPARAM) (LPVOID) pidl;

// Corresponding macro

int CommDlg_OpenSave_GetFolderIDList(hwndDlg, pidl, cbBufSize);

Retrieves the address of the item identifier list corresponding to the folder that the common Open or Save As dialog box currently has open.

Parameters

hwndDlg

Handle of the common dialog box to receive the message.

pidl

Address of the buffer that receives the list of item identifiers.

cbBufSize

Size, in bytes, of the buffer.

Return Value

Returns the number of bytes copied to the buffer specified by pidl. If the buffer is too small, the return value is the required size, in bytes, of the buffer. If the message fails, the return value is zero.


CDM_GETFOLDERPATH
 CDM_GETFOLDERPATH  Overview  Group

CDM_GETFOLDERPATH

wParam = (WPARAM) cbBufSize;

lParam = (LPARAM) (LPTSTR) lpszFolderBuf;

// Corresponding macro

int CommDlg_OpenSave_GetFolderPath(hwndDlg, lpszFolderBuf, cbBufSize);

Retrieves the path and name of the currently open folder or directory for the common Open or Save As dialog box. The common dialog box must have been created with the OFN_EXPLORER flag; otherwise, the message fails.

Parameters

hwndDlg

Handle of the common dialog box to receive the message.

lpszFolderBuf

Address of the buffer that receives the path and name.

cbBufSize

Size, in bytes, of the buffer.

Return Value

Returns the number of bytes copied to the buffer specified by lpszFileBuf, including the terminating NULL character. If the buffer is too small, the return value is the required size, in bytes, of the buffer. If the message fails, the return value is zero.


CDM_GETSPEC
 CDM_GETSPEC  Overview  Group

CDM_GETSPEC

wParam = (WPARAM) cbBufSize;

lParam = (LPARAM) (LPTSTR) lpszFileBuf;

// Corresponding macro

int CommDlg_OpenSave_GetSpec(hwndDlg, lpszFileBuf, cbBufSize);

Retrieves the filename (not including the path) of the currently selected file in the common Open or Save As dialog box. The common dialog box must have been created with the OFN_EXPLORER flag; otherwise, the message fails.

Parameters

hwndDlg

Handle of the common dialog box to receive the message.

lpszFileBuf

Address of the buffer that receives the path and name.

cbBufSize

Size, in bytes, of the buffer.

Return Value

Returns is the number of bytes copied to the buffer specified by lpszFileBuf, including the terminating NULL character. If the buffer is too small, the return value is the required size, in bytes, of the buffer. If the message fails, the return value is zero.


CDM_HIDECONTROL
 CDM_HIDECONTROL  Overview  Group

CDM_HIDECONTROL
wParam = idCtl;
lParam = 0;

// corresponding macro
void CommDlg_OpenSave_HideControl(hdlg, idCtl);

Hides the given control.

Parameters

idCtl

Identifier of the control to hide.

Return Value

No return value.


CDM_SETCONTROLTEXT
 CDM_SETCONTROLTEXT  Overview  Group

CDM_SETCONTROLTEXT
wParam = idCtl;
lParam = lpszText;

// corresponding macro
void CommDlg_OpenSave_SetControlText(hdlg, idCtl, lpszText)

Sets the text for the given control.

Parameters

idCtl

Identifier of the control to hide.

lpszText

Address of a null-terminated string specifying the new text for the control.

Return Value

No return value.


CDM_SETDEFEXT
 CDM_SETDEFEXT  Overview  Group

CDM_SETDEFEXT
wParam = 0;
lParam = lpszExt;

// corresponding macro
void CommDlg_OpenSave_SetDefExt(hdlg, lpszExt)

Sets the default filename extension for the dialog box.

Parameters

lpszExt

Address of the new filename extension. Must not include the dot (.).

Return Value

No return value.


CDN_FILEOK
 CDN_FILEOK  Overview  Group

CDN_FILEOK

lpon = (LPOFNOTIFY) lParam;

Sent when the Open or Save As dialog box is about to close. This notification is sent as a WM_NOTIFY message to the hook function for the dialog box.

Parameters

lpon

Address of an OFNOTIFY structure that contains file information. The structure include the address of an OPENFILENAME structure whose lpstrFile member specifies the address of the selected filename.

Remarks

The system sends this notification only if the dialog box was created using the OFN_EXPLORER value.

Return Value

Return nonzero to prevent the dialog box from closing. You must use the SetWindowLong function with the DWL_MSGRESULT value to return a result from the hook function.

See Also

OFNOTIFY, OPENFILENAME, SetWindowLong


CDN_FOLDERCHANGE
 CDN_FOLDERCHANGE  Overview  Group

CDN_FOLDERCHANGE

lpon = (LPOFNOTIFY) lParam;

Sent when a new folder is opened in the Open or Save As dialog box. This notification is sent as a WM_NOTIFY message to the hook function for the dialog box.

Parameters

lpon

Address of an OFNOTIFY structure that contains file information.

The system sends this notification only if the dialog box was created using the OFN_EXPLORER value.

Return Value

The return value is ignored.

See Also

OFNOTIFY, WM_NOTIFY


CDN_HELP
 CDN_HELP  Overview  Group

CDN_HELP

lpon = (LPOFNOTIFY) lParam;

Sent when the user clicks the Help button in the Open or Save As dialog box. This notification is sent as a WM_NOTIFY message to the hook function for the dialog box.

Parameters

lpon

Address of an OFNOTIFY structure that contains file information.

The system sends this notification only if the dialog box was created using the OFN_EXPLORER value.

Return Value

The return value is ignored.

See Also

OFNOTIFY, WM_NOTIFY


CDN_INITDONE
 CDN_INITDONE  Overview  Group

CDN_INITDONE

lpon = (LPOFNOTIFY) lParam;

Sent when the system has finished arranging controls in the Open or Save As dialog box to make room for the controls of the child dialog box. This notification is sent as a WM_NOTIFY message to the hook function for the dialog box.

Parameters

lpon

Address of an OFNOTIFY structure that contains file information.

Return Value

The return value is ignored.

Remarks

The system sends this notification only if the dialog box was created using the OFN_EXPLORER value.

See Also

OFNOTIFY, WM_NOTIFY


CDN_SELCHANGE
 CDN_SELCHANGE  Overview  Group

CDN_SELCHANGE

lpon = (LPOFNOTIFY) lParam;

Sent when the user selects a new file or folder in the file list of the common Open or Save As dialog box. This notification is sent as a WM_NOTIFY message to the hook function for the dialog box.

Parameters

lpon

Address of an OFNOTIFY structure that contains file information.

Return Value

The return value is ignored.

Remarks

The system sends this notification only if the dialog box was created using the OFN_EXPLORER value.

See Also

OFNOTIFY, WM_NOTIFY


CDN_SHAREVIOLATION
 CDN_SHAREVIOLATION  Overview  Group

CDN_SHAREVIOLATION

lpon = (LPOFNOTIFY) lParam;

Sent when the Open or Save As common dialog box encounters a sharing violation on the file about to be returned. This notification is sent as a WM_NOTIFY message to the hook function for the dialog box.

Parameters

lpon

Address of an OFNOTIFY structure that contains file information. The pszFile member points to the name of the file that had the sharing violation.

Return Value

Returns one of these values:

OFN_SHAREFALLTHROUGH	Specifies that the filename is returned by the dialog box.
OFN_SHARENOWARN	Specifies no further action.
OFN_SHAREWARN	Specifies that the user receives the standard warning message for this error.
Remarks

You must use the SetWindowLong function with the DWL_MSGRESULT value to return a result from the hook function.

The system sends this notification only if the dialog box was created using the OFN_EXPLORER value.

See Also

OFNOTIFY, SetWindowLong, WM_NOTIFY


CDN_TYPECHANGE
 CDN_TYPECHANGE  Overview  Group

CDN_TYPECHANGE

lpon = (LPOFNOTIFY) lParam;

Sent when the user selects a new file type from the list of file types in the Open or Save As dialog box. This notification is sent as a WM_NOTIFY message to the hook function for the dialog box.

Parameters

lpon

Address of an OFNOTIFY structure that contains file information.

Return Value

The return value is ignored.

Remarks

The system sends this notification only if the dialog box was created using the OFN_EXPLORER value.

See Also

OFNOTIFY, WM_NOTIFY


COLOROKSTRING
 COLOROKSTRING  Overview  Group

msg = uColorOkMsg;
wParam = 0;
lParam = (LPCHOOSECOLOR) lpcc;

Sent to the hook function of a Color dialog box after the user has selected a color and clicked the OK button.

Parameters

uColorOkMsg

Message identifier for the ColorOk message. This value is the same as returned by the RegisterWindowMessage function for the COLOROKSTRING string.

lpcc

Address of the CHOOSECOLOR structure that contains the RGB color value of the selected color in the rgbResult member.

Return Value

Return a zero to accept the selected color and let the dialog box close; return a nonzero value to reject the color and force the dialog box to remain open.

See Also

CHOOSECOLOR, RegisterWindowMessage


CPL_DBLCLK
 CPL_DBLCLK  QuickInfo  Overview  Group

CPL_DBLCLK

uAppNum = (UINT) lParam1;   // application number

lData = (LONG) lParam2;     // application-defined value

The CPL_DBLCLK message is sent to a Control Panel application when the user double-clicks the icon of a dialog box supported by the application.

Parameters

uAppNum

Value of lParam1. Specifies the dialog box number. This number must be in the range zero through one less than the value returned in response to the CPL_GETCOUNT message (CPL_GETCOUNT − 1).

lData

Value of lParam2. Specifies the value that the Control Panel application loaded into the lData member of the CPLINFO or NEWCPLINFO structure for the dialog box. The application loads lData member in response to the CPL_INQUIRE or CPL_NEWINQUIRE message.

Return Value

If a Control Panel application processes this message successfully, the return value is zero; otherwise, it is nonzero.

Remarks

In response to this message, a Control Panel application must display the corresponding dialog box.

See Also

CPL_GETCOUNT, CPL_INQUIRE, CPL_NEWINQUIRE, CPL_SELECT, CPLINFO, NEWCPLINFO


CPL_EXIT
 CPL_EXIT  QuickInfo  Overview  Group

CPL_EXIT

The CPL_EXIT message is sent once to a Control Panel application before the controlling application releases the DLL containing the application.

Parameters

This function has no parameters.

Return Value

If a Control Panel application processes this message successfully, it should return zero.

Remarks

This message is sent after the last CPL_STOP message is sent.

In response to this message, a Control Panel application must free any memory that it has allocated and perform global-level cleanup.

See Also

CPL_STOP, FreeLibrary


CPL_GETCOUNT
 CPL_GETCOUNT  QuickInfo  Overview  Group

CPL_GETCOUNT

The CPL_GETCOUNT message is sent to a Control Panel application to retrieve the number of dialog boxes supported by the application.

Parameters

This function has no parameters.

Return Value

A Control Panel application should return the number of dialog boxes it supports.

Remarks

This message is sent immediately after the CPL_INIT message.

See Also

CPL_INIT


CPL_INIT
 CPL_INIT  QuickInfo  Overview  Group

CPL_INIT

The CPL_INIT message is sent to a Control Panel application to prompt it to perform global initialization, especially memory allocation.

Parameters

This function has no parameters.

Return Value

If initialization succeeds, a Control Panel application should return nonzero. Otherwise, it should return zero. If the application returns zero, the controlling application ends communication and releases the DLL containing the Control Panel application.

Remarks

Because this is the only way a Control Panel application can signal an error condition, the application should allocate memory in response to this message.

This message is sent immediately after the DLL containing the application is loaded.

See Also

FreeLibrary


CPL_INQUIRE
 CPL_INQUIRE  QuickInfo  Overview  Group

CPL_INQUIRE

uAppNum = (UINT) lParam1;     // application number

lpcpli = (LPCPLINFO) lParam2; // structure for application info.

The CPL_INQUIRE message is sent to a Control Panel application to request information about a dialog box that the application supports.

This message has been superseded by the CPL_NEWINQUIRE message. The CPL_INQUIRE message is provided for compatibility with Windows versions 3.0 and earlier. Win32-based applications should use CPL_NEWINQUIRE.

Parameters

uAppNum

Value of lParam1. Specifies the dialog box number. This number must be in the range zero through one less than the value returned in response to the CPL_GETCOUNT message (CPL_GETCOUNT − 1).

lpcpli

Value of lParam2. Points to a CPLINFO structure. The application must fill this structure with resource identifiers for the icon, short name, description, and any user-defined value associated with the dialog box.

Return Value

If a Control Panel application processes this message successfully, it should return zero.

Remarks

This message is sent once for each dialog box supported by the Control Panel application. It is sent immediately after the CPL_GETCOUNT message. The application can perform initialization for the dialog box when it receives this message. If the application must allocate memory, it should do so in response to the CPL_INIT message.

See Also

CPL_GETCOUNT, CPL_INIT, CPL_NEWINQUIRE, CPLINFO


CPL_NEWINQUIRE
 CPL_NEWINQUIRE  QuickInfo  Overview  Group

CPL_NEWINQUIRE

uAppNum = (UINT) lParam1;         // application number

lpncpli = (LPNEWCPLINFO) lParam2; // structure for appl. info.

The CPL_NEWINQUIRE message is sent to a Control Panel application to request information about a dialog box that the application supports.

Parameters

uAppNum

Value of lParam1. Specifies the dialog box number. This number must be in the range zero through one less than the value returned in response to the CPL_GETCOUNT message (CPL_GETCOUNT − 1).

lpncpli

Value of lParam2. Specifies the address of a NEWCPLINFO structure. The Control Panel application should fill this structure with information about the dialog box.

Return Value

If a Control Panel application processes this message successfully, it should return zero.

Remarks

This message is sent once for each dialog box supported by the application. It is sent immediately after the CPL_GETCOUNT message. Upon receiving this message, the application can initialize the dialog box. If the application must allocate memory, it should do so in response to the CPL_INIT message.

See Also

CPL_GETCOUNT, CPL_INIT, CPL_INQUIRE, NEWCPLINFO


CPL_SELECT
 CPL_SELECT  QuickInfo  Overview  Group

CPL_SELECT

uAppNum = (UINT) lParam1;   // application number

lData = (LONG) lParam2;     // application-defined value

The CPL_SELECT message is sent to a Control Panel application when the user selects the icon of a dialog box supported by the application.

Parameters

uAppNum

Value of lParam1. Specifies the dialog box number.

lData

Value of lParam2. Specifies the value that the Control Panel application loaded into the lData member of the CPLINFO or NEWCPLINFO structure for the dialog box. The application loads the lData member in response to the CPL_INQUIRE or CPL_NEWINQUIRE message.

Return Value

If a Control Panel application processes this message successfully, it should return zero.

See Also

CPL_DBLCLK, CPL_INQUIRE, CPL_NEWINQUIRE, CPLINFO, NEWCPLINFO


CPL_STOP
 CPL_STOP  QuickInfo  Overview  Group

CPL_STOP

uAppNum = (UINT) lParam1;   // application number

lData = (LONG) lParam2;     // application-defined value

The CPL_STOP message is sent once for each dialog box when the application controlling the Control Panel application closes.

Parameters

uAppNum

Value of lParam1. Specifies the dialog box number.

lData

Value of lParam2. Specifies the value that the Control Panel application loaded into the lData member of the CPLINFO or NEWCPLINFO structure for the dialog box. The application loads lData member in response to the CPL_INQUIRE or CPL_NEWINQUIRE message.

Return Value

If a Control Panel application processes this message successfully, it should return zero.

Remarks

In response to this message, a Control Panel application must perform cleanup for the given dialog box.

See Also

CPL_EXIT, CPL_GETCOUNT, CPL_INQUIRE, CPL_NEWINQUIRE, CPLINFO, NEWCPLINFO


DBT_CONFIGCHANGED [New - Windows 95]
 DBT_CONFIGCHANGED  QuickInfo  Overview  Group

[New - Windows 95]

dwData = (DWORD) lParam;

The DBT_CONFIGCHANGED device message indicates that the current configuration has changed, due to a dock or undock. An application or driver that stores data in the registry under the HKEY_CURRENT_CONFIG key should update the data.

Parameters

dwData

Pointer to a DEV_BROADCAST_HDR structure identifying the device. lParam is zero.

Return Value

Return TRUE.

See Also

DEV_BROADCAST_HDR


DBT_DEVICEARRIVAL [New - Windows 95]
 DBT_DEVICEARRIVAL  QuickInfo  Overview  Group

[New - Windows 95]

dwData = (DWORD) lParam;

The DBT_DEVICEARRIVAL device message is sent when a device has been inserted and is now available.

Parameters

dwData

Address of a DEV_BROADCAST_HDR structure identifying the device inserted.

Return Value

Return TRUE.

See Also

DEV_BROADCAST_HDR


DBT_DEVICEQUERYREMOVE [New - Windows 95]
 DBT_DEVICEQUERYREMOVE  QuickInfo  Overview  Group

[New - Windows 95]

dwData = (DWORD) lParam;

The DBT_DEVICEQUERYREMOVE device message is sent to request permission to remove a device. Any application can deny this request and cancel the removal.

Parameters

dwData

Address of a DEV_BROADCAST_HDR structure identifying the device to remove.

Return Value

Return TRUE to grant permission, FALSE otherwise.

See Also

DEV_BROADCAST_HDR


DBT_DEVICEQUERYREMOVEFAILED [New - Windows 95]
 DBT_DEVICEQUERYREMOVEFAILED  QuickInfo  Overview  Group

[New - Windows 95]

dwData = (DWORD) lParam;

The DBT_DEVICEQUERYREMOVEFAILED device message is sent when a request to remove a device has been canceled.

Parameters

dwData

Address of a DEV_BROADCAST_HDR structure identifying the device.

Return Value

Return TRUE.

See Also

DEV_BROADCAST_HDR


DBT_DEVICEREMOVECOMPLETE [New - Windows 95]
 DBT_DEVICEREMOVECOMPLETE  QuickInfo  Overview  Group

[New - Windows 95]

dwData = (DWORD) lParam;

The DBT_DEVICEREMOVECOMPLETE device message is sent when a device has been removed.

Parameters

dwData

Address of a DEV_BROADCAST_HDR structure identifying the device removed.

Return Value

Return TRUE.

Remarks

The operating system may send a DBT_DEVICEREMOVECOMPLETE message without sending corresponding DBT_DEVICEQUERYREMOVE and DBT_DEVICEREMOVEPENDING messages. In such cases, the applications and drivers must recover from the loss of the device the best they can.

See Also

DBT_DEVICEQUERYREMOVE, DBT_DEVICEREMOVEPENDING, DEV_BROADCAST_HDR


DBT_DEVICEREMOVEPENDING [New - Windows 95]
 DBT_DEVICEREMOVEPENDING  QuickInfo  Overview  Group

[New - Windows 95]

dwData = (DWORD) lParam;

The DBT_DEVICEREMOVEPENDING device message is sent when the device is about to be removed. This message is the last chance for applications and drivers to prepare for the removal of the device.

Parameters

dwData

Address of a DEV_BROADCAST_HDR structure identifying the device to remove.

Return Value

Return TRUE.

See Also

DEV_BROADCAST_HDR


DBT_DEVICETYPESPECIFIC [New - Windows 95]
 DBT_DEVICETYPESPECIFIC  QuickInfo  Overview  Group

[New - Windows 95]

dwData = (DWORD) lParam;

The DBT_DEVICETYPESPECIFIC device message is sent when a device-specific event occurs.

Parameters

dwData

Address of a DEV_BROADCAST_HDR structure identifying the device. lParam is application-defined. May be zero.

Return Value

Return TRUE.

See Also

DEV_BROADCAST_HDR


DBT_USERDEFINED
 DBT_USERDEFINED  QuickInfo

dwData = (DWORD) lParam;

The DBT_USERDEFINED device message identifies a user-defined system message. DBT_USERDEFINED is sent as the wParam parameter of the WM_DEVICECHANGE message.

dwData

Address of the user-defined data. The data must be in the format specified by the _DEV_BROADCAST_USERDEFINED structure. lParam is application-defined. May be zero.

See Also

_DEV_BROADCAST_USERDEFINED, WM_DEVICECHANGE


DL_BEGINDRAG [New - Windows NT]
 DL_BEGINDRAG  QuickInfo  Overview  Group

[New - Windows NT]

DL_BEGINDRAG

idCtl = (int) wParam;

pDragInfo = (LPDRAGLISTINFO) lParam;

The DL_BEGINDRAG notification message notifies the parent window of a drag list box that the user has clicked the left mouse button on a list item. A drag list box sends DL_BEGINDRAG in the form of a drag list message.

Parameters

idCtl

Control identifier of the drag list box.

pDragInfo

Pointer to a DRAGLISTINFO structure that contains the DL_BEGINDRAG notification code, the handle to the drag list box, and the cursor position.

Return Value

The parent window should return TRUE to begin a drag operation or FALSE to prevent a drag operation.

Remarks

When processing this notification message, a window procedure typically determines the list item at the specified cursor position by using the LBItemFromPt function and then returns TRUE or FALSE, depending on whether the item should be dragged. Before returning TRUE, the window procedure should save the index of the list item, so the application knows which item to move or copy when the drag operation is completed.

See Also

DRAGLISTINFO, LBItemFromPt


DL_CANCELDRAG [New - Windows NT]
 DL_CANCELDRAG  QuickInfo  Overview  Group

[New - Windows NT]

DL_CANCELDRAG

idCtl = (int) wParam;

pDragInfo = (LPDRAGLISTINFO) lParam;

The DL_CANCELDRAG notification message signals that the user has canceled a drag operation by clicking the right mouse button or pressing the ESC key. A drag list box sends DL_CANCELDRAG to its parent window in the form of a drag list message.

Parameters

idCtl

Control identifier of the drag list box.

pDragInfo

Pointer to a DRAGLISTINFO structure that contains the DL_CANCELDRAG notification code, the handle to the drag list box, and the cursor position.

Return Value

No return value.

Remarks

By processing the DL_CANCELDRAG notification message, an application can reset its internal state to indicate that dragging is not in effect.

See Also

DRAGLISTINFO


DL_DRAGGING [New - Windows NT]
 DL_DRAGGING  QuickInfo  Overview  Group

[New - Windows NT]

DL_DRAGGING

idCtl = (int) wParam;

pDragInfo = (LPDRAGLISTINFO) lParam;

The DL_DRAGGING notification message signals that the user has moved the mouse while dragging an item. DL_DRAGGING is also sent periodically during dragging even if the mouse is not moved. A drag list box sends this notification to its parent window in the form of a drag list message.

Parameters

idCtl

Control identifier of the drag list box.

pDragInfo

Pointer to a DRAGLISTINFO structure that contains the DL_DRAGGING notification code, the handle to the drag list box, and the cursor position.

Return Value

The return value determines the type of mouse cursor that the drag list should set; it can be the DL_STOPCURSOR, DL_COPYCURSOR, or DL_MOVECURSOR value. If any other value is returned, the cursor does not change.

Remarks

A window procedure typically processes the DL_DRAGGING notification message by determining the item under the cursor and then drawing an insert icon. To get the item under the cursor, use the LBItemFromPt function, specifying TRUE for the bAutoScroll parameter. This option causes the drag list box to scroll periodically if the cursor is above or below its client area. To draw the insert icon, use the DrawInsert function.

See Also

DrawInsert, DRAGLISTINFO, LBItemFromPt


DL_DROPPED [New - Windows NT]
 DL_DROPPED  QuickInfo  Overview  Group

[New - Windows NT]

DL_BEGINDRAG

idCtl = (int) wParam;

pDragInfo = (LPDRAGLISTINFO) lParam;

The DL_DROPPED notification message signals that the user has completed a drag operation by releasing the left mouse button. A drag list box sends DL_DROPPED to its parent window in the form of a drag list message.

Parameters

idCtl

Control identifier of the drag list box.

pDragInfo

Pointer to a DRAGLISTINFO structure that contains the DL_DROPPED notification code, the handle to the drag list box, and the cursor position.

Return Value

No return value.

Remarks

A window procedure typically processes this notification message by inserting or copying the dragged list item before the list item under the cursor. To retrieve the index of the item at the cursor position, use the LBItemFromPoint function. Note that the DL_DROPPED notification message is sent even if the cursor is not on a list item. In that case, LBItemFromPoint returns − 1.

See Also

DRAGLISTINFO


DM_GETDEFID
 DM_GETDEFID  QuickInfo  Overview  Group

DM_GETDEFID

An application sends a DM_GETDEFID message to retrieve the identifier of the default push button control for a dialog box.

Parameters

This message has no parameters.

Return Value

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.

See Also

DefDlgProc, DM_SETDEFID


DM_REPOSITION [New - Windows 95]
 DM_REPOSITION  QuickInfo

[New - Windows 95]

DM_REPOSITION

wParam = 0;

lParam = 0;

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.

Parameters

This message has no parameters.

Return Value

This message has no return value.

Remarks

This message has no effect if the dialog box is a child window.


DM_SETDEFID
 DM_SETDEFID  QuickInfo  Overview  Group

DM_SETDEFID

wParam = idControl; // identifier of new default push button

This message has been replaced by EM_SETLIMITTEXT. An application sends a DM_SETDEFID message to change the identifier of the default push button for a dialog box.

Parameters

idControl

Value of wParam. Specifies the identifier of a push button control that will become the default.

Remarks

This message is processed by the DefDlgProc function. To set the default push button, the function can send WM_GETDLGCODE and BM_SETSTYLE messages to the given control and the current default push button.

Using the DM_SETDEFID message can result in more than one button appearing to have the default push button state. When Windows 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 Value

The return value is always TRUE.

See Also

DefDlgProc, BM_SETSTYLE, DM_GETDEFID, WM_GETDLGCODE


EM_CANPASTE [New - Windows NT]
 EM_CANPASTE  QuickInfo  Overview  Group

[New - Windows NT]

EM_CANPASTE

wParam = (WPARAM) (UINT) uFormat;

lParam = 0;

The EM_CANPASTE message determines whether a rich edit control can paste a specified clipboard format.

Parameters

uFormat

Value identifying the clipboard format to try, or zero to try any format currently on the clipboard.

Return Value

Returns a nonzero value if the clipboard format can be pasted or zero otherwise.


EM_CANUNDO
 EM_CANUNDO  QuickInfo  Overview  Group

EM_CANUNDO

wParam = 0; // not used; must be zero

lParam = 0; // not used; must be zero

An application sends an EM_CANUNDO message to determine whether an edit-control operation can be undone; that is, whether the control can respond to the EM_UNDO message.

Parameters

This message has no parameters.

Return Value

If the edit control can correctly process the EM_UNDO message, the return value is TRUE; otherwise, it is FALSE.

See Also

EM_UNDO


EM_CHARFROMPOS [New - Windows 95]
 EM_CHARFROMPOS  QuickInfo  Overview  Group

[New - Windows 95]

EM_CHARFROMPOS

wParam = 0;

lParam = MAKELPARAM(x, y)

An application sends an EM_CHARFROMPOS message to retrieve the zero-based character index and zero-based line index of the character nearest the specified point in an edit control.

Parameters

x

Value of the low-order word of lParam. Specifies the x-coordinate of a point in the edit control's client area. The coordinate is relative to the upper-left corner of the client area.

y

Value of the high-order word of lParam. Specifies the y-coordinate of a point in the edit control's client area. The coordinate is relative to the upper-left corner of the client area.

Return Value

The return value specifies the character index in the low-order word and the line index in the high-order word. For single-line edit controls, the line index is always 0. The return value is the last character in the edit control if the given point is beyond the last character in the control. The return value is −1 if the specified point is outside the client area of the edit control.

See Also

EM_POSFROMCHAR


EM_DISPLAYBAND [New - Windows NT]
 EM_DISPLAYBAND  QuickInfo  Overview  Group

[New - Windows NT]

EM_DISPLAYBAND

wParam = 0;

lParam = (LPARAM) (LPRECT) lprc;

The EM_DISPLAYBAND message displays a portion of a rich edit control's contents, as previously formatted for a device using the EM_FORMATRANGE message.

Parameters

lprc

Pointer to a RECT structure specifying the area of the device to display to.

Return Value

If the operation succeeds, the return value is TRUE.

If the operation fails, the return value is FALSE.

Remarks

Text and OLE objects are clipped by the rectangle. The application does not need to set the clipping region.

See Also

EM_FORMATRANGE, RECT


EM_EMPTYUNDOBUFFER
 EM_EMPTYUNDOBUFFER  QuickInfo  Overview  Group

EM_EMPTYUNDOBUFFER

wParam = 0; // not used; must be zero

lParam = 0; // not used; must be zero

An application sends an EM_EMPTYUNDOBUFFER message to reset the undo flag of an edit control. The undo flag is set whenever an operation within the edit control can be undone.

Parameters

This message has no parameters.

Return Value

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.

See Also

EM_CANUNDO, EM_SETHANDLE, EM_UNDO, WM_SETTEXT


EM_EXGETSEL [New - Windows NT]
 EM_EXGETSEL  QuickInfo  Overview  Group

[New - Windows NT]

EM_EXGETSEL

wParam = 0;

lParam = (LPARAM) (CHARRANGE FAR *) lpchr;

The EM_EXGETSEL message retrieves the starting and ending character positions of the selection in a rich edit control.

Parameters

lpchr

Pointer to a CHARRANGE structure that receives the selection range.

Return Value

No return value.

See Also

CHARRANGE


EM_EXLIMITTEXT [New - Windows NT]
 EM_EXLIMITTEXT  QuickInfo  Overview  Group

[New - Windows NT]

EM_EXGETSEL

wParam = 0;

lParam = (LPARAM) (DWORD) cchTextMax;

The EM_EXLIMITTEXT message sets an upper limit to the amount of text in a rich edit control.

Parameters

cchTextMax

Maximum amount of text or zero for the default maximum. An OLE object counts as a single character. The default maximum is 32K.

Return Value

No return value.


EM_EXLINEFROMCHAR [New - Windows NT]
 EM_EXLINEFROMCHAR  QuickInfo  Overview  Group

[New - Windows NT]

EM_EXLINEFROMCHAR

wParam = 0;

lParam = (LPARAM) (DWORD) ichCharPos;

The EM_EXLINEFROMCHAR message determines which line contains the specified character in a rich edit control.

Parameters

ichCharPos

Zero-based index of the character.

Return Value

Returns the zero-based index of the line.


EM_EXSETSEL [New - Windows NT]
 EM_EXSETSEL  QuickInfo  Overview  Group

[New - Windows NT]

EM_EXSETSEL

wParam = 0;

lParam = (LPARAM) (CHARRANGE FAR *) ichCharRange;

The EM_EXSETSEL message selects a range of characters in a rich edit control.

Parameters

ichCharPos

Zero-based index of the character.

Return Value

Returns the zero-based index of the line.


EM_FINDTEXT [New - Windows NT]
 EM_FINDTEXT  QuickInfo  Overview  Group

[New - Windows NT]

EM_FINDTEXT

wParam = (WPARAM) (UINT) fuFlags;

lParam = (LPARAM) (FINDTEXT FAR *) lpFindText;

The EM_FINDTEXT message finds text within a rich edit control.

Parameters

fuFlags

Zero or more of the FT_MATCHCASE and FT_WHOLEWORD values.

lpFindText

Pointer to a FINDTEXT structure containing information about the find operation.

Return Value

Returns the zero-based character position of the next match, or  − 1 if there are no more matches.

See Also

FINDTEXT


EM_FINDTEXTEX
 EM_FINDTEXTEX  Overview  Group

EM_FINDTEXTEX

wParam = (WPARAM) (UINT) fuFlags;

lParam = (LPARAM) (FINDTEXT FAR *) lpFindText;

Finds text within a rich edit control.

Parameters

fuFlags

Zero or more of the FT_MATCHCASE and FT_WHOLEWORD values.

lpFindText

Address of a FINDTEXTEX structure containing information about the find operation.

Return Value

Returns the zero-based character position of the next match or  − 1 if there are no more matches.

See Also

FINDTEXTEX


EM_FINDWORDBREAK [New - Windows NT]
 EM_FINDWORDBREAK  QuickInfo  Overview  Group

[New - Windows NT]

EM_FINDWORDBREAK

wParam = (WPARAM) (UINT) code;

lParam = (LPARAM) (DWORD) ichStart;

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.

Parameters

code

Action to take. This parameter can be one of these values:

Value	Meaning
WB_CLASSIFY	Returns the character class and word break flags of the character at the specified position.
WB_ISDELIMITER	Returns TRUE if the character at the specified position is a delimiter, or FALSE otherwise.
WB_LEFT	Finds the nearest character before the specified position that begins a word.
WB_LEFTBREAK	Finds the next word end before the specified position.
WB_MOVEWORDLEFT	Finds the next character that begins a word before the specified position. This value is used during CTRL+LEFT key processing.
WB_MOVEWORDRIGHT	Finds the next character that begins a word after the specified position. This value is used during CTRL+RIGHT key processing.
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.
ichStart

Zero-based character position to start from.

Return Value

Returns the character index of the word break, unless the code parameter is the WB_CLASSIFY or WB_ISDELIMITER value. For more information, see the description of the code parameter.

Remarks

If code is WB_LEFT and WB_RIGHT, the word break procedure finds word breaks only after delimiters. This matches the functionality of an edit control. If code is WB_MOVEWORDLEFT or WB_MOVEWORDRIGHT, the word break procedure also compares character classes and word break flags.

For information about character classes and word break flags, see Word and Line Breaks.


EM_FMTLINES
 EM_FMTLINES  QuickInfo  Overview  Group

EM_FMTLINES

wParam = (WPARAM) (BOOL) fAddEOL;   // linebreak flag

lParam = 0;                         // not used; must be zero

An application sends an EM_FMTLINES message to set the inclusion flag of soft linebreak characters on or off within a multiline edit control. A soft linebreak consists of two carriage returns and a linefeed and is inserted at the end of a line that is broken because of wordwrapping.

Parameters

fAddEOL

Value of wParam. Specifies whether soft-linebreak characters are to be inserted. A value of TRUE inserts the characters; a value of FALSE removes them.

Return Value

The return value is identical to the fAddEOL parameter.

Remarks

This message affects only the buffer returned by the EM_GETHANDLE message and the text returned by the WM_GETTEXT message. It has no effect on the display of the text within the edit control.

The EM_FMTLINES message does not affect a line that ends with a hard linebreak. A hard linebreak consists of one carriage return and a linefeed.

Note that the size of the text changes when this message is processed.

See Also

EM_GETHANDLE, WM_GETTEXT


EM_FORMATRANGE [New - Windows NT]
 EM_FORMATRANGE  QuickInfo  Overview  Group

[New - Windows NT]

EM_FORMATRANGE

wParam = (WPARAM) (BOOL) fRender;

lParam = (LPARAM) (FORMATRANGE FAR *) lpFmt;

The EM_FORMATRANGE message formats a range of text in a rich edit control for a specific device.

Parameters

fRender

Value specifying whether to render the text. If this parameter is nonzero, the text is rendered. Otherwise, the text is just measured.

lpFmt

Pointer to a FORMATRANGE structure containing information about the output device, or NULL to free information cached by the control.

This message is typically used with the EM_DISPLAYBAND message to format a rich edit control's contents for an output device such as a printer.

It is very important to free cached information after the last time you use this message. In addition, after using this message for one device, you must free cached information before using it again for a different device.

Return Value

Returns the index of the last character that fits in the region plus one.

See Also

EM_DISPLAYBAND, FORMATRANGE


EM_GETCHARFORMAT [New - Windows NT]
 EM_GETCHARFORMAT  QuickInfo  Overview  Group

[New - Windows NT]

EM_GETCHARFORMAT

wParam = (WPARAM) (BOOL) fSelection;

lParam = (LPARAM) (CHARFORMAT FAR *) lpFmt;

The EM_GETCHARFORMAT message determines the current character formatting in a rich edit control.

Parameters

fSelection

Value specifying whether to get the default character formatting or the current selection's character formatting. If this parameter is zero, the default formatting is returned. Otherwise, the current selection's formatting is returned.

lpFmt

Pointer to a CHARFORMAT structure to fill in. If the selection formatting is being retrieved, the structure receives the attributes of the first character, and the dwMask member specifies which attributes are consistent throughout the entire selection.

Return Value

Returns the value of the dwMask member of the CHARFORMAT structure.

See Also

CHARFORMAT


EM_GETEVENTMASK [New - Windows NT]
 EM_GETEVENTMASK  QuickInfo  Overview  Group

[New - Windows NT]

EM_GETEVENTMASK

wParam = 0;  // not used; must be zero

lParam = 0;  // not used; must be zero

The EM_GETEVENTMASK message retrieves the event mask for an rich edit control. The event mask specifies which notification messages the control sends to its parent window.

Return Value

Returns the event mask for the rich edit control.


EM_GETFIRSTVISIBLELINE
 EM_GETFIRSTVISIBLELINE  QuickInfo  Overview  Group

EM_GETFIRSTVISIBLELINE

wParam = 0; // not used; must be zero

lParam = 0; // not used; must be zero

An application sends an EM_GETFIRSTVISIBLELINE message to determine the uppermost visible line in an edit control.

Parameters

This message has no parameters.

Return Value

The return value is the zero-based index of the uppermost visible line in a multiline edit control. For single-line edit controls, the return value is the zero-based index of the first visible character.


EM_GETHANDLE
 EM_GETHANDLE  QuickInfo  Overview  Group

EM_GETHANDLE

wParam = 0; // not used; must be zero

lParam = 0; // not used; must be zero

An application sends an EM_GETHANDLE message to retrieve a handle of the memory currently allocated for a multiline edit control's text.

Parameters

This message has no parameters.

Return Value

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.

See Also

EM_SETHANDLE


EM_GETIMECOLOR
 EM_GETIMECOLOR  QuickInfo  Overview  Group

EM_GETIMECOLOR
wParam = (WPARAM) 0;
lParam = (LPARAM) (COMPCOLOR *) aCompColor;

Retrieves the IME composition color. This message is available only in Asian-language versions of the operating system.

Parameters

aCompColor

Address of a 4-element array of COMPCOLOR structures that receives the composition color.

Return Value

Returns nonzero if successful, zero otherwise.

See Also

COMPCOLOR


EM_GETIMEOPTIONS
 EM_GETIMEOPTIONS  QuickInfo  Overview  Group

EM_GETIMEOPTIONS
wParam = (WPARAM) 0;
lParam = (LPARAM) 0;

Retrieves the current IME options. This message is available only in Asian-language versions of the operating system.

Return Value

Returns a combination of the IME option values described for the EM_SETIMEOPTIONS message.

See Also

EM_SETIMEOPTIONS


EM_GETLIMITTEXT [New - Windows 95]
 EM_GETLIMITTEXT  QuickInfo  Overview  Group

[New - Windows 95]

EM_GETLIMITTEXT

wParam = 0;  // not used, must be zero

lParam = 0;  // not used, must be zero

An application sends the EM_GETLIMITTEXT message to retrieve the current text limit, in characters, for an edit control.

Parameters

This message has no parameters.

Return Value

The return value is the text limit.

See Also

EM_SETLIMITTEXT


EM_GETLINE
 EM_GETLINE  QuickInfo  Overview  Group

EM_GETLINE

wParam = (WPARAM) line;          // line number to retrieve

lParam = (LPARAM) (LPCSTR) lpch; // address of buffer for line

An application sends an EM_GETLINE message to copy a line of text from an edit control and place it in a specified buffer.

Parameters

line

Value of wParam. Specifies the zero-based index of the line to retrieve from a multiline edit control. A value of zero specifies the topmost line. This parameter is ignored by a single-line edit control.

lpch

Value of lParam. Points to the buffer that receives a copy of the line. The first word of the buffer specifies the maximum number of characters that can be copied to the buffer.

Return Value

The return value is the number of characters copied. The return value is zero if the line number specified by the line parameter is greater than the number of lines in the edit control.

Remarks

The copied line does not contain a terminating null character.

See Also

EM_LINELENGTH, WM_GETTEXT


EM_GETLINECOUNT
 EM_GETLINECOUNT  QuickInfo  Overview  Group

EM_GETLINECOUNT

wParam = 0; // not used; must be zero

lParam = 0; // not used; must be zero

An application sends an EM_GETLINECOUNT message to retrieve the number of lines in a multiline edit control.

Parameters

This message has no parameters.

Return Value

The return value is an integer specifying the number of lines in the multiline edit control. If no text is in the edit control, the return value is 1.

See Also

EM_GETLINE, EM_LINELENGTH


EM_GETMARGINS [New - Windows 95]
 EM_GETMARGINS  QuickInfo  Overview  Group

[New - Windows 95]

EM_GETMARGINS

wParam = 0;  // not used, must be zero

lParam = 0;  // not used, must be zero

An application sends the EM_GETMARGINS message to retrieve the widths of the left and right margins for an edit control.

Parameters

This message has no parameters.

Return Value

Returns the width of the left margin in the low-order word, and the width of the right margin in the high-order word.

See Also

EM_SETMARGINS


EM_GETMODIFY
 EM_GETMODIFY  QuickInfo  Overview  Group

EM_GETMODIFY

wParam = 0; // not used; must be zero

lParam = 0; // not used; must be zero

An application sends an EM_GETMODIFY message to determine whether the content of an edit control has been modified.

Parameters

This message has no parameters.

Return Value

If the content of edit control has been modified, the return value is TRUE; otherwise, it is FALSE.

Remarks

Windows maintains an internal flag indicating whether the content of the edit control has been changed. This flag is cleared when the edit control is first created; alternatively, an application can send an EM_SETMODIFY message to the edit control to clear the flag.

See Also

EM_SETMODIFY


EM_GETOLEINTERFACE [New - Windows NT]
 EM_GETOLEINTERFACE  QuickInfo  Overview  Group

[New - Windows NT]

EM_GETOLEINTERFACE

wParam = 0;

lParam = (LPARAM) (LPVOID FAR *) ppObject;

The EM_GETOLEINTERFACE message retrieves an IRichEditOle object that a client can use to access a rich edit control's OLE functionality.

Parameters

ppObject

Address at which the control stores a pointer to the IRichEditOle object. The control calls the AddRef function for the object before returning, so the calling application must call the Release function when it is done with the object.

Return Value

Returns a nonzero value if successful, or zero otherwise.

See Also

IRichEditOle


EM_GETOPTIONS
 EM_GETOPTIONS  QuickInfo  Overview  Group

EM_GETOPTIONS
wParam = (WPARAM) 0;
lParam = (LPARAM) 0;

Retrieves the rich edit control options.

Return Value

Returns the current option values. Can be a combination of values describedfor the EM_SETOPTIONS message.

See Also

EM_SETOPTIONS


EM_GETPARAFORMAT [New - Windows NT]
 EM_GETPARAFORMAT  QuickInfo  Overview  Group

[New - Windows NT]

EM_GETPARAFORMAT

wParam = 0;

lParam = (LPARAM) (PARAFORMAT FAR *) lpFmt;

The EM_GETPARAFORMAT message retrieves the paragraph formatting of the current selection in a rich edit control.

Parameters

lpFmt

Pointer to a PARAFORMAT structure that receives the paragraph formatting attributes of the current selection.

If more than one paragraph is selected, the structure receives the attributes of the first paragraph, and the dwMask member specifies which attributes are consistent throughout the entire selection.

Return Value

Returns the value of the dwMask member of the PARAFORMAT structure.

See Also

PARAFORMAT


EM_GETPASSWORDCHAR
 EM_GETPASSWORDCHAR  QuickInfo  Overview  Group

EM_GETPASSWORDCHAR

wParam = 0; // not used; must be zero

lParam = 0; // not used; must be zero

An application sends an EM_GETPASSWORDCHAR message to retrieve the password character displayed in an edit control when the user enters text.

Parameters

This message has no parameters.

Return Value

The return value specifies the character to be displayed in place of the character typed by the user. The return value is NULL if no password character exists.

Remarks

If the edit control is created with the ES_PASSWORD style, the default password character is set to an asterisk (*).

See Also

EM_SETPASSWORDCHAR


EM_GETPUNCTUATION
 EM_GETPUNCTUATION  QuickInfo  Overview  Group

EM_GETPUNCTUATION
wParam = (WPARAM) (UINT) fType;
lParam = (LPARAM) (PUNCTUATION FAR *) punctTable;

Gets the current punctuation characters for the rich edit control. This message is available only in Asian-language versions of the operating system.

Parameters

fType

Punctuation type flag. Can be one of the following values:

Value	Meaning
PC_LEADING	Leading punctuation characters
PC_FOLLOWING	Following punctuation characters
PC_DELIMITER	Delimiter
The PC_OVERFLOW value is not supported.

punctTable

Address of a PUNCTUATION structure that receives the punctuation characters.

Return Value

Returns nonzero if successful; zero otherwise.

See Also

PUNCTUATION


EM_GETRECT
 EM_GETRECT  QuickInfo  Overview  Group

EM_GETRECT

wParam = 0;                    // not used; must be zero

lParam (LPARAM) (LPRECT) lprc; // address of structure for rectangle

An application sends an EM_GETRECT message to retrieve the formatting rectangle of an edit control. The formatting rectangle is the limiting rectangle of the text. The limiting rectangle is independent of the size of the edit-control window.

Parameters

lprc

Value of lParam. Points to the RECT structure that receives the formatting rectangle.

Return Value

The return value is not a meaningful value.

Remarks

You can modify the formatting rectangle of a multiline edit control by using the EM_SETRECT and EM_SETRECTNP messages.

See Also

EM_SETRECT, EM_SETRECTNP, RECT


EM_GETSEL
 EM_GETSEL  QuickInfo  Overview  Group

EM_GETSEL

wParam = (WPARAM) (LPDWORD) lpdwStart; // receives starting position

lParam = (LPARAM) (LPDWORD) lpdwEnd;   // receives ending position

An application sends an EM_GETSEL message to get the starting and ending character positions of the current selection in an edit control.

Parameters

lpdwStart

Value of wParam. Points to a 32-bit value that receives the starting position of the selection. This parameter can be NULL.

lpdwEnd

Value of lParam. Points to a 32-bit value that receives the position of the first nonselected character after the end of the selection. This parameter can be NULL.

Return Value

The return value is a zero-based 32-bit value with the starting position of the selection in the low-order word and the position of the first character after the last selected character in the high-order word.

See Also

EM_SETSEL


EM_GETSELTEXT [New - Windows NT]
 EM_GETSELTEXT  QuickInfo  Overview  Group

[New - Windows NT]

EM_GETSELTEXT

wParam = 0;

lParam = (LPARAM) (LPSTR) lpBuf;

The EM_GETSELTEXT message retrieves the currently selected text in a rich edit control.

Parameters

lpBuf

Pointer to a buffer that receives the selected text. The calling application must ensure that the buffer is large enough to hold the selected text.

Return Value

Returns the number of characters copied, not including the terminating null character.


EM_GETTEXTRANGE [New - Windows NT]
 EM_GETTEXTRANGE  QuickInfo  Overview  Group

[New - Windows NT]

EM_GETTEXTRANGE

wParam = 0;

lParam = (LPARAM) (TEXTRANGE FAR *) lpRange;

The EM_GETTEXTRANGE message retrieves a specified range of characters from a rich edit control.

Parameters

lpRange

Pointer to a TEXTRANGE structure that specifies the range of characters to retrieve and a buffer to copy the characters to.

Return Value

Returns the number of characters copied, not including the terminating null character.

See Also

TEXTRANGE


EM_GETTHUMB [New - Windows NT]
 EM_GETTHUMB  QuickInfo

[New - Windows NT]

EM_GETTHUMB

wParam = 0;  // not used, must be zero

lParam = 0;  // not used, must be zero

An application sends the EM_GETTHUMB message to retrieve the position of the scroll box (thumb) in a multiline edit control.

Parameters

This message has no parameters.

Return Value

The return value is the position of the scroll box.


EM_GETWORDBREAKPROC
 EM_GETWORDBREAKPROC  QuickInfo  Overview  Group

EM_GETWORDBREAKPROC

wParam = 0; // not used; must be zero

lParam = 0; // not used; must be zero

An application sends an EM_GETWORDBREAKPROC message to an edit control to retrieve the address of the current wordwrap function.

Parameters

This message has no parameters.

Return Value

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 Windows should break a line of text for multiline edit controls, usually at a space character that separates two words.

See Also

EditWordBreakProc, EM_FMTLINES, EM_SETWORDBREAKPROC


EM_GETWORDBREAKPROCEX
 EM_GETWORDBREAKPROCEX  QuickInfo  Overview  Group

EM_GETWORDBREAKPROCEX
wParam = (WPARAM) 0;
lParam = (LPARAM) 0;

Retrieves the address of the currently registered extended word break procedure.

Return Value

Returns the address of the current procedure.


EM_GETWORDWRAPMODE
 EM_GETWORDWRAPMODE  QuickInfo  Overview  Group

EM_GETWORDWRAPMODE
wParam = (WPARAM) 0;
lParam = (LPARAM) 0:

Gets the current word wrapping and word breaking options for the rich edit control. This message is available only in Asian-language versions of the operating system.

Return Value

Returns the current word wrapping and word breaking options.

Remarks

This message must not be sent by the application-defined word breaking procedure.


EM_HIDESELECTION [New - Windows NT]
 EM_HIDESELECTION  QuickInfo  Overview  Group

[New - Windows NT]

EM_HIDESELECTION

wParam = (WPARAM) (BOOL) fHide;

lParam = (LPARAM) (BOOL) fChangeStyle;

The EM_HIDESELECTION message hides or shows the selection in a rich edit control.

Parameters

fHide

Value specifying whether to hide or show the selection. If this parameter is zero, the selection is shown. Otherwise, the selection is hidden.

fChangeStyle

Value specifying whether to change the control's ES_NOHIDESEL window style. If this parameter is zero, the selection is temporarily shown or hidden. Otherwise, the style is changed.

If this parameter is nonzero and the control has the focus, the selection is hidden or shown as appropriate.

Return Value

No return value.


EM_LIMITTEXT
 EM_LIMITTEXT  QuickInfo

EM_LIMITTEXT

wParam = (WPARAM) cchMax;   // text length, in characters

lParam = 0;                 // not used; must be zero

An application sends an EM_LIMITTEXT message to limit the amount of text the user may enter into an edit control.

Parameters

cchMax

Value of wParam. Specifies the maximum number of characters the user can enter. If this parameter is zero, the text length is set to 0x7FFFFFFE characters for single-line edit controls or 0xFFFFFFFF for multiline edit controls.

Return Value

This message does not return a value.

Remarks

The EM_LIMITTEXT message limits only the text the user can enter. It has no effect on any text already in the edit control when the message is sent, nor does it affect the length of the text copied to the edit control by the WM_SETTEXT message. If an application uses the WM_SETTEXT message to place more text into an edit control than is specified in the EM_LIMITTEXT message, the user can edit the entire contents of the edit control.

The default limit to the amount of text a user can enter in an edit control is 30,000 characters.

See Also

WM_SETTEXT


EM_LINEFROMCHAR
 EM_LINEFROMCHAR  QuickInfo  Overview  Group

EM_LINEFROMCHAR

wParam = (WPARAM) ich;  // character index

lParam = 0;             // not used; must be zero

An application sends an EM_LINEFROMCHAR message to retrieve the index of the line that contains the specified character index in a multiline edit control. A character index is the number of characters from the beginning of the edit control.

Parameters

ich

Value of wParam. Specifies the character index of the character contained in the line whose number is to be retrieved. If the ich parameter is −1, either the line number of the current line (the line containing the caret) is retrieved or, if there is a selection, the line number of the line containing the beginning of the selection is retrieved.

Return Value

The return value is the zero-based line number of the line containing the character index specified by ich.

See Also

EM_LINEINDEX


EM_LINEINDEX
 EM_LINEINDEX  QuickInfo  Overview  Group

EM_LINEINDEX

wParam = (WPARAM) line; // line number

lParam = 0;             // not used; must be zero

An application sends an EM_LINEINDEX message to retrieve the character index of a line in a multiline edit control. The character index is the number of characters from the beginning of the edit control to the specified line.

Parameters

line

Value of wParam. Specifies the zero-based line number. A value of −1 specifies the current line number (the line that contains the caret).

Return Value

The return value is the character index of the line specified in the line parameter, or it is −1 if the specified line number is greater than the number of lines in the edit control.

See Also

EM_LINEFROMCHAR


EM_LINELENGTH
 EM_LINELENGTH  QuickInfo  Overview  Group

EM_LINELENGTH

wParam = (WPARAM) ich;  // character index

lParam = 0;             // not used; must be zero

An application sends an EM_LINELENGTH message to retrieve the length of a line, in characters, in an edit control.

Parameters

ich

Value of wParam. Specifies the character index of a character in the line whose length is to be retrieved when EM_LINELENGTH is sent to a multiline edit control. If this parameter is −1, the message returns the number of unselected characters on lines containing selected characters. For example, if the selection extended from the fourth character of one line through the eighth character from the end of the next line, the return value would be 10 (three characters on the first line and seven on the next).

Return Value

The return value is the length, in characters, of the line specified by the ich parameter when an EM_LINELENGTH message is sent to a multiline edit control. The return value is the length, in characters, of the text in the edit control when an EM_LINELENGTH message is sent to a single-line edit control.

Remarks

Use the EM_LINEINDEX message to retrieve a character index for a given line number within a multiline edit control.

See Also

EM_LINEINDEX


EM_LINESCROLL
 EM_LINESCROLL  QuickInfo  Overview  Group

EM_LINESCROLL

wParam = (WPARAM) cxScroll; // characters to scroll horizontally

lParam = (LPARAM) cyScroll; // lines to scroll vertically

An application sends an EM_LINESCROLL message to scroll the text vertically or horizontally in a multiline edit control.

Parameters

cxScroll

Value of wParam. Specifies the number of characters to scroll horizontally.

cyScroll

Value of lParam. Specifies the number of lines to scroll vertically.

Return Value

If the message is sent to a multiline edit control, the return value is TRUE; if the message is sent to a single-line edit control, the return value is FALSE.

Remarks

The edit control does not scroll vertically past the last line of text in the edit control. If the current line plus the number of lines specified by the cyScroll parameter exceeds the total number of lines in the edit control, the value is adjusted so that the last line of the edit control is scrolled to the top of the edit-control window.

The EM_LINESCROLL message can be used to scroll horizontally past the last character of any line.


EM_PASTESPECIAL [New - Windows NT]
 EM_PASTESPECIAL  QuickInfo  Overview  Group

[New - Windows NT]

EM_PASTESPECIAL

wParam = (WPARAM) (UINT) uFormat;

lParam = 0;

The EM_PASTESPECIAL message pastes a specific clipboard format in a rich edit control.

Parameters

uFormat

Clipboard format to paste. For a list of clipboard formats, see SetClipboardData.

Return Value

No return value.

See Also

SetClipboardData


EM_POSFROMCHAR [New - Windows 95]
 EM_POSFROMCHAR  QuickInfo  Overview  Group

[New - Windows 95]

EM_POSFROMCHAR

wParam = (WPARAM)wCharIndex;       // zero-based index of character

lParam = 0;                 // not used, must be zero

An application sends the EM_POSFROMCHAR message to retrieve the coordinates of the specified character in an edit control.

Parameters

wCharIndex

Value of wParam. Specifies the zero-based index of the character.

Return Value

The return value specifies the coordinates of the upper-left corner of the character. If wCharIndex is greater than the index of the last character in the control, the return value specifies the coordinates of the position just past the last character in the control. The x-coordinate is in the low-order word and the y-coordinate is in the high-order word. The coordinates are relative to the upper-left corner of the edit control's client area.

Remarks

For a single-line edit control, the y-coordinate is always zero. A returned coordinate can be negative if the character has been scrolled outside the edit control's client area. The coordinates are truncated to integer values.

See Also

EM_CHARFROMPOS


EM_REPLACESEL
 EM_REPLACESEL  QuickInfo  Overview  Group

EM_REPLACESEL

fCanUndo = (BOOL) wParam ;          // flag that specifies whether replacement can be undone

lpszReplace = (LPCTSTR) lParam ;  // pointer to replacement text string

An application sends an EM_REPLACESEL message to replace the current selection in an edit control with the specified text.

Parameters

fCanUndo

Value of wParam. Specifies whether the replacement operation can be undone. If this is TRUE, the operation can be undone. If this is FALSE , the operation cannot be undone.

lpszReplace

Value of lParam. Points to a null-terminated string containing the replacement text.

Return Value

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.

See Also

WM_SETTEXT


EM_REQUESTRESIZE [New - Windows NT]
 EM_REQUESTRESIZE  QuickInfo  Overview  Group

[New - Windows NT]

EM_REQUESTRESIZE

wParam = 0;

lParam = 0;

The EM_REQUESTRESIZE message forces a rich edit control to send an EN_REQUESTRESIZE notification message to its parent window.

Return Value

No return value.

Remarks

This message is useful during WM_SIZE processing for the parent of a bottomless rich edit control.

See Also

EN_REQUESTRESIZE, WM_SIZE


EM_SCROLL
 EM_SCROLL  QuickInfo  Overview  Group

EM_SCROLL

wParam = (WPARAM) (INT) nScroll;    // scroll action

lParam = 0;                         // not used; must be zero

An application sends an EM_SCROLL message to scroll the text vertically in a multiline edit control. This message is equivalent to sending a WM_VSCROLL message to the edit control.

Parameters

nScroll

Value of wParam. Specifies the action the scroll bar is to take. This parameter may be one of the following values:

Value	Meaning
SB_LINEDOWN	Scrolls down one line.
SB_LINEUP	Scrolls up one line.
SB_PAGEDOWN	Scrolls down one page.
SB_PAGEUP	Scrolls up one page.
Return Value

If the message is successful, the high-order word of the return value is TRUE, and the low-order word is the number of lines that the command scrolls. The number returned may not be the same as the actual number of lines scrolled if the scrolling moves to the beginning or the end of the text. If the nScroll parameter specifies an invalid value, the return value is FALSE.

Remarks

An application should use the EM_LINESCROLL message to scroll to a specific line or character position.

An application should use the EM_SCROLLCARET message to scroll the caret into view.

See Also

EM_LINESCROLL, EM_SCROLLCARET, WM_VSCROLL


EM_SCROLLCARET
 EM_SCROLLCARET  QuickInfo  Overview  Group

EM_SCROLLCARET

wParam = 0 ;    // not used now; reserved for future use; must be zero

lParam = 0 ;    // not used now; reserved for future use;  must be zero

An application sends an EM_SCROLLCARET message to scroll the caret into view in an edit control.

Parameters

wParam

This parameter is currently unused. It is reserved for future use. It should be set to zero.

lParam

This parameter is currently unused. It is reserved for future use. It should be set to zero.

Return Value

The return value is nonzero if the message is sent to an edit control.

Remarks

In previous versions of Windows, scrolling the caret into view was done by specifying wParam = FALSE in the EM_SETSEL message. A Win32-based application should use the EM_SCROLLCARET message to scroll the caret into view.

See Also

EM_SETSEL


EM_SELECTIONTYPE [New - Windows NT]
 EM_SELECTIONTYPE  QuickInfo  Overview  Group

[New - Windows NT]

EM_SELECTIONTYPE

wParam = 0;

lParam = 0;

The EM_SELECTIONTYPE message determines the selection type for a rich edit control.

Return Value

Returns SEL_EMPTY if the selection is empty, or one or more of the following values:

Value	Contents of the selection
SEL_TEXT	Text
SEL_OBJECT	At least one OLE object
SEL_MULTICHAR	More than one character of text
SEL_MULTIOBJECT	More than one OLE object
Remarks

This message is useful during WM_SIZE processing for the parent of a bottomless rich edit control.

See Also

WM_SIZE


EM_SETBKGNDCOLOR [New - Windows NT]
 EM_SETBKGNDCOLOR  QuickInfo  Overview  Group

[New - Windows NT]

EM_SETBKGNDCOLOR

wParam = (WPARAM) (BOOL) fUseSysColor;

lParam = (LPARAM) (COLORREF) clr;

The EM_SETBKGNDCOLOR message sets the background color for a rich edit control.

Parameters

fUseSysColor

Value specifying whether to use the system color. If this parameter is nonzero, the background is set to the window background system color. Otherwise, the background is set to the specified color.

clr

COLORREF structure specifying the color if fUseSysColor is zero.

Return Value

Returns the old background color.

See Also

COLORREF


EM_SETCHARFORMAT [New - Windows NT]
 EM_SETCHARFORMAT  QuickInfo  Overview  Group

[New - Windows NT]

EM_SETCHARFORMAT

wParam = (WPARAM) (UINT) uFlags;

lParam = (LPARAM) (CHARFORMAT FAR *) lpFmt;

The EM_SETCHARFORMAT message sets character formatting in a rich edit control.

Parameters

uFlags

Character formatting that applies to the control. This parameter can be zero or more of these values:

Value	Meaning
SCF_SELECTION	Applies the formatting to the current selection, or sets the default formatting if the selection is empty.
SCF_WORD	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. This value must be used in conjunction with the SCF_SELECTION value.
lpFmt

Pointer to a CHARFORMAT structure specifying the character formatting to use. Only the formatting attributes specified by the dwMask member are changed.

Return Value

Returns a nonzero value if successful or zero otherwise.

Remarks

If this parameter is zero, the default character formatting is used.

See Also

CHARFORMAT


EM_SETEVENTMASK [New - Windows NT]
 EM_SETEVENTMASK  QuickInfo  Overview  Group

[New - Windows NT]

EM_SETEVENTMASK

wParam = 0;

lParam = (LPARAM) (DWORD) dwMask;

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.

Parameters

dwMask

New event mask for the rich edit control.

Return Value

Returns the previous event mask.


EM_SETHANDLE
 EM_SETHANDLE  QuickInfo  Overview  Group

EM_SETHANDLE

wParam = (WPARAM) (HLOCAL) hloc; // handle of memory buffer

lParam = 0;                      // not used; must be zero

An application sends an EM_SETHANDLE message to set the handle of the memory that will be used by a multiline edit control.

Parameters

hloc

Value of wParam. Identifies the memory the edit control uses to store the currently displayed text instead of allocating its own memory. If necessary, the control reallocates this memory.

Return Value

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.

See Also

EM_CANUNDO, EM_GETHANDLE, EM_GETMODIFY


EM_SETIMECOLOR
 EM_SETIMECOLOR  QuickInfo  Overview  Group

EM_SETIMECOLOR
wParam = (WPARAM) 0;
lParam = (LPARAM) (COMPCOLOR *) aCompColor;

Sets the IME composition color. This message is available only in Asian-language versions of the operating system.

Parameters

aCompColor

Address of a four-element array of COMPCOLOR structures that receives the composition color.

Return Value

Returns nonzero if successful, zero otherwise.

See Also

EM_GETIMECOLOR, COMPCOLOR


EM_SETIMEOPTIONS
 EM_SETIMEOPTIONS  QuickInfo  Overview  Group

EM_SETIMEOPTIONS
wParam = (WPARAM) 0;
lParam = (LPARAM) (int) fOptions;

Sets the IME options. This message is available only in Asian-language versions of the operating system.

Parameters

fOptions

IME option flag. Can be a combination of the following values:

IMF_CLOSESTATUSWINDOW	Closes the IME status window when the control receives the input focus.
IMF_FORCEACTIVE	Activates the IME when the control receives the input focus.
IMF_FORCEDISABLE	Disables the IME when the control receives the input focus.
IMF_FORCEENABLE	Enables the IME when the control receives the input focus.
IMF_FORCEINACTIVE	Inactivates the IME when the control receives the input focus.
IMF_FORCENONE	Disables IME handling.
IMF_FORCEREMEMBER	Restores the previous IME status when the control receives the input focus.
Return Value

Returns nonzero if successful, zero otherwise.

See Also

EM_GETIMEOPTIONS


EM_SETLIMITTEXT [New - Windows 95]
 EM_SETLIMITTEXT  QuickInfo  Overview  Group

[New - Windows 95]

EM_SETLIMITTEXT

wParam = (WPARAM) cbMax;    // new text limits, in bytes

lParam = 0;                 // not used, must be zero

An application sends the EM_SETLIMITTEXT message to set the text limit for an edit control. The text limit is the maximum amount of text, in bytes, that the edit control can contain.

Parameters

cbMax

Value of wParam. Specifies the new text limit, in bytes. If this parameter is 0, Windows sets the maximum text limit. The maximum text limit is 32,766 bytes for a single-line edit control, and 65,535 bytes for a multiline edit control.

Return Value

This message does not return a value.

Remarks

The EM_SETLIMITTEXT message replaces the EM_LIMITTEXT message.

See Also

EM_GETLIMITTEXT


EM_SETMARGINS [New - Windows 95]
 EM_SETMARGINS  QuickInfo  Overview  Group

[New - Windows 95]

EM_SETMARGINS

wParam = (WPARAM) fwMargin;	// left and/or right margins

lParam = (LPARAM) MAKELONG(wLeft, wRight);	// width of left or right margins, in pixels

An application sends the EM_SETMARGINS message to set the widths of the left and right margins for an edit control. The message redraws the control to reflect the new margins.

Parameters

fwMargin

Value of wParam. Specifies the margins to set. This parameter can be a combination of the following values:

Value	Meaning
EC_LEFTMARGIN	Sets the left margin.
EC_RIGHTMARGIN	Sets the right margin.
EC_USEFONTINFO	Uses information about the current font of the edit control to set the margins. For a single-line edit control, margins are set to the average width of characters in the font. For a multiline edit control, the right margin is set to the "A" width of the font (the distance added to the current position before drawing a character), and the left margin is set to the "C" width (the distance added to the current position to provide white space to the right of a character).
If EC_USEFONTINFO is specified, the lParam parameter is ignored.

wLeft

Value of the low-order word of lParam. Specifies the width of the left margin, in pixels. This value is ignored if fwMargin does not include EC_LEFTMARGIN or if EC_USEFONTINFO is specified.

wRight

Value of the high-order word of lParam. Specifies the width of the right margin, in pixels. This value is ignored if fwMargin does not include EC_RIGHTMARGIN or if EC_USEFONTINFO is specified.

Return Value

This message does not return a value.

See Also

EM_GETMARGINS


EM_SETMODIFY
 EM_SETMODIFY  QuickInfo  Overview  Group

EM_SETMODIFY

wParam = (WPARAM) (UINT) fModified;    // modification flag

lParam = 0;                            // not used; must be zero

An application sends an EM_SETMODIFY message to set or clear the modification flag for an edit control. The modification flag indicates whether the text within the edit control has been modified. It is automatically set whenever the user changes the text. An EM_GETMODIFY message can be sent to retrieve the value of the modification flag.

Parameters

fModified

Value of wParam. Specifies the new value for the modification flag. A value of TRUE indicates the text has been modified, and a value of FALSE indicates it has not been modified.

Return Value

This message does not return a value.

See Also

EM_GETMODIFY


EM_SETOLEINTERFACE [New - Windows NT]
 EM_SETOLEINTERFACE  Overview  Group

[New - Windows NT]

EM_SETOLEINTERFACE

wParam = 0;

lParam = (LPARAM) (IRichEditOleCallback FAR *) lpObj;

The EM_SETOLEINTERFACE message gives a rich edit control an IRichEditOleCallback object that the control uses to get OLE-related resources and information from the client.

Parameters

lpObj

Pointer to an IRichEditOleCallback object. The control calls the AddRef function for the object before returning.

Return Value

Returns a nonzero value if successful or zero otherwise.


EM_SETOPTIONS
 EM_SETOPTIONS  QuickInfo  Overview  Group

EM_SETOPTIONS
wParam = (WPARAM) (UINT) fOperation;
lParam = (LPARAM) (UINT) fOptions;

Sets the options for a rich edit control.

Parameters

fOperation

Operation flag. Can be one of these values:

ECOOP_SET	Set the options to those specified by fOptions.
ECOOP_OR	Combine the specified options with the current options.
ECOOP_AND	Retain only those current options that are also specified by fOptions.
ECOOP_XOR	Retain only those current options that are not specified by fOptions.
fOptions

Rich edit control options. Can be a combination of these values:

Value	Meaning
ECO_AUTOWORDSELECTION	Automatic selection of word on doubleclick.
ECO_AUTOVSCROLL	Same as ES_AUTOVSCROLL style.
ECO_AUTOHSCROLL	Same as ES_AUTOHSCROLL style.
ECO_NOHIDESEL	Same as ES_NOHIDESEL style.
ECO_READONLY	Same as ES_READONLY style.
ECO_WANTRETURN	Same as ES_WANTRETURN style.
ECO_SAVESEL	Same as ES_SAVESEL style.
ECO_SELECTIONBAR	Same as ES_SELECTIONBAR style.
ECO_VERTICAL	Same as ES_VERTICAL style. Available in Asian-language versions only.
Return Value

Returns current option of edit control.


EM_SETPARAFORMAT [New - Windows NT]
 EM_SETPARAFORMAT  QuickInfo  Overview  Group

[New - Windows NT]

EM_SETPARAFORMAT

wParam = 0;  // not used; must be zero

lParam = (LPARAM) (PARAFORMAT FAR *) lpFmt;

The EM_SETPARAFORMAT message sets the paragraph formatting for the current selection in a rich edit control.

Parameters

lpFmt

Pointer to a PARAFORMAT structure specifying the new paragraph formatting attributes. Only the attributes specified by the dwMask member are changed.

Return Value

Returns a nonzero value if successful, or zero otherwise.

See Also

PARAFORMAT


EM_SETPASSWORDCHAR
 EM_SETPASSWORDCHAR  QuickInfo  Overview  Group

EM_SETPASSWORDCHAR

wParam = (WPARAM) (UINT) ch;    // character to display

lParam = 0;                     // not used; must be zero

An application sends an EM_SETPASSWORDCHAR message to set or remove the password character for a single-line edit control when the user types text. When a password character is set, that character is displayed in place of each character the user types.

Parameters

ch

Value of wParam. Specifies the character to be displayed in place of the character typed by the user. If this parameter is zero, the characters typed by the user are displayed.

Return Value

This message does not return a value.

Remarks

When the EM_SETPASSWORDCHAR message is received by an edit control, the edit control redraws all visible characters by using the character specified by the ch parameter.

If the edit control is created with the ES_PASSWORD style, the default password character is set to an asterisk (*). This style is removed if an EM_SETPASSWORDCHAR message is sent with the ch parameter set to zero.

See Also

EM_GETPASSWORDCHAR


EM_SETPUNCTUATION
 EM_SETPUNCTUATION  QuickInfo  Overview  Group

EM_SETPUNCTUATION
wParam = (WPARAM) (UINT) fType;
lParam = (LPARAM) (PUNCTUATION FAR *) punctTable;

Sets the punctuation characters for a rich edit control. This message is available only in Asian-language versions of the operating system.

Parameters

fType

Punctuation type flag. Can be one of the following values:

Value	Meaning
PC_LEADING	Leading punctuation characters.
PC_FOLLOWING	Following punctuation characters.
PC_DELIMITER	Delimiter.
The PC_OVERFLOW value is not supported.

punctTable

Address of a PUNCTUATION structure that contains the punctuation characters.

Return Value

Returns nonzero if successful; zero otherwise.

See Also

PUNCTUATION


EM_SETREADONLY
 EM_SETREADONLY  QuickInfo  Overview  Group

EM_SETREADONLY

wParam = (WPARAM) (BOOL) fReadOnly;  // read-only flag

lParam = 0;                          // not used; must be zero

An application sends an EM_SETREADONLY message to set or remove the read-only style (ES_READONLY) of an edit control.

Parameters

fReadOnly

Value of wParam. Specifies whether to set or remove the ES_READONLY style. A value of TRUE sets the ES_READONLY style; a value of FALSE removes the ES_READONLY style.

Return Value

If the operation succeeds, the return value is nonzero; otherwise, it is zero.

Remarks

When an edit control has the ES_READONLY style, the user cannot change the text within the edit control.

To determine whether an edit control has the ES_READONLY style, use the GetWindowLong function with the GWL_STYLE flag.

See Also

GetWindowLong


EM_SETRECT
 EM_SETRECT  QuickInfo  Overview  Group

EM_SETRECT

wParam = 0;                         // not used; must be zero

lParam = (LPARAM) (LPRECT) lprc;    // address of new rectangle

An application sends an EM_SETRECT message to set the formatting rectangle of a multiline edit control. The formatting rectangle is the limiting rectangle of the text. The limiting rectangle is independent of the size of the edit control window. When the edit control is first created, the formatting rectangle is the same as the client area of the edit control window. By using the EM_SETRECT message, an application can make the formatting rectangle larger or smaller than the edit control window.

This message is processed only by multiline edit controls.

Parameters

lprc

Value of lParam. Points to a RECT structure that specifies the new dimensions of the rectangle.

Return Value

This message does not return a value.

Remarks

The EM_SETRECT message causes the text of the edit control to be redrawn. To change the size of the formatting rectangle without redrawing the text, use the EM_SETRECTNP message.

If the edit control does not have a horizontal scroll bar, and the formatting rectangle is set to be larger than the edit control window, lines of text exceeding the width of the edit control window (but smaller than the width of the formatting rectangle) are clipped instead of wrapped.

If the edit control contains a border, the formatting rectangle is reduced by the size of the border. If you are adjusting the rectangle returned by an EM_GETRECT message, you must remove the size of the border before using the rectangle with the EM_SETRECT message.

See Also

EM_GETRECT, EM_SETRECTNP, RECT


EM_SETRECTNP
 EM_SETRECTNP  QuickInfo  Overview  Group

EM_SETRECTNP

wParam = 0;                         // not used; must be zero

lParam = (LPARAM) (LPRECT) lprc;    // address of new rectangle

An application sends an EM_SETRECTNP message to set the formatting rectangle of a multiline edit control. The formatting rectangle is the limiting rectangle of the text. The limiting rectangle is independent of the size of the edit control window. When the edit control is first created, the formatting rectangle is the same as the client area of the edit control window. By using the EM_SETRECTNP message, an application can make the formatting rectangle larger or smaller than the edit control window.

The EM_SETRECTNP message is identical to the EM_SETRECT message, except that the edit control window is not redrawn.

This message is processed only by multiline edit controls.

Parameters

lprc

Value of lParam. Points to a RECT structure that specifies the new dimensions of the rectangle.

Return Value

This message does not return a value.

See Also

EM_SETRECT, RECT


EM_SETSEL
 EM_SETSEL  QuickInfo  Overview  Group

EM_SETSEL

wParam = (WPARAM) (INT) nStart;    // starting position

lParam = (LPARAM) (INT) nEnd;      // ending position

An application sends an EM_SETSEL message to select a range of characters in an edit control.

Parameters

nStart

Value of wParam. Specifies the starting character position of the selection.

nEnd

Specifies the ending character position of the selection.

Return Value

This message does not return a value.

Remarks

If the nStart parameter is 0 and the nEnd parameter is −1, all the text in the edit control is selected. If nStart is −1, any current selection is removed. The caret is placed at the end of the selection indicated by the greater of the two values nEnd and nStart.

In previous versions of Windows, the wParam parameter is a flag that is set to FALSE to scroll the caret into view or set to TRUE to omit the scrolling. A Win32-based application should use the EM_SCROLLCARET message to scroll the caret into view.

In earlier versions of Windows, the starting and ending positions of the selection are indicated by the low- and high-order words, respectively, of the lParam parameter.

See Also

EM_GETSEL, EM_REPLACESEL, EM_SCROLLCARET


EM_SETTABSTOPS
 EM_SETTABSTOPS  QuickInfo  Overview  Group

EM_SETTABSTOPS

wParam = (WPARAM) cTabs;             // number of tab stops

lParam = (LPARAM) (LPDWORD) lpdwTabs;  // tab stop array

An application sends an EM_SETTABSTOPS message to set the tab stops in a multiline edit control. When text is copied to the control, any tab character in the text causes space to be generated up to the next tab stop.

This message is processed only by multiline edit controls.

Parameters

cTabs

Value of wParam. Specifies the number of tab stops contained in the lpdwTabs parameter. If this parameter is zero, the lpdwTabs parameter is ignored and default tab stops are set at every 32 dialog box units. If this parameter is 1, tab stops are set at every n dialog box units, where n is the distance pointed to by the ldpwTabs parameter. If the cTabs parameter is greater than 1, lpdwTabs points to an array of tab stops.

lpdwTabs

Value of lParam. Points to an array of unsigned integers specifying the tab stops, in dialog units. If the cTabs parameter is 1, lpdwTabs points to an unsigned integer containing the distance between all tab stops, in dialog box units.

Return Value

If all the tabs are set, the return value is TRUE; otherwise, it is FALSE.

Remarks

The EM_SETTABSTOPS message does not automatically redraw the edit control window. If the application is changing the tab stops for text already in the edit control, it should call the InvalidateRect function to redraw the edit control window.

See Also

GetDialogBaseUnits, InvalidateRect


EM_SETTARGETDEVICE [New - Windows NT]
 EM_SETTARGETDEVICE  QuickInfo  Overview  Group

[New - Windows NT]

EM_SETTARGETDEVICE

wParam = (WPARAM) (HDC) hdcTarget;

lParam = (LPARAM) (int) cxLineWidth;

The EM_SETTARGETDEVICE message sets the target device and line width used for WYSIWYG (what you see is what you get) formatting in a rich edit control.

Parameters

hdcTarget

Handle to a device context for the target device.

cxLineWidth

Line width to use for formatting.

Return Value

Returns a nonzero value if successful or zero otherwise.


EM_SETWORDBREAK
 EM_SETWORDBREAK  QuickInfo

The EM_SETWORDBREAK message is not supported. Applications that must replace the default wordwrap function of a multiline edit control with an application-defined wordwrap function should use the EM_SETWORDBREAKPROC message.


EM_SETWORDBREAKPROC
 EM_SETWORDBREAKPROC  QuickInfo  Overview  Group

EM_SETWORDBREAKPROC

wParam = 0;                                 // not used; must be zero

lParam = (LPARAM)(EDITWORDBREAKPROC)ewbprc; // function address

An application sends the EM_SETWORDBREAKPROC message to an edit control to replace the default wordwrap function with an application-defined wordwrap function.

Parameters

ewbprc

Value of 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 Value

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 Windows 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.

See Also

EditWordBreakProc, EM_FMTLINES, EM_GETWORDBREAKPROC


EM_SETWORDBREAKPROCEX
 EM_SETWORDBREAKPROCEX  QuickInfo  Overview  Group

EM_SETWORDBREAKPROCEX
wParam = (WPARAM) 0;
lParam = (LPARAM) pfnWordBreakProcEx;

Sets the extended word-break procedure.

Parameters

pfnWordBreakprocEx

Address of an EditWordBreakProcEx function or NULL to use the default procedure.

Return Value

Returns the address of the previous extended word-break procedure.

See Also

EditWordBreakProcEx, EM_GETWORDBREAKPROCEX


EM_SETWORDWRAPMODE
 EM_SETWORDWRAPMODE  QuickInfo  Overview  Group

EM_SETWORDWRAPMODE
wParam = (WPARAM) (UINT) fOptions;
lParam = (LPARAM) 0:

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.

Parameters

fOptions

Options flag. Can be a combination of the following values:

Value	Meaning
WBF_WORDWRAP	Enables Asian-specific word-wrap operation, such as Kinsoku in Japanese.
WBF_WORDBREAK	Enables English word-breaking operation.
WBF_OVERFLOW	Recognizes overflow punctuation. (Not currently supported.)
WBF_LEVEL1	Sets level 1 punctuation table as default.
WBF_LEVEL2	Sets level 2 punctuation table as default.
WBF_CUSTOM	Sets application-defined punctuation table.
Return Value

Returns the current word-wrapping and word-breaking options.

Remarks

This message must not be sent by the application-defined word-breaking procedure.


EM_STREAMIN [New - Windows NT]
 EM_STREAMIN  QuickInfo  Overview  Group

[New - Windows NT]

EM_STREAMIN

wParam = (WPARAM) (UINT) uFormat;

lParam = (LPARAM) (EDITSTREAM FAR *) lpStream;

The EM_STREAMIN message replaces the contents of a rich edit control with the specified data stream.

Parameters

uFormat

One of the following data formats, optionally combined with the SFF_SELECTION flag:

Value	Meaning
SF_TEXT	Text
SF_RTF	Rich-text format
If the SFF_SELECTION flag is specified, the stream replaces the contents of the current selection. Otherwise, the stream replaces the entire contents of the control.

lpStream

Pointer to an EDITSTREAM structure. The control reads (streams in) the data by repeatedly calling the function specified by the structure's pfnCallback member.

Return Value

Returns the number of characters read.

See Also

EDITSTREAM


EM_STREAMOUT [New - Windows NT]
 EM_STREAMOUT  QuickInfo  Overview  Group

[New - Windows NT]

EM_STREAMOUT

wParam = (WPARAM) (UINT) uFormat;

lParam = (LPARAM) (EDITSTREAM FAR *) lpStream;

The EM_STREAMOUT message writes (streams out) the contents of a rich edit control to the specified data stream.

Parameters

uFormat

Value specifying one of the following data formats, optionally combined with the SFF_SELECTION flag:

Value	Meaning
SF_TEXT	Text with spaces in place of OLE objects
SF_RTF	Rich-text format (RTF)
SF_RTFNOOBJS	RTF with spaces in place of OLE object.
SF_TEXTIZED	Text with a text representation of OLE objects.
The SF_RTFNOOBJS option is useful if an application stores OLE objects itself, as RTF representation of OLE objects is not very compact.

If the SFF_SELECTION flag is specified, only the contents of the current selection are streamed out. Otherwise, the entire contents of the control are streamed out.

lpStream

Pointer to an EDITSTREAM structure. The control streams out the data by repeatedly calling the function specified by the structure's pfnCallback member.

Return Value

Returns the number of characters written to the data stream.

See Also

EDITSTREAM


EM_UNDO
 EM_UNDO  QuickInfo  Overview  Group

EM_UNDO

wParam = 0; // not used; must be zero

lParam = 0; // not used; must be zero

An application sends an EM_UNDO message to undo the last edit control operation.

Parameters

This message has no parameters.

Return Value

For a single-line edit control, the return value is always TRUE. For a multiline edit control, the return value is TRUE if the undo operation is successful, or FALSE if the undo operation fails.

Remarks

An undo operation can also be undone. For example, you can restore deleted text with the first EM_CANUNDO message, and remove the text again with a second EM_CANUNDO message as long as there is no intervening edit operation.

See Also

EM_CANUNDO


EN_CHANGE
 EN_CHANGE  QuickInfo  Overview  Group

EN_CHANGE

idEditCtrl = (int) LOWORD(wParam); // identifier of edit control

hwndEditCtrl = (HWND) lParam;      // handle of edit control

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 Windows updates the screen. The parent window of the edit control receives this notification message through the WM_COMMAND message.

See Also

EN_UPDATE, WM_COMMAND


EN_CORRECTTEXT
 EN_CORRECTTEXT  Overview  Group

EN_CORRECTTEXT
wParam = (WPARAM) (UINT) uID;
lParam = (LPARAM) (ENCORRECTTEXT FAR *) lpEnCorrectText;

Notifies a rich edit control's parent window that a SYV_CORRECT gesture occurred. A rich edit control sends this notification message in the form of a WM_NOTIFY message.

Parameters

uID

Identifier of the rich edit control.

lpEnCorrectText

Pointer to an ENCORRECTTEXT structure specifying the selection to be corrected.

Return Value

Returns zero to ignore the action, nonzero to process it.

Remarks

This message is sent only if pen capabilities are available.

See Also

ENCORRECTTEXT, WM_NOTIFY


EN_DROPFILES [New - Windows NT]
 EN_DROPFILES  QuickInfo  Overview  Group

[New - Windows NT]

EN_DROPFILES

wParam = (WPARAM) (UINT) uID;

lParam = (LPARAM) (ENDROPFILES FAR *) lpEnDropFiles;

The EN_DROPFILE notification message notifies a rich edit control's parent window that the user is attempting to drop files into the control. A rich edit control sends this notification message in the form of a WM_NOTIFY message when it receives the WM_DROPFILES message.

Parameters

uID

Identifier of the rich edit control.

lpEnDropFiles

Pointer to an ENDROPFILES structure.

Return Value

Returns a nonzero value to allow the drop operation or zero to ignore the drop.

Remarks

For a rich edit control to receive WM_DROPFILES messages, the parent window must register the control as a drop target by using the DragAcceptFiles function. The control does not register itself.

See Also

DragAcceptFiles, ENDROPFILES, WM_DROPFILES, WM_NOTIFY


EN_ERRSPACE
 EN_ERRSPACE  QuickInfo  Overview  Group

EN_ERRSPACE

idEditCtrl = (int) LOWORD(wParam); // identifier of edit control

hwndEditCtrl = (HWND) lParam;      // handle of edit control

The EN_ERRSPACE notification message is sent when an edit control cannot allocate enough memory to meet a specific request. The parent window of the edit control receives this notification message through the WM_COMMAND message.

See Also

WM_COMMAND


EN_HSCROLL
 EN_HSCROLL  QuickInfo  Overview  Group

EN_HSCROLL

idEditCtrl = (int) LOWORD(wParam); // identifier of edit control

hwndEditCtrl = (HWND) lParam;      // handle of edit control

The EN_HSCROLL notification message is sent when the user clicks an edit control's horizontal scroll bar. The parent window of the edit control receives this notification message through the WM_COMMAND message. The parent window is notified before the screen is updated.

See Also

EN_VSCROLL, WM_COMMAND


EN_IMECHANGE
 EN_IMECHANGE  Overview  Group

EN_IMECHANGE
wParam = (WPARAM) (UINT) uID;
lParam = (LPARAM) 0;

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.

Parameters

uID

Identifier of the rich edit control.

Return Value

Returns zero.


EN_KILLFOCUS
 EN_KILLFOCUS  QuickInfo  Overview  Group

EN_KILLFOCUS

idEditCtrl = (int) LOWORD(wParam); // identifier of edit control

wNotifyCode = HIWORD(wParam);      // notification code

hwndEditCtrl = (HWND) lParam;      // handle of edit control

The EN_KILLFOCUS notification message is sent when an edit control loses the keyboard focus. The parent window of the edit control receives this notification message through the WM_COMMAND message.

Remarks

In previous versions of Windows, the notification code was in HIWORD(lParam).

See Also

EN_SETFOCUS, WM_COMMAND


EN_MAXTEXT
 EN_MAXTEXT  QuickInfo  Overview  Group

EN_MAXTEXT

idEditCtrl = (int) LOWORD(wParam); // identifier of edit control

hwndEditCtrl = (HWND) lParam;      // handle of edit control

The EN_MAXTEXT notification message is sent when the current text insertion has exceeded the specified number of characters for the edit control. The text insertion has been truncated.

This message is also sent when an edit control does not have the ES_AUTOHSCROLL style and the number of characters to be inserted would exceed the width of the edit control.

This message is also sent when an edit control does not have the ES_AUTOVSCROLL style and the total number of lines resulting from a text insertion would exceed the height of the edit control.

The parent window of the edit control receives this notification message through the WM_COMMAND message.

See Also

WM_COMMAND


EN_MSGFILTER [New - Windows NT]
 EN_MSGFILTER  QuickInfo  Overview  Group

[New - Windows NT]

EN_MSGFILTER

wParam = (WPARAM) (UINT) uID;

lParam = (LPARAM) (MSGFILTER) lpMsgFilter;

The EN_MSGFILTER notification message notifies a rich edit control's parent window of a keyboard or mouse event in the control. A rich edit control sends this notification message in the form of a WM_NOTIFY message.

Parameters

uID

Identifier of the rich edit control.

lpMsgFilter

Pointer to a MSGFILTER structure containing information about the keyboard or mouse message. If the parent window modifies this structure and returns a nonzero value, the modified message is processed instead of the original one.

Return Value

Returns a nonzero value if the control should process the event, or zero if the control should ignore the event.

See Also

MSGFILTER, WM_NOTIFY


EN_OLEOPFAILED
 EN_OLEOPFAILED  QuickInfo  Overview  Group

EN_OLEOPFAILED
wParam = (WPARAM) (UINT) uID;
lParam = (LPARAM) (ENOLEOPFAILED *) lpeoof;

Notifies a rich edit control's parent window that a user action on an OLE object has failed.

Parameters

uID

Identifier of the rich edit control.

lpeoof

Pointer to an ENOLEOPFAILED structure that contains information about the failure.

Return Value

Returns zero.

ENOLEOPFAILED


EN_PROTECTED [New - Windows NT]
 EN_PROTECTED  QuickInfo  Overview  Group

[New - Windows NT]

EN_PROTECTED

wParam = (WPARAM) (UINT) uID;

lParam = (LPARAM) (ENPROTECTED FAR *) lpEnProtected;

The EN_PROTECTED notification message notifies a rich edit control's parent window that the user is taking an action that would change a protected range of text. A rich edit control sends this notification message in the form of a WM_NOTIFY message.

Parameters

uID

Identifier of the rich edit control.

lpEnProtected

Pointer to an ENPROTECTED structure containing information about the message that triggered the notification.

Return Value

Returns zero to allow the operation or a nonzero value to prevent it.

Remarks

If zero is returned and the msg, wParam, and lParam members of the ENPROTECTED structure are changed, the control processes the revised message instead of the original message.

See Also

ENPROTECTED, WM_NOTIFY


EN_REQUESTRESIZE [New - Windows NT]
 EN_REQUESTRESIZE  QuickInfo  Overview  Group

[New - Windows NT]

EN_REQUESTRESIZE

wParam = (WPARAM) (UINT) uID;

lParam = (LPARAM) (REQRESIZE FAR *) lpReSize;

The EN_REQUESTRESIZE notification message notifies a rich edit control's parent window that the control's contents are either smaller or larger than the control's window size. A rich edit control sends this notification message in the form of a WM_NOTIFY message.

Parameters

uID

Identifier of the rich edit control.

lpReSize

Pointer to a REQRESIZE structure.

Return Value

No return value.

Remarks

To support the bottomless behavior of a rich edit control, the parent window must resize the control when it receives this notification message.

See Also

REQRESIZE, WM_NOTIFY


EN_SAVECLIPBOARD
 EN_SAVECLIPBOARD  QuickInfo  Overview  Group

EN_SAVECLIPBOARD
wParam = (WPARAM) (UINT) uID;
lParam = (LPARAM) (ENSAVECLIPBOARD *) lpesc;

Notifies the rich edit control's parent window that the control is closing and the clipboard contains information.

Parameters

uID

Identifier of the rich edit control.

lpesc

Pointer to an ENSAVECLIPBOARD structure that contains information about clipboard information.

Return Value

Returns zero if the clipboard should be made available to other applications, nonzero if the clipboard should not be saved.

See Also

ENSAVECLIPBOARD


EN_SELCHANGE [New - Windows NT]
 EN_SELCHANGE  QuickInfo  Overview  Group

[New - Windows NT]

EN_SELCHANGE

wParam = (WPARAM) (UINT) uID;

lParam = (LPARAM) (SELCHANGE FAR *) lpSelChange;

The EN_SELCHANGE notification message notifies a rich edit control's parent window that the current selection has changed. A rich edit control sends this notification message in the form of a WM_NOTIFY message.

Parameters

uID

Identifier of the rich edit control.

lpSelChange

Pointer to a SELCHANGE structure.

Return Value

No return value.

See Also

SELCHANGE, WM_NOTIFY


EN_SETFOCUS
 EN_SETFOCUS  QuickInfo  Overview  Group

EN_SETFOCUS

idEditCtrl = (int) LOWORD(wParam); // identifier of edit control

wNotifyCode = HIWORD(wParam);      // notification code

hwndEditCtrl = (HWND) lParam;      // handle of edit control

The EN_SETFOCUS notification message is sent when an edit control receives the keyboard focus. The parent window of the edit control receives this notification message through the WM_COMMAND message.

Remarks

In previous versions of Windows, the notification code was in HIWORD(lParam).

See Also

EN_KILLFOCUS, WM_COMMAND


EN_STOPNOUNDO
 EN_STOPNOUNDO  QuickInfo  Overview  Group

EN_STOPNOUNDO
wParam = (WPARAM) (UINT) uID;
lParam = (LPARAM) (NMHDR FAR *) lpNmHdr;

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.

Parameters

uID

Identifier of the rich edit control.

lpNmHdr

Pointer to an NMHDR structure.

Return Value

Returns zero to continue the action, nonzero to stop it.

See Also

NMHDR, WM_NOTIFY


EN_UPDATE
 EN_UPDATE  QuickInfo  Overview  Group

EN_UPDATE

idEditCtrl = (int) LOWORD(wParam); // identifier of edit control

hwndEditCtrl = (HWND) lParam;      // handle of edit control

The EN_UPDATE notification message is sent when an edit control is about to display altered text. This notification message is sent after the control has formatted the text, but before it displays the text. This makes it possible to resize the edit control window, if necessary. The parent window of the edit control receives this notification message through the WM_COMMAND message.

See Also

EN_CHANGE, WM_COMMAND


EN_VSCROLL
 EN_VSCROLL  QuickInfo  Overview  Group

EN_VSCROLL

idEditCtrl = (int) LOWORD(wParam); // identifier of edit control

hwndEditCtrl = (HWND) lParam;      // handle of edit control

The EN_VSCROLL notification message is sent when the user clicks an edit control's vertical scroll bar. The parent window of the edit control receives this notification message through the WM_COMMAND message. The parent window is notified before the screen is updated.

See Also

EN_HSCROLL, WM_COMMAND


FILEOKSTRING
 FILEOKSTRING  Overview  Group

msg = uFileOkMsg;
wParam = 0;
lParam = (LPOPENFILENAME) lpofn;

Sent to the hook function of a Open or Save As dialog box after the user has selected a filename and clicked the OK button. This message has been superseded by the CDN_FILEOK message.

Parameters

uFileOkMsg

Message identifier for the FileOk message. This value is the same as returned by the RegisterWindowMessage function for the FILEOKSTRING string.

lpofn

Address of the OPENFILENAME structure that contains the selected filename in the lpstrFile member.

Return Value

Return zero to accept the filename and let the dialog box close; return the value 1 to reject the filename and force the dialog box to remain open.

See Also

OPENFILENAME, RegisterWindowMessage


FINDMSGSTRING
 FINDMSGSTRING  Overview  Group

msg = uFindMsg;
wParam = 0;
lParam = (LPFINDREPLACE) lpfr;

Sent to the window procedure of the owner window of a Find or Replace dialog box after the user has clicked the OK button.

Parameters

uFindMsg

Message identifier for the Find message. This value is the same as returned by the RegisterWindowMessage function for the FINDMSGSTRING string.

lpfr

Address of the FINDREPLACE structure that contains the information to use to carry out the search or replacement.

Return Value

No return value.

Remarks

The Flags member of the FINDREPLACE structure is set to FR_DIALOGTERM when the user has closed the dialog box.

See Also

FINDREPLACE, RegisterWindowMessage


FM_GETDRIVEINFO
 FM_GETDRIVEINFO  QuickInfo

FM_GETDRIVEINFO

wParam = 0;                                        // not used, must be zero

lParam = (LPARAM) (LPFMS_GETDRIVEINFO) lpfmsgdi;   // drive data

A File Manager extension sends an FM_GETDRIVEINFO message to retrieve drive information from the active File Manager window.

Parameters

lpfmsgdi

Value of lParam. Points to an FMS_GETDRIVEINFO structure that receives drive information.

Return Value

The return value is always nonzero.

Remarks

If 0xFFFFFFFF is returned in the dwTotalSpace or dwFreeSpace member of the FMS_GETDRIVEINFO structure, the extension library must compute the value or values.

See Also

FMExtensionProc, FMS_GETDRIVEINFO


FM_GETFILESEL
 FM_GETFILESEL  QuickInfo

FM_GETFILESEL

wParam = (WPARAM) index;                            // index of selected file

lParam = (LPARAM) (LPFMS_GETFILESEL) lpfmsgfs;      // file data

A File Manager extension sends an FM_GETFILESEL message to retrieve information about a selected file from the active File Manager window (either the directory window or the Search Results window).

Parameters

index

Value of wParam. Specifies the zero-based index of the selected file to retrieve.

lpfmsgfs

Value of lParam. Points to an FMS_GETFILESEL structure that receives information about the selection.

Return Value

The return value is the zero-based index of the selected file that was retrieved.

Remarks

An extension can use the FM_GETSELCOUNT message to get the count of selected files.

See Also

FMExtensionProc, FMS_GETFILESEL, FM_GETFILESELLFN, FM_GETSELCOUNT, FM_GETSELCOUNTLFN


FM_GETFILESELLFN
 FM_GETFILESELLFN  QuickInfo

FM_GETFILESELLFN

wParam = (WPARAM) index;                       // index of selected file

lParam = (LPARAM) (LPFMS_GETFILESEL) lpfmsgfs; // selection data

A File Manager extension sends an FM_GETFILESELLFN message to retrieve information about a selected file from the active File Manager window (either the directory window or the Search Results window). The selected file can have a long filename.

Parameters

index

Value of wParam. Specifies the zero-based index of the selected file to retrieve.

lpfmsgfs

Value of lParam. Points to an FMS_GETFILESEL structure that receives information about the selection.

Return Value

The return value is the zero-based index of the selected file that was retrieved.

Remarks

Only extensions that support long filenames (for example, network-aware extensions) should use this message.

An extension can use the FM_GETSELCOUNT message to get the count of selected files.

See Also

FMExtensionProc, FM_GETFILESEL, FM_GETSELCOUNT, FM_GETSELCOUNTLFN


FM_GETFOCUS
 FM_GETFOCUS  QuickInfo

FM_GETFOCUS

wParam = 0;     // not used, must be zero

lParam = 0;     // not used, must be zero

A File Manager extension sends a FM_GETFOCUS message to retrieve the type of the File Manager window that has the input focus.

Parameters

This message has no parameters.

Return Value

The return value is the type of File Manager window that has input focus. It can be one of the following values:

Value	Meaning
FMFOCUS_DIR	Directory portion of a directory window
FMFOCUS_TREE	Tree portion of a directory window
FMFOCUS_DRIVES	Drive bar of a directory window
FMFOCUS_SEARCH	Search Results window


FM_GETSELCOUNT
 FM_GETSELCOUNT  QuickInfo

FM_GETSELCOUNT

wParam = 0; // not used, must be zero

lParam = 0; // not used, must be zero

A File Manager extension sends a FM_GETSELCOUNT message to retrieve a count of the selected files in the active File Manager window (either the directory window or the Search Results window).

Parameters

This message has no parameters.

Return Value

The return value is the number of selected files.

See Also

FM_GETFILESEL, FM_GETFILESELLFN, FM_GETSELCOUNTLFN


FM_GETSELCOUNTLFN
 FM_GETSELCOUNTLFN  QuickInfo

FM_GETSELCOUNTLFN

wParam = 0; // not used, must be zero

lParam = 0; // not used, must be zero

A File Manager extension sends an FM_GETSELCOUNTLFN message to retrieve the number of selected files in the active File Manager window (either the directory window or the Search Results window). The count includes files that have long filenames.

Parameters

This message has no parameters.

Return Value

The return value is the number of selected files.

Remarks

Only extensions that support long filenames (for example, network-aware extensions) should use this message.

See Also

FM_GETFILESEL, FM_GETFILESELLFN, FM_GETSELCOUNT


FM_REFRESH_WINDOWS
 FM_REFRESH_WINDOWS  QuickInfo

FM_REFRESH_WINDOWS

wParam = (WPARAM) (BOOL) fRepaint;  // repaint flag

lParam = 0;                         // not used, must be zero

A File Manager extension sends an FM_REFRESH_WINDOWS message to cause File Manager to repaint either its active window or all of its windows.

Parameters

fRepaint

Value of wParam. Specifies whether File Manager repaints its active window or all of its windows. If this parameter is TRUE, File Manager repaints all of its windows. Otherwise, File Manager repaints only its active window.

Return Value

This message does not return a meaningful value.

Remarks

File-system changes caused by an extension are automatically detected by File Manager. An extension should use this message only in situations where drive connections are made or canceled.

See Also

FMExtensionProc


FM_RELOAD_EXTENSIONS
 FM_RELOAD_EXTENSIONS  QuickInfo

FM_RELOAD_EXTENSIONS

wParam = 0; // not used, must be zero

lParam = 0; // not used, must be zero

A File Manager extension (or another application) sends an FM_RELOAD_EXTENSIONS message to cause File Manager to reload all extension DLLs listed in the [AddOns] section of the WINFILE.INI file.

Parameters

This message has no parameters.

Return Value

This message does not return a meaningful value.

Remarks

Other applications can use the PostMessage function to send this message to File Manager. To obtain the appropriate File Manager window handle, an application can specify "WFS_Frame" as the lpszClassName parameter in a call to the FindWindow function.

See Also

FindWindow, FMExtensionProc, PostMessage


FMEVENT_HELPMENUITEM
 FMEVENT_HELPMENUITEM  QuickInfo

FMEVENT_HELPMENUITEM

uItem = (UINT) lParam;  /* command item for which help is sought */

The FMEVENT_HELPMENUITEM message is sent to a File Manager extension DLL procedure when the user presses F1 on a menu or toolbar command item. The extension should call WinHelp, with that function's hwnd parameter set to the value of the extension procedure's hwnd parameter.

Parameters

uItem

Identifies the menu or toolbar command item for which help is sought. The extension procedure uses this value to determine how best to call WinHelp.

Return Value

An extension DLL procedure should return zero if it processes this message.

See Also

FMExtensionProc, WinHelp, FMEVENT_HELPSTRING


FMEVENT_HELPSTRING
 FMEVENT_HELPSTRING  QuickInfo

FMEVENT_HELPSTRING

lpfmshs = (LPFMS_HELPSTRING) lParam;  /* pointer to data transfer structure */

The FMEVENT_HELPSTRING message is sent to a File Manager extension DLL procedure when File Manager wants a help string for a menu or toolbar command item.

Parameters

lpfmshs

Points to an FMS_HELPSTRING structure that communicates command item help string data.

The FMS_HELPSTRING structure identifies the command item for which a help string is wanted, along with a handle to its menu. An application then writes the appropriate help string to the FMS_HELPSTRING structure's szHelp member.

Return Value

An extension DLL procedure should return zero if it processes this message.

See Also

FMExtensionProc, FMEVENT_HELPMENUITEM


FMEVENT_INITMENU
 FMEVENT_INITMENU  QuickInfo

FMEVENT_INITMENU

hmenu = (HMENU) lParam; /* handle of File Manager menu */

The FMEVENT_INITMENU message is sent to an extension DLL when the user selects the menu for the extension from the File Manager menu bar. The extension can use this notification to initialize menu items in the menu.

Parameters

hmenu

Specifies the handle of the File Manager menu bar.

Return Value

An extension DLL should return zero if it processes this message.

Remarks

An extension DLL receives this message only when the user selects the top-level menu. If the extension contains submenus, it must initialize them at the same time it initializes the top-level menu.

See Also

FMExtensionProc


FMEVENT_LOAD
 FMEVENT_LOAD  QuickInfo

FMEVENT_LOAD

lpfmsld = (LPFMS_LOAD) lParam;  /* address of struct. with delta */

The FMEVENT_LOAD message is sent to an extension DLL when File Manager is loading the DLL.

Parameters

lpfmsld

Points to an FMS_LOAD structure that specifies the menu-item delta value. An extension DLL should save the menu-item delta value and fill the other structure members with information about the extension.

Return Value

An extension DLL must return TRUE to continue loading the DLL. If the DLL returns FALSE, File Manager calls the FreeLibrary function and ends any communication with the extension DLL.

Remarks

An application should fill the dwSize, szMenuName, and hMenu members in the FMS_LOAD structure. It should also save the value of the wMenuDelta member and use it to identify menu items when modifying the menu.

See Also

FMExtensionProc, FMS_LOAD, FreeLibrary


FMEVENT_SELCHANGE
 FMEVENT_SELCHANGE  QuickInfo

FMEVENT_SELCHANGE

The FMEVENT_SELCHANGE message is sent to an extension DLL when the user selects a filename in the File Manager directory window or Search Results window.

Parameters

This message has no parameters.

Return Value

An extension DLL should return zero if it processes this message.

Remarks

Changes in the tree portion of the directory window do not produce this message.

Because the user can change the selection many times, the extension DLL must return promptly after processing this message to avoid slowing the selection process for the user.

See Also

FMExtensionProc


FMEVENT_TOOLBARLOAD
 FMEVENT_TOOLBARLOAD  QuickInfo

FMEVENT_TOOLBARLOAD

lpfmstbl = (LPFMS_TOOLBARLOAD) lParam;   /* toolbar data */

The FMEVENT_TOOLBARLOAD message is sent to an extension DLL when File Manager is loading its toolbar. This message allows an extension DLL to add a button to the File Manager toolbar.

Parameters

lpfmstbl

Points to an FMS_TOOLBARLOAD structure. If the extension DLL adds a button to the toolbar in File Manager, the DLL should fill the structure with information about the button.

.

Return Value

An extension DLL must return TRUE to add the button to the toolbar. If the DLL returns FALSE, File Manager does not add the button.

See Also

FMExtensionProc, FMS_TOOLBARLOAD


FMEVENT_UNLOAD
 FMEVENT_UNLOAD  QuickInfo

FMEVENT_UNLOAD

The FMEVENT_UNLOAD message is sent to an extension DLL when File Manager is unloading the DLL.

Parameters

This message has no parameters.

Return Value

An extension DLL should return zero if it processes this message.

Remarks

The hwnd and hMenu values passed with the FMEVENT_LOAD and FMEVENT_INITMENU messages may not be valid at the time this message is sent.

See Also

FMExtensionProc


FMEVENT_USER_REFRESH
 FMEVENT_USER_REFRESH  QuickInfo

FMEVENT_USER_REFRESH

The FMEVENT_USER_REFRESH message is sent to an extension DLL when the user chooses the Refresh command from the Window menu in File Manager. The extension can use this notification to update its menu.

Parameters

This message has no parameters.

Return Value

An extension DLL should return zero if it processes this message.

See Also

FMExtensionProc


HDM_DELETEITEM [New - Windows NT]
 HDM_DELETEITEM  QuickInfo  Overview  Group

[New - Windows NT]

HDM_DELETEITEM

wParam = (WPARAM) (int) index;

lParam = 0;

// Corresponding macro

BOOL Header_DeleteItem(hwndHD, index);

The HDM_DELETEITEM message deletes an item from a header control.

Parameters

hwndHD

Handle to the header control.

index

Index of the item to delete.

Return Value

If the operation succeeds, the return value is TRUE.

If the operation fails, the return value is FALSE.


HDM_GETITEM [New - Windows NT]
 HDM_GETITEM  QuickInfo  Overview  Group

[New - Windows NT]

HDM_GETITEM

wParam = (WPARAM) (int) index;

lParam = (LPARAM) (HD_ITEM FAR*) phdi;

// Corresponding macro

BOOL Header_GetItem(hwndHD, index, phdi);

The HDM_GETITEM message retrieves information about an item in a header control.

Parameters

hwndHD

Handle to the header control.

index

Index of the item for which information is to be retrieved.

phdi

Pointer to an HD_ITEM structure. When the message is sent, the mask member indicates the type of information being requested. When the message returns, the other members receive the requested information. If the mask member specifies zero, the message returns TRUE but copies no information to the structure.

Return Value

If the operation succeeds, the return value is TRUE.

If the operation fails, the return value is FALSE.

See Also

HD_ITEM


HDM_GETITEMCOUNT [New - Windows NT]
 HDM_GETITEMCOUNT  QuickInfo  Overview  Group

[New - Windows NT]

HDM_GETITEMCOUNT

wParam = 0;

lParam = 0;

// Corresponding macro

int Header_GetItemCount(hwndHD);

The HDM_GETITEMCOUNT message retrieves a count of the items in a header control.

Parameters

hwndHD

Handle to the header control.

Return Value

If the operation succeeds, the return value is the number of items.

If the operation fails, the return value is − 1.


HDM_HITTEST [New - Windows NT]
 HDM_HITTEST  QuickInfo  Overview  Group

[New - Windows NT]

HDM_HITTEST

wParam = 0;

lParam = (LPARAM) (HD_HITTESTINFO FAR *) phdhti;

The HDM_HITTEST message tests a point to determine which header item, if any, is at the specified point.

Parameters

phdhti

Pointer to an HD_HITTESTINFO structure that contains the position to test and receives information about the results of the test.

Return Value

Returns the index of the item at the specified position, if any, or  − 1 otherwise.

See Also

HD_HITTESTINFO


HDM_INSERTITEM [New - Windows NT]
 HDM_INSERTITEM  QuickInfo  Overview  Group

[New - Windows NT]

HDM_INSERTITEM

wParam = (WPARAM) (int) index;

lParam = (LPARAM) (const HD_ITEM FAR*) phdi;

// Corresponding macro

int Header_InsertItem(hwndHD, index, phdi);

The HDM_INSERTITEM message inserts a new item into a header control.

Parameters

hwndHD

Handle to the header control.

index

Index of the item after which the new item is to be inserted. The new item is inserted at the end of the header control if index is greater than or equal to the number of items in the control. If index is zero, the new item is inserted at the beginning of the header control.

phdi

Pointer to an HD_ITEM structure that contains information about the new item.

Return Value

If the operation succeeds, the return value is the index of the new item.

If the operation fails, the return value is − 1.

See Also

HD_ITEM


HDM_LAYOUT [New - Windows NT]
 HDM_LAYOUT  QuickInfo

[New - Windows NT]

HDM_LAYOUT

wParam = 0;

lParam = (LPARAM) (HD_LAYOUT FAR*) playout;

// Corresponding macro

BOOL Header_Layout(hwndHD, playout);

The HDM_LAYOUT message retrieves the size and position of a header control within a given rectangle. This message is used to determine the appropriate dimensions for a new header control that is to occupy the given rectangle.

Parameters

hwndHD

Handle to the header control.

playout

Pointer to an HD_LAYOUT structure. The prc member specifies the coordinates of a rectangle, and the pwpos member receives the size and position for the header control within the rectangle.

Return Value

If the operation succeeds, the return value is TRUE.

If the operation fails, the return value is FALSE.

See Also

HD_LAYOUT


HDM_SETITEM [New - Windows NT]
 HDM_SETITEM  QuickInfo

[New - Windows NT]

HDM_SETITEM

wParam = (WPARAM) (int) index;

lParam = (LPARAM) (const HD_ITEM FAR*) phdi;

// Corresponding macro

BOOL Header_SetItem(hwndHD, index, phdi);

The HDM_SETITEM message sets the attributes of the specified item in a header control.

Parameters

hwndHD

Handle to the header control.

index

Index of the item whose attributes are to be changed.

phdi

Pointer to an HD_ITEM structure. When the message is sent, the mask member indicates the attributes to set. The other members specify new attributes.

Return Value

If the operation succeeds, the return value is TRUE.

If the operation fails, the return value is FALSE.

Remarks

The HDN_ITEMCHANGING notification message is sent to the parent window before the item attributes are changed. The parent window can return FALSE to prevent the changes, and in that case, HDM_SETITEM returns FALSE. If the parent window returns TRUE, the changes are made and the parent window receives the HDN_ITEMCHANGED notification message.

See Also

HD_ITEM, HDN_ITEMCHANGED, HDN_ITEMCHANGING


HDN_BEGINTRACK [New - Windows NT]
 HDN_BEGINTRACK  QuickInfo  Overview  Group

[New - Windows NT]

HDN_BEGINTRACK

phdn = (HD_NOTIFY FAR *) lParam;

The HDN_BEGINTRACK notification message notifies a header control's parent window that the user has begun dragging a divider in the control (that is, the user has pressed the left mouse button while the mouse cursor is on a divider in the header control). This notification message is sent in the form of a WM_NOTIFY message.

Parameters

phdn

Pointer to an HD_NOTIFY structure that contains information about the header control and the item whose divider is to be dragged.

Return Value

Returns FALSE to allow tracking of the divider or TRUE to prevent tracking.

See Also

HD_NOTIFY, WM_NOTIFY


HDN_DIVIDERDBLCLICK [New - Windows NT]
 HDN_DIVIDERDBLCLICK  QuickInfo  Overview  Group

[New - Windows NT]

HDN_DIVIDERDBLCLICK

phdn = (HD_NOTIFY FAR *) lParam;

The HDN_DIVIDERDBLCLICK notification message notifies a header control's parent window that the user double-clicked the divider area of the control. This notification message is sent in the form of a WM_NOTIFY message.

Parameters

phdn

Pointer to an HD_NOTIFY structure that contains information about the header control and the item whose divider was double-clicked.

Return Value

No return value.

See Also

HD_NOTIFY, WM_NOTIFY


HDN_ENDTRACK [New - Windows NT]
 HDN_ENDTRACK  QuickInfo  Overview  Group

[New - Windows NT]

HDN_ENDTRACK

phdn = (HD_NOTIFY FAR *) lParam;

The HDN_ENDTRACK notification message notifies a header control's parent window that the user has finished dragging a divider. This notification message sent in the form of a WM_NOTIFY message.

Parameters

phdn

Pointer to an HD_NOTIFY structure that contains information about the header control and the item whose divider was dragged.

Return Value

No return value.

See Also

HD_NOTIFY, WM_NOTIFY


HDN_ITEMCHANGED [New - Windows NT]
 HDN_ITEMCHANGED  QuickInfo  Overview  Group

[New - Windows NT]

HDN_ITEMCHANGED

phdr = (HD_NOTIFY FAR *) lParam;

The HDN_ITEMCHANGED notification message notifies a header control's parent window that the attributes of a header item have changed. This notification message is sent in the form of a WM_NOTIFY message.

Parameters

phdr

Pointer to an HD_NOTIFY structure that contains information about the header control, including the attributes that have changed.

Return Value

No return value.

See Also

HD_NOTIFY, WM_NOTIFY


HDN_ITEMCHANGING [New - Windows NT]
 HDN_ITEMCHANGING  QuickInfo  Overview  Group

[New - Windows NT]

HDN_ITEMCHANGING

phdr = (HD_NOTIFY FAR *) lParam;

The HDN_ITEMCHANGING notification message notifies a header control's parent window that the attributes of a header item are about to change. This notification message is sent in the form of a WM_NOTIFY message.

Parameters

phdr

Pointer to an HD_NOTIFY structure that contains information about the header control and the header item, including the attributes that are about to change.

Return Value

Returns FALSE to allow the changes or TRUE to prevent them.

See Also

HD_NOTIFY, WM_NOTIFY


HDN_ITEMCLICK [New - Windows NT]
 HDN_ITEMCLICK  QuickInfo  Overview  Group

[New - Windows NT]

HDN_ITEMCLICK

phdr = (HD_NOTIFY FAR *) lParam;

The HDN_ITEMCLICK notification message notifies a header control's parent window that the user clicked the control. This notification message is sent in the form of a WM_NOTIFY message.

Parameters

phdr

Pointer to an HD_NOTIFY structure that identifies the header control and specifies the index of the header item that was clicked and the mouse button used to click the item. The pitem member is set to NULL.

Return Value

No return value.

Remarks

A header control sends this notification message after the user releases the left mouse button.

See Also

HD_NOTIFY, WM_NOTIFY


HDN_ITEMDBLCLICK [New - Windows NT]
 HDN_ITEMDBLCLICK  QuickInfo  Overview  Group

[New - Windows NT]

HDN_ITEMDBLCLICK

pnmhdr = (NMHDR FAR *) lParam;

The HDN_ITEMDBLCLICK notification message notifies a header control's parent window that the user double-clicked the control. This notification message is sent in the form of a WM_NOTIFY message. Only header controls that have the HDS_BUTTONS style send this notification.

Parameters

pnmhdr

Pointer to an NMHDR structure that contains the handle and identifier of the header control and the HDN_ITEMDBLCLICK notification code.

Return Value

No return value.

Remarks

A control that has the HDS_DIVIDERTRACK style does not send this notification when the user double-clicks the divider.

See Also

NMHDR, WM_NOTIFY


HDN_TRACK [New - Windows NT]
 HDN_TRACK  QuickInfo  Overview  Group

[New - Windows NT]

HDN_TRACK

phdr = (HD_NOTIFY FAR *) lParam;

The HDN_TRACK notification message notifies a header control's parent window that the user is dragging a divider in the header control. This notification message is sent in the form of a WM_NOTIFY message.

Parameters

phdr

Pointer to an HD_NOTIFY structure that contains information about the header control and the item whose divider is being dragged.

Return Value

Returns FALSE to continue tracking the divider or TRUE to end tracking.

See Also

HD_NOTIFY, WM_NOTIFY


 HELPMSGSTRING

msg = uHelpMsg;
wParam = (HWND) hdlg;
lParam = (LPVOID) lpStruct;

Sent to the window procedure of the owner window of a dialog box after the user has clicked the Help button. This message is available only if the dialog box was created using a SHOWHELP value in the Flags member of the corresponding structure. For Open and Save As dialog boxes, this message has been superseded by the CDN_HELP message.

Parameters

uHelpMsg

Message identifier for the Help message. This value is the same as returned by the RegisterWindowMessage function for the HELPMSGSTRING string.

hdlg

Handle of the common dialog box.

lpStruct

Address of the structure for the dialog box. Can be a CHOOSECOLOR, CHOOSEFONT, OPENFILENAME, FINDREPLACE, PRINTDLG or PAGESETUPDLG structure.

Return Value

No return value.

Remarks

Applications can check the lCustData member of the given structure to determine which instance of the dialog box is requesting help.

See Also

CDN_HELP, CHOOSECOLOR, CHOOSEFONT, OPENFILENAME, FINDREPLACE, PRINTDLG, PAGESETUPDLG, RegisterWindowMessage


HKM_GETHOTKEY [New - Windows NT]
 HKM_GETHOTKEY  QuickInfo  Overview  Group

[New - Windows NT]

HKM_GETHOTKEY

wParam = 0;

lParam = 0;

The HKM_GETHOTKEY message retrieves the virtual-key code and modifier flags of a hot key from a hot-key control.

Return Value

Returns the virtual-key code and modifier flags. The virtual-key code is in the low-order byte, and the modifier flags are in the high-order byte. The modifier flags can be a combination of the following values:

Value	Meaning
HOTKEYF_ALT	ALT key
HOTKEYF_CONTROL	CTRL key
HOTKEYF_EXT	Extended key
HOTKEYF_SHIFT	SHIFT key
Remarks

The 16-bit value returned by this message can be used as the wParam parameter in the WM_SETHOTKEY message.

See Also

WM_SETHOTKEY


HKM_SETHOTKEY [New - Windows NT]
 HKM_SETHOTKEY  QuickInfo  Overview  Group

[New - Windows NT]

HKM_SETHOTKEY

wParam = MAKEWORD(bVKHotKey, bfMods);

lParam = 0;

The HKM_SETHOTKEY message sets the hot key combination for a hot-key control.

Parameters

bVKHotKey

Virtual-key code of the hot key.

bfMods

Modifier flags indicating the keys that, when used in combination with bVKHotKey, define a hot-key combination. For a list of modifier flag values, see the description of the HKM_GETHOTKEY message.

Return Value

No return value.

See Also

HKM_GETHOTKEY


HKM_SETRULES [New - Windows NT]
 HKM_SETRULES  QuickInfo  Overview  Group

[New - Windows NT]

HKM_SETRULES

wParam = (WPARAM) fwCombInv;

lParam = MAKELPARAM(fwModInv, 0);

The HKM_SETRULES message defines the invalid combinations and the default modifier combination for a hot-key control.

Parameters

fwCombInv

Array of flags that specify invalid key combinations. This parameter can be a combination of the following values:

Value	Meaning
HKCOMB_A	ALT
HKCOMB_C	CTRL
HKCOMB_CA	CTRL+ALT
HKCOMB_NONE	Unmodified keys
HKCOMB_S	SHIFT
HKCOMB_SA	SHIFT+ALT
HKCOMB_SC	SHIFT+CTRL
HKCOMB_SCA	SHIFT+CTRL+ALT
fwModInv

Array of flags that specify the key combination to use when the user enters an invalid combination. For a list of modifier flag values, see the description of the HKM_GETHOTKEY message.

Return Value

No return value.

Remarks

When a user enters an invalid key combination, as defined by flags specified in fwCombInv, the system uses the bitwise-OR operator to combine the keys entered by the user with the flags specified in fwModInv. The resulting key combination is converted into a string and then displayed in the hot-key control.

See Also

HKM_GETHOTKEY


 IMC_CLOSESTATUSWINDOW

msg = (UINT) WM_IME_CONTROL;
wParam = (WPARAM) IMC_CLOSESTATUSWINDOW;
lParam = (LPARAM) 0;

An application sends the IMC_CLOSESTATUSWINDOW message to the IME window to hide the status window.

Return Value

Returns zero if successful, nonzero otherwise.

Remarks

When the status window of IME is already hidden, this message does nothing. Although an application may send this message to the IME window, the application does not receive the corresponding IMN_CLOSESTATUSWINDOW message.


IMC_GETCANDIDATEPOS [New - Windows 95]
 IMC_GETCANDIDATEPOS  QuickInfo  Overview  Group

[New - Windows 95]

msg = (UINT) WM_IME_CONTROL;
wParam = (WPARAM) IMC_GETCANDIDATEPOS;
lParam = (LPARAM) &CandForm;

An application sends the IMC_GETCANDIDATEPOS message to an IME window to get the position of the candidate window. Because the IME may adjust the position of a candidate window, an application uses this message to get the actual position to decide whether to reposition the window.

Parameters

lParam

Pointer to the CANDIDATEFORM structure that receives the position of the candidate window.

Return Value

Returns zero if successful, nonzero otherwise.

Remarks

The returned position is in window coordinates relative to the window having the current input focus.

See Also

CANDIDATEFORM


IMC_GETCOMPOSITIONCOLOR
 IMC_GETCOMPOSITIONCOLOR  Overview  Group

msg = WM_IME_CONTROL;
wParam = (WPARAM) IMC_GETCOMPOSITIONCOLOR;
lParam = (LPARAM) (COLORREF *) aCompCr;

Gets the current IME composition colors. Available only in Asian-language versions of the operating system.

Parameters

aCompCr

Address of an array of COLORREF values identifying the composition colors. The array has the following elements:

Element	Meaning
aCompCr[0]	Foreground color of character currently being entered
aCompCr[1]	Foreground color of character currently being converted (already converted)
aCompCr[2]	Foreground color of character given from conversion
aCompCr[3]	Foreground color of character currently being converted (yet to be converted)
aCompCr[4]	Background color of character currently being entered
aCompCr[5]	Background color of character currently being converted (already converted)
aCompCr[6]	Background color of character given from conversion
aCompCr[7]	Background color of character currently being converted (yet to be converted)
Return Value

Returns TRUE.

See Also

COLORREF


IMC_GETCOMPOSITIONFONT [New - Windows 95]
 IMC_GETCOMPOSITIONFONT  QuickInfo  Overview  Group

[New - Windows 95]

msg = (UINT) WM_IME_CONTROL;
wParam = (WPARAM) IMC_GETCOMPOSITIONFONT;
lParam = (LPARAM) &LogFont;

An application sends the IMC_GETCOMPOSITIONFONT message to an IME window to retrieve the logical font used for displaying intermediate characters in the composition window.

Parameters

lParam

Pointer to the LOGFONT structure that receives information about the logical font.

Return Value

Returns zero if successful, nonzero otherwise.

See Also

LOGFONT


IMC_GETCOMPOSITIONWINDOW [New - Windows 95]
 IMC_GETCOMPOSITIONWINDOW  QuickInfo  Overview  Group

[New - Windows 95]

msg = (UINT) WM_IME_CONTROL;
wParam = (WPARAM) IMC_GETCOMPOSITIONWINDOW;
lParam = (LPARAM) &CompForm;

An application sends the IMC_GETCOMPOSITIONWINDOW message to an IME window to get the position of the composition window. Because the IME may adjust the position of a composition window, an application uses this message to get the actual position to decide whether to reposition the window.

Parameters

lParam

Pointer to the COMPOSITIONFORM structure that receives the position of the composition window.

Return Value

Returns zero if successful, nonzero otherwise.

Remarks

The returned position is in window coordinates relative to the window having the current input focus.

See Also

COMPOSITIONFORM


IMC_GETCONVERSIONMODE [New - Windows 95]
 IMC_GETCONVERSIONMODE  QuickInfo  Overview  Group

[New - Windows 95]

msg = (UINT) WM_IME_CONTROL;
wParam = (WPARAM) IMC_GETCONVERSIONMODE;
lParam = 0;

An application sends the IMC_GETCONVERSIONMODE message to an IME window to obtain the current conversion mode. The window retrieves the current conversion mode from the current input context.

Return Value

Returns a combination of the values given in the "IME Conversion Modes" table in Input Method Editor Constants.


IMC_GETOPENSTATUS [New - Windows 95]
 IMC_GETOPENSTATUS  QuickInfo  Overview  Group

[New - Windows 95]

msg = (UINT) WM_IME_CONTROL;
wParam = (WPARAM) IMC_GETOPENSTATUS;
lParam = 0;

An application sends the IMC_GETOPENSTATUS message to an IME window to determine whether the IME is open.

Return Value

Returns nonzero if the current IME is open, 0 otherwise.


IMC_GETSENTENCEMODE [New - Windows 95]
 IMC_GETSENTENCEMODE  QuickInfo  Overview  Group

[New - Windows 95]

msg = (UINT) WM_IME_CONTROL;
wParam = (WPARAM) IMC_GETSENTENCEMODE;
lParam = 0;

An application sends the IMC_GETSENTENCEMODE message to an IME window to obtain current sentence mode.

Return Value

Returns a combination of the values given in the "IME Sentence Modes" table in Input Method Editor Constants.


IMC_GETSTATUSWINDOWPOS [New - Windows 95]
 IMC_GETSTATUSWINDOWPOS  QuickInfo  Overview  Group

[New - Windows 95]

msg = (UINT) WM_IME_CONTROL;
wParam = (WPARAM) IMC_GETSTATUSWINDOWPOS;
lParam = 0;

An application sends the IMC_GETSTATUSWINDOWPOS message to an IME window to get the position of the status window.

Return Value

Returns a POINTS structure that contains the x- and y-coordinates of the status window position.

See Also

POINTS


 IMC_OPENSTATUSWINDOW

msg = (UINT) WM_IME_CONTROL;
wParam = (WPARAM) IMC_OPENSTATUSWINDOW;
lParam = (LPARAM) 0;

An application sends the IMC_OPENSTATUSWINDOW message to the IME window to show the status window. This message is ignored if the system is not in the show IME status mode. The user can set or clear the show IME status mode from the task bar.

Return Value

Returns zero if successful, nonzero otherwise.

Remarks

If the status window is already shown, this message does nothing. Although the application may send this message to the IME window, the application does not receive the corresponding IMN_OPENSTATUSWINDOW message.


IMC_SETCANDIDATEPOS [New - Windows 95]
 IMC_SETCANDIDATEPOS  QuickInfo  Overview  Group

[New - Windows 95]

msg = (UINT) WM_IME_CONTROL;
wParam = (WPARAM) IMC_SETCANDIDATEPOS;
lParam = (LPARAM) &CandForm;

An application sends the IMC_SETCANDIDATEPOS message to an IME window to set the position of the candidate window. This message is intended for applications that display composition characters on their own but use the IME window to display candidates.

Parameters

lParam

Pointer to the CANDIDATEFORM structure that contains the x- and y-coordinates for the candidate window. The application should set the dwIndex member in the structure.

Return Value

Return zero if successful, nonzero otherwise.

See Also

CANDIDATEFORM


IMC_SETCOMPOSITIONCOLOR
 IMC_SETCOMPOSITIONCOLOR  Overview  Group

msg = WM_IME_CONTROL;
wParam = (WPARAM) IMC_SETCOMPOSITIONCOLOR;
lParam = (LPARAM) (COLORREF *) aCompCr;

Sets the IME composition colors. Available only in Asian-language versions of the operating system.

Parameters

aCompCr

Address of an array of COLORREF values identifying the composition colors. The array has the following elements:

Element	Meaning
aCompCr[0]	foreground color of character currently being entered
aCompCr[1]	foreground color of character currently being converted (already converted)
aCompCr[2]	foreground color of character given from conversion
aCopmCr[3]	foreground color of character currently being converted (yet to be converted)
aCompCr[4]	background color of character currently being entered
aCompCr[5]	background color of character currently being converted (already converted)
aCompCr[6]	background color of character given from conversion
aCompCr[7]	background color of character currently being converted (yet to be converted)
Return Value

Returns TRUE.

See Also

COLORREF


IMC_SETCOMPOSITIONFONT [New - Windows 95]
 IMC_SETCOMPOSITIONFONT  QuickInfo  Overview  Group

[New - Windows 95]

msg = (UINT) WM_IME_CONTROL;
wParam = (WPARAM) IMC_SETCOMPOSITIONFONT;
lParam = (LPARAM) &LogFont;

An application sends the IMC_SETCOMPOSITIONFONT message to an IME window to specify the logical font to use for displaying intermediate characters in the composition window.

Parameters

lParam

Pointer to the LOGFONT structure that contains information about the logical font.

Return Value

Returns zero if successful, nonzero otherwise.

Remarks

When processing this message, the IME window changes the current selected font in the input context.

See Also

LOGFONT


IMC_SETCOMPOSITIONWINDOW [New - Windows 95]
 IMC_SETCOMPOSITIONWINDOW  QuickInfo  Overview  Group

[New - Windows 95]

msg = (UINT) WM_IME_CONTROL;
wParam = (WPARAM) IMC_SETCOMPOSITIONWINDOW;
lParam = (LPARAM) &CompForm;

An application sends the IMC_SETCOMPOSITIONWINDOW message to an IME window to set the style of the composition window. The message set this style in the current input context and the style is subsequently applied to each IME window that receives that input context.

Parameters

lParam

Pointer to the COMPOSITIONFORM structure that contains the style information.

Return Value

Returns zero if successful, nonzero otherwise.

Remarks

By default, the IME window has the CFS_POINT style. This means the IME window uses the current caret position and window client area when it opens composition window.

See Also

COMPOSITIONFORM


IMC_SETCONVERSIONMODE [New - Windows 95]
 IMC_SETCONVERSIONMODE  QuickInfo  Overview  Group

[New - Windows 95]

msg = (UINT) WM_IME_CONTROL;
wParam = (WPARAM) IMC_SETCONVERSIONMODE;
lParam = (LPARAM) cMode;

An application sends the IMC_SETCONVERSIONMODE message to an IME window to set current conversion mode.

Parameters

lParam

Conversion mode. Can be one of the values given in the "IME Conversion Modes" table in Input Method Editor Constants.

Return Value

Returns zero if successful, nonzero otherwise.


IMC_SETOPENSTATUS [New - Windows 95]
 IMC_SETOPENSTATUS  QuickInfo  Overview  Group

[New - Windows 95]

msg = (UINT) WM_IME_CONTROL;
wParam = (WPARAM) IMC_SETOPENSTATUS;
lParam = (LPARAM) bOpen;

An application sends the IMC_SETOPENSTATUS message to an IME window to open or close the current IME.

Parameters

lParam

Open status. If TRUE, the IME is opened, closed otherwise.

Return Value

Returns zero if successful, nonzero otherwise.

Remarks

When processing this message, the IME window changes the current input context.


IMC_SETSENTENCEMODE [New - Windows 95]
 IMC_SETSENTENCEMODE  QuickInfo  Overview  Group

[New - Windows 95]

msg = (UINT) WM_IME_CONTROL;
wParam = (WPARAM) IMC_SETSENTENCEMODE;
lParam = 0;

An application sends the IMC_SETSENTENCEMODE message to an IME window to set the current sentence mode.

Parameters

lParam

Sentence mode. Can be one of the values given in the "IME Sentence Modes" table in Input Method Editor Constants.

Return Value

Returns zero if successful, nonzero otherwise.


IMC_SETSTATUSWINDOWPOS [New - Windows 95]
 IMC_SETSTATUSWINDOWPOS  QuickInfo  Overview  Group

[New - Windows 95]

msg = (UINT) WM_IME_CONTROL;
wParam = (WPARAM) IMC_SETSTATUSWINDOWPOS;
lParam = (LPARAM) &pts;

An application sends the IMC_SETSTATUSWINDOWPOS message to an IME window to set the position of the status window.

Parameters

lParam

Pointer to a POINTS structure that contains the x- and y-coordinates of the position of the status window.

Return Value

Returns zero if successful, nonzero otherwise.

See Also

POINTS


IMN_CHANGECANDIDATE [New - Windows 95]
 IMN_CHANGECANDIDATE  QuickInfo  Overview  Group

[New - Windows 95]

fCandidates = (DWORD) lParam;

The IMN_CHANGECANDIDATE message is sent to the application when an IME is about to change the content of the candidate window. An application should process this notification message if it displays candidates itself. The application receives this notification message through the WM_IME_NOTIFY message.

Parameters

fCandidates

Candidate lists flag. Each bit corresponds to a candidate list: bit 0 to the first list, bit 1 to the second, and so on. If a specified bit is 1, the corresponding candidate window is about to be changed.

Return Value

No return value.

Remarks

The IME window changes the appearance of the candidate window when it processes this message. An application can get information about the system window with the ImmGetCandidateListCount and ImmGetCandidateList functions.

See Also

ImmGetCandidateList, ImmGetCandidateListCount, WM_IME_NOTIFY


IMN_CLOSECANDIDATE [New - Windows 95]
 IMN_CLOSECANDIDATE  QuickInfo  Overview  Group

[New - Windows 95]

fCandidate = (DWORD) lParam;

The IMN_CLOSECANDIDATE message is sent to the application when an IME is about to close the candidate window. An application should process this message if it displays candidates itself. The application receives this notification message through the WM_IME_NOTIFY message.

Parameters

fCandidates

Candidate lists flag. Each bit corresponds to a candidate list: bit 0 to the first list, bit 1 to the second, and so on. If a specified bit is 1, the corresponding candidate window is about to be closed.

Return Value

No return value.

Remarks

By default, the IME window destroys a candidate window when it processes this message.

See Also

WM_IME_NOTIFY


IMN_CLOSESTATUSWINDOW(preliminary-Windows 95) [New - Windows 95]
 IMN_CLOSESTATUSWINDOW  Overview  Group

[New - Windows 95]

The IMN_CLOSESTATUSWINDOW message is sent to the application when an IME is about to close the status window. An application should process this notification message if it displays the status window for the IME. The application receives this notification message through the WM_IME_NOTIFY message.

Return Value

No return value.

Remarks

The IME window closes the status window when it processes this message.

See Also

WM_IME_NOTIFY


IMN_GUIDELINE(preliminary-Windows 95) [New - Windows 95]
 IMN_GUIDELINE  QuickInfo  Overview  Group

[New - Windows 95]

The IMN_GUIDELINE message is sent when an IME is about to show an error message or other information. An application processes this message by calling the ImmGetGuideLine function to retrieve the error message or information from the IME. The application receives this notification message through the WM_IME_NOTIFY message.

Return Value

No return value.

Remarks

The IME window displays the error message or information string in an information window.

See Also

ImmGetGuideLine, WM_IME_NOTIFY


IMN_OPENCANDIDATE [New - Windows 95]
 IMN_OPENCANDIDATE  QuickInfo  Overview  Group

[New - Windows 95]

fCandidate = (DWORD) lParam;

The IMN_OPENCANDIDATE message is sent to the application when an IME is about to open the candidate window. An application should process this message if it displays candidates itself. The application can retrieve a list of candidates to display by using the ImmGetCandidateList function. The application receives this notification message through the WM_IME_NOTIFY message.

Parameters

fCandidates

Candidate lists flag. Each bit corresponds to a candidate list: bit 0 to the first list, bit 1 to the second, and so on. If a specified bit is 1, the corresponding candidate window is about to be opened.

Return Value

No return value.

Remarks

By default, the IME window creates a candidate window when it processes this message.

See Also

ImmGetCandidateList, WM_IME_NOTIFY


IMN_OPENSTATUSWINDOW(preliminary-Windows 95) [New - Windows 95]
 IMN_OPENSTATUSWINDOW  QuickInfo  Overview  Group

[New - Windows 95]

The IMN_OPENSTATUSWINDOW message is sent when an IME is about to create the status window. An application processes this message to display the status window for the IME by itself. The application receives this notification message through the WM_IME_NOTIFY message.

Return Value

No return value.

Remarks

The IME window creates a status window when it processes this message and sets the strings to display in the window into the input context. Applications can get information about the status window by using the ImmGetConversionStatus function.

See Also

ImmGetConversionStatus, WM_IME_NOTIFY


IMN_SETCANDIDATEPOS [New - Windows 95]
 IMN_SETCANDIDATEPOS  QuickInfo  Overview  Group

[New - Windows 95]

fCandidates = (DWORD) lParam;

The IMN_SETCANDIDATEPOS message is sent when the IME is about to move the candidate window. An application should process this message if it displays the candidate window itself. The application receives this notification message through the WM_IME_NOTIFY message.

Parameters

fCandidates

Candidate lists flag. Each bit corresponds to a candidate list: bit 0 to the first list, bit 1 to the second, and so on. If a specified bit is 1, the corresponding candidate window is about to be moved.

Return Value

No return value.

Remarks

The IME window moves the candidate window when it processes this message.

See Also

WM_IME_NOTIFY


IMN_SETCOMPOSITIONFONT(preliminary-Windows 95) [New - Windows 95]
 IMN_SETCOMPOSITIONFONT  QuickInfo  Overview  Group

[New - Windows 95]

The IMN_SETCOMPOSITIONFONT message is sent when the font of the input context is updated. The application receives this notification message through the WM_IME_NOTIFY message.

Return Value

No return value.

Remarks

The application can get information about the font by using the ImmGetCompositionFont function. The IME window subsequently uses the font to draw the composition string.

See Also

ImmGetCompositionFont, WM_IME_NOTIFY


IMN_SETCOMPOSITIONWINDOW(preliminary-Windows 95) [New - Windows 95]
 IMN_SETCOMPOSITIONWINDOW  QuickInfo  Overview  Group

[New - Windows 95]

The IMN_SETCOMPOSITIONWINDOW message is sent when the style or position of the composition window is updated. The application receives this notification message through the WM_IME_NOTIFY message.

Return Value

No return value.

Remarks

The application can get information about the composition form by using the IMC_GETCOMPOSITIONWINDOW message.

See Also

IMC_GETCOMPOSITIONWINDOW, WM_IME_NOTIFY


IMN_SETCONVERSIONMODE(preliminary-Windows 95) [New - Windows 95]
 IMN_SETCONVERSIONMODE  QuickInfo  Overview  Group

[New - Windows 95]

The IMN_SETCONVERSIONMODE message is sent when the conversion mode of the input context is updated. The application receives this notification message through the WM_IME_NOTIFY message.

Return Value

No return value.

Remarks

The application can get information about the conversion mode by using the ImmGetConversionStatus function.

See Also

ImmGetConversionStatus, WM_IME_NOTIFY


IMN_SETOPENSTATUS(preliminary-Windows 95) [New - Windows 95]
 IMN_SETOPENSTATUS  QuickInfo  Overview  Group

[New - Windows 95]

The IMN_SETOPENSTATUS message is sent when the open status of the input context is updated. The application receives this notification message through the WM_IME_NOTIFY message.

Return Value

No return value.

Remarks

The application can get information about the open status by using the ImmGetOpenStatus function.

See Also

ImmGetOpenStatus, WM_IME_NOTIFY


IMN_SETSENTENCEMODE(preliminary-Windows 95) [New - Windows 95]
 IMN_SETSENTENCEMODE  QuickInfo  Overview  Group

[New - Windows 95]

The IMN_SETSENTENCEMODE message is sent when the sentence mode of the input context is updated. The application receives this notification message through the WM_IME_NOTIFY message.

Return Value

No return value.

Remarks

The application can get information about the sentence mode by using the ImmGetConversionStatus function.

See Also

ImmGetConversionStatus, WM_IME_NOTIFY


IMN_SETSTATUSWINDOWPOS(preliminary-Windows 95) [New - Windows 95]
 IMN_SETSTATUSWINDOWPOS  QuickInfo  Overview  Group

[New - Windows 95]

The IMN_SETSTATUSWINDOWPOS message is sent when the status window position in the input context is updated. The application receives this notification message through the WM_IME_NOTIFY message.

Return Value

No return value.

Remarks

The application can get information about the status window position by using the IMC_GETSTATUSWINDOWPOS message.

See Also

IMC_GETSTATUSWINDOWPOS, WM_IME_NOTIFY


LB_ADDFILE
 LB_ADDFILE  QuickInfo  Overview  Group

LB_ADDFILE

wParam = 0;                               // not used; must be zero

lParam = (LPARAM) (LPCTSTR) lpszFilename; // name of file to add

An application sends an LB_ADDFILE message to add the specified filename to a list box that contains a directory listing.

Parameters

lpszFilename

Value of lParam. Points to the name of the file to add.

Return Value

The return value is the zero-based index of the file that was added, or LB_ERR if an error occurs.

Remarks

The list box to which lpszFilename is added must have been filled by the DlgDirList function.

See Also

DlgDirList, LB_ADDSTRING


LB_ADDSTRING
 LB_ADDSTRING  QuickInfo  Overview  Group

LB_ADDSTRING

wParam = 0;                         // not used; must be zero

lParam = (LPARAM) (LPCTSTR) lpsz;   // address of string to add

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.

Parameters

lpsz

Value of lParam. Points to the null-terminated string that is to be added.

If you create the list box with an owner-drawn style but without the LBS_HASSTRINGS style, the value of the lpsz parameter is stored as item data instead of the string it would otherwise point to. You can send the LB_GETITEMDATA and LB_SETITEMDATA messages to retrieve or modify the item data.

Return Value

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.

See Also

LB_DELETESTRING, LB_INSERTSTRING, LB_SELECTSTRING, WM_COMPAREITEM


LB_DELETESTRING
 LB_DELETESTRING  QuickInfo  Overview  Group

LB_DELETESTRING

wParam = (WPARAM) index;    // index of string to delete

lParam = 0;                 // not used; must be zero

An application sends an LB_DELETESTRING message to delete a string in a list box.

Parameters

index

Value of wParam. Specifies the zero-based index of the string to be deleted.

Windows 95 only: 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 listbox is limited only by available memory.

Return Value

The return value is a count of the strings remaining in the list. The return value is LB_ERR if the index parameter specifies an index greater than the number of items in the list.

Remarks

If an application creates the list box with an owner-drawn style but without the LBS_HASSTRINGS style, the system sends a WM_DELETEITEM message to the owner of the list box so the application can free any additional data associated with the item.

See Also

LB_ADDSTRING, LB_INSERTSTRING, WM_DELETEITEM


LB_DIR
 LB_DIR  QuickInfo  Overview  Group

LB_DIR

wParam = (WPARAM) (UINT) uAttrs;          // file attributes

lParam = (LPARAM) (LPCTSTR) lpszFileSpec; // filename address

An application sends an LB_DIR message to add a list of filenames to a list box.

Parameters

uAttrs

Value of wParam. Specifies the attributes of the files to be added to the list box. This parameter can be a combination of the following values:

Value	Description
DDL_ARCHIVE	Includes archived files.
DDL_DIRECTORY	Includes subdirectories. Subdirectory names are enclosed in square brackets ([ ]).
DDL_DRIVES	Includes drives. Drives are listed in the form [-x-], where x is the drive letter.
DDL_EXCLUSIVE	Includes only files with the specified attributes. By default, read-write files are listed even if DDL_READWRITE is not specified.
DDL_HIDDEN	Includes hidden files.
DDL_READONLY	Includes read-only files.
DDL_READWRITE	Includes read-write files with no additional attributes.
DDL_SYSTEM	Includes system files.
lpszFileSpec

Value of lParam. Points to the null-terminated string that specifies the filename to add to the list. If the filename contains wildcards (for example, *.*), all files that match the wildcards and have the attributes specified by the uAttrs parameter are added to the list.

Return Value

The return value is the zero-based index of the last filename added to the list. If an error occurs, the return value is LB_ERR. If there is insufficient space to store the new strings, the return value is LB_ERRSPACE.

See Also

DlgDirList


LB_FINDSTRING
 LB_FINDSTRING  QuickInfo  Overview  Group

LB_FINDSTRING

wParam = (WPARAM) indexStart;           // item before start of search

lParam = (LPARAM) (LPCTSTR) lpszFind;   // search string address

An application sends an LB_FINDSTRING message to find the first string in a list box that contains the specified prefix.

Parameters

indexStart

Value of wParam. Specifies the zero-based index of the item before the first item to be searched. When the search reaches the bottom of the list box, it continues from the top of the list box back to the item specified by the indexStart parameter. If indexStart is −1, the entire list box is searched from the beginning.

Windows 95 only: 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 listbox is limited only by available memory.

lpszFind

Value of lParam. Points to the null-terminated string that contains the prefix to search for. The search is case independent, so this string can contain any combination of uppercase and lowercase letters.

Return Value

The return value is the index of the matching item, or LB_ERR if the search was unsuccessful.

Remarks

If you create the list box with an owner-drawn style but without the LBS_HASSTRINGS style, this message returns the index of the item with a long value (supplied as the lParam parameter of the LB_ADDSTRING or LB_INSERTSTRING message) that matches the value supplied as the lpszFind parameter.

See Also

LB_ADDSTRING, LB_INSERTSTRING, LB_SELECTSTRING


LB_FINDSTRINGEXACT
 LB_FINDSTRINGEXACT  QuickInfo  Overview  Group

LB_FINDSTRINGEXACT

wParam = (WPARAM) indexStart;      // item before start of search

lParam = (LPARAM)(LPCSTR)lpszFind; // address of search string

An application sends a LB_FINDSTRINGEXACT message to find the first list box string that matches the string specified in the lpszFind parameter.

Parameters

indexStart

Value of wParam. Specifies the zero-based index of the item before the first item to be searched. When the search reaches the bottom of the list box, it continues from the top of the list box back to the item specified by the indexStart parameter. If indexStart is  − 1, the entire list box is searched from the beginning.

Windows 95 only: 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 listbox is limited only by available memory.

lpszFind

Value of lParam. Points to the null-terminated string to search for. This string can contain a complete filename, including the extension. The search is not case sensitive, so this string can contain any combination of uppercase and lowercase letters.

Return Value

The return value is the zero-based index of the matching item, or LB_ERR if the search was unsuccessful.

Remarks

If an application creates the list box with an owner-drawn style but without the LBS_HASSTRINGS style, the action taken by LB_FINDSTRINGEXACT depends on whether the LBS_SORT style is used. If LBS_SORT is used, the system sends WM_COMPAREITEM messages to the list box owner to determine which item matches the specified string. Otherwise, LB_FINDSTRINGEXACT attempts to match the 32-bit value against the value of the lpszFind parameter.

See Also

LB_FINDSTRING, LB_SELECTSTRING, WM_COMPAREITEM


LB_GETANCHORINDEX
 LB_GETANCHORINDEX  QuickInfo  Overview  Group

LB_GETANCHORINDEX

wParam = 0; // not used; must be zero

lParam = 0; // not used; must be zero

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.

Parameters

This message has no parameters.

Return Value

The return value is the index of the anchor item.

See Also

LB_SETANCHORINDEX


LB_GETCARETINDEX
 LB_GETCARETINDEX  QuickInfo  Overview  Group

LB_GETCARETINDEX

wParam = 0; // not used; must be zero

lParam = 0; // not used; must be zero

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.

Parameters

This message has no parameters.

Return Value

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.

See Also

LB_SETCARETINDEX


LB_GETCOUNT
 LB_GETCOUNT  QuickInfo  Overview  Group

LB_GETCOUNT

wParam = 0; // not used; must be zero

lParam = 0; // not used; must be zero

An application sends an LB_GETCOUNT message to retrieve the number of items in a list box.

Parameters

This message has no parameters.

Return Value

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).

See Also

LB_SETCOUNT


LB_GETCURSEL
 LB_GETCURSEL  QuickInfo  Overview  Group

LB_GETCURSEL

wParam = 0;     // not used; must be zero

lParam = 0;     // not used; must be zero

Send an LB_GETCURSEL message to retrieve the index of the currently selected item, if any, in a single-selection list box. For a multiple selection list box, the message retrieves the index of the first selected item (the base item), if any.

Parameters

This message has no parameters.

Return Value

The return value is the zero-based index of the currently selected item or of the base item in a multiple selection.

If there is no selection, the return value is LB_ERR.

Remarks

Use the LB_GETCARETINDEX message to retrieve the index of the item that has the focus rectangle in a multiple-selection list box.

See Also

LB_GETCARETINDEX, LB_SETCURSEL


LB_GETHORIZONTALEXTENT
 LB_GETHORIZONTALEXTENT  QuickInfo  Overview  Group

LB_GETHORIZONTALEXTENT

wParam = 0; // not used; must be zero

lParam = 0; // not used; must be zero

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.

Parameters

This message has no parameters.

Return Value

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.

See Also

LB_SETHORIZONTALEXTENT


LB_GETITEMDATA
 LB_GETITEMDATA  QuickInfo  Overview  Group

LB_GETITEMDATA

wParam = (WPARAM) index;    // item index

lParam = 0;                 // not used; must be zero

An application sends an LB_GETITEMDATA message to retrieve the application-defined 32-bit value associated with the specified list box item.

Parameters

index

Value of wParam. Specifies the index of the item.

Windows 95 only: 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 listbox is limited only by available memory.

Return Value

The return value is the 32-bit value associated with the item, or LB_ERR if an error occurs. If the item is in an owner-drawn list box and was created without the LBS_HASSTRINGS style, this 32-bit value was in the lParam parameter of the LB_ADDSTRING or LB_INSERTSTRING message that added the item to the list box. Otherwise, it is the value in the lParam of an LB_SETITEMDATA message.

See Also

LB_ADDSTRING, LB_INSERTSTRING, LB_SETITEMDATA


LB_GETITEMHEIGHT
 LB_GETITEMHEIGHT  QuickInfo  Overview  Group

LB_GETITEMHEIGHT

wParam = (WPARAM) index;    // item index

lParam = 0;                 // not used; must be zero

An application sends an LB_GETITEMHEIGHT message to retrieve the height of items in a list box.

Parameters

index

Value of wParam. Specifies the zero-based index of the list box item. This index is used only if the list box has the LBS_OWNERDRAWVARIABLE style; otherwise, it must be  zero.

Windows 95 only: 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 listbox is limited only by available memory.

Return Value

The return value is the height, in pixels, of each item in the list box. The return value is the height of the item specified by the index parameter if the list box has the LBS_OWNERDRAWVARIABLE style. The return value is LB_ERR if an error occurs.

See Also

LB_SETITEMHEIGHT


LB_GETITEMRECT
 LB_GETITEMRECT  QuickInfo  Overview  Group

LB_GETITEMRECT

wParam = (WPARAM) index;            // item index

lParam = (LPARAM) (RECT FAR*) lprc; // address of rectangle

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.

Parameters

index

Value of wParam. Specifies the zero-based index of the item.

Windows 95 only: 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 listbox is limited only by available memory.

lprc

Value of lParam. Points to a RECT structure that will receive the client coordinates for the item in the list box.

Return Value

If an error occurs, the return value is LB_ERR.

See Also

RECT


LB_GETLOCALE
 LB_GETLOCALE  QuickInfo  Overview  Group

LB_GETLOCALE

wParam = 0; // not used; must be zero

lParam = 0; // not used; must be zero

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.

Parameters

This message has no parameters.

Return Value

The return value is a 32-bit value that specifies the current locale of the list box. The high-order word contains the country code and the low-order word contains the language identifier.

Remarks

The language identifier consists of a sublanguage identifier and a primary language identifier. Use the PRIMARYLANGID macro to extract the primary language identifier from the low-order word of the return value, and the SUBLANGID macro to extract the sublanguage identifier.

See Also

LB_ADDSTRING, LB_SETLOCALE, PRIMARYLANGID, SUBLANGID


LB_GETSEL
 LB_GETSEL  QuickInfo  Overview  Group

LB_GETSEL

wParam = (WPARAM) index;    // item index

lParam = 0;                 // not used; must be zero

An application sends an LB_GETSEL message to retrieve the selection state of an item.

Parameters

index

Value of wParam. Specifies the zero-based index of the item.

Windows 95 only: 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 listbox is limited only by available memory.

Return Value

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.

See Also

LB_SETSEL


LB_GETSELCOUNT
 LB_GETSELCOUNT  QuickInfo  Overview  Group

LB_GETSELCOUNT

wParam = 0; // not used; must be zero

lParam = 0; // not used; must be zero

An application sends an LB_GETSELCOUNT message to retrieve the total number of selected items in a multiple-selection list box.

Parameters

This message has no parameters.

Return Value

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.

See Also

LB_SETSEL


LB_GETSELITEMS
 LB_GETSELITEMS  QuickInfo  Overview  Group

LB_GETSELITEMS

wParam = (WPARAM) cItems;           // maximum number of items

lParam = (LPARAM) (LPINT) lpnItems; // address of buffer

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.

Parameters

cItems

Value of wParam. Specifies the maximum number of selected items whose item numbers are to be placed in the buffer.

Windows 95 only: 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 listbox is limited only by available memory.

lpnItems

Value of lParam. Points to a buffer large enough for the number of integers specified by the cItems parameter.

Return Value

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.

See Also

LB_GETSELCOUNT


LB_GETTEXT
 LB_GETTEXT  QuickInfo  Overview  Group

LB_GETTEXT

wParam = (WPARAM) index;                // item index

lParam = (LPARAM) (LPCTSTR) lpszBuffer; // address of buffer

An application sends an LB_GETTEXT message to retrieve a string from a list box.

Parameters

index

Value of wParam. Specifies the zero-based index of the string to retrieve.

Windows 95 only: 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 listbox is limited only by available memory.

lpszBuffer

Value of lParam. Points to the buffer that will receive the string. The buffer must have sufficient space for the string and a terminating null character. An LB_GETTEXTLEN message can be sent before the LB_GETTEXT message to retrieve the length, in characters, of the string.

Return Value

The return value is the length of the string, in characters, excluding the terminating null character. If index does not specify a valid index, the return value is LB_ERR.

Remarks

If you create the list box with an owner-drawn style but without the LBS_HASSTRINGS style, the buffer pointed to by the lpszBuffer parameter will receive the 32-bit value associated with the item (the item data).

See Also

LB_GETTEXTLEN


LB_GETTEXTLEN
 LB_GETTEXTLEN  QuickInfo  Overview  Group

LB_GETTEXTLEN

wParam = (WPARAM) index;    // item index

lParam = 0;                 // not used; must be zero

An application sends an LB_GETTEXTLEN message to retrieve the length of a string in a list box.

Parameters

index

Value of wParam. Specifies the zero-based index of the string.

Windows 95 only: 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 listbox is limited only by available memory.

Return Value

The return value is the length of the string, in characters, excluding the terminating null character. Under certain conditions, this value may actually be greater than the length of the text. For more information, see the following Remarks section.

If the index parameter does not specify a valid index, the return value is LB_ERR.

Remarks

Under certain conditions, the return value is larger than the actual length of the text. This occurs with certain mixtures of ANSI and Unicode, and is due to the operating system allowing for the possible existence of double-byte character set (DBCS) characters within the text. The return value, however, will always be at least as large as the actual length of the text; you can thus always use it to guide buffer allocation. This behavior can occur when an application uses both ANSI functions and common dialogs, which use Unicode.

To obtain the exact length of the text, use the WM_GETTEXT, LB_GETTEXT, or CB_GETLBTEXT messages, or the GetWindowText function.

See Also

CB_GETLBTEXT, GetWindowText, LB_GETTEXT, WM_GETTEXT


LB_GETTOPINDEX
 LB_GETTOPINDEX  QuickInfo  Overview  Group

LB_GETTOPINDEX

wParam = 0; // not used; must be zero

lParam = 0; // not used; must be zero

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.

Parameters

This message has no parameters.

Return Value

The return value is the index of the first visible item in the list box.

See Also

LB_SETTOPINDEX


LB_INITSTORAGE [New - Windows 95]
 LB_INITSTORAGE  QuickInfo

[New - Windows 95]

LB_INITSTORAGE

wParam = (WPARAM) (int) cItems;  // number of items to add

lParam = (LPARAM) (DWORD) cb;   // amount of memory to allocate, in bytes

Allocates memory for storing list box items. An application sends this message before adding a large number of items to a list box.

Parameters

cItems

Specifies the number of items to add.

Windows 95 only: 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 listbox is limited only by available memory.

cb

Specifies the amount of memory, in bytes, to allocate for item strings.

Return Value

The return value is the maximum number of items that the memory object can store before another memory reallocation is needed, if successful. It is LB_ERRSPACE if not enough memory is available.

Remarks

This message helps speed up the initialization of list boxes that have a large number of items (more than 100). It preallocates the specified amount of memory so that subsequent LB_ADDSTRING, LB_INSERTSTRING, LB_DIR, and LB_ADDFILE messages take the shortest possible time. You can use estimates for the cItems and cb parameters. If you overestimate, some extra memory is allocated; if you underestimate, the normal allocation is used for items that exceed the preallocated amount.

See Also

LB_ADDFILE, LB_ADDSTRING, LB_DIR, LB_INSERTSTRING


LB_INSERTSTRING
 LB_INSERTSTRING  QuickInfo  Overview  Group

LB_INSERTSTRING

wParam = (WPARAM) index;          // item index

lParam = (LPARAM) (LPCTSTR) lpsz; // address of string to insert

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.

Parameters

index

Value of wParam. Specifies the zero-based index of the position at which to insert the string. If this parameter is −1, the string is added to the end of the list.

Windows 95 only: 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 listbox is limited only by available memory.

lpsz

Value of lParam. Points to the null-terminated string to be inserted.

If you create the list box with an owner-drawn style but without the LBS_HASSTRINGS style, the value of the lpsz parameter is stored as item data instead of the string it would otherwise point to. You can send the LB_GETITEMDATA and LB_SETITEMDATA messages to retrieve or modify the item data.

Return Value

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.

See Also

LB_ADDSTRING, LB_SELECTSTRING


LB_ITEMFROMPOINT [New - Windows 95]
 LB_ITEMFROMPOINT  QuickInfo

[New - Windows 95]

LB_ITEMFROMPOINT

wParam = 0;                                // not used, must be zero

lParam = (LPARAM) MAKELPARAM(xPos, yPos);  // coordinates of point

An application sends this message to retrieve the zero-based index of the item nearest the specified point in a list box.

Parameters

xPos

Value of the low-order word of lParam. Specifies the x-coordinate of a point, relative to the upper-left corner of the client area of the list box.

yPos

Value of the high-order word of lParam. Specifies the y-coordinate of a point, relative to the upper-left corner of the client area of the list box.

Return Value

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.


LB_RESETCONTENT
 LB_RESETCONTENT  QuickInfo  Overview  Group

LB_RESETCONTENT

wParam = 0; // not used; must be zero

lParam = 0; // not used; must be zero

An application sends an LB_RESETCONTENT to remove all items from a list box.

Parameters

This message has no parameters.

Return Value

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.

See Also

WM_DELETEITEM


LB_SELECTSTRING
 LB_SELECTSTRING  QuickInfo  Overview  Group

LB_SELECTSTRING

wParam = (WPARAM) indexStart;        // item before start of search

lParam = (LPARAM)(LPCTSTR)lpszFind;  // address of search string

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.

Parameters

indexStart

Value of wParam. Specifies the zero-based index of the item before the first item to be searched. When the search reaches the bottom of the list box, it continues from the top of the list box back to the item specified by the indexStart parameter. If indexStart is −1, the entire list box is searched from the beginning.

Windows 95 only: 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 listbox is limited only by available memory.

lpszFind

Value of lParam. Points to the null-terminated string that contains the prefix to search for. The search is case independent, so this string can contain any combination of uppercase and lowercase letters.

Return Value

If the search is successful, the return value is the index of the selected item. If the search is unsuccessful, the return value is LB_ERR and the current selection is not changed.

Remarks

The list box is scrolled, if necessary, to bring the selected item into view.

Do not use this message with a list box that has the LBS_MULTIPLESEL style.

An item is selected only if its initial characters from the starting point match the characters in the string specified by the lpszFind parameter.

If you create the list box with an owner-drawn style but without the LBS_HASSTRINGS style, this message returns the index of the item whose long value (supplied as the lParam parameter of the LB_ADDSTRING or LB_INSERTSTRING message) matches the value supplied as the lParam parameter of LB_SELECTSTRING.

See Also

LB_ADDSTRING, LB_FINDSTRING, LB_INSERTSTRING


LB_SELITEMRANGE
 LB_SELITEMRANGE  QuickInfo  Overview  Group

LB_SELITEMRANGE

wParam = (WPARAM) (BOOL) fSelect;   // selection flag

lParam = MAKELPARAM(wFirst, wLast); // first and last items

An application sends an LB_SELITEMRANGE message to select one or more consecutive items in a multiple-selection list box.

Parameters

fSelect

Value of wParam. Specifies how to set the selection. If the fSelect parameter is TRUE, the string is selected and highlighted; if fSelect is zero, the highlight is removed and the string is no longer selected.

wFirst

Value of the low-order word of lParam. Specifies the zero-based index of the first item to select.

wLast

Value of the high-order word of lParam. Specifies the zero-based index of the last item to select.

Return Value

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.

See Also

LB_SELITEMRANGEEX, LB_SETSEL


LB_SELITEMRANGEEX
 LB_SELITEMRANGEEX  QuickInfo  Overview  Group

LB_SELITEMRANGEEX

wParam = (WPARAM) wFirst; // first item

lParam = (LPARAM) wLast); // last item

An application sends an LB_SELITEMRANGEEX message to select one or more consecutive items in a multiple-selection list box.

Parameters

wFirst

Value of wParam. Specifies the zero-based index of the first item to select.

Windows 95 only: 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 listbox is limited only by available memory.

wLast

Value of lParam. Specifies the zero-based index of the last item to select.

Return Value

If an error occurs, the return value is LB_ERR.

Remarks

If the wFirst parameter is less than the wLast parameter, the specified range of items is selected. If wFirst is greater than wLast, the selection is removed from the specified range of items.

Use this message only with multiple-selection list boxes.

This message can select a range only within the first 65,536 items.

See Also

LB_SELITEMRANGE, LB_SETSEL


LB_SETANCHORINDEX
 LB_SETANCHORINDEX  QuickInfo  Overview  Group

LB_SETANCHORINDEX

wParam = (WPARAM) index; // index to set as anchor

lParam = 0;              // not used; must be zero

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.

Parameters

index

Value of wParam. Specifies the index of the new anchor item.

Windows 95 only: 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 listbox is limited only by available memory.

Return Value

If the message succeeds, the return value is zero.

If the message fails, the return value is LB_ERR.

See Also

LB_GETANCHORINDEX


LB_SETCARETINDEX
 LB_SETCARETINDEX  QuickInfo  Overview  Group

LB_SETCARETINDEX

wParam = (WPARAM) index;            // item index

lParam = MAKELPARAM(fScroll, 0);    // flag for scrolling item

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.

Parameters

index

Value of wParam. Specifies the zero-based index of the list box item that is to receive the focus rectangle.

Windows 95 only: 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 listbox is limited only by available memory.

fScroll

Value of lParam. If this value is FALSE, the item is scrolled until it is fully visible; if it is TRUE, the item is scrolled until it is at least partially visible.

Return Value

If an error occurs, the return value is LB_ERR.

See Also

LB_GETCARETINDEX


LB_SETCOLUMNWIDTH
 LB_SETCOLUMNWIDTH  QuickInfo  Overview  Group

LB_SETCOLUMNWIDTH

wParam = (WPARAM) cxColumn; // column width in pixels

lParam = 0;                 // not used; must be zero

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.

Parameters

cxColumn

Value of wParam. Specifies the width, in pixels, of all columns.

Return Value

This message does not return a value.

See Also

LB_SETTABSTOPS


LB_SETCOUNT
 LB_SETCOUNT  QuickInfo  Overview  Group

LB_SETCOUNT

wParam = (WPARAM) (int) cItems; // count of list box items

lParam = 0;                     // not used; must be zero

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.

Parameters

cItems

Value of wParam. Specifies the new count of items in the list box.

Windows 95 only: 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 listbox is limited only by available memory.

Return Value

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.

See Also

LB_GETCOUNT


LB_SETCURSEL
 LB_SETCURSEL  QuickInfo  Overview  Group

LB_SETCURSEL

wParam = (WPARAM) index;    // item index

lParam = 0;                 // not used; must be zero

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.

Parameters

index

Value of wParam. Specifies the zero-based index of the string that is selected. If the index parameter is -1, the list box is set to have no selection.

Windows 95 only: 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 listbox is limited only by available memory.

Return Value

If an error occurs, the return value is LB_ERR. If the index parameter is −1, the return value is LB_ERR even though no error occurred.

Remarks

Use this message only with single-selection list boxes. You cannot use it to set or remove a selection in a multiple-selection list box.

See Also

LB_GETCURSEL


LB_SETHORIZONTALEXTENT
 LB_SETHORIZONTALEXTENT  QuickInfo  Overview  Group

LB_SETHORIZONTALEXTENT

wParam = (WPARAM) cxExtent; // horizontal scroll width

lParam = 0;                 // not used; must be zero

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.

Parameters

cxExtent

Value of wParam. Specifies the number of pixels by which the list box can be scrolled.

Windows 95 only: The wParam parameter is limited to 16-bit values.

Return Value

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.

See Also

LB_GETHORIZONTALEXTENT


LB_SETITEMDATA
 LB_SETITEMDATA  QuickInfo  Overview  Group

LB_SETITEMDATA

wParam = (WPARAM) index;    // item index

lParam = (LPARAM) dwData;   // value to associate with item

An application sends an LB_SETITEMDATA message to set a 32-bit value associated with the specified item in a list box.

Parameters

index

Value of wParam. Specifies the zero-based index of the item.

Windows 95 only: 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 listbox is limited only by available memory.

dwData

Value of lParam. Specifies the 32-bit value to be associated with the item.

Return Value

If an error occurs, the return value is LB_ERR.

Remarks

If the item is in an owner-drawn list box created without the LBS_HASSTRINGS style, this message replaces the 32-bit value contained in the lParam parameter of the LB_ADDSTRING or LB_INSERTSTRING message that added the item to the list box.

See Also

LB_ADDSTRING, LB_GETITEMDATA, LB_INSERTSTRING


LB_SETITEMHEIGHT
 LB_SETITEMHEIGHT  QuickInfo  Overview  Group

LB_SETITEMHEIGHT

wParam = (WPARAM) index;        // item index

lParam = MAKELPARAM(cyItem, 0); // item height

An application sends an LB_SETITEMHEIGHT message to set the height, in pixels, of items in a list box. If the list box has the LBS_OWNERDRAWVARIABLE style, this message sets the height of the item specified by the index parameter. Otherwise, this message sets the height of all items in the list box.

Parameters

index

Value of wParam. Specifies the zero-based index of the item in the list box. Use this parameter only if the list box has the LBS_OWNERDRAWVARIABLE style; otherwise, set it to zero.

Windows 95 only: 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 listbox is limited only by available memory.

cyItem

Value of lParam. Specifies the height, in pixels, of the item.

Return Value

If the index or height is invalid, the return value is LB_ERR.

See Also

LB_GETITEMHEIGHT


LB_SETLOCALE
 LB_SETLOCALE  QuickInfo  Overview  Group

LB_SETLOCALE

wParam = (WPARAM) wLocaleID;    // locale identifier

lParam = 0;                     // not used; must be zero

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.

Parameters

wLocaleID

Value of wParam. Specifies the locale identifier that the list box will use for sorting when adding text.

Return Value

The return value is the previous locale identifier. If the wLocaleID parameter specifies a locale that is not installed on the system, the return value is LB_ERR and the current list box locale is not changed.

Remarks

Use the MAKELCID macro to construct a locale identifier.

See Also

LB_ADDSTRING, LB_GETLOCALE, MAKELCID


LB_SETSEL
 LB_SETSEL  QuickInfo  Overview  Group

LB_SETSEL

wParam = (WPARAM) (BOOL) fSelect;   // selection flag

lParam = (LPARAM) (UINT) index;     // item index

An application sends an LB_SETSEL message to select a string in a multiple-selection list box.

Parameters

fSelect

Value of wParam. Specifies how to set the selection. If the fSelect parameter is TRUE, the string is selected and highlighted; if fSelect is FALSE, the highlight is removed and the string is no longer selected.

index

Value of lParam. Specifies the zero-based index of the string to set. If index is −1, the selection is added to or removed from all strings, depending on the value of fSelect.

Return Value

If an error occurs, the return value is LB_ERR.

Remarks

Use this message only with multiple-selection list boxes.

See Also

LB_GETSEL, LB_SELITEMRANGE


LB_SETTABSTOPS
 LB_SETTABSTOPS  QuickInfo  Overview  Group

LB_SETTABSTOPS

wParam = (WPARAM) cTabs;            // number of tab stops

lParam = (LPARAM) (LPINT) lpnTabs;  // address of tab-stop array

An application sends an LB_SETTABSTOPS message to set the tab-stop positions in a list box.

Parameters

cTabs

Value of wParam. Specifies the number of tab stops in the list box.

lpnTabs

Value of lParam. Points to the first member of an array of integers containing the tab stops, in dialog box units. The tab stops must be sorted in ascending order; backward tabs are not allowed.

Return Value

If all the specified tabs are set, the return value is TRUE; otherwise, it is FALSE.

Remarks

To respond to the LB_SETTABSTOPS message, the list box must have been created with the LBS_USETABSTOPS style.

If cTabs parameter is 0 and lpnTabs is NULL, the default tab stop is two dialog box units. If cTabs is 1, the list box will have tab stops separated by the distance specified by lpnTabs.

If lpnTabs points to more than a single value, a tab stop will be set for each value in lpnTabs, up to the number specified by cTabs.

A dialog box unit is a horizontal or vertical distance. One horizontal dialog box unit is equal to 0.25 of the current dialog box base-width unit. These units are computed based on the height and width of the current system font. The GetDialogBaseUnits function returns the current dialog box base units, in pixels.

See Also

GetDialogBaseUnits


LB_SETTOPINDEX
 LB_SETTOPINDEX  QuickInfo  Overview  Group

LB_SETTOPINDEX

wParam = (WPARAM) index;    // item index

lParam = 0;                 // not used; must be zero

An application sends an LB_SETTOPINDEX message to ensure that a particular item in a list box is visible.

Parameters

index

Value of wParam. Specifies the zero-based index of the item in the list box.

Windows 95 only: 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 listbox is limited only by available memory.

Return Value

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.

See Also

LB_GETTOPINDEX


LBN_DBLCLK
 LBN_DBLCLK  QuickInfo  Overview  Group

LBN_DBLCLK

idListBox = (int) LOWORD(wParam);  // identifier of list box

hwndListBox = (HWND) lParam;       // handle of list box

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.

Remarks

Only a list box that has the LBS_NOTIFY style will send this notification message.

See Also

LBN_SELCHANGE, WM_COMMAND


LBN_ERRSPACE
 LBN_ERRSPACE  QuickInfo  Overview  Group

LBN_ERRSPACE

idListBox = (int) LOWORD(wParam);  // identifier of list box

hwndListBox = (HWND) lParam;       // handle of list box

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.

See Also

WM_COMMAND


LBN_KILLFOCUS
 LBN_KILLFOCUS  QuickInfo  Overview  Group

LBN_KILLFOCUS

idListBox = (int) LOWORD(wParam);  // identifier of list box

hwndListBox = (HWND) lParam;       // handle of list box

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.

See Also

LBN_SETFOCUS, WM_COMMAND


LBN_SELCANCEL
 LBN_SELCANCEL  QuickInfo  Overview  Group

LBN_SELCANCEL

idListBox = (int) LOWORD(wParam);  // identifier of list box

hwndListBox = (HWND) lParam;       // handle of list box

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.

Remarks

This notification message applies only to list boxes of the LBS_NOTIFY style.

See Also

LB_SETCURSEL, LBN_DBLCLK, LBN_SELCHANGE, WM_COMMAND


LBN_SELCHANGE
 LBN_SELCHANGE  QuickInfo  Overview  Group

LBN_SELCHANGE

idListBox = (int) LOWORD(wParam);  // identifier of list box

hwndListBox = (HWND) lParam;       // handle of list box

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.

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.

See Also

LB_SETCURSEL, LBN_DBLCLK, LBN_SELCANCEL, WM_COMMAND


LBN_SETFOCUS
 LBN_SETFOCUS  QuickInfo  Overview  Group

LBN_SETFOCUS

idListBox = (int) LOWORD(wParam);  // identifier of list box

hwndListBox = (HWND) lParam;       // handle of list box

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.

See Also

LBN_KILLFOCUS, WM_COMMAND


LBSELCHSTRING
 LBSELCHSTRING  Overview  Group

msg = uLBSelChMsg;
wParam = (UINT) idListBox;
lParam = MAKELONG (iItem, iType);

Sent to the hook function of a Open or Save As dialog box after the user changed the selection in the Filename list box. This message has been superseded by the CDN_SELCHANGE and CDN_TYPECHANGE messages.

Parameters

uLBSelChMsg

Message identifier for the Selection Change message. This value is the same as returned by the RegisterWindowMessage function for the LBSELCHSTRING string.

idListBox

Identifier of the list box in which the selection changed.

iItem

Item number of the selected string in the list box.

iType

Type of selection change. Can be one of these values:

CD_LBSELCHANGE	The item identified by iItem is the only item selected in a single-selection list box.
CD_LBSELSUB	The item identified by iItem is no longer selected in a multiple-selection list box.
CD_LBSELADD	The item identified by iItem is one of the items selected in a multiple-selection list box.
CD_LBSELNOITEMS	No items exist in a multiple-selection list box.
Return Value

No return value.

See Also

CDN_SELCHANGE, CDN_TYPECHANGE, RegisterWindowMessage


LVM_ARRANGE [New - Windows NT]
 LVM_ARRANGE  QuickInfo  Overview  Group

[New - Windows NT]

LVM_ARRANGE

wParam = (WPARAM) (int) code;

lParam = 0;

// Corresponding macro

BOOL ListView_Arrange(HWND hwnd, UINT code);

The LVM_ARRANGE message arranges items in icon view. You can send this message explicitly or by using the ListView_Arrange macro.

Parameters

hwnd

Handle to the list view control.

code

Specifies the alignment, which can be one of the following values:

Value	Meaning
LVA_ALIGNLEFT	Aligns items along the left edge of the window.
LVA_ALIGNTOP	Aligns items along the top edge of the window.
LVA_DEFAULT	Aligns items according to the list view control's current alignment styles (the default value).
LVA_SNAPTOGRID	Snaps all icons to the nearest grid position.
Return Value

Returns TRUE if successful or FALSE otherwise.


LVM_CREATEDRAGIMAGE [New - Windows NT]
 LVM_CREATEDRAGIMAGE  QuickInfo  Overview  Group

[New - Windows NT]

LVM_CREATEDRAGIMAGE

wParam = (WPARAM) (int) iItem;

lParam = (LPARAM) (LPPOINT) lpptUpLeft;

// Corresponding macro

HIMAGELIST ListView_CreateDragImage(HWND hwnd, int iItem,

LPPOINT lpptUpLeft);

The LVM_CREATEDRAGIMAGE message creates a drag image list for the specified item. You can send this message explicitly or by using the ListView_CreateDragImage macro.

Parameters

hwnd

Handle to the list view control.

iItem

Index of the item.

lpptUpLeft

Pointer to a POINT structure that receives the initial location of the upper-left corner of the image, in view coordinates.

Return Value

Returns the handle to the drag image list if successful or NULL otherwise.

See Also

POINT


LVM_DELETEALLITEMS [New - Windows NT]
 LVM_DELETEALLITEMS  QuickInfo  Overview  Group

[New - Windows NT]

LVM_DELETEALLITEMS

wParam = 0;

lParam = 0;

// Corresponding macro

BOOL ListView_DeleteAllItems(HWND hwnd);

The LVM_DELETEALLITEMS message removes all items from a list view control. You can send this message explicitly or by using the ListView_DeleteAllItems macro.

Parameters

hwnd

Handle to the list view control.

Return Value

Returns TRUE if successful or FALSE otherwise.


LVM_DELETECOLUMN [New - Windows NT]
 LVM_DELETECOLUMN  QuickInfo  Overview  Group

[New - Windows NT]

LVM_DELETECOLUMN

wParam = (WPARAM) (int) iCol;

lParam = 0;

// Corresponding macro

BOOL ListView_DeleteColumn(HWND hwnd, int iCol);

The LVM_DELETECOLUMN message removes a column from a list view control. You can send this message explicitly or by using the ListView_DeleteColumn macro.

Parameters

hwnd

Handle to the list view control.

iCol

Index of the column to delete.

Return Value

Returns TRUE if successful or FALSE otherwise.


LVM_DELETEITEM [New - Windows NT]
 LVM_DELETEITEM  QuickInfo  Overview  Group

[New - Windows NT]

LVM_DELETEITEM

wParam = (WPARAM) (int) iItem;

lParam = 0;

// Corresponding macro

BOOL ListView_DeleteItem(HWND hwnd, int iItem);

The LVM_DELETEITEM message removes an item from a list view control. You can send this message explicitly or by using the ListView_DeleteItem macro.

Parameters

hwnd

Handle to the list view control.

iItem

Index of the list view item to delete.

Return Value

Returns TRUE if successful or FALSE otherwise.


LVM_EDITLABEL [New - Windows NT]
 LVM_EDITLABEL  QuickInfo  Overview  Group

[New - Windows NT]

LVM_EDITLABEL

wParam = (WPARAM) (int) iItem;

lParam = 0;

// Corresponding macro

HWND ListView_EditLabel(HWND hwnd, int iItem);

The LVM_EDITLABEL message begins in-place editing of the specified list view item's text. The message implicitly selects and focuses the specified item. You can send this message explicitly or by using the ListView_EditLabel macro.

Parameters

hwnd

Handle to the list view control.

iItem

Index of the list view item. To cancel editing, set iItem to −1.

Return Value

Returns the handle of the edit control that is used to edit the item text if successful or NULL otherwise.

Remarks

When the user completes or cancels editing, the edit control is destroyed and the handle is no longer valid. You can safely subclass the edit control, but you should not destroy it.

The control must have the focus before you send this message to the control. Focus can be set using the SetFocus function.

See Also

WM_CANCELMODE, SetFocus


LVM_ENSUREVISIBLE [New - Windows NT]
 LVM_ENSUREVISIBLE  QuickInfo  Overview  Group

[New - Windows NT]

LVM_ENSUREVISIBLE

wParam = (WPARAM) (int) iItem;

lParam = (LPARAM) (BOOL) fPartialOk;

// Corresponding macro

BOOL ListView_EnsureVisible(HWND hwnd, int i, BOOL fPartialOK);

The LVM_ENSUREVISIBLE message ensures that a list view item is entirely or at least partially visible, scrolling the list view control if necessary. You can send this message explicitly or by using the ListView_EnsureVisible macro.

Parameters

hwnd

Handle to the list view control.

i

Index of the list view item.

fPartialOK

Value specifying whether the item must be entirely visible. If this parameter is TRUE, no scrolling occurs if the item is at least partially visible.

Return Value

Returns TRUE if successful or FALSE otherwise.


LVM_FINDITEM [New - Windows NT]
 LVM_FINDITEM  QuickInfo  Overview  Group

[New - Windows NT]

LVM_FINDITEM

wParam = (WPARAM) (int) iStart;

lParam = (LPARAM) (const LV_FINDINFO FAR *) plvfi;

// Corresponding macro

int ListView_FindItem(HWND hwnd, int iStart,

    const LV_FINDINFO FAR* plvfi);

The LVM_FINDITEM message searches for a list view item with the specified characteristics. You can send this message explicitly or by using the ListView_FindItem macro.

Parameters

hwnd

Handle to the list view control.

iStart

Index of the item to begin the search with or −1 to start from the beginning. The specified item is itself excluded from the search.

plvfi

Pointer to an LV_FINDINFO structure that contains information about what to search for.

Return Value

Returns the index of the item if successful or −1 otherwise.

See Also

LV_FINDINFO


LVM_GETBKCOLOR [New - Windows NT]
 LVM_GETBKCOLOR  QuickInfo  Overview  Group

[New - Windows NT]

LVM_GETBKCOLOR

wParam = 0;

lParam = 0;

// Corresponding macro

COLORREF ListView_GetBkColor(HWND hwnd);

The LVM_GETBKCOLOR message retrieves the background color of a list view control. You can send this message explicitly or by using the ListView_GetBkColor macro.

Parameters

hwnd

Handle to the list view control.

Return Value

Returns the background color of the list view control.


LVM_GETCALLBACKMASK [New - Windows NT]
 LVM_GETCALLBACKMASK  QuickInfo  Overview  Group

[New - Windows NT]

LVM_GETCALLBACKMASK

wParam = 0;

lParam = 0;

// Corresponding macro

UINT ListView_GetCallbackMask(HWND hwnd);

The LVM_GETCALLBACKMASK message retrieves the callback mask for a list view control. You can send this message explicitly or by using the ListView_GetCallbackMask macro.

Parameters

hwnd

Handle to the list view control.

Return Value

Returns the callback mask.


LVM_GETCOLUMN [New - Windows NT]
 LVM_GETCOLUMN  QuickInfo  Overview  Group

[New - Windows NT]

LVM_GETCOLUMN

wParam = (WPARAM) (int) iCol;

lParam = (LPARAM) (LV_COLUMN FAR *) pcol;

// Corresponding macro

BOOL ListView_GetColumn(HWND hwnd, int iCol,

LV_COLUMN FAR* pcol);

The LVM_GETCOLUMN message retrieves the attributes of a list view control's column. You can send this message explicitly or by using the ListView_GetColumn macro.

Parameters

hwnd

Handle to the list view control.

iCol

Index of the column.

pcol

Pointer to an LV_COLUMN structure that specifies the information to retrieve and receives information about the column. The mask member specifies which column attributes to retrieve.

If the mask member specifies the LVCF_TEXT value, the pszText member must contain the pointer to the buffer that receives the item text and the cchTextMax member must specify the size of the buffer.

Return Value

Returns TRUE if successful or FALSE otherwise.

See Also

LV_COLUMN


LVM_GETCOLUMNWIDTH [New - Windows NT]
 LVM_GETCOLUMNWIDTH  QuickInfo  Overview  Group

[New - Windows NT]

LVM_GETCOLUMNWIDTH

wParam = (WPARAM) (int) iCol;

lParam = 0;

// Corresponding macro

int ListView_GetColumnWidth(HWND hwnd, int iCol);

The LVM_GETCOLUMNWIDTH message retrieves the width of a column in report or list view. You can send this message explicitly or by using the ListView_GetColumnWidth macro.

Parameters

hwnd

Handle to the list view control.

iCol

Index of the column. This parameter is ignored in list view.

Return Value

Returns the column width if successful or zero otherwise.


LVM_GETCOUNTPERPAGE [New - Windows NT]
 LVM_GETCOUNTPERPAGE  QuickInfo  Overview  Group

[New - Windows NT]

LVM_GETCOUNTPERPAGE

wParam = 0;

lParam = 0;

// Corresponding macro

int ListView_GetCountPerPage(HWND hwnd);

The LVM_GETCOUNTPERPAGE message calculates the number of items that can fit vertically in the visible area of a list view control when in list or report view. Only fully-visible items are counted. You can send this message explicitly, or by using the ListView_GetCountPerPage macro.

Parameters

hwnd

Handle to the list view control.

Return Value

Returns the number of fully-visible items if successful. If the current view is icon or small icon view, the return value is the total number of items in the list view control.


LVM_GETEDITCONTROL [New - Windows NT]
 LVM_GETEDITCONTROL  QuickInfo  Overview  Group

[New - Windows NT]

LVM_GETEDITCONTROL

wParam = 0;

lParam = 0;

// Corresponding macro

HWND ListView_GetEditControl(HWND hwnd);

The LVM_GETEDITCONTROL message retrieves the handle to the edit control being used to edit a list view item's text. You can send this message explicitly or by using the ListView_GetEditControl macro.

Parameters

hwnd

Handle to the list view control.

Return Value

Returns the handle to the edit control if successful or NULL otherwise.

Remarks

If no label is being edited, the return value is NULL. The edit control is not created until after the LVN_BEGINLABELEDIT notification message is sent.

When the user completes or cancels editing, the edit control is destroyed and the handle is no longer valid. You can safely subclass the edit control, but you should not destroy it. To cancel editing, you can send the list view control a WM_CANCELMODE message.

The list view item being edited is the currently focused item — that is, the item in the focused state. To find an item based on its state, use the LVM_GETNEXTITEM message.

See Also

LVN_BEGINLABELEDIT, LVM_GETNEXTITEM, WM_CANCELMODE


LVM_GETIMAGELIST [New - Windows NT]
 LVM_GETIMAGELIST  QuickInfo  Overview  Group

[New - Windows NT]

LVM_GETIMAGELIST

wParam = (WPARAM) (int) iImageList;

lParam = 0;

// Corresponding macro

HIMAGELIST ListView_GetImageList(HWND hwnd, int iImageList);

The LVM_GETIMAGELIST message retrieves the handle to an image list used for drawing list view items. You can send this message explicitly or by using the ListView_GetImageList macro.

Parameters

hwnd

Handle to the list view control.

iImageList

Image list to retrieve. This parameter can be one of the following values:

Value	Meaning
LVSIL_NORMAL	Image list with large icons
LVSIL_SMALL	Image list with small icons
LVSIL_STATE	Image list with state images
Return Value

Returns the handle of the specified image list if successful or NULL otherwise.


LVM_GETISEARCHSTRING
 LVM_GETISEARCHSTRING  Overview  Group

LVM_GETISEARCHSTRING

wParam = 0;

lParam = (LPARAM) (LPSTR) lpsz;

// Corresponding macro

BOOL ListView_GetISearchString(HWND hwnd, LPSTR lpsz);

The LVM_GETISEARCHSTRING message retrieves the incremental search string of a list-view control. You can send this message explicitly or by using the ListView_GetISearchString macro.

Parameters

hwnd

Handle to the list view control.

lpsz

Pointer to a buffer that receives the incremental search string.

Return Value

Returns the number of characters in the incremental search string, or zero if the list-view control is not in incremental search mode.

Remarks

The incremental search string is the character sequence that the user types while the list view has the input focus. Each time the user types a character, the system appends the character to the search string and then searches for a matching item. If the system finds a match, it selects the item and, if necessary, scrolls it into view.

A timeout period is associated with each character that the user types. If the timeout period elapses before the user types another character, the incremental search string is reset.


LVM_GETITEM [New - Windows NT]
 LVM_GETITEM  QuickInfo  Overview  Group

[New - Windows NT]

LVM_GETITEM

wParam = 0;

lParam = (LPARAM) (LV_ITEM FAR*) pitem;

// Corresponding macro

BOOL ListView_GetItem(HWND hwnd, LV_ITEM FAR* pitem);

The LVM_GETITEM message retrieves some or all of a list view item's attributes. You can send this message explicitly or by using the ListView_GetItem macro.

Parameters

hwnd

Handle to the list view control.

pitem

Pointer to an LV_ITEM structure that specifies the information to retrieve and receives information about the list view item.

When the message is sent, the iItem and iSubItem members identify the item or subitem to retrieve information about and the mask member specifies which attributes to retrieve. For a list of possible values, see the description of the LV_ITEM structure.

If the mask member specifies the LVIF_TEXT value, the pszText member must contain the pointer to the buffer that receives the item text and the cchTextMax member must specify the size of the buffer.

If the mask member specifies the LVIF_STATE value, the stateMask member specifies which item states are to be returned.

Return Value

Returns TRUE if successful or FALSE otherwise.

See Also

LV_ITEM


LVM_GETITEMCOUNT [New - Windows NT]
 LVM_GETITEMCOUNT  QuickInfo  Overview  Group

[New - Windows NT]

LVM_GETITEMCOUNT

wParam = 0;

lParam = 0;

// Corresponding macro

int ListView_GetItemCount(HWND hwnd);

The LVM_GETITEMCOUNT message retrieves the number of items in a list view control. You can send this message explicitly or by using the ListView_GetItemCount macro.

Parameters

hwnd

Handle to the list view control.

Return Value

Returns the number of items.


LVM_GETITEMPOSITION [New - Windows NT]
 LVM_GETITEMPOSITION  QuickInfo  Overview  Group

[New - Windows NT]

LVM_GETITEMPOSITION

wParam = (WPARAM) (int) i;

lParam = (LPARAM) (POINT FAR *) ppt;

// Corresponding macro

BOOL ListView_GetItemPosition(HWND hwnd, int i, POINT FAR* ppt);

The LVM_GETITEMPOSITION message retrieves the position of a list view item. You can send this message explicitly or by using the ListView_GetItemPosition macro.

Parameters

hwnd

Handle to the list view control.

i

Index of the list view item.

ppt

Pointer to a POINT structure that receives the position of the item's upper-left corner, in view coordinates.

Return Value

Returns TRUE if successful or FALSE otherwise.

See Also

POINT


LVM_GETITEMRECT [New - Windows NT]
 LVM_GETITEMRECT  QuickInfo  Overview  Group

[New - Windows NT]

LVM_GETITEMRECT

wParam = (WPARAM) (int) i;

lParam = (LPARAM) (LPRECT) prc;

// Corresponding macro

BOOL ListView_GetItemRect(HWND hwnd, int i, RECT FAR* prc, int code);

The LVM_GETITEMRECT message retrieves the bounding rectangle for all or part of an item in the current view. You can send this message explicitly or by using the ListView_GetItemRect macro.

Parameters

hwnd

Handle to the list view control.

i

Index of the list view item.

prc

Pointer to a RECT structure that receives the bounding rectangle. When the message is sent, the left member of this structure contains the value of the code parameter.

code

Portion of the list view item for which to retrieve the bounding rectangle. This parameter can be one of the following values:

Value	Meaning
LVIR_BOUNDS	Returns the bounding rectangle of the entire item, including the icon and label.
LVIR_ICON	Returns the bounding rectangle of the icon or small icon.
LVIR_LABEL	Returns the bounding rectangle of the item text.
LVIR_SELECTBOUNDS	Returns the union of the LVIR_ICON and LVIR_LABEL rectangles, but excludes columns in details view.
Return Value

Returns TRUE if successful or FALSE otherwise.

Remarks

This parameter is specified by the left member of the RECT structure pointed to by prc.

See Also

RECT


LVM_GETITEMSPACING [New - Windows NT]
 LVM_GETITEMSPACING  QuickInfo  Overview  Group

[New - Windows NT]

LVM_GETITEMSPACING

wParam = (WPARAM) (BOOL) fSmall;

lParam = 0;

// Corresponding macro

DWORD ListView_GetItemSpacing(HWND hwnd, BOOL fSmall);

The LVM_GETITEMSPACING message determines the spacing between items in a list view control. You can send this message explicitly or by using the ListView_GetItemSpacing macro.

Parameters

hwnd

Handle to the list view control.

fSmall

View to retrieve the item spacing for. This parameter is TRUE for small icon view, or FALSE for icon view.

Return Value

Returns the amount of spacing between items.


LVM_GETITEMSTATE [New - Windows NT]
 LVM_GETITEMSTATE  QuickInfo  Overview  Group

[New - Windows NT]

LVM_GETITEMSTATE

wParam = (WPARAM) (int) i;

lParam = (LPARAM) (UINT) mask;

// Corresponding macro

UINT WINAPI ListView_GetItemState(HWND hwnd, int i, UINT mask);

The LVM_GETITEMSTATE message retrieves the state of a list view item. You can send this message explicitly or by using the ListView_GetItemState macro.

Parameters

hwnd

Handle to the list view control.

i

Index of the list view item.

mask

Mask that specifies which of the item's state flags to return.

Return Value

Returns the item's state flags.


LVM_GETITEMTEXT [New - Windows NT]
 LVM_GETITEMTEXT  QuickInfo  Overview  Group

[New - Windows NT]

LVM_GETITEMTEXT

wParam = (WPARAM) (int) iItem;

lParam = (LPARAM) (LV_ITEM FAR *) pitem;

// Corresponding macro

void WINAPI ListView_GetItemText(HWND hwnd, int iItem,

     int iSubItem, LPSTR pszText, int cchTextMax);

The LVM_GETITEMTEXT message retrieves the text of a list view item or subitem.

Parameters

The message has the following parameters:

hwnd

Handle to the list view control.

iItem

Index of the list view item.

pitem

Pointer to an LV_ITEM structure. The iSubItem member specifies the index of a subitem, or it can be zero to get the item label. The pszText member points to a buffer that receives the text, and the cchTextMax member specifies the size of the buffer.

The macro has the following parameters:

hwnd

Handle to the list view control.

iItem

Index of the list view item.

iSubItem

Index of the subitem, or zero to retrieve the item label.

pszText

Pointer to the buffer that receives the item or subitem text.

cchTextMax

Size of the buffer, in bytes.

Return Value

If you send this message explicitly, it returns the length of the retrieved string.

If you can send this message implicitly by using the ListView_GetItemText macro, there is no return value.

See Also

LV_ITEM


LVM_GETNEXTITEM [New - Windows NT]
 LVM_GETNEXTITEM  QuickInfo  Overview  Group

[New - Windows NT]

LVM_GETNEXTITEM

wParam = (WPARAM) (int) iStart;

lParam = MAKELPARAM((UINT) flags, 0);

// Corresponding macro

int ListView_GetNextItem(HWND hwnd, int iStart, UINT flags);

The LVM_GETNEXTITEM message searches for a list view item that has the specified properties and bears the specified relationship to a specified item. You can send this message explicitly or by using the ListView_GetNextItem macro.

Parameters

hwnd

Handle to the list view control.

iStart

Index of the item to begin the searching with, or −1 to find the first item that matches the specified flags. The specified item itself is excluded from the search.

flags

Geometric relation of the requested item to the specified item and, if specified, the state of the requested item.

The geometric relation can be one of the following values:

Value	Meaning
LVNI_ABOVE	Searches for an item that is above the specified item.
LVNI_ALL	Searches for a subsequent item by index (the default value).
LVNI_BELOW	Searches for an item that is below the specified item.
LVNI_TOLEFT	Searches for an item to the left of the specified item.
LVNI_TORIGHT	Searches for an item to the right of the specified item.
The state can be zero, or it can be one or more of the following values:

Value	Meaning
LVNI_CUT	The item has the LVIS_CUT state flag set.
LVNI_DROPHILITED	The item has the LVIS_DROPHILITED state flag set.
LVNI_FOCUSED	The item has the LVIS_FOCUSED state flag set.
LVNI_SELECTED	The item has the LVIS_SELECTED state flag set.
If an item does not have all of the specified state flags set, the search continues with the next item.

Return Value

Returns the index of the next item if successful or −1 otherwise.


LVM_GETORIGIN [New - Windows NT]
 LVM_GETORIGIN  QuickInfo  Overview  Group

[New - Windows NT]

LVM_GETORIGIN

wParam = 0;

lParam = (LPARAM) (LPPOINT) lpptOrg;

// Corresponding macro

BOOL ListView_GetOrigin(HWND hwnd, LPPOINT lpptOrg);

The LVM_GETORIGIN message retrieves the current view origin for a list view control. You can send this message explicitly or by using the ListView_GetOrigin macro.

Parameters

hwnd

Handle to the list view control.

lpptOrg

Pointer to a POINT structure that receives the view origin.

Return Value

Returns TRUE if successful or FALSE if the current view is list or report view.

See Also

POINT


LVM_GETSELECTEDCOUNT [New - Windows NT]
 LVM_GETSELECTEDCOUNT  QuickInfo  Overview  Group

[New - Windows NT]

LVM_GETSELECTEDCOUNT

wParam = 0;

lParam = 0;

// Corresponding macro

UINT ListView_GetSelectedCount(HWND hwnd);

The LVM_GETSELECTEDCOUNT message determines the number of selected items in a list view control. You can send this message explicitly or by using the ListView_GetSelectedCount macro.

Parameters

hwnd

Handle to the list view control.

Return Value

Returns the number of selected items.


LVM_GETSTRINGWIDTH [New - Windows NT]
 LVM_GETSTRINGWIDTH  QuickInfo  Overview  Group

[New - Windows NT]

LVM_GETSTRINGWIDTH

wParam = 0;

lParam = (LPARAM) (LPCSTR) psz;

// Corresponding macro

int ListView_GetStringWidth(HWND hwnd, LPCSTR psz);

The LVM_GETSTRINGWIDTH message determines the width of a specified string, using the specified list view control's current font. You can send this message explicitly or by using the ListView_GetStringWidth macro.

Parameters

hwnd

Handle to the list view control.

psz

Pointer to a null-terminated string.

Return Value

Returns the string width if successful or zero otherwise.


LVM_GETTEXTBKCOLOR [New - Windows NT]
 LVM_GETTEXTBKCOLOR  QuickInfo  Overview  Group

[New - Windows NT]

LVM_GETTEXTBKCOLOR

wParam = 0;

lParam = 0;

// Corresponding macro

COLORREF ListView_GetTextBkColor(HWND hwnd);

The LVM_GETTEXTBKCOLOR message retrieves the text background color of a list view control. You can send this message explicitly or by using the ListView_GetTextBkColor macro.

Parameters

hwnd

Handle to the list view control.

Return Value

Returns the background color of the text.


LVM_GETTEXTCOLOR [New - Windows NT]
 LVM_GETTEXTCOLOR  QuickInfo  Overview  Group

[New - Windows NT]

LVM_GETTEXTCOLOR

wParam = 0;

lParam = 0;

// Corresponding macro

COLORREF ListView_GetTextColor(HWND hwnd);

The LVM_GETTEXTCOLOR message retrieves the text color of a list view control. You can send this message explicitly or by using the ListView_GetTextColor macro.

Parameters

hwnd

Handle to the list view control.

Return Value

Returns the text color.


LVM_GETTOPINDEX [New - Windows NT]
 LVM_GETTOPINDEX  QuickInfo  Overview  Group

[New - Windows NT]

LVM_GETTOPINDEX

wParam = 0;

lParam = 0;

// Corresponding macro

int ListView_GetTopIndex(HWND hwnd);

The LVM_GETTOPINDEX message retrieves the index of the topmost visible item when in list or report view. You can send this message explicitly or by using the ListView_GetTopIndex macro.

Parameters

hwnd

Handle to the list view control.

Return Value

Returns the index of the item if successful or zero if the list view control is in icon or small icon view.


LVM_GETVIEWRECT [New - Windows NT]
 LVM_GETVIEWRECT  QuickInfo  Overview  Group

[New - Windows NT]

LVM_GETVIEWRECT

wParam = 0;

lParam = (LPARAM) (RECT FAR *) prc;

// Corresponding macro

BOOL ListView_GetViewRect(HWND hwnd, RECT FAR* prc);

The LVM_GETVIEWRECT message retrieves the bounding rectangle of all items in the list view control. The list view must be in icon or small icon view. You can send this message explicitly or by using the ListView_GetViewRect macro.

Parameters

hwnd

Handle to the list view control.

prc

Pointer to a RECT structure that receives the bounding rectangle. All coordinates are relative to the visible area of the list view control.

Return Value

Returns TRUE if successful or FALSE otherwise.

See Also

RECT


LVM_HITTEST [New - Windows NT]
 LVM_HITTEST  QuickInfo  Overview  Group

[New - Windows NT]

LVM_HITTEST

wParam = 0;

lParam = (LPARAM) (LV_HITTESTINFO FAR *) pinfo;

// Corresponding macro

int ListView_HitTest(HWND hwnd, LV_HITTESTINFO FAR* pinfo);

The LVM_HITTEST message determines which list view item, if any, is at a specified position. You can send this message explicitly or by using the ListView_HitTest macro.

Parameters

hwnd

Handle to the list view control.

pinfo

Pointer to an LV_HITTESTINFO structure that contains the position to hit test and receives information about the results of the hit test.

Return Value

Returns the index of the item at the specified position, if any, or −1 otherwise.

See Also

LV_HITTESTINFO


LVM_INSERTCOLUMN [New - Windows NT]
 LVM_INSERTCOLUMN  QuickInfo  Overview  Group

[New - Windows NT]

LVM_INSERTCOLUMN

wParam = (WPARAM) (int) iCol;

lParam = (LPARAM) (const LV_COLUMN FAR *) pcol;

// Corresponding macro

int ListView_InsertColumn(HWND hwnd, int iCol,

    const LV_COLUMN FAR* pcol);

The LVM_INSERTCOLUMN message inserts a new column in a list view control. You can send this message explicitly or by using the ListView_InsertColumn macro.

Parameters

hwnd

Handle to the list view control.

iCol

Index of the new column.

pcol

Pointer to an LV_COLUMN structure that contains the attributes of the new column.

Return Value

Returns the index of the new column if successful or −1 otherwise.

See Also

LV_COLUMN


LVM_INSERTITEM [New - Windows NT]
 LVM_INSERTITEM  QuickInfo  Overview  Group

[New - Windows NT]

LVM_INSERTITEM

wParam = 0;

lParam = (LPARAM) (const LV_ITEM FAR *) pitem;

// Corresponding macro

int ListView_InsertItem(HWND hwnd, const LV_ITEM FAR* pitem);

The LVM_INSERTITEM message inserts a new item in a list view control. You can send this message explicitly or by using the ListView_InsertItem macro.

Parameters

hwnd

Handle to the list view control.

pitem

Pointer to an LV_ITEM structure that specifies the attributes of the list view item. The iItem member specifies the index of the new item. The iSubItem member must be zero; the macro cannot be used to insert subitems.

Return Value

Returns the index of the new item if successful or −1 otherwise.

See Also

LV_ITEM


LVM_REDRAWITEMS [New - Windows NT]
 LVM_REDRAWITEMS  QuickInfo  Overview  Group

[New - Windows NT]

LVM_REDRAWITEMS

wParam = (int) iFirst;  // index of first item to redraw

lParam = (int) iLast;  // index of last item to redraw

// Corresponding macro

BOOL ListView_RedrawItems(HWND hwnd, int iFirst, int iLast);

The LVM_REDRAWITEMS message forces a list view control to redraw a range of items. You can send this message explicitly or by using the ListView_RedrawItems macro.

Parameters

hwnd

Handle to the list view control.

iFirst

Index of the first item to redraw.

iLast

Index of the last item to redraw.

Return Value

Returns TRUE if successful or FALSE otherwise.

Remarks

The specified items are not actually redrawn until the list view window receives a WM_PAINT message to repaint. To repaint immediately, call the UpdateWindow function after using this macro.

See Also

UpdateWindow, WM_PAINT


LVM_SCROLL [New - Windows NT]
 LVM_SCROLL  QuickInfo  Overview  Group

[New - Windows NT]

LVM_SCROLL

wParam = (int) dx;  // amount of horizontal scrolling, in pixels or columns

lParam = (int) dy;   // amount of vertical scrolling, in pixels

// Corresponding macro

BOOL ListView_Scroll(HWND hwnd, int dx, int dy);

The LVM_SCROLL message scrolls the content of a list view control. You can send this message explicitly or by using the ListView_Scroll macro.

Parameters

hwnd

Handle to the list view control.

dx

Integer value that specifies the amount of horizontal scrolling.

If the view type of the list view control is icon view, small icon view, or report view, this value specifies the number of pixels to scroll. If the view type of the list view control is list view, this value specifies the number of columns to scroll.

dy

Integer value that specifies the amount of vertical scrolling.

If the view type of the list view control is icon view, small icon view, or list view, this value specifies the number of pixels to scroll. If the view type of the list view control is report view, this value specifies the number of lines to scroll.

Return Value

Returns TRUE if successful or FALSE otherwise.


LVM_SETBKCOLOR [New - Windows NT]
 LVM_SETBKCOLOR  QuickInfo  Overview  Group

[New - Windows NT]

LVM_SETBKCOLOR

wParam = 0;

lParam = (LPARAM) (COLORREF) clrBk;

// Corresponding macro

BOOL ListView_SetBkColor(HWND hwnd, COLORREF clrBk);

The LVM_SETBKCOLOR message sets the background color of a list view control. You can send this message explicitly or by using the ListView_SetBkColor macro.

Parameters

hwnd

Handle to the list view control.

clrBk

Background color to set or the CLR_NONE value for no background color. List view controls with background colors redraw themselves significantly faster than those without background colors.

Return Value

Returns TRUE if successful or FALSE otherwise.


LVM_SETCALLBACKMASK [New - Windows NT]
 LVM_SETCALLBACKMASK  QuickInfo  Overview  Group

[New - Windows NT]

LVM_SETCALLBACKMASK

wParam = (WPARAM) (UINT) mask;

lParam = 0;

// Corresponding macro

BOOL ListView_SetCallbackMask(HWND hwnd, UINT mask);

The LVM_SETCALLBACKMASK message sets the callback mask for a list view control. You can send this message explicitly or by using the ListView_SetCallbackMask macro.

Parameters

hwnd

Handle to the list view control.

mask

New value of the callback mask.

Return Value

Returns TRUE if successful or FALSE otherwise.


LVM_SETCOLUMN [New - Windows NT]
 LVM_SETCOLUMN  QuickInfo  Overview  Group

[New - Windows NT]

LVM_SETCOLUMN

wParam = (WPARAM) (int) iCol;

lParam = (LPARAM) (const LV_COLUMN FAR *) pcol;

// Corresponding macro

BOOL ListView_SetColumn(HWND hwnd, int iCol, LV_COLUMN FAR* pcol);

The LVM_SETCOLUMN message sets the attributes of a list view column. You can send this message explicitly or by using the ListView_SetColumn macro.

Parameters

hwnd

Handle to the list view control.

iCol

Index of the column.

pcol

Pointer to an LV_COLUMN structure that contains the new column attributes. The mask member specifies which column attributes to set.

If the mask member specifies the LVCF_TEXT value, the pszText member is the pointer to a null-terminated string and the cchTextMax member is ignored.

Return Value

Returns TRUE if successful or FALSE otherwise.

See Also

LV_COLUMN


LVM_SETCOLUMNWIDTH [New - Windows NT]
 LVM_SETCOLUMNWIDTH  QuickInfo  Overview  Group

[New - Windows NT]

LVM_SETCOLUMNWIDTH

wParam = (WPARAM) (int) iCol;

lParam = MAKELPARAM((int) cx, 0);

// Corresponding macro

BOOL ListView_SetColumnWidth(HWND hwnd, int iCol, int cx);

The LVM_SETCOLUMNWIDTH message changes the width of a column in report or list view. You can send this message explicitly or by using the ListView_SetColumnWidth macro.

Parameters

hwnd

Handle to the list view control.

iCol

Index of the column. In list view, the iCol parameter must be −1.

cx

New width of the column, in list view coordinates, or one of the following values:

Value	Meaning
LVSCW_AUTOSIZE	Automatically sizes the column.
LVSCW_AUTOSIZE_USEHEADER	Automatically sizes the column to fit the header text.


LVM_SETIMAGELIST [New - Windows NT]
 LVM_SETIMAGELIST  QuickInfo  Overview  Group

[New - Windows NT]

LVM_SETIMAGELIST

wParam = (WPARAM) (int) iImageList;

lParam = (LPARAM) (HIMAGELIST) himl;

// Corresponding macro

HIMAGELIST ListView_SetImageList(HWND hwnd, HIMAGELIST himl, int iImageList);

The LVM_SETIMAGELIST message assigns an image list to a list view control. You can send this message explicitly or by using the ListView_SetImageList macro.

Parameters

hwnd

Handle to the list view control.

himl

Handle to the image list to assign.

iImageList

Type of image list. This parameter can be one of the following values:

Value	Meaning
LVSIL_NORMAL	Image list with large icons
LVSIL_SMALL	Image list with small icons
LVSIL_STATE	Image list with state images
Return Value

Returns the handle of the image list previously associated with the control if successful; NULL otherwise.


LVM_SETITEM [New - Windows NT]
 LVM_SETITEM  QuickInfo  Overview  Group

[New - Windows NT]

LVM_SETITEM

wParam = 0;

lParam = (LPARAM) (const LV_ITEM FAR *) pitem;

// Corresponding macro

BOOL ListView_SetItem(HWND hwnd, const LV_ITEM FAR* pitem);

The LVM_SETITEM message sets some or all of a list view item's attributes. You can send this message explicitly or by using the ListView_SetItem macro.

Parameters

hwnd

Handle to the list view control.

pitem

Pointer to an LV_ITEM structure that contains the new item attributes. The iItem and iSubItem members identify the item or subitem, and the mask member specifies which attributes to set.

If the mask member specifies the LVIF_TEXT value, the pszText member is the pointer to a null-terminated string and the cchTextMax member is ignored.

If the mask member specifies the LVIF_STATE value, the stateMask member specifies which item states to change and the state member contains the values for those states.

Return Value

Returns TRUE if successful or FALSE otherwise.

See Also

LV_ITEM


LVM_SETITEMCOUNT [New - Windows NT]
 LVM_SETITEMCOUNT  QuickInfo  Overview  Group

[New - Windows NT]

LVM_SETITEMCOUNT

wParam = (WPARAM) (int) cItems;

lParam = 0;

// Corresponding macro

VOID ListView_SetItemCount(HWND hwnd, int cItems);

The LVM_SETITEMCOUNT message prepares a list view control for adding a large number of items. You can send this message explicitly or by using the ListView_SetItemCount macro.

Parameters

hwnd

Handle to the list view control.

cItems

Number of items that the list view control will ultimately contain.

Return Value

No return value.

Remarks

By sending the LVM_SETITEMCOUNT message before adding a large number of items, you enable a list view control to reallocate its internal data structures only once rather than every time you add an item.


LVM_SETITEMPOSITION [New - Windows NT]
 LVM_SETITEMPOSITION  QuickInfo  Overview  Group

[New - Windows NT]

LVM_SETITEMPOSITION

wParam = (LPARAM) (int) i;

lParam = MAKELPARAM((int) x, (int) y);

// Corresponding macro

BOOL ListView_SetItemPosition(HWND hwnd, int i, int x, int y);

The LVM_SETITEMPOSITION message moves an item to a specified position in a list view control, which must be in icon or small icon view. You can send this message explicitly or by using the ListView_SetItemPosition macro.

Parameters

hwnd

Handle to the list view control.

i

Index of the list view item.

x and y

New position of the item's upper-left corner, in view coordinates.

Return Value

Returns TRUE if successful or FALSE otherwise.

Remarks

If the list view control has the LVS_AUTOARRANGE style, the list view control is arranged after the position of the item is set.


LVM_SETITEMPOSITION32 [New - Windows NT]
 LVM_SETITEMPOSITION32  QuickInfo  Overview  Group

[New - Windows NT]

LVM_SETITEMPOSITION32

wParam = (WPARAM) (int) iItem;

lParam = (LPARAM) (LPPOINT) lpptNewPos;

// Corresponding macro

void ListView_SetItemPosition32(HWND hwnd, int iItem, int x, int y);

The LVM_SETITEMPOSITION32 message moves an item to a specified position in a list view control, which must be in icon or small icon view. This message differs from the LVM_SETITEMPOSITION message in that it uses 32-bit coordinates.

Parameters

The message has the following parameters:

iItem

Index of the list view item to set the position of.

lpptNewPos

Pointer to a POINT structure that contains the new position of the item, in list view coordinates.

The macro has the following parameters:

hwnd

Handle to the list view control.

iItem

Index of the list view item to set the position of.

x and y

New horizontal and vertical coordinates of the item.

Return Value

No return value.

If you send this message by using the ListView_SetItemPosition32 macro, it has no return value.

See Also

LVM_SETITEMPOSITION, POINT


LVM_SETITEMSTATE [New - Windows NT]
 LVM_SETITEMSTATE  QuickInfo  Overview  Group

[New - Windows NT]

LVM_SETITEMSTATE

wParam = (WPARAM) (int) i;

lParam = (LPARAM) (LV_ITEM FAR *) pitem;

// Corresponding macro

BOOL WINAPI ListView_SetItemState(HWND hwnd, int i,

     UINT state, UINT mask);

The LVM_SETITEMSTATE message changes the state of an item in a list view control.

Parameters

The message has the following parameters:

i

Index of the list view item.

pitem

Pointer to an LV_ITEM structure. The stateMask member specifies which state bits to change, and the state member contains the new values for those bits. The other members are ignored.

The macro has the following parameters:

hwnd

Handle to the list view control.

i

Index of the list view item.

state

New state bits for the item.

mask

Mask specifying which of the item's current state bits to change.

Return Value

If you send this message explicitly, it returns TRUE if successful or FALSE otherwise.

If you send this message implicitly by using the ListView_SetItemState macro, there is no return value.

See Also

LV_ITEM


LVM_SETITEMTEXT [New - Windows NT]
 LVM_SETITEMTEXT  QuickInfo  Overview  Group

[New - Windows NT]

LVM_SETITEMTEXT

wParam = (WPARAM) (int) i;

lParam = (LPARAM) (LV_ITEM FAR *) pitem;

// Corresponding macro

VOID WINAPI ListView_SetItemText(HWND hwnd, int i,

int iSubItem, LPCSTR pszText);

The LVM_SETITEMTEXT message changes the text of a list view item or subitem.

Parameters

The message has the following parameters:

i

Index of the list view item.

pitem

Pointer to an LV_ITEM structure. The iSubItem member is the index of the subitem, or it can be zero to set the item label. The pszText member is the pointer to a null-terminated string containing the new text; it can also be NULL.

The macro has the following parameters:

hwnd

Handle to the list view control.

i

Index of the list view item.

iSubItem

Index of the subitem or zero to set the item label.

pszText

Pointer to a null-terminated string that contains the new text. This parameter can be NULL.

Return Value

If you send this message explicitly, it returns TRUE if successful or FALSE otherwise.

If you send this message implicitly by using the ListView_SetItemText macro, there is no return value.

See Also

LV_ITEM


LVM_SETTEXTBKCOLOR [New - Windows NT]
 LVM_SETTEXTBKCOLOR  QuickInfo  Overview  Group

[New - Windows NT]

LVM_SETTEXTBKCOLOR

wParam = 0;

lParam = (LPARAM) (COLORREF) clrText;

// Corresponding macro

BOOL ListView_SetTextBkColor(HWND hwnd, COLORREF clrText);

The LVM_SETTEXTBKCOLOR message sets the background color of text in a list view control. You can send this message explicitly or by using the ListView_SetTextBkColor macro.

Parameters

hwnd

Handle to the list view control.

clrText

New text color.

Return Value

Returns TRUE if successful or FALSE otherwise.


LVM_SETTEXTCOLOR [New - Windows NT]
 LVM_SETTEXTCOLOR  QuickInfo  Overview  Group

[New - Windows NT]

LVM_SETTEXTCOLOR

wParam = 0;

lParam = (LPARAM) (COLORREF) clrText;

// Corresponding macro

BOOL ListView_SetTextColor(HWND hwnd, COLORREF clrText);

The LVM_SETTEXTCOLOR message sets the text color of a list view control. You can send this message explicitly or by using the ListView_SetTextColor macro.

Parameters

hwnd

Handle to the list view control.

clrText

New text color.

Return Value

Returns TRUE if successful or FALSE otherwise.


LVM_SORTITEMS [New - Windows NT]
 LVM_SORTITEMS  QuickInfo  Overview  Group

[New - Windows NT]

LVM_SORTITEMS

wParam = (WPARAM) (LPARAM) lParamSort;

lParam = (LPARAM) (PFNLVCOMPARE) pfnCompare;

// Corresponding macro

BOOL ListView_SortItems(HWND hwnd, PFNLVCOMPARE pfnCompare,

LPARAM lParamSort);

The LVM_SORTITEMS message sorts list view items using an application-defined comparison function. The index of each item changes to reflect the new sequence. You can send this message explicitly or by using the ListView_SortItems macro.

Parameters

hwnd

Handle to the list view control.

pfnCompare

Pointer to the application-defined comparison function. The comparison function is called during the sort operation each time the relative order of two list items needs to be compared. For more information, see the following.

lParamSort

Application-defined value that is passed to the comparison function.

Return Value

Returns TRUE if successful or FALSE otherwise.

Remarks

The comparison function has the following form:

int CALLBACK CompareFunc(LPARAM lParam1, LPARAM lParam2,

LPARAM lParamSort);

The comparison function must return a negative value if the first item should precede the second, a positive value if the first item should follow the second, or zero if the two items are equivalent.

The lParam1 and lParam2 parameters specify the item data for the two items being compared. The lParamSort parameter is the same value passed to the LVM_SORTITEMS message.


LVM_UPDATE [New - Windows NT]
 LVM_UPDATE  QuickInfo  Overview  Group

[New - Windows NT]

LVM_UPDATE

wParam = (WPARAM) iItem;

lParam = 0;

// Corresponding macro

BOOL ListView_Update(HWND hwnd, int iItem);

The LVM_UPDATE message updates a list view item. If the list view control has the LVS_AUTOARRANGE style, this macro causes the list view control to be arranged. You can send this message explicitly or by using the ListView_Update macro.

Parameters

hwnd

Handle to the list view control.

iItem

Index of the item to update.

Return Value

Returns TRUE if successful or FALSE otherwise.


LVN_BEGINDRAG [New - Windows NT]
 LVN_BEGINDRAG  QuickInfo  Overview  Group

[New - Windows NT]

LVN_BEGINDRAG

pnmv = (NM_LISTVIEW FAR *) lParam;

The LVN_BEGINDRAG notification message notifies a list view control's parent window that a drag-and-drop operation involving the left mouse button is being initiated. This notification message is sent in the form of a WM_NOTIFY message.

Parameters

pnmv

Pointer to an NM_LISTVIEW structure. The iItem member identifies the item being dragged, and the other members are zero.

Return Value

No return value.

See Also

NM_LISTVIEW, WM_NOTIFY


LVN_BEGINLABELEDIT [New - Windows NT]
 LVN_BEGINLABELEDIT  QuickInfo  Overview  Group

[New - Windows NT]

LVN_BEGINLABELEDIT

pdi = (LV_DISPINFO FAR *) lParam;

The LVN_BEGINLABELEDIT notification message notifies a list view control's parent window about the start of label editing for an item. This notification message is sent in the form of a WM_NOTIFY message.

Parameters

pdi

Pointer to an LV_DISPINFO structure that contains information about the item

Return Value

Returns FALSE to allow label editing or TRUE to prevent it.

See Also

LV_DISPINFO, WM_NOTIFY


LVN_BEGINRDRAG [New - Windows NT]
 LVN_BEGINRDRAG  QuickInfo  Overview  Group

[New - Windows NT]

LVN_BEGINRDRAG

pnmv = (NM_LISTVIEW FAR *) lParam;

The LVN_BEGINRDRAG notification message notifies a list view control's parent window that a drag-and-drop operation involving the right mouse button is being initiated. This notification message is sent in the form of a WM_NOTIFY message.

Parameters

pnmv

Pointer to an NM_LISTVIEW structure. The iItem member identifies the item being dragged, and the other members are zero.

Return Value

No return value.

See Also

NM_LISTVIEW, WM_NOTIFY


LVN_COLUMNCLICK [New - Windows NT]
 LVN_COLUMNCLICK  QuickInfo  Overview  Group

[New - Windows NT]

LVN_COLUMNCLICK

pnmv = (NM_LISTVIEW FAR *) lParam;

The LVN_COLUMNCLICK notification message notifies a list view control's parent window that a column was clicked. This notification message is sent in the form of a WM_NOTIFY message.

Parameters

pnmv

Pointer to an NM_LISTVIEW structure. The iItem member is  − 1, and the iSubItem member identifies the column. All other members are zero.

Return Value

No return value.

See Also

NM_LISTVIEW, WM_NOTIFY


LVN_DELETEALLITEMS [New - Windows NT]
 LVN_DELETEALLITEMS  QuickInfo  Overview  Group

[New - Windows NT]

LVN_DELETEALLITEMS

pnmv = (NM_LISTVIEW FAR *) lParam;

The LVN_DELETEALLITEMS notification message notifies a list view control's parent window that all items in the control were deleted. This notification message is sent in the form of a WM_NOTIFY message.

Parameters

pnmv

Pointer to an NM_LISTVIEW structure. The iItem member is  − 1, and the other members are zero.

Return Value

No return value.

See Also

NM_LISTVIEW, WM_NOTIFY


LVN_DELETEITEM [New - Windows NT]
 LVN_DELETEITEM  QuickInfo  Overview  Group

[New - Windows NT]

LVN_DELETEITEM

pnmv = (NM_LISTVIEW FAR *) lParam;

The LVN_DELETEITEM notification message notifies a list view control's parent window that an item was deleted. This notification message is sent in the form of a WM_NOTIFY message.

Parameters

pnmv

Pointer to an NM_LISTVIEW structure. The iItem member identifies the deleted item, and the other members are zero.

Return Value

No return value.

See Also

NM_LISTVIEW, WM_NOTIFY


LVN_ENDLABELEDIT [New - Windows NT]
 LVN_ENDLABELEDIT  QuickInfo  Overview  Group

[New - Windows NT]

LVN_ENDLABELEDIT

pdi = (LV_DISPINFO FAR *) lParam;

The LVN_ENDLABELEDIT notification message notifies a list view control's parent window about the end of label editing for an item. This notification message is sent in the form of a WM_NOTIFY message.

Parameters

pdi

Pointer to an LV_DISPINFO structure. The iItem member identifies the item being edited.

Windows 95: You can determine if editing is being canceled by checking the lpszText member; if it is NULL, the user is canceling editing.

Windows NT: If editing is being canceled, the iItem member of LV_DISPINFO may be -1.

Return Value

No return value.

Remarks

The pszText member of the LV_ITEM structure contained within the LV_DISPINFO structure pointed to by pdi contains a valid value when the LVN_ENDLABELEDIT message is sent, regardless of whether the LVIF_TEXT flag is set in the mask member of the LV_ITEM structure. Note that NULL is a valid value for pszText, indicating the cancellation of the label editing operation.

 When the user cancels the editing of an item in the listview (while in report mode, of course), the LVN_ENDLABELEDIT sets the lpszText member to NULL and the iItem member to the identifier for the item that was being edited.

See Also

LV_DISPINFO, LV_ITEM, WM_NOTIFY,


LVN_GETDISPINFO [New - Windows NT]
 LVN_GETDISPINFO  QuickInfo  Overview  Group

[New - Windows NT]

LVN_GETDISPINFO

pnmv = (LV_DISPINFO FAR *) lParam;

The LVN_GETDISPINFO notification message is sent to a list view control's parent window. It is a request for the parent window to provide information needed to display or sort a list view item. The LVN_GETDISPINFO notification message is sent in the form of a WM_NOTIFY message.

Parameters

pnmv

Pointer to an LV_DISPINFO structure that specifies the type of information required and that receives the information.

Return Value

No return value.

Remarks

If your message handler sets the LVIF_DI_SETITEM flag of the mask member of the LV_ITEM structure contained within the LV_DISPINFO structure pointed to by pnmv, the operating system stores the requested information, and will not ask for it again.

See Also

LV_DISPINFO, WM_NOTIFY


LVN_INSERTITEM [New - Windows NT]
 LVN_INSERTITEM  QuickInfo  Overview  Group

[New - Windows NT]

LVN_INSERTITEM

pnmv = (NM_LISTVIEW FAR *) lParam;

The LVN_INSERTITEM notification message notifies a list view control's parent window that a new item was inserted. This notification message is sent in the form of a WM_NOTIFY message.

Parameters

pnmv

Pointer to an NM_LISTVIEW structure. The iItem member identifies the new item, and the other members are zero.

Return Value

No return value.

See Also

NM_LISTVIEW, WM_NOTIFY


LVN_ITEMCHANGED [New - Windows NT]
 LVN_ITEMCHANGED  QuickInfo  Overview  Group

[New - Windows NT]

LVN_ITEMCHANGED

pnmv = (NM_LISTVIEW FAR *) lParam;

The LVN_ITEMCHANGED notification message notifies a list view control's parent window that an item has changed. This notification message is sent in the form of a WM_NOTIFY message.

Parameters

pnmv

Pointer to an NM_LISTVIEW structure that identifies the item and specifies which of its attributes have changed.

Return Value

No return value.

See Also

NM_LISTVIEW, WM_NOTIFY


LVN_ITEMCHANGING [New - Windows NT]
 LVN_ITEMCHANGING  QuickInfo  Overview  Group

[New - Windows NT]

LVN_ITEMCHANGING

pnmv = (NM_LISTVIEW FAR *) lParam;

The LVN_ITEMCHANGING notification message notifies a list view control's parent window that an item is changing. This notification message is sent in the form of a WM_NOTIFY message.

Parameters

pnmv

Pointer to an NM_LISTVIEW structure that identifies the item and specifies which of its attributes are changing.

Return Value

Returns TRUE to allow the change or FALSE to prevent the change.

See Also

NM_LISTVIEW, WM_NOTIFY


LVN_KEYDOWN [New - Windows NT]
 LVN_KEYDOWN  QuickInfo  Overview  Group

[New - Windows NT]

LVN_KEYDOWN

pnkd = (LV_KEYDOWN FAR *) lParam;

The LVN_KEYDOWN notification message notifies a list view control's parent window that a key has been pressed. This notification message is sent in the form of a WM_NOTIFY message.

Parameters

pnkd

Pointer to an LV_KEYDOWN structure.

Return Value

No return value.

See Also

LV_KEYDOWN, WM_NOTIFY


LVN_PEN [New - Windows 95]
 LVN_PEN  QuickInfo  Overview  Group

[New - Windows 95]

LVN_PEN

The LVN_PEN notification message notifies a list view control of a pen event.

Remarks

The LVN_PEN notification message is only implemented on the Windows 95 platform. In addition, the computer must have the Microsoft Windows for Pen Computing (Pen Windows) extensions installed. To determine whether Pen Windows is installed on a system, call the GetSystemMetrics function, with nIndex set to SM_PENWINDOWS.

See Also

GetSystemMetrics


LVN_SETDISPINFO [New - Windows NT]
 LVN_SETDISPINFO  QuickInfo  Overview  Group

[New - Windows NT]

LVN_SETDISPINFO

pnmv = (LV_DISPINFO FAR *) lParam;

The LVN_SETDISPINFO notification message notifies a list view control's parent window that it must update the information it maintains for an item. This notification message is sent in the form of a WM_NOTIFY message.

Parameters

pnmv

Pointer to an LV_DISPINFO structure that specifies information for the changed item.

Return Value

No return value.

Remarks

The pszText member of the LV_ITEM structure contained within the LV_DISPINFO structure pointed to by pnmv contains a valid value when the LVN_SETDISPINFO message is sent, regardless of whether the LVIF_TEXT flag is set in the mask member of the LV_ITEM structure.

See Also

LV_DISPINFO, LV_ITEM, WM_NOTIFY


NM_CLICK [New - Windows NT]
 NM_CLICK  QuickInfo  Overview  Group

[New - Windows NT]

NM_CLICK

pnmh = (NMHDR FAR *) lParam;

The NM_CLICK notification message notifies the parent window of a control that the user has clicked the left mouse button within the control. NM_CLICK is sent in the form of a WM_NOTIFY message.


NM_DBLCLK [New - Windows NT]
 NM_DBLCLK  QuickInfo  Overview  Group

[New - Windows NT]

NM_DBLCLK

pnmh = (NMHDR FAR *) lParam;

The NM_DBLCLK notification message notifies the parent window of a control that the user has double-clicked the left mouse button within the control. NM_DBLCLK is sent in the form of a WM_NOTIFY message.


NM_KILLFOCUS [New - Windows NT]
 NM_KILLFOCUS  QuickInfo  Overview  Group

[New - Windows NT]

NM_KILLFOCUS

pnmh = (NMHDR FAR *) lParam;

The NM_KILLFOCUS notification message notifies the parent window of a control that the control has lost the input focus. NM_KILLFOCUS is sent in the form of a WM_NOTIFY message.


NM_OUTOFMEMORY [New - Windows NT]
 NM_OUTOFMEMORY  QuickInfo  Overview  Group

[New - Windows NT]

NM_OUTOFMEMORY

pnmh = (NMHDR FAR *) lParam;

The NM_OUTOFMEMORY notification message notifies the parent window of a control that the control could not complete an operation because there was not enough memory available. NM_OUTOFMEMORY is sent in the form of a WM_NOTIFY message.


NM_RCLICK [New - Windows NT]
 NM_RCLICK  QuickInfo  Overview  Group

[New - Windows NT]

NM_RCLICK

pnmh = (NMHDR FAR *) lParam;

The NM_RCLICK notification message notifies the parent window of a control that the user has clicked the right mouse button within the control. NM_RCLICK is sent in the form of a WM_NOTIFY message.


NM_RDBLCLK [New - Windows NT]
 NM_RDBLCLK  QuickInfo  Overview  Group

[New - Windows NT]

NM_RDBLCLK

pnmh = (NMHDR FAR *) lParam;

The NM_RDBLCLK notification message notifies the parent window of a control that the user has double-clicked the right mouse button within the control. NM_RDBLCLK is sent in the form of a WM_NOTIFY message.


NM_RETURN [New - Windows NT]
 NM_RETURN  QuickInfo  Overview  Group

[New - Windows NT]

NM_RETURN

pnmh = (NMHDR FAR *) lParam;

The NM_RETURN notification message notifies the parent window of a control that the control has the input focus and that the user has pressed the ENTER key. NM_RETURN is sent in the form of a WM_NOTIFY message.


NM_SETFOCUS [New - Windows NT]
 NM_SETFOCUS  QuickInfo  Overview  Group

[New - Windows NT]

NM_SETFOCUS

pnmh = (NMHDR FAR *) lParam;

The NM_SETFOCUS notification message notifies the parent window of a control that the control has received the input focus. NM_SETFOCUS is sent in the form of a WM_NOTIFY message.


PBM_DELTAPOS [New - Windows 95]
 PBM_DELTAPOS  QuickInfo  Overview  Group

[New - Windows 95]

PBM_DELTAPOS

wParam = (WPARAM) nIncrement

lParam = 0;

The PBM_DELTAPOS message advances the current position of a progress bar by a specified increment and redraws the bar to reflect the new position.

Parameters

nIncrement

Amount to advance the position.

Return Value

Returns the previous position.


PBM_SETPOS [New - Windows 95]
 PBM_SETPOS  QuickInfo  Overview  Group

[New - Windows 95]

PBM_SETPOS

wParam = (WPARAM) nNewPos;

lParam = 0;

The PBM_SETPOS message sets the current position for a progress bar and redraws the bar to reflect the new position.

Parameters

nNewPos

New position.

Return Value

Returns the previous position.


PBM_SETRANGE [New - Windows 95]
 PBM_SETRANGE  QuickInfo  Overview  Group

[New - Windows 95]

PBM_SETRANGE

wParam = 0;

lParam = MAKELPARAM(nMinRange, nMaxRange);

The PBM_SETRANGE message sets the minimum and maximum values for a progress bar and redraws the bar to reflect the new range.

Parameters

nMinRange

Minimum range value. By default, the minimum value is zero.

nMaxRange

Maximum range value. By default, the maximum value is 100.

Return Value

Returns the previous range values if successful, or zero otherwise. The low-order word specifies the previous minimum value, and the high-order word specifies the previous maximum value.


PBM_SETSTEP [New - Windows 95]
 PBM_SETSTEP  QuickInfo  Overview  Group

[New - Windows 95]

PBM_SETSTEP

wParam = (WPARAM) nStepInc;

lParam = 0;

The PBM_SETSTEP message specifies the step increment for a progress bar. The step increment is the amount by which the progress bar increases its current position whenever it receives a PBM_STEPIT message. By default, the step increment is set to 10.

Parameters

nStepInc

New step increment.

Return Value

Returns the previous step increment.

See Also

PBM_STEPIT


PBM_STEPIT [New - Windows 95]
 PBM_STEPIT  QuickInfo  Overview  Group

[New - Windows 95]

PBM_STEPIT

wParam = 0;

lParam = 0;

The PBM_STEPIT message advances the current position for a progress bar by the step increment and redraws the bar to reflect the new position. An application sets the step increment by sending the PBM_SETSTEP message.

Return Value

Returns the previous position.

Remarks

When the position exceeds the maximum range value, this message resets the current position so that the progress indicator starts over again from the beginning.

See Also

PBM_SETSTEP


PBT_APMBATTERYLOW
 PBT_APMBATTERYLOW  QuickInfo

PBT_APMBATTERYLOW

dwData = (DWORD) lParam;

The PBT_APMBATTERYLOW message is sent to notify applications that battery power is low. A window receives this message through the WM_POWERBROADCAST message.

Parameters

dwData

Reserved, must be zero.

Return Value

No return value.

Remarks

This message is broadcast when a system's APM BIOS signals an APM battery low notification. Because some APM BIOS implementations do not provide battery low notifications, this message may never be sent on some machines.

See Also

WM_POWERBROADCAST


PBT_APMOEMEVENT
 PBT_APMOEMEVENT  QuickInfo

PBT_APMOEMEVENT

dwEventCode = (DWORD) lParam;

The PBT_APMOEMEVENT message is sent when an APM BIOS signals an APM OEM event. A window receives this message through the WM_POWERBROADCAST message.

Parameters

dwEventCode

OEM-defined event code that was signaled by the system's APM BIOS. OEM event codes are in the range 0200h - 02FFh.

Return Value

No return value.

Remarks

Because not all APM BIOS implementations provide OEM event notifications, this message may never be sent on some machines.

See Also

WM_POWERBROADCAST


 PBT_APMPOWERSTATUSCHANGE

[New - Windows 95]

dwData = (DWORD) lParam;

The PBT_APMPOWERSTATUSCHANGE message is sent when a change in the power status of the computer is detected, such as a switch from battery power to A/C or a drop in remaining battery power below a threshold. A window receives this message through the WM_POWERBROADCAST message.

Parameters

dwData

Reserved; must be 0.

Return Value

No return value.

Remarks

An application should process this message by calling the GetSystemPowerStatus function to retrieve the current power status of the computer. In particular, the application should check the ACLineStatus, BatteryFlag, BatteryLifeTime, and BatteryLifePercent members of the SYSTEM_POWER_STATUS structure for any changes. This message can occur when the battery life time drops to less than 5 minutes, or when the percentage of battery life drops below 10 percent.

See Also

GetSystemPowerStatus, SYSTEM_POWER_STATUS, WM_POWERBROADCAST


PBT_APMQUERYSTANDBY [New - Windows 95]
 PBT_APMQUERYSTANDBY  QuickInfo  Overview  Group

[New - Windows 95]

Flags = (DWORD) lParam;

The PBT_APMQUERYSTANDBY message is sent to request permission to place the system in standby mode. An installable driver that grants permission should carry out preparations for changing to standby before returning. A driver receives this message through the WM_POWERBROADCAST message.

Parameters

Flags

Action flags. If bit 0 is 1, the installable driver can prompt the user for directions on how to prepare for the change to standby; otherwise, the driver must prepare without user interaction. All other bit values are reserved.

Return Value

Returns TRUE to grant the request to change to standby mode. To deny the request, return BROADCAST_QUERY_DENY.

Remarks

An installable driver should process this message by first determining whether permission to change to standby can be granted. It must not grant permission if doing so would cause a lost of data. The installable driver can prompt the user for directions on how to prepare for the change to standby only if bit 0 in the Flags parameter is set.

This message is not sent to applications.

See Also

WM_POWERBROADCAST


PBT_APMQUERYSTANDBYFAILED [New - Windows 95]
 PBT_APMQUERYSTANDBYFAILED  QuickInfo  Overview  Group

[New - Windows 95]

dwData = (DWORD) lParam;

The PBT_APMQUERYSTANDBYFAILED message is sent as a notification that permission to place the computer in standby mode was denied. This message is sent if any installable driver returned FALSE to a previous PBT_APMQUERYSTANDBY message. A driver receives this message through the WM_POWERBROADCAST message.

Parameters

dwData

Reserved; must be 0.

Return Value

No return value.

Remarks

Installable drivers typically respond to this message by resuming normal operation. This message is not sent to applications.

See Also

PBT_APMQUERYSTANDBY, WM_POWERBROADCAST


PBT_APMQUERYSUSPEND [New - Windows 95]
 PBT_APMQUERYSUSPEND  QuickInfo  Overview  Group

[New - Windows 95]

Flags = (DWORD) lParam;

The PBT_APMQUERYSUSPEND message is sent to request permission to suspend the computer. An application that grants permission should carry out preparations for the suspension before returning. A window receives this message through the WM_POWERBROADCAST message.

Parameters

Flags

Action flags. If bit 0 is 1, the application can prompt the user for directions on how to prepare for the suspension; otherwise, the application must prepare without user interaction. All other bit values are reserved.

Return Value

Returns TRUE to grant the request to suspend. To deny the question, return BROADCAST_QUERY_DENY.

Remarks

An application should process this message by first determining whether permission to suspend can be granted. It must not grant permission if doing so would cause a loss of data. The application can prompt the user for directions on how to prepare for suspension only if bit 0 in the Flags parameter is set.

See Also

WM_POWERBROADCAST


PBT_APMQUERYSUSPENDFAILED [New - Windows 95]
 PBT_APMQUERYSUSPENDFAILED  QuickInfo  Overview  Group

[New - Windows 95]

dwData = (DWORD) lParam;

The PBT_APMQUERYSUSPENDFAILED message is sent as a notification that permission to suspend the computer was denied. This message is sent if any application or driver returned FALSE to a previous PBT_APMQUERYSUSPEND message. A window receives this message through the WM_POWERBROADCAST message.

Parameters

dwData

Reserved; must be 0.

Return Value

No return value.

Remarks

Applications typically respond to this message by resuming normal operation.

See Also

PBT_APMQUERYSUSPEND, WM_POWERBROADCAST


PBT_APMRESUMECRITICAL [New - Windows 95]
 PBT_APMRESUMECRITICAL  QuickInfo  Overview  Group

[New - Windows 95]

dwData = (DWORD) lParam;

The PBT_APMRESUMECRITICAL message is sent as a notification that the system has resumed operation after a critical suspension caused by a failing battery. A driver receives this message through the WM_POWERBROADCAST message.

Parameters

dwData

Reserved; must be 0.

Return Value

No return value.

Remarks

Because a critical suspension occurs without prior notification, resources and data previously available to a driver may not be present when the driver receives this message. The driver should attempt to restore its state to the best of its ability. While in a critical suspension, the system maintains the state of the DRAM and local hard disks, but may not maintain net connections. A driver may have to take action with respect to files that were open on the network prior to the critical suspension.

This message is not sent to applications.

See Also

WM_POWERBROADCAST


PBT_APMRESUMESTANDBY [New - Windows 95]
 PBT_APMRESUMESTANDBY  QuickInfo  Overview  Group

[New - Windows 95]

dwData = (DWORD) lParam;

The PBT_APMRESUMESTANDBY message is sent as a notification that the system has resumed operation after being placed in standby mode. A driver receives this message through the WM_POWERBROADCAST message.

Parameters

dwData

Reserved; must be 0.

Return Value

No return value.

Remarks

This message is not sent to applications.

See Also

WM_POWERBROADCAST


PBT_APMRESUMESUSPEND [New - Windows 95]
 PBT_APMRESUMESUSPEND  QuickInfo  Overview  Group

[New - Windows 95]

dwData = (DWORD) lParam;

The PBT_APMRESUMESUSPEND message is sent as a notification that the system has resumed opration after being suspended. A window receives this message through the WM_POWERBROADCAST message.

Parameters

dwData

Reserved; must be 0.

Return Value

No return value.

Remarks

Applications may receive this message at any time without a preceding PBT_APMSUSPEND message.

See Also

PBT_APMSUSPEND, WM_POWERBROADCAST


PBT_APMSTANDBY [New - Windows 95]
 PBT_APMSTANDBY  QuickInfo  Overview  Group

[New - Windows 95]

dwData = (DWORD) lParam;

The PBT_APMSTANDBY message is sent immediately before the system is placed in standby mode. This message is typically sent when all installable drivers have returned TRUE to a previous PBT_APMQUERYSTANDBY message. A driver receives this message through the WM_POWERBROADCAST message. A window receives this message through the WM_POWERBROADCAST message.

Parameters

dwData

Reserved; must be 0.

Return Value

No return value.

Remarks

An installable driver should process this message by completing all tasks necessary to save data. Usually, no special action is required. This message may also be sent, without a prior PBT_APMQUERYSUSPEND message, if an application or device driver uses the SetSystemPowerState function to force suspension.

This message is not sent to applications.

See Also

PBT_APMQUERYSTANDBY, PBT_APMQUERYSUSPEND, SetSystemPowerState, WM_POWERBROADCAST


PBT_APMSUSPEND [New - Windows 95]
 PBT_APMSUSPEND  QuickInfo  Overview  Group

[New - Windows 95]

dwData = (DWORD) lParam;

The PBT_APMSUSPEND is sent immediately before the computer is suspended. This message is typically sent when all applications and installable drivers have returned TRUE to a previous PBT_APMQUERYSUSPEND message. A window receives this message through the WM_POWERBROADCAST message.

Parameters

dwData

Reserved; must be 0.

Return Value

No return value.

Remarks

An application should process this message by completing all tasks necessary to save data. This message may also be sent, without a prior PBT_APMQUERYSUSPEND message, if an application or device driver uses the SetSystemPowerState function to force suspension.

See Also

PBT_APMQUERYSUSPEND, SetSystemPowerState, WM_POWERBROADCAST


PSM_ADDPAGE [New - Windows NT]
 PSM_ADDPAGE  QuickInfo  Overview  Group

[New - Windows NT]

PSM_ADDPAGE

wParam = 0;

lParam = (LPARAM) (HPROPSHEETPAGE) hpage);

// Corresponding macro

BOOL PropSheet_AddPage(hPropSheetDlg, hpage);

The PSM_ADDPAGE message adds a new page to the end of an existing property sheet.

Parameters

hPropSheetDlg

Handle to the property sheet.

hpage

Handle to the page to add. The page must have been created by a previous call to the CreatePropertySheetPage function.

Return Value

No return value.

Remarks

The property sheet is not resized to fit the new page. The new page should be no larger than the largest page currently in the property sheet.

See Also

CreatePropertySheetPage


PSM_APPLY [New - Windows NT]
 PSM_APPLY  QuickInfo  Overview  Group

[New - Windows NT]

PSM_APPLY

wParam = 0;

lParam = 0;

// Corresponding macro

BOOL PropSheet_Apply(hPropSheetDlg);

The PSM_APPLY message simulates the choice of the Apply Now button, indicating that one or more pages have changed and the changes need to be validated and recorded. The property sheet sends the PSN_KILLACTIVE notification message to the current page. If the current page returns FALSE, the property sheet sends the PSN_APPLY notification message to all pages.

Parameters

hPropSheetDlg

Handle to the property sheet.

Return Value

Returns TRUE if all pages successfully applied the changes or FALSE otherwise.

See Also

PSN_APPLY, PSN_KILLACTIVE


PSM_CANCELTOCLOSE [New - Windows NT]
 PSM_CANCELTOCLOSE  QuickInfo  Overview  Group

[New - Windows NT]

PSM_CANCELTOCLOSE

wParam = 0;

lParam = 0;

// Corresponding macro

VOID PropSheet_CancelToClose(hPropSheetDlg)

The PSM_CANCELTOCLOSE message disables the Cancel button and changes the text of the OK button to "Close." An application sends this message after applying a change that cannot be canceled.

Parameters

hPropSheetDlg

Handle to the property sheet.

Return Value

No return value.


PSM_CHANGED [New - Windows NT]
 PSM_CHANGED  QuickInfo  Overview  Group

[New - Windows NT]

PSM_CHANGED

wParam = (WPARAM) (HWND) hwndPage;

lParam = 0;

// Corresponding macro

BOOL PropSheet_Changed(hPropSheetDlg, hwndPage);

The PSM_CHANGED message informs a property sheet that information in a page has changed. The property sheet enables the Apply Now button.

Parameters

hPropSheetDlg

Handle to the property sheet.

hwndPage

Handle to the page that has changed.

Return Value

No return value.


PSM_GETCURRENTPAGEHWND
 PSM_GETCURRENTPAGEHWND  Overview  Group

PSM_GETCURRENTPAGEHWND

wParam = 0;

lParam = 0;

// Corresponding macro

HWND PropSheet_GetCurrentPageHwnd(hDlg);

The PSM_GETCURRENTPAGEHWND message retrieves a handle to the window of the current page of a property sheet.

Parameters

hDlg

Handle to the property sheet.

Return Value

Returns a handle to the window of the current property sheet page.

Remarks

Use the PSM_GETCURRENTPAGEHWND message with modeless property sheets to determine when to destroy the dialog box. When the user selects the OK or Cancel button, PSM_GETCURRENTPAGEHWND returns NULL, and you can then use the DestroyWindow function to destroy the dialog box.

See Also

DestroyWindow, PropertySheet


PSM_GETTABCONTROL [New - Windows NT]
 PSM_GETTABCONTROL  QuickInfo  Overview  Group

[New - Windows NT]

PSM_GETTABCONTROL

wParam = 0;

lParam = 0;

// Corresponding macro

HWND PropSheet_GetTabControl(hPropSheetDlg);

The PSM_GETTABCONTROL message retrieves the handle to the tab control of a property sheet.

Parameters

hPropSheetDlg

Handle to the property sheet.

Return Value

Returns the handle to the tab control.


PSM_ISDIALOGMESSAGE
 PSM_ISDIALOGMESSAGE  Overview  Group

PSM_ISDIALOGMESSAGE

wParam = 0;

lParam = (LPARAM)pMsg;

// Corresponding macro

BOOL PropSheet_IsDialogMessage(hDlg, pMsg);

The PSM_ISDIALOGMESSAGE message passes a message to a property sheet dialog box and indicates whether the dialog processed the message.

Parameters

hDlg

Handle to the property sheet.

pMsg

Pointer to a MSG structure that contains the message to be checked.

Return Value

If the message has been processed, the return value is TRUE.

If the message has not been processed, the return value is FALSE.

Remarks

Your message loop should use the PSM_ISDIALOGMESSAGE message with modeless property sheets to pass messages to the property sheet dialog box.

If the return value indicates that the message was processed, it must not be passed to the TranslateMessage or DispatchMessage function.

See Also

DispatchMessage, MSG, PropertySheet, TranslateMessage


PSM_PRESSBUTTON [New - Windows NT]
 PSM_PRESSBUTTON  QuickInfo  Overview  Group

[New - Windows NT]

PSM_PRESSBUTTON

wParam = (WPARAM) (int) iButton;

lParam = 0;

// Corresponding macro

BOOL PropSheet_PressButton(hPropSheetDlg, iButton);

The PSM_PRESSBUTTON message simulates the choice of a property sheet button.

Parameters

hPropSheetDlg

Handle to the property sheet.

iButton

Index of button to choose. This parameter can be one of the following values:

Value	Meaning
PSBTN_APPLYNOW	Chooses the Apply Now button.
PSBTN_BACK	Chooses the Back button.
PSBTN_CANCEL	Chooses the Cancel button.
PSBTN_FINISH	Chooses the Finish button.
PSBTN_HELP	Chooses the Help button.
PSBTN_NEXT	Chooses the Next button.
PSBTN_OK	Chooses the OK button.
Return Value

No return value.


PSM_QUERYSIBLINGS [New - Windows NT]
 PSM_QUERYSIBLINGS  QuickInfo  Overview  Group

[New - Windows NT]

PSM_QUERYSIBLINGS

wParam = (WPARAM) param1;

lParam = (LPARAM) param2;

// Corresponding macro

int PropSheet_QuerySiblings(hPropSheetDlg, param1, param2);

The PSM_QUERYSIBLINGS message forwards the message to each page in the property sheet. If a page returns a nonzero value, the property sheet does not send the message to subsequent pages.

Parameters

hPropSheetDlg

Handle to the property sheet.

param1

First application-defined parameter.

param2

Second application-defined parameter.

Return Value

Returns the nonzero value from a page in the property sheet, or zero if no page returns a nonzero value.


PSM_REBOOTSYSTEM [New - Windows NT]
 PSM_REBOOTSYSTEM  QuickInfo  Overview  Group

[New - Windows NT]

PSM_REBOOTSYSTEM

wParam = 0;

lParam = 0;

// Corresponding macro

VOID PropSheet_RebootSystem(hPropSheetDlg);

The PSM_REBOOTSYSTEM message indicates that the system needs to be restarted for the changes to take effect. An application should send this message only in response to the PSN_APPLY or PSN_KILLACTIVE notification message.

Parameters

hPropSheetDlg

Handle to the property sheet.

Return Value

No return value.

Remarks

This message causes the PropertySheet function to return the ID_PSREBOOTSYSTEM value, but only if the user chooses the OK button to close the property sheet. It is the application's responsibility to reboot the system, which can be done by using the ExitWindowsEx function.

This message supersedes all PSM_RESTARTWINDOWS messages that precede or follow it.

See Also

ExitWindowsEx, PropertySheet, PSN_APPLY, PSN_KILLACTIVE, PSM_RESTARTWINDOWS


PSM_REMOVEPAGE [New - Windows NT]
 PSM_REMOVEPAGE  QuickInfo  Overview  Group

[New - Windows NT]

PSM_REMOVEPAGE

wParam = (WPARAM) (int) index;

lParam = (LPARAM) (HPROPSHEETPAGE) hpage);

// Corresponding macro

VOID PropSheet_RemovePage(hPropSheetDlg, index, hpage);

The PSM_REMOVEPAGE message removes a page from a property sheet.

Parameters

hPropSheetDlg

Handle to the property sheet.

hpage and index

Handle to the page to remove, and the zero-based index of the page to remove. An application can specify the handle or the index, or both. If both are specified, hpage takes precedence.

Return Value

No return value.


PSM_RESTARTWINDOWS [New - Windows NT]
 PSM_RESTARTWINDOWS  QuickInfo  Overview  Group

[New - Windows NT]

PSM_RESTARTWINDOWS

wParam = 0;

lParam = 0;

// Corresponding macro

VOID PropSheet_RestartWindows(hPropSheetDlg);

The PSM_RESTARTWINDOWS message indicates that Windows needs to be restarted for the changes to take effect. An application should send this message only in response to the PSN_APPLY or PSN_KILLACTIVE notification message.

Parameters

hPropSheetDlg

Handle to the property sheet.

Return Value

No return value.

Remarks

This message causes the PropertySheet function to return the ID_PSRESTARTWINDOWS value, but only if the user chooses the OK button to close the property sheet. It is the application's responsibility to restart Windows, which can be done by using the ExitWindowsEx function.

See Also

ExitWindowsEx, PropertySheet, PSN_APPLY, PSN_KILLACTIVE


PSM_SETCURSEL [New - Windows NT]
 PSM_SETCURSEL  QuickInfo  Overview  Group

[New - Windows NT]

PSM_SETCURSEL

wParam = (WPARAM) (int) index;

lParam = (LPARAM) (HPROPSHEETPAGE) hpage;

// Corresponding macro

BOOL PropSheet_SetCurSel(hPropSheetDlg, hpage, index);

The PSM_SETCURSEL message activates the given page in a property sheet.

Parameters

hPropSheetDlg

Handle to the property sheet.

hpage and index

Handle to the page to activate, and the zero-based index of the page to activate. An application can specify the handle or the index, or both. If both are specified, hpage takes precedence.

Return Value

Returns TRUE if successful or FALSE otherwise.

Remarks

The window that is losing the activation receives the PSN_KILLACTIVE notification message, and the window that is gaining the activation receives the PSN_SETACTIVE notification message.

See Also

PSN_KILLACTIVE, PSN_SETACTIVE


PSM_SETCURSELID [New - Windows NT]
 PSM_SETCURSELID  QuickInfo  Overview  Group

[New - Windows NT]

PSM_SETCURSELID

wParam = 0;

lParam = (LPARAM) (int) id;

// Corresponding macro

BOOL PropSheet_SetCurSelByID(hPropSheetDlg, id);

The PSM_SETCURSELID message activates the given page in a property sheet based on the resource identifier of the page.

Parameters

hPropSheetDlg

Handle to the property sheet.

id

Resource identifier of the page to activate.

Return Value

Returns TRUE if successful or FALSE otherwise.

Remarks

The window that is losing the activation receives the PSN_KILLACTIVE notification message, and the window that is gaining the activation receives the PSN_SETACTIVE notification message.

See Also

PSN_KILLACTIVE, PSN_SETACTIVE


PSM_SETFINISHTEXT [New - Windows NT]
 PSM_SETFINISHTEXT  QuickInfo  Overview  Group

[New - Windows NT]

PSM_SETFINISHTEXT

wParam = 0;

lParam = (LPARAM) (LPSTR) lpszText;

// Corresponding macro

VOID PropSheet_SetFinishText(hPropSheetDlg, lpszText);

The PSM_SETFINISHTEXT message sets the text of the Finish button in a wizard property sheet, shows and enables the button, and hides the Next and Back buttons.

Parameters

hPropSheetDlg

Handle to the property sheet.

lpszText

Pointer to the new text for the Finish button.

Return Value

No return value.

Remarks

This message causes the DM_SETDEFID message to be sent to the property sheet dialog box. The wParam parameter specifies the identifier of the Finish button.

See Also

DM_SETDEFID


PSM_SETTITLE [New - Windows NT]
 PSM_SETTITLE  QuickInfo  Overview  Group

[New - Windows NT]

PSM_SETTITLE

wParam = (WPARAM) (DWORD) dwStyle

lParam = (LPARAM) (LPCSTR) lpszText;

// Corresponding macro

VOID PropSheet_SetTitle(hPropSheetDlg, dwStyle, lpszText);

The PSM_SETTITLE message sets the title of a property sheet.

Parameters

hPropSheetDlg

Handle to the property sheet.

dwStyle

Flag that indicates whether to include the prefix "Properties for" with the specified title string. If dwStyle is the PSH_PROPTITLE value, the prefix is included. Otherwise, the prefix is not used.

lpszText

Pointer to a buffer that contains the title string. If the high-order word of this parameter is NULL, the property sheet loads the string resource specified in the low-order word.

Return Value

No return value.


PSM_SETWIZBUTTONS [New - Windows NT]
 PSM_SETWIZBUTTONS  QuickInfo  Overview  Group

[New - Windows NT]

PSM_SETWIZBUTTONS

wParam = 0;

lParam = (LPARAM) (DWORD) dwFlags;

// Corresponding macro

VOID PropSheet_SetWizButtons(hPropSheetDlg, dwFlags);

The PSM_SETWIZBUTTONS message enables the Back, Next, or Finish button in a wizard property sheet. The PropSheet_SetWizButtons macro posts the PSM_SETWIZBUTTONS message.

Parameters

hPropSheetDlg

Handle to the property sheet.

dwFlags

Buttons to enable. This parameter can be a combination of the following values:

Value	Meaning
PSWIZB_BACK	Back button
PSWIZB_NEXT	Next button
PSWIZB_FINISH	Finish button
Return Value

No return value.


PSM_UNCHANGED [New - Windows NT]
 PSM_UNCHANGED  QuickInfo  Overview  Group

[New - Windows NT]

PSM_UNCHANGED

wParam = (WPARAM) (HWND) hwndPage;

lParam = 0;

// Corresponding macro

VOID PropSheet_UnChanged(hPropSheetDlg, hwndPage);

The PSM_UNCHANGED message informs a property sheet that information in a page has reverted to the previously saved state. The property sheet disables the Apply Now button if no other pages have registered changes with the property sheet.

Parameters

hPropSheetDlg

Handle to the property sheet.

hwndPage

Handle to the page that has reverted to the previously saved state.

Return Value

No return value.


PSN_APPLY [New - Windows NT]
 PSN_APPLY  QuickInfo  Overview  Group

[New - Windows NT]

PSN_APPLY

lpnmhdr = (NMHDR FAR *) lParam;

The PSN_APPLY notification message indicates that the user chose the OK or Apply Now button and wants all changes to take effect. This notification message is sent in the form of a WM_NOTIFY message.

Parameters

lpnmhdr

Pointer to an NMHDR structure. The hwndFrom member is the handle to the property sheet.

Return Value

Returns the PSNRET_INVALID_NOCHANGEPAGE value to prevent the changes from taking effect and to return the focus to the page, or the PSNRET_NOERROR value to accept the changes and allow the property sheet to be destroyed.

Remarks

To set the return value, the dialog box procedure for the page must use the SetWindowLong function with the DWL_MSGRESULT value, and the dialog box procedure must return TRUE.

A page should not call the EndDialog function when processing this notification message.

The property sheet is destroyed if the user chooses the OK button and the application returns the PSNRET_NOERROR value in response to this notification.

To receive this notification, a page must set the DWL_MSGRESULT value to FALSE in response the PSN_KILLACTIVE notification message.

The PSHNOTIFY structure is supplied with the PSN_APPLY notification message. The lParam member in this structure is TRUE if the user clicked the Ok or Cancel button, and is FALSE if the user clicked the Close button.

See Also

EndDialog, NMHDR, PSN_KILLACTIVE, PSHNOTIFY, SetWindowLong, WM_NOTIFY


PSN_HELP [New - Windows NT]
 PSN_HELP  QuickInfo  Overview  Group

[New - Windows NT]

PSN_HELP

lpnmhdr = (NMHDR FAR *) lParam;

The PSN_HELP notification message notifies a page that the user has chosen the Help button. This notification message is sent in the form of a WM_NOTIFY message.

Parameters

lpnmhdr

Pointer to an NMHDR structure. The hwndFrom member is the handle to the property sheet.

Return Value

No return value.

Remarks

An application should display help information for the page.

See Also

NMHDR, WM_NOTIFY


PSN_KILLACTIVE [New - Windows NT]
 PSN_KILLACTIVE  QuickInfo  Overview  Group

[New - Windows NT]

PSN_KILLACTIVE

lpnmhdr = (NMHDR FAR *) lParam;

The PSN_KILLACTIVE notification message notifies a page that it is about to lose the activation either because another page is being activated or the user has chosen the OK button. This notification message is sent in the form of a WM_NOTIFY message.

Parameters

lpnmhdr

Pointer to an NMHDR structure. The hwndFrom member is the handle to the property sheet.

Return Value

Returns TRUE to prevent the page from losing the activation or FALSE to allow it.

Remarks

An application should validate the information that the user has typed.

To set the return value, the dialog box procedure for the page must use the SetWindowLong function with the DWL_MSGRESULT value, and the dialog box procedure must return TRUE.

If the dialog box procedure sets DWL_MSGRESULT to TRUE, it should display a message box to explain the problem to the user.

See Also

SetWindowLong, NMHDR, WM_NOTIFY


PSN_QUERYCANCEL [New - Windows NT]
 PSN_QUERYCANCEL  QuickInfo  Overview  Group

[New - Windows NT]

PSN_QUERYCANCEL

lpnmhdr = (NMHDR FAR *) lParam;

The PSN_QUERYCANCEL notification message indicates that the user chose the Cancel button. This notification message is sent in the form of a WM_NOTIFY message.

Parameters

lpnmhdr

Pointer to an NMHDR structure. The hwndFrom member is the handle of the property sheet.

Return Value

Returns TRUE to prevent the cancel operation or FALSE to allow it.

Remarks

A property sheet page can use this notification message to ask the user to verify the cancel operation.

See Also

NMHDR, WM_NOTIFY


PSN_RESET [New - Windows NT]
 PSN_RESET  QuickInfo  Overview  Group

[New - Windows NT]

PSN_RESET

lpnmhdr = (NMHDR FAR *) lParam;

The PSN_RESET notification message notifies a page that the user has chosen the Cancel button and the property sheet is about to be destroyed. All changes made since the user last chose the Apply Now button are canceled. This notification message is sent in the form of a WM_NOTIFY message.

Parameters

lpnmhdr

Pointer to an NMHDR structure. The hwndFrom member is the handle of the property sheet.

Return Value

No return value.

Remarks

An application can use this notification message as an opportunity to perform cleanup operations.

A page should not call the EndDialog function when processing this notification message.

The PSHNOTIFY structure is supplied with the PSN_RESET notification message. The lParam member in this structure is TRUE if the user clicked the Ok or Cancel button, and is FALSE if the user clicked the Close button.

See Also

EndDialog, NMHDR, PSHNOTIFY, WM_NOTIFY


PSN_SETACTIVE [New - Windows NT]
 PSN_SETACTIVE  QuickInfo  Overview  Group

[New - Windows NT]

PSN_SETACTIVE

lpnmhdr = (NMHDR FAR *) lParam;

The PSN_SETACTIVE notification message notifies a page that it is about to be activated. This notification message is sent in the form of a WM_NOTIFY message.

Parameters

lpnmhdr

Pointer to the property sheet.

Return Value

Returns zero to accept the activation or −1 to activate the next or previous page (depending on whether the user chose the Next or Back button). To set the activation to a particular page, return the resource identifier of the page.

Remarks

The PSN_SETACTIVE notification message is sent before the page is visible. An application can use this notification to initialize data in the page.

To set the return value, the dialog box procedure for the page must use the SetWindowLong function with the DWL_MSGRESULT value, and the dialog box procedure must return TRUE.

See Also

NMHDR, SetWindowLong, WM_NOTIFY


PSN_WIZBACK [New - Windows NT]
 PSN_WIZBACK  QuickInfo  Overview  Group

[New - Windows NT]

PSN_WIZBACK

lpnmhdr = (NMHDR FAR *) lParam;

The PSN_WIZBACK notification message notifies a page that the user has chosen the Back button in a wizard property sheet. This notification message is sent in the form of a WM_NOTIFY message.

Parameters

lpnmhdr

Pointer to an NMHDR structure. The hwndFrom member is the handle of the property sheet.

Return Value

Returns −1 to prevent the property sheet from advancing to the previous page.

See Also

NMHDR, WM_NOTIFY


PSN_WIZFINISH [New - Windows NT]
 PSN_WIZFINISH  QuickInfo  Overview  Group

[New - Windows NT]

PSN_WIZFINISH

lpnmhdr = (NMHDR FAR *) lParam;

The PSN_WIZFINISH notification message notifies a page that the user has chosen the Finish button in a wizard property sheet. This notification message is sent in the form of a WM_NOTIFY message.

Parameters

lpnmhdr

Pointer to an NMHDR structure. The hwndFrom member is the handle to the property sheet.

Return Value

Returns a nonzero value to prevent the property sheet from being destroyed.

See Also

NMHDR, WM_NOTIFY


PSN_WIZNEXT [New - Windows NT]
 PSN_WIZNEXT  QuickInfo  Overview  Group

[New - Windows NT]

PSN_WIZNEXT

lpnmhdr = (NMHDR FAR *) lParam;

The PSN_WIZNEXT notification message notifies a page that the user has chosen the Next button in a wizard property sheet. This notification message is sent in the form of a WM_NOTIFY message.

Parameters

lpnmhdr

Pointer to an NMHDR structure. The hwndFrom member is the handle to the property sheet.

Return Value

Returns −1 to prevent the property sheet from advancing to the next page.

See Also

NMHDR, WM_NOTIFY


SB_GETBORDERS [New - Windows NT]
 SB_GETBORDERS  QuickInfo  Overview  Group

[New - Windows NT]

SB_GETBORDERS

wParam = 0;

lParam = (LPARAM) (LPINT) aBorders;

The SB_GETBORDERS message retrieves the current widths of the horizontal and vertical borders of a status window.

Parameters

aBorders

Pointer to an integer array that has three elements. The first element receives the width of the horizontal border, the second receives the width of the vertical border, and the third receives the width of the border between rectangles.

Return Value

If the operation succeeds, the return value is TRUE.

If the operation fails, the return value is FALSE.

Remarks

The borders determine the spacing between the outside edge of the window and the rectangles within the window that contain text. The borders also determine the spacing between rectangles.


SB_GETPARTS [New - Windows NT]
 SB_GETPARTS  QuickInfo  Overview  Group

[New - Windows NT]

SB_GETPARTS

wParam = (WPARAM) nParts;

lParam = (LPARAM) (LPINT) aRightCoord;

The SB_GETPARTS message retrieves a count of the parts in a status window. The message also retrieves the coordinate of the right edge of the specified number of parts.

Parameters

nParts

Number of parts for which to retrieve coordinates. If this parameter is greater than the number of parts in the window, the message retrieves coordinates for existing parts only.

aRightCoord

Pointer to an integer array that has the same number of elements as parts specified by nParts. Each element in the array receives the client coordinate of the right edge of the corresponding part. If an element is set to − 1, the position of the right edge for that part extends to the right edge of the window. To retrieve the current number of parts, set this parameter to zero.

Return Value

Returns the number of parts in the window if successful or zero otherwise.


SB_GETRECT [New - Windows NT]
 SB_GETRECT  QuickInfo  Overview  Group

[New - Windows NT]

SB_GETRECT

wParam = (WPARAM) iPart;

lParam = (LPARAM) (LPRECT) lprc;

The SB_GETRECT message retrieves the bounding rectangle of a part in a status window.

Parameters

iPart

Zero-based index of the part whose bounding rectangle is to be retrieved.

lprc

Pointer to a RECT structure that receives the bounding rectangle.

Return Value

If the operation succeeds, the return value is TRUE.

If the operation fails, the return value is FALSE.

See Also

RECT


SB_GETTEXT [New - Windows NT]
 SB_GETTEXT  QuickInfo  Overview  Group

[New - Windows NT]

SB_GETTEXT

wParam = (WPARAM) iPart;

lParam = (LPARAM) (LPSTR) szText;

The SB_GETTEXT message retrieves the text from the specified part of a status window.

Parameters

iPart

Zero-based index of the part from which to retrieve text.

szText

Pointer to the buffer that receives the text. This parameter is a null-terminated string.

Return Value

Returns a 32-bit value that consists of two 16-bit values. The low word specifies the length, in characters, of the text. The high word specifies the type of operation used to draw the text. The type can be one of these values:

Value	Meaning
0	The text is drawn with a border to appear lower than the plane of the window.
SBT_NOBORDERS	The text is drawn without borders.
SBT_POPOUT	The text is drawn with a border to appear higher than the plane of window.
SBT_RTLREADING	Windows 95 only: Displays text using right-to-left reading order on Hebrew or Arabic systems.
If the text has the SBT_OWNERDRAW drawing type, this message returns the 32-bit value associated with the text instead of the length and operation type.


SB_GETTEXTLENGTH [New - Windows NT]
 SB_GETTEXTLENGTH  QuickInfo  Overview  Group

[New - Windows NT]

SB_GETTEXTLENGTH

wParam = (WPARAM) iPart;

lParam = 0;

The SB_GETTEXTLENGTH message retrieves the length, in characters, of the text from the specified part of a status window.

Parameters

iPart

Zero-based index of the part from which to retrieve text.

Return Value

Returns a 32-bit value that consists of two 16-bit values. The low word specifies the length, in characters, of the text. The high word specifies the type of operation used to draw the text. The type can be one of these values:

Value	Meaning
0	The text is drawn with a border to appear lower than the plane of the window.
SBT_NOBORDERS	The text is drawn without borders.
SBT_OWNERDRAW	The text is drawn by the parent window.
SBT_POPOUT	The text is drawn with a border to appear higher than the plane of the window.
SBT_RTLREADING	Windows 95 only: Displays text using right-to-left reading order on Hebrew or Arabic systems.


SB_SETMINHEIGHT [New - Windows NT]
 SB_SETMINHEIGHT  QuickInfo  Overview  Group

[New - Windows NT]

SB_SETMINHEIGHT

wParam = (WPARAM) minHeight;

lParam = 0;

The SB_SETMINHEIGHT message sets the minimum height of a status window's drawing area.

Parameters

minHeight

Minimum height, in pixels, of the window.

Return Value

No return value.

Remarks

The minimum height is the sum of wParam and twice the width, in pixels, of the vertical border of the status window. An application must send the WM_SIZE message to the status window to redraw the window. The wParam and lParam parameters of the WM_SIZE message should be set to zero.

See Also

WM_SIZE


SB_SETPARTS [New - Windows NT]
 SB_SETPARTS  QuickInfo  Overview  Group

[New - Windows NT]

SB_SETPARTS

wParam = (WPARAM) nParts;

lParam = (LPARAM) (LPINT) aWidths;

The SB_SETPARTS message sets the number of parts in a status window and the coordinate of the right edge of each part.

Parameters

nParts

Number of parts to set. The number of parts cannot be greater than 255.

aWidths

Pointer to an integer array that has the same number of elements as parts specified by nParts. Each element in the array specifies the position, in client coordinates, of the right edge of the corresponding part. If an element is  − 1, the position of the right edge for that part extends to the right edge of the window.

Return Value

If the operation succeeds, the return value is TRUE.

If the operation fails, the return value is FALSE.


SB_SETTEXT [New - Windows NT]
 SB_SETTEXT  QuickInfo  Overview  Group

[New - Windows NT]

SB_SETTEXT

wParam = (WPARAM) iPart | uType;

lParam = (LPARAM) (LPSTR) szText;

The SB_SETTEXT message sets the text in the specified part of a status window.

Parameters

iPart

Zero-based index of the part to set. If this value is 255, the status window is assumed to be a simple window having only one part.

uType

Type of drawing operation. This parameter can be one of the following values:

Value	Meaning
0	The text is drawn with a border to appear lower than the plane of the window.
SBT_NOBORDERS	The text is drawn without borders.
SBT_OWNERDRAW	The text is drawn by the parent window.
SBT_POPOUT	The text is drawn with a border to appear higher than the plane of the window.
SBT_RTLREADING	Windows 95 only: Displays text using right-to-left reading order on Hebrew or Arabic systems.
szText

Pointer to a null-terminated string that specifies the text to set. If uType is SBT_OWNERDRAW, this parameter represents 32 bits of data. The parent window must interpret the data and draw the text when it receives the WM_DRAWITEM message.

Return Value

If the operation succeeds, the return value is TRUE.

If the operation fails, the return value is FALSE.

Remarks

The message invalidates the portion of the window that has changed, causing it to display the new text when the window next receives the WM_PAINT message.

See Also

WM_DRAWITEM, WM_PAINT


SB_SIMPLE [New - Windows NT]
 SB_SIMPLE  QuickInfo  Overview  Group

[New - Windows NT]

SB_SIMPLE

wParam = (WPARAM) (BOOL) fSimple;

lParam = 0;

The SB_SIMPLE message specifies whether a status window displays simple text or displays all window parts set by a previous SB_SETPARTS message.

Parameters

fSimple

Display type flag. If this parameter is TRUE, the window displays simple text. If it is FALSE, it displays multiple parts.

Return Value

Returns FALSE if an error occurs.

Remarks

If the status window is being changed from nonsimple to simple, or vice versa, the window is immediately redrawn.

See Also

SB_SETPARTS


SBM_ENABLE_ARROWS
 SBM_ENABLE_ARROWS  QuickInfo  Overview  Group

SBM_ENABLE_ARROWS

wParam = (WPARAM) fuArrowFlags; // scroll-bar arrow flags

lParam = 0;                     // not used; must be zero

An application sends the SBM_ENABLE_ARROWS message to enable or disable one or both arrows of a scroll bar control.

Parameters

fuArrowFlags

Specifies whether the scroll bar arrows are enabled or disabled and indicates which arrows are enabled or disabled. This parameter can be one of the following values:

Value	Meaning
ESB_DISABLE_BOTH	Disables both arrows on a scroll bar.
ESB_DISABLE_DOWN	Disables the down arrow on a vertical scroll bar.
ESB_DISABLE_LTUP	Disables the left arrow on a horizontal scroll bar or the up arrow on a vertical scroll bar.
ESB_DISABLE_LEFT	Disables the left arrow on a horizontal scroll bar.
ESB_DISABLE_RTDN	Disables the right arrow on a horizontal scroll bar or the down arrow on a vertical scroll bar.
ESB_DISABLE_UP	Disables the up arrow on a vertical scroll bar.
ESB_ENABLE_BOTH	Enables both arrows on a scroll bar.
Return Value

If the message succeeds, the return value is TRUE; otherwise, it is FALSE.


SBM_GETPOS
 SBM_GETPOS  QuickInfo  Overview  Group

SBM_GETPOS

wParam = 0; // not used; must be zero

lParam = 0; // not used; must be zero

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.

Parameters

This message has no parameters.

Return Value

If the message succeeds, the return value is the current position of the scroll box in the scroll bar.

See Also

SBM_GETRANGE, SBM_SETPOS, SBM_SETRANGE, SBM_SETRANGEREDRAW


SBM_GETRANGE
 SBM_GETRANGE  QuickInfo  Overview  Group

SBM_GETRANGE

wParam = (WPARAM) (LPINT) lpnMinPos; // minimum position

lParam = (LPARAM) (LPINT) lpnMaxPos; // maximum position

An application sends the SBM_GETRANGE message to a scroll bar control to retrieve the minimum and maximum position values for the control.

Parameters

lpnMinPos

Points to a value that receives the minimum scrolling position.

lpnMaxPos

Points to a value that receives the maximum scrolling position.

Return Value

This message does not return a value.

See Also

SBM_GETPOS, SBM_SETPOS, SBM_SETRANGE, SBM_SETRANGEREDRAW


SBM_GETSCROLLINFO [New - Windows NT]
 SBM_GETSCROLLINFO  QuickInfo

[New - Windows NT]

SBM_GETSCROLLINFO

wParam = 0;                             // not used, must be zero

lParam = (LPARAM) (LPSCROLLINFO) lpsi;  // scroll bar parameters

An application sends the SBM_GETSCROLLINFO message to retrieve the parameters of a scroll bar.

Parameters

lpsi

Value of lParam. Points to a SCROLLINFO structure whose fMask member, when the message is sent, specifies the scroll bar parameters to retrieve. Before returning, the message copies the specified parameters to the appropriate members of the structure.

The fMask member can be a combination of the following values:

Value	Meaning
SIF_ALL	Combination of SIF_PAGE, SIF_POS, and SIF_RANGE.
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.
Return Value

If the message retrieved any values, the return value is TRUE; otherwise, it is FALSE.

See Also

SBM_SETSCROLLINFO, SCROLLINFO


SBM_SETPOS
 SBM_SETPOS  QuickInfo  Overview  Group

SBM_SETPOS

wParam = (WPARAM) nPos;           // new position of scroll box

lParam = (LPARAM) (BOOL) fRedraw; // redraw flag

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.

Parameters

nPos

Specifies the new position of the scroll box. It must be within the scrolling range.

fRedraw

Specifies whether the scroll bar should be redrawn to reflect the new scroll box position. If this parameter is TRUE, the scroll bar is redrawn. If it is FALSE, the scroll bar is not redrawn.

Return Value

If the position of the scroll box changed, the return value is the previous position of the scroll box; otherwise, it is zero.

Remarks

If the scroll bar control is redrawn by a subsequent call to another function, setting the fRedraw parameter to FALSE is useful.

See Also

SBM_GETPOS, SBM_GETRANGE, SBM_SETRANGE, SBM_SETRANGEREDRAW


SBM_SETRANGE
 SBM_SETRANGE  QuickInfo  Overview  Group

SBM_SETRANGE

wParam = (WPARAM) nMinPos; // minimum scrolling position

lParam = (LPARAM) nMaxPos; // maximum scrolling position

An application sends the SBM_SETRANGE message to a scroll bar control to set the minimum and maximum position values for the control.

Parameters

nMinPos

Specifies the minimum scrolling position.

fMaxPos

Specifies the maximum scrolling position.

Return Value

If the position of the scroll box changed, the return value is the previous position of the scroll box; otherwise, it is zero.

Remarks

The default minimum and maximum position values are zero. The difference between the values specified by the nMinPos and nMaxPos parameters must not be greater than the value of MAXLONG.

If the minimum and maximum position values are equal, the scroll bar control is hidden and, in effect, disabled.

See Also

SBM_GETPOS, SBM_GETRANGE, SBM_SETPOS, SBM_SETRANGEREDRAW


SBM_SETRANGEREDRAW
 SBM_SETRANGEREDRAW  QuickInfo  Overview  Group

SBM_SETRANGEREDRAW

wParam = (WPARAM) nMinPos; // minimum scrolling position

lParam = (LPARAM) nMaxPos  // maximum scrolling position

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.

Parameters

nMinPos

Specifies the minimum scrolling position.

fMaxPos

Specifies the maximum scrolling position.

Return Value

If the position of the scroll box changed, the return value is the previous position of the scroll box; otherwise, it is zero.

Remarks

The default minimum and maximum position values are zero. The difference between the values specified by the nMinPos and nMaxPos parameters must not be greater than the value of MAXLONG.

If the minimum and maximum position values are equal, the scroll bar control is hidden and, in effect, disabled.

See Also

SBM_GETPOS, SBM_GETRANGE, SBM_SETPOS, SBM_SETRANGE


SBM_SETSCROLLINFO [New - Windows NT]
 SBM_SETSCROLLINFO  QuickInfo

[New - Windows NT]

SBM_SETSCROLLINFO

wParam = (WPARAM) fRedraw;              // redraw flag

lParam = (LPARAM) (LPSCROLLINFO) lpsi;  // scroll bar parameters

An application sends the SBM_GETSCROLLINFO message to set the parameters of a scroll bar.

Parameters

fRedraw

Value of wParam. Specifies whether the scroll bar is redrawn to reflect the new scroll box position. If this parameter is TRUE, the scroll bar is redrawn. If it is FALSE, the scroll bar is not redrawn.

lpsi

Value of lParam. Points to a SCROLLINFO structure whose fMask member, when the message is sent, specifies the scroll bar parameters to set.

The fMask member can be a combination of the following values:

Value	Meaning
SIF_ALL	Combination of SIF_PAGE, SIF_POS, and SIF_RANGE.
SIF_PAGE	Sets the scroll page to the value specified in the nPage member of the SCROLLINFO structure pointed to by lpsi.
SIF_POS	Sets the scroll position to the value specified in the nPos member of the SCROLLINFO structure pointed to by lpsi.
SIF_RANGE	Sets the scroll range to the value specified in the nMin and nMax members of the SCROLLINFO structure pointed to by lpsi.
Return Value

The return value is the current position of the scroll box.

See Also

SBM_GETSCROLLINFO, SCROLLINFO


SETRGBSTRING
 SETRGBSTRING  Overview  Group

msg = uSetRGBMsg;
wParam = 0;
lParam = (COLORREF) rgbColor;

Sent from the hook function to the Color dialog box to set the current color selection.

Parameters

uSetRGBMsg

Message identifier for the Set RGB message. This value is the same as returned by the RegisterWindowMessage function for the SETRGBSTRING string.

rgbColor

Value of the color to set the selection to.

Return Value

No return value.

Remarks

If the color value matches one of the basic colors, the dialog box procedure selects that color. If the value does not match a basic color, the procedure either updates the spectrum and luminosity controls or ignores the message if these controls are not visible.

See Also

RegisterWindowMessage


SHAREVISTRING
 SHAREVISTRING  Overview  Group

msg = uShareViolationMsg;
wParam = 0;
lParam = (LPOPENFILENAME) lpofn;

Sent to the hook function of a Open or Save As dialog box when the user has selected the name of a file for which a sharing violation has occurred.

Parameters

uShareViolationMsg

Message identifier for the Share Violation message. This value is the same as returned by the RegisterWindowMessage function for the SHAREVISTRING string.

lpofn

Address of the OPENFILENAME structure that contains the name of the file that caused the sharing violation in the lpstrFile member.

Return Value

Returns one of these values:

OFN_SHAREFALLTHROUGH	Accept the filename.
OFN_SHARENOWARN	Reject the filename but do not warn the user. The application is responsible for displaying a warning message.
OFN_SHAREWARN	Rejects the filename and displays a warning message (the same result as if there were no hook function).
All other values are reserved.

Remarks

If the hook function returns an undefined value, the dialog box responds as if OFN_SHAREWARN was returned.

See Also

OPENFILENAME, RegisterWindowMessage


STM_GETICON
 STM_GETICON  QuickInfo  Overview  Group

STM_GETICON

wParam = 0; // not used; must be zero

lParam = 0; // not used; must be zero

An application sends the STM_GETICON message to retrieve the handle of the icon associated with a static control that has the SS_ICON style.

Parameters

This message has no parameters.

Return Value

The return value is the handle of the icon, or NULL if either the static control has no associated icon or if an error occurred.

See Also

STM_SETICON


STM_GETIMAGE [New - Windows NT]
 STM_GETIMAGE  QuickInfo

[New - Windows NT]

STM_GETIMAGE

wParam = (WPARAM) fImageType;  // image-type flag

lParam = 0;                    // not used; must be zero

An application sends an STM_GETIMAGE message to retrieve the handle of the image associated with a static control.

Parameters

fImageType

Value of wParam. Specifies the type of image to retrieve. This parameter can be one of the following values:

IMAGE_BITMAP

IMAGE_CURSOR

IMAGE_ENHMETAFILE

IMAGE_ICON

Return Value

The return value is the handle of the image, if any; otherwise, it is NULL.

See Also

STM_SETIMAGE


STM_SETICON
 STM_SETICON  QuickInfo  Overview  Group

STM_SETICON

wParam = (WPARAM) (HICON) hicon;    // handle of the icon

lParam = 0;                         // not used; must be zero

An application sends the STM_SETICON message to associate an icon with an icon control.

Parameters

hicon

Value of wParam. Identifies the icon to associate with the icon control.

Return Value

The return value is the handle of the icon previously associated with the icon control, or zero if an error occurs.

See Also

LoadIcon, STM_GETICON


STM_SETIMAGE [New - Windows NT]
 STM_SETIMAGE  QuickInfo

[New - Windows NT]

STM_SETIMAGE

wParam = (WPARAM) fImageType;       // image-type flag

lParam = (LPARAM) (HANDLE) hImage;  // handle of the image

An application sends an STM_SETIMAGE message to associate a new image (icon or bitmap) with a static control.

Parameters

fImageType

Value of wParam. Specifies the type if image to associate with the static control. This parameter can be one of the following values:

IMAGE_BITMAP

IMAGE_CURSOR

IMAGE_ENHMETAFILE

IMAGE_ICON

hImage

Value of lParam. Identifies the image to associate with the static control.

Return Value

The return value is the handle of the image previously associated with the static control, if any; otherwise, it is NULL.

See Also

STM_GETIMAGE


STN_CLICKED [New - Windows 95]
 STN_CLICKED  QuickInfo

[New - Windows 95]

STN_CLICKED
idStatic = (int) LOWORD(wParam);    // identifier of static control
hwndStatic = (HWND) LOWORD(lParam); // handle of static control

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.

See Also

STN_DBLCLK, WM_COMMAND


STN_DBLCLK [New - Windows 95]
 STN_DBLCLK  QuickInfo

[New - Windows 95]

STN_DBLCLK
idStatic = (int) LOWORD(wParam);    // identifier of static control
hwndStatic = (HWND) LOWORD(lParam); // handle of static control

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.

See Also

STN_CLICKED, WM_COMMAND


STN_DISABLE [New - Windows 95]
 STN_DISABLE  QuickInfo

[New - Windows 95]

STN_DISABLE
idStatic = (int) LOWORD(wParam);    // identifier of static control
hwndStatic = (HWND) LOWORD(lParam); // handle of static control

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.

See Also

STN_ENABLE, WM_COMMAND


STN_ENABLE [New - Windows 95]
 STN_ENABLE  QuickInfo

[New - Windows 95]

STN_ENABLE
idStatic = (int) LOWORD(wParam);    // identifier of static control
hwndStatic = (HWND) LOWORD(lParam); // handle of static control

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.

See Also

STN_DISABLE, WM_COMMAND


TB_ADDBITMAP [New - Windows NT]
 TB_ADDBITMAP  QuickInfo  Overview  Group

[New - Windows NT]

TB_ADDBITMAP

wParam = (WPARAM) nButtons;

lParam = (LPARAM) (LPTBADDBITMAP) lptbab;

The TB_ADDBITMAP message adds one or more images to the list of button images available for a toolbar.

Parameters

nButtons

Number of button images in the bitmap.

lptbab

Pointer to a TBADDBITMAP structure that contains the identifier of a bitmap resource and the handle to the module instance with the executable file that contains the bitmap resource.

Return Value

Returns the index of the first new image if successful or  − 1 otherwise.

Remarks

If the toolbar was created by using the CreateWindowEx function, you must send the TB_BUTTONSTRUCTSIZE message to the toolbar before sending TB_ADDBITMAP.

See Also

CreateWindowEx, TBADDBITMAP, TB_BUTTONSTRUCTSIZE


TB_ADDBUTTONS [New - Windows NT]
 TB_ADDBUTTONS  QuickInfo  Overview  Group

[New - Windows NT]

TB_ADDBUTTONS

wParam = (WPARAM) (UINT) uNumButtons;

lParam = (LPARAM) (LPTBBUTTON) lpButtons;

The TB_ADDBUTTONS message adds one or more buttons to a toolbar.

Parameters

uNumButtons

Number of buttons to add.

lpButtons

Pointer to an array of TBBUTTON structures that contains information about the buttons to add. There must be the same number of elements in the array as buttons specified by uNumButtons.

Return Value

Returns TRUE if successful or FALSE otherwise.

Remarks

If the toolbar was created by using the CreateWindowEx function, you must send the TB_BUTTONSTRUCTSIZE message to the toolbar before sending TB_ADDBUTTONS.

See Also

CreateWindowEx, TBBUTTON, TB_BUTTONSTRUCTSIZE


TB_ADDSTRING [New - Windows NT]
 TB_ADDSTRING  QuickInfo  Overview  Group

[New - Windows NT]

TB_ADDSTRING

wParam = (WPARAM) (HINSTANCE) hinst;

lParam = (LPARAM) MAKELONG(idString, 0);

The TB_ADDSTRING message adds a new string to the list of strings available for a toolbar.

Parameters

hinst

Handle to the module instance with an executable file that contains the string resource. If idString points to one or more strings to add, this parameter is zero.

idString

Resource identifier for the string resource, or the address of a buffer that contains one or more null-terminated strings to add to the list, depending on the value of hinst. The last string must be terminated with two null characters.

Return Value

Returns the index of the first new string if successful or  − 1 otherwise.


TB_AUTOSIZE [New - Windows NT]
 TB_AUTOSIZE  QuickInfo  Overview  Group

[New - Windows NT]

TB_AUTOSIZE

wParam = 0;

lParam = 0;

The TB_AUTOSIZE message causes a toolbar to be resized.

Return Value

No return value.

Remarks

An application sends the TB_AUTOSIZE message after causing the size of a toolbar to change either by setting the button or bitmap size or by adding strings for the first time.


TB_BUTTONCOUNT [New - Windows NT]
 TB_BUTTONCOUNT  QuickInfo  Overview  Group

[New - Windows NT]

TB_BUTTONCOUNT

wParam = 0;

lParam = 0;

The TB_BUTTONCOUNT message retrieves a count of the buttons currently in the toolbar.

Return Value

Returns the count of the buttons.


TB_BUTTONSTRUCTSIZE [New - Windows NT]
 TB_BUTTONSTRUCTSIZE  QuickInfo  Overview  Group

[New - Windows NT]

wParam = (WPARAM) cb;

lParam = 0;

The TB_BUTTONSTRUCTSIZE message specifies the size of the TBBUTTON structure.

Parameters

cb

Size, in bytes, of the TBBUTTON structure.

The system uses the size to determine which version of the common control dynamic-link library (DLL) is being used.

If an application uses the CreateWindowEx function to create the toolbar, the application must send this message to the toolbar before sending the TB_ADDBITMAP or TB_ADDBUTTONS message. The CreateToolBarEx function automatically sends TB_BUTTONSTRUCTSIZE, and the size of the TBBUTTON structure is a parameter of the function.

Return Value

No return value.

See Also

CreateWindowEx, TB_ADDBITMAP, TB_ADDBUTTONS, TBBUTTON


TB_CHANGEBITMAP [New - Windows NT]
 TB_CHANGEBITMAP  QuickInfo  Overview  Group

[New - Windows NT]

TB_CHANGEBITMAP

wParam = (WPARAM) idButton;

lParam = (LPARAM) MAKELPARAM(iBitmap, 0);

The TB_CHANGEBITMAP message changes the bitmap for a button in a toolbar.

Parameters

idButton

Command identifier of the button that is to receive a new bitmap.

iBitmap

Zero-based index of an image in the toolbar's image list. The system displays the specified image in the button.

Return Value

Returns TRUE if successful or FALSE otherwise.


TB_CHECKBUTTON [New - Windows NT]
 TB_CHECKBUTTON  QuickInfo  Overview  Group

[New - Windows NT]

TB_CHECKBUTTON

wParam = (WPARAM) idButton;

lParam = (LPARAM) MAKELONG(fCheck, 0);

The TB_CHECKBUTTON message checks or unchecks a given button in a toolbar.

Parameters

idButton

Command identifier of the button to check.

fCheck

Check flag. If this parameter TRUE, the check is added. If it is FALSE, the check is removed.

Return Value

Returns TRUE if successful or FALSE otherwise.

Remarks

When a button has been checked, it appears to have been pressed.


TB_COMMANDTOINDEX [New - Windows NT]
 TB_COMMANDTOINDEX  QuickInfo  Overview  Group

[New - Windows NT]

TB_COMMANDTOINDEX

wParam = (WPARAM) idButton;

lParam = 0;

The TB_COMMANDTOINDEX message retrieves the zero-based index for the button associated with the specified command identifier.

Parameters

idButton

Command identifier associated with the button.

Return Value

Returns the zero-based index for the button.


TB_CUSTOMIZE [New - Windows NT]
 TB_CUSTOMIZE  QuickInfo  Overview  Group

[New - Windows NT]

TB_CUSTOMIZE

wParam = 0;

lParam = 0;

The TB_CUSTOMIZE message displays the Customize Toolbar dialog box.

Return Value

No return value.


TB_DELETEBUTTON [New - Windows NT]
 TB_DELETEBUTTON  QuickInfo  Overview  Group

[New - Windows NT]

TB_DELETEBUTTON

wParam = (WPARAM) iButton;

lParam = 0;

The TB_DELETEBUTTON message deletes a button from the toolbar.

Parameters

iButton

Zero-based index of the button to delete.

Return Value

Returns TRUE if successful or FALSE otherwise.


TB_ENABLEBUTTON [New - Windows NT]
 TB_ENABLEBUTTON  QuickInfo  Overview  Group

[New - Windows NT]

TB_ENABLEBUTTON

wParam = (WPARAM) idButton;

lParam = (LPARAM) MAKELONG(fEnable, 0);

The TB_ENABLEBUTTON message enables or disables the specified button in a toolbar.

Parameters

idButton

Command identifier of the button to enable or disable.

fEnable

Enable flag. If this parameter is TRUE, the button is enabled. If it is FALSE, the button is disabled.

Return Value

Returns TRUE if successful or FALSE otherwise.

Remarks

When a button has been enabled, it can be pressed and checked.


TB_GETBITMAP [New - Windows NT]
 TB_GETBITMAP  QuickInfo  Overview  Group

[New - Windows NT]

TB_GETBITMAP

wParam = (WPARAM) idButton;

lParam = 0;

The TB_GETBITMAP message retrieves the index of the bitmap associated with a button in a toolbar.

Parameters

idButton

Command identifier of the button whose bitmap index is to be retrieved.

Return Value

If successful, the message returns the index of the bitmap. If unsuccessful, it returns zero.


TB_GETBITMAPFLAGS [New - Windows NT]
 TB_GETBITMAPFLAGS  QuickInfo  Overview  Group

[New - Windows NT]

TB_GETBITMAPFLAGS

wParam = 0;

lParam = 0;

The TB_GETBITMAPFLAGS message retrieves the bitmap flags.

Return Value

Returns the TBBF_LARGE value if the display can handle large bitmaps (that is, if the width of the display has at least 120 pixels per logical inch). Otherwise, the return value is zero.


TB_GETBUTTON [New - Windows NT]
 TB_GETBUTTON  QuickInfo  Overview  Group

[New - Windows NT]

TB_GETBUTTON

wParam = (WPARAM) iButton;

lParam = (LPARAM) (LPTBBUTTON) lpButton;

The TB_GETBUTTON message retrieves information about the specified button in a toolbar.

Parameters

iButton

Zero-based index of the button for which to retrieve information.

lpButton

Pointer to the TBBUTTON structure that receives the button information.

Return Value

Returns TRUE if successful or FALSE otherwise.

See Also

TBBUTTON


TB_GETBUTTONTEXT [New - Windows NT]
 TB_GETBUTTONTEXT  QuickInfo  Overview  Group

[New - Windows NT]

TB_GETBUTTONTEXT

wParam = (WPARAM) idButton;

lParam = (LPARAM) (LPSTR) lpszText;

The TB_GETBUTTONTEXT message retrieves the text of a button in a toolbar.

Parameters

idButton

Command identifier of the button whose text is to be retrieved.

lpszText

Pointer to a buffer that receives the button text.

Return Value

Returns the length, in characters, of the string copied to the specified buffer if successful. The length does not include the terminating null character. Otherwise, the return value is  − 1.


TB_GETITEMRECT [New - Windows NT]
 TB_GETITEMRECT  QuickInfo  Overview  Group

[New - Windows NT]

wParam = (WPARAM) iButton;

lParam = (LPARAM) (LPRECT) lprc;

The TB_GETITEMRECT message retrieves the bounding rectangle of a button in a toolbar.

Parameters

iButton

Zero-based index of the button for which to retrieve information.

lprc

Pointer to a RECT structure that receives the coordinates of the bounding rectangle.

Return Value

Returns TRUE if successful or FALSE otherwise.

Remarks

This message does not retrieve the bounding rectangle for buttons whose state is set to the TBSTATE_HIDDEN value.

See Also

RECT


TB_GETROWS [New - Windows NT]
 TB_GETROWS  QuickInfo  Overview  Group

[New - Windows NT]

TB_GETROWS

wParam = 0;

lParam = 0;

The TB_GETROWS message retrieves the number of rows of buttons in a toolbar with the TBSTYLE_WRAPABLE style.

Return Value

Returns the number of rows.


TB_GETSTATE [New - Windows NT]
 TB_GETSTATE  QuickInfo  Overview  Group

[New - Windows NT]

TB_GETSTATE

wParam = (WPARAM) idButton;

lParam = 0;

The TB_GETSTATE message retrieves information about the state of the specified button in a toolbar, such as whether it is enabled, pressed, or checked.

Parameters

idButton

Command identifier of the button for which to retrieve information.

Return Value

Returns the button state information if successful or  − 1 otherwise. The button state information can be a combination of the values listed in Button States.


TB_GETTOOLTIPS [New - Windows NT]
 TB_GETTOOLTIPS  QuickInfo  Overview  Group

[New - Windows NT]

TB_GETTOOLTIPS

wParam = 0;

lParam = 0;

The TB_GETTOOLTIPS message retrieves the handle to the tooltip control, if any, associated with the toolbar.

Return Value

Returns the handle to the tooltip control or NULL if the toolbar has no associated tooltip.


TB_HIDEBUTTON [New - Windows NT]
 TB_HIDEBUTTON  QuickInfo  Overview  Group

[New - Windows NT]

TB_HIDEBUTTON

wParam = (WPARAM) idButton;

lParam = (LPARAM) MAKELONG(fShow, 0);

The TB_HIDEBUTTON message hides or shows the specified button in a toolbar.

Parameters

idButton

Command identifier of the button to hide or show.

fShow

Show flag. If this parameter is TRUE, the button is hidden. If it is FALSE, the button is shown.

Return Value

Returns TRUE if successful or FALSE otherwise.


TB_INDETERMINATE [New - Windows NT]
 TB_INDETERMINATE  QuickInfo  Overview  Group

[New - Windows NT]

TB_INDETERMINATE

wParam = (WPARAM) idButton;

lParam = (LPARAM) MAKELONG(fIndeterminate, 0);

The TB_INDETERMINATE message sets or clears the indeterminate state of the specified button in a toolbar.

Parameters

idButton

Command identifier of the button whose indeterminate state is to be set or cleared.

fIndeterminate

Indeterminate flag. If this parameter is TRUE, the indeterminate state is set. If it is FALSE, the state is cleared.

Return Value

Returns TRUE if successful or FALSE otherwise.


TB_INSERTBUTTON [New - Windows NT]
 TB_INSERTBUTTON  QuickInfo  Overview  Group

[New - Windows NT]

TB_INSERTBUTTON

wParam = (WPARAM) iButton;

lParam = (LPARAM) (LPTBBUTTON) lpButton;

The TB_INSERTBUTTON message inserts a button in a toolbar.

Parameters

iButton

Zero-based index of a button. The message inserts the new button to the left of this button.

lpButton

Pointer to a TBBUTTON structure containing information about the button to insert.

Return Value

Returns TRUE if successful or FALSE otherwise.

See Also

TBBUTTON


TB_ISBUTTONCHECKED [New - Windows NT]
 TB_ISBUTTONCHECKED  QuickInfo  Overview  Group

[New - Windows NT]

TB_ISBUTTONCHECKED

wParam = (WPARAM) idButton;

lParam = 0;

The TB_ISBUTTONCHECKED message determines whether the specified button in a toolbar is checked.

Parameters

idButton

Command identifier of the button.

Return Value

Returns nonzero if the button is checked or zero otherwise.


TB_ISBUTTONENABLED [New - Windows NT]
 TB_ISBUTTONENABLED  QuickInfo  Overview  Group

[New - Windows NT]

TB_ISBUTTONENABLED

wParam = (WPARAM) idButton;

lParam = 0;

The TB_ISBUTTONENABLED message determines whether the specified button in a toolbar is enabled.

Parameters

idButton

Command identifier of the button.

Return Value

Returns nonzero if the button is enabled or zero otherwise.


TB_ISBUTTONHIDDEN [New - Windows NT]
 TB_ISBUTTONHIDDEN  QuickInfo  Overview  Group

[New - Windows NT]

TB_ISBUTTONHIDDEN

wParam = (WPARAM) idButton;

lParam = 0;

The TB_ISBUTTONHIDDEN message determines whether the specified button in a toolbar is hidden.

Parameters

idButton

Command identifier of the button.

Return Value

Returns nonzero if the button is hidden or zero otherwise.


TB_ISBUTTONINDETERMINATE [New - Windows NT]
 TB_ISBUTTONINDETERMINATE  QuickInfo  Overview  Group

[New - Windows NT]

TB_ISBUTTONINDETERMINATE

wParam = (WPARAM) idButton;

lParam = 0;

The TB_ISBUTTONINDETERMINATE message determines whether the specified button in a toolbar is indeterminate.

Parameters

idButton

Command identifier of the button.

Return Value

Returns nonzero if the button is indeterminate or zero otherwise.


TB_ISBUTTONPRESSED [New - Windows NT]
 TB_ISBUTTONPRESSED  QuickInfo  Overview  Group

[New - Windows NT]

TB_ISBUTTONPRESSED

wParam = (WPARAM) idButton;

lParam = 0;

The TB_ISBUTTONPRESSED message determines whether the specified button in a toolbar is pressed.

Parameters

idButton

Command identifier of the button.

Return Value

Returns nonzero if the button is pressed or zero otherwise.


TB_PRESSBUTTON [New - Windows NT]
 TB_PRESSBUTTON  QuickInfo  Overview  Group

[New - Windows NT]

TB_PRESSBUTTON

wParam = (WPARAM) idButton;

lParam = (LPARAM) MAKELONG(fPress, 0);

The TB_PRESSBUTTON message presses or releases the specified button in a toolbar.

Parameters

idButton

Command identifier of the button to press or release.

fPress

Press flag. If this parameter is TRUE, the button is pressed. If it is FALSE, the button is released.

Return Value

Returns TRUE if successful or FALSE otherwise.


TB_SAVERESTORE [New - Windows NT]
 TB_SAVERESTORE  QuickInfo  Overview  Group

[New - Windows NT]

TB_SAVERESTORE

wParam = (WPARAM) (BOOL) fSave;

lParam = (LPARAM)  (TBSAVEPARAMS *)ptbsp;

The TB_SAVERESTORE message saves or restores the state of the toolbar.

Parameters

fSave

Save or restore flag. If this parameter is TRUE, the information is saved. If it is FALSE, it is restored.

ptbsp

Pointer to a TBSAVEPARAMS structure that specifies the registry key, subkey, and value name for the toolbar state information.

Return Value

No return value.

See Also

TBSAVEPARAMS


TB_SETBITMAPSIZE [New - Windows NT]
 TB_SETBITMAPSIZE  QuickInfo  Overview  Group

[New - Windows NT]

TB_SETBITMAPSIZE

wParam = 0;

lParam = (LPARAM) MAKELONG(dxBitmap, dyBitmap)

The TB_SETBITMAPSIZE message sets the size of the bitmapped images to be added to a toolbar.

Parameters

dxBitmap

Width, in pixels, of the bitmapped images.

dyBitmap

Height, in pixels, of the bitmapped images.

Return Value

Returns TRUE if successful or FALSE otherwise.

Remarks

The size can be set only before adding any bitmaps to the toolbar. If an application does not explicitly set the bitmap size, the size defaults to 16 by 15 pixels.


TB_SETBUTTONSIZE [New - Windows NT]
 TB_SETBUTTONSIZE  QuickInfo  Overview  Group

[New - Windows NT]

TB_SETBUTTONSIZE

wParam = 0;

lParam = (LPARAM) MAKELONG(dxButton, dyButton)

The TB_SETBUTTONSIZE sets the size of the buttons to be added to a toolbar.

Parameters

dxButton

Width, in pixels, of the buttons.

dyButton

Height, in pixels, of the buttons.

Return Value

Returns TRUE if successful or FALSE otherwise.

Remarks

The size can be set only before adding any buttons to the toolbar. If an application does not explicitly set the button size, the size defaults to 24 by 22 pixels.


TB_SETCMDID [New - Windows NT]
 TB_SETCMDID  QuickInfo  Overview  Group

[New - Windows NT]

TB_SETCMDID

wParam = (WPARAM) (UINT) index;

lParam = (WPARAM) (UINT) cmdId;

The TB_SETCMDID message sets the command identifier of a toolbar button.

Parameters

index

Zero-based index of the button whose command identifier is to be set.

cmdId

Command identifier.

Return Value

Returns TRUE if successful or FALSE otherwise.


TB_SETPARENT [New - Windows NT]
 TB_SETPARENT  QuickInfo  Overview  Group

[New - Windows NT]

TB_SETPARENT

wParam = (WPARAM) (HWND) hwndParent;

lParam = 0;

The TB_SETPARENT message sets the parent window for a toolbar.

Parameters

hwndParent

Handle to the new parent window.

Return Value

No return value.


TB_SETROWS [New - Windows NT]
 TB_SETROWS  QuickInfo  Overview  Group

[New - Windows NT]

TB_SETROWS

wParam = (WPARAM) MAKEWPARAM(cRows, fLarger);

lParam = (LPARAM) (LPRECT) lprc;

The TB_SETROWS message sets the number of rows of buttons in a toolbar.

Parameters

cRows

Number of rows requested. The minimum number of rows is one, and the maximum is equal to the number of buttons in the toolbar.

fLarger

Flag that indicates whether to create more rows than requested when the system cannot create the number of rows specified by cRows. If this parameter is TRUE, the system creates more rows. If it is FALSE, the system creates fewer rows.

lprc

Pointer to a RECT structure that receives the bounding rectangle of the toolbar after the rows are set.

Return Value

No return value.

Remarks

Because the system does not break up button groups when setting the number of rows, the resulting number of rows might differ from the number requested.

See Also

RECT


TB_SETSTATE [New - Windows NT]
 TB_SETSTATE  QuickInfo  Overview  Group

[New - Windows NT]

TB_SETSTATE

wParam = (WPARAM) idButton;

lParam = (LPARAM) MAKELONG(fState, 0);

The TB_SETSTATE message sets the state for the specified button in a toolbar.

Parameters

idButton

Command identifier of the button.

fState

State flags. This parameter can be a combination of the values listed in Toolbar Button States.

Return Value

Returns TRUE if successful or FALSE otherwise.


TB_SETTOOLTIPS [New - Windows NT]
 TB_SETTOOLTIPS  QuickInfo  Overview  Group

[New - Windows NT]

TB_SETTOOLTIPS

wParam = (WPARAM) (HWND) hwndToolTip;

lParam = 0;

The TB_SETTOOLTIPS message associates a tooltip control with a toolbar.

Parameters

hwndToolTip

Handle to the tooltip control.

Return Value

No return value.

Remarks

Any buttons added to a toolbar before sending the TB_SETTOOLTIPS message are not registered with the tooltip control.


TBM_CLEARSEL [New - Windows NT]
 TBM_CLEARSEL  QuickInfo  Overview  Group

[New - Windows NT]

TBM_CLEARSEL

wParam = (WPARAM) (BOOL) fRedraw;

lParam = 0;

The TBM_CLEARSEL message clears the current selection in a trackbar.

Parameters

fRedraw

Redraw flag. If this parameter is TRUE, the trackbar is redrawn after the selection is cleared.

Return Value

No return value.


TBM_CLEARTICS [New - Windows NT]
 TBM_CLEARTICS  QuickInfo  Overview  Group

[New - Windows NT]

TBM_CLEARTICS

wParam = (WPARAM) (BOOL) fRedraw;

lParam = 0;

The TBM_CLEARTICS message removes the current tick marks from a trackbar.

Parameters

fRedraw

Redraw flag. If this parameter is TRUE, the trackbar is redrawn after the tick marks are cleared.

Return Value

No return value.


TBM_GETCHANNELRECT [New - Windows NT]
 TBM_GETCHANNELRECT  QuickInfo  Overview  Group

[New - Windows NT]

TBM_GETCHANNELRECT
wParam = 0;

lParam = (LPARAM) (LPRECT) lprc;

The TBM_GETCHANNELRECT message retrieves the size and position of the bounding rectangle for a trackbar's channel. (The channel is the area over which the slider moves and which contains the highlight when a range is selected.)

Parameters

lprc

Pointer to a RECT structure that contains the size and position of the channel's bounding rectangle when the function returns.

Return Value

No return value.

See Also

RECT


TBM_GETLINESIZE [New - Windows NT]
 TBM_GETLINESIZE  QuickInfo  Overview  Group

[New - Windows NT]

TBM_GETLINESIZE
wParam = 0;

lParam = 0;

The TBM_GETLINESIZE message retrieves the size of the line for a trackbar. The line size affects how much the slider moves for the TB_LINEUP and TB_LINEDOWN notification messages.

Return Value

Returns a 32-bit value that specifies the size of a line for the trackbar.

Remarks

The default setting for the line size is 1.


TBM_GETNUMTICS [New - Windows NT]
 TBM_GETNUMTICS  QuickInfo  Overview  Group

[New - Windows NT]

TBM_GETNUMTICS
wParam = 0;

lParam = 0;

The TBM_GETNUMTICS message retrieves the number of tick marks in a trackbar.

Return Value

Returns the number of tick marks.

Remarks

This message returns all of the tick marks, including the first and last tick marks created by the trackbar.


TBM_GETPAGESIZE [New - Windows NT]
 TBM_GETPAGESIZE  QuickInfo  Overview  Group

[New - Windows NT]

TBM_GETPAGESIZE
wParam = 0;

lParam = 0;

The TBM_GETPAGESIZE message retrieves the size of the page for a trackbar. The page size affects how much the slider moves for the TB_PAGEUP and TB_PAGEDOWN notification messages.

Return Value

Returns a 32-bit value that specifies the size of a page for the trackbar.


TBM_GETPOS [New - Windows NT]
 TBM_GETPOS  QuickInfo  Overview  Group

[New - Windows NT]

TBM_GETPOS

wParam = 0;

lParam = 0;

The TBM_GETPOS message retrieves the current position of the slider in a trackbar.

Return Value

Returns a 32-bit value that specifies the current position.


TBM_GETPTICS [New - Windows NT]
 TBM_GETPTICS  QuickInfo  Overview  Group

[New - Windows NT]

TBM_GETPTICS

wParam = 0;

lParam = 0;

The TBM_GETPTICS message retrieves the pointer to the array that contains the positions of tick marks for a trackbar.

Return Value

Returns the pointer to the array.


TBM_GETRANGEMAX [New - Windows NT]
 TBM_GETRANGEMAX  QuickInfo  Overview  Group

[New - Windows NT]

TBM_GETRANGEMAX

wParam = 0;

lParam = 0;

The TBM_GETRANGEMAX message retrieves the maximum position for the slider in a trackbar.

Return Value

Returns a 32-bit value that specifies the maximum position.


TBM_GETRANGEMIN [New - Windows NT]
 TBM_GETRANGEMIN  QuickInfo  Overview  Group

[New - Windows NT]

TBM_GETRANGEMIN

wParam = 0;

lParam = 0;

The TBM_GETRANGEMIN message retrieves the minimum position for the slider in a trackbar.

Return Value

Returns a 32-bit value that specifies the minimum position.


TBM_GETSELEND [New - Windows NT]
 TBM_GETSELEND  QuickInfo  Overview  Group

[New - Windows NT]

TBM_GETSELEND

wParam = 0;

lParam = 0;

The TBM_GETSELEND message retrieves the ending position of the current selection in a trackbar.

Return Value

Returns a 32-bit value that specifies the ending position of the current selection.


TBM_GETSELSTART [New - Windows NT]
 TBM_GETSELSTART  QuickInfo  Overview  Group

[New - Windows NT]

TBM_GETSELSTART

wParam = 0;

lParam = 0;

The TBM_GETSELSTART message retrieves the starting position of the current selection in a trackbar.

Return Value

Returns a 32-bit value that specifies the starting position of the current selection.


TBM_GETTHUMBLENGTH [New - Windows NT]
 TBM_GETTHUMBLENGTH  QuickInfo  Overview  Group

[New - Windows NT]

TBM_GETTHUMBLENGTH

wParam = 0;

lParam = 0;

The TBM_GETTHUMBLENGTH message retrieves the length of the slider in a trackbar.

Return Value

Returns the length, in pixels, of the slider.


TBM_GETTHUMBRECT [New - Windows NT]
 TBM_GETTHUMBRECT  QuickInfo  Overview  Group

[New - Windows NT]

TBM_GETTHUMBRECT

wParam = 0;

lParam = (LPARAM) (LPRECT) lprc;

The TBM_GETTHUMBRECT message retrieves the size and position of the bounding rectangle for the slider in a trackbar.

Parameters

lprc

Pointer to a RECT structure that contains the bounding rectangle for the slider when the function returns.

Return Value

No return value.

See Also

RECT


TBM_GETTIC [New - Windows NT]
 TBM_GETTIC  QuickInfo  Overview  Group

[New - Windows NT]

TBM_GETTIC

wParam = (WPARAM) (WORD) iTic;

lParam = 0;

The TBM_GETTIC message retrieves the position of a tick mark in a trackbar.

Parameters

iTic

Zero-based index identifying a tick mark.

Return Value

Returns the position of the specified tick mark or  − 1 if iTic does not specify a valid index.


TBM_GETTICPOS [New - Windows NT]
 TBM_GETTICPOS  QuickInfo  Overview  Group

[New - Windows NT]

TBM_GETTICPOS

wParam = (WPARAM) (WORD) iTic;

lParam = 0;

The TBM_GETTICPOS message retrieves the current physical position of a tick mark in a trackbar.

Parameters

iTic

Zero-based index identifying a tick mark.

Return Value

Returns the physical position, in client coordinates, of the specified tick mark or − 1 if iTic does not specify a valid index.


TBM_SETLINESIZE [New - Windows NT]
 TBM_SETLINESIZE  QuickInfo  Overview  Group

[New - Windows NT]

TBM_SETLINESIZE
wParam = 0;

lParam = (LONG) lLineSize;

The TBM_SETLINESIZE message sets the size of the line for a trackbar. The line size affects how much the slider moves for the TB_LINEUP and TB_LINEDOWN notification messages.

Parameters

lLineSize

New line size.

Return Value

Returns a 32-bit value that specifies the previous line size.


TBM_SETPAGESIZE [New - Windows NT]
 TBM_SETPAGESIZE  QuickInfo  Overview  Group

[New - Windows NT]

TBM_SETPAGESIZE
wParam = 0;

lParam = (LONG) lPageSize;

The TBM_SETPAGESIZE message sets the size of the page for a trackbar. The page size affects how much the slider moves for the TB_PAGEUP and TB_PAGEDOWN notification messages.

Parameters

lPageSize

New page size.

Return Value

Returns a 32-bit value that specifies the previous page size.


TBM_SETPOS [New - Windows NT]
 TBM_SETPOS  QuickInfo  Overview  Group

[New - Windows NT]

TBM_SETPOS

wParam = (WPARAM) (BOOL) fPosition;

lParam = (LPARAM) (LONG) lPosition;

The TBM_SETPOS message sets the current position of the slider in a trackbar.

Parameters

fPosition

Position flag. If this parameter is TRUE, the message sets the slider to the position given by lPosition. Otherwise, the message ensures that the current position is within the current minimum and maximum positions, but it does not move the slider.

lPosition

New position of the slider.

Return Value

No return value.


TBM_SETRANGE [New - Windows NT]
 TBM_SETRANGE  QuickInfo  Overview  Group

[New - Windows NT]

TBM_SETRANGE

wParam = (WPARAM) (BOOL) fRedraw;

lParam = (LPARAM) MAKELONG(lMinimum, lMaximum);

The TBM_SETRANGE message sets the range (minimum and maximum positions) for the slider in a trackbar.

Parameters

fRedraw

Redraw flag. If this parameter is TRUE, the slider is redrawn after the range is set.

lMinimum

Minimum position for the slider.

lMaximum

Maximum position for the slider.

Return Value

No return value.


TBM_SETRANGEMAX [New - Windows NT]
 TBM_SETRANGEMAX  QuickInfo  Overview  Group

[New - Windows NT]

TBM_SETRANGEMAX

wParam = (WPARAM) fRedraw;

lParam = (LPARAM) lMaximum;

The TBM_SETRANGEMAX message sets the maximum position for the slider in a trackbar.

Parameters

fRedraw

Redraw flag. If this parameter is TRUE, the slider is redrawn after the range is set.

lMaximum

Maximum position for the slider.

Return Value

No return value.


TBM_SETRANGEMIN [New - Windows NT]
 TBM_SETRANGEMIN  QuickInfo  Overview  Group

[New - Windows NT]

TBM_SETRANGEMIN

wParam = (WPARAM) fRedraw;

lParam = (LPARAM) lMinimum;

The TBM_SETRANGEMIN message sets the minimum position for the slider in a trackbar.

Parameters

fRedraw

Redraw flag. If this parameter is TRUE, the slider is redrawn after the range is set.

lMinimum

Minimum position for the slider.

Return Value

No return value.


TBM_SETSEL [New - Windows NT]
 TBM_SETSEL  QuickInfo  Overview  Group

[New - Windows NT]

TBM_SETSEL

wParam = (WPARAM) (BOOL) fRedraw;

lParam = (LPARAM) MAKELONG(lMinimum, lMaximum);

The TBM_SETSEL message sets the starting and ending positions for the current selection in a trackbar.

Parameters

fRedraw

Redraw flag. If this parameter is TRUE, the slider is redrawn after the selection is set.

lMinimum

Starting position for the slider.

lMaximum

Ending position for the slider.

Return Value

No return value.


TBM_SETSELEND [New - Windows NT]
 TBM_SETSELEND  QuickInfo  Overview  Group

[New - Windows NT]

TBM_SETSELEND

wParam = (WPARAM) (BOOL) fRedraw;

lParam = (LPARAM) (LONG) lEnd;

The TBM_SETSELEND message sets the ending position of the current selection in a trackbar.

Parameters

fRedraw

Redraw flag. If this parameter is TRUE, the slider is redrawn after the selection is set.

lEnd

Ending position of the selection.

Return Value

No return value.


TBM_SETSELSTART [New - Windows NT]
 TBM_SETSELSTART  QuickInfo  Overview  Group

[New - Windows NT]

TBM_SETSELSTART

wParam = (WPARAM) (BOOL) fRedraw;

lParam = (LPARAM) (LONG) lStart;

The TBM_SETSELSTART message sets the starting position of the current selection in a trackbar.

Parameters

fRedraw

Redraw flag. If this parameter is TRUE, the slider is redrawn after the selection is set.

lStart

Starting position of the selection.

Return Value

No return value.


TBM_SETTHUMBLENGTH [New - Windows NT]
 TBM_SETTHUMBLENGTH  QuickInfo  Overview  Group

[New - Windows NT]

TBM_SETTHUMBLENGTH

wParam = (WPARAM) (UINT) iLength;

lParam = 0;

The TBM_SETTHUMBLENGTH message sets the length of the slider in a trackbar.

Parameters

iLength

Length, in pixels, of the slider.

Return Value

No return value.


TBM_SETTIC [New - Windows NT]
 TBM_SETTIC  QuickInfo  Overview  Group

[New - Windows NT]

TBM_SETTIC

wParam = 0;

lParam = (LPARAM) (LONG) lPosition;

The TBM_SETTIC message sets the position of a tick mark in a trackbar.

Parameters

lPosition

Position of the tick mark. This parameter must specify a positive value.

Return Value

Returns TRUE if the tick mark is set or FALSE otherwise.

Remarks

A trackbar creates its own first and last tick marks. An application should not use this message to set the first and last marks.


TBM_SETTICFREQ [New - Windows NT]
 TBM_SETTICFREQ  QuickInfo  Overview  Group

[New - Windows NT]

TBM_SETTICFREQ

wParam = (WPARAM) wFreq;

lParam = (LPARAM) (LONG) lPosition;

The TBM_SETTICFREQ message sets the interval frequency for tick marks in a trackbar. For example, if the frequency is set to two, a tick mark is displayed for every other increment in the trackbar's range. The default setting for the frequency is one; that is, every increment in the range is associated with a tick mark.

Parameters

wFreq

Frequency of the tick marks.

lPosition

Position of the tick mark. This parameter must specify a positive value.

Return Value

No return value.

Remarks

The trackbar must have the TBS_AUTOTICKS style to use this message.


TBN_BEGINADJUST [New - Windows NT]
 TBN_BEGINADJUST  QuickInfo  Overview  Group

[New - Windows NT]

TBN_BEGINADJUST

pnmhdr = (NMHDR FAR *) lParam;

The TBN_BEGINADJUST notification message notifies a toolbar's parent window that the user has begun customizing a toolbar. This message is sent in the form of a WM_NOTIFY message.

Parameters

pnmhdr

Pointer to an NMHDR structure that contains information about the notification message.

Return Value

No return value.

See Also

NMHDR, WM_NOTIFY


TBN_BEGINDRAG [New - Windows NT]
 TBN_BEGINDRAG  QuickInfo  Overview  Group

[New - Windows NT]

TBN_BEGINDRAG

ptbn = (TBNOTIFY FAR *) lParam;

The TBN_BEGINDRAG notification message notifies a toolbar's parent window that the user has begun dragging a button in a toolbar. This message is sent in the form of a WM_NOTIFY message.

Parameters

ptbn

Pointer to a TBNOTIFY structure. The iItem member contains the zero-based index of the button being dragged.

Return Value

No return value.

See Also

TBNOTIFY, WM_NOTIFY


TBN_CUSTHELP [New - Windows NT]
 TBN_CUSTHELP  QuickInfo  Overview  Group

[New - Windows NT]

TBN_CUSTHELP

pnmhdr = (NMHDR FAR *) lParam;

The TBN_CUSTHELP notification message notifies a toolbar's parent window that the user has chosen the Help button in the Customize Toolbar dialog box. This message is sent in the form of a WM_NOTIFY message.

Parameters

pnmhdr

Pointer to an NMHDR structure that contains information about the notification message.

Return Value

No return value.

See Also

NMHDR, WM_NOTIFY


TBN_ENDADJUST [New - Windows NT]
 TBN_ENDADJUST  QuickInfo  Overview  Group

[New - Windows NT]

TBN_ENDADJUST

pnmhdr = (NMHDR FAR *) lParam;

The TBN_ENDADJUST notification message notifies a toolbar's parent window that the user has stopped customizing a toolbar. This message is sent in the form of a WM_NOTIFY message.

Parameters

pnmhdr

Pointer to an NMHDR structure that contains information about the notification message.

Return Value

No return value.

See Also

NMHDR, WM_NOTIFY


TBN_ENDDRAG [New - Windows NT]
 TBN_ENDDRAG  QuickInfo  Overview  Group

[New - Windows NT]

TBN_ENDDRAG

ptbn = (TBNOTIFY FAR *) lParam;

The TBN_ENDDRAG notification message notifies the toolbar's parent window that the user has stopped dragging a button in a toolbar. This message is sent in the form of a WM_NOTIFY message.

Parameters

ptbn

Pointer to a TBNOTIFY structure. The iItem member contains the zero-based index of the button being dragged.

Return Value

No return value.

See Also

TBNOTIFY, WM_NOTIFY


TBN_GETBUTTONINFO [New - Windows NT]
 TBN_GETBUTTONINFO  QuickInfo  Overview  Group

[New - Windows NT]

TBN_GETBUTTONINFO

ptbn = (TBNOTIFY FAR *) lParam;

The TBN_GETBUTTONINFO message retrieves toolbar customization information and notifies the toolbar's parent window of any changes being made to the toolbar. This is sent in the form of a WM_NOTIFY message.

Parameters

ptbn

Pointer to a TBNOTIFY structure. The iItem member specifies a zero-based index that provides a count of the buttons the customize dialog box displays as both available and present on the toolbar.

The pszText member specifies the address of the current button text, and cchText specifies its length in characters. The application should fill the structure with information about the button.

Return Value

Returns TRUE if button information was copied to the specified structure or FALSE otherwise.

Remarks

The toolbar control allocates a buffer, and the receiver (parent window) must copy the text into that buffer. The cchText member contains the length of the buffer allocated by the toolbar when TBN_GETBUTTONINFO is sent to the parent window.

See Also

TBNOTIFY, WM_NOTIFY


TBN_QUERYDELETE [New - Windows NT]
 TBN_QUERYDELETE  QuickInfo  Overview  Group

[New - Windows NT]

TBN_QUERYDELETE

ptbn = (TBNOTIFY FAR *) lParam;

The TBN_QUERYDELETE notification message notifies the toolbar's parent window whether a button may be deleted from a toolbar while the user is customizing a toolbar. This message is sent in the form of a WM_NOTIFY message.

Parameters

ptbn

Pointer to a TBNOTIFY structure. The iItem member contains the zero-based index of the button to be deleted.

Return Value

Returns TRUE to allow the button to be deleted or FALSE to prevent the button from being deleted.

See Also

TBNOTIFY, WM_NOTIFY


TBN_QUERYINSERT [New - Windows NT]
 TBN_QUERYINSERT  QuickInfo  Overview  Group

[New - Windows NT]

TBN_QUERYINSERT

ptbn = (TBNOTIFY FAR *) lParam;

The TBN_QUERYINSERT notification message notifies the toolbar's parent window whether a button may be inserted to the left of the specified button while the user is customizing a toolbar. This message is sent in the form of a WM_NOTIFY message.

Parameters

ptbn

Pointer to a TBNOTIFY structure. The iItem member contains the zero-based index of the button to be inserted.

Return Value

Returns TRUE to allow a button to inserted in front of the given button or FALSE to prevent the button from being inserted.

See Also

TBNOTIFY, WM_NOTIFY


TBN_RESET [New - Windows NT]
 TBN_RESET  QuickInfo  Overview  Group

[New - Windows NT]

TBN_RESET

pnmhdr = (NMHDR FAR *) lParam;

The TBN_RESET notification message notifies the toolbar's parent window that the user has reset the content of the Customize Toolbar dialog box. This message is sent in the form of a WM_NOTIFY message.

Parameters

pnmhdr

Pointer to an NMHDR structure that contains information about the notification message.

Return Value

No return value.

See Also

NMHDR, WM_NOTIFY


TBN_TOOLBARCHANGE [New - Windows NT]
 TBN_TOOLBARCHANGE  QuickInfo  Overview  Group

[New - Windows NT]

TBN_TOOLBARCHANGE

pnmhdr = (NMHDR FAR *) lParam;

The TBN_TOOLBARCHANGE notification message notifies the toolbar's parent window that the user has customized a toolbar. This message is sent in the form of a WM_NOTIFY message.

Parameters

pnmhdr

Pointer to an NMHDR structure that contains information about the notification message.

Return Value

No return value.

See Also

NMHDR, WM_NOTIFY


TCM_ADJUSTRECT [New - Windows NT]
 TCM_ADJUSTRECT  QuickInfo  Overview  Group

[New - Windows NT]

TCM_ADJUSTRECT

wParam = (WPARAM) (BOOL) fLarger;  // operation to perform

lParam = (LPARAM) (LPRECT) prc;    // pointer to a RECT structure

// Corresponding macro

VOID TabCtrl_AdjustRect(HWND hwnd, BOOL fLarger, RECT FAR* prc);

The TCM_ADJUSTRECT message calculates a tab control's display area given a window rectangle or calculates the window rectangle that would correspond to a specified display area. You can send this message explicitly or by using the TabCtrl_AdjustRect macro.

Parameters

fLarger

Operation to perform. If this parameter is TRUE, prc specifies a display rectangle and receives the corresponding window rectangle. If this parameter is FALSE, prc specifies a window rectangle and receives the corresponding display area.

prc

Pointer to a RECT structure that specifies the given rectangle and receives the calculated rectangle.

hwnd

Handle to the tab control.

Return Value

No return value.

See Also

RECT


TCM_DELETEALLITEMS [New - Windows NT]
 TCM_DELETEALLITEMS  QuickInfo  Overview  Group

[New - Windows NT]

TCM_DELETEALLITEMS

wParam = 0;           // not used; must be zero

lParam = 0;           // not used; must be zero

// Corresponding macro

BOOL TabCtrl_DeleteAllItems(HWND hwnd);

The TCM_DELETEALLITEMS message removes all items from a tab control. You can send this message explicitly or by using the TabCtrl_DeleteAllItems macro.

Parameters

hwnd

Handle to the tab control.

Return Value

Returns TRUE if successful or FALSE otherwise.


TCM_DELETEITEM [New - Windows NT]
 TCM_DELETEITEM  QuickInfo  Overview  Group

[New - Windows NT]

TCM_DELETEITEM

wParam = (WPARAM) (int) iItem;  // index of the item to delete

lParam = 0;                     // not used; must be zero

// Corresponding macro

BOOL TabCtrl_DeleteItem(HWND hwnd, int iItem);

The TCM_DELETEITEM message removes an item from a tab control. You can send this message explicitly or by using the TabCtrl_DeleteItem macro.

Parameters

iItem

Index of the item to delete.

hwnd

Handle to the tab control.

Return Value

Returns TRUE if successful or FALSE otherwise.


TCM_GETCURFOCUS [New - Windows NT]
 TCM_GETCURFOCUS  QuickInfo  Overview  Group

[New - Windows NT]

TCM_GETCURFOCUS

wParam = 0;  // not used; must be zero

lParam = 0;  // not used; must be zero

// Corresponding macro

int TabCtrl_GetCurFocus(HWND hwnd);

The TCM_GETCURFOCUS message returns the index of the item that has the focus in a tab control. You can send this message explicitly or by using the TabCtrl_GetCurFocus macro.

Parameters

hwnd

Handle to the tab control.

Return Value

Returns the index of the tab item that has the focus

Remarks

The item that has the focus may be different than the selected item.


TCM_GETCURSEL [New - Windows NT]
 TCM_GETCURSEL  QuickInfo  Overview  Group

[New - Windows NT]

TCM_GETCURSEL

wParam = 0;   // not used; must be zero

lParam = 0;   // not used; must be zero

// Corresponding macro

int TabCtrl_GetCurSel(HWND hwnd);

The TCM_GETCURSEL message determines the currently selected tab in a tab control. You can send this message explicitly or by using the TabCtrl_GetCurSel macro.

Parameters

hwnd

Handle to the tab control.

Return Value

Returns the index of the selected tab if successful or  − 1 if no tab is selected.


TCM_GETIMAGELIST [New - Windows NT]
 TCM_GETIMAGELIST  QuickInfo  Overview  Group

[New - Windows NT]

TCM_GETIMAGELIST

wParam = 0;   // not used; must be zero

lParam = 0;   // not used; must be zero

// Corresponding macro

HIMAGELIST TabCtrl_GetImageList(HWND hwnd);

The TCM_GETIMAGELIST message retrieves the image list associated with a tab control. You can send this message explicitly or by using the TabCtrl_GetImageList macro.

Return Value

Returns the handle to the image list if successful or NULL otherwise.


TCM_GETITEM [New - Windows NT]
 TCM_GETITEM  QuickInfo  Overview  Group

[New - Windows NT]

TCM_GETITEM

wParam = (WPARAM) (int) iItem;

lParam = (LPARAM) (TC_ITEM FAR *) pitem;

// Corresponding macro

BOOL TabCtrl_GetItem(HWND hwnd, int iItem, TC_ITEM FAR* pitem);

The TCM_GETITEM message retrieves information about a tab in a tab control. You can send this message explicitly or by using the TabCtrl_GetItem macro.

Parameters

iItem

Index of the tab.

pitem

Pointer to a TC_ITEM structure that specifies the information to retrieve and receives information about the tab. When the message is sent, the mask member specifies which attributes to return.

If the mask member specifies the TCIF_TEXT value, the pszText member must contain the address of the buffer that receives the item text and the cchTextMax member must specify the size of the buffer.

hwnd

Handle to the tab control.

Return Value

Returns TRUE if successful or FALSE otherwise.

See Also

TC_ITEM


TCM_GETITEMCOUNT [New - Windows NT]
 TCM_GETITEMCOUNT  QuickInfo  Overview  Group

[New - Windows NT]

TCM_GETITEMCOUNT

wParam = 0;   // not used; must be zero

lParam = 0;   // not used; must be zero

// Corresponding macro

int TabCtrl_GetItemCount(HWND hwnd);

The TCM_GETITEMCOUNT message retrieves the number of tabs in the tab control. You can send this message explicitly or by using the TabCtrl_GetItemCount macro.

Parameters

hwnd

Handle to the tab control.

Return Value

Returns the number of items if successful or zero otherwise.


TCM_GETITEMRECT [New - Windows NT]
 TCM_GETITEMRECT  QuickInfo  Overview  Group

[New - Windows NT]

TCM_GETITEMRECT

wParam = (WPARAM) (int) iItem;       // index of the tab

lParam = (LPARAM) (RECT FAR *) prc;  // pointer to a structure to receive rectangle of tab

// Corresponding macro

BOOL TabCtrl_GetItemRect(HWND hwnd, int iItem, RECT FAR* prc);

The TCM_GETITEMRECT message retrieves the bounding rectangle for a tab in a tab control. You can send this message explicitly or by using the TabCtrl_GetItemRect macro.

Parameters

iItem

Index of the tab.

prc

Pointer to a RECT structure that receives the bounding rectangle of the tab, in viewport coordinates.

hwnd

Handle to the tab control.

Return Value

Returns TRUE if successful or FALSE otherwise.

See Also

RECT


TCM_GETROWCOUNT [New - Windows NT]
 TCM_GETROWCOUNT  QuickInfo  Overview  Group

[New - Windows NT]

TCM_GETROWCOUNT

wParam = 0;   // not used; must be zero

lParam = 0;   // not used; must be zero

// Corresponding macro

int TabCtrl_GetRowCount(HWND hwnd);

The TCM_GETROWCOUNT message retrieves the current number of rows of tabs in a tab control. You can send this message explicitly or by using the TabCtrl_GetRowCount macro.

Parameters

hwnd

Handle to the tab control.

Return Value

Returns the number of rows of tabs.

Remarks

Only tab controls that have the TCS_MULTILINE style can have multiple rows of tabs.


TCM_GETTOOLTIPS [New - Windows NT]
 TCM_GETTOOLTIPS  QuickInfo  Overview  Group

[New - Windows NT]

TCM_GETTOOLTIPS

wParam = 0;   // not used; must be zero

lParam = 0;   // not used; must be zero

// Corresponding macro

int TabCtrl_GetToolTips(HWND hwnd);

The TCM_GETTOOLTIPS message retrieves the handle to the tooltip control associated with a tab control. You can send this message explicitly or by using the TabCtrl_GetToolTips macro.

Parameters

hwnd

Handle to the tab control.

Return Value

Returns the handle to the tooltip control if successful or NULL otherwise.

Remarks

A tab control creates a tooltip control if it has the TCS_TOOLTIPS style. You can also assign a tooltip control to a tab control by using the TCM_SETTOOLTIPS message.

See Also

TCM_SETTOOLTIPS


TCM_HITTEST [New - Windows NT]
 TCM_HITTEST  QuickInfo  Overview  Group

[New - Windows NT]

TCM_HITTEST

wParam = 0;    // not used; must be zero

lParam = (LPARAM) (TC_HITTESTINFO FAR *) pinfo; \\pointer to struct specifying position to test

// Corresponding macro

int TabCtrl_HitTest(HWND hwnd, TC_HITTESTINFO FAR* pinfo);

The TCM_HITTEST message determines which tab, if any, is at a specified screen position. You can send this message explicitly or by using the TabCtrl_HitTest macro.

Parameters

pinfo

Pointer to a TC_HITTESTINFO structure that specifies the screen position to test.

hwnd

Handle to the tab control.

Return Value

Returns the index of the tab or  − 1 if no tab is at the specified position.

See Also

TC_HITTESTINFO


TCM_INSERTITEM [New - Windows NT]
 TCM_INSERTITEM  QuickInfo  Overview  Group

[New - Windows NT]

TCM_INSERTITEM

wParam = (WPARAM) (int) iItem;                 \\index of the new tab

lParam = (LPARAM) (const TC_ITEM FAR*) pitem;  \\pointer to struct specifying tab attributes

// Corresponding macro

int TabCtrl_InsertItem(HWND hwnd, int iItem,

        const TC_ITEM FAR* pitem);

The TCM_INSERTITEM message inserts a new tab in a tab control. You can send this message explicitly or by using the TabCtrl_InsertItem macro.

Parameters

iItem

Index of the new tab.

pitem

Pointer to a TC_ITEM structure that specifies the attributes of the tab.

hwnd

Handle to the tab control.

Return Value

Returns the index of the new tab if successful or  − 1 otherwise.

See Also

TC_ITEM


TCM_REMOVEIMAGE [New - Windows NT]
 TCM_REMOVEIMAGE  QuickInfo  Overview  Group

[New - Windows NT]

TCM_REMOVEIMAGE

wParam = (WPARAM) (int) iImage;  // index of the image to remove

lParam = 0;                      // not used; must be zero

// Corresponding macro

void TabCtrl_RemoveImage(HWND hwnd, int iImage);

The TCM_REMOVEIMAGE message removes an image from a tab control's image list. You can send this message explicitly or by using the TabCtrl_RemoveImage macro.

Parameters

iImage

Index of the image to remove.

hwnd

Handle to the tab control.

Return Value

No return value.

Remarks

The tab control updates each tab's image index, so each tab remains associated with the same image it had been.


TCM_SETCURSEL [New - Windows NT]
 TCM_SETCURSEL  QuickInfo  Overview  Group

[New - Windows NT]

TCM_SETCURSEL

wParam = (WPARAM) (int) iItem;  // index of the tab to select

lParam = 0;                     // not used; must be zero

// Corresponding macro

int TabCtrl_SetCurSel(HWND hwnd, int iItem);

The TCM_SETCURSEL message selects a tab in a tab control. You can send this message explicitly or by using the TabCtrl_SetCurSel macro.

Parameters

iItem

Index of the tab to select.

hwnd

Handle to the tab control.

Return Value

Returns the index of the previously selected tab if successful or  − 1 otherwise.

Remarks

A tab control does not send a TCN_SELCHANGING or TCN_SELCHANGE notification message when a tab is selected using this message.

See Also

TCN_SELCHANGE, TCN_SELCHANGING


TCM_SETIMAGELIST [New - Windows NT]
 TCM_SETIMAGELIST  QuickInfo  Overview  Group

[New - Windows NT]

TCM_SETIMAGELIST

wParam = 0;                           // not used; must be zero

lParam = (LPARAM) (HIMAGELIST) himl;  // handle of image list to assign to tab control

// Corresponding macro

BOOL TabCtrl_SetImageList(HWND hwnd, HIMAGELIST himl);

The TCM_SETIMAGELIST message assigns an image list to a tab control. You can send this message explicitly or by using the TabCtrl_SetImageList macro.

Parameters

himl

Handle of the image list to assign to the tab control.

hwnd

Handle to the tab control.

Return Value

Returns the handle to the previous image list or NULL if there is no previous image list.


TCM_SETITEM [New - Windows NT]
 TCM_SETITEM  QuickInfo  Overview  Group

[New - Windows NT]

TCM_SETITEM

wParam = (WPARAM) (int) iItem;            // index of the item

lParam = (LPARAM) (TC_ITEM FAR *) pitem;  // pointer to struct containing item attributes

// Corresponding macro

BOOL TabCtrl_SetItem(HWND hwnd, int iItem, TC_ITEM FAR* pitem);

The TCM_SETITEM message sets some or all of a tab's attributes. You can send this message explicitly or by using the TabCtrl_SetItem macro.

Parameters

iItem

Index of the item.

pitem

Pointer to a TC_ITEM structure that contains the new item attributes. The mask member specifies which attributes to set.

If the mask member specifies the LVIF_TEXT value, the pszText member is the address of a null-terminated string and the cchTextMax member is ignored.

hwnd

Handle to the tab control.

Return Value

Returns TRUE if successful or FALSE otherwise.

See Also

TC_ITEM


TCM_SETITEMEXTRA [New - Windows NT]
 TCM_SETITEMEXTRA  QuickInfo  Overview  Group

[New - Windows NT]

TCM_SETITEMEXTRA

wParam = (WPARAM) (int) cb;  // number of extra bytes

lParam = 0;                  // not used; must be zero

// Corresponding macro

BOOL TabCtrl_SetItemExtra(HWND hwnd, int cb);

The TCM_SETITEMEXTRA message sets the number of bytes per tab reserved for application-defined data in a tab control. You can send this message explicitly or by using the TabCtrl_SetItemExtra macro.

Parameters

cb

Number of extra bytes.

hwnd

Handle to the tab control.

Return Value

Returns TRUE if successful or FALSE otherwise.

Remarks

By default, the number of extra bytes is four. An application that changes the number of extra bytes cannot use the TC_ITEM structure to retrieve and set the application-defined data for a tab. Instead, you must define a new structure that consists of the TC_ITEMHEADER structure followed by application-defined members.

An application should only change the number of extra bytes when a tab control does not contain any tabs.

See Also

TC_ITEM, TC_ITEMHEADER


TCM_SETITEMSIZE [New - Windows NT]
 TCM_SETITEMSIZE  QuickInfo  Overview  Group

[New - Windows NT]

TCM_SETITEMSIZE

wParam = 0;                   // not used; must be zero

lParam = MAKELPARAM(cx, cy);  // new width and height, in pixels

// Corresponding macro

DWORD TabCtrl_SetItemSize(HWND hwnd, int cx, int cy);

The TCM_SETITEMSIZE message sets the width and height of tabs in a fixed-width or owner-drawn tab control. You can send this message explicitly or by using the TabCtrl_SetItemSize macro.

Parameters

cx and cy

New width and height, in pixels.

hwnd

Handle to the tab control.

Return Value

Returns the old width and height. The width is in the low-order word of the return value, and the height is in the high-order word.


TCM_SETPADDING [New - Windows NT]
 TCM_SETPADDING  QuickInfo  Overview  Group

[New - Windows NT]

TCM_SETPADDING

wParam = 0;                   // not used; must be zero

lParam = MAKELPARAM(cx, cy);  // amount of horizontal and vertical padding, in pixels

// Corresponding macro

void TabCtrl_SetPadding(HWND hwnd, int cx, int cy);

The TCM_SETPADDING message sets the amount of space (padding) around each tab's icon and label in a tab control. You can send this message explicitly or by using the TabCtrl_SetPadding macro.

Parameters

cx and cy

Amount of horizontal and vertical padding, in pixels.

hwnd

Handle to the tab control.

Return Value

No return value.


TCM_SETTOOLTIPS [New - Windows NT]
 TCM_SETTOOLTIPS  QuickInfo  Overview  Group

[New - Windows NT]

TCM_SETTOOLTIPS

wParam = (WPARAM) (HWND) hwndTT;    \\handle to the tooltip control

lParam = 0;                       // not used; must be zero

// Corresponding macro

void TabCtrl_SetToolTips(HWND hwndTab, HWND hwndTT);

The TCM_SETTOOLTIPS message assigns a tooltip control to a tab control. You can send this message explicitly or by using the TabCtrl_SetToolTips macro.

Parameters

hwndTT

Handle to the tooltip control.

hwndTab

Handle to the tab control.

Return Value

No return value.

Remarks

You can get the tooltip control associated with a tab control by using the TCM_GETTOOLTIPS message.

See Also

TCM_GETTOOLTIPS


TCN_KEYDOWN [New - Windows NT]
 TCN_KEYDOWN  QuickInfo  Overview  Group

[New - Windows NT]

TCN_KEYDOWN

pnm = (TC_KEYDOWN FAR *) lParam;

The TCN_KEYDOWN notification message notifies a tab control's parent window that a key has been pressed. This message is sent in the form of a WM_NOTIFY message.

Parameters

pnm

Pointer to a TC_KEYDOWN structure.

Return Value

No return value.

See Also

TC_KEYDOWN, WM_NOTIFY


TCN_SELCHANGE [New - Windows NT]
 TCN_SELCHANGE  QuickInfo  Overview  Group

[New - Windows NT]

TCN_SELCHANGE

idTabCtl = (int) LOWORD(wParam);

hwndTabCtl = (HWND) lParam;

The TCN_SELCHANGE notification message notifies a tab control's parent window that the currently selected tab has changed. This message is sent in the form of a WM_NOTIFY message.

Return Value

No return value.

Remarks

To determine the currently selected tab, use the TabCtrl_GetCurSel macro.

See Also

WM_NOTIFY


TCN_SELCHANGING [New - Windows NT]
 TCN_SELCHANGING  QuickInfo  Overview  Group

[New - Windows NT]

TCN_SELCHANGE

idTabCtl = (int) LOWORD(wParam);

hwndTabCtl = (HWND) lParam;

The TCN_SELCHANGING notification message notifies a tab control's parent window that the currently selected tab is about to change. This message is sent in the form of a WM_NOTIFY message.

Return Value

Returns TRUE to prevent the selection from changing or FALSE to allow the selection to change.

Remarks

To determine the currently selected tab, use the TabCtrl_GetCurSel macro.

See Also

WM_NOTIFY


TTM_ACTIVATE [New - Windows NT]
 TTM_ACTIVATE  QuickInfo  Overview  Group

[New - Windows NT]

TTM_ACTIVATE

wParam = (WPARAM) (BOOL) fActivate;

lParam = 0;

The TTM_ACTIVATE message activates or deactivates a tooltip control.

Parameters

fActivate

Activation flag. If this parameter is TRUE, the tooltip control is activated. If it is FALSE, the tooltip control is deactivated.

Return Value

No return value.


TTM_ADDTOOL [New - Windows NT]
 TTM_ADDTOOL  QuickInfo  Overview  Group

[New - Windows NT]

TTM_ADDTOOL

wParam = 0;

lParam = (LPARAM) (LPTOOLINFO) lpti;

The TTM_ADDTOOL message registers a tool with a tooltip control.

Parameters

lpti

Pointer to a TOOLINFO structure containing information that the tooltip control needs to display text for the tool.

Return Value

Returns TRUE if successful or FALSE otherwise.

See Also

TOOLINFO


TTM_DELTOOL [New - Windows NT]
 TTM_DELTOOL  QuickInfo  Overview  Group

[New - Windows NT]

TTM_DELTOOL

wParam = 0;

lParam = (LPARAM) (LPTOOLINFO) lpti;

The TTM_DELTOOL message removes a tool from a tooltip control.

Parameters

lpti

Pointer to a TOOLINFO structure. The hwnd and uId members identify the tool to remove, and the cbSize member must specify the size of the structure. All other members are ignored.

Return Value

No return value.

See Also

TOOLINFO


TTM_ENUMTOOLS [New - Windows NT]
 TTM_ENUMTOOLS  QuickInfo  Overview  Group

[New - Windows NT]

TTM_ENUMTOOLS

wParam = (WPARAM) (UINT) iTool;

lParam = (LPARAM) (LPTOOLINFO) lpti;

The TTM_ENUMTOOLS message retrieves the information that a tooltip control maintains about the current tool; that is, the tool for which the tooltip is currently displaying text.

Parameters

iTool

Zero-based index of the tool for which to retrieve information.

lpti

Pointer to a TOOLINFO structure that receives information about the tool. Before sending this message, the cbSize member must specify the size of the structure.

Return Value

Returns TRUE if any tools are enumerated or FALSE otherwise.

Remarks

Retrieves the information that a tooltip control maintains about a tool.

See Also

TOOLINFO


TTM_GETCURRENTTOOL [New - Windows NT]
 TTM_GETCURRENTTOOL  QuickInfo  Overview  Group

[New - Windows NT]

TTM_GETCURRENTTOOL

wParam = 0;

lParam = (LPARAM) (LPTOOLINFO) lpti;

The TTM_GETCURRENTTOOL message retrieves the text that a tooltip control maintains for a tool.

Parameters

lpti

Pointer to a TOOLINFO structure that receives information about the current tool.

Return Value

Returns TRUE if successful or FALSE otherwise.

See Also

TOOLINFO


TTM_GETTEXT [New - Windows NT]
 TTM_GETTEXT  QuickInfo  Overview  Group

[New - Windows NT]

TTM_GETTEXT

wParam = 0;

lParam = (LPARAM) (LPTOOLINFO) lpti;

The TTM_GETTEXT message retrieves a count of the tools maintained by a tooltip control.

Parameters

lpti

Pointer to a TOOLINFO structure. When sending the message, the hwnd and uId members identify a tool. If the tooltip control includes the tool, the lpszText member receives the pointer to the string.

Return Value

No return value.

See Also

TOOLINFO


TTM_GETTOOLCOUNT [New - Windows NT]
 TTM_GETTOOLCOUNT  QuickInfo  Overview  Group

[New - Windows NT]

TTM_GETTOOLCOUNT

wParam = 0;

lParam = 0;

The TTM_GETTOOLCOUNT message retrieves the information that a tooltip control maintains about a tool.

Return Value

Returns a count of tools.


TTM_GETTOOLINFO [New - Windows NT]
 TTM_GETTOOLINFO  QuickInfo  Overview  Group

[New - Windows NT]

TTM_GETTOOLINFO

wParam = 0;

lParam = (LPARAM) (LPTOOLINFO) lpti;

The TTM_GETTOOLINFO message retrieves the information that a tooltip control maintains about a tool.

Parameters

lpti

Pointer to a TOOLINFO structure. When sending the message, the hwnd and uId members identify a tool, and the cbSize member must specify the size of the structure. If the tooltip control includes the tool, the structure receives information about the tool.

Return Value

Returns TRUE if successful or FALSE otherwise.

See Also

TOOLINFO


TTM_HITTEST [New - Windows NT]
 TTM_HITTEST  QuickInfo  Overview  Group

[New - Windows NT]

TTM_HITTEST

wParam = 0;

lParam = (LPARAM) (LPHITTESTINFO) lphti;

The TTM_HITTEST message tests a point to determine whether it is within the bounding rectangle of the specified tool and, if the point is within, retrieves information about the tool.

Parameters

lphti

Pointer to a TTHITTESTINFO structure. When sending the message, the hwnd member must specify the handle of a tool and the pt member must specify the coordinates of a point. If the return value is TRUE, the ti member receives information about the tool that occupies the point.

Return Value

Returns TRUE if the tool occupies the specified point or FALSE otherwise.

See Also

TTHITTESTINFO


TTM_NEWTOOLRECT [New - Windows NT]
 TTM_NEWTOOLRECT  QuickInfo  Overview  Group

[New - Windows NT]

TTM_NEWTOOLRECT

wParam = 0;

lParam = (LPARAM) (LPTOOLINFO) lpti;

The TTM_NEWTOOLRECT message sets a new bounding rectangle for a tool.

Parameters

lpti

Pointer to a TOOLINFO structure. The hwnd and uId members identify a tool, and the rect member specifies the new bounding rectangle.

Return Value

No return value.

See Also

TOOLINFO


TTM_RELAYEVENT [New - Windows NT]
 TTM_RELAYEVENT  QuickInfo  Overview  Group

[New - Windows NT]

TTM_RELAYEVENT

wParam = 0;

lParam = (LPARAM) (LPMSG) lpmsg;

The TTM_RELAYEVENT message passes a mouse message to a tooltip control for processing.

Parameters

lpmsg

Pointer to an MSG structure that contains the message to relay.

Return Value

No return value.

Remarks

A tooltip control processes only the following messages passed to it by the TTM_RELAYEVENT message.

WM_LBUTTONDOWN	WM_MOUSEMOVE
WM_LBUTTONUP	WM_RBUTTONDOWN
WM_MBUTTONDOWN	WM_RBUTTONUP
WM_MBUTTONUP
All other messages are ignored.

See Also

MSG


TTM_SETDELAYTIME [New - Windows NT]
 TTM_SETDELAYTIME  QuickInfo  Overview  Group

[New - Windows NT]

TTM_SETDELAYTIME

wParam = (WPARAM) uFlag;

lParam = (LPARAM) (int) iDelay;

The TTM_SETDELAYTIME message sets the initial, reshow, and autopopup durations for a tooltip control.

Parameters

uFlag

Duration to set. This parameter can be one of the following values:

Value	Meaning
TTDT_AUTOMATIC	Automatically calculates the initial, reshow, and autopopup durations based on the value of iDelay.
TTDT_AUTOPOP	Sets the length of time before the tooltip window is hidden if the cursor remains stationary in the tool's bounding rectangle after the tooltip window has appeared.
TTDT_INITIAL	Sets the length of time that the cursor must remain stationary within the bounding rectangle of a tool before the tooltip window is displayed.
TTDT_RESHOW	Sets the length of the delay before subsequent tooltip windows are displayed when the cursor is moved from one tool to another.
iDelay

New duration, in milliseconds.

Return Value

No return value.


TTM_SETTOOLINFO [New - Windows NT]
 TTM_SETTOOLINFO  QuickInfo  Overview  Group

[New - Windows NT]

TTM_SETTOOLINFO

wParam = 0;

lParam = (LPARAM) (LPTOOLINFO) lpti;

The TTM_SETTOOLINFO message sets the information that a tooltip control maintains for a tool.

Parameters

lpti

Pointer to a TOOLINFO structure that specifies the information to set.

Return Value

No return value.

See Also

TOOLINFO


TTM_UPDATETIPTEXT
 TTM_UPDATETIPTEXT  QuickInfo  Overview  Group

TTM_UPDATETIPTEXT

wParam = 0;

lParam = (LPARAM) (LPTOOLINFO) lpti;

The TTM_UPDATETIPTEXT message sets the tooltip text for a tool.

Parameters

lpti

Pointer to a TOOLINFO structure. The hinst and lpszText members must specify the instance handle and the pointer to the text. The hwnd and uId members identify the tool to update.

Return Value

No return value.

See Also

TOOLINFO


TTM_WINDOWFROMPOINT
 TTM_WINDOWFROMPOINT  QuickInfo  Overview  Group

TTM_WINDOWFROMPOINT

wParam = 0;

lParam = (POINT FAR *) lppt;

The TTM_WINDOWFROMPOINT message allows a subclass procedure to cause a tooltip to display text for a window other than the one beneath the mouse cursor.

Parameters

lppt

Pointer to a POINT structure that defines the point to be checked.

Return Value

The return value is the handle to the window that contains the point, or NULL if no window exists at the specified point.

Remarks

This message is intended to be processed by an application that subclasses a tooltip. It is not intended to be sent by an application. A tooltip sends this message to itself before displaying the text for a window. By changing the coordinates of the point specified by lppt, the subclass procedure can cause the tooltip to display text for a window other than the one beneath the mouse cursor.

See Also

POINT


TTN_NEEDTEXT [New - Windows NT]
 TTN_NEEDTEXT  QuickInfo  Overview  Group

[New - Windows NT]

TTN_NEEDTEXT

idTT = (int) wParam;

lpttt = (LPTOOLTIPTEXT) lParam;

The TTN_NEEDTEXT notification message retrieves text for a tool. This notification message is sent in the form of a WM_NOTIFY message.

Parameters

idTT

Identifier of the tooltip control.

lpttt

Pointer to a TOOLTIPTEXT structure. The hdr member identifies the tool for which text is needed. The receiving window can specify the string by taking one of the following actions:

•	Copying the text to the buffer specified by the szText member.

•	Copying the address of the buffer that contains the text to the lpszText member.

•	Copying the identifier of a string resource to the lpszText member and copying the handle of the instance that contains the resource to the hinst member.

Return Value

No return value.

Remarks

This notification message is sent to the window specified in the hwnd member of the TOOLINFO structure for the tool. This notification is sent only if the LPSTR_TEXTCALLBACK value is specified when the tool is added to a tooltip control.

Windows 95 only: When a TTN_NEEDTEXT notification is received, the application can set or clear the TTF_RTLREADING value in the uFlags member of the TOOLTIPTEXT structure pointed to by lpttt as required. This is the only flag that can be changed during the notification callback.

See Also

TOOLINFO, TOOLTIPTEXT, WM_NOTIFY


TTN_POP [New - Windows NT]
 TTN_POP  QuickInfo  Overview  Group

[New - Windows NT]

TTN_POP

idTT = (int) wParam;

pnmh = (NMHDR FAR *) lParam;

The TTN_POP notification message notifies the owner window that a tooltip is about to be hidden. This notification message is sent in the form of a WM_NOTIFY message.

Parameters

idTT

Identifier of the tooltip control.

lpttt

Return Value

No return value.

Remarks

Address of an NMHDR structure.

See Also

NMHDR, WM_NOTIFY


TTN_SHOW [New - Windows NT]
 TTN_SHOW  QuickInfo  Overview  Group

[New - Windows NT]

TTN_SHOW

idTT = (int) wParam;

pnmh = (NMHDR FAR *) lParam;

The TTN_SHOW notification message notifies the owner window that a tooltip is about to be displayed. This notification message is sent in the form of a WM_NOTIFY message.

Parameters

idTT

Identifier of the tooltip control.

lpttt

Return Value

No return value.

Remarks

Address of an NMHDR structure.

See Also

NMHDR, WM_NOTIFY


TVM_CREATEDRAGIMAGE [New - Windows NT]
 TVM_CREATEDRAGIMAGE  QuickInfo  Overview  Group

[New - Windows NT]

TVM_CREATEDRAGIMAGE

wParam = 0;

lParam = (LPARAM) (HTREEITEM) hitem;

// Corresponding macro

HIMAGELIST TreeView_CreateDragImage(hwnd, hitem);

The TVM_CREATEDRAGIMAGE message creates a dragging bitmap for the specified item in a tree-view control, creates an image list for the bitmap, and adds the bitmap to the image list. An application can display the image when dragging the item by using the image list functions. You can send this message explicitly or by using the TreeView_CreateDragImage macro.

Parameters

hwnd

Handle to the tree-view control.

hitem

Handle to the item that receives the new dragging bitmap.

Return Value

Returns the handle of the image list to which the dragging bitmap was added if successful or NULL otherwise.


TVM_DELETEITEM [New - Windows NT]
 TVM_DELETEITEM  QuickInfo  Overview  Group

[New - Windows NT]

TVM_DELETEITEM

wParam = 0;

lParam = (LPARAM) (HTREEITEM) hitem;

// Corresponding macro

BOOL TreeView_DeleteItem(hwnd, hitem);

// Related macro

BOOL TreeView_DeleteAllItems(hwnd);

The TVM_DELETEITEM message removes an item from a tree-view control. You can send this message explicitly or by using the TreeView_DeleteItem or TreeView_DeleteAllItems macro.

Parameters

hwnd

Handle to the tree-view control.

hitem

Handle to the item to delete. If hitem is the TVI_ROOT value, all items are deleted from the tree-view control.

Return Value

Returns TRUE if successful or FALSE otherwise.

Remarks

If the item label is being edited, the edit operation is canceled and the parent window receives the TVN_ENDLABELEDIT notification message. The parent window receives a TVN_DELETEITEM notification message when the item is removed.

See Also

TVN_DELETEITEM, TVN_ENDLABELEDIT


TVM_EDITLABEL [New - Windows NT]
 TVM_EDITLABEL  QuickInfo  Overview  Group

[New - Windows NT]

TVM_EDITLABEL

wParam = 0;

lParam = (LPARAM) (HTREEITEM) hitem;

// Corresponding macro

HWND TreeView_EditLabel(hwnd, hitem);

The TVM_EDITLABEL message begins in-place editing of the specified item's text, replacing the text of the item with a single-line edit control containing the text. This message implicitly selects and focuses the specified item. You can send this message explicitly or by using the TreeView_EditLabel macro.

Parameters

hwnd

Handle to the tree-view control.

hitem

Handle to the item to edit.

Return Value

Returns the handle to the edit control used to edit the item text if successful or NULL otherwise.

Remarks

This message sends a TVN_BEGINLABELEDIT notification message to the parent of the tree-view control.

When the user completes or cancels editing, the edit control is destroyed and the handle is no longer valid. You can safely subclass the edit control, but do not destroy it.

The control must have the focus before you send this message to the control. Focus can be set using the SetFocus function.

See Also

TVN_BEGINLABELEDIT, SetFocus


TVM_ENDEDITLABELNOW [New - Windows NT]
 TVM_ENDEDITLABELNOW  QuickInfo  Overview  Group

[New - Windows NT]

TVM_ENDEDITLABELNOW

wParam = (WPARAM) (BOOL) fCancel;

lParam = 0;

// Corresponding macro

BOOL TreeView_EndEditLabelNow(hwnd, fCancel);

The TVM_ENDEDITLABELNOW message ends the editing of a tree-view item's label.

Parameters

hwnd

Handle to the tree-view control.

fCancel

Variable that indicates whether the editing is canceled without being saved to the label. If this parameter is TRUE, the system cancels editing without saving the changes. Otherwise, the system saves the changes to the label.

Return Value

Returns TRUE if successful or FALSE otherwise.

Remarks

This message causes the TVN_ENDLABELEDIT notification message to be sent to the parent window of the tree-view control.

See Also

TVN_ENDLABELEDIT


TVM_ENSUREVISIBLE [New - Windows NT]
 TVM_ENSUREVISIBLE  QuickInfo  Overview  Group

[New - Windows NT]

TVM_ENSUREVISIBLE

wParam = 0;

lParam = (LPARAM) (HTREEITEM) hitem;

// Corresponding macro

BOOL TreeView_EnsureVisible(hwnd, hitem);

The TVM_ENSUREVISIBLE message ensures that a tree-view item is visible, expanding the parent item or scrolling the tree-view control, if necessary. You can send this message explicitly or by using the TreeView_EnsureVisible macro.

Parameters

hwnd

Handle to the tree-view control.

hitem

Handle to the item.

Return Value

Returns TRUE if the system scrolled the items in the tree-view control to ensure that the specified item is visible. Otherwise, the message returns FALSE.

Remarks

If the TVM_ENSUREVISIBLE message expands the parent item, the parent window receives the TVN_ITEMEXPANDING and TVN_ITEMEXPANDED notification messages.

See Also

TVN_ITEMEXPANDED, TVN_ITEMEXPANDING


TVM_EXPAND [New - Windows NT]
 TVM_EXPAND  QuickInfo  Overview  Group

[New - Windows NT]

TVM_EXPAND

wParam = (WPARAM) (UINT) flag;

lParam = (LPARAM) (HTREEITEM) hitem;

// Corresponding macro

BOOL TreeView_Expand(hwnd, hitem, flag);

The TVM_EXPAND message expands or collapses the list of child items, if any, associated with the specified parent item. You can send this message explicitly or by using the TreeView_Expand macro.

Parameters

hwnd

Handle to the tree-view control.

hitem

Handle to the parent item to expand or collapse.

flag

Action flag. This parameter can be one of the following values:

Value	Meaning
TVE_COLLAPSE	Collapses the list.
TVE_COLLAPSERESET	Collapses the list and removes the child items. Note that TVE_COLLAPSE must also be specified.
TVE_EXPAND	Expands the list.
TVE_TOGGLE	Collapses the list if it is currently expanded or expands it if it is currently collapsed.
Return Value

Returns TRUE if any change took place or FALSE otherwise.

Remarks

This message does not send the TVN_ITEMEXPANDING and TVN_ITEMEXPANDED notification messages to the parent window.

See Also

TVN_ITEMEXPANDED, TVN_ITEMEXPANDING


TVM_GETCOUNT [New - Windows NT]
 TVM_GETCOUNT  QuickInfo  Overview  Group

[New - Windows NT]

TVM_GETCOUNT

wParam = 0;

lParam = 0;

// Corresponding macro

UINT TreeView_GetCount(hwnd);

The TVM_GETCOUNT message retrieves a count of the items in a tree-view control. You can send this message explicitly or by using the TreeView_GetCount macro.

Parameters

hwnd

Handle to the tree-view control.

Return Value

Returns the count of items.


TVM_GETEDITCONTROL [New - Windows NT]
 TVM_GETEDITCONTROL  QuickInfo  Overview  Group

[New - Windows NT]

TVM_GETEDITCONTROL

wParam = 0;

lParam = 0;

// Corresponding macro

HWND TreeView_GetEditControl(hwnd);

The TVM_GETEDITCONTROL message retrieves the handle to the edit control being used to edit a tree-view item's text. You can send this message explicitly or by using the TreeView_GetEditControl macro.

Parameters

hwnd

Handle to the tree-view control.

Return Value

Returns the handle to the edit control if successful or NULL otherwise.


TVM_GETIMAGELIST [New - Windows NT]
 TVM_GETIMAGELIST  QuickInfo  Overview  Group

[New - Windows NT]

TVM_GETIMAGELIST

wParam = (WPARAM) iImage;

lParam = 0;

// Corresponding macro

HIMAGELIST TreeView_GetImageList(hwnd, iImage);

The TVM_GETIMAGELIST message retrieves the handle to the normal or state image list associated with a tree-view control. You can send this message explicitly or by using the TreeView_GetImageList macro.

Parameters

hwnd

Handle to the image list.

iImage

Type of image list to retrieve. This parameter can be one of the following values:

Value	Meaning
TVSIL_NORMAL	Retrieves the normal image list, which contains the selected and unselected images for the tree-view item.
TVSIL_STATE	Retrieves the state image list, which contains the images for tree-view items that are in a user-defined state.
Return Value

Returns the handle to the image list.


TVM_GETINDENT [New - Windows NT]
 TVM_GETINDENT  QuickInfo  Overview  Group

[New - Windows NT]

TV_GETINDENT

wParam = 0;

lParam = 0;

// Corresponding macro

UINT TreeView_GetIndent(hwnd);

The TVM_GETINDENT message retrieves the amount, in pixels, that child items are indented relative to their parent items. You can send this message explicitly or by using the TreeView_GetIndent macro.

Parameters

hwnd

Handle to the tree-view control.

Return Value

Returns the amount of indentation.


TVM_GETISEARCHSTRING [New - Windows NT]
 TVM_GETISEARCHSTRING  QuickInfo  Overview  Group

[New - Windows NT]

TVM_GETISEARCHSTRING

wParam = 0;

lParam = (LPARAM) (LPSTR) lpsz;

// Corresponding macro

BOOL TreeView_GetISearchString(hwnd, lpsz);

The TVM_GETISEARCHSTRING message retrieves the incremental search string for a tree-view control. The tree-view control uses the incremental search string to select an item based on characters typed by the user.

Parameters

hwnd

Handle to the tree-view control.

lpsz

Pointer to the buffer that receives the incremental search string.

Return Value

Returns the number of characters in the incremental search string.

If the tree-view control is not in incremental search mode, the return value is zero.


TVM_GETITEM [New - Windows NT]
 TVM_GETITEM  QuickInfo  Overview  Group

[New - Windows NT]

TVM_GETITEM

wParam = 0;

lParam = (LPARAM) (TV_ITEM FAR*) pitem;

// Corresponding macro

BOOL TreeView_GetItem(hwnd, pitem);

The TVM_GETITEM message retrieves some or all of a tree-view item's attributes. You can send this message explicitly or by using the TreeView_GetItem macro.

Parameters

hwnd

Handle to the tree-view control.

pitem

Pointer to a TV_ITEM structure that specifies the information to retrieve and receives information about the item. When the message is sent, the hItem member identifies the item to retrieve information about and the mask member specifies the attributes to retrieve.

If mask specifies the TVIF_TEXT value, the pszText member must contain the pointer to the buffer that receives the item text and the cchTextMax member must specify the size of the buffer.

If mask specifies the TVIF_STATE value, the stateMask member indicates which item states are to be returned.

Return Value

Returns TRUE if successful or FALSE otherwise.

See Also

TV_ITEM


TVM_GETITEMRECT [New - Windows NT]
 TVM_GETITEMRECT  QuickInfo  Overview  Group

[New - Windows NT]

TVM_GETITEMRECT

wParam = (WPARAM) (BOOL) fItemRect;

lParam = (LPARAM) (RECT FAR*) prc;

// Corresponding macro

BOOL TreeView_GetItemRect(hwnd, hitem, prc, fItemRect);

The TVM_GETITEMRECT message retrieves the bounding rectangle for a tree-view item and indicates whether the item is visible. You can send this message explicitly or by using the TreeView_GetItemRect macro.

Parameters

hwnd and hitem

Handle to the tree-view control, and the handle to the item.

prc

Pointer to a RECT structure that receives the bounding rectangle. The coordinates are relative to the upper-left corner of the tree-view control.

fItemRect

Value specifying the portion of the item for which to retrieve the bounding rectangle. If this parameter is TRUE, the bounding rectangle includes only the text of the item. Otherwise, it includes the entire line that the item occupies in the tree-view control.

Return Value

If the item is visible and retrieves the bounding rectangle, the return value is TRUE. Otherwise, the message returns FALSE and does not retrieve the bounding rectangle.

See Also

RECT


TVM_GETNEXTITEM [New - Windows NT]
 TVM_GETNEXTITEM  QuickInfo  Overview  Group

[New - Windows NT]

TVM_GETNEXTITEM

wParam = (WPARAM) (UINT) flag;

lParam = (LPARAM) (HTREEITEM) hitem;

// Corresponding macro

HTREEITEM TreeView_GetNextItem(hwnd, hitem, flag);

// Related macros

HTREEITEM TreeView_GetChild(hwnd, hitem);

HTREEITEM TreeView_GetDropHilite(hwnd);

HTREEITEM TreeView_GetFirstVisible(hwnd);

HTREEITEM TreeView_GetNextSibling(hwnd, hitem);

HTREEITEM TreeView_GetNextVisible(hwnd, hitem);

HTREEITEM TreeView_GetParent(hwnd, hitem);

HTREEITEM TreeView_GetPrevSibling(hwnd, hitem);

HTREEITEM TreeView_GetPrevVisible(hwnd, hitem);

HTREEITEM TreeView_GetRoot(hwnd);

HTREEITEM TreeView_GetSelection(hwnd);

Retrieves the tree-view item that bears the specified relationship to a specified item. You can send this message explicitly, or by using the TreeView_GetNextItem macro or one of the related macros.

Parameters

hwnd and hitem

Handle to the tree-view control, and the handle to an item.

flag

Flag specifying the item to retrieve. This parameter can be one of the following values:

Value	Message
TVGN_CARET	Retrieves the currently selected item.
TVGN_CHILD	Retrieves the first child item. The hitem parameter must be NULL.
TVGN_DROPHILITE	Retrieves the item that is the target of a drag-and-drop operation.
TVGN_FIRSTVISIBLE	Retrieves the first visible item.
TVGN_NEXT	Retrieves the next sibling item.
TVGN_NEXTVISIBLE	Retrieves the next visible item that follows the specified item. The specified item must be visible. Use the TVM_GETITEMRECT message to determine whether an item is visible.
TVGN_PARENT	Retrieves the parent of the specified item.
TVGN_PREVIOUS	Retrieves the previous sibling item.
TVGN_PREVIOUSVISIBLE	Retrieves the first visible item that precedes the specified item. The specified item must be visible. Use the TVM_GETITEMRECT message to determine whether an item is visible.
TVGN_ROOT	Retrieves the topmost or very first item of the tree-view control.
Return Value

Returns the handle to the item if successful or NULL otherwise.

See Also

TVM_GETITEMRECT


TVM_GETVISIBLECOUNT [New - Windows NT]
 TVM_GETVISIBLECOUNT  QuickInfo  Overview  Group

[New - Windows NT]

TVM_GETVISIBLECOUNT

wParam = 0;

lParam = 0;

// Corresponding macro

UINT TreeView_GetVisibleCount(hwnd);

The TVM_GETVISIBLECOUNT message obtains the number of items that are fully visible in the client window of a tree-view control. You can send this message explicitly, or by using the TreeView_GetVisibleCount macro.

Parameters

hwnd

Handle to the tree-view control.

Return Value

Returns the number of items that are fully visible in the client window of the tree-view control.

Remarks

Note that the return value is the number of fully-visible items. If you can see all of 20 items, and part of one more item, the return value is 20, not 21.


TVM_HITTEST [New - Windows NT]
 TVM_HITTEST  QuickInfo  Overview  Group

[New - Windows NT]

TV_HITTEST

wParam = 0;

lParam = (LPARAM) (LPTV_HITTESTINFO) lpht;

// Corresponding macro

HTREEITEM TreeView_HitTest(hwnd, lpht);

The TVM_HITTEST message determines the location of the specified point relative to the client area of a tree-view control. You can send this message explicitly or by using the TreeView_HitTest macro.

Parameters

hwnd

Handle to the tree-view control.

lpht

Pointer to a TV_HITTESTINFO structure. When the message is sent, the pt member specifies the coordinates of the point to test. When the message returns, the hItem member is the handle to the item at the specified point or NULL if no item occupies the point. Also, when the message returns, the flags member is a hit-test value that indicates the location of the specified point. For a list of hit-test values, see the description of the TV_HITTESTINFO structure.

Return Value

Returns the handle to the tree-view item that occupies the specified point or NULL if no item occupies the point.

See Also

TV_HITTESTINFO


TVM_INSERTITEM [New - Windows NT]
 TVM_INSERTITEM  QuickInfo  Overview  Group

[New - Windows NT]

TVM_INSERTITEM

wParam = 0;

lParam = (LPARAM) (LPTV_INSERTSTRUCT) lpis;

// Corresponding macro

HTREEITEM TreeView_InsertItem(hwnd, lpis);

The TVM_INSERTITEM message inserts a new item in a tree-view control. You can send this message explicitly or by using the TreeView_InsertItem macro.

Parameters

hwnd

Handle to the tree-view control.

lpis

Pointer to a TV_INSERTSTRUCT structure that specifies the attributes of the tree-view item.

If the item label is being edited, the edit operation is canceled and the parent window receives the TVN_ENDLABELEDIT notification message.

Return Value

Returns the handle to the new item if successful or NULL otherwise.

See Also

TV_INSERTSTRUCT, TVN_ENDLABELEDIT


TVM_SELECTITEM [New - Windows NT]
 TVM_SELECTITEM  QuickInfo  Overview  Group

[New - Windows NT]

TV_SELECTITEM

wParam = (WPARAM) flag;

lParam = (LPARAM) (HTREEITEM) hitem;

// Corresponding macro

BOOL TreeView_Select(hwnd, hitem, flag);

// Related macros

BOOL TreeView_SelectDropTarget(hwnd, hitem);

BOOL TreeView_SelectItem(hwnd, hitem);

BOOL TreeView_SelectSetFirstVisible(hwnd, hitem);

The TVM_SELECTITEM message selects the specified tree-view item, scrolls the item into view, or redraws the item in the style used to indicate the target of a drag-and-drop operation. You can send this message explicitly or by using the TreeView_Select, TreeView_SelectItem, or TreeView_SelectDropTarget macro.

Parameters

hwnd and hitem

Handle to the tree-view control, and the handle to an item. If hitem is NULL, the selection is removed from the currently selected item, if any.

flag

Action flag. This parameter can be one of the following values:

Value	Meaning
TVGN_CARET	Sets the selection to the given item.
TVGN_DROPHILITE	Redraws the given item in the style used to indicate the target of a drag and drop operation.
TVGN_FIRSTVISIBLE	Scrolls the tree view vertically so that the given item is the first visible item.
Return Value

Returns TRUE if successful or FALSE otherwise.

Remarks

If the TVGN_CARET value is specified, the parent window receives the TVN_SELCHANGING and TVN_SELCHANGED notification messages. Also, if the specified item is the child of a collapsed parent item, the parent's list of child items is expanded to reveal the specified item. In this case, the parent window receives the TVN_ITEMEXPANDING and TVN_ITEMEXPANDED notification messages.

Using the TreeView_SelectItem macro is equivalent to sending the TVM_SELECTITEM message with flag set to the TVGN_CARET value. Using the TreeView_SelectDropTarget macro is equivalent to sending the TVM_SELECTITEM message with flag set to the TVGN_DROPHILITE value. Using TreeView_SelectSetFirstVisible is equivalent to sending the TVM_SELECTITEM message with flag set to the TVGN_FIRSTVISIBLE value.

See Also

TVN_ITEMEXPANDED, TVN_ITEMEXPANDING, TVN_SELCHANGED, TVN_SELCHANGING


TVM_SETIMAGELIST [New - Windows NT]
 TVM_SETIMAGELIST  QuickInfo  Overview  Group

[New - Windows NT]

TVM_SETIMAGELIST

wParam = (WPARAM) iImage;

lParam = (LPARAM) (HIMAGELIST) himl;

// Corresponding macro

HIMAGELIST TreeView_SetImageList(hwnd, himl, iImage);

The TVM_SETIMAGELIST message sets the normal or state image list for a tree-view control and redraws the control using the new images. You can send this message explicitly or by using the TreeView_SetImageList macro.

Parameters

hwnd and himl

Handle to the tree-view control, and the handle to the image list. If himl is NULL, all images are removed from the tree-view control.

iImage

Type of image list to set. For a list of possible values, see the description of the TVM_GETIMAGELIST message.

Return Value

Returns the handle to the previous image list, if any, or NULL otherwise.

See Also

TVM_GETIMAGELIST


TVM_SETINDENT [New - Windows NT]
 TVM_SETINDENT  QuickInfo  Overview  Group

[New - Windows NT]

TVM_SETINDENT

wParam = (WPARAM) indent;

lParam = 0;

// Corresponding macro

BOOL TreeView_SetIndent(hwnd, indent);

The TVM_SETINDENT message sets the width of indentation for a tree-view control and redraws the control to reflect the new width. You can send this message explicitly or by using the TreeView_SetIndent macro.

Parameters

hwnd

Handle to the tree-view control.

indent

Width, in pixels, of the indentation. If this parameter is less than the system-defined minimum width, the new width is set to the system-defined minimum.

Return Value

No return value.


TVM_SETITEM [New - Windows NT]
 TVM_SETITEM  QuickInfo  Overview  Group

[New - Windows NT]

TVM_SETITEM

wParam = 0;

lParam = (LPARAM) (const TV_ITEM FAR*) pitem;

// Corresponding macro

BOOL TreeView_SetItem(hwnd, pitem);

The TVM_SETITEM sets some or all of a tree-view item's attributes. You can send this message explicitly or by using the TreeView_SetItem macro.

Parameters

hwnd

Handle to the tree-view control.

pitem

Pointer to a TV_ITEM structure that contains the new item attributes. The hItem member identifies the item, and the mask member specifies which attributes to set.

If mask specifies the TVIF_TEXT value, the pszText member is the pointer to a null-terminated string and the cchTextMax member is ignored.

If mask specifies the TVIF_STATE value, the stateMask member indicates which item states to change and the state member contains the values for those states.

Return Value

Returns zero if successful or  − 1 otherwise.

See Also

TV_ITEM


TVM_SORTCHILDREN [New - Windows NT]
 TVM_SORTCHILDREN  QuickInfo  Overview  Group

[New - Windows NT]

TVM_SORTCHILDREN

wParam = 0;  // reserved for future use; must be zero

lParam = (LPARAM) (HTREEITEM) hitem;

// Corresponding macro

BOOL TreeView_SortChildren(hwnd, hitem, fRecurse);

The TVM_SORTCHILDREN message sorts the child items of the specified parent item in a tree-view control. You can send this message explicitly or by using the TreeView_SortChildren macro.

Parameters

hwnd and hitem

Handle to the tree-view control, and the handle to the parent item whose child items are to be sorted.

fRecurse

Reserved for future use. Must be zero.

Return Value

Returns TRUE if successful or FALSE otherwise.


TVM_SORTCHILDRENCB [New - Windows NT]
 TVM_SORTCHILDRENCB  QuickInfo  Overview  Group

[New - Windows NT]

TVM_SORTCHILDRENCB

wParam = 0;  // reserved for future use; must be zero

lParam = (LPARAM) (LPTV_SORTCB) psort;

// Corresponding macro

BOOL TreeView_SortChildrenCB(hwnd, psort, fRecurse);

The TVM_SORTCHILDRENCB message sorts tree-view items using an application-defined callback function that compares the items. You can send this message explicitly or by using the TreeView_SortChildrenCB macro.

Parameters

hwnd

Handle to the tree-view control.

psort

Pointer to a TV_SORTCB structure. The lpfnCompare member is the pointer to the application-defined callback function, which is called during the sort operation each time the relative order of two list items needs to be compared. For more information about the callback function, see the description of TV_SORTCB.

fRecurse

Reserved for future use. Must be zero.

Return Value

Returns TRUE if successful or FALSE otherwise.

See Also

TV_SORTCB


TVN_BEGINDRAG [New - Windows NT]
 TVN_BEGINDRAG  QuickInfo  Overview  Group

[New - Windows NT]

TVN_BEGINDRAG

pnmtv = (NM_TREEVIEW FAR *) lParam

The TVN_BEGINDRAG notification message notifies a tree-view control's parent window that a drag-and-drop operation involving the left mouse button is being initiated. This notification message is sent in the form of a WM_NOTIFY message.

Parameters

pnmtv

Pointer to an NM_TREEVIEW structure. The itemNew member is a TV_ITEM structure that contains valid information about the item being dragged in the hItem, state, and lParam members. The ptDrag member specifies the current screen coordinates of the mouse.

Return Value

No return value.

Remarks

A tree-view control that has the TVS_DISABLEDRAGDROP style does not send this notification message.

See Also

NM_TREEVIEW, TV_ITEM, WM_NOTIFY


TVN_BEGINLABELEDIT [New - Windows NT]
 TVN_BEGINLABELEDIT  QuickInfo  Overview  Group

[New - Windows NT]

TVN_BEGINLABELEDIT

ptvdi = (TV_DISPINFO FAR *) lParam

The TVN_BEGINLABELEDIT notification message notifies a tree-view control's parent window about the start of label editing for an item. This notification message is sent in the form of a WM_NOTIFY message.

Parameters

ptvdi

Pointer to a TV_DISPINFO structure. The item member is a TV_ITEM structure that contains valid information about the item being edited in the hItem, state, lParam, and pszText members.

Return Value

Returns TRUE to cancel label editing.

See Also

TV_DISPINFO, TV_ITEM, WM_NOTIFY


TVN_BEGINRDRAG [New - Windows NT]
 TVN_BEGINRDRAG  QuickInfo  Overview  Group

[New - Windows NT]

TVN_BEGINRDRAG

pnmtv = (NM_TREEVIEW FAR *) lParam

The TVN_BEGINRDRAG notification message notifies a tree-view control's parent window about the initiation of a drag-and-drop operation involving the right mouse button. This notification message is sent in the form of a WM_NOTIFY message.

Parameters

pnmtv

Pointer to an NM_TREEVIEW structure. The itemNew member is a TV_ITEM structure that contains valid information in the hItem, state, and lParam members about the item to be dragged. The ptDrag member specifies the current screen coordinates of the mouse.

Return Value

No return value.

See Also

NM_TREEVIEW, TV_ITEM, WM_NOTIFY


TVN_DELETEITEM [New - Windows NT]
 TVN_DELETEITEM  QuickInfo  Overview  Group

[New - Windows NT]

TVN_DELETEITEM

pnmtv = (NM_TREEVIEW FAR *) lParam

The TVN_DELETEITEM notification message notifies a tree-view control's parent window that an item has been deleted. This notification message is sent in the form of a WM_NOTIFY message.

Parameters

pnmtv

Pointer to an NM_TREEVIEW structure. The itemOld member is a TV_ITEM structure containing valid information about the item that was deleted in the hItem and lParam members.

Return Value

No return value.

See Also

NM_TREEVIEW, TV_ITEM, WM_NOTIFY


TVN_ENDLABELEDIT [New - Windows NT]
 TVN_ENDLABELEDIT  QuickInfo  Overview  Group

[New - Windows NT]

TVN_ENDLABELEDIT

ptvdi = (TV_DISPINFO FAR *) lParam

The TVN_ENDLABELEDIT notification message notifies a tree-view control's parent window about the end of label editing for an item. This notification message is sent in the form of a WM_NOTIFY message.

Parameters

ptvdi

Pointer to a TV_DISPINFOstructure. The item member is a TV_ITEM structure containing valid information about the item that was edited in the hItem, lParam, and pszText members. If label editing was canceled, the pszText member is zero.

Return Value

No return value.

See Also

WM_NOTIFY, TV_DISPINFO, TV_ITEM


TVN_GETDISPINFO [New - Windows NT]
 TVN_GETDISPINFO  QuickInfo  Overview  Group

[New - Windows NT]

TVN_GETDISPINFO

ptvdi = (TV_DISPINFO FAR *) lParam

The TVN_GETDISPINFO notification message requests that a tree-view control's parent window provide information needed to display or sort an item. This notification message is sent in the form of a WM_NOTIFY message.

Parameters

ptvdi

Pointer to a TV_DISPINFO structure. The item member is a TV_ITEM structure whose mask, hItem, state, and lParam members specify the type of information required. You must fill the members of the structure with the appropriate information.

Return Value

No return value.

Remarks

See Also

TV_DISPINFO, TV_ITEM, WM_NOTIFY


TVN_ITEMEXPANDED [New - Windows NT]
 TVN_ITEMEXPANDED  QuickInfo  Overview  Group

[New - Windows NT]

TVN_ITEMEXPANDED

pnmtv = (NM_TREEVIEW FAR *) lParam

The TVN_ITEMEXPANDED notification message notifies a tree-view control's parent window that a parent item's list of child items has expanded or collapsed. This notification message is sent in the form of a WM_NOTIFY message.

Parameters

pnmtv

Pointer to an NM_TREEVIEW structure. The itemNew member is a TV_ITEM structure that contains valid information about the parent item in the hItem, state, and lParam members. The action member indicates whether the list expanded or collapsed. For a list of possible values, see the description of the TVM_EXPAND message.

Return Value

No return value.

See Also

NM_TREEVIEW, TV_ITEM, TVM_EXPAND, WM_NOTIFY


TVN_ITEMEXPANDING [New - Windows NT]
 TVN_ITEMEXPANDING  QuickInfo  Overview  Group

[New - Windows NT]

TVN_ITEMEXPANDING

pnmtv = (NM_TREEVIEW FAR *) lParam

The TVN_ITEMEXPANDING notification message notifies a tree-view control's parent window that a parent item's list of child items is about to expand or collapse. This notification message is sent in the form of a WM_NOTIFY message.

Parameters

pnmtv

Pointer to an NM_TREEVIEW structure. The itemNew member is a TV_ITEM structure that contains valid information about the parent item in the hItem, state, and lParam members. The action member indicates whether the list is to expand or collapse. For a list of possible values, see the description of the TVM_EXPAND message.

Return Value

Returns TRUE to prevent the list from expanding or collapsing.

See Also

NM_TREEVIEW, TV_ITEM, TVM_EXPAND, WM_NOTIFY


TVN_KEYDOWN [New - Windows NT]
 TVN_KEYDOWN  QuickInfo  Overview  Group

[New - Windows NT]

TVN_ITEMEXPANDING

ptvkd = (TV_KEYDOWN FAR *) lParam

The TVN_KEYDOWN notification message notifies a tree-view control's parent window that the user pressed a key and the tree-view control has the input focus. This notification message is sent in the form of a WM_NOTIFY message.

Parameters

ptvkd

Pointer to a TV_KEYDOWN structure. The wVKey member specifies the virtual-key code.

Return Value

No return value.

See Also

TV_KEYDOWN, WM_NOTIFY


TVN_SELCHANGED [New - Windows NT]
 TVN_SELCHANGED  QuickInfo  Overview  Group

[New - Windows NT]

TVN_SELCHANGED

pnmtv = (NM_TREEVIEW FAR *) lParam

The TVN_SELCHANGED notification message notifies a tree-view control's parent window that the selection has changed from one item to another. This notification message is sent in the form of a WM_NOTIFY message.

Parameters

pnmtv

Pointer to an NM_TREEVIEW structure. The itemOld and itemNew members are TV_ITEM structures that contain information about the previously selected item and the newly selected items in the hItem, state, and lParam members. The stateMask members in the TV_ITEM structures specified by itemOld and itemNew are undefined on input. The action member indicates the type of action that caused the selection to change; it can be one of the following values:

Value	Meaning
TVC_BYKEYBOARD	By a key stroke
TVC_BYMOUSE	By a mouse click
TVC_UNKNOWN	Unknown
Return Value

No return value.

See Also

NM_TREEVIEW, WM_NOTIFY


TVN_SELCHANGING [New - Windows NT]
 TVN_SELCHANGING  QuickInfo  Overview  Group

[New - Windows NT]

TVN_SELCHANGING

pnmtv = (NM_TREEVIEW FAR *) lParam

The TVN_SELCHANGING notification message notifies a tree-view control's parent window that the selection is about to change from one item to another. This notification message is sent in the form of a WM_NOTIFY message.

Parameters

pnmtv

Pointer to an NM_TREEVIEW structure. The itemOld and itemNew members contain valid information about the currently selected item and the newly selected item. The action member indicates whether a mouse or keyboard action is causing the selection to change. For a list of possible values, see the description of the TVN_SELCHANGED notification message.

Return Value

Returns TRUE to prevent the selection from changing.

See Also

NM_TREEVIEW, TVN_SELCHANGED, WM_NOTIFY


TVN_SETDISPINFO [New - Windows NT]
 TVN_SETDISPINFO  QuickInfo  Overview  Group

[New - Windows NT]

TVN_SETDISPINFO

ptvdi = (TV_DISPINFO FAR *) lParam

The TVN_SETDISPINFO notification message notifies a tree-view control's parent window that it must update the information it maintains about an item. This notification message is sent in the form of a WM_NOTIFY message.

Parameters

ptvdi

Pointer to a TV_DISPINFO structure. The item member is a TV_ITEM structure that contains valid information about the item in the hItem and lParam members.

Return Value

No return value.

Remarks

The system sends this notification message when the user has finished editing the label of an item whose text is set to LPSTR_TEXTCALLBACK. The notification gives the parent window the opportunity to store the new item text.

See Also

TV_DISPINFO, TV_ITEM, WM_NOTIFY


UDM_GETACCEL [New - Windows NT]
 UDM_GETACCEL  QuickInfo  Overview  Group

[New - Windows NT]

UDM_GETACCEL

wParam = (WPARAM) cAccels;

lParam = (LPARAM) (LPUDACCEL) paAccels;

The UDM_GETACCEL message retrieves acceleration information for an up-down control.

Parameters

cAccels

Number of elements in the array specified by paAccels.

paAccels

Address of an array of UDACCEL structures that receives acceleration information.

Return Value

The return value is the number of accelerator structures retrieved.

See Also

UDACCEL


UDM_GETBASE [New - Windows NT]
 UDM_GETBASE  QuickInfo  Overview  Group

[New - Windows NT]

UDM_GETBASE

wParam = 0;

lParam = 0;

The UDM_GETBASE message retrieves the current radix base (that is, either base 10 or 16) for an up-down control.

Return Value

The return value is the current base value.


UDM_GETBUDDY [New - Windows NT]
 UDM_GETBUDDY  QuickInfo  Overview  Group

[New - Windows NT]

UDM_GETBUDDY

wParam = 0;

lParam = 0;

The UDM_GETBUDDY message retrieves the handle of the current buddy window.

Return Value

The return value is the handle of the current buddy window.


UDM_GETPOS [New - Windows NT]
 UDM_GETPOS  QuickInfo  Overview  Group

[New - Windows NT]

UDM_GETPOS

wParam = 0;

lParam = 0;

The UDM_GETPOS message retrieves the current position of an up-down control.

Return Value

The return value is the current position in the low-order word. If an error occurred, the high-order word is nonzero.

Remarks

When processing this message, the up-down control updates its current position based on the caption of the buddy window. The up-down control returns an error if there is no buddy window or if the caption specifies an invalid or out-of-range value.


UDM_GETRANGE [New - Windows NT]
 UDM_GETRANGE  QuickInfo  Overview  Group

[New - Windows NT]

UDM_GETRANGE

wParam = 0;

lParam = 0;

The UDM_GETRANGE message retrieves the minimum and maximum positions (range) for an up-down control.

Return Value

The return value is a 32-bit value that contains the minimum and maximum positions. The low-order word is the maximum position for the control, and the high-order word is the minimum position.


UDM_SETACCEL [New - Windows NT]
 UDM_SETACCEL  QuickInfo  Overview  Group

[New - Windows NT]

UDM_SETACCEL

wParam = (WPARAM) nAccels;

lParam = (LPARAM) (LPUDACCEL) aAccels;

The UDM_SETACCEL message sets the acceleration for an up-down control.

Parameters

nAccels

Number of UDACCEL structures specified by aAccels.

aAccels

Address of an array of UDACCEL structures that contains acceleration information. Elements should be sorted in ascending order based on the nSec member.

Return Value

Returns TRUE if successful or FALSE otherwise.

See Also

UDACCEL


UDM_SETBASE [New - Windows NT]
 UDM_SETBASE  QuickInfo  Overview  Group

[New - Windows NT]

UDM_SETBASE

wParam = (WPARAM) nBase;

lParam = 0;

The UDM_SETBASE message sets the radix base for an up-down control. The base value determines whether the buddy window displays numbers in decimal or hexadecimal digits. Hexadecimal numbers are always unsigned, and decimal numbers are signed.

Parameters

nBase

New base value for the control. This parameter can be 10 for decimal or 16 for hexadecimal.

Return Value

The return value is the previous base value. If an invalid base is given, the return value is zero.


UDM_SETBUDDY [New - Windows NT]
 UDM_SETBUDDY  QuickInfo  Overview  Group

[New - Windows NT]

UDM_SETBUDDY

wParam = (WPARAM) (HWND) hwndBuddy;

lParam = 0;

The UDM_SETBUDDY message sets the buddy window for an up-down control.

Parameters

hwndBuddy

Handle of the new buddy window.

Return Value

The return value is the handle of the previous buddy window.


UDM_SETPOS [New - Windows NT]
 UDM_SETPOS  QuickInfo  Overview  Group

[New - Windows NT]

UDM_SETPOS

wParam = 0;

lParam = (LPARAM) MAKELONG((short) nPos, 0);

The UDM_SETPOS message sets the current position for an up-down control.

Parameters

nPos

New position for the up-down control. This parameter must be in the range specified by the upper and lower limits for the control.

Return Value

The return value is the previous position.


UDM_SETRANGE [New - Windows NT]
 UDM_SETRANGE  QuickInfo  Overview  Group

[New - Windows NT]

UDM_SETRANGE

wParam = 0;

lParam = (LPARAM) MAKELONG((short) nUpper, (short) nLower);

The UDM_SETRANGE message sets the minimum and maximum positions (range) for an up-down control.

Parameters

nUpper and nLower

Maximum position and minimum position for the up-down control. Neither position can be greater than the UD_MAXVAL value or less than the UD_MINVAL value. In addition, the difference between the two positions cannot exceed UD_MAXVAL.

Return Value

No return value.

Remarks

The maximum position can be less than the minimum position. Clicking the up arrow moves the current position closer to the maximum position, and clicking the down arrow moves towards the minimum position.


UDN_DELTAPOS [New - Windows NT]
 UDN_DELTAPOS  Overview  Group

[New - Windows NT]

UDN_DELTAPOS

pnmud = (NM_UPDOWN FAR *) lParam

The operating system sends the UDN_DELTAPOS notification message to the parent window of an up-down control when the position of the control is about to change. This happens when the user requests a change in the value by pressing the control's up or down arrow. The UDN_DELTAPOS message is sent before the WM_VSCROLL message that actually changes the control's position. This lets you examine, allow, modify, or disallow the change. The UDN_DELTAPOS message is sent in the form of a WM_NOTIFY message.

Parameters

pnmud

Pointer to an NM_UPDOWN structure that contains information about the position change.

The iPos member of this structure contains the current position of the control.

The iDelta member of the structure is a signed integer that contains the proposed change in position. If the user has clicked on the up button, this is a positive value. If the user has clicked on the down button, this is a negative value.

Return Value

Return TRUE in response to this message to prevent the change in the control's position.

Return FALSE to allow the change in the control's position.

See Also

NM_UPDOWN, WM_COMMAND, WM_VSCROLL


WM_ACTIVATE
 WM_ACTIVATE  QuickInfo  Overview  Group

WM_ACTIVATE

fActive = LOWORD(wParam);           // activation flag

fMinimized = (BOOL) HIWORD(wParam); // minimized flag

hwnd = (HWND) lParam;               // window handle

The WM_ACTIVATE message is sent when a window is being activated or deactivated. This message is sent first to the window procedure of the top-level window being deactivated; it is then sent to the window procedure of the top-level window being activated.

Parameters

fActive

Value of the low-order word of wParam. Specifies whether the window is being activated or deactivated. This parameter can be one of the following values:

Value	Meaning
WA_ACTIVE	Activated by some method other than a mouse click (for example, by a call to the SetActiveWindow function or by use of the keyboard interface to select the window).
WA_CLICKACTIVE	Activated by a mouse click.
WA_INACTIVE	Deactivated.
fMinimized

Value of the high-order word of wParam. Specifies the minimized state of the window being activated or deactivated. A nonzero value indicates the window is minimized.

hwnd

Value of lParam. Identifies the window being activated or deactivated, depending on the value of the fActive parameter. If the value of fActive is WA_INACTIVE, hwnd is the handle of the window being activated. If the value of fActive is WA_ACTIVE or WA_CLICKACTIVE, hwnd is the handle of the window being deactivated. This handle can be NULL.

Return Value

If an application processes this message, it should return zero.

Default Action

If the window is being activated and is not minimized, the DefWindowProc function sets the keyboard focus to the window.

Remarks

If the window is activated by a mouse click, it also receives a WM_MOUSEACTIVATE message.

See Also

DefWindowProc, SetActiveWindow, WM_MOUSEACTIVATE, WM_NCACTIVATE


WM_ACTIVATEAPP
 WM_ACTIVATEAPP  QuickInfo  Overview  Group

WM_ACTIVATEAPP

fActive = (BOOL) wParam;        // activation flag

dwThreadID = (DWORD) lParam:    // thread identifier

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.

Parameters

fActive

Value of wParam. Specifies whether the window is being activated or deactivated. This parameter is TRUE if the window is being activated; it is FALSE if the window is being deactivated.

dwThreadID

Value of lParam. Specifies a thread identifier. If the fActive parameter is TRUE, dwThreadID is the identifier of the thread that owns the window being deactivated. If fActive is FALSE, dwThreadID is the identifier of the thread that owns the window being activated.

Return Value

If an application processes this message, it should return zero.

See Also

WM_ACTIVATE


WM_ASKCBFORMATNAME
 WM_ASKCBFORMATNAME  QuickInfo  Overview  Group

WM_ASKCBFORMATNAME

cchName = (DWORD) wParam            // size of buffer

lpszFormatName = (LPTSTR) lParam    // buffer to receive format name

The WM_ASKCBFORMATNAME message is sent to the clipboard owner by a clipboard viewer window to request the name of a CF_OWNERDISPLAY clipboard format.

Parameters

cchName

Value of wParam. Specifies the size, in characters, of the buffer pointed to by the lpszFormatName parameter.

lpszFormatName

Value of lParam. Points to the buffer that is to receive the clipboard format name.

Return Value

If an application processes this message, it should return zero.

Remarks

In response to this message, the clipboard owner should copy the name of the owner-display format to the specified buffer, not exceeding the buffer size specified by the cchName parameter.

A clipboard viewer window sends this message to the clipboard owner to determine the name of the CF_OWNERDISPLAY format — for example, to initialize a menu listing available formats.


WM_CANCELJOURNAL
 WM_CANCELJOURNAL  QuickInfo

WM_CANCELJOURNAL

wParam = 0; // not used, must be zero

lParam = 0; // not used, must be zero

The WM_CANCELJOURNAL message is posted to an application when a user cancels the application's journaling activities. The message is posted with a NULL window handle.

Parameters

This message has no parameters.

Return Value

This message does not return a value. It is meant to be processed from within an application's main loop or a GetMessage hook procedure, not from a window procedure.

Remarks

Journal record and playback modes are modes imposed on the system that let an application sequentially record or play back user input. The system enters these modes when an application installs a JournalRecordProc or JournalPlaybackProc hook procedure. When the system is in either of these journaling modes, applications must take turns reading input from the input queue. If any one application stops reading input while the system is in a journaling mode, other applications are forced to wait.

To ensure a robust system, one that cannot be hung up by any one application, Windows NT automatically cancels any journalling activities when a user presses CTRL+ESC, ALT+ESC, or CTRL+ALT+DEL. The system then unhooks any journaling hook procedures, and posts a WM_CANCELJOURNAL message, with a NULL window handle, to the application that set the journaling hook.

Since the WM_CANCELJOURNAL has a NULL window handle, it cannot be dispatched to a window procedure. There are two ways for an application to see a WM_CANCELJOURNAL message: If the application is running in its own main loop, it must catch the message between its call to GetMessage or PeekMessage and its call to DispatchMessage. If the application is not running in its own main loop, it must set a GetMsgProc hook procedure (via a call to SetWindowsHookEx specifying the WH_GETMESSAGE hook type) that watches for the message.

When an application sees a WM_CANCELJOURNAL message, it can assume two things: the user has intentionally cancelled the journal record or playback mode, and the system has already unhooked any journal record or playback hook procedures.

Note that the key combinations mentioned above (CTRL+ESC, ALT+ESC, or CTRL+ALT+DEL) cause the system to cancel journaling. If any one application is hung, they give the user a means of recovery. The VK_CANCEL virtual keycode (usually implemented as the CTRL+BREAK key combination) is what an application that is in journal record mode should watch for as a signal that the user wishes to cancel the journaling activity. The difference is that watching for VK_CANCEL is a suggested behavior for journaling applications, whereas CTRL+ESC, ALT+ESC, or CTRL+ALT+DEL cause the system to cancel journalling regardless of a journalling application's behavior.

See Also

DispatchMessage, GetMessage, JournalPlaybackProc, JournalRecordProc, GetMsgProc, PeekMessage, SetWindowsHookEx


WM_CANCELMODE
 WM_CANCELMODE  QuickInfo  Overview  Group

WM_CANCELMODE

The WM_CANCELMODE message is sent to the focus window when a dialog box or message box is displayed; this enables the focus window to cancel modes, such as mouse capture.

Parameters

This message has no parameters.

Return Value

If an application processes this message, it should return zero.

Default Action

The DefWindowProc function cancels internal processing of standard scroll bar input, cancels internal menu processing, and releases the mouse capture.

See Also

DefWindowProc, ReleaseCapture


WM_CAPTURECHANGED [New - Windows 95]
 WM_CAPTURECHANGED  QuickInfo  Overview  Group

[New - Windows 95]

WM_CAPTURECHANGED

hwndNewCapture = (HWND) lParam;    // handle of window to gain mouse capture

The WM_CAPTURECHANGED message is sent to the window that is losing the mouse capture.

Parameters

hwndNewCapture

Value of lParam. Identifies the window that is gaining the mouse capture.

Return Value

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.

See Also

ReleaseCapture, SetCapture


WM_CHANGECBCHAIN
 WM_CHANGECBCHAIN  QuickInfo  Overview  Group

WM_CHANGECBCHAIN

hwndRemove = (HWND) wParam;     // handle of window being removed

hwndNext = (HWND) lParam;       // handle of next window in chain

The WM_CHANGECBCHAIN message is sent to the first window in the clipboard viewer chain when a window is being removed from the chain.

Parameters

hwndRemove

Value of wParam. Identifies the window being removed from the clipboard viewer chain.

hwndNext

Value of lParam. Identifies the next window in the chain following the window being removed. This parameter is NULL if the window being removed is the last window in the chain.

Return Value

If an application processes this message, it should return zero.

Remarks

Each clipboard viewer window saves the handle of the next window in the clipboard viewer chain. Initially, this handle is the return value of the SetClipboardViewer function.

When a clipboard viewer window receives the WM_CHANGECBCHAIN message, it should call the SendMessage function to pass the message to the next window in the chain, unless the next window is the window being removed. In this case, the clipboard viewer should save the handle specified by hwndNext as the next window in the chain.

See Also

SendMessage, SetClipboardViewer


WM_CHAR
 WM_CHAR  QuickInfo  Overview  Group

WM_CHAR

chCharCode = (TCHAR) wParam;    // character code

lKeyData = lParam;              // key data

The WM_CHAR message is posted to the window with the keyboard focus when a WM_KEYDOWN message is translated by the TranslateMessage function. WM_CHAR contains the character code of the key that was pressed.

Parameters

chCharCode

Value of wParam. Specifies the character code of the key.

lKeyData

Value of lParam. Specifies the repeat count, scan code, extended-key flag, context code, previous key-state flag, and transition-state flag, as shown in the following table:

Value	Description
0−15	Specifies the repeat count. The value is the number of times the keystroke is repeated as a result of the user holding down the key.
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 Value

An application should return zero if it processes this message.

Remarks

Because there is not necessarily a one-to-one correspondence between keys pressed and character messages generated, the information in the high-order word of the lKeyData parameter is generally not useful to applications. The information in the high-order word applies only to the most recent WM_KEYDOWN message that precedes the posting of the WM_CHAR message.

For enhanced 101- and 102-key keyboards, extended keys are the right ALT and the right CTRL keys on the main section of the keyboard; the INS, DEL, HOME, END, PAGE UP, PAGE DOWN and arrow keys in the clusters to the left of the numeric keypad; and the divide (/) and ENTER keys in the numeric keypad. Some other keyboards may support the extended-key bit in the lKeyData parameter.

See Also

TranslateMessage, WM_KEYDOWN


WM_CHARTOITEM
 WM_CHARTOITEM  QuickInfo  Overview  Group

WM_CHARTOITEM

nKey = LOWORD(wParam);          // key value

nCaretPos = HIWORD(wParam);     // caret position

hwndListBox = (HWND) lParam;    // handle of list box

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.

Parameters

nKey

Value of the low-order word of wParam. Specifies the value of the key the user pressed.

nCaretPos

Value of the high-order word of wParam. Specifies the current position of the caret.

hwndListBox

Value of lParam. Identifies the list box.

Return Value

The return value specifies the action that the application performed in response to the message. A return value of −1 or −2 indicates that the application handled all aspects of selecting the item and requires no further action by the list box. A return value of 0 or greater specifies the zero-based index of an item in the list box and indicates that the list box should perform the default action for the keystroke on the given item.

Default Action

The DefWindowProc function returns −1.

Remarks

Only owner-drawn list boxes that do not have the LBS_HASSTRINGS style can receive this message.

See Also

DefWindowProc, WM_CHAR, WM_VKEYTOITEM


WM_CHILDACTIVATE
 WM_CHILDACTIVATE  QuickInfo  Overview  Group

WM_CHILDACTIVATE

The WM_CHILDACTIVATE message is sent to a multiple document interface (MDI) child window when the user clicks the window's title bar or when the window is activated, moved, or sized.

Parameters

This message has no parameters.

Return Value

If an application processes this message, it should return zero.

See Also

MoveWindow, SetWindowPos


WM_CHOOSEFONT_GETLOGFONT
 WM_CHOOSEFONT_GETLOGFONT  QuickInfo

WM_CHOOSEFONT_GETLOGFONT

wParam = 0;                // not used, must be zero

lParam = (LPLOGFONT) lplf; // address of struct. with font data

An application sends a WM_CHOOSEFONT_GETLOGFONT message to the Font dialog box created by the ChooseFont function to retrieve the current LOGFONT structure.

Parameters

lplf

Points to a LOGFONT structure that receives information about the current logical font.

Return Value

This message does not return a value.

Remarks

An application uses this message to retrieve the LOGFONT structure while the Font dialog box is open. When the user closes the dialog box, the ChooseFont function receives information about the LOGFONT structure.

See Also

ChooseFont, WM_GETFONT, LOGFONT


WM_CHOOSEFONT_SETFLAGS
 WM_CHOOSEFONT_SETFLAGS  Overview  Group

WM_CHOOSEFONT_SETFLAGS

wParam = 0;                   // not used, must be zero

lParam = (LPCHOOSEFONT) lpcf; // address of struct. with flags data

Sent to a Font dialog box (created by the ChooseFont function) to set the display options for the dialog box.

Parameters

lpcf

Address of a CHOOSEFONT structure that contains new settings in the Flags member.

Return Value

No return value.

Remarks

This message is intended to be sent from the hook function for the Font dialog box to set display options while the dialog box is still open. The hook function, if any, is specified by the lpfnHook member of the CHOOSEFONT structure passed to ChooseFont.

See Also

ChooseFont, CHOOSEFONT


WM_CHOOSEFONT_SETLOGFONT
 WM_CHOOSEFONT_SETLOGFONT  Overview  Group

WM_CHOOSEFONT_SETLOGFONT

wParam = 0;                // not used, must be zero

lParam = (LPLOGFONT) lplf; // address of struct. with font data

Sent to a Font dialog box (created by the ChooseFont function) to set the current logical font information.

Parameters

lplf

Address of a LOGFONT structure that contains information about the current logical font.

Return Value

No return value.

Remarks

This message is intended to be sent from the hook function for the Font dialog box to set the font attributes while the dialog box is still open. The hook function, if any, is specified by the lpfnHook member of the CHOOSEFONT structure passed to ChooseFont.

See Also

ChooseFont, CHOOSEFONT


WM_CLEAR
 WM_CLEAR  QuickInfo

WM_CLEAR

wParam = 0; // not used; must be zero

lParam = 0; // not used; must be zero

An application sends a WM_CLEAR message to an edit control or combo box to delete (clear) the current selection, if any, from the edit control.

Parameters

This message has no parameters.

Return Value

This message does not return a value.

Remarks

The deletion performed by the WM_CLEAR message can be undone by sending the edit control an EM_UNDO message.

To delete the current selection and place the deleted content on the clipboard, use the WM_CUT message.

When sent to a combo box, the WM_CLEAR message is handled by its edit control. This message has no effect when sent to a combo box with the CBS_DROPDOWNLIST style.

See Also

EM_UNDO, WM_COPY, WM_CUT, WM_PASTE


WM_CLOSE
 WM_CLOSE  QuickInfo  Overview  Group

WM_CLOSE

The WM_CLOSE message is sent as a signal that a window or an application should terminate.

Parameters

This message has no parameters.

Return Value

If an application processes this message, it should return zero.

Default Action

The DefWindowProc function calls the DestroyWindow function to destroy the window.

Remarks

An application can prompt the user for confirmation, prior to destroying a window, by processing the WM_CLOSE message and calling the DestroyWindow function only if the user confirms the choice.

See Also

DefWindowProc, DestroyWindow


WM_COMMAND
 WM_COMMAND  QuickInfo  Overview  Group

WM_COMMAND

wNotifyCode = HIWORD(wParam); // notification code

wID = LOWORD(wParam);         // item, control, or accelerator identifier

hwndCtl = (HWND) lParam;      // handle of control

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.

Parameters

wNotifyCode

Value of the high-order word of wParam. Specifies the notification code if the message is from a control. If the message is from an accelerator, this parameter is 1. If the message is from a menu, this parameter is 0.

wID

Value of the low-order word of wParam. Specifies the identifier of the menu item, control, or accelerator.

hwndCtl

Value of lParam. Identifies the control sending the message if the message is from a control. Otherwise, this parameter is NULL.

Return Value

If an application processes this message, it should return zero.

Remarks

Accelerator keystrokes that select items from the System 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 System 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.

See Also

WM_SYSCOMMAND


WM_COMPACTING
 WM_COMPACTING  QuickInfo

WM_COMPACTING

wCompactRatio = wParam; // compacting ratio

The WM_COMPACTING message is sent to all top-level windows when Windows 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.

Parameters

wCompactRatio

Value of wParam. Specifies the ratio of central processing unit (CPU) time currently spent by Windows compacting memory to CPU time currently spent by Windows performing other operations. For example, 0x8000 represents 50 percent of CPU time spent compacting memory.

Return Value

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 with Windows.


WM_COMPAREITEM
 WM_COMPAREITEM  QuickInfo  Overview  Group

WM_COMPAREITEM

idCtl = wParam;                       // control identifier

lpcis = (LPCOMPAREITEMSTRUCT) lParam; // structure with items

Windows 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, Windows sends this message to the owner of a combo box or list box created with the CBS_SORT or LBS_SORT style.

Parameters

idCtl

Value of wParam. Specifies the identifier of the control that sent the WM_COMPAREITEM message.

lpcis

Value of lParam. Points to a COMPAREITEMSTRUCT structure that contains the identifiers and application-supplied data for two items in the combo or list box.

Return Value

The return value indicates the relative position of the two items. It may be any of the following:

Value	Meaning
−1	Item 1 precedes item 2 in the sorted order.
0	Items 1 and 2 are equivalent in the sorted order.
1	Item 1 follows item 2 in the sorted order.
Remarks

When the owner of an owner-drawn combo box or list box receives this message, the owner returns a value indicating which of the items specified by the COMPAREITEMSTRUCT structure will appear before the other. Typically, Windows sends this message several times until it determines the exact position for the new item.

See Also

COMPAREITEMSTRUCT


WM_CONTEXTMENU [New - Windows NT]
 WM_CONTEXTMENU  QuickInfo  Overview  Group

[New - Windows NT]

hwnd = (HWND) wParam;

xPos = LOWORD(lParam);

yPos = HIWORD(lParam);

The WM_CONTEXTMENU message notifies a window that the user clicked the right mouse button (right clicked) in the window.

Parameters

hwnd

Handle to the window in which the user right clicked the mouse. This can be a child window of the window receiving the message. For more information about processing this message, see the Remarks section.

xPos

Horizontal position of the cursor, in screen coordinates, at the time of the mouse click.

yPos

Vertical position of the cursor, in screen coordinates, at the time of the mouse click.

Return Value

No return value.

Remarks

A window can process this message by displaying a context menu using the TrackPopupMenu or TrackPopupMenuEx function.

If a window does not display a context 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 context 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.

See Also

DefWindowProc, TrackPopupMenu, TrackPopupMenuEx, WM_NCRBUTTONUP, WM_RBUTTONUP


WM_COPY
 WM_COPY  QuickInfo  Overview  Group

WM_COPY

wParam = 0; // not used; must be zero

lParam = 0; // not used; must be zero

An application sends the WM_COPY message to an edit control or combo box to copy the current selection to the clipboard in CF_TEXT format.

Parameters

This message has no parameters.

Return Value

This message does not return a value.

Remarks

When sent to a combo box, the WM_COPY message is handled by its edit control. This message has no effect when sent to a combo box with the CBS_DROPDOWNLIST style.

See Also

WM_CLEAR, WM_CUT, WM_PASTE


WM_COPYDATA
 WM_COPYDATA  QuickInfo  Overview  Group

WM_COPYDATA

wParam = (WPARAM) (HWND) hwnd;            // handle of sending window

lParam = (LPARAM) (PCOPYDATASTRUCT) pcds; // pointer to structure with data

The WM_COPYDATA message is sent when an application passes data to another application.

Parameters

hwnd

Identifies the window passing the data.

pcds

Points to a COPYDATASTRUCT structure that contains the data to be passed.

Return Value

If the receiving application processes this message, it should return TRUE; otherwise, it should return FALSE.

Remarks

An application must use the SendMessage function to send this message, not the PostMessage function.

The data being passed must not contain pointers or other references to objects not accessible to the application receiving the data.

While this message is being sent, the referenced data must not be changed by another thread of the sending process.

The receiving application should consider the data read-only. The pcds parameter is valid only during the processing of the message. The receiving application should not free the memory referenced by pcds. If the receiving application must access the data after SendMessage returns, it must copy the data into a local buffer.

See Also

PostMessage, SendMessage, COPYDATASTRUCT


WM_CPL_LAUNCH
 WM_CPL_LAUNCH  QuickInfo  Overview  Group

WM_CPL_LAUNCH

hwnd = (HWND) wParam;          // handle of sending window

lpszAppName = (LPSTR) lParam;  // application-name string

An application sends the WM_CPL_LAUNCH message to Windows Control Panel to request that a Control Panel application be started.

Parameters

hwnd

Value of wParam. Specifies the handle of the window sending the message. The WM_CPL_LAUNCHED message is sent to this window.

lpszAppName

Value of lParam. Specifies a far pointer to a string containing the name of the Control Panel application to open.

Return Value

If the application starts, the return value is TRUE; otherwise, it is FALSE.

See Also

WM_CPL_LAUNCHED


WM_CPL_LAUNCHED
 WM_CPL_LAUNCHED  QuickInfo  Overview  Group

WM_CPL_LAUNCHED

fAppStarted = (BOOL) wParam;

The WM_CPL_LAUNCHED message is sent when a Control Panel application, started by the WM_CPL_LAUNCH message, has closed. The WM_CPL_LAUNCHED message is sent to the window identified by the wParam parameter of the WM_CPL_LAUNCH message that started the application.

Parameters

fAppStarted

Value of wParam. Specifies whether the application was started. If the application was started, this parameter is TRUE; otherwise, it is FALSE.

Return Value

The value returned by the application is ignored for this message.

See Also

WM_CPL_LAUNCH


WM_CREATE
 WM_CREATE  QuickInfo  Overview  Group

WM_CREATE

lpcs = (LPCREATESTRUCT) lParam; // structure with creation data

The WM_CREATE message is sent when an application requests that a window be created by calling the CreateWindowEx or CreateWindow function. The window procedure of the new window receives this message after the window is created, but before the window becomes visible. The message is sent before the CreateWindowEx or CreateWindow function returns.

Parameters

lParam

Value of lParam. Points to a CREATESTRUCT structure that contains information about the window being created. The members of CREATESTRUCT are identical to the parameters of the CreateWindowEx function.

Return Value

If an application processes this message, it should return 0 to continue creation of the window. If the application returns −1, the window is destroyed and the CreateWindowEx or CreateWindow function returns a NULL handle.

See Also

CreateWindow, CreateWindowEx, CREATESTRUCT, WM_NCCREATE


WM_CTLCOLORBTN
 WM_CTLCOLORBTN  QuickInfo  Overview  Group

WM_CTLCOLORBTN

hdcButton = (HDC) wParam;   // handle of button display context

hwndButton = (HWND) lParam; // handle of button

The WM_CTLCOLORBTN message is sent to the parent window of a button when the button is about to be drawn. By responding to this message, the parent window can set a button's text and background colors.

Parameters

hdcButton

Value of wParam. Identifies the display context for the button.

hwndButton

Value of lParam. Identifies the button.

Return Value

If an application processes this message, it must return the handle of a brush. Windows uses the brush to paint the background of the button.

Default Action

The DefWindowProc function selects the default system colors for the button.

Remarks

The 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.

You cannot use a custom palette to set a button's text or background color. Although the SelectPalette and RealizePalette functions will succeed, they will have no effect on the button.

See Also

DefWindowProc, RealizePalette, SelectPalette, WM_CTLCOLORDLG, WM_CTLCOLOREDIT, WM_CTLCOLORLISTBOX, WM_CTLCOLORMSGBOX, WM_CTLCOLORSCROLLBAR, WM_CTLCOLORSTATIC


WM_CTLCOLORDLG
 WM_CTLCOLORDLG  QuickInfo

WM_CTLCOLORDLG

hdcDlg = (HDC) wParam;   // handle of dialog box display context

hwndDlg = (HWND) lParam; // handle of dialog box

The WM_CTLCOLORDLG message is sent to a dialog box before Windows draws the dialog box. By responding to this message, the dialog box can set its text and background colors by using the given display device context handle.

Parameters

hdcDlg

Value of wParam. Identifies the device context for the dialog box.

hwndDlg

Value of lParam. Identifies the dialog box.

Return Value

If an application processes this message, it must return the handle of a brush. Windows uses the brush to paint the background of the dialog box.

Default Action

The DefWindowProc function selects the default system colors for the dialog box.

Remarks

The 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.

You cannot use a custom palette to draw a dialog box's text and background colors. Although you could select and realize a custom palette into the dialog box's display context while handling the WM_CTLCOLORDLG message, no message is sent when dialog box drawing is done, and thus you wouldn't know when to restore the display context's previous palette.

You cannot use a custom palette to set a dialog box's text or background color. Although the SelectPalette and RealizePalette functions will succeed, they will have no effect on the dialog box.

See Also

DefWindowProc, RealizePalette, SelectPalette, WM_CTLCOLORBTN, WM_CTLCOLOREDIT, WM_CTLCOLORLISTBOX, WM_CTLCOLORMSGBOX, WM_CTLCOLORSCROLLBAR, WM_CTLCOLORSTATIC


WM_CTLCOLOREDIT
 WM_CTLCOLOREDIT  QuickInfo  Overview  Group

WM_CTLCOLOREDIT

hdcEdit = (HDC) wParam;   // handle of display context

hwndEdit = (HWND) lParam; // handle of static control

The WM_CTLCOLOREDIT message is sent to the parent window of an edit control when the control is about to be drawn. By responding to this message, the parent window can use the given device context handle to set the text and background colors of the edit control.

Parameters

hdcEdit

Value of wParam. Identifies the device context for the edit control window.

hwndEdit

Value of lParam. Identifies the edit control.

Return Value

If an application processes this message, it must return the handle of a brush. Windows uses the brush to paint the background of the edit control.

Default Action

The DefWindowProc function selects the default system colors for the edit control.

Remarks

The WM_CTLCOLOREDIT message is never sent between threads, it is only sent within the same thread.

You cannot use a custom palette to set an edit control's text or background color. Although the SelectPalette and RealizePalette functions will succeed, they will have no effect on the edit control.

See Also

DefWindowProc, RealizePalette, SelectPalette, WM_CTLCOLORBTN, WM_CTLCOLORDLG, WM_CTLCOLORLISTBOX, WM_CTLCOLORMSGBOX, WM_CTLCOLORSCROLLBAR, WM_CTLCOLORSTATIC


WM_CTLCOLORLISTBOX
 WM_CTLCOLORLISTBOX  QuickInfo

WM_CTLCOLORLISTBOX

hdcLB = (HDC) wParam;   // handle of list box display context

hwndLB = (HWND) lParam; // handle of list box

The WM_CTLCOLORLISTBOX message is sent to the parent window of a list box before Windows draws the list box. By responding to this message, the parent window can set the text and background colors of the list box by using the given display device context handle.

Parameters

hdcLB

Value of wParam. Identifies the device context for the list box.

hwndLB

Value of lParam. Identifies the list box.

Return Value

If an application processes this message, it must return the handle of a brush. Windows uses the brush to paint the background of the list box.

Default Action

The DefWindowProc function selects the default system colors for the list box.

Remarks

The WM_CTLCOLORLISTBOX message is never sent between threads. It is sent only within one thread.

You cannot use a custom palette to set a list box's text or background color. Although the SelectPalette and RealizePalette functions will succeed, they will have no effect on the list box.

See Also

DefWindowProc, RealizePalette, SelectPalette, WM_CTLCOLORBTN, WM_CTLCOLORDLG, WM_CTLCOLOREDIT, WM_CTLCOLORMSGBOX, WM_CTLCOLORSCROLLBAR, WM_CTLCOLORSTATIC


WM_CTLCOLORMSGBOX
 WM_CTLCOLORMSGBOX  QuickInfo  Overview  Group

WM_CTLCOLORMSGBOX

hdcMB = (HDC) wParam;   // handle of message box display context

hwndMB = (HWND) lParam; // handle of message box

The WM_CTLCOLORMSGBOX message is sent to the owner window of a message box before Windows draws the message box. By responding to this message, the owner window can set the text and background colors of the message box by using the given display device context handle.

Parameters

hdcMB

Value of wParam. Identifies the device context for the message box.

hwndMB

Value of lParam. Identifies the message box.

Return Value

If an application processes this message, it must return the handle of a brush. Windows uses the brush to paint the background of the message box.

Default Action

The DefWindowProc function selects the default system colors for the message box.

Remarks

The WM_CTLCOLORMSGBOX message is never sent between threads. It is sent only within one thread.

You cannot use a custom palette to set a message box's text or background color. Although the SelectPalette and RealizePalette functions will succeed, they will have no effect on the message box.

See Also

DefWindowProc, RealizePalette, SelectPalette, WM_CTLCOLORBTN, WM_CTLCOLORDLG, WM_CTLCOLOREDIT, WM_CTLCOLORLISTBOX, WM_CTLCOLORSCROLLBAR, WM_CTLCOLORSTATIC


WM_CTLCOLORSCROLLBAR
 WM_CTLCOLORSCROLLBAR  QuickInfo  Overview  Group

WM_CTLCOLORSCROLLBAR

hdcSB  = (HDC) wParam;   // handle of scroll-bar display context

hwndSB = (HWND) lParam;  // handle of scroll bar

The WM_CTLCOLORSCROLLBAR message is sent to the parent window of a scroll bar control when the control is about to be drawn. By responding to this message, the parent window can use the given display context handle to set the background color of the scroll bar control.

Parameters

hdcSB

Value of wParam. Identifies the device context for the scroll bar control.

hwndSB

Value of lParam. Identifies the scroll bar.

Return Value

If an application processes this message, it must return the handle of a brush. Windows uses the brush to paint the background of the scroll bar control.

Default Action

The DefWindowProc function selects the default system colors for the scroll bar control.

Remarks

The WM_CTLCOLORSCROLLBAR message is never sent between threads; it is only sent within the same thread.

You cannot use a custom palette to set a scroll bar's text or background color. Although the SelectPalette and RealizePalette functions will succeed, they will have no effect on the scroll bar.

See Also

DefWindowProc, RealizePalette, SelectPalette, WM_CTLCOLORBTN, WM_CTLCOLORDLG, WM_CTLCOLOREDIT, WM_CTLCOLORLISTBOX, WM_CTLCOLORMSGBOX, WM_CTLCOLORSTATIC


WM_CTLCOLORSTATIC
 WM_CTLCOLORSTATIC  QuickInfo  Overview  Group

WM_CTLCOLORSTATIC

hdcStatic = (HDC) wParam;   // handle of display context

hwndStatic = (HWND) lParam; // handle of static control

The WM_CTLCOLORSTATIC message is sent to the parent window of a static control when the control is about to be drawn. By responding to this message, the parent window can use the given device context handle to set the text and background colors of the static control.

Parameters

hdcStatic

Value of wParam. Identifies the device context for the static control window.

hwndStatic

Value of lParam. Identifies the static control.

Return Value

If an application processes this message, the return value is the handle of a brush that Windows uses to paint the background of the static control.

Default Action

The DefWindowProc function selects the default system colors for the static control.

Remarks

The WM_CTLCOLORSTATIC message is never sent between threads; it is sent only within the same thread.

You cannot use a custom palette to set a static control's text or background color. Although the SelectPalette and RealizePalette functions will succeed, they will have no effect on the static control.

See Also

DefWindowProc, RealizePalette, SelectPalette, WM_CTLCOLORBTN, WM_CTLCOLORDLG, WM_CTLCOLOREDIT, WM_CTLCOLORLISTBOX, WM_CTLCOLORMSGBOX, WM_CTLCOLORSCROLLBAR


WM_CUT
 WM_CUT  QuickInfo  Overview  Group

WM_CUT

wParam = 0; // not used; must be zero

lParam = 0; // not used; must be zero

An application sends a WM_CUT message to an edit control or combo box to delete (cut) the current selection, if any, in the edit control and copy the deleted text to the clipboard in CF_TEXT format.

Parameters

This message has no parameters.

Return Value

This message does not return a value.

Remarks

The deletion performed by the WM_CUT message can be undone by sending the edit control an EM_UNDO message.

To delete the current selection without placing the deleted text on the clipboard, use the WM_CLEAR message.

When sent to a combo box, the WM_CUT message is handled by its edit control. This message has no effect when sent to a combo box with the CBS_DROPDOWNLIST style.

See Also

EM_UNDO, WM_CLEAR, WM_COPY, WM_PASTE


WM_DDE_ACK
 WM_DDE_ACK  QuickInfo  Overview  Group

WM_DDE_ACK

// Response to WM_DDE_INITIATE

wParam = (WPARAM) hwnd;          // handle of posting application

lParam = MAKELPARAM(aApp, aTopic) // application and topic atoms

// Response to WM_DDE_EXECUTE

wParam = (WPARAM) hwnd;         // handle of posting application

lParam = (LPARAM) lPackedVal;   // packed status flags and data handle

// Response to all other messages

wParam = (WPARAM) hwnd;         // handle of posting application

lParam = (LPARAM) lPackedVal;   // packed status flags and item

The WM_DDE_ACK message notifies a DDE application of the receipt and processing of a WM_DDE_POKE, WM_DDE_EXECUTE, WM_DDE_DATA, WM_DDE_ADVISE, WM_DDE_UNADVISE, or WM_DDE_INITIATE message, and in some cases, of a WM_DDE_REQUEST message.

Parameters

When responding to WM_DDE_INITIATE:

hwnd

Value of wParam. Identifies the server window posting the message.

aApp

Value of the low-order word of lParam. Contains an atom that identifies the replying application.

aTopic

Value of the high-order word of lParam. Contains an atom that identifies the topic for which a conversation is being established.

When responding to WM_DDE_EXECUTE:

hwnd

Value of wParam. Identifies the server window posting the message.

lPackedVal

Value of lParam. The component parameters that are packed into lPackedVal are extracted by calling the UnpackDDElParam function. The low-order word is wStatus. The high-order word is the same hCommands that was received in the WM_DDE_EXECUTE message.

Parameter	Description
wStatus	Specifies a DDEACK structure containing a series of flags that indicate the status of the response.
hCommands	Identifies a global memory object that contains the command string.
When replying to all other messages:

hwnd

Value of wParam. Identifies the client or server window posting the message.

lPackedVal

Value of lParam. The component parameters that are packed into lPackedVal are extracted by calling the UnpackDDElParam function. The low-order word is wStatus. The high-order word is aItem.

Parameter	Description
wStatus	Specifies a DDEACK structure containing a series of flags that indicate the status of the response.
aItem	Contains a global atom that identifies the name of the data item for which the response is sent.
Remarks

Posting

Except in response to the WM_DDE_INITIATE message, the application posts the WM_DDE_ACK message by calling the PostMessage function, not by calling the SendMessage function. When responding to WM_DDE_INITIATE, the application sends the WM_DDE_ACK message by calling SendMessage. In this case, neither the application-name atom nor the topic-name atom should be NULL (even if the WM_DDE_INITIATE message specified NULL atoms).

When acknowledging any message with an accompanying aItem atom, the application posting WM_DDE_ACK can either reuse the aItem atom that accompanied the original message, or it can delete it and create a new one.

When acknowledging WM_DDE_EXECUTE, the application that posts WM_DDE_ACK should reuse the global memory object identified in the original WM_DDE_EXECUTE message.

All posted WM_DDE_ACK messages must create or reuse the lPackedVal parameter by calling the PackDDElParam function or the ReuseDDElParam function.

If an application has initiated the termination of a conversation by posting WM_DDE_TERMINATE and is awaiting confirmation, the waiting application should not acknowledge (positively or negatively) any subsequent messages sent by the other application. The waiting application should delete any atoms or shared memory objects received in these intervening messages. Memory objects should not be freed if the fRelease flag is set to FALSE in WM_DDE_POKE, and WM_DDE_DATA messages.

Receiving

The application that receives a WM_DDE_ACK message should delete all atoms accompanying the message. If the application receives a WM_DDE_ACK in response to a message with an accompanying hData object, and the object was sent with the fRelease flags set to FALSE, the application is responsible for deleteing the hData object.

If the application receives a negative WM_DDE_ACK message posted in reply to a WM_DDE_ADVISE message, the application should delete the global memory object posted with the original WM_DDE_ADVISE message (in hOptions). If the application receives a negative WM_DDE_ACK message posted in reply to a WM_DDE_DATA, WM_DDE_POKE, or WM_DDE_EXECUTE message, the application should delete the global memory object posted with the original WM_DDE_DATA, WM_DDE_POKE, or WM_DDE_EXECUTE message (in hCommands).

The application that receives a posted WM_DDE_ACK message must free the lPackedVal parameter by using the FreeDDElParam function.

See Also

DDEACK, FreeDDElParam, PackDDElParam, PostMessage, ReuseDDElParam, SendMessage, UnpackDDElParam, WM_DDE_ADVISE, WM_DDE_DATA, WM_DDE_EXECUTE, WM_DDE_INITIATE, WM_DDE_POKE, WM_DDE_REQUEST, WM_DDE_TERMINATE, WM_DDE_UNADVISE


WM_DDE_ADVISE
 WM_DDE_ADVISE  QuickInfo  Overview  Group

WM_DDE_ADVISE

wParam = (WPARAM) hwnd;        // handle of posting application

lParam = (LPARAM) lPackedVal;  // packed DDEADVISE and item atom

A DDE client application posts the WM_DDE_ADVISE message to a DDE server application to request the server to supply an update for a data item whenever the item changes.

Parameters

hwnd

Value of wParam. Identifies the client window posting the message.

lPackedVal

Value of lParam. The component parameters packed into lPackedVal are extracted by calling the UnpackDDElParam function. The low-order word is hOptions. The high-order word is aItem.

Parameter	Description
hOptions	Identifies a global memory object containing a DDEADVISE structure that specifies how the data is to be sent.
aItem	Contains an atom that identifies the requested data item.
Remarks

If a client application supports more than one clipboard format for a single topic and item, it can post multiple WM_DDE_ADVISE messages for the topic and item, specifying a different clipboard format with each message. Note that a server can support multiple formats only for hot data links, not warm data links.

Posting

The client application posts the WM_DDE_ADVISE message by calling the PostMessage function, not the SendMessage function.

The client application allocates hOptions by calling the GlobalAlloc function with the GMEM_DDESHARE option. It allocates aItem by calling the GlobalAddAtom function.

The client application must create or reuse the WM_DDE_ADVISE lPackedVal parameter by calling the PackDDElParam function or the ReuseDDElParam function with hOptions supplied as the low-order word and aItem supplied as the high-order word.

If the receiving (server) application responds with a negative WM_DDE_ACK message, the posting (client) application must delete the hOptions object.

The fRelease flag is not used in WM_DDE_ADVISE messages, but their data-freeing behavior is similar to that of WM_DDE_DATA and WM_DDE_POKE messages where fRelease is TRUE.

Receiving

The server application posts the WM_DDE_ACK message to respond positively or negatively. When posting WM_DDE_ACK, the application can reuse the aItem atom or delete it and create a new one. If the WM_DDE_ACK message is positive, the application should delete the hOptions object; otherwise, the application should not delete the object.

The server must create or reuse the WM_DDE_ACK lPackedVal parameter by calling the PackDDElParam function or the ReuseDDElParam function with wStatus supplied as the low-order word and aItem supplied as the high-order word.

See Also

DDEADVISE, FreeDDElParam, GlobalAddAtom, GlobalAlloc, PackDDElParam, PostMessage, ReuseDDElParam, SendMessage, UnpackDDElParam, WM_DDE_ACK, WM_DDE_DATA, WM_DDE_POKE, WM_DDE_REQUEST


WM_DDE_DATA
 WM_DDE_DATA  QuickInfo  Overview  Group

WM_DDE_DATA

wParam = (WPARAM) hwnd;         // handle of posting application

lParam = (LPARAM) lPackedVal;   // packed DDEDATA and item atom

A DDE server application posts a WM_DDE_DATA message to a DDE client application to pass a data item to the client or to notify the client of the availability of a data item.

Parameters

hwnd

Value of wParam. Identifies the server window posting the message.

lPackedVal

Value of lParam. The component parameters that are packed into lPackedVal are extracted by calling the UnpackDDElParam function. The low-order word is hData or NULL. The high-order word is aItem.

Parameter	Description
hData	Identifies a global memory object containing a DDEDATA structure with the data and additional information. The handle should be set to NULL if the server is notifying the client that the data-item value has changed during a warm data link. A warm link is established by the client sending a WM_DDE_ADVISE message with the fDeferUpd bit set.
aItem	Contains an atom that identifies the data item for which the data or notification is sent.
Remarks

Posting

The server application posts the WM_DDE_DATA message by calling the PostMessage function, not the SendMessage function.

The server application allocates hData by calling the GlobalAlloc function with the GMEM_DDESHARE option. It allocates aItem by calling the GlobalAddAtom function.

The server must create or reuse the WM_DDE_DATA lPackedVal parameter by calling the PackDDElParam function or the ReuseDDElParam function with hData supplied as the low-order word and aItem supplied as the high-order word.

If the receiving (client) application responds with a negative WM_DDE_ACK message, the posting (server) application must delete the hData object; otherwise, the client must delete the hData object after extracting its contents by calling the UnpackDDElParam function.

If the server application sets the fRelease member of the DDEDATA structure to FALSE, the server is responsible for deleting hData upon receiving either a positive or negative acknowledgement.

The server application should not set both the fAckReq and fRelease members of the DDEDATA structure to FALSE. If both members are set to FALSE, it is impossible for the server to determine when to delete hData.

Receiving

If fAckReq is TRUE, the client application should post the WM_DDE_ACK message to respond positively or negatively. When posting WM_DDE_ACK, the client can either reuse the aItem atom, or it can delete it and create a new one.

The client must create or reuse the WM_DDE_ACK lPackedVal parameter by calling the PackDDElParam function or the ReuseDDElParam function with wStatus supplied as the low-order word and aItem supplied as the high-order word.

If fAckReq is FALSE, the client application should delete the aItem atom.

If the posting (server) application specified hData as NULL, the receiving (client) application can request the server to send the data by posting a WM_DDE_REQUEST message.

After processing a WM_DDE_DATA message in which hData is not NULL, the client should free hData, unless one of the following conditions is true:

•	The fRelease member is FALSE.

•	The fRelease member is TRUE, but the client application responds with a negative WM_DDE_ACK message.

See Also

DDEDATA, FreeDDElParam, GlobalAddAtom, GlobalAlloc, PackDDElParam, PostMessage, ReuseDDElParam, SendMessage, UnpackDDElParam, WM_DDE_ACK, WM_DDE_ADVISE, WM_DDE_POKE, WM_DDE_REQUEST


WM_DDE_EXECUTE
 WM_DDE_EXECUTE  QuickInfo  Overview  Group

WM_DDE_EXECUTE

wParam = (WPARAM) hwnd;        // handle of posting application

lParam = (LPARAM) hCommands;   // handle to global object

A DDE client application posts a WM_DDE_EXECUTE message to a DDE server application to send a string to the server to be processed as a series of commands. The server application is expected to post a WM_DDE_ACK message in response.

Parameters

hwnd

Value of wParam. Identifies the client window posting the message.

hCommands

Value of lParam. Contains a global memory object that references an ANSI or Unicode command string, depending on the types of windows involved in the conversation.

Remarks

The command string is a null-terminated string consisting of one or more opcode strings enclosed in single brackets ([ ]).

Each opcode string has the following syntax, where the parameters list is optional:

opcode parameters

The opcode is any application-defined single token. It cannot include spaces, commas, parentheses, brackets, or quotation marks.

The parameters list can contain any application-defined value or values. Multiple parameters are separated by commas, and the entire parameter list is enclosed in parentheses. Parameters cannot include commas or parentheses except inside a quoted string. If a bracket or parenthesis character is to appear in a quoted string, it need not be doubled, as was the case under the old rules.

Following are some valid command strings:

[connect][download(query1,results.txt)][disconnect]

[query("sales per employee for each district")]

[open("sample.xlm")][run("r1c1")]

[quote_case("This is a "" character")]

[bracket_or_paren_case("()s or []s should be no problem.")]

Note that, under the old rules, parentheses and brackets had to be doubled, as follows:

[bracket_or_paren_case("(())s or [[]]s should be no problem.")]

Servers should be able to parse commands in either form.

Unicode execute strings should be used only when both the client and server window handles cause the IsWindowUnicode function to return TRUE.

Posting

The client application posts the WM_DDE_EXECUTE message by calling the PostMessage function, not the SendMessage function.

The client application allocates hCommands by calling the GlobalAlloc function with the GMEM_DDESHARE option.

When processing the WM_DDE_ACK message that the server posts in reply to a WM_DDE_EXECUTE message, the client application must delete the hCommands object sent back in the WM_DDE_ACK message.

Receiving

The server application posts the WM_DDE_ACK message to respond positively or negatively. The server should reuse the hCommands object.

Unless specified otherwise by a sub-protocol, the server should not post the WM_DDE_ACK message until all the actions specified by the execute command string are completed. The one exception to this rule is when the string causes the server to terminate the conversation.

See Also

GlobalAlloc, IsWindowUnicode, PackDDElParam, PostMessage, ReuseDDElParam, SendMessage, UnpackDDElParam, WM_DDE_ACK


WM_DDE_INITIATE
 WM_DDE_INITIATE  QuickInfo  Overview  Group

WM_DDE_INITIATE

wParam = (WPARAM) hwnd;             // handle of posting appl.

lParam = MAKELPARAM(aApp, aTopic);  // appl. and topic atoms

A DDE client application sends a WM_DDE_INITIATE message to initiate a conversation with a server application responding to the specified application and topic names. Upon receiving this message, all server applications with names that match the specified application and that support the specified topic are expected to acknowledge it. (For more information, see the WM_DDE_ACK message.)

Parameters

hwnd

Value of wParam. Identifies the client window sending the message.

aApp

Value of the low-order word of lParam. Contains an atom that identifies the application with which a conversation is requested. The application name cannot contain slashes (/) or backslashes (\). These characters are reserved for network implementations. If aApp is NULL, a conversation with all applications is requested.

aTopic

Value of the high-order word of lParam. Contains an atom that identifies the topic for which a conversation is requested. If the topic is NULL, conversations for all available topics are requested.

Remarks

If aApp is NULL, any server application can respond. If aTopic is NULL, any topic is valid. Upon receiving a WM_DDE_INITIATE request with the aTopic parameter set to NULL, a server must send a WM_DDE_ACK message for each of the topics it supports.

Sending

The client application sends WM_DDE_INITIATE by calling the SendMessage function, not the PostMessage function. The client broadcasts the message to all top-level windows by setting the first parameter of SendMessage to −1.

If the client application has already obtained the window handle of the desired server, it can send WM_DDE_INITIATE directly to the server window by passing the server's window handle as the first parameter of SendMessage.

The client application allocates aApp and aTopic by calling GlobalAddAtom.

When SendMessage returns, the client application must delete the aApp and aTopic atoms.

Receiving

To complete the initiation of a conversation, the server application must respond with one or more WM_DDE_ACK messages, where each message is for a separate topic. When sending WM_DDE_ACK message, the server should create new aApp and aTopic atoms; it should not reuse the atoms sent with WM_DDE_INITIATE.

See Also

GlobalAddAtom, GlobalAlloc, PostMessage, SendMessage, WM_DDE_ACK


WM_DDE_POKE
 WM_DDE_POKE  QuickInfo  Overview  Group

WM_DDE_POKE

wParam = (WPARAM) hwnd;        // handle of posting application

lParam = (LPARAM) lPackedVal;  // packed DDEPOKE and item atom

A DDE client application posts a WM_DDE_POKE message to a DDE server application. A client uses this message to request the server to accept an unsolicited data item. The server is expected to reply with a WM_DDE_ACK message indicating whether it accepted the data item.

Parameters

hwnd

Value of wParam. Identifies the client window posting the message.

lPackedVal

Value of lParam. The component parameters that are packed into lPackedVal are extracted by calling the UnpackDDElParam function. The low-order word is hData. The high-order word is aItem.

Parameter	Description
hData	Identifies a global memory object containing a DDEPOKE structure with the data and additional information.
aItem	Contains a global atom that identifies the data item for which the data or notification is being sent.
Remarks

Posting

The client application posts the WM_DDE_POKE message by using the PostMessage function.

The client application must allocate memory for the hData object by using the GlobalAlloc function with the GMEM_DDESHARE option. The client application must delete the hData object if either of the following conditions is true:

•	The server application responds with a negative WM_DDE_ACK message.

•	The fRelease member is FALSE, but the server application responds with either a positive or negative WM_DDE_ACK.

The client application must create the aItem atom by using the GlobalAddAtom function.

The client application must create or reuse the WM_DDE_POKE lPackedVal parameter by calling the PackDDElParam function or the ReuseDDElParam function with hData supplied as the low-order word and aItem supplied as the high-order word.

Receiving

The server application should post the WM_DDE_ACK message to respond positively or negatively. When posting WM_DDE_ACK, the server can either reuse the aItem atom, or it can delete it and create a new one.

The server must create or reuse the WM_DDE_ACK lPackedVal parameter by calling the PackDDElParam function or the ReuseDDElParam function with wStatus supplied as the low-order word and aItem supplied as the high-order word.

To free the hData object, the server should call the GlobalFree function. Also, if the data format is either CF_DSPMETAFILEPICT or CF_METAFILEPICT, the server must also call DeleteMetaFile with the embedded metafile handle. These two formats have an extra level of indirection; that is, an application must lock hData to get a pointer to a handle, then lock that handle to get a pointer to a METAFILEPICT structure, and finally call DeleteMetaFile with the handle from the hMF member of the METAFILEPICT structure.

To free the lPackedVal object, the server should call the FreeDDElParam function.

See Also

DDEPOKE, DeleteMetaFile, FreeDDElParam, GlobalAddAtom, GlobalAlloc, GlobalFree, METAFILEPICT, PackDDElParam, PostMessage, ReuseDDElParam, SendMessage, UnpackDDElParam, WM_DDE_ACK


WM_DDE_REQUEST
 WM_DDE_REQUEST  QuickInfo  Overview  Group

WM_DDE_REQUEST

wParam = (WPARAM) hwnd;        // handle of posting application

lParam = (LPARAM) lParam;      // holds cfFormat and aItem

A DDE client application posts a WM_DDE_REQUEST message to a DDE server application to request the value of a data item.

Parameters

hwnd

Value of wParam. Identifies the client window sending the message.

lParam

Holds the cfFormat and aItem parameters.

Parameter	Description
cfFormat	This is the LOWORD of lParam. Specifies a standard or registered clipboard format.
aItem	This is the HIWORD of lParam. Contains an atom that identifies the data item requested from the server.
Remarks

Posting

The client application posts the WM_DDE_REQUEST message by calling the PostMessage function, not the SendMessage function.

The client application allocates aItem by calling the GlobalAddAtom function.

Receiving

If the receiving (server) application can satisfy the request, it responds with a WM_DDE_DATA message containing the requested data. Otherwise, it responds with a negative WM_DDE_ACK message.

When responding with either a WM_DDE_DATA or WM_DDE_ACK message, the server application can either reuse the aItem atom or it can delete the atom and create a new one.

See Also

GlobalAddAtom, PackDDElParam, PostMessage, ReuseDDElParam, SendMessage, UnpackDDElParam, WM_DDE_ACK, WM_DDE_DATA


WM_DDE_TERMINATE
 WM_DDE_TERMINATE  QuickInfo  Overview  Group

WM_DDE_TERMINATE

wParam = (WPARAM) hwnd; // handle of posting window

lParam = 0;             // not used, must be zero

A DDE application (client or server) posts a WM_DDE_TERMINATE message to terminate a conversation.

Parameters

hwnd

Value of wParam. Identifies the client or server window posting the message.

Remarks

Posting

The client or server application posts the WM_DDE_TERMINATE message by calling the PostMessage function, not the SendMessage function.

While waiting for confirmation of the termination, the posting application should not post any other messages to the receiving application. If the sending application receives messages (other than WM_DDE_TERMINATE) from the receiving application, it should delete any atoms or shared memory objects accompanying the messages, except hData objects associated with WM_DDE_POKE or WM_DDE_DATA messages that do not have the fRelease flag set.

Receiving

The client or server application should respond by posting a WM_DDE_TERMINATE message.

See Also

PostMessage, SendMessage, WM_DDE_DATA, WM_DDE_POKE


WM_DDE_UNADVISE
 WM_DDE_UNADVISE  QuickInfo  Overview  Group

WM_DDE_UNADVISE

wParam = (WPARAM) hwnd;        // handle of posting application

lParam = (LPARAM) lParam;      // format and item atom

A DDE client application posts a WM_DDE_UNADVISE message to inform a DDE server application that the specified item or a particular clipboard format for the item should no longer be updated. This terminates the warm or hot data link for the specified item.

Parameters

hwnd

Value of wParam. Identifies the client window sending the message.

lParam

Holds the cfFormat and aItem parameters.

Parameter	Description
cfFormat	This is the LOWORD of lParam. Specifies the clipboard format of the item for which the update request is being retracted. If cfFormat is NULL, all active WM_DDE_ADVISE conversations for the item are to be terminated.
aItem	This is the HIWORD of lParam. Contains a global atom that identifies the item for which the update request is being retracted. When aItem is NULL, all active WM_DDE_ADVISE links associated with the conversation are to be terminated.
Remarks

Posting

The client application posts the WM_DDE_UNADVISE message by calling the PostMessage function, not the SendMessage function.

The client application allocates aItem by calling the GlobalAddAtom function.

Receiving

The server application posts the WM_DDE_ACK message to respond positively or negatively. When posting WM_DDE_ACK, the server can either reuse the aItem atom, or it can delete the atom and create a new one.

See Also

GlobalAddAtom, PackDDElParam, PostMessage, ReuseDDElParam, SendMessage, UnpackDDElParam, WM_DDE_ACK, WM_DDE_ADVISE


WM_DEADCHAR
 WM_DEADCHAR  QuickInfo  Overview  Group

WM_DEADCHAR

chCharCode = (TCHAR) wParam;    // character code

lKeyData = lParam;              // key data

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.

Parameters

chCharCode

Value of wParam. Specifies the character code generated by the dead key.

lKeyData

Value of lParam. Specifies the repeat count, scan code, extended-key flag, context code, previous key-state flag, and transition-state flag, as shown in the following table:

Value	Description
0−15	Specifies the repeat count. The value is the number of times the keystroke is repeated as a result of the user holding down the key.
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 Value

An application should return zero if it processes this message.

Remarks

The WM_DEADCHAR message typically is used by applications to give the user feedback about each key pressed. For example, an application can display the accent in the current character position without moving the caret.

Because there is not necessarily a one-to-one correspondence between keys pressed and character messages generated, the information in the high-order word of the lKeyData parameter is generally not useful to applications. The information in the high-order word applies only to the most recent WM_KEYDOWN message that precedes the posting of the WM_DEADCHAR message.

For enhanced 101- and 102-key keyboards, extended keys are the right ALT and the right CTRL keys on the main section of the keyboard; the INS, DEL, HOME, END, PAGE UP, PAGE DOWN and arrow keys in the clusters to the left of the numeric keypad; and the divide (/) and ENTER keys in the numeric keypad. Some other keyboards may support the extended-key bit in the lKeyData parameter.

See Also

TranslateMessage, WM_KEYDOWN, WM_KEYUP, WM_SYSDEADCHAR


WM_DELETEITEM
 WM_DELETEITEM  QuickInfo  Overview  Group

WM_DELETEITEM

idCtl = wParam;                      // control identifier

lpdis = (LPDELETEITEMSTRUCT) lParam; // structure with item information

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. Windows sends a WM_DELETEITEM message for each deleted item.

Windows NT

Windows 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

Windows sends the WM_DELETEITEM message for any deleted list box or combo box item with non-zero item data.

Parameters

idCtl

Value of wParam. Specifies the identifier of the control that sent the WM_DELETEITEM message.

lpdis

Value of lParam. Points to a DELETEITEMSTRUCT structure that contains information about the item deleted from a list box.

Return Value

An application should return TRUE if it processes this message.

See Also

CB_DELETESTRING, CB_RESETCONTENT, DELETEITEMSTRUCT, LB_DELETESTRING, LB_RESETCONTENT


WM_DESTROY
 WM_DESTROY  QuickInfo  Overview  Group

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.

Parameters

This message has no parameters.

Return Value

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.

See Also

ChangeClipboardChain, DestroyWindow, PostQuitMessage, SetClipboardViewer, WM_CLOSE


WM_DESTROYCLIPBOARD
 WM_DESTROYCLIPBOARD  QuickInfo  Overview  Group

WM_DESTROYCLIPBOARD

The WM_DESTROYCLIPBOARD message is sent to the clipboard owner when a call to the EmptyClipboard function empties the clipboard.

Parameters

This message has no parameters.

Return Value

If an application processes this message, it should return zero.

See Also

EmptyClipboard


WM_DEVICECHANGE [New - Windows 95]
 WM_DEVICECHANGE  QuickInfo  Overview  Group

[New - Windows 95]

Event = (UINT) wParam;
dwData = (DWORD) lParam;

The WM_DEVICECHANGE device message notifies an application or device driver of a change to the hardware configuration of a device or the computer.

Parameters

Event

Event type. Can be one of these values:

Value	Meaning
DBT_DEVICEARRIVAL	A device has been inserted and is now available.
DBT_DEVICEQUERYREMOVE	Permission to remove a device is requested. Any application can deny this request and cancel the removal.
DBT_DEVICEQUERYREMOVEFAILED	Request to remove a device has been canceled.
DBT_DEVICEREMOVEPENDING	Device is about to be removed. Can not be denied.
DBT_DEVICEREMOVECOMPLETE	Device has been removed.
DBT_DEVICETYPESPECIFIC	Device-specific event.
DBT_CONFIGCHANGED	Current configuration has changed.
dwData

Address of a structure that contains event-specific data. Its meaning depends on the given event.

Return Value

Returns TRUE to complete a requested action, FALSE otherwise.

Remarks

For devices that offer software-controllable features, such as ejection and locking, the operating system typically sends a DBT_DEVICEREMOVEPENDING message to let applications and device drivers end their use of the device gracefully.

If the operating system forcefully removes of a device, it may not send a DBT_DEVICEQUERYREMOVE message before doing so.

DBT_CONFIGCHANGED, DBT_DEVICEARRIVAL, DBT_DEVICEQUERYREMOVE, DBT_DEVICEQUERYREMOVEFAILED, DBT_DEVICEREMOVECOMPLETE, DBT_DEVICEREMOVEPENDING, DBT_DEVICETYPESPECIFIC,


WM_DEVMODECHANGE
 WM_DEVMODECHANGE  QuickInfo  Overview  Group

WM_DEVMODECHANGE

lpszDev = (LPCTSTR) lParam; // address of device name

The WM_DEVMODECHANGE message is sent to all top-level windows whenever the user changes device-mode settings.

Parameters

lpszDev

Value of lParam. Points to the device name specified in the WIN.INI file.

Return Value

An application should return zero if it processes this message.

Remarks

Windows NT only: Calls to functions that change the WIN.INI file may be mapped to the registry instead. This mapping occurs when WIN.INI and the section being changed are specified in the registry under the following keys:

HKEY_LOCAL_MACHINE\Software\Description\Microsoft\
        Windows NT\CurrentVersion\IniFileMapping

The change in the storage location has no effect on the behavior of this message.

See Also

WM_WININICHANGE


WM_DISPLAYCHANGE [New - Windows 95]
 WM_DISPLAYCHANGE  QuickInfo  Overview  Group

[New - Windows 95]

WM_DISPLAYCHANGE

cBitsPerPixel = wParam;

cxScreen = LOWORD(lParam);

cyScreen = HIWORD(lParam);

The WM_DISPLAYCHANGE message is sent to all windows when the display resolution has changed.

Parameters

cBitsPerPixel

Specifies the new image depth of the display in bits per pixel.

cxScreen

Specifies the new horizontal resolution of the screen.

cyScreen

Specifies the new vertical resolution of the screen.

Remarks

In previous versions, this message was sent twice, once in anticipation of a change to the display resolution and once after the display resolution changed. Now it is only sent after the display resolution has changed.


WM_DRAWCLIPBOARD
 WM_DRAWCLIPBOARD  QuickInfo  Overview  Group

WM_DRAWCLIPBOARD

The WM_DRAWCLIPBOARD message is sent to the first window in the clipboard viewer chain when the content of the clipboard changes. This enables a clipboard viewer window to display the new content of the clipboard.

Parameters

This message has no parameters.

Remarks

Only clipboard viewer windows receive this message. These are windows that have been added to the clipboard viewer chain by using the SetClipboardViewer function.

Each window that receives the WM_DRAWCLIPBOARD message must call the SendMessage function to pass the message on to the next window in the clipboard viewer chain. The handle of the next window in the chain is returned by SetClipboardViewer, and may change in response to a WM_CHANGECBCHAIN message.

See Also

SendMessage, SetClipboardViewer, WM_CHANGECBCHAIN


WM_DRAWITEM
 WM_DRAWITEM  QuickInfo  Overview  Group

WM_DRAWITEM

idCtl = (UINT) wParam;             // control identifier

lpdis = (LPDRAWITEMSTRUCT) lParam; // item-drawing information

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.

Parameters

idCtl

Value of wParam. Specifies the identifier of the control that sent the WM_DRAWITEM message. If the message was sent by a menu, this parameter is zero.

lpdis

Value of lParam. Points to a DRAWITEMSTRUCT structure containing information about the item to be drawn and the type of drawing required.

Return Value

If an application processes this message, it should return TRUE.

Default Action

The DefWindowProc function draws the focus rectangle for an owner-drawn list box item.

Remarks

The itemAction member of the DRAWITEMSTRUCT structure specifies the drawing operation that an application should perform.

Before returning from processing this message, an application should ensure that the device context identified by the hDC member of the DRAWITEMSTRUCT structure is in the default state.

See Also

DefWindowProc, DRAWITEMSTRUCT


WM_DROPFILES
 WM_DROPFILES  QuickInfo  Overview  Group

WM_DROPFILES

hDrop = (HANDLE) wParam;  // handle of internal drop structure

The WM_DROPFILES message is sent when the user releases the left mouse button while the cursor is in the window of an application that has registered itself as a recipient of dropped files.

Parameters

hDrop

Value of wParam. Identifies an internal structure describing the dropped files. This handle is used by the DragFinish, DragQueryFile, and DragQueryPoint functions to retrieve information about the dropped files.

Return Value

An application should return zero if it processes this message.

See Also

DragAcceptFiles, DragFinish, DragQueryFile, DragQueryPoint


WM_ENABLE
 WM_ENABLE  QuickInfo  Overview  Group

WM_ENABLE

fEnabled = (BOOL) wParam;   // enabled/disabled flag

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.

Parameters

fEnabled

Value of wParam. Specifies whether the window has been enabled or disabled. This parameter is TRUE if the window has been enabled or FALSE if the window has been disabled.

Return Value

If an application processes this message, it should return zero.

See Also

EnableWindow


WM_ENDSESSION
 WM_ENDSESSION  QuickInfo  Overview  Group

Windows 95:

WM_ENDSESSION

fEndSession = (BOOL) wParam;    // end-session flag

fLogOff = (BOOL) lParam         // logoff flag

Windows NT:

WM_ENDSESSION

fEndSession = (BOOL) wParam;    // end-session flag

The WM_ENDSESSION message is sent to an application after Windows processes the results of the WM_QUERYENDSESSION message. The WM_ENDSESSION message informs the application whether the Windows session is ending.

Parameters

fEndSession

Value of wParam. Specifies whether the session is being ended. If the session is being ended, this parameter is TRUE; otherwise, it is FALSE.

fLogOff

Windows 95 only: Value of lParam. Indicates whether the user is logging off or shutting down the system. This parameter is TRUE if the user is logging off; it is FALSE if the user is shutting down the system.

Return Value

If an application processes this message, it should return zero.

Remarks

If the fEndSession parameter is TRUE, the Windows session can end any time after all applications have returned from processing this message. Therefore, an application should perform all tasks required for termination before returning from this message.

Note that lParam is not used on the Windows NT platform but is used on the Windows 95 platform.

The application need not call the DestroyWindow or PostQuitMessage function when the session is ending.

See Also

DestroyWindow, PostQuitMessage, WM_QUERYENDSESSION


WM_ENTERIDLE
 WM_ENTERIDLE  QuickInfo  Overview  Group

WM_ENTERIDLE

fuSource = wParam;    // idle-source flag

hwnd = (HWND) lParam; // handle of dialog box or owner window

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.

Parameters

fuSource

Value of wParam. Specifies whether the message is the result of a dialog box or a menu being displayed. This parameter can be one of the following values:

Value	Meaning
MSGF_DIALOGBOX	The system is idle because a dialog box is displayed.
MSGF_MENU	The system is idle because a menu is displayed.
hwnd

Value of lParam. Contains the handle of the dialog box (if fuSource is MSGF_DIALOGBOX) or of the window containing the displayed menu (if fuSource is MSGF_MENU).

Return Value

An application should return zero if it processes this message.

Remarks

The DefWindowProc function returns zero.

See Also

DefWindowProc


WM_ENTERMENULOOP
 WM_ENTERMENULOOP  QuickInfo  Overview  Group

WM_ENTERMENULOOP

wParam = (BOOL) fIsTrackPopupMenu  // flags a pop-up menu

lParam = 0 ;                       // not used; must be zero

The WM_ENTERMENULOOP message informs an application's main window procedure that a menu modal loop has been entered.

Parameters

fIsTrackPopupMenu

Specifies whether the menu involved is a pop-up menu. This parameter has a value of TRUE if it is a pop-up, FALSE if it isn't.

Return Value

An application should return zero if it processes this message.

Remarks

The DefWindowProc function returns zero.

See Also

DefWindowProc, WM_EXITMENULOOP


WM_ENTERSIZEMOVE [New - Windows NT]
 WM_ENTERSIZEMOVE  QuickInfo

[New - Windows NT]

WM_ENTERSIZEMOVE

wParam = 0;  // not used, must be zero

lParam = 0;  // not used, must be zero

The WM_ENTERSIZEMOVE message is sent once to a window when it enters the moving or sizing mode. The window enters the moving or sizing mode 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. Windows sends the WM_ENTERSIZEMOVE message regardless of whether the dragging of full windows is enabled.

Parameters

This message has no parameters.

Return Value

An application should return zero if it processes this message.

See Also

DefWindowProc, WM_EXITSIZEMOVE, WM_SYSCOMMAND


WM_ERASEBKGND
 WM_ERASEBKGND  QuickInfo  Overview  Group

WM_ERASEBKGND

hdc = (HDC) wParam; // handle of device context

An application sends the WM_ERASEBKGND message when the window background must be erased (for example, when a window is resized). The message is sent to prepare an invalidated portion of a window for painting.

Parameters

hdc

Value of wParam. Identifies the device context.

Return Value

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.)

See Also

BeginPaint, DefWindowProc, PAINTSTRUCT, WM_ICONERASEBKGND, WNDCLASS


WM_EXITMENULOOP
 WM_EXITMENULOOP  QuickInfo  Overview  Group

WM_EXITLOOP

wParam = (BOOL) fIsTrackPopupMenu    // flags a pop-up menu

lParam = 0 ;                         // not used; must be zero

The WM_EXITMENULOOP message informs an application's main window procedure that a menu modal loop has been exited.

Parameters

fIsTrackPopupMenu

Specifies whether the menu involved is a pop-up menu. This parameter has a value of TRUE if it is a pop-up, FALSE if it isn't.

Return Value

An application should return zero if it processes this message.

Remarks

The DefWindowProc function returns zero.

See Also

DefWindowProc, WM_ENTERMENULOOP


WM_EXITSIZEMOVE [New - Windows NT]
 WM_EXITSIZEMOVE  QuickInfo

[New - Windows NT]

WM_EXITSIZEMOVE

wParam = 0;  // not used; must be zero

lParam = 0;  // not used; must be zero

The WM_EXITSIZEMOVE message is sent once to a window after it has exited the moving or sizing mode.

Parameters

This message has no parameters.

Return Value

An application should return zero if it processes this message.

See Also

WM_ENTERSIZEMOVE


WM_FONTCHANGE
 WM_FONTCHANGE  QuickInfo

WM_FONTCHANGE

wParam = 0; // not used, must be zero

lParam = 0; // not used, must be zero

An application sends the WM_FONTCHANGE message to all top-level windows in the system after changing the pool of font resources.

Parameters

This message has no parameters.

Remarks

An application that adds or removes fonts from the system (for example, by using the AddFontResource or RemoveFontResource function) should send this message to all top-level windows.

To send the WM_FONTCHANGE message to all top-level windows, an application can call the SendMessage function with the hwnd parameter set to HWND_BROADCAST.

See Also

AddFontResource, RemoveFontResource, SendMessage


WM_GETDLGCODE
 WM_GETDLGCODE  QuickInfo  Overview  Group

WM_GETDLGCODE

The WM_GETDLGCODE message is sent to the dialog box procedure associated with a control. Normally, Windows handles all arrow-key and TAB-key input to the control. By responding to the WM_GETDLGCODE message, an application can take control of a particular type of input and process the input itself.

Parameters

This message has no parameters.

Return Value

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	Nondefault 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 on to a control).
DLGC_WANTTAB	TAB key.
Default Action

The DefWindowProc function returns zero.

Remarks

Although the DefWindowProc function always returns zero in response to the WM_GETDLGCODE message, the window procedure for the predefined control classes return a code appropriate for each class.

The WM_GETDLGCODE message and the returned values are useful only with user-defined dialog box controls or standard controls modified by subclassing.

See Also

DefWindowProc, EM_SETSEL, WM_CHAR


WM_GETFONT
 WM_GETFONT  QuickInfo  Overview  Group

WM_GETFONT

wParam = 0; // not used, must be zero

lParam = 0; // not used, must be zero

An application sends a WM_GETFONT message to a control to retrieve the font with which the control is currently drawing its text.

Parameters

This message has no parameters.

Return Value

The return value is the handle of the font used by the control, or NULL if the control is using the system font.

See Also

WM_SETFONT


WM_GETHOTKEY
 WM_GETHOTKEY  QuickInfo

WM_GETHOTKEY

wParam = 0; // not used; must be zero

lParam = 0; // not used; must be zero

An application sends a WM_GETHOTKEY message to determine the hot key associated with a window.

Parameters

This message has no parameters.

Return Value

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.

See Also

RegisterHotKey, WM_SETHOTKEY


WM_GETICON [New - Windows 95]
 WM_GETICON  QuickInfo

[New - Windows 95]

WM_GETICON

fType = (BOOL) wParam;  // icon-size flag

The WM_GETICON message is sent to a window to retrieve the handle of the big or small icon associated with a window. Windows retrieves the big icon when drawing a minimized window, and retrieves the small icon when drawing a title bar.

Parameters

fType

Value of wParam. Specifies the icon to retrieve. If TRUE, the message retrieves the big icon; if FALSE, it retrieves the small icon.

Return Value

The return value is the handle of the big or small icon, depending on the value of fType. When an application receives this message, it can return the handle of a big or small icon, or pass the message to DefWindowProc.

Default Action

DefWindowProc returns the handle of the big or small icon associated with the window, depending on the value of fType.

Remarks

When an application receives this message, it can return the handle of a big or small icon, or pass the message to DefWindowProc.

See Also

DefWindowProc, WM_SETICON


WM_GETMINMAXINFO
 WM_GETMINMAXINFO  QuickInfo  Overview  Group

WM_GETMINMAXINFO

lpmmi = (LPMINMAXINFO) lParam; // address of structure

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.

Parameters

lpmmi

Value of lParam. Points 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 Value

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.

See Also

MoveWindow, SetWindowPos, MINMAXINFO


WM_GETTEXT
 WM_GETTEXT  QuickInfo  Overview  Group

WM_GETTEXT

wParam = (WPARAM) cchTextMax;   // number of characters to copy

lParam = (LPARAM) lpszText;     // address of buffer for text

An application sends a WM_GETTEXT message to copy the text that corresponds to a window into a buffer provided by the caller.

Parameters

cchTextMax

Value of wParam. Specifies the maximum number of characters to be copied, including the terminating null character.

lpszText

Value of lParam. Points to the buffer that is to receive the text.

Return Value

The return value is the number of characters copied.

Default Action

The DefWindowProc function copies the text associated with the window into the specified buffer and returns the number of characters copied.

Remarks

For an edit control, the text to be copied is the content of the edit control. For a combo box, the text is the content of the edit control (or static-text) portion of the combo box. For a button, the text is the button name. For other windows, the text is the window title. To copy the text of an item in a list box, an application can use the LB_GETTEXT message.

When the WM_GETTEXT message is sent to a static control with the SS_ICON style, the handle of the icon will be returned in the first four bytes of the buffer pointed to by lpszText. This is true only if the WM_SETTEXT message has been used to set the icon.

See Also

DefWindowProc, GetWindowText, GetWindowTextLength, LB_GETTEXT, WM_GETTEXTLENGTH, WM_SETTEXT


WM_GETTEXTLENGTH
 WM_GETTEXTLENGTH  QuickInfo

WM_GETTEXTLENGTH

wParam = 0; // not used; must be zero

lParam = 0; // not used; must be zero

An application sends a WM_GETTEXTLENGTH message to determine the length, in characters, of the text associated with a window. The length does not include the terminating null character.

Parameters

This message has no parameters.

Return Value

The return value is the length, in characters, of the text.

Default Action

The DefWindowProc function returns the length, in characters, of the text. Under certain conditions, this value may actually be greater than the length of the text. For more information, see the following Remarks section.

Remarks

For an edit control, the text to be copied is the content of the edit control. For a combo box, the text is the content of the edit control (or static-text) portion of the combo box. For a button, the text is the button name. For other windows, the text is the window title. To determine the length of an item in a list box, an application can use the LB_GETTEXTLEN message.

Under certain conditions, the DefWindowProc function returns a value that is larger than the actual length of the text. This occurs with certain mixtures of ANSI and Unicode, and is due to the operating 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.

See Also

CB_GETLBTEXT, DefWindowProc, GetWindowText, GetWindowTextLength, LB_GETTEXT, LB_GETTEXTLEN, WM_GETTEXT


WM_HELP [New - Windows NT]
 WM_HELP  QuickInfo  Overview  Group

[New - Windows NT]

WM_HELP

lphi = (LPHELPINFO) lParam;

The WM_HELP message indicates that the user pressed the F1 key. If a menu is active when F1 is pressed, WM_HELP is sent to the window associated with the menu; otherwise, WM_HELP is sent to the window that has the keyboard focus. If no Window has the keyboard focus, WM_HELP is sent to the currently active window.

Parameters

lphi

Pointer to a HELPINFO structure that contains information about the menu item, control, dialog box, or window for which help is requested.

Return Value

Returns TRUE.

Remarks

The DefWindowProc function passes WM_HELP to the parent window of a child window or to the owner of a top-level window.

See Also

DefWindowProc, HELPINFO


WM_HOTKEY
 WM_HOTKEY  QuickInfo  Overview  Group

WM_HOTKEY

idHotKey = (int) wParam;              // identifier of hot key

fuModifiers = (UINT) LOWORD(lParam);  // key-modifier flags

uVirtKey = (UINT) HIWORD(lParam);     // virtual-key code

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.

Parameters

idHotKey

Value of wParam. Specifies the identifier of the hot key that generated the message. If the message was generated by a system-defined hot key, the idHotKey parameter will be one of the following values:

Value	Meaning
IDHOT_SNAPDESKTOP	The "snap desktop" hot key was pressed.
IDHOT_SNAPWINDOW	The "snap window" hot key was pressed.
fuModifiers

Specifies the keys that were to be pressed in combination with the key specified by the nVirtKey parameter to generate the WM_HOTKEY message. The fuModifiers parameter can be a combination of the following values:

Value	Meaning
MOD_ALT	Either ALT key was held down.
MOD_CONTROL	Either CTRL key was held down.
MOD_SHIFT	Either SHIFT key was held down.
MOD_WIN	Either WINDOWS key was held down. These keys appear only on the Microsoft Ergonomic Keyboard and are labeled with the Microsoft Windows logo.
uVirtKey

Specifies the virtual key code of the hot key.

Remarks

WM_HOTKEY is unrelated to the WM_GETHOTKEY and WM_SETHOTKEY hot keys. The WM_HOTKEY message is sent for generic hot keys while the WM_SET\GETHOTKEY messages relate to window activation hot keys.

See Also

RegisterHotKey, WM_GETHOTKEY, WM_SETHOTKEY


WM_HSCROLL
 WM_HSCROLL  QuickInfo  Overview  Group

WM_HSCROLL

nScrollCode = (int) LOWORD(wParam);  // scroll bar value

nPos = (short int) HIWORD(wParam);   // scroll box position

hwndScrollBar = (HWND) lParam;       // handle of scroll bar

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.

Parameters

nScrollCode

Value of the low-order word of wParam. Specifies a scroll bar value that indicates the user's scrolling request. This parameter can be one of the following values:

Value	Meaning
SB_BOTTOM	Scrolls to the lower right.
SB_ENDSCROLL	Ends scroll.
SB_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	Scrolls to the absolute position. The current position is specified by the nPos parameter.
SB_THUMBTRACK	Drags scroll box to the specified position. The current position is specified by the nPos parameter.
SB_TOP	Scrolls to the upper left.
nPos

Value of the high-order word of wParam. Specifies the current position of the scroll box if the nScrollCode parameter is SB_THUMBPOSITION or SB_THUMBTRACK; otherwise, nPos is not used.

hwndScrollBar

Value of lParam. Identifies the control if WM_HSCROLL is sent by a scroll bar control. If WM_HSCROLL is sent by a window's standard scroll bar, hwndScrollBar is not used.

Return Value

If an application processes this message, it should return zero.

Remarks

The SB_THUMBTRACK notification message is typically used by applications that provide feedback as the user drags the scroll box.

If an application scrolls the content of the window, it must also reset the position of the scroll box by using the SetScrollPos function.

Note that the WM_HSCROLL message carries only 16 bits of scroll box position data. Thus, applications that rely solely on WM_HSCROLL (and WM_VSCROLL) for scroll position data have a practical maximum position value of 65,535.

However, because the SetScrollPos, SetScrollRange, 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 GetScrollPos for a description of the technique and its limits.

See Also

GetScrollPos, GetScrollRange, SetScrollPos, SetScrollRange, WM_VSCROLL


WM_HSCROLLCLIPBOARD
 WM_HSCROLLCLIPBOARD  QuickInfo  Overview  Group

WM_HSCROLLCLIPBOARD

hwndViewer = (HWND) wParam;         // handle of clipboard viewer window

nScrollCode = (int) LOWORD(lParam); // scroll bar code

nPos = (int) HIWORD(lParam);        // scroll box position

The WM_HSCROLLCLIPBOARD message is sent to the clipboard owner by a clipboard viewer window. This occurs when the clipboard contains data in the CF_OWNERDISPLAY format and an event occurs in the clipboard viewer's horizontal scroll bar. The owner should scroll the clipboard image and update the scroll bar values.

Parameters

hwndViewer

Value of wParam. Identifies the clipboard viewer window.

nScrollCode

Value of the low-order word of lParam. Specifies a scroll bar event. This parameter can be one of the following values:

Value	Meaning
SB_BOTTOM	Scroll to lower right.
SB_ENDSCROLL	End scroll.
SB_LINEDOWN	Scroll one line down.
SB_LINEUP	Scroll one line up.
SB_PAGEDOWN	Scroll one page down.
SB_PAGEUP	Scroll one page up.
SB_THUMBPOSITION	Scroll to absolute position. The current position is specified by the nPos parameter.
SB_TOP	Scroll to upper left.
nPos

Value of the high-order word of lParam. Specifies the current position of the scroll box if the nScrollCode parameter is SB_THUMBPOSITION; otherwise, the nPos parameter is not used.

Return Value

If an application processes this message, it should return zero.

Remarks

The clipboard owner can use the ScrollWindow function to scroll the image in the clipboard viewer window and invalidate the appropriate region.

See Also

ScrollWindow


WM_ICONERASEBKGND
 WM_ICONERASEBKGND  QuickInfo  Overview  Group

WM_ICONERASEBKGND

hdc = (HDC) wParam; // handle of device context

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.

Parameters

hdc

Value of wParam. Identifies the device context of the icon.

Return Value

An application should return nonzero if it processes this message.

Remarks

The DefWindowProc function fills the icon background with the class background brush of the parent window.

See Also

DefWindowProc, WM_ERASEBKGND


WM_IME_CHAR [New - Windows 95]
 WM_IME_CHAR  QuickInfo  Overview  Group

[New - Windows 95]

chCharCode1 = (TCHAR) wParam;
chCharCode2 = (TCHAR) wParam>>8;
lKeyData = lParam;

The WM_IME_CHAR message is sent to an application when the IME gets a character of the conversion result. Unlike the WM_CHAR message, this message can include double-byte as well as single-byte character values.

Parameters

chCharCode1 and chCharCode2

Single- or double-byte character value.

lKeyData

Repeat count, scan code, extended-key flag, context code, previous key-state flag, and transition-state flag, as shown following:

Bit	Meaning
0 - 15	Repeat count: Since the first byte and second byte is continuous, this is always 1.
16 - 23	Scan Code: Scan code for complete a FE character.
24 - 28	Not used.
29	Context code.
31	Conversion state.
Remarks

If the WM_IME_CHAR message includes a double-byte character, the DefWindowProc function converts this message into two WM_CHAR messages, each containing one byte of the double-byte character.

See Also

DefWindowProc, WM_CHAR


WM_IME_COMPOSITION [New - Windows 95]
 WM_IME_COMPOSITION  QuickInfo  Overview  Group

[New - Windows 95]

chDBCS = (WORD) wParam;
fFlags = (BOOL) lParam;

The WM_IME_COMPOSITION message is sent to an application when the IME changes composition status as a result of a key stroke. An application should process this message if it displays composition characters itself. Otherwise, it should send the message to the IME window.

Parameters

chDBCS

DBCS character representing the latest change to the composition string.

fFlags

Change flag, indicating how the composition string or character changed. This parameter can be one or more of the following values:

GCS_COMPSTR	GCS_SETCURSORPOS
GCS_COMPATTR	GCS_RESULTSTR
GCS_COMPCLAUSE	GCS_RESULTCLAUSE
GCS_COMPREADSTR	GCS_RESULTREADSTR
GCS_COMPREADATTR	GCS_RESULTREADCLAUSE
GCS_COMPREADCLAUSE	GCR_ERRORSTR
GCS_TYPINGINFO	GCR_INFOSTR
Return Value

No return value.

Remarks

For more information about these values, see the "IME Composition String Values" table in Input Method Editor Constants.

The fFlags parameter can also be a combination of the following values:

Value	Meaning
CS_INSERTCHAR	Specifies that the given composition character should be inserted at the current insertion point. An application should display the composition character if it processes this message.
CS_NOMOVECARET	Specifies that the application must not move the caret position as a result of processing the message. For example, if an IME specifies a combination of CS_INSERTCHAR and CS_NOMOVECARET, the application should insert the given character at the current caret position but should not move caret to the next position. A subsequent WM_IME_COMPOSITION message with GCS_RESULTSTR will replace this character.
If the application has created an IME window, it should pass this message to that window. The DefWindowProc function processes this message by passing it to the default IME window.The IME window processes this message by updating its appearance based on the change flag given. An application can call ImmGetCompositionString to retrieve the new composition status.

If none of the GCS_ values are set, the message indicates that the current composition has been canceled and applications that draw the composition string should delete the string.

See Also

DefWindowProc, ImmGetCompositionString


WM_IME_COMPOSITIONFULL(preliminary-Windows 95) [New - Windows 95]
 WM_IME_COMPOSITIONFULL  QuickInfo  Overview  Group

[New - Windows 95]

The WM_IME_COMPOSITIONFULL message is sent to an application when the IME window finds no space to extend the area for the composition window. The application should use the IMC_SETCOMPOSITIONWINDOW message to specify how to display the window.

Return Value

No return value.

Remarks

The wParam and lParam parameters are not used. The IME window, not the IME, sends this notification message by using the SendMessage message.

See Also

IMC_SETCOMPOSITIONWINDOW, SendMessage


WM_IME_CONTROL [New - Windows 95]
 WM_IME_CONTROL  QuickInfo  Overview  Group

[New - Windows 95]

wParam = (WPARAM) (DWORD) dwCommand;
lParam = (LPARAM) (DWORD) dwData;

The WM_IME_CONTROL message directs the IME window to carry out the requested command. An application uses this message to control the IME window created by the application.

Parameters

dwCommand

Command value. This parameter can be one of the following values:

IMC_GETCANDIDATEPOS	IMC_OPENSTATUSWINDOW
IMC_GETCOMPOSITIONFONT	IMC_SETCANDIDATEPOS
IMC_GETCOMPOSITIONWINDOW	IMC_SETCOMPOSITIONFONT
IMC_GETCONVERSIONMODE	IMC_SETCOMPOSITIONWINDOW
IMC_GETOPENSTATUS	IMC_SETCONVERSIONMODE
IMC_GETSENTENCEMODE	IMC_SETOPENSTATUS
IMC_GETSTATUSWINDOWPOS	IMC_SETSENTENCEMODE
IMC_CLOSESTATUSWINDOW	IMC_SETSTATUSWINDOWPOS
For more information about these commands, see the individual descriptions.

dwData

Command-specific value.

Return Value

Returns a command-specific value.

See Also

IMC_CLOSESTATUSWINDOW, IMC_GETCANDIDATEPOS, IMC_GETCOMPOSITIONFONT, IMC_GETCOMPOSITIONWINDOW, IMC_GETCONVERSIONMODE, IMC_GETOPENSTATUS, IMC_GETSENTENCEMODE, IMC_GETSTATUSWINDOWPOS, IMC_OPENSTATUSWINDOW, IMC_SETCANDIDATEPOS, IMC_SETCOMPOSITIONFONT, IMC_SETCOMPOSITIONWINDOW, IMC_SETCONVERSIONMODE, IMC_SETOPENSTATUS, IMC_SETSENTENCEMODE, IMC_SETSTATUSWINDOWPOS


WM_IME_ENDCOMPOSITION(preliminary-Windows 95) [New - Windows 95]
 WM_IME_ENDCOMPOSITION  QuickInfo  Overview  Group

[New - Windows 95]

The WM_IME_ENDCOMPOSITION message is sent to an application when the IME ends composition. An application should process this message if it displays composition characters itself.

Return Value

No return value.

Remarks

The wParam and lParam parameters are not used.

If an application has created an IME window, it should pass this message to that window. The DefWindowProc function processes this message by passing it to default IME window.

See Also

DefWindowProc


WM_IME_KEYDOWN
 WM_IME_KEYDOWN  QuickInfo

nVirtKey = (int) wParam;    // virtual-key code
lKeyData = lParam;          // key data

The WM_IME_KEYDOWN message is sent to an application by the IME to notify the application of a key press. The parameters and return value for this message are identical to the WM_KEYDOWN message. An application can process this message or pass it to the DefWindowProc function to generate a matching WM_KEYDOWN message. This message is usually generated by the IME to keep message order.

See Also

DefWindowProc


WM_IME_KEYUP
 WM_IME_KEYUP  QuickInfo

nVirtKey = (int) wParam;    // virtual-key code
lKeyData = lParam;          // key data

The WM_IME_KEYUP message is sent to an application by the IME to notify the application of a key release. The parameters and return value for this message are identical to the WM_KEYUP message. An application can process this message or pass it to the DefWindowProc function to generate a matching WM_KEYUP message. This message is usually generated by the IME to keep message order.

See Also

DefWindowProc


WM_IME_NOTIFY [New - Windows 95]
 WM_IME_NOTIFY  QuickInfo  Overview  Group

[New - Windows 95]

dwCommand = (DWORD) wParam;
dwData = (DWORD) lParam;

The WM_IME_NOTIFY message is sent to an application to notify it of changes to the IME window. An application processes this message if it is responsible for managing the IME window.

Parameters

dwCommand

Command value. This parameter may be one of the following values:

IMN_CHANGECANDIDATE	IMN_SETCANDIDATEPOS
IMN_CLOSECANDIDATE	IMN_SETCOMPOSITIONFONT
IMN_CLOSESTATUSWINDOW	IMN_SETCOMPOSITIONWINDOW
IMN_GUIDELINE	IMN_SETCONVERSIONMODE
IMN_OPENCANDIDATE	IMN_SETOPENSTATUS
IMN_OPENSTATUSWINDOW	IMN_SETSENTENCEMODE
IMN_PRIVATE	IMN_SETSTATUSWINDOWPOS
For more information about these commands, see the corresponding descriptions.

dwData

Command-specific value.

Return Value

Returns a command-specific value.

IMN_CHANGECANDIDATE, IMN_OPENCANDIDATE, IMN_OPENSTATUSWINDOW, IMN_SETCANDIDATEPOS, IMN_SETCOMPOSITIONFONT, IMN_SETCOMPOSITIONWINDOW, IMN_SETCONVERSIONMODE, IMN_SETOPENSTATUS, IMN_SETSENTENCEMODE, IMN_SETSTATUSWINDOWPOS


WM_IME_SELECT [New - Windows 95]
 WM_IME_SELECT  QuickInfo  Overview  Group

[New - Windows 95]

fSeleft = (BOOL) wParam;
hKL = (HANDLE) lParam;

The WM_IME_SELECT message is sent to an application when the system is about to change the current IME. An application that has created an IME window should pass this message to that window so that it can retrieve the keyboard layout handle for the newly selected IME.

Parameters

fSelect

Selection flag. If TRUE, the specified IME is selected; if FALSE, the specified IME is no longer selected.

hKL

Handle to the keyboard layout associated with the IME.

Return Value

No return value.

Remarks

The DefWindowProc function processes this message by passing the information to the default IME window.

See Also

DefWindowProc


WM_IME_SETCONTEXT [New - Windows 95]
 WM_IME_SETCONTEXT  QuickInfo  Overview  Group

[New - Windows 95]

fSet = (BOOL) wParam;
iShow = (DWORD) lParam;

The WM_IME_SETCONTEXT message is sent to an application when a window of the application is activated. If the application has created an IME window, it should call the ImmIsUIMessage function. Otherwise, it should pass this message to the DefWindowProc function.

Parameters

fSet

Active flag. If TRUE, the input context is active. If FALSE, the context is inactive.

iShow

Show flags. Can be a combination of the following values:

Value	Description
ISC_SHOWUICOMPOSITIONWINDOW	Shows the composition window by UI window.
ISC_SHOWUIGUIDWINDOW	Shows the guide window by UI window
ISC_SHOWUISOFTKBD	Shows the soft keyboard by UI window
ISC_SHOWUICANDIDATEWINDOW	Shows the candidate window of Index 0 by UI window.
ISC_SHOWUICANDIDATEWINDOW << 1	Shows the candidate window of Index 1 by UI window.
ISC_SHOWUICANDIDATEWINDOW << 2	Shows the candidate window of Index 2 by UI window.
ISC_SHOWUICANDIDATEWINDOW << 3	Shows the candidate window of Index 3 by UI window.
If the application draws the composition window, the default IME window does not need to show its composition window. In this case, the application must clear the ISC_SHOWUICOMPOSITIONWINDOW value from the lParam parameter before passing the message to the DefWindowProc or ImmIsUIMessage functions.

Return Value

Returns the value returned by DefWindowProc or ImmIsUIMessage.

See Also

DefWindowProc, ImmIsUIMessage


WM_IME_STARTCOMPOSITION(preliminary-Windows 95) [New - Windows 95]
 WM_IME_STARTCOMPOSITION  QuickInfo  Overview  Group

[New - Windows 95]

The WM_IME_STARTCOMPOSITION message is sent immediately before the IME generates composition string as a result of a key stroke. The message is a notification to an IME window to open its composition window. An application should process this message if it displays composition characters itself.

Return Value

No return value.

Remarks

The wParam and lParam parameters are not used.

If an application has created an IME window, it should pass the WM_IME_STARTCOMPOSITION message to that window. The DefWindowProc function processes this message by passing it to the default IME window.

See Also

DefWindowProc


WM_INITDIALOG
 WM_INITDIALOG  QuickInfo  Overview  Group

WM_INITDIALOG

hwndFocus = (HWND) wParam; // handle of control to receive focus

lInitParam = lParam;       // initialization parameter

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.

Parameters

hwndFocus

Value of wParam. Identifies the control to receive the default keyboard focus. Windows assigns the default keyboard focus only if the dialog box procedure returns TRUE.

lInitParam

Value of lParam. Specifies additional initialization data. This data is passed to Windows as the lParamInit parameter in a call to the CreateDialogIndirectParam, CreateDialogParam, DialogBoxIndirectParam, or DialogBoxParam function used to create the dialog box. This parameter is zero if any other dialog box creation function is used.

Return Value

The dialog box procedure should return TRUE to direct Windows to set the keyboard focus to the control given by hwndFocus. Otherwise, it should return FALSE to prevent Windows from setting the default keyboard focus.

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, Windows checks the control to ensure that the procedure has not disabled it. If it has been disabled, Windows 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.

See Also

CreateDialogIndirectParam, CreateDialogParam, DialogBoxIndirectParam, DialogBoxParam, SetFocus


WM_INITMENU
 WM_INITMENU  QuickInfo  Overview  Group

WM_INITMENU

hmenuInit = (HMENU) wParam; // handle of menu to initialize

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.

Parameters

hmenuInit

Value of wParam. Identifies the menu to be initialized.

Return Value

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.

See Also

WM_INITMENUPOPUP


WM_INITMENUPOPUP
 WM_INITMENUPOPUP  QuickInfo  Overview  Group

WM_INITMENUPOPUP

hmenuPopup = (HMENU) wParam;         // handle of pop-up menu

uPos = (UINT) LOWORD(lParam);        // pop-up item position

fSystemMenu = (BOOL) HIWORD(lParam); // System menu flag

The WM_INITMENUPOPUP message is sent when a pop-up menu is about to become active. This allows an application to modify the pop-up menu before it is displayed, without changing the entire menu.

Parameters

hmenuPopup

Value of wParam. Identifies the pop-up menu.

uPos

Value of the low-order word of lParam. Specifies the zero-based relative position of the menu item that invokes the pop-up menu.

fSystemMenu

Value of the high-order word of lParam. Specifies whether the pop-up menu is the System menu. If the pop-up menu is the System menu (also known as Control menu), this parameter is TRUE; otherwise, it is FALSE.

Return Value

If an application processes this message, it should return zero.

See Also

WM_INITMENU


WM_INPUTLANGCHANGE [New - Windows 95]
 WM_INPUTLANGCHANGE

[New - Windows 95]

WM_INPUTLANGCHANGE
charset = wParam;
hkl = (HKL) lParam;

The WM_INPUTLANGCHANGE message is sent to the topmost affected window after a task's locale has been changed. It should be used to make any application-specific settings and passed on to the DefWindowProc function to be passed on to any children.

Parameters

charset

Value of wParam. Specifies the character set of the new keyboard layout.

hkl

Value of lParam. Identifies the new keyboard layout.

Return Value

An application should return nonzero if it processes this message.

See Also

DefWindowProc, WM_INPUTLANGCHANGEREQUEST


WM_INPUTLANGCHANGEREQUEST [New - Windows 95]
 WM_INPUTLANGCHANGEREQUEST

[New - Windows 95]

WM_INPUTLANGCHANGEREQUEST
fSysCharSet = (BOOL) wParam

hkl = (HKL) lParam;

The WM_INPUTLANGCHANGEREQUEST message is sent when the user chooses an input language, either with an input language change hotkey or from the system languages menu. 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.

Parameters

wParam

This parameter is TRUE if the handle of the keyboard layout can be used with the system character set. For example, in the Russian-language version of Windows 95, this parameter is TRUE for keyboard layout handles for English (US) and Russian, but FALSE for other handles.

hkl

Value of lParam. Identifies the keyboard layout to switch to.

Return Value

The application should return nonzero if it processes this message. It should return zero to reject the change.

See Also

DefWindowProc, WM_INPUTLANGCHANGE


WM_KEYDOWN
 WM_KEYDOWN  QuickInfo  Overview  Group

WM_KEYDOWN

nVirtKey = (int) wParam;    // virtual-key code

lKeyData = lParam;          // key data

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.

Parameters

nVirtKey

Value of wParam. Specifies the virtual-key code of the nonsystem key.

lKeyData

Value of lParam. Specifies the repeat count, scan code, extended-key flag, context code, previous key-state flag, and transition-state flag, as shown in the following table:

Value	Description
0−15	Specifies the repeat count. The value is the number of times the keystroke is repeated as a result of the user holding down the key.
16−23	Specifies the scan code. The value depends on the original equipment manufacturer (OEM).
24	Specifies whether the key is an extended key, such as the right-hand ALT and CTRL keys that appear on an enhanced 101- or 102-key keyboard. The value is 1 if it is an extended key; otherwise, it is 0.
25−28	Reserved; do not use.
29	Specifies the context code. The value is always 0 for a WM_KEYDOWN message.
30	Specifies the previous key state. The value is 1 if the key is down before the message is sent, or it is 0 if the key is up.
31	Specifies the transition state. The value is always 0 for a WM_KEYDOWN message.
Return Value

An application should return zero if it processes this message.

Default Action

If the F10 key is pressed, the DefWindowProc function sets an internal flag. When DefWindowProc receives the WM_KEYUP message, the function checks whether the internal flag is set and, if so, sends a WM_SYSCOMMAND message to the top-level window. The wParam parameter of the message is set to SC_KEYMENU.

Remarks

Because of the autorepeat feature, more than one WM_KEYDOWN message may be posted before a WM_KEYUP message is posted. The previous key state (bit 30) can be used to determine whether the WM_KEYDOWN message indicates the first down transition or a repeated down transition.

For enhanced 101- and 102-key keyboards, extended keys are the right ALT and CTRL keys on the main section of the keyboard; the INS, DEL, HOME, END, PAGE UP, PAGE DOWN and arrow keys in the clusters to the left of the numeric keypad; and the divide (/) and ENTER keys in the numeric keypad. Other keyboards may support the extended-key bit in the lKeyData parameter.

See Also

DefWindowProc, WM_CHAR, WM_KEYUP, WM_SYSCOMMAND


WM_KEYUP
 WM_KEYUP  QuickInfo  Overview  Group

WM_KEYUP

nVirtKey = (int) wParam;    // virtual-key code

lKeyData = lParam;          // key data

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.

Parameters

nVirtKey

Value of wParam. Specifies the virtual-key code of the nonsystem key.

lKeyData

Value of lParam. Specifies the repeat count, scan code, extended-key flag, context code, previous key-state flag, and transition-state flag, as shown in the following table:

Value	Description
0−15	Specifies the repeat count. The value is the number of times the keystroke is repeated as a result of the user holding down the key. The repeat count is always one for a WM_KEYUP message.
16−23	Specifies the scan code. The value depends on the original equipment manufacturer (OEM).
24	Specifies whether the key is an extended key, such as the right-hand ALT and CTRL keys that appear on an enhanced 101- or 102-key keyboard. The value is 1 if it is an extended key; otherwise, it is 0.
25−28	Reserved; do not use.
29	Specifies the context code. The value is always 0 for a WM_KEYUP message.
30	Specifies the previous key state. The value is always 1 for a WM_KEYUP message.
31	Specifies the transition state. The value is always 1 for a WM_KEYUP message.
Return Value

An application should return zero if it processes this message.

Default Action

The DefWindowProc function sends a WM_SYSCOMMAND message to the top-level window if the F10 key or the ALT key was released. The wParam parameter of the message is set to SC_KEYMENU.

Remarks

For enhanced 101- and 102-key keyboards, extended keys are the right ALT and CTRL keys on the main section of the keyboard; the INS, DEL, HOME, END, PAGE UP, PAGE DOWN and arrow keys in the clusters to the left of the numeric keypad; and the divide (/) and ENTER keys in the numeric keypad. Other keyboards may support the extended-key bit in the lKeyData parameter.

See Also

DefWindowProc, WM_KEYDOWN, WM_SYSCOMMAND


WM_KILLFOCUS
 WM_KILLFOCUS  QuickInfo  Overview  Group

WM_KILLFOCUS

hwndGetFocus = (HWND) wParam; // handle of window receiving focus

The WM_KILLFOCUS message is sent to a window immediately before it loses the keyboard focus.

Parameters

hwndGetFocus

Value of wParam. Identifies the window that receives the keyboard focus (may be NULL).

Return Value

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.

See Also

SetFocus, WM_SETFOCUS


WM_LBUTTONDBLCLK
 WM_LBUTTONDBLCLK  QuickInfo  Overview  Group

WM_LBUTTONDBLCLK

fwKeys = wParam;        // key flags

xPos = LOWORD(lParam);  // horizontal position of cursor

yPos = HIWORD(lParam);  // vertical position of cursor

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.

Parameters

fwKeys

Value of wParam. Indicates whether various virtual keys are down. This parameter can be any combination of the following values:

Value	Description
MK_CONTROL	Set if the CTRL key is down.
MK_LBUTTON	Set if the left mouse button is down.
MK_MBUTTON	Set if the middle mouse button is down.
MK_RBUTTON	Set if the right mouse button is down.
MK_SHIFT	Set if the SHIFT key is down.
xPos

Value of the low-order word of lParam. Specifies the x-coordinate of the cursor. The coordinate is relative to the upper-left corner of the client area.

yPos

Value of the high-order word of lParam. Specifies the y-coordinate of the cursor. The coordinate is relative to the upper-left corner of the client area.

Return Value

If an application processes this message, it should return zero.

Remarks

Only windows that have the CS_DBLCLKS style can receive WM_LBUTTONDBLCLK messages, which Windows generates whenever the user presses, releases, and again presses the left mouse button within the system's double-click time limit. Double-clicking the left mouse button actually generates four messages: WM_LBUTTONDOWN, WM_LBUTTONUP, WM_LBUTTONDBLCLK, and WM_LBUTTONUP again.

An application can use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

See Also

GetCapture, GetDoubleClickTime, MAKEPOINTS, POINTS, SetCapture, SetDoubleClickTime, WM_LBUTTONDOWN, WM_LBUTTONUP


WM_LBUTTONDOWN
 WM_LBUTTONDOWN  QuickInfo  Overview  Group

WM_LBUTTONDOWN

fwKeys = wParam;        // key flags

xPos = LOWORD(lParam);  // horizontal position of cursor

yPos = HIWORD(lParam);  // vertical position of cursor

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.

Parameters

fwKeys

Value of wParam. Indicates whether various virtual keys are down. This parameter can be any combination of the following values:

Value	Description
MK_CONTROL	Set if the CTRL key is down.
MK_LBUTTON	Set if the left mouse button is down.
MK_MBUTTON	Set if the middle mouse button is down.
MK_RBUTTON	Set if the right mouse button is down.
MK_SHIFT	Set if the SHIFT key is down.
xPos

Value of the low-order word of lParam. Specifies the x-coordinate of the cursor. The coordinate is relative to the upper-left corner of the client area.

yPos

Value of the high-order word of lParam. Specifies the y-coordinate of the cursor. The coordinate is relative to the upper-left corner of the client area.

Return Value

If an application processes this message, it should return zero.

Remarks

An application can use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

See Also

GetCapture, MAKEPOINTS, POINTS, SetCapture, WM_LBUTTONDBLCLK, WM_LBUTTONUP


WM_LBUTTONUP
 WM_LBUTTONUP  QuickInfo  Overview  Group

WM_LBUTTONUP

fwKeys = wParam;        // key flags

xPos = LOWORD(lParam);  // horizontal position of cursor

yPos = HIWORD(lParam);  // vertical position of cursor

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.

Parameters

fwKeys

Value of wParam. Indicates whether various virtual keys are down. This parameter can be any combination of the following values:

Value	Description
MK_CONTROL	Set if the CTRL key is down.
MK_MBUTTON	Set if the middle mouse button is down.
MK_RBUTTON	Set if the right mouse button is down.
MK_SHIFT	Set if the SHIFT key is down.
xPos

Value of the low-order word of lParam. Specifies the x-coordinate of the cursor. The coordinate is relative to the upper-left corner of the client area.

yPos

Value of the high-order word of lParam. Specifies the y-coordinate of the cursor. The coordinate is relative to the upper-left corner of the client area.

Return Value

If an application processes this message, it should return zero.

Remarks

An application can use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

See Also

GetCapture, MAKEPOINTS, POINTS, SetCapture, WM_LBUTTONDBLCLK, WM_LBUTTONDOWN


WM_MBUTTONDBLCLK
 WM_MBUTTONDBLCLK  QuickInfo  Overview  Group

WM_MBUTTONDBLCLK

fwKeys = wParam;        // key flags

xPos = LOWORD(lParam);  // horizontal position of cursor

yPos = HIWORD(lParam);  // vertical position of cursor

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.

Parameters

fwKeys

Value of wParam. Indicates whether various virtual keys are down. This parameter can be any combination of the following values:

Value	Description
MK_CONTROL	Set if the CTRL key is down.
MK_LBUTTON	Set if the left mouse button is down.
MK_MBUTTON	Set if the middle mouse button is down.
MK_RBUTTON	Set if the right mouse button is down.
MK_SHIFT	Set if the SHIFT key is down.
xPos

Value of the low-order word of lParam. Specifies the x-coordinate of the cursor. The coordinate is relative to the upper-left corner of the client area.

yPos

Value of the high-order word of lParam. Specifies the y-coordinate of the cursor. The coordinate is relative to the upper-left corner of the client area.

Return Value

If an application processes this message, it should return zero.

Remarks

Only windows that have the CS_DBLCLKS style can receive WM_MBUTTONDBLCLK messages, which Windows generates whenever the user presses, releases, and again presses the middle mouse button within the system's double-click time limit. Double-clicking the middle mouse button actually generates four messages: WM_MBUTTONDOWN, WM_MBUTTONUP, WM_MBUTTONDBLCLK, and WM_MBUTTONUP again.

An application can use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

See Also

GetCapture, GetDoubleClickTime, MAKEPOINTS, POINTS, SetCapture, SetDoubleClickTime, WM_MBUTTONDOWN, WM_MBUTTONUP


WM_MBUTTONDOWN
 WM_MBUTTONDOWN  QuickInfo  Overview  Group

WM_MBUTTONDOWN

fwKeys = wParam;        // key flags

xPos = LOWORD(lParam);  // horizontal position of cursor

yPos = HIWORD(lParam);  // vertical position of cursor

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.

Parameters

fwKeys

Value of wParam. Indicates whether various virtual keys are down. This parameter can be any combination of the following values:

Value	Description
MK_CONTROL	Set if the CTRL key is down.
MK_LBUTTON	Set if the left mouse button is down.
MK_MBUTTON	Set if the middle mouse button is down.
MK_RBUTTON	Set if the right mouse button is down.
MK_SHIFT	Set if the SHIFT key is down.
xPos

Value of the low-order word of lParam. Specifies the x-coordinate of the cursor. The coordinate is relative to the upper-left corner of the client area.

yPos

Value of the high-order word of lParam. Specifies the y-coordinate of the cursor. The coordinate is relative to the upper-left corner of the client area.

Return Value

If an application processes this message, it should return zero.

Remarks

An application can use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

See Also

GetCapture, MAKEPOINTS, POINTS, SetCapture, WM_MBUTTONDBLCLK, WM_MBUTTONUP


WM_MBUTTONUP
 WM_MBUTTONUP  QuickInfo  Overview  Group

WM_MBUTTONUP

fwKeys = wParam;        // key flags

xPos = LOWORD(lParam);  // horizontal position of cursor

yPos = HIWORD(lParam);  // vertical position of cursor

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.

Parameters

fwKeys

Value of wParam. Indicates whether various virtual keys are down. This parameter can be any combination of the following values:

Value	Description
MK_CONTROL	Set if the CTRL key is down.
MK_LBUTTON	Set if the left mouse button is down.
MK_RBUTTON	Set if the right mouse button is down.
MK_SHIFT	Set if the SHIFT key is down.
xPos

Value of the low-order word of lParam. Specifies the x-coordinate of the cursor. The coordinate is relative to the upper-left corner of the client area.

yPos

Value of the high-order word of lParam. Specifies the y-coordinate of the cursor. The coordinate is relative to the upper-left corner of the client area.

An application can use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

See Also

GetCapture, MAKEPOINTS, POINTS, SetCapture, WM_MBUTTONDBLCLK, WM_MBUTTONDOWN


WM_MDIACTIVATE
 WM_MDIACTIVATE  QuickInfo  Overview  Group

WM_MDIACTIVATE

// Message sent to MDI client

wParam = (WPARAM) (HWND) hwndChildAct; // child to activate

lParam = 0;                            // not used; must be zero

// Message received by MDI child

hwndChildDeact = (HWND) wParam;        // child being deactivated

hwndChildAct = (HWND) lParam;          // child being activated

An application sends the WM_MDIACTIVATE message to a multiple document interface (MDI) client window to instruct the client window to activate a different MDI child window. As the client window processes this message, it sends WM_MDIACTIVATE to the child window being deactivated and to the child window being activated.

Parameters

In messages sent to an MDI client window:

hwndChildAct

Value of wParam. Identifies the MDI child window to be activated.

In messages received by an MDI child window:

hwndChildDeact

Value of wParam. Identifies the MDI child window being deactivated.

hwndChildAct

Value of lParam. Identifies the MDI child window being activated.

Return Value

If an application sends this message to an MDI client window, the return value is zero. An MDI child window should return zero if it processes this message.

Remarks

An MDI child window is activated independently of the MDI frame window. When the frame window becomes active, the child window last activated by using the WM_MDIACTIVATE message receives the WM_NCACTIVATE message to draw an active window frame and title bar; the child window does not receive another WM_MDIACTIVATE message.

See Also

WM_MDIGETACTIVE, WM_MDINEXT, WM_NCACTIVATE


WM_MDICASCADE
 WM_MDICASCADE  QuickInfo  Overview  Group

WM_MDICASCADE

wParam = (WPARAM) (UINT) fuCascade;  // cascade flag

lParam = 0;                          // not used; must be zero

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.

Parameters

fuCascade

Value of wParam. Specifies a cascade flag. The only flag currently available, MDITILE_SKIPDISABLED, prevents disabled MDI child windows from being cascaded.

Return Value

If the message succeeds, the return value is TRUE.

If the message fails, the return value is FALSE.

See Also

WM_MDIICONARRANGE, WM_MDITILE


WM_MDICREATE
 WM_MDICREATE  QuickInfo  Overview  Group

WM_MDICREATE

wParam = 0;                                     // not used; must be zero

lParam = (LPARAM) (LPMDICREATESTRUCT) lpmdic;   // creation data

An application sends the WM_MDICREATE message to a multiple document interface (MDI) client window to create an MDI child window.

Parameters

lpmdic

Points to an MDICREATESTRUCT structure containing information that Windows uses to create the MDI child window.

Return Value

If the message succeeds, the return value is the handle of the new child window.

If the message fails, the return value is NULL.

Remarks

The MDI child window is created with the style bits WS_CHILD, WS_CLIPSIBLINGS, WS_CLIPCHILDREN, WS_SYSMENU, WS_CAPTION, WS_THICKFRAME, WS_MINIMIZEBOX, and WS_MAXIMIZEBOX, plus additional style bits specified in the MDICREATESTRUCT structure to which the lpmdic parameter points. Windows 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, Windows restores the active child window and maximizes the newly activated child window.

When an MDI child window is created, Windows 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.

See Also

CreateMDIWindow, CREATESTRUCT, MDICREATESTRUCT, WM_CREATE, WM_MDIDESTROY


WM_MDIDESTROY
 WM_MDIDESTROY  QuickInfo  Overview  Group

WM_MDIDESTROY

wParam = (WPARAM) (HWND) hwndChild; // handle of child to close

lParam = 0;                         // not used; must be zero

An application sends the WM_MDIDESTROY message to a multiple document interface (MDI) client window to close an MDI child window.

Parameters

hwndChild

Value of wParam. Identifies the MDI child window to be closed.

Return Value

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, Windows restores the active child window and maximizes the newly activated child window.

See Also

WM_MDICREATE


WM_MDIGETACTIVE
 WM_MDIGETACTIVE  QuickInfo  Overview  Group

WM_MDIGETACTIVE

wParam = 0;                      // not used; must be zero

lParam = (LPBOOL) lpfMaximized;  // optional pointer to maximized state flag

An application sends the WM_MDIGETACTIVE message to a multiple document interface (MDI) client window to retrieve the handle of the active MDI child window.

Parameters

lpfMaximized

Value of lparam. This is an optional pointer to a maximized state flag variable. If lpfMaximized is non-NULL, the BOOL it points to is set to indicate the maximized state of the MDI child window. TRUE indicates that the window is maximized, FALSE indicates that it is not. This is equivalent to the indication supplied by the high-order word of the return value of the WM_MDIGETACTIVE message under Windows version 3.x. If lpfMaximized is NULL, the parameter is ignored.

Return Value

The return value is the handle of the active MDI child window.

Remarks

Note carefully a change in how this message indicates maximization. In Windows version 3.x, the message return value includes a flag indicating whether the MDI child window is maximized. In the Win32 application programming interface (API), the return value does not include this flag. In Win32, the MDI child window's maximized state is indicated by setting a BOOL variable via the optional parameter in lParam, lpfMaximized.


WM_MDIICONARRANGE
 WM_MDIICONARRANGE  QuickInfo  Overview  Group

WM_MDIICONARRANGE

wParam = 0; // not used; must be zero

lParam = 0; // not used; must be zero

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.

Parameters

This message has no parameters.

See Also

WM_MDICASCADE, WM_MDITILE


WM_MDIMAXIMIZE
 WM_MDIMAXIMIZE  QuickInfo  Overview  Group

WM_MDIMAXIMIZE

wParam = (WPARAM) (HWND) hwndMax; // handle of child to maximize

lParam = 0;                       // not used; must be zero

An application sends the WM_MDIMAXIMIZE message to a multiple document interface (MDI) client window to maximize an MDI child window. Windows resizes the child window to make its client area fill the client window. Windows places the child window's System 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. Windows also appends the title bar text of the child window to that of the frame window.

Parameters

hwndMax

Value of wParam. Identifies the MDI child window to be maximized.

Return Value

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, Windows restores the active child window and maximizes the newly activated child window.

See Also

WM_MDIRESTORE


WM_MDINEXT
 WM_MDINEXT  QuickInfo  Overview  Group

WM_MDINEXT

wParam = (WPARAM) (HWND) hwndChild; // handle of child

lParam = (LPARAM) fNext;            // next or previous child

An application sends the WM_MDINEXT message to a multiple document interface (MDI) client window to activate the next or previous child window.

Parameters

hwndChild

Value of wParam. Identifies the MDI child window. Windows activates the child window that is immediately before or after the given child window, depending on the value of the fNext parameter. If the hwndChild parameter is NULL, Windows activates the child window that is immediately before or after the currently active child window.

fNext

Value of lParam. If this parameter is zero, Windows 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, Windows activates the previous child window, placing it in front of the child window identified by hwndChild.

Return Value

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, Windows restores the active child window and maximizes the newly activated child window.

See Also

WM_MDIACTIVATE, WM_MDIGETACTIVE


WM_MDIREFRESHMENU
 WM_MDIREFRESHMENU  QuickInfo  Overview  Group

WM_MDIREFRESHMENU

wParam = 0; // not used; must be zero

lParam = 0; // not used; must be zero

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.

Parameters

This message has no parameters.

Return Value

If the message succeeds, the return value is the handle of 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.

See Also

DrawMenuBar, WM_MDISETMENU


WM_MDIRESTORE
 WM_MDIRESTORE  QuickInfo  Overview  Group

WM_MDIRESTORE

wParam = (WPARAM) (HWND) hwndRes; // handle of child to restore

lParam = 0;                       // not used; must be zero

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.

Parameters

hwndRes

Value of wParam. Identifies the MDI child window to be restored.

Return Value

The return value is always zero.

See Also

WM_MDIMAXIMIZE


WM_MDISETMENU
 WM_MDISETMENU  QuickInfo  Overview  Group

WM_MDISETMENU

wParam = (WPARAM) (HMENU) hmenuFrame;  // handle of frame menu

lParam = (LPARAM) (HMENU) hmenuWindow; // handle of Window menu

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.

Parameters

hmenuFrame

Value of wParam. Identifies the new frame window menu. If this parameter is NULL, the frame window menu is not changed.

hmenuWindow

Value of lParam. Identifies the new Window menu. If this parameter is NULL, the Window menu is not changed.

Return Value

If the message succeeds, the return value is the handle of 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 System menu icon and restore icon are removed from the previous frame window menu and added to the new frame window menu.

See Also

DrawMenuBar, WM_MDIREFRESHMENU


WM_MDITILE
 WM_MDITILE  QuickInfo  Overview  Group

WM_MDITILE

wParam = (WPARAM) (UINT) fuTile; // tiling flag

lParam = 0;                      // not used; must be zero

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.

Parameters

fuTile

Specifies a tiling flag. This parameter can be one of the following values:

Value	Meaning
MDITILE_HORIZONTAL	Tiles MDI child windows so that they are wide rather than tall.
MDITILE_SKIPDISABLED	Prevents disabled MDI child windows from being tiled.
MDITILE_VERTICAL	Tiles MDI child windows so that they are tall rather than wide.
Return Value

If the message succeeds, the return value is TRUE.

If the message fails, the return value is FALSE.

See Also

WM_MDICASCADE, WM_MDIICONARRANGE


WM_MEASUREITEM
 WM_MEASUREITEM  QuickInfo  Overview  Group

WM_MEASUREITEM

idCtl = (UINT) wParam;                // control identifier

lpmis = (LPMEASUREITEMSTRUCT) lParam; // item-size information

The WM_MEASUREITEM message is sent to the owner window of an owner-drawn button, combo box, list box, list view control, or menu item when the control or menu is created.

Parameters

idCtl

Value of wParam. Contains the value of the CtlID member of the MEASUREITEMSTRUCT structure pointed to by the lpmis parameter. This value identifies the control that sent the WM_MEASUREITEM message.

If the value is zero, the message was sent by a menu. If the value is nonzero, the message was sent by a combo box or by a list box. If the value is nonzero, and the value of the itemID member of the MEASUREITEMSTRUCT pointed to by lpmis is (UINT) −1, the message was sent by a combo edit field.

lpmis

Value of lParam. Points to a MEASUREITEMSTRUCT structure that contains the dimensions of the owner-drawn control or menu item.

Return Value

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 Windows 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.

Windows 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, Windows 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.

See Also

MEASUREITEMSTRUCT, WM_INITDIALOG


WM_MENUCHAR
 WM_MENUCHAR  QuickInfo  Overview  Group

WM_MENUCHAR

chUser = (char) LOWORD(wParam); // ASCII character

fuFlag = (UINT) HIWORD(wParam); // menu flag

hmenu = (HMENU) lParam;         // handle of menu

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.

Parameters

chUser

Value of the low-order word of wParam. Specifies the ASCII character that corresponds to the key the user pressed.

fuFlag

Value of the high-order word of wParam. Specifies the type of the active menu. This parameter can be one of the following values:

Value	Meaning
MF_POPUP	Pop-up menu
MF_SYSMENU	System menu
hmenu

Value of lParam. Identifies the active menu.

Return Value

An application that processes this message should return one of the following values in the high-order word of the return value:

Value	Meaning
0	Informs Windows that it should discard the character the user pressed and create a short beep on the system speaker.
1	Informs Windows that it should close the active menu.
2	Informs Windows that the low-order word of the return value specifies the zero-based relative position of a menu item. This item is selected by Windows.
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.


WM_MENUSELECT
 WM_MENUSELECT  QuickInfo  Overview  Group

WM_MENUSELECT

uItem = (UINT) LOWORD(wParam);   // menu item or pop-up menu index

fuFlags = (UINT) HIWORD(wParam); // menu flags

hmenu = (HMENU) lParam;          // handle of menu clicked

The WM_MENUSELECT message is sent to a menu's owner window when the user selects a menu item.

Parameters

uItem

Value of the low-order word of wParam. If the selected item is a command item, this parameter contains the identifier of the menu item. If the selected item invokes a pop-up menu, this parameter contains the menu index of the pop-up menu in the main menu, and the hMenu parameter then contains the handle of the main (clicked) menu; use the GetSubMenu function to get the menu handle of the pop-up menu.

fuFlags

Value of the high-order word of wParam. Specifies one or more menu flags. This parameter can be a combination of the following values:

Value	Description
MF_BITMAP	Item displays a bitmap.
MF_CHECKED	Item is checked.
MF_DISABLED	Item is disabled.
MF_GRAYED	Item is grayed.
MF_HILITE	Item is highlighted.
MF_MOUSESELECT	Item is selected with the mouse.
MF_OWNERDRAW	Item is an owner-drawn item.
MF_POPUP	Item invokes a pop-up menu.
MF_SYSMENU	Item is contained in the System menu (also known as Control menu). The hmenu parameter identifies the System menu associated with the message.
hmenu

Value of lParam. Identifies the menu that was clicked.

Return Value

If an application processes this message, it should return zero.

Remarks

If the fuFlags parameter contains 0xFFFF and the hmenu parameter contains NULL, Windows has closed the menu because the user pressed the ESC key or clicked outside the menu.

Do not use the value −1 for fuFlags. That is because fuFlags is specified as (UINT) HIWORD(wParam). If HIWORD(wParam) were 0xFFFF, fuFlags (because of the UINT cast) would be 0x0000FFFF, not −1.

See Also

GetSubMenu


WM_MOUSEACTIVATE
 WM_MOUSEACTIVATE  QuickInfo  Overview  Group

WM_MOUSEACTIVATE

hwndTopLevel = (HWND) wParam;       // handle of top-level parent

nHittest = (INT) LOWORD(lParam);    // hit-test value

uMsg =    (UINT) HIWORD(lParam);    // mouse message

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.

Parameters

hwndTopLevel

Value of wParam. Identifies the top-level parent window of the window being activated.

nHittest

Value of the low-order word of lParam. Specifies the hit-test value returned by the DefWindowProc function as a result of processing the WM_NCHITTEST message. For a list of hit-test values, see WM_NCHITTEST.

uMsg

Value of the high-order word of lParam. Specifies the identifier of the mouse message generated when the user pressed a mouse button. The mouse message is either discarded or posted to the window, depending on the return value.

Return Value

The return value specifies whether the window should be activated and whether the identifier of the mouse message should be discarded. It must be one of the following values:

Value	Meaning
MA_ACTIVATE	Activates the window, and does not discard the mouse message.
MA_ACTIVATEANDEAT	Activates the window, and discards the mouse message.
MA_NOACTIVATE	Does not activate the window, and does not discard the mouse message.
MA_NOACTIVATEANDEAT	Does not activate the window, but discards the mouse message.
Default Action

The DefWindowProc function passes the message to a child window's parent window before any processing occurs. The parent window determines whether to activate the child window. If it activates the child window, the parent window should return TRUE to prevent the system from processing the message further.

See Also

DefWindowProc, WM_NCHITTEST


WM_MOUSEMOVE
 WM_MOUSEMOVE  QuickInfo  Overview  Group

WM_MOUSEMOVE

fwKeys = wParam;        // key flags

xPos = LOWORD(lParam);  // horizontal position of cursor

yPos = HIWORD(lParam);  // vertical position of cursor

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.

Parameters

fwKeys

Value of wParam. Indicates whether various virtual keys are down. This parameter can be any combination of the following values:

Value	Description
MK_CONTROL	Set if the CTRL key is down.
MK_LBUTTON	Set if the left mouse button is down.
MK_MBUTTON	Set if the middle mouse button is down.
MK_RBUTTON	Set if the right mouse button is down.
MK_SHIFT	Set if the SHIFT key is down.
xPos

Value of the low-order word of lParam. Specifies the x-coordinate of the cursor. The coordinate is relative to the upper-left corner of the client area.

yPos

Value of the high-order word of lParam. Specifies the y-coordinate of the cursor. The coordinate is relative to the upper-left corner of the client area.

Remarks

The MAKEPOINTS macro can be used to convert the lParam parameter to a POINTS structure.

See Also

GetCapture, MAKEPOINTS, POINTS, SetCapture


WM_MOVE
 WM_MOVE  QuickInfo  Overview  Group

WM_MOVE

xPos = (int) LOWORD(lParam);    // horizontal position

yPos = (int) HIWORD(lParam);    // vertical position

The WM_MOVE message is sent after a window has been moved.

Parameters

xPos

Value of the low-order word of lParam. Specifies the x-coordinate of the upper-left corner of the client area of the window.

yPos

Value of the high-order word of lParam. Specifies the y-coordinate of the upper-left corner of the client area of the window.

Return Value

If an application processes this message, it should return zero.

Remarks

The xPos and yPos parameters are given in screen coordinates for overlapped and pop-up windows and in parent-client coordinates for child windows.

An application can use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

See Also

MAKEPOINTS, POINTS


WM_MOVING [New - Windows 95]
 WM_MOVING  QuickInfo

[New - Windows 95]

fwSide = wParam;	// edge of window to be moved

lprc = (LPRECT) lParam;	// screen coordinates of drag rectangle

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.

Parameters

fwSide

Value of wParam. Indicates which edge of the window is being moved. This parameter can be a combination of the following values:

Value	Meaning
WMSZ_BOTTOM	Bottom edge
WMSZ_BOTTOMLEFT	Bottom-left corner
WMSZ_BOTTOMRIGHT	Bottom-right corner
WMSZ_LEFT	Left edge
WMSZ_RIGHT	Right edge
WMSZ_TOP	Top edge
WMSZ_TOPLEFT	Top-left corner
WMSZ_TOPRIGHT	Top-right corner
lprc

Value of lParam. Address of a RECT structure with the screen coordinates of the drag rectangle. To change the size or position of the drag rectangle, an application must change the members of this structure.

Return Value

An application should return TRUE if it processes this message.

See Also

RECT, WM_MOVE, WM_SIZING


WM_NCACTIVATE
 WM_NCACTIVATE  QuickInfo  Overview  Group

WM_NCACTIVATE

fActive = (BOOL) wParam;	// new state of the title bar or icon

The WM_NCACTIVATE message is sent to a window when its nonclient area needs to be changed to indicate an active or inactive state.

Parameters

fActive

Value of wParam. Specifies when a title bar or icon needs to be changed to indicate an active or inactive state. If an active title bar or icon is to be drawn, the fActive parameter is TRUE. It is FALSE for an inactive title bar or icon.

Return Value

When the fActive parameter is FALSE, an application should return TRUE to indicate that Windows should proceed with the default processing, or it should return FALSE to prevent the title bar or icon from being deactivated. When fActive is TRUE, the return value is ignored.

Default Action

The DefWindowProc function draws the title bar or icon title in its active colors when the fActive parameter is TRUE and in its inactive colors when fActive is FALSE.

See Also

DefWindowProc


WM_NCCALCSIZE
 WM_NCCALCSIZE  QuickInfo  Overview  Group

WM_NCCALCSIZE

fCalcValidRects = (BOOL) wParam;        // valid area flag

lpncsp = (LPNCCALCSIZE_PARAMS) lParam;  // points to size calculation data

   or

lpncsp = (LPRECT) lParam;               // points to new window coordinates

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.

Parameters

fCalcValidRects

Value of wParam. A Boolean value that, if TRUE, specifies that the application should indicate which part of the client area contains valid information. The operating system copies the valid information to the specified area within the new client area. Also, if this parameter is TRUE, lParam points to an NCCALCSIZE_PARAMS structure.

If this parameter is FALSE, the application does not need to indicate the valid part of the client area. Also, if this parameter is FALSE, lParam points to a RECT structure.

lpncsp

Value of lParam.

If wParam  is TRUE, lParam points to an NCCALCSIZE_PARAMS structure that contains information an application can use to calculate the new size and position of the client rectangle.

If wParam  is FALSE, lParam points to a RECT structure that contains the new coordinates of the window that has been moved or resized. This is equivalent to rgrc[0] of an NCCALCSIZE_PARAMS structure.

Return Value

If the fCalcValidRects parameter is FALSE, the application should return zero.

If fCalcValidRects is TRUE, the application can return zero or a valid combination of the following values:

Value	Meaning
WVR_ALIGNTOP, WVR_ALIGNLEFT, WVR_ALIGNBOTTOM, WVR_ALIGNRIGHT
	These values, used in combination, specify that the client area of the window is to be preserved and aligned appropriately relative to the new position of the window. For example, to align the client area to the lower-left corner, return the WVR_ALIGNLEFT and WVR_ALIGNTOP 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 source and destination area rectangles, respectively. Windows combines these rectangles to calculate the area of the window to be preserved. Windows copies any part of the window image that is within the source rectangle and clips the image to the destination rectangle. Both rectangles are in parent-relative or screen-relative coordinates.
	This return value allows an application to implement more elaborate client-area preservation strategies, such as centering or preserving a subset of the client area.
If fCalcValidRects is TRUE and an application returns zero, the old client area is preserved and is aligned with the upper-left corner of the new client area.

Default Action

The window may be redrawn, depending on whether the CS_HREDRAW or CS_VREDRAW class style is specified. This is the default, backward-compatible processing of this message by the DefWindowProc function (in addition to the usual client rectangle calculation described in the preceding table).

See Also

DefWindowProc, MoveWindow, SetWindowPos, NCCALCSIZE_PARAMS, RECT


WM_NCCREATE
 WM_NCCREATE  QuickInfo  Overview  Group

WM_NCCREATE

lpcs = (LPCREATESTRUCT) lParam; // initialization data

The WM_NCCREATE message is sent prior to the WM_CREATE message when a window is first created.

Parameters

lpcs

Value of wParam. Points to the CREATESTRUCT structure for the window.

Return Value

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.

Default Action

The DefWindowProc function returns TRUE.

See Also

CreateWindow, CreateWindowEx, DefWindowProc, CREATESTRUCT, WM_CREATE


WM_NCDESTROY
 WM_NCDESTROY  QuickInfo  Overview  Group

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.

Parameters

This message has no parameters.

Return Value

If an application processes this message, it should return zero.

Remarks

This message frees any memory internally allocated for the window.

See Also

DestroyWindow, WM_DESTROY, WM_NCCREATE


WM_NCHITTEST
 WM_NCHITTEST  QuickInfo  Overview  Group

WM_NCHITTEST

xPos = LOWORD(lParam);  // horizontal position of cursor

yPos = HIWORD(lParam);  // vertical position of cursor

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 posted to the window that has captured the mouse.

Parameters

xPos

Value of the low-order word of lParam. Specifies the x-coordinate of the cursor. The coordinate is relative to the upper-left corner of the screen.

yPos

Value of the high-order word of lParam. Specifies the y-coordinate of the cursor. The coordinate is relative to the upper-left corner of the screen.

Return Value

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 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
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)
HTHSCROLL	In a horizontal scroll bar
HTLEFT	In the left border of a window
HTMENU	In a menu
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
HTVSCROLL	In the vertical scroll bar
HTZOOM	In a Maximize button
Remarks

An application can use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

See Also

DefWindowProc, GetCapture, MAKEPOINTS, POINTS


WM_NCLBUTTONDBLCLK
 WM_NCLBUTTONDBLCLK  QuickInfo  Overview  Group

WM_NCLBUTTONDBLCLK

nHittest = (INT) wParam;    // hit-test value

pts = MAKEPOINTS(lParam);   // position of cursor

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.

Parameters

nHittest

Value of wParam. Specifies the hit-test value returned by the DefWindowProc function as a result of processing the WM_NCHITTEST message. For a list of hit-test values, see WM_NCHITTEST.

pts

Value of lParam. Specifies a POINTS structure that contains the x- and y-coordinates of the cursor. The coordinates are relative to the upper-left corner of the screen.

Return Value

If an application processes this message, it should return zero.

Default Action

The DefWindowProc function tests the given point to find out the location of the cursor and performs the appropriate action. If appropriate, DefWindowProc sends the WM_SYSCOMMAND message to the window.

Remarks

A window need not have the CS_DBLCLKS style to receive WM_NCLBUTTONDBLCLK messages.

Windows generates a WM_NCLBUTTONDBLCLK message when the user presses, releases, and again presses the left mouse button within the system's double-click time limit. Double-clicking the left mouse button actually generates four messages: WM_NCLBUTTONDOWN, WM_NCLBUTTONUP, WM_NCLBUTTONDBLCLK, and WM_NCLBUTTONUP again.

An application can use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

See Also

DefWindowProc, MAKEPOINTS, POINTS, WM_NCHITTEST, WM_NCLBUTTONDOWN, WM_NCLBUTTONUP, WM_SYSCOMMAND


WM_NCLBUTTONDOWN
 WM_NCLBUTTONDOWN  QuickInfo  Overview  Group

WM_NCLBUTTONDOWN

nHittest = (INT) wParam;    // hit-test value

pts = MAKEPOINTS(lParam);   // position of cursor

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.

Parameters

nHittest

Value of wParam. Specifies the hit-test value returned by the DefWindowProc function as a result of processing the WM_NCHITTEST message. For a list of hit-test values, see WM_NCHITTEST.

pts

Value of lParam. Specifies a POINTS structure that contains the x- and y-coordinates of the cursor. The coordinates are relative to the upper-left corner of the screen.

Return Value

If an application processes this message, it should return zero.

Default Action

The DefWindowProc function tests the given point to find out the location of the cursor and performs the appropriate action. If appropriate, DefWindowProc sends the WM_SYSCOMMAND message to the window.

Remarks

An application can use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

See Also

DefWindowProc, MAKEPOINTS, POINTS, WM_NCHITTEST, WM_NCLBUTTONDBLCLK, WM_NCLBUTTONUP, WM_SYSCOMMAND


WM_NCLBUTTONUP
 WM_NCLBUTTONUP  QuickInfo  Overview  Group

WM_NCLBUTTONUP

nHittest = (INT) wParam;    // hit-test value

pts = MAKEPOINTS(lParam);   // mouse-cursor coordinates

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.

Parameters

nHittest

Value of wParam. Specifies the hit-test value returned by the DefWindowProc function as a result of processing the WM_NCHITTEST message. For a list of hit-test values, see WM_NCHITTEST.

pts

Value of lParam. Specifies a POINTS structure that contains the x- and y-coordinates of the cursor. The coordinates are relative to the upper-left corner of the screen.

Return Value

If an application processes this message, it should return zero.

Default Action

The DefWindowProc function tests the given point to find out the location of the cursor and performs the appropriate action. If appropriate, DefWindowProc sends the WM_SYSCOMMAND message to the window.

Remarks

An application can use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

If it is appropriate to do so, the system sends the WM_SYSCOMMAND message to the window.

See Also

DefWindowProc, MAKEPOINTS, POINTS, WM_NCHITTEST, WM_NCLBUTTONDBLCLK, WM_NCLBUTTONDOWN, WM_SYSCOMMAND


WM_NCMBUTTONDBLCLK
 WM_NCMBUTTONDBLCLK  QuickInfo  Overview  Group

WM_NCMBUTTONDBLCLK

nHittest = (INT) wParam;    // hit-test value

pts = MAKEPOINTS(lParam);   // position of cursor

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.

Parameters

nHittest

Value of wParam. Specifies the hit-test value returned by the DefWindowProc function as a result of processing the WM_NCHITTEST message. For a list of hit-test values, see WM_NCHITTEST.

pts

Value of lParam. Specifies a POINTS structure that contains the x- and y-coordinates of the cursor. The coordinates are relative to the upper-left corner of the screen.

Return Value

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.

Windows generates a WM_NCMBUTTONDBLCLK message when the user presses, releases, and again presses the middle mouse button within the system's double-click time limit. Double-clicking the middle mouse button actually generates four messages: WM_NCMBUTTONDOWN, WM_NCMBUTTONUP, WM_NCMBUTTONDBLCLK, and WM_NCMBUTTONUP again.

An application can use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

If it is appropriate to do so, the system sends the WM_SYSCOMMAND message to the window.

See Also

DefWindowProc, MAKEPOINTS, POINTS, WM_NCHITTEST, WM_NCMBUTTONDOWN, WM_NCMBUTTONUP, WM_SYSCOMMAND


WM_NCMBUTTONDOWN
 WM_NCMBUTTONDOWN  QuickInfo  Overview  Group

WM_NCMBUTTONDOWN

nHittest = (INT) wParam;    // hit-test value

pts = MAKEPOINTS(lParam);   // position of cursor

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.

Parameters

nHittest

Value of wParam. Specifies the hit-test value returned by the DefWindowProc function as a result of processing the WM_NCHITTEST message. For a list of hit-test values, see WM_NCHITTEST.

pts

Value of lParam. Specifies a POINTS structure that contains the x- and y-coordinates of the cursor. The coordinates are relative to the upper-left corner of the screen.

Return Value

If an application processes this message, it should return zero.

Remarks

An application can use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

If it is appropriate to do so, the system sends the WM_SYSCOMMAND message to the window.

See Also

DefWindowProc, MAKEPOINTS, POINTS, WM_NCHITTEST, WM_NCMBUTTONDBLCLK, WM_NCMBUTTONUP, WM_SYSCOMMAND


WM_NCMBUTTONUP
 WM_NCMBUTTONUP  QuickInfo  Overview  Group

WM_NCMBUTTONUP

nHittest = (INT) wParam;    // hit-test value

pts = MAKEPOINTS(lParam);   // position of cursor

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.

Parameters

nHittest

Value of wParam. Specifies the hit-test value returned by the DefWindowProc function as a result of processing the WM_NCHITTEST message. For a list of hit-test values, see WM_NCHITTEST.

pts

Value of lParam. Specifies a POINTS structure that contains the x- and y-coordinates of the cursor. The coordinates are relative to the upper-left corner of the screen.

Return Value

If an application processes this message, it should return zero.

Remarks

An application can use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

If it is appropriate to do so, the system sends the WM_SYSCOMMAND message to the window.

See Also

DefWindowProc, MAKEPOINTS, POINTS, WM_NCHITTEST, WM_NCMBUTTONDBLCLK, WM_NCMBUTTONDOWN, WM_SYSCOMMAND


WM_NCMOUSEMOVE
 WM_NCMOUSEMOVE  QuickInfo  Overview  Group

WM_NCMOUSEMOVE

nHittest = (INT) wParam;    // hit-test value

pts = MAKEPOINTS(lParam);   // position of cursor

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.

Parameters

nHittest

Value of wParam. Specifies the hit-test value returned by the DefWindowProc function as a result of processing the WM_NCHITTEST message. For a list of hit-test values, see WM_NCHITTEST.

pts

Value of lParam. Specifies a POINTS structure that contains the x- and y-coordinates of the cursor. The coordinates are relative to the upper-left corner of the screen.

Return Value

If an application processes this message, it should return zero.

Remarks

If it is appropriate to do so, the system sends the WM_SYSCOMMAND message to the window.

An application can use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

See Also

DefWindowProc, MAKEPOINTS, POINTS, WM_NCHITTEST, WM_SYSCOMMAND


WM_NCPAINT
 WM_NCPAINT  QuickInfo  Overview  Group

WM_NCPAINT

hrgn = (HRGN) wParam;   // handle of update region

An application sends the WM_NCPAINT message to a window when its frame must be painted.

Parameters

hrgn

Value of wParam. Identifies the update region of the window. The update region is clipped to the window frame.

Return Value

An application should return zero if it processes this message.

Remarks

The DefWindowProc function paints the window frame.

An application can intercept this message and paint its own custom window frame. The clipping region for a window is always rectangular, even if the shape of the frame is altered.

See Also

DefWindowProc, GetWindowDC, WM_PAINT


WM_NCRBUTTONDBLCLK
 WM_NCRBUTTONDBLCLK  QuickInfo  Overview  Group

WM_NCRBUTTONDBLCLK

nHittest = (INT) wParam;    // hit-test value

pts = MAKEPOINTS(lParam);   // position of cursor

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.

Parameters

nHittest

Value of wParam. Specifies the hit-test value returned by the DefWindowProc function as a result of processing the WM_NCHITTEST message. For a list of hit-test values, see WM_NCHITTEST.

pts

Value of lParam. Specifies a POINTS structure that contains the x- and y-coordinates of the cursor. The coordinates are relative to the upper-left corner of the screen.

Return Value

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.

Windows generates a WM_NCRBUTTONDBLCLK message when the user presses, releases, and again presses the right mouse button within the system's double-click time limit. Double-clicking the right mouse button actually generates four messages: WM_NCRBUTTONDOWN, WM_NCRBUTTONUP, WM_NCRBUTTONDBLCLK, and WM_NCRBUTTONUP again.

An application can use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

If it is appropriate to do so, the system sends the WM_SYSCOMMAND message to the window.

See Also

DefWindowProc, MAKEPOINTS, POINTS, WM_NCHITTEST, WM_NCRBUTTONDOWN, WM_NCRBUTTONUP, WM_SYSCOMMAND


WM_NCRBUTTONDOWN
 WM_NCRBUTTONDOWN  QuickInfo  Overview  Group

WM_NCRBUTTONDOWN

nHittest = (INT) wParam;    // hit-test value

pts = MAKEPOINTS(lParam);   // position of cursor

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.

Parameters

nHittest

Value of wParam. Specifies the hit-test value returned by the DefWindowProc function as a result of processing the WM_NCHITTEST message. For a list of hit-test values, see WM_NCHITTEST.

pts

Value of lParam. Specifies a POINTS structure that contains the x- and y-coordinates of the cursor. The coordinates are relative to the upper-left corner of the screen.

Return Value

If an application processes this message, it should return zero.

Remarks

An application can use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

If it is appropriate to do so, the system sends the WM_SYSCOMMAND message to the window.

See Also

DefWindowProc, MAKEPOINTS, POINTS, WM_NCHITTEST, WM_NCRBUTTONDBLCLK, WM_NCRBUTTONUP, WM_SYSCOMMAND


WM_NCRBUTTONUP
 WM_NCRBUTTONUP  QuickInfo  Overview  Group

WM_NCRBUTTONUP

nHittest = (INT) wParam;    // hit-test value

pts = MAKEPOINTS(lParam);   // position of cursor

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.

Parameters

nHittest

Value of wParam. Specifies the hit-test value returned by the DefWindowProc function as a result of processing the WM_NCHITTEST message. For a list of hit-test values, see WM_NCHITTEST.

pts

Value of lParam. Specifies a POINTS structure that contains the x- and y-coordinates of the cursor. The coordinates are relative to the upper-left corner of the screen.

Return Value

If an application processes this message, it should return zero.

Remarks

An application can use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

If it is appropriate to do so, the system sends the WM_SYSCOMMAND message to the window.

See Also

DefWindowProc, MAKEPOINTS, POINTS, WM_NCHITTEST, WM_NCRBUTTONDBLCLK, WM_NCRBUTTONDOWN, WM_SYSCOMMAND


WM_NEXTDLGCTL
 WM_NEXTDLGCTL  QuickInfo  Overview  Group

WM_NEXTDLGCTL

wCtlFocus = wParam;              // identifies control for focus

fHandle = (BOOL) LOWORD(lParam); // wParam handle flag

The WM_NEXTDLGCTL message is sent to a dialog box procedure to set the keyboard focus to a different control in the dialog box.

Parameters

wCtlFocus

Value of wParam. If the fHandle parameter is TRUE, the wCtlFocus parameter identifies the control that receives the focus. If fHandle is FALSE, wCtlFocus is a flag that indicates whether the next or previous control with the WS_TABSTOP style receives the focus. If wCtlFocus is zero, the next control receives the focus; otherwise, the previous control with the WS_TABSTOP style receives the focus.

fHandle

Value of lParam. Contains a flag that indicates how Windows uses the wCtlFocus parameter. If the fHandle parameter is TRUE, wCtlFocus is a handle associated with the control that receives the focus; otherwise, wCtlFocus is a flag that indicates whether the next or previous control with the WS_TABSTOP style receives the focus.

Return Value

An application should return zero if it processes this message.

Remarks

The effect of this message differs from that of the SetFocus function because WM_NEXTDLGCTL modifies the border around the control.

Do not use the SendMessage function to send a WM_NEXTDLGCTL message if your application will concurrently process other messages that set the focus. Use the PostMessage function instead.

See Also

PostMessage, SendMessage, SetFocus


WM_NOTIFY [New - Windows NT]
 WM_NOTIFY  QuickInfo  Overview  Group

[New - Windows NT]

WM_NOTIFY

idCtrl = (int) wParam;

pnmh = (LPNMHDR) lParam;

The WM_NOTIFY message informs the parent window of a control that an event has occurred in the control or that the control requires some kind of information.

Parameters

idCtrl

Identifier of the control sending the message. This identifier is not guaranteed to be unique. An application should use the hwindFrom or idFrom member of the NMHDR structure (passed as the lParam parameter) to identify the control.

pnmh

Pointer to an NMHDR structure that contains the notification code and additional information. For some notification messages, this parameter points to a larger structure that has the NMHDR structure as its first member.

Return Value

The return value is ignored except for notification messages that specify otherwise.

See Also

NMHDR


WM_NOTIFYFORMAT  (preliminary-WindowsNT) [New - Windows NT]
 WM_NOTIFYFORMAT  QuickInfo

[New - Windows NT]

hwndFrom = (HWND) wParam;        // handle of the window sending this message

Command =  lParam;               // command value specifying the nature of this message

Common controls, custom controls, and their parent windows use the WM_NOTIFYFORMAT message to determine whether the control should use ANSI or Unicode structures in the WM_NOTIFY notification messages that the control uses to communicate with its parent window. WM_NOTIFYFORMAT messages are sent from a control to its parent window, and from the parent window to the control.

Parameters

hwndFrom

Value of wParam. Handle of the window that is sending the WM_NOTIFYFORMAT message. If Command is NF_QUERY, hwndFrom is the handle of a control. If Command is NF_REQUERY, this is the handle of the parent window of a control.

Command

Value of lParam. A command value that specifies the nature of the WM_NOTIFYFORMAT message. The following values are defined:

Value	Meaning
NF_QUERY	The message is a query to determine whether ANSI or Unicode structures should be used in WM_NOTIFY messages. This command is sent from a control to its parent window. This command is sent during the creation of a control, and in response to an NF_REQUERY command.
NF_REQUERY	The message is a request that a control send an NF_QUERY form of this message to its parent window. This command is sent from a control's parent window to the control. The parent window is asking the control to requery it about the type of structures to use in WM_NOTIFY messages.
Return Value

The return value is one of the following :

Value	Meaning
NFR_ANSI	ANSI structures should be used in WM_NOTIFY messages sent by the control.
NFR_UNICODE	Unicode structures should be used in WM_NOTIFY messages sent by the control.
0	An error occurred.
If Command is NF_REQUERY, the return value is the result of the requery operation.

Remarks

When a common control is created, the control sends a WM_NOTIFYFORMAT message to its parent window to determine the type of structures to use in WM_NOTIFY messages. If the parent window does not handle this message, the DefWindowProc function responds according to the type of the parent window. That is, if the parent window is a Unicode window, DefWindowProc returns NFR_UNICODE, and if the parent window is an ANSI window, DefWindowProc returns NFR_ANSI. If the parent window is a dialog box and does not handle this message, the DefDlgProc function similarly responds according to the type of the dialog box (Unicode or ANSI).

A parent window can change the type of structures a common control uses in WM_NOTIFY messages by setting lParam to NF_REQUERY and sending a WM_NOTIFYFORMAT message to the control. This causes the control to send an NF_QUERY form of the WM_NOTIFYFORMAT message to the parent window.

See Also

DefDlgProc, DefWindowProc, WM_NOTIFY


WM_PAINT
 WM_PAINT  QuickInfo  Overview  Group

WM_PAINT

An application sends the WM_PAINT message when Windows or another application makes a request to paint a portion of an application's window. The message is sent when the UpdateWindow or RedrawWindow function is called, or by the DispatchMessage function when the application obtains a WM_PAINT message by using the GetMessage or PeekMessage function.

Parameters

This message has no parameters.

Return Value

An application should return zero if it processes this message.

Remarks

The DefWindowProc function validates the update region. The function may also send the WM_NCPAINT message to the window procedure if the window frame must be painted and send the WM_ERASEBKGND message if the window background must be erased.

The system sends this message when there are no other messages in the application's message queue. DispatchMessage determines where to send the message; GetMessage determines which message to dispatch. GetMessage returns the WM_PAINT message when there are no other messages in the application's message queue, and DispatchMessage sends the message to the appropriate window procedure.

A window may receive internal paint messages as a result of calling RedrawWindow with the RDW_INTERNALPAINT flag set. In this case, the window may not have an update region. An application should call the GetUpdateRect function to determine whether the window has an update region. If GetUpdateRect returns zero, the application should not call the BeginPaint and EndPaint functions.

An application must check for any necessary internal painting by looking at its internal data structures for each WM_PAINT message, because a WM_PAINT message may have been caused by both a non-NULL update region and a call to RedrawWindow with the RDW_INTERNALPAINT flag set.

Windows sends an internal WM_PAINT message only once. After an internal WM_PAINT message is returned from GetMessage or PeekMessage or is sent to a window by UpdateWindow, Windows does not post or send further WM_PAINT messages until the window is invalidated or until RedrawWindow is called again with the RDW_INTERNALPAINT flag set.

See Also

BeginPaint, DefWindowProc, DispatchMessage, EndPaint, GetMessage, GetUpdateRect, PeekMessage, RedrawWindow, UpdateWindow, WM_ERASEBKGND, WM_NCPAINT


WM_PAINTCLIPBOARD
 WM_PAINTCLIPBOARD  QuickInfo  Overview  Group

WM_PAINTCLIPBOARD

hwndViewer = (HWND) wParam;     // handle of clipboard viewer window

hglbPs = (HGLOBAL) lParam;      // handle of PAINTSTRUCT object

The WM_PAINTCLIPBOARD message is sent to the clipboard owner by a clipboard viewer window when the clipboard contains data in the CF_OWNERDISPLAY format and the clipboard viewer's client area needs repainting.

Parameters

hwndViewer

Value of wParam. Identifies the clipboard viewer window.

hglbPs

Value of lParam. Identifies a global DDESHARE object that contains a PAINTSTRUCT structure. The structure defines the part of the client area to paint.

Return Value

If an application processes this message, it should return zero.

Remarks

To determine whether the entire client area or just a portion of it needs repainting, the clipboard owner must compare the dimensions of the drawing area given in the rcpaint member of PAINTSTRUCT to the dimensions given in the most recent WM_SIZECLIPBOARD message.

The clipboard owner must use the GlobalLock function to lock the memory that contains the PAINTSTRUCT structure. Before returning, the clipboard owner must unlock that memory by using the GlobalUnlock function.

See Also

GlobalLock, GlobalUnlock, PAINTSTRUCT, WM_SIZECLIPBOARD


WM_PAINTICON
 WM_PAINTICON  QuickInfo  Overview  Group

WM_PAINTICON

The WM_PAINTICON message is sent to a minimized window when the icon is to be painted but only if the application is written for Windows 3.x. A window receives this message only if a class icon is defined for the window; otherwise, WM_PAINT is sent instead.

Parameters

This message has no parameters.

Return Value

An application should return zero if it processes this message.

Remarks

The DefWindowProc function draws the class icon. For compatibility with Windows 3.x, wParam is TRUE. However, this value has no significance.

See Also

DefWindowProc, WM_ICONERASEBKGND, WM_PAINT


WM_PALETTECHANGED
 WM_PALETTECHANGED  QuickInfo  Overview  Group

WM_PALETTECHANGED

hwndPalChg = (HWND) wParam; // handle of window that changed palette

The WM_PALETTECHANGED message is sent to all top-level and overlapped windows after the window with the keyboard focus has realized its logical palette, thereby changing the system palette. This message enables a window that uses a color palette but does not have the keyboard focus to realize its logical palette and update its client area.

Parameters

hwndPalChg

Value of wParam. Identifies the window that caused the system palette to change.

Remarks

This message must be sent to all top-level and overlapped windows, including the one that changed the system palette. If any child windows use a color palette, this message must be passed on to them as well.

To avoid creating an infinite loop, a window that receives this message must not realize its palette, unless it determines that wParam does not contain its own window handle.

See Also

WM_PALETTEISCHANGING, WM_QUERYNEWPALETTE


WM_PALETTEISCHANGING
 WM_PALETTEISCHANGING  QuickInfo  Overview  Group

WM_PALETTEISCHANGING

hwndRealize = (HWND) wParam; // window to realize palette

The WM_PALETTEISCHANGING message informs applications that an application is going to realize its logical palette.

Parameters

hwndRealize

Value of wParam. Identifies the window that is going to realize its logical palette.

Return Value

If an application processes this message, it should return zero.

Remarks

The application changing its palette does not wait for acknowledgment of this message before changing the palette and sending the WM_PALETTECHANGED message. As a result, the palette may already be changed by the time an application receives this message.

If the application either ignores or fails to process this message and a second application realizes its palette while the first is using palette indices, there is a strong possibility that the user will see unexpected colors during subsequent drawing operations.

See Also

WM_PALETTECHANGED, WM_QUERYNEWPALETTE


WM_PARENTNOTIFY
 WM_PARENTNOTIFY  QuickInfo  Overview  Group

WM_PARENTNOTIFY

fwEvent = LOWORD(wParam);  // event flags

idChild = HIWORD(wParam);  // identifier of child window

lValue = lParam;           // child handle, or cursor coordinates

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, Windows sends the message before any processing to destroy the window takes place.

Parameters

fwEvent

Value of the low-order word of wParam. Specifies the event for which the parent is being notified. This parameter can be one of the following values:

Value	Meaning
WM_CREATE	The child window is being created.
WM_DESTROY	The child window is being destroyed.
WM_LBUTTONDOWN	The user has placed the cursor over the child window and has clicked the left mouse button.
WM_MBUTTONDOWN	The user has placed the cursor over the child window and has clicked the middle mouse button.
WM_RBUTTONDOWN	The user has placed the cursor over the child window and has clicked the right mouse button.
idChild

Value of the high-order word of wParam. If the fwEvent parameter is the WM_CREATE or WM_DESTROY value, idChild specifies the identifier of the child window. Otherwise, idChild is undefined.

lValue

Contains the handle of the child window, if the fwEvent parameter is the WM_CREATE or WM_DESTROY value; otherwise, lValue contains the x- and y-coordinates of the cursor. The x-coordinate is in the low-order word and the y-coordinate is in the high-order word.

Return Value

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.

See Also

CreateWindow, CreateWindowEx, WM_CREATE, WM_DESTROY, WM_LBUTTONDOWN, WM_MBUTTONDOWN, WM_RBUTTONDOWN


WM_PASTE
 WM_PASTE  QuickInfo  Overview  Group

WM_PASTE

wParam = 0; // not used; must be zero

lParam = 0; // not used; must be zero

An application sends a WM_PASTE message to an edit control or combo box to copy the current content of the clipboard to the edit control at the current caret position. Data is inserted only if the clipboard contains data in CF_TEXT format.

Parameters

This message has no parameters.

Return Value

This message does not return a value.

Remarks

When sent to a combo box, the WM_PASTE message is handled by its edit control. This message has no effect when sent to a combo box with the CBS_DROPDOWNLIST style.

See Also

WM_CLEAR, WM_COPY, WM_CUT


WM_POWER
 WM_POWER  QuickInfo  Overview  Group

WM_POWER

fwPowerEvt = wParam;    // power-event notification message

The WM_POWER message is sent when the system, typically a battery-powered personal computer, is about to enter suspended mode.

Windows 95: For Windows 95 applications, The WM_POWER message is not supported. It is provided to simplify porting of 16-bit Windows-based applications. Win32-based applications for Windows 95 should use the WM_POWERBROADCAST message.

Parameters

fwPowerEvt

Value of wParam. Specifies a power-event notification message. This parameter can be one of the following values:

Value	Meaning
PWR_CRITICALRESUME	Indicates that the system is resuming operation after entering suspended mode without first sending a PWR_SUSPENDREQUEST notification message to the application. An application should perform any necessary recovery actions.
PWR_SUSPENDREQUEST	Indicates that the system is about to enter suspended mode.
PWR_SUSPENDRESUME	Indicates that the system is resuming operation after having entered suspended mode normally — that is, the system sent a PWR_SUSPENDREQUEST notification message to the application before the system was suspended. An application should perform any necessary recovery actions.
Return Value

The value an application returns depends on the value of the wParam parameter. If wParam is PWR_SUSPENDREQUEST, the return value is PWR_FAIL to prevent the system from entering the suspended state; otherwise, it is PWR_OK. If wParam is PWR_SUSPENDRESUME or PWR_CRITICALRESUME, the return value is zero.

Remarks

This message is sent only to an application that is running on a system that conforms to the Advanced Power Management (APM) basic input/output system (BIOS) specification. The message is sent by the power-management driver to each window returned by the EnumWindows function.

The suspended mode is the state in which the greatest amount of power savings occurs, but all operational data and parameters are preserved. Random-access memory (RAM) contents are preserved, but many devices are likely to be turned off.

See Also

EnumWindows, WM_POWERBROADCAST


WM_POWERBROADCAST [New - Windows 95]
 WM_POWERBROADCAST  QuickInfo  Overview  Group

[New - Windows 95]

dwPowerEvent = (DWORD) wParam;
dwData = (DWORD) lParam;

The WM_POWERBROADCAST message is sent to an application to notify it of power-management events.

Windows NT: For Windows NT applications, use WM_POWER.

Parameters

dwPowerEvent

Event notification message. This parameter can be one of the following values:

Value	Meaning
PBT_APMBATTERYLOW	Battery power is low.
PBT_APMOEMEVENT	OEM-defined event occurred.
PBT_APMPOWERSTATUSCHANGED	Power status has changed.
PBT_APMQUERYSTANDBY	Request for permission to standby.
PBT_APMQUERYSTANDBYFAILED	Standby request denied.
PBT_APMQUERYSUSPEND	Request for permission to suspend.
PBT_APMQUERYSUSPENDFAILED	Suspension request denied.
PBT_APMRESUMECRITICAL	Operation resuming after critical suspension.
PBT_APMRESUMESTANDBY	Operation resuming after standby.
PBT_APMRESUMESUSPEND	Operation resuming after suspension.
PBT_APMSTANDBY	System is changing to standby.
PBT_APMSUSPEND	System is suspending operation.
dwData

Function-specific data. For most messages, this parameter is reserved and not used.

However, if wParam is one of the resume notifications (PBT_APMRESUME*), the lParam parameter can specify the PBTF_APMRESUMEFROMFAILURE flag. This flag indicates that a suspend or standby operation failed after the PBT_APMSUSPEND or PBT_APMSTANDBY message was sent.

Return Value

Returns TRUE if successful or FALSE otherwise.


WM_PRINT [New - Windows 95]
 WM_PRINT  QuickInfo  Overview  Group

[New - Windows 95]

WM_PRINT

hdc = (HDC) wParam;

uFlags = lParam;

The WM_PRINT message is sent to a window to request that it draw itself in the specified device context, most commonly in a printer device context.

Parameters

hdc

Identifies the device context to draw in.

uFlags

Specifies the drawing options. This parameter can be one or more of these flags:

Value	Meaning
PRF_CHECKVISIBLE	Draw the window only if it is visible.
PRF_CHILDREN	Draw all visible children windows.
PRF_CLIENT	Draw the client area of the window.
PRF_ERASEBKGND	Erase the background before drawing the window.
PRF_NONCLIENT	Draw the nonclient area of the window.
PRF_OWNED	Draw all owned windows.
Remarks

The DefWindowProc function processes this message based on which drawing option is specified: if PRF_CHECKVISIBLE is specified and the window is not visible, do nothing, if PRF_NONCLIENT is specified, draw the nonclient area in the given device context, if PRF_ERASEBKGND is specified, send the window a WM_ERASEBKGND message, if PRF_PRINTCLIENT is specified, send the window a WM_PRINTCLIENT message, if PRF_PRINTCHILDREN is set, send each visible child window a WM_PRINT message, if PRF_OWNED is set, send each visible owned window a WM_PRINT message.

See Also

DefWindowProc, WM_ERASEBKGND, WM_PRINTCLIENT


WM_PRINTCLIENT
 WM_PRINTCLIENT  QuickInfo  Overview  Group

WM_PRINTCLIENT

hdc = (HDC) wParam;

uFlags = lParam;

The WM_PRINTCLIENT message is sent to a window to request that it draw its client area in the specified device context, most commonly in a printer device context.

Parameters

hdc

Identifies the device context to draw in.

uFlags

Specifies drawing options. This parameter can be one or more of these flags:

Value	Meaning
PRF_CHECKVISIBLE	Draw the window only if it is visible.
PRF_CHILDREN	Draw all visible children windows.
PRF_CLIENT	Draw the client area of the window.
PRF_ERASEBKGND	Erase the background before drawing the window.
PRF_NONCLIENT	Draw the nonclient area of the window.
PRF_OWNED	Draw all owned windows.
Remarks

A window can process this message in much the same manner as WM_PAINT, except that BeginPaint and EndPaint need not be called (a device context is provided), and the window should draw its entire client area rather than just the invalid region.

Windows that can be used anywhere in the system, such as controls, should process this message. It is probably worthwhile for other windows to process this message as well because it is relatively easy to implement.

See Also

BeginPaint, EndPaint, WM_PAINT


WM_PSD_ENVSTAMPRECT
 WM_PSD_ENVSTAMPRECT  Overview  Group

WM_PSD_ENVSTAMPRECT

hDC = (WPARAM) (HDC) wParam;             // handle of device context

lprcEnvStamp = (LPARAM) (LPRECT) lParam; // envelope-stamp rectangle

Informs a hook function of the coordinates of the envelope-stamp rectangle in the sample page of the Page Setup dialog box. Before drawing in the envelope-stamp rectangle, the system passes this message to the hook function specified in the lpfnPagePaintHook member of the PAGESETUPDLG structure used to create the dialog box.

Parameters

hDC

Value of wParam. Identifies the device context for the sample page.

lprcMargin

Value of lParam. Points to a RECT structure that contains the coordinates, in pixels, of the envelope-stamp rectangle.

Return Value

A hook procedure should return TRUE to prevent the system from drawing the envelope-stamp rectangle; otherwise, it should return FALSE.

Remarks

A hook procedure receives this message only if the selected paper type is an envelope.

See Also

PAGESETUPDLG, RECT


WM_PSD_FULLPAGERECT
 WM_PSD_FULLPAGERECT  Overview  Group

WM_PSD_FULLPAGERECT

hDC = (WPARAM) (HDC) wParam;         // handle of device context

lprcPage = (LPARAM) (LPRECT) lParam; // dimensions of page rectangle

Informs a hook function of the coordinates of the sample page rectangle in the Page Setup dialog box. Before drawing in the sample page rectangle, the system sends this message to the hook function specified in the lpfnPagePaintHook member of the PAGESETUPDLG structure used to create the dialog box.

Parameters

hDC

Value of wParam. Handle of the device context for the sample page.

lprcPage

Value of lParam. Points to a RECT structure that contains the coordinates, in pixels, of the sample page.

Return Value

A hook procedure should return TRUE to prevent the system from drawing in the sample page rectangle; otherwise, it should return FALSE. If it returns TRUE, the hook procedure receives no more messages until the next time the system needs to redraw the sample page.

See Also

PAGESETUPDLG, RECT


WM_PSD_GREEKTEXTRECT
 WM_PSD_GREEKTEXTRECT  Overview  Group

WM_PSD_GREEKTEXTRECT

hDC = (WPARAM) (HDC) wParam;              // handle of device context

lprcGreekText = (LPARAM) (LPRECT) lParam; // greek text rectangle

Informs a hook function of the coordinates of the greek-text rectangle in the sample page of the Page Setup dialog box. The system fills the greek-text rectangle with random characters to demonstrate how text is be formatted on a printed page. Before drawing the greek text, the system passes this message to the hook function specified in the lpfnPagePaintHook member of the PAGESETUPDLG structure used to create the dialog box.

Parameters

hDC

Value of wParam. Identifies the device context for the sample page.

lprcMargin

Value of lParam. Points to a RECT structure that contains the coordinates, in pixels, of the greek-text rectangle.

Return Value

A hook function should return TRUE to prevent the system from drawing in the greek-text rectangle; otherwise, it should return FALSE.

See Also

PAGESETUPDLG, RECT


WM_PSD_MARGINRECT
 WM_PSD_MARGINRECT  Overview  Group

WM_PSD_MARGINRECT

hDC = (WPARAM) (HDC) wParam;           // handle of device context

lprcMargin = (LPARAM) (LPRECT) lParam; // margin rectangle

Informs a hook function of the coordinates of the margin rectangle in the sample page of the Page Setup dialog box. Before drawing the margin rectangle, the system passes this message to the hook function specified in the lpfnPagePaintHook member of the PAGESETUPDLG structure used to create the dialog box.

Parameters

hDC

Value of wParam. Identifies the device context for the sample page.

lprcMargin

Value of lParam. Points to a RECT structure that contains the coordinates, in pixels, of the margin rectangle.

Return Value

A hook function should return TRUE to prevent the system from drawing the margin rectangle; otherwise, is should return FALSE.

See Also

PAGESETUPDLG, RECT


WM_PSD_MINMARGINRECT
 WM_PSD_MINMARGINRECT  Overview  Group

WM_PSD_MINMARGINRECT

hDC = (WPARAM) (HDC) wParam;              // handle of device context

lprcMinMargin = (LPARAM) (LPRECT) lParam; // minimum margin rectangle

Informs a hook function of the coordinates of the minimum margin rectangle of the sample page in the Page Setup dialog box. The system passes this message to the hook function specified in the lpfnPagePaintHook member of the PAGESETUPDLG structure used to create the dialog box.

Parameters

hDC

Value of wParam. Identifies the device context for the sample page.

lprcMinMargin

Value of lParam. Points to a RECT structure that contains the coordinates, in pixels, of the minimum margin rectangle.

Return Value

A hook function should return TRUE to prevent the system from any further drawing in the sample page rectangle; otherwise, it should return FALSE. If it returns TRUE, the hook function receives no more messages until the next time the system needs to redraw the sample page.

See Also

PAGESETUPDLG, RECT


WM_PSD_PAGESETUPDLG
 WM_PSD_PAGESETUPDLG  Overview  Group

WM_PSD_PAGESETUPDLG

wPaper = LOWORD(wParam);         // paper-size flag

wFlags = HIWORD(wParam);         // paper-orientation flag

lppsd = (LPPAGESETUPDLG) lParam; // dialog box information

Sent when the system is about to draw the contents of the sample page in the Page Setup dialog box. The system sends this message to the hook function specified in the lpfnPagePaintHook member of the PAGESETUPDLG structure used to create the dialog box. The hook function can use this message to carry out initialization tasks related to drawing the contents of the sample page.

Parameters

wPaper

Value of the low-order word of wParam. Specifies a value that indicates the paper size. This value can be one of the DMPAPER_ values listed in the description of the DEVMODE structure.

wFlags

Value of the high-order word of wParam. Indicates the orientation of the paper or envelope, and whether the printer is a dot matrix or HPPCL (Hewlett Packard Printer Control Language) device. This parameter can be one of the following values:

0x0001	Paper in landscape mode (dot matrix)
0x0003	Paper in landscape mode (HPPCL)
0x0005	Paper in portrait mode (dot matrix)
0x0007	Paper in portrait mode (HPPCL)
0x000b	Envelope in landscape mode (HPPCL)
0x000d	Envelope in portrait mode (dot matrix)
0x0019	Envelope in landscape mode (dot matrix)
0x001f	Envelope in portrait mode (HPPCL)
lppsd

Value of lParam. Points to a PAGESETUPDLG structure that contains information used to initialize the Page Setup dialog box.

Return Value

A hook function should return TRUE to prevent the system from drawing in the sample page rectangle; otherwise, it should return FALSE. If it returns TRUE, the hook function receives no more messages until the next time the system needs to redraw the sample page.

See Also

DEVMODE, PAGESETUPDLG


WM_PSD_YAFULLPAGERECT
 WM_PSD_YAFULLPAGERECT  Overview  Group

WM_PSD_YAFULLPAGERECT

hDC = (WPARAM) (HDC) wParam;               // handle of device context

lprcYaFullPage = (LPARAM) (LPRECT) lParam; // dimensions of page rectangle

Informs a hook function of the coordinates of the sample page rectangle in the Page Setup dialog box. The system sends this message to the hook function specified in the lpfnPagePaintHook member of the PAGESETUPDLG structure used to create the dialog box.

Parameters

hDC

Value of wParam. Handle of the device context for the sample page.

lprcPage

Value of lParam. Points to a RECT structure that contains the coordinates, in pixels, of the sample page.

Return Value

A hook function should return TRUE to prevent the system from drawing in the return address rectangle of the sample page. It should return FALSE to allow the system to draw in the return address rectangle. If the paper type is not an envelope, the return value has no effect.

See Also

PAGESETUPDLG, RECT


WM_QUERYDRAGICON
 WM_QUERYDRAGICON  QuickInfo

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 the handle of an icon or cursor. The system displays this cursor or icon while the user drags the icon.

Parameters

This message has no parameters.

Return Value

An application should return the handle of a cursor or icon that Windows is to display while the user drags the icon. The cursor or icon must be compatible with the display driver's resolution. If the application returns NULL, the system displays the default cursor.

Default Action

The DefWindowProc function returns the handle of the default cursor.

Remarks

When the user drags the icon of a window without a class icon, Windows replaces the icon with a default cursor. If the application requires a different cursor to be displayed during dragging, it must return the handle of the cursor or icon compatible with the display driver's resolution. If an application returns the handle of 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.

See Also

DefWindowProc, LoadCursor, LoadIcon


WM_QUERYENDSESSION
 WM_QUERYENDSESSION  QuickInfo  Overview  Group

Windows 95:

WM_QUERYENDSESSION

nSource = (UINT) wParam;    // source of end-session request

fLogOff = (BOOL) lParam    // logoff flag

Windows NT:

WM_QUERYENDSESSION

nSource = (UINT) wParam;    // source of end-session request

The WM_QUERYENDSESSION message is sent when the user chooses to end the Windows session or when an application calls the ExitWindows function. If any application returns zero, the Windows session is not ended. Windows stops sending WM_QUERYENDSESSION messages as soon as one application returns zero.

After processing this message, Windows sends the WM_ENDSESSION message with the wParam parameter set to the results of the WM_QUERYENDSESSION message.

Parameters

nSource

Value of wParam. Specifies the source of the request to end the Windows session. This parameter is zero if the request occurred because the user clicked the Logoff or Shutdown button in the Shut Down Windows dialog box. This parameter is nonzero if the user clicked the End Task button in the Task List dialog box.

fLogOff

Windows 95 only: Value of lParam. Indicates whether the user is logging off or shutting down the system. This parameter is TRUE if the user is logging off; it is FALSE if the user is shutting down the system.

Return Value

If an application can terminate conveniently, it should return TRUE; otherwise, it should return FALSE.

Default Action

The DefWindowProc function returns TRUE.

Remarks

Note that lParam is not used on the Windows NT platform, but is used on the Windows 95 platform.

See Also

DefWindowProc, ExitWindows, WM_ENDSESSION


WM_QUERYNEWPALETTE
 WM_QUERYNEWPALETTE  QuickInfo  Overview  Group

WM_QUERYNEWPALETTE

The WM_QUERYNEWPALETTE message informs a window that it is about to receive the keyboard focus, giving the window the opportunity to realize its logical palette when it receives the focus.

Parameters

This message has no parameters.

Return Value

If the window realizes its logical palette, it must return TRUE; otherwise, it must return FALSE.

See Also

WM_PALETTECHANGED, WM_PALETTEISCHANGING


WM_QUERYOPEN
 WM_QUERYOPEN  QuickInfo  Overview  Group

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.

Parameters

This message has no parameters.

Return Value

If the icon can be opened, an application that processes this message should return TRUE; otherwise, it should return FALSE to prevent the icon from being opened.

Default Action

The DefWindowProc function returns TRUE.

Remarks

While processing this message, the application should not perform any action that would cause an activation or focus change (for example, creating a dialog box).

See Also

DefWindowProc


WM_QUEUESYNC
 WM_QUEUESYNC  QuickInfo  Overview  Group

WM_QUEUESYNC

wParam = 0; // not used, must be zero

lParam = 0; // not used, must be zero

The WM_QUEUESYNC message is sent by a computer-based training (CBT) application to separate user-input messages from other messages sent through the WH_JOURNALPLAYBACK hook procedure.

Parameters

This message has no parameters.

Return Value

A CBT application should return zero if it processes this message.

Remarks

Whenever a CBT application uses the WH_JOURNALPLAYBACK hook procedure, the first and last messages are WM_QUEUESYNC. This allows the CBT application to intercept and examine user-initiated messages without doing so for events that it sends.

If an application specifies a NULL window handle, the message is posted to the message queue of the active window.


WM_QUIT
 WM_QUIT  QuickInfo  Overview  Group

WM_QUIT

nExitCode = (int) wParam;   // exit code

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.

Parameters

nExitCode

Value of wParam. Specifies the exit code given in the PostQuitMessage function.

Return Value

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.

See Also

GetMessage, PostQuitMessage


WM_RASDIALEVENT
 WM_RASDIALEVENT  QuickInfo  Overview  Group

WM_RASDIALEVENT

rasconnstate = (RASCONNSTATE) wParam; // connection state about to be entered

dwError = (DWORD) lParam;             // error that may have occurred

The operating system sends a WM_RASDIALEVENT message to a window procedure when a change of state event occurs during a Remote Access Service (RAS) connection process, and a window has been specified to handle notifications of such events by using the notifier parameter of RasDial.

The two message parameters are equivalent to the parameters of the same names that are used with RasDialFunc and RasDialFunc1 callback functions.

Parameters

rasconnstate

Value of wParam. Equivalent to the rasconnstate parameter of the RasDialFunc and RasDialFunc1 callback functions. Specifies a RASCONNSTATE enumerator value that indicates the state the RasDial remote access connection process is about to enter.

dwError

Value of lParam. Equivalent to the dwError parameter of the RasDialFunc and RasDialFunc1 callback functions. A nonzero value indicates the error that has occurred, or zero if no error has occurred.

RasDial sends this message with dwError set to zero upon entry to each connection state. If an error occurs within a state, the message is sent again for the state, this time with a nonzero dwError value.

Return Value

If an application processes this message, it should return TRUE.

See Also

RasDial, RasDialFunc, RasDialFunc1, RASCONNSTATE


WM_RBUTTONDBLCLK
 WM_RBUTTONDBLCLK  QuickInfo  Overview  Group

WM_RBUTTONDBLCLK

fwKeys = wParam;        // key flags

xPos = LOWORD(lParam);  // horizontal position of cursor

yPos = HIWORD(lParam);  // vertical position of cursor

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.

Parameters

fwKeys

Value of wParam. Indicates whether various virtual keys are down. This parameter can be any combination of the following values:

Value	Description
MK_CONTROL	Set if the CTRL key is down.
MK_LBUTTON	Set if the left mouse button is down.
MK_MBUTTON	Set if the middle mouse button is down.
MK_RBUTTON	Set if the right mouse button is down.
MK_SHIFT	Set if the SHIFT key is down.
xPos

Value of the low-order word of lParam. Specifies the x-coordinate of the cursor. The coordinate is relative to the upper left corner of the client area.

yPos

Value of the high-order word of lParam. Specifies the y-coordinate of the cursor. The coordinate is relative to the upper left corner of the client area.

Return Value

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 Windows generates whenever the user presses, releases, and again presses the right mouse button within the system's double-click time limit. Double-clicking the right mouse button actually generates four messages: WM_RBUTTONDOWN, WM_RBUTTONUP, WM_RBUTTONDBLCLK, and WM_RBUTTONUP again.

An application can use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

See Also

GetCapture, GetDoubleClickTime, MAKEPOINTS, POINTS, SetCapture, SetDoubleClickTime, WM_RBUTTONDOWN, WM_RBUTTONUP


WM_RBUTTONDOWN
 WM_RBUTTONDOWN  QuickInfo  Overview  Group

WM_RBUTTONDOWN

fwKeys = wParam;        // key flags

xPos = LOWORD(lParam);  // horizontal position of cursor

yPos = HIWORD(lParam);  // vertical position of cursor

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.

Parameters

fwKeys

Value of wParam. Indicates whether various virtual keys are down. This parameter can be any combination of the following values:

Value	Description
MK_CONTROL	Set if the CTRL key is down.
MK_LBUTTON	Set if the left mouse button is down.
MK_MBUTTON	Set if the middle mouse button is down.
MK_RBUTTON	Set if the right mouse button is down.
MK_SHIFT	Set if the SHIFT key is down.
xPos

Value of the low-order word of lParam. Specifies the x-coordinate of the cursor. The coordinate is relative to the upper left corner of the client area.

yPos

Value of the high-order word of lParam. Specifies the y-coordinate of the cursor. The coordinate is relative to the upper left corner of the client area.

Return Value

If an application processes this message, it should return zero.

Remarks

An application can use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

See Also

GetCapture, MAKEPOINTS, POINTS, SetCapture, WM_RBUTTONDBLCLK, WM_RBUTTONUP


WM_RBUTTONUP
 WM_RBUTTONUP  QuickInfo  Overview  Group

WM_RBUTTONUP

fwKeys = wParam;        // key flags

xPos = LOWORD(lParam);  // horizontal position of cursor

yPos = HIWORD(lParam);  // vertical position of cursor

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.

Parameters

fwKeys

Value of wParam. Indicates whether various virtual keys are down. This parameter can be any combination of the following values:

Value	Description
MK_CONTROL	Set if the CTRL key is down.
MK_LBUTTON	Set if the left mouse button is down.
MK_MBUTTON	Set if the middle mouse button is down.
MK_SHIFT	Set if the SHIFT key is down.
xPos

Value of the low-order word of lParam. Specifies the x-coordinate of the cursor. The coordinate is relative to the upper left corner of the client area.

yPos

Value of the high-order word of lParam. Specifies the y-coordinate of the cursor. The coordinate is relative to the upper left corner of the client area.

Return Value

If an application processes this message, it should return zero.

Remarks

An application can use the MAKEPOINTS macro to convert the lParam parameter to a POINTS structure.

See Also

GetCapture, MAKEPOINTS, POINTS, SetCapture, WM_RBUTTONDBLCLK, WM_RBUTTONDOWN


WM_RENDERALLFORMATS
 WM_RENDERALLFORMATS  QuickInfo  Overview  Group

WM_RENDERALLFORMATS

The WM_RENDERALLFORMATS message is sent to the clipboard owner before it is destroyed, if the clipboard owner has delayed rendering one or more clipboard formats. For the content of the clipboard to remain available to other applications, the clipboard owner must render data in all the formats it is capable of generating, and place the data on the clipboard by calling the SetClipboardData function.

Parameters

This message has no parameters.

Return Value

If an application processes this message, it should return zero.

Remarks

When responding to a WM_RENDERFORMAT or WM_RENDERALLFORMATS message, the clipboard owner must not open the clipboard before calling SetClipboardData.

When the application returns, the system removes any unrendered formats from the list of available clipboard formats. For information about delayed rendering, see SetClipboardData.

See Also

SetClipboardData, WM_RENDERFORMAT


WM_RENDERFORMAT
 WM_RENDERFORMAT  QuickInfo  Overview  Group

WM_RENDERFORMAT

uFormat = (UINT) wParam;    // clipboard format

The WM_RENDERFORMAT message is sent to the clipboard owner if it has delayed rendering a specific clipboard format and if an application has requested data in that format. The clipboard owner must render data in the specified format and place it on the clipboard by calling the SetClipboardData function.

Parameters

uFormat

Specifies the clipboard format to be rendered.

Return Value

If an application processes this message, it should return zero.

Remarks

When responding to a WM_RENDERFORMAT or WM_RENDERALLFORMATS message, the clipboard owner must not open the clipboard before calling SetClipboardData.

See Also

SetClipboardData, WM_RENDERALLFORMATS


WM_SETCURSOR
 WM_SETCURSOR  QuickInfo  Overview  Group

WM_SETCURSOR

hwnd = (HWND) wParam;       // handle of window with cursor

nHittest = LOWORD(lParam);  // hit-test code

wMouseMsg = HIWORD(lParam); // mouse-message identifier

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.

Parameters

hwnd

Value of wParam. Identifies the window that contains the cursor.

nHittest

Value of the low-order word of lParam. Specifies the hit-test code.

wMouseMsg

Value of the high-order word of lParam. Specifies the identifier of the mouse message.

Default Action

The DefWindowProc function passes the WM_SETCURSOR message to a parent window before processing. If the parent window returns TRUE, further processing is halted. Passing the message to a window's parent window gives the parent window control over the cursor's setting in a child window. The DefWindowProc function also uses this message to set the cursor to an arrow if it is not in the client area, or to the registered class cursor if it is in the client area. If the low-order word of the lParam parameter is HTERROR and the high-order word of lParam specifies that one of the mouse buttons is pressed, DefWindowProc calls the MessageBeep function.

Remarks

The high-order word of lParam is zero when the window enters menu mode.

See Also

DefWindowProc, MessageBeep


WM_SETFOCUS
 WM_SETFOCUS  QuickInfo  Overview  Group

WM_SETFOCUS

hwndLoseFocus = (HWND) wParam; // handle of window losing focus

The WM_SETFOCUS message is sent to a window after it has gained the keyboard focus.

Parameters

hwndLoseFocus

Value of wParam. Identifies the window that has lost the keyboard focus (may be NULL).

Return Value

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.

See Also

SetFocus, WM_KILLFOCUS


WM_SETFONT
 WM_SETFONT  QuickInfo  Overview  Group

WM_SETFONT

wParam = (WPARAM) hfont;            // handle of font

lParam = MAKELPARAM(fRedraw, 0);    // redraw flag

An application sends a WM_SETFONT message to specify the font that a control is to use when drawing text.

Parameters

hfont

Value of wParam. Identifies the font. If this parameter is NULL, the control uses the default system font to draw text.

fRedraw

Value of lParam. Specifies whether the control should be redrawn immediately upon setting the font. Setting the fRedraw parameter to TRUE causes the control to redraw itself.

Return Value

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, Windows 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

See Also

CreateDialogIndirect, CreateDialogIndirectParam, DeleteObject, DialogBoxIndirect, DialogBoxIndirectParam, WM_INITDIALOG, DLGTEMPLATE


WM_SETHOTKEY
 WM_SETHOTKEY  QuickInfo

WM_SETHOTKEY

wParam = (WPARAM) MAKEWORD(vkey, modifiers)   // virtual-key code and modifiers of hot key

lParam = 0;                                   // not used; must be zero

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.

Parameters

vkey

Value of wParam. Specifies the virtual-key code and modifiers of the hot key to associate with the window. The virtual-key code is in the low byte of the parameter and the modifier flags are in the high byte. Setting this parameter to NULL removes the hot key associated with a window. The modifier byte can be a combination of the following flags:

Value	Meaning
HOTKEYF_ALT	ALT key
HOTKEYF_CONTROL	CTRL key
HOTKEYF_EXT	Extended key
HOTKEYF_SHIFT	SHIFT key
Return Value

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.

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.

See Also

RegisterHotKey, WM_GETHOTKEY, WM_SYSCOMMAND


WM_SETICON [New - Windows 95]
 WM_SETICON  QuickInfo

[New - Windows 95]

WM_SETICON

wParam = (WPARAM) (BOOL) fType;    // icon size (large or small)

lParam = (LPARAM) (HICON) hicon;   // handle of icon

An application sends the WM_SETICON message to associate a new big or small icon with a window. Windows draws the big icon when the window is minimized, and the small icon in the window's title bar.

Parameters

fType

Value of wParam. Specifies the icon being set. If TRUE, the message sets the big icon. If FALSE, the message sets the small icon.

hicon

Value of lParam. Identifies the new big or small icon. If this parameter is NULL, the icon indicated by fType is removed.

Return Value

The return value is the handle of the previous big or small icon, depending on the value of fType. It is NULL if the window previously had no icon of the type indicated by fType.

Default Action

The DefWindowProc function returns the handle of the previous big or small icon associated with the window, depending on the value of fType.

See Also

DefWindowProc, WM_GETICON


WM_SETREDRAW
 WM_SETREDRAW  QuickInfo  Overview  Group

WM_SETREDRAW

wParam = (WPARAM) fRedraw;  // state of redraw flag

lParam = 0;                 // not used; must be zero

An application sends the WM_SETREDRAW message to a window to allow changes in that window to be redrawn or to prevent changes in that window from being redrawn.

Parameters

fRedraw

Value of wParam. Specifies the state of the redraw flag. If this parameter is TRUE, the redraw flag is set. If the parameter is FALSE, the flag is cleared.

Return Value

An application should return zero if it processes this message.

Remarks

This message sets or clears the redraw flag. If the redraw flag is cleared, the content of the given window is not updated after each change, and the window is not repainted until the redraw flag is set. For example, an application that must add several items to a list box can clear the redraw flag, add the items, and then set the redraw flag. Finally, the application can call the InvalidateRect function to cause the list box to be repainted.

See Also

InvalidateRect


WM_SETTEXT
 WM_SETTEXT  QuickInfo  Overview  Group

WM_SETTEXT

wParam = 0;                     // not used; must be zero

lParam = (LPARAM)(LPCTSTR)lpsz; // address of window-text string

An application sends a WM_SETTEXT message to set the text of a window.

Parameters

lpsz

Value of lParam. Points to a null-terminated string that is the window text.

Return Value

The return value is TRUE if the text is set. It is FALSE (for an edit control), LB_ERRSPACE (for a list box), or CB_ERRSPACE (for a combo box) if insufficient space is available to set the text in the edit control. It is CB_ERR if this message is sent to a combo box without an edit control.

Default Action

The DefWindowProc function sets and displays the window text.

Remarks

For an edit control, the text is the contents of the edit control. For a combo box, the text is the contents of the edit-control portion of the combo box. For a button, the text is the button name. For other windows, the text is the window title.

This message does not change the current selection in the list box of a combo box. An application should use the CB_SELECTSTRING message to select the item in a list box that matches the text in the edit control.

See Also

DefWindowProc, CB_SELECTSTRING, WM_GETTEXT


WM_SETTINGCHANGE [New - Windows 95]
 WM_SETTINGCHANGE  QuickInfo

[New - Windows 95]

WM_SETTINGCHANGE

wParam = wFlag;                         // system-wide parameter flag

lParam = (LPARAM) (LPCTSTR) pszMetrics; // metrics name

The WM_SETTINGCHANGE message is sent to all windows when an application changes a systemwide setting by using the SystemParametersInfo function.

Parameters

wFlag

Value of wParam. Specifies the systemwide parameter that has changed. For a list of values, see the SystemParametersInfo function.

pszMetrics

Points to a buffer that contains the string "WindowMetrics" if wFlag specifies any of the following systemwide parameters. This parameter is NULL, otherwise.

SPI_SETANIMATION

SPI_SETNONCLIENTMETRICS

SPI_SETICONMETRICS

SPI_SETMINIMIZEDMETRICS

Return Value

An application should return zero if it processes this message.

Remarks

Windows NT: The WM_SETTINGCHANGE message is implemented on the Windows 95 platform. It is not implemented on the Windows NT platform. The Windows NT message WM_WININICHANGE provides equivalent functionality.

See Also

SystemParametersInfo, WM_WININICHANGE


WM_SHOWWINDOW
 WM_SHOWWINDOW  QuickInfo  Overview  Group

WM_SHOWWINDOW

fShow = (BOOL) wParam;      // show/hide flag

fnStatus = (int) lParam;    // status flag

The WM_SHOWWINDOW message is sent to a window when the window is about to be hidden or shown.

Parameters

fShow

Value of wParam. Specifies whether a window is being shown. It is TRUE if the window is being shown or FALSE if the window is being hidden.

fnStatus

Value of lParam. Specifies the status of the window being shown. The fnStatus parameter is zero if the message is sent because of a call to the ShowWindow function; otherwise, fnStatus is one of the following values:

Value	Meaning
SW_OTHERUNZOOM	Window is being uncovered because a maximize window was restored or minimized.
SW_OTHERZOOM	Window is being covered by another window that has been maximized.
SW_PARENTCLOSING	Window's owner window is being minimized.
SW_PARENTOPENING	Window's owner window is being restored.
Return Value

If an application processes this message, it should return zero.

Default Action

The DefWindowProc function hides or shows the window, as specified by the message.

Remarks

If a window has the WS_VISIBLE style when it is created, the window receives this message after it is created, but before it is displayed. A window also receives this message when its visibility state is changed by the ShowWindow or ShowOwnedPopups function.

The WM_SHOWWINDOW message is not sent under the following circumstances:

•	When a top-level, overlapped window is created with the WS_MAXIMIZE or WS_MINIMIZE style.

•	When the SW_SHOWNORMAL flag is specified in the call to the ShowWindow function.

See Also

DefWindowProc, ShowOwnedPopups, ShowWindow


WM_SIZE
 WM_SIZE  QuickInfo  Overview  Group

WM_SIZE

fwSizeType = wParam;      // resizing flag

nWidth = LOWORD(lParam);  // width of client area

nHeight = HIWORD(lParam); // height of client area

The WM_SIZE message is sent to a window after its size has changed.

Parameters

fwSizeType

Value of wParam. Specifies the type of resizing requested. This parameter can be one of the following values:

Value	Meaning
SIZE_MAXHIDE	Message is sent to all pop-up windows when some other window is maximized.
SIZE_MAXIMIZED	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	Window has been minimized.
SIZE_RESTORED	Window has been resized, but neither the SIZE_MINIMIZED nor SIZE_MAXIMIZED value applies.
nWidth

Value of the low-order word of lParam. Specifies the new width of the client area.

nHeight

Value of the high-order word of lParam. Specifies the new height of the client area.

Return Value

If an application processes this message, it should return zero.

Remarks

If the SetScrollPos or MoveWindow function is called for a child window as a result of the WM_SIZE message, the bRedraw parameter should be nonzero to cause the window to be repainted.

Although the width and height of a window are 32-bit values, the nWidth and nHeight parameters of the WM_SIZE message contain only the low-order 16 bits.

See Also

MoveWindow, SetScrollPos


WM_SIZECLIPBOARD
 WM_SIZECLIPBOARD  QuickInfo  Overview  Group

WM_SIZECLIPBOARD

hwndViewer = (HWND) wParam;  // handle of clipboard viewer window

hglbRc = (HGLOBAL) lParam;   // handle of RECT object

The WM_SIZECLIPBOARD message is sent to the clipboard owner by a clipboard viewer window when the clipboard contains data in the CF_OWNERDISPLAY format and the clipboard viewer's client area has changed size.

Parameters

hwndViewer

Value of wParam. Identifies the clipboard viewer window.

hglbRc

Value of lParam. Identifies a global memory object that contains a RECT structure. The structure specifies the new dimensions of the clipboard viewer's client area.

Remarks

When the clipboard viewer window is about to be destroyed or resized, a WM_SIZECLIPBOARD message is sent with a null rectangle (0, 0, 0, 0) as the new size. This permits the clipboard owner to free its display resources.

The clipboard owner must use the GlobalLock function to lock the memory object that contains RECT. Before returning, the clipboard owner must unlock the object by using the GlobalUnlock function.

See Also

GlobalLock, GlobalUnlock, RECT


WM_SIZING [New - Windows 95]
 WM_SIZING  QuickInfo

[New - Windows 95]

fwSide = wParam;         // edge of window being sized

lprc = (LPRECT) lParam;  // screen coordinates of drag rectangle

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.

Parameters

fwSide

Value of wParam. Indicates which edge of the window is being sized. This parameter can be a combination of the following values:

Value	Meaning
WMSZ_BOTTOM	Bottom edge
WMSZ_BOTTOMLEFT	Bottom-left corner
WMSZ_BOTTOMRIGHT	Bottom-right corner
WMSZ_LEFT	Left edge
WMSZ_RIGHT	Right edge
WMSZ_TOP	Top edge
WMSZ_TOPLEFT	Top-left corner
WMSZ_TOPRIGHT	Top-right corner
lprc

Address of a RECT structure with the screen coordinates of the drag rectangle. To change the size or position of the drag rectangle, an application must change the members of this structure.

Return Value

An application should return TRUE if it processes this message.

See Also

RECT, WM_MOVING, WM_SIZE


WM_SPOOLERSTATUS
 WM_SPOOLERSTATUS  QuickInfo  Overview  Group

WM_SPOOLERSTATUS

fwJobStatus = wParam;       // job-status flag

cJobsLeft = LOWORD(lParam); // number of jobs remaining

The WM_SPOOLERSTATUS message is sent from Windows Print Manager whenever a job is added to or removed from the Print Manager queue.

Parameters

fwJobStatus

Value of wParam. Specifies the PR_JOBSTATUS flag.

cJobsLeft

Value of the low-order word of lParam. Specifies the number of jobs remaining in the Print Manager queue.

Return Value

An application should return zero if it processes this message.

Remarks

This message is for informational purposes only.


WM_STYLECHANGED [New - Windows NT]
 WM_STYLECHANGED  QuickInfo

[New - Windows NT]

WM_STYLECHANGED

wStyleType = wParam;            // extended or nonextended styles

lpss = (LPSTYLESTRUCT) lParam;  // structure containing new styles

The WM_STYLECHANGED message is sent to a window after the SetWindowLong function has changed one or more of the window's styles.

Parameters

wStyleType

Value of wParam. Specifies whether the window's extended or nonextended styles have changed. This parameter can be a combination of the following values:

Value	Meaning
GWL_EXSTYLE	The window's extended styles have changed.
GWL_STYLE	The window's nonextended styles have changed.
lpss

Value of lParam. Points to a STYLESTRUCT structure that contains the new styles for the window. An application can examine the styles, but can not change them.

Return Value

An application should return zero if it processes this message.

See Also

SetWindowLong, STYLESTRUCT, WM_STYLECHANGING


WM_STYLECHANGING [New - Windows NT]
 WM_STYLECHANGING  QuickInfo

[New - Windows NT]

WM_STYLECHANGING

wStyleType = wParam;            // extended or nonextended styles

lpss = (LPSTYLESTRUCT) lParam;  // structure containing new styles

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.

Parameters

wStyleType

Value of wParam. Specifies whether the window's extended or nonextended styles have changed. This parameter can be a combination of the following values:

Value	Meaning
GWL_EXSTYLE	The window's extended styles are changing.
GWL_STYLE	The window's nonextended styles are changing.
lpss

Value of lParam. Points 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 Value

An application should return zero if it processes this message.

See Also

STYLESTRUCT, WM_STYLECHANGED


WM_SYSCHAR
 WM_SYSCHAR  QuickInfo  Overview  Group

WM_SYSCHAR

chCharCode = (TCHAR) wParam;   // character code

lKeyData = lParam;             // key data

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.

Parameters

chCharCode

Value of wParam. Specifies the character code of the System menu key.

lKeyData

Value of lParam. Specifies the repeat count, scan code, extended-key flag, context code, previous key-state flag, and transition-state flag, as shown in the following table:

Value	Meaning
0−15	Specifies the repeat count. The value is the number of times the keystroke is repeated as a result of the user holding down the key.
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 Value

An application should return zero if it processes this message.

Remarks

When the context code is zero, the message can be passed to the TranslateAccelerator function, which will handle it as though it were a standard key message instead of a system character-key message. This allows accelerator keys to be used with the active window even if the active window does not have the keyboard focus.

For enhanced 101- and 102-key keyboards, extended keys are the right ALT and CTRL keys on the main section of the keyboard; the INS, DEL, HOME, END, PAGE UP, PAGE DOWN and arrow keys in the clusters to the left of the numeric keypad; the PRINT SCRN key; the BREAK key; the NUMLOCK key; and the divide (/) and ENTER keys in the numeric keypad. Other keyboards may support the extended-key bit in the lKeyData parameter.

See Also

TranslateAccelerator, TranslateMessage, WM_SYSKEYDOWN


WM_SYSCOLORCHANGE
 WM_SYSCOLORCHANGE  QuickInfo  Overview  Group

WM_SYSCOLORCHANGE

The WM_SYSCOLORCHANGE message is sent to all top-level windows when a change is made to a system color setting.

Parameters

This message has no parameters.

Remarks

Windows sends a WM_PAINT message to any window that is affected by a system color change.

Applications that have brushes using the existing system colors should delete those brushes and recreate them using the new system colors.

Top level windows that use common controls must forward the WM_SYSCOLORCHANGE message to the controls; otherwise, the controls will not be notified of the color change. This ensures that the colors used by your common controls are consistent with those used by other user interface objects. For example, a toolbar control uses the "3D Objects" color to draw its buttons. If the user changes the 3D Objects color but the WM_SYSCOLORCHANGE message is not forwarded to the toolbar, the toolbar buttons will remain in their original color while the color of other buttons in the system changes.

See Also

WM_PAINT


WM_SYSCOMMAND
 WM_SYSCOMMAND  QuickInfo  Overview  Group

WM_SYSCOMMAND

uCmdType = wParam;        // type of system command requested

xPos = LOWORD(lParam);    // horizontal postion, in screen coordinates

yPos = HIWORD(lParam);    // vertical postion, in screen coordinates

A window receives this message when the user chooses a command from the System menu (also known as Control menu) or when the user chooses the Maximize button or Minimize button.

Parameters

uCmdType

Specifies the type of system command requested. This can be one of these 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 System menu.
SC_HOTKEY	Activates the window associated with the application-specified hot key. The low-order word of lParam identifies the window to activate.
SC_HSCROLL	Scrolls horizontally.
SC_KEYMENU	Retrieves the System menu as a result of a keystroke.
SC_MAXIMIZE (or SC_ZOOM)	Maximizes the window.
SC_MINIMIZE (or SC_ICON)	Minimizes the window.
SC_MONITORPOWER	Windows 95 only: Sets the state of the display. This command supports devices that have power-saving features, such as a battery-powered personal computer.
SC_MOUSEMENU	Retrieves the System 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	Executes or activates Windows Task Manager.
SC_VSCROLL	Scrolls vertically.
xPos

Specifies the horizontal position of the cursor, in screen coordinates, if a System menu command is chosen with the mouse. Otherwise, the xPos parameter is not used.

yPos

Specifies the vertical position of the cursor, in screen coordinates, if a System menu command is chosen with the mouse. This parameter is − 1 if the command is chosen using a system accelerator, or zero if using a mnenomic.

Return Value

An application should return zero if it processes this message.

Remarks

The DefWindowProc function carries out the System menu request for the predefined actions specified in the previous table.

In WM_SYSCOMMAND messages, the four low-order bits of the uCmdType parameter are used internally by Windows. To obtain the correct result when testing the value of uCmdType, an application must combine the value 0xFFF0 with the uCmdType value by using the bitwise AND operator.

The menu items in a System menu can be modified by using the GetSystemMenu, AppendMenu, InsertMenu, ModifyMenu, InsertMenuItem, and SetMenuItem functions. Applications that modify the System 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 System menu are translated into WM_SYSCOMMAND messages; all other accelerator keystrokes are translated into WM_COMMAND messages.

See Also

AppendMenu, DefWindowProc, GetSystemMenu, InsertMenu, ModifyMenu, WM_COMMAND


WM_SYSDEADCHAR
 WM_SYSDEADCHAR  QuickInfo  Overview  Group

WM_SYSDEADCHAR

chCharCode = (TCHAR) wParam;    // character code

lKeyData = lParam;              // key data

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.

Parameters

chCharCode

Value of wParam. Specifies the character code generated by the system dead key — that is, a dead key that is pressed while holding down the ALT key.

lKeyData

Value of lParam. Specifies the repeat count, scan code, extended-key flag, context code, previous key-state flag, and transition-state flag, as shown in the following table:

Value	Description
0−15	Specifies the repeat count. The value is the number of times the keystroke is repeated as a result of the user holding down the key.
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 Value

An application should return zero if it processes this message.

Remarks

For enhanced 101- and 102-key keyboards, extended keys are the right ALT and CTRL keys on the main section of the keyboard; the INS, DEL, HOME, END, PAGE UP, PAGE DOWN and arrow keys in the clusters to the left of the numeric keypad; and the divide (/) and ENTER keys in the numeric keypad. Other keyboards may support the extended-key bit in the lKeyData parameter.

See Also

TranslateMessage, WM_DEADCHAR, WM_SYSKEYDOWN


WM_SYSKEYDOWN
 WM_SYSKEYDOWN  QuickInfo  Overview  Group

WM_SYSKEYDOWN

nVirtKey = (int) wParam;    // virtual-key code

lKeyData = lParam;          // key data

The WM_SYSKEYDOWN message is posted to the window with the keyboard focus when the user holds down the ALT key and then presses another key. It also occurs when no window currently has the keyboard focus; in this case, the WM_SYSKEYDOWN message is sent to the active window. The window that receives the message can distinguish between these two contexts by checking the context code in the lKeyData parameter.

Parameters

nVirtKey

Value of wParam. Specifies the virtual-key code of the key being pressed.

lKeyData

Value of lParam. Specifies the repeat count, scan code, extended-key flag, context code, previous key-state flag, and transition-state flag, as shown in the following table:

Value	Description
0−15	Specifies the repeat count. The value is the number of times the keystroke is repeated as a result of the user holding down the key.
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 Value

An application should return zero if it processes this message.

Default Action

The DefWindowProc function examines the given key and generates a WM_SYSCOMMAND message if the key is either TAB or ENTER.

Remarks

When the context code is zero, the message can be passed to the TranslateAccelerator function, which will handle it as though it were a normal key message instead of a 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.

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.

See Also

DefWindowProc, TranslateAccelerator, WM_SYSCOMMAND, WM_SYSKEYUP


WM_SYSKEYUP
 WM_SYSKEYUP  QuickInfo  Overview  Group

WM_SYSKEYUP

nVirtKey = (int) wParam;    // virtual-key code

lKeyData = lParam;          // key data

The WM_SYSKEYUP message is posted to the window with the keyboard focus when the user releases a key that was pressed while the ALT key was held down. It also occurs when no window currently has the keyboard focus; in this case, the WM_SYSKEYUP message is sent to the active window. The window that receives the message can distinguish between these two contexts by checking the context code in the lKeyData parameter.

Parameters

nVirtKey

Value of wParam. Specifies the virtual-key code of the key being released.

lKeyData

Value of lParam. Specifies the repeat count, scan code, extended-key flag, context code, previous key-state flag, and transition-state flag, as shown in the following table:

Value	Description
0−15	Specifies the repeat count. The value is the number of times the keystroke is repeated as a result of the user holding down the key. The repeat count is always one for a WM_SYSKEYUP message.
16−23	Specifies the scan code. The value depends on the original equipment manufacturer (OEM).
24	Specifies whether the key is an extended key, such as the right-hand ALT and CTRL keys that appear on an enhanced 101- or 102-key keyboard. The value is 1 if it is an extended key; otherwise, it is 0.
25−28	Reserved; do not use.
29	Specifies the context code. The value is 1 if the ALT key is down while the key is released; it is 0 if the WM_SYSKEYDOWN message is posted to the active window because no window has the keyboard focus.
30	Specifies the previous key state. The value is always 1 for a WM_SYSKEYUP message.
31	Specifies the transition state. The value is always 1 for a WM_SYSKEYUP message.
Return Value

An application should return zero if it processes this message.

Default Action

The DefWindowProc function sends a WM_SYSCOMMAND message to the top-level window if the F10 key or the ALT key was released. The wParam parameter of the message is set to SC_KEYMENU.

Remarks

When the context code is zero, the message can be passed to the TranslateAccelerator function, which will handle it as though it were a normal key message instead of a 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; and the divide (/) and ENTER keys in the numeric keypad. Other keyboards may support the extended-key bit in the lKeyData parameter.

For non-U.S. enhanced 102-key keyboards, the right ALT key is handled as a CTRL+ALT key. The following table shows the sequence of messages that result when the user presses and releases this key:

Message	Virtual-key code
WM_KEYDOWN	VK_CONTROL
WM_KEYDOWN	VK_MENU
WM_KEYUP	VK_CONTROL
WM_SYSKEYUP	VK_MENU
See Also

DefWindowProc, TranslateAccelerator, WM_SYSCOMMAND, WM_SYSKEYDOWN


WM_TCARD [New - Windows 95]
 WM_TCARD  QuickInfo  Overview  Group

[New - Windows 95]

WM_TCARD

idAction = wParam;

dwActionData = lParam;

The WM_TCARD message is sent to an application that has initiated a training card with Windows Help. The message informs the application when the user clicks an authorable button. An application initiates a training card by specifying the HELP_TCARD command in a call to the WinHelp function.

Parameters

idAction

Value of wParam. Indicates the action the user has taken. This parameter can be one of these values:

Value	Meaning
IDABORT	The user clicked an authorable Abort button.
IDCANCEL	The user clicked an authorable Cancel button.
IDCLOSE	The user closed the training card.
IDHELP	The user clicked an authorable Windows Help button.
IDIGNORE	The user clicked an authorable Ignore button.
IDOK	The user clicked an authorable OK button.
IDNO	The user clicked an authorable No button.
IDRETRY	The user clicked an authorable Retry button.
HELP_TCARD_DATA	The user clicked an authorable button. The lParam parameter contains a long integer specified by the help author.
HELP_TCARD_NEXT	The user clicked an authorable Next button.
HELP_TCARD_OTHER_CALLER	Another application has requested training cards.
IDYES	The user clicked an authorable Yes button.
dwActionData

Value of lParam. If idAction specifies HELP_TCARD_DATA, this parameter is a long integer specified by the help author. Otherwise, this parameter is zero.

Return Value

The return value is ignored; use zero.

See Also

WinHelp


WM_TIMECHANGE
 WM_TIMECHANGE  QuickInfo

WM_TIMECHANGE

wParam = 0; // not used, must be zero

lParam = 0; // not used, must be zero

An application sends the WM_TIMECHANGE message to all top-level windows after changing the system time.

Parameters

This message has no parameters.

Return Value

An application should return zero if it processes this message.

Remarks

An application that changes the system time should send this message to all top-level windows. To send the WM_TIMECHANGE message to all top-level windows, an application can use the SendMessage function with the hwnd parameter set to HWND_TOPMOST.

See Also

SendMessage


WM_TIMER
 WM_TIMER  QuickInfo

WM_TIMER

wTimerID = wParam;            // timer identifier

tmprc = (TIMERPROC *) lParam; // address of timer callback

The WM_TIMER message is posted to the installing thread's message queue or sent to the appropriate TimerProc callback function after each interval specified in the SetTimer function used to install a timer.

Parameters

wTimerID

Value of wParam. Specifies the timer identifier.

tmprc

Value of lParam. Points to an application-defined callback function that was passed to the SetTimer function when the timer was installed. If the tmprc parameter is not NULL, Windows passes the WM_TIMER message to the specified callback function rather than posting the message to the thread's message queue.

Return Value

An application should return zero if it processes this message.

Remarks

The DispatchMessage function forwards this message when no other messages are in the thread's message queue.

See Also

DispatchMessage, SetTimer, TimerProc


WM_UNDO
 WM_UNDO  QuickInfo  Overview  Group

WM_UNDO

wParam = 0; // not used; must be zero

lParam = 0; // not used; must be zero

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.

Parameters

This message has no parameters.

Return Value

If the message succeeds, the return value is TRUE; otherwise, it is FALSE.

See Also

WM_CLEAR, WM_COPY, WM_CUT, WM_PASTE


WM_USER
 WM_USER  QuickInfo

WM_USER

The WM_USER constant is used by applications to help define private messages.

Remarks

The WM_USER constant is used to distinguish between message values that are reserved for use by Windows and values that can be used by an application to send messages within a private window class. There are five ranges of message numbers:

Range	Meaning
0 through WM_USER − 1	Messages reserved for use by Windows.
WM_USER through 0x7FFF	Integer messages for use by private window classes.
0x8000 through 0xBFFF	Messages reserved for future use by Windows.
0xC000 through 0xFFFF	String messages for use by applications.
Greater than 0xFFFF	Reserved by Windows for future use.
Message numbers in the first range (0 through WM_USER − 1) are defined by Windows. Values in this range that are not explicitly defined are reserved for future use by Windows.

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 reserved for future use by Windows.

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 Windows sessions.

Message numbers in the fifth range (greater than 0xFFFF) are reserved for future use by Windows.

See Also

RegisterWindowMessage


WM_USERCHANGED [New - Windows 95]
 WM_USERCHANGED  QuickInfo

[New - Windows 95]

WM_USERCHANGED

wParam = 0;       // not used, must be zero

lParam = 0;       // not used, must be zero

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.

Return Value

An application should return zero if it processes this message.


WM_VKEYTOITEM
 WM_VKEYTOITEM  QuickInfo  Overview  Group

WM_VKEYTOITEM

vkey = LOWORD(wParam);      // virtual-key code

nCaretPos = HIWORD(wParam); // caret position

hwndLB = lParam;            // handle of list box

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.

Parameters

vkey

Value of the low-order word of wParam. Specifies the virtual-key code of the key the user pressed.

nCaretPos

Value of the high-order word of wParam. Specifies the current position of the caret.

hwndLB

Value of lParam. Identifies the list box.

Return Value

The return value specifies the action that the application performed in response to the message. A return value of −2 indicates that the application handled all aspects of selecting the item and requires no further action by the list box. A return value of −1 indicates that the list box should perform the default action in response to the keystroke. A return value of 0 or greater specifies the index of an item in the list box and indicates that the list box should perform the default action for the keystroke on the given item.

Default Action

The DefWindowProc function returns −1.

See Also

DefWindowProc, WM_CHARTOITEM, WM_KEYDOWN


WM_VSCROLL
 WM_VSCROLL  QuickInfo  Overview  Group

WM_VSCROLL

nScrollCode = (int) LOWORD(wParam); // scroll bar value

nPos = (short int) HIWORD(wParam);  // scroll box position

hwndScrollBar = (HWND) lParam;      // handle of scroll bar

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.

Parameters

nScrollCode

Value of the low-order word of wParam. Specifies a scroll bar value that indicates the user's scrolling request. This parameter can be one of the following values:

Value	Meaning
SB_BOTTOM	Scrolls to the lower right.
SB_ENDSCROLL	Ends scroll.
SB_LINEDOWN	Scrolls one line down.
SB_LINEUP	Scrolls one line up.
SB_PAGEDOWN	Scrolls one page down.
SB_PAGEUP	Scrolls one page up.
SB_THUMBPOSITION	Scrolls to the absolute position. The current position is specified by the nPos parameter.
SB_THUMBTRACK	Drags scroll box to the specified position. The current position is specified by the nPos parameter.
SB_TOP	Scrolls to the upper left.
nPos

Value of the high-order word of wParam. Specifies the current position of the scroll box if the nScrollCode parameter is SB_THUMBPOSITION or SB_THUMBTRACK; otherwise, nPos is not used.

hwndScrollBar

Value of lParam. Identifies the control if WM_VSCROLL is sent by a scroll bar control. If WM_VSCROLL is sent by a window's standard scroll bar, hwndScrollBar is not used.

Return Value

If an application processes this message, it should return zero.

Remarks

The SB_THUMBTRACK notification message is typically used by applications that provide feedback as the user drags the scroll box.

If an application scrolls the content of the window, it must also reset the position of the scroll box by using the SetScrollPos function.

Note that the WM_VSCROLL message carries only 16 bits of scroll box position data. Thus, applications that rely solely on WM_VSCROLL (and WM_HSCROLL) for scroll position data have a practical maximum position value of 65,535.

However, because the SetScrollPos, SetScrollRange, 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 GetScrollPos for a description of the technique and its limits.

See Also

GetScrollPos, GetScrollRange, SetScrollPos, SetScrollRange, WM_HSCROLL


WM_VSCROLLCLIPBOARD
 WM_VSCROLLCLIPBOARD  QuickInfo  Overview  Group

WM_VSCROLLCLIPBOARD

hwndViewer = (HWND) wParam;         // handle of clipboard viewer window

nScrollCode = (int) LOWORD(lParam); // scroll bar code

nPos = (int) HIWORD(lParam);        // scroll box position

The WM_VSCROLLCLIPBOARD message is sent to the clipboard owner by a clipboard viewer window when the clipboard contains data in the CF_OWNERDISPLAY format and an event occurs in the clipboard viewer's vertical scroll bar. The owner should scroll the clipboard image and update the scroll bar values.

Parameters

hwndViewer

Value of wParam. Identifies the clipboard viewer window.

nScrollCode

Value of the low-order word of lParam. Specifies a scroll bar event. This parameter can be one of the following values:

Value	Meaning
SB_BOTTOM	Scroll to lower right.
SB_ENDSCROLL	End scroll.
SB_LINEDOWN	Scroll one line down.
SB_LINEUP	Scroll one line up.
SB_PAGEDOWN	Scroll one page down.
SB_PAGEUP	Scroll one page up.
SB_THUMBPOSITION	Scroll to absolute position. The current position is specified by the nPos parameter.
SB_TOP	Scroll to upper left.
nPos

Value of the high-order word of lParam. Specifies the current position of the scroll box if the nScrollCode parameter is SB_THUMBPOSITION; otherwise, the nPos parameter is not used.

Return Value

If an application processes this message, it should return zero.

Remarks

The clipboard owner can use the ScrollWindow function to scroll the image in the clipboard viewer window and invalidate the appropriate region.

See Also

ScrollWindow


WM_WINDOWPOSCHANGED
 WM_WINDOWPOSCHANGED  QuickInfo  Overview  Group

WM_WINDOWPOSCHANGED

lpwp = (LPWINDOWPOS) lParam; // points to size and position data

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.

Parameters

lpwp

Value of lParam. Points to a WINDOWPOS structure that contains information about the window's new size and position.

Return Value

If an application processes this message, it should return zero.

Default Action

The DefWindowProc function sends the WM_SIZE and WM_MOVE messages to the window.

Remarks

The WM_SIZE and WM_MOVE messages are not sent if an application handles the WM_WINDOWPOSCHANGED message without calling DefWindowProc. It is more efficient to perform any move or size change processing during the WM_WINDOWPOSCHANGED message without calling DefWindowProc.

See Also

DefWindowProc, EndDeferWindowPos, SetWindowPos, WINDOWPOS, WM_MOVE, WM_SIZE, WM_WINDOWPOSCHANGING


WM_WINDOWPOSCHANGING
 WM_WINDOWPOSCHANGING  QuickInfo  Overview  Group

WM_WINDOWPOSCHANGING

lpwp = (LPWINDOWPOS) lParam; // points to size and position data

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.

Parameters

lpwp

Value of lParam. Points to a WINDOWPOS structure that contains information about the window's new size and position.

Return Value

If an application processes this message, it should return zero.

Default Action

For a window with the WS_OVERLAPPED or WS_THICKFRAME style, the DefWindowProc function sends the WM_GETMINMAXINFO message to the window. This is done to validate the new size and position of the window and to enforce the CS_BYTEALIGNCLIENT and CS_BYTEALIGNWINDOW client styles. By not passing the WM_WINDOWPOSCHANGING message to the DefWindowProc function, an application can override these defaults.

Remarks

While this message is being processed, modifying any of the values in WINDOWPOS affects the window's new size, position, or place in the Z order. An application can prevent changes to the window by setting or clearing the appropriate bits in the flags member of WINDOWPOS.

See Also

DefWindowProc, EndDeferWindowPos, SetWindowPos, WINDOWPOS, WM_GETMINMAXINFO, WM_MOVE, WM_SIZE, WM_WINDOWPOSCHANGED


WM_WININICHANGE
 WM_WININICHANGE  QuickInfo

WM_WININICHANGE

wParam = 0;                          // not used, must be zero

lParam = (LPARAM) (LPCTSTR) pszSection; // section-name string

An application sends the WM_WININICHANGE message to all top-level windows after making a change to the WIN.INI file. The SystemParametersInfo function sends the WM_WININICHANGE message after an application uses the function to change a setting in WIN.INI.

Parameters

pszSection

Value of lParam. Points to a string containing the name of the section that has changed. The string does not include the square brackets that enclose the section name.

Return Value

An application should return zero if it processes this message.

Remarks

To send the WM_WININICHANGE message to all top-level windows, an application can use the SendMessage function with the hwnd parameter set to HWND_BROADCAST.

Some applications send this message with lParam set to NULL. If an application receives this message with an lParam value of NULL, it should check all sections in WIN.INI that affect the application.

Calls to functions that change WIN.INI may be mapped to the registry instead. This mapping occurs when WIN.INI and the section being changed are specified in the registry under the following keys:

HKEY_LOCAL_MACHINE\Software\Microsoft\
        Windows NT\CurrentVersion\IniFileMapping

The change in the storage location has no effect on the behavior of this message.

Windows 95: The WM_WININICHANGE message is implemented on the Windows NT platform, but not on the Windows 95 platform. Windows 95 applications should use the WM_SETTINGCHANGE message, which provides equivalent functionality.

See Also

SendMessage, SystemParametersInfo, WM_DEVMODECHANGE, WM_SETTINGCHANGE


 Data Types

Various simple data types define the size and meaning of parameters, return values, and members associated with the functions, messages, and structures of Microsoft Windows. The following table contains character, integer, and Boolean types; pointer types; and handles. The character, integer, and Boolean types are common to most C compilers. Many of the pointer-type names begin with a prefix of P or LP. A Windows-based application uses a handle to refer to a resource that has been loaded into memory. Windows provides access to these resources through internally maintained tables that contain individual entries for each handle. Each entry in the handle table contains the address of the resource and a means of identifying the resource type.

Type	Definition
ABORTPROC	Pointer to an application-defined callback function that the operating system calls when a print job is to be cancelled during spooling. See AbortProc for information on functions of this type.
ACMDRIVERENUMCB	Pointer to an application-defined callback function that is used with the acmDriverEnum function. See acmDriverEnumCallback for information on functions of this type.
ACMDRIVERPROC	Pointer to an application-defined callback function that is used with an installable audio compression manager (ACM) driver. See acmDriverProc for information on functions of this type.
ACMFILTERCHOOSEHOOKPROC	Pointer to an application-defined function that hooks the acmFilterChoose dialog box. See acmFilterChooseHookProc for information on functions of this type.
ACMFILTERENUMCB	Pointer to an application-defined callback function that is used with the acmFilterEnum function. See acmFilterEnumCallback for information on functions of this type.
ACMFILTERTAGENUMCB	Pointer to an application-defined callback function that is used with the acmFilterTagEnum function. See acmFilterTagEnumCallback for information on functions of this type.
ACMFORMATCHOOSEHOOKPROC	Pointer to an application-defined function that hooks the acmFormatChoose dialog box. See acmFormatChooseHookProc for information on functions of this type.
ACMFORMATENUMCB	Pointer to an application-defined callback function that is used with the acmFormatEnum function. See acmFormatEnumCallback for information on functions of this type.
ACMFORMATTAGENUMCB	Pointer to an application-defined callback function that is used with the acmFormatTagEnum function. See acmFormatTagEnumCallback for information on functions of this type.
APPLET_PROC	Pointer to a library-defined callback function that is the entry point for a Control Panel application. See CplApplet for information on functions of this type.
ATOM	Atom (a reference to a character string in an atom table).
BOOL	Boolean variable (should be TRUE or FALSE).
BOOLEAN	Boolean variable (should be TRUE or FALSE).
BYTE	Byte (8 bits).
CCHAR	Windows character.
CHAR	Windows character.
COLORREF	Red, green, blue (RGB) color value (32 bits).
CONST	Variable whose value is to remain constant during execution.
CRITICAL_SECTION	Critical-section object.
CTRYID	Country identifier.
DLGPROC	Pointer to an application-defined dialog box callback procedure.
DWORD	Doubleword (32 bits).
DWORDLONG	Double (64 bits).
EDITWORDBREAKPROC	Pointer to an application-defined callback function that the operating system calls when a multiline edit control needs to break a line of text. See EditWordBreakProc for information on functions of this type.
ENHMFENUMPROC	Pointer to an application-defined callback function that enumerates enhanced-metafile records.
ENUMRESLANGPROC	Pointer to an application-defined callback function that enumerates resource languages.
ENUMRESNAMEPROC	Pointer to an application-defined callback function that enumerates resource names.
ENUMRESTYPEPROC	Pointer to an application-defined callback function that enumerates resource types.
FARPROC	Pointer to a callback function.
FLOAT	Floating-point variable.
FONTENUMPROC	Pointer to an application-defined callback function that enumerates fonts.
GLOBALHANDLE	Handle of a global memory block.
GOBJENUMPROC	Pointer to an application-defined callback function that enumerates graphics device interface (GDI) objects.
GRAYSTRINGPROC	Pointer to an application-defined callback function that draws gray text.
HACCEL	Handle of an accelerator table.
HANDLE	Handle of an object.
HBITMAP	Handle of a bitmap.
HBRUSH	Handle of a brush.
HCOLORSPACE	Windows 95 only: Handle of a logical color space.
HCONV	Handle of a dynamic data exchange (DDE) conversation.
HCONVLIST	Handle of a DDE conversation list.
HCURSOR	Handle of a cursor.
HDC	Handle of a device context (DC).
HDDEDATA	Handle of DDE data.
HDWP	Handle of a deferred window position structure.
HENHMETAFILE	Handle of an enhanced metafile.
HFILE	Handle of a file.
HFONT	Handle of a font.
HGDIOBJ	Handle of a GDI object.
HGLOBAL	Handle of a global memory block.
HHOOK	Handle of a hook.
HICON	Handle of an icon.
HIMAGELIST	Handle to an image list.
HINSTANCE	Handle of an instance.
HKEY	Handle of a registry key.
HKL	Windows 95 only: Handle of a keyboard layout.
HLOCAL	Handle of a local memory block.
HMENU	Handle of a menu.
HMETAFILE	Handle of a metafile.
HMODULE	Handle of a module.
HOOKPROC	Pointer to an application-defined hook function.
HPALETTE	Handle of a palette.
HPEN	Handle of a pen.
HRGN	Handle of a region.
HRSRC	Handle of a resource.
HSZ	Handle of a DDE string.
HWINSTA	Handle of a workstation.
HWND	Handle of a window.
INT	Signed integer.
LANGID	Language identifier.
LCID	Locale identifier.
LCSCSTYPE	Color space type.
LCSGAMUTMATCH	Gamut-matching method.
LCTYPE	Locale type.
LINEDDAPROC	Pointer to a callback function that processes line coordinates.
LOCALHANDLE	Handle of a local memory block.
LONG	32-bit signed value.
LONGLONG	Double (64 bits).
LP	Pointer to a null-terminated Unicode™ string.
LPARAM	32-bit message parameter.
LPBOOL	Pointer to a Boolean variable.
LPBYTE	Pointer to a byte.
LPCCH	Pointer to a constant Windows character.
LPCCHOOKPROC	Pointer to an application-defined hook function.
LPCFHOOKPROC	Pointer to an application-defined hook function.
LPCH	Pointer to a Windows character.
LPCOLORREF	Pointer to a COLORREF value.
LPCRITICAL_SECTION	Pointer to a critical-section object.
LPCSTR	Pointer to a constant null-terminated Windows character string.
LPCTSTR	Pointer to a constant null-terminated Unicode or Windows character string.
LPCWCH	Pointer to a constant null-terminated Unicode character.
LPCWSTR	Pointer to a constant null-terminated Unicode character string.
LPDWORD	Pointer to an unsigned doubleword (32 bits).
LPFRHOOKPROC	Pointer to an application-defined hook function.
LPHANDLE	Pointer to a handle.
LPHANDLER_FUNCTION	Pointer to a handler function.
LPINT	Pointer to a signed integer.
LPLONG	Pointer to a signed long (32 bits).
LPOFNHOOKPROC	Pointer to an application-defined hook function.
LPPRINTHOOKPROC	Pointer to an application-defined hook function.
LPSETUPHOOKPROC	Pointer to an application-defined hook function.
LPSTR	Pointer to a null-terminated Windows character string.
LPTCH	Pointer to a Unicode character or a Windows character.
LPTSTR	Pointer to a null-terminated Windows or Unicode character string.
LRESULT	Signed result of message processing.
LPVOID	Pointer to any type.
LPWCH	Pointer to a Unicode character.
LPWORD	Pointer to an unsigned word (16 bits).
LPWSTR	Pointer to a null-terminated Unicode character string.
LUID	Locally unique identifier.
MFENUMPROC	Pointer to an application-defined callback function that enumerates metafile records.
NPSTR	Pointer to a null-terminated Windows character string.
NWPSTR	Pointer to a null-terminated Unicode string.
PBOOL	Pointer to a Boolean variable.
PBOOLEAN	Pointer to a Boolean variable.
PBYTE	Pointer to a byte.
PCCH	Pointer to a constant Windows character.
PCH	Pointer to a Windows character.
PCHAR	Pointer to a Windows character.
PCRITICAL_SECTION	Pointer to a critical-section object.
PCSTR	Pointer to a constant null-terminated Windows character string.
PCWCH	Pointer to a constant Unicode character.
PCWSTR	Pointer to a constant null-terminated Unicode character string.
PDWORD	Pointer to an unsigned doubleword (32 bits).
PFLOAT	Pointer to a floating-point variable.
PFNCALLBACK	Pointer to a callback function.
PHANDLE	Pointer to a handle.
PHANDLER_ROUTINE	Pointer to a handler routine.
PHKEY	Pointer to a registry key.
PINT	Pointer to a signed integer.
PLCID	Pointer to a locale identifier.
PLONG	Pointer to a signed long (32 bits).
PLUID	Pointer to a locally unique identifier (LUID).
PROC	Pointer to a callback function.
PROPENUMPROC	Pointer to an application-defined callback function that enumerates window properties. See PropEnumProc for information on functions of this type.
PROPENUMPROCEX	Pointer to an application-defined callback function that enumerates window properties. See PropEnumProcEx for information on functions of this type.
PSHORT	Pointer to a signed short (16 bits).
PSID	Pointer to a security identifier (SID).
PSTR	Pointer to a null-terminated Windows character string.
PSZ	Pointer to a null-terminated Windows character string.
PTBYTE	Pointer to a Windows or Unicode character.
PTCH	Pointer to a Windows or Unicode character.
PTCHAR	Pointer to a Windows or Unicode character.
PTSTR	Pointer to a null-terminated Windows or Unicode character string.
PUCHAR	Pointer to an unsigned Windows character.
PUINT	Pointer to an unsigned integer.
PULONG	Pointer to an unsigned long (32 bits).
PUSHORT	Pointer to an unsigned short (16 bits).
PVOID	Pointer to any type.
PWCH	Pointer to a Unicode character.
PWCHAR	Pointer to a Unicode character.
PWORD	Pointer to an unsigned word (16 bits).
PWSTR	Pointer to a null-terminated Unicode character string.
REGSAM	Security access mask for registry key.
SC_HANDLE	Handle of a service.
SENDASYNCPROC	Pointer to an application-defined callback function that the operating system calls when the SendMessageCallback function is called. The system passes the message to the callback function after passing the message to the destination window procedure. See SendAsyncProc for information on functions of this type.
SERVICE_STATUS_HANDLE	Handle of a service status value.
SHORT	Short integer.
SPHANDLE	Pointer to a handle.
TBYTE	Windows or Unicode character.
TCHAR	Unicode character or Windows character.
TIMERPROC	Pointer to an application-defined timer callback function.
UCHAR	Unsigned Windows character.
UINT	Unsigned integer.
ULONG	Unsigned long integer (32 bits).
USHORT	Unsigned short integer (16 bits).
VOID	Any type.
WCHAR	Unicode character.
WNDENUMPROC	Pointer to an application-defined callback function that enumerates windows.
WNDPROC	Pointer to an application-defined window procedure.
WORD	Unsigned word (16 bits).
WPARAM	32-bit message parameter.
YIELDPROC	Pointer to a yield callback function.


ABC
 ABC  QuickInfo

typedef struct _ABC { // abc

    int     abcA;

    UINT    abcB;

    int     abcC;

} ABC;

The ABC structure contains the width of a character in a TrueType font.

Members

abcA

Specifies the "A" spacing of the character. The "A" spacing is the distance to add to the current position before drawing the character glyph.

abcB

Specifies the "B" spacing of the character. The "B" spacing is the width of the drawn portion of the character glyph.

abcC

Specifies the "C" spacing of the character. The "C" spacing is the distance to add to the current position to provide white space to the right of the character glyph.

Remarks

The total width of a character is the summation of the "A," "B," and "C" spaces. Either the "A" or the "C" space can be negative to indicate underhangs or overhangs.

See Also

GetCharABCWidths


ABCFLOAT
 ABCFLOAT  QuickInfo

typedef struct _ABCFLOAT { // abcf

    FLOAT   abcfA;

    FLOAT   abcfB;

    FLOAT   abcfC;

} ABCFLOAT;

The ABCFLOAT structure contains the A, B, and C widths of a font character.

Members

abcfA

Specifies the "A" spacing of the character. The "A" spacing is the distance to add to the current position before drawing the character glyph.

abcfB

Specifies the "B" spacing of the character. The "B" spacing is the width of the drawn portion of the character glyph.

abcfC

Specifies the "C" spacing of the character. The "C" spacing is the distance to add to the current position to provide white space to the right of the character glyph.

Remarks

The A, B, and C widths are measured along the base line of the font.

The character increment (total width) of a character is the sum of the "A," "B," and "C" spaces. Either the "A" or the "C" space can be negative to indicate underhangs or overhangs.

See Also

GetCharABCWidthsFloat


ACCEL
 ACCEL  QuickInfo

typedef struct tagACCEL { // accl

    BYTE   fVirt;

    WORD   key;

    WORD   cmd;

} ACCEL;

The ACCEL structure defines an accelerator key used in an accelerator table.

Members

fVirt

Specifies the accelerator flags. This member can be a combination of the following values:

Value	Meaning
FALT	The ALT key must be held down when the accelerator key is pressed.
FCONTROL	The CTRL key must be held down when the accelerator key is pressed.
FNOINVERT	Specifies that no top-level menu item is highlighted when the accelerator is used. If this flag is not specified, a top-level menu item will be highlighted, if possible, when the accelerator is used.
FSHIFT	The SHIFT key must be held down when the accelerator key is pressed.
FVIRTKEY	The key member specifies a virtual-key code. If this flag is not specified, key is assumed to specify an ASCII character code.
key

Specifies the accelerator key. This member can be either a virtual-key code or an ASCII character code.

cmd

Specifies the accelerator identifier. This value is placed in the low-order word of the wParam parameter of the WM_COMMAND or WM_SYSCOMMAND message when the accelerator is pressed.

See Also

WM_COMMAND, WM_SYSCOMMAND


ACCESS_ALLOWED_ACE
 ACCESS_ALLOWED_ACE  QuickInfo

typedef struct _ACCESS_ALLOWED_ACE { // aaace

    ACE_HEADER Header;

    ACCESS_MASK Mask;

    DWORD SidStart;

} ACCESS_ALLOWED_ACE;

The ACCESS_ALLOWED_ACE structure defines an access-control entry (ACE) for the discretionary access-control list (ACL) that controls access to an object. An access-allowed ACE allows access to an object for a specific subject identified by a security identifier (SID).

Members

Header

Specifies an ACE_HEADER structure.

Mask

Specifies an ACCESS_MASK structure that specifies the access rights granted by this ACE.

SidStart

Specifies an SID. The access rights specified by the Mask member are granted to any subject possessing an enabled SID matching this field.

Remarks

ACE structures must be aligned on doubleword boundaries. All Windows memory-management functions return doubleword-aligned handles to memory.

See Also

AddAccessAllowedAce, AddAce, GetAce, ACCESS_DENIED_ACE, ACCESS_MASK, ACE_HEADER, ACL, SID, SYSTEM_ALARM_ACE, SYSTEM_AUDIT_ACE


ACCESS_DENIED_ACE
 ACCESS_DENIED_ACE  QuickInfo

typedef struct _ACCESS_DENIED_ACE { // adace

    ACE_HEADER  Header;

    ACCESS_MASK Mask;

    DWORD       SidStart;

} ACCESS_DENIED_ACE;

The ACCESS_DENIED_ACE structure defines an access-control entry (ACE) for the discretionary access-control list (ACL) controlling access to an object. An access-denied ACE denies access to an object for a specific subject identified by a security identifier (SID).

Members

Header

Specifies an ACE_HEADER structure.

Mask

Specifies an ACCESS_MASK structure specifying the access rights explicitly denied by this ACE.

SidStart

Specifies an SID. The access rights specified by the Mask member are denied to any subject possessing an enabled SID matching this field.

Remarks

ACE structures must be aligned on doubleword boundaries. All Windows memory-management functions return doubleword-aligned handles to memory.

See Also

AddAccessDeniedAce, ACCESS_ALLOWED_ACE, ACCESS_MASK, ACE_HEADER, ACL, SID, SYSTEM_ALARM_ACE, SYSTEM_AUDIT_ACE


ACCESS_MASK
 ACCESS_MASK  QuickInfo

typedef DWORD ACCESS_MASK;

The ACCESS_MASK structure is one doubleword value containing standard, specific, and generic rights. These rights are used in access-control entries (ACEs) and are the primary means of specifying the requested or granted access to an object.

The bits in this value are allocated as follows:

Bits	Meaning
0 through 15	Specific rights. Contains the access mask specific to the object type associated with the mask.
16 through 23	Standard rights. Contains the object's standard access rights and can be a combination of the following predefined flags:
	Bit	Flag	Meaning
	16	DELETE	Delete access
	17	READ_CONTROL	Read access to the owner, group, and discretionary access-control list (ACL) of the security descriptor
	18	WRITE_DAC	Write access to the discretionary access-control list (ACL)
	19	WRITE_OWNER	Write access to owner
	20	SYNCHRONIZE	Windows NT: Synchronize access
Bits	Meaning
24	Access system security (ACCESS_SYSTEM_SECURITY). This flag is not a typical access type. It is used to indicate access to a system ACL. This type of access requires the calling process to have a specific privilege.
25	Maximum allowed (MAXIMUM_ALLOWED)
26 through 27	Reserved
28	Generic all (GENERIC_ALL)
29	Generic execute (GENERIC_EXECUTE)
30	Generic write (GENERIC_WRITE)
31	Generic read (GENERIC_READ)
The following constants represent the specific and standard access rights:

#define SPECIFIC_RIGHTS_ALL           0x0000FFFF

#define STANDARD_RIGHTS_REQUIRED      0x000F0000

#define STANDARD_RIGHTS_ALL           0x001F0000

See Also

GENERIC_MAPPING


ACCESSTIMEOUT
 ACCESSTIMEOUT  QuickInfo  Overview  Group

typedef struct tagACCESSTIMEOUT {     // ato

    UINT  cbSize;

    DWORD dwFlags;

    DWORD iTimeOutMSec;

} ACCESSTIMEOUT;

The ACCESSTIMEOUT structure contains information about the time-out period associated with the Win32 accessibility features. The accessibility time-out period is the length of time that must pass without keyboard and mouse input before the operating system automatically turns off accessibility features. The accessibility features affected by the time-out are the FilterKeys features (SlowKeys, BounceKeys, and RepeatKeys), MouseKeys, ToggleKeys, and StickyKeys. The accessibility time-out is designed for computers that are shared by several users so that options selected by one user do not inconvenience a subsequent user.

Windows 95 only: The accessibility time-out affects the High Contrast Mode setting.

Members

cbSize

Specifies the size, in bytes, of this structure.

dwFlags

A set of bit flags that specify properties of the time-out behavior for accessibility features. The following values are defined:

Value	Meaning
ATF_ONOFFFEEDBACK	If this flag is set, the operating system plays a descending siren sound when the time-out period elapses and the accessibility features are turned off.
ATF_AVAILABLE	If this flag is set, you can set a time-out period for accessibility features. An application can retrieve this value, but cannot set it.
ATF_TIMEOUTON	If this flag is set, a time-out period has been set for accessibility features. If this flag is not set, the features will not time out even though a time-out period is specified.
iTimeOutMSec

Specifies the time-out period, in milliseconds.

Remarks

Use an ACCESSTIMEOUT structure when calling the SystemParametersInfo function with the uiAction parameter set to the SPI_GETACCESSTIMEOUT or SPI_SETACCESSTIMEOUT value. When using SPI_GETACCESSTIMEOUT, you must specify the cbSize member of the ACCESSTIMEOUT structure; the SystemParametersInfo function fills in the remaining members. Specify all structure members when using the SPI_SETACCESSTIMEOUT value.

See Also

SystemParametersInfo


ACE
 ACE  QuickInfo

An ACE is an access-control entry (ACE) in an access-control list (ACL).

Following are the currently defined ACE types:

ACE type	Structure	ACL Type
Access allowed	ACCESS_ALLOWED_ACE	Discretionary
Access denied	ACCESS_DENIED_ACE	Discretionary
System alarm	SYSTEM_ALARM_ACE	System
System audit	SYSTEM_AUDIT_ACE	System
System-alarm ACEs are not supported in the current version of Windows NT.

Remarks

An ACL contains a list of ACEs. An ACE defines access to an object for a specific user or group or defines the types of access that generate system-administration messages or alarms for a specific user or group. The user or group is identified by a security identifier (SID).

Each ACE starts with an ACE_HEADER structure. The format of the data following the header varies according to the ACE type specified in the header.

See Also

AddAce, ACCESS_ALLOWED_ACE, ACCESS_DENIED_ACE, ACL, SYSTEM_ALARM_ACE, SYSTEM_AUDIT_ACE


ACE_HEADER
 ACE_HEADER  QuickInfo

typedef struct _ACE_HEADER { // acehdr

    BYTE AceType;

    BYTE AceFlags;

    WORD AceSize;

} ACE_HEADER;

The ACE_HEADER structure describes the type and size of an access-control entry (ACE).

Members

AceType

Specifies the ACE type. This member can be one of the following values:

Value	ACE type
ACCESS_ALLOWED_ACE_TYPE	Access-allowed (defined by the ACCESS_ALLOWED_ACE structure)
ACCESS_DENIED_ACE_TYPE	Access-denied (defined by the ACCESS_DENIED_ACE structure)
SYSTEM_AUDIT_ACE_TYPE	System-audit (defined by the SYSTEM_AUDIT_ACE structure)
System-alarm ACEs are not supported in the current version of Windows NT. Applications cannot use the SYSTEM_ALARM_ACE_TYPE value or SYSTEM_ALARM_ACE structure.

AceFlags

Specifies a set of ACE type-specific control flags. This member can be a combination of the following values:

Value	Meaning
CONTAINER_INHERIT_ACE
	The ACE is inherited by container objects, such as directories.
INHERIT_ONLY_ACE
	The ACE does not apply to the container object, but to objects contained by it.
NO_PROPAGATE_INHERIT_ACE
	The OBJECT_INHERIT_ACE and CONTAINER_INHERIT_ACE bits are not propagated to an inherited ACE.
OBJECT_INHERIT_ACE
	The ACE is inherited by noncontainer objects, such as files created within the container object to which the ACE is assigned.
FAILED_ACCESS_ACE_FLAG
	Used with system-audit and system-alarm ACEs to indicate a message is generated for failed access attempts.
SUCCESSFUL_ACCESS_ACE_FLAG
	Used with system-audit and system-alarm ACEs to indicate a message is generated for successful access attempts.
AceSize

Specifies the size, in bytes, of the ACE.

Remarks

An ACE defines access to an object for a specific user or group or defines the types of access that generate system-administration messages or alarms for a specific user or group. The user or group is identified by a security identifier (SID).

See Also

ACCESS_ALLOWED_ACE, ACCESS_DENIED_ACE, ACL, SYSTEM_ALARM_ACE, SYSTEM_AUDIT_ACE


ACL
 ACL  QuickInfo

typedef struct _ACL { // acl

    BYTE AclRevision;

    BYTE Sbz1;

    WORD AclSize;

    WORD AceCount;

    WORD Sbz2;

} ACL;

The ACL structure is the header of an access-control list (ACL). A complete ACL consists of an ACL structure followed by an ordered list of zero or more access-control entries (ACEs).

Members

AclRevision

Specifies the ACL's revision level. This value should be ACL_REVISION. All ACEs in an ACL must be at the same revision level.

Sbz1

Specifies a zero byte of padding that aligns the AclRevision member on a 16-bit boundary.

AclSize

Specifies the size, in bytes, of the ACL. This value includes both the ACL structure and all the ACEs.

AceCount

Specifies the number of ACEs stored in the ACL.

Sbz2

Specifies two zero bytes of padding that align the ACL structure on a 32-bit boundary.

Remarks

An ACL includes a sequential list of zero or more ACEs. The individual ACEs in an ACL are numbered from 0 to n, where n+1 is the number of ACEs in the ACL. When editing an ACL, an application refers to an ACE within the ACL by its index.

There are two types of ACL: discretionary and system.

A discretionary ACL is controlled by the owner of an object or anyone granted WRITE_DAC access to the object. It specifies the access particular users and groups can have to an object. For example, the owner of a file can use a discretionary ACL to control which users and groups can and cannot have access to the file.

An object may also have system-level security information associated with it, in the form of a system ACL controlled by a system administrator. A system ACL can allow the system administrator to audit any attempts to gain access to an object.

Three ACE structures are currently defined:

ACE structure	Description
ACCESS_ALLOWED_ACE	Grants specified rights to a user or group. This ACE is stored in a discretionary ACL.
ACCESS_DENIED_ACE	Denies specified rights to a user or group. This ACE is stored in a discretionary ACL.
SYSTEM_AUDIT_ACE	Specifies what types of access will cause system-level audits. This ACE is stored in a system ACL.
A fourth ACE structure, SYSTEM_ALARM_ACE, is not currently supported by Windows NT.

The ACL structure is to be treated as though it were opaque and applications are not to attempt to work with its members directly. To ensure that ACLs are semantically correct, applications can use the functions listed in the SeeAlso section to create and manipulate ACLs.

Each ACL and ACE structure begins on a doubleword boundary.

See Also

AddAce, DeleteAce, GetAclInformation, GetSecurityDescriptorDacl, GetSecurityDescriptorSacl, InitializeAcl, IsValidAcl, SetAclInformation, SetSecurityDescriptorDacl, SetSecurityDescriptorSacl


ACL_REVISION_INFORMATION
 ACL_REVISION_INFORMATION  QuickInfo

typedef struct _ACL_REVISION_INFORMATION {

    DWORD   AclRevision;

} ACL_REVISION_INFORMATION;

The ACL_REVISION_INFORMATION structure contains revision information about an ACL structure.

Members

AclRevision

Specifies a revision number. The current revision number is ACL_REVISION.

See Also

GetAclInformation, SetAclInformation, ACL, ACL_INFORMATION_CLASS, ACL_SIZE_INFORMATION


ACL_SIZE_INFORMATION
 ACL_SIZE_INFORMATION  QuickInfo

typedef struct _ACL_SIZE_INFORMATION {

    DWORD   AceCount;

    DWORD   AclBytesInUse;

    DWORD   AclBytesFree;

} ACL_SIZE_INFORMATION;

The ACL_SIZE_INFORMATION structure contains information about the size of an ACL structure.

Members

AceCount

Specifies the number of access-control entries (ACEs) in the access-control list (ACL).

AclBytesInUse

Specifies the number of bytes in the ACL actually used to store the ACEs and ACL structure. This may be less than the total number of bytes allocated to the ACL.

AclBytesFree

Specifies the number of unused bytes in the ACL.

See Also

GetAclInformation, SetAclInformation, ACL, ACL_INFORMATION_CLASS, ACL_REVISION_INFORMATION


ACTION_HEADER
 ACTION_HEADER  QuickInfo

typedef struct _ACTION_HEADER {

    ULONG   transport_id;

    USHORT  action_code;

    USHORT  reserved;

} ACTION_HEADER;

The ACTION_HEADER structure contains information about an action. This action is an extension to the standard transport interface.

Members

transport_id

Specifies the transport provider. This member can be used to check the validity of the request by the transport.

This member is always a four-character string. All strings starting with the letter M are reserved, as shown in the following example:

String	Meaning
M000	All transports
MNBF	NBF
MABF	AsyBEUI
MXNS	XNS
action_code

Specifies the action.

reserved

Reserved.

Remarks

The scope of the action is determined by the ncb_lsn and ncb_num members of the NCB structure, as follows:

	ncb_lsn = 0	ncb_lsn != 0
ncb_num = 0	Action applies to control channel associated with the valid LAN adapter.	Action applies to connection identifier associated with the valid local session number.
ncb_num != 0	Action applies to address associated with the valid LAN adapter.	Illegal combination.
See Also

NCB


ADAPTER_STATUS
 ADAPTER_STATUS  QuickInfo

typedef struct _ADAPTER_STATUS { // adptst

    UCHAR   adapter_address[6];

    UCHAR   rev_major;

    UCHAR   reserved0;

    UCHAR   adapter_type;

    UCHAR   rev_minor;

    WORD    duration;

    WORD    frmr_recv;

    WORD    frmr_xmit;

    WORD    iframe_recv_err;

    WORD    xmit_aborts;

    DWORD   xmit_success;

    DWORD   recv_success;

    WORD    iframe_xmit_err;

    WORD    recv_buff_unavail;

    WORD    t1_timeouts;

    WORD    ti_timeouts;

    DWORD   reserved1;

    WORD    free_ncbs;

    WORD    max_cfg_ncbs;

    WORD    max_ncbs;

    WORD    xmit_buf_unavail;

    WORD    max_dgram_size;

    WORD    pending_sess;

    WORD    max_cfg_sess;

    WORD    max_sess;

    WORD    max_sess_pkt_size;

    WORD    name_count;

} ADAPTER_STATUS;

The ADAPTER_STATUS structure contains information about a network adapter. This structure is pointed to by the ncb_buffer member of the NCB structure. ADAPTER_STATUS is followed by as many NAME_BUFFER structures as required to describe the network adapters on the system.

Members

adapter_address

Specifies encoded address of the adapter.

rev_major

Specifies the major software-release level. This value is 3 for IBM NetBIOS 3. x.

reserved0

Reserved. This value is always zero.

adapter_type

Specifies the adapter type. This value is 0xFF for a Token Ring adapter or 0xFE for an Ethernet adapter.

rev_minor

Specifies the minor software-release level. This value is zero for IBM NetBIOS x.0.

duration

Specifies the duration of the reporting period, in minutes.

frmr_recv

Specifies the number of FRMR frames received.

frmr_xmit

Specifies the number of FRMR frames transmitted.

iframe_recv_err

Specifies the number of I frames received in error.

xmit_aborts

Specifies the number of aborted transmissions.

xmit_success

Specifies the number of successfully transmitted packets.

recv_success

Specifies the number of successfully received packets.

iframe_xmit_err

Specifies the number of I frames transmitted in error.

recv_buff_unavail

Specifies the number of times a buffer was not available to service a request from a remote computer.

t1_timeouts

Specifies the number of times that the DLC T1 timer timed out.

ti_timeouts

Specifies the number of times that the ti inactivity timer timed out.The ti timer is used to detect links that have been broken.

reserved1

Reserved. This value is always zero.

free_ncbs

Specifies the current number of free network control blocks.

max_cfg_ncbs

Undefined for IBM NetBIOS 3.0.

max_ncbs

Undefined for IBM NetBIOS 3.0.

xmit_buf_unavail

Undefined for IBM NetBIOS 3.0.

max_dgram_size

Specifies the maximum size of a datagram packet. This value is always at least 512 bytes.

pending_sess

Specifies the number of pending sessions.

max_cfg_sess

Specifies the configured maximum pending sessions.

max_sess

Undefined for IBM NetBIOS 3.0.

max_sess_pkt_size

Specifies the maximum size of a session data packet.

name_count

Specifies the number of names in the local names table.

See Also

NAME_BUFFER, NCB


ADDJOB_INFO_1
 ADDJOB_INFO_1  QuickInfo

typedef struct _ADDJOB_INFO_1 { // aji1

    LPTSTR  Path;

    DWORD   JobId;

} ADDJOB_INFO_1;

The ADDJOB_INFO_1 structure identifies a print job as well as the directory and file in which an application can store that job.

Members

Path

Points to a null-terminated string that contains the path and filename that the application can use to store the print job.

JobId

Identifies the print job.

See Also

AddJob


ANIMATIONINFO
 ANIMATIONINFO  QuickInfo

typedef struct tagANIMATIONINFO {

    UINT cbSize;

    int  iMinAnimate;

} ANIMATIONINFO, FAR *LPANIMATIONINFO;

The ANIMATIONINFO structure specifies the animation effects associated with user actions. This structure is used with the SystemParametersInfo function when the SPI_GETANIMATION or SPI_SETANIMATION action value is specified.

Members

cbSize

Specifies the size of the structure, in bytes.

iMinAnimate

Indicates that minimize and restore animation is enabled (if the member is a nonzero value) or not enabled (if zero).

See Also

SystemParametersInfo


APPBARDATA
 APPBARDATA  QuickInfo

typedef struct _AppBarData { // abd

    DWORD  cbSize;           // sizeof(APPBARDATA)

    HWND   hWnd;             // handle of appbar

    UINT   uCallbackMessage; // see below

    UINT   uEdge;            // see below

    RECT   rc;               // see below

    LPARAM lParam;           // see below

} APPBARDATA, *PAPPBARDATA;

Contains information that the system uses to process appbar messages.

Members

uCallbackMessage

Application-defined message identifier. The application uses the specified identifier for notification messages that it sends to the the appbar identified by the hWnd member. This member is used when sending the ABM_NEW message.

uEdge

Flag that specifies an edge of the screen. This member can be one of the following values:

ABE_BOTTOM	Bottom edge
ABE_LEFT	Left edge
ABE_RIGHT	Right edge
ABE_TOP	Top edge
This member is used when sending the ABM_GETAUTOHIDEBAR, ABM_QUERYPOS, ABM_SETAUTOHIDEBAR, and ABM_SETPOS messages.

rc

RECT structure that contains the bounding rectangle, in screen coordinates, of an appbar or the Windows taskbar. This member is used when sending the ABM_GETTASKBARPOS, ABM_QUERYPOS, and ABM_SETPOS messages.

lParam

Message-dependent value. This member is used with the ABM_SETAUTOHIDEBAR message.

Remarks

This structure is used with the SHAppBarMessage function.

See Also

SHAppBarMessage


BITMAP
 BITMAP  QuickInfo

typedef struct tagBITMAP {  // bm

   LONG   bmType;

   LONG   bmWidth;

   LONG   bmHeight;

   LONG   bmWidthBytes;

   WORD   bmPlanes;

   WORD   bmBitsPixel;

   LPVOID bmBits;

} BITMAP;

The BITMAP structure defines the type, width, height, color format, and bit values of a bitmap.

Members

bmType

Specifies the bitmap type. This member must be zero.

bmWidth

Specifies the width, in pixels, of the bitmap. The width must be greater than zero.

bmHeight

Specifies the height, in pixels, of the bitmap. The height must be greater than zero.

bmWidthBytes

Specifies the number of bytes in each scan line. This value must be divisible by 2, because Windows assumes that the bit values of a bitmap form an array that is word aligned.

bmPlanes

Specifies the count of color planes.

bmBitsPixel

Specifies the number of bits required to indicate the color of a pixel.

bmBits

Points to the location of the bit values for the bitmap. The bmBits member must be a long pointer to an array of character (1-byte) values.

Remarks

The bitmap formats currently used are monochrome and color. The monochrome bitmap uses a one-bit, one-plane format. Each scan is a multiple of 32 bits.

Scans are organized as follows for a monochrome bitmap of height n:

    Scan 0

    Scan 1

    .

    .

    .

    Scan n-2

    Scan n-1

The pixels on a monochrome device are either black or white. If the corresponding bit in the bitmap is 1, the pixel is set to the foreground color; if the corresponding bit in the bitmap is zero, the pixel is set to the background color.

All devices that have the RC_BITBLT device capability support bitmaps. For more information, see GetDeviceCaps.

Each device has a unique color format. To transfer a bitmap from one device to another, use the GetDIBits and SetDIBits functions.

See Also

CreateBitmapIndirect, GetObject


BITMAPCOREHEADER
 BITMAPCOREHEADER  QuickInfo

typedef struct tagBITMAPCOREHEADER { // bmch

        DWORD   bcSize;

        WORD    bcWidth;

        WORD    bcHeight;

        WORD    bcPlanes;

        WORD    bcBitCount;

} BITMAPCOREHEADER;

The BITMAPCOREHEADER structure contains information about the dimensions and color format of a device-independent bitmap (DIB).

Members

bcSize

Specifies the number of bytes required by the structure.

bcWidth

Specifies the width of the bitmap, in pixels.

bcHeight

Specifies the height of the bitmap, in pixels.

bcPlanes

Specifies the number of planes for the target device. This value must be 1.

bcBitCount

Specifies the number of bits per pixel. This value must be 1, 4, 8, or 24.

Remarks

The BITMAPCOREINFO structure combines the BITMAPCOREHEADER structure and a color table to provide a complete definition of the dimensions and colors of a DIB. For more information about specifying a device-independent bitmap, see BITMAPCOREINFO structure.

An application should use the information stored in the bcSize member to locate the color table in a BITMAPCOREINFO structure, using a method such as the following:

pColor = ((LPBYTE) pBitmapCoreInfo +

        (WORD) (pBitmapCoreInfo -> bcSize))


BITMAPCOREINFO
 BITMAPCOREINFO  QuickInfo

typedef struct _BITMAPCOREINFO {    // bmci

        BITMAPCOREHEADER  bmciHeader;

        RGBTRIPLE         bmciColors[1];

} BITMAPCOREINFO;

The BITMAPCOREINFO structure defines the dimensions and color information for a device-independent bitmap (DIB).

Members

bmciHeader

Specifies a BITMAPCOREHEADER structure that contains information about the dimensions and color format of a DIB.

bmciColors

Specifies an array of RGBTRIPLE structures that define the colors in the bitmap.

Remarks

A DIB consists of two parts: a BITMAPCOREINFO structure describing the dimensions and colors of the bitmap, and an array of bytes defining the pixels of the bitmap. The bits in the array are packed together, but each scan line must be padded with zeroes to end on a LONG boundary. The origin of the bitmap is the lower left corner.

The bcBitCount member of the BITMAPCOREHEADER structure determines the number of bits that define each pixel and the maximum number of colors in the bitmap. This member can be one of the following values:

Value	Meaning
1	The bitmap is monochrome, and the bmciColors member contains two entries. Each bit in the bitmap array represents a pixel. If the bit is clear, the pixel is displayed with the color of the first entry in the bmciColors table; if the bit is set, the pixel has the color of the second entry in the table.
4	The bitmap has a maximum of 16 colors, and the bmciColors member contains up to 16 entries. Each pixel in the bitmap is represented by a 4-bit index into the color table. For example, if the first byte in the bitmap is 0x1F, the byte represents two pixels. The first pixel contains the color in the second table entry, and the second pixel contains the color in the sixteenth table entry.
8	The bitmap has a maximum of 256 colors, and the bmciColors member contains up to 256 entries. In this case, each byte in the array represents a single pixel.
24	The bitmap has a maximum of 2 (24)  colors, and the bmciColors member is NULL. Each three-byte triplet in the bitmap array represents the relative intensities of red, green, and blue, respectively, for a pixel.
The colors in the bmciColors table should appear in order of importance.

Alternatively, for functions that use DIBs, the bmciColors member can be an array of 16-bit unsigned integers that specify indices into the currently realized logical palette, instead of explicit RGB values. In this case, an application using the bitmap must call the DIB functions (CreateDIBitmap, CreateDIBPatternBrush, and CreateDIBSection) with the iUsage parameter set to DIB_PAL_COLORS.

Note  The bmciColors member should not contain palette indices if the bitmap is to be stored in a file or transferred to another application. Unless the application has exclusive use and control of the bitmap, the bitmap color table should contain explicit RGB values.

See Also

BITMAPCOREHEADER, CreateDIBitmap, CreateDIBPatternBrush, CreateDIBSection RGBTRIPLE


BITMAPFILEHEADER
 BITMAPFILEHEADER  QuickInfo

typedef struct tagBITMAPFILEHEADER { // bmfh

        WORD    bfType;

        DWORD   bfSize;

        WORD    bfReserved1;

        WORD    bfReserved2;

        DWORD   bfOffBits;

} BITMAPFILEHEADER;

The BITMAPFILEHEADER structure contains information about the type, size, and layout of a file that contains a device-independent bitmap (DIB).

Members

bfType

Specifies the file type. It must be BM.

bfSize

Specifies the size, in bytes, of the bitmap file.

bfReserved1

Reserved; must be zero.

bfReserved2

Reserved; must be zero.

bfOffBits

Specifies the offset, in bytes, from the BITMAPFILEHEADER structure to the bitmap bits.

Remarks

A BITMAPINFO or BITMAPCOREINFO structure immediately follows the BITMAPFILEHEADER structure in the DIB file.

See Also

BITMAPCOREINFO, BITMAPINFO


BITMAPINFO
 BITMAPINFO  QuickInfo

typedef struct tagBITMAPINFO { // bmi

   BITMAPINFOHEADER bmiHeader;

   RGBQUAD          bmiColors[1];

} BITMAPINFO;

The BITMAPINFO structure defines the dimensions and color information for a Windows device-independent bitmap (DIB).

Members

bmiHeader

Specifies a BITMAPINFOHEADER structure that contains information about the dimensions and color format of a DIB.

bmiColors

Specifies an array of RGBQUAD or doubleword data types that define the colors in the bitmap.

Remarks

A device-independent bitmap consists of two distinct parts: a BITMAPINFO structure describing the dimensions and colors of the bitmap, and an array of bytes defining the pixels of the bitmap. The bits in the array are packed together, but each scan line must be padded with zeroes to end on a LONG data-type boundary. If the height is positive, the bitmap is a bottom-up DIB and its origin is the lower left corner. If the height is negative, the bitmap is a top-down DIB and its origin is the upper left corner.

The biBitCount member of the BITMAPINFOHEADER structure determines the number of bits that define each pixel and the maximum number of colors in the bitmap. This member can be one of the following values:

Value	Meaning
1	The bitmap is monochrome, and the bmiColors member contains two entries. Each bit in the bitmap array represents a pixel. If the bit is clear, the pixel is displayed with the color of the first entry in the bmiColors table; if the bit is set, the pixel has the color of the second entry in the table.
4	The bitmap has a maximum of 16 colors, and the bmiColors member contains up to 16 entries. Each pixel in the bitmap is represented by a 4-bit index into the color table. For example, if the first byte in the bitmap is 0x1F, the byte represents two pixels. The first pixel contains the color in the second table entry, and the second pixel contains the color in the sixteenth table entry.
8	The bitmap has a maximum of 256 colors, and the bmiColors member contains up to 256 entries. In this case, each byte in the array represents a single pixel.
16	The bitmap has a maximum of 2 (16)  colors. If the biCompression member of the BITMAPINFOHEADER is BI_RGB, the bmiColors member is NULL. Each WORD in the bitmap array represents a single pixel. The relative intensities of red, green, and blue are represented with 5 bits for each color component. The value for blue is in the least significant 5 bits, followed by 5 bits each for green and red, respectively. The most significant bit is not used. If the biCompression member of the BITMAPINFOHEADER is BI_BITFIELDS, the bmiColors member contains three DWORD color masks that specify the red, green, and blue components, respectively, of each pixel. Each WORD in the bitmap array represents a single pixel. Windows NT: When the biCompression member is BI_BITFIELDS, bits set in each DWORD mask must be contiguous and should not overlap the bits of another mask. All the bits in the pixel do not have to be used.  Windows 95: When the biCompression member is BI_BITFIELDS, Windows 95 supports only the following 16bpp color masks: A 5-5-5 16-bit image, where the blue mask is 0x001F, the green mask is 0x03E0, and the red mask is 0x7C00; and a 5-6-5 16-bit image, where the blue mask is 0x001F, the green mask is 0x07E0, and the red mask is 0xF800.
24	The bitmap has a maximum of 2 (24)  colors, and the bmiColors member is NULL. Each 3-byte triplet in the bitmap array represents the relative intensities of blue, green, and red, respectively, for a pixel.
32	The bitmap has a maximum of 2 (32)  colors. If the biCompression member of the BITMAPINFOHEADER is BI_RGB, the bmiColors member is NULL. Each DWORD in the bitmap array represents the relative intensities of blue, green, and red, respectively, for a pixel. The high byte in each DWORD is not used. If the biCompression member of the BITMAPINFOHEADER is BI_BITFIELDS, the bmiColors member contains three DWORD color masks that specify the red, green, and blue components, respectively, of each pixel. Each DWORD in the bitmap array represents a single pixel. Windows NT: When the biCompression member is BI_BITFIELDS, bits set in each DWORD mask must be contiguous and should not overlap the bits of another mask. All the bits in the pixel do not have to be used.  Windows 95: When the biCompression member is BI_BITFIELDS, Windows 95 supports only the following 32bpp color mask: The blue mask is 0x000000FF, the green mask is 0x0000FF00, and the red mask is 0x00FF0000.
The biClrUsed member of the BITMAPINFOHEADER structure specifies the number of color indices in the color table that are actually used by the bitmap. If the biClrUsed member is set to zero, the bitmap uses the maximum number of colors corresponding to the value of the biBitCount member.

The colors in the bmiColors table should appear in order of importance.

Alternatively, for functions that use DIBs, the bmiColors member can be an array of 16-bit unsigned integers that specify indices into the currently realized logical palette, instead of explicit RGB values. In this case, an application using the bitmap must call the DIB functions (CreateDIBitmap, CreateDIBPatternBrush, and CreateDIBSection) with the iUsage parameter set to DIB_PAL_COLORS.

If the bitmap is a packed bitmap (a bitmap in which the bitmap array immediately follows the BITMAPINFO header and which is referenced by a single pointer), the biClrUsed member must be set to an even number when using the DIB_PAL_COLORS mode so the DIB bitmap array starts on a doubleword boundary.

Note  The bmiColors member should not contain palette indices if the bitmap is to be stored in a file or transferred to another application. Unless the application has exclusive use and control of the bitmap, the bitmap color table should contain explicit RGB values.

See Also

BITMAPINFOHEADER, CreateDIBitmap, CreateDIBPatternBrush, CreateDIBSection, RGBQUAD


BITMAPINFOHEADER
 BITMAPINFOHEADER  QuickInfo

typedef struct tagBITMAPINFOHEADER{ // bmih

   DWORD  biSize;

   LONG   biWidth;

   LONG   biHeight;

   WORD   biPlanes;

   WORD   biBitCount

   DWORD  biCompression;

   DWORD  biSizeImage;

   LONG   biXPelsPerMeter;

   LONG   biYPelsPerMeter;

   DWORD  biClrUsed;

   DWORD  biClrImportant;

} BITMAPINFOHEADER;

The BITMAPINFOHEADER structure contains information about the dimensions and color format of a device-independent bitmap (DIB).

Members

biSize

Specifies the number of bytes required by the structure.

biWidth

Specifies the width of the bitmap, in pixels.

biHeight

Specifies the height of the bitmap, in pixels. If biHeight is positive, the bitmap is a bottom-up DIB and its origin is the lower left corner. If biHeight is negative, the bitmap is a top-down DIB and its origin is the upper left corner.

biPlanes

Specifies the number of planes for the target device. This value must be set to 1.

biBitCount

Specifies the number of bits per pixel. This value must be 1, 4, 8, 16, 24, or 32.

biCompression

Specifies the type of compression for a compressed bottom-up bitmap (top-down DIBs cannot be compressed). It can be one of the following values:

Value	Description
BI_RGB	An uncompressed format.
BI_RLE8	A run-length encoded (RLE) format for bitmaps with 8 bits per pixel. The compression format is a two-byte format consisting of a count byte followed by a byte containing a color index. For more information, see the following Remarks section.
BI_RLE4	An RLE format for bitmaps with 4 bits per pixel. The compression format is a two-byte format consisting of a count byte followed by two word-length color indices. For more information, see the following Remarks section.
BI_BITFIELDS	Specifies that the bitmap is not compressed and that the color table consists of three doubleword color masks that specify the red, green, and blue components, respectively, of each pixel. This is valid when used with 16- and 32-bits-per-pixel bitmaps.
biSizeImage

Specifies the size, in bytes, of the image. This may be set to 0 for BI_RGB bitmaps.

biXPelsPerMeter

Specifies the horizontal resolution, in pixels per meter, of the target device for the bitmap. An application can use this value to select a bitmap from a resource group that best matches the characteristics of the current device.

biYPelsPerMeter

Specifies the vertical resolution, in pixels per meter, of the target device for the bitmap.

biClrUsed

Specifies the number of color indices in the color table that are actually used by the bitmap. If this value is zero, the bitmap uses the maximum number of colors corresponding to the value of the biBitCount member for the compression mode specified by biCompression.

If biClrUsed is nonzero and the biBitCount member is less than 16, the biClrUsed member specifies the actual number of colors the graphics engine or device driver accesses. If biBitCount is 16 or greater, then biClrUsed member specifies the size of the color table used to optimize performance of Windows color palettes. If biBitCount equals 16 or 32, the optimal color palette starts immediately following the three doubleword masks.

If the bitmap is a packed bitmap (a bitmap in which the bitmap array immediately follows the BITMAPINFO header and which is referenced by a single pointer), the biClrUsed member must be either 0 or the actual size of the color table.

biClrImportant

Specifies the number of color indices that are considered important for displaying the bitmap. If this value is zero, all colors are important.

Remarks

The BITMAPINFO structure combines the BITMAPINFOHEADER structure and a color table to provide a complete definition of the dimensions and colors of a DIB. For more information about DIBs, see the description of the BITMAPINFO data structure.

An application should use the information stored in the biSize member to locate the color table in a BITMAPINFO structure, as follows:

pColor = ((LPSTR)pBitmapInfo +

    (WORD)(pBitmapInfo->bmiHeader.biSize));

Windows supports formats for compressing bitmaps that define their colors with eight or four bits per pixel. Compression reduces the disk and memory storage required for the bitmap. The following paragraphs describe these formats.

When the biCompression member is BI_RLE8, the bitmap is compressed by using a run-length encoding (RLE) format for an 8-bit bitmap. This format can be compressed in encoded or absolute modes. Both modes can occur anywhere in the same bitmap.

•	Encoded mode consists of two bytes: the first byte specifies the number of consecutive pixels to be drawn using the color index contained in the second byte. In addition, the first byte of the pair can be set to zero to indicate an escape that denotes an end of line, end of bitmap, or delta. The interpretation of the escape depends on the value of the second byte of the pair, which can be one of the following:

Value	Meaning
0	End of line.
1	End of bitmap.
2	Delta. The two bytes following the escape contain unsigned values indicating the horizontal and vertical offsets of the next pixel from the current position.
•	In absolute mode, the first byte is zero and the second byte is a value in the range 03H through FFH. The second byte represents the number of bytes that follow, each of which contains the color index of a single pixel. When the second byte is 2 or less, the escape has the same meaning as in encoded mode. In absolute mode, each run must be aligned on a word boundary.

The following example shows the hexadecimal values of an 8-bit compressed bitmap.

03 04 05 06 00 03 45 56 67 00 02 78 00 02 05 01

02 78 00 00 09 1E 00 01

This bitmap would expand as follows (two-digit values represent a color index for a single pixel):

04 04 04

06 06 06 06 06

45 56 67

78 78

move current position 5 right and 1 down

78 78

end of line

1E 1E 1E 1E 1E 1E 1E 1E 1E

end of RLE bitmap

When the biCompression member is BI_RLE4, the bitmap is compressed by using a run-length encoding format for a 4-bit bitmap, which also uses encoded and absolute modes:

•	In encoded mode, the first byte of the pair contains the number of pixels to be drawn using the color indices in the second byte. The second byte contains two color indices, one in its high-order four bits and one in its low-order four bits. The first of the pixels is drawn using the color specified by the high-order four bits, the second is drawn using the color in the low-order four bits, the third is drawn using the color in the high-order four bits, and so on, until all the pixels specified by the first byte have been drawn.

•	In absolute mode, the first byte is zero, the second byte contains the number of color indices that follow, and subsequent bytes contain color indices in their high- and low-order four bits, one color index for each pixel. In absolute mode, each run must be aligned on a word boundary. The end-of-line, end-of-bitmap, and delta escapes described for BI_RLE8 also apply to BI_RLE4 compression.

The following example shows the hexadecimal values of a 4-bit compressed bitmap.

03 04 05 06 00 06 45 56 67 00 04 78 00 02 05 01

04 78 00 00 09 1E 00 01

This bitmap would expand as follows (single-digit values represent a color index for a single pixel):

0 4 0

0 6 0 6 0

4 5 5 6 6 7

7 8 7 8

move current position 5 right and 1 down

7 8 7 8

end of line

1 E 1 E 1 E 1 E 1

end of RLE bitmap

If biHeight is negative, indicating a top-down DIB, biCompression must be either BI_RGB or BI_BITFIELDS. Top-down DIBs cannot be compressed.

See Also

BITMAPINFO


BITMAPV4HEADER [New - Windows 95]
 BITMAPV4HEADER  QuickInfo  Overview  Group

[New - Windows 95]

typedef struct {
    DWORD        bV4Size;
    LONG         bV4Width;
    LONG         bV4Height;
    WORD         bV4Planes;
    WORD         bV4BitCount;
    DWORD        bV4V4Compression;
    DWORD        bV4SizeImage;
    LONG         bV4XPelsPerMeter;
    LONG         bV4YPelsPerMeter;
    DWORD        bV4ClrUsed;
    DWORD        bV4ClrImportant;
    DWORD        bV4RedMask;
    DWORD        bV4GreenMask;
    DWORD        bV4BlueMask;
    DWORD        bV4AlphaMask;
    DWORD        bV4CSType;
    CIEXYZTRIPLE bV4Endpoints;
    DWORD        bV4GammaRed;
    DWORD        bV4GammaGreen;
    DWORD        bV4GammaBlue;
} BITMAPV4HEADER, FAR *LPBITMAPV4HEADER, *PBITMAPV4HEADER;

The BITMAPV4HEADER structure contains information about a Win32 version 4.0 bitmap.


BLOB
 BLOB  QuickInfo  Overview  Group

typedef struct _BLOB {

    ULONG   cbSize;

    BYTE    *pBlobData;

} BLOB;

A BLOB structure contains information about a block of data.

Members

cbSize

Specifies the size in bytes of the block of data pointed to by pBlobData

Addresses

Points to a block of data.

Remarks

The structure name BLOB comes from the acronym BLOB, which stands for "Binary Large OBject".

Note that this structure description says nothing about the nature of the data pointed to by pBlobData.

See Also

SERVICE_INFO


BROWSEINFO
 BROWSEINFO  QuickInfo

typedef struct _browseinfo {

    HWND hwndOwner;          // see below

    LPCITEMIDLIST pidlRoot;  // see below

    LPSTR pszDisplayName;    // see below

    LPCSTR lpszTitle;        // see below

    UINT ulFlags;            // see below

    BFFCALLBACK lpfn;        // see below

    LPARAM lParam;           // see below

    int iImage;              // see below

} BROWSEINFO, *PBROWSEINFO, *LPBROWSEINFO;

Contains parameters for the the SHBrowseForFolder function and receives information about the folder selected by the user.

Members

hwndOwner

Handle of the owner window for the dialog box.

pidlRoot

Pointer to an item identifier list (an ITEMIDLIST structure) specifying the location of the "root" folder to browse from. Only the specified folder and its subfolders appear in the dialog box. This member can be NULL, and in that case, the name space root (the desktop folder) is used.

pszDisplayName

Pointer to a buffer that receives the display name of the folder selected by the user. The size of this buffer is assumed to be MAX_PATH bytes.

lpszTitle

Pointer to a null-terminated string that is displayed above the tree view control in the dialog box. This string can be used to specify instructions to the user.

ulFlags

Value specifying the types of folders to be listed in the dialog box as well as other options. This member can include zero or more of the following values:

BIF_BROWSEFORCOMPUTER	Only returns computers. If the user selects anything other than a computer, the OK button is grayed.
BIF_BROWSEFORPRINTER	Only returns printers. If the user selects anything other than a printer, the OK button is grayed.
BIF_DONTGOBELOWDOMAIN	Does not include network folders below the domain level in the tree view control.
BIF_RETURNFSANCESTORS	Only returns file system ancestors. If the user selects anything other than a file system ancestor, the OK button is grayed.
BIF_RETURNONLYFSDIRS	Only returns file system directories. If the user selects folders that are not part of the file system, the OK button is grayed.
BIF_STATUSTEXT	Includes a status area in the dialog box. The callback function can set the status text by sending messages to the dialog box.
lpfn

Address an application-defined function that the dialog box calls when events occur. For more information, see the description of the BrowseCallbackProc function. This member can be NULL.

lParam

Application-defined value that the dialog box passes to the callback function (if one is specified).

iImage

Variable that receives the image associated with the selected folder. The image is specified as an index to the system image list.

See Also

BrowseCallbackProc, ITEMIDLIST, SHBrowseForFolder


BY_HANDLE_FILE_INFORMATION
 BY_HANDLE_FILE_INFORMATION  QuickInfo

typedef struct _BY_HANDLE_FILE_INFORMATION { // bhfi

    DWORD    dwFileAttributes;

    FILETIME ftCreationTime;

    FILETIME ftLastAccessTime;

    FILETIME ftLastWriteTime;

    DWORD    dwVolumeSerialNumber;

    DWORD    nFileSizeHigh;

    DWORD    nFileSizeLow;

    DWORD    nNumberOfLinks;

    DWORD    nFileIndexHigh;

    DWORD    nFileIndexLow;

} BY_HANDLE_FILE_INFORMATION;

The BY_HANDLE_FILE_INFORMATION structure contains information retrieved by the GetFileInformationByHandle function.

Members

dwFileAttributes

Specifies file attributes. This member can be one or more of the following values:

Value	Meaning
FILE_ATTRIBUTE_ARCHIVE
	The file is an archive file. Applications use this value to mark files for backup or removal.
FILE_ATTRIBUTE_COMPRESSED
	The file or directory is compressed. For a file, this means that all of the data in the file is compressed. For a directory, this means that compression is the default for newly created files and subdirectories.
FILE_ATTRIBUTE_DIRECTORY
	The file is a directory.
FILE_ATTRIBUTE_HIDDEN
	The file is hidden. It is not included in an ordinary directory listing.
FILE_ATTRIBUTE_NORMAL
	The file has no other attributes. This value is valid only if used alone.
FILE_ATTRIBUTE_READONLY
	The file is read-only. Applications can read the file but cannot write to it or delete it.
FILE_ATTRIBUTE_SYSTEM
	The file is part of the operating system or is used exclusively by it.
FILE_ATTRIBUTE_TEMPORARY
	The file is being used for temporary storage. Applications should write to the file only if absolutely necessary. Most of the file's data remains in memory without being flushed to the media because the file will soon be deleted.
ftCreationTime

Specifies the time the file was created. If the underlying file system does not support this time member, ftCreationTime is zero.

ftLastAccessTime

Specifies the time the file was last accessed. If the underlying file system does not support this time member, ftLastAccessTime is zero.

ftLastWriteTime

Specifies the last time the file was written to.

dwVolumeSerialNumber

Specifies the serial number of the volume that contains the file.

nFileSizeHigh

Specifies the high-order word of the file size.

nFileSizeLow

Specifies the low-order word of the file size.

nNumberOfLinks

Specifies the number of links to this file. For the FAT file system and HPFS, this member is always 1. For NTFS, it may be more than 1.

nFileIndexHigh

Specifies the high-order word of a unique identifier associated with the file.

nFileIndexLow

Specifies the low-order word of a unique identifier associated with the file. This identifier and the volume serial number uniquely identify a file. This number may change when the system is restarted or when the file is opened. After a process opens a file, the identifier is constant until the file is closed. An application can use this identifier and the volume serial number to determine whether two handles refer to the same file.

See Also

GetFileInformationByHandle


CANDIDATEFORM [New - Windows 95]
 CANDIDATEFORM  QuickInfo  Overview  Group

[New - Windows 95]

typedef _tagCANDIDATEFORM {
    DWORD  dwIndex;
    DWORD  dwStyle;
    POINT  ptCurrentPos;
    RECT   rcArea;
} CANDIDATEFORM;

The CANDIDATEFORM structure contains position information for the candidate window.

Members

dwIndex

Candidate list identifier. Can be 0 for the first list, 1 for the second, and so on. The maximum index is 31.

dwStyle

Position style. This member can be one of the following values:

CFS_CANDIDATEPOS	Display the upper-left corner of the candidate list window at the position given by ptCurrentPos. The coordinates are relative to the upper-left corner of the window containing the list window, and are subject to adjustment by the system.
CFS_EXCLUDE	Exclude the candidate window from the area given by rcArea. The ptCurrentPos member specifies the coordinates of the current point of interest, typically the caret position.
ptCurrentPos

Coordinates of the upper-left corner of the candidate window or the caret position, depending on the value of dwStyle.

rcArea

Coordinates of the upper-left and lower-right corners of the exclusion area.


CANDIDATELIST [New - Windows 95]
 CANDIDATELIST  QuickInfo  Overview  Group

[New - Windows 95]

typedef struct _tagCANDIDATELIST {
    DWORD  dwSize;
    DWORD  dwStyle;
    DWORD  dwCount;
    DWORD  dwSelection;
    DWORD  dwPageStart;
    DWORD  dwPageSize;
    DWORD  dwOffset[];
} CANDIDATELIST;

The CANDIDATELIST structure contains information about a candidate list.

Members

dwSize

Size, in bytes, of the structure, the offset array, and all candidate strings.

dwStyle

Candidate style values. This member can be one or more of the following values:

Value	Meaning
IME_CAND_UNKNOWN	Candidates are in a style other than listed here.
IME_CAND_READ	Candidates are in same reading.
IME_CAND_CODE	Candidates are in a code range.
IME_CAND_MEANING	Candidates are in same meaning.
IME_CAND_RADICAL	Candidates use same radical character.
IME_CAND_STROKES	Candidates are in same number of strokes.
For the IME_CAND_CODE style, the candidate list has a special structure depending on the value of the dwCount member. If dwCount is 1, the dwOffset member contains a single DBCS character rather than an offset, and no candidate string is provided. If the dwCount member is greater than 1, the dwOffset member contains valid offsets, and the candidate strings are text representations of individual DBCS character values in hexadecimal notation.

dwCount

Number of candidate strings.

dwSelection

Index of the selected candidate string.

dwPageStart

Index of the first candidate string in the candidate window. This varies as the user presses the PAGE UP and PAGE DOWN keys.

dwPageSize

Number of candidate strings to be shown in one page in the candidate window. The user can move to the next page by pressing IME-defined keys, such as the PAGE UP or PAGE DOWN key. If this number is zero, an application can define a proper value by itself.

dwOffset

Offset to the start of the first candidate string, relative to the start of this structure. The offsets for subsequent strings immediately follow this member, forming an array of 32-bit offsets.

Remarks

The candidate strings immediately follow the last offset in the dwOffset array.


CBT_CREATEWND
 CBT_CREATEWND  QuickInfo

typedef struct tagCBT_CREATEWND { // cbtcw

    LPCREATESTRUCT lpcs;

    HWND           hwndInsertAfter;

} CBT_CREATEWND;

The CBT_CREATEWND structure contains information passed to a WH_CBT hook procedure before a window is created.

Members

lpcs

Points to a CREATESTRUCT structure that contains initialization parameters for the window about to be created.

hwndInsertAfter

Identifies the window whose position in the Z order precedes that of the window being created.

See Also

CBTProc, CREATESTRUCT, SetWindowsHookEx


CBTACTIVATESTRUCT
 CBTACTIVATESTRUCT  QuickInfo

typedef struct tagCBTACTIVATESTRUCT { // cas

    BOOL fMouse;

    HWND hWndActive;

} CBTACTIVATESTRUCT;

The CBTACTIVATESTRUCT structure contains information passed to a WH_CBT hook procedure before a window is activated.

Members

fMouse

Specifies whether the window is being activated as a result of a mouse click. This value is TRUE if a mouse click is causing the activation or FALSE if it is not.

hWndActive

Identifies the active window.

See Also

SetWindowsHookEx


CHAR_INFO
 CHAR_INFO  QuickInfo  Overview  Group

typedef struct _CHAR_INFO { // chi

    union {                /* Unicode or ANSI character  */

        WCHAR UnicodeChar;

        CHAR AsciiChar;

    } Char;

    WORD Attributes;       // text and background colors

} CHAR_INFO, *PCHAR_INFO;

The CHAR_INFO structure specifies the Unicode or ANSI character and the foreground (text) and background color attributes of a screen buffer character cell. This structure is used by console functions to read from and write to a console screen buffer.

Members

Char

Specifies either the Unicode (wide-character) or ANSI character of a screen buffer character cell, depending on whether the Unicode or ANSI version of the function is used.

Attributes

Specifies the foreground (text) and background colors in which a screen buffer character cell is drawn. This member can be zero, or it can be any combination of the following values:

BACKGROUND_BLUE	FOREGROUND_BLUE
BACKGROUND_GREEN	FOREGROUND_GREEN
BACKGROUND_RED	FOREGROUND_RED
BACKGROUND_INTENSITY	FOREGROUND_INTENSITY
See Also

ReadConsoleOutput, ScrollConsoleScreenBuffer, WriteConsoleOutput


CHARFORMAT [New - Windows NT]
 CHARFORMAT  QuickInfo  Overview  Group

[New - Windows NT]

typedef struct _charformat {

    UINT     cbSize;

    _WPAD    _wPad1;

    DWORD    dwMask;

    DWORD    dwEffects;

    LONG     yHeight;

    LONG     yOffset;

    COLORREF crTextColor;

    BYTE     bCharSet;

    BYTE     bPitchAndFamily;

    TCHAR    szFaceName[LF_FACESIZE];

    _WPAD    _wPad2;

} CHARFORMAT;

The CHARFORMAT structure contains information about character formatting in a rich edit control.

Members

cbSize

Size in bytes of this structure. Must be set before passing the structure to the rich edit control.

dwMask

Members containing valid information or attributes to set. This member can be zero or more of the following values:

Value	Meaning
CFM_BOLD	The CFE_BOLD value of the dwEffects member is valid.
CFM_COLOR	The crTextColor member and the CFE_AUTOCOLOR value of the dwEffects member are valid.
CFM_FACE	The szFaceName member is valid.
CFM_ITALIC	The CFE_ITALIC value of the dwEffects member is valid.
CFM_OFFSET	The yOffset member is valid.
CFM_PROTECTED	The CFE_PROTECTED value of the dwEffects member is valid.
CFM_SIZE	The yHeight member is valid.
CFM_STRIKEOUT	The CFE_STRIKEOUT value of the dwEffects member is valid.
CFM_UNDERLINE.	The CFE_UNDERLINE value of the dwEffects member is valid.
dwEffects

Character effects. This member can be a combination of the following values:

Value	Meaning
CFE_AUTOCOLOR	The text color is the return value of GetSysColor (COLOR_WINDOWTEXT).
CFE_BOLD	Characters are bold.
CFE_ITALIC	Characters are italic.
CFE_STRIKEOUT	Characters are struck out.
CFE_UNDERLINE	Characters are underlined.
CFE_PROTECTED	Characters are protected; an attempt to modify them will cause an EN_PROTECTED notification message.
yHeight

Character height.

yOffset

Character offset from the baseline. If this member is positive, the character is a superscript; if it is negative, the character is a subscript.

crTextColor

Text color. This member is ignored if the CFE_AUTOCOLOR character effect is specified.

bCharSet

Character set value. Can be one of the values specified for the lfCharSet member of the LOGFONT structure.

bPitchAndFamily

Font family and pitch. This member is the same as the lfPitchAndFamily member of the LOGFONT structure.

szFaceName

Null-terminated character array specifying the font face name.

Remarks

This structure is used with the EM_GETCHARFORMAT and EM_SETCHARFORMAT messages.

See Also

GetSysColor, EM_GETCHARFORMAT, EM_SETCHARFORMAT, EN_PROTECTED, LOGFONT


CHARRANGE [New - Windows NT]
 CHARRANGE  QuickInfo  Overview  Group

[New - Windows NT]

typedef struct _charrange {

    LONG cpMin;

    LONG cpMax;

} 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.

Members

cpMin

Index of first intercharacter position.

cpMax

Index of last intercharacter position.

EM_EXGETSEL, EM_EXSETSEL


CHARSET
 CHARSET  QuickInfo

typedef struct tagCHARSET { // chst

    DWORD aflBlock[3];

    DWORD flLang;

} CHARSET;

The CHARSET structure specifies the Unicode blocks and the character sets supported by a given font.

Members

aflBlock

Specifies which (if any) of the 96 Unicode blocks are supported by a font. If the font contains at least one character in the given block, the corresponding bit is set.

flLang

Identifies the character set supported by the font. This member can be one of the following values:

Value	Meaning
CS_UGL	Supports the Universal Glyph List (UGL) character set.
CS_LATIN	Supports the Latin character set.
CS_GREEK	Supports the Greek character set.
CS_WIN30	Supports the Windows 3.0 character set.
Bits 0 and 31 of flLang are reserved and must be set to zero.


CHARSETINFO [New - Windows 95]
 CHARSETINFO  QuickInfo  Overview  Group

[New - Windows 95]

typedef struct {
    UINT ciCharset;
    UINT ciACP;
    FONTSIGNATURE fs;
} CHARSETINFO;

The CHARSETINFO structure contains information about a character set.

Members

ciCharset

Character set value.

ciACP

ANSI code-page value.

fs

A FONTSIGNATURE structure that identifies the Unicode and code-page font signature values. Only one Windows code-page will be set when this structure is set by the function.

See Also

FONTSIGNATURE, TranslateCharsetInfo


CHOOSECOLOR
 CHOOSECOLOR  QuickInfo

typedef struct {   // cc

    DWORD        lStructSize;

    HWND         hwndOwner;

    HWND         hInstance;

    COLORREF     rgbResult;

    COLORREF*    lpCustColors;

    DWORD        Flags;

    LPARAM       lCustData;

    LPCCHOOKPROC lpfnHook;

    LPCTSTR      lpTemplateName;

} CHOOSECOLOR;

The CHOOSECOLOR structure contains information the operating system uses to initialize the system-defined Color dialog box. After the user closes the dialog box, the system returns information about the user's selection in this structure.

Members

lStructSize

Specifies the length, in bytes, of the structure.

hwndOwner

Identifies the window that owns the dialog box. This member can be any valid window handle, or it can be NULL if the dialog box has no owner.

hInstance

Identifies a data block that contains the dialog box template specified by the lpTemplateName member. This member is used only if the Flags member specifies the CC_ENABLETEMPLATE flag; otherwise, this member is ignored.

rgbResult

Specifies the color initially selected when the dialog box is created, and contains the user's color selection when the dialog box is closed. When the dialog box is created, the system selects the nearest solid color available if the CC_RGBINIT flag is specified in the Flags member and the value of this member is not among the colors available. If this member is NULL, the color initially selected is black.

lpCustColors

Points to an array of 16 doublewords 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. An application should save these values for future calls to the ChooseColor function.

Flags

Specifies the dialog box initialization flags. This member may be a combination of the following flags:

Flag	Meaning
CC_ENABLEHOOK	Enables the hook function specified in the lpfnHook member.
CC_ENABLETEMPLATE	Causes the system to create the dialog box by using the dialog box template identified by the hInstance and lpTemplateName members.
CC_ENABLETEMPLATEHANDLE	Indicates that the hInstance member identifies a data block containing a pre-loaded dialog box template. The system ignores the lpTemplateName member if this flag is specified.
CC_FULLOPEN	Causes the entire dialog box to appear when the dialog box is created, including the portion that allows the user to create custom colors. If this flag is not specified, the user must choose the Define Custom Color button to see this portion of the dialog box.
CC_PREVENTFULLOPEN	Disables the Define Custom Colors button, preventing the user from creating custom colors.
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 show the Help button. The hwndOwner member must not be NULL if this option is specified.
lCustData

Specifies application-defined data the system passes to the hook function identified by the lpfnHook member. The system passes the data in the lParam parameter of the WM_INITDIALOG message.

lpfnHook

Points to a hook function that processes messages intended for the dialog box. An application must specify the CC_ENABLEHOOK flag in the Flags member to enable the function; otherwise, the system ignores this member. The hook function must return FALSE to pass a message to the standard color dialog box procedure or TRUE to discard the message.

lpstrTemplateName

Points to a null-terminated string that names the dialog box template to be substituted for the standard dialog box template. An application can use the MAKEINTRESOURCE macro for numbered dialog box resources. This member is used only if Flags specifies the CC_ENABLETEMPLATE flag; otherwise, this member is ignored.

See Also

ChooseColor, MAKEINTRESOURCE, WM_INITDIALOG


CHOOSEFONT
 CHOOSEFONT  QuickInfo

typedef struct {    // cf

    DWORD        lStructSize;

    HWND         hwndOwner;

    HDC          hDC;

    LPLOGFONT    lpLogFont;

    INT          iPointSize;

    DWORD        Flags;

    DWORD        rgbColors;

    LPARAM       lCustData;

    LPCFHOOKPROC lpfnHook;

    LPCTSTR      lpTemplateName;

    HINSTANCE    hInstance;

    LPTSTR       lpszStyle;

    WORD         nFontType;

    WORD         ___MISSING_ALIGNMENT__;

    INT          nSizeMin;

    INT          nSizeMax;

} CHOOSEFONT;

The CHOOSEFONT structure contains information the operating system uses to initialize the system-defined Font dialog box. After the user closes the dialog box, the system returns information about the user's selection in this structure.

Members

lStructSize

Specifies the length, in bytes, of the structure.

hwndOwner

Identifies the window that owns the dialog box. This member can be any valid window handle, or it can be NULL if the dialog box has no owner.

hDC

Identifies the device context (or information context) of the printer whose fonts will be listed in the dialog box. This member is used only if the Flags member specifies the CF_PRINTERFONTS flag; otherwise, this member is ignored.

lpLogFont

Points to a LOGFONT structure. If an application initializes the members of this structure before calling the ChooseFont function and also sets the CF_INITTOLOGFONTSTRUCT flag, ChooseFont initializes the dialog box with a font that is the closest possible match. After the user closes the dialog box, ChooseFont sets the members of the LOGFONT structure based on the user's final selection.

iPointSize

Specifies the size of the selected font, in units of 1/10 of a point. ChooseFont sets this value after the user closes the dialog box.

Flags

Specifies the dialog box initialization flags. This member may be a combination of the following flags:

Flag	Meaning
CF_APPLY	Specifies that ChooseFont should enable the Apply button.
CF_ANSIONLY	Windows 95: 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. Windows NT: Specifies that ChooseFont should allow the selection of all fonts that use the Windows and Unicode character sets. The user will not be able to select fonts that use the OEM or Symbol character sets. This flag is equivalent to the Windows 95 CF_SCRIPTSONLY flag.
CF_BOTH	Causes the dialog box to list the available printer and screen fonts. The hDC member identifies the device context (or information context) associated with the printer.
CF_TTONLY	Specifies that ChooseFont should only enumerate and allow the selection of TrueType fonts.
CF_EFFECTS	Specifies that ChooseFont should enable strikeout, underline, and color effects. If this flag is specified, you can set the rgbColors member of this structure and the lfStrikeOut and lfUnderline members of the LOGFONT structure pointed to by lpLogFont. ChooseFont can then use these members after the user closes the dialog box.
CF_ENABLEHOOK	Enables the hook function specified in the lpfnHook member of this structure.
CF_ENABLETEMPLATE	Indicates that the hInstance member identifies a data block that contains a dialog box template identified by the lpTemplateName member.
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	See the CF_NOVECTORFONTS description.
CF_NOFACESEL	Specifies that ChooseFont should not make an initial face name selection, because there is no one single face name that applies to the text selection. Set this flag if the text selection contains multiple face names.
CF_NOSCRIPTSEL	Windows 95 only: Specifies that there is no selection in the character set combo box. Applications use this flag to support multiple character set selections. This flag is set on input only. When it is set, the script combo box is disabled and the lfCharSet member of the LOGFONT structure is set to DEFAULT_CHARSET.
CF_NOSTYLESEL	Specifies that ChooseFont should not make an initial style selection, because there is no one single style that applies to the text selection. Set this flag if the text selection contains multiple styles.
CF_NOSIZESEL	Specifies that ChooseFont should not make an initial size selection, because there is no one single size that applies to the text selection. Set this flag if the text selection contains multiple sizes.
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	Windows 95: 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	Windows 95 only: 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	Windows 95 only: 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 combo box.
CF_SHOWHELP	Causes the dialog box to show the Help button. The hwndOwner member must not be NULL if this option is specified.
CF_USESTYLE	Specifies that lpszStyle member points to a buffer that contains style data that ChooseFont should use to initialize the Font Style selection. 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 specified, this member contains an RGB value that ChooseFont should use to specify the text color. After the user closes the dialog box, this member contains the RGB value of the color the user selected.

lCustData

Specifies application-defined data the application passes to the hook function.

lpfnHook

Points to a hook function that processes messages intended for the dialog box. An application must specify the CF_ENABLEHOOK flag in the Flags member to enable the function; otherwise, the system ignores this member. The hook function must return FALSE to pass a message to the standard dialog box procedure or TRUE to discard the message.

lpTemplateName

Points to a null-terminated string that names the dialog box template to be substituted for the standard dialog box template. An application can use the MAKEINTRESOURCE macro for numbered dialog box resources. This member is used only if Flags specifies the CF_ENABLETEMPLATE flag; otherwise, this member is ignored.

hInstance

Identifies a data block that contains the dialog box template specified by lpstrTemplateName. This member is used only if Flags specifies the CF_ENABLETEMPLATE flag; otherwise, this member is ignored.

lpszStyle

Points to a buffer that contains style data. If the CF_USESTYLE flag is specified, ChooseFont uses the data in this buffer to initialize the style control. When the user closes the dialog box, ChooseFont copies the string in the style control into this buffer.

nFontType

Specifies the type of the selected font. This member may contain one of the following values:

Value	Meaning
BOLD_FONTTYPE	The font weight is bold. This information is duplicated from 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 from 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 from 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.

See Also

ChooseFont, MAKEINTRESOURCE


CIDA
 CIDA  QuickInfo

typedef struct _IDA {

    UINT cidl;        // number array elements

    UINT aoffset[1];  // see below

} CIDA, * LPIDA;

This structure corresponds to the CF_IDLIST clipboard format.

Member

aoffset

Array of offsets relative to the beginning of the CIDA structure. The first element is the offset of the ITEMIDLIST structure for a folder (absolute from the root). Subsequent elements are offsets of ITEMIDLIST structures for file objects (relative from the parent folder).

See Also

ITEMIDLIST


CIEXYZ [New - Windows 95]
 CIEXYZ  QuickInfo  Overview  Group

[New - Windows 95]

typedef struct tagCIEXYZ
{
    FXPT2DOT30 ciexyzX;

    FXPT2DOT30 ciexyzY;

    FXPT2DOT30 ciexyzZ;

} CIEXYZ;
typedef CIEXYZ FAR* LPCIEXYZ;

The CIEXYZ structure contains the x, y, and z coordinates of a specific color in a specified color space.

Members

ciexyzX

x coordinate in fix point (2.30).

ciexyzY

y coordinate in fix point (2.30).

ciexyzZ

z coordinate in fix point (2.30).


CIEXYZTRIPLE [New - Windows 95]
 CIEXYZTRIPLE  QuickInfo  Overview  Group

[New - Windows 95]

typedef struct tagCIEXYZTRIPLE
{
    CIEXYZ  ciexyzRed;

    CIEXYZ  ciexyzGreen;

    CIEXYZ  ciexyzBlue;

} CIEXYZTRIPLE;
typedef CIEXYZTRIPLE FAR* LPCIEXYZTRIPLE;

The CIEXYZTRIPLE structure contains the x, y, and z coordinates of the three colors that correspond to the red, green, and blue endpoints for a specified logical color space.

Members

ciexyzRed;

xyz coordinates of red endpoint.

ciexyzGreen

xyz coordinates of green endpoint.

ciexyzBlue

xyz coordinates of blue endpoint.


CLIENTCREATESTRUCT
 CLIENTCREATESTRUCT  QuickInfo

typedef struct tagCLIENTCREATESTRUCT { // ccs

    HANDLE hWindowMenu;

    UINT   idFirstChild;

} 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.

Members

hWindowMenu

Identifies the handle of 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. Windows 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.

See Also

CreateWindow, GetSubMenu, MDICREATESTRUCT, WM_COMMAND


CMINVOKECOMMANDINFO
 CMINVOKECOMMANDINFO  QuickInfo

typedef struct _CMInvokeCommandInfo {

    DWORD cbSize;        // sizeof(CMINVOKECOMMANDINFO)

    DWORD fMask;

    HWND hwnd;

    LPCSTR lpVerb;

    LPCSTR lpParameters;

    LPCSTR lpDirectory;

    int nShow;

    DWORD dwHotKey;

    HANDLE hIcon;

} CMINVOKECOMMANDINFO, *LPCMINVOKECOMMANDINFO;

Contains information about a context menu command.

Members

fMask

Value specifying zero or more of the following flags:

CMIC_MASK_HOTKEY	Specifies that the dwHotKey member is valid.
CMIC_MASK_ICON	Specifies that the hIcon member is valid.
CMIC_MASK_FLAG_NO_UI	Prevents the system from displaying user interface elements (for example, error messages) while carrying out a command.
hwnd

Handle of the window that owned the context menu, such as the desktop, the explorer, or the tray. An extension might specify this handle as the owner window of any message boxes or dialog boxes it displays.

lpVerb

32-bit value containing zero in the high-order word and the menu-identifier offset of the command to carry out in the low-order word. The shell specifies this value (using the MAKEINTRESOURCE macro) when the user chooses a menu command.

If the high-order word is not zero, this member is the address of a null-terminated string specifying the language-independent name of the command to carry out. This member is typically a string when a command is being activated by an application. The system provides predefined constant values for the following command strings:

Value	String
CMDSTR_NEWFOLDER	"NewFolder"
CMDSTR_VIEWDETAIL	"ViewDetails"
CMDSTR_VIEWLIST	"ViewList"
lpParameters

Optional parameters. This member is always NULL for menu items inserted by a shell extension.

lpDirectory

Optional working directory name. This member is always NULL for menu items inserted by a shell extension.

nShow

Flag to pass to the ShowWindow function if the command displays a window or starts an application.

dwHotKey

Optional hot key to assign any application activated by the command. If fMask does not specify CMIC_MASK_HOTKEY, this member is ignored.

hIcon

Icon to use for any application activated by the command. If the fMask member does not specify CMIC_MASK_ICON, this member is ignored.

Remarks

The address of this structure is passed to the IContextMenu::InvokeCommand method.

See Also

IContextMenu::InvokeCommand, MAKEINTRESOURCE, ShowWindow


COLORADJUSTMENT
 COLORADJUSTMENT  QuickInfo

typedef struct  tagCOLORADJUSTMENT {    // ca

    WORD  caSize;

    WORD  caFlags;

    WORD  caIlluminantIndex;

    WORD  caRedGamma;

    WORD  caGreenGamma;

    WORD  caBlueGamma;

    WORD  caReferenceBlack;

    WORD  caReferenceWhite;

    SHORT caContrast;

    SHORT caBrightness;

    SHORT caColorfulness;

    SHORT caRedGreenTint;

} COLORADJUSTMENT;

The COLORADJUSTMENT structure defines the color adjustment values used by the StretchBlt and StretchDIBits functions when the stretch mode is HALFTONE.

Members

caSize

Specifies the size, in bytes, of the structure.

caFlags

Specifies how the output image should be prepared. This member may be set to NULL or any combination of the following values:

Value	Meaning
CA_NEGATIVE	Specifies that the negative of the original image should be displayed.
CA_LOG_FILTER	Specifies that a logarithmic function should be applied to the final density of the output colors. This will increase the color contrast when the luminance is low.
caIlluminantIndex

Specifies the type of standard light source under which the image is viewed. This member may be set to one of the following values:

Value	Meaning
ILLUMINANT_DEVICE_DEFAULT	Device's default. Standard used by output devices.
ILLUMINANT_A	Tungsten lamp.
ILLUMINANT_B	Noon sunlight.
ILLUMINANT_C	NTSC daylight.
ILLUMINANT_D50	Normal print.
ILLUMINANT_D55	Bond paper print.
ILLUMINANT_D65	Standard daylight. Standard for CRTs and pictures.
ILLUMINANT_D75	Northern daylight.
ILLUMINANT_F2	Cool white lamp
ILLUMINANT_TUNGSTEN	Same as ILLUMINANT_A.
ILLUMINANT_DAYLIGHT	Same as ILLUMINANT_C.
ILLUMINANT_FLUORESCENT	Same as ILLUMINANT_F2.
ILLUMINANT_NTSC	Same as ILLUMINANT_C.
caRedGamma

Specifies the nth power gamma-correction value for the red primary of the source colors. The value must be in the range from 2500 to 65,000. A value of 10,000 means no gamma-correction.

caGreenGamma

Specifies the nth power gamma-correction value for the green primary of the source colors. The value must be in the range from 2500 to 65,000. A value of 10,000 means no gamma-correction.

caBlueGamma

Specifies the nth power gamma-correction value for the blue primary of the source colors. The value must be in the range from 2500 to 65,000. A value of 10,000 means no gamma-correction.

caReferenceBlack

Specifies the black reference for the source colors. Any colors that are darker than this are treated as black. The value must be in the range from 0 to 4000.

caReferenceWhite

Specifies the white reference for the source colors. Any colors that are lighter than this are treated as white. The value must be in the range from 6000 to 10,000.

caContrast

Specifies the amount of contrast to be applied to the source object. The value must be in the range from  − 100 to 100. A value of 0 means no contrast adjustment.

caBrightness

Specifies the amount of brightness to be applied to the source object. The value must be in the range from  − 100 to 100. A value of 0 means no brightness adjustment.

caColorfulness

Specifies the amount of colorfulness to be applied to the source object. The value must be in the range from  − 100 to 100. A value of 0 means no colorfulness adjustment.

caRedGreenTint

Specifies the amount of red or green tint adjustment to be applied to the source object. The value must be in the range from  − 100 to 100. Positive numbers adjust towards red and negative numbers adjust towards green. Zero means no tint adjustment.

See Also

SetStretchBltMode, StretchBlt, StretchDIBits


COLORMAP [New - Windows NT]
 COLORMAP  QuickInfo  Overview  Group

[New - Windows NT]

typedef struct _COLORMAP {

    COLORREF from;

    COLORREF to;

} COLORMAP, FAR* LPCOLORMAP;

The COLORMAP structure contains information used by the CreateMappedBitmap function to map the colors of the bitmap.

Members

from

Color to map from.

to

Color to map to.

See Also

CreateMappedBitmap


COLORREF
 COLORREF  QuickInfo

The COLORREF value is a 32-bit value used to specify an RGB color.

Remarks

When specifying an explicit RGB color, the COLORREF value has 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. The maximum value for a single byte is 0xFF.

See Also

GetBValue, GetGValue, GetRValue, RGB


COMMCONFIG [New - Windows 95]
 COMMCONFIG  QuickInfo

[New - Windows 95]

typedef struct _COMM_CONFIG {
    DWORD dwSize;
    WORD  wVersion;

    WORD  wReserved;
    DCB   dcb;
    DWORD dwProviderSubType;
    DWORD dwProviderOffset;
    DWORD dwProviderSize;
    WCHAR wcProviderData[1];
} COMMCONFIG, *LPCOMMCONFIG;

The COMMCONFIG structure contains information about the configuration state of a communications device.

Members

dwSize

Specifies the size, in bytes, of the COMMCONFIG structure.

wVersion

Specifies the version number of the COMMCONFIG structure. For
Windows 95 device drivers, this parameter can be 1. The version of the provider-specific structure should be included in the wcProviderData member.

wReserved

Reserved; do not use.

dcb

Specifies a device-control block (DCB) structure for RS-232 serial devices. A DCB structure is always present regardless of the port driver subtype specified in the device's COMMPROP structure.

dwProviderSubType

Identifies the type of communications provider, and thus the format of the provider-specific data. For a list of communications provider types, see the description of the COMMPROP structure.

dwProviderOffset

Specifies the offset, in bytes, of the provider-specific data relative to the beginning of the structure. This member is zero if there is no provider-specific data.

dwProviderSize

Specifies the size, in bytes, of the provider-specific data.

wcProviderData

Contains the provider-specific data, if any. This member may be of any size or may be omitted. Because the COMMCONFIG structure may be expanded in the future, applications should use the dwProviderOffset member to determine the location of this member.

Remarks

If the provider subtype is PST_RS232 or PST_PARALLELPORT the wcProviderData member is omitted. If the provider subtype is PST_MODEM, the wcProviderData member contains a MODEMSETTINGS structure.

See Also

DCB, COMMPROP, GetCommProperties, MODEMSETTINGS


COMMPROP
 COMMPROP  QuickInfo

typedef struct _COMMPROP { // cmmp

    WORD  wPacketLength;       // packet size, in bytes

    WORD  wPacketVersion;      // packet version

    DWORD dwServiceMask;       // services implemented

    DWORD dwReserved1;         // reserved

    DWORD dwMaxTxQueue;        // max Tx bufsize, in bytes

    DWORD dwMaxRxQueue;        // max Rx bufsize, in bytes

    DWORD dwMaxBaud;           // max baud rate, in bps

    DWORD dwProvSubType;       // specific provider type

    DWORD dwProvCapabilities;  // capabilities supported

    DWORD dwSettableParams;    // changable parameters

    DWORD dwSettableBaud;      // allowable baud rates

    WORD  wSettableData;       // allowable byte sizes

    WORD  wSettableStopParity; // stop bits/parity allowed

    DWORD dwCurrentTxQueue;    // Tx buffer size, in bytes

    DWORD dwCurrentRxQueue;    // Rx buffer size, in bytes

    DWORD dwProvSpec1;         // provider-specific data

    DWORD dwProvSpec2;         // provider-specific data

    WCHAR wcProvChar[1];       // provider-specific data

} COMMPROP;

The COMMPROP structure is used by the GetCommProperties function to return information about a given communications driver.

Members

wPacketLength

Specifies the size, in bytes, of the entire data packet, regardless of the amount of data requested.

wPacketVersion

Specifies the version of the structure.

dwServiceMask

Specifies a bitmask indicating which services are implemented by this provider. The SP_SERIALCOMM value is always specified for communications providers, including modem providers.

dwReserved1

Reserved; do not use.

dwMaxTxQueue

Specifies the maximum size, in bytes, of the driver's internal output buffer. A value of zero indicates that no maximum value is imposed by the serial provider.

dwMaxRxQueue

Specifies the maximum size, in bytes, of the driver's internal input buffer. A value of zero indicates that no maximum value is imposed by the serial provider.

dwMaxBaud

Specifies the maximum allowable baud rate, in bits per second (bps). This member can be one of the following values:

Value	Meaning
BAUD_075	75 bps
BAUD_110	110 bps
BAUD_134_5	134.5 bps
BAUD_150	150 bps
BAUD_300	300 bps
BAUD_600	600 bps
BAUD_1200	1200 bps
BAUD_1800	1800 bps
BAUD_2400	2400 bps
BAUD_4800	4800 bps
BAUD_7200	7200 bps
BAUD_9600	9600 bps
BAUD_14400	14400 bps
BAUD_19200	19200 bps
BAUD_38400	38400 bps
BAUD_56K	56K bps
BAUD_57600	57600 bps
BAUD_115200	115200 bps
BAUD_128K	128K bps
BAUD_USER	Programmable baud rates available
dwProvSubType

Specifies the specific communications provider type:

Value	Meaning
PST_FAX	FAX device
PST_LAT	LAT protocol
PST_MODEM	Modem device
PST_NETWORK_BRIDGE	Unspecified network bridge
PST_PARALLELPORT	Parallel port
PST_RS232	RS-232 serial port
PST_RS422	RS-422 port
PST_RS423	RS-423 port
PST_RS449	RS-449 port
PST_SCANNER	Scanner device
PST_TCPIP_TELNET	TCP/IP Telnet® protocol
PST_UNSPECIFIED	Unspecified
PST_X25	X.25 standards
dwProvCapabilities

Specifies a bitmask indicating the capabilities offered by the provider. This member can be one of the following values:

Value	Meaning
PCF_16BITMODE	Special 16-bit mode supported
PCF_DTRDSR	DTR (data-terminal-ready)/DSR (data-set-ready) supported
PCF_INTTIMEOUTS	Interval time-outs supported
PCF_PARITY_CHECK	Parity checking supported
PCF_RLSD	RLSD (receive-line-signal-detect) supported
PCF_RTSCTS	RTS (request-to-send)/CTS (clear-to-send) supported
PCF_SETXCHAR	Settable XON/XOFF supported
PCF_SPECIALCHARS	Special character support provided
PCF_TOTALTIMEOUTS	Total (elapsed) time-outs supported
PCF_XONXOFF	XON/XOFF flow control supported
dwSettableParams

Specifies a bitmask indicating the communications parameter that can be changed. This member can be one of the following values:

Value	Meaning
SP_BAUD	Baud rate
SP_DATABITS	Data bits
SP_HANDSHAKING	Handshaking (flow control)
SP_PARITY	Parity
SP_PARITY_CHECK	Parity checking
SP_RLSD	RLSD (receive-line-signal-detect)
SP_STOPBITS	Stop bits
dwSettableBaud

Specifies a bitmask indicating the baud rates that can be used. For values, see the dwMaxBaud member.

wSettableData

Specifies a bitmask indicating the number of data bits that can be set. This member can be one of the following values:

Value	Meaning
DATABITS_5	5 data bits
DATABITS_6	6 data bits
DATABITS_7	7 data bits
DATABITS_8	8 data bits
DATABITS_16	16 data bits
DATABITS_16X	Special wide path through serial hardware lines
wSettableStopParity

Specifies a bitmask indicating the stop bit and parity settings that can be selected. This member can be one of the following values:

Value	Meaning
STOPBITS_10	1 stop bit
STOPBITS_15	1.5 stop bits
STOPBITS_20	2 stop bits
PARITY_NONE	No parity
PARITY_ODD	Odd parity
PARITY_EVEN	Even parity
PARITY_MARK	Mark parity
PARITY_SPACE	Space parity
dwCurrentTxQueue

Specifies the size, in bytes, of the driver's internal output buffer. A value of zero indicates that the value is unavailable.

dwCurrentRxQueue

Specifies the size, in bytes, of the driver's internal input buffer. A value of zero indicates that the value is unavailable.

dwProvSpec1

Specifies provider-specific data. Applications should ignore this member unless they have detailed information about the format of the data required by the provider.

Windows 95 only: Set this member to COMMPROP_INITIALIZED before calling the GetCommProperties function to indicate that the wPacketLength member is already valid.

dwProvSpec2

Specifies provider-specific data. Applications should ignore this member unless they have detailed information about the format of the data required by the provider.

wcProvChar

Specifies provider-specific data. Applications should ignore this member unless they have detailed information about the format of the data required by the provider.

Remarks

The contents of the dwProvSpec1, dwProvSpec2, and wcProvChar members depend on the provider subtype (specified by the dwProvSubType member).

Windows 95 only:

If the provider subtype is PST_MODEM, these members are used as follows:

Value	Meaning
dwProvSpec1	Not used.
dwProvSpec2	Not used.
wcProvChar	Contains a MODEMDEVCAPS structure.
See Also

GetCommProperties


COMMTIMEOUTS
 COMMTIMEOUTS  QuickInfo

typedef struct _COMMTIMEOUTS {   // ctmo

    DWORD ReadIntervalTimeout;

    DWORD ReadTotalTimeoutMultiplier;

    DWORD ReadTotalTimeoutConstant;

    DWORD WriteTotalTimeoutMultiplier;

    DWORD WriteTotalTimeoutConstant;

} COMMTIMEOUTS,*LPCOMMTIMEOUTS;

The COMMTIMEOUTS structure is used in the SetCommTimeouts and GetCommTimeouts functions to set and query the time-out parameters for a communications device. The parameters determine the behavior of ReadFile, WriteFile, ReadFileEx, and WriteFileEx operations on the device.

Members

ReadIntervalTimeout

Specifies the maximum time, in milliseconds, allowed to elapse between the arrival of two characters on the communications line. During a ReadFile operation, the time period begins when the first character is received. If the interval between the arrival of any two characters exceeds this amount, the ReadFile operation is completed and any buffered data is returned. A value of zero indicates that interval time-outs are not used.

A value of MAXDWORD, combined with zero values for both the ReadTotalTimeoutConstant and ReadTotalTimeoutMultiplier members, specifies that the read operation is to return immediately with the characters that have already been received, even if no characters have been received.

ReadTotalTimeoutMultiplier

Specifies the multiplier, in milliseconds, used to calculate the total time-out period for read operations. For each read operation, this value is multiplied by the requested number of bytes to be read.

ReadTotalTimeoutConstant

Specifies the constant, in milliseconds, used to calculate the total time-out period for read operations. For each read operation, this value is added to the product of the ReadTotalTimeoutMultiplier member and the requested number of bytes.

A value of zero for both the ReadTotalTimeoutMultiplier and ReadTotalTimeoutConstant members indicates that total time-outs are not used for read operations.

WriteTotalTimeoutMultiplier

Specifies the multiplier, in milliseconds, used to calculate the total time-out period for write operations. For each write operation, this value is multiplied by the number of bytes to be written.

WriteTotalTimeoutConstant

Specifies the constant, in milliseconds, used to calculate the total time-out period for write operations. For each write operation, this value is added to the product of the WriteTotalTimeoutMultiplier member and the number of bytes to be written.

A value of zero for both the WriteTotalTimeoutMultiplier and WriteTotalTimeoutConstant members indicates that total time-outs are not used for write operations.

Remarks

Windows 95: If an application sets the ReadIntervalTimeout and readTotalTimeoutMultiplier members to MAXDWORD and the ReadTotalTimeoutConstant member to a value greater than zero and less than MAXDWORD, one of the following occurs when the readFile function is called:Selecting a button typically causes the following events:

•	If there are any characters in the input buffer, ReadFile returns immediately with the characters in the buffer.

•	If there are no characters in the input buffer, ReadFile waits until a character arrives and then returns immediately.

•	If no character arrives within the time specified by the ReadTotalTimeoutConstant member, ReadFile times out.

See Also

GetCommTimeouts, ReadFile, ReadFileEx, SetCommTimeouts, WriteFile, WriteFileEx


COMPAREITEMSTRUCT
 COMPAREITEMSTRUCT  QuickInfo

typedef struct tagCOMPAREITEMSTRUCT { // cis

    UINT  CtlType;

    UINT  CtlID;

    HWND  hwndItem;

    UINT  itemID1;

    DWORD itemData1;

    UINT  itemID2;

    DWORD itemData2;

} 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, Windows 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.

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

Identifies the control.

itemID1

Specifies the index of the first item in the list box or combo box being compared.

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.

See Also

WM_COMPAREITEM


COMPCOLOR
 COMPCOLOR  QuickInfo  Overview  Group

typedef struct {
    COLORREF crText;
    COLORREF crBackground;
    DWORD dwEffects;
} COMPCOLOR;

Contains color settings for the composition string.

Members

crText

Color of text.

crBackground

Color of background.

dwEffects

Character effect values as described for the dwEffects member in the CHARFORMAT structure.

See Also

CHARFORMAT


COMPOSITIONFORM [New - Windows 95]
 COMPOSITIONFORM  QuickInfo  Overview  Group

[New - Windows 95]

typedef _tagCOMPOSITIONFORM {
    DWORD  dwStyle;
    POINT  ptCurrentPos;
    RECT   rcArea;
} COMPOSITIONFORM;

The COMPOSITIONFORM structure contains position information for the composition window.

Members

dwStyle

Position style. This member can be one of the following values:

Value	Meaning
CFS_DEFAULT	Move the composition window to the default position. The IME window can display the composition window outside the client area, such as in a floating window.
CFS_FORCE_POSITION	Display the upper-left corner of the composition window at exactly the position given by ptCurrentPos. The coordinates are relative to the upper-left corner of the window containing the composition window and are not subject to adjustment by the IME.
CFS_POINT	Display the upper-left corner of the composition window at the position given by ptCurrentPos. The coordinates are relative to the upper-left corner of the window containing the composition window and are subject to adjustment by the IME.
CFS_RECT	Display the composition window at the position given by rcArea. The coordinates are relative to the upper-left of the window containing the composition window.
ptCurrentPos

Coordinates of the upper-left corner of the composition window.

rcArea

Coordinates of the upper-left and lower-right corners of the composition window.

Remarks

Some IME windows adjust the composition window position specified by the system or the application. The CFS_FORCE_POSITION directs the IME window to skip this adjustment.


COMSTAT
 COMSTAT  QuickInfo

typedef struct _COMSTAT { // cst

    DWORD fCtsHold : 1;   // Tx waiting for CTS signal

    DWORD fDsrHold : 1;   // Tx waiting for DSR signal

    DWORD fRlsdHold : 1;  // Tx waiting for RLSD signal

    DWORD fXoffHold : 1;  // Tx waiting, XOFF char rec'd

    DWORD fXoffSent : 1;  // Tx waiting, XOFF char sent

    DWORD fEof : 1;       // EOF character sent

    DWORD fTxim : 1;      // character waiting for Tx

    DWORD fReserved : 25; // reserved

    DWORD cbInQue;        // bytes in input buffer

    DWORD cbOutQue;       // bytes in output buffer

} COMSTAT, *LPCOMSTAT;

The COMSTAT structure contains information about a communications device. This structure is filled by the ClearCommError function.

Members

fCtsHold

Specifies whether transmission is waiting for the CTS (clear-to-send) signal to be sent. If this member is TRUE, transmission is waiting.

fDsrHold

Specifies whether transmission is waiting for the DSR (data-set-ready) signal to be sent. If this member is TRUE, transmission is waiting.

fRlsdHold

Specifies whether transmission is waiting for the RLSD (receive-line-signal-detect) signal to be sent. If this member is TRUE, transmission is waiting.

fXoffHold

Specifies whether transmission is waiting because the XOFF character was received. If this member is TRUE, transmission is waiting.

fXoffSent

Specifies whether transmission is waiting because the XOFF character was transmitted. If this member is TRUE, transmission is waiting. Transmission halts when the XOFF character is transmitted to a system that takes the next character as XON, regardless of the actual character.

fEof

Specifies whether the end-of-file (EOF) character has been received. If this member is TRUE, the EOF character has been received.

fTxim

If this member is TRUE, there is a character queued for transmission that has come to the communications device by way of the TransmitCommChar function. The communications device transmits such a character ahead of other characters in the device's output buffer.

fReserved

Reserved; do not use.

cbInQue

Specifies the number of bytes received by the serial provider but not yet read by a ReadFile operation.

cbOutQue

Specifies the number of bytes of user data remaining to be transmitted for all write operations. This value will be zero for a nonoverlapped write.

See Also

ClearCommError, ReadFile, TransmitCommChar


CONSOLE_CURSOR_INFO
 CONSOLE_CURSOR_INFO  QuickInfo  Overview  Group

typedef struct _CONSOLE_CURSOR_INFO { // cci

    DWORD  dwSize;

    BOOL   bVisible;

} CONSOLE_CURSOR_INFO, *PCONSOLE_CURSOR_INFO;

The CONSOLE_CURSOR_INFO structure contains information about the console cursor.

Members

dwSize

Specifies a number between 1 and 100, indicating the percentage of the character cell that is filled by the cursor. The cursor appearance varies, ranging from completely filling the cell to showing up as a horizontal line at the bottom of the cell.

bVisible

Specifies the visibility of the cursor. If the cursor is visible, this member is TRUE.

See Also

GetConsoleCursorInfo, SetConsoleCursorInfo


CONSOLE_SCREEN_BUFFER_INFO
 CONSOLE_SCREEN_BUFFER_INFO  QuickInfo  Overview  Group

typedef struct _CONSOLE_SCREEN_BUFFER_INFO { // csbi

    COORD      dwSize;

    COORD      dwCursorPosition;

    WORD       wAttributes;

    SMALL_RECT srWindow;

    COORD      dwMaximumWindowSize;

} CONSOLE_SCREEN_BUFFER_INFO ;

The CONSOLE_SCREEN_BUFFER_INFO structure contains information about a console screen buffer.

Members

dwSize

Specifies the size, in character columns and rows, of the screen buffer.

dwCursorPosition

Specifies the column and row coordinates of the cursor in the screen buffer.

wAttributes

Specifies the foreground (text) and background color attributes to be used for characters that are written to a screen buffer by the WriteFile and WriteConsole functions, or echoed to a screen buffer by the ReadFile and ReadConsole functions. The attribute values are some combination of the following values: FOREGROUND_BLUE, FOREGROUND_GREEN, FOREGROUND_RED, FOREGROUND_INTENSITY, BACKGROUND_BLUE, BACKGROUND_GREEN, BACKGROUND_RED, and BACKGROUND_INTENSITY. For example, the following combination of values produces red text on a white background:

FOREGROUND_RED | BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE

srWindow

Specifies a SMALL_RECT structure that contains the screen buffer coordinates of the upper-left and lower-right corners of the display window.

dwMaximumWindowSize

Specifies the maximum size of the console window, given the current screen buffer size and font and the screen size.

See Also

GetConsoleScreenBufferInfo, ReadConsole, ReadFile, SMALL_RECT, WriteConsole, WriteFile


CONTEXT
 CONTEXT  QuickInfo

A CONTEXT structure contains processor-specific register data. The Windows NT operating system uses CONTEXT structures to perform various internal operations. Currently, there are CONTEXT structures defined for Intel®, MIPS®,  Alpha®, and PowerPC®,processors. Refer to the header file WinNT.h for definitions of these structures.


CONVCONTEXT
 CONVCONTEXT  QuickInfo

typedef struct tagCONVCONTEXT {   // cc

    UINT  cb;

    UINT  wFlags;

    UINT  wCountryID;

    int   iCodePage;

    DWORD dwLangID;

    DWORD dwSecurity;

    SECURITY_QUALITY_OF_SERVICE qos;  // client side's quality of service

} CONVCONTEXT;

The CONVCONTEXT structure contains information supplied by a DDE client application. The information is useful for specialized or cross-language DDE conversations.

Members

cb

Specifies the structure's size, in bytes.

wFlags

Specifies conversation context flags. Currently, no flags are defined for this member.

wCountryID

Specifies the country-code identifier for topic-name and item-name strings.

iCodePage

Specifies the code page for topic-name and item-name strings. Non-multilingual clients should set this member to CP_WINANSI. Unicode clients should set this value to CP_WINUNICODE.

dwLangID

Specifies the language identifier for topic-name and item-name strings.

dwSecurity

Specifies a private (application-defined) security code.

qos

Specifies the quality of service a DDE client wants from the system during a given conversation. The quality of service level specified lasts for the duration of the conversation. It cannot be changed once the conversation is started.


CONVINFO
 CONVINFO  QuickInfo

typedef struct tagCONVINFO {  // ci

    DWORD       cb;

    DWORD       hUser;

    HCONV       hConvPartner;

    HSZ         hszSvcPartner;

    HSZ         hszServiceReq;

    HSZ         hszTopic;

    HSZ         hszItem;

    UINT        wFmt;

    UINT        wType;

    UINT        wStatus;

    UINT        wConvst;

    UINT        wLastError;

    HCONVLIST   hConvList;

    CONVCONTEXT ConvCtxt;

    HWND        hwnd;

    HWND        hwndPartner;

} CONVINFO;

The CONVINFO structure contains information about a DDE conversation.

Members

cb

Specifies the structure's size, in bytes.

hUser

Identifies application-defined data.

hConvPartner

Identifies the partner application in the DDE conversation. This member is zero if the partner has not registered itself (using the DdeInitialize function) to make DDE Management Library (DDEML) function calls. An application should not pass this member to any DDEML function except DdeQueryConvInfo.

hszSvcPartner

Identifies the service name of the partner application.

hszServiceReq

Identifies the service name of the server application that was requested for connection.

hszTopic

Identifies the name of the requested topic.

hszItem

Identifies the name of the requested item. This member is transaction specific.

wFmt

Specifies the format of the data being exchanged. This member is transaction specific.

wType

Specifies the type of the current transaction. This member is transaction specific; it can be one of the following values:

Value	Meaning
XTYP_ADVDATA	Informs a client that advise data from a server has arrived.
XTYP_ADVREQ	Requests a server to send updated data to the client during an advise loop. This transaction results when the server calls DdePostAdvise.
XTYP_ADVSTART	Requests a server to begin an advise loop with a client.
XTYP_ADVSTOP	Notifies a server that an advise loop is stopping.
XTYP_CONNECT	Requests a server to establish a conversation with a client.
XTYP_CONNECT_CONFIRM	Notifies a server that a conversation with a client has been established.
XTYP_DISCONNECT	Notifies a server that a conversation has terminated.
XTYP_EXECUTE	Requests a server to execute a command sent by a client.
XTYP_MONITOR	Notifies an application registered as APPCMD_MONITOR that DDE data is being transmitted.
XTYP_POKE	Requests a server to accept unsolicited data from a client.
XTYP_REGISTER	Notifies other DDEML applications that a server has registered a service name.
XTYP_REQUEST	Requests a server to send data to a client.
XTYP_UNREGISTER	Notifies other DDEML applications that a server has unregistered a service name.
XTYP_WILDCONNECT	Requests a server to establish multiple conversations with the same client.
XTYP_XACT_COMPLETE	Notifies a client that an asynchronous data transaction has been completed.
wStatus

Specifies the status of the current conversation. This member can be a combination of the following values:

Value	Meaning
ST_ADVISE	One or more links are in progress.
ST_BLOCKED	The conversation is blocked.
ST_BLOCKNEXT	The conversation will block after calling the next callback.
ST_CLIENT	The conversation handle passed to the DdeQueryConvInfo function is a client-side handle. If the handle is zero, the conversation handle passed to the DdeQueryConvInfo function is a server-side handle.
ST_CONNECTED	The conversation is connected.
ST_INLIST	The conversation is a member of a conversation list.
ST_ISLOCAL	Both sides of the conversation are using the DDEML.
ST_ISSELF	Both sides of the conversation are using the same instance of the DDEML.
ST_TERMINATED	The conversation has been terminated by the partner.
wConvst

Specifies the conversation state. This member can be one of the following values:

Value	Meaning
XST_ADVACKRCVD	The advise transaction has just been completed.
XST_ADVDATAACKRCVD	The advise data transaction has just been completed.
XST_ADVDATASENT	Advise data has been sent and is awaiting an acknowledgement.
XST_ADVSENT	An advise transaction is awaiting an acknowledgement.
XST_CONNECTED	The conversation has no active transactions.
XST_DATARCVD	The requested data has just been received.
XST_EXECACKRCVD	An execute transaction has just been completed.
XST_EXECSENT	An execute transaction is awaiting an acknowledgement.
XST_INCOMPLETE	The last transaction failed.
XST_INIT1	Mid-initiate state 1.
XST_INIT2	Mid-initiate state 2.
XST_NULL	Pre-initiate state.
XST_POKEACKRCVD	A poke transaction has just been completed.
XST_POKESENT	A poke transaction is awaiting an acknowledgement.
XST_REQSENT	A request transaction is awaiting an acknowledgement.
XST_UNADVACKRCVD	An unadvise transaction has just been completed.
XST_UNADVSENT	An unadvise transaction is awaiting an acknowledgement.
wLastError

Specifies the error value associated with the last transaction.

hConvList

Identifies the conversation list if the handle of the current conversation is in a conversation list. This member is NULL if the conversation is not in a conversation list.

ConvCtxt

Specifies the conversation context.

hwnd

Identifies the window of the calling application involved in the conversation.

hwndPartner

Identifies the window of the partner application involved in the current conversation.

See Also

CONVCONTEXT, DdeInitialize, DdePostAdvise, DdeQueryConvInfo


COORD
 COORD  QuickInfo

typedef struct _COORD { // coord.

    SHORT X;      // horizontal coordinate

    SHORT Y;      // vertical coordinate

} COORD;

The COORD structure defines the coordinates of a character cell in a console screen buffer. The origin of the coordinate system (0,0) is at the top, left cell of the buffer.

Members

X

Horizontal or column value.

Y

Vertical or row value.


COPYDATASTRUCT
 COPYDATASTRUCT  QuickInfo

typedef struct tagCOPYDATASTRUCT {  // cds

    DWORD dwData;

    DWORD cbData;

    PVOID lpData;

} COPYDATASTRUCT;

The COPYDATASTRUCT structure contains data to be passed to another application by the WM_COPYDATA message.

Members

dwData

Specifies up to 32 bits of data to be passed to the receiving application.

cbData

Specifies the size, in bytes, of the data pointed to by the lpData member.

lpData

Points to data to be passed to the receiving application. This member can be NULL.

See Also

WM_COPYDATA


CPINFO
 CPINFO  QuickInfo

struct _cpinfo {

    UINT MaxCharSize;

    BYTE DefaultChar[MAX_DEFAULTCHAR];

    BYTE LeadByte[MAX_LEADBYTES];

} CPINFO;

The CPINFO structure contains information about a code page.

Members

MaxCharSize

Specifies the maximum length, in bytes, of a character in this code page.

DefaultChar

Specifies the default character used in translations into this code page. This character is used by the WideCharToMultiByte function if an explicit default character is not given.

LeadByte

Specifies a fixed-length array of lead-byte ranges, where the number of lead-byte ranges is variable. If there are no lead bytes in this code page, then every element of the array is NULL. If there are lead bytes in this code page, a starting value and ending value is given for each range. Ranges are inclusive. The maximum number of lead-byte ranges for any code page is 5. The array uses two bytes to describe each range, with a double-byte null terminator after the last range.

Remarks

Lead bytes are unique to double-byte character sets (DBCS). A lead byte is the first byte of a 2-byte character in a DBCS. Lead bytes occupy a specific range of byte values.

See Also

GetCPInfo, WideCharToMultiByte


CPLINFO
 CPLINFO  QuickInfo

typedef struct tagCPLINFO { // cpli

    int  idIcon;

    int  idName;

    int  idInfo;

    LONG lData;

} CPLINFO;

The CPLINFO structure contains resource information and a user-defined value for a dialog box supported by a Control Panel application.

Members

idIcon

Specifies the resource identifier of the icon that represents the dialog box.

idName

Specifies the resource identifier of the string containing the short name for the dialog box. This name is intended to be displayed below the icon.

idInfo

Specifies the resource identifier of the string containing the description for the dialog box. The description is the descriptive string that is intended to be displayed when the application icon is selected.

lData

Specifies user-defined data for the dialog box.

See Also

CPL_NEWINQUIRE, NEWCPLINFO


CREATE_PROCESS_DEBUG_INFO
 CREATE_PROCESS_DEBUG_INFO  QuickInfo

typedef struct _CREATE_PROCESS_DEBUG_INFO { // cpdi

    HANDLE hFile;

    HANDLE hProcess;

    HANDLE hThread;

    LPVOID lpBaseOfImage;

    DWORD dwDebugInfoFileOffset;

    DWORD nDebugInfoSize;

    LPVOID lpThreadLocalBase;

    LPTHREAD_START_ROUTINE lpStartAddress;

    LPVOID lpImageName;

    WORD fUnicode;

} CREATE_PROCESS_DEBUG_INFO;

The CREATE_PROCESS_DEBUG_INFO structure contains process creation information that can be used by a debugger.

Members

hFile

Identifies an open handle of the process's image file. If this member is NULL, the handle is not valid. Otherwise, the debugger can use the member to read from and write to the image file.

hProcess

Identifies an open handle of the process. If this member is NULL, the handle is not valid. Otherwise, the debugger can use the member to read from and write to the process's memory.

hThread

Identifies an open handle of the initial thread of the process identified by the hProcess member. If hThread is NULL, the handle is not valid. Otherwise, the debugger has THREAD_GET_CONTEXT, THREAD_SET_CONTEXT, and THREAD_SUSPEND_RESUME access to the thread, allowing the debugger to read from and write to the registers of the thread and to control execution of the thread.

lpBaseOfImage

Points to the base address of the executable image that the process is running.

dwDebugInfoFileOffset

Specifies the offset to the debugging information in the file identified by the hFile member. The kernel expects the debugging information to be in Microsoft® CodeView® version 4.0 format. This format is currently a derivative of COFF (Common Object File Format).

nDebugInfoSize

Specifies the size, in bytes, of the debugging information in the file. If this value is zero, there is no debugging information.

lpThreadLocalBase

Points to a block of data. At offset 0x2C into this block is another pointer, called ThreadLocalStoragePointer, that points to an array of per-module thread local storage blocks. This gives a debugger access to per-thread data in the threads of the process being debugged using the same algorithms that a compiler would use.

lpStartAddress

Points to the starting address of the thread. This value may only be an approximation of the thread's starting address, because any application with appropriate access to the thread can change the thread's context by using the SetThreadContext function.

lpImageName

Points to the filename associated with the hFile parameter. This parameter may be NULL, or it may contain the address of a string pointer in the address space of the process being debugged. That address may, in turn, either be NULL or point to the actual filename. If fUnicode is a nonzero value, the name string is Unicode; otherwise, it is ANSI.

This member is strictly optional. Debuggers must be prepared to handle the case where lpImageName is NULL or *lpImageName (in the address space of the process being debugged) is NULL. Specifically, Windows does not provide an image name for a create process event, and will not likely pass an image name for the first DLL event. Windows also does not provide this information in the case of debug events that originate from a call to the DebugActiveProcess function.

fUnicode

Indicates whether a file name specified by the lpImageName member is Unicode or ANSI. A nonzero value indicates Unicode; zero indicates ANSI.

See Also

CREATE_THREAD_DEBUG_INFO, DebugActiveProcess, DEBUG_EVENT, LOAD_DLL_DEBUG_INFO, SetThreadContext


CREATE_THREAD_DEBUG_INFO
 CREATE_THREAD_DEBUG_INFO  QuickInfo

typedef struct _CREATE_THREAD_DEBUG_INFO { // ctdi

    HANDLE hThread;

    LPVOID lpThreadLocalBase;

    LPTHREAD_START_ROUTINE lpStartAddress;

} CREATE_THREAD_DEBUG_INFO;

The CREATE_THREAD_DEBUG_INFO structure contains thread-creation information that can be used by a debugger.

Members

hThread

Identifies a handle of the thread whose creation caused the debugging event. If this member is NULL, the handle is not valid. Otherwise, the debugger has THREAD_GET_CONTEXT, THREAD_SET_CONTEXT, and THREAD_SUSPEND_RESUME access to the thread, allowing the debugger to read from and write to the registers of the thread and control execution of the thread.

lpThreadLocalBase

Points to a block of data. At offset 0x2C into this block is another pointer, called ThreadLocalStoragePointer, that points to an array of per-module thread local storage blocks. This gives a debugger access to per-thread data in the threads of the process being debugged using the same algorithms that a compiler would use.

lpStartAddress

Points to the starting address of the thread. This value may only be an approximation of the thread's starting address, because any application with appropriate access to the thread can change the thread's context by using the SetThreadContext function.

See Also

CREATE_PROCESS_DEBUG_INFO, DEBUG_EVENT, LOAD_DLL_DEBUG_INFO, SetThreadContext


CREATESTRUCT
 CREATESTRUCT  QuickInfo

typedef struct tagCREATESTRUCT { // cs

    LPVOID    lpCreateParams;

    HINSTANCE hInstance;

    HMENU     hMenu;

    HWND      hwndParent;

    int       cy;

    int       cx;

    int       y;

    int       x;

    LONG      style;

    LPCTSTR   lpszName;

    LPCTSTR   lpszClass;

    DWORD     dwExStyle;

} CREATESTRUCT;

The CREATESTRUCT structure defines the initialization parameters passed to the window procedure of an application.

Members

lpCreateParams

Points to data to be used for creating the window.

Windows NT: This member is the address of a SHORT (16_bit) 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

Identifies the module that owns the new window.

hMenu

Identifies the menu to be used by the new window.

hwndParent

Identifies 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

Points to a null-terminated string that specifies the name of the new window.

lpszClass

Points to a null-terminated string that specifies the class name of the new window.

dwExStyle

Specifies the extended style for the new window.

Remarks

Windows NT: Referring to the lpCreateParams member of the CREATESTRUCT structure, because the pointer may not be DWORD aligned, an application should access the data using a pointer that has been declared using the UNALIGNED type, as shown 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);

See Also

CreateWindow, CreateWindowEx


CSADDR_INFO
 CSADDR_INFO  QuickInfo  Overview  Group

typedef struct _CSADDR_INFO {

    SOCKET_ADDRESS  LocalAddr;

    SOCKET_ADDRESS  RemoteAddr;

    INT             iSocketType;

    INT             iProtocol;

} CSADDR_INFO;

The CSADDR_INFO structure contains Windows Sockets address information for a network service or name space provider. The GetAddressByName function obtains Windows Sockets address information using CSADDR_INFO structures.

LocalAddr

Specifies a Windows Sockets local address.

In a client application, pass this address to the bind function to obtain access to a network service.

In a network service, pass this address to the bind function so that the service is bound to the appropriate local address.

RemoteAddr

Specifies a Windows Sockets remote address. There are several uses for this remote address:

•	You can use this remote address to connect to the service via the connect function. This is useful if an application performs send/receive operations that involve connection-oriented protocols.

•	You can use this remote address with the sendto function when you are communicating over a connectionless (datagram) protocol. If you are using a connectionless protocol, such as UDP, sendto is typically the way you pass data to the remote system.

iSocketType

Specifies the type of the Windows socket. The following socket types are defined in WINSOCK.H:

Value	Socket Type
SOCK_STREAM	Stream.This is a protocol that sends data as a stream of bytes, with no message boundaries.
SOCK_DGRAM	Datagram. This is a connectionless protocol. There is no virtual circuit setup. There are typically no reliability guarantees. Services use recvfrom to obtain datagrams. The listen and accept functions do not work with datagrams.
SOCK_RDM	Reliably-Delivered Message. This is a protocol that preserves message boundaries in data.
SOCK_SEQPACKET	Sequenced packet stream. This is a protocol that is essentially the same as SOCK_RDM.
iProtocol

Specifies a value to pass as the protocol parameter to the socket function to open a socket for this service.

See Also

bind, connect, GetAddressByName, recv, send, sendto


CURRENCYFMT
 CURRENCYFMT  QuickInfo

typedef struct _currencyfmt {

    UINT      NumDigits;

    UINT      LeadingZero;

    UINT      Grouping;

    LPTSTR    lpDecimalSep;

    LPTSTR    lpThousandSep;

    UINT      NegativeOrder;

    UINT      PositiveOrder;

    LPTSTR    lpCurrencySymbol;
} CURRENCYFMT;

The CURRENCYFMT structure contains information that defines the format of a currency string. The GetCurrencyFormat function uses this information to customize a currency string for a specified locale.

Members

NumDigits

Specifies the number of fractional digits. This is equivalent to the locale information specified by the LCTYPE constant value LOCALE_IDIGITS.

LeadingZero

Specifies whether to use leading zeroes in decimal fields. This is equivalent to the locale information specified by the LCTYPE constant value LOCALE_ILZERO.

Grouping

Specifies the size of each group of digits to the left of the decimal. Values in the range 0 − 9 are valid.

lpDecimalSep

Points to a null-terminated decimal separator string.

lpThousandSep

Points to a null-terminated thousand separator string.

NegativeOrder

Specifies the negative currency mode. This is equivalent to the locale information specified by the LCTYPE constant value LOCALE_INEGCURR.

PositiveOrder

Specifies the positive currency mode. This is equivalent to the locale information specified by the LCTYPE constant value LOCALE_ICURRENCY.

lpCurrencySymbol

Points to a null-terminated currency symbol string.

Remarks

For more information about the LCTYPE constants, see LCTYPE Constants.

See Also

GetCurrencyFormat


CURSORSHAPE
 CURSORSHAPE  QuickInfo

typedef struct tagCURSORSHAPE {    // cs

    int     xHotSpot;

    int     yHotSpot;

    int     cx;

    int     cy;

    int     cbWidth;

    BYTE    Planes;

    BYTE    BitsPixel;

} CURSORSHAPE, FAR *LPCURSORSHAPE;

The CURSORSHAPE structure contains information about a cursor.

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.

See Also

LockResource


CWPRETSTRUCT [New - Windows 95]
 CWPRETSTRUCT  QuickInfo

[New - Windows 95]

typedef struct tagCWPRETSTRUCT { // cwprs

    LRESULT lResult;

    LPARAM  lParam;

    WPARAM  wParam;

    DWORD   message;

    HWND    hwnd;

} CWPRETSTRUCT;

The CWPRETSTRUCT structure defines the message parameters passed to a WH_CALLWNDPROCRET hook procedure.

Members

lResult

Specifies the return value of the window procedure that processed the message specified by the message value.

lParam

Specifies additional information about the message. The exact meaning depends on the message value.

wParam

Specifies additional information about the message. The exact meaning depends on the message value.

message

Specifies the message.

hwnd

Identifies the window that processed the message specified by the message value.

See Also

CallWndRetProc, SetWindowsHook, SetWindowsHookEx


CWPSTRUCT
 CWPSTRUCT  QuickInfo

typedef struct tagCWPSTRUCT { // cwps

    LPARAM  lParam;

    WPARAM  wParam;

    UINT    message;

    HWND    hwnd;

} CWPSTRUCT;

The CWPSTRUCT structure defines the message parameters passed to a WH_CALLWNDPROC hook procedure.

Members

lParam

Specifies additional information about the message. The exact meaning depends on the message value.

wParam

Specifies additional information about the message. The exact meaning depends on the message value.

message

Specifies the message.

hwnd

Identifies the window to receive the message.

See Also

CallWndProc, SetWindowsHook, SetWindowsHookEx


DATATYPES_INFO_1
 DATATYPES_INFO_1  QuickInfo  Overview  Group

typedef struct _DATATYPES_INFO_1 {

    LPTSTR pName;

} DATATYPES_INFO_1;

The DATATYPES_INFO_1 structure contains information about the data type used to record a print job.

Members

pName

Points to a null-terminated string that identifies the data type used to record a print job.

See Also

EnumPrintProcessorDataTypes


DCB
 DCB  QuickInfo

typedef struct _DCB { // dcb

    DWORD DCBlength;           // sizeof(DCB)

    DWORD BaudRate;            // current baud rate

    DWORD fBinary: 1;          // binary mode, no EOF check

    DWORD fParity: 1;          // enable parity checking

    DWORD fOutxCtsFlow:1;      // CTS output flow control

    DWORD fOutxDsrFlow:1;      // DSR output flow control

    DWORD fDtrControl:2;       // DTR flow control type

    DWORD fDsrSensitivity:1;   // DSR sensitivity

    DWORD fTXContinueOnXoff:1; // XOFF continues Tx

    DWORD fOutX: 1;        // XON/XOFF out flow control

    DWORD fInX: 1;         // XON/XOFF in flow control

    DWORD fErrorChar: 1;   // enable error replacement

    DWORD fNull: 1;        // enable null stripping

    DWORD fRtsControl:2;   // RTS flow control

    DWORD fAbortOnError:1; // abort reads/writes on error

    DWORD fDummy2:17;      // reserved

    WORD wReserved;        // not currently used

    WORD XonLim;           // transmit XON threshold

    WORD XoffLim;          // transmit XOFF threshold

    BYTE ByteSize;         // number of bits/byte, 4-8

    BYTE Parity;           // 0-4=no,odd,even,mark,space

    BYTE StopBits;         // 0,1,2 = 1, 1.5, 2

    char XonChar;          // Tx and Rx XON character

    char XoffChar;         // Tx and Rx XOFF character

    char ErrorChar;        // error replacement character

    char EofChar;          // end of input character

    char EvtChar;          // received event character

    WORD wReserved1;       // reserved; do not use

} DCB;

The DCB structure defines the control setting for a serial communications device.

Members

DCBlength

Specifies the length, in bytes, of the DCB structure.

BaudRate

Specifies the baud rate at which the communications device operates. This member can be an actual baud rate value, or one of the following baud rate indexes:

CBR_110	CBR_19200
CBR_300	CBR_38400
CBR_600	CBR_56000
CBR_1200	CBR_57600
CBR_2400	CBR_115200
CBR_4800	CBR_128000
CBR_9600	CBR_256000
CBR_14400
fBinary

Specifies whether binary mode is enabled. The Win32 API does not support nonbinary mode transfers, so this member should be TRUE. Trying to use FALSE will not work.

Under Windows 3.1, if this member is FALSE, nonbinary mode is enabled, and the character specified by the EofChar member is recognized on input and remembered as the end of data.

fParity

Specifies whether parity checking is enabled. If this member is TRUE, parity checking is performed and errors are reported.

fOutxCtsFlow

Specifies whether the CTS (clear-to-send) signal is monitored for output flow control. If this member is TRUE and CTS is turned off, output is suspended until CTS is sent again.

fOutxDsrFlow

Specifies whether the DSR (data-set-ready) signal is monitored for output flow control. If this member is TRUE and DSR is turned off, output is suspended until DSR is sent again.

fDtrControl

Specifies the DTR (data-terminal-ready) flow control. This member can be one of the following values:

Value	Meaning
DTR_CONTROL_DISABLE	Disables the DTR line when the device is opened and leaves it disabled.
DTR_CONTROL_ENABLE	Enables the DTR line when the device is opened and leaves it on.
DTR_CONTROL_HANDSHAKE	Enables DTR handshaking. If handshaking is enabled, it is an error for the application to adjust the line by using the EscapeCommFunction function.
fDsrSensitivity

Specifies whether the communications driver is sensitive to the state of the DSR signal. If this member is TRUE, the driver ignores any bytes received, unless the DSR modem input line is high.

fTXContinueOnXoff

Specifies whether transmission stops when the input buffer is full and the driver has transmitted the XoffChar character. If this member is TRUE, transmission continues after the input buffer has come within XoffLim bytes of being full and the driver has transmitted the XoffChar character to stop receiving bytes. If this member is FALSE, transmission does not continue until the input buffer is within XonLim bytes of being empty and the driver has transmitted the XonChar character to resume reception.

fOutX

Specifies whether XON/XOFF flow control is used during transmission. If this member is TRUE, transmission stops when the XoffChar character is received and starts again when the XonChar character is received.

fInX

Specifies whether XON/XOFF flow control is used during reception. If this member is TRUE, the XoffChar character is sent when the input buffer comes within XoffLim bytes of being full, and the XonChar character is sent when the input buffer comes within XonLim bytes of being empty.

fErrorChar

Specifies whether bytes received with parity errors are replaced with the character specified by the ErrorChar member. If this member is TRUE and the fParity member is TRUE, replacement occurs.

fNull

Specifies whether null bytes are discarded. If this member is TRUE, null bytes are discarded when received.

fRtsControl

Specifies the RTS (request-to-send) flow control. If this value is zero, the default is RTS_CONTROL_HANDSHAKE. This member can be one of the following values:

Value	Meaning
RTS_CONTROL_DISABLE	Disables the RTS line when the device is opened and leaves it disabled.
RTS_CONTROL_ENABLE	Enables the RTS line when the device is opened and leaves it on.
RTS_CONTROL_HANDSHAKE	Enables RTS handshaking. The driver raises the RTS line when the "type-ahead" (input) buffer is less than one-half full and lowers the RTS line when the buffer is more than three-quarters full. If handshaking is enabled, it is an error for the application to adjust the line by using the EscapeCommFunction function.
RTS_CONTROL_TOGGLE	Specifies that the RTS line will be high if bytes are available for transmission. After all buffered bytes have been sent, the RTS line will be low.
fAbortOnError

Specifies whether read and write operations are terminated if an error occurs. If this member is TRUE, the driver terminates all read and write operations with an error status if an error occurs. The driver will not accept any further communications operations until the application has acknowledged the error by calling the ClearCommError function.

fDummy2

Reserved; do not use.

wReserved

Not used; must be set to zero.

XonLim

Specifies the minimum number of bytes allowed in the input buffer before the XON character is sent.

XoffLim

Specifies the maximum number of bytes allowed in the input buffer before the XOFF character is sent. The maximum number of bytes allowed is calculated by subtracting this value from the size, in bytes, of the input buffer.

ByteSize

Specifies the number of bits in the bytes transmitted and received.

Parity

Specifies the parity scheme to be used. This member can be one of the following values:

Value	Meaning
EVENPARITY	Even
MARKPARITY	Mark
NOPARITY	No parity
ODDPARITY	Odd
StopBits

Specifies the number of stop bits to be used. This member can be one of the following values:

Value	Meaning
ONESTOPBIT	1 stop bit
ONE5STOPBITS	1.5 stop bits
TWOSTOPBITS	2 stop bits
XonChar

Specifies the value of the XON character for both transmission and reception.

XoffChar

Specifies the value of the XOFF character for both transmission and reception.

ErrorChar

Specifies the value of the character used to replace bytes received with a parity error.

EofChar

Specifies the value of the character used to signal the end of data.

EvtChar

Specifies the value of the character used to signal an event.

wReserved1

Reserved; do not use.

Remarks

When a DCB structure is used to configure the 8250, the following restrictions apply to the values specified for the ByteSize and StopBits members:

•	The number of data bits must be 5 to 8 bits.

•	The use of 5 data bits with 2 stop bits is an invalid combination, as is 6, 7, or 8 data bits with 1.5 stop bits.

See Also

BuildCommDCB, ClearCommError, EscapeCommFunction, GetCommState, SetCommState


DDEACK
 DDEACK  QuickInfo

typedef struct { // ddeack

    unsigned short bAppReturnCode:8,

    reserved:6,

    fBusy:1,

    fAck:1;

} DDEACK;

The DDEACK structure contains status flags that a DDE application passes to its partner as part of the WM_DDE_ACK message. The flags provide details about the application's response to the messages WM_DDE_DATA, WM_DDE_POKE, WM_DDE_EXECUTE, WM_DDE_ADVISE, WM_DDE_UNADVISE, and WM_DDE_REQUEST.

Members

bAppReturnCode

Specifies an application-defined return code.

fBusy

Indicates whether the application was busy and unable to respond to the partner's message at the time the message was received. A nonzero value indicates the partner was busy and unable to respond. The fBusy member is defined only when the fAck member is zero.

fAck

Indicates whether the application accepted the message from its partner. A nonzero value indicates the partner accepted the message.

See Also

WM_DDE_ACK, WM_DDE_ADVISE, WM_DDE_DATA, WM_DDE_EXECUTE, WM_DDE_REQUEST, WM_DDE_POKE, WM_DDE_UNADVISE


DDEADVISE
 DDEADVISE  QuickInfo

typedef struct { // ddeadv

    unsigned short reserved:14,

        fDeferUpd:1,

        fAckReq:1;

    short cfFormat;

} DDEADVISE;

The DDEADVISE structure contains flags that specify how a DDE server application should send data to a client application during an advise loop. A client passes the handle of a DDEADVISE structure to a server as part of a WM_DDE_ADVISE message. This structure supersedes the DDELN structure.

Members

fDeferUpd

Indicates whether the server should defer sending updated data to the client. If this value is nonzero, the server should send a WM_DDE_DATA message with a NULL data handle whenever the data item changes. In response, the client can post a WM_DDE_REQUEST message to the server to get a handle of the updated data.

fAckReq

Indicates whether the server should set the fAckReq flag in the WM_DDE_DATA messages it posts to the client. If this value is nonzero, the server should set the fAckReq bit.

cfFormat

Specifies the client application's preferred data format. The format must be a standard or registered clipboard format. The following standard clipboard formats can be used:

CF_BITMAP
CF_DIB
CF_DIF
CF_ENHMETAFILE
CF_METAFILEPICT
CF_OEMTEXT
CF_PALETTE
CF_PENDATA
CF_RIFF
CF_SYLK
CF_TEXT
CF_TIFF
CF_WAVE
CF_UNICODETEXT

See Also

WM_DDE_ADVISE, WM_DDE_DATA, WM_DDE_UNADVISE


DDEDATA
 DDEDATA  QuickInfo

typedef struct { // ddedat

    unsigned short unused:12,

        fResponse:1,

        fRelease:1,

        reserved:1,

        fAckReq:1;

    short cfFormat;

    BYTE  Value[1];

} DDEDATA;

The DDEDATA structure contains the data, and information about the data, sent as part of a WM_DDE_DATA message. This structure supersedes the DDEUP structure.

Members

fResponse

Indicates whether the data was sent in response to a WM_DDE_REQUEST message or a WM_DDE_ADVISE message. If this value is nonzero, the data was sent in response to a WM_DDE_REQUEST message.

fRelease

Indicates whether the application receiving the WM_DDE_POKE message should free the data. If this value is nonzero, the application should free the data.

fAckReq

Indicates whether the application receiving the WM_DDE_DATA message should acknowledge receipt of the data by sending a WM_DDE_ACK message. If this value is nonzero, the application should send the acknowledgment.

cfFormat

Specifies the format of the data. The format should be a standard or registered clipboard format. The following standard clipboard formats can be used:

CF_BITMAP
CF_DIB
CF_DIF
CF_ENHMETAFILE
CF_METAFILEPICT
CF_OEMTEXT
CF_PALETTE
CF_PENDATA
CF_RIFF
CF_SYLK
CF_TEXT
CF_TIFF
CF_WAVE
CF_UNICODETEXT

Value

Contains the data. The length and type of data depend on the cfFormat member.

See Also

DDEUP, WM_DDE_ACK, WM_DDE_ADVISE, WM_DDE_DATA, WM_DDE_POKE, WM_DDE_REQUEST


DDELN
 DDELN  QuickInfo

typedef struct { // ddeln

    unsigned short unused:13,

        fRelease:1,

        fDeferUpd:1,

        fAckReq:1;

    short cfFormat;

} DDELN;

The DDELN structure is obsolete. Win32-based applications should use the DDEADVISE structure.

See Also

DDEADVISE, WM_DDE_ADVISE, WM_DDE_UNADVISE


DDEML_MSG_HOOK_DATA
 DDEML_MSG_HOOK_DATA  QuickInfo

typedef struct tagDDEML_MSG_HOOK_DATA { // dmhd

    UINT  uiLo;

    UINT  uiHi;

    DWORD cbData;

    DWORD Data[8];

} DDEML_MSG_HOOK_DATA;

The DDEML_MSG_HOOK_DATA structure contains information about a DDE message, and provides read access to the data referenced by the message. This structure is intended to be used by a DDE Management Library (DDEML) monitoring application.

Members

uiLo

Specifies the unpacked low-order word of the lParam parameter associated with the DDE message.

uiHi

Specifies the unpacked high-order word of the lParam parameter associated with the DDE message.

cbData

Specifies the amount, in bytes, of data being passed with the message. This value can be greater than 32.

Data

Contains the first 32 bytes of data being passed with the message
(8 * sizeof(DWORD)).

See Also

MONCBSTRUCT, MONCONVSTRUCT, MONERRSTRUCT, MONHSZSTRUCT, MONLINKSTRUCT, MONMSGSTRUCT


DDEPOKE
 DDEPOKE  QuickInfo

typedef struct { // ddepok

    unsigned short unused:13,

        fRelease:1,

        fReserved:2;

    short cfFormat;

    BYTE  Value[1];

} DDEPOKE;

The DDEPOKE structure contains the data, and information about the data, sent as part of a WM_DDE_POKE message. This structure supersedes the DDEUP structure.

Members

fRelease

Indicates whether the application receiving the WM_DDE_POKE message should free the data. If this value is nonzero, the application should free the data.

fReserved

Reserved; do not use.

cfFormat

Specifies the format of the data. The format should be a standard or registered clipboard format. The following standard clipboard formats can be used:

CF_BITMAP
CF_DIB
CF_DIF
CF_ENHMETAFILE
CF_METAFILEPICT
CF_OEMTEXT
CF_PALETTE
CF_PENDATA
CF_RIFF
CF_SYLK
CF_TEXT
CF_TIFF
CF_WAVE
CF_UNICODETEXT

Value

Contains the data. The length and type of data depend on the value of the cfFormat member.

See Also

DDEUP, WM_DDE_POKE


DDEUP
 DDEUP  QuickInfo

typedef struct { // ddeup

    unsigned short unused:12,

        fAck:1,

        fRelease:1,

        fReserved:1,

        fAckReq:1;

    short cfFormat;

    BYTE rgb[1];

} DDEUP;

The DDEUP structure is obsolete. Win32-based applications should use the DDEDATA and DDEPOKE structures.

See Also

WM_DDE_DATA, WM_DDE_POKE


DEBUG_EVENT
 DEBUG_EVENT  QuickInfo

typedef struct _DEBUG_EVENT { // de

    DWORD dwDebugEventCode;

    DWORD dwProcessId;

    DWORD dwThreadId;

    union {

        EXCEPTION_DEBUG_INFO Exception;

        CREATE_THREAD_DEBUG_INFO CreateThread;

        CREATE_PROCESS_DEBUG_INFO CreateProcessInfo;

        EXIT_THREAD_DEBUG_INFO ExitThread;

        EXIT_PROCESS_DEBUG_INFO ExitProcess;

        LOAD_DLL_DEBUG_INFO LoadDll;

        UNLOAD_DLL_DEBUG_INFO UnloadDll;

        OUTPUT_DEBUG_STRING_INFO DebugString;

        RIP_INFO RipInfo;

    } u;

} DEBUG_EVENT;

The DEBUG_EVENT structure describes a debugging event.

Members

dwDebugEventCode

Specifies a debugging event code that identifies the type of debugging event. This parameter can be one of the following values:

Value	Meaning
EXCEPTION_DEBUG_EVENT
	Reports an exception debugging event. The value of u.Exception specifies an EXCEPTION_DEBUG_INFO structure.
CREATE_THREAD_DEBUG_EVENT
	Reports a create-thread debugging event. The value of u.CreateThread specifies a CREATE_THREAD_DEBUG_INFO str structure.
CREATE_PROCESS_DEBUG_EVENT
	Reports a create-process debugging event. The value of u.CreateProcessInfo specifies a CREATE_PROCESS_DEBUG_INFO str structure.
EXIT_THREAD_DEBUG_EVENT
	Reports an exit-thread debugging event. The value of u.ExitThread specifies an EXIT_THREAD_DEBUG_INFO str structure.
EXIT_PROCESS_DEBUG_EVENT
	Reports an exit-process debugging event. The value of u.ExitProcess specifies an EXIT_PROCESS_DEBUG_INFO str structure.
LOAD_DLL_DEBUG_EVENT
	Reports a load-dynamic-link-library (DLL) debugging event. The value of u.LoadDll specifies a LOAD_DLL_DEBUG_INFO str structure.
UNLOAD_DLL_DEBUG_EVENT
	Reports an unload-DLL debugging event. The value of u.UnloadDll specifies an UNLOAD_DLL_DEBUG_INFO str structure.
OUTPUT_DEBUG_STRING_EVENT
	Reports an output-debugging-string debugging event. The value of u.DebugString specifies an OUTPUT_DEBUG_STRING_INFO str structure.
RIP_EVENT
	Reports a RIP-debugging event (system debugging error). The value of u.RipInfo specifies a RIP_INFO structure.
dwProcessId

Specifies the identifier of the process in which the debugging event occurred. A debugger uses this value to locate the debugger's per-process structure. These values are not necessarily small integers that can be used as table indices.

dwThreadId

Specifies the identifier of the thread in which the debugging event occurred. A debugger uses this value to locate the debugger's per-thread structure. These values are not necessarily small integers that can be used as table indices.

u

Specifies additional information relating to the debugging event. This union takes on the type and value appropriate to the type of debugging event, as described in the dwDebugEventCode member.

Remarks

If the WaitForDebugEvent function succeeds, it fills in the members of a DEBUG_EVENT structure.

See Also

CREATE_PROCESS_DEBUG_INFO, CREATE_THREAD_DEBUG_INFO, EXIT_PROCESS_DEBUG_INFO, EXIT_THREAD_DEBUG_INFO, EXCEPTION_DEBUG_INFO, LOAD_DLL_DEBUG_INFO, OUTPUT_DEBUG_STRING_INFO, UNLOAD_DLL_DEBUG_INFO, WaitForDebugEvent


DEBUGHOOKINFO
 DEBUGHOOKINFO  QuickInfo

typedef struct tagDEBUGHOOKINFO { // dh

    DWORD  idThread;

    DWORD  idThreadInstaller;

    LPARAM lParam;

    WPARAM wParam;

    int    code;

} DEBUGHOOKINFO;

The DEBUGHOOKINFO structure contains debugging information.

Members

idThread

Identifies the thread containing the filter function.

idThreadInstaller

Identifies the thread that installed the debugging filter function.

lParam

Specifies the value to be passed to the hook in the lParam parameter of the DebugProc callback function.

wParam

Specifies the value to be passed to the hook in the wParam parameter of the DebugProc callback function.

code

Specifies the value to be passed to the hook in the nCode parameter of the DebugProc callback function.

See Also

DebugProc, SetWindowsHook, SetWindowsHookEx


DELETEITEMSTRUCT
 DELETEITEMSTRUCT  QuickInfo

typedef struct tagDELETEITEMSTRUCT { // ditms

    UINT CtlType;

    UINT CtlID;

    UINT itemID;

    HWND hwndItem;

    UINT itemData;

} 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, Windows sends the WM_DELETEITEM message to the owner for each deleted item.

Windows NT

Windows 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

Windows sends the WM_DELETEITEM message for any deleted list box or combo box item with non-zero item data.

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

Identifies 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.

See Also

WM_DELETEITEM


DEV_BROADCAST_HDR [New - Windows 95]
 DEV_BROADCAST_HDR  QuickInfo  Overview  Group

[New - Windows 95]

typedef struct _DEV_BROADCAST_HDR {
    ULONG dbch_size;

    ULONG dbch_devicetype;

    ULONG dbch_reserved;

} DEV_BROADCAST_HDR;
typedef DEV_BROADCAST_HDR *PDEV_BROADCAST_HDR;

The DEV_BROADCAST_HDR structure contains information about the device affected by a WM_DEVICECHANGE message.

Members

dbch_size

Size of this structure, in bytes.

dbch_devicetype

Type of device. Can be one of these values:

Value	Meaning
DBT_DEVTYP_OEM	OEM- or IHV-defined device type.
DBT_DEVTYP_VOLUME	Logical volume.
DBT_DEVTYP_PORT	Port device (serial or parallel).
dbch_reserved

Reserved; do not use.

See Also

WM_DEVICECHANGE


DEV_BROADCAST_OEM [New - Windows 95]
 DEV_BROADCAST_OEM  QuickInfo  Overview  Group

[New - Windows 95]

typedef struct _DEV_BROADCAST_OEM {
    ULONG dbco_size;

    ULONG dbco_devicetype;

    ULONG dbco_reserved;

    ULONG dbco_identifier;

    ULONG dbco_suppfunc;

} DEV_BROADCAST_OEM;
typedef DEV_BROADCAST_OEM *PDEV_BROADCAST_OEM;

The DEV_BROADCAST_OEM structure contains information about a OEM-defined device type.

Members

dbco_size

Size of this structure, in bytes.

dbco_devicetype

DBT_DEVTYPE_OEM.

dbco_reserved

Reserved; do not use.

dbco_identifier

Globally unique identifier (GUID) for the device. Use the uuidgen utility to create this identifier.

dbco_suppfunc

OEM-specific function value. Possible values depend on the device.


DEV_BROADCAST_PORT [New - Windows 95]
 DEV_BROADCAST_PORT  QuickInfo  Overview  Group

[New - Windows 95]

typedef struct _DEV_BROADCAST_PORT {
    ULONG dbcp_size;

    ULONG dbcp_devicetype;

    ULONG dbcp_reserved;

    char dbcp_name[1];

} DEV_BROADCAST_PORT;
typedef DEV_BROADCAST_PORT *PDEV_BROADCAST_PORT;

The DEV_BROADCAST_PORT structure contains information about a modem, serial, or parallel port.

Members

dbcp_size

Size of this structure, in bytes.

dbcp_devicetype

DBT_DEVTYP_VOLUME.

dbcp_reserved

Reserved; do not use.

dbcp_name

Null-terminated string specifying the friendly name of the port or the device connected to the port. Friendly names are intended to help the user quickly and accurately identify the device—for example, "COM1", "Hayes 2400 Smartmodem", and "LPT1" are considered friendly names.


_DEV_BROADCAST_USERDEFINED
 _DEV_BROADCAST_USERDEFINED  Overview  Group

struct _DEV_BROADCAST_USERDEFINED {
    struct _DEV_BROADCAST_HDR dbud_dbh;
    char  dbud_szName[1];           // ASCIIZ name
//    BYTE  dbud_rgbUserDefined[];  // Optional user-defined contents
};

The _DEV_BROADCAST_USERDEFINED structure contains the user-defined message and optional data associated with the DBT_USERDEFINED device message.

Members

dbud_dbh

Information about the device affected by a WM_DEVICECHANGE message as specified by the DEV_BROADCAST_HDR structure. Because the _DEV_BROADCAST_USERDEFINED structure is variable length, dbud_dbh.dbch_size must be the size in bytes of the entire structure, including the variable length part.

dbud_szName

A case-sensitive, null-terminated string that names the message. The name must consist of the vendor name, a backslash, followed by arbitrary user-defined null-terminated text. For example:

"WidgetWare\QueryScannerShutdown"

or

"WidgetWare\Video Q39S\AdapterReady"

dbud_rgbUserDefined

Optional user-defined information.

Because this structure contains variable length fields, use this structure tag as a template for creating a pointer to a user-defined structure. Note that the structure must not contain pointers. For example:

#define NAME_LENGTH 32

#define USER_LENGTH 50

typedef struct tagWIDGET_WARE_DEV_BROADCAST_USERDEFINED
{
    struct _DEV_BROADCAST_HDR DBHeader;
    char  szName[NAME_LENGTH]
    BYTE  UserDefined[USER_LENGTH];

} WIDGET_WARE_DEV_BROADCAST_USERDEFINED;

See Also

DBT_USERDEFINED, DEV_BROADCAST_HDR, WM_DEVICECHANGE


DEV_BROADCAST_VOLUME [New - Windows 95]
 DEV_BROADCAST_VOLUME  QuickInfo  Overview  Group

[New - Windows 95]

typedef struct _DEV_BROADCAST_VOLUME {
    ULONG dbcv_size;

    ULONG dbcv_devicetype;

    ULONG dbcv_reserved;

    ULONG dbcv_unitmask;

    USHORT dbcv_flags;

} DEV_BROADCAST_VOLUME;
typedef DEV_BROADCAST_VOLUME *PDEV_BROADCAST_VOLUME;

The DEV_BROADCAST_VOLUME structure contains information about a logical volume.

Members

dbcv_size

Size of this structure, in bytes.

dbcv_devicetype

DBT_DEVTYP_VOLUME.

dbcv_reserved

Reserved; do not use.

dbcv_unitmask

Logical unit mask identifying one or more logical units. Each bit in the mask corresponds to one logical drive. Bit 0 represents drive A, bit 1 drive B, and so on.

dbcv_flags

Flags indicating whether drive or media.

Value	Meaning
DBTF_MEDIA	Change affects media in drive. If not set, change affects physical device or drive.
DBTF_NET	Indicated logical volume is a network volume.
Remarks

Although the dbcv_unitmask member may specify more than one volume in any given message, this does not guarantee that only message is generated for a given event. Multiple system components may independently generate messages for logical volumes at the same time.


DEVMODE
 DEVMODE  QuickInfo

typedef struct _devicemode {    // dvmd

    BCHAR  dmDeviceName[CCHDEVICENAME];

    WORD   dmSpecVersion;

    WORD   dmDriverVersion;

    WORD   dmSize;

    WORD   dmDriverExtra;

    DWORD  dmFields;

    short  dmOrientation;

    short  dmPaperSize;

    short  dmPaperLength;

    short  dmPaperWidth;

    short  dmScale;

    short  dmCopies;

    short  dmDefaultSource;

    short  dmPrintQuality;

    short  dmColor;

    short  dmDuplex;

    short  dmYResolution;

    short  dmTTOption;

    short  dmCollate;

    BCHAR  dmFormName[CCHFORMNAME];

    WORD  dmLogPixels;

    DWORD  dmBitsPerPel;

    DWORD  dmPelsWidth;

    DWORD  dmPelsHeight;

    DWORD  dmDisplayFlags;

    DWORD  dmDisplayFrequency;

#if(WINVER >= 0x0400)

    DWORD  dmICMMethod;         // Windows 95 only

    DWORD  dmICMIntent;         // Windows 95 only

    DWORD  dmMediaType;         // Windows 95 only

    DWORD  dmDitherType;        // Windows 95 only

    DWORD  dmReserved1;         // Windows 95 only

    DWORD  dmReserved2;         // Windows 95 only

#endif /* WINVER >= 0x0400 */

} DEVMODE;

The DEVMODE data structure contains information about the device initialization and environment of a printer.

Members

dmDeviceName

Specifies the the "friendly" name of the printer; for example, "PCL/HP LaserJet" in the case of PCL/HP LaserJet®. This string is unique among device drivers. Note that this name may be truncated to fit in the dmDeviceName array.

dmSpecVersion

Specifies the version number of the initialization data specification on which the structure is based.

dmDriverVersion

Specifies the printer driver version number assigned by the printer driver developer.

dmSize

Specifies the size, in bytes, of the DEVMODE structure, not including any private driver-specific data that might follow the structure's public members. You can use this member to determine the number of bytes of public data regardless of the version of the DEVMODE structure being used.

dmDriverExtra

Contains the number of bytes of private driver-data that follow this structure. If a device driver does not use device-specific information, set this member to zero.

dmFields

A set of bit flags that specify whether certain members of the DEVMODE structure have been initialized. If a field is initialized, its corresponding bit flag is set, otherwise the bit flag is clear.  A printer driver supports only those DEVMODE structure members that are appropriate for the printer technology.

The following bit flags are defined, and are listed here with the corresponding structure members:

Value	Structure Member
DM_ORIENTATION	dmOrientation
DM_PAPERSIZE	dmPaperSize
DM_PAPERLENGTH	dmPaperLength
DM_PAPERWIDTH	dmPaperWidth
DM_SCALE	dmScale
DM_COPIES	dmCopies
DM_DEFAULTSOURCE	dmDefaultSource
DM_PRINTQUALITY	dmPrintQuality
DM_COLOR	dmColor
DM_DUPLEX	dmDuplex
DM_YRESOLUTION	dmYResolution
DM_TTOPTION	dmTTOption
DM_COLLATE	dmCollate
DM_FORMNAME	dmFormName
DM_LOGPIXELS	dmLogPixels
DM_BITSPERPEL	dmBitsPerPel
DM_PELSWIDTH	dmPelsWidth
DM_PELSHEIGHT	dmPelsHeight
DM_DISPLAYFLAGS	dmDisplayFlags
DM_DISPLAYFREQUENCY	dmDisplayFrequency
DM_ICMMETHOD	Windows 95 only: dmICMMethod
DM_ICMINTENT	Windows 95 only: dmICMIntent
DM_MEDIATYPE	Windows 95 only: dmMediaType
DM_DITHERTYPE	Windows 95 only: dmDitherType
dmOrientation

Selects the orientation of the paper. This member can be either DMORIENT_PORTRAIT (1) or DMORIENT_LANDSCAPE (2).

dmPaperSize

Selects the size of the paper to print on. This member can be set to zero if the length and width of the paper are both set by the dmPaperLength and dmPaperWidth members. Otherwise, the dmPaperSize member can be set to one of the following predefined values:

Value	Meaning
DMPAPER_LETTER	Letter, 8 1/2- by 11-inches
DMPAPER_LEGAL	Legal, 8 1/2- by 14-inches
DMPAPER_A4	A4 Sheet, 210- by 297-millimeters
DMPAPER_CSHEET	C Sheet, 17- by 22-inches
DMPAPER_DSHEET	D Sheet, 22- by 34-inches
DMPAPER_ESHEET	E Sheet, 34- by 44-inches
DMPAPER_LETTERSMALL	Letter Small, 8 1/2- by 11-inches
DMPAPER_TABLOID	Tabloid, 11- by 17-inches
DMPAPER_LEDGER	Ledger, 17- by 11-inches
DMPAPER_STATEMENT	Statement, 5 1/2- by 8 1/2-inches
DMPAPER_EXECUTIVE	Executive, 7 1/4- by 10 1/2-inches
DMPAPER_A3	A3 sheet, 297- by 420-millimeters
DMPAPER_A4SMALL	A4 small sheet, 210- by 297-millimeters
DMPAPER_A5	A5 sheet, 148- by 210-millimeters
DMPAPER_B4	B4 sheet, 250- by 354-millimeters
DMPAPER_B5	B5 sheet, 182- by 257-millimeter paper
DMPAPER_FOLIO	Folio, 8 1/2- by 13-inch paper
DMPAPER_QUARTO	Quarto, 215- by 275-millimeter paper
DMPAPER_10X14	10- by 14-inch sheet
DMPAPER_11X17	11- by 17-inch sheet
DMPAPER_NOTE	Note, 8 1/2- by 11-inches
DMPAPER_ENV_9	#9 Envelope, 3 7/8- by 8 7/8-inches
DMPAPER_ENV_10	#10 Envelope, 4 1/8- by 9 1/2-inches
DMPAPER_ENV_11	#11 Envelope, 4 1/2- by 10 3/8-inches
DMPAPER_ENV_12	#12 Envelope, 4 3/4- by 11-inches
DMPAPER_ENV_14	#14 Envelope, 5- by 11 1/2-inches
DMPAPER_ENV_DL	DL Envelope, 110- by 220-millimeters
DMPAPER_ENV_C5	C5 Envelope, 162- by 229-millimeters
DMPAPER_ENV_C3	C3 Envelope,  324- by 458-millimeters
DMPAPER_ENV_C4	C4 Envelope,  229- by 324-millimeters
DMPAPER_ENV_C6	C6 Envelope,  114- by 162-millimeters
DMPAPER_ENV_C65	C65 Envelope, 114- by 229-millimeters
DMPAPER_ENV_B4	B4 Envelope,  250- by 353-millimeters
DMPAPER_ENV_B5	B5 Envelope,  176- by 250-millimeters
DMPAPER_ENV_B6	B6 Envelope,  176- by 125-millimeters
DMPAPER_ENV_ITALY	Italy Envelope, 110- by 230-millimeters
DMPAPER_ENV_MONARCH	Monarch Envelope, 3 7/8- by 7 1/2-inches
DMPAPER_ENV_PERSONAL	6 3/4 Envelope, 3 5/8- by 6 1/2-inches
DMPAPER_FANFOLD_US	US Std Fanfold, 14 7/8- by 11-inches
DMPAPER_FANFOLD_STD_GERMAN	German Std Fanfold, 8 1/2- by 12-inches
DMPAPER_FANFOLD_LGL_GERMAN	German Legal Fanfold, 8 1/2- by 13-inches
dmPaperLength

Overrides the length of the paper specified by the dmPaperSize member, either for custom paper sizes or for devices such as dot-matrix printers, which can print on a page of arbitrary length. These values, along with all other values in this structure that specify a physical length, are in tenths of a millimeter.

dmPaperWidth

Overrides the width of the paper specified by the dmPaperSize member.

dmScale

Specifies the factor by which the printed output is to be scaled. The apparent page size is scaled from the physical page size by a factor of dmScale/100. For example, a letter-sized page with a dmScale value of 50 would contain as much data as a page of 17- by 22-inches because the output text and graphics would be half their original height and width.

dmCopies

Selects the number of copies printed if the device supports multiple-page copies.

dmDefaultSource

Reserved; must be zero.

dmPrintQuality

Specifies the printer resolution. There are four predefined device-independent values:

DMRES_HIGH
DMRES_MEDIUM
DMRES_LOW
DMRES_DRAFT

If a positive value is given, it specifies the number of dots per inch (DPI) and is therefore device dependent.

dmColor

Switches between color and monochrome on color printers. Following are the possible values:

DMCOLOR_COLOR
DMCOLOR_MONOCHROME

dmDuplex

Selects duplex or double-sided printing for printers capable of duplex printing. Following are the possible values:

DMDUP_SIMPLEX
DMDUP_HORIZONTAL
DMDUP_VERTICAL

dmYResolution

Specifies the y-resolution, in dots per inch, of the printer. If the printer initializes this member, the dmPrintQuality member specifies the x-resolution, in dots per inch, of the printer.

dmTTOption

Specifies how TrueType® fonts should be printed. This member can be one of the following values:

Value	Meaning
DMTT_BITMAP	Prints TrueType fonts as graphics. This is the default action for dot-matrix printers.
DMTT_DOWNLOAD	Downloads TrueType fonts as soft fonts. This is the default action for Hewlett-Packard printers that use Printer Control Language (PCL).
DMTT_SUBDEV	Substitute device fonts for TrueType fonts. This is the default action for PostScript® printers.
dmUnusedPadding

Used to align the structure to a DWORD boundary. This should not be used or referenced. Its name and usage is reserved, and can change in future releases.

dmCollate

Specifies whether collation should be used when printing multiple copies. (This member is ignored unless the printer driver indicates support for collation by setting the dmFields member to DM_COLLATE.) This member can be be one of the following values:

Value	Meaning
DMCOLLATE_TRUE	Collate when printing multiple copies.
DMCOLLATE_FALSE	Do not collate when printing multiple copies.
Using DMCOLLATE_TRUE provides faster, more efficient output for collation, since the data is sent to the device driver just once, no matter how many copies are required. The printer is told to simply print the page again.

dmFormName

Windows NT: Specifies the name of the form to use; for example, "Letter" or "Legal". A complete set of names can be retrieved by using the EnumForms function.

Windows 95: Printer drivers do not use this member.

dmLogPixels

Specifies the number of pixels per logical inch.

dmBitsPerPel

Windows NT: Specifies the color resolution, in bits per pixel, of the display device (for example: 4 bits for 16 colors, 8 bits for 256 colors, or 16 bits for 65536 colors).

Windows 95: Display drivers use this member, for example, in the ChangeDisplaySettings function. Printer drivers do not use this member.

dmPelsWidth

Windows NT: Specifies the width, in pixels, of the visible device surface.

Windows 95: Display drivers use this member, for example, in the ChangeDisplaySettings function. Printer drivers do not use this member.

dmPelsHeight

Windows NT: Specifies the height, in pixels, of the visible device surface.

Windows 95: Display drivers use this member, for example, in the ChangeDisplaySettings function. Printer drivers do not use this member.

dmDisplayFlags

Windows NT: Specifies the device's display mode. This member can be one of the following values:

Value	Meaning
DM_GRAYSCALE	Specifies that the display is a NON-color device. If this flag is not set, color is assumed.
DM_INTERLACED	Specifies that the display mode is interlaced. If the flag is not set, NON-interlaced is assumed.
Windows 95: Display drivers use this member, for example, in the ChangeDisplaySettings function. Printer drivers do not use this member.

dmDisplayFrequency

Windows NT: Specifies the frequency, in hertz (cycles per second), of the display device in a particular mode.

Windows 95: Display drivers use this member, for example, in the ChangeDisplaySettings function. Printer drivers do not use this member.

dmICMMethod

Windows 95

Specifies how ICM is handled. For a non-ICM application, this member determines if ICM is enabled or disabled. For ICM applications, Windows examines this member to determine how to handle ICM support. This member can be one of the following predefined values, or a driver-defined value greater than the value of DMICMMETHOD_USER:

Value	Meaning
DMICMMETHOD_NONE	Windows 95 only: Specifies that ICM is disabled.
DMICMMETHOD_SYSTEM	Windows 95 only: Specifies that ICM is handled by Windows.
DMICMMETHOD_DRIVER	Windows 95 only: Specifies that ICM is handled by the device driver.
DMICMMETHOD_DEVICE	Windows 95 only: Specifies that ICM is handled by the destination device.
The printer driver must provide a user interface for setting this member. Most printer drivers support only the DMICMMETHOD_SYSTEM or DMICMMETHOD_NONE value. Drivers for PostScript printers support all values.

Windows NT

This member is not supported on Windows NT.

dmICMIntent

Windows 95

Specifies which of the three possible color matching methods, or intents, should be used by default. This member is primarily for non-ICM applications. ICM applications can establish intents by using the ICM functions. This member can be one of the following predefined values, or a driver defined value greater than the value of DMICM_USER:

Value	Meaning
DMICM_SATURATE	Windows 95 only: Color matching should optimize for color saturation. This value is the most appropriate choice for business graphs when dithering is not desired.
DMICM_CONTRAST	Windows 95 only: Color matching should optimize for color contrast. This value is the most appropriate choice for scanned or photographic images when dithering is desired.
DMICM_COLORMETRIC	Windows 95 only: Color matching should optimize to match the exact color requested. This value is most appropriate for use with business logos or other images when an exact color match is desired.
Windows NT

This member is not supported on Windows NT.

dmMediaType

Windows 95

Specifies the type of media being printed on. The member can be one of the following predefined values, or a driver-defined value greater than the value of DMMEDIA_USER:

Value	Meaning
DMMEDIA_STANDARD	Windows 95 only: Plain paper.
DMMEDIA_GLOSSY	Windows 95 only: Glossy paper.
DMMEDIA_TRANSPARENCY	Windows 95 only: Transparent film.
Windows NT

This member is not supported on Windows NT.

dmDitherType

Windows 95

Specifies how dithering is to be done. The member can be one of the following predefined values, or a driver-defined value greater than the value of DMDITHER_USER:

Value	Meaning
DMDITHER_NONE	Windows 95 only: No dithering.
DMDITHER_COARSE	Windows 95 only: Dithering with a coarse brush.
DMDITHER_FINE	Windows 95 only: Dithering with a fine brush.
DMDITHER_LINEART	Windows 95 only: Line art dithering, a special dithering method that produces well defined borders between black, white, and gray scalings. It is not suitable for images that include continuous graduations in intensisty and hue such as scanned photographs.
DMDITHER_GRAYSCALE	Windows 95 only: Device does grayscaling.
Windows NT

This member is not supported on Windows NT.

dmReserved1

Windows 95

Not used; must be zero.

Windows NT

This member is not supported on Windows NT.

dmReserved2

Windows 95

Not used; must be zero.

Windows NT

This member is not supported on Windows NT.

Remarks

A device driver's private data follows the public portion of the DEVMODE structure. The size of the public data can vary for different versions of the structure. The dmSize member specifies the number of bytes of public data, and the dmDriverExtra member specifies the number of bytes of private data.

See Also

AdvancedDocumentProperties, CreateDC, CreateIC, DeviceCapabilities, DocumentProperties, OpenPrinter


DEVNAMES
 DEVNAMES  QuickInfo

typedef struct tagDEVNAMES { // dvnm

    WORD wDriverOffset;

    WORD wDeviceOffset;

    WORD wOutputOffset;

    WORD wDefault;

    // driver, device, and port name strings follow wDefault

} DEVNAMES;

The DEVNAMES structure contains strings that identify the driver, device, and output port names for a printer. The PrintDlg function uses these strings to initialize members in the system-defined Print dialog box. When the user closes the dialog box, information about the selected printer is returned in this structure.

Members

wDriverOffset

(Input/Output) Specifies the offset in characters from the beginning of this structure to a null-terminated string that contains the filename (without the extension) of the device driver. On input, this string is used to determine the printer to display initially in the dialog box.

wDeviceOffset

(Input/Output) Specifies the offset in characters from the beginning of this structure to the null-terminated string (maximum of 32 bytes including the null) that contains the name of the device. This string must be identical to the dmDeviceName member of the DEVMODE structure.

wOutputOffset

(Input/Output) Specifies the offset in characters from the beginning of this structure to the null-terminated string that contains the device name for the physical output medium (output port).

wDefault

Specifies whether the strings contained in the DEVNAMES structure identify the default printer. This string is used to verify that the default printer has not changed since the last print operation. If any of the strings do not match, a warning message is displayed informing the user that the document may need to be reformatted.

On output, the wDefault member is changed only if the Print Setup dialog box was displayed and the user chose the OK button. The DN_DEFAULTPRN flag is used if the default printer was selected. If a specific printer is selected, the flag is not used. All other flags in this member are reserved for internal use by the Print Dialog box procedure.

See Also

DEVMODE, PrintDlg


DIBSECTION
 DIBSECTION  QuickInfo

typedef struct tagDIBSECTION {

    BITMAP              dsBm;

    BITMAPINFOHEADER    dsBmih;

    DWORD               dsBitfields[3];

    HANDLE              dshSection;

    DWORD               dsOffset;

} DIBSECTION;

The DIBSECTION structure contains information about a device-independent bitmap created by calling the CreateDIBSection function. A DIBSECTION structure includes information about the bitmap's dimensions, color format, color masks, optional file mapping object, and optional bit values storage offset. An application can obtain a filled-in DIBSECTION structure for a given device-independent bitmap by calling the GetObject function.

Members

dsBm

A BITMAP data structure that contains information about the device-independent bitmap: its type, its dimensions, its color capacities, and a pointer to its bit values.

dsBmih

A BITMAPINFOHEADER data structure that contains information about the color format of the device-independent bitmap.

dsBitfields

Specifies three DWORD color masks for the device-independent bitmap. This field is only valid when the biBitCount member of the BITMAPINFOHEADER structure has a value greater than 8. Each color mask indicates the bits within a bit value doubleword that are used to encode one of the three color channels (red, green, and blue).

dshSection

Contains a handle to the file mapping object that the CreateDIBSection function used to create the device-independent bitmap. If CreateDIBSection was called with a NULL value for its hSection parameter, causing the operating system to allocate memory for the bitmap, the dshSection member will be NULL.

dsOffset

Specifies the offset to the bitmap's bit values within the file mapping object referenced by dshSection. If dshSection is NULL, the dsOffset value has no meaning.

See Also

BITMAP, BITMAPINFOHEADER, CreateDIBSection, GetDIBColorTable, GetObject


DISK_GEOMETRY
 DISK_GEOMETRY  QuickInfo  Overview  Group

typedef struct _DISK_GEOMETRY {

   LARGE_INTEGER  Cylinders;

   MEDIA_TYPE  MediaType;

   DWORD  TracksPerCylinder;

   DWORD  SectorsPerTrack;

   DWORD  BytesPerSector;

} DISK_GEOMETRY ;

The DISK_GEOMETRY structure describes the geometry of disk devices and media.

Members

Cylinders

The number of cylinders.

MediaType

The type of media. See MEDIA_TYPE.

TracksPerCylinder

The number of tracks per cylinder.

SectorsPerTrack

The number of sectors per track.

BytesPerSector

The number of bytes per sector

Remarks

The DeviceIoControl function receives a DISK_GEOMETRY structure in response to an IOCTL_DISK_GET_DRIVE_GEOMETRY device input and output contol (IOCTL) operation. The DeviceIoControl function receives an array of DISK_GEOMETRY structures in response to an IOCTL_DISK_GET_MEDIA_TYPES device I/O operation.

See Also

DeviceIoControl, IOCTL_DISK_GET_DRIVE_GEOMETRY, IOCTL_DISK_GET_MEDIA_TYPES, MEDIA_TYPE


DISK_PERFORMANCE
 DISK_PERFORMANCE  QuickInfo  Overview  Group

typedef struct _DISK_PERFORMANCE {

        LARGE_INTEGER BytesRead;

        LARGE_INTEGER BytesWritten;

        LARGE_INTEGER ReadTime;

        LARGE_INTEGER WriteTime;

        DWORD ReadCount;

        DWORD WriteCount;

        DWORD QueueDepth;

} DISK_PERFORMANCE ;

The DISK_PERFORMANCE structure provides disk performance information.

Members

BytesRead

Specifies the number of bytes read.

BytesWritten

Specifies the number of bytes written.

ReadTime

Specifies the time it took to complete the read.

WriteTime

Specifies the time it took to complete the write.

ReadCount

Specifies the number of read operations.

WriteCount

Specifies the number of write operations.

QueueDepth

Specifies the depth of the queue.

Remarks

The DeviceIoControl function receives a DISK_PERFORMANCE structure in response to an IOCTL_DISK_PERFORMANCE device I/O operation.

See Also

DeviceIoControl, IOCTL_DISK_PERFORMANCE


DLGITEMTEMPLATE
 DLGITEMTEMPLATE  QuickInfo  Overview  Group

typedef struct { // dlit

    DWORD style;

    DWORD dwExtendedStyle;

    short x;

    short y;

    short cx;

    short cy;

    WORD  id;

} 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 dialog box template.

Members

style

Specifies the style of the control. This member can be a combination of window style values (such as WS_BORDER) and one or more of the control style values (such as BS_PUSHBUTTON and ES_LEFT).

dwExtendedStyle

Specifies extended styles for a window. This member is not used to create controls in dialog boxes, but applications that use dialog box templates can use it to create other types of windows.

x

Specifies the x-coordinate, in dialog box units, of the upper-left corner of the control. This coordinate is always relative to the upper-left corner of the dialog box's client area.

y

Specifies the y-coordinate, in dialog box units, of the upper-left corner of the control. This coordinate is always relative to the upper-left corner of the dialog box's client area.

cx

Specifies the width, in dialog box units, of the control.

cy

Specifies the height, in dialog box units, of the control.

id

Specifies the control identifier.

Remarks

In a dialog box template, 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.

The class array follows the DLGITEMTEMPLATE structure. When the first element of this array is 0xFFFF, the array has one additional element that specifies an atom value identifying a registered window class. When the first element has any other value, Windows assumes the array is a null-terminated Unicode string that specifies the name of a registered window class. Following are the class atom values for predefined controls:

Value	Meaning
0x0080	Button
0x0081	Edit
0x0082	Static
0x0083	List box
0x0084	Scroll bar
0x0085	Combo box
The title array follows the class array. When the first element is 0xFFFF, the array has one additional element that specifies the identifier of a resource, such as an icon, in an executable file. Resource identifiers are usually given for controls, such as static icon controls, that load and display an icon or other resources rather than text. When the first element is any other value, Windows assumes the array is a null-terminated Unicode string that specifies the initial text for the control.

The creation data array follows the text array. This array can contain any number of elements; the control's window procedure must understand the content and format of the data. Windows passes this data to the control when it calls the CreateWindowEx function.

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.

See Also

CreateDialogIndirect, CreateDialogIndirectParam, CreateWindowEx, DialogBoxIndirect, DialogBoxIndirectParam, MapDialogRect


DLGTEMPLATE
 DLGTEMPLATE  QuickInfo  Overview  Group

typedef struct { // dltt

    DWORD style;

    DWORD dwExtendedStyle;

    WORD  cdit;

    short x;

    short y;

    short cx;

    short cy;

} DLGTEMPLATE;

The DLGTEMPLATE structure defines the dimensions and style of a dialog box. This structure, always the first in a dialog box template, also specifies the number of controls in the dialog box and therefore specifies the number of subsequent DLGITEMTEMPLATE structures in the template.

Members

style

Specifies the style of the dialog box. This member can be a combination of window style values (such as WS_CAPTION and WS_SYSMENU) and one or more of the following dialog box style values:

Value	Meaning
DS_3DLOOK	Windows 95 only: Gives the dialog box a non-bold font and draws three dimensional borders around control windows in the dialog box.  The DS_3DLOOK style is not required by Win32-based applications that are marked with version number 4.0 or greater; the system automatically applies the three dimensional look to dialog boxes created by these applications.
DS_ABSALIGN	Indicates that the coordinates of the dialog box are screen coordinates. If this style is not specified, Windows assumes they are client coordinates.
DS_CENTER	Windows 95 only: Centers the dialog box in the working area; that is, the area not obscured by the tray.
DS_CENTERMOUSE	Windows 95 only: Centers the mouse cursor in the dialog box.
DS_CONTEXTHELP	Includes a question mark in the title bar of the dialog box. When the user clicks the question mark, the cursor changes to a question mark with a pointer. If the user then clicks a control in the dialog box the control receives a WM_HELP message. The control should pass the message to the dialog procedure, which should call the WinHelp function using the HELP_WM_HELP command. The Help application displays a pop-up window that typically contains help for the control.  Note that DS_CONTEXTHELP is just 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.
DS_CONTROL	Creates a dialog gox 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	Windows 95 only: Use SYSTEM_FIXED_FONT instead of SYSTEM_FONT.
DS_LOCALEDIT	Applies to 16-bit applications only. This style directs edit controls in the dialog box to allocate memory from the application's data segment. Otherwise, edit controls allocate storage from a global memory object.
DS_MODALFRAME	Creates a dialog box with a modal dialog-box frame that can be combined with a title bar and System menu by specifying the WS_CAPTION and WS_SYSMENU styles.
DS_NOFAILCREATE	Windows 95 only: Creates the dialog 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 Windows would otherwise send to the owner of the dialog box while the dialog box is displayed.
DS_SETFONT	Indicates that the dialog box template (the DLGTEMPLATE structure) contains two additional members specifying a font name and point size. The corresponding font is used to display text within the dialog box client area and within the dialog box controls. Windows passes the handle of the font to the dialog box and to each control by sending them the WM_SETFONT message.
DS_SETFOREGROUND	This style brings the dialog box to the foreground. Internally, Windows calls the SetForegroundWindow function for the dialog box.
DS_SYSMODAL	Creates a system-modal dialog box. This style causes the dialog box to have the WS_EX_TOPMOST style, but otherwise has no effect on the dialog box or the behavior of other windows in the system when the dialog box is displayed.
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 dialog box template, the DLGTEMPLATE structure is always immediately followed by three variable-length arrays that specify the menu, class, and title for the dialog box. When the DS_SETFONT style is given, these arrays are also followed by a 16-bit value specifying point size and another variable-length array specifying a typeface name. Each array consists of one or more 16-bit elements.

The menu array follows the DLGTEMPLATE structure. When the first element of this array is 0x0000, the dialog box has no menu and the array has no other elements. When the first element is 0xFFFF, the array has one additional element that specifies the resource identifier for a menu resource in an executable file. If the first element has any other value, Windows assumes the array is a null-terminated Unicode string that specifies the name of the menu resource in an executable file.

The class array follows the menu array. When the first element of the array is 0x0000, Windows uses the predefined dialog box class for the dialog box. When the first element is 0xFFFF, the array has one additional element that specifies the atom value identifying a registered window class. When the first element has any other value, Windows assumes the array is a null-terminated Unicode string that specifies the name of a registered window class.

The title array follows the class array. When the first element of the array is 0x0000, the dialog box has no title. When the first element has any other value, Windows assumes the array is a null-terminated Unicode string that specifies the title.

The 16-bit point size value and the typeface array follow the title array, but only if the style member gives the DS_SETFONT style. The point size value specifies the point size of the font to use for the text in the dialog box and its controls. The typeface array is a null-terminated Unicode string specifying the name of the typeface for the font. When these values are given, Windows creates a font having the given size and typeface (if possible) and sends a WM_SETFONT message to the dialog box procedure and the control window procedures as it creates the dialog box and controls.

Every dialog box template also contains the number of DLGITEMTEMPLATE structures as given by the cdit member. These structures define the dimensions and style of the controls in the dialog box.

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.

See Also

CreateDialogIndirect, CreateDialogIndirectParam, DialogBoxIndirect, DialogBoxIndirectParam, MapDialogRect


DOC_INFO_1
 DOC_INFO_1  QuickInfo

typedef struct _DOC_INFO_1 { // dci1

    LPTSTR pDocName;

    LPTSTR pOutputFile;

    LPTSTR pDatatype;

} DOC_INFO_1;

The DOC_INFO_1 structure describes a document that will be printed.

Members

pDocName

Points to a null-terminated string that specifies the name of the document.

pOutputFile

Points to a null-terminated string that specifies the name of an output file.

pDatatype

Points to a null-terminated string that identifies the type of data used to record the document.

See Also

StartDocPrinter


DOC_INFO_2 [New - Windows 95]
 DOC_INFO_2  QuickInfo

[New - Windows 95]

typedef struct _DOC_INFO_2 { // dci2

    LPTSTR pDocName;

    LPTSTR pOutputFile;

    LPTSTR pDatatype;

    DWORD  dwMode;

    DWORD  JobId;

} DOC_INFO_2;

The DOC_INFO_2 structure describes a document that will be printed.

Members

pDocName

Points to a null-terminated string that specifies the name of the document.

pOutputFile

Points to a null-terminated string that specifies the name of an output file.

pDatatype

Points to a null-terminated string that identifies the type of data used to record the document.

dwMode

Informs the print spooler of the nature of the data to follow. If this value is zero, the print spooler treats the data sent by subsequent calls to WritePrinter as a normal print job (whether or not it is spooled depends on the printer property). If this value is DI_CHANNEL, only a communications channel is opened. In this case, the data passed into subsequent calls to WritePrinter is sent to the printer or subsequent calls to ReadPrinter retrieve data from the printer. This mode remains effective until EndDoc is called.

JobId

Reserved for internal use; should be zero.

See Also

EndDoc, ReadPrinter, StartDocPrinter, WritePrinter


DOCINFO
 DOCINFO  QuickInfo

typedef struct {    // di

    int     cbSize;

    LPCTSTR lpszDocName;

    LPCTSTR lpszOutput;

    LPCTSTR lpszDatatype;   // Windows 95 only; ignored on Windows NT

    DWORD   fwType;         // Windows 95 only; ignored on Windows NT

} DOCINFO;

The DOCINFO structure contains the input and output filenames and other information used by the StartDoc function.

Members

cbSize

Specifies the size, in bytes, of the structure.

lpszDocName

Points to a null-terminated string that specifies the name of the document.

lpszOutput

Points to a null-terminated string that specifies the name of an output file. If this pointer is NULL, the output will be sent to the device identified by the device context handle that was passed to the StartDoc function.

lpszDatatype

Windows 95:

Points to a null-terminated string that specifies the type of data used to record the print job.

Windows NT:

This member is ignored.

fwType

Windows 95:

Specifies additional information about the print job. Can be zero or DI_APPBANDING if the application will use banding. For optimal performance during printing, banding applications should specify DI_APPBANDING.

Windows NT:

This member is ignored.

See Also

StartDoc


DRAGLISTINFO [New - Windows NT]
 DRAGLISTINFO  QuickInfo  Overview  Group

[New - Windows NT]

Typedef struct {

    UINT uNotification;

    HWND hWnd;

    POINT ptCursor;

} DRAGLISTINFO, FAR *LPDRAGLISTINFO;

The DRAGLISTINFO structure contains information about a drag event. The pointer to DRAGLISTINFO is passed as the lParam parameter of the drag list message.

Members

uNotification

Notification code that specifies the type of drag event. This member can be one of the following values:

Value	Meaning
DL_BEGINDRAG	The user has clicked the left mouse button on a list item.
DL_CANCELDRAG	The user has canceled the drag operation by clicking the right mouse button or pressing the ESC key.
DL_DRAGGING	The user has moved the mouse while dragging an item.
DL_DROPPED	The user has released the left mouse button, completing a drag operation.
hWnd

Handle to drag list box.

ptCursor

POINT structure that contains the current x- and y-coordinates of the mouse cursor.

See also

DL_BEGINDRAG, DL_CANCELDRAG, DL_DRAGGING, DL_DROPPED, POINT


DRAWITEMSTRUCT
 DRAWITEMSTRUCT  QuickInfo

typedef struct tagDRAWITEMSTRUCT {  // dis

    UINT  CtlType;

    UINT  CtlID;

    UINT  itemID;

    UINT  itemAction;

    UINT  itemState;

    HWND  hwndItem;

    HDC   hDC;

    RECT  rcItem;

    DWORD itemData;

} 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.

Members

CtlType

Specifies the control type. This member can be one of the following values:

Value	Meaning
ODT_BUTTON	Owner-drawn button
ODT_COMBOBOX	Owner-drawn combo box
ODT_LISTBOX	Owner-drawn list box
ODT_LISTVIEW	List view control
ODT_MENU	Owner-drawn menu item
ODT_STATIC	Owner-drawn static control
ODT_TAB	Tab control
CtlID

Specifies the identifier of the combo box, list box, button, or static control. This member is not used for a menu item.

itemID

Specifies the menu item identifier for a menu item or the index of the item in a list box or combo box. For an empty list box or combo box, this member can be −1. This allows the application to draw only the focus rectangle at the coordinates specified by the rcItem member even though there are no items in the control. This indicates to the user whether the list box or combo box has the focus. How the bits are set in the itemAction member determines whether the rectangle is to be drawn as though the list box or combo box has the focus.

itemAction

Specifies the drawing action required. This member can be one or more of the following values:

Value	Meaning
ODA_DRAWENTIRE	The entire control needs to be drawn.
ODA_FOCUS	The control has lost or gained the keyboard focus. The itemState member should be checked to determine whether the control has the focus.
ODA_SELECT	The selection status has changed. The itemState member should be checked to determine the new selection state.
itemState

Specifies the visual state of the item after the current drawing action takes place. This member can be a combination of the following values:

Value	Meaning
ODS_CHECKED	The menu item is to be checked. This bit is used only in a menu.
ODS_COMBOBOXEDIT	The drawing takes place in the selection field (edit control) of an ownerdrawn combo box.
ODS_DEFAULT	The item is the default item.
ODS_DISABLED	The item is to be drawn as disabled.
ODS_FOCUS	The item has the keyboard focus.
ODS_GRAYED	The item is to be grayed. This bit is used only in a menu.
ODS_SELECTED	The menu item's status is selected.
hwndItem

Identifies the control for combo boxes, list boxes, buttons, and static controls. For menus, this member identifies the menu containing the item.

hDC

Identifies 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. Windows automatically clips anything the owner window draws in the device context for combo boxes, list boxes, and buttons, but does not clip menu items. When drawing menu items, the owner window must not draw outside the boundaries of the rectangle defined by the rcItem member.

itemData

Specifies the application-defined 32-bit value associated with the menu item. For a control, this parameter specifies the value last assigned to the list box or combo box by the LB_SETITEMDATA or CB_SETITEMDATA message. If the list box or combo box has the LBS_HASSTRINGS or CBS_HASSTRINGS style, this value is initially zero. Otherwise, this value is initially the value that was passed to the list box or combo box in the lParam parameter of one of the following messages:

CB_ADDSTRING
CB_INSERTSTRING
LB_ADDSTRING
LB_INSERTSTRING

If ctlType is ODT_BUTTON or ODT_STATIC, itemData is zero.

See Also

CB_ADDSTRING, CB_INSERTSTRING, CB_SETITEMDATA, LB_ADDSTRING, LB_INSERTSTRING, SETITEMDATA, WM_DRAWITEM


DRAWTEXTPARAMS [New - Windows 95]
 DRAWTEXTPARAMS  QuickInfo

[New - Windows 95]

typedef struct {

    UINT cbSize;

    int  iTabLength;

    int  iLeftMargin;

    int  iRightMargin;

    UINT uiLengthDrawn;

} DRAWTEXTPARAMS, FAR *LPDRAWTEXTPARAMS;

The DRAWTEXTPARAMS structure contains extended formatting options for the DrawTextEx function.

Members

cbSize

Specifies the structure size, in bytes.

iTabLength

Specifies the size of each tab stop, in units equal to the average character width.

iLeftMargin

Specifies the left margin, in units equal to the average character width.

iRightMargin

Specifies the right margin, in units equal to the average character width.

uiLengthDrawn

Receives the number of characters processed by DrawTextEx, including white-space characters. The number can be the length of the string or the index of the first line that falls below the drawing area. Note that DrawTextEx always processes the entire string if the DT_NOCLIP formatting flag is specified.

See Also

DrawTextEx


DRIVE_LAYOUT_INFORMATION
 DRIVE_LAYOUT_INFORMATION  QuickInfo  Overview  Group

typedef struct _DRIVE_LAYOUT_INFORMATION {

   DWORD  PartitionCount;

   DWORD  Signature;

   PARTITION_INFORMATION  PartitionEntry[1];

} DRIVE_LAYOUT_INFORMATION;

The DRIVE_LAYOUT_INFORMATION structure provides information about a drive's partitions.

Members

PartitionCount

The number of partitions on the drive.

Signature

A drive signature value.

PartitionEntry

A variable-sized array of PARTITION_INFORMATION structures, one structure for each partition on the drive.

Remarks

The DeviceIoControl function receives a DRIVE_LAYOUT_INFORMATION structure in response to an IOCTL_DISK_GET_DRIVE_LAYOUT device I/O operation. The DeviceIoControl function  uses a DRIVE_LAYOUT_INFORMATION structure as input to an IOCTL_DISK_SET_DRIVE_LAYOUT device I/O operation.

See Also

DeviceIoControl, IOCTL_DISK_GET_DRIVE_LAYOUT, IOCTL_DISK_SET_DRIVE_LAYOUT, PARTITION_INFORMATION


DRIVER_INFO_1
 DRIVER_INFO_1  QuickInfo

typedef struct _DRIVER_INFO_1 { // dri1

    LPTSTR pName;

} DRIVER_INFO_1;

The DRIVER_INFO_1 structure identifies a printer driver.

Members

pName

Points to a null-terminated string that specifies the name of a printer driver.

See Also

EnumPrinterDrivers


DRIVER_INFO_2
 DRIVER_INFO_2  QuickInfo

typedef struct _DRIVER_INFO_2 { // dri2

    DWORD  cVersion;

    LPTSTR pName;

    LPTSTR pEnvironment;

    LPTSTR pDriverPath;

    LPTSTR pDataFile;

    LPTSTR pConfigFile;

} DRIVER_INFO_2;

The DRIVER_INFO_2 structure identifies a printer driver, the driver version number, the environment for which the driver was written, the name of the file in which the driver is stored, and so on.

Members

cVersion

Specifies a printer-driver version number.

pName

Points to a null-terminated string that specifies the name of the driver (for example, "QMS 810").

pEnvironment

Points to a null-terminated string that specifies the environment for which the driver was written (for example, "Windows NT x86" or "Windows NT R4000").

pDriverPath

Points to null-terminated string that specifies a filename or full path and filename for the file that contains the device driver (for example, "c:\drivers\pscript.dll").

pDataFile

Points to a null-terminated string that specifies a filename or a full path and filename for the file that contains driver data (for example, "c:\drivers\QMS810.PPD").

pConfigFile

Points to a null-terminated string that specifies a filename or a full path and filename for the device-driver's configuration DLL (for example, "c:\drivers\PSCRPTUI.DLL").

See Also

AddPrinterDriver, GetPrinterDriver


DRIVER_INFO_3 [New - Windows 95]
 DRIVER_INFO_3  QuickInfo

[New - Windows 95]

typedef struct _DRIVER_INFO_3 { // dri3

    DWORD  cVersion;

    LPTSTR pName;

    LPTSTR pEnvironment;

    LPTSTR pDriverPath;

    LPTSTR pDataFile;

    LPTSTR pConfigFile;

    LPTSTR pHelpFile;

    LPTSTR pDependentFiles;

    LPTSTR pMonitorName;

    LPTSTR pDefaultDataType;

} DRIVER_INFO_3;

The DRIVER_INFO_3 structure contains printer driver information.

Members

cVersion

Specifies a printer-driver version number.

pName

Points to a null-terminated string that specifies the name of the driver (for example, "QMS 810").

pEnvironment

Points to a null-terminated string that specifies the environment for which the driver was written (for example, "Windows x86" or "Windows NT R4000").

pDriverPath

Points to a null-terminated string that specifies a filename or full path and filename for the file that contains the device driver (for example, "C:\DRIVERS\PSCRIPT.DLL").

pDataFile

Points to a null-terminated string that specifies a filename or a full path and filename for the file that contains driver data (for example, "C:\DRIVERS\QMS810.PPD").

pConfigFile

Points to a null-terminated string that specifies a filename or a full path and filename for the device driver's configuration dynamic-link library (for example, "C:\DRIVERS\PSCRPTUI.DLL").

pHelpFile

Points to a null-terminated string that specifies a filename or a full path and filename for the device driver's help file.

pDependentFiles

Points to a null-terminated string that specifies the files the driver is dependent on. Each filename in the string is also terminated with a null (for example, "PSCRIPT.DLL\0QMS810.PPD\0PSCRPTUI.DLL\0PSPCRIPTUI.HLP\0PSTEST.TXT\0\0").

pMonitorName

Points to a null-terminated string that specifies a language monitor (for example, "PJL monitor"). This member can be NULL and should be specified only for printers capable of bidirectional communication.

pDefaultDataType

Points to a null-terminated string that specifies the default data type of the print job (for example, "EMF").

See Also

AddPrinterDriver, EnumPrinterDrivers, GetPrinterDriver


EDITSTREAM [New - Windows NT]
 EDITSTREAM  QuickInfo  Overview  Group

[New - Windows NT]

typedef struct _editstream {

    DWORD dwCookie;

    DWORD dwError;

    EDITSTREAMCALLBACK pfnCallback;

} EDITSTREAM;

The EDITSTREAM structure contains information about a data stream used with a rich edit control.

Members

dwCookie

Application-defined value that is passed to the callback function.

dwError

Error encountered while streaming. If there was no error, this member is zero.

pfnCallback

Pointer to an application-defined function that the control calls to transfer data.

This structure is used with the EM_STREAMIN message to read (stream in) data into a rich edit control, replacing its contents. It is used with the EM_STREAMOUT message to write (stream out) the contents of a rich edit control.

The control calls the callback function repeatedly, transferring a portion of the data with each call. The callback function has the following form:

DWORD CALLBACK EditStreamCallback(DWORD dwCookie,

    LPBYTE pbBuff, LONG cb, LONG FAR *pcb);

dwCookie

Value of the dwCookie member of the EDITSTREAM structure.

pbBuff

Pointer to the buffer to read from or write to.

cb

Count of bytes to read or write.

pcb

Pointer to a variable that receives the number of bytes actually read or written.

Return Value

The return value depends on direction. If data is streaming in, the return value is the number of bytes copied to the buffer, or zero if the transfer is complete.

If data is streaming out, the return value is a nonzero value to continue to the transfer operation, or zero to abort it.

See Also

EM_STREAMIN, EM_STREAMOUT


EMR
 EMR  QuickInfo  Overview  Group

typedef struct tagEMR
{
    DWORD iType;

    DWORD nSize;
} EMR, *PEMR;

The EMR structure provides the base structure for all enhanced metafile records. An enhanced metafile record contains the parameters for a specific GDI function used to create part of a picture in an enhanced format metafile.

Members

iType

Specifies the record type.

nSize

Size of the record, in bytes. This member must be a multiple of four.


EMRANGLEARC
 EMRANGLEARC  QuickInfo  Overview  Group

typedef struct tagEMRANGLEARC
{
    EMR     emr;
    POINTL  ptlCenter;

    DWORD   nRadius;
    FLOAT   eStartAngle;
    FLOAT   eSweepAngle;
} EMRANGLEARC, *PEMRANGLEARC;

The EMRANGLEARC structure contains members for the AngleArc enhanced metafile record.

Members

emr

Base structure for all record types.

ptlCenter

Logical coordinates of circle's center.

nRadius

Circle's radius, in logical units.

eStartAngle

Arc's start angle, in degrees.

eSweepAngle

Arc's sweep angle, in degrees.

See Also

AngleArc


EMRARC, EMRARCTO, EMRCHORD, EMRPIE
 EMRARC, EMRARCTO, EMRCHORD, EMRPIE  Overview  Group

typedef struct tagEMRARC
{
    EMR    emr;

    RECTL  rclBox;
    POINTL ptlStart;
    POINTL ptlEnd;
} EMRARC,   *PEMRARC,
  EMRARCTO, *PEMRARCTO,
  EMRCHORD, *PEMRCHORD,
  EMRPIE,   *PEMRPIE;

The EMRARC, EMRARCTO, EMRCHORD, and EMRPIE structures contain members for the Arc, ArcTo, Chord, and Pie enhanced metafile records.

Members

emr

Base structure for all record types.

rclBox

Bounding rectangle.

ptlStart

Coordinates of first radial ending point.

ptlEnd

Coordinates of second radial ending point.

See Also

Arc, ArcTo, Chord, Pie


EMRBITBLT
 EMRBITBLT  QuickInfo  Overview  Group

typedef struct tagEMRBITBLT
{
    EMR      emr;

    RECTL    rclBounds;

    LONG     xDest;

    LONG     yDest;

    LONG     cxDest;

    LONG     cyDest;

    DWORD    dwRop;

    LONG     xSrc;

    LONG     ySrc;

    XFORM    xformSrc;

    COLORREF crBkColorSrc;

    DWORD    iUsageSrc;

    DWORD    offBmiSrc;

    DWORD    offBitsSrc;

    DWORD    cbBitsSrc;

} EMRBITBLT, *PEMRBITBLT;

The EMRBITBLT structure contains members for the BitBlt enhanced metafile record. Note that graphics device interface (GDI) converts the device-dependent bitmap into a device-independent bitmap (DIB) before storing it in the metafile record.

Members

emr

Base structure for all record types.

rclBounds

Bounding rectangle, in device units.

xDest

Logical x-coordinate of the upper-left corner of the destination rectangle.

yDest

Logical y-coordinate of the upper-left corner of the destination rectangle.

dwRop

Raster-operation code. These codes define how the color data of the source rectangle is to be combined with the color data of the destination rectangle to achieve the final color.

xSrc

Logical x-coordinate of the upper-left corner of the source rectangle.

ySrc

Logical y-coordinate of the upper-left corner of the source rectangle.

xformSrc

World-space to page-space transformation of the source device context.

crBkColorSrc

Background color (the RGB value) of the source device context.

iUsageSrc

Value of the bmiColors member of the BITMAPINFO structure. The iUsageSrc member can be either the DIB_PAL_COLORS, DIB_PAL_INDICES or DIB_RGB_COLORS value.

offBmiSrc

Offset to source BITMAPINFO structure.

cbBmiSrc

Size of source BITMAPINFO structure.

offBitsSrc

Offset to source bitmap bits.

cbBitsSrc

Size of source bitmap bits.

See Also

BitBlt, BITMAPINFO, RGB


EMRCREATEBRUSHINDIRECT
 EMRCREATEBRUSHINDIRECT  QuickInfo  Overview  Group

typedef struct tagEMRCREATEBRUSHINDIRECT
{
    EMR      emr;

    DWORD    ihBrush;

    LOGBRUSH lb;

} EMRCREATEBRUSHINDIRECT, *PEMRCREATEBRUSHINDIRECT;

The EMRCREATEBRUSHINDIRECT structure contains members for the CreateBrushIndirect enhanced metafile record.

Members

emr

Base structure for all record types.

ihBrush

Index of brush in handle table.

lb

LOGBRUSH structure containing information about the brush. The lbStyle member must be either the BS_SOLID, BS_HOLLOW, BS_NULL, or BS_HATCHED value.

CreateBrushIndirect, LOGBRUSH


EMRCREATECOLORSPACE [New - Windows 95]
 EMRCREATECOLORSPACE  QuickInfo  Overview  Group

[New - Windows 95]

typedef struct tagEMRCREATECOLORSPACE
{
    EMR           emr;

    DWORD         ihCS;

    LOGCOLORSPACE lcs;

} EMRCREATECOLORSPACE, *PEMRCREATECOLORSPACE;

The EMRCREATECOLORSPACE structure contains members for the CreateColorSpace enhanced metafile record.

Members

emr

Base structure for all record types

ihCS

Index of the color cpace in handle table

lcs

Logical color space

See Also

CreateColorSpace


EMRCREATEDIBPATTERNBRUSHPT
 EMRCREATEDIBPATTERNBRUSHPT  QuickInfo  Overview  Group

typedef struct tagEMRCREATEDIBPATTERNBRUSHPT
{
    EMR   emr;

    DWORD ihBrush;

    DWORD iUsage;

    DWORD offBmi;

    DWORD cbBmi;

    DWORD offBits;

    DWORD cbBits;

} EMRCREATEDIBPATTERNBRUSHPT,
PEMRCREATEDIBPATTERNBRUSHPT;

The EMRCREATEDIBPATTERNBRUSHPT structure contains members for the CreateDIBPatternBrushPt enhanced metafile record. The BITMAPINFO structure is followed by the bitmap bits that form a packed device-independent bitmap (DIB).

Members

emr

Base structure for all record types.

ihBrush

Index of brush in handle table.

iUsage

Value specifying whether the bmiColors member of the BITMAPINFO structure was provided and, if so, whether bmiColors contains explicit red, green, blue (RGB) values or indices. The iUsage member must be either the DIB_PAL_COLORS, DIB_PAL_INDICES, or DIB_RGB_COLORS value.

offBmi

Offset to BITMAPINFO structure.

cbBmi

Size of BITMAPINFO structure.

offBits

Offset to bitmap bits.

cbBits

Size of bitmap bits.

See Also

BITMAPINFO, CreateDIBPatternBrushPt, RGB


EMRCREATEMONOBRUSH
 EMRCREATEMONOBRUSH  QuickInfo  Overview  Group

typedef struct tagEMRCREATEMONOBRUSH
{
    EMR   emr;

    DWORD ihBrush;

    DWORD iUsage;

    DWORD offBmi;

    DWORD cbBmi;

    DWORD offBits;

    DWORD cbBits;

} EMRCREATEMONOBRUSH, *PEMRCREATEMONOBRUSH;

The EMRCREATEMONOBRUSH structure contains members for the CreatePatternBrush (when passed a monochrome bitmap) or CreateDIBPatternBrush (when passed a monochrome DIB) enhanced metafile records.

Members

emr

Base structure for all record types.

ihBrush

Index of brush in handle table.

iUsage

Value specifying whether the bmiColors member of the BITMAPINFO structure was provided and, if so, whether bmiColors contains explicit red, green, blue (RGB) values or indices. The iUsage member must be either the DIB_PAL_COLORS, DIB_PAL_INDICES, or DIB_RGB_COLORS value.

offBmi

Offset to BITMAPINFO structure.

cbBmi

Size of BITMAPINFO structure.

offBits

Offset to bitmap bits.

cbBits

Size of bitmap bits.

See Also

BITMAPINFO, CreateDIBPatternBrush, CreatePatternBrush, RGB


EMRCREATEPALETTE
 EMRCREATEPALETTE  QuickInfo  Overview  Group

typedef struct tagEMRCREATEPALETTE
{
    EMR        emr;

    DWORD      ihPal;

    LOGPALETTE lgpl;

} EMRCREATEPALETTE, *PEMRCREATEPALETTE;

The EMRCREATEPALETTE structure contains members for the CreatePalette enhanced metafile record.

Members

emr

Base structure for all record types.

ihPal

Index of palette in handle table.

lgpl

LOGPALETTE structure that contains information about the palette. Note that peFlags members in the PALETTEENTRY structures do not contain any flags.

See Also

CreatePalette, LOGPALETTE, PALETTEENTRY


EMRCREATEPEN
 EMRCREATEPEN  QuickInfo  Overview  Group

typedef struct tagEMRCREATEPEN
{
    EMR    emr;

    DWORD  ihPen;

    LOGPEN lopn;

} EMRCREATEPEN, *PEMRCREATEPEN;

The EMRCREATEPEN structure contains members for the CreatePen enhanced metafile record.

Members

emr

Base structure for all record types

ihPen

Index to pen in handle table

lopn

Logical pen

See Also

CreatePen


EMRELLIPSE, EMRRECTANGLE
 EMRELLIPSE, EMRRECTANGLE  Overview  Group

typedef struct tagEMRELLIPSE
{
    EMR   emr;

    RECTL rclBox;

} EMRELLIPSE,  *PEMRELLIPSE,
  EMRRECTANGLE, *PEMRRECTANGLE;

The EMRELLIPSE and EMRRECTANGLE structures contain members for the Ellipse and Rectangle enhanced metafile records.

Members

emr

Base structure for all record types.

rclBox

Bounding rectangle.

See Also

Ellipse, Rectangle


EMREOF
 EMREOF  QuickInfo  Overview  Group

typedef struct tagEMREOF
{
    EMR     emr;
    DWORD   nPalEntries;

    DWORD   offPalEntries;

    DWORD   nSizeLast;

} EMREOF, *PEMREOF;

The EMREOF structure contains data for the enhanced metafile record that indicates the end of the metafile.

Members

emr

Base structure for all record types.

nPalEntries

Number of palette entries.

offPalEntires

Offset to palette entries.

nSizeLast

Same size as the nSize member of the EMR structure. This member must be the last doubleword of the record. If palette entries exist, they precede this member.

See Also

EMR


EMREXCLUDECLIPRECT, EMRINTERSECTCLIPRECT
 EMREXCLUDECLIPRECT, EMRINTERSECTCLIPRECT  Overview  Group

typedef struct tagEMREXCLUDECLIPRECT
{
    EMR   emr;      // base structure for all record types
    RECTL rclClip;  // clipping rectangle
} EMREXCLUDECLIPRECT,   *PEMREXCLUDECLIPRECT,
  EMRINTERSECTCLIPRECT, *PEMRINTERSECTCLIPRECT;

The EMREXCLUDECLIPRECT and EMRINTERSECTCLIPRECTstructures contain members for the ExcludeClipRect and IntersectClipRect enhanced metafile records.

Members

emr

Base structure for all record types.

rclClip

Clipping rectangle.

ExcludeClipRect, IntersectClipRect


EMREXTCREATEFONTINDIRECTW
 EMREXTCREATEFONTINDIRECTW  QuickInfo  Overview  Group

typedef struct tagEMREXTCREATEFONTINDIRECTW
{
    EMR         emr;

    DWORD       ihFont;

    EXTLOGFONTW elfw;

} EMREXTCREATEFONTINDIRECTW,
PEMREXTCREATEFONTINDIRECTW;

The EMREXTCREATEFONTINDIRECTW structure contains members for the CreateFontIndirect enhanced metafile record.

Members

emr

Base structure for all record types.

ihFont

Index to the font in handle table.

elfw

Logical font.

See Also

CreateFontIndirect


EMREXTCREATEPEN
 EMREXTCREATEPEN  QuickInfo  Overview  Group

typedef struct tagEMREXTCREATEPEN
{
    EMR       emr;

    DWORD     ihPen;

    DWORD     offBmi;

    DWORD     cbBmi;

    DWORD     offBits;

    DWORD     cbBits;

    EXTLOGPEN elp;

} EMREXTCREATEPEN, *PEMREXTCREATEPEN;

The EMREXTCREATEPEN structure contains members for the ExtCreatePen enhanced metafile record. If the record contains a BITMAPINFO structure, it is followed by the bitmap bits that form a packed device-independent bitmap (DIB).

Members

emr

Base structure for all record types.

ihPen

Index to pen in handle table.

offBmi

Offset to BITMAPINFO structure, if any.

cbBmi

Size of BITMAPINFO structure, if any.

offBits

Offset to brush bitmap bits, if any.

cbBits

Size of brush bitmap bits, if any.

elp

Extended logical pen, including the elpStyleEntry member of the EXTLOGPEN structure.

See Also

BITMAPINFO, ExtCreatePen, EXTLOGPEN


EMREXTFLOODFILL
 EMREXTFLOODFILL  QuickInfo  Overview  Group

typedef struct tagEMREXTFLOODFILL
{
    EMR     emr;

    POINTL  ptlStart;

    COLORREF crColor;

    DWORD   iMode;

} EMREXTFLOODFILL, *PEMREXTFLOODFILL;

The EMREXTFLOODFILL structure contains members for the ExtFloodFill enhanced metafile record.

Members

emr

Base structure for all record types.

ptlStart

Coordinates where filling begins.

crColor

Color of fill.

iMode

Type of fill operation to be performed. This member must be either the FLOODFILLBORDER or FLOODFILLSURFACE value.

See Also

ExtFloodFill


EMREXTSELECTCLIPRGN
 EMREXTSELECTCLIPRGN  QuickInfo  Overview  Group

typedef struct tagEMREXTSELECTCLIPRGN
{
    EMR   emr;

    DWORD cbRgnData;

    DWORD iMode;

    BYTE  RgnData[1]; //

} EMREXTSELECTCLIPRGN, *PEMREXTSELECTCLIPRGN;

The EMREXTSELECTCLIPRGN structure contains members for the ExtSelectClipRgn enhanced metafile record.

Members

emr

Base structure for all record types.

cbRgnData

Size of region data, in bytes.

iMode

Operation to be performed. This member must be one of the following values: RGN_AND, RGN_COPY, RGN_DIFF, RGN_OR, or RGN_XOR.

See Also

ExtSelectClipRgn


EMREXTTEXTOUTA, EMREXTTEXTOUTW
 EMREXTTEXTOUTA, EMREXTTEXTOUTW  Overview  Group

typedef struct tagEMREXTTEXTOUTA
{
    EMR     emr;

    RECTL   rclBounds;

    DWORD   iGraphicsMode;

    FLOAT   exScale;

    FLOAT   eyScale;
    EMRTEXT emrtext;

} EMREXTTEXTOUTA, *PEMREXTTEXTOUTA,
  EMREXTTEXTOUTW, *PEMREXTTEXTOUTW;

The EMREXTTEXTOUTA and EMREXTTEXTOUTW structures contain members for the ExtTextOut, TextOut, or DrawText enhanced metafile records.

Members

emr

Base structure for all record types.

rclBounds

Bounding rectangle, in device units.

iGraphicsMode

Current graphics mode. This member can be either the GM_COMPATIBLE or GM_ADVANCED value.

exScale

X-scaling factor from page units to .01mm units if the graphics mode is the GM_COMPATIBLE value.

eyScale

Y-scaling factor from page units to .01mm units if the graphics mode is the GM_COMPATIBLE value.

emrtext

EMRTEXT structure, which is followed by the string and the intercharacter spacing array.

See Also

DrawText, ExtTextOut, TextOut, EMRTEXT


EMRFILLPATH, EMRSTROKEANDFILLPATH, EMRSTROKEPATH
 EMRFILLPATH, EMRSTROKEANDFILLPATH, EMRSTROKEPATH  Overview  Group

typedef struct tagEMRFILLPATH
{
    EMR   emr;

    RECTL rclBounds;

} EMRFILLPATH,          *PEMRFILLPATH,
  EMRSTROKEANDFILLPATH, *PEMRSTROKEANDFILLPATH,
  EMRSTROKEPATH,        *PEMRSTROKEPATH;

The EMRFILLPATH, EMRSTROKEANDFILLPATH, and EMRSTROKEPATH structures contain members for the FillPath, StrokeAndFillPath, and StrokePath enhanced metafile records.

Members

emr

Base structure for all record types.

rclBounds

Bounding rectangle, in device units.

See Also

FillPath, StrokeAndFillPath, StrokePath


EMRFILLRGN
 EMRFILLRGN  QuickInfo  Overview  Group

typedef struct tagEMRFILLRGN
{
    EMR   emr;

    RECTL rclBounds;

    DWORD cbRgnData;

    DWORD ihBrush;

    BYTE  RgnData[1];

} EMRFILLRGN, *PEMRFILLRGN;

The EMRFILLRGN structure contains members for the FillRgn enhanced metafile record.

Members

emr

Base structure for all record types.

rclBounds

Bounding rectangle, in device units.

cbRgnData

Size of region data, in bytes.

ihBrush

Index of brush, in handle table.

RgnData

Buffer containing RGNDATA structure.

See Also

FillRgn, RGNDATA


EMRFORMAT
 EMRFORMAT  QuickInfo

typedef struct tagEMRFORMAT   {

    DWORD   dSignature;

    DWORD   nVersion;

    DWORD   cbData;

    DWORD   offData;

} EMRFORMAT;

The EMRFORMAT structure contains information that identifies graphics data in an enhanced metafile. A GDICOMMENT_MULTIFORMATS enhanced metafile public comment contains an array of EMRFORMAT structures.

Members

dSignature

Contains a picture format identifier. The following identifier values are defined:

Identifier	Meaning
ENHMETA_SIGNATURE	The picture is in enhanced metafile format.
0x46535045	The picture is in encapsulated PostScript file format.
nVersion

Contains a picture version number. The following version number value is defined:

Version	Meaning
1	This is the version number of a level 1 encapsulated PostScript file.
cbData

Specifies the size, in bytes, of the picture data.

offData

Specifies an offset to the picture data. The offset is figured from the start of the GDICOMMENT_MULTIFORMATS public comment within which this EMRFORMAT structure is embedded. The offset must be a DWORD offset.

Remarks

GdiComment discusses enhanced metafile public comments in general, and the GDICOMMENT_MULTIFORMATS public comment in particular.

See Also

GdiComment


EMRFRAMERGN
 EMRFRAMERGN  QuickInfo  Overview  Group

typedef struct tagEMRFRAMERGN
{
    EMR   emr;

    RECTL rclBounds;

    DWORD cbRgnData;

    DWORD ihBrush;

    SIZEL szlStroke;

    BYTE  RgnData[1];

} EMRFRAMERGN, *PEMRFRAMERGN;

The EMRFRAMERGN structure contains members for the FrameRgn enhanced metafile record.

Members

emr

Base structure for all record types.

rclBounds

Bounding rectangle, in device units.

cbRgnData

Size of region data, in bytes.

ihBrush

Index of brush, in handle table.

szlStroke

Width and height of region frame.

RgnData

Buffer containing RGNDATA structure.

See Also

FrameRgn, RGNDATA


EMRGDICOMMENT
 EMRGDICOMMENT  QuickInfo  Overview  Group

typedef struct tagEMRGDICOMMENT
{
    EMR   emr;

    DWORD cbData;

    BYTE  Data[1];

} EMRGDICOMMENT, *PEMRGDICOMMENT;

The EMRGDICOMMENT structure contains application-specific data. This enhanced metafile record is only meaningful to applications that know the format of the data and how to utilize it. This record is ignored by graphics device interface (GDI) during playback of the enhanced metafile.

Members

emr

Base structure for all record types.

cbData

Size of data buffer, in bytes.

Data[1]

Application-specific data.


EMRINVERTRGN, EMRPAINTRGN
 EMRINVERTRGN, EMRPAINTRGN  Overview  Group

typedef struct tagEMRINVERTRGN
{
    EMR   emr;

    RECTL rclBounds;

    DWORD cbRgnData;

    BYTE  RgnData[1];

} EMRINVERTRGN, *PEMRINVERTRGN,
  EMRPAINTRGN,  *PEMRPAINTRGN;

The EMRINVERTRGN and EMRPAINTRGN structures contain members for the InvertRgn and PaintRgn enhanced metafile records.

Members

emr

Base structure for all record types.

rclBounds

Bounding rectangle, in device units.

cbRgnData

Size of region data, in bytes.

RgnData

Buffer containing RGNDATA structure.

See Also

InvertRgn, PaintRgn


EMRLINETO, EMRMOVETOEX
 EMRLINETO, EMRMOVETOEX  Overview  Group

typedef struct tagEMRLINETO
{
    EMR    emr;

    POINTL ptl;

} EMRLINETO,   *PEMRLINETO,
  EMRMOVETOEX, *PEMRMOVETOEX;

The EMRLINETO and EMRMOVETOEX structures contains members for the LineTo and MoveToEx enhanced metafile records.

Members

emr

Base structure for all record types.

ptl

Coordinates of the line's ending point for the LineTo function or coordinates of the new current position for the MoveToEx function.

See Also

LineTo, MoveToEx


EMRMASKBLT
 EMRMASKBLT  QuickInfo  Overview  Group

typedef struct tagEMRMASKBLT
{
    EMR     emr;

    RECTL   rclBounds;

    LONG    xDest;

    LONG    yDest;

    LONG    cxDest;

    LONG    cyDest;

    DWORD   dwRop;

    LONG    xSrc;

    LONG    ySrc;

    XFORM   xformSrc;

    COLORREF crBkColorSrc;

    DWORD   iUsageSrc;

    DWORD   offBmiSrc;

    DWORD   cbBmiSrc;

    DWORD   offBitsSrc;

    DWORD   cbBitsSrc;

    LONG    xMask;

    LONG    yMask;

    DWORD   iUsageMask;

    DWORD   offBmiMask;

    DWORD   cbBmiMask;

    DWORD   offBitsMask;

    DWORD   cbBitsMask;

} EMRMASKBLT, *PEMRMASKBLT;

The EMRMASKBLT structure contains members for the MaskBlt enhanced metafile record. Note that graphics device interface (GDI) converts the device-dependent bitmap into a device-independent bitmap (DIB) before storing it in the metafile record.

Members

emr

Base structure for all record types.

rclBounds

Bounding rectangle, in device units.

xDest

Logical x-coordinate of the upper-left corner of the destination rectangle.

yDest

Logical y-coordinate of the upper-left corner of the destination rectangle.

cxDest

Logical width of destination rectangle

cyDest

Logical height of destination rectangle

dwRop

Raster-operation code. These codes define how the color data of the source rectangle is to be combined with the color data of the destination rectangle to achieve the final color.

xSrc

Logical x-coordinate of the upper-left corner of the source rectangle.

ySrc

Logical y-coordinate of the upper-left corner of the source rectangle.

xformSrc

World-space to page-space transformation of the source device context.

crBkColorSrc

Background color (the RGB value) of the source device context.

iUsageSrc

Value of the bmiColors member of the source BITMAPINFO structure. The iUsageSrc member can be either the DIB_PAL_COLORS, DIB_PAL_INDICES, or DIB_RGB_COLORS value.

offBmiSrc

Offset to source BITMAPINFO structure.

cbBmiSrc

Size of source BITMAPINFO structure.

offBitsSrc

Offset to source bitmap bits.

cbBitsSrc

Size of source bitmap bits.

xMask

Horizontal pixel offset into mask bitmap

yMask

Vertical pixel offset into mask bitmap

iUsageMask

Value of the bmiColors member of the mask BITMAPINFO structure.

offBmiMask

Offset to mask BITMAPINFO structure.

cbBmiMask

Size of mask BITMAPINFO structure.

offBitsMask

Offset to mask bitmap bits.

cbBitsMask

Size of mask bitmap bits.

See Also

BITMAPINFO, MaskBlt, RGB


EMRMODIFYWORLDTRANSFORM
 EMRMODIFYWORLDTRANSFORM  QuickInfo  Overview  Group

typedef struct tagEMRMODIFYWORLDTRANSFORM
{
    EMR   emr;

    XFORM xform;

    DWORD iMode;

transformation
} EMRMODIFYWORLDTRANSFORM,
PEMRMODIFYWORLDTRANSFORM;

The EMRMODIFYWORLDTRANSFORM structure contains members for the ModifyWorldTransform enhanced metafile record.

Members

emr

Base structure for all record types.

xform

World-space to page-space transformation data.

iMode

Value specifying how the transformation data modifies the current world transformation. This member can be one of the following values: MWT_IDENTITY, MWT_LEFTMULTIPLY, or MWT_RIGHTMULTIPLY.

See Also

ModifyWorldTransform


EMROFFSETCLIPRGN
 EMROFFSETCLIPRGN  QuickInfo  Overview  Group

typedef struct tagEMROFFSETCLIPRGN
{
    EMR    emr;

    POINTL ptlOffset;

} EMROFFSETCLIPRGN, *PEMROFFSETCLIPRGN;

The EMROFFSETCLIPRGN structure contains members for the OffsetClipRgn enhanced metafile record.

Members

emr

Base structure for all record types.

ptlOffset

Logical coordinates of offset.

See Also

OffsetClipRgn


EMRPLGBLT
 EMRPLGBLT  QuickInfo  Overview  Group

typedef struct tagEMRPLGBLT
{
    EMR      emr;

    RECTL    rclBounds;

    POINTL   aptlDest[3];

    LONG    xSrc;

    LONG    ySrc;

    LONG     cxSrc;

    LONG     cySrc;

    XFORM   xformSrc;

    COLORREF crBkColorSrc;

    DWORD    iUsageSrc;

    DWORD    offBmiSrc;

    DWORD   cbBmiSrc;

    DWORD   offBitsSrc;

    DWORD   cbBitsSrc;

    LONG    xMask;
    LONG    yMask;

    DWORD   iUsageMask;

    DWORD   offBmiMask;

    DWORD   cbBmiMask;
    DWORD   offBitsMask;
    DWORD   cbBitsMask;
} EMRPLGBLT, *PEMRPLGBLT;

The EMRPLGBLT structure contains members for the PlgBlt enhanced metafile record. Note that graphics device interface (GDI) converts the device-dependent bitmap into a device-independent bitmap (DIB) before storing it in the metafile record.

Members

emr

Base structure for all record types.

rclBounds

Bounding rectangle, in device units.

aptlDest

Array of three points in logical space that identify three corners of the destination parallelogram. The upper-left corner of the source rectangle is mapped to the first point in this array, the upper-right corner to the second point in this array, and the lower-left corner to the third point. The lower-right corner of the source rectangle is mapped to the implicit fourth point in the parallelogram.

xSrc

Logical x-coordinate of the upper-left corner of the source rectangle.

ySrc

Logical y-coordinate of the upper-left corner of the source rectangle.

cxSrc

Logical width of source

cySrc

Logical height of source

xformSrc

World-space to page-space transformation of the source device context.

crBkColorSrc

Background color (the RGB value) of the source device context.

iUsageSrc

Value of the bmiColors member of the BITMAPINFO structure. The iUsageSrc member can be either the DIB_PAL_COLORS, DIB_PAL_INDICES, or DIB_RGB_COLORS value.

offBmiSrc

Offset to source BITMAPINFO structure.

cbBmiSrc

Size of source BITMAPINFO structure.

offBitsSrc

Offset to source bitmap bits.

cbBitsSrc

Size of source bitmap bits.

xMask

Horizontal pixel offset into mask bitmap.

yMask

Vertical pixel offset into mask bitmap.

iUsageMask

Value of the bmiColors member of the mask BITMAPINFO structure.

offBmiMask

Offset to mask BITMAPINFO structure.

cbBmiMask

Size of mask BITMAPINFO structure.

offBitsMask

Offset to mask bitmap bits.

cbBitsMask

Size of mask bitmap bits.

See Also

BITMAPINFO, PlgBlt, RGB


EMRPOLYDRAW
 EMRPOLYDRAW  QuickInfo  Overview  Group

typedef struct tagEMRPOLYDRAW
{
    EMR    emr;

    RECTL  rclBounds;

    DWORD  cptl;

    POINTL aptl[1];

    BYTE   abTypes[1];

} EMRPOLYDRAW, *PEMRPOLYDRAW;

The EMRPOLYDRAW structure contains members for the PolyDraw enhanced metafile record.

Members

emr

Base structure for all record types.

rclBounds

Bounding rectangle, in device units.

cptl

Number of points.

aptl

Array of 32-bit points.

abTypes

Array of values that specifies how each point in the aptl array is used. This member can be one of the following values: PT_MOVETO, PT_LINETO, or PT_BEZIERTO. The PT_LINETO or PT_BEZIERTO value can be combined with the PT_CLOSEFIGURE value by using the bitwise-xOR operator.

See Also

PolyDraw


EMRPOLYDRAW16
 EMRPOLYDRAW16  QuickInfo  Overview  Group

typedef struct tagEMRPOLYDRAW16
{
    EMR    emr;

    RECTL  rclBounds;

    DWORD  cpts;

    POINTS apts[1];

    BYTE   abTypes[1];

} EMRPOLYDRAW16, *PEMRPOLYDRAW16;

The EMRPOLYDRAW16 structure contains members for the PolyDraw enhanced metafile record.

Members

emr

Base structure for all record types.

rclBounds

Bounding rectangle, in device units.

cpts

Number of points.

apts

Array of 16-bit points.

abTypes

Array of values that specifies how each point in the apts array is used. This member can be one of the following values: PT_MOVETO, PT_LINETO, or PT_BEZIERTO. The PT_LINETO or PT_BEZIERTO value can be combined with the PT_CLOSEFIGURE value by using the bitwise-OR operator.

See Also

PolyDraw


EMRPOLYLINE, EMRPOLYBEZIER, EMRPOLYGON, EMRPOLYBEZIERTO, EMRPOLYLINETO  [New - Windows 95]
 EMRPOLYLINE, EMRPOLYBEZIER, EMRPOLYGON, EMRPOLYBEZIERTO, EMRPOLYLINETO  Overview  Group

[New - Windows 95]

typedef struct tagEMRPOLYLINE
{
    EMR    emr;
    RECTL  rclBounds;

    DWORD  cptl;

    POINTL aptl[1];

} EMRPOLYLINE,     *PEMRPOLYLINE,
  EMRPOLYBEZIER,   *PEMRPOLYBEZIER,
  EMRPOLYGON,      *PEMRPOLYGON,
  EMRPOLYBEZIERTO, *PEMRPOLYBEZIERTO,
  EMRPOLYLINETO,   *PEMRPOLYLINETO;

The EMRPOLYLINE, EMRPOLYBEZIER, EMRPOLYGON, EMRPOLYBEZIERTO, and EMRPOLYLINETO structures contain members for the Polyline, PolyBezier, Polygon, PolyBezierTo, and PolylineTo enhanced metafile records.

Members

emr

Base structure for all record types.

rclBounds

Bounding rectangle, in device units.

cptl

Number of points array.

aptl

Array of 32-bit points.

See Also

PolyBezier, PolyBezierTo, Polygon, Polyline, PolylineTo


EMRPOLYLINE16, EMRPOLYBEZIER16, EMRPOLYGON16, EMRPOLYBEZIERTO16, EMRPOLYLINETO16
 EMRPOLYLINE16, EMRPOLYBEZIER16, EMRPOLYGON16, EMRPOLYBEZIERTO16, EMRPOLYLINETO16  Overview  Group

typedef struct tagEMRPOLYLINE
{
    EMR    emr;

    RECTL  rclBounds;

    DWORD  cpts;

    POINTL apts[1];

} EMRPOLYLINE16,     *PEMRPOLYLINE16,
  EMRPOLYBEZIER16,   *PEMRPOLYBEZIER16,
  EMRPOLYGON16,      *PEMRPOLYGON16,
  EMRPOLYBEZIERTO16, *PEMRPOLYBEZIERTO16,
  EMRPOLYLINETO16,   *PEMRPOLYLINETO16;

The EMRPOLYLINE16, EMRPOLYBEZIER16, EMRPOLYGON16, EMRPOLYBEZIERTO16, and EMRPOLYLINETO16 structures contain members for the Polyline, PolyBezier, Polygon, PolyBezierTo, and PolylineTo enhanced metafile records.

Members

emr

Base structure for all record types.

rclBounds

Bounding rectangle, in device units.

cpts

Number of points in the array.

apts

Array of 16-bit points.

See Also

PolyBezier, PolyBezierTo, Polygon, Polyline, PolylineTo


EMRPOLYPOLYLINE, EMRPOLYPOLYGON
 EMRPOLYPOLYLINE, EMRPOLYPOLYGON  Overview  Group

typedef struct tagEMRPOLYPOLYLINE
{
    EMR     emr;

    RECTL   rclBounds;

    DWORD   nPolys;

    DWORD   cptl;

    DWORD   aPolyCounts[1];

    POINTL  aptl[1];

} EMRPOLYPOLYLINE, *PEMRPOLYPOLYLINE,
  EMRPOLYPOLYGON,  *PEMRPOLYPOLYGON;

The EMRPOLYPOLYLINE and EMRPOLYPOLYGON structures contain members for the PolyPolyline and PolyPolygon enhanced metafile records.

Members

emr

Base structure for all record types.

rclBounds

Bounding rectangle, in device units.

nPolys

Number of polys.

cpt1

Total number of points in all polys.

aPolyCounts

Array of point counts for each poly.

aptl

Array of 32-bit points.

See Also

PolyPolyline, PolyPolygon


EMRPOLYPOLYLINE16, EMRPOLYPOLYGON16
 EMRPOLYPOLYLINE16, EMRPOLYPOLYGON16  Overview  Group

typedef struct tagEMRPOLYPOLYLINE16
{
    EMR     emr;

    RECTL   rclBounds;
    DWORD   nPolys;

    DWORD   cpts;

    DWORD   aPolyCounts[1];

    POINTS  apts[1];

} EMRPOLYPOLYLINE16, *PEMRPOLYPOLYLINE16,
  EMRPOLYPOLYGON16,  *PEMRPOLYPOLYGON16;

The EMRPOLYPOLYLINE16 and EMRPOLYPOLYGON16 structures contain members for the PolyPolyline and PolyPolygon enhanced metafile records.

Members

emr

Base structure for all record types.

rclBounds

Bounding rectangle, in device units.

nPolys

Number of polys.

cpt1

Total number of points in all polys.

aPolyCounts

Array of point counts for each poly.

aptl

Array of 16-bit points.

See Also

PolyPolyline, PolyPolygon


EMRPOLYTEXTOUTA, EMRPOLYTEXTOUTW
 EMRPOLYTEXTOUTA, EMRPOLYTEXTOUTW  Overview  Group

typedef struct tagEMRPOLYTEXTOUTA
{
    EMR     emr;

    RECTL   rclBounds;

    DWORD   iGraphicsMode;

    FLOAT   exScale;

    FLOAT   eyScale;

    LONG    cStrings;

    EMRTEXT aemrtext[1];

} EMRPOLYTEXTOUTA, *PEMRPOLYTEXTOUTA,
  EMRPOLYTEXTOUTW, *PEMRPOLYTEXTOUTW;

The EMRPOLYTEXTOUTA and EMRPOLYTEXTOUTW structures contain members for the PolyTextOut enhanced metafile record.

Members

emr

Base structure for all record types.

rclBounds

Bounding rectangle, in device units.

iGraphicsMode

Current graphics mode. This member can be either the GM_COMPATIBLE or GM_ADVANCED value.

exScale

X-scaling factor from page units to .01mm units if the graphics mode is the GM_COMPATIBLE value.

eyScale

Y-scaling factor from page units to .01mm units if the graphics mode is the GM_COMPATIBLE value.

cStrings

Number of strings.

aemrtext

EMRTEXT structure, which is followed by the string and the intercharacter spacing array.

See Also

EMRTEXT


EMRRESIZEPALETTE
 EMRRESIZEPALETTE  QuickInfo  Overview  Group

typedef struct tagEMRRESIZEPALETTE
{
    EMR   emr;

    DWORD ihPal;

    DWORD cEntries;

} EMRRESIZEPALETTE, *PEMRRESIZEPALETTE;

The EMRRESIZEPALETTE structure contains members for the ResizePalette enhanced metafile record.

Members

emr

Base structure for all record types.

ihPal

Index of palette in handle table.

cEntries

Number of entries in palette after resizing.

See Also

ResizePalette


EMRRESTOREDC
 EMRRESTOREDC  QuickInfo  Overview  Group

typedef struct tagEMRRESTOREDC
{
    EMR  emr;

    LONG iRelative;

} EMRRESTOREDC, *PEMRRESTOREDC;

The EMRRESTOREDC structure contains members for the RestoreDC enhanced metafile record.

Members

emr

Base structure for all record types.

iRelative

Relative instance to restore.

See Also

RestoreDC


EMRROUNDRECT
 EMRROUNDRECT  QuickInfo  Overview  Group

typedef struct tagEMRROUNDRECT
{
    EMR   emr;

    RECTL rclBox;

    SIZEL szlCorner;

} EMRROUNDRECT, *PEMRROUNDRECT;

The EMRROUNDRECT structure contains members for the RoundRect enhanced metafile record.

Members

emr

Base structure for all record types.

szlCorner

Width and height of the ellipse used to draw rounded corners.

See Also

RoundRect


EMRSCALEVIEWPORTEXTEX, EMRSCALEWINDOWEXTEX
 EMRSCALEVIEWPORTEXTEX, EMRSCALEWINDOWEXTEX  Overview  Group

typedef struct tagEMRSCALEVIEWPORTEXTEX
{
    EMR  emr;

    LONG xNum;

    LONG xDenom;

    LONG yNum;

    LONG yDenom;

} EMRSCALEVIEWPORTEXTEX, *PEMRSCALEVIEWPORTEXTEX,

  EMRSCALEWINDOWEXTEX,   *PEMRSCALEWINDOWEXTEX;

The EMRSCALEVIEWPORTEXTEX and EMRSCALEWINDOWEXTEX structures contain members for the ScaleViewportExtEx and ScaleWindowExtEx enhanced metafile records.

Members

emr

Base structure for all record types.

xNum

Horizontal multiplicand.

xDenom

Horizontal divisor.

yNum

Vertical multiplicand.

yDenom

Vertical divisor.

See Also

ScaleViewportExtEx, ScaleWindowExtEx


EMRSELECTCOLORSPACE, EMRDELETECOLORSPACE [New - Windows 95]
 EMRSELECTCOLORSPACE, EMRDELETECOLORSPACE  Overview  Group

[New - Windows 95]

typedef struct tagEMRSELECTCOLORSPACE

{

    EMR     emr;

    DWORD   ihCS;

} EMRSELECTCOLORSPACE, *PEMRSELECTCOLORSPACE,
  EMRDELETECOLORSPACE, *PEMRDELETECOLORSPACE;

The EMRSELECTCOLORSPACE and EMRDELETECOLORSPACE structures contain members for the SelectColorSpace and DeleteColorSpace enhanced metafile records.

Members

emr

Base structure for all record types.

ihCS

Color space handle index.

See Also

DeleteColorSpace


EMRSELECTOBJECT, EMRDELETEOBJECT
 EMRSELECTOBJECT, EMRDELETEOBJECT  Overview  Group

typedef struct tagEMRSELECTOBJECT
{
    EMR   emr;

    DWORD ihObject;
} EMRSELECTOBJECT, *PEMRSELECTOBJECT,
  EMRDELETEOBJECT, *PEMRDELETEOBJECT;

The EMRSELECTOBJECT and EMRDELETEOBJECT structures contain members for the SelectObject and DeleteObject enhanced metafile records.

Members

emr

Base structure for all record types.

ihObject

Index of object in handle table.

See Also

SelectObject, DeleteObject


EMRSELECTPALETTE
 EMRSELECTPALETTE  QuickInfo  Overview  Group

typedef struct tagEMRSELECTPALETTE

{
    EMR   emr;

    DWORD ihPal;

} EMRSELECTPALETTE, *PEMRSELECTPALETTE;

The EMRSELECTPALETTE structure contains members for the SelectPalette enhanced metafile record. Note that the bForceBackground parameter in SelectPalette is always recorded as TRUE, which causes the palette to be realized as a background palette.

Members

emr

Base structure for all record types.

ihPal

Index to logical palette in handle table.

See Also

SelectPalette


EMRSETARCDIRECTION
 EMRSETARCDIRECTION  QuickInfo  Overview  Group

typedef struct tagEMRSETARCDIRECTION
{
    EMR   emr;

    DWORD iArcDirection;
} EMRSETARCDIRECTION, *PEMRSETARCDIRECTION;

The EMRSETARCDIRECTION structure contains members for the SetArcDirection enhanced metafile record.

Members

emr

Base structure for all record types.

iArcDirection

Arc direction. This member can be either the AD_CLOCKWISE or AD_COUNTERCLOCKWISE value.

See Also

Arc, SetArcDirection


EMRSETBKCOLOR, EMRSETTEXTCOLOR
 EMRSETBKCOLOR, EMRSETTEXTCOLOR  Overview  Group

typedef struct tagEMRSETTEXTCOLOR
{
    EMR      emr;

    COLORREF crColor;

} EMRSETBKCOLOR,   *PEMRSETBKCOLOR,
  EMRSETTEXTCOLOR, *PEMRSETTEXTCOLOR;

The EMRSETBKCOLOR and EMRSETTEXTCOLOR structures contain members for the SetBkColor and SetTextColor enhanced metafile records.

Members

emr

Base structure for all record types.

crColor

Color value.

See Also

SetBkColor, SetTextColor


EMRSETCOLORADJUSTMENT
 EMRSETCOLORADJUSTMENT  QuickInfo  Overview  Group

typedef struct tagEMRSETCOLORADJUSTMENT
{
    EMR  emr;

    COLORADJUSTMENT ColorAdjustment;

} EMRSETCOLORADJUSTMENT, *PEMRSETCOLORADJUSTMENT;

The EMRSETCOLORADJUSTMENT structure contains members for the SetColorAdjustment enhanced metafile record.

Members

emr

Base structure for all record types.

ColorAdjustment

COLORADJUSTMENT structure.

See Also

SetColorAdjustment


EMRSETDIBITSTODEVICE
 EMRSETDIBITSTODEVICE  QuickInfo  Overview  Group

typedef struct tagEMRSETDIBITSTODEVICE
{
    EMR   emr;

    RECTL rclBounds;

    LONG  xDest;

    LONG  yDest;

    LONG  xSrc;

    LONG  ySrc;

    LONG  cxSrc;

    LONG  cySrc;

    DWORD offBmiSrc;

    DWORD cbBmiSrc;

    DWORD offBitsSrc;

    DWORD cbBitsSrc;

    DWORD iUsageSrc;

    DWORD iStartScan;

    DWORD cScans;

} EMRSETDIBITSTODEVICE, *PEMRSETDIBITSTODEVICE;

The EMRSETDIBITSTODEVICE structure contains members for the SetDIBitsToDevice enhanced metafile record.

Members

emr

Base structure for all record types.

rclBounds

Bounding rectangle, in device units.

xDest

Logical x-coordinate of the upper-left corner of the destination rectangle.

yDest

Logical y-coordinate of the upper-left corner of the destination rectangle.

xSrc

Logical x-coordinate of the lower-left corner of the source device-independent bitmap (DIB).

ySrc

Logical y-coordinate of the lower-left corner of the source DIB.

cxSrc

Width of source rectangle.

cyScr

Height of source rectangle.

offBmiSrc

Offset to source BITMAPINFO structure.

cbBmiSrc

Size of source BITMAPINFO structure.

offBitsSrc

Offset to source bitmap bits.

cbBitsSrc

Size of source bitmap bits.

iUsageSrc

Value of the bmiColors member of the BITMAPINFO structure. The iUsageSrc member can be either the DIB_PAL_COLORS, DIB_PAL_INDICES, or DIB_RGB_COLORS value.

iStartScan

First scan line in array.

cScans

Number of scan lines.

See Also

BITMAPINFO, SetDIBitsToDevice


EMRSETMAPPERFLAGS
 EMRSETMAPPERFLAGS  QuickInfo  Overview  Group

typedef struct tagEMRSETMAPPERFLAGS
{
    EMR   emr;

    DWORD dwFlags;

} EMRSETMAPPERFLAGS, *PEMRSETMAPPERFLAGS;

The EMRSETMAPPERFLAGS structure contains members for the SetMapperFlags enhanced metafile record.

Members

emr

Base structure for all record types.

dwFlags

Font mapper flag.

See Also

SetMapperFlags


EMRSETMITERLIMIT
 EMRSETMITERLIMIT  QuickInfo  Overview  Group

typedef struct tagEMRSETMITERLIMIT
{
    EMR   emr;
    FLOAT eMiterLimit;

} EMRSETMITERLIMIT, *PEMRSETMITERLIMIT;

The EMRSETMITERLIMIT structure contains members for the SetMiterLimit enhanced metafile record.

Members

emr

Base structure for all record types.

eMiterLimit

New miter limit.

See Also

SetMiterLimit


EMRSETPALETTEENTRIES
 EMRSETPALETTEENTRIES  QuickInfo  Overview  Group

typedef struct tagEMRSETPALETTEENTRIES
{
    EMR          emr;

    DWORD        ihPal;

    DWORD        iStart;

    DWORD        cEntries;

    PALETTEENTRY aPalEntries[1];

} EMRSETPALETTEENTRIES, *PEMRSETPALETTEENTRIES;

The EMRSETPALETTEENTRIES structure contains members for the SetPaletteEntries enhanced metafile record.

Members

emr

Base structure for all record types.

ihPal

Palette handle index.

iStart

Index of first entry to set.

cEntries

Number of entries.

aPalEntries

Array of PALETTEENTRY structures. Note that peFlags members in the structures do not contain any flags.

See Also

PALETTEENTRY, SetPaletteEntries


EMRSETPIXELV
 EMRSETPIXELV  QuickInfo  Overview  Group

typedef struct tagEMRSETPIXELV
{
    EMR     emr;

    POINTL  ptlPixel;

    COLORREF crColor;

} EMRSETPIXELV, *PEMRSETPIXELV;

The EMRSETPIXELV structure contains members for the SetPixelV enhanced metafile record. When an enhanced metafile is created, calls to SetPixel are also recorded in this record.

Members

emr

Base structure for all record types.

ptlPixel

Logical coordinates of pixel.

crColor

Color value.

SetPixelV, SetPixel


EMRSETVIEWPORTEXTEX, EMRSETWINDOWEXTEX
 EMRSETVIEWPORTEXTEX, EMRSETWINDOWEXTEX  Overview  Group

typedef struct tagEMRSETVIEWPORTEXTEX
{
    EMR   emr;

    SIZEL szlExtent;

} EMRSETVIEWPORTEXTEX, *PEMRSETVIEWPORTEXTEX,
  EMRSETWINDOWEXTEX,   *PEMRSETWINDOWEXTEX;

The EMRSETVIEWPORTEXTEX and EMRSETWINDOWEXTEX structures contains members for the SetViewportExtEx and SetWindowExtEx enhanced metafile records.

Members

emr

Base structure for all record types.

szlExtent

Horizontal and vertical extents. For SetViewportExtEx, the extents are in device units, and for SetWindowExtEx, the extents are in logical units.

SetViewportExtEx, SetWindowExtEx


EMRSETVIEWPORTORGEX, EMRSETWINDOWORGEX, EMRSETBRUSHORGEX
 EMRSETVIEWPORTORGEX, EMRSETWINDOWORGEX, EMRSETBRUSHORGEX  Overview  Group

typedef struct tagEMRSETVIEWPORTORGEX
{
    EMR    emr;

    POINTL ptlOrigin;

} EMRSETVIEWPORTORGEX, *PEMRSETVIEWPORTORGEX,
  EMRSETWINDOWORGEX,   *PEMRSETWINDOWORGEX,
  EMRSETBRUSHORGEX,    *PEMRSETBRUSHORGEX;

The EMRSETVIEWPORTORGEX, EMRSETWINDOWORGEX, and EMRSETBRUSHORGEX structures contain members for the SetViewportOrgEx, SetWindowOrgEx, and SetBrushOrgEx enhanced metafile records.

Members

emr

Base structure for all record types.

ptlOrigin

Coordinate of origin.

See Also

SetBrushOrgEx, SetViewportOrgEx, SetWindowOrgEx


EMRSETWORLDTRANSFORM
 EMRSETWORLDTRANSFORM  QuickInfo  Overview  Group

typedef struct tagEMRSETWORLDTRANSFORM
{
    EMR   emr;

    XFORM xform;

} EMRSETWORLDTRANSFORM, *PEMRSETWORLDTRANSFORM;

The EMRSETWORLDTRANSFORM structure contains members for the SetWorldTransform enhanced metafile record.

Members

emr

Base structure for all record types.

xform

World-space to page-space transformation data.

See Also

SetWorldTransform


EMRSTRETCHBLT
 EMRSTRETCHBLT  QuickInfo  Overview  Group

typedef struct tagEMRSTRETCHBLT
{
    EMR      emr;

    RECTL    rclBounds;

    LONG     xDest;

    LONG     yDest;

    LONG     cxDest;

    LONG     cyDest;

    DWORD    dwRop;

    LONG     xSrc;

    LONG     ySrc;

    XFORM    xformSrc;

    COLORREF crBkColorSrc;

    DWORD    iUsageSrc;

    DWORD    offBmiSrc;

    DWORD    cbBmiSrc;

    DWORD    offBitsSrc;

    DWORD    cbBitsSrc;

    LONG     cxSrc;

    LONG     cySrc;

} EMRSTRETCHBLT, *PEMRSTRETCHBLT;

The EMRSTRETCHBLT structure contains members for the StretchBlt enhanced metafile record. Note that graphics device interface (GDI) converts the device-dependent bitmap into a device-independent bitmap (DIB) before storing it in the metafile record.

Members

emr

Base structure for all record types.

rclBounds

Bounding rectangle, in device units.

xDest

Logical x-coordinate of the upper-left corner of the destination rectangle.

yDest

Logical y-coordinate of the upper-left corner of the destination rectangle.

cxDest

Logical width of destination rectangle

cyDest

Logical height of destination rectangle

dwRop

Raster-operation code. These codes define how the color data of the source rectangle is to be combined with the color data of the destination rectangle to achieve the final color.

xSrc

Logical x-coordinate of the upper-left corner of the source rectangle.

ySrc

Logical y-coordinate of the upper-left corner of the source rectangle.

xformSrc

World-space to page-space transformation of the source device context.

crBkColorSrc

Background color (the RGB value) of the source device context.

iUsageSrc

Value of the bmiColors member of the BITMAPINFO structure. The iUsageSrc member can be either the DIB_PAL_COLORS, DIB_PAL_INDICES, or DIB_RGB_COLORS value.

offBmiSrc

Offset to source BITMAPINFO structure.

cbBmiSrc

Size of source BITMAPINFO structure.

offBitsSrc

Offset to source bitmap bits.

cbBitsSrc

Size of source bitmap bits.

cxSrc

Width of source rectangle.

cySrc

Height of source rectangle.

See Also

BITMAPINFO, RGB, StretchBlt


EMRSTRETCHDIBITS
 EMRSTRETCHDIBITS  QuickInfo  Overview  Group

typedef struct tagEMRSTRETCHDIBITS
{
    EMR   emr;
    RECTL rclBounds;

    LONG  xDest;

    LONG  yDest;

    LONG  xSrc;

    LONG  ySrc;

    LONG  cxSrc;

    LONG  cySrc;
    DWORD offBmiSrc;
    DWORD cbBmiSrc;

    DWORD offBitsSrc;

    DWORD cbBitsSrc;

    DWORD iUsageSrc;

    DWORD dwRop;

    LONG  cxDest;

    LONG  cyDest;

} EMRSTRETCHDIBITS, *PEMRSTRETCHDIBITS;

The EMRSTRETCHDIBITS structure contains members for the StretchDIBits enhanced metafile record.

Members

emr

Base structure for all record types.

rclBounds

Bounding rectangle, in device units.

xDest

Logical x-coordinate of the upper-left corner of the destination rectangle.

yDest

Logical y-coordinate of the upper-left corner of the destination rectangle.

xSrc

Logical x-coordinate of the upper-left corner of the source rectangle.

ySrc

Logical y-coordinate of the upper-left corner of the source rectangle.

cxSrc

Width of source rectangle.

cyScr

Height of source rectangle.

offBmiSrc

Offset to source BITMAPINFO structure.

cbBmiSrc

Size of source BITMAPINFO structure.

offBitsSrc

Offset to source bitmap bits.

cbBitsSrc

Size of source bitmap bits.

iUsageSrc

Value of the bmiColors member of the BITMAPINFO structure. The iUsageSrc member can be either the DIB_PAL_COLORS, DIB_PAL_INDICES, or DIB_RGB_COLORS value.

dwRop

Raster-operation code. These codes define how the color data of the source rectangle is to be combined with the color data of the destination rectangle to achieve the final color.

cxDest

Logical width of destination rectangle

cyDest

Logical height of destination rectangle

See Also

BITMAPINFO, StretchDIBits


EMRTEXT
 EMRTEXT  QuickInfo  Overview  Group

typedef struct tagEMRTEXT

{
    POINTL ptlReference;

    DWORD  nChars;

    DWORD  offString;

    DWORD  fOptions;

    RECTL  rcl;

    DWORD  offDx;

} EMRTEXT, *PEMRTEXT;

The EMRTEXT structure contains members for text output.

Members

ptlReference

Logical coordinates of the reference point used to position the string.

nChars

Number of characters in string.

offString

Offset to string.

fOptions

Value specifying how to use the application-defined rectangle. This member can be a combination of the ETO_CLIPPED and ETO_OPAQUE values.

rcl

Optional clipping and/or opaquing rectangle.

offDx

Offset to intercharacter spacing array.

Remarks

The EMRTEXT structure is used as a member in the EMREXTTEXTOUT and EMRPOLYTEXTOUT structures.


 Enhanced Metafile Records with No Parameters

typedef struct tagABORTPATH

{

    EMR emr;

} EMRABORTPATH,      *PEMRABORTPATH,
  EMRBEGINPATH,      *PEMRBEGINPATH,
  EMRENDPATH,        *PEMRENDPATH,
  EMRCLOSEFIGURE,    *PEMRCLOSEFIGURE,
  EMRFLATTENPATH,    *PEMRFLATTENPATH,
  EMRWIDENPATH,      *PEMRWIDENPATH,
  EMRSETMETARGN,     *PEMRSETMETARGN,
  EMRSAVEDC,         *PEMRSAVEDC,
  EMRREALIZEPALETTE, *PEMRREALIZEPALETTE;

Contains data for the AbortPath, BeginPath, EndPath, CloseFigure, FlattenPath, WidenPath, SetMetaRgn, SaveDC, and RealizePalette enhanced metafile records.


 Enhanced Metafile Records with One Parameter

typedef struct tagEMRSELECTCLIPPATH
{
    EMR   emr;

    DWORD iMode;

} EMRSELECTCLIPPATH,    *PEMRSELECTCLIPPATH,
  EMRSETBKMODE,         *PEMRSETBKMODE,
  EMRSETMAPMODE,        *PEMRSETMAPMODE,
  EMRSETPOLYFILLMODE,   *PEMRSETPOLYFILLMODE,
  EMRSETROP2,           *PEMRSETROP2,
  EMRSETSTRETCHBLTMODE, *PEMRSETSTRETCHBLTMODE,
  EMRSETTEXTALIGN,	      *PEMRSETTEXTALIGN,
  EMRENABLEICM, 	      *PEMRENABLEICM

Contains parameters for the SelectClipPath, SetBkMode, SetPolyFillMode, SetROP2, SetStretchBltMode, SetTextAlign, and EnableICM enhanced metafile records.

Members

emr

Base structure for all record types.

iMode

Value and meaning that varies depending on the function contained in the enhanced metafile record. For a description of this member, see the documentation of the functions contained in this record .

See Also

SelectClipPath, SetBkMode, SetPolyFillMode, SetROP2, SetStretchBltMode, SetTextAlign


ENCORRECTTEXT
 ENCORRECTTEXT  QuickInfo

typedef struct _encorrecttext {
    NMHDR nmhdr;     // notification header
    CHARRANGE chrg;  // current selection
    WORD seltyp;     // selection type
} ENCORRECTTEXT;

Contains information about the selected text to be corrected.

Members

seltyp

Value specifying the contents of the new selection. This member is SEL_EMPTY if the selection is empty or one or more of the following values:

Value	Meaning
SEL_TEXT	Text
SEL_OBJECT	At least one OLE object
SEL_MULTICHAR	More than one character of text
SEL_MULTIOBJECT	More than one OLE object


ENDROPFILES [New - Windows NT]
 ENDROPFILES  QuickInfo  Overview  Group

[New - Windows NT]

typedef struct _endropfiles {

    NMHDR nmhdr;

    HANDLE hDrop;

    LONG cp;

    BOOL fProtected;

} 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.

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).

See Also

DragFinish, DragQueryFile, DragQueryPoint, EN_DROPFILES, WM_DROPFILES


ENHMETAHEADER
 ENHMETAHEADER  QuickInfo

typedef struct tagENHMETAHEADER { // enmh

    DWORD iType;

    DWORD nSize;

    RECTL rclBounds;

    RECTL rclFrame;

    DWORD dSignature;

    DWORD nVersion;

    DWORD nBytes;

    DWORD nRecords;

    WORD  nHandles;

    WORD  sReserved;

    DWORD nDescription;

    DWORD offDescription;

    DWORD nPalEntries;

    SIZEL szlDevice;

    SIZEL szlMillimeters;

} ENHMETAHEADER;

The ENHMETAHEADER structure contains enhanced-metafile data such as the dimensions of the picture stored in the enhanced metafile, the count of records in the enhanced metafile, the resolution of the device on which the picture was created, and so on.

This structure is always the first record in an enhanced metafile.

Members

iType

Specifies the record type. This member must specify the value assigned to the EMR_HEADER constant.

nSize

Specifies the structure size, in bytes.

rclBounds

Specifies the dimensions, in device units, of the smallest rectangle that can be drawn around the picture stored in the metafile. This rectangle is supplied by graphics device interface (GDI). Its dimensions include the right and bottom edges.

rclFrame

Specifies the dimensions, in .01 millimeter units, of a rectangle that surrounds the picture stored in the metafile. This rectangle must be supplied by the application that creates the metafile. Its dimensions include the right and bottom edges.

dSignature

Specifies a doubleword signature. This member must specify the value assigned to the ENHMETA_SIGNATURE constant.

nVersion

Specifies the metafile version. The current version value is 0x10000.

nBytes

Specifies the size of the enhanced metafile, in bytes.

nRecords

Specifies the number of records in the enhanced metafile.

nHandles

Specifies the number of handles in the enhanced-metafile handle table. (Index zero in this table is reserved.)

sReserved

Reserved; must be zero.

nDescription

Specifies the number of characters in the array that contains the description of the enhanced metafile's contents. This member should be set to zero if the enhanced metafile does not contain a description string.

offDescription

Specifies the offset from the beginning of the ENHMETAHEADER structure to the array that contains the description of the enhanced metafile's contents. This member should be set to zero if the enhanced metafile does not contain a description string.

nPalEntries

Specifies the number of entries in the enhanced metafile's palette.

szlDevice

Specifies the resolution of the reference device, in pixels.

szlMillimeters

Specifies the resolution of the reference device, in millimeters.

See Also

ENHMETARECORD


ENHMETARECORD
 ENHMETARECORD  QuickInfo

typedef struct tagENHMETARECORD { // enmr

    DWORD iType;

    DWORD nSize;

    DWORD dParm[1];

} ENHMETARECORD;

The ENHMETARECORD structure contains data that describes a graphics device interface (GDI) function used to create part of a picture in an enhanced-format metafile.

Members

iType

Specifies the record type.

nSize

Specifies the size of the record, in bytes.

dParm

Specifies an array of parameters passed to the GDI function identified by the record.

See Also

ENHMETAHEADER


ENOLEOPFAILED
 ENOLEOPFAILED  QuickInfo  Overview  Group

typedef struct {
    NMHDR nmhdr;
    LONG iob;
    LONG lOper;
    HRESULT hr;
} ENOLEOPFAILED;

Contains information about a failed OLE operation.

Members

nmhdr

Notification header.

iob

Object index.

lOper

OLE operation that failed. This can be OLEOP_DOVERB to indicate that IOleObject::DoVerb failed.

hr

Error code returned by the object on the operation.

See Also

EN_OLEOPFAILED, IOleObject::DoVerb


ENPROTECTED [New - Windows NT]
 ENPROTECTED  QuickInfo  Overview  Group

[New - Windows NT]

typedef struct _enprotected {

    NMHDR nmhdr;

    _WPAD _wPad1;

    UINT msg;

    _WPAD _wPad2;

    WPARAM wParam;

    LPARAM lParam;

    CHARRANGE chrg;

} 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.

Members

nmhdr

Notification header.

msg

Message that triggered the notification.

wParam

wParam parameter of the message.

lParam

lParam parameter of the message.

chrg

Current selection.

See Also

EN_PROTECTED


ENSAVECLIPBOARD
 ENSAVECLIPBOARD  QuickInfo  Overview  Group

typedef struct {
    NMHDR nmhdr;
    LONG cObjectCount;
    LONG cch;
} ENSAVECLIPBOARD;

Contains information about objects and text on the clipboard.

Members

nmhdr

Notification header.

cObjectCount

Number of objects on the clipboard.

cch

Number of characters on the clipboard.


ENUM_SERVICE_STATUS
 ENUM_SERVICE_STATUS  QuickInfo

typedef struct _ENUM_SERVICE_STATUS { // ess

    LPTSTR lpServiceName;

    LPTSTR lpDisplayName;

    SERVICE_STATUS ServiceStatus;

} ENUM_SERVICE_STATUS, *LPENUM_SERVICE_STATUS;

The ENUM_SERVICE_STATUS structure is used by the EnumDependentServices and EnumServicesStatus functions to return the name of a service in a service control manager database and to return information about that service.

Members

lpServiceName

Points to a null-terminated string that names a service in a service control manager database. The maximum string length is 256 characters. The service control manager database preserves the case of the characters, but service name comparisons are always case insensitive. A slash (/), backslash (\), comma, and space are invalid service name characters.

lpDisplayName

Points to a null-terminated string that is to be used by user interface programs to identify the service. This string has a maximum length of 256 characters. The name is case-preserved in the Service Control Manager. Display name comparisons are always case-insensitive.

ServiceStatus

Specifies a SERVICE_STATUS structure in which status information about the lpServiceName service is returned.

See Also

EnumDependentServices, EnumServicesStatus, SERVICE_STATUS


ENUMLOGFONT
 ENUMLOGFONT  QuickInfo

typedef struct tagENUMLOGFONT { // elf

    LOGFONT elfLogFont;

    BCHAR    elfFullName[LF_FULLFACESIZE];

    BCHAR    elfStyle[LF_FACESIZE];

} ENUMLOGFONT;

The ENUMLOGFONT structure defines the attributes of a font, the complete name of a font, and the style of a font.

Members

elfLogFont

Specifies a LOGFONT structure that defines the attributes of a font.

elfFullName

Specifies a unique name for the font. For example, "ABCD Font Company TrueType Bold Italic Sans Serif".

elfStyle

Specifies the style of the font. For example, "Bold Italic".

See Also

EnumFontFamProc, LOGFONT


ENUMLOGFONTEX [New - Windows 95]
 ENUMLOGFONTEX  QuickInfo

[New - Windows 95]

typedef struct tagENUMLOGFONTEX {
    LOGFONT  elfLogFont;
    BCHAR  elfFullName[LF_FULLFACESIZE];
    BCHAR  elfStyle[LF_FACESIZE];
    BCHAR  elfScript[LF_FACESIZE];
} ENUMLOGFONTEX;

The ENUMLOGFONTEX structure contains information about an enumerated font.

Members

elfLogFont

Specifies a LOGFONT structure that contains values defining the font attributes.

elfFullName

Specifies a null-terminated string specifying the unique name of the font. For example, "ABC Font Company TrueType Bold Italic Sans Serif".

elfStyle

Specifies a null-terminated string specifying the style of the font. For example, "Bold Italic".

elfScript

Specifies a null-terminated string specifying the script of the font. For example, "Cyrillic".

See Also

EnumFontFamExProc, EnumFontFamiliesEx, LOGFONT


EVENTLOGRECORD
 EVENTLOGRECORD  QuickInfo

typedef struct _EVENTLOGRECORD { // evlr

    DWORD  Length;

    DWORD  Reserved;

    DWORD  RecordNumber;

    DWORD  TimeGenerated;

    DWORD  TimeWritten;

    DWORD  EventID;

    WORD   EventType;

    WORD   NumStrings;

    WORD   EventCategory;

    WORD   ReservedFlags;

    DWORD  ClosingRecordNumber;

    DWORD  StringOffset;

    DWORD  UserSidLength;

    DWORD  UserSidOffset;

    DWORD  DataLength;

    DWORD  DataOffset;

    //

    // Then follow:

    //

    // TCHAR SourceName[]

    // TCHAR Computername[]

    // SID   UserSid

    // TCHAR Strings[]

    // BYTE  Data[]

    // CHAR  Pad[]

    // DWORD Length;

    //

} EVENTLOGRECORD;

The EVENTLOGRECORD structure contains information about an event record.

Members

Length

Specifies the length, in bytes, of this event record. Note that this value is stored at both ends of the entry to ease moving forward or backward through the log. The length includes any pad bytes inserted at the end of the record for DWORD alignment.

Reserved

Reserved.

RecordNumber

Contains a record number that can be used with the EVENTLOG_SEEK_READ flag passed in a call to the ReadEventLog function to begin reading at a specified record.

TimeGenerated

The time at which this entry was submitted. This time is measured in the number of seconds elapsed since 00:00:00 January 1, 1970.

TimeWritten

Specifies the time at which this entry was received by the service to be written to the logfile. This time is measured in the number of seconds elapsed since 00:00:00 January 1, 1970.

EventID

Identifies the event. This is specific to the source that generated the event log entry, and is used, together with SourceName, to identify a message in a message file that is presented to the user while viewing the log.

EventType

Specifies the type of event. This member can be one of the following values:

Value	Meaning
EVENTLOG_ERROR_TYPE	Error event
EVENTLOG_WARNING_TYPE	Warning event
EVENTLOG_INFORMATION_TYPE	Information event
EVENTLOG_AUDIT_SUCCESS	Success Audit event
EVENTLOG_AUDIT_FAILURE	Failure Audit event
For more information about event types, see Event Logging.

NumStrings

Specifies the number of strings present in the log (at the position indicated by StringOffset). These strings are merged into the message before it is displayed to the user.

EventCategory

Specifies a subcategory for this event. This subcategory is source specific.

ReservedFlags

Reserved.

ClosingRecordNumber

Reserved.

StringOffset

Specifies the offset of the strings within this event log entry.

UserSidLength

Specifies the length, in bytes, of the UserSid member. This value can be zero if no security identifier was provided.

UserSidOffset

Specifies the offset of the security identifier within this event record.

DataLength

Specifies the length, in bytes, of the event-specific data (at the position indicated by DataOffset).

DataOffset

Specifies the offset of the event-specific information within this log. This information could be something specific (a disk driver might log the number of retries, for example), followed by binary information specific to the event being logged and to the source that generated the entry.

SourceName

Contains the variable-length null-terminated string specifying the name of the source (application, service, driver, subsystem) that generated the entry. This is the name used to retrieve from the registry the name of the file containing the message strings for this source. It is used, together with the event identifier, to get the message string that describes this event.

Computername

Contains the variable-length null-terminated string specifying the name of the computer that generated this event. There may also be some pad bytes after this field to ensure that the UserSid is aligned on a DWORD boundary.

UserSid

Specifies the security identifier of the active user at the time this event was logged. This member may be empty if the UserSidLength member is zero.

The defined members are followed by the replacement strings for the message identified by the event identifier, the binary information, some pad bytes to make sure the full entry is on a DWORD boundary, and finally the length of the log entry again. Because the strings and the binary information can be of any length, no structure members are defined to reference them.

The event identifier together with SourceName and a language identifier identify a message string that describes the event in more detail. The strings are used as replacement strings and are merged into the message string to make a complete message. The message strings are contained in a message file specified in the source entry in the registry.

The binary information is information that is specific to the event. It could be the contents of the processor registers when a device driver got an error, a dump of an invalid packet that was received from the network, a dump of all the structures in a program (when the data area was detected to be corrupt), and so on. This information should be useful to the writer of the device driver or the application in tracking down bugs or unauthorized breaks into the application.

See Also

ReadEventLog


EVENTMSG
 EVENTMSG  QuickInfo

typedef struct tagEVENTMSG {    // em

    UINT  message;

    UINT  paramL;

    UINT  paramH;

    DWORD time;

    HWND  hwnd;

} EVENTMSG;

The EVENTMSG structure contains information about a hardware message sent to the system message queue. This structure is used to store message information for the JournalPlaybackProc callback function.

Members

message

Specifies the message.

paramL

Specifies additional information about the message. The exact meaning depends on the message value.

paramH

Specifies additional information about the message. The exact meaning depends on the message value.

time

Specifies the time at which the message was posted.

hwnd

Identifies the window to which the message was posted.

See Also

JournalPlaybackProc, SetWindowsHookEx


EXCEPTION_DEBUG_INFO
 EXCEPTION_DEBUG_INFO  QuickInfo

typedef struct _EXCEPTION_DEBUG_INFO { // exdi

    EXCEPTION_RECORD ExceptionRecord;

    DWORD dwFirstChance;

} EXCEPTION_DEBUG_INFO;

The EXCEPTION_DEBUG_INFO structure contains exception information that can be used by a debugger.

Members

ExceptionRecord

Contains an EXCEPTION_RECORD structure with information specific to the exception. This includes the exception code, flags, address, a pointer to a related exception, extra parameters, and so on.

dwFirstChance

Indicates whether the debugger has previously encountered the exception specified by the ExceptionRecord member. If the dwFirstChance member is nonzero, this is the first time the debugger has encountered the exception. Debuggers typically handle breakpoint and single-step exceptions when they are first encountered. If this member is zero, the debugger has previously encountered the exception. This occurs only if, during the search for structured exception handlers, either no handler was found or the exception was continued.

See Also

DEBUG_EVENT, EXCEPTION_RECORD


EXCEPTION_POINTERS
 EXCEPTION_POINTERS  QuickInfo

typedef struct _EXCEPTION_POINTERS { // exp

    PEXCEPTION_RECORD ExceptionRecord;

    PCONTEXT ContextRecord;

} EXCEPTION_POINTERS;

The EXCEPTION_POINTERS structure contains an exception record with a machine-independent description of an exception and a context record with a machine-dependent description of the processor context at the time of the exception.

Members

ExceptionRecord

Points to an EXCEPTION_RECORD structure that contains a machine-independent description of the exception.

ContextRecord

Points to a CONTEXT structure that contains a processor-specific description of the state of the processor at the time of the exception.

See Also

GetExceptionInformation, CONTEXT, EXCEPTION_RECORD


EXCEPTION_RECORD
 EXCEPTION_RECORD  QuickInfo

typedef struct _EXCEPTION_RECORD { // exr

    DWORD ExceptionCode;

    DWORD ExceptionFlags;

    struct _EXCEPTION_RECORD *ExceptionRecord;

    PVOID ExceptionAddress;

    DWORD NumberParameters;

    DWORD ExceptionInformation[EXCEPTION_MAXIMUM_PARAMETERS];

} EXCEPTION_RECORD;

The EXCEPTION_RECORD structure describes an exception.

Members

ExceptionCode

Specifies the reason the exception occurred. This is the code generated by a hardware exception, or the code specified in the RaiseException function for a software-generated exception. Following are the exception codes likely to occur due to common programming errors:

Value	Meaning
EXCEPTION_ACCESS_VIOLATION
	The thread tried to read from or write to a virtual address for which it does not have the appropriate access.
EXCEPTION_ARRAY_BOUNDS_EXCEEDED
	The thread tried to access an array element that is out of bounds and the underlying hardware supports bounds checking.
EXCEPTION_BREAKPOINT
	A breakpoint was encountered.
EXCEPTION_DATATYPE_MISALIGNMENT
	The thread tried to read or write data that is misaligned on hardware that does not provide alignment. For example, 16-bit values must be aligned on 2-byte boundaries; 32-bit values on 4-byte boundaries, and so on.
EXCEPTION_FLT_DENORMAL_OPERAND
	One of the operands in a floating-point operation is denormal. A denormal value is one that is too small to represent as a standard floating-point value.
EXCEPTION_FLT_DIVIDE_BY_ZERO
	The thread tried to divide a floating-point value by a floating-point divisor of zero.
EXCEPTION_FLT_INEXACT_RESULT
	The result of a floating-point operation cannot be represented exactly as a decimal fraction.
EXCEPTION_FLT_INVALID_OPERATION
	This exception represents any floating-point exception not included in this list.
EXCEPTION_FLT_OVERFLOW
	The exponent of a floating-point operation is greater than the magnitude allowed by the corresponding type.
EXCEPTION_FLT_STACK_CHECK
	The stack overflowed or underflowed as the result of a floating-point operation.
EXCEPTION_FLT_UNDERFLOW
	The exponent of a floating-point operation is less than the magnitude allowed by the corresponding type.
EXCEPTION_ILLEGAL_INSTRUCTION
	The thread tried to execute an invalid instruction.
EXCEPTION_IN_PAGE_ERROR
	The thread tried to access a page that was not present, and the system was unable to load the page. For example, this exception might occur if a network connection is lost while running a program over the network.
EXCEPTION_INT_DIVIDE_BY_ZERO
	The thread tried to divide an integer value by an integer divisor of zero.
EXCEPTION_INT_OVERFLOW
	The result of an integer operation caused a carry out of the most significant bit of the result.
EXCEPTION_INVALID_DISPOSITION
	An exception handler returned an invalid disposition to the exception dispatcher. Programmers using a high-level language such as C should never encounter this exception.
EXCEPTION_NONCONTINUABLE_EXCEPTION
	The thread tried to continue execution after a noncontinuable exception occurred.
EXCEPTION_PRIV_INSTRUCTION
	The thread tried to execute an instruction whose operation is not allowed in the current machine mode.
EXCEPTION_SINGLE_STEP
	A trace trap or other single-instruction mechanism signaled that one instruction has been executed.
EXCEPTION_STACK_OVERFLOW
	The thread used up its stack.
Another exception code is likely to occur when debugging console processes. It does not arise because of a programming error. The DBG_CONTROL_C exception code occurs when CTRL+C is input to a console process that handles CTRL+C signals and is being debugged. This exception code is not meant to be handled by applications. It is raised only for the benefit of the debugger, and is raised only when a debugger is attached to the console process.

ExceptionFlags

Specifies the exception flags. This member can be either zero, indicating a continuable exception, or EXCEPTION_NONCONTINUABLE indicating a noncontinuable exception. Any attempt to continue execution after a noncontinuable exception causes the EXCEPTION_NONCONTINUABLE_EXCEPTION exception.

ExceptionRecord

Points to an associated EXCEPTION_RECORD structure. Exception records can be chained together to provide additional information when nested exceptions occur.

ExceptionAddress

Specifies the address where the exception occurred.

NumberParameters

Specifies the number of parameters associated with the exception. This is the number of defined elements in the ExceptionInformation array.

ExceptionInformation

Specifies an array of additional 32-bit arguments that describe the exception. The RaiseException function can specify this array of arguments. For most exception codes, the array elements are undefined. For the following exception code, the array elements are defined as follows:

Exception code	Array contents
EXCEPTION_ACCESS_VIOLATION
	The first element of the array contains a read-write flag that indicates the type of operation that caused the access violation. If this value is zero, the thread attempted to read the inaccessible data. If this value is 1, the thread attempted to write to an inaccessible address.
	The second array element specifies the virtual address of the inaccessible data.
See Also

EXCEPTION_DEBUG_INFO, EXCEPTION_POINTERS, GetExceptionInformation, RaiseException, UnhandledExceptionFilter


EXIT_PROCESS_DEBUG_INFO
 EXIT_PROCESS_DEBUG_INFO  QuickInfo

typedef struct _EXIT_PROCESS_DEBUG_INFO { // epdi

    DWORD dwExitCode;

} EXIT_PROCESS_DEBUG_INFO;

The EXIT_PROCESS_DEBUG_INFO structure contains an exiting process's exit code.

Members

dwExitCode

Specifies the exit code for the process.

See Also

DEBUG_EVENT


EXIT_THREAD_DEBUG_INFO
 EXIT_THREAD_DEBUG_INFO  QuickInfo

typedef struct _EXIT_THREAD_DEBUG_INFO { // etdi

    DWORD dwExitCode;

} EXIT_THREAD_DEBUG_INFO;

The EXIT_THREAD_DEBUG_INFO structure contains an exiting thread's exit code.

Members

dwExitCode

Specifies the exit code for the thread.

See Also

DEBUG_EVENT


EXT_BUTTON
 EXT_BUTTON  QuickInfo

typedef struct _EXT_BUTTON { /* extbtn */

    WORD idCommand;

    WORD idsHelp;

    WORD fsStyle;

} EXT_BUTTON;

The EXT_BUTTON structure contains information about a button that a File Manager extension dynamic-link library is adding to the toolbar of File Manager.

Members

idCommand

Specifies the command identifier for the button.

idsHelp

Specifies the identifier of the Help string for the button.

fsStyle

Specifies the style of the button.

See Also

FMEVENT_TOOLBARLOAD, FMS_TOOLBARLOAD


EXTLOGFONT
 EXTLOGFONT  QuickInfo

typedef struct tagEXTLOGFONT {

    LOGFONT elfLogFont;

    BCHAR    elfFullName[LF_FULLFACESIZE];

    BCHAR    elfStyle[LF_FACESIZE];

    DWORD   elfVersion;

    DWORD   elfStyleSize;

    DWORD   elfMatch;

    DWORD   elfReserved;

    BYTE    elfVendorId[ELF_VENDOR_SIZE];

    DWORD   elfCulture;

    PANOSE  elfPanose;

} EXTLOGFONT;

The EXTLOGFONT structure defines the attributes of a font.

Members

elfLogFont

Specifies some of the attributes of the given font. This member is a LOGFONT structure.

elfFullName

Specifies a unique name for the font (for example, ABCD Font Company TrueType Bold Italic Sans Serif).

elfStyle

Specifies the style of the font (for example, Bold Italic).

elfVersion

Reserved. Must be zero.

elfStyleSize

This member only has meaning for hinted fonts. It specifies the point size at which the font is hinted. If set to zero, which is its default value, the font is hinted at the point size corresponding to the lfHeight member of the LOGFONT structure specified by elfLogFont.

elfMatch

A unique identifier for an enumerated font. This will be filled in by the graphics device interface (GDI) upon font enumeration.

elfReserved

Reserved; must be zero.

elfVendorId

A 4-byte identifier of the font vendor.

elfCulture

Reserved; must be zero.

elfPanose

A PANOSE structure that specifies the shape of the font. If all members of this structure are set to zero, the elfPanose member is ignored by the font mapper.

See Also

LOGFONT, PANOSE


EXTLOGPEN
 EXTLOGPEN  QuickInfo

typedef struct tagEXTLOGPEN { // exlp

    UINT     elpPenStyle;

    UINT     elpWidth;

    UINT     elpBrushStyle;

    COLORREF elpColor;

    LONG     elpHatch;

    DWORD    elpNumEntries;

    DWORD    elpStyleEntry[1];

} EXTLOGPEN;

The EXTLOGPEN structure defines the pen style, width, and brush attributes for an extended pen. This structure is used by the GetObject function when it retrieves a description of a pen that was created when an application called the ExtCreatePen function.

Members

elpPenStyle

Specifies a combination of pen type, style, end cap style, and join style. The values from each category can be retrieved by using a bitwise AND with the appropriate mask.

The elpPenStyle member masked with PS_TYPE_MASK has one of the following pen type values:

Value	Meaning
PS_GEOMETRIC	The pen is geometric.
PS_COSMETIC	The pen is cosmetic.
The elpPenStyle member masked with PS_STYLE_MASK has one of the following pen styles values:

Value	Meaning
PS_SOLID	The pen is solid.
PS_DASH	The pen is dashed.
PS_DOT	The pen is dotted.
PS_DASHDOT	The pen has alternating dashes and dots.
PS_DASHDOTDOT	The pen has alternating dashes and double dots.
PS_NULL	The pen is invisible.
PS_USERSTYLE	The pen will use a styling array supplied by the user.
PS_INSIDEFRAME	The pen is solid. When this pen is used in any GDI drawing function that takes a bounding rectangle, the dimensions of the figure are shrunk so that it fits entirely in the bounding rectangle, taking into account the width of the pen. This applies only to PS_GEOMETRIC pens.
The following category applies only to PS_GEOMETRIC pens. The elpPenStyle member masked with PS_ENDCAP_MASK has one of the following end cap values:

Value	Meaning
PS_ENDCAP_ROUND	Line end caps are round.
PS_ENDCAP_SQUARE	Line end caps are square.
PS_ENDCAP_FLAT	Line end caps are flat.
The following category applies only to PS_GEOMETRIC pens. The elpPenStyle member masked with PS_JOIN_STYLE has one of the following join values:

Value	Meaning
PS_JOIN_BEVEL	Line joins are beveled.
PS_JOIN_MITER	Line joins are mitered when they are within the current SetMiterLimit limit. A join is beveled when it would exceed the limit.
PS_JOIN_ROUND	Line joins are round.
elpWidth

Specifies the width of the pen. If the elpPenStyle member specifies geometric lines, this value is the width, in logical units, of the line. Otherwise, the lines are cosmetic and this value is 1.

elpBrushStyle

Specifies the brush style of the pen. The elpBrushStyle member values can be one of the following:

Value	Description
BS_DIBPATTERN	Specifies a pattern brush defined by a device-independent bitmap (DIB) specification. If elpBrushStyle is BS_DIBPATTERN, the elpHatch member contains a handle to a packed DIB.
BS_DIBPATTERNPT	Specifies a pattern brush defined by a device-independent bitmap (DIB) specification. If elpBrushStyle is BS_DIBPATTERNPT, the elpHatch member contains a pointer to a packed DIB.
BS_HATCHED	Specifies a hatched brush.
BS_HOLLOW	Specifies a hollow or NULL brush.
BS_PATTERN	Specifies a pattern brush defined by a memory bitmap.
BS_SOLID	Specifies a solid brush.
elpColor

If elpBrushStyle is BS_SOLID or BS_HATCHED, elpColor specifies the color in which the pen is to be drawn. For BS_HATCHED, the SetBkMode and SetBkColor functions determine the background color.

If elpBrushStyle is BS_HOLLOW or BS_PATTERN, elpColor is ignored.

If elpBrushStyle is BS_DIBPATTERN or BS_DIBPATTERNPT, the low-order word of elpColor specifies whether the bmiColors members of the BITMAPINFO structure contain explicit red, green, blue (RGB) values or indexes into the currently realized logical palette. The elpColor value must be one of the following:

Value	Meaning
DIB_PAL_COLORS	The color table consists of an array of 16-bit indexes into the currently realized logical palette.
DIB_RGB_COLORS	The color table contains literal RGB values.
elpHatch

If elpBrushStyle is BS_PATTERN, elpHatch is a handle to the bitmap that defines the pattern.

If elpBrushStyle is BS_SOLID or BS_HOLLOW, elpHatch is ignored.

If elpBrushStyle is BS_DIBPATTERN, the elpHatch member is a handle to a packed DIB. To obtain this handle, an application calls the GlobalAlloc function to allocate a block of global memory and then fills the memory with the packed DIB. A packed DIB consists of a BITMAPINFO structure immediately followed by the array of bytes that define the pixels of the bitmap.

If elpBrushStyle is BS_DIBPATTERNPT, the elpHatch member is a pointer to a packed DIB.

If elpBrushStyle is BS_HATCHED, the elpHatch member specifies the orientation of the lines used to create the hatch. It can be any one of the following values:

Value	Meaning
HS_BDIAGONAL	45-degree upward hatch (left to right)
HS_CROSS	Horizontal and vertical crosshatch
HS_DIAGCROSS	45-degree crosshatch
HS_FDIAGONAL	45-degree downward hatch (left to right)
HS_HORIZONTAL	Horizontal hatch
HS_VERTICAL	Vertical hatch
elpNumEntries

Specifies the number of entries in the style array in the elpStyleEntry member. This value is zero if elpPenStyle does not specify PS_USERSTYLE.

elpStyleEntry

Specifies a user-supplied style array. The array is specified with a finite length, but it is used as if it repeated indefinitely. The first entry in the array specifies the length of the first dash. The second entry specifies the length of the first gap. Thereafter, lengths of dashes and gaps alternate.

If elpWidth specifies geometric lines, the lengths are in logical units. Otherwise, the lines are cosmetic and lengths are in device units.

See Also

BITMAPINFO, ExtCreatePen, GetObject, GlobalAlloc, SetBkColor, SetBkMode


FILETIME
 FILETIME  QuickInfo

typedef struct _FILETIME { // ft

    DWORD dwLowDateTime;

    DWORD dwHighDateTime;

} FILETIME;

The FILETIME structure is a 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601.

Members

dwLowDateTime

Specifies the low-order 32 bits of the file time.

dwHighDateTime

Specifies the high-order 32 bits of the file time.

See Also

CompareFileTime, DosDateTimeToFileTime, FileTimeToDosDateTime, FileTimeToLocalFileTime, FileTimeToSystemTime, GetFileTime, LocalFileTimeToFileTime, SetFileTime, SystemTimeToFileTime


FILTERKEYS
 FILTERKEYS  QuickInfo  Overview  Group

typedef struct tagFILTERKEYS {     // fk

    UINT  cbSize;

    DWORD dwFlags;

    DWORD iWaitMSec;

    DWORD iDelayMSec;

    DWORD iRepeatMSec;

    DWORD iBounceMSec;

} FILTERKEYS;

The FILTERKEYS structure contains information about the FilterKeys accessibility feature, which allow a user with disabilities to set the keyboard repeat rate (RepeatKeys), acceptance delay (SlowKeys), and bounce rate (BounceKeys).

Members

cbSize

Specifies the structure size, in bytes.

dwFlags

A set of bit flags that specify properties of the FilterKeys feature. The following bit-flag values are defined:

Value	Meaning
FKF_AVAILABLE	The FilterKeys features are available.
FKF_CLICKON	The computer makes a click sound when a key is pressed or accepted, that is, if SlowKeys is on, the acceptance is separated from the press and gets a separate click..
FKF_FILTERKEYSON	The FilterKeys features are on.
FKF_HOTKEYACTIVE	The user can turn the FilterKeys feature on and off by holding down the SHIFT key for eight seconds.
FKF_HOTKEYSOUND	If this flag is set, the computer plays a siren sound when the user turns the FilterKeys feature on or off by using the hot key.
FKF_CONFIRMHOTKEY	Windows 95 only: A confirmation dialog box appears when the the FilterKeys features are activated by using the hot key.
FKF_INDICATOR	Windows 95 only: A visual indicator is displayed when the FilterKeys features are on.
iWaitMSec

Specifies the length of time, in milliseconds, that the user must hold down a key before it is accepted by the computer.

iDelayMSec

Specifies the length of time, in milliseconds, that the user must hold down a key before it begins to repeat.

iRepeatMSec

Specifies the length of time, in milliseconds, between each repetition of the keystroke.

iBounceMSec

Specifies the amount of time, in milliseconds, that must elapse after releasing a key before the computer will accept a subsequent press of the same key.

Remarks

Use a FILTERKEYS structure when calling the SystemParametersInfo function with the wAction parameter set to the SPI_GETFILTERKEYS or SPI_SETFILTERKEYS value. When using SPI_GETFILTERKEYS,you must specify the cbSize member of the FILTERKEYS structure; the SystemParametersInfo function fills the remaining members. Specify all structure members when using the SPI_SETFILTERKEYS value.

Either iDelayMSec or iBounceMSec, or both, must be zero; they cannot both be non-zero at the same time.

If iBounceMSec is non-zero, the BounceKeys feature is on and the SlowKeys feature is off (the iDelayMSec value is ignored). If iBounceMSec is zero, the BounceKeys feature is off.

If iDelayMSec is nonzero and iBounceMSec is zero, the SlowKeys feature is on; otherwise, it is off.

See Also

SystemParametersInfo


FIND_NAME_BUFFER
 FIND_NAME_BUFFER  QuickInfo

typedef struct _FIND_NAME_BUFFER { // fnb

    UCHAR length;

    UCHAR access_control;

    UCHAR frame_control;

    UCHAR destination_addr[6];

    UCHAR source_addr[6];

    UCHAR routing_info[18];

} FIND_NAME_BUFFER;

The FIND_NAME_BUFFER structure contains information about a local network session. One or more FIND_NAME_BUFFER structures follows a FIND_NAME_HEADER structure when an application specifies the NCBFINDNAME command in the ncb_command member of the NCB structure.

Members

length

Specifies the length, in bytes, of the FIND_NAME_BUFFER structure. Although this structure always occupies 33 bytes, not all of the structure is necessarily valid.

access_control

Specifies the access control for the LAN header.

frame_control

Specifies the frame control for the LAN header.

destination_addr

Specifies the destination address of the remote node where the name was found.

source_addr

Specifies the source address for the remote node where the name was found.

routing_info

Specifies additional routing information.

See Also

FIND_NAME_HEADER, NCB


FIND_NAME_HEADER
 FIND_NAME_HEADER  QuickInfo

typedef struct _FIND_NAME_HEADER { // fnh

    WORD  node_count;

    UCHAR reserved;

    UCHAR unique_group;

} FIND_NAME_HEADER;

The FIND_NAME_HEADER structure contains information about a network name. This structure is followed by as many FIND_NAME_BUFFER structures as are required to describe the name.

Members

node_count

Specifies the number of nodes on which the specified name was found. This structure is followed by the number of FIND_NAME_BUFFER structures specified by the node_count member.

reserved

Reserved.

unique_group

Specifies whether the name is unique. This value is 0 to specify a unique name or 1 to specify a group.

Remarks

The FIND_NAME_HEADER structure is pointed to by the ncb_buffer member of the NCB structure when an application issues an NCBFINDNAME command.

See Also

FIND_NAME_BUFFER, NCB


FINDREPLACE
 FINDREPLACE  QuickInfo

typedef struct {    // fr

    DWORD        lStructSize;

    HWND         hwndOwner;

    HINSTANCE    hInstance;

    DWORD        Flags;

    LPTSTR        lpstrFindWhat;

    LPTSTR        lpstrReplaceWith;

    WORD         wFindWhatLen;

    WORD         wReplaceWithLen;

    LPARAM        lCustData;

    LPFRHOOKPROC lpfnHook;

    LPCTSTR       lpTemplateName;

} FINDREPLACE;

The FINDREPLACE structure contains information the operating system uses to initialize the system-defined Find and Replace dialog boxes. After the user closes the dialog box, the system returns information about the user-defined find or replace selections in this structure.

Members

lStructSize

Specifies the length, in bytes, of the structure.

hwndOwner

Identifies the window that owns the dialog box. This member can be any valid window handle, but it must not be NULL.

hInstance

Identifies a data block that contains a dialog box template specified by the lpTemplateName member. This member is used only if the Flags member specifies the FR_ENABLETEMPLATE flag; otherwise, this member is ignored.

Flags

Specifies the dialog box initialization flags. This member may be a combination of the following flags:

Flag	Meaning
FR_DIALOGTERM
	Indicates that the dialog box is closing. The window handle returned by the FindText or ReplaceText function is not valid if this flag is specified.
FR_DOWN
	Determines the direction of searches through a document. If this flag is used, the search direction is down; if the flag is not used, the search direction is up. Initially, this flag specifies the state of the Up and Down controls; after the user closes the dialog box, this flag specifies the user's selection.
FR_ENABLEHOOK
	Enables the hook function specified in the lpfnHook member of this structure. This flag is used only to initialize the dialog box.
FR_ENABLETEMPLATE
	Causes the system to create the dialog box by using the dialog box template identified by the hInstance and lpTemplateName members. 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
	Indicates that the application should search for the next occurrence of the string specified by the lpstrFindWhat member.
FR_HIDEUPDOWN
	Causes the system to hide the Direction check box and the Up and Down controls.
FR_HIDEMATCHCASE
	Causes the system to hide the Match Case check box.
FR_HIDEWHOLEWORD
	Causes the system to hide the Match Whole Word Only check box.
FR_MATCHCASE
	Indicates case-sensitive searches.
FR_NOMATCHCASE
	Disables the Match Case check box. This flag is used only to initialize the dialog box.
FR_NOUPDOWN
	Disables the direction radio buttons. This flag is used only to initialize the dialog box.
FR_NOWHOLEWORD
	Disables the Whole Word check box. This flag is used only to initialize the dialog box.
FR_REPLACE
	Indicates that the application should replace the current occurrence of the string specified in the lpstrFindWhat member with the string specified in the lpstrReplaceWith member.
FR_REPLACEALL
	Indicates that the application should replace all occurrences of the string specified in the lpstrFindWhat member with the string specified in the lpstrReplaceWith member.
FR_SHOWHELP
	Causes the dialog box to show the Help button. The hwndOwner member must not be NULL if this flag is specified.
FR_WHOLEWORD
	Checks the Whole Word check box. Only whole words matching the search string will be considered.
lpstrFindWhat

Specifies the string to search for. If there is a string specified when the dialog box starts, the dialog box initializes the Find What: text control with this string. If the FR_FINDNEXT flag is specified when the dialog box is opened, the application should search for an occurrence of this string by using the FR_DOWN, FR_WHOLEWORD, and FR_MATCHCASE flags to further define the direction and type of search. The application must allocate a buffer for the string. This buffer should be at least 80 characters long.

lpstrReplaceWith

Specifies the replacement string for replace operations. 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 the system passes to the hook function identified by the lpfnHook member. The system passes the data in the lParam parameter of the WM_INITDIALOG message.

lpfnHook

Points to a hook function that processes messages intended for the dialog box. An application must specify the FR_ENABLEHOOK flag in the Flags member to enable the function; otherwise, the system ignores this member. The hook function should return FALSE to pass a message on to the standard dialog box procedure or TRUE to discard the message.

If the hook function returns FALSE in response to the WM_INITDIALOG message, it is responsible for displaying the dialog box, which is done by calling the ShowWindow and UpdateWindow functions. (These calls should be placed after any other paint operations). 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);

If the hook function returns FALSE in response to the WM_INITDIALOG message but fails to display the dialog, the dialog box will not be shown.

lpTemplateName

Points to a null-terminated string that names the dialog box template resource to be substituted for the standard dialog box template. An application can use the MAKEINTRESOURCE macro for numbered dialog resources. This member is used only if the Flags member specifies the FR_ENABLETEMPLATE flag; otherwise, this member is ignored.

See Also

FindText, MAKEINTRESOURCE, ReplaceText, ShowWindow, UpdateWindow, WM_INITDIALOG


FINDTEXT [New - Windows NT]
 FINDTEXT  QuickInfo  Overview  Group

[New - Windows NT]

typedef struct _findtext {

    CHARRANGE chrg;

    LPSTR lpstrText;

} FINDTEXT;

The FINDTEXT structure contains information about text to search for in a rich edit control. This structure is used with the EM_FINDTEXT message.

Members

chrg

Range to search.

lpstrText

Null-terminated string to find.

See Also

EM_FINDTEXT


FINDTEXTEX
 FINDTEXTEX  QuickInfo  Overview  Group

typedef struct _findtextex {
    CHARRANGE chrg;      // range to search
    LPSTR lpstrText;     // null-terminated string to find
    CHARRANGE chrgText;  // range in which text is found
} FINDTEXTEX;

Contains information about text to search for in a rich edit control. This structure is used with the EM_FINDTEXTEX message.


FIXED
 FIXED  QuickInfo

typedef struct _FIXED { // fix

    WORD  fract;

    short value;

} FIXED;

The FIXED structure contains the integral and fractional parts of a fixed-point real number.

Members

fract

Specifies the fractional part of the number.

value

Specifies the integer part of the number.

Remarks

The FIXED structure is used to describe the elements of the MAT2 structure.

See Also

MAT2


FMS_GETDRIVEINFO
 FMS_GETDRIVEINFO  QuickInfo

typedef struct _FMS_GETDRIVEINFO { /* fmsgdi */

    DWORD dwTotalSpace;

    DWORD dwFreeSpace;

    TCHAR  szPath[260];

    TCHAR  szVolume[14];

    TCHAR  szShare[128];

} FMS_GETDRIVEINFO;

The FMS_GETDRIVEINFO structure contains information about the drive selected in the active File Manager window (the directory window or the Search Results window).

Members

dwTotalSpace

Specifies the total amount of storage space, in bytes, on the disk associated with the drive.

dwFreeSpace

Specifies the amount of free storage space, in bytes, on the disk associated with the drive.

szPath

Specifies the null-terminated path of the current directory.

szVolume

Specifies the null-terminated volume label of the disk associated with the drive.

szShare

Specifies the null-terminated name of the sharepoint (if the drive is being accessed through a network).

See Also

FMExtensionProc, FM_GETDRIVEINFO


FMS_GETFILESEL
 FMS_GETFILESEL  QuickInfo

typedef struct _FMS_GETFILESEL { /* fmsgfs */

    FILETIME ftTime;

    DWORD    dwSize;

    BYTE     bAttr;

    TCHAR     szName[260];

} FMS_GETFILESEL;

The FMS_GETFILESEL structure contains information about a selected file in the active File Manager window (the directory window or the Search Results window).

Members

ftTime

Specifies the time and date the file was created.

dwSize

Specifies the size, in bytes, of the file.

bAttr

Specifies the attributes of the file.

szName

Specifies the null-terminated full path and filename of the selected file.

See Also

FMExtensionProc


FMS_LOAD
 FMS_LOAD  QuickInfo

typedef struct _FMS_LOAD { /* fmsld */

    DWORD dwSize;

    TCHAR  szMenuName[MENU_TEXT_LEN];

    HMENU hMenu;

    UINT  wMenuDelta;

} FMS_LOAD;

The FMS_LOAD structure contains information that File Manager uses to add a custom menu provided by a File Manager extension DLL. The structure also provides a delta value that the extension DLL can use to manipulate the custom menu after File Manager has loaded the menu.

Members

dwSize

Specifies the length, in bytes, of the structure.

szMenuName

Specifies the null-terminated name for a menu item that appears on the menu bar in File Manager.

hMenu

Identifies the pop-up menu added to the menu bar in File Manager.

wMenuDelta

Specifies the menu-item delta value. To avoid conflicts with its own menu items, File Manager renumbers the menu-item identifiers in the pop-up menu identified by the hMenu member by adding this delta value to each identifier. An extension DLL that must modify a menu item must identify the item by adding the delta value to the menu item's identifier. The value of this member can vary from session to session.

See Also

FMExtensionProc


FMS_TOOLBARLOAD
 FMS_TOOLBARLOAD  QuickInfo

typedef struct _FMS_TOOLBARLOAD { /* fmstbl */

    DWORD        dwSize;

    LPEXT_BUTTON lpButtons;

    WORD         cButtons;

    WORD         cBitmaps;

    WORD         idBitmap;

    HBITMAP      hBitmap;

} FMS_TOOLBARLOAD;

The FMS_TOOLBARLOAD structure contains information about custom buttons to be added to the File Manager toolbar. The buttons are provided by a File Manager extension DLL.

Members

dwSize

Specifies the size, in bytes, of the structure. File Manager sets the size before calling the extension and checks the size after the extension procedure returns.

lpButtons

Points to an array of EXT_BUTTON structures that specify the style, command identifier, and Help string identifier for each toolbar button.

cButtons

Specifies the number of EXT_BUTTON structures in the array pointed to by the lpButtons member. This number equals the number of buttons and separators to add to the toolbar.

cBitmaps

Specifies the number of buttons represented by the given bitmap.

idBitmap

Specifies the identifier of a bitmap resource in the executable file for the extension DLL. The bitmap resource contains images for the number of buttons specified by cBitmaps. File Manager loads the bitmap resource, then uses it to display the buttons.

hBitmap

Specifies the handle of a bitmap that the File Manager will use to obtain and display button images if idBitmap is 0.

See Also

FMEVENT_TOOLBARLOAD, EXT_BUTTON


FOCUS_EVENT_RECORD
 FOCUS_EVENT_RECORD  QuickInfo  Overview  Group

typedef struct _FOCUS_EVENT_RECORD { // fer

    BOOL bSetFocus;

} FOCUS_EVENT_RECORD;

The FOCUS_EVENT_RECORD structure is used to report focus events in a console INPUT_RECORD structure. These events are used internally and should be ignored.

Members

bSetFocus

Used internally.

See Also

INPUT_RECORD


FONTSIGNATURE [New - Windows 95]
 FONTSIGNATURE  QuickInfo  Overview  Group

[New - Windows 95]

typedef struct tagFONTSIGNATURE {
    DWORD  fsUsb[4];
    DWORD  fsCsb[2];
} FONTSIGNATURE;

The FONTSIGNATURE structure contains information identifying the code-pages and Unicode subranges for which a given font provides glyphs.

Members

fsUsb

A 128-bit Unicode subset bitfield (USB) identifying up to 126 Unicode subranges. Each bit, except the two most significant bits, represents a single subrange. The most significant bit is always 1 and identifies the bitfield as a font signature; the second most significant bit is reserved and must be 0. Unicode subranges are numbered in accordance with the ISO 10646 standard.

fsCsb

A 64-bit, code-page bitfield (CPB) that identifies a specific character set or code-page. Windows code-pages are in the lower 32 bits of this bitfield. The high 32 are used for non-Windows code-pages. For more information, see Code-Page Bitfields.

Remarks

GDI relies on Windows code-pages fitting within a 32-bit value. Furthermore, the highest two bits within this value are reserved for GDI internal use and may not be assigned to code-pages.


FORM_INFO_1
 FORM_INFO_1  QuickInfo

typedef struct _FORM_INFO_1 { // fi1

    DWORD Flags;

    LPTSTR pName;

    SIZEL  Size;

    RECTL  ImageableArea;

} FORM_INFO_1;

The FORM_INFO_1 structure contains information about a print form. The information includes the print form's origin, its name, its dimensions, and the dimensions of its printable area.

Members

Flags

A set of bit-flags that specify form properties. The following bit-flag is defined:

Value	Meaning
FORM_BUILTIN	If this bit-flag is set, the form is built-in. If this bit-flag is clear, the form is user-defined.
pName

Points to a null-terminated string that specifies the name of the form.

Size

Specifies the width and height, in thousandths of millimeters, of the form.

ImageableArea

Specifies the width and height, in thousandths of millimeters, of the form.

See Also

AddForm, GetForm, SetForm


FORMAT_PARAMETERS
 FORMAT_PARAMETERS  QuickInfo  Overview  Group

typedef struct _FORMAT_PARAMETERS{

   MEDIA_TYPE MediaType;

   DWORD StartCylinderNumber;

   DWORD EndCylinderNumber;

   DWORD StartHeadNumber;

   DWORD EndHeadNumber;

} FORMAT_PARAMETERS ;

The FORMAT_PARAMETERS structure provides information used in formatting a contiguous set of disk tracks.

Members

MediaType

Specifies the media type. See MEDIA_TYPE.

StartCylinderNumber

Specifies the cylinder number at which to begin the format.

EndCylinderNumber

Specifies the cylinder number at which to end the format.

StartHeadNumber

Specifies the beginning head location.

EndHeadNumber

Specifies the ending head location.

Remarks

The DeviceIoControl function uses a FORMAT_PARAMETERS structure as input to an IOCTL_DISK_FORMAT_TRACKS device I/O operation.

See Also

DeviceIoControl, IOCTL_DISK_FORMAT_TRACKS, MEDIA_TYPE


FORMATRANGE [New - Windows NT]
 FORMATRANGE  QuickInfo  Overview  Group

[New - Windows NT]

typedef struct _formatrange {

    HDC hdc;

    HDC hdcTarget;

    RECT rc;

    RECT rcPage;

    CHARRANGE chrg;

} 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.

Members

hdc

Device to render to.

hdcTarget

Target device to format for.

rc

Area to render to. Units are in TWIPS

rcPage

Entire area of rendering device. Units are in TWIPS

chrg

Range of text to format.

See Also

EM_FORMATRANGE


GCP_RESULTS [New - Windows 95]
 GCP_RESULTS  QuickInfo

[New - Windows 95]

typedef struct tagGCP_RESULTS {
    DWORD  lStructSize;
    LPTSTR  lpOutString;
    UINT  *lpOrder;
    INT  *lpDx;
    INT  *lpCaretPos;
    LPTSTR lpClass;
    UINT  *lpGlyphs;
    UINT  nGlyphs;
    UINT  nMaxFit;
} GCP_RESULTS;

The GCP_RESULTS structure contains information about characters in a string. This structure receives the results of the GetCharacterPlacement function. For some languages, the first element in the arrays may contain more, language-dependent information.

Members

lStructSize

Specifies the size, in bytes, of the structure.

lpOutString

Pointer to the buffer that receives the output string or is NULL if the output string is not needed. The output string is a version of the original string that is in the order that will be displayed on a given device. Typically the output string is identical to the original string, but may be different if the string needs reordering and the GCP_REORDER flag is set or if the the original string exceeds the maximum extent and the GCP_MAXEXTENT flag is set.

lpOrder

Address of the array that receives the ordering indices for the characters in the output string or is NULL if the ordering indices are not needed. The original string needs reordering if the GetFontLanguageInfo function returns the GCP_REORDER value. This is typically used when GetFontLanguageInfo returns the GCP_REORDER flag. For example, in Hebrew, in which the text runs from right to left, the lpOrder array gives the exact locations of each element in the original string.

lpDx

Pointer to the array that receives the distances between adjacent character cells or is NULL if these distances are not needed. If glyph rendering is done, the distances are for the glyphs not the characters, so the resulting array can be used with the ExtTextOut function.

The distances in this array are in display order. To find the distance for the ith character in the original string, use the lpOrder array as follows:

width = lpDx[lpOrder[i]];

On input, this member may contain justification weight values if the GCP_JUSTIFYIN value is given with the GetCharacterPlacement function.

lpCaretPos

Pointer to the array that receives the caret position values or is NULL if caret positions are not needed. Each value specifies the caret position immediately before the corresponding character. In some languages the position of the caret for each character may not be immediately to the left of the character. For example, in Hebrew, in which the text runs from right to left, the caret position is to the right of the character. If glyph ordering is done, lpCaretPos matches the original string not the output string. This means that some adjacent values may be the same.

The values in this array are in input order. To find the caret position value for the ith character in the original string, use the array as follows:

position = lpCaretPos[i];

lpClass

Pointer to the array that contains and/or receives character classifications. The values indicate how to lay out characters in the string and are similar (but not identical) to the CT_CTYPE2 values returned by the GetStringTypeEx function. Each element of the array can be set to zero or one of the following values:

Value	Meaning
GCPCLASS_ARABIC	Arabic character.
GCPCLASS_HEBREW	Hebrew character.
GCPCLASS_LATIN	Character from a Latin or other single-byte character set for a left-to-right language.
GCPCLASS_LATINNUMBER	Digit from a Latin or other single-byte character set for a left-to-right language.
GCPCLASS_LOCALNUMBER	Digit from the character set associated with the current font.
In addition, the following can be used when supplying values in the lpClass array with the GCP_CLASSIN flag.

Value	Meaning
GCPCLASS_LATINNUMERICSEPARATOR	Input only. Character used to separate Latin digits, such as acomma or decimal point.
GCPCLASS_LATINNUMERICTERMINATOR	Input only. Character used to terminate Latin digits, such as a plus or minus sign.
GCPCLASS_NEUTRAL	Input only. character has no specific classification.
GCPCLASS_NUMERICSEPARATOR	Input only. Character used to separate digits, such as a comma or decimal point.
For languages that use the GCP_REORDER flag, the following values can also be used with the GCP_CLASSIN flag. Unlike the preceding values, which can be used anywhere in the lpClass array, all of the following values are used only in the first location in the array. All combine with other classifications. Note that GCPCLASS_PREBOUNDLTR and GCPCLASS_PREBOUNDRTL are mutually exclusive, as are GCPCLASSPOSTBOUNDLTR and GCPCLASSPOSTBOUNDRTL.

Value	Meaning
GCPCLASS_PREBOUNDLTR	Set lpClass[0] to GCP_CLASS_PREBOUNDLTR to bind the string to left-to-right reading order before the string.
CGPCLASS_PREBOUNDRTL	Set lpClass[0] to GCP_CLASS_PREBOUNDRTL to bind the string to right-to-left reading order before the string.
GCPCLASS_POSTBOUNDLTR	Set lpClass[0] to GCP_CLASS_POSTBOUNDLTR to bind the string to left-to-right reading order after the string.
GCPCLASS_POSTBOUNDRTL	Set lpClass[0] to GCP_CLASS_POSTBOUNDRTL to bind the string to right-to-left reading order after the string.
To force the layout of a character to be carried out in a specific way, preset the classification for the corresponding array element; the function leaves such preset classifications unchanged and computes classifications only for array elements that have been set to zero. Preset classifications are used only if the GCP_CLASSIN flag is set and the lpclass array is supplied.

If getFontLanguageInfo does not return GCP_REORDER for the current font, only the GCPCLASS_LATIN value is meaningful.

lpGlyphs

Pointer to the array that receives the values identifying the glyphs used for rendering the string or is NULL if glyph rendering is not needed. The number of glyphs in the array may be less than the number of characters in the original string if the string contains ligated glyphs. Also if reordering is required, the order of the glyphs may not be sequential.

This array is useful if more than one operation is being done on a string which has any form of ligation, kerning or order-switching. Using the values in this array for subsequent operations saves the time otherwise required to generate the glyph indices each time.

This array always contains glyph indices and the ETO_GLYPH_INDEX value must always be used when this array is used with the ExtTextOut function.

When GCP_LIGATE is used, you can limit the number of characters that will be ligated together. (In Arabic for example, three-character ligations are common). This is done by setting the maximum required in lpGcpResults->lpGlyphs[0]. If no maximum is required, you should set this field to zero.

For languages such as Arabic, where GetFontLanguageInfo returns the GCP_GLYPHSHAPE flag, the glyphs for a character will be different depending on whether the character is at the beginning, middle, or end of a word. Typically, the first character in the input string will also be the first character in a word, and the last character in the input string will be treated as the last character in a word. However, if the displayed string is a subset of the complete string, such as when displaying a section of scrolled text, this may not be true. In these cases, it is desirable to force the first or last characters to be shaped as not being initial or final forms. To do this, again, the first location in the lpGlyphs array is used by performing an OR operation of the ligation value above with the values GCPGLYPH_LINKBEFORE and/or GCPGLYPH_LINKAFTER. For example, a value of GCPGLYPH_LINKBEFORE | 2 means that two-character ligatures are the maximum required, and the first character in the string should be treated as if it is in the middle of a word.

nGlyphs

On input, this member must be set to the size of the arrays pointed to by the array pointer members. On output, this is set to the number of glyphs filled in, in the output arrays. If glyph substitution is not required (that is, each input character maps to exactly one glyph), this member is the same as it is on input.

nMaxFit

Number of characters that fit within the extents specified by the nMaxExtent parameter of the GetCharacterPlacement function. If the GCP_MAXEXTENT or GCP_JUSTIFY value is set, this value may be less than the number of characters in the original string. This member is set regardless of whether the GCP_MAXEXTENT or GCP_JUSTIFY value is given. Unlike nGlyphs, which specifies the number of output glyphs, nMaxFit refers to the number of characters from the input string. For Latin SBCS languages, this will be the same.

Remarks

Whether the lpGlyphs, lpOutString, or neither is required depends on the results of the GetFontLanguageInfo call.

In the case of a font for a language such as English, in which none of the GCP_DBCS, GCP_REORDER, GCP_GLYPHSHAPE, GCP_LIGATE, GCP_DIACRITIC, or GCP_KASHIDA flags are returned, neither of the arrays is required for proper operation. (Though not required, they can still be used. If the lpOutString array is used, it will be exactly the same as the lpInputString passed to GetCharacterPlacement.) Note, however, that if GCP_MAXEXTENT is used, then lpOutString will contain the truncated string if it is used, NOT an exact copy of the original.

In the case of fonts for languages such as Hebrew, which DO have reordering but do not typically have extra glyph shapes, lpOutString should be used. This will give the string on the screen-readable order. However, the lpGlyphs array is not typically needed. (Hebrew can have extra glyphs, if the font is a TrueType/Open font.)

In the case of languages such as Thai or Arabic, in which GetFontLanguageInfo returns the GCP_GLYPHSHAPE flag, the lpOutString will give the display-readable order of the string passed to GetCharacterPlacement, but the values will still be the unshaped characters. For proper display, the lpGlyphs array must be used.

See Also

ExtTextOut, GetCharacterPlacement, GetFontLanguageInfo


GENERIC_MAPPING
 GENERIC_MAPPING  QuickInfo

typedef struct _GENERIC_MAPPING { // gm

    ACCESS_MASK GenericRead;

    ACCESS_MASK GenericWrite;

    ACCESS_MASK GenericExecute;

    ACCESS_MASK GenericAll;

} GENERIC_MAPPING;

The GENERIC_MAPPING structure defines the mapping of generic access rights to specific and standard access rights for an object. When a client application requests generic access to an object, that request is mapped to the access rights defined in this structure.

Members

GenericRead

Specifies an access mask defining read access to an object.

GenericWrite

Specifies an access mask defining write access to an object.

GenericExecute

Specifies an access mask defining execute access to an object.

GenericAll

Specifies an access mask defining all possible types of access to an object.

See Also

AccessCheck, AccessCheckAndAuditAlarm, CreatePrivateObjectSecurity, MapGenericMask, SetPrivateObjectSecurity, ACCESS_MASK


GLYPHMETRICS
 GLYPHMETRICS  QuickInfo

typedef struct _GLYPHMETRICS { // glmt

    UINT  gmBlackBoxX;

    UINT  gmBlackBoxY;

    POINT gmptGlyphOrigin;

    short gmCellIncX;

    short gmCellIncY;

} GLYPHMETRICS;

The GLYPHMETRICS structure contains information about the placement and orientation of a glyph in a character cell.

Members

gmBlackBoxX

Specifies the width of the smallest rectangle that completely encloses the glyph (its "black box").

gmBlackBoxY

Specifies the height of the smallest rectangle that completely encloses the glyph (its "black box").

gmptGlyphOrigin

Specifies the x- and y-coordinates of the upper left corner of the smallest rectangle that completely encloses the glyph.

gmCellIncX

Specifies the horizontal distance from the origin of the current character cell to the origin of the next character cell.

gmCellIncY

Specifies the vertical distance from the origin of the current character cell to the origin of the next character cell.

Remarks

Values in the GLYPHMETRICS structure are specified in device units.

See Also

GetGlyphOutline


HANDLETABLE
 HANDLETABLE  QuickInfo

typedef struct tagHANDLETABLE { // ht

    HGDIOBJ objectHandle[1];

} HANDLETABLE;

The HANDLETABLE structure is an array of handles, each of which identifies a graphics device interface (GDI) object.

Members

objectHandle

Contains an array of handles.

See Also

EnhMetaFileProc, EnumMetaFileProc


HD_HITTESTINFO [New - Windows NT]
 HD_HITTESTINFO  QuickInfo  Overview  Group

[New - Windows NT]

typedef struct _HD_HITTESTINFO {

    POINT pt;

    UINT flags;

    int iItem;

} HD_HITTESTINFO;

The HD_HITTESTINFO structure contains information about a hit test.

Members

pt

Points to test, in client coordinates

flags

Variable that receives information about the results of a hit test. This member can be one or more of the following values:

Value	Meaning
HHT_NOWHERE	The point is inside the bounding rectangle of the header control but is not over a header item.
HHT_ONDIVIDER	The point is on the divider between two header items.
HHT_ONDIVOPEN	The point is on the divider of an item that has a width of zero. Dragging the divider reveals the item instead of resizing the item to the left of the divider.
HHT_ONHEADER	The point is inside the bounding rectangle of the header control.
HHT_TOLEFT	The point is to the left of the bounding rectangle of the header control.
HHT_TORIGHT	The point is to the right of the bounding rectangle of the header control.
Two of these values can be combined, such as when the position is above and to the left of the client area.

iItem

Receives the index of item at point, if any.

Remarks

This structure is used with the HDM_HITTEST message.

See Also

HDM_HITTEST


HD_ITEM [New - Windows NT]
 HD_ITEM  QuickInfo  Overview  Group

[New - Windows NT]

typedef struct _HD_ITEM {   hdi

    UINT    mask;

    int     cxy;

    LPTSTR   pszText;

    HBITMAP hbm;

    int     cchTextMax;

    int     fmt;

    LPARAM  lParam;

} HD_ITEM;

The HD_ITEM structure contains information about an item in a header control.

Members

mask

Mask flags that indicate which of the other structure members contain valid data. This member can be a combination of the following values:

Value	Meaning
HDI_BITMAP	The hbm member is valid.
HDI_FORMAT	The fmt member is valid.
HDI_HEIGHT	The cxy member is valid and specifies the height of the item.
HDI_LPARAM	The lParam member is valid.
HDI_TEXT	The pszText and cchTextMax members are valid.
HDI_WIDTH	The cxy member is valid and specifies the width of the item.
cxy

Width or height of item.

pszText

Pointer to item string.

hbm

Handle to item bitmap.

cchTextMax

Length of item string, in characters.

fmt

Format flags. This member can be one of the following values:

Value	Meaning
HDF_CENTER	Centers the contents of the item.
HDF_LEFT	Left aligns the contents of the item.
HDF_RIGHT	Right aligns the contents of the item.
HDF_RTLREADING	Windows 95 only: Displays text using right-to-left reading order on Hebrew or Arabic systems.
The preceding value is combined with one of the following values:

Value	Meaning
HDF_BITMAP	The item displays a bitmap.
HDF_OWNERDRAW	The owner window of the header control draws the item.
HDF_STRING	The item displays a string.
lParam

Application-defined item data.


HD_LAYOUT [New - Windows NT]
 HD_LAYOUT  QuickInfo  Overview  Group

[New - Windows NT]

typedef struct _HD_LAYOUT {  // hdl

    RECT FAR* prc;

    WINDOWPOS FAR* pwpos;

} HD_LAYOUT;

The HD_LAYOUT structure contains information used to set the size and position of a header control.

Members

prc

Pointer to a RECT structure that contains the coordinates of a rectangle that the header control is to occupy.

pwpos

Pointer to a WINDOWPOS structure that receives information about the appropriate size and position of the header control.

Remarks

This structure is used with the HDM_LAYOUT message.

See Also

HDM_LAYOUT, RECT, WINDOWPOS


HD_NOTIFY [New - Windows NT]
 HD_NOTIFY  QuickInfo  Overview  Group

[New - Windows NT]

typedef struct _HD_NOTIFY {  // hdn

    NMHDR   hdr;

    int     iItem;

    int     iButton;

    HD_ITEM FAR* pitem;

} HD_NOTIFY;

The HD_NOTIFY structure contains information used to process notification messages from a header control.

Members

hdr

Required for all WM_NOTIFY messages.z

iItem

Index of item associated with notification.

iButton

Index of the mouse button involved in generating the notification message. This member can be one of these values:

Value	Meaning
0	Left button
1	Right button
2	Middle button
pitem

Pointer to an HD_ITEM structure that contains information about the header item associated with the notification message.

See Also

HD_ITEM, WM_NOTIFY


HELPINFO
 HELPINFO  QuickInfo

typedef  struct  tagHELPINFO {  // hi

    UINT   cbSize;

    int    iContextType

    int    iCtrlId;

    HANDLE hItemHandle;

    DWORD  dwContextId;

    POINT  MousePos;

} HELPINFO, FAR *LPHELPINFO;

The HELPINFO structure contains information about an item for which context-sensitive help has been requested.

cbSize

Specifies the structure size, in bytes.

iContextType

Specifies the type of context for which help is requested. This member can be one of the following values:

Value	Meaning
HELPINFO_MENUITEM	Help requested for a menu item
HELPINFO_WINDOW	Help requested for a control or window
iCtrlId

Specifies the identifier of the window or control if iContextType is HELPINFO_WINDOW. Specifies the identifier of the menu item if iContextType is HELPINFO_MENUITEM.

hItemHandle

Identifies the child window or control if iContextType is HELPINFO_WINDOW. Identifies the associated menu if iContextType is HELPINFO_MENUITEM.

dwContextId

Specifies the help context identifier of the window or control.

MousePos

Specifies a POINT structure that contains the screen coordinates of the mouse cursor. This is useful for providing help based on the position of the mouse cursor.

See Also

POINT


HELPWININFO
 HELPWININFO  QuickInfo

typedef struct {    // hwi

    int   wStructSize;

    int   x;

    int   y;

    int   dx;

    int   dy;

    int   wMax;

    TCHAR rgchMember[2];

} HELPWININFO;

The HELPWININFO structure contains the size and position of either a primary or a secondary Help window. An application can set this information by calling the WinHelp function with the HELP_SETWINPOS value.

Members

wStructSize

Specifies the structure size, in bytes.

x

Specifies the x-coordinate of the upper-left corner of the window, in screen coordinates.

y

Specifies the y-coordinate of the upper-left corner of the window, in screen coordinates.

dx

Specifies the window width, in pixels.

dy

Specifies the window height, in pixels.

wMax

Specifies how to show the window. This member must be one of the following values:

Value	Action
SW_HIDE	Hides the window and passes activation to another window.
SW_MINIMIZE	Minimizes the specified window and activates the top-level window in the Z order.
SW_RESTORE	Same as SW_SHOWNORMAL.
SW_SHOW	Activates a 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 an icon.
SW_SHOWMINNOACTIVE	Displays the window as an icon. The window that is currently active remains active.
SW_SHOWNA	Displays the window in its current state. The window that is currently active remains active.
SW_SHOWNOACTIVATE	Displays a window in its most recent size and position. The window that is currently active remains active.
SW_SHOWNORMAL	Activates and displays the window. Whether the window is minimized or maximized, Windows restores it to its original size and position.
rgchMember

Specifies the name of the window.

Remarks

Windows Help divides the display into 1024 units in both the x- and y-directions. To create a secondary window that fills the upper-left quadrant of the display, for example, an application would specify zero for the x and y members and 512 for the dx and dy members.

See Also

WinHelp


HIGHCONTRAST [New - Windows 95]
 HIGHCONTRAST  QuickInfo  Overview  Group

[New - Windows 95]

typedef struct tagHIGHCONTRAST {     // hc

    UINT cbSize;

    DWORD dwFlags;

    LPTSTR lpszDefaultScheme;

} HIGHCONTRAST, FAR* LPHIGHCONTRAST;

The HIGHCONTRAST structure contains information about the High Contrast Mode accessibility feature, which sets the appearance scheme of the user interface for maximum visibility for a visually-impaired user, and advises applications to comply with this appearance scheme.

Members

cbSize

Specifies the size, in bytes, of this structure.

dwFlags

Specifies a combination of the following values:

Value	Meaning
HCF_AVAILABLE	The High Contrast Mode is available.
HCF_CONFIRMHOTKEY	A confirmation dialog appears when the the High Contrast Mode is activated by using the hot key.
HCF_HIGHCONTRASTON	The High Contrast Mode is on.
HCF_HOTKEYACTIVE	The user can turn the High Contrast Mode on and off by simultaneously pressing the left ALT, left SHIFT, and PRINT SCREEN keys.
HCF_HOTKEYAVAILABLE	The hot key associated with the High Contrast Mode can be enabled. An application can retrieve this value, but cannot set it.
HCF_HOTKEYSOUND	A siren is played when the user turns the High Contrast Mode on or off by using the hot key.
HCF_INDICATOR	A visual indicator is displayed when the High Contrast Mode is on. This value is not currently used and is ignored.
lpszDefaultScheme

Points to a string that contains the name of the default color scheme.

Remarks

An application uses this structure when calling the SystemParametersInfo function with the SPI_GETHIGHCONTRAST or SPI_SETHIGHCONTRAST value. When using SPI_GETHIGHCONTRAST, an application must specify the cbSize member of the HIGHCONTRAST structure; the SystemParametersInfo function fills the remaining members. An application must specify all structure members when using the SPI_SETHIGHCONTRAST value.

See Also

SystemParametersInfo


HSZPAIR
 HSZPAIR  QuickInfo

typedef struct tagHSZPAIR {   // hp

    HSZ hszSvc;

    HSZ hszTopic;

} HSZPAIR;

The HSZPAIR structure contains a DDE service name and topic name. A DDE server application can use this structure during an XTYP_WILDCONNECT transaction to enumerate the service-topic pairs that it supports.

Members

hszSvc

Identifies a service name.

hszTopic

Identifies a topic name.


ICONINFO
 ICONINFO  QuickInfo

typedef struct _ICONINFO { // ii

   BOOL    fIcon;

   DWORD   xHotspot;

   DWORD   yHotspot;

   HBITMAP hbmMask;

   HBITMAP hbmColor;

} ICONINFO;

The ICONINFO structure contains information about an icon or a cursor.

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

Identifies 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.

See Also

CreateIconIndirect, GetIconInfo


ICONMETRICS
 ICONMETRICS  QuickInfo

typedef struct tagICONMETRICS {

    UINT    cbSize;

    int     iHorzSpacing;

    int     iVertSpacing;

    int     iTitleWrap;

    LOGFONT lfFont;

} ICONMETRICS, FAR *LPICONMETRICS;

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.

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.

See Also

SystemParametersInfo


IMAGEINFO [New - Windows NT]
 IMAGEINFO  QuickInfo  Overview  Group

[New - Windows NT]

The IMAGEINFO structure contains information about an image in an image list. This structure is used with the ImageList_GetImageInfo function.

typedef struct _IMAGEINFO {

    HBITMAP hbmImage;  // bitmap containing the images

    HBITMAP hbmMask;   // handle to a monochrome bitmap

    int     Unused1;   // not used

    int     Unused2;   // not used

    RECT    rcImage;   // bounding rectangle of the image

} IMAGEINFO;

Members

hbmMask

Handle to a monochrome bitmap that contains the masks for the images. If the image list does not contain a mask, this member is NULL.

rcImage

Bounding rectangle of the image within the bitmap specified by hbmImage.


INPUT_RECORD
 INPUT_RECORD  QuickInfo  Overview  Group

typedef struct _INPUT_RECORD { // ir

    WORD EventType;

    union {

        KEY_EVENT_RECORD KeyEvent;

        MOUSE_EVENT_RECORD MouseEvent;

        WINDOW_BUFFER_SIZE_RECORD WindowBufferSizeEvent;

        MENU_EVENT_RECORD MenuEvent;

        FOCUS_EVENT_RECORD FocusEvent;

    } Event;

} INPUT_RECORD;

The INPUT_RECORD structure is used to report input events in the console input buffer. These records can be read from the input buffer by using the ReadConsoleInput or PeekConsoleInput function, or written to the input buffer by using the WriteConsoleInput function.

Members

EventType

Identifies the type of input event and the event record stored in the Event member.

This member can have one of the following values:

Value	Meaning
KEY_EVENT
MOUSE_EVENT
WINDOW_BUFFER_SIZE_EVENT
MENU_EVENT
FOCUS_EVENT
Event

Contains a KEY_EVENT_RECORD, MOUSE_EVENT_RECORD, WINDOW_BUFFER_SIZE_RECORD, MENU_EVENT_RECORD, or FOCUS_EVENT_RECORD structure, depending on the event type specified by the EventType member.

See Also

FOCUS_EVENT_RECORD, KEY_EVENT_RECORD, MENU_EVENT_RECORD, MOUSE_EVENT_RECORD, PeekConsoleInput, ReadConsoleInput, WriteConsoleInput


ITEMIDLIST
 ITEMIDLIST  QuickInfo

typedef struct _ITEMIDLIST { // idl

    SHITEMID mkid;  // list of item identifers

} ITEMIDLIST, * LPITEMIDLIST;

typedef const ITEMIDLIST * LPCITEMIDLIST;

Contains a list of item identifiers.


JOB_INFO_1
 JOB_INFO_1  QuickInfo

typedef struct _JOB_INFO_1 {    // ji1

    DWORD  JobId;

    LPTSTR pPrinterName;

    LPTSTR pMachineName;

    LPTSTR pUserName;

    LPTSTR pDocument;

    LPTSTR pDatatype;

    LPTSTR pStatus;

    DWORD  Status;

    DWORD  Priority;

    DWORD  Position;

    DWORD  TotalPages;

    DWORD  PagesPrinted;

    SYSTEMTIME Submitted;

} JOB_INFO_1;

The JOB_INFO_1 structure specifies print-job information such as the job-identifier value, the name of the printer for which the job is spooled, the name of the machine that created the print job, the name of the user that owns the print job, and so on.

Members

JobId

Specifies a job identifier.

pPrinterName

Points to a null-terminated string that specifies the name of the printer for which the job is spooled.

pMachineName

Points to a null-terminated string that specifies the name of the machine that created the print job.

pUserName

Points to a null-terminated string that specifies the name of the user that owns the print job.

pDocument

Points to a null-terminated string that specifies the name of the print job (for example, "MS-WORD: Review.doc").

pDatatype

Points to a null-terminated string that specifies the type of data used to record the print job.

pStatus

Points to a null-terminated string that specifies the status of the print job. This member should be checked prior to Status and, if pStatus is NULL, the status is defined by the contents of the Status member.

Status

Specifies the job status. This member can be one or more of the following values:

JOB_STATUS_DELETING
JOB_STATUS_ERROR
JOB_STATUS_OFFLINE
JOB_STATUS_PAPEROUT
JOB_STATUS_PAUSED
JOB_STATUS_PRINTED
JOB_STATUS_PRINTING
JOB_STATUS_SPOOLING

Priority

Specifies the job priority. This member can be one of the following values or in the range between 1 through 99 (MIN_PRIORITY through MAX_PRIORITY):

Value	Meaning
MIN_PRIORITY	Minimum priority.
MAX_PRIORITY	Maximum priority.
DEF_PRIORITY	Default priority.

Position

Specifies the job's position in the print queue.

TotalPages

Specifies how many pages the document contains.

PagesPrinted

Specifies the number of pages that have printed.

Submitted

Specifies the time that this document was spooled.

See Also

EnumJobs, GetJob, SetJob


JOB_INFO_2
 JOB_INFO_2  QuickInfo

typedef struct _JOB_INFO_2 { // ji2

    DWORD      JobId;

    LPTSTR     pPrinterName;

    LPTSTR     pMachineName;

    LPTSTR     pUserName;

    LPTSTR     pDocument;

    LPTSTR     pNotifyName;

    LPTSTR     pDatatype;

    LPTSTR     pPrintProcessor;

    LPTSTR     pParameters;

    LPTSTR     pDriverName;

    LPDEVMODE  pDevMode;

    LPTSTR     pStatus;

    PSECURITY_DESCRIPTOR pSecurityDescriptor;

    DWORD      Status;

    DWORD      Priority;

    DWORD      Position;

    DWORD      StartTime;

    DWORD      UntilTime;

    DWORD      TotalPages;

    DWORD      Size;

    SYSTEMTIME Submitted;

    DWORD      Time;

    DWORD      PagesPrinted ;

} JOB_INFO_2;

The JOB_INFO_2 structure describes a full set of values associated with a job.

Members

JobId

Specifies a job identifier value.

pPrinterName

Points to a null-terminated string that specifies the name of the printer for which the job is spooled.

pMachineName

Points to a null-terminated string that specifies the name of the machine that created the print job.

pUserName

Points to a null-terminated string that specifies the name of the user who owns the print job.

pDocument

Points to a null-terminated string that specifies the name of the print job (for example, "MS-WORD: Review.doc").

pNotifyName

Points to a null-terminated string that specifies the name of the user who should be notified when the job has been printed or when an error occurs while printing the job.

pDatatype

Points to a null-terminated string that specifies the type of data used to record the print job.

pPrintProcessor

Points to a null-terminated string that specifies the name of the print processor that should be used to print the job.

pParameters

Points to a null-terminated string that specifies print-processor parameters.

pDriverName

Points to a null-terminated string that specifies the name of the printer driver that should be used to process the print job.

pDevMode

Points to a DEVMODE structure that contains device-initialization and environment data for the printer driver.

pStatus

Points to a null-terminated string that specifies the status of the print job. This member should be checked prior to Status and, if pStatus is NULL, the status is defined by the contents of the Status member.

pSecurityDescriptor

The value of this member is NULL. Retrieval and setting of document security descriptors is not supported in this release.

Status

Specifies the job status. This member can be one or more of the following values:

JOB_STATUS_PAUSED
JOB_STATUS_ERROR
JOB_STATUS_DELETING
JOB_STATUS_SPOOLING
JOB_STATUS_PRINTING
JOB_STATUS_OFFLINE
JOB_STATUS_PAPEROUT
JOB_STATUS_PRINTED

Priority

Specifies the job priority. This member can be one of the following values or in the range between 1 through 99 (MIN_PRIORITY through MAX_PRIORITY):

Value	Meaning
MIN_PRIORITY	Minimum priority.
MAX_PRIORITY	Maximum priority.
DEF_PRIORITY	Default priority.
Position

Specifies the job's position in the print queue.

StartTime

Specifies the earliest time that the job can be printed.

UntilTime

Specifies the the latest time that the job can be printed.

TotalPages

Specifies the number of pages required for the job.

Size

Specifies the size, in bytes, of the job.

Submitted

Specifies the time when the job was submitted.

Time

Specifies the total time, in seconds, that has elapsed since the job began printing.

PagesPrinted

Specifies the number of pages that have printed.

See Also

DEVMODE, EnumJobs, GetJob, SetJob


KERNINGPAIR
 KERNINGPAIR  QuickInfo

typedef struct tagKERNINGPAIR { // kp

    WORD wFirst;

    WORD wSecond;

    int  iKernAmount;

} KERNINGPAIR;

The KERNINGPAIR structure defines a kerning pair.

Members

wFirst

Specifies the character code for the first character in the kerning pair.

wSecond

Specifies the character code for the second character in the kerning pair.

iKernAmount

Specifies the amount this pair will be kerned if they appear side by side in the same font and size. This value is typically negative, because pair kerning usually results in two characters being set more tightly than normal. The value is given in logical units — that is, it depends on the current mapping mode.

See Also

GetKerningPairs


KEY_EVENT_RECORD
 KEY_EVENT_RECORD  QuickInfo

typedef struct _KEY_EVENT_RECORD { // ker

    BOOL bKeyDown;

    WORD wRepeatCount;

    WORD wVirtualKeyCode;

    WORD wVirtualScanCode;

    union {

        WCHAR UnicodeChar;

        CHAR  AsciiChar;

    } uChar;

    DWORD dwControlKeyState;

} KEY_EVENT_RECORD;

The KEY_EVENT_RECORD structure is used to report keyboard input events in a console INPUT_RECORD structure.

Members

bKeyDown

Specifies TRUE if the key is being pressed, FALSE if the key is being released.

wRepeatCount

Specifies a count indicating that a key is being held down. For example, when a key is held down, you might get five events with this member equal to 1, one event with this member equal to 5, or multiple events with this member greater than or equal to 1.

wVirtualKeyCode

Specifies the virtual-key code that identifies the given key in a device-independent manner.

wVirtualScanCode

Specifies the virtual scan code of the given key that represents the device-dependent value generated by the keyboard hardware.

uChar

Specifies the translated Unicode or ASCII character, depending on whether the wide-character (Unicode) or ANSI version of the ReadConsoleInput function was used.

dwControlKeyState

Indicates the state of the control keys. This member can be a combination of the following values:

Value	Meaning
CAPSLOCK_ON	The CAPS LOCK light is on.
ENHANCED_KEY	The key is enhanced.
LEFT_ALT_PRESSED	The left ALT key is pressed.
LEFT_CTRL_PRESSED	The left CTRL key is pressed.
NUMLOCK_ON	The NUM LOCK light is on.
RIGHT_ALT_PRESSED	The right ALT key is pressed.
RIGHT_CTRL_PRESSED	The right CTRL key is pressed.
SCROLLLOCK_ON	The SCROLL LOCK light is on.
SHIFT_PRESSED	The SHIFT key is pressed.
Remarks

Enhanced keys for the IBM® 101- and 102-key keyboards are the INS, DEL, HOME, END, PAGE UP, PAGE DOWN, and direction keys in the clusters to the left of the keypad; and the divide (/) and ENTER keys in the keypad.

Keyboard input events are generated when any key, including control keys, is pressed or released. However, the ALT key when pressed and released without combining with another character, has special meaning to Windows and is not passed through to the application. Also, the CTRL+C key combination is not passed through if the input handle is in processed mode (ENABLE_PROCESSED_INPUT).

See Also

PeekConsoleInput, ReadConsoleInput, WriteConsoleInput, INPUT_RECORD


LANA_ENUM
 LANA_ENUM  QuickInfo

typedef struct _LANA_ENUM { // le

    UCHAR length;

    UCHAR lana[MAX_LANA];

} LANA_ENUM;

The LANA_ENUM structure contains the numbers for the current LAN adapters.

Members

length

Specifies the number of valid entries in the array of LAN adapter numbers.

lana

Specifies an array of LAN adapter numbers.

Remarks

The LANA_ENUM structure is pointed to by the ncb_buffer member of the NCB structure when an application issues the NCBENUM command. The NCBENUM command is not part of the IBM NetBIOS 3.0 specification.

See Also

NCB


LARGE_INTEGER
 LARGE_INTEGER  QuickInfo

typedef struct _LARGE_INTEGER { // li

    DWORD LowPart;

    LONG  HighPart;

} LARGE_INTEGER;

The LARGE_INTEGER structure is used to represent a 64-bit signed integer value.

Members

LowPart

Specifies the low-order 32 bits.

HighPart

Specifies the high-order 32 bits.

See Also

LUID, ULARGE_INTEGER


LDT_ENTRY
 LDT_ENTRY  QuickInfo

typedef struct _LDT_ENTRY { // ldte

    WORD LimitLow;

    WORD BaseLow;

    union {

        struct {

            BYTE BaseMid;

            BYTE Flags1;

            BYTE Flags2;

            BYTE BaseHi;

        } Bytes;

        struct {

            DWORD BaseMid : 8;

            DWORD Type : 5;

            DWORD Dpl : 2;

            DWORD Pres : 1;

            DWORD LimitHi : 4;

            DWORD Sys : 1;

            DWORD Reserved_0 : 1;

            DWORD Default_Big : 1;

            DWORD Granularity : 1;

            DWORD BaseHi : 8;

        } Bits;

    } HighWord;

} LDT_ENTRY, *PLDT_ENTRY;

The LDT_ENTRY structure describes an entry in the descriptor table. This structure is valid only on x86-based systems.

Members

LimitLow

Contains the low 16 bits of the address of the last byte in the segment.

BaseLow

Contains the low 16 bits of the base address of the segment.

HighWord

Contains the high two words of the descriptor. This member may be interpreted as bytes or collections of bits, depending on the level of detail required.

The members of the Bits structure are as follows:

Member	Contents
BaseMid	Middle bits (16−23) of the base address of the segment.
Type	Bitmask that indicates the type of segment. This member can be one of the following values:
Value	Meaning
0	Read-only data segment
1	Read-write data segment
2	Unused segment
3	Read-write expand-down data segment
4	Execute-only code segment
5	Executable-readable code segment
6	Execute-only "conforming" code segment
7	Executable-readable "conforming" code segment
Dpl	Privilege level of the descriptor. This member is an integer value in the range 0 (most privileged) through 3 (least privileged).
Pres	Present flag. This member is 1 if the segment is present in physical memory or 0 if it is not.
LimitHi	High bits (16−19) of the address of the last byte in the segment.
Sys	Space that is available to system programmers. This member might be used for marking segments in some system-specific way.
Reserved_0	Reserved.
Default_Big	Size of segment. If the segment is a data segment, this member contains 1 if the segment is larger than 64 kilobytes (K) or 0 if the segment is smaller than or equal to 64K.
	If the segment is a code segment, this member contains 1 if the segment is a code segment and runs with the default (native mode) instruction set. This member contains 0 if the code segment is an 80286 code segment and runs with 16-bit offsets and the 80286-compatible instruction set.
Granularity	Granularity. This member contains 0 if the segment is byte granular, 1 if the segment is page granular.
BaseHi	High bits (24−31) of the base address of the segment.
The members of the Bytes structure are as follows:

Member	Contents
BaseMid	Middle bits (16−23) of the base address of the segment.
Flags1	Values of the Type, Dpl, and Pres members in the Bits structure.
Flags2	Values of the LimitHi, Sys, Reserved_0, Default_Big, and Granularity members in the Bits structure.
BaseHi	High bits (24−31) of the base address of the segment.
Remarks

The GetThreadSelectorEntry function fills this structure with information from an entry in the descriptor table. You can use this information to convert a segment-relative address to a linear virtual address.

The base address of a segment is the address of offset 0 in the segment. To calculate this value, combine the BaseLow, BaseMid, and BaseHi members.

The limit of a segment is the address of the last byte that can be addressed in the segment. To calculate this value, combine the LimitLow and LimitHi members.

See Also

GetThreadSelectorEntry


LIST_ENTRY
 LIST_ENTRY  QuickInfo

typedef struct _LIST_ENTRY { // le

    struct _LIST_ENTRY *Flink;

    struct _LIST_ENTRY *Blink;

} LIST_ENTRY;

The LIST_ENTRY structure is available for any entry in a double-linked list.

Members

Flink

Points to the preceding entry in a double-linked list.

Blink

Points to the next entry in a double-linked list.

Remarks

This structure can be used as the beginning of a double-linked list or as any subsequent entry in the list.


LOAD_DLL_DEBUG_INFO
 LOAD_DLL_DEBUG_INFO  QuickInfo

typedef struct _LOAD_DLL_DEBUG_INFO { // lddi

    HANDLE hFile;

    LPVOID lpBaseOfDll;

    DWORD  dwDebugInfoFileOffset;

    DWORD  nDebugInfoSize;

    LPVOID lpImageName;

    WORD fUnicode;

} LOAD_DLL_DEBUG_INFO;

The LOAD_DLL_DEBUG_INFO structure contains information about a dynamic-link library (DLL) that has just been loaded.

Members

hFile

Identifies a handle of the DLL. If this member is NULL, the handle is not valid. Otherwise, the member is opened for reading and read-sharing in the context of the debugger.

lpBaseOfDll

Points to the base address of the DLL in the address space of the process loading the DLL.

dwDebugInfoFileOffset

Specifies the offset to the debugging information in the file identified by the hFile member. The kernel expects the debugging information to be in CodeView 4.0 format. This format is currently a derivative of Common Object File Format (COFF).

nDebugInfoSize

Specifies the size, in bytes, of the debugging information in the file. If this value is zero, there is no debugging information.

lpImageName

Points to the filename associated with hFile. This member may be NULL, or it may contain the address of a string pointer in the address space of the process being debugged. That address may, in turn, either be NULL or point to the actual filename. If fUnicode is a nonzero value, the name string is Unicode; otherwise, it is ANSI.

This member is strictly optional. Debuggers must be prepared to handle the case where lpImageName is NULL or *lpImageName (in the address space of the process being debugged) is NULL. Specifically, this release of Windows NT will never provide an image name for a create process event, and it will not likely pass an image name for the first DLL event. This version of Windows NT will also never provide this information in the case of debugging events that originate from a call to the DebugActiveProcess function.

fUnicode

Indicates whether a filename specified by lpImageName is Unicode or ANSI. A nonzero value for this member indicates Unicode; zero indicates ANSI.

See Also

CREATE_PROCESS_DEBUG_INFO, CREATE_THREAD_DEBUG_INFO, DebugActiveProcess, DEBUG_EVENT


LOCALESIGNATURE [New - Windows 95]
 LOCALESIGNATURE  QuickInfo  Overview  Group

[New - Windows 95]

typedef struct tagLOCALESIGNATURE {
    DWORD  lsUsb[4];
    DWORD  lsCsbDefault[2];
    DWORD  lsCsbSupported[2];
} LOCALESIGNATURE;

The LOCALESIGNATURE structure contains extended font-signature information, including two code-page bitfields (CPBs) that define the default and supported character sets and code-pages. This structure is typically used to represent the relationships between font coverage and locales.

Members

lsUsb

A 128-bit Unicode subset bitfield (USB) identifying up to 126 Unicode subranges. Each bit, except the two most significant bits, represents a single subrange. The most significant bit is always 1 and identifies the bitfield as a font signature; the second most significant is reserved and must be 0. Unicode subranges are numbered in accordance with the ISO 10646 standard.

lsCsbDefault

A code-page bitfield that indicates the default OEM and ANSI code-pages for a locale. The code-pages may be identified by separate bits or a single bit representing a common ANSI and OEM code-page. For a list of possible bitfield values, see Code-Page Bitfields.

lsCsbSupported

A code-page bitfield that indicates all the code-pages in which the locale can be supported. For a list of possible bitfield values, see Code-Page Bitfields.


LOCALGROUP_MEMBERS_INFO_0
 LOCALGROUP_MEMBERS_INFO_0  QuickInfo

typedef struct _LOCALGROUP_MEMBERS_INFO_0 {

    PSID  lgrmi0_sid;

} LOCALGROUP_MEMBERS_INFO_0;

The LOCALGROUP_MEMBERS_INFO_0 structure is used in the NetLocalGroupAddMembers and NetLocalGroupDelMembers functions to identify a member of a local group.

Members

lgrmi0_sid

Points to the security identifier of the member.

See Also

LOCALGROUP_MEMBERS_INFO_3, NetLocalGroupAddMembers, NetLocalGroupDelMembers


LOCALGROUP_MEMBERS_INFO_3
 LOCALGROUP_MEMBERS_INFO_3  QuickInfo

typedef struct _LOCALGROUP_MEMBERS_INFO_3 {

    LPWSTR  lgrmi3_domainandname;

} LOCALGROUP_MEMBERS_INFO_3;

The LOCALGROUP_MEMBERS_INFO_3 structure is used in the NetLocalGroupAddMembers and NetLocalGroupDelMembers functions to identify a member of a local group.

Members

lgrmi3_domainandname

Points to a null-terminated Unicode string containing the name of the member prefixed by the domain name and the "\" separator character.

See Also

LOCALGROUP_MEMBERS_INFO_0, NetLocalGroupAddMembers, NetLocalGroupDelMembers


LOGBRUSH
 LOGBRUSH  QuickInfo

typedef struct tagLOGBRUSH { // lb

   UINT     lbStyle;

   COLORREF lbColor;

   LONG     lbHatch;

} LOGBRUSH;

The LOGBRUSH structure defines the style, color, and pattern of a physical brush. It is used by the CreateBrushIndirect and ExtCreatePen functions.

Members

lbStyle

Specifies the brush style. The lbStyle member must be one of the following styles:

Value	Meaning
BS_DIBPATTERN	A pattern brush defined by a device-independent bitmap (DIB) specification. If lbStyle is BS_DIBPATTERN, the lbHatch member contains a handle to a packed DIB. Windows 95 only: Creating brushes from bitmaps or DIBs larger than 8x8 pixels is not supported. If a larger bitmap is given, only a portion of the bitmap is used.
BS_DIBPATTERN8X8	Same as BS_DIBPATTERN.
BS_DIBPATTERNPT	A pattern brush defined by a device-independent bitmap (DIB) specification. If lbStyle is BS_DIBPATTERNPT, the lbHatch member contains a pointer to a packed DIB.
BS_HATCHED	Hatched brush.
BS_HOLLOW	Hollow brush.
BS_NULL	Same as BS_HOLLOW.
BS_PATTERN	Pattern brush defined by a memory bitmap.
BS_PATTERN8X8	Same as BS_PATTERN.
BS_SOLID	Solid brush.
lbColor

Specifies the color in which the brush is to be drawn. If lbStyle is the BS_HOLLOW or BS_PATTERN style, lbColor is ignored.

If lbStyle is BS_DIBPATTERN or BS_DIBPATTERNBT, the low-order word of lbColor specifies whether the bmiColors members of the BITMAPINFO structure contain explicit red, green, blue (RGB) values or indices into the currently realized logical palette. The lbColor member must be one of the following values:

Value	Meaning
DIB_PAL_COLORS	The color table consists of an array of 16-bit indices into the currently realized logical palette.
DIB_RGB_COLORS	The color table contains literal RGB values.
lbHatch

Specifies a hatch style. The meaning depends on the brush style defined by lbStyle.

If lbStyle is BS_DIBPATTERN, the lbHatch member contains a handle to a packed DIB. If lbStyle is BS_DIBPATTERNPT, the lbHatch member contains a pointer to a packed DIB.

If lbStyle is BS_HATCHED, the lbHatch member specifies the orientation of the lines used to create the hatch. It can be one of the following values:

Value	Meaning
HS_BDIAGONAL	A 45-degree upward, left-to-right hatch
HS_CROSS	Horizontal and vertical cross-hatch
HS_DIAGCROSS	45-degree crosshatch
HS_FDIAGONAL	A 45-degree downward, left-to-right hatch
HS_HORIZONTAL	Horizontal hatch
HS_VERTICAL	Vertical hatch
If lbStyle is BS_PATTERN, lbHatch is a handle to the bitmap that defines the pattern. The bitmap cannot be a DIB section bitmap, which is created by the CreateDIBSection function.

If lbStyle is BS_SOLID or BS_HOLLOW, lbHatch is ignored.

Remarks

Although lbColor controls the foreground color of a hatch brush, the SetBkMode and SetBkColor functions control the background color.

See Also

BITMAPINFO, CreateBrushIndirect, CreateDIBSection, ExtCreatePen, SetBkColor, SetBkMode


LOGCOLORSPACE [New - Windows 95]
 LOGCOLORSPACE  QuickInfo  Overview  Group

[New - Windows 95]

typedef struct tagLOGCOLORSPACE {
    DWORD         lcsSignature;

    DWORD         lcsVersion;

    DWORD         lcsSize;

    LCSCSTYPE     lcsCSType;

    LCSGAMUTMATCH lcsIntent;

    CIEXYZTRIPLE  lcsEndpoints;
    DWORD         lcsGammaRed;
    DWORD         lcsGammaGreen;

    DWORD         lcsGammaBlue;
    TCHAR         lcsFilename[MAX_PATH];

} LOGCOLORSPACE, *LPLOGCOLORSPACE;

The LOGCOLORSPACE structure contains information that defines a logical color space.

Members

lcsSignature

Color space signature.

lcsVersion

Version number; must be 0x400.

lcsSize

Size of this structure, in bytes.

lcsCSType

Color space type. Can be one of the following values:

Value	Meaning
LCS_DEVICE_RGB	Color values are device RGB values. The values are passed to the device without translation.
LCS_DEVICE_CMYK	Color values are device CMYK values. The values are passed to the device without translation
LCS_CALIBRATED_RGB	Color values are calibrated RGB values. The values are translated using the endpoints specified by the lcsEndpoints member before being passed to the device.
If LCS_CALIBRATED_RGB is not specified, the lcsEndpoints member is ignored.

lcsIntent

The gamut matching method. Can be one of the following values:

Value	Meaning
LCS_GM_BUSINESS	Maintain saturation. Used for business charts and other situations in which undithered colors are required.
LCS_GM_GRAPHICS	Maintain colormetric match. Used for graphic designs and named colors.
LCS_GM_IMAGES	Maintain contrast. Used for photographs and natural images.
lcsEndpoints

Red, green, blue endpoints.

lcsGammaRed

Scale of the red coordinate.

lcsGammaGreen

Scale of the green coordinate.

lcsGammaBlue

Scale of the blue coordinate.

lcsFilename

A null-terminated string that names a color profile file. This member is typically set to zero, but may be used to set the color space to be exactly as specified by the color profile. This is useful for devices that input color values for a specific printer, or when using an installable image color matcher. If a color profile is specified, all other members of this structure should be set to reasonable values, even if the values are not 100 percent accurate.

See Also

RGB, CMYK


LOGFONT
 LOGFONT  QuickInfo

typedef struct tagLOGFONT { // lf

   LONG lfHeight;

   LONG lfWidth;

   LONG lfEscapement;

   LONG lfOrientation;

   LONG lfWeight;

   BYTE lfItalic;

   BYTE lfUnderline;

   BYTE lfStrikeOut;

   BYTE lfCharSet;

   BYTE lfOutPrecision;

   BYTE lfClipPrecision;

   BYTE lfQuality;

   BYTE lfPitchAndFamily;

   TCHAR lfFaceName[LF_FACESIZE];

} LOGFONT;

The LOGFONT structure defines the attributes of a font.

Members

lfHeight

Specifies the height, in logical units, of the font's character cell or character. The character height value (also known as the em height) is the character cell height value minus the internal-leading value. The font mapper interprets the value specified in lfHeight in the following manner:

Value	Meaning
> 0	The font mapper transforms this value into device units and matches it against the cell height of the available fonts.
0	The font mapper uses a default height value when it searches for a match.
< 0	The font mapper transforms this value into device units and matches its absolute value against the character height of the available fonts.
For all height comparisons, the font mapper looks for the largest font that does not exceed the requested size.

This mapping occurs when the font is used for the first time.

For the MM_TEXT mapping mode, you can use the following formula to specify a height for a font with a given point size:

lfHeight = -MulDiv(PointSize, GetDeviceCaps(hDC, LOGPIXELSY), 72);

lfWidth

Specifies the average width, in logical units, of characters in the font. If lfWidth is zero, the aspect ratio of the device is matched against the digitization aspect ratio of the available fonts to find the closest match, determined by the absolute value of the difference.

lfEscapement

Specifies the angle, in tenths of degrees, between the escapement vector and the x-axis of the device. The escapement vector is parallel to the base line of a row of text.

Windows NT:

When the graphics mode is set to GM_ADVANCED, you can specify the escapement angle of the string independently of the orientation angle of the string's characters.

When the graphics mode is set to GM_COMPATIBLE, lfEscapement specifies both the escapement and orientation. You should set lfEscapement and lfOrientation to the same value.

Windows 95:

The lfEscapement member specifies both the escapement and orientation. You should set lfEscapement and lfOrientation to the same value.

lfOrientation

Specifies the angle, in tenths of degrees, between each character's base line and the x-axis of the device.

lfWeight

Specifies the weight of the font in the range 0 through 1000. For example, 400 is normal and 700 is bold. If this value is zero, a default weight is used.

The following values are defined for convenience:

Value	Weight
FW_DONTCARE	0
FW_THIN	100
FW_EXTRALIGHT	200
FW_ULTRALIGHT	200
FW_LIGHT	300
FW_NORMAL	400
FW_REGULAR	400
FW_MEDIUM	500
FW_SEMIBOLD	600
FW_DEMIBOLD	600
FW_BOLD	700
FW_EXTRABOLD	800
FW_ULTRABOLD	800
FW_HEAVY	900
FW_BLACK	900
lfItalic

Specifies an italic font if set to TRUE.

lfUnderline

Specifies an underlined font if set to TRUE.

lfStrikeOut

Specifies a strikeout font if set to TRUE.

lfCharSet

Specifies the character set. The following values are predefined:

ANSI_CHARSET
DEFAULT_CHARSET
SYMBOL_CHARSET
SHIFTJIS_CHARSET
GB2312_CHARSET
HANGEUL_CHARSET
CHINESEBIG5_CHARSET
OEM_CHARSET

Windows 95 only:

JOHAB_CHARSET
HEBREW_CHARSET
ARABIC_CHARSET
GREEK_CHARSET
TURKISH_CHARSET
THAI_CHARSET
EASTEUROPE_CHARSET
RUSSIAN_CHARSET
MAC_CHARSET
BALTIC_CHARSET

The OEM_CHARSET value specifies a character set that is operating-system dependent.

You can use the DEFAULT_CHARSET value to allow the name and size of a font to fully describe the logical font. If the specified font name does not exist, a font from any character set can be substituted for the specified font, so you should use DEFAULT_CHARSET sparingly to avoid unexpected results.

Fonts with other character sets may exist in the operating system. If an application uses a font with an unknown character set, it should not attempt to translate or interpret strings that are rendered with that font.

This parameter is important in the font mapping process. To ensure consistent results, specify a specific character set. If you specify a typeface name in the lfFaceName member, make sure that the lfCharSet value matches the character set of the typeface specified in lfFaceName.

lfOutPrecision

Specifies the output precision. The output precision defines how closely the output must match the requested font's height, width, character orientation, escapement, pitch, and font type. It can be one of the following values:

Value	Meaning
OUT_CHARACTER_PRECIS	Not used.
OUT_DEFAULT_PRECIS	Specifies the default font mapper behavior.
OUT_DEVICE_PRECIS	Instructs the font mapper to choose a Device font when the system contains multiple fonts with the same name.
OUT_OUTLINE_PRECIS	Windows NT: This value instructs the font mapper to choose from TrueType and other outline-based fonts. Windows 95: This value is not used.
OUT_RASTER_PRECIS	Instructs the font mapper to choose a raster font when the system contains multiple fonts with the same name.
OUT_STRING_PRECIS	This value is not used by the font mapper, but it is returned when raster fonts are enumerated.
OUT_STROKE_PRECIS	Windows NT: This value is not used by the font mapper, but it is returned when TrueType, other outline-based fonts, and vector fonts are enumerated.  Windows 95: This value is used to map vector fonts, and is returned when TrueType or vector fonts are enumerated.
OUT_TT_ONLY_PRECIS	Instructs the font mapper to choose from only TrueType fonts. If there are no TrueType fonts installed in the system, the font mapper returns to default behavior.
OUT_TT_PRECIS	Instructs the font mapper to choose a TrueType font when the system contains multiple fonts with the same name.
Applications can use the OUT_DEVICE_PRECIS, OUT_RASTER_PRECIS, and OUT_TT_PRECIS values to control how the font mapper chooses a font when the operating system contains more than one font with a given name. For example, if an operating system contains a font named Symbol in raster and TrueType form, specifying OUT_TT_PRECIS forces the font mapper to choose the TrueType version. Specifying OUT_TT_ONLY_PRECIS forces the font mapper to choose a TrueType font, even if it must substitute a TrueType font of another name.

lfClipPrecision

Specifies the clipping precision. The clipping precision defines how to clip characters that are partially outside the clipping region. It can be one or more of the following values:

Value	Meaning
CLIP_DEFAULT_PRECIS	Specifies default clipping behavior.
CLIP_CHARACTER_PRECIS	Not used.
CLIP_STROKE_PRECIS	Not used by the font mapper, but is returned when raster, vector, or TrueType fonts are enumerated. Windows NT: For compatibility, this value is always returned when enumerating fonts.
CLIP_MASK	Not used.
CLIP_EMBEDDED	You must specify this flag to use an embedded read-only font.
CLIP_LH_ANGLES	When this value is used, the rotation for all fonts depends on whether the orientation of the coordinate system is left-handed or right-handed.  If not used, device fonts always rotate counterclockwise, but the rotation of other fonts is dependent on the orientation of the coordinate system. For more information about the orientation of coordinate systems, see the description of the nOrientation parameter
CLIP_TT_ALWAYS	Not used.
lfQuality

Specifies the output quality. The output quality defines how carefully the graphics device interface (GDI) must attempt to match the logical-font attributes to those of an actual physical font. It can be one of the following values:

Value	Meaning
DEFAULT_QUALITY	Appearance of the font does not matter.
DRAFT_QUALITY	Appearance of the font is less important than when PROOF_QUALITY is used. For GDI raster fonts, scaling is enabled, which means that more font sizes are available, but the quality may be lower. Bold, italic, underline, and strikeout fonts are synthesized if necessary.
PROOF_QUALITY	Character quality of the font is more important than exact matching of the logical-font attributes. For GDI raster fonts, scaling is disabled and the font closest in size is chosen. Although the chosen font size may not be mapped exactly when PROOF_QUALITY is used, the quality of the font is high and there is no distortion of appearance. Bold, italic, underline, and strikeout fonts are synthesized if necessary.
lfPitchAndFamily

Specifies the pitch and family of the font. The two low-order bits specify the pitch of the font and can be one of the following values:

DEFAULT_PITCH
FIXED_PITCH
VARIABLE_PITCH

Bits 4 through 7 of the member specify the font family and can be one of the following values:

FF_DECORATIVE
FF_DONTCARE
FF_MODERN
FF_ROMAN
FF_SCRIPT
FF_SWISS

The proper value can be obtained by using the Boolean OR operator to join one pitch constant with one family constant.

Font families describe the look of a font in a general way. They are intended for specifying fonts when the exact typeface desired is not available. The values for font families are as follows:

Value	Meaning
FF_DECORATIVE	Novelty fonts. Old English is an example.
FF_DONTCARE	Don't care or don't know.
FF_MODERN	Fonts with constant stroke width (monospace), with or without serifs. Monospace fonts are usually modern. Pica, Elite, and CourierNew® are examples.
FF_ROMAN	Fonts with variable stroke width (proportional) and with serifs. MS® Serif is an example.
FF_SCRIPT	Fonts designed to look like handwriting. Script and Cursive are examples.
FF_SWISS	Fonts with variable stroke width (proportional) and without serifs. MS® Sans Serif is an example.
lfFaceName

A null-terminated string that specifies the typeface name of the font. The length of this string must not exceed 32 characters, including the null terminator. The EnumFontFamilies function can be used to enumerate the typeface names of all currently available fonts. If lfFaceName is an empty string, GDI uses the first font that matches the other specified attributes.

See Also

CreateFont, CreateFontIndirect, EnumFontFamilies


LOGPALETTE
 LOGPALETTE  QuickInfo

typedef struct tagLOGPALETTE { // lgpl

    WORD         palVersion;

    WORD         palNumEntries;

    PALETTEENTRY palPalEntry[1];

} LOGPALETTE;

The LOGPALETTE structure defines a logical color palette.

Members

palVersion

Specifies the Windows version number for the structure (currently 0x300).

palNumEntries

Specifies the number of entries in the logical color palette.

palPalEntry

Specifies an array of PALETTEENTRY structures that define the color and usage of each entry in the logical palette.

Remarks

The colors in the palette-entry table should appear in order of importance because entries earlier in the logical palette are most likely to be placed in the system palette.

See Also

CreatePalette, PALETTEENTRY


LOGPEN
 LOGPEN  QuickInfo

typedef struct tagLOGPEN { // lgpn

    UINT     lopnStyle;

    POINT    lopnWidth;

    COLORREF lopnColor;

} LOGPEN;

The LOGPEN structure defines the style, width, and color of a pen. The CreatePenIndirect function uses the LOGPEN structure.

Members

lopnStyle

Specifies the pen style, which can be one of the following values:

Value	Meaning
PS_SOLID	Pen is solid.
PS_DASH	Pen is dashed.
PS_DOT	Pen is dotted.
PS_DASHDOT	Pen has alternating dashes and dots.
PS_DASHDOTDOT	Pen has dashes and double dots.
PS_NULL	Pen is invisible.
PS_INSIDEFRAME	Pen is solid. When this pen is used in any graphics device interface (GDI) drawing function that takes a bounding rectangle, the dimensions of the figure are shrunk so that it fits entirely in the bounding rectangle, taking into account the width of the pen. This applies only to geometric pens.
lopnWidth

Specifies the POINT structure that contains the pen width, in logical units. If the pointer member is NULL, the pen is one pixel wide on raster devices. The y member in the POINT structure for lopnWidth is not used.

lopnColor

Specifies the pen color.

Remarks

If the width of the pen is greater than 1 and the pen style is PS_INSIDEFRAME, the line is drawn inside the frame of all GDI objects except polygons and polylines. If the pen color does not match an available red, green, blue (RGB) value, the pen is drawn with a logical (dithered) color. If the pen width is less than or equal to 1, the PS_INSIDEFRAME style is identical to the PS_SOLID style.

See Also

CreatePenIndirect, POINT, RGB


LUID
 LUID  QuickInfo

typedef LARGE_INTEGER LUID

An LUID is a 64-bit value guaranteed to be unique only on the system on which it was generated. The uniqueness of a locally unique identifier (LUID) is guaranteed only until the system is restarted.

An LUID is not for direct manipulation. Applications are to use functions and structures to manipulate LUID values.

See Also

AllocateLocallyUniqueId, LookupPrivilegeName, LookupPrivilegeValue, PrivilegeCheck, LUID_AND_ATTRIBUTES, PRIVILEGE_SET


LUID_AND_ATTRIBUTES
 LUID_AND_ATTRIBUTES  QuickInfo

typedef struct _LUID_AND_ATTRIBUTES { // luaa

    LUID  Luid;

    DWORD Attributes;

} LUID_AND_ATTRIBUTES;

The LUID_AND_ATTRIBUTES structure represents a locally unique identifier (LUID) and its attributes.

Members

Luid

Specifies an LUID value.

Attributes

Specifies attributes of the LUID. This value contains up to 32 one-bit flags. Its meaning is dependent on the definition and use of the LUID.

Remarks

An LUID_AND_ATTRIBUTES structure can represent an LUID whose attributes change frequently, such as when it is used to represent privileges in the PRIVILEGE_SET structure. Privileges are represented by LUIDs and have attributes indicating whether they are currently enabled or disabled.

See Also

AllocateLocallyUniqueId, LUID, PRIVILEGE_SET, TOKEN_PRIVILEGES


LV_COLUMN [New - Windows NT]
 LV_COLUMN  QuickInfo  Overview  Group

[New - Windows NT]

typedef struct _LV_COLUMN {

    UINT mask;

    int fmt;

    int cx;

    LPTSTR pszText;

    int cchTextMax;

    int iSubItem;

} LV_COLUMN;

The LV_COLUMN structure contains information about a column in report view. This structure is also used to receive information about a column.

Members

mask

Variable specifying which members contain valid information. This member can be zero, or one or more of the following values:

Value	Meaning
LVCF_FMT	The fmt member is valid.
LVCF_SUBITEM	The iSubItem member is valid.
LVCF_TEXT	The pszText member is valid.
LVCF_WIDTH	The cx member is valid.
fmt

Alignment of the column. This member can be one of the following values: LVCFMT_LEFT, LVCFMT_RIGHT, or LVCFMT_CENTER. The first column in a list view control must be left aligned; that is, the LVCFMT_RIGHT must not be specified for the first column.

cx

Width of the column, in pixels.

pszText

Pointer to a null-terminated string that contains the column heading if the structure contains information about a column. If the structure is receiving information about a column, this member specifies the address of the buffer that receives the column heading.

cchTextMax

Size of the buffer pointed to by the pszText member. If the structure is not receiving information about a column, this member is ignored.

iSubItem

Index of subitem associated with column.

Remarks

This structure is used with the LVM_GETCOLUMN, LVM_SETCOLUMN, LVM_INSERTCOLUMN, and LVM_DELETECOLUMN messages.

See Also

LVM_DELETECOLUMN, LVM_GETCOLUMN, LVM_INSERTCOLUMN, LVM_SETCOLUMN


LV_DISPINFO [New - Windows NT]
 LV_DISPINFO  QuickInfo  Overview  Group

[New - Windows NT]

typedef struct tagLV_DISPINFO {

    NMHDR   hdr;

    LV_ITEM item;

} LV_DISPINFO;

The LV_DISPINFO structure contains information needed to display an owner-drawn item in a list view control. The LV_DISPINFO structure is used with the LVN_GETDISPINFO and LVN_SETDISPINFO notification messages.

Members

hdr

Required for all WM_NOTIFY messages.

item

LV_ITEM structure that identifies the item or subitem. The structure either contains or receives information about the item. The mask member contains a set of bit flags that specify which item attributes are relevant. You can set one or more of the following bit flags:

Value	Meaning
LVIF_IMAGE	The iImage member specifies, or is to receive, the index of the item's icon in the image list.
LVIF_STATE	The state member specifies, or is to receive, the state of the item.
LVIF_TEXT	The pszText member specifies the new item text or the address of a buffer that is to receive the item text.
If the structure is receiving item text, the pszText and cchTextMax members specify the address and size of a buffer. You can either copy text to the buffer or assign the address of a string to the pszText member. In the latter case, you must not change or delete the string until the corresponding item text is deleted or two additional LVN_GETDISPINFO messages have been sent.

If you are handling the LVN_GETDISPINFO message, you can set the LVIF_DI_SETITEM flag in the mask member. This tells the operating system to store the requested list item information, and not ask for it again.

See Also

LV_ITEM, LVN_GETDISPINFO, LVN_SETDISPINFO, WM_NOTIFY


LV_FINDINFO [New - Windows NT]
 LV_FINDINFO  QuickInfo  Overview  Group

[New - Windows NT]

typedef struct _LV_FINDINFO {

    UINT flags;

    LPCTSTR psz;

    LPARAM lParam;

    POINT pt;

    UINT vkDirection;

} LV_FINDINFO;

The LV_FINDINFO structure contains information used to search for a list view item.

Members

flags

Type of search to perform. This member can be one or more of the following values:

Value	Meaning
LVFI_PARAM	Searches based on the lParam member. The lParam member of the matching item's LV_ITEM structure must match the lParam member of this structure. If this value is specified, all other values are ignored.
LVFI_PARTIAL	Matches if the item text begins with the string pointed to by the psz member. This value implies use of LVFI_STRING.
LVFI_STRING	Searches based on the item text. Unless additional values are specified, the item text of the matching item must exactly match the string pointed to by the psz member.
LVFI_WRAP	Continues the search at the beginning if no match is found.
LVFI_NEARESTXY	Finds the item nearest the specified position in the specified direction.
psz

Pointer to a null-terminated string to compare with the item text if flags specifies LVFI_STRING or LVFI_PARTIAL.

lParam

Value to compare with the lParam member of a list view item's LV_ITEM structure if the flags member specifies LVFI_PARAM.

pt

POINT structure that specifies the starting position to search from. This member is used only if LVFI_NEARESTXY is specified.

vkDirection

Direction to search in. This member is used only if LVFI_NEARESTXY is specified. If this member used, it specifies the virtual-key code of an arrow key.

Remarks

The LV_FINDINFO structure is used with the LVM_FINDITEM message.

See Also

LV_ITEM, LVM_FINDITEM, POINT


LV_HITTESTINFO [New - Windows NT]
 LV_HITTESTINFO  QuickInfo  Overview  Group

[New - Windows NT]

typedef struct _LV_HITTESTINFO {

    POINT pt;

    UINT flags;

    int iItem;

} LV_HITTESTINFO;

The LV_HITTESTINFO structure contains information about a hit test.

Members

pt

Position to hit test, in client coordinates.

flags

Variable that receives information about the results of a hit test. This member can be one or more of the following values:

Value	Meaning
LVHT_ABOVE	The position is above the client area of the control.
LVHT_BELOW	The position is below the client area of the control.
LVHT_NOWHERE	The position is inside the list view control's client window, but it is not over a list item.
LVHT_ONITEMICON	The position is over a list view item's icon.
LVHT_ONITEMLABEL	The position is over a list view item's text.
LVHT_ONITEMSTATEICON	The position is over the state image of a list view item.
LVHT_TOLEFT	The position is to the left of the list view control's client area.
LVHT_TORIGHT	The position is to the right of the list view control's client area.
You can use LVHT_ABOVE, LVHT_BELOW, LVHT_TOLEFT, and LVHT_TORIGHT to determine whether to scroll the contents of a list view control. Two of these values may be combined — for example, if the position is above and to the left of the client area.

You can test for LVHT_ONITEM to determine whether a specified position is over a list view item. This value is a bitwise-OR operation on LVHT_ONITEMICON, LVHT_ONITEMLABEL, and LVHT_ONITEMSTATEICON.

iItem

Receives the index of the matching item.

Remarks

This structure is used with the LVM_HITTEST message.

See Also

LVM_HITTEST


LV_ITEM [New - Windows NT]
 LV_ITEM  QuickInfo  Overview  Group

[New - Windows NT]

typedef struct _LV_ITEM {

    UINT   mask;

    int    iItem;

    int    iSubItem;

    UINT   state;

    UINT   stateMask;

    LPTSTR  pszText;

    int    cchTextMax;

    int    iImage;       // index of the list view item's icon

    LPARAM lParam;       // 32-bit value to associate with item

} LV_ITEM;

The LV_ITEM structure specifies or receives the attributes of a list view item.

Members

mask

A set of bit flags that specify attributes of this data structure or of an operation that is using this structure.

The following bit flags specify the members of the LV_ITEM structure that contain valid data or need to be filled in. One or more of these bit flags may be set:

Value	Meaning
LVIF_TEXT	The pszText member is valid or needs to be filled in.
LVIF_IMAGE	The iImage member is valid or needs to be filled in.
LVIF_PARAM	The lParam member is valid or needs to be filled in.
LVIF_STATE	The state member is valid or needs to be filled in..
The following bit flag is used with the LVN_GETDISPINFO notification message:

Value	Meaning
LVIF_DI_SETITEM	The operating system should store the requested list item information, and not ask for it again.
iItem

Item that this structure refers to.

iSubItem

Subitem that this structure refers to, or zero.

state and statemask

Current state of the item, and the valid states of the item. This member can be any valid combination of state flags.

pszText

Pointer to a null-terminated string that contains the item text if the structure specifies item attributes. If this member is the LPSTR_TEXTCALLBACK value, the item is a callback item. Do not set the pszText member to LPSTR_TEXTCALLBACK if the list view control has LVS_SORTASCENDING or LVS_SORTDESCENDING style.

If the structure is receiving item attributes, this member is the pointer to the buffer that receives the item text.

cchTextMax

Size of the buffer pointed to by the pszText member if the structure is receiving item attributes. If the structure specifies item attributes, this member is ignored.

iImage

Index of the list view item's icon in the icon and small icon image lists. If this member is the I_IMAGECALLBACK value, the item is a callback item.

Remarks

The LV_ITEM structure is used with a number of messages, including LVM_GETITEM, LVM_SETITEM, LVM_INSERTITEM, and LVM_DELETEITEM.

See Also

LVM_DELETEITEM, LVM_GETITEM, LVM_INSERTITEM, LVM_SETITEM


LV_KEYDOWN [New - Windows NT]
 LV_KEYDOWN  QuickInfo  Overview  Group

[New - Windows NT]

typedef struct tagLV_KEYDOWN {

    NMHDR hdr;

    WORD wVKey;

    UINT flags;

} LV_KEYDOWN;

The LV_KEYDOWN structure contains information about a keyboard event in a list view control.

Members

hdr

Required for all WM_NOTIFY messages.

wVKey

Virtual-key code.

flags

Always zero.

Remarks

The LV_KEYDOWN structure is used with the LVN_KEYDOWN notification message.

See Also

LVN_KEYDOWN, WM_NOTIFY


MAT2
 MAT2  QuickInfo

typedef struct _MAT2 { // mt2

    FIXED eM11;

    FIXED eM12;

    FIXED eM21;

    FIXED eM22;

} MAT2;

The MAT2 structure contains the values for a transformation matrix used by the GetGlyphOutline function.

Members

eM11

Specifies a fixed-point value for the M11 component of a 3 by 3 transformation matrix.

eM12

Specifies a fixed-point value for the M12 component of a 3 by 3 transformation matrix.

eM21

Specifies a fixed-point value for the M21 component of a 3 by 3 transformation matrix.

eM22

Specifies a fixed-point value for the M22 component of a 3 by 3 transformation matrix.

Remarks

The identity matrix produces a transformation in which the transformed graphical object is identical to the source object. In the identity matrix, the value of eM11 is 1, the value of eM12 is zero, the value of eM21 is zero, and the value of eM22 is 1.

See Also

GetGlyphOutline


MDICREATESTRUCT
 MDICREATESTRUCT  QuickInfo

typedef struct tagMDICREATESTRUCT { // mdic

    LPCTSTR szClass;

    LPCTSTR szTitle;

    HANDLE  hOwner;

    int     x;

    int     y;

    int     cx;

    int     cy;

    DWORD   style;

    LPARAM  lParam;

} MDICREATESTRUCT;

The MDICREATESTRUCT structure contains information about the class, title, owner, location, and size of a multiple document interface (MDI) child window.

Members

szClass

Points 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

Points to a null-terminated string that represents the title of the MDI child window. Windows displays the title in the child window's title bar.

hOwner

Identifies the instance of the application creating the MDI client window.

x

Specifies the initial horizontal position, in client coordinates, of the MDI child window. If this member is CW_USEDEFAULT, the MDI child window is assigned the default horizontal position.

y

Specifies the initial vertical position, in client coordinates, of the MDI child window. If this member is CW_USEDEFAULT, the MDI child window is assigned the default vertical position.

cx

Specifies the initial width, in device units, of the MDI child window. If this member is CW_USEDEFAULT, the MDI child window is assigned the default width.

cy

Specifies the initial height, in device units, of the MDI child window. If this member is set to CW_USEDEFAULT, the MDI child window is assigned the default height.

style

Specifies the style of the MDI child window. If the MDI client window was created with the MDIS_ALLCHILDSTYLES window style, this member can be any combination of the window styles listed in the description of the CreateWindow function. Otherwise, this member can be one or more of the following values:

Value	Meaning
WS_MINIMIZE	Creates an MDI child window that is initially minimized.
WS_MAXIMIZE	Creates an MDI child window that is initially maximized.
WS_HSCROLL	Creates an MDI child window that has a horizontal scroll bar.
WS_VSCROLL	Creates an MDI child window that has a vertical scroll bar.
lParam

Specifies an application-defined 32-bit value.

Remarks

When the MDI child window is created, Windows 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.

See Also

CLIENTCREATESTRUCT, CREATESTRUCT, WM_CREATE


MEASUREITEMSTRUCT
 MEASUREITEMSTRUCT  QuickInfo

typedef struct tagMEASUREITEMSTRUCT {   // mis

    UINT  CtlType;      // type of control

    UINT  CtlID;        // combo box, list box, or button identifier

    UINT  itemID;       // menu item, variable-height list box, or combo box identifier

    UINT  itemWidth;    // width of menu item, in pixels

    UINT  itemHeight;   // height of single item in list box menu, in pixels

    DWORD itemData;     // application-defined 32-bit value

} MEASUREITEMSTRUCT;

The MEASUREITEMSTRUCT structure informs Windows of the dimensions of an owner-drawn control or menu item. This allows Windows to process user interaction with the control correctly.

Members

CtlType

Specifies the control type. This member can be one of the following values:

Value	Meaning
ODT_BUTTON	Owner-drawn button
ODT_COMBOBOX	Owner-drawn combo box
ODT_LISTBOX	Owner-drawn list box
ODT_LISTVIEW	Owner-draw listview control
ODT_MENU	Owner-drawn menu
CtlID

Specifies the identifier of the combo box, list box, or button. This member is not used for a menu.

itemID

Specifies the identifier for a menu item or the position of a list box or combo box item. This value is specified for a list box only if it has the LBS_OWNERDRAWVARIABLE style; this value is specified for a combo box only if it has the CBS_OWNERDRAWVARIABLE style.

itemWidth

Specifies the width, in pixels, of a menu item. Before returning from the message, the owner of the owner-drawn menu item must fill this member.

itemHeight

Specifies the height, in pixels, of an individual item in a list box or a menu. Before returning from the message, the owner of the owner-drawn combo box, list box, or menu item must fill out this member.

itemData

Specifies the application-defined 32-bit value associated with the menu item. For a control, this member specifies the value last assigned to the list box or combo box by the LB_SETITEMDATA or CB_SETITEMDATA message. If the list box or combo box has the LB_HASSTRINGS or CB_HASSTRINGS style, this value is initially zero. Otherwise, this value is initially the value passed to the list box or combo box in the lParam parameter of one of the following messages:

CB_ADDSTRING
CB_INSERTSTRING
LB_ADDSTRING
LB_INSERTSTRING

Remarks

The owner window of an owner-drawn control receives a pointer to the MEASUREITEMSTRUCT structure as the lParam parameter of a WM_MEASUREITEM message. The owner-drawn control sends this message to its owner window when the control is created. The owner then fills in the appropriate members in the structure for the control and returns. This structure is common to all owner-drawn controls.

If an application does not fill the appropriate members of MEASUREITEMSTRUCT, the control or menu item may not be drawn properly.

See Also

CB_ADDSTRING, CB_INSERTSTRING, CB_SETITEMDATA, LB_ADDSTRING, LB_INSERTSTRING, LB_SETITEMDATA, WM_MEASUREITEM


MEMORY_BASIC_INFORMATION
 MEMORY_BASIC_INFORMATION  QuickInfo

typedef struct _MEMORY_BASIC_INFORMATION { // mbi

    PVOID BaseAddress;            // base address of region

    PVOID AllocationBase;         // allocation base address

    DWORD AllocationProtect;      // initial access protection

    DWORD RegionSize;             // size, in bytes, of region

    DWORD State;                  // committed, reserved, free

    DWORD Protect;                // current access protection

    DWORD Type;                   // type of pages

} MEMORY_BASIC_INFORMATION;

typedef MEMORY_BASIC_INFORMATION *PMEMORY_BASIC_INFORMATION;

The MEMORY_BASIC_INFORMATION structure contains information about a range of pages in the virtual address space of a process. The VirtualQuery and VirtualQueryEx functions use this structure.

Members

BaseAddress

Points to the base address of the region of pages.

AllocationBase

Points to the base address of a range of pages allocated by the VirtualAlloc function. The page pointed to by the BaseAddress member is contained within this allocation range.

AllocationProtect

Specifies the access protection given when the region was initially allocated. One of the following flags can be present, along with the PAGE_GUARD and PAGE_NOCACHE protection modifier flags:

Flag	Meaning
PAGE_READONLY	Enables read access to the committed region of pages. An attempt to write to the committed region results in an access violation. If the system differentiates between read-only access and execute access, an attempt to execute code in the committed region results in an access violation.
PAGE_READWRITE	Enables both read and write access to the committed region of pages.
PAGE_WRITECOPY	Gives copy-on-write access to the committed region of pages.
PAGE_EXECUTE	Enables execute access to the committed region of pages. An attempt to read or write to the committed region results in an access violation.
PAGE_EXECUTE_READ	Enables execute and read access to the committed region of pages. An attempt to write to the committed region results in an access violation.
PAGE_EXECUTE_READWRITE	Enables execute, read, and write access to the committed region of pages.
PAGE_EXECUTE_WRITECOPY	Enables execute, read, and write access to the committed region of pages. The pages are shared read-on-write and copy-on-write.
PAGE_GUARD	Protects the page with the underlying page protection. However, access to the region causes a "guard page entered" condition to be raised in the subject process. This flag is a page protection modifier, only valid when used with one of the page protections other than PAGE_NOACCESS.
PAGE_NOACCESS	Disables all access to the committed region of pages. An attempt to read from, write to, or execute in the committed region results in an access violation exception, called a general protection (GP) fault.
PAGE_NOCACHE	Allows no caching of the committed regions of pages. The hardware attributes for the physical memory should be set to no cache. This is not recommended for general usage. It is useful for device drivers; for example, mapping a video frame buffer with no caching. This flag is a page protection modifier, only valid when used with one of the page protections other than PAGE_NOACCESS.
RegionSize

Specifies the size, in bytes, of the region beginning at the base address in which all pages have identical attributes.

State

Specifies the state of the pages in the region. One of the following states is indicated:

State	Meaning
MEM_COMMIT	Indicates committed pages for which physical storage has been allocated, either in memory or in the paging file on disk.
MEM_FREE	Indicates free pages not accessible to the calling process and available to be allocated. For free pages, the information in the AllocationBase, AllocationProtect, Protect, and Type members is undefined.
MEM_RESERVE	Indicates reserved pages where a range of the process's virtual address space is reserved without allocating any physical storage. For reserved pages, the information in the Protect member is undefined.
Protect

Specifies the access protection of the pages in the region. One of the flags listed for the AllocationProtect member is specified.

Type

Specifies the type of pages in the region. The following types are defined:

Type	Meaning
MEM_IMAGE	Indicates that the memory pages within the region are mapped into the view of an image section.
MEM_MAPPED	Indicates that the memory pages within the region are mapped into the view of a section.
MEM_PRIVATE	Indicates that the memory pages within the region are private (not shared by other processes).
See Also

VirtualAlloc, VirtualQuery, VirtualQueryEx


MEMORYSTATUS
 MEMORYSTATUS  QuickInfo

typedef struct _MEMORYSTATUS { // mst

    DWORD dwLength;        // sizeof(MEMORYSTATUS)

    DWORD dwMemoryLoad;    // percent of memory in use

    DWORD dwTotalPhys;     // bytes of physical memory

    DWORD dwAvailPhys;     // free physical memory bytes

    DWORD dwTotalPageFile; // bytes of paging file

    DWORD dwAvailPageFile; // free bytes of paging file

    DWORD dwTotalVirtual;  // user bytes of address space

    DWORD dwAvailVirtual;  // free user bytes

} MEMORYSTATUS, *LPMEMORYSTATUS;

The MEMORYSTATUS structure contains information about current memory availability. The GlobalMemoryStatus function uses this structure.

Members

dwLength

Indicates the size of the structure. The calling process should set this member prior to calling GlobalMemoryStatus.

dwMemoryLoad

Specifies a number between 0 and 100 that gives a general idea of current memory utilization, in which 0 indicates no memory use and 100 indicates full memory use.

dwTotalPhys

Indicates the total number of bytes of physical memory.

dwAvailPhys

Indicates the number of bytes of physical memory available.

dwTotalPageFile

Indicates the total number of bytes that can be stored in the paging file. Note that this number does not represent the actual physical size of the paging file on disk.

dwAvailPageFile

Indicates the number of bytes available in the paging file.

dwTotalVirtual

Indicates the total number of bytes that can be described in the user mode portion of the virtual address space of the calling process.

dwAvailVirtual

Indicates the number of bytes of unreserved and uncommitted memory in the user mode portion of the virtual address space of the calling process.

See Also

GlobalMemoryStatus


MENU_EVENT_RECORD
 MENU_EVENT_RECORD  QuickInfo  Overview  Group

typedef struct _MENU_EVENT_RECORD { // mer

    UINT dwCommandId;

} MENU_EVENT_RECORD, *PMENU_EVENT_RECORD;

The MENU_EVENT_RECORD structure reports menu events in a console INPUT_RECORD structure. These events are used internally and should be ignored.

Members

dwCommandId

Used internally.

See Also

INPUT_RECORD


MENUEX_TEMPLATE_HEADER [New - Windows 95]
 MENUEX_TEMPLATE_HEADER  QuickInfo  Overview  Group

[New - Windows 95]

typedef struct

    WORD  wVersion;

    WORD  wOffset;

    DWORD dwHelpId;

} MENUEX_TEMPLATE_HEADER;

The MENUEX_TEMPLATE_HEADER structure defines the header for an extended menu template.

Members

wVersion

Template version number. This member must be 1 for extended menu templates.

wOffset

Offset of the first MENUEX_TEMPLATE_ITEM structure, relative to the end of this structure member. If the first item definition immediately follows the dwHelpId member, this member should be 4.

dwHelpId

Help identifier of menu bar

Remarks

An extended menu template consists of a MENUEX_TEMPLATE_HEADER structure followed by one or more contiguous MENUEX_TEMPLATE_ITEM structures. The MENUEX_TEMPLATE_ITEM structures, which are variable in length, are aligned on doubleword boundaries. To create a menu from an extended menu template in memory, use the LoadMenuIndirect function.

The structure definition given here is for explanation only; it is not present in any standard header file.

See Also

LoadMenuIndirect, MENUEX_TEMPLATE_ITEM


MENUEX_TEMPLATE_ITEM [New - Windows 95]
 MENUEX_TEMPLATE_ITEM  QuickInfo  Overview  Group

[New - Windows 95]

typedef struct {

    DWORD  dwType;

    DWORD  dwState;

    UINT   uId;

    BYTE   bResInfo;

    WCHAR  szText[1];

    // DWORD dwHelpId;

} MENUEX_TEMPLATE_ITEM;

The MENUEX_TEMPLATE_ITEM structure defines a menu item in an extended menu template.

Members

dwType

Menu item type. This member can be a combination of the type (beginning with MFT) values listed with the MENUITEMINFO structure.

dwState

Menu item state. This member can be a combination of the state (beginning with MFS) values listed with the MENUITEMINFO structure.

uId

Menu item identifier. This is an application-defined 16-bit value that identifies the menu item. In an extended menu resource, pop-up items as well as command items can have identifiers.

bResInfo

Value specifying whether the menu item is the last item in the menu bar or pop-up menu and whether it is a pop-up item. This member can be zero or more of these values:

Value	Meaning
MFR_END	The structure defines the last menu item in the menu bar or pop-up menu.
MFR_POPUP	The structure defines a pop-up item. Subsequent structures define menu items in the corresponding pop-up menu.
szText

Menu item text. This member, which is a null-terminated Unicode string, is aligned on a word boundary. The size of the menu item definition varies depending on the length of this string.

dwHelpId

Help identifier for a pop-up menu. This member, which is included only for pop-up items, is located at the first doubleword boundary following the variable-length szText member.

Remarks

An extended menu template consists of a MENUEX_TEMPLATE_HEADER structure followed by one or more contiguous MENUEX_TEMPLATE_ITEM structures. The MENUEX_TEMPLATE_ITEM structures, which are variable in length, are aligned on doubleword boundaries.

The structure definition given here is for explanation only; it is not present in any standard header file.

See Also

MENUEX_TEMPLATE_HEADER, MENUITEMINFO


MENUITEMINFO [New - Windows 95]
 MENUITEMINFO  QuickInfo  Overview  Group

[New - Windows 95]

typedef struct tagMENUITEMINFO {
    UINT    cbSize;

    UINT    fMask;

    UINT    fType;

    UINT    fState;

    UINT    wID;

    HMENU   hSubMenu;

    HBITMAP hbmpChecked;

    HBITMAP hbmpUnchecked;

    DWORD   dwItemData;

    LPTSTR  dwTypeData;

    UINT    cch;

} MENUITEMINFO, FAR *LPMENUITEMINFO;

The MENUITEMINFO structure contains information about a menu item.

Members

cbsize

Size of structure, in bytes.

fMask

Members to retrieve or set. This member can be one or more of these values:

Value	Meaning
MIIM_CHECKMARKS	Retrieves or sets the hbmpChecked and hbmpUnchecked members.
MIIM_DATA	Retrieves or sets the dwItemData member.
MIIM_ID	Retrieves or sets the wID member.
MIIM_STATE	Retrieves or sets the fState member.
MIIM_SUBMENU	Retrieves or sets the hSubMenu member.
MIIM_TYPE	Retrieves or sets the fType and dwTypeData members.
fType

Menu item type. This member can be one or more of these values:

Value	Meaning
MFT_BITMAP	Displays the menu item using a bitmap. The low-order word of the dwTypeData member is the bitmap handle, and the cch member is ignored.
MFT_MENUBARBREAK	Places the menu item on a new line if it is in a menu bar or in a new column if it is in a pop-up menu. A vertical line separates the new column from the old.
MFT_MENUBREAK	Places the menu item on a new line if it is in a menu bar or in a new column if it is in a pop-up menu. The columns are not separated by a vertical line.
MFT_OWNERDRAW	Assigns responsibility for drawing the menu item to the window that owns the menu. The window receives a WM_MEASUREITEM message before the menu is displayed for the first time, and a WM_DRAWITEM message whenever the appearance of the menu item must be updated. If this value is specified, the dwTypeData member contains an application-defined 32-bit value.
MFT_RADIOCHECK	Displays checked menu items using a radio-button mark instead of a check mark if the hbmpChecked member is NULL.
MFT_RIGHTJUSTIFY	Right-justifies the menu item and any subsequent items. This value is valid only if the menu item is in a menu bar.
MFT_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 if the menu item is in a pop-up menu.
MFT_STRING	Displays the menu item using a text string. The dwTypeData member is the pointer to a null-terminated string, and the cch member is the length of the string.
The MFT_BITMAP, MFT_SEPARATOR, and MFT_STRING values cannot be combined with one another.

fState

Menu item state. This member can be one or more of these values:

Value	Meaning
MFS_CHECKED	Checks the menu item. For more information about checked menu items, see the hbmpChecked member.
MFS_DEFAULT	Specifies that the menu item is the default. A menu can contain only one default menu item, which is displayed in bold.
MFS_DISABLED	Disables the menu item so that it cannot be selected, but does not gray it.
MFS_ENABLED	Enables the menu item so that it can be selected. This is the default state.
MFS_GRAYED	Disables the menu item and grays it so that it cannot be selected.
MFS_HILITE	Highlights the menu item.
MFS_UNCHECKED	Unchecks the menu item. For more information about unchecked menu items, see the hbmpUnchecked member.
MFS_UNHILITE	Removes the highlight from the menu item. This is the default state.
wID

Application-defined 16-bit value that identifies the menu item.

hSubMenu

Handle to the pop-up menu associated with the menu item. If the menu item is not a pop-up item, this member is NULL.

hbmpChecked

Handle to the bitmap to display next to the item if it is checked. If this member is NULL, a default bitmap is used. If the MFT_RADIOCHECK type value is specified, the default bitmap is a bullet. Otherwise, it is a check mark.

hbmpUnchecked

Handle to the bitmap to display next to the item if it is not checked. If this member is NULL, no bitmap is used.

dwItemData

Application-defined value associated with the menu item.

dwTypeData

Content of the menu item. The meaning of this member depends on the menu item type: the MFT_BITMAP, MFT_SEPARATOR, or MFT_STRING values.

cch

Length of the menu item text, when information is received about a menu item of the MFT_STRING type. This value is zero for other menu item types. This member is ignored when the content of a menu item is set.

Remarks

The MENUITEMINFO structure is used with the GetMenuItemInfo, InsertMenuItem, and SetMenuItemInfo functions.

See Also

GetMenuItemInfo, InsertMenuItem, SetMenuItemInfo, WM_DRAWITEM, WM_MEASUREITEM


MENUITEMTEMPLATE
 MENUITEMTEMPLATE  QuickInfo

typedef struct {    // mit

    WORD mtOption;       // menu item flags

    WORD mtID;           // menu item identifier (omitted for pop-up items)

    WCHAR mtString[1];   // null-terminated string for menu item

} MENUITEMTEMPLATE;

The MENUITEMTEMPLATE structure defines a menu item in a menu template.

Members

mtOption

Specifies one or more of the following predefined menu options that control the appearance of the menu item:

Value	Meaning
MF_CHECKED	Indicates that the menu item has a check mark next to it.
MF_GRAYED	Indicates that the menu item is initially inactive and drawn with a gray effect.
MF_HELP	Indicates that the menu item has a vertical separator to its left.
MF_MENUBARBREAK	Indicates that the menu item is placed in a new column. The old and new columns are separated by a bar.
MF_MENUBREAK	Indicates that the menu item is placed in a new column.
MF_OWNERDRAW	Indicates that the owner window of the menu is responsible for drawing all visual aspects of the menu item, including highlighted, checked, and inactive states. This option is not valid for an item in a menu bar.
MF_POPUP	Indicates that the item is a pop-up item (a pop-up item invokes a pop-up menu when the user chooses the item).
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 a pop-up item does not contain the mtID member.

mtString

Specifies the null-terminated string for the menu item.

See Also

LoadMenuIndirect, MENUITEMTEMPLATEHEADER


MENUITEMTEMPLATEHEADER
 MENUITEMTEMPLATEHEADER  QuickInfo

typedef struct {          // mith

    WORD versionNumber;   // version number; must be zero

    WORD offset;          // offset first MENUITEMTEMPLATE structure

} 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.

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.

See Also

LoadMenuIndirect, MENUITEMTEMPLATE


METAFILEPICT
 METAFILEPICT  QuickInfo

typedef struct tagMETAFILEPICT { // mfp

    LONG      mm;

    LONG      xExt;

    LONG      yExt;

    HMETAFILE hMF;

} METAFILEPICT;

The METAFILEPICT structure defines the metafile picture format used for exchanging metafile data through the clipboard.

Members

mm

Specifies the mapping mode in which the picture is drawn.

xExt

Specifies the size of the metafile picture for all modes except the MM_ISOTROPIC and MM_ANISOTROPIC modes. (For more information about these modes, see the yExt member.) The x-extent specifies the width of the rectangle within which the picture is drawn. The coordinates are in units that correspond to the mapping mode.

yExt

Specifies the size of the metafile picture for all modes except the MM_ISOTROPIC and MM_ANISOTROPIC modes. The y-extent specifies the height of the rectangle within which the picture is drawn. The coordinates are in units that correspond to the mapping mode.

For MM_ISOTROPIC and MM_ANISOTROPIC modes, which can be scaled, the xExt and yExt members contain an optional suggested size in MM_HIMETRIC units. For MM_ANISOTROPIC pictures, xExt and yExt can be zero when no suggested size is supplied. For MM_ISOTROPIC pictures, an aspect ratio must be supplied even when no suggested size is given. (If a suggested size is given, the aspect ratio is implied by the size.) To give an aspect ratio without implying a suggested size, set xExt and yExt to negative values whose ratio is the appropriate aspect ratio. The magnitude of the negative xExt and yExt values is ignored; only the ratio is used.

hMF

Identifies a memory metafile.

See Also

SetClipboardData


METAHEADER
 METAHEADER  QuickInfo

typedef struct tagMETAHEADER {  // mh

    WORD  mtType;

    WORD  mtHeaderSize;

    WORD  mtVersion;

    DWORD mtSize;

    WORD  mtNoObjects;

    DWORD mtMaxRecord;

    WORD  mtNoParameters;

} METAHEADER;

The METAHEADER structure contains information about a Windows-format metafile.

Members

mtType

Specifies whether the metafile is in memory or recorded in a disk file. This member can be one of the following values:

Value	Meaning
1	Metafile is in memory.
2	Metafile is in a disk file.
mtHeaderSize

Specifies the size, in words, of the metafile header.

mtVersion

Specifies the Windows version number. The version number for metafiles that support device-independent bitmaps (DIBs) is 0x0300. Otherwise, the version number is 0x0100.

mtSize

Specifies the size, in words, of the file.

mtNoObjects

Specifies the maximum number of objects that exist in the metafile at the same time.

mtMaxRecord

Specifies the size, in words, of the largest record in the metafile.

mtNoParameters

Reserved.

See Also

METARECORD


METARECORD
 METARECORD  QuickInfo

typedef struct tagMETARECORD {  // mr

    DWORD rdSize;

    WORD  rdFunction;

    WORD  rdParm[1];

} METARECORD;

The METARECORD structure contains a Windows-format metafile record.

Members

rdSize

Specifies the size, in words, of the record.

rdFunction

Specifies the function number.

rdParm

Specifies an array of words containing the function parameters, in reverse of the order they are passed to the function.

See Also

METAHEADER


MINIMIZEDMETRICS
 MINIMIZEDMETRICS  QuickInfo

typedef struct tagMINIMIZEDMETRICS {

    UINT    cbSize;

    int     iWidth;

    int     iHorzGap;

    int     iVertGap;

    int     iArrange;

}   MINIMIZEDMETRICS, FAR *LPMINIMIZEDMETRICS;

The MINIMIZEDMETRICS structure contains the scalable metrics associated with minimized windows. This structure is used with the SystemParametersInfo function when the SPI_GETMINIMIZEDMETRICS or SPI_SETMINIMIZEDMETRICS action value is specified.

Members

cbSize

Specifies the size of the structure, in bytes.

iWidth

Specifies the width, in pixels, of minimized windows.

iHorzGap and iVertGap

Specifies the amount of horizontal and vertical space, in pixels, between arranged minimized windows.

iArrange

Specifies the starting position and direction used when arranging minimized windows. The starting position must be one of the following values:

Value	Meaning
ARW_BOTTOMLEFT	Start at the lower-left corner of the work area.
ARW_BOTTOMRIGHT	Start at the lower-right corner of the work area.
ARW_TOPLEFT	Start at the upper-left corner of the work area.
ARW_TOPRIGHT	Start at the upper-right corner of the work area.
The direction must be one of the following values:

Value	Meaning
ARW_LEFT	Arrange left (valid with ARW_BOTTOMRIGHT and ARW_TOPRIGHT only).
ARW_RIGHT	Arrange right (valid with ARW_BOTTOMLEFT and ARW_TOPLEFT only).
ARW_UP	Arrange up (valid with ARW_BOTTOMLEFT and ARW_BOTTOMRIGHT only).
ARW_DOWN	Arrange down (valid with ARW_TOPLEFT and ARW_TOPRIGHT only).
See Also

SystemParametersInfo


MINMAXINFO
 MINMAXINFO  QuickInfo

typedef struct tagMINMAXINFO {  // mmi

    POINT ptReserved;

    POINT ptMaxSize;

    POINT ptMaxPosition;

    POINT ptMinTrackSize;

    POINT ptMaxTrackSize;

} MINMAXINFO;

The MINMAXINFO structure contains information about a window's maximized size and position and its minimum and maximum tracking size.

Members

ptReserved

Reserved; do not use.

ptMaxSize

Specifies the maximized width (point.x) and the maximized height (point.y) of the window.

ptMaxPosition

Specifies the position of the left side of the maximized window (point.x) and the position of the top of the maximized window (point.y).

ptMinTrackSize

Specifies the minimum tracking width (point.x) and the minimum tracking height (point.y) of the window.

ptMaxTrackSize

Specifies the maximum tracking width (point.x) and the maximum tracking height (point.y) of the window.

See Also

POINT, WM_GETMINMAXINFO


MODEMDEVCAPS
 MODEMDEVCAPS  QuickInfo

typedef struct modemdevcaps_tag {
    DWORD dwActualSize;               // size of returned data, in bytes
    DWORD dwRequiredSize;             // total size of structure
    DWORD dwDevSpecificOffset;        // offset of provider-defined data
    DWORD dwDevSpecificSize;          // size of provider-defined data

    // Product and version identification
    DWORD dwModemProviderVersion;     // provider version number
    DWORD dwModemManufacturerOffset;  // offset of manufacturer name
    DWORD dwModemManufacturerSize;    // length of manufacturer name
    DWORD dwModemModelOffset;         // offset of model name
    DWORD dwModemModelSize;           // length of model name
    DWORD dwModemVersionOffset;       // offset of version name
    DWORD dwModemVersionSize;         // length of version name

    // Local option capabilities
    DWORD dwDialOptions;              // bitmap of supported values
    DWORD dwCallSetupFailTimer;       // maximum in seconds
    DWORD dwInactivityTimeout;        // maximum in tenths of seconds
    DWORD dwSpeakerVolume;            // bitmap of supported values
    DWORD dwSpeakerMode;              // bitmap of supported values
    DWORD dwModemOptions;             // bitmap of supported values
    DWORD dwMaxDTERate;               // maximum value in bit/s
    DWORD dwMaxDCERate;               // maximum value in bit/s

    // Variable portion for strings and provider-specific data
    BYTE abVariablePortion [1];       // variable-length data
} MODEMDEVCAPS, *PMODEMDEVCAPS, *LPMODEMDEVCAPS;

The MODEMDEVCAPS structure contains information about the capabilities of a modem.

Members

dwActualSize

Specifies the size, in bytes, of the data actually returned to the application. This member may be less than the dwRequiredSize member, if an application did not allocate enough space for the variable-length portion of the structure.

dwRequiredSize

Specifies the number of bytes required for the entire MODEMDEVCAPS structure, including the variable-length portion.

dwDevSpecificOffset

Specifies the offset of the provider-defined portion of the structure, in bytes relative to the beginning of the structure.

dwDevSpecificSize

Specifies the size of the provider-defined portion of the structure, in bytes.

dwModemProviderVersion

Specifies the version of the service provider. The format and use of this member depends on the service provider.

dwModemManufacturerOffset

Specifies the offset of a text string that contains the name of the modem manufacturer. The offset is specified in bytes relative to the beginning of the structure.

dwModemManufacturerSize

Specifies the length of the modem manufacturer name, in bytes. The string is not null-terminated.

dwModemModelOffset

Specifies the offset of a text string that contains the model of the modem. The offset is specified in bytes relative to the beginning of the structure.

dwModemModelSize

Specifies the length of the model name, in bytes. The string is not null-terminated.

dwModemVersionOffset

Specifies the offset of a text string that gives the version and revision of the attached modem, if the provider could determine the information. The offset is specified in bytes relative to the beginning of the structure.

dwModemVersionSize

Specifies the length of the modem version string, in bytes. The string is not null-terminated.

dwDialOptions

Specifies dialing options that are supported by the modem device. This member can be zero or more of the following values:

Value	Meaning
DIALOPTION_DIALBILLING	Specifies that the modem supports waiting for billing tone (bong).
DIALOPTION_DIALQUIET	Specifies that the modem supports waiting for quiet.
DIALOPTION_DIALDIALTONE	Specifies that the modem supports waiting for a dial tone.
dwCallSetupFailTimer

Specifies the maximum call setup timeout supported by the modem, in seconds. This is the largest value that can be specified for the corresponding member of the MODEMSETTINGS structure.

dwInactivityTimeout

Specifies the maximum inactivity timeout supported by the modem, in tenths of seconds. This is the largest value that can be specified for the corresponding member of the MODEMSETTINGS structure.

dwSpeakerVolume

Specifies the speaker volume settings supported by the modem. This member can be zero or more of the following values:

Value	Meaning
MDMVOLFLAG_LOW	The modem supports low (MDMVOL_LOW) volume.
MDMVOLFLAG_MEDIUM	The modem supports medium (MDMVOL_MEDIUM) volume.
MDMVOLFLAG_HIGH	The modem supports high (MDMVOL_HIGH) volume.
dwSpeakerMode

Specifies the speaker mode settings supported by the modem. This member can be zero or more of the following values:

Value	Meaning
MDMSPKRFLAG_OFF	The modem supports the MDMSPKR_OFF speaker mode.
MDMSPKRFLAG_DIAL	The modem supports the MDMSPKR_DIAL speaker mode.
MDMSPKRFLAG_ON	The modem supports the MDMSPKR_ON speaker mode.
MDMSPKRFLAG_CALLSETUP	The modem supports the MDMSPKR_CALLSETUP speaker mode.
dwModemOptions

Specifies supported modem options. This member can be zero or more of the following values:

MDM_BLIND_DIAL	MDM_FLOWCONTROL_SOFT
MDM_CCITT_OVERRIDE	MDM_FORCED_EC
MDM_CELLULAR	MDM_SPEED_ADJUST
MDM_COMPRESSION	MDM_TONE_DIAL
MDM_ERROR_CONTROL	MDM_V23_OVERRIDE
MDM_FLOWCONTROL_HARD
When MODEMDEVCAPS is used to set modem options, as part of the MODEMSETTINGS structure, these values are used as follows:

Value	Meaning
MDM_CCITT_OVERRIDE	When set, CCITT modulations are enabled for V.21 and V.22 or V.23. When clear, bell modulations are enabled for 103 and 212A.
MDM_V23_OVERRIDE	When set, CCITT modulations are enabled for V.23. When clear, CCITT modulations are enabled for V.21 and V.22.
For V.23 to be set, both MDM_CCITT_OVERRIDE and MDM_V23_OVERRIDE must be set.

dwMaxDTERate

Maximum DTE rate in bits per second.

dwMaxDCERate

Maximum DCE rate in bits per second.

abVariablePortion

Contains variable-length information, including strings and any provider-defined information.

See Also

MODEMSETTINGS


MODEMSETTINGS
 MODEMSETTINGS  QuickInfo

typedef struct modemsettings_tag {
    DWORD dwActualSize;               // size of returned data, in bytes
    DWORD dwRequiredSize;             // total size of structure
    DWORD dwDevSpecificOffset;        // offset of provider-defined data
    DWORD dwDevSpecificSize;          // size of provider-defined data

    // Static local options (read/write)
    DWORD dwCallSetupFailTimer;       // call setup timeout, in seconds
    DWORD dwInactivityTimeout;        // inactivity timeout, in tenths of seconds
    DWORD dwSpeakerVolume;            // speaker volume level
    DWORD dwSpeakerMode;              // speaker mode
    DWORD dwPreferredModemOptions;    // bitmap specifying preferred options

    // negotiated options (read only) for current or last call
    DWORD dwNegotiatedModemOptions;   // bitmap specifying actual options
    DWORD dwNegotiatedDCERate;        // DCE rate, in bits per second

    // Variable portion for proprietary expansion
    BYTE  abVariablePortion[1];       // variable-length data
} MODEMSETTINGS, *PMODEMSETTINGS, *LPMODEMSETTINGS;

The MODEMSETTINGS structure contains information about a modem's configuration.

Members

dwActualSize

Specifies the size, in bytes, of the data actually returned to the application. This member may be less than the dwRequiredSize member if an application did not allocate enough space for the variable-length portion of the structure.

dwRequiredSize

Specifies the number of bytes required for the entire MODEMDEVCAPS structure, including the variable-length portion.

dwDevSpecificOffset

Specifies the offset of the provider-defined portion of the structure, in bytes relative to the beginning of the structure.

dwDevSpecificSize

Specifies the size of the provider-defined portion of the structure, in bytes.

dwCallSetupFailTimer

Specifies the maximum number of seconds the modem should wait, after dialing is completed, for an indication that a modem-to-modem connection has been established. If a connection is not established in this interval, the call is assumed to have failed. This member is equivalent to register S7 in Hayes® compatible modems.

dwInactivityTimeout

Specifies the maximum number of seconds of inactivity allowed after a connection is established. If no data is either transmitted or received for this period of time, the call is automatically terminated. This time-out is used to avoid excessive long distance charges or online service charges if an application unexpectedly locks up or the user leaves.

dwSpeakerVolume

Specifies the volume level of the monitor speaker when the speaker is on. This member can be one of the following values:

Value	Meaning
MDMVOL_LOW	Low volume.
MDMVOL_MEDIUM	Medium volume.
MDMVOL_HIGH	High volume.
The MODEMDEVCAPS structure specifies the speaker volumes a modem supports. Actual volumes are hardware-specific.

dwSpeakerMode

Specifies when the speaker should be on. This member can be one of the following values:

Value	Meaning
MDMSPKR_OFF	The speaker is always off.
MDMSPKR_CALLSETUP	The speaker is on until a connection is established.
MDMSPKR_ON	The speaker is always on.
MDMSPKR_DIAL	The speaker is on until a connection is established, except that it is off while the modem is actually dialing.
dwPreferredModemOptions

Specifies the modem options requested by the application. The local and remote modems negotiate modem options during call setup; this member specifies the initial negotiating position of the local modem.

The dwModemOptions member of the MODEMDEVCAPSstructure specifies the modem options supported by the local modem. For a list of modem options, see the description of the MODEMDEVCAPS structure.

dwNegotiatedModemOptions

Specifies the modem options that are actually in effect. This member is filled in after a connection is established and the local and remote modems negotiate modem options.

The dwModemOptions member of the MODEMDEVCAPS structure specifies the modem options supported by the local modem. For a list of modem options, see the description of the MODEMDEVCAPS structure.

dwNegotiatedDCERate

Specifies the DCE rate that is in effect. This member is filled in after a connection is established and the local and remote modems negotiate modem modulations.

abVariablePortion

Contains provider-defined information, if any.

See Also

MODEMDEVCAPS


MONCBSTRUCT
 MONCBSTRUCT  QuickInfo

typedef struct tagMONCBSTRUCT { // mcbst

    UINT   cb;

    DWORD  dwTime;

    HANDLE hTask;

    DWORD  dwRet;

    UINT   wType;

    UINT   wFmt;

    HCONV  hConv;

    HSZ    hsz1;

    HSZ    hsz2;

    HDDEDATA hData;

    DWORD    dwData1;

    DWORD    dwData2;

    CONVCONTEXT cc;

    DWORD  cbData;

    DWORD  Data[8];

} MONCBSTRUCT;

The MONCBSTRUCT structure contains information about the current DDE transaction. A DDE debugging application can use this structure when monitoring transactions that the system passes to the DDE callback functions of other applications.

Members

cb

Specifies the structure's size, in bytes.

dwTime

Specifies the Windows time that the transaction occurred. Windows time is the number of milliseconds that have elapsed since the system was booted.

hTask

Identifies the task (application instance) containing the DDE callback function that received the transaction.

dwRet

Specifies the value returned by the DDE callback function that processed the transaction.

wType

Identifies the transaction type.

wFmt

Specifies the format of the data exchanged (if any) during the transaction.

hConv

Identifies the conversation in which the transaction took place.

hsz1

Identifies a string.

hsz2

Identifies a string.

hData

Identifies the data exchanged (if any) during the transaction.

dwData1

Specifies additional data.

dwData2

Specifies additional data.

cc

Specifies a CONVCONTEXT structure containing language information used to share data in different languages.

cbData

Specifies the amount, in bytes, of data being passed with the transaction. This value may be more than 32 bytes.

Data

Contains the first 32 bytes of data being passed with the transaction
(8 * sizeof(DWORD)).

See Also

CONVCONTEXT, MONERRSTRUCT, MONHSZSTRUCT, MONLINKSTRUCT, MONMSGSTRUCT


MONCONVSTRUCT
 MONCONVSTRUCT  QuickInfo

typedef struct tagMONCONVSTRUCT { // mcvst

    UINT   cb;

    BOOL   fConnect;

    DWORD  dwTime;

    HANDLE hTask;

    HSZ    hszSvc;

    HSZ    hszTopic;

    HCONV  hConvClient;

    HCONV  hConvServer;

} MONCONVSTRUCT;

The MONCONVSTRUCT structure contains information about a DDE conversation. A DDE monitoring application can use this structure to obtain information about a conversation that has been established or has terminated.

Members

cb

Specifies the structure's size, in bytes.

fConnect

Indicates whether the conversation is currently established. A value of TRUE indicates the conversation is established; FALSE indicates it is not.

dwTime

Specifies the Windows time at which the conversation was established or terminated. Windows time is the number of milliseconds that have elapsed since the system was booted.

hTask

Identifies a task (application instance) that is a partner in the conversation.

hszSvc

Identifies the service name on which the conversation is established.

hszTopic

Identifies the topic name on which the conversation is established.

hConvClient

Identifies the client conversation.

hConvServer

Identifies the server conversation.

Remarks

Because string handles are local to the process, the hszSvc and hszTopic members are global atoms. Similarly, conversation handles are local to the instance; therefore, the hConvClient and hConvServer members are window handles.

The hConvClient and hConvServer members of the MONCONVSTRUCT structure do not hold the same value as would be seen by the applications engaged in the conversation. Instead, they hold a globally unique pair of values that identify the conversation.

See Also

MONCBSTRUCT, MONERRSTRUCT, MONHSZSTRUCT, MONLINKSTRUCT, MONMSGSTRUCT


MONERRSTRUCT
 MONERRSTRUCT  QuickInfo

typedef struct tagMONERRSTRUCT { // mest

    UINT   cb;

    UINT   wLastError;

    DWORD  dwTime;

    HANDLE hTask;

} MONERRSTRUCT;

The MONERRSTRUCT structure contains information about the current DDE error. A DDE monitoring application can use this structure to monitor errors returned by DDE Management Library functions.

Members

cb

Specifies the structure's size, in bytes.

wLastError

Identifies the current error.

dwTime

Specifies the Windows time that the error occurred. Windows time is the number of milliseconds that have elapsed since the system was booted.

hTask

Identifies the task (application instance) that called the DDE function that caused the error.

See Also

MONCBSTRUCT, MONCONVSTRUCT, MONHSZSTRUCT, MONLINKSTRUCT, MONMSGSTRUCT


MONHSZSTRUCT
 MONHSZSTRUCT  QuickInfo

typedef struct tagMONHSZSTRUCT { // mhst

    UINT   cb;

    BOOL   fsAction;

    DWORD  dwTime;

    HSZ    hsz;

    HANDLE hTask;

    TCHAR   str[1];

} MONHSZSTRUCT;

The MONHSZSTRUCT structure contains information about a DDE string handle. A DDE monitoring application can use this structure when monitoring the activity of the string manager component of the DDE Management Library.

Members

cb

Specifies the structure's size, in bytes.

fsAction

Specifies the action being performed on the string identified by the hsz member.

Value	Meaning
MH_CLEANUP	An application is freeing its DDE resources, causing the system to delete string handles the application had created. (The application called the DdeUninitialize function.)
MH_CREATE	An application is creating a string handle. (The application called the DdeCreateStringHandle function.)
MH_DELETE	An application is deleting a string handle. (The application called the DdeFreeStringHandle function.)
MH_KEEP	An application is increasing the usage count of a string handle. (The application called the DdeKeepStringHandle function.)
dwTime

Specifies the Windows time when the action specified by the fsAction member takes place. Windows time is the number of milliseconds that have elapsed since the system was booted.

hsz

Identifies the string. Because string handles are local to the process, this member is a global atom.

hTask

Identifies the task (application instance) performing the action on the string handle.

str

Points to the string identified by the hsz member.

See Also

MONCBSTRUCT, MONCONVSTRUCT, MONERRSTRUCT, MONLINKSTRUCT, MONMSGSTRUCT


MONITOR_INFO_1
 MONITOR_INFO_1  QuickInfo

typedef struct _MONITOR_INFO_1 { // mi1

    LPTSTR pName;

} MONITOR_INFO_1;

The MONITOR_INFO_1 structure identifies an installed monitor.

Members

pName

Points to a null-terminated string that identifies an installed monitor.

See Also

EnumMonitors, MONITOR_INFO_2


MONITOR_INFO_2
 MONITOR_INFO_2  QuickInfo

typedef struct _MONITOR_INFO_2 { // mi2

    LPTSTR pName;

    LPTSTR pEnvironment ;

    LPTSTR pDLLName ;

} MONITOR_INFO_2;

The MONITOR_INFO_2 structure identifies a monitor.

Members

pName

Points to a null-terminated string that is the name of the monitor.

pEnvironment

Points to a null-terminated environment string specifying the environment in which the monitor dynamic-link library (DLL) is designed to run.

pDLLName

Points to a null-terminated string that is the name of the monitor DLL.

See Also

EnumMonitors, MONITOR_INFO_1


MONLINKSTRUCT
 MONLINKSTRUCT  QuickInfo

typedef struct tagMONLINKSTRUCT { // mlst

    UINT   cb;

    DWORD  dwTime;

    HANDLE hTask;

    BOOL   fEstablished;

    BOOL   fNoData;

    HSZ    hszSvc;

    HSZ    hszTopic;

    HSZ    hszItem;

    UINT   wFmt;

    BOOL   fServer;

    HCONV  hConvServer;

    HCONV  hConvClient;

} MONLINKSTRUCT;

The MONLINKSTRUCT structure contains information about a DDE advise loop. A DDE monitoring application can use this structure to obtain information about an advise loop that has started or ended.

Members

cb

Specifies the structure's size, in bytes.

dwTime

Specifies the Windows time when the advise loop was started or ended. Windows time is the number of milliseconds that have elapsed since the system was booted.

hTask

Identifies a task (application instance) that is a partner in the advise loop.

fEstablished

Indicates whether an advise loop was successfully established. A value of TRUE indicates an advise loop was established; FALSE indicates it was not.

fNoData

Indicates whether the XTYPF_NODATA flag is set for the advise loop. A value of TRUE indicates the flag is set; FALSE indicates it is not.

hszSvc

Identifies the service name of the server in the advise loop.

hszTopic

Identifies the topic name on which the advise loop is established.

hszItem

Identifies the item name that is the subject of the advise loop.

wFmt

Specifies the format of the data exchanged (if any) during the advise loop.

fServer

Indicates whether the link notification came from the server. A value of TRUE indicates the notification came from the server; FALSE indicates otherwise.

hConvServer

Identifies the server conversation.

hConvClient

Identifies the client conversation.

Remarks

Because string handles are local to the process, the hszSvc, hszTopic, and hszItem members are global atoms.

The hConvClient and hConvServer members of the MONLINKSTRUCT structure do not hold the same value as would be seen by the applications engaged in the conversation. Instead, they hold a globally unique pair of values that identify the conversation.

See Also

MONCBSTRUCT, MONERRSTRUCT, MONHSZSTRUCT, MONMSGSTRUCT


MONMSGSTRUCT
 MONMSGSTRUCT  QuickInfo

typedef struct tagMONMSGSTRUCT { // mmst

    UINT   cb;

    HWND   hwndTo;

    DWORD  dwTime;

    HANDLE hTask;

    UINT   wMsg;

    WPARAM wParam;

    LPARAM lParam;

    DDEML_MSG_HOOK_DATA dmhd;

} MONMSGSTRUCT;

The MONMSGSTRUCT structure contains information about a DDE message. A DDE monitoring application can use this structure to obtain information about a DDE message that was sent or posted.

Members

cb

Specifies the structure's size, in bytes.

hwndTo

Identifies the window that receives the DDE message.

dwTime

Specifies the Windows time at which the message was sent or posted. Windows time is the number of milliseconds that have elapsed since the system was booted.

hTask

Identifies the task (application instance) containing the window that receives the DDE message.

wMsg

Specifies the identifier of the DDE message.

wParam

Specifies the wParam parameter of the DDE message.

lParam

Specifies the lParam parameter of the DDE message.

dmhd

Specifies a DDEML_MSG_HOOK_DATA structure that contains additional information about the DDE message.

See Also

DDEML_MSG_HOOK_DATA, MONCBSTRUCT, MONCONVSTRUCT, MONERRSTRUCT, MONHSZSTRUCT, MONLINKSTRUCT


MOUSE_EVENT_RECORD
 MOUSE_EVENT_RECORD  QuickInfo

typedef struct _MOUSE_EVENT_RECORD { // mer

    COORD dwMousePosition;

    DWORD dwButtonState;

    DWORD dwControlKeyState;

    DWORD dwEventFlags;

} MOUSE_EVENT_RECORD;

The MOUSE_EVENT_RECORD structure is used in a console INPUT_RECORD structure to report mouse input events.

Members

dwMousePosition

Specifies the location of the cursor in terms of the screen buffer's character-cell coordinates.

dwButtonState

Indicates the status of the mouse buttons. The least significant bit corresponds to the leftmost mouse button. The next least significant bit corresponds to the rightmost mouse button. The next bit indicates the next-to-leftmost mouse button. The bits then correspond left to right to the mouse buttons. A bit is 1 if the button was pressed.

The following constants are defined for the first five mouse buttons:

FROM_LEFT_1ST_BUTTON_PRESSED

RIGHTMOST_BUTTON_PRESSED

FROM_LEFT_2ND_BUTTON_PRESSED

FROM_LEFT_3RD_BUTTON_PRESSED

FROM_LEFT_4TH_BUTTON_PRESSED

dwControlKeyState

Indicates the state of the control keys. This member can be a combination of the following values:

Value	Meaning
RIGHT_ALT_PRESSED	The right ALT key is pressed.
LEFT_ALT_PRESSED	The left ALT key is pressed.
RIGHT_CTRL_PRESSED	The right CTRL key is pressed.
LEFT_CTRL_PRESSED	The left CTRL key is pressed.
CAPSLOCK_ON	The CAPS LOCK light is on.
ENHANCED_KEY	The key is enhanced.
NUMLOCK_ON	The NUM LOCK light is on.
SCROLLLOCK_ON	The SCROLL LOCK light is on.
SHIFT_PRESSED	The SHIFT key is pressed.
dwEventFlags

Indicates the type of mouse event. If this value is zero, it indicates a mouse button being pressed or released. Otherwise, the value is one of the following:

Value	Meaning
DOUBLE_CLICK	The second click (button press) of a double-click occurred. The first click is returned as a regular button-press event.
MOUSE_MOVED	A change in mouse position occurred.
Remarks

Mouse events are placed in the input buffer when the console is in mouse mode (ENABLE_MOUSE_INPUT).

Mouse events are generated whenever the user moves the mouse, or presses or releases one of the mouse buttons. Mouse events are placed in a console's input buffer only when the console group has the keyboard focus and the cursor is within the borders of the console's window.

See Also

INPUT_RECORD, PeekConsoleInput, ReadConsoleInput, WriteConsoleInput


MOUSEHOOKSTRUCT
 MOUSEHOOKSTRUCT  QuickInfo

typedef struct tagMOUSEHOOKSTRUCT { // ms

    POINT pt;

    HWND  hwnd;

    UINT  wHitTestCode;

    DWORD dwExtraInfo;

} MOUSEHOOKSTRUCT;

The MOUSEHOOKSTRUCT structure contains information about a mouse event.

Members

pt

Specifies a POINT structure that contains the x- and y-coordinates of the cursor, in screen coordinates.

hwnd

Identifies the window that will receive the mouse message corresponding to the mouse event.

wHitTestCode

Specifies the hit-test value. For a list of hit-test values, see the description of the WM_NCHITTEST message.

dwExtraInfo

Specifies extra information associated with the message.

See Also

GetMessageExtraInfo, POINT, SetWindowsHook, SetWindowsHookEx, WM_NCHITTEST


MOUSEKEYS
 MOUSEKEYS  QuickInfo  Overview  Group

typedef struct _MOUSEKEYS {     // mk

    DWORD cbSize;

    DWORD dwFlags;

    DWORD iMaxSpeed;

    DWORD iTimeToMaxSpeed;

    DWORD iCtrlSpeed;

    DWORD dwReserved1;

    DWORD dwReserved2;

} MOUSEKEYS;

The MOUSEKEYS structure contains information about the MouseKeys accessibility feature. When the MouseKeys feature is active, the user can use the numeric keypad to control the mousepointer, and to click, double-click, drag, and drop. By pressing NUMLOCK, the user can toggle the numeric keypad between mouse control mode and normal operation.

Members

cbSize

Specifies the size, in bytes, of this structure.

dwFlags

A set of bit-flags that specify properties of the FilterKeys feature. The following bit-flag values are defined:

Value	Meaning
MKF_AVAILABLE	If this flag is set, the MouseKeys feature is available.
MKF_CONFIRMHOTKEY	Windows 95 only: A confirmation dialog box appears when the MouseKeys feature is activated by using the hot key.
MKF_HOTKEYACTIVE	If this flag is set, the user can turn the MouseKeys feature on and off by using the hot key, which is LEFT ALT+LEFT SHIFT+NUM LOCK.
MKF_HOTKEYSOUND	If this flag is set, the system plays a siren sound when the user turns the MouseKeys feature on or off by using the hot key.
MKF_INDICATOR	Windows 95 only: A visual indicator is displayed when the MouseKeys feature is on.
MKF_MOUSEKEYSON	If this flag is set, the MouseKeys feature is on.
MKF_MODIFIERS	Windows 95 only: The CTRL key increases cursor speed by the value specified by the iCtrlSpeed member, and the SHIFT key causes the cursor to delay briefly after moving a single pixel, allowing fine positioning of the cursor. If this value is not specified, the CTRL and SHIFT keys are ignored while the user moves the mouse cursor using the arrow keys.
MKF_REPLACENUMBERS	Windows 95 only:The numeric keypad moves the mouse when the NUM LOCK key is on. If this flag is not specified, the numeric keypad moves the mouse cursor when the NUM LOCK key is off.
iMaxSpeed

Specifies the maximum speed the mouse cursor attains when an arrow key is held down.

Windows 95: Range checking is not performed.

Windows NT: Valid values are from 10 to 360.

iTimeToMaxSpeed

Specifies the length of time, in milliseconds, that it takes for the mouse cursor to reach maximum speed when an arrow key is held down. Valid values are from 1000 to 5000.

iCtrlSpeed

Windows 95: Specifies the multiplier to apply to the mouse cursor speed when the user holds down the CTRL key while using the arrow keys to move the cursor. this value is ignored if MKF_MODIFIERS is not set.

Windows NT: This member is reserved for future use. It must be set to zero.

dwReserved1

This member is reserved for future use. It must be set to zero.

dwReserved2

This member is reserved for future use. It must be set to zero.

Remarks

An application uses a MOUSEKEYS structure when calling the SystemParametersInfo function with the wAction parameter set to the SPI_GETMOUSEKEYS or SPI_SETMOUSEKEYS value. When using SPI_GETMOUSEKEYS, an application must specify the cbSize member of the MOUSEKEYS structure; the SystemParametersInfo function fills the remaining members. An application must specify all structure members when using the SPI_SETMOUSEKEYS value.

See Also

SystemParametersInfo


MSG
 MSG  QuickInfo

typedef struct tagMSG {     // msg

    HWND   hwnd;

    UINT   message;

    WPARAM wParam;

    LPARAM lParam;

    DWORD  time;

    POINT  pt;

} MSG;

The MSG structure contains message information from a thread's message queue.

Members

hwnd

Identifies the window whose window procedure receives the message.

message

Specifies the message number.

wParam

Specifies additional information about the message. The exact meaning depends on the value of the message member.

lParam

Specifies additional information about the message. The exact meaning depends on the value of the message member.

time

Specifies the time at which the message was posted.

pt

Specifies the cursor position, in screen coordinates, when the message was posted.

See Also

GetMessage, PeekMessage


MSGBOXPARAMS [New - Windows 95]
 MSGBOXPARAMS  QuickInfo  Overview  Group

[New - Windows 95]

typedef struct {

    UINT      cbSize;

    HWND      hwndOwner;

    HINSTANCE hInstance;

    LPCSTR    lpszText;

    LPCSTR    lpszCaption;

    DWORD     dwStyle;

    LPCSTR    lpszIcon;

    DWORD     dwContextHelpId;

    MSGBOXCALLBACK lpfnMsgBoxCallback;

    DWORD     dwLanguageId;

} MSGBOXPARAMS, *PMSGBOXPARAMS, FAR *LPMSGBOXPARAMS;

The MSGBOXPARAMS structure contains information used to display a message box. The MessageBoxIndirect function uses this structure.

Members

cbSize

Specifies the structure size, in bytes.

hwndOwner

Identifies the owner window; can be NULL.

hInstance

Identifies the instance containing the icon resource identified by the lpszIcon member, and the string resource identified by the lpszText or lpszCaption member.

lpszText

Points to a null-terminated string, or the identifier of a string resource, that contains the message to be displayed.

lpszCaption

Points 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 message box. Can be one or more of the values specified in the MessageBoxEx function and one of the following values:

Value	Meaning
MB_HELP	Adds a Help button to the message box. Choosing the Help button or pressing F1 generates a Help event.
MB_TOPMOST	Uses the WS_EX_TOPMOST window style.
MB_USERICON	Uses 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 a standard icon, the hInstance member should be NULL, and lpszIcon should be one of the values listed with the LoadIcon function. This parameter 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

Points 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.

See Also

HELPINFO, LoadIcon, MAKEINTRESOURCE, MAKELANGID, MessageBoxEx, MessageBoxIndirect


MSGFILTER [New - Windows NT]
 MSGFILTER  QuickInfo  Overview  Group

[New - Windows NT]

typedef struct _msgfilter {

    NMHDR nmhdr;

    UINT msg;

    _WPAD _wPad1;

    WPARAM wParam;

    _WPAD _wPad2;

    LPARAM lParam;

} 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.

Members

nmhdr

Notification header.

msg

Keyboard or mouse message identifier.

wParam

wParam parameter of the message.

lParam

lParam parameter of the message.

See Also

EN_MSGFILTER


MULTIKEYHELP
 MULTIKEYHELP  QuickInfo

typedef struct tagMULTIKEYHELP { // mkh

    DWORD  mkSize;

    TCHAR  mkKeylist;

    TCHAR  szKeyphrase[1];

} MULTIKEYHELP;

The MULTIKEYHELP structure specifies a keyword table and an associated keyword to be used by Windows Help.

Members

mkSize

Specifies the structure size, in bytes.

mkKeylist

Specifies a single character that identifies the keyword table to search.

szKeyphrase

Contains a null-terminated text string that specifies the keyword to locate in the keyword table.

See Also

WinHelp


NAME_BUFFER
 NAME_BUFFER  QuickInfo

typedef struct _NAME_BUFFER { // nb

    UCHAR name[NCBNAMSZ];

    UCHAR name_num;

    UCHAR name_flags;

} NAME_BUFFER;

The NAME_BUFFER structure contains information about a local network name. One or more NAME_BUFFER structures follows an ADAPTER_STATUS structure when an application specifies the NCBASTAT command in the ncb_command member of the NCB structure.

Members

name

Specifies the local network name. This value is in the ncb_name member of the NCB structure.

name_num

Specifies the number for the local network name. This value is in the ncb_num member of the NCB structure.

name_flags

Specifies the current state of the name table entry. This member can be one of the following values:

Value	Meaning
REGISTERING	The name specified by the name member is being added to the network.
REGISTERED	The name specified by the name member has been successfully added to the network.
DEREGISTERED	The name specified by the name member has an active session when an NCBDELNAME command is issued. The name will be removed from the name table when the session is closed.
DUPLICATE	A duplicate name was detected during registration.
DUPLICATE_DEREG	A duplicate name was detected with a pending deregistration.
GROUP_NAME	The name specified by the name member was created by using the NCBADDGRNAME command.
UNIQUE_NAME	The name specified by the name member was created by using the NCBADDNAME command.
See Also

ADAPTER_STATUS, NCB


NCB
 NCB  QuickInfo

typedef struct _NCB { // ncb

    UCHAR  ncb_command;

    UCHAR  ncb_retcode;

    UCHAR  ncb_lsn;

    UCHAR  ncb_num;

    PUCHAR ncb_buffer;

    WORD   ncb_length;

    UCHAR  ncb_callname[NCBNAMSZ];

    UCHAR  ncb_name[NCBNAMSZ];

    UCHAR  ncb_rto;

    UCHAR  ncb_sto;

    void (*ncb_post) (struct _NCB *);

    UCHAR  ncb_lana_num;

    UCHAR  ncb_cmd_cplt;

    UCHAR  ncb_reserve[10];

    HANDLE ncb_event;

} NCB;

The NCB structure describes a network control block. A pointer to this structure is passed to the Netbios function.

Members

ncb_command

Specifies the command code and a flag that indicates whether the NCB structure is processed asynchronously. The most significant bit contains the flag. If the ASYNCH constant is combined with a command code (by using the OR operator), the NCB structure is processed asynchronously. The following command codes are supported:

Code	Meaning
NCBACTION	Enables extensions to the transport interface. NCBACTION commands are mapped to TdiAction. When this code is specified, the ncb_buffer member points to a buffer to be filled with an ACTION_HEADER structure, which is optionally followed by data. NCBACTION commands cannot be canceled by using NCBCANCEL.
NCBADDGRNAME	Adds a group name to the local name table.
NCBADDNAME	Adds a unique name to the local name table.
NCBASTAT	Retrieves the status of the adapter. When this code is specified, the ncb_buffer member points to a buffer to be filled with an ADAPTER_STATUS structure, followed by an array of NAME_BUFFER structures.
NCBCALL	Opens a session with another name.
NCBCANCEL	Cancels a previous command.
NCBCHAINSEND	Sends the contents of two data buffers to the specified session partner.
NCBCHAINSENDNA	Sends the contents of two data buffers to the specified session partner and does not wait for acknowledgment.
NCBDELNAME	Deletes a name from the local name table.
NCBDGRECV	Receives a datagram from any name.
NCBDGRECVBC	Receives broadcast datagram from any host.
NCBDGSEND	Sends datagram to a specified name.
NCBDGSENDBC	Sends a broadcast datagram to every host on the local area network (LAN).
NCBENUM	Enumerates LAN adapter (LANA) numbers. When this code is specified, the ncb_buffer member points to a buffer to be filled with a LANA_ENUM structure.
NCBFINDNAME	Determines the location of a name on the network. When this code is specified, the ncb_buffer member points to a buffer to be filled with a FIND_NAME_HEADER structure followed by one or more FIND_NAME_BUFFER structures.
NCBHANGUP	Closes a specified session.
NCBLANSTALERT	Notifies the user of LAN failures that last for more than one minute.
NCBLISTEN	Enables a session to be opened with another name.
NCBRECV	Receives data from the specified session partner.
NCBRECVANY	Receives data from any session corresponding to a specified name.
NCBRESET	Resets a LAN adapter. An adapter must be reset before any other NCB command that specifies the same number in the ncb_lana_num member will be accepted.
	The IBM NetBIOS 3.0 specification documents several NCB_RESET NCB's. Win32 implements the NCB.RESET using the dynamic link routine interface. Particular values can be passed in specific bytes of the NCB, more specifically:
	• If ncb_lsn is not 0x00, all resources associated with ncb_lana_num are to be freed.
	• If ncb_lsn is 0x00, all resources associated with ncb_lana_num are to be freed, and new resources are to be allocated. The ncb_callname[0] byte specifies the maximum number of sessions, and the ncb_callname[2] byte specifies the maximum number of names. A nonzero value for the ncb_callname[3] byte requests that the application use NAME_NUMBER_1.
NCBSEND	Sends data to the specified session partner.
NCBSENDNA	Sends data to specified session partner and does not wait for an acknowledgment.
NCBSSTAT	Retrieves the status of the session. When this value is specified, the ncb_buffer member points to a buffer to be filled with a SESSION_HEADER structure, followed by one or more SESSION_BUFFER structures.
NCBTRACE	Activates or deactivates NCB tracing. Support for this command in the system is optional and system-specific.
NCBUNLINK	Unlinks the adapter.
ncb_retcode

Specifies the return code. This value is set to NRC_PENDING while an asynchronous operation is in progress. One of the following return code values can be specified:

Value	Meaning
NRC_GOODRET	The operation succeeded.
NRC_BUFLEN	An illegal buffer length was supplied.
NRC_ILLCMD	An illegal command was supplied.
NRC_CMDTMO	The command was timed out.
NRC_INCOMP	The message was incomplete. The application is to issue another command.
NRC_BADDR	The buffer address was illegal.
NRC_SNUMOUT	The session number was out of range.
NRC_NORES	No resource was available.
NRC_SCLOSED	The session was closed.
NRC_CMDCAN	The command was canceled.
NRC_DUPNAME	A duplicate name existed in the local name table.
NRC_NAMTFUL	The name table was full.
NRC_ACTSES	The command finished; the name has active sessions and is no longer registered.
NRC_LOCTFUL	The local session table was full.
NRC_REMTFUL	The remote session table was full. The request to open a session was rejected.
NRC_ILLNN	An illegal name number was specified.
NRC_NOCALL	The system did not find the name that was called.
NRC_NOWILD	Wildcards are not permitted in the ncb_name member.
NRC_INUSE	The name was already in use on the remote adapter.
NRC_NAMERR	The name was deleted.
NRC_SABORT	The session ended abnormally.
NRC_NAMCONF	A name conflict was detected.
NRC_IFBUSY	The interface was busy.
NRC_TOOMANY	Too many commands were outstanding; the application can retry the command later.
NRC_BRIDGE	The ncb_lana_num member did not specify a valid network number.
NRC_CANOCCR	The command finished while a cancel operation was occurring.
NRC_CANCEL	The NCBCANCEL command was not valid; the command was not canceled.
NRC_DUPENV	The name was defined by another local process.
NRC_ENVNOTDEF	The environment was not defined. A reset command must be issued.
NRC_OSRESNOTAV	Operating system resources were exhausted. The application can retry the command later.
NRC_MAXAPPS	The maximum number of applications was exceeded.
NRC_NOSAPS	No service access points (SAPs) were available for NetBIOS.
NRC_NORESOURCES	The requested resources were not available.
NRC_INVADDRESS	The NCB address was not valid.
	This return code is not part of the IBM NetBIOS 3.0 specification and is not returned in the NCB structure. Instead, it is returned by the Netbios function.
NRC_INVDDID	The NCB DDID was invalid.
NRC_LOCKFAIL	The attempt to lock the user area failed.
NRC_OPENERR	An error occurred during an open operation being performed by the device driver. This return code is not part of the IBM NetBIOS 3.0 specification.
NRC_SYSTEM	A system error occurred.
NRC_PENDING	An asynchronous operation is not yet finished.
ncb_lsn

Specifies the local session number. This number uniquely identifies a session within an environment.

ncb_num

Specifies the number for the local network name. This number is returned by Netbios after a successful NCBADDNAME or NCBADDGRNAME command. This number, not the name, must be used with all datagram commands and for NCBRECVANY commands.

The number for NAME_NUMBER_1 (see NCBRESET) is always 0x01. Netbios assigns values in the range 0x02 to 0xFE for the remaining names.

ncb_buffer

Points to the message buffer.

ncb_length

Specifies the size, in bytes, of the message buffer.

ncb_callname

Specifies the string that contains the remote name. Trailing space characters should be supplied to make the length of the string equal to NCBNAMSZ.

ncb_name

Specifies the string that contains the local name. Trailing space characters should be supplied to make the length of the string equal to NCBNAMSZ.

ncb_rto

Specifies the receive time-out period, in 500-millisecond units, for the session. A value of zero implies no time-out. Specified only for NCBRECV commands.

ncb_sto

Specifies the send time-out period, in 500-millisecond units, for the session. A value of zero implies no time-out. Specified only for NCBSEND and NCBCHAINSEND commands.

ncb_post

Specifies the address of the routine to call when the asynchronous NCB finishes. The completion routine is passed a pointer to the completed network control block.

ncb_lana_num

Specifies the LAN adapter number. This zero-based number corresponds to a particular transport provider using a particular LAN adapter board.

ncb_cmd_cplt

Specifies the command complete flag. This value is the same as the ncb_retcode member.

ncb_reserve

Reserved; must be zero.

ncb_event

Specifies a handle to a Windows event that is set to the signaled state when the asynchronous network control block finishes. The event is signaled if the Netbios function returns a nonzero value.

The ncb_event member must be zero if the ncb_command member does not have the ASYNCH value set or if ncb_post is non zero. Otherwise, NRC_ILLCMD is returned.

The event specified by ncb_event is set to the nonsignaled state by the system when an asynchronous NetBIOS command is accepted, and it is set to the signaled state when the asynchronous NetBIOS command finishes.

Using ncb_event to submit asynchronous requests requires fewer system resources than using ncb_post. Also, when ncb_event is nonzero, the pending request is canceled if the thread terminates before the request is processed. This is not true for requests sent by using ncb_post.

Only manual reset events should be used with Netbios. A given event should not be associated with more than one active asynchronous NetBIOS command.

See Also

ACTION_HEADER, ADAPTER_STATUS, FIND_NAME_BUFFER, FIND_NAME_HEADER, LANA_ENUM, NAME_BUFFER, Netbios, SESSION_BUFFER, SESSION_HEADER,


NCCALCSIZE_PARAMS
 NCCALCSIZE_PARAMS  QuickInfo

typedef struct _NCCALCSIZE_PARAMS { // nccp

    RECT        rgrc[3];

    PWINDOWPOS  lppos;

} 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.

Members

rgrc

Specifies an array of rectangles. The first contains the new coordinates of a window that has been moved or resized. The second contains the coordinates of the window before it was moved or resized. The third contains the coordinates of the window's client area before the window was moved or resized. If the window is a child window, the coordinates are relative to the client area of the parent window. If the window is a top-level window, the coordinates are relative to the screen origin.

lppos

Points to a WINDOWPOS structure that contains the size and position values specified in the operation that moved or resized the window.

See Also

MoveWindow, RECT, SetWindowPos, WINDOWPOS, WM_NCCALCSIZE


NDDESHAREINFO
 NDDESHAREINFO  QuickInfo  Overview  Group

typedef struct _NDDESHAREINFO {

    LONG   lRevision;

    LPTSTR lpszShareName;

    LONG   lShareType;

    LPTSTR lpszAppTopicList;

    LONG   fSharedFlag;

    LONG   fService;

    LONG   fStartAppFlag;

    LONG   nCmdShow;

    LONG   qModifyId[2];

    LONG   cNumItems;

    LPTSTR lpszItemList;

}NDDESHAREINFO;

The NDDESHAREINFO structure gets and sets DDE share attributes maintained by the NetDDE Share Database Manager (DSDM). The security descriptor associated with each DDE share is not passed through this structure but is accessed through specific functions. The NetDDE DSDM API accepts this structure for set functions; for get functions, the DSDM returns the structure packed into the supplied buffer along with the data referenced by the members lpszShareName, lpszAppTopicList, and lpszItemList.

Members

lRevision

Specifies the revision level of the NDDESHAREINFO structure. Currently, the revision level is 1.

lpszShareName

Points to a buffer containing a null-terminated string that specifies the name of the share. This string must be no more than MAX_NDDESHARENAME characters long.

lShareType

Specifies the DDE share type(s). A DDE share can assume more than one type. This member can be a combination of the following supported DDE share types:

Share type	Meaning
SHARE_TYPE_OLD	Specifies that the share contains a DDE application/topic pair.
SHARE_TYPE_NEW	Specifies that the share contains an OLE application/topic pair.
SHARE_TYPE_STATIC	Specifies that the share contains a static application/topic pair.
lpszAppTopicList

Points to a buffer containing null-terminated strings for the DDE, OLE, and static application/topic pairs. The buffer should be in the following format:

    <DDE application name>|<DDE topic name>\0

        <OLE application name>|<OLE topic name>\0

        <static application name>|<static topic name>\0\0

fSharedFlag

Specifies whether the share is accessible to remote clients for linking. If this flag is set to FALSE, the DDE share will not allow remote users to communicate through it by using DDE. However, local users can still communicate through the DDE share. Local client links are always implied if the associated DACL grants access.

fService

If this flag is set, the DDE share will not check whether the current user has set it as trusted before before allowing DDE communication through it.

fStartAppFlag

If this flag is set and the share is trusted to start applications, NetDDE will attempt to start the application specified by lpszAppTopicList if it cannot initially start a DDE conversation with the application.

nCmdShow

When NetDDE starts an application to initiate a DDE conversation with it, this value is sent to the application by the nCmdShow parameter of the WinMain function. It defines the preferred mode for the application window to be shown in. This parameter is significant only if fStartAppFlag is active. The logged on user in whose context the application is started can also override this option when promoting the share to trusted status. The default for this field is SW_SHOWMAXIMIZED.

qModifyId

An 8-byte serial number that indicates the modification serial number of the DDE share. Every time the DDE share is modified by a NDdeShareSetInfo or NDdeSetShareSecurity call, these values are changed.

cNumItems

Specifies the number of items listed in lpszItemList. If cNumItems is zero, then lpszItemList is empty, and the share information and associated security descriptor apply to all items serviced by the associated application.

lpszItemList

Points to a buffer containing null-terminated strings that specify the items the client application in a DDE transaction can request or start advise loops on. If no items are listed, the DDE share allows any item to be used. The number of items in the list must match the cNumItems count.

See Also

NDdeSetShareSecurity, NDdeShareSetInfo, WinMain


NETRESOURCE
 NETRESOURCE  QuickInfo

typedef struct _NETRESOURCE {  // nr

    DWORD  dwScope;

    DWORD  dwType;

    DWORD  dwDisplayType;

    DWORD  dwUsage;

    LPTSTR lpLocalName;

    LPTSTR lpRemoteName;

    LPTSTR lpComment;

    LPTSTR lpProvider;

} NETRESOURCE;

The NETRESOURCE structure is returned during enumeration of resources on the network and during enumeration of currently connected resources.

Members

dwScope

Specifies the scope of the enumeration. Currently, this member can be one of the following values:

Value	Meaning
RESOURCE_CONNECTED	Currently connected resources (the dwUsage member is undefined).
RESOURCE_GLOBALNET	Resources on the network.
RESOURCE_REMEMBERED	Remembered (persistent) connections (dwUsage is undefined).
dwType

Specifies a bitmask that gives the resource type. Currently, this member can be one of the following values:

Value	Meaning
RESOURCETYPE_ANY	All resources
RESOURCETYPE_DISK	Disk resources
RESOURCETYPE_PRINT	Print resources
dwDisplayType

Specifies how the network object should be displayed in a network browsing user interface. Currently, this member can be the following values:

Value	Meaning
RESOURCEDISPLAYTYPE_DOMAIN
	The object should be displayed as a domain.
RESOURCEDISPLAYTYPE_GENERIC
	The method used to display the object does not matter.
RESOURCEDISPLAYTYPE_SERVER
	The object should be displayed as a server.
RESOURCEDISPLAYTYPE_SHARE
	The object should be displayed as a sharepoint.
dwUsage

Specifies a bitmask that gives the resource usage. This member is defined only if dwScope is RESOURCE_GLOBALNET. Currently, this member can be one of the following values:

Value	Meaning
RESOURCEUSAGE_CONNECTABLE	This is a connectable resource; the name pointed to by the lpRemoteName member can be passed to the WNetAddConnection function to make a network connection.
RESOURCEUSAGE_CONTAINER	This is a container resource; the name pointed to by the lpRemoteName member can be passed to the WNetOpenEnum function to enumerate the resources in the container.
lpLocalName

Points to the name of a local device if the dwScope member is RESOURCE_CONNECTED or RESOURCE_REMEMBERED. This member is NULL if the connection does not use a device. Otherwise, it is undefined.

lpRemoteName

Points to a remote network name if the entry is a network resource.

If the entry is a current or persistent connection, lpRemoteName points to the network name associated with the name pointed to by the lpLocalName member.

lpComment

Points to a provider-supplied comment.

lpProvider

Points to the name of the provider owning this resource. This member can be NULL if the provider name is unknown.

See Also

WNetAddConnection, WNetCloseEnum, WNetEnumResource, WNetOpenEnum


NEWCPLINFO
 NEWCPLINFO  QuickInfo

typedef struct tagNEWCPLINFO {  // ncpli

    DWORD dwSize;

    DWORD dwFlags;

    DWORD dwHelpContext;

    LONG  lData;

    HICON hIcon;

    TCHAR  szName[32];

    TCHAR  szInfo[64];

    TCHAR  szHelpFile[128];

} NEWCPLINFO;

The NEWCPLINFO structure contains resource information and a user-defined value for a dialog box supported by a Control Panel application.

Members

dwSize

Specifies the length of the structure, in bytes.

dwFlags

Specifies Control Panel flags.

dwHelpContext

Specifies the context number of a topic in a Help (.HLP) file. This topic is intended to be displayed when the user selects help for the dialog box.

lData

Specifies data defined by the application.

hIcon

Identifies the icon that represents the dialog box. This icon is intended to be displayed by the application that controls the Control Panel application.

szName

Specifies a null-terminated string that contains the dialog box name. The name is intended to be displayed below the icon.

szInfo

Specifies a null-terminated string containing the dialog box description. The description is intended to be displayed when the icon for the dialog box is selected.

szHelpFile

Specifies a null-terminated string that contains the path of the help file, if any, for the application.

See Also

CPLINFO, CPL_NEWINQUIRE


NEWTEXTMETRIC
 NEWTEXTMETRIC  QuickInfo

typedef struct tagNEWTEXTMETRIC { // ntm

    LONG   tmHeight;

    LONG   tmAscent;

    LONG   tmDescent;

    LONG   tmInternalLeading;

    LONG   tmExternalLeading;

    LONG   tmAveCharWidth;

    LONG   tmMaxCharWidth;

    LONG   tmWeight;

    LONG   tmOverhang;

    LONG   tmDigitizedAspectX;

    LONG   tmDigitizedAspectY;

    BCHAR  tmFirstChar;

    BCHAR  tmLastChar;

    BCHAR  tmDefaultChar;

    BCHAR  tmBreakChar;

    BYTE   tmItalic;

    BYTE   tmUnderlined;

    BYTE   tmStruckOut;

    BYTE   tmPitchAndFamily;

    BYTE   tmCharSet;

    DWORD  ntmFlags;

    UINT   ntmSizeEM;

    UINT   ntmCellHeight;

    UINT   ntmAvgWidth;

} NEWTEXTMETRIC;

The NEWTEXTMETRIC structure contains data that describes a physical font.

Members

tmHeight

Specifies the height (ascent + descent) of characters.

tmAscent

Specifies the ascent (units above the base line) of characters.

tmDescent

Specifies the descent (units below the base line) of characters.

tmInternalLeading

Specifies the amount of leading (space) inside the bounds set by the tmHeight member. Accent marks and other diacritical characters may occur in this area. The designer may set this member to zero.

tmExternalLeading

Specifies the amount of extra leading (space) that the application adds between rows. Since this area is outside the font, it contains no marks and is not altered by text output calls in either OPAQUE or TRANSPARENT mode. The designer may set this member to zero.

tmAveCharWidth

Specifies the average width of characters in the font (generally defined as the width of the letter x). This value does not include overhang required for bold or italic characters.

tmMaxCharWidth

Specifies the width of the widest character in the font.

tmWeight

Specifies the weight of the font.

tmOverhang

Specifies the extra width per string that may be added to some synthesized fonts. When synthesizing some attributes, such as bold or italic, graphics device interface (GDI) or a device may have to add width to a string on both a per-character and per-string basis. For example, GDI makes a string bold by expanding the spacing of each character and overstriking by an offset value; it italicizes a font by shearing the string. In either case, there is an overhang past the basic string. For bold strings, the overhang is the distance by which the overstrike is offset. For italic strings, the overhang is the amount the top of the font is sheared past the bottom of the font.

The tmOverhang member enables the application to determine how much of the character width returned by a GetTextExtentPoint32 function call on a single character is the actual character width and how much is the per-string extra width. The actual width is the extent minus the overhang.

tmDigitizedAspectX

Specifies the horizontal aspect of the device for which the font was designed.

tmDigitizedAspectY

Specifies the vertical aspect of the device for which the font was designed. The ratio of the tmDigitizedAspectX and tmDigitizedAspectY members is the aspect ratio of the device for which the font was designed.

tmFirstChar

Specifies the value of the first character defined in the font.

tmLastChar

Specifies the value of the last character defined in the font.

tmDefaultChar

Specifies the value of the character to be substituted for characters that are not in the font.

tmBreakChar

Specifies the value of the character to be used to define word breaks for text justification.

tmItalic

Specifies an italic font if it is nonzero.

tmUnderlined

Specifies an underlined font if it is nonzero.

tmStruckOut

Specifies a strikeout font if it is nonzero.

tmPitchAndFamily

Specifies the pitch and family of the selected font. The low-order bit (bit 0) specifies the pitch of the font. If it is 1, the font is variable pitch (or proportional). If it is 0, the font is fixed pitch (or monospace). Bits 1 and 2 specify the font type. If both bits are 0, the font is a raster font; if bit 1 is 1 and bit 2 is 0, the font is a vector font; if bit 1 is 0 and bit 2 is set, or if both bits are 1, the font is some other type. Bit 3 is 1 if the font is a device font; otherwise, it is 0.

The four high-order bits designate the font family. The tmPitchAndFamily member can be combined with the hexadecimal value 0xF0 by using the bitwise AND operator and can then be compared with the font family names for an identical match. For more information about the font families, see the LOGFONT structure.

tmCharSet

Specifies the character set of the font.

ntmFlags

Specifies whether the font is italic, underscored, outlined, bold, and so forth. The following list shows the bits corresponding to each font type:

Bit	Meaning
0	Italic
1	Underscore
2	Negative
3	Outline
4	Strikeout
5	Bold
ntmSizeEM

Specifies the size of the em square for the font. This value is in "notional units" (that is, the units for which the font was designed).

ntmCellHeight

Specifies the height, in notional units, of the font. This value should be compared with the value of the ntmSizeEM member.

ntmAvgWidth

Specifies the average width of characters in the font, in notional units. This value should be compared with the value of the ntmSizeEM member.

Remarks

The last four members of the NEWTEXTMETRIC structure are not included in the TEXTMETRIC structure; in all other respects, the structures are identical.

The sizes in the NEWTEXTMETRIC structure are typically given in logical units; that is, they depend on the current mapping mode of the display context.

See Also

EnumFontFamilies, GetTextExtentPoint32, GetTextMetrics, LOGFONT


NEWTEXTMETRICEX [New - Windows 95]
 NEWTEXTMETRICEX  QuickInfo

[New - Windows 95]

typedef struct tagNEWTEXTMETRICEX {
    NEWTEXTMETRIC  ntmentm;
    FONTSIGNATURE  ntmeFontSignature;
} NEWTEXTMETRICEX;

The NEWTEXTMETRICEX structure contains information about a physical font.

Members

ntmentm

Specifies a NEWTEXTMETRIC structure.

ntmeFontSignature

Specifies a FONTSIGNATURE structure indicating the coverage of the font.

See Also

NEWTEXTMETRIC


NM_LISTVIEW [New - Windows NT]
 NM_LISTVIEW  QuickInfo  Overview  Group

[New - Windows NT]

typedef struct tagNM_LISTVIEW {

    NMHDR hdr;

    int   iItem;

    int   iSubItem;

    UINT  uNewState;

    UINT  uOldState;

    UINT  uChanged;

    POINT ptAction;

    LPARAM lParam;

} NM_LISTVIEW;

The NM_LISTVIEW structure contains information about a list view notification message.

Members

hdr

Required for all WM_NOTIFY messages.

iItem

List view item, or −1 if not used.

iSubItem

Subitem, or zero if none.

uNewState

New item state. This member is zero for notification messages that do not use it.

uOldState

Old item state. This member is zero for notification messages that do not use it.

uChanged

Item attributes that have changed. This member is zero for notifications that do not use it. Otherwise, it can have the same values as the mask member of the LV_ITEM structure.

ptAction

Location at which the event occurred. This member is valid only for the LVN_BEGINDRAG and LVN_BEGINRDRAG notification messages.

Remarks

The address of the NM_LISTVIEW structure is specified as the lParam parameter of the WM_NOTIFY message for several list view notification messages.

See Also

LV_ITEM, LVN_BEGINDRAG, LVN_BEGINRDRAG, WM_NOTIFY


NM_TREEVIEW [New - Windows NT]
 NM_TREEVIEW  QuickInfo  Overview  Group

[New - Windows NT]

typedef struct _NM_TREEVIEW {  nmtv

    NMHDR    hdr;

    UINT     action;        TV_ITEM  itemOld;   // see below

    TV_ITEM  itemNew;

    POINT    ptDrag;

} NM_TREEVIEW;

typedef NM_TREEVIEW FAR *LPNM_TREEVIEW;

The NM_TREEVIEW structure contains information about a tree view notification message.

Members

hdr

Required for all WM_NOTIFY messages.

action

Notification-specific action flag.

itemOld

Address of TV_ITEM structures that contain information about the old item state. This member is zero for notification messages that do not use it.

itemNew

Address of TV_ITEM structures that contain information about the new item state. This member is zero for notification messages that do not use it.

ptDrag

POINT structure that contains the client coordinates of the mouse at the time the event occurred that caused the notification message to be sent.

Remarks

The address of this structure is specified as the lParam parameter of the WM_NOTIFY message for several tree-view notification messages.

See Also

POINT, TV_ITEM, WM_NOTIFY


NM_UPDOWN [New - Windows NT]
 NM_UPDOWN  QuickInfo

[New - Windows NT]

typedef struct _NM_UPDOWN {  nmud

    NMHDR    hdr;       // notification message header

    int     iPos;        // current position

    int  iDelta;      // proposed change in position

} NM_UPDOWNW;

The NM_UPDOWN structure contains information about an up-down control notification message.

Members

hdr

Notification message header structure. This is required for all WM_NOTIFY messages.

iPos

Signed integer value that is the current position of the up-down control.

iDelta

Signed integer value that is the proposed change in the position of the up-down control.

Remarks

The address of this structure is specified as the lParam parameter of the WM_NOTIFY message for the UDN_DELTAPOS notification message.

See Also

NMHDR, UDN_DELTAPOS, WM_NOTIFY


NMHDR [New - Windows NT]
 NMHDR  QuickInfo  Overview  Group

[New - Windows NT]

typedef struct tagNMHDR {

    HWND hwndFrom;

    UINT idFrom;

    UINT code;

} NMHDR;

The NMHDR structure contains information about a notification message. The pointer to this structure is specified as the lParam member of the WM_NOTIFY message.

Members

hwndFrom

Handle to control sending message

idFrom

Identifier of control sending message

code

Notification code. This member can be a control-specific notification code, or it can be one of the following common notification values:

Value	Meaning
NM_CLICK	The user has clicked the left mouse button within the control.
NM_DBLCLK	The user has double-clicked the left mouse button within the control.
NM_KILLFOCUS	The control has lost the input focus.
NM_OUTOFMEMORY	The control could not complete an operation because there was not enough memory available.
NM_RCLICK	The user has clicked the right mouse button within the control.
NM_RDBLCLK	The user has double-clicked the right mouse button within the control.
NM_RETURN	The control has the input focus, and the user has pressed the ENTER key.
NM_SETFOCUS	The control has received the input focus.


NONCLIENTMETRICS
 NONCLIENTMETRICS  QuickInfo

typedef struct tagNONCLIENTMETRICS {

    UINT    cbSize;

    int     iBorderWidth;

    int     iScrollWidth;

    int     iScrollHeight;

    int     iCaptionWidth;

    int     iCaptionHeight;

    LOGFONT lfCaptionFont;

    int     iSmCaptionWidth;

    int     iSmCaptionHeight;

    LOGFONT lfSmCaptionFont;

    int     iMenuWidth;

    int     iMenuHeight;

    LOGFONT lfMenuFont;

    LOGFONT lfStatusFont;

    LOGFONT lfMessageFont;

} NONCLIENTMETRICS, FAR* LPNONCLIENTMETRICS;

The NONCLIENTMETRICS structure contains the scalable metrics associated with the nonclient area of a nonminimized window. This structure is used by the SPI_GETNONCLIENTMETRICS and SPI_SETNONCLIENTMETRICS actions of SystemParametersInfo.

Members

cbSize

Specifies the size of the structure, in bytes.

iBorderWidth

Specifies the thickness, in pixels, of the sizing border.

iScrollWidth

Specifies the width, in pixels, of a standard vertical scroll bar.

iScrollHeight

Specifies the height, in pixels, of a standard horizontal scroll bar.

iCaptionWidth

Specifies the width, in pixels, of caption buttons.

iCaptionHeight

Specifies the height, in pixels, of caption buttons.

lfCaptionFont

Contains information about the caption font.

iSmCaptionWidth

Specifies the width, in pixels, of small caption buttons.

iSmCaptionHeight

Specifies the height, in pixels, of small captions.

iMenuWidth

Specifies the width, in pixels, of menu-bar buttons.

iMenuHeight

Specifies the height, in pixels, of a menu bar.

lfMenuFont

Contains information about the font used in menu bars.

lfStatusFont

Contains information about the font used in status bars.

lfMessageFont

Contains information about the font used in message boxes.

See Also

SystemParametersInfo


NS_SERVICE_INFO
 NS_SERVICE_INFO  QuickInfo  Overview  Group

typedef struct _NS_SERVICE_INFO {

    DWORD   dwNameSpace;

    SERVICE_INFO ServiceInfo;

} NS_SERVICE_INFO;

The NS_SERVICE_INFO structure contains information about a network service or a network service type in the context of a specified name space, or a set of default name spaces.

Members

dwNameSpace

Specifies the name space or a set of default name spaces to which this service information applies.

Use one of the following constant values to specify a name space:

Value	Name Space
NS_DEFAULT	A set of default name spaces. The set of default name spaces typically includes all the name spaces installed on the system. System administrators, however, can exclude particular name spaces from the set.
NS_DNS	The Domain Name System used in the Internet to resolve the name of the host.
NS_MS
NS_NDS	The NetWare 4 provider.
NS_NETBT	The NetBIOS over TCP/IP layer. The operating system registers their computer names with NetBIOS. This name space is used to convert a computer name to an IP address that uses this registration.
NS_NIS
NS_SAP	The NetWare Service Advertising Protocol. This can access the Netware bindery, if appropriate. NS_SAP is a dynamic name space that enables the registration of services.
NS_STDA
NS_TCPIP_HOSTS	Lookup value in the <systemroot>\system32\drivers\etc\posts file.
NS_TCPIP_LOCAL	Local TCP/IP name resolution mechanisms, including comparisons against the local host name and lookup value in the cache of host to IP address mappings.
NS_WINS
NS_X500
ServiceInfo

A SERVICE_INFO structure that contains information about a network service or network service type.

See Also

GetService, SetService, SERVICE_INFO


NUMBERFMT
 NUMBERFMT  QuickInfo

typedef struct _numberfmt {

    UINT      NumDigits;

    UINT      LeadingZero;

    UINT      Grouping;

    LPTSTR    lpDecimalSep;

    LPTSTR    lpThousandSep;

    UINT      NegativeOrder;

} NUMBERFMT;

The NUMBERFMT structure contains information that defines the format of a number string. The GetNumberFormat function uses this information to customize a number string for a specified locale.

Members

NumDigits

Specifies the number of fractional digits. This is equivalent to the locale information specified by the LCTYPE constant value LOCALE_IDIGITS.

LeadingZero

Specifies whether to use leading zeroes in decimal fields. This is equivalent to the locale information specified by the LCTYPE constant value LOCALE_ILZERO.

Grouping

Specifies the size of each group of digits to the left of the decimal. Values in the range 0 − 9 are valid.

lpDecimalSep

Points to a null-terminated decimal separator string.

lpThousandSep

Points to a null-terminated thousand separator string.

NegativeOrder

Specifies the negative number mode. This is equivalent to the locale information specified by the LCTYPE constant value LOCALE_INEGNUMBER.

Remarks

For more information about the LCTYPE constants, see LCTYPE Constants.

See Also

GetNumberFormat


OFNOTIFY
 OFNOTIFY  Overview  Group

typedef struct _OFNOTIFY {  // on

    NMHDR          hdr;

    LPOPENFILENAME lpOFN;

    LPTSTR         pszFile;

} OFNOTIFY, FAR *LPOFNOTIFY;

Contains information about the WM_NOTIFY message sent to a hook function from an Open or Save As dialog box. The address of the OFNOTIFY structure is passed as the lParam parameter of the WM_NOTIFY message.

Members

hdr

Handle to an NMHDR structure. The code member of this structure identifies the notification message being sent and can be one of the CDN_ notification message values.

lpOFN

Handle to an OPENFILENAME structure that contains the initialization parameters for the Open or Save As dialog box.

pszFile

Pointer to the filename for which a sharing violation has occurred. The member is valid only with the CDN_SHAREVIOLATION notification message.

See Also

NMHDR, OPENFILENAME


OFSTRUCT
 OFSTRUCT  QuickInfo

typedef struct _OFSTRUCT { // of

    BYTE cBytes;

    BYTE fFixedDisk;

    WORD nErrCode;

    WORD Reserved1;

    WORD Reserved2;

    CHAR szPathName[OFS_MAXPATHNAME];

} OFSTRUCT;

The OFSTRUCT structure contains information about a file that the OpenFile function opened or attempted to open.

Members

cBytes

Specifies the length, in bytes, of the structure.

fFixedDisk

Specifies whether the file is on a hard (fixed) disk. This member is nonzero if the file is on a hard disk.

nErrCode

Specifies the MS-DOS error code if the OpenFile function failed.

Reserved1

Reserved; do not use.

Reserved2

Reserved; do not use.

szPathName

Specifies the path and filename of the file. This string consists of characters from the Windows character set.

See Also

OpenFile


OPENFILENAME
 OPENFILENAME  QuickInfo

typedef struct tagOFN { // ofn

    DWORD         lStructSize;

    HWND          hwndOwner;

    HINSTANCE     hInstance;

    LPCTSTR       lpstrFilter;

    LPTSTR        lpstrCustomFilter;

    DWORD         nMaxCustFilter;

    DWORD         nFilterIndex;

    LPTSTR        lpstrFile;

    DWORD         nMaxFile;

    LPTSTR        lpstrFileTitle;

    DWORD         nMaxFileTitle;

    LPCTSTR       lpstrInitialDir;

    LPCTSTR       lpstrTitle;

    DWORD         Flags;

    WORD          nFileOffset;

    WORD          nFileExtension;

    LPCTSTR       lpstrDefExt;

    DWORD         lCustData;

    LPOFNHOOKPROC lpfnHook;

    LPCTSTR       lpTemplateName;

} OPENFILENAME;

The OPENFILENAME structure contains information the operating system uses to initialize the system-defined 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.

Members

lStructSize

Specifies the length, in bytes, of the structure.

hwndOwner

Identifies the window that owns the dialog box. This member can be any valid window handle, or it can be NULL if the dialog box has no owner.

hInstance

Identifies a data block that contains a dialog box template specified by the lpTemplateName member (if the Flags member is set to OFN_ENABLETEMPLATE).  Identifies the memory object containing a dialog box template (if Flags is set to OFN_ENABLETEMPLATEHANDLE). If neither OFN_ENABLETEMPLATE nor OFN_ENABLETEMPLATEHANDLE is set, this member is ignored.

lpstrFilter

Points to a buffer containing pairs of null-terminated filter strings. The first string in each pair describes a filter (for example, "Text Files"), and the second specifies the filter pattern (for example, "*.TXT"). Multiple filters can be specified for a single item by separating the filter pattern strings with a semicolon (for example, "*.TXT;*.DOC;*.BAK"). The last string in the buffer must be terminated by two NULL characters. If this member is NULL, the dialog box will not display any filters. The filter strings are assumed to be in the proper order — the operating system does not change the order.

lpstrCustomFilter

Points to a buffer containing a pair of user-defined filter strings. The first string describes the filter, and the second specifies the filter pattern (for example "WinWord, *.docnn"). The buffer is terminated by two NULL characters. The operating system copies the strings to the buffer when the user closes the dialog box. The system uses the strings to initialize the user-defined file filter the next time the dialog box is created. If this member is NULL, the dialog box lists but does not save user-defined filter strings.

Windows 95: If this member is NULL, the member is ignored.

If this member is not NULL, the value of the nMaxCustFilter member is used to determine the length of the corresponding string.

nMaxCustFilter

Specifies the size, in bytes or characters, of the buffer identified by lpstrCustomFilter. This buffer should be at least 40 characters long. This member is ignored if lpstrCustomFilter is NULL or points to a NULL string.

Windows 95: The value of nMaxcustFilter is used whenever lpstrCustomFilter is defined.

nFilterIndex

Specifies an index into the buffer pointed to by lpstrFilter. The system uses the index value to obtain a pair of strings to use as the initial filter description and filter pattern for the dialog box. The first pair of strings has an index value of 1. When the user closes the dialog box, the system copies the index of the selected filter strings into this location. If nFilterIndex is zero, the custom filter is used. If nFilterIndex is zero and lpstrCustomFilter is NULL, the system uses the first filter in the buffer identified by lpstrFilter. 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

Points to a buffer that contains a filename used to initialize the File Name edit control. The first character of this buffer must be NULL if initialization is not necessary. When the GetOpenFileName or GetSaveFileName function returns, this buffer contains the drive designator, path, filename, and extension of the selected file.

If the buffer is too small, the dialog box procedure copies the required size into this member.

nMaxFile

Windows NT: Specifies the size, in characters, of the buffer pointed to by lpstrFile. The GetOpenFileName and GetSaveFileName functions return FALSE if the buffer is too small to contain the file information. The buffer should be at least 256 characters long. This member is ignored if lpstrFile is NULL.

Windows 95: Specifies the size in bytes or characters of the buffer pointed to by lpstrFile. The buffer should be at least 260 charcters long. this member is ignored if lpstrFile is NULL.

lpstrFileTitle

Points to a buffer that receives the title of the selected file. For Windows versions 3.0 and 3.1, this buffer receives the filename and extension without path information. The application should use this string to display the file title. If this member is NULL, the function does not copy the file title.

nMaxFileTitle

Specifies the maximum length of the string that can be copied into the lpstrFileTitle buffer. This member is ignored if lpstrFileTitle is NULL.

lpstrInitialDir

Points to a string that specifies the initial file directory. If this member is NULL, the system uses the current directory as the initial directory.

lpstrTitle

Points 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

Specifies the dialog box creation flags. This member may be a combination of the following flags:

Flag	Meaning
OFN_ALLOWMULTISELECT
	Specifies that the File Name list box allows multiple selections. (If the dialog box is created by using a private template, the definition of the File Name list box must contain the LBS_EXTENDEDSEL value.) Specifies that the File Name list box allows multiple selections.  If the dialog box is created by using a private template, the  definition of the File Name list box must contain the LBS_EXTENDEDSEL value. When this flag is set, the lpstrFile member points to a buffer containing the path to the current directory and all filenames in the selection. The first filename is separated from the path by a space. Each subsequent filename is separated by one space from the preceding filename. Note that for the new Explorer-style dialogs (dialogs that have the OFN_EXPLORER flag set), a single null character, \0, separates the filenames, and two null characters, \0\0, terminate the entire string.
OFN_CREATEPROMPT
	Specifies that the dialog box function should ask whether the user wants to create a file that does not currently exist. (This flag automatically uses the OFN_PATHMUSTEXIST and OFN_FILEMUSTEXIST flags.)
OFN_ENABLEHOOK
	Enables the hook function specified in the lpfnHook member.
OFN_ENABLETEMPLATE
	Causes the operating system to create the dialog box by using the dialog box template identified by hInstance and lpTemplateName.
OFN_ENABLETEMPLATEHANDLE
	Indicates that hInstance identifies a data block that contains a preloaded dialog box template. The operating system ignores lpTemplateName if this flag is specified.
OFN_EXPLORER
	Creates an Open or Save As dialog box that uses user-interface features similar to the Windows Explorer.
OFN_EXTENSIONDIFFERENT
	Specifies that the user typed a filename extension that differs from the extension specified by lpstrDefExt. The function does not use this flag if lpstrDefExt is NULL.
OFN_FILEMUSTEXIST
	Specifies that the user can type only names of existing files in the File Name entry field. If this flag is specified and the user enters an invalid name, the dialog box procedure displays a warning in a message box. If this flag is specified, the OFN_PATHMUSTEXIST flag is also used.
OFN_HIDEREADONLY
	Hides the Read Only check box.
OFN_LONGNAMES
	Causes the Open or Save As dialog box to display long filenames. If this flag is not specified, the dialog box displays filenames in 8.3 format. This value is ignored if OFN_EXPLORER is set.
OFN_NOCHANGEDIR
	Restores the current directory to its original value if the user changed the directory while searching for files.
OFN_NODEREFERENCELINKS
	Directs the dialog box to return the path and filename of the selected shortcut (.LNK) file. If this value is not given, the dialog box returns the path and filename of the file referenced by the shortcut.
OFN_NOLONGNAMES
	Specifies that long filenames are not displayed in the File Name list box. This value is ignored if OFN_EXPLORER is set.
OFN_NONETWORKBUTTON
	Hides and disables the Network button.
OFN_NOREADONLYRETURN
	Specifies that the returned file does not have the Read Only check box checked and is not in a write-protected directory.
OFN_NOTESTFILECREATE
	Specifies that the file is not created before the dialog box is closed. This flag should be specified if the application saves the file on a create-nonmodify network sharepoint. When an application specifies this flag, the library does not check for write protection, a full disk, an open drive door, or network protection. Applications using this flag must perform file operations carefully, because a file cannot be reopened once it is closed.
OFN_NOVALIDATE
	Specifies that the common dialog boxes allow invalid characters in the returned filename. Typically, the calling application uses a hook function that checks the filename by using the FILEOKSTRING message. If the text box in the edit control is empty or contains nothing but spaces, the lists of files and directories are updated. If the text box in the edit control contains anything else, nFileOffset and nFileExtension are set to values generated by parsing the text. No default extension is added to the text, nor is text copied to the buffer specified by lpstrFileTitle.
	If the value specified by nFileOffset is less than zero, the filename is invalid. Otherwise, the filename is valid, and nFileExtension and nFileOffset can be used as if the OFN_NOVALIDATE flag had not been specified.
OFN_OVERWRITEPROMPT
	Causes the Save As dialog box to generate a message box if the selected file already exists. The user must confirm whether to overwrite the file.
OFN_PATHMUSTEXIST
	Specifies that the user can type only valid paths and filenames. If this flag is used and the user types an invalid path and filename in the File Name entry field, the dialog box function displays a warning in a message box.
OFN_READONLY
	Causes the Read Only check box to be checked initially when the dialog box is created. This flag indicates the state of the Read Only check box when the dialog box is closed.
OFN_SHAREAWARE
	Specifies that if a call to the OpenFile function fails because of a network sharing violation, the error is ignored and the dialog box returns the given filename. If this flag is not specified, the registered message for SHAREVISTRING is sent to the hook function with a pointer to a null-terminated string for the path and filename in the lParam parameter.
OFN_SHOWHELP
	Causes the dialog box to show the Help button. The hwndOwner member must not be NULL if this option is specified.
nFileOffset

Specifies a zero-based offset from the beginning of the path to the filename in the string pointed to by lpstrFile. For example, if lpstrFile points to the following string, "c:\dir1\dir2\file.ext", this member contains the value 13.

nFileExtension

Specifies a zero-based offset from the beginning of the path to the filename extension in the string pointed to by lpstrFile. For example, if lpstrFile points to the following string, "c:\dir1\dir2\file.ext", this member contains the value 18. If the user did not type an extension and lpstrDefExt is NULL, this member specifies an offset to the terminating null character. If the user typed "." as the last character in the filename, this member specifies 0.

lpstrDefExt

Points to a buffer that contains the default extension. GetOpenFileName and GetSaveFileName append this extension to the filename if the user fails to type an extension. This string can be any length, but only the first three characters are appended. The string should not contain a period (.). If this member is NULL and the user fails to type an extension, no extension is appended.

lCustData

Specifies application-defined data that the operating system passes to the hook function identified by lpfnHook. The system passes the data in the lParam parameter of the WM_INITDIALOG message.

lpfnHook

Points to a hook function that processes messages intended for the dialog box. An application must specify the OFN_ENABLEHOOK flag in the Flags member to enable the function; otherwise, the operating system ignores this structure member. The hook function should return FALSE to pass a message to the standard dialog box procedure or TRUE to discard the message.

If the hook function processes WM_CTLCOLOR* messages (such as WM_CTLCOLORDLG), the function must return a valid brush handle for painting the background of the dialog box or the corresponding control.

lpTemplateName

Points to a null-terminated string that names the dialog box template to be substituted for the standard dialog box template. An application can use the MAKEINTRESOURCE macro for numbered dialog box resources. This member is only used if Flags specifies the OFN_ENABLETEMPLATE flag; otherwise, this member is ignored.

See Also

GetOpenFileName, GetSaveFileName


OSVERSIONINFO
 OSVERSIONINFO  QuickInfo

typedef struct _OSVERSIONINFO{

    DWORD dwOSVersionInfoSize;

    DWORD dwMajorVersion;

    DWORD dwMinorVersion;

    DWORD dwBuildNumber;

    DWORD dwPlatformId;

    TCHAR szCSDVersion[ 128 ];

} OSVERSIONINFO;

The OSVERSIONINFO data structure contains operating system version information. The information includes major and minor version numbers, a build number, a platform identifier, and descriptive text about the operating system. This structure is used with the GetVersionEx function.

Members

dwOSVersionInfoSize

Specifies the size, in bytes, of this data structure. Set this member to sizeof(OSVERSIONINFO) before calling the GetVersionEx function.

dwMajorVersion

Identifies the major version number of the operating system. For example, the major version number of the Daytona release of Windows NT is 3.

dwMinorVersion

Identifies the minor version number of the operating system. For example, the minor version number of the Daytona release of Windows NT is 5.

dwBuildNumber

Identifies the build number of the operating system in the low-order word. (The high-order word contains the major and minor version numbers.)

dwPlatformId

Identifies the platform supported by the operating system.

This member can have one of the following values:

Value	Platform
VER_PLATFORM_WIN32s	Win32s on Windows 3.1
VER_PLATFORM_WIN32_WINDOWS	Win32 on Windows 95
VER_PLATFORM_WIN32_NT	Windows NT
szCSDVersion

Contains a zero-terminated string that provides arbitrary additional information about the operating system.

See Also

GetVersionEx


OUTLINETEXTMETRIC
 OUTLINETEXTMETRIC  QuickInfo

typedef struct _OUTLINETEXTMETRIC { // otm

    UINT   otmSize;

    TEXTMETRIC otmTextMetrics;

    BYTE   otmFiller;

    PANOSE otmPanoseNumber;

    UINT   otmfsSelection;

    UINT   otmfsType;

    int    otmsCharSlopeRise;

    int    otmsCharSlopeRun;

    int    otmItalicAngle;

    UINT   otmEMSquare;

    int    otmAscent;

    int    otmDescent;

    UINT   otmLineGap;

    UINT   otmsCapEmHeight;

    UINT   otmsXHeight;

    RECT   otmrcFontBox;

    int    otmMacAscent;

    int    otmMacDescent;

    UINT   otmMacLineGap;

    UINT   otmusMinimumPPEM;

    POINT  otmptSubscriptSize;

    POINT  otmptSubscriptOffset;

    POINT  otmptSuperscriptSize;

    POINT  otmptSuperscriptOffset;

    UINT   otmsStrikeoutSize;

    int    otmsStrikeoutPosition;

    int    otmsUnderscoreSize;

    int    otmsUnderscorePosition;

    PSTR   otmpFamilyName;

    PSTR   otmpFaceName;

    PSTR   otmpStyleName;

    PSTR   otmpFullName;

} OUTLINETEXTMETRIC;

The OUTLINETEXTMETRIC structure contains metrics describing a TrueType font.

Members

otmSize

Specifies the size, in bytes, of the OUTLINETEXTMETRIC structure.

otmTextMetrics

Specifies a TEXTMETRIC structure containing further information about the font.

otmFiller

Specifies a value that causes the structure to be byte aligned.

otmPanoseNumber

Specifies the PANOSE number for this font.

otmfsSelection

Specifies the nature of the font pattern. This member can be a combination of the following bits:

Bit	Meaning
0	Italic
1	Underscore
2	Negative
3	Outline
4	Strikeout
5	Bold
otmfsType

Specifies whether the font is licensed. Licensed fonts must not be modified or exchanged. If bit 1 is set, the font may not be embedded in a document. If bit 1 is clear, the font can be embedded. If bit 2 is set, the embedding is read-only.

otmsCharSlopeRise

Specifies the slope of the cursor. This value is 1 if the slope is vertical. Applications can use this value and the value of the otmsCharSlopeRun member to create an italic cursor that has the same slope as the main italic angle (specified by the otmItalicAngle member).

otmsCharSlopeRun

Specifies the slope of the cursor. This value is zero if the slope is vertical. Applications can use this value and the value of the otmsCharSlopeRise member to create an italic cursor that has the same slope as the main italic angle (specified by the otmItalicAngle member).

otmItalicAngle

Specifies the main italic angle of the font, in tenths of a degree counterclockwise from vertical. Regular (roman) fonts have a value of zero. Italic fonts typically have a negative italic angle (that is, they lean to the right).

otmEMSquare

Specifies the number of logical units defining the x- or y-dimension of the em square for this font. (The number of units in the x- and y-directions are always the same for an em square.)

otmAscent

Specifies the maximum distance characters in this font extend above the base line. This is the typographic ascent for the font.

otmDescent

Specifies the maximum distance characters in this font extend below the base line. This is the typographic descent for the font.

otmLineGap

Specifies typographic line spacing.

otmsCapEmHeight

Not supported.

otmsXHeight

Not supported.

otmrcFontBox

Specifies the bounding box for the font.

otmMacAscent

Specifies the maximum distance characters in this font extend above the base line for the Macintosh® computer.

otmMacDescent

Specifies the maximum distance characters in this font extend below the base line for the Macintosh® computer.

otmMacLineGap

Specifies line-spacing information for the Macintosh® computer.

otmusMinimumPPEM

Specifies the smallest recommended size for this font, in pixels per em-square.

otmptSubscriptSize

Specifies the recommended horizontal and vertical size for subscripts in this font.

otmptSubscriptOffset

Specifies the recommended horizontal and vertical offset for subscripts in this font. The subscript offset is measured from the character origin to the origin of the subscript character.

otmptSuperscriptSize

Specifies the recommended horizontal and vertical size for superscripts in this font.

otmptSuperscriptOffset

Specifies the recommended horizontal and vertical offset for superscripts in this font. The superscript offset is measured from the character base line to the base line of the superscript character.

otmsStrikeoutSize

Specifies the width of the strikeout stroke for this font. Typically, this is the width of the em dash for the font.

otmsStrikeoutPosition

Specifies the position of the strikeout stroke relative to the base line for this font. Positive values are above the base line and negative values are below.

otmsUnderscoreSize

Specifies the thickness of the underscore character for this font.

otmsUnderscorePosition

Specifies the position of the underscore character for this font.

otmpFamilyName

Specifies the offset from the beginning of the structure to a string specifying the family name for the font.

otmpFaceName

Specifies the offset from the beginning of the structure to a string specifying the typeface name for the font. (This typeface name corresponds to the name specified in the LOGFONT structure.)

otmpStyleName

Specifies the offset from the beginning of the structure to a string specifying the style name for the font.

otmpFullName

Specifies the offset from the beginning of the structure to a string specifying the full name for the font. This name is unique for the font and often contains a version number or other identifying information.

Remarks

The sizes returned in OUTLINETEXTMETRIC are given in logical units; that is, they depend on the current mapping mode of the specified display context.

See Also

GetOutlineTextMetrics, LOGFONT, TEXTMETRIC


OUTPUT_DEBUG_STRING_INFO
 OUTPUT_DEBUG_STRING_INFO  QuickInfo

typedef struct _OUTPUT_DEBUG_STRING_INFO { // odsi

    LPSTR lpDebugStringData;

    WORD  fUnicode;

    WORD  nDebugStringLength;

} OUTPUT_DEBUG_STRING_INFO;

The OUTPUT_DEBUG_STRING_INFO structure contains the address, format, and length, in bytes, of a debugging string.

Members

lpDebugStringData

Points to the address of the debugging string in the calling process's address space. The debugger can use the ReadProcessMemory function to retrieve the value of the string.

fUnicode

Specifies the format of the debugging string. If this member is zero, the debugging string is 8-bit ASCII; if it is nonzero, the string is 16-bit Unicode™.

nDebugStringLength

Specifies the length, in bytes, of the debugging string. The length includes the string's terminating null character.

See Also

DEBUG_EVENT, ReadProcessMemory


OVERLAPPED
 OVERLAPPED  QuickInfo

typedef struct _OVERLAPPED { // o

    DWORD  Internal;

    DWORD  InternalHigh;

    DWORD  Offset;

    DWORD  OffsetHigh;

    HANDLE hEvent;

} OVERLAPPED;

The OVERLAPPED structure contains information used in asynchronous input and output (I/O).

Members

Internal

Reserved for operating system use. This member, which specifies a system-dependent status, is valid when the GetOverlappedResult function returns without setting the extended error information to ERROR_IO_PENDING.

InternalHigh

Reserved for operating system use. This member, which specifies the length of the data transferred, is valid when the GetOverlappedResult function returns TRUE.

Offset

Specifies a file position at which to start the transfer. The file position is a byte offset from the start of the file. The calling process sets this member before calling the ReadFile or WriteFile function. This member is ignored when reading from or writing to named pipes and communications devices.

OffsetHigh

Specifies the high word of the byte offset at which to start the transfer. This member is ignored when reading from or writing to named pipes and communications devices.

hEvent

Identifies an event set to the signaled state when the transfer has been completed. The calling process sets this member before calling the ReadFile, WriteFile, ConnectNamedPipe, or TransactNamedPipe function.

See Also

ConnectNamedPipe, CreateFile, GetOverlappedResult, ReadFile, ReadFileEx, TransactNamedPipe, WriteFile, WriteFileEx


PAGESETUPDLG
 PAGESETUPDLG  Overview  Group

typedef struct tagPSD {  // psd

    DWORD           lStructSize;

    HWND            hwndOwner;

    HGLOBAL         hDevMode;

    HGLOBAL         hDevNames;

    DWORD           Flags;

    POINT           ptPaperSize;

    RECT            rtMinMargin;

    RECT            rtMargin;

    HINSTANCE       hInstance;

    LPARAM          lCustData;

    LPPAGESETUPHOOK lpfnPageSetupHook;

    LPPAGEPAINTHOOK lpfnPagePaintHook;

    LPCTSTR         lpPageSetupTemplateName;

    HGLOBAL         hPageSetupTemplate;

} PAGESETUPDLG, * LPPAGESETUPDLG;

Contains information to initialize the Page Setup dialog box. After the user closes the dialog box, the structure receives information about the user-defined page parameters in this structure. This structure is used with the PageSetupDlg function.

Members

lStructSize

Size, in bytes, of this structure.

hwndOwner

Handle to the window that owns the Setup dialog box. If this parameter is NULL, the dialog box has no owner.

hDevMode

Handle to a global memory object that contains a DEVMODE structure. On input, if a handle is given, the values in the corresponding DEVMODE structure are used to initialize the controls in the dialog box. On output, this member is set to a global memory handle for a DEVMODE structure that contains values specifying the user's selections or to NULL if the user's selections are not available.

hDevNames

Handle to a global memory object that contains a DEVNAMES structure. This structure contains three strings that specify the driver name, the printer name, and the output port name. On input, if a handle is given, the strings in the corresponding DEVNAMES structure are used to initialize controls in the dialog box. On output, this member is set to the global memory handle for a DEVNAMES structure that contains strings specifying the user's selections or to NULL if the user's selections are not available.

Flags

Initialization flags. Can be a combination of the following values:

PSD_DEFAULTMINMARGINS
	Sets the minimum allowable widths for the page margins to be the same as the printer's minimums. 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 system from displaying 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 function specified in the lpfnPagePaintHook member. This flag overrides the PSD_DISABLEPAGEPAINTING flag.
PSD_ENABLEPAGESETUPHOOK
	Enables the hook function specified in the lpfnPageSetupHook member.
PSD_ENABLEPAGESETUPTEMPLATE
	Causes the system to create the Page Setup dialog box by using the dialog template identified by the hInstance and lpPageSetupTemplateName members.
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
	Causes the system to use hundredths of millimeters as the unit of measure for the margins.
PSD_INTHOUSANDTHSOFINCHES
	Causes the system to use thousandths of inches as the unit of measure for the margins.
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 specified, 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_NOWARNING
	Prevents the system from displaying a warning message when there is no default printer.
PSD_RETURNDEFAULT
	Causes PageSetupDlg to return DEVMODE and DEVNAMES structures that are initialized for the system default printer, without displaying a dialog box. It is assumed that both hDevNames and hDevMode are NULL; otherwise, the function returns an error.
PSD_SHOWHELP
	Causes the dialog box to show the help button. Because the system sends a message to the owner window when the user presses the Help button, the hwndOwner member must not be NULL if PSD_SHOWHELP is specified.
ptPaperSize

Dimensions of the paper selected by the user.

rtMinMargin

Minimum allowable widths for the left, top, right, and bottom margins. These values must be less than the values specified in the rtMargin member. This system ignores this member if the PSD_MARGINS and PSD_MINMARGINS flags are not specified.

rtMargin

Initial widths for the left, top, right, and bottom margins. When the PageSetupDlg function returns, this member contains the margins widths selected by the user. This system ignores this member if the PSD_MARGINS flag is not specified.

hInstance

Handle to the application or module instance that contains the dialog box template specified in the lpPageSetupTemplateName member. This member is used only if the Flags member includes the PSD_ENABLEPAGESETUPTEMPLATE flag; otherwise, this member is ignored.

lCustData

Application-defined data that the system passes to the hook function pointed to by the lpfnPageSetupHook member. The system passes the data in the lParam parameter of the WM_INITDIALOG message.

lpfnPageSetupHook

Pointer to a hook function that processes messages intended for the dialog box. An application must specify the PSD_ENABLEPAGESETUPHOOK flag in the Flags member to enable the function; otherwise, the system ignores this member. The hook function should return FALSE to pass a message on to the standard dialog box procedure or TRUE to discard the message. If the hook function processes the WM_CTLCOLORDLG message, the function must return a valid brush handle for painting the background of the dialog box.

If the hook function returns FALSE in response to the WM_INITDIALOG message, the function is responsible for calling the ShowWindow and UpdateWindow functions to display the dialog box any painting operations are complete.

lpfnPagePaintHook

Pointer to a hook function that receives WM_PSD_* messages from the dialog box whenever the sample page is redrawn. By processing the messages, the hook function can customize the appearance of the sample page.

lpPageSetupTemplateName

Pointer to a null-terminated string that names the dialog box template resource to substitute for the standard dialog box template. An application can use the MAKEINTRESOURCE macro for numbered dialog box resources. This member is used only if the Flags member specifies the PSD_ENABLEPAGESETUPTEMPLATE flag; otherwise, this member is ignored.

hPageSetupTemplate

Identifies a data block that contains a preloaded dialog box template. This member is used only if the Flags member specifies the PSD_ENABLEPAGESETUPTEMPLATEHANDLE flag; otherwise, this member is ignored.

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.

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.

See Also

DEVMODE, DEVNAMES, MAKEINTRESOURCE, PageSetupDlg, ShowWindow, UpdateWindow, WM_CTLCOLORDLG, WM_INITDIALOG


PAINTSTRUCT
 PAINTSTRUCT  QuickInfo

typedef struct tagPAINTSTRUCT { // ps

    HDC  hdc;

    BOOL fErase;

    RECT rcPaint;

    BOOL fRestore;

    BOOL fIncUpdate;

    BYTE rgbReserved[32];

} PAINTSTRUCT;

The PAINTSTRUCT structure contains information for an application. This information can be used to paint the client area of a window owned by that application.

Members

hdc

Identifies the display DC to be used for painting.

fErase

Specifies whether the background must be erased. This value is nonzero if the application should erase the background. The application is responsible for erasing the background if a window class is created without a background brush. For more information, see the description of the hbrBackground member of the WNDCLASS structure.

rcPaint

Specifies a RECT structure that specifies the upper left and lower right corners of the rectangle in which the painting is requested.

fRestore

Reserved; used internally by Windows.

fIncUpdate

Reserved; used internally by Windows.

rgbReserved

Reserved; used internally by Windows.

See Also

BeginPaint, RECT, WNDCLASS


PALETTEENTRY
 PALETTEENTRY  QuickInfo

typedef struct tagPALETTEENTRY { // pe

    BYTE peRed;

    BYTE peGreen;

    BYTE peBlue;

    BYTE peFlags;

} PALETTEENTRY;

The PALETTEENTRY structure specifies the color and usage of an entry in a logical color palette. A logical palette is defined by a LOGPALETTE structure.

Members

peRed

Specifies a red intensity value for the palette entry.

peGreen

Specifies a green intensity value for the palette entry.

peBlue

Specifies a blue intensity value for the palette entry.

peFlags

Specifies how the palette entry is to be used. The peFlags member may be set to NULL or one of the following values:

Value	Meaning
PC_EXPLICIT	Specifies that the low-order word of the logical palette entry designates a hardware palette index. This flag allows the application to show the contents of the display device palette.
PC_NOCOLLAPSE	Specifies that the color be placed in an unused entry in the system palette instead of being matched to an existing color in the system palette. If there are no unused entries in the system palette, the color is matched normally. Once this color is in the system palette, colors in other logical palettes can be matched to this color.
PC_RESERVED	Specifies that the logical palette entry be used for palette animation. This flag prevents other windows from matching colors to the palette entry since the color frequently changes. If an unused system-palette entry is available, the color is placed in that entry. Otherwise, the color is not available for animation.
See Also

LOGPALETTE


PANOSE
 PANOSE  QuickInfo

typedef struct tagPANOSE { // pnse

    BYTE bFamilyType;

    BYTE bSerifStyle;

    BYTE bWeight;

    BYTE bProportion;

    BYTE bContrast;

    BYTE bStrokeVariation;

    BYTE bArmStyle;

    BYTE bLetterform;

    BYTE bMidline;

    BYTE bXHeight;

} PANOSE

The PANOSE structure describes the PANOSE font-classification values for a TrueType font. These characteristics are then used to associate the font with other fonts of similar appearance but different names.

Members

bFamilyType

For Latin fonts, bFamilyType can have one of the following values:

Value	Meaning
PAN_ANY	Any
PAN_NO_FIT	No fit
PAN_FAMILY_TEXT_DISPLAY	Text and display
PAN_FAMILY_SCRIPT	Script
PAN_FAMILY_DECORATIVE	Decorative
PAN_FAMILY_PICTORIAL	Pictorial
bSerifStyle

Specifies the serif style. For Latin fonts, bSerifStyle can have one of the following values:

Value	Meaning
PAN_ANY	Any
PAN_NO_FIT	No fit
PAN_SERIF_COVE	Cove
PAN_SERIF_OBTUSE_COVE	Obtuse cove
PAN_SERIF_SQUARE_COVE	Square cove
PAN_SERIF_OBTUSE_SQUARE_COVE	Obtuse square cove
PAN_SERIF_SQUARE	Square
PAN_SERIF_THIN	Thin
PAN_SERIF_BONE	Bone
PAN_SERIF_EXAGGERATED	Exaggerated
PAN_SERIF_TRIANGLE	Triangle
PAN_SERIF_NORMAL_SANS	Normal sans serif
PAN_SERIF_OBTUSE_SANS	Obtuse sans serif
PAN_SERIF_PERP_SANS	Perp sans serif
PAN_SERIF_FLARED	Flared
PAN_SERIF_ROUNDED	Rounded
bWeight

For Latin fonts, bWeight can have one of the following values:

Value	Meaning
PAN_ANY	Any
PAN_NO_FIT	No fit
PAN_WEIGHT_VERY_LIGHT	Very light
PAN_WEIGHT_LIGHT	Light
PAN_WEIGHT_THIN	Thin
PAN_WEIGHT_BOOK	Book
PAN_WEIGHT_MEDIUM	Medium
PAN_WEIGHT_DEMI	Demibold
PAN_WEIGHT_BOLD	Bold
PAN_WEIGHT_HEAVY	Heavy
PAN_WEIGHT_BLACK	Black
PAN_WEIGHT_NORD	Nord
bProportion

For Latin fonts, bProportion can have one of the following values:

Value	Meaning
PAN_ANY	Any
PAN_NO_FIT	No fit
PAN_PROP_OLD_STYLE	Old style
PAN_PROP_MODERN	Modern
PAN_PROP_EVEN_WIDTH	Even width
PAN_PROP_EXPANDED	Expanded
PAN_PROP_CONDENSED	Condensed
PAN_PROP_VERY_EXPANDED	Very expanded
PAN_PROP_VERY_CONDENSED	Very condensed
PAN_PROP_MONOSPACED	Monospaced
bContrast

For Latin fonts, bContrast can have one of the following values:

Value	Meaning
PAN_ANY	Any
PAN_NO_FIT	No fit
PAN_CONTRAST_NONE	None
PAN_CONTRAST_VERY_LOW	Very low
PAN_CONTRAST_LOW	Low
PAN_CONTRAST_MEDIUM_LOW	Medium low
PAN_CONTRAST_MEDIUM	Medium
PAN_CONTRAST_MEDIUM_HIGH	Medium high
PAN_CONTRAST_HIGH	High
PAN_CONTRAST_VERY_HIGH	Very high
bStrokeVariation

For Latin fonts, bStrokeVariation can have one of the following values:

Value	Meaning
PAN_ANY	Any
PAN_NO_FIT	No fit
PAN_STROKE_GRADUAL_DIAG	Gradual/diagonal
PAN_STROKE_GRADUAL_TRAN	Gradual/transitional
PAN_STROKE_GRADUAL_VERT	Gradual/vertical
PAN_STROKE_GRADUAL_HORZ	Gradual/horizontal
PAN_STROKE_RAPID_VERT	Rapid/vertical
PAN_STROKE_RAPID_HORZ	Rapid/horizontal
PAN_STROKE_INSTANT_VERT	Instant/vertical
bArmStyle

For Latin fonts, bArmStyle can have one of the following values:

Value	Meaning
PAN_ANY	Any
PAN_NO_FIT	No fit
PAN_STRAIGHT_ARMS_HORZ	Straight arms/horizontal
PAN_STRAIGHT_ARMS_WEDGE	Straight arms/wedge
PAN_STRAIGHT_ARMS_VERT	Straight arms/vertical
PAN_STRAIGHT_ARMS_SINGLE_SERIF	Straight arms/single-serif
PAN_STRAIGHT_ARMS_DOUBLE_SERIF	Straight arms/double-serif
PAN_BENT_ARMS_HORZ	Non-straight arms/horizontal
PAN_BENT_ARMS_WEDGE	Non-straight arms/wedge
PAN_BENT_ARMS_VERT	Non-straight arms/vertical
PAN_BENT_ARMS_SINGLE_SERIF	Non-straight arms/single-serif
PAN_BENT_ARMS_DOUBLE_SERIF	Non-straight arms/double-serif
bLetterform

For Latin fonts, bLetterform can have one of the following values:

Value	Meaning
PAN_ANY	Any
PAN_NO_FIT	No fit
PAN_LETT_NORMAL_CONTACT	Normal/contact
PAN_LETT_NORMAL_WEIGHTED	Normal/weighted
PAN_LETT_NORMAL_BOXED	Normal/boxed
PAN_LETT_NORMAL_FLATTENED	Normal/flattened
PAN_LETT_NORMAL_ROUNDED	Normal/rounded
PAN_LETT_NORMAL_OFF_CENTER	Normal/off center
PAN_LETT_NORMAL_SQUARE	Normal/square
PAN_LETT_OBLIQUE_CONTACT	Oblique/contact
PAN_LETT_OBLIQUE_WEIGHTED	Oblique/weighted
PAN_LETT_OBLIQUE_BOXED	Oblique/boxed
PAN_LETT_OBLIQUE_FLATTENED	Oblique/flattened
PAN_LETT_OBLIQUE_ROUNDED	Oblique/rounded
PAN_LETT_OBLIQUE_OFF_CENTER	Oblique/off center
PAN_LETT_OBLIQUE_SQUARE	Oblique/square
bMidline

For Latin fonts, bMidline can have one of the following values:

Value	Meaning
PAN_ANY	Any
PAN_NO_FIT	No fit
PAN_MIDLINE_STANDARD_TRIMMED	Standard/trimmed
PAN_MIDLINE_STANDARD_POINTED	Standard/pointed
PAN_MIDLINE_STANDARD_SERIFED	Standard/serifed
PAN_MIDLINE_HIGH_TRIMMED	High/trimmed
PAN_MIDLINE_HIGH_POINTED	High/pointed
PAN_MIDLINE_HIGH_SERIFED	High/serifed
PAN_MIDLINE_CONSTANT_TRIMMED	Constant/trimmed
PAN_MIDLINE_CONSTANT_POINTED	Constant/pointed
PAN_MIDLINE_CONSTANT_SERIFED	Constant/serifed
PAN_MIDLINE_LOW_TRIMMED	Low/trimmed
PAN_MIDLINE_LOW_POINTED	Low/pointed
PAN_MIDLINE_LOW_SERIFED	Low/serifed
bXHeight

For Latin fonts, bXHeight can have one of the following values:

Value	Meaning
PAN_ANY	Any
PAN_NO_FIT	No fit
PAN_XHEIGHT_CONSTANT_SMALL	Constant/small
PAN_XHEIGHT_CONSTANT_STD	Constant/standard
PAN_XHEIGHT_CONSTANT_LARGE	Constant/large
PAN_XHEIGHT_DUCKING_SMALL	Ducking/small
PAN_XHEIGHT_DUCKING_STD	Ducking/standard
PAN_XHEIGHT_DUCKING_LARGE	Ducking/large


PARAFORMAT [New - Windows NT]
 PARAFORMAT  QuickInfo  Overview  Group

[New - Windows NT]

typedef struct _paraformat {

    UINT cbSize;

    _WPAD _wPad1;

    DWORD dwMask;

    WORD  wNumbering;

    WORD  wReserved;

    LONG  dxStartIndent;

    LONG  dxRightIndent;

    LONG  dxOffset;

    WORD  wAlignment;

    SHORT cTabCount;

    LONG  rgxTabs[MAX_TAB_STOPS];

} PARAFORMAT;

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.

Members

cbSize

Size in bytes of this structure. Must be filled before passing to the rich edit control.

dwMask

Members containing valid information or attributes to set. This parameter can be zero or more of these values:

Value	Meaning
PFM_ALIGNMENT	The wAlignment member is valid.
PFM_NUMBERING	The wNumbering member is valid.
PFM_OFFSET	The dxOffset member is valid.
PFM_OFFSETINDENT	The dxStartIndent member is valid and specifies a relative value.
PFM_RIGHTINDENT	The dxRightIndent member is valid.
PFM_STARTINDENT	The dxStartIndent member is valid.
PFM_TABSTOPS	The cTabStobs and rgxTabStops members are valid.
If both PFM_STARTINDENT and PFM_OFFSETINDENT are specified, PFM_STARTINDENT takes precedence.

wNumbering

Value specifying numbering options. This member can be zero or PFN_BULLET.

dxStartIndent

Indentation of the first line in the paragraph. If the paragraph formatting is being set and PFM_OFFSETINDENT is specified, this member is treated as a relative value that is added to the starting indentation of each affected paragraph.

dxRightIndent

Size of the right indentation, relative to the right margin.

dxOffset

Indentation of the second line and subsequent lines, relative to the starting indentation. The first line is indented if this member is negative, or outdented is this member is positive.

wAlignment

Value specifying the paragraph alignment. This member can be one of the following values:

Value	Meaning
PFA_LEFT	Paragraphs are aligned with the left margin.
PFA_RIGHT	Paragraphs are aligned with the right margin.
PFA_CENTER	Paragraphs are centered.
cTabCount

Number of tab stops.

rgxTabs

Array of absolute tab stop positions.

See Also

EM_GETPARAFORMAT, EM_SETPARAFORMAT


PARTITION_INFORMATION
 PARTITION_INFORMATION  QuickInfo  Overview  Group

typedef struct _PARTITION_INFORMATION {

    BYTE PartitionType;

    BOOLEAN BootIndicator;

    BOOLEAN RecognizedPartition;

    BOOLEAN RewritePartition;

    LARGE_INTEGER StartingOffset;

    LARGE_INTEGER PartitionLength;

    LARGE_INTEGER HiddenSectors;

} PARTITION_INFORMATION ;

The PARTITION_INFORMATION structure provides information about a disk partition.

Members

PartitionType

Specifies the type of partition. This member can be one of the following values:

Value	Meaning
PARTITION_ENTRY_UNUSED	Entry unused.
PARTITION_FAT_12	Specifies a partition with 12-bit FAT entries.
PARTITION_XENIX_1	Specifies a Xenix type 1 partition.
PARTITION_XENIX_2	Specifies a Xenix type 2 partition.
PARTITION_FAT_16	Specifies a partition with 16-bit FAT entries.
PARTITION_EXTENDED	Specifies an extended partition entry.
PARTITION_HUGE	Specifies an MS-DOS V4 huge partition.
PARTITION_IFS	Specifies an IFS partition.
PARTITION_UNIX	Specifies a Unix partition.
VALID_NTFT	Specifies an NTFT partition.
BootIndicator

The boot sector of the disk.

RecognizedPartition

The partition is recognized.

RewritePartition

The rewrite partition.

StartingOffset

The starting offset.

PartitionLength

The partition length.

HiddenSectors

The number of hidden sectors.

Remarks

The DeviceIoControl function receives a PARTITION_INFORMATION structure in response to an IOCTL_DISK_GET_PARTITION_INFO or IOCTL_DISK_GET_DRIVE_LAYOUT device input and output control (IOCTL) operation. The DeviceIoControl function uses a PARTITION_INFORMATION structure as input to an IOCTL_DISK_SET_DRIVE_LAYOUT device IOCTL operation.

See Also

DeviceIoControl, IOCTL_DISK_GET_DRIVE_LAYOUT, IOCTL_DISK_GET_PARTITION_INFO, IOCTL_DISK_SET_DRIVE_LAYOUT


PERF_COUNTER_BLOCK
 PERF_COUNTER_BLOCK  QuickInfo

typedef struct _PERF_COUNTER_BLOCK { // pcd

    DWORD ByteLength;

} PERF_COUNTER_BLOCK;

The PERF_COUNTER_BLOCK structure contains the length, in bytes, of the performance-counter data. This structure is followed by data for the number of counters specified in the PERF_OBJECT_TYPE structure.

Members

ByteLength

Specifies the length, in bytes, of this structure, including the counters that follow.

Remarks

This structure is part of the performance data provided by the RegQueryValueEx function when the HKEY_PERFORMANCE_DATA key is used.

See Also

PERF_OBJECT_TYPE, RegQueryValueEx


PERF_COUNTER_DEFINITION
 PERF_COUNTER_DEFINITION  QuickInfo

typedef struct _PERF_COUNTER_DEFINITION { // pcd

    DWORD  ByteLength;

    DWORD  CounterNameTitleIndex;

    LPWSTR CounterNameTitle;

    DWORD  CounterHelpTitleIndex;

    LPWSTR CounterHelpTitle;

    DWORD  DefaultScale;

    DWORD  DetailLevel;

    DWORD  CounterType;

    DWORD  CounterSize;

    DWORD  CounterOffset;

} PERF_COUNTER_DEFINITION;

The PERF_COUNTER_DEFINITION structure describes a performance counter. The Unicode names in this structure must appear in a message file.

Members

ByteLength

Contains the length, in bytes, of this structure.

CounterNameTitleIndex

Contains the index of the counter name in the title database of the registry.

CounterNameTitle

Points to the name of the counter. This member contains NULL, initially, but it can contain a pointer to the actual string once the string is located.

CounterHelpTitleIndex

Contains the index to the counter's Help title in the title database of the registry.

CounterHelpTitle

Points to the title of Help. This member contains NULL, initially, but it can contain a pointer to the actual string once the string is located.

DefaultScale

Specifies the power of 10 by which to scale a chart line, assuming the vertical axis is 100. If this value is zero, the scale value is 1; if this value is 1, the scale value is 10; if this value is −1, the scale value is .10; and so on.

DetailLevel

Specifies the level of detail for the counter. Applications use this value to control display complexity. This member can be one of the following values:

Value	Meaning
PERF_DETAIL_NOVICE	The data can be understood by the uninformed user.
PERF_DETAIL_ADVANCED	The data is designed for the advanced user.
PERF_DETAIL_EXPERT	The data is designed for the expert user.
PERF_DETAIL_WIZARD	The data is designed for the system designer.
CounterType

Specifies the type of counter. This member is some combination of the following values.

These values indicate the counter's data size:

Value	Meaning
PERF_SIZE_DWORD	The counter data is a doubleword.
PERF_SIZE_LARGE	The counter data is a large integer.
PERF_SIZE_ZERO	The counter data is a zero-length field.
PERF_SIZE_VARIABLE_LEN	The size of the counter data is in the CounterSize member.
These values indicate the additional contents of this member:

Value	Meaning
PERF_TYPE_NUMBER	The counter data is a number value but not a counter.
PERF_TYPE_COUNTER	The counter data is an increasing numeric value.
PERF_TYPE_TEXT	The counter data is a text field.
PERF_TYPE_ZERO	The counter data is always zero.
If PERF_TYPE_NUMBER is specified, one of these values is also specified to indicate the format of the number:

Value	Meaning
PERF_NUMBER_HEX	The counter data should be displayed as a hexadecimal value.
PERF_NUMBER_DECIMAL	The counter data should be displayed as a decimal value.
PERF_NUMBER_DEC_1000	The counter data should be divided by 1000 and displayed as a decimal value.
If PERF_TYPE_COUNTER is specified, one of these values is also specified to indicate the type of counter:

Value	Meaning
PERF_COUNTER_VALUE	The counter value is valid without additional calculation; that is, it should be displayed as is.
PERF_COUNTER_RATE	The counter value should be divided by the elapsed time.
PERF_COUNTER_FRACTION	The counter value should be divided by the base value indicated by the next counter if it is of type PERF_COUNTER_BASE or by the value of the counter subtype.
PERF_COUNTER_BASE	The counter value is the base value to use in fractions.
PERF_COUNTER_ELAPSED	The counter value is a start time to be subtracted from the current time.
PERF_COUNTER_QUEUELEN	The performance application should use the Queuelen counter — that is, the Queue Length Space-Time Product formula. The next counter is the number currently in the queue. Multiply it by the current time (units specified by this counter's subtype). Add the product to the original value of the counter. To obtain the average queue length, divide the result of the addition by the delta time.
PERF_COUNTER_HISTOGRAM	The counter value begins or ends a histogram.
If PERF_TYPE_COUNTER is specified, one of these values is also specified to indicate the subtype of counter:

Value	Meaning
PERF_TIMER_TICK	The frequency of the high-resolution performance counter should be used as the base.
PERF_TIMER_100NS	The time base units of the 100-nanosecond timer should be used as the base.
PERF_OBJECT_TIMER	The object-timer frequency should be used as the base unit. This value is system-defined in this counter's PERF_OBJECT_TYPE definition.
If PERF_TYPE_TEXT is specified, one of these values is also specified to indicate the type of text:

Value	Meaning
PERF_TEXT_UNICODE	The counter data contains Unicode text.
PERF_TEXT_ASCII	The counter data contains ASCII text.
These values indicate how to use the counter data in a calculation:

Value	Meaning
PERF_DELTA_COUNTER	The difference between the previous counter value and the current counter value is computed before proceeding.
PERF_DELTA_BASE	The difference between the previous base value and the current base value is computed before proceeding.
PERF_INVERSE_COUNTER	After other calculations, the counter should be inverted before displaying or converting to a percentage.
PERF_MULTI_COUNTER	This value is a sum of counters from several sources, the number of which is indicated by the next counter.
These values indicate the display suffix of the counter data:

Value	Meaning
PERF_DISPLAY_NO_SUFFIX	There is no display suffix.
PERF_DISPLAY_PER_SEC	The display suffix is '/sec'.
PERF_DISPLAY_PERCENT	The display suffix is '%'.
PERF_DISPLAY_SECONDS	The display suffix is 'secs'.
PERF_DISPLAY_NOSHOW	The counter value should not be displayed.
CounterSize

Specifies the counter size, in bytes.

CounterOffset

Specifies the offset from the start of the PERF_COUNTER_BLOCK structure to the first byte of this counter.

Remarks

This structure is part of the performance data provided by the RegQueryValueEx function when the HKEY_PERFORMANCE_DATA key is used.

See Also

RegQueryValueEx


PERF_DATA_BLOCK
 PERF_DATA_BLOCK  QuickInfo

typedef struct _PERF_DATA_BLOCK { // pdb

    WCHAR         Signature[4];

    DWORD         LittleEndian;

    DWORD         Version;

    DWORD         Revision;

    DWORD         TotalByteLength;

    DWORD         HeaderLength;

    DWORD         NumObjectTypes;

    DWORD         DefaultObject;

    SYSTEMTIME    SystemTime;

    LARGE_INTEGER PerfTime;

    LARGE_INTEGER PerfFreq;

    LARGE_INTEGER PerfTime100nSec;

    DWORD         SystemNameLength;

    DWORD         SystemNameOffset;

} PERF_DATA_BLOCK;

The PERF_DATA_BLOCK structure describes the performance data provided by RegQueryValueEx function. The data starts with a PERF_DATA_BLOCK structure and is followed by a PERF_OBJECT_TYPE structure and other object-specific data for each type of object monitored.

Members

Signature

Contains the Unicode string PERF.

LittleEndian

Contains zero if the processor is big endian and one if it is little endian.

Version

Contains the version of the performance (PERF_) structures. This member is greater than or equal to one.

Revision

Contains the revision of the performance (PERF_) structures. This member is greater than or equal to zero.

TotalByteLength

Contains the total length, in bytes, of the performance data.

HeaderLength

Contains the length, in bytes, of this structure.

NumObjectTypes

Contains the number of object types being monitored.

DefaultObject

Contains the object title index of the default object whose performance data is to be displayed. This member can be −1 to indicate that no data is to be displayed.

SystemTime

Contains the time when the system is monitored. This member is in Coordinated Universal Time (UTC) format.

PerfTime

Contains the performance-counter value, in counts, for the system being monitored.

PerfFreq

Contains the performance-counter frequency, in counts per second, for the system being monitored.

PerfTime100nSec

Contains the performance-counter value, in 100 nanosecond units, for the system being monitored.

SystemNameLength

Contains the length, in bytes, of the system name.

SystemNameOffset

Contains the offset from the beginning of this structure to the name of the system being monitored.

See Also

PERF_OBJECT_TYPE, RegQueryValueEx


PERF_INSTANCE_DEFINITION
 PERF_INSTANCE_DEFINITION  QuickInfo

typedef struct _PERF_INSTANCE_DEFINITION { // pid

    DWORD ByteLength;

    DWORD ParentObjectTitleIndex;

    DWORD ParentObjectInstance;

    DWORD UniqueID;

    DWORD NameOffset;

    DWORD NameLength;

} PERF_INSTANCE_DEFINITION;

The PERF_INSTANCE_DEFINITION structure contains the instance-specific information for a block of performance data. There is one PERF_INSTANCE_DEFINITION structure for each instance specified in the PERF_DATA_BLOCK structure.

Members

ByteLength

Specifies the length, in bytes, of this structure, including the subsequent name.

ParentObjectTitleIndex

Specifies the index of the name of the "parent" object in the title database. For example, if the object is a thread, the parent object type is a process, or if the object is a logical drive, the parent is a physical drive.

ParentObjectInstance

Specifies the index to an instance of the parent object type that is the parent of this instance. This member may be zero or greater.

UniqueID

Specifies the unique identifier used instead of the instance name. This member is PERF_NO_UNIQUE_ID if there is no such identifier.

NameOffset

Specifies the offset from the beginning of this structure to the Unicode name of this instance.

NameLength

Specifies the length, in bytes, of the instance name. This member is zero if the instance does not have a name.

See Also

PERF_DATA_BLOCK


PERF_OBJECT_TYPE
 PERF_OBJECT_TYPE  QuickInfo

typedef struct _PERF_OBJECT_TYPE {  // pot

    DWORD  TotalByteLength;

    DWORD  DefinitionLength;

    DWORD  HeaderLength;

    DWORD  ObjectNameTitleIndex;

    LPWSTR ObjectNameTitle;

    DWORD  ObjectHelpTitleIndex;

    LPWSTR ObjectHelpTitle;

    DWORD  DetailLevel;

    DWORD  NumCounters;

    DWORD  DefaultCounter;

    DWORD  NumInstances;

    DWORD  CodePage;

    LARGE_INTEGER PerfTime;

    LARGE_INTEGER PerfFreq;

} PERF_OBJECT_TYPE;

The PERF_OBJECT_TYPE structure describes object-specific performance information. This structure is followed by a list of PERF_COUNTER_DEFINITION structures, one for each counter defined for the type of object.

Members

TotalByteLength

Contains the length, in bytes, of the object-specific data. This value includes this structure, the PERF_COUNTER_DEFINITION structures, and the PERF_INSTANCE_DEFINITION and PERF_COUNTER_BLOCK structures for each instance. This member specifies the offset from the beginning of this structure to the next PERF_OBJECT_TYPE structure if one exists.

DefinitionLength

Contains the length, in bytes, of the object-specific data. This value includes this structure and the PERF_COUNTER_DEFINITION structures for this object. This member is the offset from the beginning of the PERF_OBJECT_TYPE structure to the first PERF_INSTANCE_DEFINITION structure or to the PERF_COUNTER_DEFINITION structures if there is no instance data.

HeaderLength

Contains the length, in bytes, of this structure. This member is the offset to the first PERF_COUNTER_DEFINITION structure for this object.

ObjectNameTitleIndex

Contains the index to the object's name in the title database.

ObjectNameTitle

Points to the name of the object. This member initially contains NULL, but it can contain a pointer to the actual string once the string is located.

ObjectHelpTitleIndex

Contains the index to the object's Help title in the title database.

ObjectHelpTitle

Points to the title of Help. This member initially contains NULL, but it can contain a pointer to the actual string once the string is located.

DetailLevel

Specifies the level of detail. Applications use this value to control display complexity. This value is the minimum detail level of all the counters for a given object. This member can be one of the following values:

Detail level	Meaning
PERF_DETAIL_NOVICE	No technical ability is required to understand the counter data.
PERF_DETAIL_ADVANCED	The counter data is provided for advanced users.
PERF_DETAIL_EXPERT	The counter data is provided for expert users.
PERF_DETAIL_WIZARD	The counter data is provided for system designers.
NumCounters

Specifies the number of counters in each counter block. There is one counter block per instance.

DefaultCounter

Specifies the default counter whose information is to be displayed when this object is selected. This member is typically greater than or equal to zero. However, this member may be −1 to indicate that there is no default.

NumInstances

Specifies the number of object instances for which counters are being provided.

CodePage

Specifies the code page. This member is zero if the instance strings are in Unicode. Otherwise, this member is the code-page identifier of the instance names.

PerfTime

Specifies the current value, in counts, of the high-resolution performance counter.

PerfFreq

Specifies the current frequency, in counts per second, of the high-resolution performance counter.

Remarks

If there is only one instance of the object type, the counter definitions are followed by a single PERF_COUNTER_BLOCK structure. This structure is followed by data for each counter. (The PERF_COUNTER_BLOCK structure contains the total length of the structure and the counter data that follows it.)

If there is more than one instance of the object type, the list of counter definitions is followed by a PERF_INSTANCE_DEFINITION structure and a PERF_COUNTER_BLOCK structure for each instance. The PERF_INSTANCE_DEFINITION structure includes the name, the identifier, and the name of the parent of the instance.

Following the counter data, there is a PERF_INSTANCE_DEFINITION structure and a PERF_COUNTER_BLOCK structure for each instance specified in the PERF_DATA_BLOCK structure that begins the performance-data area.

See Also

PERF_COUNTER_BLOCK, PERF_COUNTER_DEFINITION, PERF_INSTANCE_DEFINITION


POINT
 POINT  QuickInfo

typedef struct tagPOINT { // pt

    LONG x;

    LONG y;

} POINT;

The POINT structure defines the x- and y- coordinates of a point.

Members

x

Specifies the x-coordinate of the point.

y

Specifies the y-coordinate of the point.

See Also

ChildWindowFromPoint, GetBrushOrgEx, PtInRect, SetBrushOrgEx, WindowFromPoint


POINTFX
 POINTFX  QuickInfo

typedef struct tagPOINTFX { // ptfx

    FIXED x;

    FIXED y;

} POINTFX;

The POINTFX structure contains the coordinates of points that describe the outline of a character in a TrueType font.

Members

x

Specifies the x-component of a point on the outline of a TrueType character.

y

Specifies the y-component of a point on the outline of a TrueType character.

Remarks

The POINTFX structure is a member of the TTPOLYCURVE and TTPOLYGONHEADER structures. Values in the POINTFX structure are specified in device units.

See Also

FIXED, TTPOLYCURVE, TTPOLYGONHEADER


POINTL
 POINTL  QuickInfo

typedef struct _POINTL { // ptl

    LONG x;

    LONG y;

} POINTL;

The POINTL structure contains the coordinates of a point.

Members

x

Specifies the horizontal (x) coordinate of the point.

y

Specifies the vertical (y) coordinate of the point.


POINTS
 POINTS  QuickInfo

typedef struct tagPOINTS { // pts

    SHORT x;

    SHORT y;

} POINTS;

The POINTS structure defines the coordinates of a point.

Members

x

Specifies the x-coordinate of the point.

y

Specifies the y-coordinate of the point.

See Also

ChildWindowFromPoint, PtInRect, WindowFromPoint, POINT


POLYTEXT
 POLYTEXT  QuickInfo

typedef struct _POLYTEXT { // ptxt

    int     x;

    int     y;

    UINT    n;

    LPCTSTR lpstr;

    UINT    uiFlags;

    RECT    rcl;

    int     *pdx;

} POLYTEXT;

The POLYTEXT structure describes how the PolyTextOut function should draw a string of text.

Members

x

Specifies the horizontal reference point for the string. The string is aligned to this point using the current text-alignment mode.

y

Specifies the vertical reference point for the string. The string is aligned to this point using the current text-alignment mode.

n

Specifies the number of characters in the string.

uiFlags

Specifies whether the string is to be opaque or clipped and whether the string is accompanied by an array of character-width values. This member can be one or more of the following values:

Value	Meaning
ETO_OPAQUE	The rectangles given for each string is to be opaqued with the current background color.
ETO_CLIPPED	Each string is to be clipped to its given rectangle.
lpstr

Points to a string of text to be drawn by the PolyTextOut function.

rcl

Specifies a rectangle structure that contains the dimensions of the opaquing or clipping rectangle. This member is ignored if neither of the ETO_OPAQUE nor the ETO_CLIPPED value is specified for the uiFlags member.

pdx

Specifies in an array the width value for each character in the string.

See Also

PolyTextOut


PORT_INFO_1
 PORT_INFO_1  QuickInfo

typedef struct _PORT_INFO_1 { // pi1

    LPTSTR pName;

} PORT_INFO_1;

The PORT_INFO_1 structure identifies a supported printer port.

Members

pName

Points to a null-terminated string that identifies a supported printer port (for example, "LPT1:").

See Also

EnumPorts


PORT_INFO_2 [New - Windows 95]
 PORT_INFO_2  QuickInfo

[New - Windows 95]

typedef struct _PORT_INFO_2 { // pi2

    LPSTR pPortName;

    LPSTR pMonitorName

    LPSTR pDescription;

    DWORD fPortType;

    DWORD Reserved;

} PORT_INFO_2;

The PORT_INFO_2 structure identifies a supported printer port.

Members

pPortName

Points to a null-terminated string that identifies a supported printer port (for example, "LPT1:").

pMonitorName

Points to a null-terminated string that identifies an installed monitor (for example, "PJL monitor").

pDescription

Points to a null-terminated string that describes the port in more detail (for example, if pPortName is "LPT1:", pDescription is "printer port").

fPortType

Identifies the type of port. Can be one of these values:

PORT_TYPE_WRITE

PORT_TYPE_READ

PORT_TYPE_REDIRECTED

PORT_TYPE_NET_ATTACHED

Reserved

Reserved; must be zero.

Remarks

Use the PORT_INFO_2 structure when calling EnumPorts if there are multiple monitors installed that support the same ports.

See Also

EnumPorts


PREVENT_MEDIA_REMOVAL
 PREVENT_MEDIA_REMOVAL  QuickInfo  Overview  Group

typedef struct _PREVENT_MEDIA_REMOVAL{

   BOOLEAN PreventMediaRemoval;

} PREVENT_MEDIA_REMOVAL ;

The PREVENT_MEDIA_REMOVAL structure provides removable media locking data.

Members

PreventMediaRemoval

Specifies whether the media is to be locked (if TRUE) or not (if FALSE).

Remarks

The DeviceIoControl function uses a PREVENT_MEDIA_REMOVAL structure as input to an IOCTL_DISK_MEDIA_REMOVAL device input and output operation.

See Also

DeviceIoControl, IOCTL_DISK_MEDIA_REMOVAL


PRINTDLG
 PRINTDLG  QuickInfo

typedef struct tagPD {  // pd

    DWORD     lStructSize;

    HWND      hwndOwner;

    HANDLE    hDevMode;

    HANDLE    hDevNames;

    HDC       hDC;

    DWORD     Flags;

    WORD      nFromPage;

    WORD      nToPage;

    WORD      nMinPage;

    WORD      nMaxPage;

    WORD      nCopies;

    HINSTANCE hInstance;

    DWORD     lCustData;

    LPPRINTHOOKPROC lpfnPrintHook;

    LPSETUPHOOKPROC lpfnSetupHook;

    LPCTSTR    lpPrintTemplateName;

    LPCTSTR    lpSetupTemplateName;

    HANDLE    hPrintTemplate;

    HANDLE    hSetupTemplate;

} PRINTDLG;

The PRINTDLG structure contains information the system uses to initialize the system-defined Print dialog boxes. After the user closes the dialog box, the system returns information about the user-defined print selections in this structure.

Members

lStructSize

Specifies the structure size, in bytes.

hwndOwner

Identifies the window that owns the dialog box. This member can be any valid window handle, or it can be NULL if the dialog box has no owner.

hDevMode

Identifies a movable global memory object that contains a DEVMODE structure. Before a call to the PrintDlg function, the structure members may contain data used to initialize the dialog controls. When PrintDlg returns, the structure members specify the state of the dialog box controls.

If the application uses the structure to initialize the dialog box controls, it must allocate space for and create the DEVMODE structure. (The application should allocate a movable block of memory.)

If the application does not use the structure to initialize the dialog box controls, hDevMode may be NULL. In this case, PrintDlg allocates memory for the structure, initializes its members, 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.

Because this structure is a movable global memory object, the value of hDevMode may change during the execution of PrintDlg.

For a discussion of how the system resolves a possible data collision between values specified by the hDevMode and hDevNames members, see the Remarks section later in this topic.

hDevNames

Identifies a movable 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. Before the call to PrintDlg, the structure members contain strings used to initialize dialog box controls. When PrintDlg returns, the structure members contain the strings typed by the user. The calling application uses these strings to create a device context or an information context.

If the application uses the structure to initialize the dialog box controls, it must allocate space for and create the DEVNAMES structure. (The application should allocate a movable block of global memory.)

If the application does not use the structure to initialize the dialog box controls, hDevNames may be NULL. In this case, PrintDlg allocates memory for the structure, initializes its members (by using the printer name specified in the DEVMODE structure), and returns a handle that identifies it. PrintDlg uses the first port name that appears in the [devices] section of WIN.INI when it initializes the members in the DEVNAMES structure. For example, the function uses "LPT1:" as the port name if the following string appears in the [devices] section:

PCL / HP LaserJet=HPPCL,LPT1:,LPT2:

If both hDevMode and hDevNames are NULL, PrintDlg initializes hDevNames using the current default printer.

Because this structure is a movable global memory object, the value of hDevNames may change during the execution of PrintDlg.

For a discussion of how the system resolves a possible data collision between values specified by hDevNames and hDevMode, see the Remarks section later in this topic.

hDC

Identifies a device context or an information context, depending on whether the Flags member specifies the PD_RETURNDC or PC_RETURNIC flag. If neither flag is specified, the value of this member is undefined. If both flags are specified, PD_RETURNDC has priority.

Flags

Specifies the dialog box initialization flags. This member may be a combination of the following flags:

Flag	Meaning
PD_ALLPAGES
	Indicates that the All radio button was selected when the user closed the dialog box. (This flag is used as a placeholder to indicate that the PD_PAGENUMS and PD_SELECTION flags are not specified. This flag can be set on input and on output.)
PD_COLLATE
	Places a checkmark in the Collate check box when set on input. When the PrintDlg function returns, this value indicates that the user selected the Collate option and the printer driver does not support collation. In this case, the application must provide collation. If PrintDlg sets the PD_COLLATE value on return, the print driver does not support collation and dmCollate in the DEVMODE structure is undefined.
PD_DISABLEPRINTTOFILE
	Disables the Print to File check box.
PD_ENABLEPRINTHOOK
	Enables the hook function specified in lpfnPrintHook.
PD_ENABLEPRINTTEMPLATE
	Causes the system to create the dialog box by using the dialog box template identified by hInstance and lpPrintTemplateName.
PD_ENABLEPRINTTEMPLATEHANDLE
	Indicates that hInstance identifies a data block that contains a preloaded dialog box template. The system ignores lpPrintTemplateName if this flag is specified.
PD_ENABLESETUPHOOK
	Enables the hook function specified in lpfnSetupHook.
PD_ENABLESETUPTEMPLATE
	Causes the operating system to create the dialog box by using the dialog template box identified by hInstance and lpSetupTemplateName.
PD_ENABLESETUPTEMPLATEHANDLE
	Indicates that hInstance identifies a data block that contains a preloaded dialog box template. The system ignores lpSetupTemplateName if this flag is specified.
PD_HIDEPRINTTOFILE
	Hides and disables the Print to File check box.
PD_NOPAGENUMS
	Disables the Pages radio button and the associated edit control.
PD_NOSELECTION
	Disables the Selection radio button.
PD_NOWARNING
	Prevents the warning message from being displayed when there is no default printer.
PD_PAGENUMS
	Causes the Pages radio button to be in the selected state when the dialog box is created. When PrintDlg returns, this flag is specified if the Pages radio button is in the selected state.
PD_PRINTSETUP
	Causes the system to display the Print Setup dialog box rather than the Print dialog box.
PD_PRINTTOFILE
	Causes the Print to File check box to be in the checked state when the dialog box is created. When PrintDlg returns, the pOutput member of the DEVNAMES structure points to the "FILE:" string.
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
	Causes PrintDlg to return DEVMODE and DEVNAMES structures that are initialized for the system default printer without displaying a dialog box. It is assumed that both hDevNames and hDevMode are NULL; otherwise, the function 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 that 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
	Causes the Selection radio button to be in the selected state when the dialog box is created. When PrintDlg returns, this flag is specified if the Selection radio button is in the selected state. If neither PD_PAGENUMS nor PD_SELECTION is specified, the All radio button is in the selected state.
PD_SHOWHELP
	Causes the dialog box to show the Help button. The hwndOwner member must not be NULL if this flag is specified.
PD_USEDEVMODECOPIES
	Same as PD_USEDEVMODECOPIESANDCOLLATE
PD_USEDEVMODECOPIESANDCOLLATE
	Disables the Copies edit control if the printer driver does not support multiple copies, and disables the Collate checkbox if the printer driver does not support collation. If this flag is not specified, PrintDlg stores the user selections for the Copies and Collate options in the dmCopies and dmCollate members of the DEVMODE structure.
	If this flag isn't set, the copies and collate information is returned in the DEVMODE structure if the driver supports multiple copies and collation. If the driver doesn't support multiple copies and collation, the information is returned in the PRINTDLG structure. this means that an application only has to look at nCopies and PD_COLLATE to determine how many copies it needs to render and whether it needs to print them collated.
nFromPage

Specifies the initial value for the starting page edit control. When the PrintDlg function returns, this member specifies the page at which to begin printing. This value is valid only if the PD_PAGENUMS flag is specified.

nToPage

Specifies the initial value for the ending page edit control. When the PrintDlg function returns, this member specifies the last page to print. This value is valid only if the PD_PAGENUMS flag is specified.

nMinPage

Specifies the minimum value for the range of pages specified in the From and To page edit controls.

nMaxPage

Specifies the maximum value for the range of pages 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, this member contains the actual number of copies to print. If the printer driver does not support multiple copies, this value may be greater than one and the application must print all requested copies. If the PD_USEDEVMODECOPIESANDCOLLATE value is set in the Flags member, nCopies is always set to 1 on return and the dmCopies member in the DEVMODE receives the actual number of copies to print.

hInstance

Identifies a data block that contains the preloaded dialog box template specified by lpPrintTemplateName or lpSetupTemplateName. This member is used only if Flags specifies the PD_ENABLEPRINTTEMPLATE or PD_ENABLESETUPTEMPLATE flag; otherwise, this member is ignored.

lCustData

Specifies application-defined data that the operating system passes to the hook function pointed to by lpfnHook. The system passes the data in the lParam parameter of the WM_INITDIALOG message.

lpfnPrintHook

Points to the exported function that hooks dialog messages if the application alters the Print dialog box. This member is ignored unless the Flags member specifies the PD_ENABLEPRINTHOOK flag.

lpfnSetupHook

Points to the exported function that hooks dialog messages if the application alters the Print Setup dialog box. This member is ignored unless the Flags member specifies the PD_ENABLESETUPHOOK flag.

lpPrintTemplateName

Specifies the name of the Print dialog box template identified by hInstance.

lpSetupTemplateName

Specifies the name of the Print Setup dialog box identified by hInstance.

hPrintTemplate

Identifies the global memory object that contains the preloaded dialog box template to be used instead of the default Print Dialog box.

hSetupTemplate

Identifies the global memory object that contains the preloaded dialog box template to be used instead of the default Setup dialog box.

Remarks

There might be data collision between the values specified by hDevNames and hDevMode because the wDeviceOffset member of the DEVNAMES structure is supposed to be identical to the dmDeviceName member of the DEVMODE structure. If it is not, the system resolves the data collision by using the value of wDeviceOffset.

If the user checks the Collate check box in the common Print dialog box, but the printer driver does not support collation, the Flags member of the printdlg structure returned by PrintDlg includes the PD_COLLATE flag. In addition, the dmCollate member of the DEVMODE structure identified by the hDevMode member is set to COLLATE_TRUE. If the PD_COLLATE flag is set, the application must simulate collation.

If the PD_USEDEVMODECOPIESANDCOLLATE flag is set, the Collate check box is grayed out if the printer driver does not support collation. This ensures that the user can only select one copy, and nCopies will be one. If the driver does support multiple copies, dmCopies will contain the number of copies, and nCopies will be one.

On entry to PrintDlg, the nCopies member of the PRINTDLG structure specifies the number of copies if PD_USEDEVMODECOPIESANDCOLLATE is not set. On exit from PrintDlg, nCopies contains the number of copies if the printer driver does not support multiple copies. Otherwise it is set to one. If nCopies is greater than one on exit from PrintDlg, the application must print multiple copies of the document.

See Also

CreateDC, CreateIC, PrintDlg, DEVMODE, DEVNAMES, WM_INITDIALOG


PRINTER_DEFAULTS
 PRINTER_DEFAULTS  QuickInfo

typedef struct _PRINTER_DEFAULTS {  // pd

    LPTSTR      pDatatype;

    LPDEVMODE   pDevMode;

    ACCESS_MASK DesiredAccess;

} PRINTER_DEFAULTS;

The PRINTER_DEFAULTS structure specifies the default data type, environment, initialization data, and access rights for a printer.

Members

pDatatype

Points to a null-terminated string that specifies the default data type for a printer.

pDevMode

Points to a DEVMODE structure that identifies the default environment and initialization data for a printer.

DesiredAccess

Specifies desired access rights for a printer. The OpenPrinter function uses this member to set access rights to the printer. These rights can affect the operation of the SetPrinter and DeletePrinter functions.

This member can be set to PRINTER_ACCESS_ADMINISTER, PRINTER_ACCESS_USE, or any generic security value (for example, WRITE_DACL). If an application wishes to open a printer to perform administrative tasks, such as the SetPrinter function, it must open the printer with PRINTER_ACCESS_ADMINISTER access.

See Also

DeletePrinter, DEVMODE, OpenPrinter, SetPrinter


PRINTER_INFO_1
 PRINTER_INFO_1  QuickInfo

typedef struct _PRINTER_INFO_1 { // pri1

    DWORD  Flags;

    LPTSTR pDescription;

    LPTSTR pName;

    LPTSTR pComment;

} PRINTER_INFO_1;

The PRINTER_INFO_1 structure specifies general printer information.

Members

Flags

Specifies information about the returned data. Following are the values for this member

Value	Meaning
PRINTER_ENUM_EXPAND	A print provider can set this flag as a hint to a calling application to enumerate this object further if default expansion is enabled. For example, when domains are enumerated, a print provider might indicate the user's domain by setting this flag.
PRINTER_ENUM_CONTAINER	If this flag is set, the printer object may contain enumerable objects. For example, the object may be a print server that contains printers.
PRINTER_ENUM_ICON1	Indicates that, where appropriate, an application should display an icon identifying the object as a top-level network name, such as Microsoft Windows Network.
PRINTER_ENUM_ICON2	Indicates that, where appropriate, an application should display an icon that identifies the object as a network domain.
PRINTER_ENUM_ICON3	Indicates that, where appropriate, an application should display an icon that identifies the object as a print server.
PRINTER_ENUM_ICON4	Reserved for future use.
PRINTER_ENUM_ICON5	Reserved for future use.
PRINTER_ENUM_ICON6	Reserved for future use.
PRINTER_ENUM_ICON7	Reserved for future use.
PRINTER_ENUM_ICON8	Indicates that, where appropriate, an application should display an icon that identifies the object as a printer.
pDescription

Windows NT: Points to a null-terminated string that describes the contents of the structure.

Windows 95: Points to a null-terminated string that describes the printer. The string contains the pPrinterName, pDriverName, and pComment members of the PRINTER_INFO_2 structure concatenated and separated by commas.

pName

Windows NT: Points to a null-terminated string that names the contents of the structure.

Windows 95: Points to a null-terminated string that specifies the name of the printer.

pComment

Windows NT: Points to a null-terminated string that contains additional data describing the structure.

Windows 95: Points to a null-terminated string that provides a brief description of the printer.

See Also

GetPrinter, EnumPrinters, PRINTER_INFO_2, PRINTER_INFO_3, PRINTER_INFO_4


PRINTER_INFO_2
 PRINTER_INFO_2  QuickInfo

typedef struct _PRINTER_INFO_2 { // pri2

    LPTSTR    pServerName;

    LPTSTR    pPrinterName;

    LPTSTR    pShareName;

    LPTSTR    pPortName;

    LPTSTR    pDriverName;

    LPTSTR    pComment;

    LPTSTR    pLocation;

    LPDEVMODE pDevMode;

    LPTSTR    pSepFile;

    LPTSTR    pPrintProcessor;

    LPTSTR    pDatatype;

    LPTSTR    pParameters;

    PSECURITY_DESCRIPTOR pSecurityDescriptor;

    DWORD     Attributes;

    DWORD     Priority;

    DWORD     DefaultPriority;

    DWORD     StartTime;

    DWORD     UntilTime;

    DWORD     Status;

    DWORD     cJobs;

    DWORD     AveragePPM;

} PRINTER_INFO_2;

The PRINTER_INFO_2 structure specifies detailed printer information.

Members

pServerName

Points to a null-terminated string identifying the server that controls the printer. If this string is NULL, the printer is controlled locally.

pPrinterName

Points to a null-terminated string that specifies the name of the printer.

pShareName

Points to a null-terminated string that identifies the sharepoint for the printer. (This string is used only if the PRINTER_ATTRIBUTE_SHARED constant was set for the Attributes member.)

pPortName

Points to a null-terminated string that identifies the port(s) used to transmit data to the printer. If a printer is connected to more than one port, the names of each port must be separated by commas (for example, "LPT1:,LPT2:,LPT3:").

pDriverName

Points to a null-terminated string that specifies the name of the printer driver.

pComment

Points to a null-terminated string that provides a brief description of the printer.

pLocation

Points to a null-terminated string that specifies the physical location of the printer (for example, "Bldg. 38, Room 1164").

pDevMode

Points to a DEVMODE structure that defines default printer data such as the paper orientation and the resolution.

pSepFile

Points to a null-terminated string that specifies the name of the file used to create the separator page. This page is used to separate print jobs sent to the printer.

pPrintProcessor

Points to a null-terminated string that specifies the name of the print processor used by the printer.

pDatatype

Points to a null-terminated string that specifies the data type used to record the print job.

pParameters

Points to a null-terminated string that specifies the default print-processor parameters.

pSecurityDescriptor

Points to a SECURITY_DESCRIPTOR structure for the printer. This member may be NULL.

Attributes

Specifies the printer attributes. This member can be one of the following values:

PRINTER_ATTRIBUTE_DEFAULT
PRINTER_ATTRIBUTE_DIRECT
PRINTER_ATTRIBUTE_DO_COMPLETE_FIRST
PRINTER_ATTRIBUTE_ENABLE_BIDI (Windows 95 only)
PRINTER_ATTRIBUTE_ENABLE_DEVQ
PRINTER_ATTRIBUTE_KEEPPRINTEDJOBS
PRINTER_ATTRIBUTE_QUEUED
PRINTER_ATTRIBUTE_SHARED
PRINTER_ATTRIBUTE_WORK_OFFLINE (Windows 95 only)

Priority

Specifies a priority value that the spooler uses to route print jobs.

DefaultPriority

Specifies the default priority value assigned to each print job.

StartTime

Specifies the earliest time at which the printer will print a job. (This value is specified in minutes elapsed since 12:00 A.M.)

UntilTime

Specifies the latest time at which the printer will print a job. (This value is specified in minutes elapsed since 12:00 A.M.)

Status

Specifies the printer status. This member can be one of the following values:

Windows NT:

PRINTER_STATUS_PAUSED
PRINTER_STATUS_PENDING_DELETION

Windows 95:

PRINTER_STATUS_BUSY
PRINTER_STATUS_DOOR_OPEN
PRINTER_STATUS_ERROR
PRINTER_STATUS_INITIALIZING
PRINTER_STATUS_IO_ACTIVE
PRINTER_STATUS_MANUAL_FEED
PRINTER_STATUS_NO_TONER
PRINTER_STATUS_NOT_AVAILABLE
PRINTER_STATUS_OFFLINE
PRINTER_STATUS_OUT_OF_MEMORY
PRINTER_STATUS_OUTPUT_BIN_FULL
PRINTER_STATUS_PAGE_PUNT
PRINTER_STATUS_PAPER_JAM
PRINTER_STATUS_PAPER_OUT
PRINTER_STATUS_PAPER_PROBLEM
PRINTER_STATUS_PAUSED
PRINTER_STATUS_PENDING_DELETION
PRINTER_STATUS_PRINTING
PRINTER_STATUS_PROCESSING
PRINTER_STATUS_TONER_LOW
PRINTER_STATUS_UNAVAILABLE
PRINTER_STATUS_USER_INTERVENTION
PRINTER_STATUS_WAITING
PRINTER_STATUS_WARMING_UP

cJobs

Specifies the number of print jobs that have been queued for the printer.

AveragePPM

Specifies the average number of pages per minute that have been printed on the printer.

Remarks

Windows 95: The PRINTER_STATUS_PAGE_PUNT value specifies that the page is being "punted" (that is, not printed) because it is too complex for the printer to print.

See Also

DEVMODE, EnumPrinters, PRINTER_INFO_1, PRINTER_INFO_3, PRINTER_INFO_4, SECURITY_DESCRIPTOR


PRINTER_INFO_3
 PRINTER_INFO_3  QuickInfo

typedef struct _PRINTER_INFO_3 { // pri3

    PSECURITY_DESCRIPTOR pSecurityDescriptor;

} PRINTER_INFO_3;

The PRINTER_INFO_3 structure specifies printer security information.

Members

pSecurityDescriptor

Points to a SECURITY_DESCRIPTOR structure that specifies a printer's security information.

Remarks

The PRINTER_INFO_3 structure lets an application get and set a printer's security descriptor. The caller may do so even if it lacks specific printer permissions, as long as it has the standard rights described in SetPrinter and GetPrinter. Thus, an application may temporarily deny all access to a printer, while allowing the owner of the printer to have access to the printer's discretionary ACL.

See Also

SetPrinter, GetPrinter, PRINTER_INFO_1, PRINTER_INFO_2, PRINTER_INFO_4, SECURITY_DESCRIPTOR


PRINTER_INFO_4
 PRINTER_INFO_4  QuickInfo

typedef struct _PRINTER_INFO_4 { // pri4

    LPTSTR  pPrinterName;

    LPTSTR  pServerName;

    DWORD  Attributes;

} PRINTER_INFO_4;

The PRINTER_INFO_4 structure specifies general printer information.

The structure can be used to retrieve minimal printer information on a call to EnumPrinters. Such a call is a fast and easy way to retrieve the names and attributes of all locally installed printers on a system and all remote printer connections that a user has established.

Members

pPrinterName

Points to a null-terminated string that specifies the name of the printer (local or remote).

pServerName

Points to a null-terminated string that is the name of the server.

Attributes

Specifies information about the returned data.

Value	Meaning
PRINTER_ATTRIBUTE_LOCAL	The printer is a local printer.
PRINTER_ATTRIBUTE_NETWORK	The printer is a remote printer.
Remarks

The PRINTER_INFO_4 structure provides an easy and extremely fast way to retrieve the names of the printers installed on a local machine, as well as the remote connections that a user has established. When EnumPrinters is called with a PRINTER_INFO_4 data structure, that function queries the registry for the specified information, then returns immediately. This differs from the behavior of EnumPrinters when called with other levels of PRINTER_INFO_xxx data structures. In particular, when EnumPrinters is called with a level 2 (PRINTER_INFO_2) data structure, it performs an OpenPrinter call on each remote connection. If a remote connection is down, if the remote server no longer exists, or if the remote printer no longer exists, the function must wait for RPC to time out and consequently fail the OpenPrinter call. This can take a while. Passing a PRINTER_INFO_4 structure lets an application retrieve a bare minimium of required information; if more detailed information is desired, a subsequent EnumPrinter level 2 call can be made.

See Also

GetPrinter, EnumPrinters, OpenPrinter, PRINTER_INFO_1, PRINTER_INFO_2, PRINTER_INFO_3


PRINTER_INFO_5 [New - Windows 95]
 PRINTER_INFO_5  QuickInfo

[New - Windows 95]

typedef struct _PRINTER_INFO_5 { // pri5

    LPTSTR    pPrinterName;

    LPTSTR    pPortName;

    DWORD     Attributes;

    DWORD     DeviceNotSelectedTimeout;

    DWORD     TransmissionRetryTimeout;

} PRINTER_INFO_5;

The PRINTER_INFO_5 structure specifies detailed printer information.

Members

pPrinterName

Points to a null-terminated string that specifies the name of the printer.

pPortName

Points to a null-terminated string that identifies the port(s) used to transmit data to the printer. If a printer is connected to more than one port, the names of each port must be separated by commas (for example, "LPT1:,LPT2:,LPT3:").

Attributes

Specifies the printer attributes. This member can be one of the following values:

PRINTER_ATTRIBUTE_QUEUED
PRINTER_ATTRIBUTE_DIRECT
PRINTER_ATTRIBUTE_DEFAULT
PRINTER_ATTRIBUTE_SHARED
PRINTER_ATTRIBUTE_WORK_OFFLINE

DeviceNotSelectedTimeout

Specifies the maximum time, in milliseconds, allowed to elapse between attempts to select a device.

TransmissionRetryTimeout

Specifies the maximum time, in milliseconds, allowed to elapse between transmission retries.

See Also

EnumPrinters, GetPrinter, SetPrinter, PRINTER_INFO_1, PRINTER_INFO_2, PRINTER_INFO_3, PRINTER_INFO_4


PRINTER_NOTIFY_INFO
 PRINTER_NOTIFY_INFO  QuickInfo  Overview  Group

typedef struct _PRINTER_NOTIFY_INFO {

    DWORD  Version;

    DWORD  Flags;

    DWORD  Count;

    PRINTER_NOTIFY_INFO_DATA  aData[1];

} PRINTER_NOTIFY_INFO;

The PRINTER_NOTIFY_INFO structure contains printer information returned by the FindNextPrinterChangeNotification function. The function returns this information after a wait operation on a printer change notification object has been satisfied.

Members

Version

Specifies the version of this structure. Set this member to 2.

Flags

Contains a bit flag to indicate the state of the notification structure. If the PRINTER_NOTIFY_INFO_DISCARDED bit is set, it indicates that some notifications had to be discarded.

Count

Specifies the number of PRINTER_NOTIFY_INFO_DATA elements in the aData array.

aData

An array of PRINTER_NOTIFY_INFO_DATA structures. Each element of the array identifies a single job or printer information field, and provides the current data for that field.

Remarks

If the Flags member has the PRINTER_NOTIFY_INFO_DISCARDED bit set, this indicates that an overflow or error occured, and notifications may have been lost. In this case, you must call FindNextPrinterChangeNotification and specify the PRINTER_NOTIFY_OPTIONS_REFRESH flag to retrieve all current information. Until you request this refresh operation, the system will not send additional notifications for this change notification object.

See Also

FindNextPrinterChangeNotification, PRINTER_NOTIFY_INFO_DATA


PRINTER_NOTIFY_INFO_DATA
 PRINTER_NOTIFY_INFO_DATA  QuickInfo  Overview  Group

typedef struct _PRINTER_NOTIFY_INFO_DATA {

    WORD   Type;

    WORD   Field;

    DWORD  Reserved;

    DWORD  Id;

    union {

        DWORD  adwData[2];

        struct {

            DWORD  cbBuf;

            LPVOID pBuf;

        } Data;

    } NotifyData;

} PRINTER_NOTIFY_INFO_DATA;

The PRINTER_NOTIFY_INFO_DATA structure identifies a job or printer information field and provides the current data for that field.

The FindNextPrinterChangeNotification function returns a PRINTER_NOTIFY_INFO structure, which contains an array of PRINTER_NOTIFY_INFO_DATA structures.

Members

Type

Indicates the type of information provided. This member can be one of the following values:

Value	Meaning
PRINTER_NOTIFY_TYPE	Indicates that the Field member specifies a PRINTER_NOTIFY_FIELD_* constant.
JOB_NOTIFY_TYPE	Indicates that the Field member specifies a JOB_NOTIFY_FIELD_* constant.
Field

Indicates the field that changed. For a list of possible values, see the following Remarks section.

Reserved

Reserved.

Id

Indicates the job identifier if the Type member specifies JOB_NOTIFY_TYPE. If the Type member specfies PRINTER_NOTIFY_TYPE, this member is undefined.

NotifyData

A union of data information based on the Type and Field members. For a description of the type of data associated with each field, see the following Remarks section.

The NotifyData union can be one of the following members:

Member	Meaning
adwData	An array of two DWORD values. For information fields that use only a single DWORD, the data is in adwData[0]
Data	The following members are contained in the Data structure:
Member	Meaning
cbBuf	Indicates the size, in bytes, of the buffer pointed to by pBuf.
pBuf	Points to a buffer that contains the field's current data.
Remarks

If the Type member specifies PRINTER_NOTIFY_TYPE, the Field member can be one of the following values:

Field	Type of data
PRINTER_NOTIFY_FIELD_PRINTER_NAME
	pBuf points to a null-terminated string containing the name of the printer.
PRINTER_NOTIFY_FIELD_SHARE_NAME
	pBuf points to a null-terminated string that identifies the sharepoint for the printer.
PRINTER_NOTIFY_FIELD_DRIVER_NAME
	pBuf points to a null-terminated string containing the name of the printer's driver.
PRINTER_NOTIFY_FIELD_COMMENT
	pBuf points to a null-terminated string containing the new comment string, which is typically a brief description of the printer.
PRINTER_NOTIFY_FIELD_LOCATION
	pBuf points to a null-terminated string containing the new physical location of the printer (for example, "Bldg. 38, Room 1164").
PRINTER_NOTIFY_FIELD_DEVMODE
	pBuf points to a DEVMODE structure that defines default printer data such as the paper orientation and the resolution.
PRINTER_NOTIFY_FIELD_SEPFILE
	pBuf points to a null-terminated string that specifies the name of the file used to create the separator page. This page is used to separate print jobs sent to the printer.
PRINTER_NOTIFY_FIELD_PRINT_PROCESSOR
	pBuf points to a null-terminated string that specifies the name of the print processor used by the printer.
PRINTER_NOTIFY_FIELD_PARAMETERS
	pBuf points to a null-terminated string that specifies the default print-processor parameters.
PRINTER_NOTIFY_FIELD_DATATYPE
	pBuf points to a null-terminated string that specifies the data type used to record the print job.
PRINTER_NOTIFY_FIELD_SECURITY_DESCRIPTOR
	pBuf points to a SECURITY_DESCRIPTOR structure for the printer. The pointer may be NULL if there is no security descriptor.
PRINTER_NOTIFY_FIELD_ATTRIBUTES
	adwData[0] specifies the printer attributes, which can be one of the following values:  PRINTER_ATTRIBUTE_QUEUED PRINTER_ATTRIBUTE_DIRECT PRINTER_ATTRIBUTE_DEFAULT PRINTER_ATTRIBUTE_SHARED
PRINTER_NOTIFY_FIELD_PRIORITY
	adwData[0] specifies a priority value that the spooler uses to route print jobs.
PRINTER_NOTIFY_FIELD_DEFAULT_PRIORITY
	adwData[0] specifies the default priority value assigned to each print job.
PRINTER_NOTIFY_FIELD_START_TIME
	adwData[0] specifies the earliest time at which the printer will print a job. (This value is specified in minutes elapsed since 12:00 A.M.)
PRINTER_NOTIFY_FIELD_UNTIL_TIME
	adwData[0] specifies the latest time at which the printer will print a job. (This value is specified in minutes elapsed since 12:00 A.M.)
PRINTER_NOTIFY_FIELD_STATUS
	adwData[0] specifies the printer status. For a list of possible values, see the PRINTER_INFO_2 structure.
PRINTER_NOTIFY_FIELD_CJOBS
	adwData[0] specifies the number of print jobs that have been queued for the printer.
PRINTER_NOTIFY_FIELD_AVERAGE_PPM
	adwData[0] specifies the average number of pages per minute that have been printed on the printer.

If the Type member specifies JOB_NOTIFY_TYPE, the Field member can be one of the following values:

Field	Type of data
JOB_NOTIFY_FIELD_PRINTER_NAME
	pBuf points to a null-terminated string containing the name of the printer for which the job is spooled.
JOB_NOTIFY_FIELD_MACHINE_NAME
	pBuf points to a null-terminated string that specifies the name of the machine that created the print job.
JOB_NOTIFY_FIELD_PORT_NAME
	pBuf points to a null-terminated string that identifies the port(s) used to transmit data to the printer. If a printer is connected to more than one port, the names of the ports are separated by commas (for example, "LPT1:,LPT2:,LPT3:").
JOB_NOTIFY_FIELD_USER_NAME
	pBuf points to a null-terminated string that specifies the name of the user who sent the print job.
JOB_NOTIFY_FIELD_NOTIFY_NAME
	pBuf points to a null-terminated string that specifies the name of the user who should be notified when the job has been printed or when an error occurs while printing the job.
JOB_NOTIFY_FIELD_DATATYPE
	pBuf points to a null-terminated string that specifies the type of data used to record the print job.
JOB_NOTIFY_FIELD_PRINT_PROCESSOR
	pBuf points to a null-terminated string that specifies the name of the print processor to be used to print the job.
JOB_NOTIFY_FIELD_PARAMETERS
	pBuf points to a null-terminated string that specifies print-processor parameters.
JOB_NOTIFY_FIELD_DRIVER_NAME
	pBuf points to a null-terminated string that specifies the name of the printer driver that should be used to process the print job.
JOB_NOTIFY_FIELD_DEVMODE
	pBuf points to a DEVMODE structure that contains device-initialization and environment data for the printer driver.
JOB_NOTIFY_FIELD_STATUS
	adwData[0] specifies the job status. For a list of possible values, see the JOB_INFO_2 structure.
JOB_NOTIFY_FIELD_STATUS_STRING
	pBuf points to a null-terminated string that specifies the status of the print job.
JOB_NOTIFY_FIELD_DOCUMENT
	pBuf points to a null-terminated string that specifies the name of the print job (for example, "MS-WORD: Review.doc").
JOB_NOTIFY_FIELD_PRIORITY
	adwData[0] specifies the job priority.
JOB_NOTIFY_FIELD_POSITION
	adwData[0] specifies the job's position in the print queue.
JOB_NOTIFY_FIELD_SUBMITTED
	pBuf points to a SYSTEMTIME structure that specifies the time when the job was submitted.
JOB_NOTIFY_FIELD_START_TIME
	adwData[0] specifies the earliest time that the job can be printed. (This value is specified in minutes elapsed since 12:00 A.M.)
JOB_NOTIFY_FIELD_UNTIL_TIME
	adwData[0] specifies the the latest time that the job can be printed. (This value is specified in minutes elapsed since 12:00 A.M.)
JOB_NOTIFY_FIELD_TIME
	adwData[0] specifies the total time, in seconds, that has elapsed since the job began printing.
JOB_NOTIFY_FIELD_TOTAL_PAGES
	adwData[0] specifies the size, in pages, of the job.
JOB_NOTIFY_FIELD_PAGES_PRINTED
	adwData[0] specifies the number of pages that have printed.
JOB_NOTIFY_FIELD_TOTAL_BYTES
	adwData[0] specifies the size, in bytes, of the job.
JOB_NOTIFY_FIELD_BYTES_PRINTED
	adwData[0] specifies the number of bytes that have been printed on this job. For this field, the change notification object is signaled when bytes are sent to the printer.
See Also

DEVMODE, FindNextPrinterChangeNotification, JOB_INFO_2, PRINTER_INFO_2, PRINTER_NOTIFY_INFO, SECURITY_DESCRIPTOR, SYSTEMTIME


PRINTER_NOTIFY_OPTIONS
 PRINTER_NOTIFY_OPTIONS  QuickInfo  Overview  Group

typedef struct _PRINTER_NOTIFY_OPTIONS {

    DWORD  Version;

    DWORD  Flags;

    DWORD  Count;

    PPRINTER_NOTIFY_OPTIONS_TYPE  pTypes;

} PRINTER_NOTIFY_OPTIONS;

The PRINTER_NOTIFY_OPTIONS structure specifies options for a change notification object that monitors a printer or print server.

Members

Version

Specifies the version of this structure. Set this member to 2.

Flags

Contains a bit flag. If you set the PRINTER_NOTIFY_OPTIONS_REFRESH flag in a call to the FindNextPrinterChangeNotification function, the function provides current data for all monitored printer information fields. The FindFirstPrinterChangeNotification function ignores the Flags member.

Count

Specifies the number of elements in the pTypes array.

pTypes

Points to an array of PRINTER_NOTIFY_OPTIONS_TYPE structures. Use one element of this array to specify the printer information fields to monitor, and one element to specify the job information fields to monitor. You can monitor either printer information, job information, or both.

Remarks

Use this structure with the FindFirstPrinterChangeNotification function to specify the set of printer or job information fields to monitor for change.

Use this structure with the FindNextPrinterChangeNotification function to request the current data for all monitored printer and job information fields. In this case, the Flags member specifies the PRINTER_NOTIFY_OPTIONS_REFRESH flag, and the function ignores the other structure members.

See Also

FindFirstPrinterChangeNotification, FindNextPrinterChangeNotification, PRINTER_NOTIFY_OPTIONS_TYPE


PRINTER_NOTIFY_OPTIONS_TYPE
 PRINTER_NOTIFY_OPTIONS_TYPE  QuickInfo  Overview  Group

typedef struct _PRINTER_NOTIFY_OPTIONS_TYPE {

    WORD   Type;

    WORD   Reserved0;

    DWORD  Reserved1;

    DWORD  Reserved2;

    DWORD  Count;

    PWORD  pFields;

} PRINTER_NOTIFY_OPTIONS_TYPE;

The PRINTER_NOTIFY_OPTIONS_TYPE structure specifies the set of printer or job information fields to be monitored by a printer change notification object.

A call to the FindFirstPrinterChangeNotification function specifies a PRINTER_NOTIFY_OPTIONS structure, which contains an array of PRINTER_NOTIFY_OPTIONS_TYPE structures.

Members

Type

Specifies the type to watch. This member can be one of the following values:

Value	Meaning
PRINTER_NOTIFY_TYPE	Indicates that the fields specified in the pFields array are PRINTER_NOTIFY_FIELD_* constants.
JOB_NOTIFY_TYPE	Indicates that the fields specified in the pFields array are JOB_NOTIFY_FIELD_* constants.
Reserved0

Reserved.

Reserved1

Reserved.

Reserved2

Reserved.

Count

Specifies the number of elements in the pFields array.

pFields

Points to an array of 16-bit values. Each element of the array specifies a job or printer information field of interest. For a list of supported printer and job information fields, see the PRINTER_NOTIFY_INFO_DATA structure.

See Also

FindFirstPrinterChangeNotification, PRINTER_NOTIFY_INFO_DATA, PRINTER_NOTIFY_OPTIONS


PRINTPROCESSOR_INFO_1
 PRINTPROCESSOR_INFO_1  QuickInfo

typedef struct _PRINTPROCESSOR_INFO_1 { // ppi1

    LPTSTR pName;

} PRINTPROCESSOR_INFO_1;

The PRINTPROCESSOR_INFO_1 structure specifies the name of an installed print processor.

Members

pName

Points to a null-terminated string that specifies the name of an installed print processor.

See Also

EnumPrintProcessors


PRIVILEGE_SET
 PRIVILEGE_SET  QuickInfo

typedef struct _PRIVILEGE_SET { // ps

    DWORD PrivilegeCount;

    DWORD Control;

    LUID_AND_ATTRIBUTES Privilege[ANYSIZE_ARRAY];

} PRIVILEGE_SET;

The PRIVILEGE_SET structure specifies a set of privileges. It is also used to indicate which, if any, privileges are held by a user or group requesting access to an object.

Members

PrivilegeCount

Specifies the number of privileges in the privilege set.

Control

Specifies a control flag related to the privileges. The PRIVILEGE_SET_ALL_NECESSARY control flag is currently defined. It indicates that all of the specified privileges must be held by the process requesting access. If this flag is not set, the presence of any privileges in the user's access token grants the access.

Privilege

Specifies an array of LUID_AND_ATTRIBUTES structures describing the set's privileges. The following attributes are defined for privileges:

Attribute	Description
SE_PRIVILEGE_ENABLED_BY_DEFAULT
	The privilege is enabled by default.
SE_PRIVILEGE_ENABLED
	The privilege is enabled.
SE_PRIVILEGE_USED_FOR_ACCESS
	The privilege was used to gain access to an object or service. This flag is used to identify the relevant privileges in a set passed by a client application that may contain unnecessary privileges.
Remarks

A privilege is used to control access to an object or service more strictly than is typical with discretionary access control. A system manager uses privileges to control which users are able to manipulate system resources. An application uses privileges when it changes a system-wide resource, such as when it changes the system time or shuts down the system.

See Also

PrivilegeCheck, LUID, LUID_AND_ATTRIBUTES


PROCESS_HEAP_ENTRY
 PROCESS_HEAP_ENTRY  QuickInfo

typedef struct _PROCESS_HEAP_ENTRY {

    PVOID lpData;

    DWORD cbData;

    BYTE cbOverhead;

    BYTE iRegionIndex;

    WORD wFlags;

    union {

        struct {

            HANDLE hMem;

            DWORD dwReserved[ 3 ];

        } Block;

        struct {

            DWORD dwCommittedSize;

            DWORD dwUnCommittedSize;

            LPVOID lpFirstBlock;

            LPVOID lpLastBlock;

        } Region;

    };

} PROCESS_HEAP_ENTRY;

The PROCESS_HEAP_ENTRY structure contains information about a heap element. The HeapWalk function uses a PROCESS_HEAP_ENTRY structure to enumerate the elements of a heap.

Members

lpData

Points to the data portion of the heap element.

To initiate a HeapWalk heap enumeration, set lpData to NULL.

If the PROCESS_HEAP_REGION bit flag is set in the wFlags member, lpData points to the first virtual address used by the region.

If the PROCESS_HEAP_UNCOMMITTED_RANGE bit flag is set in wFlags, lpData points to the beginning of the range of uncommitted memory.

cbData

Specifies the size, in bytes, of the data portion of the heap element.

If the PROCESS_HEAP_REGION bit flag is set in wFlags, cbData specifies the total size, in bytes, of the address space that is reserved for this region.

If the PROCESS_HEAP_UNCOMMITTED_RANGE bit flag is set in wFlags, cbData specifies the size, in bytes, of the range of uncommitted memory.

cbOverhead

Specifies the size, in bytes, of the data used by the system to maintain information about the heap element. These overhead bytes are in addition to the cbData bytes of the data portion of the heap element.

If the PROCESS_HEAP_REGION bit flag is set in wFlags, cbOverhead specifies the size, in bytes, of the heap control structures that describe the region.

If the PROCESS_HEAP_UNCOMMITTED_RANGE bit flag is set in wFlags, cbOverhead specifies the size, in bytes, of the control structures that describe this uncommitted range.

iRegionIndex

Identifies the heap region that contains the heap element. A heap consists of one or more regions of virtual memory, each with a unique region index.

In the first heap entry returned for most heap regions, HeapWalk sets the PROCESS_HEAP_REGION flag in the wFlags member. When this flag is set, the members of the Region structure contain additional information about the region.

The HeapAlloc function sometimes uses the VirtualAlloc function to allocate large blocks from a growable heap. The heap manager treats such a large block allocation as a separate region with a unique region index. HeapWalk does not set the PROCESS_HEAP_REGION flag in the heap entry returned for a large block region, so the members of the Region structure are not valid. You can use the VirtualQuery function to get additional information about a large block region.

wFlags

A set of bit flags that specify properties of the heap element. Some of these flags affect the meaning of other members of this PROCESS_HEAP_ENTRY data structure. The following bit-flag constants are defined:

Value	Meaning
PROCESS_HEAP_REGION	If this flag is set, the heap element is located at the beginning of a region of contiguous virtual memory in use by the heap.  If this flag is set, the lpData member of the structure points to the first virtual address used by the region; the cbData member specifies the total size, in bytes, of the address space that is reserved for this region; and the cbOverhead member specifies the size, in bytes, of the heap control structures that describe the region. If this flag is set, the Region structure becomes valid. The dwCommittedSize, dwUnCommittedSize, lpFirstBlock, and lpLastBlock members of the structure contain additional information about the region.
PROCESS_HEAP_UNCOMMITTED_RANGE	If this flag is set, the heap element is located in a range of uncommitted memory within the heap region.  If this flag is set, the lpData member points to the beginning of the range of uncommitted memory; the cbData member specifies the size, in bytes, of the range of uncommitted memory; and the cbOverhead member specifies the size, in bytes, of the control structures that describe this uncommitted range.
PROCESS_HEAP_ENTRY_BUSY	If this flag is set, the heap element is an allocated block.  If both this flag and the PROCESS_HEAP_ENTRY_MOVEABLE flag are set, the Block structure becomes valid. The hMem member of the Block structure contains a handle to the allocated, moveable memory block.
PROCESS_HEAP_ENTRY_MOVEABLE	This flag is only valid if the PROCESS_HEAP_ENTRY_BUSY flag is set, indicating that the heap element is an allocated block. If this flag is valid and set, the block was allocated with the LMEM_MOVEABLE or GMEM_MOVEABLE flag, and the Block structure becomes valid. The hMem member of the Block structure contains a handle to the allocated, moveable memory block.
PROCESS_HEAP_ENTRY_DDESHARE	This flag is only valid if the PROCESS_HEAP_ENTRY_BUSY flag is set, indicating that the heap element is an allocated block. If this flag is valid and set, the block was allocated with the GMEM_DDESHARE flag. For a discussion of the GMEM_DDESHARE flag, see GlobalAlloc .
Block

This structure is valid only if both the PROCESS_HEAP_ENTRY_BUSY and PROCESS_HEAP_ENTRY_MOVEABLE flags in wFlags are set.

The members of the Block structure are as follows:

Member	Description
hMem	Contains a handle to the allocated, moveable memory block.
dwReserved	Reserved; not used.
Region

This structure is valid only if the PROCESS_HEAP_REGION flag is set in the wFlags member.

The members of the Region structure are as follows:

Member	Description
dwCommittedSize	Specifies the number of bytes in the heap region that are currently committed as free memory blocks, busy memory blocks, or heap control structures. This is an optional field that is set to zero if the number of committed bytes is not available.
dwUnCommittedSize	Specifies the number of bytes in the heap region that are currently uncommitted. This is an optional field that is set to zero if the number of uncommitted bytes is not available.
lpFirstBlock	Pointer to the first valid memory block in this heap region.
lpLastBlock	Pointer to the first invalid memory block in thisheap region.
See Also

GlobalAlloc, HeapAlloc, HeapWalk, VirtualAlloc, VirtualQuery


PROCESS_INFORMATION
 PROCESS_INFORMATION  QuickInfo

typedef struct _PROCESS_INFORMATION { // pi

    HANDLE hProcess;

    HANDLE hThread;

    DWORD dwProcessId;

    DWORD dwThreadId;

} PROCESS_INFORMATION;

The PROCESS_INFORMATION structure is filled in by the CreateProcess function with information about a newly created process and its primary thread.

Members

hProcess

Returns a handle to the newly created process. The handle is used to specify the process in all functions that perform operations on the process object.

hThread

Returns a handle to the primary thread of the newly created process. The handle is used to specify the thread in all functions that perform operations on the thread object.

dwProcessId

Returns a global process identifier that can be used to identify a process. The value is valid from the time the process is created until the time the process is terminated.

dwThreadId

Returns a global thread identifiers that can be used to identify a thread. The value is valid from the time the thread is created until the time the thread is terminated.

See Also

CreateProcess


PROPSHEETHEADER [New - Windows NT]
 PROPSHEETHEADER  QuickInfo  Overview  Group

[New - Windows NT]

typedef struct _PROPSHEETHEADER { // psh

    DWORD      dwSize;

    DWORD      dwFlags;

    HWND       hwndParent;

    HINSTANCE  hInstance;

    union {

        HICON  hIcon;

        LPCTSTR pszIcon;

    };

    LPCTSTR     pszCaption;

    UINT       nPages

    union {

        UINT  nStartPage

        LPCTSTR pStartPage;

    };

    union {

        LPCPROPSHEETPAGE    ppsp;

        HPROPSHEETPAGE FAR *phpage;

    };

    PFNPROPSHEETCALLBACK pfnCallback;

} PROPSHEETHEADER, FAR *LPPROPSHEETHEADER;

typedef const PROPSHEETHEADER FAR *LPCPROPSHEETHEADER;

The PROPSHEETHEADER structure defines the frame and pages of a property sheet.

Members

dwSize

Size, in bytes, of this structure.

dwFlags

Array of flags that indicate which other members to use and which to ignore. This member can be a combination of the following values:

Value	Meaning
PSH_DEFAULT	Uses the default meaning for all structure members.
PSH_HASHELP	Displays the property sheet Help button. The Help button is enabled only when the PSP_HASHELP flag is set in the PROPSHEETPAGE structure for the active page.  If any of the initial property sheet pages sets the PSP_HASHELP flag, the Help button is automatically displayed regardless of the PSH_HASHELP flag. However, PSH_HASHELP is useful when none of the initial pages set PSP_HASHELP, but pages added later might.
PSH_MODELESS	Causes the PropertySheet function to create the property sheet as a modeless dialog instead of the default modal behavior. When this flag is set, PropertySheet returns immediately after the dialog is created and the return value from PropertySheet is the window handle of the property sheet dialog.
PSH_MULTILINETABS	Allows multiple rows of tabbed pages.
PSH_NOAPPLYNOW	Removes the Apply Now button.
PSH_PROPSHEETPAGE	Uses ppsp and ignores phpage when creating the pages for the property sheet.
PSH_PROPTITLE	Includes "Properties for" with the string specified by pszCaption in the title bar of the property sheet.
PSH_USECALLBACK	Calls the function specified by pfnCallback when initializing the property sheet defined by this structure.
PSH_USEHICON	Uses hIcon as the small icon in the title bar of the property sheet dialog box.
PSH_USEICONID	Uses pszIcon as the name of the icon resource to load and use as the small icon in the title bar of the property sheet dialog box.
PSH_USEPSTARTPAGE	Uses pStartPage and ignores nStartPage when displaying the initial page of the property sheet.
PSH_WIZARD	Creates a wizard property sheet.
PSH_RTLREADING	Windows 95 only: Displays the title of the property sheet dialog using right-to-left reading order on Hebrew or Arabic systems.
hwndParent

Handle of the owner window.

hInstance

Handle of the instance from which to load the icon or title string resource. If pszIcon or pszCaption identifies a resource to load, this member must be specified.

hIcon

Handle of the icon to use as the small icon in the title bar of the property sheet dialog box. If dwFlags does not include the PSH_USEHICON value, this member is ignored.

pszIcon

Icon resource to use as the small icon in the title bar of the property sheet dialog box. This member can specify either the identifier of the icon resource or the pointer to the string that specifies the name of the icon resource. If dwFlags does not include the PSH_USEICONID value, this member is ignored.

pszCaption

Title of the property sheet dialog box. This member can specify either the identifier of a string resource or the pointer to a string that specifies the title. If dwFlags includes the PSH_PROPTITLE value, the string, "Properties for" is used with the title.

nPages

Number of elements in phpage array.

nStartPage

Zero-based index of the initial page that appears when the property sheet dialog box is created.

pStartPage

Name of the initial page that appears when the property sheet dialog box is created. This member can specify either the identifier of a string resource or the pointer to a string that specifies the name.

ppsp

Pointer to an array of PROPSHEETPAGE structures that define the pages in the property sheet. If dwFlags does not include the PSH_PROPSHEETPAGE value, this member is ignored.

phpage

Pointer to an array that contains handles of property sheet pages. Each handle must have been created by a previous call to the CreatePropertySheetPage function. If dwFlags includes the PSH_PROPSHEETPAGE value, this member is ignored.

pfnCallback

Pointer to an application-defined callback function that is called when the property sheet is initialized. For more information about the callback function, see the description of the PropSheetProc function. If dwFlags does not include the PSP_USECALLBACK value, this member is ignored.

See Also

CreatePropertySheetPage, PropertySheet, PROPSHEETPAGE, PropSheetProc


PROPSHEETPAGE [New - Windows NT]
 PROPSHEETPAGE  QuickInfo  Overview  Group

[New - Windows NT]

typedef struct _PROPSHEETPAGE { // psp

    DWORD     dwSize;

    DWORD     dwFlags;

    HINSTANCE hInstance;

    union {

        LPCTSTR        pszTemplate;

        LPCDLGTEMPLATE pResource;

    };

    union {

        HICON  hIcon;

        LPCTSTR pszIcon;

    };

    LPCTSTR pszTitle;

    DLGPROC pfnDlgProc;

    LPARAM  lParam;

    LPFNPSPCALLBACK pfnCallback;

    UINT FAR * pcRefParent;

} PROPSHEETPAGE, FAR *LPPROPSHEETPAGE;

typedef const PROPSHEETPAGE FAR *LPCPROPSHEETPAGE;

The PROPSHEETPAGE structure defines a page in a property sheet.

Members

dwSize

Size, in bytes, of the structure. The size includes any extra application-defined data at the end of the structure.

dwFlags

Array of flags that indicate which other structure members to use and which to ignore. This member can be a combination of the following values:

Value	Meaning
PSP_DEFAULT	Uses the default meaning for all structure members.
PSP_DLGINDIRECT	Uses pResource instead of pszTemplate. That is, the template for the property sheet dialog box is supplied in memory, not loaded from a resource.
PSP_HASHELP	Enables the property sheet Help button when this page is active.
PSP_USECALLBACK	Calls the function specified by pfnCallback when creating or destroying the property sheet page defined by this structure.
PSP_USEHICON	Uses hIcon as the small icon on the tab for the page.
PSP_USEICONID	Uses pszIcon as the name of the icon resource to load and use as the small icon on the tab for the page.
PSP_USEREFPARENT	Maintains the reference count specified by pcRefParent for the lifetime of the property sheet page created from this structure.
PSP_USETITLE	Uses pszTitle as the title of the property sheet dialog box instead of the title stored in the dialog box template.
PSP_RTLREADING	Windows 95 only: When this page is active, displays the text of pszTitle using right-to-left reading order on Hebrew or Arabic systems.
hInstance

Handle to the instance from which to load the dialog box template, icon, or title string resource.

pszTemplate

Dialog box template to use to create the page. This member can specify either the resource identifier of the template or the address of a string that specifies the name of the template. If dwFlags includes the PSP_DLGINDIRECT value, this member is ignored.

pResource

Pointer to a dialog box template in memory. If dwFlags does not include the PSP_DLGINDIRECT value, this member is ignored.

hIcon

Handle to the icon to use as the small icon in the tab for the page. If dwFlags does not include the PSP_USEHICON value, this member is ignored.

pszIcon

Icon resource to use as the small icon in the tab for the page. This member can specify either the identifier of the icon resource or the pointer to the string that specifies the name of the icon resource. If dwFlags does not include the PSP_USEICONID value, this member is ignored.

pszTitle

Title of the property sheet dialog box. This title overrides the title specified in the dialog box template. This member can specify either the identifier of a string resource or the pointer to a string that specifies the title. If dwFlags does not include the PSP_USETITLE value, this member is ignored.

pfnDlgProc

Pointer to the dialog box procedure for the page. The dialog box procedure must not call the EndDialog function.

lParam

Application-defined data.

pfnCallback

Pointer to an application-defined callback function that is called when the page is created and when it is about to be destroyed. For more information about the callback function, see PropSheetPageProc. If dwFlags does not include the PSP_USECALLBACK value, this member is ignored.

pcRefParent

Pointer to the reference count value. If dwFlags does not include the PSP_USERREFPARENT value, this member is ignored.

Remarks

When the PropertySheet function creates the page, the dialog box procedure for the page receives a WM_INITDIALOG message. The lParam parameter of this message points to the PROPSHEETPAGE structure used to create the page.

See Also

EndDialog, PropSheetPageProc, PropertySheet, WM_INITDIALOG


PROTOCOL_INFO
 PROTOCOL_INFO  QuickInfo  Overview  Group

typedef  struct _PROTOCOL_INFO {

    DWORD  dwServiceFlags;

    INT  iAddressFamily;

    INT  iMaxSockAddr;

    INT  iMinSockAddr;

    INT  iSocketType;

    INT  iProtocol;

    DWORD  dwMessageSize;

    LPTSTR  lpProtocol;

} PROTOCOL_INFO;

The PROTOCOL_INFO structure contains information about a protocol.

Members

dwServiceFlags

A set of bit flags that specify the services provided by the protocol. One or more of the following bit flags may be set:

Value	Meaning
XP_CONNECTIONLESS	If this flag is set, the protocol providesconnectionless (datagram) service. If this flag is clear, the protocol provides connection-oriented data transfer.
XP_GUARANTEED_DELIVERY	If this flag is set, the protocol guarantees that all data sent will reach the intended destination. If this flag is clear, there is no such guarantee.
XP_GUARANTEED_ORDER	If this flag is set, the protocol guarantees that data will arrive in the order in which it was sent. Note that this characteristic does not guarantee delivery of the data, but guarantees only its order. If this flag is clear, the order of data sent is not guaranteed.
XP_MESSAGE_ORIENTED	If this flag is set, the protocol is message-oriented. A message-oriented protocol honors message boundaries. If this flag is clear, the protocol is stream-oriented, and the concept of message boundaries is irrelevant.
XP_PSEUDO_STREAM	If this flag is set, the protocol is a message-oriented protocol that ignores message boundaries for all receive operations.  This optional capability is useful when you do not want the protocol to frame messages. An application that requires stream-oriented characteristics can open a socket with type SOCK_STREAM for transport protocols that support this functionality, regardless of the value of iSocketType.
XP_GRACEFUL_CLOSE	If this flag is set, the protocol supports two-phase close operations, also known as "graceful" close operations. If this flag is clear, the protocol supports only abortive close operations.
XP_EXPEDITED_DATA	If this flag is set, the protocol supports expedited data, also known as "urgent data."
XP_CONNECT_DATA	If this flag is set, the protocol supports connect data.
XP_DISCONNECT_DATA	If this flag is set, the protocol supports disconnect data.
XP_SUPPORTS_BROADCAST	If this flag is set, the protocol supports a broadcast mechanism.
XP_SUPPORTS_MULTICAST	If this flag is set, the protocol supports a multicast mechanism.
XP_BANDWIDTH_ALLOCATION	If this flag is set, the protocol supports a mechanism for allocating a guaranteed bandwidth to an application.
XP_FRAGMENTATION	If this flag isset, the protocol supports message fragmentation; physical network MTU is hidden from applications.
XP_ENCRYPTS	If this flag is set, the protocol supports data encryption.
iAddressFamily

Specifies the value to pass as the af parameter when you call the socket function to open a socket for the protocol. This address family value uniquely defines the structure of Protocol addresses, also known as SOCKADDRs, used by the protocol.

iMaxSockAddr

Specifies the maximum length of a socket address supported by the protocol.

iMinSockAddr

Specifies the minimum length of a socket address supported by the protocol.

iSocketType

Specifies the value to pass as the type parameter when you call the socket function to open a socket for the protocol.

Note that if XP_PSEUDO_STREAM is set in dwServiceFlags, the application can specify SOCK_STREAM as the type parameter to socket, regardless of the value of iSocketType.

iProtocol

Specifies the value to pass as the protocol parameter when you call the socket function to open a socket for the protocol.

dwMessageSize

Specifies the maximum message size supported by the protocol. This is the maximum size of a message that can be sent from or received by the host. For protocols that do not support message framing, the actual maximum size of a message that can be sent to a given address may be less than this value.

The following special message size values are defined:

Value	Meaning
0	The protocol is stream-oriented; the concept of message size is not relevant.
0xFFFFFFFF	The protocol is message-oriented, but there is no maximum message size.
lpProtocol

Points to a zero-terminated string that supplies a name for the protocol; for example, "SPX2."

See Also

EnumProtocols, socket


PROVIDOR_INFO_1
 PROVIDOR_INFO_1  QuickInfo

typedef struct _PROVIDOR_INFO_1 { // pi1

    LPTSTR pName;

    LPTSTR pEnvironment ;

    LPTSTR pDLLName ;

} PROVIDOR_INFO_1;

The PROVIDOR_INFO_1 structure identifies a print provider.

Members

pName

Points to a null-terminated string that is the name of the print provider.

pEnvironment

Points to a null-terminated environment string specifying the environment the provider dynamic-link library (DLL) is designed to run in.

pDLLName

Points to a null-terminated string that is the name of the provider DLL.

See Also

MONITOR_INFO_2


PSHNOTIFY
 PSHNOTIFY  QuickInfo

typedef struct _PSHNOTIFY {
    NMHDR hdr;

    LPARAM lParam;

} PSHNOTIFY, FAR *LPPSHNOTIFY;

PSHNOTIFY contains information for the PSN_APPLY and PSN_RESET notification messages.

Members

hdr

Notification header.

lParam

Close flag. TRUE if the OK or Cancel button is used to close the property sheet. FALSE if the Close button used.

See Also

PSN_APPLY, PSN_RESET


PUNCTUATION
 PUNCTUATION  QuickInfo  Overview  Group

typedef struct _punctuation {
    UINT   iSize;          // size of table; see below
    LPSTR  szPunctuation;  // punctuation; see below
} PUNCTUATION;

Contains information about the punctuation used in a rich edit control.

Members

iSize

Size in bytes of buffer pointed to by the szPunctuation member.

szPunctuation

Address of the buffer containing the punctuation characters.


QUERY_SERVICE_CONFIG
 QUERY_SERVICE_CONFIG  QuickInfo

typedef struct _QUERY_SERVICE_CONFIG { // qsc

    DWORD dwServiceType;

    DWORD dwStartType;

    DWORD dwErrorControl;

    LPTSTR lpBinaryPathName;

    LPTSTR lpLoadOrderGroup;

    DWORD dwTagId;

    LPTSTR lpDependencies;

    LPTSTR lpServiceStartName;

    LPTSTR lpDisplayName;

} QUERY_SERVICE_CONFIG, LPQUERY_SERVICE_CONFIG;

The QUERY_SERVICE_CONFIG structure is used by the QueryServiceConfig function to return configuration information about an installed service.

Members

dwServiceType

The value returned includes one of the following service type flags to indicate the type of service. In addition, for a SERVICE_WIN32 service, the SERVICE_INTERACTIVE_PROCESS flag might be set, indicating that the service process can interact with the desktop.

Value	Meaning
SERVICE_WIN32_OWN_PROCESS	A service type flag that indicates a Win32 service that runs in its own process.
SERVICE_WIN32_SHARE_PROCESS	A service type flag that indicates a Win32 service that shares a process with other services.
SERVICE_KERNEL_DRIVER	A service type flag that indicates a Windows NT device driver.
SERVICE_FILE_SYSTEM_DRIVER	A service type flag that indicates a Windows NT file system driver.
SERVICE_INTERACTIVE_PROCESS	A flag that indicates a Win32 service process that can interact with the desktop.
dwStartType

Specifies when to start the service. One of the following values is specified:

Value	Meaning
SERVICE_BOOT_START	Specifies a device driver started by the operating system loader. This value is valid only if the service type is SERVICE_KERNEL_DRIVER or SERVICE_FILE_SYSTEM_DRIVER.
SERVICE_SYSTEM_START	Specifies a device driver started by the IoInitSystem function. This value is valid only if the service type is SERVICE_KERNEL_DRIVER or SERVICE_FILE_SYSTEM_DRIVER.
SERVICE_AUTO_START	Specifies a device driver or Win32 service started by the service control manager automatically during system startup.
SERVICE_DEMAND_START	Specifies a device driver or Win32 service started by the service control manager when a process calls the StartService function.
SERVICE_DISABLED	Specifies a device driver or Win32 service that can no longer be started.
dwErrorControl

Specifies the severity of the error if this service fails to start during startup, and determines the action taken by the startup program if failure occurs. One of the following values can be specified:

Value	Meaning
SERVICE_ERROR_IGNORE
	The startup (boot) program logs the error but continues the startup operation.
SERVICE_ERROR_NORMAL
	The startup program logs the error and displays a message box pop-up but continues the startup operation.
SERVICE_ERROR_SEVERE
	The startup program logs the error. If the last-known good configuration is being started, the startup operation continues. Otherwise, the system is restarted with the last-known-good configuration.
SERVICE_ERROR_CRITICAL
	The startup program logs the error, if possible. If the last-known good configuration is being started, the startup operation fails. Otherwise, the system is restarted with the last-known good configuration.
lpBinaryPathName

Points to a null-terminated string that contains the fully qualified path to the service binary file.

lpLoadOrderGroup

Points to a null-terminated string that names the load ordering group of which this service is a member. If the pointer is NULL or if it points to an empty string, the service does not belong to a group. The registry has a list of load ordering groups located at:

HKEY_LOCAL_MACHINE\System
\CurrentControlSet\Control\ServiceGroupOrder.

The startup program uses this list to load groups of services in a specified order with respect to the other groups in the list. You can place a service in a group so that another service can depend on the group.

The order in which a service starts is determined by the following criteria:

1.	The order of groups in the registry's load-ordering group list. Services in groups in the load-ordering group list are started first, followed by services in groups not in the load-ordering group list and then services that do not belong to a group.

2.	The service's dependencies listed in the lpszDependencies parameter and the dependencies of other services dependent on the service.

dwTagId

Specifies a unique tag value for this service in the group specified by the lpLoadOrderGroup parameter. A value of zero indicates that the service has not been assigned a tag. You can use a tag for ordering service startup within a load order group by specifying a tag order vector in the registry located at:

HKEY_LOCAL_MACHINE\System\CurrentControlSet
\Control\GroupOrderList

Tags are only evaluated for SERVICE_KERNEL_DRIVER and SERVICE_FILE_SYSTEM_DRIVER type services that have SERVICE_BOOT_START or SERVICE_SYSTEM_START start types.

lpDependencies

Points to an array of null-separated names of services or load ordering groups that must start before this service. The array is doubly null-terminated. If the pointer is NULL or if it points to an empty string, the service has no dependencies. If a group name is specified, it must be prefixed by the SC_GROUP_IDENTIFIER (defined in the WINSVC.H file) character to differentiate it from a service name, because services and service groups share the same name space. Dependency on a service means that this service can only run if the service it depends on is running. Dependency on a group means that this service can run if at least one member of the group is running after an attempt to start all members of the group.

lpServiceStartName

Points to a null-terminated string. If the service type is SERVICE_WIN32_OWN_PROCESS or SERVICE_WIN32_SHARE_PROCESS, this name is the account name in the form of "DomainName\Username", which the service process will be logged on as when it runs. If the account belongs to the built-in domain, ".\Username" can be specified. If NULL is specified, the service will be logged on as the LocalSystem account.

If the service type is SERVICE_KERNEL_DRIVER or SERVICE_FILE_SYSTEM_DRIVER, this name is the Windows NT driver object name (that is, \FileSystem\Rdr or \Driver\Xns) which the input and output (I/O) system uses to load the device driver. If NULL is specified, the driver is run with a default object name created by the I/O system based on the service name.

lpDisplayName

Points to a null-terminated string that is to be used by user interface programs to identify the service. This string has a maximum length of 256 characters. The name is case-preserved in the service control manager. Display name comparisons are always case-insensitive.

Remarks

The configuration information for a service is initially specified when the service is created by a call to the CreateService function. The information can be modified by calling the ChangeServiceConfig function.

See Also

ChangeServiceConfig, CreateService, QueryServiceConfig, StartService


QUERY_SERVICE_LOCK_STATUS
 QUERY_SERVICE_LOCK_STATUS  QuickInfo

typedef struct _QUERY_SERVICE_LOCK_STATUS { // qsls

    DWORD fIsLocked;

    LPTSTR lpLockOwner;

    DWORD dwLockDuration;

} QUERY_SERVICE_LOCK_STATUS, * LPQUERY_SERVICE_LOCK_STATUS ;

The QUERY_SERVICE_LOCK_STATUS structure is used by the QueryServiceLockStatus function to return information about the lock status of a service control manager database.

Members

fIsLocked

Specifies whether the database is locked. If this member is nonzero, the database is locked. If it is zero, the database is unlocked.

lpLockOwner

Points to a null-terminated string containing the name of the user who acquired the lock.

dwLockDuration

Specifies the time, in seconds, since the lock was first acquired.

See Also

QueryServiceLockStatus


RASAMB
 RASAMB  QuickInfo  Overview  Group

typedef  struct  _RASAMB {

    DWORD    dwSize;

    DWORD    dwError;

    TCHAR    szNetBiosError[ NETBIOS_NAME_LEN + 1 ];

     BYTE     bLana;

} RASAMB;

The RASAMB structure contains the result of a remote access server (RAS) Authentication Message Block (AMB) projection operation.

The RasGetProjectionInfo function returns a RASAMB data structure when its rasprojection parameter has the value RASP_Amb.

Members

dwSize

Specifies the size of the structure, in bytes. Before calling the RasGetProjectionInfo function, set this member to sizeof(RASAMB). The function can then determine the version of the RASAMB data structure that the caller of RasGetProjectionInfo is expecting. This allows backward compatibility for compiled applications if there are future enhancements to the data structure.

dwError

Contains the result of the PPP control protocol negotiation. A value of zero indicates success. A nonzero value indicates failure, and is the actual fatal error that occurred during the control protocol negotiation, the error that prevented the projection from completing successfully.

szNetBiosError

If dwError has the value ERROR_NAME_EXISTS_ON_NET, the szNetBiosError field contains a zero-terminated string that is the NetBIOS name that caused the conflict. For other values of dwError, this field contains the null string.

bLana

Identifies the NetBIOS network adapter identifier, or LANA, on which the remote access connection was established. This member contains the value 0xFF if a connection was not established.

Remarks

The AMB protocol is used with servers that were released before PPP was adopted as the primary framing protocol; for example, Windows NT 3.1 and OS/2 1.3 RAS servers.

See Also

RasGetProjectionInfo, RASPROJECTION


RASCONN
 RASCONN  QuickInfo  Overview  Group

typedef struct _RASCONN {

    DWORD     dwSize;

    HRASCONN  hrasconn;

    TCHAR     szEntryName[RAS_MaxEntryName + 1];

#if (WINVER >= 0x400)

    CHAR      szDeviceType[ RAS_MaxDeviceType + 1 ];

    CHAR      szDeviceName[ RAS_MaxDeviceName + 1 ];

#endif

} RASCONN ;

The RASCONN structure provides information about a remote access connection. The RasEnumConnections function returns an array of RASCONN structures.

Members

dwSize

Specifies the size, in bytes, of the RASCONN structure.

hrasconn

Specifies the remote access connection. This handle is used in other remote access API calls.

szEntryName

A string that specifies the phonebook entry used to establish the remote access connection. If the connection was established using an empty entry name, this string consists of a "." followed by the connection phone number.

szDeviceType

A null-terminated string that contains the device type through which the connection is made.

Windows NT: This member is defined only if you build with the WINVER constant defined as 0x400 or greater. By default, the SDK for Windows NT 3.51 defines WINVER as less than 0x400.

szDeviceName

A null-terminated string that contains the device name through which the connection is made.

Windows NT: This member is defined only if you build with the WINVER constant defined as 0x400 or greater.

See Also

RasEnumConnections, RasGetConnectStatus


RASCONNSTATUS
 RASCONNSTATUS  QuickInfo  Overview  Group

typedef struct _RASCONNSTATUS {

    DWORD         dwSize;

    RASCONNSTATE  rasconnstate;

    DWORD         dwError;

    TCHAR         szDeviceType[RAS_MaxDeviceType + 1];

    TCHAR         szDeviceName[RAS_MaxDeviceName + 1];

} RASCONNSTATUS;

A RASCONNSTATUS structure describes the current status of a remote access connection. It is returned by the RasGetConnectStatus function.

Members

dwSize

Specifies the structure size, in bytes.

rasconnstate

Specifies a RASCONNSTATE enumerator value that indicates the current state of the RasDial connection process; that is, the piece of the RasDial process that is currently executing.

Two state values are especially significant:

State	Meaning
RASCS_Connected	Indicates that the connection has completed successfully.
RASCS_Disconnected	Indicates that the connection has failed.
dwError

If nonzero, indicates the reason for failure. The value is one of the error values from the RAS header file or one of ERROR_NOT_ENOUGH_MEMORY or ERROR_INVALID_HANDLE.

szDeviceType

A string that specifies the type of the current device, if available. For example, common device types supported by RAS remote access service are "modem",  "pad", "switch", "isdn", or "null".

szDeviceName

A string that specifies the name of the current device, if available. This would be the name of the modem — for example, "Hayes Smartmodem 2400"; the name of the PAD, for example "US Sprint"; or the name of a switch device, for example "Racal-Guardata".

See Also

RasGetConnectStatus, RasDial, RASCONNSTATE


RASDIALEXTENSIONS
 RASDIALEXTENSIONS  QuickInfo  Overview  Group

typedef  struct  _RASDIALEXTENSIONS {

    DWORD    dwSize;

    DWORD    dwfOptions;

    HWND    hwndParent;

    DWORD    reserved;

} RASDIALEXTENSIONS;

The RASDIALEXTENSIONS structure contains information about extended features of the RasDial function. You can enable one or more of these extensions by passing a pointer to a RASDIALEXTENSIONS structure when you call RasDial. If you do not pass a pointer to a RASDIALEXTENSIONS structure to RasDial, RasDial uses the default settings that are noted following.

Members

dwSize

Specifies the size of this structure, in bytes. Set this member to sizeof(RASDIALEXTENSIONS). This indicates the version of the structure.

dwfOptions

A set of bit flags that specify RasDial extensions. The following bit flags are defined; you must set all undefined bits to zero:

Value	Description
RDEOPT_UsePrefixSuffix	If this bit flag is one, RasDial uses the prefix and suffix that is in the RAS phonebook. If this bit flag is zero, RasDial ignores the prefix and suffix that is in the RAS phonebook. If no phonebook entry name is specified in the call to RasDial, the actual value of this bit flag is ignored, and it is assumed to be zero.
RDEOPT_PausedStates	If this bit flag is one, RasDial accepts paused states. Examples of paused states are terminal mode, retry logon, change password, and set callback number. If this bit flag is zero, RasDial reports a fatal error if it enters a paused state.
RDEOPT_IgnoreModemSpeaker	If this bit flag is one, RasDial ignores the modem speaker setting that is in the RAS phonebook, and uses the setting specified by the RDEOPT_SetModemSpeaker bit flag. If this bit flag is zero, RasDial uses the modem speaker setting that is in the RAS phonebook, and ignores the setting specified by the RDEOPT_SetModemSpeaker bit flag. If no phonebook entry name is specified in the call to RasDial, the choice is between using a default setting or the setting specified by the RDEOPT_SetModemSpeaker bit flag. The default setting is used if RDEOPT_IgnoreModemSpeaker is zero. The setting specified by RDEOPT_SetModemSpeaker is used if RDEOPT_IgnoreModemSpeaker is one.
RDEOPT_SetModemSpeaker	If this bit flag is one, and RDEOPT_IgnoreModemSpeaker is one, RasDial sets the modem speaker on.  If this bit flag is zero, and RDEOPT_IgnoreModemSpeaker is one, RasDial sets the modem speaker off. If RDEOPT_IgnoreModemSpeaker is zero, RasDial ignores the value of RDEOPT_SetModemSpeaker, and sets the modem speaker based on the RAS phonebook setting or the default setting.
RDEOPT_IgnoreSoftwareCompression	If this bit flag is one, RasDial ignores the software compression setting that is in the RAS phonebook, and uses the setting specified by the RDEOPT_SetSoftwareCompression bit flag. If this bit flag is zero, RasDial uses the software compression setting that is in the RAS phonebook, and ignores the setting specified by the RDEOPT_SetSoftwareCompression bit flag. If no phonebook entry name is specified in the call to RasDial, the choice is between using a default setting or the setting specified by the RDEOPT_SetSoftwareCompression bit flag. The default setting is used if RDEOPT_IgnoreSoftwareCompression is zero. The setting specified by RDEOPT_SetSoftwareCompression is used if RDEOPT_IgnoreSoftwareCompression is one.
RDEOPT_SetSoftwareCompression	If this bit flag is one, and RDEOPT_IgnoreSoftwareCompression is one, RasDial uses software compression.  If this bit flag is zero, and RDEOPT_IgnoreSoftwareCompression is one, RasDial does not use software compression. If RDEOPT_IgnoreSoftwareCompression is zero, RasDial ignores the value of RDEOPT_SetSoftwareCompression, and sets the software compression state based on the RAS phonebook setting or the default setting.
The default value for each of these bit flags is zero.

hwndParent

Handle to a parent window that a security DLL can use for dialog box creation and centering.

Note that this is not the window that receives RasDial progress notifications.

This member is optional; it is not required when no security DLL is defined.

The default value for this member is NULL.

reserved

This member is reserved for future use. It must be set to zero.

See Also

RasDial


RASDIALPARAMS
 RASDIALPARAMS  QuickInfo  Overview  Group

typedef struct _RASDIALPARAMS {

   DWORD  dwSize;

   TCHAR  szEntryName[RAS_MaxEntryName + 1];

   TCHAR  szPhoneNumber[RAS_MaxPhoneNumber + 1];

   TCHAR  szCallbackNumber[RAS_MaxCallbackNumber + 1];

   TCHAR  szUserName[UNLEN + 1];

   TCHAR  szPassword[PWLEN + 1];

   TCHAR  szDomain[DNLEN + 1] ;

} RASDIALPARAMS;

The RASDIALPARAMS structure contains parameters used by RasDial to establish a remote access connection.

Members

dwSize

Specifies the structure size, in bytes.

szEntryName

Specifies a string containing the phonebook entry to use to establish the connection. An empty string ("") specifies a simple modem connection on the first available modem port, in which case a non-empty szPhoneNumber must be provided.

szPhoneNumber

Specifies a string containing an overriding phone number. An empty string ("") indicates that the phonebook entry's phone number should be used. If szEntryName is "", szPhoneNumber cannot be "".

szCallbackNumber

Specifies a string containing a callback phone number. An empty string ("") indicates that callback should not be used. This string is ignored unless the user has "Set By Caller" callback permission on the RAS server. An asterisk indicates that the number stored in the phonebook should be used for callback.

szUserName

Specifies a string containing the user's user name. This string is used to authenticate the user's access to the remote access server.

szPassword

Specifies a string containing the user's password. This string is used to authenticate the user's access to the remote access server.

szDomain

Specifies a string containing the domain on which authentication is to occur. An empty string ("") specifies the domain in which the remote access server is a member. An asterisk specifies the domain stored in the phonebook for the entry.

Remarks

The szUserName and szPassword strings are used to authenticate the user's access to the remote access server.

Windows NT

RAS does not actually log the user onto the network. The user does this in the usual manner, for example, by logging on with cached credentials prior to making the connection or by using CTRL+ALT+DEL, after the RAS connection is established.

If both the szUserName and the szPassword members are empty strings (""), RAS uses the user name and password of the currently logged-on user for authentication.

Windows 95

RAS uses the szUserName and szPassword strings to log the user onto the network.

Windows 95 cannot get the password of the currently logged-on user, so if both the szUserName and the szPassword members are empty strings (""), RAS leaves the user name and password empty during authentication.

See Also

RasDial


RASENTRYNAME
 RASENTRYNAME  QuickInfo  Overview  Group

typedef struct _RASENTRYNAME {

    DWORD  dwSize;

    TCHAR  szEntryName[RAS_MaxEntryName + 1];

}RASENTRYNAME;

The RASENTRYNAME structure contains an entry name from a remote access phonebook. The RasEnumEntries function returns an array of these structures.

Members

dwSize

Specifies the structure size, in bytes.

szEntryName

Specifies a string containing the name of a remote access phonebook entry.

See Also

RasEnumEntries


RASPPPIP
 RASPPPIP  QuickInfo  Overview  Group

typedef  struct  _RASPPPIP {

    DWORD    dwSize;

    DWORD    dwError;

    TCHAR    szIpAddress[ RAS_MaxIpAddress + 1 ];

} RASPPPIP;

The RASPPPIP structure contains the result of a PPP Internet Protocol (IP) projection operation.

The RasGetProjectionInfo function returns a RASPPPIP data structure when its rasprojection parameter has the value RASP_PppIp.

Members

dwSize

Specifies the size of the structure, in bytes. Before calling the RasGetProjectionInfo function, set this member to indicate the version of the RASPPPIP structure that you are using. For information about earlier versions of this structure, see the following Remarks section.

dwError

Contains the result of the PPP control protocol negotiation. A value of zero indicates success. A nonzero value indicates failure, and is the actual fatal error that occurred during the control protocol negotiation, the error that prevented the projection from completing successfully.

szIpAddress

Contains a zero-terminated string that is the client's IP address on the RAS connection. This address string has the form a.b.c.d; for example, "11.101.237.71".

szServerIpAddress

Contains a null-terminated string that is the IP address of the remote PPP peer (that is, the server's IP address). This string is in "a.b.c.d" form. PPP does not require that servers provide this address, but Windows NT servers will consistently return the address anyway. Other PPP vendors may not provide the address. If the address is not available, this member returns an empty string, "".

Remarks

The szServerIpAddress member was added to the RASPPPIP structure beginning with Windows NT 3.51 and the initial release of Windows 95. Beginning with these systems, RasGetProjectionInfo will support both the current form of the structure and the old form without the szServerIpAddress member. Use the dwSize member to indicate which version you are using.

For earlier versions of Windows NT, RasGetProjectionInfo will return ERROR_INVALID_SIZE if dwSize specifies the current structure size. To retrieve PPP IP information from older systems, dwSize must specify the size of the old structure without the szServerIpAddress member.

See Also

RasGetProjectionInfo, RASPROJECTION


RASPPPIPX
 RASPPPIPX  QuickInfo  Overview  Group

typedef  struct  _RASPPPIPX {

    DWORD    dwSize;

    DWORD    dwError;

    TCHAR    szIpxAddress[ RAS_MaxIpxAddress + 1 ];

} RASPPPIPX;

The RASPPPIPX structure contains the result of a PPP Internetwork Packet Exchange (IPX) projection operation.

The RasGetProjectionInfo function returns a RASPPPIPX data structure when its rasprojection parameter has the value RASP_PppIpx.

Members

dwSize

Specifies the size of the structure, in bytes. Before calling the RasGetProjectionInfo function, set this member to sizeof(RASPPPIPX). The function can then determine the version of the RASPPPIPX data structure that the caller of RasGetProjectionInfo is expecting. This allows backwards compatibility for compiled applications if there are future enhancements to the data structure.

dwError

Contains the result of the PPP control protocol negotiation. A value of zero indicates success. A nonzero value indicates failure, and is the actual fatal error that occurred during the control protocol negotiation, the error that prevented the projection from completing successfully.

szIpxAddress

Contains a zero-terminated string that is the client's IPX address on the RAS connection. This address string has the form net.node; for example, "1234ABCD.12AB34CD56EF".

See Also

RasGetProjectionInfo, RASPROJECTION


RASPPPNBF
 RASPPPNBF  QuickInfo  Overview  Group

typedef  struct  _RASPPPNBF {

    DWORD    dwSize;

    DWORD    dwError;

    DWORD    dwNetBiosError;

    TCHAR    szNetBiosError[ NETBIOS_NAME_LEN + 1 ];

    TCHAR    szWorkstationName[ NETBIOS_NAME_LEN + 1 ];

    BYTE     bLana;

} RASPPPNBF;

The RASPPPNBF structure contains the result of a PPP NetBEUI Framer (NBF) projection operation.

The RasGetProjectionInfo function returns a RASPPPNBF data structure when its rasprojection parameter has the value RASP_PppNbf.

Members

dwSize

Specifies the size of the structure, in bytes. Before calling the RasGetProjectionInfo function, set this member to sizeof(RASPPPNBF). The function can then determine the version of the RASPPPNBF data structure that the caller of RasGetProjectionInfo is expecting. This allows backwards compatibility for compiled applications if there are future enhancements to the data structure.

dwError

Contains the result of the PPP control protocol negotiation. A value of zero indicates success. A nonzero value indicates failure, and is the actual fatal error that occurred during the control protocol negotiation, the error that prevented the projection from completing successfully.

dwNetBiosError

If dwError has the value ERROR_SERVER_NOT_RESPONDING or ERROR_NETBIOS_ERROR, the dwNetBiosError field contains the NetBIOS error that occurred. For other values of dwError, this field contains zero.

szNetBiosError

If dwError has the value ERROR_NAME_EXISTS_ON_NET, the szNetBiosError field contains a zero-terminated string that is the NetBIOS name that caused the conflict. For other values of dwError, this field contains the null string.

szWorkStationName

Contains a zero-terminated string that is the local workstation's computer name. This unique computer name is the closest NetBIOS equivalent to a client's NetBEUI address on a remote access connection.

bLana

Identifies the NetBIOS network adapter identifier, or LANA, on which the remote access connection was established. This member contains the value 0xFF if a connection was not established.

See Also

RasGetProjectionInfo, RASPROJECTION


RASTERIZER_STATUS
 RASTERIZER_STATUS  QuickInfo

typedef struct _RASTERIZER_STATUS {    // rs

    short nSize;

    short wFlags;

    short nLanguageID;

} RASTERIZER_STATUS;

The RASTERIZER_STATUS structure contains information about whether TrueType is installed. This structure is filled when an application calls the GetRasterizerCaps function.

Members

nSize

Specifies the size, in bytes, of the RASTERIZER_STATUS structure.

wFlags

Specifies whether at least one TrueType font is installed and whether TrueType is enabled. This value is TT_AVAILABLE, TT_ENABLED, or both if TrueType is on the system.

nLanguageID

Specifies the language in the system's SETUP.INF file.

See Also

GetRasterizerCaps


REASSIGN_BLOCKS
 REASSIGN_BLOCKS  QuickInfo  Overview  Group

typedef struct _REASSIGN_BLOCKS {

    WORD   Reserved;

    WORD   Count;

    DWORD BlockNumber[1];

} REASSIGN_BLOCKS ;

The REASSIGN_BLOCKS structure provides disk-block reassignment data. It is a variable-length structure whose last member is an array of block numbers to be reassigned.

Members

Reserved

This member is reserved. Do not use it. Set it to zero.

Count

Specifies the number of blocks to be reassigned. This is the number of elements that are in the BlockNumber member array.

BlockNumber

An array of Count block numbers, one for each block to be reassigned.

Remarks

The DeviceIoControl function uses a REASSIGN_BLOCKS structure as input to an IOCTL_DISK_REASSIGN_BLOCKS device input and output control operation.

See Also

DeviceIoControl, IOCTL_DISK_REASSIGN_BLOCKS


RECT
 RECT  QuickInfo

typedef struct _RECT {    // rc

    LONG left;

    LONG top;

    LONG right;

    LONG bottom;

} RECT;

The RECT structure defines the coordinates of the upper-left and lower-right corners of a rectangle.

Members

left

Specifies the x-coordinate of the upper-left corner of the rectangle.

top

Specifies the y-coordinate of the upper-left corner of the rectangle.

right

Specifies the x-coordinate of the lower-right corner of the rectangle.

bottom

Specifies the y-coordinate of the lower-right corner of the rectangle.

Remarks

When RECT is passed to the FillRect function, the rectangle is filled up to, but not including, the right column and bottom row of pixels. This structure is identical to the RECTL structure.

See Also

FillRect, RECTL, SMALL_RECT


RECTL
 RECTL  QuickInfo

typedef struct _RECTL { // rcl

    LONG left;

    LONG top;

    LONG right;

    LONG bottom;

} RECTL;

The RECTL structure defines the coordinates of the upper-left and lower-right corners of a rectangle.

Members

left

Specifies the x-coordinate of the upper-left corner of the rectangle.

top

Specifies the y-coordinate of the upper-left corner of the rectangle.

right

Specifies the x-coordinate of the lower-right corner of the rectangle.

bottom

Specifies the y-coordinate of the lower-right corner of the rectangle.

Remarks

When RECTL is passed to the FillRect function, the rectangle is filled up to, but not including, the right column and bottom row of pixels. This structure is identical to the RECT structure.

See Also

FillRect, RECT, SMALL_RECT


REGISTERWORD
 REGISTERWORD  QuickInfo

typedef struct tagREGISTERWORD {

    LPTSTR  lpReading;

    LPTSTR  lpWord;

} REGISTERWORD;

The REGISTERWORD structure contains reading information or a word to register. You can pass this structure to the ImmConfigureIME function to have the information or word appear as an initial value in the configuration dialog box of the input method editor.

Members

lpReading

Pointer to the reading information for the word to register. If the reading information is not needed, it can be NULL.

lpWord

Pointer to the word to register. If a word is not needed, it can be NULL.

See Also

ImmConfigureIME


REMOTE_NAME_INFO
 REMOTE_NAME_INFO  QuickInfo

typedef struct _REMOTE_NAME_INFO { /* rni */

    LPTSTR  lpUniversalName;

    LPTSTR  lpConnectionName;

    LPTSTR  lpRemainingPath;

} REMOTE_NAME_INFO;

The REMOTE_NAME_INFO data structure contains path and name information about a network resource. The structure contains a member that points to a Universal Naming Convention (UNC) name string for the resource, and two members that point to additional network connection information strings.

Members

lpUniversalName

Points to a zero-terminated UNC name string.

lpConnectionName

Points to a zero-terminated string that is the name of a network connection.

lpRemainingPath

Points to a zero-terminated UNC name string.

Remarks

The REMOTE_NAME_INFO data structure contains a pointer to a Universal Naming Convention (UNC) name string. UNC names look like this:

\\servername\sharename\path\file

You can pass the REMOTE_NAME_INFO structure's lpConnectionName member to the WNetAddConnection2 function as the lpRemoteName member of the NETRESOURCE structure pointed to by lpNetResource. This lets you connect a local device to a network resource. You can then append the string pointed to by the lpRemainingPath member to the local device string, and pass the resulting string to Win32 functions that use a drive-based path.

See Also

WNetAddConnection2, UNIVERSAL_NAME_INFO


REOBJECT
 REOBJECT  QuickInfo  Overview  Group

typedef struct _reobject {
    DWORD  cbStruct;           // size of structure in bytes
    LONG   cp;                 // character position of object
    CLSID  clsid;              // class ID of object
    LPOLEOBJECT      poleobj;  // OLE object interface
    LPSTORAGE        pstg;     // associated storage interface
    LPOLECLIENTSITE  polesite; // associated client site interface
    SIZEL  sizel;              // size of object (may be 0,0)
    DWORD  dvaspect;           // display aspect to use
    DWORD  dwFlags;            // object status flags
    DWORD  dwUser;             // user-defined value
} REOBJECT;

The REOBJECT structure contains information about an object.

Members

cbStruct

Size, in bytes, of this structure.

cp

Character position of the object.

clsid

Class identifier of the object.

poleobj

Points to an instance of the IOleObject interface for the object.

pstg

Points to an instance of the IStorage interface. This is the storage object associated with the object.

polesite

Points to an instance of the IOleClientSite interface. This is the object's client site in the rich edit control. This address must have been obtained from the IRichEditOle::GetClientSite method.

sizel

SIZEL structure specifying the size of the object. A 0,0 on insert indicates that an object is free to determine its size until the modify flag is turned off.

dvAspect

Display aspect to use.

dwFlags

Object status flags. Can be a combination of the following values:

Value	Meaning
REO_BELOWBASELINE	Object sits below the baseline of the surrounding text; the default is to sit on the baseline.
REO_DONTUSEPALETTE	Prevents creation and realization of a half-tone palette before rendering the object. Applies to 32-bit platforms only.
REO_DYNAMICSIZE	Object always determines its extents and may change despite the modify flag being turned off.
REO_GETMETAFILE	The rich edit control retrieved the metafile from the object to correctly determine the object's extents. This flag can be read but not set.
REO_HILITED	Object is currently highlighted to indicate selection. Occurs when focus is in the control and REO_SELECTED is set. This flag can be read but not set.
REO_INPLACEACTIVE	Object is currently in place active. This flag can be read but not set.
REO_INVERTEDSELECT	Object is to be drawn entirely inverted when selected; the default is to be drawn with a border.
REO_LINK	Object is a link. This flag can be read but not set.
REO_LINKAVAILABLE	Object is a link and is believed to be available. This flag can be read but not set.
REO_OPEN	Object is currently open in its server. This flag can be read but not set.
REO_RESIZABLE	Object may be resized.
REO_SELECTED	Object is currently selected in the rich edit control. This flag can be read but not set.
REO_STATIC	Object is a static object. This flag can be read but not set.
dwUser

Reserved for user-defined values.

See Also

IOleClientSite, IOleObject, IRichEditOle::GetClientSite, IStorage


REPASTESPECIAL
 REPASTESPECIAL  QuickInfo  Overview  Group

typedef struct _repastespecial {
    DWORD  dwAspect;  // display aspect for object
    DWORD  dwParam;   // aspect data
} REPASTESPECIAL;

Contains information identifying whether the display aspect of a pasted object should be based on the content of the object or the icon that represent the object.

Members

dwAspect

Display aspect. Can be DVASPECT_CONTENT if the aspect of the pasted object is based on the content of the object, or DVASPECT_ICON if the aspect is based on the icon view of the object.

dwParam

Aspect data. If dwAspect is DVASPECT_ICON, this member contains the handle to the metafile with the icon view of the object.


REQRESIZE [New - Windows NT]
 REQRESIZE  QuickInfo  Overview  Group

[New - Windows NT]

typedef struct _reqresize {

    NMHDR nmhdr;

    RECT rc;

} 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.

Members

nmhdr

Notification header.

rc

Requested new size.

See Also

EN_REQUESTRESIZE


RGBQUAD
 RGBQUAD  QuickInfo

typedef struct tagRGBQUAD { // rgbq

    BYTE    rgbBlue;

    BYTE    rgbGreen;

    BYTE    rgbRed;

    BYTE    rgbReserved;

} RGBQUAD;

The RGBQUAD structure describes a color consisting of relative intensities of red, green, and blue.

Members

rgbBlue

Specifies the intensity of blue in the color.

rgbGreen

Specifies the intensity of green in the color.

rgbRed

Specifies the intensity of red in the color.

rgbReserved

Reserved; must be zero.

Remarks

The bmiColors member of the BITMAPINFO structure consists of an array of RGBQUAD structures.

See Also

BITMAPINFO, CreateDIBitmap, CreateDIBSection, GetDIBits, SetDIBits, SetDIBitsToDevice, StretchDIBits


RGBTRIPLE
 RGBTRIPLE  QuickInfo

typedef struct tagRGBTRIPLE { // rgbt

    BYTE rgbtBlue;

    BYTE rgbtGreen;

    BYTE rgbtRed;

} RGBTRIPLE;

The RGBTRIPLE structure describes a color consisting of relative intensities of red, green, and blue. The bmciColors member of the BITMAPCOREINFO structure consists of an array of RGBTRIPLE structures.

Members

rgbtBlue

Specifies the intensity of blue in the color.

rgbtGreen

Specifies the intensity of green in the color.

rgbtRed

Specifies the intensity of red in the color.

See Also

BITMAPCOREINFO


RGNDATA
 RGNDATA  QuickInfo

typedef struct _RGNDATA { // rgnd

    RGNDATAHEADER rdh;

    char          Buffer[1];

} RGNDATA;

The RGNDATA structure contains a header and an array of rectangles that compose a region. The rectangles are sorted top to bottom, left to right. They do not overlap.

Members

rdh

Specifies a RGNDATAHEADER structure. The members of this structure specify the type of region (whether it is rectangular or trapezoidal), the number of rectangles that make up the region, the size of the buffer that contains the rectangle structures, and so on.

Buffer

Specifies an arbitrary-size buffer that contains the RECT structures that make up the region.

See Also

RECT, RGNDATAHEADER


RGNDATAHEADER
 RGNDATAHEADER  QuickInfo

typedef struct _RGNDATAHEADER { // rgndh

    DWORD dwSize;

    DWORD iType;

    DWORD nCount;

    DWORD nRgnSize;

    RECT  rcBound;

} RGNDATAHEADER;

The RGNDATAHEADER structure describes the data returned by the GetRegionData function.

Members

dwSize

Specifies the size, in bytes, of the header.

iType

Specifies the type of region. This value must be RDH_RECTANGLES.

nCount

Specifies the number of rectangles that make up the region.

nRgnSize

Specifies the size of the buffer required to receive the RECT structure that specifies the coordinates of the rectangles that make up the region. If the size is not known, this member can be zero.

rcBound

Specifies a bounding rectangle for the region.

See Also

GetRegionData, RECT, RGNDATA


RIP_INFO
 RIP_INFO  QuickInfo

typedef struct _RIP_INFO { /* ri */

    DWORD  dwError;

    DWORD  dwType;

} RIP_INFO;

The RIP_INFO structure contains the error and address, format, and length, in bytes, of a debugging string.

dwError

Specifies the error that caused the RIP debug event. For more information about exception handling, see Errors.

dwType

Specifies additional information about the type of error that caused the RIP debug event. This may be one of the following values:

Value	Meaning
SLE_ERROR	Indicates that invalid data was passed to the function that failed. This caused the application to fail.
SLE_MINORERROR	Indicates that invalid data was passed to the function, but the error probably will not cause the application to fail.
SLE_WARNING	Indicates that potentially invalid data was passed to the function, but the function completed processing.
0	Indicates that only dwError was set.
See Also

DEBUG_EVENT


SCROLLINFO
 SCROLLINFO  QuickInfo

typedef struct tagSCROLLINFO {  // si

    UINT cbSize;

    UINT fMask;

    int  nMin;

    int  nMax;

    UINT nPage;

    int  nPos;

    int  nTrackPos;

}   SCROLLINFO;

typedef SCROLLINFO FAR *LPSCROLLINFO;

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).

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, and SIF_RANGE.
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 parameter contains the scroll box position.
SIF_RANGE	The nMin and nMax members contain the minimum and maximum values for the scrolling range.
nMin

Specifies the minimum scrolling position.

nMax

Specifies the maximum scrolling position.

nPage

Specifies the page size. A scroll bar uses this value to determine the appropriate size of the proportional scroll box.

nPos

Specifies the position of the scroll box.

nTrackPos

Specifies the immediate position of a scroll box that the user is dragging. An application can retrieve this value while processing the SB_THUMBTRACK notification message. An application cannot set the immediate scroll position; the SetScrollInfo function ignores this member.

See Also

SBM_GETSCROLLINFO, SBM_SETSCROLLINFO, GetScrollInfo, SetScrollInfo


SECURITY_ATTRIBUTES
 SECURITY_ATTRIBUTES  QuickInfo

typedef struct _SECURITY_ATTRIBUTES { // sa

    DWORD  nLength;

    LPVOID lpSecurityDescriptor;

    BOOL   bInheritHandle;

} SECURITY_ATTRIBUTES;

The SECURITY_ATTRIBUTES structure contains the security descriptor for an object and specifies whether the handle retrieved by specifying this structure is inheritable.

Members

nLength

Specifies the length, in bytes, of this structure. This value is to be set to the size of the SECURITY_ATTRIBUTES structure.

lpSecurityDescriptor

Points to a security descriptor for the object that controls the sharing of it. If NULL is specified for this member, the object may be assigned the default security descriptor of the calling process.

bInheritHandle

Specifies whether the returned handle is inherited when a new process is created. If this member is TRUE, the new process inherits the handle.

Remarks

A pointer to a SECURITY_ATTRIBUTES structure is used as a parameter in most kernel and window-management functions in the Win32 API that return a handle of an object.

See Also

SECURITY_DESCRIPTOR


SECURITY_DESCRIPTOR
 SECURITY_DESCRIPTOR  QuickInfo

typedef PVOID PSECURITY_DESCRIPTOR;

The SECURITY_DESCRIPTOR structure contains the security information associated with an object. Applications use this structure to set and query an object's security status.

Applications are not to modify the SECURITY_DESCRIPTOR structure directly. For creating and manipulating a security descriptor, use the functions listed in the See Also section.

Remarks

A security descriptor includes information that specifies the following components of an object's security:

•	An owner (SID)

•	A primary group (SID)

•	A discretionary ACL

•	A system ACL

•	Qualifiers for the preceding items

Security descriptors use access-control lists (ACLs) and security identifiers (SIDs) to specify the information in this list.

A security descriptor can be in absolute or self-relative form. In self-relative form, all members of the structure are located contiguously in memory. In absolute form, the structure only contains pointers to the members.

See Also

GetSecurityDescriptorControl, GetSecurityDescriptorDacl, GetSecurityDescriptorGroup, GetSecurityDescriptorLength, GetSecurityDescriptorOwner, GetSecurityDescriptorSacl, InitializeSecurityDescriptor, IsValidSecurityDescriptor, SetSecurityDescriptorDacl, SetSecurityDescriptorGroup, SetSecurityDescriptorOwner, SetSecurityDescriptorSacl


SECURITY_DESCRIPTOR_CONTROL
 SECURITY_DESCRIPTOR_CONTROL  QuickInfo

typedef WORD SECURITY_DESCRIPTOR_CONTROL;

The SECURITY_DESCRIPTOR_CONTROL structure contains a set of bit flags that qualify the meaning of a security descriptor or its individual members.

Each security descriptor has an associated SECURITY_DESCRIPTOR_CONTROL structure. Applications can use the Win32 API functions to set and retrieve a security descriptor's SECURITY_DESCRIPTOR_CONTROL values. These functions are listed in the See Also section.

The following constants are defined for setting and retrieving SECURITY_DESCRIPTOR_CONTROL bit flags:

Value	Meaning
SE_OWNER_DEFAULTED	Instead of the original provider of the security descriptor, a default mechanism provided the security descriptor's owner security identifier (SID). This can affect the treatment of the SID with respect to inheritance of an owner. This flag is ignored if the owner member is NULL. The SetSecurityDescriptorOwner function sets this flag.
SE_GROUP_DEFAULTED	Instead of the the original provider of the security descriptor, a default mechanism provided the security descriptor's group SID. This can affect the treatment of the SID with respect to inheritance of a primary group. This flag is ignored if the group member is NULL. The SetSecurityDescriptorGroup function sets this flag.
SE_DACL_PRESENT	The security descriptor contains a discretionary access-control list (ACL). If this flag is set and the discretionary ACL is NULL, an empty ACL is being explicitly specified. An empty ACL has a size but no access-control entries (ACEs). A NULL ACL has no pointer to an ACL. This flag allows functions to determine whether a security descriptor points to a NULL ACL or no ACL at all. The SetSecurityDescriptorDacl function sets this flag.
SE_DACL_DEFAULTED	Instead of the the original provider of the security descriptor, a default mechanism provided the discretionary ACL. This can affect the treatment of the ACL with respect to inheritance of an ACL. If the SE_DACL_PRESENT flag is not set, this flag is ignored. The SetSecurityDescriptorDacl function sets this flag.
SE_SACL_PRESENT	The security descriptor contains a system ACL. If this flag is set and the Sacl member is NULL, an empty ACL is being explicitly specified. This flag allows functions to determine whether a security descriptor points to a NULL ACL or no ACL at all. The SetSecurityDescriptorSacl function sets this flag.
SE_SACL_DEFAULTED	Instead of the the original provider of the security descriptor, a default mechanism provided the ACL. This can affect the treatment of the ACL with respect to inheritance of an ACL. If the SE_SACL_PRESENT flag is not set, this flag is ignored. The SetSecurityDescriptorSacl function sets this flag.
SE_SELF_RELATIVE	The security descriptor is in self-relative form and all members of the security descriptor are contiguous in memory. All pointer members are expressed as offsets from the beginning of the security descriptor. This form is useful for treating security descriptors as opaque structures for transmission in a communications protocol or for storage on secondary media.
See Also

GetSecurityDescriptorControl, GetSecurityDescriptorDacl, GetSecurityDescriptorGroup, GetSecurityDescriptorOwner, GetSecurityDescriptorSacl, SetSecurityDescriptorDacl, SetSecurityDescriptorGroup, SetSecurityDescriptorOwner, SetSecurityDescriptorSacl


SECURITY_INFORMATION
 SECURITY_INFORMATION  QuickInfo

typedef DWORD SECURITY_INFORMATION;

The SECURITY_INFORMATION structure identifies the object-related security information being set or queried. This security information includes:

•	The owner of an object

•	The primary group of an object

•	The discretionary access-control list (ACL) of an object

•	The system ACL of an object

Each item of security information is designated by a bit flag. The following values specify the bits:

Value	Meaning
OWNER_SECURITY_INFORMATION	Indicates the owner identifier of the object is being referenced.
GROUP_SECURITY_INFORMATION	Indicates the primary group identifier of the object is being referenced.
DACL_SECURITY_INFORMATION	Indicates the discretionary ACL of the object is being referenced.
SACL_SECURITY_INFORMATION	Indicates the system ACL of the object is being referenced.
See Also

GetFileSecurity, GetKernelObjectSecurity, GetPrivateObjectSecurity, GetUserObjectSecurity, SetFileSecurity, SetKernelObjectSecurity, SetPrivateObjectSecurity, SetUserObjectSecurity


SECURITY_QUALITY_OF_SERVICE
 SECURITY_QUALITY_OF_SERVICE  QuickInfo

typedef struct _SECURITY_QUALITY_OF_SERVICE { // sqos

    DWORD Length;

    SECURITY_IMPERSONATION_LEVEL ImpersonationLevel;

    SECURITY_CONTEXT_TRACKING_MODE ContextTrackingMode;

    BOOLEAN EffectiveOnly;

} SECURITY_QUALITY_OF_SERVICE;

The SECURITY_QUALITY_OF_SERVICE data structure contains information used to support client impersonation. A client can specify this information when it connects to a server; the information determines whether or not the server may impersonate the client, and if so, to what extent.

Members

Length

Specifies the size, in bytes, of this structure.

ImpersonationLevel

Specifies what the server may be told about the client, and how the server may represent, or impersonate, the client. Security impersonation levels govern the degree to which a server process can act on behalf of a client process. This member is a SECURITY_IMPERSONATION_LEVEL enumeration type value.

ContextTracking Mode

Specifies whether the server is to be given a snapshot of the client's security context (called static tracking), or is to be continually updated to track changes to the client's security context (called dynamic tracking). The value SECURITY_STATIC_TRACKING specifies static tracking, and the value SECURITY_DYNAMIC_TRACKING specifies dynamic tracking. Not all communications mechanisms support dynamic tracking; those that do not will default to static tracking.

Effective Only

Specifies whether or not the server may enable or disable privileges and groups that the client's security context may include.

See Also

SECURITY_IMPERSONATION_LEVEL


SELCHANGE [New - Windows NT]
 SELCHANGE  QuickInfo  Overview  Group

[New - Windows NT]

typedef struct _selchange {

    NMHDR nmhdr;

    CHARRANGE chrg;

    WORD seltyp;

} SELCHANGE;

The SELCHANGE stucture contains information associated with an EN_SELCHANGE notification message. A rich edit control sends this notification to its parent window when the current selection changes.

Members

nmhdr

Notification header.

chrg

New selection range.

seltyp

Value specifying the contents of the new selection. This member is SEL_EMPTY if the selection is empty or one or more of the following values:

Value	Contents of the selection
SEL_TEXT	Text
SEL_OBJECT	At least one OLE object
SEL_MULTICHAR	More than one character of text
SEL_MULTIOBJECT	More than one OLE object
See Also

EN_SELCHANGE


SERIALKEYS [New - Windows NT]
 SERIALKEYS  QuickInfo  Overview  Group

[New - Windows NT]

typedef struct tagSERIALKEYS {     // sk

    DWORD cbSize;

    DWORD dwFlags;

    LPSTR lpszActivePort;

    LPSTR lpszPort;

    DWORD iBaudRate;

    DWORD iPortState;

} SERIALKEYS, FAR* LPSERIALKEYS;

The SERIALKEYS structure contains information about the SerialKeys accessibility feature, which interprets data from a communication aid attached to a serial port as commands causing the system to simulate keyboard and mouse input.

Members

cbSize

Specifies the structure size, in bytes.

dwFlags

Specifies a combination of the following values:

Value	Meaning
SERKF_ACTIVE	The SerialKeys feature is currently receiving input on the serial port specified by lpszPort.
SERKF_AVAILABLE	The SerialKeys feature is available.
SERKF_INDICATOR	A visual indicator is displayed when the SerialKeys feature is on. This value is not currently used and is ignored.
SERKF_SERIALKEYSON	The SerialKeys feature is on.
lpszActivePort

Points to a string that contains the name of the serial port that receives input from the communication aid when the SerialKeys feature is on. If no port is being used, this member is NULL. If this member is "Auto", the system watches all unused serial ports for input from communication aids.

lpszPort

Reserved; must be NULL.

iBaudRate

Specifies the baud rate setting for the serial port specified by the lpszActivePort member. This member should be set to one of the CBR_ values defined in the Windows header files. If lpszActivePort is NULL, this member is zero.

iPortState

Specifies the state of the port specified by the lpszActivePort member. If lpszActivePort is NULL, iPortState is zero; otherwise, it is one of the following values:

Value	Meaning
0	All input on this port is ignored by the SerialKeys feature.
1	Input on this port is watched for SerialKeys activation sequences when no other application has the port open.
2	All input on this port is treated as SerialKeys commands.
Remarks

An application uses this structure when calling the SystemParametersInfo function with the SPI_GETSERIALKEYS or SPI_SETSERIALKEYS value. When using SPI_GETSERIALKEYS, an application must specify the cbSize, lpszActivePort, and lpszPort members of the SERIALKEYS structure; the SystemParametersInfo function fills the remaining members. An application must specify all structure members when using the SPI_SETSERIALKEYS value.

See Also

SystemParametersInfo


SERVICE_ADDRESS [New - Windows NT]
 SERVICE_ADDRESS  QuickInfo  Overview  Group

[New - Windows NT]

typedef struct _SERVICE_ADDRESS {

    DWORD   dwAddressType;

    DWORD   dwAddressFlags;

    DWORD   dwAddressLength;

    DWORD   dwPrincipalLength;

    BYTE   *lpAddress;

    BYTE   *lpPrincipal;

} SERVICE_ADDRESS;

The SERVICE_ADDRESS structure contains address information for a service. The structure can accomodate many types of interprocess communications (IPC) mechanisms and their address forms, including remote procedure calls (RPCs), named pipes, and sockets.

Members

dwAddressType

Specifies the address family that the socket address pointed to by lpAddress belongs to.

dwAddressFlags

A set of bit flags that specify properties of the address. The following bit flags are defined:

Value	Meaning
SERVICE_ADDRESS_FLAG_RPC_CN	If this bit flag is set, the service supports connection-oriented RPC over this transport protocol.
SERVICE_ADDRESS_FLAG_RPC_DG	If this bit flag is set, the service supports datagram-oriented RPC over this transport protocol.
SERVICE_ADDRESS_FLAG_RPC_NB	If this bit flag is set, the service supports NetBIOS RPC over this transport protocol.
dwAddressLength

Specifies the size, in bytes, of the address.

dwPrincipalLength

This member is reserved for future use. It must be zero.

lpAddress

Points to a socket address of the appropriate type.

lpPrincipal

This member is reserved for future use. It must be NULL.

See Also

SERVICE_ADDRESSES, SERVICE_INFO


SERVICE_ADDRESSES [New - Windows NT]
 SERVICE_ADDRESSES  QuickInfo  Overview  Group

[New - Windows NT]

typedef struct _SERVICE_ADDRESSES {

    DWORD   dwAddressCount;

    SERVICE_ADDRESS   Addresses[1];

} SERVICE_ADDRESSES;

The SERVICE_ADDRESSES structure contains an array of SERVICE_ADDRESS data structures.

Members

dwAddressCount

Specifies the number of SERVICE_ADDRESS structures in the Addresses array.

Addresses

An array of SERVICE_ADDRESS data structures. Each SERVICE_ADDRESS structure contains information about a network service address.

See Also

SERVICE_ADDRESS, SERVICE_INFO


SERVICE_INFO [New - Windows NT]
 SERVICE_INFO  QuickInfo  Overview  Group

[New - Windows NT]

typedef struct _SERVICE_INFO {

    LPGUID   lpServiceType;

    LPTSTR   lpServiceName;

    LPTSTR   lpComment;

    LPTSTR   lpLocale;

    DWORD    dwDisplayHint;

    DWORD    dwVersion;

    DWORD    dwTime;

    LPTSTR   lpMachineName;

    LPSERVICE_ADDRESSES lpServiceAddress;

    BLOB ServiceSpecificInfo;

} SERVICE_INFO;

The SERVICE_INFO structure contains information about a network service or a network service type.

Members

lpServiceType

Points to a GUID that is the type of the network service.

lpServiceName

Points to a zero-terminated string that is the name of the network service.

If you are calling the SetService function with the dwNameSpace parameter set to NS_DEFAULT, the network service name must be a common name A common name is what the network service is commonly known as. An example of a common name for a network service is "My SQL Server".

If you are calling the SetService function with the dwNameSpace parameter set to a specific service name, the network service name can be a common name or a distinguished name. A distinguished name distinguishes the service to a unique location with a directory service. An example of a distinguished name for a network service is "MS\\SYS\\NT\\DEV\\My SQL Server". The

lpComment

Points to a zero-terminated string that is a comment or description for the network service. For example, "Used for development upgrades."

lpLocale

Points to a zero-terminated string that contains locale information.

dwDisplayHint

Specifies a hint as to how to display the network service in a network browsing user interface. This can be one of the following values:

Value	Meaning
RESOURCEDISPLAYTYPE_DOMAIN	Display the network service as a domain.
RESOURCEDISPLAYTYPE_FILE	Display the network service as a file.
RESOURCEDISPLAYTYPE_GENERIC	The method used to display the object does not matter.
RESOURCEDISPLAYTYPE_GROUP	Display the network service as a group.
RESOURCEDISPLAYTYPE_SERVER	Display the network service as a server.
RESOURCEDISPLAYTYPE_SHARE	Display the network service as a sharepoint.
RESOURCEDISPLAYTYPE_TREE	Display the network service as a tree.
dwVersion

Specifies version information for the network service. The high word of this value specifies a major version number. The low word of this value specifies a minor version number.

dwTime

This member is reserved for future use. It must be set to zero.

lpMachineName

Points to a zero-terminated string that is the name of the computer on which the network service is running.

lpServiceAddress

Points to a SERVICE_ADDRESSES structure that contains an array of SERVICE_ADDRESS structures. Each SERVICE_ADDRESS structure contains information about a network service address.

A network service can call the getsockname function to determine the local address of the system.

ServiceSpecificInfo

A BLOB structure that specifies service-defined information.

Note that, in general, the data pointed to by the BLOB structure's pBlobData member must not contain any pointers. That is because only the network service knows the format of the data; copying the data without such knowledge would lead to pointer invalidation. If the data pointed to by pBlobData contains variable-sized elements, offsets from pBlobData can be used to indicate the location of those elements. There is one exception to this general rule: when pBlobData points to a SERVICE_TYPE_INFO_ABS structure. This is possible because both the SERVICE_TYPE_INFO_ABS structure, and any SERVICE_TYPE_VALUE_ABS structures it contains are predefined, and thus their formats are known to the operating system.

See Also

BLOB, GetService, NS_SERVICE_INFO, SetService, SERVICE_ADDRESS, SERVICE_ADDRESSES, SERVICE_TYPE_INFO_ABS, SERVICE_TYPE_VALUE_ABS


SERVICE_STATUS
 SERVICE_STATUS  QuickInfo

typedef struct _SERVICE_STATUS { // ss

    DWORD dwServiceType;

    DWORD dwCurrentState;

    DWORD dwControlsAccepted;

    DWORD dwWin32ExitCode;

    DWORD dwServiceSpecificExitCode;

    DWORD dwCheckPoint;

    DWORD dwWaitHint;

} SERVICE_STATUS, *LPSERVICE_STATUS;

The SERVICE_STATUS structure contains information about a service. The ControlService, EnumDependentServices, EnumServicesStatus, and QueryServiceStatus functions use this structure to return information about a service. A service uses this structure in the SetServiceStatus function to report its current status to the service control manager.

Members

dwServiceType

The value returned includes one of the following service type flags to indicate the type of service. In addition, for a SERVICE_WIN32 service, the SERVICE_INTERACTIVE_PROCESS flag might be set, indicating that the service process can interact with the desktop.

Value	Meaning
SERVICE_WIN32_OWN_PROCESS	A service type flag that indicates a Win32 service that runs in its own process.
SERVICE_WIN32_SHARE_PROCESS	A service type flag that indicates a Win32 service that shares a process with other services.
SERVICE_KERNEL_DRIVER	A service type flag that indicates a Windows NT device driver.
SERVICE_FILE_SYSTEM_DRIVER	A service type flag that indicates a Windows NT file system driver.
SERVICE_INTERACTIVE_PROCESS	A flag that indicates a Win32 service process that can interact with the desktop.
dwCurrentState

Indicates the current state of the service. One of the following values is specified:

Value	Meaning
SERVICE_STOPPED	The service is not running.
SERVICE_START_PENDING	The service is starting.
SERVICE_STOP_PENDING	The service is stopping.
SERVICE_RUNNING	The service is running.
SERVICE_CONTINUE_PENDING	The service continue is pending.
SERVICE_PAUSE_PENDING	The service pause is pending.
SERVICE_PAUSED	The service is paused.
dwControlsAccepted

Specifies the control codes that the service will accept and process. A user interface process can control a service by specifying a control command in the ControlService function. By default, all services accept the SERVICE_CONTROL_INTERROGATE value. Any or all of the following flags can be specified to enable the other control codes.

Value	Meaning
SERVICE_ACCEPT_STOP
	The service can be stopped. This enables the SERVICE_CONTROL_STOP value.
SERVICE_ACCEPT_PAUSE_CONTINUE
	The service can be paused and continued. This enables the SERVICE_CONTROL_PAUSE and SERVICE_CONTROL_CONTINUE values.
SERVICE_ACCEPT_SHUTDOWN
	The service is notified when system shutdown occurs. This enables the system to send a SERVICE_CONTROL_SHUTDOWN value to the service. The ControlService function cannot send this control code.
dwWin32ExitCode

Specifies a Win32 error code that the service uses to report an error that occurs when it is starting or stopping. To return an error code specific to the service, the service must set this value to ERROR_SERVICE_SPECIFIC_ERROR to indicate that the dwServiceSpecificExitCode member contains the error code. The service should set this value to NO_ERROR when it is running and on normal termination.

dwServiceSpecificExitCode

Specifies a service specific error code that the service returns when an error occurs while the service is starting or stopping. This value is ignored unless the dwWin32ExitCode member is set to ERROR_SERVICE_SPECIFIC_ERROR.

dwCheckPoint

Specifies a value that the service increments periodically to report its progress during a lengthy start, stop, or continue operation. For example, the service should increment this value as it completes each step of its initialization when it is starting up. The user interface program that invoked the operation on the service uses this value to track the progress of the service during a lengthy operation. This value is not valid and should be zero when the service does not have a start, stop, or continue operation pending.

dwWaitHint

Specifies an estimate of the amount of time, in milliseconds, that the service expects a pending start, stop, or continue operation to take before the service makes its next call to the SetServiceStatus function with either an incremented dwCheckPoint value or a change in dwCurrentState. If the amount of time specified by dwWaitHint passes, and dwCheckPoint has not been incremented, or dwCurrentState has not changed, the service control manager or service control program can assume that an error has occurred.

See Also

ControlService, EnumDependentServices, EnumServicesStatus, QueryServiceStatus, SetServiceStatus


SERVICE_TABLE_ENTRY [New - Windows NT]
 SERVICE_TABLE_ENTRY  QuickInfo

[New - Windows NT]

typedef struct _SERVICE_TABLE_ENTRY { // ste

    LPTSTR lpServiceName;

    LPSERVICE_MAIN_FUNCTION lpServiceProc;

} SERVICE_TABLE_ENTRY, *LPSERVICE_TABLE_ENTRY;

The SERVICE_TABLE_ENTRY structure is used by the StartServiceCtrlDispatcher function to specify the ServiceMain function for a Win32 service that can run in the calling process.

Members

lpServiceName

Points to a null-terminated string that names a service that can run in this service process. This string is ignored if the service is installed in the service control manager database as a SERVICE_WIN32_OWN_PROCESS service type. For a SERVICE_WIN32_SHARE_PROCESS service process, this string names the service that uses the ServiceMain function pointed to by the lpServiceProc member.

lpServiceProc

Points to a ServiceMain function.

See Also

ServiceMain, StartServiceCtrlDispatcher


SERVICE_TYPE_INFO_ABS [New - Windows NT]
 SERVICE_TYPE_INFO_ABS  QuickInfo  Overview  Group

[New - Windows NT]

typedef struct _SERVICE_TYPE_INFO_ABS {

    LPTSTR                  lpTypeName;

    DWORD                   dwValueCount;

    SERVICE_TYPE_VALUE_ABS  Values[1];

} SERVICE_TYPE_INFO_ABS

The SERVICE_TYPE_INFO_ABS structure contains information about a network service type. You use a SERVICE_TYPE_INFO_ABS structure to add a network service type to a name space.

Members

lpTypeName

Points to a zero-terminated string that is the name of the network service type.  This name is the same in all name spaces, and is used by the GetTypeByName and GetNameByType functions.

dwValueCount

Specifies the number of SERVICE_TYPE_VALUE_ABS structures in the Values member array that follows dwValueCount.

Values[1]

An array of SERVICE_TYPE_VALUE_ABS structures.

Each of these structures contains information about a service type value that the operating system or network service may need when an instance of this network service type is registered with a name space.

The information in these structures may be specific to a name-space. For example, if a network service uses the SAP name space, but does not have a GUID that contains the SAP identifier (SAPID), it defines the SAPID in a SERVICE_TYPE_VALUE_ABS structure.

Remarks

When you use the SetService function to add a network service type to a name space, the SERVICE_TYPE_INFO_ABS structure is passed as the ServiceSpecificInfo BLOB member of a SERVICE_INFO structure. Although the ServiceSpecificInfo member generally should not contain pointers, an exception is made in the case of the SERVICE_TYPE_INFO_ABS and SERVICE_TYPE_VALUE_ABS structures.

See Also

SetService, SERVICE_INFO, SERVICE_TYPE_VALUE_ABS


SERVICE_TYPE_VALUE_ABS [New - Windows NT]
 SERVICE_TYPE_VALUE_ABS  QuickInfo  Overview  Group

[New - Windows NT]

typedef struct _SERVICE_TYPE_VALUE_ABS {

    DWORD   dwNameSpace;

    DWORD   dwValueType;

    DWORD   dwValueSize;

    LPTSTR  lpValueName;

    PVOID   lpValue;

} SERVICE_TYPE_VALUE_ABS

The SERVICE_TYPE_VALUE_ABS structure contains information about a network-service type value. This information may be specific to a name space.

Members

dwNameSpace

Specifies the name space, or a set of default name spaces, for which the network service type value is intended . Name-space providers will look only at values intended for their name space.

Use one of the following constants to specify a name space:

Value	Name Space
NS_DEFAULT	A set of default name spaces. The function queries each name space within this set. The set of default name spaces typically includes all the name spaces installed on the system. System administrators, however, can exclude particular name spaces from the set. NS_DEFAULT is the value that most applications should use for dwNameSpace.
NS_DNS	The Domain Name System used in the Internet for host name resolution.
NS_NETBT	The NetBIOS over TCP/IP layer. All Windows NT systems register their computer names with NetBIOS. This name space is used to convert a computer name to an IP address that uses this registration. Note that NS_NETBT may access a WINS server to perform the resolution.
NS_SAP	The Netware Service Advertising Protocol. This may access the Netware bindery if appropriate. NS_SAP is a dynamic name space that allows registration of services.
NS_TCPIP_HOSTS	Lookup value in the <systemroot>\system32\drivers\etc\hosts file.
NS_TCPIP_LOCAL	Local TCP/IP name resolution mechanisms, including comparisons against the local host name and looks up host names and IP addresses in cache of host to IP address mappings.
dwValueType

Specifies the type of the value data. You can specify one of the following types:

Value	Meaning
REG_BINARY	Binary data in any form.
REG_DWORD	A 32-bit number.
REG_MULTI_SZ	An array of null-terminated strings, terminated by two null characters.
REG_SZ	A null-terminated string.
dwValueSize

Specifies the size, in bytes, of the value data. In the case of REG_SZ and REG_MULTI_SZ string data, the terminating characters are counted as part of the size.

lpValueName

Points to a zero-terminated string that is the name of the value. This name is specific to a name space.

Several commonly used value name strings are associated with defined constants. These name strings include the following:

Constant	Name String
SERVICE_TYPE_VALUE_SAPID	"SapId"
SERVICE_TYPE_VALUE_CONN	"ConnectionOriented"
SERVICE_TYPE_VALUE_TCPPORT	"TcpPort"
SERVICE_TYPE_VALUE_UDPPORT	"UdpPort"
lpValue

Points to the value data.

Remarks

When you use the SetService function to add a network service type to a name space, a SERVICE_TYPE_INFO_ABS structure is passed as the ServiceSpecificInfo BLOB member of a SERVICE_INFO structure. Although the ServiceSpecificInfo member generally should not contain pointers, an exception is made in the case of the SERVICE_TYPE_INFO_ABS and SERVICE_TYPE_VALUE_ABS structures.

See Also

SetService, SERVICE_INFO, SERVICE_TYPE_INFO_ABS


SESSION_BUFFER
 SESSION_BUFFER  QuickInfo

typedef struct _SESSION_BUFFER { // sb

    UCHAR lsn;

    UCHAR state;

    UCHAR local_name[NCBNAMSZ];

    UCHAR remote_name[NCBNAMSZ];

    UCHAR rcvs_outstanding;

    UCHAR sends_outstanding;

} SESSION_BUFFER;

The SESSION_BUFFER structure contains information about a local network session. One or more SESSION_BUFFER structures follows a SESSION_HEADER structure when an application specifies the NCBSSTAT command in the ncb_command member of the NCB structure.

Members

lsn

Specifies the local session number.

state

Specifies the state of the session. This member can be one of the following values:

Value	Meaning
LISTEN_OUTSTANDING	The session is waiting for a call from a remote computer.
CALL_PENDING	The session is attempting to connect to a remote computer.
SESSION_ESTABLISHED	The session connected and is able to transfer data.
HANGUP_PENDING	The session is being deleted due to a command by the local user.
HANGUP_COMPLETE	The session was deleted due to a command by the local user.
SESSION_ABORTED	The session was abandoned due to a network or user problem.
local_name

Specifies the 16-byte NetBIOS name on the local computer used for this session.

remote_name

Specifies the 16-byte NetBIOS name on the remote computer used for this session.

rcvs_outstanding

Specifies the number of pending NCBRECV commands.

sends_outstanding

Specifies the number of pending NCBSEND and NCBCHAINSEND commands.

See Also

NCB, SESSION_HEADER


SESSION_HEADER
 SESSION_HEADER  QuickInfo

typedef struct _SESSION_HEADER { // sh

    UCHAR sess_name;

    UCHAR num_sess;

    UCHAR rcv_dg_outstanding;

    UCHAR rcv_any_outstanding;

} SESSION_HEADER;

The SESSION_HEADER structure contains information about a network session. This structure is pointed to by the ncb_buffer member of the NCB structure. SESSION_HEADER is followed by as many SESSION_BUFFER structures as are required to describe the current network sessions.

Members

sess_name

Specifies the name number of the session. This value corresponds to the ncb_num member of the NCB structure.

num_sess

Specifies the number of sessions that have the name specified by the sess_name member.

rcv_dg_outstanding

Specifies the number of outstanding NCBDGRECV and NCBDGRECVBC commands.

rcv_any_outstanding

Specifies the number of outstanding NCBRECVANY commands.

See Also

NCB, SESSION_BUFFER


SET_PARTITION_INFORMATION [New - Windows NT]
 SET_PARTITION_INFORMATION  QuickInfo  Overview  Group

[New - Windows NT]

typedef struct _SET_PARTITION_INFORMATION {

   BYTE PartitionType;

} SET_PARTITION_INFORMATION ;

The SET_PARTITION_INFORMATION structure provides information used to set a disk partition's type.

Members

PartitionType

Specifies the type of partition. This member can be one of the following values:

Value	Meaning
PARTITION_ENTRY_UNUSED	Entry unused.
PARTITION_FAT_12	Specifies a partition with 12-bit FAT entries.
PARTITION_XENIX_1	Specifies a Xenix type 1 partition.
PARTITION_XENIX_2	Specifies a Xenix type 2 partition.
PARTITION_FAT_16	Specifies a partition with 16-bit FAT entries.
PARTITION_EXTENDED	Specifies an extended partition entry.
PARTITION_HUGE	Specifies an MS-DOS V4 huge partition.
PARTITION_IFS	Specifies an IFS partition.
PARTITION_UNIX	Specifies a Unix partition.
VALID_NTFT	Specifies an NTFT partition.
Remarks

The DeviceIoControl function uses a SET_PARTITION_INFORMATION structure as input to an IOCTL_DISK_SET_PARTITION_INFO device input and output control operation.

See Also

DeviceIoControl, IOCTL_DISK_GET_PARTITION_INFO, IOCTL_DISK_SET_PARTITION_INFO, PARTITION_INFORMATION


SHCONTF [New - Windows 95]
 SHCONTF  QuickInfo

[New - Windows 95]

typedef enum tagSHCONTF {

    SHCONTF_FOLDERS = 32,         // for shell browser

    SHCONTF_NONFOLDERS = 64,      // for default view

    SHCONTF_INCLUDEHIDDEN = 128,  // for hidden or system objects

} SHCONTF;

Specifies an enumerated type that defines flags used with the IShellFolder::EnumObjects method.

See Also

IShellFolder::EnumObjects


SHELLEXECUTEINFO
 SHELLEXECUTEINFO  Overview  Group

typedef struct _SHELLEXECUTEINFO {   // sei

    DWORD     cbSize;

    ULONG     fMask;

    HWND      hwnd;

    LPCSTR    lpVerb;

    LPCSTR    lpFile;

    LPCSTR    lpParameters;

    LPCSTR    lpDirectory;

    int       nShow;

    HINSTANCE hInstApp;

    // Optional members

    LPVOID lpIDList;

    LPCSTR lpClass;

    HKEY   hkeyClass;

    DWORD  dwHotKey;

    HANDLE hIcon;

    HANDLE hProcess;

} SHELLEXECUTEINFO, FAR *LPSHELLEXECUTEINFO;

The SHELLEXECUTEINFO structure contains information used by the ShellExecuteEx function.

Members

cbSize

Specifies the size, in bytes, of the structure.

fMask

This is an array of flags that indicate the content and validity of the other structure members. You can specify a combination of the following values:

Value	Meaning
SEE_MASK_CLASSKEY	Use class key given by the hkeyClass member.
SEE_MASK_CLASSNAME	Use the class name given by the lpClass member.
SEE_MASK_CONNECTNETDRV	The lpFile member is a Universal Naming Convention (UNC) path of a file on a network. Validate the share and connect to a drive letter.
SEE_MASK_DOENVSUBST	Expand any environment variables specified in the string given by the lpDirectory or lpFile member.
SEE_MASK_FLAG_DDEWAIT	Wait for the DDE conversation to terminate before returning, if the ShellExecuteEx function causes a DDE conversation to start.
SEE_MASK_FLAG_NO_UI	Do not display an error message box if an error occurs.
SEE_MASK_HOTKEY	Use the hot key given by the dwHotKey member.
SEE_MASK_ICON	Use the icon given by the hIcon member.
SEE_MASK_IDLIST	Use the item identifier list given by the lpIDList member.
SEE_MASK_INVOKEIDLIST	Use the item identifier list given by the lpIDList member to invoke an application. If this member is NULL, the function creates an item identifier list and invokes the application. SEE_MASK_INVOKEIDLIST overrides SEE_MASK_IDLIST.
SEE_MASK_NOCLOSEPROCESS	Leave the process running after the ShellExecuteEx function exits. The hProcess member receives the handle of the process.
hwnd

Handle to the parent window for any message boxes that the system may produce while executing this function (for example, for error reporting).

lpVerb

Pointer to a string specifying the name of a verb. The verb specifies an action for the application to perform. This member defaults to "Open" if no verb is specified.

lpFile

Pointer to a list of null-terminated strings that specify the names of the files to open or print. The function can open an executable file or a document file. The function can print a document file. If the path is not included with a name, the current directory is assumed.

lpParameters

Pointer to a null-terminated string containing the application parameters. The parameters must be separated by spaces. To include double quotation marks, you must enclose the marks in double quotation marks, as in the following example:

sei.lpParameters = "An example: \"\"\"quoted text\"\"\"";

In this case, the application receives three parameters: An, example:, and "quoted text".

If lpFile specifies a document file, lpParameters should be NULL.

lpDirectory

Pointer to a null-terminated string that specifies the name of the working directory. If this member is not specified, the current directory is used as the working directory.

nShow

Show flags. Can be one of the SW_ values described for the ShowWindow function. If lpFile specifies an executable file, nShow specifies how the application is to be shown when it is opened. If lpFile specifies a document file, nShow should be zero.

hInstApp

Handle to the instance of the application that was started or an error value if the application could not be started. (This handle could also be the handle of a dynamic data exchange [DDE] server application.) This member is set on return. Error values can be one of the following:

Value	Meaning
SE_ERR_FNF	File not found
SE_ERR_PNF	Path not found
SE_ERR_ACCESSDENIED	Access denied
SE_ERR_OOM	Out of memory
SE_ERR_DLLNOTFOUND	Dynamic-link library not found
SE_ERR_SHARE	Cannot share open file
SE_ERR_ASSOCINCOMPLETE	File association information not complete
SE_ERR_DDETIMEOUT	DDE operation timed out
SE_ERR_DDEFAIL	DDE operation failed
SE_ERR_DDEBUSY	DDE operation busy
SE_ERR_NOASSOC	File association not available
lpIDList

Pointer to an ITEMIDLIST structure that contains an item identifier list that uniquely identifies the file to execute. Ignored if fMask is not set to SEE_MASK_IDLIST.

lpClass

Pointer to a null-terminated string specifying the name of a file class or a globally unique identifier (GUID). Ignored if fMask is not set to SEE_MASK_CLASSNAME.

hkeyClass

Handle to the registry key for the file class. Ignored if fMask is not set to SEE_MASK_CLASSKEY.

dwHotKey

Hot key to associate with the application. The low-order word is the virtual-key code, and the high-order word is a modifier flag (HOTKEYF_). For a list of modifier flags, see the description of the WM_SETHOTKEY message. Ignored if fMask is not set to SEE_MASK_HOTKEY.

hIcon

Handle to the icon for the file class. Ignored if fMask is not set to SEE_MASK_ICON.

hProcess

Handle to the newly started application. This member is set on return and is always NULL if fMask is not set to SEE_MASK_NOCLOSEPROCESS.

See Also

ITEMIDLIST, ShellExecuteEx, ShowWindow, WM_SETHOTKEY


SHFILEINFO [New - Windows 95]
 SHFILEINFO  QuickInfo

[New - Windows 95]

typedef struct _SHFILEINFO { // shfi

    HICON hIcon;

    int   iIcon;

    DWORD dwAttributes;

    char  szDisplayName[MAX_PATH];

    char  szTypeName[80];

} SHFILEINFO;

Contains information about a file object.

Members

hIcon

Handle of the icon that represents the file.

iIcon

Index of the icon image within the system image list.

dwAttributes

Array of flags that indicates the attributes of the file object. For information about the flags, see the description of the IShellFolder::GetAttributesOf method.

szDisplayName

String that contains the name of the file as it appears in the Windows shell, or path and filename of the file that contains the icon representing the file.

szTypeName

String that describes the type of the file.

Remarks

This structure is used with the SHGetFileInfo function.

See Also

IShellFolder::GetAttributesOf, SHGetFileInfo


SHFILEOPSTRUCT [New - Windows 95]
 SHFILEOPSTRUCT  QuickInfo

[New - Windows 95]

typedef struct _SHFILEOPSTRUCT { // shfos

    HWND         hwnd;

    UINT         wFunc;

    LPCSTR       pFrom;

    LPCSTR       pTo;

    FILEOP_FLAGS fFlags;

    BOOL         fAnyOperationsAborted;

    LPVOID       hNameMappings;

    LPCSTR       lpszProgressTitle;

} SHFILEOPSTRUCT, FAR *LPSHFILEOPSTRUCT;

Contains information that the SHFileOperation function uses to perform file operations.

Members

hwnd

Handle of the dialog box to use to display information about the status of the operation. If fFlags includes the FOF_CREATEPROGRESSDLG value, this parameter is the handle of the parent window for the progress dialog box created by the system.

wFunc

Operation to perform. This member can be one of the following values:

FO_COPY	Copies the files specified by pFrom to the location specified by pTo.
FO_DELETE	Deletes the files specified by pFrom (pTo is ignored).
FO_MOVE	Moves the files specified by pFrom to the location specified by pTo.
FO_RENAME	Renames the files specified by pFrom.
pFrom

Pointer to a string that contains the names of the source files.

pTo

Pointer to a string that specifies the destination for the moved, copied, or renamed file.

fFlags

Flags that control the file operation. This member can be a combination of the following values:

FOF_ALLOWUNDO	Preserves undo information, if possible.
FOF_CONFIRMMOUSE	Not implemented.
FOF_FILESONLY	Performs the operation only on files if a wildcard filename (*.*) is specified.
FOF_MULTIDESTFILES	Indicates that the pTo member specifies multiple destination files (one for each source file) rather than one directory where all source files are to be deposited.
FOF_NOCONFIRMATION	Responds with "yes to all" for any dialog box that is displayed.
FOF_NOCONFIRMMKDIR	Does not confirm the creation of a new directory if the operation requires one to be created.
FOF_RENAMEONCOLLISION	Gives the file being operated on a new name (such as "Copy #1 of...") in a move, copy, or rename operation if a file of the target name already exists.
FOF_SILENT	Does not display a progress dialog box.
FOF_SIMPLEPROGRESS	Displays a progress dialog box, but does not show the filenames.
FOF_WANTMAPPINGHANDLE	Fills in the hNameMappings member. The handle must be freed by using the SHFreeNameMappings function.
fAnyOperationsAborted

Value that receives TRUE if the user aborted any file operations before they were completed or FALSE otherwise.

hNameMappings

Handle of a filename mapping object that contains an array of SHNAMEMAPPING structures. Each structure contains the old and new path names for each file that was moved, copied, or renamed. This member is used only if fFlags includes FOF_WANTMAPPINGHANDLE.

lpszProgressTitle

Pointer to a string to use as the title for a progress dialog box. This member is used only if fFlags includes FOF_SIMPLEPROGRESS.

Remarks

If pFrom or pTo are unqualified names, the current directories are taken from the global current drive and directory settings as managed by the GetCurrentDirectory and SetCurrentDirectory functions.

The SHGetNameMappingPtr macro retrieves a pointer to the filename mapping object returned in the hNameMappings member. The SHGetNameMappingCount macro retrieves the number of SHNAMEMAPPING structures in the object.

See Also

GetCurrentDirectory, SetCurrentDirectory, SHFileOperation, SHFreeNameMappings, SHGetNameMappingPtr, SHGetNameMappingCount, SHNAMEMAPPING


SHGNO [New - Windows 95]
 SHGNO  QuickInfo

[New - Windows 95]

typedef enum tagSHGDN {

    SHGDN_NORMAL = 0,

    SHGDN_INFOLDER = 1,

    SHGDN_FORPARSING = 0x8000,

} SHGNO;

Specifies an enumerated type that defines flags used with the IShellFolder::GetDisplayNameOf and IShellFolder::SetNameOf methods.

Members

SHGDN_NORMAL

Default display name that is suitable for a file object displayed by itself, as shown in the following examples.

File system path	Corresponding display name
C:\WINDOWS\FILE.TXT	file
\\COMPUTER\SHARE	share on computer
C:\ (where drive C has the volume name My Drive)	My Drive (C)
SHGDN_INFOLDER

Display name that is suitable for a file object displayed within its respective folder, as shown in the following examples.

File system path	Corresponding display name
C:\WINDOWS\FILE.TXT	file
\\COMP\SHARE	user
C:\ (where drive C has the volume name My Drive)	My Drive (C)
SHGDN_FORPARSING

Display name that can be passed to the ParseDisplayName method of the parent folder's IShellFolder object.

File system path	Corresponding display name
C:\WINDOWS\FILE.TXT	C:\WINDOWS\FILE.TXT
\\COMP\SHARE	\\COMP\SHARE
C:\ (where drive C has the volume name My Drive)	C:\
See Also

IShellFolder::GetDisplayNameOf, IShellFolder::SetNameOf, ParseDisplayName


SHITEMID [New - Windows 95]
 SHITEMID  QuickInfo

[New - Windows 95]

typedef struct _SHITEMID {       // mkid

    USHORT cb;       // size of identifier, including cb itself

    BYTE   abID[1];  // variable length item identifier

} SHITEMID, * LPSHITEMID;

typedef const SHITEMID  * LPCSHITEMID;

Defines an item identifier.


SHNAMEMAPPING [New - Windows 95]
 SHNAMEMAPPING  QuickInfo

[New - Windows 95]

typedef struct _SHNAMEMAPPING { // shnm

    LPSTR pszOldPath; // address of old path name

    LPSTR pszNewPath; // pointer to new path name

    int   cchOldPath; // number of characters in old path name

    int   cchNewPath; // number of characters in new path name

} SHNAMEMAPPING, FAR *LPSHNAMEMAPPING;

Contains the old and new path names for each file that was moved, copied, or renamed by the SHFileOperation function.

See Also

SHFileOperation


SID
 SID  QuickInfo

typedef PVOID PSID;

The SID structure is a variable-length structure used to uniquely identify users or groups. SID stands for security identifier.

Applications are not to modify the SID structure directly. To create and manipulate a security identifier, use the functions listed in the See Also section.

See Also

AllocateAndInitializeSid, CopySid, EqualSid, FreeSid, GetLengthSid, GetSidIdentifierAuthority, GetSidLengthRequired, GetSidSubAuthority, GetSidSubAuthorityCount, InitializeSid, IsValidSid, LookupAccountName, LookupAccountSid


SID_AND_ATTRIBUTES
 SID_AND_ATTRIBUTES  QuickInfo

typedef struct _SID_AND_ATTRIBUTES { // saa

    PSID  Sid;

    DWORD Attributes;

} SID_AND_ATTRIBUTES ;

The SID_AND_ATTRIBUTES structure represents a security identifier (SID) and its attributes. SIDs are used to uniquely identify users or groups.

Members

Sid

Points to a SID structure.

Attributes

Specifies attributes of the SID. This value contains up to 32 one-bit flags. Its meaning depends on the definition and use of the SID.

Remarks

A group is represented by a SID. SIDs have attributes that indicate whether they are currently enabled, disabled, or mandatory, and how they are used. A SID_AND_ATTRIBUTES structure can represent a SID whose attributes change frequently. For example, it is used to represent groups in the TOKEN_GROUPS structure.

See Also

SID, TOKEN_GROUPS, TOKEN_USER


SID_IDENTIFIER_AUTHORITY
 SID_IDENTIFIER_AUTHORITY  QuickInfo

typedef struct _SID_IDENTIFIER_AUTHORITY { // sia

    BYTE Value[6];

} SID_IDENTIFIER_AUTHORITY ;

The SID_IDENTIFIER_AUTHORITY structure represents the top-level authority of a security identifier (SID).

Members

Value

An array of six bytes specifying a SID's top-level authority.

Remarks

The identifier authority value identifies the agency that issued the SID. Some identifier authorities are predefined:

Identifier authority	Value
SECURITY_NULL_SID_AUTHORITY	0
SECURITY_WORLD_SID_AUTHORITY	1
SECURITY_LOCAL_SID_AUTHORITY	2
SECURITY_CREATOR_SID_AUTHORITY	3
SECURITY_NT_AUTHORITY	5
A SID must contain a top-level authority and at least one relative identifier (RID) value.

See Also

AllocateAndInitializeSid, GetSidIdentifierAuthority, InitializeSid, SID


SINGLE_LIST_ENTRY
 SINGLE_LIST_ENTRY  QuickInfo

typedef struct _SINGLE_LIST_ENTRY { // sle

    struct _SINGLE_LIST_ENTRY *Next;

} SINGLE_LIST_ENTRY;

The SINGLE_LIST_ENTRY structure is available for any entry in a single-linked list.

Members

Next

Points to the next entry in a single-linked list.

Remarks

This structure can be used as the beginning of a single-linked list or as any subsequent entry in the list.


SIZE
 SIZE  QuickInfo

typedef struct tagSIZE { // siz

    LONG cx;

    LONG cy;

} SIZE;

The SIZE structure specifies the width and height of a rectangle.

Members

cx

Specifies the rectangle's width.

cy

Specifies the rectangle's height.

Remarks

The rectangle dimensions stored in this structure may correspond to viewport extents, window extents, text extents, bitmap dimensions, or the aspect-ratio filter for some extended functions.

See Also

GetAspectRatioFilterEx, GetBitmapDimensionEx, GetTextExtentPoint32, GetViewportExtEx, GetWindowExtEx, ScaleViewportExtEx, ScaleWindowExtEx, SetBitmapDimensionEx, SetViewportExtEx, SetWindowExtEx


SMALL_RECT
 SMALL_RECT  QuickInfo

typedef struct _SMALL_RECT { // srct

    SHORT Left;

    SHORT Top;

    SHORT Right;

    SHORT Bottom;

} SMALL_RECT;

The SMALL_RECT structure defines the coordinates of the upper left and lower right corners of a rectangle.

Members

Left

Specifies the x-coordinate of the upper left corner of the rectangle.

Top

Specifies the y-coordinate of the upper left corner of the rectangle.

Right

Specifies the x-coordinate of the lower right corner of the rectangle.

Bottom

Specifies the y-coordinate of the lower right corner of the rectangle.

Remarks

This structure is used by console functions to specify rectangular areas of console screen buffers, where the coordinates specify the rows and columns of screen-buffer character cells.

See Also

RECT, RECTL


SOUNDSENTRY
 SOUNDSENTRY  QuickInfo  Overview  Group

typedef struct tagSOUNDSENTRY {     // ss

    UINT cbSize;

    DWORD dwFlags;

    DWORD iFSTextEffect;

    DWORD iFSTextEffectMSec;

    DWORD iFSTextEffectColorBits;

    DWORD iFSGrafEffect;

    DWORD iFSGrafEffectMSec;

    DWORD iFSGrafEffectColor;

    DWORD iWindowsEffect;

    DWORD iWindowsEffectMSec;

    LPTSTR lpszWindowsEffectDLL;

    DWORD iWindowsEffectOrdinal;

} SOUNDSENTRY, *LPSOUNDSENTRY;

The SOUNDSENTRY structure contains information about the SoundSentry accessibility feature. When the SoundSentry feature is on, the computer displays a visual indication only when a sound is generated.

Windows 95: The visual indication is displayed when a sound is generated through the computer's internal speaker.

Windows NT The visual indication is displayed when a sound is generated through either the multimedia sound services or through the computer's speaker.

Members

cbSize

Specifies the size, in bytes, of this structure.

dwFlags

A set of bit flags that specify properties of the SoundSentry feature. The following bit-flag values are defined:

Value	Meaning
SSF_AVAILABLE	If this flag is set, the SoundSentry feature is available.
SSF_SOUNDSENTRYON	If this flag is set, the SoundSentry feature is on.
iFSTextEffect

Windows 95: Specifies the visual signal to present when a text-mode application generates a sound while running in a full-screen virtual machine. This member can be one of the following values:

Value	Meaning
SSTF_BORDER	Flash the screen border (that is, the overscan area), which is unavailable on some displays.
SSTF_CHARS	Flash characters in the corner of the screen.
SSTF_DISPLAY	Flash the entire display.
SSTF_NONE	No visual signal.

Windows NT: This member is reserved for future use. It must be set to zero.

iFSTextEffectMSec

Windows 95: Specifies the duration, in milliseconds, of the visual signal that is displayed when a full-screen, text-mode application generates a sound.

Wndows NT: This member is reserved for future use. It must be set to zero.

iFSTextEffectColorBits

Windows 95: Specifies the RGB value of the color to be used when displaying the visual signal shown when a full-screen, text-mode application generates a sound.

Windows NT: This member is reserved for future use. It must be set to zero.

iFSGrafEffect

Windows 95: Specifies the visual signal to present when a graphics-mode application generates a sound while running in a full-screen virtual machine. This member can be one of the following values:

Value	Meaning
SSGF_DISPLAY	No visual signal.
SSGF_NONE	Flash the entire display.

Windows NT: This member is reserved for future use. It must be set to zero.

iFSGrafEffectMSec

Windows 95: Specifies the duration, in milliseconds, of the visual signal that is displayed when a full-screen, graphics-mode application generates a sound.

Windows NT: This member is reserved for future use. It must be set to zero.

iFSGrafEffectColor

Windows 95: Specifies the RGB value of the color to be used when displaying the visual signal shown when a full-screen, graphics-mode application generates a sound.

Windows NT: This member is reserved for future use. It must be set to zero.

iWindowsEffect

Specifies the visual signal to display when a sound is generated by a Windows-based application or an MS-DOS application running in a window. This member can be one of the following values:

Value	Meaning
SSWF_CUSTOM	Windows 95 only: Call the SoundSentryProc routine exported by the DLL specified by the iFSWindowsEffectDLL member.
SSWF_DISPLAY	Flash the entire display.
SSWF_NONE	No visual signal.
SSWF_TITLE	Flash the title bar of the active window.
SSWF_WINDOW	Flash the active window.
iWindowsEffectMSec

Windows 95: Specifies the duration, in milliseconds, of the visual signal that is displayed when a Windows-based application (or a non-Windows-based application running in a window) generates a sound.

Windows NT: This member is reserved for future use. It must be set to zero.

lpszWindowsEffectDLL

Windows 95: Points to the buffer that contains the name of the DLL that contains a SoundSentryProc callback function. The length of the name must not exceed the value of MAX_PATH. This member is NULL if no DLL is used. When retrieving information about the SoundSentry feature, the size of the buffer must be equal to, or larger than, the value of MAX_PATH.

Windows NT: This member is reserved for future use. It must be set to NULL.

iWindowsEffectOrdinal

This member is reserved for future use on both platforms. It must be set to zero.

Remarks

An application uses a SOUNDSENTRY structure when calling the SystemParametersInfo function with the wAction parameter set to SPI_GETSOUNDSENTRY or SPI_SETSOUNDSENTRY. When using SPI_GETSOUNDSENTRY, an application must specify the cbSize member of the SOUNDSENTRY structure; the SystemParametersInfo function fills the remaining members. An application must specify the cbSize, dwFlags, and iWindowsEffect members when using the SPI_SETSOUNDSENTRY value.

See Also

SoundSentryProc, SystemParametersInfo


STARTUPINFO
 STARTUPINFO  QuickInfo

typedef struct _STARTUPINFO { // si

    DWORD   cb;

    LPTSTR  lpReserved;

    LPTSTR  lpDesktop;

    LPTSTR  lpTitle;

    DWORD   dwX;

    DWORD   dwY;

    DWORD   dwXSize;

    DWORD   dwYSize;

    DWORD   dwXCountChars;

    DWORD   dwYCountChars;

    DWORD   dwFillAttribute;

    DWORD   dwFlags;

    WORD    wShowWindow;

    WORD    cbReserved2;

    LPBYTE  lpReserved2;

    HANDLE  hStdInput;

    HANDLE  hStdOutput;

    HANDLE  hStdError;

} STARTUPINFO, *LPSTARTUPINFO;

The STARTUPINFO structure is used with the CreateProcess function to specify main window properties if a new window is created for the new process. For graphical user interface (GUI) processes, this information affects the first window created by the CreateWindow function. For console processes, this information affects the console window if a new console is created for the process. A process can use the GetStartupInfo function to retrieve the STARTUPINFO structure specified when the process was created.

Members

cb

Specifies the size, in bytes, of the structure.

lpReserved

Reserved. Set this member to NULL before passing the structure to CreateProcess.

lpDesktop

Windows 95: Ignore this member.

Windows NT: Points to a zero-terminated string that specifies either the name of the desktop only or the name of both the window station and desktop for this process. A backslash in the string pointed to by lpDesktop indicates that the string includes both desktop and window station names. Otherwise, the lpDesktop string is interpreted as a desktop name. If lpDesktop is NULL, the new process inherits the window station and desktop of its parent process.

lpTitle

For console processes, this is the title displayed in the title bar if a new console window is created. If NULL, the name of the executable file is used as the window title instead. This parameter must be NULL for GUI or console processes that do not create a new console window.

dwX, dwY

Ignored unless dwFlags specifies STARTF_USEPOSITION. Specifies the x and y offsets, in pixels, of the upper left corner of a window if a new window is created. The offsets are from the upper left corner of the screen. For GUI processes, the specified position is used the first time the new process calls CreateWindow to create an overlapped window if the x parameter of CreateWindow is CW_USEDEFAULT.

dwXSize, dwYSize

Ignored unless dwFlags specifies STARTF_USESIZE. Specifies the width (dwXSize) and height (dwYSize), in pixels, of the window if a new window is created. For GUI processes, this is used only the first time the new process calls CreateWindow to create an overlapped window if the nWidth parameter of CreateWindow is CW_USEDEFAULT.

dwXCountChars, dwYCountChars

Ignored unless dwFlags specifies STARTF_USECOUNTCHARS. For console processes, if a new console window is created, dwXCountChars specifies the screen buffer width in character columns, and dwYCountChars specifies the screen buffer height in character rows. These values are ignored in GUI processes.

dwFillAttribute

Ignored unless dwFlags specifies STARTF_USEFILLATTRIBUTE. For console processes, specifies the initial text and background colors if a new console window is created. These values are ignored in GUI processes.

dwFlags

This is a bit field that determines whether certain STARTUPINFO members are used when the process creates a window. Any combination of the following values can be specified:

Value	Meaning
STARTF_USESHOWWINDOW	If this value is not specified, the wShowWindow member is ignored.
STARTF_USEPOSITION	If this value is not specified, the dwX and dwY members are ignored.
STARTF_USESIZE	If this value is not specified, the dwXSize and dwYSize members are ignored.
STARTF_USECOUNTCHARS	If this value is not specified, the dwXCountChars and dwYCountChars members are ignored.
STARTF_USEFILLATTRIBUTE	If this value is not specified, the dwFillAttribute member is ignored.
STARTF_FORCEONFEEDBACK	If this value is specified, the cursor is in feedback mode for two seconds after CreateProcess is called. If during those two seconds the process makes the first GUI call, the system gives five more seconds to the process. If during those five seconds the process shows a window, the system gives five more seconds to the process to finish drawing the window.
	The system turns the feedback cursor off after the first call to GetMessage, regardless of whether the process is drawing.
	For more information on feedback, see the following Remarks section.
STARTF_FORCEOFFFEEDBACK	If specified, the feedback cursor is forced off while the process is starting. The normal cursor is displayed. For more information on feedback, see the following Remarks section.
STARTF_SCREENSAVER	If specified, the system will treat the application as a screen saver:
	• The system allows the application to initialize at the foreground priority of the priority class passed to the CreateProcess function. For more information on process priorities, see Scheduling Priorities .
	• When the application checks for input using the GetMessage or PeekMessage function for the first time, the system changes it to the idle priority class. That lets background applications get priority over it.
	• When the user moves the mouse or presses a key, the system gives the application the foreground priority of the priority class originally passed to the CreateProcess function.
	Creating a screen saver with NORMAL_PRIORITY_CLASS lets the screen saver initialize and terminate over other normal priority applications.
STARTF_USESTDHANDLES	If this value is specified, sets the standard input of the process, standard output, and standard error handles to the handles specified in the hStdInput, hStdOutput, and hStdError members of the STARTUPINFO structure. The CreateProcess function's fInheritHandles parameter must be set to TRUE for this to work properly.
	If this value is not specified, the hStdInput, hStdOutput, and hStdError members of the STARTUPINFO structure are ignored.
wShowWindow

Ignored unless dwFlags specifies STARTF_USESHOWWINDOW. For GUI processes, wShowWindow specifies the default value the first time ShowWindow is called, if the nCmdShow parameter of ShowWindow is SW_SHOWDEFAULT. The wshowWindow member can be any of the SW_ constants defined in WINUSER.H.

In earlier versions of Windows, the WinMain function had an nCmdShow parameter that applications were encouraged to pass to the CreateWindow or ShowWindow function. The nCmdShow parameter is no longer available through WinMain. Now applications are encouraged to use SW_SHOWDEFAULT as the default ShowWindow command, in which case, ShowWindow uses the wShowWindow member of the STARTUPINFO structure of the process.

cbReserved2

Reserved; must be zero.

lpReserved2

Reserved; must be NULL.

hStdInput

Ignored unless dwFlags specifies STARTF_USESTDHANDLES. Specifies a handle that will be used as the standard input handle of the process if STARTF_USESTDHANDLES is specified.

hStdOutput

Ignored unless dwFlags specifies STARTF_USESTDHANDLES. Specifies a handle that will be used as the standard output handle of the process if STARTF_USESTDHANDLES is specified.

hStdError

Ignored unless dwFlags specifies STARTF_USESTDHANDLES. Specifies a handle that will be used as the standard error handle of the process if STARTF_USESTDHANDLES is specified.

Remarks

If a GUI process is being started and neither STARTF_FORCEONFEEDBACK or STARTF_FORCEOFFFEEDBACK is specified, the process feedback cursor is used. A GUI process is one whose subsystem is specified as "windows."

See Also

CreateProcess, CreateWindow, GetMessage, GetStartupInfo, PeekMessage, ShowWindow, WinMain


STICKYKEYS
 STICKYKEYS  QuickInfo  Overview  Group

typedef struct tagSTICKYKEYS {     // sk

    DWORD cbSize;

    DWORD dwFlags;

} STICKYKEYS, *LPSTICKYKEYS;

The STICKYKEYS structure contains information about the StickyKeys accessibility feature. When the StickyKeys feature is on, the user can press a modifier key (SHIFT, CTRL, or ALT) and then another key in sequence rather than at the same time, to enter shifted (modified) characters and other key combinations.

Members

cbSize

Specifies the size, in bytes, of this structure.

dwFlags

A set of bit-flags that specify properties of the StickyKeys feature. The following bit-flag values are defined:

Value	Meaning
SKF_AUDIBLEFEEDBACK	If this flag is set, the system plays a sound when the user latches, locks, or releases modifier keys using the StickyKeys feature.
SKF_AVAILABLE	If this flag is set, the StickyKeys feature is available.
SKF_CONFIRMHOTKEY	Windows 95 only: A confirmation dialog appears when the StickyKeys feature is activated by using the hot key.
SKF_HOTKEYACTIVE	If this flag is set, the user can turn the StickyKeys feature on and off by pressing the SHIFT key five times.
SKF_HOTKEYSOUND	If this flag is set, the system plays a siren sound when the user turns the StickyKeys feature on or off by using the hot key.
SKF_INDICATOR	Windows 95 only: A visual indicator should be displayed when the StickyKeys feature is on.
SKF_STICKYKEYSON	If this flag is set, the StickyKeys feature is on.
SKF_TRISTATE	If this flag is set, pressing a modifier key twice in a row locks down the key until the user presses it a third time.
SKF_TWOKEYSOFF	If this flag is set, releasing a modifier key that has been pressed in combination with any other key turns off the StickyKeys feature.
Remarks

An application uses a STICKYKEYS structure when calling the SystemParametersInfo function with the wAction parameter set to SPI_GETSTICKYKEYS or SPI_SETSTICKYKEYS. When using SPI_GETSTICKYKEYS, an application must specify the cbSize member of the STICKYKEYS structure; the SystemParametersInfo function fills the remaining members. You must specify all structure members when using the SPI_SETSTICKYKEYS value.

See Also

SystemParametersInfo


STRRET
 STRRET  QuickInfo

typedef struct _STRRET { // str

    UINT uType;

    union

    {

        LPWSTR pOleStr;        // pointer to OLE string to free

        UINT   uOffset;        // offset into item identifier list

        char   cStr[MAX_PATH]; // buffer to receive the display name

    } DUMMYUNIONNAME;

} STRRET, *LPSTRRET;

Contains strings returned from IShellFolder methods, such as GetDisplayNameOf.

Member

uType

Value that specifies the desired format of the string. This member can be one of the following values:

STRRET_CSTR	The string is returned in cStr.
STRRET_OFFSET	The string is located at uOffset bytes from the beginning of the item identifier list.
STRRET_WSTR	The string is at the address pointed to by pOleStr.
Remarks

The system may or may not provide the display name in the desired format. When IShellFolder::GetDisplayNameOf returns, the uType member indicates the format.

See Also

IShellFolder::GetDisplayNameOf


String
 String  QuickInfo

String {

    WCHAR  szKey[];

    BYTE   Padding[];

    String Value[];

} String;

The String structure depicts the organization of data in a file-version resource. This structure is not a true C data 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® Win32® Software Development Kit (SDK).

The String structure contains a string that describes a specific aspect of a file.

Members

szKey

Specifies an arbitrary 7-bit ASCII English string. The szKey member can be one of the following values:

String	Description
Comments	Value contains any additional information that should be displayed for diagnostic purposes. This string is optional and can be of an arbitrary length.
CompanyName	Value identifies the company that produced the file. For example, "Microsoft Corporation" or "Standard Microsystems Corporation, Inc." This string is required.
FileDescription	Value 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". This string is required.
FileVersion	Value identifies the version of this file. For example, Value could be "3.00A" or "5.00.RC2". This string is required.
InternalName	Value identifies the file's internal name, if one exists. For example, this string would contain the module name for Windows dynamic-link libraries (DLLs), a virtual device name for Windows virtual devices, or a device name for MS-DOS device drivers. This string is required.
LegalCopyright	Value 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. This string is optional. In English, this string should be in the format "Copyright Microsoft Corp. 1990−1994".
LegalTrademarks	Value 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. This string is optional. In English, this string should be in the format "Windows is a trademark of Microsoft Corporation".
OriginalFilename	Value 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. This string is required.
PrivateBuild	Value 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	Value identifies the name of the product with which this file is distributed. For example, this string could be "Microsoft Windows". This string is required.
ProductVersion	Value identifies the version of the product with which this file is distributed. For example, Value could be "3.00A" or "5.00.RC2". This string is required.
SpecialBuild	Value 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 bytes as necessary to align the Value member on a 32-bit boundary.

Value

Specifies a zero-terminated string formatted in the language and code page indicated by the current StringTable structure. See the szKey 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 04070000 — that is, German/ASCII.

See Also

StringTable, VS_FIXEDFILEINFO, VS_VERSION_INFO


StringFileInfo
 StringFileInfo  QuickInfo

StringFileInfo {

    WCHAR       szKey[];

    BYTE        Padding[];

    StringTable Children[];

};

The StringFileInfo structure depicts the organization of data in a file-version resource. This structure is not a true C data 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 Win32 Software Development Kit (SDK).

The StringFileInfo structure contains version information that must be displayed in a particular language and code page. A code page is an ordered character set.

Members

szKey

Contains "StringFileInfo".

Padding

Contains as many zero bytes as necessary to align the Children member on a 32-bit boundary.

Children

Specifies a list of one or more Children structures. Each StringTable structure's szKey member indicates the appropriate language and code-page formatting.

Remarks

The Children member of the VS_VERSION_INFO structure may contain zero or more StringFileInfo structures.

See Also

StringTable, VS_VERSION_INFO


StringTable
 StringTable  QuickInfo

StringTable {

    WCHAR  szKey[];

    BYTE   Padding[];

    String Children[];

};

The StringTable structure depicts the organization of data in a file-version resource. This structure is not a true C data 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 Win32 Software Development Kit (SDK).

The StringTable structure contains language and code-page formatting information for the strings specified by the Children member. A code page is an ordered character set.

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.

Members

szKey

Specifies an 8-digit hexadecimal number stored as a string. The four most significant digits represent the language identifier, and 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. The following language identifiers are valid:

Identifier	Language
0x0401	Arabic
0x0402	Bulgarian
0x0403	Catalan
0x0404	Traditional Chinese
0x0804	Simplified Chinese
0x0405	Czech
0x0406	Danish
0x0407	German
0x0807	Swiss German
0x0408	Greek
0x0409	U.S. English
0x0809	U.K. English
0x040A	Castilian Spanish
0x080A	Mexican Spanish
0x040B	Finnish
0x040C	French
0x080C	Belgian French
0x0C0C	Canadian French
0x100C	Swiss French
0x040D	Hebrew
0x040E	Hungarian
0x040F	Icelandic
0x0410	Italian
0x0810	Swiss Italian
0x0411	Japanese
0x0412	Korean
0x0413	Dutch
0x0813	Belgian Dutch
0x0414	Norwegian — Bokmål
0x0814	Norwegian — Nynorsk
0x0415	Polish
0x0416	Brazilian Portuguese
0x0816	Portuguese
0x0417	Rhaeto-Romanic
0x0418	Romanian
0x0419	Russian
0x041A	Croato-Serbian (Latin)
0x081A	Serbo-Croatian (Cyrillic)
0x041B	Slovak
0x041C	Albanian
0x041D	Swedish
0x041E	Thai
0x041F	Turkish
0x0420	Urdu
0x0421	Bahasa
The code-page value can be one of the following or any IBM-registered code page:

Code page	Description
0	7-bit ASCII
932	Windows, Japan (Shift — JIS X-0208)
949	Windows, Korea (Shift — KSC 5601)
950	Windows, Taiwan (GB5)
1200	Unicode
1250	Windows, Latin-2 (Eastern European)
1251	Windows, Cyrillic
1252	Windows, Multilingual (ANSI)
1253	Windows, Greek
1254	Windows, Turkish
1255	Windows, Hebrew
1256	Windows, Arabic
Files designed for the English version of Windows would normally be marked with a code-page value of 1252.

Padding

Contains as many zero bytes as necessary to align the Children member on a 32-bit boundary.

Children

Specifies a list of zero or more String structures.

Remarks

The Children member of the StringFileInfo structure contains at least one StringTable structure with an szKey value of "04090000". This value indicates that the language is U.S. English and the code page is generic 7-bit ASCII.

See Also

Strings, StringFileInfo, VS_VERSION_INFO


STYLEBUF [New - Windows 95]
 STYLEBUF  QuickInfo  Overview  Group

[New - Windows 95]

typedef struct _tagSTYLEBUF {
    DWORD  dwStyle;
    CHAR  szDescription[32];
} STYLEBUF;

The STYLEBUF structure contains the identifier and name of a style.

Members

dwStyle

Style of the register string. Can be IME_REGWORD_STYLE_EUDC to indicate a string in the EUDC range.

szDescription

Description of the style.


STYLESTRUCT
 STYLESTRUCT  QuickInfo

typedef struct tagSTYLESTRUCT {  // ss

    DWORD styleOld;

    DWORD styleNew;

} STYLESTRUCT, * LPSTYLESTRUCT;

The STYLESTRUCT structure contains the window styles for a window.

Members

style

Specifies an array of window style or extended-style flags.

See Also

WM_STYLECHANGED, WM_STYLECHANGING


SYSTEM_ALARM_ACE
 SYSTEM_ALARM_ACE  QuickInfo

Reserved for future use.


SYSTEM_AUDIT_ACE
 SYSTEM_AUDIT_ACE  QuickInfo

typedef struct _SYSTEM_AUDIT_ACE { // sada

    ACE_HEADER  Header;

    ACCESS_MASK Mask;

    DWORD       SidStart;

} SYSTEM_AUDIT_ACE;

The SYSTEM_AUDIT_ACE structure defines an access-control entry (ACE) for the system access-control list (ACL) specifying what types of access cause system-level notifications. A system-audit ACE causes an audit message to be logged when a specified user or group attempts to gain access to an object. The user or group is identified by a security identifier (SID).

Members

Header

Specifies an ACE_HEADER structure.

Mask

Specifies an ACCESS_MASK structure that gives the access rights causing audit messages to be generated. The SUCCESSFUL_ACCESS_ACE_FLAG and FAILED_ACCESS_ACE_FLAG flags in the AceFlags member of the ACE_HEADER structure indicate whether messages are generated for successful access attempts, unsuccessful access attempts, or both.

SidStart

Specifies a SID. An access attempt of a kind specified by the Mask member by any user or group whose SID matches the SidStart member causes the system to generate an audit message. If an application does not specify a SID for this member, audit messages are generated for the specified access rights for all users and groups.

Remarks

Audit messages are stored in an event log that can be manipulated by using the Win32 API event-logging functions or by using Windows NT Event Viewer (EVENTVWR.EXE).

ACE structures should be aligned on doubleword boundaries. All Windows memory-management functions return doubleword-aligned handles to memory.

See Also

ACCESS_ALLOWED_ACE, ACCESS_DENIED_ACE, ACCESS_MASK, ACE_HEADER, ACL, SYSTEM_ALARM_ACE


SYSTEM_INFO
 SYSTEM_INFO  QuickInfo

typedef struct _SYSTEM_INFO { // sinf

    union {

        DWORD  dwOemId;

        struct {

            WORD wProcessorArchitecture;

            WORD wReserved;

        };

    };

    DWORD  dwPageSize;

    LPVOID lpMinimumApplicationAddress;

    LPVOID lpMaximumApplicationAddress;

    DWORD  dwActiveProcessorMask;

    DWORD  dwNumberOfProcessors;

    DWORD  dwProcessorType;

    DWORD  dwAllocationGranularity;

    WORD  wProcessorLevel;

    WORD  wProcessorRevision;

} SYSTEM_INFO;

The SYSTEM_INFO structure contains information about the current computer system. This includes the processor type, page size, original equipment manufacturer (OEM) identifier, and other such information.

Members

dwOemId

Windows 95: The system always sets this parameter to zero, the value defined for PROCESSOR_ARCHITECTURE_INTEL.

Windows NT: On Windows NT, use wProcessorArchitecture.

wProcessorArchitecture

Specifies the system's processor architecture. This value can be one of the following:

Platform	Value
Windows 95	PROCESSOR_ARCHITECTURE_INTEL
Windows NT	PROCESSOR_ARCHITECTURE_INTEL PROCESSOR_ARCHITECTURE_MIPS PROCESSOR_ARCHITECTURE_ALPHA PROCESSOR_ARCHITECTURE_PPC
wReserved

Reserved for future use.

dwPageSize

Returns the page size and specifies the granularity of page protection and commitment.

lpMinimumApplicationAddress

Returns the lowest memory address accessible to applications and dynamic-link libraries (DLLs).

lpMaximumApplicationAddress

Returns the highest memory address accessible to applications and DLLs.

dwActiveProcessorMask

Returns a mask representing the set of processors configured into the system. Bit 0 is processor 0; bit 31 is processor 31.

dwNumberOfProcessors

Returns the number of processors in the system.

dwProcessorType

No longer relevant but is retained for compatibility with Windows 95 and previous versions of Windows NT. It can be one of the following values:

Platform	Value
Windows 95	PROCESSOR_INTEL_386 PROCESSOR_INTEL_486 PROCESSOR_INTEL_PENTIUM
Windows NT	PROCESSOR_INTEL_386 PROCESSOR_INTEL_486 PROCESSOR_INTEL_PENTIUM PROCESSOR_MIPS_R4000 PROCESSOR_ALPHA_21046
dwAllocationGranularity

Returns the allocation granularity in which memory will be allocated on. This value was hard coded as 64K in the past, but other hardware architectures may require different values.

wProcessorLevel

Specifies the system's architecture-dependent processor level. This parameter can be one of the following:

Processor Architecture	Value
PROCESSOR_ARCHITECTURE_INTEL	3 - 80386 4 - 80486 5 - Pentium
PROCESSOR_ARCHITECTURE_MIPS	00xx - Where xx is an 8-bit implementation number (bits 8-15 of the PRid register. 0004 - R4000
PROCESSOR_ARCHITECTURE_ALPHA	xxxx where xxxx is a 16-bit processor version number (the low-order 16 bits of a version number from the firmware. 21064 - 21064 21066 - 21066 21164 - 21164
PROCESSOR_ARCHITECTURE_PPC	xxxx - where xxxx is a 16-bit processor version number (the high-order 16 bits of the Processor Version Register. 1  -  601 3  -  603 4  -  604 6  -  603+ 9  -  604+ 20 - 620
wProcessorRevision

Specifies an architecture-dependent processor revision. The following shows how appropriate revision values for each type of processor architecture are assembled.

Processor Architecture	Value
PROCESSOR_ARCHITECTURE_INTEL	Intel 80386 or 80486: xxyy - where xx + 'A' is the stepping level and yy is the stepping, so 0300 is a D0 chip. Intel Pentium or Cyrex/NextGen 486: xxyy - where xx is the model number and yy is the stepping, so 0201 is Model 2, Stepping 1.
PROCESSOR_ARCHITECTURE_MIPS	00xx is the 8-bit revision number of the processor (the low-order 8 bits of the PRId register).
PROCESSOR_ARCHITECTURE_ALPHA	xxxx where xxxx is a 16-bit processor revision number (the low-order 16 bits of the processor revision number from the firmware). It is displayed as:  Model 'A'+xx, Pass yy
PROCESSOR_ARCHITECTURE_PPC	xxyy - where xxyy is a 16-bit processor revision number (the low-order 16 bits of the Processor Version Register). it is displayed as a fixed point number xx.yy.
See Also

GetSystemInfo, MapViewOfFile, MapViewOfFileEx


SYSTEM_POWER_STATUS [New - Windows 95]
 SYSTEM_POWER_STATUS  QuickInfo  Overview  Group

[New - Windows 95]

typedef struct _SYSTEM_POWER_STATUS {
    BYTE ACLineStatus;
    BYTE  BatteryFlag;
    BYTE  BatteryLifePercent;
    BYTE  Reserved1;
    DWORD  BatteryLifeTime;
    DWORD  BatteryFullLifeTime;
} SYSTEM_POWER_STATUS;
typedef struct SYSTEM_POWER_STATUS *LPSYSTEM_POWER_STATUS;

The SYSTEM_POWER_STATUS structure contains information about the power status of the system.

Members

ACLineStatus

AC power status. This parameter can be one of the following values:

Value	Meaning
0	Offline
1	Online
255	Unknown status.
All other values are reserved.

BatteryFlag

Battery charge status. This parameter can be a combination of the following values:

Value	Meaning
1	High
2	Low
4	Critical
8	Charging
128	No system battery
255	Unknown status
All other values are reserved.

BatteryLifePercent

Percentage of full battery charge remaining. This member can be a value in the range 0 to 100, or 255 if status is unknown. All other values are reserved.

Reserved1

Reserved; must be zero.

BatteryLifeTime

Number of seconds of battery life remaining, or 0xFFFFFFFF if remaining seconds are unknown.

BatteryFullLifeTime

Number of seconds of battery life when at full charge, or 0xFFFFFFFF if full lifetime is unknown.

Remarks

Windows 95 is only capable of estimating BatteryFullTime based on calculations on BatteryLifeTime and BatteryLifePercent. Without smart battery subsystems, this value may not be accurate enough to be useful.


SYSTEMTIME
 SYSTEMTIME  QuickInfo

typedef struct _SYSTEMTIME {  // st

    WORD wYear;

    WORD wMonth;

    WORD wDayOfWeek;

    WORD wDay;

    WORD wHour;

    WORD wMinute;

    WORD wSecond;

    WORD wMilliseconds;

} SYSTEMTIME;

The SYSTEMTIME structure represents a date and time using individual members for the month, day, year, weekday, hour, minute, second, and millisecond.

Members

wYear

Specifies the current year.

wMonth

Specifies the current month; January = 1, February = 2, and so on.

wDayOfWeek

Specifies the current day of the week; Sunday = 0, Monday = 1, and so on.

wDay

Specifies the current day of the month.

wHour

Specifies the current hour.

wMinute

Specifies the current minute.

wSecond

Specifies the current second.

wMilliseconds

Specifies the current millisecond.

See Also

GetLocalTime, GetSystemTime, SetLocalTime, SetSystemTime, FILETIME


TAPE_ERASE
 TAPE_ERASE  QuickInfo

typedef struct _TAPE_ERASE { // ter

    ULONG Type;

} TAPE_ERASE;

The TAPE_ERASE structure describes the partition to be erased.

Members

Type

Specifies how to erase the tape. This member must have one of the following values:

Value	Description
TAPE_ERASE_LONG	Erases the entire partition.
TAPE_ERASE_SHORT	Erases only the partition's header block.


TAPE_GET_DRIVE_PARAMETERS
 TAPE_GET_DRIVE_PARAMETERS  QuickInfo

typedef struct _TAPE_GET_DRIVE_PARAMETERS { // tgdp

    BOOLEAN ECC;

    BOOLEAN Compression;

    BOOLEAN DataPadding;

    BOOLEAN ReportSetmarks;

    ULONG   DefaultBlockSize;

    ULONG   MaximumBlockSize;

    ULONG   MinimumBlockSize;

    ULONG   MaximumPartitionCount;

    ULONG   FeaturesLow;

    ULONG   FeaturesHigh;

    ULONG   EOTWarningZoneSize;

} TAPE_GET_DRIVE_PARAMETERS;

The TAPE_GET_DRIVE_PARAMETERS structure describes the tape drive.

Members

ECC

Specifies whether the device supports hardware error correction. This member is TRUE if hardware error correction is supported.

Compression

Specifies whether hardware data compression is enabled or disabled. This member is TRUE if hardware data compression is enabled.

DataPadding

Specifies whether data padding is enabled or disabled. Data padding keeps the tape streaming at a constant speed. This member is TRUE if data padding is enabled.

ReportSetmarks

Specifies whether setmark reporting is enabled or disabled. This member is TRUE if setmark reporting is enabled.

DefaultBlockSize

Specifies the device's default fixed block size.

MaximumBlockSize

Specifies the device's maximum block size.

MinimumBlockSize

Specifies the device's minimum block size.

MaximumPartitionCount

Specifies the maximum number of partitions that can be created on the device.

FeaturesLow

Specifies the low-order 32 bits of the device features flag. This member can be one or more of following values:

Value	Meaning
TAPE_DRIVE_COMPRESSION	The device supports hardware data compression.
TAPE_DRIVE_ECC	The device supports hardware error correction.
TAPE_DRIVE_ERASE_BOP_ONLY	The device performs the erase operation from the beginning-of-partition marker only.
TAPE_DRIVE_ERASE_LONG	The device performs a long erase operation.
TAPE_DRIVE_ERASE_IMMEDIATE	The device performs an immediate erase operation —  that is, it returns when the erase operation begins.
TAPE_DRIVE_ERASE_SHORT	The device performs a short erase operation.
TAPE_DRIVE_FIXED	The device creates fixed data partitions.
TAPE_DRIVE_FIXED_BLOCK	The device supports fixed-length block mode.
TAPE_DRIVE_INITIATOR	The device creates initiator-defined partitions.
TAPE_DRIVE_PADDING	The device supports data padding.
TAPE_DRIVE_GET_ABSOLUTE_BLK	The device provides the current device-specific block address.
TAPE_DRIVE_GET_LOGICAL_BLK	The device provides the current logical block address (and logical tape partition).
TAPE_DRIVE_REPORT_SMKS	The device supports setmark reporting.
TAPE_DRIVE_SELECT	The device creates select data partitions.
TAPE_DRIVE_SET_EOT_WT_SIZE	The device supports setting the end-of-medium warning size.
TAPE_DRIVE_TAPE_CAPACITY	The device returns the maximum capacity of the tape.
TAPE_DRIVE_TAPE_REMAINING	The device returns the remaining capacity of the tape.
TAPE_DRIVE_VARIABLE_BLOCK	The device supports variable-length block mode.
TAPE_DRIVE_WRITE_PROTECT	The device returns an error if the tape is write-enabled or write-protected.
FeaturesHigh

Contains the high-order 32 bits of the device features flag. This member can be one or more of the following values:

Value	Meaning
TAPE_DRIVE_ABS_BLK_IMMED	The device moves the tape to a device-specific block address and returns as soon as the move begins.
TAPE_DRIVE_ABSOLUTE_BLK	The device moves the tape to a device specific block address.
TAPE_DRIVE_END_OF_DATA	The device moves the tape to the end-of-data marker in a partition.
TAPE_DRIVE_FILEMARKS	The device moves the tape forward (or backward) a specified number of filemarks.
TAPE_DRIVE_LOAD_UNLOAD	The device enables and disables the device for further operations.
TAPE_DRIVE_LOAD_UNLOAD_IMMED	The device supports immediate load and unload operations.
TAPE_DRIVE_LOCK_UNLOCK	The device enables and disables the tape ejection mechanism.
TAPE_DRIVE_LOCK_UNLK_IMMED	The device supports immediate lock and unlock operations.
TAPE_DRIVE_LOG_BLK_IMMED	The device moves the tape to a logical block address in a partition and returns as soon as the move begins.
TAPE_DRIVE_LOGICAL_BLK	The device moves the tape to a logical block address in a partition.
TAPE_DRIVE_RELATIVE_BLKS	The device moves the tape forward (or backward) a specified number of blocks.
TAPE_DRIVE_REVERSE_POSITION	The device moves the tape backward over blocks, filemarks, or setmarks.
TAPE_DRIVE_REWIND_IMMEDIATE	The device supports immediate rewind operation.
TAPE_DRIVE_SEQUENTIAL_FMKS	The device moves the tape forward (or backward) to the first occurrence of a specified number of consecutive filemarks.
TAPE_DRIVE_SEQUENTIAL_SMKS	The device moves the tape forward (or backward) to the first occurrence of a specified number of consecutive setmarks.
TAPE_DRIVE_SET_BLOCK_SIZE	The device supports setting the size of a fixed-length logical block or setting the variable-length block mode.
TAPE_DRIVE_SET_COMPRESSION	The device enables and disables hardware data compression.
TAPE_DRIVE_SET_ECC	The device enables and disables hardware error correction.
TAPE_DRIVE_SET_PADDING	The device enables and disables data padding.
TAPE_DRIVE_SET_REPORT_SMKS	The device enables and disables the reporting of setmarks.
TAPE_DRIVE_SETMARKS	The device moves the tape forward (or reverse) a specified number of setmarks.
TAPE_DRIVE_SPACE_IMMEDIATE	The device supports immediate spacing.
TAPE_DRIVE_TENSION	The device supports tape tensioning.
TAPE_DRIVE_TENSION_IMMED	The device supports immediate tape tensioning.
TAPE_DRIVE_WRITE_FILEMARKS	The device writes filemarks.
TAPE_DRIVE_WRITE_LONG_FMKS	The device writes long filemarks.
TAPE_DRIVE_WRITE_MARK_IMMED	The device supports immediate writing of short and long filemarks.
TAPE_DRIVE_WRITE_SETMARKS	The device writes setmarks.
TAPE_DRIVE_WRITE_SHORT_FMKS	The device writes short filemarks.
EOTWarningZoneSize

Indicates the number of bytes between the end-of-tape warning and the physical end of the tape.


TAPE_GET_MEDIA_PARAMETERS
 TAPE_GET_MEDIA_PARAMETERS  QuickInfo

typedef struct _TAPE_GET_MEDIA_PARAMETERS {  // tgmp

    LARGE_INTEGER   Capacity;

    LARGE_INTEGER   Remaining;

    DWORD   BlockSize;

    DWORD   PartitionCount;

    BOOLEAN WriteProtected;

} TAPE_GET_MEDIA_PARAMETERS;

The TAPE_GET_MEDIA_PARAMETERS structure describes the tape in the tape drive.

Members

Capacity

Specifies the total number of bytes on the current tape partition.

Remaining

Specifies the number of bytes between the current position and the end of the current tape partition.

BlockSize

Specifies the number of bytes per block.

PartitionCount

Specifies the number of partitions on the tape.

WriteProtected

Specifies whether the tape is write-protected. If this member is TRUE, the tape is write-protected.

Remarks

The GetTapeParameters function fills the Remaining and Capacity members with estimates of the tape remaining in the current tape partition and the total capacity of the current tape partition.

See Also

GetTapeParameters


TAPE_GET_POSITION
 TAPE_GET_POSITION  QuickInfo

typedef struct _TAPE_GET_POSITION { // tgpos

    ULONG Type;

    ULONG Partition;

    ULONG OffsetLow;

    ULONG OffsetHigh;

} TAPE_GET_POSITION;

The TAPE_GET_POSITION structure describes the position of the tape.

Members

Type

Specifies the type of position. This member must be one of the following values:

Value	Description
TAPE_ABSOLUTE_POSITION	The position specified by the OffsetLow and OffsetHigh members is an absolute number of blocks from the beginning of the partition specified by the Partition member.
TAPE_LOGICAL_POSITION	The position specified by OffsetLow and OffsetHigh is relative to the current position in the partition specified by Partition.
Partition

Specifies the partition to position within. If this member is zero, the current partition is assumed.

OffsetLow

Specifies the low-order 32 bits of the block address.

OffsetHigh

Specifies the high-order 32 bits of the block address. If the high-order 32 bits are not required, this member should be zero.


TAPE_PREPARE
 TAPE_PREPARE  QuickInfo

typedef struct _TAPE_PREPARE { // tp

    ULONG Operation;

} TAPE_PREPARE;

The TAPE_PREPARE structure describes how to prepare the tape.

Members

Operation

Specifies how to prepare the tape. This member must be one of the following values:

Value	Description
TAPE_LOCK	Locks the tape ejection mechanism so that the tape is not ejected accidentally during a tape operation.
TAPE_TENSION	Moves to the end of the tape and rewinds to the beginning of the tape. This value is ignored if the tape device does not support tensioning.
TAPE_UNLOAD	Rewinds and unloads the tape.
TAPE_UNLOCK	Unlocks the tape ejection mechanism.


TAPE_SET_DRIVE_PARAMETERS
 TAPE_SET_DRIVE_PARAMETERS  QuickInfo

typedef struct _TAPE_SET_DRIVE_PARAMETERS {  // tsdp

    BOOLEAN ECC;

    BOOLEAN Compression;

    BOOLEAN DataPadding;

    BOOLEAN ReportSetmarks;

    ULONG   EOTWarningZoneSize;

} TAPE_SET_DRIVE_PARAMETERS;

The TAPE_SET_DRIVE_PARAMETERS structure describes the tape drive.

Members

ECC

Specifies whether the device supports hardware error correction. This member is TRUE if hardware error correction is supported.

Compression

Specifies whether hardware data compression is enabled or disabled. This member is TRUE if hardware data compression is enabled.

DataPadding

Specifies whether data padding is enabled or disabled. Data padding keeps the tape streaming at a constant speed. This member is TRUE if data padding is enabled.

ReportSetmarks

Specifies whether setmark reporting is enabled or disabled. This member is TRUE if setmarks are enabled.

EOTWarningZoneSize

Specifies the number of bytes between the end-of-tape warning and the physical end of the tape.


TAPE_SET_MEDIA_PARAMETERS
 TAPE_SET_MEDIA_PARAMETERS  QuickInfo

typedef struct _TAPE_SET_MEDIA_PARAMETERS { // tsmp

    ULONG BlockSize;

} TAPE_SET_MEDIA_PARAMETERS;

The TAPE_SET_MEDIA_PARAMETERS structure describes the tape in the tape drive.

Members

BlockSize

Specifies the number of bytes per block. Maximum and minimum block sizes can be obtained by calling the GetTapeParameters function.

Remarks

There is no longer a requirement that block sizes be powers of 2.

See Also

GetTapeParameters, SetTapeParameters


TAPE_SET_POSITION
 TAPE_SET_POSITION  QuickInfo

typedef struct _TAPE_SET_POSITION { // tspos

    ULONG Method;

    ULONG Partition;

    ULONG OffsetLow;

    ULONG OffsetHigh;

} TAPE_SET_POSITION;

The TAPE_SET_POSITION structure describes how and where to position the tape.

Members

Method

Specifies the type of positioning. This member must be one of the following values:

Value	Description
TAPE_ABSOLUTE_BLOCK	Moves the tape to the device-specific block address specified by the OffsetLow and OffsetHigh members. The Partition member is ignored.
TAPE_LOGICAL_BLOCK	Moves the tape to the block address specified by OffsetLow and OffsetHigh in the partition specified by Partition.
TAPE_REWIND	Moves the tape to the beginning of the current partition. The Partition, OffsetLow, and OffsetHigh members are ignored.
TAPE_SPACE_END_OF_DATA	Moves the tape to the end of the data on the partition specified by Partition.
TAPE_SPACE_FILEMARKS	Moves the tape forward (or backward) the number of filemarks specified by OffsetLow and OffsetHigh in the current partition. The Partition member is ignored.
TAPE_SPACE_RELATIVE_BLOCKS	Moves the tape forward (or backward) the number of blocks specified by OffsetLow and OffsetHigh in the current partition. The Partition member is ignored.
TAPE_SPACE_SEQUENTIAL_FMKS	Moves the tape forward (or backward) to the first occurrence of n filemarks in the current partition, where n is the number specified by OffsetLow and OffsetHigh. The Partition parameter is ignored.
TAPE_SPACE_SEQUENTIAL_SMKS	Moves the tape forward (or backward) to the first occurrence of n setmarks in the current partition, where n is the number specified by OffsetLow and OffsetHigh. The Partition member is ignored.
TAPE_SPACE_SETMARKS	Moves the tape forward (or backward) the number of setmarks specified by OffsetLow and OffsetHigh in the current partition. The Partition member is ignored.
Partition

Specifies the partition to position within. If this member is zero, the current partition is assumed.

OffsetLow

Specifies the low-order 32 bits of the block address or count for the position operation specified by the Method member.

OffsetHigh

Specifies the high-order 32 bits of the block address or count for the position operation specified by the Method member. If the high-order 32 bits are not required, this member should be zero.

Remarks

If the positioning is relative, a positive offset moves the tape forward (toward the end of the tape) and a negative offset moves the tape backward (toward the beginning of the tape).


TAPE_WRITE_MARKS
 TAPE_WRITE_MARKS  QuickInfo

typedef struct _TAPE_WRITE_MARKS { // twm

    ULONG Type;

    ULONG Count;

} TAPE_WRITE_MARKS;

The TAPE_WRITE_MARKS structure describes the type and number of tapemarks to write.

Members

Type

Specifies the type of tapemark to write. This member can be one of the following values:

Value	Description
TAPE_LONG_FILEMARKS	Writes long filemarks.
TAPE_SEQUENTIAL_FILEMARKS	Writes sequential filemarks.
TAPE_SETMARKS	Writes setmarks.
TAPE_SHORT_FILEMARKS	Writes short filemarks.
Count

Specifies the number of tapemarks to write.


TBADDBITMAP [New - Windows NT]
 TBADDBITMAP  QuickInfo  Overview  Group

[New - Windows NT]

typedef struct {  // tbab

    HINSTANCE hInst;

    UINT nID;

} TBADDBITMAP, *LPTBADDBITMAP;

The TBADDBITMAP structure adds a bitmap that contains button images to a toolbar.

Members

hInst

Handle to the module instance with the executable file that contains a bitmap resource. You can add the system-defined button bitmaps to the list by specifying HINST_COMMCTRL as the hInst member and one of the following values as the nID member:

Value	Meaning
IDB_STD_LARGE_COLOR	Adds large, color standard bitmaps.
IDB_STD_SMALL_COLOR	Adds small, color standard bitmaps.
IDB_VIEW_LARGE_COLOR	Adds large, color view bitmaps.
IDB_VIEW_SMALL_COLOR	Adds small, color view bitmaps.
For more information about the system-defined standard and view bitmaps, see the following Remarks section.

nID

Resource identifier of the bitmap resource that contains the button images. If hInst is NULL, this parameter must be the handle to a bitmap that contains the button images.

Remarks

The Windows header files provide the following values that you use as indexes to the standard and view bitmaps.

STD_COPY	STD_PASTE
STD_CUT	STD_PRINT
STD_DELETE	STD_PRINTPRE
STD_FILENEW	STD_PROPERTIES
STD_FILEOPEN	STD_REDOW
STD_FILESAVE	STD_REPLACE
STD_FIND	STD_UNDO
STD_HELP
VIEW_LARGEICONS	VIEW_SORTNAME
VIEW_SMALLICONS	VIEW_SORTSIZE
VIEW_LIST	VIEW_SORTDATE
VIEW_DETAILS	VIEW_SORTTYPE
The TBADDBITMAP structure is used with the TB_ADDBITMAP message.

See Also

TB_ADDBITMAP


TBBUTTON [New - Windows NT]
 TBBUTTON  QuickInfo  Overview  Group

[New - Windows NT]

typedef struct _TBBUTTON { \\ tbb

    int iBitmap;

    int idCommand;

    BYTE fsState;

    BYTE fsStyle;

    DWORD dwData;

    int iString;

} TBBUTTON, NEAR* PTBBUTTON, FAR* LPTBBUTTON;

typedef const TBBUTTON FAR* LPCTBBUTTON;

The TBBUTTON structure contains information about a button in a toolbar.

Members

iBitmap

Zero-based index of button image.

idCommand

Command identifier associated with the button. This identifier is used in a WM_COMMAND message when the button is chosen. If the fsStyle member is the TBSTYLE_SEP value, this member must be zero.

fsState

Button state flags. This member can be a combination of the values listed in Toolbar Button States.

fsStyle

Button style. This member can be a combination of values listed in Toolbar Button Styles

dwData

Application-defined value.

iString

Zero-based index of button string.

See Also

WM_COMMAND


TBNOTIFY [New - Windows NT]
 TBNOTIFY  QuickInfo  Overview  Group

[New - Windows NT]

typedef struct { \\ tbn

    NMHDR hdr;

    int iItem;

    TBBUTTON tbButton;

    int cchText;

    LPTSTR pszText;

} TBNOTIFY, FAR* LPTBNOTIFY;

The TBNOTIFY structure contains information used to process notification messages from a toolbar.

Members

hdr

Required for all WM_NOTIFY messages.

iItem

Index of the button associated with notification.

tbButton

Address of a TBBUTTON structure that contains information about the toolbar button associated with the notification.

cchText

Count of characters in the button text.

pszText

Address of the button text.

See Also

TBBUTTON, WM_NOTIFY


TBSAVEPARAMS [New - Windows NT]
 TBSAVEPARAMS  QuickInfo  Overview  Group

[New - Windows NT]

typedef struct { \\ tbsr

    HKEY hkr;

    LPCTSTR pszSubKey;

    LPCTSTR pszValueName;

} TBSAVEPARAMS;

The TBSAVEPARAMS function specifies the location in the registry where the TB_SAVERESTORE message stores and retrieves information about the state of a toolbar.

Members

hkr

Handle to the registry key.

pszSubKey

Subkey name.

pszValueName

Value name.

See Also

TB_SAVERESTORE


TC_HITTESTINFO [New - Windows NT]
 TC_HITTESTINFO  QuickInfo  Overview  Group

[New - Windows NT]

typedef struct _TC_HITTESTINFO {

    POINT pt;     // position to hit test, in client coordinates

    UINT  flags;  // variable to receive hit test results

} TC_HITTESTINFO;

The TC_HITTESTINFO structure contains information about a hit test.

Members

pt

Position to hit test, in client coordinates.

flags

Variable that receives the results of a hit test. The tab control sets this member to one of the following values:

Value	Meaning
TCHT_NOWHERE	The position is not over a tab.
TCHT_ONITEM	The position is over a tab, but not over its icon or its text. For owner-drawn tab controls, this value is specified if the position is anywhere over a tab.
TCHT_ONITEMICON	The position is over a tab's icon.
TCHT_ONITEMLABEL	The position is over a tab's text.
TCHT_ONITEM is a bitwise OR operation on TCHT_ONITEMICON and TCHT_ONITEMLABEL.

Remarks

This structure is used with the TCM_HITTEST message.

See Also

TCM_HITTEST


TC_ITEM [New - Windows NT]
 TC_ITEM  QuickInfo  Overview  Group

[New - Windows NT]

typedef struct _TC_ITEM {

    UINT mask;         // value specifying which members to retrieve or set

    UINT lpReserved1;  // reserved; do not use

    UINT lpReserved2;  // reserved; do not use

    LPSTR pszText;     // pointer to string containing tab text

    int cchTextMax;    // size of buffer pointed to by the pszText member

    int iImage;        // index to tab control's image

    LPARAM lParam;     // application-defined data associated with tab

} TC_ITEM;

The TC_ITEM structure specifies or receives the attributes of a tab.

Members

mask

Value specifying which members to retrieve or set. This member can be TCIF_ALL (meaning all members), or zero or more of the following values:

Value	Meaning
TCIF_TEXT	The pszText member is valid.
TCIF_IMAGE	The iImage member is valid.
TCIF_PARAM	The lParam member is valid.
TCIF_RTLREADING	Windows 95 only: Displays the text of pszText using right-to-left reading order on Hebrew or Arabic systems.
lpReserved1

Reserved; do not use.

lpReserved2

Reserved; do not use.

pszText

Pointer to a null-terminated string that contains the tab text if the structure contains information about a tab. If the structure is receiving information, this member specifies the address of the buffer that receives the tab text.

cchTextMax

Size of the buffer pointed to by the pszText member. If the structure is not receiving information, this member is ignored.

iImage

Index into the tab control's image list or  − 1 if there is no image for the tab.

lParam

Application-defined data associated with the tab. If there are more or less than 4 bytes of application-defined data per tab, an application must define a structure and use it instead of the TC_ITEM structure. The first member of the application-defined structure must be a TC_ITEMHEADER structure.

This structure is used with the TCM_INSERTITEM, TCM_GETITEM, and TCM_SETITEM messages.

See Also

TCM_GETITEM, TCM_INSERTITEM, TC_ITEMHEADER, TCM_SETITEM


TC_ITEMHEADER [New - Windows NT]
 TC_ITEMHEADER  QuickInfo  Overview  Group

[New - Windows NT]

typedef struct _TC_ITEMHEADER {

    UINT mask;         // value specifying which members to retrieve or set

    UINT lpReserved1;  // reserved; do not use

    UINT lpReserved2;  // reserved; do not use

    LPSTR pszText;     // pointer to string containing tab text

    int cchTextMax;    // size of buffer pointed to by the pszText member

    int iImage;        // index to tab control's image

} TC_ITEMHEADER;

The TC_ITEMHEADER structure specifies or receives the attributes of a tab. This structure is the same as the TC_ITEM structure, that it does not include an lParam member for application-defined data.

Members

mask

Value specifying which members to retrieve or set. This member can be TCIF_ALL (meaning all members), or zero or more of the following values:

Value	Meaning
TCIF_TEXT	The pszText member is valid.
TCIF_IMAGE	The iImage member is valid.
TCIF_PARAM	The lParam member is valid.
TCIF_RTLREADING	Windows 95 only: Displays the text of pszText using right-to-left reading order on Hebrew or Arabic systems.
lpReserved1

Reserved; do not use.

lpReserved2

Reserved; do not use.

pszText

Pointer to a null-terminated string that contains the tab text if the structure contains information about a tab. If the structure is receiving information, this member specifies the address of the buffer that receives the tab text.

cchTextMax

Size of the buffer pointed to by the pszText member. If the structure is not receiving information, this member is ignored.

iImage

Index into the tab control's image list or  − 1 if there is no image for the tab.

Remarks

An application cannot use the TC_ITEM structure to retrieve or set the application-defined data for tabs in a tab control with more or less than four extra bytes per tab. Instead, you should define a structure that consists of the TC_ITEMHEADER structure followed by application-defined data.

To set the number of extra bytes per tab, use the TCM_SETITEMEXTRA message.

See Also

TC_ITEM, TCM_SETITEMEXTRA


TC_KEYDOWN [New - Windows NT]
 TC_KEYDOWN  QuickInfo  Overview  Group

[New - Windows NT]

typedef struct _TC_KEYDOWN {

    NMHDR hdr;    // notification header

    WORD wVKey;   // virtual-key code

    UINT flags;
} TC_KEYDOWN;

The TC_KEYDOWN structure contains information about a key press in a tab control. This structure is used with the TCN_KEYDOWN notification message.

Members

hdr

Notification header

wVKey

Virtual key code.

flags

Same as the lParam parameter of the WM_KEYDOWN message.

See Also

TCN_KEYDOWN, WM_KEYDOWN


TEXTMETRIC
 TEXTMETRIC  QuickInfo

typedef struct tagTEXTMETRIC { // tm

    LONG tmHeight;

    LONG tmAscent;

    LONG tmDescent;

    LONG tmInternalLeading;

    LONG tmExternalLeading;

    LONG tmAveCharWidth;

    LONG tmMaxCharWidth;

    LONG tmWeight;

    LONG tmOverhang;

    LONG tmDigitizedAspectX;

    LONG tmDigitizedAspectY;

    BCHAR tmFirstChar;

    BCHAR tmLastChar;

    BCHAR tmDefaultChar;

    BCHAR tmBreakChar;

    BYTE tmItalic;

    BYTE tmUnderlined;

    BYTE tmStruckOut;

    BYTE tmPitchAndFamily;

    BYTE tmCharSet;

} TEXTMETRIC;

The TEXTMETRIC structure contains basic information about a physical font. All sizes are given in logical units; that is, they depend on the current mapping mode of the display context.

Members

tmHeight

Specifies the height (ascent + descent) of characters.

tmAscent

Specifies the ascent (units above the base line) of characters.

tmDescent

Specifies the descent (units below the base line) of characters.

tmInternalLeading

Specifies the amount of leading (space) inside the bounds set by the tmHeight member. Accent marks and other diacritical characters may occur in this area. The designer may set this member to zero.

tmExternalLeading

Specifies the amount of extra leading (space) that the application adds between rows. Since this area is outside the font, it contains no marks and is not altered by text output calls in either OPAQUE or TRANSPARENT mode. The designer may set this member to zero.

tmAveCharWidth

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.

tmMaxCharWidth

Specifies the width of the widest character in the font.

tmWeight

Specifies the weight of the font.

tmOverhang

Specifies the extra width per string that may be added to some synthesized fonts. When synthesizing some attributes, such as bold or italic, graphics device interface (GDI) or a device may have to add width to a string on both a per-character and per-string basis. For example, GDI makes a string bold by expanding the spacing of each character and overstriking by an offset value; it italicizes a font by shearing the string. In either case, there is an overhang past the basic string. For bold strings, the overhang is the distance by which the overstrike is offset. For italic strings, the overhang is the amount the top of the font is sheared past the bottom of the font.

The tmOverhang member enables the application to determine how much of the character width returned by a GetTextExtentPoint32 function call on a single character is the actual character width and how much is the per-string extra width. The actual width is the extent minus the overhang.

tmDigitizedAspectX

Specifies the horizontal aspect of the device for which the font was designed.

tmDigitizedAspectY

Specifies the vertical aspect of the device for which the font was designed. The ratio of the tmDigitizedAspectX and tmDigitizedAspectY members is the aspect ratio of the device for which the font was designed.

tmFirstChar

Specifies the value of the first character defined in the font.

tmLastChar

Specifies the value of the last character defined in the font.

tmDefaultChar

Specifies the value of the character to be substituted for characters not in the font.

tmBreakChar

Specifies the value of the character that will be used to define word breaks for text justification.

tmItalic

Specifies an italic font if it is nonzero.

tmUnderlined

Specifies an underlined font if it is nonzero.

tmStruckOut

Specifies a strikeout font if it is nonzero.

tmPitchAndFamily

Specifies information about the pitch, the technology, and the family of a physical font.

The four low-order bits of this member specify information about the pitch and the technology of the font. A constant is defined for each of the four bits:

Constant	Meaning
TMPF_FIXED_PITCH	If this bit is set the font is a variable pitch font. If this bit is clear the font is a fixed pitch font. Note very carefully that those meanings are the opposite of what the constant name implies.
TMPF_VECTOR	If this bit is set the font is a vector font.
TMPF_TRUETYPE	If this bit is set the font is a TrueType font.
TMPF_DEVICE	If this bit is set the font is a device font.
An application should carefully test for qualities encoded in these low-order bits, making no arbitrary assumptions. For example, besides having their own bits set, TrueType and PostScript fonts set the TMPF_VECTOR bit. A monospace bitmap font has all of these low-order bits clear; a proportional bitmap font sets the TMPF_FIXED_PITCH bit. A Postscript printer device font sets the TMPF_DEVICE, TMPF_VECTOR, and TMPF_FIXED_PITCH bits.

The four high-order bits of tmPitchAndFamily designate the font's font family. An application can use the value 0xF0 and the bitwise AND operator to mask out the four low-order bits of tmPitchAndFamily, thus obtaining a value that can be directly compared with font family names to find an identical match. For information about font families, see the description of the LOGFONT structure.

tmCharSet

Specifies the character set of the font.

See Also

GetTextMetrics, GetTextExtentPoint32, LOGFONT


TEXTRANGE [New - Windows NT]
 TEXTRANGE  QuickInfo  Overview  Group

[New - Windows NT]

pedef struct _textrange {

    CHARRANGE chrg;

    LPSTR lpstrText;

} TEXTRANGE;

The TEXTRANGE structure receives a range of text from a rich edit control. This structure is filled in by the EM_GETTEXTRANGE message. The buffer pointed to by the lpstrText member must be large enough to receive all characters and the teminating null character.

Members

chrg

Range of characters to get.

lpstrText

Pointer to buffer to receive the text.

See Also

EM_GETTEXTRANGE


TIME_ZONE_INFORMATION
 TIME_ZONE_INFORMATION  QuickInfo

typedef struct _TIME_ZONE_INFORMATION { // tzi

    LONG       Bias;

    WCHAR      StandardName[ 32 ];

    SYSTEMTIME StandardDate;

    LONG       StandardBias;

    WCHAR      DaylightName[ 32 ];

    SYSTEMTIME DaylightDate;

    LONG       DaylightBias;

} TIME_ZONE_INFORMATION;

The TIME_ZONE_INFORMATION structure specifies information specific to the time zone.

Members

Bias

Specifies the current bias, in minutes, for local time translation on this computer. The bias is the difference, in minutes, between Coordinated Universal Time (UTC) and local time. All translations between UTC and local time are based on the following formula:

UTC = local time + bias

This member is required.

StandardName

Specifies a null-terminated string associated with standard time on this operating system. For example, this parameter could contain "EST" to indicate Eastern Standard Time. This string is not used by the operating system, so anything stored there by using the SetTimeZoneInformation function is returned unchanged by the GetTimeZoneInformation function. This string can be empty.

StandardDate

Specifies a SYSTEMTIME structure that contains a date and UTC when the transition from daylight time to standard time occurs on this operating system. If this date is not specified, the wMonth member in the SYSTEMTIME structure must be zero. If this date is specified, the DaylightDate value in the TIME_ZONE_INFORMATION structure must also be specified. Local time translations done during the standard-time range are relative to the supplied StandardBias value.

This member supports two date formats. Absolute format specifies an exact date and time when standard time begins. In this form, the wYear, wMonth, wDay, wHour, wMinute, wSecond, and wMilliseconds members of the SYSTEMTIME structure are used to specify an exact date.

Day-in-month format is specified by setting the wYear member to zero, setting the wDayOfWeek member to an appropriate weekday, and using a wDay value in the range 1 through 5 to select the correct day in the month. Using this notation, the first Sunday in April can be specified, as can the last Thursday in October (5 is equal to "the last").

StandardBias

Specifies a bias value to be used during local time translations that occur during standard time. This member is ignored if a value for the StandardDate member is not supplied.

This value is added to the value of the Bias member to form the bias used during standard time. In most time zones, the value of this member is zero.

DaylightName

Specifies a null-terminated string associated with daylight time on this operating system. For example, this parameter could contain "PDT" to indicate Pacific Daylight Time. This string is not used by the operating system, so anything stored there by using the SetTimeZoneInformation function is returned unchanged by the GetTimeZoneInformation function. This string can be empty.

DaylightDate

Specifies a SYSTEMTIME structure that contains a date and UTC when the transition from standard time to daylight time occurs on this operating system. If this date is not specified, the wMonth member in the SYSTEMTIME structure must be zero. If this date is specified, the StandardDate value in the TIME_ZONE_INFORMATION structure must also be specified. Local time translations during the daylight-time range are relative to the supplied DaylightBias value. This member supports the absolute and day-in-month time formats described for the StandardDate member.

DaylightBias

Specifies a bias value to be used during local time translations that occur during daylight time. This member is ignored if a value for the DaylightDate member is not supplied.

This value is added to the value of the Bias member to form the bias used during daylight time. In most time zones, the value of this member is  − 60.

See Also

GetTimeZoneInformation, SetTimeZoneInformation, SYSTEMTIME


TOGGLEKEYS
 TOGGLEKEYS  QuickInfo  Overview  Group

typedef struct tagTOGGLEKEYS {     // tk

    DWORD cbSize;

    DWORD dwFlags;

} TOGGLEKEYS;

The TOGGLEKEYS structure contains information about the ToggleKeys accessibility feature. When the ToggleKeys feature is on, the computer emits a high-pitched tone whenever the user turns on the CAPS LOCK, NUM LOCK, or SCROLL LOCK key, and a low-pitched tone whenever the user turns off one of those keys.

Members

cbSize

Specifies the size, in bytes, of this structure.

dwFlags

A set of bit flags that specify properties of the ToggleKeys feature. The following bit flag values are defined:

Value	Meaning
TKF_AVAILABLE	If this flag is set, the ToggleKeys feature is available.
TKD_CONFIRMHOTKEY	Windows 95 only: A confirmation dialog box appears when the Togglekeys feature is activated by using the hot key.
TKF_HOTKEYACTIVE	If this flag is set, the user can turn the ToggleKeys feature on and off by holding down the NUM LOCK key for eight seconds.
TKF_HOTKEYSOUND	If this flag is set, the system plays a siren sound when the user turns the ToggleKeys feature on or off by using the hot key.
TKF_TOGGLEKEYSON	If this flag is set, the ToggleKeys feature is on.
Remarks

An application uses a TOGGLEKEYS structure when calling the SystemParametersInfo function with the wAction parameter set to SPI_GETTOGGLEKEYS or SPI_SETTOGGLEKEYS. When using SPI_GETTOGGLEKEYS, an application must specify the cbSize member of the TOGGLEKEYS structure; the SystemParametersInfo function fills the remaining members. An application must specify all structure members when using the SETTOGGLEKEYS value.

See Also

SystemParametersInfo


TOKEN_CONTROL
 TOKEN_CONTROL  QuickInfo

typedef struct _TOKEN_CONTROL { // tc

    LUID TokenId;

    LUID AuthenticationId;

    LUID ModifiedId;

    TOKEN_SOURCE TokenSource;

} TOKEN_CONTROL ;

The TOKEN_CONTROL structure contains information that identifies an access token.

Members

TokenId

Specifies a locally unique identifier (LUID) identifying this instance of the token object.

AuthenticationId

Specifies an LUID assigned to the session this token represents. There can be many tokens representing a single logon session.

ModifiedId

Specifies an LUID that changes each time the token is modified. An application can use this value as a test of whether a security context has changed since it was last used.

TokenSource

Specifies a TOKEN_SOURCE structure identifying the agency that issued the token. This information is used in audit logging.

See Also

LUID, TOKEN_DEFAULT_DACL, TOKEN_GROUPS, TOKEN_INFORMATION_CLASS, TOKEN_OWNER, TOKEN_PRIMARY_GROUP, TOKEN_PRIVILEGES, TOKEN_SOURCE, TOKEN_STATISTICS, TOKEN_TYPE, TOKEN_USER


TOKEN_DEFAULT_DACL
 TOKEN_DEFAULT_DACL  QuickInfo

typedef struct _TOKEN_DEFAULT_DACL {  // tdd

    PACL DefaultDacl;

} TOKEN_DEFAULT_DACL;

The TOKEN_DEFAULT_DACL structure specifies a discretionary access-control list (ACL).

Members

DefaultDacl

Points to an ACL structure assigned by default to any objects created by the user represented by the access token.

Remarks

The GetTokenInformation function retrieves the default discretionary ACL for an access token, in the form of a TOKEN_DEFAULT_DACL structure. This structure is also used with the SetTokenInformation function to set the default discretionary ACL.

See Also

ACL, GetTokenInformation, SetTokenInformation, TOKEN_CONTROL, TOKEN_GROUPS, TOKEN_INFORMATION_CLASS, TOKEN_OWNER, TOKEN_PRIMARY_GROUP, TOKEN_PRIVILEGES, TOKEN_SOURCE, TOKEN_STATISTICS, TOKEN_TYPE, TOKEN_USER


TOKEN_GROUPS
 TOKEN_GROUPS  QuickInfo

typedef struct _TOKEN_GROUPS { // tg

    DWORD GroupCount;

    SID_AND_ATTRIBUTES Groups[ANYSIZE_ARRAY];

} TOKEN_GROUPS;

The TOKEN_GROUPS structure contains information about a set of groups in an access token.

Members

GroupCount

Specifies the number of groups in the access token.

Groups

Specifies an array of SID_AND_ATTRIBUTES structures containing a token's group security identifiers (SIDs) and corresponding attributes.

The following attributes can be used with this parameter:

Value	Meaning
SE_GROUP_MANDATORY	The group cannot be disabled.
SE_GROUP_ENABLED_BY_DEFAULT	The group is enabled by default.
SE_GROUP_ENABLED	The group is enabled.
SE_GROUP_OWNER	The user is the owner of the group or the SID can be assigned as the owner of the token or objects.
SE_GROUP_LOGON_ID	The group is a logon identifier.
See Also

AdjustTokenGroups, SID_AND_ATTRIBUTES, TOKEN_CONTROL, TOKEN_DEFAULT_DACL, TOKEN_INFORMATION_CLASS, TOKEN_OWNER, TOKEN_PRIMARY_GROUP, TOKEN_PRIVILEGES, TOKEN_SOURCE, TOKEN_STATISTICS, TOKEN_TYPE, TOKEN_USER


TOKEN_OWNER
 TOKEN_OWNER  QuickInfo

typedef struct _TOKEN_OWNER { // to

    PSID Owner;

} TOKEN_OWNER;

The TOKEN_OWNER structure contains the default owner SID that will be applied to newly created objects.

Members

Owner

Points to a SID structure representing a user who will become the owner of any objects created by a process using this access token. The security identifier (SID) must be one of the user or group SIDs already in the token.

See Also

GetTokenInformation, SetTokenInformation, SID, TOKEN_CONTROL, TOKEN_DEFAULT_DACL, TOKEN_GROUPS, TOKEN_INFORMATION_CLASS, TOKEN_PRIMARY_GROUP, TOKEN_PRIVILEGES, TOKEN_SOURCE, TOKEN_STATISTICS, TOKEN_TYPE, TOKEN_USER


TOKEN_PRIMARY_GROUP
 TOKEN_PRIMARY_GROUP  QuickInfo

typedef struct _TOKEN_PRIMARY_GROUP { // tpg

    PSID PrimaryGroup;

} TOKEN_PRIMARY_GROUP;

The TOKEN_PRIMARY_GROUP structure specifies a group security identifier (SID) for an access token.

Members

PrimaryGroup

Points to a SID structure representing a group that will become the primary group of any objects created by a process using this access token. The security identifier (SID) must be one of the group SIDs already in the token.

See Also

GetTokenInformation, SetTokenInformation, SID, TOKEN_CONTROL, TOKEN_DEFAULT_DACL, TOKEN_GROUPS, TOKEN_INFORMATION_CLASS, TOKEN_OWNER, TOKEN_PRIVILEGES, TOKEN_SOURCE, TOKEN_STATISTICS, TOKEN_TYPE, TOKEN_USER


TOKEN_PRIVILEGES
 TOKEN_PRIVILEGES  QuickInfo

typedef struct _TOKEN_PRIVILEGES { // tp

    DWORD PrivilegeCount;

    LUID_AND_ATTRIBUTES Privileges[ANYSIZE_ARRAY];

} TOKEN_PRIVILEGES;

The TOKEN_PRIVILEGES structure contains information about the set of privileges for an access token.

Members

PrivilegeCount

Specifies the number of privileges in the token.

Privileges

Specifies an array of LUID_AND_ATTRIBUTES structures describing the token's privileges.

The following attributes can be used with this parameter:

Attribute	Description
SE_PRIVILEGE_ENABLED_BY_DEFAULT
	The privilege is enabled by default.
SE_PRIVILEGE_ENABLED
	The privilege is enabled.
SE_PRIVILEGE_USED_FOR_ACCESS
	The privilege was used to gain access to an object or service. This flag is used to identify the relevant privileges in a set passed by a client application that may contain unnecessary privileges.
See Also

AdjustTokenPrivileges, GetTokenInformation, PrivilegeCheck, PrivilegedServiceAuditAlarm, SetTokenInformation, LUID_AND_ATTRIBUTES, PRIVILEGE_SET, TOKEN_CONTROL, TOKEN_DEFAULT_DACL, TOKEN_GROUPS, TOKEN_INFORMATION_CLASS, TOKEN_OWNER, TOKEN_PRIMARY_GROUP, TOKEN_SOURCE, TOKEN_STATISTICS, TOKEN_TYPE, TOKEN_USER


TOKEN_SOURCE
 TOKEN_SOURCE  QuickInfo

typedef struct _TOKEN_SOURCE { // ts

    CHAR SourceName[8];

    LUID SourceIdentifier;

} TOKEN_SOURCE;

The TOKEN_SOURCE structure identifies the source of an access token.

Members

SourceName

Specifies an eight-byte character string used to identify the source of an access token. This is used to distinguish between such sources as Session Manager, LAN Manager, and RPC Server. A string, rather than a constant, is used to identify the source so users and developers can make extensions to the system, such as by adding other networks, that act as the source of access tokens.

SourceIdentifier

Specifies a locally unique identifier (LUID) provided by the source component named by the SourceName member. This value aids the source component in relating context blocks, such as session-control structures, to the token. This value is typically, but not necessarily, an LUID.

See Also

GetTokenInformation, LUID, TOKEN_CONTROL, TOKEN_DEFAULT_DACL, TOKEN_GROUPS, TOKEN_INFORMATION_CLASS, TOKEN_OWNER, TOKEN_PRIMARY_GROUP, TOKEN_PRIVILEGES, TOKEN_STATISTICS, TOKEN_TYPE, TOKEN_USER


TOKEN_STATISTICS
 TOKEN_STATISTICS  QuickInfo

typedef struct _TOKEN_STATISTICS { // tst

    LUID  TokenId;

    LUID  AuthenticationId;

    LARGE_INTEGER ExpirationTime;

    TOKEN_TYPE    TokenType;

    SECURITY_IMPERSONATION_LEVEL ImpersonationLevel;

    DWORD DynamicCharged;

    DWORD DynamicAvailable;

    DWORD GroupCount;

    DWORD PrivilegeCount;

    LUID  ModifiedId;

} TOKEN_STATISTICS;

The TOKEN_STATISTICS structure contains information about an access token. An application can retrieve this information by calling the GetTokenInformation function.

Members

TokenId

Specifies a locally unique identifier (LUID) that identifies this instance of the token object.

AuthenticationId

Specifies an LUID assigned to the session this token represents. There can be many tokens representing a single logon session.

ExpirationTime

Specifies the time at which this token expires. Expiration times for access tokens are not supported in the current version of Windows NT.

TokenType

Specifies a TOKEN_TYPE enumerated type indicating whether the token is a primary or impersonation token.

ImpersonationLevel

Specifies a SECURITY_IMPERSONATION_LEVEL enumerated type indicating the impersonation level of the token. This member is valid only if the TokenType is TokenImpersonation.

DynamicCharged

Specifies the amount, in bytes, of memory allocated for storing default protection and a primary group identifier.

DynamicAvailable

Specifies the portion of memory allocated for storing default protection and a primary group identifier not already in use. This value is returned as a count of free bytes.

GroupCount

Specifies the number of supplemental group security identifiers (SIDs) included in the token.

PrivilegeCount

Specifies the number of privileges included in the token.

ModifiedId

Specifies an LUID that changes each time the token is modified. An application can use this value as a test of whether a security context has changed since it was last used.

See Also

GetTokenInformation, LUID, SECURITY_IMPERSONATION_LEVEL, TOKEN_CONTROL, TOKEN_DEFAULT_DACL, TOKEN_GROUPS, TOKEN_INFORMATION_CLASS, TOKEN_OWNER, TOKEN_PRIMARY_GROUP, TOKEN_PRIVILEGES, TOKEN_SOURCE, TOKEN_TYPE, TOKEN_USER


TOKEN_USER
 TOKEN_USER  QuickInfo

typedef struct _TOKEN_USER { // tu

    SID_AND_ATTRIBUTES User;

} TOKEN_USER;

The TOKEN_USER structure identifies the user associated with an access token.

Members

User

Specifies an SID_AND_ATTRIBUTES structure representing the user associated with the access token. There are currently no attributes defined for user security identifiers (SIDs).

See Also

GetTokenInformation, SID_AND_ATTRIBUTES, TOKEN_CONTROL, TOKEN_DEFAULT_DACL, TOKEN_GROUPS, TOKEN_INFORMATION_CLASS, TOKEN_OWNER, TOKEN_PRIMARY_GROUP, TOKEN_PRIVILEGES, TOKEN_SOURCE, TOKEN_STATISTICS, TOKEN_TYPE


TOOLINFO [New - Windows NT]
 TOOLINFO  QuickInfo  Overview  Group

[New - Windows NT]

typedef struct {  // ti

    UINT      cbSize;

    UINT      uFlags;

    HWND      hwnd;

    UINT      uId;

    RECT      rect;

    HINSTANCE hinst;

    LPTSTR     lpszText;

} TOOLINFO, NEAR *PTOOLINFO, FAR *LPTOOLINFO;

The TOOLINFO structure contains information about a tool in a tooltip control.

Members

cbSize

Size, in bytes, of the TOOLINFO structure. This member must be specified.

uFlags

A set of bit flags. This member can be a combination of the following values:

Value	Meaning
TTF_IDISHWND	Indicates that the uId member is the window handle to the tool. If this flag is not set, uId is the identifier of the tool.
TTF_CENTERTIP	Centers the tooltip window below the tool specified by the uId member.
TTF_RTLREADING	Windows 95 only: Displays text using right-to-left reading order on Hebrew or Arabic systems.
TTF_SUBCLASS	Indicates that the tooltip control should subclass the tool's window to intercept messages, such as WM_MOUSEMOVE. If not set, you need to use the TTM_RELAYEVENT message to forward messages to the tooltip control. For a list of messages that a tooltip control processes, see TTM_RELAYEVENT.
hwnd

Handle to the window that contains the tool. If lpszText includes the LPSTR_TEXTCALLBACK value, this member identifies the window that receives TTN_NEEDTEXT notification messages.

uId

Application-defined identifier of the tool. If uFlags includes the TTF_IDISHWND value, uId must specify the window handle to the tool.

rect

Coordinates of the bounding rectangle of the tool. The coordinates are relative to the upper-left corner of the client area of the window identified by hwnd. If uFlags includes the TTF_IDISHWND value, this member is ignored.

hinst

Handle to the instance that contains the string resource for the tool. If lpszText specifies the identifier of a string resource, this member is used.

lpszText

Pointer to the buffer that contains the text for the tool, or identifier of the string resource that contains the text. If this member is set to the LPSTR_TEXTCALLBACK value, the control sends the TTN_NEEDTEXT notification message to the owner window to retrieve the text.

See Also

TTN_NEEDTEXT


TOOLTIPTEXT [New - Windows NT]
 TOOLTIPTEXT  QuickInfo  Overview  Group

[New - Windows NT]

typedef struct { // ttt

    NMHDR     hdr;

    LPTSTR    lpszText;

    char      szText[80];

    HINSTANCE hinst;

    UINT      uFlags;

} TOOLTIPTEXT, FAR *LPTOOLTIPTEXT;

The TOOLTIPTEXT structure identifies a tool for which text is to be displayed and receives the text for the tool.

Members

hdr

Required for all WM_NOTIFY messages.

lpszText

Pointer to a string that contains or receives the text for a tool. If hinst specifies an instance handle, this member must be the identifier of a string resource.

szText

Buffer that receives the tooltip text. An application can copy the text to this buffer as an alternative to specifying a string address or string resource.

hinst

Handle to the instance that contains a string resource to be used as the tooltip text. If lpszText is the pointer to the tooltip text, this member is NULL.

uFlags

Flag that indicates how to interpret the idFrom member of the NMHDR structure that is included in the structure. If this member is the TTF_IDISHWND value, idFrom is the handle of the tool. Otherwise, idFrom is the identifier of the tool.

Windows 95 only: If this member is the TTF_RTLREADING value, then text on Hebrew or Arabic systems is displayed using right-to-left reading order.

Remarks

This structure is used with the TTN_NEEDTEXT notification message.

See Also

NMHDR, TTN_NEEDTEXT, WM_NOTIFY


TPMPARAMS [New - Windows 95]
 TPMPARAMS  QuickInfo  Overview  Group

[New - Windows 95]

typedef struct tagTPMPARAMS {

    UINT cbSize;

    RECT rcExclude;

} TPMPARAMS, FAR *LPTPMPARAMS;

The TPMPARAMS structure contains extended parameters for the TrackPopupMenuEx function.

Members

cbsize

Size of structure, in bytes.

rcExclude

Rectangle to exclude when positioning the window, in screen coordinates.

See Also

TrackPopupMenuEx, Rectangle


TRANSMIT_FILE_BUFFERS [New - Windows NT]
 TRANSMIT_FILE_BUFFERS  QuickInfo

[New - Windows NT]

typedef struct _TRANSMIT_FILE_BUFFERS {

    PVOID Head;

    DWORD HeadLength;

    PVOID Tail;

    DWORD TailLength;

} TRANSMIT_FILE_BUFFERS;

The TRANSMIT_FILE_BUFFERS structure specifies data to be transmitted before and after file data during a TransmitFile function file transfer operation.

Members

Head

Pointer to a buffer that contains data to be transmitted before the file data is transmitted.

HeadLength

Specifies the number of bytes of data in the buffer pointed to by the Head member that are to be transmitted.

Tail

Pointer to a buffer that contains data to be transmitted after the file data is transmitted.

TailLength

Specifies the number of bytes of data in the buffer pointed to by the Tail member that are to be transmitted.

See Also

TransmitFile


TTHITTESTINFO [New - Windows NT]
 TTHITTESTINFO  QuickInfo  Overview  Group

[New - Windows NT]

typedef struct _TT_HITTESTINFO { // tthti

    HWND hwnd;

    POINT pt;

    TOOLINFO ti;

} TTHITTESTINFO, FAR * LPHITTESTINFO;

The TTHITTESTINFO structure contains information that a tooltip control uses to determine whether a point is in the bounding rectangle of the specified tool. If the point is in the rectangle, the structure receives information about the tool.

Members

hwnd

Handle to the tool or window with the specified tool.

pt

Client coordinates of the point to test.

ti

Receives information about the specified tool.

Remarks

This structure is used with the TTM_HITTEST message.

See Also

TTM_HITTEST


TTPOLYCURVE
 TTPOLYCURVE  QuickInfo

typedef struct tagTTPOLYCURVE { // ttpc

    WORD    wType;

    WORD    cpfx;

    POINTFX apfx[1];

} TTPOLYCURVE, FAR* LPTTPOLYCURVE;

The TTPOLYCURVE structure contains information about a curve in the outline of a TrueType character.

Members

wType

Specifies the type of curve described by the structure. This member can be one of the following values:

Value	Meaning
TT_PRIM_LINE	Curve is a polyline.
TT_PRIM_QSPLINE	Curve is a Bézier spline.
cpfx

Specifies the number of POINTFX structures in the array.

apfx

Specifies an array of POINTFX structures that define the polyline or Bézier spline.

Remarks

When an application calls the GetGlyphOutline function, a glyph outline for a TrueType character is returned in a TTPOLYGONHEADER structure, followed by as many TTPOLYCURVE structures as are required to describe the glyph. All points are returned as POINTFX structures and represent absolute positions, not relative moves. The starting point given by the pfxStart member of the TTPOLYGONHEADER structure is the point at which the outline for a contour begins. The TTPOLYCURVE structures that follow can be either polyline records or spline records.

Polyline records are a series of points; lines drawn between the points describe the outline of the character. Spline records represent the quadratic curves (that is, quadratic b-splines) used by TrueType.

See Also

GetGlyphOutline, POINTFX, TTPOLYGONHEADER


TTPOLYGONHEADER
 TTPOLYGONHEADER  QuickInfo

typedef struct _TTPOLYGONHEADER { // ttph

    DWORD   cb;

    DWORD   dwType;

    POINTFX pfxStart;

} TTPOLYGONHEADER, FAR* LPTTPOLYGONHEADER;

The TTPOLYGONHEADER structure specifies the starting position and type of a contour in a TrueType character outline.

Members

cb

Specifies the number of bytes required by the TTPOLYGONHEADER structure and TTPOLYCURVE structure or structures required to describe the contour of the character.

dwType

Specifies the type of character outline returned. Currently, this value must be TT_POLYGON_TYPE.

pfxStart

Specifies the starting point of the contour in the character outline.

Remarks

Each TTPOLYGONHEADER structure is followed by one or more TTPOLYCURVE structures.

See Also

POINTFX, TTPOLYCURVE


TV_DISPINFO [New - Windows NT]
 TV_DISPINFO  QuickInfo  Overview  Group

[New - Windows NT]

typedef struct _TV_DISPINFO {  tvdi

    NMHDR   hdr;

    TV_ITEM item;

} TV_DISPINFO;

The TV_DISPINFO structure retrieves and sets information about a tree-view item.

Members

hdr

Required for all WM_NOTIFY messages.

item

TV_ITEM structure that identifies and contains information about the tree-view item. The mask member specifies which information is being set or retrieved; it can be one or more of the following values:

Value	Meaning
TVIF_CHILDREN	The iChildren member specifies, or is to receive, the number of child items associated with the item.
TVIF_IMAGE	The iImage member specifies, or is to receive, the index of the item's icon in the image list.
TVIF_SELECTEDIMAGE	The iSelectedImage member specifies, or is to receive, the index of the item's icon in the image list.
TVIF_TEXT	The pszText member specifies the new item text or the pointer to a buffer that is to receive the item text.
If the structure is receiving item text, you typically copy the text to the buffer pointed to by the pszText member of the TV_ITEM structure. However, you can return a string in the pszText member instead. If you do so, you cannot change or delete the string until the corresponding item text is deleted or until two additional TVN_GETDISPINFO notification messages have been sent.

Remarks

A tree-view control sends a notification message to retrieve or set an item's text if the pszText member of the item's TV_ITEM structure is the LPSTR_TEXTCALLBACK value. A tree-view control sends a notification message to retrieve or set an item's icon or small icon if the iImage or iSelectedImage member of the TV_ITEM structure is the I_IMAGECALLBACK value. A tree-view control sends a notification message to retrieve or set an item's state flags if the corresponding bits are set in the control's state callback mask.

The notification mesages are sent only if the parent window is responsible for maintaining certain information. The TV_ITEM structure is used with the TVN_GETDISPINFO and TVN_SETDISPINFO notification messages.

See Also

TV_ITEM, TVN_GETDISPINFO, TVN_SETDISPINFO


TV_HITTESTINFO [New - Windows NT]
 TV_HITTESTINFO  QuickInfo  Overview  Group

[New - Windows NT]

typedef struct _TVHITTESTINFO {  tvhtst

    POINT     pt;

    UINT      flags;

    HTREEITEM hItem;

} TV_HITTESTINFO, FAR *LPTV_HITTESTINFO;

The TV_HITTESTINFO structure contains information used to determine the location of a point relative to a tree-view control.

Members

pt

Client coordinates of point to test.

flags

Variable that receives information about the results of a hit test. This member can be one or more of the following values:

Value	Meaning
TVHT_ABOVE	Above the client area
TVHT_BELOW	Below the client area
TVHT_NOWHERE	In the client area, but below the last item
TVHT_ONITEM	On the bitmap or label associated with an item
TVHT_ONITEMBUTTON	On the button associated with an item
TVHT_ONITEMICON	On the bitmap associated with an item
TVHT_ONITEMINDENT	In the indentation associated with an item
TVHT_ONITEMLABEL	On the label (string) associated with an item
TVHT_ONITEMRIGHT	In the area to the right of an item
TVHT_ONITEMSTATEICON	On the state icon for a tree-view item that is in a user-defined state
TVHT_TOLEFT	To the right of the client area
TVHT_TORIGHT	To the left of the client area
hItem

Handle to the item that occupies the point.

Remarks

This structure is used with the TVM_HITTEST message.

See Also

TVM_HITTEST


TV_INSERTSTRUCT [New - Windows NT]
 TV_INSERTSTRUCT  QuickInfo  Overview  Group

[New - Windows NT]

typedef struct _TV_INSERTSTRUCT {  tvins

    HTREEITEM hParent;

    HTREEITEM hInsertAfter;

    TV_ITEM   item;

} TV_INSERTSTRUCT, FAR *LPTV_INSERTSTRUCT;

The TV_INSERTSTRUCT structure contains information used to add a new item to a tree-view control.

Members

hParent

Handle to the parent item. If this member is the TVI_ROOT value or NULL, the item is inserted at the root of the tree-view control.

hInsertAfter

Handle to the item after which the new item is to be inserted or one of the following values:

Value	Meaning
TVI_FIRST	Inserts the item at the beginning of the list.
TVI_LAST	Inserts the item at the end of the list.
TVI_SORT	Inserts the item into the list in alphabetical order.
item

Information about the item to add.

Remarks

This structure is used with the TVM_INSERTITEM message.

See Also

TVM_INSERTITEM


TV_ITEM [New - Windows NT]
 TV_ITEM  QuickInfo  Overview  Group

[New - Windows NT]

typedef struct _TV_ITEM {  tvi

    UINT       mask;

    HTREEITEM  hItem;

    UINT       state;

    UINT       stateMask;

    LPSTR      pszText;

    int        cchTextMax;

    int        iImage;

    int        iSelectedImage;

    int        cChildren;

    LPARAM     lParam;

} TV_ITEM, FAR *LPTV_ITEM;

The TV_ITEM structure specifies or receives attributes of a tree-view item.

Members

mask

Array of flags that indicate which of the other structure members contain valid data or which are to be filled in. This member can be a combination of the following values:

Value	Meaning
TVIF_CHILDREN	The cChildren member is valid.
TVIF_IMAGE	The iImage member is valid.
TVIF_PARAM	The lParam member is valid.
TVIF_SELECTEDIMAGE	The iSelectedImage member is valid.
TVIF_STATE	The state and stateMask members are valid.
TVIF_TEXT	The pszText and cchTextMax members are valid.
hItem

Item to which this structure refers.

state and stateMask

Variables specifying the current state of the item and the valid states of the item. This member can be any valid combination of state values. For a list of item states, see Tree-View Control Constants.

pszText

Pointer to a null-terminated string that contains the item text if the structure specifies item attributes. If this member is the LPSTR_TEXTCALLBACK value, the parent window is responsible for storing the name. In this case, the tree-view control sends the parent window a TVN_GETDISPINFO notification message when it needs the item text for displaying, sorting, or editing and a TVN_SETDISPINFO notification message when the item text changes.

If the structure is receiving item attributes, this member is the pointer to the buffer that receives the item text.

cchTextMax

Size of the buffer pointed to by the pszText member if the structure is receiving item attributes. If the structure specifies item attributes, this member is ignored.

iImage and iSelectedImage

Indices of the icon image and the selected icon image within the image list. If either member is the I_IMAGECALLBACK value, the parent window is responsible for storing the corresponding images. In this case, the tree-view control sends the parent a TVN_GETDISPINFO notification message when it needs to display the images and a TVN_SETDISPINFO notification message when the images change.

cChildren

Flag indicating whether the item has associated child items. It is one if the item has one or more child items; otherwise, it is zero. If this member is the I_CHILDRENCALLBACK value, the parent window is responsible for drawing the child items. In this case, the tree-view control sends the parent a TVN_GETDISPINFO notification message when it needs to display the child items and a TVN_SETDISPINFO notification message when the attributes of a child item change.

lParam

32-bit value to associate with the item.

Remarks

This structure is used with the TVM_GETITEM, TVM_SETITEM, and TVM_INSERTITEM messages. It is also included with many of the notification messages. When the structure is used to retrieve item information, only the structure members indicated by mask contain valid data. All other members are invalid.

See Also

TVN_GETDISPINFO, TVM_GETITEM, TVM_INSERTITEM, TVN_SETDISPINFO, TVM_SETITEM


TV_KEYDOWN [New - Windows NT]
 TV_KEYDOWN  QuickInfo  Overview  Group

[New - Windows NT]

pedef struct _TV_KEYDOWN { tvkd

    NMHDR hdr;

    WORD  wVKey;

    UINT  flags;

} TV_KEYDOWN;

The TV_KEYDOWN structure contains information about a keyboard event in a tree-view control.

Members

hdr

Required for all WM_NOTIFY messages.

sVKey

Virtual key code.

flags

Always zero.

Remarks

This structure is used with the TVN_KEYDOWN notification message.

See Also

TVN_KEYDOWN


TV_SORTCB [New - Windows NT]
 TV_SORTCB  QuickInfo  Overview  Group

[New - Windows NT]

typedef struct _TV_SORTCB { tvscb

    HTREEITEM    hParent;

    PFNTVCOMPARE lpfnCompare;

    LPARAM       lParam;

} TV_SORTCB, FAR *LPTV_SORTCB;

The TV_SORTCB structure contains information used to sort child items in a tree-view control.

Members

lpfnCompare

Pointer to an application-defined callback function, which is called during a sort operation each time the relative order of two list items needs to be compared. The callback function has the following form:

int CALLBACK CompareFunc(LPARAM lParam1, LPARAM lParam2,

LPARAM lParamSort);

The callback function must return a negative value if the first item should precede the second, a positive value if the first item should follow the second, or zero if the two items are equivalent.

The lParam1 and lParam2 parameters correspond to the lParam member of the TV_ITEM structure for the two items being compared. The lParamSort parameter corresponds to the lParam member of the TV_SORTCB structure that was passed with the TVM_SORTCHILDRENCB message.

hParent

Handle to the parent item.

lParam

Application-defined 32-bit value.

Remarks

This structure is used with the TVM_SORTCHILDRENCB message.

See Also

TV_ITEM, TVM_SORTCHILDRENCB


UDACCEL [New - Windows NT]
 UDACCEL  QuickInfo  Overview  Group

[New - Windows NT]

typedef struct {

    UINT nSec;

    UINT nInc;

} UDACCEL;

The UDACCEL structure contains acceleration information for an up-down control.

Members

nSec

Amount of elapsed time, in seconds, before the position change increment specified by nInc is used.

nInc

Position change increment to use after the time specified by nSec elapses.


ULARGE_INTEGER
 ULARGE_INTEGER  QuickInfo

typedef struct _ULARGE_INTEGER { // uli

    DWORD LowPart;

    DWORD HighPart;

} ULARGE_INTEGER;

The ULARGE_INTEGER structure is used to specify a 64-bit unsigned integer value.

Members

LowPart

Specifies the low-order 32 bits.

HighPart

Specifies the high-order 32 bits.

See Also

LARGE_INTEGER


UNIVERSAL_NAME_INFO
 UNIVERSAL_NAME_INFO  QuickInfo

typedef struct _UNIVERSAL_NAME_INFO { /* uni */

    LPTSTR  lpUniversalName;

} UNIVERSAL_NAME_INFO;

The UNIVERSAL_NAME_INFO structure contains a pointer to a Universal Naming Convention (UNC) name string.

Members

lpUniversalName

Points to a zero-terminated UNC name string.

Remarks

A universal form of a path identifies a network resource in an unambiguous, computer-independent manner. The path can then be passed to processes on other computers, allowing those processes to obtain access to the network resource.

Universal Naming Convention (UNC) names look like this:

\\servername\sharename\path\file

See Also

WNetGetUniversalName, REMOTE_NAME_INFO


UNLOAD_DLL_DEBUG_INFO
 UNLOAD_DLL_DEBUG_INFO  QuickInfo

typedef struct _UNLOAD_DLL_DEBUG_INFO { // uddi

    LPVOID lpBaseOfDll;

} UNLOAD_DLL_DEBUG_INFO;

The UNLOAD_DLL_DEBUG_INFO structure contains information about a dynamic-link library (DLL) that has just been unloaded.

Members

lpBaseOfDll

Points to the base address of the DLL in the address space of the process unloading the DLL.

See Also

DEBUG_EVENT


USEROBJECTFLAGS [New - Windows NT]
 USEROBJECTFLAGS  QuickInfo  Overview  Group

[New - Windows NT]

typedef struct tagUSEROBJECTFLAGS {

    BOOL fInherit;

    BOOL fReserved;

    DWORD dwFlags;

} USEROBJECTFLAGS;

The USEROBJECTFLAGS structure contains information about a window station or desktop handle.

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 flag:

Value	Description
WSF_VISIBLE	Window station has visible display surfaces.
For desktops, the dwFlags member can contain the following desktop control flag:

Value	Description
DF_ALLOWOTHERACCOUNTHOOK	Allows processes running in other accounts on the desktop to set hooks in this process.
See Also

CreateDesktop, GetUserObjectInformation, OpenDesktop, OpenInputDesktop,SetUserObjectInformation


Var
 Var  QuickInfo

Var {

    WCHAR szKey[];

    BYTE  Padding[];

    Var   Value[];

};

The Var structure depicts the organization of data in a file-version resource. This structure is not a true C data 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 Win32 Software Development Kit (SDK).

The Var structure contains version information not dependent on a particular language and code page.

Members

szKey

Specifies an arbitrary 7-bit ASCII English string. The szKey member can be the following value:

Value	Meaning
Translation	Value contains an array of doubleword values indicating the language and code-page combinations supported by this file. The high-order word of each doubleword contains a Microsoft language identifier and the low-order word contains the IBM® code-page number. Either high-order or low-order word may be zero, indicating that the file is language or code-page independent. If this block is omitted, the file will be interpreted as language and code-page independent.
Padding

Contains as many zero bytes as necessary to align the Value member on a 32-bit boundary.

Value

Specifies a list of zero or more Var structures.

Remarks

The Children member of the VS_VERSION_INFO structure may contain zero or more Var structures.

See Also

VarFileInfo, VS_VERSION_INFO


VarFileInfo
 VarFileInfo  QuickInfo

VarFileInfo {

    WCHAR szKey[];

    BYTE  Padding[];

    Var   Children[];

};

The VarFileInfo structure depicts the organization of data in a file-version resource. This structure is not a true C data 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 Win32 Software Development Kit (SDK).

The VarFileInfo structure contains version information not dependent on a particular language and code page.

Members

szKey

Contains "VarFileInfo".

Padding

Contains as many zero bytes as necessary to align the Children member on a 32-bit boundary.

Children

Specifies a list of zero or more Var structures.

Remarks

The Children member of the VS_VERSION_INFO structure may contain zero or more VarFileInfo structures.

See Also

Var, VS_VERSION_INFO


VERIFY_INFORMATION
 VERIFY_INFORMATION  QuickInfo  Overview  Group

typedef struct _VERIFY_INFORMATION {

   LARGE_INTEGER  StartingOffset;

   DWORD  Length;

} VERIFY_INFORMATION ;

The VERIFY_INFORMATION structure provides information used to logically format a disk extent.

Members

StartingOffset

Specifies the starting offset of the disk extent.

Length

Length, in bytes, of the disk extent.

Remarks

The DeviceIoControl function uses a VERIFY_INFORMATION structure as input to an IOCTL_DISK_VERIFY device I/O operation.

See Also

DeviceIoControl, IOCTL_DISK_VERIFY


VS_FIXEDFILEINFO
 VS_FIXEDFILEINFO  QuickInfo

typedef struct _VS_FIXEDFILEINFO {  // vsffi

    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;

} VS_FIXEDFILEINFO;

The VS_FIXEDFILEINFO structure contains version information about a file. This information is language and code-page independent.

Members

dwSignature

Contains the value 0xFEEFO4BD. This is used with the szKey member of VS_VERSION_INFO data 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. This value must be greater than 0x00000029.

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_VERSION_INFO 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_UNKNOWN	The operating system for which the file was designed is unknown to Windows.
VOS_DOS	The file was designed for MS-DOS.
VOS_OS216	The file was designed for 16-bit OS/2.
VOS_OS232	The file was designed for 32-bit OS/2.
VOS_NT	The file was designed for Windows NT.
VOS_WINDOWS16	The file was designed for 16-bit Windows.
VOS_PM16	The file was designed for 16-bit Presentation Manager.
VOS_PM32	The file was designed for 32-bit Presentation Manager.
VOS_WINDOWS32	The file was designed for the Win32 API.
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 the Win32 API running on MS-DOS.
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.
VOS_NT_WINDOWS32	The file was designed for the Win32 API running on Windows NT.
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 Windows.
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 Windows.
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 Windows.
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.

Remarks

The Value member of the VS_VERSION_INFO data is a VS_FIXEDFILEINFO structure.

See Also

StringFileInfo, VS_VERSION_INFO


VS_VERSION_INFO
 VS_VERSION_INFO  QuickInfo

VS_VERSION_INFO {

    WORD  wLength;

    WORD  wValueLength;

    WORD  bText;

    WCHAR szKey[];

    BYTE  Padding1[];

    VS_FIXEDFILEINFO Value;

    BYTE  Padding2[];

    BYTE  Children[];

};

The VS_VERSION_INFO structure depicts the organization of data in a file-version resource. This structure is not a true C data 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 Win32 Software Development Kit (SDK).

Members

wLength

Specifies the length of the VS_VERSION_INFO structure. This length does not include any padding that aligns the subsequent version structure on a 32-bit boundary.

wValueLength

Specifies the length of the Value member. This value is zero if there is no Value member associated with the current version structure.

bText

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 "VS_VERSION_INFO".

Padding1

Contains as many zero bytes 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 structure. The wValueLength member specifies the length of this member; if wValueLength is zero, this member does not exist.

Padding2

Contains as many zero bytes as necessary to align the Children member on a 32-bit boundary. These bytes are not included in wValueLength.

Children

Specifies a list of zero or more StringFileInfo or VarFileInfo structures (or both) that are children of the current version structure.

Remarks

The VS_VERSION_INFO structure is the root structure that contains all other file information structures.

See Also

StringFileInfo, VarFileInfo, VS_FIXEDFILEINFO


WIN32_FIND_DATA
 WIN32_FIND_DATA  QuickInfo

typedef struct _WIN32_FIND_DATA { // wfd

    DWORD dwFileAttributes;

    FILETIME ftCreationTime;

    FILETIME ftLastAccessTime;

    FILETIME ftLastWriteTime;

    DWORD    nFileSizeHigh;

    DWORD    nFileSizeLow;

    DWORD    dwReserved0;

    DWORD    dwReserved1;

    TCHAR    cFileName[ MAX_PATH ];

    TCHAR    cAlternateFileName[ 14 ];

} WIN32_FIND_DATA;

The WIN32_FIND_DATA structure describes a file found by the FindFirstFile or FindNextFile function.

Members

dwFileAttributes

Specifies the file attributes of the file found. This member can be one or more of the following values:

Value	Meaning
FILE_ATTRIBUTE_ARCHIVE
	The file is an archive file. Applications use this value to mark files for backup or removal.
FILE_ATTRIBUTE_COMPRESSED
	The file or directory is compressed. For a file, this means that all of the data in the file is compressed. For a directory, this means that compression is the default for newly created files and subdirectories.
FILE_ATTRIBUTE_DIRECTORY
	The file is a directory.
FILE_ATTRIBUTE_HIDDEN
	The file is hidden. It is not included in an ordinary directory listing.
FILE_ATTRIBUTE_NORMAL
	The file has no other attributes set. This value is valid only if used alone.
FILE_ATTRIBUTE_READONLY
	The file is read-only. Applications can read the file but cannot write to it or delete it.
FILE_ATTRIBUTE_SYSTEM
	The file is part of the operating system or is used exclusively by it.
FILE_ATTRIBUTE_TEMPORARY
	The file is being used for temporary storage. Applications should write to the file only if absolutely necessary. Most of the file's data remains in memory without being flushed to the media because the file will soon be deleted.
ftCreationTime

Specifies a FILETIME structure containing the time the file was created. FindFirstFile and FindNextFile report file times in Coordinated Universal Time (UTC) format. These functions set the FILETIME members to zero if the file system containing the file does not support this time member. You can use the FileTimeToLocalFileTime function to convert from UTC to local time, and then use the FileTimeToSystemTime function to convert the local time to a SYSTEMTIME structure containing individual members for the month, day, year, weekday, hour, minute, second, and millisecond.

ftLastAccessTime

Specifies a FILETIME structure containing the time that the file was last accessed. The time is in UTC format; the FILETIME members are zero if the file system does not support this time member.

ftLastWriteTime

Specifies a FILETIME structure containing the time that the file was last written to. The time is in UTC format; the FILETIME members are zero if the file system does not support this time member.

nFileSizeHigh

Specifies the high-order DWORD value of the file size, in bytes. This value is zero unless the file size is greater than MAXDWORD. The size of the file is equal to (nFileSizeHigh * MAXDWORD) + nFileSizeLow.

nFileSizeLow

Specifies the low-order DWORD value of the file size, in bytes.

dwReserved0

Reserved for future use.

dwReserved1

Reserved for future use.

cFileName

A null-terminated string that is the name of the file.

cAlternateFileName

A null-terminated string that is an alternative name for the file. This name is in the classic 8.3 (filename.ext) filename format.

Remarks

If a file has a long filename, the complete name appears in the cFileName field, and the 8.3 format truncated version of the name appears in the cAlternateFileName field.

See Also

FindFirstFile, FindNextFile, FILETIME, FileTimeToLocalFileTime, FileTimeToSystemTime


WIN32_STREAM_ID
 WIN32_STREAM_ID  QuickInfo

struct WIN32_STREAM_ID {

    DWORD dwStreamId;

    DWORD dwStreamAttributes;

    LARGE_INTEGER Size;

    DWORD dwStreamNameSize;

    WCHAR  cStreamName[ ] ;

}

Members

dwStreamId

Specifies the type of data. This member can be one of the following values:

Value	Meaning
BACKUP_DATA	Standard data
BACKUP_EA_DATA	Extended attribute data
BACKUP_SECURITY_DATA	Windows NT security descriptor data
BACKUP_ALTERNATE_DATA	Alternative data streams
BACKUP_LINK	Hard link information
dwStreamAttributes

Specifies the attributes of data to facilitate cross-operating system transfer. This member must be one or more of the following values:

Value	Description
STREAM_MODIFIED_WHEN_READ	Attribute set if the stream contains data that is modified when read. Allows the backup application to know that verification of data will fail.
STREAM_CONTAINS_SECURITY	Stream contains security data (general attributes). Allows the stream to be ignored on cross-operations restore.
Size

Specifies the size, in bytes, of data. Note that this is a 64-bit value.

dwStreamNameSize

Specifies the length of the name of the alternative data stream.

cStreamName

Specifies the name of the alternative data stream, in Unicode™.

See Also

BackupRead, BackupSeek, BackupWrite


WINDOW_BUFFER_SIZE_RECORD
 WINDOW_BUFFER_SIZE_RECORD  QuickInfo  Overview  Group

typedef struct _WINDOW_BUFFER_SIZE_RECORD { // wbsr

    COORD dwSize;

} WINDOW_BUFFER_SIZE_RECORD;

The WINDOW_BUFFER_SIZE_RECORD structure is used in a console INPUT_RECORD structure to report changes in the size of the screen buffer.

Members

dwSize

Specifies the new size of the screen buffer, in character cell columns and rows.

Remarks

Buffer size events are placed in the input buffer when the console is in window-aware mode (ENABLE_WINDOW_INPUT).

See Also

INPUT_RECORD, ReadConsoleInput


WINDOWPLACEMENT
 WINDOWPLACEMENT  QuickInfo

typedef struct _WINDOWPLACEMENT {     // wndpl

    UINT  length;

    UINT  flags;

    UINT  showCmd;

    POINT ptMinPosition;

    POINT ptMaxPosition;

    RECT  rcNormalPosition;

} WINDOWPLACEMENT;

The WINDOWPLACEMENT structure contains information about the placement of a window on the screen.

Members

length

Specifies the length, in bytes, of the structure. Before calling the GetWindowPlacement or SetWindowPlacement functions, set this member to sizeof(WINDOWPLACEMENT).

Windows 95 only: GetWindowPlacement and SetWindowPlacement fail if this member is not set correctly.

flags

Specifies flags that control the position of the minimized window and the method by which the window is restored. This member can be one or both of the following values:

Value	Meaning
WPF_RESTORETOMAXIMIZED
	Specifies that the restored window will be maximized, regardless of whether it was maximized before it was minimized. This setting is only valid the next time the window is restored. It does not change the default restoration behavior. This flag is only valid when the SW_SHOWMINIMIZED value is specified for the showCmd member.
WPF_SETMINPOSITION
	Specifies that the coordinates of the minimized window may be specified. This flag must be specified if the coordinates are set in the ptMinPosition member.
showCmd

Specifies the current show state of the window. This member can be one of the following values:

Value	Meaning
SW_HIDE	Hides the window and activates another window.
SW_MINIMIZE	Minimizes the specified window and activates the top-level window in the system's list.
SW_RESTORE	Activates and displays a window. If the window is minimized or maximized, Windows restores it to its original size and position (same as SW_SHOWNORMAL).
SW_SHOW	Activates a window and displays it in its current size and position.
SW_SHOWMAXIMIZED	Activates a window and displays it as a maximized window.
SW_SHOWMINIMIZED	Activates a window and displays it as an icon.
SW_SHOWMINNOACTIVE	Displays a window as an icon. The active window remains active.
SW_SHOWNA	Displays a window in its current state. The active window remains active.
SW_SHOWNOACTIVATE	Displays a window in its most recent size and position. The active window remains active.
SW_SHOWNORMAL	Activates and displays a window. If the window is minimized or maximized, Windows restores it to its original size and position (same as SW_RESTORE).
ptMinPosition

Specifies the coordinates of the window's upper-left corner when the window is minimized.

ptMaxPosition

Specifies the coordinates of the window's upper-left corner when the window is maximized.

rcNormalPosition

Specifies the window's coordinates when the window is in the restored position.

See Also

ShowWindow, POINT, RECT


WINDOWPOS
 WINDOWPOS  QuickInfo

typedef struct _WINDOWPOS { // wp

    HWND hwnd;

    HWND hwndInsertAfter;

    int  x;

    int  y;

    int  cx;

    int  cy;

    UINT flags;

} WINDOWPOS;

The WINDOWPOS structure contains information about the size and position of a window.

Members

hwnd

Identifies the window.

hwndInsertAfter

Specifies the position of the window in Z order (front-to-back position). This member can be the handle of the window behind which this window is placed, or can be one of the special values listed with the SetWindowPos function.

x

Specifies the position of the left edge of the window.

y

Specifies the position of the top edge of the window.

cx

Specifies the window width, in pixels.

cy

Specifies the window height, in pixels.

flags

Specifies the window position. This member can be one of the following values:

Value	Meaning
SWP_DRAWFRAME	Draws a frame (defined in the window's class description) around the window. The window receives a WM_NCCALCSIZE message.
SWP_HIDEWINDOW	Hides the window.
SWP_NOACTIVATE	Does not activate the window.
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 has been 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_NOSIZE	Retains the current size (ignores the cx and cy parameters).
SWP_NOREDRAW	Does not redraw changes.
SWP_NOREPOSITION	Same as the SWP_NOOWNERZORDER flag.
SWP_NOZORDER	Retains the current Z order (ignores the hwndInsertAfter member).
SWP_SHOWWINDOW	Displays the window.
See Also

EndDeferWindowPos, SetWindowPos, WM_NCCALCSIZE


WNDCLASS
 WNDCLASS  QuickInfo

typedef struct _WNDCLASS {    // wc

    UINT    style;

    WNDPROC lpfnWndProc;

    int     cbClsExtra;

    int     cbWndExtra;

    HANDLE  hInstance;

    HICON   hIcon;

    HCURSOR hCursor;

    HBRUSH  hbrBackground;

    LPCTSTR lpszMenuName;

    LPCTSTR lpszClassName;

} WNDCLASS;

The WNDCLASS structure contains the window class attributes that are registered by the RegisterClass function.

Members

style

Specifies the class style(s). Styles can be combined by using the bitwise OR (|) operator. This member can be any combination of the following values:

Value	Action
CS_BYTEALIGNCLIENT	Aligns the window's client area on the byte boundary (in the x direction) to enhance performance during drawing operations. This style affects the width of the window and its horizontal position on the display.
CS_BYTEALIGNWINDOW	Aligns a window on a byte boundary (in the x direction) to enhance performance during operations that involve moving or sizing the window. This style affects the width of the window and its horizontal position on the display.
CS_CLASSDC	Allocates one device context to be shared by all windows in the class. Because window classes are process specific, it is possible for multiple threads of a multithreaded 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 operating system allows only one of the threads to successfully finish its drawing operation.
CS_DBLCLKS	Sends double-click messages to the window procedure when the user double-clicks the mouse while the cursor is within a window belonging to the class.
CS_GLOBALCLASS	Allows an application to create a window of the class regardless of the value of the hInstance parameter passed to the CreateWindow or CreateWindowEx function. If you do not specify this style, the hInstance parameter passed to the CreateWindow (or CreateWindowEx) function must be the same as the hInstance parameter passed to the RegisterClass function.
	You can create a global class by creating the window class in a dynamic-link library (DLL) and listing the name of the DLL in the registry under the following keys:
	HKEY_LOCAL_MACHINE\Software \Microsoft\Windows NT\ CurrentVersion\Windows\APPINIT_DLLS
	Whenever a process starts, the operating system loads the specified DLLs in the context of the newly started process before calling the main function in that process. The DLL must register the class during its initialization procedure and must specify the CS_GLOBALCLASS style.
CS_HREDRAW	Redraws the entire window if a movement or size adjustment changes the width of the client area.
CS_NOCLOSE	Disables the Close command on the System menu.
CS_OWNDC	Allocates a unique device context for each window in the class.
CS_PARENTDC	Specifies that child windows inherit their parent window's device context. Specifying CS_PARENTDC enhances an application's performance. When an application calls the GetDC function, passing the handle of a window that belongs to a class with the CS_PARENTDC style, the operating system searches for a device context that has been precalculated for the window's parent window. If all child windows of a particular parent window specify this style, the system need not recalculate a device context for any of the child windows.
CS_SAVEBITS	Saves, as a bitmap, the portion of the screen image obscured by a window. Windows uses the saved bitmap to re-create the screen image when the window is removed. Windows displays the bitmap at its original location and does not send WM_PAINT messages to windows obscured by the window if the memory used by the bitmap has not been discarded and if other screen actions have not invalidated the stored image. This style is useful for small windows (for example, menus or dialog boxes) that are displayed briefly and then removed before other screen activity takes place. This style increases the time required to display the window, because the operating system must first allocate memory to store the bitmap.
CS_VREDRAW	Redraws the entire window if a movement or size adjustment changes the height of the client area.
lpfnWndProc

Points to the window procedure. For more information, see WindowProc.

cbClsExtra

Specifies the number of extra bytes to allocate following the window-class structure. The operating system initializes the bytes to zero.

cbWndExtra

Specifies the number of extra bytes to allocate following the window instance. The operating system initializes the bytes to zero. If an application uses the WNDCLASS structure to register a dialog box created by using the CLASS directive in the resource file, it must set this member to DLGWINDOWEXTRA.

hInstance

Identifies the instance that the window procedure of this class is within.

hIcon

Identifies the class icon. This member must be a handle of an icon resource. If this member is NULL, an application must draw an icon whenever the user minimizes the application's window.

hCursor

Identifies the class cursor. This member must be a handle of a cursor resource. If this member is NULL, an application must explicitly set the cursor shape whenever the mouse moves into the application's window.

hbrBackground

Identifies 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 operating system automatically deletes class background brushes when the class is freed. An application should not delete these brushes, because a class may be used by multiple instances of an application.

When this member is NULL, an application must paint its own background whenever it is requested to paint in its client area. To determine whether the background must be painted, an application can either process the WM_ERASEBKGND message or test the fErase member of the PAINTSTRUCT structure filled by the BeginPaint function.

lpszMenuName

Points 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

Points to a null-terminated string or is an atom. If this parameter is an atom, it must be a global atom created by a previous call to the GlobalAddAtom function. The atom, a 16-bit value, must be in the low-order word of lpszClassName; the high-order word must be zero.

If lpszClassName is a string, it specifies the window class name.

See Also

BeginPaint, CreateWindow, CreateWindowEx, GetDC, GlobalAddAtom, MAKEINTRESOURCE, PAINTSTRUCT, RegisterClass, WindowProc, WM_PAINT


WNDCLASSEX
 WNDCLASSEX  QuickInfo

typedef struct _WNDCLASSEX {    // wc

    UINT    cbSize;

    UINT    style;

    WNDPROC lpfnWndProc;

    int     cbClsExtra;

    int     cbWndExtra;

    HANDLE  hInstance;

    HICON   hIcon;

    HCURSOR hCursor;

    HBRUSH  hbrBackground;

    LPCTSTR lpszMenuName;

    LPCTSTR lpszClassName;

    HICON   hIconSm;

} WNDCLASSEX;

The WNDCLASSEX structure contains window class information. It is used with the 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.

Windows NT: The hIconSm member is not used. Set it to NULL before calling RegisterClassEx. It will be NULL when GetClassInfoEx returns.

Members

cbSize

Specifies the size, in bytes, of this structure. Set this member to sizeof(WINDOWCLASSEX). Be sure to set this member before calling the GetClassInfoEx function.

style

Specifies the class style(s). Styles can be combined by using the bitwise OR (|) operator. This member can be any combination of the following values:

Value	Action
CS_BYTEALIGNCLIENT	Aligns the window's client area on the byte boundary (in the x direction) to enhance performance during drawing operations. This style affects the width of the window and its horizontal position on the display.
CS_BYTEALIGNWINDOW	Aligns a window on a byte boundary (in the x direction) to enhance performance during operations that involve moving or sizing the window. This style affects the width of the window and its horizontal position on the display.
CS_CLASSDC	Allocates one device context to be shared by all windows in the class. Because window classes are process specific, it is possible for multiple threads of a multithreaded 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 operating system allows only one of the threads to successfully finish its drawing operation.
CS_DBLCLKS	Sends double-click messages to the window procedure when the user double-clicks the mouse while the cursor is within a window belonging to the class.
CS_GLOBALCLASS	Allows an application to create a window of the class regardless of the value of the hInstance parameter passed to the CreateWindow or CreateWindowEx function. If you do not specify this style, the hInstance parameter passed to the CreateWindow (or CreateWindowEx) function must be the same as the hInstance parameter passed to the RegisterClass function.
	You can create a global class by creating the window class in a dynamic-link library (DLL) and listing the name of the DLL in the registry under the following keys:
	HKEY_LOCAL_MACHINE\Software \Microsoft\Windows NT\ CurrentVersion\Windows\APPINIT_DLLS
	Whenever a process starts, the operating system loads the specified DLLs in the context of the newly started process before calling the main function in that process. The DLL must register the class during its initialization procedure and must specify the CS_GLOBALCLASS style.
CS_HREDRAW	Redraws the entire window if a movement or size adjustment changes the width of the client area.
CS_NOCLOSE	Disables the Close command on the System menu.
CS_OWNDC	Allocates a unique device context for each window in the class.
CS_PARENTDC	Specifies that child windows inherit their parent window's device context. Specifying CS_PARENTDC enhances an application's performance. When an application calls the GetDC function, passing the handle of a window that belongs to a class with the CS_PARENTDC style, the operating system searches for a device context that has been precalculated for the window's parent window. If all child windows of a particular parent window specify this style, the system need not recalculate a device context for any of the child windows.
CS_SAVEBITS	Saves, as a bitmap, the portion of the screen image obscured by a window. Windows uses the saved bitmap to re-create the screen image when the window is removed. Windows displays the bitmap at its original location and does not send WM_PAINT messages to windows obscured by the window if the memory used by the bitmap has not been discarded and if other screen actions have not invalidated the stored image. This style is useful for small windows (for example, menus or dialog boxes) that are displayed briefly and then removed before other screen activity takes place. This style increases the time required to display the window, because the operating system must first allocate memory to store the bitmap.
CS_VREDRAW	Redraws the entire window if a movement or size adjustment changes the height of the client area.
lpfnWndProc

Points to the window procedure. For more information, see WindowProc.

cbClsExtra

Specifies the number of extra bytes to allocate following the window-class structure. The operating system initializes the bytes to zero.

cbWndExtra

Specifies the number of extra bytes to allocate following the window instance. The operating system initializes the bytes to zero. If an application uses the WNDCLASS structure to register a dialog box created by using the CLASS directive in the resource file, it must set this member to DLGWINDOWEXTRA.

hInstance

Identifies the instance that the window procedure of this class is within.

hIcon

Identifies the class icon. This member must be a handle of an icon resource. If this member is NULL, an application must draw an icon whenever the user minimizes the application's window.

hCursor

Identifies the class cursor. This member must be a handle of a cursor resource. If this member is NULL, an application must explicitly set the cursor shape whenever the mouse moves into the application's window.

hbrBackground

Identifies 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 operating system automatically deletes class background brushes when the class is freed. An application should not delete these brushes, because a class may be used by multiple instances of an application.

When this member is NULL, an application must paint its own background whenever it is requested to paint in its client area. To determine whether the background must be painted, an application can either process the WM_ERASEBKGND message or test the fErase member of the PAINTSTRUCT structure filled by the BeginPaint function.

lpszMenuName

Points 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

Points to a null-terminated string or is an atom. If this parameter is an atom, it must be a global atom created by a previous call to the GlobalAddAtom function. The atom, a 16-bit value, must be in the low-order word of lpszClassName; the high-order word must be zero.

If lpszClassName is a string, it specifies the window class name.

hIconSm

Windows 95: Handle to a small icon that is associated with the window class.

Windows NT: This member is not used. Set it to NULL before calling RegisterClassEx. It will be NULL when GetClassInfoEx returns.

See Also

GetClassInfoEx, RegisterClassEx, WNDCLASS


XFORM
 XFORM  QuickInfo

typedef struct  _XFORM {  // xfrm

    FLOAT eM11;

    FLOAT eM12;

    FLOAT eM21;

    FLOAT eM22;

    FLOAT eDx;

    FLOAT eDy;

} XFORM;

The XFORM structure specifies a world-space to page-space transformation.

Members

eM11

Specifies the following:

Operation	Meaning
Scaling	Horizontal scaling component
Rotation	Cosine of rotation angle
Reflection	Horizontal component
eM12

Specifies the following:

Operation	Meaning
Shear	Horizontal proportionality constant
Rotation	Sine of the rotation angle
eM21

Specifies the following:

Operation	Meaning
Shear	Vertical proportionality constant
Rotation	Negative sine of the rotation angle
eM22

Specifies the following:

Operation	Meaning
Scaling	Vertical scaling component
Rotation	Cosine of rotation angle
Reflection	Vertical reflection component
eDx

Specifies the horizontal translation component.

eDy

Specifies the vertical translation component.

Remarks

The following list describes how the members are used for each operation:

Operation	eM11	eM12	eM21	eM22
Rotation	Cosine	Sine	Negative sine	Cosine
Scaling	Horizontal scaling component	Nothing	Nothing	Vertical Scaling Component
Shear	Nothing	Horizontal Proportionality Constant	Vertical Proportionality Constant	Nothing
Reflection	Horizontal Reflection Component	Nothing	Nothing	Vertical Reflection Component
See Also

ExtCreateRegion, GetWorldTransform, ModifyWorldTransform, PlayEnhMetaFile, SetWorldTransform


ACL_INFORMATION_CLASS
 ACL_INFORMATION_CLASS  QuickInfo

typedef enum _ACL_INFORMATION_CLASS { // aclic

    AclRevisionInformation = 1,    // ACL revision information

    AclSizeInformation             // ACL size information

} ACL_INFORMATION_CLASS;

The ACL_INFORMATION_CLASS enumeration type contains values that specify the type of information being assigned to or retrieved from an access-control list (ACL).

See Also

ACL, ACL_REVISION_INFORMATION, ACL_SIZE_INFORMATION, GetAclInformation, SetAclInformation


MEDIA_TYPE
 MEDIA_TYPE  QuickInfo

typedef enum _MEDIA_TYPE {

    Unknown,                // Format is unknown

    F5_1Pt2_512,            // 5.25", 1.2MB,  512 bytes/sector

    F3_1Pt44_512,           // 3.5",  1.44MB, 512 bytes/sector

    F3_2Pt88_512,           // 3.5",  2.88MB, 512 bytes/sector

    F3_20Pt8_512,           // 3.5",  20.8MB, 512 bytes/sector

    F3_720_512,             // 3.5",  720KB,  512 bytes/sector

    F5_360_512,             // 5.25", 360KB,  512 bytes/sector

    F5_320_512,             // 5.25", 320KB,  512 bytes/sector

    F5_320_1024,            // 5.25", 320KB,  1024 bytes/sector

    F5_180_512,             // 5.25", 180KB,  512 bytes/sector

    F5_160_512,             // 5.25", 160KB,  512 bytes/sector

    RemovableMedia,         // Removable media other than floppy

    FixedMedia              // Fixed hard disk media

} MEDIA_TYPE;

The MEDIA_TYPE enumeration type contains values that specify various forms of device media. The comments above explain the enumerators.

Remarks

The MediaType member of the DISK_GEOMETRY data structure is of type MEDIA_TYPE. The DeviceIoControl function receives a DISK_GEOMETRY structure in response to an IOCTL_DISK_GET_DRIVE_GEOMETRY device I/O operation. The DeviceIoControl function receives an array of DISK_GEOMETRY structures in response to an IOCTL_DISK_GET_MEDIA_TYPES device I/O operation.

See Also

DeviceIoControl, DISK_GEOMETRY, IOCTL_DISK_GET_DRIVE_GEOMETRY, IOCTL_DISK_GET_MEDIA_TYPES


RASCONNSTATE
 RASCONNSTATE  QuickInfo

typedef enum _RASCONNSTATE {

    RASCS_OpenPort = 0,

    RASCS_PortOpened,

    RASCS_ConnectDevice,

    RASCS_DeviceConnected,

    RASCS_AllDevicesConnected,

    RASCS_Authenticate,

    RASCS_AuthNotify,

    RASCS_AuthRetry,

    RASCS_AuthCallback,

    RASCS_AuthChangePassword,

    RASCS_AuthProject,

    RASCS_AuthLinkSpeed,

    RASCS_AuthAck,

    RASCS_ReAuthenticate,

    RASCS_Authenticated,

    RASCS_PrepareForCallback,

    RASCS_WaitForModemReset,

    RASCS_WaitForCallback,
    RASCS_Projected,

#if (WINVER >= 0x400)

    RASCS_StartAuthentication,    // Windows 95 only

    RASCS_CallbackComplete,       // Windows 95 only

    RASCS_LogonNetwork,           // Windows 95 only

#endif

    RASCS_Interactive = RASCS_PAUSED,

    RASCS_RetryAuthentication,

    RASCS_CallbackSetByCaller,

    RASCS_PasswordExpired,

    RASCS_Connected = RASCS_DONE,

    RASCS_Disconnected

} RASCONNSTATE ;

The RASCONNSTATE enumeration type contains values that specify the states that may occur when connecting by using the RasDial function.

A RASCONNSTATE enumerator value is returned as part of a RASCONNSTATUS structure, which is retrieved by calls to the RasGetConnectStatus function.

The enumerator values are listed here in the general order in which the connection states occur. However, you should not write code that depends on the order or occurrence of particular RASCONNSTATE connection states, because this may vary between platforms.

Enumerator	Meaning
RASCS_OpenPort	The communication port is about to be opened.
RASCS_PortOpened	The communication port has been opened successfully.
RASCS_ConnectDevice	A device is about to be connected. RasGetConnectStatus can be called to determine the name and type of the device being connected.
RASCS_DeviceConnected	A device has connected successfully. RasGetConnectStatus can be called to determine the name and type of the device being connected.
	For a simple modem connection, RASCS_ConnectDevice and RASCS_DeviceConnected will be called only once. For a dial-up X.25 PAD connection, the pair will be called first for the modem, then for the PAD. If a preconnect switch is configured, the pair will be called for the switch before any other devices connect. Likewise, the pair will be called for a postconnect switch after any other devices connect. Windows 95: Note that Windows 95 does not currently support multi-stage connections such as the X.25 PAD connection described above.
RASCS_AllDevicesConnected	All devices in the device chain have successfully connected. At this point, the physical link is established.
RASCS_Authenticate	The authentication process is starting. Remote access does not allow the remote client to generate any traffic on the LAN until authentication has been successfully completed.  Remote access authentication on a Windows NT or Windows 95 server consists of: • Validating the username/password on the specified domain.  • Projecting the client onto the LAN. This means that the remote access server does what is necessary to send and receive data on the LAN on behalf of the client. For example, the remote access server might need to add a NetBIOS name that corresponds to the client's computer name.  • Callback processing in which the client hangs up and the server calls back. (The user needs special permissions on the remote access server for this.)  • Calculating the link speed. This is necessary to correctly set transport timeouts to match the relatively slow speed of the remote link.
RASCS_AuthNotify	An authentication event has occurred. If dwError is zero, this event will be immediately followed by one of the more specific authentication states following. If dwError is nonzero, authentication has failed, and the error value indicates why.
RASCS_AuthRetry	The client has requested another validation attempt with a new username/password/domain. This state does not occur in Windows NT version 3.1.
RASCS_AuthCallback	The remote access server has requested a callback number. This occurs only if the user has "Set By Caller" callback privilege on the server.
RASCS_AuthChangePassword	The client has requested to change the password on the account. This state does not occur in Windows NT version 3.1.
RASCS_AuthProject	The projection phase is starting.
RASCS_AuthLinkSpeed	The link-speed calculation phase is starting.
RASCS_AuthAck	An authentication request is being acknowledged.
RASCS_ReAuthenticate	Reauthentication (after callback) is starting.
RASCS_Authenticated	The client has successfully completed authentication.
RASCS_PrepareForCallback	The line is about to disconnect in preparation for callback.
RASCS_WaitForModemReset	The client is delaying in order to give the modem time to reset itself in preparation for callback.
RASCS_WaitForCallback	The client is waiting for an incoming call from the remote access server.
RASCS_Projected	This state occurs after the RASCS_AuthProject state. It indicates that projection result information is available. You can access the projection result information by calling RasGetProjectionInfo.
RASCS_StartAuthentication	Windows 95 only: Indicates that user authentication is being initiated or retried.
RASCS_CallbackComplete	Windows 95 only: Indicates that the client has been called back and is about to resume authentication.
RASCS_LogonNetwork	Windows 95 only: Indicates that the client is logging on to the network.
RASCS_Interactive	This state corresponds to the terminal state supported by RASPHONE.EXE. This state does not occur in Windows NT version 3.1.
RASCS_RetryAuthentication	This state corresponds to the retry authentication state supported by RASPHONE.EXE. This state does not occur in Windows NT version 3.1.
RASCS_CallbackSetByCaller	This state corresponds to the Callback state supported by RASPHONE.EXE. This state does not occur in Windows NT version 3.1.
RASCS_PasswordExpired	This state corresponds to the change password state supported by RASPHONE.EXE. This state does not occur in Windows NT version 3.1.
RASCS_Connected	Successful connection.
RASCS_Disconnected	Disconnection or failed connection.
Remarks

The connection process states are divided into three classes: running states, paused states, and terminal states.

An application can easily determine the class of a specific state by performing Boolean bit operations with the RASCS_PAUSED and RASCS_DONE bitmasks. Here are some examples:

fDoneState = (state & RASCS_DONE);

fPausedState = (state & RASCS_PAUSED);

fRunState = !(fDoneState || fPausedState);

See Also

RasDial, RasGetConnectStatus, RasGetProjectionInfo, RASCONNSTATUS


RASPROJECTION
 RASPROJECTION  QuickInfo  Overview  Group

typedef enum _RASPROJECTION {

    RASP_Amb = 0x10000,

    RASP_PppNbf = 0x803F,

    RASP_PppIpx = 0x802B,

    RASP_PppIp = 0x8021

} RASPROJECTION ;

The RASPROJECTION enumeration type defines values that specify a particular authentication protocol or Point-to-Point Protocol control protocol (PPP). An application passes a value of this type to the RasGetProjectionInfo function to specify the protocol of interest.

Each of the RASPROJECTION enumerators has a corresponding data structure; the RasGetProjectionInfo function returns the specified information in a structure of that type.

Value	Meaning
RASP_Amb	Specifies the Authentication Message Block (AMB) authentication protocol. AMB is a NetBIOS-based protocol used to authenticate with downlevel remote access servers ( all those prior to Windows NT 3.5). The corresponding data structure is a RASAMB.
RASP_PppNbf	Specifies the NetBEUI Framer (NBF) protocol. NBFCP is a PPP network control protocol used to negotiate the parameters necessary to ship NetBEUI packets on a WAN link. The corresponding data structure is a RASPPPNBF.
RASP_PppIpx	Specifies the Internetwork Packet Exchange (IPX) control protocol. IPXCP is a PPP network control protocol used to negotiate the parameters necessary to ship IPX packets on a WAN link. The corresponding data structure is a RASPPPIPX.
RASP_PppIp	Specifies the Internet Protocol (IP) control protocol. IPCP is a PPP network control protocol used to negotiate the parameters necessary to ship IP packets on a WAN link.  The corresponding data structure is a RASPPPIP.
See Also

RasGetProjectionInfo, RASAMB, RASPPPIP, RASPPPIPX, RASPPPNBF


SECURITY_IMPERSONATION_LEVEL
 SECURITY_IMPERSONATION_LEVEL  QuickInfo

typedef enum _SECURITY_IMPERSONATION_LEVEL { // sil

    SecurityAnonymous,

    SecurityIdentification,

    SecurityImpersonation,

    SecurityDelegation

} SECURITY_IMPERSONATION_LEVEL;

The SECURITY_IMPERSONATION_LEVEL enumeration type contains values that specify security impersonation levels. Security impersonation levels govern the degree to which a server process can act on behalf of a client process.

Value	Meaning
SecurityAnonymous	The server process cannot obtain identification information about the client and it cannot impersonate the client. It is defined with no value given, and thus, by ANSI C rules, defaults to a value of 0.
SecurityIdentification	The server process can obtain information about the client, such as security identifiers and privileges, but it cannot use kernel functions. This is useful for servers that export their own objects — for example, tables and views exported by a database product. Using the retrieved client-security information, the server can make access-validation decisions without being able to utilize other services using the client's security context.
SecurityImpersonation	The server process can impersonate the client's security context on its local system. The server cannot impersonate the client on remote systems.
SecurityDelegation	This impersonation level is not supported in the current version of Windows NT.
Remarks

Impersonation is the ability of a process to take on the security attributes of another process.

See Also

CreatePrivateObjectSecurity, DuplicateToken, GetTokenInformation, ImpersonateSelf, OpenThreadToken


SID_NAME_USE
 SID_NAME_USE  QuickInfo

typedef enum _SID_NAME_USE {

    SidTypeUser = 1,

    SidTypeGroup,

    SidTypeDomain,

    SidTypeAlias,

    SidTypeWellKnownGroup,

    SidTypeDeletedAccount,

    SidTypeInvalid,

    SidTypeUnknown

} SID_NAME_USE;

The SID_NAME_USE enumeration type contains values that specify the type of a security identifier (SID).

Value	Meaning
SidTypeUser	Indicates a user SID.
SidTypeGroup	Indicates a group SID.
SidTypeDomain	Indicates a domain SID.
SidTypeAlias	Indicates an alias SID.
SidTypeWellKnownGroup	Indicates an SID for a well-known group.
SidTypeDeletedAccount	Indicates an SID for a deleted account.
SidTypeInvalid	Indicates an invalid SID.
SidTypeUnknown	Indicates an unknown SID type.
See Also

LookupAccountName, LookupAccountSid


TOKEN_INFORMATION_CLASS
 TOKEN_INFORMATION_CLASS  QuickInfo

typedef enum _TOKEN_INFORMATION_CLASS { // tic

    TokenUser = 1,

    TokenGroups,

    TokenPrivileges,

    TokenOwner,

    TokenPrimaryGroup,

    TokenDefaultDacl,

    TokenSource,

    TokenType,

    TokenImpersonationLevel,

    TokenStatistics

} TOKEN_INFORMATION_CLASS;

The TOKEN_INFORMATION_CLASS enumeration type contains values that specify the type of information being assigned to or retrieved from an access token.

See Also

GetTokenInformation, SetTokenInformation, TOKEN_CONTROL, TOKEN_DEFAULT_DACL, TOKEN_GROUPS, TOKEN_OWNER, TOKEN_PRIMARY_GROUP, TOKEN_PRIVILEGES, TOKEN_SOURCE, TOKEN_STATISTICS, TOKEN_TYPE, TOKEN_USER


TOKEN_TYPE
 TOKEN_TYPE  QuickInfo

typedef enum tagTOKEN_TYPE { // tt

    TokenPrimary = 1,

    TokenImpersonation

} TOKEN_TYPE;

The TOKEN_TYPE enumeration type contains values that differentiate between a primary token and an impersonation token.

See Also

GetTokenInformation, TOKEN_CONTROL, TOKEN_DEFAULT_DACL, TOKEN_GROUPS, TOKEN_INFORMATION_CLASS, TOKEN_OWNER, TOKEN_PRIMARY_GROUP, TOKEN_PRIVILEGES, TOKEN_SOURCE, TOKEN_STATISTICS, TOKEN_USER


Animate_Create [New - Windows NT]
 Animate_Create  QuickInfo  Overview  Group

[New - Windows NT]

The Animate_Create macro creates an animation control. Animate_Create calls the CreateWindow function.

HWND Animate_Create(

HWND  hwndP,
UINT  id,
DWORD  dwStyle,
HINSTANCE  hInstance
);
Parameters

hwndP

Handle to the parent window.

id

Child window identifier of the animation control.

dwStyle

Window styles. For a list of the animation-control style values, see Animation Control Styles.

hInstance

Handle to the instance of the module that is creating the animation control.

Return Value

Returns the handle to the animation control.

Remarks

The Animate_Create macro sets the width and height of the animation control to zero if the ACS_CENTER style is specified. If the ACS_CENTER style is not specified, Animate_Create sets the width and height based on the dimensions of a frame in the AVI clip.

See Also

CreateWindow


CMYK [New - Windows 95]
 CMYK  QuickInfo  Overview  Group

[New - Windows 95]

The CMYK macro creates a CMYK color value by combining the specified cyan, magenta, yellow, and black values.

COLORREF CMYK(

c,
m,
y,
k
);
See Also

GetCValue, GetMValue, GetKValue, GetYValue


FORWARD_WM_NOTIFY [New - Windows NT]
 FORWARD_WM_NOTIFY  QuickInfo  Overview  Group

[New - Windows NT]

The FORWARD_WM_NOTIFY macro sends or posts the WM_NOTIFY message.

VOID FORWARD_WM_NOTIFY(

hwnd,
idFrom,
pnmhdr,
fn
);
Parameters

hwnd

Handle to the window that receives the WM_NOTIFY message.

idFrom

Identifier of the control sending the message.

pnmhdr

Pointer to an NMHDR structure that contains the notification code and additional information. For some notification messages, this parameter points to a larger structure that has the NMHDR structure as its first member.

fn

Function that sends or posts the WM_NOTIFY message. This parameter can be either the SendMessage or PostMessage function.

Return Value

Returns a value whose meaning depends on the fn parameter.

Remarks

The FORWARD_WM_NOTIFY macro is defined as follows:

#define FORWARD_WM_NOTIFY(hwnd, idFrom, pnmhdr, fn) \

    (void)(fn)((hwnd), WM_NOTIFY, (WPARAM)(int)(id), \

    (LPARAM)(NMHDR FAR*)(pnmhdr))

See Also

NMHDR, PostMessage, SendMessage, WM_NOTIFY


GetBValue
 GetBValue  QuickInfo

The GetBValue macro retrieves an intensity value for the blue component of a 32-bit red, green, blue (RGB) value.

BYTE GetBValue(

WORD  rgb	// 32-bit RGB value
);
Parameters

rgb

Specifies an RGB color value.

Return Value

The return value is the intensity of the blue component of the specified RGB color.

Remarks

The intensity value is in the range 0 through 255.

The GetBValue macro is defined as follows:

#define GetBValue(rgb)   ((BYTE) ((rgb) >> 16))

See Also

GetGValue, GetRValue, PALETTEINDEX, PALETTERGB, RGB


GetCValue [New - Windows 95]
 GetCValue  QuickInfo  Overview  Group

[New - Windows 95]

The GetCValue macro retrieves the cyan color value from a CMYK color value.

BYTE GetCValue(

cmyk
);
See Also

CMYK, GetKValue, GetMValue, GetYValue


GetGValue
 GetGValue  QuickInfo

The GetGValue macro retrieves an intensity value for the green component of a 32-bit red, green, blue (RGB) value.

BYTE GetGValue(

DWORD  rgb	// 32-bit RGB value
);
Parameters

rgb

Specifies an RGB color value.

Return Value

The return value is the intensity of the green component of the specified RGB color.

Remarks

The intensity value is in the range 0 through 255.

The GetGValue macro is defined as follows:

#define GetGValue(rgb)   ((BYTE) (((WORD) (rgb)) >> 8))

See Also

GetBValue, GetRValue, PALETTEINDEX, PALETTERGB, RGB


GetKValue [New - Windows 95]
 GetKValue  QuickInfo  Overview  Group

[New - Windows 95]

The GetKValue macro retrieves the black color value from a CMYK color value.

BYTE GetKValue(

cmyk
);
See Also

CMYK, GetCValue, GetMValue, GetYValue


GetMValue [New - Windows 95]
 GetMValue  QuickInfo  Overview  Group

[New - Windows 95]

The GetMValue macro retrieves the magenta color value from a CMYK color value.

BYTE GetMValue(

cmyk
);
See Also

CMYK, GetCValue, GetKValue, GetYValue


GetRValue
 GetRValue  QuickInfo

The GetRValue macro retrieves an intensity value for the red component of a 32-bit red, green, blue (RGB) value.

BYTE GetRValue(

DWORD  rgb	// 32-bit RGB value
);
Parameters

rgb

Specifies an RGB color value.

Return Value

The return value is the intensity of the red component of the specified RGB color.

Remarks

The intensity value is in the range 0 through 255.

The GetRValue macro is defined as follows:

#define GetRValue(rgb)   ((BYTE) (rgb))

See Also

GetBValue, GetGValue, PALETTEINDEX, PALETTERGB, RGB


GetYValue [New - Windows 95]
 GetYValue  QuickInfo  Overview  Group

[New - Windows 95]

The GetYValue macro retrieves the yellow color value from a CMYK color value.

BYTE GetYValue(

cmyk
);
See Also

CMYK, GetCValue, GetMValue, GetKValue,


HANDLE_WM_NOTIFY [New - Windows NT]
 HANDLE_WM_NOTIFY  QuickInfo  Overview  Group

[New - Windows NT]

The HANDLE_WM_NOTIFY macro calls a function that processes the WM_NOTIFY message.

HANDLE_WM_NOTIFY(

hwnd,
wParam,
lParam,
fn
);
Parameters

hwnd

Handle to the window that received WM_NOTIFY.

wParam

First parameter of WM_NOTIFY.

lParam

Second parameter of WM_NOTIFY.

fn

Function that is to process WM_NOTIFY.

Return Value

Returns a value whose meaning depends on the fn parameter.

Remarks

The HANDLE_WM_NOTIFY macro is defined as follows:

#define HANDLE_WM_NOTIFY(hwnd, wParam, lParam, fn) \

    (fn)((hwnd), (int)(wParam), (NMHDR FAR*)(lParam))

See Also

WM_NOTIFY


HIBYTE
 HIBYTE  QuickInfo

The HIBYTE macro retrieves the high-order byte from the given 16-bit value.

BYTE HIBYTE(

WORD  wValue	// value from which high-order byte is retrieved
);
Parameters

wValue

Specifies the value to be converted.

Return Value

The return value is the high-order byte of the specified value.

Remarks

The HIBYTE macro is defined as follows:

#define HIBYTE(w)   ((BYTE) (((WORD) (w) >> 8) & 0xFF))

See Also

HIWORD, LOBYTE


HIWORD
 HIWORD  QuickInfo

The HIWORD macro retrieves the high-order word from the given 32-bit value.

WORD HIWORD(

DWORD  dwValue	// value from which high-order word is retrieved
);
Parameters

dwValue

Specifies the value to be converted.

Return Value

The return value is the high-order word of the specified value.

Remarks

The HIWORD macro is defined as follows:

#define HIWORD(l)   ((WORD) (((DWORD) (l) >> 16) & 0xFFFF))

See Also

HIBYTE, LOWORD


INDEXTOOVERLAYMASK [New - Windows NT]
 INDEXTOOVERLAYMASK  QuickInfo  Overview  Group

[New - Windows NT]

The INDEXTOOVERLAYMASK macro prepares the index of an overlay mask so that the ImageList_Draw function can use it.

UINT INDEXTOOVERLAYMASK(

UINT  iOverlay	//
);
Parameters

iOverlay

Index of an overlay mask.

Remarks

The INDEXTOOVERLAYMASK macro is defined as follows:

#define INDEXTOOVERLAYMASK(i) ((i) << 8)


INDEXTOSTATEIMAGEMASK [New - Windows NT]
 INDEXTOSTATEIMAGEMASK  QuickInfo  Overview  Group

[New - Windows NT]

The INDEXTOSTATEIMAGEMASK macro prepares the index of a state image so that a tree-view control or list-view control can use the index to retrieve the state image for an item.

UINT INDEXTOSTATEIMAGEMASK(

UINT  i
);
Parameters

i

Index of a state image.

Remarks

The INDEXTOSTATEIMAGEMASK macro is defined as follows:

#define INDEXTOSTATEIMAGEMASK(i) ((i) << 12)


LANGIDFROMLCID
 LANGIDFROMLCID  QuickInfo  Overview  Group

The LANGIDFROMLCID macro retrieves a language identifier from a locale identifier.

WORD LANGIDFROMLCID(

LCID  lcid	// locale identifier
);
Parameters

lcid

Specifies the locale identifier. This parameter may have been created by using the MAKELCID macro.

Return Value

The return value is a language identifier.

Remarks

The LANGIDFROMLCID macro is defined as follows:

#define LANGIDFROMLCID(lcid)   ((WORD) (lcid))

See Also

MAKELANGID, MAKELCID, PRIMARYLANGID, SUBLANGID


LOBYTE
 LOBYTE  QuickInfo

The LOBYTE macro retrieves the low-order byte from the given 16-bit value.

BYTE LOBYTE(

WORD  wValue	// value from which low-order byte is retrieved
);
Parameters

wValue

Specifies the value to be converted.

Return Value

The return value is the low-order byte of the specified value.

Remarks

The LOBYTE macro is defined as follows:

#define LOBYTE(w)   ((BYTE) (w))

See Also

HIBYTE, LOWORD


LOWORD
 LOWORD  QuickInfo

The LOWORD macro retrieves the low-order word from the given 32-bit value.

WORD LOWORD(

DWORD  dwValue	// value from which low-order word is retrieved
);
Parameters

dwValue

Specifies the value to be converted.

Return Value

The return value is the low-order word of the specified value.

Remarks

The LOWORD macro is defined as follows:

#define LOWORD(l)   ((WORD) (l))

See Also

HIWORD, LOBYTE


MAKEINTATOM
 MAKEINTATOM  QuickInfo

The MAKEINTATOM macro creates an integer atom that represents a character string of decimal digits.

Integer atoms created by this macro can be added to an atom table by using the AddAtom or GlobalAddAtom function.

LPTSTR MAKEINTATOM(

WORD  wInteger	// integer to make into atom
);
Parameters

wInteger

Specifies the numeric value to be made into an integer atom.

Return Value

The return value is a pointer to the atom created for the given integer.

Remarks

Although the return value of the MAKEINTATOM macro is cast as an LPTSTR value, it cannot be used as a string pointer except when it is passed to atom-management functions that require an LPTSTR argument.

The DeleteAtom and GlobalDeleteAtom functions always succeed for integer atoms, even though they do nothing. The string returned by the GetAtomName and GlobalGetAtomName functions for an integer atom is a null-terminated string in which the first character is a pound sign (#) and the remaining characters are the decimal digits used in the MAKEINTATOM macro.

The MAKEINTATOM macro is defined as follows:

#define MAKEINTATOM(i)   (LPTSTR) ((DWORD) ((WORD) (i)))

See Also

AddAtom, DeleteAtom, GetAtomName, GlobalAddAtom, GlobalDeleteAtom, GlobalGetAtomName


MAKEINTRESOURCE
 MAKEINTRESOURCE  QuickInfo

The MAKEINTRESOURCE macro converts an integer value to a resource type compatible with Win32 resource-management functions. This macro is used in place of a string containing the name of the resource.

LPTSTR MAKEINTRESOURCE(

WORD  wInteger	// integer to convert
);
Parameters

wInteger

Specifies the integer value to be converted.

Return Value

The return value is the specified value in the low-order word and zero in the high-order word.

Remarks

The return value should be passed only to the Win32 resource-management functions, as the lpType parameter.

The MAKEINTRESOURCE macro is defined as follows:

#define MAKEINTRESOURCE(i)  (LPTSTR) ((DWORD) ((WORD) (i)))


MAKELANGID
 MAKELANGID  QuickInfo  Overview  Group

The MAKELANGID macro creates a language identifier from a primary language identifier and a sublanguage identifier.

WORD MAKELANGID(

USHORT  usPrimaryLanguage,	// primary language identifier
USHORT  usSubLanguage	// sublanguage identifier
);
Parameters

usPrimaryLanguage

Specifies the primary language identifier. This parameter can be one of the following values:

LANG_BULGARIAN	LANG_JAPANESE
LANG_CHINESE	LANG_KOREAN
LANG_CROATIAN	LANG_NEUTRAL
LANG_CZECH	LANG_NORWEGIAN
LANG_DANISH	LANG_POLISH
LANG_DUTCH	LANG_PORTUGUESE
LANG_ENGLISH	LANG_ROMANIAN
LANG_FINNISH	LANG_RUSSIAN
LANG_FRENCH	LANG_SLOVAK
LANG_GERMAN	LANG_SLOVENIAN
LANG_GREEK	LANG_SPANISH
LANG_HUNGARIAN	LANG_SWEDISH
LANG_ICELANDIC	LANG_TURKISH
LANG_ITALIAN
Windows 95: In addition to the preceding, Windows 95 also defines the following values:

LANG_AFRIKAANS	LANG_HEBREW
LANG_ALBANIAN	LANG_INDONESIAN
LANG_ARABIC	LANG_LATVIAN
LANG_BASQUE	LANG_LITHUANIAN
LANG_BYELORUSSIAN	LANG_SORBIAN
LANG_CATALAN	LANG_THAI
LANG_ESTONIAN	LANG_UKRANIAN
For a user-defined language, usPrimaryLanguage can be a value in the range 0x0200 to 0x03FF. All other values are reserved for system use.

usSubLanguage

Specifies the sublanguage identifier. This parameter can be one of the following values:

SUBLANG_CHINESE_SIMPLIFIED	SUBLANG_FRENCH_SWISS
SUBLANG_CHINESE_TRADITIONAL	SUBLANG_GERMAN
SUBLANG_CHINESE_HONGKONG	SUBLANG_GERMAN_AUSTRIAN
SUBLANG_CHINESE_SINGAPORE	SUBLANG_GERMAN_SWISS
SUBLANG_DEFAULT	SUBLANG_ITALIAN
SUBLANG_DUTCH	SUBLANG_ITALIAN_SWISS
SUBLANG_DUTCH_BELGIAN	SUBLANG_NEUTRAL
SUBLANG_ENGLISH_AUS	SUBLANG_NORWEGIAN_BOKMAL
SUBLANG_ENGLISH_CAN	SUBLANG_NORWEGIAN_NYNORSK
SUBLANG_ENGLISH_EIRE	SUBLANG_PORTUGUESE
SUBLANG_ENGLISH_NZ	SUBLANG_PORTUGUESE_ BRAZILIAN
SUBLANG_ENGLISH_UK	SUBLANG_SPANISH
SUBLANG_ENGLISH_US	SUBLANG_SPANISH_MEXICAN
SUBLANG_FRENCH	SUBLANG_SPANISH_MODERN
SUBLANG_FRENCH_BELGIAN	SUBLANG_SYS_DEFAULT
SUBLANG_FRENCH_CANADIAN
For a user-defined sublanguage, usSubLanguage can be a value in the range 0x20 to 0x3F. All other values are reserved for system use.

Return Value

The return value is a language identifier that can be used with the FindResourceEx and EnumResLangProc functions.

Remarks

The following three combinations of usPrimaryLanguage and usSubLanguage have special meaning:

Primary language ID	Sublanguage ID	Meaning
LANG_NEUTRAL	SUBLANG_NEUTRAL	Language neutral
LANG_NEUTRAL	SUBLANG_DEFAULT	User default language
LANG_NEUTRAL	SUBLANG_SYS_DEFAULT	System default language
The MAKELANGID macro is defined as follows:

#define MAKELANGID(p, s) ((((WORD) (s)) << 10) | (WORD) (p))

See Also

EnumResLangProc, FindResourceEx, LANGIDFROMLCID, MAKELCID, PRIMARYLANGID, SUBLANGID


MAKELCID
 MAKELCID  QuickInfo  Overview  Group

The MAKELCID macro creates a locale identifier from a language identifier.

DWORD MAKELCID(

WORD  wLanguageID,	// language identifier
WORD  wSortID	// sorting identifier
);
Parameters

wLanguageID

Specifies the language identifier. This parameter is a combination of a primary language identifier and a sublanguage identifier and is usually created by using the MAKELANGID macro.

wSortID

Specifies the sort identifier. Use the value SORT_DEFAULT for this parameter.

Return Value

The return value is a locale identifier.

Remarks

The MAKELCID macro is defined as follows:

#define MAKELCID(lgid, srtid)  \

    ((DWORD)((((DWORD)((WORD  )(srtid))) << 16) |  \

            ((DWORD)((WORD  )(lgid)))))

See Also

LANGIDFROMLCID, MAKELANGID, SORTIDFROMLCID


MAKELONG
 MAKELONG  QuickInfo

The MAKELONG macro creates an unsigned 32-bit value by concatenating two given 16-bit values.

DWORD MAKELONG(

WORD  wLow,	// low-order word of long value
WORD  wHigh	// high-order word of long value
);
Parameters

wLow

Specifies the low-order word of the new long value.

wHigh

Specifies the high-order word of the new long value.

Return Value

The return value is an unsigned 32-bit value.

Remarks

The MAKELONG macro is defined as follows:

#define MAKELONG(a, b) \

    ((LONG) (((WORD) (a)) | ((DWORD) ((WORD) (b))) << 16))


MAKELPARAM
 MAKELPARAM  QuickInfo

The MAKELPARAM macro creates an unsigned 32-bit value for use as an lParam parameter in a message. The macro concatenates two given 16-bit values.

LPARAM MAKELPARAM(

WORD  wLow,	// low-order word
WORD  wHigh	// high-order word
);
Parameters

wLow

Specifies the low-order word of the new long value.

wHigh

Specifies the high-order word of the new long value.

Return Value

The return value is an unsigned 32-bit value.

Remarks

The MAKELPARAM macro is defined as follows:

#define MAKELPARAM(l, h)   ((LPARAM) MAKELONG(l, h))

See Also

MAKELONG, MAKELRESULT, MAKEWPARAM


MAKELRESULT
 MAKELRESULT  QuickInfo

The MAKELRESULT macro creates an unsigned 32-bit value for use as a return value from a window procedure. The macro concatenates two given 16-bit values.

LRESULT MAKELRESULT(

WORD  wLow,	// low-order word
WORD  wHigh	// high-order word
);
Parameters

wLow

Specifies the low-order word of the new long value.

wHigh

Specifies the high-order word of the new long value.

Return Value

The return value is an unsigned 32-bit value.

Remarks

The MAKELRESULT macro is defined as follows:

#define MAKELRESULT(l, h)   ((LRESULT) MAKELONG(l, h))

See Also

MAKELONG, MAKELPARAM, MAKEWPARAM


MAKEPOINTS
 MAKEPOINTS  QuickInfo

The MAKEPOINTS macro converts a value that contains the x- and y-coordinates of a point into a POINTS structure.

POINTS MAKEPOINTS(

DWORD  dwValue	// coordinates of a point
);
Parameters

dwValue

Specifies the coordinates of a point. The x-coordinate is in the low-order word, and the y-coordinate is in the high-order word.

Return Value

The return value is a pointer to a POINTS structure.

Remarks

The MAKEPOINTS macro is defined as follows:

#define MAKEPOINTS(l)   (*((POINTS FAR *) & (l)))

See Also

GetMessagePos


MAKEROP4
 MAKEROP4  QuickInfo

The MAKEROP4 macro creates a quaternary raster operation code for use with the MaskBlt function. The macro takes two ternary raster operation codes as input, one for the foreground and one for the background, and packs their Boolean operation indexes into the high-order word of a 32-bit value. The low-order word of this value will be ignored.

DWORD MAKEROP4(

DWORD  fore,	// foreground ternary raster operation code
DWORD  back	// background ternary raster operation code
);
Parameters

fore

Specifies a foreground ternary raster operation code.

back

Specifies a background ternary raster operation code

Return Value

The return value is a DWORD quaternary raster operation code for use with the MaskBlt function.

Remarks

The MAKEROP4 macro is defined as follows:

#define MAKEROP4(fore,back)

          (DWORD)((((back) << 8) & 0xFF000000) | (fore))

See Also

MaskBlt


MAKEWORD
 MAKEWORD  QuickInfo

The MAKEWORD macro creates an unsigned 16-bit integer by concatenating two given unsigned character values.

WORD MAKEWORD(

BYTE  bLow,	// low-order byte of short value
BYTE  bHigh	// high-order byte of short value
);
Parameters

bLow

Specifies the low-order byte of the new short value.

bHigh

Specifies the high-order byte of the new short value.

Return Value

The return value is an unsigned 16-bit integer value.

Remarks

The MAKEWORD macro is defined as follows:

#define MAKEWORD(a, b) \

    ((WORD) (((BYTE) (a)) | ((WORD) ((BYTE) (b))) << 8))


MAKEWPARAM
 MAKEWPARAM  QuickInfo

The MAKEWPARAM macro creates an unsigned 32-bit value for use as a wParam parameter in a message. The macro concatenates two given 16-bit values.

LPARAM MAKEWPARAM(

WORD  wLow,	// low-order word
WORD  wHigh	// high-order word
);
Parameters

wLow

Specifies the low-order word of the new long value.

wHigh

Specifies the high-order word of the new long value.

Return Value

The return value is an unsigned 32-bit value.

Remarks

The MAKEWPARAM macro is defined as follows:

#define MAKEWPARAM(l, h)   ((LPARAM) MAKELONG(l, h))

See Also

MAKELONG, MAKELPARAM, MAKELRESULT


max
 max  QuickInfo

The max macro compares two values and returns the larger one. The data type can be any numeric data type, signed or unsigned. The data type of the arguments and the return value is the same.

max(

value1,	// low-order word
value2	// high-order word
);
Parameters

value1

Specifies the first of two values.

value2

Specifies the second of two values.

Return Value

The return value is the greater of the two specified values.

Remarks

The max macro is defined as follows:

#define max(a, b)  (((a) > (b)) ? (a) : (b))

See Also

min


min
 min  QuickInfo

The min macro compares two values and returns the smaller one. The data type can be any numeric data type, signed or unsigned. The data type of the arguments and the return value is the same.

min(

value1,
value2
);
Parameters

value1

Specifies the first of two values.

value2

Specifies the second of two values.

Return Value

The return value is the smaller of the two specified values.

Remarks

The min macro is defined as follows:

#define min(a, b)  (((a) < (b)) ? (a) : (b))

See Also

max


PALETTEINDEX
 PALETTEINDEX  QuickInfo

The PALETTEINDEX macro accepts an index to a logical-color palette entry and returns a palette-entry specifier consisting of a 32-bit COLORREF value that specifies the color associated with the given index. An application using a logical color palette can pass this specifier, instead of an explicit red, green, blue (RGB) value, to GDI functions that expect a color. This allows the function to use the color in the specified palette entry.

COLORREF PALETTEINDEX(

WORD  wPaletteIndex	// index to palette entry
);
Parameters

wPaletteIndex

Specifies an index to the palette entry containing the color to be used for a graphics operation.

Return Value

The return value is a logical-palette index specifier.

Remarks

The PALETTEINDEX macro is defined as follows:

#define PALETTEINDEX(i) /

    ((COLORREF) (0x01000000 | (DWORD) (WORD) (i)))

See Also

PALETTERGB, RGB


PALETTERGB
 PALETTERGB  QuickInfo

The PALETTERGB macro accepts three values that represent the relative intensities of red, green, and blue and returns a palette-relative red, green, blue (RGB) specifier consisting of 2 in the high-order byte and an RGB value in the three low-order bytes. An application using a color palette can pass this specifier, instead of an explicit RGB value, to functions that expect a color.

COLORREF PALETTERGB(

BYTE  bRed,	// red component of palette-relative RGB
BYTE  bGreen,	// green component of palette-relative RGB
BYTE  bBlue	// blue component of palette-relative RGB
);
Parameters

bRed

Specifies the intensity of the red color field.

bGreen

Specifies the intensity of the green color field.

bBlue

Specifies the intensity of the blue color field.

Return Value

The return value is a palette-relative RGB specifier. For output devices that support logical palettes, Windows matches a palette-relative RGB value to the nearest color in the logical palette of the device context as though the application had specified an index to that palette entry. If an output device does not support a system palette, Windows uses the palette-relative RGB as though it were a conventional RGB doubleword returned by the RGB macro.

Remarks

The PALETTERGB macro is defined as follows:

#define PALETTERGB(r, g, b)  (0x02000000 | RGB(r, g, b))

See Also

PALETTEINDEX, RGB


POINTSTOPOINT
 POINTSTOPOINT  QuickInfo

The POINTSTOPOINT macro copies the contents of a POINTS structure into a POINT structure.

POINTSTOPOINT(

POINT  pt,	// POINT structure
POINTS  pts	// POINTS structure
);
Parameters

pt

Specifies the POINT structure to receive the contents of the POINTS structure.

pts

Specifies the POINTS structure to copy.

Remarks

The POINTSTOPOINT macro is defined as follows:

#define POINTSTOPOINT(pt, pts) {(pt).x = (SHORT) LOWORD(pts); \

                               (pt).y = (SHORT) HIWORD(pts);}

See Also

MAKEPOINTS, POINTTOPOINTS


POINTTOPOINTS
 POINTTOPOINTS  QuickInfo

The POINTTOPOINTS macro converts a POINT structure to a POINTS structure.

POINTS POINTTOPOINTS(

POINT  pt	// coordinates of a point
);
Parameters

pt

Specifies the POINT structure to convert.

Return Value

The return value is a POINTS structure.

Remarks

The POINTTOPOINTS macro is defined as follows:

#define POINTTOPOINTS(pt) \

    (MAKELONG((short) ((pt).x), (short) ((pt).y)))

See Also

MAKEPOINTS, POINTSTOPOINT


PRIMARYLANGID
 PRIMARYLANGID  QuickInfo

The PRIMARYLANGID macro extracts a primary language identifier from a language identifier.

WORD PRIMARYLANGID(

WORD  lgid	// language identifier
);
Parameters

lgid

Specifies the language identifier. This value is a combination of a primary language identifier and a sublanguage identifier and is usually created by using the MAKELANGID macro.

Return Value

The return value is a primary language identifier. The following primary language identifiers are defined:

LANG_BULGARIAN	LANG_JAPANESE
LANG_CHINESE	LANG_KOREAN
LANG_CROATIAN	LANG_NEUTRAL
LANG_CZECH	LANG_NORWEGIAN
LANG_DANISH	LANG_POLISH
LANG_DUTCH	LANG_PORTUGUESE
LANG_ENGLISH	LANG_ROMANIAN
LANG_FINNISH	LANG_RUSSIAN
LANG_FRENCH	LANG_SLOVAK
LANG_GERMAN	LANG_SLOVENIAN
LANG_GREEK	LANG_SPANISH
LANG_HUNGARIAN	LANG_SWEDISH
LANG_ICELANDIC	LANG_TURKISH
LANG_ITALIAN
Remarks

The PRIMARYLANGID macro is defined as follows:

#define PRIMARYLANGID(lgid)    ((WORD  )(lgid) & 0x3ff)

See Also

LANGIDFROMLCID, MAKELANGID, SUBLANGID


RGB
 RGB  QuickInfo

The RGB macro selects a red, green, blue (RGB) color based on the arguments supplied and the color capabilities of the output device.

COLORREF RGB(

BYTE  bRed,	// red component of color
BYTE  bGreen,	// green component of color
BYTE  bBlue	// blue component of color
);
Parameters

cRed

Specifies the intensity of the red color.

cGreen

Specifies the intensity of the green color.

cBlue

Specifies the intensity of the blue color.

Return Value

The return value is the resultant RGB color.

Remarks

The intensity for each argument is in the range 0 through 255. If all three intensities are zero, the result is black. If all three intensities are 255, the result is white.

For information about using color values in a color palette, see the descriptions of the PALETTEINDEX and PALETTERGB macros.

The RGB macro is defined as follows:

#define RGB(r, g ,b)  ((DWORD) (((BYTE) (r) | \

    ((WORD) (g) << 8)) | \

    (((DWORD) (BYTE) (b)) << 16)))

See Also

PALETTEINDEX, PALETTERGB


SORTIDFROMLCID
 SORTIDFROMLCID  QuickInfo

The SORTIDFROMLCID macro retrieves a sort identifier from a locale identifier.

WORD SORTIDFROMLCID(

LCID  lcid	// locale identifier
);
Parameters

lcid

Specifies the locale identifier. This parameter may have been created by using the MAKELCID macro.

Return Value

The return value is a sort identifier.

Remarks

The SORTIDFROMLCID macro is defined as follows:

#define SORTIDFROMLCID(lcid) \

          ((WORD  )((((DWORD)(lcid)) & NLS_VALID_LOCALE_MASK) >> 16))

The following sort identifiers are defined:

Value	Meaning
SORT_DEFAULT	Specifies the default sort.
SORT_JAPANESE_XJIS	Specifies Japanese XJIS order.
SORT_JAPANESE_UNICODE	Specifies Japanese Unicode order.
SORT_CHINESE_BIG5	Specifies Chinese BIG5 order.
SORT_CHINESE_UNICODE	Specifies Chinese Unicode order.
SORT_KOREAN_KSC	Specifies Korean KSC order.
SORT_KOREAN_UNICODE	Specifies Korean Unicode order.
See Also

MAKELANGID, MAKELCID, PRIMARYLANGID, SUBLANGID


SUBLANGID
 SUBLANGID  QuickInfo

The SUBLANGID macro extracts a sublanguage identifier from a language identifier.

WORD SUBLANGID(

WORD  lgid	// language identifier
);
Parameters

lgid

Specifies the language identifier. This value is a combination of a primary language identifier and a sublanguage identifier and is usually created by using the MAKELANGID macro.

Return Value

The return value is a sublanguage identifier. The following sublanguage identifiers are defined:

SUBLANG_CHINESE_HONGKONG	SUBLANG_FRENCH_SWISS
SUBLANG_CHINESE_SIMPLIFIED	SUBLANG_GERMAN
SUBLANG_CHINESE_SINGAPORE	SUBLANG_GERMAN_AUSTRIAN
SUBLANG_CHINESE_TRADITIONAL	SUBLANG_GERMAN_SWISS
SUBLANG_DEFAULT	SUBLANG_ITALIAN
SUBLANG_DUTCH	SUBLANG_ITALIAN_SWISS
SUBLANG_DUTCH_BELGIAN	SUBLANG_NEUTRAL
SUBLANG_ENGLISH_AUS	SUBLANG_NORWEGIAN_BOKMAL
SUBLANG_ENGLISH_CAN	SUBLANG_NORWEGIAN_NYNORSK
SUBLANG_ENGLISH_EIRE	SUBLANG_PORTUGUESE
SUBLANG_ENGLISH_NZ	SUBLANG_PORTUGUESE_BRAZILIAN
SUBLANG_ENGLISH_UK	SUBLANG_SPANISH
SUBLANG_ENGLISH_US	SUBLANG_SPANISH_MEXICAN
SUBLANG_FRENCH	SUBLANG_SPANISH_MODERN
SUBLANG_FRENCH_BELGIAN	SUBLANG_SYS_DEFAULT
SUBLANG_FRENCH_CANADIAN
Remarks

The SUBLANGID macro is defined as follows:

#define SUBLANGID(lgid)        ((WORD  )(lgid) >> 10)

See Also

LANGIDFROMLCID, MAKELANGID, PRIMARYLANGID


TEXT Macro
 TEXT  QuickInfo

The TEXT macro identifies a string as Unicode when the UNICODE compile flag is used or as an ANSI string when Unicode is not defined.

TEXT(

LPTSTR  string	// address of ANSI or Unicode string
);
Parameters

string

Specifies the string to be interpreted as either Unicode or ANSI.

Remarks

The TEXT macro is defined as follows:

#define TEXT(quote) L##quote


XTYP_ADVDATA
 XTYP_ADVDATA  QuickInfo

XTYP_ADVDATA

A dynamic data exchange (DDE) client callback function receives the XTYP_ADVDATA transaction after establishing an advise loop with a server. This transaction informs the client that the value of the data item has changed.

Parameters

uFmt

Specifies the format atom of the data sent from the server.

hconv

Identifies the conversation.

hsz1

Identifies the topic name.

hsz2

Identifies the item name.

hdata

Identifies the data associated with the topic name and item name pair. This parameter is NULL if the client specified the XTYPF_NODATA flag when it requested the advise loop.

dwData1

Not used.

dwData2

Not used.

Return Value

A DDE callback function should return DDE_FACK if it processes this transaction, DDE_FBUSY if it is too busy to process this transaction, or DDE_FNOTPROCESSED if it rejects this transaction.

Remarks

An application must not free the data handle obtained during this transaction. An application must, however, copy the data associated with the data handle if the application must process the data after the callback function returns. An application can use the DdeGetData function to copy the data.

See Also

DdeClientTransaction, DdeGetData, DdePostAdvise


XTYP_ADVREQ
 XTYP_ADVREQ  QuickInfo

XTYP_ADVREQ

The system sends the XTYP_ADVREQ transaction to a server after the server calls the DdePostAdvise function. This transaction informs the server that an advise transaction is outstanding on the specified topic name and item name pair and that data corresponding to the topic name and item name pair has changed.

Parameters

uFmt

Specifies the format in which the data should be submitted to the client.

hconv

Identifies the conversation.

hsz1

Identifies the topic name.

hsz2

Identifies the item name that has changed.

hdata

Not used.

dwData1

Specifies the count, in the low-order word, of XTYP_ADVREQ transactions that remain to be processed on the same topic, item, and format name set within the context of the current call to the DdePostAdvise function. The count is zero if the current XTYP_ADVREQ transaction is the last one. A server can use this count to determine whether to create an HDATA_APPOWNED data handle for the advise data.

The low-order word is set to CADV_LATEACK if the Dynamic Data Exchange Management Library (DDEML) issued the XTYP_ADVREQ transaction because of a late-arriving DDE_ACK message from a client being outrun by the server.

The high-order word is not used.

dwData2

Not used.

Return Value

The server should first call the DdeCreateDataHandle function to create a data handle that identifies the changed data and then return the handle. The server should return NULL if it is unable to complete the transaction.

Remarks

A server cannot block this transaction type; the CBR_BLOCK return code is ignored.

See Also

DdeCreateDataHandle, DdeInitialize, DdePostAdvise


XTYP_ADVSTART
 XTYP_ADVSTART  QuickInfo

XTYP_ADVSTART

A dynamic data exchange (DDE) server callback function receives the XTYP_ADVSTART transaction when a client specifies XTYP_ADVSTART as the uType parameter of the DdeClientTransaction function. A client uses this transaction to establish an advise loop with a server.

Parameters

uFmt

Specifies the data format requested by the client.

hconv

Identifies the conversation.

hsz1

Identifies the topic name.

hsz2

Identifies the item name.

hdata

Not used.

dwData1

Not used.

dwData2

Not used.

Return Value

A server callback function should return TRUE to allow an advise loop on the specified topic name and item name pair, or FALSE to deny the advise loop. If the callback function returns TRUE, any subsequent calls to the DdePostAdvise function by the server on the same topic name and item name pair causes the system to send XTYP_ADVREQ transactions to the server.

Remarks

If a client requests an advise loop on a topic name, item name, and data format for an advise loop that is already established, the Dynamic Data Exchange Management Library (DDEML) does not create a duplicate advise loop but instead alters the advise loop flags (XTYPF_ACKREQ and XTYPF_NODATA) to match the latest request.

This transaction is filtered if the server application specified the CBF_FAIL_ADVISES flag in the DdeInitialize function.

See Also

DdeClientTransaction, DdeInitialize, DdePostAdvise


XTYP_ADVSTOP
 XTYP_ADVSTOP  QuickInfo

XTYP_ADVSTOP

A dynamic data exchange (DDE) server callback function receives the XTYP_ADVSTOP transaction when a client specifies XTYP_ADVSTOP in the DdeClientTransaction function. A client uses this transaction to end an advise loop with a server.

Parameters

uFmt

Specifies the data format associated with the advise loop being ended.

hconv

Identifies the conversation.

hsz1

Identifies the topic name.

hsz2

Identifies the item name.

hdata

Not used.

dwData1

Not used.

dwData2

Not used.

Remarks

This transaction is filtered if the server application specified the CBF_FAIL_ADVISES flag in the DdeInitialize function.

See Also

DdeClientTransaction, DdeInitialize, DdePostAdvise


XTYP_CONNECT
 XTYP_CONNECT  QuickInfo

XTYP_CONNECT

A dynamic data exchange (DDE) server callback function receives the XTYP_CONNECT transaction when a client specifies a service name that the server supports and a topic name that is not NULL in a call to the DdeConnect function.

Parameters

uFmt

Not used.

hconv

Not used.

hsz1

Identifies the topic name.

hsz2

Identifies the service name.

hdata

Not used.

dwData1

Points to a CONVCONTEXT structure that contains context information for the conversation. If the client is not a Dynamic Data Exchange Management Library (DDEML) application, this parameter is 0.

dwData2

Specifies whether the client is the same application instance as the server. If the parameter is 1, the client is the same instance. If the parameter is 0, the client is a different instance.

Return Value

A server callback function should return TRUE to allow the client to establish a conversation on the specified service name and topic name pair, or the function should return FALSE to deny the conversation. If the callback function returns TRUE and a conversation is successfully established, the system passes the conversation handle to the server by issuing an XTYP_CONNECT_CONFIRM transaction to the server's callback function (unless the server specified the CBF_SKIP_CONNECT_CONFIRMS flag in the DdeInitialize function).

Remarks

This transaction is filtered if the server application specified the CBF_FAIL_CONNECTIONS flag in the DdeInitialize function.

A server cannot block this transaction type; the CBR_BLOCK return code is ignored.

See Also

CONVCONTEXT, DdeConnect, DdeInitialize


XTYP_CONNECT_CONFIRM
 XTYP_CONNECT_CONFIRM  QuickInfo

XTYP_CONNECT_CONFIRM

A dynamic data exchange (DDE) server callback function receives the XTYP_CONNECT_CONFIRM transaction to confirm that a conversation has been established with a client and to provide the server with the conversation handle. The system sends this transaction as a result of a previous XTYP_CONNECT or XTYP_WILDCONNECT transaction.

Parameters

uFmt

Not used.

hconv

Identifies the new conversation.

hsz1

Identifies the topic name on which the conversation has been established.

hsz2

Identifies the service name on which the conversation has been established.

hdata

Not used.

dwData1

Not used.

dwData2

Specifies whether the client is the same application instance as the server. If the parameter is 1, the client is the same instance. If the parameter is 0, the client is a different instance.

Remarks

This transaction is filtered if the server application specified the CBF_SKIP_CONNECT_CONFIRMS flag in the DdeInitialize function.

A server cannot block this transaction type; the CBR_BLOCK return code is ignored.

See Also

DdeConnect, DdeConnectList, DdeInitialize


XTYP_DISCONNECT
 XTYP_DISCONNECT  QuickInfo

XTYP_DISCONNECT

An application's dynamic data exchange (DDE) callback function receives the XTYP_DISCONNECT transaction when the application's partner in a conversation uses the DdeDisconnect function to terminate the conversation.

Parameters

uFmt

Not used.

hconv

Identifies that the conversation was terminated.

hsz1

Not used.

hsz2

Not used.

hdata

Not used.

dwData1

Not used.

dwData2

Specifies whether the partners in the conversation are the same application instance. If this parameter is 1, the partners are the same instance. If this parameter is 0, the partners are different instances.

Remarks

This transaction is filtered if the application specified the CBF_SKIP_DISCONNECTS flag in the DdeInitialize function.

The application can obtain the status of the terminated conversation by calling the DdeQueryConvInfo function while processing this transaction. The conversation handle becomes invalid after the callback function returns.

An application cannot block this transaction type; the CBR_BLOCK return code is ignored.

See Also

DdeDisconnect, DdeInitialize, DdeQueryConvInfo


XTYP_ERROR
 XTYP_ERROR  QuickInfo

XTYP_ERROR

A dynamic data exchange (DDE) callback function receives the XTYP_ERROR transaction when a critical error occurs.

Parameters

uFmt

Not used.

hconv

Identifies the conversation associated with the error. This parameter is NULL if the error is not associated with a conversation.

hsz1

Not used.

hsz2

Not used.

hdata

Not used.

dwData1

Specifies the error code in the low-order word. Currently, only the following error code is supported:

Error Code	Description
DMLERR_LOW_MEMORY	Memory is low; advise, poke, or execute data may be lost, or the system may fail.
dwData2

Not used.

Remarks

An application cannot block this transaction type; the CBR_BLOCK return code is ignored. The DDEML attempts to free memory by removing noncritical resources. An application that has blocked conversations should unblock them.


XTYP_EXECUTE
 XTYP_EXECUTE  QuickInfo

XTYP_EXECUTE

A dynamic data exchange (DDE) server callback function receives the XTYP_EXECUTE transaction when a client specifies XTYP_EXECUTE in the DdeClientTransaction function. A client uses this transaction to send a command string to the server.

Parameters

uFmt

Not used.

hconv

Identifies the conversation.

hsz1

Identifies the topic name.

hsz2

Not used.

hdata

Identifies the command string.

dwData1

Not used.

dwData2

Not used.

Return Value

A server callback function should return DDE_FACK if it processes this transaction, DDE_FBUSY if it is too busy to process this transaction, or DDE_FNOTPROCESSED if it rejects this transaction.

Remarks

This transaction is filtered if the server application specified the CBF_FAIL_EXECUTES flag in the DdeInitialize function.

An application must free the data handle obtained during this transaction. An application must, however, copy the command string associated with the data handle if the application must process the string after the callback function returns. An application can use the DdeGetData function to copy the data.

Because most client applications expect a server application to perform an XTYP_EXECUTE transaction synchonrously, a server should attempt to perform all processing of the XTYP_EXECUTE transaction either from within the DDE callback function or by returning the CBR_BLOCK return code. If the hdata parameter is a command that instructs the server to terminate, the server should do so after processing the XTYP_EXECUTE transaction.

See Also

DdeClientTransaction, DdeGetData, DdeInitialize


XTYP_MONITOR
 XTYP_MONITOR  QuickInfo

XTYP_MONITOR

The dynamic data exchange (DDE) callback function of a DDE debugging application receives the XTYP_MONITOR transaction whenever a DDE event occurs in the system. To receive this transaction, an application must specify the APPCLASS_MONITOR flag when it calls the DdeInitialize function.

Parameters

uFmt

Not used.

hconv

Not used.

hsz1

Not used.

hsz2

Not used.

hdata

Identifies a DDE object that contains information about the DDE event. The application should use the DdeAccessData function to obtain a pointer to the object.

dwData1

Not used.

dwData2

Identifies the DDE event. This parameter may be one of the following values:

Value	Meaning
MF_CALLBACKS	The system sent a transaction to a DDE callback function. The DDE object contains a MONCBSTRUCT structure that provides information about the transaction.
MF_CONV	A DDE conversation was established or terminated. The DDE object contains a MONCONVSTRUCT structure that provides information about the conversation.
MF_ERRORS	A DDE error occurred. The DDE object contains a MONERRSTRUCT structure that provides information about the error.
MF_HSZ_INFO	A DDE application created, freed, or incremented the usage count of a string handle, or a string handle was freed as a result of a call to the DdeUninitialize function. The DDE object contains a MONHSZSTRUCT structure that provides information about the string handle.
MF_LINKS	A DDE application started or stopped an advise loop. The DDE object contains a MONLINKSTRUCT structure that provides information about the advise loop.
MF_POSTMSGS	The system or an application posted a DDE message. The DDE object contains a MONMSGSTRUCT structure that provides information about the message.
MF_SENDMSGS	The system or an application sent a DDE message. The DDE object contains a MONMSGSTRUCT structure that provides information about the message.
Return Value

If the callback function processes this transaction, it should return 0.

See Also

DdeAccessData, DdeInitialize, DdeUninitialize, MONCBSTRUCT, MONCONVSTRUCT, MONERRSTRUCT, MONHSZSTRUCT, MONLINKSTRUCT, MONMSGSTRUCT


XTYP_POKE
 XTYP_POKE  QuickInfo

XTYP_POKE

A dynamic data exchange (DDE) server callback function receives the XTYP_POKE transaction when a client specifies XTYP_POKE in DdeClientTransaction function. A client uses this transaction to send unsolicited data to the server.

Parameters

uFmt

Specifies the format of the data sent from the server.

hconv

Identifies the conversation.

hsz1

Identifies the topic name.

hsz2

Identifies the item name.

hdata

Identifies the data that the client is sending to the server.

dwData1

Not used.

dwData2

Not used.

Return Value

A server callback function should return the DDE_FACK flag if it processes this transaction, the DDE_FBUSY flag if it is too busy to process this transaction, or the DDE_FNOTPROCESSED flag if it rejects this transaction.

Remarks

This transaction is filtered if the server application specified the CBF_FAIL_POKES flag in the DdeInitialize function.

See Also

DdeClientTransaction, DdeInitialize


XTYP_REGISTER
 XTYP_REGISTER  QuickInfo

XTYP_REGISTER

A dynamic data exchange (DDE) callback function receives the XTYP_REGISTER transaction type whenever a Dynamic Data Exchange Library (DDEML) server application uses the DdeNameService function to register a service name, or whenever a non-DDEML application that supports the System topic is started.

Parameters

uFmt

Not used.

hconv

Not used.

hsz1

Identifies the base service name being registered.

hsz2

Identifies the instance-specific service name being registered.

hdata

Not used.

dwData1

Not used.

dwData2

Not used.

Remarks

This transaction is filtered if the application specified the CBF_SKIP_REGISTRATIONS flag in the DdeInitialize function.

A application cannot block this transaction type; the CBR_BLOCK return code is ignored.

An application should use the hsz1 parameter to add the service name to the list of servers available to the user. An application should use the hsz2 parameter to identify which application instance has started.

See Also

DdeInitialize, DdeNameService


XTYP_REQUEST
 XTYP_REQUEST  QuickInfo

XTYP_REQUEST

A dynamic data exchange (DDE) server callback function receives the XTYP_REQUEST transaction when a client specifies XTYP_REQUEST in the DdeClientTransaction function. A client uses this transaction to request data from a server.

Parameters

uFmt

Specifies the format in which the server should submit data to the client.

hconv

Identifies the conversation.

hsz1

Identifies the topic name.

hsz2

Identifies the item name.

hdata

Not used.

dwData1

Not used.

dwData2

Not used.

Return Value

The server should call the DdeCreateDataHandle function to create a data handle that identifies the data and then return the handle. The server should return NULL if it is unable to complete the transaction. If the server returns NULL, the client will receive a DDE_FNOTPROCESSED flag.

Remarks

This transaction is filtered if the server application specified the CBF_FAIL_REQUESTS flag in the DdeInitialize function.

If responding to this transaction requires lengthy processing, the server can return the CBR_BLOCK return code to suspend future transactions on the current conversation and then process the transaction asynchronously. When the server has finished and the data is ready to pass to the client, the server can call the DdeEnableCallback function to resume the conversation.

See Also

DdeClientTransaction, DdeCreateDataHandle, DdeEnableCallback, DdeInitialize


XTYP_UNREGISTER
 XTYP_UNREGISTER  QuickInfo

XTYP_UNREGISTER

A dynamic data exchange (DDE) callback function receives the XTYP_UNREGISTER transaction whenever a Dynamic Data Exchange Management Library (DDEML) server application uses the DdeNameService function to unregister a service name, or whenever a non-DDEML application that supports the System topic is terminated.

Parameters

uFmt

Not used.

hconv

Not used.

hsz1

Identifies the base service name being unregistered.

hsz2

Identifies the instance-specific service name being unregistered.

hdata

Not used.

dwData1

Not used.

dwData2

Not used.

Remarks

This transaction is filtered if the application specified the CBF_SKIP_REGISTRATIONS flag in the DdeInitialize function.

A application cannot block this transaction type; the CBR_BLOCK return code is ignored.

An application should use the hsz1 parameter to remove the service name from the list of servers available to the user. An application should use the hsz2 parameter to identify which application instance has terminated.

See Also

DdeInitialize, DdeNameService


XTYP_WILDCONNECT
 XTYP_WILDCONNECT  QuickInfo

XTYP_WILDCONNECT

A dynamic data exchange (DDE) server callback function receives the XTYP_WILDCONNECT transaction when a client specifies a NULL service name, a NULL topic name, or both in a call to the DdeConnect or DdeConnectList function. This transaction allows a client to establish a conversation on each of the server's service name and topic name pairs that match the specified service name and topic name.

Parameters

uFmt

Not used.

hconv

Not used.

hsz1

Identifies the topic name. If this parameter is NULL, the client is requesting a conversation on all topic names that the server supports.

hsz2

Identifies the service name. If this parameter is NULL, the client is requesting a conversation on all service names that the server supports.

hdata

Not used.

dwData1

Points to a CONVCONTEXT structure that contains context information for the conversation. If the client is not a Dynamic Data Exchange Management Library (DDEML) application, this parameter is set to 0.

dwData2

Specifies whether the client is the same application instance as the server. If the parameter is 1, the client is same instance. If the parameter is 0, the client is a different instance.

Return Value

The server should return a data handle that identifies an array of HSZPAIR structures. The array should contain one structure for each service-name and topic-name pair that matches the service-name and topic-name pair requested by the client. The array must be terminated by a NULL string handle. The system sends the XTYP_CONNECT_CONFIRM transaction to the server to confirm each conversation and to pass the conversation handles to the server. The server will not receive these confirmations if it specified the CBF_SKIP_CONNECT_CONFIRMS flag in the DdeInitialize function.

The server should return NULL to refuse the XTYP_WILDCONNECT transaction.

Remarks

This transaction is filtered if the server application specified the CBF_FAIL_CONNECTIONS flag in the DdeInitialize function.

A server cannot block this transaction type; the CBR_BLOCK return code is ignored.

See Also

CONVCONTEXT, DdeConnect, DdeInitialize, HSZPAIR


XTYP_XACT_COMPLETE
 XTYP_XACT_COMPLETE  QuickInfo

XTYP_XACT_COMPLETE

A dynamic data exchange (DDE) client callback function receives the XTYP_XACT_COMPLETE transaction when an asynchronous transaction, initiated by a call to the DdeClientTransaction function, has completed.

Parameters

uFmt

Specifies the format of the data associated with the completed transaction (if applicable) or NULL if no data was exchanged during the transaction.

hconv

Identifies the conversation.

hsz1

Identifies the topic name involved in the completed transaction.

hsz2

Identifies the item name involved in the completed transaction.

hdata

Identifies the data involved in the completed transaction, if applicable. If the transaction was successful but involved no data, this parameter is TRUE. This parameter is NULL if the transaction was unsuccessful.

dwData1

Specifies the transaction identifier of the completed transaction.

dwData2

Specifies any applicable DDE_ status flags in the low word. This parameter provides support for applications dependent on DDE_APPSTATUS bits. It is recommended that applications no longer use these bits — future versions of the Dynamic Data Exchange Management Library (DDEML) may not support them.

Remarks

An application must not free the data handle obtained during this transaction. An application must, however, copy the data associated with the data handle if the application must process the data after the callback function returns. An application can use the DdeGetData function to copy the data.

See Also

DdeClientTransaction, DdeGetData


 Virtual-Key Codes

The following table shows the symbolic constant names, hexadecimal values, and keyboard equivalents for the virtual-key codes used by the Microsoft Windows operating system. The codes are listed in numeric order.

Symbolic constant name	Value (hexadecimal)	Mouse or keyboard equivalent
VK_LBUTTON	01	Left mouse button
VK_RBUTTON	02	Right mouse button
VK_CANCEL	03	Control-break processing
VK_MBUTTON	04	Middle mouse button (three-button mouse)
—	05−07	Undefined
VK_BACK	08	BACKSPACE key
VK_TAB	09	TAB key
—	0A−0B	Undefined
VK_CLEAR	0C	CLEAR key
VK_RETURN	0D	ENTER key
—	0E−0F	Undefined
VK_SHIFT	10	SHIFT key
VK_CONTROL	11	CTRL key
VK_MENU	12	ALT key
VK_PAUSE	13	PAUSE key
VK_CAPITAL	14	CAPS LOCK key
—	15−19	Reserved for Kanji systems
—	1A	Undefined
VK_ESCAPE	1B	ESC key
—	1C−1F	Reserved for Kanji systems
VK_SPACE	20	SPACEBAR
VK_PRIOR	21	PAGE UP key
VK_NEXT	22	PAGE DOWN key
VK_END	23	END key
VK_HOME	24	HOME key
VK_LEFT	25	LEFT ARROW key
VK_UP	26	UP ARROW key
VK_RIGHT	27	RIGHT ARROW key
VK_DOWN	28	DOWN ARROW key
VK_SELECT	29	SELECT key
—	2A	Original equipment manufacturer (OEM) specific
VK_EXECUTE	2B	EXECUTE key
VK_SNAPSHOT	2C	PRINT SCREEN key for Windows 3.0 and later
VK_INSERT	2D	INS key
VK_DELETE	2E	DEL key
VK_HELP	2F	HELP key
VK_0	30	0 key
VK_1	31	1 key
VK_2	32	2 key
VK_3	33	3 key
VK_4	34	4 key
VK_5	35	5 key
VK_6	36	6 key
VK_7	37	7 key
VK_8	38	8 key
VK_9	39	9 key
—	3A−40	Undefined
VK_A	41	A key
VK_B	42	B key
VK_C	43	C key
VK_D	44	D key
VK_E	45	E key
VK_F	46	F key
VK_G	47	G key
VK_H	48	H key
VK_I	49	I key
VK_J	4A	J key
VK_K	4B	K key
VK_L	4C	L key
VK_M	4D	M key
VK_N	4E	N key
VK_O	4F	O key
VK_P	50	P key
VK_Q	51	Q key
VK_R	52	R key
VK_S	53	S key
VK_T	54	T key
VK_U	55	U key
VK_V	56	V key
VK_W	57	W key
VK_X	58	X key
VK_Y	59	Y key
VK_Z	5A	Z key
—	5B−5F	Undefined
VK_NUMPAD0	60	Numeric keypad 0 key
VK_NUMPAD1	61	Numeric keypad 1 key
VK_NUMPAD2	62	Numeric keypad 2 key
VK_NUMPAD3	63	Numeric keypad 3 key
VK_NUMPAD4	64	Numeric keypad 4 key
VK_NUMPAD5	65	Numeric keypad 5 key
VK_NUMPAD6	66	Numeric keypad 6 key
VK_NUMPAD7	67	Numeric keypad 7 key
VK_NUMPAD8	68	Numeric keypad 8 key
VK_NUMPAD9	69	Numeric keypad 9 key
VK_MULTIPLY	6A	Multiply key
VK_ADD	6B	Add key
VK_SEPARATOR	6C	Separator key
VK_SUBTRACT	6D	Subtract key
VK_DECIMAL	6E	Decimal key
VK_DIVIDE	6F	Divide key
VK_F1	70	F1 key
VK_F2	71	F2 key
VK_F3	72	F3 key
VK_F4	73	F4 key
VK_F5	74	F5 key
VK_F6	75	F6 key
VK_F7	76	F7 key
VK_F8	77	F8 key
VK_F9	78	F9 key
VK_F10	79	F10 key
VK_F11	7A	F11 key
VK_F12	7B	F12 key
VK_F13	7C	F13 key
VK_F14	7D	F14 key
VK_F15	7E	F15 key
VK_F16	7F	F16 key
VK_F17	80H	F17 key
VK_F18	81H	F18 key
VK_F19	82H	F19 key
VK_F20	83H	F20 key
VK_F21	84H	F21 key
VK_F22	85H	F22 key
VK_F23	86H	F23 key
VK_F24	87H	F24 key
—	88−8F	Unassigned
VK_NUMLOCK	90	NUM LOCK key
VK_SCROLL	91	SCROLL LOCK key
—	92−B9	Unassigned
—	BA−C0	OEM specific
—	C1−DA	Unassigned
—	DB−E4	OEM specific
—	E5	Unassigned
—	E6	OEM specific
—	E7−E8	Unassigned
—	E9−F5	OEM specific
—	F6−FE	Unassigned


 Locale Identifiers

This appendix contains detailed information about national language support in Microsoft® Windows®. The information presented here pertains to locale identifiers, LCTYPE constants, country codes, and language identifiers.

A locale identifier (LCID) is a DWORD value containing the language identifier in the lower word and a reserved value in the upper word. The identifier supplied in an LCID is a standard international numeric abbreviation. This LCID has the components necessary to uniquely identify one of the installed system-defined locales.

Applications can use the MAKELCID macro to create LCID values.

There are two predefined LCID values: LOCALE_SYSTEM_DEFAULT is the system default locale, and LOCALE_USER_DEFAULT is the current user's locale.


 LCTYPE Constants

An LCTYPE constant is a constant that specifies a particular piece of locale information.

The values in the following list correspond to the names of these values in the configuration registry, under both the user's preferences (as values in the registry key HKEY_CURRENT_USER\Control Panel\International) and the system's installed languages (as files pointed to by registry keys, one key per language installed, under HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\NLS). All values are null-terminated Unicode™ strings. If no maximum length is indicated, the strings may vary in length.

Constant	Description
LOCALE_ILANGUAGE	Language identifier indicating the language. The maximum number of characters allowed for this string is 5.
LOCALE_SLANGUAGE	Full localized name of the language.
LOCALE_SENGLANGUAGE	Full English name of the language from the International Organization for Standardization (ISO) Standard 639. This is always restricted to characters mappable into the ASCII 127-character subset.
LOCALE_SABBREVLANGNAME	Abbreviated name of the language, created by taking the 2-letter language abbreviation from the ISO Standard 639 and adding a third letter, as appropriate, to indicate the sublanguage.
LOCALE_SNATIVELANGNAME	Native name of the language.
LOCALE_ICOUNTRY	Country code, based on international phone codes, also referred to as IBM country codes. The maximum number of characters allowed for this string is 6.
LOCALE_SCOUNTRY	Full localized name of the country.
LOCALE_SENGCOUNTRY	Full English name of the country. This is always restricted to characters mappable into the ASCII 127-character subset.
LOCALE_SABBREVCTRYNAME	Abbreviated name of the country from the ISO Standard 3166.
LOCALE_SNATIVECTRYNAME	Native name of the country.
LOCALE_IDEFAULTLANGUAGE	Language identifier for the principal language spoken in this locale. This is provided so that partially specified locales can be completed with default values. The maximum number of characters allowed for this string is 5.
LOCALE_IDEFAULTCOUNTRY	Country code for the principal country in this locale. This is provided so that partially specified locales can be completed with default values. The maximum number of characters allowed for this string is 6.
LOCALE_IDEFAULTCODEPAGE	Original equipment manufacturer (OEM) code page associated with the country. The maximum number of characters allowed for this string is 6.
LOCALE_SLIST	Character(s) used to separate list items. For example, a comma is used in many locales.
LOCALE_IMEASURE	System of measurement. This value is 0 if the metric system (Systéme International d'Unités, or S.I.) is used and 1 if the U.S. system is used. The maximum number of characters allowed for this string is 2.
LOCALE_SDECIMAL	Character(s) used as the decimal separator.
LOCALE_STHOUSAND	Character(s) used to separate groups of digits to the left of the decimal.
LOCALE_SGROUPING	Sizes for each group of digits to the left of the decimal. An explicit size is needed for each group; sizes are separated by semicolons. If the last value is zero, the preceding value is repeated. To group thousands, specify 3;0, for example.
LOCALE_IDIGITS	Number of fractional digits. The maximum number of characters allowed for this string is 3.
LOCALE_ILZERO	Specifier for leading zeros in decimal fields. The maximum number of characters allowed for this string is 2. The specifier can be one of the following values:
Value	Meaning
0	No leading zeros
1	Leading zeros
LOCALE_SNATIVEDIGITS	Native equivalents to ASCII 0 through 9.
LOCALE_SCURRENCY	String used as the local monetary symbol.
LOCALE_SINTLSYMBOL	Three characters of the international monetary symbol specified in ISO 4217, "Codes for the Representation of Currencies and Funds," followed by the character separating this string from the amount.
LOCALE_SMONDECIMALSEP	Character(s) used as the monetary decimal separator.
LOCALE_SMONTHOUSANDSEP	Character(s) used as the monetary separator between groups of digits to the left of the decimal.
LOCALE_SMONGROUPING	Sizes for each group of monetary digits to the left of the decimal. An explicit size is needed for each group; sizes are separated by semicolons. If the last value is zero, the preceding value is repeated. To group thousands, specify 3;0, for example.
LOCALE_ICURRDIGITS	Number of fractional digits for the local monetary format. The maximum number of characters allowed for this string is 3.
LOCALE_IINTLCURRDIGITS	Number of fractional digits for the international monetary format. The maximum number of characters allowed for this string is 3.
LOCALE_ICURRENCY	Positive currency mode. The maximum number of characters allowed for this string is 2. The mode can be one of the following values:
Value	Meaning
0	Prefix, no separation
1	Suffix, no separation
2	Prefix, 1-char. separation
3	Suffix, 1-char. separation
LOCALE_INEGCURR	Negative currency mode. The maximum number of characters allowed for this string is 3. The mode can be one of the following values:
Value	Example
0	($1.1)
1	−$1.1
2	$−1.1
3	$1.1−
4	(1.1$)
5	−1.1$
6	1.1−$
7	1.1$−
8	−1.1 $ (space before $)
9	−$ 1.1 (space after $)
10	1.1 $− (space before $)
11	$ 1.1− (space after $)
12	$ −1.1 (space after $)
13	1.1− $ (space before $)
14	($ 1.1) (space after $)
15	(1.1 $) (space before $)
LOCALE_SDATE	Character(s) for the date separator.
LOCALE_STIME	Character(s) for the time separator.
LOCALE_STIMEFORMAT	Time formatting strings for this locale.
LOCALE_SSHORTDATE	Short date formatting string for this locale.
LOCALE_SLONGDATE	Long date formatting string for this locale.
LOCALE_IDATE	Short date format-ordering specifier. The maximum number of characters allowed for this string is 2. The specifier can be one of the following values:
Value	Meaning
0	Month-Day-Year
1	Day-Month-Year
2	Year-Month-Day
LOCALE_ILDATE	Long date format-ordering specifier. The maximum number of characters allowed for this string is 2. The specifier can be one of the following values:
Value	Meaning
0	Month-Day-Year
1	Day-Month-Year
2	Year-Month-Day
LOCALE_ITIME	Time format specifier. The maximum number of characters allowed for this string is 2. The specifier can be one of the following values:
Value	Meaning
0	AM / PM 12-hour format
1	24-hour format
LOCALE_ICENTURY	Specifier for full 4-digit century. The maximum number of characters allowed for this string is 2. The specifier can be one of the following values:
Value	Meaning
0	Abbreviated 2-digit century
1	Full 4-digit century
LOCALE_ITLZERO	Specifier for leading zeros in time fields. The maximum number of characters allowed for this string is 2. The specifier can be one of the following values:
Value	Meaning
0	No leading zeros for hours
1	Leading zeros for hours
LOCALE_IDAYLZERO	Specifier for leading zeros in day fields. The maximum number of characters allowed for this string is 2. The specifier can be one of the following values:
Value	Meaning
0	No leading zeros for days
1	Leading zeros for days
LOCALE_IMONLZERO	Specifier for leading zeros in month fields. The maximum number of characters allowed for this string is 2. The specifier can be one of the following values:
Value	Meaning
0	No leading zeros for months
1	Leading zeros for months
LOCALE_S1159	String for the AM designator.
LOCALE_S2359	String for the PM designator.
LOCALE_SDAYNAME1	Native long name for Monday.
LOCALE_SDAYNAME2	Native long name for Tuesday.
LOCALE_SDAYNAME3	Native long name for Wednesday.
LOCALE_SDAYNAME4	Native long name for Thursday.
LOCALE_SDAYNAME5	Native long name for Friday.
LOCALE_SDAYNAME6	Native long name for Saturday.
LOCALE_SDAYNAME7	Native long name for Sunday.
LOCALE_SABBREVDAYNAME1	Native abbreviated name for Monday.
LOCALE_SABBREVDAYNAME2	Native abbreviated name for Tuesday.
LOCALE_SABBREVDAYNAME3	Native abbreviated name for Wednesday.
LOCALE_SABBREVDAYNAME4	Native abbreviated name for Thursday.
LOCALE_SABBREVDAYNAME5	Native abbreviated name for Friday.
LOCALE_SABBREVDAYNAME6	Native abbreviated name for Saturday.
LOCALE_SABBREVDAYNAME7	Native abbreviated name for Sunday.
LOCALE_SMONTHNAME1	Native long name for January.
LOCALE_SMONTHNAME2	Native long name for February.
LOCALE_SMONTHNAME3	Native long name for March.
LOCALE_SMONTHNAME4	Native long name for April.
LOCALE_SMONTHNAME5	Native long name for May.
LOCALE_SMONTHNAME6	Native long name for June.
LOCALE_SMONTHNAME7	Native long name for July.
LOCALE_SMONTHNAME8	Native long name for August.
LOCALE_SMONTHNAME9	Native long name for September.
LOCALE_SMONTHNAME10	Native long name for October.
LOCALE_SMONTHNAME11	Native long name for November.
LOCALE_SMONTHNAME12	Native long name for December.
LOCALE_SABBREVMONTHNAME1	Native abbreviated name for January.
LOCALE_SABBREVMONTHNAME2	Native abbreviated name for February.
LOCALE_SABBREVMONTHNAME3	Native abbreviated name for March.
LOCALE_SABBREVMONTHNAME4	Native abbreviated name for April.
LOCALE_SABBREVMONTHNAME5	Native abbreviated name for May.
LOCALE_SABBREVMONTHNAME6	Native abbreviated name for June.
LOCALE_SABBREVMONTHNAME7	Native abbreviated name for July.
LOCALE_SABBREVMONTHNAME8	Native abbreviated name for August.
LOCALE_SABBREVMONTHNAME9	Native abbreviated name for September.
LOCALE_SABBREVMONTHNAME10	Native abbreviated name for October.
LOCALE_SABBREVMONTHNAME11	Native abbreviated name for November.
LOCALE_SABBREVMONTHNAME12	Native abbreviated name for December.
LOCALE_SPOSITIVESIGN	String value for the positive sign.
LOCALE_SNEGATIVESIGN	String value for the negative sign.
LOCALE_IPOSSIGNPOSN	Formatting index for positive values. The maximum number of characters allowed for this string is 2. The index can be one of the following values:
Value	Meaning
0	Parentheses surround the amount and the monetary symbol.
1	The sign string precedes the amount and the monetary symbol.
2	The sign string succeeds the amount and the monetary symbol.
3	The sign string immediately precedes the monetary symbol.
4	The sign string immediately succeeds the monetary symbol.
LOCALE_INEGSIGNPOSN	Formatting index for negative values. This index uses the same values as LOCALE_IPOSSIGNPOSN. The maximum number of characters allowed for this string is 2.
LOCALE_IPOSSYMPRECEDES	Position of monetary symbol in a positive monetary value. This value is 1 if the monetary symbol precedes the positive amount, 0 if it follows it. The maximum number of characters allowed for this string is 2.
LOCALE_IPOSSEPBYSPACE	Separation of monetary symbol in a positive monetary value. This value is 1 if the monetary symbol is separated by a space from a positive amount, 0 if it is not. The maximum number of characters allowed for this string is 2.
LOCALE_INEGSYMPRECEDES	Position of monetary symbol in a negative monetary value. This value is 1 if the monetary symbol precedes the negative amount, 0 if it follows it. The maximum number of characters allowed for this string is 2.
LOCALE_INEGSEPBYSPACE	Separation of monetary symbol in a negative monetary value. This value is 1 if the monetary symbol is separated by a space from the negative amount, 0 if it is not. The maximum number of characters allowed for this string is 2.
LOCALE_NOUSEROVERRIDE	This constant may be OR'ed with any other LCTYPE constant in a call to the GetLocaleInfo function. This always causes the function to bypass any user overrides, and return the system default value for the other LCTYPE specified in the function call, based on the given LCID.


 Language Identifiers and Locales

Applications can use the MAKELANGID macro to create a language identifier.

The first release of Windows NT supports 35 sublanguages/locales.

The following 28 sublanguages/locales use the Latin 1 script:

Latin 1 Script

Identifier	Language	Sublanguage/Locale	Language Code
0x0406	Danish	Danish	DAN
0x0413	Dutch	Dutch (Standard)	NLD
0x0813	Dutch	Belgian (Flemish)	NLB
0x0409	English	American	ENU
0x0809	English	British	ENG
0x0c09	English	Australian	ENA
0x1009	English	Canadian	ENC
0x1409	English	New Zealand	ENZ
0x1809	English	Ireland	ENI
0x040b	Finnish	Finnish	FIN
0x040c	French	French (Standard)	FRA
0x080c	French	Belgian	FRB
0x0c0c	French	Canadian	FRC
0x100c	French	Swiss	FRS
0x0407	German	German (Standard)	DEU
0x0807	German	Swiss	DES
0x0c07	German	Austrian	DEA
0x040f	Icelandic	Icelandic	ISL
0x0410	Italian	Italian (Standard)	ITA
0x0810	Italian	Swiss	ITS
0x0414	Norwegian	Norwegian (Bokmal)	NOR
0x0814	Norwegian	Norwegian (Nynorsk)	NON
0x0416	Portuguese	Portuguese (Brazilian)	PTB
0x0816	Portuguese	Portuguese (Standard)	PTG
0x041D	Swedish	Swedish	SVE
0x040a	Spanish	Spanish (Standard/Traditional)	ESP
0x080a	Spanish	Mexican	ESM
0x0c0a	Spanish	Spanish (Modern)	ESN
The following 5 sublanguages/locales use the Latin 2 script:

Latin 2 Script

Identifier	Sublanguage/Locale	Language Code
0x041f	Turkish	TRK
0x0415	Polish	PLK
0x0405	Czech	CSY
0x041b	Slovak	SKY
0x040e	Hungarian	HUN
The following sublanguage/locale uses the Cyrillic script:

Cyrillic Script

Identifier	Sublanguage/Locale	Language Code
0x0419	Russian	RUS
The following sublanguage/locale uses an other script:

Other Script

Identifier	Sublanguage/Locale	Language Code
0x0408	Greek	ELL
The following special identifiers are also defined:

Special Identifiers

Identifier	Sublanguage/Locale
0x0000	Language-Neutral
0x0400	Process Default Language


 MCI Command String Syntax Summary

This section summarizes MCI commands and their options, by device type. For the conventions used in the command tables, see About the Command Tables.


 Introduction

This topic provides a summary of the syntax of the MCI command strings.

To view a command table, click on one of the following:

•	System command set

•	Required command set

•	Basic command set

•	Animation commands

•	Audio CD command set

•	MIDI sequencer commands

•	Videodisc command set

•	Video overlay command set

•	Waveform audio command set


 About the Command Tables

Each command table has a Command column and an Arguments column. The Command column contains the MCI commands available for a device type. The Arguments column contains the options available for each MCI command. For example, the following table contains the MCI commands all devices support.

Command	Arguments
capability device_name	{can eject
	| can play | can record | can save | compound device | device type | has audio | has video | uses files}
close device_name
info device_name	[product]
open device_name	[alias device_alias]
	[shareable]
	[type device_type]
status device_name	[mode | ready]
Each command also has a notify and wait flag that does not appear in the tables. These flags can be added to any command.

The following conventions are used in the previous example and for the other MCI command tables.

Type style	Used for
Bold	A specific term intended to be used literally. When used in the command column, it represents the MCI string command. When used in the arguments column, it represents a flag. For example, the capability command and the can play flag must be typed as shown.
Italics	Placeholders for information you must provide. The MCI command or flag associated with the information must precede it. For example, to use the alias words for the device_name with the capability command, type "capability words can play."
|	Divider for mutually exclusive arguments. When multiple arguments are separated by this symbol, only one of them can be used for each command. For example, the items in the list can eject, can play, can record, can save, compound device, device type, has audio, has video, uses files are mutually exclusive and you must select only one to use with the capability command. (Do not type the | with the argument.)
{}	Required argument. You must include an argument enclosed by braces. For example, you must use one of the arguments can eject, can play, can record, can save, compound device, device type, has audio, has video, uses files with the capability command. (Do not type the braces with the argument.)
[ ]	Optional argument. For example, the alias, type and shareable flags are optional for the open command. You can use any combination of these flags. You can also use optional arguments with a required argument. (Do not type the brackets with the argument.)


 System Command Set

The following table summarizes the MCI system commands. These commands are interpreted directly by MCI. System commands also support notify and wait as optional flags. You can add either or both of these flags to any system command.

Command	Arguments
break device_name	{off | on virtual key code}
sound sound_name
sysinfo device_name	{installname
	| name index | name index open | quantity | quantity open}


 Required Command Set

The following table lists the commands recognized by all devices. Extended commands can add other options to these commands. Required commands also support notify and wait as optional flags. You can add either or both of these flags to any required command.

Command	Arguments
capability device_name	{can eject
	| can play | can record | can save | compound device | device type | has audio | has video | uses files}
close device_name
info device_name	[product]
open device_name	[alias device_alias]
	[shareable]
	[type device_type]
status device_name	[mode | ready]


 Basic Command Set

In addition to supporting the commands described previously, each device supports a set of commands specific to its device type. Although these commands are optional for a device, if a command is used it must support the options listed in this table as a minimum set of capabilities. Basic commands also support notify and wait as optional flags. You can add either or both of these flags to any basic command.

Command	Arguments
load device_name	{file_name}
pause device_name
play device_name	[from position]
	[to position]
	[insert | overwrite]
resume device_name
save device_name	[file_name]
seek device_name	{to position | to start | to end}
set device_name	[audio all off
	| audio all on | audio left off | audio left on | audio right off | audio right on | video off | video on]
	[door closed | door open]
	[time format milliseconds | time format ms]
status device_name	{current track
	| length | length track track_number | mode | number of tracks | position | position track track_number | ready | start position | time format}
stop device name


 Animation Commands

Animation devices support the following set of commands. These devices also supporty notify and wait as optional flags. You can add either or both of these flags to any animation command.

Command	Arguments
capability device_name	{can eject
	| can play | can record | can reverse | can save | can stretch | compound device | device type | fast play rate | has audio | has video | normal play rate | slow play rate | uses files | uses palettes | windows}
close device_name
info device_name	[file | product | window text]
open device_name	[alias device_alias]
	[nostatic]
	[parent hwnd]
	[shareable]
	[style child
	| style overlapped | style popup]
	[type device_type]
pause device_name
play device_name	[fast | slow | speed fps]
	[from position]
	[to position | reverse]
	[scan]
put device_name	{destination
	| destination at destination_rectangle | source | source at source_rectangle}
realize device_name	{background | normal}
resume device_name
seek device_name	[to position | to start | to end]
set device_name	[audio all off
	| audio all on | audio left off | audio left on | audio right off | audio right on | video off | video on]
	[time format milliseconds
	| time format ms | time format frames]
status device_name	{current track
	| forward | length | length track track_number | media present | mode | number of tracks | palette handle | position | position track track_number | ready | speed | start position | stretch | time format | window handle}
step device_name	[by frames]
stop device_name
update device_name	[at update_rect]
	[hdc hdc]
where device_name	{destination | source}
window device_name	[handle window_handle | handle default]
	[stretch | fixed]
	[state hide
	| state iconic | state maximized | state minimize | state minimized | state no action | state no active | state normal | state show]
	[text caption_text]


 Audio CD Command Set

Audio CD devices support the following core set of commands. Audio CD devices also support notify and wait as option flags. You can add either or both of these flags to any audio CD command.

Command	Arguments
capability device_name	{can eject
	| can play | can record | can save | compound device | device type | has audio | has video | uses files}
close device_name	[product]
info device_name
open device_name	[alias device_name]
	[shareable]
pause device_name
play device_name	[from position]
	[to position]
resume device_name
seek device_name	[to position to start | to end]
set device_name	[audio all off
	| audio all on | audio left off | audio left on | audio right off | audio right on | video off | video on]
	[door closed | door open]
	[time format milliseconds
	| time format ms | time format msf | time format tmsf]
status device_name	{current track
	| length | length track track_number | media present | mode | number of tracks | position | position track track_number | ready | start position | time format}
stop device_name


 MIDI Sequencer Commands

The MIDI sequencer supports the following set of commands. MIDI sequencers also support notify and wait as optional flags. You can add either or both of these flags to any MIDI sequencer command.

Command	Arguments
capability device_name	{can eject
	| can play | can record | can save | compound device | device type | has audio | has video | uses files}
close device_name
info device_name	[file | product]
open device_name	[alias device_alias]
	[shareable]
	[type device_type]
pause device_name
play device_name	[from position]
	[to position]
record device_name	[from position]
	[to position]
	[insert | overwrite]
save device_name	[file_name]
seek device_name	[to position | to start | to end]
set device_name	[audio all off
	| audio all on | audio left off | audio left on | audio right off | audio right on | video off | video on]
	[master MIDI
	| master none | master SMPTE]
	[offset hmsf_value]
	[port port_number
	| port mapper | port none]
	[slave file
	| slave MIDI | slave none | slave SMPTE]
	[tempo tempo_value]
	[time format milliseconds
	| time format ms | time format smpte 24 | time format smpte 25 | time format smpte 30 | time format smpte 30 drop | time format song pointer]
status device_name	{current track
	| division type | length | length track track_number | master | media present | mode | number of tracks | offset | port | position | position track track_number | ready | slave | start position | tempo | time format}
stop device_name


 Videodisc Commands

Videodisc players support the following set of commands. Videodisc devices also support notify and wait as optional flags. You can add either or both of these flags to any videodisc command.

Command	Arguments
capability device_name	{can eject
	| can play | can record | can reverse | can save | compound device | device type | fast play rate | has audio | has video | normal play rate | slow play rate | uses files}
	[CAV | CLV]
close device_name
escape device_name	{command_string}
info device_name	[product]
open device_name	[alias device_alias]
	[shareable]
pause device_name
play device_name	[fast | slow | speed fps]
	[from position]
	[scan]
	[to position | reverse]
resume device_name
seek device_name	[reverse | to position | to start | to end]
set device_name	[audio all off
	| audio all on | audio left off | audio left on | audio right off | audio right on | video off | video on]
	[door closed | door open]
	[time format milliseconds
	| time format ms | time format frames | time format hms | time format track]
spin device_name	[down | up]
status device_name	{current track
	| disc size | forward | length | length track track_number | media present | media type | mode | number of tracks | position | position track track_number | ready | side | speed | start position | time format}
step device_name	[by] position
	[reverse]
stop device_name


 Video Overlay Command Set

Video overlay devices support the following set of commands. Video overlay devices also support notify and wait as optional flags. You can add either or both of these flags to any video overlay command.

Command	Arguments
capability device_name	{can eject
	| can freeze | can play | can record | can save | can stretch | compound device | device type | has audio | has video | uses files | windows}
close device_name
freeze device_name	[at rectangle]
info device_name	[product | file | window text]
load device_name	[file_name]
	at  buffer_rectangle
open device_name	[alias device_alias]
	[parent hwnd]
	[shareable]
	[style style_type
	| style child | style overlapped | style popup]
	[type device_type]
put device_name	{destination | at destination_rectangle
	| frame | frame at frame_rectangle | source | source at source_rectangle | video | video at video_rectangle}
save device_name	[file_name]
	at buffer_rectangle
set device_name	[audio all off
	| audio all on | audio left off | audio left on | audio right off | audio right on | video off | video on]
	[time format milliseconds
	| time format ms]
status device_name	{current track
	| length | length track track_number | media present | mode | number of tracks | position | position track track_number | ready | start position | stretch | time format | window handle}
unfreeze device_name	[at freeze_rectangle]
where device_name	{destination | frame | source | video}
window device_name	[handle window_handle | handle default]
	| [stretch | fixed]
	[state hide
	| state iconic | state maximized | state minimized | state no action | state no activate | state normal | state show]
	[text caption_text]


 Waveform Audio Command Set

Wave audio devices support the following set of commands. Wave audio devices also support notify and wait as optional flags. You can add either or both of these flags to any wave audio command.

Command	Arguments
capability device_name	{can eject
	| can play | can record | can save | compound device | device type | has audio | has video | inputs | outputs | uses files}
close device_name
cue device_name	[input | output]
delete device_name	[from position]
	[to position]
info device_name	[file
	| input | output | product]
open device_name	[alias device_alias]
	[buffer buffer_size]
	[shareable]
	[type device_type]
pause device_name
play device_name	[from position]
	[to position]
record device_name	[from position]
	[to position]
	[insert | overwrite]
resume device_name
save device_name	[file_name]
seek device_name	[to position | to start | to end]
set device_name	[alignment block_alignment]
	[any input]
	[any output]
	[audio all off
	| audio all on | audio left off | audio left on | audio right off | audio right on | video off | video on]
	[bitspersample bit_count]
	[bytespersec byte_rate]
	[channels channel_count]
	[format tag tag | format tag pcm]
	[input device_number]
	[output device_number]
	[samplespersec sample_rate]
	[timeformat milliseconds
	| time format ms | time format bytes | time format samples]
status device_name	{alignment
	| bitspersample | bytespersec | channels | current track | format tag | input | length | length track track_number | level | media present | mode | number of tracks | output | position | position track track_number | ready | samplespersec | start position | time format}
stop device_name


 Raster Operation Codes

Raster-operation codes define how the graphics device interface (GDI) combines the bits from the selected pen with the bits in the destination bitmap. This appendix lists and describes the binary and ternary raster operations used by GDI.


 About Raster Operation Codes

This appendix lists and describes the binary and ternary raster operations used by graphics device interface (GDI). A binary raster operation involves two operands: a pen and a destination bitmap. A ternary raster operation involves three operands: a source bitmap, a brush, and a destination bitmap. Both binary and ternary raster operations use Boolean operators.


 Binary Raster Operations

This section lists the binary raster-operation codes used by the GetROP2 and SetROP2 functions. Raster-operation codes define how GDI combines the bits from the selected pen with the bits in the destination bitmap.

Each raster-operation code represents a Boolean operation in which the values of the pixels in the selected pen and the destination bitmap are combined. Following are the two operands used in these operations:

Operand	Meaning
P	Selected pen
D	Destination bitmap
The Boolean operators used in these operations follow:

Operator	Meaning
a	Bitwise AND
n	Bitwise NOT (inverse)
o	Bitwise OR
x	Bitwise exclusive OR (XOR)
All Boolean operations are presented in reverse Polish notation. For example, the following operation replaces the values of the pixels in the destination bitmap with a combination of the pixel values of the pen and the selected brush:

DPo

Each raster-operation code is a 32-bit integer whose high-order word is a Boolean operation index and whose low-order word is the operation code. The 16-bit operation index is a zero-extended 8-bit value that represents all possible outcomes resulting from the Boolean operation on two parameters (in this case, the pen and destination values). For example, the operation indexes for the DPo and DPan operations are shown in the following list:

P	D	DPo	DPan
0	0	0	1
0	1	1	1
1	0	1	1
1	1	1	0
The following list outlines the drawing modes and the Boolean operations that they represent:

Raster operation	Boolean operation
R2_BLACK	0
R2_COPYPEN	P
R2_MASKNOTPEN	DPna
R2_MASKPEN	DPa
R2_MASKPENNOT	PDna
R2_MERGENOTPEN	DPno
R2_MERGEPEN	DPo
R2_MERGEPENNOT	PDno
R2_NOP	D
R2_NOT	Dn
R2_NOTCOPYPEN	Pn
R2_NOTMASKPEN	DPan
R2_NOTMERGEPEN	DPon
R2_NOTXORPEN	DPxn
R2_WHITE	1
R2_XORPEN	DPx
For a monochrome device, GDI maps the value zero to black and the value 1 to white. If an application attempts to draw with a black pen on a white destination by using the available binary raster operations, the following results occur:

Raster operation	Result
R2_BLACK	Visible black line
R2_COPYPEN	Visible black line
R2_MASKNOTPEN	No visible line
R2_MASKPEN	Visible black line
R2_MASKPENNOT	Visible black line
R2_MERGENOTPEN	No visible line
R2_MERGEPEN	Visible black line
R2_MERGEPENNOT	Visible black line
R2_NOP	No visible line
R2_NOT	Visible black line
R2_NOTCOPYPEN	No visible line
R2_NOTMASKPEN	No visible line
R2_NOTMERGEPEN	Visible black line
R2_NOTXORPEN	Visible black line
R2_WHITE	No visible line
R2_XORPEN	No visible line
For a color device, GDI uses RGB values to represent the colors of the pen and the destination. An RGB color value is a long integer that contains a red, a green, and a blue color field, each specifying the intensity of the given color. Intensities range from 0 through 255. The values are packed in the three low-order bytes of the long integer. The color of a pen is always a solid color, but the color of the destination may be a mixture of any two or three colors. If an application attempts to draw with a white pen on a blue destination by using the available binary raster operations, the following results occur:

Raster operation	Result
R2_BLACK	Visible black line
R2_COPYPEN	Visible white line
R2_MASKNOTPEN	Visible black line
R2_MASKPEN	Invisible blue line
R2_MASKPENNOT	Visible red/green line
R2_MERGENOTPEN	Invisible blue line
R2_MERGEPEN	Visible white line
R2_MERGEPENNOT	Visible white line
R2_NOP	Invisible blue line
R2_NOT	Visible red/green line
R2_NOTCOPYPEN	Visible black line
R2_NOTMASKPEN	Visible red/green line
R2_NOTMERGEPEN	Visible black line
R2_NOTXORPEN	Invisible blue line
R2_WHITE	Visible white line
R2_XORPEN	Visible red/green line


 Ternary Raster Operations

This section lists the ternary raster-operation codes used by the BitBlt, PatBlt, and StretchBlt functions. Ternary raster-operation codes define how GDI combines the bits in a source bitmap with the bits in the destination bitmap.

Each raster-operation code represents a Boolean operation in which the values of the pixels in the source, the selected brush, and the destination are combined. Following are the three operands used in these operations:

Operand	Meaning
D	Destination bitmap
P	Selected brush (also called pattern)
S	Source bitmap
Boolean operators used in these operations follow:

Operator	Meaning
a	Bitwise AND
n	Bitwise NOT (inverse)
o	Bitwise OR
x	Bitwise exclusive OR (XOR)
All Boolean operations are presented in reverse Polish notation. For example, the following operation replaces the values of the pixels in the destination bitmap with a combination of the pixel values of the source and brush:

PSo

The following operation combines the values of the pixels in the source and brush with the pixel values of the destination bitmap (there are alternative spellings of the same function, so although a particular spelling may not be in the list, an equivalent form would be):

DPSoo

Each raster-operation code is a 32-bit integer whose high-order word is a Boolean operation index and whose low-order word is the operation code. The 16-bit operation index is a zero-extended, 8-bit value that represents the result of the Boolean operation on predefined brush, source, and destination values. For example, the operation indexes for the PSo and DPSoo operations are shown in the following list:

P	S	D	PSo	DPSoo
0	0	0	0	0
0	0	1	0	1
0	1	0	1	1
0	1	1	1	1
1	0	0	1	1
1	0	1	1	1
1	1	0	1	1
1	1	1	1	1
Operation index:			00FCh	00FEh
In this case, PSo has the operation index 00FC (read from the bottom up); DPSoo has the operation index 00FE. These values define the location of the corresponding raster-operation codes, as shown in Table A.1, "Raster-Operation Codes." The PSo operation is in line 252 (00FCh) of the table; DPSoo is in line 254 (00FEh).

The most commonly used raster operations have been given special names in the Windows include file, WINDOWS.H. You should use these names whenever possible in your applications.

When the source and destination bitmaps are monochrome, a bit value of zero represents a black pixel and a bit value of 1 represents a white pixel. When the source and the destination bitmaps are color, those colors are represented with RGB values. For more information about RGB values, see RGB

Raster-Operation Codes

Boolean function (hexadecimal)	Raster operation (hexadecimal)	Boolean function in reverse Polish	Common name
00	00000042	0	BLACKNESS
01	00010289	DPSoon	−
02	00020C89	DPSona	−
03	000300AA	PSon	−
04	00040C88	SDPona	−
05	000500A9	DPon	−
06	00060865	PDSxnon	−
07	000702C5	PDSaon	−
08	00080F08	SDPnaa	−
09	00090245	PDSxon	−
0A	000A0329	DPna	−
0B	000B0B2A	PSDnaon	−
0C	000C0324	SPna	−
0D	000D0B25	PDSnaon	−
0E	000E08A5	PDSonon	−
0F	000F0001	Pn	−
10	00100C85	PDSona	−
11	001100A6	DSon	NOTSRCERASE
12	00120868	SDPxnon	−
13	001302C8	SDPaon	−
14	00140869	DPSxnon	−
15	001502C9	DPSaon	−
16	00165CCA	PSDPSanaxx	−
17	00171D54	SSPxDSxaxn	−
18	00180D59	SPxPDxa	−
19	00191CC8	SDPSanaxn	−
1A	001A06C5	PDSPaox	−
1B	001B0768	SDPSxaxn	−
1C	001C06CA	PSDPaox	−
1D	001D0766	DSPDxaxn	−
1E	001E01A5	PDSox	−
1F	001F0385	PDSoan	−
20	00200F09	DPSnaa	−
21	00210248	SDPxon	−
22	00220326	DSna	−
23	00230B24	SPDnaon	−
24	00240D55	SPxDSxa	−
25	00251CC5	PDSPanaxn	−
26	002606C8	SDPSaox	−
27	00271868	SDPSxnox	−
28	00280369	DPSxa	−
29	002916CA	PSDPSaoxxn	−
2A	002A0CC9	DPSana	−
2B	002B1D58	SSPxPDxaxn	−
2C	002C0784	SPDSoax	−
2D	002D060A	PSDnox	−
2E	002E064A	PSDPxox	−
2F	002F0E2A	PSDnoan	−
30	0030032A	PSna	−
31	00310B28	SDPnaon	−
32	00320688	SDPSoox	−
33	00330008	Sn	NOTSRCCOPY
34	003406C4	SPDSaox	−
35	00351864	SPDSxnox	−
36	003601A8	SDPox	−
37	00370388	SDPoan	−
38	0038078A	PSDPoax	−
39	00390604	SPDnox	−
3A	003A0644	SPDSxox	−
3B	003B0E24	SPDnoan	−
3C	003C004A	PSx	−
3D	003D18A4	SPDSonox	−
3E	003E1B24	SPDSnaox	−
3F	003F00EA	PSan	−
40	00400F0A	PSDnaa	−
41	00410249	DPSxon	−
42	00420D5D	SDxPDxa	−
43	00431CC4	SPDSanaxn	−
44	00440328	SDna	SRCERASE
45	00450B29	DPSnaon	−
46	004606C6	DSPDaox	−
47	0047076A	PSDPxaxn	−
48	00480368	SDPxa	−
49	004916C5	PDSPDaoxxn	−
4A	004A0789	DPSDoax	−
4B	004B0605	PDSnox	−
4C	004C0CC8	SDPana	−
4D	004D1954	SSPxDSxoxn	−
4E	004E0645	PDSPxox	−
4F	004F0E25	PDSnoan	−
50	00500325	PDna	−
51	00510B26	DSPnaon	−
52	005206C9	DPSDaox	−
53	00530764	SPDSxaxn	−
54	005408A9	DPSonon	−
55	00550009	Dn	DSTINVERT
56	005601A9	DPSox	−
57	00570389	DPSoan	−
58	00580785	PDSPoax	−
59	00590609	DPSnox	−
5A	005A0049	DPx	PATINVERT
5B	005B18A9	DPSDonox	−
5C	005C0649	DPSDxox	−
5D	005D0E29	DPSnoan	−
5E	005E1B29	DPSDnaox	−
5F	005F00E9	DPan	−
60	00600365	PDSxa	−
61	006116C6	DSPDSaoxxn	−
62	00620786	DSPDoax	−
63	00630608	SDPnox	−
64	00640788	SDPSoax	−
65	00650606	DSPnox	−
66	00660046	DSx	SRCINVERT
67	006718A8	SDPSonox	−
68	006858A6	DSPDSonoxxn	−
69	00690145	PDSxxn	−
6A	006A01E9	DPSax	−
6B	006B178A	PSDPSoaxxn	−
6C	006C01E8	SDPax	−
6D	006D1785	PDSPDoaxxn	−
6E	006E1E28	SDPSnoax	−
6F	006F0C65	PDSxnan	−
70	00700CC5	PDSana	−
71	00711D5C	SSDxPDxaxn	−
72	00720648	SDPSxox	−
73	00730E28	SDPnoan	−
74	00740646	DSPDxox	−
75	00750E26	DSPnoan	−
76	00761B28	SDPSnaox	−
77	007700E6	DSan	−
78	007801E5	PDSax	−
79	00791786	DSPDSoaxxn	−
7A	007A1E29	DPSDnoax	−
7B	007B0C68	SDPxnan	−
7C	007C1E24	SPDSnoax	−
7D	007D0C69	DPSxnan	−
7E	007E0955	SPxDSxo	−
7F	007F03C9	DPSaan	−
80	008003E9	DPSaa	−
81	00810975	SPxDSxon	−
82	00820C49	DPSxna	−
83	00831E04	SPDSnoaxn	−
84	00840C48	SDPxna	−
85	00851E05	PDSPnoaxn	−
86	008617A6	DSPDSoaxx	−
87	008701C5	PDSaxn	−
88	008800C6	DSa	SRCAND
89	00891B08	SDPSnaoxn	−
8A	008A0E06	DSPnoa	−
8B	008B0666	DSPDxoxn	−
8C	008C0E08	SDPnoa	−
8D	008D0668	SDPSxoxn	−
8E	008E1D7C	SSDxPDxax	−
8F	008F0CE5	PDSanan	−
90	00900C45	PDSxna	−
91	00911E08	SDPSnoaxn	−
92	009217A9	DPSDPoaxx	−
93	009301C4	SPDaxn	−
94	009417AA	PSDPSoaxx	−
95	009501C9	DPSaxn	−
96	00960169	DPSxx	−
97	0097588A	PSDPSonoxx	−
98	00981888	SDPSonoxn	−
99	00990066	DSxn	−
9A	009A0709	DPSnax	−
9B	009B07A8	SDPSoaxn	−
9C	009C0704	SPDnax	−
9D	009D07A6	DSPDoaxn	−
9E	009E16E6	DSPDSaoxx	−
9F	009F0345	PDSxan	−
A0	00A000C9	DPa	−
A1	00A11B05	PDSPnaoxn	−
A2	00A20E09	DPSnoa	−
A3	00A30669	DPSDxoxn	−
A4	00A41885	PDSPonoxn	−
A5	00A50065	PDxn	−
A6	00A60706	DSPnax	−
A7	00A707A5	PDSPoaxn	−
A8	00A803A9	DPSoa	−
A9	00A90189	DPSoxn	−
AA	00AA0029	D	−
AB	00AB0889	DPSono	−
AC	00AC0744	SPDSxax	−
AD	00AD06E9	DPSDaoxn	−
AE	00AE0B06	DSPnao	−
AF	00AF0229	DPno	−
B0	00B00E05	PDSnoa	−
B1	00B10665	PDSPxoxn	−
B2	00B21974	SSPxDSxox	−
B3	00B30CE8	SDPanan	−
B4	00B4070A	PSDnax	−
B5	00B507A9	DPSDoaxn	−
B6	00B616E9	DPSDPaoxx	−
B7	00B70348	SDPxan	−
B8	00B8074A	PSDPxax	−
B9	00B906E6	DSPDaoxn	−
BA	00BA0B09	DPSnao	−
BB	00BB0226	DSno	MERGEPAINT
BC	00BC1CE4	SPDSanax	−
BD	00BD0D7D	SDxPDxan	−
BE	00BE0269	DPSxo	−
BF	00BF08C9	DPSano	−
C0	00C000CA	PSa	MERGECOPY
C1	00C11B04	SPDSnaoxn	−
C2	00C21884	SPDSonoxn	−
C3	00C3006A	PSxn	−
C4	00C40E04	SPDnoa	−
C5	00C50664	SPDSxoxn	−
C6	00C60708	SDPnax	−
C7	00C707AA	PSDPoaxn	−
C8	00C803A8	SDPoa	−
C9	00C90184	SPDoxn	−
CA	00CA0749	DPSDxax	−
CB	00CB06E4	SPDSaoxn	−
CC	00CC0020	S	SRCCOPY
CD	00CD0888	SDPono	−
CE	00CE0B08	SDPnao	−
CF	00CF0224	SPno	−
D0	00D00E0A	PSDnoa	−
D1	00D1066A	PSDPxoxn	−
D2	00D20705	PDSnax	−
D3	00D307A4	SPDSoaxn	−
D4	00D41D78	SSPxPDxax	−
D5	00D50CE9	DPSanan	−
D6	00D616EA	PSDPSaoxx	−
D7	00D70349	DPSxan	−
D8	00D80745	PDSPxax	−
D9	00D906E8	SDPSaoxn	−
DA	00DA1CE9	DPSDanax	−
DB	00DB0D75	SPxDSxan	−
DC	00DC0B04	SPDnao	−
DD	00DD0228	SDno	−
DE	00DE0268	SDPxo	−
DF	00DF08C8	SDPano	−
E0	00E003A5	PDSoa	−
E1	00E10185	PDSoxn	−
E2	00E20746	DSPDxax	−
E3	00E306EA	PSDPaoxn	−
E4	00E40748	SDPSxax	−
E5	00E506E5	PDSPaoxn	−
E6	00E61CE8	SDPSanax	−
E7	00E70D79	SPxPDxan	−
E8	00E81D74	SSPxDSxax	−
E9	00E95CE6	DSPDSanaxxn	−
EA	00EA02E9	DPSao	−
EB	00EB0849	DPSxno	−
EC	00EC02E8	SDPao	−
ED	00ED0848	SDPxno	−
EE	00EE0086	DSo	SRCPAINT
EF	00EF0A08	SDPnoo	−
F0	00F00021	P	PATCOPY
F1	00F10885	PDSono	−
F2	00F20B05	PDSnao	−
F3	00F3022A	PSno	−
F4	00F40B0A	PSDnao	−
F5	00F50225	PDno	−
F6	00F60265	PDSxo	−
F7	00F708C5	PDSano	−
F8	00F802E5	PDSao	−
F9	00F90845	PDSxno	−
FA	00FA0089	DPo	−
FB	00FB0A09	DPSnoo	PATPAINT
FC	00FC008A	PSo	−
FD	00FD0A0A	PSDnoo	−
FE	00FE02A9	DPSoo	−
FF	00FF0062	1	WHITENESS


 Error Codes

Alphabetic listing

Numerical listing


 Alphabetical List of Error Codes

EPT_S_CANT_CREATE

The endpoint mapper database could not be created.

EPT_S_CANT_PERFORM_OP

The operation cannot be performed.

EPT_S_INVALID_ENTRY

The entry is invalid.

EPT_S_NOT_REGISTERED

There are no more endpoints available from the endpoint mapper.

ERROR_ACCESS_DENIED

Access is denied.

ERROR_ACCOUNT_DISABLED

The referenced account is currently disabled and cannot be logged on to.

ERROR_ACCOUNT_EXPIRED

The user's account has expired.

ERROR_ACCOUNT_RESTRICTION

Indicates a referenced user name and authentication information are valid, but some user account restriction has prevented successful authentication (such as time-of-day restrictions).

ERROR_ADAP_HDW_ERR

A network adapter hardware error occurred.

ERROR_ALIAS_EXISTS

The specified alias already exists.

ERROR_ALLOTTED_SPACE_EXCEEDED

When a block of memory is allotted for future updates, such as the memory allocated to hold discretionary access control and primary group information, successive updates may exceed the amount of memory originally allotted. Since quota may already have been charged to several processes that have handles of the object, it is not reasonable to alter the size of the allocated memory. Instead, a request that requires more memory than has been allotted must fail and the ERROR_ALLOTTED_SPACE_EXCEEDED error returned.

ERROR_ALREADY_ASSIGNED

The local device name is already in use.

ERROR_ALREADY_EXISTS

Attempt to create file that already exists.

ERROR_ALREADY_RUNNING_LKG

The system is currently running with the last-known-good configuration.

ERROR_ARENA_TRASHED

The storage control blocks were destroyed.

ERROR_ARITHMETIC_OVERFLOW

Arithmetic result exceeded 32-bits.

ERROR_ATOMIC_LOCKS_NOT_SUPPORTED

The file system does not support atomic changing of the lock type.

ERROR_AUTODATASEG_EXCEEDS_64k

The operating system cannot run this application program.

ERROR_BAD_ARGUMENTS

The argument string passed to DosExecPgm is incorrect.

ERROR_BAD_COMMAND

The device does not recognize the command.

ERROR_BAD_DESCRIPTOR_FORMAT

Indicates a security descriptor is not in the required format (absolute or self-relative).

ERROR_BAD_DEV_TYPE

The network resource type is incorrect.

ERROR_BAD_DEVICE

The specified device name is invalid.

ERROR_BAD_DRIVER_LEVEL

The system does not support the requested command.

ERROR_BAD_ENVIRONMENT

The environment is incorrect.

ERROR_BAD_EXE_FORMAT

%1 is not a valid Windows-based application.

ERROR_BAD_FORMAT

An attempt was made to load a program with an incorrect format.

ERROR_BAD_IMPERSONATION_LEVEL

A specified impersonation level is invalid. Also used to indicate a required impersonation level was not provided.

ERROR_BAD_INHERITANCE_ACL

Indicates that an attempt to build either an inherited ACL or ACE did not succeed. One of the more probable causes is the replacement of a CreatorId with an SID that didn't fit into the ACE or ACL.

ERROR_BAD_LENGTH

The program issued a command but the command length is incorrect.

ERROR_BAD_LOGON_SESSION_STATE

The logon session is not in a state consistent with the requested operation.

ERROR_BAD_NET_NAME

The network name cannot be found.

ERROR_BAD_NET_RESP

The specified server cannot perform the requested operation.

ERROR_BAD_NETPATH

The network path was not found.

ERROR_BAD_PATHNAME

The specified path name is invalid.

ERROR_BAD_PIPE

The pipe state is invalid.

ERROR_BAD_PROFILE

The network connection profile is damaged.

ERROR_BAD_PROVIDER

The specified network provider name is invalid.

ERROR_BAD_REM_ADAP

The remote adapter is not compatible.

ERROR_BAD_THREADID_ADDR

The address for the thread ID is incorrect.

ERROR_BAD_TOKEN_TYPE

The type of token object is inappropriate for its attempted use.

ERROR_BAD_UNIT

The system cannot find the specified device.

ERROR_BAD_USERNAME

The specified user name is invalid.

ERROR_BAD_VALIDATION_CLASS

The requested validation information class is invalid.

ERROR_BADDB

The configuration registry database is damaged.

ERROR_BADKEY

The configuration registry key is invalid.

ERROR_BEGINNING_OF_MEDIA

The beginning of the tape or partition was encountered.

ERROR_BOOT_ALREADY_ACCEPTED

The current boot has already been accepted for use as the last-known-good control set.

ERROR_BROKEN_PIPE

The pipe was ended.

ERROR_BUFFER_OVERFLOW

The file name is too long.

ERROR_BUS_RESET

The I/O bus was reset.

ERROR_BUSY

The requested resource is in use.

ERROR_BUSY_DRIVE

The system cannot perform a JOIN or SUBST at this time.

ERROR_CALL_NOT_IMPLEMENTED

The Application Program Interface (API) entered will only work in Windows/NT mode.

ERROR_CAN_NOT_COMPLETE

Cannot complete function for some reason.

ERROR_CANCEL_VIOLATION

A lock request was not outstanding for the supplied cancel region.

ERROR_CANNOT_COPY

The Copy API cannot be used.

ERROR_CANNOT_FIND_WND_CLASS

Cannot find window class.

ERROR_CANNOT_IMPERSONATE

Indicates that an attempt was made to impersonate via a named pipe was not yet read from.

ERROR_CANNOT_MAKE

The directory or file cannot be created.

ERROR_CANNOT_OPEN_PROFILE

Unable to open the network connection profile.

ERROR_CANT_ACCESS_DOMAIN_INFO

Indicates a domain controller could not be contacted or that objects within the domain are protected and necessary information could not be retrieved.

ERROR_CANT_DISABLE_MANDATORY

A mandatory group cannot be disabled.

ERROR_CANT_OPEN_ANONYMOUS

An attempt was made to open an anonymous level token. Anonymous tokens cannot be opened.

ERROR_CANTOPEN

The configuration registry key cannot be opened.

ERROR_CANTREAD

The configuration registry key cannot be read.

ERROR_CANTWRITE

The configuration registry key cannot be written.

ERROR_CHILD_MUST_BE_VOLATILE

An attempt was made to create a stable subkey under a volatile parent key.

ERROR_CHILD_NOT_COMPLETE

The %1 application cannot be run in Windows mode.

ERROR_CHILD_WINDOW_MENU

Child windows can't have menus.

ERROR_CIRCULAR_DEPENDENCY

Circular service dependency was specified.

ERROR_CLASS_ALREADY_EXISTS

Class already exists.

ERROR_CLASS_DOES_NOT_EXIST

Class does not exist.

ERROR_CLASS_HAS_WINDOWS

Class still has open windows.

ERROR_CLIPBOARD_NOT_OPEN

Thread doesn't have clipboard open.

ERROR_CONNECTION_UNAVAIL

The device is not currently connected but is a remembered connection.

ERROR_CONTROL_ID_NOT_FOUND

Control ID not found.

ERROR_COUNTER_TIMEOUT

A serial I/O operation completed because the time-out period expired. (The IOCTL_SERIAL_XOFF_COUNTER did not reach zero.)

ERROR_CRC

Data error (cyclic redundancy check).

ERROR_CURRENT_DIRECTORY

The directory cannot be removed.

ERROR_DATABASE_DOES_NOT_EXIST

The database specified does not exist.

ERROR_DC_NOT_FOUND

Invalid HDC passed to ReleaseDC.

ERROR_DEPENDENT_SERVICES_RUNNING

A stop control has been sent to a service which other running services are dependent on.

ERROR_DESTROY_OBJECT_OF_OTHER_THREAD

Cannot destroy object created by another thread.

ERROR_DEV_NOT_EXIST

The specified network resource is no longer available.

ERROR_DEVICE_ALREADY_REMEMBERED

An attempt was made to remember a device that was previously remembered.

ERROR_DEVICE_IN_USE

The device is in use by an active process and cannot be disconnected.

ERROR_DEVICE_NOT_PARTITIONED

Tape partition information could not be found when loading a tape.

ERROR_DIR_NOT_EMPTY

The directory is not empty.

ERROR_DIR_NOT_ROOT

The directory is not a subdirectory of the root directory.

ERROR_DIRECT_ACCESS_HANDLE

Attempt to use a file handle to an open disk partition for an operation other than raw disk I/O.

ERROR_DIRECTORY

The directory name is invalid.

ERROR_DISCARDED

The segment is already discarded and cannot be locked.

ERROR_DISK_CHANGE

Program stopped because alternate disk was not inserted.

ERROR_DISK_CORRUPT

The disk structure is damaged and nonreadable.

ERROR_DISK_FULL

There is not enough space on the disk.

ERROR_DISK_OPERATION_FAILED

While accessing the hard disk, a disk operation failed even after retries.

ERROR_DISK_RECALIBRATE_FAILED

While accessing the hard disk, a recalibrate operation failed, even after retries.

ERROR_DISK_RESET_FAILED

While accessing the hard disk, a disk controller reset was needed, but even that failed.

ERROR_DLL_INIT_FAILED

A DLL initialization routine failed.

ERROR_DOMAIN_EXISTS

The specified domain already exists.

ERROR_DOMAIN_LIMIT_EXCEEDED

An attempt to exceed the limit on the number of domains per server for this release.

ERROR_DOMAIN_TRUST_INCONSISTENT

The name or security ID (SID) of the domain specified is inconsistent with the trust information for that domain.

ERROR_DRIVE_LOCKED

The disk is in use or locked by another process.

ERROR_DUP_DOMAINNAME

The workgroup or domain name is already in use by another computer on the network.

ERROR_DUP_NAME

A duplicate name exists on the network.

ERROR_DUPLICATE_SERVICE_NAME

The name is already in use as either a service name or a service display name.

ERROR_DYNLINK_FROM_INVALID_RING

The operating system cannot run this application program.

ERROR_EA_ACCESS_DENIED

Access to the EA is denied.

ERROR_EA_FILE_CORRUPT

The EA file on the mounted file system is damaged.

ERROR_EA_LIST_INCONSISTENT

The EAs are inconsistent.

ERROR_EA_TABLE_FULL

The EA table in the EA file on the mounted file system is full.

ERROR_EAS_DIDNT_FIT

The EAs did not fit in the buffer.

ERROR_EAS_NOT_SUPPORTED

The mounted file system does not support extended attributes.

ERROR_END_OF_MEDIA

End of tape mark was reached during an operation.

ERROR_ENVVAR_NOT_FOUND

The system could not find the environment option entered.

ERROR_EOM_OVERFLOW

Physical end of tape encountered.

ERROR_EVENTLOG_CANT_START

No event log file could be opened, so the event logging service did not start.

ERROR_EVENTLOG_FILE_CHANGED

The event log file has changed between reads.

ERROR_EVENTLOG_FILE_CORRUPT

One of the Eventlog logfiles is damaged.

ERROR_EXCEPTION_IN_SERVICE

An exception occurred in the service when handling the control request.

ERROR_EXCL_SEM_ALREADY_OWNED

The exclusive semaphore is owned by another process.

ERROR_EXE_MARKED_INVALID

The operating system cannot run %1.

ERROR_EXTENDED_ERROR

An extended error has occurred.

ERROR_FAIL_I24

Fail on INT 24.

ERROR_FAILED_SERVICE_CONTROLLER_CONNECT

The service process could not connect to the service controller.

ERROR_FILE_CORRUPT

The file or directory is damaged and nonreadable.

ERROR_FILE_EXISTS

The file exists.

ERROR_FILE_INVALID

The volume for a file was externally altered and the opened file is no longer valid.

ERROR_FILE_NOT_FOUND

The system cannot find the file specified.

ERROR_FILEMARK_DETECTED

A tape access reached a filemark.

ERROR_FILENAME_EXCED_RANGE

The file name or extension is too long.

ERROR_FLOPPY_BAD_REGISTERS

The floppy disk controller returned inconsistent results in its registers.

ERROR_FLOPPY_ID_MARK_NOT_FOUND

No ID address mark was found on the floppy disk.

ERROR_FLOPPY_WRONG_CYLINDER

Mismatch between the floppy disk sector ID field and the floppy disk controller track address.

ERROR_FLOPPY_UNKNOWN_ERROR

The floppy disk controller reported an error that is not recognized by the floppy disk driver.

ERROR_FULLSCREEN_MODE

The requested operation cannot be performed in full-screen mode.

ERROR_GEN_FAILURE

A device attached to the system is not functioning.

ERROR_GENERIC_NOT_MAPPED

Indicates generic access types were contained in an access mask that should already be mapped to non-generic access types.

ERROR_GLOBAL_ONLY_HOOK

This hook can only be set globally.

ERROR_GROUP_EXISTS

The specified group already exists.

ERROR_HANDLE_DISK_FULL

The disk is full.

ERROR_HANDLE_EOF

Reached End Of File.

ERROR_HOOK_NEEDS_HMOD

Cannot set non-local hook without an module handle.

ERROR_HOOK_NOT_INSTALLED

Hook is not installed.

ERROR_HOTKEY_ALREADY_REGISTERED

Hotkey is already registered.

ERROR_HOTKEY_NOT_REGISTERED

Hotkey is not registered.

ERROR_HWNDS_HAVE_DIFFERENT_PARENT

All DeferWindowPos HWNDs must have same parent.

ERROR_ILL_FORMED_PASSWORD

When trying to update a password, this return status indicates the value provided for the new password contains values not allowed in passwords.

ERROR_INFLOOP_IN_RELOC_CHAIN

The operating system cannot run %1.

ERROR_INSUFFICIENT_BUFFER

The data area passed to a system call is too small.

ERROR_INTERNAL_DB_CORRUPTION

This error indicates the requested operation cannot be completed due to a catastrophic media failure or on-disk data structure corruption.

ERROR_INTERNAL_DB_ERROR

The Local Security Authority (LSA) database contains in internal inconsistency.

ERROR_INTERNAL_ERROR

This error indicates the SAM server has encounterred an internal consistency error in its database. This catastrophic failure prevents further operation of SAM.

ERROR_INVALID_ACCEL_HANDLE

Invalid accelerator-table handle.

ERROR_INVALID_ACCESS

The access code is invalid.

ERROR_INVALID_ACCOUNT_NAME

The name provided is not a properly formed account name.

ERROR_INVALID_ACL

Indicates the ACL structure is not valid.

ERROR_INVALID_ADDRESS

Attempt to access invalid address.

ERROR_INVALID_AT_INTERRUPT_TIME

Cannot request exclusive semaphores at interrupt time.

ERROR_INVALID_BLOCK

The storage control block address is invalid.

ERROR_INVALID_BLOCK_LENGTH

When accessing a new tape of a multivolume partition, the current block size is incorrect.

ERROR_INVALID_CATEGORY

The IOCTL call made by the application program is incorrect.

ERROR_INVALID_COMBOBOX_MESSAGE

Invalid Message, combo box doesn't have an edit control.

ERROR_INVALID_COMPUTERNAME

The format of the specified computer name is invalid.

ERROR_INVALID_CURSOR_HANDLE

The cursor handle is invalid.

ERROR_INVALID_DATA

The data is invalid.

ERROR_INVALID_DATATYPE

The specified datatype is invalid.

ERROR_INVALID_DOMAINNAME

The format of the specified domain name is invalid.

ERROR_INVALID_DOMAIN_ROLE

Indicates the requested operation cannot be completed with the domain in its present role.

ERROR_INVALID_DOMAIN_STATE

Indicates the domain is in the wrong state to perform the desired operation.

ERROR_INVALID_DRIVE

The system cannot find the specified drive.

ERROR_INVALID_DWP_HANDLE

The DeferWindowPos handle is invalid.

ERROR_INVALID_EA_HANDLE

The specified EA handle is invalid.

ERROR_INVALID_EA_NAME

The specified EA name is invalid.

ERROR_INVALID_EDIT_HEIGHT

Height must be less than 256.

ERROR_INVALID_ENVIRONMENT

The Environment specified is invalid.

ERROR_INVALID_EVENT_COUNT

The number of specified semaphore events is incorrect.

ERROR_INVALID_EVENTNAME

The format of the specified event name is invalid.

ERROR_INVALID_EXE_SIGNATURE

%1 cannot be run in Windows/NT mode.

ERROR_INVALID_FILTER_PROC

The filter proc is invalid.

ERROR_INVALID_FLAG_NUMBER

The flag passed is incorrect.

ERROR_INVALID_FLAGS

The flags are invalid.

ERROR_INVALID_FUNCTION

The function is incorrect.

ERROR_INVALID_GROUP_ATTRIBUTES

The specified attributes are invalid, or incompatible with the attributes for the group as a whole.

ERROR_INVALID_GROUPNAME

The format of the specified group name is invalid.

ERROR_INVALID_GW_COMMAND

The GW_* command is invalid.

ERROR_INVALID_HANDLE

The internal file identifier is incorrect.

ERROR_INVALID_HOOK_FILTER

The hook filter type is invalid.

ERROR_INVALID_HOOK_HANDLE

The hook handle is invalid.

ERROR_INVALID_ICON_HANDLE

The icon handle is invalid.

ERROR_INVALID_ID_AUTHORITY

The value provided is an invalid value for an identifier authority.

ERROR_INVALID_INDEX

The index is invalid.

ERROR_INVALID_LB_MESSAGE

The message for single-selection list box is invalid.

ERROR_INVALID_LEVEL

The system call level is incorrect.

ERROR_INVALID_LIST_FORMAT

The list is not correct.

ERROR_INVALID_LOGON_HOURS

The user account has time restrictions and cannot be logged onto at this time.

ERROR_INVALID_LOGON_TYPE

Indicates an invalid value has been provided for LogonType has been requested.

ERROR_INVALID_MEMBER

A new member could not be added to an alias because the member has the wrong account type.

ERROR_INVALID_MENU_HANDLE

The menu handle is invalid.

ERROR_INVALID_MESSAGE

Window can't handle sent message.

ERROR_INVALID_MESSAGEDEST

The format of the specified message destination is invalid.

ERROR_INVALID_MESSAGENAME

The format of the specified message name is invalid.

ERROR_INVALID_MINALLOCSIZE

The operating system cannot run %1.

ERROR_INVALID_MODULETYPE

The operating system cannot run %1.

ERROR_INVALID_MSGBOX_STYLE

The message box style is invalid.

ERROR_INVALID_NAME

The file name, directory name, or volume label is syntactically incorrect.

ERROR_INVALID_NETNAME

The format of the specified network name is invalid.

ERROR_INVALID_ORDINAL

The operating system cannot run %1.

ERROR_INVALID_OWNER

Indicates a particular Security ID cannot be assigned as the owner of an object.

ERROR_INVALID_PARAMETER

The parameter is incorrect.

ERROR_INVALID_PASSWORD

The specified network password is incorrect.

ERROR_INVALID_PASSWORDNAME

The format of the specified password is invalid.

ERROR_INVALID_PRIMARY_GROUP

Indicates a particular Security ID cannot be assigned as the primary group of an object.

ERROR_INVALID_PRINTER_COMMAND

The printer command is invalid.

ERROR_INVALID_PRINTER_NAME

The printer name is invalid.

ERROR_INVALID_PRIORITY

The specified priority is invalid.

ERROR_INVALID_SCROLLBAR_RANGE

Scrollbar range greater than 0x7FFF.

ERROR_INVALID_SECURITY_DESCR

Indicates the SECURITY_DESCRIPTOR structure is invalid.

ERROR_INVALID_SEGDPL

The operating system cannot run %1.

ERROR_INVALID_SEGMENT_NUMBER

The system detected a segment number that is incorrect.

ERROR_INVALID_SEPARATOR_FILE

The specified separator file is invalid.

ERROR_INVALID_SERVER_STATE

Indicates the Sam Server was in the wrong state to perform the desired operation.

ERROR_INVALID_SERVICE_ACCOUNT

The account name is invalid or does not exist.

ERROR_INVALID_SERVICE_CONTROL

The requested control is not valid for this service

ERROR_INVALID_SERVICE_LOCK

The specified service database lock is invalid.

ERROR_INVALID_SERVICENAME

The format of the specified service name is invalid.

ERROR_INVALID_SHARENAME

The format of the specified share name is invalid.

ERROR_INVALID_SHOWWIN_COMMAND

The ShowWindow command is invalid.

ERROR_INVALID_SID

Indicates the SID structure is invalid.

ERROR_INVALID_SIGNAL_NUMBER

The signal being posted is incorrect.

ERROR_INVALID_SPI_VALUE

The SPI_* parameter is invalid.

ERROR_INVALID_STACKSEG

The operating system cannot run %1.

ERROR_INVALID_STARTING_CODESEG

The operating system cannot run %1.

ERROR_INVALID_SUB_AUTHORITY

Indicates the sub-authority value is invalid for the particular use.

ERROR_INVALID_TARGET_HANDLE

The target internal file identifier is incorrect.

ERROR_INVALID_THREAD_ID

The thread ID is invalid.

ERROR_INVALID_USER_BUFFER

The supplied user buffer is invalid for the requested operation.

ERROR_INVALID_VERIFY_SWITCH

The verify-on-write switch parameter value is incorrect.

ERROR_INVALID_WINDOW_HANDLE

The window handle invalid.

ERROR_INVALID_WORKSTATION

The user account is restricted and cannot be used to log on from the source workstation.

ERROR_IO_DEVICE

The request could not be performed because of an I/O device error.

ERROR_IO_INCOMPLETE

Overlapped IO event not in signaled state.

ERROR_IO_PENDING

Overlapped IO operation in progress.

ERROR_IOPL_NOT_ENABLED

The operating system is not presently configured to run this application.

ERROR_IRQ_BUSY

Unable to open a device that was sharing an interrupt request (IRQ) with other devices. At least one other device that uses that IRQ was already opened.

ERROR_IS_JOIN_PATH

Not enough resources are available to process this command.

ERROR_IS_JOIN_TARGET

A JOIN or SUBST command cannot be used for a drive that contains previously joined drives.

ERROR_IS_JOINED

An attempt was made to use a JOIN or SUBST command on a drive that is already joined.

ERROR_IS_SUBST_PATH

The path specified is being used in a substitute.

ERROR_IS_SUBST_TARGET

An attempt was made to join or substitute a drive for which a directory on the drive is the target of a previous substitute.

ERROR_IS_SUBSTED

An attempt was made to use a JOIN or SUBST command on a drive already substituted.

ERROR_ITERATED_DATA_EXCEEDS_64k

The operating system cannot run %1.

ERROR_JOIN_TO_JOIN

The system tried to join a drive to a directory on a joined drive.

ERROR_JOIN_TO_SUBST

The system tried to join a drive to a directory on a substituted drive.

ERROR_JOURNAL_HOOK_SET

The journal hook is already installed.

ERROR_KEY_DELETED

Illegal operation attempted on a registry key that has been marked for deletion.

ERROR_KEY_HAS_CHILDREN

An attempt was made to create a symbolic link in a registry key that already has subkeys or values.

ERROR_LABEL_TOO_LONG

The volume label entered exceeds the 11 character limit. The first 11 characters were written to disk. Any characters that exceeded the 11 character limit were automatically deleted.

ERROR_LAST_ADMIN

Indicates the requested operation would disable or delete the last remaining administration account. This is not allowed to prevent creating a situation where the system will not be administrable.

ERROR_LB_WITHOUT_TABSTOPS

This list box doesn't support tab stops.

ERROR_LISTBOX_ID_NOT_FOUND

List box ID not found.

ERROR_LM_CROSS_ENCRYPTION_REQUIRED

An attempt was made to change a user password in the security account manager without providing the required LM cross-encrypted password.

ERROR_LOCAL_USER_SESSION_KEY

A user session key was requested for a local RPC connection. The session key returned is a constant value and not unique to this connection.

ERROR_LOCK_FAILED

Attempt to lock a region of a file failed.

ERROR_LOCK_VIOLATION

The process cannot access the file because another process has locked a portion of the file.

ERROR_LOCKED

The segment is locked and cannot be reallocated.

ERROR_LOG_FILE_FULL

The event log file is full.

ERROR_LOGON_FAILURE

The attempted logon is invalid. This is due to either a bad user name or authentication information.

ERROR_LOGON_NOT_GRANTED

A requested type of logon, such as Interactive, Network, or Service, is not granted by the target system's local security policy. The system administrator can grant the required form of logon.

ERROR_LOGON_SESSION_COLLISION

The logon session ID is already in use.

ERROR_LOGON_SESSION_EXISTS

An attempt was made to start a new session manager or LSA logon session with an ID already in use.

ERROR_LOGON_TYPE_NOT_GRANTED

A user has requested a type of logon, such as interactive or network, that was not granted. An administrator has control over who may logon interactively and through the network.

ERROR_LUIDS_EXHAUSTED

Indicates there are no more LUID to allocate.

ERROR_MAX_THRDS_REACHED

No more threads can be created in the system.

ERROR_MEDIA_CHANGED

Media in drive may have changed.

ERROR_MEMBER_IN_ALIAS

The specified account name is not a member of the alias.

ERROR_MEMBER_IN_GROUP

The specified user account is already in the specified group account. Also used to indicate a group can not be deleted because it contains a member.

ERROR_MEMBER_NOT_IN_ALIAS

The specified account name is not a member of the alias.

ERROR_MEMBER_NOT_IN_GROUP

The specified user account is not a member of the specified group account.

ERROR_MEMBERS_PRIMARY_GROUP

Indicates a member cannot be removed from a group because the group is currently the member's primary group.

ERROR_META_EXPANSION_TOO_LONG

The global filename characters * or ? are entered incorrectly, or too many global filename characters are specified.

ERROR_MOD_NOT_FOUND

The specified module cannot be found.

ERROR_MORE_DATA

More data is available.

ERROR_MORE_WRITES

A serial I/O operation was completed by another write to the serial port. (The IOCTL_SERIAL_XOFF_COUNTER reached zero.)

ERROR_MR_MID_NOT_FOUND

The system cannot find message for message number 0x%1 in message file for %2.

ERROR_NEGATIVE_SEEK

An attempt was made to move the file pointer before the beginning of the file.

ERROR_NESTING_NOT_ALLOWED

Can't nest calls to LoadModule.

ERROR_NETLOGON_NOT_STARTED

An attempt was made to logon, but the network logon service was not started.

ERROR_NET_WRITE_FAULT

A write fault occurred on the network.

ERROR_NETNAME_DELETED

The specified network name is no longer available.

ERROR_NETWORK_ACCESS_DENIED

Network access is denied.

ERROR_NETWORK_BUSY

The network is busy.

ERROR_NO_BROWSER_SERVERS_FOUND

The list of servers for this workgroup is not currently available

ERROR_NO_DATA

Pipe close in progress.

ERROR_NO_DATA_DETECTED

During a tape access, the end of the data marker was reached.

ERROR_NO_IMPERSONATION_TOKEN

An attempt was made to operate on an impersonation token by a thread was not currently impersonating a client.

ERROR_NO_INHERITANCE

Indicates an ACL contains no inheritable components.

ERROR_NO_LOG_SPACE

System could not allocate required space in a registry log.

ERROR_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT

The account used is an interdomain trust account. Use your normal user account or remote user account to access this server.

ERROR_NOLOGON_SERVER_TRUST_ACCOUNT

The account used is an server trust account. Use your normal user account or remote user account to access this server.

ERROR_NO_LOGON_SERVERS

There are currently no logon servers available to service the logon request.

ERROR_NOLOGON_WORKSTATION_TRUST_ACCOUNT

The account used is a workstation trust account. Use your normal user account or remote user account to access this server.

ERROR_NO_MEDIA_IN_DRIVE

Tape query failed because of no media in drive.

ERROR_NO_MORE_FILES

There are no more files.

ERROR_NO_MORE_ITEMS

No more data is available.

ERROR_NO_MORE_SEARCH_HANDLES

No more internal file identifiers available.

ERROR_NO_NET_OR_BAD_PATH

No network provider accepted the given network path.

ERROR_NO_NETWORK

The network is not present or not started.

ERROR_NO_PROC_SLOTS

The system cannot start another process at this time.

ERROR_NO_QUOTAS_FOR_ACCOUNT

No system quota limits are specifically set for this account.

ERROR_NO_SCROLLBARS

Window does not have scroll bars.

ERROR_NO_SECURITY_ON_OBJECT

Indicates an attempt was made to operate on the security of an object that does not have security associated with it.

ERROR_NO_SHUTDOWN_IN_PROGRESS

An attempt to abort the shutdown of the system failed because no shutdown was in progress.

ERROR_NO_SIGNAL_SENT

No process in the command subtree has a signal handler.

ERROR_NO_SPOOL_SPACE

Space to store the file waiting to be printed is not available on the server.

ERROR_NO_SUCH_ALIAS

The specified alias does not exist.

ERROR_NO_SUCH_DOMAIN

The specified domain does not exist.

ERROR_NO_SUCH_GROUP

The specified group does not exist.

ERROR_NO_SUCH_LOGON_SESSION

A specified logon session does not exist. It may already have been terminated.

ERROR_NO_SUCH_MEMBER

A new member cannot be added to an alias because the member does not exist.

ERROR_NO_SUCH_PACKAGE

A specified authentication package is unknown.

ERROR_NO_SUCH_PRIVILEGE

A specified privilege does not exist.

ERROR_NO_SUCH_USER

The specified user does not exist.

ERROR_NO_SYSTEM_MENU

Window does not have system menu.

ERROR_NO_TOKEN

An attempt was made to reference a token that does not exist.

ERROR_NO_TRUST_LSA_SECRET

The workstation does not have a trust secret.

ERROR_NO_TRUST_SAM_ACCOUNT

The domain controller does not have an account for this workstation.

ERROR_NO_UNICODE_TRANSLATION

No mapping for the Unicode character exists in the target multi-byte code page.

ERROR_NO_USER_SESSION_KEY

There is no user session key for the specified logon session.

ERROR_NO_VOLUME_LABEL

The disk has no volume label.

ERROR_NO_WILDCARD_CHARACTERS

No wildcard characters found.

ERROR_NOACCESS

Invalid access to memory location.

ERROR_NON_MDICHILD_WINDOW

DefMDIChildProc called with a non-MDI child window.

ERROR_NONE_MAPPED

None of the information to be mapped has been translated.

ERROR_NOT_ALL_ASSIGNED

Indicates not all privileges referenced are assigned to the caller. This allows, for example, all privileges to be disabled without having to know exactly which privileges are assigned.

ERROR_NOT_CHILD_WINDOW

Window is not a child window.

ERROR_NOT_CONNECTED

This network connection does not exist.

ERROR_NOT_CONTAINER

Cannot enumerate a non-container.

ERROR_NOT_DOS_DISK

The specified disk cannot be accessed.

ERROR_NOT_ENOUGH_MEMORY

Not enough storage is available to process this command.

ERROR_NOT_ENOUGH_SERVER_MEMORY

Not enough server storage is available to process this command.

ERROR_NOT_JOINED

The system attempted to delete the JOIN of a drive not previously joined.

ERROR_NOT_LOCKED

The segment is already unlocked.

ERROR_NOT_LOGON_PROCESS

The requested action is restricted for use by logon processes only. The calling process has not registered as a logon process.

ERROR_NOT_OWNER

Attempt to release mutex not owned by caller.

ERROR_NOT_READY

The drive is not ready.

ERROR_NOT_REGISTRY_FILE

The system attempted to load or restore a file into the registry, and the specified file is not in the format of a registry file.

ERROR_NOT_SAME_DEVICE

The system cannot move the file to a different disk drive.

ERROR_NOT_SUBSTED

The system attempted to delete the substitution of a drive not previously substituted.

ERROR_NOT_SUPPORTED

The network request is not supported.

ERROR_NOTIFY_ENUM_DIR

This indicates that a notify change request is being completed and the information is not being returned in the caller's buffer. The caller now needs to enumerate the files to find the changes.

ERROR_NT_CROSS_ENCRYPTION_REQUIRED

An attempt was made to change a user password in the security account manager without providing the necessary NT cross-encrypted password.

ERROR_NULL_LM_PASSWORD

The Windows NT password is too complex to be converted to a Windows-networking password. The Windows-networking password returned is a NULL string.

ERROR_OPEN_FAILED

The system cannot open the specified device or file.

ERROR_OPEN_FILES

There are open files or requests pending on this connection.

ERROR_OPERATION_ABORTED

The I/O operation was aborted due to either thread exit or application request.

ERROR_OUT_OF_PAPER

The printer is out of paper.

ERROR_OUT_OF_STRUCTURES

Storage to process this request is not available.

ERROR_OUTOFMEMORY

Not enough storage is available to complete this operation.

ERROR_PARTITION_FAILURE

Tape could not be partitioned.

ERROR_PASSWORD_EXPIRED

The user account's password has expired.

ERROR_PASSWORD_RESTRICTION

When trying to update a password, this status indicates that some password update rule was violated. For example, the password may not meet length criteria.

ERROR_PATH_BUSY

The specified path cannot be used at this time.

ERROR_PATH_NOT_FOUND

The system cannot find the specified path.

ERROR_PIPE_BUSY

All pipe instances busy.

ERROR_PIPE_CONNECTED

There is a process on other end of the pipe.

ERROR_PIPE_LISTENING

Waiting for a process to open the other end of the pipe.

ERROR_PIPE_NOT_CONNECTED

No process on other end of pipe.

ERROR_POPUP_ALREADY_ACTIVE

Pop-up menu already active.

ERROR_POSSIBLE_DEADLOCK

A potential deadlock condition has been detected.

ERROR_PRINT_CANCELLED

File waiting to be printed was deleted.

ERROR_PRINTER_ALREADY_EXISTS

The printer already exists.

ERROR_PRINTER_DRIVER_ALREADY_INSTALLED

The specified printer driver is already installed.

ERROR_PRINTQ_FULL

The printer queue is full.

ERROR_PRIVATE_DIALOG_INDEX

Using private DIALOG window words.

ERROR_PRIVILEGE_NOT_HELD

A required privilege is not held by the client.

ERROR_PROC_NOT_FOUND

The specified procedure could not be found.

ERROR_PROCESS_ABORTED

The process terminated unexpectedly.

ERROR_READ_FAULT

The system cannot read from the specified device.

ERROR_REDIR_PAUSED

The specified printer or disk device has been paused.

ERROR_REDIRECTOR_HAS_OPEN_HANDLES

The redirector is in use and cannot be unloaded.

ERROR_REGISTRY_CORRUPT

The registry is damaged. The structure of one of the files that contains registry data is damaged, or the system's in memory image of the file is damaged, or the file could not be recovered because its alternate copy or log was absent or damaged.

ERROR_REGISTRY_IO_FAILED

The registry initiated an I/O operation that had an unrecoverable failure. The registry could not read in, or write out, or flush, one of the files that contain the system's image of the registry.

ERROR_REGISTRY_RECOVERED

One of the files containing the system's registry data had to be recovered by use of a log or alternate copy. The recovery succeeded.

ERROR_RELOC_CHAIN_XEEDS_SEGLIM

The operating system cannot run %1.

ERROR_REM_NOT_LIST

The remote computer is not available.

ERROR_REMOTE_SESSION_LIMIT_EXCEEDED

An attempt was made to establish a session to a LAN Manager server, but there are already too many sessions established to that server.

ERROR_REQ_NOT_ACCEP

The network request was not accepted.

ERROR_NOT_ENOUGH_QUOTA

Not enough quota is available to process this command.

ERROR_RESOURCE_DATA_NOT_FOUND

The specified image file did not contain a resource section.

ERROR_RESOURCE_LANG_NOT_FOUND

The specified resource language ID cannot be found in the image file.

ERROR_RESOURCE_NAME_NOT_FOUND

The specified resource name can not be found in the image file.

ERROR_RESOURCE_TYPE_NOT_FOUND

The specified resource type can not be found in the image file.

ERROR_REVISION_MISMATCH

Indicates two revision levels are incompatible.

ERROR_RING2_STACK_IN_USE

The ring 2 stack is in use.

ERROR_RING2SEG_MUST_BE_MOVABLE

The code segment cannot be greater than or equal to 64KB.

ERROR_RXACT_COMMIT_FAILURE

Indicates an error occurred during a registry transaction commit. The database has been left in an unknown state. The state of the registry transaction is left as COMMITTING. This status value is returned by the runtime library (RTL) registry transaction package (RXact).

ERROR_RXACT_INVALID_STATE

Indicates that the transaction state of a registry sub-tree is incompatible with the requested operation. For example, a request has been made to start a new transaction with one already in progress, or a request to apply a transaction when one is not currently in progress. This status value is returned by the runtime library (RTL) registry transaction package (RXact).

ERROR_SAME_DRIVE

The system cannot join or substitute a drive to or for a directory on the same drive.

ERROR_SCREEN_ALREADY_LOCKED

Screen already locked.

ERROR_SECRET_TOO_LONG

The length of a secret exceeds the maximum length allowed. The length and number of secrets is limited to satisfy the United States State Department export restrictions.

ERROR_SECTOR_NOT_FOUND

The drive cannot find the requested sector.

ERROR_SEEK

The drive cannot locate a specific area or track on the disk.

ERROR_SEEK_ON_DEVICE

The file pointer cannot be set on the specified device or file.

ERROR_SEM_IS_SET

The semaphore is set and cannot be closed.

ERROR_SEM_NOT_FOUND

The specified system semaphore name was not found.

ERROR_SEM_OWNER_DIED

The previous ownership of this semaphore has ended.

ERROR_SEM_TIMEOUT

The semaphore timeout period has expired.

ERROR_SEM_USER_LIMIT

Insert the disk for drive 1.

ERROR_SERIAL_NO_DEVICE

No serial device was successfully initialized. The serial driver will unload.

ERROR_SERVER_DISABLED

The GUID allocation server is already disabled at the moment.

ERROR_SERVER_HAS_OPEN_HANDLES

The server is in use and cannot be unloaded.

ERROR_SERVER_NOT_DISABLED

The GUID allocation server is already enabled at the moment.

ERROR_SERVICE_ALREADY_RUNNING

An instance of the service is already running.

ERROR_SERVICE_CANNOT_ACCEPT_CTRL

The service cannot accept control messages at this time.

ERROR_SERVICE_DATABASE_LOCKED

The service database is locked.

ERROR_SERVICE_DEPENDENCY_DELETED

The dependency service does not exist or has been marked for deletion.

ERROR_SERVICE_DEPENDENCY_FAIL

The dependency service or group failed to start.

ERROR_SERVICE_DISABLED

The specified service is disabled and cannot be started.

ERROR_SERVICE_DOES_NOT_EXIST

The specified service does not exist as an installed service.

ERROR_SERVICE_EXISTS

The specified service already exists.

ERROR_SERVICE_LOGON_FAILED

The service did not start due to a logon failure.

ERROR_SERVICE_MARKED_FOR_DELETE

The specified service has been marked for deletion.

ERROR_SERVICE_NEVER_STARTED

No attempts to start the service have been made since the last boot.

ERROR_SERVICE_NO_THREAD

A thread could not be created for the service.

ERROR_SERVICE_NOT_ACTIVE

The service has not been started.

ERROR_SERVICE_REQUEST_TIMEOUT

The service did not respond to the start or control request in a timely fashion.

ERROR_SERVICE_SPECIFIC_ERROR

The service has returned a service-specific error code.

ERROR_SERVICE_START_HANG

After starting, the service hung in a start-pending state.

ERROR_SESSION_CREDENTIAL_CONFLICT

The credentials supplied conflict with an existing set of credentials.

ERROR_SETCOUNT_ON_BAD_LB

LB_SETCOUNT sent to non-lazy list box.

ERROR_SETMARK_DETECTED

A tape access reached a setmark.

ERROR_SHARING_BUFFER_EXCEEDED

Too many files opened for sharing.

ERROR_SHARING_PAUSED

The remote server is paused or is in the process of being started.

ERROR_SHARING_VIOLATION

The process cannot access the file because it is being used by another process.

ERROR_SHUTDOWN_IN_PROGRESS

A system shutdown is in progress.

ERROR_SIGNAL_PENDING

A signal is already pending.

ERROR_SIGNAL_REFUSED

The recipient process has refused the signal.

ERROR_SOME_NOT_MAPPED

Some of the information to be mapped has not been translated.

ERROR_SPECIAL_ACCOUNT

Indicates an operation was attempted on a built-in (special) SAM account that is incompatible with built-in accounts. For example, built-in accounts cannot be renamed or deleted.

ERROR_SPECIAL_GROUP

The requested operation cannot be performed on the specified group because it is a built-in special group.

ERROR_SPECIAL_USER

The requested operation cannot be performed on the specified user because it is a built-in special user.

ERROR_STACK_OVERFLOW

Recursion too deep, stack overflowed.

ERROR_SUBST_TO_JOIN

The system attempted to SUBST a drive to a directory on a joined drive.

ERROR_SUBST_TO_SUBST

The system attempted to substitute a drive to a directory on a substituted drive.

ERROR_SUCCESS

The operation was successfully completed.

ERROR_SWAPERROR

Error accessing paging file.

ERROR_SYSTEM_TRACE

System trace information not specified in your CONFIG.SYS file, or tracing is not allowed.

ERROR_THREAD_1_INACTIVE

The signal handler cannot be set.

ERROR_TLW_WITH_WSCHILD

CreateWindow failed, creating top-level window with WS_CHILD style.

ERROR_TOKEN_ALREADY_IN_USE

An attempt was made to establish a token for use as a primary token but the token is already in use. A token can only be the primary token of one process at a time.

ERROR_TOO_MANY_CMDS

The network BIOS command limit has been reached.

ERROR_TOO_MANY_CONTEXT_IDS

During a logon attempt, the user's security context accumulated too many security IDs. Remove the user from some groups or aliases to reduce the number of security ids to incorporate into the security context.

ERROR_TOO_MANY_LUIDS_REQUESTED

The number of LUID requested cannot be allocated with a single allocation.

ERROR_TOO_MANY_MODULES

Too many dynamic link modules are attached to this program or dynamic link module.

ERROR_TOO_MANY_MUXWAITERS

Too many semaphores are already set.

ERROR_TOO_MANY_NAMES

The name limit for the local computer network adapter card exceeded.

ERROR_TOO_MANY_OPEN_FILES

The system cannot open the file.

ERROR_TOO_MANY_POSTS

Too many posts made to a semaphore.

ERROR_TOO_MANY_SECRETS

The maximum number of secrets that can be stored in a single system was exceeded. The length and number of secrets is limited to satisfy the United States State Department export restrictions.

ERROR_TOO_MANY_SEM_REQUESTS

The semaphore cannot be set again.

ERROR_TOO_MANY_SEMAPHORES

Cannot create another system semaphore.

ERROR_TOO_MANY_SESS

The network BIOS session limit exceeded.

ERROR_TOO_MANY_SIDS

Too many SIDs specified.

ERROR_TOO_MANY_TCBS

Cannot create another thread.

ERROR_TRUST_FAILURE

The network logon failed.

ERROR_TRUSTED_DOMAIN_FAILURE

The trust relationship between the primary domain and the trusted domain failed.

ERROR_TRUSTED_RELATIONSHIP_FAILURE

The trust relationship between this workstation and the primary domain failed.

ERROR_UNABLE_TO_LOCK_MEDIA

Attempt to lock the eject media mechanism failed.

ERROR_UNABLE_TO_UNLOAD_MEDIA

Unload media failed.

ERROR_UNEXP_NET_ERR

An unexpected network error occurred.

ERROR_UNKNOWN_PORT

The specified port is unknown.

ERROR_UNKNOWN_PRINTPROCESSOR

The print processor is unknown.

ERROR_UNKNOWN_PRINTER_DRIVER

The printer driver is unknown.

ERROR_UNKNOWN_REVISION

Indicates an encountered or specified revision number is not one known by the service. The service may not be aware of a more recent revision.

ERROR_UNRECOGNIZED_MEDIA

The disk media is not recognized. It may not be formatted.

ERROR_UNRECOGNIZED_VOLUME

The volume does not contain a recognized file system. Make sure that all required file system drivers are loaded and the volume is not damaged.

ERROR_USER_EXISTS

The specified user already exists.

ERROR_VC_DISCONNECTED

The session was canceled.

ERROR_WAIT_NO_CHILDREN

There are no child processes to wait for.

ERROR_WINDOW_NOT_COMBOBOX

The window is not a combo box.

ERROR_WINDOW_NOT_DIALOG

The window is not a valid dialog window.

ERROR_WINDOW_OF_OTHER_THREAD

Invalid window, belongs to other thread.

ERROR_WRITE_FAULT

The system cannot write to the specified device.

ERROR_WRITE_PROTECT

The media is write protected.

ERROR_WRONG_DISK

The wrong disk is in the drive. Insert %2 (Volume Serial Number: %3) into drive %1.

ERROR_WRONG_PASSWORD

When trying to update a password, this return status indicates the value provided as the current password is incorrect.

LZERROR_BADINHANDLE

Invalid input handle.

LZERROR_BADOUTHANDLE

Invalid output handle.

LZERROR_BADVALUE

Input parameter out of acceptable range.

LZERROR_GLOBALLOC

Insufficient memory for LZFile structure.

LZERROR_GLOBLOCK

Bad global handle.

LZERROR_READ

Corrupt compressed file format.

LZERROR_WRITE

Out of space for output file.

LZERROR_UNKNOWNALG

Compression algorithm not recognized.

NO_ERROR

No error.

RPC_S_ADDRESS_ERROR

An addressing error occurred in the server.

RPC_S_ALREADY_LISTENING

The server is already listening.

RPC_S_ALREADY_REGISTERED

The object UUID already registered.

RPC_S_BINDING_HAS_NO_AUTH

The binding does not contain any authentication information.

RPC_S_CALL_FAILED

The remote procedure call failed.

RPC_S_CALL_FAILED_DNE

The remote procedure call failed and did not execute.

RPC_S_CALL_IN_PROGRESS

A remote procedure call is already in progress for this thread.

RPC_S_CANNOT_SUPPORT

The requested operation is not supported.

RPC_S_CANT_CREATE_ENDPOINT

The endpoint cannot be created.

RPC_S_DUPLICATE_ENDPOINT

The endpoint is a duplicate.

RPC_S_ENTRY_ALREADY_EXISTS

The entry already exists.

RPC_S_ENTRY_NOT_FOUND

The entry is not found.

RPC_S_FP_DIV_ZERO

A floating point operation at the server caused a divide by zero.

RPC_S_FP_OVERFLOW

A floating point overflow occurred at the server.

RPC_S_FP_UNDERFLOW

A floating point underflow occurred at the server.

RPC_S_GROUP_MEMBER_NOT_FOUND

The group member was not found.

RPC_S_INCOMPLETE_NAME

The entry name is incomplete.

RPC_S_INTERFACE_NOT_FOUND

The interface was not found.

RPC_S_INTERNAL_ERROR

An internal error occurred in RPC.

RPC_S_INVALID_AUTH_IDENTITY

The security context is invalid.

RPC_S_INVALID_BINDING

The binding handle is invalid.

RPC_S_INVALID_BOUND

The array bounds are invalid.

RPC_S_INVALID_ENDPOINT_FORMAT

The endpoint format is invalid.

RPC_S_INVALID_NAME_SYNTAX

The name syntax is invalid.

RPC_S_INVALID_NET_ADDR

The network address is invalid.

RPC_S_INVALID_NETWORK_OPTIONS

The network options are invalid.

RPC_S_INVALID_OBJECT

The object universal unique identifier (UUID) is the nil UUID.

RPC_S_INVALID_RPC_PROTSEQ

The RPC protocol sequence is invalid.

RPC_S_INVALID_STRING_BINDING

The string binding is invalid.

RPC_S_INVALID_STRING_UUID

The string UUID is invalid.

RPC_S_INVALID_TAG

The tag is invalid.

RPC_S_INVALID_TIMEOUT

The timeout value is invalid.

RPC_S_INVALID_VERS_OPTION

The version option is invalid.

RPC_S_MAX_CALLS_TOO_SMALL

The maximum number of calls is too small.

RPC_S_NAME_SERVICE_UNAVAILABLE

The name service is unavailable.

RPC_S_NO_BINDINGS

There are no bindings.

RPC_S_NO_CALL_ACTIVE

There is not a remote procedure call active in this thread.

RPC_S_NO_CONTEXT_AVAILABLE

No security context is available to allow impersonation.

RPC_S_NO_ENDPOINT_FOUND

No endpoint was found.

RPC_S_NO_ENTRY_NAME

The binding does not contain an entry name.

RPC_S_NO_MORE_BINDINGS

There are no more bindings.

RPC_S_NO_MORE_MEMBERS

There are no more members.

RPC_S_NO_PROTSEQS

There are no protocol sequences.

RPC_S_NO_PROTSEQS_REGISTERED

No protocol sequences were registered.

RPC_S_NOT_LISTENING

The server is not listening.

RPC_S_OBJECT_NOT_FOUND

The object UUID was not found.

RPC_S_OUT_OF_RESOURCES

Not enough resources are available to complete this operation.

RPC_S_PROCNUM_OUT_OF_RANGE

The procedure number is out of range.

RPC_S_PROTOCOL_ERROR

An RPC protocol error occurred.

RPC_S_PROTSEQ_NOT_FOUND

The RPC protocol sequence was not found.

RPC_S_PROTSEQ_NOT_SUPPORTED

The RPC protocol sequence is not supported.

RPC_S_SERVER_OUT_OF_MEMORY

The server has insufficient memory to complete this operation.

RPC_S_SERVER_TOO_BUSY

The server is too busy to complete this operation.

RPC_S_SERVER_UNAVAILABLE

The server is unavailable.

RPC_S_STRING_TOO_LONG

The string is too long.

RPC_S_TYPE_ALREADY_REGISTERED

The type UUID is already registered.

RPC_S_UNKNOWN_AUTHN_LEVEL

The authentication level is unknown.

RPC_S_UNKNOWN_AUTHN_SERVICE

The authentication service is unknown.

RPC_S_UNKNOWN_AUTHN_TYPE

The authentication type is unknown.

RPC_S_UNKNOWN_AUTHZ_SERVICE

The authorization service is unknown.

RPC_S_UNKNOWN_IF

The interface is unknown.

RPC_S_UNKNOWN_MGR_TYPE

The manager type is unknown.

RPC_S_UNSUPPORTED_NAME_SYNTAX

The name syntax is not supported.

RPC_S_UNSUPPORTED_TRANS_SYN

The transfer syntax is not supported by the server.

RPC_S_UNSUPPORTED_TYPE

The type UUID is not supported.

RPC_S_UUID_NO_ADDRESS

No network address is available to use to construct a UUID.

RPC_S_WRONG_KIND_OF_BINDING

The binding handle is the incorrect type.

RPC_S_ZERO_DIVIDE

The server attempted an integer divide by zero.

RPC_X_BAD_STUB_DATA

The stub received bad data.

RPC_X_BYTE_COUNT_TOO_SMALL

The byte count is too small.

RPC_X_ENUM_VALUE_OUT_OF_RANGE

The enumeration value is out of range.

RPC_X_NO_MORE_ENTRIES

The list of servers available for auto_handle binding was exhausted.

RPC_X_NULL_REF_POINTER

A null reference pointer was passed to the stub.

RPC_X_SS_CANNOT_GET_CALL_HANDLE

The stub is unable to get the call handle.

RPC_X_SS_CHAR_TRANS_OPEN_FAIL

The file designated by DCERPCCHARTRANS cannot be opened.

RPC_X_SS_CHAR_TRANS_SHORT_FILE

The file containing the character translation table has fewer than 512 bytes.

RPC_X_SS_CONTEXT_DAMAGED

The context handle changed during a call.

RPC_X_SS_CONTEXT_MISMATCH

The context handle does not match any known context handles.

RPC_X_SS_HANDLES_MISMATCH

The binding handles passed to a remote procedure call do not match.

RPC_X_SS_IN_NULL_CONTEXT

A null context handle is passed as an [in] parameter.


 Numerical List of Error Codes

-8        LZERROR_UNKNOWNALG

-7        LZERROR_BADVALUE

-6        LZERROR_GLOBLOCK

-5        LZERROR_GLOBALLOC

-4        LZERROR_WRITE

-3        LZERROR_READ

-2        LZERROR_BADOUTHANDLE

-1        LZERROR_BADINHANDLE

0L        NO_ERROR

0L        ERROR_SUCCESS

1L        ERROR_INVALID_FUNCTION

2L        ERROR_FILE_NOT_FOUND

3L        ERROR_PATH_NOT_FOUND

4L        ERROR_TOO_MANY_OPEN_FILES

5L        ERROR_ACCESS_DENIED

6L        ERROR_INVALID_HANDLE

7L        ERROR_ARENA_TRASHED

8L        ERROR_NOT_ENOUGH_MEMORY

9L        ERROR_INVALID_BLOCK

10L       ROR_BAD_ENVIRONMENT

11L       ROR_BAD_FORMAT

12L       ROR_INVALID_ACCESS

13L       ROR_INVALID_DATA

14L       ROR_OUTOFMEMORY

15L       ROR_INVALID_DRIVE

16L       ROR_CURRENT_DIRECTORY

17L       ROR_NOT_SAME_DEVICE

18L       ROR_NO_MORE_FILES

19L       ROR_WRITE_PROTECT

20L       ROR_BAD_UNIT

21L       ROR_NOT_READY

22L       ROR_BAD_COMMAND

23L       ROR_CRC

24L       ROR_BAD_LENGTH

25L       ROR_SEEK

26L       ROR_NOT_DOS_DISK

27L       ROR_SECTOR_NOT_FOUND

28L       ROR_OUT_OF_PAPER

29L       ROR_WRITE_FAULT

30L       ROR_READ_FAULT

31L       ROR_GEN_FAILURE

32L       ROR_SHARING_VIOLATION

33L       ROR_LOCK_VIOLATION

34L       ROR_WRONG_DISK

36L       ROR_SHARING_BUFFER_EXCEEDED

38L       ROR_HANDLE_EOF

39L       ROR_HANDLE_DISK_FULL

50L       ROR_NOT_SUPPORTED

51L       ROR_REM_NOT_LIST

52L       ROR_DUP_NAME

53L       ROR_BAD_NETPATH

54L       ROR_NETWORK_BUSY

55L       ROR_DEV_NOT_EXIST

56L       ROR_TOO_MANY_CMDS

57L       ROR_ADAP_HDW_ERR

58L       ROR_BAD_NET_RESP

59L       ROR_UNEXP_NET_ERR

60L       ROR_BAD_REM_ADAP

61L       ROR_PRINTQ_FULL

62L       ROR_NO_SPOOL_SPACE

63L       ROR_PRINT_CANCELLED

64L       ROR_NETNAME_DELETED

65L       ROR_NETWORK_ACCESS_DENIED

66L       ROR_BAD_DEV_TYPE

67L       ROR_BAD_NET_NAME

68L       ROR_TOO_MANY_NAMES

69L       ROR_TOO_MANY_SESS

70L       ROR_SHARING_PAUSED

71L       ROR_REQ_NOT_ACCEP

72L       ROR_REDIR_PAUSED

80L       ROR_FILE_EXISTS

82L       ROR_CANNOT_MAKE

83L       ROR_FAIL_I24

84L       ROR_OUT_OF_STRUCTURES

85L       ROR_ALREADY_ASSIGNED

86L       ROR_INVALID_PASSWORD

87L       ROR_INVALID_PARAMETER

88L       ROR_NET_WRITE_FAULT

89L       ROR_NO_PROC_SLOTS

100L      RROR_TOO_MANY_SEMAPHORES

101L      RROR_EXCL_SEM_ALREADY_OWNED

102L      RROR_SEM_IS_SET

103L      RROR_TOO_MANY_SEM_REQUESTS

104L      RROR_INVALID_AT_INTERRUPT_TIME

105L      RROR_SEM_OWNER_DIED

106L      RROR_SEM_USER_LIMIT

107L      RROR_DISK_CHANGE

108L      RROR_DRIVE_LOCKED

109L      RROR_BROKEN_PIPE

110L      RROR_OPEN_FAILED

111L      RROR_BUFFER_OVERFLOW

112L      RROR_DISK_FULL

113L      RROR_NO_MORE_SEARCH_HANDLES

114L      RROR_INVALID_TARGET_HANDLE

117L      RROR_INVALID_CATEGORY

118L      RROR_INVALID_VERIFY_SWITCH

119L      RROR_BAD_DRIVER_LEVEL

120L      RROR_CALL_NOT_IMPLEMENTED

121L      RROR_SEM_TIMEOUT

122L      RROR_INSUFFICIENT_BUFFER

123L      RROR_INVALID_NAME

124L      RROR_INVALID_LEVEL

125L      RROR_NO_VOLUME_LABEL

126L      RROR_MOD_NOT_FOUND

127L      RROR_PROC_NOT_FOUND

128L      RROR_WAIT_NO_CHILDREN

129L      RROR_CHILD_NOT_COMPLETE

130L      RROR_DIRECT_ACCESS_HANDLE

131L      RROR_NEGATIVE_SEEK

132L      RROR_SEEK_ON_DEVICE

133L      RROR_IS_JOIN_TARGET

134L      RROR_IS_JOINED

135L      RROR_IS_SUBSTED

136L      RROR_NOT_JOINED

137L      RROR_NOT_SUBSTED

138L      RROR_JOIN_TO_JOIN

139L      RROR_SUBST_TO_SUBST

140L      RROR_JOIN_TO_SUBST

141L      RROR_SUBST_TO_JOIN

142L      RROR_BUSY_DRIVE

143L      RROR_SAME_DRIVE

144L      RROR_DIR_NOT_ROOT

145L      RROR_DIR_NOT_EMPTY

146L      RROR_IS_SUBST_PATH

147L      RROR_IS_JOIN_PATH

148L      RROR_PATH_BUSY

149L      RROR_IS_SUBST_TARGET

150L      RROR_SYSTEM_TRACE

151L      RROR_INVALID_EVENT_COUNT

152L      RROR_TOO_MANY_MUXWAITERS

153L      RROR_INVALID_LIST_FORMAT

154L      RROR_LABEL_TOO_LONG

155L      RROR_TOO_MANY_TCBS

156L      RROR_SIGNAL_REFUSED

157L      RROR_DISCARDED

158L      RROR_NOT_LOCKED

159L      RROR_BAD_THREADID_ADDR

160L      RROR_BAD_ARGUMENTS

161L      RROR_BAD_PATHNAME

162L      RROR_SIGNAL_PENDING

164L      RROR_MAX_THRDS_REACHED

167L      RROR_LOCK_FAILED

170L      RROR_BUSY

173L      RROR_CANCEL_VIOLATION

174L      RROR_ATOMIC_LOCKS_NOT_SUPPORTED

180L      RROR_INVALID_SEGMENT_NUMBER

182L      RROR_INVALID_ORDINAL

183L      RROR_ALREADY_EXISTS

186L      RROR_INVALID_FLAG_NUMBER

187L      RROR_SEM_NOT_FOUND

188L      RROR_INVALID_STARTING_CODESEG

189L      RROR_INVALID_STACKSEG

190L      RROR_INVALID_MODULETYPE

191L      RROR_INVALID_EXE_SIGNATURE

192L      RROR_EXE_MARKED_INVALID

193L      RROR_BAD_EXE_FORMAT

194L      RROR_ITERATED_DATA_EXCEEDS_64k

195L      RROR_INVALID_MINALLOCSIZE

196L      RROR_DYNLINK_FROM_INVALID_RING

197L      RROR_IOPL_NOT_ENABLED

198L      RROR_INVALID_SEGDPL

199L      RROR_AUTODATASEG_EXCEEDS_64k

200L      RROR_RING2SEG_MUST_BE_MOVABLE

201L      RROR_RELOC_CHAIN_XEEDS_SEGLIM

202L      RROR_INFLOOP_IN_RELOC_CHAIN

203L      RROR_ENVVAR_NOT_FOUND

205L      RROR_NO_SIGNAL_SENT

206L      RROR_FILENAME_EXCED_RANGE

207L      RROR_RING2_STACK_IN_USE

208L      RROR_META_EXPANSION_TOO_LONG

209L      RROR_INVALID_SIGNAL_NUMBER

210L      RROR_THREAD_1_INACTIVE

212L      RROR_LOCKED

214L      RROR_TOO_MANY_MODULES

215L      RROR_NESTING_NOT_ALLOWED

230L      RROR_BAD_PIPE

231L      RROR_PIPE_BUSY

232L      RROR_NO_DATA

233L      RROR_PIPE_NOT_CONNECTED

234L      RROR_MORE_DATA

240L      RROR_VC_DISCONNECTED

254L      RROR_INVALID_EA_NAME

255L      RROR_EA_LIST_INCONSISTENT

259L      RROR_NO_MORE_ITEMS

266L      RROR_CANNOT_COPY

267L      RROR_DIRECTORY

275L      RROR_EAS_DIDNT_FIT

276L      RROR_EA_FILE_CORRUPT

277L      RROR_EA_TABLE_FULL

278L      RROR_INVALID_EA_HANDLE

282L      RROR_EAS_NOT_SUPPORTED

288L      RROR_NOT_OWNER

298L      RROR_TOO_MANY_POSTS

317L      RROR_MR_MID_NOT_FOUND

487L      RROR_INVALID_ADDRESS

534L      RROR_ARITHMETIC_OVERFLOW

535L      RROR_PIPE_CONNECTED

536L      RROR_PIPE_LISTENING

994L      RROR_EA_ACCESS_DENIED

995L      RROR_OPERATION_ABORTED

996L      RROR_IO_INCOMPLETE

997L      RROR_IO_PENDING

998L      RROR_NOACCESS

999L      RROR_SWAPERROR

1001L     ERROR_STACK_OVERFLOW

1002L     ERROR_INVALID_MESSAGE

1003L     ERROR_CAN_NOT_COMPLETE

1004L     ERROR_INVALID_FLAGS

1005L     ERROR_UNRECOGNIZED_VOLUME

1006L     ERROR_FILE_INVALID

1007L     ERROR_FULLSCREEN_MODE

1008L     ERROR_NO_TOKEN

1009L     ERROR_BADDB

1010L     ERROR_BADKEY

1011L     ERROR_CANTOPEN

1012L     ERROR_CANTREAD

1013L     ERROR_CANTWRITE

1014L     ERROR_REGISTRY_RECOVERED

1015L     ERROR_REGISTRY_CORRUPT

1016L     ERROR_REGISTRY_IO_FAILED

1017L     ERROR_NOT_REGISTRY_FILE

1018L     ERROR_KEY_DELETED

1019L     ERROR_NO_LOG_SPACE

1020L     ERROR_KEY_HAS_CHILDREN

1021L     ERROR_CHILD_MUST_BE_VOLATILE

1022L     ERROR_NOTIFY_ENUM_DIR

1051L     ERROR_DEPENDENT_SERVICES_RUNNING

1052L     ERROR_INVALID_SERVICE_CONTROL

1053L     ERROR_SERVICE_REQUEST_TIMEOUT

1054L     ERROR_SERVICE_NO_THREAD

1055L     ERROR_SERVICE_DATABASE_LOCKED

1056L     ERROR_SERVICE_ALREADY_RUNNING

1057L     ERROR_INVALID_SERVICE_ACCOUNT

1058L     ERROR_SERVICE_DISABLED

1059L     ERROR_CIRCULAR_DEPENDENCY

1060L     ERROR_SERVICE_DOES_NOT_EXIST

1061L     ERROR_SERVICE_CANNOT_ACCEPT_CTRL

1062L     ERROR_SERVICE_NOT_ACTIVE

1063L     ERROR_FAILED_SERVICE_CONTROLLER_CONNECT

1064L     ERROR_EXCEPTION_IN_SERVICE

1065L     ERROR_DATABASE_DOES_NOT_EXIST

1066L     ERROR_SERVICE_SPECIFIC_ERROR

1067L     ERROR_PROCESS_ABORTED

1068L     ERROR_SERVICE_DEPENDENCY_FAIL

1069L     ERROR_SERVICE_LOGON_FAILED

1070L     ERROR_SERVICE_START_HANG

1071L     ERROR_INVALID_SERVICE_LOCK

1072L     ERROR_SERVICE_MARKED_FOR_DELETE

1073L     ERROR_SERVICE_EXISTS

1074L     ERROR_ALREADY_RUNNING_LKG

1075L     ERROR_SERVICE_DEPENDENCY_DELETED

1076L     ERROR_BOOT_ALREADY_ACCEPTED

1077L     ERROR_SERVICE_NEVER_STARTED

1078L     ERROR_DUPLICATE_SERVICE_NAME

1100L     ERROR_END_OF_MEDIA

1101L     ERROR_FILEMARK_DETECTED

1102L     ERROR_BEGINNING_OF_MEDIA

1103L     ERROR_SETMARK_DETECTED

1104L     ERROR_NO_DATA_DETECTED

1105L     ERROR_PARTITION_FAILURE

1106L     ERROR_INVALID_BLOCK_LENGTH

1107L     ERROR_DEVICE_NOT_PARTITIONED

1108L     ERROR_UNABLE_TO_LOCK_MEDIA

1109L     ERROR_UNABLE_TO_UNLOAD_MEDIA

1110L     ERROR_MEDIA_CHANGED

1111L     ERROR_BUS_RESET

1112L     ERROR_NO_MEDIA_IN_DRIVE

1113L     ERROR_NO_UNICODE_TRANSLATION

1114L     ERROR_DLL_INIT_FAILED

1115L     ERROR_SHUTDOWN_IN_PROGRESS

1116L     ERROR_NO_SHUTDOWN_IN_PROGRESS

1117L     ERROR_IO_DEVICE

1118L     ERROR_SERIAL_NO_DEVICE

1119L     ERROR_IRQ_BUSY

1120L     ERROR_MORE_WRITES

1121L     ERROR_COUNTER_TIMEOUT

1122L     ERROR_FLOPPY_ID_MARK_NOT_FOUND

1123L     ERROR_FLOPPY_WRONG_CYLINDER

1124L     ERROR_FLOPPY_UNKNOWN_ERROR

1125L     ERROR_FLOPPY_BAD_REGISTERS

1126L     ERROR_DISK_RECALIBRATE_FAILED

1127L     ERROR_DISK_OPERATION_FAILED

1128L     ERROR_DISK_RESET_FAILED

1129L     ERROR_EOM_OVERFLOW

1130L     ERROR_NOT_ENOUGH_SERVER_MEMORY

1131L     ERROR_POSSIBLE_DEADLOCK

1200L     ERROR_BAD_DEVICE

1201L     ERROR_CONNECTION_UNAVAIL

1202L     ERROR_DEVICE_ALREADY_REMEMBERED

1203L     ERROR_NO_NET_OR_BAD_PATH

1204L     ERROR_BAD_PROVIDER

1205L     ERROR_CANNOT_OPEN_PROFILE

1206L     ERROR_BAD_PROFILE

1207L     ERROR_NOT_CONTAINER

1208L     ERROR_EXTENDED_ERROR

1209L     ERROR_INVALID_GROUPNAME

1210L     ERROR_INVALID_COMPUTERNAME

1211L     ERROR_INVALID_EVENTNAME

1212L     ERROR_INVALID_DOMAINNAME

1213L     ERROR_INVALID_SERVICENAME

1214L     ERROR_INVALID_NETNAME

1215L     ERROR_INVALID_SHARENAME

1216L     ERROR_INVALID_PASSWORDNAME

1217L     ERROR_INVALID_MESSAGENAME

1218L     ERROR_INVALID_MESSAGEDEST

1219L     ERROR_SESSION_CREDENTIAL_CONFLICT

1220L     ERROR_REMOTE_SESSION_LIMIT_EXCEEDED

1221L     ERROR_DUP_DOMAINNAME

1300L     ERROR_NOT_ALL_ASSIGNED

1301L     ERROR_SOME_NOT_MAPPED

1302L     ERROR_NO_QUOTAS_FOR_ACCOUNT

1303L     ERROR_LOCAL_USER_SESSION_KEY

1304L     ERROR_NULL_LM_PASSWORD

1305L     ERROR_UNKNOWN_REVISION

1306L     ERROR_REVISION_MISMATCH

1307L     ERROR_INVALID_OWNER

1308L     ERROR_INVALID_PRIMARY_GROUP

1309L     ERROR_NO_IMPERSONATION_TOKEN

1310L     ERROR_CANT_DISABLE_MANDATORY

1311L     ERROR_NO_LOGON_SERVERS

1312L     ERROR_NO_SUCH_LOGON_SESSION

1313L     ERROR_NO_SUCH_PRIVILEGE

1314L     ERROR_PRIVILEGE_NOT_HELD

1315L     ERROR_INVALID_ACCOUNT_NAME

1316L     ERROR_USER_EXISTS

1317L     ERROR_NO_SUCH_USER

1318L     ERROR_GROUP_EXISTS

1319L     ERROR_NO_SUCH_GROUP

1320L     ERROR_MEMBER_IN_GROUP

1321L     ERROR_MEMBER_NOT_IN_GROUP

1322L     ERROR_LAST_ADMIN

1323L     ERROR_WRONG_PASSWORD

1324L     ERROR_ILL_FORMED_PASSWORD

1325L     ERROR_PASSWORD_RESTRICTION

1326L     ERROR_LOGON_FAILURE

1327L     ERROR_ACCOUNT_RESTRICTION

1328L     ERROR_INVALID_LOGON_HOURS

1329L     ERROR_INVALID_WORKSTATION

1330L     ERROR_PASSWORD_EXPIRED

1331L     ERROR_ACCOUNT_DISABLED

1332L     ERROR_NONE_MAPPED

1333L     ERROR_TOO_MANY_LUIDS_REQUESTED

1334L     ERROR_LUIDS_EXHAUSTED

1335L     ERROR_INVALID_SUB_AUTHORITY

1336L     ERROR_INVALID_ACL

1337L     ERROR_INVALID_SID

1338L     ERROR_INVALID_SECURITY_DESCR

1340L     ERROR_BAD_INHERITANCE_ACL

1341L     ERROR_SERVER_DISABLED

1342L     ERROR_SERVER_NOT_DISABLED

1343L     ERROR_INVALID_ID_AUTHORITY

1344L     ERROR_ALLOTTED_SPACE_EXCEEDED

1345L     ERROR_INVALID_GROUP_ATTRIBUTES

1346L     ERROR_BAD_IMPERSONATION_LEVEL

1347L     ERROR_CANT_OPEN_ANONYMOUS

1348L     ERROR_BAD_VALIDATION_CLASS

1349L     ERROR_BAD_TOKEN_TYPE

1350L     ERROR_NO_SECURITY_ON_OBJECT

1351L     ERROR_CANT_ACCESS_DOMAIN_INFO

1352L     ERROR_INVALID_SERVER_STATE

1353L     ERROR_INVALID_DOMAIN_STATE

1354L     ERROR_INVALID_DOMAIN_ROLE

1355L     ERROR_NO_SUCH_DOMAIN

1356L     ERROR_DOMAIN_EXISTS

1357L     ERROR_DOMAIN_LIMIT_EXCEEDED

1358L     ERROR_INTERNAL_DB_CORRUPTION

1359L     ERROR_INTERNAL_ERROR

1360L     ERROR_GENERIC_NOT_MAPPED

1361L     ERROR_BAD_DESCRIPTOR_FORMAT

1362L     ERROR_NOT_LOGON_PROCESS

1363L     ERROR_LOGON_SESSION_EXISTS

1364L     ERROR_NO_SUCH_PACKAGE

1365L     ERROR_BAD_LOGON_SESSION_STATE

1366L     ERROR_LOGON_SESSION_COLLISION

1367L     ERROR_INVALID_LOGON_TYPE

1368L     ERROR_CANNOT_IMPERSONATE

1369L     ERROR_RXACT_INVALID_STATE

1370L     ERROR_RXACT_COMMIT_FAILURE

1371L     ERROR_SPECIAL_ACCOUNT

1372L     ERROR_SPECIAL_GROUP

1373L     ERROR_SPECIAL_USER

1374L     ERROR_MEMBERS_PRIMARY_GROUP

1375L     ERROR_TOKEN_ALREADY_IN_USE

1376L     ERROR_NO_SUCH_ALIAS

1377L     ERROR_MEMBER_NOT_IN_ALIAS

1378L     ERROR_MEMBER_IN_ALIAS

1379L     ERROR_ALIAS_EXISTS

1380L     ERROR_LOGON_NOT_GRANTED

1381L     ERROR_TOO_MANY_SECRETS

1382L     ERROR_SECRET_TOO_LONG

1383L     ERROR_INTERNAL_DB_ERROR

1384L     ERROR_TOO_MANY_CONTEXT_IDS

1385L     ERROR_LOGON_TYPE_NOT_GRANTED

1386L     ERROR_NT_CROSS_ENCRYPTION_REQUIRED

1387L     ERROR_NO_SUCH_MEMBER

1388L     ERROR_INVALID_MEMBER

1389L     ERROR_TOO_MANY_SIDS

1390L     ERROR_LM_CROSS_ENCRYPTION_REQUIRED

1391L     ERROR_NO_INHERITANCE

1392L     ERROR_FILE_CORRUPT

1393L     ERROR_DISK_CORRUPT

1394L     ERROR_NO_USER_SESSION_KEY

1400L     ERROR_INVALID_WINDOW_HANDLE

1401L     ERROR_INVALID_MENU_HANDLE

1402L     ERROR_INVALID_CURSOR_HANDLE

1403L     ERROR_INVALID_ACCEL_HANDLE

1404L     ERROR_INVALID_HOOK_HANDLE

1405L     ERROR_INVALID_DWP_HANDLE

1406L     ERROR_TLW_WITH_WSCHILD

1407L     ERROR_CANNOT_FIND_WND_CLASS

1408L     ERROR_WINDOW_OF_OTHER_THREAD

1409L     ERROR_HOTKEY_ALREADY_REGISTERED

1410L     ERROR_CLASS_ALREADY_EXISTS

1411L     ERROR_CLASS_DOES_NOT_EXIST

1412L     ERROR_CLASS_HAS_WINDOWS

1413L     ERROR_INVALID_INDEX

1414L     ERROR_INVALID_ICON_HANDLE

1415L     ERROR_PRIVATE_DIALOG_INDEX

1416L     ERROR_LISTBOX_ID_NOT_FOUND

1417L     ERROR_NO_WILDCARD_CHARACTERS

1418L     ERROR_CLIPBOARD_NOT_OPEN

1419L     ERROR_HOTKEY_NOT_REGISTERED

1420L     ERROR_WINDOW_NOT_DIALOG

1421L     ERROR_CONTROL_ID_NOT_FOUND

1422L     ERROR_INVALID_COMBOBOX_MESSAGE

1423L     ERROR_WINDOW_NOT_COMBOBOX

1424L     ERROR_INVALID_EDIT_HEIGHT

1425L     ERROR_DC_NOT_FOUND

1426L     ERROR_INVALID_HOOK_FILTER

1427L     ERROR_INVALID_FILTER_PROC

1428L     ERROR_HOOK_NEEDS_HMOD

1429L     ERROR_GLOBAL_ONLY_HOOK

1430L     ERROR_JOURNAL_HOOK_SET

1431L     ERROR_HOOK_NOT_INSTALLED

1432L     ERROR_INVALID_LB_MESSAGE

1433L     ERROR_SETCOUNT_ON_BAD_LB

1434L     ERROR_LB_WITHOUT_TABSTOPS

1435L     ERROR_DESTROY_OBJECT_OF_OTHER_THREAD

1436L     ERROR_CHILD_WINDOW_MENU

1437L     ERROR_NO_SYSTEM_MENU

1438L     ERROR_INVALID_MSGBOX_STYLE

1439L     ERROR_INVALID_SPI_VALUE

1440L     ERROR_SCREEN_ALREADY_LOCKED

1441L     ERROR_HWNDS_HAVE_DIFFERENT_PARENT

1442L     ERROR_NOT_CHILD_WINDOW

1443L     ERROR_INVALID_GW_COMMAND

1444L     ERROR_INVALID_THREAD_ID

1445L     ERROR_NON_MDICHILD_WINDOW

1446L     ERROR_POPUP_ALREADY_ACTIVE

1447L     ERROR_NO_SCROLLBARS

1448L     ERROR_INVALID_SCROLLBAR_RANGE

1449L     ERROR_INVALID_SHOWWIN_COMMAND

1500L     ERROR_EVENTLOG_FILE_CORRUPT

1501L     ERROR_EVENTLOG_CANT_START

1502L     ERROR_LOG_FILE_FULL

1503L     ERROR_EVENTLOG_FILE_CHANGED

1700L     RPC_S_INVALID_STRING_BINDING

1701L     RPC_S_WRONG_KIND_OF_BINDING

1702L     RPC_S_INVALID_BINDING

1703L     RPC_S_PROTSEQ_NOT_SUPPORTED

1704L     RPC_S_INVALID_RPC_PROTSEQ

1705L     RPC_S_INVALID_STRING_UUID

1706L     RPC_S_INVALID_ENDPOINT_FORMAT

1707L     RPC_S_INVALID_NET_ADDR

1708L     RPC_S_NO_ENDPOINT_FOUND

1709L     RPC_S_INVALID_TIMEOUT

1710L     RPC_S_OBJECT_NOT_FOUND

1711L     RPC_S_ALREADY_REGISTERED

1712L     RPC_S_TYPE_ALREADY_REGISTERED

1713L     RPC_S_ALREADY_LISTENING

1714L     RPC_S_NO_PROTSEQS_REGISTERED

1715L     RPC_S_NOT_LISTENING

1716L     RPC_S_UNKNOWN_MGR_TYPE

1717L     RPC_S_UNKNOWN_IF

1718L     RPC_S_NO_BINDINGS

1719L     RPC_S_NO_PROTSEQS

1720L     RPC_S_CANT_CREATE_ENDPOINT

1721L     RPC_S_OUT_OF_RESOURCES

1722L     RPC_S_SERVER_UNAVAILABLE

1723L     RPC_S_SERVER_TOO_BUSY

1724L     RPC_S_INVALID_NETWORK_OPTIONS

1725L     RPC_S_NO_CALL_ACTIVE

1726L     RPC_S_CALL_FAILED

1727L     RPC_S_CALL_FAILED_DNE

1728L     RPC_S_PROTOCOL_ERROR

1730L     RPC_S_UNSUPPORTED_TRANS_SYN

1731L     RPC_S_SERVER_OUT_OF_MEMORY

1732L     RPC_S_UNSUPPORTED_TYPE

1733L     RPC_S_INVALID_TAG

1734L     RPC_S_INVALID_BOUND

1735L     RPC_S_NO_ENTRY_NAME

1736L     RPC_S_INVALID_NAME_SYNTAX

1737L     RPC_S_UNSUPPORTED_NAME_SYNTAX

1739L     RPC_S_UUID_NO_ADDRESS

1740L     RPC_S_DUPLICATE_ENDPOINT

1741L     RPC_S_UNKNOWN_AUTHN_TYPE

1742L     RPC_S_MAX_CALLS_TOO_SMALL

1743L     RPC_S_STRING_TOO_LONG

1744L     RPC_S_PROTSEQ_NOT_FOUND

1745L     RPC_S_PROCNUM_OUT_OF_RANGE

1746L     RPC_S_BINDING_HAS_NO_AUTH

1747L     RPC_S_UNKNOWN_AUTHN_SERVICE

1748L     RPC_S_UNKNOWN_AUTHN_LEVEL

1749L     RPC_S_INVALID_AUTH_IDENTITY

1750L     RPC_S_UNKNOWN_AUTHZ_SERVICE

1751L     EPT_S_INVALID_ENTRY

1752L     EPT_S_CANT_PERFORM_OP

1753L     EPT_S_NOT_REGISTERED

1755L     RPC_S_INCOMPLETE_NAME

1756L     RPC_S_INVALID_VERS_OPTION

1757L     RPC_S_NO_MORE_MEMBERS

1759L     RPC_S_INTERFACE_NOT_FOUND

1760L     RPC_S_ENTRY_ALREADY_EXISTS

1761L     RPC_S_ENTRY_NOT_FOUND

1762L     RPC_S_NAME_SERVICE_UNAVAILABLE

1764L     RPC_S_CANNOT_SUPPORT

1765L     RPC_S_NO_CONTEXT_AVAILABLE

1766L     RPC_S_INTERNAL_ERROR

1767L     RPC_S_ZERO_DIVIDE

1768L     RPC_S_ADDRESS_ERROR

1769L     RPC_S_FP_DIV_ZERO

1770L     RPC_S_FP_UNDERFLOW

1771L     RPC_S_FP_OVERFLOW

1772L     RPC_X_NO_MORE_ENTRIES

1773L     RPC_X_SS_CHAR_TRANS_OPEN_FAIL

1774L     RPC_X_SS_CHAR_TRANS_SHORT_FILE

1775L     RPC_X_SS_IN_NULL_CONTEXT

1776L     RPC_X_SS_CONTEXT_MISMATCH

1777L     RPC_X_SS_CONTEXT_DAMAGED

1778L     RPC_X_SS_HANDLES_MISMATCH

1779L     RPC_X_SS_CANNOT_GET_CALL_HANDLE

1780L     RPC_X_NULL_REF_POINTER

1781L     RPC_X_ENUM_VALUE_OUT_OF_RANGE

1782L     RPC_X_BYTE_COUNT_TOO_SMALL

1783L     RPC_X_BAD_STUB_DATA

1784L     ERROR_INVALID_USER_BUFFER

1785L     ERROR_UNRECOGNIZED_MEDIA

1786L     ERROR_NO_TRUST_LSA_SECRET

1787L     ERROR_NO_TRUST_SAM_ACCOUNT

1788L     ERROR_TRUSTED_DOMAIN_FAILURE

1789L     ERROR_TRUSTED_RELATIONSHIP_FAILURE

1790L     ERROR_TRUST_FAILURE

1791L     RPC_S_CALL_IN_PROGRESS

1792L     ERROR_NETLOGON_NOT_STARTED

1793L     ERROR_ACCOUNT_EXPIRED

1794L     ERROR_REDIRECTOR_HAS_OPEN_HANDLES

1795L     ERROR_PRINTER_DRIVER_ALREADY_INSTALLED

1796L     ERROR_UNKNOWN_PORT

1797L     ERROR_UNKNOWN_PRINTER_DRIVER

1798L     ERROR_UNKNOWN_PRINTPROCESSOR

1799L     ERROR_INVALID_SEPARATOR_FILE

1800L     ERROR_INVALID_PRIORITY

1801L     ERROR_INVALID_PRINTER_NAME

1802L     ERROR_PRINTER_ALREADY_EXISTS

1803L     ERROR_INVALID_PRINTER_COMMAND

1804L     ERROR_INVALID_DATATYPE

1805L     ERROR_INVALID_ENVIRONMENT

1806L     RPC_S_NO_MORE_BINDINGS

1807L     ERROR_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT

1808L     ERROR_NOLOGON_WORKSTATION_TRUST_ACCOUNT

1809L     ERROR_NOLOGON_SERVER_TRUST_ACCOUNT

1810L     ERROR_DOMAIN_TRUST_INCONSISTENT

1811L     ERROR_SERVER_HAS_OPEN_HANDLES

1812L     ERROR_RESOURCE_DATA_NOT_FOUND

1813L     ERROR_RESOURCE_TYPE_NOT_FOUND

1814L     ERROR_RESOURCE_NAME_NOT_FOUND

1815L     ERROR_RESOURCE_LANG_NOT_FOUND

1816L     ERROR_NOT_ENOUGH_QUOTA

1898L     RPC_S_GROUP_MEMBER_NOT_FOUND

1899L     EPT_S_CANT_CREATE

1900L     RPC_S_INVALID_OBJECT

2138L     ERROR_NO_NETWORK

2202L     ERROR_BAD_USERNAME

2250L     ERROR_NOT_CONNECTED

2401L     ERROR_OPEN_FILES

2404L     ERROR_DEVICE_IN_USE

6118L     ERROR_NO_BROWSER_SERVERS_FOUND


 Win32 Glossary


  A

ABC width

The amount of spacing required for a single glyph in a font. "A" spacing is added to the current position before drawing the glyph. "B" spacing is the width of the black part of the glyph. "C" spacing is added to the current position to account for the white space to the right of the glyph. The total advanced width is given by A+B+C. See also glyph.

absolute security descriptor

A security descriptor structure that contains pointers to the security information associated with an object. See also security descriptor, self-relative security descriptor.

accelerator table

An array of ACCEL data structures, each of which defines a keyboard accelerator. See also keyboard accelerator.

access-control entry (ACE)

An entry in an access-control list (ACL). An access-control entry contains a security identifier and may also contain a set of access rights. Access-control entries are used to grant or deny access to a user or group and to audit the access attempts of a user or group. See also access-control list (ACL), security identifier (SID).

access-control list (ACL)

A list of security protections that applies to an object. (An object can be a file, process, event, or anything else having a security descriptor.) An entry in an access-control list (ACL) is an access-control entry (ACE). There are two types of access-control list: discretionary and system. See also access-control entry (ACE), discretionary access-control list (DACL), security descriptor, system access-control list (SACL).

access mask

A 32-bit value that specifies the rights that are granted or denied in an access-control entry (ACE). An access mask is also used to request access rights when an object is opened. See also access-control entry (ACE).

access time

The last time a file was written to, read from, or run, if the file is executable.

access token

A group of security attributes permanently attached to a process when a user logs on to the operating system. An access token contains privileges and security identifiers for a user, global group, or local group. The privileges regulate the use of some system services and the security identifiers regulate access to objects that are protected by access-control lists (ACLs). There are two kinds of access token: primary and impersonation. See also impersonation token, primary token, privilege, process, security identifier (SID).

ACE

See access-control entry (ACE).

ACL

See access-control list (ACL).

active screen buffer

The screen buffer that is currently displayed in a console's window.

active window

A top-level window of the application with which the user is working. Windows identifies the active window by positioning it at the top of the Z order and highlighting its title bar and border. See also window.

Adaptive Differential Pulse Code Modulation (ADPCM)

An audio-compression technique.

additive color technology

The color technology, used by video displays, that is based on the three primary colors red, green, and blue (RGB). Other colors (except black) are a combination of two or more of the primaries in varying amounts. Black is defined as the absence of the primaries.

ADPCM

See Adaptive Differential Pulse Code Modulation (ADPCM).

alertable wait

(1) A wait operation initiated when a thread calls either the WaitForSingleObjectEx, WaitForMultipleObjectsEx, or SleepEx function with the function's fAlertable flag set to TRUE. In an alertable wait, the wait function returns when a ReadFileEx or WriteFileEx function completion routine is queued for execution.

(2) A wait function operation in which the function can return when the specified conditions are satisfied, or when the system queues a completion routine for execution by the waiting thread. See also completion routine, wait function.

animation

The display of a series of graphic images that simulates motion. Animation can be frame based or cast based.

anonymous pipe

An unnamed, one-way pipe that transfers data between a parent and child process, or between two child processes of the same parent process. An anonymous pipe is created by the CreatePipe function that returns two handles (one to the read end and one to the write end of the pipe). The creating parent process controls whether these handles are inherited by its child processes. See also child process, handle, parent process, pipe.

application-defined control

A control belonging to a window class supplied by an application.

application-defined resource

A resource whose format is defined and recognized by a specific application. See also custom resource.

association

The process of matching a filename extension with a specific application. When an extension and an application have been associated, applications can use the association to find and start other applications or to open and print files.

asynchronous input and output (I/O)

A type of I/O in which some file I/O functions return immediately, even though an I/O request is still pending. This enables an application to continue with other processing and wait for the I/O to finish at a later time. See also overlapped input and output (I/O).

asynchronous task handle

The handle returned by the WSAAsyncGetXByY routines. This handle is used to identify the outstanding operation and allow the application to cancel it if needed.

atom

An integer that identifies a character string in an atom table.

atom name

The character string identified by an atom.

atom table

A table, defined by the operating system, that stores character strings and their associated atoms. A global atom table is available to all applications. A local atom table can be used only by the application that created it.

attribute

A characteristic of a file. The six Windows file attributes indicate whether a file is read only, hidden, system, archived, a directory, or normal. See also directory.

auto-reset event object

See event object.

auxiliary audio device

Audio devices whose output is mixed with the Musical Instrument Digital Interface (MIDI) and waveform output devices in a multimedia computer. An example of an auxiliary audio device is the compact disc audio output from a CD-drive.


  B

background window

Any window created by a thread other than the foreground thread.

base character

A character followed by a nonspacing character; typically, this is a letter that receives an accent mark. For example, in the character è, an accented e, the e is the base character. See also nonspacing character.

base class

The window class an application uses as the starting point when creating a superclass. See also superclass.

base line

An imaginary line where the capital letters for a given font rest. See also font.

base priority

A thread priority value that provides the basis for calculating the thread's dynamic priority. This value is set to one of the five levels within the priority class of the thread's process. The scheduler can temporarily boost the priority of a thread, but it cannot reduce it below this base. See also dynamic priority, priority class, process, thread.

beginning-of-medium marker

The position on a tape where you can begin recording data.

beginning-of-partition marker

The position in a partition where you can begin recording data. If there is only one partition, this position is usually equivalent to the beginning-of-medium marker.

Bezier spline

An irregular curve defined by four points: two endpoints and two control points. The endpoints determine where the curve begins and ends. The control points determine the shape of the curve; however, unlike the endpoints, the control points do not intersect the curve.

bit count

The number of bits of data in a color plane that represent a single pixel. See also pixel.

bitmap

An array of bits that contains data that describes the colors found in a rectangular region on the screen (or the rectangular region found on a page of printer paper). See also rectangular region.

bitmapped image

A rectangular image on a video display (or page of printer paper) represented by the color data in a bitmap.

blink time

The elapsed time, in milliseconds, required to invert the caret display. This value is half of the flash time. See also caret, flash time.

blocking input and output (I/O)

A wait mode for I/O operations on a named pipe where functions wait for a process on the other end of the pipe to perform an action. In nonblocking wait mode, the functions return if their operations are not finished immediately. See also named pipe, pipe, process.

bottom-up DIB

A device-independent bitmap (DIB) whose origin lies at the bottom-left corner. See also top-down DIB.

bounding rectangle

A Windows or graphics device interface (GDI) object. In the case of some GDI objects, the dimensions of this rectangle are inclusive-exclusive when no world transformation has been set, and inclusive-inclusive when a world transformation has been set.

break key

In Media Control Interface (MCI), a keystroke that interrupts a wait operation. By default, MCI defines this key as ^CTRL+BREAK^. An application can redefine this key by using the MCI_BREAK command message.

breakpoint

A location in a process where execution is stopped to allow the developer to examine the process's code, variables, and register values, and, as necessary, make changes, continue execution, or terminate execution.

brush

A bitmap that is used to fill the interior of closed shapes, polygons, ellipses, and paths. See also bitmap, ellipse, path, polygon.

brush origin

A coordinate that specifies the location of one of the pixels in a brush's bitmap. Windows maps this pixel to the upper left corner of the window that contains the object to be painted. See also bitmap, pixel, window.

button

An element in the Windows user interface that enables a user to provide input to an application. Buttons are typically used in dialog boxes.

byte-order mark

A special Unicode character (0xFEFF) that is placed at the beginning of Unicode text files to indicate that the text is in Unicode format.

byte reversed

A Unicode file in which the most significant byte is first (as on Motorola architectures).

byte type pipe

A named pipe where data is written as a stream of bytes. See also named pipe.


  C

caret

A flashing line, block, or bitmap that marks the location of the insertion point in a window's client area. See also bitmap.

CD-ROM extended architecture (CD-XA)

An extension of the CD-ROM standard that provides for storage of compressed audio data along with other data on a CD-ROM disc. This standard also defines the way data is read from a disc. Audio signals are combined with text and graphic data on a single track so they can be read at virtually the same time.

channel

A method, provided by Musical Instrument Digital Interface (MIDI), for sending messages to an individual device within a MIDI setup. There are 16 MIDI channel numbers. Devices in a MIDI setup can be directed to respond only to messages marked with a channel number specific to the device.

channel map

A channel map, provided by the MIDI Mapper, that can redirect Musical Instrument Digital Interface (MIDI) messages from one channel to another. See also MIDI Mapper, Musical Instrument Digital Interface (MIDI).

character code

A numeric value that represents a particular character in a set, such as the ASCII character set. See also code page.

character set

A mapping of characters to their identifying numeric values. See also multibyte character set, single-byte character set, Unicode.

character-mode application

An application that does not provide its own graphical user interface (GUI). The Win32 API provides consoles for managing input and output (I/O) for character-mode applications. See also console.

check box

A square box operated by the user to choose from a set of related but independent options. A checked check box contains an X. Repeatedly checking a check box toggles it from state to state. A standard check box has two states: checked and unchecked. A three-state check box has an additional state: disabled (grayed). In versions of standard and three-state check boxes, Windows is responsible for changing the state of the check box.

child process

A process (child) initiated by another process (the parent). The child process can operate independently from the parent process. Further, the parent process can suspend or terminate without affecting the child process. See also parent process.

child window

A window that has the WS_CHILD style. A child window always appears within the client area of its parent window.

child-window identifier

An application-defined value assigned to a child window. An application that creates multiple child windows of the same class uses the identifiers to distinguish among the child windows.

chord

A region bounded by the intersection of an ellipse and a secant. In Windows, a chord is outlined by using the current pen and filled by using the current brush. See also ellipse, secant.

chunk

The basic building block of a Resource Interchange File Format (RIFF) file, consisting of an identifier (called a chunk identifier), a chunk-size variable, and a chunk data area of variable size.

class cursor

The default cursor for a window class. The class cursor is specified by the hCursor member of a WNDCLASS structure. See also cursor.

class icon

The default icon for a window class. The class icon is identified by the hIcon member of a WNDCLASS structure. See also icon.

class menu

The default menu for a window class. All windows of a given class use the same menu unless the application specifies a different menu when creating a window of that class. See also menu, window.

click

To press and release a mouse button.

client area

The part of a window where the application displays output such as text or graphics.

client coordinates

Coordinates relative to the upper left corner of a window's client area.

clip path

One or more irregular shapes in a window's client area where clipped output appears. The edges of a clip path can be straight lines, Bezier curves, or combinations of the two. See also irregular shape.

clipboard

A set of functions and messages used to transfer information between applications or within an application.

clipboard format

The format of data on the clipboard. A window can copy information to the clipboard using multiple clipboard formats. A clipboard format is identified by a unique unsigned integer value. See also clipboard, window.

clipboard owner

The window associated with the information on the clipboard. It is possible for there to be no clipboard owner. See also clipboard, window.

clipboard viewer

A window that displays the contents of the clipboard. See also clipboard, window.

clipping

The process of limiting output to part of the client area in a window. See also window.

clipping region

A polygon or ellipse in a window's client area where clipped output appears. See also ellipse, polygon.

CMY format

See cyan, magenta, yellow (CMY) format.

code page

A mapping of characters to 256 8-bit character codes. See also character code.

coherent

A description of file views that contain identical data at a given time. File views are coherent if they are derived from the same file-mapping object.

Color common dialog box

A common dialog box that displays available colors and controls that let the user define a custom color. See also common dialog box.

color palette

An array containing the RGB (red, green, blue) values identifying the colors that can currently be displayed or drawn on the output device. Color palettes are used by devices that are capable of generating many colors but can only display or draw a subset of these at any given time.

color plane

An array of bits that represents the red, green, blue, or intensity components for the pixels in a bitmapped image. See also bitmapped image, pixel.

command item

A menu item that, when chosen, sends a command message to the window procedure of the window that owns the menu. See also menu item, window.

command message

In Media Control Interface (MCI), a symbolic constant that represents a unique command for an MCI device. Command messages have associated data structures that provide information a device requires to carry out a request.

command string

In Media Control Interface (MCI), a null-terminated character string that represents a command for an MCI device. The text string contains all the information that an MCI device needs to carry out a request. MCI parses the text string and translates it into an equivalent command message and data structure that it then sends to an MCI device driver.

comment

A string of text inserted between records in a metafile. See also metafile.

committed page

A page of memory in a process's virtual address space for which physical storage has been allocated. The storage is either in RAM or on disk.

common dialog box

A dialog box that an application displays by calling a single function rather than by creating a dialog box procedure and a resource file containing the dialog box template. See also resource file.

common display context

The default display context assigned to a window that does not specify CS_OWNDC or CS_CLASSDC as the window's class style. See also display context, window.

communications resource

A physical or logical device that provides a single bidirectional, asynchronous data stream. Serial ports, parallel ports, fax machines, and modems are examples of communications resources. For each communications resource, there is a service provider, consisting of a library or driver, that enables applications to access the resource.

compact disc − digital audio (CD-DA)

An optical data-storage format that provides for the storage of up to 73 minutes of high-quality digital-audio data on a compact disc. Also known as Red Book audio.

compact disc − read-only memory (CD-ROM)

An optical data-storage technology that allows large quantities of data to be stored on a compact disc.

compatible device context (DC)

A virtual-device context that provides a means of storing an image that was created on a physical screen. (Compatible DCs are sometimes referred to as "memory" DCs.) See also device context.

completion routine

A function specified in a call to either the ReadFileEx or WriteFileEx function. A completion routine is queued for execution when the read or write operation is finished. The completion routine is not executed until the thread that called the ReadFileEx and WriteFileEx function enters an alertable wait. See also alertable wait.

composite character

An accented character represented by two character values, one for the base character and another for the nonspacing accent character. See also base character, nonspacing character, precomposed character.

compound device

A Media Control Interface (MCI) device that requires a device element, usually a data file. An example of a compound device is the MCI waveform audio driver. See also device element.

compound file

A number of individual files bound together in one physical file. Each individual file in a compound file can be accessed as if it were a single physical file.

console

An interface that provides input and output to character-mode applications. See also character-mode application.

console modes

Settings associated with a console that determine the behavior of some of its input and output operations.

console process

A character-mode process whose entry point is the main function. A console process uses the console functions or the file input and output (I/O) functions for I/O, while a graphical user interface (GUI) process uses the USER/graphic device interface (GDI) functions. See also process.

console window

A window managed by the system that a console uses to receive input and display output.

container

A network resource that contains other network resources. The contained resources can be such objects as servers or printers, or containers that can also contain further objects and containers. See also sharepoint.

context record

A record of the machine state created when an exception occurs. The context record is saved in a CONTEXT structure.

control

A child window used in conjunction with another window to carry out simple input and output (I/O) tasks.

control change

See MIDI control-change message.

control identifier

A number that an application uses to uniquely identify a control.

control message

A message sent to a control to request information or perform an action.

control set

A set of configurable options for a computer. See also profile.

control style

A value, similar to a window style, that specifies the appearance and behavior of a control. The window procedure for the control uses the style to determine how to draw the control and process input.

coordinate space

A planar space based on the Cartesian coordinate system. This system requires two axes that are perpendicular and equal in length. There are four coordinate spaces in Windows: world, page, device, and physical device (client area, or desktop, or page of printer paper).

Coordinated Universal Time

The standard international time used internally by Windows NT.

cosmetic pen

A pen with dimensions specified in device units. See also pen.

counter

A general term referring to an incrementing variable.

critical section

An object used to synchronize the threads of a single process. Only one thread at a time can own a critical-section object.

current directory

The directory at the end of the active path. This is the directory where the active application started, unless explicitly changed. See also directory.

current position

The starting point for any line-drawing or curve-drawing operations.

current selection

The portion of a document the user has marked in preparation for carrying out a command.

cursor

A small bitmap whose location on the screen is controlled by a pointing device, such as a mouse, pen, or trackball. See also bitmap.

cursor handle

A unique value of the HCURSOR type that identifies a cursor.

custom cursor

A cursor designed for use in a specific application.

custom icon

An icon designed for use in a specific application. See also icon.

custom resource

See application-defined resource.

cyan, magenta, yellow (CMY) format

A color format that identifies a given color with a cyan, magenta, yellow (CMY) format triplet. This format is used by printers and other ink-based devices.


  D

DACL

See discretionary access-control list.

DBCS

See double-byte character set.

DC

See device context.

DDE

See dynamic data exchange.

DDE client application

An application that requests a conversation with a dynamic data exchange (DDE) server application, and receives data from the server during the conversation. See also DDE server application.

DDE conversation

The interaction between a dynamic data exchange (DDE) client and a DDE server application.

DDE server application

An application that provides data to a dynamic data exchange (DDE) client application during a DDE conversation. See also DDE client application, DDE conversation.

DDE transaction

An exchange of messages or data between a dynamic data exchange (DDE) client application and a DDE server application. See also DDE client application.

dead key

A key used with another key to create an accented character. A dead key, when pressed, produces no visible character but indicates that the accent mark it represents is to be combined with the character produced by the next letter key pressed. See also key.

deadlock

A bug where the execution of thread A is blocked indefinitely waiting for thread B to perform some action, while thread B is blocked waiting for thread A. For example, two threads on opposite ends of a named pipe can become deadlocked if each thread waits to read data written by the other thread. A single thread can also deadlock itself. See also named pipe, thread.

debugger

An application that enables a developer to observe and correct programming errors by stepping through an application program, examining data, and checking conditions.

debugging

The process of observing and correcting logical and syntactical errors in an application.

debugging event

An event that occurs in a process being debugged that causes the kernel to notify the debugger. Also, the notification the kernel sends to the debugger. See also debugger, process.

default color palette

An array of RGB values identifying the colors that can be used with a device context by default. Windows associates the default color palette with a context whenever an application creates a context for a device that supports color palettes. The default color palette ensures that colors are available for use by an application without requiring additional action by the application.

default window procedure

A system-defined function that provides default processing for messages an application-defined window procedure does not process. See also window procedure.

desktop wallpaper

The pattern created by the bitmap that the desktop window uses to paint the background of the screen.

desktop window

A system-defined window that paints the background of the screen and serves as the base for all windows displayed by all Windows applications.

detached process

A console process that does not have access to the console of its parent process. Typically, a detached process runs in the background, but it can use the AllocConsole function to create a new console if it needs to print a message to the screen or get input from the user. See also console process, parent process.

device capabilities

The curve-, line-, polygon-, raster-, and text-drawing capabilities of a display or printer.

device context

A data structure defining the graphic objects, their associated attributes, and the graphic modes affecting output on a device. See also graphic modes, graphic objects.

device coordinate space

One of four coordinate spaces used for all graphic device interface (GDI) drawing operations.

device-dependent bitmap

An array of bits that can only be used with a particular display or printer.

device element

Data required for operation of Media Control Interface (MCI) compound devices. The device element is generally an input or output data file.

device-independent bitmap (DIB)

An array of bits combined with several structures that specify the width and height of the bitmapped image (in pixels), the color format of the device where the image was created, and the resolution of the device used to create that image. See also bitmapped image, pixel.

device type

A class of Media Control Interface (MCI) devices that respond to a common set of commands.

DIB palette

The logical color palette created when a device-independent bitmap (DIB) was created. See also color palette.

DIB pattern-brush

A logical brush created from a device-independent bitmap (DIB). See also device-independent bitmap (DIB), logical brush.

digital differential analyzer (DDA)

An algorithm that determines which pixels on a video display (or dots on a printed page) are part of a line or curve. See also pixel.

directory

An organizational construct supported by most disk-based operating systems. Rather than listing all the files on a volume at once, users can create multiple directories to contain groups of files. Directories can also contain other directories.

disabled window

A window that cannot receive input from keyboard, mouse, or other input device.

discretionary access-control list (DACL)

An access-control list that is controlled by the owner of an object and that specifies the access particular users or groups can have to the object. See also access-control list (ACL), system access-control list.

disk drive

A physical device that reads from or writes to disks. Disk drives are referenced by letters, typically A for the first floppy-disk drive, B for the second floppy-disk, C for the first fixed-disk drive, D for the second fixed-disk drive, and so on. Each drive on an operating system is assigned a unique letter to distinguish it from other drives.

display context

A special device context that treats each window like a separate screen surface. See also device context, window.

display driver

A Windows dynamic-link library (DLL) that contains functions that process input from the graphics engine and convert that input into device-specific commands. These commands are processed by the display adapter. See also dynamic-link library (DLL).

display element

The parts of a window and the Windows display that appear on the system display screen.

division type

The technique used to represent the time between Musical Instruments Digital Interface (MIDI) events in a MIDI sequencer.

DLL

See dynamic-link library (DLL).

domain

A group of workstations and servers that share a single group name.

double-byte character set (DBCS)

A mapping of characters to their identifying numeric values, in which each value is 2 bytes wide. Double-byte character sets are sometimes used for languages that have more than 256 characters. For example, a double-byte character set is used to encode Japanese (Kanji) characters. See also multibyte character set.

double-click

To press and release a mouse button twice in quick succession.

drag

To move the mouse while holding down a mouse button.

drag-drop

To select one or more files in File Manager, drag them to an open application, and drop them there.

driver service

A service that follows the device driver protocols for Windows NT rather than using the Service Control Manager interface.

drop-down combo box

A combo box, created by using the CBS_DROPDOWN style, containing a drop-down list and a selection field that can be edited by the user.

drop-down list

A list in a combo box that is visible only when it is opened by the user. Combo boxes with the CBS_DROPDOWN and CBS_DROPDOWNLIST styles contain drop-down lists.

drop-down list box

A combo box, created by using the CBS_DROPDOWNLIST style, containing a drop-down list and a selection field that cannot be edited by the user. A drop-down list box can be used in place of a list box when screen space is tight.

dynamic data exchange (DDE)

A form of interprocess communications that uses shared memory to exchange data between applications. Applications can use DDE for one-time data transfers and for ongoing exchanges in applications that send updates to one another as new data becomes available.

dynamic-link library (DLL)

A .DLL file that contains one or more functions compiled, linked, and stored separately from the processes that use them. The operating system maps the DLLs into the process's address space when the process is starting up or while it is running. The process then executes functions in the DLL. See also process.

dynamic priority

A thread priority value used by the scheduler in making scheduling decisions. The value for each thread can never be lower than the thread's base priority, but it can be raised and then lowered to enhance responsiveness to input or other significant events. See also base priority, thread.


  E

early-warning position

A physical mark or device-computed position immediately before the end-of-partition marker.

edit control

An element of the Windows user interface that allows the user to enter and edit text. Edit controls are typically used in dialog boxes.

ellipse

A closed curve defined by two fixed points such that the sum of the distances from any point on the curve to the two fixed points is constant.

elliptical region

A region with the shape of an ellipse. See also ellipse, region.

embedded font

A TrueType font stored as part of a document. (By storing a font in a document, the document's author is guaranteed that the original appearance and format of the document remain intact.) See also TrueType font.

end cap

A geometric pen attribute that specifies the shape of the pen. There are three types of end caps: flat, round, and square.

end-of-medium marker

The last position on a tape where you can record data.

end-of-partition marker

The last position on a partition where you can record data.

end-of-tape marker

Same as end-of-medium marker.

enhanced metafile

One of two metafile formats. This format, used in applications written to run with the Win32 application programming interface (API), consists of a header, a table of handles to graphics device interface (GDI) objects, a private palette, and an array of metafile records. See also handle.

environment variable

A symbolic variable that represents some element of the operating system, such as a path, a filename, or other literal data. For example, the environment variable PATH represents the directories to search for executable files. See also directory, path.

erase gap

An area of erased tape or a pattern that the device does not recognize as a marker or as user data; it is used to locate a filemark to be overwritten.

escapement

An angle defined by the escapement vector and the x-axis of a device. The base line of a string of text is parallel to the escapement vector. See also x-axis.

event object

An interprocess synchronization object whose state is explicitly set to signaled by the SetEvent or PulseEvent function. A manual-reset event object's state must be explicitly reset to the nonsignaled state by the ResetEvent function. A wait function resets an auto-reset event object's state to nonsignaled before returning. See also synchronization object, wait function.

exception

An event that occurs during the execution of a program and that requires the execution of software outside the normal flow of control.

exception record

A record of an exception. The exception record is saved in an EXCEPTION_RECORD structure.


  F

family name

One of two attributes used to organize TrueType fonts. Family names include Courier New, Arial, and Times New Roman. (The other attribute used to organize TrueType fonts is the style name.) See also TrueType font.

FAT

See file allocation table (FAT).

file

A named, ordered collection of information, such as a program, a set of data used by a program, or a user-created document. A file is the basic unit of storage that enables a computer to distinguish one set of information from another.

file allocation table (FAT)

A table that contains the status of various segments of disk space used for file storage. Also, the file system that maintains the table.

file element

A complete file contained in a Resource Interchange File Format (RIFF) compound file.

file handle

A unique identifier that Windows assigns to a file when the file is opened or created. A file handle is valid until the file is closed.

file-mapping object

An object whose handle can be used to create a view to a file or piece of memory. The CreateFileMapping function creates file-mapping objects. See also handle.

file pointer

A pointer to the next byte to be read or written in a file.

file system

A part of the operating system that enables you to store, access, and organize files on storage devices, such as hard or floppy disks or tape drives. File allocation table (FAT), high-performance file system (HPFS), and New Technology file system (NTFS) are examples of file systems.

file time

A 64-bit value representing the number of 100-nanosecond intervals that have elapsed since January 1, 1601.

file view

A copy of a file or piece of memory that appears in a process's virtual address space. The MapViewOfFile function creates a file view in the process's address space and returns a pointer to the file view.

filemark

A special recorded element that contains no user data and is used to provide a segmentation scheme. A normal filemark does not contain an erase gap.

filled path

A path that is filled by using the brush currently selected into an application's device context. See also device context, path.

filter expression

An expression that is part of a frame-based exception handler. When an exception occurs during the execution of the guarded body of code in a frame-based exception handler, the system evaluates the filter expression to determine whether the exception handler code is to be executed. See also frame-based exception handler, guarded body of code.

filter function

A function called by a filter expression in a frame-based exception handler. See also frame-based exception handler.

Find common dialog box

A common dialog box that displays an edit control in which the user can type a string that the application should search. See also common dialog box.

first-chance notification

The first time the kernel notifies the debugger of an exception. See also debugger.

flash time

The elapsed time, in milliseconds, required to display, invert, and restore the caret display. This value is twice as much as the blink time. See also blink time, caret.

flattened path

A path altered by converting each curve (in the path) into a series of line segments. See also path.

floating pop-up menu

A pop-up menu that is not attached to a menu bar. See also pop-up menu.

FM synthesizer

See frequency modulation (FM) synthesizer.

font

(1) A collection of characters and symbols that share a common design.

(2) A drawing object used to write text on a display surface.

Font common dialog box

A common dialog box that displays lists of fonts and point sizes that correspond to available fonts. See also common dialog box.

font mapper

An algorithm that Windows uses to determine which available font most closely matches a requested font. See also font.

font table

An array that identifies each of the fonts whose resources have been loaded. Only fonts whose resources have been loaded can be used for text output. See also font.

foreground window

The window with which the user is currently working. The system assigns a slightly higher priority to the thread that created the foreground window than it does to other threads.

form type

A four-character code (FOURCC) identifying the type of data contained in a Resource Interchange File Format (RIFF) chunk. For example, a RIFF chunk with a form type of WAVE contains waveform audio data.

FOURCC (Four-Character Code)

A code used to identify Resource Interchange File Format (RIFF) chunks. A FOURCC is a 32-bit quantity represented as a sequence of one to four ASCII alphanumeric characters, padded on the right with blank characters.

frame-based exception handler

A mechanism used by a developer to deal with the possibility that an exception may occur in a certain sequence of code. A frame-based exception handler consists of a guarded body of code, a filter expression, and an exception handler. See also filter expression, guarded body of code.

free page

A page of memory in a process's virtual address space that is available to be reserved or committed. A process cannot access a free page. See also committed page, reserved page.

frequency

With respect to the high-resolution performance counter, the number of counts per second. This value is processor dependent.

frequency modulation (FM) synthesizer

A synthesizer that creates sounds by combining the output of digital oscillators using a frequency modulation technique.


  G

General MIDI

A synthesizer specification created by the MIDI Manufacturers Association (MMA) defining a common configuration and set of capabilities for consumer Musical Instrument Digital Interface (MIDI) synthesizers.

geometric pen

A pen with dimensions that are specified in world units. A geometric pen may possess attributes usually associated with a brush, such as pattern and hatch. See also brush, geometric pen, pen.

global atom

An atom stored in the global atom table. The value of a global atom is unique among all others in the operating system. See also atom.

global atom table

See atom table.

global subclassing

A type of subclassing in which an application replaces the window-procedure address stored in the WNDCLASS structure of a window class with the address of a subclass procedure. All subsequent windows created with the class use the subclass procedure rather than the original window procedure. See also subclassing, window, window procedure.

glyph

The bitmap, collection of points, or collection of graphic commands that define a single character or symbol in a font. See also bitmap, font.

graceful disconnect

In a graceful disconnect, all the data sent by both sides are delivered and there is full acknowledgment of the session termination by both sides. This contrasts with an abortive disconnect, in which one side unilaterally terminates the connection, disregarding any queued data. As a result, in an abortive disconnect there may be data loss.

graphic modes

A set of modes that define how the Win32 API draws output with the objects found in a device context. See also device context.

graphic objects

The pen, brush, bitmap, palette, region, and path associated with a device context. See also bitmap, brush, device context, palette, path, region.

graphical user interface (GUI) process

A process whose entry point is the WinMain function. A GUI process uses the USER/graphics device interface (GDI) functions for input and output (I/O), while a console process uses the console functions or the file I/O functions. See also console process.

graphics device interface

A dynamic-link library that processes graphics function calls from a Windows-based application and passes those calls to the appropriate device driver. See also dynamic-link library (DLL).

group box

A rectangle used to group related controls (usually check boxes or radio buttons). Because its sole purpose is to organize other controls, a group box cannot be selected. See also check box, radio button.

guarded body of code

A set of one or more statements for which an exception or termination handler provides protection.

GUI process

See graphical user interface (GUI) process.


  H

handle

A variable that identifies an object; an indirect reference to an operating system resource.

hatched brush

A logical brush created from one of twenty predefined bitmaps. See also bitmap, logical brush.

hidden window

A window that does not have the WS_VISIBLE style. A hidden window does not appear on the screen. As a result, it cannot receive user input or display output, although it can receive input from Windows and other applications.

high-performance file system (HPFS)

A file system that supports extended attributes and long, mixed-case filenames, and improves operating system performance by implementing several levels of caching. Windows NT cannot manipulate the extended attributes of a file created on HPFS.

high-resolution performance counter

Hardware that provides high-resolution timing useful in improving the performance of applications.

hit testing

(1) The process of detecting user input by using the position of the mouse cursor hot spot. See also hot spot.

(2) A procedure for determining the current cursor position related to a given region. See also region.

hive

A discrete body of registry information, typically rooted at the top of the registry hierarchy. Each hive is usually supported by a single file of registry data.

HLS format

A color format that identifies a given color with a HLS (hue, luminosity, and saturation) triplet.

HMS time format

A time format used by Media Control Interface (MCI) to express time in hours, minutes, and seconds. The HMS time format is used primarily by videodisc devices.

hollow brush

See null brush.

hook

A point in the Windows message-handling mechanism where an application can install a subroutine to monitor messages.

hook chain

A list of pointers to the hook procedures associated with a hook. When a message occurs that is monitored by the hook, Windows calls the first hook procedure in the chain.

hook procedure

An application-defined callback function whose address has been installed in a hook chain.

hot key

A key combination that generates a WM_HOTKEY message.

hot spot

The pixel in a cursor that marks the exact screen location affected by a mouse action, such as a button click. Mouse messages include the coordinates of the hot spot. See also cursor, pixel.

HPFS

See high-performance file system (HPFS).


  I

icon

A small bitmap that usually represents a minimized application. Icons may also serve as symbols in warning messages or other windows. See also bitmap.

icon handle

A unique value of the HICON type that identifies an icon. See also icon.

iconic

Minimized. If an icon represents a minimized application, the application's window is said to be iconic. See also icon, window.

ideographic

A single character that represents a word, object or a phrase — for example, a single character that means "month." This term would apply to the Han script.

IMA

See Interactive Multimedia Association (IMA) and International MIDI Association (IMA).

image

A rectangular region on a video display that contains a graphical representation of an object. See also rectangular region.

impersonation token

An access token that has been created to capture the security information of a client process, allowing a server to "impersonate" the client process in security operations. See also access token, primary token.

import library

A .LIB file that contains information about one or more dynamic-link libraries (DLLs), but does not contain the DLL's executable code. The linker uses an import library when building an executable module of a process, to provide the information needed to resolve the external references to DLL functions. See also dynamic-link library, process.

information context

A device context used strictly for data retrieval; it cannot be used for any drawing operations. See also device context.

input buffer

A buffer containing a queue of input records with information about keyboard, mouse, and window-sizing events for a console. See also console.

input event

An event--such as a keystroke, mouse movement, or mouse-button click--that causes a console to place an INPUT_RECORD structure in its input buffer. A console process can get information about an input event by reading from the console's input buffer.

instance

An instantiation of a particular object type in a class, such as a specific process or thread. All instances of a given type have identical performance counters.

instance subclassing

A type of subclassing where an application replaces the window-procedure address of a single instance of a window with the address of a subclass procedure. See also subclassing, window.

integer atom

An atom that identifies an integer value. See also atom.

Interactive Multimedia Association (IMA)

A professional trade association of companies, institutions, and individuals involved in producing and using interactive multimedia technology.

International MIDI Association (IMA)

The nonprofit organization that circulates information about the Musical Instrument Digital Interface (MIDI) specification.

irregular curve

A curve that does not fit the perimeter of a conic section.

irregular shape

A shape composed of curves and straight line segments.

item name

A string that identifies a unit of data a server can pass to a client during a transaction.


  J

join style

A geometric pen attribute that specifies how the ends of connected lines are joined. See also geometric pen.


  K

key

An entry (or node) in the registry. A key may have one or more values, subkeys, or both. With the exception of four predefined keys, all keys are subkeys of other keys. See also registry, subkey.

keyboard accelerator

A keystroke or combination of keystrokes that sends a command message to the specified application window.

keyboard focus

A property of the window currently receiving keyboard input. Only one window at a time can have the keyboard focus. See also window.


  L

language identifier

A 16-bit value that identifies a language and, where appropriate, the variant of the language being used. A language identifier is a combination of a primary language identifier and a sublanguage identifier. For example, if the primary language identifier specifies English, the sublanguage identifier might specify Australian English.

last-chance notification

The last time the kernel notifies the debugger of an exception. If the debugger does not handle an exception after last-chance notification, the kernel terminates the process being debugged. See also debugger, process.

last-error code

A per-thread value set by Win32 functions when an error occurs. The last-error code can be retrieved by using the GetLastError function.

LCID

See locale identifier.

line

A set of highlighted pixels on a video display (or a series of dots on a printed page) that is defined by two points: a starting point and an ending point. See also pixel.

line and curve attributes

The width, color, style, and (in the case of lines or curves drawn with a geometric pen) end cap, join style, and transformation of a line or curve. See also end cap, geometric pen, join style, transformation.

list box

A control window that contains a list of items that can be selected by the user.

LIST chunk

A Resource Interchange File Format (RIFF) chunk with a chunk identifier of LIST. LIST chunks contain a series of subchunks.

list type

A four-character code (FOURCC) identifying the type of data contained in a Resource Interchange File Format (RIFF) chunk with a chunk identifier of LIST. For example, a LIST chunk with a list type of INFO contains a list of information about a file, such as the creation date and author.

load-time linking

Dynamic linking that occurs when a program (either an application or another dynamic-link library [DLL]) makes an explicit call to a DLL function. This requires that the executable module of the program be built by linking with the DLL's import library. When the program is executed, the operating system uses the information provided by the import library to locate the executable module of the DLL, which is mapped into the address space of the process. See also import library, process.

local atom

An atom stored in an application's atom table. The value of a local atom is unique within the application but may not be unique throughout the operating system. See also atom, atom table.

local atom table

See atom table.

locale identifier (LCID)

A DWORD value containing the language identifer in the lower word and a reserved value in the upper word. The identifier supplied in an LCID is a standard international numeric abbreviation. This LCID has the components necessary to uniquely identify one of the installed system-defined locales.

locally unique identifier (LUID)

A 64-bit value guaranteed to be unique on the operating system that generated it (until the system is restarted).

logfile

A configuration registry key that specifies the filename of an event log. Logfiles are subkeys of the EventLog registration key. See also key, subkey.

logging off

The action of stopping all processes running in the security context of the process that called the Exit function.

logical brush

A description of a bitmap. A logical brush can be selected into a device context. See also bitmap, device context.

logical coordinate space

Another name for the world or page coordinate space. If an application has set a world-space to page-space transformation, the logical space is the world space; otherwise, the logical space is the page space.

logical palette

An array of colors, or "color palette," that an application creates and associates with a device context and uses for graphics output. See also device context.

logical volume

See partition.

long filemark

A filemark that contains a long erase gap that enables an application to position the tape at the beginning of the filemark and to overwrite the filemark and the erase gap. See also erase gap.

LUID

See locally unique identifier.


  M

mailslot

A pseudofile used for one-way interprocess communications.

mailslot client

A process that writes a message to a mailslot.

mailslot server

A process that creates and owns a mailslot and can read messages from it. See also process.

main window

The window that serves as the primary interface between the user and an application.

manual-reset event object

See event object.

mapping

A representation of the elements (or points) from a source coordinate space on a target coordinate space.

mapping mode

An algorithm that specifies the size of the units used for any drawing operations associated with a particular device context.

matrix

An n-dimensional array that is used to specify a transformation. Transformations in a two-dimensional space require either a two-dimensional or a three-dimensional array.

maximize box

A window component that, when clicked, causes Windows to enlarge the window to the size of the screen.

maximized window

A window that has the WS_MAXIMIZE style. A maximized top level window fills the screen; a maximized child window fills the client area of its parent window.

maximum tracking size

The largest window size the user can produce by dragging the sizing border.

MCI

See Media Control Interface.

MDI client window

See multiple document interface client window.

MDI frame window

See multiple document interface frame window.

Media Control Interface (MCI)

High-level control software that provides a device-independent interface to multimedia devices and media files. MCI includes a command-message interface and a command-string interface.

memory device context (DC)

See compatible device context (DC).

menu

A list of items that represent an application's commands. A menu item can be either a string or a bitmap. See also bitmap, menu item.

menu bar

The topmost menu in a hierarchy of menus. A menu bar typically contains one or more menu items that the user can select to display pop-up menus. See also menu, menu item, pop-up menu.

menu handle

A unique value of the type HMENU used to identify a menu. See also menu.

menu item

A string or bitmap displayed in a menu. Choosing a menu item either sends a command message or activates a pop-up menu. See also bitmap, pop-up menu.

message

A data packet used for communicating information or a request. Messages can be passed between the operating system and an application, different applications, threads within an application, and windows within an application. See also thread, window.

message loop

A program loop that retrieves messages from a thread's message queue and dispatches them to the appropriate window procedures. See also message queue.

message parameters

A pair of 32-bit values that contains information a window procedure uses while processing a message.

message queue

An operating system-defined memory object that holds an ordered list of messages awaiting processing. The system message queue holds mouse and keyboard input waiting to be passed to a thread's message queue. A thread's message queue holds messages waiting to be retrieved by a thread's message loop. See also message loop.

message-type pipe

A named pipe where data is written as a stream of messages. See also named pipe.

metafile

A collection of structures that stores a picture in a device-independent format. (There are two metafile formats: the enhanced format and the Windows format.)

metafile bits

The binary representation of a metafile. The bits include the header, an optional palette, an optional text description of the metafile contents, and the metafile records. See also metafile record, palette.

metafile device context (DC)

A device context that is used for metafile operations. See also device context.

metafile handle table

An array of handles that identify pens, brushes, fonts, and other objects used to create the picture stored in the metafile. See also brush, font, handle, metafile, pen.

metafile header

A structure that specifies the size of the picture stored in the metafile, the size of the metafile (in bytes), the number of entries in the metafile palette, the number of records in the metafile, a pointer to the metafile description (if one exists), and a pointer to the metafile palette (if one exists). See also metafile, metafile palette, palette.

metafile palette

An array of red, green, blue (RGB) values that represent the colors used to create the picture stored in a metafile. See also metafile.

metafile record

A variable-length structure. In most cases, this structure represents a call made to a graphics device interface (GDI) function to create part of the picture stored in the metafile. See also metafile.

MIDI

See Musical Instrument Digital Interface.

MIDI control-change message

A Musical Instrument Digital Interface (MIDI) message sent to a synthesizer to change different synthesizer control settings. An example of a control-change message is the volume controller message, which changes the volume of a specific MIDI channel.

MIDI Manufacturers Association (MMA)

A collective organization composed of Musical Instrument Digital Interface (MIDI) instrument manufacturers and MIDI software companies. The MMA works with the MIDI Standard Committee to maintain the MIDI specification.

MIDI Mapper

Windows systems software that modifies Musical Instrument Digital Interface (MIDI) output messages and redirects them to a MIDI output device using values stored in a MIDI setup map. The MIDI Mapper can change the destination channel and output device for a message, as well as modify program-change messages, volume values, and key values.

MIDI mapping

The process of translating and redirecting Musical Instrument Digital Interface (MIDI) messages according to data defined in a MIDI map setup.

MIDI program-change message

A Musical Instrument Digital Interface (MIDI) message sent to a synthesizer to change the patch on a specific MIDI channel.

MIDI sequence

Musical Instrument Digital Interface (MIDI) data that can be played by a MIDI sequencer.

MIDI sequencer

A program that creates or plays songs stored as Musical Instrument Digital Interface (MIDI) files. When a sequencer plays MIDI files, it sends MIDI data from the file to a MIDI synthesizer, which produces the sounds. Windows provides a MIDI sequencer, accessible through media control interface (MCI), that plays MIDI files. See also Media Control Interface (MCI).

MIDI setup map

A complete set of data for the Musical Instrument Digital Interface (MIDI) Mapper to use when redirecting MIDI messages. Only one setup map can be in effect at a given time, but the user can have several setup maps available and can choose between them by using the MIDI Mapper Control Panel option.

minimize box

A window component that, when clicked, causes Windows to reduce the window to the size of an icon.

minimized window

A window that has the WS_MINIMIZE style. A minimized window is the same size as an icon. Windows displays a minimized top-level window at the bottom of the screen; Windows displays a minimized child window at the bottom of its parent window's client area.

minimum tracking size

The smallest window size the user can produce by dragging the window's sizing border.

MMA

See MIDI Manufacturers Association.

module-definition file

A text file (.DEF) that contains one or more statements describing various attributes of an executable module. A dynamic-link library (DLL) must have a .DEF file to specify the DLL's name and a list of its exported functions. See also dynamic-link library (DLL).

mouse capture

The act of channeling mouse input to a specific window without regard to the position of the mouse-cursor hot spot. See also hot spot, window.

MS-DOS date

A date in the format used by MS-DOS. The date is a packed 16-bit value in which bits in the value represent the day, month, and year.

MS-DOS time

A time in the format used by MS-DOS. The time is a packed 16-bit value in which bits in the value represent the hour, minute, and second.

MSF time format

A time format used by Media Control Interface (MCI) to express time in minutes, seconds, and frames. The number of frames in a second depends on the type of device being used; compact disc audio devices use 75 frames per second. The MSF time format is used primarily by compact disc audio devices.

multibyte character set

A character set in which each character is identified by using more than one byte--for example, a double-byte character set (DBCS). Although Unicode characters are 2 bytes wide, the Unicode character set is not referred to by this term. See also double-byte character set (DBCS), single-byte character set, Unicode.

multiple document interface (MDI) client window

A window that belongs to the MDICLIENT window class. An MDI client window serves as the background for MDI child windows, and it provides support for creating and manipulating child windows. See also window.

multiple document interface (MDI) frame window

The main window of a multiple document interface (MDI) application. See also window.

multiple-selection list box

A list box in which more than one item can be selected at the same time.

Musical Instrument Digital Interface (MIDI)

A standard protocol for communication between musical instruments and computers.

mutex object

An interprocess synchronization object whose state is signaled when it is not owned by any thread, and nonsignaled when it is owned. Only one thread at a time can own a mutex. See also nonsignaled, signaled, synchronization object.


  N

named pipe

A one-way or two-way pipe used for communications between a server process and one or more client processes. A server process specifies a name when it creates one or more instances of a named pipe. Each instance of the pipe can be connected to a client process that uses the pipe name to open a handle to the other end of the pipe. See also handle, pipe.

network provider

The supplier of a complete implementation of a networking system: for example, Microsoft Server or Novell Netware.

network root

The topmost container resource in a network hierarchy. The network root can contain the network providers on a system.

New Technology File System (NTFS)

A file system that supports object-oriented applications by treating all files as objects with user-defined and system-defined attributes. NTFS provides all the capabilities of the file allocation table (FAT) and high-performance (HPFS) file systems without many of their limitations.

nonclient area

The parts of a window that are not a part of the client area. A window's nonclient area consists of the border, menu bar, title bar, scroll bar, System menu, Minimize button, and Maximize button. See also menu bar, scroll bar, window.

nonqueued message

A message sent directly to a window procedure.

nonsignaled

The state of an object used for synchronization in one of the wait functions is either signaled or nonsignaled. A nonsignaled state can prevent the wait function from returning. See also signaled, wait function.

nonspacing character

A character that prints over the preceding character--typically, an accent mark. See also base character.

normal filemark

A filemark that does not contain an erase gap. See also erase gap.

notification message

A message a control sends to its parent window when events, such as input from the user, occur.

NTFS

See New Technology File System (NTFS).

null brush

A logical brush created from a bitmap that matches the current window background colors. (A null brush is identical to a hollow brush.) See also bitmap, hollow brush, logical brush.


  O

object

(1) An internal structure that represents a system resource, such as a file, a thread, or a graphic image. See also thread.

(2) A network resource that does not contain any further network resources. It is not necessarily possible to connect to an object.

object type

A measurable entity, such as a processor, disk, or thread.

Open common dialog box

A common dialog box that displays a list of filenames matching any specified extensions, directories, or drives. By selecting one of the listed filenames, the user indicates the file an application should open. See also common dialog box, directory.

overlapped input and output (I/O)

See asynchronous input and output (I/O).

overlapped window

A style of window meant to serve as an application's main window.

owned window

A window that has an owner. Being owned affects the window's position in the Z order and its visibility and can determine when the window is destroyed.

owner window

A window that affects aspects of another window's appearance and behavior.

owner-drawn button

A button with the style BS_OWNERDRAW. Unlike all other button types, an owner-drawn button has no predefined appearance or behavior. Also, the application, not Windows, is responsible for painting it. See also button.

owner-drawn control

A predefined control that sends messages to its parent window when it must be drawn.

owner-drawn item

A menu item whose appearance is controlled by a menu's owner window rather than by Windows. See also menu item, window.


  P

page

A unit of memory that is used by the system in managing memory. The size of a page is computer dependent and can be determined by using the GetSystemInfo function. The system manages memory by assigning pages of memory to specific processes, moving pages to and from a paging file on disk to keep the most recently used pages in physical memory (RAM), and maintaining a page map for each process that keeps track of the current physical location of each committed page in a process's virtual address space. See also committed page, page map.

page coordinate space

The coordinate space in which all graphics device interface (GDI) drawing operations begin if an application has not set the world-space to page-space transformation.

page map

An internal data structure maintained by the system for each process that maps the pages of a process's virtual address space with the corresponding pages of physical storage. See also page.

paging file

A disk file that the system uses to increase the amount of physical storage.

palette

An array of colors currently available on a device.

palette animation

A method of updating the colors in the logical palette.

PANOSE numbers

Special values specified by an application to select a particular font.

parent process

A process (parent) that initiates and controls another process (child) in a multitasking environment. The parent process defines the environment for the child process. The parent process can suspend or complete its own processing while the child process continues its operation. See also child process.

parent window

A window that has one or more child windows.

partition

A logically distinct portion of memory or a storage device that the system references as though it were a physically separate unit. The partition is referenced as a separate volume. For example, a single fixed disk may be divided into two partitions, referred to as C and D, even though they exist on the same physical volume.

parts per quarter note (PPQN)

A time format used for Musical Instrument Digital Interface (MIDI) sequences. PPQN is the most common time format used with standard MIDI files.

patch

A particular setup of a Musical Instrument Digital Interface (MIDI) synthesizer that results in a particular sound, usually a sound simulating a specific musical instrument. Patches are also called programs. A MIDI program-change message changes the patch setting in a synthesizer. Patch also refers to the connection or connections between MIDI devices. See also Musical Instrument Digital Interface (MIDI).

patch caching

A technique that enables some internal Musical Instrument Digital Interface (MIDI) synthesizer device drivers to preload their patch data, reducing the delay between the moment the synthesizer receives a MIDI program-change message and the moment it plays a note using the new patch. Patch caching also ensures that required patches are available (the synthesizer might load only a subset of its patches). See also Musical Instrument Digital Interface (MIDI), patch.

path

(1) A string that describes the location of a file or directory on a volume relative to the current directory or the root directory.

(2) One or more figures that are filled, outlined, or filled and outlined. See also directory, volume.

path bracket

One or more graphics device interface (GDI) functions embedded between a BeginPath and an EndPath function. (The BeginPath function defines the start of the bracket; the EndPath function defines the end.)

pattern brush

A logical brush created from an application-defined bitmap. See also bitmap, logical brush.

pen

A drawing tool used to draw lines and curves.

pen style

One of the cosmetic and geometric pen attributes that define the appearance of lines drawn with the pen. There are eight possible styles: solid, dashed, dotted, dashed and dotted, dash followed by two dots, invisible, inside frame, and user defined. See also cosmetic pen, geometric pen, pen.

pen type

An attribute that determines whether the pen's dimensions are specified in world units or device units.

performance monitoring

The process of determining the system resources an application consumes, such as processor time and memory.

persistent connection

A network connection that Windows restores automatically when the user logs on.

physical brush

A bitmap that Windows uses to paint the interior of filled shapes. A physical brush is a device driver's approximation of a logical brush. See also bitmap, logical brush.

physical device

The fourth and final coordinate space for most graphics device interface (GDI) drawing operations. (The points in this coordinate space may correspond to the desktop, a client area, or a page of printer paper.)

physical palette

See system palette.

picture frame

A rectangle defining the width and height of the picture stored in a metafile. (The dimensions of this rectangle are always specified in .01-mm units.) See also metafile.

pie

A region bounded by the intersection of an ellipse and two radials. In Windows, a pie is outlined by using the current pen and filled by using the current brush. See also ellipse, radial.

pipe

A communication conduit with two ends. A process with a handle to one end can communicate through a pipe with a process having a handle to the other end. Pipes can be one way (where one end is read only and the other end is write only) or two way (where both ends of the pipe can be used for reading or writing). The Win32 application programming interface (API) provides both anonymous (unnamed) pipes and named pipes. See also anonymous pipe, handle, named pipe, process.

pipe instance

A separate conduit for named pipe communications between a client and a server process. A named pipe can have multiple instances, where all instances share the same pipe name but each instance has its own buffers and handles. See also handle, named pipe.

pitch scale factor

In waveform audio, the amount by which a waveform audio driver scales the pitch. A scale factor of two results in a one-octave increase in pitch. Pitch scaling requires specialized hardware. The playback rate and sample rate are not changed.

pixel

The smallest definable unit on a video display. (A pixel's size is a function of video-display technology.)

playback rate scale factor

In waveform audio, the amount by which the waveform audio driver scales the playback rate. Playback scaling is accomplished through software; the sample rate is not changed, but the driver interpolates by skipping or synthesizing samples. For example, if the playback rate is changed by a factor of two, the driver skips every other sample.

playing a metafile

The process of converting the records in a metafile into the respective device commands and drawing the corresponding picture on the device. See also metafile.

Point-to-Point Protocol (PPP)

The Point-to-Point Protocol, or PPP, is an industry-standard suite of control protocols that allow multiple network protocols to be carried on a point-to-point link. Windows NT supports IP, IPX, and NBF connections using PPP. This allows the use of applications that write to a network-specific interface, connections to third-party PPP servers, and remote access to the Internet.

polygon

A closed figure with straight sides. In Windows, a polygon is outlined by using the current pen and filled by using the current brush. See also brush, pen.

polygon fill mode

An algorithm that determines the parts of a region that can be filled, painted, inverted, or clipped. See also region.

polygonal region

A region with the shape of a polygon. See also polygon, region.

polyphony

The maximum number of notes that a Musical Instrument Digital Interface (MIDI) output device can play simultaneously.

pop-up item

A menu item that, when chosen, displays a pop-up menu. See also menu item, pop-up menu.

pop-up menu

A menu that is hidden until the user performs an action that causes Windows to display the menu. See also menu.

pop-up window

A special type of overlapped window typically used for dialog boxes, message boxes, and other temporary windows that appear outside an application's main window.

PPP

See Point-to-Point Protocol.

PPQN

See parts per quarter note.

precomposed character

An accented character represented by a single character value. See also base character, composite character, nonspacing character.

predefined control

A control belonging to a window class supplied by Windows.

preimaging

The process of building a movie frame in a memory buffer before it is displayed.

primary domain

The domain used by the local computer as its usual and default network environment. See also domain.

primary language identifier

An 8-bit value identifying the primary language in a language identifier. See also language identifier, sublanguage identifier.

primary thread

The initial thread of a process. Also called the main thread or thread 1. When the main or WinMain function of a primary thread returns, the ExitProcess function is called implicitly, terminating all other threads of the process. A primary thread does not differ from other threads with respect to signals because all signals are delivered to the thread that caused them. See also process, thread.

primary token

An access token that is typically created only by the Windows NT™ executive layer. It may be assigned to a process to represent the default security information for that process. See also access token, impersonation token.

Print common dialog box

A common dialog box that displays information about the installed printer and its configuration. By altering and selecting controls in this dialog box, the user specifies how output should be printed and starts the printing process. See also common dialog box.

Print-setup common dialog box

A common dialog box that displays the current printer configuration and provides options for setting the paper orientation, size, and source. See also common dialog box.

priority class

A process priority category (high, normal, or idle) used to determine the scheduling priorities of a process's threads. Each priority class has five levels. See also thread.

private memory

Pages of a process's memory that cannot be accessed by other processes. All memory objects allocated by the GlobalAlloc, LocalAlloc, VirtualAlloc, and HeapAlloc functions are in private pages.

privilege

A locally unique identifier used to regulate the use of some system services. See also locally unique identifier (LUID).

process

An executing application that consists of a private virtual address space, code, data, and other operating system resources, such as files, pipes, and synchronization objects that are visible to the process. A process also contains one or more threads that run in the context of the process. See also pipe, process, thread.

profile

A set of configurable options for a user. See also control set.

push button

A rounded rectangle used by the user to start or cancel an operation by clicking the rectangle, which "pushes" the button. A default push button is "pushed" when the user presses the ENTER key. See also button.


  Q

queued message

A message in a message queue. See also message queue.


  R

race condition

A bug in a multithreaded process where the code of thread A relies on thread B to complete some action, but where there is no synchronization between the two threads. The process works if thread B wins the race by completing its action before thread A needs it, but the process fails if thread A wins the race. See also process, thread.

radial

A line drawn from the center of an ellipse to a point on the ellipse. See also ellipse.

radio button

A round button operated by the user to choose from a set of related but mutually exclusive options. The check mark for a radio button is a black dot. A radio button can assume two states: checked (dot) or unchecked (no dot). In automatic radio buttons, Windows is responsible for changing the state of the radio button.

raster device

A device that creates text and graphics output by highlighting rows and columns of pixels (in the case of video displays) or rows and columns of dots (in the case of printers). See also pixel.

rasterizer

A Windows dynamic-link library that converts the graphics commands and hints for TrueType glyphs into actual bitmaps that are drawn on a video display or page of paper. See also bitmap, glyph, dynamic-link library (DLL).

rectangular region

A region with the shape of a rectangle. See also region.

Red Book audio

See compact disc − digital audio (CD-DA).

red, green, blue (RGB) format

A color format that identifies a given color with a red, green, blue (RGB) triplet. This format is used by video displays.

reference count

The number of times a string has been added to or deleted from an atom table. The AddAtom or GlobalAddAtom function increments the count; the DeleteAtom or GlobalDeleteAtom function decrements the count. See also atom table.

reference device

The device where the original picture was created.

reference device context (DC)

The device context associated with the reference device.

reflection

A transformation that creates a mirror image of an object.

region

A rectangle, polygon, ellipse (or a combination of two or more of these shapes) used by Windows-based applications to define a part of the client area to be painted, inverted, filled with output, framed, or used for hit testing. See also ellipse, hit testing, polygon.

region operation

A procedure such as inverting, painting, clipping, or hit testing. See also clipping, hit testing.

registered clipboard format

A clipboard format registered by an application, as opposed to a standard clipboard format.

registry

The database in which configuration information is registered. This database takes the place of most configuration and initialization files for Windows and new Windows-based applications.

regular curve

A curve that defines the perimeter of a conic section.

relative identifier (RID)

The portion of a security identifier (SID) that identifies a user or group in relation to the authority that issued the SID. See also security identifier (SID).

render

To make data available in a specific clipboard format. See also clipboard format.

Replace common dialog box

A common dialog box that displays two edit controls where the user can type strings: The first string identifies a word or value that the application should replace, and the second string identifies the replacement word or value. See also common dialog box, edit control.

reserved page

A page of memory in a process's virtual address space that has been set aside for future use. The page is not accessible and has no physical storage associated with it. A reserve page reserves a range of virtual addresses that cannot be used subsequently by other allocation operations.

resolution

(1) For joysticks, the minimum and maximum intervals between joystick messages sent for a captured joystick.

(2) For timers, the accuracy of the timer event. A resolution value of zero means that the event must occur at the exact time requested; a resolution value of ten means that the event must occur within ten milliseconds of the requested time.

resource

Binary data the resource compiler or developer adds to an application's executable file. Windows resources include icons, cursors, menus, dialog boxes, bitmaps, fonts, keyboard-accelerator tables, message-table entries, string-table entries, version data, and user-defined data.

resource compiler

An application that creates a binary resource file based on the resource-definition file. The resource compiler can also append binary resource data to an executable file and create a resource table in the executable file's header. See also resource table.

resource-definition file

A text file containing descriptions of an application's resources. The resource compiler creates a binary resource file based on the contents of the resource-definition file. Resource-definition files usually have a .RC extension.

resource file

A binary file created by the resource compiler that contains an application's resource data. Resource files usually have a .RES extension. See also resource compiler.

Resource Interchange File Format (RIFF)

A tagged-file specification used to define standard formats for multimedia files. Tagged-file structure helps prevent compatibility problems that often occur when file-format definitions change over time. Because each piece of data in the file is identified by a standard header, an application that does not recognize a given data element can skip over the unknown information. See also tagged file format.

resource object

An object file that consists of the resource file and the resource table. The linker links the resource object to the executable file. See also resource file.

resource table

Data the resource compiler adds to the header of an application's executable file. This data includes the location, name, type, language, and so on, of each resource in the executable file. See also resource compiler.

restore box

A bitmap that, when clicked, restores the window to its previous size and position.

restored window

A window that does not have the WS_MAXIMIZE or WS_MINIMIZE style.

RGB format

See red, green, blue (RGB) format.

RID

See relative identifier (RID).

RIFF

See Resource Interchange File Format (RIFF).

RIFF chunk

A chunk with chunk identifier Resource Interchange File Format (RIFF) that includes an identifying code and zero or more subchunks, the contents of which depend on the form type.

RIFF file

A file whose format complies with one of the published Resource Interchange File Format (RIFF) forms. Examples of RIFF files include WAVE files for waveform audio data, RMID files for Musical Instrument Digital Interface (MIDI) sequences, and RDIB files for device-independent bitmaps.

RIFF form

A file-format specification based on the Resource Interchange File Format (RIFF) standard.

root directory

The topmost directory on a volume. Files and directories on a volume are organized in a tree structure whose entry point is the root directory. The root directory is referenced in a path by a single backslash (\\) or a leading backslash in a longer path (\\MYDIR\\MYFILE.TXT). See also directory, path, volume.

rotation

A transformation that rotates an object with respect to the coordinate-space origin.

run-time linking

Dynamic linking that occurs when the LoadLibrary and GetProcAddress functions are used to get the starting address of a dynamic-link library (DLL) function.


  S

SACL

See system access control list.

sample

A discrete piece of waveform data represented by a single numerical value. Sampling is the process of converting analog data to digital data by taking samples of the analog waveform at regular intervals.

sampling rate

The rate at which a waveform audio driver performs audio-to-digital or digital-to-audio conversion. For compact disc − digital audio (CD-DA), the sampling rate is 44.1 kHz. See also compact disc − digital audio

Save As common dialog box

A common dialog box that displays a list of filenames matching any specified extensions, directories, or drives. By selecting one of the listed filenames, the user indicates what file an application should save. See also common dialog box.

scalable font

A TrueType font. See also TrueType font.

scaling

A transformation that alters the apparent size of an object.

scan code

A device-dependent value that identifies a physical key on the keyboard. Each key on a keyboard generates two unique scan codes--one when the user presses the key and the other when the user releases the key.

scan line

A single row of adjacent pixels on a video display. See also pixel.

scheduler

The component of the operating system that determines which of the competing threads receives the next slice of the processor's time. See also thread.

screen buffer

A two-dimensional array of character and color data for output in a console window. A screen buffer can be accessed for reading and writing whether it is active or inactive. Its character data can be either a Unicode™ or ANSI value. See also console window.

screen coordinates

Coordinates relative to the upper left corner of the screen.

scroll bar

An element of the Windows user interface that converts mouse or keyboard input into values that a window procedure can use to shift the contents of a window's client area either horizontally or vertically. See also window procedure.

scroll bar control

A predefined control window that belongs to the SCROLLBAR window class. See also window.

scroll box

A movable area in a scroll bar that indicates the position of the information currently displayed in the associated window. The position of the scroll box is relative to the total amount of information available for display. See also scroll bar.

scrolling

The process of shifting a data object in a window's client area in order to see parts of the object that extend beyond the border of the client area.

scrolling range

The minimum and maximum values that a scroll bar can report. See also scroll bar.

secant

A line drawn through two points on an ellipse. See also ellipse.

security descriptor

A structure that contains the security information associated with an object. An absolute security descriptor contains pointers to the information, and a self-relative security descriptor stores the structure and associated information contiguously in memory. See also absolute security descriptor, self-relative security descriptor.

security domain

A collection of nodes in a security database that share a common set of user and group accounts.

security identifier (SID)

A structure of variable length that uniquely identifies a user or group on all Windows NT™ implementations.

seek

(1) With file input and output (I/O), to change the current position in the file. (The current position is the location where the next read or write operation will take place.)

(2) With a media device (such as a hard disk), to position the medium so a certain sector can be accessed. The seek operation involves a physical movement of the device, so the time it takes can often be perceived by the user.

selection field

The portion of a combo box that displays the currently selected item. Selecting an item in the list causes that item to appear in the selection field. In simple and drop-down combo boxes, the selection field is an edit control and can be used to enter input not in the list.

self-relative security descriptor

See security descriptor.

semaphore object

An interprocess synchronization object that maintains a count between zero and some maximum value. The object's state is signaled when its count is greater than zero and nonsignaled when its count is zero. See also synchronization object.

sequence

See MIDI sequence.

sequencer

See MIDI sequencer.

service

An executable object that is installed in a registry database maintained by the Service Control Manager. The executable file associated with a service can be started at boot time by a boot program or by the system, or it can be started on demand by the Service Control Manager. The two types of service are Win32 service and driver service. See also driver service, Win32 service.

service control manager

A Windows NT system process that provides a unified and secure means of controlling Win32 and driver services. Each computer that is running Windows NT has a service control manager process that is started during system startup.

service name

A string that a server application responds to when a client attempts to establish a conversation with the server.

setmark

A special recorded element that contains no user data and is used to provide a segmentation scheme hierarchically superior to filemarks. Setmarks typically provide faster positioning on high-capacity tapes.

share mode

A condition that indicates whether a file is to be shared for reading, writing, both, or neither.

shared memory

Memory that two or more processes can read from and write to. If the file-mapping object that references the shared memory has a name, the memory is referred to as "named shared memory."

sharepoint

A network resource that remote applications can address specifically and use across a network--for example, a printer or a shared directory. See also container.

shearing

A transformation that alters the apparent length and orientation of vertical or horizontal lines in an object.

shell

An application that enables users to group, start, and otherwise control other applications.

short filemark

A filemark that contains a short erase gap that cannot be overwritten unless the write operation is performed from the beginning of the partition or from an earlier long filemark.

show state

The collective qualities of a window at a given time (whether active or visible; minimized; maximized; or restored).

shut down

To stop all processes, flush all file-system buffers to disk, and bring the system to a condition in which it is safe to turn off the computer.

sibling window

A child window that has the same parent window as one or more other child windows.

SID

See security identifier (SID).

signaled

The state of an object used for synchronization in one of the wait functions. A signaled state can enable the wait function to return. See also nonsignaled, wait function.

signature

A 4-byte value that identifies an enhanced metafile. See also enhanced metafile.

simple combo box

A combo box in which the list box is visible at all times.

simple device

A media control interface (MCI) device that does not require a device element (data file) for playback. The MCI compact disc audio driver is an example of a simple device.

simple list

A list in a combo box that is always visible. Combo boxes with the CBS_SIMPLE style contain simple lists.

single-byte character set

to their identifying numeric values, in which each value is one byte wide. The ANSI and original equipment manufacturer (OEM) character sets are single-byte character sets. See also character set, multibyte character set, Unicode.

single-selection list box

A list box in which only one item can be selected at a time.

sizing border A type of window border that enables the user to size the window by clicking and dragging the border.

SMPTE

See Society of Motion Picture and Television Engineers.

SMPTE division type

One of four SMPTE timing formats. SMPTE time is expressed in hours, minutes, seconds, and frames. The SMPTE division type specifies the frames-per-second value corresponding to a given SMPTE time. For example, a SMPTE time of one hour, 30 minutes, 24 seconds, and 15 frames is useful only if the frames-per-second value, or SMPTE division type, is known.

SMPTE offset

A Musical Instrument Digital Interface (MIDI) event that designates the SMPTE time at which playback of a MIDI file is to start. SMPTE offsets are used only with MIDI files using SMPTE division type.

SMPTE time

A standard representation of time developed for the video and film industries. SMPTE time is used with Musical Instrument Digital Interface (MIDI) audio because many people use MIDI to score films and video. SMPTE time is an absolute time format expressed in hours, minutes, seconds, and frames. Standard SMPTE division types are 24, 25, and 30 frames per second.

Society of Motion Picture and Television Engineers (SMPTE)

An association of engineers involved in movie, television, and video production. SMPTE also refers to SMPTE time, the timing standard that this group adopted.

solid brush

A logical brush created from a bitmap that contains pixels of the same color. See also bitmap, logical brush, pixel.

source

A configuration registry key that specifies message-file names for replacement strings in events logged by an application, service, or group of applications. Sources are subkeys of logfile keys. See also key, logfile, subkey.

square-wave synthesizer

A synthesizer that produces sound by adding square waves of various frequencies. A square wave is a rectangular waveform.

standard cursors

The default cursors that Windows automatically displays when users move windows or icons, resize windows, or wait. Standard cursors include an arrow, hourglass, crosshair, and I-beam. Standard cursors are also known as system cursors. See also cursor, icon, window.

standard icons

The default icons that Windows displays in system message boxes. Standard icons include, among other bitmaps, a stop sign and a circled exclamation point. See also icon.

standard resource

A resource whose format is defined and recognized by Windows. Standard resources include icons, cursors, menus, dialog boxes, bitmaps, fonts, keyboard accelerator tables, message-table entries, string-table entries, and version data.

standard scroll bar

A scroll bar created as part of the nonclient area of an overlapped, pop-up, or child window. See also scroll bar.

standard VGA

A video adapter that supports a resolution of 640 by 480 pixels and 16 simultaneous colors. See also pixel.

static control

An element of the Windows user interface used to display text and graphics that require no response from the user. Static controls are typically used in dialog boxes.

stock brush

One of seven logical brushes maintained by Windows. See also logical brush.

stock pen

A cosmetic pen created and maintained by the window manager. There are three kinds of stock pens: black, white, and invisible. See also cosmetic pen.

streaming

The process of transferring information from a storage device, such as a hard disk or CD-ROM, to a device driver.

string atom

An atom that identifies a character string in an atom table. See also atom, atom table.

string handle

A doubleword value, assigned by the operating system, that identifies a string passed between a dynamic data exchange (DDE) client and a DDE server. See also dynamic data exchange (DDE).

stroked path

A path that is outlined by using the pen that is currently selected into an application's device context. See also device context, path, pen.

structured exception handling

A mechanism for handling hardware- and software-generated exceptions. Structured exception handling gives developers complete control over the handling of exceptions, provides support for debuggers, and is usable across all programming languages and computers.

style names

One of two attributes used to organize TrueType® fonts. Style names include extra-bold, bold, and italic. (The other attribute used to organize TrueType fonts is the family name.) See also TrueType font.

subclass procedure

An application-defined window procedure that replaces a window's original window procedure when the window is subclassed. See also subclassing, window procedure.

subclassing

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. See also subclass procedure.

subdirectory

A directory within another directory. See also directory.

subkey

An entry (or node) in the registry subordinate to a given key. With the exception of four predefined keys, all keys are subkeys of other keys. See also key, registry.

sublanguage identifier

An 8-bit value identifying the variant of a language in a language identifier. See also language identifier, primary language identifier.

subtractive color technology

The color technology, used by ink-based printers, that is based on the three primary colors cyan, yellow, and magenta. Other colors (except white) are obtained by combining two or more of the primaries in varying amounts. White is defined as the absence of the primaries. Black is defined as the presence of all the primaries.

super VGA

A video adapter that supports resolutions higher than 640-by-480 pixels or more than 16 simultaneous colors (or both).

superclass procedure

An application-defined window procedure that replaces the window procedure for a window of a particular window class when the class is superclassed. See also superclassing, window procedure.

superclassing

A technique that allows an application to create a new window class that has the basic functionality of the existing class, but with enhancements provided by the application. See also superclass procedure.

syllabary

A single character that represents what we would call a syllable, using consonant/vowel combinations as their linguistically-discrete units — for example, the sound created by "ta." This term would apply to Kana (Katakana and Hiragana) and Hangul scripts. Linguists use the word "syllabary" to define a system of phonemic (linguistically-distinct) syllabic units used in a language.

synchronization object

An object whose handle can be specified in one of the wait functions to coordinate the execution of multiple threads. Synchronization objects include change notification, console input, event, mutex, process, thread, and semaphore objects. See also object, wait function.

system access-control list (SACL)

An access-control list (ACL) that is controlled by a system administrator and used to control the generation of audit messages. See also access-control list (ACL), discretionary access-control list (DACL).

system directory

The directory that contains Windows libraries, drivers, and font files. See also directory.

system-exclusive data

In Musical Instrument Digital Interface (MIDI), messages understood only by MIDI devices from a specific manufacturer. MIDI device manufacturers can use system-exclusive data to define custom messages that can be exchanged between their MIDI devices. (The standard MIDI specification defines only a framework for system-exclusive messages.) See also Musical Instrument Digital Interface.

System menu

A pop-up menu, defined mainly by the operating system, that typically contains commands used to set a window's size or position, close a window or application, or activate a different application. See also pop-up menu.

system metric

A dimension of a Windows display element, such as the border width, scroll bar arrow height, icon height, and so on. System metrics may also describe other aspects of the operating system, such as whether a mouse is installed, whether the current version of Windows supports double-byte characters, and so on. See also scroll bar.

system paging file

The storage file that the kernel uses to hold pages of memory swapped out of RAM.

system palette

An array that identifies all of the colors that can be displayed simultaneously on a device. For most displays, this array is a subset of all possible colors that can appear on the display.

system time

The "real-time" clock format. System time uses a structure containing individual members for the date and time.


  T

tagged file format

A file format in which data is tagged using standard headers that identify information type and length. See also Resource Interchange File Format (RIFF).

tape drive

A device that reads from and writes to a tape.

tape volume

A recording medium and its physical carrier.

tempo

The speed at which a Musical Instrument Digital Interface (MIDI) file is played. Tempo is measured in beats per minute (BPM); typical MIDI tempo is 120 BPM. See also Musical Instrument Digital Interface.

tension

To move the tape to the end-of-medium marker and back to the beginning-of-medium marker in one command.

termination handler

A mechanism by which a developer ensures that a block of termination code is executed. A termination handler consists of a guarded body of code and a termination block. See also guarded body of code.

thread

The basic entity to which the operating system allocates CPU time. A thread can execute any part of the application's code, including a part currently being executed by another thread. All threads of a process share the virtual address space, global variables, and operating system resources of the process. See also process.

thread affinity mask

A bit vector in which each bit represents the processors that a thread is allowed to run on.

thread local storage

A storage method in which an index can be used by multiple threads of the same process to store and retrieve a different value for each thread. See also thread.

threshold

For the joystick interface, the amount, in device units, that the stick coordinates must change before the application is notified of the movement. A high threshold reduces the number of joystick messages sent to an application, but it also reduces the sensitivity of the joystick.

time-out value

The interval, in milliseconds, measured by a timer.

timer

An internal routine that causes the system to send a WM_TIMER message whenever a specified interval elapses.

time slice

A unit of processor time (in clock ticks) allocated to a thread. See also thread.

time stamp

A tag that enables a Musical Instrument Digital Interface (MIDI) sequencer to replay recorded MIDI data at the proper moment. See also Musical Instrument Digital Interface.

title bar

A window component that displays an application-defined line of text. Typically, the text identifies the application or indicates the purpose of the window.

TLS

See thread local storage.

TMSF time format

A time format used by Media Control Interface (MCI) to express time in tracks, minutes, seconds, and frames. The number of frames in a second depends on the type of device being used; compact disc audio devices use 75 frames per second. The TMSF time format is used primarily by compact disc audio devices. See also Media Control Interface (MCI).

token

See access token.

top-down DIB

A device-independent bitmap (DIB) whose origin lies at the top-left corner. See also bottom-up DIB.

top-level window

A window that has no parent window.

topic name

A string that identifies the type of data requested by a dynamic data exchange (DDE) client application.

topmost window

A window with the WS_EX_TOPMOST style. A topmost window overlaps all other non-topmost windows.

track

A sequence of sound on a compact disc − digital audio (CD-DA) disc. With a Musical Instrument Digital Interface (MIDI) file, information can be separated into tracks, defined by the creator of the file. MIDI file tracks can correspond to MIDI channels, or they can correspond to parts of a song (such as melody or chorus); a CD-DA track usually corresponds to a song. See also compact disc − digital audio.

transaction filter

A flag that prevents the Data Exchange Management Library (DDEML) from passing an unwanted type of transaction to an application's dynamic data exchange (DDE) callback function. See also dynamic data exchange (DDE).

transformation

An algorithm that alters ("transforms") the size, orientation, and shape of objects.

translation

A transformation that shifts an object farther from or closer to the coordinate-space origin.

TrueType font

A font whose glyphs are stored as a collection of line and curve commands plus a collection of hints. Windows uses the line and curve commands to define the outline of the glyph's bitmap. Windows uses the hints to adjust the length of the lines and shapes of the curves. These hints and the respective adjustments are based on the amount of scaling used to reduce or increase the size of the bitmap. See also bitmap, font, glyph.

try block

A guarded body of code in a try-except frame-based exception handler or try-finally termination handler. See also frame-based exception handler, guarded body of code, termination handler.


  U

Unicode

A 16-bit character set capable of encoding all known characters and used as a worldwide character-encoding standard. Windows uses Unicode exclusively at the system level.

universal well-known security identifier (SID)

An SID that is meaningful on all secure systems using the security model implemented in Windows NT™.

user-defined pen

A cosmetic or geometric pen that uses a unique series of dashes, dots, or dashes and dots defined by the user. See also cosmetic pen, geometric pen.

UTC

See Coordinated Universal Time.


  V

value

Data associated with a key. A key may have zero or more values. Each value has three parts: a name, a type, and data. See also key.

vector device

A device that creates text and graphics output by drawing lines.

viewport

A rectangle in device space that is used to specify a transformation between page and device space. The viewport extents are always measured in pixels for a video display or dots for printers.

viewport extent

The width or height of the viewport.

viewport origin

The corner of the viewport from which the extents are measured. (The viewport-origin coordinates are specified with respect to the device-space origin.)

virtual-key code

A device-independent value that identifies the purpose of a keystroke as interpreted by the Windows keyboard device driver.

visible region

The part of the client area that is visible to the user.

visible window

A window that has the WS_VISIBLE style. A visible window is displayed on the screen and can receive user input.

volatile key

A key that is valid only until the next time the operating system is started. See also key.

volume

A storage medium, such as a disk or tape, that is formatted to contain files and directories. A volume is accessed through a disk drive. In a path, a volume is referenced by the letter of the disk drive that accesses the volume. For example, a fixed disk may be referred to as C. A single volume may be divided into more than one logical volume, also called a partition. Each partition is referenced by a unique volume identifier.

volume scalar

A component of a Musical Instrument Digital Interface (MIDI) Mapper patch map that adjusts the volume of a patch on a synthesizer. For example, if the bass patch on a synthesizer is too loud relative to the piano patch, the volume scalar can reduce the volume for the bass or increase the volume for the piano. (Applications playing waveform audio can also adjust the output volume.) See also MIDI Mapper, patch.


  W

wait function

A function that blocks the execution of the calling thread until a specified set of conditions has been satisfied.

waiting thread

A thread whose execution is blocked while waiting for a wait function to return. See also wait function.

WAVE file

A Microsoft standard file format for storing waveform audio data. WAVE files have a .WAV filename extension.

waveform audio

A technique of recreating an audio waveform from digital samples of the waveform.

wide character

A synonym for a Unicode™ character; Unicode characters are 2 bytes wide.

widened path

A modified path. See also path.

wildcard characters

Characters that represent one or more characters in a filename. The Windows wildcard characters are the question mark (?) and the asterisk (*). The question mark matches any single character; the asterisk matches any combination of characters. For example, if a directory contains files with the names BAT, B12, BOAT, and CAT, the pattern b\* matches the names BAT, B12, and BOAT. The pattern b?t matches only the name BAT.

Win32 service

A service that conforms to the interface rules of the Service Control Manger. This enables the Service Control Manager to start the service at system startup or on demand and enables communication between the service and service control programs. A Win32 service can execute in its own process, or it can share a process with other Win32 services.

window

A rectangle in page space that is used to specify a transformation between page and device space.

window extent

The width or height of the window.

window handle

A 32-bit value, assigned by Windows, that uniquely identifies a window.

window name

A text string that identifies a window for the user.

window origin

(1) The upper left corner of a window's client area.

(2) The corner of the window from which the extents are measured. (The window-origin coordinates are specified with respect to the page-space origin.)

window procedure

A function, called by the operating system, that controls the appearance and behavior of its associated windows. The procedure receives and processes all messages to these windows.

window style

A named constant that defines an aspect of the window's appearance and behavior not specified by the window's class.

window text

See window name.

Windows directory

The directory that contains Windows-based applications, initialization files, and Help files. See also directory.

Windows metafile

One of two metafile formats. This format, used for applications written to run with Windows version 3.x, consists of a header and an array of metafile records. See also metafile record.

Windows time

The number of milliseconds since Windows started running. This time is recorded as a 32-bit value, so it overflows to zero every 49.7 days.

world coordinate space

The coordinate space in which all graphics device interface (GDI) drawing operations begin if an application has set the world-space to page-space transformation.

world space

The coordinate space in which all graphics device interface (GDI) drawing operations begin if an application has set the world-space to page-space transformation. Applications use world space to rotate shear, or reflect graphics output. World space measures 2^(32) units high by 2^(32) units wide, and is one of four coordinate spaces used in the Win32 API. See also device coordinate space, page coordinate space, and physical device.


  X

x-axis

The axis that normally extends horizontally across a coordinate space.


  Y

y-axis

The axis that normally extends vertically across a coordinate space.


  Z

Z order

A stack of overlapping windows. Each window has a unique position in the Z order.


 Copyright Notice

This document is provided for informational purposes only, and Microsoft Corporation makes no warranties, either express or implied, in this document. The entire risk of the use or the results of the use of this document remains with the user. Companies, names, and data used in examples herein are fictitious unless otherwise noted. No part of this document may be reproduced or transmitted in any form or by any means, electronic or mechanical, for any purpose, without the express written permission of Microsoft Corporation.

© 1995 Microsoft Corporation. Portions Copyright Intel/Microsoft 1992-93. All Rights Reserved.


 Introduction

The Microsoft Windows Telephony application programming interface (API) provides services that enable an application developer to add telephone communications to applications developed for the Microsoft Win32 (API). This guide is intended to help experienced programmers learn the application programming interface for Telephony under the Windows operating system.

This document is intended to be used by developers familiar with the Win32 programming environment. Previous development experience with telecommunications or other telephony applications is helpful but not necessary.


 Document Overview

This guide presents general information about how to develop telephonic applications and offers specific information about the functions, messages, and data types of the Telephony API (TAPI). Following the introduction, this guide is divided into three parts:

Part I, "Telephony Basics", describes what Windows Telephony is, how it can be used within Windows applications, and how to use the Software Development Kit (SDK).

•	Chapter 1, "Overview of Telephony", explains Windows Telephony's position within the Windows Open Services Architecture (WOSA) environment and describes the TAPI programming model.

•	Chapter 2, "The Telephony Programming Model", explains the concepts programmers should know before they begin development of telephonic applications. It includes sections that describe the uses of Assisted Telephony, Telephony's device classes, addresses, and other topics.

•	Chapter 3, "Programming Telephony Applications: Getting Started", outlines the elements of the Windows Telephony SDK.

•	Chapter 4, "Programming with Assisted Telephony", tells how to add basic telephonic functionality to applications that don't require the flexibility or control provided by the full Telephony API. This chapter also provides a complete listing of the Assisted Telephony functions, messages, and data types. Readers whose development goals do not include the creation of new applications with a variety of telephonic functions may need to read no further than this chapter.

Part II, "Telephony Programmer's Guide", explains the concepts associated with developing Telephony functionality within applications.

•	Chapter 5, "Concepts of Line Devices," explains one of the two device classes defined by TAPI: the line device. (The data functions, data types, and messages for the other device class, the phone device, are detailed in chapters 11-13.)

•	Chapter 6, "Programming a TAPI Application", refers to the source code of a telephonic application (supplied with the Windows Telephony SDK) to illustrate how to create a functional Windows application.

•	Chapter 7, "Supplementary Line Functions", describes some of the more advanced functions used to create telephonic applications, include media monitoring, media control, and call conferencing.

•	Chapter 8, "Multiple-Application Programming Considerations", details what developers need to know when programming more than one application to work together or among other applications.

•	Chapter 9, "Programming with Phone Devices", describes the phone device class and the functions TAPI provides to use phone devices.

Part III, "Telephony: Reference", contains several chapters of detailed reference information about the functions, messages, or data types that are used by the Telephony API. These chapters, which also constitute the online TAPI reference (a Windows Help file), are the following:

•	Chapter 10," Line Device Functions"

•	Chapter 11, "Line Device Messages"

•	Chapter 12, "Line Device Data Structures"

•	Chapter 13, "Line Device Constants"

•	Chapter 14, "Phone Device Functions"

•	Chapter 15, "Phone Device Messages"

•	Chapter 16, "Phone Device Data Structures"

•	Chapter 17, "Phone Device Constants"

Part IV, "Appendices", contains sections of supplementary reference information for using TAPI:

•	Appendix A, "TAPI Quick Function Reference", lists the functions of TAPI, a brief description of each, and the nature of each function's reply callback: synchronous or asynchronous.

•	Appendix B, "Windows Telephony Configuration Parameters", describes the purpose of the TELEPHON.INI file and why telephony applications need to communicate with it.

•	Appendix C, "Call States and Events", describes the call states through which a call transitions as it is established or disconnected.

•	Appendix D, "Glossary of Telephony Terminology", defines terms useful to developers of TAPI applications.


 Telephony API for Windows 95

To provide improvements and better serve clients, Windows Telephony includes the following extensions in Windows 95:

Plug and Play — Class installers, including the Telephony class installer, have the ability to cause Telephony service providers to be added or removed from the Telephony system without user interaction with the Telephony control panel. Also, service providers are able to dynamically create new devices without restarting the entire Telephony system.

User interface improvements and commonality — The "Change Options and Redial" functionality and the ability to select Telephony locations and calling cards are common to all telephony applications. A common dialog is accessible to all applications through TAPI, so that this function looks the same in all applications and users have to learn it only once.

Access to additional information — Applications can present information to the user not previously been exposed, such as the list of country codes.

Elimination of application calls directly into Telephony control panel — All access to control panel functions by Win32 applications is through TAPI.

VoiceView support — Support for alternate voice/data support in modems with the addition of the VoiceView media mode to the existing media modes supported in TAPI.


 Telephony API Version 1.4, Changes and Additions

For Windows 95, TAPI includes a number of new functions and messages as well as some changes to existing structures and constants. The following list these new items:

Functions
lineTranslateDialog	New
lineGetCountry	New
lineGetAppPriority	New
lineSetAppPriority	New
lineAddProvider	New
lineConfigProvider	New
lineRemoveProvider	New
lineGetProviderList	New
lineConfigDialogEdit	New
lineReleaseUserUserInfo	New
Messages
LINE_CREATE	New
PHONE_CREATE	New
LINE_ADDRESSSTATE	Changed
LINE_CALLSTATE	Changed
LINE_LINEDEVSTATE	Changed
PHONE_STATE	Changed
Structures
LINEADDRESSCAPS	Changed
LINECARDENTRY	Changed
LINECOUNTRYLIST	New
LINECOUNTRYENTRY	New
LINEDEVCAPS	Changed
LINELOCATIONENTRY	Changed
LINEPROVIDERLIST	New
LINEPROVIDERENTRY	New
PHONEBUTTONINFO	Changed


 Document Conventions

The type conventions used in this document are as follows:

Bold text	Bold letters indicate terms, such function and structure names, that you must use exactly as shown.
ALL CAPS	All capitals typically indicate terms, such as message and constant names, that must be used exactly as shown.
Italic text	In introductory and explanatory text, italicized words indicate that a key term or concept is being introduced. In function and message descriptions, italics indicates a placeholder for which you are expected to provide a value or the name of a variable name.
Monospaced text	Monospaced type indicates code samples and data-structure definitions.


 Related Documentation

Other documentation that will help you understand the Telephony services as they apply to Windows includes:

•	Microsoft Win32 Programmer's Reference.

•	The Windows Telephony Service Provider Programmer's Guide, which provides information on how to write a Windows Telephony service provider.


 Overview of Telephony

What Is Telephony?

Telephony is a technology that integrates computers with the telephone network. With telephony, people can use their computers to take advantage of a wide range of sophisticated communications features and services over a telephone line.

The Telephony application programming interface (TAPI) lets programmers develop applications that provide personal telephony to users. TAPI supports both speech and data transmission, allows for a variety of terminal devices, and supports complex connection types and call-management techniques such as conference calls, call waiting, and voice mail. TAPI allows all elements of telephone usage—from the simple dial-and-speak call to international e-mail—to be controlled within applications developed for the Microsoft Win32 application programming interface.


 Using Telephony in Applications

Telephony capabilities help people get the most from telecommunications systems, allowing them to more efficiently manage their voice calls and control their data-transfer operations. You can use TAPI to bring this efficiency to any application — database manager, spreadsheet, word processor, personal information manager — any application that can benefit by sending and receiving data through the telephone network.

TAPI gives you a consistent set of tools for incorporate these features into your applications:

•	Connect directly to the telephone network rather than rely on a separate communications application

•	Dial phone numbers automatically

•	Transmit documents as files, facsimiles, or electronic mail

•	Access data from news retrieval and other information services

•	Setup and manage conference calls

•	Receive, store, and sort voice mail

•	Use caller-ID to automate the handling of incoming calls

•	Control the operations of a remote computer

•	Compute collaboratively over telephone lines

TAPI provides your application with access to the telephone network, you provide your users with access to these features. This means you choose and create a user interface that is consistent with the rest of your application. For example, if you use drag and drop extensively, you could let the user send files or facsimiles through the telephone to a colleague by dragging the icon of the file to an icon representing the colleague's destination. Similarly, you could let the user initiate conference calls by dragging three or four names from an electronic directory into a "Conference box" and clicking a "Connect" command. You choose the interface, and let TAPI carry out the work needed to make and manage the telephone connections.


 Telephone Network Services

TAPI provides access to a variety of telephone network services. Although these services may use different technologies to establish calls and transmit voice and data, TAPI makes these service-specific details transparent to applications. This means you can create applications that can take advantage of any available service without including service-specific code in your application.

Historicaly, most telephone connections in the world have been of the type POTS, or "Plain Old Telephone Service." Most POTS calls are transmitted digitally except while in the local loop—the part of the telephone network between the telephone and the telephone company's central switching office. Within this loop, human speech from a household telephone is usually transmitted in analog format and the digital data from a computer must first be converted to analog by a modem. Digital networks are gradually replacing analog in the local loop.

Using TAPI for POTS is straight-forward because POTS is comparatively simple. It normally uses only one type of information (such as data or voice) per call, supports one channel per line, and so on. The vast majority of uses for TAPI are still POTS, and most telephony programmers will use TAPI only for POTS applications.

But TAPI is not restricted to POTS. TAPI also lets you make connections over other types of networks. More advanced kinds of data transmission methods are being developed, refined, and installed. For example, one important digital service is Integrated Services Digital Network (ISDN), which is expected to grow significantly in availability. ISDN networks have these advantages over POTS:

•	All digital

•	Less prone to error

•	Faster data transmission, with speeds up to 128 kilobytes per second on basic service

•	From 3 to 32 channels for simultaneous transmission of voice and data

•	An international standard

On ISDN networks, error rates are lower than with analog transmission because data travels from one end of the ISDN network to the other in digital format. Speeds of up to 128 Kbps are possible on Basic Rate Interface (BRI-ISDN) standard lines and much higher on Primary Rate Interface (PRI-ISDN) standard lines. By contrast, today's maximum dial-up modem data rates of 28.8 Kbps. When ISDN connections become more widespread, users will be able to send data to the recipient simultaneously with a voice call to that or another person. Each ISDN line, depending on its transmission rate, provides at least three channels (two for voice or data and one strictly for data or signaling information) and as many as 32 channels, for simultaneous, independently operated transmission of voice and data. BRI-ISDN lines provide two 64-Kbps "B" channels (B channels carry voice or data) and one 16-Kbps "D" channel (D channels carry signaling information or packet data). The PRI-ISDN lines for the U.S., Canada, and Japan have twenty-three 64-Kbps B channels and one 64-Kbps D channel. The European PRI standard offers thirty B channels and two D channels.

TAPI can also be used with other digital networks such as T1/E1 and Switched 56 service. With Switched 56, some local and long-distance telephone companies provide signaling at 56 Kbps over dial-up telephone lines. Switched 56 is quickly becoming available throughout the U.S. and in many other countries. It requires special equipment, and though its connection capabilities are limited to calls to other specially equipped facilities, its high speed and pricing make it a reasonable choice for many data communications needs. Switched 56 is used for data calls only.

TAPI can also be used with other services such as CENTREX, which provides a set of centralized network services (such as conferencing) without the need to install special equipment. With CENTREX, you pay for the use of telephone-company equipment over regular telephone lines. In addition, TAPI can be used with digital Private Branch Exchanges (PBXs) and key systems. Because TAPI is independent of the underlying telephone network, programming a PBX application using TAPI is the same as programming a POTS application using TAPI. An application that was originally programmed for a POTS environment can be used within a PBX environment with no changes to the application's source code.


 Telephony Components

Based on the Windows Open Services Architecture (WOSA) model, Windows Telephony consists of the TAPI dynamic link library (which implements and manages the TAPI functions) and one or more telephone network service providers. The TAPI dynamic link library provides a device-independent interface for carrying out telephony tasks. Service providers are dynamic link libraries that carry out low-level and possibly device-specific actions needed to complete telephony tasks through hardware devices such as fax boards, ISDN cards, telephones, and modems. Applications link to and call functions in the TAPI dynamic link library only; they never call the service providers directly.

A third component, a support-service application called TAPIEXE.EXE, provides an execution context for the TAPI dynamic link library to carry out duties such as allocating memory or accessing data structures that have been swapped out to disk. This internal, system-only application runs in memory when running telephony applications, but does not create a window or appear in the task list. The TAPI dynamic link library automatically loads and unloads the application as needed.

When an application calls a TAPI function, the TAPI dynamic link library processes the call and routes a request to the appropriate service provider. To receive requests from the TAPI dynamic link library, the service provider must implement the Telephony service provider interface (TSPI). A service provider can provide different levels of the service provider interface: basic, supplementary, or extended. For example, a simple service provider might provide basic telephony service, such as support for outgoing calls, through a Hayes-compatible modem. An custom service provider, written by a third party vendor, might provide a full range of incoming and outgoing call support through modems other than Hayes-compatible or even through devices other than a modem.

A user can install any number service providers on a computer as long as the service providers do not attempt to access the same hardware device. The user associates the hardware and the service provider when installing. Some service providers may be capable of accessing multiple devices. In some cases, the user may need to install an device driver along with the service provider.

Applications use the TAPI functions to determine which services are available on the given computer. The TAPI dynamic link library determines what service providers are available and provides information about their capabilities to the applications. In this way, any number of applications can request services from the same service provider; the TAPI dynamic link library manages all access to the service provider.

As long as an application does not depend on optional features, the applications can, without modification, use any services to carry out telephony tasks, even services made available after the application is developed. This is because the application always accesses the many different services through TAPI which translates the requests the application makes into the actual protocols and interfaces required.

The Telephony SPI is beyond the scope of this book. For more information bout the TSPI and service providers, see the Telephony Service Provider Programmer's Reference.


 Media Stream

The media stream consists of the information exchanged over a call. TAPI by itself provides control only for line and phone devices and does not give access to the content of the media stream. To manage the media stream, an application uses Win32 functions, such as the Communication, Wave Audio, or Media Control Interface (MCI) functions. For example, an application that provides an interface for managing fax or data transmission uses the TAPI functions to control and monitor the line over which bits are sent, but uses the Communications functions to transmits the actual data.

In the same manner, the media stream in a speech call (where speech refers exclusively to human speech) is produced and controlled not by TAPI, but by one human talking to another. However, the line on which that call is established and monitored, and the call itself, remain in control of the TAPI application. (Note that voice is considered to be any signal that can travel over a 3.1 kHz-bandwidth channel.)


 Special Hardware

Some of the more advanced capabilities of TAPI require that an application be able, for example, to retrieve data from telephones. Most telephones cannot be connected directly to computers to control speech calls and thus are currently incapable of supporting Telephony functions beyond the passive role they play in POTS. In the future, users will install and configure telephone sets like other peripheral devices. The sets will be accompanied by cards that will control the flow of information between the computer and the telephone. Client-server configurations will also be possible that allow users to take advantage of telephonic services by connecting over a LAN to a server that has such a board and associated software installed.


 Physical Connections

Lines and phones can be connected in a variety of ways to the desktop computer and the telephone network. The following examples show a selection of configurations that could be supported by a service provider. Note that some of the telephone hardware required to implement some of these example is not yet widely available.

A phone-centric connection consists of a single POTS line in which the computer is connected to the switch through the desktop phone set. Such phone sets typically connect to the computer through one of its serial ports. When an application requests an action, the corresponding service provider sends telephony commands, which are often based on the Hayes AT command set (ANSI/TIA/EIA-602), over the serial connection to the telephone. This configuration is limited because it generally provides only line control.The computer does not have access to the media stream.

A computer-centric connection uses a computer add-in card or external box that is connected to both the telephone network and the phone set. The service provider can easily integrate modem and fax functions, as well as the use of the telephone as an audio I/O device.

A BRI-ISDN connection is similar tot he computer-centric connection but allows for using the two B-channels in a variety of line configurations. A service provider can treat this connection in a number of ways:

•	A single line device with a pool of two channels, allowing both channels to be combined for establishing 128 Kbps calls.

•	Two separate line devices, each with exclusive use of a single B-channel.

•	Two separate line devices, each drawing up to two channels from a shared pool of two B-channels.

•	Three line devices: one for each of the two B-channels and one for the combination.

In the latter two models, channels may be assigned to different line devices at different times.

In client-server networks, a pool of telephone ports attached to a server may be shared among multiple client computers using a local area network. The ports may be configured to assign a maximum number of line devices (the quota) to each client workstation. It is not unusual for the sum of all quotas to exceed the total number of lines.

Also, the assignment of lines through ports is dynamic. For example, a client computer with a quota of 2 may use ports 1 and 2 at one time and ports 7 and 11 at a later time.

The service provider for the pool may model this arrangement by giving each client workstation access to two line devices. This implies that the device IDs (which are fixed) for each client are 0 and 1. If the application later requests information for device 0 and again for device 1, it must assume that the device capabilities for each device is constant, since that is the Windows device model. For server-based devices that are pooled as described in the example above, this constancy holds only for line devices that have identical device capabilities.

A LAN-based server might have multiple telephone-line connections to the switch. TAPI operations invoked at any of the client computers are forwarded over the LAN to the server. The server uses third-party call control between the server and the switch to implement the client's call-control requests.

This model offers a lower cost per computer for call control if the LAN is already in use, and it also offers reduced cost for media stream access if shared devices such as voice digitizers, fax and/or data modems, and interactive voice response cards are installed in the server. The digitized media streams can be carried over the LAN, although real-time transfer of media may be problematic with some LAN technologies due to inconsistent throughput.

A LAN-based host can be connected to the switch using a switch-to-host link. TAPI operations invoked at any of the client computers are forwarded over the LAN to the host, which uses a third-party switch-to-host link protocol to implement the client's call-control requests.

Note that it is also possible for a private branch exchange (PBX) to be directly connected to the LAN, and for the server functions to be integrated into the PBX. Within this model, different sub-configurations are possible:

•	To provide personal telephony to each desktop, the service provider could model the PBX line associated with the computer (on a desktop) as a single line device with one channel. Each client computer would have one line device available.

•	Each third-party station can be modeled as a separate line device to allow applications to control calls on other stations. (In a PBX, a station is anything to which a wire leads from the PBX). This enables the application to control calls on other stations. This solution requires that the application open each line it wants to manipulate or monitor, which may be satisfactory if only a small number of lines is of interest, but may generate excessive overhead if a large number of lines is involved.

•	Model the set of all third-party stations as a single line device with one address (one phone number) assigned to it per station. Only a single device is to be opened, providing monitoring and control of all addresses (all stations) on the line. To originate a call on any of these stations, the application must only specify the station's address to the function that makes the call. No extra lin opening operations are required. However, this modeling implies that all stations have the same line-device capabilities, although their address capabilities could be different.

A potential advantage of this model is a lowered cost per computer if the LAN is already in use, but a limitation would be a possible lack of media-stream access by the computers.

The computer in use need not be a desktop computer. It can also be a laptop or other portable computer connected to the telephone network over a wireless connection.

In a shared telephony connection, the computer's connection may be shared by other telephony equipment, such as the telephone set shown below. For an application to operate properly in this arrangement, neither the application nor the service provider can assume that there are no other active devices on the line.


 The Telephony Programming Model

About the Telephony Programming Model

The Telephony application programming interface (TAPI) simplifies the development of telephonic applications by hiding the complexities of low-level communications programming. TAPI accomplishes this by abstracting telephony services to make them independent of the underlying telephone network and of the way the computer is connected to the switch and phone set. Connections to the switch may be established in a variety of arrangements including directly from the user's workstation or through a server on a local area network. Regardless of their nature, telephony devices and connections are handled in a single, consistent manner, allowing developers to apply the same programming techniques to a broad range of communications functions.

This chapter is meant for developers of applications that use the Telephony API. If you plan to use only Assisted Telephony in your application, this chapter may be skipped.


 Telephony API

Telephony services are divided into Assisted Telephony services and the services provided by the full Telephony API. In general, the full Telephony API is used to implement powerful telephonic applications and Assisted Telephony is used to add minimal but useful telephonic functionality to non-telephony applications. Telephony's services are divided into the groups shown in the following illustration:


 Assisted Telephony

A valuable feature of Windows Telephony is the small set of functions called Assisted Telephony. Assisted Telephony is designed to make the establishment of voice calls and of media calls available to any Windows application, not just those dedicated to telephonic functionality. In other words, Assisted Telephony lets applications make telephone calls without needing to be aware of the details of the services of the full Telephony API. It extends telephony to word processors, spreadsheets, databases, personal information managers, and other non-Telephony applications.

The programming model of Assisted Telephony fits within the programming model of Windows. Assisted Telephony merely adds four functions to those already available to the developer in other APIs such as the Win32 SDK.

For example, adding the Assisted Telephony function tapiRequestMakeCall to a spreadsheet lets users automatically dial telephone numbers stored in the spreadsheet (or in a connected database).

The power of Assisted Telephony can be illustrated by the following example. A spreadsheet application can incorporate functions that dial a telephone number for a speech call. As long as the application needs none of the detailed call control provided by the full Telephony API, Assisted Telephony is the easiest and most efficient way to give it telephonic functionality. Functionality beyond dialing such as the transmission and reception of data would require additional data-transfer APIs, including the communications functions of the Comm API.

Because Assisted Telephony and the full Telephony API are used and implemented in different ways, it is not advised to mix Assisted Telephony function calls and Telephony API function calls within a single application.


 Service Levels

All the functionality of Assisted Telephony exists in the full Telephony API, but Assisted Telephony has its own set of commands. Thus, the Telephony interface consists of all Telephony's functions except those of Assisted Telephony. Applications whose telephony functionality goes beyond the most basic call control or are meant to handle inbound calls must be built using Telephony. The Telephony API defines three levels of service:

•	The elementary level of service is called Basic Telephony and provides a minimum set of functions that corresponds to "Plain Old Telephone Service" (POTS). TAPI service providers are required to support all Basic Telephony functions.

•	The next service level is Supplementary Telephony service, which provides advanced switch features such as hold, transfer, and so on. All supplementary services are optional; that is, the service provider is not required to support them.

•	At the Extended Telephony level, the API provides well-defined API extension mechanisms that enable application developers to access service provider-specific functions not directly defined by the Telephony API.


 Basic Telephony Services

Basic Services are a minimal subset of the Windows Telephony specification. Since all service providers must support the functions of Basic Services, applications that use only these functions will work with any TAPI service provider. The functionality contained in Basic Telephony roughly corresponds to the features of POTS.

Today, many programmers will use only the services provided by Basic Telephony. But others, such as those writing code for PBX phone systems, will need the functions of Supplementary Telephony. Soon, the demand for ISDN and other network services, along with advancements in telephone equipment, will drive even greater usage of Supplementary Telephony.

For a list of the functions of Basic Telephony, please see Appendix A, "Quick Function Reference."

Because control of phone devices is not assumed to be offered by all service providers, phone-device services are considered to be "optional." That is, they are not a part of Basic Telephony. For a list of phone-device services, please read the following section on Supplementary Telephony services, and for more information on phone devices, see the section "Device Classes" later in this chapter.


 Supplementary Telephony Services

Supplementary Telephony Services are the collection of all the services defined by the API other than those included in the Basic Telephony subset. It includes all so-called "supplementary" features found on modern PBXs, such as hold, transfer, conference, park, and so on. All supplementary features are considered optional; that is, the service provider decides which of these services it does or does not provide.

An application can query a line or phone device for the set of supplementary services it provides using functions such as lineGetDevCaps or lineGetAddressCaps. Note that a single supplementary service may consist of multiple function calls and messages. It is important to point out that the Telephony API, and not the service provider developer, defines the behavior of each of these supplementary features. A service provider should provide a Supplementary Telephony service only if it can implement the exact meaning as defined by the API. If not, the feature should be provided as an Extended Telephony service.

As mentioned under Basic Telephony Services above, phone-device services are considered "optional." Therefore, all phone-device services are part of Supplementary Telephony. For a list of the functions of Supplementary Telephony, please see Appendix A, "Quick Function Reference."


 Extended Telephony Services

The API contains a mechanism that allows service-provider vendors to extend the Telephony API using device-specific extensions. Extended Services (or Device-Specific Services) include all extensions to the API defined by a particular service provider. Since the API defines the extension mechanism only, the definition of the Extended-Service behavior must be completely specified by the service provider.

TAPI's extension mechanism allows service-provider vendors to define new values for some enumeration types and bit flags and to add fields to most data structures. The interpretation of extensions is keyed off the service provider's Extension ID, an identifier for the specification of the set of extensions supported, which may cross several manufacturers. Special functions and messages such as lineDevSpecific and phoneDevSpecific are provided in the API to allow an application to directly communicate with a service provider. The parameters for each function are also defined by the service provider.

Vendors are not required to register in order to be assigned Extension IDs. Instead, a utility is provided that allows the generation of Extension IDs locally. This unique ID is composed of an Ethernet-adapter address, a random number, and the time of day. An ID is assigned to a set of extensions (before distribution), not to each individual instance of an implementation of those extensions. A tool called EXTIDGEN.EXE is provided within the Win32 SDK that allows service provider authors to generate these IDs.


 Extending Data Structures and Types

A range of values is reserved to accommodate future extensions to the Basic and Supplementary TAPI function set. The "Extensibility" section in the data structure entry in the online TAPI reference and in the later chapters of this guide tells the amount by which the data structure can be extended. For a list of the functions used for extending Telephony, please see Appendix A, "Quick Function Reference."


 Version Parameters

Every function that takes a dwAPIVersion or similar parameter must set this parameter to either the highest API version supported by the application or the API version negotiated using the lineNegotiateAPIVersion or phoneNegotiateAPIVersion function on a particular device. Use the following table as a guide:

lineGetAddressCaps	Use version returned by lineNegotiateAPIVersion
lineGetCountry	Use highest version supported by the application
lineGetDevCaps	Use version returned by lineNegotiateAPIVersion
lineGetProviderList	Use highest version supported by the application
lineGetTranslateCaps	Use highest version supported by the application
lineNegotiateAPIVersion	Use highest version supported by the application
lineNegotiateExtVersion	Use version returned by lineNegotiateAPIVersion
lineOpen	Use version returned by lineNegotiateAPIVersion
lineTranslateAddress	Use highest version supported by the application
lineTranslateDialog	Use highest version supported by the application
phoneGetDevCaps	Use version returned by phoneNegotiateAPIVersion
phoneNegotiateAPIVersion	Use highest version supported by the application
phoneNegotiateExtVersion	Use version returned by phoneNegotiateAPIVersion
phoneOpen	Use version returned by phoneNegotiateAPIVersion


 Device Classes

Device classes simplify development by letting programmers treat devices that have similar properties in a similar manner. Real-world devices such as telephones, modems, and telephone lines belong to device classes. Applications access devices belonging to a given class using the same functions.

An application never needs to know which service provider controls which device.

Device classes help make TAPI extensible by providing a framework from which to classify and support new equipment.

Application developers should keep in mind the existence of other applications that share telephony services, as explained in Chapter 8, "Multiple-Application Programming."

There are two device classes: line device and phone device.

It also defines two sets of functions and messages, one used for line devices and one used for phone devices.

The line device class is a device-independent representation of a physical line device, such as a modem. It can contain one or more identical communications channels (used for signaling and/or information) between the application and the switch or network. Since channels belonging to a single line have identical capabilities, they are interchangeable. In many cases (as with POTS), a service provider will model a line as having only one channel. Other technologies, like ISDN, offer more channels, and the service provider should treat them accordingly.

A service provider may allow an application to request that multiple channels be combined in a single call (as, for example, when ISDN "B" channels are combined into "H" channels) to give the call wider bandwidth, using a technique often referred to as inverse multiplexing. This added bandwidth enables the call to transmit more information at the same time. For most current telephonic purposes, inverse multiplexing is not necessary.

In POTS, it is normally necessary to assign one channel per line, but with ISDN, a line's channels are dynamically allocated when an application makes or answers a call. Because these channels have identical capabilities and are interchangeable, the application need not identify which channel is to be used in a given function call. Channels are owned and assigned by the service provider for the line device in a way that is transparent to applications. This channel management is a method of abstraction that eliminates the need to introduce the naming of channels by TAPI.

Just as a line device class is an abstraction of a physical line device, the phone device class represents a device-independent abstraction of a telephone set. TAPI treats line and phone devices as devices that are independent of each other. In other words, you can use a phone (device) without using an associated line, and you can use a line (device) without using a phone.

Service providers that fully implement this independence can offer uses for these devices not defined by traditional telephony protocols. For example, a person can use the handset of the desktop's phone as a waveform audio device for voice recording or playback, perhaps without the switch's knowledge that the phone is in use. In such an implementation, lifting the local phone handset need not automatically send an offhook signal to the switch.

This independence also allows an application to ring the local telephone in a manner that is independent of inbound calls. The capabilities of service providers is limited by the capabilities of the hardware and software used to interconnect the switch, the phone, and the computer.


 Addresses to Lines Assignments

An address is the telephone number, complete with national or international codes, of a telephone, fax machine, or other device that can receive calls. Addresses can be dialed by a human or stored in an electronic directory for retrieval and use by a telephony application. For more complete information on addresses assignments, channels, and lines, please see Chapter 5, "Line Devices."

The local assignment of an address to a line (that is controlled in TAPI) takes place in the setup operation for the service provider. This can be done using the Control Panel to configure the service provider or by calling the lineConfigDialog function from within the application. On the local side of the central office, everything about a line is controlled by a service provider, such as whether there are multiple addresses and what these addresses are.

Usually, there is exactly one address per line, with the following exceptions:

•	Multiple Addresses with POTS.  In POTS, multiple addresses work only with systems that support distinctive ringing or are connected to a "DID trunk." (DID—direct inward dialing—is an extra-fee service provided by the phone company.) With DID in a multi-user voice mail system, the dialed number is signaled to the system on the DID trunk before the call rings. This allows the system to play the called party's pre-stored announcement message and to store any incoming messages in the correct voice mail box.

On a residential line with "distinctive ringing service," different ringing patterns correspond to multiple numbers assigned to the same line.

•	Multiple Addresses with ISDN.  ISDN was designed to allow simultaneous multiple addresses. It does that by providing multiple channels, each of which can have its own address. On an ISDN network, "call offering" (which means a call-setup message has been sent from the switch) takes place before ringing, so the call can be redirected before it is answered. The lineAccept function means "start ringing" for ISDN. For POTS, it means that some application has accepted responsibility for the call and has presented it to the user.


 Call Control

The developer's view of telephony is one in which telephone lines and phone sets are logically connected through TAPI. This logical connection also provides a point of termination for the telephone line. The physical connection can be made at the desktop, or at a LAN-based host or server, where a LAN protocol "extends" the connection of the phone lines or phone to the client application. TAPI uses a first-party call-control model on the logically terminated line as well as control of the associated phone device, if any.

Applications access Telephony API services using a first-party call control model. This means that the application controls telephone calls as if it is an endpoint (the initiator or the recipient) of the call. The application can make calls, be notified about inbound calls, answer inbound calls, invoke switch features such as hold, transfer, conference, pickup, and park, and can detect and generate DTMF tones for signaling remote equipment. An application can also use TAPI functions to monitor call related activities occurring in the system.

In contrast, third-party call control means that the controlling application does not act as an endpoint of the call. A third-party call-control model allows an application to establish or answer a call between any two parties—the application does not act as either of these parties.

A service provider may implement TAPI's line and phone functions by treating the set of all stations on the switch as a single line device to which multiple phone numbers are assigned. Each phone number on the line device maps to one of the stations on the switch—that is, calls passing through the switch can reach a local station by using its address (telephone number). The application can answer calls or make calls, selecting any one of the addresses on the line device as the origination number. Although the application appears to be the originating party, a call is actually established between the station whose address was selected by its originating number and the other party. However, this implementation is a type of third-party call control and is not a design goal of TAPI, which emphasizes first-party call control applications.


 Media Access

The media mode is the form in which data is transmitted on a line. The four main types of media mode are voice, speech, facsimile, and data. With TAPI, calls can be established independently of the call's media mode.

The media stream is the actual stream of information that travels on the line. Phone devices and calls on line devices are capable of carrying media streams. The Telephony-API line and phone device classes provide a wide range of control operations for these devices, but access to the media stream itself is not provided by TAPI. Instead, the application must use other APIs for the Windows environments to access or manage these media streams. These APIs include the Waveform API, the Comm API, and the MCI (Media Control Interface). (The Waveform API is used for multi-media programming, the MCI provides a high-level generalized interface for controlling media devices, and the Comm API is the set of communications functions provided by the Win32 SDK.)

For example, for line devices, an application can use TAPI to establish a connection to another station. Once the connection is established, the application can then use the Waveform API (or the MCI Waveaudio API) on the associated device to play back (send) and record (receive) audio data over the connection. Similarly, if the connection's media stream is from a modem, an application would use the modem configuration extensions of the Comm API to control the media stream.

To provide TAPI and media-stream access to either a phone or a call on a line device, the service provider must implement both the Telephony SPI and the appropriate media stream SPI or DDI (device-driver interface). The service provider can support lines and phones simultaneously.

Since these device classes and media stream interfaces function independently of one another, coordination of their usage must occur at the application level. Multiple applications that share calls and media streams in nontrivial ways will likely need to coordinate their activities at the application level to prevent conflicting usage of TAPI and the media stream API in use. For more information on preventing conflicts, please see Chapter 8, "Multiple-Application Programming."

TAPI reports changes in the type of media stream (voice, fax, data modem, and so on) to participating applications. This process is sometimes referred to as call classification. The mechanism used to determine the type of media stream is specific to the service-provider. For example, a service provider may filter the media stream for energy or tones that characterize the media type, or it may use distinctive ringing, information exchanged in messages over the network, or knowledge about the caller or called ID to make this determination.

TAPI also provides limited support for control of the media stream on a call, particularly in server-based networks. The actual data does not pass through TAPI, but TAPI can be used to a limited extent to control functions that control the media stream. This control is provided to avoid latency (delay) problems that could arise in client-server configurations for which the application is forced to use the stream's media API. An application can request actions on a call's media stream if these actions are to be triggered by events normally reported by TAPI, such as the detection of a tone or DTMF digit, or the transition of a call to a specified call state.

For example, an application can request that a call's media stream be suspended (with lineSetMediaControl) when a # DTMF digit is detected on the call, and that the media stream be resumed when a * DTMF digit is detected. Note that some implementations or configurations will be unable to provide any media-control functions or media access to the phone or line. Providing media control is optional to the service provider; it should provide performance benefits primarily for client-server implementations. Since it is optional and since only limited control is provided, its usage is generally discouraged. If possible, applications should use the media stream's control functions instead.


 Application Notifications

The programming model for Windows Telephony matches the standard programming model for the Windows environment with regard to device naming, the use of sections and entries in the TELEPHON.INI file, and function calling conventions. But it deviates from this model in one important way—the synchronous/asynchronous operational model, which is a callback scheme through which applications are notified of the success or failure of function calls and other events.


 Function Callbacks

The mechanism used by TAPI to notify applications of events is based on function callbacks, and TAPI defines the parameter profile for these callbacks. When an event occurs, the application's callback function is invoked from within the application's thread (at the time the application calls the GetMessage function), providing a normal, fully functional execution environment in which all Windows APIs can be safely invoked.

The reply callback made to the application carries the request ID and an error indication. Valid error indications for this reply are identical to those that are returned synchronously for the associated request, or zero for success. Only the application that issued the request will receive the reply callback, but when the request causes changes in the state of the device or call, other interested applications may also receive event-related messages.

TAPI guarantees that a reply callback is made for every request that operates asynchronously, and it defines which functions are notified synchronously and which are notified asynchronously. (See the section "Introduction: Synchronous/Asynchronous Operation" later in this chapter.)


 Information Returned by Functions

An application receives two kinds of information as a result of a function call: the function's return value, and values written to data locations specified by the function's arguments.

If the function's return value is zero, the application knows that the function has completed synchronously. In this case, any values written as a result of the function call are reliable and can be used immediately. However, if the return value is positive, the function has not yet completed but it will complete asynchronously, at which time TAPI notifies the application by sending it an asynchronous reply message (or reply callback) for the function. Once the application receives this message (and the message indicates success), any values returned by the function are considered to be reliable. However, before the message is received, the application should consider these values suspect and should not use them. Also, because asynchronous reply messages can take varying lengths of time to be sent, the application may not receive them in the same order in which it called their functions. This is why an application must retain the request IDs of its requests in progress so that it can identify and correctly respond to incoming asynchronous reply messages.


 Example Illustrating the Programming Model

Consider a Windows-based application that can make either voice or data (modem) calls. Although these calls could be made simultaneously if a telephone line were in place for each device (the telephone and the modem), assume that there is only one line, so calls are placed one at a time.

For this discussion, a line is defined as a physical telephone line leading from the wall to the telephone company's switch, and a line device (such as a fax or modem) is a local device on the telephone line. Also, this example is restricted to POTS; the telephone line is a standard, two-wire twisted-pair cable that carries an analog signal and constitutes a single channel.

The line devices attached to the computer are visible to the application as instances of the line device class, which is defined by TAPI. The physical telephone is visible to the application as an instance of the phone device class. This application therefore must be able to execute two types of calls: voice and data. One strength of the TAPI programming model is the way its abstraction into classes exploits the similarities between these different types of calls.

For a more in-depth discussion of this process and related ones, see Chapter 6, "TAPI Applications."


 Determining the Call Type (Media Mode)

Before an application uses any telephony services, it needs to interact with the user to know what kind of call to make. To do this, the standard Win32 API functions are used to build the menus or dialogs needed to gather the user input that tells your application what to do. In this example, the user specifies the transmission of data, so the application will make a call that transmits a specified file to another user.


 Initializing TAPI

Before placing a call, an application must establish a means of communication between itself and TAPI. This process consists of telling TAPI the address of a chosen callback function within the application. This is the function that is notified by TAPI when relevant external events occur. The application passes the pointer to its callback function to TAPI with the lineInitialize function. One of the values lineInitialize returns is the number of line devices available to the application. In this example, that number is one, and the line's ID in Telephony's zero-based scheme is 0. The application must establish this communication link (with lineInitialize) regardless of the type of call to be placed or received.


 Obtaining a Line

Next, the application needs to obtain a handle to a capable telephone line. The application opens the line with lineOpen, but before doing this, it must make sure that the line can support the desired type of call. Invoking the lineGetDevCaps function returns that information to the application in a data structure of type LINEDEVCAPS. If data calls were not supported, this fact could be reported to the user in a dialog box. The application does not need to use lineGetDevCaps before every call, because a line's capabilities should remain static. If the local telephonic configuration (as expressed in .INI files) changes, TAPI notifies applications, which can then call lineGetDevCaps to see what has changed.

One of the values returned by lineGetDevCaps (as a field in the LINEDEVCAPS structure) is the number of addresses assigned to the specified line device. In this example, a single device has a single address.

Ownership of a call is a type of privilege. Applications obtain owner or monitor privilege to new incoming calls by specifying the desired privilege as a parameter of lineOpen. The privilege with which a line is opened remains in effect for subsequent calls used by that application on that line. An application always has owner privileges on calls it creates. When the application opens a line to place calls (as opposed to taking inbound calls) it invokes lineOpen with the privilege LINECALLPRIVILEGE_NONE, which insulates the application from incoming calls while allowing outgoing calls. The other privileges used with the lineOpen function are only for incoming calls.


 Placing the Call

Once the application has opened the line device, it places the call with lineMakeCall, specifying the address (phone number and area code) in the lpszDestAddress parameter and the media mode (datamodem, in this case) in the lpCallParams parameter. This function returns a positive "request ID" if the function will be completed asynchronously, or a negative error number if an error has occurred. Negative return values describe specific error states. LINEERR_CALLUNAVAIL, for example, means that the line is probably in use (someone else already has an active call). If dialing completes successfully, callbacks are made to the application to inform it about the call's progress. Applications typically use these messages to display status reports to the user.

Later, when the lineMakeCall function has successfully set up the call, the application receives a LINE_REPLY message (the asynchronous reply to lineMakeCall). At this point there is not necessarily a connection to the remote station, just an established call at the local end—perhaps indicated by a dialtone. This LINE_REPLY message informs the application that the call handle returned by lineMakeCall is valid.

TAPI's programming model treats data calls similarly to voice calls, as shown by the fact that the same function is used to make calls of both types. If LINEBEARERMODE_DATA is specified in a field of the lpCallParams parameter of lineMakeCall, the call is set up to send data. Speech transmission can be chosen by using a different value. And if NULL is specified, a default 3.1 kHz voice call is established, which can support the speech, fax, and modem media modes.

Note  TAPI should not be used for fax transmissions. Instead, use the functions available through MAPI, the Microsoft Messaging API.

As the call is placed, it passes through a number of states, each of which results in a LINE_CALLSTATE message sent to the application. These states include dialtone, dialing, ringback, and, if connection succeeds, LINECALLSTATE_CONNECTED. (To see the complete list of call states, refer to the LINECALLSTATE structure in Chapter 12, "Line Device Structures.") After the message indicating the connected state is received, the application can begin sending data.


 Sending Data

If the line is available (not busy) and the connection is established, the data can be sent. The application accomplishes this by giving control back to the user, who, using a dialog box, specifies the file to send and initiates data transmission. Though TAPI functions continue to manage the opened line and the call in progress, actual transmission is started and controlled by non-TAPI functions. In this case, for example, the Comm API of the Win32 SDK could be used to control the media stream.

If the application were setting up a speech call, its actions would be similar. Once the call is established, the duty of data transmission is transferred outside of TAPI to the people who wish to speak, although the line and call continue to be monitored by the application using TAPI functions.


 Ending the Call

When the modem transmission is finished, the application receives a LINE_CALLSTATE message, which informs it that the state of a line device has changed. In this example, a remote disconnect has occurred. The application disconnects the call at the local end (it "goes on-hook") with lineDrop. Alternatively, the application itself may choose to end the call by invoking lineDrop before receiving the remote-disconnect message.

Here are the steps that might be used to end a call, close the line, and leave TAPI:

1.	The application calls lineDrop, which places the call in the IDLE state. The call still exists, and the application still has its handle. Now the application can examine the call-information record, if desired.

2.	The application calls lineDeallocateCall to release the call handle for the finished call. The call no longer exists.

3.	If the application expects no more calls on the line, it uses lineClose to close the line. At this point, there will be no more incoming or outgoing calls on that line.

4.	The application invokes lineShutdown to end the use of TAPI's functions for the current session.


 Synchronous/Asynchronous Operation

The interactive nature of telephony requires that TAPI be a real-time operating environment. Many of TAPI's functions are required to complete quickly and return their results to the application synchronously. Other functions (such as dialing) may not be able to complete as quickly and therefore operate asynchronously. Any given operation always completes either synchronously or asynchronously, and both types of operation are explained below. A list of all TAPI functions, which states whether each one completes synchronously or asynchronously, appears in Appendix A, "Quick Function Reference."


 Synchronous Functions

An operation that completes synchronously performs all of its processing in the function call made by the application. The function returns different values depending on its success or failure:

•	Synchronous Success.  If the request or service corresponding to the function has been carried out successfully, the function returns zero, indicating success. Any values written as a result of the function call are reliable and can be used immediately.

•	Synchronous Failure.  If the function detects an error and the request is not carried out, a negative error number is returned to identifies the error.


 Asynchronous Functions

An operation that completes asynchronously performs part of its processing in the function call made by the application and the remainder of it in an independent execution thread after the application has returned from the function call. To ensure completion of the call's processing, the service provider vectors the request to another active entity in the system—such as a LAN server, add-in hardware, a switch, or a network—and then returns to the application. At this time, either a negative error result or a positive request ID is returned to the application.

At the time of asynchronous completion (the service provider has received an interrupt from the hardware, meaning that a message must be delivered), the service provider calls TAPI.DLL through a callback function and reports that "Event X has just taken place. Deliver an appropriate message to all concerned applications." To minimize the processing done during interrupt context, TAPI.DLL posts a message to TAPIEXE.EXE. When TAPIEXE.EXE receives this message, it calls TAPI.DLL, which in turn posts a Windows message. When the application that requested the asynchronous operation receives this message from Windows, a special message-class function in TAPI.DLL is invoked, which calls the line or phone callback function registered by the application. Through this mechanism, the application's callback function is invoked from within the application's own context (thread of control).

When the asynchronous portion of the operation completes, a LINE_REPLY (or PHONE_REPLY) callback message is sent to the application. This callback message contains, as one of its parameters, the request ID returned by the function call. This request ID allows the application to determine which original request has completed. (Applications should remember the request IDs of all their requests in progress so that reply messages can be properly handled.) A second parameter to the LINE_REPLY (or PHONE_REPLY) message is the asynchronous return value. This is either a negative value (for an error) or 0 if the operation completed successfully. For asynchronous operations, any of the return values may be returned as part of the function return or as the dwParam2 parameter in the _REPLY message. The value 0, which indicates success, will only be returned in the LINE_REPLY message, and never as the function's return value.

The initialize functions (lineInitialize and phoneInitialize) tell TAPI where to send these messages, or reply callbacks, to the application. This mechanism is explained in Chapter 6, "TAPI Applications."


 The Meaning of SUCCESS

When an operation returns a SUCCESS indication (either synchronously upon function return for synchronous operations, or asynchronously through a LINE_REPLY or PHONE_REPLY message for asynchronous operations), the following is assumed to be true:

•	The function has successfully progressed to a point that is defined by the API on a function-by-function basis. After that point has been reached, either the operation is completely done, or it will be in a state such that independent state messages will inform the application about subsequent progress.

For example, a service provider's implementation of lineMakeCall should return SUCCESS no later than when the call enters the proceeding call state. Ideally, the provider should indicate SUCCESS as soon as possible, such as when the call enters the dialtone call state (if applicable). Once SUCCESS has been returned to the application, LINE_CALLSTATE messages will inform the application about the progress of the call. Service providers that delay returning the lineMakeCall SUCCESS indication, say, until after dialing is complete, must be aware that this places that provider at a disadvantage because the usability at the application level may be severely limited. For example, it would not be possible for a user to cancel the call setup request in progress until after dialing is complete and all digits had been sent to the switch.

•	Functions that return information (such as lineGetCallInfo) return SUCCESS only when the requested information is available to the application. Functions that return handles (to lines or calls), can return SUCCESS only after the handle is valid. No callback messages should be sent about that line or call prior to the SUCCESS indication of the function that caused its creation. The service provider is responsible for suppressing such messages.

•	Functions that enable certain permanent conditions (such as lineMonitorDigits) return SUCCESS only after the condition is enabled, not when the condition is removed again (for example, not when all digit monitoring has completed).

•	Call-control functions (such as lineHold or lineSetupTransfer, but not lineMakeCall) return SUCCESS when the operation is completed. Some telephone networks do not provide acknowledgment (positive or negative) about the completion of certain requests made by service providers. In such situations, the service provider must decide upon success or failure of the request. Therefore, SUCCESS may indicate that the service provider has initiated actions to fulfill the request, but not necessarily anything more. For example, the provider may receive no affirmative acknowledgment to its request from the switch, although it has already sent a success message to the application.


 Request Recipient Services

Two kinds of applications are needed to run Assisted Telephony. Assisted Telephony Clients are applications that use Assisted Telephony by calling the functions that have the prefix "tapi." An example of such a client application would be a spreadsheet to which a Dial... menu command or toolbar button is added. For more information about the uses and functions of Assisted Telephony, see Chapter 4, "Assisted Telephony."

Assisted Telephony Servers are applications that can execute Telephony API functions that result from another application's call to a "tapi"-prefixed function. To make itself known as an Assisted Telephony server, such an application registers as one using the function lineRegisterRequestRecipient.

The functions of Assisted Telephony (which begin with the prefix tapi) are known as request functions. Assisted Telephony applications that process these requests—Assisted Telephony servers—are called request recipients.


 Assisted Telephony Requests

Applications that use Assisted Telephony services only initiate requests that are temporarily queued by TAPI.DLL. It is the request recipient application that retrieves these requests and executes them on behalf of the Assisted Telephony application. The tapiRequestMakeCall function requests the establishment of a voice call. The requesting application does not control the call.

TAPI allows the user to establish different or the same request recipient applications for each of these services. An application becomes a request recipient by registering with lineRegisterRequestRecipient, which can also be used to deregister the application for the specified services. The application selects which services it wants to handle in the dwRequestMode parameter of lineRegisterRequestRecipient. If multiple applications register for the same services, a priority scheme is used to allow the user to select which application is preferred for handling requests. This priority scheme is identical to that used for call hand-off and the routing of incoming calls based on a list of filenames in the [HandoffPriorities] section of the TELEPHON.INI file.


 Processing Assisted Telephony Requests

The process with which requests are delivered and serviced is as follows:

1.	When TAPI.DLL receives an Assisted Telephony request, it checks for a request recipient, that is, an application currently registered to process that type of request. If so, the request is queued, and the highest-priority application that has registered for that request's service is sent a LINE_REQUEST message. The message notifies the request recipient that a new request has arrived, and it carries an indication of the request's mode.

2.	If TAPI.DLL cannot find a currently running application to process such a request, it tries to launch an application that has been registered as capable of doing so. This registration information is recorded in the [HandoffPriorities] section of the TELEPHON.INI configuration file. TAPI.DLL tries to launch applications in the order in which they are listed in the [HandoffPriorities] section. (See the following step.)

If no application is currently registered, TAPI.DLL examines the list of request-processing applications on the associated entry in the [HandoffPriorities] section of TELEPHON.INI. If the associated line is missing from the file, if there are no applications listed on it, or if none of the applications in the list can be launched, the request is rejected with the error TAPIERR_NOREQUESTRECIPIENT.

When a request recipient is launched (whether or not it has been launched by TAPI.DLL) it is its duty to call lineRegisterRequestRecipient during the startup process and register itself as a request recipient.

3.	If one or more applications are listed in the entry, TAPI begins with the first listed application (highest priority), and attempts to launch it using the LoadModule or WinExec function. If the attempt to launch the application fails, TAPI.DLL attempts to launch the next application in the list. When any application launches successfully, TAPI.DLL simply queues the request and returns a success indication to the application even though the request hasn't yet been signaled to the request recipient.

Once the request recipient application is launched, it calls lineRegisterRequestRecipient, which causes a LINE_REQUEST message to be sent, signalling that the request is queued. If for some reason the launched application never registers, the request remains queued and remains in the queue indefinitely until an application registers for that type of request.

4.	If TAPI.DLL finds such a registered application already running or successfully launches one, it queues the request, sending a LINE_REQUEST message to the server application, and returns a success indication for the function call to the Assisted Telephony application. This success message states only that the request has been accepted and queued, not that it has been successfully executed.

5.	When the server application is ready to process a request, it calls the function lineGetRequest. This lets it receive any information it needs, such as an address to dial. It then processes the request, using the Telephony API functions (such as lineMakeCall and lineDrop) that would otherwise be used to place the call. Invoking lineGetRequest removes the request from TAPI.DLL, and the request parameters are copied in an application-allocated request buffer. The size and interpretation of the contents of the buffer depend on the request mode.

6.	If TAPI.DLL cannot launch an application capable of serving as a request recipient, the Assisted Telephony call fails and returns the error TAPIERR_NOREQUESTRECIPIENT.


 Notes on Request Recipient Operations

The following information concerns systems on which Assisted Telephony requests are processed:

•	The default TELEPHON.INI file should list a call manager application in the priority list for tapiRequestMakeCall. It would be helpful, but not essential, for the call manager application to have a menu option that allows users to set it to the highest priority.

•	When an Assisted Telephony recipient application is launched automatically by TAPI.DLL and if it is the only TAPI application in the system, this action initializes TAPI.DLL. If the Assisted Telephony recipient application initializes and shuts down the line device before registering for Assisted Telephony requests, TAPI is shut down as well, and the Assisted Telephony request is lost. Assisted Telephony requests might also be lost when another TAPI application that is launched performs an initialize and shutdown.


 Passthrough Mode

Windows 95 defines a new LINEBEARERMODE_PASSTHROUGH value (0x00000040). When a call is active in LINEBEARERMODE_PASSTHROUGH, the service provider gives direct access to the attached hardware for control by the application. This mode is for use by applications desiring temporary direct control over asynchronous modems, accessed via the Win32 comm functions, for the purpose of configuring or using special features not otherwise supported by the service provider, such as facsimile (Class 1, 2, etc.). This bearer mode is supported by the Universal Modem Driver (UNIMODEM) service provider included with Windows 95.

Service providers that support LINEBEARERMODE_PASSTHROUGH indicate it in the dwBearerModes field of the LINEDEVCAPS structure. When LINEBEARERMODE_PASSTHROUGH is indicated, the Unimodem service provider will also include in the DevSpecific area of the LINEDEVCAPS structure the registry key used to access information about the modem associated with the line device, in the following format:

struct {
    DWORD dwContents;   // Set to 1 (indicates containing key)
    DWORD dwKeyOffset;  // Offset to key from start of this
                        // structure (not from start of
                        // LINEDEVCAPS structure). 8 in
                        // our case.
    BYTE rgby[...];     // place containing null-terminated
                        // registry key.
}

For example:

    00000001 00000008 74737953 435c6d65  ........System\C
    65727275 6f43746e 6f72746e 7465536c  urrentControlSet
    7265535c 65636976 6c435c73 5c737361  urrentControlSet
    65646f4d 30305c6d xx003030 xxxxxxxx  Modem\0000.

This registry key could then be opened using this function:

RegOpenKey(HKEY_LOCAL_MACHINE, pszDevSpecificRegKey, &phkResult)

Passthrough mode is invoked most often using the lineMakeCall function, by setting the LINEBEARERMODE_PASSTHROUGH bit in the dwBearerMode field of the LINECALLPARAMS structure pointed to by the lpCallParams parameter. When this is done, the service provider will open the serial port to the modem and immediately place the call into LINECALLSTATE_CONNECTED. The application can then use the lineGetID function with the device class "comm/datamodem" to obtain an open Win32 file handle to read from and write to the comm port.

Passthrough mode can be invoked in response to an incoming call as well. Generally, applications will invoke passthrough mode while the call is in LINECALLSTATE_OFFERING, before the call has been answered. Instead of calling lineAnswer, the applications calls lineSetCallParams, passing LINEBEARERMODE_PASSTHROUGH as the dwBearerMode parameter. When this is done, as with lineMakeCall, the call will immediately be placed into LINECALLSTATE_CONNECTED by the service provider, and the application can obtain a handle to the open port using lineGetID. lineSetCallParams may be called when the call is in LINECALLSTATE_OFFERING, LINECALLSTATE_ACCEPTED, or LINECALLSTATE_CONNECTED.

Passthrough mode is normally terminated by calling lineDrop on the call handle obtained from lineMakeCall or the first LINE_CALLSTATE message (if the call was an incoming call). The service provider will close the port, and restore the modem to its default state. The application must call CloseHandle on the handle it received from lineGetID.

Passthrough mode can also be terminated by calling lineSetCallParams with the dwBearerMode parameter set to LINEBEARERMODE_VOICE. The media mode set by lineSetMediaMode is presumed to be in effect. If LINEMEDIAMODE_DATAMODEM is active, the service provider will take over the call as though it was a datamodem call already in progress; if lineDrop is subsequently called, the service provider will issue the appropriate modem commands or interface state changes to drop a data call.


 Assisted Telephony

About Assisted Telephony

Assisted telephony provides very basic telephony functionality to primarily non-telephonic applications. If your application needs extensive telephonic control or is meant to handle incoming calls, skip this chapter.


 Call Requests

Assisted Telephony provides telephony-enabled applications with an easy-to-use mechanism for making phone calls without requiring the developer to become fully telephony literate.

The tapiRequestMakeCall function requests a voice call between the user and a remote party specified by its phone number. The request is made to TAPI, which passes it to an application that is registered as a recipient of such requests. This recipient is a call-manager application.

After the application has made the request, the call is controlled entirely from the call-manager application because Assisted Telephony applications cannot manage calls. Since the more complex aspects of telephony and all user-interface operations are handled by the call-manager application, telephony-enabled applications need not be modified in any substantial way. In fact, applications that allow this operation to be invoked from their built-in script language may not need to be modified at all.

The tapiGetLocationInfo function returns to the application the country code and city (area) code which the user has set in the current location parameters in the Telephony control panel. The application may use this information to assist the user in forming proper canonical telephone numbers, such as by offering these as defaults when new numbers are entered in a phone book entry or database record.

The Assisted Telephony server application is also known as a request recipient. For more information about request recipients, see Chapter 2, "The Telephony Programming Model."


 Using Assisted Telephony

You might use assisted telephony to in a word-processing application. Consider a word-processing application that has a button with a caption of "George." When the user selects a telephone number in a document and clicks this button, the application sends a request (tapiRequestMakeCall) to the call-control application, which dials the number and notifies the user of the call's status.


 Reference

Following is a list of the functions, messages, and data types used by Assisted Telephony.


 Functions

 The following functions are used by Assisted Telephony.


 tapiRequestMakeCall

[New - Windows 95]

LONG tapiRequestMakeCall(LPCSTR lpszDestAddress, LPCSTR lpszAppName,
    LPCSTR lpszCalledParty, LPCSTR lpszComment);

Requests the establishment of a voice call. A call-manager application is responsible for establishing the call on behalf of the requesting application, which is then controlled by the user's call-manager application.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible error return value are:

TAPIERR_NOREQUESTRECIPIENT	TAPIERR_INVALDESTADDRESS
TAPIERR_REQUESTQUEUEFULL	TAPIERR_INVALPOINTER
lpszDestAddress

Specifies a pointer to a memory location where the NULL-terminated destination address of the call request is located. The address can use the canonical address format (address formats are discussed in Chapter 5, "Concepts of Line Devices") or the dialable address format. Validity of the specified address is not checked by this operation. The maximum length of the address is TAPIMAXDESTADDRESSSIZE characters, which includes the NULL terminator.

lpszAppName

Specifies a pointer to a memory location where the ASCII NULL-terminated user-friendly application name of the call request is located. This pointer may be left NULL if the application does not wish to supply an application name. The maximum length of the address is TAPIMAXAPPNAMESIZE characters, which includes the NULL terminator. Longer strings are truncated.

lpszCalledParty

Specifies a pointer to a memory location where the ASCII NULL-terminated called party name for the called party of the call is located. This pointer may be left NULL if the application does not wish to supply this information. The maximum length of the string is TAPIMAXCALLEDPARTYSIZE characters, which includes the NULL terminator. Longer strings are truncated.

lpszComment

Specifies a pointer to a memory location where the ASCII NULL-terminated comment about the call is located. This pointer may be left NULL if the application does not wish to supply a comment. The maximum length of the address is TAPIMAXCOMMENTSIZE characters, which includes the NULL terminator. Longer strings are truncated.

A telephony-enabled application can request that a call be placed on its behalf by invoking tapiRequestMakeCall, providing only the destination address for the call. This request is forwarded to the user's call-control application, which places the call on behalf of the original application. A default call-control application is provided as part of Windows Telephony. Users can replace this with a call-control application of their choice.

Invoking tapiRequestMakeCall when no call control application is running returns the TAPIERR_NOREQUESTRECIPIENT error indication. If the call control application is not running, TAPI.DLL will attempt to launch the highest-priority call control application (which is listed for RequestMakeCall in TELEPHON.INI). Invoking this function when the Assisted TAPI request queue is full returns the TAPIERR_REQUESTQUEUEFULL error.


 tapiRequestMediaCall

The tapiRequestMediaCall function is nonfunctional in Win32 -based applications and obsolete for all classes of Windows-based applications. It should not be used.


 tapiGetLocationInfo

[New - Windows 95]

LONG tapiGetLocationInfo(LPCSTR lpszCountryCode, LPCSTR lpszCityCode);

Returns the country code and city (area) code which the user has set in the current location parameters in the Telephony control panel. The application may use this information to assist the user in forming proper canonical telephone numbers, such as by offering these as defaults when new numbers are entered in a phone book entry or database record.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are TAPIERR_REQUESTFAILED.

lpszCountryCode

Specifies a pointer to a memory location where a NULL-terminated ASCII string specifying the country code for the current location is to be returned. The application should allocate at least 8 bytes of storage at this location to hold the string (TAPI.DLL will not return more than 8 bytes, including the terminating NULL). An empty string (\0) will be returned if the country code has not been set for the current location.

lpszCityCode

Specifies a pointer to a memory location where a NULL-terminated ASCII string specifying the city (area) code for the current location is to be returned. The application should allocate at least 8 bytes of storage at this location to hold the string (TAPI.DLL will not return more than 8 bytes, including the terminating NULL). An empty string (\0) will be returned if the city code has not been set for the current location.


 tapiRequestDrop

The tapiRequestDrop function is nonfunctional in Win32 -based applications and obsolete for all classes of Windows-based applications. It should not be used.


 Messages

The following messages are used by Assisted Telephony.


 TAPI_REPLY

The TAPI_REPLY message is nonfunctional in Win32 -based applications and obsolete for all classes of Windows-based applications. It should not be used.


 Constants

The following constants are used by Assisted Telephony.


 TAPI Error Values

TAPIERR_INVALDESTADDRESS	The pointer to the destination address is not valid, is NULL, or the destination address string is too long.
TAPIERR_INVALPOINTER	The pointer does not reference a valid memory location. One or more of the pointers lpszDestAddress, lpszAppName, lpszCalledParty, or lpszComment have been specified but are invalid.
TAPIERR_NOREQUESTRECIPIENT	No recipient application is available to handle the request. The user should start the recipient application and try again.
TAPIERR_REQUESTFAILED	The request failed for unspecified reasons.
TAPIERR_REQUESTQUEUEFULL	A recipient application is active, but the request queue is full or there is insufficient memory to expand the queue. The application can try again later.
Any other TAPIERR_ values are nonfunctional in Win32-based applications and must not be used.


 Line Devices

About Line Devices

A line device is a physical device such as a fax board, a modem, or an ISDN card that is connected to an actual telephone line. Line devices support telephonic capabilities by allowing applications to send or receive information to or from a telephone network. A line device is the logical representation of a physical line device, one of the two device classes supported by TAPI. This chapter describes line devices and explains how to use the line functions that access these devices.


 What is a Line Device?

A line device is a physical device such as a fax board, a modem, or an ISDN card that is connected to an actual telephone line (although the device may not be physically connected to the computer on which the telephony application is running). Line devices support telephonic capabilities by allowing applications to send or receive information to or from a telephone network. A line device contains a set of one or more homogeneous channels that can be used to establish calls.

Within TAPI applications, a line device is the logical representation of a physical line device. Although "line" often connotes something with two endpoints, it is possible to abstract a line device to a single point because TAPI views it only as a point of entry to the line that leads to the switch.

Although the three lines in the preceding illustration are composed of different hardware and used for different functions, they are abstracted to the same device type and governed by the same rules. Note that the telephone represents not a phone device but a line device used for voice calls. When using this line device for incoming or outgoing calls, the application would also need to open and control an instance of the phone-device class, which is described in detail in later chapters.

TAPI requires that every TAPI-capable line device support all of Basic Telephony. If an application needs to use capabilities beyond those of Basic Telephony (namely Supplementary or Extended Telephony), it must first determine the line device's capabilities, which can vary according to network configuration (client versus client-server), hardware, service-provider software, and the telephone network.  The lineNegotiateAPIVersion function allows the application to identify the set of Extended capabilities supported on a line device, and the lineNegotiateExtVersion function allows for different versions of that set to be used. The function lineGetDevCaps returns the telephonic capabilities implemented through the use of the Supplementary and Extended (if any) TAPI functions of a given line device in a data structure of the type LINEDEVCAPS.


 Lines, Channels, and Addresses

In POTS, exactly one channel exists on a line, and this is used exclusively for voice. With ISDN, at least three (and as many as 30 or more) channels can exist on a line simultaneously. Currently, most TAPI functionality involves POTS applications that handle a single line using its single channel because ISDN hardware is not yet widespread. In POTS, an application that wants to transmit data would communicate over one line, and a voice application would communicate over another line—both of these applications could use the same line, but if so, not at the same time.

In general, one line has exactly one address (telephone number). In cases where lines carry two or more channels, each channel may have its own address, which means that a line has as many addresses as it has channels. TAPI assigns Address IDs to these different addresses to make it easier to manipulate them.


 Multiple Addresses on a Single Channel

Some installations support the assignment of more than one address to a single channel. On POTS lines, multiple addresses are made possible by various systems, such as "DID" (direct inward dialing) or "distinctive ringing," which are extra-fee services provided by the telephone company.

Many large corporations use DID for incoming calls. Before a call is connected, its destination extension number is signaled to the PBX, which causes the extension to ring instead of the operator's phone. An example of distinctive ringing in a private home would be if the parents used one address, the children another, and a fax machine a third. Because only one line connects the house to the telephone network, all phones ring when a call appears, but the ring pattern will be different depending on the number dialed by the calling party. With distinctive ringing, the people know who the incoming call is meant for, and the fax machine answers its calls by recognizing its own ringing style.

In ISDN, the various B channels might not have separate addresses. Because these B channels might be on the same address, it is the service provider (and not the application or a person who has dialed the number) that assigns calls to these channels.


 ISDN Subaddresses

Subaddressing is a capability provided on ISDN lines that allows more information than just a single telephone number to be used when dialing. This additional information may specify an individual telephone extension to ring or, in a computing environment, a particular application to be alerted. Other parameters that can be passed can describe the required aspects of a requested modem connection, such as rate and timing.


 Addresses and Address Identifiers

Each line device is assigned one or more addresses. An address corresponds to a telephone directory number, and it is actually assigned twice: First, by the telephone company at the switch, and second, by the user while configuring the local system. If a telephone number is changed at the switch, the user will normally need to assign the new number at the local system, although some systems may be sophisticated enough to perform the reassignment without human control.

After addresses have been assigned to lines, TAPI assigns address IDs to addresses. An address ID is a number between 0 and the number of addresses on the line minus one. Because each address depends on its line to exist, the address's ID is meaningful only in the context of the associated line device. For this reason, an address name consists of not only the address ID, but also an identifier of the line. It serves as a kind of shorthand, an easy way for programmers to identify addresses.


 Address Configurations

The relationship of an address to a line (and to other local addresses) is known as its configuration. The network or switch can configure address-to-line assignments in several ways. The main types of address configurations recognized by TAPI are:

1.	Private. The address is assigned to one line device only. An inbound call for this address is offered (the switch informs the desktop computer of an incoming call) at one line device only.

2.	Bridged. A bridged address is a single address assigned to more than one line device. (Different switch vendors have different names for address bridging, such as "multiple appearance directory number" (MADN), "bridged appearance," or "shared appearance.") An incoming call on a bridged address will be offered on all lines associated with the address. The network of lines connected together is known as the "bridge." Different variations of bridged behavior are possible:

•	Bridged-Exclusive. Connecting one of the bridged lines to a remote party causes the address to appear "in use" to all other members of the bridge.

•	Bridged-New. Connecting one of the bridged lines to a remote party does not preclude the other lines from using the bridged address to answer or make calls. However, a new call appearance is allocated to another of the connected lines.

•	Bridged-Shared. If one line is connected to a remote party, other bridged lines that use the address automatically enter into a multi-party conference call on the existing call.

3.	Monitored. The line indicates the busy or idle status of the address, but the line cannot use the address for answering or making calls.


 Address-Related Functions and Messages

Different line devices may have different capabilities and so may their addresses. Additionally, switching features and capabilities may be different for different addresses. An application calls the function lineGetAddressCaps to determine the telephony capabilities of each address and then receives this information in a data structure of the type LINEADDRESSCAPS. In a similar way, an application can call LineGetDevCaps for a line device to determine the number of addresses assigned to the line, as well as other information.

TAPI's device-query capability and status and event reporting mechanisms give an application the information it needs to manage the different kinds of bridged-address arrangements. For example, the application can determine whether a bridged station has answered a call by tracking the status changes and call-state event changes on the address. (Call states are explained in Appendix C, "Call States and Events.")

Normally, addresses on a line device are identified by their address IDs. However, TAPI lets applications that make outgoing calls use alternate address types for the originating address, such as dialable format (see the following section), or naming mechanisms specific to a given service provider. This can be accomplished through API extensions that are based on switch-assigned station IDs. A useful function for this purpose is lineGetAddressID, which retrieves the ID of an address specified in an alternate format.


 Address Formats

Each address ID corresponds to a directory number through which incoming calls can be placed to the address. Similarly, making outbound calls typically requires that a directory number—the address—be supplied to identify the party being called.


 Storing Numbers in Electronic Address Books

Many users choose to dial people, fax machines, bulletin boards, and other entities by selecting their names from an address book. The actual number that is dialed depends on the geographic location of the user and the way the line device to be used is connected. For example, a desktop computer may have access to two lines, one connected to a PBX, the other to the telephone company's central office. When making a call to the same party, different numbers may have to be used. (To dial through the PBX, for example, the computer may need to dial '9' to "get out," or a different prefix may be needed for a call made through the central office.) Or, a user may make calls from a portable computer and want to use a single, static address book even when calling from different locations or telephony environments. TAPI's address translation capabilities let the user inform the computer of the current location and the desired line device for the call. TAPI then handles any dialing differences, requiring no changes to the user's address book. An application uses the lineTranslateAddress function to convert an address from the canonical address format to the dialable address format (see the next section).

A related topic is the handling of international call progress monitoring, which is the process of listening for audible tones such as dialtone, special information tones, busy signals, and ringback tones to determine the state of a call (its "progress" through the network). Because the cadences and frequencies of call-progress tones vary from country to country, the service provider must know what call progress to follow when making an international outbound call. Therefore, applications specify the destination country code when placing outgoing calls.


 Canonical Addresses

The canonical address format is intended to be a universally constant directory number. For this reason, numbers in address books are best stored using canonical format. A canonical address is an ASCII string with the following structure:

+ CountryCode Space [(AreaCode) Space] SubscriberNumber | Subaddress ^ Name CRLF ...

The components of this structure are given in the following table:

+	Equivalent to ASCII Hex (2B). It indicates that the number that follows it uses the canonical format.
CountryCode	A variably sized string containing one or more of the digits 0-9. The CountryCode is delimited by the following Space. It identifies the country in which the address is located.
Space	Exactly one ASCII space character (0x20). It is used to delimit the end of the CountryCode part of an address.
AreaCode	A variably sized string containing zero or more of the digits 0-9. AreaCode is the area code part of the address and is optional. If the area code is present, it must be preceded by exactly one ASCII left parenthesis character (0x28), and be followed by exactly one ASCII right parenthesis character (0x29) and one ASCII Space character (0x20).
SubscriberNumber	A variably sized string containing one or more of the digits 0-9. It may include other formatting characters as well, including any of the dialing control characters described in the Dialable Address Format:
	AaBbCcDdPpTtWw*#!,@$?
	The subscriber number should not contain the left parenthesis or right parenthesis character (which are used only to delimit the area code), nor should it contain the "|", "^", or CRLF characters (which are used to begin following fields). Most commonly, non-digit characters in the subscriber number would include only spaces, periods ("."), and dashes ("-"). Any allowable non-digit characters which appear in the subscriber number will be omitted from the DialableString returned by the lineTranslateAddress function, but will be retained in the DisplayableString.
|	ASCII Hex (7C). If this optional character is present, the information following it up to the next + | ^ CRLF, or the end of the canonical address string is treated as subaddress information, as for an ISDN subaddress.
Subaddress	A variably sized string containing a subaddress. The string is delimited by + | ^ CRLF or the end of the address string. During dialing, subaddress information is passed to the remote party. It can be such things as an ISDN subaddress or an email address.
^	ASCII Hex (5E). If this optional character is present, the information following it up to the next CRLF or the end of the canonical address string is treated as an ISDN name.
Name	A variably sized string treated as name information. Name is delimited by CRLF or the end of the canonical address string and may contain other delimiters. During dialing, name information is passed to the remote party.
CRLF	ASCII Hex (0D) followed by ASCII Hex (0A), and is optional. If present, it indicates that another canonical number is following this one. It is used to separate multiple canonical addresses as part of a single address string (inverse multiplexing).
	For example, the canonical representation of the main switchboard telephone number at Microsoft Corporation would be:
	+1 (206) 882-8080


 Dialable Addresses

The dialable address format describes a number that can be dialed on the given line. A dialable address contains part addressing information and is part navigational in nature. Any input string which does not begin with a "+" character is presumed to be not in canonical format and therefore in dialable address format, and is returned to the application unmodified. A dialable address is an ASCII string with the following structure:

DialableNumber | Subaddress ^ Name CRLF ...

where:

DialableNumber	digits and modifiers 0-9 A-D * # , ! W w P p T t @ $ ? ; delimited by | ^ CRLF or the end of the dialable address string. The plus sign (+) is a valid character in dialable strings. It indicates that the phone number is a fully-qualified international number.
	Within the DialableNumber, note the following definitions:
	0-9 A-D * #  ASCII characters corresponding to the DTMF and/or pulse digits.
!	ASCII Hex (21). Indicates that a hookflash (one-half second on hook, followed by one-half second off-hook before continuing) is to be inserted in the dial string.
P p	ASCII Hex (50) or Hex (70). Indicates that pulse dialing is to be used for the digits following it.
T t	ASCII Hex (54) or Hex (74). Indicates that tone (DTMF) dialing is to be used for the digits following it.
,	ASCII Hex (27). Indicates that dialing is to be paused. The duration of a pause is device specific and can be retrieved from the line's device capabilities. Multiple commas can be used to provide longer pauses.
W w	ASCII Hex (57) or Hex (77). An uppercase or lowercase W indicates that dialing should proceed only after a dial tone has been detected.
@	ASCII Hex (40). Indicates that dialing is to "wait for quiet answer" before dialing the remainder of the dialable address. This means to wait for at least one ringback tone followed by several seconds of silence.
$	ASCII Hex (24). It indicates that dialing the billing information is to wait for a "billing signal" (such as a credit card prompt tone).
?	ASCII Hex (3F). It indicates that the user is to be prompted before continuing with dialing. The provider does not actually do the prompting, but the presence of the "?" forces the provider to reject the string as invalid, alerting the application to the need to break it into pieces and prompt the user in-between.
;	ASCII Hex (3B). If placed at the end of a partially specified dialable address string, it indicates that the dialable number information is incomplete and more address information will be provided later. ";" is only allowed in the DialableNumber portion of an address.
|	ASCII Hex (7C), and is optional. If present, the information following it up to the next + | ^ CRLF, or the end of the dialable address string is treated as subaddress information (as for an ISDN subaddress).
Subaddress	A variably sized string containing a subaddress. The string is delimited by the next + | ^ CRLF or the end of the address string. When dialing, subaddress information is passed to the remote party. It can be for an ISDN subaddress, an email address, and so on.
^	ASCII Hex (5E), and is optional. If present, the information following it up to the next CRLF or the end of the dialable address string is treated as an ISDN name.
Name	A variably sized string treated as name information. Name is delimited by CRLF or the end of the dialable address string. When dialing, name information is passed to the remote party.
CRLF	ASCII Hex (0D) followed by ASCII Hex (0A). If present, this optional character indicates that another dialable number is following this one. It is used to separate multiple dialable addresses as part of a single address string (for inverse multiplexing).
The lineTranslateAddress function and related support functions are used to translate an address from canonical format to dialable format. An application might not use this function to dial a number but it might use it to generate and display for verification a number that could be dialed. Also, it can compute the local time at the destination address from the country code and area code.

The application uses lineTranslateAddress to specify both the line device upon which it intends to dial the call and a canonical address, and the function returns the dialable number and the country code. Because the line device may have specific dialing requirements, it is part of the context needed for an accurate translation.

The user's location also plays a role in address translation. Information related to the current location, such as the country code, area code, and outside line access codes is entered by the user through the Telephony applet in the Control Panel. The Subaddress and Name fields, if present in the address, are unmodified by the translation. Alphabetic characters in the number, such as in 1-800-FOR-TAPI, are not translated by the lineTranslateAddress function due to the different standardizations in use in different countries, but they may be translated by applications themselves.

Although an application can use dialable addresses returned by lineTranslateAddress, it is not limited to them and can compose its own dialable numbers.


 Initialization and Shutdown

For an application to use any of TAPI's basic or supplementary line functions, it needs a connection to TAPI.DLL through which it can receive messages. The application establishes this connection, using either the lineInitialize or the phoneInitialize function. One of the parameters passed to TAPI in these function calls is a pointer to the application's callback function. After initialization, TAPI uses this pointer to notify the application of the asynchronous completion of functions and other events occuring on devices which the application has opened. Following are specifics about the initialization process:

•	The initialization functions are not device-related. When an application calls an initialization function, TAPI does not act on a line or phone device or an abstraction thereof.

•	The first time an initialization function is called in a telephony session, TAPI also sets up the telephony environment. Among the tasks it performs are loading TAPI.DLL and TAPIEXE.EXE, and loading the device drivers (Telephony service providers and ancillary components) specified in TELEPHON.INI. In addition, the communication link described above is established between TAPI and the calling application. After environment-related tasks are completed, calling an initialization function only passes a pointer to a callback function.

•	The INIFILECORRUPT error can be returned if TAPI.DLL determines that the TELEPHON.INI contains an invalid entry. When this error occurs (in lineInitialize and phoneInitialize, or another function), the user should identify and resolve the problem. It may be necessary to rebuild the entire INI file or a portion of it, which can be done through the Telephony Control Panel.

For example, the LINEERR_NODRIVER ("the driver was not installed") error indicates either that a service provider that was previously installed can no longer be found or that some subsidiary component of a service provider (such as a VxD) cannot be found. When this error is encountered, the application should advise the user to correct the problem with the Driver Setup function within the Telephony Control Panel.

•	Although each application needs only one callback function, it can call an initialization function more than once to specify other callback functions.

•	The functions lineInitialize and phoneInitialize are the only two callbacks defined in TAPI. This means that they are the only two functions that can pass the pointer of a callback function to TAPI. All subsequent TAPI functions, when completing asynchronously, result in calls to this callback function. (There is one exception: In Assisted Telephony, the functions tapiRequestMediaCall and tapiRequestDrop use Windows messages to return call statuses to the application that is placing the call.)

•	Both lineInitialize and lineShutdown (and the corresponding phone functions) operate synchronously. That is, these functions return a success or failure indication, not an asynchronous Request ID. They cannot finish asynchronously because, at the time they are called, TAPI has no pointer to use for sending messages to the application. Not until they complete is this pointer (to a callback function) available to TAPI.

Upon completion, the lineInitialize function returns two pieces of information to the application: an application handle and the number of available line devices.

•	The application handle represents the application's usage of TAPI. That is, to TAPI, it represents the application. TAPI functions that use line or call handles (explained later in this chapter) do not require the application handle, because this handle is derived from the specified line, phone, or call handle.

•	The lineInitialize function also returns the number of line devices available to the application through TAPI. Line devices are identified by their device identifier (device ID). Valid device IDs range from zero to one less than the number of line devices. For example, if lineInitialize reports that there are two line devices in a system, the valid line-device IDs are 0 and 1.

Once an application is finished calling TAPI's line functions, it calls lineShutdown and passes its application handle to terminate its usage of TAPI. This allows TAPI to free any resources assigned to the application.


 Calls

Unlike line devices and addresses, calls are dynamic. A call represents a connection between two (or more) addresses. The originating address (the caller) is the address from which the call originates, and the destination address (the called) identifies the remote end point or station with which the originator wishes to communicate.

Zero, one, or more calls can exist on a single address at any given time. A familiar example of multiple calls on a single address is call waiting: During a conversation with one party, a subscriber with call waiting is alerted that another party is trying to call. The subscriber can flash the phone to answer the second caller (which automatically places the first party on hold) and then toggle between the two parties by flashing. In this example, the subscriber has two calls on one address on the line. Since the person at the telephone handset can be talking to only one remote party at a time, only one call is active per line at any point in time. The telephone switch keeps the other calls on hold. With a line able to encompass more than one channel, different configurations can allow multiple active calls on a line at the same time.


 Call Handles

TAPI identifies a specific call by means of the call's handle, and TAPI.DLL assigns call handles as required. One call handle exists for every call owned or monitored by an application, and an application can obtain call handles in a number of well defined ways. Certain TAPI functions create new calls. As they do so, they return any new call's handle to the application. Sometimes, call handles are provided unsolicited in callbacks made to the application from TAPI.DLL, as is the case with inbound calls or calls being handed off by other applications.

For every call, one handle exists per application—unique call handles are provided to each application by TAPI. This means that different applications with handles to the same call use different handles for it, which limits the scope of a call handle to a single application. In addition, the service provider may assign a unique call ID to a call (unrelated to the call's handle), which is used to track the call across transfers. Whether or not a service provider can assign call IDs to calls is a device capability.

The privileges of an application for a given call are maintained by TAPI.DLL and are not the property of an application's handle for the call. (For information about call privileges, see Chapter 6, "TAPI Applications.") Resources such as memory are allocated dynamically for each call for each application that is given a handle to the call. These resources are not automatically deallocated when the call is dropped since the application may still find it useful to extract information from the call (such as for logging purposes). Therefore, applications must dispose of their call handle when they have finished using it by calling the lineDeallocateCall function.


 Version Negotiation

Over time, different versions may exist for TAPI.DLL, applications, and service providers for a line or phone. New versions may define new features, new fields to data structures, and so on. Version numbers therefore indicate how to interpret various data structures.

To allow optimal interoperability of different versions of applications, versions of TAPI.DLL itself, and versions of service providers by different vendors, TAPI provides a simple, two-step version negotiation mechanism for applications. Two different versions must be agreed on by the application, TAPI.DLL, and the service provider for each line device. The first is the version number for Basic and Supplementary Telephony and is referred to as the API version. The other is for provider-specific extensions, if any, and is referred to as the extension version. The format of the data structures and data types used by TAPI's basic and supplementary features is defined by the API version, while the extension version determines the format of the data structures defined by the vendor-specific extensions.

Version negotiation proceeds in two phases. In the first phase, the API version number is negotiated and the extension ID associated with any vendor-specific extensions supported on the device is obtained. In the second phase, the extension version is negotiated. If the application does not use any API extensions, it skips the second phase and extensions are not activated by the service provider. If the application does wish to use extensions, but the service provider's extensions (the extension ID) are not recognized by the application, the application should skip the negotiation for extension version as well. Each vendor has its own set of legal (recognized) versions for each set of extension specifications it distributes.

The lineNegotiateAPIVersion function is used to negotiate the API version number to use. It also retrieves the extension ID supported by the line device, returning zeros if no extensions are supported. With this function call, the application provides the API version range it is compatible with. TAPI.DLL in turn negotiates with the line's service provider to determine which API version range it supports. TAPI.DLL next selects a version number (typically, although not necessarily, the highest version number) in the overlapping version range that the application, the DLL, and the service provider have supplied. This number is returned to the application, along with the extension ID that defines the extensions available from that line's service provider.

If the application wishes to use the extensions defined by the returned extension ID, it must first call lineNegotiateExtVersion to negotiate the extension version. In a similar negotiation phase, the application specifies the already-agreed-upon API version and the extension version range it supports. TAPI.DLL passes this information to the service provider for the line. The service provider checks the API version and the extension version range against its own, and selects the appropriate extension version number, if one exists.

When the application later calls lineGetDevCaps, it returns a set of device capabilities for the line that correspond to the results of version negotiation. These include the line's device capabilities consistent with the API version and the line's device-specific capabilities consistent with the extension version. The application must specify both of these version numbers when it opens a line. At that point, the application, the DLL, and the service provider are committed to using the agreed-upon versions. If device-specific extensions are not to be used, the extension version should be specified as zero.

In an environment where multiple applications open the same line device, the first application to open the line device selects the versions for all future applications that wish to use the line (service providers do not support multiple versions simultaneously.) Similarly, an application that opens multiple line devices may find it easier to operate all line devices under the same API version number.


 TAPI Applications

About TAPI Applications

This chapter explains what you need to know to program basic telephonic functionality using the line-device class functions.


 Establishing a Link

Before an application can call the functions of Windows Telephony for using a line device, it must take the following steps:

•	Initialize the TAPI environment and TAPI's functions (enable function callbacks) with an initialization function. Invoking this function also informs the application of the number of line devices available.

•	Negotiate the API version, and if necessary, negotiate the Extensions version.

An application must take the preceding steps for each line device it intends to use. Each line initialization gives TAPI dynamic link library a pointer to callback function within the application that uses the line.

Applications should not invoke phoneInitialize without subsequently opening a phone (at least for monitoring). If the application is not monitoring and not using any devices, it should call phoneShutdown so that memory resources allocated by the TAPI dynamic link library can be released if unneeded, and library itself can be unloaded from memory while not needed.


 Opening Lines

After having obtained the capabilities of a line, an application must open the line device before it can access telephony functions on that line. (Because a line device is an abstraction of a line as defined by Telephony, "opening a line" and "opening a line device" can be used interchangeably.) When a line device has been opened successfully, the application receives a handle for it. The application can then use that line to take inbound calls, make outbound calls, or monitor call activities on the line for logging purposes.

To open a line device for any purpose—monitoring or control—the application calls the function lineOpen. (Later, when the application is finished with the line device, it can close it with lineClose.)

The function lineOpen can be invoked in one of two ways:

•	A specific line device is selected by means of its line-device ID (the parameter dwDeviceID). The lineOpen request will open the specified line device. Applications interested in handling inbound calls typically use specific line devices because the application has been notified which line is carrying or is expected to carry the inbound call. When a line device has been opened successfully, the application is returned a handle representing the open line.

•	The application can specify that it wants to use any line device that has certain properties. In this case, the application uses the value LINEMAPPER instead of a specific line-device ID as a parameter for lineOpen. The application also specifies which properties it needs on the call in parameters to lineOpen. The function opens any available line device that supports the specified call parameters. This attempt, of course, may fail. If successful, the caller can determine the line-device ID by calling lineGetID, specifying the handle (lphLine) to the open line device returned by lineOpen.

An application that has successfully opened a line device can use it to make an outbound call except when the line supports only inbound calls.


 Selecting One or More Lines

An application can open one or more lines for various purposes. For example, it can open one line for monitoring calls and another line for making outgoing calls. If several lines are available, the application can choose to open any or all of them. To decide which of several line devices to use, determine the capabilities of each one with lineGetDevCaps. This tells whether the line supports the functionality needed by the calls to be made or received—such as their required media mode. This function is also used to get the name of the line.

Because opening a line merely means obtaining a handle to the line (hLine) with a given privilege, an application can obtain more than one handle to the same line. In other words, an application can open the same line many times, also called opening different instances of the line. For example, a line may simultaneously be opened once for monitoring calls, a second time for accepting incoming calls as their owner, and a third time for making outgoing calls.

After choosing a suitable line (or lines), the application uses lineOpen, either specifying a certain line or using LINEMAPPER, as explained in the previous section.


 Specifying Media Modes

The ability of an application to deal with inbound calls or to be the target of call handoffs on a line is determined by the value used for the dwMediaModes parameter of the lineOpen function. With this function, the application indicates its interest in monitoring calls or receiving ownership of inbound calls of one or more specific media modes, or of any (unspecified) media mode, as described in the following cases:

•	An inbound call of a certain media mode is given to the application that has opened the line device for that particular media mode. A single application may specify multiple flags simultaneously to handle multiple media modes.

•	An application that wants to handle calls for which the actual media mode present has not yet been determined would turn on the unknown media bit as a parameter of lineOpen.

•	An application that wants to handle calls of any media mode would indicate this capability by turning on all of the media bits that are supported on the line (which can be obtained from LINEDEVCAPS).

All applications that have opened a line device in any mode are notified about certain general statuses and events occurring on the line device or its addresses. These include the line being taken out of service, the line going back into service, the line being under maintenance, an address coming in use or going idle, and an open or close operation being executed on the line. An application that does not care about certain message can use the lineSetStatusMessages function to filter the message. Most such status messages are disabled by default; an application would need to call lineSetStatusMessages to enable them.

The media modes specified with lineOpen add to the default value for the provider's media mode monitoring for initial inbound call type determination. This means that the dwMediaMode settings of all applications with the line open are "or'd" together, and that union becomes the default media detection on the line. The lineMonitorMedia function modifies the mask that controls LINE_MONITORMEDIA messages but does not affect the default media detection enabled on new incoming calls. It is necessary for an application using lineMonitorMedia to call it to establish media monitoring on every new call in which it is interested.


 Requesting Call Privileges

In addition to media mode, an application can specify the call privileges it wants for the calls provided to it. With privileges, an application specifies whether it wants to monitor calls or own them. For an inbound call, only one application is selected as the owner, although all applications with monitor interest in the call are also notified about the incoming call. The usual privileges an application specifies are summarized in the following list:

•	If the application only wants to monitor calls, it specifies LINECALLPRIVILEGE_MONITOR. The application will also receive monitor handles to outgoing calls placed by other applications (an application receives owner handles for outgoing calls it places itself). It will also receive MONITOR handles for calls it places itself on other instances of the same line.

•	If the application wants to make outbound calls only, it specifies LINECALLPRIVILEGE_NONE. An application that has NONE selected will not be automatically informed of incoming calls. However, it can also become aware of calls on the line with LINE_ADDRESSSTATE(numCalls) or LINEDEVSTATE(numCalls) messages. It can then call lineGetNewCalls.

•	If the application wants to accept incoming calls of a specific media mode (or modes), it specifies LINECALLPRIVILEGE_OWNER and one or more relevant LINEMEDIAMODE_ settings.

•	If the application is willing to control unclassified calls (incoming calls of as-yet unknown media mode), it specifies LINECALLPRIVILEGE_OWNER and LINEMEDIAMODE_UNKNOWN.

•	In other cases, the application should specify the media mode it is interested in handling and set dwPrivilege to LINECALLPRIVILEGE_OWNER.

An application that wants to be informed of all calls on the line regardless of whether it can become an owner on the call can set both the LINECALLPRIVILEGE_OWNER and LINECALLPRIVILEGE_MONITOR bits. It will get call handles with owner privileges for incoming calls for which it is the highest priority application for the highest priority media mode on the call, and monitor privileges for all other incoming and outgoing calls.

An application that has successfully opened a line device can always initiate calls using lineMakeCall, lineUnpark, linePickup, lineSetupConference (with a NULL hCall parameter), as well as use lineForward (assuming that doing so is allowed by the device capabilities, line state, and so on).


 Application Priority

Conflicts can arise if multiple applications open the same line device for the same media mode. These conflicts are resolved with a priority scheme by which the user assigns relative priorities to the applications. This is usually done through a Control Panel applet or a Preferences menu in a telephonic application. Note the following points about this mechanism:

•	Only the highest priority application for a given media mode ever receives ownership (unsolicited) of a call of that media mode.

•	Although ownership is usually received when an inbound call first arrives or when a call is handed off, any application (including a lower priority one) can later acquire ownership by using the function lineGetNewCalls or lineGetConfRelatedCalls.

The user can assign relative priorities to the modules (the applications and the DLLs) that use TAPI. The resulting configuration information is stored in a standard format in the TELEPHON.INI file. For more information about using TELEPHON.INI, see Appendix B, "Telephony Configuration Parameters."

For in-depth information about the way applications receive calls in a multi-application environment, see Chapter 8, "Multiple-Application Programming."


 Using lineOpen

An application can open a number of lines as well as negotiating API and extension versions. The application can call the lineOpen function with LINECALLPRIVILEGE_MONITOR privilege, meaning that it will only monitor, not own, incoming calls on all the lines opened.

An application could open a line with the intent of owning incoming calls by specifying LINECALLPRIVILEGE_OWNER as the privilege and a media mode other than NONE. The application could actually specify a number of media modes in this parameter by "or-ing" the bit flags for each of the desired media modes. In that case, the application would be notified of incoming calls in any of the specified media modes, and it receives those calls as their owner. (Actually, another application that is also registered to receive calls of that media mode would receive the call instead, if it has a higher priority as designated in the TELEPHON.INI file.) This notification arrives in a call-state message that specifies, among other information, which line is carrying the incoming call. For example, by specifying LINEMEDIAMODE_INTERACTIVEVOICE, the application would be notified of incoming calls of the interactive voice media type (voice calls with a person on the local end of the line).


 Preparing to Accept Assisted Telephony Requests

An application to be used as a recipient of Assisted Telephony requests must register its ability to do so. This is done with the lineRegisterRequestRecipient function, in which TRUE is specified as the value for the parameter bEnable. (Specifying FALSE de-registers the application as a request recipient, which it should do when it has determined that its recipient duties are through for the current session.)

When registering, the application must also specify the type(s) of request it can handle. Possible values of requests are LINEREQUESTMODE_MAKECALL, to show that the application will handle tapiRequestMakeCall requests. For more information about servicing Assisted Telephony requests, see the section "Performing Request Recipient Duties" later in this chapter.


 Receiving Information

An application receives information in two ways: solicited and unsolicited. Solicited information is requested by the application through a function call such as lineGetDevCaps or lineGetAddressCaps. Unsolicited information arrives in the form of messages—most importantly call-state messages. Often, the two mechanisms are used together, as when an application receives a LINE_CALLSTATE message, after which it checks the information contained in the LINECALLINFO structure by calling lineGetCallInfo.

An application can call lineGetDevCaps to learn more about available lines. The application determines the names of the lines and the number of addresses on those lines. (An important factor in the configuration of lines and addresses is the way the service provider chooses to map lines and addresses. Though the application has no control over this mapping, it can determine the details of the mapping by calling functions such as lineGetDevCaps.) Later, using this information, the application could allow the user to choose which line (and address) to use for an outgoing call, restricting the lines it displays (in a dialog box, for example) to those that support a specific media mode. As an example, an application designed to be used only for faxing may choose to let the user select only lines that support fax transmission.

Call lineGetAddressCaps to obtain information for a given address. The application can use the names of the addresses to let the user choose them in a popup menu, but other information is also reported, such as whether caller-ID is supported, what kinds of call states can be produced, and how many active calls can exist on that address.


 Changes in the Status of a Line Device

The status of a line device can change for many reasons, some as a result of requests submitted by the local application, and some as a result of actions performed by the switch or by the application (or person) at the other end of the connection.

In either case, an application is notified about these changes with the LINE_LINEDEVSTATE callback message, which indicates the status item (the attribute of the line device) that has changed. The application can choose the line status items for which it wants to be notified using the function lineSetStatusMessages. The messages controlled by invoking lineSetStatusMessages are LINE_LINEDEVSTATE and LINE_ADDRESSSTATE.

In addition, an application can determine the current status of an address by calling lineGetAddressStatus, which returns its information in a structure of the type LINEADDRESSSTATUS. It can also see the complete status of the specified open line device by calling lineGetLineDevStatus, which returns its information in a structure of the type LINEDEVSTATUS.


 Callback and Call State Functions

When a TAPI application initializes its connection to the line service with the function lineInitialize, it gives a pointer to the callback function it uses for that line service. This pointer applies to all lines subsequently opened with the same application handle. The callback function obtains a large amount of information for the application, including asynchronous replies, indications of Assisted Telephony requests, or messages resulting from ongoing monitoring of a line. These messages include indications that the status of a line, address, or call has changed; indication that media, tone, or digit monitoring has detected the requested event; and indication that information about a call has changed.

The callback function does not ned to support all messages. Unsupported messages are the ones whose names are immediately followed by a break statement. For example:

case LINE_GATHERDIGITS:
   break;

You can enhance functionality by enabling it to handle these unsupported call-state messages.

To keep the size of the callback function manageable, the processing of call-state messages is performed in separate functions which respond to all call-state messages received by the application. It is in these functions that call-state transitions (such as from connected to idle) are made known as notification of the actual call states.


 Receiving Calls

After an application has opened a line device and, while doing so, registered a privilege other than none, and a media mode, it is notified when a call arrives on that line. Specifically, applications that have the line open with LINECALLPRIVILEGE_MONITOR will receive a LINE_CALLSTATE message for every call that arrives on the line. An application that has opened the line with LINECALLPRIVILEGE_OWNER receives a LINE_CALLSTATE message only if it has become an owner of the call or is the target of a directed handoff. In this notification, TAPI gives the application a handle to the incoming call, and the application keeps this handle until the application deallocates the call.

Applications are informed of call arrivals and all other call-state events with the LINE_CALLSTATE callback message. This message provides the call handle, the application's privilege to the call, and the call's new state. For an unanswered inbound call, the call state is offering. An application can invoke lineGetCallInfo to obtain information about an offering call before accepting it. This function call also causes the call information in the LINECALLINFO data structure to be updated. By knowing the call state and other information, the application can determine whether the call needs to be answered.

The call information stored in LINECALLINFO includes, among other things, the following items:

•	bearer mode, rate  This is the bearer mode (voice, data) and data rate (in bits per second) of the call, for digital data calls.

•	media mode  The current media mode of the call. Unknown is the mode specified if this information is unknown, and the other set bits indicate which media modes might possibly exist on the call. For more information about this, see Chapter 8, "Multiple-Application Programming."

•	call origin  Indicates whether the call originated from an internal caller, an external caller, or an unknown caller.

•	reason for the call  Describes "why" the call is occurring. Possible reasons are:

•	direct call

•	transferred from another number

•	busy—forwarded from another number

•	unconditionally forwarded from another number

•	the call was picked up from another number

•	a call completion request

•	a callback reminder

The reason for the call is given as unknown if this information is not known.

•	caller-ID  Identifies the originating party of the call. This can be in a variety of (name or number) formats, determined by what the switch or network provides.

•	called-ID  Identifies the party originally dialed by the caller.

•	connected-ID  Identifies the party to which the call was actually connected. This may be different from the called party if the call was diverted.

•	redirection-ID  Identifies to the caller the number towards which diversion was invoked.

•	redirecting-ID  Identifies to the diverted-to user the party from which diversion was invoked.

•	user-to-user information  User-to-user information sent by the remote station (ISDN).

The LINE_CALLSTATE message also notifies monitoring applications about the existence and state of outbound (and inbound) calls established by other applications or established manually by the user—for example, on an attached phone device (if the telephony hardware and the service provider support monitoring of actions on external equipment). The call state of such calls reflects the actual state of the call as follows: An inbound call for which ownership is given to another application is indicated to the monitor applications as initially being in the offering state. An outbound call placed by another application would normally first appear to the monitoring applications in the dialtone state.

The fact that a call is offered does not necessarily imply that the user is being alerted. Once alerting (ringing) has begun, a separate LINE_LINEDEVSTATE callback message is sent with a ringing indication to inform the application. It may be necessary, in some telephony environments, for the application to accept the call (with lineAccept) before ringing starts. The application can determine whether or not this is necessary by checking the LINEADDRCAPFLAGS_ACCEPTTOALERT bit.

Depending on the telephony environment, not all the information about a call may be available at the time the call is initially offered. For example, if caller ID is provided by the network between the first and second ring, caller ID will be unknown at the time the call is first offered. When it becomes known shortly thereafter, a LINE_CALLINFO callback message notifies the application about the change in party-ID information of the call.


 Incoming Calls and Line Privileges

An application cannot refuse ownership of a call for which it receives an owner handle. Whether the call is delivered to the application with owner or monitor privileges is decided before the call arrives—at the time the application opens the line on which the call is established by the remote caller.

If the application opens the line with lineOpen with the parameter dwPrivilege set to LINECALLPRIVILEGE_MONITOR, it automatically receives a handle with monitoring privileges for all incoming calls on the line. It can then choose to become an owner by calling lineSetCallPrivilege. The fact that it indicated MONITOR when it opened the line does not prevent it from later becoming an owner with lineSetCallPrivilege or by originating a call with lineMakeCall (an application is always an owner of calls it places regardless of the privilege specified with lineOpen).

When an incoming call has been offered to an application and the application is an owner of the call, the application can answer the call with lineAnswer. Once the call has been answered, its call state typically transitions to connected, at which time information can be exchanged over the call.

An application can receive handles to incoming calls only for monitoring. You can modify the application (specifically, the parameters for lineOpen) to change the privileges with which it initially opens lines.


 Securing a Call

If a new call arrives while another call exists on the line or address, similar notification and call information may be supplied following the same mechanism as for any incoming call. If an application does not want any interference by outside events for a call from the switch or phone network, it should secure the call. Securing a call can be done at the time the call is made with a parameter to lineMakeCall, or later (when the call already exists) with lineSecureCall. The call will be secure until the call is disconnected. Securing a call may be useful, for example, when certain network tones (such as those for call waiting) could disrupt a call's media stream, such as fax.


 Logging Call Information

An application can call the function lineGetCallInfo to obtain information about a call. Although this function fills the LINECALLINFO structure with a large amount of data, applications need to maintain other items, such as the start and stop time of the call.

Developers of applications that log call information should note the following guidelines when designing those applications:

•	Free the call's handle (hCall) when the call goes idle—that is, when a LINECALLSTATE_IDLE message is received for the call. At any point in the call's existence prior to its deallocation, monitoring applications can retrieve information about the call.

•	To keep the call's log sheet complete, log the fact that the call has gone idle.

•	Some applications may also need to update the user interface to show that important events have occurred, such as the fact that a fax is being received. This functionality is driven by the call-state messages received in the newCallState routine described earlier in this chapter.

For more information about call logging, see Chapter 8, "Multiple-Application Programming."


 Establishing a Call

Once an application has determined that a given line offers the needed set of capabilities, and then opens that line, it can access telephony functions for either incoming or outgoing calls on the line. The usual way to place a call on that line is to invoke lineMakeCall, specifying the line handle and a dialable destination address.


 Address Translation

Applications can provide users with location independence and take advantage of calling-card information managed by Windows Telephony by storing telephone numbers in the Canonical address format. Before a Canonical address can be used in placing a call, it must be converted (translated) into the Dialable address format using the lineTranslateAddress function.

To do this, the lineTranslateAddress function starts by examining the settings in TELEPHON.INI to find the user's location, including the country and area code. It then produces a valid dialing sequence by removing unnecessary portions of the number (such as the country code or area code) and adding other digits such as a long distance prefix or a digit used to dial out of a local PBX.

To avoid inadvertent misdialing, such as if the user has changed locations but has not yet informed Windows Telephony of the change, an application may want to present the output of this function call to the user in a dialog box. The user can then confirm the translated address or change it if it is incorrect.


 Toll Lists

In some locations in North America, all calls placed to the local area code are local calls. In other locations, some calls placed to the local area code are long distance, and need a "1" to be dialed. The first three digits of the address (the prefix) determine whether or not a call within the local area code is a toll call.

A toll list is a list of prefixes in the local area code whose addresses must be dialed as long distance addresses, and are assessed long distance charges. With Windows Telephony, a toll list can be built in one of two ways:

1.	The user can add or remove prefixes manually with the the Telephony Control Panel.

2.	The user can add or remove prefixes dynamically after a telephone call to that prefix fails for one of these reasons: When the call was dialed, the "1" prefix was missing and necessary or present and unnecessary. This dynamic process works as follows:

The application knows by the value of the LINETRANSLATERESULT_INTOLLLIST and LINETRANSLATERESULT_NOTINTOLLLIST bits in the LINETRANSLATEOUTPUT structure (returned by lineTranslateAddress) whether an address with the dialed prefix is already in the toll list. The application can then let the user add or remove (whichever applies) this prefix from the toll list. Adding and removing are both peformed using the lineSetTollList function.


 Dialing the Call

The lineMakeCall function first attempts to obtain a call appearance on an address on the line, then waits for a dial tone, and finally dials the specified address. (A call appearance is a connection to the switch over which a call can be made. Once the connection is established, the call appearance exists, even if no call is placed. After the call is established, the call appearance remains in existence until the call transitions to the idle state.) (If calls controlled by other applications exist on the line, these calls would normally have to be on hold, and would typically be forced to stay on hold until the application either drops its call or places it on hold.) If dialing is successful, a handle to a call with owner privileges is returned to the application.

Before invoking lineMakeCall, an application can set up parameters for the call and store them in the data structure LINECALLPARAMS. A pointer to this structure is then used as a parameter of lineMakeCall. In the fields of LINECALLPARAMS, the application can specify the quality of service requested from the network as well as a variety of ISDN call setup parameters. If no LINECALLPARAMS structure is supplied to lineMakeCall, a default POTS voice-grade call is requested with a set of default values. However, it is a good idea to use LINECALLPARAMS so that monitoring applications can report this call information (such as the identification of the called party) accurately.

The call's origination address also appears in LINECALLPARAMS. Using this field, the application can specify the address on the line where it wants the call to originate. It can do so by specifying an address ID, though in some configurations it is more practical to identify the originating address by its directory number.

Note  Do not mix function calls of the Telephony API with the functions of Assisted Telephony. The actions requested by lineMakeCall would happen automatically with the Assisted Telephony function calls tapiRequestMakeCall. But once an application has reached this state by using the calls of the Telephony API, it makes no sense to revert to an Assisted Telephony function call (such as tapiRequestMakeCall), because doing so would cause TAPI to repeat already performed actions. At this stage, therefore, simply calling lineMakeCall causes less overhead.

Once dialing is complete and the call is being established, it passes through a number of different states. These states (the progress of the call) are provided to the application with LINE_CALLSTATE callback messages. This mechanism lets the application track whether the call is reaching the called party. It is important that every telephony application base its behavior on the information received in these messages, and not on any other assumptions about a call's state. An application must not assume that a requested state change has occurred until notification of that state change arrives. Note that it can be helpful to display user-friendly interpretations of call states as indicators of a call's progress, especially for calls expected to pass through states slowly.

If special call setup parameters are to be taken into consideration, the application must supply them to lineMakeCall. Call setup parameters are required for actions such as the following:

•	requesting a special bearer mode, bandwidth, or media mode for the call,

•	sending user-to-user information (with ISDN),

•	securing the call,

•	blocking sending of caller ID to the called party,

•	taking the phone offhook automatically at the originator and/or the called party.


 Calling Card Information

The importance of a "calling card" rests in the different dialing procedures required by the various calling cards. The routine FInitCallingCardInfo provides TAPI with the information it needs to display a dialog box, from which the user can choose a calling card. (The "calling card" numbered 0 means "use the default dialing rules for the country you are in.") The routine returns, among other information, the user's location (country and area code), the number of calling cards registered for this user in the TELEPHON.INI file, and the preferred calling card for that location. This calling card information is applied by the lineTranslateAddress function and does not happen automatically through lineMakeCall.

Typically, an application would prepare a menu choice for the user, such as whether to make a call with the default carrier, to override the default carrier and use a given calling code, or simply to use another specific dialing sequence.


 Using Multiple Addresses Simultaneously

The dialable number format (dialing formats are described in Chapter Concepts of Line Devices) allows multiple destination addresses to be supplied at once. This ability can be useful if the service provider offers some form of inverse multiplexing by setting up calls to each of the specified destinations and then managing the information stream as a single high-bandwidth media stream. The application perceives this group of calls as a single call because it receives only a single call handle representing the aggregate of the individual phone calls.

It is also possible to support inverse multiplexing at the application level. To do this, the application would set up a series of individual calls and synchronize their media streams.


 Delayed Dialing

The application can also use lineMakeCall to allocate a call appearance or to dial just part of the full number. Later, it can complete dialing using lineDial. When the number provided is incomplete, dialing some of the digits may be delayed by placing a ';' (semicolon) at the end of the number. The lineDial function is used in cases in which the application needs to send address information to the switch on an existing call, such as dialing the address of a party to which the call will be transferred.

Note  An application should make sure that "incremental dialing" (providing the number in small pieces) is supported before attempting to use it. This support is indicated by the LINEADDRCAPFLAGS_PARTIALDIAL bit in the dwAddrCapFlags field in the LINEADDRESSCAPS structure, which is returned by lineGetAddressCaps.

The main reasons for an application to use delayed dialing are if the ? character appears in a dialable address or if the service provider does not support one or more of the call progress detection control characters. These characters, which can occur in a dialable address, are W (wait for dial tone); @ (wait for quiet answer); and $ (wait for calling-card prompt tone). These and all other characters used in address strings are discussed in greater detail in Chapter 5, "Concepts of Line Devices."

The provider indicates which "wait for" dial string modifiers it supports in the following bits in the dwDevCapFlags field within the LINEDEVCAPS structure returned by lineGetDevCaps:

•	LINEDEVCAPFLAGS_DIALBILLING

•	LINEDEVCAPFLAGS_DIALQUIET

•	LINEDEVCAPFLAGS_DIALDIALTONE

The ? can be placed in the string (either directly by the application or by the address translator with the function lineTranslateAddress) if it is known that the user needs to listen for an undetectable tone before dialing can proceed. Every provider should treat ? as requiring the dial string to be "rejected."

The lineTranslateAddress function returns bits, in the dwTranslateResults field of the LINETRANSLATEOUTPUT structure, that indicate whether any of the four potentially offending modifiers occur in the dialable string output from that translation operation. These bits give the application an idea of whether the dialable string might need to be scanned for unsupported modifiers:

•	LINETRANSLATERESULT_DIALBILLING

•	LINETRANSLATERESULT_DIALQUIET

•	LINETRANSLATERESULT_DIALDIALTONE

•	LINETRANSLATERESULT_DIALPROMPT

If the application tries to send an unsupported modifier or a ? to the provider, it receives an error indicating which offending modifier occured first within the string:

•	LINEERR_DIALBILLING

•	LINEERR_DIALQUIET

•	LINEERR_DIALDIALTONE

•	LINEERR_DIALPROMPT

The application can choose to pre-scan dialable strings for unsupported characters. Or it can pass the "raw" string from lineTranslateAddress directly to the provider as part of lineMakeCall (or lineDial or any other function that passes a dialable address as a parameter) and then let the service provider generate an error to tell it which unsupported modifier occurs first in the string.

When the application is told (or finds) that an unsupported dial modifier is in the dialable string, it must take the following steps:

1.	Locate the offending modifier in the string;

2.	Isolate the characters occuring in the string to the left of the offending modifier;

3.	Append a semicolon to the end of the partial string;

4.	Reissue the dialing command using the partial string;

5.	Prompt the user to listen for the audible tones indicating when it is OK to proceed with dialing;

6.	Reissue the remainder of the dialable string (the portion following the offending modifier).

Note that in step 6 it is possible for another error to occur, since it is possible for multiple unsupported characters to occur within a single dialable string. Therefore, the application should repeat this process to dial the number in stages.


 Tracking Asynchronous Requests

The function lineMakeCall is one of many functions that operate asynchronously. If an application manages only one line, it can use one state record, a struct containing all the information needed to track one outstanding asynchronous request. State records contain information such as the Request ID, the type of request, and pointers to allocated data that may need to be freed later.

But some applications have to manage more than one line—for example, to manage more than one outgoing call at the same time. To do so, they need to track the different asynchronous requests possible on each of those lines, and must therefore create an array of state records, one for each of the outstanding asynchronous operations (such as multiple invocations of lineMakeCall).

When a reply arrives that shows an asynchronous function has completed, the application matches the incoming Request ID with a Request ID in the array, and does whatever that specific call needs at that point. You can design one function to handle the reply that indicates completion of the outstanding asynchronous lineMakeCall request. The success or failure of the asynchronous request is recorded in the requestResult field of the state struct.


 Performing Request Recipient Duties

If the application is an Assisted Telephony server—that is, if it receives and handles requests from Assisted Telephony client applications—it must ensure that it uses the correct parameters when executing requests. (The terms "Assisted Telephony server" and "request recipient (application)" can be used interchangeably. ) When doing so, these steps are followed:

•	The request recipient first receives a LINE_REQUEST message informing it that requests may exist for it in the request queue. This tells the application to call lineGetRequest and keep calling it until the queue is drained (if the request is for making a new call), or to drop an existing call. This message does not contain the parameters for the request, except in the case of a request to drop an existing call.

•	If the request is to make a new call, the Assisted Telephony server uses the lineGetRequest function to retrieve the full request, which includes the request's parameters. The server now has all the information it needs, such as the number to dial or the identification of the maker of the request. First, however, the server must allocate the memory needed to store this information.

•	Finally, the server executes the request by invoking the appropriate Telephony API function or set of functions.


 Call Handle Manipulation

When an application makes a call, a handle to the call with owner privileges is returned to the application. When the application is notified about an inbound call, it is given a handle to the call with either owner privilege or monitor privilege, depending on the privilege previously requested with lineOpen. It can also receive a handoff from another application, in which case it would receive owner privilege.

An application's call handle and associated privileges remain valid until the application takes an explicit action to change them or if it receives a LINE_CLOSE message, which closes the line. In this case, all handles to calls on the line instantly become invalid.

After a call reverts to the idle state, the application is still allowed to read the call's information structure and status. When the application has no further use for the call (and its information), it should deallocate the call handle by invoking lineDeallocateCall, which is discussed in following sections.

For more information about call logging and handing off calls to other applications, see Chapter 8, "Multiple-Application Programming."


 Dropping Calls

To terminate a call, the application uses lineDrop on the call. This has the effect of hanging up on (disconnecting) the call, which makes it possible to make another call on the line. The lineDrop function is also used to abandon a call attempt in progress. If the remote party disconnects a call, the local application receives a LINE_CALLSTATE message with a call state of disconnected. If the local application disconnects a call, the call becomes idle, but its handle is not automatically deallocated (the application must call lineDeallocateCall). An application should check the dwCallFeatures field in LINECALLSTATUS to determine whether or not it is legal to invoke lineDrop at a particular time.


 Deallocating Call Handles

A call handle remains valid after the call has been dropped. This enables applications to use operations such as lineGetCallInfo to retrieve call information for logging purposes. Once an application knows it has all the information it needs about a call and it has received a LINE_CALLSTATE(LINECALLSTATE_IDLE) message, it should call lineDeallocateCall to free system-allocated memory related to the call. The application must itself free memory that it allocated for its own purposes.

The way to free an idle call is to deallocate its handle with lineDeallocateCall. The application's duty to free a call is independent of the reason the call went idle. That is, the handle must be deallocated whether it was the local or the remote application that dropped it. If an application is the owner of the call, it can deallocate the call's handle only if the call is in the idle state. If monitoring the call, it can deallocate the call handle at any time.

It is better to process the LINE_CALLSTATE(LINECALLSTATE_IDLE) message (and all other call-state notifications) consistently in one location regardless of its cause.


 Reclaiming Memory Resources

The TAPI dynamic link library allocates memory for each call for each application that has a handle to the call. It is likely that service providers will allocate memory to hold call information as well. Deallocation of an application's call handle allows the library and the service provider to reclaim these memory resources. An application's handle for a call becomes void after a successful deallocation.

An application's attempt to deallocate the handle of a non-idle call for which it is the only owner will fail. The application should either first hand off ownership and change its privilege to monitor, or simply try to change its privilege to monitor (in case there are other owners) or clear the call by dropping it—which places the call into the idle state—and then deallocate its handle.


 Closing Line Devices

After an application is finished using a line device, it should close the device by calling lineClose on the line-device handle. After the line has been closed, the application's handle for the line device is no longer valid. A LINE_LINEDEVSTATE message is sent to other interested applications to inform them about the state change on the line.

In certain environments, it may be desirable for a line device that is currently open by an application to be forcibly reclaimed (possibly by the use of some control applet) from the application's control. This feature can be used to prevent a single misbehaved application or user from monopolizing a line. It is also used when the user wants to reconfigure the line parameters, and has told the service provider directly through its Setup function in the Telephony Control Panel that the provider should forcibly close the line. When this occurs, an application receives a LINE_CLOSE message for the open line device that was forcibly closed.


 Exiting Telephony

The lineShutdown function disconnects the application from the Telephony API. If this function is called when the application has lines open or calls active, the call handles are deleted and the equivalent of a call to the lineClose function is automatically performed on each open line. (It is better for applications to explicitly close all open lines before invoking lineShutdown.) If shutdown is performed while asynchronous requests are outstanding, those requests are canceled.

An application that has registered as an Assisted Telephony request recipient should de-register itself by calling lineRegisterRequestRecipient, using the value FALSE for the bEnable parameter.


 Setting a Terminal for Phone Conversations

The user's desktop computer may have access to multiple devices that are individually selectable and used to conduct interactive voice conversations. One of these devices is the telephone itself, complete with lamps, buttons, display, ringer, and a voice I/O device (handset, speakerphone, or headset). The user's computer may also have a separate voice I/O device (such as a headset, or microphone/speaker combination attached to a sound card) for use with phone conversations. TAPI enables the user to select where to route the information sent by the switch over the line, address, or call. The switch normally expects this destination to be one of its phone sets, and sends ring requests, lamp events (for stimulus phones), display data, and voice data as appropriate.

The phone in turn sends hookswitch events, button press events (for stimulus phones), and voice data back to the switch. The line portion of TAPI makes lamp events, display events, and ring events available, either as "functional" return codes to TAPI's various operations or as unsolicited functional call-status messages sent to the application callback. TAPI's implementation is responsible for mapping the functional API level to the underlying stimulus or functional messages used by the telephony network. In functional telephony environments, TAPI's functions are mapped to the functional protocol.


 Modes of Operation: Functional and Stimulus

The "functional" mode of operation differs from the "stimulus" mode in the way meaning is attributed to events. For example, a given telephone has a button labeled "Transfer." When this button is pressed, one of two things can happen: the phone can send a message to the switch stating that the Transfer button was pressed, or it can send a message stating that "button number 18" was pressed. In the functional model, the button's function is indicated. It allows more flexibility in the phone hardware, because the switch doesn't need to know anything about the layout of the buttons, but the telephone will likely be more expensive, because it has more intelligence.

The stimulus model means that the event is simply indicated in a more raw, hardware fashion, such as by button number—even down to separate button-up and button-down events. In a stimulus-based system, telephones can cost less, but more intelligence is required in the switch so that it can recognize different types of telephones and translate their buttons into features. The stimulus model can provide more flexibility because different people can configure their phone buttons to mean different things through switch programming rather than by changing the phone itself.


 Event Routing

Although not described in the "Supplementary Line Functions" chapter, event routing is a part of the supplementary line services and is not a basic function.

With the lineSetTerminal function, the application can control or suppress the routing of specified low-level events (exchanged between the switch and the station) to a device. With lineSetTerminal, the application specifies the terminal device to which these events (such as line, address, or call media-stream events) are routed.

The routing of the different classes of events can be individually controlled, allowing separate terminals to be specified for each event class. Event classes include lamps, buttons, display, ringer, hookswitch, and media stream.

For example, the media stream of a call (voice, for example) can be sent to any transducer device if the service provider and the hardware is capable of doing so. In general, a "transducer" means the same as what is referred to as a "hookswitch" device in the Telephony Phone API—something that has a microphone and a speaker. Ring events from the switch to the phone can be mapped into a visual alert on the computer's screen or they can be routed to a phone device. Lamp events and display events can be ignored or routed to a phone device (which appears to behave as a normal phone set). Finally, button presses at a phone device may or may not be passed to the line. In any case, this routing of low-level signals from the line does not affect the operation of the line portion of TAPI, which always maps low-level events to their functional equivalent. To determine the terminals a line device has available (and their capabilities), consult the line device's capabilities with lineGetDevCaps.

Assume initially that the application has suppressed the routing of all events (with lineSetTerminal), and the user selects a headset as the current I/O device. An incoming call sends a LINE_CALLSTATE message, and a LINE_LINEDEVSTATE message with the ringing indication. Since routing of all events is suppressed, ring events are not routed to the phone, so ringing is suppressed. Instead, the application notifies the user with a pop-up dialog box and a system beep in the headset.

The user decides to answer the call. Since the user's current I/O device is the headset, the telephony application invokes lineSetTerminal on the incoming call to route the call's media to the headset and answer the call. The application may also invoke lineSetTerminal to route lamp and display information events to the phone set so that it will behave as usual.

As a second example, assume that an incoming call is alerting at the user's computer. Instead of selecting the answer option with the mouse, the user decides to just pick up the phone's handset to answer the call. The offhook status at the phone sends a callback message to the application. The application can interpret this status as a request by the user to select the phone handset to conduct the conversation. The application then invokes lineSetTerminal to route the voice data on the call to the phone set.


 Supplementary Line Functions

About Supplementary Line Functions

In Windows Telephony, supplementary functions are functions whose form and functionality has been defined by the API description, but which are not required in basic Telephony. They are functions that developers of telephony applications and service providers may choose to implement to suit the design of their custom products. That is, in contrast to Basic Telephony functions, Supplementary Telephony functions are optional.

This chapter describes the Supplementary functions used with TAPI-defined line devices. For convenience, they are grouped into general functional categories.


 Bearer Mode and Rate

The notion of bearer mode corresponds to the quality of service requested from the network for establishing a call. It is important to keep the concept of bearer mode separate from that of media mode. The media mode of a call describes the type of information that is exchanged over a specific call of a given bearer mode. As an example, the analog telephone network (PSTN) provides only 3.1 kHz voice-grade quality of service—this is its bearer mode. However, a call with this bearer mode can support a variety of different media modes such as voice, fax, or data modem. In other words, media modes require certain bearer modes. TAPI manages the bearer modes only by passing the bearer mode parameters on to the network. Media modes are fully managed through the appropriate media stream APIs, although some limited support is provided in TAPI.

The bearer mode of a call is specified when the call is set up, or is provided when the call is offered. With line devices able to represent channel pools, it is possible for a service provider to allow calls to be established with wider bandwidth. The rate (or bandwidth) of a call is specified separately from the bearer mode, allowing an application to request arbitrary data rates.

The bearer modes defined in TAPI are:

•	Voice  Regular 3.1 kHz analog voice service. Bit integrity is not assured.

•	Speech  G.711 speech transmission on the call.

•	Multiuse  As defined by ISDN.

•	Data  Unrestricted data transfer. The data rate is specified separately.

•	Alternate speech and data  The alternate transfer of speech and unrestricted data on a call (ISDN).

•	Non call-associated signaling  This provides a clear signaling path from the application to the service provider.

Although support for changing a call's bearer mode or bandwidth is limited in networks today, TAPI provides an operation to request a change in the bearer mode or the data-rate parameters of an existing call. This function is lineSetCallParams.


 Call Monitoring

Call monitoring includes media, digit, and tone monitoring.


 Media Monitoring

When a call is in the connected state, information can be transported over the call. A call's media mode provides an indication of the type of information (for example, its data type, or higher-level protocol) of this media stream. TAPI allows applications to be provided with a callback notification about changes in a call's media mode. The notification provides an indication of the call's new media mode. Note that the service provider decides how it wants to make this determination. For example, the service provider could use signal processing of the media stream to determine the media mode, or it could rely on distinctive ringing patterns assigned to different media streams, or on information elements passed in an out-of-band signaling protocol. Independent of how the media mode determination is achieved, the application is simply informed about media mode changes on an existing call.

The media modes defined by TAPI include:

•	Unknown  The media mode of the call is not currently known—the call is unclassified.

•	Interactive voice  Voice energy was detected on the call, and the call is handled as an interactive voice call with a person at the application's end.

•	Automated voice  Voice energy was detected on the call, and the call is handled as a voice call but with no person at the application's end, such as with an answering machine application.

•	Data modem  A modem session on the call. Note that current modem protocols require the called station to initiate the handshake. For an inbound data modem call, the application can typically make no positive detection. How the service provider makes this determination is its choice. For example, a period of silence just after answering an inbound call may be used as a heuristic to decide that this might be a data modem call.

•	G3 fax  A group 3 fax session on the call.

•	TDD  The call's media stream uses the Telephony Devices for the Deaf protocol.

•	G4 fax  A group 4 fax session on the call.

•	Digital data  A digital data stream of unspecified format.

•	Teletex, Videotex, Telex, Mixed  These correspond to the telematic services of the same names.

•	ADSI  An Analog Display Services Interface session on the call. ADSI enhances voice calls with alphanumeric information downloaded to the phone and the use of soft buttons on the phone.

An application can enable or disable media monitoring on a specified call with lineMonitorMedia. The application specifies which media modes it is interested in monitoring, and when media monitoring is enabled, the detection of a media mode change causes the application to be notified with the LINE_MONITORMEDIA callback message. This callback message provides the call handle on which the media mode change was detected as well as the new media mode.

There is a distinction between the media mode of a call as reported by lineGetCallInfo and the media mode event reports by LINE_MONITORMEDIA messages. A call's media mode is determined exclusively by owner applications of the call and is not automatically changed by media monitoring events. The one exception is the initial media mode determination that may be performed by the TAPI dynamic link library to select the first owner of a call. One could argue that in this case, the library is the owner of the call.

Default media mode monitoring is performed for the media modes for which the line device has been opened. This allows an inbound call's media mode to be determined before the call is handed to an application based on what the applications demand. Note that the scope of the media monitoring of a call is bound by the lifetime of the call. Media monitoring on a call ends as soon the call disconnects or goes idle.

An application can obtain device IDs for various Windows device classes associated with an opened line by calling lineGetID. This function takes a line handle, address, or call handle and a device class description. It returns the device ID for the device of the given device class that is associated with the open line device, address, or call. If the device class is "tapi/line," then the device ID of the line device is returned. If the device class is "mci/wave," then the device ID of an mci waveaudio device is returned (if supported), which allows activities such as the recording or playback of audio over the call on the line.

The application can use the returned device ID with the corresponding media API to query the device's capabilities and subsequently open the media device. For example, if your application needs to use the line as a waveform device, it must first call waveInGetDevCaps and/or waveOutGetDevCaps to determine the waveform capabilities of the device. The typical wave form data format supported by telephony in North America is 8-bit m-law at 8000 samples per second, although the wave device driver can convert this sample rate and companding to other more common multimedia audio formats.

To subsequently open a line device for audio playback using the waveform API, an application calls waveOutOpen. The implementation of waveOutOpen is device specific, and there is a variety of options for implementing this function.


 Digit Monitoring

Digit monitoring monitors the call for digits. TAPI allows digits to be signaled according to two methods (digit modes):

•	Pulse  Digits are signaled as pulse or rotary sequences. For detection, these pulses manifest themselves as nothing more than sequences of audible clicks. Valid pulse digits are '0' through '9'.

•	DTMF  Digits are signaled as DTMF (Dual Tone Multiple Frequency) tones. Valid DTMF digits are '0' through '9', 'A'. 'B', 'C', 'D', '*', and '#'. Both the beginning and the down edge of DTMF digits can be monitored.

An application can enable or disable digit monitoring on a specified call with lineMonitorDigits. When digit monitoring is enabled, detected digits cause the application to be notified with the LINE_MONITORDIGITS callback message. This callback message provides the call handle on which the digit was detected as well as the digit value and the digit mode. The scope of digit monitoring is bound by the lifetime of the call. Digit monitoring on a call ends as soon as the call disconnects or goes idle.


 Tone Monitoring

Tone monitoring monitors the media stream of a call for specified tones. A tone is described by its component frequencies and cadence. An implementation of the API may allow several different tones to be monitored simultaneously. An application can "tag" each tone in order to be able to distinguish the different tones for which it requests detection.

An application can enable or disable tone monitoring on a specified call with lineMonitorTones. With this function, the application specifies which tones to detect on a specified call. When tone monitoring is enabled, detected digits cause the application to be notified with the LINE_MONITORTONE callback message. This callback message provides the call handle on which the tone was detected as well as the application's "tag" for the tone.

The scope of tone monitoring is bound by the lifetime of the call. Tone monitoring on a call ends as soon the call disconnects or goes idle.

Note that the monitoring of tones, digits, or media modes often requires the use of resources of which the service provider may only have a finite amount. A request for monitoring may be rejected if resources are not available. For the same reason, an application should disable any unnecessary monitoring.


 Media Control

An application can request the execution of a limited set of media-control operations on the call's media stream triggered by telephony events. Although an application is encouraged to use the media API specifically defined for the media mode, media control can yield a significant performance improvement for client-server implementations. The lineSetMediaControl function is used to set up a call's media stream for media control by allowing an application to specify a list of tuples specifying a telephony event and the associated media-control action. The telephony events that can trigger media-control activities are:

•	Detection of a digit  The application provides a list of specific digits and the media-control action that each of them triggers.

•	Detection of a media mode  The application provides a list of media modes and the media-control actions that a transition into the media mode triggers.

•	Detection of a specified tone  The application specifies a list of tones and the media-control action that each tone detection triggers.

•	Detection of a call state  The application specifies a list of call states and the media-control action that each transition to the call state triggers.

The media-control actions listed below are defined generically for the different media modes. Not all media streams may provide meaningful interpretations of the media-control actions. The operations should map well to audio streams.

•	Start  Starts the media stream.

•	Reset  Resets the media stream.

•	Pause  Stops or pauses the media stream.

•	Resume  Starts or resumes the media stream.

•	Rate up  Increases the rate (speed) of the media stream by an implementation-defined amount.

•	Rate down  Decreases the rate of the media stream by an implementation-defined amount.

•	Rate normal  Returns the rate to normal.

•	Volume up  Increases the volume (amplitude) of the media stream.

•	Volume down  Decreases the volume of the media stream.

•	Volume normal  Returns the volume to normal.

The scope of media control is bound by the lifetime of the call. Media control on a call ends as soon the call disconnects or goes idle. Only a single media-control request can be outstanding on a call across all applications.


 Digit Gathering

Besides enabling digit monitoring and being notified of digits one at a time, an application can also request that multiple digits be collected in a buffer. Only when the buffer is full or when some other termination condition is met is the application notified. Digit gathering is useful for functions such as credit card number collection. It is peformed when an application calls lineGatherDigits, specifying a buffer to fill with digits. Digit gathering terminates when one of the following conditions is true:

•	The requested number of digits has been collected.

•	One of multiple termination digits is detected. The termination digits are specified to lineGatherDigits, and the termination digit is placed in the buffer as well.

•	One of two timeouts expires. The timeouts are a first digit timeout, specifying the maximum duration before the first digit must be collected, and an inter-digit timeout, specifying the maximum duration between successive digits.

•	Digit gathering is canceled explictly by lineGatherDigits again with either another set of parameters to start a new gathering request or by using a NULL digit buffer parameter to cancel.

When terminated for any reason, a LINE_GATHERDIGITS message is sent to the application that requested the digit gathering. Note that only a single digit gathering request can be outstanding on a call at any given time across all applications that are owners of the call.

Note that digit gathering and digit monitoring may be enabled on the same call at the same time. In that case, the application will receive a LINE_MONITORDIGITS message for each detected digit and a separate LINE_GATHERDIGITS message when the buffer is sent back.


 Generating Inband Digits and Tones

Once a call is in the connected state, information can be transmitted over it. Two functions are provided that allow end-to-end inband signaling between the application and remote station equipment such as an answering machine. One function is lineGenerateDigits, which generates inband digits on a call, signaling them over the voice channel. Digits can be signaled as either rotary/pulse sequences or as DTMF tones. The other function is lineGenerateTone, which enables the application to generate one of a variety of multi-frequency tones inband (over the media stream). This generates telephony tones, such as ringback, beep, and busy, as well as arbitrary multi-frequency, multi-cadenced tones.

Only one digit or tone generation can be in progress on a call at any one time. When digit or tone generation completes, a LINE_GENERATE message is sent to the application that requested the generation. In the case where multiple digits are generated, only a single message is sent back after all digits have been generated. Calling lineGenerateDigits or lineGenerateTone while digit or tone generation is in progress will abort the generation currently in progress and send the LINE_GENERATE message to the application whose generation was aborted with a cancel indication.


 Call Operations

The call operations include acceptence, rejection, redirecting, holding, forwarding, parking, pick up, and completion.


 Call Accept, Reject, and Redirect

In environments like ISDN, call offering is separate from alerting. In fact, after a call has been offered to an application, a time window exists during which the application has a number of options:

•	It can answer the call using lineAnswer, which immediately answers the call.

•	It can accept the call using lineAccept, which initiates alerting to both the caller (as ringback), and the called party (as ring).

•	It can reject the offering call using lineDrop, which reverts the offering call to the idle state.

•	It can redirect the call using lineRedirect, which deflects the offering call to another address. The call reverts to the idle state.


 Call Hold

Most PBXs can associate multiple calls with a single line. A call can be placed on hard hold, which frees the user's line/address to make other calls. An application can place a call on hard hold by calling lineHold. An application may retrieve a call on hard hold by calling lineUnhold.

Hard hold is different from a consultation hold. A call is automatically placed on consultation hold, for example, when a call is prepared for transfer or conference.


 Call Transfer

TAPI provides two mechanisms for call transfer: blind transfer and consultation transfer.

•	In blind transfer (or single-step transfer), an existing call is transferred to a specified destination address in one phase using lineBlindTransfer.

•	In a consultation transfer, the existing call is first prepared for transfer to another address using lineSetupTransfer. This places the existing call on consultation hold, and identifies the call as the target for the next transfer-completion request. lineSetupTransfer also allocates a consultation call that can be used to establish the consultation call with the party to which the call will be transferred. The application can dial the extension of the destination party on the consultation call (using lineDial), or it can drop and deallocate the consultation call and instead activate an existing held call (using lineUnhold), if supported by the switch.

While the initial call is on consultation hold and the consultation call is active, the application can toggle between these calls using lineSwapHold.

Finally, the application completes the transfer in one of two ways using lineCompleteTransfer:

•	Transfer the call on transfer hold to the destination party. Both calls will revert to the idle state.

•	Enter a three-way conference. A new call handle is created to represent the conference and this handle is returned to the application.


 Call Conference

Conference calls are calls that include more than two parties simultaneously. They can be set up using either a switch-based conference bridge or an external server-based bridge. Typically, only switch-based conferencing will allow the level of conference control provided by the API. In server-based conference calls all participating parties dial into the server which mixes all the media streams together and sends each participant the mix; there may be no notion of individual parties in the conference call, only that of a single call between the application and the bridge server.

A conference call can be established in a number of ways, depending on device capabilities:

•	A conference call may begin as a regular two-party call, such as a call established with lineMakeCall. Once the two-party call exists, additional parties can be added, one at a time. Calling lineSetupConference prepares a given call for the addition of another party, and this action establishes the conference call. This operation takes the original two-party call as input, allocates a conference call, connects the original call to the conference, and allocates a consultation call whose handle is returned to the application.

Note that the capabilities of the addressed line device may limit the number of parties conferenced in a single call and whether or not a conference starts out with a normal two-party call.

The application can then use lineDial on the consultation call to establish a connection to the next party to be added. lineDrop can be used to abandon this call attempt. The third party is added with the function lineAddToConference, which specifies both the conference call and the consultation call.

•	A three-way conference call can be established by resolving a transfer request for three-way conference. In this scenario, a two-party call is established as either an inbound or outbound call. Next the call is placed on transfer hold with the function lineSetupTransfer which returns a consultation call handle. After a period of consultation, the application may have the option to resolve the transfer setup by selecting the three-way conference option which conferences all three parties together in a conference call with lineCompleteTransfer with the conference option (instead of the transfer option). Under this option, a conference call handle representing the conference call is allocated and returned to the application.

•	A conference call may need to be established with lineSetupConference without an existing two-party call. This returns a handle for the conference call and allocates a consultation call. After a period of consultation, the consultation call can be added with lineAddToConference. Additional parties are added with linePrepareAddToConference followed by lineAddToConference.

To add additional parties to an existing conference call, the application uses linePrepareAddToConference. When calling this function, the application supplies the handle of an existing conference call. The function allocates a consultation call that can later be added to the conference call and returns a consultation call handle to the application. This conference call is then placed on conference hold. Once the consultation call exists, it can be added to the existing conference call with lineAddToConference.

Once a call becomes a member of a conference call, the member's call state reverts to conferenced. The state of the conference call typically becomes connected. The call handle to the conference call and all the added parties remain valid as individual calls. LINE_CALLSTATE events can be received about all calls. For example, if one of the members disconnects by hanging up, an appropriate call-state message may inform the application of this fact; such a call is no longer a member of the conference.

As is the case with call transfer, the application may toggle between the consultation call and the conference call using lineSwapHold.

Use the call handle for the member calls to later remove the call from the conference. Do this by calling lineRemoveFromConference on the call handle. Note that this operation is not commonly available in its fully general form. Some switches may not allow it at all, or only allow the most recently added party to be removed. The line's device capabilities describe which type of lineRemoveFromConference is possible.


 Removing a Party

When canceling the consultation call to the third party for a conference call or when removing the third party in a previously established conference call, the service provider (and switch) may release the conference bridge and revert the call back to a normal two-party call. If this is the case, hConfCall will transition to the idle state, and the only remaining participating call will transition to the connected state.


 Call Park

Two forms of call parking are provided: directed call park and non-directed call park. In directed call park, the application specifies the destination address where the call is to be parked. This roughly behaves like a call transfer to the destination address, but it doesn't alert or time out as a transfer would.

In non-directed call park, the switch returns to the application the address where it parked the call. In either case, the function linePark is used to park a call. A parked call can later be retrieved with lineUnpark. The application specifies the park address to lineUnpark which returns a call handle to the unparked call. Appropriate LINE_CALLSTATE messages will be sent to the application as the call is reconnected.


 Call Forwarding

Forwarding affects the treatment by the switch or network of incoming calls destined for a given address. The application can specify call forwarding conditions based on the origin of the call (internal, external, selective based on caller ID), the status of the address (busy, no answer, unconditionally), and the destination address where calls are to be forwarded. When the specified conditions are met for an incoming call, the switch deflects the incoming call to the specified destination number. Because the switch performs the forwarding action, the application will typically not know when a call has been forwarded.

The lineForward function provides a combination of call forwarding (by setting call-forwarding requests) and a do-not-disturb feature. LineForward can also cancel any or all of the forwarding requests currently in effect. Some switches require that a call be established to the forwarding address in order for call forwarding to be initiated. On such systems, lineForward allocates a consultation call and returns the handle for it to the application. The consultation call can be used as any other call. After the connection is established, forwarding confirmation is received from the switch, the call is dropped (using lineDrop), and forwarding is in effect. A LINE_ADDRESSSTATE message with a forwarding indication informs the application about changes in an address' forwarding status.

Note that it may be impossible for a service provider to know at all times what forwarding is in effect for an address. Forwarding may be canceled or changed in ways that make it impossible for a service provider to be informed of this fact.


 Call Pickup

Call pickup allows an application to answer a call that is alerting at another address. The application invokes linePickup by identifying the target of the pickup and is returned a call handle for the picked-up call. There are several ways to specify the target of the pickup request. First, specify the address (extension) of the alerting party. Second, if no extension is specified and the switch allows it, the application can pick up any ringing phone in its pickup group. Third, some switches require a group ID to identify the group to which the ringing extensions belongs.

After the call has been picked up, it is diverted to the application and the application is sent appropriate LINE_CALLSTATE messages for the call. An application can invoke lineGetCallInfo to find out information about the picked-up call, if provided by the switch.


 Call Completion

When making an outbound call, the unavailability of certain resources may prevent the call from reaching the connected state, as when the destination party is busy or doesn't answer. Unavailable resources include trunk circuits as well as the destination party's station. The lineCompleteCall function lets the application specify how it wants to complete a call that cannot be completed normally—this is called "placing a call-completion request." The application has the following options:

•	Camp on to queue the call until the call can be completed.

•	Call back requests the called station to return the call when the station returns to idle. Answering the call-back may automatically re-initiate (redial) the connection request.

•	Intrude allows the application to barge in to the existing call.

•	Message (also known as "leave word calling") allows the application to send one of a small number of predefined messages to the destination. These messages can be text shown on the phone's display, a voice message left for the user, and so forth.

A call completion request can be canceled with lineUncompleteCall. Multiple call completion requests can potentially be outstanding for a given address at any one time. To identify individual requests, the implementation returns a completion ID. When a call completion request completes and results in a new call, the call completion ID is available in the LINECALLINFO data structure returned by lineGetCallInfo. Canceling a call completion request in progress also uses this call completion ID.


 Extended Line Functions

Extended Line Services (or device-specific line services) include all service-provider defined extensions to the API. The API defines a mechanism that enables service-provider vendors to extend TAPI using device-specific extensions. The API only defines the extension mechanism, and by doing so provides access to device-specific extensions, but the API does not define their behavior. Behavior is completely defined by the service provider.

TAPI consists of scalar and bit-flag constant definitions, data structures, functions, and callback messages. Procedures are defined that enable a vendor to extend most of these as follows:

For extensible scalar data constants, a service-provider vendor may define new values in a specified range. As most data constants are DWORDs, typically the range 0x00000000 through 0x7FFFFFFF is reserved for common future extensions, while 0x80000000 through 0xFFFFFFFF are available for vendor-specific extensions. The assumption is that a vendor would define values that are natural extensions of the data types defined by the API.

For extensible bit-flag data constants, a service-provider vendor may define new values for specified bits. As most bit-flag constants are DWORDs, typically a specific number of the lower bits are reserved for common extensions while the remaining upper bits are available for vendor-specific extensions. Common bit flags are assigned from bit zero up; vendor-specific extensions should be assigned from bit 31 down. This provides maximum flexibility in assigning bit positions to common extensions versus vendor-specific extensions. A vendor is expected to define new values that are natural extensions of the bit flags defined by the API.

Extensible data structures have a variably sized field that is reserved for device-specific use. Being variably sized, the service provider decides the amount of information and the interpretation. A vendor that defines a device-specific field is expected to make these natural extensions of the original data structure defined by the API.

Two functions, lineDevSpecific and lineDevSpecificFeature, and two related messages, LINE_DEVSPECIFIC and LINE_DEVSPECIFICFEATURE, provide a vendor-specific extension mechanism. The lineDevSpecific function and associated LINE_DEVSPECIFIC message enables an application to access device-specific line, address, or call features that are unavailable with the Basic or Supplementary Telephony services. The parameter profile of the lineDevSpecific function is generic in that little interpretation of the parameters is made by the API. The interpretation of the parameters is defined by the service provider and must be understood by an application that uses them. The parameters are simply passed through TAPI from the application to the service provider. An application that relies on device-specific extensions will not generally work with other service providers; however, applications written to the Basic and Supplementary Telephony Services will work with the extended service provider.

For convenience, a more specialized escape function is also provided. It is similar to lineDevSpecific, but places interpretation on some of the parameters. This more specialized function lineDevSpecificFeature, which is a device-specific escape function to allow sending switch features to the switch. The message LINE_DEVSPECIFICFEATURE is the device-specific message sent to the application's callback as an indication of features sent to the switch. This function and its associated message allow an application to emulate button presses at the line's feature phone. As feature phones and the meanings of their buttons are vendor-specific, feature invocation using lineDevSpecificFeature is also vendor specific.

As mentioned earlier, there is no central registry for manufacturer IDs. Instead, a unique ID generator (EXTIDGEN) is made available.


 Multiple-Application Programming

About Multiple-Application Programming

Windows Telephony applications may be designed to cooperate with each other, or they may act independently of one another. These TAPI applications will at times operate with non-TAPI applications built to support TAPI functionality, such as media-stream control applications. All these applications must be able to work together, or at least function independently in a cooperative way. To achieve this, TAPI defines mechanisms that let applications coordinate their telephony and phone activities while maintaining a high degree of flexibility.

The roles played by Telephony's major components are described in various sections of this chapter. Application writers can not only learn about TAPI's functioning from these sections, but can apply that knowledge directly when designing TAPI applications. For example, the "Unknown" application (defined in the following section) performs specific duties in media-mode probing and call handoffs. It is important to note and understand these duties before writing an Unknown application.


 Event-Driven Environment

Like all Windows applications, Windows Telephony applications operate in the event-driven model used by Windows. In Telephony, the most important events are call-state transitions. The service provider and TAPI dynamic link library report call states to applications for particular calls. Interested applications, which know the previous state of the call, could infer call-state transitions from call states.

All running applications receive information—call-state messages—about all the calls in which they are interested. At times, several applications will have interest in the same call or calls, as monitors or owners of those calls. Incoming call-state events often cause applications to take actions on calls, and because those actions sometimes involve a shared call, one application must react to the knowledge that another has taken a certain step. Examples include the case where one application shows interest in owning (having control of) a call currently owned by your application, or drops a call co-owned by your application.

The Telephony system was designed to minimize "race" situations—in which the timing of competing function calls from different applications makes a difference. Awareness of the principles and the guidelines described in this chapter should help minimize possible competition.


 Definitions

The following concepts are important for understanding the material presented in this chapter.

Initial Media Modes

On a network other than ISDN, service providers usually do not know the media mode of an arriving call. For such calls, the service provider indicates a number of initial media modes, from which the correct one is eventually selected during the next step—the probing process. The initial media mode(s) identified by the service provider as being possible on the call will be reflected in the dwMediaMode field of the LINECALLINFO data structure, which the application can obtain by calling lineGetCallInfo after the initial LINE_CALLSTATE message announcing a new call is received.

Call Control

Having control of a call means that the application has received a LINE_CALLSTATE message stating that it has become an owner of the call. With this event, the application acquires a handle to the call with owner privileges. A way for a monitoring application to obtain call control (ownership) is to call lineSetCallPrivilege in order to set its call privilege to owner.

Call Monitor

An application that has a handle to a call with monitor privileges is a monitor of that call. Such an application cannot control the existence or other aspects of the call, but it can record (log) facts about the call. The application can also reset its call privilege to owner, thus becoming an owner of the call, in the event that the application determines (by monitoring media modes or other events) that it should take control.

Call Owner

An application that has control of a call is an owner of that call. An application can become an owner of a call in several ways, all discussed in this chapter. A call can have several owners simultaneously, although the usual situation is for only one application to be the owner of a call.

Probing

Probing is the sending of signals on the phone line as an attempt to determine an incoming call's media mode. This search for the media mode is conducted only by applications. Some service providers may also be configured to do some amount of probing automatically to narrow down the initial media modes reported on a new call.

The "Unknown" Application

An application that has opened a line requesting ownership privilege for calls of as-yet undetermined, or UNKNOWN media mode, is referred to as the Unknown application. (The LINEMEDIAMODE_UNKNOWN bit is set in the dwMediaMode field of the LINECALLINFO structure, along with other bits indicating other modes that are potentially present on the call.) An application that does this may actually be capable of handling calls of a number of different media modes. Alternatively, it may simply act as a traffic director, passing calls on to other applications that can use calls of the specific media modes.


 Call Ownership

The mechanism with which applications control calls is based on the concept of ownership. At any given time, one or more applications can own a call. While an application has ownership of a call, it is allowed to manipulate the call in ways that affect the state of the call. An application that does not own a call (but has a handle to it) is a monitor of the call and is prevented from manipulating it. It can only perform status- and information-query operations on that call. While one or more applications are owners of a call, still other applications can be monitoring the call.

Ownership of a call is assigned to applications according to the following rules:

•	An application that makes an outgoing call is the initial sole owner of that call. Other applications monitoring the line will be informed of the outgoing call at the time the first LINE_CALLSTATE message is received. Usually, this notification occurs when dial tone is initially detected.

•	Ownership of an incoming call is assigned to one application only. This assignment avoids the situation in which, depending on timing, different applications may seize control at different times, causing unpredictable results.

•	An application that is currently an owner of a call can pass ("hand off") ownership to another application that has the call's line open. While handing off ownership of a call, the original owner application can specify the new media type of the call. When the handoff succeeds, the original application remains an owner of the call, and it can then choose to either deallocate its handle (if it is no longer interested in the call), change to being a monitor (using lineSetCallPrivilege), or remain an owner (although doing so is discouraged). The original application's privilege is not automatically changed by lineHandoff. More information on the two types of call handoffs (directed and media-mode) can be found later in this chapter.

•	If a target application for the handoff is found, and if it is already a co-owner of the call, it will see no effect caused by the handoff although it will receive a LINE_CALLSTATE message. This message repeats the fact that it is an owner to alert it that another application has explicitly asked it to take control of the call. The application initiating the handoff is informed about the success of the handoff.

•	If there is no target application for the requested handoff and the call is active, an error is returned. No handoff takes place.

•	Handing off a call between applications never affects the state of the physical call as perceived by the switch or the service provider.

•	An application that does not have (but wants) ownership of a call may request ownership. The application can select calls based on a number of criteria, ranging from all calls on a particular line or address (a phone number assigned to the line, using lineGetNewCalls), to calls related to a specified call (using lineGetConfRelatedCalls). An application that calls lineGetNewCalls or lineGetConfRelatedCalls will always receive a monitor handle. If it wants to become an owner of a call it receives, it must then call lineSetCallPrivilege. If it determines that it is not interested in one or more of the calls to which it receives handles using lineGetNewCalls or lineGetConfRelatedCalls, it must call lineDeallocateCall for each such handle to release the internal resources maintained to track the call ownership.

•	Any application that asks for ownership receives it; any application that is offered ownership cannot refuse it. An application that becomes an owner through a handoff actually becomes a co-owner of the call. When the call is initially presented by the provider, the initial owner is the sole owner of the call.

•	The originally owning applications are informed about the existence of every new owner. Monitoring applications are informed as well.

Note that with co-owned calls (calls simultaneously owned by more than one application), no protection is offered to prevent the applications from interfering with each other. For this reason, maintaining ownership after a handoff or after ownership is taken by another application is discouraged.

Since media streams are not managed by the Windows Telephony API, call handoff does not handle the handoff of the call's media stream. Media-stream handoff must be carried out using commands from an appropriate media-control API or directly coordinated between the applications involved.


 Handling Incoming Calls

When multiple applications are running simultaneously, an appropriate one must be found to become the initial owner of each incoming call. In general, incoming calls reach their destination, or "target" application, in two or three steps: First, the service provider learns of the new call and passes it to the TAPI dynamic link library which gives the call to the appropriate application. Finally, applications conduct probing, if necessary, which can cause the call to be handed off between applications one or more times. These steps are described below. Sometimes applications perform further probing, a case which is also covered in the following description.


 Duties of the Service Provider

The service provider determines the media modes.


 Determining Initial Media Modes

When a service provider learns of the appearance of a call, its first task is to determine the call's media mode to the best of its ability. (It has received "ringing voltage" on a POTS line or, in the case of EPBX or ISDN, a protocol message indicating that a call is incoming.) It may be able to tell the single correct media mode or it may only be able to narrow down the possibilities to a certain few. These first media mode settings are called initial media modes, and following are the considerations used for setting initial media mode bits:

•	Service Provider Setup  The service provider has been configured to work with only a single media mode or certain media modes.

•	Hardware Limitations  Hardware limitations are usually reflected in the service provider's configuration, but the media modes could be further restricted by a particular card in use.

•	Call to lineOpen  Possible media modes are limited by what applications have requested in their invocation of the lineOpen function. TAPI combines all of the media modes requested by applications and indicates the sum of them to the service provider in a call to TSPI_lineSetDefaultMediaDetection. For example, a telephony device and its service provider may be able to handle Group 3 facsimile calls, but if no application is running to handle such calls, the provider would know not to bother with probing for fax or reporting fax calls to TAPI. (The TAPI dynamic link library does not automatically launch an application to handle a particular type of incoming call.)

•	Caller ID and Direct Inward Dialing  With Direct Inward Dialing (DID) at the called address, the switch supplies the service provider with the digits that were dialed (the called address). The service provider can be configured to associate particular called addresses with particular media modes. Likewise, it could associate calls from particular numbers as being associated with particular media modes, although this is much less commonly used.

•	Distinctive Ringing  The ring pattern of the incoming call may match a predetermined pattern (of several possible at the called address) that is reserved for calls of a certain media mode. If, for example, the incoming call is using ring pattern 2, the service provider knows it to be a fax call (based on configuration information supplied by the user).

•	ISDN  On an ISDN network, the provider may analyze the call's protocol frames to determine the media mode. If the call is indicated as a 3.1kHz Voice call, it is still possible that the actual media mode on the call is analog datamodem, Group 3 fax, text telephone, or any of several other voiceband modulated signals, in addition to human voice; it is only with digital data signals that the media mode would necessarily be clearly defined—for example as Group 4 fax—at call setup time in ISDN.

•	Auto Answer and Probe  Some providers give the user an option to let the service provider autoanswer the call and do some of the probing itself. In this process, TAPI gives the call the correct application with the correct media mode already identified.

These tools may be enough to make a final and accurate determination of the media mode. In any case, when the service provider passes the new call to TAPI, it sends a LINE_CALLSTATE message and includes in the message all that it knows about the call's media mode(s). The following sections give details on the possible cases.


 Known Media Mode

When the service provider knows the media of the call unambiguously, one flag is set in LINECALLINFO.dwMediaMode. The media mode cannot be the single bit LINEMEDIAMODE_UNKNOWN, which is a different scenario. TAPI gives ownership of the call to the highest priority application that has opened a line for this media mode. It also gives call handles with monitor privileges to all other monitor applications on the line.


 Unknown Media Mode

Even when the service provider does not know the exact media mode of the call, it might still know which media modes are possible. In this case, the service provider sets a combination of likely media mode bit flags, including LINEMEDIAMODE_UNKNOWN and passes the call to TAPI. The service provider sets these bits both in the dwMediaMode field of the LINECALLINFO record and in the dwParam3 parameter of the first LINE_CALLSTATE message it sends to TAPI.

The service provider considers only the media modes for which applications have opened the line with owner privileges (it becomes aware of these media modes through the TSPI_SetDefaultMediaDetection call) and which it is capable of handling. TAPI informs the provider about the union of all the lines that have been opened with a specified media mode. The provider can use this union to enable only the appropriate media mode detections for which applications are interested. If no applications have opened the line for ownership, the provider will not consider any media modes. Incoming calls are still delivered to TAPI, but no initial owner is possible. In this case, monitoring applications will still be informed of the call, and if none of them changes their privilege to owner and answers the call, the call will remain unanswered.


 Duties of the TAPI Dynamic Link Library

The TAPI dynamic link library does not perform probing; that is, it does not send signals on phone lines in order to determine a call's media mode. TAPI does try to deliver the call to an application that can do probing. The way in which TAPI gives calls to applications is determined by several factors, the most important of which are the media mode bits that have been set and the running applications that can (or cannot) handle calls of those media modes.

TAPI's behavior can be divided into two main scenarios: 1) One Media Mode Bit Is Set and 2) The UNKNOWN Bit Is Set. These cases are described in the following sections.


 Only One Media Mode Bit Is Set

If only one media-mode bit (not the UNKNOWN bit) has been set in the dwMediaMode field of the LINECALLINFO data structure, TAPI distributes calls by following a consistent procedure based on the current state of the system and on information saved by the user in the TELEPHON.INI file. These are the steps it takes:

•	The TAPI dynmaic link library is notified by the service provider that a call is arriving.

•	The TAPI library uses the information in the [HandoffPriorities] section of TELEPHON.INI to know which applications have been listed—possibly through a Preferences option in the application's user interface—as being interested in calls having the incoming call's media mode.

The first such application listed, reading left to right, is the highest priority application. If that application is currently running and has the arriving call's line open for that media mode, it is given ownership of the call. If it is not running or it does not have that line open, TAPI.DLL again uses the information in TELEPHON.INI to find an interested application in the correct state, and it gives the call to it.

•	If none of the applications listed in TELEPHON.INI are in the proper state, TAPI looks for other applications that are currently executing and have the line open for that media mode (though they are not listed in TELEPHON.INI). The relative priority among these unlisted applications is arbitrary and not necessarily associated with the sequence in which they were launched or opened the line.

•	Every application that has the line open for monitoring also receives a handle to a call, and any of them could step up, claim ownership (by calling lineSetCallPrivilege), and answer the call. However, this behavior could result in "race conditions" and unpredictable call handling, and is therefore discouraged.

•	If no application becomes an owner of the call, the call is eventually dropped. Calls can be dropped by TAPI only if no owner is found for the call and the call state is not idle or offering. The calling party can also drop the call. (On an ISDN network, this event becomes known when a "call-disconnect" frame is received.) If the call is not explicitly dropped, it can go idle after the expiration of a timeout based on the absence of ringing. (The service provider would need to assume that the call has been dropped by the calling party, and implement the timeout.) Because there were no applications that could take the call successfully, this situation usually means that the incoming call reached a wrong number.


 The UNKNOWN Bit Is Set

If the LINEMEDIAMODE_UNKNOWN bit is on in param3 of the first LINE_CALLSTATE message delivered by the service provider, the call is treated differently depending on whether an application prepared to accept calls of unknown media type has opened the line. These two possible cases (an Unknown application is running, or is not) are described in this section:


 An "Unknown" Application Is Running

If at least one Unknown application has opened the line, the TAPI dynamic link library gives an ownership handle for the incoming call to the highest priority Unknown application. It also passes monitoring handles to the other applications that have the line open for monitoring. The Unknown application receives a LINE_CALLSTATE message with dwParam3 set to owner.

This Unknown application can then try to perform media determination itself, or use the assistance of the other media applications, allowing them to perform "probes" for their media mode(s), if appropriate. The Unknown application can pass the call to another media application using lineHandoff. The Unknown application would examine LINECALLINFO.dwMediaMode to determine the possible remaining candidate media. In doing so, it uses the highest priority media to determine the initial handoff target. It calls lineHandoff, specifying the single highest priority destination media mode as the target.

The following is the default priority of media modes, listed in order from first tried to last tried when used during media-type handoffs:

Order	Media Mode
1	LINEMEDIAMODE_INTERACTIVEVOICE
2	LINEMEDIAMODE_DATAMODEM
3	LINEMEDIAMODE_G3FAX
4	LINEMEDIAMODE_TDD
5	LINEMEDIAMODE_G4FAX
6	LINEMEDIAMODE_DIGITALDATA
7	LINEMEDIAMODE_TELETEX
8	LINEMEDIAMODE_VIDEOTEX
9	LINEMEDIAMODE_TELEX
10	LINEMEDIAMODE_MIXED
11	LINEMEDIAMODE_ADSI
AUTOMATEDVOICE is a media mode that has no meaningful distinction with INTERACTIVEVOICE at this level, and is therefore not listed.

If the handoff fails, the Unknown application should clear that media mode flag in LINECALLINFO.dwMediaMode. This action moves the probe for the call one step closer to a final determination of the media mode. If the handoff indicates TARGETSELF, it means that the Unknown application is the highest priority application for the media mode for which it was trying to hand off the call, so it should go ahead and do the probing itself.

If the handoff indicates SUCCESS, it means that a different application is the highest priority application for the media mode for which the call was being handed off. The Unknown application should deallocate the call handle or change to being a monitor while the new owner has control and proceeds with probing.

The receiving application controls the call. If the probe is successful, it should set the correct media mode bit. If the probe fails, the application should clear the failed media mode bit in LINECALLINFO and hand the call off to the next highest priority application. If no more media mode bits are set, the handoff fails, because no suitable owner application exists for the call.

Eventually, the media mode may be identified through monitoring or successful probing, though the UNKNOWN bit still may be set in dwMediaMode in the data structure LINECALLINFO. In this case, the application that has received the call cannot be sure that it is the highest priority application for the identified media mode. It is now the duty of that application to ensure that the call goes to the highest priority application. To do so, it follows these steps:

•	It calls lineSetMediaMode, which writes into the dwMediaMode field of the call to turn off the UNKNOWN bit and specify the newly identified media mode bit.

•	It calls lineHandoff to return the call to TAPI. The TAPI dynamic link library is not explicitly specified in this command, but rather a media-type handoff is performed, through which the TAPI library knows that it must look for other applications to find the highest priority application for that media mode.

•	If this application is itself the highest priority application for this media mode, it receives a LINEERR_TARGETSELF return value (for the lineHandoff function call). This error means "No, you already are the highest priority application for that media mode." The application never loses control of the call, and it continues handling the call normally. If the lineHandoff succeeds, then there was a higher priority application for the identified media mode, and the application that called lineHandoff should deallocate its handle or change to being a monitor while the highest-priority application handles the call.

As long as the UNKNOWN bit is still on, the receiving application still does not know that the highest-priority media mode is present on the call, so it still needs to probe for it. It only considers the media mode to be present if the UNKNOWN bit is off—only then can it use the call as a call of that media mode.


 Using Media Priorities while Probing

Unknown applications should take care to use default priorities given in the preceding table when probing for applications to take calls of unknown media modes. One reason to do this is to protect human callers from hearing unpleasant fax or modem signals. If, for example, both the INTERACTIVEVOICE and the G3FAX bits are set in LINEMEDIAMODE_, a human caller may still be on the other end of the line. The application should wait to start probing for a fax (with a fax tone) until it is sure that the call is not a voice call. The way to be sure is to probe first for voice, which occurs automatically if following the order stated in the default media-mode list.

However, while probing for high-priority media modes, it is a good idea to turn media monitoring on. This feature, invoked by calling lineMonitorMedia, detects signals that indicate other media. For example, one application may be playing an outgoing "leave a message" voice message while the incoming call starts sending a fax "calling" tone and waits for a handshake. In order not to lose the fax call, the local application needs to be monitoring for this tone while playing the voice message. Determining the lower-priority media (the fax call) while actively probing for the higher-priority media (voice) is not only a safer method—it helps prevent the loss of a call—it is efficient because it can shorten the probing process.


 No "Unknown" Application Is Running

If no Unknown application has the line open, the TAPI dynamic link library itself assumes the role of a simplistic Unknown application. The TAPI library first passes an owner handle for the call to the highest priority application that is registered for the highest-priority media mode for which a media mode flag is set in LINECALLINFO.dwMediaMode. If there is no such application, the media mode flag is cleared, and TAPI tries the highest priority application for the next highest-priority media mode. If there is such an application, it can try to make a determination for the highest priority media mode in LINECALLINFO.dwMediaMode.

If no application is found to become the initial owner of a call, the call remains in the offering state until a monitor application becomes an owner through lineSetCallPrivilege, or until the call is abandoned by the calling party and is transitioned (by the service provider) to the idle state, at which time all monitoring applications deallocate their handles to the call.


 Duties of the Media Application

The media mode application that receives a call as a handoff target first checks the bit flags of LINECALLINFO.dwMediaMode. If only a single media mode flag is set, the call is officially of that media mode, and the application can act accordingly.

If the UNKNOWN and other media mode flags are set, the media mode of the call is officially UNKNOWN, but is assumed to be one of the media modes for which a flag is set in LINECALLINFO. The application should now probe for the highest priority media mode.

If more than one bit is set in LINECALLINFO and the call has not been answered, the application must perform a lineAnswer to continue probing. If the call has already been answered, the application can continue probing without having to first answer the call.

If the probe succeeds (either for the highest-priority media mode or for another one), the application should set LINECALLINFO.dwMediaMode to the single media mode that was recognized. If the actual media mode is this expected media mode, the application can act accordingly. Otherwise—if it makes a determination of another media mode—it must first attempt to hand off the call in case it is not the highest priority application for the detected media mode.

If the probe fails, the application should clear the flag for that media mode in LINECALLINFO.dwMediaMode, and hand the call off to the Unknown application. It should also deallocate its call handle or revert back to monitoring the call. At this point, the fate of the call is determined by the steps described under the preceding sections of this chapter—depending on whether or not an Unknown application is active.

If the attempt to hand off the call to the UNKNOWN application fails, this means that no unknown application is running. It is then the responsibility of the application that currently owns the call to attempt to hand it off to the next-highest-priority media mode (while leaving the UNKNOWN bit turned on in LINECALLINFO.dwMediaModes). If that handoff fails, the application should turn off that media bit, and attempt the next higher-priority bit, until the handoff succeeds or all of the bits are off except for the UNKNOWN bit.

If none of the media modes were determined to be the actual one, only the UNKNOWN flag will remain set in LINECALLINFO.dwMediaMode at the time the media application attempts to hand the call off to UNKNOWN. The final lineHandoff invocation will fail if the application is the only remaining owner of the call. This failure informs the application that it should drop the call and then deallocate the call's handle. At this point, the call is abandoned.


 Receiving Incoming Calls

Once the target application has been determined, it is given the call. The following points pertain to the target application as it accepts and answers calls:


 Accepting and Answering Calls

On a POTS network, the only reason for an application to call lineAccept is to inform other applications that it has accepted responsibility to present the call to the user. Similarly, on an ISDN line, the effect of accepting a call is to make other applications aware that some application has accepted responsibility for handling the call.

On an ISDN network, accepting a call also informs the switch that the application will present the call to the user (by alerting the user for example, by ringing or by "popping up" a dialog box). If the LINEADDRCAPFLAGS_ACCEPTTOALERT bit is set, the application must perform a lineAccept on the call or the call will not ring. If the application fails to call lineAccept quickly enough (the timeout may be as short as three seconds on some ISDN networks), the network will assume that the station is powered off or disconnected and act accordingly, such as by deflecting the call (if Forward on No Answer is activated) or sending a disconnect message to the calling station.

Accepting a call is not the same as answering a call. Answering calls, in POTS, simply means to go offhook. On an ISDN line, it means to tell the switch to place the call in a connected state. Before answering, there is no physical connection for the call between the switch and the destination, though the call is connected from the caller to the switch.

Sometimes a call has already been answered when a new application takes control of it. This can occur, for example, when one application discovers that it is not the highest priority application for a call of a given media mode, and it hands the call off. If the first application has already answered the call, the receiving application takes control of an answered call. It should treat the call normally—that is, as if it had answered the call itself. Another example is when a user instructs an application to operate on an existing call. In this case, the application seizes the call. Again, it should treat the call as if it had answered it.


 Waiting a Minimum Number of Rings

The lineGetNumRings function can be used by any application to determine the number of times an inbound call on the given address should ring before the call is to be answered. Waiting a certain number of rings allows callers to be spared the charge of a call connection if it seems that the call will not be answered by the desired party (usually a person). This feature is sometimes called toll-saver support. Applications can use the functions lineGetNumRings and lineSetNumRings in combination to provide a mechanism to support toll-saver features for multiple independent applications.

Any application that receives a handle for a call in the offering state and a LINE_LINEDEVSTATE ringing message should wait a number of rings equal to the number returned by lineGetNumRings before answering the call in order to honor the toll-saver settings across all applications. The function lineGetNumRings returns the minimum number of rings any application has specified with the function lineSetNumRings. Since this number may vary dynamically, an application should call lineGetNumRings each time it has the option to answer a call—that is, when it is the owner of a call still in the offering state. A separate LINE_LINEDEVSTATE ringing message is sent to the application for each ring cycle.

If the service provider is set to auto-answer calls, it answers after a certain number of rings. Service providers do not have access to the minimum-ring information established by lineSetNumRings, and therefore will make their own determination of when to automatically answer an incoming call. When a call has been so answered by a service provider, it will be initially delivered to the owning application already in the connected state, so the application will not need to be concerned with counting rings or with answering the call.


 Taking Ownership of a Call

In general, when one application learns that another application wants ownership of a call, it simply relinquishes ownership of the call to that other application. Although there can be many co-owners of a call, it should be a transitory state for there to be multiple owners.

In one specific case, it is valid for an application to actively take ownership of a call owned by another application. This is when the application is instructed to do so by the user—perhaps through a user interface. For example, a fax application may be instructed by a user to break into that same user's existing voice call and use the call to send a fax. In this case, the fax application takes ownership from the previous owner, the application that was controlling the voice call.

An application can forcibly become owner of a call by taking the following steps:

•	Obtain a handle to the call with monitor privilege. If the desired call is one for which the application does not yet have a handle, it should request a handle with lineGetNewCalls. If the application is already a co-owner of the call and wants to become sole owner, it should start by calling lineSetCallPrivilege with the parameter dwCallPrivilege set to LINECALLPRIVILEGE_MONITOR. This action, which relinquishes ownership of the call (temporarily, in this case), is seen by other applications as the departure of an owner.

•	Call lineSetCallPrivilege with the parameter dwCallPrivilege set to LINECALLPRIVILEGE_OWNER for the call. Other applications see a new owner coming on line by receiving a LINE_CALLINFO message stating that the number of owners has increased and the number of monitors has changed; the bit LINECALLINFOSTATE_NUMOWNERINCR is on. These applications should yield the call to the new owner but there is no guarantee that they will do so. If the other existing owners do relinquish ownership, the new owner can proceed with what it intended to do on the call.

Note  There is no way to shield a call from another application's attempt to become an owner of it, nor is there any reason to do so. Once an application is informed that another application has become an owner, it should draw its activities on the call to an orderly close, and then relinquish ownership, because such changes in ownership are almost always done at the explicit direction of the user.


 Relinquishing a Call

An application can relinquish ownership of a call by invoking lineSetCallPrivilege to change to a monitor application, or simply by using lineDeallocateCall to indicate that it has no further interest in the call. If the application is the sole owner of the call and cannot hand off ownership to another application, TAPI will not permit it to change to being a monitor or to deallocate its call handle—in this situation, the application has no choice but to drop the call.


 Control of the Media Stream

An application that has just obtained a call may not immediately receive control of the media stream, and may need to wait until the previous owner application relinquishes it. Though this may take time, any application with control of the media stream should transfer control when it sees that a new owner has come on line (the number of owners has increased).

The procedures for transferring control of an active media stream differ for every media-control API. The API may allow only one application to have a media-stream device (such as a COM port used for data transfer) open. In this case, it is important that the current owner relinquish control of a media stream device before handing off the call. But with some other types of media such as WAV audio, several applications (and several devices) can have the media stream open at the same time. This makes it unnecessary to close the media stream before the handoff, and perhaps not at all.


 Call Handoffs

After an application has acquired ownership of the call, ownership can be transferred to another application. Why would this be necessary? Normally, to allow the call's media mode to be changed. In this case, the highest priority application for the new media mode should take and handle the call. Media mode changing usually occurs because of one of these causes:

•	User Command  Through a user interface or through Windows messages, the application learns that the local user wants to change media mode. For example, the user has told the new "target" application (which is not yet an owner) to obtain an existing voice call for transmitting data. The target application must now take control of the call. In this case, the current owner notices the number of owners increase, and then relinquishes its control of the call.

Alternatively, the user could instruct the current owner of the call to hand it off to an application that can handle the new media mode.

•	Media Mode Change  The service provider can detect a media mode change with lineMonitorMedia. As an example of this, the local application is playing a recorded voice message to the caller. During this message, the caller spontaneously decides to transmit a fax calling tone, and the local application can respond accordingly by changing the media mode to fax and, if necessary, handing the call off to a fax application.

Another way this can work is for a monitoring application to enable media mode monitoring, and, when the media mode in which it is interested is detected on a call, it can request ownership of the call. This mechanism makes it unnecessary for every application to monitor every call for every media mode.

•	Remote Party Command  The remote party can interactively indicate a change in media modes during an existing call. For example, the local application is using lineMonitorDigits to monitor DTMF input by the remote caller. Through this monitoring, the caller indicates, for example, that a fax is about to be sent. Other ways the caller can control local applications is with commands received on other data connections and through ISDN user-user information messages.

A call handoff will have one of these outcomes:

•	the call is given to another application (SUCCESS),

•	the handing-off application is itself the target (TARGETSELF),

•	the handoff fails (TARGETNOTFOUND).

If the application that is receiving the handed-off call already has a call handle to the call, this old call handle is used. Otherwise a new call handle is created. In either case, the application ends up with owner privileges to the call. Whenever the handing-off application is not the same as the target application, the target is informed about the handoff in a LINE_CALLSTATE message with dwParam3 set to LINECALLPRIVILEGE_OWNER, as if it were receiving a new call.

Note  The LINE_CALLSTATE parameter dwParam3 is set to owner only if the LINE_CALLSTATE message is being sent to an application that is the initial owner of a new call, is the target of a handoff, or was previously a monitor or an owner of the call. The parameter dwParam3 can be set to monitor only if the LINE_CALLSTATE message is sent to the application when it is presented a new call for monitoring. In all other cases (such as when the application already has a handle to the call, and its ownership state is not being changed), dwParam3 is set to 0.

If the current owner application is told to change modes, it does so by handing off the call to an application used for the target media mode. The two types of call handoffs are described in the following sections:


 Directed Handoffs

A directed handoff takes place when the target application is known by name to the original application. This situation would occur, for example, among a set of applications written by the same vendor. Control of directed handoffs can usually be configured by the user. With such a handoff, the call is given to the specified application if it has opened the line on which the call exists. The media mode specified at the time the application opened the line is ignored. One common example is a voice call followed by fax transmission in the same call. Directed handoff would most often be used by applications from the same developer that are linked in other ways as well.

Directed handoff may also be used in future versions of Windows as part of the process of arbitrating multiple applications waiting for incoming calls of the same media mode, with the selection of the application to handle the call being based on data-link or higher level protocol detection rather than media mode. An example of its use would be an incoming datamodem line with applications such as remote takeover, bulletin board, remote network access, and remote email access all waiting for calls simultaneously.


 Media Mode Handoffs

A media mode handoff takes place when there is a new, targeted media mode, usually when the owning application determines that the media mode needed for the call is not present or is about to change. The process for a media-dependent handoff can be a probing process if the UNKNOWN bit is on, and is virtually the same as for the initial assignment of a call to an application. The difference is the fact that lineHandoff can have only one media-mode bit set.

Because only a single media mode bit can be specified, the call is given to the highest priority application for that media mode. However, it is possible that more than one media mode is to be considered for the handoff. In this case, the handing-off application should specify the highest-priority of the possible media modes as a parameter for lineHandoff. If an applications specifies the UNKNOWN bit when performing a media-mode handoff and the handoff fails, this means that no Unknown application is currently running. The handing off application should then try to hand the call off to the highest priority application registered for the next higher media mode.

The receiving application is now responsible for the call. It now probes for the call's actual media mode. If the call's media mode matches that handled by the application, it must ensure that it is the highest-priority application registered for that media mode. If so, it keeps the call and processes it normally. If not, it hands the call off to another application registered for that media mode.

If, however, the probe for that media mode fails, the application probes again, attempting the remaining media-mode possibilities. It determines these by examining the dwMediaMode field in the LINECALLINFO structure. But first, using the lineSetMediaMode function, the owning application turns off the bit for the current (disproved) media mode in the dwMediaMode field.

This process of probing and handing off continues, and the remaining media modes are eliminated one by one. Along the way, one of the applications may see that the media mode it handles is on the call, and the handoff is successful. The application should now perform a final lineSetMediaMode to set the correct media mode and clear all other media-mode bits. This informs other interested applications of the correct media mode. These other applications receive a LINE_CALLINFO message stating that the call's media mode has changed. To determine the correct media mode, they invoke lineGetCallInfo and examine the dwMediaMode field in the LINECALLINFO structure.

It is the responsibility of the owning application to cycle through media modes to find the highest-priority application. TAPI does this cycling only on the initial incoming call to find the first owner. It does not do it when lineHandoff is called.

To sum up the media-mode handoff process, TAPI does not check for other media bits during lineHandoff. TAPI only attempts to hand off to the single media mode indicated in the parameter to lineHandoff. It is up to the application to turn off the bit corresponding to the media mode that failed to hand off, and to try other media modes until the handoff succeeds or all the possible media modes are exhausted. If it gets to a point where all of the bits are off except for UNKNOWN, it must abandon the call by calling lineDrop and then deallocating the handle.


 Logging Calls

Logging a call simply means actively recording the actions and states of a monitored call into a file on a disk. (An application that owns a call is also a monitor of that call.) Though limited call logging is performed by the call manager provided with Windows Telephony, any application can be programmed to log a call that it is monitoring.

TAPI facilitates logging by allowing applications to monitor calls and by collecting information from other applications that are controlling calls. TAPI writes the information it collects into the LINECALLINFO structure, which can then be read by applications.


 Sources of Log Information

Information useful to call logging (which is saved by TAPI) originates in the following sources. This information is placed in the LINECALLINFO data structure.

• 	Initialization Function:  In an application's call of the initialization function (lineInitialize), it provides information such as the application's name. An application should ensure that the information it provides with the initialization command is accurate so that its activities are reflected correctly in the call log.

•	The LINECALLPARAMS data structure (used in the function lineMakeCall): This structure stores information such as the name of the called party, the originating address, and the destination address. This structure is passed to TAPI by any application that originates a call.

•	The Service Provider:  The service provider supplies many items that can be logged such as caller's ID.

•	The LINE_CALLSTATE messages that pertain to a given call are an important source of logging information because they indicate whether the call successfully connected or was abandoned because of a busy signal, no answer, network congestion, or other causes.

The start time, end time, and duration of a call are not recorded by TAPI. A logging application that wants to log this information must record the time by checking the system clock when certain LINE_CALLSTATE messages (such as CONNECTED, DISCONNECTED, and IDLE) are received, and then derive the related time log information.


 Using the LINECALLINFO Data Structure

The LINECALLINFO structure stores a large amount of information about a call, and is thus an important source of data. Generally, a logging application reads from LINECALLINFO and write this information into its log file.

A separate LINECALLINFO structure exists for every inbound and outbound call. Information in this structure is obtained by an application with lineGetCallInfo. An application typically reads the information from LINECALLINFO at the following times:

•	when the application first receives a handle for a call in the LINE_CALLSTATE message.

•	each time the application receives notification in a LINE_CALLINFO message that LINECALLINFO has changed. Whenever any part of the structure changes, a LINE_CALLINFO message is sent to the application indicating which information item has changed.

Both the LINE_CALLSTATE message and the LINE_CALLINFO message also supply the call's handle as a parameter.

Much of the information held in LINECALLINFO remains fixed for the duration of the call. Information about a call that changes dynamically, such as call progress status, is available in the LINECALLSTATUS structure, which is returned with the function call lineGetCallStatus. Other information needed by logging applications that is not stored in LINECALLINFO is call start time, call stop time, and the call's duration, which it determines by checking the system time when the corresponding LINE_CALLSTATE messages are received.

LINECALLINFO stays intact after the call is disconnected, so the logging application can later read it in order to write additional information into the log. LINECALLINFO remains available only until the last application that had a handle for the call (owner and monitor handles) deallocates its handle.


 Deallocating a Call

If an application is finished with a call and another application wants the call, the call can be handed off. But if no other applications want to take ownership, there is nothing to do but deallocate the call's handle. This is done with lineDeallocateCall. A call handle is no longer valid after it has been deallocated.

In contrast, dropping (disconnecting) a call puts the call in the idle state, which means that the local end of the connection is on hook. If the other end of the connection drops the call, the call transitions to the disconnected state, not the idle state. Typically, once an application receives a call-state message indicating the disconnected state, it immediately drops the call, causing it to become idle. Although the call is in the idle state, any handles to it held by applications remain valid until they are deallocated. If the call was never answered (the local end never went off hook), it may revert to the idle state without being dropped.

An application cannot deallocate a call if it is the sole owner and the call's state is not idle. This is because TAPI tries to ensure that there is always at least one owner for every active call. If the application is the sole owner and the call is not idle, the error message LINEERR_INVALCALLSTATE is returned. If an application needs to circumvent this restriction, it can do so by dropping the call first (with lineDrop) and then deallocating its handle. This prevents an application from deallocating its handle which would result in a call disconnect. By making the application do an explicit drop, it can inform the user (in a dialog box) that the call is about to be disconnected.

If releasing the ownership handle results in the call's having no more handles, TAPI calls the service provider function TSPI_lineCloseCall. When this function is invoked on a call that is not yet idle, it is up to the service provider to drop the call.

Note  An application that has monitor privileges for a call can always deallocate its handle for the call. Deallocating a call does not affect the call state of the physical call, but it does release the internal resources (memory) related to the call.

An application should deallocate the handle to a call it owns in these two cases:

•	Idle call state  If an application receives a LINE_CALLSTATE message indicating that the call has transitioned to the idle state, and has already gathered all the information it needs about the call, it should deallocate the call handle immediately.

•	Handoff  The application has handed off the call (or has otherwise relinquished call ownership to another application) or has set its call privilege to monitor, and has no interest in monitoring or logging the call.

Note that failure to deallocate call handles in a timely way can result in system failure and lost calls due to unnecessary consumption of memory and other resources.


 Closing Lines

An application should close a line it has open in the following cases:

•	Before Exiting  An application should always close all lines it has open before it becomes inactive.

•	For non-TAPI Applications  TAPI applications should cooperate with non-TAPI applications that use media stream devices such as COM ports. If your TAPI device is a serial device accessed through a COM port (such as a modem) and the line is open, the service provider needs to have the COM port open. But with the COM port open, non-TAPI Windows applications and DOS applications are prevented from accessing the COM port. Therefore, a TAPI application should open the line (and keep it open) only if it is waiting for incoming calls or it is actively engaged in placing an outgoing call.

Non-Telephony communications applications may need to share resources with Telephony applications.

The data structure LINEDEVCAPS contains a capabilities bit (LINEDEVCAPFLAGS_CLOSEDROP) that tells whether closing a line while a call is still active causes calls on the line to be dropped. If TRUE, calling lineClose drops (clears) all calls on the line if the application is the sole owner of those calls. If the bit is set to FALSE, lineClose does not automatically drop any calls still active on the line.

Therefore, an application can examine LINEDEVCAPS to detect in advance whether closing a line will cause this active call to be dropped. The application should warn all appropriate users that the call is about to be dropped, perhaps by displaying an OK/Cancel dialog box that lets the user keep the line open.

For example, if a desktop computer and a phoneset are both connected directly to an analog line (in a party-line configuration), the service provider should set the flag to FALSE, as the offhook phone would automatically keep the call active even after the computer powers down.

As another example, a user of Microsoft Windows is speaking on the phone on a call owned by an active application. The user decides to leave the office for the day and shuts down Windows. Windows in turn shuts down the active telephony application, which attempts to close the lines it has open. Whether the call is automatically hung up depends on whether the LINEDEVCAPFLAGS_CLOSEDROP bit in LINEDEVCAPS is set or not and whether the phone is off hook.

If other applications are monitoring the call, the service provider will not even be informed that one application has closed the line. It is only when the last application that has a handle to the call closes the line that the service provider is informed (with TSPI_lineClose). At that point, it is up to the service provider to handle any remaining calls. If the service provider is required to drop the calls, it should do so but it should first warn applications about this requirement with the LINEDEVCAPFLAGS_CLOSEDROP flag.

Closing an application should ideally perform the following cleanup tasks:

•	Dispose of all calls.

•	Close all open lines and phones.

•	Shut down the usage of the Telephony API.

Failure to do so may leave calls in indeterminate states.


 Learning About Existing Calls at Application Startup

Applications can become aware of existing calls on the line at the time of application startup with lineGetNewCalls. This function gives the application handles (with monitor privilege) to all the calls on the line or address for which it did not already have handles.

An example of the usefulness of this mechanism is when a user starts a fax application during a voice call, having decided to send a fax. The new fax application needs to discover the existing call (using lineGetNewCalls) to request ownership of the call in order to send the fax.


 Media Mode Updating

A call's media mode as stated in LINECALLINFO.dwMediaMode and a media mode message (LINE_MONITORMEDIA) sent from the service provider to the application can and often will differ. An application could use lineMonitorMedia to enable monitoring for particular media modes, and use any resulting LINE_MONITORMEDIA messages as guidance in determining what the calling party might be probing for or what the Unknown application should probe for first. LINE_MONITORMEDIA messages report events on the line (such as probes being received from the remote station) and not "hard" decisions about media modes. When an application determines that a call involves a particular media mode, it calls lineSetMediaMode to update LINECALLINFO.dwMediaMode and inform other applications of this update.


 Communication Between Applications

Applications can communicate with each other by writing to and reading from a field in a specified call's information record, the LINECALLINFO data structure. With lineSetAppSpecific, any owner application can write to the application-specific field called dwAppSpecific. It is uninterpreted by the Telephony API or any of its service providers. This field's usage is entirely controlled by applications.

The field can be read from the LINECALLINFO record returned by lineGetCallInfo. However, lineSetAppSpecific must be used to set the field so that changes become visible to other applications. When this field is changed, all other applications with call handles are sent a LINE_CALLINFO message with an indication that the dwAppSpecific field has changed.


 Special Cases

The following sections describe situations that could occur in multiple-application environments.


 A Call Without an Owner

What happens to an incoming call if no applications have the line open with owner privilege? First, TAPI informs all monitoring applications on the line about the call. If no monitoring application switches to owner privilege to answer the call, the service provider eventually drops the call.

The following steps describe what normally happens if a line has only monitoring applications, a call comes in, and no applications answer the call. Assume that the service provider is not configured to answer new calls by itself.

•	The service provider passes the call handle to TAPI.

•	TAPI passes monitor handles to the monitor applications.

•	TAPI determines that the call is in the offering (not connected) state and lets the call "sit."

•	The remote party eventually hangs up, and the call reverts to the idle call state since it was never connected.

•	The monitors are notified that the call is idle and deallocate their handles if they have not already done so.

•	The last deallocation causes a TSPI_lineCloseCall.

Although the call in this example was never answered, its appearance and disappearance may have been significant to the applications monitoring the line. On a network that offers caller-ID, a user may wish to screen incoming calls, recording who has called without necessarily answering every call. Monitoring applications can help accomplish this without ever needing to answer a call.


 The Call Is Answered Elsewhere

This scenario is similar to the first one, but the user answers the phone elsewhere on the line, and this answer is detected by the provider through the hardware. The call is reported as being in the connected state, though it is not connected to any application on the local computer. The call eventually goes idle, at which point each application (monitor as well as all owner applications) must deallocate its handle.

These are the steps of Scenario 2, in which a line has only monitoring applications,  the service provider is configured to not answer new calls by itself, and a call comes in.

•	The service provider passes the call handle to TAPI.

•	TAPI passes monitor handles to the monitor applications.

•	TAPI determines that the call in the offering (not connected) state and lets the call "sit."

•	The user picks up a ringing downline phone, and the call becomes connected.

•	All monitoring applications are sent a corresponding LINE_CALLSTATE message.

•	The user eventually hangs up the downline phone, and the call reverts to the idle state.

•	The monitor applications are notified the call is idle and deallocate their handles, if they have not already done so.

•	The last deallocation causes a TSPI_lineCloseCall.


 Auto-Answer by the Service Provider

In this scenario, the provider is set up to auto-answer a new call. The provider answers it and determines the call's media mode. It then informs TAPI of the call. Since no applications decide to take ownership, TAPI cannot pass the call to any application.

A line has only monitoring applications. The service provider is configured to auto-answer all new calls. At this point, a call comes in.

These are the steps:

•	The service provider passes the call handle to TAPI.

•	TAPI passes monitor handles to the monitor applications (the call is in the connected state).

•	TAPI realizes that the call is connected, but there are, so far, no potential owners.

•	TAPI must do a TSPI_lineDrop to cause the call to revert to idle.

•	The monitor applications are notified that the call is idle and deallocate their handles if they have not already done so.

•	The last deallocation causes a TSPI_lineCloseCall.

This last example illustrates an important point for writers of monitoring applications. It is not a good idea to wait monitor for incoming calls you later want to own. It is better to open the line as an owner, because there might not be enough time to change your privilege from monitor to owner before TAPI drops the call.


 Phone Devices

About Phone Devices

A phone device is one of the two device classes supported by TAPI. This chapter describes phone devices and explains how to use the TAPI phone functions to access these devices.


 The Phone Device

A device that supports the phone device class as a device that includes some or all of the following elements:

•	Hookswitch/Transducer  This is a means for audio input and output. The Telephony API recognizes that a phone device may have several transducers, which can be activated and deactivated (taken offhook or placed onhook) under application or manual user control. TAPI identifies three types of hookswitch devices common to many phone sets:

Handset  The traditional mouth-and-ear piece combination that must be manually lifted from a cradle and held against the user's ear.

Speakerphone  Enables the user to conduct calls hands-free. The hookswitch state of a speakerphone can usually be changed both manually and by the API. The speakerphone may be internal or external to the phone device. The speaker part of a speakerphone allows multiple listeners.

Headset  Enables the user to conduct calls hands-free. The hook switch state of a headset can usually be changed both manually and by the API.

A hookswitch must be offhook to allow audio data to be sent to and/or received by the corresponding transducer.

•	Volume Control/Gain Control/Mute  Each hookswitch device is the pairing of a speaker and a microphone component. The API provides for volume control and muting of speaker components and for gain control or muting of microphone components.

•	Ringer  A means for alerting users, usually through a bell. A phone device may be able to ring in a variety of modes or patterns.

•	Display  A mechanism for visually presenting messages to the user. A phone display is characterized by its number of rows and columns.

•	Buttons  An array of buttons. Whenever the user presses a button on the phone set, the API reports that the corresponding button was pressed. Button-Lamp IDs identify a button and lamp pair. Of course, it is possible to have button-lamp pairs with either no button or no lamp. Button-lamp IDs are integer values that range from 0 to the maximum number of button-lamps available on the phone device, minus one. Each button belongs to a button class. Classes include call appearance buttons, feature buttons, keypad buttons, and local buttons.

•	Lamps  An array of lamps (such as LEDs) individually controllable from the API. Lamps can be lit in different modes by varying the on and off frequency. The button-lamp ID identifies the lamp.

•	Data Areas  Memory areas in the phone device where instruction code or data can be downloaded to and/or uploaded from. The downloaded information would affect the behavior (or in other words, program) the phone device.

TAPI allows an application to monitor and control elements of the phone device. The most useful elements for an application are the hookswitch devices. The phone set can act as an audio I/O device (to the computer) with volume control, gain control and mute, a ringer (for alerting the user), data areas (for programming the phone), and perhaps a display, though the computer's display is more capable. The application writer is discouraged from directly controlling or using phone lamps or phone buttons, since lamp and button capabilities can vary widely among phone sets, and applications can quickly become tailored to specific phone sets.

There is no guaranteed core set of services supported by all phone devices as there is for line devices (the Basic Telephony services). Therefore, before an application can use a phone device, the application must first determine the exact capabilities of the phone device. Telephony capability varies with the configuration (client versus client-server), the telephone hardware, and the service-provider software. Applications should make no assumptions as to what telephony capabilities are available. An application determines the device capabilities of a phone device by calling the phoneGetDevCaps function. A phone's device capabilities indicate which of these elements exist for each phone device present in the system and what their capabilities are. Although strongly oriented towards real-life telephone sets, this abstraction can provide a meaningful implementation (or subset thereof) for other devices as well. Take as an example a separate headset directly connected and controllable from the computer and operated as a phone device. Hookswitch changes can be triggered by detection of voice energy (offhook) or a period of silence (onhook); ringing can be emulated by the generation of an audible signal into the headset; a display can be emulated through text-to-speech conversion.

Note that a phone device need not be realized in hardware, but can instead be emulated in software using a mouse- or keyboard-driven graphical command interface and the computer's speaker or sound system. Such a "soft phone" can be an application that uses TAPI. It can also be a service provider, which can be listed as a phone device available to other applications through the API, and as such is assigned a phone device ID.

Depending on the environment and configuration, phone sets can be shared devices between the application and the switch. Some minor provision is made in the API where the switch may temporarily suspend the API's control of a phone device.


 Initialization and Shutdown

For an application to use any of TAPI's 30 supplementary phone functions, it needs a connection to TAPI.DLL, through which it can receive messages. The application establishes this connection using the phoneInitialize function. One of the parameters passed to TAPI.DLL in these function calls is a pointer to the application's callback function. After initialization, TAPI uses this pointer to notify the application of the asynchronous completion of functions.

The phoneInitialize function returns two pieces of information to the application: an application handle, and the number of phone devices. The application handle represents the application's usage of TAPI. The TAPI functions that use phone handles do not require the application handle, as this handle is derived from the specified phone handle.

The second piece of information returned by phoneInitialize is the number of phone devices available to the application through the Telephony API. Phone devices are identified by their device identifier (device ID). Valid device IDs range from zero to the number of phone devices minus one. For example, if phoneInitialize reports that there are two phone devices in a system, then valid phone device IDs are 0 and 1. Once an application is finished using the phone functions of TAPI, it invokes phoneShutdown, passing its application handle to shut down its usage of TAPI. This allows TAPI to free any resources assigned to the application.

Both phoneInitialize and phoneShutdown operate synchronously. That is, these functions either return a success or failure indication, and never return an asynchronous Request ID.


 Opening and Closing Phone Devices

After determining the capabilities of a phone device, an application must open the device before it can access functions on that phone. After a phone device has been successfully opened, the application is returned a handle representing the open phone. A phone device can be opened in different modes, thus providing a structured way of sharing a phone device.

The function phoneOpen opens the specified phone device to give the application access to functions on the phone. A phone device is identified to phoneOpen by means of its device ID, which is passed as the parameter dwDeviceID.


 Operating Modes and Privileges

The application can request one of two operating modes when opening a phone device. These modes reflect the privileges the application requests for the device:

•	Opening a phone for monitor privileges lets the application determine the status of the phone device. Messages are sent to the application's callback function when status changes on the phone device are detected.

•	An application that opens a phone device for owner privileges can use operations that modify the state of the phone device. Owner privilege automatically includes full monitor privileges as well. At any time, a given phone device can be open only once for owner privileges, but multiple times for monitor privileges. All phoneSet operations require owner privileges, while all phoneGet operations require only monitor privileges.


 Device IDs

Other TAPI phone functions use a handle to an open phone device to identify the open phone device. The only functions for phone devices that take a phone device ID parameter (as opposed to a phone handle) are the phoneGetDevCaps and phoneOpen functions. An application can retrieve the phone's device ID by using the function phoneGetID with the phone handle as a parameter.

An application can also obtain device IDs for various Windows device classes associated with an opened phone by invoking phoneGetID. See Chapter 9, "Device Classes" device class names.

This function takes a phone handle and a device class description. It returns the device ID for the device of the given device class that is associated with the open phone device. If the device class is "tapi/phone," the device ID of the phone device is returned.

In contrast with line devices, for which the basic line services provide the equivalent of POTS, no minimum guaranteed set of functions is defined for phone devices. While each phone device provides at least the functions and messages described in this section, they do not offer any actual operations on the physical phone device.


 Closing the Phone Device

The function phoneClose closes the specified phone device. The phone device may also be forcibly closed after the user has modified the configuration of that phone or its driver. If the user wants the configuration changes to be effective immediately (as opposed to after the next system restart), and they affect the application's current view of the device (such as a change in device capabilities), then a service provider may forcibly close the phone device.

Note that these messages can also be sent unsolicited as a result of the phone device being reclaimed in some other manner. An application should therefore be prepared to handle unsolicited PHONE_CLOSE messages. At the time the phone device is closed, any outstanding asynchronous replies pertaining to that device are suppressed.


 Hookswitch Devices

A phone device may have multiple hookswitch devices. (A hookswitch is the switch that connects or disconnects a device from the phone line. On a telephone, for example, this is the switch that is automatically activated when a user lifts the receiver from the cradle to get a new dial tone.) The Telephony API defines three types of hookswitch devices for a phone: handset, speakerphone, and headset. Each hookswitch device has a speaker and a microphone component, and operates in one of four hookswitch modes:

•	Onhook  The hookswitch device is onhook, and both its microphone and speaker are disabled.

•	Microphone only  The hookswitch device is offhook, its microphone is enabled, and its speaker is mute.

•	Speaker only  The hookswitch device is offhook, its microphone is mute, and its speaker is enabled.

•	Microphone and speaker  The hookswitch device is offhook, and both microphone and speaker are enabled.

The phoneSetHookSwitch function is used to set the hookswitch mode of one or more of the hookswitch devices of an open phone device. For example, to mute or unmute the microphone or speaker component of a hookswitch device, use phoneSetHookSwitch with the appropriate hookswitch mode. The function phoneGetHookSwitch can be used to query the hookswitch mode of a hookswitch device of an open phone device.

When the mode of a phone's hookswitch device is changed manually, for example by lifting the handset from its cradle, a PHONE_STATE message is sent to the application's callback to notify the application about the state change. Parameters to this message provide an indication of the change.

The volume of the speaker component of a hookswitch device can be set with phoneSetVolume. Note that volume setting is different from mute in that muting a speaker and later unmuting it will preserve the volume setting of the speaker. The phoneGetVolume function can be used to return the current volume setting of a hookswitch device's speaker of an open phone device.

The microphone component of a hookswitch device can also be gain controlled. Note that gain setting is different from mute in that muting a microphone and later unmuting it will preserve the gain setting of the microphone. Use phoneSetGain to set the gain of a hookswitch device's microphone of an open phone device, and phoneGetGain to return the gain setting of a hookswitch device's microphone of an opened phone.

When the volume or gain of a phone's hookswitch device is changed, a PHONE_STATE message is sent to the application's callback function to notify the application about the state change. Parameters to this message provide an indication of the change.


 Display

The Telephony API provides access to a phone's display. The display is modeled as an alphanumeric area with rows and columns. A phone's device capabilities indicate the size of a phone's display as the number of rows and the number of columns. Both these numbers are zero if the phone device does not have a display. Use phoneSetDisplay to write information to the display of an open phone device, and phoneGetDisplay to retrieve the current contents of a phone's display.

When the display of a phone device is changed, a PHONE_STATE message is sent to the application's callback function to notify the application about the state change. Parameters to this message provide an indication of the change.


 Ring

A single phone may be able to ring with different ring modes. Given the wide variety of ring modes available, ring modes are identified by means of their ring mode number. A ring mode number ranges from zero to the number of available ring modes minus one.

The functions an application would use to control a phone device's ring modes are phoneSetRing, which rings an open phone device according to a given ring mode, and phoneGetRing, which returns the current ring mode of an opened phone device.

When the ring mode of a phone device is changed, a PHONE_STATE message is sent to the application's callback function to notify the application about the state change. Parameters to this message provide an indication of the change.


 Buttons

The Telephony API models a phone's buttons and lamps as button-lamp pairs. A button with no lamp next to it or a lamp with no button is specified using a "dummy" indicator for the missing lamp or button. A button with multiple lamps is modeled by using multiple button-lamp pairs.

Information associated with a phone button can be set and retrieved. When a button is pressed, a PHONE_BUTTON message is sent to the application's callback function. The parameters of this message are a handle to the phone device and the button-lamp ID of the button that was pressed. The keypad buttons '0' through '9', '*', and '#' are assigned the fixed button-lamp IDs 0 through 11.

The functions associated with buttons are phoneSetButtonInfo, which sets the information associated with a button on a phone device, and phoneGetButtonInfo, which returns information associated with a button on a phone device. The PHONE_BUTTON message is sent to an application's callback when a button on the phone is pressed.

The information associated with a button does not carry any semantic meaning as far as TAPI is concerned. It is useful for device-specific applications that understand the meaning of this information for a given phone device, or for display to the user, such as online help.


 Lamps

The lamps on a phone device can be lit in a variety of different lighting modes. Unlike ringing patterns, lamp modes are more uniform across phone sets of different vendors. A common set of lamp modes is defined by the API. A lamp identified by its lamp-button ID can be lit in a given lamp mode. A lamp can also be queried for its current lamp mode.

The TAPI functions used for lamps are phoneSetLamp, which lights a lamp on a specified open phone device in a given lamp lighting mode, and phoneGetLamp, which returns the current lamp mode of the specified lamp.

When a lamp of a phone device is changed, a PHONE_STATE message is sent to the application's callback function to notify the application about the state change. Parameters to this message provide an indication of the change.


 Data Areas

Some phone sets support the notion of downloading data from or uploading data to the phone device, which allows the phone set to be programmed in a variety of ways. The Telephony API models these phone sets as having one or more download or upload areas. Each area is identified by a number that ranges from zero to the number of data areas available on the phone minus one. Sizes of each area may vary. The format of the data itself is device-specific.

The TAPI phoneSetData function downloads a buffer of data to a given data area in the phone device, and the phoneGetData function uploads the contents of a given data area in the phone device to a buffer.

When a data area of a phone device is changed, a PHONE_STATE message is sent to the application's callback function to notify the application about the state change. Parameters to this message provide an indication of the change.


 Status

Most of the get and set operations deal with one component of information only. The phoneGetStatus function returns complete status information about a phone device to an application.

As mentioned earlier, whenever a status item changes on the phone device, a PHONE_STATE message is sent to the application's callback function. This message's parameters include a handle to the phone device and an indication of the status item that changed.

An application can use phoneSetStatusMessages to select the specific status changes for which it wants to be notified through the callback. Correspondingly, phoneGetStatusMessages returns the status changes for which the application wants to be notified.


 Extended-Telephony Phone Functions

The Extended Phone Services (or Device-Specific Phone Services) include all extensions to the Telephony API defined by the service provider. TAPI defines a mechanism that enables service-provider vendors to extend TAPI using device-specific extensions. TAPI defines only the extension mechanism, and by doing so provides access to device-specific extensions. The Telephony API does not define their behavior, which is completely defined by the service provider.

TAPI consists of scalar and bit-flag data constant definitions, data structures, functions, and callback messages. Procedures are defined that enable a vendor to extend most of these as follows:


 Scalar Data Constants

For extensible scalar data constants, a service-provider vendor may define new values in a specified range. Since most data constants are DWORDs, the range 0x00000000 through 0x7FFFFFFF is typically reserved for common future extensions, while 0x80000000 through 0xFFFFFFFF is available for vendor-specific extensions. The assumption is that a vendor would define values that are natural extensions of the data types defined by the API.


 Bit-Flag Data Constants

For extensible bit-flag data constants, a service-provider vendor may define new values for specified bits. Since most bit-flag constants are DWORDs, a specific number of the lower bits are usually reserved for common extensions, while the remaining upper bits are available for vendor-specific extensions. Common bit flags are assigned from bit zero up, and vendor-specific extensions should be assigned from bit 31 down. This scheme provides maximum flexibility in assigning bit positions to common extensions, as opposed to vendor-specific extensions. A vendor is expected to define new values that are natural extensions of the bit flags defined by the API.

Extensible data structures have a variably sized field that is reserved for device-specific use. Because the field is variably sized, the service provider decides the field's amount of information and interpretation. A vendor that defines a device-specific field is expected to make these natural extensions of the original data structure defined by the API.


 Functions and Messages

The phoneDevSpecific function and its associated PHONE_DEVSPECIFIC message enable an application to access device-specific phone features that are unavailable through the common Telephony services for phones. In other words, phoneDevSpecific is the device-specific escape function that allows vendor-dependent extensions, and PHONE_DEVSPECIFIC is the device-specific message that is sent to the application's callback function.

The parameter profile of the phoneDevSpecific function is generic in that little interpretation of the parameters is made by the Telephony API. Rather, the interpretation of the parameters is defined by the service provider and must be understood by an application that uses them. The parameters are simply passed through by TAPI.DLL from the application to the service provider. An application that relies on device-specific extensions will usually not work with other service providers, but applications written to the common telephony phone services will work with the extended service provider.


 Line Device Functions

About Line Device Functions

This chapter contains an alphabetical list of the functions in the Telephony Applications Programming Interface (API).

The information for each function includes a list of the valid call states on entry of the function and typical call state transitions when the request completes. Note that the actual states in which a function may be performed may be further limited by the capabilities of the service provider; applications must check the dwCallFeatures field in the LINECALLSTATUS structure, the dwAddressFeatures field in the LINEADDRESSSTATUS structure, and the dwLineFeatures field in the LINEDEVSTATUS structure to determine whether or not a function is permitted at that point in time.


 Reference

Following are the Telephony API functions.


 lineAccept

[New - Windows 95]

LONG lineAccept(HCALL hCall, LPCSTR lpsUserUserInfo, DWORD dwSize)

Accepts the specified offered call. It may optionally send the specified user-to-user information to the calling party.

•	Returns a positive request ID if the function will be completed asynchronously, or a negative error number if an error has occurred. The dwParam2 parameter of the corresponding LINE_REPLY callback message is zero if the function is successful or it is a negative error number if an error has occurred. Possible return values are:

LINEERR_INVALCALLHANDLE	LINEERR_RESOURCEUNAVAIL
LINEERR_INVALCALLSTATE	LINEERR_OPERATIONUNAVAIL
LINEERR_NOTOWNER	LINEERR_UNINITIALIZED
LINEERR_INVALPOINTER	LINEERR_OPERATIONFAILED
LINEERR_NOMEM	LINEERR_USERUSERINFOTOOBIG
hCall

Specifies a handle to the call to be accepted. The application must be an owner of the call. Call state of hCall must be offering.

lpsUserUserInfo

Specifies a pointer to a string containing user-to-user information to be sent to the remote party as part of the call accept. This pointer can be left NULL if no user-to-user information is to be sent. User-to-user information is only sent if supported by the underlying network (see LINEDEVCAPS). The protocol discriminator field for the user-user information, if required, should appear as the first byte of the buffer pointed to by lpsUserUserInfo, and must be accounted for in dwSize.

dwSize

Specifies the size in bytes of the user-to-user information in lpsUserUserInfo. If lpsUserUserInfo is NULL, no user-to-user information is sent to the calling party and dwSize is ignored.

The lineAccept function is used in telephony environments like Integrated Services Digital Network (ISDN) that allow alerting associated with incoming calls to be separate from the initial offering of the call. When a call comes in, it is first offered. For some small amount of time, the application may have the option to reject the call using lineDrop, redirect the call to another station using lineRedirect, answer the call using lineAnswer, or accept the call using lineAccept. After a call has been successfully accepted, alerting at both the called and calling device begins. After a call has been accepted by an application, the call state typically transitions to accepted.

Alerting is reported to the application by the LINE_LINEDEVSTATE message with the ringing indication.

The lineAccept function may also be supported by non-ISDN service providers. The call state transition to accepted can be used by other applications as an indication that another application has claimed responsibility for the call and has presented the call to the user.

The application has the option to send user-to-user information at the time of the accept. Even if user-to-user information is sent, there is no guarantee that the network will deliver this information to the calling party. An application should consult a line's device capabilities to determine whether call accept is available.


 lineAddProvider

[New - Windows 95]

LONG lineAddProvider(LPCSTR lpszProviderFilename, HWND hwndOwner,
    LPDWORD lpdwPermanentProviderID)

Installs a new Telephony Service Provider into the Telephony system.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

LINEERR_INIFILECORRUPT	LINEERR_NOMEM
LINEERR_INVALPARAM	LINEERR_OPERATIONFAILED
LINEERR_INVALPOINTER
lpszProviderFilename

Specifies a pointer to a NULL-terminated string containing the pathname of the service provider to be added.

hwndOwner

Specifies a handle to a window to which the any dialogs which need to be displayed as part of the installation process (e.g., by the service provider's TSPI_providerInstall function) would be attached.

lpdwPermanentProviderID

Specifies a pointer to a DWORD-sized memory location into which TAPI writes the permanent provider ID of the newly-installed service provider.

During this function call, TAPI checks to insure that it can access the service provider by calling its TSPI_providerInstall function; if this is unsuccessful (if the DLL or function cannot be found, or if TSPI_providerInstall returns an error), the function fails and the provider is not added to the telephony system. If this is successful, and the Windows Telephony system is active (one or more applications have called lineInitialize), TAPI will attempt to activate the service provider by calling TSPI_providerEnumDevices and TSPI_providerInit (and other startup functions). If these functions fail, the provider will have been installed but not activated. If the activation succeeds, applications will be informed of any new devices created via LINE_CREATE or PHONE_CREATE messages, or by a LINE_LINEDEVSTATE message requesting reinitialization (if the application does not support the CREATE messages).

This function copies no files − not the service provider DLL itself nor any supporting files; it is the responsibility of the application managing the addition of the provider to insure that the provider is installed in a directory where it can be found by TAPI (e.g., \WINDOWS, \WINDOWS\SYSTEM, or elsewhere on the path), and that all other files necessary for operation.

Although this is a new function which older applications would not be expected to call, for backward compatibility, they should not be prevented from doing so; the function will work the same way for all applications.


 lineAddToConference

[New - Windows 95]

LONG lineAddToConference(HCALL hConfCall, HCALL hConsultCall)

Adds the call specified by hConsultCall to the conference call specified by hConfCall.

•	Returns a positive request ID if the function will be completed asynchronously, or a negative error number if an error has occurred. dwParam2 of the corresponding LINE_REPLY callback message is zero if the function is successful or it is a negative error number if an error has occurred. Possible return values are:

LINEERR_CONFERENCEFULL	LINEERR_NOTOWNER
LINEERR_INVALCONFCALLHANDLE	LINEERR_OPERATIONUNAVAIL
LINEERR_INVALCALLHANDLE	LINEERR_OPERATIONFAILED
LINEERR_INVALCALLSTATE	LINEERR_RESOURCEUNAVAIL
LINEERR_NOMEM	LINEERR_UNINITIALIZED
hConfCall

Specifies a handle to the conference call. The application must be an owner of this call. Any monitoring (media, tones, digits) on a conference call applies only to the hConfCall, not to the individual participating calls. Call state of hConfCall must be onHoldPendingConference or onHold.

hConsultCall

Specifies a handle to the call to be added to the conference call. The application must be an owner of this call. This call cannot be a parent of another conference or a participant in any conference. Depending on the device capabilities indicated in LINEADDRESSCAPS, the hConsultCall may not necessarily have been established using lineSetupConference or linePrepareAddToConference. Call state of hConsultCall must be connected or onHold. The valid call states for the hConsultCall parameter also include proceeding and ringback. Many PBXes allow calls to be added to conferences before they are actually answered.

If LINEERR_INVALCALLHANDLE is returned, the specified call handle for the added call is invalid, hConsultCall is a parent of another conference or already a participant in a conference, hConsultCall cannot be added for other reasons (such as, it must have been established using lineSetupConference or linePrepareAddToConference), or hConsultCall and hConfCall are calls on different open lines.

The call handle of the added party remains valid after adding the call to a conference. Its state typically changes to conferenced while the state of the conference call typically becomes connected. Using lineGetConfRelatedCalls, you can obtain a list of call handles that are part of the same conference call as the specified call. The specified call is either a conference call or a participant call in a conference call. New handles are generated for those calls for which the application does not already have handles, and the application is granted monitor privilege to those calls. The handle to an individual participating call can be used later to remove that party from the conference call using lineRemoveFromConference.

Note that if lineGetConfRelatedCalls is called immediately after lineAddToConference, it may not return a complete list of related calls because TAPI.DLL waits to receive a LINE_CALLSTATE message indicating that the call has entered LINECALLSTATE_CONFERENCED before it considers the call to actually be part of the conference (that is, the conferenced state is confirmed by the service provider). Once the application has received the LINE_CALLSTATE message, lineGetConfRelatedCalls returns complete information. Note that all calls that are part of a conference must exist on the same open line.

The call states of the calls participating in a conference are not independent. For example, when dropping a conference call, all participating calls may automatically become idle. An application should consult the line's device capabilities to determine what form of conference removal is available. The application should track the LINE_CALLSTATE messages to determine what happened to the calls involved.

The conference call is established either by lineSetupConference or lineCompleteTransfer. The call added to a conference is typically established using lineSetupConference or linePrepareAddToConference. Some switches may allow adding arbitrary calls to the conference, and such a call may have been set up using lineMakeCall and be on (hard) hold. The application may examine the dwAddrCapFlags field of the LINEADDRESSCAPS structure to determine the permitted operations.


 lineAnswer

[New - Windows 95]

LONG lineAnswer(HCALL hCall, LPCSTR lpsUserUserInfo, DWORD dwSize)

Answers the specified offering call.

•	Returns a positive request ID if the function will be completed asynchronously, or a negative error number if an error has occurred. The dwParam2 parameter of the corresponding LINE_REPLY callback message is zero if the function is successful or it is a negative error number if an error has occurred. Possible return values are:

LINEERR_INUSE	LINEERR_OPERATIONUNAVAIL
LINEERR_INVALCALLHANDLE	LINEERR_OPERATIONFAILED
LINEERR_INVALCALLSTATE	LINEERR_RESOURCEUNAVAIL
LINEERR_INVALPOINTER	LINEERR_UNINITIALIZED
LINEERR_NOMEM	LINEERR_USERUSERINFOTOOBIG
LINEERR_NOTOWNER
hCall

Specifies a handle to the call to be answered. The application must be an owner of this call. Call state of hCall must be offering or accepted.

lpsUserUserInfo

Specifies a pointer to a string containing user-to-user information to be sent to the remote party at the time of answering the call. This pointer can be left NULL if no user-to-user information is to be sent. User-to-user information is only sent if supported by the underlying network (see LINEDEVCAPS). The protocol discriminator field for the user-user information, if required, should appear as the first byte of the buffer pointed to by lpsUserUserInfo, and must be accounted for in dwSize.

dwSize

Specifies the size in bytes of the user-to-user information in lpsUserUserInfo. If lpsUserUserInfo is NULL, no user-to-user information is sent to the calling party and dwSize is ignored.

When a new call arrives, applications with an interest in the call are sent a LINE_CALLSTATE message to provide the new call handle and to inform the application about the call's state and the privileges to the new call (such as monitor or owner). The application with owner privilege for the call can answer this call using lineAnswer. After the call has been successfully answered, the call typically transitions to the connected state. Initially, only one application is given owner privilege to the inbound call.

In some telephony environments (like ISDN), where user alerting is separate from call offering, the application may have the option to accept a call prior to answering or to reject or redirect the offering call.

If a call comes in (is offered) at the time another call is already active, the new call is connected to by invoking lineAnswer. The effect this has on the existing active call depends on the line's device capabilities. The first call may be unaffected, it may automatically be dropped, or it may automatically be placed on hold. The appropriate LINE_CALLSTATE messages report state transitions to the application about both calls.

The application has the option to send user-to-user information at the time of the answer. Even if user-to-user information can be sent, there is no guarantee that the network will deliver this information to the calling party. An application should consult a line's device capabilities to determine whether sending user-to-user information upon answering the call is available.


 lineBlindTransfer

[New - Windows 95]

LONG lineBlindTransfer(HCALL hCall, LPCSTR lpszDestAddress,
    DWORD dwCountryCode)

Performs a blind or single-step transfer of the specified call to the specified destination address.

•	Returns a positive request ID if the function will be completed asynchronously, or a negative error number if an error has occurred. The dwParam2 parameter of the corresponding LINE_REPLY callback message is zero if the function is successful or it is a negative error number if an error has occurred. Possible return values are:

LINEERR_INVALCALLHANDLE	LINEERR_INVALCOUNTRYCODE
LINEERR_INVALCALLSTATE	LINEERR_INVALPOINTER
LINEERR_NOMEM	LINEERR_OPERATIONUNAVAIL
LINEERR_NOTOWNER	LINEERR_RESOURCEUNAVAIL
LINEERR_INVALADDRESS	LINEERR_UNINITIALIZED
LINEERR_ADDRESSBLOCKED	LINEERR_OPERATIONFAILED
hCall

Specifies a handle to the call to be transferred. The application must be an owner of this call. Call state of hCall must be connected.

lpszDestAddress

Specifies a pointer to a NULL-terminated string identifying where the call is to be transferred to. The destination address uses the standard dialable number format.

dwCountryCode

Specifies the country code of the destination. This is used by the implementation to select the call progress protocols for the destination address. If a value of zero is specified, a default call-progress protocol defined by the service provider is used.

If LINEERR_INVALADDRESS is returned, no dialing has occured.

Blind transfer differs from a consultation transfer in that no consultation call is made visible to the application. After the blind transfer successfully completes, the specified call is typically cleared from the application's line, and it transitions to the idle state. Note that the application's call handle remains valid after the transfer has completed. The application must deallocate its handle when it is no longer interested in the transferred call. It uses lineHandoff for this purpose.


 lineClose

[New - Windows 95]

LONG lineClose(HLINE hLine)

Closes the specified open line device.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

LINEERR_INVALLINEHANDLE	LINEERR_RESOURCEUNAVAIL
LINEERR_NOMEM	LINEERR_UNINITIALIZED
LINEERR_OPERATIONFAILED	LINEERR_OPERATIONUNAVAIL
hLine

Specifies a handle to the open line device to be closed. After the line has been successfully closed, this handle is no longer valid.

If an application calls lineClose while it still has active calls on the opened line, the application's ownership of these calls is revoked. If the application was the sole owner of these calls, the calls are dropped as well. It is good programming practice for an application to dispose of the calls it owns on an opened line by explicity relinquishing ownership and/or by dropping these calls prior to closing the line.

If the close was successful, a LINE_LINEDEVSTATE message is sent to all applications that are monitoring the line status of open/close changes. Outstanding asynchronous replies are suppressed.

Service providers may find it useful or necessary to forcibly reclaim line devices from an application that has the line open. This may be useful to prevent a misbehaved application from monopolizing the line device for too long. If this happens, a LINE_CLOSE message is sent to the application, specifying the line handle of the line device that was closed.

The lineOpen function allocates resources to the invoking application, and applications may be prevented from opening a line if resources are unavailable. Therefore, an application that only occasionally uses a line device (such as for making outbound calls) should close the line to free resources and allow other applications to open the line.


 lineCompleteCall

[New - Windows 95]

LONG lineCompleteCall(HCALL hCall, LPDWORD lpdwCompletionID,
    DWORD dwCompletionMode, DWORD dwMessageID)

Specifies how a call that could not be connected normally should be completed instead. The network or switch may not be able to complete a call because network resources are busy or the remote station is busy or doesn't answer. The application can request that the call be completed in one of a number of ways.

•	Returns a positive request ID if the function will be completed asynchronously, or a negative error number if an error has occurred. The dwParam2 parameter of the corresponding LINE_REPLY callback message is zero if the function is successful or it is a negative error number if an error has occurred. Possible return values are:

LINEERR_COMPLETIONOVERRUN	LINEERR_NOMEM
LINEERR_INVALCALLCOMPLMODE	LINEERR_NOTOWNER
LINEERR_INVALCALLSTATE	LINEERR_OPERATIONUNAVAIL
LINEERR_INVALCALLHANDLE	LINEERR_OPERATIONFAILED
LINEERR_INVALMESSAGEID	LINEERR_RESOURCEUNAVAIL
LINEERR_INVALPOINTER	LINEERR_UNINITIALIZED
hCall

Specifies a handle to the call whose completion is requested. The application must be an owner of the call. Call state of hCall must be busy, ringback.

lpdwCompletionID

Specifies a pointer to a DWORD-sized memory location. The completion ID is used to identify individual completion requests in progress. A completion ID becomes invalid and may be reused after the request completes or after an outstanding request is canceled.

dwCompletionMode

Specifies the way in which the call is to be completed. Note that dwCompletionMode is allowed to have only a single flag set. This parameter uses the following LINECALLCOMPLMODE_ constants:

LINECALLCOMPLMODE_CAMPON

Queues the call until the call can be completed. The call remains in the busy state while queued.

LINECALLCOMPLMODE_CALLBACK

Requests the called station to return the call when it returns to idle.

LINECALLCOMPLMODE_INTRUDE

Adds the application to the existing physical call at the called station (barge in).

LINECALLCOMPLMODE_MESSAGE

Leave a short predefined message for the called station ("Leave Word Calling"). The message to be sent is specified by dwMessageID.

dwMessageID

Specifies the message that is to be sent when completing the call using LINECALLCOMPLMODE_MESSAGE. This ID selects the message from a small number of predefined messages.

This function is considered complete when the request has been accepted by the network or switch; not when the request is fully completed in the way specified. After this function completes, the call typically transitions to idle. When the called station or network enters a state where the call can be completed as requested, the application will be notified by a LINE_CALLSTATE message with the call state equal to offering. The call's LINECALLINFO record lists the reason for the call as CALLCOMPLETION and provide the completion ID as well. It is possible to have multiple call completion requests outstanding at any given time; the maximum number is device dependent. The completion ID is also used to refer to each individual request so requests can be canceled by calling lineUncompleteCall.


 lineCompleteTransfer

[New - Windows 95]

LONG lineCompleteTransfer(HCALL hCall, HCALL hConsultCall,
    LPHCALL lphConfCall, DWORD dwTransferMode)

Completes the transfer of the specified call to the party connected in the consultation call.

•	Returns a positive request ID if the function will be completed asynchronously, or a negative error number if an error has occurred. The dwParam2 parameter of the corresponding LINE_REPLY callback message is zero if the function is successful or it is a negative error number if an error has occurred. Possible return values are:

LINEERR_INVALCALLHANDLE	LINEERR_NOTOWNER
LINEERR_INVALCALLSTATE	LINEERR_OPERATIONUNAVAIL
LINEERR_INVALCONSULTCALLHANDLE	LINEERR_OPERATIONFAILED
LINEERR_INVALTRANSFERMODE	LINEERR_RESOURCEUNAVAIL
LINEERR_INVALPOINTER	LINEERR_UNINITIALIZED
LINEERR_NOMEM
hCall

Specifies a handle to the call to be transferred. The application must be an owner of this call. Call state of hCall must be onHold, onHoldPendingTransfer.

hConsultCall

Specifies a handle to the call that represents a connection with the destination of the transfer. The application must be an owner of this call. Call state of hConsultCall must be connected, ringback, busy, or proceeding.

lphConfCall

Specifies a pointer to a memory location where an HCALL handle can be returned. If dwTransferMode is LINETRANSFERMODE_CONFERENCE, the newly created conference call is returned in lphConfCall and the application becomes the sole owner of the conference call. Otherwise, this parameter is ignored by TAPI.DLL.

dwTransferMode

Specifies how the initiated transfer request is to be resolved. This parameter uses the following LINETRANSFERMODE_ constants:

LINETRANSFERMODE_TRANSFER

Resolve the initiated transfer by transferring the initial call to the consultation call.

LINETRANSFERMODE_CONFERENCE

Resolve the initiated transfer by conferencing all three parties into a three-way conference call. A conference call is created and returned to the application.

The LINE_REPLY message sent in response to a call to the lineCompleteTransfer function is based on the status of the call specified by the hCall parameter.

This operation completes the transfer of the original call, hCall, to the party currently connected by hConsultCall. The consultation call will typically have been dialed on the consultation call allocated as part of lineSetupTransfer, but it may be any call to which the switch is capable of transferring hCall.

The transfer request can be resolved either as a transfer or as a three-way conference call. When resolved as a transfer, the parties connected by hCall and hConsultCall are connected to each other, and both hCall and hConsultCall are typically cleared from the application's line and transition to the idle state. Note that the application's call handle remains valid after the transfer has completed. The application must deallocate its handle with lineHandoff when it is no longer interested in the transferred call.

When resolved as a conference, all three parties enter into a conference call. Both existing call handles remain valid but will transition to the conferenced state. A conference call handle will be created and returned, and it will transition to the connected state.

If lineGetConfRelatedCalls is called immediately after lineCompleteTransfer with the result that the calls are conferenced, lineGetConfRelatedCalls may not return a complete list of related calls. This is because TAPI.DLL waits to receive a LINE_CALLSTATE message indicating that the call has entered LINECALLSTATE_CONFERENCED before it considers the call to actually be part of the conference. That is, it waits for the service provider to confirm the conferenced state. Once the application has received the LINE_CALLSTATE message, lineGetConfRelatedCalls returns complete information.

It may also be possible to perform a blind transfer of a call using lineBlindTransfer.


 lineConfigDialog

[New - Windows 95]

LONG lineConfigDialog(DWORD dwDeviceID, HWND hwndOwner,
    LPCSTR lpszDeviceClass)

Causes the provider of the specified line device to display a dialog (attached to hwndOwner of the application) to allow the user to configure parameters related to the line device.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

LINEERR_BADDEVICEID	LINEERR_NOMEM
LINEERR_INUSE	LINEERR_OPERATIONFAILED
LINEERR_INVALDEVICECLASS	LINEERR_RESOURCEUNAVAIL
LINEERR_INVALPARAM	LINEERR_UNINITIALIZED
LINEERR_INVALPOINTER	LINEERR_OPERATIONUNAVAIL
LINEERR_NODEVICE
dwDeviceID

Specifies the line device to be configured.

hwndOwner

Specifies a handle to a window to which the dialog is to be attached.

lpszDeviceClass

Specifies a pointer to a NULL-terminated string that identifies a device class name. This device class allows the application to select a specific subscreen of configuration information applicable to that device class. This parameter is optional and can be left NULL or empty, in which case the highest level configuration is selected.

The lineConfigDialog function causes the service provider to display a modal dialog (attached to hwndOwner of the application) to allow the user to configure parameters related to the line specified by dwDeviceID. The lpszDeviceClass parameter allows the application to select a specific subscreen of configuration information applicable to the device class in which the user is interested; the permitted strings are the same as for lineGetID. For example, if the line supports the Comm API, passing "COMM" as lpszDeviceClass causes the provider to display the parameters related specifically to Comm (or, at least, start at the corresponding point in a multilevel configuration dialog chain, so the user doesn't have to "dig" to find the parameters of interest).

The lpszDeviceClass parameter would be "tapi/line" , "", or NULL to cause the provider to display the highest level configuration for the line.


 lineConfigDialogEdit

[New - Windows 95]

LONG lineConfigDialogEdit (DWORD dwDeviceID, HWND hwndOwner,
    LPCSTR lpszDeviceClass, LPVOID const lpDeviceConfigIn,
    DWORD dwSize, LPVARSTRING lpDeviceConfigOut)

Causes the provider of the specified line device to display a dialog (attached to hwndOwner of the application) to allow the user to configure parameters related to the line device.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

LINEERR_BADDEVICEID	LINEERR_OPERATIONFAILED
LINEERR_INVALDEVICECLASS	LINEERR_RESOURCEUNAVAIL
LINEERR_INVALPARAM	LINEERR_STRUCTURETOOSMALL
LINEERR_INVALPOINTER	LINEERR_UNINITIALIZED
LINEERR_NODRIVER	LINEERR_OPERATIONUNAVAIL
LINEERR_NOMEM	LINEERR_NODEVICE
dwDeviceID

Specifies the line device to be configured.

hwndOwner

Specifies a handle to a window to which the dialog is to be attached.

lpszDeviceClass

Specifies a pointer to a NULL-terminated string that identifies a device class name. This device class allows the application to select a specific subscreen of configuration information applicable to that device class. This parameter is optional and can be left NULL or empty, in which case the highest level configuration is selected.

lpDeviceConfigIn

Specifies a pointer to the opaque configuration data structure that was returned by lineGetDevConfig (or a previous invocation of lineConfigDialogEdit) in the variable portion of the VARSTRING structure.

dwSize

Specifies the number of bytes in the structure pointed to by lpDeviceConfigIn. This value will have been returned in the dwStringSize field in the VARSTRING structure returned by lineGetDevConfig or a previous invocation of lineConfigDialogEdit.

lpDeviceConfigOut

Specifies a pointer to the memory location of type VARSTRING where the device configuration structure is returned. Upon successful completion of the request, this location is filled with the device configuration. The dwStringFormat field in the VARSTRING structure will be set to STRINGFORMAT_BINARY. Prior to calling lineGetDevConfig (or a future invocation of lineConfigDialogEdit), the application should set the dwTotalSize field of this structure to indicate the amount of memory available to TAPI for returning information.

If LINEERR_STRUCTURETOOSMALL is returned, the dwTotalSize field of the VARSTRING structure pointed to by lpDeviceConfigOut does not specify enough memory to contain the entire configuration structure. The dwNeededSize field has been set to the amount required. To the extent that user entries were reflected in information that could not be returned due to insufficient space, those edits are lost; applications should therefore allocate the maximum amount of space that may be needed by the device class to return its configuration structure (see documentation for the device class for further information).

The lineConfigDialogEdit function causes the service provider to display a modal dialog (attached to hwndOwner of the application) to allow the user to configure parameters related to the line specified by dwDeviceID.

The lpszDeviceClass parameter allows the application to select a specific subscreen of configuration information applicable to the device class in which the user is interested; the permitted strings are the same as for lineGetID. For example, if the line supports the Comm API, passing "COMM" as lpszDeviceClass causes the provider to display the parameters related specifically to Comm (or, at least, start at the corresponding point in a multilevel configuration dialog chain, so the user doesn't have to "dig" to find the parameters of interest).

The lpszDeviceClass parameter would be "tapi/line" , "", or NULL to cause the provider to display the highest level configuration for the line.

The difference between this function and lineConfigDialog is the source of the parameters to edit and the result of the editing. In lineConfigDialog, the parameters edited are those currently in use on the device (or set for use on the next call), and any changes made have (to the maximum extent possible) an immediate impact on any active connection; also, the application must use lineGetDevConfig to fetch the result of parameter changes from lineConfigDialog. With lineConfigDialogEdit, the parameters to edit are passed in from the application, and the results are returned to the application, with no impact on active connections; the results of the editing are returned with this function, and the application does not need to call lineGetDevConfig. Thus, lineConfigDialogEdit permits an application to provide the ability for the user to set up parameters for future calls without having an impact on any active call. Note, however, the output of this function can be passed to lineSetDevConfig to affect the current call or next call.

Although this is a new function which older applications would not be expected to call, for backward compatibility, they should not be prevented from doing so; the function will work the same way for all applications.


 lineConfigProvider

[New - Windows 95]

LONG lineConfigProvider(HWND hwndOwner, DWORD dwPermanentProviderID)

Causes a service provider to display its configuration dialog.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

LINEERR_INIFILECORRUPT	LINEERR_NOMEM
LINEERR_INVALPARAM	LINEERR_OPERATIONFAILED
hwndOwner

Specifies a handle to a window to which the configuration dialog (displayed by TSPI_providerConfig) will be attached.

dwPermanentProviderID

Specifies the permanent provider ID of the service provider to be configured.

This is basically a straight pass-through to TSPI_providerConfig.

Although this is a new function which older applications would not be expected to call, for backward compatibility, they should not be prevented from doing so; the function will work the same way for all applications.


 lineDeallocateCall

[New - Windows 95]

LONG lineDeallocateCall(HCALL hCall)

Deallocates the specified call handle.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

LINEERR_INVALCALLHANDLE	LINEERR_OPERATIONFAILED
LINEERR_INVALCALLSTATE	LINEERR_RESOURCEUNAVAIL
LINEERR_NOMEM	LINEERR_UNINITIALIZED
hCall

Specifies the call handle to be deallocated. An application with monitoring privileges for a call can always deallocate its handle for that call. An application with owner privilege for a call can deallocate its handle except when the application is the sole owner of the call and the call is not in the idle state. The call handle is no longer valid after it has been deallocated.

The deallocation does not affect the call state of the physical call. It does, however, release internal resources related to the call. If the application is the sole owner of a call and the call is not in the idle state, LINEERR_INVALCALLSTATE is returned. In this case, the application can first drop the call using lineDrop and deallocate its call handle afterwards. An application that has monitor privilege for a call can always deallocate its handle for the call.

When the lineDeallocateCall function deallocates a call handle, it also suspends further processing of any outstanding LINE_REPLY messages for the call. An application must be designed not to wait indefinately for LINE_REPLY messages for each corresponding call to an asynchronous function if it also uses the lineDeallocateCall function to deallocate handles.


 lineDevSpecific

[New - Windows 95]

LONG lineDevSpecific(HLINE hLine, DWORD dwAddressID, HCALL hCall,
    LPVOID lpParams, DWORD dwSize)

Enables service providers to provide access to features not offered by other TAPI functions. The meaning of the extensions are device specific, and taking advantage of these extensions requires the application to be fully aware of them.

•	Returns a positive request ID if the function will be completed asynchronously, or a negative error number if an error has occurred. The dwParam2 parameter of the corresponding LINE_REPLY callback message is zero if the function is successful or it is a negative error number if an error has occurred. Possible return values are:

LINEERR_INVALADDRESSID	LINEERR_OPERATIONUNAVAIL
LINEERR_INVALCALLHANDLE	LINEERR_OPERATIONFAILED
LINEERR_INVALLINEHANDLE	LINEERR_RESOURCEUNAVAIL
LINEERR_INVALPOINTER	LINEERR_UNINITIALIZED
LINEERR_NOMEM
Additional return values are device specific.

hLine

Specifies a handle to a line device. This parameter is required.

dwAddressID

Specifies an address ID on the given line device.

hCall

Specifies a handle to a call. This parameter is optional, but if it is specified, the call it represents must belong to the hLine line device. Call state of hCall is device specific.

lpParams

Specifies a pointer to a memory area used to hold a parameter block. The format of this parameter block is device specific and its contents are passed by TAPI.DLL to or from the service provider.

dwSize

The size in bytes of the parameter block area.

This operation is part of the Extended Telephony services. It provides access to a device-specific feature without defining its meaning. This operation is only available if the application has successfully negotiated a device-specific extension version.

This function provides a generic parameter profile. The interpretation of the parameter structure is device specific. Whether dwAddressID and/or hCall are expected to be valid is device-specific. If specified, they must belong to hLine. Indications and replies sent back the application that are device specific should use the LINE_DEVSPECIFIC message.

A service provider can provide access to device-specific functions by defining parameters for use with this function. Applications that want to make use of these device-specific extensions should consult the device-specific (in this case meaning vendor specific) documentation that describes what extensions are defined. An application that relies on these device-specific extensions will typically not be able to work with other service provider environments.


 lineDevSpecificFeature

[New - Windows 95]

LONG lineDevSpecificFeature(HLINE hLine, DWORD dwFeature,
    LPVOID lpParams, DWORD dwSize)

Enables service providers to provide access to features not offered by other TAPI functions. The meaning of these extensions are device specific, and taking advantage of these extensions requires the application to be fully aware of them.

•	Returns a positive request ID if the function will be completed asynchronously, or a negative error number if an error has occurred. The dwParam2 parameter of the corresponding LINE_REPLY callback message is zero if the function is successful or it is a negative error number if an error has occurred. Possible return values are:

LINEERR_INVALFEATURE	LINEERR_OPERATIONUNAVAIL
LINEERR_INVALLINEHANDLE	LINEERR_OPERATIONFAILED
LINEERR_INVALPOINTER	LINEERR_RESOURCEUNAVAIL
LINEERR_NOMEM	LINEERR_UNINITIALIZED
Additional return values are device specific.

hLine

Specifies a handle to the line device.

dwFeature

Specifies the feature to invoke on the line device. This parameter uses the PHONEBUTTONFUNCTION_ constants.

lpParams

Specifies a pointer to a memory area used to hold a feature-dependent parameter block. The format of this parameter block is device specific and its contents are passed through by TAPI.DLL to or from the service provider.

dwSize

Specifies the size of the buffer in bytes.

This operation is part of the Extended Telephony services. It provides access to a device-specific feature without defining its meaning. This operation is only available if the application has successfully negotiated a device-specific extension version.

This function provides the application with phone feature-button emulation capabilities. When an application invokes this operation, it specifies the equivalent of a button-press event. This method of invoking features is device dependent, as TAPI does not define their meaning. Note that an application that relies on these device-specific extensions will typically not work with other service provider environments.

Note also that the structure pointed to by lpParams should not contain any pointers since they would not be properly translated (thunked) when running a 16-bit application in a 32-bit version of TAPI.DLL and vice versa.


 lineDial

[New - Windows 95]

LONG lineDial(HCALL hCall, LPCSTR lpszDestAddress, DWORD dwCountryCode)

Dials the specified dialable number on the specified call.

•	Returns a positive request ID if the function will be completed asynchronously, or a negative error number if an error has occurred. The dwParam2 parameter of the corresponding LINE_REPLY callback message is zero if the function is successful or it is a negative error number if an error has occurred. Possible return values are:

LINEERR_ADDRESSBLOCKED	LINEERR_INVALPOINTER
LINEERR_DIALBILLING	LINEERR_NOMEM
LINEERR_DIALDIALTONE	LINEERR_NOTOWNER
LINEERR_DIALPROMPT	LINEERR_OPERATIONFAILED
LINEERR_DIALQUIET	LINEERR_OPERATIONUNAVAIL
LINEERR_INVALCALLHANDLE	LINEERR_RESOURCEUNAVAIL
LINEERR_INVALCALLSTATE	LINEERR_UNINITIALIZED
LINEERR_INVALCOUNTRYCODE
hCall

Specifies a handle to the call on which a number is to be dialed. The application must be an owner of the call. Call state of hCall can be any state except idle and disconnected.

lpszDestAddress

Specifies the destination to be dialed using the standard dialable number format.

dwCountryCode

Specifies the country code of the destination. This is used by the implementation to select the call progress protocols for the destination address. If a value of zero is specified, a service provider-defined default call progress protocol is used.

If LINEERR_INVALADDRESS is returned, no dialing has been done. If LINEERR_DIALBILLING, LINEERR_DIALQUIET, LINEERR_DIALDIALTONE, or LINEERR_DIALPROMPT is returned, none of the actions otherwise performed by lineDial have occured; for example, none of the dialable addresses prior to the offending character has been dialed, no hookswitch state has changed, and so on.

The lineDial function is used for dialing on an existing call appearance. For example, after a call has been set up for transfer or conference, a consultation call is automatically allocated, and the lineDial function would be used to perform the dialing of this consultation call. Note that lineDial may be invoked multiple times in the course of multi-stage dialing, if the line's device capabilities allows it. Also, multiple addresses may be provided in a single dial string separated by CRLF. Service providers that provide inverse multiplexing can establish individual physical calls with each of the addresses and can return a single call handle to the aggregate of all calls to the application. All addresses would use the same country code.

Dialing is considered complete after the address has been passed to the service provider; not after the call is finally connected. Service providers that provide inverse multiplexing may allow multiple addresses to be provided at once. The service provider sends LINE_CALLSTATE messages to the application to inform it about the progress of the call. To abort a call attempt while a call is being established, the invoking application should use lineDrop.

An application can set the lpszDestAddress parameter of the lineDial function to the addess of an empty string to indicate that dialing is complete, but only if the previous calls to the lineMakeCall and lineDial functions have had the strings specified by lpszDestAddress terminated with semicolons.


 lineDrop

[New - Windows 95]

LONG lineDrop(HCALL hCall, LPCSTR lpsUserUserInfo, DWORD dwSize)

Drops or disconnects the specified call. The application has the option to specify user-to-user information to be transmitted as part of the call disconnect.

•	Returns a positive request ID if the function will be completed asynchronously, or a negative error number if an error has occurred. The dwParam2 parameter of the corresponding LINE_REPLY callback message is zero if the function is successful or it is a negative error number if an error has occurred. Possible return values are:

LINEERR_INVALCALLHANDLE	LINEERR_OPERATIONUNAVAIL
LINEERR_NOMEM	LINEERR_OPERATIONFAILED
LINEERR_NOTOWNER	LINEERR_RESOURCEUNAVAIL
LINEERR_INVALPOINTER	LINEERR_USERUSERINFOTOOBIG
LINEERR_INVALCALLSTATE	LINEERR_UNINITIALIZED
hCall

Specifies a handle to the call to be dropped. The application must be an owner of the call. Call state of hCall can be any state except idle.

lpsUserUserInfo

Specifies a pointer to a string containing user-to-user information to be sent to the remote party as part of the call disconnect. This pointer can be left NULL if no user-to-user information is to be sent. User-to-user information is only sent if supported by the underlying network (see LINEDEVCAPS). The protocol discriminator field for the user-user information, if required, should appear as the first byte of the buffer pointed to by lpsUserUserInfo, and must be accounted for in dwSize.

dwSize

Specifies the size in bytes of the user-to-user information in lpsUserUserInfo. If lpsUserUserInfo is NULL, no user-to-user information is sent to the calling party and dwSize is ignored.

When invoking lineDrop, related calls may sometimes be affected as well. For example, dropping a conference call may drop all individual participating calls. LINE_CALLSTATE messages are sent to the application for all calls whose call state is affected. A dropped call typically transitions to the idle state. Invoking lineDrop on a call in the offering state rejects the call. Not all telephone networks provide this capability.

A call in the onholdpending state will typically revert to the connected state. When dropping the consultation call to the third party for a conference call or when removing the third party in a previously established conference call, the provider (and switch) may release the conference bridge and revert the call back to a normal two-party call. If this is the case, hConfCall transitions to the idle state, and the only remaining participating call will transition to the connected state. Some switches automatically "unhold" the other call.

The application has the option to send user-to-user information at the time of the drop. Even if user-to-user information can be sent, there is no guarantee that the network will deliver this information to the remote party.

Note that in various bridged or party-line configurations when multiple parties are on the call, lineDrop may not actually clear the call.


 lineForward

[New - Windows 95]

LONG lineForward(HLINE hLine, DWORD bAllAddresses, DWORD dwAddressID,
    LPLINEFORWARDLIST const lpForwardList, DWORD dwNumRingsNoAnswer,
    LPHCALL lphConsultCall, LPLINECALLPARAMS const lpCallParams)

Forwards calls destined for the specified address on the specified line, according to the specified forwarding instructions. When an originating address (dwAddressID) is forwarded, the specified incoming calls for that address are deflected to the other number by the switch. This function provides a combination of forward and do-not-disturb features. This function can also cancel forwarding currently in effect.

•	Returns a positive request ID if the function will be completed asynchronously, or a negative error number if an error has occurred. The dwParam2 parameter of the corresponding LINE_REPLY callback message is zero if the function is successful or it is a negative error number if an error has occurred. Possible return values are:

LINEERR_INVALLINEHANDLE	LINEERR_NOMEM
LINEERR_INVALADDRESSID	LINEERR_OPERATIONUNAVAIL
LINEERR_INVALADDRESS	LINEERR_OPERATIONFAILED
LINEERR_INVALCOUNTRYCODE	LINEERR_RESOURCEUNAVAIL
LINEERR_INVALPOINTER	LINEERR_STRUCTURETOOSMALL
LINEERR_INVALPARAM	LINEERR_UNINITIALIZED
hLine

Specifies a handle to the line device.

bAllAddresses

Specifies whether all originating addresses on the line or just the one specified is to be forwarded. If TRUE, all addresses on the line are forwarded and dwAddressID is ignored; if FALSE, only the address specified as dwAddressID is forwarded.

dwAddressID

Specifies the address on the specified line whose incoming calls are to be forwarded. This parameter is ignored if bAllAddresses is TRUE.

lpForwardList

Specifies a pointer to a variably sized data structure that describes the specific forwarding instructions, of type LINEFORWARDLIST.

dwNumRingsNoAnswer

Specifies the number of rings before a call is considered a "no answer." If dwNumRingsNoAnswer is out of range, the actual value is set to the nearest value in the allowable range.

lphConsultCall

Specifies a pointer to an HCALL location. In some telephony environments, this location is loaded with a handle to a consultation call that is used to consult the party that is being forwarded to, and the application becomes the initial sole owner of this call. This pointer must be valid even in environments where call forwarding does not require a consultation call. This handle will be set to NULL if no consultation call is created.

lpCallParams

Specifies a pointer to a structure of type LINECALLPARAMS. This pointer is ignored unless lineForward requires the establishment of a call to the forwarding destination (and lphConsultCall is returned, in which case lpCallParams is optional). If NULL, default call parameters are used. Otherwise, the specified call parameters are used for establishing hConsultCall.

A successful forwarding indicates only that the request has been accepted by the service provider, not that forwarding is set up at the switch. A LINE_ADDRESSSTATE (forwarding) message provides confirmation for forwarding having been set up at the switch.

Forwarding of the address(es) remains in effect until this function is called again. The most recent forwarding list replaces the old one. Forwarding can be canceled by specifying a NULL pointer as lpForwardList. If a NULL destination address is specified for an entry in the forwarding list, the operation acts as a do-not-disturb.

Forwarding status of an address may also be affected externally; for example, by administrative actions at the switch or by a user from another station. It may not be possible for the service provider to be aware of this state change, and it may not be able to keep in synchronization with the forwarding state known to the switch.

Since a service provider may not know the forwarding state of the address "for sure" (that is, it may have been forwarded or unforwarded in an unknown way), lineForward will succeed unless it fails to set the new forwarding instructions. In other words, a request that all forwarding be canceled at a time that there is no forwarding in effect will be successful. This is because there is no "unforwarding"—you can only change the previous set of forwarding instructions.

The success or failure of this operation does not depend on the previous set of forwarding instructions, and the same is true when setting different forwarding instructions. The provider should "unforward everything" prior to setting the new forwarding instructions. Since this may take time in analog telephony environments, a provider may also want to compare the current forwarding with the new one, and only issue instructions to the switch to get to the final state (leaving unchanged forwarding unaffected).

Invoking lineForward when LINEFORWARDLIST has dwNumEntries set to zero has the same effect as providing a NULL lpForwardList parameter. It cancels all forwarding currently in effect.


 lineGatherDigits

[New - Windows 95]

LONG lineGatherDigits(HCALL hCall, DWORD dwDigitModes, LPSTR lpsDigits,
    DWORD dwNumDigits, LPCSTR lpszTerminationDigits,
    DWORD dwFirstDigitTimeout, DWORD dwInterDigitTimeout)

Initiates the buffered gathering of digits on the specified call. The application specifies a buffer in which to place the digits and the maximum number of digits to be collected.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

LINEERR_INVALCALLHANDLE	LINEERR_NOMEM
LINEERR_INVALCALLSTATE	LINEERR_NOTOWNER
LINEERR_INVALDIGITMODE	LINEERR_OPERATIONUNAVAIL
LINEERR_INVALDIGITS	LINEERR_OPERATIONFAILED
LINEERR_INVALPARAM	LINEERR_RESOURCEUNAVAIL
LINEERR_INVALPOINTER	LINEERR_UNINITIALIZED
LINEERR_INVALTIMEOUT
hCall

Specifies a handle to the call on which digits are to be gathered. The application must be an owner of the call. Call state of hCall can be any state.

dwDigitModes

Specifies the digit mode(s) to be monitored. Note that dwDigitModes is allowed to have one or more flags set. This parameter uses the following LINEDIGITMODE_ constants:

LINEDIGITMODE_PULSE

Detect digits as audible clicks that are the result of the use of rotary pulse sequences. Valid digits for pulse mode are '0' through '9'.

LINEDIGITMODE_DTMF

Detect digits as DTMF tones. Valid digits for DTMF mode are '0' through '9', 'A', 'B', 'C', 'D', '*', '#'.

lpsDigits

Specifies a pointer to the buffer where detected digits are to be stored as ASCII characters. Digits may not show up in the buffer one at a time as they are collected. Only after a LINE_GATHERDIGITS message is received should the content of the buffer be assumed to be valid. If lpsDigits is NULL, the digit gathering currently in progress on the call is terminated and dwNumDigits is ignored. Otherwise, lpsDigits is assumed to have room for dwNumDigits digits.

dwNumDigits

Specifies the number of digits to be collected before a LINE_GATHERDIGITS message is sent to the application. The dwNumDigits parameter is ignored when lpsDigits is NULL. This function fails if dwNumDigits is zero.

lpszTerminationDigits

Specifies a NULL-terminated string of termination digits as ASCII characters. If one of the digits in the string is detected, that termination digit is appended to the buffer, digit collection is terminated, and the LINE_GATHERDIGITS message is sent to the application.
Valid characters for pulse mode are '0' through '9'. Valid characters for DTMF mode are '0' through '9', 'A', 'B', 'C', 'D', '*', '#'. If this pointer is NULL, or if it points to an empty string, the function behaves as though no termination digits were supplied.

dwFirstDigitTimeout

Specifies the time duration in milliseconds in which the first digit is expected. If the first digit is not received in this timeframe, digit collection is aborted and a LINE_GATHERDIGITS message is sent to the application. The buffer only contains the NULL character, indicating that no digits were received and the first digit timeout terminated digit gathering. The call's line-device capabilities specifies the valid range for this parameter or indicates that timeouts are not supported.

dwInterDigitTimeout

Specifies the maximum time duration in milliseconds between consecutive digits. If no digit is received in this timeframe, digit collection is aborted and a LINE_GATHERDIGITS message is sent to the application. The buffer only contains the digits collected up to this point followed by a NULL character, indicating that an interdigit timeout terminated digit gathering. The call's line-device capabilities specifies the valid range for this parameter or indicates that timeouts are not supported.

Digit collection is terminated when the requested number of digits has been collected. It is also terminated when one of the digits detected matches a digit in szTerminationDigits before the specified number of digits has been collected. The detected termination digit is also placed in the buffer and the partial buffer is returned.

Another way of cancelling digit collection is when one of the timeouts expires. The dwFirstDigitTimeout expires if the first digit is not received in this time period. The dwInterDigitTimout expires if the second, third, (and so forth) digit is not received within that time period from the previously detected digit, and a partial buffer is returned.

A fourth method for terminating digit detection is by calling this function again while collection is in progress. The old collection session is terminated, any digits collected up to that point are copied to the buffer supplied from the previous call to this function, and the buffer is delivered when the LINE_GATHERDIGITS message is sent to the application. The mechanism for terminating digit gathering without initiating another gathering of the digits is by invoking this function with lpsDigits equal to NULL.

This function is considered successful if digit collection has been correctly initiated, not when digit collection has terminated. In all cases where a partial buffer is returned, valid digits (if any) are followed by an ASCII NULL character.

Although this function can be invoked in any call state, digits can typically only be gathered while the call is in the connected state.

The message LINE_GATHERDIGITS is sent only to the application that initiated the request. It is also sent when partial buffers are returned because of timeouts or matching termination digits, or when the request is canceled by another lineGatherDigits request on the call. Only one gather-digits request can be active on a call at any given time across all applications that are owners of the call. Given the asynchronous behavior of the operation, an application that issues multiple lineGatherDigits in quick succession may be able to do so and receive several LINE_GATHERDIGITS messages later. While this would be unusual application behavior, the application will be able to count the number of these messages to allow cancel messages to be matched with the earlier requests. In any case, only the most recent request should be assumed to be valid.

An application can use lineMonitorDigits to enable or disable unbuffered digit detection. Each time a digit is detected in this fashion, a LINE_MONITORDIGITS message is sent to the application. Both buffered and unbuffered digit detection can be enabled for the same call simultaneously.

Gathering of digits on a conference call applies only to the hConfCall, not to the individual participating calls.

If the lineGatherDigits function is used to cancel a previous request to gather digits, the function copies any digits collected up to that point to the buffer specified in the original function call and sends a LINE_GATHERDIGITS message to the application, regardless of whether the lpszDigits parameter in the second call specifies a NULL or different address.


 lineGenerateDigits

[New - Windows 95]

LONG lineGenerateDigits(HCALL hCall, DWORD dwDigitMode,
    LPCSTR lpszDigits, DWORD dwDuration)

Initiates the generation of the specified digits on the specified call as inband tones using the specified signaling mode. Invoking this function with a NULL value for lpszDigits aborts any digit generation currently in progress. Invoking lineGenerateDigits or lineGenerateTone while digit generation is in progress aborts the current digit generation or tone generation and initiates the generation of the most recently specified digits or tone.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

LINEERR_INVALCALLHANDLE	LINEERR_NOTOWNER
LINEERR_INVALCALLSTATE	LINEERR_OPERATIONUNAVAIL
LINEERR_INVALDIGITMODE	LINEERR_OPERATIONFAILED
LINEERR_INVALPOINTER	LINEERR_RESOURCEUNAVAIL
LINEERR_NOMEM	LINEERR_UNINITIALIZED
hCall

Specifies a handle to the call. The application must be an owner of the call. Call state of hCall can be any state.

dwDigitMode

Indicates the format to be used for signaling these digits. Note that dwDigitMode is allowed to have only a single flag set. This parameter uses the following LINEDIGITMODE_ constants:

LINEDIGITMODE_PULSE

Uses pulse/rotary for digit signaling. Valid digits for pulse mode are '0' through '9'.

LINEDIGITMODE_DTMF

Uses DTMF tones for digit signaling. Valid digits for DTMF mode are '0' through '9', 'A', 'B', 'C', 'D', '*', '#'.

lpszDigits

Specifies a pointer to a NULL-terminated character buffer that contains the digits to be generated. Valid characters for pulse mode are '0' through '9' and ',' (comma). Valid characters for DTMF mode are '0' through '9', 'A', 'B', 'C', 'D', '*', '#', and ',' (comma). A comma injects an extra delay between the signaling of the previous and next digits it separates. The duration of this pause is configuration defined, and the line's device capabilities indicates what this duration is. Multiple commas may be used to inject longer pauses. Invalid digits are ignored during the generation, rather than being reported as an error. The exclamation character (!) is a valid character in the string specifed by the lpszDigits parameter for both DTMF and pulse mode. This character causes a "hookflash" operation, as described for dialable addresses.

dwDuration

Specifies both the duration in milliseconds of DTMF digits and pulse and DTMF inter-digit spacing. A value of zero will use a default value. The dwDuration parameter must be within the range specified by MinDialParams and MaxDialParams in LINEDEVCAPS. If out of range, the actual value is set to the nearest value in the range.

The lineGenerateDigits function is considered to have completed successfully when the digit generation has been successfully initiated, not when all digits have been generated. In contrast to lineDial, which dials digits in a network-dependent fashion, lineGenerateDigits guarantees to produce the digits as inband tones over the voice channel using DTMF or hookswitch dial pulses when using pulse. The lineGenerateDigits function is generally not suitable for making calls or dialing. It is intended for end-to-end signaling over an established call.

After all digits in lpszDigits have been generated, or after digit generation has been aborted or canceled, a LINE_GENERATE message is sent to the application.

Only one inband generation request (tone generation or digit generation) is allowed to be in progress per call across all applications that are owners of the call. Digit generation on a call is cancelled by initiating either another digit generation request or a tone generation request. To cancel the current digit generation, the application can invoke lineGenerateDigits and specify NULL for the lpszDigits parameter.

Depending on the service provider and hardware, the application may monitor the digits it generates itself. If that is not desired, the application can disable digit monitoring while generating digits.


 lineGenerateTone

[New - Windows 95]

LONG lineGenerateTone(HCALL hCall, DWORD dwToneMode,
    DWORD dwDuration, DWORD dwNumTones,
    LPLINEGENERATETONE const lpTones)

Generates the specified inband tone over the specified call. Invoking this function with a zero for dwToneMode aborts the tone generation currently in progress on the specified call. Invoking lineGenerateTone or lineGenerateDigits while tone generation is in progress aborts the current tone generation or digit generation and initiates the generation of the newly specified tone or digits.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

LINEERR_INVALCALLHANDLE	LINEERR_NOTOWNER
LINEERR_INVALCALLSTATE	LINEERR_OPERATIONUNAVAIL
LINEERR_INVALPOINTER	LINEERR_OPERATIONFAILED
LINEERR_INVALTONEMODE	LINEERR_RESOURCEUNAVAIL
LINEERR_INVALTONE	LINEERR_UNINITIALIZED
LINEERR_NOMEM
hCall

Specifies a handle to the call on which a tone is to be generated. The application must be an owner of the call. Call state of hCall can be any state.

dwToneMode

Defines the tone to be generated. Tones can be either standard or custom. A custom tone is composed of a set of arbitrary frequencies. A small number of standard tones are predefined. The duration of the tone is specified with dwDuration for both standard and custom tones. Note that dwToneMode can only have one bit set. If no bits are set (the value 0 is passed), tone generation is cancelled. This parameter uses the following LINETONEMODE_ constants:

LINETONEMODE_CUSTOM

The tone is a custom tone, defined by the specified frequencies.

LINETONEMODE_RINGBACK

The tone to be generated is ring tone. The exact ringback tone is service provider defined.

LINETONEMODE_BUSY

The tone is a standard (station) busy tone. The exact busy tone is service provider defined.

LINETONEMODE_BEEP

The tone is a beep, as used to announce the beginning of a recording. The exact beep tone is service provider defined.

LINETONEMODE_BILLING

The tone is billing information tone such as a credit card prompt tone. The exact billing tone is service provider defined.

A value of zero for dwToneMode cancels tone generation.

dwDuration

Specifies duration in milliseconds during which the tone should be sustained. A value of zero for dwDuration uses a default duration for the specified tone. Default values are:

CUSTOM:	infinite
RINGBACK:	infinite
BUSY:	infinite
BEEP:	infinite
BILLING:	fixed (single cycle)

dwNumTones

Specifies the number of entries in the lpTones array. This field is ignored if dwToneMode is not equal to CUSTOM.

lpTones

Specifies a pointer to a LINEGENERATETONE array that specifies the tone's components. This parameter is ignored for non-custom tones. If lpTones is a multi-frequency tone, the various tones are played simultaneously.

lineGenerateTone is considered to have completed successfully when the tone generation has been successfully initiated, not when the generation of the tone is done. The function allows the inband generation of several predefined tones, such as ring back, busy tones, and beep. It also allows for the fabrication of custom tones by specifying their component frequencies, cadence and volume. Since these tones are generated as inband tones, the call would typically have to be in the connected state for tone generation to be effective. When the generation of the tone is complete, or when tone generation is canceled, a LINE_GENERATE message is sent to the application.

Only one inband generation request (tone generation or digit generation) is allowed to be in progress per call across all applications that are owners of the call. This implies that if tone generation is currently in progress on a call, invoking lineGenerateDigits cancels the tone generation.

If the LINEERR_INVALPOINTER error value is returned, the specified lpTones parameter is invalid or the value specified by the dwNumTones parameter is too large.


 lineGetAddressCaps

[New - Windows 95]

LONG lineGetAddressCaps(HLINEAPP hLineApp, DWORD dwDeviceID,
    DWORD dwAddressID, DWORD dwAPIVersion, DWORD dwExtVersion,
    LPLINEADDRESSCAPS lpAddressCaps)

Queries the specified address on the specified line device to determine its telephony capabilities.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

LINEERR_BADDEVICEID	LINEERR_NOMEM
LINEERR_INCOMPATIBLEAPIVERSION	LINEERR_OPERATIONFAILED
LINEERR_INCOMPATIBLEEXTVERSION	LINEERR_RESOURCEUNAVAIL
LINEERR_INVALADDRESSID	LINEERR_STRUCTURETOOSMALL
LINEERR_INVALAPPHANDLE	LINEERR_UNINITIALIZED
LINEERR_INVALPOINTER	LINEERR_OPERATIONUNAVAIL
LINEERR_NODRIVER	LINEERR_NODEVICE
hLineApp

Specifies the handle to the application's registration with TAPI.

dwDeviceID

Specifies the line device containing the address to be queried.

dwAddressID

Specifies the address on the given line device whose capabilities are to be queried.

dwAPIVersion

Specifies the version number of the Telephony API to be used. The high-order word contains the major version number; the low-order word contains the minor version number.

dwExtVersion

Specifies the version number of the service provider-specific extensions to be used. This number can be left zero if no device-specific extensions are to be used. Otherwise, the high-order word contains the major version number; the low-order word contain the minor version number.

lpAddressCaps

Specifies a pointer to a variably sized structure of type LINEADDRESSCAPS. Upon successful completion of the request, this structure is filled with address capabilities information. Prior to calling lineGetAddressCaps, the application should set the dwTotalSize field of this structure to indicate the amount of memory available to TAPI.DLL for returning information.

Valid address IDs range from zero to one less than the number of addresses returned by lineGetDevCaps. The version number to be supplied is the version number that was returned as part of the line's device capabilities by lineGetDevCaps.


 lineGetAddressID

[New - Windows 95]

LONG lineGetAddressID(HLINE hLine, LPDWORD lpdwAddressID,
    DWORD dwAddressMode, LPCSTR lpsAddress, DWORD dwSize)

Returns the address ID associated with an address in a different format on the specified line.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

LINEERR_INVALLINEHANDLE	LINEERR_OPERATIONUNAVAIL
LINEERR_INVALADDRESSMODE	LINEERR_OPERATIONFAILED
LINEERR_INVALPOINTER	LINEERR_RESOURCEUNAVAIL
LINEERR_INVALADDRESS	LINEERR_UNINITIALIZED
LINEERR_NOMEM
hLine

Specifies a handle to the open line device.

lpdwAddressID

Specifies a pointer to a DWORD-sized memory location where the address ID is returned.

dwAddressMode

Specifies the address mode of the address contained in lpsAddress. The dwAddressMode parameter is allowed to have only a single flag set. This parameter uses the following LINEADDRESSMODE_ constants:

LINEADDRESSMODE_DIALABLEADDR

The address is specified by its dialable address. The lpsAddress parameter is the dialable address or canonical address format.

lpsAddress

Specifies a pointer to a data structure holding the address assigned to the specified line device. The format of the address is determined by dwAddressMode. Since the only valid value is LINEADDRESSMODE_DIALABLEADDR, lpsAddress uses the common dialable number format and is NULL-terminated.

dwSize

Specifies the size of the address contained in lpsAddress.

This function is used to map a phone number (address) assigned to a line device back to its dwAddressID in the range 0 to the number of addresses minus one returned in the line's device capabilities. The lineMakeCall function allows the application to make a call by specifying a line handle and an address on the line. The address can be specified as a dwAddressID, as a phone number, or as a device-specific name or identifier. Using a phone number may be practical in environments where a single line is assigned multiple addresses. Note that LINEADDRESSMODE_ADDRESSID may not be used with lineGetAddressID.


 lineGetAddressStatus

[New - Windows 95]

LONG lineGetAddressStatus(HLINE hLine, DWORD dwAddressID,
    LPLINEADDRESSSTATUS lpAddressStatus)

Allows an application to query the specified address for its current status.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

LINEERR_INVALADDRESSID	LINEERR_RESOURCEUNAVAIL
LINEERR_INVALLINEHANDLE	LINEERR_STRUCTURETOOSMALL
LINEERR_INVALPOINTER	LINEERR_UNINITIALIZED
LINEERR_NOMEM	LINEERR_OPERATIONUNAVAIL
LINEERR_OPERATIONFAILED
hLine

Specifies a handle to the open line device.

dwAddressID

Specifies an address on the given open line device. This is the address to be queried.

lpAddressStatus

Specifies a pointer to a variably sized data structure of type LINEADDRESSSTATUS. Prior to calling lineGetAddressStatus, the application should set the dwTotalSize field of this structure to indicate the amount of memory available to TAPI.DLL for returning information.


 lineGetAppPriority

[New - Windows 95]

LONG lineGetAppPriority(LPCSTR lpszAppFilename, DWORD dwMediaMode,
    LPLINEEXTENSIONID const lpExtensionID, DWORD dwRequestMode,
    LPVARSTRING lpExtensionName, LPDWORD lpdwPriority)

Allows an application to determine whether or not it is in the handoff priority list for a particular media mode or Assisted Telephony request mode, and, if so, its position in the priority list.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

LINEERR_INIFILECORRUPT	LINEERR_INVALREQUESTMODE
LINEERR_INVALAPPNAME	LINEERR_NOMEM
LINEERR_INVALMEDIAMODE	LINEERR_OPERATIONFAILED
LINEERR_INVALPOINTER	LINEERR_STRUCTURETOOSMALL
lpszAppFilename

Specifies a pointer to a string containing the application executable module filename (without directory information). The parameter must specify a filename in the 8.3 format. Long filenames cannot be used.

dwMediaMode

Specifies the media mode for which the priority information is to be obtained. The value may be one of the LINEMEDIAMODE_ constants, or an extended media mode value defined by a service provider; only a single bit may be on. The value 0 should be used if checking application priority for Assisted Telephony requests.

lpExtensionID

Specifies a pointer to structure of type LINEEXTENSIONID. This parameter is referenced only if dwMediaModes specifies a value in the range 0x01000000 through 0x80000000 (extended media modes). This parameter is ignored if dwMediaMode is 0 or specifies a LINEMEDIAMODE_ value.

dwRequestMode

If the dwMediaMode parameter is 0, this parameter specifies the Assisted Telephony request mode for which priority is to be checked. It must be either LINEREQUESTMODE_MAKECALL or LINEREQUESTMODE_MEDIACALL. This parameter is ignored if dwMediaMode is non-zero.

lpExtensionName

If dwMediaMode specifies an extended media mode, this parameter must specify a pointer to a memory location into which a VARSTRING structure will be written by TAPI. This structure will contain the "friendly name" of the extended media mode associated with the specified media mode value and extension ID, if one exists. This parameter is ignored if dwMediaMode is 0 or specifies a LINEMEDIAMODE_ value. Prior to calling lineGetAppPriority, the application should set the dwTotalSize field of this structure to indicate the amount of memory available to TAPI for returning information.

lpdwPriority

Specifies a pointer to a DWORD-size memory location into which TAPI will write the priority of the application for the specified media or request mode. The value 0 will be returned if the application is not in the stored priority list and is does not currently have any line device open with ownership requested of the specified media mode or having registered for the specified request mode. The value -1 (0xFFFFFFFF) is returned if the application has the line open for the specified media mode or has registered for the specified requests,  but the application is not in the stored priority list (i.e., it is in the temporary priority list only). Otherwise, the value will indicate the application's position in the list (with 1 being highest priority, and increasing values indicating decreasing priority).

If LINEERR_INVALMEDIAMODE is returned, the value specified in dwMediaMode is not 0, not a valid extended media mode, and not a LINEMEDIAMODE_ constant, or more than one bit is on in the parameter value.

Although this is a new function which older applications would not be expected to call, for backward compatibility, they should not be prevented from doing so; the function will work the same way for all applications.


 lineGetCallInfo

[New - Windows 95]

LONG lineGetCallInfo(HCALL hCall, LPLINECALLINFO lpCallInfo)

This operation enables an application to obtain fixed information about the specified call.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

LINEERR_INVALCALLHANDLE	LINEERR_RESOURCEUNAVAIL
LINEERR_INVALPOINTER	LINEERR_STRUCTURETOOSMALL
LINEERR_NOMEM	LINEERR_UNINITIALIZED
LINEERR_OPERATIONFAILED	LINEERR_OPERATIONUNAVAIL
hCall

Specifies a handle to the call to be queried. Call state of hCall can be any state.

lpCallInfo

Specifies a pointer to a variably sized data structure of type LINECALLINFO. Upon successful completion of the request, this structure is filled with call-related information. Prior to calling lineGetCallInfo, the application should set the dwTotalSize field of this structure to indicate the amount of memory available to TAPI.DLL for returning information.

A separate LINECALLINFO structure exists for every inbound or outbound call. The structure contains primarily fixed information about the call. An application would typically be interested in checking this information when it receives its handle for a call by the LINE_CALLSTATE message, or each time it receives notification by a LINE_CALLINFO message that parts of the call information structure have changed. These messages supply the handle for the call as a parameter.


 lineGetCallStatus

[New - Windows 95]

LONG lineGetCallStatus(HCALL hCall, LPLINECALLSTATUS lpCallStatus)

Returns the current status of the specified call.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

LINEERR_INVALCALLHANDLE	LINEERR_RESOURCEUNAVAIL
LINEERR_INVALPOINTER	LINEERR_STRUCTURETOOSMALL
LINEERR_NOMEM	LINEERR_UNINITIALIZED
LINEERR_OPERATIONFAILED	LINEERR_OPERATIONUNAVAIL
hCall

Specifies a handle to the call to be queried. Call state of hCall can be any state.

lpCallStatus

Specifies a pointer to a variably sized data structure of type LINECALLSTATUS. Upon successful completion of the request, this structure is filled with call status information. Prior to calling lineGetCallStatus, the application should set the dwTotalSize field of this structure to indicate the amount of memory available to TAPI.DLL for returning information.

The lineGetCallStatus function returns the dynamic status of a call, whereas lineGetCallInfo returns primarily static information about a call. Call status information includes the current call state, detailed mode information related to the call while in this state (if any), as well as a list of the available API functions the application can invoke on the call while the call is in this state. An application would typically be interested in requesting this information when it receives notification about a call state change by the LINE_CALLSTATE message.


 lineGetConfRelatedCalls

[New - Windows 95]

LONG lineGetConfRelatedCalls(HCALL hCall, LPLINECALLLIST lpCallList)

Returns a list of call handles that are part of the same conference call as the specified call. The specified call is either a conference call or a participant call in a conference call. New handles are generated for those calls for which the application does not already have handles, and the application is granted monitor privilege to those calls.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

LINEERR_INVALCALLHANDLE	LINEERR_OPERATIONFAILED
LINEERR_NOCONFERENCE	LINEERR_RESOURCEUNAVAIL
LINEERR_INVALPOINTER	LINEERR_STRUCTURETOOSMALL
LINEERR_NOMEM	LINEERR_UNINITIALIZED
hCall

Specifies a handle to a call. This is either a conference call or a participant call in a conference call. For a conference parent call, call state of hCall can be any state. For a conference participant call, it must be in the conferenced state.

lpCallList

Specifies a pointer to a variably sized data structure of type LINECALLLIST. Upon successful completion of the request, call handles to all calls in the conference call are returned in this structure. The first call in the list is the conference call, the other calls are the participant calls. The application is granted monitor privilege to those calls for which it does not already have handles; the privileges to calls in the list for which the application already has handles is unchanged. Prior to calling lineGetConfRelatedCalls, the application should set the dwTotalSize field of this structure to indicate the amount of memory available to TAPI.DLL for returning information.

The specified call can either be a conference call handle or a handle to a participant call. For example, a consultation call that has not yet been added to a conference call is not part of a conference. The first entry in the list that is returned is the conference call handle, the other handles are all the participant calls. The specified call is always one of the calls returned in the list. Calls in the list to which the application does not already have a call handle are assigned monitor privilege; privileges to calls for which the application already has handles are unchanged. The application can use lineSetCallPrivilege to change the privilege of the call.

Note that if lineGetConfRelatedCalls is called immediately after a call is added to a conference using lineAddToConferenceor lineCompleteTransfer, lineGetConfRelatedCalls may not return a complete list of related calls because TAPI.DLL waits to receive a LINE_CALLSTATE message indicating that the call has entered LINECALLSTATE_CONFERENCED before it considers the call to actually be part of the conference (that is, the conferenced state is confirmed by the service provider). Once the application has received the LINE_CALLSTATE message, lineGetConfRelatedCalls returns complete information.

The application can invoke lineGetCallInfo and lineGetCallStatus for each call in the list to determine the call's information and status, respectively.


 lineGetCountry

[New - Windows 95]

LONG lineGetCountry (DWORD dwCountryID, DWORD dwAPIVersion,
    LPLINECOUNTRYLIST lpLineCountryList)

Fetches the stored dialing rules and other information related to a specified country, the first country in the country list, or all countries.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

LINEERR_INCOMPATIBLEAPIVERSION	LINEERR_NOMEM
LINEERR_INIFILECORRUPT	LINEERR_OPERATIONFAILED
LINEERR_INVALCOUNTRYCODE	LINEERR_STRUCTURETOOSMALL
LINEERR_INVALPOINTER
dwCountryID

Specifies the country ID (not the country code) of the country for which information is to be obtained. If the value 1 is specified, information on the first country in the country list is obtained. If the value 0 is specified, information on all countries is obtained (which may require a great deal of memory − 20Kbytes or more).

dwAPIVersion

Indicates the highest version of TAPI supported by the application (not necessarily the value negotiated by lineNegotiateAPIVersion on some particular line device).

lpLineCountryList

Specifies a pointer to a location to which a LINECOUNTRYLIST structure will be loaded. Prior to calling lineGetCountry, the application should set the dwTotalSize field of this structure to indicate the amount of memory available to TAPI for returning information.

Although this is a new function which older applications would not be expected to call, for backward compatibility, they should not be prevented from doing so; the function will work the same way for all applications.


 lineGetDevCaps

[New - Windows 95]

LONG lineGetDevCaps(HLINEAPP hLineApp, DWORD dwDeviceID,
    DWORD dwAPIVersion, DWORD dwExtVersion, LPLINEDEVCAPS lpLineDevCaps)

Queries a specified line device to determine its telephony capabilities. The returned information is valid for all addresses on the line device.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

LINEERR_BADDEVICEID	LINEERR_NOMEM
LINEERR_INCOMPATIBLEAPIVERSION	LINEERR_OPERATIONFAILED
LINEERR_INCOMPATIBLEEXTVERSION	LINEERR_RESOURCEUNAVAIL
LINEERR_INVALAPPHANDLE	LINEERR_STRUCTURETOOSMALL
LINEERR_INVALPOINTER	LINEERR_UNINITIALIZED
LINEERR_NODRIVER	LINEERR_OPERATIONUNAVAIL
LINEERR_NODEVICE
hLineApp

Specifies the handle to the application's registration with TAPI.

dwDeviceID

Specifies the line device to be queried.

dwAPIVersion

Specifies the version number of the Telephony API to be used. The high-order word contains the major version number; the low-order word contains the minor version number. This number is obtained by lineNegotiateAPIVersion.

dwExtVersion

Specifies the version number of the service provider-specific extensions to be used. This number is obtained by lineNegotiateExtVersion. It can be left zero if no device-specific extensions are to be used. Otherwise, the high-order word contains the major version number; the low-order word contains the minor version number.

lpLineDevCaps

Specifies a pointer to a variably sized structure of type LINEDEVCAPS. Upon successful completion of the request, this structure is filled with line device capabilities information. Prior to calling lineGetDevCaps, the application should set the dwTotalSize field of this structure to indicate the amount of memory available to TAPI.DLL for returning information.

Before using lineGetDevCaps, the application must negotiate the API version number to use, and, if desired, the extension version to use.

The API and extension version numbers are those under which TAPI.DLL and the service provider must operate. If version ranges do not overlap, the application, API, or service-provider versions are incompatible and an error is returned.

One of the fields in the LINEDEVCAPS structure returned by this function contains the number of addresses assigned to the specified line device. The actual address IDs used to reference individual addresses vary from zero to one less than the returned number. The capabilities of each address may be different. Use lineGetAddressCaps for each available <dwDeviceID, dwAddressID> combination to determine the exact capabilities of each address.


 lineGetDevConfig

[New - Windows 95]

LONG lineGetDevConfig (DWORD dwDeviceID, LPVARSTRING lpDeviceConfig,
    LPCSTR lpszDeviceClass)

Returns an "opaque" data structure object the contents of which are specific to the line (service provider) and device class. The data structure object stores the current configuration of a media-stream device associated with the line device.

•	Returns zero if the function is successful or a negative error number if an error has occurred. Possible return values are:

LINEERR_BADDEVICEID	LINEERR_NODRIVER
LINEERR_INVALDEVICECLASS	LINEERR_OPERATIONUNAVAIL
LINEERR_INVALPOINTER	LINEERR_RESOURCEUNAVAIL
LINEERR_STRUCTURETOOSMALL	LINEERR_OPERATIONFAILED
LINEERR_NOMEM	LINEERR_UNINITIALIZED
LINEERR_NODEVICE
dwDeviceID

Specifies the line device to be configured.

lpDeviceConfig

Specifies a pointer to the memory location of type VARSTRING where the device configuration structure is returned. Upon successful completion of the request, this location is filled with the device configuration. The dwStringFormat field in the VARSTRING structure will be set to STRINGFORMAT_BINARY. Prior to calling lineGetDevConfig, the application should set the dwTotalSize field of this structure to indicate the amount of memory available to TAPI.DLL for returning information.

lpszDeviceClass

Specifies a pointer to a NULL-terminated ASCII string that specifies the device class of the device whose configuration is requested. Valid device class lineGetID strings are the same as those specified for the function.

Call states are device specific.

This function can be used to retrieve a data structure from TAPI that specifies the configuration of a media stream device associated with a particular line device. For example, the contents of this structure could specify data rate, character format, modulation schemes, and error control protocol settings for a "datamodem" media device associated with the line.

Typically, an application will call lineGetID to identify the media stream device associated with a line, and then call lineConfigDialog to allow the user to set up the device configuration. It could then call lineGetDevConfig, and save the configuration information in a phone book (or other database) associated with a particular call destination. When the user later wishes to call the same destination again, lineSetDevConfig can be used to restore the configuration settings selected by the user. The functions lineSetDevConfig, lineConfigDialog, and lineGetDevConfig can be used, in that order, to allow the user to view and update the settings.

The exact format of the data contained within the structure is specific to the line and media stream API (device class), is undocumented, and is undefined. The structure returned by this function cannot be directly accessed or manipulated by the application, but can only be stored intact and later used in lineSetDevConfig to restore the settings. The structure also cannot necessarily be passed to other devices, even of the same device class (although this may work in some instances, it is not guaranteed).


 lineGetIcon

[New - Windows 95]

LONG lineGetIcon(DWORD dwDeviceID, LPCSTR lpszDeviceClass,
    LPHICON lphIcon)

Allows an application to retrieve a service line device-specific (or provider-specific) icon for display to the user.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

LINEERR_BADDEVICEID	LINEERR_OPERATIONFAILED
LINEERR_INVALPOINTER	LINEERR_RESOURCEUNAVAIL
LINEERR_INVALDEVICECLASS	LINEERR_UNINITIALIZED
LINEERR_NOMEM	LINEERR_NODEVICE
dwDeviceID

Specifies the line device whose icon is requested.

lpszDeviceClass

Specifies a pointer to a NULL-terminated string that identifies a device class name. This device class allows the application to select a specific sub-icon applicable to that device class. This parameter is optional and can be left NULL or empty, in which case the highest-level icon associated with the line device rather than a specified media stream device would be selected.

lphIcon

Specifies a pointer to a memory location in which the handle to the icon is returned.

The lineGetIcon function causes the provider to return a handle (in lphIcon) to an icon resource (obtained from LoadIcon) that is associated with the specified line. The icon handle is for a resource associated with the provider. The application must use CopyIcon if it wishes to reference the icon after the provider is unloaded, which is unlikely to happen as long as the application has the line open.

lpszDeviceClass allows the provider to return different icons based on the type of service being referenced by the caller. The permitted strings are the same as for lineGetID. For example, if the line supports the Comm API, passing "COMM" as lpszDeviceClass causes the provider to return an icon related specifically to the Comm device functions of the service provider.

The parameters "tapi/line", "a", or NULL may be used to request the icon for the line service. If the provider does not return an icon, TAPI.DLL substitutes a generic Windows Telephony line device icon.


 lineGetID

[New - Windows 95]

LONG lineGetID(HLINE hLine, DWORD dwAddressID, HCALL hCall,
    DWORD dwSelect, LPVARSTRING lpDeviceID, LPCSTR lpszDeviceClass)

Returns a device ID for the specified device class associated with the selected line, address, or call.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

LINEERR_INVALLINEHANDLE	LINEERR_NOMEM
LINEERR_INVALADDRESSID	LINEERR_OPERATIONUNAVAIL
LINEERR_INVALCALLHANDLE	LINEERR_OPERATIONFAILED
LINEERR_INVALCALLSELECT	LINEERR_RESOURCEUNAVAIL
LINEERR_INVALPOINTER	LINEERR_STRUCTURETOOSMALL
LINEERR_NODEVICE	LINEERR_UNINITIALIZED
hLine

Specifies a handle to an open line device.

dwAddressID

Specifies an address on the given open line device.

hCall

Specifies a handle to a call.

dwSelect

Specifies whether the requested device ID is associated with the line, address or a single call. The dwSelect parameter can only have a single flag set. This parameter uses the following LINECALLSELECT_ constants:

LINECALLSELECT_LINE

Selects the specified line device. The hLine parameter must be a valid line handle; hCall and dwAddressID are ignored.

LINECALLSELECT_ADDRESS

Selects the specified address on the line. Both hLine and dwAddressID must be valid; hCall is ignored.

LINECALLSELECT_CALL

Selects the specified call. hCall must be valid; hLine and dwAddressID are both ignored.

lpDeviceID

Specifies a pointer to a memory location of type VARSTRING, where the device ID is returned. Upon successful completion of the request, this location is filled with the device ID. The format of the returned information depends on the method used by the device class API for naming devices. Prior to calling lineGetID, the application should set the dwTotalSize field of this structure to indicate the amount of memory available to TAPI.DLL for returning information.

lpszDeviceClass

Specifies a pointer to a NULL-terminated ASCII string that specifies the device class of the device whose ID is requested. Valid device class strings are those used in the SYSTEM.INI section to identify device classes.

This function can be used to retrieve a line-device ID when given a line handle. This is useful after a line device has been opened using LINEMAPPER as a device ID in order to determine the real line-device ID of the opened line. This function can also be used to obtain the device ID of a phone device or media device (for device classes such as COM, wave, MIDI, phone, line, or NDIS) associated with a call, address or line. This ID can then be used with the appropriate API (such as phone, midi, wave) to select the corresponding media device associated with the specified call.

See Chapter 9, "Device Classes" for device class names.

A vendor that defines a device-specific media mode also needs to define the corresponding device-specific (proprietary) API to manage devices of the media mode. To avoid collisions on device class names assigned independently by different vendors, a vendor should select a name that uniquely identifies both the vendor and, following it, the media type. For example: "intel/video".


 lineGetLineDevStatus

[New - Windows 95]

LONG lineGetLineDevStatus(HLINE hLine, LPLINEDEVSTATUS lpLineDevStatus)

Enables an application to query the specified open line device for its current status.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

LINEERR_INVALLINEHANDLE	LINEERR_RESOURCEUNAVAIL
LINEERR_INVALPOINTER	LINEERR_STRUCTURETOOSMALL
LINEERR_NOMEM	LINEERR_UNINITIALIZED
LINEERR_OPERATIONFAILED	LINEERR_OPERATIONUNAVAIL
hLine

Specifies a handle to the open line device to be queried.

lpLineDevStatus

Specifies a pointer to a variably sized data structure of type LINEDEVSTATUS. Upon successful completion of the request, this structure is filled with the line's device status. Prior to calling lineGetLineDevStatus, the application should set the dwTotalSize field of this structure to indicate the amount of memory available to TAPI.DLL for returning information.

An application uses lineGetLineDevStatus to query the line device for its current line status. This status information applies globally to all addresses on the line device. Use lineGetAddressStatus to determine status information about a specific address on a line.


 lineGetNewCalls

[New - Windows 95]

LONG lineGetNewCalls(HLINE hLine, DWORD dwAddressID, DWORD dwSelect,
     LPLINECALLLIST lpCallList)

Returns call handles to calls on a specified line or address for which the application currently does not have handles. The application is granted monitor privilege to these calls.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

LINEERR_INVALADDRESSID	LINEERR_OPERATIONFAILED
LINEERR_INVALCALLSELECT	LINEERR_RESOURCEUNAVAIL
LINEERR_INVALLINEHANDLE	LINEERR_STRUCTURETOOSMALL
LINEERR_INVALPOINTER	LINEERR_UNINITIALIZED
LINEERR_NOMEM
hLine

Specifies a handle to an open line device.

dwAddressID

Specifies an address on the given open line device.

dwSelect

Specifies the selection of calls that are requested. Note that dwSelect can only have one bit set. This parameter uses the following LINECALLSELECT_ constants:

LINECALLSELECT_LINE

Selects calls on the specified line device. The hLine parameter must be a valid line handle; dwAddressID is ignored.

LINECALLSELECT_ADDRESS

Selects calls on the specified address on the specified line device. Both hLine and dwAddressID must be valid.

lpCallList

Specifies a pointer to a variably sized data structure of type LINECALLLIST. Upon successful completion of the request, call handles to all selected calls are returned in this structure. Prior to calling lineGetNewCalls, the application should set the dwTotalSize field of this structure to indicate the amount of memory available to TAPI.DLL for returning information.

An application can use lineGetNewCalls to obtain handles to calls for which it currently has no handles. The application can select the calls for which handles are to be returned by basing this selection on scope (calls on a specified line, or calls on a specified address). For example, an application can request call handles to all calls on a given address for which it currently has no handle. The application is always given monitor privilege to the new call handles. Also, when opening a line, an application uses this function to become aware of existing calls.

The application can invoke lineGetCallInfo and lineGetCallStatus for each call in the list to determine the call's information and status, respectively. It can use lineSetCallPrivilege to change its privilege to owner.


 lineGetNumRings

[New - Windows 95]

LONG lineGetNumRings(HLINE hLine, DWORD dwAddressID,
    LPDWORD lpdwNumRings)

Determines the number of rings an inbound call on the given address should ring prior to answering the call.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

LINEERR_INVALADDRESSID	LINEERR_OPERATIONFAILED
LINEERR_INVALLINEHANDLE	LINEERR_RESOURCEUNAVAIL
LINEERR_INVALPOINTER	LINEERR_UNINITIALIZED
LINEERR_NOMEM
hLine

Specifies a handle to the open line device.

dwAddressID

Specifies an address on the line device.

lpdwNumRings

Specifies the number of rings that is the minimum of all current lineSetNumRings requests.

The lineGetNumRings and lineSetNumRings functions, when used in combination, provide a mechanism to support the implementation of toll-saver features across multiple independent applications.

An application that receives a handle for a call in the offering state and a LINE_LINEDEVSTATE ringing message should wait a number of rings equal to the number returned by lineGetNumRings before answering the call in order to honor the toll-saver settings across all applications. The lineGetNumRings function returns the minimum of all application's number of rings specified by lineSetNumRings. Since this number may vary dynamically, an application should invoke lineGetNumRings each time it has the option to answer a call. If no application has called lineSetNumRings, the number or rings returned is 0xFFFFFFFF. A separate LINE_LINEDEVSTATE ringing message is sent to the application for each ring cycle.

If call classification is performed by TAPI.DLL of answering all calls of unknown media mode and filtering the media stream, TAPI.DLL honors this number as well.

Note that this operation is purely informational and does not in itself affect the state of any calls on the line device.


 lineGetProviderList

[New - Windows 95]

LONG lineGetProviderList (DWORD dwAPIVersion,
    LPLINEPROVIDERLIST lpProviderList)

Returns a list of service providers currently installed in the telephony system.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

LINEERR_INCOMPATIBLEAPIVERSION	LINEERR_NOMEM
LINEERR_INIFILECORRUPT	LINEERR_OPERATIONFAILED
LINEERR_INVALPOINTER	LINEERR_STRUCTURETOOSMALL
dwAPIVersion

Indicates the highest version of TAPI supported by the application (not necessarily the value negotiated by lineNegotiateAPIVersion on some particular line device).

lpProviderList

Specifies a pointer to a memory location where TAPI will return a LINEPROVIDERLIST structure. Prior to calling lineGetProviderList, the application should set the dwTotalSize field of this structure to indicate the amount of memory available to TAPI for returning information.

Although this is a new function which older applications would not be expected to call, for backward compatibility, they should not be prevented from doing so; the function will work the same way for all applications.


 lineGetRequest

[New - Windows 95]

LONG lineGetRequest(HLINEAPP hLineApp, DWORD dwRequestMode,
    LPVOID lpRequestBuffer)

Retrieves the next by-proxy request for the specified request mode.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

LINEERR_INVALAPPHANDLE	LINEERR_NOTREGISTERED
LINEERR_INVALPOINTER	LINEERR_OPERATIONFAILED
LINEERR_INVALREQUESTMODE	LINEERR_RESOURCEUNAVAIL
LINEERR_NOMEM	LINEERR_UNINITIALIZED
LINEERR_NOREQUEST
hLineApp

Specifies the application's usage handle for the line portion of TAPI.

dwRequestMode

Specifies the type of request that is to be obtained. Note that dwRequestMode can only have one bit set. This parameter uses the following LINEREQUESTMODE_ constants:

LINEREQUESTMODE_MAKECALL

A tapiRequestMakeCall request.

lpRequestBuffer

Specifies a pointer to a memory buffer where the parameters of the request are to be placed. The size of the buffer and the interpretation of the information placed in the buffer depends on the request mode. The application-allocated buffer is assumed to be of sufficient size to hold the request.

If dwRequestMode is LINEREQUESTMODE_MAKECALL, interpret the content of the request buffer using the LINEREQMAKECALL structure.

If dwRequestMode is LINEREQUESTMODE_MEDIACALL, interpret the content of the request buffer using the LINEREQMEDIACALL structure.

A telephony-enabled application can request that a call be placed on its behalf by invoking tapiRequestMakeCall. These requests are queued by TAPI.DLL and the highest priority application that has registered to handle the request is sent a LINE_REQUEST message with indication of the mode of the request that is pending. Typically, this application is the user's call-control application. The LINE_REQUEST message indicates that zero or more requests may be pending for the registered application to process; after receiving LINE_REQUEST, it is the responsibility of the recipient application to call lineGetRequest until LINEERR_NOREQUEST is returned, indicating that no more requests are pending.

Next, the call-control application that receives this message invokes lineGetRequest, specifying the request mode and a buffer that is large enough to hold the request. The call-control application then interprets and executes the request.

After execution of lineGetRequest, TAPI.DLL purges the request from its internal queue, making room available for a subsequent request. It is therefore possible for a new LINE_REQUEST message to be received immediately upon execution of lineGetRequest, should the same or another application issue another request. It is the responsibility of the request recipient application to handle this scenario by some mechanism (for example, by making note of the additional LINE_REQUEST and deferring a subsequent lineGetRequest until processing of the preceeding request completes, by getting the subsequent request and buffer as necessary, or by another appropriate means).

Note that the subsequent LINE_REQUEST should not be ignored because it will not be repeated by TAPI.DLL.


 lineGetStatusMessages

[New - Windows 95]

LONG lineGetStatusMessages(HLINE hLine, LPDWORD lpdwLineStates,
    LPDWORD lpdwAddressStates)

This operation enables an application to query which notification messages the application is set up to receive for events related to status changes for the specified line or any of its addresses.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

LINEERR_INVALLINEHANDLE	LINEERR_OPERATIONFAILED
LINEERR_INVALPOINTER	LINEERR_RESOURCEUNAVAIL
LINEERR_NOMEM	LINEERR_UNINITIALIZED
hLine

Specifies a handle to the line device.

lpdwLineStates

Specifies a bit array that identifies for which line device status changes a message is to be sent to the application. If a flag is TRUE, that message is enabled; if FALSE, it is disabled. Note that multiple flags can be set. This parameter uses the following LINEDEVSTATE_ constants:

LINEDEVSTATE_OTHER

Device-status items other than those listed below have changed. The application should check the current device status to determine which items have changed.

LINEDEVSTATE_RINGING

The switch tells the line to alert the user.

LINEDEVSTATE_CONNECTED

The line was previously disconnected and is now connected to TAPI.

LINEDEVSTATE_NUMCOMPLETIONS

The number of outstanding call completions on the line device has changed.

LINEDEVSTATE_DISCONNECTED

This line was previously connected and is now disconnected from TAPI.

LINEDEVSTATE_MSGWAITON

The "message waiting" indicator is turned on.

LINEDEVSTATE_MSGWAITOFF

The "message waiting" indicator is turned off.

LINEDEVSTATE_INSERVICE

The line is connected to TAPI. This happens when TAPI is first activated or when the line wire is physically plugged in and in service at the switch while TAPI is active.

LINEDEVSTATE_OUTOFSERVICE

The line is out of service at the switch or physically disconnected. TAPI cannot be used to operate on the line device.

LINEDEVSTATE_MAINTENANCE

Maintenance is being performed on the line at the switch. TAPI cannot be used to operate on the line device.

LINEDEVSTATE_OPEN

The line has been opened by some application.

LINEDEVSTATE_CLOSE

The line has been closed by some application.

LINEDEVSTATE_NUMCALLS

The number of calls on the line device has changed.

LINEDEVSTATE_TERMINALS

The terminal settings have changed.

LINEDEVSTATE_ROAMMODE

The roam mode of the line device has changed.

LINEDEVSTATE_BATTERY

The battery level has changed significantly (cellular).

LINEDEVSTATE_SIGNAL

The signal level has changed significantly (cellular).

LINEDEVSTATE_DEVSPECIFIC

The line's device-specific information has changed.

LINEDEVSTATE_REINIT

Items have changed in the configuration of line devices. To become aware of these changes (for example, the appearance of new line devices) the application should reinitialize its use of TAPI. The hDevice parameter parameter of the LINE_LINEDEVSTATE message is left NULL for this state change as it applies to any of the lines in the system.

LINEDEVSTATE_LOCK

The locked status of the line device has changed.

lpdwAddressStates

Specifies a bit array that identifies for which address status changes a message is to be sent to the application. If a flag is TRUE, that message is enabled; if FALSE, disabled. Multiple flags can be set. This parameter uses the following LINEADDRESSSTATE_ constants:

LINEADDRESSSTATE_OTHER

Address-status items other than those listed below have changed. The application should check the current address status to determine which items have changed.

LINEADDRESSSTATE_DEVSPECIFIC

The device-specific item of the address status has changed.

LINEADDRESSSTATE_INUSEZERO

The address has changed to idle (it is now in use by zero stations).

LINEADDRESSSTATE_INUSEONE

The address has changed from being idle or from being in use by many bridged stations to being in use by just one station.

LINEADDRESSSTATE_INUSEMANY

The monitored or bridged address has changed from being in use by one station to being used by more than one station.

LINEADDRESSSTATE_NUMCALLS

The number of calls on the address has changed. This is the result of events such as a new inbound call, an outbound call on the address, or a call changing its hold status.

LINEADDRESSSTATE_FORWARD

The forwarding status of the address has changed, including the number of rings for determining a "no answer" condition. The application should check the address status to determine details about the address's current forwarding status.

LINEADDRESSSTATE_TERMINALS

The terminal settings for the address have changed.

TAPI defines a number of messages that notify applications about events occurring on lines and addresses. An application may not be interested in receiving all address and line status change messages. The lineSetStatusMessages function can be used to select which messages the application wants to receive. By default, address status and line status reporting is disabled.


 lineGetTranslateCaps

[New - Windows 95]

LONG lineGetTranslateCaps(HLINEAPP hLineApp, DWORD dwAPIVersion,
    LPLINETRANSLATECAPS lpTranslateCaps)

Returns address translation capabilities.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

LINEERR_INCOMPATIBLEAPIVERSION	LINEERR_NOMEM
LINEERR_INIFILECORRUPT	LINEERR_OPERATIONFAILED
LINEERR_INVALAPPHANDLE	LINEERR_RESOURCEUNAVAIL
LINEERR_INVALPOINTER	LINEERR_STRUCTURETOOSMALL
LINEERR_NODRIVER	LINEERR_UNINITIALIZED
hLineApp

Specifies the application handle returned by lineInitialize.

dwAPIVersion

Indicates the version of TAPI negotiated by lineNegotiateAPIVersion.

lpTranslateCaps

Specifies a pointer to a location to which a LINETRANSLATECAPS structure will be loaded. Prior to calling lineGetTranslateCaps, the application should set the dwTotalSize field of this structure to indicate the amount of memory available to TAPI.DLL for returning information.

If an application has not yet called the lineInitialize function, it can set the hLineApp parameter to NULL and the dwDevice parameter to 0 when calling the lineGetTranslateCaps function.


 lineHandoff

[New - Windows 95]

LONG lineHandoff(HCALL hCall, LPCSTR lpszFileName, DWORD dwMediaMode)

Gives ownership of the specified call to another application. The application can be either specified directly by its file name or indirectly as the highest priority application that handles calls of the specified media mode.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

LINEERR_INVALCALLHANDLE	LINEERR_OPERATIONFAILED
LINEERR_INVALMEDIAMODE	LINEERR_TARGETNOTFOUND
LINEERR_INVALPOINTER	LINEERR_TARGETSELF
LINEERR_NOMEM	LINEERR_UNINITIALIZED
LINEERR_NOTOWNER
hCall

Specifies a handle to the call to be handed off. The application must be an owner of the call. Call state of hCall can be any state.

lpszFileName

Specifies a pointer to a NULL-terminated ASCII string. If this pointer parameter is non-NULL, it contains the file name of the application that is the target of the handoff. If NULL, the handoff target is the highest priority application that has opened the line for owner privilege for the specified media mode. A valid file name does not include the path of the file.

dwMediaMode

Specifies the media mode used to identify the target for the indirect handoff. The dwMediaMode parameter indirectly identifies the target application that is to receive ownership of the call. This parameter is ignored if lpszFileName is not NULL. Only a single flag may be set in the dwMediaMode parameter at any one time. This parameter uses the following LINEMEDIAMODE_ constants:

LINEMEDIAMODE_UNKNOWN

The target application is the one that handles calls of unknown media mode (unclassified calls).

LINEMEDIAMODE_INTERACTIVEVOICE

The target application is the one that handles calls with the interactive voice media mode (live conversations).

LINEMEDIAMODE_AUTOMATEDVOICE

Voice energy is present on the call and the voice is locally handled by an automated application.

LINEMEDIAMODE_DATAMODEM

The target application is the one that handles calls with the data modem media mode.

LINEMEDIAMODE_G3FAX

The target application is the one that handles calls with the group 3 fax media mode.

LINEMEDIAMODE_TDD

The target application is the one that handles calls with the TDD (Telephony Devices for the Deaf) media mode.

LINEMEDIAMODE_G4FAX

The target application is the one that handles calls with the group 4 fax media mode.

LINEMEDIAMODE_DIGITALDATA

The target application is the one that handles calls that are digital data calls.

LINEMEDIAMODE_TELETEX

The target application is the one that handles calls with the teletex media mode.

LINEMEDIAMODE_VIDEOTEX

The target application is the one that handles calls with the videotex media mode.

LINEMEDIAMODE_TELEX

The target application is the one that handles calls with the telex media mode.

LINEMEDIAMODE_MIXED

The target application is the one that handles calls with the ISDN mixed media mode.

LINEMEDIAMODE_ADSI

The target application is the one that handles calls with the ADSI (Analog Display Services Interface) media mode.

LINEMEDIAMODE_VOICEVIEW

The media mode of the call is VoiceView.

If LINEERR_TARGETNOTFOUND is returned, a target for the call handoff was not found. This may occur if the named application did not open the same line with the LINECALLPRIVILEGE_OWNER bit in the dwPrivileges parameter of lineOpen. Or, in the case of media-mode handoff, no application has opened the same line with the LINECALLPRIVILEGE_OWNER bit in the dwPrivileges parameter of lineOpen and with the media mode specified in the dwMediaMode parameter having been specified in the dwMediaModes parameter of lineOpen.

Call handoff allows ownership of a call to be passed among applications. There are two types of handoff. In the first type, if the application knows the file name of the target application, it can simply specify the file name of that application. If an instance of the target application has opened the line device, ownership of the call will be passed to the other application; otherwise, the handoff will fail and an error is returned. This form of handoff will succeed if the call handle is handed off to the same file name as the application requesting the handoff.

The second type of handoff is based on media mode. In this case, the application indirectly specifies the target application by means of a media mode. The highest priority application that has currently opened the line device for that media mode is the target for the handoff. If there is no such application, the handoff fails and an error is returned.

The lineHandoff function does not change the media mode of a call. To change the media mode of a call, the application should use lineSetMediaMode on the call, specifying the new media mode. This changes the call's media as stored in the call's LINECALLINFO structure.

If handoff is successful, the receiving application will receive a LINE_CALLSTATE message for the call. This message indicates that the receiving application has owner privilege to the call (dwParam3). In addition, the number of owners and/or monitors for the call may have changed. This is reported by the LINE_CALLINFO message, and the receiving application can then invoke lineGetCallStatus and lineGetCallInfo to retrieve more information about the received call.

The receiving application should first check the media mode in LINECALLINFO. If only a single media mode flag is set, the call is officially of that media mode, and the application can act accordingly. If UNKNOWN and other media mode flags are set, then the media mode of the call is officially UNKNOWN but is assumed to be of one of the media modes for which a flag is set in LINECALLINFO. The application should assume that it ought to probe for the highest priority media mode.

If the probe succeeds (either for that media mode or for another one), the application should set the media mode field in LINECALLINFO to just the single media mode that was recognized. If the media mode is for that media mode, the application can act accordingly; otherwise, if it makes a determination for another media mode, it must first hand off the call to that media mode.

If the probe fails, the application should clear the corresponding media mode flag in LINECALLINFO and hand off the callback, specifying dwMediaMode as LINEMEDIAMODE_UNKNOWN. It should also deallocate its call handle (or revert back to monitoring).

If none of the media modes succeeded in making a determination, only the UNKNOWN flag will remain set in the media mode field of LINECALLINFO at the time the media application attempts to hand off the call back to UNKNOWN. The final lineHandoff will fail if the application is the only remaining owner of the call. This informs the application that it should drop the call and deallocate its handle, in which case the call is abandoned. The privileges of the invoking application to the call are unchanged by this operation, but the application can change its privileges to a call with lineSetCallPrivilege.


 lineHold

[New - Windows 95]

LONG lineHold(HCALL hCall)

Places the specified call on hold.

•	Returns a positive request ID if the function will be completed asynchronously or a negative error number if an error has occurred. The dwParam2 parameter of the corresponding LINE_REPLY callback message is zero if the function is successful or it is a negative error number if an error has occurred. Possible return values are:

LINEERR_INVALCALLHANDLE	LINEERR_OPERATIONUNAVAIL
LINEERR_INVALCALLSTATE	LINEERR_OPERATIONFAILED
LINEERR_NOMEM	LINEERR_RESOURCEUNAVAIL
LINEERR_NOTOWNER	LINEERR_UNINITIALIZED
hCall

Specifies a handle to the call to be placed on hold. The application must be an owner of the call. Call state of hCall must be connected.

The call on hold is temporarily disconnected allowing the application to use the line device for making or answering other calls. The lineHold function performs a so-called "hard hold" of the specified call (as opposed to a "consultation call"). A call on hard hold typically cannot be transferred or included in a conference call, but a consultation call can. Consultation calls are initiated using lineSetupTransfer, lineSetupConference, or linePrepareAddToConference.

After a call has been successfully placed on hold, the call state typically transitions to onHold. A held call is retrieved by lineUnhold. While a call is on hold, the application may receive LINE_CALLSTATE messages about state changes of the held call. For example, if the held party hangs up, the call state may transition to disconnected.


 lineInitialize

[New - Windows 95]

LONG lineInitialize(LPHLINEAPP lphLineApp, HINSTANCE hInstance,
    LINECALLBACK lpfnCallback, LPCSTR lpszAppName, LPDWORD lpdwNumDevs)

Initializes the application's use of TAPI.DLL for subsequent use of the line abstraction. It registers the application's specified notification mechanism and returns the number of line devices available to the application. A line device is any device that provides an implementation for the line-prefixed functions in the Telephony API.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

LINEERR_INVALAPPNAME	LINEERR_OPERATIONFAILED
LINEERR_INIFILECORRUPT	LINEERR_RESOURCEUNAVAIL
LINEERR_INVALPOINTER	LINEERR_REINIT
LINEERR_NODRIVER	LINEERR_NODEVICE
LINEERR_NOMEM	LINEERR_NOMULTIPLEINSTANCE
lphLineApp

Specifies a pointer to a location that is filled with the application's usage handle for TAPI.

hInstance

Specifies the instance handle of the client application or DLL.

lpfnCallback

Specifies the address of a callback function that is invoked to determine status and events on the line device, addresses, or calls. For more information see lineCallbackFunc.

lpszAppName

Specifies a pointer to a NULL-terminated ASCII string that contains only displayable ASCII characters. If this parameter is not NULL, it contains an application-supplied name of the application. This name is provided in the LINECALLINFO structure to indicate, in a user-friendly way, which application originated, or originally accepted or answered the call. This information can be useful for call logging purposes. If lpszAppName is NULL, the application's file name is used instead.

lpdwNumDevs

Specifies a pointer to a DWORD-sized location. Upon successful completion of this request, this location is filled with the number of line devices available to the application.

If LINEERR_REINIT is returned and TAPI reinitialization has been requested, for example as a result of adding or removing a Telephony service provider, then lineInitialize requests are rejected with this error until the last application shuts down its usage of the API (using lineShutdown), at which time the new configuration becomes effective and applications are once again permitted to call lineInitialize.

If the LINEERR_INVALPARAM error value is returned, the specified hInstance parameter is invalid.

The application can refer to individual line devices by using line device IDs that range from zero to dwNumDevs minus one. An application should not assume that these line devices are capable of anything beyond what is specified by the Basic Telephony subset without first querying their device capabilities by lineGetDevCaps and lineGetAddressCaps.

Applications should not invoke lineInitialize without subsequently opening a line (at least for monitoring). If the application is not monitoring and not using any devices, it should call lineShutdown so that memory resources allocated by TAPI.DLL can be released if unneeded, and TAPI.DLL itself can be unloaded from memory while not needed.

Another reason for performing a lineShutdown is that if a user changes the device configuration (adds or removes a line or phone), there is no way for TAPI to notify an application that has a line or phone handle open at the time. Once a reconfiguration has taken place, causing a LINEDEVSTATE_REINIT message to be sent, no applications can open a device until all applications have performed a lineShutdown.

If any service provider fails to initialize properly, this function fails and returns the error indicated by the service provider.


 lineCallbackFunc

[New - Windows 95]

VOID FAR PASCAL lineCallbackFunc(DWORD hDevice, DWORD dwMsg,
    DWORD dwCallbackInstance, DWORD dwParam1, DWORD dwParam2,
    DWORD dwParam3)

The lineCallbackFunc function is a placeholder for the application-supplied function name.

hDevice

Specified a handle to either a line device or a call associated with the callback. The nature of this handle (line handle or call handle) can be determined by the context provided by dwMsg. Applications must use the DWORD type for this parameter since using the HANDLE type may generate an error.

dwMsg

Specifies a line or call device message.

dwCallbackInstance

Specifies callback instance data passed back to the application in the callback. This DWORD is not interpreted by TAPI.

dwParam1

Specifies a parameter for the message.

dwParam2

Specifies a parameter for the message.

dwParam3

Specifies a parameter for the message.

For information about parameters values passed to this function, see Chapter 11, "Line Device Messages."

All callbacks occur in the application's context. The callback function must reside in a dynamic link library (DLL) or application module.


 lineMakeCall

[New - Windows 95]

LONG lineMakeCall(HLINE hLine, LPHCALL lphCall, LPCSTR lpszDestAddress,
    DWORD dwCountryCode, LPLINECALLPARAMS const lpCallParams)

Places a call on the specified line to the specified destination address. Optionally, call parameters can be specified if anything but default call setup parameters are requested.

•	Returns a positive request ID if the function will be completed asynchronously, or a negative error number if an error has occurred. The dwParam2 parameter of the corresponding LINE_REPLY callback message is zero if the function is successful or it is a negative error number if an error has occurred. Possible return values are:

LINEERR_ADDRESSBLOCKED	LINEERR_INVALLINEHANDLE
LINEERR_BEARERMODEUNAVAIL	LINEERR_INVALLINESTATE
LINEERR_CALLUNAVAIL	LINEERR_INVALMEDIAMODE
LINEERR_DIALBILLING	LINEERR_INVALPARAM
LINEERR_DIALDIALTONE	LINEERR_INVALPOINTER
LINEERR_DIALPROMPT	LINEERR_INVALRATE
LINEERR_DIALQUIET	LINEERR_NOMEM
LINEERR_INUSE	LINEERR_OPERATIONFAILED
LINEERR_INVALADDRESS	LINEERR_OPERATIONUNAVAIL
LINEERR_INVALADDRESSID	LINEERR_RATEUNAVAIL
LINEERR_INVALADDRESSMODE	LINEERR_RESOURCEUNAVAIL
LINEERR_INVALBEARERMODE	LINEERR_STRUCTURETOOSMALL
LINEERR_INVALCALLPARAMS	LINEERR_UNINITIALIZED
LINEERR_INVALCOUNTRYCODE	LINEERR_USERUSERINFOTOOBIG
hLine

Specifies a handle to the open line device on which a call is to be originated.

lphCall

Specifies a pointer to an HCALL handle. The handle is only valid after the LINE_REPLY message is received by the application indicating that the lineMakeCall function successfully completed. Use this handle to identify the call when invoking other telephony operations on the call. The application will initially be the sole owner of this call. This handle is void if the function returns an error (synchronously or asynchronously by the reply message).

lpszDestAddress

Specifies a pointer to the destination address. This follows the standard dialable number format. This pointer can be NULL for non-dialed addresses (as with a hot phone) or when all dialing will be performed using lineDial. In the latter case, lineMakeCall allocates an available call appearance that would typically remain in the dialtone state until dialing begins. Service providers that have inverse multiplexing capabilities may allow an application to specify multiple addresses at once.

dwCountryCode

Specifies the country code of the called party. If a value of zero is specified, a default is used by the implementation.

lpCallParams

Specifies a pointer to a LINECALLPARAMS structure. This structure allows the application to specify how it wants the call to be set up. If NULL is specified, a default 3.1kHz voice call is established and an arbitrary origination address on the line is selected. This structure allows the application to select elements such as the call's bearer mode, data rate, expected media mode, origination address, blocking of caller ID information, and dialing parameters.

If LINEERR_INVALLINESTATE is returned, the line is currently not in a state in which this operation can be performed. A list of currently valid operations can be found in the dwLineFeatures field (of the type LINEFEATURE_) in the LINEDEVSTATUS structure. Calling lineGetLineDevStatus updates the information in LINEDEVSTATUS. If LINEERR_DIALBILLING, LINEERR_DIALQUIET, LINEERR_DIALDIALTONE, or LINEERR_DIALPROMPT is returned, none of the actions otherwise performed by lineMakeCall have occured; for example, none of the dialable address prior to the offending character has been dialed, no hookswitch state has changed, and so on.

After dialing has completed, several LINE_CALLSTATE messages are usually sent to the application to notify it about the progress of the call. No generally valid sequence of call-state transitions is specified, as no single fixed sequence of transitions can be guaranteed in practice. A typical sequence may cause a call to transition from dialtone, dialing, proceeding, ringback, to connected. With non-dialed lines, the call may typically transition directly to connected state.

An application has the option to specify an originating address on the specified line device. A service provider that models all stations on a switch as addresses on a single line device allows the application to originate calls from any of these stations using lineMakeCall.

The call parameters allow the application to make non-voice calls or request special call setup options that are not available by default.

An application can partially dial using lineMakeCall and continue dialing using lineDial. To abandon a call attempt, use lineDrop.

After lineMakeCall returns a SUCCESS reply callback message to the application, a LINE_CALLSTATE message is sent to the application to indicate the current state of the call. This state will not necessarily be LINECALLSTATE_DIALTONE.


 lineMonitorDigits

[New - Windows 95]

LONG lineMonitorDigits(HCALL hCall, DWORD dwDigitModes)

Enables and disables the unbuffered detection of digits received on the call. Each time a digit of the specified digit mode(s) is detected, a message is sent to the application indicating which digit has been detected.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

LINEERR_INVALCALLHANDLE	LINEERR_OPERATIONUNAVAIL
LINEERR_INVALCALLSTATE	LINEERR_OPERATIONFAILED
LINEERR_INVALDIGITMODE	LINEERR_RESOURCEUNAVAIL
LINEERR_NOMEM	LINEERR_UNINITIALIZED
hCall

Specifies a handle to the call on which digits are to be detected. Call state of hCall can be any state except idle or disconnected.

dwDigitModes

Specifies the digit mode(s) that are to be monitored. If dwDigitModes is zero, digit monitoring is cancelled. This parameter can have multiple flags set, and uses the following LINEDIGITMODE_ constants:

LINEDIGITMODE_PULSE

Detect digits as audible clicks that are the result of rotary pulse sequences. Valid digits for pulse are '0' through '9'.

LINEDIGITMODE_DTMF

Detect digits as DTMF tones. Valid digits for DTMF are '0' through '9', 'A', 'B', 'C', 'D', '*', and '#'.

LINEDIGITMODE_DTMFEND

Detect and provide application notification of DTMF down edges. Valid digits for DTMF are '0' through '9', 'A', 'B', 'C', 'D', '*', and '#'.

This function is considered successful if digit monitoring has been correctly initiated; not when digit monitoring has terminated. Digit monitoring remains in effect until it is explicitly disabled by calling lineMonitorDigits with dwDigitModes set to zero, until the call transitions to idle, or when the application deallocates its call handle for the call. Although this function can be invoked in any call state, digits are usually detected only while the call is in the connected state.

Each time a digit is detected, a LINE_MONITORDIGITS message is sent to the application passing the detected digit as a parameter.

An application can use lineMonitorDigits to enable or disable unbuffered digit detection. It can use lineGatherDigits for buffered digit detection. After buffered digit gathering is complete, a LINE_GATHERDIGITS message is sent to the application. Both buffered and unbuffered digit detection can be enabled on the same call simultaneously.

Monitoring of digits on a conference call applies only to the hConfCall, not to the individual participating calls.


 lineMonitorMedia

[New - Windows 95]

LONG lineMonitorMedia(HCALL hCall, DWORD dwMediaModes)

Enables and disables the detection of media modes on the specified call. When a media mode is detected, a message is sent to the application.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

LINEERR_INVALCALLHANDLE	LINEERR_OPERATIONUNAVAIL
LINEERR_INVALCALLSTATE	LINEERR_OPERATIONFAILED
LINEERR_INVALMEDIAMODE	LINEERR_RESOURCEUNAVAIL
LINEERR_NOMEM	LINEERR_UNINITIALIZED
hCall

Specifies a handle to the call. Call state of hCall can be any state except idle.

dwMediaModes

Specifies the media modes to be monitored. A value of zero for the dwMediaModes parameter cancels all media mode detection. This parameter can have multiple flags set. This parameter uses the following LINEMEDIAMODE_ constants:

LINEMEDIAMODE_INTERACTIVEVOICE

The application wants to handle calls of the interactive voice media type (it manages live voice calls).

LINEMEDIAMODE_AUTOMATEDVOICE

Voice energy is present on the call and the voice is locally handled by an automated application.

LINEMEDIAMODE_DATAMODEM

The application wants to handle calls with the data modem media mode.

LINEMEDIAMODE_G3FAX

The application wants to handle calls of the group 3 fax media type.

LINEMEDIAMODE_TDD

The application wants to handle calls with the TDD (Telephony Devices for the Deaf) media mode.

LINEMEDIAMODE_G4FAX

The application wants to handle calls of the group 4 fax media type.

LINEMEDIAMODE_DIGITALDATA

The application wants to handle calls of the digital data media type

LINEMEDIAMODE_TELETEX

The application wants to handle calls with the teletex media mode.

LINEMEDIAMODE_VIDEOTEX

The application wants to handle calls with the videotex media mode.

LINEMEDIAMODE_TELEX

The application wants to handle calls with the telex media mode.

LINEMEDIAMODE_MIXED

The application wants to handle calls with the ISDN mixed media mode.

LINEMEDIAMODE_ADSI

The application wants to handle calls with the ADSI (Analog Display Services Interface) media mode.

LINEMEDIAMODE_VOICEVIEW

The media mode of the call is VoiceView.

The media modes specified with lineOpen relate only to enabling the detection of these media modes by the service provider for the purpose of handing off new incoming calls to the proper application. They do not impact any of the media-mode notification messages that are expected because of a previous invocation of lineMonitorMedia.

This function is considered successful if media-mode monitoring has been correctly initiated, not when media mode monitoring has terminated. Media monitoring for a given media mode remains in effect until it is explicitly disabled by calling lineMonitorMedia with a dwMediaModes parameter set to zero, until the call transitions to idle, or when the application deallocates its call handle for the call. The lineMonitorMedia function is primarily an event reporting mechanism. The media mode of call, as indicated in LINECALLINFO, is not affected by the service provider's detection of the media mode. Only the controlling application can change a call's media mode.

Default media monitoring performed by the service provider corresponds to the union of all media modes specified on lineOpen.

Although this function can be invoked in any call state, a call's media mode can typically only be detected while the call is certain call states. These states may be device specific. For example, in ISDN, a message may indicate the media mode of the media stream before the media stream exists. Similarly, distinctive ringing or the called ID information about the call can be used to identify the media mode of a call. Otherwise, the call may have to be answered (call in the connected state) to allow a service provider to determine the call's media mode by filtering the media stream. Since filtering a call's media stream implies a computational overhead, applications should disable media monitoring when not required. By default, media monitoring is enabled for newly inbound calls, since a call's media mode selects the application that should handle the call.

An outbound application that deals with voice media modes may want to monitor the call for silence (a tone) to distinguish who or what is at the called end of a call. For example, a person at home may answer calls with just a short "hello." A person in the office may provide a longer greeting, indicating name and company name. An answering machine may typically have an even longer greeting.

Because media-mode detection enabled by lineMonitorMedia is implemented as a read-only operation of the call's media stream, it is not disruptive.

Monitoring of media on a conference call applies only to the hConfCall, not to the individual participating calls


 lineMonitorTones

[New - Windows 95]

LONG lineMonitorTones(HCALL hCall, LPLINEMONITORTONE	const lpToneList,
    DWORD dwNumEntries)

Enables and disables the detection of inband tones on the call. Each time a specified tone is detected, a message is sent to the application.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

LINEERR_INVALCALLHANDLE	LINEERR_OPERATIONFAILED
LINEERR_INVALCALLSTATE	LINEERR_RESOURCEUNAVAIL
LINEERR_INVALTONE	LINEERR_UNINITIALIZED
LINEERR_NOMEM	LINEERR_INVALPOINTER
LINEERR_OPERATIONUNAVAIL
hCall

Specifies a handle to the call on whose voice channel tones are to be monitored.  Call state of hCall can be any state except idle.

lpToneList

Specifies a list of tones to be monitored, of type LINEMONITORTONE. Each tone in this list has an application-defined tag field that is used to identify individual tones in the list report a tone detection. Tone monitoring in progress is canceled or changed by calling this operation with either NULL for lpToneList or with another tone list.

dwNumEntries

Specifies the number of entries in lpToneList. This parameter is ignored if lpToneList is NULL.

This function is successful if tone monitoring has been correctly initiated, not when tone monitoring has terminated. Tone monitoring will remain in effect until it is explicitly disabled by calling lineMonitorTones with another tone list (or NULL), until the call transitions to idle, or when the application deallocates its call handle for the call.

Although this function can be invoked in any call state, tones can typically only be detected while the call is in the connected state. Tone detection typically requires computational resources. Depending on the service provider and other activities that compete for such resources, the number of tones that can be detected may vary over time. Also, an equivalent amount of resources may be consumed for monitoring a single triple frequency tone versus three single frequency tones. If resources are overcommitted, the LINEERR_RESOURCEUNAVAIL error is returned.

Note that lineMonitorTones is also used to detect silence. Silence is specified as a tone with all zero frequencies.

Monitoring of tones on a conference call applies only to the hConfCall, not to the individual participating calls

If the LINEERR_INVALPOINTER error value is returned, the specified lpToneList parameter is invalid or the value specified by the dwNumEntries parameter is too large.


 lineNegotiateAPIVersion

[New - Windows 95]

LONG lineNegotiateAPIVersion(HLINEAPP hLineApp, DWORD dwDeviceID,
    DWORD dwAPILowVersion, DWORD dwAPIHighVersion,
    LPDWORD lpdwAPIVersion, LPLINEEXTENSIONID lpExtensionID)

Allows an application to negotiate an API version to use.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

LINEERR_BADDEVICEID	LINEERR_NODRIVER
LINEERR_INCOMPATIBLEAPIVERSION	LINEERR_OPERATIONFAILED
LINEERR_INVALAPPHANDLE	LINEERR_RESOURCEUNAVAIL
LINEERR_INVALPOINTER	LINEERR_UNINITIALIZED
LINEERR_NOMEM	LINEERR_OPERATIONUNAVAIL
LINEERR_NODEVICE
hLineApp

Specifies the handle to the application's registration with TAPI.

dwDeviceID

Specifies the line device to be queried.

dwAPILowVersion

Specifies the least recent API version the application is compliant with. The high-order word is the major version number; the low-order word is the minor version number.

dwAPIHighVersion

Specifies the most recent API version the application is compliant with. The high-order word is the major version number; the low-order word is the minor version number.

lpdwAPIVersion

Specifies a pointer to a DWORD-sized location that contains the API version number that was negotiated. If negotiation is successful, this number will be in the range between dwAPILowVersion and dwAPIHighVersion.

lpExtensionID

Specifies a pointer to a structure of type LINEEXTENSIONID. If the service provider for the specified dwDeviceID supports provider-specific extensions, then, upon a successful negotiation, this structure is filled with the extension ID of these extensions. This structure contains all zeros if the line provides no extensions. An application can ignore the returned parameter if it does not use extensions.

Use lineInitialize to determine the number of line devices present in the system. The device ID specified by dwDeviceID varies from zero to one less than the number of line devices present.

The lineNegotiateAPIVersion function is used to negotiate the API version number to use. It also retrieves the extension ID supported by the line device, and it returns zeros if no extensions are supported. If the application wants to use the extensions defined by the returned extension ID, it must call lineNegotiateExtVersion to negotiate the extension version to use.

The API version number negotiated is that under which TAPI can operate. If version ranges do not overlap, the application and API or service provider versions are incompatible and an error is returned.


 lineNegotiateExtVersion

[New - Windows 95]

LONG lineNegotiateExtVersion(HLINEAPP hLineApp, DWORD dwDeviceID,
    DWORD dwAPIVersion, DWORD dwExtLowVersion, DWORD dwExtHighVersion,
    LPDWORD lpdwExtVersion)

Allows an application to negotiate an extension version to use with the specified line device. This operation need not be called if the application does not support extensions.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

LINEERR_BADDEVICEID	LINEERR_NOMEM
LINEERR_INCOMPATIBLEAPIVERSION	LINEERR_NODRIVER
LINEERR_INCOMPATIBLEEXTVERSION	LINEERR_OPERATIONFAILED
LINEERR_INVALAPPHANDLE	LINEERR_RESOURCEUNAVAIL
LINEERR_INVALPOINTER	LINEERR_UNINITIALIZED
LINEERR_NODEVICE	LINEERR_OPERATIONUNAVAIL
hLineApp

Specifies the handle to the application's registration with TAPI.

dwDeviceID

Specifies the line device to be queried.

dwAPIVersion

Specifies the API version number that was negotiated for the specified line device using lineNegotiateAPIVersion.

dwExtLowVersion

Specifies the least recent extension version of the extension ID returned by lineNegotiateAPIVersion that the application is compliant with. The high-order word is the major version number; the low-order word is the minor version number.

dwExtHighVersion

Specifies the most recent extension version of the extension ID returned by lineNegotiateAPIVersion that the application is compliant with. The high-order word is the major version number; the low-order word is the minor version number.

lpdwExtVersion

Specifies a pointer to a DWORD-sized location that contains the extension version number that was negotiated. If negotiation is successful, this number will be in the range between dwExtLowVersion and dwExtHighVersion.

Use lineInitialize to determine the number of line devices present in the system. The device ID specified by dwDeviceID varies from zero to one less than the number of line devices present.

lineNegotiateAPIVersion is used to negotiate the API version number to use. It also retrieves the extension ID supported by the line device, which is zeros if no extensions are provided. Version numbers should be incremented by one for each release. Leaving gaps in release version numbering may cause unexpected results.

If the application wants to use the extensions defined by the returned extension ID, it must call lineNegotiateExtVersion to negotiate the extension version to use.

The extension version number negotiated is that under which the application and service provider must both operate. If version ranges do not overlap, the application and service provider versions are incompatible and an error is returned.


 lineOpen

[New - Windows 95]

LONG lineOpen(HLINEAPP hLineApp, DWORD dwDeviceID, LPHLINE lphLine,
    DWORD dwAPIVersion, DWORD dwExtVersion, DWORD dwCallbackInstance,
    DWORD dwPrivileges, DWORD dwMediaModes,
    LPLINECALLPARAMS const lpCallParams)

Opens the line device specified by its device ID and returns a line handle for the corresponding opened line device. This line handle is used in subsequent operations on the line device.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

LINEERR_ALLOCATED	LINEERR_LINEMAPPERFAILED
LINEERR_BADDEVICEID	LINEERR_NODRIVER
LINEERR_INCOMPATIBLEAPIVERSION	LINEERR_NOMEM
LINEERR_INCOMPATIBLEEXTVERSION	LINEERR_OPERATIONFAILED
LINEERR_INVALAPPHANDLE	LINEERR_RESOURCEUNAVAIL
LINEERR_INVALMEDIAMODE	LINEERR_STRUCTURETOOSMALL
LINEERR_INVALPOINTER	LINEERR_UNINITIALIZED
LINEERR_INVALPRIVSELECT	LINEERR_REINIT
LINEERR_NODEVICE	LINEERR_OPERATIONUNAVAIL
hLineApp

Specifies a handle to the application's registration with TAPI.

dwDeviceID

Identifies the line device to be opened. It can either be a valid device ID or the value:

LINEMAPPER

This value is used to open a line device in the system that supports the properties specified in lpCallParams. The application can use lineGetID to determine the ID of the line device that was opened.

lphLine

Specifies a pointer to an HLINE handle, which is then loaded with the handle representing the opened line device. Use this handle to identify the device when invoking other functions on the open line device.

dwAPIVersion

Specifies the API version number under which the application and Telephony API have agreed to operate. This number is obtained with lineNegotiateAPIVersion.

dwExtVersion

Specifies the extension version number under which the application and the service provider agree to operate. This number is zero if the application does not use any extensions. This number is obtained with lineNegotiateExtVersion.

dwCallbackInstance

Specifies user-instance data passed back to the application's callback. This parameter is not interpreted by the Telephony API.

dwPrivileges

Specifies the privilege the application wants for the calls it is notified for. This parameter can have multiple flags set, and it uses the following LINECALLPRIVILEGE_ constants:

LINECALLPRIVILEGE_NONE

The application wants to make only outbound calls.

LINECALLPRIVILEGE_MONITOR

The application only wants to monitor inbound and outbound calls.

LINECALLPRIVILEGE_OWNER

The application wants to own inbound calls of the types specified in dwMediaModes.

LINECALLPRIVILEGE_MONITOR + LINECALLPRIVILEGE_OWNER

The application wants to own inbound calls of the types specified in dwMediaModes, but if it cannot be an owner of a call, it wants to be a monitor.

Other flag combinations return the LINEERR_INVALPRIVSELECT error.

dwMediaModes

Specifies the media mode(s) of interest to the application. The dwMediaModes parameter is used to register the application as a potential target for inbound call and call handoff for the specified media mode. This parameter is meaningful only if the bit LINECALLPRIVILEGE_OWNER in dwPrivileges is set (and ignored if it is not). This parameter uses the following LINEMEDIAMODE_ constants:

LINEMEDIAMODE_UNKNOWN

The application wants to handle calls of unknown media type (unclassified calls).

LINEMEDIAMODE_INTERACTIVEVOICE

The application wants to handle calls of the interactive voice media type. That is, it manages voice calls with the human user on this end of the call.

LINEMEDIAMODE_AUTOMATEDVOICE

Voice energy is present on the call. The voice is locally handled by an automated application.

LINEMEDIAMODE_DATAMODEM

The application wants to handle calls with the data-modem media mode.

LINEMEDIAMODE_G3FAX

The application wants to handle calls of the group 3 fax media type.

LINEMEDIAMODE_TDD

The application wants to handle calls with the TDD (Telephony Devices for the Deaf) media mode.

LINEMEDIAMODE_G4FAX

The application wants to handle calls of the group 4 fax media type.

LINEMEDIAMODE_DIGITALDATA

The application wants to handle calls of the digital-data media type.

LINEMEDIAMODE_TELETEX

The application wants to handle calls with the teletex media mode.

LINEMEDIAMODE_VIDEOTEX

The application wants to handle calls with the videotex media mode.

LINEMEDIAMODE_TELEX

The application wants to handle calls with the telex media mode.

LINEMEDIAMODE_MIXED

The application wants to handle calls with the ISDN mixed media mode.

LINEMEDIAMODE_ADSI

The application wants to handle calls with the ADSI (Analog Display Services Interface) media mode.

LINEMEDIAMODE_VOICEVIEW

The media mode of the call is VoiceView.

lpCallParams

Specifies a pointer to a structure of type LINECALLPARAMS. This pointer is only used if LINEMAPPER is used; otherwise lpCallParams is ignored. It describes the call parameter that the line device should be able to provide.

If LINEERR_ALLOCATED is returned, the line cannot be opened due to a "persistent" condition, such as that of a serial port being exclusively opened by another process. If LINEERR_RESOURCEUNAVAIL is returned, the line cannot be opened due to a dynamic resource overcommitment such as in DSP processor cycles or memory. This overcommitment may be transitory, caused by monitoring of media mode or tones, and changes in these activities by other applications may make it possible to reopen the line within a short time period. If LINEERR_REINIT is returned and TAPI reinitialization has been requested, for example as a result of adding or removing a Telephony service provider, then lineOpen requests are rejected with this error until the last application shuts down its usage of the API (using lineShutdown), at which time the new configuration becomes effective and applications are once again permitted to call lineInitialize.

Opening a line always entitles the application to make calls on any address available on the line. The ability of the application to deal with inbound calls or to be the target of call handoffs on the line is determined by the dwMediaModes parameter. The lineOpen function registers the application as having an interest in monitoring calls or receiving ownership of calls that are of the specified media modes. If the application just wants to monitor calls, then it can specify LINECALLPRIVILEGE_MONITOR. If the application just wants to make outbound calls, it can specify LINECALLPRIVILEGE_NONE. If the application is willing to control unclassified calls (calls of unknown media mode), it can specify LINECALLPRIVILEGE_OWNER and LINEMEDIAMODE_UNKNOWN. Otherwise, the application should specify the media mode it is interested in handling.

The media modes specified with lineOpen add to the default value for the provider's media mode monitoring for initial inbound call type determination. The lineMonitorMedia function modifies the mask that controls LINE_MONITORMEDIA messages. If a line device is opened with owner privilege and an extension media mode is not registered in TELEPHON.INI, then the error LINEERR_INVALMEDIAMODE is returned.

An application that has successfully opened a line device can always initiate calls using lineMakeCall, lineUnpark, linePickup, lineSetupConference (with a NULL hCall), as well as use lineForward (assuming that doing so is allowed by the device capabilities, line state, and so on).

Note that a single application may specify multiple flags simultaneously to handle multiple media modes. Conflicts may arise if multiple applications open the same line device for the same media mode. These conflicts are resolved by a priority scheme in which the user assigns relative priorities to the applications. Only the highest priority application for a given media mode will ever receive ownership (unsolicited) of a call of that media mode. Ownership can be received when an inbound call first arrives or when a call is handed off.

Note that any application (including any lower priority application) can always acquire ownership with lineGetNewCalls or lineGetConfRelatedCalls. If an application opens a line for monitoring at a time that calls exist on the line, LINE_CALLSTATE messages for those existing calls are not automatically generated to the new monitoring application. The application can query the number of current calls on the line to determine how many calls exist, and, if it wants, it can call lineGetNewCalls to obtain handles to these calls.

An application that handles automated voice should also select the interactive voice open mode and be assigned the lowest priority for interactive voice. The reason for this is that service providers will report all voice media modes as interactive voice. If media mode determination is not performed by the application for the UNKNOWN media type, and no interactive voice application has opened the line device, voice calls would be unable to reach the automated voice application, but be dropped instead.

The same application, or different instantiations of the same application, may open the same line multiple times with the same or different parameters.

When an application opens a line device it must specify the negotiated API version and, if it wants to use the line's extensions, it should specify the line's device-specific extension version. These version numbers should have been obtained with lineNegotiateAPIVersion and lineNegotiateExtVersion. Version numbering allows the mixing and matching of different application versions with different API versions and service provider versions.

LINEMAPPER allows an application to select a line indirectly—by means of the services it wants from it. When opening a line device using LINEMAPPER, the following is true: All fields from beginning of the LINECALLPARAMS data structure through dwAddressMode are relevant. If dwAddressMode is LINEADDRESSMODE_ADDRESSID it means that any address on the line is acceptable, otherwise if dwAddressMode is LINEADDRESSMODE_DIALABLEADDR, indicating that a specific originating address (phone number) is searched for, or if it is a provider-specific extension, then dwOrigAddressSize/Offset and the portion of the variable part they refer to are also relevant. If dwAddressMode is a provider-specific extension additional information may be contained in the dwDeviceSpecific variably sized field.


 linePark

[New - Windows 95]

LONG linePark(HCALL hCall, DWORD dwParkMode, LPCSTR lpszDirAddress,
    LPVARSTRING lpNonDirAddress)

Parks the specified call according to the specified park mode.

•	Returns a positive request ID if the function will be completed asynchronously, or a negative error number if an error has occurred. The dwParam2 parameter of the corresponding LINE_REPLY callback message is zero if the function is successful or it is a negative error number if an error has occurred. Possible return values are:

LINEERR_INVALADDRESS	LINEERR_NOTOWNER
LINEERR_INVALCALLHANDLE	LINEERR_OPERATIONUNAVAIL
LINEERR_INVALCALLSTATE	LINEERR_OPERATIONFAILED
LINEERR_INVALPARKMODE	LINEERR_RESOURCEUNAVAIL
LINEERR_INVALPOINTER	LINEERR_STRUCTURETOOSMALL
LINEERR_NOMEM	LINEERR_UNINITIALIZED
hCall

Specifies a handle to the call to be parked. The application must be an owner of the call. Call state of hCall must be connected.

dwParkMode

Specifies the park mode with which the call is to be parked. This parameter can have only a single flag set, and it uses the following LINEPARKMODE_ constants:

LINEPARKMODE_DIRECTED

The application specifies at which address the call is to be parked in lpszDirAddress.

LINEPARKMODE_NONDIRECTED

This operation reports to the application where the call has been parked in lpNonDirAddress.

lpszDirAddress

Specifies a pointer to a NULL-terminated string that indicates the address where the call is to be parked when using directed park. The address is in dialable number format. This parameter is ignored for nondirected park.

lpNonDirAddress

Specifies a pointer to a structure of type VARSTRING. For nondirected park, the address where the call is parked is returned in this structure. This parameter is ignored for directed park. Within the VARSTRING structure, dwStringFormat must be set to STRINGFORMAT_ASCII (an ASCII string buffer containing a NULL-terminated string), and the terminating NULL must be accounted for in the dwStringSize. Prior to calling linePark, the application should set the dwTotalSize field of this structure to indicate the amount of memory available to TAPI.DLL for returning information.

With directed park, the application determines the address at which it wants to park the call. With nondirected park, the switch determines the address and provides this to the application. In either case, a parked call can be unparked by specifying this address.

The parked call typically enters the idle state after it has been successfully parked and the application should then deallocate its handle to the call. If the application performs a lineUnpark on the parked call, a new call handle will be created for the unparked call even if the application has not deallocated its old call handle.

Some switches may remind the user after a call has been parked for some long amount of time. The application will see an offering call with a call reason set to reminder.

On a nondirected park, if the dwTotalSize member in the VARSTRING structure does not specify a sufficient amount of memory to receive the park address, the corresponding reply message returns a LINEERR_STRUCTURETOOSMALL error value. In such cases, there is no way to retrieve the complete park address.


 linePickup

[New - Windows 95]

LONG linePickup(HLINE hLine, DWORD dwAddressID, LPHCALL lphCall,
    LPCSTR lpszDestAddress, LPCSTR lpszGroupID)

Picks up a call alerting at the specified destination address and returns a call handle for the picked-up call. If invoked with NULL for the lpszDestAddress parameter, a group pickup is performed. If required by the device, lpszGroupID specifies the group ID to which the alerting station belongs.

•	Returns a positive request ID if the function will be completed asynchronously, or a negative error number if an error has occurred. The dwParam2 parameter of the corresponding LINE_REPLY callback message is zero if the function is successful or it is a negative error number if an error has occurred. Possible return values are:

LINEERR_INVALADDRESS	LINEERR_NOMEM
LINEERR_INVALADDRESSID	LINEERR_OPERATIONUNAVAIL
LINEERR_INVALGROUPID	LINEERR_OPERATIONFAILED
LINEERR_INVALLINEHANDLE	LINEERR_RESOURCEUNAVAIL
LINEERR_INVALPOINTER	LINEERR_UNINITIALIZED
hLine

Specifies a handle to the open line device on which a call is to be picked up.

dwAddressID

Specifies the address on hLine at which the pickup is to be originated.

lphCall

Specifies a pointer to a memory location where the handle to the picked up call will be returned. The application will be the initial sole owner of the call.

lpszDestAddress

Specifies a pointer to a NULL-terminated character buffer that contains the address whose call is to be picked up. The address is in standard dialable address format.

lpszGroupID

Specifies a pointer to a NULL-terminated character buffer containing the group ID to which the alerting station belongs. This parameter is required on some switches to pick up calls outside of the current pickup group.

Note that lpszGroupID can be specified by itself with a NULL pointer for lpszDestAddress. Alternatively, lpszGroupID can be specified in addition to lpszDestAddress, if required by the device.

When a call has been picked up successfully, the application is notified by the LINE_CALLSTATE message about call state changes. The LINECALLINFO structure supplies information about the call that was picked up. It will list the reason for the call as pickup. This structure is available using lineGetCallInfo.

If LINEADDRCAPFLAGS_PICKUPCALLWAIT is TRUE, linePickup can be used to pick up a call for which the user has audibly detected the call-waiting signal but for which the provider is unable to perform the detection. This gives the user a mechanism to "answer" a waiting call even though the service provider was unable to detect the call-waiting signal. Both lpszDestAddress and lpszGroupID pointer parameters must be NULL to pick up a call-waiting call. The linePickup function will create a new call handle for the waiting call and pass that handle to the user. dwAddressID will most often be zero (particularly in single-line residential cases).

Once linePickup has been used to pick up the second call, lineSwapHold can be used to toggle between them. lineDrop can be used to drop one (and toggle to the other), and so forth. If the user wants to drop the current call and pick up the second call, they should call lineDrop when they get the call-waiting beep, wait for the second call to ring, and then call lineAnswer on the new call handle. The LINEADDRFEATURE_PICKUP flag in the dwAddressFeatures field in LINEADDRESSSTATUS indicates when pickup is actually possible.


 linePrepareAddToConference

[New - Windows 95]

LONG linePrepareAddToConference(HCALL hConfCall, LPHCALL lphConsultCall,
    LPLINECALLPARAMS const lpCallParams)

Prepares an existing conference call for the addition of another party.

•	Returns a positive request ID if the function will be completed asynchronously, or a negative error number if an error has occurred. The dwParam2 parameter of the corresponding LINE_REPLY callback message is zero if the function is successful or it is a negative error number if an error has occurred. Possible return values are:

LINEERR_BEARERMODEUNAVAIL	LINEERR_INVALPOINTER
LINEERR_CALLUNAVAIL	LINEERR_INVALRATE
LINEERR_CONFERENCEFULL	LINEERR_NOMEM
LINEERR_INUSE	LINEERR_NOTOWNER
LINEERR_INVALADDRESSMODE	LINEERR_OPERATIONUNAVAIL
LINEERR_INVALBEARERMODE	LINEERR_OPERATIONFAILED
LINEERR_INVALCALLPARAMS	LINEERR_RATEUNAVAIL
LINEERR_INVALCALLSTATE	LINEERR_RESOURCEUNAVAIL
LINEERR_INVALCONFCALLHANDLE	LINEERR_STRUCTURETOOSMALL
LINEERR_INVALLINESTATE	LINEERR_USERUSERINFOTOOBIG
LINEERR_INVALMEDIAMODE	LINEERR_UNINITIALIZED
hConfCall

Specifies a handle to a conference call. The application must be an owner of this call. Call state of hConfCall must be connected.

lphConsultCall

Specifies a pointer to an HCALL handle. This location is then loaded with a handle identifying the consultation call to be added. Initially, the application will be the sole owner of this call.

lpCallParams

Specifies a pointer to call parameters to be used when establishing the consultation call. This parameter may be set to NULL if no special call setup parameters are desired.

If LINEERR_INVALLINESTATE is returned, the line is currently not in a state in which this operation can be performed. A list of currently valid operations can be found in the dwLineFeatures field (of the type LINEFEATURE_) in the LINEDEVSTATUS structure. (Calling lineGetLineDevStatus updates the information in LINEDEVSTATUS.)

A conference call handle can be obtained with lineSetupConference or with lineCompleteTransfer that is resolved as a three-way conference call. The function linePrepareAddToConference typically places the existing conference call in the onHoldPendingConference state and creates a consultation call that can be added later to the existing conference call with lineAddToConference.

The consultation call can be canceled using lineDrop. It may also be possible for an application to swap between the consultation call and the held conference call with lineSwapHold.


 lineRedirect

[New - Windows 95]

LONG lineRedirect(HCALL hCall, LPCSTR lpszDestAddress,
    DWORD dwCountryCode)

Redirects the specified offering call to the specified destination address.

•	Returns a positive request ID if the function will be completed asynchronously, or a negative error number if an error has occurred. The dwParam2 parameter of the corresponding LINE_REPLY callback message is zero if the function is successful or it is a negative error number if an error has occurred. Possible return values are:

LINEERR_INVALADDRESS	LINEERR_NOTOWNER
LINEERR_INVALCALLHANDLE	LINEERR_OPERATIONUNAVAIL
LINEERR_INVALCALLSTATE	LINEERR_OPERATIONFAILED
LINEERR_INVALCOUNTRYCODE	LINEERR_RESOURCEUNAVAIL
LINEERR_INVALPOINTER	LINEERR_UNINITIALIZED
LINEERR_NOMEM
hCall

Specifies a handle to the call to be redirected. The application must be an owner of the call. Call state of hCall must be offering.

lpszDestAddress

Specifies a pointer to the destination address. This follows the standard dialable number format.

dwCountryCode

Specifies the country code of the party the call is redirected to. If a value of zero is specified, a default is used by the implementation.

Call redirection allows an application to deflect an offering call to another address without first answering the call. Call redirect differs from call forwarding in that call forwarding is performed by the switch without the involvement of the application; redirection can be done on a call-by-call basis by the application, for example, driven by caller ID information. It differs from call transfer in that transferring a call requires the call first be answered.

After a call has been successfully redirected, the call typically transitions to idle.

Besides redirecting an incoming call, an application may have the option to accept the call using lineAccept, reject the call using lineDrop, or answer the call using lineAnswer. The availability of these operations is dependent on device capabilities.


 lineRegisterRequestRecipient

[New - Windows 95]

LONG lineRegisterRequestRecipient(HLINEAPP hLineApp,
    DWORD dwRegistrationInstance, DWORD dwRequestMode, DWORD bEnable)

Registers the invoking application as a recipient of requests for the specified request mode.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

LINEERR_INVALAPPHANDLE	LINEERR_OPERATIONFAILED
LINEERR_INVALREQUESTMODE	LINEERR_RESOURCEUNAVAIL
LINEERR_NOMEM	LINEERR_UNINITIALIZED
hLineApp

Specifies the application's usage handle for the line portion of TAPI.

dwRegistrationInstance

Specifies an application-specific DWORD that is passed back as a parameter of the LINE_REQUEST message. This message notifies the application that a request is pending. This parameter is ignored if bEnable is set to zero. This parameter is examined by TAPI only for registration, not for deregistration. The dwRegistrationInstance value used while deregistering need not match the dwRegistrationInstance used while registering for a request mode.

dwRequestMode

Specifies the type(s) of request for which the application registers. One or both bits may be set. This parameter uses the following LINEREQUESTMODE_ constants:

LINEREQUESTMODE_MAKECALL

A tapiRequestMakeCall request.

bEnable

If TRUE, the application registers; if FALSE, the application deregisters for the specified request modes.

A telephony-enabled application can request that a call be placed on its behalf by invoking tapiRequestMakeCall. Additionally, other applications can request that information be logged with a given call. tapiRequestMakeCall requests are queued by TAPI.DLL, and the highest priority application that has registered to handle the request is sent a LINE_REQUEST message with an indication of the mode of the request that is pending. This application is typically the user's call-control application.

Next, the call-control application that receives this message invokes lineGetRequest, specifying the request mode and a buffer that is large enough to hold the request.The call-control application then interprets and executes the request.

The recipient application is also automatically deregistered for all requests when it does a lineShutdown.


 lineReleaseUserUserInfo

[New - Windows 95]

LONG lineReleaseUserUserInfo (HCALL hCall)

Informs the service provider that the application has processed the user-user information contained in the LINECALLINFO structure, and that subsequently received user-user information can now be written into that structure. The service provider will send a LINE_CALLINFO message indicating LINECALLINFOSTATE_USERUSERINFO when new information is available.

•	Returns a positive request ID if the function will be completed asynchronously or a negative error number if an error has occurred. The dwParam2 parameter of the corresponding LINE_REPLY callback message is zero if the function is successful or it is a negative error number if an error has occurred. Possible return values are:

LINEERR_INVALCALLHANDLE	LINEERR_OPERATIONFAILED
LINEERR_NOMEM	LINEERR_RESOURCEUNAVAIL
LINEERR_NOTOWNER	LINEERR_UNINITIALIZED
LINEERR_OPERATIONUNAVAIL
hCall

Specifies a handle to the call. The application must be an owner of the call. Call state of hCall can be any state.

The lineReleaseUserUserInfo function allows the application to control the flow of incoming user-user information on an ISDN connection. When a new, complete user-user information message is received, the service provider informs the application using a LINE_CALLINFO message (specifying LINECALLINFOSTATE_USERUSERINFO). Any number of applications may examine the information (using lineGetCallInfo), but the application owning the call controls when the information is released so that subsequent information can be reported. The service provider will not overwrite previous user-user information in LINECALLINFO with newer information until after lineReleaseUserUserInfo has been called. It is the responsibility of the service provider to buffer subsequently received user-user information until the previous information is released by the application owning the call.

Although this is a new function which older applications would not be expected to call, for backward compatibility, they should not be prevented from doing so; the function will work the same way for all applications.


 lineRemoveFromConference

[New - Windows 95]

LONG lineRemoveFromConference(HCALL hCall)

Removes the specified call from the conference call to which it currently belongs. The remaining calls in the conference call are unaffected.

•	Returns a positive request ID if the function will be completed asynchronously, or a negative error number if an error has occurred. The dwParam2 parameter of the corresponding LINE_REPLY callback message is zero if the function is successful or it is a negative error number if an error has occurred. Possible return values are:

LINEERR_INVALCALLHANDLE	LINEERR_OPERATIONUNAVAIL
LINEERR_INVALCALLSTATE	LINEERR_OPERATIONFAILED
LINEERR_NOMEM	LINEERR_RESOURCEUNAVAIL
LINEERR_NOTOWNER	LINEERR_UNINITIALIZED
hCall

Specifies a handle to the call to be removed from the conference. The application must be an owner of this call. Call state of hCall must be conferenced.

This operation removes a party that currently belongs to a conference call. After the call has been successfully removed, it may be possible to further manipulate it using its handle. The availability of this operation and its result are likely to be limited in many implementations. For example, in many implementations, only the most recently added party may be removed from a conference, and the removed call may be automatically dropped (becomes idle). Consult the line's device capabilities to determine the available effects of removing a call from a conference.

If the removal of a participant from a conference is supported, the participant call, after it is removed from the conference, will enter the call-state listed in the dwRemoveFromConfState field in LINEADDRESSCAPS.


 lineRemoveProvider

[New - Windows 95]

LONG lineRemoveProvider (DWORD dwPermanentProviderID, HWND hwndOwner)

Removes an existing Telephony Service Provider from the Telephony system.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

LINEERR_INIFILECORRUPT	LINEERR_NOMEM
LINEERR_INVALPARAM	LINEERR_OPERATIONFAILED
dwPermanentProviderID

Specifies the permanent provider ID of the service provider to be removed.

hwndOwner

Specifies a handle to a window to which the any dialogs which need to be displayed as part of the removal process (e.g., a confirmation dialog by the service provider's TSPI_providerRemove function) would be attached.

If the call to TSPI_providerRemove is successful, and the telephony system is active at the time, TAPI calls TSPI_lineShutdown and/or TSPI_phoneShutdown on the service provider (depending on which device types are active). Any line or phone handles still held by applications on associated devices are forcibly closed with LINE_CLOSE or PHONE_CLOSE messages (it is preferable for service providers themselves to issue these messages as part of TSPI_providerRemove, after verification with the user). The devices previously under the control of that provider are then marked as "unavailable", so that any future attempts by applications to reference them by device ID result in LINEERR_NODRIVER.

Although this is a new function which older applications would not be expected to call, for backward compatibility, they should not be prevented from doing so; the function will work the same way for all applications.


 lineSecureCall

[New - Windows 95]

LONG lineSecureCall(HCALL hCall)

Secures the call from any interruptions or interference that may affect the call's media stream.

•	Returns a positive request ID if the function will be completed asynchronously, or a negative error number if an error has occurred. The dwParam2 parameter of the corresponding LINE_REPLY callback message is zero if the function is successful or it is a negative error number if an error has occurred. Possible return values are:

LINEERR_INVALCALLHANDLE	LINEERR_OPERATIONUNAVAIL
LINEERR_INVALCALLSTATE	LINEERR_OPERATIONFAILED
LINEERR_NOMEM	LINEERR_RESOURCEUNAVAIL
LINEERR_NOTOWNER	LINEERR_UNINITIALIZED
hCall

Specifies a handle to the call to be secured. The application must be an owner of the call. Call state of hCall can be any state.

A call can be secured to avoid interference. For example, in an analog environment, call-waiting tones may destroy a fax or modem session on the original call. The function lineSecureCall allows an existing call to be secured. The lineMakeCall function provides the option to secure the call from the time of call setup. The securing of a call remains in effect for the duration of the call.


 lineSendUserUserInfo

[New - Windows 95]

LONG lineSendUserUserInfo(HCALL hCall, LPCSTR lpsUserUserInfo,
    DWORD dwSize)

Send user-to-user information to the remote party on the specified call.

•	Returns a positive request ID if the function will be completed asynchronously, or a negative error number if an error has occurred. The dwParam2 parameter of the corresponding LINE_REPLY callback message is zero if the function is successful or it is a negative error number if an error has occurred. Possible return values are:

LINEERR_INVALCALLHANDLE	LINEERR_OPERATIONUNAVAIL
LINEERR_INVALCALLSTATE	LINEERR_OPERATIONFAILED
LINEERR_INVALPOINTER	LINEERR_RESOURCEUNAVAIL
LINEERR_NOMEM	LINEERR_USERUSERINFOTOOBIG
LINEERR_NOTOWNER	LINEERR_UNINITIALIZED
hCall

Specifies a handle to the call on which to send user-to-user information. The application must be an owner of the call. Call state of hCall must be connected, offering, accepted, or ringback.

lpsUserUserInfo

Specifies a pointer to a string containing user-to-user information to be sent to the remote party. User-to-user information is only sent if supported by the underlying network (see LINEDEVCAPS). The protocol discriminator field for the user-user information, if required, should appear as the first byte of the buffer pointed to by lpsUserUserInfo, and must be accounted for in dwSize.

dwSize

Specifies the size in bytes of the user-to-user information in lpsUserUserInfo.

This function can be used to send user-to-user information at any time during a connected call. If the size of the specified information to be sent is larger than what may fit into a single network message (as in ISDN), the service provider is responsible for dividing the information into a sequence of chained network messages (using "more data").

User-to-user information can also be sent as part of call accept, call reject, call redirect, and when making calls. User-to-user information can also be received. The received information is available through the call's call-information record. Whenever user-to-user information arrives after call offering or prior to call disconnect, a LINE_CALLINFO message with a UserUserInfo parameter will notify the application that user-to-user information in the call-information record has changed. If multiple network messages are chained, the information is assembled by the service provider and a single message is sent to the application.


 lineSetAppPriority

[New - Windows 95]

LONG lineSetAppPriority(LPCSTR lpszAppFilename, DWORD dwMediaMode,
    LPLINEEXTENSIONID const lpExtensionID, DWORD dwRequestMode,
    LPCSTR lpszExtensionName, DWORD dwPriority)

Allows an application to set its priority in the handoff priority list for a particular media mode or Assisted Telephony request mode or to remove itself from the priority list.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

LINEERR_INIFILECORRUPT	LINEERR_INVALREQUESTMODE
LINEERR_INVALAPPNAME	LINEERR_NOMEM
LINEERR_INVALMEDIAMODE	LINEERR_OPERATIONFAILED
LINEERR_INVALPARAM	LINEERR_RESOURCEUNAVAIL
LINEERR_INVALPOINTER
lpszAppFilename

Specifies a pointer to a string containing the application executable module filename (without directory information). The parameter must specify a filename in the 8.3 format. Long filenames cannot be used.

dwMediaMode

Specifies the media mode for which the priority of the application is to be set. The value may be one of the LINEMEDIAMODE_ constants, or an extended media mode value defined by a service provider; only a single bit may be on. The value 0 should be used to set the application priority for Assisted Telephony requests.

lpExtensionID

Specifies a pointer to structure of type LINEEXTENSIONID. This parameter is referenced only if dwMediaModes specifies a value in the range 0x01000000 through 0x80000000 (extended media modes). This parameter is ignored if dwMediaMode is 0 or specifies a LINEMEDIAMODE_ value.

dwRequestMode

If the dwMediaMode parameter is 0, this parameter specifies the Assisted Telephony request mode for which priority is to be set. It must be either LINEREQUESTMODE_MAKECALL or LINEREQUESTMODE_MEDIACALL. This parameter is ignored if dwMediaMode is non-zero.

lpszExtensionName

If dwMediaMode specifies an extended media mode, this parameter may point to a null-terminated ASCII string specifying a friendly name for the extended media mode. If the pointer is NULL, any existing name is preserved, or, if a new entry is being created in the priority list, the friendly name will be set to the empty string. This parameter is ignored if dwMediaMode is 0 or specifies a LINEMEDIAMODE_ value.

dwPriority

Specifies the new priority for the application. If the value 0 is passed, the application is removed from the priority list for the specified media or request mode (if it was already not present, no error is generated). If the value 1 is passed, the application is inserted as the highest-priority application for the media or request mode (and removed from a lower-priority position, if it was already in the list). Any other value generates an error.

If LINEERR_INVALMEDIAMODE is returned, the value specified in dwMediaMode is not 0, not a valid extended media mode, and not a LINEMEDIAMODE_ constant, or more than one bit is on in the parameter value.

This function updates to stored priority list. If the telephony system is initialized, it also sets the current, active priorities for applications then running; the new priority will be used on the next incoming call or lineHandoff based on media mode.

Although this is a new function which older applications would not be expected to call, for backward compatibility, they should not be prevented from doing so; the function will work the same way for all applications.


 lineSetAppSpecific

[New - Windows 95]

LONG lineSetAppSpecific(HCALL hCall, DWORD dwAppSpecific)

This operation enables an application to set the application-specific field of the specified call's call-information record.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

LINEERR_INVALCALLHANDLE	LINEERR_RESOURCEUNAVAIL
LINEERR_NOMEM	LINEERR_UNINITIALIZED
LINEERR_NOTOWNER	LINEERR_OPERATIONUNAVAIL
LINEERR_OPERATIONFAILED
hCall

Specifies a handle to the call whose application-specific field needs to be set. The application must be an owner of the call. Call state of hCall can be any state.

dwAppSpecific

Specifies the new content of the dwAppSpecific field for the call's LINECALLINFO structure. This value is not interpreted by the Telephony API.

The application-specific field in the LINECALLINFO data structure that exists for each call is not interpreted by the Telephony API or any of its service providers. Its usage is entirely defined by the applications. The field can be read from the LINECALLINFO record returned by lineGetCallInfo. However, lineSetAppSpecific must be used to set the field so that changes become visible to other applications. When this field is changed, all other applications with call handles are sent a LINE_CALLINFO message with an indication that the dwAppSpecific field has changed.


 lineSetCallParams

[New - Windows 95]

LONG lineSetCallParams(HCALL hCall, DWORD dwBearerMode, DWORD dwMinRate,
    DWORD dwMaxRate, LPLINEDIALPARAMS const lpDialParams)

Allows an application to change bearer mode and/or the rate parameters of an existing call.

•	Returns a positive request ID if the function will be completed asynchronously, or a negative error number if an error has occurred. The dwParam2 parameter of the corresponding LINE_REPLY callback message is zero if the function is successful or it is a negative error number if an error has occurred. Possible return values are:

LINEERR_BEARERMODEUNAVAIL	LINEERR_NOTOWNER
LINEERR_INVALBEARERMODE	LINEERR_OPERATIONUNAVAIL
LINEERR_INVALCALLHANDLE	LINEERR_OPERATIONFAILED
LINEERR_INVALCALLSTATE	LINEERR_RATEUNAVAIL
LINEERR_INVALPOINTER	LINEERR_RESOURCEUNAVAIL
LINEERR_INVALRATE	LINEERR_UNINITIALIZED
LINEERR_NOMEM
hCall

Specifies a handle to the call whose parameters are to be changed. The application must be an owner of the call. Call state of hCall can be any state except idle and disconnected.

dwBearerMode

Specifies the new bearer mode for the call. This parameter can have only a single bit set, and it uses the following LINEBEARERMODE_ constants:

LINEBEARERMODE_VOICE

This is a regular 3.1kHz analog voice-grade bearer service. Bit integrity is not assured. Voice can support fax and modem media modes.

LINEBEARERMODE_SPEECH

This corresponds to G.711 speech transmission on the call. The network may use processing techniques such as analog transmission, echo cancellation, and compression/decompression. Bit integrity is not assured. Speech is not intended to support fax and modem media modes.

LINEBEARERMODE_MULTIUSE

The multi-use mode defined by ISDN.

LINEBEARERMODE_DATA

The unrestricted data transfer on the call. The data rate is specified separately.

LINEBEARERMODE_ALTSPEECHDATA

The alternate transfer of speech or unrestricted data on the same call (ISDN).

LINEBEARERMODE_NONCALLSIGNALING

This corresponds to a non-call-associated signaling connection from the application to the service provider or switch (treated as a media stream by the Telephony API).

dwMinRate

Specifies a lower bound for the call's new data rate. The application is willing to accept a new rate as low as this one.

dwMaxRate

Specifies an upper bound for the call's new data rate. This is the maximum data rate the application can accept. If an exact data rate is required, dwMinRate and dwMaxRate should be equal.

lpDialParams

Specifies a pointer to the new dial parameters for the call, of type LINEDIALPARAMS. This parameter can be left NULL if the call's current dialing parameters are to be used.

This operation is used to change the parameters of an existing call. Examples of its usage include changing the bearer mode and/or the data rate of an existing call.


 lineSetCallPrivilege

[New - Windows 95]

LONG lineSetCallPrivilege(HCALL hCall, DWORD dwCallPrivilege)

This operation sets the application's privilege to the specified privilege.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

LINEERR_INVALCALLHANDLE	LINEERR_OPERATIONFAILED
LINEERR_INVALCALLSTATE	LINEERR_RESOURCEUNAVAIL
LINEERR_INVALCALLPRIVILEGE	LINEERR_UNINITIALIZED
LINEERR_NOMEM
hCall

Specifies a handle to the call whose privilege is to be set. Call state of hCall can be any state.

dwCallPrivilege

Specifies the privilege the application wants to have for the specified call. Only a single flag can be set. This parameter uses the following LINECALLPRIVILEGE_ constants:

LINECALLPRIVILEGE_MONITOR

The application requests monitor privilege to the call. These privileges allow the application to monitor state changes and to query information and status about the call.

LINECALLPRIVILEGE_OWNER

The application requests owner privilege to the call. These privileges allow the application to manipulate the call in ways that affect the state of the call.

If the application is the sole owner of a non-idle call and wants to change its privilege to monitor, a LINEERR_INVALCALLSTATE error is returned. If the application wants to, it can first drop the call using lineDrop to make the call transition to the idle state and then change its privilege.


 lineSetCurrentLocation

[New - Windows 95]

LONG lineSetCurrentLocation(HLINEAPP hLineApp, DWORD dwLocation)

This operation sets the location used as the context for address translation.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

LINEERR_INIFILECORRUPT	LINEERR_NOMEM
LINEERR_INVALAPPHANDLE	LINEERR_OPERATIONFAILED
LINEERR_INVALLOCATION	LINEERR_RESOURCEUNAVAIL
LINEERR_NODRIVER	LINEERR_UNINITIALIZED
hLineApp

Specifies the application handle returned by lineInitialize.

dwLocation

Specifies a new value for the CurrentLocation entry in the [Locations] section of TELEPHON.INI. It must contain a valid permanent ID of a Location entry in the [Locations] section, as obtained from lineGetTranslateCaps. If it is valid, the CurrentLocation entry is updated.

If an application has not yet called the lineInitialize function, it can set the hLineApp parameter to NULL and the dwDevice parameter to 0 when calling the lineSetCurrentLocation function.


 lineSetDevConfig

[New - Windows 95]

LONG lineSetDevConfig (DWORD dwDeviceID, LPVOID const lpDeviceConfig,
    DWORD dwSize, LPCSTR lpszDeviceClass)

Allows the application to restore the configuration of a media stream device on a line device to a setup previously obtained using lineGetDevConfig. For example, the contents of this structure could specify data rate, character format, modulation schemes, and error control protocol settings for a "datamodem" media device associated with the line.

•	Returns zero if the function is successful or a negative error number if an error has occurred. Possible return values are:

LINEERR_BADDEVICEID	LINEERR_NODRIVER
LINEERR_INVALDEVICECLASS	LINEERR_OPERATIONUNAVAIL
LINEERR_INVALPOINTER	LINEERR_OPERATIONFAILED
LINEERR_INVALPARAM	LINEERR_RESOURCEUNAVAIL
LINEERR_INVALLINESTATE	LINEERR_UNINITIALIZED
LINEERR_NOMEM	LINEERR_NODEVICE
dwDeviceID

Specifies the line device to be configured.

lpDeviceConfig

Specifies a pointer to the opaque configuration data structure that was returned by lineGetDevConfig in the variable portion of the VARSTRING structure.

dwSize

Specifies the number of bytes in the structure pointed to by lpDeviceConfig. This value will have been returned in the dwStringSize field in the VARSTRING structure returned by lineGetDevConfig.

lpszDeviceClass

Specifies a pointer to a NULL-terminated ASCII string that specifies the device class of the device whose configuration is to be set. Valid device class strings are the same as those specified for the lineGetID function.

Call states are device specific.

Typically, an application will call lineGetID to identify the media stream device associated with a line, and then call lineConfigDialog to allow the user to set up the device configuration. It could then call lineGetDevConfig and save the configuration information in a phone book or other database associated with a particular call destination. When the user later wants to call the same destination again, this function lineSetDevConfig can be used to restore the configuration settings selected by the user. lineSetDevConfig, lineConfigDialog, and lineGetDevConfig can be used, in that order, to allow the user to view and update the settings.

The exact format of the data contained within the structure is specific to the line and media stream API (device class), is undocumented, and is undefined. The application must treat it as "opaque" and not manipulate the contents directly. Generally, the structure can be sent using this function only to the same device from which it was obtained. Certain Telephony service providers may, however, permit structures to be interchanged between identical devices (that is, multiple ports on the same multi-port modem card). Such interchangability is not guaranteed in any way, even for devices of the same device class.

Note that some service providers may permit the configuration to be set while a call is active, and others may not.


 lineSetMediaControl

[New - Windows 95]

LONG lineSetMediaControl(HLINE hLine, DWORD dwAddressID, HCALL hCall,
    DWORD dwSelect, LPLINEMEDIACONTROLDIGIT const lpDigitList,
    DWORD dwDigitNumEntries, LPLINEMEDIACONTROLMEDIA	 const lpMediaList,
    DWORD dwMediaNumEntries, LPLINEMEDIACONTROLTONE const lpToneList,
    DWORD dwToneNumEntries,
    LPLINEMEDIACONTROLCALLSTATE const lpCallStateList,
    DWORD dwCallStateNumEntries)

Enables and disables control actions on the media stream associated with the specified line, address, or call. Media control actions can be triggered by the detection of specified digits, media modes, custom tones, and call states.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

LINEERR_INVALADDRESSID	LINEERR_NOMEM
LINEERR_INVALCALLHANDLE	LINEERR_NOTOWNER
LINEERR_INVALCALLSELECT	LINEERR_OPERATIONUNAVAIL
LINEERR_INVALCALLSTATELIST	LINEERR_OPERATIONFAILED
LINEERR_INVALDIGITLIST	LINEERR_RESOURCEUNAVAIL
LINEERR_INVALLINEHANDLE	LINEERR_UNINITIALIZED
LINEERR_INVALMEDIALIST	LINEERR_INVALPOINTER
LINEERR_INVALTONELIST
hLine

Specifies a handle to an open line device.

dwAddressID

Specifies an address on the given open line device.

hCall

Specifies a handle to a call. The application must be an owner of the call.  Call state of hCall can be any state.

dwSelect

Specifies whether the media control requested is associated with a single call, is the default for all calls on an address, or is the default for all calls on a line. This parameter can only have a single flag set, and it uses the following LINECALLSELECT_ constants:

LINECALLSELECT_LINE

Selects the specified line device. The hLine parameter must be a valid line handle; hCall and dwAddressID are ignored.

LINECALLSELECT_ADDRESS

Selects the specified address on the line. Both hLine and dwAddressID must be valid; hCall is ignored.

LINECALLSELECT_CALL

Selects the specified call. hCall must be valid; hLine and dwAddressID are both ignored.

lpDigitList

Specifies a pointer to the array that contains the digits that are to trigger media control actions, of type LINEMEDIACONTROLDIGIT. Each time a digit listed in the digit list is detected, the specified media control action is carried out on the call's media stream.

Valid digits for pulse mode are '0' through '9'. Valid digits for DTMF mode are '0' through '9', 'A', 'B', 'C', 'D', '*', '#'.

dwDigitNumEntries

Specifies the number of entries in the lpDigitList.

lpMediaList

Specifies a pointer to an array with entries of type LINEMEDIACONTROLMEDIA. The array has dwMediaNumEntries entries. Each entry contains a media mode to be monitored, media-type specific information (such as duration), and a media control field. If a media mode in the list is detected, the corresponding media control action is performed on the call's media stream.

dwMediaNumEntries

Specifies the number of entries in lpMediaList.

lpToneList

Specifies a pointer to an array with entries of type LINEMEDIACONTROLTONE. The array has dwToneNumEntries entries. Each entry contains a description of a tone to be monitored, duration of the tone, and a media-control field. If a tone in the list is detected, the corresponding media control action is performed on the call's media stream.

dwToneNumEntries

Specifies the number of entries in lpToneList.

lpCallStateList

Specifies a pointer to an array with entries are of type LINEMEDIACONTROLCALLSTATE. The array has dwCallStateNumEntries entries. Each entry contains a call state and a media control action. Whenever the given call transitions into one of the call states in the list, the corresponding media control action is invoked.

dwCallStateNumEntries

Specifies the number of entries in lpCallStateList.

This function is considered successful if media control has been correctly initiated, not when any media control has taken effect. Media control in progress is changed or is canceled by calling this function again with either different parameters or NULLs. If one or more of the parameters lpDigitList, lpMediaList, lpToneList, and lpCallStateList are NULL, then the corresponding digit, media mode, tone, or call state-triggered media control is disabled. To modify just a portion of the media control parameters while leaving the remaining settings in effect, the application should invoke lineSetMediaControl supplying the previous parameters for those portions that must remain in effect, and new parameters for those parts that are to be modified.

If hCall is selected and the call terminates or the application deallocates its handle, media control on that call is canceled.

All applications that are owners of the call are in principle allowed to make media control requests on the call. Only a single media control request can be outstanding on a call across all applications that own the call. Each time lineSetMediaControl is called, the new request overrides any media control then in effect on the call, whether set by the calling application or any other owning application.

Depending on the service provider and other activities that compete for such resources, the amount of simultaneous detections that can be made may vary over time. If service provider resources are overcommitted, the LINEERR_RESOURCEUNAVAIL error is returned.

Whether or not media control is supported by the service provider is a device capability.


 lineSetMediaMode

[New - Windows 95]

LONG lineSetMediaMode(HCALL hCall, DWORD dwMediaModes)

Sets the media mode(s) of the specified call in its LINECALLINFO structure.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

LINEERR_INVALCALLHANDLE	LINEERR_OPERATIONFAILED
LINEERR_INVALMEDIAMODE	LINEERR_RESOURCEUNAVAIL
LINEERR_NOMEM	LINEERR_UNINITIALIZED
LINEERR_OPERATIONUNAVAIL
hCall

Specifies a handle to the call whose media mode is to be changed. The application must be an owner of the call. Call state of hCall can be any state.

dwMediaModes

Specifies the new media mode(s) for the call. As long as the UNKNOWN media mode flag is set, other media mode flags may be set as well. This is used to identify a call's media mode as not fully determined, but narrowed down to one of a small set of specified media modes. If the UNKNOWN flag is not set, only a single media mode can be specified. This parameter uses the following LINEMEDIAMODE_ constants:

LINEMEDIAMODE_UNKNOWN

The target application is the one that handles calls of unknown media mode (unclassified calls).

LINEMEDIAMODE_INTERACTIVEVOICE

The target application is the one that handles calls with the interactive voice media mode (live conversations).

LINEMEDIAMODE_AUTOMATEDVOICE

Voice energy is present on the call, and the voice is locally handled by an automated application.

LINEMEDIAMODE_DATAMODEM

The target application is the one that handles calls with the data modem media mode.

LINEMEDIAMODE_G3FAX

The target application is the one that handles calls with the group 3 fax media mode.

LINEMEDIAMODE_TDD

The target application is the one that handles calls with the TDD (Telephony Devices for the Deaf) media mode.

LINEMEDIAMODE_G4FAX

The target application is the one that handles calls with the group 4 fax media mode.

LINEMEDIAMODE_DIGITALDATA

The target application is the one that handles calls that are digital data calls.

LINEMEDIAMODE_TELETEX

The target application is the one that handles calls with the teletex media mode.

LINEMEDIAMODE_VIDEOTEX

The target application is the one that handles calls with the videotex media mode.

LINEMEDIAMODE_TELEX

The target application is the one that handles calls with the telex media mode.

LINEMEDIAMODE_MIXED

The target application is the one that handles calls with the ISDN mixed media mode.

LINEMEDIAMODE_ADSI

The target application is the one that handles calls with the ADSI (Analog Display Services Interface) media mode.

LINEMEDIAMODE_VOICEVIEW

The media mode of the call is VoiceView.

This function changes the call's media mode in its LINECALLINFO structure. Typical usage of this operation is either to set a call's media mode to a specific known media mode or to exclude possible media modes as long as the call's media mode is officially unknown (the UNKNOWN media mode flag is set).


 lineSetNumRings

[New - Windows 95]

LONG lineSetNumRings(HLINE hLine, DWORD dwAddressID, DWORD dwNumRings)

Sets the number of rings that must occur before an incoming call is answered. This function can be used to implement a toll-saver-style function. It allows multiple independent applications to each register the number of rings. The function lineGetNumRings returns the minimum number of all number of rings requested. It can be used by the application that answers inbound calls to determine the number of rings it should wait before answering the call.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

LINEERR_INVALLINEHANDLE	LINEERR_OPERATIONFAILED
LINEERR_INVALADDRESSID	LINEERR_RESOURCEUNAVAIL
LINEERR_NOMEM	LINEERR_UNINITIALIZED
hLine

Specifies a handle to the open line device.

dwAddressID

Specifies an address on the line device.

dwNumRings

Specifies the number of rings before a call should be answered in order to honor the toll-saver requests from all applications.

The lineGetNumRings and lineSetNumRings functions, when used in combination, provide a mechanism to support the implementation of toll-saver features across multiple independent applications. If no application ever calls lineSetNumRings, lineGetNumRings will return 0xFFFFFFFF.

An application that is the owner of a call in the offering state and that received a LINE_LINEDEVSTATE ringing message should wait a number of rings equal to the number returned by lineGetNumRings before answering the call in order to honor the toll-saver settings across all applications. A separate LINE_LINEDEVSTATE ringing message is sent to the application for each ring cycle, so the application should count these messages. If this call disconnects before being answered, and another call comes in shortly thereafter, the LINE_CALLSTATE message should allow the application to determine that ringing is related to the second call.

If call classification is performed by TAPI.DLL by means of answering inbound calls of unknown media mode and filtering the media stream, TAPI.DLL will honor this number as well.

Note that this operation is purely informational and does not affect the state of any calls on the line device.


 lineSetStatusMessages

[New - Windows 95]

LONG lineSetStatusMessages(HLINE hLine, DWORD dwLineStates,
    DWORD dwAddressStates)

Enables an application to specify which notification messages the application wants to receive for events related to status changes for the specified line or any of its addresses.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

LINEERR_INVALADDRESSSTATE	LINEERR_OPERATIONFAILED
LINEERR_INVALLINEHANDLE	LINEERR_RESOURCEUNAVAIL
LINEERR_INVALLINESTATE	LINEERR_UNINITIALIZED
LINEERR_NOMEM	LINEERR_OPERATIONUNAVAIL
hLine

Specifies a handle to the line device.

dwLineStates

Specifies a bit array that identifies for which line-device status changes a message is to be sent to the application. This parameter uses the following LINEDEVSTATE_ constants:

LINEDEVSTATE_OTHER

Device-status items other than those listed below have changed. The application should check the current device status to determine which items have changed.

LINEDEVSTATE_RINGING

The switch tells the line to alert the user.

LINEDEVSTATE_CONNECTED

The line was previously disconnected and is now connected to TAPI.

LINEDEVSTATE_DISCONNECTED

This line was previously connected and is now disconnected from TAPI.

LINEDEVSTATE_MSGWAITON

The "message waiting" indicator is turned on.

LINEDEVSTATE_MSGWAITOFF

The "message waiting" indicator is turned off.

LINEDEVSTATE_INSERVICE

The line is connected to TAPI. This happens when TAPI is first activated, or when the line wire is physically plugged in and in service at the switch while TAPI is active.

LINEDEVSTATE_OUTOFSERVICE

The line is out of service at the switch or physically disconnected. TAPI cannot be used to operate on the line device.

LINEDEVSTATE_MAINTENANCE

Maintenance is being performed on the line at the switch. TAPI cannot be used to operate on the line device.

LINEDEVSTATE_OPEN

The line has been opened by some application.

LINEDEVSTATE_CLOSE

The line has been closed by some application.

LINEDEVSTATE_NUMCALLS

The number of calls on the line device has changed.

LINEDEVSTATE_NUMCOMPLETIONS

The number of outstanding call completions on the line device has changed.

LINEDEVSTATE_TERMINALS

The terminal settings have changed.

LINEDEVSTATE_ROAMMODE

The roam mode of the line device has changed.

LINEDEVSTATE_BATTERY

The battery level has changed significantly (cellular).

LINEDEVSTATE_SIGNAL

The signal level has changed significantly (cellular).

LINEDEVSTATE_DEVSPECIFIC

The line's device-specific information has changed.

LINEDEVSTATE_REINIT

Items have changed in the configuration of line devices. To become aware of these changes (as with the appearance of new line devices) the application should reinitialize its use of TAPI. New lineInitialize and lineOpen requests are denied until applications have shut down their usage of TAPI. The hDevice parameter of the LINE_LINEDEVSTATE message is left NULL for this state change as it applies to any of the lines in the system. Because of the critical nature of LINEDEVSTATE_REINIT, such messages cannot be masked, so the setting of this bit is ignored and the messages are always delivered to the application.

LINEDEVSTATE_LOCK

The locked status of the line device has changed.

dwAddressStates

Specifies a bit array that identifies for which address status changes a message is to be sent to the application. This parameter uses the following LINEADDRESSSTATE_ constants:

LINEADDRESSSTATE_OTHER

Address-status items other than those listed below have changed. The application should check the current address status to determine which items have changed.

LINEADDRESSSTATE_DEVSPECIFIC

The device-specific item of the address status has changed.

LINEADDRESSSTATE_INUSEZERO

The address has changed to idle (it is now in use by zero stations).

LINEADDRESSSTATE_INUSEONE

The address has changed from idle or from being in use by many bridged stations to being in use by just one station.

LINEADDRESSSTATE_INUSEMANY

The monitored or bridged address has changed from being in use by one station to being used by more than one station.

LINEADDRESSSTATE_NUMCALLS

The number of calls on the address has changed. This is the result of events such as a new inbound call, an outbound call on the address, or a call changing its hold status.

LINEADDRESSSTATE_FORWARD

The forwarding status of the address has changed (including the number of rings for determining a no answer condition). The application should check the address status to determine details about the address's current forwarding status.

LINEADDRESSSTATE_TERMINALS

The terminal settings for the address have changed.

TAPI defines a number of messages that notify applications about events occurring on lines and addresses. An application may not be interested in receiving all address and line status change messages. lineSetStatusMessages can be used to select which messages the application wants to receive. By default, address and line status reporting is disabled.


 lineSetTerminal

[New - Windows 95]

LONG lineSetTerminal(HLINE hLine, DWORD dwAddressID, HCALL hCall,
    DWORD dwSelect, DWORD dwTerminalModes, DWORD dwTerminalID,
    DWORD bEnable)

Enables an application to specify which terminal information related to the specified line, address, or call is to be routed. lineSetTerminal can be used while calls are in progress on the line to allow an application to route these events to different devices as required.

•	Returns a positive request ID if the function will be completed asynchronously, or a negative error number if an error has occurred. The dwParam2 parameter of the corresponding LINE_REPLY callback message is zero if the function is successful or it is a negative error number if an error has occurred. Possible return values are:

LINEERR_INVALADDRESSID	LINEERR_NOMEM
LINEERR_INVALCALLHANDLE	LINEERR_OPERATIONUNAVAIL
LINEERR_INVALCALLSELECT	LINEERR_OPERATIONFAILED
LINEERR_INVALLINEHANDLE	LINEERR_RESOURCEUNAVAIL
LINEERR_INVALTERMINALID	LINEERR_UNINITIALIZED
LINEERR_INVALTERMINALMODE
hLine

Specifies a handle to an open line device.

dwAddressID

Specifies an address on the given open line device.

hCall

Specifies a handle to a call. Call state of hCall can be any state, if dwSelect is CALL.

dwSelect

Specifies whether the terminal setting is requested for the line, the address, or just the specified call. If line or address is specified, events either apply to the line or address itself or serves as a default initial setting for all new calls on the line or address. This parameter uses the following LINECALLSELECT_ constants:

LINECALLSELECT_LINE

Selects the specified line device. The hLine parameter must be a valid line handle; hCall and dwAddressID are ignored.

LINECALLSELECT_ADDRESS

Selects the specified address on the line. Both hLine and dwAddressID must be valid; hCall is ignored.

LINECALLSELECT_CALL

Selects the specified call. hCall must be valid; hLine and dwAddressID are both ignored.

dwTerminalModes

Specifies the class(es) of low-level events to be routed to the given terminal. This parameter uses the following LINETERMMODE_ constants:

LINETERMMODE_BUTTONS

The button presses from the terminal to the line.

LINETERMMODE_DISPLAY

The display events from the line to the terminal.

LINETERMMODE_LAMPS

The lamp lighting events from the line to the terminal.

LINETERMMODE_RINGER

The ring requests from the line to the terminal.

LINETERMMODE_HOOKSWITCH

The hookswitch events between the terminal and the line.

LINETERMMODE_MEDIATOLINE

This is the unidirectional media stream from the terminal to the line associated with a call on the line. Use this value when routing of both unidirectional channels of a call's media stream can be controlled independently.

LINETERMMODE_MEDIAFROMLINE

This is the unidirectional media stream from the line to the terminal associated with a call on the line. Use this value when routing of both unidirectional channels of a call's media stream can be controlled independently.

LINETERMMODE_MEDIABIDIRECT

This is the bidirectional media stream associated with a call on the line and the terminal. Use this value when routing of both unidirectional channels of a call's media stream cannot be controlled independently. Note that MEDIABIDIRECT is mutually exclusive with MEDIATOLINE and MEDIAFROMLINE

dwTerminalID

Specifies the device ID of the terminal device where the given events are to be routed. Terminal IDs are small integers in the range of 0 to one less than dwNumTerminals, where dwNumTerminals, and the terminal modes each terminal is capable of handling, are returned by lineGetDevCaps. Note that these terminal IDs have no relation to other device IDs and are defined by the service provider using device capabilities.

bEnable

If TRUE, dwTerminalID is valid and the specified event classes are routed to or from that terminal. If FALSE, these events are not routed to or from the terminal device with ID equal to dwTerminalID.

An application can use this function to route certain classes of low-level line events to the specified terminal device or to suppress the routing of these events. For example, voice may be routed to an audio I/O device (headset); lamps and display events may be routed to the local phone device, and button events and ringer events may be suppressed altogether.

This function can be called at any time, even when a call is active on the given line device. This allows a user to switch from using the local phone set to another audio I/O device. This function may be called multiple times to route the same events to multiple terminals simultaneously. To reroute events to a different terminal, the application should first disable routing to the existing terminal and then route the events to the new terminal.

Terminal ID assignments are made by the line's service provider. Device capabilities indicate only which terminal IDs the service provider has available. Service providers that do not support this type of event routing would indicate that they have no terminal devices (dwNumTerminals in LINEDEVCAPS would be zero).

Invoking lineSetTerminal on a line or address affects all existing calls on that line or address, but does not affect calls on other addresses. It also sets the default for future calls on that line or address. A line or address that has multiple connected calls active at one time may have different routing in effect for each call.

Disabling the routing of low-level events to a terminal when these events are not currently routed to or from that terminal will not necessarily generate an error so long after the function succeeds (the specified events are not routed to or from that terminal).

TAPI routes call progress tones and messages to the same location as set by the lineSetTerminal function for "media". For example, if audio signals are going to the phone, then so will busy signals (analog) or Q.931 messages indicating busy (digital).


 lineSetTollList

[New - Windows 95]

LONG lineSetTollList(HLINEAPP hLineApp, DWORD dwDeviceID,
    LPCSTR lpszAddressIn, DWORD dwTollListOption)

Manipulates the toll list.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

LINEERR_BADDEVICEID	LINEERR_NODRIVER
LINEERR_INVALAPPHANDLE	LINEERR_NOMEM
LINEERR_INVALADDRESS	LINEERR_OPERATIONFAILED
LINEERR_INVALPARAM	LINEERR_RESOURCEUNAVAIL
LINEERR_INIFILECORRUPT	LINEERR_UNINITIALIZED
LINEERR_INVALLOCATION
hLineApp

Specifies the application handle returned by lineInitialize.

dwDeviceID

Specifies the device ID for the line device upon which the call is intended to be dialed, so that variations in dialing procedures on different lines can be applied to the translation process.

lpszAddressIn

Specifies a pointer to a NULL-terminated ASCII string containing the address from which the prefix information is to be extracted for processing. This parameter must not be NULL, and it must be in the canonical address format.

dwTollListOption

Specifies the toll list operation to be performed. Only a single flag can be set. This parameter uses the following LINETOLLLISTOPTION_ constants:

LINETOLLLISTOPTION_ADD

Causes the prefix contained within the string pointed to by lpszAddressIn to be added to the toll list for the current location.

LINETOLLLISTOPTION_REMOVE

Causes the prefix to be removed from the toll list of the current location. If toll lists are not used or relevant to the country indicated in the current location, the operation has no affect.

If an application has not yet called the lineInitialize function, it can set the hLineApp parameter to NULL and the dwDevice parameter to 0 when calling the lineSetTollList function.


 lineSetupConference

[New - Windows 95]

LONG lineSetupConference(HCALL hCall, HLINE hLine, LPHCALL lphConfCall,
    LPHCALL lphConsultCall, DWORD dwNumParties,
    LPLINECALLPARAMS const lpCallParams)

Sets up a conference call for the addition of the third party.

•	Returns a positive request ID if the function will be completed asynchronously, or a negative error number if an error has occurred. The dwParam2 parameter of the corresponding LINE_REPLY callback message is zero if the function is successful or it is a negative error number if an error has occurred. Possible return values are:

LINEERR_BEARERMODEUNAVAIL	LINEERR_UNINITIALIZED
LINEERR_CALLUNAVAIL	LINEERR_INVALMEDIAMODE
LINEERR_CONFERENCEFULL	LINEERR_INVALPOINTER
LINEERR_INUSE	LINEERR_INVALRATE
LINEERR_INVALADDRESSMODE	LINEERR_NOMEM
LINEERR_INVALBEARERMODE	LINEERR_NOTOWNER
LINEERR_INVALCALLHANDLE	LINEERR_OPERATIONUNAVAIL
LINEERR_INVALCALLSTATE	LINEERR_OPERATIONFAILED
LINEERR_INVALCALLPARAMS	LINEERR_RATEUNAVAIL
LINEERR_INVALLINEHANDLE	LINEERR_RESOURCEUNAVAIL
LINEERR_INVALLINESTATE	LINEERR_STRUCTURETOOSMALL
LINEERR_USERUSERINFOTOOBIG
hCall

Specifies the initial call that identifies the first party of a conference call. In some environments (as described in device capabilities), a call must exist in order to start a conference call, and the application must be an owner of this call. In other telephony environments, no call initially exists, hCall must be left NULL, and hLine must be specified to identify the line on which the conference call is to be initiated. Call state of hCall must be connected.

hLine

Specifies a handle to the line. This handle is used to identify the line device on which to originate the conference call if hCall is NULL. The hLine parameter is ignored if hCall is non-NULL.

lphConfCall

Specifies a pointer to an HCALL handle. This location is then loaded with a handle identifying the newly created conference call. The application will be the initial sole owner of this call. Call state of hConfCall is not applicable.

lphConsultCall

Specifies a pointer to an HCALL handle. When setting up a call for the addition of a new party, a new temporary call (consultation call) is automatically allocated. Initially, the application will be the sole owner for this call.

dwNumParties

Specifies the expected number of parties in the conference call. This number is passed to the service provider. The service provider is free to do as it pleases with this number: ignore it, use it as a hint to allocate the right size conference bridge inside the switch, and so on.

lpCallParams

Specifies a pointer to call parameters to be used when establishing the consultation call. This parameter may be set to NULL if no special call setup parameters are desired.

If LINEERR_INVALLINESTATE is returned, the line is currently not in a state in which this operation can be performed. A list of currently valid operations can be found in the dwLineFeatures field (of the type LINEFEATURE) in the LINEDEVSTATUS structure. (Calling lineGetLineDevStatus updates the information in LINEDEVSTATUS.) If LINEERR_INVALMEDIAMODE is returned, check for supported media modes on the line in the dwMediaModes field in the LINEDEVCAPS structure.

lineSetupConference provides two ways to establish a new conference call, depending on whether a normal two-party call is required to pre-exist or not. When setting up a conference call from an existing two-party call, the hCall parameter is a valid call handle that is initially added to the conference call by the lineSetupConference request; hLine is ignored. On switches where conference call setup does not start with an existing call, hCall must be NULL and hLine must be specified to identify the line device on which to initiate the conference call. In either case, a consultation call is allocated for connecting to the party that is to be added to the call. The application can then use lineDial to dial the address of the other party.

The conference call typically transitions into the onHoldPendingConference state, the consultation call into the dialtone state, and the initial call (if there is one) into the conferenced state.

A conference call can also be set up by a lineCompleteTransfer that is resolved into a three-way conference. The application may be able to toggle between the consultation call and the conference call using lineSwapHold.

A consultation call can be canceled by invoking lineDropon it. When dropping a consultation call, the existing conference call typically transitions back to the connected state. The application should observe the LINE_CALLSTATE messages to determine exactly what happens to the calls. For example, if the conference call reverts back to a regular two-party call, the conference call will become idle and the original participant call may revert to connected.

If an application specifies the handle of the conference call in a call to the lineUnhold function, the conference call state is set to idle.


 lineSetupTransfer

[New - Windows 95]

LONG lineSetupTransfer(HCALL hCall, LPHCALL lphConsultCall,
    LPLINECALLPARAMS const lpCallParams)

Initiates a transfer of the call specified by hCall. It establishes a consultation call, lphConsultCall, on which the party can be dialed that can become the destination of the transfer. The application acquires owner privilege to lphConsultCall.

•	Returns a positive request ID if the function will be completed asynchronously, or a negative error number if an error has occurred. The dwParam2 parameter of the corresponding LINE_REPLY callback message is zero if the function is successful or it is a negative error number if an error has occurred. Possible return values are:

LINEERR_BEARERMODEUNAVAIL	LINEERR_INVALRATE
LINEERR_CALLUNAVAIL	LINEERR_NOMEM
LINEERR_INUSE	LINEERR_NOTOWNER
LINEERR_INVALADDRESSMODE	LINEERR_OPERATIONFAILED
LINEERR_INVALBEARERMODE	LINEERR_OPERATIONUNAVAIL
LINEERR_INVALCALLHANDLE	LINEERR_RATEUNAVAIL
LINEERR_INVALCALLPARAMS	LINEERR_RESOURCEUNAVAIL
LINEERR_INVALCALLSTATE	LINEERR_STRUCTURETOOSMALL
LINEERR_INVALLINESTATE	LINEERR_UNINITIALIZED
LINEERR_INVALMEDIAMODE	LINEERR_USERUSERINFOTOOBIG
LINEERR_INVALPOINTER
hCall

Specifies the handle of the call to be transferred. The application must be an owner of the call. Call state of hCall must be connected.

lphConsultCall

Specifies a pointer to an HCALL handle. This location is then loaded with a handle identifying the temporary consultation call. When setting up a call for transfer, another call (a consultation call) is automatically allocated to enable the application to dial the address (using lineDial) of the party to where the call is to be transferred. The originating party can carry on a conversation over this consultation call prior to completing the transfer. Call state of hConsultCall is not applicable.

This transfer procedure may not be valid for some line devices. The application may need to ignore the new consultation call and unhold an existing held call (using lineUnhold) to identify the destination of the transfer. On switches that support cross-address call transfer, the consultation call may exist on a different address than the call to be transferred. It may also be necessary that the consultation call be set up as an entirely new call, by lineMakeCall, to the destination of the transfer. Which forms of transfer are available are specified in the call's address capabilities.

lpCallParams

Specifies a pointer to call parameters to be used when establishing the consultation call. This parameter may be set to NULL if no special call setup parameters are desired.

This function sets up the transfer of the call specified by hCall. The setup phase of a transfer establishes a consultation call that enables the application to send the address of the destination (the party to be transferred to) to the switch, while the call to be transferred is kept on hold. This new call is referred to as a consultation call (hConsultCall) and can be dropped or otherwise manipulated independently of the original call.

When the consultation call has reached the dialtone call state, the application may proceed transferring the call either by dialing the destination address and tracking its progress, or by unholding an existing call. The transfer of the original call to the selected destination is completed using lineCompleteTransfer.

While the consultation call exists, the original call typically transitions to the onholdPendingTransfer state. The application may be able to toggle between the consultation call and the original call by using lineSwapHold. A consultation call can be canceled by invoking lineDrop on it. After dropping a consultation call, the original call will typically transition back to the connected state. If the call state of the original call is onHoldPendingTransfer, the lineUnhold function can be used to recover the call. In this case, the call state of the consultation call is set to idle.

The application may also transfer calls in a single step, without having to deal with the intervening consultation call by using lineBlindTransfer.


 lineShutdown

[New - Windows 95]

LONG lineShutdown(HLINEAPP hLineApp)

Shuts down the application's usage of the line abstraction of API.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

LINEERR_INVALAPPHANDLE	LINEERR_RESOURCEUNAVAIL
LINEERR_NOMEM	LINEERR_UNINITIALIZED
hLineApp

Specifies the application's usage handle for the line API.

If this function is called when the application has lines open or calls active, the call handles are deleted and TAPI.DLL automatically performs the equivalent of a lineClose on each open line. However, it is recommended that applications explicitly close all open lines before invoking lineShutdown. If shutdown is performed while asynchronous requests are outstanding, those requests will be cancelled.


 lineSwapHold

[New - Windows 95]

LONG lineSwapHold(HCALL hActiveCall, HCALL hHeldCall)

Swaps the specified active call with the specified call on consultation hold.

•	Returns a positive request ID if the function will be completed asynchronously, or a negative error number if an error has occurred. The dwParam2 parameter of the corresponding LINE_REPLY callback message is zero if the function is successful or it is a negative error number if an error has occurred. Possible return values are:

LINEERR_INVALCALLHANDLE	LINEERR_OPERATIONUNAVAIL
LINEERR_INVALCALLSTATE	LINEERR_OPERATIONFAILED
LINEERR_NOMEM	LINEERR_RESOURCEUNAVAIL
LINEERR_NOTOWNER	LINEERR_UNINITIALIZED
hActiveCall

Specifies the handle to the active call. The application must be an owner of the call. Call state of hActiveCall must be connected.

hHeldCall

Specifies the handle to the consultation call. The application must be an owner of the call. Call state of hHeldCall can be onHoldPendingTransfer, onHoldPendingConference, onHold .

Swapping the active call with the call on consultation hold allows the application to alternate or toggle between these two calls. This is typical in call waiting.


 lineTranslateAddress

[New - Windows 95]

LONG lineTranslateAddress(HLINEAPP hLineApp, DWORD dwDeviceID,
    DWORD dwAPIVersion, LPCSTR lpszAddressIn, DWORD dwCard,
    DWORD dwTranslateOptions, LPLINETRANSLATEOUTPUT lpTranslateOutput)

This operation translates the specified address into another format.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

LINEERR_BADDEVICEID	LINEERR_INVALPOINTER
LINEERR_INCOMPATIBLEAPIVERSION	LINEERR_NODRIVER
LINEERR_INIFILECORRUPT	LINEERR_NOMEM
LINEERR_INVALADDRESS	LINEERR_OPERATIONFAILED
LINEERR_INVALAPPHANDLE	LINEERR_RESOURCEUNAVAIL
LINEERR_INVALCARD	LINEERR_STRUCTURETOOSMALL
LINEERR_INVALPARAM	LINEERR_UNINITIALIZED
hLineApp

Specifies the application handle returned by lineInitialize.

dwDeviceID

Specifies the device ID for the line device upon which the call is intended to be dialed, so that variations in dialing procedures on different lines can be applied to the translation process.

dwAPIVersion

Indicates the version of TAPI negotiated by lineNegotiateAPIVersion.

lpszAddressIn

Specifies a pointer to a NULL-terminated ASCII string containing the address from which the information is to be extracted for translation. Must be in either the canonical address format, or an arbitrary string of dialable digits (non-canonical). This parameter must not be NULL. If the AddressIn contains a subaddress or name field, or additional addresses separated from the first address by ASCII CR and LF characters, only the first address is translated, and the remainder of the string is returned to the application without modification.

dwCard

Specifies the credit card to be used for dialing. This field in only valid if the CARDOVERRIDE bit is set in dwTranslateOptions. This field specifies the permanent ID of a Card entry in the [Cards] section of TELEPHON.INI (as obtained from lineTranslateCaps) which should be used instead of the PreferredCardID specified in the definition of the CurrentLocation. It does not cause the PreferredCardID parameter of the current Location entry in TELEPHON.INI to be modified; the override applies only to the current translation operation. This field is ignored if the CARDOVERRIDE bit is not set in dwTranslateOptions.

dwTranslateOptions

Specifies the associated operations to be performed prior to the translation of the address into a dialable string. This parameter uses the following LINETRANSLATEOPTION_ constants:

LINETRANSLATEOPTION_CARDOVERRIDE

If this bit is set, dwCard specifies the permanent ID of a Card entry in the [Cards] section of TELEPHON.INI (as obtained from lineTranslateCaps) which should be used instead of the PreferredCardID specified in the definition of the CurrentLocation. It does not cause the PreferredCardID parameter of the current Location entry in TELEPHON.INI to be modified; the override applies only to the current translation operation. The dwCard field is ignored if the CARDOVERRIDE bit is not set.

LINETRANSLATEOPTION_CANCELCALLWAITING

If a Cancel Call Waiting string is defined for the location, setting this bit will cause that string to be inserted at the beginning of the dialable string. This is commonly used by datamodem and fax applications to prevent interruption of calls by call waiting beeps. If no Cancel Call Waiting string is defined for the location, this bit has no affect. Note that applications using this bit are advised to also set the LINECALLPARAMFLAGS_SECURE bit in the dwCallParamFlags field of the LINECALLPARAMS structure passed in to lineMakeCall via the lpCallParams parameter, so that if the line device uses a mechanism other than dialable digits to supress call interrupts that that mechanism will be invoked.

LINETRANSLATEOPTION_FORCELOCAL

If the number is local but would have been translated as a long distance call (LINETRANSLATERESULT_INTOLLLIST bit set in the LINETRANSLATEOUTPUT structure), this option will force it to be translated as local. This is a temporary override of the toll list setting.

LINETRANSLATEOPTION_FORCELD

If the address could potentially have been a toll call, but would have been translated as a local call (LINETRANSLATERESULT_NOTINTOLLLIST bit set in the LINETRANSLATEOUTPUT structure), this option will force it to be translated as long distance. This is a temporary override of the toll list setting.

lpTranslateOutput

Specifies a pointer to an application-allocated memory area to contain the output of the translation operation, of type LINETRANSLATEOUTPUT. Prior to calling lineTranslateAdress, the application should set the dwTotalSize field of this structure to indicate the amount of memory available to TAPI.DLL for returning information.

If an application has not yet called the lineInitialize function, it can set the hLineApp parameter to NULL and the dwDevice parameter to 0 when calling the lineTranslateAddress function.


 lineTranslateDialog

[New - Windows 95]

LONG lineTranslateDialog (HLINEAPP hLineApp, DWORD dwDeviceID,
    DWORD dwAPIVersion, HWND hwndOwner, LPCSTR lpszAddressIn)

Displays an application-modal dialog which allows the user to change the current location, adjust location and calling card parameters, and see the effect on a phone number about to be dialed.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

LINEERR_BADDEVICEID	LINEERR_INVALPARAM
LINEERR_INCOMPATIBLEAPIVERSION	LINEERR_INVALPOINTER
LINEERR_INIFILECORRUPT	LINEERR_NODRIVER
LINEERR_INUSE	LINEERR_NOMEM
LINEERR_INVALADDRESS	LINEERR_OPERATIONFAILED
LINEERR_INVALAPPHANDLE	LINEERR_UNINITIALIZED
hLineApp

Specifies the application handle returned by lineInitialize.

dwDeviceID

Specifies the device ID for the line device upon which the call is intended to be dialed, so that variations in dialing procedures on different lines can be applied to the translation process.

dwAPIVersion

Indicates the highest version of TAPI supported by the application (not necessarily the value negotiated by lineNegotiateAPIVersion on the line device indicated by dwDeviceID).

hwndOwner

Specifies a handle to a window to which the dialog is to be attached.

lpszAddressIn

Specifies a pointer to a NULL-terminated ASCII string containing a phone number which will be used, in the lower portion of the dialog, to show the effect of the user's changes to the location parameters. The number must be in canonical format; if non-canonical, the phone number portion of the dialog will not be displayed. This pointer can be left NULL, in which case the phone number portion of the dialog will not be displayed. If the AddressIn contains a subaddress or name field, or additional addresses separated from the first address by ASCII CR and LF characters, only the first address is used in the dialog.

If LINEERR_INUSE is returned, the dialog is already displayed by another application, and cannot be open more than once. TAPI brings the existing dialog to the front. This error indicates that any particulars related to the address passed in by the current application have not been handled, since that address was not processed by the function.

The application must call lineGetTranslateCaps after this function to obtain any changes the user made to the telephony address translation parameters, and call lineTranslateAddress to obtain a dialable string based on the user's new selections.

If any function related to address translation (e.g., lineGetTranslateCaps or lineTranslateAddress) returns LINEERR_INIFILECORRUPT, the application should call lineTranslateDialog. lineTranslateDialog will detect the errors and correct them, and report the action taken to the user. Note that LINEERR_INIFILECORRUPT will be returned the first time any of these functions are used after installation of Windows 95, because the parameters will be uninitialized (lineTranslateDialog will take care of initializing them, using the user-specified default country to select the default country code).

Although this is a new function which older applications would not be expected to call, for backward compatibility, they should not be prevented from doing so; the full range of API versions supported by TAPI (0x00010003 to 0x00010004) should work the same way.

If an application has not yet called the lineInitialize function, it can set the hLineApp parameter to NULL and the dwDevice parameter to 0 when calling the lineTranslateDialog function.


 lineUncompleteCall

[New - Windows 95]

LONG lineUncompleteCall(HLINE hLine, DWORD dwCompletionID)

Cancels the specified call competion request on the specified line.

•	Returns a positive request ID if the function will be completed asynchronously, or a negative error number if an error has occurred. The dwParam2 parameter of the corresponding LINE_REPLY callback message is zero if the function is successful or it is a negative error number if an error has occurred. Possible return values are:

LINEERR_INVALLINEHANDLE	LINEERR_OPERATIONFAILED
LINEERR_INVALCOMPLETIONID	LINEERR_RESOURCEUNAVAIL
LINEERR_NOMEM	LINEERR_UNINITIALIZED
LINEERR_OPERATIONUNAVAIL
hLine

Specifies a handle to the line device on which a call completion is to be canceled.

dwCompletionID

Specifies the completion ID for the request that is to be canceled.


 lineUnhold

[New - Windows 95]

LONG lineUnhold(HCALL hCall)

Retrieves the specified held call.

•	Returns a positive request ID if the function will be completed asynchronously, or a negative error number if an error has occurred. The dwParam2 parameter of the corresponding LINE_REPLY callback message is zero if the function is successful or it is a negative error number if an error has occurred. Possible return values are:

LINEERR_INVALCALLHANDLE	LINEERR_OPERATIONUNAVAIL
LINEERR_INVALCALLSTATE	LINEERR_OPERATIONFAILED
LINEERR_NOMEM	LINEERR_RESOURCEUNAVAIL
LINEERR_NOTOWNER	LINEERR_UNINITIALIZED
hCall

Specifies the handle to the call to be retrieved. The application must be an owner of this call. Call state of hCall must be onHold, onHoldPendingTransfer, or onHoldPendingConference.


 lineUnpark

[New - Windows 95]

LONG lineUnpark(HLINE hLine, DWORD dwAddressID, LPHCALL lphCall,
    LPCSTR lpszDestAddress)

Retrieves the call parked at the specified address and returns a call handle for it.

•	Returns a positive request ID if the function will be completed asynchronously, or a negative error number if an error has occurred. The dwParam2 parameter of the corresponding LINE_REPLY callback message is zero if the function is successful or it is a negative error number if an error has occurred. Possible return values are:

LINEERR_INVALADDRESS	LINEERR_OPERATIONUNAVAIL
LINEERR_INVALADDRESSID	LINEERR_OPERATIONFAILED
LINEERR_INVALLINEHANDLE	LINEERR_RESOURCEUNAVAIL
LINEERR_INVALPOINTER	LINEERR_UNINITIALIZED
LINEERR_NOMEM
hLine

Specifies a handle to the open line device on which a call is to unparked.

dwAddressID

Specifies the address on hLine at which the unpark is to be originated.

lphCall

Specifies a pointer to the location of type HCALL where the handle to the unparked call is returned. This handle is unrelated to any other handle which might have been previously associated with the retrieved call, such as the handle that might have been associated with the call when it was originally parked. The application will be the initial sole owner of this call.

lpszDestAddress

Specifies a pointer to a NULL-terminated character buffer that contains the address where the call is parked. The address is in standard dialable address format.


 Constants


 Line Error Constants

This section lists the line error constants returned by the line functions.

LINEERR_ADDRESSBLOCKED

The specified address is blocked from being dialed on the specified call.

LINEERR_ALLOCATED

The line cannot be opened due to a "persistent" condition, such as that of a serial port being exclusively opened by another process.

LINEERR_BADDEVICEID

The specified device ID or line device ID (such as in a dwDeviceID parameter) is invalid or out of range.

LINEERR_BEARERMODEUNAVAIL

The call's bearer mode cannot be changed to the specified bearer mode.

LINEERR_CALLUNAVAIL

All call appearances on the specified address are currently in use.

LINEERR_COMPLETIONOVERRUN

The maximum number of outstanding call completions has been exceeded.

LINEERR_CONFERENCEFULL

The maximum number of parties for a conference has been reached, or the requested number of parties cannot be satisfied.

LINEERR_DIALBILLING

The dialable address parameter contains dialing control characters that are not processed by the service provider.

LINEERR_DIALQUIET

The dialable address parameter contains dialing control characters that are not processed by the service provider.

LINEERR_DIALDIALTONE

The dialable address parameter contains dialing control characters that are not processed by the service provider.

LINEERR_DIALPROMPT

The dialable address parameter contains dialing control characters that are not processed by the service provider.

LINEERR_INCOMPATIBLEAPIVERSION

The application requested an API version or version range that is either incompatible or cannot be supported by the Telephony API implementation and/or corresponding service provider.

LINEERR_INCOMPATIBLEEXTVERSION

The application requested an extension version range that is either invalid or cannot be supported by the corresponding service provider.

LINEERR_INIFILECORRUPT

The file TELEPHON.INI cannot be read or understood properly by TAPI.DLL because of internal inconsistencies or formatting problems. For example, the [Locations], [Cards], or [Countries] section of TELEPHON.INI may be corrupted or inconsistent.

LINEERR_INUSE

The line device is in use and cannot currently be configured, allow a party to be added, allow a call to be answered, allow a call to be placed, or allow a call to be transferred.

LINEERR_INVALADDRESS

A specified address is either invalid or not allowed. If invalid, the address contains invalid characters or digits, or the deistination address contains dialing control characters (W, @, $, or ?) that are not supported by the service provider. If not allowed, the specified address is either not assigned to the specified line or is not valid for address redirection.

LINEERR_INVALADDRESSID

The specified address ID is either invalid or out of range.

LINEERR_INVALADDRESSMODE

The specified address mode is invalid.

LINEERR_INVALADDRESSSTATE

dwAddressStates contains one or more bits that are not LINEADDRESSSTATE_ constants.

LINEERR_INVALAPPHANDLE

The application handle (such as specified by a hLineApp parameter) or the appliction registration handle is invalid.

LINEERR_INVALAPPNAME

The specified application name is invalid. If an application name is specified by the application, it is assumed that the string does not contain any non-displayable characters, and is zero-terminated.

LINEERR_INVALBEARERMODE

The specified bearer mode is invalid.

LINEERR_INVALCALLCOMPLMODE

The specified completion is invalid.

LINEERR_INVALCALLHANDLE

The specified call handle is not valid. For example, the handle is not NULL but does not belong to the given line. In some cases, the specified call device handle is invalid.

LINEERR_INVALCALLPARAMS

The specified call parameters are invalid.

LINEERR_INVALCALLPRIVILEGE

The specified call privilege parameter is invalid.

LINEERR_INVALCALLSELECT

The specified select parameter is invalid.

LINEERR_INVALCALLSTATE

The current state of a call is not in a valid state for the requested operation.

LINEERR_INVALCALLSTATELIST

The specified call state list is invalid.

LINEERR_INVALCARD

The permanent card ID specified in dwCard could not be found in any entry in the [Cards] section of TELEPHON.INI.

LINEERR_INVALCOMPLETIONID

The completion ID is invalid.

LINEERR_INVALCONFCALLHANDLE

The specified call handle for the conference call is invalid or is not a handle for a conference call.

LINEERR_INVALCONSULTCALLHANDLE

The specified consultation call handle is invalid.

LINEERR_INVALCOUNTRYCODE

The specified country code is invalid.

LINEERR_INVALDEVICECLASS

The line device has no associated device for the given device class, or the specified line does not support the indicated device class.

LINEERR_INVALDIGITLIST

The specified digit list is invalid.

LINEERR_INVALDIGITMODE

The specified digit mode is invalid.

LINEERR_INVALDIGITS

The specified termination digits are not valid.

LINEERR_INVALFEATURE

The dwFeature parameter is invalid.

LINEERR_INVALGROUPID

The specified group ID is invalid.

LINEERR_INVALLINEHANDLE

The specified call, device, line device, or line handle is invalid.

LINEERR_INVALLINESTATE

The device configuration may not be changed in the current line state. The line may be in use by another application or a dwLineStates parameter contains one or more bits that are not LINEDEVSTATE_ constants. The LINEERR_INVALLINESTATE value can also indicate that the device is DISCONNECTED or OUTOFSERVICE. These states are indicated by setting the bits corresponding to the LINEDEVSTATUSFLAGS_CONNECTED and LINEDEVSTATUSFLAGS_INSERVICE values to 0 in the dwDevStatusFlags member of the LINEDEVSTATUS structure returned by the lineGetLineDevStatus function.

LINEERR_INVALLOCATION

The permanent location ID specified in dwLocation could not be found in any entry in the [Locations] section of TELEPHON.INI.

LINEERR_INVALMEDIALIST

The specified media list is invalid.

LINEERR_INVALMEDIAMODE

The list of media types to be monitored contains invalid information, the specified media mode parameter is invalid, or the service provider does not support the specified media mode. The media modes supported on the line are listed in the dwMediaModes field in the LINEDEVCAPS structure.

LINEERR_INVALMESSAGEID

The number given in dwMessageID is outside the range specified by the dwNumCompletionMessages field in the LINEADDRESSCAPS structure.

LINEERR_INVALPARAM

A parameter (such as dwTollListOption, dwTranslateOptions, dwNumDigits, or a structure pointed to by lpDeviceConfig) contains invalid values, a country code is invalid, a window handle is invalid, or the specified forward list parameter contains invalid information.

LINEERR_INVALPARKMODE

The specified park mode is invalid.

LINEERR_INVALPOINTER

One or more of the specified pointer parameters (such as lpCallList, lpdwAPIVersion, lpExtensionID, lpdwExtVersion, lphIcon, lpLineDevCaps, and lpToneList) are invalid, or a required pointer to an output parameter is NULL.

LINEERR_INVALPRIVSELECT

An invalid flag or combination of flags was set for the dwPrivileges parameter.

LINEERR_INVALRATE

The specified bearer mode is invalid.

LINEERR_INVALREQUESTMODE

The specified request mode is invalid.

LINEERR_INVALTERMINALID

The specified terminal mode parameter is invalid.

LINEERR_INVALTERMINALMODE

The specified terminal modes parameter is invalid.

LINEERR_INVALTIMEOUT

Timeouts are not supported or the values of either or both of the parameters dwFirstDigitTimeout or dwInterDigitTimeout fall outside the valid range specified by the call's line-device capabilities.

LINEERR_INVALTONE

The specified custom tone does not represent a valid tone or is made up of too many frequencies or the specified tone structure does not describe a valid tone.

LINEERR_INVALTONELIST

The specified tone list is invalid.

LINEERR_INVALTONEMODE

The specified tone mode parameter is invalid.

LINEERR_INVALTRANSFERMODE

The specified transfer mode parameter is invalid.

LINEERR_LINEMAPPERFAILED

LINEMAPPER was the value passed in the dwDeviceID parameter, but no lines were found that match the requirements specified in the lpCallParams parameter.

LINEERR_NOCONFERENCE

The specified call is not a conference call handle or a participant call.

LINEERR_NODEVICE

The specified device ID, which was previously valid, is no longer accepted because the associated device has been removed from the system since TAPI was last initialized. Alternately, the line device has no associated device for the given device class.

LINEERR_NODRIVER

Either TAPIADDR.DLL could not be located or the telephone service provider for the specified device found that one of its components is missing or corrupt in a way that was not detected at initialization time. The user should be advised to use the Telephony Control Panel to correct the problem.

LINEERR_NOMEM

Insufficient memory to perform the operation, or unable to lock memory.

LINEERR_NOMULTIPLEINSTANCE

A Telephony Service Provider which does not support multiple instances is listed more than once in the [Providers] section of TELEPHON.INI. The application should advise the user to use the Telephony Control Panel to remove the duplicated driver.

LINEERR_NOREQUEST

There currently is no request pending of the indicated mode, or the application is no longer the highest-priority application for the specified request mode.

LINEERR_NOTOWNER

The application does not have owner privilege to the specified call(s).

LINEERR_NOTREGISTERED

The application is not registered as a request recipient for the indicated request mode.

LINEERR_OPERATIONFAILED

The operation failed for an unspecified or unknown reason.

LINEERR_OPERATIONUNAVAIL

The operation is not available, such as for the given device or specified line.

LINEERR_RATEUNAVAIL

The service provider currently does not have enough bandwidth available for the specified rate.

LINEERR_REINIT

If TAPI reinitialization has been requested, for example as a result of adding or removing a Telephony service provider, then lineInitialize or lineOpen requests are rejected with this error until the last application shuts down its usage of the API (using lineShutdown), at which time the new configuration becomes effective and applications are once again permitted to call lineInitialize.

LINEERR_RESOURCEUNAVAIL

Insufficient resources to complete the operation. For example, a line cannot be opened due to a dynamic resource overcommitment.

LINEERR_STRUCTURETOOSMALL

The dwTotalSize field indicates insufficient space to contain the fixed portion of the specified structure.

LINEERR_TARGETNOTFOUND

A target for the call handoff was not found. This may occur if the named application did not open the same line with the LINECALLPRIVILEGE_OWNER bit in the dwPrivileges parameter of lineOpen. Or, in the case of media-mode handoff, no application has opened the same line with the LINECALLPRIVILEGE_OWNER bit in the dwPrivileges parameter of lineOpen and with the media mode specified in the dwMediaMode parameter having been specified in the dwMediaModes parameter of lineOpen.

LINEERR_TARGETSELF

The application invoking this operation is the target of the indirect handoff.

LINEERR_UNINITIALIZED

The operation was invoked before any application called lineInitialize.

LINEERR_USERUSERINFOTOOBIG

The string containing user-to-user information exceeds the maximum number of bytes specified in the dwUUIAcceptSize, dwUUIAnswerSize, dwUUIDropSize, dwUUIMakeCallSize, or dwUUISendUserUserInfoSize field of LINEDEVCAPS, or the string containing user-to-user information is too long.


 Line Device Messages

About Line Device Messages

This chapter contains a list of the messages in the Telephony API. Messages are used to notify the application of the occurrence of asynchronous events. All of these messages are sent to the application-supplied callback function, lineCallbackFunc, in the application's context. When an application uses lineInitialize or phoneInitialize, it specifies a callback function by passing its pointer as a parameter.

The callback message always contains a handle to the relevant object (phone, line, or call). The parameter profile for callbacks contains a multi-purpose handle parameter which is used for passing a handle to the relevant phone, line, or call. The callback function can determine the type of the handle from the message that was passed to the callback.

Certain messages are used to notify the application about a change in an object's status. These messages provide the object handle and give an indication of which status item has changed. The application can call the appropriate "get status" function of the object to obtain the object's full status.

When an event occurs, messages or callbacks may be sent to zero, one, or more applications. The target applications for a message are determined by a number of different factors including the meaning of the message, the application's privilege to the object, whether or not the application initiated the request for which the message is a direct result, and the message masking that has been set by the application. Note the following points about messages:

•	Asynchronous reply messages are only sent to the application that originated the request and cannot be masked.

•	Messages that signal the completion of digit or tone generation or the gathering of digits are only sent to the application that requested the digit or tone generation.

•	Messages that indicate line or address state changes are sent to all applications that have opened the line.

•	Messages that indicate call state and call information changes are sent to all applications that are owners for the call and to monitoring applications that have not masked these messages.

•	Messages that signal a digit detection, tone detection, or media mode detection are sent to all applications (owners or monitors) that have not masked the event.

For more information about the lineCallbackFunc function, see Chapter 10, "Line Device Functions."


 Reference

Following are the Telephony API messages.


 LINE_ADDRESSSTATE

[New - Windows 95]

LINE_ADDRESSSTATE
dwDevice = (DWORD) hLine;
dwCallbackInstance = (DWORD) hCallback;
dwParam1 = (DWORD) idAddress;
dwParam2 = (DWORD) AddressState;
dwParam3 = (DWORD) 0;

Sent when the status of an address changes on a line that is currently open by the application. The application can invoke lineGetAddressStatus to determine the current status of the address.

•	No return value.

dwDevice

Specifies a handle to the line device.

dwCallbackInstance

Specifies the callback instance supplied when opening the line.

dwParam1

Specifies the address ID of the address that changed status.

dwParam2

Specifies the address state that changed. Can be a combination of these values:

LINEADDRESSSTATE_OTHER

Address-status items other than those listed below have changed. The application should check the current address status to determine which items have changed.

LINEADDRESSSTATE_DEVSPECIFIC

The device-specific item of the address status has changed.

LINEADDRESSSTATE_INUSEZERO

The address has changed to idle (it is now in use by zero stations).

LINEADDRESSSTATE_INUSEONE

The address has changed from idle or from being used by many bridged stations to being used by just one station.

LINEADDRESSSTATE_INUSEMANY

The monitored or bridged address has changed from being used by one station to being used by more than one station.

LINEADDRESSSTATE_NUMCALLS

The number of calls on the address has changed. This is the result of events such as a new inbound call, an outbound call on the address, or a call changing its hold status.

LINEADDRESSSTATE_FORWARD

The forwarding status of the address has changed, including the number of rings for determining a no answer condition. The application should check the address status to determine details about the address's current forwarding status.

LINEADDRESSSTATE_TERMINALS

The terminal settings for the address have changed.

LINEADDRESSSTATE_CAPSCHANGE

Indicates that, due to configuration changes made by the user or other circumstances, one or more of the fields in the LINEADDRESSCAPS structure for the address have changed. The application should use lineGetAddressCaps to read the updated structure. Applications which support API versions less than 0x00010004 will receive a LINEDEVSTATE_REINIT message, requiring them to shutdown and reinitialize their connection to TAPI in order to obtain the updated information.

dwParam3

Unused.

This message is sent to any application that has opened the line device and that has enabled this message. The sending of this message for the various status items can be controlled and queried using lineGetStatusMessages and lineSetStatusMessages. By default, address status reporting is disabled.


 LINE_CALLINFO

[New - Windows 95]

LINE_CALLINFO
dwDevice = (DWORD) hCall;
dwCallbackInstance = (DWORD) hCallback;
dwParam1 = (DWORD) CallInfoState;
dwParam2 = (DWORD) 0;
dwParam3 = (DWORD) 0;

Sent when the call information about the specified call has changed. The application can invoke lineGetCallInfo to determine the current call information.

•	No return value.

dwDevice

Specifies a handle to the call.

dwCallbackInstance

Specifies the callback instance supplied when opening the call's line.

dwParam1

Specifies the call information item that has changed. Can be a combination of these values:

LINECALLINFOSTATE_OTHER

Information items other than those listed below have changed. The application should check the current call information to determine which items have changed.

LINECALLINFOSTATE_DEVSPECIFIC

The device-specific field of the call-information record has changed.

LINECALLINFOSTATE_BEARERMODE

The bearer mode field of the call-information record has changed.

LINECALLINFOSTATE_RATE

The rate field of the call-information record has changed.

LINECALLINFOSTATE_MEDIAMODE

The media mode field of the call-information record has changed.

LINECALLINFOSTATE_APPSPECIFIC

The application-specific field of the call-information record has changed.

LINECALLINFOSTATE_CALLID

The call ID field of the call-information record has changed.

LINECALLINFOSTATE_RELATEDCALLID

The related call ID field of the call-information record has changed.

LINECALLINFOSTATE_ORIGIN

The origin field of the call-information record has changed.

LINECALLINFOSTATE_REASON

The reason field of the call-information record has changed.

LINECALLINFOSTATE_COMPLETIONID

The completion ID field of the call-information record has changed.

LINECALLINFOSTATE_NUMOWNERINCR

The number of owner fields in the call-information record was increased.

LINECALLINFOSTATE_NUMOWNERDECR

The number of owner fields in the call-information record was decreased.

LINECALLINFOSTATE_NUMMONITORS

The number of monitors fields in the call-information record has changed.

LINECALLINFOSTATE_TRUNK

The trunk field of the call-information record has changed.

LINECALLINFOSTATE_CALLERID

One of the callerID-related fields of the call-information record has changed.

LINECALLINFOSTATE_CALLEDID

One of the calledID-related fields of the call-information record has changed.

LINECALLINFOSTATE_CONNECTEDID

One of the cconnectedID-related fields of the call-information record has changed.

LINECALLINFOSTATE_REDIRECTIONID

One of the redirectionID-related fields of the call-information record has changed.

LINECALLINFOSTATE_REDIRECTINGID

One of the redirectingID-related fields of the call-information record has changed.

LINECALLINFOSTATE_DISPLAY

The display field of the call-information record has changed.

LINECALLINFOSTATE_USERUSERINFO

The user-to-user information of the call-information record has changed.

LINECALLINFOSTATE_HIGHLEVELCOMP

The high-level compatibility field of the call-information record has changed.

LINECALLINFOSTATE_LOWLEVELCOMP

The low-level compatibility field of the call-information record has changed.

LINECALLINFOSTATE_CHARGINGINFO

The charging information of the call-information record has changed.

LINECALLINFOSTATE_TERMINAL

The terminal mode information of the call-information record has changed.

LINECALLINFOSTATE_DIALPARAMS

The dial parameters of the call-information record has changed.

LINECALLINFOSTATE_MONITORMODES

One or more of the digit, tone, or media monitoring fields in the call-information record has changed.

dwParam2

Unused.

dwParam3

Unused.

A LINE_CALLINFO message with a NumOwnersIncr, NumOwnersDecr, and/or NumMonitorsChanged indication is sent to applications that already have a handle for the call. This can be the result of another application changing ownership or monitorship to a call with  lineOpen, lineClose, lineShutdown, lineSetCallPrivilege, lineGetNewCalls, and lineGetConfRelatedCalls.

These LINE_CALLINFO messages are not sent when a notification of a new call is provided in a LINE_CALLSTATE message, since the call information already reflects the correct number of owners and monitors at the time the LINE_CALLSTATE messages are sent. LINE_CALLINFO messages are also suppressed in the case where a call is offered by TAPI to monitors through the LINECALLSTATE_UNKNOWN mechanism.

Note also that the application which causes a change in the number of owners or monitors (for example, by invoking lineDeallocateCall or lineSetCallPrivilege) will not itself receive a message indicating that the change has been done.

No LINE_CALLINFO messages are sent for a call after the call has entered the idle state. Specifically, changes in the number of owners and monitors are not reported as applications deallocate their handles for the idle call.


 LINE_CALLSTATE

[New - Windows 95]

LINE_CALLSTATE
dwDevice = (DWORD) hCall;
dwCallbackInstance = (DWORD) hCallback;
dwParam1 = (DWORD) CallState;
dwParam2 = (DWORD) CallStateDetail;
dwParam3 = (DWORD) CallPrivilege;

Sent when the status of the specified call has changed. Several such messages will typically be received during the lifetime of a call. Applications are notified of new incoming calls with this message; the new call will be in the offering state. The application can use lineGetCallStatus to retrieve more detailed information about the current status of the call.

•	No return value.

dwDevice

Specifies a handle to the call.

dwCallbackInstance

Specifies the callback instance supplied when opening the call's line.

dwParam1

Specifies the new call state. This parameter must be one and only one of the following LINECALLSTATE_ values:

LINECALLSTATE_IDLE

The call is idle—no call actually exists.

LINECALLSTATE_OFFERING

The call is being offered to the station, signaling the arrival of a new call. In some environments, a call in the offering state does not automatically alert the user. Alerting is done by the switch instructing the line to ring; it does not affect any call states.

LINECALLSTATE_ACCEPTED

The call was offering and has been accepted. This indicates to other (monitoring) applications that the current owner application has claimed responsibility for answering the call. In ISDN, this also indicates that alerting to both parties has started.

LINECALLSTATE_DIALTONE

The call is receiving a dial tone from the switch, which means that the switch is ready to receive a dialed number.

LINECALLSTATE_DIALING

Destination address information (a phone number) is being sent to the switch over the call. Note that lineGenerateDigits does not place the line into the dialing state.

LINECALLSTATE_RINGBACK

The call is receiving ringback from the called address. Ringback indicates that the other station has been reached and is being alerted.

LINECALLSTATE_BUSY

The call is receiving a busy tone. Busy tone indicates that the call cannot be completed—either a circuit (trunk) or the remote party's station are in use.

LINECALLSTATE_SPECIALINFO

Special information is sent by the network. Special information is typically sent when the destination cannot be reached.

LINECALLSTATE_CONNECTED

The call has been established and the connection is made. Information is able to flow over the call between the originating address and the destination address.

LINECALLSTATE_PROCEEDING

Dialing has completed and the call is proceeding through the switch or telephone network.

LINECALLSTATE_ONHOLD

The call is on hold by the switch.

LINECALLSTATE_CONFERENCED

The call is currently a member of a multi-party conference call.

LINECALLSTATE_ONHOLDPENDCONF

The call is currently on hold while it is being added to a conference.

LINECALLSTATE_ONHOLDPENTRANSFER

The call is currently on hold awaiting transfer to another number.

LINECALLSTATE_DISCONNECTED

The remote party has disconnected from the call.

LINECALLSTATE_UNKNOWN

The state of the call is not known. This may be due to limitations of the call-progress detection implementation.

dwParam2

Specifies call-state-dependent information.

If dwParam1 is LINECALLSTATE_BUSY, dwParam2 contains details about the busy mode. This parameter uses the following LINEBUSYMODE_ constants:

LINEBUSYMODE_STATION

The busy signal indicates that the called party's station is busy. This is usually signaled by means of a "normal" busy tone.

LINEBUSYMODE_TRUNK

The busy signal indicates that a trunk or circuit is busy. This is usually signaled with a "long" busy tone.

LINEBUSYMODE_UNKNOWN

The busy signal's specific mode is currently unkown, but may become known later.

LINEBUSYMODE_UNAVAIL

The busy signal's specific mode is unavailable and will not become known.

If dwParam1 is LINECALLSTATE_DIALTONE, dwParam2 contains the details about the dialtone mode. This parameter uses the following LINEDIALTONEMODE_ constants:

LINEDIALTONEMODE_NORMAL

This is a "normal" dialtone, which typically is a continuous tone.

LINEDIALTONEMODE_SPECIAL

This is a special dialtone indicating that a certain condition is currently in effect.

LINEDIALTONEMODE_INTERNAL

This is an internal dialtone, as within a PBX.

LINEDIALTONEMODE_EXTERNAL

This is an external (public network) dialtone.

LINEDIALTONEMODE_UNKNOWN

The dialtone mode is currently unknown, but may become known later.

LINEDIALTONEMODE_UNAVAIL

The dialtone mode is unavailable and will not become known.

If dwParam1 is LINECALLSTATE_SPECIALINFO, dwParam2 contains the details about the special information mode. This parameter uses the following LINESPECIALINFO_ constants:

LINESPECIALINFO_NOCIRCUIT

This special information tone preceeds a "no circuit" or emergency announcement (trunk blockage category).

LINESPECIALINFO_CUSTIRREG

This special information tone preceeds a vacant number, AIS, Centrex number change and non-working station, access code not dialed or dialed in error, or manual intercept operator message (customer irregularity category).

LINESPECIALINFO_REORDER

This special information tone preceeds a reorder announcement (equipment irregularity category).

LINESPECIALINFO_UNKNOWN

Specifics about the special information tone are currently unknown but may become known later.

LINESPECIALINFO_UNAVAIL

Specifics about the special information tone are unavailable and will not become known.

If dwParam1 is LINECALLSTATE_DISCONNECTED, dwParam2 contains details about the disconnect mode. This parameter uses the following LINEDISCONNECTMODE_ constants:

LINEDISCONNECTMODE_NORMAL

This is a "normal" disconnect request by the remote party, the call was terminated normally.

LINEDISCONNECTMODE_UNKNOWN

The reason for the disconnect request is unknown.

LINEDISCONNECTMODE_REJECT

The remote user has rejected the call.

LINEDISCONNECTMODE_PICKUP

The call was picked up from elsewhere.

LINEDISCONNECTMODE_FORWARDED

The call was forwarded by the switch.

LINEDISCONNECTMODE_BUSY

The remote user's station is busy.

LINEDISCONNECTMODE_NOANSWER

The remote user's station does not answer.

LINEDISCONNECTMODE_BADADDRESS

The destination address in invalid.

LINEDISCONNECTMODE_UNREACHABLE

The remote user could not be reached.

LINEDISCONNECTMODE_CONGESTION

The network is congested.

LINEDISCONNECTMODE_INCOMPATIBLE

The remote user's station equipment is incompatible for the type of call requested.

LINEDISCONNECTMODE_UNAVAIL

The reason for the disconnect is unavailable and will not become known later.

If dwParam1 is LINECALLSTATE_CONFERENCED, dwParam2 contains the hConfCall of the parent call of the conference of which the subject hCall is a member. If the call specified in dwParam2 was not previously considered by the application to be a parent conference call (hConfCall), the application must do so as a result of this message. If the application does not have a handle to the parent call of the conference (because it has previously called lineDeallocateCall on that handle, dwParam2 will be set to null.)

dwParam3

If zero, this parameter indicates that there has been no change in the application's privilege for the call.

If non-zero, it specifies the application's privilege to the call. This will occur in the following situations: (1) The first time that the application is given a handle to this call; (2) When the application is the target of a call handoff (even if the application already was an owner of the call). This parameter uses the following LINECALLPRIVILEGE_ constants:

LINECALLPRIVILEGE_MONITOR

The application has monitor privilege.

LINECALLPRIVILEGE_OWNER

The application has owner privilege.

This message is sent to any application that has a handle for the call. Note that the LINE_CALLSTATE message also notifies applications that monitor calls on a line about the existence and state of outbound calls established by other applications or manually by the user (for example, on an attached phone device). The call state of such calls reflects the actual state of the call, which will not be offering. By examining the call state, the application can determine whether the call is an inbound call that needs to be answered or not.

A LINE_CALLSTATE message with an unknown call state may be sent to a monitoring application as the result of a successful lineMakeCall, lineForward, lineUnpark, lineSetupTransfer,  linePickup, lineSetupConference, or linePrepareAddToConference that has been requested by another application. At the same time that the requesting application is sent a LINE_REPLY (success) for the requested operation, any monitoring applications on the line will be sent the LINE_CALLSTATE (unknown) message. A LINE_CALLSTATE indicating the "real" call state of the newly generated call will be sent (using information provided by the service provider) to the requesting and monitoring applications shortly thereafter.

A LINE_CALLSTATE (unknown) message is sent to monitoring applications only if lineCompleteTransfer causes calls to be resolved into a three-way conference.

For backward compatibility, older applications will not be expecting any particular value in dwParam2 of a LINECALLSTATE_CONFERENCED message. TAPI will therefore pass the parent call hConfCall in dwParam2 regardles of the API version of the application receiving the message. In the case of a conference call initiated by the service provider, the older application will not be aware that the parent call has become a conference call unless it happens to spontaneously examine other information (e.g., call lineGetConfRelatedCalls)

The LINE_CALLSTATE message may receive the LINECONNECTEDMODE_ACTIVE or LINECONNECTEDMODE_INACTIVE and the LINEOFFERINGMODE_ACTIVE or LINEOFFERINGMODE_INACTIVE values depending on the state of the corresponding call.

This message cannot be disabled.


 LINE_CLOSE

[New - Windows 95]

LINE_CLOSE
dwDevice = (DWORD) hLine;
dwCallbackInstance = (DWORD) hCallback;
dwParam1 = (DWORD) 0;
dwParam2 = (DWORD) 0;
dwParam3 = (DWORD) 0;

Sent when the specified line device has been forcibly closed. The line device handle or any call handles for calls on the line are no longer valid once this message has been sent.

•	No return value.

dwDevice

Specifies a handle to the line device that was closed. This handle is no longer valid.

dwCallbackInstance

Specifies the callback instance supplied when opening the line.

dwParam1

Unused.

dwParam2

Unused.

dwParam3

Unused.

This message is only sent to any application after an open line has been forcibly closed. This may be done to prevent a single application from monopolizing a line device for too long. Whether or not the line can be reopened immediately after a forced close is device-specific.

A line device may also be forcibly closed after the user has modified the configuration of that line or its driver. If the user wants the configuration changes to be effective immediately (as opposed to after the next system restart), and they affect the application's current view of the device (such as a change in device capabilities), then a service provider may forcibly close the line device.


 LINE_CREATE

[New - Windows 95]

dwDevice = (DWORD) 0;
dwCallbackInstance = (DWORD) 0;
dwParam1 = (DWORD) idDevice;
dwParam2 = (DWORD) 0;
dwParam3 = (DWORD) 0;

Sent to inform the application of the creation of a new line device.

•	No return value.

dwDevice

Unused.

dwCallbackInstance

Unused.

dwParam1

Specifies the dwDeviceID of the newly-created device.

dwParam2

Unused.

dwParam3

Unused.

Older applications (which negotiated an API version prior to the creation of this feature) are sent a LINE_LINEDEVSTATE message specifying LINEDEVSTATE_REINIT, which requires them to shut down their use of the API and call lineInitialize again to obtain the new number of devices. Unlike previous versions of TAPI, however, this version does not require all applications to shut down before allowing applications to reinitialize; reinitialization can take place immediately when a new device is created (complete shutdown is still required when a service provider is removed from the system).

Applications supporting this and subsequent versions of the API are sent a LINE_CREATE message. This informs them of the existence of the new device and its new device ID. The application can then choose whether or not to attempt working with the new device at its leisure. This message will be sent to all applications supporting this or subsequent versions of the API which have called lineInitialize, including those that do not have any line devices open at the time.

Although TAPI ordinarily sends the LINE_CREATE message when an application creates a line, it will instead send the LINE_LINEDEVSTATE message with the LINEDEVSTATE_REINIT value set if the application is creating its first line and has not yet called the lineNegotiateAPIVersion or other function to set the API version. In such cases, TAPI assumes that the application is an old version and can not correctly process the LINE_CREATE message.


 LINE_DEVSPECIFIC

[New - Windows 95]

LINE_DEVSPECIFIC
dwDevice = (DWORD) hLineOrCall;
dwCallbackInstance = (DWORD) hCallback;
dwParam1 = (DWORD) DeviceSpecific1;
dwParam2 = (DWORD) DeviceSpecific2;
dwParam3 = (DWORD) DeviceSpecific3;

Sent to notify the application about device-specific events occurring a line, address or call. The meaning of the message and the interpretation of the parameters is device specific.

•	No return value.

dwDevice

Specifies a handle to either a line device or call. This is device specific.

dwCallbackInstance

Specifies the callback instance supplied when opening the line.

dwParam1

Device specific.

dwParam2

Device specific.

dwParam3

Device specific.

This message is used by a service provider in conjunction with the lineDevSpecific function. Its meaning is device specific.


 LINE_DEVSPECIFICFEATURE

[New - Windows 95]

LINE_DEVSPECIFICFEATURE
dwDevice = (DWORD) hLineOrCall;
dwCallbackInstance = (DWORD) hCallback;
dwParam1 = (DWORD) DeviceSpecific1;
dwParam2 = (DWORD) DeviceSpecific2;
dwParam3 = (DWORD) DeviceSpecific3;

Sent to notify the application about device-specific events occurring on a line, address or call. The meaning of the message and the interpretation of the parameters is device specific.

•	No return value.

dwDevice

Specifies a handle to either a line device or call. This is device specific.

dwCallbackInstance

Specifies the callback instance supplied when opening the line.

dwParam1

Device specific.

dwParam2

Device specific.

dwParam3

Device specific.

This message is used by a service provider in conjunction with the lineDevSpecificFeature function. Its meaning is device specific.


 LINE_GATHERDIGITS

[New - Windows 95]

LINE_GATHERDIGITS
dwDevice = (DWORD) hCall;
dwCallbackInstance = (DWORD) hCallback;
dwParam1 = (DWORD) GatherTermination;
dwParam2 = (DWORD) 0;
dwParam3 = (DWORD) 0;

Sent when the current buffered digit-gathering request has terminated or is canceled. The digit buffer may be examined after this message has been received by the application.

•	No return value.

dwDevice

Specifies a handle to the call.

dwCallbackInstance

Specifies the callback instance supplied when opening the line.

dwParam1

Specifies the reason why digit gathering was terminated. This parameter must be one and only one of the following LINEGATHERTERM_ constants:

LINEGATHERTERM_BUFFERFULL

The requested number of digits has been gathered. The buffer is full.

LINEGATHERTERM_TERMDIGIT

One of the termination digits matched a received digit. The matched termination digit is the last digit in the buffer.

LINEGATHERTERM_FIRSTTIMEOUT

The first digit timeout expired. The buffer contains no digits.

LINEGATHERTERM_INTERTIMEOUT

The inter-digit timeout expired. The buffer contains at least one digit.

LINEGATHERTERM_CANCEL

The request was canceled by this application, by another application, or because the call terminated.

dwParam2

Unused.

dwParam3

Unused.

This message is only sent to the application that initiated the digit gathering on the call using lineGatherDigits.

If the lineGatherDigits function is used to cancel a previous request to gather digits, TAPI sends a LINE_GATHERDIGITS message with dwParam1 set to LINEGATHERTERM_CANCEL to the application indicating that originally specified buffer contains the digits gathered up to the cancellation.


 LINE_GENERATE

[New - Windows 95]

LINE_GENERATE
dwDevice = (DWORD) hCall;
dwCallbackInstance = (DWORD) hCallback;
dwParam1 = (DWORD) GenerateTermination;
dwParam2 = (DWORD) 0;
dwParam3 = (DWORD) 0;

Sent to notify the application that the current digit or tone generation has terminated. Note that only one such generation request can be in progress an a given call at any time. This message is also sent when digit or tone generation is canceled.

•	No return value.

dwDevice

Specifies a handle to the call.

dwCallbackInstance

Specifies the callback instance supplied when opening the line.

dwParam1

Specifies the reason why digit or tone generation was terminated. This parameter must be one and only one of the following LINEGENERATETERM_ constants:

LINEGENERATETERM_DONE

The requested number of digits have been generated, or the requested tones have been generated for the requested duration.

LINEGENERATETERM_CANCEL

The digit or tone generation request was canceled by this application, by another application, or because the call terminated.

dwParam2

Unused.

dwParam3

Unused.

This message is only sent to the application that requested the digit or tone generation.


 LINE_LINEDEVSTATE

[New - Windows 95]

LINE_LINEDEVSTATE
dwDevice = (DWORD) hLine;
dwCallbackInstance = (DWORD) hCallback;
dwParam1 = (DWORD) DeviceState;
dwParam2 = (DWORD) DeviceStateDetail1;
dwParam3 = (DWORD) DeviceStateDetail2;

Sent when the state of a line device has changed. The application can invoke lineGetLineDevStatus to determine the new status of the line.

•	No return value.

dwDevice

Specifies a handle to the line device. This parameter is NULL when dwParam1 is LINEDEVSTATE_REINIT.

dwCallbackInstance

Specifies the callback instance supplied when opening the line. If the dwParam1 parameter is LINEDEVSTATE_REINIT, the dwCallbackInstance parameter is not valid and is set to zero.

dwParam1

Specifies the line device status item that has changed. The parameter can be a combination of the following LINEDEVSTATE_ constants:

LINEDEVSTATE_OTHER

Device-status items other than those listed below have changed. The application should check the current device status to determine which items have changed.

LINEDEVSTATE_RINGING

The switch tells the line to alert the user.

LINEDEVSTATE_CONNECTED

The line was previously disconnected and is now connected to TAPI.

LINEDEVSTATE_DISCONNECTED

This line was previously connected and is now disconnected from TAPI.

LINEDEVSTATE_MSGWAITON

The "message waiting" indicator is turned on.

LINEDEVSTATE_MSGWAITOFF

The "message waiting" indicator is turned off.

LINEDEVSTATE_NUMCOMPLETIONS

The number of outstanding call completions on the line device has changed.

LINEDEVSTATE_INSERVICE

The line is connected to TAPI. This happens when TAPI is first activated, or when the line wire is physically plugged in and in service at the switch while TAPI is active.

LINEDEVSTATE_OUTOFSERVICE

The line is out of service at the switch or physically disconnected. TAPI cannot be used to operate on the line device.

LINEDEVSTATE_MAINTENANCE

Mainatenance is being performed on the line at the switch. TAPI cannot be used to operate on the line device.

LINEDEVSTATE_OPEN

The line has been opened by another application.

LINEDEVSTATE_CLOSE

The line has been closed by another application.

LINEDEVSTATE_NUMCALLS

The number of calls on the line device has changed.

LINEDEVSTATE_TERMINALS

The terminal settings have changed.

LINEDEVSTATE_ROAMMODE

The roaming state of the line device has changed.

LINEDEVSTATE_BATTERY

The battery level has changed significantly (cellular).

LINEDEVSTATE_SIGNAL

The signal level has changed significantly (cellular).

LINEDEVSTATE_DEVSPECIFIC

The line's device-specific information has changed.

LINEDEVSTATE_REINIT

Items have changed in the configuration of line devices. To become aware of these changes (as with the appearance of new line devices), the application should reinitialize its use of TAPI. The dwDevice parameter is left NULL for this state change as it applies to any of the lines in the system. This message with the LINEDEVSTATE_REINIT bit set is only sent to applications that have opened a line. That is, if an application has only called lineInitialize but has not yet opened any device, and a LINEDEVSTATE_REINIT message is sent, this message is not sent to that application.

LINEDEVSTATE_LOCK

The locked status of the line device has changed. (For more information, refer to the description of the LINEDEVSTATUSFLAGS_LOCKED bit of the LINEDEVSTATUSFLAGS_ constants.)

LINEDEVSTATE_CAPSCHANGE

Indicates that, due to configuration changes made by the user or other circumstances, one or more of the fields in the LINEDEVCAPS structure for the address have changed. The application should use lineGetDevCaps to read the updated structure.

LINEDEVSTATE_CONFIGCHANGE

Indicates that configuration changes have been made to one or more of the media devices associated with the line device. The application, if it desires, may use lineGetDevConfig to read the updated information.

LINEDEVSTATE_TRANSLATECHANGE

Indicates that, due to configuration changes made by the user or other circumstances, one or more of the fields in the LINETRANSLATECAPS structure have changed. The application should use lineGetTranslateCaps to read the updated structure.

LINEDEVSTATE_COMPLCANCEL

Indicates that the call completion identified by the completion ID contained in parameter dwParam2 of the LINE_LINEDEVSTATE message has been externally cancelled and is no longer considered valid (if that value were to be passed in a subsequent call to lineUncompleteCall, the function would fail with LINEERR_INVALCOMPLETIONID).

dwParam2

The interpretation of this parameter depends on the value of dwParam1. If dwParam1 is LINEDEVSTATE_RINGING, dwParam2 contains the ring mode with which the switch instructs the line to ring. Valid ring modes are numbers in the range one to dwNumRingModes, where dwNumRingModes is a line device capability.

If dwParam1 is LINEDEVSTATE_REINIT, and the message was issued by TAPI as a result of translation of a new API message into a REINIT message, then dwParam2 contains the dwMsg parameter of the original message (e.g., LINE_CREATE or LINE_LINEDEVSTATE). If dwParam2 is zero, this indicates that the REINIT message is a "real" REINIT message that requires the application to call lineShutdown at its earliest convenience.

dwParam3

The interpretation of this parameter depends on the value of dwParam1. If dwParam1 is LINEDEVSTATE_RINGING, dwParam3 contains the ring count for this ring event. The ring count starts at zero.

If dwParam1 is LINEDEVSTATE_REINIT, and the message was issued by TAPI as a result of translation of a new API message into a REINIT message, then dwParam3 contains the dwParam1 parameter of the original message (e.g., LINEDEVSTATE_TRANSLATECHANGE or some other LINEDEVSTATE_ value, if dwParam2 is LINE_LINEDEVSTATE, or the new device ID, if dwParam2 is LINE_CREATE).

The sending of this message can be controlled with lineSetStatusMessages. An application can indicate status item changes about which it wants to be notified. By default, all status reporting will be disabled except for LINEDEVSTATE_REINIT, which cannot be disabled. This message is sent to all applications that have a handle to the line, including those that called lineOpen with the dwPrivileges parameter set to LINECALLPRIVILEGE_NONE, LINECALLPRIVILEGE_OWNER, LINECALLPRIVILEGE_MONITOR, or permitted combinations of these.


 LINE_MONITORDIGITS

[New - Windows 95]

LINE_MONITORDIGITS
dwDevice = (DWORD) hCall;
dwCallbackInstance = (DWORD) hCallback;
dwParam1 = (DWORD) Digit;
dwParam2 = (DWORD) DigitMode;
dwParam3 = (DWORD) 0;

Sent when a digit is detected. The sending of this message is controlled with the lineMonitorDigits function.

•	No return value.

dwDevice

Specifies a handle to the call.

dwCallbackInstance

Specifies the callback instance supplied when opening the call's line.

dwParam1

The low-order byte contains the last digit received in ASCII.

dwParam2

Specifies the digit mode that was detected. This parameter must be one and only one of the following LINEDIGITMODE_ constants:

LINEDIGITMODE_PULSE

Detect digits as audible clicks that are the result of rotary pulse sequences. Valid digits for pulse are '0' through '9'.

LINEDIGITMODE_DTMF

Detect digits as DTMF tones. Valid digits for DTMF are '0' through '9', 'A', 'B', 'C', 'D', '*', and '#'.

LINEDIGITMODE_DTMFEND

Detect and provide application notification of DTMF down edges. Valid digits for DTMF are '0' through '9', 'A', 'B', 'C', 'D', '*', and '#'.

dwParam3

Unused.

This message is sent to the application that has enabled digit monitoring.


 LINE_MONITORMEDIA

[New - Windows 95]

LINE_MONITORMEDIA
dwDevice = (DWORD) hCall;
dwCallbackInstance = (DWORD) hCallback;
dwParam1 = (DWORD) MediaMode;
dwParam2 = (DWORD) 0;
dwParam3 = (DWORD) 0;

Sent when a change in the call's media mode is detected. The sending of this message is controlled with the lineMonitorMedia function.

•	No return value.

dwDevice

Specifies a handle to the call.

dwCallbackInstance

Specifies the callback instance supplied when opening the line.

dwParam1

Specifies the new media mode. This parameter must be one and only one of the following LINEMEDIAMODE_ constants:

LINEMEDIAMODE_INTERACTIVEVOICE

The presence of voice energy has been detected and the call is treated as an interactive call with humans on both ends.

LINEMEDIAMODE_AUTOMATEDVOICE

The presence of voice energy has been detected and the call is locally handled by an automated application.

LINEMEDIAMODE_DATAMODEM

A datamodem session has been detected.

LINEMEDIAMODE_G3FAX

A group 3 fax has been detected.

LINEMEDIAMODE_TDD

A TDD (Telephony Devices for the Deaf) session has been detected.

LINEMEDIAMODE_G4FAX

A group 4 fax has been detected.

LINEMEDIAMODE_DIGITALDATA

Digital data has been detected.

LINEMEDIAMODE_TELETEX

A teletex session has been detected. Teletex is one of the telematic services.

LINEMEDIAMODE_VIDEOTEX

A videotex session has been detected. Videotex is one the telematic services.

LINEMEDIAMODE_TELEX

A telex session has been detected. Telex is one the telematic services.

LINEMEDIAMODE_MIXED

A mixed session has been detected. Mixed is one the telematic services.

LINEMEDIAMODE_ADSI

An ADSI (Analog Display Services Interface) session has been detected.

LINEMEDIAMODE_VOICEVIEW

The media mode of the call is VoiceView.

dwParam2

Unused.

dwParam3

Unused.

This message is sent to the application that has enabled media monitoring for the media mode detected.


 LINE_MONITORTONE

[New - Windows 95]

LINE_MONITORTONE
dwDevice = (DWORD) hCall;
dwCallbackInstance = (DWORD) hCallback;
dwParam1 = (DWORD) dwAppSpecific;
dwParam2 = (DWORD) 0;
dwParam3 = (DWORD) 0;

Sent when a tone is detected. The sending of this message is controlled with the lineMonitorTones function.

•	No return value.

dwDevice

Specifies a handle to the call.

dwCallbackInstance

Specifies the callback instance supplied when opening the call's line.

dwParam1

Specifies the application-specific dwAppSpecific field of the LINEMONITORTONE structure for the tone that was detected.

dwParam2

Unused.

dwParam3

Unused.

This message is only sent to the application that has requested the tone be monitored.


 LINE_REPLY

[New - Windows 95]

LINE_REPLY
dwDevice = (DWORD) 0;
dwCallbackInstance = (DWORD) hCallback;
dwParam1 = (DWORD) idRequest;
dwParam2 = (DWORD) Status;
dwParam3 = (DWORD) 0;

Sent to report the results of function calls that completed asynchronously.

•	No return value.

dwDevice

Not used.

dwCallbackInstance

Returns the application's callback instance.

dwParam1

Specifies the request ID for which this is the reply.

dwParam2

Specifies the success or error indication. The application should cast this parameter into a LONG. Zero indicates success; a negative number indicates an error.

dwParam3

Unused.

Functions that operate asynchronously return a positive request ID value to the application. This request ID is returned with the reply message to identify the request that was completed. The other parameter for this message carries the success or failure indication. Possible errors are the same as those defined by the corresponding function. This message cannot be disabled.

In some cases, an application may fail to receive the LINE_REPLY message corresponding to a call to an asynchronous function. This occurs if the corresponding call handle is deallocated before the message has been received.


 LINE_REQUEST

[New - Windows 95]

LINE_REQUEST
dwDevice = (DWORD) 0;
dwCallbackInstance = (DWORD) hRegistration;
dwParam1 = (DWORD) RequestMode;
dwParam2 = (DWORD) RequestModeDetail1;
dwParam3 = (DWORD) RequestModeDetail2;

Sent report the arrival of a new request from another application.

•	No return value.

dwDevice

Not used.

dwCallbackInstance

Specifies the registration instance of the application specified on lineRegisterRequestRecipient.

dwParam1

Specifies the request mode of the newly pending request. This parameter uses the following LINEREQUESTMODE_ constants:

LINEREQUESTMODE_MAKECALL

A tapiRequestMakeCall request.

dwParam2

If dwParam1 is set to LINEREQUESTMODE_DROP, dwParam2 contains the hWnd of the application requesting the drop. Otherwise, dwParam2 is unused.

dwParam3

If dwParam1 is set to LINEREQUESTMODE_DROP, the low-order word of dwParam3 contains the wRequestID as specified by the application requesting the drop. Otherwise, dwParam3 is unused.

This message is sent to the highest priority application that has registered for the corresponding request mode. This callback message indicates the arrival of an Assisted Telephony request of the specified request mode. If dwParam1 is LINEREQUESTMODE_MAKECALL or LINEREQUESTMODE_MEDIACALL, the application can invoke lineGetRequest using the corresponding request mode to receive the request. If dwParam1 is LINEREQUESTMODE_DROP, the message contains all of the information the request recipient needs in order to perform the request.


 Line Device Structures

About Line Device Structures

This chapter describes the data structures used by the Telephony API. They are listed in alphabetical order.


 Memory Allocation

Memory for all data structures used by the API must be allocated by the application. The application passes a pointer to the API function that returns the information and the function fills the data structure with the requested information. If the operation is asynchonous, then the information is not available until the asynchonous reply message indicates success.

All data structures used to pass information between the application and the Telephony API are "flattened." This means that data structures do not contain pointers to substructures that contain variably sized components of information. Instead, data structures that are used to pass variable amounts of information back to the application have the following meta structure:

  DWORD  dwTotalSize;
  DWORD  dwNeededSize;
  DWORD  dwUsedSize;

    <fixed size fields>

  DWORD  dw<VarSizeField1>Size;
  DWORD  dw<VarSizeField1>Offset;

    <fixed size fields>

  DWORD  dw<VarSizeField2>Size;
  DWORD  dw<VarSizeField2>Offset;

    <common extensions>

    <var sized field1>

    <var sized field2>

The dwTotalSize field is the size in bytes allocated to this data structure. It marks the end of the data structure and is set by the application before it invokes the function that uses this data structure. The function will not read or write beyond this size. An application must set the dwTotalSize field to indicate the total number of bytes allocated for TAPI.DLL to return the contents of the structure.

The dwNeededSize field is filled in by TAPI.DLL. It indicates how many bytes are needed to return all the information requested. The existence of variably sized fields often makes it impossible for the application to estimate the data structure size it needs to allocate. This field simply returns the number of bytes actually needed for the infomation. This number could be smaller than, equal to, or larger than dwTotalSize, and it includes space for the dwTotalSize field itself. If larger, the returned structure is only partially filled. If the fields the application is interested in are available in the partial structure, nothing else must be done. Otherwise, the application should allocate a structure at least the size of dwNeededSize and invoke the function again. Usually, enough space will be available this time to return all the information, although it is possible the size could have increased again.

The dwUsedSize field is filled in by TAPI if it returns information to the application to indicate the actual size in bytes of the portion of the data structure that contains useful information. If, for example, a structure was allocated too small and the truncated field is a variably sized field, dwNeededSize will be larger than dwTotalSize, and the truncated field will be left empty. The dwUsedSize field could therefore be smaller than dwTotalSize. Partial field values are not returned.

Following this header is the fixed part of the data structure. It contains regular fields and size/offset pairs that describe the actual variably sized fields. The offset field contains the offset in bytes of the variably sized field from the beginning of the record. The size field contains the size in bytes of the variably sized field. If a variably sized field is empty, then the size field is zero and the offset is set to zero. Variably sized field that would be truncated if the total structure size is insufficient are left empty. That is, their size field is set to zero and the offset is set to zero. The variably sized fields follow the fixed fields.


 Variably Sized Data Structures

When variably sized data structures are used to transmit information between TAPI.DLL and the application, the application is responsible for allocating the necessary memory. The amount of memory allocated must be at least large enough for the fixed portion of the data structure, and is set by the application in the dwTotalSize field of the data structure. The dwUsedSize and dwNeededSize fields are filled in by TAPI.DLL. If dwTotalSize is less than the size of the fixed portion, then  LINEERR/ PHONEERR_STRUCTURETOOSMALL is returned. If a function returns success, then all the fields in the fixed portion have been filled in. dwUsedSize and dwNeededSize can be compared to determine if all variable parts have been filled in, and how much space would be required to fill them all in.

If dwNeededSize is equal to dwUsedSize, then all fixed and variable parts have been filled in. If dwNeededSize is larger than dwUsedSize, some variable parts may have been filled in, but exactly which variably sized fields have been filled in is undefined. No variable part is ever truncated, and variable parts that would have been truncated due to insufficient space are indicated by having both of their corresponding "Offset" and "Size" parts set to zero. If these are not both zero (and no error was returned), they indicate the offset and size of valid, non-truncated variable-part data.

An application can always guarantee that all variable parts are filled in by allocating and indicating dwNeededSize bytes for the structure and calling the "Get" function again until the function returns success and dwNeededSize "covers" dwUsedSize. This should happen on the second try except for race conditions that cause changes in the size of variable parts between calls, which should be a rare occurrence.

Note  All ASCII, DBCS, and Unicode strings that occur in variable-sized structures should be NULL-terminated according to normal C string handling conventions.


 Extensibility

Provisions are made for extending constants and structures both in a device-independent way and in a device-specific (vendor-specific) way. In constants that are scalar enumerations, a range of values is reserved for future common extensions. The remainder of values are identified as device specific. A vendor can define meanings for these values in any way desired. Their interpretation is keyed to the extension ID provided in the LINEDEVCAPS data structure. For constants that are defined as bit flags, a range of low-order bits are reserved, where the high-order bits can be extension specific. It is recommended that extended values and bit arrays use bits from the highest value or high-order bit down. This leaves the option to move the border between the common portion and extension portion if there is a need to do so in the future. Extensions to data structures are assigned a variably sized field with size/offset being part of the fixed part. TAPI describes for each data structures what device-specific extensions are allowed.

In addition to recognizing a specific extension ID, the application must negotiate the extension version number that the application and the service provider will operate under. This is done in the second version negotiation phase of the lineGetDevCaps function.

An extension ID is a globally unique identifier. There is no central registry for extension IDs. Instead, they are generated locally by the manufacturer by a utility that is available with the toolkit. The number is made up of parts such as a unique LAN address, time of day, and random number, to guarantee global uniqueness. Globally Unique Identifiers are designed to be distinguishable from HP/DEC universally unique identifiers and are thus fully compatible with them.


 Reference

Following are the Telephony API structures.


 LINEADDRESSCAPS

[New - Windows 95]

typedef struct lineaddresscaps_tag {
  DWORD  dwTotalSize;
  DWORD  dwNeededSize;
  DWORD  dwUsedSize;

  DWORD  dwLineDeviceID;

  DWORD  dwAddressSize;
  DWORD  dwAddressOffset;

  DWORD  dwDevSpecificSize;
  DWORD  dwDevSpecificOffset;

  DWORD  dwAddressSharing;
  DWORD  dwAddressStates;
  DWORD  dwCallInfoStates;
  DWORD  dwCallerIDFlags;
  DWORD  dwCalledIDFlags;
  DWORD  dwConnectedIDFlags;
  DWORD  dwRedirectionIDFlags;
  DWORD  dwRedirectingIDFlags;
  DWORD  dwCallStates;
  DWORD  dwDialToneModes;
  DWORD  dwBusyModes;
  DWORD  dwSpecialInfo;
  DWORD  dwDisconnectModes;

  DWORD  dwMaxNumActiveCalls;
  DWORD  dwMaxNumOnHoldCalls;
  DWORD  dwMaxNumOnHoldPendingCalls;
  DWORD  dwMaxNumConference;
  DWORD  dwMaxNumTransConf;

  DWORD  dwAddrCapFlags;
  DWORD  dwCallFeatures;
  DWORD  dwRemoveFromConfCaps;
  DWORD  dwRemoveFromConfState;
  DWORD  dwTransferModes;
  DWORD  dwParkModes;

  DWORD  dwForwardModes;
  DWORD  dwMaxForwardEntries;
  DWORD  dwMaxSpecificEntries;
  DWORD  dwMinFwdNumRings;
  DWORD  dwMaxFwdNumRings;

  DWORD  dwMaxCallCompletions;
  DWORD  dwCallCompletionConds;
  DWORD  dwCallCompletionModes;
  DWORD  dwNumCompletionMessages;
  DWORD  dwCompletionMsgTextEntrySize;
  DWORD  dwCompletionMsgTextSize;
  DWORD  dwCompletionMsgTextOffset;
  DWORD  dwAddressFeatures;
} LINEADDRESSCAPS, FAR *LPLINEADDRESSCAPS;

The LINEADDRESSCAPS structure describes the capabilities of a specified address.

dwTotalSize

The total size in bytes allocated to this data structure.

dwNeededSize

The size in bytes for this data structure that is needed to hold all the returned information.

dwUsedSize

The size in bytes of the portion of this data structure that contains useful information.

dwLineDeviceID

Specifies the device ID of the line device with which this address is associated.

dwAddressSize
dwAddressOffset

The size in bytes of the variably sized address field and the offset in bytes from the beginning of this data structure.

dwDevSpecificSize
dwDevSpecificOffset

The size in bytes of the variably sized device-specific field and the offset in bytes from the beginning of this data structure.

dwAddressSharing

Specifies the sharing mode of the address. Values are:

LINEADDRESSSHARING_PRIVATE

An address with private sharing mode is only assigned to a single line or station.

LINEADDRESSSHARING_BRIDGEDEXCL

An address with a bridged-exclusive sharing mode is assigned to one or more other lines or stations. The exclusive portion refers to the fact that only one of the bridged parties can be connected with a remote party at any given time.

LINEADDRESSSHARING_BRIDGEDNEW

An address with a bridged-new sharing mode is assigned to one or more other lines or stations. The new portion refers to the fact that activities by the different bridged parties result in the creation of new calls on the address.

LINEADDRESSSHARING_BRIDGEDSHARED

An address with a bridged-shared sharing mode is also assigned to one or more other lines or stations. The shared portion refers to the fact that if one of the bridged parties is connected with a remote party, the remaining bridged parties can share in the conversation (as in a conference) by activating that call appearance.

LINEADDRESSSHARING_MONITORED

An address with a monitored address mode simply monitors the status of that address. The status is either idle or in use. The message LINE_ADDRESSSTATE notifies the application about these changes.

dwAddressStates

This field contains the address states changes for which the application may get notified in the LINE_ADDRESSSTATE callback message. It uses the following LINEADDRESSSTATE_ constants:

LINEADDRESSSTATE_OTHER

Address-status items other than those listed below have changed. The application should check the current address status to determine which items have changed.

LINEADDRESSSTATE_DEVSPECIFIC

The device-specific item of the address status has changed.

LINEADDRESSSTATE_INUSEZERO

The address has changed to idle (it is not in use by any stations).

LINEADDRESSSTATE_INUSEONE

The address has changed from being idle or from being in use by many bridged stations to being in use by just one station.

LINEADDRESSSTATE_INUSEMANY

The monitored or bridged address has changed to being in use by one station to being used by more than one station.

LINEADDRESSSTATE_NUMCALLS

The number of calls on the address has changed. This is the result of events such as a new inbound call, an outbound call on the address, or a call changing its hold status.

LINEADDRESSSTATE_FORWARD

The forwarding status of the address has changed, including the number of rings for determining a "no answer" condition. The application should check the address status to retrieve details about the address's current forwarding status.

LINEADDRESSSTATE_TERMINALS

The terminal settings for the address have changed.

LINEADDRESSSTATE_CAPSCHANGE

Indicates that, due to configuration changes made by the user or other circumstances, one or more of the fields in the LINEADDRESSCAPS structure for the address have changed. The application should use lineGetAddressCaps to read the updated structure. If a service provider sends a LINE_ADDRESSSTATE message containing this value to TAPI, TAPI will pass it along to applications which have negotiated this or a subsequent API version; applications negotiating a previous API version will receive LINE_LINEDEVSTATE messages specifying LINEDEVSTATE_REINIT, requiring them to shutdown and reinitialize their connection to TAPI in order to obtain the updated information.

dwCallInfoStates

This field describes the call information elements that are meaningful for all calls on this address. An application may get notified about changes in some of these states in LINE_CALLINFO messages. It uses the following LINECALLINFOSTATE_ constants:

LINECALLINFOSTATE_OTHER

Call-information items other than those listed below have changed. The application should check the current call information to determine which items have changed.

LINECALLINFOSTATE_DEVSPECIFIC

The device-specific field of the call-information.

LINECALLINFOSTATE_BEARERMODE

The bearer mode field of the call-information record.

LINECALLINFOSTATE_RATE

The rate field of the call-information record.

LINECALLINFOSTATE_MEDIAMODE

The media-mode field of the call-information record.

LINECALLINFOSTATE_APPSPECIFIC

The application-specific field of the call-information record.

LINECALLINFOSTATE_CALLID

The call ID field of the call-information record.

LINECALLINFOSTATE_RELATEDCALLID

The related call ID field of the call-information record.

LINECALLINFOSTATE_ORIGIN

The origin field of the call-information record.

LINECALLINFOSTATE_REASON

The reason field of the call-information record.

LINECALLINFOSTATE_COMPLETIONID

The completion ID field of the call-information record.

LINECALLINFOSTATE_NUMOWNERINCR

The number of owner field in the call-information record was increased.

LINECALLINFOSTATE_NUMOWNERDECR

The number of owner field in the call-information record was decreased.

LINECALLINFOSTATE_NUMMONITORS

The number of monitors field in the call-information record has changed.

LINECALLINFOSTATE_TRUNK

The trunk field of the call-information record has changed.

LINECALLINFOSTATE_CALLERID

One of the callerID-related fields of the call-information record has changed.

LINECALLINFOSTATE_CALLEDID

One of the calledID-related fields of the call-information record has changed.

LINECALLINFOSTATE_CONNECTEDID

One of the connectedID-related fields of the call-information record has changed.

LINECALLINFOSTATE_REDIRECTIONID

One of the redirectionID-related fields of the call-information record has changed.

LINECALLINFOSTATE_REDIRECTINGID

One of the redirectingID-related fields of the call-information record has changed.

LINECALLINFOSTATE_DISPLAY

The display field of the call-information record.

LINECALLINFOSTATE_USERUSERINFO

The user-to-user information of the call-information record.

LINECALLINFOSTATE_HIGHLEVELCOMP

The high-level compatibility field of the call-information record.

LINECALLINFOSTATE_LOWLEVELCOMP

The low-level compatibility field of the call-information record.

LINECALLINFOSTATE_CHARGINGINFO

The charging information of the call-information record.

LINECALLINFOSTATE_TERMINAL

The terminal mode information of the call-information record.

LINECALLINFOSTATE_DIALPARAMS

The dial parameters of the call-information record.

LINECALLINFOSTATE_MONITORMODES

One or more of the digit, tone, or media monitoring fields in the call-information record has changed.

dwCallerIDFlags
dwCalledIDFlags
dwConnectedIDFlags
dwRedirectionIDFlags
dwRedirectingIDFlags

These fields describe the various party ID information types that may be provided for calls on this address. It uses the following LINECALLPARTYID_ constants:

LINECALLPARTYID_BLOCKED

Caller ID information for the call has been blocked by the caller but would otherwise have been available.

LINECALLPARTYID_OUTOFAREA

Caller ID information for the call is not available since it is not propagated all the way by the network.

LINECALLPARTYID_NAME

The caller ID information for the call is the caller's name (from a table maintained inside the switch). It is provided in the caller ID name variably sized field.

LINECALLPARTYID_ADDRESS

The caller ID information for the call is the caller's number and is provided in the caller ID variably sized field.

LINECALLPARTYID_PARTIAL

Caller ID information for the call is valid but is limited to partial number information.

LINECALLPARTYID_UNKNOWN

Caller ID information is currently unknown; it may become known later.

LINECALLPARTYID_UNAVAIL

Caller ID information is unavailable and will not become known later.

dwCallStates

This field describes the various call states that can possibly be reported for calls on this address. This parameter uses the following LINECALLSTATE_ constants:

LINECALLSTATE_IDLE

The call is idle—no call exists.

LINECALLSTATE_OFFERING

The call is being offered to the station, signaling the arrival of a new call. In some environments, a call in the offering state does not automatically alert the user; alerting is done by the switch instructing the line to ring. It does not affect any call states.

LINECALLSTATE_ACCEPTED

The call was offering and has been accepted. This indicates to other (monitoring) applications that the current owner application has claimed responsibility for answering the call. In ISDN, this also initiates alerting to both parties.

LINECALLSTATE_DIALTONE

The call is receiving a dial tone from the switch, which means that the switch is ready to receive a dialed number.

LINECALLSTATE_DIALING

Destination address information (a phone number) is being sent to the switch over the call. Note that the operation lineGenerateDigits does not place the line into the dialing state.

LINECALLSTATE_RINGBACK

The call is receiving ringback from the called address. Ringback indicates that the other station has been reached and is being alerted.

LINECALLSTATE_BUSY

The call is receiving a busy tone. Busy tone indicates that the call cannot be completed—either a circuit (trunk) or the remote party's station are in use.

LINECALLSTATE_SPECIALINFO

Special information is sent by the network. Special information is typically sent when the destination cannot be reached.

LINECALLSTATE_CONNECTED

The call has been established and the connection is made. Information is able to flow over the call between the originating address and the destination address.

LINECALLSTATE_PROCEEDING

Dialing has completed and the call is proceeding through the switch or telephone network.

LINECALLSTATE_ONHOLD

The call is on hold by the switch.

LINECALLSTATE_CONFERENCED

The call is currently a member of a multiparty conference call.

LINECALLSTATE_ONHOLDPENDCONF

The call is currently on hold while it is being added to a conference.

LINECALLSTATE_ONHOLDPENDTRANSF

The call is currently on hold awaiting transfer to another number.

LINECALLSTATE_DISCONNECTED

The remote party has disconnected from the call.

LINECALLSTATE_UNKNOWN

The state of the call is not known. This may be due to limitations of the call progress detection implementation.

dwDialToneModes

This field describes the various dialtone modes that can possibly be reported for calls made on this address. This field is meaningful only if the dialtone call state can be reported. It uses the following LINEDIALTONEMODE_ constants:

LINEDIALTONEMODE_NORMAL

This is a "normal" dialtone which typically is a continuous tone.

LINEDIALTONEMODE_SPECIAL

This is a special dialtone indicating a certain condition is currently in effect.

LINEDIALTONEMODE_INTERNAL

This is an internal dialtone, as within a PBX.

LINEDIALTONEMODE_EXTERNAL

This is an external (public network) dialtone.

LINEDIALTONEMODE_UNKNOWN

The dialtone mode is currently unknown but may become known later.

LINEDIALTONEMODE_UNAVAIL

The dialtone mode is unavailable and will not become known.

wBusyModes

This field describes the various busy modes that can possibly be reported for calls made on this address. This field is meaningful only if the busy call state can be reported. It uses the following LINEBUSYMODE_ constants:

LINEBUSYMODE_STATION

The busy signal indicates that the called party's station is busy. This is usually signaled with a "normal" busy tone.

LINEBUSYMODE_TRUNK

The busy signal indicates that a trunk or circuit is busy. This is usually signaled with a "long" busy tone.

LINEBUSYMODE_UNKNOWN

The busy signal's specific mode is currently unknown but may become known later.

LINEBUSYMODE_UNAVAIL

The busy signal's specific mode is unavailable and will not become known.

dwSpecialInfo

This field describes the various special information types that can possibly be reported for calls made on this address. This field is meaningful only if the specialInfo call state can be reported. It uses the following LINESPECIALINFO_ constants:

LINESPECIALINFO_NOCIRCUIT

This special information tone preceeds a no circuit or emergency announcement (trunk blockage category).

LINESPECIALINFO_CUSTIRREG

This special information tone preceeds a vacant number, AIS, Centrex (™)  number change and nonworking station, access code not dialed or dialed in error, manual intercept operator message (customer irregularity category).

LINESPECIALINFO_REORDER

This special information tone preceeds a reorder announcement (equipment irregularity category).

LINESPECIALINFO_UNKNOWN

Specifics about the special information tone are currently unknown but may become known later.

LINESPECIALINFO_UNAVAIL

Specifics about the special information tone are unavailable and will not become known.

dwDisconnectModes

This field describes the various disconnect modes that can possibly be reported for calls made on this address. This field is meaningful only if the disconnected call state can be reported. It uses the following LINEDISCONNECTMODE_ constants:

LINEDISCONNECTMODE_NORMAL

This is a "normal" disconnect request by the remote party; the call was terminated normally.

LINEDISCONNECTMODE_UNKNOWN

The reason for the disconnect request is unknown.

LINEDISCONNECTMODE_REJECT

The remote user has rejected the call.

LINEDISCONNECTMODE_PICKUP

The call was picked up from elsewhere.

LINEDISCONNECTMODE_FORWARDED

The call was forwarded by the switch.

LINEDISCONNECTMODE_BUSY

The remote user's station is busy.

LINEDISCONNECTMODE_NOANSWER

The remote user's station does not answer.

LINEDISCONNECTMODE_BADADDRESS

The destination address in invalid.

LINEDISCONNECTMODE_UNREACHABLE

The remote user could not be reached.

LINEDISCONNECTMODE_CONGESTION

The network is congested.

LINEDISCONNECTMODE_INCOMPATIBLE

The remote user's station equipment is incompatible with the type of call requested.

LINEDISCONNECTMODE_UNAVAIL

The reason for the disconnect is unavailable and will not become known later.

dwMaxNumActiveCalls

This field contains the maximum number of active call appearances that the address can handle. This number does not include calls on hold or calls on hold pending transfer or conference.

dwMaxNumOnHoldCalls

This field contains the maximum number of call appearances at the address that can be on hold.

dwMaxNumOnHoldPendingCalls

This field contains the maximum number of call appearances at the address that can be on hold pending transfer or conference.

dwMaxNumConference

This field contains the maximum number of parties that can be conferenced in a single conference call on this address.

dwMaxNumTransConf

This field specifies the number of parties (including "self") that can be added in a conference call that is initiated as a generic consultation call using lineSetupTransfer.

dwAddrCapFlags

This field contains a series of packed bit flags that describe a variety of address capabilities. It uses the following LINEADDRCAPFLAGS_ constants:

LINEADDRCAPFLAGS_FWDNUMRINGS

Specifies whether the number of rings for a "no answer" can be specified when forwarding calls on no answer.

LINEADDRCAPFLAGS_PICKUPGROUPID

Specifies whether or not a group ID is required for call pickup.

LINEADDRCAPFLAGS_SECURE

Specifies whether or not calls on this address can be made secure at call-setup time.

LINEADDRCAPFLAGS_BLOCKIDDEFAULT

Specifies whether the network by default sends or blocks caller ID information when making a call on this address. If TRUE, ID information is blocked by default; if FALSE, ID information is transmitted by default.

LINEADDRCAPFLAGS_BLOCKIDOVERRIDE

Specifies whether the default setting for sending or blocking of caller ID information can be overridden per call. If TRUE, override is possible; if FALSE, override is not possible.

LINEADDRCAPFLAGS_DIALED

Specifies whether an destination address can be dialed on this address for making a call. TRUE if a destination address must be dialed; FALSE if the destination address is fixed (as with a "hot phone").

LINEADDRCAPFLAGS_ORIGOFFHOOK

Specifies whether the originating party's phone can automatically be taken offhook when making calls.

LINEADDRCAPFLAGS_DESTOFFHOOK

Specifies whether the called party's phone can automatically be forced offhook when making calls.

LINEADDRCAPFLAGS_FWDCONSULT

Specifies whether call forwarding involves the establishment of a consultation call.

LINEADDRCAPFLAGS_SETUPCONFNULL

Specifies whether setting up a conference call starts out with an initial call (FALSE) or with no initial call (TRUE).

LINEADDRCAPFLAGS_AUTORECONNECT

Specifies whether dropping a consultation call automatically reconnects to the call on consultation hold. TRUE if reconnect happens automatically; otherwise, FALSE.

LINEADDRCAPFLAGS_COMPLETIONID

Specifies whether the completion IDs returned by lineCompleteCall are useful and unique. TRUE is useful; otherwise, FALSE.

LINEADDRCAPFLAGS_TRANSFERHELD

Specifies whether a (hard) held call can be transferred. Often, only calls on consultation hold may be able to be transferred.

LINEADDRCAPFLAGS_CONFERENCEHELD

Specifies whether a (hard) held call can be conferenced to. Often, only calls on consultation hold may be able to be added to as a conference call.

LINEADDRCAPFLAGS_ PARTIALDIAL

Specifies whether partial dialing is available.

LINEADDRCAPFLAGS_FWDSTATUSVALID

Specifies whether the forwarding status in the LINEADDRESSSTATUS structure for this address is valid.

LINEADDRCAPFLAGS_ FWDINTEXTADDR

Specifies whether internal and external calls can be forwarded to different forwarding addresses. This flag is meaningful only if forwarding of internal and external calls can be controlled separately. It is TRUE if internal and external calls can be forwarded to different destination addresses; otherwise, FALSE.

LINEADDRCAPFLAGS_ FWDBUSYNAADDR

Specifies whether call forwarding for busy and for no answer can use different forwarding addresses. This flag is meaningful only if forwarding for busy and for no answer can be controlled separately. It is TRUE if forwarding for busy and for no answer can use different destination addresses; otherwise, FALSE.

LINEADDRCAPFLAGS_ACCEPTTOALERT

TRUE if an offering call must be accepted using lineAccept in order to start alerting the users at both ends of the call; otherwise, FALSE. Typically, this is only used with ISDN.

LINEADDRCAPFLAGS_CONFDROP

TRUE if invoking lineDrop on a conference call parent also has the side effect of dropping (disconnecting) the other parties involved in the conference call; FALSE if dropping a conference call still allows the other parties to talk among themselves.

LINEADDRCAPFLAGS_ PICKUPCALLWAIT

TRUE if linePickup can be used to pickup a call detected by the user as a "call waiting" call; otherwise FALSE.

dwCallFeatures

This field specifies the switching capabilities or features available for all calls on this address using the LINECALLFEATURE_ constants. This member represents the call-related features which may possibly be available on an address (static availability as opposed to dynamic availability). Invoking a supported feature requires the call to be in the proper state and the underlying line device to be opened in a compatible mode. A zero in a bit position indicates that the corresponding feature is never available. A one indicates that the corresponding feature may be available if the application has the right privileges to the call and the call is in the appropriate state for the operation to be meaningful. This field allows an aplication to discover which call features can be (and which can never be) supported by the address.

dwRemoveFromConfCaps

This field specifies the address's capabilities for removing calls from a conference call. It uses the following LINEREMOVEFROMCONF_ constants:

LINEREMOVEFROMCONF_NONE

Parties cannot be removed from the conference call.

LINEREMOVEFROMCONF_LAST

Only the most recently added party can be removed from the conference call.

LINEREMOVEFROMCONF_ANY

Any participating party can be removed from the conference call.

dwRemoveFromConfState

This field uses the LINECALLSTATE_ constants to specify the state of the call after it has been removed from a conference call.

dwTransferModes

This field specifies the address's capabilities for resolving transfer requests. It uses the following LINETRANSFERMODE_ constants:

LINETRANSFERMODE_TRANSFER

Resolve the initiated transfer by transferring the initial call to the consultation call.

LINETRANSFERMODE_CONFERENCE

Resolve the initiated transfer by conferencing all three parties into a three-way conference call. A conference call is created and returned to the application.

dwParkModes

This field specifies the different call park modes available at this address. It uses the LINEPARKMODE_ constants:

LINEPARKMODE_DIRECTED

Specifies directed call park. The address where the call is to be parked must be supplied to the switch.

LINEPARKMODE_NONDIRECTED

Specifies nondirected call park. The address where the call is parked is selected by the switch and provided by the switch to the application.

dwForwardModes

This field specifies the different modes of forwarding available for this address. It uses the following LINEFORWARDMODE_ constants:

LINEFORWARDMODE_UNCOND

Forward all calls unconditionally, irrespective of their origin. Use this value when unconditional forwarding for internal and external calls cannot be controlled separately. Unconditional forwarding overrides forwarding on busy and/or no answer conditions.

LINEFORWARDMODE_UNCONDINTERNAL

Forward all internal calls unconditionally. Use this value when unconditional forwarding for internal and external calls can be controlled separately.

LINEFORWARDMODE_UNCONDEXTERNAL

Forward all external calls unconditionally. Use this value when unconditional forwarding for internal and external calls can be controlled separately.

LINEFORWARDMODE_UNCONDSPECIFIC

Forward all calls that originated at a specified address unconditionally (selective call forwarding).

LINEFORWARDMODE_BUSY

Forward all calls on busy, irrespective of their origin. Use this value when forwarding for internal and external calls on busy and on no answer cannot be controlled separately.

LINEFORWARDMODE_BUSYINTERNAL

Forward all internal calls on busy. Use this value when forwarding for internal and external calls on busy and on no answer can be controlled separately.

LINEFORWARDMODE_BUSYEXTERNAL

Forward all external calls on busy. Use this value when forwarding for internal and external calls on busy and on no answer can be controlled separately.

LINEFORWARDMODE_BUSYSPECIFIC

Forward all calls that originated at a specified address on busy (selective call forwarding).

LINEFORWARDMODE_NOANSW

Forward all calls on no answer, irrespective of their origin. Use this value when call forwarding for internal and external calls on no answer cannot be controlled separately.

LINEFORWARDMODE_NOANSWINTERNAL

Forward all internal calls on no answer. Use this value when forwarding for internal and external calls on no answer can be controlled separately.

LINEFORWARDMODE_NOANSWEXTERNAL

Forward all external calls on no answer. Use this value when forwarding for internal and external calls on no answer can be controlled separately.

LINEFORWARDMODE_NOANSWSPECIFIC

Forward all calls that originated at a specified address on no answer (selective call forwarding).

LINEFORWARDMODE_BUSYNA

Forward all calls on busy/no answer, irrespective of their origin. Use this value when forwarding for internal and external calls on busy and on no answer cannot be controlled separately.

LINEFORWARDMODE_BUSYNAINTERNAL

Forward all internal calls on busy/no answer. Use this value when call forwarding on busy and on no answer cannot be controlled separately for internal calls.

LINEFORWARDMODE_BUSYNAEXTERNAL

Forward all external calls on busy/no answer. Use this value when call forwarding on busy and on no answer cannot be controlled separately for internal calls.

LINEFORWARDMODE_BUSYNASPECIFIC

Forward all calls that originated at a specified address on busy/no answer (selective call forwarding).

dwMaxForwardEntries

Specifies the maximum number of entries that can be passed to lineForward in the lpForwardList parameter.

dwMaxSpecificEntries

Specifies the maximum number of entries in the lpForwardList parameter passed to lineForward that can contain forwarding instructions based on a specific caller ID (selective call forwarding). This field is zero if selective call forwarding is not supported.

dwMinFwdNumRings

Specifies the minimum number of rings that can be set to determine when a call is officially considered "no answer."

dwMaxFwdNumRings

Specifies the maximum number of rings that can be set to determine when a call is officially considered "no answer." If this number of rings cannot be set, then dwMinFwdNumRings and dwMaxNumRings will be equal.

dwMaxCallCompletions

Specifies the maximum number of concurrent call completion requests that can be outstanding on this line device. Zero implies that call completion is not available.

dwCallCompletionCond

Specifies the different call conditions under which call completion can be requested. This field uses the following  LINECALLCOMPLCOND_ constants:

LINECALLCOMPLCOND_BUSY

Complete the call under the busy condition.

LINECALLCOMPLCOND_NOANSWER

Complete the call under the ringback no answer condition.

dwCallCompletionModes

Specifies the way in which the call can be completed. This field uses the following LINECALLCOMPLCOND_ constants:

LINECALLCOMPLMODE_CAMPON

Queues the call until the call can be completed.

LINECALLCOMPLMODE_CALLBACK

Requests the called station to return the call when it returns to idle.

LINECALLCOMPLMODE_INTRUDE

Adds the application to the existing call at the called station if busy (barge in).

LINECALLCOMPLMODE_MESSAGE

Leave a short predefined message for the called station (Leave Word Calling). A specific message can be identified.

dwNumCompletionMessages

Specifies the number of call completion messages that can be selected from when using the LINECALLCOMPLMODE_MESSAGE option. Individual messages are identified by values in the range 0 through one less than dwNumCompletionMessages.

dwCompletionMsgTextEntrySize

Specifies the size in bytes of each of the call completion text descriptions pointed at by dwCompletionMsgTextSize/Offset.

dwCompletionMsgTextSize
dwCompletionMsgTextOffset

The size in bytes and the offset in bytes from the beginning of this data structure of the variably sized field containing descriptive text about each of the call completion messages. Each message is dwCompletionMsgTextEntrySize bytes long. The string format of these textual descriptions is indicated by dwStringFormat in the line's device capabilities.

dwAddressFeatures

This field specifies the features available for this address using the LINEADDRFEATURE_ constants. Invoking a supported feature requires the address to be in the proper state and the underlying line device to be opened in a compatible mode. A zero in a bit position indicates that the corresponding feature is never available. A one indicates that the corresponding feature may be available if the address is in the appropriate state for the operation to be meaningful. This field allows an application to discover which address features can be (and which can never be) supported by the address.

Device-specific extensions should use the DevSpecific (dwDevSpecificSize and dwDevSpecificOffset) variably sized area of this data structure.

Older applications will have been compiled without this field in the LINEADDRESSCAPS structure, and using a SIZEOF LINEADDRESSCAPS smaller than the new size. The application passes in a dwAPIVersion parameter with the lineGetAddressCaps function, which can be used for guidance by TAPI in handling this situation. If the application passes in a dwTotalSize less than the size of the fixed portion of the structure as defined in the dwAPIVersion specified, LINEERR_STRUCTURETOOSMALL will be returned. If sufficient memory has been allocated by the application, before calling TSPI_lineGetAddressCaps, TAPI will set the dwNeededSize and dwUsedSize fields to the fixed size of the structure as it existed in the specified API version.

New service providers (which support the new API version) must examine the API version passed in. If the API version is less than the highest version supported by the provider, the service provider must not fill in fields not supported in older API versions, as these would fall in the variable portion of the older structure.

New applications must be cognizant of the API version negotiated, and not examine the contents of fields in the fixed portion beyond the original end of the fixed portion of the structure for the negotiated API version.


 LINEADDRESSSTATUS

[New - Windows 95]

typedef struct lineaddressstatus_tag {
  DWORD  dwTotalSize;
  DWORD  dwNeededSize;
  DWORD  dwUsedSize;

  DWORD  dwNumInUse;
  DWORD  dwNumActiveCalls;
  DWORD  dwNumOnHoldCalls;
  DWORD  dwNumOnHoldPendCalls;
  DWORD  dwAddressFeatures;

  DWORD  dwNumRingsNoAnswer;
  DWORD  dwForwardNumEntries;
  DWORD  dwForwardSize;
  DWORD  dwForwardOffset;

  DWORD  dwTerminalModesSize;
  DWORD  dwTerminalModesOffset;

  DWORD  dwDevSpecificSize;
  DWORD  dwDevSpecificOffset;
} LINEADDRESSSTATUS, FAR *LPLINEADDRESSSTATUS;

The LINEADDRESSSTATUS structure describes the current status of an address.

dwTotalSize

The total size in bytes allocated to this data structure.

dwNeededSize

The size in bytes for this data structure that is needed to hold all the returned information.

dwUsedSize

The size in bytes of the portion of this data structure that contains useful information.

dwNumInUse

Specifies the number of stations that are currently using the address.

dwNumActiveCalls

The number of calls on the address that are in call states other than idle, onhold, onholdpendingtransfer, and onholdpendingconference.

dwNumOnHoldCalls

The number of calls on the address in the onhold state.

dwNumOnHoldPendCalls

The number of calls on the address in the onholdpendingtransfer or onholdpendingconference state.

dwAddressFeatures

This field specifies the address-related API functions that can be invoked on the address in its current state. It uses the following LINEADDRFEATURE_ constants:

LINEADDRFEATURE_FORWARD

The address can be forwarded.

LINEADDRFEATURE_MAKECALL

An outbound call can be placed on the address.

LINEADDRFEATURE_PICKUP

A call can be picked up at the address.

LINEADDRFEATURE_SETMEDIACONTROL

Media control can be set on this address.

LINEADDRFEATURE_SETTERMINAL

The terminal modes for this address can be set.

LINEADDRFEATURE_SETUPCONF

A conference call with a NULL initial call can be set up at this address.

LINEADDRFEATURE_UNCOMPLETECALL

Call completion requests can be canceled at this address.

LINEADDRFEATURE_UNPARK

Calls can be unparked using this address.

dwNumRingsNoAnswer

Specifies the number of rings set for this address before an unanswered call is considered as no answer.

dwForwardNumEntries

Specifies the number of entries in the array referred to by dwForwardSize and dwForwardOffset.

dwForwardSize
dwForwardOffset

The size in bytes and the offset in bytes from the beginning of this data structure of the variably sized field that describes the address's forwarding information. This information is an array of dwForwardNumEntries elements, of type LINEFORWARD. The offsets of the addresses in the array are relative to the beginning of the LINEADDRESSSTATUS structure. The offsets dwCallerAddressOffset and dwDestAddressOffset in the variably sized field of type LINEFORWARD pointed to by dwForwardSize and dwForwardOffset are relative to the beginning of the LINEADDRESSSTATUS data structure (the "root" container).

dwTerminalModesSize
dwTerminalModesOffset

The size in bytes and the offset in bytes from the beginning of this data structure of the variably sized device field containing an array with DWORD-sized entries, that use the LINETERMMODE_ constants. This array is indexed by terminal IDs, in the range from zero to one less than dwNumTerminals. Each entry in the array specifies the current terminal modes for the corresponding terminal set with the lineSetTerminal function for this address. Values are:

LINETERMMODE_LAMPS

These are lamp events sent from the line to the terminal.

LINETERMMODE_BUTTONS

These are button-press events sent from the terminal to the line.

LINETERMMODE_DISPLAY

This is display information sent from the line to the terminal.

LINETERMMODE_RINGER

This is ringer-control information sent from the switch to the terminal.

LINETERMMODE_HOOKSWITCH

These are hookswitch events sent between the terminal and the line.

LINETERMMODE_MEDIATOLINE

This is the unidirectional media stream from the terminal to the line associated with a call on the line. Use this value when the routing of both unidirectional channels of a call's media stream can be controlled independently.

LINETERMMODE_MEDIAFROMLINE

This is the unidirectional media stream from the line to the terminal associated with a call on the line. Use this value when the routing of both unidirectional channels of a call's media stream can be controlled independently.

LINETERMMODE_MEDIABIDIRECT

This is the bidirectional media stream associated with a call on the line and the terminal. Use this value when the routing of both unidirectional channels of a call's media stream cannot be controlled independently.

dwDevSpecificSize
dwDevSpecificOffset

The size in bytes and the offset in bytes from the beginning of this data structure of the variably sized device-specific field.

Device-specific extensions should use the DevSpecific (dwDevSpecificSize and dwDevSpecificOffset) variably sized area of this data structure.

This data structure is returned by lineGetAddressStatus. When items in this data structure change as a consequence of activities on the address, a LINE_ADDRESSSTATE message is sent to the application. A parameter to this message is the address state, the constant LINEADDRESSSTATE_, which is an indication that the status item in this record that changed.


 LINECALLINFO

[New - Windows 95]

typedef struct linecallinfo_tag {
  DWORD  dwTotalSize;
  DWORD  dwNeededSize;
  DWORD  dwUsedSize;

  HLINE  hLine;
  DWORD  dwLineDeviceID;
  DWORD  dwAddressID;

  DWORD  dwBearerMode;
  DWORD  dwRate;
  DWORD  dwMediaMode;

  DWORD  dwAppSpecific;
  DWORD  dwCallID;
  DWORD  dwRelatedCallID;
  DWORD  dwCallParamFlags;
  DWORD  dwCallStates;

  DWORD  dwMonitorDigitModes;
  DWORD  dwMonitorMediaModes;
  LINEDIALPARAMS  DialParams;

  DWORD  dwOrigin;
  DWORD  dwReason;
  DWORD  dwCompletionID;
  DWORD  dwNumOwners;
  DWORD  dwNumMonitors;

  DWORD  dwCountryCode;
  DWORD  dwTrunk;

  DWORD  dwCallerIDFlags;
  DWORD  dwCallerIDSize;
  DWORD  dwCallerIDOffset;
  DWORD  dwCallerIDNameSize;
  DWORD  dwCallerIDNameOffset;

  DWORD  dwCalledIDFlags;
  DWORD  dwCalledIDSize;
  DWORD  dwCalledIDOffset;
  DWORD  dwCalledIDNameSize;
  DWORD  dwCalledIDNameOffset;

  DWORD  dwConnectedIDFlags;
  DWORD  dwConnectedIDSize;
  DWORD  dwConnectedIDOffset;
  DWORD  dwConnectedIDNameSize;
  DWORD  dwConnectedIDNameOffset;

  DWORD  dwRedirectionIDFlags;
  DWORD  dwRedirectionIDSize;
  DWORD  dwRedirectionIDOffset;
  DWORD  dwRedirectionIDNameSize;
  DWORD  dwRedirectionIDNameOffset;

  DWORD  dwRedirectingIDFlags;
  DWORD  dwRedirectingIDSize;
  DWORD  dwRedirectingIDOffset;
  DWORD  dwRedirectingIDNameSize;
  DWORD  dwRedirectingIDNameOffset;

  DWORD  dwAppNameSize;
  DWORD  dwAppNameOffset;
  DWORD  dwDisplayableAddressSize;

  DWORD  dwDisplayableAddressOffset;

  DWORD  dwCalledPartySize;
  DWORD  dwCalledPartyOffset;

  DWORD  dwCommentSize;
  DWORD  dwCommentOffset;

  DWORD  dwDisplaySize;
  DWORD  dwDisplayOffset;

  DWORD  dwUserUserInfoSize;
  DWORD  dwUserUserInfoOffset;

  DWORD  dwHighLevelCompSize;
  DWORD  dwHighLevelCompOffset;

  DWORD  dwLowLevelCompSize;
  DWORD  dwLowLevelCompOffset;

  DWORD  dwChargingInfoSize;
  DWORD  dwChargingInfoOffset;

  DWORD  dwTerminalModesSize;
  DWORD  dwTerminalModesOffset;

  DWORD  dwDevSpecificSize;
  DWORD  dwDevSpecificOffset;
} LINECALLINFO, FAR *LPLINECALLINFO;

The LINECALLINFO structure contains information about a call. This information remains relatively fixed for the duration of the call and is obtained with lineGetCallInfo. If a part of the structure does change, then a LINE_CALLINFO message is sent to the application indicating which information item has changed. Dynamically changing information about a call, such as call progress status, is available in the LINECALLSTATUS structure, returned with the function lineGetCallStatus.

dwTotalSize

The total size in bytes allocated to this data structure.

dwNeededSize

The size in bytes for this data structure that is needed to hold all the returned information.

dwUsedSize

The size in bytes of the portion of this data structure that contains useful information.

hLine

Specifies the handle for the line device with which this call is associated.

dwLineDeviceID

Specifies the device ID of the line device with which this call is associated.

dwAddressID

Specifies the address ID of the address on the line on which this call exists.

dwBearerMode

Specifies the current bearer mode of the call. This field uses the following LINEBEARERMODE_ constants:

LINEBEARERMODE_VOICE

This is a regular 3.1kHz analog voice grade bearer service. Bit integrity is not assured. Voice can support fax and modem media modes.

LINEBEARERMODE_SPEECH

This corresponds to G.711 speech transmission on the call. The network may use processing techniques such as analog transmission, echo cancellation, and compression/decompression. Bit integrity is not assured. Speech is not intended to support fax and modem media modes.

LINEBEARERMODE_MULTIUSE

The multi-use mode defined by ISDN.

LINEBEARERMODE_DATA

The unrestricted data transfer on the call. The data rate is specified separately.

LINEBEARERMODE_ALTSPEECHDATA

The alternate transfer of speech or unrestricted data on the same call (ISDN).

LINEBEARERMODE_NONCALLSIGNALING

A non-call-associated signaling connection from the application to the service provider or switch (treated as a "media stream" by TAPI).

LINEBEARERMODE_PASSTHROUGH

When a call is active in LINEBEARERMODE_PASSTHROUGH, the service provider gives direct access to the attached hardware for control by the application. This mode is used primarily by applications desiring temporary direct control over asynchronous modems, accessed via the Win32 comm functions, for the purpose of configuring or using special features not otherwise supported by the service provider.

dwRate

Specifies the rate of the call's data stream in bps (bits per second).

dwMediaMode

Specifies the media mode of the information stream currently on the call. This is the media mode as determined by the owner of the call, which is not necessarily the same as that of the last LINE_MONITORMEDIA message. This field is not directly affected by the LINE_MONITORMEDIA messages. It uses the following LINEMEDIAMODE_ constants:

LINEMEDIAMODE_UNKNOWN

A media stream exists but its mode is not known. This corresponds to a call with an unclassified media type. In typical analog telephony environments, an inbound call's media mode may be unknown until after the call has been answered and the media stream has been filtered to make a determination.

LINEMEDIAMODE_INTERACTIVEVOICE

The presence of voice energy is detected on the call and the call is treated as an interactive call with humans on both ends.

LINEMEDIAMODE_AUTOMATEDVOICE

The presence of voice energy is detected on the call and the voice is locally handled by an automated application.

LINEMEDIAMODE_DATAMODEM

A data modem session is detected on the call.

LINEMEDIAMODE_G3FAX

A group 3 fax is being sent or received on the call.

LINEMEDIAMODE_TDD

A TDD (Telephony Devices for the Deaf) session on the call.

LINEMEDIAMODE_G4FAX

A group 4 fax is being sent or received over the call.

LINEMEDIAMODE_DIGITALDATA

Digital data being sent or received over the call.

LINEMEDIAMODE_TELETEX

A teletex session on the call. Teletex is one of the telematic services.

LINEMEDIAMODE_VIDEOTEX

A videotex session on the call. Videotex is one the telematic services.

LINEMEDIAMODE_TELEX

A telex session on the call. Telex is one the telematic services.

LINEMEDIAMODE_MIXED

A mixed session on the call. Mixed is one the ISDN telematic services.

LINEMEDIAMODE_ADSI

An ADSI (Analog Display Services Interface) session on the call.

dwAppSpecific

This field is uninterpreted by the API implementation and service provider. It can be set by any owner application of this call with the operation lineSetAppSpecific.

dwCallID

In some telephony environments, the switch or service provider may assign a unique identifier to each call. This allows the call to be tracked across transfers, forwards, or other events. The domain of these call IDs and their scope is service-provider defined. The dwCallID field makes this unique identifier available to the applications.

dwRelatedCallID

Telephony environments that use the call ID often may find it necessary to relate one call to another. The dwRelatedCallID field may be used by the service provider for this purpose.

dwCallParamFlags

Specifies a collection of call-related parameters when the call is outbound. These are same call parameters specified in lineMakeCall, of type LINECALLPARAMFLAGS_. Values are:

LINECALLPARAMFLAGS_SECURE

The call is currently secure. This flag is also updated if the call is later secured through lineSecureCall.

LINECALLPARAMFLAGS_IDLE

The call started out using an idle call.

LINECALLPARAMFLAGS_BLOCKID

The originator identity was concealed (block caller ID presentation to the remote party).

LINECALLPARAMFLAGS_ORIGOFFHOOK

The originator's phone was automatically taken offhook.

LINECALLPARAMFLAGS_DESTOFFHOOK

The called party's phone was automatically taken offhook.

dwCallStates

Specifies the call states for which the application may be notified on this call, of type LINECALLSTATE_. dwCallStates is constant in LINECALLINFO and does not change depending on the call state. Values are:

LINECALLSTATE_IDLE

The call is idle—no call exists.

LINECALLSTATE_OFFERING

The call is being offered to the station signaling the arrival of a new call. In some environments, a call in the offering state does not automatically alert the user; alerting is done by the switch instructing the line to ring. It does not affect any call states.

LINECALLSTATE_ACCEPTED

The call was offering and has been accepted. This indicates to other (monitoring) applications that the current owner application has claimed responsibility for answering the call. In ISDN, this also initiates alerting to both parties.

LINECALLSTATE_DIALTONE

The call is receiving a dial tone from the switch, which means that the switch is ready to receive a dialed number.

LINECALLSTATE_DIALING

Destination address information (a phone number) is being sent to the switch over the call. Note that the operation lineGenerateDigits does not place the line into the dialing state.

LINECALLSTATE_RINGBACK

The call is receiving ringback from the called address. Ringback indicates that the other station has been reached and is being alerted.

LINECALLSTATE_BUSY

The call is receiving a busy tone. Busy tone indicates that the call cannot be completed—either a circuit (trunk) or the remote party's station are in use.

LINECALLSTATE_SPECIALINFO

Special information is sent by the network. Special information is typically sent when the destination cannot be reached.

LINECALLSTATE_CONNECTED

The call has been established, the connection is made. Information is able to flow over the call between the originating address and the destination address.

LINECALLSTATE_PROCEEDING

Dialing has completed and the call is proceeding through the switch or telephone network.

LINECALLSTATE_ONHOLD

The call is on hold by the switch.

LINECALLSTATE_CONFERENCED

The call is currently a member of a multiparty conference call.

LINECALLSTATE_ONHOLDPENDCONF

The call is currently on hold while it is being added to a conference.

LINECALLSTATE_ONHOLDPENDTRANSF

The call is currently on hold awaiting transfer to another number.

LINECALLSTATE_DISCONNECTED

The remote party has disconnected from the call.

LINECALLSTATE_UNKNOWN

The state of the call is not known. This may be due to limitations of the call progress detection implementation.

dwMonitorDigitsModes

Specifies the various digit modes for which monitoring is currently enabled, of type LINEDIGITMODE_. Values are:

LINEDIGITMODE_PULSE

Uses pulse/rotary for digit signaling.

LINEDIGITMODE_DTMF

Uses DTMF tones for digit signaling.

LINEDIGITMODE_DTMFEND

Uses DTMF tones for digit detection, and also detects the down edges.

dwMonitorMediaModes

Specifies the various media modes for which monitoring is currently enabled, of type LINEMEDIAMODE_. Values are:

LINEMEDIAMODE_INTERACTIVEVOICE

The presence of voice energy on the call and the call is treated as an interactive call with humans on both ends.

LINEMEDIAMODE_AUTOMATEDVOICE

The presence of voice energy on the call and the voice is locally handled by an automated application.

LINEMEDIAMODE_DATAMODEM

A data modem session on the call.

LINEMEDIAMODE_G3FAX

A group 3 fax is being sent or received over the call.

LINEMEDIAMODE_TDD

A TDD (Telephony Devices for the Deaf) session on the call.

LINEMEDIAMODE_G4FAX

A group 4 fax is being sent or received over the call.

LINEMEDIAMODE_DIGITALDATA

Digital data is being sent or received over the call.

LINEMEDIAMODE_TELETEX

A teletex session on the call. Teletex is one of the telematic services.

LINEMEDIAMODE_VIDEOTEX

A videotex session on the call. Videotex is one the telematic services.

LINEMEDIAMODE_TELEX

A telex session on the call. Telex is one the telematic services.

LINEMEDIAMODE_MIXED

A mixed session on the call. Mixed is one the ISDN telematic services.

LINEMEDIAMODE_ADSI

An ADSI (Analog Display Services Interface) session on the call.

DialParams

Specifies the dialing parameters currently in effect on the call, of type LINEDIALPARAMS. Unless these parameters are set by either lineMakeCall or lineSetCallParams, their values will be the same as the defaults used in the LINEDEVCAPS.

dwOrigin

Identifies where the call originated from. This field uses the following LINECALLORIGIN_ constants:

LINECALLORIGIN_OUTBOUND

The call is an outbound call.

LINECALLORIGIN_INTERNAL

The call is inbound and originated internally (on the same PBX, for example).

LINECALLORIGIN_EXTERNAL

The call is inbound and originated externally.

LINECALLORIGIN_UNKNOWN

The call is an inbound call and its origin is currently unknown but may become known later.

LINECALLORIGIN_UNAVAIL

The call is an inbound call. Its origin is not available and will never become known for this call.

LINECALLORIGIN_CONFERENCE

The call handle is for a conference call, that is, the application's connection to the conference bridge in the switch.

dwReason

Specifies the reason why the call occurred. This field uses the following LINECALLREASON_ constants:

LINECALLREASON_DIRECT

This is a direct call.

LINECALLREASON_FWDBUSY

This call was forwarded from another extension that was busy at the time of the call.

LINECALLREASON_FWDNOANSWER

The call was forwarded from another extension that didn't answer the call after some number of rings.

LINECALLREASON_FWDUNCOND

The call was forwarded unconditionally from another number.

LINECALLREASON_PICKUP

The call was picked up from another extension.

LINECALLREASON_UNPARK

The call was retrieved as a parked call.

LINECALLREASON_REDIRECT

The call was redirected to this station.

LINECALLREASON_CALLCOMPLETION

The call was the result of a call completion request.

LINECALLREASON_TRANSFER

The call has been transferred from another number. Party ID information may indicate who the caller is and where the call was transferred from.

LINECALLREASON_REMINDER

The call is a reminder (or "recall") that the user has a call parked or on hold for potentially a long time.

LINECALLREASON_UNKNOWN

The reason for the call is currently unknown but may become known later.

LINECALLREASON_UNAVAIL

The reason for the call is unavailable and will not become known later.

dwCompletionID

The completion ID for the incoming call if it is the result of a completion request that terminates. This ID is meaningful only if dwReason is LINECALLREASON_CALLCOMPLETION.

dwNumOwners

The number of application modules with different call handles with owner privilege for the call.

dwNumMonitors

The number of application modules with different call handles with monitor privilege for the call.

dwCountryCode

The country code of the destination party. Zero if unknown.

dwTrunk

The number of the trunk over which the call is routed. This field is used for both inbound and outgoing calls. dwTrunk should be set to 0xFFFFFFFF if it is unknown.

dwCallerIDFlags

Determines the validity and content of the caller party ID information. The caller is the originator of the call. This field uses the following LINECALLPARTYID_ constants:

LINECALLPARTYID_BLOCKED

Caller ID information for the call has been blocked by the caller but would otherwise have been available.

LINECALLPARTYID_OUTOFAREA

Caller ID information for the call is not available since it is not propagated all the way by the network.

LINECALLPARTYID_NAME

The caller ID information for the call is the caller's name (from a table maintained inside the switch). It is provided in the caller ID name variably sized field.

LINECALLPARTYID_ADDRESS

The caller ID information for the call is the caller's number and is provided in the caller ID variably sized field.

LINECALLPARTYID_PARTIAL

Caller ID information for the call is valid but is limited to partial number information.

LINECALLPARTYID_UNKNOWN

Caller ID information is currently unknown but it may become known later.

LINECALLPARTYID_UNAVAIL

Caller ID information is unavailable and will not become known later.

dwCallerIDSize
dwCallerIDOffset

The size in bytes of the variably sized field containing the caller party ID number information, and the offset in bytes from the beginning of this data structure.

dwCallerIDNameSize
dwCallerIDNameOffset

The size in bytes of the variably sized field containing the caller party ID name information, and the offset in bytes from the beginning of this data structure.

dwCalledIDFlags

Determines the validity and content of the called-party ID information. The called party corresponds to the orignally addressed party. This field uses the following LINECALLPARTYID_ constants:

LINECALLPARTYID_BLOCKED

Called ID information for the call has been blocked by the caller but would otherwise have been available.

LINECALLPARTYID_OUTOFAREA

Caller ID information for the call is not available since it is not propagated all the way by the network.

LINECALLPARTYID_NAME

The called ID information for the call is the caller's name (from a table maintained inside the switch). It is provided in the called ID name variably sized field.

LINECALLPARTYID_ADDRESS

The called ID information for the call is the caller's number and is provided in the called ID variably sized field.

LINECALLPARTYID_PARTIAL

Called ID information for the call is valid but is limited to partial number information.

LINECALLPARTYID_UNKNOWN

Called ID information is currently unknown but it may become known later.

LINECALLPARTYID_UNAVAIL

Called ID information is unavailable and will not become known later.

dwCalledIDSize
dwCalledIDOffset

The size in bytes of the variably sized field containing the called-party ID number information, and the offset in bytes from the beginning of this data structure.

dwCalledIDNameSize
dwCalledIDNameOffset

The size in bytes of the variably sized field containing the called-party ID name information, and the offset in bytes from the beginning of this data structure.

dwConnectedFlags

Determines the validity and content of the connected party ID information. The connected party is the party that was actually connected to. This may be different from the called-party ID if the call was diverted. This field uses the following LINECALLPARTYID_ constants:

LINECALLPARTYID_BLOCKED

Connected party ID information for the call has been blocked by the caller but would otherwise have been available.

LINECALLPARTYID_OUTOFAREA

Connected ID information for the call is not available as it is not propagated all the way by the network.

LINECALLPARTYID_NAME

The connected party ID information for the call is the caller's name (from a table maintained inside the switch). It is provided in the connected ID name variably sized field.

LINECALLPARTYID_ADDRESS

The connected party ID information for the call is the caller's number and is provided in the connected ID variably sized field.

LINECALLPARTYID_PARTIAL

Connected party ID information for the call is valid but is limited to partial number information.

LINECALLPARTYID_UNKNOWN

Connected party ID information is currently unknown but it may become known later.

LINECALLPARTYID_UNAVAIL

Connected party ID information is unavailable and will not become known later.

dwConnectedIDSize
dwConnectedIDOffset

The size in bytes of the variably sized field containing the connected party ID number information, and the offset in bytes from the beginning of this data structure.

dwConnectedIDNameSize
dwConnectedIDNameOffset

The size in bytes of the variably sized field containing the connected party ID name information, and the offset in bytes from the beginning of this data structure.

dwRedirectionIDFlags

Determines the validity and content of the redirection party ID information. The redirection party identifies to the calling user the number towards which diversion was invoked. This field uses the following LINECALLPARTYID_ constants:

LINECALLPARTYID_BLOCKED

Redirection party ID information for the call has been blocked by the caller but would otherwise have been available.

LINECALLPARTYID_OUTOFAREA

Redirection ID information for the call is not available since it is not propagated all the way by the network.

LINECALLPARTYID_NAME

The redirection party ID information for the call is the caller's name (from a table maintained inside the switch). It is provided in the redirection ID name variably sized field.

LINECALLPARTYID_ADDRESS

The redirection party ID information for the call is the caller's number and is provided in the redirection ID variably sized field.

LINECALLPARTYID_PARTIAL

Redirection party ID information for the call is valid but is limited to partial number information.

LINECALLPARTYID_UNKNOWN

Redirection ID information is currently unknown but it may become known later.

LINECALLPARTYID_UNAVAIL

Redirection ID information is unavailable and will not become known later.

dwRedirectionIDSize
dwRedirectionIDOffset

The size in bytes of the variably sized field containing the redirection party ID number information, and the offset in bytes from the beginning of this data structure.

dwRedirectionIDNameSize
dwRedirectionIDNameOffset

The size in bytes of the variably sized field containing the redirection party ID name information, and the offset in bytes from the beginning of this data structure.

dwRedirectingIDFlags

Determines the validity and content of the redirecting party ID information. The redirecting party identifies to the diverted-to user the party from which diversion was invoked. This field uses the following LINECALLPARTYID_ constants:

LINECALLPARTYID_BLOCKED

Redirecting party ID information for the call has been blocked by the caller but would otherwise have been available.

LINECALLPARTYID_OUTOFAREA

Redirecting ID information for the call is not available since it is not propagated all the way by the network.

LINECALLPARTYID_NAME

The redirecting party ID information for the call is the caller's name (from a table maintained inside the switch). It is provided in the redirecting ID name variably sized field.

LINECALLPARTYID_ADDRESS

The redirecting party ID information for the call is the caller's number and is provided in the redirecting ID variably sized field.

LINECALLPARTYID_PARTIAL

Redirecting party ID information for the call is valid but is limited to partial number information.

LINECALLPARTYID_UNKNOWN

Redirecting ID information is currently unknown but it may become known later.

LINECALLPARTYID_UNAVAIL

Redirecting ID information is unavailable and will not become known later.

dwRedirectingIDSize
dwRedirectingIDOffset

The size in bytes of the variably sized field containing the redirecting party ID number information, and the offset in bytes from the beginning of this data structure.

dwRedirectingIDNameSize
dwRedirectingIDNameOffset

The size in bytes of the variably sized field containing the redirecting party ID name information, and the offset in bytes from the beginning of this data structure.

dwAppNameSize
dwAppNameOffset

The size in bytes and the offset in bytes from the beginning of this data structure of the variably sized field holding the user-friendly application name of the application that first originated, accepted, or answered the call. This is the name that an application can specify on lineInitialize. If the application specifies no such name, then the application's file name is used instead.

dwDisplayableAddressSize
dwDisplayableAddressOffset

The displayable string is used for logging purposes. The information is obtained from LINECALLPARAMS for functions that intiate calls. The function lineTranslateAddress returns appropriate information to be placed in this field in the dwDisplayableAddressSize and dwDisplayableAddressOffset fields of the LINETRANSLATEOUTPUT structure.

dwCalledPartySize
dwCalledPartyOffset

The size in bytes of the variably sized field holding a user-friendly description of the called party, and the offset in bytes from the beginning of this data structure. This information can be specified on lineMakeCall and can be optionally specified in the lpCallParams whenever a new call is established. It is useful for call logging purposes.

dwCommentSize
dwCommentOffset

The size in bytes of the variably sized field holding a comment about the call provided by the application that originated the call using lineMakeCall, and the offset in bytes from the beginning of this data structure. This information can be optionally specified in the lpCallParams whenever a new call is established.

dwDisplaySize
dwDisplayOffset

The size in bytes of the variably sized field holding raw display information, and the offset in bytes from the beginning of this data structure. Depending on the telephony environment, a service provider may extract functional information from this for presentation in a more functional way.

dwUserUserInfoSize
dwUserUserInfoOffset

The size in bytes of the variably sized field holding user-to-user information, and the offset in bytes from the beginning of this data structure The protocol discriminator field for the user-user information, if used, appears as the first byte of the data pointed to by dwUserUserInfoOffset, and is accounted for in dwUserUserInfoSize.

dwHighLevelCompSize
dwHighLevelCompOffset

The size in bytes of the variably sized field holding high-level compatibility information, and the offset in bytes from the beginning of this data structure. The format of this information is specified by other standards (ISDN Q.931).

dwLowLevelCompSize
dwLowLevelCompOffset

The size in bytes of the variably sized field holding low-level compatibility information, and the offset in bytes from the beginning of this data structure The format of this information is specified by other standards (ISDN Q.931).

dwChargingInfoSize
dwChargingInfoOffset

The size in bytes of the variably sized field holding charging information, and the offset in bytes from the beginning of this data structure The format of this information is specified by other standards (ISDN Q.931).

dwTerminalModesSize
dwTerminalModesOffset

The size in bytes of the variably sized device field containing an array with DWORD-sized entries, and the offset in bytes from the beginning of this data structure. The set of LINETERMMODE_ constants is indexed by terminal IDs, in the range from zero to one less than dwNumTerminals. Each entry in the array specifies the current terminal modes for the corresponding terminal set with the lineSetTerminal operation for this call's media stream. Values are:

LINETERMMODE_LAMPS

These are lamp events sent from the line to the terminal.

LINETERMMODE_BUTTONS

These are button-press events sent from the terminal to the line.

LINETERMMODE_DISPLAY

This is display information sent from the line to the terminal.

LINETERMMODE_RINGER

This is ringer-control information sent from the switch to the terminal.

LINETERMMODE_HOOKSWITCH

These are hookswitch event sent between the terminal and the line.

LINETERMMODE_MEDIATOLINE

This is the unidirectional media stream from the terminal to the line associated with a call on the line. Use this value when the routing of both unidirectional channels of a call's media stream can be controlled independently.

LINETERMMODE_MEDIAFROMLINE

This is the unidirectional media stream from the line to the terminal associated with a call on the line. Use this value when the routing of both unidirectional channels of a call's media stream can be controlled independently.

LINETERMMODE_MEDIABIDIRECT

This is the bidirectional media stream associated with a call on the line and the terminal. Use this value when the routing of both the unidirectional channels of a call's media stream cannot be controlled independently.

dwDevSpecificSize
dwDevSpecificOffset

The size in bytes of the variably sized field holding device-specific information., and the offset in bytes from the beginning of this data structure.

Device-specific extensions should use the DevSpecific (dwDevSpecificSize and dwDevSpecificOffset) variably sized area of this data structure.

The LINECALLINFO data structure contains relatively fixed information about a call. This structure is returned with lineGetCallInfo. When information items in this data structure have changed, a LINE_CALLINFO message is sent to the application. A parameter to this message is the information item or field that changed.

The dwAppSpecific field can be used by applications to tag calls by using lineSetAppSpecific. This field is uninterpreted by TAPI or service providers. It is initially set to zero.


 LINECALLLIST

[New - Windows 95]

typedef struct linecalllist_tag {
  DWORD  dwTotalSize;
  DWORD  dwNeededSize;
  DWORD  dwUsedSize;

  DWORD  dwCallsNumEntries;
  DWORD  dwCallsSize;
  DWORD  dwCallsOffset;
} LINECALLLIST, FAR *LPLINECALLLIST;

The LINECALLLIST structure describes a list of call handles. A structure of this type is returned by the functions lineGetNewCalls and lineGetConfRelatedCalls.

dwTotalSize

The total size in bytes allocated to this data structure.

dwNeededSize

The size in bytes for this data structure that is needed to hold all the returned information.

dwUsedSize

The size in bytes of the portion of this data structure that contains useful information.

dwCallsNumEntries

Specifies the number of handles in the hCalls array.

dwCallsSize
dwCallsOffset

The size in bytes and the offset in bytes from the beginning of this data structure of the variably sized field (which is an array of HCALL-sized handles).

No extensions.


 LINECALLPARAMS

[New - Windows 95]

typedef struct linecallparams_tag {  // Defaults:
  DWORD  dwTotalSize;          // ---------

  DWORD  dwBearerMode;        // voice
  DWORD  dwMinRate;          // (3.1kHz)
  DWORD  dwMaxRate;          // (3.1kHz)
  DWORD  dwMediaMode;          // interactiveVoice

  DWORD  dwCallParamFlags;      // 0
  DWORD  dwAddressMode;        // addressID
  DWORD  dwAddressID;          // (any available)

  LINEDIALPARAMS DialParams;      // (0, 0, 0, 0)

  DWORD  dwOrigAddressSize;      // 0
  DWORD  dwOrigAddressOffset;

  DWORD  dwDisplayableAddressSize;  // 0
  DWORD  dwDisplayableAddressOffset;

  DWORD  dwCalledPartySize;      // 0
  DWORD  dwCalledPartyOffset;

  DWORD  dwCommentSize;        // 0
  DWORD  dwCommentOffset;

  DWORD  dwUserUserInfoSize;      // 0
  DWORD  dwUserUserInfoOffset;

  DWORD  dwHighLevelCompSize;      // 0
  DWORD  dwHighLevelCompOffset;

  DWORD  dwLowLevelCompSize;      // 0
  DWORD  dwLowLevelCompOffset;

  DWORD  dwDevSpecificSize;      // 0
  DWORD  dwDevSpecificOffset;
} LINECALLPARAMS, FAR *LPLINECALLPARAMS;

The LINECALLPARAMS structure describes parameters supplied when making calls using lineMakeCall. The LINECALLPARAMS structure is also used as a parameter in other operations. The comments on the right indicate the default values used when this structure is not provided to lineMakeCall.

dwTotalSize

The total size in bytes allocated to this data structure. This size should be big enough to hold all the fixed and variably sized portions of this data structure.

dwBearerMode

Specifies the bearer mode for the call. This field uses the following LINEBEARERMODE_ constants:

LINEBEARERMODE_VOICE

This is a regular 3.1kHz analog voice grade bearer service. Bit integrity is not assured. Voice can support fax and modem media modes.

LINEBEARERMODE_SPEECH

This corresponds to G.711 speech transmission on the call. The network may use processing techniques such as analog transmission, echo cancellation, and compression/decompression. Bit integrity is not assured. Speech is not intended to support fax and modem media modes.

LINEBEARERMODE_MULTIUSE

The multi-use mode defined by ISDN.

LINEBEARERMODE_DATA

The unrestricted data transfer on the call. The data rate is specified separately.

LINEBEARERMODE_ALTSPEECHDATA

The alternate transfer of speech or unrestricted data on the same call (ISDN).

LINEBEARERMODE_NONCALLSIGNALING

This corresponds to a non-call-associated signaling connection from the application to the service provider or switch (treated as a "media stream" by the Telephony API).

LINEBEARERMODE_PASSTHROUGH

When a call is active in LINEBEARERMODE_PASSTHROUGH, the service provider gives direct access to the attached hardware for control by the application. This mode is used primarily by applications desiring temporary direct control over asynchronous modems, accessed via the Win32 comm functions, for the purpose of configuring or using special features not otherwise supported by the service provider.

If dwBearerMode is 0, default value is LINEBEARERMODE_VOICE.

dwMinRate
dwMaxRate

Specifies the data rate range requested for the call's data stream in bps (bits per second). When making a call, the service provider attempts to provide the highest available rate in the requested range. If a specific data rate is required, both min and max should be set to that value. If an application works best with one rate but is able the degrade to lower rates, the application should specify these as the max and min rates respectively. If dwMaxRate is 0, default value is as specified by the dwMaxRate member of the LINEDEVCAPS structure. This is the maximum rate supported by device.

dwMediaMode

Specifies the expected media mode of the call. This field uses the following LINEMEDIAMODE_ constants:

LINEMEDIAMODE_UNKNOWN

A media stream exists but its mode is not known. This would correspond to a call with an unclassified media type. In typical analog telephony environments, an inbound call's media mode may be unknown until after the call has been answered and the media stream has been filtered to make a determination.

LINEMEDIAMODE_INTERACTIVEVOICE

The presence of voice energy on the call and the call is treated as an interactive call with humans on both ends.

LINEMEDIAMODE_AUTOMATEDVOICE

The presence of voice energy on the call and the voice is locally handled by an automated application.

LINEMEDIAMODE_DATAMODEM

A data modem session on the call.

LINEMEDIAMODE_G3FAX

A group 3 fax is being sent or received over the call.

LINEMEDIAMODE_TDD

A TDD (Telephony Devices for the Deaf) session on the call.

LINEMEDIAMODE_G4FAX

A group 4 fax is being sent or received over the call.

LINEMEDIAMODE_DIGITALDATA

Digital data is being sent or received over the call.

LINEMEDIAMODE_TELETEX

A teletex session on the call. Teletex is one of the telematic services.

LINEMEDIAMODE_VIDEOTEX

A videotex session on the call. Videotex is one the telematic services.

LINEMEDIAMODE_TELEX

A telex session on the call. Telex is one the telematic services.

LINEMEDIAMODE_MIXED

A mixed session on the call. Mixed is one the ISDN telematic services.

LINEMEDIAMODE_ADSI

An ADSI (Analog Display Services Interface) session on the call.

If dwMediaMode is 0, the default value is LINEMEDIAMODE_INTERACTIVEVOICE.

dwCallParamFlags

These flags specify a collection of Boolean call-setup parameters. This field uses the following LINECALLPARAMFLAGS_ constants:

LINECALLPARAMFLAGS_SECURE

The call should be set up as secure.

LINECALLPARAMFLAGS_IDLE

The call should get an idle call appearance.

LINECALLPARAMFLAGS_BLOCKID

The originator identity should be concealed (block caller ID).

LINECALLPARAMFLAGS_ORIGOFFHOOK

The originator's phone should be automatically taken offhook.

LINECALLPARAMFLAGS_DESTOFFHOOK

The called party's phone should be automatically be taken offhook.

dwAddressMode

Specifies the mode by which the originating address is specified. The dwAddressMode field cannot be LINEADDRESSMODE_ADDRESSID for the function call lineOpen. This field uses the following LINEADDRESSMODE_ constants:

LINEADDRESSMODE_ADDRESSID

The address is specified with a small integer in the range 0 to dwNumAddresses minus one, where dwNumAddresses is the value in the line's LINEDEVCAPS structure. The selected address is specified in the dwAddressID field.

LINEADDRESSMODE_DIALABLEADDR

The address is specified with its dialable address. The address is contained in the dwOrigAddressSize, dwOrigAddressOffset variably sized field.

If dwAddressMode is 0, the default value is LINEADDRESSMODE_ADDRESSID.

dwAddressID

Specifies the address ID of the originating address if dwAddressMode is set to LINEADDRESSMODE_ADDRESSID.

DialParams

Specifies dial parameters to be used on this call, of type LINEDIALPARAMS. When a value of zero is specified for this field, the default value for the field is used as specified in the DefaultDialParams member of the LINEDEVCAPS structure. If a non-zero value is specified for a field which is outside the range specified by the corresponding fields in MinDialParams and MaxDialParams in the LINEDEVCAPS structure, the nearest value within the valid range is used instead.

dwOrigAddressSize
dwOrigAddressOffset

The size in bytes of the variably sized field holding the originating address, and the offset in bytes from the beginning of this data structure. The format of this address is dependent on the dwAddressMode field.

dwDisplayableAddressSize
dwDisplayableAddressOffset

The displayable string is used for logging purposes. The content of these fields is recorded in the dwDisplayableAddressOffset and dwDisplayableAddressSize fields of the call's LINECALLINFO message.  lineTranslateAddress returns appropriate information to be placed in this field in the dwDisplayableAddressSize and dwDisplayableAddressOffset fields of the LINETRANSLATEOUTPUT structure.

dwCalledPartySize
dwCalledPartyOffset

The size in bytes of the variably sized field holding called-party information, and the offset in bytes from the beginning of this data structure. This information can be specified by the application that makes the call and is made available in the call's information structure for logging purposes. The format of this field is that of dwStringFormat, as specified in LINEDEVCAPS.

dwCommentSize
dwCommentOffset

The size in bytes of the variably sized field holding comments about the call, and the offset in bytes from the beginning of this data structure. This information can be specified by the application the makes the call and is made available in the call's information structure for logging purposes. The format of this field is that of dwStringFormat, as specified in LINEDEVCAPS.

dwUserUserInfoSize
dwUserUserInfoOffset

The size in bytes of the variably sized field holding user-to-user information, and the offset in bytes from the beginning of this data structure. The protocol discriminator field for the user-user information, if required, should appear as the first byte of the data pointed to by dwUserUserInfoOffset, and must be accounted for in dwUserUserInfoSize.

dwHighLevelCompSize
dwHighLevelCompOffset

The size in bytes of the variably sized field holding high-level compatibility information, and the offset in bytes from the beginning of this data structure

dwLowLevelCompSize
dwLowLevelCompOffset

The size in bytes of the variably sized field holding low-level compatibility information, and the offset in bytes from the beginning of this data structure.

dwDevSpecificSize
dwDevSpecificOffset

The size in bytes of the variably sized field holding device-specific information, and the offset in bytes from the beginning of this data structure

Device-specific extensions should use the DevSpecific (dwDevSpecificSize and dwDevSpecificOffset) variably sized area of this data structure.

This structure is used as a parameter to lineMakeCall when setting up a call. Its fields allow the application to specify the quality of service requested from the network as well as a variety of ISDN call-setup parameters. If no LINECALLPARAMS structure is supplied to lineMakeCall, a default POTS voice-grade call is requested with the default values listed above.

Note that the fields DialParams through dwDevSpecificOffset are ignored when an lpCallParams parameter is specified with the function lineOpen.


 LINECALLSTATUS

[New - Windows 95]

typedef struct linecallstatus_tag {
  DWORD  dwTotalSize;
  DWORD  dwNeededSize;
  DWORD  dwUsedSize;

  DWORD  dwCallState;
  DWORD  dwCallStateMode;
  DWORD  dwCallPrivilege;
  DWORD  dwCallFeatures;

  DWORD  dwDevSpecificSize;
  DWORD  dwDevSpecificOffset;
} LINECALLSTATUS, FAR *LPLINECALLSTATUS;

The LINECALLSTATUS structure describes the current status of a call. The information in this structure, as returned with lineGetCallStatus, depends on the device capabilities of the address, the ownership of the call by the invoking application, and the current state of the call being queried.

dwTotalSize

The total size in bytes allocated to this data structure.

dwNeededSize

The size in bytes for this data structure that is needed to hold all the returned information.

dwUsedSize

The size in bytes of the portion of this data structure that contains useful information.

dwCallState
dwCallStateMode

The dwCallState field specifies the current call state of the call. The interpretation of the dwCallStateMode field is call-state-dependent. It specifies the current mode of the call while in its current state (if that state defines a mode). This field uses the following LINECALLSTATE_ constants:

LINECALLSTATE_IDLE

The call state mode is unused.

LINECALLSTATE_OFFERING

The call state mode is unused.

LINECALLSTATE_ACCEPTED

The call state mode is unused.

LINECALLSTATE_DIALTONE

The call state mode, of type LINEDIALTONEMODE_. Values are:

LINEDIALTONEMODE_NORMAL

This is a "normal" dialtone which typically is a continuous tone.

LINEDIALTONEMODE_SPECIAL

This is a special dialtone indicating a certain condition is currently in effect.

LINEDIALTONEMODE_INTERNAL

This an internal dialtone, as within a PBX.

LINEDIALTONEMODE_EXTERNAL

This is an external (public network) dialtone.

LINEDIALTONEMODE_UNKNOWN

The dialtone mode is not currently known but may become known later.

LINEDIALTONEMODE_UNAVAIL

The dialtone mode is unavailable and will not become known.

LINECALLSTATE_DIALING

Call state mode is unused.

LINECALLSTATE_RINGBACK

Call state mode is unused.

LINECALLSTATE_BUSY

The call state mode is of type LINEBUSYMODE_. Values are:

LINEBUSYMODE_STATION

The busy signal indicates that the called party's station is busy. This is usually signaled with a "normal" busy tone.

LINEBUSYMODE_TRUNK

The busy signal indicates that a trunk or circuit is busy. This is usually signaled with a "long" busy tone.

LINEBUSYMODE_UNKNOWN

The busy signal's specific mode is currently unknown but may become known later.

LINEBUSYMODE_UNAVAIL

The busy signal's specific mode is unavailable and will not become known.

LINECALLSTATE_SPECIALINFO

The call state mode is of type LINESPECIALINFO_. Values are:

LINESPECIALINFO_NOCIRCUIT

This special information tone preceeds a no circuit or emergency announcement (trunk blockage category).

LINESPECIALINFO_CUSTIRREG

This special information tone preceeds a vacant number, AIS, Centrex number change and nonworking station, access code not dialed or dialed in error, or manual intercept operator message (customer irregularity category).

LINESPECIALINFO_REORDER

This special information tone preceeds a reorder announcement (equipment irregularity category).

LINESPECIALINFO_UNKNOWN

Specifics about the special information tone are currently unknown but may become known later.

LINESPECIALINFO_UNAVAIL

Specifics about the special information tone are unavailable and will not become known.

LINECALLSTATE_CONNECTED

Call state mode is unused.

LINECALLSTATE_PROCEEDING

Call state mode is unused.

LINECALLSTATE_ONHOLD

Call state mode is unused.

LINECALLSTATE_CONFERENCED

Call state mode is unused.

LINECALLSTATE_ONHOLDPENDCONF

Call state mode is unused.

LINECALLSTATE_ONHOLDPENDTRANSF

Call state mode is unused.

LINECALLSTATE_DISCONNECTED

Call state mode is of type LINEDISCONNECTMODE_. Values are:

LINEDISCONNECTMODE_NORMAL

This is a "normal" disconnect request by the remote party. The call was terminated normally.

LINEDISCONNECTMODE_UNKNOWN

The reason for the disconnect request is unknown.

LINEDISCONNECTMODE_REJECT

The remote user has rejected the call.

LINEDISCONNECTMODE_PICKUP

The call was picked up from elsewhere.

LINEDISCONNECTMODE_FORWARDED

The call was forwarded by the switch.

LINEDISCONNECTMODE_BUSY

The remote user's station is busy.

LINEDISCONNECTMODE_NOANSWER

The remote user's station does not answer.

LINEDISCONNECTMODE_BADADDRESS

The destination address in invalid.

LINEDISCONNECTMODE_UNREACHABLE

The remote user could not be reached.

LINEDISCONNECTMODE_CONGESTION

The network is congested.

LINEDISCONNECTMODE_INCOMPATIBLE

The remote user's station equipment is incompatible with the type of call requested.

LINEDISCONNECTMODE_UNAVAIL

The reason for the disconnect is unavailable and will not become known later.

LINECALLSTATE_UNKNOWN

Call state mode is unused.

dwCallPrivilege

Specifies the application's privilege for this call. This field uses the following LINECALLPRIVILEGE_ constants. Values are:

LINECALLPRIVILEGE_MONITOR

The application has monitor privilege.

LINECALLPRIVILEGE_OWNER

The application has owner privilege.

dwCallFeatures

These flags indicate which Telephony API functions can be invoked on the call, given the availability of the feature in the device capabilities, the current call state, and call ownership of the invoking application. A zero indicates the corresponding feature cannot be invoked by the application on the call in its current state; a one indicates the feature can be invoked. This field uses LINECALLFEATURE_ constants.

dwDevSpecificSize
dwDevSpecificOffset

The size in bytes of the variably sized device-specific field, and the offset in bytes from the beginning of this data structure.

Device-specific extensions should use the DevSpecific (dwDevSpecificSize and dwDevSpecificOffset) variably sized area of this data structure.

The application is sent a LINE_CALLSTATE message whenever the call state of a call changes. This message only provides the new call state of the call. Additional status about a call is available with lineGetCallStatus.

The members of the LINECALLSTATUS structure may be set to the LINECONNECTEDMODE_ACTIVE or LINECONNECTEDMODE_INACTIVE and the LINEOFFERINGMODE_ACTIVE or LINEOFFERINGMODE_INACTIVE values depending on the state of the corresponding call.


 LINECARDENTRY

[New - Windows 95]

typedef struct linecardentry_tag {
  DWORD  dwPermanentCardID;
  DWORD  dwCardNameSize;
  DWORD  dwCardNameOffset;
  DWORD  dwCardNumberDigits;
  DWORD  dwSameAreaRuleSize;
  DWORD  dwSameAreaRuleOffset;
  DWORD  dwLongDistanceRuleSize;
  DWORD  dwLongDistanceRuleOffset;
  DWORD  dwInternationalRuleSize;
  DWORD  dwInternationalRuleOffset;
  DWORD  dwOptions;
} LINECARDENTRY, FAR *LPLINECARDENTRY;

The LINECARDENTRY structure describes a calling card.

dwPermanentCardID

The permanent ID that identifies the card.

dwCardNameSize
dwCardNameOffset

Contains a NULL-terminated ASCII string (size includes the NULL) that describes the card in a user-friendly manner.

dwCardNumberDigits

Specifies the number of digits in the existing card number. The card number itself is not return for security reasons (it is stored in scrambled form by TAPI). The application can use this to insert filler bytes into a text control in "password" mode to show that a number exists.

dwSameAreaRuleSize
dwSameAreaRuleOffset

Specifies the offset in bytes from the beginning of the LINETRANSLATECAPS structure and the total number of bytes in the dialing rule defined for calls to numbers in the same area code. The rule is a null-terminated ASCII string.

dwLongDistanceRuleSize
dwLongDistanceRuleOffset

Specifies the offset in bytes from the beginning of the LINETRANSLATECAPS structure and the total number of bytes in the dialing rule defined for calls to numbers in the other areas in the same country. The rule is a null-terminated ASCII string.

dwInternationalRuleSize
dwInternationalRuleOffset

Specifies the offset in bytes from the beginning of the LINETRANSLATECAPS structure and the total number of bytes in the dialing rule defined for calls to numbers in other countries. The rule is a null-terminated ASCII string.

dwOptions

Indicates other settings associated with this calling card, using the LINECARDOPTION_ set of constants.

Older applications will have been compiled without knowledge of these new fields, and using a SIZEOF LINECARDENTRY smaller than the new size. Since this is an array in the variable portion of a LINETRANSLATECAPS structure, it is imperitive that older applications receive LINECARDENTRY structures in the format they previously expected, or they will not be able to index through the array properly. The application passes in a dwAPIVersion parameter with the lineGetTranslateCaps function, which can be used for guidance by TAPI in handling this situation. lineGetTranslateCaps should use the LINECARDENTRY fields and size that match the indicated API version, when building the LINETRANSLATECAPS structure to be returned to the application.

No extensions.


 LINECOUNTRYENTRY

[New - Windows 95]

typedef struct linecountryentry_tag {
  DWORD  dwCountryID;
  DWORD  dwCountryCode;
  DWORD  dwNextCountryID;
  DWORD  dwCountryNameSize;
  DWORD  dwCountryNameOffset;
  DWORD  dwSameAreaRuleSize;
  DWORD  dwSameAreaRuleOffset;
  DWORD  dwLongDistanceRuleSize;
  DWORD  dwLongDistanceRuleOffset;
  DWORD  dwInternationalRuleSize;
  DWORD  dwInternationalRuleOffset;
} LINECOUNTRYENTRY, FAR *LPLINECOUNTRYENTRY;

The LINECOUNTRYENTRY structure provides the information for a single country entry. An array of 1 or more of these structures is returned as part of the LINECOUNTRYLIST structure returned by the function lineGetCountry.

dwCountryID

Specifies the country ID of the entry. The country ID is an internal identifier which allows multiple entries to exist in the country list with the same country code (for example, all countries in North America and the Caribbean share country code 1, but require separate entries in the list).

dwCountryCode

Specifies the actual country code of the country represented by the entry (i.e., the digits that would be dialed in an international call). Only this value should ever be displayed to users (country IDs should never be displayed, as they would be confusing).

dwNextCountryID

Specifies the country ID of the next entry in the country list. Because country codes and IDs are not assigned in any regular numeric sequence, the country list is a single linked list, with each entry pointing to the next. The last country in the list has a dwNextCountryID value of 0. When the LINECOUNTRYLIST structure is used to obtain the entire list, the entries in the list will be in sequence as linked by their dwNextCountryID fields.

dwCountryNameSize
dwCountryNameOffset

The size in bytes and the offset in bytes from the beginning of the LINECOUNTRYLIST structure of a null-terminated string giving the name of the country.

dwSameAreaRuleSize
dwSameAreaRuleOffset

The size in bytes and the offset in bytes from the beginning of the LINECOUNTRYLIST structure of a null-terminated ASCII string containing the dialing rule for direct-dialed calls to the same area code.

dwLongDistanceRuleSize
dwLongDistanceRuleOffset

The size in bytes and the offset in bytes from the beginning of the LINECOUNTRYLIST structure of a null-terminated ASCII string containing the dialing rule for direct-dialed calls to other areas in the same country.

dwInternationalRuleSize
dwInternationalRuleOffset

The size in bytes and the offset in bytes from the beginning of the LINECOUNTRYLIST structure of a null-terminated ASCII string containing the dialing rule for direct-dialed calls to other countries.

Not extensible.

Because this structure is returned by a new function, backward compatibility is not an issue at this time.


 LINECOUNTRYLIST

[New - Windows 95]

typedef struct linecountrylist_tag {
    DWORD  dwTotalSize;
    DWORD  dwNeededSize;
    DWORD  dwUsedSize;

    DWORD  dwNumCountries;
    DWORD  dwCountryListSize;
    DWORD  dwCountryListOffset;
} LINECOUNTRYLIST, FAR *LPLINECOUNTRYLIST;

The LINECOUNTRYLIST structure describes a list of countries. A structure of this type is returned by the function lineGetCountry.

dwTotalSize

The total size in bytes allocated to this data structure.

dwNeededSize

The size in bytes for this data structure that is needed to hold all the returned information.

dwUsedSize

The size in bytes of the portion of this data structure that contains useful information.

dwNumCountries

Specifies the number of LINECOUNTRYENTRY structures present in the array denominated by dwCountryListSize and dwCountryListOffset.

dwCountryListSize
dwCountryListOffset

The size in bytes and the offset in bytes from the beginning of this data structure of an array of LINECOUNTRYENTRY elements which provide the information on each country.

Not extensible.

Because this structure is returned by a new function, backward compatibility is not an issue at this time.


 LINEDEVCAPS

[New - Windows 95]

typedef struct linedevcaps_tag {
  DWORD  dwTotalSize;
  DWORD  dwNeededSize;
  DWORD  dwUsedSize;

  DWORD  dwProviderInfoSize;
  DWORD  dwProviderInfoOffset;

  DWORD  dwSwitchInfoSize;
  DWORD  dwSwitchInfoOffset;

  DWORD  dwPermanentLineID;
  DWORD  dwLineNameSize;
  DWORD  dwLineNameOffset;
  DWORD  dwStringFormat;

  DWORD  dwAddressModes;
  DWORD  dwNumAddresses;
  DWORD  dwBearerModes;
  DWORD  dwMaxRate;
  DWORD  dwMediaModes;

  DWORD  dwGenerateToneModes;
  DWORD  dwGenerateToneMaxNumFreq;
  DWORD  dwGenerateDigitModes;
  DWORD  dwMonitorToneMaxNumFreq;
  DWORD  dwMonitorToneMaxNumEntries;
  DWORD  dwMonitorDigitModes;
  DWORD  dwGatherDigitsMinTimeout;
  DWORD  dwGatherDigitsMaxTimeout;

  DWORD  dwMedCtlDigitMaxListSize;
  DWORD  dwMedCtlMediaMaxListSize;
  DWORD  dwMedCtlToneMaxListSize;
  DWORD  dwMedCtlCallStateMaxListSize;

  DWORD  dwDevCapFlags;
  DWORD  dwMaxNumActiveCalls;
  DWORD  dwAnswerMode;
  DWORD  dwRingModes;
  DWORD  dwLineStates;

  DWORD  dwUUIAcceptSize;
  DWORD  dwUUIAnswerSize;
  DWORD  dwUUIMakeCallSize;
  DWORD  dwUUIDropSize;
  DWORD  dwUUISendUserUserInfoSize;
  DWORD  dwUUICallInfoSize;

  LINEDIALPARAMS  MinDialParams;
  LINEDIALPARAMS  MaxDialParams;
  LINEDIALPARAMS  DefaultDialParams;

  DWORD  dwNumTerminals;
  DWORD  dwTerminalCapsSize;
  DWORD  dwTerminalCapsOffset;
  DWORD  dwTerminalTextEntrySize;
  DWORD  dwTerminalTextSize;
  DWORD  dwTerminalTextOffset;

  DWORD  dwDevSpecificSize;
  DWORD  dwDevSpecificOffset;

  DWORD  dwLineFeatures;
} LINEDEVCAPS, FAR *LPLINEDEVCAPS;

The LINEDEVCAPS structure describes the capabilities of a line device.

dwTotalSize

The total size in bytes allocated to this data structure.

dwNeededSize

The size in bytes for this data structure that is needed to hold all the returned information.

dwUsedSize

The size in bytes of the portion of this data structure that contains useful information.

dwProviderInfoSize
dwProviderInfoOffset

The size in bytes of the variably sized field containing service provider information, and the offset in bytes from the beginning of this data structure. The dwProviderInfoSize/Offset field is intended to provide information about the provider hardware and/or software, such as the vendor name and version numbers of hardware and software. This information can be useful when a user needs to call customer service with problems regarding the provider.

dwSwitchInfoSize
dwSwitchInfoOffset

The size in bytes of the variably sized device field containing switch information, and the offset in bytes from the beginning of this data structure. The dwSwitchInfoSize/Offset field is intended to provide information about the switch to which the line device is connected, such as the switch manaufacturer, the model name, the software version, and so on. This information can be useful when a user needs to call customer service with problems regarding the switch.

dwPermanentLineID

Specifies the permanent DWORD identifier by which the line device is known in the system's configuration. It is a permanent name for the line device. This permanent name (as opposed to dwDevice ID) does not change as lines are added or removed from the system. It can therefore be used to link line-specific information in INI files (or other files) in a way that is not affected by adding or removing other lines.

dwLineNameSize
dwLineNameOffset

The size in bytes of the variably sized device field containing user configurable name for this line device, and the offset in bytes from the beginning of this data structure. This name can be configured by the user when configuring the line device's service provider, and is provided for the user's convenience.

dwStringFormat

Specifies the string format used with this line device. This field uses the following STRINGFORMAT_ constants:

STRINGFORMAT_ASCII

The ASCII string format using one byte per character.

STRINGFORMAT_DBCS

The DBCS string format using two bytes per character.

STRINGFORMAT_UNICODE

The unicode string format using two bytes per character.

dwAddressModes

Specifies the mode by which the originating address is specified. This field uses the LINEADDRESSMODE_ constants.

dwNumAddresses

Specifies the number of addresses associated with this line device. Individual addresses are referred to by address IDs. Address IDs range from zero to one less than the value indicated by dwNumAddresses.

dwBearerModes

This flag array indicates the different bearer modes that the address is able to support. It uses the following LINEBEARERMODE_ constants:

LINEBEARERMODE_VOICE

This is a regular 3.1kHz analog voice grade bearer service. Bit integrity is not assured. Voice can support fax and modem media modes.

LINEBEARERMODE_SPEECH

This corresponds to G.711 speech transmission on the call. The network may use processing techniques such as analog transmission, echo cancellation and compression/decompression. Bit integrity is not assured. Speech is not intended to support fax and modem media modes.

LINEBEARERMODE_MULTIUSE

The multi-use mode defined by ISDN.

LINEBEARERMODE_DATA

The unrestricted data transfer on the call. The data rate is specified separately.

LINEBEARERMODE_ALTSPEECHDATA

The alternate transfer of speech or unrestricted data on the same call (ISDN).

LINEBEARERMODE_NONCALLSIGNALING

This corresponds to a non-call-associated signaling connection from the application to the service provider or switch (treated as a "media stream" by the Telephony API).

LINEBEARERMODE_PASSTHROUGH

When a call is active in LINEBEARERMODE_PASSTHROUGH, the service provider gives direct access to the attached hardware for control by the application. This mode is used primarily by applications desiring temporary direct control over asynchronous modems, accessed via the Win32 comm functions, for the purpose of configuring or using special features not otherwise supported by the service provider.

dwMaxRate

This field contains the maximum data rate in bits per second for information exchange over the call.

dwMediaModes

This flag array indicates the different media modes the address is able to support. It uses the following LINEMEDIAMODE_ constants:

LINEMEDIAMODE_UNKNOWN

A media stream exists but its mode is not known. This corresponds to a call with an unclassified media type. In typical analog telephony environments, an inbound call's media mode may be unknown until after the call has been answered and the media stream filtered to make a determination.

LINEMEDIAMODE_INTERACTIVEVOICE

The presence of voice energy on the call and the call is treated as an interactive call with humans on both ends.

LINEMEDIAMODE_AUTOMATEDVOICE

The presence of voice energy on the call and the voice is locally handled by an automated application.

LINEMEDIAMODE_DATAMODEM

A data modem session on the call.

LINEMEDIAMODE_G3FAX

A group 3 fax is being sent or received over the call.

LINEMEDIAMODE_TDD

A TDD (Telephony Devices for the Deaf) session on the call.

LINEMEDIAMODE_G4FAX

A group 4 fax is being sent or received over the call.

LINEMEDIAMODE_DIGITALDATA

Digital data being transmitted over the call.

LINEMEDIAMODE_TELETEX

A teletex session on the call. Teletex is one of the telematic services.

LINEMEDIAMODE_VIDEOTEX

A videotex session on the call. Videotex is one the telematic services.

LINEMEDIAMODE_TELEX

A telex session on the call. Telex is one the telematic services.

LINEMEDIAMODE_MIXED

A mixed session on the call. Mixed is one the ISDN telematic services.

LINEMEDIAMODE_ADSI

An ADSI (Analog Display Services Interface) session on the call.

dwGenerateToneModes

Specifies the different kinds of tones that can be generated on this line. This field uses the following LINETONEMODE_ constants:

LINETONEMODE_CUSTOM

The tone is a custom tone defined by the specified frequencies.

LINETONEMODE_RINGBACK

The tone to be generated is ringback tone.

LINETONEMODE_BUSY

The tone is a standard (station) busy tone.

LINETONEMODE_BEEP

The tone is a beep, as used to announce the beginning of a recording.

LINETONEMODE_BILLING

The tone is billing information tone such as a credit card prompt tone.

dwGenerateToneMaxNumFreq

This field contains the maximum number of frequencies that can be specified in describing a general tone using the LINEGENERATETONE data structure when generating a tone using lineGenerateTone. A value of zero indicates that tone generation is not available.

dwGenerateDigitModes

This field specifies the digit modes than can be generated on this line. It uses the following LINEDIGITMODE_ constants:

LINEDIGITMODE_PULSE

Generate digits as pulse/rotary pulse sequences.

LINEDIGITMODE_DTMF

Generate digits as DTMF tones.

dwMonitorToneMaxNumFreq

This field contains the maximum number of frequencies that can be specified in describing a general tone using the LINEMONITORTONE data structure when monitoring a general tone using lineMonitorTones. A value of zero indicates that tone monitor is not available.

dwMonitorToneMaxNumEntries

This field contains the maximum number of entries that can be specified in a tone list to lineMonitorTones.

dwMonitorDigitModes

This field specifies the digit modes than can be detected on this line. It uses the following LINEDIGITMODE_ constants:

LINEDIGITMODE_PULSE

Detect digits as audible clicks that are the result of rotary pulse sequences.

LINEDIGITMODE_DTMF

Detect digits as DTMF tones.

LINEDIGITMODE_DTMFEND

Detect the down edges of digits detected as DTMF tones.

dwGatherDigitsMinTimeout
dwGatherDigitsMaxTimeout

These fields contain the minimum and maximum values in milliseconds that can be specified for both the first digit and inter-digit timeout values used by lineGatherDigits. If both these field are zero, timeouts are not supported.

dwMedCtlDigitMaxListSize
dwMedCtlMediaMaxListSize
dwMedCtlToneMaxListSize
dwMedCtlCallStateMaxListSize

These fields contain the maximum number of entries that can be specified in the digit list, the media list, the tone list, and the call state list parameters of lineSetMediaControl respectively.

dwDevCapFlags

This field specifies various Boolean device capabilities. It uses the following LINEDEVCAPFLAGS_ constants:

LINEDEVCAPFLAGS_CROSSADDRCONF

Specifies whether calls on different addresses on this line can be conferenced.

LINEDEVCAPFLAGS_HIGHLEVCOMP

Specifies whether high-level compatibility information elements are supported on this line.

LINEDEVCAPFLAGS_LOWLEVCOMP

Specifies whether low-level compatibility information elements are supported on this line.

LINEDEVCAPFLAGS_MEDIACONTROL

Specifies whether media-control operations are available for calls at this line.

LINEDEVCAPFLAGS_MULTIPLEADDR

Specifies whether lineMakeCall or lineDial are able to deal with multiple addresses at once (such as for inverse multiplexing).

LINEDEVCAPFLAGS_CLOSEDROP

Specifies what happens when an open line is closed while the application has calls active on the line. If TRUE, then a lineClose will drop (that is, clear) all calls on the line if the application is the sole owner of those calls. Knowing the setting of this flag ahead of time makes it possible for the application to display an OK/Cancel dialog box for the user, warning that the active call will be lost. If CLOSEDROP is FALSE, a lineClose will not automatically drop any calls that are still active on the line if the service provider knows that some other device can keep the call alive. For example, if an analog line has the computer and phoneset both connect directly to them (in a party-line configuration), the service provider should set the flag to FALSE, as the offhook phone will automatically keep the call active even after the computer powers down.

LINEDEVCAPFLAGS_DIALBILLING

LINEDEVCAPFLAGS_DIALQUIET

LINEDEVCAPFLAGS_DIALDIALTONE

These flags indicate whether the "$", "@", or "W" dialable string modifier is supported for a given line device.  It is TRUE if the modifier is supported; otherwise, FALSE. The "?" (prompt user to continue dialing) is never supported by a line device. These flags allow an application to determine "up front" which modifiers would result in the generation of a LINEERR. The application has the choice of pre-scanning dialable strings for unsupported characters, or passing the "raw" string from lineTranslateAddress directly to the provider as part of lineMakeCall (lineDial, etc.) and let the function generate an error to tell it which unsupported modifier occurs first in the string.

dwMaxNumActiveCalls

This field provides the maximum number of (minimum bandwidth) calls that can be active (connected) on the line at any one time. The actual number of active calls may be lower if higher bandwidth calls have been established on the line.

dwAnswerMode

This field specifies the effect on the active call when answering another offering call on a line device. This field uses the following LINEANSWERMODE_ constants:

LINEANSWERMODE_NONE

Answering another call on the same line has no effect on the existing active call(s) on the line.

LINEANSWERMODE_DROP

The currently active call will be automatically dropped.

LINEANSWERMODE_HOLD

The currently active call will automatically be placed on hold.

dwRingModes

This field contains the number of different ring modes that can be reported in the LINE_LINEDEVSTATE message with the ringing indication. Different ring modes range from one to dwRingModes. Zero indicates no ring.

dwLineStates

This field specifies the different line status components for which the application may be notified in a LINE_LINEDEVSTATE message on this line. It uses the following LINEDEVSTATE_ constants:

LINEDEVSTATE_OTHER

Device-status items other than those listed below have changed. The application should check the current device status to determine which items have changed.

LINEDEVSTATE_RINGING

The switch tells the line to alert the user.

LINEDEVSTATE_CONNECTED

The line was previously disconnected and is now connected to TAPI.

LINEDEVSTATE_DISCONNECTED

This line was previously connected and is now disconnected from TAPI.

LINEDEVSTATE_MSGWAITON

The "message waiting" indicator is turned on.

LINEDEVSTATE_MSGWAITOFF

The "message waiting" indicator is turned off.

LINEDEVSTATE_NUMCOMPLETIONS

The number of outstanding call completions on the line device has changed.

LINEDEVSTATE_INSERVICE

The line is connected to TAPI. This happens when TAPI is first activated or when the line wire is physically plugged in and in service at the switch while TAPI is active.

LINEDEVSTATE_OUTOFSERVICE

The line is out of service at the switch or physically disconnected. TAPI cannot be used to operate on the line device.

LINEDEVSTATE_MAINTENANCE

Maintenance is being performed on the line at the switch. TAPI cannot be used to operate on the line device.

LINEDEVSTATE_OPEN

The line has been opened.

LINEDEVSTATE_CLOSE

The line has been closed.

LINEDEVSTATE_NUMCALLS

The number of calls on the line device has changed.

LINEDEVSTATE_TERMINALS

The terminal settings have changed.

LINEDEVSTATE_ROAMMODE

The roam mode of the line device has changed.

LINEDEVSTATE_BATTERY

The battery level has changed significantly (cellular).

LINEDEVSTATE_SIGNAL

The signal level has changed significantly (cellular).

LINEDEVSTATE_DEVSPECIFIC

The line's device-specific information has changed.

LINEDEVSTATE_REINIT

Items have changed in the configuration of line devices. To become aware of these changes (such as for the appearance of new line devices), the application should reinitialize its use of TAPI. The hDevice parameter is left NULL for this state change as it applies to any of the lines in the system.

LINEDEVSTATE_LOCK

The locked status of the line device has changed.

LINEDEVSTATE_CAPSCHANGE

Indicates that, due to configuration changes made by the user or other circumstances, one or more of the fields in the LINEDEVCAPS structure for the address have changed. The application should use lineGetDevCaps to read the updated structure. If a service provider sends a LINE_LINEDEVSTATE message containing this value to TAPI, TAPI will pass it along to applications which have negotiated this or a subsequent API version; applications negotiating a previous API version will receive LINE_LINEDEVSTATE messages specifying LINEDEVSTATE_REINIT, requiring them to shutdown and reinitialize their connection to TAPI in order to obtain the updated information.

LINEDEVSTATE_CONFIGCHANGE

Indicates that configuration changes have been made to one or more of the media devices associated with the line device. The application, if it desires, may use lineGetDevConfig to read the updated information. If a service provider sends a LINE_LINEDEVSTATE message containing this value to TAPI, TAPI will pass it along to applications which have negotiated this or a subsequent API version; applications negotiating a previous API version will not receive any notification.

LINEDEVSTATE_TRANSLATECHANGE

Indicates that, due to configuration changes made by the user or other circumstances, one or more of the fields in the LINETRANSLATECAPS structure have changed. The application should use lineGetTranslateCaps to read the updated structure. If a service provider sends a LINE_LINEDEVSTATE message containing this value to TAPI, TAPI will pass it along to applications which have negotiated this or a subsequent API version; applications negotiating a previous API version will receive LINE_LINEDEVSTATE messages specifying LINEDEVSTATE_REINIT, requiring them to shutdown and reinitialize their connection to TAPI in order to obtain the updated information.

LINEDEVSTATE_COMPLCANCEL

Indicates that the call completion identified by the completion ID contained in parameter dwParam2 of the LINE_LINEDEVSTATE message has been externally cancelled and is no longer considered valid (if that value were to be passed in a subsequent call to lineUncompleteCall, the function would fail with LINEERR_INVALCOMPLETIONID). If a service provider sends a LINE_LINEDEVSTATE message containing this value to TAPI, TAPI will pass it along to applications which have negotiated this or a subsequent API version; applications negotiating a previous API version will not receive any notification.

LINEDEVSTATE_REMOVED

Indicates that the device is being removed from the system by the service provider (most likely through user action, via a control panel or similar utility). A LINE_LINEDEVSTATE message with this value will normally be immediately followed by a LINE_CLOSE message on the device. Subsequent attempts to access the device prior to TAPI being reinitialized will result in LINEERR_NODEVICE being returned to the application. If a service provider sends a LINE_LINEDEVSTATE message containing this value to TAPI, TAPI will pass it along to applications which have negotiated this or a subsequent API version; applications negotiating a previous API version will not receive any notification.

dwUUIAcceptSize

This field specifies the maximum size of user-to-user information that can be sent during a call accept.

dwUUIAnswerSize

This field specifies the maximum size of user-to-user information that can be sent during a call answer.

dwUUIMakeCallSize

This field specifies the maximum size of user-to-user information that can be sent during a make call.

dwUUIDropSize

This field specifies the maximum size of user-to-user information that can be sent during a call drop.

dwUUISendUserUserInfoSize

This field specifies the maximum size of user-to-user information that can be sent separately any time during a call with lineSendUserUserInfo.

dwUUICallInfoSize

This field specifies the maximum size of user-to-user information that can be received in the LINECALLINFO structure.

MinDialParams
MaxDialParams

These fields contain the minimum and maximum values for the dial parameters in milliseconds that can be set for calls on this line. Dialing parameters can be set to values in this range. The granularity of the actual settings is service provider-specific.

DefaultDialParams

This field contains the default dial parameters used for calls on this line. These parameter values can be overridden on a per-call basis.

dwNumTerminals

Specifies the number of terminals that can be set for this line device, its addresses, or its calls. Individual terminals are referred to by terminal IDs and range from zero to one less than the value indicated by dwNumTerminals.

dwTerminalCapsSize
dwTerminalCapsOffset

The size in bytes and the offset in bytes from the beginning of this data structure of the variably sized device field containing an array with entries of type LINETERMCAPS. This array is indexed by terminal IDs, in the range from zero to dwNumTerminals minus one. Each entry in the array specifies the terminal device capabilities of the corresponding terminal.

dwTerminalTextEntrySize

Specifies the size in bytes of each of the terminal text descriptions pointed at by dwTerminalTextSize/Offset.

dwTerminalTextSize
dwTerminalTextOffset

The size in bytes of the variably sized field containing descriptive text about each of the line's available terminals, and the offset in bytes from the beginning of this data structure  Each message is dwTerminalTextEntrySize bytes long. The string format of these textual descriptions is indicated by dwStringFormat in the line's device capabilities.

dwDevSpecificSize
dwDevSpecificOffset

The size in bytes of the variably sized device-specific field, and the offset in bytes from the beginning of this data structure

dwLineFeatures

This field specifies the features available for this line using the LINEFEATURE_ constants. Invoking a supported feature requires the line to be in the proper state and the underlying line device to be opened in a compatible mode. A zero in a bit position indicates that the corresponding feature is never available. A one indicates that the corresponding feature may be available if the line is in the appropriate state for the operation to be meaningful. This field allows an application to discover which line features can be (and which can never be) supported by the device.

Device-specific extensions should use the DevSpecific (dwDevSpecificSize and dwDevSpecificOffset) variably sized area of this data structure.

Older applications will have been compiled without this field in the LINEDEVCAPS structure, and using a SIZEOF LINEDEVCAPS smaller than the new size. The application passes in a dwAPIVersion parameter with the lineGetDevCaps function, which can be used for guidance by TAPI in handling this situation. If the application passes in a dwTotalSize less than the size of the fixed portion of the structure as defined in the dwAPIVersion specified, LINEERR_STRUCTURETOOSMALL will be returned. If sufficient memory has been allocated by the application, before calling TSPI_lineGetDevCaps, TAPI will set the dwNeededSize and dwUsedSize fields to the fixed size of the structure as it existed in the specified API version.

New service providers (which support the new API version) must examine the API version passed in. If the API version is less than the highest version supported by the provider, the service provider must not fill in fields not supported in older API versions, as these would fall in the variable portion of the older structure.

New applications must be cognizant of the API version negotiated, and not examine the contents of fields in the fixed portion beyond the original end of the fixed portion of the structure for the negotiated API version.

If the LINEBEARERMODE_DATA bit is set in dwBearerModes member, the dwMaxRate member indicates the maximum rate of digital transmission on the bearer channel. The dwMaxRate member of the LINEDEVCAPS structure can contain valid values even if the dwBearerModes member of the LINEDEVCAPS structure is not set to LINEBEARERMODE_DATA.

If LINEBEARERMODE_DATA is not set in dwBearerModes, but the LINEBEARERMODE_VOICE value is set and the LINEMEDIAMODE_DATAMODEM value is set in the dwMediaModes member, the dwMaxRate member indicates the maximum SYNCHRONOUS (DCE) bit rate on the phone line for the attached modem or functional equivalent. For example, if the modem's fastest modulation speed is V.32bis at 14,400bps, dwMaxRate will equal 14400. This is not the fastest DTE port rate (which would most likely be 38400, 57600, or 115200), but the fastest bit rate the modem supports on the phone line.

The application must be careful to check to see that LINEBEARERMODE_DATA is not set, in order to avoid misinterpreting the dwMaxRate member. It is likely to be 64000 or higher if LINEBEARERMODE_DATA is set.

It should also be noted that if the modem has not been specifically identified (for example, it is a "generic" modem), the figure indicated is a "best guess" based on examination of the modem.


 LINEDEVSTATUS

[New - Windows 95]

typedef struct linedevstatus_tag {
  DWORD  dwTotalSize;
  DWORD  dwNeededSize;
  DWORD  dwUsedSize;

  DWORD  dwNumOpens;
  DWORD  dwOpenMediaModes;
  DWORD  dwNumActiveCalls;
  DWORD  dwNumOnHoldCalls;
  DWORD  dwNumOnHoldPendCalls;
  DWORD  dwLineFeatures;
  DWORD  dwNumCallCompletions;
  DWORD  dwRingMode;
  DWORD  dwSignalLevel;
  DWORD  dwBatteryLevel;
  DWORD  dwRoamMode;

  DWORD  dwDevStatusFlags;

  DWORD  dwTerminalModesSize;
  DWORD  dwTerminalModesOffset;

  DWORD  dwDevSpecificSize;
  DWORD  dwDevSpecificOffset;
} LINEDEVSTATUS, FAR *LPLINEDEVSTATUS;

The LINEDEVSTATUS structure describes the current status of a line device.

dwTotalSize

The total size in bytes allocated to this data structure.

dwNeededSize

The size in bytes for this data structure that is needed to hold all the returned information.

dwUsedSize

The size in bytes of the portion of this data structure that contains useful information.

dwNumOpens

Specifies the number of active opens on the line device.

dwOpenMediaModes

This bit array indicates for which media modes the line device is currently open.

dwNumActiveCalls

The number of calls on the line in call states other than idle, onhold, onholdpendingtransfer, and onholdpendingconference.

dwNumOnHoldCalls

The number of calls on the line in the onhold state.

dwNumOnHoldPendingCalls

The number of calls on the line in the onholdpendingtransfer or onholdpendingconference states.

dwLineFeatures

This field specifies the line-related API functions that are currently available on this line. It uses the following LINEFEATURE_ constants:

LINEFEATURE_DEVSPECIFIC

Device-specific operations can be used on the line.

LINEFEATURE_DEVSPECIFICFEAT

Device-specific features can be used on the line.

LINEFEATURE_FORWARD

Forwarding of all addresses can be used on the line.

LINEFEATURE_MAKECALL

An outbound call can be placed on this line using an unspecified address.

LINEFEATURE_SETMEDIACONTROL

Media control can be set on this line.

LINEFEATURE_SETTERMINAL

Terminal modes for this line can be set.

dwNumCallCompletions

Specifies the number of outstanding call completion requests on the line.

dwRingMode

Specifies the current ring mode on the line device.

dwBatteryLevel

Specifies the current battery level of the line device hardware. This is a value in the range 0x00000000 (battery empty) to 0x0000FFFF (battery full).

dwSignalLevel

Specifies the current signal level of the connection on the line. This is a value in the range 0x00000000 (weakest signal) to 0x0000FFFF (strongest signal).

dwRoamMode

Specifies the current roam mode of the line device. It uses the following LINEROAMMODE_ constants:

LINEROAMMODE_UNKNOWN

The roam mode is currently unknown but may become known later.

LINEROAMMODE_UNAVAIL

The roam mode is unavailable and will not be known.

LINEROAMMODE_HOME

The line is connected to the home network node.

LINEROAMMODE_ROAMA

The line is connected to the Roam-A carrier and calls are charged accordingly.

LINEROAMMODE_ROAMB

The line is connected to the Roam-B carrier and calls are charged accordingly.

dwDevStatusFlags

The size in bytes of this data structure that contains useful information, of type LINEDEVSTATUSFLAGS_.

LINEDEVSTATUSFLAGS_CONNECTED

Specifies whether the line is connected to TAPI. If TRUE, the line is connected and API is able to operate on the line device. If FALSE, the line is disconnected and the application is unable to control the line device using TAPI.

LINEDEVSTATUSFLAGS_LOCKED

This bit is most often used with line devices associated with cellular phones. Many cellular phones have a security mechanism that requires the entry of a password to enable the phone to place calls. This bit may be used to indicate to applications that the phone is locked and cannot place calls until the password is entered on the user interface of the phone, so that the application can present an appropriate alert to the user.

LINEDEVSTATUSFLAGS_MSGWAIT

This field indicates whether the line has a message waiting. If TRUE, a message is waiting; if FALSE, no message is waiting.

LINEDEVSTATUSFLAGS_INSERVICE

This field indicates whether the line is in service. If TRUE, the line is in service; if FALSE, the line is out of service.

dwTerminalModesSize
dwTerminalModesOffset

The size in bytes of the variably sized device field containing an array with DWORD-sized entries, and the offset in bytes from the beginning of this data structure. This array is indexed by terminal IDs, in the range from zero to dwNumTerminals minus one. Each entry in the array specifies the current terminal modes for the corresponding terminal set using the lineSetTerminal operation for this line. It uses the following LINETERMMODE_ constants:

LINETERMMODE_LAMPS

These are lamp events sent from the line to the terminal.

LINETERMMODE_BUTTONS

These are button-press events sent from the terminal to the line.

LINETERMMODE_DISPLAY

This is display information sent from the line to the terminal.

LINETERMMODE_RINGER

This is ringer-control information sent from the switch to the terminal.

LINETERMMODE_HOOKSWITCH

These are hookswitch event sent between the terminal and the line.

LINETERMMODE_MEDIATOLINE

This is the unidirectional media stream from the terminal to the line associated with a call on the line. Use this value when the routing of both unidirectional channels of a call's media stream can be controlled independently.

LINETERMMODE_MEDIAFROMTERM

This is the unidirectional media stream from the line to the terminal associated with a call on the line. Use this value when the routing of both unidirectional channels of a call's media stream can be controlled independently.

LINETERMMODE_MEDIABIDIRECT

This is the bidirectional media stream associated with a call on the line and the terminal. Use this value when the routing of both unidirectional channels of a call's media stream cannot be controlled independently.

dwDevSpecificSize
dwDevSpecificOffset

The size in bytes of the variably sized device-specific field, and the offset in bytes from the beginning of this data structure.

Device-specific extensions should use the DevSpecific (dwDevSpecificSize and dwDevSpecificOffset) variably sized area of this data structure.


 LINEDIALPARAMS

[New - Windows 95]

typedef struct linedialparams_tag {
  DWORD  dwDialPause;
  DWORD  dwDialSpeed;
  DWORD  dwDigitDuration;
  DWORD  dwWaitForDialtone;
} LINEDIALPARAMS, FAR *LPLINEDIALPARAMS;

The LINEDIALPARAMS structure specifies a collection of dialing-related fields.

dwDialPause

Specifies the duration in milliseconds of a comma in the dialable address.

dwDialSpeed

Specifies the inter-digit time period in milliseconds between successive digits.

dwDigitDuration

Specifies the duration in milliseconds of a digit.

dwWaitForDialtone

Specifies the maximum amount of time that should be waited for dialtone when a 'W' is used in the dialable address.

No extensions.

When a value of zero is specified for a field, the default value for that field is used. If a non-zero value is specified for a field which is outside the range specified by the corresponding fields in MinDialParams and MaxDialParams in the LINEDEVCAPS structure, the nearest value within the valid range is used instead.

The lineMakeCall function allows an application to adjust the dialing parameters to be used for the call. The lineSetCallParams function can be used to adjust the dialing parameters of an existing call. The LINECALLINFO structure lists the call's current dialing parameters.


 LINEEXTENSIONID

[New - Windows 95]

typedef struct lineextensionid_tag {
  DWORD  dwExtensionID0;
  DWORD  dwExtensionID1;
  DWORD  dwExtensionID2;
  DWORD  dwExtensionID3;
} LINEEXTENSIONID, FAR *LPLINEEXTENSIONID;

The LINEEXTENSIONID structure describes an extension ID. Extension IDs are used to identify service provider-specific extensions for line devices.

dwExtensionID0
dwExtensionID1
dwExtensionID2
dwExtensionID3

These four DWORD-sized fields together specify a universally unique extension ID that identifies a line device class extension.

No extensions.

Extension IDs are generated using an SDK-provided generation utility.


 LINEFORWARD

[New - Windows 95]

typedef struct lineforward_tag {
  DWORD  dwForwardMode;

  DWORD  dwCallerAddressSize;
  DWORD  dwCallerAddressOffset;

  DWORD  dwDestCountryCode;
  DWORD  dwDestAddressSize;
  DWORD  dwDestAddressOffset;
} LINEFORWARD, FAR *LPLINEFORWARD;

The LINEFORWARD structure describes an entry of the forwarding instructions.

dwForwardMode

Specifies the types of forwarding. dwForwardMode can have only a single bit set. This field uses the following  LINEFORWARDMODE_ constants:

LINEFORWARDMODE_UNCOND

Forward all calls unconditionally, irrespective of their origin. Use this value when unconditional forwarding for internal and external calls cannot be controlled separately. Unconditional forwarding overrides forwarding on busy and/or no answer conditions.

LINEFORWARDMODE_UNCONDINTERNAL

Forward all internal calls unconditionally. Use this value when unconditional forwarding for internal and external calls can be controlled separately.

LINEFORWARDMODE_UNCONDEXTERNAL

Forward all external calls unconditionally. Use this value when unconditional forwarding for internal and external calls can be controlled separately.

LINEFORWARDMODE_UNCONDSPECIFIC

Unconditionally forward all calls that originated at a specified address (selective call forwarding).

LINEFORWARDMODE_BUSY

Forward all calls on busy, irrespective of their origin. Use this value when forwarding for internal and external calls both on busy and on no answer cannot be controlled separately.

LINEFORWARDMODE_BUSYINTERNAL

Forward all internal calls on busy. Use this value when forwarding for internal and external calls on busy and on no answer can be controlled separately.

LINEFORWARDMODE_BUSYEXTERNAL

Forward all external calls on busy. Use this value when forwarding for internal and external calls on busy and on no answer can be controlled separately.

LINEFORWARDMODE_BUSYSPECIFIC

Forward on busy all calls that originated at a specified address (selective call forwarding).

LINEFORWARDMODE_NOANSW

Forward all calls on no answer, irrespective of their origin. Use this value when call forwarding for internal and external calls on no answer cannot be controlled separately.

LINEFORWARDMODE_NOANSWINTERNAL

Forward all internal calls on no answer. Use this value when forwarding for internal and external calls on no answer can be controlled separately.

LINEFORWARDMODE_NOANSWEXTERNAL

Forward all external calls on no answer. Use this value when forwarding for internal and external calls on no answer can be controlled separately.

LINEFORWARDMODE_NOANSWSPECIFIC

Forward all calls that originated at a specified address on no answer (selective call forwarding).

LINEFORWARDMODE_BUSYNA

Forward all calls on busy/no answer, irrespective of their origin. Use this value when forwarding for internal and external calls on both busy and on no answer cannot be controlled separately.

LINEFORWARDMODE_BUSYNAINTERNAL

Forward all internal calls on busy/no answer. Use this value when call forwarding on busy and on no answer cannot be controlled separately for internal calls.

LINEFORWARDMODE_BUSYNAEXTERNAL

Forward all external calls on busy/no answer. Use this value when call forwarding on busy and on no answer cannot be controlled separately for internal calls.

LINEFORWARDMODE_BUSYNASPECIFIC

Forward on busy/no answer all calls that originated at a specified address (selective call forwarding).

LINEFORWARDMODE_UNKNOWN

Calls are forwarded, but the conditions under which forwarding will occur are not known at this time. It is possible that the conditions may become known at a future time.

LINEFORWARDMODE_UNAVAIL

Calls are forwarded, but the conditions under which forwarding will occur are not known, and will never be known by the service provider.

dwCallerAddressSize
dwCallerAddressOffset

The size in bytes of the variably sized address field containing the address of a caller to be forwarded, and the offset in bytes from the beginning of the containing data structure. dwCallerAddressSize/Offset is set to zero if dwForwardMode is not one of the following: LINEFORWARDMODE_BUSYNASPECIFIC, LINEFORWARDMODE_NOANSWSPECIFIC, LINEFORWARDMODE_UNCONDSPECIFIC, or LINEFORWARDMODE_BUSYSPECIFIC.

dwDestCountryCode

Specifies the country code of the destination address to which the call is to be forwarded.

dwDestAddressSize
dwDestAddressOffset

The size in bytes  of the variably sized address field containing the address of the address where calls are to be forwarded, and the offset in bytes from the beginning of the containing data structure.

No extensions.

Each entry in the LINEFORWARD structure specifies a forwarding request.


 LINEFORWARDLIST

[New - Windows 95]

The LINEFORWARDLIST structure describes a list of forwarding instructions.

typedef struct lineforwardlist_tag {
  DWORD  dwTotalSize;

  DWORD  dwNumEntries;
  LINEFORWARD  ForwardList[1];
} LINEFORWARDLIST, FAR *LPLINEFORWARDLIST;

The LINEFORWARDLIST structure contains the following fields:

dwTotalSize

Specifies the total size in bytes of the data structure.

dwNumEntries

Specifies number of entries in the array specified as ForwardList[ ].

ForwardList[ ]

Specifies an array of forwarding instruction. The array's entries are of type LINEFORWARD.

No extensions.

The LINEFORWARDLIST structure defines the forwarding parameters requested for forwarding calls on an address or on all addresses on a line.


 LINEGENERATETONE

[New - Windows 95]

typedef struct linegeneratetone_tag {
  DWORD  dwFrequency;
  DWORD  dwCadenceOn;
  DWORD  dwCadenceOff;
  DWORD  dwVolume;
} LINEGENERATETONE, FAR *LPLINEGENERATETONE;

The LINEGENERATETONE structure contains information about a tone to be generated.

dwFrequency

Specifies the frequency in Hertz of this tone component. A service provider may adjust (round up or down) the frequency specified by the application to fit its resolution.

dwCadenceOn

Determines the "on" duration in milliseconds of the cadence of the custom tone to be generated. Zero means no tone is generated.

dwCadenceOff

Determines the "off" duration in milliseconds of the cadence of the custom tone to be generated. Zero means no off time, that is, a constant tone.

dwVolume

Determines the volume level at which the tone is to be generated. A value of 0x0000FFFF represents full volume, and a value of 0x00000000 is silence.

No extensions.

This structure is only used for the generation of tones. It is not used for tone monitoring.


 LINELOCATIONENTRY

[New - Windows 95]

typedef struct linelocationentry_tag {
  DWORD  dwPermanentLocationID;
  DWORD  dwLocationNameSize;
  DWORD  dwLocationNameOffset;
  DWORD  dwCountryCode;

  DWORD  dwCityCodeSize;

  DWORD  dwCityCodeOffset;

  DWORD  dwPreferredCardID;
  DWORD  dwLocalAccessCodeSize;
  DWORD  dwLocalAccessCodeOffset;
  DWORD  dwLongDistanceAccessCodeSize;
  DWORD  dwLongDistanceAccessCodeOffset;
  DWORD  dwTollPrefixListSize;
  DWORD  dwTollPrefixListOffset;
  DWORD  dwCountryID;
  DWORD  dwOptions;
  DWORD  dwCancelCallWaitingSize;
  DWORD  dwCancelCallWaitingOffset;
} LINELOCATIONENTRY, FAR *LPLINELOCATIONENTRY;

The LINELOCATIONENTRY structure describes a location used to provide an address translation context.

dwPermanentLocationID

The permanent ID that identifies the location.

dwLocationNameSize
dwLocationNameOffset

Contains a NULL-terminated ASCII string (size includes the NULL) that describes the location in a user-friendly manner.

dwCountryCode

Specifies the country code of the location.

dwPreferredCardID

Specifies the preferred calling card when dialing from this location.

dwCityCodeSize
dwCityCodeOffset

Contains a NULL-terminated ASCII string specifying the city/area code associated with the location (the size includes the NULL). This information, along with the country code, can be used by applications to "default" entry fields for the user when entering phone numbers, to encourage the entry of proper canonical numbers.

dwLocalAccessCodeSize
dwLocalAccessCodeOffset

The size in bytes and the offset in bytes from the beginning of the LINETRANSLATECAPS structure of a null-terminated ASCII string containing the access code to be dialed before calls to addresses in the local calling area.

dwLongDistanceAccessCodeSize
dwLongDistanceAccessCodeOffset

The size in bytes and the offset in bytes from the beginning of the LINETRANSLATECAPS structure of a null-terminated ASCII string containing the access code to be dialed before calls to addresses outside the local calling area.

dwTollPrefixListSize
dwTollPrefixListOffset

The size in bytes and the offset in bytes from the beginning of the LINETRANSLATECAPS structure of a null-terminated ASCII string containing the toll prefix list for the location. The string will contain only prefixes consisting of the digits "0" through "9", separated from each other by a single "," (comma) character.

dwCountryID

Specifies the country ID of the country selected for the location. This can be used with the lineGetCountry function to obtain additional information about the specific country, such as the country name (the dwCountryCode field cannot be used for this purpose because country codes are not unique).

dwOptions

Indicates options in effect for this location, with values taken from the LINELOCATIONOPTION_ set of constants.

dwCancelCallWaitingSize
dwCancelCallWaitingOffset

The size in bytes and the offset in bytes from the beginning of the LINETRANSLATECAPS structure of a null-terminated ASCII string containing the dial digits and modifier characters that should be prefixed to the dialable string (after the pulse/tone character) when an application sets the LINETRANSLATEOPTION_CANCELCALLWAITING bit in the dwTranslateOptions parameter of lineTranslateAddress. If no prefix is defined, this may be indicated by dwCancelCallWaitingSize being set to 0, or by it being set to 1 and dwCancelCallWaitingOffset pointing to an empty string (single null byte).

No extensions.

Older applications will have been compiled without knowledge of these new fields, and using a SIZEOF LINELOCATIONENTRY smaller than the new size. Since this is an array in the variable portion of a LINETRANSLATECAPS structure, it is imperitive that older applications receive LINELOCATIONENTRY structures in the format they previously expected, or they will not be able to index through the array properly. The application passes in a dwAPIVersion parameter with the lineGetTranslateCaps function, which can be used for guidance by TAPI in handling this situation. lineGetTranslateCaps should use the LINELOCATIONENTRY fields and size that match the indicated API version, when building the LINETRANSLATECAPS structure to be returned to the application.


 LINEMEDIACONTROLCALLSTATE

[New - Windows 95]

typedef struct linemediacontrolcallstate_tag {
  DWORD  dwCallStates;
  DWORD  dwMediaControl;
} LINEMEDIACONTROLCALLSTATE, FAR *LPLINEMEDIACONTROLCALLSTATE;

The LINEMEDIACONTROLCALLSTATE structure describes a media action to be executed when detecting transitions into one or more call states.

dwCallStates

Specifies one or more call states. This field uses the following LINECALLSTATE_ constants:

LINECALLSTATE_IDLE

The call is idle—no call exists.

LINECALLSTATE_OFFERING

The call is being offered to the station, signaling the arrival of a new call. In some environments, a call in the offering state does not automatically alert the user. Alerting is done by the switch instructing the line to ring, and it does not affect any call states.

LINECALLSTATE_ACCEPTED

The call was offering and has been accepted. This indicates to other (monitoring) applications that the current owner application has claimed responsibility for answering the call. In ISDN, this also initiates alerting to both parties.

LINECALLSTATE_DIALTONE

The call is receiving a dial tone from the switch, which means that the switch is ready to receive a dialed number.

LINECALLSTATE_DIALING

Destination address information (a phone number) is being sent to the switch over the call. Note that the operation lineGenerateDigits does not place the line into the dialing state.

LINECALLSTATE_RINGBACK

The call is receiving ringback from the called address. Ringback indicates that the other station has been reached and is being alerted.

LINECALLSTATE_BUSY

The call is receiving a busy tone. Busy tone indicates that the call cannot be completed because either a circuit (trunk) or the remote party's station are in use.

LINECALLSTATE_SPECIALINFO

Special information is sent by the network. Special information is typically sent when the destination cannot be reached.

LINECALLSTATE_CONNECTED

The call has been established, and the connection is made. Information is able to flow over the call between the originating address and the destination address.

LINECALLSTATE_PROCEEDING

Dialing has completed and the call is proceeding through the switch or telephone network.

LINECALLSTATE_ONHOLD

The call is on hold by the switch.

LINECALLSTATE_CONFERENCED

The call is currently a member of a multiparty conference call.

LINECALLSTATE_ONHOLDPENDCONF

The call is currently on hold while it is being added to a conference.

LINECALLSTATE_ONHOLDPENDTRANSF

The call is currently on hold awaiting transfer to another number.

LINECALLSTATE_DISCONNECTED

The remote party has disconnected from the call.

LINECALLSTATE_UNKNOWN

The state of the call is not known. This may be due to limitations of the call-progress detection implementation.

dwMediaControl

Specifies the media-control action. This field uses the following LINEMEDIACONTROL_ constants:

LINEMEDIACONTROL_NONE

No change is to be made to the media stream.

LINEMEDIACONTROL_RESET

Reset the media stream. Equivalent to an end-of-input. All buffers are released.

LINEMEDIACONTROL_PAUSE

Temporarily pause the media stream.

LINEMEDIACONTROL_RESUME

Start or resume a paused media stream.

LINEMEDIACONTROL_RATEUP

The speed of the media stream is increased by some stream-defined quantity.

LINEMEDIACONTROL_RATEDOWN

The speed of the media stream is decreased by some stream-defined quantity.

LINEMEDIACONTROL_RATENORMAL

The speed of the media stream is returned to normal.

LINEMEDIACONTROL_VOLUMEUP

The amplitude of the media stream is increased by some stream-defined quantity.

LINEMEDIACONTROL_VOLUMEDOWN

The amplitude of the media stream is decreased by some stream-defined quantity.

LINEMEDIACONTROL_VOLUMENORMAL

The amplitude of the media stream is returned to normal.

No extensions.

The LINEMEDIACONTROLCALLSTATE structure defines a triple <call state(s), media-control action>. An array of these triples is passed to the lineSetMediaControl function to set the media-control actions triggered by the transition to the call state of the given call. When a transition to a listed call state is detected, the corresponding action on the media stream is invoked.


 LINEMEDIACONTROLDIGIT

[New - Windows 95]

typedef struct linemediacontroldigit_tag {
  DWORD      dwDigit;
  DWORD      dwDigitModes;
  DWORD      dwMediaControl;
} LINEMEDIACONTROLDIGIT, FAR *LPLINEMEDIACONTROLDIGIT;

The LINEMEDIACONTROLDIGIT structure describes a media action to be executed when detecting a digit. It is used as as entry in an array.

dwDigit

The low-order byte of this DWORD specifies the digit in ASCII whose detection is to trigger a media action. Valid digits depend on the media mode.

dwDigitModes

Specifies the digit mode(s) that are to be monitored. This field uses the following LINEDIGITMODE_ constants:

LINEDIGITMODE_PULSE

Detect digits as audible clicks that are the result of rotary pulse sequences. Valid digits for pulse are '0' through '9'.

LINEDIGITMODE_DTMF

Detect digits as DTMF tones. Valid digits for DTMF are '0' through '9', 'A', 'B', 'C', 'D', '*', and '#'.

LINEDIGITMODE_DTMFEND

Detect and provide application notification of DTMF down edges. Valid digits for DTMF are '0' through '9', 'A', 'B', 'C', 'D', '*', and '#'.

dwMediaControl

Specifies the media-control action. This field uses the following LINEMEDIACONTROL_ constants:

LINEMEDIACONTROL_NONE

No change is to be made to the media stream.

LINEMEDIACONTROL_RESET

Reset the media stream. Equivalent to an end-of-input. All buffers are released.

LINEMEDIACONTROL_PAUSE

Temporarily pause the media stream.

LINEMEDIACONTROL_RESUME

Start or resume a paused media stream.

LINEMEDIACONTROL_RATEUP

The speed of the media stream is increased by some stream-defined quantity.

LINEMEDIACONTROL_RATEDOWN

The speed of the media stream is decreased by some stream-defined quantity.

LINEMEDIACONTROL_RATENORMAL

The speed of the media stream is returned to normal.

LINEMEDIACONTROL_VOLUMEUP

The amplitude of the media stream is increased by some stream-defined quantity.

LINEMEDIACONTROL_VOLUMEDOWN

The amplitude of the media stream is decreased by some stream-defined quantity.

LINEMEDIACONTROL_VOLUMENORMAL

The amplitude of the media stream is returned to normal.

No extensions.

The LINEMEDIACONTROLMEDIA structure defines a triple <digit, digit mode(s), media-control action>. An array of these triples is passed to the lineSetMediaControl function to set the media-control actions triggered by digits detected on a given call. When a listed digit is detected, then the corresponding action on the media stream is invoked.


 LINEMEDIACONTROLMEDIA

[New - Windows 95]

typedef struct linemediacontrolmedia_tag {
  DWORD      dwMediaModes;
  DWORD      dwDuration;
  DWORD      dwMediaControl;
} LINEMEDIACONTROLMEDIA, FAR *LPLINEMEDIACONTROLMEDIA;

The LINEMEDIACONTROLMEDIA structure describes a media action to be executed when detecting a media-mode change. It is used as as entry in an array.

dwMediaModes

Specifies one or more media modes. This field uses the following LINEMEDIAMODE_ constants:

LINEMEDIAMODE_UNKNOWN

A media stream exists but its mode is not known. This would correspond to a call with an unclassified media type. In typical analog telephony environments, an inbound call's media mode may be unknown until after the call has been answered and the media stream filtered to make a determination.

LINEMEDIAMODE_INTERACTIVEVOICE

The presence of voice energy on the call and the call is treated as an interactive call with humans on both ends.

LINEMEDIAMODE_AUTOMATEDVOICE

The presence of voice energy on the call and the voice is locally handled by an automated application.

LINEMEDIAMODE_DATAMODEM

A data modem session on the call.

LINEMEDIAMODE_G3FAX

A group 3 fax is being sent or received over the call.

LINEMEDIAMODE_TDD

A TDD (Telephony Devices for the Deaf) session on the call.

LINEMEDIAMODE_G4FAX

A group 4 fax is being sent or received over the call.

LINEMEDIAMODE_DIGITALDATA

Digital data is being sent or received over the call.

LINEMEDIAMODE_TELETEX

A teletex session on the call. Teletex is one of the telematic services.

LINEMEDIAMODE_VIDEOTEX

A videotex session on the call. Videotex is one the telematic services.

LINEMEDIAMODE_TELEX

A telex session on the call. Telex is one the telematic services.

LINEMEDIAMODE_MIXED

A mixed session on the call. Mixed is one the ISDN telematic services.

LINEMEDIAMODE_ADSI

An ADSI (Analog Display Services Interface) session on the call.

dwDuration

Specifies the duration in milliseconds during which the media mode should be present before the application should be notified or media-control action should be taken.

dwMediaControl

Specifies the media-control action. This field uses the following LINEMEDIACONTROL_ constants:

LINEMEDIACONTROL_NONE

No change is to be made to the media stream.

LINEMEDIACONTROL_RESET

Reset the media stream. Equivalent to an end-of-input. All buffers are released.

LINEMEDIACONTROL_PAUSE

Temporarily pause the media stream.

LINEMEDIACONTROL_RESUME

Start or resume a paused media stream.

LINEMEDIACONTROL_RATEUP

The speed of the media stream is increased by some stream-defined quantity.

LINEMEDIACONTROL_RATEDOWN

The speed of the media stream is decreased by some stream-defined quantity.

LINEMEDIACONTROL_RATENORMAL

The speed of the media stream is returned to normal.

LINEMEDIACONTROL_VOLUMEUP

The amplitude of the media stream is increased by some stream-defined quantity.

LINEMEDIACONTROL_VOLUMEDOWN

The amplitude of the media stream is decreased by some stream-defined quantity.

LINEMEDIACONTROL_VOLUMENORMAL

The amplitude of the media stream is returned to normal.

No extensions.

The LINEMEDIACONTROLMEDIA structure defines a triple <media mode(s), duration, media-control action>. An array of these triples is passed to the lineSetMediaControl function to set the media-control actions triggered by media-mode changes for a given call. When a change to a listed media mode is detected, then the corresponding action on the media stream is invoked.


 LINEMEDIACONTROLTONE

[New - Windows 95]

typedef struct linemediacontroltone_tag {
  DWORD  dwAppSpecific;
  DWORD  dwDuration;
  DWORD  dwFrequency1;
  DWORD  dwFrequency2;
  DWORD  dwFrequency3;
  DWORD  dwMediaControl;
} LINEMEDIACONTROLTONE, FAR *LPLINEMEDIACONTROLTONE;

The LINEMEDIACONTROLTONE structure describes a media action to be executed when a tone has been detected. It is used as an entry in an array.

dwAppSpecific

This field is used by the application for tagging the tone. When this tone is detected, the value of the dwAppSpecific field is passed back to the application.

dwDuration

Specifies the duration in milliseconds during which the tone should be present before a detection is made.

dwFrequency1
dwFrequency2
dwFrequency3

Specifies the frequency in Hertz of a component of the tone. If fewer than three frequencies are needed in the tone, a value of zero should be used for the unused frequencies. A tone with all three frequencies set to zero is interpreted as silence and can be use for silence detection.

dwMediaControl

Specifies the media-control action. This field uses the following LINEMEDIACONTROL_ constants:

LINEMEDIACONTROL_NONE

No change is to be made to the media stream.

LINEMEDIACONTROL_RESET

Reset the media stream. Equivalent to an end-of-input. All buffers are released.

LINEMEDIACONTROL_PAUSE

Temporarily pause the media stream.

LINEMEDIACONTROL_RESUME

Start or resume a paused media stream.

LINEMEDIACONTROL_RATEUP

The speed of the media stream is increased by some stream-defined quantity.

LINEMEDIACONTROL_RATEDOWN

The speed of the media stream is decreased by some stream-defined quantity.

LINEMEDIACONTROL_RATENORMAL

The speed of the media stream is returned to normal.

LINEMEDIACONTROL_VOLUMEUP

The amplitude of the media stream is increased by some stream-defined quantity.

LINEMEDIACONTROL_VOLUMEDOWN

The amplitude of the media stream is decreased by some stream-defined quantity.

LINEMEDIACONTROL_VOLUMENORMAL

The amplitude of the media stream is returned to normal.

No extensions.

The LINEMEDIACONTROLTONE structure defines a tuple <tone, media-control action>. An array of these tuples is passed to the lineSetMediaControl function to set media-control actions triggered by media-mode changes for a given call. When a change to a listed media mode is detected, the corresponding action on the media stream is invoked.

A tone with all frequencies set to zero corresponds to silence. An application can thus monitor the call's information stream for silence.


 LINEMONITORTONE

[New - Windows 95]

typedef struct linemonitortone_tag {
  DWORD  dwAppSpecific;
  DWORD  dwDuration;
  DWORD  dwFrequency1;
  DWORD  dwFrequency2;
  DWORD  dwFrequency3;
} LINEMONITORTONE, FAR *LPLINEMONITORTONE;

The LINEMONITORTONE structure describes a tone to be monitored. This is used as an entry in an array.

dwAppSpecific

This field is used by the application for tagging the tone. When this tone is detected, the value of the dwAppSpecific field is passed back to the application.

dwDuration

Specifies the duration in milliseconds during which the tone should be present before a detection is made.

dwFrequency1
dwFrequency2
dwFrequency3

Specifies the frequency in Hertz of a component of the tone. If fewer than three frequencies are needed in the tone, a value of zero should be used for the unused frequencies. A tone with all three frequencies set to zero is interpreted as silence and can be use for silence detection.

No extensions.

The LINEMONITORTONE structure defines a tone for the purpose of detection. An array of tones is passed to the lineMonitorTones function which monitors these tones and send a LINE_MONITORTONE message to the application when a detection is made.

A tone with all frequencies set to zero corresponds to silence. An application can thus monitor the call's information stream for silence.


 LINEPROVIDERENTRY

[New - Windows 95]

typedef struct lineproviderentry_tag {
  DWORD  dwPermanentProviderID;
  DWORD  dwProviderFilenameSize;
  DWORD  dwProviderFilenameOffset;
} LINEPROVIDERENTRY, FAR *LPLINEPROVIDERENTRY;

The LINEPROVIDERENTRY structure provides the information for a single service provider entry. An array of these structures is returned as part of the LINEPROVIDERLIST structure returned by the function lineGetProviderList.

dwPermanentProviderID

Specifies the permanent provider ID of the entry.

dwProviderFilenameSize
dwProviderFilenameOffset

The size in bytes and the offset in bytes from the beginning of the LINEPROVIDERLIST structure of a null-terminated ASCII string containing the filename (pathname) of the service provider DLL (.TSP) file.

Not extensible.


 LINEPROVIDERLIST

[New - Windows 95]

typedef struct lineproviderlist_tag {
  DWORD  dwTotalSize;
  DWORD  dwNeededSize;
  DWORD  dwUsedSize;

  DWORD  dwNumProviders;
  DWORD  dwProviderListSize;
  DWORD  dwProviderListOffset;
} LINEPROVIDERLIST, FAR *LPLINEPROVIDERLIST;

The LINEPROVIDERLIST structure describes a list of service providers. A structure of this type is returned by the function lineGetProviderList.

dwTotalSize

The total size in bytes allocated to this data structure.

dwNeededSize

The size in bytes for this data structure that is needed to hold all the returned information.

dwUsedSize

The size in bytes of the portion of this data structure that contains useful information.

dwNumProviders

Specifies the number of LINEPROVIDERENTRY structures present in the array denominated by dwProviderListSize and dwProviderListOffset.

dwProviderListSize
dwProviderListOffset

The size in bytes and the offset in bytes from the beginning of this data structure of an array of LINEPROVIDERENTRY elements which provide the information on each service provider.

Not extensible.


 LINEREQMAKECALL

[New - Windows 95]

typedef struct linereqmakecall_tag {
  char  szDestAddress[TAPIMAXDESTADDRESSSIZE];
  char  szAppName[TAPIMAXAPPNAMESIZE];
  char  szCalledParty[TAPIMAXCALLEDPARTYSIZE];
  char  szComment[TAPIMAXCOMMENTSIZE];
} LINEREQMAKECALL, FAR *LPLINEREQMAKECALL;

The LINEREQMAKECALL structure describes a tapiRequestMakeCall request.

szDestAddress[TAPIMAXADDRESSSIZE]

Specifies the NULL-terminated destination address of the make-call request. The address can use the canonical address format or the dialable address format. The maximum length of the address is TAPIMAXDESTADDRESSSIZE characters, which includes the NULL terminator. Longer strings are truncated.

szAppName[TAPIMAXAPPNAMESIZE]

Specifies the ASCII NULL-terminated user-friendly application name or file name of the application that originated the request. The maximum length of the address is TAPIMAXAPPNAMESIZE characters, which includes the NULL terminator.

szCalledParty[TAPIMAXCALLEDPARTYSIZE]

Specifies the ASCII NULL-terminated user-friendly called-party name. The maximum length of the called-party information is TAPIMAXCALLEDPARTYSIZE characters, which includes the NULL terminator.

szComment[TAPIMAXCOMMENTSIZE]

Specifies the ASCII NULL-terminated comment about the call request. The maximum length of the comment string is TAPIMAXCOMMENTSIZE characters, which includes the NULL terminator.

No extensions.

The szDestAddress field contains the address of the remote party; the other fields are useful for logging purposes. An application must use this structure to interpret the request buffer it received from lineGetRequest with the LINEREQUESTMODE_MAKECALL request mode.


 LINETERMCAPS

[New - Windows 95]

typedef struct linetermcaps_tag {
  DWORD  dwTermDev;
  DWORD  dwTermModes;
  DWORD  dwTermSharing;
} LINETERMCAPS, FAR *LPLINETERMCAPS;

The LINETERMCAPS structure describes the capabilities of a line's terminal device.

dwTermDev

Specifies the device type of the terminal. This field uses the following LINETERMDEV_ constants:

LINETERMDEV_PHONE

The terminal is a phone set.

LINETERMDEV_HEADSET

The terminal is a headset

LINETERMDEV_SPEAKER

The terminal is an external speaker and microphone.

dwTermModes

Specifies the terminal mode(s) the terminal device is able to deal with. This field uses the following LINETERMMODE_ constants:

LINETERMMODE_BUTTONS

These are button-press events sent from the terminal to the line.

LINETERMMODE_LAMPS

These are lamp events sent from the line to the terminal.

LINETERMMODE_DISPLAY

This is display information sent from the line to the terminal.

LINETERMMODE_RINGER

This is ringer-control information sent from the switch to the terminal.

LINETERMMODE_HOOKSWITCH

These are hookswitch events sent from the terminal to the line.

LINETERMMODE_MEDIATOLINE

This is the unidirectional media stream from the terminal to the line associated with a call on the line. Use this value when the routing of both unidirectional channels of a call's media stream can be controlled independently.

LINETERMMODE_MEDIAFROMLINE

This is the unidirectional media stream from the line to the terminal associated with a call on the line. Use this value when the routing of both unidirectional channels of a call's media stream can be controlled independently.

LINETERMMODE_MEDIABIDIRECT

This is the bidirectional media stream associated with a call on the line and the terminal. Use this value when the routing of both unidirectional channels of a call's media stream cannot be controlled independently.

dwTermSharing

Specifies how the terminal device is shared between line devices. This field uses the following LINETERMSHARING_ constants:

LINETERMSHARING_PRIVATE

The terminal device is private to a single line device.

LINETERMSHARING_SHAREDEXCL

The terminal device can be used by multiple lines. The last line device to do a lineSetTerminal to the terminal for a given terminal mode will have exclusive connection to the terminal for that mode.

LINETERMSHARING_SHAREDCONF

The terminal device can be used by multiple lines. The lineSetTerminal requests of the various terminals end up being "merged" at the terminal.

No extensions.


 LINETRANSLATECAPS

[New - Windows 95]

typedef struct linetranslatecaps_tag {
  DWORD  dwTotalSize;
  DWORD  dwNeededSize;
  DWORD  dwUsedSize;

  DWORD  dwNumLocations;
  DWORD  dwLocationListSize;
  DWORD  dwLocationListOffset;

  DWORD  dwCurrentLocationID;
  DWORD  dwNumCards;
  DWORD  dwCardListSize;
  DWORD  dwCardListOffset;

  DWORD  dwCurrentPreferredCardID;
} LINETRANSLATECAPS, FAR *LPLINETRANSLATECAPS;

The LINETRANSLATECAPS structure describes the address translation capabilities.

dwTotalSize

The total size in bytes allocated to this data structure.

dwNeededSize

The size in bytes for this data structure that is needed to hold all the returned information.

dwUsedSize

The size in bytes of the portion of this data structure that contains useful information.

dwNumLocations

The number of entries in the LocationList. It includes all locations defined, including 0 (default).

dwLocationListSize
dwLocationListOffset

List of locations known to address translation. The list consists of a sequence of LINELOCATIONENTRY structures. The dwLocationListOffset field points to the first byte of the first LINELOCATIONENTRY structure, and the dwLocationListSize field indicates the total number of bytes in the entire list.

dwCurrentLocationID

This is the dwPermanentLocationID from the LINELOCATIONENTRY for the Current Location.

dwNumCards

The number of entries in the CardList.

dwCardListSize
dwCardListOffset

List of calling cards known to address translation. It includes only non-hidden card entries and always includes card 0 (direct dial). The list consists of a sequence of LINECARDENTRY structures. The dwCardListOffset field points to the first byte of the first LINECARDENTRY structure, and the dwCardListSize field indicates the total number of bytes in the entire list.

dwCurrentPreferredCardID

This is the dwPreferredCardID from the LINELOCATIONENTRY for the Current Location.

No extensions.


 LINETRANSLATEOUTPUT

[New - Windows 95]

typedef struct linetranslateoutput_tag {
  DWORD  dwTotalSize;
  DWORD  dwNeededSize;
  DWORD  dwUsedSize;

  DWORD  dwDialableStringSize;
  DWORD  dwDialableStringOffset;
  DWORD  dwDisplayableStringSize;
  DWORD  dwDisplayableStringOffset;

  DWORD  dwCurrentCountry;
  DWORD  dwDestCountry;
  DWORD  dwTranslateResults;
} LINETRANSLATEOUTPUT, FAR *LPLINETRANSLATEOUTPUT;

The LINETRANSLATEOUTPUT structure describes the result of an address translation.

dwTotalSize

The total size in bytes allocated to this data structure.

dwNeededSize

The size in bytes for this data structure that is needed to hold all the returned information.

dwUsedSize

The size in bytes of the portion of this data structure that contains useful information.

dwDialableStringSize
dwDialableStringOffset

Contains the translated output which can be passed to lineMakeCall, lineDial, or other function requiring a dialable string. The output is always a null-terminated ASCII string (null is accounted for in Size). Ancillary fields such as name and subaddress are included in this output string if they were in the input string. This string may contain private information such as calling card numbers. It should not be displayed to the user, to prevent inadvertent visibility to unauthorized persons.

dwDisplayableStringSize
dwDisplayableStringOffset

Contains the translated output which can be displayed to the user for confirmation. It will be identical to DialableString, except that calling card digits will be replaced with the "friendly name" of the card enclosed within bracket characters (for example, "[AT&T Card]"), and ancillary fields such as name and subaddress will be removed. It should normally be safe to display this string in call-status dialog boxes without exposing private information to unauthorized persons. This information is also appropriate to include in call logs.

dwCurrentCountry

Contains the country code configured in CurrentLocation. This value may be used to control the display by the application of certain user interface elements, local call progress tone detection, and for other purposes.

dwDestCountry

Contains the destination country code of the translated address. This value may be passed to the dwCountryCode parameter of lineMakeCall and other dialing functions (so that the call progress tones of the destination country such as a busy signal will be properly detected). This field is set to 0 if the destination address passed to lineTranslateAddress is not in canonical format.

dwTranslateResults

Indicates the information derived from the translation process, which may assist the application in presenting user-interface element. This field uses the following LINETRANSLATERESULT_ constants:

LINETRANSLATERESULT_CANONICAL

Indicates that the input string was in valid canonical format.

LINETRANSLATERESULT_INTERNATIONAL

If this bit is on, the call is being treated as an international call (country code specified in the destination address is the different from the country code specified for the CurrentLocation).

LINETRANSLATERESULT_LONGDISTANCE

If this bit is on, the call is being treated as a long distance call (country code specified in the destination address is the same but area code is different from those specified for the CurrentLocation).

LINETRANSLATERESULT_LOCAL

If this bit is on, the call is being treated as a local call (country code and area code specified in the destination address are the same as those specified for the CurrentLocation).

LINETRANSLATERESULT_INTOLLLIST

If this bit is on, the local call is being dialed as long distance because the country has toll calling and the prefix appears in the TollPrefixList of the CurrentLocation.

LINETRANSLATERESULT_NOTINTOLLLIST

If this bit is on, the country supports toll calling but the prefix does not appear in the TollPrefixList, so the call is dialed as a local call.  Note that if both INTOLLIST and NOTINTOLLIST are off, the current country does not support toll prefixes, and user-interface elements related to toll prefixes should not be presented to the user; if either such bit is on, the country does support toll lists, and the related user-interface elements should be enabled.

LINETRANSLATERESULT_DIALBILLING

Indicates that the returned address contains a "$".

LINETRANSLATERESULT_DIALQUIET

Indicates that the returned address contain a "@".

LINETRANSLATERESULT_DIALDIALTONE

Indicates that the returned address contains a "W".

LINETRANSLATERESULT_DIALPROMPT

Indicates that the returned address contains a "?".

No extensions.


 Line Device Constants

About Line Device Constants

This chapter describes the constants used by the Telephony API. They are listed in alphabetical order.


 Reference

Following are the Telephony API constants.


 LINEADDRCAPFLAGS_ Constants

[New - Windows 95]

The LINEADDRCAPFLAGS__bit-flag constants are used in the dwAddrCapFlags field of the LINEADDRESSCAPS data structure to describe various Boolean address capabilities.

LINEADDRCAPFLAGS_FWDNUMRINGS

Specifies whether the number of rings for a no answer can be specified when forwarding calls on no answer. If TRUE, the valid range is provided in LINEADDRESSCAPS.

LINEADDRCAPFLAGS_PICKUPGROUPID

Specifies whether a group ID is required for call pickup.

LINEADDRCAPFLAGS_SECURE

Specifies whether calls on this address can be made secure at call-setup time.

LINEADDRCAPFLAGS_BLOCKIDDEFAULT

Specifies whether the network by default sends or blocks caller ID information when making a call on this address. If TRUE, ID information is blocked by default; if FALSE, ID information is transmitted by default.

LINEADDRCAPFLAGS_BLOCKIDOVERRIDE

Specifies whether the default setting for sending or blocking of caller ID information can be overridden per call. If TRUE, override is possible; if FALSE, override is not possible.

LINEADDRCAPFLAGS_DIALED

Specifies whether a destination address can be dialed on this address for making a call. TRUE if a destination address must be dialed; FALSE if the destination address is fixed (as with a "hot phone").

LINEADDRCAPFLAGS_ORIGOFFHOOK

Specifies whether the originating party's phone can automatically be taken offhook when making calls.

LINEADDRCAPFLAGS_DESTOFFHOOK

Specifies whether the called party's phone can automatically be forced offhook when making calls.

LINEADDRCAPFLAGS_FWDCONSULT

Specifies whether call forwarding involves the establishment of a consultation call.

LINEADDRCAPFLAGS_SETUPCONFNULL

Specifies whether setting up a conference call starts out with an initial call (FALSE) or with no initial call (TRUE).

LINEADDRCAPFLAGS_AUTORECONNECT

Specifies whether dropping a consultation call automatically reconnects to the call on consultation hold. TRUE if reconnect happens automatically; otherwise, FALSE.

LINEADDRCAPFLAGS_COMPLETIONID

Specifies whether the completion IDs returned by lineCompleteCall are useful and unique. TRUE if useful; otherwise, FALSE.

LINEADDRCAPFLAGS_TRANSFERHELD

Specifies whether a hard-held call can be transferred. Often, only calls on consultation hold can be transferred.

LINEADDRCAPFLAGS_TRANSFERMAKE

Specifies whether an entirely new call can be established for use as a consultation call on transfer.

LINEADDRCAPFLAGS_CONFERENCEHELD

Specifies whether a hard-held call can be conferenced to. Often, only calls on consultation hold can be added to as a conference call.

LINEADDRCAPFLAGS_CONFERENCEMAKE

Specifies whether an entirely new call can be established for use as a consultation call (to add) on conference.

LINEADDRCAPFLAGS_PARTIALDIAL

Specifies whether partial dialing is available.

LINEADDRCAPFLAGS_FWDSTATUSVALID

Specifies whether the forwarding status in the LINEADDRESSSTATUS structure for this address is valid or is at most a "best estimate," given absence of accurate confirmation by the switch or network.

LINEADDRCAPFLAGS_FWDINTEXTADDR

Specifies whether internal and external calls can be forwarded to different forwarding addresses. This flag is meaningful only if forwarding of internal and external calls can be controlled separately. This flag is TRUE if internal and external calls can be forwarded to different destination addresses; otherwise, it is FALSE.

LINEADDRCAPFLAGS_FWDBUSYNAADDR

Specifies whether call forwarding for busy and for no answer can use different forwarding addresses. This flag is meaningful only if forwarding for busy and for no answer can be controlled separately. This flag is TRUE if forwarding for busy and for no answer can use different destination addresses; otherwise, it is FALSE.

LINEADDRCAPFLAGS_ACCEPTTOALERT

TRUE if an offering call must be accepted using lineAccept in order to start alerting the users at both ends of the call; otherwise, FALSE. This is typically only used with ISDN.

LINEADDRCAPFLAGS_CONFDROP

TRUE if lineDrop on a conference call parent also has the side effect of dropping (that is, disconnecting) the other parties involved in the conference call; FALSE if dropping a conference call still allows the other parties to talk among themselves.

LINEADDRCAPFLAGS_PICKUPCALLWAIT

TRUE if linePickup can be used to pickup a call detected by the user as a call waiting call; otherwise, FALSE.

No extensibility. All 32 bits are reserved.


 LINEADDRESSMODE_ Constants

[New - Windows 95]

The LINEADDRESSMODE_ bit-flag constants describe various ways of identifying an address on a line device.

LINEADDRESSMODE_ADDRESSID

The address is specified with a small integer in the range 0 to dwNumAddresses minus one, where dwNumAddresses is the value in the line's device capabilities.

LINEADDRESSMODE_DIALABLEADDR

The address is specified through its phone number.

The high-order 16 bits can be assigned for device-specific extensions. The low-order 16 bits are reserved.

This constant is used to select an address on a line on which to originate a call. The usual model would select the address by means of its address ID. Address IDs are the mechanism used to identify addresses throughout TAPI. However, in some environments, when making a call, it is often more practical to identify a call's originating address by phone number rather than by address ID. One example is in the possible modeling of large numbers of stations (third party) on the switch by means of one line device with many addresses. The line represents the set of all stations, and each station is mapped to an address with its own primary phone number and address ID.


 LINEADDRESSSHARING_ Constants

[New - Windows 95]

The LINEADDRESSSHARING_ bit-flag constants describe various ways an address can be shared between lines.

LINEADDRESSSHARING_PRIVATE

The address is private to the user's line; it is not assigned to any other station.

LINEADDRESSSHARING_BRIDGEDEXCL

The address is bridged to one or more other stations. The first line to activate a call on the line will have exclusive access to the address and calls that may exist on it. Other lines will not be able to use the bridged address while it is in use.

LINEADDRESSSHARING_BRIDGEDNEW

The address is bridged with one or more other stations. The first line to activate a call on the line will have exclusive access to only the corresponding call. Other applications that use the address will result in new and separate call appearances.

LINEADDRESSSHARING_BRIDGEDSHARED

The address is bridged with one or more other lines. All bridged parties can share in calls on the address, which then functions as a conference.

LINEADDRESSSHARING_MONITORED

This is an address whose idle/busy status is made available to this line.

No extensibility. All 32 bits are reserved.

The way in which an address is shared across lines can affect the behavior of that address. LINE_CALLSTATE and LINE_ADDRESSSTATE messages are sent to the application in response to activities by the bridging stations. It is through these messages that an application can track the status of the address.


 LINEADDRESSSTATE_ Constants

[New - Windows 95]

The LINEADDRESSSTATE_ bit-flag constants describe various address status items.

LINEADDRESSSTATE_OTHER

Address-status items other than those listed below have changed. The application should check the current address status to determine which items have changed.

LINEADDRESSSTATE_DEVSPECIFIC

The device-specific item of the address status has changed.

LINEADDRESSSTATE_INUSEZERO

The address has changed to idle (it is not in use by any stations).

LINEADDRESSSTATE_INUSEONE

The address has changed from idle or in use by many bridged stations to being in use by just one station.

LINEADDRESSSTATE_INUSEMANY

The monitored or bridged address has changed from being in use by one station to being in use by more than one station.

LINEADDRESSSTATE_NUMCALLS

The number of calls on the address has changed. This is the result of events such as a new inbound call, an outbound call on the address, or a call changing its hold status. This flag covers changes in any of the fields dwNumActiveCalls, dwNumOnHoldCalls and dwNumOnHoldPendingCalls in the LINEADDRESSSTATUS structure. The application should check all three of these fields when it receives a LINE_ADDRESSSTATE (numCalls) message.

LINEADDRESSSTATE_FORWARD

The forwarding status of the address has changed, including possibly the number of rings for determining a no answer condition. The application should check the address status to determine details about the address's current forwarding status.

LINEADDRESSSTATE_TERMINALS

The terminal settings for the address have changed.

LINEADDRESSSTATE_CAPSCHANGE

Indicates that, due to configuration changes made by the user or other circumstances, one or more of the fields in the LINEADDRESSCAPS structure for the address have changed. The application should use lineGetAddressCaps to read the updated structure. If a service provider sends a LINE_ADDRESSSTATE message containing this value to TAPI, TAPI will pass it along to applications which have negotiated this or a subsequent API version; applications negotiating a previous API version will receive LINE_LINEDEVSTATE messages specifying LINEDEVSTATE_REINIT, requiring them to shutdown and reinitialize their connection to TAPI in order to obtain the updated information.

No extensibility. All 32 bits are reserved.

An application is notified about changes to these status items in the LINE_ADDRESSSTATE message. The address's device capabilities indicate which address state changes can possibly be reported for this address.


 LINEADDRFEATURE_ Constants

[New - Windows 95]

The LINEADDRFEATURE_ constants list the operations that can be invoked on an address.

LINEADDRFEATURE_FORWARD

The address can be forwarded.

LINEADDRFEATURE_MAKECALL

An outbound call can be placed on the address.

LINEADDRFEATURE_PICKUP

A call can be picked-up at the address.

LINEADDRFEATURE_SETMEDIACONTROL

Media control can be set on this address.

LINEADDRFEATURE_SETTERMINAL

The terminal modes for this address can be set.

LINEADDRFEATURE_SETUPCONF

A conference call with a NULL initial call can be set up at this address.

LINEADDRFEATURE_UNCOMPLETECALL

Call completion requests can be canceled at this address.

LINEADDRFEATURE_UNPARK

Calls can be unparked using this address.

No extensibility. All 32 bits are reserved.

This constant is used both in LINEADDRESSCAPS (returned by lineGetAddressCaps) and in LINEADDRESSSTATUS (returned by lineGetAddressStatus). LINEADDRESSCAPS reports the availability of the address features by the service provider (mainly the switch) for a given address. An application would make this determination when it initializes. The LINEADDRESSSTATUS structure reports, for a given address, which address features can actually be invoked while the address is in the current state. An application would make this determination dynamically after address-state changes, typically caused by call-related activities on the address.


 LINEANSWERMODE_ Constants

[New - Windows 95]

The LINEANSWERMODE_ bit-flag constants describe how an existing active call on a line device is affected by answering another offering call on the same line.

LINEANSWERMODE_NONE

Answering another call on the same line has no effect on the existing active call(s) on the line.

LINEANSWERMODE_DROP

The currently active call will automatically be dropped.

LINEANSWERMODE_HOLD

The currently active call will automatically be placed on hold.

No extensibility. All 32 bits are reserved.

If a call comes in (is offered) at the time another call is already active, the new call is connected to by invoking lineAnswer. The effect this has on the existing active call depends on the line's device capabilities. The first call may be unaffected, it may automatically be dropped, or it may automatically be placed on hold.


 LINEBEARERMODE_ Constants

[New - Windows 95]

The LINEBEARERMODE_ bit-flag constants describe different bearer modes of a call. When an application makes a call, it can request a specific bearer mode. These modes are used to select a certain quality of service for the requested connection from the underlying telephone network. Bearer modes available on a given line are a device capability of the line.

LINEBEARERMODE_VOICE

This is a regular 3.1kHz analog voice grade bearer service. Bit integrity is not assured. Voice can support fax and modem media modes.

LINEBEARERMODE_SPEECH

This corresponds to G.711 speech transmission on the call. The network may use processing techniques such as analog transmission, echo cancellation, and compression/decompression. Bit integrity is not assured. Speech is not intended to support fax and modem media modes.

LINEBEARERMODE_MULTIUSE

The multi-use mode defined by ISDN.

LINEBEARERMODE_DATA

The unrestricted data transfer on the call. The data rate is specified separately.

LINEBEARERMODE_ALTSPEECHDATA

The alternate transfer of speech or unrestricted data on the same call (ISDN).

LINEBEARERMODE_NONCALLSIGNALING

This corresponds to a non-call-associated signaling connection from the application to the service provider or switch (treated as a "media stream" by TAPI).

LINEBEARERMODE_PASSTHROUGH

When a call is active in LINEBEARERMODE_PASSTHROUGH, the service provider gives direct access to the attached hardware for control by the application. This mode is used primarily by applications desiring temporary direct control over asynchronous modems, accessed via the Win32 comm functions, for the purpose of configuring or using special features not otherwise supported by the service provider.

The high-order 16 bits can be assigned for device-specific extensions. The low-order 16 bits are reserved.

Note that bearer mode and media mode are different notions. The bearer mode of a call is an indication of the quality of the telephone connection as provided primarily by the network. The media mode of a call is an indication of the type of information stream that is exchanged over that call. Group 3 fax or data modem are media modes that use a call with a 3.1kHz voice bearer mode.


 LINEBUSYMODE_ Constants

[New - Windows 95]

The LINEBUSYMODE_ bit-flag constants describe different busy signals that the switch or network may generate. These busy signals typically indicate that a different resource that is required to make a call is currently in use.

LINEBUSYMODE_STATION

The busy signal indicates that the called party's station is busy. This is usually signaled with a "normal" busy tone.

LINEBUSYMODE_TRUNK

The busy signal indicates that a trunk or circuit is busy. This is usually signaled with a "fast" busy tone.

LINEBUSYMODE_UNKNOWN

The busy signal's specific mode is currently unknown but may become known later.

LINEBUSYMODE_UNAVAIL

The busy signal's specific mode is unavailable and will not become known.

The high-order 16 bits can be assigned for device-specific extensions. The low-order 16 bits are reserved.

Note that busy signals may be sent as inband tones or out-of-band messages. TAPI makes no assumption about the specific signaling mechanism.


 LINECALLCOMPLCOND_ Constants

[New - Windows 95]

The LINECALLCOMPLCOND_ bit-flag constants describe the conditions under which a call can be completed.

LINECALLCOMPLCOND_BUSY

Completion of the call under busy conditions.

LINECALLCOMPLCOND_NOANSWER

Completion of the call under ringback no answer conditions.

No extensibility. All 32 bits are reserved.


 LINECALLCOMPLMODE_ Constants

[New - Windows 95]

The LINECALLCOMPLMODE_ bit-flag constants describe different ways in which a call can be completed.

LINECALLCOMPLMODE_CAMPON

Queues the call until the call can be completed.

LINECALLCOMPLMODE_CALLBACK

Requests the called station to return the call when it returns to idle.

LINECALLCOMPLMODE_INTRUDE

Adds the application to the existing call at the called station (barge in).

LINECALLCOMPLMODE_MESSAGE

Leave a short predefined message for the called station (Leave Word Calling). The message to be sent is specified separately.

No extensibility. All 32 bits are reserved.


 LINECALLFEATURE_ Constants

[New - Windows 95]

The LINECALLFEATURE_ constants list the operations that can be invoked on a call using this API.

Each of the LINECALLFEATURE_ values correspond to the TAPI operations with the same name. The list is not repeated here.

No extensibility. All 32 bits are reserved.

This constant is used both in LINEADDRESSCAPS (returned by lineGetAddressCaps) and in LINECALLSTATUS (returned by lineGetCallStatus). LINEADDRESSCAPS reports the availability of the call features on the specified address. An application would use this information when it initializes to determine what it may be able to do later when calls exist. For the specified call, LINECALLSTATUS reports which call features can be invoked while the call is in the current call state. The latter takes call privileges into account. An application would make this determination dynamically, after call state changes.

The LINECALLFEATURE_RELEASEUSERUSER value is new. No backward compatibility considerations. A service provider may elect to return this value in relevant fields (in LINEADDRESSCAPS and LINECALLSTATUS) even when older API versions have been negotiated on the line device.


 LINECALLINFOSTATE_ Constants

[New - Windows 95]

The LINECALLINFOSTATE_ bit-flag constants describe various call information items about which an application may be notified in the LINE_CALLINFO message.

LINECALLINFOSTATE_OTHER

Call information items other than those listed below have changed. The application should check the current call information to determine which items have changed.

LINECALLINFOSTATE_DEVSPECIFIC

The device-specific field of the call-information record.

LINECALLINFOSTATE_BEARERMODE

The bearer mode field of the call-information record.

LINECALLINFOSTATE_RATE

The rate field of the call-information record.

LINECALLINFOSTATE_MEDIAMODE

The media-mode field of the call-information record.

LINECALLINFOSTATE_APPSPECIFIC

The application-specific field of the call-information record.

LINECALLINFOSTATE_CALLID

The call ID field of the call-information record.

LINECALLINFOSTATE_RELATEDCALLID

The related call ID field of the call-information record.

LINECALLINFOSTATE_ORIGIN

The origin field of the call-information record.

LINECALLINFOSTATE_REASON

The reason field of the call-information record.

LINECALLINFOSTATE_COMPLETIONID

The completion ID field of the call-information record.

LINECALLINFOSTATE_NUMOWNERINCR

The number of owner field in the call-information record was increased.

LINECALLINFOSTATE_NUMOWNERDECR

The number of owner field in the call-information record was decreased.

LINECALLINFOSTATE_NUMMONITORS

The number of monitors field in the call-information record has changed.

LINECALLINFOSTATE_TRUNK

The trunk field of the call-information record.

LINECALLINFOSTATE_CALLERID

One of the callerID-related fields of the call-information record.

LINECALLINFOSTATE_CALLEDID

One of the calledID-related fields of the call-information record.

LINECALLINFOSTATE_CONNECTEDID

One of the cconnectedID-related fields of the call-information record.

LINECALLINFOSTATE_REDIRECTIONID

One of the redirectionID-related fields of the call-information record.

LINECALLINFOSTATE_REDIRECTINGID

One of the redirectingID-related fields of the call-information record.

LINECALLINFOSTATE_DISPLAY

The display field of the call-information record.

LINECALLINFOSTATE_USERUSERINFO

The user-to-user information of the call-information record.

LINECALLINFOSTATE_HIGHLEVELCOMP

The high level compatibility field of the call-information record.

LINECALLINFOSTATE_LOWLEVELCOMP

The low level compatibility field of the call-information record.

LINECALLINFOSTATE_CHARGINGINFO

The charging information of the call-information record.

LINECALLINFOSTATE_TERMINAL

The terminal mode information of the call-information record.

LINECALLINFOSTATE_DIALPARAMS

The dial parameters of the call-information record.

LINECALLINFOSTATE_MONITORMODES

One or more of the digit, tone, or media monitoring fields in the call-information record.

No extensibility. All 32 bits are reserved.

When changes occur in this data structure, a LINE_CALLINFO message is sent to the application. The parameters to this message are a handle to the call and an indication of the information item that has changed. The LINEADDRESSCAPS data structure also indicates which of these call information elements are valid for every call on the address.


 LINECALLORIGIN_ Constants

[New - Windows 95]

The LINECALLORIGIN_ constants describe the origin of a call.

LINECALLORIGIN_OUTBOUND

The call originated from this station as an outbound call.

LINECALLORIGIN_INTERNAL

The call originated as an inbound call at a station internal to the same switching environment.

LINECALLORIGIN_EXTERNAL

The call originated as an inbound call on an external line.

LINECALLORIGIN_UNKNOWN

The call origin is currently unknown but may become known later.

LINECALLORIGIN_UNAVAIL

The call origin is not available and will never become known for this call.

LINECALLORIGIN_CONFERENCE

The call handle is for a conference call, that is, it is the application's connection to the conference bridge in the switch.

LINECALLORIGIN_INBOUND

The call originated as an inbound call, but the service provider is unable to determine whether it came from another station on the same switch or from an external line.

No extensibility. All 32 bits are reserved.

The origin of a call is stored in the dwOrigin field of the call's LINECALLINFO structure.

For backward compatibility, it is the responsibility of the service provider to examine the negotiated API version on the line, and to not use the LINECALLORIGIN_INBOUND value if it is not supported on the negotiated version (LINECALLORIGIN_UNAVAIL may be substituted).


 LINECALLPARAMFLAGS_ Constants

[New - Windows 95]

The LINECALLPARAMFLAGS_ constants describe various status flags about a call.

LINECALLPARAMFLAGS_SECURE

The call should be set up as secure.

LINECALLPARAMFLAGS_IDLE

The call should be originated on an idle call appearance and not join a call in progress. When using the lineMakeCall function, if the LINECALLPARAMFLAGS_IDLE value is not set and there is an existing call on the line, the function breaks into the existing call if necessary to make the new call. If there is no existing call, the function makes the new call as specified.

LINECALLPARAMFLAGS_BLOCKID

The originator identity should be concealed (block caller ID).

LINECALLPARAMFLAGS_ORIGOFFHOOK

The originator's phone should be automatically taken offhook.

LINECALLPARAMFLAGS_DESTOFFHOOK

The called party's phone should be automatically be taken offhook.

No extensibility. All 32 bits are reserved.


 LINECALLPARTYID_ Constants

[New - Windows 95]

The LINECALLPARTYID_ bit-flag constants describe the nature of the information available about the parties involved in a call.

LINECALLPARTYID_BLOCKED

Party ID information is not available because it has been blocked by the remote party.

LINECALLPARTYID_OUTOFAREA

Caller ID information for the call is not available since it is not propagated all the way by the network.

LINECALLPARTYID_NAME

Party ID information consists of the party's name (as, for example, from a directory kept inside the switch).

LINECALLPARTYID_ADDRESS

Party ID information consists of the party's address in either canonical address format or dialable address format.

LINECALLPARTYID_PARTIAL

Party ID information is valid but it is limited to partial information only.

LINECALLPARTYID_UNKNOWN

Party ID information is currently unknown but may become known later.

LINECALLPARTYID_UNAVAIL

Party ID information is not available and will not become available later. Information may be unavailable for unspecified reasons. For example, the information was not delivered by the network, it was ignored by the service provider, and so forth.

No extensibility. All 32 bits are reserved.

For each of the possible parties involved in a call, the LINECALLPARTYID_ constants describes how the party ID information is formatted. This information is supplied in the LINECALLINFO data structure.


 LINECALLPRIVILEGE_ Constants

[New - Windows 95]

The LINECALLPRIVILEGE_ bit-flag constants describe the kinds of access rights or privileges an application with a call handle may have to the corresponding call.

LINECALLPRIVILEGE_NONE

The application has no privileges to the call. The application's handle is void and should not be used.

LINECALLPRIVILEGE_MONITOR

The application has monitor privileges to the call. These privileges allow the application to monitor state changes and query information and status about the call.

LINECALLPRIVILEGE_OWNER

The application has owner privileges to the call. These privileges allow the application to manipulate the call in ways that affect the state of the call.

No extensibility. All 32 bits are reserved.

When a call handle is first provided to an application or whenever call privileges of that application are modified, the LINE_CALLSTATE message is sent to the application. When an application hands off a call, and if the receiving application does not already have a handle with owner privileges, then this message informs the application about its new privileges to the call.


 LINECALLREASON_ Constants

[New - Windows 95]

The LINECALLREASON_ bit-flag constants describe the reason for a call.

LINECALLREASON_DIRECT

This is a direct inbound or outbound call.

LINECALLREASON_FWDBUSY

This call was forwarded from another extension that was busy at the time of the call.

LINECALLREASON_FWDNOANSWER

The call was forwarded from another extension that didn't answer the call after some number of rings.

LINECALLREASON_FWDUNCOND

The call was forwarded unconditionally from another number.

LINECALLREASON_PICKUP

The call was picked up from another extension.

LINECALLREASON_UNPARK

The call was retrieved as a parked call.

LINECALLREASON_REDIRECT

The call was redirected to this station.

LINECALLREASON_CALLCOMPLETION

The call was the result of a call completion request.

LINECALLREASON_TRANSFER

The call has been transferred from another number.

LINECALLREASON_REMINDER

The call is a reminder (or "recall") that the user has a call parked or on hold for (potentially) a long time.

LINECALLREASON_UNKNOWN

The reason for the call is currently unknown but may become known later.

LINECALLREASON_UNAVAIL

The reason for the call is unavailable and will not become known later.

LINECALLREASON_INTRUDE

The call intruded onto the line, either by a call completion action invoked by another station or by operator action. Depending on switch implementation, the call may appear either in the connected state, or conferenced with an existing active call on the line.

LINECALLREASON_PARKED

The call was parked on the address. Usually, it appears initially in the onhold state.

No extensibility. All 32 bits are reserved.

The LINECALLREASON_ constants are used in the dwReason field of the LINECALLINFO data structure.

For backward compatibility, it is the responsibility of the service provider to examine the negotiated API version on the line, and to not use these LINECALLREASON_ values if not supported on the negotiated version (LINECALLREASON_UNAVAIL may be substituted).


 LINECALLSELECT_ Constants

[New - Windows 95]

The LINECALLSELECT_ bit-flag constants describe which calls are to be selected.

LINECALLSELECT_LINE

Selects calls on the specified line device.

LINECALLSELECT_ADDRESS

Selects call on the specified address.

LINECALLSELECT_CALL

Selects related calls to the specified call. For example, the parties in a conference call.

No extensibility. All 32 bits are reserved.

This constant is used in lineGetNewCalls and to specify a selection (scope) of the calls that are requested.


 LINECALLSTATE_ Constants

[New - Windows 95]

The LINECALLSTATE_ bit-flag constants describe the call states a call can be in.

LINECALLSTATE_IDLE

The call is idle—no call exists.

LINECALLSTATE_OFFERING

The call is being offered to the station, signaling the arrival of a new call. In some environments, a call in the offering state does not automatically alert the user since alerting is done by the switch instructing the line to ring. It does not affect any call states.

LINECALLSTATE_ACCEPTED

The call was offering and has been accepted. This indicates to other (monitoring) applications that the current owner application has claimed responsibility for answering the call. In ISDN, this also initiates alerting to both parties.

LINECALLSTATE_DIALTONE

The call is receiving a dial tone from the switch, which means that the switch is ready to receive a dialed number.

LINECALLSTATE_DIALING

Destination address information (a phone number) is being sent to the switch over the call. Note that lineGenerateDigits does not place the line into the dialing state.

LINECALLSTATE_RINGBACK

The call is receiving ringback from the called address. Ringback indicates that the other station has been reached and is being alerted.

LINECALLSTATE_BUSY

The call is receiving a busy tone. A busy tone indicates that the call cannot be completed—either a circuit (trunk) or the remote party's station are in use.

LINECALLSTATE_SPECIALINFO

Special information is sent by the network. Special information is typically sent when the destination cannot be reached.

LINECALLSTATE_CONNECTED

The call has been established and the connection is made. Information is able to flow over the call between the originating address and the destination address.

LINECALLSTATE_PROCEEDING

Dialing has completed and the call is proceeding through the switch or telephone network.

LINECALLSTATE_ONHOLD

The call is on hold by the switch.

LINECALLSTATE_CONFERENCED

The call is currently a member of a multi-party conference call.

LINECALLSTATE_ONHOLDPENDCONF

The call is currently on hold while it is being added to a conference.

LINECALLSTATE_ONHOLDPENDTRANSFER

The call is currently on hold awaiting transfer to another number.

LINECALLSTATE_DISCONNECTED

The remote party has disconnected from the call.

LINECALLSTATE_UNKNOWN

The state of the call is not known. This may be due to limitations of the call-progress detection implementation.

The high-order 8 bits can define a device-specific substate of any of the predefined states, provided that one of the LINECALLSTATE_ bits defined above is also set. The low-order 24 bits are reserved for predefined states.

The LINECALLSTATE_ constants are used as parameters by the LINE_CALLSTATE message sent to the application. The message carries the new call state that the call transitioned to. These constants are also used as fields in the LINECALLSTATUS structure returned by the lineGetCallStatus function.


 LINECARDOPTION_ Constants

[New - Windows 95]

The LINECARDOPTION_ constants define values used in the dwOptions field of the LINECARDENTRY structure returned as part of the LINETRANSLATECAPS structure returned by lineGetTranslateCaps. The LINECARDOPTION_ constant has the following values:

LINECARDOPTION_PREDEFINED

This calling card is one of the predefined calling card definitions included by Microsoft with Windows Telephony. It cannot be removed entirely using Dial Helper; if the user attempts to remove it, it will become HIDDEN. It thus continues to be accessible for copying of dialing rules.

LINECARDOPTION_HIDDEN

This calling card has been hidden by the user. It is not shown by Dial Helper in the main listing of available calling cards, but will be shown in the list of cards from which dialing rules can be copied.

Not extensible. All 32 bits are reserved.


 LINECONNECTEDMODE_ Constants

[New - Windows 95]

The LINECONNECTEDMODE_ bit-flag constants describe different substates of a connected call. A mode is available as call status to the application after the call state transitions to connected, and within the LINE_CALLSTATE message indicating the call is in LINECALLSTATE_CONNECTED. These values are used when the call is on an address that is shared (bridged) with other stations (see the LINEADDRESSSHARING_ constants), primarily electronic key systems. The LINECONNECTEDMODE_ constants have the following values:

LINECONNECTEDMODE_ACTIVE

Indicates that the call is connected at the current station (the current station is a participant in the call). If the call state mode is 0 (zero), the application should assume that the value is "active" (which would be the situation on a non-bridged address). The mode may switch between ACTIVE and INACTIVE during a call if the user joins and leaves the call through manual action.  In such a bridged situation, a lineDrop or lineHold operation may possibly not actually drop the call or place it on hold, since the status of other stations on the call may govern (e.g., attempting to "hold" a call when other stations are particating won't be possible); instead, the call may simply be changed to the INACTIVE mode if it remains CONNECTED at other stations.

LINECONNECTEDMODE_INACTIVE

Indicates that the call is active at one or more other stations, but the current station is not a participant in the call.  If the call state mode is ZERO, the application should assume that the value is "active" (which would be the situation on a non-bridged address). A call in the INACTIVE state may be joined using the lineAnswer. Many operations which are valid in calls in the CONNECTED state may be impossible in the INACTIVE mode, such as monitoring for tones and digits, since the station is not actually participating in the call; monitoring is usually suspended (although not cancelled) while the call is in the INACTIVE mode.

Not extensible. All 32 bits are reserved.

For backward compatibility, it is the responsibility of the service provider to examine the negotiated API version on the line, and to not use these LINECONNECTEDMODE_ values if not supported on the negotiated version. It should be noted that applications which are not cognizant of LINECONNECTEDMODE_ will most likely assume that a call that is in LINECALLSTATE_CONNECTED is in LINECONNECTEDMODE_ACTIVE.

The LINECONNECTEDMODE_ACTIVE and LINECONNECTEDMODE_INACTIVE values are used when the call is on an address that is shared with other stations (bridged; see LINEADDRESSSHARING_ constants), primarily electronic key systems. If the connected call state mode is "active," it means that the call is connected at the current station (the current station is a participant in the call). If the call state mode is "inactive," the call is active at one or more other stations, but the current station is not a participant in the call. If the call state mode is ZERO, the application should assume that the value is "active" (which would be the situation on a non-bridged address). The mode may switch between ACTIVE and INACTIVE during a call if the user joins and leaves the call through manual action.

In such a bridged situation, a lineDrop or lineHold operation may possibly not actually drop the call or place it on hold, since the status of other stations on the call may govern (for example, attempting to "hold" a call when other stations are particating will not be possible); instead, the call may simply be changed to the INACTIVE mode if it remains connected at other stations. A call in the INACTIVE state may be joined using the lineAnswer.

Many operations which are valid in calls in the connected state may be impossible in the INACTIVE mode, such as monitoring for tones and digits, since the station is not actually participating in the call; monitoring is usually suspended (although not cancelled) while the call is in the INACTIVE mode.


 LINEDEVCAPFLAGS_ Constants

[New - Windows 95]

The LINEDEVCAPFLAGS_ bit-flag constants are a collection of Booleans describing various line device capabilities.

LINEDEVCAPFLAGS_CROSSADDRCONF

Specifies whether calls on different addresses on this line can be conferenced.

LINEDEVCAPFLAGS_HIGHLEVCOMP

Specifies whether high-level compatibility information elements are supported on this line.

LINEDEVCAPFLAGS_LOWLEVCOMP

Specifies whether low-level compatibility information elements are supported on this line.

LINEDEVCAPFLAGS_MEDIACONTROL

Specifies whether media-control operations are available for calls at this line.

LINEDEVCAPFLAGS_MULTIPLEADDR

Specifies whether lineMakeCall or lineDial are able to deal with multiple addresses at once (as for inverse multiplexing).

LINEDEVCAPFLAGS_CLOSEDROP

Specifies what happens when an open line is closed while the application has calls active on the line. If TRUE and used with the lineClose function, directs TAPI to forcibly drop calls when the last owner closes the line. The CLOSEDROP bit applies to external devices that keep the line open (such as a phone) and does not affect TAPI's behavior. Knowing the setting of this flag ahead of time makes it possible for the application to display an [OK]/[Cancel] dialog box for the user, warning that the active call will be lost. If CLOSEDROP is FALSE, a lineClose will not automatically drop any calls still active on the line if the service provider knows that some other device can keep the call alive. For example, if an analog line has the computer and phoneset both connect directly to them (in a party-line configuration), the service provider should set the flag to FALSE, as the offhook phone will automatically keep the call active even after the computer powers down.

LINEDEVCAPFLAGS_DIALBILLING

LINEDEVCAPFLAGS_DIALQUIET

LINEDEVCAPFLAGS_DIALDIALTONE

These flags indicate whether the "$", "@", or "W" dialable string modifier is supported for a given line device. It is TRUE if the modifier is supported; otherwise, FALSE. The "?" (prompt user to continue dialing) is never supported by a line device. These flags allow an application to determine "up front" which modifiers would result in the generation of a LINEERR. The application has the choice of pre-scanning dialable strings for unsupported characters or of passing the "raw" string from lineTranslateAddress directly to the provider as part of functions such as lineMakeCall or lineDial and let the function generate an error to tell it which unsupported modifier occurs first in the string.

No extensibility. All 32 bits are reserved.


 LINEDEVSTATE_ Constants

[New - Windows 95]

The LINEDEVSTATE_ bit-flag constants describe various line status events.

LINEDEVSTATE_OTHER

Device-status items other than those listed below have changed. The application should check the current device status to determine which items have changed.

LINEDEVSTATE_RINGING

The switch tells the line to alert the user.

LINEDEVSTATE_CONNECTED

The line was previously disconnected and is now connected to TAPI.

LINEDEVSTATE_DISCONNECTED

This line was previously connected and is now disconnected from TAPI.

LINEDEVSTATE_MSGWAITON

The "message waiting" indicator is turned on.

LINEDEVSTATE_MSGWAITOFF

The "message waiting" indicator is turned off.

LINEDEVSTATE_INSERVICE

The line is connected to TAPI. This happens when TAPI is first activated or when the line wire is physically plugged in and in-service at the switch while TAPI is active.

LINEDEVSTATE_OUTOFSERVICE

The line is out of service at the switch or physically disconnected. TAPI cannot be used to operate on the line device.

LINEDEVSTATE_MAINTENANCE

Maintenance is being performed on the line at the switch. TAPI cannot be used to operate on the line device.

LINEDEVSTATE_OPEN

The line has been opened by another application.

LINEDEVSTATE_CLOSE

The line has been closed by another application.

LINEDEVSTATE_NUMCALLS

The number of calls on the line device has changed.

LINEDEVSTATE_NUMCOMPLETIONS

The number of outstanding call completions on the line device has changed.

LINEDEVSTATE_TERMINALS

The terminal settings have changed. This may happen, for example, if multiple line devices share terminals among them (for example, two lines sharing a phone terminal).

LINEDEVSTATE_ROAMMODE

The roam mode of the line device has changed.

LINEDEVSTATE_BATTERY

The battery level has changed significantly (cellular).

LINEDEVSTATE_SIGNAL

The signal level has changed significantly (cellular).

LINEDEVSTATE_DEVSPECIFIC

The line's device-specific information has changed.

LINEDEVSTATE_REINIT

Items have changed in the configuration of line devices. To become aware of these changes (as for the appearance of new line devices) the application should reinitialize its use of TAPI.

LINEDEVSTATE_LOCK

The locked status of the line device has changed. (For more information, refer to the description of the LINEDEVSTATUSFLAGS_LOCKED bit in the LINEDEVSTATUSFLAGS_ constants.)

LINEDEVSTATE_CAPSCHANGE

Indicates that, due to configuration changes made by the user or other circumstances, one or more of the fields in the LINEDEVCAPS structure for the address have changed. The application should use lineGetDevCaps to read the updated structure. If a service provider sends a LINE_LINEDEVSTATE message containing this value to TAPI, TAPI will pass it along to applications which have negotiated this or a subsequent API version; applications negotiating a previous API version will receive LINE_LINEDEVSTATE messages specifying LINEDEVSTATE_REINIT, requiring them to shutdown and reinitialize their connection to TAPI in order to obtain the updated information.

LINEDEVSTATE_CONFIGCHANGE

Indicates that configuration changes have been made to one or more of the media devices associated with the line device. The application, if it desires, may use lineGetDevConfig to read the updated information. If a service provider sends a LINE_LINEDEVSTATE message containing this value to TAPI, TAPI will pass it along to applications which have negotiated this or a subsequent API version; applications negotiating a previous API version will not receive any notification.

LINEDEVSTATE_TRANSLATECHANGE

Indicates that, due to configuration changes made by the user or other circumstances, one or more of the fields in the LINETRANSLATECAPS structure have changed. The application should use lineGetTranslateCaps to read the updated structure. If a service provider sends a LINE_LINEDEVSTATE message containing this value to TAPI, TAPI will pass it along to applications which have negotiated this or a subsequent API version; applications negotiating a previous API version will receive LINE_LINEDEVSTATE messages specifying LINEDEVSTATE_REINIT, requiring them to shutdown and reinitialize their connection to TAPI in order to obtain the updated information.

LINEDEVSTATE_COMPLCANCEL

Indicates that the call completion identified by the completion ID contained in parameter dwParam2 of the LINE_LINEDEVSTATE message has been externally cancelled and is no longer considered valid (if that value were to be passed in a subsequent call to lineUncompleteCall, the function would fail with LINEERR_INVALCOMPLETIONID). If a service provider sends a LINE_LINEDEVSTATE message containing this value to TAPI, TAPI will pass it along to applications which have negotiated this or a subsequent API version; applications negotiating a previous API version will not receive any notification.

LINEDEVSTATE_REMOVED

Indicates that the device is being removed from the system by the service provider (most likely through user action, via a control panel or similar utility). A LINE_LINEDEVSTATE message with this value will normally be immediately followed by a LINE_CLOSE message on the device. Subsequent attempts to access the device prior to TAPI being reinitialized will result in LINEERR_NODEVICE being returned to the application. If a service provider sends a LINE_LINEDEVSTATE message containing this value to TAPI, TAPI will pass it along to applications which have negotiated this or a subsequent API version; applications negotiating a previous API version will not receive any notification.

No extensibility. All 32 bits are reserved.


 LINEDEVSTATUSFLAGS_ Constants

[New - Windows 95]

The LINEDEVSTATUSFLAGS_ bit-flag constants describe a collection of Boolean line device status items.

LINEDEVSTATUSFLAGS_CONNECTED

Specifies whether the line is connected to TAPI. If TRUE, the line is connected and TAPI is able to operate on the line device. If FALSE, the line is disconnected and the application is unable to control the line device through TAPI.

LINEDEVSTATUSFLAGS_MSGWAIT

Indicates whether the line has a message waiting. If TRUE, a message is waiting; if FALSE, no message is waiting.

LINEDEVSTATUSFLAGS_INSERVICE

Indicates whether the line is in service. If TRUE, the line is in service; if FALSE, the line is out of service.

LINEDEVSTATUSFLAGS_LOCKED

Indicates whether the line is locked or unlocked. This bit is most often used with line devices associated with cellular phones. Many cellular phones have a security mechanism that requires the entry of a password to enable the phone to place calls. This bit may be used to indicate to applications that the phone is locked and cannot place calls until the password is entered on the user interface of the phone so that the application can present an appropriate alert to the user.

No extensibility. All 32 bits are reserved.

LINEDEVSTATUSFLAGS_ constants are used within the dwDevStatusFlags field of the LINEDEVSTATUS data structure.


 LINEDIALTONEMODE_ Constants

[New - Windows 95]

The LINEDIALTONEMODE_ bit-flag constants describe different types of dialtones. A special dialtone typically carries a special meaning (as with message waiting).

LINEDIALTONEMODE_NORMAL

This is a "normal" dialtone which typically is a continuous tone.

LINEDIALTONEMODE_SPECIAL

This is a special dialtone indicating that a certain condition (known by the switch or network) is currently in effect. Special dial tones typically use an interrupted tone. As with a normal dial tone, this indicates that the switch is ready to receive the number to be dialed.

LINEDIALTONEMODE_INTERNAL

This is an internal dialtone, as within a PBX.

LINEDIALTONEMODE_EXTERNAL

This is an external (public network) dialtone.

LINEDIALTONEMODE_UNKNOWN

The dialtone mode is not currently known but may become known later.

LINEDIALTONEMODE_UNAVAIL

The dialtone mode is unavailable and will not become known.

The high-order 16 bits can be assigned for device-specific extensions. The low-order 16 bits are reserved.

The LINEDIALTONEMODE_ constants are used within the LINECALLSTATUS data structure for a call in the dialtone state.


 LINEDIGITMODE_ Constants

[New - Windows 95]

The LINEDIGITMODE_ constants describe different types of inband digit generation.

LINEDIGITMODE_PULSE

Uses rotary pulse sequences to signal digits. Valid digits are '0' through '9'.

LINEDIGITMODE_DTMF

Uses DTMF tones to signal digits. Valid digits are '0' through '9', '*', '#', 'A', 'B', 'C', and 'D'.

LINEDIGITMODE_DTMFEND

Uses DTMF tones to signal digits and detect the down edges. Valid digits are '0' through '9', '*', '#', 'A', 'B', 'C', and 'D'.

No extensibility. All 32 bits are reserved.

A digit mode can be specified when generating or detecting digits. Note that pulse digits are generated by making and breaking the local loop circuit. These pulses are absorbed by the switch. The remote end merely observes this as a series of inband audio clicks. Detecting digits sent as pulses must therefore be able to detect these sequences of 1 to 10 audible clicks.


 LINEDISCONNECTMODE_ Constants

[New - Windows 95]

The LINEDISCONNECTMODE_ bit-flag constants describe different reasons for a remote disconnect request. A disconnect mode is available as call status to the application after the call state transitions to disconnected.

LINEDISCONNECTMODE_NORMAL

This is a "normal" disconnect request by the remote party. The call was terminated normally.

LINEDISCONNECTMODE_UNKNOWN

The reason for the disconnect request is unknown but may become known later.

LINEDISCONNECTMODE_REJECT

The remote user has rejected the call.

LINEDISCONNECTMODE_PICKUP

The call was picked up from elsewhere.

LINEDISCONNECTMODE_FORWARDED

The call was forwarded by the switch.

LINEDISCONNECTMODE_BUSY

The remote user's station is busy.

LINEDISCONNECTMODE_NOANSWER

The remote user's station does not answer.

LINEDISCONNECTMODE_BADADDRESS

The destination address is invalid.

LINEDISCONNECTMODE_UNREACHABLE

The remote user could not be reached.

LINEDISCONNECTMODE_CONGESTION

The network is congested.

LINEDISCONNECTMODE_INCOMPATIBLE

The remote user's station equipment is incompatible with the type of call requested.

LINEDISCONNECTMODE_UNAVAIL

The reason for the disconnect is unavailable and will not become known later.

LINEDISCONNECTMODE_NODIALTONE

A dial tone was not detected within a service-provider defined timeout, at a point during dialing when one was expected (such as at a "W" in the dialable string). This can also occur without a service-provider-defined timeout period or without a value specified in the dwWaitForDialTone member of the LINEDIALPARAMS structure.

The high-order 16 bits can be assigned for device-specific extensions. The low-order 16 bits are reserved.

A remote disconnect request for a given call results in the call state transitioning to the disconnected state and a LINE_CALLSTATE message is sent to the application. The LINEDISCONNECTMODE_ information provides details about the remote disconnect request. It is available in the call's LINECALLSTATUS structure when the call is in the disconnected state. While a call is in this state, the application is still allowed to query the call's information and status. For example, user-to-user information that is received as part of the remote disconnect is available then. The application can clear a disconnected call by dropping the call.

For backward compatibility, it is the responsibility of the service provider to examine the negotiated API version on the line, and to not use this LINEDISCONNECTMODE_ value if it is not supported on the negotiated version (LINEDISCONNECTMODE_NORMAL or _UNKNOWN could be used instead).


 LINEERR_ Constants

[New - Windows 95]

This is the list of error codes that TAPI may return when invoking operations on lines, addresses, or calls. Consult the individual function descriptions to determine which of these error codes a particular function may return.

The values 0xC0000000 through 0xFFFFFFFF are available for device-specific extensions. The values 0x80000000 through 0xBFFFFFFF are reserved, while 0x00000000 through 0x7FFFFFFF are used as request IDs.

If an application gets an error return that it does not specifically handle (such as an error defined by a device-specific extension), it should treat the error as a LINEERR_OPERATIONFAILED (for an unspecified reason).


 LINEFEATURE_ Constants

[New - Windows 95]

The LINEFEATURE_ constants list the operations that can be invoked on a line using this API.

LINEFEATURE_DEVSPECIFIC

Device-specific operations can be used on the line.

LINEFEATURE_DEVSPECIFICFEAT

Device-specific features can be used on the line.

LINEFEATURE_FORWARD

Forwarding of all addresses can be used on the line.

LINEFEATURE_MAKECALL

An outbound call can be placed on this line using an unspecified address.

LINEFEATURE_SETMEDIACONTROL

Media control can be set on this line.

LINEFEATURE_SETTERMINAL

Terminal modes for this line can be set.

No extensibility. All 32 bits are reserved.

The LINEFEATURE_ constants are used in LINEDEVSTATUS (returned by lineGetLineDevStatus). LINEDEVSTATUS reports, for a given line, which line features can actually be invoked while the line is in the current state. An application would make this determination dynamically after line state changes, typically caused by address or call-related activities on the line.


 LINEFORWARDMODE_ Constants

[New - Windows 95]

The LINEFORWARDMODE_ bit-flag constants describe the conditions under which calls to an address can be forwarded.

LINEFORWARDMODE_UNCOND

Forward all calls unconditionally, irrespective of their origin. Use this value when unconditional forwarding for internal and external calls cannot be controlled separately. Unconditional forwarding overrides forwarding on busy and/or no answer conditions.

LINEFORWARDMODE_UNCONDINTERNAL

Forward all internal calls unconditionally. Use this value when unconditional forwarding for internal and external calls can be controlled separately.

LINEFORWARDMODE_UNCONDEXTERNAL

Forward all external calls unconditionally. Use this value when unconditional forwarding for internal and external calls can be controlled separately.

LINEFORWARDMODE_UNCONDSPECIFIC

Unconditionally forward all calls that originated at a specified address (selective call forwarding).

LINEFORWARDMODE_BUSY

Forward all calls on busy, irrespective of their origin. Use this value when forwarding for internal and external calls on busy and on no answer cannot be controlled separately.

LINEFORWARDMODE_BUSYINTERNAL

Forward all internal calls on busy. Use this value when forwarding for internal and external calls on busy and on no answer can be controlled separately.

LINEFORWARDMODE_BUSYEXTERNAL

Forward all external calls on busy. Use this value when forwarding for internal and external calls on busy and on no answer can be controlled separately.

LINEFORWARDMODE_BUSYSPECIFIC

Forward on busy all calls that originated at a specified address (selective call forwarding).

LINEFORWARDMODE_NOANSW

Forward all calls on no answer, irrespective of their origin. Use this value when call forwarding for internal and external calls on no answer cannot be controlled separately.

LINEFORWARDMODE_NOANSWINTERNAL

Forward all internal calls on no answer. Use this value when forwarding for internal and external calls on no answer can be controlled separately.

LINEFORWARDMODE_NOANSWEXTERNAL

Forward all external calls on no answer. Use this value when forwarding for internal and external calls on no answer can be controlled separately.

LINEFORWARDMODE_NOANSWSPECIFIC

Forward on no answer all calls that originated at a specified address (selective call forwarding).

LINEFORWARDMODE_BUSYNA

Forward all calls on busy/no answer, irrespective of their origin. Use this value when forwarding for internal and external calls on busy and on no answer cannot be controlled separately.

LINEFORWARDMODE_BUSYNAINTERNAL

Forward all internal calls on busy/no answer. Use this value when call forwarding on busy and on no answer cannot be controlled separately for internal calls.

LINEFORWARDMODE_BUSYNAEXTERNAL

Forward all external calls on busy/no answer. Use this value when call forwarding on busy and on no answer cannot be controlled separately for internal calls.

LINEFORWARDMODE_BUSYNASPECIFIC

Forward on busy/no answer all calls that originated at a specified address (selective call forwarding).

LINEFORWARDMODE_UNKNOWN

Calls are forwarded, but the conditions under which forwarding will occur are not known at this time. It is possible that the conditions may become known at a future time.

LINEFORWARDMODE_UNAVAIL

Calls are forwarded, but the conditions under which forwarding will occur are not known, and will never be known by the service provider.

No extensibility. All 32 bits are reserved.

The bit flags defined by LINEFORWARDMODE_ are not orthogonal. Unconditional forwarding ignores any specific condition such as busy or no answer. If unconditional forwarding is not in effect, then forwarding on busy and on no answer can be controlled separately or not separately. If controlled separately, the LINEFORWARDMODE_BUSY and LINEFORWARDMODE_NOANSW flags can be used separately. If not controlled separately, the flag LINEFORWARDMODE_BUSYNA must be used. Similarly, if forwarding of internal and external calls can be controlled separately, then LINEFORWARDMODE_INTERNAL and LINEFORWARDMODE_EXTERNAL flags can be used separately; otherwise the combination is used.

Address capabilities indicate which forwarding mode(s) are available for each address assigned to a line. An application can use lineForward to set forwarding conditions at the switch.

For backward compatibility, it is the responsibility of the service provider to examine the negotiated API version on the line, and to not use these LINEFORWARDMODE_ values if i not supported on the negotiated version.


 LINEGATHERTERM_ Constants

[New - Windows 95]

The LINEGATHERTERM_ bit-flag constants describe the conditions under which buffered digit gathering is terminated.

LINEGATHERTERM_BUFFERFULL

The requested number of digits has been gathered. The buffer is full.

LINEGATHERTERM_TERMDIGIT

One of the termination digits matched a received digit. The matched termination digit is the last digit in the buffer.

LINEGATHERTERM_FIRSTTIMEOUT

The first digit timeout expired. The buffer contains no digits.

LINEGATHERTERM_INTERTIMEOUT

The inter-digit timeout expired. The buffer contains at least one digit.

LINEGATHERTERM_CANCEL

The request was canceled by this application, by another application, or because the call terminated.

No extensibility. All 32 bits are reserved.


 LINEGENERATETERM_ Constants

[New - Windows 95]

The LINEGENERATETERM_ bit-flag constants describe the conditions under which digit or tone generation is terminated.

LINEGENERATETERM_DONE

The requested number of digits or requested tones have been generated for the requested duration.

LINEGENERATETERM_CANCEL

The digit or tone generation request was canceled by this application, by another application, or because the call terminated. This value may also be returned when digit or tone generation cannot be completed due to internal failure of the service provider.

No extensibility. All 32 bits are reserved.


 LINELOCATIONOPTION_ Constants

[New - Windows 95]

The LINELOCATIONOPTION_ constants define values used in the dwOptions field of the LINELOCATIONENTRY structure returned as part of the LINETRANSLATECAPS structure returned by lineGetTranslateCaps.

LINELOCATIONOPTION_PULSEDIAL

The default dialing mode at this location is pulse dialing. If this bit is set, lineTranslateAddress will insert a "P" dial modifier at the beginning of the dialable string returned when this location is selected. If this bit is not set, lineTranslateAddress will insert a "T" dial modifier at the beginning of the dialable string.

Not extensible. All 32 bits are reserved.


 LINEMEDIACONTROL_ Constants

[New - Windows 95]

The LINEMEDIACONTROL_ bit-flag constants describe a set of generic operations on media streams. The interpretations are determined by the media stream. The line device must have the media-control capability for any media-control operations to be effective.

LINEMEDIACONTROL_NONE

No change is to be made to the media stream.

LINEMEDIACONTROL_START

Start the media stream.

LINEMEDIACONTROL_RESET

Reset the media stream. Equivalent to an end-of-input. All buffers are released.

LINEMEDIACONTROL_PAUSE

Temporarily pause the media stream.

LINEMEDIACONTROL_RESUME

Resume a paused media stream.

LINEMEDIACONTROL_RATEUP

The speed of the media stream is increased by some stream-defined quantity.

LINEMEDIACONTROL_RATEDOWN

The speed of the media stream is decreased by some stream-defined quantity.

LINEMEDIACONTROL_RATENORMAL

The speed of the media stream is returned to normal.

LINEMEDIACONTROL_VOLUMEUP

The amplitude of the media stream is increased by some stream-defined quantity.

LINEMEDIACONTROL_VOLUMEDOWN

The amplitude of the media stream is decreased by some stream-defined quantity.

LINEMEDIACONTROL_VOLUMENORMAL

The amplitude of the media stream is returned to normal.

The high-order 16 bits can be assigned for device-specific extensions. The low-order 16 bits are reserved.

Media control is provided to improve performance of actions on media streams in response to telephony-related events. The application should normally manage a media stream through the media-specific API. The media-control functionality provided here is not intended to replace the native media APIs.

Media-control actions can be associated with the detection of digits, the detection of tones, the transition into a call state, and the detection of a media mode. Consult a line's device capabilities to determine whether media control is available on a line.


 LINEMEDIAMODE_ Constants

[New - Windows 95]

The LINEMEDIAMODE_ constants describe media modes (the data type of a media stream) on calls.

LINEMEDIAMODE_UNKNOWN

A media stream exists but its mode is not currently known and may become known later. This would correspond to a call with an unclassified media type. In typical analog telephony environments, an inbound call's media mode may be unknown until after the call has been answered and the media stream has been filtered to make a determination.

If the unknown media-mode flag is set, other media flags may also be set. This is used to signify that the media is unknown but that it is likely to be one of the other selected media modes.

LINEMEDIAMODE_INTERACTIVEVOICE

The presence of voice energy on the call, and the call is treated as an interactive call with humans on both ends.

LINEMEDIAMODE_AUTOMATEDVOICE

The presence of voice energy on the call and the voice is locally handled by an automated application.

LINEMEDIAMODE_DATAMODEM

A data modem session on the call.

LINEMEDIAMODE_G3FAX

A group 3 fax is being sent or received over the call.

LINEMEDIAMODE_TDD

A TDD (Telephony Devices for the Deaf) session on the call.

LINEMEDIAMODE_G4FAX

A group 4 fax is being sent or received over the call.

LINEMEDIAMODE_DIGITALDATA

Digital data is being sent or received over the call.

LINEMEDIAMODE_TELETEX

A teletex session on the call. Teletex is one of the telematic services.

LINEMEDIAMODE_VIDEOTEX

A videotex session on the call. Videotex is one the telematic services.

LINEMEDIAMODE_TELEX

A telex session on the call. Telex is one the telematic services.

LINEMEDIAMODE_MIXED

A mixed session on the call. Mixed is one the ISDN telematic services.

LINEMEDIAMODE_ADSI

An ADSI (Analog Display Services Interface) session on the call.

LINEMEDIAMODE_VOICEVIEW

The media mode of the call is VoiceView.

The high-order 8 bits can be assigned for device-specific extensions. The low-order 24 bits are reserved.

Note that bearer mode and media mode are different notions. The bearer mode of a call is an indication of the quality of the telephone connection as provided primarily by the network. The media mode of a call is an indication of the type of information stream that is exchanged over that call. Group 3 fax or data modem are media modes that use a call with a 3.1kHz voice bearer mode.

For backward compatibility, it is the responsibility of the service provider to examine the negotiated API version on the line, and to not use this LINEMEDIAMODE_ value if not supported on the negotiated version.


 LINEOFFERINGMODE_ Constants

[New - Windows 95]

The LINEOFFERINGMODE_ bit-flag constants describe different substates of an offering call. A mode is available as call status to the application after the call state transitions to offering, and within the LINE_CALLSTATE message indicating the call is in LINECALLSTATE_OFFERING. These values are used when the call is on an address that is shared (bridged) with other stations (see the LINEADDRESSSHARING_ constants), primarily electronic key systems.

LINEOFFERINGMODE_ACTIVE

Indicates that the call is alerting at the current station (will be accompanied by LINEDEVSTATE_RINGING messages), and if any application is set up to automatically answer, it may do so. If the call state mode is ZERO, the application should assume that the value is "active" (which would be the situation on a non-bridged address).

LINEOFFERINGMODE_INACTIVE

Indicates that the call is being offered at more than one station, but the current station is not alerting (e.g., it may be an attendant station where the offering status is advisory, such as blinking a light); software at the station set for automatic answering should preferably not answer the call, since this should be the perogative at the primary (alerting) station, but lineAnswer may be used to connect the call.

Not extensible. All 32 bits are reserved.

For backward compatibility, it is the responsibility of the service provider to examine the negotiated API version on the line, and to not use these LINEOFFERINGMODE_ values if not supported on the negotiated version. It should be noted that applications which are not cognizant of LINEOFFERINGMODE_ will most likely assume that a call that is in LINECALLSTATE_OFFERING is in LINEOFFERINGMODE_ACTIVE.

The LINEOFFERINGMODE_ACTIVE and LINEOFFERINGMODE_INACTIVE values are used when the call is on an address that is shared with other stations (bridged; see LINEADDRESSSHARING_ constants), primarily electronic key systems. If the offering call state mode is "active," it means that the call is alerting at the current station (will be accompanied by LINEDEVSTATE_RINGING messages), and if any application is set up to automatically answer, it may do so. If the call state mode is "inactive," the call is being offered at more than one station, but the current station is not alerting (e.g., it may be an attendant station where the offering status is advisory, such as blinking a light); software at the station set for automatic answering should preferably not answer the call, since this should be the perogative at the primary (alerting) station, but lineAnswer may be used to connect the call. If the call state mode is ZERO, the application should assume that the value is "active" (which would be the situation on a non-bridged address).


 LINEPARKMODE_ Constants

[New - Windows 95]

The LINEPARKMODE_ bit-flag constants describe different ways of parking calls.

LINEPARKMODE_DIRECTED

Specifies directed call park. The address where the call is to be parked must be supplied to the switch.

LINEPARKMODE_NONDIRECTED

Specifies nondirected call park. The address where the call is parked is selected by the switch and provided by the switch to the application.

No extensibility. All 32 bits are reserved.

The LINEPARKMODE_ constants are used when parking a call. Consult a line's address device capabilities to find out which park mode is available.


 LINEREMOVEFROMCONF_ Constants

[New - Windows 95]

The LINEREMOVEFROMCONF_ scalar constants describe how parties participating in a conference call can be removed from a conference call.

LINEREMOVEFROMCONF_NONE

Parties cannot be removed from the conference call.

LINEREMOVEFROMCONF_LAST

Only the most recently added party can be removed from the conference call

LINEREMOVEFROMCONF_ANY

Any participating party can be removed from the conference call.

No extensibility. All 32 bits are reserved.


 LINEREQUESTMODE_ Constants

[New - Windows 95]

The LINEREQUESTMODE_ bit-flag constants describe different types of telephony requests that can be made from one application to another.

LINEREQUESTMODE_MAKECALL

A tapiRequestMakeCall request.

No extensibility. All 32 bits are reserved.


 LINEROAMMODE_ Constants

[New - Windows 95]

The LINEROAMMODE_ bit-flag constants describe the roaming status of a line device.

LINEROAMMODE_UNKNOWN

The roam mode is currently unknown but may become known later.

LINEROAMMODE_UNAVAIL

The roam mode is unavailable and will not be known.

LINEROAMMODE_HOME

The line is connected to the home network node.

LINEROAMMODE_ROAMA

The line is connected to the Roam-A carrier and calls are charged accordingly.

LINEROAMMODE_ROAMB

The line is connected to the Roam-B carrier and calls are charged accordingly.

No extensibility. All 32 bits are reserved.


 LINESPECIALINFO_ Constants

[New - Windows 95]

The LINESPECIALINFO_ bit-flag constants describes special information signals that the network may use to report various reporting and network observation operations. They are special coded tone sequences transmitted at the beginning of network advisory recorded announcements.

LINESPECIALINFO_NOCIRCUIT

This special information tone preceeds a no circuit or an emergency announcement (trunk blockage category).

LINESPECIALINFO_CUSTIRREG

This special information tone preceeds a vacant number, AIS, Centrex (™)  number change and nonworking station, access code not dialed or dialed in error, or manual intercept operator message (customer irregularity category). LINESPECIALINFO_CUSTIRREG is also reported when billing information is rejected and when the dialed address is blocked at the switch.

LINESPECIALINFO_REORDER

This special information tone preceeds a reorder announcement (equipment irregularity category). LINESPECIALINFO_REORDER is also reported when the telephone is kept offhook too long.

LINESPECIALINFO_UNKNOWN

Specifics about the special information tone are currently unknown but may become known later.

LINESPECIALINFO_UNAVAIL

Specifics about the special information tone are unavailable and will not become known.

The high-order 16 bits can be assigned for device-specific extensions. The low-order 16 bits are reserved.

Special information tones are defined for advisory messages and are not normally used for billing or supervisory purpose.


 LINETERMDEV_ Constants

[New - Windows 95]

The LINETERMDEV_ bit-flag constants describe different types of terminal devices.

LINETERMDEV_PHONE

The terminal is a phone set.

LINETERMDEV_HEADSET

The terminal is a headset.

LINETERMDEV_SPEAKER

The terminal is an external speaker and microphone.

No extensibility. All 32 bits are reserved.

These constants are used to characterize a line's terminal device and help an application to determine the nature of a terminal device.


 LINETERMMODE_ Constants

[New - Windows 95]

The LINETERMMODE_ bit-flag constants describe different types of events on a phone line that can be routed to a terminal device.

LINETERMMODE_BUTTONS

These are button-press events sent from the terminal to the line.

LINETERMMODE_LAMPS

These are lamp events sent from the line to the terminal.

LINETERMMODE_DISPLAY

This is display information sent from the line to the terminal.

LINETERMMODE_RINGER

This is ringer-control information sent from the switch to the terminal.

LINETERMMODE_HOOKSWITCH

These are hookswitch events sent from the terminal to the line.

LINETERMMODE_MEDIATOLINE

This is the unidirectional media stream from the terminal to the line associated with a call on the line. Use this value when the routing of both unidirectional channels of a call's media stream can be controlled independently.

LINETERMMODE_MEDIAFROMLINE

This is the unidirectional media stream from the line to the terminal associated with a call on the line. Use this value when the routing of both unidirectional channels of a call's media stream can be controlled independently.

LINETERMMODE_MEDIABIDIRECT

This is the bidirectional media stream associated with a call on the line and the terminal. Use this value when the routing of both unidirectional channels of a call's media stream cannot be controlled independently.

No extensibility. All 32 bits are reserved.

These constants describe the classes of control and information streams that can be routed directly between a line device and a terminal device (such as a phone set).


 LINETERMSHARING_ Constants

[New - Windows 95]

The LINETERMSHARING_ bit-flag constants describe different ways in which a terminal can be shared between line devices, addresses, or calls.

LINETERMSHARING_PRIVATE

The terminal device is private to a single line device.

LINETERMSHARING_SHAREDEXCL

The terminal device can be used by multiple lines. The last line device to do a lineSetTerminal to the terminal for a given terminal mode will have exclusive connection to the terminal for that mode.

LINETERMSHARING_SHAREDCONF

The terminal device can be used by multiple lines. The lineSetTerminal requests of the various terminals end up being "merged" or conferenced at the terminal.

No extensibility. All 32 bits are reserved.

These constants describe the classes of control and information streams that can be routed directly between a line device and a terminal device (such as a phone set).


 LINETOLLLISTOPTION_ Constants

[New - Windows 95]

The LINETOLLLISTOPTION_ bit-flag constants describe options for manipulating a toll list.

LINETOLLLISTOPTION_ADD

A prefix is to be added to the toll list.

LINETOLLLISTOPTION_REMOVE

A prefix is to be removed from the toll list.

No extensibility. All 32 bits are reserved.


 LINETONEMODE_ Constants

[New - Windows 95]

The LINETONEMODE_ constants describe different selections that are used when generating line tones.

LINETONEMODE_CUSTOM

The tone is a custom tone defined by its component frequencies, of type LINEGENERATETONE.

LINETONEMODE_RINGBACK

The tone is ringback tone. Exact definition is service-provider defined.

LINETONEMODE_BUSY

The tone is a busy tone. Exact definition is service-provider defined.

LINETONEMODE_BEEP

The tone is a beep, such as that used to announce the beginning of a recording. Exact definition is service-provider defined.

LINETONEMODE_BILLING

The tone is a billing information tone such as a credit card prompt tone. Exact definition is service-provider defined.

The high-order 16 bits can be assigned for device-specific extensions. The low-order 16 bits are reserved.

These constants are used to define tones to be generated inband over a call to the remote party. Note that tone detection of non-custom tones does not use these constants.


 LINETRANSFERMODE_ Constants

[New - Windows 95]

The LINETRANSFERMODE_ bit-flag constants describe different ways of resolving call transfer requests.

LINETRANSFERMODE_TRANSFER

The transfer is resolved by transferring the initial call to the consultation call. Both calls will become idle to the application.

LINETRANSFERMODE_CONFERENCE

The transfer is resolved by establishing a three-way conference between the application, the party connected to the initial call, and the party connected to the consultation call. A conference call is created when this option is selected.

No extensibility. All 32 bits are reserved.


 LINETRANSLATEOPTION_ Constants

[New - Windows 95]

The LINETRANSLATEOPTION_ bit-flag constant describes an option used by address translation.

LINETRANSLATEOPTION_CARDOVERRIDE

The default calling card is to be overriden with a specified one.

LINETRANSLATEOPTION_CANCELCALLWAITING

If a Cancel Call Waiting string is defined for the location, setting this bit will cause that string to be inserted at the beginning of the dialable string. This is commonly used by datamodem and fax applications to prevent interruption of calls by call waiting beeps. If no Cancel Call Waiting string is defined for the location, this bit has no affect. Note that applications using this bit are advised to also set the LINECALLPARAMFLAGS_SECURE bit in the dwCallParamFlags field of the LINECALLPARAMS structure passed in to lineMakeCall via the lpCallParams parameter, so that if the line device uses a mechanism other than dialable digits to supress call interrupts that that mechanism will be invoked.

LINETRANSLATEOPTION_FORCELOCAL

If the number is local but would have been translated as a long distance call (LINETRANSLATERESULT_INTOLLLIST bit set in the LINETRANSLATEOUTPUT structure), this option will force it to be translated as local. This is a temporary override of the toll list setting.

LINETRANSLATEOPTION_FORCELD

If the address could potentially have been a toll call, but would have been translated as a local call (LINETRANSLATERESULT_NOTINTOLLLIST bit set in the LINETRANSLATEOUTPUT structure), this option will force it to be translated as long distance. This is a temporary override of the toll list setting.

No extensibility. All 32 bits are reserved.


 LINETRANSLATERESULT_ Constants

[New - Windows 95]

The LINETRANSLATERESULT_ bit-flag constants describe various results of an address translation.

LINETRANSLATERESULT_CANONICAL

Indicates that the input string was in valid canonical format.

LINETRANSLATERESULT_INTERNATIONAL

Indicates that the call is being treated as an international call (country code specified in the destination address is the different from the country code specified for the CurrentLocation).

LINETRANSLATERESULT_LONGDISTANCE

Indicates that the call is being treated as a long distance call (country code specified in the destination address is the same but area code is different from those specified for the CurrentLocation).

LINETRANSLATERESULT_LOCAL

Indicates that the call is being treated as a local call (country code and area code specified in the destination address are the same as those specified for the CurrentLocation).

LINETRANSLATERESULT_INTOLLLIST

Indicates that the local call is being dialed as long distance because the country has toll calling and the prefix appears in the TollPrefixList of the CurrentLocation.

LINETRANSLATERESULT_NOTINTOLLLIST

Indicates that the country supports toll calling but the prefix does not appear in the TollPrefixList, so the call is dialed as a local call. Note that if both INTOLLIST and NOTINTOLLIST are off, the current country does not support toll prefixes, and user-interface elements related to toll prefixes should not be presented to the user; if either such bit is on, the country does support toll lists, and the related user-interface elements should be enabled.

LINETRANSLATERESULT_DIALBILLING

Indicates that the returned address contains a "$".

LINETRANSLATERESULT_DIALQUIET

Indicates that the returned address contain a "@".

LINETRANSLATERESULT_DIALDIALTONE

Indicates that the returned address contains a "W".

LINETRANSLATERESULT_DIALPROMPT

Indicates that the returned address contains a "?".

No extensibility. All 32 bits are reserved.


 Phone Device Reference

Following are the functions, messages, structures, and constants used with TAPI phone devices.


 Functions

Following are the TAPI phone functions.


 phoneClose

[New - Windows 95]

LONG phoneClose(HPHONE hPhone)

Closes the specified open phone device.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

PHONEERR_INVALPHONEHANDLE	PHONEERR_NOMEM
PHONEERR_OPERATIONFAILED	PHONEERR_RESOURCEUNAVAIL
PHONEERR_OPERATIONUNAVAIL	PHONEERR_UNINITIALIZED
hPhone

Specifies a handle to the open phone device to be closed. If the function is successful, the handle is no longer valid.

After the open phone device has been successfully closed, the implementation sends a PHONE_CLOSE message to the application. Note that these messages can also be sent unsolicited as a result of the phone device being reclaimed somehow. An application should therefore be prepared to handle these unsolicited close messages. At the time the phone device is closed, any outstanding asynchronous replies are suppressed.


 phoneConfigDialog

[New - Windows 95]

LONG phoneConfigDialog(HPHONE dwDeviceID, HWND hwndOwner,
    LPCSTR lpszDeviceClass)

Causes the provider of the specified phone device to display a modal dialog (attached to the application's hwndOwner) that allows the user to configure parameters related to the phone device specified by dwDeviceID.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

PHONEERR_BADDEVICEID	PHONEERR_NOMEM
PHONEERR_INUSE	PHONEERR_OPERATIONFAILED
PHONEERR_INVALPARAM	PHONEERR_OPERATIONUNAVAIL
PHONEERR_INVALDEVICECLASS	PHONEERR_RESOURCEUNAVAIL
PHONEERR_INVALPOINTER	PHONEERR_UNINITIALIZED
PHONEERR_NODEVICE
dwDeviceID

Specifies the phone device to be configured.

hwndOwner

Specifies a handle to a window to which the dialog is to be attached.

lpszDeviceClass

Specifies a pointer to a NULL-terminated string that identifies a device class name. This device class allows the application to select a specific subscreen of configuration information applicable to that device class. This parameter is optional and can be left NULL or empty, in which case the highest level configuration is selected.

The lpszDeviceClass parameter allows the application to select a specific subscreen of configuration information applicable to the device class in which the user is interested; the permitted strings are the same as for phoneGetID. For example, if the phone supports the wave API, passing "wave/in" as lpszDeviceClass would cause the provider to display the parameters related specifically to wave (or at least to start at the corresponding point in a multilevel configuration dialog chain, eliminating the need to search for relevant parameters).

lpszDeviceClass should be "tapi/phone", "", or NULL to cause the provider to display the highest level configuration for the phone.


 phoneDevSpecific

[New - Windows 95]

LONG phoneDevSpecific(HPHONE hPhone, LPVOID lpParams, DWORD dwSize)

Is used as a general extension mechanism to enable a Telephony API implementation to provide features not described in the other TAPI functions. The meanings of these extensions are device specific.

•	Returns a positive request ID if the function will be completed asynchronously or a negative error number if an error has occurred. The dwParam2 parameter of the corresponding PHONE_REPLY callback message is zero if the function is successful or it is a negative error number if an error has occurred. Possible return values are:

PHONEERR_INVALPHONEHANDLE	PHONEERR_NOMEM
PHONEERR_INVALPOINTER	PHONEERR_RESOURCEUNAVAIL
PHONEERR_OPERATIONUNAVAIL	PHONEERR_UNINITIALIZED
PHONEERR_OPERATIONFAILED
Additional return values are device specific.

hPhone

Specifies a handle to a phone device.

lpParams

Specifies a pointer to a memory area used to hold a parameter block. Its interpretation is device specific. The contents of the parameter block is passed unchanged to or from the service provider by TAPI.

dwSize

The size in bytes of the parameter block area.

This operation provides a generic parameter profile. The interpretation of the parameter block is device specific. Indications and replies that are device specific should use the PHONE_DEVSPECIFIC message.

A service provider can provide access to device-specific functions by defining parameters for use with this operation. Applications that want to make use of these device-specific extensions should consult the device-specific (vendor-specific) documentation that describes which extentions are defined. Note that an application that relies on these device-specific extensions will typically not be portable to work with other service-provider environments.


 phoneGetButtonInfo

[New - Windows 95]

LONG phoneGetButtonInfo(HPHONE hPhone, DWORD dwButtonLampID,
    LPPHONEBUTTONINFO lpButtonInfo)

Returns information about the specified button.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

PHONEERR_INVALPHONEHANDLE	PHONEERR_NOMEM
PHONEERR_INVALBUTTONLAMPID	PHONEERR_RESOURCEUNAVAIL
PHONEERR_INVALPOINTER	PHONEERR_OPERATIONFAILED
PHONEERR_INVALPHONESTATE	PHONEERR_STRUCTURETOOSMALL
PHONEERR_OPERATIONUNAVAIL	PHONEERR_UNINITIALIZED
hPhone

Specifies a handle to the open phone device.

dwButtonLampID

Specifies a button on the phone device.

lpButtonInfo

Specifies a pointer to a variably sized structure of type PHONEBUTTONINFO. This data structure describes the mode, the function, and provides additional descriptive text corresponding to the button.


 phoneGetData

[New - Windows 95]

LONG phoneGetData(HPHONE hPhone, DWORD dwDataID, LPVOID lpData,
    DWORD dwSize)

Uploads the information from the specified location in the open phone device to the specified buffer.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

PHONEERR_INVALPHONEHANDLE	PHONEERR_NOMEM
PHONEERR_INVALPOINTER	PHONEERR_RESOURCEUNAVAIL
PHONEERR_INVALPHONESTATE	PHONEERR_OPERATIONFAILED
PHONEERR_INVALDATAID	PHONEERR_UNINITIALIZED
PHONEERR_OPERATIONUNAVAIL
hPhone

Specifies a handle to the open phone device.

dwDataID

Specifies where in the phone device the buffer is to be uploaded from.

lpData

Specifies a pointer to the memory buffer where the data is to be uploaded.

dwSize

Specifies the size of the data buffer in bytes.

The function uploads a maximum of dwSize bytes from the phone device into the memory area pointed to by lpData. If dwSize is zero, nothing is copied. The size of each data area is listed in the phone's device capabilities.


 phoneGetDevCaps

[New - Windows 95]

LONG phoneGetDevCaps(HPHONEAPP hPhoneApp, DWORD dwDeviceID,
    DWORD dwAPIVersion, DWORD dwExtVersion, LPPHONECAPS lpPhoneCaps)

Queries a specified phone device to determine its telephony capabilities.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

PHONEERR_INVALAPPHANDLE	PHONEERR_INVALPOINTER
PHONEERR_BADDEVICEID	PHONEERR_OPERATIONFAILED
PHONEERR_INCOMPATIBLEAPIVERSION	PHONEERR_OPERATIONUNAVAIL
PHONEERR_INCOMPATIBLEEXTVERSION	PHONEERR_NOMEM
PHONEERR_STRUCTURETOOSMALL	PHONEERR_RESOURCEUNAVAIL
PHONEERR_NODRIVER	PHONEERR_UNINITIALIZED
PHONEERR_NODEVICE
hPhoneApp

Specifies the handle to the application's registration with TAPI.

dwDeviceID

Specifies the phone device to be queried.

dwAPIVersion

Specifies the version number of the Telephony API to be used. The high-order word contains the major version number; the low-order word contains the minor version number. This number is obtained with the function phoneNegotiateAPIVersion.

dwExtVersion

Specifies the version number of the service provider-specific extensions to be used. This number is obtained with the function phoneNegotiateExtVersion. It can be left zero if no device-specific extensions are to be used. Otherwise, the high-order word contains the major version number; the low-order word contains the minor version number.

lpPhoneCaps

Specifies a pointer to a variably sized structure of type PHONECAPS. Upon successful completion of the request, this structure is filled with phone device capabilities information.

Before using phoneGetDevCaps, the application must negotiate the TAPI version number to use, and optionally, the extension version to use.

TAPI and extension version numbers are those under which TAPI, Telephony DLL, and service provider must operate. If version ranges do not overlap, the application and API or service-provider versions are incompatible and an error is returned.


 phoneGetDisplay

[New - Windows 95]

LONG phoneGetDisplay(HPHONE hPhone, LPVARSTRING lpDisplay)

Returns the current contents of the specified phone display.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

PHONEERR_INVALPHONEHANDLE	PHONEERR_RESOURCEUNAVAIL
PHONEERR_INVALPOINTER	PHONEERR_OPERATIONFAILED
PHONEERR_INVALPHONESTATE	PHONEERR_STRUCTURETOOSMALL
PHONEERR_OPERATIONUNAVAIL	PHONEERR_UNINITIALIZED
PHONEERR_NOMEM
hPhone

Specifies a handle to the open phone device.

lpDisplay

Specifies a pointer to the memory location where the display content is to be stored, of type VARSTRING.

The lpDisplay memory area should be at least (dwNumRows * dwNumColumns) elements in size to receive all of the display information. dwNumRows and dwNumColumns are available in the PHONECAPS structure returned by phoneGetDevCaps.


 phoneGetGain

[New - Windows 95]

LONG phoneGetGain(HPHONE hPhone, DWORD dwHookSwitchDev,
    LPDWORD lpdwGain)

Returns the gain setting of the microphone of the specified phone's hookswitch device.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

PHONEERR_INVALPHONEHANDLE	PHONEERR_NOMEM
PHONEERR_INVALPOINTER	PHONEERR_RESOURCEUNAVAIL
PHONEERR_INVALPHONESTATE	PHONEERR_OPERATIONFAILED
PHONEERR_INVALHOOKSWITCHDEV	PHONEERR_UNINITIALIZED
PHONEERR_OPERATIONUNAVAIL
hPhone

Specifies a handle to the open phone device.

dwHookSwitchDev

Identifies the hookswitch device whose gain level is queried. Note that dwHookSwitchDev can have at most one bit set. This parameter uses the following PHONEHOOKSWITCHDEV_ constants:

PHONEHOOKSWITCHDEV_HANDSET

This is the phone's handset.

PHONEHOOKSWITCHDEV_SPEAKER

This is the phone's speakerphone or adjunct.

PHONEHOOKSWITCHDEV_HEADSET

This is the phone's headset.

lpdwGain

Specifies a pointer to a DWORD-sized location containing the current gain setting of the hookswitch microphone component. dwGain specifies the volume level of the hookswitch device. This is a number in the range 0x00000000 (silence) to 0x0000FFFF (maximum volume). The actual granularity and quantization of gain settings in this range are service provider specific.


 phoneGetHookSwitch

[New - Windows 95]

LONG phoneGetHookSwitch(HPHONE hPhone, LPDWORD lpdwHookSwitchDevs)

Returns the current hookswitch mode of the specified open phone device.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

PHONEERR_INVALPHONEHANDLE	PHONEERR_NOMEM
PHONEERR_INVALPOINTER	PHONEERR_RESOURCEUNAVAIL
PHONEERR_INVALPHONESTATE	PHONEERR_OPERATIONFAILED
PHONEERR_OPERATIONUNAVAIL	PHONEERR_UNINITIALIZED
hPhone

Specifies a handle to the open phone device.

lpdwHookSwitchDevs

Specifies a pointer to a DWORD-sized location to be filled with the mode of the phone's hookswitch devices. If a bit position is FALSE, the corresponding hookswitch device is on-hook; if TRUE, the microphone and/or speaker part of the corresponding hookswitch device is offhook. To find out whether the microphone and/or speaker are enabled, the application can use phoneGetStatus. This parameter uses the following PHONEHOOKSWITCHDEV_ constants:

PHONEHOOKSWITCHDEV_HANDSET

This is the phone's handset.

PHONEHOOKSWITCHDEV_SPEAKER

This is the phone's speakerphone or adjunct.

PHONEHOOKSWITCHDEV_HEADSET

This is the phone's headset.

After the hookswitch state of a device changes, and if hookswitch monitoring is enabled, the application is sent a PHONE_STATE message.


 phoneGetIcon

[New - Windows 95]

LONG phoneGetIcon(DWORD dwDeviceID, LPCSTR lpszDeviceClass,
    LPHICON lphIcon)

Allows an application to retrieve a service phone device-specific (or provider-specific) icon that can be displayed to the user.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

PHONEERR_BADDEVICEID	PHONEERR_RESOURCEUNAVAIL
PHONEERR_INVALPOINTER	PHONEERR_OPERATIONFAILED
PHONEERR_INVALDEVICECLASS	PHONEERR_UNINITIALIZED
PHONEERR_NOMEM	PHONEERR_NODEVICE
dwDeviceID

Specifies the phone device whose icon is requested.

lpszDeviceClass

Specifies a pointer to a NULL-terminated string that identifies a device class name. This device class allows the application to select a specific sub-icon applicable to that device class. This parameter is optional and can be left NULL or empty, in which case the highest-level icon associated with the phone device rather than a specified media stream device would be selected.

lphIcon

Specifies a pointer to a memory location in which the handle to the icon is returned.

phoneGetIcon causes the provider to return a handle (in lphIcon) to an icon resource (obtained from LoadIcon) associated with the specified phone. The icon handle will be for a resource associated with the provider; the application must use CopyIcon if it wishes to reference the icon after the provider is unloaded, which is unlikely to happen as long as the application has the phone open.

lpszDeviceClass allows the provider to return different icons based on the type of service being referenced by the caller. The permitted strings are the same as for phoneGetID. For example, if the phone supports the Comm API, passing "COMM" as lpszDeviceClass causes the provider to return an icon related specifically to the Comm device functions of the service provider.

The parameters "tapi/phone", "", or NULL may be used to request the icon for the phone service. If the provider does not return an icon, TAPI substitutes a generic Windows Telephony phone device icon.


 phoneGetID

[New - Windows 95]

LONG phoneGetID(HPHONE hPhone, LPVARSTRING lpDeviceID,
    LPCSTR lpszDeviceClass)

Returns a device ID for the given device class associated with the specified phone device.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

PHONEERR_INVALPHONEHANDLE	PHONEERR_NOMEM
PHONEERR_INVALPOINTER	PHONEERR_RESOURCEUNAVAIL
PHONEERR_INVALDEVICECLASS	PHONEERR_UNINITIALIZED
PHONEERR_OPERATIONFAILED	PHONEERR_STRUCTURETOOSMALL
PHONEERR_OPERATIONUNAVAIL
hPhone

Specifies a handle to an open phone device.

lpDeviceID

Specifies a pointer to a data structure of type VARSTRING where the device ID is returned. Upon successful completion of the request, this location is filled with the device ID. The format of the returned information depends on the method used by the device class (API) for naming devices.

lpszDeviceClass

Specifies a pointer to a NULL-terminated string that specifies the device class of the device whose ID is requested. Valid device class strings are those used in the SYSTEM.INI section to identify device classes.

This function can be used to retrieve a phone device ID given a phone handle. It can also be used to obtain the device ID of the media device (for device classes such as COM, wave, MIDI, phone, line, or NDIS) associated with the opened phone device. The names of these device class are not case sensitive. This ID can then be used with the appropriate media API to select the corresponding device.

See Chapter 9, "Device Classes" for device class names.

A vendor that defines a device-specific media mode also needs to define the corresponding device-specific (proprietary) API to manage devices of the media mode. To avoid collisions on device class names assigned independently by different vendors, a vendor should select a name that uniquely identifies both the vendor and, following it, the media type. For example: "intel/video".


 phoneGetLamp

[New - Windows 95]

LONG phoneGetLamp(HPHONE hPhone, DWORD dwButtonLampID,
    LPDWORD lpdwLampMode)

Returns the current lamp mode of the specified lamp.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

PHONEERR_INVALPHONEHANDLE	PHONEERR_NOMEM
PHONEERR_INVALBUTTONLAMPID	PHONEERR_RESOURCEUNAVAIL
PHONEERR_INVALPOINTER	PHONEERR_OPERATIONFAILED
PHONEERR_INVALPHONESTATE	PHONEERR_UNINITIALIZED
PHONEERR_OPERATIONUNAVAIL
hPhone

Specifies a handle to the open phone device.

dwButtonLampID

Specifies the ID of the lamp to be queried.

lpdwLampMode

Specifies a pointer to a memory location that will hold the lamp mode status of the given lamp. Note that lpdwLampMode can have at most one bit set. This parameter uses the following PHONELAMPMODE_ constants:

PHONELAMPMODE_BROKENFLUTTER

Broken flutter is the superposition of flash and flutter.

PHONELAMPMODE_FLASH

Flash means slow on and off.

PHONELAMPMODE_FLUTTER

Flutter means fast on and off.

PHONELAMPMODE_OFF

The lamp is off.

PHONELAMPMODE_STEADY

The lamp is continuously lit.

PHONELAMPMODE_WINK

The lamp is winking.

PHONELAMPMODE_UNKNOWN

The lamp mode is currently unknown.

PHONELAMPMODE_DUMMY

This value is used to describe a button/lamp position that has no corresponding lamp.

Phone sets that have multiple lamps per button should be modeled using multiple button/lamps pairs. Each extra button/lamp pair should use a DUMMY button.


 phoneGetRing

[New - Windows 95]

LONG phoneGetRing(HPHONE hPhone, LPDWORD lpdwRingMode,
    LPDWORD lpdwVolume)

Enables an application to query the specified open phone device as to its current ring mode.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

PHONEERR_INVALPHONEHANDLE	PHONEERR_NOMEM
PHONEERR_INVALPHONESTATE	PHONEERR_RESOURCEUNAVAIL
PHONEERR_INVALPOINTER	PHONEERR_OPERATIONFAILED
PHONEERR_OPERATIONUNAVAIL	PHONEERR_UNINITIALIZED
hPhone

Specifies a handle to the open phone device.

lpdwRingMode

Specifies the ringing pattern with which the phone is ringing. Zero indicates that the phone is not ringing.

lpdwVolume

Specifies the volume level with which the phone is ringing. This is a number in the range 0x00000000 (silence) to 0x0000FFFF (maximum volume). The actual granularity and quantization of volume settings in this range are service-provider specific.

The service provider defines the actual audible ringing patterns corresponding to each of phone's ring modes.


 phoneGetStatus

[New - Windows 95]

LONG phoneGetStatus(HPHONE hPhone, LPPHONESTATUS lpPhoneStatus)

Enables an application to query the specified open phone device for its overall status.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

PHONEERR_INVALPHONEHANDLE	PHONEERR_NOMEM
PHONEERR_INVALPOINTER	PHONEERR_RESOURCEUNAVAIL
PHONEERR_OPERATIONFAILED	PHONEERR_STRUCTURETOOSMALL
PHONEERR_OPERATIONUNAVAIL	PHONEERR_UNINITIALIZED
hPhone

Specifies a handle to the open phone device to be queried.

lpPhoneStatus

Specifies a pointer to a variably sized data structure of type PHONESTATUS, which is loaded with the returned information about the phone's status.

An application can use this function to determine the current state of an open phone device. The status information describes information about the phone device's hookswitch devices, ringer, volume, display, and lamps of the open phone.


 phoneGetStatusMessages

[New - Windows 95]

LONG phoneGetStatusMessages(HPHONE hPhone, LPDWORD lpdwPhoneStates,
    LPDWORD lpdwButtonModes, LPDWORD lpdwButtonStates)

Returns which phone-state changes on the specified phone device will generate a callback to the application.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

PHONEERR_INVALPHONEHANDLE	PHONEERR_NOMEM
PHONEERR_INVALPOINTER	PHONEERR_RESOURCEUNAVAIL
PHONEERR_OPERATIONFAILED	PHONEERR_UNINITIALIZED
hPhone

Specifies a handle to the open phone device to be monitored.

lpdwPhoneStates

Specifies a pointer to a PHONESTATE_ constant. These flags specify the set of phone status changes and events for which the application wishes to receive notification messages. The lpdwPhoneStates parameter can return a value with zero, one, or multiple bits set. Monitoring can be individually enabled and disabled for:

PHONESTATE_OTHER

Phone-status items other than those listed below have changed. The application should check the current phone status to determine which items have changed.

PHONESTATE_CONNECTED

The connection between the phone device and TAPI was just made. This happens when TAPI is first invoked or when the wire connecting the phone to the computer is plugged in while TAPI is active.

PHONESTATE_DISCONNECTED

The connection between the phone device and TAPI was just broken. This happens when the wire connecting the phone set to the computer is unplugged while TAPI is active.

PHONESTATE_OWNER

The number of owners for the phone device has changed.

PHONESTATE_MONITORS

The number of monitors for the phone device has changed.

PHONESTATE_DISPLAY

The display of the phone has changed.

PHONESTATE_LAMP

A lamp of the phone has changed.

PHONESTATE_RINGMODE

The ring mode of the phone has changed.

PHONESTATE_RINGVOLUME

The ring volume of the phone has changed.

PHONESTATE_HANDSETHOOKSWITCH

The handset hookswitch state has changed.

PHONESTATE_HANDSETVOLUME

The handset's speaker volume setting has changed.

PHONESTATE_HANDSETGAIN

The handset's microphone gain setting has changed.

PHONESTATE_SPEAKERHOOKSWITCH

The speakerphone's hookswitch state has changed.

PHONESTATE_SPEAKERVOLUME

The speakerphone's speaker volume setting has changed.

PHONESTATE_SPEAKERGAIN

The speakerphone's microphone gain setting state has changed.

PHONESTATE_HEADSETHOOKSWITCH

The headset's hookswitch state has changed.

PHONESTATE_HEADSETVOLUME

The headset's speaker volume setting has changed.

PHONESTATE_HEADSETGAIN

The headset's microphone gain setting has changed.

PHONESTATE_SUSPEND

The application's use of the phone is temporarily suspended.

PHONESTATE_RESUME

The application's use of the phone device is resumed after having been suspended for some time.

PHONESTATE_DEVSPECIFIC

The phone's device-specific information has changed.

PHONESTATE_REINIT

Items have changed in the configuration of phone devices. To become aware of these changes (as with the appearance of new phone devices) the application should reinitialize its use of TAPI. The hDevice parameter of the PHONE_STATE message is left NULL for this state change, as it applies to any of the phones in the system.

PHONESTATE_CAPSCHANGE

Indicates that, due to configuration changes made by the user or other circumstances, one or more of the fields in the PHONECAPS structure have changed. The application should use phoneGetDevCaps to read the updated structure. If a service provider sends a PHONE_STATE message containing this value to TAPI, TAPI will pass it along to applications which have negotiated this or a subsequent API version; applications negotiating a previous API version will receive PHONE_STATE messages specifying PHONESTATE_REINIT, requiring them to shutdown and reinitialize their connection to TAPI in order to obtain the updated information.

PHONESTATE_REMOVED

Indicates that the device is being removed from the system by the service provider (most likely through user action, via a control panel or similar utility). A PHONE_STATE message with this value will normally be immediately followed by a PHONE_CLOSE message on the device. Subsequent attempts to access the device prior to TAPI being reinitialized will result in PHONEERR_NODEVICE being returned to the application. If a service provider sends a PHONE_STATE message containing this value to TAPI, TAPI will pass it along to applications which have negotiated this or a subsequent API version; applications negotiating a previous API version will not receive any notification.

lpdwButtonModes

Specifies a pointer to a . These flags specify the set of phone-button modes for which the application wishes to receive notification messages. The lpdwButtonModes parameter can return a value with zero, one, or multiple bits set. This parameter uses the following PHONEBUTTONMODE_ constants:

PHONEBUTTONMODE_CALL

The button is assigned to a call appearance.

PHONEBUTTONMODE_FEATURE

The button is assigned to requesting features from the switch, such as hold, conference, and transfer.

PHONEBUTTONMODE_KEYPAD

The button is one of the twelve keypad buttons, '0' through '9', '*', and '#'.

PHONEBUTTONMODE_LOCAL

The button is a local function button, such as mute or volume control.

PHONEBUTTONMODE_DISPLAY

The button is a "soft" button associated with the phone's display. A phone set can have zero or more display buttons.

lpdwButtonStates

Specifies a pointer to a DWORD-sized location that contains flags specifying the set of phone button state changes for which the application wishes to receive notification messages. The lpdwButtonStates field can return a value with zero, one or multiple bits set. This parameter uses the following PHONEBUTTONSTATE_ constants:

PHONEBUTTONSTATE_UP

The button is in the "up" state.

PHONEBUTTONSTATE_DOWN

The button is in the "down" state (pressed down).

PHONEBUTTONSTATE_UNKNOWN

Indicates that the up or down state of the button is not known at this time, but may become known at a future time.

PHONEBUTTONSTATE_UNAVAIL

Indicates that the up or down state of the button is not known to the service provider, and will not become known at a future time.

An application can use this function to query the generation of the corresponding messages. Message generation can be controlled by phoneSetStatusMessages. All phone status messages are disabled by default.


 phoneGetVolume

[New - Windows 95]

LONG phoneGetVolume(HPHONE hPhone, DWORD dwHookSwitchDev,
    LPDWORD lpdwVolume)

Returns the volume setting of the specified phone's hookswitch device.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

PHONEERR_INVALPHONEHANDLE	PHONEERR_NOMEM
PHONEERR_INVALPHONESTATE	PHONEERR_RESOURCEUNAVAIL
PHONEERR_INVALPOINTER	PHONEERR_OPERATIONFAILED
PHONEERR_INVALHOOKSWITCHDEV	PHONEERR_UNINITIALIZED
PHONEERR_OPERATIONUNAVAIL
hPhone

Specifies a handle to the open phone device.

dwHookSwitchDev

Identifies a single hookswitch device whose volume level is queried. This parameter uses the following PHONEHOOKSWITCHDEV_ constants:

PHONEHOOKSWITCHDEV_HANDSET

This is the phone's handset.

PHONEHOOKSWITCHDEV_SPEAKER

This is the phone's speakerphone or adjunct.

PHONEHOOKSWITCHDEV_HEADSET

This is the phone's headset.

lpdwVolume

Specifies a pointer to a DWORD-sized location containing the current volume setting of the hookswitch device. dwVolume specifies the volume level of the hookswitch device. This is a number in the range 0x00000000 (silence) to 0x0000FFFF (maximum volume). The actual granularity and quantization of volume settings in this range are service-provider specific.


 phoneInitialize

[New - Windows 95]

LONG phoneInitialize(LPHPHONEAPP lphPhoneApp, HINSTANCE hInstance,
    PHONECALLBACK lpfnCallback, LPCSTR lpszAppName,

    LPDWORD lpdwNumDevs)

Initializes the application's use of TAPI for subsequent use of the phone functions in the Telephony API. It registers the application's specified notification mechanism and returns the number of phone devices that are available to the application.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

PHONEERR_INVALAPPNAME	PHONEERR_INIFILECORRUPT
PHONEERR_INVALPOINTER	PHONEERR_NOMEM
PHONEERR_OPERATIONFAILED	PHONEERR_REINIT
PHONEERR_RESOURCEUNAVAIL	PHONEERR_NODEVICE
PHONEERR_NODRIVER
lphPhoneApp

Specifies a pointer to a location that is filled with the application's usage handle for TAPI.

hInstance

Specifies the instance handle of the client application or DLL.

lpfnCallback

Specifies the address of a callback function to be invoked related to status and events on the phone device.

lpszAppName

Specifies a pointer to a NULL-terminated ASCII string that contains displayable characters. If this parameter is non-NULL, it contains an application-supplied name of the application. This name is provided in the PHONESTATUS structure to indicate, in a user-friendly way, which application is the current owner of the phone device. This information can be useful for logging and status reporting purposes. If lpszAppName is NULL, the application's file name will be used instead.

lpdwNumDevs

Specifies a pointer to DWORD-sized memory location. This location is loaded with the number of phone devices available to the application.

The application can refer to individual phone devices by using phone device IDs that range from zero to dwNumDevs minus one. An application should not assume that these phone devices are capable of anything beyond what is specified by the Assisted Telephony subset without first querying their device capabilities with the function phoneGetDevCaps.

Applications should not invoke phoneInitialize without subsequently opening a phone (at least for monitoring). If the application is not monitoring and not using any devices, it should call phoneShutdown so that memory resources allocated by TAPI can be released if unneeded, and TAPI itself can be unloaded from memory while not needed.

Another reason for performing a phoneShutdown is that if a user changes the device configuration (adds or removes a line or phone), there is no way for TAPI to notify an application that has a line or phone handle open at the time. Once a reconfiguration has taken place, causing a PHONESTATE_REINIT message to be sent, no applications can open a device until all applications have performed a phoneShutdown.

If any service provider fails to initialize properly, this function fails and returns the error indicated by the service provider.

If the LINEERR_INVALPARAM error value is returned, the specified hInstance parameter is invalid.


 phoneCallbackFunc

[New - Windows 95]

VOID FAR PASCAL phoneCallbackFunc(HANDLE hDevice, DWORD dwMsg,
    DWORD dwCallbackInstance, DWORD dwParam1, DWORD dwParam2,
    DWORD dwParam3)

phoneCallbackFunc is a placeholder for the application-supplied function name.

hDevice

Specified a handle to a phone device associated with the callback.

dwMsg

Specifies a line or call device message.

dwCallbackInstance

Specifies callback instance data passed back to the application in the callback. This DWORD is not interpreted by TAPI.

dwParam1

Specifies a parameter for the message.

dwParam2

Specifies a parameter for the message.

dwParam3

Specifies a parameter for the message.

For more information about the parameters passed to this callback function, see "Messages" later in this chapter.

All callbacks occur in the application's context. The callback function must reside in a dynamic link library (DLL) or application module and be exported in the module-definition file.


 phoneNegotiateAPIVersion

[New - Windows 95]

LONG phoneNegotiateAPIVersion(HPHONEAPP hPhoneApp, DWORD dwDeviceID,
    DWORD dwAPILowVersion, DWORD dwAPIHighVersion,
    LPDWORD lpdwAPIVersion, LPPHONEEXTENSIONID lpExtensionID)

Allows an application to negotiate an API version to use for the specified phone device.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

PHONEERR_INVALAPPHANDLE	PHONEERR_OPERATIONFAILED
PHONEERR_BADDEVICEID	PHONEERR_OPERATIONUNAVAIL
PHONEERR_NODRIVER	PHONEERR_NOMEM
PHONEERR_INVALPOINTER	PHONEERR_RESOURCEUNAVAIL
PHONEERR_INCOMPATIBLEAPIVERSION	PHONEERR_UNINITIALIZED
PHONEERR_NODEVICE
hPhoneApp

Specifies the handle to the application's registration with TAPI.

dwDeviceID

Specifies the phone device to be queried.

dwAPILowVersion

Specifies the least recent API version the application is compliant with. The high-order word is the major version number, the low-order word is the minor version number.

dwAPIHighVersion

Specifies the most recent API version the application is compliant with. The high-order word is the major version number, the low-order word is the minor version number.

lpdwAPIVersion

Specifies a pointer to a DWORD-sized location that contains the API version number that was negotiated. If negotiation is successful, this number will be in the range dwAPILowVersion and dwAPIHighVersion.

lpExtensionID

Specifies a pointer to a structure of type PHONEEXTENSIONID. If the service provider for the specified dwDeviceID supports provider-specific extensions, this structure is filled with the extension ID of these extensions when negotiation is successful. This structure contains all zeros if the line provides no extensions. An application can ignore the returned parameter if it does not use extensions.

phoneNegotiateAPIVersion is used to negotiate the API version number to use with the specified phone device. It returns the extension ID supported by the phone device; zeros if no extensions are provided.

If the application wants to use the extensions defined by the returned Extension ID, it must call phoneNegotiateExtVersion to negotiate the extension version to use.

Use phoneInitialize to determine the number of phone devices present in the system. The device ID specified by dwDeviceID varies from zero to one less than the number of phone devices present.

The API version number negotiated is that under which TAPI can operate. If version ranges do not overlap, the application, API, or service-provider versions are incompatible and an error is returned.


 phoneNegotiateExtVersion

[New - Windows 95]

LONG phoneNegotiateExtVersion(HPHONEAPP hPhoneApp, DWORD dwDeviceID,
    DWORD dwAPIVersion, DWORD dwExtLowVersion, DWORD dwExtHighVersion,
    LPDWORD lpdwExtVersion)

Allows an application to negotiate an extension version to use with the specified phone device. This operation need not be called if the application does not support extensions.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

PHONEERR_INVALAPPHANDLE	PHONEERR_OPERATIONFAILED
PHONEERR_BADDEVICEID	PHONEERR_OPERATIONUNAVAIL
PHONEERR_NODRIVER	PHONEERR_NOMEM
PHONEERR_INCOMPATIBLEAPIVERSION	PHONEERR_RESOURCEUNAVAIL
PHONEERR_INCOMPATIBLEEXTVERSION	PHONEERR_UNINITIALIZED
PHONEERR_INVALPOINTER	PHONEERR_NODEVICE
hPhoneApp

Specifies the handle to the application's registration with TAPI.

dwDeviceID

Specifies the phone device to be queried.

dwAPIVersion

Specifies the API version number that was negotiated for the specified phone device using phoneNegotiateAPIVersion.

dwExtLowVersion

Specifies the least recent extension version of the Extension ID returned by phoneNegotiateAPIVersion that the application is compliant with. The high-order word is the major version number; the low-order word is the minor version number.

dwExtHighVersion

Specifies the most recent extension version of the Extension ID returned by phoneNegotiateAPIVersion that the application is compliant with. The high-order word is the major version number; the low-order word is the minor version number.

lpdwExtVersion

Specifies a pointer to a DWORD-sized location that contains the extension version number that was negotiated. If negotiation is successful, this number will be in the range dwExtLowVersion and dwExtHighVersion.

The function phoneNegotiateAPIVersion is used to negotiate the API version number to use. It returns the extension ID supported by the phone device, or zeros if no extensions are provided.

If the application wants to use the extensions defined by the returned Extension ID, it must call phoneNegotiateExtVersion to negotiate the extension version to use.

Use phoneInitialize to determine the number of phone devices present in the system. The device ID specified by dwDeviceID varies from zero to one less than the number of phone devices present.

The extension version number negotiated is that under which the application and service provider must both operate. If version ranges do not overlap, the application and service-provider versions are incompatible and an error is returned.


 phoneOpen

[New - Windows 95]

LONG phoneOpen(HPHONEAPP hPhoneApp, DWORD dwDeviceID, LPHPHONE lphPhone,
    DWORD dwAPIVersion, DWORD dwExtVersion, DWORD dwCallbackInstance,
    DWORD dwPrivilege)

Opens the specified phone device. A phone device can be opened using either owner privilege or monitor privilege. An application that opens the phone with owner privilege can control the phone's lamps, display, ringer, and hookswitch(es). An application that opens the phone device with monitor privilege is notified only about events that occur at the phone, such as hookswitch changes or button presses, in messages sent to its window or callback. Ownership of a phone device is exclusive. In other words, only one application can have a phone device opened with owner privilege at a time. The phone device can, however, be opened multiple times with monitor privilege.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

PHONEERR_ALLOCATED	PHONEERR_NODRIVER
PHONEERR_BADDEVICEID	PHONEERR_NOMEM
PHONEERR_INCOMPATIBLEAPIVERSION	PHONEERR_OPERATIONFAILED
PHONEERR_INCOMPATIBLEEXTVERSION	PHONEERR_OPERATIONUNAVAIL
PHONEERR_INVALAPPHANDLE	PHONEERR_RESOURCEUNAVAIL
PHONEERR_INVALPOINTER	PHONEERR_UNINITIALIZED
PHONEERR_INVALPRIVILEGE	PHONEERR_REINIT
PHONEERR_INUSE	PHONEERR_NODEVICE
PHONEERR_INIFILECORRUPT
hPhoneApp

Specifies a handle to the application's registration with TAPI.

dwDeviceID

Identifies the phone device to be opened.

lphPhone

Specifies a pointer to an HPHONE handle, which identifies the open phone device. Use this handle to identify the device when invoking other phone control functions.

dwAPIVersion

Specifies the API version number under which the application and Telephony API have agreed to operate. This number is obtained from phoneNegotiationAPIVersion.

dwExtVersion

Specifies the extension version number under which the application and the service provider agree to operate. This number is zero if the application does not use any extensions. This number is obtained from phoneNegotiateExtVersion.

dwCallbackInstance

Specifies user instance data passed back to the application's callback. This parameter is not interpreted by the Telephony API.

dwPrivilege

Specifies the privilege requested. The dwPrivilege parameter can have only one bit set. This parameter uses the following PHONEPRIVILEGE_ constants:

PHONEPRIVILEGE_MONITOR

An application that opens a phone device with this privilege is informed about events and state changes occurring on the phone. The application cannot invoke any operations on the phone device that would change its state.

PHONEPRIVILEGE_OWNER

An application that opens a phone device in this mode is allowed to change the state of the lamps, ringer, display, and hookswitch devices of the phone. Having owner privilege to a phone device automatically includes monitor privilege as well.

When opening a phone device with monitor privileges, the application is sent messages when events occur that change the status of the phone. Messages sent to the application include PHONE_BUTTON and PHONE_STATE. The latter provides an indication of the phone's status item that has changed.

When opening a phone with owner privilege, the phone device can be manipulated in ways that affect the state of the phone device. An application should only open a phone using owner privilege if it actively wants to manipulate the phone device, and it should close the phone device when done to allow other applications to control the phone.

When an application opens a phone device, it must specify the negotiated API version and, if it wants to use the phone's extensions, the phone's device-specific extension version. This version numbers should have been obtained with the function phoneNegotiateAPIVersion and phoneNegotiateExtVersion. Version numbering allows the mix and match of different application versions with different API versions and service-provider versions.


 phoneSetButtonInfo

[New - Windows 95]

LONG phoneSetButtonInfo(HPHONE hPhone, DWORD dwButtonLampID,
    LPPHONEBUTTONINFO const lpButtonInfo)

Sets information about the specified button on the specified phone.

•	Returns a positive request ID if the function will be completed asynchronously or a negative error number if an error has occurred. The dwParam2 parameter of the corresponding PHONE_REPLY callback message is zero if the function is successful or it is a negative error number if an error has occurred. Possible return values are:

PHONEERR_INVALBUTTONLAMPID	PHONEERR_OPERATIONFAILED
PHONEERR_INVALPHONEHANDLE	PHONEERR_STRUCTURETOOSMALL
PHONEERR_INVALPOINTER	PHONEERR_UNINITIALIZED
PHONEERR_NOTOWNER	PHONEERR_NOMEM
PHONEERR_OPERATIONUNAVAIL	PHONEERR_RESOURCEUNAVAIL
hPhone

Specifies a handle to the open phone device. The application must be the owner of the phone device.

dwButtonLampID

Specifies a button on the phone device.

lpButtonInfo

Specifies a pointer to a variably sized structure of type PHONEBUTTONINFO. This data structure describes the mode, the function, and provides additional descriptive text about the button.


 phoneSetData

[New - Windows 95]

LONG phoneSetData(HPHONE hPhone, DWORD dwDataID, LPVOID const lpData,
    DWORD dwSize)

Downloads the information in the specified buffer to the opened phone device at the selected data ID.

•	Returns a positive request ID if the function will be completed asynchronously or a negative error number if an error has occurred. The dwParam2 parameter of the corresponding PHONE_REPLY callback message is zero if the function is successful or it is a negative error number if an error has occurred. Possible return values are:

PHONEERR_INVALPHONEHANDLE	PHONEERR_OPERATIONUNAVAIL
PHONEERR_NOTOWNER	PHONEERR_NOMEM
PHONEERR_INVALDATAID	PHONEERR_RESOURCEUNAVAIL
PHONEERR_INVALPHONESTATE	PHONEERR_OPERATIONFAILED
PHONEERR_INVALPOINTER	PHONEERR_UNINITIALIZED
hPhone

Specifies a handle to the open phone device. The application must be the owner of the phone.

dwDataID

Specifies where in the phone device the buffer is to be downloaded.

lpData

Specifies a pointer to the memory location where the data is to be downloaded from.

dwSize

Specifies the size of the buffer in bytes.

The function downloads a maximum of dwSize bytes from lpData to the phone device. The format of the data, its meaning to the phone device, and the meaning of the data ID are service-provider specific. The data in the buffer or the selection of a data ID may act as commands to the phone device.


 phoneSetDisplay

[New - Windows 95]

LONG phoneSetDisplay(HPHONE hPhone, DWORD dwRow, DWORD dwColumn,
    LPCSTR lpsDisplay, DWORD dwSize)

Causes the specified string to be displayed on the specified open phone device.

•	Returns a positive request ID if the function will be completed asynchronously or a negative error number if an error has occurred. The dwParam2 parameter of the corresponding PHONE_REPLY callback message is zero if the function is successful or it is a negative error number if an error has occurred. Possible return values are:

PHONEERR_INVALPHONEHANDLE	PHONEERR_OPERATIONUNAVAIL
PHONEERR_NOTOWNER	PHONEERR_OPERATIONFAILED
PHONEERR_INVALPHONESTATE	PHONEERR_UNINITIALIZED
PHONEERR_INVALPOINTER	PHONEERR_NOMEM
PHONEERR_INVALPARAM	PHONEERR_RESOURCEUNAVAIL
hPhone

Specifies a handle to the open phone device. The application must be the owner of the phone.

dwRow

Specifies the row on the display where the new text is to be displayed.

dwColumn

Specifies the column position on the display where the new text is to be displayed.

lpsDisplay

Specifies a pointer to the memory location where the display content is stored. The display information must have the format specified in the dwStringFormat field of the phone's device capabilities.

dwSize

Specifies the size in bytes of the information pointed to by lpsDisplay.

The specified display information is written to the phone's display, starting at the specified positions. This operation overwrites previously displayed information. If the amount of information exceeds the size of the display, the information will be truncated. The amount of information that can be displayed is at most (dwNumRows * dwNumColumns) elements in size. dwNumRows and dwNumColumns are available in the PHONECAPS structure, which is returned by phoneGetDevCaps; they are zero-based.


 phoneSetGain

[New - Windows 95]

LONG phoneSetGain(HPHONE hPhone, DWORD dwHookSwitchDev, DWORD dwGain)

Sets the gain of the microphone of the specified hookswitch device to the specified gain level.

•	Returns a positive request ID if the function will be completed asynchronously or a negative error number if an error has occurred. The dwParam2 parameter of the corresponding PHONE_REPLY callback message is zero if the function is successful or it is a negative error number if an error has occurred. Possible return values are:

PHONEERR_INVALPHONEHANDLE	PHONEERR_NOMEM
PHONEERR_NOTOWNER	PHONEERR_RESOURCEUNAVAIL
PHONEERR_INVALPHONESTATE	PHONEERR_OPERATIONFAILED
PHONEERR_INVALHOOKSWITCHDEV	PHONEERR_UNINITIALIZED
PHONEERR_OPERATIONUNAVAIL
hPhone

Specifies a handle to the open phone device. The application must be the owner of the phone.

dwHookSwitchDev

Identifies the hookswitch device whose microphone's gain is to be set. The dwHookswitchDev parameter can only have a single bit set. This parameter uses the following PHONEHOOKSWITCHDEV_ constants:

PHONEHOOKSWITCHDEV_HANDSET

This is the phone's handset.

PHONEHOOKSWITCHDEV_SPEAKER

This is the phone's speakerphone or adjunct.

PHONEHOOKSWITCHDEV_HEADSET

This is the phone's headset.

dwGain

Specifies a pointer to a DWORD-sized location containing the current gain setting of the device. dwGain specifies the gain level of the hookswitch device. This is a number in the range 0x00000000 (silence) to 0x0000FFFF (maximum volume). The actual granularity and quantization of gain settings in this range are service-provider specific. A value for dwGain that is out of range is set to the nearest value in the range.


 phoneSetHookSwitch

[New - Windows 95]

LONG phoneSetHookSwitch(HPHONE hPhone, DWORD dwHookSwitchDevs,
    DWORD dwHookSwitchMode)

Sets the hook state of the specified open phone's hookswitch devices to the specified mode. Only the hookswitch state of the hookswitch devices listed is affected.

•	Returns a positive request ID if the function will be completed asynchronously or a negative error number if an error has occurred. The dwParam2 parameter of the corresponding PHONE_REPLY callback message is zero if the function is successful or it is a negative error number if an error has occurred. Possible return values are:

PHONEERR_INVALPHONEHANDLE	PHONEERR_OPERATIONUNAVAIL
PHONEERR_NOTOWNER	PHONEERR_NOMEM
PHONEERR_INVALHOOKSWITCHDEV	PHONEERR_RESOURCEUNAVAIL
PHONEERR_INVALHOOKSWITCHMODE	PHONEERR_OPERATIONFAILED
PHONEERR_INVALPHONESTATE	PHONEERR_UNINITIALIZED
hPhone

Specifies a handle to the open phone device. The application must be the owner of the phone.

dwHookSwitchDevs

Specifies the device(s) whose hookswitch mode is to be set. This parameter uses the following PHONEHOOKSWITCHDEV_ constants:

PHONEHOOKSWITCHDEV_HANDSET

This is the phone's handset.

PHONEHOOKSWITCHDEV_SPEAKER

This is the phone's speakerphone or adjunct.

PHONEHOOKSWITCHDEV_HEADSET

This is the phone's headset.

dwHookSwitchMode

Specifies the hookswitch mode to set. The dwHookSwitchMode parameter can have only a single bit set. This parameter uses the following PHONEHOOKSWITCHMODE_ constants:

PHONEHOOKSWITCHMODE_ONHOOK

The device's microphone and speaker are both onhook.

PHONEHOOKSWITCHMODE_MIC

The device's microphone is active, the speaker is mute.

PHONEHOOKSWITCHMODE_SPEAKER

The device's speaker is active, the microphone is mute.

PHONEHOOKSWITCHMODE_MICSPEAKER

The device's microphone and speaker are both active.

The hookswitch mode is the same for all devices specified. If different settings are desired, this function can be invoked multiple times with a different set of parameters. A PHONE_STATE message is sent to the application after the hookswitch state has changed.


 phoneSetLamp

[New - Windows 95]

LONG phoneSetLamp(HPHONE hPhone, DWORD dwButtonLampID, DWORD dwLampMode)

Causes the specified lamp to be lit on the specified open phone device in the specified lamp mode.

•	Returns a positive request ID if the function will be completed asynchronously or a negative error number if an error has occurred. The dwParam2 parameter of the corresponding PHONE_REPLY callback message is zero if the function is successful or it is a negative error number if an error has occurred. Possible return values are:

PHONEERR_INVALPHONEHANDLE	PHONEERR_OPERATIONUNAVAIL
PHONEERR_NOTOWNER	PHONEERR_NOMEM
PHONEERR_INVALBUTTONLAMPID	PHONEERR_RESOURCEUNAVAIL
PHONEERR_INVALPHONESTATE	PHONEERR_OPERATIONFAILED
PHONEERR_INVALLAMPMODE	PHONEERR_UNINITIALIZED
hPhone

Specifies a handle to the open phone device. The application must be the owner of the phone.

dwButtonLampID

Identifies the button whose lamp is to be lit.

dwLampMode

Specifies how the lamp is to be lit. The dwLampMode parameter can have only a single bit set. This parameter uses the following PHONELAMPMODE_ constants:

PHONELAMPMODE_BROKENFLUTTER

Broken flutter is the superposition of flash and flutter.

PHONELAMPMODE_FLASH

Flash means slow on and off.

PHONELAMPMODE_FLUTTER

Flutter means fast on and off.

PHONELAMPMODE_OFF

The lamp is off.

PHONELAMPMODE_STEADY

The lamp is continuously lit.

PHONELAMPMODE_WINK

The lamp is winking.

PHONELAMPMODE_DUMMY

This value is used to describe a button/lamp position that has no corresponding lamp.


 phoneSetRing

[New - Windows 95]

LONG phoneSetRing(HPHONE hPhone, DWORD dwRingMode, DWORD dwVolume)

Rings the specified open phone device using the specified ring mode and volume.

•	Returns a positive request ID if the function will be completed asynchronously or a negative error number if an error has occurred. The dwParam2 parameter of the corresponding PHONE_REPLY callback message is zero if the function is successful or it is a negative error number if an error has occurred. Possible return values are:

PHONEERR_INVALPHONEHANDLE	PHONEERR_NOMEM
PHONEERR_NOTOWNER	PHONEERR_RESOURCEUNAVAIL
PHONEERR_INVALPHONESTATE	PHONEERR_OPERATIONFAILED
PHONEERR_INVALRINGMODE	PHONEERR_UNINITIALIZED
PHONEERR_OPERATIONUNAVAIL
hPhone

Specifies a handle to the open phone device. The application must be the owner of the phone device.

dwRingMode

Specifies the ringing pattern with which to ring the phone. This parameter must be within the range of 0 to the value of the dwNumRingModes field in the PHONECAPS structure. If dwNumRingModes is 0, the ring mode of the phone cannot be controlled; if dwNumRingModes is 1, a value of 0 for dwRingMode indicates that the phone should not be rung (silence), and other values from 1 to dwNumRingModes are valid ring modes for the phone device.

dwVolume

Specifies the volume level with which the phone is ringing. This is a number in the range 0x00000000 (silence) to 0x0000FFFF (maximum volume). The actual granularity and quantization of volume settings in this range are service-provider specific. A value for dwVolume that is out of range is set to the nearest value in the range.

The service provider defines the actual audible ringing patterns corresponding to each of the phone's ring modes.


 phoneSetStatusMessages

[New - Windows 95]

LONG phoneSetStatusMessages(HPHONE hPhone, DWORD dwPhoneStates,
    DWORD dwButtonModes, DWORD dwButtonStates)

Enables an application to monitor the specified phone device for selected status events.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

PHONEERR_INVALPHONEHANDLE	PHONEERR_NOMEM
PHONEERR_INVALPHONESTATE	PHONEERR_RESOURCEUNAVAIL
PHONEERR_INVALBUTTONMODE	PHONEERR_OPERATIONFAILED
PHONEERR_INVALBUTTONSTATE	PHONEERR_UNINITIALIZED
PHONEERR_OPERATIONUNAVAIL
hPhone

Specifies a handle to the open phone device to be monitored.

dwPhoneStates

These flags specify the set of phone status changes and events for which the application wishes to receive notification messages. This parameter can have zero, one, or more bits set. This parameter uses the following PHONESTATE_ constants:

PHONESTATE_OTHER

Phone-status items other than those listed below have changed. The application should check the current phone status to determine which items have changed.

PHONESTATE_CONNECTED

The connection between the phone device and TAPI was just made. This happens when TAPI is first invoked or when the wire connecting the phone to the PC is plugged in while TAPI is active.

PHONESTATE_DISCONNECTED

The connection between the phone device and TAPI was just broken. This happens when the wire connecting the phone set to the PC is unplugged while TAPI is active.

PHONESTATE_OWNER

The number of owners for the phone device has changed.

PHONESTATE_MONITORS

The number of monitors for the phone device has changed.

PHONESTATE_DISPLAY

The display of the phone has changed.

PHONESTATE_LAMP

A lamp of the phone has changed.

PHONESTATE_RINGMODE

The ring mode of the phone has changed.

PHONESTATE_RINGVOLUME

The ring volume of the phone has changed.

PHONESTATE_HANDSETHOOKSWITCH

The handset hookswitch state has changed.

PHONESTATE_HANDSETVOLUME

The handset's speaker volume setting has changed.

PHONESTATE_HANDSETGAIN

The handset's microphone gain setting has changed.

PHONESTATE_SPEAKERHOOKSWITCH

The speakerphone's hookswitch state has changed.

PHONESTATE_SPEAKERVOLUME

The speakerphone's speaker volume setting has changed.

PHONESTATE_SPEAKERGAIN

The speakerphone's microphone gain setting state has changed.

PHONESTATE_HEADSETHOOKSWITCH

The headset's hookswitch state has changed.

PHONESTATE_HEADSETVOLUME

The headset's speaker volume setting has changed.

PHONESTATE_HEADSETGAIN

The headset's microphone gain setting has changed.

PHONESTATE_SUSPEND

The application's use of the phone is temporarily suspended.

PHONESTATE_RESUME

The application's use of the phone device is resumed after having been suspended for some time.

PHONESTATE_DEVSPECIFIC

The phone's device-specific information has changed.

PHONESTATE_REINIT

Items have changed in the configuration of phone devices. To become aware of these changes (as with the appearance of new phone devices) the application should reinitialize its use of TAPI. New phoneInitialize and phoneOpen requests are denied until applications have shut down their usage of TAPI. The hDevice parameter of the PHONE_STATE message is left NULL for this state change, since it applies to any of the lines in the system. Because of the critical nature of PHONESTATE_REINIT, such messages cannot be masked, so the setting of this bit is ignored and the messages are always delivered to the application.

PHONESTATE_CAPSCHANGE

Indicates that, due to configuration changes made by the user or other circumstances, one or more of the fields in the PHONECAPS structure have changed. The application should use phoneGetDevCaps to read the updated structure. If a service provider sends a PHONE_STATE message containing this value to TAPI, TAPI will pass it along to applications which have negotiated this or a subsequent API version; applications negotiating a previous API version will receive PHONE_STATE messages specifying PHONESTATE_REINIT, requiring them to shutdown and reinitialize their connection to TAPI in order to obtain the updated information.

PHONESTATE_REMOVED

Indicates that the device is being removed from the system by the service provider (most likely through user action, via a control panel or similar utility). A PHONE_STATE message with this value will normally be immediately followed by a PHONE_CLOSE message on the device. Subsequent attempts to access the device prior to TAPI being reinitialized will result in PHONEERR_NODEVICE being returned to the application. If a service provider sends a PHONE_STATE message containing this value to TAPI, TAPI will pass it along to applications which have negotiated this or a subsequent API version; applications negotiating a previous API version will not receive any notification.

dwButtonModes

These flags specify the set of phone-button modes for which the application wishes to receive notification messages. This parameter can have zero, one, or more bits set. This parameter uses the following PHONEBUTTONMODE_ constants:

PHONEBUTTONMODE_CALL

The button is assigned to a call appearance.

PHONEBUTTONMODE_FEATURE

The button is assigned to requesting features from the switch, such as hold, conference, and transfer.

PHONEBUTTONMODE_KEYPAD

The button is one of the twelve keypad buttons, '0' through '9', '*', and '#'.

PHONEBUTTONMODE_LOCAL

The button is a local function button, such as mute or volume control.

PHONEBUTTONMODE_DISPLAY

The button is a "soft" button associated with the phone's display. A phone set can have zero or more display buttons.

dwButtonStates

These flags specify the set of phone-button state changes for which the application wishes to receive notification messages. If the dwButtonModes parameter is 0, dwButtonStates is ignored. If dwButtonModes has one or more bits set, this parameter must also have at least one bit set. This parameter uses the following PHONEBUTTONSTATE_ constants:

PHONEBUTTONSTATE_UP

The button is in the "up" state.

PHONEBUTTONSTATE_DOWN

The button is in the "down" state (pressed down).

PHONEBUTTONSTATE_UNKNOWN

Indicates that the up or down state of the button is not known at this time, but may become known at a future time.

PHONEBUTTONSTATE_UNAVAIL

Indicates that the up or down state of the button is not known to the service provider, and will not become known at a future time.

An application can use this function to enable or disable the generation of the corresponding messages. All phone status messages are disabled by default.


 phoneSetVolume

[New - Windows 95]

LONG phoneSetVolume(HPHONE hPhone, DWORD dwHookSwitchDev,
    DWORD dwVolume)

Sets the volume of the speaker component of the specified hookswitch device to the specified level.

•	Returns a positive request ID if the function will be completed asynchronously or a negative error number if an error has occurred. The dwParam2 parameter of the corresponding PHONE_REPLY callback message is zero if the function is successful or it is a negative error number if an error has occurred. Possible return values are:

PHONEERR_INVALPHONEHANDLE	PHONEERR_NOMEM
PHONEERR_NOTOWNER	PHONEERR_RESOURCEUNAVAIL
PHONEERR_INVALPHONESTATE	PHONEERR_OPERATIONFAILED
PHONEERR_INVALHOOKSWITCHDEV	PHONEERR_UNINITIALIZED
PHONEERR_OPERATIONUNAVAIL
hPhone

Specifies a handle to the open phone device. The application must be the owner of the phone.

dwHookSwitchDev

Identifies the hookswitch device whose speaker's volume is to be set.

PHONEHOOKSWITCHDEV_HANDSET

This is the phone's handset.

PHONEHOOKSWITCHDEV_SPEAKER

This is the phone's speakerphone or adjunct.

PHONEHOOKSWITCHDEV_HEADSET

This is the phone's headset.

dwVolume

Specifies the current volume setting of the device. dwVolume specifies the volume level of the hookswitch device. This is a number in the range 0x00000000 (silence) to 0x0000FFFF (maximum volume). The actual granularity and quantization of volume settings in this range are service-provider specific. A value for dwVolume that is out of range is set to the nearest value in the range.


 phoneShutdown

[New - Windows 95]

LONG phoneShutdown(HPHONEAPP hPhoneApp)

Shuts down the application's usage of TAPI's phone abstraction.

•	Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are:

PHONEERR_INVALAPPHANDLE	PHONEERR_NOMEM
PHONEERR_UNINITIALIZED	PHONEERR_RESOURCEUNAVAIL
hPhoneApp

Specifies the application's usage handle for TAPI.

If this function is called when the application has open phone devices. These devices will be closed.


 Messages

Following are the TAPI phone messages.


 PHONE_BUTTON

[New - Windows 95]

PHONE_BUTTON
hPhone = (HPHONE) hPhoneDevice;
dwCallbackInstance = (DWORD) hCallback;
dwParam1 = (DWORD) idButtonOrLamp;
dwParam2 = (DWORD) ButtonMode;
dwParam3 = (DWORD) ButtonState;

Sent to notify the application that button press monitoring is enabled if it has detected a button press on the local phone.

•	No return value.

hPhone

Specifies a handle to the phone device.

dwCallbackInstance

Specifies the application's callback instance provided when opening the phone device.

dwParam1

Specifies the button/lamp ID of the button that was pressed. Note that button IDs 0 through 11 are always the KEYPAD buttons, with '0' being button ID 0, '1' being button ID 1 (and so on through button ID 9), and with '*' being button ID 10, and '#' being button ID 11. Additional information about a button ID is available with phoneGetDevCaps and phoneGetButtonInfo.

dwParam2

Specifies the button mode of the button. This parameter uses the following PHONEBUTTONMODE_ constants:

PHONEBUTTONMODE_CALL

The button is assigned to a call appearance.

PHONEBUTTONMODE_FEATURE

The button is assigned to requesting features from the switch, such as hold, conference, and transfer.

PHONEBUTTONMODE_KEYPAD

The button is one of the twelve keypad buttons, '0' through '9', '*', and '#'.

PHONEBUTTONMODE_LOCAL

The button is a local function button, such as mute or volume control.

PHONEBUTTONMODE_DISPLAY

The button is a "soft" button associated with the phone's display. A phone set can have zero or more display buttons.

dwParam3

Specifies whether this is a button-down event or a button-up event. This parameter uses the following PHONEBUTTONSTATE_ constants:

PHONEBUTTONSTATE_UP

The button is in the "up" state.

PHONEBUTTONSTATE_DOWN

The button is in the "down" state (pressed down).

PHONEBUTTONSTATE_UNKNOWN

Indicates that the up or down state of the button is not known at this time, but may become known at a future time.

PHONEBUTTONSTATE_UNAVAIL

Indicates that the up or down state of the button is not known to the service provider, and will not become known at a future time.

A PHONE_BUTTON message is sent whenever a button changes state. An application is guaranteed that for each button down event, it will eventually be sent a corresponding button up event. Note that a service provider that is incapable of detecting the actual button up is required to generate the button up message shortly after the button down message for each button press.


 PHONE_CLOSE

[New - Windows 95]

PHONE_CLOSE
hPhone = (HPHONE) hPhoneDevice;
dwCallbackInstance = (DWORD) hCallback;
dwParam1 = (DWORD) 0;
dwParam2 = (DWORD) 0;
dwParam3 = (DWORD) 0;

Sent when an open phone device has been forcibly closed as part of resource reclamation. The device handle is no longer valid once this message has been sent.

•	No return value.

hPhone

Specifies a handle to the open phone device that was closed. The handle is no longer valid after this message has been sent

dwCallbackInstance

Specifies the application's callback instance provided when opening the phone device.

dwParam1

Unused.

dwParam2

Unused.

dwParam3

Unused.

This message is only sent to an application after an open phone has been forcibly closed. This may be done to prevent a single application from monopolizing a phone device for too long. Whether the phone can be reopened immediately after a forced close is device-specific.

An open phone device may also be forcibly closed after the user has modified the configuration of that phone or its driver. If the user wants the configuration changes to be effective immediately (as opposed to after the next system restart), and these changes affect the application's current view of the device (such as a change in device capabilities), then a service provider may forcibly close the phone device.


 PHONE_CREATE

[New - Windows 95]

PHONE_CREATE
hPhone = (HPHONE) hPhoneDev;
dwCallbackInstance = (DWORD) 0;
dwParam1 = (DWORD) idDevice;
dwParam2 = (DWORD) 0;
dwParam3 = (DWORD) 0;

Set to inform applications of the creation of a new phone device.

•	No return value.

hPhone

Unused.

dwCallbackInstance

Unused.

dwParam1

Specifies the dwDeviceID of the newly-created device.

dwParam2

Unused.

dwParam3

Unused.

Older applications (which negotiated an API version prior to the creation of this feature) are sent a PHONE_STATE message specifying PHONESTATE_REINIT, which requires them to shut down their use of the API and call phoneInitialize again to obtain the new number of devices. Unlike previous versions of TAPI, however, this version does not require all applications to shut down before allowing applications to reinitialize; reinitialization can take place immediately when a new device is created (complete shutdown is still required when a service provider is removed from the system).

Applications supporting this and subsequent versions of the API are sent a PHONE_CREATE message. This informs them of the existence of the new device and its new device ID. The application can then choose whether or not to attempt working with the new device at its leisure. This message will be sent to all applications supporting this or subsequent versions of the API which have called phoneInitialize, including those that do not have any line devices open at the time.


 PHONE_DEVSPECIFIC

[New - Windows 95]

PHONE_DEVSPECIFIC
hPhone = (HPHONE) hPhoneDevice;
dwCallbackInstance = (DWORD) hCallback;
dwParam1 = (DWORD) DeviceSpecific1;
dwParam2 = (DWORD) DeviceSpecific2;
dwParam3 = (DWORD) DeviceSpecific3;

The implementation sends this message to an application's callback to notify the application about device-specific events occurring at the phone. The meaning of the message and the interpretation of the parameters is implementation-defined.

•	No return value.

hPhone

Specifies a handle to the phone device.

dwCallbackInstance

Specifies the application's callback instance provided when opening the phone device.

dwParam1

Device specific.

dwParam2

Device specific.

dwParam3

Device specific.


 PHONE_REPLY

[New - Windows 95]

PHONE_REPLY
hPhone = (HPHONE) 0;
dwCallbackInstance = (DWORD) hCallback;
dwParam1 = (DWORD) idRequest;
dwParam2 = (DWORD) Status;
dwParam3 = (DWORD) 0;

This message is sent to an application's callback to report the results of function call that completed asynchronously.

•	No return value.

hDevice

Unused.

dwCallbackInstance

Returns the application's callback instance.

dwParam1

Specifies the request ID for which this is the reply.

dwParam2

Specifies the success or error indication. The application should cast this parameter into a LONG. Zero indicates success; a negative number indicates an error.

dwParam3

Unused.

Functions that operate asynchronously return a positive request ID value to the application. This request ID is returned with the reply message to identify the request that was completed. The other parameter for this message carries the success or failure indication. Possible errors are the same as those defined by the corresponding function. This message cannot be disabled.


 PHONE_STATE

[New - Windows 95]

PHONE_STATE
hPhone = (HPHONE) hPhoneDevice;
dwCallbackInstance = (DWORD) hCallback;
dwParam1 = (DWORD) PhoneState;
dwParam2 = (DWORD) PhoneStateDetails;
dwParam3 = (DWORD) 0;

The service provider sends this message to an application's callback function whenever the status of a phone device changes.

•	No return value.

hPhone

Specifies a handle to the phone device.

dwCallbackInstance

Specifies the application's callback instance provided when opening the phone device.

dwParam1

Specifies the phone state that has changed. This parameter uses the following PHONESTATE_ constants:

PHONESTATE_OTHER

Phone-status items other than those listed below have changed. The application should check the current phone status to determine which items have changed.

PHONESTATE_CONNECTED

The connection between the phone device and TAPI was just made. This happens when TAPI is first invoked or when the wire connecting the phone to the computer is plugged in with TAPI active.

PHONESTATE_DISCONNECTED

The connection between the phone device and TAPI was just broken. This happens when the wire connecting the phone set to the computer is unplugged while TAPI is active.

PHONESTATE_OWNER

The number of owners for the phone device has changed.

PHONESTATE_MONITORS

The number of monitors for the phone device has changed.

PHONESTATE_DISPLAY

The display of the phone has changed.

PHONESTATE_LAMP

A lamp of the phone has changed.

PHONESTATE_RINGMODE

The ring mode of the phone has changed.

PHONESTATE_RINGVOLUME

The ring volume of the phone has changed.

PHONESTATE_HANDSETHOOKSWITCH

The handset hookswitch state has changed.

PHONESTATE_HANDSETVOLUME

The handset's speaker volume setting has changed.

PHONESTATE_HANDSETGAIN

The handset's microphone gain setting has changed.

PHONESTATE_SPEAKERHOOKSWITCH

The speakerphone's hookswitch state has changed.

PHONESTATE_SPEAKERVOLUME

The speakerphone's speaker volume setting has changed.

PHONESTATE_SPEAKERGAIN

The speakerphone's microphone gain setting state has changed.

PHONESTATE_HEADSETHOOKSWITCH

The headset's hookswitch state has changed.

PHONESTATE_HEADSETVOLUME

The headset's speaker volume setting has changed.

PHONESTATE_HEADSETGAIN

The headset's microphone gain setting has changed.

PHONESTATE_SUSPEND

The application's use of the phone device is temporarily suspended.

PHONESTATE_RESUME

The application's use of the phone device is resumed after having been suspended for some time.

PHONESTATE_DEVSPECIFIC

The phone's device-specific information has changed.

PHONESTATE_REINIT

Items have changed in the configuration of phone devices. To become aware of these changes (as with the appearance of new phone devices), the application should reinitialize its use of TAPI. The hDevice parameter of the PHONE_STATE message is left NULL for this state change as it applies to any of the phones in the system. This message with the PHONESTATE_REINIT bit set is only sent to applications that have opened a phone; that is, if an application has only called phoneInitialize but not yet opened any device and a PHONESTATE_REINIT message is sent, then the message is not sent to that application.

PHONESTATE_CAPSCHANGE

Indicates that, due to configuration changes made by the user or other circumstances, one or more of the fields in the PHONECAPS structure have changed. The application should use phoneGetDevCaps to read the updated structure.

PHONESTATE_REMOVED

Indicates that the device is being removed from the system by the service provider (most likely through user action, via a control panel or similar utility). A PHONE_STATE message with this value will normally be immediately followed by a PHONE_CLOSE message on the device. Subsequent attempts to access the device prior to TAPI being reinitialized will result in PHONEERR_NODEVICE being returned to the application. If a service provider sends a PHONE_STATE message containing this value to TAPI, TAPI will pass it along to applications which have negotiated this or a subsequent API version; applications negotiating a previous API version will not receive any notification.

dwParam2

Specifies phone-state-dependent information detailing the status change. This field is not used if multiple flags are set in dwParam1, since multiple status items have changed. The application should invoke phoneGetStatus to obtain complete set of information.

If dwParam1 is PHONESTATE_OWNER, dwParam2 contains the new number of owners.

If dwParam1 is PHONESTATE_MONITORS, dwParam2 contains the new number of monitors.

If dwParam1 is PHONESTATE_LAMP, dwParam2 contains the button/lamp ID of the lamp that has changed.

If dwParam1 is PHONESTATE_RINGMODE, dwParam2 contains the new ring mode.

If dwParam1 is PHONESTATE_HANDSET, SPEAKER or HEADSET, dwParam2 contains the new hookswitch mode of that hookswitch device. This parameter uses the following PHONEHOOKSWITCHMODE_ constants:

PHONEHOOKSWITCHMODE_ONHOOK

The device's microphone and speaker are both onhook.

PHONEHOOKSWITCHMODE_MIC

The device's microphone is active, the speaker is mute.

PHONEHOOKSWITCHMODE_SPEAKER

The device's speaker is active, the microphone is mute.

PHONEHOOKSWITCHMODE_MICSPEAKER

The device's microphone and speaker are both active.

dwParam3

Unused.

Sending this message to the callback function can be controlled and queried using phoneSetStatusMessages and phoneGetStatusMessages. By default, this message is disabled for all state changes except for PHONESTATE_REINIT, which cannot be disabled. This message is sent to all applications that have a handle to the phone, including those that called phoneOpen with the dwPrivileges parameter set to PHONEPRIVILEGE_OWNER or PHONEPRIVILEGE_MONITOR.

A PHONE_STATE message with an Owners and/or Monitors indication is sent to applications that already have a handle for the phone. This can be the result of another application changing ownership or monitorship of the phone device with phoneOpen, phoneClose or phoneShutdown.


 Structures

Following are the TAPI phone structures.


 PHONEBUTTONINFO

[New - Windows 95]

typedef struct phonebuttoninfo_tag {
  DWORD  dwTotalSize;
  DWORD  dwNeededSize;
  DWORD  dwUsedSize;
  DWORD  dwButtonMode;
  DWORD  dwButtonFunction;
  DWORD  dwButtonTextSize;
  DWORD  dwButtonTextOffset;
  DWORD  dwDevSpecificSize;
  DWORD  dwDevSpecificOffset;
  DWORD  dwButtonState;
} PHONEBUTTONINFO, FAR *LPPHONEBUTTONINFO;

The PHONEBUTTONINFO structure contains information about a button on a phone device.

dwTotalSize

The total size in bytes allocated to this data structure.

dwNeededSize

The size in bytes for this data structure that is needed to hold all the returned information.

dwUsedSize

The size in bytes of the portion of this data structure that contains useful information.

dwButtonMode

Defines the mode or general usage class of the button. This parameter uses the following PHONEBUTTONMODE_ constants:

PHONEBUTTONMODE_DUMMY

This value is used to describe a button/lamp position that has no corresponding button but has only a lamp.

PHONEBUTTONMODE_CALL

The button is assigned to a call appearance.

PHONEBUTTONMODE_FEATURE

The button is assigned to requesting features from the switch, such as hold, conference, and transfer.

PHONEBUTTONMODE_KEYPAD

The button is one of the twelve keypad buttons, '0' through '9', '*', and '#'.

PHONEBUTTONMODE_LOCAL

The button is a local function button, such as mute or volume control.

PHONEBUTTONMODE_DISPLAY

The button is a "soft" button associated with the phone's display. A phone set can have zero or more display buttons.

dwButtonFunction

Specifies the function assigned to the button. This field uses the PHONEBUTTONFUNCTION_ constants.

dwButtonTextSize
dwButtonTextOffset

The size in bytes of the variably sized field containing descriptive text for this button., and the offset in bytes from the beginning of this data structure.  The format of this information is as specified in the dwStringFormat field of the phone's device capabilities.

dwDevSpecificSize
dwDevSpecificOffset

The size in bytes of the variably sized device-specific field, and the offset in bytes from the beginning of this data structure.

dwButtonState

For the phoneGetButtonInfo function, this field indicates the current state of the button, using the PHONEBUTTONSTATE_ constants. This field is ignored by the phoneSetButtonInfo function.

Device-specific extensions should use the DevSpecific (dwDevSpecificSize and dwDevSpecificOffset) variably sized area of this data structure.

Older applications will have been compiled without this field in the PHONEBUTTONINFO structure, and using a SIZEOF PHONEBUTTONINFO smaller than the new size. The application passes in a dwAPIVersion parameter with the phoneOpen function, which can be used for guidance by TAPI in handling this situation. If the application passes in a dwTotalSize less than the size of the fixed portion of the structure as defined in the dwAPIVersion specified, PHONEERR_STRUCTURETOOSMALL will be returned. If sufficient memory has been allocated by the application, before calling TSPI_phoneGetButtonInfo, TAPI will set the dwNeededSize and dwUsedSize fields to the fixed size of the structure as it existed in the specified API version.

New service providers (which support the new API version) must examine the API version passed in. If the API version is less than the highest version supported by the provider, the service provider must not fill in fields not supported in older API versions, as these would fall in the variable portion of the older structure.

New applications must be cognizant of the API version negotiated, and not examine the contents of fields in the fixed portion beyond the original end of the fixed portion of the structure for the negotiated API version.


 PHONECAPS

[New - Windows 95]

typedef struct phonecaps_tag {
  DWORD  dwTotalSize;
  DWORD  dwNeededSize;
  DWORD  dwUsedSize;
  DWORD  dwProviderInfoSize;
  DWORD  dwProviderInfoOffset;
  DWORD  dwPhoneInfoSize;
  DWORD  dwPhoneInfoOffset;
  DWORD  dwPermanentPhoneID;
  DWORD  dwPhoneNameSize;
  DWORD  dwPhoneNameOffset;
  DWORD  dwStringFormat;
  DWORD  dwPhoneStates;
  DWORD  dwHookSwitchDevs;
  DWORD  dwHandsetHookSwitchModes;
  DWORD  dwSpeakerHookSwitchModes;
  DWORD  dwHeadsetHookSwitchModes;
  DWORD  dwVolumeFlags;
  DWORD  dwGainFlags;
  DWORD  dwDisplayNumRows;
  DWORD  dwDisplayNumColumns;
  DWORD  dwNumRingModes;
  DWORD  dwNumButtonLamps;
  DWORD  dwButtonModesSize;
  DWORD  dwButtonModesOffset;
  DWORD  dwButtonFunctionsSize;
  DWORD  dwButtonFunctionsOffset;
  DWORD  dwLampModesSize;
  DWORD  dwLampModesOffset;
  DWORD  dwNumSetData;
  DWORD  dwSetDataSize;
  DWORD  dwSetDataOffset;
  DWORD  dwNumGetData
  DWORD  dwGetDataSize;
  DWORD  dwGetDataOffset;
  DWORD  dwDevSpecificSize;

  DWORD  dwDevSpecificOffset;
} PHONECAPS, FAR *LPPHONECAPS;

The PHONECAPS structure describes the capabilities of a phone device.

dwTotalSize

The total size in bytes allocated to this data structure.

dwNeededSize

The size in bytes for this data structure that is needed to hold all the returned information.

dwUsedSize

The size in bytes of the portion of this data structure that contains useful information.

dwProviderInfoSize
dwProviderInfoOffset

The size in bytes of the variably sized field containing service provider-specific information, and the offset in bytes from the beginning of this data structure.

The dwProviderInfoSize/Offset field is intended to provide information about the provider hardware and/or software, such as the vendor name and version numbers of hardware and software. This information can be useful when a user needs to call customer service with problems regarding the provider.

dwPhoneInfoSize
dwPhoneInfoOffset

The size in bytes of the variably sized device field containing phone-specific information, and the offset in bytes from the beginning of this data structure.

The dwPhoneInfoSize/Offset field is intended to provide information about the attached phone device, such as the phone-device manufacturer, the model name, the software version, and so on. This information can be useful when a user needs to call customer service with problems regarding the phone.

dwPermanentPhoneID

Specifies the permanent DWORD identifier by which the phone device is known in the system's configuration.

dwPhoneNameSize
dwPhoneNameOffset

The size in bytes of the variably sized device field containing user configurable name for this phone device,  and the offset in bytes from the beginning of this data structure This name can be configured by the user when configuring the phone device's service provider and is provided for the user's convenience.

dwStringFormat

Specifies the string format to be used with this phone device. This parameter uses the following STRINGFORMAT_ constants:

STRINGFORMAT_ASCII

This is ASCII string format using one byte per character.

STRINGFORMAT_DBCS

This is DBCS string format using two bytes per character.

STRINGFORMAT_UNICODE

This is unicode string format using two bytes per character.

dwPhoneStates

Specifies the state changes for this phone device for which the application can be notified in a PHONE_STATE callback message. This parameter uses the following PHONESTATE_ constants:

PHONESTATE_OTHER

Phone-status items other than those listed below have changed. The application should check the current phone status to determine which items have changed.

PHONESTATE_CONNECTED

The connection between the phone device and TAPI was just made. This happens when TAPI is first invoked or when the wire connecting the phone to the PC is plugged in with TAPI active.

PHONESTATE_DISCONNECTED

The connection between the phone device and TAPI was just broken. This happens when the wire connecting the phone set to the PC is unplugged while TAPI is active.

PHONESTATE_OWNER

The number of owners for the phone device has changed.

PHONESTATE_MONITORS

The number of monitors for the phone device has changed.

PHONESTATE_DISPLAY

The display of the phone has changed.

PHONESTATE_LAMP

A lamp of the phone has changed.

PHONESTATE_RINGMODE

The ring mode of the phone has changed.

PHONESTATE_RINGVOLUME

The ring volume of the phone has changed.

PHONESTATE_HANDSETHOOKSWITCH

The handset hookswitch state has changed.

PHONESTATE_HANDSETVOLUME

The handset's speaker volume setting has changed.

PHONESTATE_HANDSETGAIN

The handset's microphone gain setting has changed.

PHONESTATE_SPEAKERHOOKSWITCH

The speakerphone's hookswitch state has changed.

PHONESTATE_SPEAKERVOLUME

The speakerphone's speaker volume setting has changed.

PHONESTATE_SPEAKERGAIN

The speakerphone's microphone gain setting state has changed.

PHONESTATE_HEADSETHOOKSWITCH

The headset's hookswitch state has changed.

PHONESTATE_HEADSETVOLUME

The headset's speaker volume setting has changed.

PHONESTATE_HEADSETGAIN

The headset's microphone gain setting has changed.

PHONESTATE_SUSPEND

The application's use of the phone is temporarily suspended.

PHONESTATE_RESUME

The application's use of the phone device is resumed after having been suspended for some time.

PHONESTATE_DEVSPECIFIC

The phone's device-specific information has changed.

PHONESTATE_REINIT

Items have changed in the configuration of phone devices. To become aware of these changes (as for the appearance of new phone devices) the application should reinitialize its use of TAPI.

PHONESTATE_CAPSCHANGE

Indicates that, due to configuration changes made by the user or other circumstances, one or more of the fields in the PHONECAPS structure have changed. The application should use phoneGetDevCaps to read the updated structure.

PHONESTATE_REMOVED

Indicates that the device is being removed from the system by the service provider (most likely through user action, via a control panel or similar utility). A PHONE_STATE message with this value will normally be immediately followed by a PHONE_CLOSE message on the device. Subsequent attempts to access the device prior to TAPI being reinitialized will result in PHONEERR_NODEVICE being returned to the application. If a service provider sends a PHONE_STATE message containing this value to TAPI, TAPI will pass it along to applications which have negotiated this or a subsequent API version; applications negotiating a previous API version will not receive any notification.

dwHookSwitchDevs

This field specifies the phone's hookswitch devices. This parameter uses the following PHONEHOOKSWITCHDEV_ constants:

PHONEHOOKSWITCHDEV_HANDSET

This is the ubiquitous, handheld, ear- and mouthpiece.

PHONEHOOKSWITCHDEV_SPEAKER

A built-in loudspeaker and microphone. This could also be an externally connected adjunct to the telephone set.

PHONEHOOKSWITCHDEV_HEADSET

This is a headset connected to the phone set.

dwHandsetHookSwitchModes
dwSpeakerHookSwitchModes
dwHeadsetHookSwitchModes

This field specifies the phone's hookswitch mode capabilities of the handset, speaker, or headset, respectively. The field is only meaningful if the hookswitch device is listed in dwHookSwitchDevs. This parameter uses the following PHONEHOOKSWITCHMODE_ constants:

PHONEHOOKSWITCHMODE_ONHOOK

The device's microphone and speaker are both onhook.

PHONEHOOKSWITCHMODE_MIC

The device's microphone is active, the speaker is mute.

PHONEHOOKSWITCHMODE_SPEAKER

The device's speaker is active, the microphone is mute.

PHONEHOOKSWITCHMODE_MICSPEAKER

The device's microphone and speaker are both active.

dwVolumeFlags

This field specifies the volume setting capabilities of the phone device's speaker components. If the bit in position PHONEHOOKSWITCHDEV_ is TRUE, the volume of the corresponding hookswitch device's speaker component can be adjusted with phoneSetVolume; otherwise FALSE.

dwGainFlags

This field specifies the gain setting capabilities of the phone device's microphone components. If the bit position PHONEHOOKSWITCHDEV_ is TRUE, the volume of the corresponding hookswitch device's microphone component can be adjusted with phoneSetGain; otherwise FALSE.

dwDisplayNumRows

This field specifies the display capabilities of the phone device by describing the number of rows in the phone display. dwDisplayNumRows and dwDisplayNumColumns are both zero for a phone device without a display.

dwDisplayNumColumns

This field specifies the display capabilities of the phone device by describing the number of columns in the phone display. dwDisplayNumRows and dwDisplayNumColumns are both zero for a phone device without a display.

dwNumRingModes

This field specifies the ring capabilities of the phone device. The phone is able to ring with dwNumRingModes different ring patterns, identified as 1, 2, thru dwNumRingModes minus one. If the value of this field is zero, applications have no control over the ring mode of the phone. If the value of this field is greater than zero, it indicates the number of ring modes in addition to silence that are supported by the service provider. A value of 0 in the lpdwRingMode parameter of phoneGetRing or the dwRingMode parameter of phoneSetRing indicates silence (the phone is not ringing or should not be rung), and dwRingMode values of 1 to dwNumRingModes are valid ring modes for the phone device.

dwNumButtonLamps

This field specifies the number of button/lamps on the phone device that are detectable in TAPI. Button/lamps are identified by their ID. Valid button/lamp IDs range from zero to dwNumButtonLamps minus one. The keypad buttons '0', through '9', '*', and '#' are assigned the IDs 0 through 12.

dwButtonModesSize
dwButtonModesOffset

The size in bytes and the offset from the beginning of this data structure in bytes of the variably sized field containing the button modes of the phone's buttons. The array is indexed by button/lamp ID. This parameter uses the following PHONEBUTTONMODE_ constants:

PHONEBUTTONMODE_DUMMY

This value is used to describe a button/lamp position that has no corresponding button, but has only a lamp. If the phone provides any non-DUMMY buttons, the PHONE_BUTTON message will be sent to the application if a button is pressed at the phone device.

PHONEBUTTONMODE_CALL

The button is assigned to a call appearance.

PHONEBUTTONMODE_FEATURE

The button is assigned to requesting features from the switch, such as hold, conference, and transfer.

PHONEBUTTONMODE_KEYPAD

The button is one of the twelve keypad buttons, '0' through '9', '*', and '#'.

PHONEBUTTONMODE_LOCAL

The button is a local function button, such as mute or volume control.

PHONEBUTTONMODE_DISPLAY

The button is a "soft" button associated with the phone's display. A phone set can have zero or more display buttons.

dwButtonFunctionsSize
dwButtonFunctionsOffset

The size in bytes of the variably sized field containing the button modes of the phone's buttons, and the offset in bytes from the beginning of this data structure. This field uses the values specified by the PHONEBUTTONFUNCTION_ constants. The array is indexed by button/lamp ID.

dwLampModesSize
dwLampModesOffset

The size in bytes of the variably sized field containing the lamp modes of the phone's lamps, and the offset in bytes from the beginning of this data structure. The array is indexed by button/lamp ID. This parameter uses the following PHONELAMPMODE_ constants:

PHONELAMPMODE_BROKENFLUTTER

Broken flutter is the superposition of flash and flutter.

PHONELAMPMODE_FLASH

Flash means slow on and off.

PHONELAMPMODE_FLUTTER

Flutter means fast on and off.

PHONELAMPMODE_OFF

The lamp is off.

PHONELAMPMODE_STEADY

The lamp is continuously lit.

PHONELAMPMODE_WINK

The lamp is winking.

PHONELAMPMODE_DUMMY

This value is used to describe a button/lamp position that has no corresponding lamp.

dwNumSetData

The number of different download areas in the phone device. The different areas are referred to using the data IDs 0, 1, …, dwNumSetData minus one. If this field is zero, the phone does not support the download capability.

dwSetDataSize
dwSetDataOffset

The size in bytes of the variably sized field containing the sizes (in bytes) of the phone's download data areas, and the offset in bytes from the beginning of this data structure. This is an array with DWORD-sized elements indexed by data ID.

dwNumGetData

The number of different upload areas in the phone device. The different areas are referred to using the data IDs 0, 1, …, dwNumGetData minus one. If this field is zero, the phone does not support the upload capability.

dwGetDataSize
dwGetDataOffset

The size in bytes of the variably sized field containing the sizes (in bytes) of the phone's upload data areas, and the offset in bytes from the beginning of this data structure. This is an array with DWORD-sized elements indexed by data ID.

dwDevSpecificSize
dwDevSpecificOffset

The size in bytes of the variably sized device-specific field, and the offset in bytes from the beginning of this data structure

Device-specific extensions should use the DevSpecific (dwDevSpecificSize and dwDevSpecificOffset) variably sized area of this data structure.


 PHONEEXTENSIONID

[New - Windows 95]

typedef struct phoneextensionid_tag {
  DWORD  dwExtensionID0;
  DWORD  dwExtensionID1;
  DWORD  dwExtensionID2;
  DWORD  dwExtensionID3;
} PHONEEXTENSIONID, FAR *LPPHONEEXTENSIONID;

The PHONEEXTENSIONID structure describes an extension ID. Extension IDs are used to identify service provider-specific extensions for phone device classes.

dwExtensionID0
dwExtensionID1
dwExtensionID2
dwExtensionID3

These four DWORD-sized fields together specify a universally unique extension ID that identifies a phone device class extension.

No extensibility.

Extension IDs are generated using an SDK-provided generation utility.


 PHONESTATUS

[New - Windows 95]

typedef struct phonestatus_tag {
  DWORD  dwTotalSize;
  DWORD  dwNeededSize;
  DWORD  dwUsedSize;
  DWORD  dwStatusFlags;
  DWORD  dwNumOwners;
  DWORD  dwNumMonitors;
  DWORD  dwRingMode;
  DWORD  dwRingVolume;
  DWORD  dwHandsetHookSwitchMode;
  DWORD  dwHandsetVolume;
  DWORD  dwHandsetGain;
  DWORD  dwSpeakerHookSwitchMode;
  DWORD  dwSpeakerVolume;
  DWORD  dwSpeakerGain;
  DWORD  dwHeadsetHookSwitchMode;
  DWORD  dwHeadsetVolume;
  DWORD  dwHeadsetGain;
  DWORD  dwDisplaySize;
  DWORD  dwDisplayOffset;
  DWORD  dwLampModesSize;
  DWORD  dwLampModesOffset;
  DWORD  dwOwnerNameSize;
  DWORD  dwOwnerNameOffset;
  DWORD  dwDevSpecificSize;
  DWORD  dwDevSpecificOffset;
} PHONESTATUS, FAR *LPPHONESTATUS;

The PHONESTATUS structure describes the current status of a phone device.

dwTotalSize

The total size in bytes allocated to this data structure.

dwNeededSize

The size in bytes for this data structure that is needed to hold all the returned information.

dwUsedSize

The size in bytes of the portion of this data structure that contains useful information.

dwStatusFlags

This field provides a set of status flags for this phone device. This parameter uses the following PHONESTATUSFLAGS_ constants:

PHONESTATUSFLAGS_CONNECTED

Specifies whether the phone is currently connected to TAPI. TRUE if connected; FALSE otherwise.

PHONESTATUSFLAGS_SUSPENDED

Specifies whether TAPI's manipulation of the phone device is suspended. TRUE if suspended; FALSE otherwise. An application's use of a phone device may be temporarily suspended when the switch wants to manipulate the phone in a way that cannot tolerate interference from the application.

dwNumOwners

The number of application modules with owner privilege for the phone.

dwNumMonitors

The number of application modules with monitor privilege for the phone.

dwRingMode

Specifies the current ring mode of a phone device.

dwRingVolume

Specifies the current ring volume of a phone device. This is a value between 0x00000000 (silence) and 0x0000FFFF (maximum volume).

dwHandsetHookSwitchMode

Specifies the current hookswitch mode of the phone's handset. This parameter uses the following PHONEHOOKSWITCHMODE_ constants:

PHONEHOOKSWITCHMODE_ONHOOK

The device's microphone and speaker are both onhook.

PHONEHOOKSWITCHMODE_MIC

The devicer's microphone is active, the speaker is mute.

PHONEHOOKSWITCHMODE_SPEAKER

The device's speaker is active, the microphone is mute.

PHONEHOOKSWITCHMODE_MICSPEAKER

The device's microphone and speaker are both active.

dwHandsetVolume

Specifies the current speaker volume of the phone's handset device. This is a value between 0x00000000 (silence) and 0x0000FFFF (maximum volume).

dwHandsetGain

Specifies the current microphone gain of the phone's handset device. This is a value between 0x00000000 (silence) and 0x0000FFFF (maximum gain).

dwSpeakerHookSwitchMode

Specifies the current hookswitch mode of the phone's speakerphone. This parameter uses the following PHONEHOOKSWITCHMODE_ constants:

PHONEHOOKSWITCHMODE_ONHOOK

The device's microphone and speaker are both onhook.

PHONEHOOKSWITCHMODE_MIC

The devicer's microphone is active, the speaker is mute.

PHONEHOOKSWITCHMODE_SPEAKER

The device's speaker is active, the microphone is mute.

PHONEHOOKSWITCHMODE_MICSPEAKER

The device's microphone and speaker are both active.

dwSpeakerVolume

Specifies the current speaker volume of the phone's speaker device. This is a value between 0x00000000 (silence) and 0x0000FFFF (maximum volume).

dwSpeakerGain

Specifies the current microphone gain of the phone's speaker device. This is a value between 0x00000000 (silence) and 0x0000FFFF (maximum gain).

dwHeadsetHookSwitchMode

Specifies the current hookswitch mode of the phone's headset. This parameter uses the following PHONEHOOKSWITCHMODE_ constants:

PHONEHOOKSWITCHMODE_ONHOOK

The device's microphone and speaker are both onhook.

PHONEHOOKSWITCHMODE_MIC

The devicer's microphone is active, the speaker is mute.

PHONEHOOKSWITCHMODE_SPEAKER

The device's speaker is active, the microphone is mute.

PHONEHOOKSWITCHMODE_MICSPEAKER

The device's microphone and speaker are both active.

dwHeadsetVolume

Specifies the current speaker volume of the phone's headset device. This is a value between 0x00000000 (silence) and 0x0000FFFF (maximum volume).

dwHeadsetGain

Specifies the current microphone gain of the phone's headset device. This is a value between 0x00000000 (silence) and 0x0000FFFF (maximum gain).

dwDisplaySize
dwDisplayOffset

The size in bytes of the variably sized field containing the phone's current display information, and the offset in bytes, from the beginning of this data structure.

dwLampModesSize
dwLampModesOffset

The size in bytes of the variably sized field containing the phone's current lamp modes, and the offset in bytes from the beginning of this data structure.

dwOwnerNameSize
dwOwnerNameOffset

The size in bytes of the variably sized field containing the name of the application that is the the current owner of the phone device, and the offset in bytes from the beginning of this data structure. The name is the application name provided by the application when it invoked with phoneInitialize. If no application name was supplied, the application's file name is used instead. If the phone currently has no owner, dwOwnerNameSize is zero.

dwDevSpecificSize
dwDevSpecificOffset

The size in bytes of the variably sized device-specific field, and the offset in bytes from the beginning of this data structure

Device-specific extensions should use the DevSpecific (dwDevSpecificSize and dwDevSpecificOffset) variably sized area of this data structure.


 VARSTRING

[New - Windows 95]

typedef struct varstring_tag {
  DWORD  dwTotalSize;
  DWORD  dwNeededSize;
  DWORD  dwUsedSize;
  DWORD  dwStringFormat;
  DWORD  dwStringSize;
  DWORD  dwStringOffset;
} VARSTRING, FAR *LPVARSTRING;

The VARSTRING structure is used for returning variably sized strings. It is used both by the line device class and the phone device class.

dwTotalSize

The total size in bytes allocated to this data structure.

dwNeededSize

The size in bytes for this data structure that is needed to hold all the returned information.

dwUsedSize

The size in bytes of the portion of this data structure that contains useful information.

dwStringFormat

Specifies the format of the string. This parameter uses the following STRINGFORMAT_ constants:

STRINGFORMAT_ASCII

This is ASCII string format using one byte per character. The actual string is a NULL-terminated ASCII string with the terminating NULL accounted for in the string size.

STRINGFORMAT_DBCS

This is DBCS string format using one or two bytes per character.

STRINGFORMAT_UNICODE

This is unicode string format using two bytes per character.

STRINGFORMAT_BINARY

This is an array of unsigned characters that could be used for numeric values.

dwStringSize
dwStringOffset

The size in bytes of the variably sized device field containing the string information, and the offset in bytes from the beginning of this data structure, .

No extensibility.

If a string cannot be returned in a variable structure, the dwStringSize and dwStringOffset members are set in one of these ways:

•	dwStringSize and dwStringOffset members are both set to zero.

•	dwStringOffset is nonzero and dwStringSize is zero.

•	dwStringOffset is nonzero, dwStringSize is 1, and the byte at the given offset is 0.


 Constants

Following are the TAPI phone constants.


 PHONEBUTTONFUNCTION_ Constants

[New - Windows 95]

The PHONEBUTTONFUNCTION_ scalar constants describe the functions commonly assigned to buttons on telephone sets.

PHONEBUTTONFUNCTION_UNKNOWN

A "dummy" function assignment that indicates that the exact function of the button is unknown or has not been assigned.

PHONEBUTTONFUNCTION_CONFERENCE

Initiates a conference call or adds a call to a conference call.

PHONEBUTTONFUNCTION_TRANSFER

Initiates a call transfer or completes the transfer of a call.

PHONEBUTTONFUNCTION_DROP

Drops the active call.

PHONEBUTTONFUNCTION_HOLD

Places the active call on hold.

PHONEBUTTONFUNCTION_RECALL

Unholds a call.

PHONEBUTTONFUNCTION_DISCONNECT

Disconnects a call, such as after initiating a transfer.

PHONEBUTTONFUNCTION_CONNECT

Reconnects a call that is on consultation hold.

PHONEBUTTONFUNCTION_MSGWAITON

Turns on a message waiting lamp.

PHONEBUTTONFUNCTION_MSGWAITOFF

Turns off a message waiting lamp.

PHONEBUTTONFUNCTION_SELECTRING

Allows the user to select the ring pattern of the phone.

PHONEBUTTONFUNCTION_ABBREVDIAL

The number to dialed will be indicated using a short, abbreviated number consisting of one or a few digits.

PHONEBUTTONFUNCTION_FORWARD

Initiates or changes call forwarding to this phone.

PHONEBUTTONFUNCTION_PICKUP

Picks up a call ringing on another phone.

PHONEBUTTONFUNCTION_RINGAGAIN

Initiates a request to be notified if a call cannot be completed normally because of a busy or no answer.

PHONEBUTTONFUNCTION_PARK

Parks the active call on another phone, placing it on hold there.

PHONEBUTTONFUNCTION_REJECT

Rejects an inbound call before the call has been answered.

PHONEBUTTONFUNCTION_REDIRECT

Redirects an inbound call to another extension before the call has been answered.

PHONEBUTTONFUNCTION_MUTE

Mutes the phone's microphone device.

PHONEBUTTONFUNCTION_VOLUMEUP

Increases the volume of audio through the phone's handset speaker or speakerphone.

PHONEBUTTONFUNCTION_VOLUMEDOWN

Decreases the volume of audio through the phone's handset speaker or speakerphone.

PHONEBUTTONFUNCTION_SPEAKERON

Turns the phone's external speaker on.

PHONEBUTTONFUNCTION_SPEAKEROFF

Turns the phone's external speaker off.

PHONEBUTTONFUNCTION_FLASH

Generates the equivalent of a on-hook/off-hook sequence. A flash typically indicates that any digits typed next are to be understood as commands to the switch. On many switches, places an active call on consultation hold.

PHONEBUTTONFUNCTION_DATAON

Indicates that the next call is a data call.

PHONEBUTTONFUNCTION_DATAOFF

Indicates that the next call is not a data call.

PHONEBUTTONFUNCTION_DONOTDISTURB

Places the phone in "do not disturb" mode; incoming calls receive a busy signal or are forwarded to an operator or voicemail system.

PHONEBUTTONFUNCTION_INTERCOM

Connect to the intercom to broadcast a page.

PHONEBUTTONFUNCTION_BRIDGEDAPP

Selects a particular appearance of a bridged address.

PHONEBUTTONFUNCTION_BUSY

Makes the phone appear "busy" to incoming calls.

PHONEBUTTONFUNCTION_CALLAPP

Selects a particular call appearance.

PHONEBUTTONFUNCTION_DATETIME

Causes the phone to display current date and time; this information would be sent by the switch.

PHONEBUTTONFUNCTION_DIRECTORY

Calls up directory service from the switch.

PHONEBUTTONFUNCTION_COVER

Forwards all calls destined for this phone to another phone used for coverage.

PHONEBUTTONFUNCTION_CALLID

Requests display of caller ID on the phone's display.

PHONEBUTTONFUNCTION_LASTNUM

Redials last number dialed.

PHONEBUTTONFUNCTION_NIGHTSRV

Places the phone in the mode it is configured for during night hours.

PHONEBUTTONFUNCTION_SENDCALLS

Sends all calls to another phone used for coverage; same as PHONEBUTTONFUNCTION_COVER.

PHONEBUTTONFUNCTION_MSGINDICATOR

Controls the message indicator lamp.

PHONEBUTTONFUNCTION_REPDIAL

Repertory dialing—the number to be dialed is provided as a shorthand following pressing of this button.

PHONEBUTTONFUNCTION_SETREPDIAL

Programs the shorthand-to-phone number mappings accessible by means of repertory dialing (the "REPDIAL" button).

PHONEBUTTONFUNCTION_SYSTEMSPEED

The number to be dialed is provided as a shorthand following pressing of this button. The mappings for system speed dialing are configured inside the switch.

PHONEBUTTONFUNCTION_STATIONSPEED

The number to be dialed is provided as a shorthand following pressing of this button. The mappings for station speed dialing are specific to this station (phone).

PHONEBUTTONFUNCTION_CAMPON

Camps-on an extension that returns a busy indication. When the remote station returns to idle, the phone will be rung with a distinctive patterns. Picking up the local phone re-initiates the call.

PHONEBUTTONFUNCTION_SAVEREPEAT

When pressed while a call or call attempt is active, it will remember that call's number or command. When pressed while no call is active (such as during dialtone), it repeats the most saved command.

PHONEBUTTONFUNCTION_QUEUECALL

Queues a call to an outside number after it encounters a trunk-busy indiction. When a trunk becomes later available, the phone will be rung with a distinctive pattern. Picking up the local phone re-initiates the call.

PHONEBUTTONFUNCTION_NONE

A "dummy" function assignment that indicates that the button does not have a function.

Values in the range 0x80000000 to 0xFFFFFFFF can be assigned for device-specific extensions; values in the range 0x00000000 to 0x7FFFFFFF are reserved.

The PHONEBUTTONFUNCTION_ constants have values commonly found on current telephone sets. These button functions can be used to invoke the corresponding function from the switch using lineDevSpecificFeature. Note that TAPI does not define the semantics of the button functions; it only provides access to the corresponding function. The behavior associated with each of the function values above is generic and may vary based on the telephony environment.


 PHONEBUTTONMODE_ Constants

[New - Windows 95]

The PHONEBUTTONMODE_ bit-flag constants describe the button classes.

PHONEBUTTONMODE_DUMMY

This value is used to describe a button/lamp position that has no corresponding button but has only a lamp.

PHONEBUTTONMODE_CALL

The button is assigned to a call appearance.

PHONEBUTTONMODE_FEATURE

The button is assigned to requesting features from the switch, such as hold, conference, and transfer.

PHONEBUTTONMODE_KEYPAD

The button is one of the twelve keypad buttons, '0' through '9', '*', and '#'.

PHONEBUTTONMODE_LOCAL

The button is a local function button, such as mute or volume control.

PHONEBUTTONMODE_DISPLAY

The button is a "soft" button associated with the phone's display. A phone set can have zero or more display buttons.

No extensibility. All 32 bits are reserved.

This enumeration type is used in the PHONECAPS data structure to describe the meaning associated with the phone's buttons.


 PHONEBUTTONSTATE_ Constants

[New - Windows 95]

The PHONEBUTTONSTATE_ bit-flag constants describe the button's positions.

PHONEBUTTONSTATE_UP

The button is in the "up" state.

PHONEBUTTONSTATE_DOWN

The button is in the "down" state (pressed down).

PHONEBUTTONSTATE_UNKNOWN

Indicates that the up or down state of the button is not known at this time, but may become known at a future time.

PHONEBUTTONSTATE_UNAVAIL

Indicates that the up or down state of the button is not known to the service provider, and will not become known at a future time.

No extensibility. All 32 bits are reserved.

For backward compatibility, it is the responsibility of the service provider to examine the negotiated API version on the phone, and to not use these PHONEBUTTONSTATE_ values if not supported on the negotiated version.


 PHONEERR_ Constants

[New - Windows 95]

This is the list of error codes that the implementation may return when invoking operations on phone devices. Consult the individual function descriptions to determine which of these error codes each function may return.

PHONEERR_ALLOCATED

The specified resource is already allocated.

PHONEERR_BADDEVICEID

The specified device ID is invalid or out of range.

PHONEERR_INCOMPATIBLEAPIVERSION

The application requested an API version or version range that cannot be supported by the Telephony API implementation and/or corresponding service provider.

PHONEERR_INCOMPATIBLEEXTVERSION

The application requested an extension version or version range that cannot supported by the service provider.

PHONEERR_INIFILECORRUPT

Because of internal inconsistencies or formatting problems in the file TELEPHON.INI, it cannot be read and understood properly by TAPI.

PHONEERR_INIFILECORRUPT

The TELEPHON.INI file was corrupted.

PHONEERR_INUSE

The device is currently in use. The device cannot be configured.

PHONEERR_INVALAPPHANDLE

The application's specified usage handle or registration handle is invalid.

PHONEERR_INVALAPPNAME

The specified application name is invalid. If an application name is specified by the application, it is assumed that the string does not contain any non-displayable characters and is NULL-terminated.

PHONEERR_INVALBUTTONLAMPID

The specified button/lamp ID is out of range or invalid.

PHONEERR_INVALBUTTONMODE

The button mode parameter is invalid.

PHONEERR_INVALBUTTONSTATE

The button states parameter is invalid.

PHONEERR_INVALDATAID

The specified data ID is invalid.

PHONEERR_INVALDEVICECLASS

The specified phone does not support the indicated device class.

PHONEERR_INVALHOOKSWITCHDEV

The hookswitch device parameter is invalid.

PHONEERR_INVALHOOKSWITCHMODE

The hookswitch mode parameter is invalid.

PHONEERR_INVALLAMPMODE

The specified lamp mode parameter is invalid.

PHONEERR_INVALPARAM

A parameter, such as a row or column value or a window handle, is invalid or out of range.

PHONEERR_INVALPHONEHANDLE

The specified device handle is invalid.

PHONEERR_INVALPHONESTATE

The phone device is not in a valid state for the requested operation.

PHONEERR_INVALPOINTER

One or more of the specified pointer parameters are invalid.

PHONEERR_INVALPRIVILEGE

The dwPrivilege parameter is invalid.

PHONEERR_INVALRINGMODE

The ring mode parameter is invalid.

PHONEERR_NODEVICE

The specified device ID, which was previously valid, is no longer accepted because the associated device has been removed from the system since TAPI was last initialized.

PHONEERR_NODRIVER

The telephone service provider for the specified device found that one of its components is missing or corrupt in a way that was not detected at initialization time. The user should be advised to use the Telephony Control Panel to correct the problem.

PHONEERR_NOMEM

Insufficient memory to complete the requested operation, or unable to allocate or lock memory.

PHONEERR_NOTOWNER

The application does not have owner privilege to the specified phone device.

PHONEERR_OPERATIONFAILED

The operation failed for an unspecified reason.

PHONEERR_OPERATIONUNAVAIL

The operation is not available.

PHONEERR_REINIT

If TAPI reinitialization has been requested, for example as a result of adding or removing a Telephony service provider, then phoneInitialize or phoneOpen requests are rejected with this error until the last application shuts down its usage of the API (using phoneShutdown), at which time the new configuration becomes effective and applications are once again permitted to call phoneInitialize

PHONEERR_RESOURCEUNAVAIL

The operation cannot be completed because of resource overcommitment.

PHONEERR_STRUCTURETOOSMALL

The specified phone caps structure is too small.

PHONEERR_UNINITIALIZED

The operation was invoked before any application called phoneInitialize.

The values 0xC0000000 through 0xFFFFFFFF are available for device-specific extensions; the values 0x80000000 through 0xBFFFFFFF are reserved; and 0x00000000 through 0x7FFFFFFF are used as request IDs.

If an application gets an error return that it does not specifically handle (such as an error defined by a device-specific extension), it should treat the error as a PHONEERR_OPERATIONFAILED (for an unspecified reason).


 PHONEHOOKSWITCHDEV_ Constants

[New - Windows 95]

The PHONEHOOKSWITCHDEV_ bit-flag constants describe various audio I/O devices each with its own hookswitch controllable from the computer.

PHONEHOOKSWITCHDEV_HANDSET

This is the ubiquitous, handheld, ear- and mouthpiece.

PHONEHOOKSWITCHDEV_SPEAKER

This is a built-in loudspeaker and microphone. This could also be an externally connected adjunct speaker to the telephone set.

PHONEHOOKSWITCHDEV_HEADSET

This is a headset connected to the phone set.

No extensibility. All 32 bits are reserved.

These constants are used in the PHONECAPS data structure to indicate the hookswitch device capabilities of a phone device. The PHONESTATUS structure reports the state of the phone's hookswitch devices. The function phoneSetHookSwitch and phoneGetHookSwitch use it as a parameter to select the phone's I/O device.


 PHONEHOOKSWITCHMODE_ Constants

[New - Windows 95]

The PHONEHOOKSWITCHMODE_ bit-flag constants describe the microphone and speaker components of a hookswitch device.

PHONEHOOKSWITCHMODE_ONHOOK

The device's microphone and speaker are both onhook.

PHONEHOOKSWITCHMODE_MIC

The devicer's microphone is active, the speaker is mute.

PHONEHOOKSWITCHMODE_SPEAKER

The device's speaker is active, the microphone is mute.

PHONEHOOKSWITCHMODE_MICSPEAKER

The device's microphone and speaker are both active.

PHONEHOOKSWITCHMODE_UNKNOWN

The device's hookswitch mode is currenly unknown.

No extensibility. All 32 bits are reserved.

These constants are used to provide individual level of control over the microphone and speaker components of a phone device.


 PHONELAMPMODE_ Constants

[New - Windows 95]

The PHONELAMPMODE_ bit-flag constants describe various ways in which a phone's lamp can be lit.

PHONELAMPMODE_DUMMY

This value is used to describe a button/lamp position that has no corresponding lamp.

PHONELAMPMODE_OFF

The lamp is off.

PHONELAMPMODE_STEADY

Steady means the lamp is continuously lit.

PHONELAMPMODE_WINK

Wink means normal rate on and off.

PHONELAMPMODE_FLASH

Flash means slow on and off.

PHONELAMPMODE_FLUTTER

Flutter means fast on and off.

PHONELAMPMODE_BROKENFLUTTER

Broken flutter is the superposition of flash and flutter.

PHONELAMPMODE_UNKNOWN

The lamp mode is currently unknown.

The high-order 16 bits can be assigned for device-specific extensions. The low-order 16 bits are reserved.

Where the exact on and off cadences may differ across phone sets from different vendors, mapping of actual lamp lighting patterns for most phones onto the values listed above should be straightforward.


 PHONEPRIVILEGE_ Constants

[New - Windows 95]

The PHONEPRIVILEGE_ bit-flag constants describe the various ways in which a phone device can be opened.

PHONEPRIVILEGE_MONITOR

An application that opens a phone device with the monitor privilege is informed about events and state changes occurring on the phone. The application cannot invoke any operations on the phone device that would change its state, so only status operations can be invoked. Multiple applications can monitor a phone device at any given time.

PHONEPRIVILEGE_OWNER

An application that opens a phone device with the owner privilege is allowed to change the state of the lamps, ringer, display, hookswitch, and data blocks of the phone. Opening a phone device in owner mode also provides monitoring of the phone device. Only one application is allowed to be the owner of a phone device at any given time.

No extensibility. All 32 bits are reserved.


 PHONESTATE_ Constants

[New - Windows 95]

The PHONESTATE_ bit-flag constants describe various status items for a phone device.

PHONESTATE_OTHER

Phone-status items other than those listed below have changed. The application should check the current phone status to determine which items have changed.

PHONESTATE_CONNECTED

The connection between the phone device and TAPI was just made. This happens when TAPI is first invoked or when the wire connecting the phone to the PC is plugged in with TAPI active.

PHONESTATE_DISCONNECTED

The connection between the phone device and TAPI was just broken. This happens when the wire connecting the phone set to the PC is unplugged while TAPI is active.

PHONESTATE_OWNER

The number of owners for the phone device.

PHONESTATE_MONITORS

The number of monitors for the phone device.

PHONESTATE_DISPLAY

The display of the phone has changed.

PHONESTATE_LAMP

A lamp of the phone has changed.

PHONESTATE_RINGMODE

The ring mode of the phone has changed.

PHONESTATE_RINGVOLUME

The ring volume of the phone has changed.

PHONESTATE_HANDSETHOOKSWITCH

The handset hookswitch state has changed.

PHONESTATE_HANDSETVOLUME

The handset's speaker volume setting has changed.

PHONESTATE_HANDSETGAIN

The handset's microphone gain setting has changed.

PHONESTATE_SPEAKERHOOKSWITCH

The speakerphone's hookswitch state has changed.

PHONESTATE_SPEAKERVOLUME

The speakerphone's speaker volume setting has changed.

PHONESTATE_SPEAKERGAIN

The speakerphone's microphone gain setting state has changed.

PHONESTATE_HEADSETHOOKSWITCH

The headset's hookswitch state has changed.

PHONESTATE_HEADSETVOLUME

The headset's speaker volume setting has changed.

PHONESTATE_HEADSETGAIN

The headset's microphone gain setting has changed.

PHONESTATE_SUSPEND

The application's use of the phone is temporarily suspended.

PHONESTATE_RESUME

The application's use of the phone device is resumed after having been suspended for some time.

PHONESTATE_DEVSPECIFIC

The phone's device-specific information has changed.

PHONESTATE_REINIT

Items have changed in the configuration of phone devices. To become aware of these changes (as for the appearance of new phone devices), the application should reinitialize its use of TAPI.

PHONESTATE_CAPSCHANGE

Indicates that, due to configuration changes made by the user or other circumstances, one or more of the fields in the PHONECAPS structure have changed. The application should use phoneGetDevCaps to read the updated structure. If a service provider sends a PHONE_STATE message containing this value to TAPI, TAPI will pass it along to applications which have negotiated this or a subsequent API version; applications negotiating a previous API version will receive PHONE_STATE messages specifying PHONESTATE_REINIT, requiring them to shutdown and reinitialize their connection to TAPI in order to obtain the updated information.

PHONESTATE_REMOVED

Indicates that the device is being removed from the system by the service provider (most likely through user action, via a control panel or similar utility). A PHONE_STATE message with this value will normally be immediately followed by a PHONE_CLOSE message on the device. Subsequent attempts to access the device prior to TAPI being reinitialized will result in PHONEERR_NODEVICE being returned to the application. If a service provider sends a PHONE_STATE message containing this value to TAPI, TAPI will pass it along to applications which have negotiated this or a subsequent API version; applications negotiating a previous API version will not receive any notification.

No extensibility. All 32 bits are reserved.


 PHONESTATUSFLAGS_ Constants

[New - Windows 95]

The PHONESTATUSFLAGS_ bit-flag constants describe a variety of phone device status information.

PHONESTATUSFLAGS_CONNECTED

Specifies whether the phone is currently connected to TAPI. TRUE if connected, FALSE otherwise.

PHONESTATUSFLAGS_SUSPENDED

Specifies whether TAPI's manipulation of the phone device is suspended. TRUE if suspended, FALSE otherwise. An application's use of a phone device may be temporarily suspended when the switch wants to manipulate the phone in a way that cannot tolerate interference from the application.

No extensibility. All 32 bits are reserved.


 STRINGFORMAT_ Constants

[New - Windows 95]

The STRINGFORMAT_ enumeration constants describe different string formats.

STRINGFORMAT_ASCII

Specifies standard ASCII character format using one byte per character.

STRINGFORMAT_DBCS

Specifies standard DBCS character format using two bytes per character.

STRINGFORMAT_UNICODE

Specifies standard Unicode character format using two bytes per character.

STRINGFORMAT_BINARY

This is an array of unsigned characters; could be used for numeric values.

No extensibility. All 32 bits are reserved.


 Device Classes

About Device Classes

A device class is a group of related physical devices or device drivers through which applications send and receive the information or data that makes up a call. Every device class has a device class name that uniquely identifies the class and provides information about the programming interface and commands that can be used to open and communicate with the devices in the class.

The telephony application programming interface (TAPI) associates devices from one or more device classes to each line or phone device. You access one of these devices by retrieving the device identifier for the device using the lineGetID or phoneGetID function. You supply the device class name, and the function returns the specific port name, device name, device handle, or device identifier that you need to open and access the device. The format of the information returned depends on the device class and is described in subsequent sections of this chapter.

Note  The device identifier definitions apply to 16-bit and 32-bit TAPI. In some cases, the data type of a media handle in the device identifier definition may be different than that specified by the Microsoft® Windows® version 3.x or Microsoft® Win32® application programming interface (API). For example, Windows 3.x and Win32 define wave device identifiers with the UINT type, but TAPI defines this device identifier with the DWORD type. In such cases, you should cast the media handle to the appropriate data type when using it with the Windows version 3.x or Win32 API.

You also use device class names with the lineConfigDialog and phoneConfigDialog functions to enable the user to set configuration options for the given device, with the lineGetIcon and phoneGetIcon functions to retrieve an icon to represent the given device, and with the lineGetDevConfig and lineSetDevConfig functions to directly retrieve and set configuration options for the given device.

By default, there are the following device class names.

comm	Communications port.
comm/datamodem	Modem through a communications port.
wave/in	Wave audio device (input only).
wave/out	Wave audio device (output only).
midi/in	Midi sequencer (input only).
midi/out	Midi sequencer (output only).
tapi/line	Line device.
tapi/phone	Phone device.
ndis	Network device.
tapi/terminal	Terminal device.
These names are not case sensitive, so you can use any combination of uppercase and lowercase letters.

Additional device classes and device class names may be available on a given system. In general, if a device does not belong to one of the default device classes, the manufacturer typically defines a new device class and assigns a unique device class name. You need to check the documentation for the device to determine what additional device classes are available for it. Note, however, that although the device class and media mode are related, they are not the same. A media mode describes a format of information on a call, and a device class defines the programming interface used to manage that information. So, even if a manufacturer defines a new media mode, it is not necessarily true that the manufacturer also needs to define a new device class to support the mode.

The format of the configuration data used with the lineSetDevConfig and lineGetDevConfig functions also depends on the device class. In general, you use lineGetDevConfig to save a copy of the current device configuration data and then later use lineSetDevConfig with the saved configuration data to restore the device configuration to the previous state. This is a convenient way to temporarily change the configuration without requiring the user to manually restore it to the previous state. Because the exact format of the device configuration data may be different with each service provider, you should not use lineSetDevConfig and lineGetDevConfig to manipulate the device configuration data directly. Some formats are provided for information only.


 comm

The comm device class consists of communications ports. You access these devices by using the Win32 file and communications functions.

The lineGetID and phoneGetID functions fill a VARSTRING structure, setting the dwStringFormat member to the STRINGFORMAT_ASCII value and appending a null-terminated string that specifies the name of the communication port (such as COM1). You use this port name in a call to the CreateFile function to open the communication device for the line or phone.


 comm/datamodem

The comm/datamodem device class consists of modem devices. You access these devices by using the Win32 file and communications functions. Devices in this class are associated with line devices that support the LINEMEDIAMODE_DATAMODEM media mode, which is specified in the dwMediaModes member of the LINEDEVCAPS structure for the line device.

The lineGetID and phoneGetID functions fill a VARSTRING structure, setting dwStringFormat to the STRINGFORMAT_BINARY value and appending these additional members.

HANDLE hComm;            // handle of open comm. device
CHAR   szDeviceName[1];  // name of comm. device

The hComm member is the handle of the open communications port. This member is NULL if the port is not yet open or if the dwSelect parameter of lineGetID is not the LINECALLSELECT_CALL value. If a call is active, the service provider typically opens the port itself to get direct control of the communications hardware, but is only required to return a valid handle if the line is connected. The service provider opens the port using the FILE_FLAG_OVERLAPPED value and then configures the port using the settings specified by the lineSetDevConfig function. You can set additional configuration options for the device by using Win32 functions with the returned handle.

The szDeviceName member is a null-terminated ASCII string that specifies the name of the communications port associated with the line, address, or call.

If hComm is a valid handle, you can use it in subsequent calls to Win32 file functions, such as ReadFile and WriteFile, to send and receive data on the call. When you are finished using the communications port and preferably before you use the lineDeallocateCall function to deallocate the call, you must close the port by using the CloseHandle function.

When using the lineGetDevConfig and lineSetDevConfig functions, some service providers require that the configuration data for this device class have the following format.

typedef struct  tagDEVCFG  {
  DEVCFGHDR   dfgHdr;
  COMMCONFIG  commconfig;
} DEVCFG, *PDEVCFG, FAR* LPDEVCFG;

// Device setting information
typedef struct  tagDEVCFGDR  {
  DWORD       dwSize;
  DWORD       dwVersion;
  WORD        fwOptions;
  WORD        wWaitBong;
} DEVCFGHDR;

Contains device configuration information for use with the lineGetDevConfig and lineSetDevConfig functions.

dwSize

Sum of the size of the DEVCFGHDR structure and the actual size of COMMCONFIG structure.

dwVersion

Version number of the Unimodem DevConfig structure. This member can be MDMCFG_VERSION (0x00010003).

fwOptions

Option flags that appear on the Unimodem Option page. This member can be a combination of these values:

TERMINAL_PRE (1)	Displays the preterminal screen.
TERMINAL_POST (2)	Displays the post terminal screen.
MANUAL_DIAL (4)	Dials the phone manually, if capable of doing so.
LAUNCH_LIGHTS (8)	Displays the modem tray icon.
Only the LAUNCH_LIGHTS value is set by default.

wWaitBong

Number of seconds (in two seconds granularity) to replace the wait for credit tone ($).

commconfig

COMMCONFIG structure that can be used with the Win32 communications and MCX functions.


 wave/in

The wave/in device class consists of audio devices for low-level wave audio input. You access these devices by using the wave functions, which are described in the Microsoft Win32 Software Development Kit (SDK). Devices in this class are associated with line devices that support the LINEMEDIAMODE_AUTOMATEDVOICE media modem which is specified in the dwMediaModes member of the LINEDEVCAPS structure for the line device.

The lineGetID and phoneGetID functions fill a VARSTRING structure, setting the dwStringFormat member to the STRINGFORMAT_BINARY value and appending this additional member.

DWORD DeviceId;  // identifier of audio device

The DeviceId member is the identifier of a closed audio device. You use this identifier in a call to the waveInOpen function to open the device for input. You can use the resulting device handle to record digitized audio data from the line or phone device.

Although a "wave" device class also exists for low-level wave audio devices, you should always use the wave/in device class for low-level wave input.


 wave/out

The wave/out device class consists of audio devices for low-level wave audio output. You access these devices by using the wave functions, which are described in the Win32 SDK. Devices in this class are associated with line devices that support the LINEMEDIAMODE_AUTOMATEDVOICE media mode, which is specified in the dwMediaModes member of the LINEDEVCAPS structure for the line device.

The lineGetID and phoneGetID functions fill a VARSTRING structure, setting the dwStringFormat member to the STRINGFORMAT_BINARY value and appending this additional member.

DWORD DeviceId;  // identifier of audio device

The DeviceId member is the identifier of a closed audio device. You use this identifier in a call to the waveOutOpen function to open the device for output. You can use the resulting device handle to play digitized audio data at the line or phone device.

Although a "wave" device class also exists for low-level wave audio devices, you should always use the wave/out device class for low-level wave output.


 midi/in

The midi/in device class consists of MIDI sequencers that are used for input. You access these devices by using the MIDI functions, which are described in the Win32 SDK.

The lineGetID and phoneGetID functions fill a VARSTRING structure, setting the dwStringFormat member to the STRINGFORMAT_BINARY value and appending this additional member.

DWORD DeviceId;  // identifier of MIDI device

The DeviceId member is the identifier of a closed MIDI device. You use this identifier in a call to the midiInOpen function to open the device for input. You can use the resulting device handle to record MIDI data from the line or phone device.


 midi/out

The midi/out device class consists of MIDI sequencers that are used for output. You access these devices by using the MIDI functions, which are described in the Win32 SDK.

The lineGetID and phoneGetID functions fill a VARSTRING structure, setting the dwStringFormat member to the STRINGFORMAT_BINARY value and appending this additional member.

DWORD DeviceId;  // identifier of MIDI device

The DeviceId member is the identifier of a closed MIDI device. You use this identifier in a call to the midiOutOpen function to open the device for output. You can use the resulting device handle to play MIDI data at the line or phone device.


 tapi/line

The tapi/line device class consists of all line devices. You access these devices using the TAPI line functions.

The lineGetID function fills a VARSTRING structure, setting the dwStringFormat member to the STRINGFORMAT_BINARY value and appending this additional member.

DWORD dwDeviceI;  // line device identifier

The dwDeviceId member is the identifier of the line device associated with the line handle given by lineGetID.

The phoneGetID function also fills a VARSTRING structure, setting dwStringFormat to STRINGFORMAT_BINARY and appending this additional member.

DWORD adwDeviceIds[];  // array of line device identifiers

The adwDeviceIds member is an array containing the device identifiers of all line devices that are associated with the phone device. If there are no associated line devices, phoneGetID returns the PHONEERR_INVALDEVICECLASS value.


 tapi/phone

The tapi/phone device class consists of all phone devices. You access these devices by using the TAPI phone functions.

The phoneGetID function fills a VARSTRING structure, setting the dwStringFormat member to the STRINGFORMAT_BINARY value and appending this additional member.

DWORD dwDeviceI;  // phone device identifier

The dwDeviceId member is the identifier of the phone device associated with the phone handle given by phoneGetID.

The lineGetID function also fills a VARSTRING structure, setting dwStringFormat to STRINGFORMAT_BINARY and appending this additional member.

DWORD adwDeviceIds[];  // array of phone device identifiers

The adwDeviceIds member is an array containing the device identifiers of all phone devices that are associated with the given line device. If there are no associated phone devices, lineGetID returns the LINEERR_INVALDEVICECLASS value.


 ndis

The ndis device class consists of devices that can be associated with network driver interface specification (NDIS) media access control (MAC) drivers to support network communications. You access these devices by using functions.

The lineGetID and phoneGetID functions fill a VARSTRING structure, setting the dwStringFormat member to the STRINGFORMAT_BINARY value and appending these additional members.

HANDLE  hDevice;          // NDIS connection identifier
CHAR    szDeviceType[1];  // name of device

The hDevice member is the identifier to pass to a MAC, such as the asynchronous MAC for dial-up networking, to associate a network connection with the call/modem connection. The szDeviceType member is a null-terminated ASCII string specifying the name of the device associated with the identifier. For more information, see documentation about writing NDIS MAC drivers for use with dial-up networking.


 tapi/terminal

The tapi/terminal device class consists of the phone devices associated with each terminal on a line or the terminal on each line associated with a phone device. You access these devices by using the TAPI line or phone functions.

The lineGetID function fills a VARSTRING structure, setting the dwStringFormat member to the STRINGFORMAT_BINARY value and appending this additional member.

DWORD adwDeviceId[];  // array of phone device identifiers

The adwDeviceId member is an array of phone device identifiers. There is one array element for each terminal specified by the dwNumTerminals member in the LINEDEVCAPS structure for the given line device. Each element specifies the identifier of the phone device associated with the corresponding terminal on the line. If there is no phone device associated with a terminal, the element is set to  − 1 (0xFFFFFFFF).

The phoneGetID function fills a VARSTRING structure, setting the dwStringFormat member to the STRINGFORMAT_BINARY value and appending this additional member.

DWORD adwTerminalID[];  // array of terminal identifiers

The adwTerminalID member is an array of terminal identifiers. There is one array element for each line device identifier specified by the lineInitialize function. Each array element contains the terminal identifier associated with the phone device for the given line device. If there is no phone device, the element is set to  − 1 (0xFFFFFFFF). The terminal identifiers range in value from zero to one less than the number specified by the dwNumTerminals member in the LINEDEVCAPS structure.


 Quick Function Reference

Assisted Telephony

The assisted telephony functions are:

tapiRequestMakeCall	Submits a request to place a voice call.
tapiRequestMediaCall	Obsolete. Do not use.
tapiRequestDrop	Obsolete. Do not use.
tapiGetLocationInfo	Returns country code and city/area code information.
These functions do not return until after making a call to the application's reply callback function and therefore are considered synchronous.


 Basic Telephony Services

The Basic Telephony functions are listed below by category. A function is identified as "asynchronous" if it might return before making a call to the application's reply callback function. Otherwise, the function is considered synchronous.

TAPI Initialization and Shutdown

lineInitialize	Initializes the Telephony API line abstraction for use by the invoking application. Synchronous.
lineShutdown	Shuts down the application's use of the line Telephony API. Synchronous.
Line Version Negotiation

lineNegotiateAPIVersion	Allows an application to negotiate an API version to use. Synchronous.
Line Status and Capabilities

lineGetDevCaps	Returns the capabilities of a given line device. Synchronous.
lineGetDevConfig	Returns configration of a a media stream device. Synchronous.
lineGetLineDevStatus	Returns current status of the specified open line device. Synchronous.
lineSetDevConfig	Sets the configuration of the specified media stream device. Synchronous.
lineSetStatusMessages	Specifies the status changes for which the application wants to be notified. Synchronous.
lineGetStatusMessages	Return the application's current line and address status message settings. Synchronous.
lineGetID	Retrieves a device ID associated with the specified open line, address, or call. Synchronous.
lineGetIcon	Allows an application to retrieve an icon for display to the user.  Synchronous.
lineConfigDialog	Causes the provider of the specified line device to display a dialog that allows the user to configure parameters related to the line device.  Synchronous.
Addresses

lineGetAddressCaps	Returns the telephony capabilities of an address. Synchronous.
lineGetAddressStatus	Returns current status of a specified address. Synchronous.
lineGetAddressID	Retrieves the address ID of an address specified using an alternate format. Synchronous.
Opening and Closing Line Devices

lineOpen	Opens a specified line device for providing subsequent monitoring and/or control of the line. Synchronous.
lineClose	Closes a specified opened line device. Synchronous.
Address Formats

lineTranslateAddress	Translates between an address in canonical format and an address in dialable format.  Synchronous.
lineSetCurrentLocation	Sets the location used as the context for address translation.  Synchronous.
lineSetTollList	Manipulates the toll list. Synchronous.
lineGetTranslateCaps	Returns address translation capabilities.  Synchronous.
Call States and Events

lineGetCallInfo	Returns mostly constant information about a call. Synchronous.
lineGetCallStatus	Returns complete call status information for the specified call. Synchronous.
lineSetAppSpecific	Sets the application-specific field of a call's information structure. Synchronous.
Request Recipient Services

These functions are used only in support of assisted telephony.

lineRegisterRequestRecipient	Registers or deregisters the application as a request recipient for the specified request mode. Synchronous.
lineGetRequest	Gets the next request from the Telephony DLL.  Synchronous.
Making Calls

lineMakeCall	Makes an outbound call and returns a call handle for it. Asynchronous.
lineDial	Dials (parts of one or more) dialable addresses. Asynchronous.
Answering Inbound Calls

lineAnswer	Answers an inbound call. Asynchronous.
Toll Saver Support

lineSetNumRings	Indicates the number of rings after which inbound calls are to be answered. Synchronous.
lineGetNumRings	This function returns the minimum number of rings requested with lineSetNumRings. Synchronous.
Call Privilege Control

lineSetCallPrivilege	Sets the application's privilege to the privilege specified.  Synchronous.
Call Drop

lineDrop	Disconnects a call, or abandons a call attempt in progress. Asynchronous.
lineDeallocateCall	Deallocates the specified call handle. Synchronous.
Call Handle Manipulation

lineHandoff	Hands off call ownership and/or changes an application's privileges to a call. Synchronous.
lineGetNewCalls	Returns call handles to calls on a specified line or address for which the application does not yet have handles.  Synchronous.
lineGetConfRelatedCalls	Returns a list of call handles that are part of the same conference call as the call specified as a parameter. Synchronous.


 Supplementary Telephony Services

The supplementary telephony functions are listed below by category. Line services are listed first, phone services next. A function is identified as "asynchronous" if it might return before making a call to the application's reply callback function. Otherwise, the function is considered synchronous.


 Line Services

Bearer Mode and Rate

lineSetCallParams	Requests a change in the call parameters of an existing call. Synchronous.
Media Monitoring

lineMonitorMedia	Enables or disables media mode notification on a specified call. Synchronous.
Digit Monitoring and Gathering

lineMonitorDigits	Enables or disables digit detection notification on a specified call. Synchronous.
lineGatherDigits	Performs the buffered gathering of digits on a call. Synchronous.
Tone Monitoring

lineMonitorTones	Specifies which tones to detect on a specified call. Synchronous.
Media Control

lineSetMediaControl	Sets up a call's media stream for media control. Synchronous.
lineSetMediaMode	Sets the media mode(s) of the specified call in its LINECALLINFO structure.  Synchronous.
Generating Inband Digits and Tones

lineGenerateDigits	Generates inband digits on a call. Synchronous.
lineGenerateTone	Generates a given set of tones inband on a call. Synchronous.
Call Accept and Redirect

lineAccept	Accepts an offered call and start alerting both caller (ringback) and called party (ring). Asynchronous.
lineRedirect	Redirects an offering call to another address. Asynchronous.
Call Reject

lineDrop	See table for Basic Telephony. Asynchronous.
Call Hold

lineHold	Places the specified call on hard hold. Asynchronous.
lineUnhold	Retrieves a held call. Asynchronous.
Making Calls

lineSecureCall	Secures an existing call from interference by other events such as call-waiting beeps on data connections. Asynchronous.
Call Transfer

lineSetupTransfer	Prepares a specified call for transfer to another address. Asynchronous.
lineCompleteTransfer	Transfers a call that was set up for transfer to another  call, or enter a three-way conference. Asynchronous.
lineBlindTransfer	Transfers a call to another party. Asynchronous.
lineSwapHold	Swaps the active call with the call currently on consultation hold. Asynchronous.
Call Conference

lineSetupConference	Prepares a given call for the addition of another party. Asynchronous.
linePrepareAddToConference	Prepares to add a party to an existing conference call by allocating a consultation call that can later be added to the conference call that is placed on conference hold. Asynchronous.
lineAddToConference	Adds a consultation call to an existing conference call. Asynchronous.
lineRemoveFromConference	Removes a party from a conference call. Asynchronous.
Call Park

linePark	Parks a given call at another address. Asynchronous.
lineUnpark	Retrieves a parked call. Asynchronous.
Call Forwarding

lineForward	Sets or cancels call forwarding requests. Asynchronous.
Call Pickup

linePickup	Picks up a call that is alerting at another number. Picks up a call alerting at another destination address and returns a call handle for the picked up call (linePickup can also be used for call waiting). Asynchronous.
Sending Information to Remote Party

lineSendUserUserInfo	Sends user-to-user information to the remote party on the specified call. Asynchronous.
Call Completion

lineCompleteCall	Places a call completion request. Asynchronous.
lineUncompleteCall	Cancels a call completion request. Asynchronous.
Setting a Terminal for Phone Conversations

lineSetTerminal	Specifies the terminal device to which the specified line, address events or call media stream events are routed. Asynchronous.


 Phone Services

TAPI Initialization and Shutdown

phoneInitialize	Initializes the Telephony API phone abstraction for use by the invoking application. Synchronous.
phoneShutdown	Shuts down the application's use of the phone Telephony API. Synchronous.
Phone Version Negotiation

phoneNegotiateAPIVersion	Allows an application to negotiate an API version to use. Synchronous.
Opening and Closing Phone Devices

phoneOpen	Opens the specified phone device, giving the application either owner or monitor privileges. Synchronous.
phoneClose	Closes a specified open phone device. Synchronous.
Phone Status and Capabilities

phoneGetDevCaps	Returns the capabilities of a given phone device. Synchronous.
phoneGetID	Returns a device ID for the given device class associated with the specified phone device. Synchronous.
phoneGetIcon	Allows an application to retrieve an icon for display to the user. Synchronous.
phoneConfigDialog	Causes the provider of the specified phone device to display a dialog that allows the user to configure parameters related to the phone device. Synchronous.
Hookswitch Devices

phoneSetHookSwitch	Sets the hookswitch mode of one or more of the hookswitch devices of an open phone device. Asynchronous.
phoneGetHookSwitch	Queries the hookswitch mode of a hookswitch device of an open phone device. Synchronous.
phoneSetVolume	Sets the volume of a hookswitch device's speaker of an open phone device. Asynchronous.
phoneGetVolume	Returns the volume setting of a hookswitch device's speaker of an open phone device. Synchronous.
phoneSetGain	Sets the gain of a hookswitch device's mic of an open phone device. Asynchronous.
phoneGetGain	Returns the gain setting of a hookswitch device's mic of an opened phone. Synchronous.
Display

phoneSetDisplay	Writes information to the display of an open phone device. Asynchronous.
phoneGetDisplay	Returns the current contents of a phone's display. Synchronous.
Ring

phoneSetRing	Rings an open phone device according to a given ring mode. Asynchronous.
phoneGetRing	Returns the current ring mode of an opened phone device. Synchronous.
Buttons

phoneSetButtonInfo	Sets the information associated with a button on a phone device. Asynchronous.
phoneGetButtonInfo	Returns information associated with a button on a phone device. Synchronous.
Lamps

phoneSetLamp	Lights a lamp on a specified open phone device in a given lamp lighting mode. Asynchronous.
phoneGetLamp	Returns the current lamp mode of the specified lamp. Synchronous.
Data Areas

phoneSetData	Downloads a buffer of data to a given data area in the phone device. Asynchronous.
phoneGetData	Uploads the contents of a given data area in the phone device to a buffer. Synchronous.
Status

phoneSetStatusMessages	Specifies the status changes for which the application wants to be notified. Synchronous.
phoneGetStatusMessages	Returns the status changes for which the application wants to be notified. Synchronous.
phoneGetStatus	Returns the complete status of an open phone device. Synchronous.


 Extended Telephony Services

The extended telephony functions for both line and phone devices are listed below by category.

Extended Line Services

lineNegotiateExtVersion	Allows an application to negotiate an extension version to use with the specified line device. Asynchronous.
lineDevSpecific	Device-specific escape function. Synchronous.
lineDevSpecificFeature	Device-specific escape function to allow sending switch features to the switch. Asynchronous.
Extended Phone Services

phoneDevSpecific	Device-specific escape function to allow vendor dependent extensions. Asynchronous.
phoneNegotiateExtVersion	Allows an application to negotiate an extension version to use with the specified phone device. Synchronous.


 Telephony Configuration Parameters

About Telephony Coniguration Parameters

Note  The TELEPHON.INI file is used for backward compatibility with existing 16-bit Telephony applications. Win32-based applications should never attempt to access this file directly. Instead use functions such as lineGetAppPriority and lineSetAppPriority to get and set configuration information.

This appendix specifies the configuration parameters associated with Windows Telephony. These parameters are manipulated by Control Panel applets, Telephony service providers, and Telephony applications. Much of the configuration information related to TAPI, such as the default priorities users wish to assign to applications () , is stored in the TELEPHON.INI file. A small amount of information is stored in the file WIN.INI. Priorities are used to determine which of two or more applications capable of accepting an incoming call of a given media mode (such as "datamodem") actually receives the call. Telephony applications should offer a Preferences option that, according to the application design, can let users reset the current application's priority. These settings remain constant in TELEPHON.INI until changed by a later edit.

Note  The only section of TELEPHON.INI that is of interest to application programmers is the [HandoffPriorities] section. All other sections of TELEPHON.INI are to be modified only by service providers or Telephony Control Panel applets, and should not be modified in any way by Telephony applications.

In the TELEPHON.INI file, filenames that are either longer than the standard 8.3 filename format or use characters that are not valid in the 8.3 format must be enclosed in double quotation marks. Any filename without quotes is assumed to be a standard 8.3 filename.


 WIN.INI

Most Windows Telephony parameters are stored in TELEPHON.INI. The entry in WIN.INI is to inform Telephony service providers and applications of the last date and time that TELEPHON.INI was changed, and so the WM_WININICHANGE messages can be issued to inform active applications and drivers of changes. The section consists of a single entry.

[Windows Telephony]
TelephonINIChanged=yyyy-mm-dd hh:mm:ss

For example,

TelephonINIChanged=1993-06-03 16:48:56

would indicate that TELEPHON.INI was last updated on June 3, 1993, at 4:48:56 p.m.

This document is the specification for the configuration parameters associated with Windows Telephony. These parameters are manipulated by Control Panel applets, Telephony service providers, and Telephony applications.


 Providers

The "[Providers]" section of TELEPHON.INI specifies the permanent provider IDs and filenames of installed Telephony service providers. This information is used so that TAPI can identify and load each provider.

This section uses the following format:

[Providers]
NumProviders=<count>
NextProviderID=<nextPPID>
ProviderID<index>=<PPID>
ProviderFilename<index>=<filename>

For example:

[Providers]
NumProviders=2
NextProviderID=5
ProviderID0=3
ProviderFilename0=UNIMODEM.TSP
ProviderID1=4
ProviderFilename1=PDI-1000.TSP

The NumProviders entry indicates how many service providers are installed (and how many ProviderID<index> and ProviderFilename<index> entries appear in the section). The NextProviderID entry indicates the Permanent Provider ID (<nextPPID>) that will be assigned to the next provider to be installed. Both parameters are set to 0 when Telephony is installed; the values are subsequently controlled by any software that installs or removes service providers, such as the Windows Telephony Control Panel.

The ProviderID<index> entry (one per provider) assigns a permanent <PPID> to a Telephony service provider; this ID is used to link parameters in other sections and files to the provider information. These entries are created by any software that installs or removes service providers, such as the Windows Telephony Control Panel.

The ProviderFilename<index> (one per provider) identifies the filename (in \WINDOWS\SYSTEM) of the service provider DLL. These entries are created by any software that installs or removes service providers, such as the Telephony Control Panel.

In both the ProviderID<index> and ProviderFilename<index> entries, <index> takes values from 0 to one less than <count> (as specified in NumProviders). These entries are renumbered as providers are deleted, but the permanent provider IDs are not changed.


 Provider-Specific Sections

For each telephony service provider defined in the [Providers] section, there must be a [Provider<PPID>] section. The <PPID> value is the Permanent Provider ID defined for that service provider in the corresponding ProviderID<index>=<PPID> entry in the [Providers] section. For example, corresponding to an entry such as "ProviderID2=278" there would be a section named "[Provider278]".

It is the responsibility of the service provider to create its provider-specific section in TELEPHON.INI at the time the TSPI_providerInstall function is called. It is also the responsibility of the provider to delete its provider-specific section in TELEPHON.INI at the time the TSPI_providerRemove function is called. The provider may update the information in the section whenever TSPI_providerConfig, TSPI_lineConfigDialog, or TSPI_phoneConfigDialog is called, or at other times when appropriate. Only the service provider writes entries in its provider-specific section; neither TAPI nor any other Windows Telephony component writes any entries to provider-specific section. TAPI reads only two entries in the provider-specific section—NumLines and NumPhones (defined below)—and all other entries in the section are the responsibility of the provider.

Every provider-specific section in TELEPHON.INI specifies, at a minimum, the number of lines and phones supported (or currently configured, for providers which support multiple devices) by that provider. This section consists, at a minimum, of the following:

[Provider<PPID>]
NumLines=<count>
NumPhones=<count>

For example:

[Provider3]
NumLines=1
NumPhones=0

The service provider may include any other entries in its section which are necessary to fulfill the responsibilities of the provider as specified in the Windows Telephony Service Provider Interface Specification, or for other private configuration purposes. In particular, it is the responsibility of the service provider to provide unique device IDs for every line and phone device, which are valid over a long span of time.

The 32-bit permanent device IDs which appear on the Telephony API and SPI (as with the LINEDEVCAPS and PHONECAPS structures) are made up of a combination of the permanent provider ID (high word, range 0 to 32767) and the permanent device ID (low word, range of 0 to 32767). If the provider supports multiple line or phone devices, it must provide a way to maintain unique IDs. One mechanism to accomplish this would be to define the following entries in the provider section:

NextLineID=<PLID>
NextPhoneID=<PFID>
LineID<index>=<PLID>
PhoneID<index>=<PFID>

If no Phone devices are supported by the provider, then only the "Line" entries need be included, and vice-versa (however, NumLines and NumPhones must always be included). NextLineID and NextPhoneID would be used (like NextProviderID) to indicate the next permanent ID to be used (in an increasing fashion to minimize reusing of ID values).

The LineID<index> and PhoneID<index> entries provide convenient, permanent "partial ID" tags that are independent of the permanent Provider ID assigned. If this scheme of partial ID tags is used, it is suggested that other device-specific parameters (such as the "friendly name" of a device) be linked on the basis of the permanent ID tag; this way, it is not necessary to renumber those other parameters if a line or phone is deleted. For example, if the third line device on a provider has permament line ID 257, and has a couple of additional parameters, they could be stored in TELEPHON.INI as follows:

LineID3=257
LineName257="Microsoft ATSP"
LinePortDevice257="COM4"
LineInitString257="ATM2L0X0"

Of course, this tagging of additional parameters is not necessary if the provider supports one, and only one, device. In that case, only the NumLines and NumPhones entries need be included; other parameters can have arbitrary, non-indexed names. Also, providers may choose to use an entirely different mechanism for assigning permanent device IDs as long as the requirements that the IDs be unique and contain the permanent provider ID in their high-order word are obeyed.


 Handoff Priorities

The "[HandoffPriorities]" section of TELEPHON.INI specifies the priority of applications to handle incoming calls and call handoffs of particular media types and for Assisted Telephony requests. It should be modified only by the writer of the telephonic application.

When a call is initially received or handed off, TAPI checks the applications that have the line open to determine which of them expressed interest in calls of the current media mode (specified by the provider or application handing off the call). If more than one application has the line open and is interested in calls of the current media mode, TAPI checks the priorities specified in this section to determine which application will get the call. For each media type, applications are listed in the "[HandoffPriorities]" section of TELEPHON.INI in order of preference (earlier ones in the list are preferred over later ones). In other words, TAPI attempts first to choose as the target of the handoff the first listed application that has the line open for that media type.

Applications can also be targets of handoffs without being listed. Among unlisted applications, the order of preference is arbitrary, but listed applications are preferred to unlisted applications. There is no direct association between the media modes for which applications are registered and particular media stream APIs; it is up to the application to know which API is used to access a particular media stream.

Likewise, when a Assisted Telephony request is received, TAPI checks the applications that have registered to process that type of request. If more than one application has has registered for that type of request, TAPI checks the priorities specified in this section to determine which application will be signalled to process the request (with the highest priority being assigned to the first listed application under that request type, and proceeding in the order listed). If none of the open, interested applications are listed in the corresponding request entry in this section (or if there is no entry for that request type), the application to receive the request indication is arbitrary.

If no application is registered to handle the request type (for a tapiRequestMakeCall or tapiRequestMediaCall), TAPI attempts to launch the applications listed in this section, in order, until one of them successfully starts up. The request then remains pending until an application (perhaps the one that launched) registers to receive it.


 Handoff Priorities Entries

Users may manipulate the entries in [HandoffPriorities] directly, although it's better that they use the Preferences settings of Telephony-aware applications. Such applications should be capable of adding entries to [HandoffPriorities] for all the media modes and request types they support, and of rearranging the application names in entries in the section (to set themselves as the highest priority, for example). Entries in the [HandoffPriorities] section are not manipulated through the Telephony control panel.

The [HandoffPriorities] section has the following format:

[HandoffPriorities]
RequestMakeCall=[<appname>[,<appname>]...]
RequestMediaCall=[<appname>[,<appname>]...]
unknown=[<appname>[,<appname>]...]
interactivevoice=[<appname>[,<appname>]...]
automatedvoice=[<appname>[,<appname>]...]
g3fax=[<appname>[,<appname>]...]
g4fax=[<appname>[,<appname>]...]
datamodem=[<appname>[,<appname>]...]
teletex=[<appname>[,<appname>]...]
videotex=[<appname>[,<appname>]...]
telex=[<appname>[,<appname>]...]
mixed=[<appname>[,<appname>]...]
tdd=[<appname>[,<appname>]...]
adsi=[<appname>[,<appname>]...]
digitaldata=[<appname>[,<appname>]...]
NumExtends=<count>
extend<index>=<extid0>,<extid1>,<extid2>,<extid3>,<bit>,"<friendlyname>"
    [,<appname>[,<appname>]...]

where each <appname> is the module filename of a Windows Telephony application.

The first two entries correspond to the request types defined in LINEREQUESTMODE (LINEREQUESTMODE_DROP requests are automatically routed to the same application which handles LINEREQUESTMODE_MEDIACALL requests, since only media calls can be dropped in Assisted Telephony; therefore, the same priorities apply to both).

The next 13 entries correspond to the standard LINEMEDIAMODEs defined in the Telephony API Specification.

NumExtends provides a count of the number of extend<index> lines which follow (with <index> taking values from 0 through <count>-1). By default, it is set to 0. It may be adjusted by any application which adds or deletes an extended media mode.

Each extend<index> line gives the four DWORDs of the Extension Identifier for the extension set, a bit identifier corresponding to the LINEMEDIAMODE bit assigned in that extension set, a friendly name for the media mode (assigned by the provider or application, based on a priori knowledge), and the application priorities.

Note  If an application expects to use an extended media mode, it must ensure that TELEPHON.INI contains an entry defining that media mode. Otherwise, TAPI may not be able to handle incoming calls or call handoffs properly for that (extended) media mode.

<extid0>, <extid1>, <extid2>, and <extid3> shall each be expressed as exactly eight ASCII hex digits. For example, if the EXTIDGEN program outputs an extension ID as:

dwExtensionID0 = 0xA2A9E740;
dwExtensionID1 = 0xA0A51068;
dwExtensionID2 = 0x968A0800;
dwExtensionID3 = 0x2B312E8A;

the extension ID would be specified in an extend<index> entry as:

extend<index>=A2A9E740,A0A51068,968A0800,2B312E8A,...

<bit> shall be a single decimal digit with a value from 1 to 8. These identifiers correspond to the following bit values in LINEMEDIAMODE (which are the only values available for assignment to proprietary media modes in provider extensions):

1    0x80000000
2    0x40000000
3    0x20000000
4    0x10000000
5    0x08000000
6    0x04000000
7    0x02000000
8    0x01000000

The following steps are used to add a new extend<index> entry:

1.	If <count> is already equal to 32767, no more extend<index> can be added.

2.	Obtain <extid0>, <extid1>, <extid2>, <extid3>, <bit>, and <friendlyname> from a priori knowledge.

3.	Add an extend<index> entry to the section, with <index> set to the value of <count>.

4.	Increment <count> by 1. Update the extends entry to show the new value of <count>.

5.	Update TelephonINIChanged, and issue a WM_WININICHANGE message.

The following steps are used to delete an extend<index> entry:

1.	Scan the extend<index> entries to find the entry to be deleted. If it is the last extend<index> (<index> is equal to <count>-1), skip step 2.

2.	Copy the information for all higher-numbered extend<index> entries to one lower value of <index> (for example, copy extend6 to extend5). This will leave the highest-numbered extend<index> entry duplicating the next to highest-numbered extend<index> entry.

3.	Delete the highest numbered extend<index> entry (<index> equal to <count>-1)

4.	Decrement <count> by 1.

5.	Update the extends entry to show the new value of <count>.

6.	Update TelephonINIChanged, and issue a WM_WININICHANGE message.

Note that duplicate entries in the [HandoffPriorities] section are not allowed. For example, if two (or more) entries exist in TELEPHON.INI such as

G3fax=<some stuff>
G3fax=<more stuff>

or,

extension<index>=<extension ID>,bit, <some stuff>
extensiony=<extension ID>,bit, <more stuff>

actual application priorities for these media modes are arbitrary.

Also note that leading "0x" as in "0x <extensionID> is not allowed in the TELEPHON.INI file format.


 Locations

The "[Locations]" section of TELEPHON.INI specifies the locations that are defined by the user. A Location includes a user-defined name, the prefixes necessary to obtain access to an "outside line" at the location, the country code and area/city code of the location, the preferred dialing method for calls placed at the location, and additional information about dialing calls. This information is maintained by the Telephony Control Panel applet.

This section will have the following format:

[Locations]
Locations=<count>,<nextID>
Location<index>=<id>,"<friendlyname>","<localprefix>","<LDprefix>",
"<areacode>",<countrycode>,<preferredcardid>,<hint>,
    <insertareacode>,"<tollprefixes>"
CurrentLocation=<id>,<hint>

For example:

[Locations]
Locations=3,458
Location0=0,"Default Location","","","206",1,0,0,1,""
Location1=233,"Seattle Office","9,","9,","206",1,0,0,
    1,"223,224,233,281,282,283,284,285,286,287,..."
Location2=457,"Boston Office","9","8","617",1,2,2,1,
    ""
CurrentLocation=233,1

The Locations entry indicates how many locations are defined (and how many Location<index> entries appear in the section) with the <count> parameter, and the next permanent location ID to be assigned with the <nextID> parameter. Both parameters are set to 0 when Telephony is installed; the value is subsequently controlled by the Locations function of the control panel.

Each Location<index> entry identifies a location, and gives its permanent ID (used to link parameters in other files to the location). "<index>" takes values from 0 to one less than <count>. These entries may be renumbered as locations are deleted. Location0 is the "Default Location", and can never be removed; its <id> is always 0, its name should not be changed, but all of the other parameters may be changed by the user.

Within each Location<index> entry, the individual fields have the following meanings:

<id> is the permanent ID for the location, which is used to link parameters to other files to the location. Once a permanent ID is assigned to a location, it is never changed. These IDs shall be in the range 0 to 32767 (when 32767 is used, <nextID> shall wrap to 0).

"<friendlyname>" is the user-assigned name for the location, entered through the Telephony control panel. It must be enclosed in quotation marks, and must not contain quotation marks.

"<localprefix>" is the dialable string to be dialed before all calls determined to be "local" (same country, same area code, not in the toll list).

"<LDprefix>" is the dialable string to be dialed before all calls that are not local (different country, different area code, or in the toll list).

"<areacode>" is the area/city code associated with the current location. If this is empty, the current country is presumed to have a flat numbering system without city codes (all local numbers unique throughout the country). This is used in determining whether the canonical number is local or long distance.

<countrycode> is the country code associated with the current location. This is linked to an entry in the "[Countries]" section to determine the dialing procedures when the selected dialing method is "Direct" (CallingCard permanent ID 0); if the code does not match an entry in the [Countries] section, then canonical translation fails and the number is returned unmodified. It is also used in determining whether the canonical number is local or long distance. This value is returned with the lineTranslateAddress function of the Telephony API.

<preferredcardid> is the preferred dialing method which will be preselected when the user requests a dialing operation. It must match one of the permanent IDs of an entry in the [Cards] section; if it does not, it is presumed to be 0 ("Direct").

<hint> indicates the number of the Card<index> entry which matched <preferredcardid> at the time this Location<index> was last modified; to save time, the DLL can check this entry first when trying to find the information on the Card<index>, before scanning all cards (which should only be necessary after a card entry is removed).

<insertareacode> shall have a value of 0 or 1. 0 indicates that toll calls should not include the area code before the local number; 1 indicates that toll calls should have the area code before the local number. This is applicable only when <countrycode> is 1 (North America), the country code and area code being dialed are the same as for the current location, and the prefix of the local number appears in <tollprefixes>.

"<tollprefixes>" is a list of three-digit prefixes for calls which receive special treatment. If the country code for the current location is 1, the country code and area code being dialed are the same as for the current location, and the prefix of the local number matches an entry in this list, then the number will be dialed according to the <longdistance> dialing rule rather than the <samearea> dialing rule. The inclusion of the area code as part of the local number can be controlled by the <insertareacode> parameter. The entries within the list consist of three-digit numbers, separated by comma characters (0x2C), preferably sorted in ascending numeric order.

The CurrentLocation entry gives the <id> of the location at which the user is presently located. The value should match an <id> in an existing Location<index> entry; if it does not, the current location should be assumed to be the default location (permanent ID 0). CurrentLocation should be set to "0,0" when TELEPHON.INI is first created. The <hint> parameter indicates the number of the Location<index> entry which matched <id> at the time CurrentLocation was last set; to save time, the DLL can check this entry first when trying to find the information on the CurrentLocation, before scanning all locations (which should only be necessary after a location is removed).


 Calling Cards

The "[Cards]" section of TELEPHON.INI specifies information related to a method of dialing telephone calls. This method may, or may not, include an associated telephone calling card number (the dialing methods are referred to generically as "calling cards" because use of a calling card is the most frequent reason for using an alternative dialing procedure). The calling card numbers are scrambled to provide security against non-determined, casual observation (for example, someone looking at the TELEPHON.INI file with a text editor); greater security will depend on system-level file or system access security (such as in case a notebook computer is stolen).

This section will have the following format:

[Cards]
Cards=<count>,<nextID>
Card<index>=<id>,"<friendlyname>","<scrambledcardnum>",
    "<samearea>","<longdistance>","<international>",<hidden>

For example:

[Cards]
Cards=5,4
Card0=0,"None (Direct Dial)","","","","",0
Card1=1,"AT&T via 10288","438 293 482 1938",
    "102880FG$H","102880FG$H","1028801EFG$H",0
Card2=2,"AT&T via 1-800-321-0288","",
    "18003210288$FG$H","18003210288$FG$H",
    "18003210288$01EFG$H",1
Card3=3,"Direct With Security Code",
    "","G","1FG,3948","011EFG,3948",0
Card4=4,"USA Direct from Italy","549 304 593 2049",
    "","","P1721011$TFG$H",0

The Cards entry indicates how many locations are defined (and how many Card<index> entries appear in the section) with the <count> parameter, and the next permanent card ID to be assigned with the <nextID> parameter. The values of these parameters are controlled by the Telephony control panel. Their initial settings when Telephony is installed is dependent on the number of predefined Card<index> entries shipped.

Each Card<index> entry identifies a card, giving its permanent ID (used to link parameters in other files to the card). "<index>" takes values from 0 to one less than <count>. These entries may be renumbered as cards are deleted. Card0 shall not be removable or modifiable by the user; it is a placeholder used to indicate that the direct dialing rules for the country specified in CurrentLocation should be used for dialing.

The parameters included in each Cardx entry are as follows:

<id> is the permanent ID associated with this card, assigned by the control panel. Once assigned, it is never changed. It is used to link the <preferredcardid> for a Location<index> entry to the associated card in a manner insensitive to the insertion and remove of Card<index> entries. These IDs shall always be in the range of 0 to 32767.

"<friendlyname>" is the user-assigned name for the card. It must be enclosed in quotation marks and may not contain quotation marks.

"<scrambledcardnum>" is the card number associated with this entry (if any; it may be "" for a Card<index> entry which actually specifies alternative direct dial rules). The contents are scrambled in order to provide security from accidental viewing.

"<samearea>", "<longdistance>", and "<international>" are the dialable string templates for the three classes of calls (same area code, different area code but same country, and different country code, respectively). The contents of these strings should be selected from the following list (spaces, hyphens, periods, and parentheses may be included for formatting purposes):

0-9	Dialable digits

A-D	Dialable digits

#	Dial DTMF "#"

*	Dial DTMF "*"

T	DTMF dial subsequent digits

P	Pulse dial subsequent digits

!	Hook flash

,	Pause during dialing

W	Wait for second dial tone

@	Wait for quiet answer

$	Wait for "bong" tone

?	Prompt user before proceeding

E	Insert country code

F	Insert area code

G	Insert subscriber number

H	Insert calling card number

I	Insert area code (area codes are optional; used in country entries only)

<hidden> determines whether or not this entry should be displayed in lists of available dialing methods displayed to the user by applications. These are delivered to applications by the lineGetTranslateCaps function. Values are as follows:

Value	Meaning
0	Not hidden. The value can be set by the user.
1	Not hidden. The value can only be set by the application (it cannot be deleted).
2	Hidden. The value can be set by the user.
3	Hidden. The value can only be set by the application (it cannot be deleted).
The function lineGetTranslateCaps will not return to the application entries for calling cards which have this parameter set to 1 and which have a null card number field.


 Countries

The "[Countries]" section of TELEPHON.INI specifies the well-known direct dialing procedures for calls placed within specific countries. The contents of this section are shipped with Windows Telephony, are not intended to be edited by the user, and could, in future releases, be moved to a compressed binary file for quick access; however, the information is contained in the TELEPHON.INI file, at least in the initial release, to facilitate user editing (under the guidance of Microsoft Product Support Services) if problems are discovered.

This section will have the following format:

[Countries]
Country<index>=<countrycode>,<nextcountry>,"<name>","<samearea>",
    "<longdistance>","<international>"

For example:

[Countries]
Country1=1,100,"North America and Caribbean","G","1FG","011EFG"
Country100=1,101,"United States of America","G","1FG","011EFG"
Country101=1,102,"Anguilla","G","1FG","011EFG"
Country102=1,103,"Antigua","G","1FG","011EFG"
Country103=1,104,"Bahamas","G","1FG","011EFG"
Country104=1,105,"Barbados","G","1FG","011EFG"
Country105=1,106,"Bermuda","G","1FG","011EFG"
    ...
Country98=98,0,"Iran","G","0FG","00EFG"

There are two kinds of entries in the [Countries] section. The first, known as "primary" entries, are indicated by the <countrycode> parameter equaling the value of <index>. Primary entries specify the name of a World Numbering Plan Area as specified in CCITT Recommendation E.163, and include the direct dialing rules applicable to that numbering plan area. The second type of entries, known as "secondary" entries, are indicated by the <countrycode> parameter not being equal to the value of <index>. Secondary entries are used to specify countries which are contained within multi-country World Numbering Plan Areas (e.g, "1" for North America and Caribbean).

The <nextcountry> parameter is used by the lineTranslateCaps function when reading in the [Countries] section to build the table of countries in the LINETRANSLATECAPS structure. Country codes are non-contiguous, and this parameter allows the lineTranslateCaps function to read in the entries without either guessing at country codes or having to read in the entire section at once and parsing out the entries itself. The last country in the list shall have its <nextcountry> parameter set to 0.

"<samearea>", "<longdistance>", and "<international>" are the dialable string templates for the three classes of calls which may be direct dialed from this country. A parameter should be left empty ("") if that type of call cannot be direct dialed. The permitted contents of these strings are the same as specified above in the [Cards] section.


 Call States and Events

About Call States and Events

A connection is not fully established until both parties are communicating. To reach that point, the establishment of the call goes through several stages, as does the clearing (termination) of the call. A call's events cause it to transition through call states as it comes into existence, is used to exchange information, and terminates. These call-state transitions result from both solicited and unsolicited events. A solicited event is one caused by the application controlling the call (as when it invokes TAPI operations), while unsolicited events are caused by the switch, the telephone network, the user pressing buttons on the local phone, or the actions of the remote party. Some operations on line devices, addresses, and calls may first require that the line, address, or call upon which they operate be in certain specific states.

Different call states indicate that connections exist to different parts of the switch. For example, a dial tone is a particular state of a switch that means the computer is ready to receive digits.

Whenever a call changes state, TAPI reports the new state to the application in a callback. This programming model, therefore, is one in which the application reacts to the events reported to it, as opposed to a rigid call-state model. In other words, call-state notification tells the application what the call's new state is, instead of reporting the occurrence of specific events and assuming that the application will be able to deduce the transitions between two states.


 Call State Definitions

Some of the call states and events defined by TAPI are exclusive to inbound or outbound call processing, while others occur in both cases. Several of these call states provide additional information that can be used by the application. For example, the busy state signifies that a call cannot be completed because a resource between the originator and the destination is unavailable, as when an intermediate switch has reached its capacity and cannot handle an additional call. Information supplied with the busy state includes station busy or trunk busy. Station busy means that the destination's station is busy (the phone is offhook), while trunk busy means that a circuit in the switch or network is busy. The call states defined by TAPI are listed below:

Call State	Description
idle	This corresponds to the "null" state:  No "activity exists" on the call, which means that no call is currently active.
offering (inbound)	When the switch informs the computer of the arrival of a new incoming call, that call is in the offering state. Note that offering is not the same as causing a phone or computer to ring. When a call is offered, the computer is not necessarily instructed to alert the user.
	Example: An incoming call on a shared call appearance is offered to all stations that share the appearance, but typically only the station that has the appearance as its primary address is instructed to ring. If that station does not answer after some amount of time, the bridging stations may be instructed to ring as well.
accepted (inbound)	An application has taken responsibility for an incoming call. In ISDN, the accepted state is entered when the called party equipment sends a message to the switch indicating that it is willing to present the call to the called person; this has the side effect of alerting the users at both sides of the call: the caller's and the called party's. An incoming call can always be immediately answered without first being separately accepted.
dial tone (outbound)	Indicates that the switch is ready to receive a dialable number. In most telephony environments, this state is entered when audible dial tone is detected by the line device. Additional information includes:
— normal dial tone	The "normal" or everyday dial tone, usually a continuous tone.
— special dial tone	A special dial tone is often used to signal certain conditions such as message-waiting. This is usually an interrupted dial tone.
dialing (outbound)	The originator is dialing digits on the call. The dialed digits are collected by the switch.
proceeding (outbound)	The call is proceeding through the network. This occurs after dialing is complete and before the call reaches the dialed party, as indicated by ringback, busy, or answer.
special info (outbound)	The call is receiving a special information signal. A special information signal precedes a prerecorded announcement indicating why a call cannot be completed. Such announcements can be of these types:
— no circuit	A no-circuit or emergency announcement.
— customer irregularity	This typically means that the dialed number is not correct.
— reorder	A reorder or equipment-irregularity announcement.
busy (outbound)	The call is receiving a busy signal. Busy indicates that some resource is not available and the call cannot be normally completed at this time. Additional information consists of:
— station busy	The station at the other end is off-hook.
— trunk busy	The network is congested. This usually produces a "fast busy" signal.
ringback (outbound)	The station to be called has been reached, and the destination's switch is generating a ring tone back to the originator. A ringback means that the destination address is being alerted to the call.
connected (inbound and outbound)	Information is being exchanged over the call.
on hold (inbound and outbound)	The call is currently held by the switch. This frees the physical line, which allows another call to use the line.
conferenced (inbound and outbound)	The call is a member of a conference call and is logically in the connected state (to the conference bridge). A call in the conferenced state refers to a conference call (in the connected, onHold, ... state).
on hold pending conference (inbound and outbound)	The conference call is currently on hold and waiting for the user to add another party.
on hold pending transfer (inbound and outbound)	The call is on hold in preparation of being transferred.
disconnected (inbound and outbound)	The call has been disconnected by the remote party.
unknown (inbound and outbound)	The call exists, but its state is currently unknown. This may be the result of poor call progress detection by the service provider. A call state message with the callstate set to unknown may also be generated to inform the TAPI DLL about a new call at a time that that the actual call state of the call is not exactly known.
Although under normal circumstances an outbound call is likely to transition to connected through a number of intermediate states (dial tone, dialing, proceeding, ringback), other paths are often possible. For example, the ringback state may be skipped, as when a hot phone (or other non-dialed phone) transitions directly to connected.

An application should always process call-state event notifications. Call-state transitions valid for one switch or configuration may be invalid for another. For example, consider a line from the switch that (using a simple Y-connector) physically terminates both at the computer and at a separate phone set, creating a party line configuration between the computer and the phone set. The computer termination and, therefore, the application using TAPI, may not know of the activities on the line handled by the phone set. That is, the line may be in use without the service provider being aware of it. An application that wants to make an outbound call will succeed in allocating a call appearance from the API, but this results in sharing the active call on the line. In this case, blindly sending a DTMF dial string without first checking for a dial tone may not result in intended (or polite) behavior.


 Obtaining Call State Information

Using the function lineGetCallStatus, an application can receive complete call status information for the specified call as a data structure of type LINECALLSTATUS. The function lineGetCallInfo returns mostly constant information about a call as a data structure of the type LINECALLINFO. The message LINE_CALLSTATE is sent unsolicited to an application to notify it about changes in a call's state.

The call-information data structure maintained for each call contains an application-specific field that applications can read from and write to. This field is not interpreted by TAPI. Applications can use it to "tag" calls in application-specific ways. Writing to this field so that the change is visible to other applications can be done with the function lineSetAppSpecific.


 Introduction

This book describes how to create applications that use the Microsoft® Windows® Pen Application Programming Interface (API). The book is divided into two parts. Part 1 presents an overview of pen-based computing and describes the various components of the Pen API. Sample code supplements the text and later chapters present a complete sample program and sample recognizer as examples. (Recognizers translate pen strokes into characters, symbols, or shapes.) Part 2 provides a reference for the functions, structures, messages, and constants that make up the Pen API. Following the reference, a number of appendixes provide information about the differences between versions 1.0 and 2.0 of the Pen API, the 32-bit pen services, and more.

The Microsoft Windows 95 operating system includes a subset of the Pen API for displaying pen data. This allows a pen-based application to collect pen data from a pen tablet, store the data, and later display the data on any personal computer running Windows 95, even without pen hardware. The full pen services come only with pen hardware from original equipment manufacturers (OEMs) of pen equipment. Thus, an application running with Windows 95 has guaranteed access to at least the display portion of the Pen API; if a pen tablet is attached, the application can also accept pen input.

The full pen services of the Pen API version 2.0 described in this book can run only with Windows 95 or later Windows versions.

This book assumes a familiarity with the C language and with Windows programming in general. To keep discussions concise, the text does not digress to define such general terms as dynamic-link library (DLL), callback function, or message. However, pen-based computing generates its own lexicon, so the text defines new terms specific to the Pen API as they are introduced. In addition, a brief glossary of terminology specific to pen-based computing appears at the end of this book.


 Organization

This book is divided into the following chapters and appendixes.

Chapter or appendix	Describes
Chapter 1, Overview of the Pen Application Programming Interface	Architecture of the Pen API.
Chapter 2, Starting Out with System Defaults	How to add pen functionality to an application with a minimum of programming effort.
Chapter 3, The Writing Process	How an application gets input from a pen device.
Chapter 4, The Inking Process	How an application collects and changes pen input data.
Chapter 5, The Recognition Process	Converting raw pen input into usable characters such as letters and numerals.
Chapter 6, Design Considerations	Proper techniques, warnings, and tips for writing a pen-based application.
Chapter 7, A Sample Pen Application	The PENAPP.C sample application, to illustrate the information in Chapters 1 through 6.
Chapter 8, Writing a Recognizer	The requirements and design of a recognizer. Illustrates information using the sample recognizer SREC.C as a model.
Chapter 9, Summary of the Pen Application Programming Interface	Pen API services, listed by category.
Chapter 10, Pen Application Programming Interface Functions	Functions, listed alphabetically.
Chapter 11, Pen Application Programming Interface Structures	Structures, listed alphabetically.
Chapter 12, Pen Application Programming Interface Messages	Messages, listed alphabetically.
Chapter 13, Pen Application Programming Interface Constants	Constants, listed alphabetically.
Appendix A, Differences Between Versions 1.0 and 2.0 of the Pen Application Programming Interface	Changes and improvements to the Pen API.
Appendix B, Using the 32-Bit Pen Application Programming Interface	How to write 32-bit pen-based applications.
Appendix C, Modifying the SYSTEM.INI File	Settings used in Windows SYSTEM.INI.
Appendix D, Accessing the Pen Device Driver	How an application calls the pen driver.
Glossary	Pen-based terms.


 Document Conventions

The following document conventions are used throughout this book.

Convention	Description
Bold text	Bold letters indicate a specific term or punctuation mark intended to be used literally: language functions or keywords (such as DrawPenDataEx or switch), MS-DOS® commands, and command-line options. You must type these terms and punctuation marks exactly as shown. The use of uppercase or lowercase letters is usually, but not always, significant. For example, you can invoke the C compiler by typing either CL, cl, or Cl at the MS-DOS prompt.
( )	In syntax statements, parentheses enclose one or more parameters that you pass to a function.
Italic text	Italic text indicates a placeholder; you are expected to provide an actual value. For example, in the following syntax the placeholder lpszRecogName represents a pointer to the filename of a recognizer: InstallRecognizer( lpszRecogName ); New terms pertaining to pen-based computing also appear in italics where they are first introduced or defined in the text. Such terms are also listed in the glossary.
Monospace text	Code examples are displayed in a nonproportional typeface.
if(RegisterClass(LPWNDCLASS)&wc))      .      .      . else	A vertical ellipsis in a program example indicates that a portion of the program has been omitted.
. . .	A horizontal ellipsis following an item indicates that more items having the same form may appear.
[[ ]]	Double brackets enclose optional fields or parameters in command lines or syntax statements.
|	A vertical bar indicates that you can enter one of the entries shown on either side of the bar. In symbol graphs, a vertical bar indicates the possible character choices.
{ }	Braces indicate that you must specify one of the enclosed items.
SMALL CAPITAL LETTERS	Small capital letters indicate the names of keys and key sequences; for example, CTRL+ALT+DEL. If the key names are separated by commas instead of plus signs; for example ALT, F—then you must press the keys consecutively rather than together.


 Books and Articles for Further Reading

The documentation listed in the following table provides additional information about the Pen API and about Windows in general.

Title	Contents
Microsoft Windows Pen API version 2.0 online Help	Online reference for Pen API functions, structures, messages, and constants.
Microsoft Windows Software Development Kit (SDK) documentation, or equivalent documentation	Information about the application programming interface of the Windows operating system.
Microsoft Windows Device Driver Kit (DDK) documentation, or equivalent documentation	Description of the application programming interface of the Windows device drivers. Required only for developing drivers.
Duncan, Ray. "Power Programming." PC Magazine. New York, New York: Ziff-Davis Publishing Company, January 14, 1992 through May 12, 1992	Series of articles on the basics of the Pen API version 1.0.
Petzold, Charles. Programming Windows. Third edition. Redmond, Washington: Microsoft Press, 1992	Good introduction to general programming for Windows.


 System Requirements

You can develop pen applications for version 2.0 of the Pen API with the following software and hardware:

•	A personal computer running Windows 95 or a later version of Windows

•	A mouse, tablet, or other pointing device supported by the Pen API

•	Microsoft Win32® Software Development Kit (SDK)

•	Microsoft Windows 95 Device Driver Kit (DDK) — necessary only if you will be building pen, display, or keyboard drivers

•	Microsoft C Optimizing Compiler, version 5.1 or later, or Microsoft QuickC® for Windows version 1.0 or later

•	Microsoft Macro Assembler version 5.1 or later — necessary only if you will be building pen, display, or keyboard drivers

You may also use equivalent development software produced by other manufacturers, such as Borland International, Inc.


 Acknowledgments

Special thanks to the contributors to this book including:

Writers	Beck Zaratian Don Gilbert	Mark Williams
Editors	David Steinmetz Peter Delaney	Barb Ellsworth David Thornbrugh
Program Managers	Jeff Aamodt Eric Berman	Steve Liffick
Pen Services Development Team	Eric Onasick Vinayak Bhalerao Haresh Ved	Shishir Pardikar Chris Leyerle Fumitaka Kawasaki
Recognition Development Team	Mike Van Kleeck Justin Ferrari Sung Rhee Donald Sidoroff Greg Hullender	Jim Adcock Shamik Basu Oswaldo Ribas Patrick Haluptzok
Testing Team	Becca Moss Brian Watson Xian-Ling Wu	Keith Stutler Randy Shedden David Flenniken


 Overview of the Pen Application Programming Interface

This chapter presents an overview of pen-based computing, divided into two main sections. The first section broadly describes the various components that make up the Pen application programming interface (API). The second section describes how applications access the pen services to incorporate pen-based features.

The architecture of version 2.0 of the Pen API remains similar to version 1.0, but its style and design differ considerably. Even if you have worked with version 1.0, you should read this chapter to understand the shift in programming philosophy in version 2.0.


 Architecture of the Pen API

The seemingly simple step of getting data from the pen to an application involves many intermediate tasks. Fortunately, the Pen API itself takes on the major share of this work. By providing applications with convenient access to pen features, the Pen API insulates the programmer from the most tedious aspects of pen data recognition. At the same time, its flexible design allows applications to control most of the low-level processes of pen input.

As you read this section, keep in mind that the complexities of the Pen API architecture in no way imply a corresponding difficulty in creating pen-based programs. You will find that writing intelligent pen-based software is no more difficult than writing other applications for Microsoft Windows.

Figure 1.1 illustrates the interaction between applications and the main components of the Pen API.

The following four sections describe each component of Figure 1.1, beginning with the main Windows component. Each section contains a figure that incorporates Figure 1.1, exploding the component into a detailed view. The accompanying text describes the component and explains how it interacts with the other components.


 Windows

As Figure 1.2 shows, the heart of the pen-based services for Microsoft Windows 95 consists of two libraries — PKPD.DLL and PENWIN.DLL. The PKPD.DLL file provides ink management for the pen services of Windows 95. This allows an application to display and manipulate ink data with any installation of Windows 95, even one without pen hardware. Chapter 9, "Summary of the Pen Application Programming Interface," identifies the pen services exported by PKPD.DLL.

The PENWIN.DLL file is available only with original equipment manufacturer (OEM) pen hardware and provides additional pen services that collect, modify, and recognize ink data. Before using these input and recognition features, an application should first test for the presence of the PENWIN.DLL file and either gracefully exit or alter its behavior accordingly.

In Pen Windows version 1.0, applications were required to call RegisterPenApp in order to tell the system to convert all edit controls to handwriting edit (hedit) controls. With Pen API version 2.0, however, this is not necessary; all edit controls in applications are automatically converted. If the application is version-stamped as a Windows 95 − based application, the conversion is automatic; otherwise, applications version-stamped as Windows 3.1 − based applications require the call to RegisterPenApp that was required for Pen Windows version 1.0.

It is important to understand that for any application to successfully use the functions in PENWIN.DLL, the computer on which it is running must load the pen services when Windows boots and terminated the pen services when Windows shuts down (that is, PENWIN.DLLmust be referenced from the drivers line in the [Boot] section of the SYSTEM.INI file). This does not apply to functions in the PKPD.DLL library, which is automatically available on all Windows 95 systems. See Appendix C, "Modifying the SYSTEM.INI File," for information on the SYSTEM.INI file requirements.

Because of this requirement, PENWIN.DLL should never be statically linked by any application that may be run on a system on which pen services are not installed. Instead, its functions should always be called using function pointers. Typically, when the pen-aware application initializes, it calls GetSystemMetrics with SM_PENWINDOWS as a parameter which, if returned successful, provides a handle to the loaded library. Then, for each PENWIN.DLL function used by the application, the application calls the GetProcAddress function (with the library handle and the function name) and saves a function pointer to be used in future calls to that function. See the HFORM sample application for an example of this technique.

By not linking PENWIN.LIB, it is insured that an application running on a system on which PENWIN.DLL has not been installed, but which contains PENWIN.DLL on the path, will not load PENWIN.DLL at runtime. Pen components not loaded at system boot time are not guaranteed to perform properly. Note that this applies for both 16-bit and 32-bit libraries.

Applications that are destined to be run only on systems that have pen services installed can link directly to PENWIN.LIB. These applications should test for the existence of pen services at startup, however, and exit if it is not found. Note that most of the examples in this manual follow normal linking practice for the sake of readability and do not use the safer practice of using function pointers. It is the responsibility of the developer to choose the best means of accessing the functions in PENWIN.DLL for each application.

The Pen Message Interpreter provides basic pen services to pen-unaware applications. Such applications, which do not explicitly take advantage of Windows pen services, currently represent a majority of Windows-based software. The Message Interpreter allows use of a pen with pen-unaware programs by capturing handwritten input and other pen events and converting them into equivalent keyboard and mouse messages. The application has no knowledge of the pen or that pen input has occurred.

In capturing handwritten input, the Message Interpreter acts only when it detects a standard I-beam pointer or insertion point in the pen-unaware application. Since applications generally show the system I-beam pointer when prompting for input in writing areas, the Message Interpreter reliably serves most pen-unaware programs. However, a few pen-unaware Windows-based applications do not prompt with a standard I-beam pointer, defeating the Interpreter's detection method. Although the Interpreter still allows the pen to serve as a mouse with such applications, it cannot interpret handwritten input.

The Message Interpreter may also falter when serving applications developed for a version of Windows earlier than version 3.1. These applications were not designed with the pen in mind and therefore may not work optimally with the pen. For example, edit fields in applications written for Windows version 3.0 are often too small to write in with a pen. A final problem with older applications is that the Message Interpreter has no means of receiving contextual information from the application about what sort of input it expects. This can reduce recognition accuracy.

The Message Interpreter is of academic interest for the programmer because it pertains to only pen-unaware applications. The rest of this book focuses on how to write pen-aware applications and dynamic-link libraries (DLLs) that make use of the Pen API directly.


 Drivers

Figure 1.3 shows the two types of drivers that function within the Pen API system. Most drivers incorporate two modules: an installable device driver that uses the Windows installable driver interface and a virtual device driver that handles interaction with the hardware.


 Pen Driver

The pen installable device driver, which Windows supplies as the file PENC.DRV, interacts with the virtual pen driver (VPENDC.VXD) and passes pen movement data to Windows. The fact that the pen driver's data may sometimes be needed for on-the-fly handwriting recognition places several constraints on a pen input device:

•	The pen driver must be able to report the location of the pen at least 60 times per second. This rate ensures the true path of the pen is reported accurately enough to support the efforts of vector-based recognizers. It also makes the ink, a path of pixels that traces the pen's movement, appear smooth and natural at normal writing speeds. For more information about recognizers, see the "Recognizer" section later in this chapter.

•	The pen driver must be able to report pen positions with a resolution of at least 200 points per inch. This degree of resolution ensures ink coordinates are sufficiently fine to let the recognizer make accurate judgments about the path of the pen over the digitizing surface.

•	Regardless of the resolution of the device, the pen driver must report the pen position in tablet coordinates of 0.001 inch. This convention ensures that Windows, the recognizer modules, and the application all view the ink at the same scale.


 Display Driver

The display driver is responsible for interacting with the display hardware and the graphics device interface (GDI) module of Microsoft Windows. A display driver should support inking to provide the user with visible feedback as the pen moves. Technically, the Pen API does not require inking support from the display driver. However, the system is far more practical and convenient when the user can see the ink trail left by the pen.

Two types of display drivers are supported:  Display Control Interface (DCI) drivers (called DCI Providers) and non-DCI drivers, such as older VGA or 8514 drivers. For DCI Providers, no extra work is required to support the pen interface.

To support inking in a non-DCI driver, the display driver must be able to:

•	Export the GetLPDevice function to provide Windows with a value identifying the pen hardware.

•	Export the InkReady function, which Windows calls to notify the driver that the pen is in motion and Windows is ready to display ink. InkReady must be able to handle calls during system interrupts.

•	Provide a pointer in the shape of a pen.

Windows — not the display driver — displays the ink. When Windows receives notice through its InkReady function, the driver calls back into Windows to draw the ink.

For more details on display drivers, refer to the device driver kit (DDK) for Windows 95.


 Recognizer

A recognizer is a DLL with functions that determine what symbol a pattern of pen strokes represents. As illustrated in Figure 1.4, Windows allows the concurrent operation of more than one recognizer. For example, one recognizer may specialize in English letters, another in mathematical symbols, another in geometric shapes, and so forth.

Each handwriting recognizer can access any number of word lists. Word lists offer a way for a recognizer to corroborate and refine its guesses. For example, if a recognizer cannot decide whether a handwritten word is "boy" or "looy," finding one word but not the other in a word list helps the recognizer make a more confident choice.

Although many recognizers may be available to an application, only one serves as the system default recognizer. This is the recognizer that Windows automatically installs and calls by default. To use other recognizers, an application must first specifically install them. (For information about how to install multiple recognizers, see Chapter 5, "The Recognition Process.") The Microsoft Handwriting Recognizer (GRECO.DLL)  is provided as the default system recognizer on most OEM tablet installations of Microsoft pen services. The Microsoft Handwriting Recognizer recognizes all European letters, numerals, and punctuation, with emphasis on English, French, and German, An application can set up a different system recognizer by identifying the new file in the Windows registry. Appendix A explains how to set up a new default recognizer.


 Accessing the Pen API from Applications

As Figure 1.5 shows, applications that accept user input are divided into two categories: pen-aware and pen-unaware applications. A pen-unaware application, as the name implies, is written to expect input only through the keyboard or mouse, unaware of the existence of Windows pen services. However, if a pen device is present, Windows 95 supports its use both as a mouse and for text entry with a pen-unaware application. For details about how Windows allows the use of a pen with an application not written to accept pen input, see "Pen-Unaware Applications" in Chapter 2, "Starting Out with System Defaults."

The Pen API is designed for small handheld systems with limited memory and power, so its API consists of 16-bit functions. Therefore, Windows provides a thunk layer for 32-bit applications to call through to the API. The thunk layer automatically converts 32-bit function parameters and structure data to 16-bit equivalents. The application must ensure its data will fit into the smaller sizes before calling into the Pen API. See Appendix B for information about using the 32-bit API.


 Starting Out with System Defaults

As much as possible, the Pen application programming interface (API) handles the many complexities of pen-based computing. A rich API leaves the developer free to concentrate on design without having to worry about details. This chapter describes how to create a pen-based application that relies on the system default services of the Pen API. For the sake of simplicity, the term "application" as used in this chapter refers both to Windows-based programs and dynamic-link libraries (DLLs).


 Pen-Unaware Applications

Microsoft Windows 95 supports the use of a pen even with pen-unaware applications. For such applications, Windows provides a means for the pen to mimic both mouse and keyboard data. It does this in two ways.

The first method, the Pen Message Interpreter, is described in the "Windows" section in the previous chapter. The second method involves two utility "applets" called Writing Palette (WRITEPAL.EXE) and Screen Keyboard (SK.EXE), both supplied as installed applications. Writing Palette allows the user to enter handwritten text for those occasions when the Message Interpreter fails to detect an input prompt. For example, when running an MS-DOS text editor in a window, the user can input handwritten text through the Writing Palette utility. The Pen API translates the handwritten text into characters and displays the result in the writing window. The user can then correct the text if necessary and tap the OK button when the corrections are recognized. Windows feeds the characters to the pen-unaware text editor as a series of WM_KEYDOWN and WM_KEYUP messages as though they were typed at the keyboard.

The Screen Keyboard applet displays an image of a typical keyboard on which the user can "type" by tapping the keys of the on-screen keyboard with the pen. Each key is sent as soon as it is typed. This does not require recognition because no handwriting is involved.


 Pen-Aware Applications

The Pen API allows the developer to approach pen-based computing in stages. For those who wish to do only a minimum amount of programming work and yet incorporate significant pen capabilities in an application, the Pen API provides the DoDefaultPenInput function. DoDefaultPenInput embodies a set of more complex API elements in one function. As its name implies, it allows applications to rely on the system to make all of the decisions concerning pen input. The developer can incrementally enhance a pen-based application as time and interest permit.

When called in response to a WM_LBUTTONDOWN message generated by the pen device, DoDefaultPenInput starts a cascade of messages. These messages reflect the many steps of the recognition process, each message serving as a notice that a next step in the process is about to occur. The application can take some action prior to each step or simply ignore the message and let the DefWindowProc function provide default services.

This approach follows standard Windows messaging procedures. If an application lets the message pass through to DefWindowProc, Windows translates the pen events into the appropriate keyboard messages. For example, handwritten characters generate appropriate WM_CHAR messages. In this way, a developer can gradually modify an existing application to become more and more sophisticated about pen input by adding code to handle more of the DoDefaultPenInput messages.

The following sections describe the programming convenience of using system defaults, which you might think of as "letting the system do the work." The text also mentions various options available to the developer who wishes to exercise more control over the recognition process. These options involve manipulating data objects such as HRC and HPENDATA, which are fully described in Chapters 4 and 5. The following sections serve as an introduction to the entire process of converting pen-based input to usable data. When you later decide to incorporate additional recognition management into your application, see Chapters 4 and 5.


 Beginning an Input Session

A pen input session begins when the user touches pen to tablet and begins writing. The end of the session depends on parameters established by the application. Usually, the session ends when the user taps the pen outside the writing area or when a brief period of inactivity elapses. As when writing with a real pen, people tend to pause between words or sentences to gather their thoughts; an application can use these momentary pauses to get recognition results. A new session begins when the user begins writing again.

When the pen first touches the tablet at the start of an input session, Windows sends a WM_LBUTTONDOWN message to the application's main window procedure. In a pen-based environment, this message can indicate either a true mouse event or that the pen point has touched the tablet. The application must distinguish between these two possibilities before calling the DoDefaultPenInput function, as shown in the following fragment:

LONG	lExtraInfo;

.

.

.

switch (wMsg)

{

case WM_LBUTTONDOWN:

// If true pen-down event, call DoDefaultPenInput.

lExtraInfo = GetMessageExtraInfo();

if (IsPenEvent( wMsg, lExtraInfo )

return DoDefaultPenInput( hwnd, LOWORD(lExtraInfo) );

else	// No, it's a mouse

{	//   button down

.

.

.


 DoDefaultPenInput Messages

This section lists in chronologic order the message traffic that DoDefaultPenInput generates. It discusses why an application might want to handle each message and explains what action DefWindowProc takes. The sample application described in Chapter 7, "A Sample Pen Application," demonstrates how to handle most of these messages.


 Step 1: PE_BEGININPUT Submessage

Immediately upon calling DoDefaultPenInput, an application receives a WM_PENEVENT message with a PE_BEGININPUT submessage. Sending WM_PENEVENT and PE_BEGININPUT via the SendMessage function is the equivalent of calling DoDefaultPenInput. The caller should not trap the PE_BEGININPUT submessage because DefWindowProc starts the chain of events based on this message. The application should complete all its initialization work before calling DoDefaultPenInput.


 Step 2: PE_SETTARGETS Submessage

Windows sends the WM_PENEVENT message with a PE_SETTARGETS submessage to the window that received the PE_BEGININPUT submessage. PE_SETTARGETS is important when several windows on the screen vie for input at the same time, presenting Windows with more than one potential recipient for the pen data. This can occur when a dialog box contains multiple edit controls or a forms program prompts the user simultaneously with several writing areas. The user can write in different writing areas without having to pause between each and wait for recognition results. Windows treats the writing as part of a single input session, regardless of the targets.

DoDefaultPenInput must therefore select between targets when distributing pen data. A target is a rectangular area associated with the handle of a window that is a valid destination for pen data. When writing starts, all valid targets participate in the DoDefaultPenInput messaging. This allows the user to move freely between windows — for example, writing the name of a city in one control, interrupting to write the date in another control, then moving back to the first control to add the state and zip code. The system correctly routes pen input to the control on which ink was written or, barring that, to the control nearest the ink.

DoDefaultPenInput handles all routing automatically. Upon receiving a PE_SETTARGETS submessage, the application can process the message and create a TARGINFO structure that describes all valid targets for the pen data. If the application chooses not to process PE_SETTARGETS itself, DefWindowProc enumerates the children of the window and creates a TARGINFO structure automatically. If the application returns FALSE to the PE_SETTARGETS submessage, Windows assumes no targets exist and sends the pen data to the window that received PE_SETTARGETS.

For information on how to specify a target area larger than the window size, see the "PE_SETTARGETS Submessage"section.


 Step 3: PE_GETPCMINFO Submessage

If the application calls DefWindowProc to process the PE_SETTARGETS submessage, every descendant of the window that received PE_SETTARGETS receives a PE_GETPCMINFO message. This message is so named because it gets information about the pen collection mode (PCM). The PCM describes the system state during an input session when the pen is writing and not operating as a mouse.

PE_GETPCMINFO gives each target the opportunity to:

•	Proclaim or disclaim itself as a valid target.

•	Specify termination conditions, such as timeout or range.

•	Identify areas in which tapping terminates the input session.

•	Do any combination of the above.

In processing PE_GETPCMINFO, the child window must fill in a PCMINFO structure that describes how pen interaction should proceed. If the candidate window wishes to receive input from the pen and become a true target, it can provide the coordinates of a bounding rectangle in the rectBound member of PCMINFO. The bounding rectangle constitutes the target area of the child window; inking that occurs within or nearest a bounding rectangle is sent to the window associated with the rectangle. If the child window does not process PE_GETPCMINFO, Windows does not consider the window a candidate for pen input but also does not prevent ink from overwriting the window.

DefWindowProc collects all bounding rectangles and exclusion rectangles provided by the descendant windows and creates a master PCMINFO structure that describes the situation.

For information about how to initialize and make changes to a PCMINFO structure, see the "Starting the Chain of Events" section in Chapter 3, "The Writing Process." See Chapter 11, "Pen Application Programming Interface Structures," for descriptions of the structure members.


 Step 4: PE_GETINKINGINFO Message

Each target specified in the TARGINFO structure created in step 2 that has a valid bounding rectangle from step 3 receives a PE_GETINKINGINFO message. In response to this message, a child window can set ink color and ink width, establish the ink clip region, and specify whether or not Windows should automatically restore the screen and erase the ink after pen interaction has ceased.

Processing the message through DefWindowProc sets the system default ink attributes, uses the window boundary for the ink clip region, and forces automatic restoration of the screen after input. DefWindowProc merges the responses from each target into a master INKINGINFO structure.


 Step 5: Master PCMINFO and INKINGINFO Structures

Having created a master PCMINFO structure and a master INKINGINFO structure, DefWindowProc sends one more PE_GETPCMINFO message and PE_GETINKINGINFO message to the parent window that contains the child targets. This provides the parent window a final opportunity to examine and change, if necessary, the system's assumptions about the impending inking event. For example, the parent window can specify a default ink color in the INKINGINFO structure or set an exclusion region around a screen object that had not, for some reason, handled the PE_GETPCMINFO message.


 Step 6: PE_BEGINDATA Message

When pen activity destined for a particular target begins, the target first receives a PE_BEGINDATA message. This message provides the target a way to inform DoDefaultPenInput what to do with the data. If DefWindowProc handles this message, it assigns the pen data to a default HRC object and uses the system recognizer for recognition. (For more information about the system default recognizer, see "Recognizer" and "Creating the HRC.") Alternatively, the target can attach its own HRC for recognition, an HPENDATA to store the data, or a private object of some kind associated with the target.

To govern recognition, an application should handle PE_BEGINDATA, create and configure its own HRC object, and identify the object with the dwData member of the TARGET structure pointed to by the message's lParam. The application calls the CreateCompatibleHRC function to create the HRC object and set its context. This forces the system to use the new HRC. For more information about HRC and how to create one with CreateCompatibleHRC, see "The HRC Object."


 Step 7: PE_MOREDATA Message

Multiple PE_MOREDATA messages can arrive at each target window to indicate more pen data is available. Generally, an application passes PE_MOREDATA on to DefWindowProc for default processing. DefWindowProc accrues new data by adding it to the HRC or HPENDATA object established in step 6.


 Step 8: PE_ENDDATA Message

The PE_ENDDATA message informs a target window that input for the target has ceased. The message's lParam points to a TARGET structure, the dwData member of which identifies the HRC or HPENDATA created in step 6. If recognizing

input through an HRC object, the application should let DefWindowProc handle this message. However, DefWindowProc will destroy an HPENDATA object when processing PE_ENDDATA. To preserve the HPENDATA, the application has two choices:

•	Trap the message, preventing it from reaching DefWindowProc. In this case, the HPENDATA object outlives the input session. Note that an HPENDATA object occupies memory in the system heap. When finished, the application must remove the object by calling DestroyPenData to avoid wasting resources.

•	Alternatively, copy the HPENDATA object with DuplicatePenData before letting the PE_ENDDATA message fall through to DefWindowProc. However, this approach has no advantage over the preceding method, merely trading the original object for its clone. Again, the application is responsible for destroying the new HPENDATA object.


 Step 9: PE_RESULT Message

The PE_RESULT message arrives only if the application has specified an HRC object in step 6, rather than an HPENDATA or other object. The message signals the target window that recognition results are ready. This message differs slightly from the others in that its lParam holds the HRC handle and not a pointer to a TARGET structure. If DefWindowProc handles PE_RESULT, it converts the recognizer's best guess to a string of characters and sends them to the target window as WM_CHAR messages. Gestures are also converted to appropriate messages, such as WM_COPY or WM_PASTE.

If the application handles the message, it must not destroy the HRC for the default system recognizer. Because DoDefaultPenInput created the default HRC, it expects to destroy it as well. The application must not destroy objects it did not create.

At this point, an application can process any of the results itself. For example, it might check for a recognized gesture such as the lasso or cut gesture. The procedure for examining gestures at this point involves three steps:

1.	Retrieve any recognized gesture symbols from the HRCRESULT object by calling the GetResultsHRC function with the GRH_GESTURE argument.

2.	If this call indicates the recognizer has found a gesture, the application then calls the GetSymbolsHRCRESULT function to see if the gesture is a lasso or X mark.

3.	If the gesture is a lasso or X mark, the application should examine the data further to determine the size of the gesture, as outlined in the following example.

If the first or second test fails, indicating the recognizer has found no lasso or X mark, the application should pass the PE_RESULT message to DefWindowProc for text processing. Note that the lasso and cut gestures cannot exist with other gestures; therefore, the following code allocates only one HRCRESULT object because it examines at most a single gesture:

HRCRESULT	hresult;	// Look at only the first gesture

HPENDATA	hpendata;	// Points that comprise the gesture

HRGN	hrgn;	// Screen region of the gesture

SYV	syv;	// Symbol value of the gesture

UINT	uRgnType;	// Region type: X or LASSO

int	cGest;	// Count of gestures in results

.

.

.

switch ( wParam )	// Handle WM_PENEVENT messages

{

case PE_RESULT:

// Check for gesture

cGest = GetResultsHRC( (HRC) lParam,	// HRC handle

  GRH_GESTURE,	// Gestures only

  (LPHRCRESULT)&hresult,	// Buffer

  1 );	// Get one result

// If one gesture available, get its symbol

if (cGest == 1)

{

GetSymbolsHRCRESULT( hresult,	// HRCRESULT handle

 0,	// Index to 1st syv

 (LPSYV) &syv,	// Symbol buffer

 1 );	// Get 1 symbol

//

// If the gesture is lasso or x, collect the

// points that make up the gesture

//

if (syv == SYV_LASSO  ||  syv == SYV_CUT)

{

hpendata = GetPenDataHRC( (HRC) lParam );

if (hpendata)

{

// Step 1:  Get region of the gesture

uRgnType = (syv==SYV_LASSO) ? CPDR_LASSO : CPDR_BOX;

hrgn = CreatePenDataRegion( hpendata, uRngType );

// Step 2: Determine what text lies within the

// region.  If the gesture covers more than one

// letter of a word but not the entire word, assume

// it's meant for entire word.

.

.

.

// Step 3:  Either select . . .

if (syv == SYV_LASSO)

{

.	// Select the text

.

.

}

// . . . or delete the text

else

{

.	// Delete the text

.

.

}

DeleteObject( hrgn );

DestroyHPENDATA( hpendata );

}

}

}

break;

default:

DefWindowProc( hwnd, message, wParam, lParam );

}

As the previous code shows, applying a gesture to text requires three steps:

1.	Call the CreatePenDataRegion function to find the region covered by the gesture.

2.	Determine the text that lies within the gesture's region using the Windows GetTextExtent function or some other method.

3.	Select or cut the text, according to the gesture.


 Step 10: PE_ENDINPUT Message

Windows sends the PE_ENDINPUT message to the window that received the PE_BEGININPUT submessage in step 1. An application can perform any necessary cleanup chores at this time, but should pass the PE_ENDINPUT message to DefWindowProc.


 The Writing Process

This chapter begins a series of three chapters that describe the three main stages of converting pen input into valid computer data. This chapter looks at the writing process. The next two chapters discuss the processes of inking and recognition.

The writing process includes the various ways a user can write input to a pen-based application. These involve not only writing words and scribbling figures with a pen, but also gesturing with predefined pen movements and tapping an on-screen keyboard.

This chapter is divided into three main sections, each discussing a different method by which an application can accept writing from the pen. The first section describes the pen edit controls, which are pen-based versions of a standard Windows edit control. The second section discusses ink input application programming interface (API) services, which allow an application to govern pen interaction at a lower level than edit controls. The final section briefly describes the on-screen keyboard.


 Pen Edit Controls

The Pen API provides three different edit controls for pen input — the handwriting edit (hedit ), boxed edit (bedit), and ink edit (iedit) controls. (The first letter of the control name is pronounced separately, as in "h-edit.")

The first two controls are designed for text input. Characters written in an hedit or bedit control are passed to one or more recognizers and interpreted as equivalent digital text. Usually, the interpreted text replaces the handwritten glyphs within the control window after the recognition finishes. The iedit control serves as a drawing area. With the exception of gestures, the iedit control does not attempt to recognize written input but merely preserves the pen data in its raw form.

An application creates a pen edit control through the Windows CreateWindow function, specifying a class of HEDIT, BEDIT, or IEDIT. The next three sections describe the pen edit controls in detail and provide examples of how to create them.


 The hedit Control

Except under special circumstances, the hedit control displays two sets of text. First, the handwritten characters appear as written by the user, formed by the ink trail of the pen. When the writing is recognized, the handwritten ink disappears from the screen, replaced within the control window by the interpreted characters as determined by the recognizer. The interpreted text appears in a Windows font as though typed at the keyboard.

The following instruction creates a multiline hedit control with left justification:

hwndHedit = CreateWindow( "HEDIT", NULL,

                           ES_MULTILINE | ES_LEFT |

                           WS_CHILD | WS_VISIBLE,

                           CW_USEDEFAULT, CW_USEDEFAULT,

                           CW_USEDEFAULT, CW_USEDEFAULT,

                           hwndParent, CHILD_ID, hinstCurrent, NULL );

The styles of ES_MULTILINE and ES_LEFT do not constrain the freeform approach of handwriting in an hedit control. The user can write anywhere on the pen tablet allowed by the control — usually within or near the control window. The styles determine the format of the resulting interpreted text displayed in the control.

The hedit control is a pen-aware version of the default Windows 3.1 edit control. The hedit control not only supports handwritten characters and gestures, but also responds normally to keyboard and mouse events in the same way as an edit control. An application can use an hedit control anywhere a regular edit control will work, including dialog boxes. In fact, specifying EDIT class for a control in Windows 95 automatically creates an hedit control. The hedit control is visually identical to a standard control except that it displays a pen pointer instead of an I-beam pointer. Single-line hedit controls also display a lens button when a pen is present. When specifying an HEDIT control for a dialog box in a resource, use the DIALOGEX resource. Refer to the DIALOGEX resource description in the Win32 SDK tools documentation for a more information on using the HEDIT control class.

With a window style of ES_READONLY, an hedit window can accept no pen input. The pointer within the control does not change to a pen.

An hedit control processes tabs and carriage returns differently depending on whether they are entered as gestures or typed from the keyboard. If the user draws a tab or carriage return gesture in a multiline hedit control, the control inserts a tab or carriage return character into the text. For tabs and carriage returns entered from the keyboard, an hedit control in a dialog box mimics the standard dialog box behavior — that is, pressing the TAB or RETURN key passes control respectively to the TABSTOP or DEFPUSHBUTTON statement given in the dialog box template.


 hedit Control Messages

The Pen API defines the WM_PENCTL message and its alias, WM_HEDITCTL. An application can send the WM_PENCTL message to an hedit control like this:

lRet = SendMessage( hwndHedit, WM_PENCTL, wParam, lParam );

The wParam parameter of WM_PENCTL contains an identifier for an HE_ submessage, as listed in Chapter 12, "Pen API Messages." The lParam specifies a value dependent on the HE_ submessage. For more information about the wParam and corresponding lParam values, see the entry for WM_PENCTL messages in Chapter 12, "Pen Application Programming Interface Messages."

Sizing the Writing Area with Control Messages

An hedit control must make allowances for handwriting input by providing a sufficiently large area in which to write. Typically, this area incorporates the control window itself plus an ample margin around the border of the window. Besides increasing user comfort, this extra space helps ensure parts of written characters are not inadvertently clipped, making them difficult to recognize. For example, the cut gesture X often extends above the text selected for deletion. Losing part of the gesture at the edge of the control window can make it less recognizable.

Note that adjusting a control's writing area does not change the appearance or size of the control window on the screen. It only specifies an invisible area overlaying the window; any ink within the writing area belongs to the control. It is possible, though not recommended, to enlarge the writing areas of two nearby controls so that they overlap. In this case, Windows assumes ink within the overlapping area belongs to only one of the control windows, according to normal Windows z-ordering.

The Pen API provides two methods for an application to adjust the size of the control writing area. These methods involve either receiving a PE_SETTARGETS submessage or sending an HE_SETINFLATE submessage. The following sections describe both methods.

PE_SETTARGETS Submessage

As described in the "DoDefaultPenInput Messages" section in Chapter 2, Windows sends a PE_SETTARGETS submessage to the application's window procedure before ink collection begins. This submessage gives the application the opportunity to set the target writing areas by specifying a new TARGINFO structure identified by lParam. The structure member rgTarget contains an array of TARGET structures, one for each target area. The rectangle in the rectBound member of TARGET specifies each target's writing area. The following code fragment shows how to set a writing area 4 pixels larger than the boundaries of the child window:

#define      NTARG	3               // Number of target windows

#define      MARGIN	4               // Inflation margin in pixel units

LPTARGINFO   lpti;                   // Allocate new TARGINFO structure

HWND         hwndCtl[NTARG];         // Handles to child windows

RECT         rect;                   // Bounding rectangle of child

RECTL        rectl;                  // Long version of bounding rect

HGLOBAL      h;

.

.

.

h = GlobalAlloc( sizeof( TARGINFO ) + (NTARG - 1)*sizeof( TARGET ) );

lpti = GlobalLock( h );

lpti->cbSize = sizeof( TARGETINFO );

lpti->wFlags    = 0;

lpti->htrgOwner = HtrgFromHwnd( hWnd );

lpti->cTargets  = NTARG;

for (i=0; i < NTARG; i++)

{

GetWindowRect( hwndCtl[i], (LPRECT) &rect );

rectl.left   = (LONG) (rect.left   - MARGIN);    // Inflate

rectl.top    = (LONG) (rect.top    - MARGIN);    //   rectangle

rectl.right  = (LONG) (rect.right  + MARGIN);    //   by MARGIN

rectl.bottom = (LONG) (rect.bottom + MARGIN);    //   pixel units

lpti->rgTarget[i].idTarget         = i;

lpti->rgTarget[i].htrgTarget       = HtrgFromHwnd( hwndCtl[i] );

lpti->rgTarget[i].rectBound.left   = rectl.left;

lpti->rgTarget[i].rectBound.right  = rectl.right;

lpti->rgTarget[i].rectBound.top    = rectl.top;

lpti->rgTarget[i].rectBound.bottom = rectl.bottom;

}

If the Windows DefWindowProc function handles the PE_SETTARGETS submessage, it creates a TARGINFO structure identifying all child windows as targets. DefWindowProc does not inflate writing areas; that is, it sets the writing area for each child window within the window borders.

HE_SETINFLATE Submessage

An application can also enlarge a control's writing area by sending the submessage HE_SETINFLATE to the control window specifying a RECTOFS structure:

typedef struct {

                  int  dLeft;            // Left margin

                  int  dTop;             // Top margin

                  int  dRight;           // Right margin

                  int  dBottom;          // Bottom margin

               } RECTOFS FAR * LPRECTOFS;

The RECTOFS structure does not contain the coordinates of a writing rectangle per se; instead, it contains the dimensions of the additional writing margin around the control window. The margins specify how many pixel units to add to each member of the windows rectangle. Margins conform to the x-y screen coordinate system. Thus, to inflate a writing area, specify negative values for dLeft and dTop as shown here:

#define     MARGIN    4              // Inflation margin in pixel units

RECTOFS     rectofs = { -MARGIN,     // Structure of window margins

                        -MARGIN,

                         MARGIN,

                         MARGIN};

.

.

.

wParam = HE_SETINFLATE;

lParam = (LONG)((LPRECTOFS) &rectofs);

lRet   = SendMessage( hwndHedit, WM_PENCTL, wParam, lParam );

An application can retrieve a window's current inflation margins with the submessage HE_GETINFLATE like this:

wParam = HE_GETINFLATE;

lParam = (LONG)((LPRECTOFS) &rectofs);

lRet   = SendMessage( hwndHedit, WM_PENCTL, wParam, lParam );

This call fills the RECTOFS structure pointed to by lParam with the control window's current margins.

Notification Messages

An hedit window's parent receives the same EN_ notification messages as the parent of a standard edit window. The parent receives a WM_COMMAND message in which the low-order word of the wParam parameter contains the control ID number and the lParam parameter contains the edit window handle. In 16-bit applications, the high-order word of lParam also contains the notification value. In 32-bit applications, the high-order word of wParam contains the notification. The hedit control also provides HN_ notifications, described in Chapter 12, "Pen Application Programming Interface Messages."

The hedit control also sends a WM_CTLINIT message to its parent windows when created. The wParam parameter holds the constant CTLINIT_HEDIT and lParam points to a CTLINITBEDIT structure. The structure contains the current system assumptions concerning the appearance and behavior of the hedit control. The parent window has the option of changing any of these assumptions.


 Printing an Edit Control

An application can display a pen edit control in any device context by sending the control a WM_PRINT message. The message's wParam contains the HDC handle for the device context. This technique, which applies to all pen edit controls, provides a means for printing the contents of a control window.


 The bedit Control

The bedit (boxed edit) control is a variation of the hedit control. All characteristics of an hedit control described in the preceding section also apply to the bedit control, with two exceptions:

•	A bedit window displays writing guides in which the user must write. Interpreted text returned from the recognizer replaces the handwritten characters within the guides.

•	A bedit control does not support edit control styles ES_READONLY, ES_CENTER, ES_LEFT, and ES_RIGHT. (Text in a bedit is left aligned.)

An application can specify guides either as a comb or as a set of boxes, as shown in Figure 3.1. The comb consists of a horizontal line with spaced tick marks. The user writes individual characters between the marks.

These visual guides can greatly improve recognition because they remove from the recognizer the significant burden of correctly segmenting the text into separate characters. For example, consider Figure 3.2, which shows a word written in an hedit control.

In this case, the recognizer would probably have difficulty choosing between the words "clean" and "dean" because of the narrow spacing between the first two strokes. The bedit control removes such ambiguities. By writing within the guides of a bedit control, the user implicitly informs the recognizer what strokes compose a single character.

For a description of how the bedit control has been improved in Windows 95, see Appendix A, "Differences Between Versions 1.0 and 2.0 of the Pen Application Programming Interface."

Windows treats characters in a bedit control as a continuous stream of text. If the control contains more than one row, text wraps at each row end without regard to word boundaries. The EM_SETWORDBREAK message has no effect on a boxed edit control.

An application creates a bedit control with the Windows CreateWindow function, specifying a window class of BEDIT. The following code shows how to create a multiline bedit control:

hwndBedit = CreateWindow( "BEDIT", NULL,

                           ES_MULTILINE | WS_CHILD | WS_VISIBLE,

                           CW_USEDEFAULT, CW_USEDEFAULT,

                           CW_USEDEFAULT, CW_USEDEFAULT,

                           hwndParent, CHILD_ID, hinstCurrent, NULL );

The BOXLAYOUT structure governs the height and style of the box grid within the bedit control. Its style member accepts one of the following BXS_ values:

Style	Description
BXS_NONE	Resets current box style to the default comb style.
BXS_RECT	Specifies a grid of closed rectangular boxes.
BXS_BOXCROSS	Specifies small crosses at the center of each box. This is used mainly to aid recognition of certain Far Eastern languages.
To set box height and style, fill a BOXLAYOUT structure with the desired values and pass it as a submessage of WM_PENCTL, as shown here:

    BOXLAYOUT boxlayout;

.

.

.

    boxlayout.cyCusp    = 6;             // Box sides are 6 pixels high

    boxlayout.cyEndCusp = 6;             // Ends should be the same

    boxlayout.style     = BXS_RECT;      // Grid of closed boxes

    iRet = SendMessage( hwndHedit, WM_PENCTL, HE_SETBOXLAYOUT,

                        (LONG)((LPBOXLAYOUT) &boxlayout) );

Refer to Chapter 11, "Pen Application Programming Interface Structures," for a more detailed description of the BOXLAYOUT structure. The next section explains how to set the system assumptions about the appearance of a bedit control.


 bedit Control Messages

The bedit control sends a WM_CTLINIT message to its parent windows when created. The wParam parameter holds the constant CTLINIT_BEDIT and lParam points to a CTLINITBEDIT structure. The structure contains the current system assumptions concerning the appearance and behavior of the bedit control. The parent window has the option of changing any of these assumptions.

An application can also initialize a bedit control for a dialog box by using a DIALOGEX resource  in the dialog resource file (.RC) and specifying a CONTROL statement with a class of BEDIT or specifying a BEDIT edit control class. In this case, the control still sends the WM_CTLINIT message.  However, the CTLINITBEDIT structure reflects the specifications of the BEDIT class statement instead of the system defaults. As before, the parent window can modify the structure if desired. Refer to Chapters 11 and 12 for descriptions of the CTLINITBEDIT structure and WM_CTLINIT message, respectively. Refer to the DIALOGEX resource description in the Win32 SDK tools for more information on using the BEDIT control class.

The EM_LIMITTEXT message deserves special mention because it has changed slightly from version 1.0 of the Pen API. The message now sets the maximum number of bytes of text, rather than the number of boxes, that the control can hold. Note that although a newline character occupies only one box, the newline itself — carriage return and linefeed — takes 2 bytes. Certain Far Eastern languages also require 2 bytes per character.

Thus, the EM_LIMITTEXT message has the same effect on bedit controls as it does on hedit and edit controls. For example, the instruction

SendMessage( hwndBedit, EM_LIMITTEXT, 50, 0L );

sets to 50 the number of bytes the bedit control can accept. This has the following effects on the control:

•	If the user attempts to write the 51st byte, the control beeps and ignores the input.

•	If the user inserts text into existing text, the control beeps and ignores further input after the total number of bytes equals 50.


 Using bedit Controls in Dialog Boxes

Windows determines the number of box cells that can fit within a control window based on the window dimensions and the cell widths given in a GUIDE structure. Although the Pen API does not provide a way to explicitly set the number of boxes displayed in a bedit control, an application can imply the number by adjusting the size of the control window or the size of the cells. Under certain circumstances, however, Windows may change the dimensions of a bedit control in a dialog box, thus potentially decreasing or increasing the number of box cells within the bedit.

Usually, this makes no difference to the developer or the user. But if your application must always show a specific number of boxes within a bedit, this section explains how to forestall or handle any changes.

By default, Windows sizes a dialog box and its controls based on the system font. If the dialog template requests a different font with a FONT statement and the font is not available when Windows creates the dialog box, Windows selects an available font that best matches the requested font. It then scales the dialog box and the controls within it according to the size of the selected font, but does not also scale the bedit guides. Thus, although a bedit window may change in size because of new scaling, the size of the boxes within it remain the same. For this reason, the window may end up with fewer or more cells than the programmer expects.

To ensure a bedit window always displays a specific number of cells, use one of the following techniques:

•	Remove the FONT statement from the dialog template and let Windows use the system font in the dialog box controls.

•	Specify a font likely to be always available. However, this technique cannot guarantee correct results for an application that must run under many different configurations of Windows.

•	Readjust the size of the bedit window after Windows has changed it. When processing WM_INITDIALOG, an application can call the GetWindowRect function to see whether Windows has resized the bedit control window. If so, the application can restore the window's original size with either the MoveWindow or SetWindowPos function.

Note that this technique assumes a generous blank area surrounds the control, so that if your application enlarges the control window while Windows shrinks the rest of the dialog box, the various components of the dialog box do not overlap.

•	Recalculate the GUIDE values if Windows has changed the window size.

By default, all the controls within a dialog box use the font selected for the dialog box. An application can set a different font in bedit controls within the dialog box by sending a WM_SETFONT message when processing WM_INITDIALOG.


 The iedit Control

The ink edit (iedit) control provides easy formatting and manipulation of ink input. It is not designed for text input, and in this regard differs from the other two pen edit controls, hedit and bedit. Think of iedit instead as a convenient drawing area suitable for sketches, diagrams, signatures, doodling — any sort of pen input that does not need to be recognized as text. However, an application can collect handwritten text as input from an iedit control and later transfer it to an hedit or bedit control for editing, if desired, or send it to a recognizer for recognition.

An iedit control ignores most keyboard input because the user cannot type text into an iedit window. However, an iedit control supports the following keystrokes and key combinations as convenient shortcuts:

Keystroke or key combination	Effect
DEL	Delete selected strokes.
CTRL+X	Cut selected strokes to clipboard.
CTRL+C	Copy selected strokes to clipboard.
CTRL+V or CTRL+P	Paste stroke from clipboard
CTRL+A	Select all strokes.
CTRL+Z	Undo last command.
An iedit window can scroll like any other edit control. Specifying a window style incorporating WS_VSCROLL and WS_HSCROLL creates a scrollable drawing area of 32,767 by 32,767 coordinate units. Scroll bars appear on the iedit window only when ink resides outside the current visible area. This behavior mimics the Control Panel window, which displays scroll bars only when an icon lies hidden beyond the boundaries of the window.

The following sample procedure demonstrates how to use iedit to create a drawing area within a single window. After creating the main parent window, the procedure InitInstance copies the window's coordinates into a RECT structure. It then uses the results when sizing the child iedit window so that the child window entirely overlays its parent.

HWND    vhwndMain;                   // Main window

HWND    vhwndIedit;                  // iedit control window

.

.

.

BOOL InitInstance( HINSTANCE hInstance, int nCmdShow )

{

    RECT    rect;                    // Main window rectangle

    //

    // Create main window

    //

    vhwndMain = CreateWindow(

        "StylusClass",               // Window class name

        "Stylus Sample Program",     // Text for title bar

        WS_OVERLAPPEDWINDOW,         // Window style

        CW_USEDEFAULT,               // Default horizontal position

        CW_USEDEFAULT,               // Default vertical position

        CW_USEDEFAULT,               // Default width

        CW_USEDEFAULT,               // Default height

        NULL,                        // No parent

        NULL,                        // Class default menu

        hInstance,                   // Window owner

        NULL );                      // Unused pointer

    if (!vhwndMain)                  // If can't create window,

        return FALSE;                //   exit

    //

    // Create iedit control window within main window

    //

    GetClientRect( vhwndMain, (LPRECT) &rect );

    vhwndIedit = CreateWindow(

        "IEDIT",                     // Window class name

        NULL,                        // No title bar

        WS_CHILD | WS_VISIBLE |      // Window style

        WS_HSCROLL | WS_VSCROLL,

        0,                           // Overlay control window

        0,                           //   onto parent window

        rect.right - rect.left,      // Use parent width

        rect.bottom - rect.top,      //   and parent height

        vhwndMain,                   // Parent window handle

        (HMENU) CHILD_ID,            // Child ID

        hInstance,                   // Window owner

        NULL );                      // Unused pointer

    if (!vhwndIedit)                 // If problem,

        return FALSE;                //   return error code

    SetFocus( vhwndIedit );            // Give control immediate focus

    ShowWindow( vhwndMain, nCmdShow ); // Display main window

    UpdateWindow( vhwndMain );         // Force WM_PAINT message

    return TRUE;                       // Return success

}


 iedit Control Messages

When created, an iedit control behaves similarly to a bedit control, as described in the "bedit Control Messages" section. The iedit sends a WM_CTLINIT message to its parent window. The message's wParam parameter contains the constant CTLINIT_IEDIT and lParam points to a CTLINITIEDIT structure. The structure contains the current system assumptions concerning the appearance and behavior of the iedit control.

An application can initialize an iedit control in a dialog box by specifying the desired attributes in an IEDIT statement in the .RC file. See "bedit Control Messages" for details. For information about the CTLINITIEDIT structure, see Chapter 11.


 Ink Input

The pen edit controls discussed previously provide a simple and efficient method for an application to accept handwritten input. Pen edit controls continue the philosophy and design of a standard Windows edit control; that is, they place the burden of getting user input on the system rather than the application.

However, ink input API services also offer an application low-level control over the writing process. Ink input allows an application to gather raw data from the pen, then process it in any way it wishes. For example, the application can manage its own inking or even postpone inking to a later time. It can massage or filter the pen data in some way — say, by rotating an image based on pen movement. It can pass the data to a handwriting recognizer or simply throw the data away. Ink input offers an application greater freedom with ink data than simply parsing it for characters.

As you might expect, the increased control afforded by ink input requires increased programming effort. The flexibility of ink input does not allow a simple recipe of tasks, but in broad terms the three main steps are as follows:

1.	Start the chain of events.

2.	Collect and display data.

3.	Process the data.

An application can rely on the DoDefaultPenInput function to collect and process ink input. For a description of this function, see Chapter 2, "Starting Out with System Defaults." The following sections focus on the lowest-level API services. Through these low-level services, an application has complete control over ink input. These are the same services DoDefaultPenInput calls internally. If you have read Chapter 2, the message traffic described here will seem familiar.

The PENAPP sample application described in Chapter 7, "A Sample Pen Application," demonstrates how to use the low-level API services for ink input. Most of the code fragments in the following sections appear in the PENAPP.C source listing located in the SAMPLES\C\PENAPP directory.


 Starting the Chain of Events

When an application receives a WM_LBUTTONDOWN message, that message signals the beginning of an input session. (For a definition of input session, see "Beginning an Input Session" in Chapter 2.) The following code fragment shows how to handle the message when not calling DoDefaultPenInput:

INKINGINFO   inkinfo;

PCMINFO      pcminfo;

HPCM         hpcm;

LONG         lExInfo;

int          iRet = TRUE;

.

.

.

switch (wMsg)

{

case WM_LBUTTONDOWN:	  // Pen down (maybe)

lExInfo = GetMessageExtraInfo();

if (IsPenEvent( wMsg, LOWORD(lExInfo) ) 	// If true pen down,

{	  //   take the actions

.	  //   described in the

.	  //   text below

.

}

else	  // No, it's a mouse

{	  //   button down

The application initializes a PCMINFO structure and INKINGINFO structure in preparation for data collection and display. DoDefaultPenInput handles this task automatically, then provides the application an opportunity to selectively change the default values. (For a description of the submessages PE_GETPCMINFO and PE_GETINKINGINFO, see "DoDefaultPenInput Messages" in Chapter 2.) If it does not call DoDefaultPenInput, an application must initialize the structures itself, as shown here:

#define         TIME_OUT      1000               // Time-out in msec

PCMINFO         pcm;

INKINGINFO      ink;

.

.

.

pcm.cbSize = sizeof( PCMINFO );          	       //  Required

pcm.dwPcm = PCM_TIMEOUT | PCM_RECTBOUND;        //  When to end session

pcm.dwTimeOut = TIME_OUT;                       //  Time-out value in ms

GetWindowRect( hwnd, (LPRECT) &pcm.rectBound ); //  Use window borders

ink.cbSize    = sizeof( INKINGINFO );           //  initialize

.                                           //   the INKINGINFO

.                                           //   structure "ink"

.

The above lines specify that the input session ends when the pen travels (or taps) outside the hwnd window or pauses for the number of milliseconds set by the constant TIME_OUT. For a detailed description of these structures, see the entries for PCMINFO and INKINGINFO in Chapter 11, "Pen Application Programming Interface Structures."


 Collecting and Displaying Data

After initializing the necessary structures, the application calls StartPenInput to begin the process of collecting ink data:

hpcm = StartPenInput( hwnd, LOWORD (lExtraInfo),

                      (LPPCMINFO) &pcm, NULL );

The returned value hpcm is a handle to the pen collection mode — that is, the input session — that StartPenInput begins. The variable lExtraInfo is the value returned by GetMessageExtraInfo called when first processing the message WM_LBUTTONDOWN (see the preceding code fragment). Note that the StartPenInput call initiates ink collection, not ink display. The application must take separate steps to begin inking immediately after StartPenInput returns.

Inking is the process of displaying a trail of bits behind the tip of the pen as it moves across the surface of the digitizer, simulating the ink dropped by a real pen. If necessary, an application can take on the burden of real-time inking by hooking hardware interrupts with SetPenHook and calling the appropriate graphics device interface (GDI) functions to incrementally display ink. However, the Pen API provides a much simpler and more convenient method with the StartInking function.

As the PCMINFO structure governs StartPenInput, the INKINGINFO structure determines how StartInking operates. To turn on inking with StartInking, an application supplies the handle returned by StartPenInput and a pointer to the initialized INKINGINFO structure, like this:

iRet = StartInking( hpcm, LOWORD (lExtraInfo),

                    (LPINKINGINFO) &ink );

StartInking offers flexibility in how it displays ink. By modifying values in the INKINGINFO structure, an application can change ink color as the pen moves over a specified screen area or it can prevent ink from overwriting a screen object. With the wFlags member of INKINGINFO, an application can request automatic screen restoration to erase the ink. In this case, Windows replaces the ink trail with the original screen contents overwritten by the ink. This is much faster and simpler than repainting an entire window. Alternatively, an application can prevent ink erasure when pen input ends if, for example, it wants to preserve annotations or other handwritten notes on the screen. The StartInking function allows both scenarios.

When StartPenInput returns, a stream of WM_PENEVENT messages begins to arrive at the application window procedure. These messages contain submessages that represent current pen activity, such as PE_TERMINATING, PE_PENMOVE, PE_PENDOWN, and PE_PENUP. These submessages represent milestones in the system's ongoing process of collecting data from the pen driver. Each message affords an application the opportunity to gather the raw pen data that has accumulated since the last WM_PENEVENT message.

Windows maintains an internal buffer for data collection, informally named "the ten-second buffer" as a reminder of its limitations. An application should regularly drain the internal buffer by copying data from it at every opportunity afforded by the WM_PENEVENT messages. If it responds to no other event, the application must at least collect data when it receives the PE_BUFFERWARNING submessage, which indicates the internal buffer is more than half full.

To gather the data, an application calls GetPenInput. This can be done either in a polling model or in an event-driven model.

In the polling model, the application must repeatedly call GetPenInput to get data. It is important for the application to yield periodically; for example, by calling the PeekMessage function. A fast loop can potentially process the points before the system can collect more. In this case, successive calls to GetPenInput return 0 until the user writes some more. Polling is typically terminated when GetPenInput detects and returns a termination condition specified in StartPenInput.

In the event model, the application calls GetPenInput in response to each WM_PENEVENT message. The following fragment shows a typical message handler that accumulates ink coordinates in an array of POINT structures. The example assumes StartPenInput has already been called:

POINT       rgPt[MAX_POINTS];            // Array of POINT structures

STROKEINFO  si;                          // Receives pen stroke info

.

.

.

switch (wParam)                          // Process WM_PENEVENT message

{

case PE_PENDOWN:                     // On any of these events,

case PE_PENMOVE:                     //   get all points currently

case PE_PENUP:                       //   in the internal buffer

case PE_TERMINATING:

case PE_BUFFERWARNING:

GetPenInput( hpcm, (LPPOINT) rgPt, NULL, NULL,

                      MAX_POINTS, (LPSTROKEINFO) &si );

//

// Latest batch of pen coordinates is now collected

// into rgPt array.  At this point, the coordinates can be:

//	(1) Passed to a recognizer (or recognizers)

//	(2) Passed to a target or control

//	(3) Placed into an HPENDATA object

//

.

.

.

break;

case PE_TERMINATED:

// Input session has ended. Do any required

// clean-up work and display the results.

.

.

.

break;

The example continually calls GetPenInput while the pen is in motion until it receives a PE_TERMINATING submessage, indicating the data flow is about to stop. Windows sends a PE_TERMINATING message when it detects one of the termination conditions specified in the PCMINFO structure. Typically, the input session ends when the user taps the pen outside a given tablet area or when a specified period of pen inactivity elapses.

An application may need to call StopPenInput to stop further data collection. The call to StopPenInput is not necessary if the input session ends because of a condition defined in the PCMINFO structure. In this case, the system calls StopPenInput internally. However, if the application terminates the input session for any other reason, it must call StopPenInput explicitly. Unless your application defines all possible termination conditions in a PCMINFO structure, it should call StopPenInput on detection of a condition that requires termination. Even if the system has already called the function, subsequent calls do no harm.

The preceding description also applies to StopInking, provided the application has called StartInking to display ink. The system calls StopInking automatically if it detects one of the termination conditions defined in the PCMINFO structure; otherwise, the application should call StopInking explicitly when required.


 Processing the Data

The GetPenInput function accumulates the coordinates of the pen stroke in an array of POINT structures and places information about the stroke in a STROKEINFO structure. This data is "raw" in that it represents a literal history of the pen movement. Some applications will require no more than this. However, further processing of the raw data using other functions of the Pen API usually requires placing the data into an HPENDATA or HRC object.

The next two chapters examine these objects thoroughly and continue the code fragment outlined previously. Chapter 4, "The Inking Process," describes how an application can alter or manipulate ink data with an HPENDATA object. Chapter 5, "The Recognition Process," describes the HRC object, which pertains solely to handwriting recognition.


 The On-screen Keyboard

The hedit and bedit controls automatically provide user access to the on-screen keyboard. In other situations, an application can display the on-screen keyboard as required by calling the ShowKeyboard function.

Besides displaying and hiding the on-screen keyboard, ShowKeyboard can also move and minimize the display and select different keyboard types. For a detailed description of the capabilities of ShowKeyboard, see Chapter 10, "Pen Application Programming Interface Functions." For other considerations concerning ShowKeyboard, see the "Recognition: Use and Misuse" section in Chapter 6.


 The Inking Process

This chapter introduces the inking process, in which an application collects and manipulates ink data written by the user. The inking process is a logical next step from the writing process, described in the preceding chapter. In the writing process, the application provides the means for the user to enter ink. In the inking process, the application assembles the ink data, optionally modifies it, and applies it to some task.

The inking process pertains to ink data collected for its own sake rather than immediately passed on to a recognizer for interpretation. Although an application can later submit gathered data to a recognizer, the inking process deals with ink that "stays ink" rather than serving as transitory symbols immediately converted into recognized characters.

The HPENDATA data object serves as the major instrument in the inking process. The first part of this chapter describes HPENDATA and the various application programming interface (API) functions that serve it. Example code fragments throughout illustrate how to store and manage ink data with the HPENDATA services.

An application can refer to the data in an HPENDATA object by stroke and point indices, or time intervals. For viewing and manipulating ink data that falls within specified time intervals, the Pen API provides the HINKSET object. The last section of this chapter, "The HINKSET Object," examines HINKSET and its corresponding API functions.


 The HPENDATA Object

An application accesses ink data with HPENDATA, which stands for "a handle to pen data." Windows stores the pen data in a block of memory, called the HPENDATA object. This data structure is analogous to the other Window "H" data types such as HDC, HCURSOR, and HPEN. HPENDATA shares certain similarities with these data types:

•	The handle references an internal data structure that resides in memory.

•	Windows provides various API functions that operate on the data.

•	Developers should ignore the details of the underlying data structure and use the API functions alone to perform the required work.

The remainder of this chapter discusses the HPENDATA object and the API functions used to manipulate the data it contains.


 Overview of HPENDATA

Windows allocates the HPENDATA object with an internal call to the Windows GlobalAlloc function. Other Windows data objects are allocated from the USER or GDI heaps, but the large size of an HPENDATA object necessitates allocation from the system global heap.

Windows imposes a 64K limit on the size of each HPENDATA object. At a report rate of 120 samples per second, at 4 bytes per data point, plus some overhead data structures, minus the time the pen is not in contact with the surface of the tablet, a single HPENDATA object can contain the data representing roughly two and one-half minutes of pen activity.

The following section describes the internal structure of an HPENDATA memory block. Though not recommended, your application can use this information to read ink data if necessary. However, the internal structure of the HPENDATA block may change in future versions of Windows. Therefore, applications should always use standard API functions to read from an HPENDATA object.

Important  Under no circumstances should an application write directly into an HPENDATA block. The Pen API provides functions for modifying ink data safely. Directly changing point data in the block can cause hazardous side effects.


 Data Within an HPENDATA Object

Figure 4.1 illustrates the internal structure of an HPENDATA object.

Windows stores the pen data in memory in a simple hierarchy. Data points are grouped by strokes in the order in which they are entered. The HPENDATA block of memory begins with a descriptive header area. The following sections describe the data points, the stroke headers, and the main header that make up an HPENDATA object.

Note that the drawing in Figure 4.1 is not to scale. The data points generally represent a much larger proportion of the memory block than the header components.


 Data Points

The data points associated with each stroke are initially tablet coordinates with a resolution of 0.001 inch and an origin at the upper left corner of the tablet. Tablets must report points in this scale regardless of their actual resolution. The Pen API provides functions to scale the points to other metric systems. It is not necessary for the data in an HPENDATA object to remain at a resolution of 0.001 inch.

If Windows is running in portrait mode, the tablet still reports coordinates with the upper left corner of the tablet corresponding to the current upper left corner of the display. The developer need not be concerned with the current orientation of the screen. The (0,0) coordinate of the Windows display always corresponds to (0,0) on the tablet.

The HPENDATA object can contain additional information supported by the pen device, such as pen pressure, angle, and rotation. The main header section of the HPENDATA object specifies how this additional information is stored in the stroke data areas for each data point. Internally, such data, which reflects original equipment manufacturer (OEM) hardware, is stored immediately following the block of coordinates for a stroke. This is called OEM data.


 Stroke Headers

A stroke refers to the data points collected while the pen is in contact with the tablet. These are called pen-down points. When the user lifts the pen, the stroke ends. A new stroke begins when the pen next touches the tablet. Some tablets also support proximity strokes, which consist of points received when the pen is not in contact with the tablet but near enough for the tablet to sense the pen movement. Such points are called pen-up points; a stroke consisting of pen-up points is said to have a pen-up state.

As Figure 4.1 shows, a stroke header prefaces each collection of pen coordinates that make up a single stroke. Note that the structure of the stroke header in version 2.0 of the Pen API is different from the stroke header of version 1.0, because, instead of the STROKEINFO structure used in version 1.0, the stroke header now consists of a variable-length array . The current STROKEINFO structure is still compatible with version 1.0 stroke headers.

Figure 4.1 shows strokes of different sizes. This is because the pen can be in contact with the surface of the tablet for longer or shorter periods of time, resulting in more or fewer points of data. The length of a single stroke is limited only by the 64K maximum size of an HPENDATA memory block.


 Main Header

A PENDATAHEADER structure is the first part of the main header of the HPENDATA object. The PENDATAHEADER structure, described in Chapter 11, "Pen Application Programming Interface Structures," contains the following information:

•	Number of strokes

•	Total number of points

•	Number of points in longest stroke

•	Size in bytes of the memory block

•	Bounding rectangle of all pen-down points

•	Ink color

•	Ink width

•	Version

The wPndts member of the PENDATAHEADER structure describes the state of the data in the HPENDATA object. The state of the data reflects whether the data is compressed, includes pen-up points, or includes OEM data. The wPndts element is a bitwise-OR combination of the PDTS_ flags described in Chapter 13, "Pen Application Programming Interface Constants."

The next component in the main header is a PENINFO structure. The PENINFO structure contains information about the tablet device that produced the data. This information includes the tablet width, height, resolution, report rate, proximity capabilities, and barrel-button status. For more information about the PENINFO structure, see Chapter 11, "Pen Application Programming Interface Structures."

The cbOemData member of the PENINFO structure specifies how much (if any) OEM pen data each pen packet contains. The format and order of the extra OEM information are contained in the rgboempeninfo member, which is an array of OEMPENINFO structures. The OEMPENINFO structures describe the order, minimum value, and scale of any OEM pen data the tablet reports along with the coordinate data. Chapter 11 describes the OEMPENINFO structure in detail.


 HPENDATA Functions

This section introduces the Pen API functions that manipulate ink data in an HPENDATA object. The recognition functions described in the next chapter apply to a specific task — the recognition of text. The HPENDATA functions, however, are not so easily summed up. They are building blocks for an infinite variety of tasks, according to the requirements and imagination of the developer. For this reason, the best introduction to the HPENDATA functions is a simple list of their capabilities.

The following subsections group the functions into six categories and provide a brief description of each function. These subsections serve only as an introduction to the HPE NDATA functions. For complete details about the functions, see the appropriate reference sections in Chapter 10, "Pen Application Programming Interface Functions." To see some of the HPENDATA functions in use, refer to the PENAPP sample program presented in Chapter 7, "A Sample Pen Application."

The six categories of the HPENDATA functions are:

•	Creating an HPENDATA object

•	Displaying ink data

•	Scaling ink data

•	Examining ink data

•	Editing or copying ink data

•	Compressing ink data

The order in which functions appear in the following lists reflects either a logical sequence of discussion or, where such criteria do not exist, simple alphabetic ordering. The order does not imply relative importance of the functions.


 Creating an HPENDATA Object

The Pen API provides five functions that allocate and free an HPENDATA object. These functions are similar to many Windows data types.

Note  It is recommended that you use only the functions from version 2.0 of the Pen API. Although API from version 1.0 are included for backward compatibility, it is not guaranteed that they will be supported in future versions of the Pen API.

The functions that allocate and free HPENDATA objects are as follows:

Function	Description
CreatePenData	Creates an empty HPENDATA object. The application provides the PENINFO structure for the header, the real size of any OEM data stored with each coordinate, and the scale of the coordinates. Superseded by CreatePenDataEx.
CreatePenDataEx	Creates an empty HPENDATA object. This function is an enhanced version of CreatePenData that provides an application with greater control over the contents of the HPENDATA object.
CreatePenDataHRC	Returns a handle to an HPENDATA object copied from an HRC object. Since this call creates a new HPENDATA, the application should free the object when finished by calling DestroyPenData, described below. The AddPenDataHRC function reverses the process by copying pen data to an HRC object. Chapter 5, "The Recognition Process," describes the HRC object.
DuplicatePenData	Duplicates an HPENDATA object, allowing an application to create clones of existing pen data. Since this call creates a new HPENDATA, the application should free the object when finished by calling DestroyPenData, described below.
DestroyPenData	Frees the heap memory occupied by the HPENDATA block. If the function returns TRUE, the handle to the object is no longer valid and should be set to NULL.


 Displaying Pen Data

The Pen API provides four functions for displaying the pen data contained in an HPENDATA object. An additional function, CreatePenDataRegion, determines the screen area necessary to display the pen data. This enables an application to determine the screen area affected by a gesture.

The following table describes the API drawing functions:

Function	Description
DrawPenData	Draws pen data in the specified device context using the Windows GDI Polyline function. The ink width and color specified in the PENDATAHEADER structure have no effect on how DrawPenData renders the ink. The rendering of the ink data produced by DrawPenData generally does not exactly match the rendering produced by the display driver when the data was first collected. An application that requires an exact replication of the original ink rendering should call the RedisplayPenData function.
DrawPenDataEx	Draws pen data in its original color or in a given device context. This function is an enhanced version of DrawPenData. Besides basic drawing capabilities, DrawPenDataEx can control the speed at which the data is rendered, a process called animation. This function can also draw a selected subset of strokes or the points within a stroke, rather than the entire pen data. DrawPenDataEx can display a set of sequential strokes with a single call. Drawing nonsequential strokes — say, the second, fifth, and eighth strokes of the pen data — requires separate calls to DrawPenDataEx for each stroke.
DrawPenDataFmt	A macro function that simplifies calls to DrawPenDataEx by specifying: • Rendering ink data in original ink attributes and speed (no animation). • Entire data set is drawn (no stroke subsets). • Each stroke is drawn with the color and width specified in the stroke header.
RedisplayPenData	Draws pen data ink that exactly matches the original rendering. RedisplayPenData displays pen data with a square GDI pen brush for maximum drawing speed. When displaying wide lines of ink, this optimization can cause the ends of abutting lines to appear "blocky."
CreatePenDataRegion	Returns a region of the screen required to show the contents of an HPENDATA object. Another call to the GDI function GetRgnBox returns the bounding rectangle that holds the region. (See also the description of GetPenDataAttributes, which can return the bounding rectangle for the entire set of pen data.) The application should call the Windows function DestroyObject to free the region when finished.


 Scaling Pen Data

The Pen API provides three functions to transform or scale pen data in an HPENDATA object. The related functions TPtoDP and DPtoTP do not operate explicitly on an HPENDATA object, but instead convert the resolution of an array of points.

Function	Description
MetricScalePenData	Converts pen coordinates between metric and English standard measurements. Metric units are 0.1 and 0.01 millimeter; English standard units are 0.001 inch. These scaling metrics comply with the mapping modes set in the Windows function SetMapMode, described in the Windows Software Development Kit. MetricScalePenData can also convert pen data to display resolution. See "Converting Data to Display Resolution" later in this chapter.
OffsetPenData	Offsets the coordinates in an HPENDATA object to make them relative to another origin. The function adds or subtracts offset values to or from the coordinate points. The offset values must use the same units as the pen data. Offsetting coordinates does not lose data. The process is completely reversible and does not reduce recognition accuracy.
ResizePenData	Scales ink into arbitrarily sized rectangles. This function exhibits the same weakness as the other scaling functions. It preserves rectangle proportions, but rounding errors prevent the scaling process from being precisely reversible. However, enlarging the ink data generally does not adversely affect recognition accuracy for data later given to a recognizer.


 Examining Pen Data

The following functions enable an application to examine, directly modify, or retrieve information from an HPENDATA object:

Function	Description
BeginEnumStrokes GetPenDataStroke EndEnumStrokes	These three functions work in tandem. Together, they enable an application to directly read an HPENDATA block in memory. Use these functions with caution and only for reading pen data. Do not attempt to write into an HPENDATA block. BeginEnumStrokes returns a far pointer to the HPENDATA memory block within the global heap. GetPenDataStroke retrieves pointers to point data within the HPENDATA. Although an HPENDATA block no longer prefaces strokes with STROKEINFO structures, GetPenDataStroke can retrieve a STROKEINFO structure corresponding to any stroke within the block. When the application has finished with the memory block, it must call EndEnumStrokes. This unlocks the block in the global heap and invalidates the pointers returned by GetPenDataStroke. For this reason, an application must not use the pointers once it has called EndEnumStrokes.
GetPenDataInfo	Retrieves summary information from the pen data memory block. It is superseded by the GetPenDataAttributes function to some extent.
GetPenDataAttributes	Provides enhanced versions of some of the capabilities of GetPenDataInfo. It also provides additional detailed information taken from the HPENDATA block. For example, GetPenDataAttributes can return • The total number of points in the HPENDATA • The total number of strokes • The time the HPENDATA was created • The device sampling rate
GetStrokeAttributes SetStrokeAttributes	Retrieve or set information about a given stroke in an HPENDATA object. For example, these functions can get or set • The pen state (up or down) for a stroke • The ink color and width • The absolute time the stroke occurred
GetStrokeTableAttributes SetStrokeTableAttributes	Retrieve or set information about all strokes in an HPENDATA object that share a given class. For all such strokes, these functions can get or set: • The ink color and width. • The user value. • The number of entries in the stroke table.
HitTestPenData	Determines whether a given point lies near the line of a stroke. The function accepts a threshold value that describes a square region around the given point on the tablet or screen. If a stroke in an HPENDATA block passes through the square, this function reports a "hit." HitTestPenData considers only points with a pen-down state.


 Editing or Copying Pen Data

The functions listed below add, delete, or copy coordinate data to and from an HPENDATA object.

An empty HPENDATA object has the following value for the wPndts member of its PENDATAHEADER structure:

PDTS_NOUPPOINTS | PDTS_NOCOLLINEAR | PDTS_NOEMPTYSTROKES

For a full list of PDTS_ values, see Chapter 13, "Pen Application Programming Interface Constants." See Chapter 11 for a description of PENDATAHEADER.

Functions in the following list with a name prefix of Add, Insert, Extract, or Remove add to or delete from an HPENDATA object. These functions check the results of their operation and adjust the value in wPndts accordingly.

Function	Description
AddPenDataHRC	Copies the pen data from an HPENDATA object to an HRC object. This function provides the means for deferred recognition. An application can gather pen data into an HPENDATA block, manipulate or store it if desired, then later copy the data to an HRC object for recognition.
AddPointsPenData	Appends a set of points, including a STROKEINFO structure and any corresponding OEM data, to an HPENDATA object.
ExtractPenDataPoints	Copies points and OEM data from an HPENDATA block to supplied buffers. The application can convert the points to screen resolution with the TPtoDP function to reduce the buffer size. The application can also optionally delete these points from the original pen data.
ExtractPenDataStrokes	Copies selected strokes from an HPENDATA block, optionally creating a new HPENDATA block containing the copied strokes. ExtractPenDataStrokes can optionally delete the original strokes.
GetPointsFromPenData	Retrieves information from an HPENDATA object in a way similar to the GetPenDataStroke function. However, GetPointsFromPenData copies the required data to buffers supplied by the application rather than simply returning pointers to the original data in the global heap. Therefore, the application need not call BeginEnumStrokes and/or EndEnumStrokes when using GetPointsFromPenData.
InsertPenData	Merges two separate HPENDATA objects into a single object.
InsertPenDataPoints	Inserts points into the stroke of an existing HPENDATA object. InsertPenDataPoints automatically updates the stroke and pen data headers. This function can adversely affect recognition accuracy for data that must later be recognized.
InsertPenDataStroke	Inserts an entire stroke into an existing HPENDATA object. InsertPenDataStroke automatically updates the stroke and pen data headers. The ink of the inserted stroke has default color and width. To change these attributes, call SetStrokeAttributes after inserting the stroke.
PenDataToBuffer PenDataFromBuffer	Copy an HPENDATA object as sequential data from and to a buffer. PenDataFromBuffer creates and loads an HPENDATA object with the data from the sequential buffer created by PenDataToBuffer. These functions are used to transfer pen data to and from a file or the clipboard.
RemovePenDataStrokes	Deletes a contiguous set of strokes from an HPENDATA object.


 Compressing Pen Data

Data compression plays an important role in pen-based computing. The high sampling rates of a pen device, combined with large amounts of input, result in large blocks of ink data. The Pen API offers three methods of compression, each with advantages and disadvantages depending on the intended use of the ink data.

•	Removal of redundant or otherwise unwanted data from the data structure. This compression method does not result in loss of recognition accuracy if the compressed data is later recognized.

•	Reversible compression, also called "lossless" compression. Subsequently decompressing the data produces an HPENDATA object identical to the original. Since this compression method loses no information, the data can later be recognized with no loss of accuracy. However, the application cannot copy the compressed data to an HRC object; it must first uncompress the data before calling AddPenInputHRC.

•	Irreversible compression, sometimes called "lossy" compression. This method produces the highest degree of compression, but at the cost of lost information. Though the data is still perfectly suitable for display, it cannot be uncompressed and given to a recognizer without a significant loss of recognition accuracy. Irreversible compression is discussed later in the section "Converting Data to Display Resolution."


 Compression Functions

Following are the three compression functions provided by the Pen API.

Function	Description
CompactPenData	Provided only for compatibility with version 1.0 of the Pen API and may not be supported in future versions. Use the functions CompressPenData and TrimPenData instead.
CompressPenData	Primary function used to compress and uncompress pen data.
TrimPenData	Removes selected data from an HPENDATA object to reduce the size of the memory block. For example, TrimPenData can remove OEM information, timing indexes, pen-up points, and so forth.


 Converting Data to Display Resolution

Converting the points in an HPENDATA block to display resolution effectively compresses the data because display coordinates are coarser than tablet coordinates and therefore occupy less memory. However, the conversion is irreversible; an application cannot convert the points back to their original tablet resolution. Moreover, converting to display coordinates virtually disallows subsequent recognition of the data because recognizers lose accuracy when dealing with data at coarse screen coordinates.

To compress pen data to screen resolution

1.	Call MetricScalePenData to convert the ink data from tablet coordinates to display coordinates.

2.	Call TrimPenData with the TPD_COLLINEAR flag to remove the duplicate and collinear points.

These two steps substantially reduce the number of points in the pen data by removing many high-resolution digitizer points. The following code fragment demonstrates these steps:

HPENDATA	hpendata;	// Handle to HPENDATA object

.

.

.

if (MetricScalePenData( hpendata, PDTS_DISPLAY ))

iRet = TrimPenData( hpendata, TPD_COLLINEAR );

After converting the HPENDATA block to display resolution, the application can call CompressPenData or TrimPenData to compress the points even more. For maximum compression of data intended only for display, use the following instructions instead of the preceding example:

if (MetricScalePenData( hpendata, PDTS_DISPLAY ))

if (TrimPenData( hpendata, TPD_EVERYTHING ) == PDR_OK)

CompressPenData( hpendata, CMPD_COMPRESS );


 The HINKSET Object

An inkset object consists of time intervals for either individual strokes or a collection of strokes. In turn, the interval of each stroke consists of the times at which the stroke begins and ends. In this way, a pen-based application can refer to a stroke not only by the points it contains but also by the time interval in which the stroke occurs. A rough analogy of this sort of indirect referencing is the way some programming languages allow the use of pointers to indicate data.

Timing information principally serves recognizers. It provides them with an additional characteristic of the raw data that may offer clues for interpretation.

Timing information has other uses, as well. For example, it enables an application to accurately verify a signature by comparing not only the coordinates but the duration of each stroke against a copy of the original signature. This is an effective safeguard against forgery because of the difficulty of simultaneously duplicating both the pattern and duration of the original signature.

An HINKSET object can contain up to 5,460 intervals. An interval is expressed as an INTERVAL structure, which consists of two ABSTIME structures. Each INTERVAL structure identifies a stroke's start and stop times in milliseconds. See the appropriate reference sections in Chapter 11 for type definitions of the ABSTIME and INTERVAL structures.


 The HINKSET Functions

The Pen API provides six functions for creating, adding data to, and destroying an HINKSET object. The functions automatically ensure intervals within an inkset remain in chronological order.

Function	Description
CreateInkset	Creates an empty inkset into which intervals can be added with the AddInksetInterval function.
CreateInksetHRCRESULT	Retrieves the intervals for a specified series of symbols returned by the recognizer.
AddInksetInterval	Adds a single INTERVAL structure to an existing HINKSET object. Intervals need not be added in any particular order because AddInksetInterval automatically sorts the intervals chronologically and merges overlapping intervals.
GetInksetInterval	Copies a series of intervals from an HINKSET object to an array of INTERVAL structures.
GetInksetIntervalCount	Returns the number of intervals in an HINKSET object.
DestroyInkset	Frees the memory occupied by an HINKSET object and invalidates its handle.


 Timing Information

For uncompressed data, a stroke's interval implies the number of points in the stroke. An application can obtain this number directly from a STROKEINFO structure. The following is of academic interest only, illustrating how time intervals correspond to the point data within a stroke.

First, an application gets the device sampling rate with a call to GetPenDataInfo. The sampling rate is the number of points the pen device driver sends to Windows during each second of pen activity.

HPENDATA        hpndt;

PENINFO         peninfo;

int             nSamplingRate;

.

.

.

if (GetPenDataInfo( hpndt, NULL, (LPPENINFO) &peninfo, 0 ))

    nSamplingRate = peninfo.nSamplingRate;

Alternatively, an application can query the pen device driver directly for the sampling rate, as described in "Recognition Functions" in Chapter 8, "Writing a Recognizer."

The number of points in a stroke can now be determined from the start and stop times in the stroke's INTERVAL structure:

INTERVAL        interval;

int             nSamplingRate, nPoints, nms;

.

.

.

// Compute number of milliseconds in interval

nms = ((interval.atEnd.sec - interval.atBegin.sec) * 1000) +

       (interval.atEnd.ms - interval.atBegin.ms);

// Compute number of points that occurred during interval

nPoints = (nms * nSamplingRate) / 1000;

After recognition, an application can determine the time intervals at which recognized symbols were written. Calling CreateInksetHRCRESULT creates the inkset for the required intervals:

HINKSET     hinkset;             // Allocate the inkset

HRCRESULT   hresult;             // Symbols for guesses go here

.

.

.

// Get symbols that make up the recognizer's best guess

GetResultsHRC( hrc, GRH_ALL, (LPHRCRESULT) &hresult, 1 );

// Get the inkset for symbols 2 through 11 of the guess

hinkset = CreateInksetHRCRESULT( hresult, 2, 10 );

The above code fragment creates an inkset containing a maximum of 10 intervals corresponding to the second through eleventh symbols of the recognizer's best guess. The section "Unboxed Recognition"  in the next chapter describes the GetResultsHRC function in detail. For a description of the internal workings of CreateInksetHRCRESULT, see "The Recognition Functions" in Chapter 8, "Writing a Recognizer."


 Timing Macros

The PENWIN.H file defines several macro functions designed to deal with timing information. The following reference section briefly describes these macros.


 dwDiffAT

dwDiffAT( at1, at2 )

Compute time difference in milliseconds between two ABSTIME (absolute time) structures at1 and at2. If at2 is more than at1, the result is positive.

Example

x = dwDiffAT( at1, at2);	// Get time difference in milliseconds


 dwDurInterval

dwDurInterval( lpi )

Calculate the duration in milliseconds of the INTERVAL structure lpi points to.

Example

x = dwDurInterval( lpi );	// Get duration in milliseconds


 FAbsTimeInInterval

FAbsTimeInInterval( at, lpi )

Test whether the time in the ABSTIME structure at is contained within the time interval in the INTERVAL structure pointed to by lpi.

Example

if (FAbsTimeInInterval( at, lpi ))	// TRUE if at within INTERVAL


 FIntervalInInterval

FIntervalInInterval( lpiT, lpiS )

Test whether the time interval in the INTERVAL structure pointed to by lpiT is within the INTERVAL structure pointed to by lpiS.

Example

if (FIntervalInterval( lpiT, lpiS ))	// TRUE if lpiT within lpiS


 FIntervalXInterval

FIntervalXInterval( lpiT, lpiS )

Test whether the time interval in the INTERVAL structure pointed to by lpiT overlaps the INTERVAL structure pointed to by lpiS.

Example

if (FIntervalXInterval( lpiT, lpiS ))	// TRUE if lpiT overlaps lpiS


 FLTAbsTimeFLTEAbsTime
FEQAbsTime

FLTAbsTime( at1, at2 )

FLTEAbsTime( at1, at2 )

FEQAbsTime( at1, at2 )

Compare two ABSTIME structures at1 and at2. These macros return TRUE for the following conditions: less than, less than or equal, and equal.

Example

if (FLTAbsTime( at1, at2 ))   // TRUE if at1 < at2

if (FLTEAbsTime( at1, at2 ))  // TRUE if at1 <= at2

if (FEQAbsTime( at1, at2 ))   // TRUE if at1 == at2


 MakeAbsTime

MakeAbsTime( lpat, sec, ms )

Initialize the ABSTIME structure pointed to by lpat with the values sec and ms.

Example

sec = 5;                         // Time = 5.4 seconds (5 seconds

ms  = 400;                       //   plus 400 milliseconds)

MakeAbsTime( lpat, sec, ms );    // Fill ABSTIME structure


 The Recognition Process

Recognition is the process of translating pen strokes into characters, symbols, or shapes. An application conducts recognition by passing the raw pen data to special dynamic-link libraries (DLLs) called recognizers, each of which may specialize in a particular data type. For example, one recognizer may specialize in English text, another in Greek, and yet another in electronic symbols.

The system default recognizer serves the recognition needs of most applications. Alternatively, applications can load additional recognizers and select which to use for any given input. Regardless of the recognizer, the DoDefaultPenInput function can conveniently run the entire recognition process.

An application interfaces with recognizers through a data object called HRC, an abbreviation for "handle to a recognition context." This chapter describes the HRC and explains how an application uses the HRC functions to recognize pen-based handwriting.


 The HRC Object

The HRC object incorporates a set of functions, called the HRC functions, that govern the recognition process. To conduct handwriting recognition, an application creates an HRC object, configures its recognition parameters, sends pen data to the object, gives the object time to perform recognition, and eventually gets results from the object.

An HRC object provides four different functions, serving as:

•	Recognition manager, containing the word lists, templates, alphabets, and GUIDE information that aid recognition.

•	Data storage, containing the pen coordinates placed into the object with the AddPenInputHRC or AddPenDataHRC functions. An application can retrieve the entire set of pen data stored in the HRC object or only a portion. For example, it can retrieve only the ink associated with a specific letter or word in the recognized text.

•	Recognition workhorse, handling the task of recognition through the ProcessHRC function.

•	Results warehouse, storing recognition results and guesses.


 Using the HRC Functions

The following sections describe how an application uses the HRC functions to recognize handwritten input as the user writes. The text builds on the steps given in "Starting the Chain of Events"  in Chapter 3, "The Writing Process;" refer to that section for more details on each step in the process. The following sections deal with five separate areas of the recognition process:

•	Creating the HRC

•	Configuring the HRC

•	Processing

•	Getting results

•	Destroying the HRC and other recognition objects


 Creating the HRC

Before recognition can occur, the application must create an HRC object. DoDefaultPenInput does this automatically for the system recognizer, or an application can call the CreateCompatibleHRC function to specify another recognizer. CreateCompatibleHRC takes two arguments: a handle to an existing HRC (if any) that serves as a template for the new HRC, and the handle to the recognizer that serves the new HRC.

Either or both arguments can be NULL. Giving NULL as the first argument creates a new HRC with default settings. The next section, "Configuring the HRC," describes the default parameters, which include the following settings:

•	Recognition ends after a brief period of inactivity or when the user taps outside the target window.

•	The target window does not use guides.

•	The recognizer returns only its best guess without alternative guesses.

Giving NULL as the second argument binds the HRC to the system default recognizer. Microsoft Windows sets the supplied file GRECO.DLL as the system default recognizer, specified in the Microsoft Windows 95 system registry. Refer to Appendix A for an explanation of how to change the default to another recognizer.

CreateCompatibleHRC, which is analogous to CreateCompatibleDC, copies configuration information from an existing HRC to the new HRC, which the application can then modify. The following fragment demonstrates how to load a fictitious recognizer called RECOG1.DLL and bind it to a new HRC patterned after an existing HRC called hrcTemplate:

HRC     hrc1;                       // Handle to new HRC

HREC    hrec1;                      // Module handle of recognizer

.

.

.

hrec1 = InstallRecognizer( "RECOG1.DLL" );

if (hrec1)

hrc1 = CreateCompatibleHRC( hrcTemplate, hrec1 );

Each HRC can access only one recognizer and the binding lasts the life of the HRC. To use multiple recognizers, an application must create multiple HRC objects, binding each to a different recognizer. The Pen API does not provide a means for changing the recognizer associated with an HRC.

As shown in the example above, an application must call InstallRecognizer to load any other recognizer it will use. The exception is the system default recognizer, which is already installed when the system starts up. An application should not install the system recognizer with InstallRecognizer. Doing so only creates an unnecessary module handle.

To preserve system resources, an application must free all handles obtained from InstallRecognizer with separate calls to UninstallRecognizer. Unlike other DLLs, a recognizer belongs to the system instead of the application. Windows does not unload the recognizer from memory until every client has called UninstallRecognizer.

Once it receives a valid HRC handle, the application can begin configuring the HRC to perform handwriting recognition.


 Configuring the HRC

Before passing data to the HRC, the application must ensure the HRC is properly configured to perform recognition. The configuration information in an HRC provides a context to guide the recognition process. For example, if the application expects only numerical input, it can configure the HRC accordingly. This prevents the recognizer from mistakenly confusing the numeral "0" for the letter "O."

A new HRC shares the same configuration as the template HRC given when calling CreateCompatibleHRC. If the application does not provide a template for CreateCompatibleHRC, the new HRC receives a default configuration.

The following paragraphs describe the various configurations an application can set for an HRC object.


 Alphabet

The SetAlphabetHRC function specifies a set of symbols the HRC should expect in the input. (A similar function, SetBoxAlphabetHRC, provides the same service for a group of boxes when the HRC uses guides.) For example, the application can constrain recognition to numerals and uppercase letters, as shown here:

iRet = SetAlphabetHRC( hrc1, ALC_NUMERIC | ALC_UCALPHA, NULL );

For more details about SetAlphabetHRC and SetBoxAlphabetHRC, see Chapter 10, "Pen Application Programming Interface Functions."

The first argument of SetAlphabetHRC is the HRC handle returned by CreateCompatibleHRC. The second argument is a bitwise-OR value formed by the desired combination of ALC_ constants, some of which are listed here:

Alphabet constant	Description
ALC_DEFAULT	Default alphabet value for recognizer. If recognizer can serve as a system recognizer, its default alphabet must include at least the ALC_SYSMINIMUM set. The Pen API does not specify a default for nonsystem recognizers.
ALC_LCALPHA	Lowercase letters: a−z.
ALC_UCALPHA	Uppercase letters: A−Z.
ALC_NUMERIC	Numerals: 0−9.
ALC_ALPHANUMERIC	Combines ALC_LCALPHA, ALC_UCALPHA, and ALC_NUMERIC.
ALC_PUNC	Punctuation: !-;`"?()&.,;\.
ALC_MATH	Math symbols: %^*()-+={}<>,/.
ALC_MONETARY	Monetary symbols: ,.$ (or as determined by language).
ALC_OTHER	Other special characters: @#|_~[].
ALC_ASCII	Seven-bit characters ASCII #20 to ASCII #127.
ALC_WHITE	White space such as tabs and newline and space characters.
ALC_NONPRINT	TAB, ENTER, and CTRL keys.
ALC_SYSMINIMUM	Combines ALC_ALPHANUMERIC, ALC_PUNC, ALC_WHITE, and ALC_GESTURE.
If an application does not specify alphabet configuration either through an existing HRC model or by calling SetAlphabetHRC or SetBoxAlphabetHRC, Windows assumes ALC_SYSMINIMUM as the default alphabet configuration. For a complete list of ALC_ values, see Chapter 13, "Pen Application Programming Interface Constants."


 Gesture

A default HRC enables all gestures. An application can disable certain gestures by calling the EnableGestureSetHRC function to change the gesture configuration for the HRC. The following example disables the gestures for cut, copy, and paste while enabling all other gestures:

iRet = EnableGestureSetHRC( hrc1, GST_ALL ^ GST_CLIP, TRUE );

For more information about EnableGestureSetHRC, see the reference section in Chapter 10, "Pen Application Programming Interface Functions."

The first argument of EnableGestureSetHRC is the HRC handle returned by CreateComptibleHRC. The second argument is a bitwise-OR value formed by the desired combination of GST_ constants, listed here:

Gesture constant	Description
GST_CLIP	Cut, copy, and paste.
GST_WHITE	Space, tab, and newline.
GST_SEL	Lasso selection.
GST_EDIT	Insert, correct, and undo.
GST_SYS	Combines all the above.
GST_CIRCLELO	Lowercase circle gestures.
GST_CIRCLEUP	Uppercase circle gestures.
GST_CIRCLE	Combines GST_CIRCLELO and GST_CIRCLEUP.
GST_ALL	Combines all the above.


 Word List

An application can select a word list from any number of lists to attach to an HRC. A word list, referenced by a handle, consists of words the recognizer should consider when translating a handwritten word or phrase. For example, Figure 5.1 shows a case in which the recognizer must decide between the valid interpretations of "boy" and "looy".

By consulting a word list that contains the entry "boy" but not "looy", the recognizer can select the first choice with more confidence.

An application must call the CreateHWL function to create a word list. The function accepts a pointer to a word list already in memory. Alternatively, an application can fill the word list from an existing file through the ReadHWL function. The SetWordlistHRC function attaches the word list to a particular HRC, and DestroyHWL returns the memory occupied by the list to the operating system.

The function SetWordlistCoercionHRC allows an application to establish the word list's influence over the recognizer's interpretations. The function accepts the following values to set the degree of coercion:

Coercion value	Description
SCH_ADVISE	The recognizer should use the word list only for hints; results are not strongly coerced to match the word list. This is the default coercion value.
SCH_FORCE	If the recognizer does not find an exact match in the word list, it should return the best fit. For example, if the recognizer interprets a handwritten word as "swoden," it will return "Sweden," given a word list of country names.
SCH_NONE	Cancels any coercion currently in effect.
The following code fragment illustrates all these steps by reading a list of country names from the fictitious file COUNTRY.LST and attaching the list to the HRC identified by the handle hrc1. It calls SetWordlistCoercionHRC to force the recognizer to return only names found in the COUNTRY.LST file. The code assumes vhwl is a global variable, visible in all parts of the program.

HWL	vhwl;	// Handle to word list

HFILE	hfile;	// File handle

OFSTRUCT	OFstruct;	// Receives info about open file

int	iRet;	// Return code

.

.

.

// In intialization procedure, open and read the word list

hfile = OpenFile( "COUNTRY.LST", (LPOFSTRUCT) &OFstruct, OF_READ );

if (hfile != HFILE_ERROR)

{

vhwl  = CreateHWL( hrec1, NULL, WLT_EMPTY );	// Create empty list

iRet  = ReadHWL( vhwl, hfile );	// Read list from file

}

.

.

.

// After creating hrc1, attach word list vhwl to it

SetWordlistHRC( hrc1, vhwl );	// Attach list to hrc1

SetWordlistCoercionHRC( hrc1, SCH_FORCE );	// Establish coercion

.

.

.

//Before terminating, destroy word list

DestroyHWL( vhwl );

Note that an application must first set the word list with SetWordlistHRC before calling SetWordlistCoercionHRC.


 Guide

Guides are visual cues such as lines or boxes in a bedit control. Guide configuration informs the recognizer of the types and locations of guides displayed for the user. With this information, the recognizer can confidently determine which pen strokes constitute a single character or shape. For an illustration of box guides, see the "The bedit Control" section in Chapter 3, "The Writing Process."

To establish guide configuration, an application calls the SetGuideHRC function, providing a pointer to a GUIDE structure:

GUIDE	guide;

.

.

.

iRet = SetGuideHRC( hrc1, (LPGUIDE) &guide, 0 );


 Number of Recognition Guesses

The application can specify the maximum number of guesses the recognizer should provide in its results. This allows the application to prevent the recognizer from generating more alternative guesses than required.

Set the maximum number of guesses with the SetMaxResultsHRC function. The following example code tells the recognizer to provide its five best guesses:

iRet = SetMaxResultsHRC( hrc1, 5 );

The default number of maximum recognition results is 1.


 Processing

Once the HRC object has been properly created and configured, it can take on its role of recognition agent. To fulfill this role, the HRC requires:

•	The data generated by the pen movement.

•	Sufficient central processing unit (CPU) time to execute the recognition algorithms and generate results.

The following sections describe how an application supplies these two requirements to the HRC object.


 Adding Data to an HRC Object

An application provides pen data to the HRC through one of two API functions: AddPenInputHRC or AddPenDataHRC.

AddPenInputHRC operates at intervals as pen data is collected, in the same manner as GetPenInput. An application must call AddPenInputHRC only after it has called GetPenInput. AddPenInputHRC provides the pen coordinates and original equipment manufacturer (OEM) data to the recognizer bound to the HRC object.

AddPenDataHRC also provides pen data to the recognizer, but is designed to operate after all the data is collected. An application can thus collect pen data without realtime recognition, store the data in an HPENDATA structure, and call AddPenDataHRC to recognize the data any time thereafter.


 Allocating Processing Time

After it has supplied the raw pen data to an HRC object, the application then allocates processing time for recognition by calling ProcessHRC. To accommodate applications with time-critical communications requirements or other CPU-intensive activities, ProcessHRC takes a time-out value (in milliseconds) as its second argument. If the time-out period elapses before ProcessHRC finishes processing, the function returns an HRCR_INCOMPLETE value. In this way, an application can repeatedly allocate small slices of time until the recognizer finishes its work.

PENWIN.H defines three time-out codes that an application can use when calling ProcessHRC. The following table describes the time-out codes.

Time-out code	Description
PH_MIN	Allocates the smallest possible period of time to the recognizer, approximately 50 milliseconds.
PH_DEFAULT	Allocates a moderate amount of time to the recognizer, approximately 200 milliseconds.
PH_MAX	Grants the recognizer as much time as it requires to complete the recognition.
The following line allocates the default time-out period to the recognizer in the HRC identified by the handle hrc1:

iRet = ProcessHRC( hrc1, PH_DEFAULT );

Typically, AddPenInputHRC and ProcessHRC work together in a loop or in repeated response to a PE_ message as the user writes. One function continually retrieves the latest pen data while the other processes that data. When the input session terminates, an application should call ProcessHRC with PH_MAX to finalize the recognition.

See the reference section for ProcessHRC in Chapter 10 for additional information about this function. When ProcessHRC returns, the application can retrieve results from the HRC object, as described in the next section.


 Getting Results

The Pen API provides three methods for an application to get recognition results. The first two methods are functions — GetBoxResultsHRC and GetResultsHRC — that retrieve the results from an HRC object. The GetBoxResultsHRC function assumes the application has provided a GUIDE structure to the HRC. If the application has not specified a GUIDE structure, it must call GetResultsHRC to retrieve an HRCRESULT object for each alternative guess.

The third method applies only to version 1.0 recognition functions. It retrieves recognition results for both boxed and unboxed input from an RCRESULT structure. With this method, an application must dissect the RCRESULT structure to get information that GetBoxResultsHRC and GetResultsHRC provide automatically.

The rest of this section gives examples for each of the three methods.


 Boxed Recognition

GetBoxResultsHRC retrieves boxed recognition results on a box-by-box basis. The function fills an array of BOXRESULTS structures with the results and alternatives for a set of boxed character positions in the recognized text. Each of the BOXRESULTS structure in the array contains one or more recognition guesses for a single box.

For example, consider the case in which the user has written a seven-letter word before requesting recognition — say, by tapping an OK button. The application can retrieve results individually for each box by calling GetBoxResultsHRC in a loop, or provide an array of at least seven BOXRESULTS structures and receive all seven recognition results with a single call to GetBoxResultsHRC.

The following example code retrieves recognition results two boxes at a time. It requests only the first alternative for each box, which represents the recognizer's best guess about the character in the box:

#define	NBOX	2	// Number of boxes to get

#define	NALT	1	// Only one alternative per box

BOXRESULTS	box[NBOX];	// Array of BOXRESULTS structures

UINT	iSyv = 0;	// Index of symbol values

int	cBox;	// Number of results returned

.

.

.

do {

cBox = GetBoxResultsHRC( hrc1, NALT, iSyv, NBOX,

   (LPBOXRESULTS)&box, FALSE );

.	// Do error checking

.	// Read results from

.	//   box[] array

iSyv += (UINT) cBox;	// Increment index

} while (cBox == NBOX)	// Loop for next boxes

By requesting only a single alternative for a small number of boxes, the preceding example can allocate the array on the stack. However, the BOXRESULTS structure contains a variable-length array of type SYV for additional alternative characters. For a value of NALT greater than 1, the application must allocate extra space for the alternatives in each BOXRESULTS, as the following line demonstrates:

HGLOBAL	hMem = GlobalAlloc( GHND,

   NBOX*( sizeof(BOXRESULTS) + (NALT-1)*sizeof(SYV)) );

The example provided in the GetBoxResultsHRC reference section in Chapter 10 further illustrates how to use this function.

When GetBoxResultsHRC returns, the application can walk the BOXRESULTS array and display the information appropriately. The boxed edit control described in the "The bedit Control" section in Chapter 3 uses GetBoxResultsHRC to perform recognition and to generate alternative results.

Boxed writing does not constrain an application to call GetBoxResultsHRC for recognition results. An application can also call GetResultsHRC, described next, even if the HRC is configured for box guides.


 Unboxed Recognition

For recognition of unboxed handwriting — that is, writing without visual guides as specified by a GUIDE structure, an application must call the GetResultsHRC function. This function fills an array of HRCRESULT objects, each containing a separate guess by the recognizer. The number of HRCRESULT objects in the array is always less than or equal to the maximum number of guesses requested through the SetMaxResultsHRC function.

An example will clarify this. Assume an application contains the following instructions:

#define	MAX_GUESS	5	// Maximum number of guesses allowed

.

.

.

SetMaxResultsHRC( hrc1, MAX_GUESS );

The user next writes a word that the recognizer associated with hrc1 guesses to be, in descending order of probability, either "clear," "dear," "clean," "dean," or "deer." Though it might have generated even more guesses, the recognizer is constrained to stop after its fifth guess by the earlier call to SetMaxResultsHRC. In this case, a subsequent call to GetResultsHRC fills an array of up to five HRCRESULT objects, the first HRCRESULT containing the word "clear," the second the word "dear," and so forth.

An HRCRESULT object does not contain a normal ASCII string representation of a guess. This is not possible since a guess might be made up of a gesture, shape, or other entity that has no ASCII equivalent. Instead, an HRCRESULT contains a string of symbol values, which are 32-bit numbers type-defined as SYV.

Symbol values can represent geometric shapes, gestures, letters of the alphabet, Japanese Kanji characters, musical notes, electronic symbols, or any other symbols defined by the recognizer. The Pen API provides the function SymbolToCharacter to convert the null-terminated symbol string in HRCRESULT to an ASCII string.

The following code continues the example above, illustrating how to retrieve and display the five guesses returned by the recognizer:

#define     MAX_GUESS   5       // Maximum number of guesses allowed

#define     MAX_CHAR	    50      // Maximum number of characters in

                                //   a single guess

HRCRESULT   result[MAX_GUESS];  // Array for recognition result objects

int         cGuess;

.

.

.

SetMaxResultsHRC( hrc1, MAX_GUESS );

.

.

.

//

// Get all (non-gesture) guesses available, and if no errors,

// convert to ASCII strings and display them.  Note in our

// example the following call returns the value 5 to cGuess.

//

cGuess = GetResultsHRC( hrc1, GRH_NONGESTURE,

                       (LPHRCRESULT) &result, MAX_GUESS );

if (cGuess > 0)

{

int     i, cSyv, cChar;

char    szText[MAX_CHAR];           // Buffer for converted text

SYV     rgSyv[MAX_CHAR];            // Buffer for symbol string

//

// Loop cGuess (5) times, retrieving each time a symbol string

// representing a different guess.  Convert the symbol string

// to a normal ASCII string and display it.

//

// In our example, the five iterations of this loop display the

// words "clear," "dear," "clean," "dean," and "deer."

//

for (i = 0; i < cGuess; i++)

{

cSyv = GetSymbolsHRCRESULT( result[i], 0, rgSyv, MAX_CHAR );

if (cSyv > 0)

{

             SymbolToCharacter( (LPSYV) rgSyv, cSyv,

                                (LPSTR) szText, (LPINT) &cChar );

.

.	// After converting to ASCII

.	//   string, display text

             TextOut( hdc, nX, nY, (LPSTR) szText, cChar );

.

.

.

}

        DestroyHRCRESULT( result[i] );  // When finished with results,

        result[i] = NULL;               //   destroy HRCRESULT objects

}

}

For another example of how to use the GetResultsHRC function, see "Step 9: PE_RESULT Message" in Chapter 2. If an application must retrieve an unknown number of symbol values from the recognizer, it should follow these three steps:

1.	Call GetSymbolCountHRCRESULT to determine the number of symbol values the recognizer can return.

2.	Allocate a sufficient buffer for the values.

3.	Call GetSymbolsHRCRESULT. to copy the symbol values to the buffer.


 Getting Results from the RCRESULT Structure

Note  The RCRESULT structure is supported only for backward compatibility. It may not exist in future versions of the Pen API. Applications should obtain recognition results through the API functions described in this chapter, rather than from an RCRESULT structure.

The RCRESULT structure applies only when an application calls either of the version 1.0 recognition functions, Recognize or RecognizeData. In this case, the system sends a WM_RCRESULT message to the application. The wParam of this message contains a REC_ submessage that indicates why recognition ended. The lParam of WM_RCRESULT points to an RCRESULT structure, which contains all the results of the recognition.

An application can retrieve from the RCRESULT structure all the recognizer's guesses by walking through the list, called the symbol graph, contained in the RCRESULT structure.

The RCRESULT structure identifies the recognizer's "best guess," which is the guess in which the recognizer places the most confidence. With this information, an application can conveniently retrieve an ASCII string of the best guess by calling SymbolToCharacter:

char	szBestGuess[MAX_CHAR];	// ASCII string of best guess

.

.

.

switch (wMsg)

{

case WM_RCRESULT:

SymbolToCharacter(

(LPSYV) ((LPRCRESULT)lparam)->lpsyv,	// Symbol string

MAX_CHAR,	// Maximum length

(LPSTR) szBestGuess,	// Buffer for ASCII

NULL );	// Don't need count

Compare the above call to SymbolToCharacter with the previous example. Here, the second argument represents a maximum, rather than the actual length of the symbol string, which is the value

(int) ((LPRCRESULT)lparam)->cSyv

By specifying the length of the buffer that receives the ASCII text, the second argument sets a cap on the number of symbols SymbolToCharacter will convert. This prevents the function from overflowing the szBestGuess buffer if the length of the symbol string happens to be larger than MAX_CHAR. SymbolToCharacter returns when it encounters SYV_NULL at the end of the symbol string or when it converts MAX_CHAR symbols, whichever occurs first.

An application that calls Recognize or RecognizeData must be prepared to receive WM_RCRESULT messages before calling either function. This is because the recognizer dispatches all WM_RCRESULT messages associated with a particular recognition event before Recognize or RecognizeData returns.

Version 2.0 of the Pen API provides, through function calls, all the information contained in an RCRESULT structure. An application need not examine the structure at all. RCRESULT is a product of recognition, and is therefore of more interest to the recognizer developer than the application developer. Consequently, it is described in more detail in Chapter 8, "Writing a Recognizer."


 Destroying the HRC

The useful life of an HRC object usually expires when the recognizer returns results at the end of an input session. The next input session requires the creation of a new HRC. When finished with an HRC object, an application should destroy the object in two steps:

1.	Call DestroyHRC to free the occupied memory.

2.	Set the HRC handle to NULL.

For example:

HRC	vhrc = NULL;	// Set to NULL until HRC is created

.

.	// Create and use the HRC

.

DestroyHRC( vhrc );	// Destroy the HRC when finished

vhrc = NULL;	// Handle is now invalid

When DestroyHRC returns, the handle value remains unchanged though no longer valid. The second step above prevents frustrating bugs arising from the inadvertent use of an invalid HRC handle.

This same advice applies to the other recognition objects, HRCRESULT and HWL. After calling DestroyHRCRESULT or DestroyHWL, always set the invalid handle to NULL.


 Design Considerations

The developer of pen-based applications should bear in mind the unusual qualities of a pen interface. Input through a pen device provides unique advantages, yet at the same time carries severe limitations. The best applications will seek to profit from one quality while minimizing the effects of the other.

This chapter discusses some of the characteristics of an intelligent and responsive pen-based application. It offers tips, ideas, and a few warnings. The advice is based on experience and the results of usability studies conducted by Microsoft.


 Basic Principles

Consider the following basic principles when designing the user interface of a pen-based application. Though not intended to constrain the developer's creativity, these principles can help ensure that the resulting application appeals to its users.

•	Keep it simple.

•	Use familiar models.

•	Show feedback for user.

•	Make it fast.

•	Make it fun.

•	Make exploration safe.

•	Let the user maintain control.

The following sections explore each of these guidelines.


 Keep It Simple

The developer should value simplicity over power when designing a pen-based application. Simplicity is not only a characteristic of good interface design, it hastens the user's acceptance of a type of input paradigm apt to be new and unfamiliar.

The same principles for writing a standard Windows-based application apply equally to pen-based programs:

•	Limit features and options to reduce the number of choices a user must make. When adapting an existing application to run on a pen-based computer, remember the so-called "80/20" rule: 80 percent of an application's value is typically provided by only 20 percent of its features.

•	Keep the interface clear, consistent, uncomplicated, and predictable. The relationship between what a user does and how the application responds should be logical and consistent. Keeping the interface consistent and predictable reduces the amount of information the user must remember in order to use an application.

•	Make possible actions and results visible to the user. Enable the user to work directly with objects without resorting to abstractions. The user wants to "send mail" or "find a note," not "open an application" or "search for data."

•	Use constraints to prevent the user from choosing inappropriate actions and provide default choices whenever appropriate. Constraints encourage the user to make appropriate decisions by limiting unlikely choices. For example, a button enabling a user to save or pause a game should not be visible until play has started.


 Use Familiar Models

Familiar conceptual models are powerful aids in user-interface design. A conceptual model enables users to apply knowledge gained from experience toward understanding the structure and use of the application. For example, an Address application modeled after a typical paper-based address book would allow users to apply their understanding of address books to the new application.


 Use Feedback

The user should receive immediate and tangible feedback during interaction with an application. Appropriate feedback includes acknowledging a request, pointing out an error, or tracking the progress of an operation. Although auditory feedback can be useful for attracting a user's attention, it should be used sparingly in a pen-based application for the following reasons:

•	Many users find beeps annoying.

•	Pen-based computers will be used more and more frequently in conference rooms and other group areas where beeping from a machine will not be welcome.

•	Auditory messages disappear without a trace. If the user is momentarily away or distracted, the auditory signal has failed to do its job.

•	If the user can turn the warning sound off, sound is not a reliable source of feedback.

•	An audible notification is not useful for users who are deaf or hard of hearing.


 Make It Fast

A simple and responsive interface is more appealing than an attractive yet sluggish interface. An application should always be ready for user input and prepared to offer immediate feedback. Ideally, results should quickly follow the user's actions.

Where immediate results are not possible, run lengthy operations in separate threads if practical. This technique has the advantage of at least simulating speed by returning control quickly to the user.


 Make It Fun

Users will look for applications that have simple, creative interfaces that are fun to use when deciding what to keep on their portable pen-based machines. Paying special attention to the visual appeal of an interface pays off in gaining user acceptance. The most powerful interfaces are those that combine aesthetics with functionality.


 Make Exploration Safe

People like to explore applications and learn by trial and error. Such selfmotivated learning is extremely effective, but users might not always be aware of potential dangers. Even with the best-designed interface, users make mistakes — such as accidentally tapping the wrong object or data, or making a wrong decision about which data to select. The interface should accommodate user exploration by:

•	Softening any penalty caused by mistake.

•	Minimizing the opportunities for errors.

•	Handling user errors gracefully, without implying the user is at fault.

•	Allowing easy undo and undelete.

•	Keeping separate training databases to accommodate guest users.


 Let the User Maintain Control

People want to feel in control of an application. A well-designed, responsive user interface contributes much toward the user's perception of being in control. The following list gives design suggestions for achieving this:

•	Enable the user to interrupt long operations.

•	Discard meaningless user input during long operations. While waiting, users might randomly tap on the pen tablet or display. To dispose of spurious input in a discreet manner, enable your application to distinguish between meaningful and unintentional data.

•	Allow the user to specify desired default settings.


 Recognition: Use and Misuse

Recognition is often the deciding factor in how people react to pen-based computing. It is, unfortunately, an inexact science and always will be. The best applications will seek to minimize the potential for error introduced by recognition by restricting as much as possible the amount of recognition necessary. The following may give you some ideas.


 Selecting Is Better Than Writing

As much as possible, let the user select rather than write. For example, take advantage of spin-box and list-box controls that don't require written input. When prompting for a date, present the user with a simple calendar on which he or she can pick a date by tapping with the pen.

Keep track of previous entries and allow the user to select one from a list rather than having to rewrite it. For example, when prompting for a name, consider using a combo-box control to provide access to a list of the previous 10 or so names the user has last entered. This confines the potential for recognition errors to the first time the name is written.

When prompting for a filename, provide an option for browsing through directory lists, allowing the user to select a file and path by tapping the filename with the pen.


 bedit Is Better Than hedit

People prefer to write in the relatively unrestricted space of an hedit control, but the bedit control offers better recognition accuracy. The comb and box guides of a bedit also serve as discreet prompts, informing the user that the application awaits written input.

If saving screen space is important, consider using a lens instead of a bedit. Always create a single-line edit control with ES_AUTOHSCROLL so it shows a lens button.


 Real Time Is Better Than Deferred Time

Deferred recognition offers the seductive advantages of speed and instantaneous response. By collecting ink without pausing to recognize it, an application can easily keep up with rapid pen movements. The input can be recognized later when requested by the user, or perhaps during periods of user inactivity.

However, Microsoft tests have demonstrated that the accuracy of deferred recognition often compares unfavorably to real-time recognition. This has nothing to do with the recognizers, since they apply the same processing procedures to the data regardless of when the ink is collected. The discrepancy arises from the fact that people tend to write more carelessly if not continually informed about the recognizer's success rate.

By seeing the recognition results as they write, users naturally adapt their writing speed and style to assure the greatest recognition accuracy. Although in theory the user should train the recognizer, to a certain extent the reverse undeniably occurs.


 Make Corrections Easy

Users don't mind recognition errors as much as they mind the effort required to correct the errors. A good pen model focuses on making corrections as easy and fast as possible.

An error in recognition should never have unpleasant consequences. For example, misrecognizing an undo gesture wastes the user's time. When in doubt, prompt for confirmation and make confirmation easy — say, with an extra-large OK button. The extra step will annoy the user less than having to recover from the error.


 Provide Easy Access to the On-screen Keyboard

The on-screen keyboard serves well for short input, especially for correcting erroneous recognition results. An application should ensure that the on-screen keyboard is easily accessible to the user, yet remains unobtrusive. Microsoft usability studies have shown that users prefer writing to tapping on the on-screen keyboard, even though the latter is often faster because it avoids recognition errors. Consider making the on-screen keyboard more or less noticeable depending on whether your application runs on a desktop system with a real keyboard or on a handheld unit with no physical keyboard.


 Other Considerations

The developer of pen-based applications should consider other facets of pen computing besides recognition. This section lists a few ideas.


 Don't Rely on Gestures

In a well-designed pen application, all operations are possible without gestures. The application may support gestures as shortcuts, but should not sacrifice common operations for the sake of the gesture.

Gestures also tend to remain a hidden (or "nondiscoverable") functionality, which the novice user often does not guess at. Gestures should facilitate the experienced user without hampering the uninitiated.

Action handles provide the same benefits as gestures. Moreover, they are more discoverable and reliable, since they do not require recognition.

Every pen application should, at minimum, support the cut and lasso gestures. Anything else is at the discretion of the developer. Incidentally, usability tests have found that a common gesture among novice users is to scribble over an entry to erase or undo it. An intelligent application should respond to such unknown gestures and display a polite inquiry, listing possible alternative actions that the user can select by tapping.


 Provide Ample Target Space

The pen often proves an inaccurate pointing device. The well-behaved pen application allows ample margin for pointing errors from the user, who can easily miss a small button or other target. Consider the following suggestions to make your pen-based application friendly to the user with poor aim:

•	Create targets as large as practical.

•	Space toolbar buttons so that they have gaps between them.

•	Avoid crowding dialog boxes with controls placed near one another.

•	Pen-down events falling within a few pixels of a button should be treated as a press of that button. Always increase the effective size of a control by sending the HE_SETINFLATE submessage, as described in the "HE_SETINFLATE Submessage" section in Chapter 3, "The Writing Process."

•	Compensate for the pixel sizes of different displays. Use GetDeviceCaps to determine sizes and maintain uniform dimensions for on-screen targets.


 Use Position Clues

A pen-based application should consider position clues in determining the user's intentions. The following offers a few examples of inferring the user's desires from the position of the ink:

•	A gesture drawn over part of a selection should operate on the entire selection. In the same vein, a gesture or lasso that intersects more than a single letter of a word is probably meant for the entire word.

•	Writing text on a line below existing text serves as a good indication the user intends the new text to go on a new line. In this case, an application can insert a newline character automatically.

•	Text written over an insertion point should be inserted at the insertion point.


 Conserve Power

A pen-based environment will often be found on small notebook- or handheld-size computers. Users will appreciate pen-based applications that extend battery life by conserving power. Here are a few power-saving tips:

•	Avoid "disk hits" as much as possible. Hard disks on small systems often turn off after a period of inactivity and powering them up again significantly affects battery life. An application should avoid unnecessarily accessing the disk, since doing so may force the system to repower the drive.

•	Keep code and data files small to minimize the disk swapping Windows must do to clear memory. Restrict the number of dynamic-link library (DLL) files your application requires and consider loading the DLLs early. In this way, Windows reads the DLL files immediately after having loaded the application itself, while the disk is still in motion. Linking to a DLL's import library ensures that the DLL is installed at the same time as the application.

However, this advice applies only to small DLL files and DLLs that the application will most likely use at some point. Large DLL files that stand a good chance of not being required by the application should be loaded explicitly only when needed by calling the InstallRecognizer function or the LoadLibrary function. Although this risks powering up a dormant disk drive, it also prevents unneeded objects from occupying memory.

•	Prefer visual to auditory signals. Besides the negative reasons cited in the "Use Feedback" section, beeps from the speaker also waste battery power.

•	Reduce video power drain by making background colors black.


 Guidelines for Applications

The following presents some recommended approaches for different types of applications, based on the guidelines presented above. While by no means exhaustive, the material may give you some ideas for various types of applications.


 Annotation

Many different types of software can benefit from the unique advantages of pen-based annotation. A user annotates by writing with a pen on top of an existing document, as though on an overlaying transparent sheet. This allows adding to the document free-form writing such as notes, diagrams, review comments, questions, and so forth.

Unless evident by the context, an application should prompt the user to identify a position in the document to attach the annotation. This prevents the annotation from drifting from its intended location if the underlying document is changed.

Often, annotated text remains unrecognized, captured as ink data. Reduce such text to display resolution to minimize the file space it occupies. For more information on how to achieve maximum compression of handwritten text, see "Converting Data to Display Resolution"  in Chapter 4.


 Word Processor

Although the pen does not serve well to create a word-processor document, it can do so for small editing tasks on existing documents, such as for cut-and-paste operations, formatting changes, rewriting small amounts of text, and navigation (scrolling). Thus, the pen in a word-processing application should behave as a pointing device most of the time. The user should be able to select text by dragging the pen and the selection should include an action handle. Double-tapping should display a writing window, as should an "edit" command on a selection action handle. Consider also providing an insertion-point action handle, including an "insert text" command.

When the user creates a new blank document, the application should automatically display an editing window because the user clearly intends to enter new text. For existing documents, the application should provide a means for annotating the text, either by inserting scribble notes (like Post-it™ notes) or by inking directly on top of the text.


 Spreadsheet

Within the spreadsheet area, the pen should default to a pointer. If the application allows in-cell editing, double-tapping the cell should open a writing window in which the user can write or edit the contents of the cell. This window should include a palette of commonly entered symbols such as "*" or formula names that are hard to recognize. This allows the user to enter an unambiguous symbol by tapping an appropriate button.

A formula bar area should behave more like the word-processor application just described. If the area is empty, the application should display the writing window automatically. Naturally, the recognizer should be configured according to the type of input expected, whether text, numerical, or whatever.

Annotation, including quick notes and diagrams, represents an ideal usage of a pen in a spreadsheet application. Often, annotated text can be kept as ink and does not require recognition. Anchoring and targeting annotations on a spreadsheet is somewhat easier than on a word-processing document because cells do not flow in the same manner as text. Annotations should be anchored to the data and not the cell. This ensures that, if the data moves to another cell, the annotation moves with it.

Because spreadsheets contain much data that is not based on words, on-screen keyboards should be easy to display (and automatic in many circumstances). As with word-processing applications, writing in a spreadsheet will most likely be limited to small editing and format changes.

The user will often wish to edit the contents of a single cell to see how it affects the rest of the spreadsheet. To facilitate this operation with a pen, the application should anticipate as much as possible. For example, double-tapping a field containing a numeric value should display a numeric on-screen keypad.

If the spreadsheet offers text entry with recognition, it should provide an appropriate tool accessible from a toolbar or menu. When the user selects text-entry mode, the spreadsheet should enlarge (zoom), allowing the user to write comfortably within a cell. The application can rely on the automatic targeting capabilities provided by the Pen application programming interface (API), described in Chapter 2, to route text appropriately to different cells.


 Mail

Perhaps the most common operations in electronic mail with a pen are navigation, annotation, responding to and forwarding mail, and composition of short notes.

When the user selects "new" to create a new blank message or presses a "reply" or "forward" button, the application should automatically display a writing window in which the user can enter new text. In the case of the reply and forward operations, the writing window should include the text of the original message. The user may wish to selectively edit or delete parts of the original message when replying or forwarding. The application should provide action handles for this.


 Forms

Pen computers are ideal for filling out electronic forms. Forms applications can achieve superior handwriting recognition for several reasons:

•	The bedit control with its built-in guides serves perfectly in many if not all the writing sections of a form.

•	Because each writing window of an electronic form often expects input of a certain type, the forms application can constrain recognition to that type. For example, an application can restrict recognition to numerals for a control window that expects a telephone number.

•	Through the use of word lists such as local street names or regional cities, a recognizer can greatly improve accuracy for certain input sections of the form.

Forms usually appear blank or nearly blank by default, so the most common operation in a forms application is adding text. The system's automatic targeting routes input to the proper control window without intervention by the application.

A writing window should appear automatically on the appropriate field if recognized text produces questionable results. Double-tapping should display a writing window, and the application should provide a lens (writing window) and on-screen keyboard accelerator buttons. It should also provide insertion-point action handles for selection.


 Shell

The most common shell operations involve selecting files, opening files or running programs, dragging filenames to copy or move files, and deleting files. A pointer-based interface serves all such operations well. Therefore, the pen should behave as a pointer in the shell. Tapping or dragging a rectangular marquee should select files, double-tapping should open files, and dragging should copy or move files. The shell can provide deletion services on selected files either through a "delete" option in a menu or by handling a cut gesture.


 A Sample Pen Application

This chapter describes a simple pen-based application called PENAPP that demonstrates some of the programming techniques covered in the previous chapters. The source code in this chapter is fragmentary, illustrating only the most interesting parts of the application. For the complete source listing, see the file PENAPP.C in the Microsoft Win32 Software Development Kit, in the SAMPLES\PEN\PENAPP directory.

PENAPP uses the sample recognizer SREC, described in the next chapter, "Writing a Recognizer." The source files for SREC also reside in the SAMPLES directory. To see PENAPP in action, you must first build both PENAPP.EXE and SREC.DLL using the supplied makefiles. Place the  SREC.DLL file in your Windows directory or in a directory on the PATH list before running PENAPP.

The SAMPLES\PEN directory also provides source code for other sample pen-based applications. All code is commented, demonstrating different approaches to different issues.


 Overview of PENAPP

PENAPP is a standard pen-based application with the familiar Windows look. It displays a main window with a border, an application menu, and Minimize and Maximize buttons. It also has three child windows titled Input, Info, and Raw Data.

In operation, PENAPP accepts pen input through the Input child window. Depending on the menu option, PENAPP sends the input to the system recognizer or the sample custom recognizer SREC, or collects the data into an HPENDATA object to create a mirror image of the ink.

The output from the recognizers is displayed through the Raw Data and Info child windows. The Raw Data child window redisplays the raw input data, sized for the smaller window. The Info child window displays one of the following, depending on the current menu selection:

•	If the selected recognizer is the system recognizer, the Info child window displays the recognized ANSI text.

•	If the selected recognizer is the sample custom recognizer, the Info child window displays an arrow indicating the compass direction of the input stroke. If the pen rests on the tablet surface without moving, the Info window displays a single dot.

•	If the Mirror option is selected, the Info window displays a mirror image of the drawing.

In this chapter, PENAPP function and variable names appear in monospace font, including the application's entry function, WinMain. In keeping with the conventions of the rest of the book, API elements are styled bold.


 Initialization

The PENAPP function WinMain is a standard Windows entry function. PENAPP uses initialization functions, called InitApp and InitInstance, to create windows and initialize data. To an experienced programmer in Windows, the WinMain and initialization functions will look very familiar.


 WinMain

The WinMain function performs the same tasks as a regular Windows function:

•	It calls the initialization functions to register window classes and create windows.

•	It enters a message loop to process messages from the application queue.

•	The message loop ends when the user chooses Exit from the menu, generating a WM_DESTROY message, which in turn posts a WM_QUIT message to WinMain. When the GetMessage function detects the WM_QUIT message, it returns NULL to end the loop.

The WinMain function calls GetSystemMetrics to check whether pen services are installed. If they are not found, the application should either exit with an explanatory message or alter its behavior to run without pen input.

Note that Microsoft pen services must be installed when Windows starts. Simply linking PENWIN.DLL and loading it at runtime is not sufficient to initialize pen services. For this reason, unless it is known that the application being developed  will always be run on a system with pen services installed, pen API should  be called through function pointers. This mechanism insures that a pen-aware application can run only on a system on which pen services has been properly installed and will not run on any system that merely has PENWIN.DLL on the path. See the HFORM sample application for an example of this technique.

For the sake of simplicity and readability, the PENAPP application described in this chapter links directly to PENWIN.DLL and does not use function pointers.

int PASCAL	WinMain(

HANDLE hInstance,	// Instance handle

HANDLE hPrevInstance,	// Previous instance handle

LPSTR lpszCommandLine,	// Command line string

int cmdShow )	// ShowWindow flag

{

MSG	msg;

// Mention to prevent compiler warnings ....

lpszCommandLine;

if (!hPrevInstance)	// If first instance,

if (!InitApp( hInstance ))	//   register window class

return FALSE;	// Exit if can't register

if (!InitInstance( hInstance, nCmdShow ))

// Create this instance's window

return FALSE;	 	// Exit if error

if (!GetSystemMetrics( SM_PENWINDOWS ))	// If no pen services

return FALSE;	// exit

while (GetMessage( (LPMSG) &msg, NULL, 0, 0) )

{

TranslateMessage( (LPMSG) &msg );

DispatchMessage( (LPMSG) &msg );

}

return 0;	// Success

}

The InitApp function initializes data and registers the window classes. Following standard programming practice for Windows, the function returns FALSE if it cannot register the window classes.

For the Input window, InitApp specifies a cursor type of IDC_PEN. This is the default cursor type supplied by the pen-aware display driver. For more information on pen types, see the reference section for the IDC_ constants in Chapter 13, "Pen Application Programming Interface Constants."

The following fragment shows how InitApp creates the Input window:

BOOL	InitApp( HANDLE hInstance )	// Instance handle

{

WNDCLASS	wc;

.

.

.

//

// Register PenApp child window classes

//

wc.hCursor       = LoadCursor( NULL, IDC_PEN );

wc.hIcon         = NULL;

wc.lpszMenuName  = NULL;

wc.lpszClassName = (LPSTR) szPenAppInputClass;

wc.hbrBackground = (HBRUSH) (COLOR_WINDOW + 1);

wc.style         = CS_VREDRAW | CS_HREDRAW | CS_SAVEBITS;

wc.lpfnWndProc   = InputWndProc;

if (!RegisterClass( (LPWNDCLASS) &wc) )

return FALSE;

.

.

.

}


 InitInstance

The InitInstance function initializes all data structures for the program instance and creates the necessary windows. InitInstance looks like a standard Windows initialization function except that it calls the InstallRecognizer function to load the default recognizer SREC. Windows loads the default recognizer automatically, so a program should call InstallRecognizer to load only recognizers other than the default recognizer.

The following fragment taken from the InitInstance function shows how the program loads the SREC recognizer:

BOOL	InitInstance(

HANDLE hInstance,	// Instance handle

int cmdShow )	// ShowWindow flag

{

.

.

.

//

// Load sample recognizer SREC

//

vhrec = InstallRecognizer( (LPSTR) szSampleRec );

if (vhrec)

return TRUE;

else

{

   MessageBox( vhwndMain, "Could not install recognizer SREC",

    szPenAppWnd, MB_OK | MB_ICONSTOP );

   return FALSE;

}

}


 Window Procedures

PENAPP provides a separate procedure to handle messages for each of its four windows. In accordance with usual programming techniques for Windows, each window procedure passes all unprocessed messages to DefWindowProc for default processing.

The following sections describe the procedures for the Main, Input, Raw, and Info windows.


 MainWndProc

As its name implies, the MainWndProc function handles messages sent to the program's parent (main) window. These messages signal that the user has made a menu selection, resized the window, or changed the pen system through Control Panel. These actions generate, respectively, the following messages:

•	WM_COMMAND message. If the user selects a command from the Options menu, the program notes the selection in the global flag viMenuSel. The state of this flag determines whether subsequent input goes to the system recognizer or the sample recognizer SREC, or is collected into an HPENDATA object for conversion to a mirror image.

•	WM_SIZE message. PENAPP resizes its windows according to the information in the lParam variable.

•	WM_PENMISCINFO message. The procedure allows this message to fall through to DefWindowProc for default handling.

LRESULT CALLBACK	MainWndProc(

HWND hwnd,	// Window handle

UINT message,	// Message

WPARAM wParam,	// Varies

LPARAM lParam )	// Varies

{

LONG	lRet = 0L;

.

.

.

switch (message)

{

case WM_COMMAND:

switch (wParam)

{

case miExit:

DestroyWindow( vhwndMain );

break;

case miSample:

case miSystem:

case miMirror:

ResetWindow( wParam );

break;

}

break;

.

.

.

case WM_DESTROY:

if (vhpendata)

{

// PKPD.DLL API: function pointer not needed:

DestroyPenData( vhpendata );

vhpendata = NULL;

}

//

// Unload sample recognizer. (Don't

// unload system default recognizer.)

//

UninstallRecognizer( vhrec );

vhrec = NULL;

PostQuitMessage( 0 );

break;

default:

lRet = DefWindowProc( hwnd, message, wParam, lParam );

break;

}

return lRet;

}


 InputWndProc

The InputWndProc procedure receives the WM_LBUTTONDOWN message that signals the start of an input session. It distinguishes between a pen-down event and a true mouse event, using the methods described in the "Beginning an Input Session" section in Chapter 2.

When it detects the start of a pen-input session, InputWndProc calls the DoDefaultPenInput function to handle the chores of initialization, data collection, and inking.

As described in the "Step 3: PE_GETPCMINFO Message" section in Chapter 2, InputWndProc immediately receives a PE_GETPCMINFO submessage. The lParam variable points to an initialized PCMINFO structure that the system will use for recognition. The SREC recognizer requires the structure to specify a pen-up event as a condition of termination. Accordingly, InputWndProc takes this opportunity to set the PCM_PENUP flag.

InputWndProc next receives a PE_BEGINDATA submessage, as described in "Step 6:  PE_BEGINDATA Message" in Chapter 2. In response, the procedure takes one of the following courses of action:

•	If currently using the sample recognizer, InputWndProc creates an HRC object for that recognizer and specifies the HRC in the TARGET structure pointed to by lParam. This tells DoDefaultPenInput to use the sample recognizer SREC instead of the system default recognizer.

•	If displaying a mirror image of the ink, InputWndProc creates an HPENDATA object for the ink and specifies it in the TARGET structure pointed to by lParam. This tells DoDefaultPenInput to collect data into the HPENDATA block instead of passing it to a recognizer.

•	If using the default recognizer, InputWndProc simply passes the message to DefWindowProc, which creates an HRC for the default recognizer. The code also demonstrates how an application can take advantage of the convenience afforded by DefWindowProc, yet override any default assumptions it makes.

When DefWindowProc returns, lParam still points to the TARGET structure, which now reflects the default assumptions. One of these assumptions limits to one the maximum number of guesses the system recognizer should return. Since PENAPP requires a maximum of five guesses, it changes the value by calling SetMaxResultsHRC for the HRC that DefWindowProc creates.

The PE_ENDDATA submessage informs InputWndProc that the input session has ended. The procedure collects any symbols returned by the current recognizer into an array of symbol strings called vsyvSymbol. This portion of the code does not check to see which menu option is current. It simply collects symbols into the array if available. If the Mirror option is selected, the attempt to collect recognized symbols harmlessly fails since no HRC exists.

After it collects the data, InputWndProc invalidates all three child windows. This sends WM_PAINT messages to each window, clearing the Input window and causing the other two windows to display their new data.

#define	MAX_GUESS	5	// Maximum number of guesses

#define	MAX_CHAR	20	// Maximum number of characters per guess

// Global Variables ***************************************************

HRCRESULT	vrghresult[MAX_GUESS];	 // Array of results

SYV	 vsyvSymbol[MAX_GUESS][MAX_CHAR];	 // Array of symbol strings

int	vcSyv[MAX_GUESS];	 // Array of string lengths

.

.

.

LRESULT CALLBACK	InputWndProc(

HWND hwnd,	// Window handle

UINT message,	// Message

WPARAM wParam,	// Varies

LPARAM lParam )	// Varies

{

LONG	lRet = 0L;	// Initialize return code to FALSE

HRC	hrc;	// HRC object

HDC	hdc;

PAINSTRUCT	ps;

DWORD	dwInfo;

int	i, cGuess;

switch (message)

{

.

.

.

 case WM_LBUTTONDOWN:

//

// Two possibilities exist: user is using mouse or the pen.	// The latter case indicates the user is starting to write.

//

dwInfo = GetMessageExtraInfo();

if (IsPenEvent( msg, dwInfo ))

{

  if (DoDefaultPenInput( vhwndInput,

 (UINT)dwInfo ) == PCMR_OK)

lRet = TRUE;

else

lRet = DefWindowProc( hwnd, msg, wParam, lParam );

}

break;

case WM_PENEVENT:

switch (wParam)

{

  case PE_GETPCMINFO:

//

// If using SREC recognizer, ensure session ends

// on pen-up.

//

if (viMenuSel == miSample)

((LPPCMINFO) lParam)->dwPcm |= PCM_PENUP;

lRet = DefWindowProc( hwnd, msg, wParam, lParam );

break;

case PE_BEGINDATA:

//

// 1) If using sample recognizer, create an HRC

//    for it and specify it in the TARGET structure

//    pointed to by lParam.  This tells

//    DoDefaultPenInput to use the sample recognizer

//    instead of the system default.

//

// 2) If displaying mirror image of ink, create an

//    HPENDATA for it.  This tells DeDefaultPenInput

//    to collect data into the HPENDATA object

//    instead of passing it to a recognizer.

//

// 3) If using default recognizer, pass to

//    DefWindowProc.  DefWindowProc sets the maximum

//    number of guesses to 1; the code below shows

//    how to access the HRC that DefWindowProc

//    creates and reset the maximum number of

//    guesses to MAX_GUESS.

//

if (vhpendata)

{

DestroyPenData( vhpendata );

vhpendata = NULL;

}

switch (viMenuSel)

{

case miSample:

hrc = CreateCompatibleHRC( NULL, vhrec );

if (hrc)

{

((LPTARGET) lParam)->dwData = hrc;

lRet = LRET_HRC;

}

break;

case miMirror:

vhpendata = CreatePenData( NULL, 0,

   PDTS_HIENGLISH, 0 );

if (vhpendata)

{

((LPTARGET) lParam)->dwData = vhpendata;

lRet = LRET_HPENDATA;

}

break;

case miSystem:

lRet = DefWindowProc( hwnd, msg,

  wParam, lParam );

//

// On return, lParam->dwData points to HRC.

// Use it to reset max number of guesses.

//

SetMaxResultsHRC(

   ((LPTARGET) lParam)->dwData,

   MAX_GUESS );

break;

}

break;

case PE_ENDDATA:

//

// DefWindowProc will destroy vhpendata, so if

// collecting mirror image, don't let DefWindowProc

// handle message.

//

   if (viMenuSel != miMirror)

   lRet = DefWindowProc(hwnd, msg, wParam, lParam);

   break;

case PE_RESULT:

//

// At end of input, collect recognition results (if

// any) into symbol strings.  DoDefaultPenInput

// generates the PE_RESULT submessage only when

// using a recognizer.  The lParam contains the HRC

// for the recognition process.

//

// Collect pen data for DrawRawData

vhpendata = CreatePenDataHRC( (HRC) lParam );

// Initialize array to zero

for (i = 0; i < MAX_GUESS; i++)

vcSyv[i] = SYV_NULL;

// Get number of guesses available

cGuess = GetResultsHRC( (HRC) lParam,

 GRH_ALL,

 (LPHRCRESULT) vrghresult,

 MAX_GUESS );

// Get guesses (in vsyvSymbol) and

// their lengths (in vcSyv)

if (cGuess != HRCR_ERROR )

for (i = 0; i < cGuess; i++)

vcSyv[i] = GetSymbolsHRCRESULT(

    vrghresult[i],

    0,

    (LPSYV) vsyvSymbol[i],

    MAX_CHAR );

break;

.

.

.

default:

lRet = DefWindowProc( hwnd, msg, wParam, lParam );

}	// End switch (wParam)

break;

default:

lRet = DefWindowProc( hwnd, message, wParam, lParam );

  }	// End switch (msg)

return lRet;

}


 InfoWndProc

PENAPP displays results in the Info window. When the InfoWndProc procedure receives a WM_PAINT message, it calls one of three functions to display the results, depending on the current menu selection. It calls:

•	DisplayGuesses if the Default option is chosen.

•	DrawArrow if the Sample option is chosen.

•	DrawMirrorImage if the Mirror option is chosen.

The following list describes the three functions and points out interesting portions of their code.


 DisplayGuesses

The DisplayGuesses function writes the guesses returned from the default recognizer. The guesses appear in a column, listed in descending order of confidence. The for loop shown below converts the symbol values to characters, then calls the Windows function TextOut to display the text.

VOID	DisplayGuesses( HDC hdc )	// DC handle

{

TEXTMETRIC	tm;

int	nX, nY;	// Text coords

.

.

.

for (i = 0; i < MAX_GUESS; i++)

{

if (vcSyv[i])

{

SymbolToCharacter( (LPSYV) vsyvSymbol[i],

  vcSyv[i],

  (LPSTR) szText,

  (LPINT) &cChar );

TextOut( hdc, nX, nY, (LPSTR) szText, cChar );

nY += tm.tmExternalLeading + tm.tmHeight;

}

}

}


 DrawArrow

DrawArrow draws an arrow to indicate the symbol value returned from the SREC recognizer. SREC returns a compass direction determined from the start and end points of the stroke. DrawArrow reads the direction in vsyvSymbol and diplays an appropriate arrow.


 DrawMirrorImage

DrawMirrorImage creates a mirror image of the data by subtracting each x-coordinate from the tablet width. This moves each point from one side of the tablet to a corresponding position on the other side. In other words, the original distance from the tablet's left side now becomes the point's distance from the tablet's right side.

DrawMirrorImage works in five steps:

1.	Creates a duplicate HPENDATA of the input data.

2.	Calls TrimPenData to remove unneeded information from the block.

3.	Converts the new HPENDATA block to a mirror image.

4.	Displays the mirror image by calling DrawPenDataFmt.

5.	Deletes the mirror image HPENDATA block.


 RawWndProc

The RawWndProc function is a standard Windows procedure for the Raw Data child window. It calls the DrawRawData function to draw a copy of the input resized for the Raw Data window. Normal pen-down strokes appear in the current window color; pen-up strokes appear in blue. Note that the system recognizer GRECO.DLL does not collect pen-up strokes. Therefore, the blue pen-up strokes do not appear when default recognition is selected from the menu.

DrawRawData calls the DrawPenDataEx function to display the strokes. Since DrawPenDataEx does not show pen-up strokes, DrawRawData first changes all pen-up strokes to pen-down strokes. The following fragment illustrates this:

VOID DrawRawData( HDC hdc )

{

PENDATAHEADER   pendataheader;  // Header for vhpendata

HPEN	         hpenUp, hpenSave;  	// GDI pen for up-strokes

UINT            fPen;           // Pen flag

UINT            iStroke=0;      // Stroke counter

int             nWidth;         // Ink width

.

.

.

if ( !GetPenDataInfo( vhpendata, &pendataheader, NULL, 0 ))

return;

nWidth   = NSetExtents (hdc, &pendataheader, &rectWnd );

hpenUp   = CreatePen( PS_SOLID, nWidth, rgbBlue );

hpenSave = SelectObject( hdc, hpenUp );

// Loop for each stroke, beginning with first

for (iStroke = 0; iStroke < pendataheader.cStrokes; ++iStroke)

{

//

// If down stroke, use same ink characteristics as original.

// If up stroke, first call SetStrokeAttributes to convert it

// to a down stroke, then draw it in blue ink with GDI pen.

//

 	 if (GetStrokeAttributes(vhpendata, iStroke, NULL, GSA_DOWN))

fPen = DPD_DRAWSEL;

  else

  {

SetStrokeAttributes( vhpendata, iStroke, 1, SSA_DOWN );

fPen = DPD_HDCPEN;

  }

  iRet = DrawPenDataEx(hdc, NULL, vhpendata, iStroke, iStroke,

  0, IX_END, NULL, NULL, fPen );

 	 // Set altered strokes back to their original pen-up state

 if (fPen == DPD_HDCPEN)

   SetStrokeAttributes( vhpendata, iStroke, 0, SSA_DOWN );

}

SelectObject( hdc, hpenSave );

DeleteObject( hpenUp );

return

}


 Writing a Recognizer

A recognizer is a dynamic-link library (DLL) that interprets lines of ink as characters and symbols. Version 2.0 of the Pen API allows a pen-based application to install multiple recognizers and use them selectively. Each recognizer should specialize in recognizing a particular set of symbols instead of trying to handle many different types. Besides keeping the recognizer code manageable, this approach lets an application choose among several available recognizers to fulfill its current recognition needs.

The recognizer developer must know both sides of the interface between application and recognizer. The foregoing chapters, particularly Chapter 5, "The Recognition Process," should be read before venturing into this one.

Such a developer should also have some familiarity with the coding requirements of a DLL. For information about how to write a DLL, see the Guide to Programming manual in the Microsoft Windows Software Development Kit. In addition, the "Writing a Dynamic-Link Library for Windows" chapter in the MASM version 6.1 Programmer's Guide offers valuable information about DLL coding requirements.

This chapter describes the framework of a recognizer DLL and the functions it must export. The final section presents a sample recognizer called SREC. The source file for SREC resides in the SAMPLES\PEN\SREC subdirectory.


 Recognizer Objects

Three objects serve the process of recognition, identified by their handles: recognition context (HRC), recognition context result (HRCRESULT), and word list (HWL). The structure and implementation of these objects are left to the recognizer developer and remain invisible to applications and the system. However, the objects must comply with the following two requirements:

•	The handle value must be a 32-bit pointer to the object in memory.

•	The first DWORD (32 bits) of the memory that the handle points to is reserved for system use. The recognizer must not alter the DWORD value during the life of the object.

Thus, a recognizer's internal structure of a recognition object should be of the following form:

typedef struct {

DWORD dwReserved;

.

.

.

} INTERNALOBJECT;

It is the application's responsibility to destroy the recognition objects when finished. A recognizer should validate all handles to ensure an object exists before processing. Although a product of an HRC, an HRCRESULT is usually an independent object. Destroying an HRC does not destroy its HRCRESULT objects, which remain valid objects and must be destroyed separately.

A single HWL object can be associated with multiple HRC objects at any given time. The recognizer should not allow alteration of an HWL while processing any of its associated HRC objects. Similarly, the recognizer should not allow destruction of an HWL before the destruction of all its associated HRC objects. In either case, the recognizer should return an error to the application.


 How a Recognizer Works

There are two techniques for recognizing handwriting, called bitmap and vector recognition.

Bitmap recognition attempts to match an ink image with a record of known character images. The bitmap recognizer sees the ink data as a stencil pattern of points that it can compare to a library of patterns, searching for the closest match. This technique, employed by optical character recognizers (OCRs), works well for patterns limited to a few styles and sizes.

In contrast, vector recognition sees the ink as lines rather than points. The method considers characteristics of the lines collected as the pen moves. These characteristics include sequence, curvature, direction, and so forth. Given the wide varieties and styles of handwriting, vector recognition works best for deciphering pen input. The Pen API does not mandate which method a recognizer employs, but is designed to facilitate vector rather than bitmap recognition.


 List of Exported Functions

Technically, an application does not call directly into a recognizer's exported functions, though the distinction is not important to the recognizer. Instead, all calls go to the system, which acts as a switchboard to route the calls to the proper recognizer when more than one recognizer is installed. For example, when an application loads a recognizer with InstallRecognizer, that recognizer exports functions with the same name as those exported by other recognizers, including the default recognizer. The system automatically transfers calls to the correct recognizer based on the HRC argument or other value that identifies the intended recipient.

As a DLL, a recognizer must export functions to the pen system that installs the recognizer. This section lists these recognition functions, describes their purpose, and identifies them as required or optional.

The optional functions that a recognizer should provide depend on the clients it will serve. Commonly, a recognizer DLL is part of an application package designed only for that application. As author of both client application and its private DLL, the developer need write only those functions the application requires. In this case, the developer is also free to design other functions not specified by the Pen API.

At the other extreme, some recognizers serve client applications indiscriminately. For example, a developer might market a recognizer of foreign script to various application developers with international product lines. A recognizer can also take on the role of system default recognizer, in which case it must:

•	Export all recognizer functions.

•	Recognize letters, punctuation, numbers, and predefined gestures from ink data.

•	Associate raw data with matched results.

•	Return characters only within the requested subset.

•	Return an "I don't know" response when appropriate.

A system default recognizer should support all recognizer functions, not merely export stub versions of the optional functions. At the very least, the recognizer must return an HRCR_UNSUPPORTED value from functions it does not support. For a description of how to specify the system recognizer through the registry, see Appendix A, "Differences Between Versions 1.0 and 2.0 of the Pen Application Programming Interface."

The following sections describe all 47 recognition functions of the Pen API version 2.0. The lists of functions represent the following categories:

•	Initialization

•	HRC functions

•	HRCRESULT functions

•	Alphabet support

•	Word lists

•	Training

All recognizers must export 13 required functions, which are indicated by asterisks in the following tables. The functions without asterisks are optional for a recognizer. Each table corresponds to one of the categories listed previously, with functions arranged in alphabetic order within the table.


 Initialization

The Pen API specifies the following functions for initializing, modifying, and closing down the recognizer. Note that, in version 2.0 of the Pen API, the required function ConfigRecognizer handles all initialization and configuration tasks. The other initialization functions are obsolete in version 2.0 and should only be included in a recognizer if it is expected to work with older applications that work with a version 1.0 recognizer (see the Microsoft Pen Windows, version 1.0 documentation for descriptions of these functions).

Function	Description
ConfigRecognizer*	Provides access for querying or altering recognizer configuration. In version 2.0, only the system calls ConfigRecognizer. Applications call ConfigHREC, which the system translates into a call to ConfigRecognizer.
CloseRecognizer	Required only for compatibility with version 1.0 API. Called when the system uninstalls a version 1.0 recognizer.
InitRecognizer	Required only for compatibility with version 1.0 API. Called when the system installs a version 1.0 recognizer.
RecognizeDataInternal	Required only for compatibility with version 1.0 API. The system calls this function only when an application calls RecognizeData.
RecognizeInternal	Required only for compatibility with version 1.0 API. The system calls this function only when an application calls Recognize.


 HRC Functions

In general terms, the HRC functions carry out the recognition process. Together, they collect raw data, derive recognized symbols from the data, and place the symbols into HRCRESULT objects. Their work ends with recognition. To retrieve the recognized symbols, an application calls the HRCRESULT functions described in the next section.

Function	Description
AddPenInputHRC*	Adds input to the recognizer's HRC object. This function is normally called at every pen movement, providing data a few points at a time.
CreatePenDataHRC	Returns an HPENDATA handle for the pen data within the HRC.
CreateCompatibleHRC*	Creates an empty HRC object, ready to receive input data.
DestroyHRC*	Frees the memory occupied by an HRC object, invalidating the handle value.
EnableGestureSetHRC	Enables or disables the recognition of a specified set of gestures.
EnableSystemDictionaryHRC	Specifies whether or not the recognizer should use its dictionary to validate recognition guesses.
EndPenInputHRC*	Notifies the recognizer that input has ended for the session. This function does not initiate recognition of the collected data; the client application must call ProcessHRC to do that.
GetBoxResultsHRC	Gets recognition results for a range of boxes.
GetGuideHRC	Retrieves a copy of the GUIDE structure (if any) used in the HRC.
GetHRECFromHRC*	Gets the module handle to the recognizer DLL attached to the HRC.
GetMaxResultsHRC	Gets the current maximum number of guesses the recognizer can make for the HRC.
GetResultsHRC*	Retrieves recognition results as HRCRESULT objects. Each object represents one guess.
ProcessHRC*	Tells the recognizer that it should begin recognition and sets the maximum amount of time allowed for the task.
SetGuideHRC	Specifies a GUIDE structure for recognition.
SetMaxResultsHRC	Sets the maximum number of guesses the recognizer can make for the HRC.


 HRCRESULT Functions

The HRCRESULT functions retrieve recognized symbols and other associated information from the recognizer. The GetResultsHRC function described in the previous table collects results into one or more HRCRESULT objects. Each object represents an alternative interpretation the recognizer has made about the input. Once an application calls GetResultsHRC to create the HRCRESULT objects, it can then call the HRCRESULT functions listed here to get the recognized characters from the objects.

Function	Description
CreateInksetHRCRESULT	Creates an inkset corresponding to recognition results.
DestroyHRCRESULT*	Frees the memory occupied by an HRCRESULT object, invalidating the handle value.
GetAlternateWordsHRCRESULT	Retrieves alternative guesses from the results of a recognition process.
GetBoxMappingHRCRESULT	Retrieves the indices for a range of symbols in boxes. For example, if writing begins in the fifth box of a guide, this function returns the index 4 for the first symbol.
GetHotspotsHRCRESULT	Returns the critical point for a given recognized gesture. (See the "Hot Spots" section.)
GetSymbolCountHRCRESULT*	Gets the length of the symbol array that forms one of the recognizer's guesses.
GetSymbolsHRCRESULT*	Retrieves symbol values corresponding to one of the recognizer's guesses.


 Specifying an Alphabet Set

By supporting the following alphabet functions, a recognizer enables an application to specify which alphabet sets to consider during recognition. Alphabets are sets of characters within the entire range of characters the recognizer can interpret. For example, an application can limit recognition to any combination of lowercase characters, punctuation, math symbols, and so forth.

The Pen API defines ALC_ values to identify an alphabet set. For further information on alphabets and an abbreviated list of the most common ALC_ values, see "Configuring the HRC" in Chapter 5, "The Recognition Process." A full list of ALC_ values appears in Chapter 13, "Pen Application Programming Interface Constants."

The Pen API allows an application to set a priority when using multiple alphabet sets. Priority can resolve conflicts when one glyph has different interpretations in different alphabets. For example, consider a case in which input consists of both letters and numerals, but the application expects numerals more often. By setting an alphabet of ALC_ALPHANUMERIC and a priority of ALC_NUMERIC, the application tells the recognizer to consider both letters and numerals, but interpret for numerals first. This helps resolve the problem of distinguishing between the numeral "0" and the letter "O."

The following table lists the optional recognizer functions that pertain to alphabets.

Function	Description
GetAlphabetHRC	Retrieves bitwise-OR flags of ALC_ values indicating which alphabet(s) the recognizer can currently recognize.
GetAlphabetPriorityHRC	Retrieves bitwise-OR flags of ALC_values indicating priority.
SetAlphabetHRC	Constrains recognition to a specified set of alphabet characters.
SetAlphabetPriorityHRC	Specifies the priority of alphabets used during recognition.
SetBoxAlphabetHRC	Constrains recognition to a set of specified alphabet characters for individual boxes in a group of boxes.


 Word Lists

A word list acts as a broad alphabet set. A list consists of valid words that can influence the confidence a recognizer places in a guess. After guessing at a word (or phrase), a recognizer can search for the guess in one or more word lists. Locating a guess in a word list helps verify the validity of the guess.

A word list can consist of a small group of words permanently stored in the recognizer's data segment. Often, however, the words reside in an accompanying file that the recognizer reads as required. A word list file should be in standard ANSI text format, one word per line, with each line ending in a carriage return and linefeed. This allows the user to emend the files, if necessary, with a text editor.

A recognizer that uses word lists should export the ReadHWL and WriteHWL functions. These functions read and write standard word list files, enabling an application to move words directly between a file and an HWL object.

The table below lists the exported functions for a recognizer that uses word lists.

Function	Description
AddWordsHWL	Adds a specified collection of words to an existing word list in memory.
CreateHWL	Creates a word list in memory, either empty or containing a given list of words.
DestroyHWL	Destroys a word list, invalidating the handle.
GetWordlistCoercionHRC	Retrieves the current degree of influence a word list or the system dictionary has on the confidence level of a guess.
GetWordlistHRC	Retrieves a word list from the HRC object.
ReadHWL	Reads from a file into an empty word list. The words must be in ANSI text format, one word per line, each line ending with a carriage return and linefeed.
SetWordlistCoercionHRC	Specifies the influence a word list or the system dictionary should exert on the confidence level of a guess.
SetWordlistHRC	Sets a word list into the HRC object.
WriteHWL	Writes from a word list to a file. The words are written as ANSI text, one word per line.


 Training

Training is optional for a recognizer and the method of its implementation is up to the developer. Through training, a recognizer can consider the individual style and writing characteristics of different users when interpreting handwriting.

Training can be classified as either passive or active. However, the distinction usually pertains more to the application than to the recognizer. In passive training, the application quietly calls the recognizer's training functions whenever the user corrects a wrong guess. Correctly implemented, passive training helps ensure that the recognizer learns from its mistakes.

Active training takes place only when specifically requested by the user. A training window prompts the user for written samples, then the verified input is given to the recognizer to store in its database for that user. The recognizer can provide the active training support, though usually this task is left to an application. Microsoft usability studies have shown that users do not object to the time invested in active training.

The following table lists the functions that a recognizer with training capabilities can export. Only TrainHREC is used by version 2.0 Pen API. The other functions are obsolete in version 2.0 and should be included in a recognizer only if it is expected to work with older applications that work with a version 1.0 recognizer (see the Microsoft Pen Windows version 1.0 documentation for descriptions of these functions).

Function	Description
TrainContextInternal	Passes a previous recognition result that may contain errors along with the required interpretation. The system calls this function in response to a call to TrainContext. This function applies only to training recognizers compatible with version 1.0 of the Pen API. It is superseded by the TrainHREC function.
TrainHREC	Passes ink data and its required interpretation to the recognizer. The recognizer then stores the data and interpretation for future reference.
TrainInkInternal	Passes a previous erroneous recognition result along with the correct interpretation. The system calls this function when the application calls TrainInk. TrainInkInternal is rendered obsolete by TrainHREC and is only for training recognizers compatible with version 1.0 of the Pen API.


 Interpreting Input

Typically, a recognizer converts pen input to recognized data in three steps:

1.	Collect and process the raw pen input data.

2.	Segment the written symbols.

3.	Note the order and direction of pen strokes.


 Processing Raw Data

Raw data for recognition consists of pen coordinates. At a minimum, the recognizer must collect coordinate data while the pen is in contact with the tablet. Optionally, the recognizer can also process additional pen data such as pen pressure, the height of the pen tip above the pad, the angle of the pen, and the rotation of the pen. Not all pen devices can provide such information.

The Microsoft Handwriting Recognizer (GRECO.DLL) processes only coordinate data. The Pen API provides the OEMPENINFO structure for other types of pen data. For details, see the entry for OEMPENINFO in Chapter 11, "Pen Application Programming Interface Structures."

Noise Reduction and Normalization

To improve recognition, a recognizer can optionally employ noise reduction and normalization techniques. Noise reduction filters the input to weed out erroneous input—for example, pen skips, inadvertent marks from the user, or spurious noise from the input device.

Normalization corrects the natural skewing of handwritten text. In the same way that lines of text tend to run askew on blank paper, lines of pen input are usually not parallel to the top and bottom of the tablet. (An application can provide guidelines to help correct this tendency.)

Coordinates should be normalized relative to a horizontal line, called the baseline, that marks the bottom of the text. The baseline is analogous to a single line on lined notebook paper. Letter descenders, such as the lower parts of "y" or "j," descend below the baseline.

If a guide is present, its vertical coordinate defines the baseline. The baseline of a single-line guide in absolute coordinates is the sum of the yOrigin and cyBase members of the GUIDE structure. For more information, see the reference description of the GUIDE structure.

Allowed Time

The recognizer must return within the period of time specified by the dwTimeMax parameter of the ProcessHRC function. This parameter can have the values PH_MIN, PH_DEFAULT, or PH_MAX. Respectively, these values limit the time allowed for processing to approximately 50 milliseconds, 200 milliseconds, or as much time as required.

For values other than PH_MAX, the recognizer must ensure that it does not exceed the allotted time. The recognizer can either regularly poll with the GetTickCount function to mark the passage of time or, through the SetTimer function, provide a callback function that sets a time-out flag. The SREC sample recognizer described at the end of this chapter demonstrates the latter technique.

Allowed Number of Guesses

The recognizer must return no more than the maximum number of guesses specified by the SetMaxResultsHRC function. For a description of this function, see the "Number of Recognition Guesses" section in Chapter 5. By default, the recognizer returns only its best guess with no alternative guesses.


 Segmentation of Symbols

A recognizer can view symbols at any granularity. For instance, most handwriting recognizers see individual letters and numerals as symbols. A recognizer for cursive writing, on the other hand, may see a complete word as a single symbol without distinguishing each letter of the word.

No matter how it views symbols, a recognizer must separate them within a stream of written symbols, a process called segmentation. The task of segmenting letters is greatly facilitated if the application provides box guides. In this case, the recognizer can assume that strokes lying within a box constitute a single character. The problem of accurate segmentation becomes more difficult for unguided text.

Segmentation is a crucial issue for recognizing different handwriting styles. The following table lists the forms of input in decreasing order of constraint on the user. The information in the table is taken from IBM Research Report RC 11175, No. 50249, (May 21, 1985), An Adaptive System for Handwriting Recognition, by C. C. Tappert.

Input form	Definition
Boxed input	Each character appears within its own box.
Discrete spaced	A set of strokes in a given space belong to the same character. (This is also called external segmentation.)
Discrete run on	Printed characters can overlap.
Cursive	Letters are connected by ligatures. The recognizer must either identify discrete letters or interpret a whole word at a time.
Mixed	The recognizer can segment discrete, run-on, and cursive writing.
Figure 8.1 illustrates these various styles.

The Pen API places few restrictions on the recognizer. At a minimum, however, a default recognizer must be able to recognize discrete characters because many applications do not use boxed input.


 Stroke Order and Direction

Noting the order and placement of strokes can help a recognizer handle the following cases:

•	Delayed strokes. A delayed stroke occurs after other strokes, but belongs to an earlier, unfinished character. For example, in writing the word "two," the user might cross the "t" only after writing the rest of the word.

•	Correction strokes. A correction stroke alters the interpretation of other strokes — for example, placing a small stroke on the top of a "y" to change it to a "g." Correction strokes are often delayed.

•	Characters written out of order. For example, the user should be able to first write "t  o," then fill in a "w" between the letters. The recognizer should recognize the completed word as "two" instead of "tow."

•	Variations in stroke order or direction. Different users often write the multiple strokes of characters in a different order and direction. To take an extreme example, the four strokes forming a capital "E" can be written in 2 (4) *4! = 384 distinct ways.


 Returning Results

To return results, the recognizer must conform to the procedures described in the section "Getting Results" in Chapter 5. That section examines the case where the words "clear," "dear," "clean," "dean," and "deer" represent valid interpretations of a handwritten word. In such a case, the recognizer should return the possibilities arranged in order of decreasing likelihood.

Without an internal concept of likelihood, the recognizer must impose an arbitrary order. However, for multiple recognizers to cooperate, a recognizer must have some concept of a poor match and be able to return "unknown" in lieu of a guess. While the pen API does not strictly require a recognizer to assign confidence levels to its guesses, without confidence values a recognizer cannot work efficiently with other recognizers.

The recognizer must be able to associate individual strokes with a recognized symbol. Applications can use the stroke data to correctly juxtapose the recognized text with the ink on the screen, redraw the data, or send information to other recognizers.

Speed and timing are very important in the recognition process. A recognizer should recognize input at least at the speed of normal handwriting, approximately two to three characters per second.


 Results Messages

Results messages concerning recognition come from the system, not the recognizer. The messages depend on what services the application uses:

•	If DoDefaultPenInput runs the recognition process, it sends a chain of messages to the application as described in Chapter 2, "Starting Out with System Defaults."

•	If the application calls one of the version 1.0 recognizer functions, such as Recognize or ProcessWriting, the system generates a WM_RCRESULT message. The system can send many WM_RCRESULT messages during a single recognition event, depending on the frequency that the application has specified for receiving data. The lParam of each message points to a new, self-contained RCRESULT structure that contains the recognition results generated since the last WM_RCRESULT message.


 The RCRESULT Structure

A recognizer can store its results in any format the developer wishes. It need not create an RCRESULT structure except in response to calls to certain superseded functions such as Recognize and RecognizeData. For completeness, this section describes the RCRESULT structure, which the developer may wish to use as a model for storage. Although a recognizer must calculate the information found in an RCRESULT structure, it need not organize the information in the same format.

Note  The RCRESULT structure is not required in version 2.0 of the Pen API and is supported only to maintain compatibility with older applications that use version 1.0 recognizer API.

The first member of the RCRESULT structure is a list called the symbol graph, which contains all the recognizer's guesses. An application can read the guesses in order of likelihood by walking through the symbol graph.

The Symbol Graph

The best way to understand the symbol graph is to first diagram its contents before describing how to actually read it. The following discussion again takes up the example in the section "Getting Results" in Chapter 5, in which the recognizer generated the five guesses "clear," "dear," "clean," "dean," and "deer." A diagram of the symbol graph that represents all these possibilities might look like this:

Letter:     {  cl   |   d  }    e    {  a   |   e  }    {  r   |   n  }

Confidence:    80%     60%    100%     85%     20%        80%     50%

Average:    clear   86%

            dear    81%

            clean   79%

            dean    74%

            deer    58%

If you study the diagram a moment, you will see its logic. Alternative letters appear separated by a C bitwise-OR symbol, with the most likely alternative first. All the guesses in this example, however, agree that the second (or third) character is the letter "e," so it has no alternatives. Taking the first letter in each alternative set produces the most likely of the guesses — in this case, the word "clear."

The symbol graph includes confidence values for each character or character set (as in the case of the interpretation "cl"). The recognizer can determine a confidence value for an entire word by averaging the values for each character or character set, as shown in the diagram above. (Note that this hypothesis is purely for purposes of discussion. The pen API does not mandate how a recognizer determines its confidence levels. The influence of word lists and other factors may also change confidence levels.)

Symbol graphs must, therefore, contain three types of information:

•	All characters (or character sets) determined as likely interpretations for a set of pen strokes

•	A map identifying the pen strokes that correspond to each interpretation

•	A confidence level for each interpretation

As described in Chapter 11, "Pen Application Programming Interface Structures," the symbol graph is a structure of type SYG. The SYG structure contains two additional data structures that provide the needed information: symbol correspondence and symbol element structures.

A symbol correspondence structure SYC delineates a specific subset of the strokes entered by the user. Each SYC contains the first and last strokes of a subset; these strokes and the strokes between them define the subset of pen data associated with the SYC. The symbol graph contains an array of SYC structures, each of which corresponds to a different part of the ink input. Taken together, the SYC structures define all the ink gathered during the input session.

A SYG structure also contains an array of symbol element SYE structures. An SYE contains a symbol value, a confidence level, and an index into the array of SYC structures. Each character or character set in the recognized input has its own symbol element.

The Best Guess

The RCRESULT structure also provides information about the recognizer's "best guess." The best guess is simply the first interpretation in the symbol graph, which lists interpretations in descending order of probability. Since an application is often interested only in the most likely interpretation, the recognizer should place in the RCRESULT the following three members specifically to identify the best guess:

•	The lpsyv member points to a null-terminated symbol string containing the best guess.

•	The cSyv member contains the number of symbols in the best guess string.

•	The hSyv member is the handle to the memory block to which lpsyv points.

Location and Position of the Input

The RCRESULT structure also contains information regarding the location and position of the ink entered by the user.

•	The nBaseLine member is the recognizer's estimate of the baseline of the ink entered by the user. (For a definition of baseline, see "Noise Reduction and Normalization" earlier in this chapter.) If the baseline is not known, the recognizer sets this value to 0. The Microsoft Handwriting Recognizer (GRECO.DLL) sets nBaseLine to 0.

•	The nMidLine member is the recognizer's estimate of the midline of the ink entered by the user. If the midline is not known, the recognizer sets this value to 0. The Microsoft Handwriting Recognizer sets nMidLine to 0.

•	The rectBoundInk member is a Windows RECT structure. It holds the bounding rectangle that circumscribes the area of the screen on which the user has written. Typically, an application uses rectBoundInk to invalidate the screen area to update the display in the appropriate location. This occurs, for example, when Windows replaces ink on the screen with recognized text.

Contextual Information

Two elements of the RCRESULT structure provide information about the recognition event, but not as a part of the results of recognition. They are lprc, a far pointer to the RC structure passed to the Recognize function, and wResultsType, a flag that describes how the recognition event proceeded. The wResultsType flag contains a combination of RCRT_ constants, described in Chapter 13, "Pen Application Programming Interface Constants."

The Ink

The final two members of the RCRESULT structure contain information about the ink entered by the user.

•	The pntEnd member contains the last point of the ink data from the user only if PCM_RECTBOUND or PCM_RECTEXCLUDE have been specified. An application sets these flags either in the lPcm member of the RC structure or the dwPcm member of the PCMINFO structure.

•	The hpendata member is a handle to a pen data memory block that contains all of the ink information entered by the user.


 Hot Spots

While recognizing a symbol, the recognizer may also identify critical points on the symbol called hot spots. Hot spots can apply to any symbol but usually are of interest only for gestures. For example, if the user writes an X for deletion, the cross of the X — its hot spot — points to the item to be deleted. If the recognizer identifies hot spots for a recognized symbol, it places coordinates for all hot spot points in the rgpntHotSpot member of the symbol's SYG structure. This array can hold up to MAXHOTSPOT points. Note that all symbols do not have the same number of hot spots, and many symbols have none.


 Writing a Recognizer

A recognizer must reflect the developer's requirements, design, and programming style. Although it cannot prescribe any one method for creating a recognizer, this section offers guidance on writing several important recognition functions. The section also presents a sample recognizer called SREC to illustrate some of the information in this chapter.

For a description of how an application uses the InstallRecognizer function to load a recognizer function, see "Creating the HRC" in Chapter 5. The reference section for InstallRecognizer in Chapter 10 also discusses how to load a recognizer by using the LoadLibrary function to aid in debugging the recognizer. To designate a recognizer as the system default recognizer, see "Registry Configuration" in Appendix A.


 Recognition Functions

The following sections provide fragmentary examples of the recognition functions AddPenInputHRC, CreateCompatibleHRC, CreateInksetHRCRESULT, CreatePenDataHRC, and DestroyHRC.

For purposes of discussion, the examples assume the recognizer's HRC takes the form of a private structure called HRCinternal. This structure contains a handle to an HPENDATA block, which stores the stroke information and pen data points for an input session. (For a description of HPENDATA, see "The HPENDATA Object" in Chapter 4.) The HRC applies only to a single session — say, a word written by the user. The client application must create a new HRC to recognize the next word.

The following typedef statement defines the hypothetical HRC object used by the example code fragments in this section:

typedef struct

{

DWORD       reserved;           // Reserve first DWORD for system

HGLOBAL     hglobal;            // Handle from GlobalAlloc

HPENDATA    hpendata;           // HPENDATA handle for input

int         wPdk;               // Current stroke is pen-up or down

                                    // Other information for the HRC

.

.

} HRCinternal, FAR *LPHRCinternal;

Notice that the structure reserves the first DWORD for system use. This is required for all recognizer objects. The structure also groups pertinent variables within the object itself instead of allocating them as global data. This ensures that the object remains private to the client that creates it.

In the code that follows, all internal functions have an "N" prefix. This helps distinguish them from standard API functions.


 CreateCompatibleHRC

The CreateCompatibleHRC function allocates memory for the HRC object. The example below calls the Windows function GlobalAlloc and uses the returned memory handle as the HRC. Locking the allocated memory with GlobalLock provides a far pointer to the allocated HRCinternal structure.

When an input session begins, the pen state is always down. Therefore, the function initializes the wPdk member to PDK_DOWN.

HRC WINAPI	CreateCompatibleHRC( HRC hrcTemplate, HREC hrec )

{

HGLOBAL         hglobal;        // Handle of allocated HRC object

LPHRCinternal   lphrc;          // Far pointer to object

.

.

.

// Allocate memory for HRC and get far pointer to it

hglobal = GlobalAlloc( GHND, sizeof( HRCinternal ) );

lphrc   = (LPHRCinternal) GlobalLock( hglobal );

// If failure, return NULL

if (!lphrc)

return NULL;

// Save HRC memory handle, because DestroyHRC will need it

lphrc->hglobal = hglobal;

// If template provided, copy its information to the new HRC

if (hrcTemplate)

NCopyTemplateInfo( hrcTemplate, lphrc );

// Initialize other information

lphrc->hpendata = CreatePenData( NULL, 0, PDTS_HIENGLISH, 0 );

lphrc->wPdk     = PDK_DOWN;

.

.

.

// If no errors, return pointer as HRC handle

return ((HRC) lphrc);

}


 DestroyHRC

Generally, the life of an HRC object is brief. An application destroys the HRC after obtaining results from the recognizer and creates a new HRC at the start of the next input session.

In the model described above, CreateCompatibleHRC calls GlobalAlloc to allocate system memory in which the HRC object resides. The function returns a pointer to the fixed allocation as an HRC handle.

DestroyHRC reverses the action, using the original HGLOBAL handle to free the allocated memory. When DestroyHRC successfully returns, the HRC handle is no longer valid. The application should set the handle to NULL to prevent accidental reuse, as described in "Destroying the HRC" in Chapter 5.

int WINAPI	DestroyHRC( HRC hrc )

{

    LPHRCinternal  lphrc = (LPHRCinternal) hrc;  // Pointer to HRC

if (!GlobalUnlock( lphrc->hglobal ))

return HRCR_OK;

else

return HRCR_ERROR;

}


 AddPenInputHRC

As the pen moves, an application continually gets data from the pen driver by calling GetPenInput. It then passes the retrieved information to the recognizer via AddPenInputHRC. This function may be called many times before the user completes the stroke. Each time, AddPenInputHRC receives a small subset of points that collectively form a pen stroke.

Along with the subset of points, AddPenInputHRC receives a STROKEINFO structure that represents the points in the subset. For example, the member dwTick contains the starting time for each subset, not the entire stroke. (The starting time of the first subset of a stroke is also the starting time of the entire stroke.) Similarly, cPnt contains the point count only for the current subset.

The following example lets the system take care of accumulating the points. It calls the AddPointsPenData API function to add the subset of points to the HPENDATA block belonging to the HRC. The code also demonstrates how a recognizer can determine when one stroke ends and another begins. This allows the recognizer to take some intermediate steps to facilitate recognition at the end of each stroke. Such intermediate work can remove some of the burden from ProcessHRC, improving response time and perhaps accuracy as well.

int WINAPI	AddPenInputHRC( HRC hrc, LPPOINT lppnt, LPVOID lpvOem,

                            UINT oemdatatype, LPSTROKEINFO lpsi )

{

    LPHRCinternal   lphrc = (LPHRCinternal) hrc; // Pointer to HRC

    int             iRet  = HRCR_OK;             // Return code

.

.

.

//

// If state change from down to up (or vice versa), the previous

// stroke has ended and the point data that lppnt points to belongs

// to a new stroke.  Take any intermediate action to process the

// just-completed stroke.

//

if (lpsi->wPdk != lphrc->wPdk)

{

.

.	// Take intermediate action

.

lphrc->wPdk = lpsi->wPdk	// Note new pen state

}

// Accumulate stroke points in internal HPENDATA object

if (!AddPointsPenData( lphrc->hpendata,	// HPENDATA handle

   lppnt,	// Point subset

   lpvOem,	// OEM data

   lpsi ))	// Subset STROKEINFO

iRet = HRCR_ERROR;

.

.

.

// Return appropriate error code (HRCR_OK or HRCR_ERROR)

return (iRet);

}


 CreatePenDataHRC

The CreatePenDataHRC function returns a handle to an HPENDATA object that contains the raw data used for recognition. In the example code above, AddPenInputHRC has already done the work of storing the pen data into an internal HPENDATA. Thus, the hypothetical CreatePenDataHRC function outlined below simply duplicates the internal object.

HPENDATA WINAPI    CreatePenDataHRC( HRC hrc )

{

    LPHRCinternal  lphrc = (LPHRCinternal) hrc;  // Pointer to HRC

// Clone the internal HPENDATA and return its handle

return (DuplicatePenData( lphrc->hpendata, 0 ));

}


 CreateInksetHRCRESULT

The optional CreateInksetHRCRESULT function creates a corresponding inkset from the data in an HPENDATA object. For a description of inksets and the INTERVAL structure, see "The HINKSET Object" in Chapter 4.

A description of the CreateInksetHRCRESULT function first requires a brief discussion of stroke start and end times. Some of this information also appears in the section "Timing Information" in Chapter 4, but it is presented here from the point of view of the recognizer rather than the application.

A stroke's start time is the starting tick count of the first group of points that AddPenInputHRC receives when a new stroke begins. The member dwTick of the STROKEINFO structure is the number of milliseconds that have elapsed since the system tick reference determined at system startup time. A recognizer can retrieve this value in an ABSTIME structure through a call to the Pen API function GetPenMiscInfo:

    ABSTIME  atTickRef;

    GetPenMiscInfo( PMI_TICKREF, (LPARAM)((LPABSTIME) &atTickRef) );

The STROKEINFO structure also contains in its cPnt member the number of points in the collection. Because the pen device sends points at a constant rate (called the sampling rate), the number of points in the collection implies how much time has elapsed between the first and last points.

The sampling rate does not change, so the recognizer need only determine the rate during initialization and store the value. The following example shows how a recognizer can get the sampling rate from the pen driver:

PENINFO     pinfo;

HDRVR       hPenDrv;

int         vnSamplingRate;

.

.

.

hPenDrv = OpenDriver( "pen", 0, 0 );

if (hPenDrv)

{

if (SendDriverMessage( hPenDrv, DRV_GetPenInfo, (LPARAM)&pinfo, 0 ))

vnSamplingRate = pinfo.nSamplingRate;

CloseDriver( hDriverPen, 0, 0 );

}

With this information, CreateInksetHRCRESULT can fill an INTERVAL structure with a stroke's start and stop times as shown below. The code assumes the HRCRESULT object contains the HRC handle. This allows the internal function NGetStrokeFromHPENDATA to locate the internal HPENDATA object with the raw input data.

HINKSET WINAPI CreateInksetHRCRESULT( HRCRESULT hrcresult,

  UINT isyv, UINT csyv)

{

HINKSET     hinkset;

INTERVAL    interval;

STROKEINFO  si;

DWORD       dwMsec;

UINT        i, j;

// Call Pen API to create hinkset object

hinkset = CreateInkset( GMEM_MOVEABLE | GMEM_DDESHARE );

// Initialize INTERVAL with tick reference (described above)

GetPenMiscInfo( PMI_TICKREF,

                    (LPARAM)((LPABSTIME) &interval.atBegin) );

// For each SYV in the HRCRESULT between the given indices ...

for (i = 0; i < csyv; i++, isyv++ )

{

j = 0;

// For each stroke in the SYV ...

while ( NGetStrokeFromHPENDATA( hrcresult, &si, isyv, j++ ))

{

//

// Calculate the interval for the stroke.

// Note si.dwTick is the number of milliseconds

// that have elapsed since system start-up.

//

dwMsec = (DWORD)(1000L*interval.atBegin.sec +

    interval.atBegin.ms + si.dwTick);

interval.atBegin.sec = dwMsec/1000L;

interval.atBegin.ms  = (UINT)(dwMsec % 1000L);

dwMsec = (DWORD)(1000L*interval.atBegin.sec +

     interval.atBegin.ms +

     1000L*si.cPnt/vnSamplingRate);

interval.atEnd.sec = dwMsec/1000L;

interval.atEnd.ms  = (UINT)(dwMsec % 1000L);

// Call Pen API function to add interval to inkset

AddInksetInterval( hinkset, (LPINTERVAL) &interval );

}

}

return (hinkset);

}


 A Sample Recognizer

This section describes a simple recognizer called SREC that demonstrates some of the information given in this chapter. The text describes the most interesting parts of the program and illustrates with code fragments. The complete source listing for SREC.C resides in the SAMPLES\PEN\SREC subdirectory.

SREC is used by the PENAPP application described in Chapter 7, "A Sample Pen Application." To see how SREC works, you must create both PENAPP.EXE and SREC.DLL using the supplied MAKE files, then run PENAPP.

When using the SREC recognizer, PENAPP specifies that a stroke ends when the pen leaves the tablet. Therefore, SREC recognizes only one stroke at a time. SREC takes the beginning and ending points of the stroke and calculates the nearest compass direction of the line formed by these endpoints.

For its HRC object, SREC creates a structure that contains an HPENDATA handle to the input data, the module handle returned from InstallRecognizer, and recognition results. The following typedef statements define the HRC and HRCRESULT objects for SREC. Notice that SREC keeps its HRCRESULT within the HRC.

typedef struct                      // HRCRESULT object

{

DWORD   reserved;               // Reserve top DWORD

SYG     syg;                    // Recognition results

} HRCRESULTinternal, FAR *LPHRCRESULTinternal;

typedef struct                      // HRC object

{

DWORD               reserved;   // Reserve top DWORD

HPENDATA            hpendata;   // Raw pen data to be recognized

HREC                hrec;       // Module handle for SREC

HRCRESULTinternal   hrcresult;  // HRCRESULT structure

} HRCinternal, FAR *LPHRCinternal;

When it finishes recognizing a stroke, SREC fills out a SYG symbol graph structure. The structure holds one of the symbol values listed here:

Symbol value	Direction
syvEast	Right
syvSouth	Down
syvWest	Left
syvNorth	Up
syvDot	Single tap
The following sections describe the functions that SREC exports. These functions appear under the same categories described earlier in this chapter, in the section "List of Exported Functions." This allows for quick cross-referencing between a general description of a function and its actual implementation in SREC.

Although defined by the Pen API, the function names below appear in monospace font rather than bold because the names refer to routines in the SREC.C source file.


 SREC Initialization Functions

As a Windows dynamic-link library, SREC exports LibMain and WEP. As a recognizer, it also exports the required initialization function ConfigRecognizer. All recognizers compatible with version 2.0 of the Pen API must provide these functions.

LibMain and WEP

The first two functions in the SREC recognizer are the standard Windows functions required in any dynamic-link library, LibMain and WEP. LibMain, the main DLL function, is analogous to WinMain. It performs any needed initialization and unlocks the data segment of the library. WEP is the standard DLL termination function, which receives control when Windows unloads the DLL. For a description of WEP, see the references listed at the beginning of this chapter.

ConfigRecognizer

The ConfigRecognizer function handles the recognizer's initialization tasks and configures it for special options. When it loads a recognizer, InstallRecognizer internally calls the recognizer's ConfigRecognizer function with the subcommand WCR_INITRECOGNIZER. In response to this call, the recognizer should perform any required initialization tasks.

As its name suggests, ConfigRecognizer handles more than initialization work. It also provides the means for setting recognizer options and to query for capabilities. With version 2.0 of the Pen API, which can load multiple recognizers, applications do not call ConfigRecognizer, because the function provides no way to identify the intended library. Instead, applications call the ConfigHREC function, which takes

the same arguments as ConfigRecognizer, with the addition of the HREC handle returned from InstallRecognizer. Internally, the system identifies the intended recognizer from the handle and passes the arguments to ConfigRecognizer in the appropriate recognizer. Thus, ConfigHREC and ConfigRecognizer refer to the same function. ConfigRecognizer is unique in that it is the only function exported by a recognizer that applications do not call directly.

As the following code fragment shows, SREC returns only its identification string and version number from ConfigRecognizer. Note also that SREC does not allow itself to be set as the system recognizer. Since SREC does not support standard editing gestures or recognize characters, it cannot serve as a system default recognizer.

int WINAPI   ConfigRecognizer( UINT uSubFunc,

                               WPARAM wParam, LPARAM lParam )

{

int	iRet = TRUE;

switch ( uSubFunc )

{

.

.

.

case WCR_INITRECOGNIZER:	// No initialization or

case WCR_CLOSERECOGNIZER:	//   clean up duties to

break;	//   perform

case WCR_RECOGNAME:

lstrncpy( (LPSTR)lParam, szID, wParam );

break;

case WCR_DEFAULT:	// Can't be system default

case WCR_QUERY:	// Does not support config dialog

case WCR_QUERYLANGUAGE:	// Does not support any language

iRet = FALSE;

break;

case WCR_PWVERSION:

case WCR_VERSION:

iRet = 0x0002;	// Recognizer version 2.0

break;

default:

iRet = FALSE;	// Anything else is unsupported

break;

}

return iRet;

}

For a complete list of WCR_ subfunctions, refer to the reference section for ConfigRecognizer in Chapter 10.

When the last client application unloads a recognizer, the UninstallRecognizer function calls the recognizer's ConfigRecognizer function with the command WCR_CLOSERECOGNIZER. This informs the recognizer that it is being unloaded. The previous code takes no action for WCR_CLOSERECOGNIZER because in SREC, memory allocations come from the local heap. As with any Windows-based program, a DLL's heap resides in its data segment. When Windows unloads a DLL, it automatically returns the entire data segment to the memory pool.

However, unloading SREC does not destroy its internal HPENDATA object. HPENDATA blocks occupy global heap space. If the client application terminates or unloads SREC without first destroying all HRC objects created by SREC, the corresponding HPENDATA blocks are left orphaned in memory. A recognizer more intelligent than SREC should maintain a count of active HPENDATA allocations and free any that remain before terminating.

A recognizer's WEP routine also receives control when Windows unloads the recognizer. Developers should note a subtle difference between handling cleanup chores in ConfigRecognizer and in WEP. When the former executes in response to the WCR_CLOSERECOGNIZER subfunction, the client is still active. However, the WEP routine cannot safely make the same assumption when it executes. ConfigRecognizer can therefore conceivably post a message to the client or perform some other action that relies on an active recipient.

The disadvantage of ConfigRecognizer is that the recognizer cannot be certain the function will execute because the client might not call UninstallRecognizer. Since the WEP function is guaranteed to execute when Windows unloads the recognizer, essential cleanup duties, such as unhooking interrupts, should be handled in WEP.


 SREC Recognition Functions

This section takes a brief look at some of SREC's exported recognition functions, including CreateCompatibleHRC, ProcessHRC, and CreatePenDataHRC. The code uses the macro

#define  lpHRC    ((LPHRCinternal) hrc)

to represent a far pointer to the HRC object.

CreateCompatibleHRC

The CreateCompatibleHRC function allocates an HRCinternal structure in the local heap, creates an HPENDATA block for the pen data, and returns a far pointer to the structure. The LPTR argument forces LocalAlloc to return a far pointer to the allocation instead of a memory handle. This far pointer serves as SREC's HRC handle.

Since the HRC has no configurable elements, SREC ignores any template HRC provided in the first parameter.

HRC WINAPI 	CreateCompatibleHRC( HRC hrcTemplate, HREC hrec )

{

HRC	hrc;

hrc = (HRC) LocalAlloc( LPTR, sizeof( HRCinternal ) );

if (hrc)

{

lpHRC->hrec     = hrec;

lpHRC->hpendata = CreatePenData( NULL, 0, PDTS_HIENGLISH, 0 );

if (lpHRC->hpendata)

return (hrc);

}

LocalFree( (HLOCAL) hrc );	// If error, free allocation

return NULL;	//   and return NULL

}

ProcessHRC

The most interesting feature of SREC's ProcessHRC function is the way it sets a time limit for processing. If called with a limit of PH_MIN or PH_DEFAULT, ProcessHRC passes the address of a callback function to SetTimer. When the specified time-out period elapses, the callback function receives control and sets a global flag called vfOutOfTime.

A recognizer can use this technique to ensure that it does not overrun a specified time limit. Its internal processing functions should check the vfOutOfTime flag regularly and, if it is set, terminate immediately. In this case, ProcessHRC returns a value of HRCR_INCOMPLETE to tell the caller recognition has not yet finished.

int WINAPI      ProcessHRC( HRC hrc, DWORD dwTimeMax )

{

    UINT        idTimer, uTime;

    int         iRet;

vfOutOfTime = FALSE;	// Initialize time-out flag

if (dwTimeMax != PH_MAX)	// If time limit specified ...

{

uTime   = (dwTimeMax == PH_MIN) ? 50 : 200;

idTimer = SetTimer( NULL, NULL, uTime, (TIMERPROC) TimerProc );

iRet    = GetSYG( hrc );	// Quit if out of time

KillTimer( NULL, idTimer );

}

else

iRet = GetSYG( hrc );	// Don't quit until finished

return (iRet);

}

VOID CALLBACK	TimerProc( HWND hwnd, UINT ms, UINT iId, DWORD dwTm )

{

vfOutOfTime = TRUE;

}

CreatePenDataHRC

SREC keeps an HPENDATA handle in its HRC structure. Because the AddPenInputHRC function has already stored pen input in the internal HPENDATA block, CreatePenDataHRC simply duplicates the block.

HPENDATA WINAPI	CreatePenDataHRC( HRC hrc )

{

if (hrc)

return (DuplicatePenData( lpHRC->hpendata, 0 ));

else

return NULL;

}


 Summary of the Pen Application Programming Interface

This chapter summarizes the pen services by listing them according to category. The lists complement the detailed descriptions of functions, structures, messages, and constants in the reference chapters that follow this chapter. The lists let you quickly identify those services that pertain to your application, then refer to the reference chapters for detailed information.

The "Pen Kernel Functions" section is of interest to developers who want to write applications for Microsoft Windows 95 that use ink data without the presence of pen hardware.


 Pen API Functions

The Pen Application Programming Interface (API) provides functions that can be divided into 10 broad categories. The following table describes the 10 categories. Other tables list the functions within each category.

Function category	Description
System and hardware	Provide information about pen hardware and current system assumptions.
Display	Display ink data, get screen information.
Pen data	Collect, copy, move, and delete data in an HPENDATA object.
Recognition	Recognize handwritten characters.
Symbol manipulation	Collect and convert symbols returned from a recognizer.
Time intervals	Manipulate time intervals associated with pen strokes.
Compression	Reduce the size of an HPENDATA object.
Utility	Miscellaneous utility services provided by the system.
Hook	Program hooks to monitor inking or recognition.
Obsolete	Obsolete functions of version 1.0 maintained by version 2.0 only for compatibility reasons.


 List of Pen API Functions

The following tables list by category all functions in version 2.0 of the Pen API. Functions appear in alphabetical order within each category, together with a brief description.

System and hardware functions	Description
GetPenAsyncState	Gets state of pen barrel button.
GetPenMiscInfo	Gets current system settings.
GetVersionPenWin	Gets the Pen API version number.
SetPenMiscInfo	Sets system defaults and assumptions.
UpdatePenInfo	Called by the pen driver to notify the system of a change in the driver configuration.
Display functions	Description
CreatePenDataRegion	Returns a screen region that contains the points of an HPENDATA object.
DrawPenDataEx	Enhanced version of DrawPenData.
DrawPenDataFmt	Default version of DrawPenDataEx.
RedisplayPenData	Displays collected pen data exactly as originally drawn.
ShowKeyboard	Displays or hides the on-screen keyboard.
StartInking	Begins the process of leaving a visible ink trail  as the pen moves. See the descriptions of StartPenInput and DoDefaultPenInput.
StopInking	Stops the inking process begun by a call to StartInking.
Pen data functions	Description
AddPenDataHRC	Adds an HPENDATA object to an HRC.
AddPointsPenData	Adds new points and original equipment manufacturer (OEM) data to an existing HPENDATA object.
CreatePenData	Allocates memory for a new HPENDATA object and initializes its header.
CreatePenDataEx	Enhanced version of CreatePenData.
CreatePenDataHRC	Returns handle to HPENDATA object associated with an HRC.
DestroyPenData	Frees memory occupied by an HPENDATA memory block.
DuplicatePenData	Clones an existing HPENDATA object.
ExtractPenDataPoints	Copies or removes points from a stroke.
ExtractPenDataStrokes	Copies or removes selected strokes, optionally creating a new HPENDATA object from the copied strokes.
GetPenDataAttributes	Retrieves information about an HPENDATA object.
GetPenDataInfo	Gets status information for an HPENDATA object.
GetPointsFromPenData	Returns an array of points from an HPENDATA object.
GetStrokeAttributes	Retrieves information about a stroke.
GetStrokeTableAttributes	Retrieves information about a stroke's class.  The class is an entry in a table stored in the PENDATAHEADER structure.
InsertPenData	Combines two HPENDATA blocks.
InsertPenDataPoints	Inserts points into a stroke in an HPENDATA object.
InsertPenDataStroke	Inserts data for a new stroke into an existing HPENDATA object.
OffsetPenData	Offsets pen data points by a specified amount.
PenDataFromBuffer	Reverse of PenDataToBuffer, which must be called first. Creates an HPENDATA block and writes the buffer back into it.
PenDataToBuffer	Serializes the contents of an HPENDATA block to a buffer.
RemovePenDataStrokes	Removes specified strokes from an HPENDATA object.
ResizePenData	Scales ink data to fit a specified rectangle.
SetStrokeAttributes	Sets attributes of a stroke. Reverse of GetStrokeAttributes.
SetStrokeTableAttributes	Sets attributes for a stroke's class. Reverse of GetStrokeTableAttributes.
Recognition functions	Description
AddPenInputHRC	Adds raw pen input to an HRC object.
AddWordsHWL	Adds words to a word list.
ConfigRecognizer	System access to recognizer configuration. Applications should not call this function.
CreateCompatibleHRC	Creates an empty HRC object.
CreateHWL	Creates a word list.
DestroyHRC	Destroys a recognizer's recognition context object.
DestroyHRCRESULT	Destroys a recognizer's results object.
DestroyHWL	Destroys the word list handle created by CreateHWL and frees its memory.
EnableGestureSetHRC	Enables or disables recognition of specified gestures.
EnableSystemDictionaryHRC	Specifies whether a recognizer should use its dictionary.
EndPenInputHRC	Informs a recognizer that the input session has ended.
GetAlphabetHRC	Retrieves the current alphabet from a recognizer.
GetAlphabetPriorityHRC	Retrieves the current alphabet priority from a recognizer.
GetAlternateWordsHRCRESULT	Gets alternative guesses made by a recognizer.
GetBoxMappingHRCRESULT	Retrieves from a recognizer the locations of a range of symbols in boxes.
GetBoxResultsHRC	Gets recognition results for a range of boxes.
GetGuideHRC	Gets a copy of the GUIDE structure (if any) in an HRC object.
GetHotspotsHRCRESULT	Returns the hot spots for a specified gesture.
GetHRECFromHRC	Gets module handle of recognizer from an HRC.
GetMaxResultsHRC	Gets the maximum number of guesses a recognizer can make.
GetResultsHRC	Retrieves an HRCRESULT object from recognizer containing recognition results.
GetWordlistCoercionHRC	Gets the current degree of influence a word list or dictionary has on recognition confidence levels.
GetWordlistHRC	Gets a word list from an HRC object.
InstallRecognizer	Loads a specified recognizer.
ProcessHRC	Tells recognizer to process input for a given period of time.
ReadHWL	Reads a word list from a file.
SetAlphabetHRC	Specifies the alphabet for a recognition session.
SetAlphabetPriorityHRC	Specifies alphabet priority for a session.
SetBoxAlphabetHRC	Specifies the alphabet for a range of boxes.
SetGuideHRC	Specifies guides for an HRC.
SetMaxResultsHRC	Sets the maximum number of guesses a recognizer can make.
SetWordlistCoercionHRC	Sets the degree of influence a word list or dictionary has on recognition confidence levels.
SetWordlistHRC	Identifies a word list for an HRC object.
TrainHREC	Passes ink and correct interpretations to recognizer for training.
UninstallRecognizer	Unloads a specified recognizer.
WriteHWL	Writes a word list to a file.
Symbol manipulation functions	Description
CharacterToSymbol	Converts an ANSI string to an array of symbol values.
EnumSymbols	Enumerates symbol strings in a symbol graph.
FirstSymbolFromGraph	Returns the array of symbols that is the most likely interpretation of a specific symbol graph.
GetSymbolCount	Returns the number of symbol strings contained in the symbol graph.
GetSymbolCountHRCRESULT	Gets the number of symbol values in results.
GetSymbolMaxLength	Gets the length of the longest symbol string contained in the symbol graph.
GetSymbolsHRCRESULT	Gets symbol values of recognition results.
SymbolToCharacter	Converts an array of symbols to an ANSI string.
Time interval functions	Description
AddInksetInterval	Adds an INTERVAL structure to an existing HINKSET object.
CreateInkset	Creates an empty inkset into which intervals can be added with the AddInksetInterval function.
CreateInksetHRCRESULT	Retrieves the intervals for a specified series of symbols returned by the recognizer.
DestroyInkset	Frees memory occupied by an inkset and invalidates the HINKSET handle.
GetInksetInterval	Copies a series of intervals from an HINKSET object to an array of INTERVAL structures.
GetInksetIntervalCount	Returns the number of intervals in an HINKSET object.
Compression functions	Description
CompressPenData	Compresses and uncompresses data.
DPtoTP	Converts display coordinates to tablet coordinates.
MetricScalePenData	Converts pen data points to one of the supported metric modes.
TPtoDP	Converts tablet coordinates to display coordinates.
TrimPenData	Removes selected data from an HPENDATA block.
Utility functions	Description
AtomicVirtualEvent	Blocks out physical pen events while posting virtual events.
BoundingRectFromPoints	Returns the bounding rectangle of an array of points.
ConfigHREC	Configures or queries recognizer options.
CorrectWriting	Displays lens or Correct Text dialog box to allow user to correct text.
CorrectWritingEx	Sends text to the CorrectText dialog box to allow the user to edit text using the Japanese Data Input Window. (Japanese version only.)
DoDefaultPenInput	Runs high-level recognition/data collection. Internally calls StartPenInput, StartInking, StopPenInput, and StopInking.
GetPenAppFlags	Returns the task flags created by SetPenAppFlags.
GetPenInput	Collects input data as the user writes.
GetPenResource	Retrieves a copy of the pen services resource. (Japanese version only.)
HitTestPenData	Determines whether a given point lies near a stroke.
IsPenEvent	Determines whether a WM_LBUTTONDOWN message is generated by a mouse or pen device.
KKConvert	(Japanese version only.) Activates the Kana-to-Kanji converter.
PeekPenInput	Retrieves information about a pen packet in the pen input queue. This function is similar to GetPenInput, but does not remove the pen packet from the queue.
PostVirtualKeyEvent	Simulates a keystroke by sending a virtual key code to Windows.
PostVirtualMouseEvent	Simulates mouse activity by sending a virtual mouse event to Windows.
SetPenAppFlags	Sets pen flags for the application that are used globally by the pen services.
StartPenInput	Begins collecting into an internal buffer ink  data generated by the moving pen. See also  the descriptions of . DoDefaultPenInput and StartInking.
StopPenInput	Ends collection process begun by a call to StartPenInput.
TargetPoints	Determines the logical recipient of data among several targets.
Hook functions	Description
SetPenHook	Sets or removes a hook for capturing low-level pen events.
SetResultsHookHREC	Sets a hook for recognition results.
UnhookResultsHookHREC	Unhooks a hook set by SetResultsHookHREC.
Obsolete functions	Description
BeginEnumStrokes	Locks an HPENDATA memory block in global memory in preparation for reading.
CloseRecognizer	Called by the system when uninstalling a  recognizer. Subfunction has been superseded  by WCR_CLOSERECOGNIZER in ConfigRecognizer.
CompactPenData	Data compression function superseded by CompressPenData and TrimPenData.
DictionarySearch	Searches dictionary for a word or phrase.
DrawPenData	Displays ink according to a display context HDC. Superseded by DrawPenDataEx.
EmulatePen	Emulates a pen system.
EndEnumStrokes	Unlocks an HPENDATA memory block. Required after calling BeginEnumStrokes.
GetGlobalRC	Retrieves a copy of the current system RC structure.
GetPenDataStroke	Gets the raw data for a stroke stored in an HPENDATA memory block.
GetPenHwEventData	Retrieves a range of pen event data from the internal pen data buffer.
InitRC	Initializes recognition context for the recognizer. Only for compatibility with version 1.0.
InitRecognizer	Called by the system when it installs a recognizer. Superseded by WCR_INITRECOGNIZER subfunction in ConfigRecognizer.
IsPenAware	Checks application's capability to handle pen events. Superseded by GetPenAppFlags.
ProcessWriting	Runs high-level recognition services. Superseded by DoDefaultPenInput.
Recognize	Begins recognition for a version 1.0 recognizer.
RecognizeData	Delayed recognition for a version 1.0 recognizer.
RegisterPenApp	Identifies an application to the system as pen-aware. Superseded by SetPenAppFlags.
SetGlobalRC	Sets default settings for the specified recognition context. This function should be called only from the pen Control Panel program.
SetRecogHook	Installs and removes a recognition hook in version 1.0. Superseded by SetResultsHookHREC.
TrainContext	Passes to the recognizer a previous recognition result that may contain errors along with the required interpretation.
TrainContextInternal	Called by system when an application calls TrainContext.
TrainInk	Informs the recognizer at the DLL recognition level that the raw data input represents the symbol value results.
TrainInkInternal	Called by system when an application calls TrainInk.


 Pen Kernel Functions

As described in Chapter 1, the services of the Pen API are provided by the libraries PENWIN.DLL and PKPD.DLL. PENWIN.DLL is provided by original equipment manufacturers and exists only on systems with attached pen hardware. The ink management services of PKPD.DLL, however, are part of Windows 95. This allows an application to display and manipulate ink data with any installation of Windows 95, even one without pen hardware.

The following table lists the 41 Pen API functions exported by PKPD. If an application detects Windows 95 without PENWIN.DLL, it can still use these functions to display, examine, alter, and compress existing ink data.

AddInksetInterval

AddPointsPenData

BeginEnumStrokes

BoundingRectFromPoints

CompactPenData

CompressPenData

CreateInkset

CreatePenData

CreatePenDataEx

CreatePenDataRegion

DestroyInkset

DestroyPenData

DrawPenData

DrawPenDataEx

DrawPenDataFmt

DuplicatePenData

EndEnumStrokes

ExtractPenDataPoints

ExtractPenDataStrokes

GetInksetInterval

GetInksetIntervalCount

GetPenDataAttributes

GetPenDataInfo

GetPenDataStroke

GetPointsFromPenData

GetStrokeAttributes

GetStrokeTableAttributes

HitTestPenData

InsertPenData

InsertPenDataPoints

InsertPenDataStroke

MetricScalePenData

OffsetPenData

PenDataFromBuffer

PenDataToBuffer

RedisplayPenData

RemovePenDataStrokes

ResizePenData

SetStrokeAttributes

SetStrokeTableAttributes

TrimPenData


 Pen API Structures

The Pen API defines 31 structures in the following categories:

Structure category	Description
System and hardware	Information about the system and pen hardware.
Display	Structures that affect display.
Guides and controls	Structures that affect boxes, guides, and controls.
Recognition	Pertain to the process and results of recognition.
Pen data	Information about points and strokes.
Target	Pertain to target windows.
Time intervals	Stroke interval information.
The following tables list the structures of the Pen API by category. For structures new to version 2.0, the first member is cbSize, which contains the structure's size in bytes.

Important  Before using a version 2.0 structure, an application must initialize its cbSize mem-ber with the value sizeof( structname ), where structname represents the name of the structure. For example:

INKINGINFO        inkinginfo;

inkinginfo.cbSize = sizeof( INKINGINFO );

or

INKINGINFO        inkinginfo = {sizeof( INKINGINFO )};

System and hardware structures	Description
CALBSTRUCT	Pen calibration information.
OEMPENINFO	Tablet hardware information provided by original equipment manufacturer.
PDEVENT	Provides information about the pen device associated with an IN_PDEVENT notification.
PENINFO	Pen or tablet hardware information.
Display structures	Description
ANIMATEINFO	Animation information used by the DrawPenDataEx function.
CWX	Specifies optional parameters for the CorrectWritingEx function. (Japanese version only.)
INKINGINFO	Specifies where and how to display ink.
PCMINFO	Specifies screen areas that affect pen data collection.
PENTIP	Width and color of ink trail left by pen.
RECTOFS	Offsets of inflated or deflated writing area.
SKBINFO	Information about on-screen keyboard.
Guide and control structures	Description
BOXEDITINFO	Size information for boxed edit control.
BOXLAYOUT	Layout of boxed edit control.
CTLINITBEDIT	Initialization for boxed edit control.
CTLINITHEDIT	Initialization for handwriting edit control.
CTLINITIEDIT	Initialization for ink edit control.
GUIDE	Characteristics of handwriting guides.
Recognition structures	Description
BOXRESULTS	Results returned from the GetBoxResultsHRC function.
RC	Various information about the recognition context used by version 1.0 recognition functions.
RCRESULT	Results of recognition initiated through a version 1.0 recognition function.
SYC	Symbol correspondence linking ink strokes with a particular recognized symbol.
SYE	Symbol element containing a recognized symbol and its confidence level.
SYG	Symbol graph containing SYC and SYE struc-tures that together specify all guesses a recog-nizer has made.
Pen data structures	Description
PENDATAHEADER	Header structure of an HPENDATA memory block.
PENPACKET	Data sent by pen driver to inform system of pen activity.
STRKFMT	Attributes of a stroke.
STROKEINFO	Information about points making up a single stroke.
Time interval structures	Description
ABSTIME	Time of a pen data point in seconds and milliseconds.
INTERVAL	Start and end times for a set of data points.
Target structures	Description
INPPARAMS	Describes a set of targets.
TARGET	Information about a single target window.
TARGINFO	Information about a set of targets.


 Pen API Messages

The Pen API defines message and submessage values identified by the following prefixes:

Message prefix	Description
CTLINIT_	Submessages for WM_CTLINIT.
DRV_	Messages from the pen hardware driver.
HE_	Submessages of WM_PENCTL for hedit and bedit controls.
HN_	Notification messages for hedit and bedit controls.
IE_	Messages for iedit control.
IN_	Notification messages for iedit control.
PE_	Submessages for WM_PENEVENT.
PMSC_	Submessages for WM_PENMISC.
SKB_	Submessages for WM_SKB.
SKN_	Notifications for WM_SKB.
WM_	Window messages for pen-based applications.


 Pen API Constants

The PENWIN.H header file defines manifest constants for the Pen API, most of which begin with prefixes of two or more letters to indicate their purpose. The following table describes the prefixes of the Pen API constants:

Constant prefix	Description
AI_	Options for AnimateProc function.
ALC_	Alphabet codes.
BEI_	Information for bedit control.
BESC_	Size of bedit control.
BXD_	Define dimensions of bedit control (Roman).
BXDK_	Define dimensions of bedit control (Japanese).
BXS_	Styles for bedit controls.
CMPD_	Options for CompressPenData function.
COLOR_	Input method editor colors for bedit control.
CPD_	Storage codes for CreatePenDataEx.
CPDR_	Types for CreatePenDataRegion.
CWR_	Options for CorrectWriting.
DIRQ_	Dictionary request codes.
DPD_	Flags for DrawPenDataEx function.
EPDP_	Options for ExtractPenDataPoints.
EPDS_	Options for ExtractPenDataStrokes.
GGRC_	Options for GetGlobalRC.
GPA_	Options for GetPenDataAttributes.
GRH_	Return types from GetResultsHRC.
GSA_	Options for GetStrokeAttributes.
GST_	Codes for EnableGestureSetHRC.
HEKK_	Subfunctions for kana-kanji conversions.
HEP_	Subfunctions for HE_STOPINKMODE.
HKP_	Options for SetPenHook.
HRCR_	Return values from recognition functions.
IDC_	Cursor types defined by pen display driver.
IEB_	Codes for background in iedit controls.
IEDO_	Codes for draw option IE_ messages.
IEM_	Menu codes for IE_ iedit control messages.
IEMODE_	Codes for IE_SETMODE message.
IEN_	Codes for IE_SETNOTIFY message.
IER_	Codes for stroke format IE_ messages.
IEREC_	Codes for recognition IE_ messages.
IES_	Style attributes for iedit control.
IESEC_	Codes for security IE_ messages.
IESF_	Flags for STRKFMT structure.
ISR_	Return values from inkset functions.
OBM_	Public bitmaps.
PCM_	Termination conditions for pen collection mode.
PCMR_	Return values from data collection functions.
PDC_	Pen device capability codes.
PDK_	Pen driver state bits for GetPenAsyncState function.
PDR_	General pen data return values.
PDT_	Pen driver values specific to original equipment manufacturer.
PDTS_	Trim options for MetricScalePenData.
PDTT_	Trim options for CompactPenData.
PENTIP_	Values for PENTIP structure.
PHW_	Report codes for CreatePenDataEx.
PII_	Flags for INKINGINFO structure.
PMI_	Codes for GetPenMiscInfo, SetPenMiscInfo, and WM_PENMISCINFO.
PMSCL_	lParam values for PMSC_ constants.
PMSCR_	Return values for PMSC_TARGETING subfunction.
PWF_	Subcodes of PMI_SYSFLAGS.
RC_	Values for RC structure.
RCD_	Indicates writing direction (left to right, top down, etc.).
RCO_	Recognition options for RC structure.
RCOR_	Tablet orientation codes.
RCP_	User preference codes.
RCRT_	Values for wResultsType member of RCRESULT structure.
REC_	Return codes from a version 1.0 recognizer.
RHH_	Hook types for ResultsHookHREC.
SGRC_	Options for SetGlobalRC.
SHC_	Codes for word-list coercion functions.
SKB_	Flag values for ShowKeyboard.
SSA_	Options for SetStrokeAttributes.
SSH_	Indicates writing direction (left to right, etc.).
SYV_	Codes for symbol characters, shapes, and gestures.
TPD_	Options for TrimPenData function.
TPT_	Flags for TARGINFO structure.
VWM_	Flag values for PostVirtualMouseEvent.
WCR_	Configuration options for ConfigHREC and ConfigRecognizer.
WLT_	Word list types.


 Pen Application Programming Interface Functions

This chapter provides a reference listing of the pen API functions, arranged in alphabetical order. Each entry describes a separate function organized under the following margin headings:

Margin heading	Description
Parameters	List of function parameters
Return Value	Possible return values and their meanings
Comments	Additional information about the function
See Also	Cross-reference to related API services
Next to each function name is a number that identifies the pen API version that supports the function — for example, 1.0 or 2.0.

The names of application callback functions appear in italics to indicate the names are placeholders. Callback functions can have any name.

Constants that pertain only to a specific function are listed in this chapter in the reference entry for that function. Generally, constants that pertain to two or more API services appear in Chapter 13, "Pen Application Programming Interface Constants."


AddInksetInterval [New - Windows 95]
 AddInksetInterval

2.0      [New - Windows 95]

Merges an interval into an inkset.

BOOL AddInksetInterval( HINKSET hinkset, LPINTERVAL lpiNew )

Parameters

hinkset

Handle to an inkset.

lpiNew

Address of an INTERVAL structure.

Return Value

Returns TRUE if successful; otherwise FALSE.

Comments

The inkset is reallocated to a larger size by this function. The interval merges with any existing intervals, changing the interval only when required. For example, if the new interval is a subset of an existing one, there will be no change. Similarly, if the new interval overlaps an existing one, the union is formed. The maximum number of intervals allowed is defined to be (65536 - sizeof(INKSET)) / sizeof(INTERVAL), which evaluates to 5460.

The ending time of the new interval must be greater than or equal to the beginning time. If the interval has a duration of 0, AddInksetInterval does nothing, but returns TRUE.

An inkset formed using this function is guaranteed to have the intervals in ascending chronological order.

See Also

GetInksetInterval, INTERVAL


AddPenDataHRC [New - Windows 95]
 AddPenDataHRC

2.0      [New - Windows 95]

Adds an HPENDATA object to an HRC object for recognition.

int AddPenDataHRC( HRC hrc, HPENDATA hpndt )

Parameters

hrc

Handle to the HRC object.

hpndt

Handle to the HPENDATA object.

Return Value

Returns HRCR_OK if successful; otherwise, returns one of the following negative values:

Constant	Description
HRCR_ERROR	Invalid parameter or other error.
HRCR_MEMERR	Insufficient memory.
HRCR_INVALIDPNDT	Invalid pen data object.
Comments

Before terminating, the application must free the pen data, using DestroyPenData. Because the recognizer copies any data it requires, the recognizer does not affect the original data.

Calling this function is equivalent to adding data to the recognition context by walking the pen data strokes from beginning to end in stroke order. (Note that the stroke order may not necessarily be in chronological order if insertions have been made.)

A recognizer is not required to use or maintain OEM data; that is, a recognizer may choose to ignore some or all of the OEM data it receives from AddPenDataHRC. This means that the HPENDATA object that the recognizer returns through its CreatePenDataHRC function may differ from hpndt in its OEM data.

See Also

CreatePenData, AddPenInputHRC


AddPenInputHRC [New - Windows 95]
 AddPenInputHRC

2.0      [New - Windows 95]

Adds pen data to an HRC object for recognition. A recognizer must export this function.

int AddPenInputHRC( HRC hrc, LPPOINT lppt, LPVOID lpvOem, UINT fuOem, LPSTROKEINFO lpsi )

Parameters

hrc

Handle to the HRC object.

lppt

Address of an array of POINT structures.

lpvOem

Address of a buffer containing OEM data, or NULL if there is no OEM data.

fuOem

Flags to specify which OEM data is valid.

lpsi

Address of a STROKEINFO structure.

Return Value

Returns HRCR_OK if successful; otherwise, returns one of the following negative values:

Constant	Description
HRCR_ERROR	Invalid parameter or other error.
HRCR_MEMERR	Insufficient memory.
Comments

A recognizer is not required to use or maintain OEM data; that is, a recognizer may choose to ignore some or all of the OEM data it receives from AddPenInputHRC. This means that the HPENDATA object that the recognizer returns through its CreatePenDataHRC function may differ from hpndt in its OEM data.

See Also

GetPenInput, GetPenDataStroke


AddPointsPenData [New - Windows 95]
 AddPointsPenData

1.0     2.0      [New - Windows 95]

Adds a set of data points to the pen data object.

HPENDATA AddPointsPenData( HPENDATA hpendata, LPPOINT lppt, LPVOID lpvOem, LPSTROKEINFO lpsiNew )

Parameters

hpendata

Handle to a pen data object.

lppt

Address of an array of POINT structures containing new data points to be added to the pen data. Zero points can be added to force a change of pen state or to set a new pen state.

lpvOem

OEM data. Can be set to NULL if there is no additional OEM data. The pen data header determines how the OEM data is interpreted.

lpsiNew

Address of a STROKEINFO structure for new stroke data. Contains the count of points from lppt to be added.

Return Value

Returns a handle to the pen data object. Normally, this is the same handle originally passed to the function. NULL is returned on error. The size of hpendata is limited to 64K.

Comments

A call to GetPenHwEventData or GetPenInput gets the lpsiNew and lpvOem values. A subsequent call to AddPointsPenData appends the set of points to the HPENDATA memory block identified by hpendata. The lpsiNew argument points to a STROKEINFO structure that describes the new points, and lpvOem points to the corresponding OEM data (if any) to be added along with the points.

The STROKEINFO structure indicates the pen state of the new points—that is, whether the pen is up or down. To avoid unnecessarily creating new strokes in the HPENDATA block, AddPointsPenData compares the pen state of the new points with the pen state of the last stroke in the HPENDATA block. If the new points have the same pen state as the last stroke, the function appends the points to the last stroke and updates the last STROKEINFO structure within the HPENDATA block. If the new points have a different pen state, AddPointsPenData appends them to the HPENDATA block as a new stroke, along with the STROKEINFO structure pointed to by lpsiNew.

AddPointsPenData does not scale the data points. The calling application must ensure that the added data points have the same scale as the rest of the HPENDATA block.

See Also

CreatePenData, GetPenHwEventData


AddWordsHWL [New - Windows 95]
 AddWordsHWL

2.0      [New - Windows 95]

Adds words to a word list.

int AddWordsHWL( HWL hwl, LPSTR lpsz, UINT uType )

Parameters

hwl

Handle to a word list, or the constant HWL_SYSTEM for the recognizer's master word list.

lpsz

A pointer to a source of words, depending on the uType parameter.

uType

Word list type. This can be one of the following values:

Constant	Description
WLT_STRING	lpsz points to a single null-terminated character string in memory.
WLT_STRINGTABLE	lpsz points to an array of null-terminated character strings in memory. The list is terminated by two null characters.
WLT_WORDLIST	lpsz is the handle of a previously created word list, cast as LPSTR.
Return Value

Returns HRCR_OK if successful; otherwise, returns one of the following negative values:

Constant	Description
HRCR_ERROR	Invalid parameter or other error.
HRCR_MEMERR	Insufficient memory.
Comments

If a user wants to add a word to the system word list, which is available whenever the system dictionary is enabled (see EnableSystemDictionaryHRC), then hwl should be set to the predefined constant HWL_SYSTEM. Words that are not normally found in a dictionary, such as a person's name, can be added to the system word list. How this list is implemented, its size, or if it even exists, depends on the recognizer. A typical recognizer might maintain a thousand-word list, replacing random entries on overflow.

The HWL_SYSTEM constant cannot be used in any of the other word-list functions. For example, it is not possible to destroy the system word list with the DestroyHWL function.

For a description of word lists and how a recognizer uses them, see "Configuring the HRC" in Chapter 5, "The Recognition Process."

See Also

CreateHWL, EnableSystemDictionaryHRC


AnimateProc [New - Windows 95]
 AnimateProc

2.0      [New - Windows 95]

The AnimateProc function is an application-defined callback function that provides information to DrawPenDataEx on a periodic basis. The name AnimateProc serves only as a placeholder; the function can have any name.

BOOL CALLBACK AnimateProc( HPENDATA hpndt, UINT iStrk, UINT cPnt, UINT FAR * lpuSpeedPct, LPARAM lParam )

Parameters

hpndt

Handle to the pen data currently being drawn.

iStrk

Zero-based index to the stroke being drawn, or about to be drawn.

cPnt

Count of points already drawn in this stroke.

lpuSpeedPct

Address of the speed-percent value.

lParam

Application-specific data passed to the callback. This value is specified in ANIMATEINFO.

Return Value

The callback function must return TRUE to continue drawing the pen data. Returning FALSE stops animation immediately.

Comments

One of the parameters of DrawPenDataEx provides the address of this callback function. The application must create an instance of this function using the MakeProcInstance function, and ensure that it is exported in the module-definition (.DEF) file.

The application can monitor the state of animation or provide the user with an opportunity to change the speed of animation, including pausing it, using the value addressed by lpuSpeedPct.

The application can also pass application-specific information to the callback in lParam. For example, a handle to the DC (device context) can be passed.

Callbacks are made at the beginning of the stroke or time interval, before any drawing is done. However, if AI_SKIPUPSTROKES is specified, a callback is not made before up strokes.

See Also

DrawPenDataEx,  ANIMATEINFO


AtomicVirtualEvent [New - Windows 95]
 AtomicVirtualEvent

1.0     2.0      [New - Windows 95]

Locks out pen packets.

void AtomicVirtualEvent( BOOL fBegin )

Parameters

fBegin

Flag for beginning or ending lockout. TRUE begins lockout, FALSE ends it.

Return Value

This function does not return a value.

Comments

AtomicVirtualEvent is used by the Pen Palette or a similar virtual-keyboard program to lock out pen packets while the application is posting simulated key or mouse events.

Calling AtomicVirtualEvent with a TRUE value blocks input from physical devices until they are freed with a call specifying FALSE. Applications should end the lockout as quickly as possible.

An interruptable thread should not call AtomicVirtualEvent.

Example

The following code fragment posts a mouse click:

AtomicVirtualEvent( TRUE );

PostVirtualMouseEvent( VWM_MOUSELEFTDOWN, xPos, yPos );

PostVirtualMouseEvent( VWM_MOUSEMOVE, xPos, yPos );

PostVirtualMouseEvent( VWM_MOUSELEFTUP, xPos, yPos );

AtomicVirtualEvent( FALSE );

See Also

PostVirtualKeyEvent, PostVirtualMouseEvent


BeginEnumStrokes [New - Windows 95]
 BeginEnumStrokes

1.0     2.0      [New - Windows 95]

Locks a pen data block in memory in preparation for enumerating strokes.

Note  This function is provided only for compatibility with version 1.0 of the Pen API, and will not be supported in future versions.

LPPENDATA BeginEnumStrokes( HPENDATA hpendata )

Parameters

hpendata

Handle to an HPENDATA object.

Return Value

Returns a pointer to the locked pen data if successful. Returns NULL if hpendata is compressed or if the handle cannot be locked.

Comments

BeginEnumStrokes calls the GlobalLock function internally, returning a far pointer to the memory block in the global heap. This serves to lock the data in preparation for direct reading or calling GetPenDataStroke. The return value from BeginEnumStrokes is used as an argument for GetPenDataStroke. After calling BeginEnumStrokes to lock data, an application must unlock the data when finished by calling EndEnumStrokes.

An application should never modify data directly within an HPENDATA block. Doing so can invalidate other information in the block. To modify an HPENDATA block, use one of the Pen API functions listed in Chapter 4, "The Inking Process."

See Also

EndEnumStrokes, GetPenDataStroke


BoundingRectFromPoints [New - Windows 95]
 BoundingRectFromPoints

1.0     2.0      [New - Windows 95]

Calculates a rectangle that bounds a range of points.

void BoundingRectFromPoints( LPPOINT lppt, UINT cPt, LPRECT lprect )

Parameters

lppt

Address of an array of POINT structures.

cPt

Number of POINT structures in the array. This parameter can be 0.

lprect

Address of a RECT structure that contains the bounding rectangle when the function returns.

Return Value

This function does not return a value.

Comments

The bounding rectangle is empty at [0,0] if there are no points. For a single point, the rectangle is empty at that point.


CharacterToSymbol [New - Windows 95]
 CharacterToSymbol

1.0     2.0      [New - Windows 95]

Converts an ANSI string to an array of SYV_ symbol values.

int CharacterToSymbol( LPSTR lpstr, int cSyv, LPSYV lpsyv )

Parameters

lpstr

Address of a null-terminated ANSI string to be converted.

cSyv

Maximum number of SYV_ symbols the array lpsyv can hold.

lpsyv

Address of an array of SYV_ symbol values into which CharacterToSymbol places the converted symbols. The array must be large enough to hold cSyv symbols.

Return Value

Returns the number of characters converted, or −1 if there is an error.

Comments

Conversion proceeds until a null byte is found in lpstr or until lpsyv has been filled with cSyv symbols. A null byte is converted to SYV_NULL.

See Also

SymbolToCharacter, SYG, SYV_


CompactPenData [New - Windows 95]
 CompactPenData

1.0     2.0      [New - Windows 95]

Compacts pen data based on specified trim options.

Note  This function is provided for compatibility with version 1.0 of the Pen API and will not be supported in future versions. Use TrimPenData and CompressPenData instead.

HPENDATA CompactPenData( HPENDATA hpndt, UINT fuTrim )

Parameters

hpndt

Handle to a pen data object.

fuTrim

Data-trimming options:

PDTT_DEFAULT

Reallocates memory block to fit the data; does not trim the data. If you call CompactPenData with this trim option and then call the GlobalSize function with the pen data handle as a parameter, you can retrieve the size of the pen data.

PDTT_ALL

Removes the PENINFO structure from the header. Discards all data from pen-up points (points collected when the pen is not in contact with the tablet), and removes OEM data and collinear points.

PDTT_COLLINEAR

Removes successive identical (coincident) points and collinear points from the pen data. After the operation is performed, PDTS_NOCOLLINEAR is set in the wPndts member of the PENDATAHEADER structure. The collinear points can be removed with very little if any loss of recognition accuracy. If the collinear points are removed before the points are scaled to display coordinates, there may be a small change in the displayed image.

PDTT_COMPRESS

Compresses the data without losing any information. After the data has been compressed, the compressed handle to the pen data can be passed as a parameter only to the functions CompactPenData, GetPenDataInfo, and DuplicatePenData. CompactPenData uses a "lossless" compression method that retains the ability for an application to recognize the ink after subsequent decompression. You can use this option with other trim options, including PDTT_DECOMPRESS. In this case, compression is done after all other options have been satisfied.

PDTT_DECOMPRESS

Decompresses the data. You can use this option with other trim options, including PDTT_COMPRESS. In this case, decompression is performed first, followed by any other trim options specified, and followed by recompression if PDTT_COMPRESS is specified. Since the compression method used by CompactPenData does not lose information, the data is completely restored.

PDTT_OEMDATA

Removes all OEM data—this is data other than coordinates, such as pressure. This option does not affect delayed recognition unless a recognizer is being used that expressly requires OEM data. For example, signature recognizers often use pressure information.

PDTT_PENINFO

Removes the PENINFO structure from the header. You can use this option if there is no OEM data associated with the data points or if the application does not use any of the OEM data. This option has no effect on the pen data for delayed recognition. Any OEM data present is also removed.

PDTT_UPPOINTS

Removes all data from pen-up points (points collected when the pen is not in contact with the tablet). This option has no effect on delayed recognition. This option is not usually necessary because pen-up points are not a part of standard pen data.

Return Value

If successful, CompactPenData returns a handle to a pen data object; otherwise, it returns NULL. CompactPenData may fail and return NULL in low-memory situations if compression or decompression is requested.

Comments

The PDTS_ bits are set in the wPndts member of the PENDATAHEADER structure to indicate which operations have been performed.

See Also

CompressPenData, TrimPenData, CreatePenData, PENINFO, PENDATAHEADER


CompressPenData [New - Windows 95]
 CompressPenData

2.0      [New - Windows 95]

Compresses or decompresses the data in an HPENDATA object.

int CompressPenData( HPENDATA hpndt, UINT fuFlags, DWORD dwReserved )

Parameters

hpndt

Handle to the HPENDATA object.

fuFlags

Specifies whether to compress or decompress the data, as follows:

Constant	Description
CMPD_COMPRESS	Compress the pen data.
CMPD_DECOMPRESS	Decompress the pen data.
dwReserved

Must be 0.

Return Value

This function returns one of the following:

Constant	Description
PDR_OK	Successful completion. Redundant operations, such as compressing an HPENDATA object that has already been compressed, are not errors.
PDR_ERROR	Illegal parameter or other error.
PDR_MEMERR	Memory error.
PDR_PNDTERR	Invalid pen data.
PDR_VERSIONERR	Could not convert old pen data.
Comments

This function replaces the the version 1.0 Pen API function CompactPenData, which is supported for compatibility only.

For a discussion of data compression, see "Compressing Pen Data" in Chapter 4, "The Inking Process."

See Also

CompactPenData,  TrimPenData


ConfigHREC [New - Windows 95]
 ConfigHREC

2.0      [New - Windows 95]

Allows an application to set or query recognizer-specific values. All calls to ConfigHREC are serviced by the recognizer's ConfigRecognizer function. In version 2.0 of the Pen API, applications must call ConfigHREC rather than ConfigRecognizer.

int ConfigHREC( HREC hrec, UINT uSubFunction, WPARAM wParam, LPARAM lParam )

Parameters

hrec

Module handle of the recognizer library. If this value is NULL, the system default recognizer is used.

uSubFunction

Recognizer subfunction identifier. See the "Comments" section below.

wParam

Depends on the value of uSubFunction.

lParam

Address of a buffer. The contents of the buffer depend on the value of uSubFunction.

Return Value

If successful, returns 0 or a positive value as described in the list of uSubfunction constants below; otherwise, returns one of the following negative values:

Constant	Description
HRCR_ERROR	Missing recognizer, invalid parameter, or other error.
HRCR_MEMERR	Insufficient memory.
Comments

The uSubFunction parameter contains one of the following WCR_ values that identifies the requested configuration service:

WCR_CONFIGDIALOG

Instructs the recognizer to open a dialog box to set any recognizer-specific parameters. (This is analogous to DEVMODE in printer drivers, which is called when a user sets up a printer.) Some examples of the kind of settings a recognizer might implement are whether or not to allow cursive input, how much to depend on stroke order, and how rapidly to modify prototypes based on the user's own style.

The lParam parameter points to the name of the user currently selected in the Control Panel application. The wParam parameter is used by the recognizer as the parent window for any dialog boxes it displays. The return value is always TRUE.

WCR_DEFAULT

Returns TRUE if the recognizer is capable of being a default recognizer. A default recognizer must support the standard character set as well as standard gestures.

WCR_GETALCPRIORITY

Returns the current default alphabet priority being used by the recognizer. The lParam parameter points to a variable that specifies the alphabet priority as a bitwise-OR combination of ALC_ values. The wParam parameter is not used. This subfunction is used by the system; applications should instead get alphabet priority by calling GetAlphabetPriorityHRC. The return value is TRUE if successful.

WCR_GETANSISTATE

Returns TRUE if the recognizer can recognize all of the ANSI character set; otherwise, returns FALSE or HRCR_ERROR.

WCR_GETDIRECTION

If successful, returns the current writing direction assumed by the recognizer; otherwise, returns HRCR_ERROR.

WCR_GETHAND

If successful, returns 0 if the user writes with the right hand or nonzero if the user writes with the left hand; otherwise, returns HRCR_ERROR.

WCR_PRIVATE

Values above WCR_PRIVATE have a meaning dependent on the recognizer.

WCR_PWVERSION

Returns the version number of the Pen API for which this recognizer was created. This value is 2 for the current version.

WCR_QUERY

Returns TRUE if the recognizer supports a configuration dialog box.

WCR_QUERYLANGUAGE

The wParam parameter is not used. The lParam parameter points to a null-terminated language string. The return value is TRUE if the recognizer supports the language; otherwise, it is FALSE.

WCR_RECOGNAME

Retrieves an identification string from the recognizer. The lParam parameter is treated as a far pointer to a buffer that is filled with an identification string from the recognizer. The wParam parameter is the size of the buffer to fill. The identification string is a short description of the recognizer that Control Panel presents to the user. A sample string is "US English character set, cursive & print." The return value is always 0.

WCR_SETALCPRIORITY

Sets the current default alphabet priority for the recognizer to the value in lParam. Note that setting a priority for individual characters is not supported for defaults. The wParam parameter is not used. This subfunction is used by the system; applications should set priority explicitly in an HRC with the SetAlphabetPriorityHRC function. The return value is TRUE if successful.

WCR_SETANSISTATE

Sets a flag to enable or disable recognition of the entire ANSI character set. Setting lParam to 1 enables recognition of the entire ANSI set; setting lParam to 0 allows recognition of only English (ASCII) characters. The wParam parameter is not used.

The WCR_SETANSISTATE subfunction determines the default setting when CreateCompatibleHRC creates an HRC. An application can explicitly override the setting for the HRC with the SetInternationalHRC function. The return value is TRUE if successful.

WCR_SETDIRECTION

Sets the current writing direction for the recognizer to the value in lParam, which can be an appropriate combination of the RCD_ values. The wParam parameter is not used. The return value is TRUE if successful.

WCR_SETHAND

Sets the current writing hand preference for the recognizer. The lParam parameter is 0 for a right-handed user or 1 for a left-handed user. The wParam parameter is not used. The return value is TRUE if successful.

WCR_TRAIN

This subfunction returns TRAIN_NONE if the recognizer does not support training. A return value of TRAIN_DEFAULT indicates support for the default trainer, including the capability of resetting its database to the original "factory" setting (see WCR_TRAINSAVE). A return value of TRAIN_CUSTOM indicates that the recognizer also provides its own custom trainer. A return value of TRAIN_BOTH indicates support for both kinds of training.

WCR_TRAINMAX

The recognizer returns the maximum number of SYV_ symbol values that it can train for any given shape.

The recognizer should return 0 if it can train any number of characters. For example, the Microsoft recognizer can train one character for a shape; a cursive recognizer may allow more.

WCR_TRAINSAVE

The trainer calls the ConfigHREC function with the parameters set to (WCR_TRAINSAVE, TRAIN_SAVE, 0) when it is time to save the data-base. This happens when the user closes the trainer. After this call, the recognizer should return TRUE if it can successfully save the database; otherwise, it should return FALSE.

The trainer calls the function with (WCR_TRAINSAVE, TRAIN_REVERT, 0) before it discards any changes made to the database that have not yet been saved to disk (that is, revert to saved). This happens when the user cancels the changes. The recognizer should return TRUE if it is successful.

The trainer can alternatively call ConfigHREC with (WCR_TRAINSAVE, TRAIN_RESET, 0) to reset the database to the original "factory" settings. The recognizer should return TRUE if it is successful.

WCR_TRAINDIRTY

The recognizer returns TRUE if the recognizer needs to save training. The recognizer returns FALSE if no training occurred, if the recognizer does not use a database for training, if the recognizer saves as it works, or if the recognizer cannot revert the training.

The hwnd parameter is a handle to the requesting window. The trainer can use this as the parent window for a dialog box, for example. If there has been a recent recognition, a pointer to it is passed in the lParam parameter, although this may be NULL.

The format for the WCR_TRAINDIRTY subfunction call is:

ConfigHREC( hrec, WCR_TRAINDIRTY, 0, 0 );

WCR_TRAINCUSTOM

If the recognizer returns TRAIN_CUSTOM or TRAIN_BOTH in response to WCR_TRAIN, it will receive a WCR_TRAINCUSTOM message when it is time to display its own training system.

The format for the WCR_TRAINCUSTOM subfunction call is:

ConfigHREC( hrec, WCR_TRAINCUSTOM, hwnd, lprcresult );

WCR_USERCHANGE

Notifies the recognizer of a change in user. The lParam parameter points to a null-terminated string containing the user's name. The wParam parameter specifies the required modification:

A wParam value of CRUC_NOTIFY indicates a new user, the name of whom is in the string that lParam points to.

A wParam value of CRUC_REMOVE indicates that the user identified by lParam should be removed from the recognizer's user list. If the recognizer has saved any files or settings for the user, they should be deleted in response to this notification.

WCR_VERSION

Returns the version number. The low-order byte of the return value specifies the major (version) number. The high-order byte specifies the minor (revision) number.

See Also

ConfigRecognizer, ALC_, SYV_


ConfigRecognizer [New - Windows 95]
 ConfigRecognizer

1.0     2.0      [New - Windows 95]

Provides system access to the configuration settings of a recognizer. In version 2.0 of the Pen API, only the pen system can call ConfigRecognizer. Applications must call ConfigHREC to query or set recognizer configuration values. The system routes ConfigHREC calls to the ConfigRecognizer function of the appropriate recognizer.

A recognizer must export ConfigRecognizer. The information in this entry is for recognizer developers only, not application developers.

UINT ConfigRecognizer( UINT uSubFunction, WPARAM wParam, LPARAM lParam )

Parameters

uSubFunction

Recognizer subfunction identifier. See ConfigHREC for descriptions of the WCR_ subfunctions that ConfigRecognizer must support. In addition, ConfigRecognizer must support the following two WCR_ subfunctions:

WCR_INITRECOGNIZER

When an application installs a recognizer by using InstallRecognizer, the system calls the recognizer's ConfigRecognizer function with the WCR_INITRECOGNIZER subfunction. The wParam parameter is not used and lParam is a far pointer to an ASCII string containing the user's name, as set in the system registry. If successful, the recognizer should return 1; otherwise, it should return 0 to indicate an error.

In response to the WCR_INITRECOGNIZER subfunction, the recognizer should perform any required initialization tasks. (This subfunction replaces the InitRecognizer function exported by version 1.0 recognizers.)

WCR_CLOSERECOGNIZER

When an application unloads a recognizer by using UninstallRecognizer, the system calls the recognizer's ConfigRecognizer function with the WCR_CLOSERECOGNIZER subfunction. The wParam and lParam parameters are not used. If successful, the recognizer should return 1; otherwise, it should return 0 to indicate an error.

In response to the WCR_CLOSERECOGNIZER subfunction, the recognizer should perform any required cleanup tasks. (This subfunction replaces the CloseRecognizer function exported by version 1.0 recognizers.)

wParam

Depends on the value of uSubFunction.

lParam

A value, or an address of a buffer. The contents of the buffer depend on the value of uSubFunction.

Return Value

Returns 0 or a positive value, depending on uSubFunction.

Comments

ConfigRecognizer provides initialization and query services for the pen system. The parameter uSubFunction is a WCR_ value that specifies the configuration service that ConfigRecognizer must perform.

When an application calls ConfigHREC, the system determines the appropriate recognizer and passes the call to that recognizer's ConfigRecognizer function. ConfigHREC exists only because its extra argument hrec identifies to the system the intended recognizer library. This information is necessary in version 2.0 of the Pen API, which allows multiple recognizer libraries to exist simultaneously. Thus, the names ConfigHREC and ConfigRecognizer refer to the same function. Applications refer to the function as ConfigHREC, while recognizers export it as ConfigRecognizer.

See Also

ConfigHREC, SYV_


CorrectWriting [New - Windows 95]
 CorrectWriting

1.0     2.0      [New - Windows 95]

Sends text to the CorrectText dialog box to allow the user to edit text using a single-line or multiline bedit control.

BOOL CorrectWriting( HWND hwnd, LPSTR lpText0, UINT cbText0, LPVOID lpvReserved, DWORD dwFlags, DWORD dwParam )

Parameters

hwnd

Handle of the owner of the CorrectText dialog box or writing tools used to edit the text.

lpText0

Far pointer to a buffer containing the text to be corrected.

When CorrectWriting returns, the lpText0 buffer holds the corrected text. As a general rule, this parameter should allow for growth by a factor of at least two or some maximum size that depends on the field of entry.

cbText0

Number of characters in lpText0. This value must be greater than 1 and include a byte for the string's null terminator.

lpvReserved

This parameter is reserved and should be set to NULL.

dwFlags

Translation and style flags, formed by the low-order word and high-order word of dwFlags. The low-order word must be one or more of the following flags, combined with the bitwise-OR operator. Note that the CWR_REPLACECR and CWR_REPLACETAB flags replace CWR_STRIPTAB and CWR_STRIPCR, respectively; both flags are in version 1.0 of the Pen API.

Constant	Description
CWR_BOXES	Create bedit writing tool instead of keyboard. This flag can be used only for edit control and its derivatives. Use of this flag by applications is not recommended.
CWR_HEDIT	Indicates that the given hwnd is an edit control or a control derived from the edit control. This flag can be used only for edit control and its derivatives. Use of this flag by applications is not recommended.
CWR_INSERT	Use "Insert Text" instead of "Edit Text" as the title. CWR_TITLE overrides this flag.
CWR_KEYBOARD	Create keyboard writing tool instead of bedit lens. This flag can be used only for edit control and its derivatives. Use of this flag by applications is not recommended.
CWR_KKCONVERT	Initiate IME (Japanese version only).
CWR_REPLACECR	Replace carriage return characters in the text in the buffer by spaces just before the call returns.
CWR_REPLACETAB	Replace tabs in the text in the buffer by spaces just before the call returns.
CWR_SIMPLE	Use writing tool (simple dialog box). This flag can be used only for an edit control and its derivatives. Use of this flag by applications is not recommended.
CWR_SINGLELINEEDIT	Replace carriage returns and tabs with spaces and strip linefeeds from the text in the buffer just before the call returns.
CWR_STRIPLF	Strip linefeed characters from the text in the buffer just before the call returns.
CWR_TITLE	Interpret dwParam (see below) as a pointer to the title text string.
The high-order word must be one of the following values and cannot be combined with the bitwise-OR operator. The values determine the type of keyboard to show when the user clicks the keyboard button in the dialog box.

Constant	Description
CWRK_TELPAD	Use the telephone-type keyboard.
CWRK_BASIC	Use the basic keyboard.
CWRK_DEFAULT	Use the default keyboard type. The default keyboard type is currently the same as the basic keyboard type.
CWRK_FULL	Use the full keyboard.
CWRK_NUMPAD	Use the numeric keyboard.
dwParam

A far pointer to a text string that serves as the title of the dialog box if CWR_TITLE is present in dwFlags; otherwise, this parameter must be 0.

Return Value

Returns TRUE if the writing tool or CorrectWriting operation was successful. Otherwise, the return value is FALSE.

Comments

CorrectWriting sends a WM_PENMISC message with PMSC_GETHRC as the lParam to the specified window. This message requests the HRC handle associated with the window, which the system then uses for the dialog box. The window should return a copy of its HRC so that the system can destroy it before the call returns. If the window returns NULL to this message, the system creates a default HRC.

Note that in the Japanese version, CorrectWriting is supported but internally calls CorrectWritingEx, which opens a Dialog Input Window.


CorrectWritingEx [New - Windows 95]
 CorrectWritingEx

2.0      [New - Windows 95]

Sends text to the CorrectText dialog box to allow the user to edit text using the Japanese Data Input Window. (Japanese version only.)

INT CorrectWritingEx( HWND hwnd, LPSTR lpText, UINT cbText, LPCWX lpcwx )

Parameters

hwnd

Handle of the owner of the CorrectText dialog box or writing tool used to edit the text. This can be NULL.

lpText

Far pointer to a buffer containing text to correct. This is copied into the Data Input Window's edit control.  If lpText is NULL, a WM_GETTEXT message is sent to the text source window, specified by the hwndText member of lpcwx, or if lpcwx or its hwndText member is NULL, to hwnd.  On successful exit, a WM_SETTEXT message will be sent to that window with modified text.

cbText

Size of the lpText buffer. If the source of the text is an edit control constrained by EM_LIMITTEXT, cbText should reflect that size. If lpText is NULL, the cbText value will be used to limit text if it is greater than zero; otherwise, no limit is used and the returned text may be of arbitrary size.

lpcwx

Address of a CWX structure, or NULL. The structure is used to specify optional correction parameters; for a description of its members, see CWX. If this value is NULL, the following default assumptions are made:

•	The text window is the same as the owner window hwnd.

•	A default recognition context is used.

•	The edit control style is a combination of ES_LEFT and ES_MULTILINE.

•	All text is selected; the caption is "Edit Text".

•	Most recently use values for context flags, keyboard, keyboard states, position, and size are used.

Return Value

If there is a programming or memory error, the negative value CWXR_ERROR is returned. Otherwise, one of the following nonnegative values is returned:

Constant	Description
CWXR_MODIFIED	User pressed the OK button.
CWXR_UNMODIFIED	User pressed the Cancel button, or closed the dialog, or pressed the OK button but did not make any changes to the text.
Comments

An application must be sure to initialize the CWX structure properly if it is used. In particular, the cbSize member must be set to sizeof(CWX), and the remaining fields (at least up to dwSel) are typically set to zero.

Example

The following example shows how to initialize and call CorrectWritingEx when a button is pressed in a dialog:

CWX cwx = {sizeof(CWX), 0, NULL, NULL, {0}, 0L, 0L};

cwx.hwndText = GetDlgItem(hdlg, IDD_ETSL);	// dialog edit

cwx.dwEditStyle = GetWindowLong(cwx.hwndText, GWL_STYLE)

| ES_PASSWORD;

cwx.dwSel = SendMessage(cwx.hwndText, EM_GETSEL, 0, 0);

_fstrcpy((LPSTR)cwx.szCaption, (LPSTR)"Enter your password:");

// we specify kbd and context, but use MRU placement

cwx.wApplyFlags = CWXA_KBD | CWXA_STATE | CWXA_CONTEXT;

// don't update most-recently used settings for this one-shot:

cwx.wApplyFlags |= CWXA_NOUPDATEMRU;

cwx.ixkb = CWXK_QWERTY;

cwx.rgState[CWXK_QWERTY-CWXK_FIRST] = CWXKS_HAN | CWXKS_ROMA;

cwx.dwFlags = CWX_NOTOOLTIPS | CWX_TOPMOST;	// no distractions

if (CorrectWritingEx(hdlg, NULL, 0, &cwx) != CWXR_MODIFIED)

ErrBox(EB_WHOAREYOU);

// validate pwd in the text window etc...

See Also

CWX


CreateCompatibleHRC [New - Windows 95]
 CreateCompatibleHRC

2.0      [New - Windows 95]

Creates a handwriting recognition context HRC that can be used to do handwriting recognition, optionally compatible with an existing context template. A recognizer must export this function.

HRC CreateCompatibleHRC( HRC hrcTemplate, HREC hrec )

Parameters

hrcTemplate

Handle to an existing HRC object that can provide default settings for the recognition context being created. If NULL, this parameter is ignored and default settings are used.

hrec

Instance handle of the recognizer library. This is the value returned by the Windows function LoadLibrary. Note that the module handle returned by the Windows function GetModuleHandle does not work in this case. If this value is NULL, the system default recognizer is used by internally making a call to GetPenMiscInfo with PMI_SYSREC as the first argument.

Return Value

Returns a handle to a new HRC object if successful; otherwise, returns NULL.

Comments

The hrcTemplate parameter can be used to copy an old context into the new HRC object. This includes settings such as word lists, coercion, and GUIDE structure, but excludes any pen data that may be in the old context.

See Also

DestroyHRC, GetResultsHRC, SetMaxResultsHRC


CreateHWL [New - Windows 95]
 CreateHWL

2.0      [New - Windows 95]

Creates a handle to a word list.

HWL CreateHWL( HREC hrec, LPSTR lpsz, UINT uType, DWORD dwReserved )

Parameters

hrec

Module handle of the recognizer library. If this value is NULL, the system default recognizer is used.

lpsz

A pointer to a source of words, depending on the uType parameter.

Type

Word-list type. This can be one of the following values:

Constant	Description
WLT_EMPTY	An empty word list is created. The lpsz parameter is ignored.
WLT_STRING	The lpsz parameter points to a single null-terminated character string in memory.
WLT_STRINGTABLE	The lpsz parameter points to an array of null-terminated character strings in memory. The list is terminated by two null characters.
dwReserved

Must be 0.

Return Value

If successful, returns the handle of a newly created word list; otherwise, returns NULL. If the recognizer does not support word lists, the return value is NULL.

Comments

CreateHWL creates a word list for constraining recognition. Word lists can be combined using the AddWordsHWL function.

To make a word list from words in a file, an application uses CreateHWL to create an empty word list, then reads the file into it with the ReadHWL function.

Any word lists created by an application must eventually be destroyed by calling DestroyHWL. Attempting to unload a recognizer that has open word lists results in an error.

For a description of word lists and how a recognizer uses them, see "Configuring the HRC" in Chapter 5, "The Recognition Process."

Example

The following example demonstrates how to provide a word list to constrain recognition results to the words "Canada," "USA," or "Mexico":

static char szNames[] = { "Canada",

  "USA",

  "Mexico"

};

HWL hwlCountries = CreateHWL( NULL,

(LPSTR)szNames,

WLT_STRINGS, 0L );	      // Create early for later use

.

.

.

if (hrc = CreateCompatibleHRC( NULL, NULL ))

{

   SetWordlistHRC( hrc, hwlCountries );       // Set list into HRC

   SetWordlistCoercionHRC( hrc, SCH_FORCE );  // Force match

   .

   .	   // Code that collects and recognizes input goes here

   .

}

See Also

AddWordsHWL, DestroyHWL, SetWordlistHRC


CreateInkset [New - Windows 95]
 CreateInkset

2.0      [New - Windows 95]

Creates an empty inkset.

HINKSET CreateInkset( UINT gmemFlags )

Parameters

gmemFlags

Flag that specifies whether or not the Windows GlobalAlloc function should create a shared memory object when the inkset object is created. This flag should be either 0 or GMEM_DDESHARE. The GMEM_MOVEABLE and GMEM_ZEROINIT flags are added to this value, and other GMEM_ flags are ignored.

Return Value

Returns a handle to an inkset if successful; otherwise, the return value is NULL.

See Also

DestroyInkset, INTERVAL


CreateInksetHRCRESULT [New - Windows 95]
 CreateInksetHRCRESULT

2.0      [New - Windows 95]

Creates an inkset from parts of a recognition result.

HINKSET CreateInksetHRCRESULT( HRCRESULT hrcresult, UINT iSyv, UINT cSyv )

Parameters

hrcresult

Handle of an HRCRESULT object.

iSyv

Index to first symbol for inkset.

cSyv

Count of symbols.

Return Value

Returns the handle of a newly created inkset if successful. If the index to the first symbol iSyv is invalid, or some other error occurs, the return value is NULL.

Comments

The inkset spans a series of continuous symbols; disjoint sets are not allowed. Before terminating, the calling application must destroy the HINKSET object by calling DestroyInkset.

If the range of symbols specified by iSyv + cSyv exceeds the number of symbols available, the returned inkset is valid only for available symbols. This is not an error, so it is possible to assign cSyv a large value to get an inkset for all symbols after iSyv.

For a description of inksets, see "The HINKSET Object" in Chapter 4, "The Inking Process."

See Also

DestroyInkset, GetResultsHRC


CreatePenData [New - Windows 95]
 CreatePenData

1.0     2.0      [New - Windows 95]

Creates an empty HPENDATA block.

Note  This function is provided only for compatibility with version 1.0 of the Pen API and will not be supported in future versions. Use CreatePenDataEx instead.

HPENDATA CreatePenData( LPPENINFO lppeninfo, int cbOem, UINT uScale, UINT gmemFlags )

Parameters

lppeninfo

Address of tablet information to be inserted into the PENINFO structure in the pen data header. If this parameter is NULL, the current tablet settings are retrieved from the hardware instead. If there is no tablet, the pen data will not have an embedded PENINFO section and the wPndts member in PENDATAHEADER will have the PDTS_NOPENINFO flag set.

cbOem

Width of OEM data packet. If this value is greater than or equal to 0, the OEM data overrides the contents of the PENINFO structure, if present; otherwise, a negative value such as −1 can be used to specify that the system should calculate the size of the OEM data packet.

uScale

Data-scaling metric value. This parameter can be one of the following values:

Constant	Description
PDTS_LOMETRIC	Each logical unit is mapped to 0.1 millimeter. Positive x is to the right; positive y is down.
PDTS_HIMETRIC	Each logical unit is mapped to 0.01 millimeter. Positive x is to the right; positive y is down.
PDTS_HIENGLISH	Each logical unit is mapped to 0.001 inch. Positive x is to the right; positive y is down.
PDTS_ARBITRARY	The application has done its own scaling of the data point.
PDTS_STANDARDSCALE	The standard scaling metric; equivalent to PDTS_HIENGLISH.
gmemFlags

Flag that specifies whether or not the Windows GlobalAlloc function should create a shared memory object when the pen data object is created. This should be either 0 or GMEM_DDESHARE. The GMEM_MOVEABLE and GMEM_ZEROINIT flags are added to this value, and other GMEM_ flags are ignored.

Return Value

Returns a handle to a new and empty pen data object if successful; otherwise, it returns NULL.

Comments

The application provides the PENINFO structure for the header, the real size of any OEM data stored with each coordinate, and the scale of the coordinates.

The uScale parameter specifies scaling values that are also used in the MetricScalePenData function and in the PENDATAHEADER structure member wPndts. The scaling values do not behave in the same way as the Windows scaling units with similar names. For example, a 1-inch line in MM_HIENGLISH will not necessarily be an inch long on the screen because GDI does not know the size of the monitor. However, with PDTS_HIENGLISH in MetricScalePenData, a line drawn an inch long is actually an inch long.

If lppeninfo is NULL, and if there is no tablet on the system (that is, if SendDriverMessage fails), it returns NULL.

The cbOem value must be less than or equal to 12, depending on the size of the OEM data packet. A value of 0 explicitly sets the amount of OEM information to none. A negative value indicates that the size of the OEM data packet is to be calculated by the system. Any existing value for the cbOemData member of PENINFO can be overwritten.

See Also

CreatePenDataEx, DestroyPenData, PDTS_


CreatePenDataEx [New - Windows 95]
 CreatePenDataEx

2.0      [New - Windows 95]

Creates a PENDATA structure with specified OEM data subsets.

HPENDATA CreatePenDataEx( LPPENINFO lppeninfo, UINT uScale, UINT fuOptions, UINT gmemFlags )

Parameters

lppeninfo

Address of tablet information to be inserted into the PENINFO structure in the pen data header. If this parameter is NULL, the current tablet settings are retrieved from the hardware instead. If there is no tablet, the pendata will not have an embedded PENINFO section and the wPndts member in PENDATAHEADER will have the PDTS_NOPENINFO flag set.

uScale

Data-scaling metric value. This parameter can be one of the following values:

Constant	Description
PDTS_LOMETRIC	Each logical unit is mapped to 0.1 millimeter. Positive x is to the right; positive y is down.
PDTS_HIMETRIC	Each logical unit is mapped to 0.01 millimeter. Positive x is to the right; positive y is down.
PDTS_HIENGLISH	Each logical unit is mapped to 0.001 inch. Positive x is to the right; positive y is down.
PDTS_ARBITRARY	The application has done its own scaling of the data point.
PDTS_STANDARDSCALE	The standard scaling metric is equivalent to PDTS_HIENGLISH.
fuOptions

Storage and trim options. If this parameter is 0, no timing, PDK_, or OEM data is stored. If it is CPD_DEFAULT, everything but user data is stored.

Otherwise, this parameter can explicitly specify subsets of OEM and other data. To do so, the parameter should be a combination of one of the CPD_USER values that allocate extra storage and any collection of PHW_ constants. (These values should be combined using the bitwise-OR operator.)

The following table lists the PHW_ values for the fuOptions parameter:

Constant	Description
PHW_PRESSURE	Report pressure in OEM data if available.
PHW_HEIGHT	Report height in OEM data if available.
PHW_ANGLEXY	Report XY-angle in OEM data if available.
PHW_ANGLEZ	Report Z-angle in OEM data if available.
PHW_BARRELROTATION	Report barrel rotation in OEM data if available.
PHW_OEMSPECIFIC	Report OEM-specific value in OEM data if available.
PHW_PDK	Report per-point PDK_ bits in OEM data.
PHW_ALL	Report all available OEM data. This flag is the sum of all other PHW_ flags. The following table lists the CPD_ values for the fuOptions parameter:
CPD_DEFAULT	Store timing, PDK, and all OEM data for each stroke.
CPD_USERBYTE	Set internal flag to add space for one byte of additional storage to be allocated for each stroke. Added space is for application use.
CPD_USERWORD	Set internal flag to add space for one word of additional storage to be allocated for each stroke. Added space is for application use.
CPD_USERDWORD	Set internal flag to add space for one doubleword of additional storage to be allocated for each stroke. Added space is for application use.
CPD_TIME	Maintain absolute time information for each stroke.
gmemFlags

Flag that specifies whether GlobalAlloc should create a shared memory object or not when the pen data object is created. This should be either 0 or GMEM_DDESHARE. The GMEM_MOVEABLE and GMEM_ZEROINIT flags are added to this value, and other GMEM_ flags are ignored.

Return Value

Returns the handle to the HPENDATA object if successful; otherwise, returns NULL.

Comments

CreatePenDataEx is an extension of CreatePenData that allows a more detailed specification of what is stored in each stroke of the pen data.

The fuOptions parameter is typically specified as CPD_DEFAULT to request collection and storage of all information generated by the tablet, including x-y data, absolute stroke timing information, and all available OEM data. The OEM data set that is actually stored in the pen data is the minimum set that satisfies both the request and what is physically available from the tablet (that is, intersection set).

If lppeninfo is NULL, and if there is no tablet on the system (that is, if the SendDriverMessage function fails), the pen data that is created will not have any hardware or OEM information and a default sampling rate of 100Hz will be used. This case is similar to removing PENINFO from the header using TrimPenData with a parameter of TPD_PENINFO.

A value of 0 for fuOptions is used to indicate that only coordinate data is required. While recognition of this type of pen data may suffer, this provides the least complicated type of pen data.

PHW_ bits can be specified to indicate which OEM values or per-point PDK_ pen state information is to be collected. Note that, except for PHW_PDK, which is always valid, this is only a request; if the hardware does not support certain types of OEM data, that data will be absent.

The uScale parameter specifies scaling values that are also used in the MetricScalePenData function and in the PENDATAHEADER structure member wPndts. The scaling values do not behave in the same way as the Windows scaling units with similar names. For example, a 1-inch line in MM_HIENGLISH will not necessarily be an inch long on the screen, because GDI does not know the size of the monitor. However, with PDTS_HIENGLISH in MetricScalePenData, a line drawn an inch long is actually an inch long.

See Also

CreatePenData, DestroyPenData, PDTS_, PDK_


CreatePenDataHRC [New - Windows 95]
 CreatePenDataHRC

2.0      [New - Windows 95]

Returns the handle to the HPENDATA object containing the pen data in the HRC.

HPENDATA CreatePenDataHRC( HRC hrc )

Parameters

hrc

Handle to the HRC object.

Return Value

Returns a handle to the HPENDATA object if successful; otherwise, it returns NULL.

Comments

It is the responsibility of the caller to destroy the HPENDATA object.

A recognizer is not required to use or maintain OEM data; that is, a recognizer can choose to ignore some or all of the OEM data it receives from AddPenDataHRC or AddPenInputHRC. This means that the HPENDATA object the recognizer returns through CreatePenDataHRC may not contain all the OEM data originally provided by the application. Whether or not a recognizer uses the OEM data, it should store all such data it receives and forward it so that subsequent recognizers, if any, can use the data.

See Also

AddPenInputHRC, AddPenDataHRC


CreatePenDataRegion [New - Windows 95]
 CreatePenDataRegion

2.0      [New - Windows 95]

Creates a region that envelops the point data in an HPENDATA object.

HRGN CreatePenDataRegion( HPENDATA hpndt, UINT uType )

Parameters

hpndt

Handle to the HPENDATA object.

uType

Type of region to create. This can be one of the following values:

CPDR_BOX

The bounding box of the pen data ink is converted to a region.

CPDR_LASSO

The pen data describes a lasso that makes up the boundary of the region. If the last point of the pen data does not coincide with the first point, a closed figure is created either by joining the endpoints with a straight line or by using the intersection point of the beginning and ending line segments, whichever is more appropriate. Only the first stroke is used; if the pen data has more than a single stroke, subsequent strokes are ignored.

Return Value

This function returns a handle to a region if successful; otherwise the return value is NULL.

Comments

The coordinates of the region are the same as those used in the pen data. It is the application's responsibility to remove the region when the application is finished with it, using the Windows DeleteObject function.

CreatePenDataRegion enables an application to determine the screen area a gesture such as lasso or cut applies to. For an example of how to use the CreatePenDataRegion function to determine the area of a gesture, see the section "DoDefaultPenInput Messages" in Chapter 2, "Starting Out with System Defaults."


DestroyHRC [New - Windows 95]
 DestroyHRC

2.0      [New - Windows 95]

Destroys an HRC object. A recognizer must export this function.

int DestroyHRC( HRC hrc )

Parameters

hrc

Handle to the HRC object.

Return Value

Returns HRCR_OK if successful; otherwise, returns one of the following negative values:

Constant	Description
HRCR_ERROR	Invalid parameter or other error.
HRCR_MEMERR	Insufficient memory.
Comments

If the HRC contains other objects such as an HPENDATA object, the recognizer must destroy the contained objects as well. After DestroyHRC returns HRCR_OK, the handle hrc is no longer valid. The application should set hrc to NULL to ensure it is not inadvertently used again.

See Also

CreateCompatibleHRC, DestroyHRCRESULT


DestroyHRCRESULT [New - Windows 95]
 DestroyHRCRESULT

2.0      [New - Windows 95]

Destroys an HRCRESULT object. A recognizer must export this function.

int DestroyHRCRESULT( HRCRESULT hrcresult )

Parameters

hrcresult

Handle to the HRCRESULT object to destroy.

Return Value

Returns HRCR_OK if successful; otherwise, returns one of the following negative values:

Constant	Description
HRCR_ERROR	Invalid parameter or other error.
HRCR_MEMERR	Insufficient memory.
Comments

A recognizer must maintain a count of the number of HRCRESULT objects it creates. If an application calls DestroyHRC, the recognizer should not remove the HRC from memory until the application has called DestroyHRCRESULT for all HRCRESULT objects associated with the HRC.

After DestroyHRCRESULT returns HRCR_OK, the handle hrcresult is no longer valid. The application should set hrcresult to NULL to ensure it is not inadvertently used again.

See Also

GetResultsHRC, DestroyHRC


DestroyHWL [New - Windows 95]
 DestroyHWL

2.0      [New - Windows 95]

Destroys a handle to a handwriting-recognition word list.

int DestroyHWL( HWL hwl )

Parameters

hwl

Word list to destroy.

Return Value

Returns HRCR_OK if successful; otherwise, returns one of the following negative values:

Constant	Description
HRCR_ERROR	Invalid parameter or other error.
HRCR_MEMERR	Insufficient memory.
HRCR_UNSUPPORTED	The recognizer does not support this function.
Comments

After DestroyHWL returns HRCR_OK, the handle hwl is no longer valid. The application should set hwl to NULL to ensure it is not inadvertently used again.

See Also

CreateHWL


DestroyInkset [New - Windows 95]
 DestroyInkset

2.0      [New - Windows 95]

Frees memory associated with an inkset.

BOOL DestroyInkset( HINKSET hinkset )

Parameters

hinkset

Handle of an inkset to destroy.

Return Value

Returns TRUE if successful; otherwise FALSE.

Comments

Once memory is freed, the handle hinkset is invalid. The application should set the handle to NULL.

See Also

CreateInkset, INTERVAL


DestroyPenData [New - Windows 95]
 DestroyPenData

1.0     2.0      [New - Windows 95]

Frees the memory associated with a specified pen data memory block.

BOOL DestroyPenData( HPENDATA hpndt )

Parameters

hpndt

Handle to a pen data memory block to destroy.

Return Value

Returns TRUE if the memory was successfully freed; otherwise, FALSE.

Comments

Once the memory block is destroyed, the HPENDATA handle is no longer valid. The application should set the handle to NULL.

See Also

CreatePenData, CreatePenDataEx


DictionarySearch [New - Windows 95]
 DictionarySearch

1.0     2.0      [New - Windows 95]

Performs a dictionary search for a version 1.0 recognizer.

Note  This function is provided only for compatibility with version 1.0 of the Pen API and will not be supported in future versions.

BOOL DictionarySearch( LPRC lprc, LPSYE lpsye, int cSye, LPSYV lpsyv, int csyvMax )

Parameters

lprc

Address of an RC structure.

lpsye

Address of an array of SYE symbol elements that constitute the symbol graph.

cSye

Number of SYE structures in the array.

lpsyv

Output buffer of SYV types. This parameter contains the return results of the dictionary search. A SYV_NULL value is always appended at the end of this buffer. Therefore, this parameter must have enough space for csyvMax + 1 SYV symbol values.

csyvMax

Size of the output buffer.

Return Value

Returns TRUE if any enumeration is found in a dictionary. It returns FALSE if a NULL dictionary was requested or none of the enumerations was found in any dictionary.

Comments

The DictionarySearch function uses the symbol graph pointed to by lpsye, performs a dictionary search based on the options set in lprc, and returns the result as an array of SYV symbol values in the buffer pointed to by lpsyv. The function returns the number of SYV elements copied, limited by the maximum specified in the csyvMax parameter.

DictionarySearch first passes the symbol graph with DIRQ_SYMBOLGRAPH to all the dictionaries in the rglpdf array in the specified RC structure. If none succeeds, the function enumerates the symbol graph in lpsye and searches through all of the dictionary functions for a match. The calling application can get suggestions by setting the RCO_SUGGEST flag in the lRcOptions field in the RC structure. When this flag is set and no enumeration is found in any of the dictionaries in the rglpdf array, DictionarySearch tries to get a suggestion from the dictionaries on the path. DictionarySearch takes the first suggestion offered by any dictionary and returns that as the result of the search. If there are no suggestions, the function returns the best enumeration. The best enumeration is obtained using the FirstSymbolFromGraph function.

If the option RCO_NOSPACEBREAK is set in the lRcOptions field of the specified RC structure, DictionarySearch treats the entire lpsye array as a single symbol graph. If this flag is not set, the function breaks down the input symbol graph into tokens delimited by white space, performs the search sequence on each of them, and assembles the result in the lpsyv array.

This function uses the EnumSymbols function for enumeration and the wTryDictionary member in the RC structure to specify the maximum number of enumerations to search through for each symbol graph token.

See Also

EnumSymbols, FirstSymbolFromGraph, SYE, SYV_, RC


DoDefaultPenInput [New - Windows 95]
 DoDefaultPenInput

2.0      [New - Windows 95]

Initiates default handling of pen input.

int DoDefaultPenInput( HWND hwnd, UINT wEventRef )

Parameters

hwnd

Handle to the window initiating the default processing.

wEventRef

An identifier of a pen event in the input stream, from which input is begun. This identifier is the value returned from the GetMessageExtraInfo function.

Return Value

Returns one of the following values:

Constant	Description
PCMR_OK	Pen collection was successfully started.
PCMR_ALREADYCOLLECTING	StartPenInput has already been called for this session.
PCMR_APPTERMINATED	The application aborted input.
PCMR_ERROR	Illegal parameter or unspecified error.
PCMR_INVALID_PACKETID	Invalid packet identifier.
PCMR_SELECT	Press-and-hold was detected. Collection is not started.
PCMR_TAP	A pen tap was detected. Collection is not started.
Comments

DoDefaultPenInput simplifies the pen input process by including the following capabilities in a single call:

•	Starts pen input by calling StartPenInput

•	Starts inking by calling StartInking

•	Saves the screen background overwritten by the ink

•	Collects the pen input data

•	Stops inking by calling StopInking

•	Stops pen input by calling StopPenInput

•	Targets the pen input data to windows

•	Recognizes results

•	Sends the recognition results to the targets

The default processing proceeds in three phases: initialization, data gathering, and termination. A set of submessages corresponds to each of the three phases.

•	During the initialization phase, the system sends the WM_PENEVENT sub-message PE_SETTARGETS and potentially several PE_GETPCMINFO and PE_GETINKINGINFO messages. After the target or the DefWindowProc function handles these messages and returns a value of PCMR_OK to indicate success, the data-gathering phase begins.

•	During the data-gathering phase, the window specified by the hwnd parameter starts to receive the core pen-input submessages PE_PENDOWN, PE_PENUP, and PE_PENMOVE. The window should let these submessages fall through to DefWindowProc, which translates them into the higher-level messages PE_BEGINDATA and PE_MOREDATA. These are sent to one of the windows specified in the htrgTarget members of the TARGET structures if targeting is in progress; otherwise, the messages are sent to hwnd.

•	The termination phase begins when the pen input terminates. The target window should let the core termination messages PE_TERMINATING and PE_TERMINATED fall through to DefWindowProc. The PE_ENDDATA, PE_RESULT, and PE_ENDINPUT submessages are sent by DefWindowProc while processing PE_TERMINATED.

A return value of LRET_ABORT to any of the WM_PENEVENT submessages aborts the entire process of default input.

See Also

WM_PENEVENT, StartPenInput, StartInking, StopPenInput, StopInking


DPtoTP [New - Windows 95]
 DPtoTP

1.0     2.0      [New - Windows 95]

Converts an array of points in display coordinates to tablet coordinates.

BOOL DPtoTP( LPPOINT lppt, int cPnt )

Parameters

lppt

Address of an array of POINT structures to convert to tablet coordinates. This parameter cannot be NULL.

cPnt

Number of POINT structures to convert.

Return Value

Returns TRUE if the conversion was successful; otherwise, returns FALSE.

Comments

Because of possible rounding errors, the DPtoTP and TPtoDP functions are not guaranteed to be perfect inverses of each other.

The calling application must avoid overflow by passing in points that are within the limits of the current physical display.

See Also

TPtoDP


DrawPenData [New - Windows 95]
 DrawPenData

1.0     2.0      [New - Windows 95]

Displays the pen data in an HPENDATA object as a trail of visible ink.

void DrawPenData( HDC hdc, LPRECT lprect, HPENDATA hpndt )

Parameters

hdc

Handle to a device context. This parameter can also be the handle of a metafile.

lprect

Bounding rectangle of ink, in client coordinates. Can be NULL.

hpndt

Handle to a pen data object.

Return Value

This function does not return a value. If hpndt is NULL, DrawPenData does nothing.

Comments

DrawPenData draws the pen data in the specified device context using the GDI Polyline function. The current settings in the device context rather than the ink characteristics determine how the data is rendered. This means the ink width and color specified in the PENDATAHEADER structure have no effect on how DrawPenData renders the ink. To alter the display characteristics of the ink, an application must call the appropriate Windows GDI functions to set the GDI drawing pen (not to be confused with the real pen).

The application using DrawPenData must either scale the data points or set the mapping appropriately if lprect is NULL.

If lprect is not NULL, the points are scaled into lprect as the drawing is done. Internally, nondestructive calls to the SetViewportExt, SetViewPortOrg, SetWindowOrg, and SetWindowExt functions are used to render the pen data in the device context within the bounds of the provided rectangle. An application must compute the proper pen width (if it is other than 1) before calling this function with a valid lprect parameter to account for the scaling that occurs.

DrawPenData draws the ink in the rectangle relative to the upper-left corner of the window. It ignores any changes that have been made to the origin of the device context by previous calls to the SetWindowOrg or SetViewportOrg functions. If the origin has changed, the rectangle passed to DrawPenData must be offset by the appropriate amount.

If the ink is to be drawn with a width of greater than 1 pixel, the width of the currently selected pen must be set to achieve the desired result. The width must be set in client coordinates if a mapping mode is set in the device context. For example, if the mapping mode has been set to MM_HIENGLISH, the pen width must be set to a number appropriate for the desired width in MM_HIENGLISH units to preserve the proper scale of the ink. This scaling is only an issue when the ink width is greater than 1.

The rendering of the ink data produced by DrawPenData generally does not exactly match the rendering produced by the display driver when the data was first collected. This discrepancy results because DrawPenData and the Polyline function use different algorithms to draw the data. The difference is an occasional "off by one" error that appears as a shifting of some pixels around the edges, depending on the rounding done by Polyline. An application that requires an exact replication of the original ink rendering should call the RedisplayPenData function.

The DrawPenDataEx function allows more control when drawing the contents of pen structures.

See Also

CreatePenData, DrawPenDataEx, DuplicatePenData, RedisplayPenData


DrawPenDataEx [New - Windows 95]
 DrawPenDataEx

2.0      [New - Windows 95]

An enhanced version of DrawPenData. Besides displaying the pen data in an HPENDATA object as a trail of visible ink, DrawPenDataEx can govern the speed at which the data is rendered, a process called animation.

int DrawPenDataEx( HDC hdc, LPRECT lprectVP, HPENDATA hpndt, UINT iStrkFirst, UINT iStrkLast, UINT iPntFirst, UINT iPntLast, ANIMATEPROC lpfnAnimateCB, LPANIMATEINFO lpai, UINT fuFlags )

Parameters

hdc

Handle to a device context.

lprectVP

Viewport rectangle, usually the bounding rectangle of the pen data, in client coordinates. The ink is scaled to fit the specified rectangle. If this parameter is NULL, the bounding rectangle of the ink in hpndt is used, in whatever coordinate system it happens to be in.

hpndt

Handle to a pen data object.

iStrkFirst

Index of the first stroke to display.

iStrkLast

Index of the last stroke to display.

iPntFirst

Index of the first point in the first stroke to display.

iPntLast

Index of the last point in the last stroke to display.

lpfnAnimateCB

Pointer to a callback function instance, or NULL. The callback function is called periodically during drawing, and animation is controlled by values in the structure addressed by the next parameter, lpai, which should not be NULL. If lpfnAnimateCB and the speed in the lpai structure parameters are NULL, the specified pen data is drawn without regard to timing information, and no callback functions are generated. See AnimateProc for a description of the callback function.

lpai

Address of an ANIMATEINFO structure that specifies animation parameters to control how the pen data is drawn. If this parameter is NULL, the function draws the specified pen data without regard to timing information, and no callback functions are generated; otherwise, the caller must initialize the cbSize member to sizeof( ANIMATEINFO ).

fuFlags

This flag can be 0 or one of the following values:

DPD_HDCPEN

Use the GDI pen already selected into the specified device context. If this flag is set, any pen formatting stored in hpndt is ignored and all strokes are drawn with a single width and color. The DrawPenData function uses this flag.

DPD_DRAWSEL

Paint selected strokes in the specified range. A solid pen is used, with a width slightly larger than the stroke width. This flag can be used only for drawing and is ignored for animation. It is incompatible with DPD_HDCPEN.

Return Value

Returns PDR_OK if successful. Attempting to draw an empty HPENDATA (containing no strokes) also returns PDR_OK. Otherwise, returns one of the following:

Constant	Description
PDR_ABORT	Drawing aborted because pen data became invalid after a callback or yield.
PDR_CANCEL	Callback cancel or impasse. An impasse occurs when the user attempts to animate with 0 percent speed (that is, pause),  but the callback interval is on a per-stroke basis.
PDR_COMPRESSED	Pen data is compressed.
PDR_ERROR	Bad animation structure, invalid sampling rate (0 or less) in pen data header, illegal flags, or other error.
PDR_MEMERR	Memory error.
PDR_PNDTERR	Invalid pen data. This value is also returned if the pen data is destroyed or corrupted during drawing or animation. This error can occur if an application is drawing a large pen data object and then destroys the data before drawing is complete.
PDR_PNTINDEXERR	Invalid point index.
PDR_STRKINDEXERR	Invalid stroke index.
PDR_VERSIONERR	Could not convert old pendata.
Comments

DrawPenDataEx is a general-purpose drawing function for rendering pen data objects. The calling application can use the timing information in the strokes to animate the pen data and specify which subset of the pen data should be drawn.

Partial pen data objects can be drawn by specifying first and last strokes and points with iStrkFirst, iStrkLast, iPntFirst, and iPntLast. Set beginning values to 0 and ending values to IX_END to display the entire pen data object. The function fails if any of these values lie outside the ranges available in the pen data. The stroke values must be between 0 and the total number of strokes in the pen data, and the point indices must be between 0 and the number of points in their stroke.

DrawPenDataEx can display only a set of sequential strokes with a single call. To draw nonsequential strokes—say, the second, fifth, and eighth strokes of the pen data—requires multiple calls to DrawPenDataEx.

Ink displayed by DrawPenDataEx differs slightly from the original rendering, as described in the DrawPenData topic. However, DrawPenDataEx can automatically display the ink with its original color and width, saving the application the burden of resetting the current GDI pen characteristics. To draw the ink according to the GDI settings, set fuFlags to DPD_HDCPEN.

If lpfnAnimateCB is not NULL, the specified callback function must return TRUE to continue drawing, or FALSE to terminate drawing.

An application can modify the pen data while it is being rendered, for example, during an animation callback, task switching, or internal yield. However, doing so can make internal pointers or data invalid and result in unpredictable behavior. For this reason, editing the pen data during rendering is not recommended.

See Also

AnimateProc, DrawPenData, RedisplayPenData, DrawPenDataFmt, ANIMATEINFO


DrawPenDataFmt [New - Windows 95]
 DrawPenDataFmt

2.0      [New - Windows 95]

The DrawPenDataFmt macro is used to draw pen data using its stored stroke attributes.

int DrawPenDataFmt( HDC hdc, LPRECT lprectVP, HPENDATA hpndt )

Parameters

hdc

Handle to a device context.

lprectVP

Viewport rectangle, usually the bounding rectangle of the HPENDATA object, in client coordinates. The ink is scaled to fit the specified rectangle. If this parameter is NULL, the bounding rectangle of the ink in hpndt is used, in whatever coordinate system it happens to be in.

hpndt

Handle to an HPENDATA object.

Return Value

Returns PDR_OK if successful. Attempting to draw valid but empty pen data (containing no strokes) also returns PDR_OK. Otherwise, the return value is one of the following:

Constant	Description
PDR_COMPRESSED	Pen data is compressed.
PDR_ERROR	Invalid sampling rate (0 or less) in pen data header, or other error.
PDR_MEMERR	Memory error.
PDR_PNDTERR	Invalid pen data.
PDR_VERSIONERR	Could not convert old pen data.
Comments

The DrawPenDataFmt macro is a wrapper for DrawPenDataEx, providing default values for most of the parameters.

The definition is:

#define DrawPenDataFmt( hdc, lprectVP, hpndt )

DrawPenDataEx( hdc, lprectVP, hpndt, 0, IX_END, 0, IX_END, NULL,

   NULL, 0 );

These default values specify:

•	Full-speed rendering (no animation).

•	Entire data set is drawn (no stroke subsets).

See Also

DrawPenDataEx


DuplicatePenData [New - Windows 95]
 DuplicatePenData

1.0     2.0      [New - Windows 95]

Duplicates an HPENDATA object, allowing an application to generate clones of existing pen data.

HPENDATA DuplicatePenData( HPENDATA hpendata, UINT gmemFlags )

Parameters

hpendata

Pen data to be duplicated.

gmemFlags

Flag that specifies whether or not the Windows GlobalAlloc function should create a shared memory object when the pen data object is created. This should be either 0 or GMEM_DDESHARE. The GMEM_MOVEABLE and GMEM_ZEROINIT flags are added to this value and other GMEM_ flags are ignored.

Return Value

Returns a handle to the duplicated pen data object if successful; otherwise, it returns NULL. It returns NULL if memory is not allocated successfully.

Comments

The DuplicatePenData function duplicates the data specified by the hpendata parameter by creating a second pen data memory block. The application is responsible for destroying this memory block by calling DestroyPenData.

See Also

CreatePenData, DestroyPenData


EmulatePen [New - Windows 95]
 EmulatePen

1.0     2.0      [New - Windows 95]

Emulates a pen in an application that does not use the standard Windows I-beam cursor in text areas.

Note  This function is provided only for compatibility with version 1.0 of the Pen API and will not be supported in future versions. Use DoDefaultPenInput or hedit controls instead.

void EmulatePen( BOOL fPen )

Parameters

fPen

Flag to set pen emulation. TRUE activates pen emulation; FALSE turns it off.

Return Value

This function does not return a value.

Comments

The application must call EmulatePen with fPen set to TRUE whenever the cursor is over a text input window. When the cursor leaves that area, the application must call EmulatePen with fPen set to FALSE.

EmulatePen is useful only for those applications that do not use other Pen API services and do not use the standard Windows I-beam cursor. Windows automatically provides pen-based input in edit controls that use the I-beam cursor, as described in Chapter 1.

See Also

DoDefaultPenInput


EnableGestureSetHRC [New - Windows 95]
 EnableGestureSetHRC

2.0      [New - Windows 95]

Enables or disables recognition of specific gestures or collections of gestures in an HRC object.

int EnableGestureSetHRC( HRC hrc, SYV syv, BOOL fEnable )

Parameters

hrc

Handle to the HRC object.

syv

Either a gesture SYV_ symbol value, such as SYV_COPY, or one or more of the following GST_ constants combined using the bitwise-OR operator. Note that individual SYV_ gesture symbol values cannot be combined with GST_ constants.

Constant	Description
GST_SEL	Selection and lasso.
GST_CLIP	Cut, copy, paste.
GST_WHITE	Space, tab, return.
GST_EDIT	Insert, correct, undo.
GST_CIRCLELO	Lowercase circle gestures.
GST_CIRCLEUP	Uppercase circle gestures.
GST_CIRCLE	All circle gestures.
GST_ALL	All gestures.
fEnable

Enable recognition flag. This flag must be set to TRUE to enable recognition of the gesture or gestures in syv, or to FALSE to disable recognition of the specified gestures.

Return Value

Returns HRCR_OK if successful; otherwise, returns one of the following negative values:

Constant	Description
HRCR_ERROR	Invalid parameter or other error.
HRCR_MEMERR	Insufficient memory.
HRCR_UNSUPPORTED	The recognizer does not support this function.
Comments

The results of EnableGestureSetHRC are cumulative. The function can be called several times in succession to refine the precise gesture set required. However, calling EnableGestureSetHRC with syv set to GST_ALL and fEnable set to FALSE disables all gestures.

By default, a recognition context HRC enables all gestures that its associated recognizer supports.

Example

The following example enables selection, Clipboard functions, and SYV_CIRCLEUPA:

EnableGestureSetHRC( hrc, GST_ALL, FALSE );	    // Disable all

EnableGestureSetHRC( hrc, GST_SEL | GST_CLIP, TRUE ); // Enable sets

EnableGestureSetHRC( hrc, SYV_CIRCLEUPA, TRUE );	    // Enable circle A

See Also

SetAlphabetHRC, SYV_


EnableSystemDictionaryHRC [New - Windows 95]
 EnableSystemDictionaryHRC

2.0      [New - Windows 95]

Enables or disables a recognizer's dictionary.

int EnableSystemDictionaryHRC( HRC hrc, BOOL fEnable )

Parameters

hrc

Handle to the HRC object for the recognizer.

fEnable

Enable recognition flag. This flag must be set to TRUE to enable use of the dictionary, or FALSE to disable its use.

Return Value

Returns HRCR_OK if successful; otherwise, returns one of the following negative values:

Constant	Description
HRCR_ERROR	Invalid parameter, no system dictionary, or other error.
HRCR_MEMERR	Insufficient memory.
HRCR_UNSUPPORTED	The recognizer does not support this function.
Comments

The enable state of the system dictionary does not affect any word lists that may be set into the HRC object.

See Also

SetWordlistHRC


EndEnumStrokes [New - Windows 95]
 EndEnumStrokes

1.0     2.0      [New - Windows 95]

Unlocks an HPENDATA memory block previously locked with the function BeginEnumStrokes.

Note  This function is provided only for compatibility with version 1.0 of the Pen API, and will not be supported in future versions.

LPPENDATA EndEnumStrokes( HPENDATA hpndt )

Parameters

hpndt

Handle to the locked HPENDATA memory block.

Return Value

Returns NULL if the function is successful; otherwise, the return value is nonzero.

Comments

EndEnumStrokes internally calls the Windows GlobalUnlock function to unlock the memory block specified by hpndt. Calling EndEnumStrokes invalidates any pointers previously returned by the GetPenDataStroke function.

See Also

BeginEnumStrokes, GetPenDataStroke


EndPenInputHRC [New - Windows 95]
 EndPenInputHRC

2.0      [New - Windows 95]

Informs a recognizer that pen data input has been terminated. A recognizer must export this function.

int EndPenInputHRC( HRC hrc )

Parameters

hrc

Handle to the HRC object for the recognizer.

Return Value

Returns HRCR_OK if successful; otherwise, returns one of the following negative values:

Constant	Description
HRCR_MEMERR	Insufficient memory.
HRCR_ERROR	Invalid parameter or other error.
Comments

EndPenInputHRC does not instruct the recognizer to complete recognition; an application must call ProcessHRC to do that. However, an application that does not use DoDefaultPenInput must call EndPenInputHRC when it detects that input has finished. (DoDefaultPenInput calls EndPenInputHRC internally.)

The recognizer can terminate open-ended states and reduce ambiguity in searches when it knows that no more ink will arrive. For example, the recognizer can keep various options open for possible delayed strokes that can modify a character. EndPenInputHRC tells the recognizer that no more delayed strokes will arrive.

After calling EndPenInputHRC for an HRC, an application should cease adding pen input into the HRC. Some recognizers, such as the Microsoft Handwriting Recognizer (GRECO.DLL), do not accept late pen input. If the application calls AddPenInputHRC after having called EndPenInputHRC for the same HRC, the Microsoft Handwriting Recognizer returns HRCR_ERROR.

Other recognizers may differ. With such recognizers, a client may continue to add pen input without error into a recognition context, even after having called EndPenInputHRC. However, doing so is not efficient. In the worst case, the recognizer may be forced to reprocess all of the pen data from the beginning.

For an example of a normal termination sequence, see the code sample in GetSymbolsHRCRESULT.

See Also

ProcessHRC, DoDefaultPenInput


EnumSymbols [New - Windows 95]
 EnumSymbols

1.0     2.0      [New - Windows 95]

Enumerates strings in a symbol graph in order of most probable to least probable.

UINT EnumSymbols( LPSYG lpsyg, UINT cstrMax, ENUMPROC lpEnumFunc, LPVOID lvData )

Parameters

lpsyg

Address of the symbol graph SYG.

cstrMax

Maximum number of strings to enumerate.

lpEnumFunc

Address of enumeration function.

lvData

Application-specific data.

Return Value

Returns the number of strings enumerated.

Comments

The EnumSymbols function enumerates all symbol strings (to a maximum defined by cstrMax) contained in the symbol graph that lpsyg points to. The lpEnumFunc parameter points to the enumeration function called with each enumeration.

To generate all the symbols from a symbol graph, set cstrMax equal to the value retrieved by passing lpsyg to GetSymbolCount.

See Also

EnumSymbolsCallback, FirstSymbolFromGraph, SYG, SYV_


EnumSymbolsCallback [New - Windows 95]
 EnumSymbolsCallback

1.0     2.0      [New - Windows 95]

EnumSymbolsCallback is a callback function pointed to by the lpEnumFunc parameter of EnumSymbols. The callback function can have any name. The function's name must appear in the EXPORT section of the application's module definition file.

int CALLBACK EnumSymbolsCallback( LPSYV lpsyv, int csyv, FAR void * lvData )

Parameters

lpsyv

Symbol string.

csyv

Count of symbols in string.

lvData

Address of application-specific data from EnumSymbols.

Return Value

Returns TRUE to continue enumeration, or FALSE to stop enumeration.

See Also

EnumSymbols, SYV_


ExtractPenDataPoints [New - Windows 95]
 ExtractPenDataPoints

2.0      [New - Windows 95]

Extracts points from a specified stroke in an HPENDATA object.

int ExtractPenDataPoints( HPENDATA hpndt, UINT iStrk, UINT iPnt, UINT cPnts, LPPOINT lppt, LPVOID lpvOem, UINT fuOption )

Parameters

hpndt

Handle to an HPENDATA object.

iStrk

Zero-based index of the stroke to remove points from.

iPnt

Zero-based index to the first point to remove.

cPnts

Count of points to remove. If this value is greater than the number of points after iPnt, all the points from iPnt to the last point of the stroke are removed. ExtractPenDataPoints fails if iPnt is greater then the number of points in the stroke.

lppt

Array of POINT structures that receives the extracted points. This must be large enough to hold cPnts points.

lpvOem

Buffer to put extracted OEM data if it exists, or NULL. This must be large enough to hold cPnts OEM packets.

fuOption

Flags. This value can be EPDP_REMOVE to remove the points from the stroke in the pen data object.

Return Value

Returns PDR_OK if successful; otherwise, the return value can be one of the following negative values:

Constant	Description
PDR_COMPRESSED	Pen data is compressed.
PDR_ERROR	Parameter or other unspecified error.
PDR_MEMERR	Out of memory.
PDR_STRKINDEXERR	Invalid stroke index.
PDR_PNTINDEXERR	Invalid point index.
PDR_VERSIONERR	Could not convert old pen data object.
Comments

ExtractPenDataPoints extracts points (and OEM data, if any) from a specified stroke of the pen data object specified by hpndt. It copies the extracted points and the OEM data to the buffers pointed to by lppt and lpvOem.

Use ExtractPenDataStrokes to extract strokes from the pen data object or RemovePenDataStrokes to remove strokes from the pen data object.

See Also

InsertPenDataPoints, InsertPenDataStroke, RemovePenDataStrokes


ExtractPenDataStrokes [New - Windows 95]
 ExtractPenDataStrokes

2.0      [New - Windows 95]

Creates a new HPENDATA object that is a subset of an existing object.

int ExtractPenDataStrokes( HPENDATA hpndt, UINT fuExtract, LPARAM lParam, LPHPENDATA lphpndtNew, UINT gmemFlags )

Parameters

hpndt

Handle to an existing pen data object.

fuExtract

Extraction options and modifiers. This value can be a combination of one of the principal EPDS_ options, with an optional comparison modifier, if appropriate, and the optional EPDS_REMOVE modifier. The flags should be combined using the bitwise-OR operator.

The following table gives the principal options. These options specify what the new pen data object will be based on.

Constant	Description
EPDS_INKSET	Based on a handle to an inkset. The EPDS_GT, EPDS_GTE, EPDS_LT, and EPDS_LTE comparison operators are ignored, because extraction is based on matching the inkset. (However, EPDS_NOT creates a pen data set with all stroke/inkset intersections that do not match the provided inkset.)
EPDS_PENTIP	Based on complete pen-tip characteristics.
EPDS_SELECT	Based on selected strokes.
EPDS_STROKEINDEX	Based on index.
EPDS_TIPCOLOR	Based on pen-tip color.
EPDS_TIPWIDTH	Based on pen-tip width.
EPDS_TIPNIB	Based on pen tip nib style.
EPDS_USER	Based on user-specific value. The following table gives the optional comparison modifiers and the optional removal modifier:
EPDS_LT	Less than comparison: extract all strokes with attribute less than the value specified in lParam.
EPDS_LTE	Less than or equal comparison: extract all strokes with attributes less than or equal to the value specified in lParam.
EPDS_GT	Greater than comparison: extract all strokes with attributes greater than the value specified in lParam.
EPDS_GTE	Greater than or equal comparison: extract all strokes with attributes greater than or equal to the value specified in lParam.
Constant	Description
EPDS_NOT	Negative comparison (alias EPDS_NE): extract all strokes with attributes not equal to the value specified by lParam. If combined with other EPDS_ constants, reverses the constant meaning (for example, EPDS_NE | EPDS_LT | EPDS_GT means not less than or not greater than). If lParam is EPDS_SELECT, EPDS_NOT means extract all unselected strokes.
EPDS_REMOVE	Remove matching strokes from source. If this flag is added, any strokes matching the criteria for extraction are removed from the source pen data.
lParam

Meaning is dependent on the value of the fuExtract parameter, as follows:

Constant	Description
EPDS_INKSET	lParam is a handle to an inkset.
EPDS_PENTIP	lParam is a pointer to a PENTIP structure to compare. Only equal or not-equal matches are supported. EPDS_LT, for example, is ignored.
EPDS_SELECT	lParam is not used and should be set to 0.
EPDS_STROKEINDEX	lParam is a zero-based stroke index to compare.
EPDS_TIPCOLOR	lParam is a pen tip color to compare.
EPDS_TIPNIB	lParam is a pen tip nib style to compare. Only equal or not-equal matches are supported.
EPDS_TIPWIDTH	lParam is a pen tip width to compare.
EPDS_USER	lParam is a user-specific value to compare, cast to a double-word value.
lphpndtNew

Address of a pen data handle if one is to be created; otherwise, NULL.

gmemFlags

Flag that specifies whether or not the Windows GlobalAlloc function should create a shared memory object when the pen data object is created. This should be either 0 or GMEM_DDESHARE. The GMEM_MOVEABLE and GMEM_ZEROINIT flags are added to this value, and other GMEM_ flags are ignored.

Return Value

Returns the number of strokes that match the comparison criteria if successful, or a negative error value. (The return value can be 0. The maximum is the largest integer value.)  The error value can be one of the following:

Constant	Description
PDR_COMPRESSED	Pen data is compressed.
PDR_ERROR	Parameter or other unspecified error.
PDR_INKSETERR	Invalid inkset and EPDS_INKSET specified.
PDR_MEMERR	Memory error.
PDR_NA	Option not available.
PDR_PNDTERR	Invalid pendata.
PDR_STRKINDEXERR	Invalid stroke index.
PDR_USERDATAERR	EPDS_USER was specified but there is no per-stroke user data.
PDR_VERSIONERR	Could not convert old pendata.
Comments

ExtractPenDataStrokes extracts strokes from an existing pen data object, optionally creating a new pen data object made up of the extracted strokes. The extraction can be a copy or move process; that is, the source pen data object can remain the same or contain only the remaining strokes not moved to the new structure. Modifier flags in fuExtract specify how the value in lParam compares with attributes of the pen data strokes (equal by default, greater than, less than, or none of these three).

If lphpndtNew is NULL, no pen data object is created. This is useful for modifying the original pen data object hpndt (when EPDS_REMOVE specified), or simply for determining a return value without modifying or creating a pen data object. If lphpndtNew is not NULL, the flags specified by gmemFlags are passed to the GlobalAlloc function when memory for the pen data memory block is created.

If EPDS_REMOVE is specified, any strokes with an attribute matching the comparison criteria are removed from the source pen data object, regardless of whether a new pen data is created. In the case of inksets, this may actually generate more strokes if there are multiple intersections with the inkset within any one stroke.

Example

To create an HPENDATA object consisting only of selected strokes:

ExtractPenDataStrokes( hpndt, EPDS_SELECT, 0, &hpndtDst, 0 );

To return the count of selected strokes:

ExtractPenDataStrokes( hpndt, EPDS_SELECT, 0, NULL, 0 );

To delete all but the selected strokes from the source:

ExtractPenDataStrokes( hpndt, EPDS_NOT | EPDS_SELECT | EPDS_REMOVE,

   0, NULL, 0 );

To copy strokes 0 through 10 inclusive to a new HPENDATA object:

ExtractPenDataStrokes( hpndt, EPDS_LTE | EPDS_STROKE, 10,

   &hpndtDst, 0 );

To move all but blue strokes to a separate HPENDATA object:

ExtractPenDataStrokes( hpndt, EPDS_NOT | EPDS_TIPCOLOR | EPDS_REMOVE,

   RGB_BLUE, &hpndtDst, 0 );

See Also

DuplicatePenData


FirstSymbolFromGraph [New - Windows 95]
 FirstSymbolFromGraph

1.0     2.0      [New - Windows 95]

Retrieves an array of symbols that is the most likely interpretation of a specified symbol graph SYG.

void FirstSymbolFromGraph( LPSYG lpsyg, LPSYV lpsyv, int cSyvMax, LPINT lpcSyv )

Parameters

lpsyg

Address of the symbol graph.

lpsyv

Address of an empty array of SYV_ symbol values. FirstSymbolFromGraph fills this array with the likeliest interpretation from the graph.

cSyvMax

Size of the array that lpsyv points to.

lpcSyv

Number of symbols returned in lpsyv. This value is 0 if lpsyg is empty. It is −1 if the buffer is not large enough to hold the results.

Return Value

This function does not return a value.

Comments

The array of symbols is identical to the first string returned to the EnumSymbolsCallback callback function of EnumSymbols.

See Also

EnumSymbols, SYG, SYV_


GetAlphabetHRC [New - Windows 95]
 GetAlphabetHRC

2.0      [New - Windows 95]

Retrieves the alphabet being used in a handwriting recognition context HRC.

int GetAlphabetHRC( HRC hrc, LPALC lpalc, LPBYTE rgbfAlc )

Parameters

hrc

Handle to the HRC object.

lpalc

Address of a buffer that receives the current ALC_ values. If NULL, this parameter is ignored.

rgbfAlc

Address of an array of bits or NULL. If NULL, this parameter is ignored. If lpalc contains ALC_USEBITMAP and rgbfAlc points to a valid array, the array is filled according to the bits set by the SetAlphabetHRC function.

Return Value

Returns HRCR_OK if successful; otherwise, returns one of the following negative values:

Constant	Description
HRCR_ERROR	Invalid parameter or other error.
HRCR_MEMERR	Insufficient memory.
HRCR_UNSUPPORTED	The recognizer does not support this function.
Comments

If rgbfAlc is not NULL, the array it points to must be large enough to accommodate 256 bits (32 bytes). If the nth bit is set, the nth ANSI character is recognizable. Bits representing characters with ASCII values less than 32 (the space character) currently have no meaning.

ALC_DEFAULT specifies the set of characters at or above ALC_SYSMINIMUM that the recognizer can accurately distinguish.

For a description of alphabets and their relationship to a recognizer, see "Configuring the HRC" in Chapter 5, "The Recognition Process."

See Also

EnableGestureSetHRC, SetAlphabetHRC, GetAlphabetPriorityHRC, ALC_


GetAlphabetPriorityHRC [New - Windows 95]
 GetAlphabetPriorityHRC

2.0      [New - Windows 95]

Retrieves the alphabet priority used in a handwriting recognition context HRC.

int GetAlphabetPriorityHRC( HRC hrc, LPALC lpalc, LPBYTE rgbfalc )

Parameters

hrc

Handle to the HRC object.

lpalc

Address of an ALC type that will be filled with the current ALC_ priority values.

rgbfalc

Address of a 256-bit (32-byte) buffer whose bits map to ANSI single-byte characters, or NULL if this information is not required.

Return Value

Returns HRCR_OK if successful; otherwise, returns one of the following negative values:

Constant	Description
HRCR_ERROR	Invalid parameter or other error.
HRCR_MEMERR	Insufficient memory.
HRCR_UNSUPPORTED	The recognizer does not support this function.
For a description of how a recognizer uses alphabet priority, see "Configuring the HRC" in Chapter 5, "The Recognition Process."

See Also

GetAlphabetHRC, SetAlphabetPriorityHRC, ALC_


GetAlternateWordsHRCRESULT [New - Windows 95]
 GetAlternateWordsHRCRESULT

2.0      [New - Windows 95]

Returns alternative word interpretations of a previous result. (Not supported in Japanese version.)

int GetAlternateWordsHRCRESULT( HRCRESULT hrcresult, UINT iSyv, UINT cSyv, LPHRCRESULT rghrcresults, UINT cResults )

Parameters

hrcresult

Handle of a results object.

iSyv

Index of the first of a span of symbols within the results object.

cSyv

The number of symbols in the original result, starting at iSyv, for which alternative words are required.

rghrcresults

Address of a result array. This address cannot be NULL.

cResults

The size of the rghrcresults array in results. This parameter must be greater than 0.

Return Value

Returns the number of results actually provided, if successful. This can be less than the space allocated in rghrcresults, and may be 0; otherwise, returns one of the following negative values:

Constant	Description
HRCR_ERROR	Invalid parameter or other error.
HRCR_MEMERR	Insufficient memory.
HRCR_UNSUPPORTED	The recognizer does not support this function.
Comments

GetAlternateWordsHRCRESULT provides alternative word interpretations of a previous result. The alternatives returned are strongly coerced to words in the recognizer's dictionary, if enabled, and the word list, if any, of the HRC that processed the results.

The span of symbols defined by iSyv and cSyv need not fall on word boundaries. However, the recognizer returns only a single word per result. It is the application's responsibility to ensure that embedding a full word within other symbols makes sense. (The application can also choose to let the user make that decision.) For example, finding alternatives for "polce" in the phrase "pig-in-a-polce" could legitimately return "poke" as an alternative, but alternatives for "kef" in "markefplace" would probably be meaningless.

See Also

GetResultsHRC


GetBoxMappingHRCRESULT [New - Windows 95]
 GetBoxMappingHRCRESULT

2.0      [New - Windows 95]

Returns the box indices for a range of symbols.

int GetBoxMappingHRCRESULT( HRCRESULT hrcresult, UINT iSyv, UINT cSyv, UINT FAR * rgi )

Parameters

hrcresult

Handle of a results object.

iSyv

Index of the first symbol of interest in the results object.

cSyv

The number of symbols following iSyv for which box indices are required. Note that the array rgi must be large enough to accommodate this many items of size UINT. A value of 0 is allowed, in which case the function simply returns 0.

rgi

Address of an index array. The array must be large enough to store cSyv indices. This address cannot be NULL.

Return Value

Returns the number of indices actually retrieved, if successful. This can be less than the space allocated in rgi if iSyv indexes an element near the end of the results array, and is 0 if iSyv indexes a nonexistent element; otherwise, returns one of the following negative values:

Constant	Description
HRCR_ERROR	Invalid parameter or other error.
HRCR_MEMERR	Insufficient memory.
HRCR_UNSUPPORTED	The recognizer does not support this function.
Comments

GetBoxMappingHRCRESULT is typically used with boxed input established by SetGuideHRC. If no guide structure has been set, the recognizer will return HRCR_ERROR.

It is possible to allocate a small buffer in rgi and call GetBoxMappingHRCRESULT repeatedly, incrementing the index iSyv each time by the number of indices returned in the previous call until GetBoxMappingHRCRESULT returns 0.

See Also

GetResultsHRC, SetGuideHRC


GetBoxResultsHRC [New - Windows 95]
 GetBoxResultsHRC

2.0      [New - Windows 95]

Encapsulates recognizer functionality for boxed input.

int GetBoxResultsHRC( HRC hrc, UINT cAlt, UINT iSyv, UINT cBoxRes, LPBOXRESULTS rgBoxResults, BOOL fGetInkset )

Parameters

hrc

Handle to the HRC object used for the boxed input.

cAlt

Count of alternatives expected in the BOXRESULTS structure. If this parameter is 0, the function returns 0.

iSyv

Index to the starting symbol.

cBoxRes

The count of BOXRESULTS structures that the rgBoxResults array can hold. This parameter must be greater than 0.

rgBoxResults

Address of an array of BOXRESULTS structures.

fGetInkset

Flag to request inksets for each result if TRUE. If FALSE, the recognizer provides no inksets.

Return Value

Returns the count of BOXRESULTS elements returned in the rgBoxResults structure, if successful; otherwise, returns one of the following negative values:

Constant	Description
HRCR_ERROR	Invalid parameter or other error.
HRCR_INVALIDGUIDE	The guide structure is invalid.
HRCR_MEMERR	Insufficient memory.
HRCR_HOOKED	A hook preempted the result.
HRCR_UNSUPPORTED	The recognizer does not support this function.
Comments

GetBoxResultsHRC simplifies the task of boxed recognition by providing character alternatives on a per-box basis in one call.

If fGetInkset is TRUE, the recognizer assigns a valid inkset handle to the hinksetBox member of the BOXRESULTS structure addressed by rgBoxResults. It is the application's responsibility to destroy these inksets with DestroyInkset.

Example

The following code sample gets results for 10 boxes at a time, with five alternatives per box:

HANDLE hMem = GlobalAlloc( GHND, 10 * (sizeof( BOXRESULTS )

 + (5-1) * sizeof( SYV )) );

LPBOXRESULTS rgBoxR = (LPBOXRESULTS)GlobalLock( hMem );

UINT indx = 0;

do

{

   int cRes = GetBoxResultsHRC( hrc, 5, indx, 10, rgBoxR, FALSE );

   .

   .	// Check for errors and use rgBoxR

   .

   indx += (UINT)cRes;

}

while (cRes == 10);

See Also

GetBoxMappingHRCRESULT, GetResultsHRC, DestroyInkset


GetGlobalRC [New - Windows 95]
 GetGlobalRC

1.0     2.0      [New - Windows 95]

Queries the current default settings and fills an RC structure with the global values. In version 2.0 of the Pen API, RC is made obsolete by the HRC object.

Note  This function is provided only for compatibility with version 1.0 of the Pen API and will not be supported in future versions.

UINT GetGlobalRC( LPRC lprc, LPSTR lpszDefRecog, LPSTR lpszDefDict, int cbDefDictMax )

Parameters

lprc

Address of an RC structure. This parameter can be NULL.

lpszDefRecog

Address of a character string in which the default recognizer module name is returned. This must be at least 128 bytes long. This parameter can be NULL.

lpszDefDict

Buffer in which the default dictionary path is returned. This path ends with two null characters. This parameter can be NULL.

cbDefDictMax

Size of lpszDefDict buffer to be filled.

Return Value

Returns GGRC_OK if successful; otherwise, the return value may be one of the following values:

Constant	Description
GGRC_PARAMERROR	One or more invalid parameters were detected. The call to GetGlobalRC has no effect.
GGRC_DICTBUFTOOSMALL	The size of the lpszDefDict buffer is not large enough to contain the entire dictionary path. The buffer is filled with as many complete dictionary module names as allowed by the size. The list is terminated by a null string.
Comments

GetGlobalRC fills the RC structure with global values. Values that have no default settings—for example, the bounding rectangle—are set to 0.

An application does not need to call this function to use the default values. When an application initializes an RC structure using InitRC, the system default values are set as the values for the structure members. This function returns the actual current values for RC members. The InitRC function returns the default values, which include placeholder values for some RC members.

See Also

InitRC,  SetGlobalRC,  RC


GetGuideHRC [New - Windows 95]
 GetGuideHRC

2.0      [New - Windows 95]

Retrieves the guide structure being used in a recognition context HRC.

int GetGuideHRC( HRC hrc, LPGUIDE lpguide, UINT FAR * lpnFirstVisible )

Parameters

hrc

Handle to the HRC object.

lpguide

Address of a GUIDE structure; all coordinates are in screen coordinates. This parameter cannot be NULL.

lpnFirstVisible

Pointer to first visible character or line, or NULL. For boxed controls, this is the first visible box (leftmost and topmost for left-right, top-down languages like English). For other controls, this is the first visible character position (left-most for English) in a single-line control, and the first visible line (topmost for English) in multiline controls.

If set to NULL, lpnFirstVisible is ignored.

Return Value

Returns HRCR_OK if successful; otherwise, returns one of the following negative values:

Constant	Description
HRCR_ERROR	Invalid parameter or other error.
HRCR_MEMERR	Insufficient memory.
HRCR_UNSUPPORTED	The recognizer does not support this function.
See Also

GUIDE, SetGuideHRC


GetHotspotsHRCRESULT [New - Windows 95]
 GetHotspotsHRCRESULT

2.0      [New - Windows 95]

Retrieves the hot spots for a particular symbol.

int GetHotspotsHRCRESULT( HRCRESULT hrcresult, UINT iSyv, LPPOINT lppt, UINT cPnts )

Parameters

hrcresult

Handle of a results object.

iSyv

Index of the symbol in the results object.

lppt

Address of an array of up to MAXHOTSPOT POINT structures.

cPnts

Actual size of lppt array in points.

Return Value

If successful, returns the count of hot spots; otherwise, returns one of the following negative values:

Constant	Description
HRCR_ERROR	Invalid parameter or other error.
HRCR_MEMERR	Insufficient memory.
HRCR_UNSUPPORTED	The recognizer does not support this function.
Comments

Any symbol can have hot spots, but they are usually of interest only for gestures. For example, if the user writes "X" for deletion, the center of the "X"—its hotspot —points to the item to be deleted. Hot spots are returned in tablet coordinates. The maximum number of hot spots allowed is provided in the PENWIN.H constant MAXHOTSPOT. The Microsoft Handwriting Recognizer (GRECO.DLL), supports this function for gesture symbols only.

If cPnts is smaller than the actual number of hot spots, only cPnts points are reported.


GetHRECFromHRC [New - Windows 95]
 GetHRECFromHRC

2.0      [New - Windows 95]

Retrieves a handle to the recognizer bound to an HRC object. A recognizer must export this function.

HREC GetHRECFromHRC( HRC hrc )

Parameters

hrc

Handle to the HRC object.

Return Value

If successful, returns the handle to the recognizer used for the HRC object; otherwise, returns NULL.

See Also

CreateCompatibleHRC, InstallRecognizer


GetInksetInterval [New - Windows 95]
 GetInksetInterval

2.0      [New - Windows 95]

Retrieves an interval from an inkset.

int GetInksetInterval( HINKSET hinkset, UINT uIndex, LPINTERVAL lpi )

Parameters

hinkset

Handle to an inkset.

uIndex

Zero-based index of an interval or IX_END.

lpi

Pointer to an INTERVAL structure. This can be NULL if the user merely wishes to find out how many intervals are in the inkset.

Return Value

GetInksetInterval returns the number of intervals in the inkset if successful; otherwise, the return value can be one of the following negative values:

Constant	Description
ISR_ERROR	The inkset handle is bad, or a parameter error.
ISR_BADINDEX	The interval index is bad.
ISR_BADINKSET	The inkset has been corrupted or contains bad intervals.
Comments

An application can use GetInksetInterval to enumerate all the intervals in an inkset.

See Also

GetInksetIntervalCount, INTERVAL


GetInksetIntervalCount [New - Windows 95]
 GetInksetIntervalCount

2.0      [New - Windows 95]

Returns the number of intervals in an inkset.

int GetInksetIntervalCount( HINKSET hinkset )

Parameters

hinkset

Handle to an inkset.

Return Value

Returns the number of intervals in the inkset is successful; otherwise, the return value can be one of the following negative values:

Constant	Description
ISR_ERROR	The inkset handle is bad, or a parameter error.
ISR_BADINKSET	The inkset has been corrupted or contains bad intervals.
Comments

An application uses GetInksetIntervalCount to determine how many intervals there are to enumerate in an inkset. This function can also be used to verify that an inkset is valid.

See Also

GetInksetInterval


GetInternationalHRC [New - Windows 95]
 GetInternationalHRC

2.0      [New - Windows 95]

Retrieves the country, language, script direction, and international preferences from a recognition context HRC object.

int GetInternationalHRC( HRC hrc, UINT FAR * lpuCountry, LPSTR lpszLangCode, UINT FAR * lpfuFlags, UINT FAR * lpuDir )

Parameters

hrc

Handle to the HRC object.

lpuCountry

The country code, or NULL to ignore this value.

lpszLangCode

A buffer large enough to receive a three-letter string (that is, 4 bytes) identifying the language ("enu", "fra", etc.). If set to NULL, lpszLangCode is ignored.

lpfuFlags

A pointer to a flags value or NULL to ignore this value. If GetInternationalHRC returns SIH_ALLANSICHAR in lpfuFlags, it means that the user intends to use the entire ANSI character set. If this is the case, the application should ignore the value returned in lpszLangCode, since all the ANSI-based languages are undifferentiated.

lpuDir

Address of a value for the script direction, or NULL to ignore this value. This value specifies which primary and secondary writing directions are in use. Possible values are:

Constant	Description
SSH_RD	To right and down (English).
SSH_RU	To right and up.
SSH_LD	To left and down (Hebrew).
SSH_LU	To left and up.
SSH_DL	Down and to the left (Chinese).
SSH_DR	Down and to the right (Chinese).
SSH_UL	Up and to the left.
SSH_UR	Up and to the right.
Return Value

Returns HRCR_OK if successful; otherwise, returns one of the following negative values:

Constant	Description
HRCR_ERROR	Invalid parameter or other error.
HRCR_MEMERR	Insufficient memory.
HRCR_UNSUPPORTED	The recognizer does not support this function.
See Also

SetInternationalHRC


GetMaxResultsHRC [New - Windows 95]
 GetMaxResultsHRC

2.0      [New - Windows 95]

Gets the maximum number of recognition results that a recognizer can generate in the current handwriting recognition context HRC object.

int GetMaxResultsHRC( HRC hrc )

Parameters

hrc

Handle to the HRC object.

Return Value

If successful, returns the maximum number of recognition results as a positive number; otherwise, returns one of the following negative values:

Constant	Description
HRCR_ERROR	Invalid parameter or other error.
HRCR_MEMERR	Insufficient memory.
Comments

The default maximum number of results a recognizer can return is 1. An application must call SetMaxResultsHRC to set a different maximum value.

See Also

SetMaxResultsHRC


GetPenAppFlags [New - Windows 95]
 GetPenAppFlags

2.0      [New - Windows 95]

GetPenAppFlags returns task pen flags cached by RegisterPenApp.

UINT GetPenAppFlags(  )

Return Value

GetPenAppFlags returns the flags set by RegisterPenApp for the current task. It extends and replaces the functionality of the version 1.0 function IsPenAware, which will not be supported in future versions of the Pen API.

Applications written specifically for Windows 95 and later versions automatically get RPA_DEFAULT so that any edit controls created by such applications automatically become pen-aware.

If the registration cache has been destroyed (which indicates PENWIN.DLL has been unloaded), this function returns 0.

See Also

RegisterPenApp, IsPenAware


GetPenAsyncState [New - Windows 95]
 GetPenAsyncState

1.0     2.0      [New - Windows 95]

Gets the state of the pen barrel button.

BOOL GetPenAsyncState( UINT wPDK )

Parameters

wPDK

One of the PDK_ values for the barrel buttons. The following table lists the PDK_ values that GetPenAsyncState can query for:

Constant	Description
PDK_BARREL1	Get state of barrel button 1.
PDK_BARREL2	Get state of barrel button 2.
PDK_BARREL3	Get state of barrel button 3.
Return Value

Returns TRUE if the specified barrel button state is currently down; otherwise, the return value is FALSE.


GetPenDataAttributes [New - Windows 95]
 GetPenDataAttributes

2.0      [New - Windows 95]

Retrieves information about an HPENDATA object.

int GetPenDataAttributes( HPENDATA hpndt, LPVOID lpvBuffer, UINT uOption )

Parameters

hpndt

Handle to the HPENDATA object.

lpvBuffer

Pointer to a structure whose type depends on uOption, or NULL if the uOption parameter does not require this buffer.

uOption

Specifies the attributes to retrieve. This parameter can be one of the following:

Constant	Description
GPA_MAXLEN	Retrieves the length (in points) of the longest stroke. lpvBuffer is unused and ignored.
GPA_POINTS	Retrieves the total number of points. lpvBuffer is unused and ignored.
GPA_PDTS	Retrieves the PDTS_ bits. lpvBuffer is unused and ignored.
GPA_RATE	Retrieves the sampling rate in samples per second. lpvBuffer is unused and ignored.
GPA_RECTBOUND	Retrieves the bounding rectangle of all pen-down points. lpvBuffer is the address of a RECT structure.
GPA_RECTBOUNDINK	Like GPA_RECTBOUND, retrieves the bounding rectangle of all pen-down points, but inflates the rectangle to accommodate ink width. lpvBuffer is the address of a RECT structure.
GPA_SIZE	Retrieves the size of the pen data memory block in bytes. Because of the potential large size of this value, the return value of the function is not used. Instead, lpvBuffer is the address of a DWORD variable to fill with the size.
GPA_STROKES	Retrieves the total number of strokes, including pen-up strokes. lpvBuffer is unused and ignored.
GPA_TIME	Retrieves the absolute time of creation of the pen data. lpvBuffer is the address of an ABSTIME structure.
GPA_USER	Retrieves the number of user bytes available per stroke: 0, 1, 2, or 4. lpvBuffer is unused and ignored.
GPA_VERSION	Retrieves the version number of the pen data. lpvBuffer is unused and ignored.
Return Value

Returns PDR_OK or an integer value if successful, depending on the uOption parameter.

Comments

GetPenDataAttributes provides enhancements of some of the capabilities of GetPenDataInfo. It also provides additional detailed information taken from the HPENDATA block.

See Also

GetStrokeAttributes, GetPenDataInfo


GetPenDataInfo [New - Windows 95]
 GetPenDataInfo

1.0     2.0      [New - Windows 95]

This function retrieves information from an HPENDATA memory block. It is superseded by the GetPenDataAttributes function.

BOOL GetPenDataInfo( HPENDATA hpndt, LPPENDATAHEADER lppdh, LPPENINFO lppeninfo, DWORD dwReserved )

Parameters

hpndt

Handle to a pen data object that receives the pen data information.

lppdh

Address of a PENDATAHEADER structure, or NULL if not required.

lppeninfo

Address of a PENINFO structure, or NULL if not required.

dwReserved

Reserved for future use. Must be set to 0.

Return Value

Returns TRUE if successful. The return value is FALSE if invalid parameters are used, or if the handle to the pen data is invalid, or if the requested PENINFO does not exist in the pen data.

Comments

This function retrieves the header and pen information in the pen data memory block. If lppeninfo is not NULL and the pen data does not contain pen information, the contents of lppeninfo are not changed. The wPndts member in the PENDATAHEADER structure can be checked to see if the HPENDATA object has a PENINFO structure associated with it (a value of PTDS_NOPENINFO indicates not). The amount of data allocated is contained in the cbSizeUsed member of the PENDATAHEADER structure.

See Also

GetPenDataAttributes


GetPenDataStroke [New - Windows 95]
 GetPenDataStroke

1.0     2.0      [New - Windows 95]

Returns a pointer to stroke data contained in an HPENDATA memory block previously locked with the BeginEnumStrokes function.

Note  This function is provided only for compatibility with version 1.0 of the Pen API and will not be supported in future versions. Use other services such as GetPenDataAttributes, GetPointsFromPenData, or GetStrokeAttributes to examine an HPENDATA block.

BOOL GetPenDataStroke( LPPENDATA lppd, UINT iStrk, LPPOINT FAR * lplppt, LPVOID FAR * lplpvOem, LPSTROKEINFO lpsi )

Parameters

lppd

Address of the HPENDATA memory block. This parameter is the value returned by a previous call to the BeginEnumStrokes function.

iStrk

Zero-based index of the stroke to retrieve.

lplppt

Address of a pointer to a point. The pointer returned by the function will point to the first point of the stroke inside the pen data object. This parameter can be NULL if point data is not required.

lplpvOem

Address of a void pointer. The pointer returned by the function will point to the OEM data block of the stroke inside the pen data object. The format of the OEM data is specified by the rgoempeninfo member in the PENINFO structure. This parameter can be NULL if OEM data is not required.

lpsi

Address of a STROKEINFO structure. This parameter can be NULL if stroke information is not required.

Return Value

Returns TRUE if successful. If the stroke requested is out of range, the function returns FALSE.

Comments

GetPenDataStroke returns in lpsi a pointer to a STROKEINFO structure created from the stroke referenced by iStrk. The lpsi parameter does not point directly into the HPENDATA memory block.

However, the lplppt argument points to the first point of the stroke inside the HPENDATA block. For a description of how the GetPenDataStroke function has changed in version 2.0 of the Pen API, refer to AppendixA.

Applications must call BeginEnumStrokes before calling GetPenDataStroke. After the last call to GetPenDataStroke, the application must call EndEnumStrokes. Once EndEnumStrokes is called, the data that lplppt and lplpvOem point to is no longer valid.

Under no circumstances should an application modify data directly within an HPENDATA block. Doing so can invalidate other information in the block. To modify an HPENDATA block, use one of the Pen API functions listed in Chapter 4, "The Inking Process."

See Also

BeginEnumStrokes, EndEnumStrokes, GetStrokeAttributes


GetPenHwEventData [New - Windows 95]
 GetPenHwEventData

1.0     2.0      [New - Windows 95]

Gets the pen data associated with events in a given range.

Note  This function is provided only for compatibility with version 1.0 of the Pen API and will not be supported in future versions. Use DoDefaultPenInput or GetPenInput instead.

REC GetPenHwEventData( UINT wEventRefBeg, UINT wEventRefEnd, LPPOINT lppt, LPVOID lpvOemData, int cPntMax, LPSTROKEINFO lpsi )

Parameters

wEventRefBeg

Beginning pen event.

wEventRefEnd

Ending pen event.

lppt

Address of a an array of POINT structures. The size of the array must be at least sizeof( POINT ) multiplied by cPntMax.

lpvOemData

Buffer to fill with OEM-specific data. This can be NULL if no data is required.

cPntMax

Maximum number of samples to return.

lpsi

Address of a STROKEINFO structure that receives the stroke information, including the count of points and point state. Also included is the time stamp of the first point returned in the buffer, which is the number of milliseconds that have elapsed since Windows started.

Return Value

Returns REC_OK if successful; otherwise, the return value can be one of the following:

Constant	Description
REC_BUFFERTOOSMALL	The array identified by lppt is not large enough to hold all the points requested.
REC_PARAMERROR	Invalid parameter.
Comments

This function fetches all data collected from the pen event wEventRefBeg up to but not including the pen event wEventRefEnd. If wEventRefBeg equals wEventRefEnd, GetPenHwEventData retrieves the single pen event associated with wEventRefBeg.

The values for wEventRefBeg and wEventRefEnd are obtained by calling the Windows GetMessageExtraInfo function.

This function can be called directly from an application. If it returns REC_BUFFERTOOSMALL, no data is returned and the cPnt member of lpsi contains the number of points between wEventRefBeg and wEventRefEnd. If REC_OK is returned, the cPnt member contains the number of valid points placed in the array at lppt.

See Also

STROKEINFO


GetPenInput [New - Windows 95]
 GetPenInput

2.0      [New - Windows 95]

Collects data after StartPenInput has started pen input.

int GetPenInput( HPCM hpcm, LPPOINT lppt, LPVOID lpvOem, UINT fuOemFlags, UINT cPntMax, LPSTROKEINFO lpsi )

Parameters

hpcm

Handle to the current collection. This is the return value from StartPenInput.

lppt

Address of an array of POINT structures. The array must consist of at least cPntMax structures.

lpvOem

The address of a buffer of OEM data associated with each point. This parameter can be NULL if the application does not require OEM data.

fuOemFlags

Flags specifying which OEM data to retrieve. If this parameter is NULL, all OEM data provided by the tablet is returned in the order specified by the rgoempeninfo array in PENINFO.

These flags have an implicit order. For example, if pressure and barrel rotation are specified, cPntMax pairs of these data are returned, in the order [pressure, rotation], [pressure, rotation], and so on.

Constant	Description
PHW_PRESSURE	Retrieve pressure data.
PHW_HEIGHT	Retrieve height data.
PHW_ANGLEXY	Retrieve data pertaining to the x- and y-coordinates.
PHW_ANGLEZ	Retrieve data pertaining to the z-coordinates.
PHW_BARRELROTATION	Retrieve barrel-rotation data.
PHW_OEMSPECIFIC	Retrieve OEM-specific data.
PHW_PDK	Retrieve per-point PDK_ information in OEM data.
cPntMax

The number of POINT structures in the array at lppt. This is the maximum number of points to return and also the maximum number of OEM items the buffer at lpvOem can hold.

lpsi

A pointer to a STROKEINFO structure. This structure receives information about the first point of the collection of points placed into the array at lppt. The cbPnts member contains the packet ID of the first point. All returned points in the collection have the same tip polarity (that is, up or down) as the first point.

Return Value

Returns 0 if there are no points available. If the return value is positive, the value is the number of points copied to the lppt (and, optionally, lpvOem) buffers. Otherwise, the return value is one of the following:

Constant	Description
PCMR_APPTERMINATED	Input has already terminated because the application called StopPenInput. There are no more points to retrieve.
PCMR_EVENTLOCK	An event must be taken out of the queue using the Windows functions PeekMessage or GetMessage before any more points can be retrieved using GetPenInput.
PCMR_INVALIDCOLLECTION	The hpcm handle is invalid because the calling application did not start input with StartPenInput.
PCMR_TERMTIMEOUT	Input has already terminated because the specified time-out period has elapsed.
PCMR_TERMRANGE	Input has already terminated because the pen has left the range of the tablet's zone of sensitivity.
PCMR_TERMPENUP	Input has already terminated because the pen was lifted from the tablet.
PCMR_TERMEX	Input has already terminated because the pen went down in a specified exclusion rectangle or region.
PCMR_TERMBOUND	Input has already terminated because the pen went down outside a specified bounding rectangle or region.
Comments

Once an application initiates pen-input collection by calling StartPenInput, the application then calls the GetPenInput function frequently to retrieve the actual data arriving from the pen device. This can be done by responding to hardware events or by continuously polling.

In the polling model, the application repeatedly calls GetPenInput to get data. It is important for the application to yield periodically; for example, by calling PeekMessage. A fast loop can potentially process the points before the system can collect more. In this case, successive calls to GetPenInput return 0 until the user writes some more. Polling is typically terminated when GetPenInput detects and returns a termination condition specified in StartPenInput.

In the event model, the application calls GetPenInput on receipt of a WM_PENEVENT message. All points up to this event are returned to the caller. An application can retrieve all available data in a short loop, until GetPenInput returns PCMR_EVENTLOCK. The application then falls out of the loop and exits the window procedure. The process begins again when the window procedure is called in response to another WM_PENEVENT message in the application's message queue.

If lpvOem is not NULL, the buffer must be large enough to hold cPntMax OEM data packets. The size of each packet is the width specified in the cbOemData member of the PENINFO structure, plus sizeof( UINT ) if PDK_ values are required.

Example

The following code example gathers more pen input for use by the recognizer. Assume the application has already called StartPenInput and is using the messaging collection model.

POINT	rgPnt[cbBuffer];

STROKEINFO	si;

// ... in WM_PENEVENT message handler:

switch (wParam)

{

.

.

.

case PE_PENUP:

case PE_PENMOVE:

case PE_TERMINATING:

// Get all the points collected since the last message

while ( (iRet = GetPenInput( hpcm, rgPnt, NULL, 0,

 cbBuffer, &si) ) > 0)

{

// Add pen data to recognition context and def process

AddPenInputHRC( vhrc, rgPnt, NULL, 0, &si );

ProcessHRC( vhrc, PH_DEFAULT );

}

break;

See Also

PeekPenInput,  StartPenInput,  PDK_


GetPenResource [New - Windows 95]
 GetPenResource

2.0      [New - Windows 95]

The GetPenResource function retrieves a copy of a pen services resource. (Japanese version only.)

HANDLE GetPenResource( WPARAM wParam )

Parameters

wParam

Specifies the pen services resource for which to retrieve a handle. This may be one of the following:

Constant	Description
GPR_CURSPEN	Standard pen cursor.
GPR_CURSCOPY	Copy cursor.
GPR_CURSUNKNOWN	Unknown cursor.
GPR_CURSERASE	Erase cursor.
GPR_BMCRMONO	Monochrome Return bitmap.
GPR_BMLFMONO	Monochrome LineFeed bitmap.
GPR_BMTABMONO	Monochrome Tab bitmap.
GPR_BMDELETE	Delete bitmap.
GPR_BMLENSBTN	Lens buttonface bitmap.
GPR_BMHSPMONO	Hankaku space bitmap (Japanese version only).
GPR_BMZSPMONO	Zenkaku space bitmap (Japanese version only).
Comments

An application can use this function to get a copy of a cursor or bitmap used by pen services. It is the application's responsibility to destroy the object by calling either the DestroyCursor or DeleteObject Windows API.

Return Value

This function returns a handle to an object, depending on the index specified by wParam if successful. Otherwise the return value is NULL.


GetPenMiscInfo [New - Windows 95]
 GetPenMiscInfo

1.0     2.0      [New - Windows 95]

Retrieves values pertaining to the pen system.

LONG GetPenMiscInfo( WPARAM wParam, LPARAM lParam )

Parameters

wParam

Specifies the identifier of the pen system value to retrieve. The pen system identifier must be a PMI_ value. See the table below for the possible PMI_ values in wParam.

lParam

Address of storage for data. This must not be NULL. The calling application must ensure that there is sufficient room to store the requested information. The type of storage object that lParam points to depends on wParam, as described in the following table. For each value of wParam in the first column, the second column describes the corresponding requirement for lParam:

wParam constant	LParam description
PMI_BEDIT	lParam is the address of a BOXEDITINFO structure. Boxed edit information.
PMI_CXTABLET	lParam is a far pointer to a UINT value specifying the width of tablet (in units of 0.001 inch) if present; otherwise,  the width of the screen.
PMI_CYTABLET	lParam is a far pointer to a UINT value specifying the height of tablet (in units of 0.001 inch) if present; otherwise,  the height of the screen.
PMI_INDEXFROMRGB	lParam is a far pointer to a DWORD value. On entry, lParam is the address of an RGB ink color value. On return, the low-order word of lParam is replaced with an index in the range 0 to 15 for the closest standard ink color and the high-order word is 0.
PMI_ENABLEFLAGS	lParam is a far pointer to a WORD value containing a flag describing whether certain Pen API features are enabled. The flags can be a combination of the following values: PWE_AUTOWRITE   Enable pen functionality where the I-Beam cursor is present. PWE_ACTIONHANDLES   Enable action handles in controls. PWE_INPUTCURSOR   Show cursor while writing. PWE_LENS   Enable pop-up letter guides (that is, the lens).
PMI_PENTIP	lParam is the address of a PENTIP structure.
PMI_RGBFROMINDEX	lParam is the address of a DWORD value. On entry, lParam is the address of an index in the range 0 to 15; on return, this value at this address is replaced with the standard RGB ink color value.
wParam constant	LParam description
PMI_SYSFLAGS	lParam is a far pointer to a WORD value containing a flag describing which pen system components are loaded. The flags can be a combination of the following values: PWF_RC1   Support available for Pen API version 1.0 Recognition Context (RC) and associated functions. PWF_PEN   Pen/tablet hardware is present. PWF_INKDISPLAY   Ink-compatible display driver is present. PWF_RECOGNIZER   System recognizer is present. PWF_BEDIT   Boxed edit (bedit) control is available. PWF_HEDIT   Handwriting edit (hedit) control is available. PWF_IEDIT   Ink edit (iedit) control is available. PWF_ENHANCED   Enhanced features, including gesture support and 1 millisecond timing, are available. PWF_FULL   All components listed above are present..
PMI_SYSREC	lParam is a far pointer to an HREC value which is the handle of the system recognizer, if present.
PMI_TICKREF	lParam is the address of an ABSTIME structure indicating  the absolute reference time that the system uses to calculate time-stamps for strokes in pen data objects and inkset
PMI_TIMEOUT	lParam is a far pointer to a UINT value indicating time-out value to end hand-writing input, in milliseconds.
PMI_TIMEOUTGEST	lParam is a far pointer to a UINT value indicating time-out value to end a gesture, in milliseconds.
PMI_TIMEOUTSEL	lParam is a far pointer to a UINT value indicating  the time-out value in milli-seconds for press-and-hold gesture. The range of permissible values is 0 to 5000. If press-and-hold has been disabled, this value is 65,535.
Return Value

The return value is PMIR_OK if successful; otherwise it is one of the following negative error values:

Constant	Description
PMIR_INDEX	wParam is out of range.
PMIR_NA	Support for this value of wParam is not available.
PMIR_VALUE	lParam is NULL or a invalid pointer.
Comments

The information type returned varies depending on the index. Note that if a UINT is expected, for example, it is an error to provide the address of a DWORD variable without explicitly setting the HIWORD to 0. This function only sets the LOWORD in this case, and since the variable is usually declared on the stack, there would be an unknown value in the HIWORD. See the examples below.

If wParam is PMI_INDEXFROMRGB or PMI_RGBFROMINDEX, the standard pen-tip color table is as follows:

00  black       RGB(  0,   0,   0)

01  dark blue   RGB(  0,   0, 127)

02  dark green  RGB(  0, 127,   0)

03  dark cyan   RGB(  0, 127, 127)

04  dark red    RGB(127,   0,   0)

05  purple      RGB(127,   0, 127)

06  brown       RGB(127, 127,   0)

07  gray        RGB(127, 127, 127)

08  light gray  RGB(192, 192, 192)

09  blue        RGB(  0,   0, 255)

10  green       RGB(  0, 255,   0)

11  cyan        RGB(  0, 255, 255)

12  red         RGB(255,   0,   0)

13  magenta     RGB(255,   0, 255)

14  yellow      RGB(255, 255,   0)

15  white       RGB(255, 255, 255)

Example

The following code sample retrieves the timeout and pen tip:

UINT uTimeout;

PENTIP tip;

GetPenMiscInfo( PMI_TIMEOUT, (LPARAM)(UINT FAR *)&utimeout );

GetPenMiscInfo( PMI_PENTIP, (LPARAM)(LPPENTIP)&tip );

Note that the following is an error, since the HIWORD is undefined:

DWORD dwTimeout;

GetPenMiscInfo( PMI_TIMEOUT, (LPARAM)&dwtimeout );	  // Wrong!

See Also

SetPenMiscInfo,  PMI_


GetPointsFromPenData [New - Windows 95]
 GetPointsFromPenData

1.0     2.0      [New - Windows 95]

Retrieves a specified range of points.

BOOL GetPointsFromPenData( HPENDATA hpndt, UINT iStrk, UINT iPnt, UINT cPnts, LPPOINT lppt )

Parameters

hpndt

Handle to a pen data object.

iStrk

The zero-based stroke index from which points are retrieved.

iPnt

First point to retrieve from the specified stroke.

cPnts

Number of points to retrieve. If this value is 0, the function returns TRUE.

lppt

Address of buffer to fill with points.

Return Value

Returns TRUE if successful, or FALSE if the requested points are out of range.

Comments

GetPointsFromPenData performs a function similar to GetPenDataStroke in that it retrieves information from an HPENDATA memory block. But GetPointsFromPenData copies the required data to buffers supplied by the application, rather than simply returning pointers to the original data in the global heap.

An application can also request a copy of a particular subset of points within a stroke. In this case, iPnt identifies the first point and cPnts is the number of points to retrieve. This allows an application to digest the points in an HPENDATA block a few at a time to avoid having to allocate a large block of memory for the entire set of points.

GetPointsFromPenData returns the last point in a stroke if the iPnt argument is set to a value larger than the total number of points in the stroke. In the same manner, the function returns the points of the last stroke if iStrk exceeds the total number of strokes in the HPENDATA block. If the count of points to return is 1 and iPnt is beyond the last point in the stroke, the function returns the last point in the stroke.

See Also

GetPenDataStroke


GetResultsHRC [New - Windows 95]
 GetResultsHRC

2.0      [New - Windows 95]

Retrieves results from a recognition context HRC. A recognizer must export this function.

int GetResultsHRC( HRC hrc, UINT uType, LPHRCRESULT rghrcresults, UINT cResults )

Parameters

hrc

Handle to the HRC object.

uType

Specifies the type of expected results. This can be one of the following values:

Constant	Description
GRH_ALL	Return all results.
GRH_GESTURE	Return results of type gesture only.
GRH_NONGESTURE	Return all results not of type gesture.
rghrcresults

Address of an array of HRCRESULT objects.

cResults

The size of the rghrcresults array, in objects. The actual size in bytes can be calculated by multiplying cResults by the size of HRCRESULT. This parameter must be greater than 0.

Return Value

Returns the actual number of results returned if successful. This can be 0; otherwise, returns one of the following negative values:

Constant	Description
HRCR_ERROR	Invalid parameter or other error.
HRCR_HOOKED	A hook preempted the result.
HRCR_MEMERR	Insufficient memory.
Comments

The actual number of results returned by this function may be less than the number specified by cResults. It is also less than or equal to the count specified at the creation of hrc by the cMaxResults parameter in SetMaxResultsHRC, regardless of the size of the rghrcresults array.

A return value of 0 indicates that the recognizer was not able to recognize any of the input, even if coerced by a word list set into the HRC. A recognizer should never return a result consisting entirely of SYV_UNKNOWN symbols.

The calling application must explicitly destroy each valid result using DestroyHRCRESULT. However, if the return value is 0 or negative, the contents of the rghrcresults array are undefined (though not NULL) and DestroyHRCRESULT must not be called.

See Also

DestroyHRCRESULT


GetStrokeAttributes [New - Windows 95]
 GetStrokeAttributes

2.0      [New - Windows 95]

Retrieves information about a stroke in an HPENDATA object.

int GetStrokeAttributes( HPENDATA hpndt, UINT iStrk, LPVOID lpvBuffer, UINT uOption )

Parameters

hpndt

Handle to the HPENDATA object, which must not be compressed.

iStrk

Zero-based stroke index. If there are no strokes in the pen data, an index of 0 can be used to retrieve the default attributes for the pen data. A value of IX_END specifies the last available stroke in the pen data.

lpvBuffer

Pointer to a structure whose type depends on uOption, or NULL if the uOption parameter does not require this buffer.

uOption

Specifies the attributes to retrieve. This parameter has one of the following values:

Constant	Description
GSA_DOWN	Retrieve the up/down state of the pen tip for this stroke. Returns 1 if the stroke is a down-stroke or 0 if it is an up-stroke. lpvBuffer is unused and ignored.
GSA_PENTIP	Retrieve the pen-tip characteristics (color, width, nib) used by the stroke specified by iStrk. lpvBuffer is a pointer to a PENTIP structure. Return value is PDR_OK.
GSA_PENTIPCLASS	Retrieve the pen-tip characteristics (color, width, nib), if any, for the class of strokes of which the stroke specified by iStrk is a member. lpvBuffer is a pointer to a PENTIP structure. Return value is PDR_OK.
GSA_RECTBOUND	Retrieve the bounding rectangle of the specified stroke. lpvBuffer is a pointer to a RECT structure. Return value is PDR_OK.
GSA_SELECT	Retrieve the selection status of the specified stroke. lpvBuffer is unused and ignored. Returns a nonzero value if the stroke is selected; otherwise, the return value is 0.
GSA_SIZE	Retrieve size of stroke in points and bytes. lpvBuffer is a pointer to a double-word value, or NULL. LOWORD(*(LPDWORD)lpvBuffer) is the size in points, and HIWORD(*(LPDWORD)lpvBuffer) is the size in bytes. Return value is PDR_OK.
GSA_TIME	Retrieve the absolute time of the stroke. lpvBuffer is a pointer to an ABSTIME structure; it cannot be NULL. The sec field specifies the number of seconds since Jan 1, 1970, and the ms field specifies the number of milliseconds offset from that time to the beginning of the stroke. Return value is PDR_OK.
GSA_USER	Retrieve the user value, if any, for the stroke. lpvBuffer is a pointer to a double-word value, or NULL. Returns the number of bytes of user data available in the stroke: 0, 1, 2, or 4.
GSA_USERCLASS	Retrieve the user value, if any, for the class of strokes of which the stroke specified by iStrk is a member. lpvBuffer is a pointer to a double-word value, or NULL. The return value is 4 because the user value in the strokes class table is a doubleword value.
Return Value

Returns PDR_OK or an integer value if successful, as described for the uOption parameter. If an error occurs, returns one of the following:

Constant	Description
PDR_COMPRESSED	Pen data is compressed.
PDR_ERROR	Parameter or other unspecified error.
PDR_MEMERR	Memory error.
PDR_PNDTERR	Invalid pen data.
PDR_STRKINDEXERR	Invalid stroke index.
PDR_TIMESTAMPERR	Timing information was removed.
PDR_VERSIONERR	Could not convert old pen data.
See Also

CreatePenDataEx, GetStrokeTableAttributes, SetStrokeAttributes, SetStrokeTableAttributes, PENTIP


GetStrokeTableAttributes [New - Windows 95]
 GetStrokeTableAttributes

2.0      [New - Windows 95]

Retrieves information about a stroke's class from the table in the PENDATAHEADER of an HPENDATA object.

int GetStrokeTableAttributes( HPENDATA hpndt, UINT iTblEntry, LPVOID lpvBuffer, UINT uOption )

Parameters

hpndt

Handle to the HPENDATA object, which must not be compressed.

iTblEntry

Zero-based table index to the class entry in the pen data header.

lpvBuffer

Pointer to a structure whose type depends on uOption, or NULL if the uOption parameter does not require this buffer.

uOption

Specifies the attributes to retrieve. This parameter can be one of the following:

Constant	Description
GSA_PENTIPTABLE	Retrieve the pen-tip characteristics (color, width, nib) of the class of strokes specified by iTblEntry. lpvBuffer is a pointer to a PENTIP structure. Return value is the number of strokes using this class.
GSA_SIZETABLE	Retrieve the number of entries in the stroke class table. iTblEntry and lpvBuffer are unused and ignored. Return value is the number of classes used in the stroke class table.
GSA_USERTABLE	Retrieve the user value, if any, of the class of strokes specified by iTblEntry. lpvBuffer is a pointer to a doubleword value, or NULL. The number of bytes that are valid in lpvBuffer depends on flags set in CreatePenDataEx. This number is returned by the function, and can be 0 (no user value), 1 (byte value),  2 (word value), or 4 (doubleword value). Return value  is 4, because the user value in the stroke class table  is a doubleword value.
Return Value

Returns an integer if successful, depending on the value of uOption, as described above. If an error occurs, returns one of the following:

Constant	Description
PDR_COMPRESSED	Pen data is compressed.
PDR_ERROR	Parameter or other unspecified error.
PDR_MEMERR	Memory error.
PDR_PNDTERR	Invalid pen data.
PDR_VERSIONERR	Could not convert old pen data.
See Also

CreatePenDataEx, GetStrokeAttributes, SetStrokeAttributes, SetStrokeTableAttributes, PENTIP


GetSymbolCount [New - Windows 95]
 GetSymbolCount

1.0     2.0      [New - Windows 95]

Returns the number of symbol strings contained in a symbol graph SYG.

int GetSymbolCount( LPSYG lpsyg )

Parameters

lpsyg

Address of the symbol graph.

Return Value

Returns the number of possible symbol strings that can be generated from the symbol graph. Returns −1 for any graph that can generate more than 32,767 symbol strings, or if there is a parameter error.

Example

For example, if the symbol graph pointed to by lpsyg is

ex {a | u} mple

GetSymbolCount returns the value 2 because the graph contains two symbol strings ("example" and "exumple").

See Also

EnumSymbols, FirstSymbolFromGraph, GetSymbolMaxLength SYG, SYV_


GetSymbolCountHRCRESULT [New - Windows 95]
 GetSymbolCountHRCRESULT

2.0      [New - Windows 95]

Retrieves the count of symbols available in a recognition result. A recognizer must export this function.

int GetSymbolCountHRCRESULT( HRCRESULT hrcresult )

Parameters

hrcresult

Handle of a results object.

Return Value

Returns the count of symbols if successful; otherwise, returns one of the following negative values:

Constant	Description
HRCR_ERROR	Invalid parameter or other error.
HRCR_MEMERR	Insufficient memory.
Comments

This function is typically called before GetSymbolsHRCRESULT to determine the size of a buffer required to store the symbol values returned in a recognition result. To calculate the size of the buffer, multiply the value returned by this function by sizeof( SYV ).

See Also

GetSymbolsHRCRESULT, SYV_


GetSymbolMaxLength [New - Windows 95]
 GetSymbolMaxLength

1.0     2.0      [New - Windows 95]

Returns the length of the longest symbol string contained in a symbol graph SYG.

int GetSymbolMaxLength( LPSYG lpsyg )

Parameters

lpsyg

Address of the symbol graph.

Return Value

Returns the number of symbols in the longest symbol string that can be generated from the symbol graph, or −1 if there is a parameter error.

Example

For example, if the symbol graph pointed to by lpsyg is

ab {c | de} f

GetSymbolMaxLength returns 5 because the longest string is "abdef".

See Also

EnumSymbols, FirstSymbolFromGraph, SYG, SYV_


GetSymbolsHRCRESULT [New - Windows 95]
 GetSymbolsHRCRESULT

2.0      [New - Windows 95]

Retrieves an array of symbol values corresponding to a recognition result. A recognizer must export this function.

int GetSymbolsHRCRESULT( HRCRESULT hrcresult, UINT iSyv, LPSYV rgsyv, UINT cSyv )

Parameters

hrcresult

Handle of a results object.

iSyv

Index of the first symbol of interest in the results object.

rgsyv

Address of a buffer in which to put the symbols. The array must be large enough to store cSyv symbols.

cSyv

The size of rgsyv in symbols (not bytes). This is the number of symbols to be returned. A value of 0 is legal, in which case the function simply returns 0.

Return Value

Returns the count of symbols copied, if successful; otherwise, returns one of the following negative values:

Constant	Description
HRCR_ERROR	Invalid parameter or other error.
HRCR_MEMERR	Insufficient memory.
Comments

It is possible to allocate a small buffer in rgsyv and call this function repeatedly, incrementing the index iSyv each time by the number of symbols returned in the previous call, until the function returns 0.

Example

The following example gets a character result, using a small buffer:

#define CBCHBUF 1024	// Char buffer

#define CSYVMAX 32	// Relatively small symbol chunk

HRC	  vhrc; 	      // Handle to a handwriting context

HRCRESULT vhrcresult;	      // Handle to a recognition result

SYV	  vrgsyv[CSYVMAX];    // Symbol result buffer

char	  vrgcBuff[CBCHBUF];  // Buffer for recognition results

.

.	     // Code that creates HRC, gets input, etc....

.

EndPenInputHRC( vhrc );     // Tell recognizer no more ink

ProcessHRC( vhrc, PH_MAX ); // Finish recognition

.

.	     // Retrieve a handle to the results

.

if (GetResultsHRC( vhrc, &vhrcresult, 1 ) > 0)

{

int i = 0, cSyv;

// Retrieve some symbols

while ((cSyv = GetSymbolsHRCRESULT( vhrcresult,

i, vrgsyv, CSYVMAX )) > 0)

{

if (i + cSyv + 1 > CBCHBUF) // Don't overflow buffer

cSyv = CBCHBUF - i - 1;

if (cSyv > 0)	    // Still have something?

{

SymbolToCharacter( vrgsyv, cSyv, vrgcBuff + i, NULL );

i += cSyv;

}

if (i + 1 >= CBCHBUF)

break;

}

vrgcBuff[i] = chNull;	 // Terminate string

}

DestroyHRCRESULT( vhrcresult );  // We're finished with result

vhrcresult = NULL;

DestroyHRC( vhrc );	 // Finished with this HRC session

vhrc = NULL;

See Also

GetSymbolCountHRCRESULT, SYV_


GetVersionPenWin [New - Windows 95]
 GetVersionPenWin

1.0     2.0      [New - Windows 95]

Retrieves the Pen API version number.

UINT GetVersionPenWin(  )

Return Value

The low-order byte of the return value specifies the major (version) number. The high-order byte specifies the minor (revision) number.


GetWordlistCoercionHRC [New - Windows 95]
 GetWordlistCoercionHRC

2.0      [New - Windows 95]

Retrieves the current word list coercion setting in a handwriting-recognition context HRC.

int GetWordlistCoercionHRC( HRC hrc )

Parameters

hrc

Handle to the HRC object.

Return Value

If successful, returns one of the following values:

Constant	Description
SCH_ADVISE	The word list is a hint to the recognizer, and results are not strongly coerced to match the word list.
SCH_FORCE	If results do not match the word list, the closest fit is returned.
SCH_NONE	Do not coerce. This flag can be used to turn off a previous request.
Otherwise, returns one of the following negative values:

Constant	Description
HRCR_ERROR	Invalid parameter or other error.
HRCR_MEMERR	Insufficient memory.
HRCR_UNSUPPORTED	The recognizer does not support this function.
See Also

SetWordlistCoercionHRC


GetWordlistHRC [New - Windows 95]
 GetWordlistHRC

2.0      [New - Windows 95]

Retrieves a word list from a recognition context HRC.

int GetWordlistHRC( HRC hrc, LPHWL lphwl )

Parameters

hrc

Handle to the HRC object.

lphwl

Address of a handle to a word list. The recognizer sets the handle to NULL if the recognition context does not contain a word list.

Return Value

Returns HRCR_OK if successful; otherwise, returns one of the following negative values:

Constant	Description
HRCR_ERROR	Invalid parameter or other error.
HRCR_MEMERR	Insufficient memory.
HRCR_UNSUPPORTED	The recognizer does not support this function.
Comments

An HRC can be configured for only one word list at a time. This is independent of the recognizer's dictionary, which can be manipulated through the EnableSystemDictionaryHRC function.

For a description of word lists and how a recognizer uses them, see "Configuring the HRC" in Chapter 5, "The Recognition Process."

See Also

SetWordlistHRC


HitTestPenData [New - Windows 95]
 HitTestPenData

2.0      [New - Windows 95]

Determines if a given point lies on or near the pen-down strokes contained in an HPENDATA object.

int HitTestPenData( HPENDATA hpndt, LPPOINT lppt, UINT dThresh, UINT FAR* lpiStrk, UINT FAR* lpiPnt )

Parameters

hpndt

Handle to the HPENDATA object. HitTestPenData does not alter the data in the HPENDATA object.

lppt

Address of a POINT structure containing the point to test.

dThresh

Threshold around the point given in lppt. The point lies at the center of a square with sides of length dThresh. If HitTestPenData finds a point in the HPENDATA object that lies in the square, it indicates a "hit." dThresh must have the same scaling units as the points in the HPENDATA or the result will not be correct. If dThresh is 0, HitTestPenData assumes a default threshold value of 3.

lpiStrk

Stroke index from which to begin testing. After HitTestPenData returns from a successful test, the variable that lpiStrk points to contains the index of the hit stroke.

lpiPnt

Point index from which to begin testing. After HitTestPenData returns from a successful test, the variable that lpiPnt points to contains the index of the hit point in the stroke indicated by lpiStrk.

Return Value

Returns one of the following if successful:

Constant	Description
PDR_HIT	The point hits (intersects) the pen data or falls within the provided threshold around a particular point in the pen data as specified by the stroke and the point indices. The stroke and point values are returned in lpiStrk and lpiPnt, respectively.
PDR_NOHIT	The point does not hit (intersect) the pen data nor does it fall within the provided threshold around a particular point in the pen data as specified by the stroke and the point indices.
Otherwise, the function returns one of the following negative values:

Constant	Description
PDR_COMPRESSED	Pen data is compressed.
PDR_ERROR	Parameter or other unspecified error.
PDR_MEMERR	Memory error.
PDR_PNDTERR	Invalid pen data.
PDR_PNTINDEXERR	Invalid point index.
PDR_STRKINDEXERR	Invalid stroke index.
PDR_VERSIONERR	Could not convert old pen data.
Comments

HitTestPenData checks whether the point specified by lppt falls within the threshold specified by dThresh around a point in the pen data, depending on the zero-based starting stroke and point indices specified by lpiStrk and lpiPnt. This function tests only down strokes in the pen data. If lpiStrk is greater than the number of strokes in the pen data, testing starts from the first stroke.

Similarly, if lpiPnt is greater than the number of points in the stroke, testing starts from the first point in that stroke. The first point in the first stroke (from the specified indices) that meets the test condition is returned via lpiPnt and lpiStrk, respectively.

In any case, HitTestPenData accounts for the width of the ink trail. If the value given in dThresh is less than the ink width, HitTestPenData ignores the specified value of dThresh and instead uses the ink width as the threshold.

HitTestPenData does not consider pen-up strokes.


InitRC [New - Windows 95]
 InitRC

1.0     2.0      [New - Windows 95]

Initializes an RC structure with default values.

Note  This function is provided only for compatibility with version 1.0 of the Pen API, and will not be supported in future versions.

void InitRC( HWND hwnd, LPRC lprc )

Parameters

hwnd

Handle to a window.

lprc

Address of the RC structure to initialize.

Return Value

This function does not return a value.

Comments

InitRC serves little purpose in applications that conform to version 2.0 of the Pen API. Under version 2.0, a recognizer maintains an HRC object, which makes the RC structure obsolete.

For suggestions on how to update a version 1.0 application to remove services that rely on RC, see the section "The RC Structure" in Appendix A.

InitRC initializes an RC structure with default values, many of which come from the global RC structure. The application can use the initialized RC structure when calling the Recognize function. Although an application can change any of these values, it should be careful about changing those items that can be set by the user through the Windows Control Panel.

InitRC sets the bounding rectangle to the client area of the window identified by hwnd. The bounding rectangle is valid only until the window is resized or moved. When this occurs, the application must again call InitRC to update the rectBound member of the RC structure or correct rectBound manually. If the window handle hwnd is NULL, the bounding rectangle and hwnd remain uninitialized. The application must set the hwnd member to a valid window before calling Recognize or RecognizeData.

The following table describes the default values used to initialize the RC structure. Values not listed in the table come from the global RC. Some of the global default values can be modified by the user in Control Panel.

Value	Description
rc.alc	ALC_DEFAULT. The function uses the complete alphabet and all gestures. The exact character set depends on the recognizer.
rc.lRcOptions	Zero.
rc.hwnd	hwnd (the first argument of InitRC).
rc.wResultMode	RRM_COMPLETE.
rc.rectBound	(0,0,0,0) or client rectangle of hwnd if hwnd is not NULL.
rc.lPcm	PCM_ADDDEFAULTS, or PCM_ADDDEFAULTS | PCM_RECTBOUND if hwnd is not NULL.
rc.rectExclude	(0,0,0,0).
rc.guide	(0,0,0,0,0,0,0).
rc.wRcOrient	RCOR_NORMAL.
rc.wRcDirect	0x0103
Members the user can change through the system Control Panel are filled with values indicating that the system default should be used. These placeholder values are RC_WDEFAULT or RC_LDEFAULT, depending on whether the member is a UINT or LONG value. During the processing of ProcessWriting, Recognize, or RecognizeData, these values are replaced with the current system defaults before the RC structure is passed to the recognizer. If the PCM_ADDDEFAULTS flag is set in lPcm, the values of the lPcm member in the global RC are combined with the current lPcm values with OR operators at the time the recognizer is called. If the high bit is set in wRcPreferences, the values of the wRcPreferences member in the global RC are combined with the current wRcPreferences values with bitwise-OR operators at the time the recognizer is called.

The following table gives the default values for the members of the RC structure:

Value	Description
rc.hrec	RC_WDEFAULT
rc.lpfnYield	RC_LDEFAULT
rc.lpUser	RC_LDEFAULT
rc.wCountry	RC_WDEFAULT
rc.wIntlPreferences	RC_WDEFAULTFLAGS
rc.lpLanguage	RC_LDEFAULT
rc.rglpdf	RC_LDEFAULT
rc.wTryDictionary	RC_WDEFAULT
rc.clErrorLevel	RC_WDEFAULT
rc.wTimeOut	RC_WDEFAULT
rc.wRcPreferences	RC_WDEFAULTFLAGS
rc.nInkWidth	RC_WDEFAULT
rc.rgbInk	RC_LDEFAULT
rc.alcPriority	ALC_NOPRIORITY
rc.rgbfAlc	Array initialized to 0
The RC structure pointed to in the RCRESULT structure is a copy of the original RC structure passed as a parameter to Recognize. In the copy, default values are replaced. All coordinates are in the tablet coordinate system and the lRcOptions member has the RCO_TABLETCOORD flag set.

See Also

Recognize,  RecognizeData,  RC,  ALC_,  PCM_,  RCO_


InsertPenData [New - Windows 95]
 InsertPenData

2.0      [New - Windows 95]

Merges two blocks of pen data at the specified stroke index.

int InsertPenData( HPENDATA hpndtDst, HPENDATA hpndtSrc, UINT iStrk )

Parameters

hpndtDst

Handle of the pen data object to merge into. When this function returns, this is the handle of the merged data.

hpndtSrc

Handle of the pen data object to merge from.

iStrk

Stroke index. The merge operation occurs before this index. This parameter can also be IX_END to append hpndtSrc to the end of hpndtDst.

Return Value

Returns PDR_OK if successful; otherwise, the return value is one of the following negative values:

Constant	Description
PDR_COMPRESSED	Pen data is compressed.
PDR_ERROR	Parameter or other unspecified error.
PDR_MEMERR	Out of memory.
PDR_OEMDATAERR	Incompatible OEM data in the two pen data objects.
PDR_STRKINDEXERR	Invalid stroke index.
PDR_TIMESTAMPERR	Incompatible time fields in the two pen data objects.
PDR_USERDATAERR	Incompatible user space in the two pen data objects.
PDR_VERSIONERR	Could not convert old pen data object.
Comments

InsertPenData merges two blocks of pen data starting at the zero-based stroke index specified by iStrk of the destination pen data.

The blocks of pen data to be merged must be compatible. The calling application should ensure that the blocks of data are in the same scaling mode. The user space, if present, should be of the same size. OEM data, if present, must be compatible and of the same type. The application can use TrimPenData to delete certain information from either the source or the destination HPENDATA object to make it compatible. If hpndtDst has timing information and hpndtSrc does not, the merge fails. However, if hpndtDst does not have timing information and hpndtSrc does have it, the timing is stripped from hpndtSrc.

For a description of timing information, see "The HINKSET Object" in Chapter 4, "The Inking Process."

See Also

InsertPenDataStroke, InsertPenDataPoints, MetricScalePenData, TrimPenData, CreatePenDataEx


InsertPenDataPoints [New - Windows 95]
 InsertPenDataPoints

2.0      [New - Windows 95]

Inserts points into an existing HPENDATA object.

int InsertPenDataPoints( HPENDATA hpndt, UINT iStrk, UINT iPnt, UINT cPnts, LPPOINT lppt, LPVOID lpvOem )

Parameters

hpndt

Handle to an HPENDATA object.

iStrk

Zero-based index of the stroke into which the points are inserted. If this value is IX_END, the points are inserted in the last stroke.

iPnt

Zero-based index of the point in the stroke before which the points are inserted. If this value is IX_END, the points are appended to the end of the stroke.

cPnts

Total number of points to be inserted. If this is 0, the function returns PDR_OK without taking any other action.

lppt

Address of an array of POINT structures containing the points to be inserted.

lpvOem

Address of a buffer containing the OEM data to be inserted. This value can be NULL only if the HPENDATA object does not have OEM data or a PENINFO structure.

Return Value

Returns PDR_OK if successful; otherwise, the return value can be one of the following negative values:

Constant	Description
PDR_COMPRESSED	Pen data is compressed.
PDR_ERROR	Parameter or other unspecified error.
PDR_MEMERR	Out of memory.
PDR_STRKINDEXERR	Invalid stroke index.
PDR_PNTINDEXERR	Invalid point index.
PDR_VERSIONERR	Could not convert old pen data object.
Comments

InsertPenDataPoints inserts points into an existing stroke of the specified pen data object. It does not create a new stroke. (Use the InsertPenDataStroke function to insert new strokes into the pen data object.) The stroke attributes are not affected by the points added to the stroke.

The calling application must ensure that lppt and lpvOem are valid and that the points are in the same scale as those of the pen data object. InsertPenDataPoints performs no automatic scaling of the points.

InsertPenDataPoints does not make any timing adjustments after adding points. This can affect recognition accuracy and should be used judiciously.

For a description of timing information, see "The HINKSET Object" in Chapter 4, "The Inking Process."

See Also

AddPointsPenData, ExtractPenDataPoints, InsertPenData, InsertPenDataStroke, RemovePenDataStrokes


InsertPenDataStroke [New - Windows 95]
 InsertPenDataStroke

2.0      [New - Windows 95]

Inserts a stroke into an existing HPENDATA object.

int InsertPenDataStroke( HPENDATA hpndt, UINT iStrk, LPPOINT lppt, LPVOID lpvOem, LPSTROKEINFO lpsiNew )

Parameters

hpndt

Handle to the HPENDATA object that receives the inserted strokes.

iStrk

Zero-based index of the stroke at which the new stroke is to be inserted. If this value is IX_END, the stroke is appended at the end of the HPENDATA memory block.

lppt

Pointer to a buffer containing the points to be inserted.

lpvOem

Pointer to a buffer of OEM data. This value can be NULL only if the pen data object does not have OEM data or a PENINFO structure.

lpsiNew

Pointer to the STROKEINFO structure containing information about the stroke.

Return Value

Returns PDR_OK if successful; otherwise, the return value can be one of the following negative values:

Constant	Description
PDR_COMPRESSED	Pen data is compressed.
PDR_ERROR	Parameter or other unspecified error.
PDR_MEMERR	Out of memory.
PDR_STRKINDEXERR	Invalid stroke index.
PDR_TIMESTAMPERR	Timing error.
PDR_VERSIONERR	Could not convert old pen data object.
Comments

InsertPenDataStroke inserts an entire stroke into an HPENDATA object. Use InsertPenDataPoints to insert points into a particular stroke.

The inserted stroke assumes the default pen-tip attributes. SetStrokeAttributes should be called after inserting the stroke to change such stroke attributes as the pen-tip characteristics or user data.

The calling application must ensure that lppt and lpvOem are valid, and that the points in the stroke that is being added have compatible scaling modes.

Attempting to insert an empty stroke simply returns PDR_OK.

See Also

AddPointsPenData, ExtractPenDataPoints, InsertPenDataPoints, RemovePenDataStrokes, STROKEINFO


InstallRecognizer [New - Windows 95]
 InstallRecognizer

1.0     2.0      [New - Windows 95]

Loads and initializes a specified recognizer.

HREC InstallRecognizer( LPSTR lpszRecogName )

Parameters

lpszRecogName

Name of recognizer to load. If lpszRecogName is NULL, the default recognizer is loaded. (An application should not set lpszRecogName to NULL, because Windows automatically loads the default recognizer on initialization.)

Return Value

Returns a handle to a recognizer if successful; otherwise, returns NULL.

Comments

The recognizer's name is the name of the DLL to be loaded. Windows searches for the recognizer file according to the standard rules for searching for a DLL—that is, it first searches the current directory, then the Windows directory, the system subdirectory, the PATH directories, and so forth. The procedure fails if the library cannot be found, the load fails, or the loaded DLL is not a valid recognizer. The recognizer may decline to load if it requires hardware information such as pen pressure that the pen device cannot provide.

An application should not load the default recognizer. All recognizers installed by an application must be uninstalled by a call to UninstallRecognizer before the application terminates.

After loading a recognizer library, the system calls the recognizer's ConfigRecognizer function with the subfunction WCR_INITRECOGNIZER.

An application can load a recognizer with a call to LoadLibrary instead of InstallRecognizer. However, the application must first link with an import library derived from the recognizer DLL. The recognizer's import library must appear in the library section of the LINK command line before PENWIN.LIB. This forces the application's calls to pass directly to the recognizer's exported recognition functions instead of the system.

This procedure may facilitate debugging the recognizer, but otherwise serves no purpose. It prevents use of other recognizers, including the system default recognizer. For a discussion of import libraries, refer to the section on the IMPLIB utility described in the Environment and Tools manual of the Microsoft VisualC++ documentation.

See Also

ConfigRecognizer, ConfigHREC, UninstallRecognizer


IsPenAware [New - Windows 95]
 IsPenAware

1.0     2.0      [New - Windows 95]

Checks the capability of an application to handle pen events by returning cached task pen flags.

Note  This function is provided only for compatibility with version 1.0 of the Pen API and will not be supported in future versions. Use GetPenAppFlags instead.

UINT IsPenAware(  )

Return Value

Returns the registration flags word set by a previous call to the SetPenAppFlags function. If SetPenAppFlags has not been called, IsPenAware returns 0.

See Also

GetPenAppFlags, SetPenAppFlags


IsPenEvent [New - Windows 95]
 IsPenEvent

1.0     2.0      [New - Windows 95]

Checks whether a mouse event was generated by the pen driver.

BOOL IsPenEvent( UINT message, LONG lExtraInfo )

Parameters

message

Windows mouse message being queried.

lExtraInfo

Value returned by GetMessageExtraInfo for the given message.

Return Value

Returns TRUE if the mouse event referenced by the message parameter was generated by the pen driver; otherwise, returns FALSE.

Comments

Mouse drivers that have not been updated to be compatible with pens may produce an event that cannot be distinguished from a real pen event. This has a very low probability of occurring.


KKConvert [New - Windows 95]
 KKConvert

2.0      [New - Windows 95]

Activates the Kana-to-Kanji converter. (Japanese version only.)

BOOL KKConvert( HWND hwndConvert, HWND hwndCaller, LPSTR  lpBuf, UINT cbBuf, LPPOINT lpPoint )

Parameters

hwndConvert

Handle to the window with the text to be converted.

hwndCaller

Handle to the window that calls KKConvert.

lpBuf

The text to be converted.

cBuf

The number of bytes (greater than 1) in lpBuf.

lpPoint

The positition where the Kana-to-Kanji converter will appear.

Return Value

Returns TRUE if the text is successfully converted; otherwise, returns FALSE.

Comments

If lpBuf is NULL, the currently-selected text in the window specified by hwndConvert will be used for conversion and then replaced with the converted text. If lpBuf is not NULL, the text in lpBuf will be converted and replaced with the converted text. If the length of the converted text is longer than cbBuf, the text will be truncated.

If the window referenced by hwndConvert is of the bedit class, lpPnt is ignored; otherwise, the center of the Kana-to-Kanji conversion is displayed at lpPnt.

If the window referenced by hwndConvert is of the hedit class and lpPnt is NULL, then the current caret position is used; otherwise, the client position (0,0) in the window referenced by hwndConvert is used.


MetricScalePenData [New - Windows 95]
 MetricScalePenData

1.0     2.0      [New - Windows 95]

Converts pen data points to one of the supported metric modes.

BOOL MetricScalePenData( HPENDATA hpndt, UINT wPndtNew )

Parameters

hpndt

Handle to a pen data object containing the points to be converted.

wPndtNew

Scaling metric to be used with the data, as listed here:

Constant	Description
PDTS_LOMETRIC	Each logical unit is mapped to 0.1 millimeter. Positive x is to the right; positive y is down.
PDTS_HIMETRIC	Each logical unit is mapped to 0.01 millimeter. Positive x is to the right; positive y is down.
PDTS_HIENGLISH	Each logical unit is mapped to 0.001 inch. Positive x is to the right; positive y is down. This is equivalent to PDTS_STANDARDSCALE.
PDTS_DISPLAY	This parameter scales the data, using DPtoTP. The pen data memory block is left in display coordinates.
Return Value

Returns TRUE if successful, or FALSE if hpndt is in a compressed state or if the data is not already in one of the metric modes such as PDTS_ARBITRARY.

Comments

The MetricScalePenData function converts pen coordinates between metric and English standard measurements. Metric units are 0.1 and 0.01 millimeter; English standard units are 0.001 inch. These scaling metrics form the same mapping mode set in the Windows function SetMapMode.

MetricScalePenData allows an application to transform pen data to the mapping mode set for a device context. This ensures that ink rendered in the device context appears in the proper scale.

Note the following caveats about MetricScalePenData:

•	Because of rounding errors, scaling is not precisely reversible between mapping modes. Rounding errors can also adversely affect recognition accuracy if the data is later given to a recognizer. The problem arises when transforming the standard ink scale of HIENGLISH to a scale of lower resolution, a transformation that loses some of the original data. The lost data cannot be recovered, even if the coordinates are converted back into HIENGLISH.

•	The scaling is not perfect and results in numerous "off-by-one" discrepancies, visible when displaying the scaled data.

Strictly speaking, the PDTS_DISPLAY scaling type is not a metric scale. To use it, the current scale of the data must be in PDTS_STANDARDSCALE units.

The effect of this call is similar to that of using the TPtoDP function on the array of points. A recognizer may not accurately recognize the resulting data. As with the other scales, the PDTS_DISPLAY is set in the wPndts member of the pen data header. If data is in PDTS_DISPLAY scale, MetricScalePenData cannot be called to scale it back to the other metric scales. No overflow checks are made. Because of rounding errors, scaling conversion is not perfectly reversible. Recognizers must recognize points that have been scaled to PDTS_STANDARDSCALE (equivalent to PDTS_HIENGLISH).

See Also

OffsetPenData, ResizePenData, PDTS_


OffsetPenData [New - Windows 95]
 OffsetPenData

1.0     2.0      [New - Windows 95]

Offsets the coordinates in an HPENDATA memory block to make them relative to another origin.

BOOL OffsetPenData( HPENDATA hpndt, int dx, int dy )

Parameters

hpndt

Handle to a pen data object.

dx

Offset of x-axis; that is, the amount to move left or right. To move left, the dx value must be negative.

dy

Offset of y-axis; that is, the amount to move up or down. To move up, the dy value must be negative.

Return Value

Returns TRUE if successful, or FALSE if hpndt is in a compressed state.

Comments

For every point in hpndt, dx is added to the x-coordinate and dy is added to the y-coordinate. No overflow checks are made.

An application can use OffsetPenData to make points at display resolution relative to a particular window. If the window is then moved, the application need only call OffsetPenData again to move the data by the same amount, as shown in the example.

Example

The following sample code illustrates using the OffsetPenData function.

DWORD	dwOrg;	// Store window origin

.

.

.

// After creating window, note its current position

dwOrg = GetWindowOrg( hWnd );

.

.

.

switch( wMsg )

{

case WM_MOVE:

dx    = (int) (LOWORD(lParam) - LOWORD(dwOrg));	// X increment

dy    = (int) (HIWORD(lParam) - HIWORD(dwOrg));	// Y increment

dwOrg = (DWORD) lParam;	// Keep new org

OffsetPenData( hpendata, dx, dy );

See Also

MetricScalePenData, ResizePenData


PeekPenInput [New - Windows 95]
 PeekPenInput

2.0      [New - Windows 95]

Retrieves information about a specified pen packet in the pen input queue. For a definition of pen packet, see the description of SetPenHook.

int PeekPenInput( HPCM hpcm, UINT idEvent, LPPOINT lppt, LPVOID lpvOem, UINT fuOemFlags )

Parameters

hpcm

Handle to a pen collection. This is the return value from StartPenInput.

idEvent

The identifier of the packet to be retrieved. The idEvent is the low-order word of the value returned from the Windows GetMessageExtraInfo function when processing a WM_LBUTTONDOWN message.

lppt

Far pointer to a POINT structure. PeekPenInput copies the point corresponding to idEvent into the buffer pointed to by lppt.

lpvOem

The address of a buffer of OEM data in the packet. This parameter can be NULL if no OEM data is required.

fuOemFlags

Flags specifying which OEM data to retrieve. If this parameter is NULL, all of the OEM data provided by the tablet is returned in the order specified by the rgoempeninfo array in PENINFO.

These flags have an implicit order. For example, if pressure and barrel rotation are specified in that order, cPntMax pairs of these data are returned in the same order: [pressure, rotation], [pressure, rotation], and so on. (cPntMax is the number of POINT structures specified in GetPenInput.)

Constant	Description
PHW_PRESSURE	Retrieve pressure data.
PHW_HEIGHT	Retrieve height data.
PHW_ANGLEXY	Retrieve data pertaining to the x- and y-coordinates.
PHW_ANGLEZ	Retrieve data pertaining to the z-coordinates.
PHW_BARRELROTATION	Retrieve barrel-rotation data.
PHW_OEMSPECIFIC	Retrieve OEM-specific data.
PHW_PDK	Retrieve PDK_ data.
Return Value

Returns PCMR_OK if successful; otherwise, the return value can be one of the following:

Constant	Description
PCMR_INVALIDCOLLECTION	The hpcm handle is invalid because the calling application did not start input with StartPenInput.
PCMR_INVALID_PACKETID	idEvent is invalid.
Comments

Unlike GetPenInput, this function does not remove data from the pen input queue. It only returns information about the packet specified by idEvent.

Whereas lppt points into the pen input queue, lpvOem does not. If lpvOem is not NULL, it points to a buffer provided by the caller into which the OEM data are copied from the pen input queue.

The buffer that lpvOem points to must be large enough to hold the requested OEM data copied from the packet. The size of each packet is the width specified in the cbOemData member of the PENINFO structure, plus sizeof( UINT ) if PDK_ values are required.

See Also

GetPenInput,  PENPACKET,  PDK_


PenDataFromBuffer [New - Windows 95]
 PenDataFromBuffer

2.0      [New - Windows 95]

Creates a HPENDATA object from serial data in a buffer. The buffer must have been previously written by the PenDataToBuffer function.

LONG PenDataFromBuffer( LPHPENDATA lphpndt, UINT gmemFlags, LPBYTE lpBuffer, LONG cbBuf, LPDWORD lpdwState )

Parameters

lphpndt

Pointer to an uninitialized HPENDATA handle. If PenDataFromBuffer returns successfully, lphpndt points to a new HPENDATA object containing a copy of the serial points.

gmemFlags

Flag that specifies whether or not the Windows GlobalAlloc function should create a shared memory object when the pen data object is created. This should be either 0 or GMEM_DDESHARE. The GMEM_MOVEABLE and GMEM_ZEROINIT flags are added to this value and other GMEM_ flags are ignored.

lpBuffer

Pointer to a byte buffer containing serial data.

cbBuf

Size of the buffer, which must be at least 64 bytes in size. If the buffer serves as an intermediate holding area, it need not be as large as the final HPENDATA object. To create the object, the application must call PenDataFromBuffer successively, each time reading a new section of data into the buffer that lpBuffer points to before the call. The example below illustrates this technique by filling an HPENDATA object in stages, reading data from a file in cbBuf increments.

lpdwState

Address of a DWORD variable used by the system to maintain the transfer state. The DWORD variable must be initialized to 0 before the first call to PenDataFromBuffer. Between successive calls to PenDataFromBuffer, the application must not alter the value that lpdwState points to. lpdwState can be NULL to signify that the buffer contains the entire data set for the HPENDATA object. This implies that subsequent calls to PenDataFromBuffer are not necessary.

Return Value

If successful, PenDataFromBuffer returns the number of bytes transferred from the buffer. If the size of the pen data is larger than the buffer, the return value is equal to the buffer size passed in cbBuf. A value of 0 indicates no more data to transfer. If there is an error, one of the following negative values is returned:

Constant	Description
PDR_ERROR	Parameter or overflow error.
PDR_MEMERR	Memory error.
Comments

The data being provided by the application must have been previously written by the PenDataToBuffer function. The application cannot modify this data in any way. Embedded values within the first 64 bytes provide information to PenDataFromBuffer about the size of the pen data.

PenDataFromBuffer creates an HPENDATA object and provides a handle to it. The application must destroy the object when finished. The lphpndt argument points to a valid HPENDATA handle only if the function returns PDR_OK.

While this function is reconstituting the HPENDATA object, the application must not attempt to use it in any way because it will be invalid until the last buffer is read.

Example

The following example shows how to create a HPENDATA object from a file (hfile) that has already been opened for reading. Before reading the pen data, its length is retrieved from the file:

#define cbBufMax	1024

HPENDATA NEAR PASCAL ReadPenData( HFILE hfile )

{

HPENDATA	hpndt = NULL;

LONG	cb, cbRead, cbHpndt;

BYTE	lpbBuf[cbBufMax];	// Buffer

DWORD	dwState = 0L;	// Must initialize to 0

if (!hfile

|| (cb = _lread(hfile, &cbHpndt, sizeof(DWORD))) == HFILE_ERROR

|| cb != sizeof(LONG))

return NULL;

while (cbHpndt > 0)

{

if ((cbRead = _lread( hfile, lpbBuf, min(cbHpndt, cbBufMax )))

== HFILE_ERROR

|| PenDataFromBuffer( &hpndt, 0, lpbBuf,

  cbBufMax, &dwState ) < 0)

{

if (hpndt)

DestroyPenData( hpndt );

return NULL;

}

cbHpndt -= cbRead;

}

return hpndt;

}

See Also

PenDataToBuffer,  GetPenDataAttributes


PenDataToBuffer [New - Windows 95]
 PenDataToBuffer

2.0      [New - Windows 95]

Writes the data in an existing HPENDATA object to a serial buffer.

LONG PenDataToBuffer( HPENDATA hpndt, LPBYTE lpBuffer, LONG cbBuf, LPDWORD lpdwState )

Parameters

hpndt

Handle to the HPENDATA object.

lpBuffer

Pointer to an empty buffer.

cbBuf

Size of the buffer in bytes. The buffer must be at least 64 bytes in size. If the buffer serves as an intermediate holding area, it need not be as large as the HPENDATA object. To read all data from the object in this case, the application must call PenDataToBuffer successively, each time copying the data from the buffer that lpBuffer points to before the next call. The example below illustrates this technique by writing an HPENDATA object in cbBuf increments to a file.

lpdwState

Address of a DWORD variable used by the system to maintain the transfer state. The DWORD variable must be initialized to 0 before the first call to PenDataToBuffer. Between successive calls to PenDataToBuffer, the application must not alter the value that lpdwState points to. lpdwState can be NULL to signify that the buffer is large enough to contain the entire HPENDATA object. This implies that subsequent calls to PenDataToBuffer are not necessary.

Return Value

If successful, PenDataToBuffer returns the number of bytes transferred into the buffer. If the size of the pen data is larger than the buffer, the return value is equal to the buffer size passed in cbBuf until the final transfer, when it is typically some smaller value. A value of 0 indicates no more data to transfer. If there is an error, one of the following negative values is returned:

Constant	Description
PDR_ERROR	Parameter or other unspecified error.
PDR_MEMERR	Memory error.
PDR_PNDTERR	Invalid HPENDATA object.
PDR_VERSIONERR	Could not convert old HPENDATA object.
Comments

The buffer need not be large enough to accommodate the entire HPENDATA object. To allocate a buffer large enough for a single transfer, the application can determine the required size with the GetPenDataAttributes subfunction GPA_SIZE .

Example

The following example shows how to save an HPENDATA object to a file (hfile) that has already been opened for writing. The length of the pen data is saved in the file before writing the pen data itself:

#define cbBufMax	1024

BOOL NEAR PASCAL	WritePenData( HFILE hfile, HPENDATA hpndt )

{

BYTE    lpbBuf[cbBufMax];

DWORD   dwState = 0L;	// Must initialize to zero

LONG    cb;

LONG    cbSize;

if (!hfile || !hpndt)

return FALSE;

// Get size and save to file

if (GetPenDataAttributes(hpndt, (LPVOID)&cbSize, GPA_SIZE) < 0)

return FALSE;

// write size of pen data to file so that it can be used while reading it back

if (_lwrite(hfile, &cbSize, sizeof(LONG)) == HFILE_ERROR)

return FALSE;

// Write the pen data in chunks, and repeat until done

while ((cb = PenDataToBuffer(hpndt, lpbBuf,

  cbBufMax, &dwState )) > 0L)

{

if (_lwrite( hfile, lpbBuf, (UINT)cb ) == HFILE_ERROR)

return FALSE;

}

return (cb >= 0L);	// Return TRUE if cb >= 0

}

See Also

PenDataFromBuffer


PostVirtualKeyEvent [New - Windows 95]
 PostVirtualKeyEvent

1.0     2.0      [New - Windows 95]

Posts a virtual key-code event to Windows.

void PostVirtualKeyEvent( UINT vk, BOOL fUp )

Parameters

vk

Virtual key. This argument takes a Windows VK_ constant as defined in the WINDOWS.H include file. Depending on the key, this is either the key scan code or the ASCII equivalent to represent a character key. For example, VK_A has the value "A."

fUp

Key-transition flag. This parameter should be FALSE to specify that the key is down or TRUE to specify that it is up.

Return Value

This function does not return a value.

Comments

PostVirtualKeyEvent does not check the virtual key code for errors.

Normally, an application should follow a key-down message with a corresponding key-up message to accurately simulate the actual events from the keyboard. You can post repeating keys by calling PostVirtualKeyEvent consecutively, one call per repeat, with fUp set to FALSE. End the sequence with a single call to PostVirtualKeyEvent with fUp set to TRUE.

The events are posted to the system message queue. The application with the input focus can receive the messages by calling the Windows GetMessage or PeekMessage function.

See Also

AtomicVirtualEvent, PostVirtualMouseEvent


PostVirtualMouseEvent [New - Windows 95]
 PostVirtualMouseEvent

1.0     2.0      [New - Windows 95]

Posts a virtual mouse code to Windows.

void PostVirtualMouseEvent( UINT wMouseFlags, int xPos, int yPos )

Parameters

wMouseFlags

Flags indicating the type of mouse event. This can be one or more of the following values, combined by a bitwise-OR operator.

Constant	Description
VWM_MOUSEMOVE	Simulates a change in the mouse cursor position. This flag can be combined with any of the other flags in this table.
VWM_MOUSELEFTDOWN	Simulates pushing the left mouse button.
VWM_MOUSELEFTUP	Simulates releasing the left mouse button.
VWM_MOUSERIGHTDOWN	Simulates pushing the right mouse button.
VWM_MOUSERIGHTUP	Simulates releasing the right mouse button.
xPos

The x-axis position in screen coordinates.

yPos

The y-axis position in screen coordinates.

Return Value

This function does not return a value.

Comments

The x- and y-axis positions are absolute positions in screen coordinates. Note that the x and y values should not exceed the screen-resolution limits. Values greater than the maximum resolution in the x-direction (640 for standard VGA) or the y-direction (480 for standard VGA) cause an overflow.

The events are posted to the system message queue. The application with the input focus can receive the messages by calling the Windows GetMessage or PeekMessage message.

Because of the way Windows interprets mouse messages, the calling application must be careful about the order in which events are sent to the system. A message that represents both a button-state transition and a move generates first a Windows event for the button transition at the current pointer location and then a move to the new location. To simulate a move to a new location followed by a button transition, the application must make separate calls to PostVirtualMouseEvent for each simulated event.

Example

When posting events, the caller should bracket the calls by calls to AtomicVirtualEvent, which locks out pen packets while the application is posting simulated mouse events. For example, the following code fragment posts a mouse event:

AtomicVirtualEvent(TRUE);

//

//  ... PostVirtualMouseEvent calls go here

//

AtomicVirtualEvent(FALSE);

The Windows GetMessageExtraInfo function returns 0 for any messages generated by PostVirtualMouseEvent.

See Also

AtomicVirtualEvent, PostVirtualKeyEvent


ProcessHRC [New - Windows 95]
 ProcessHRC

2.0      [New - Windows 95]

Gives a recognizer sufficient time for intermediate processing of pen input. A recognizer must export this function.

int ProcessHRC( HRC hrc, DWORD dwTimeMax )

Parameters

hrc

Handle to the HRC object for the recognizer.

dwTimeMax

The maximum time in milliseconds that the recognizer should process before returning from this call. This parameter can also be one of the following time-out codes:

Constant	Description
PH_MIN	The recognizer should take only a very small amount of time to process the input, typically 50 milliseconds.
PH_DEFAULT	The recognizer should take a moderate amount of time to process the input, typically 200 milliseconds.
PH_MAX	The recognizer should take as much time as required to complete recognition.
Return Value

If there are no errors, returns one of the following values:

Constant	Description
HRCR_OK	Processing is successful.
HRCR_INCOMPLETE	The recognizer is still processing the current batch of input.
HRCR_GESTURE	The recognizer has recognized a possible gesture.  This can be returned before the recognition process  is complete. If the processing completes, HRCR_COMPLETE is always returned, even for gestures.
HRCR_COMPLETE	The recognizer completed processing and does not expect any more input.
To indicate an error, ProcessHRC returns one of the following negative values:

Constant	Description
HRCR_ERROR	Invalid parameter or other error.
HRCR_MEMERR	Insufficient memory.
Comments

ProcessHRC returns if the time specified by dwTimeMax elapses before recognition is complete.

In an operating environment that does not use threads, this function allows an application to provide some time for the recognizer to process input. By checking the return value, the application is able to monitor the progress, specifically whether a gesture is a recognition candidate. If the function returns HRCR_GESTURE, the application can call GetResultsHRC to determine whether the gesture should be acted on immediately.

Typically, the return value is HRCR_OK if the current batch of ink input has been processed by the recognizer, and HRCR_INCOMPLETE if the recognizer has not yet finished processing.

If ProcessHRC is called with PH_MAX, recognition is complete only if EndPenInputHRC has been called to notify the recognizer that no more results are expected. The return value in this case is HRCR_COMPLETE, and the application is free to get and display final results. If the application supplies further input at this point, it has the effect of canceling the EndPenInputHRC call, although this procedure is not recommended for reasons of efficiency.

However, PH_MAX may result in poorer performance, since further processing in the system is blocked until ProcessHRC returns. Instead, the application can call ProcessHRC in an idle loop or a separate thread, calling it repeatedly with smaller time allotments until the function returns HRCR_COMPLETE. Note that if a separate thread is used to finish processing, the main thread can call this function with PH_MIN from time to time to determine if processing has finished (that is, checking for the HRCR_COMPLETE return value).

The first time that ProcessHRC is called for a particular recognition context, functions that set its state cannot be used for the remainder of that context's existence. The following functions return an error if they are called before ProcessHRC returns HRCR_COMPLETE:

•	EnableGestureSetHRC

•	EnableSystemDictionaryHRC

•	SetAlphabetHRC

•	SetAlphabetPriorityHRC

•	SetBoxAlphabetHRC

•	SetWordlistCoercionHRC

•	SetGuideHRC

•	SetInternationalHRC

•	SetMaxResultsHRC

•	SetWordlistHRC

See Also

EndPenInputHRC, GetResultsHRC


ProcessWriting [New - Windows 95]
 ProcessWriting

1.0     2.0      [New - Windows 95]

Processes handwriting.

Note  This function is provided only for compatibility with version 1.0 of the Pen API and will not be supported in future versions. Use DoDefaultPenInput instead.

REC ProcessWriting( HWND hwnd, LPRC lprc )

Parameters

hwnd

Window to receive messages. This parameter must not be NULL.

lprc

Address of RC structure to use for recognition. This parameter can be NULL.

Return Value

Returns values less than 0 if the application should treat the event as a mouse event instead of a pen event. Return values less than 0 occur if the event did not come from a pen, the user performed a press-and-hold action (REC_POINTEREVENT), or an error occurred—for example, running out of memory.

Comments

The ProcessWriting function is similar to Recognize except that ProcessWriting also takes care of inking, removing the ink, and converting the results message to standard Windows messages.

Depending on the existing code in an application, ProcessWriting may not be suitable for making an application pen-aware. This function can also limit the power of a pen interface.

If lprc is NULL, a default RC structure is created for the application. The default RC structure contains all system defaults and the inking is constrained to the client area of hwnd. If lprc points to a valid RC structure, the rectBound member of the RC structure is used to constrain the inking. Regardless of whether the application provides an RC or not, ProcessWriting assumes a value of RRM_COMPLETE for the wResultMode member. See RC for a description of wResultMode and the RRM_ values.

After the writing is completed, the ink is removed before any messages are sent to hwnd. After the ink is removed, the screen is updated and hwnd receives a WM_RCRESULT message. If the application processes this message, it should return TRUE. In this case, no further messages are sent.

If the application returns FALSE, ProcessWriting performs the default conversion of the results message to standard Windows messages, as shown in the following table. The messages are sent rather than posted. Note that the DefWindowProc function returns 0 when processing the WM_RCRESULT message.

Results message	Windows message
SYV_BACKSPACE	WM_LBUTTONDOWN, followed by WM_LBUTTONUP at the hot spot of the gesture, followed by WM_CHAR specifying a backspace.
SYV_CLEAR	WM_CLEAR.
SYV_CLEARWORD	WM_LBUTTONDOWN, WM_LBUTTONUP, WM_LBUTTONDBLCLK, WM_LBUTTONUP at the same point, followed by WM_CLEAR.
SYV_COPY	WM_COPY.
Results message	Windows message
SYV_CORRECT	WM_LBUTTONDOWN, WM_LBUTTONUP, WM_LBUTTONDBLCLK, WM_LBUTTONUP at the hot spot of the gesture, followed by WM_COPY. At this point the Edit Text dialog box is activated; it retrieves text from the Clipboard. This uses the existing selection, if any. The previous contents of the Clipboard are lost.
SYV_CUT	WM_CUT.
SYV_EXTENDSELECT	WM_LBUTTONDOWN, followed by WM_LBUTTONUP at the hot spot of the gesture.  The MK_SHIFT flag is set for the wParam of these messages.
SYV_LASSO	WM_LBUTTONDOWN at upper-left corner of selected area, followed by WM_MOUSEMOVE message, followed by WM_LBUTTONUP at the lower-right corner of selected area.
SYV_PASTE	WM_LBUTTONDOWN, followed by WM_LBUTTONUP at the hot spot of the gesture, followed by WM_PASTE.
SYV_RETURN	WM_LBUTTONDOWN, followed by WM_LBUTTONUP at the hot spot of the gesture, followed by WM_CHAR specifying a carriage return.
SYV_SPACE	WM_LBUTTONDOWN, followed by WM_LBUTTONUP at the hot spot of the gesture, followed by WM_CHAR specifying a space.
SYV_TAB	WM_LBUTTONDOWN, followed by WM_LBUTTONUP at the hot spot of the gesture, followed by WM_CHAR specifying a tab.
SYV_UNDO	WM_UNDO.
text	One WM_CHAR message per character of text.
The SYV_ symbol values in the previous table identify gestures. To see a complete list of symbol values, refer to Chapter 13, "Pen Application Programming Interface Constants."

The lParam of a WM_RCRESULT message generated by ProcessWriting is a far pointer to an RCRESULT structure. By default, when an application receives a WM_RCRESULT message, the hpendata member of the RCRESULT structure is NULL. If you need the HPENDATA handle, set the RCO_SAVEHPENDATA flag in the lRcOptions member of the RC structure. In this case, the calling application is responsible for destroying the HPENDATA object.

See Also

DoDefaultPenInput, InitRC, Recognize, REC_, SYV_, RCO_


ReadHWL [New - Windows 95]
 ReadHWL

2.0      [New - Windows 95]

Reads a word list from a file.

int ReadHWL( HWL hwl, HFILE hfile )

Parameters

hwl

A handle to an empty word list.

hfile

A handle to a file previously opened for reading.

Return Value

Returns HRCR_OK if successful; otherwise, returns one of the following negative values:

Constant	Description
HRCR_ERROR	Invalid parameter or file or other error.
HRCR_MEMERR	Insufficient memory.
Comments

The words are expected as ANSI text, one word per line, followed by a carriage return and linefeed. In this context, a word can represent a phrase and contain spaces or other noncharacters, such as "New York" and "ne'er-do-well." Empty lines or lines containing only spaces or tabs are allowed but ignored.

The file that hfile refers to must already exist and be open for reading.

The hwl parameter must be the handle of an empty word list created by CreateHWL. If the word list is not empty, ReadHWL returns HRCR_ERROR.

Once the file is read, it can be closed immediately.

Example

The following example demonstrates how to provide a word list to constrain recognition results to the words contained in the fictitious file COUNTRY.LST:

HWL	  hwlCountries = CreateHWL( NULL, NULL, WLT_EMPTY, 0L );

OFSTRUCT	  ofStruct;

HFILE	  hfile = OpenFile( "country.lst", &ofStruct, OF_READ );

if (hfile != HFILE_ERROR)

{

ReadHWL(hwlCountries, hfile);

_lclose(hfile);

}

else

ErrorMsg(FILEOPEN);

.

.

.

if (hrc = CreateCompatibleHRC( NULL, NULL ))

{

SetWordlistHRC( hrc, hwlCountries );	    // Set list into HRC

SetWordlistCoercionHRC( hrc, SCH_FORCE );  // Force match

.

.     // Code that collects and recognizes input here

.

}

See Also

CreateHWL, WriteHWL


Recognize [New - Windows 95]
 Recognize

1.0     2.0      [New - Windows 95]

Begins sampling pen data and converts tablet input to recognized symbols.

Note  This function is provided only for compatibility with version 1.0 of the Pen API and will not be supported in future versions.

REC Recognize( LPRC lprc )

Parameters

lprc

Address of an RC structure.

Return Value

Returns an REC_ value. See the "Comments" section for a description of the return values.7

Comments

The RC structure that lprc points to contains the parameters that control recognition. The system sends recognition results via the WM_RCRESULT message to the window indicated by the hwnd member of the RC. All results messages are sent before Recognize returns. Multiple result messages can be sent if the application asks for results to be sent to the application before all input has been completed (as indicated by the wResultMode member of the RC structure).

An application that uses version 1.0 recognizers should call Recognize when the input session begins, signaled by the WM_LBUTTONDOWN message.

The value REC_OK is used in the wParam of the WM_RCRESULT message to indicate that more data is coming. Return values of greater than 0 signal normal successful completion. Return values of less than 0 indicate abnormal termination. Return values of less than REC_DEBUG are reserved for return values from

debugging versions of the system or recognizer. If an application creates a condition that would be caught in a debugging version while running a nondebugging version, the results are undefined.

Each return value can be the wParam value of the WM_RCRESULT message or the return value for Recognize. The wParam value of the last WM_RCRESULT message generated by a call to Recognize is the return value of Recognize. Some error conditions, such as REC_OOM or REC_NOTABLET, are returned without generating any corresponding WM_RCRESULT message.

All of the values listed in the following table are in the debug version only. No WM_RCRESULT message is generated if these values are returned by Recognize.

Constant	Description
REC_ALC	Invalid enabled alphabet.
REC_BADEVENTREF	Returned when the wEventRef member in the lprc structure is invalid.
REC_CLVERIFY	Invalid verification level.
REC_DEBUG	All debugging return values are less than this.
REC_DICT	Invalid dictionary parameters.
REC_ERRORLEVEL	Invalid error level.
REC_GUIDE	Invalid GUIDE structure.
REC_HREC	Invalid recognition handle.
REC_HWND	Invalid handle to window to send results to.
REC_INVALIDREF	Invalid data reference parameter.
REC_LANGUAGE	Returned by the recognizer when the lpLanguage member contains a language that is not supported  by the recognizer. Call ConfigRecognizer with the WCR_QUERYLANGUAGE subfunction to determine whether a particular language is supported.
REC_NOCOLLECTION	In version 1.0, was returned by GetPenHwData if collection mode has not been set. Not used now.
REC_OEM	Error codes less than or equal to REC_OEM are specific to the recognizer.
REC_PCM	Invalid lPcm member in the RC structure. There is no way for the recognition to end.
REC_RECTBOUND	Invalid rectangle.
REC_RECTEXCLUDE	Invalid rectangle.
REC_RESULTSMODE	Unsupported results mode requested.
See Also

InitRC, RecognizeData, GetPenHwEventData,  RC,  REC_


RecognizeData [New - Windows 95]
 RecognizeData

1.0     2.0      [New - Windows 95]

Converts the data in an HPENDATA object to recognized symbols.

Note  This function is provided only for compatibility with version 1.0 of the Pen API and will not be supported in future versions.

REC RecognizeData( LPRC lprc, HPENDATA hpndt )

Parameters

lprc

Address of an RC structure.

hpndt

Handle to an HPENDATA object.

Return Value

Returns REC_DONE if successful, or an REC_ error code if an error occurs.

Comments

RecognizeData recognizes data in an HPENDATA object and returns the results to the window specified in the RC structure. RecognizeData is similar to Recognize. The difference is that in RecognizeData, the input data comes from a buffer of points already collected instead of from the tablet driver. Members pertaining to the end of recognition in the RC structure are ignored.

RecognizeData can return REC_BUSY if the recognizer is not reentrant. A recognizer is not guaranteed to return the same results for identical input. This is because persistent states, such as the current average size of writing or the position of the baseline, can affect recognition results. In addition, training may change the prototypes against which the data is being compared.

RecognizeData attempts to convert the pen data to PDTS_STANDARDSCALE if it is not already in standard scale. If the conversion fails (for example, because the data was in an application-specific scale PDTS_ARBITRARY), the data is still passed to the recognizer. A recognizer may return an error code (REC_BADHPENDATA) for data in a scale it cannot handle.

See Also

InitRC, Recognize, GetPenHwEventData, RC, REC_,  PDTS_


RedisplayPenData [New - Windows 95]
 RedisplayPenData

1.0     2.0      [New - Windows 95]

Redraws the pen data in the same manner as originally inked.

BOOL RedisplayPenData( HDC hdc, HPENDATA hpndt, LPPOINT lpDelta, LPPOINT lpExt, int nInkWidth, DWORD rgbColor )

Parameters

hdc

Handle to a device context. The mapping mode should be MM_TEXT.

hpndt

Handle to a pen data object. The pen data must be scaled to PDTS_DISPLAY or PDTS_STANDARDSCALE.

lpDelta

An offset, in logical units, that is subtracted from the pen data points to position the ink. If lpDelta is NULL, there is no offset.

lpExt

Extent, in logical units, for scaling. If lpExt is NULL, no scaling is performed.

nInkWidth

Width of the ink to be drawn, in pixels (1 to 15). If nInkWidth is −1, the strokes are rendered using the original ink width stored in the stroke header. An ink width of 0 causes the function to simply return TRUE.

rgbColor

RGB value of the color to draw the ink. If rgbColor is 0xFFFFFFFF, the strokes are rendered using the original ink color stored in the stroke header.

Return Value

Returns TRUE if successful; otherwise FALSE.

Comments

The nInkWidth and rgbColor values override the pen currently selected for the hdc device context.

If the mapping mode of the hdc device context is not MM_TEXT, two problems can occur:

•	RedisplayPenData uses TPtoDP to prepare the pen data points for rendering. After this, the points are in MM_TEXT coordinates; this assumes an MM_TEXT device context for display. If the device context is in a different mapping mode, the ink coordinates will not be correct. Even if you use the ink-scaling functions to bypass this problem, you will still encounter rounding-error problems between the two scalings.

•	No matter what scaling is done, rounding errors occur when converting between modes. These errors cause the ink to shift slightly when repainted.

For any rendering into a device context that represents anything other than a display device context, DrawPenDataEx should be used. This is because RedisplayPenData makes assumptions that are not optimal for other devices such as printers or metafiles.

RedisplayPenData provides the ability to re-create original inking perfectly. To do this, an application can use either of two methods:

•	After the input session ends and data is collected into an HPENDATA object, store the current origin of the window containing the ink. When calling RedisplayPenData to redraw the ink, supply the origin value in the lpDelta argument, set lpExt to NULL, and set the mapping mode of the device context to MM_TEXT. Only ink data with a common window origin can be merged into a single HPENDATA.

•	In the second method, the application must call two Pen functions immediately after collecting the data into an HPENDATA object. The first call to MetricScalePenData converts the pen data to display coordinates. The second call to OffsetPenData sets the display coordinates relative to the window containing the original ink. To display, the application must call RedisplayPenData with lpDelta and lpExt set to NULL and the mapping mode of the device context set to MM_TEXT. If the application adopts this method for multiple HPENDATA objects, it can later merge them to form a single HPENDATA object (up to the 64K limit).

The second method has the advantages of simplicity and data compression. See the description of MetricScalePenData for a discussion of the limitations of converting data to display resolution.

Since the pen data has the origin of (0,0) based on the upper-left corner of the display, applications must move from a screen-relative position to a position relative to the device context. To do this, subtract the origin of the device context (in screen coordinates) from the object currently residing in screen-coordinate space.

The lpDelta parameter enables the application to render ink relative to the window instead of relative to the screen. An application should call the ClientToScreen function for (0,0) to find the proper screen coordinates to be placed in the *lpDelta POINT structure. Once this is done, the pen data is rendered at the appropriate location in window coordinates. If lpDelta is NULL, no offset for the data is assumed.

The lpExt argument specifies the extents into which the data should be scaled. If extents are provided, data is scaled into a rectangle described by lpDelta and lpExt. The values of x and y in lpExt and lpDelta are in the mapping mode of the device context into which the data is rendered.

RedisplayPenData displays pen data with a square graphical device interface (GDI) pen brush for maximum drawing speed. When displaying wide lines of ink, this optimization can cause the ends of abutting lines to appear blocky. If you prefer a smoother look to the joints of wide lines at the expense of rendering speed, draw the ink with DrawPenData, DrawPenDataEx, or DrawPenDataFmt instead of RedisplayPenData. These functions draw wide lines by flood-filling a region, thus smoothing the ends.

See Also

DrawPenData,  DrawPenDataEx,  PDTS_


RegisterPenApp [New - Windows 95]
 RegisterPenApp

1.0     2.0      [New - Windows 95]

Notifies the pen system that the application edit controls should be replaced with hedit controls. This function is required only for applications that specify EDIT class (instead of HEDIT class) for control windows with versions of Windows earlier than Windows 95.

Note that this function has been superseded by the SetPenAppFlags function in the 2.0 version of the Pen API, although calling RegisterPenApp is still supported. See SetPenAppFlags for more information.

void RegisterPenApp( UINT fuFlags, UINT uVersion )


RemovePenDataStrokes [New - Windows 95]
 RemovePenDataStrokes

2.0      [New - Windows 95]

Removes strokes from an HPENDATA object.

int RemovePenDataStrokes( HPENDATA hpndt, UINT iStrk, UINT cStrks )

Parameters

hpndt

Handle to the HPENDATA object.

iStrk

Zero-based index of the first stroke to remove. This value can be IX_END to remove the last stroke. The function fails if iStrk is greater than the number of strokes in the pen data object.

cStrks

Count of strokes to remove. If this value is greater than the number of strokes after the specified stroke index, the stroke indexed by iStrk and all following strokes are removed. cStrks can be IX_END to remove all strokes from iStrk onward.

Return Value

Returns PDR_OK if successful; otherwise, the return value can be one of the following negative values:

Constant	Description
PDR_COMPRESSED	Pen data is compressed.
PDR_ERROR	Parameter or other unspecified error.
PDR_MEMERR	Out of memory.
PDR_PNDTERR	Invalid pen data object.
PDR_STRKINDEXERR	Invalid stroke index.
PDR_VERSIONERR	Could not convert old pen data object.
Comments

RemovePenDataStrokes removes the number of strokes specified by cStrks, starting at the stroke specified by iStrk. Use ExtractPenDataPoints to remove points from a particular stroke of the pen data object.

See Also

ExtractPenDataPoints, InsertPenDataPoints, InsertPenDataStroke


ResizePenData [New - Windows 95]
 ResizePenData

1.0     2.0      [New - Windows 95]

Scales ink in an HPENDATA object into an arbitrarily sized rectangle.

BOOL ResizePenData( HPENDATA hpndt, LPRECT lprect )

Parameters

hpndt

Handle to a pen data object.

lprect

Address of a bounding rectangle, or NULL.

Return Value

Returns TRUE if successful; otherwise, the return value is FALSE.

Comments

This function changes the physical size of the object without changing the meaning of the measurements. Use the MetricScalePenData function to convert the data to one of the supported metric modes of measurement.

ResizePenData physically resizes the data in hpndt to the bounding rectangle dimensions given by the lprect parameter. Data from hpndt is mapped to the new rectangle. If lprect is NULL, this function recalculates the bounding rectangle (the rectBound member in the PENDATAHEADER structure). For example, consider the case of pen data with PDTS_HIMETRIC scaling bounded by the square (500, 600, 1500, 1600). To double the size, set lprect to (500, 600, 2500, 2600).

See Also

OffsetPenData, MetricScalePenData, PDTS_


ResultsHookHREC [New - Windows 95]
 ResultsHookHREC

2.0      [New - Windows 95]

The ResultsHookHREC function is an application-defined callback function that provides the application with the opportunity to view all recognition results before they are returned to the application. The name ResultsHookHREC is a placeholder; the function can have any name.

BOOL CALLBACK ResultsHookHREC( HREC hrec, HRC hrc, WORD wHooktype, UINT cResults, UINT cAlt, LPVOID rgresults )

Parameters

hrec

Module handle of the recognizer library whose results are being hooked.

hrc

Handle to the HRC object for the recognizer that hrec refers to.

wHooktype

Type of hook. This can be one of the following values:

RHH_STD

Standard results generated by GetResultsHRC.

RHH_BOX

Boxed results generated by GetBoxResultsHRC.

cResults

Count of results available.

cAlt

Count of box alternatives. This is valid only if wHooktype is RHH_BOX.

rgresults

An array of result objects. The object type depends on wHooktype. If RHH_STD, rgresults should be cast as LPHRCRESULT and the array receives cResults HRCRESULT objects. If RHH_BOX, rgresults should be cast as LPBOXRESULTS and the array receives cResults BOXRESULTS structures.

Return Value

The application hook function should return TRUE to indicate that it has processed the data and that the recognizer should do no further processing. In this case, it is the application's responsibility to destroy the results and inksets, if any; otherwise, the hook function should return FALSE.

See Also

SetResultsHookHREC


SetAlphabetHRC [New - Windows 95]
 SetAlphabetHRC

2.0      [New - Windows 95]

Specifies which alphabet should be used in an HRC object.

int SetAlphabetHRC( HRC hrc, ALC alc, LPBYTE rgbfAlc )

Parameters

hrc

Handle to the HRC object.

alc

Alphabet. This value is one or more ALC_ values combined using the bitwise-OR operator.

rgbfAlc

Array of bits if alc contains ALC_USEBITMAP; otherwise, it can be NULL.

Return Value

Returns HRCR_OK if successful; otherwise, returns one of the following negative values:

Constant	Description
HRCR_ERROR	Invalid parameter or other error.
HRCR_MEMERR	Insufficient memory.
HRCR_UNSUPPORTED	The recognizer does not support this function.
Comments

Some recognizers may not support ALC_ values and alphabet priorities. An application should check for HRCR_UNSUPPORTED when using this function.

The following values may require Japanese, wide-character, or recognizer-specific support: ALC_DBCS, ALC_JIS1, ALC_KANJI, ALC_OEM, ALC_HIRAGANA, and ALC_KATAKANA. In addition, ALC_RESERVED is reserved for future use and is ignored. Recognizers, such as the Microsoft Handwriting Recognizer (GRECO.DLL) for default American English, can return HRCR_OK even if some of these values are set.

The size of the rgbfAlc array, if used, must be large enough to accommodate 256 bits (32 bytes). If the nth bit is set, then the nth ANSI character is recognizable. Bits representing characters less than 32 (space) currently have no meaning.

The ALC_GESTURE value is ignored, even if it is part of the alc parameter. See EnableGestureSetHRC.

For a description of alphabets and their relationship to a recognizer, see "Configuring the HRC" in Chapter 5, "The Recognition Process." For a list of alphabet codes, see Chapter 13, "Pen API Constants."

See Also

EnableGestureSetHRC, GetAlphabetHRC

SetAlphabetPriorityHRC, ALC_


SetAlphabetPriorityHRC [New - Windows 95]
 SetAlphabetPriorityHRC

2.0      [New - Windows 95]

Specifies the priority of alphabet sets in an HRC object.

int SetAlphabetPriorityHRC( HRC hrc, ALC alc, LPBYTE rgbfalc )

Parameters

hrc

Handle to the HRC object.

alc

Alphabet priority. This value is one or more ALC_ values combined using the bitwise-OR operator.

rgbfalc

Address of a 256-bit (32-byte) buffer whose bits map to ANSI single-byte characters if alc contains ALC_USEBITMAP; otherwise, it can be NULL.

Return Value

Returns HRCR_OK if successful; otherwise, returns one of the following negative values:

Constant	Description
HRCR_ERROR	Invalid parameter or other error.
HRCR_MEMERR	Insufficient memory.
HRCR_UNSUPPORTED	The recognizer does not support this function.
Comments

Some recognizers may not support ALC_ values and priorities. An application should check for HRCR_UNSUPPORTED when using this function.

For a description of how a recognizer uses alphabet priority, see "Configuring the HRC" in Chapter 5, "The Recognition Process." For a list of alphabet codes, see Chapter 13, "Pen Application Programming Interface Constants."

See Also

GetAlphabetHRC, SetAlphabetHRC, GetAlphabetPriorityHRC, ALC_


SetBoxAlphabetHRC [New - Windows 95]
 SetBoxAlphabetHRC

2.0      [New - Windows 95]

Specifies the alphabet codes to use for a range of boxes.

int SetBoxAlphabetHRC( HRC hrc, LPALC rgalc, UINT cAlc )

Parameters

hrc

Handle to an HRC object.

rgalc

An array of cAlc ALC_ values. The array is mapped onto boxes starting at box zero.

cAlc

Number of ALC_ values in rgalc. This should match the number of boxes. If this parameter is 0, SetBoxAlphabetHRC simply returns 0.

Return Value

Returns HRCR_OK if successful; otherwise, returns one of the following negative values:

Constant	Description
HRCR_ERROR	Invalid parameter or other error.
HRCR_MEMERR	Insufficient memory.
HRCR_UNSUPPORTED	The recognizer does not support this function.
Comments

SetBoxAlphabetHRC applies only when an HRC has been configured for box guides with the SetGuideHRC function. Although SetAlphabetHRC can also specify an alphabet set for boxed input, it attaches the same alphabet setting to all boxes indiscriminately. SetBoxAlphabetHRC offers greater control by allowing an application to set different alphabets for individual boxes of a single HRC.

Example

For example, consider a boxed entry on a requisition form that expects a part number consisting of five characters. The first two characters are uppercase letters, the next two are numerals, and the last character can be either another numeral or a lowercase revision code. The following example demonstrates how to configure the HRC for this hypothetical scenario:

#define  PART_LEN    5                  // Five characters in entry

HRC      hrcPart;                       // HRC for parts entry

GUIDE    guidePart;                     // GUIDE for parts entry

ALC      alcPart[PART_LEN];             // Array of ALC_ codes for entry

.

.                                   // Initialize the GUIDE here

.

guidePart.cHorzBox = PART_LEN;          // Number of boxes in entry

guidePart.cVertBox = 1;                 // Single row

guidePart.cyMid    = 0;                 // No midline

iret = SetGuideHRC( hrcPart, (LPGUIDE)&guidePart, 0 );

if (iret == HRCR_OK)

{

alcPart[0] = alcPart[1] = ALC_UCALPHA;  // Uppercase in boxes 1-2

alcPart[2] = alcPart[3] = ALC_NUMERIC;  // Numerals in boxes 3-4

alcPart[4] = ALC_LCALPHA | ALC_NUMERIC; // Lower or numeral in box 5

// Map alphabet codes onto boxes of parts number entry

SetBoxAlphabet( hrcPart, (LPALC)&alcPart, PART_LEN );

}

See Also

GetAlphabetHRC, SetAlphabetHRC, ALC_


SetGlobalRC [New - Windows 95]
 SetGlobalRC

1.0     2.0      [New - Windows 95]

Sets the current default settings for the global RC structure. In version 2.0 of the Pen API, the RC structure is made obsolete by the HRC object.

Note  This function is provided only for compatibility with version 1.0 of the Pen API and will not be supported in future versions.

UINT SetGlobalRC( LPRC lprc, LPSTR lpszDefRecog, LPSTR lpszDefDict )

Parameters

lprc

Address of an RC structure or NULL.

lpszDefRecog

Address of string specifying the name of the default recognizer module (maximum 128 bytes).

lpszDefDict

Address of a string specifying the default dictionary path. The list should end with two null characters.

Return Value

Returns the value SGRC_OK if successful. If an error occurs, the return value consists of one or more of the following values, combined using the bitwise-OR operator.

Constant	Description
SGRC_USER	An invalid user name was found in the supplied RC structure. The call to SetGlobalRC has no effect.
SGRC_PARAMERROR	One or more invalid parameters were detected. The call to SetGlobalRC has no effect.
SGRC_RC	The supplied recognition context lprc has entries, other than the user name, that contain invalid settings for a global recognition context. The supplied recognition context is ignored.
SGRC_RECOGNIZER	The supplied recognizer module name lpszDefRecog is invalid or the recognizer cannot be loaded. The supplied recognizer module name is ignored.
SGRC_DICTIONARY	The supplied dictionary path lpszDefDict is invalid or some dictionaries on the path cannot be loaded. The supplied dictionary path is ignored.
SGRC_INIFILE	An error was encountered while saving the new global recognition context settings to the pen section of the system registry. The new settings are lost after rebooting Windows.
Comments

Because the default RC values are shared among all version 1.0 applications running, the values should be changed only through the Control Panel. Whenever a change is made to the global RC values, the WM_PENMISCINFO message is sent to all top-level windows. The wParam and lParam values are not used, and they are set to 0.

Any of the parameters can be NULL to indicate that the calling application does not want the value changed.

SetGlobalRC uses only the following members of the RC structure pointed to by the lprc parameter:

clErrorLevel lPcm (PCM_TIMEOUT and PCM_RANGE bits)  lpLanguage lpUser nInkWidth rgbInk wCountry wIntlPreferences wRcDirect wRcPreferences wTimeOut wTryDictionary

When InitRC is called for a new recognizer from within the SetGlobalRC call, the RC structure that is passed in contains the new values for all members except hrec and rglpdf. No new recognizer and dictionaries have been set up at this point.

When a version 1.0 application receives a WM_PENMISCINFO message, it should call ConfigRecognizer with a WCR_RCCHANGE subfunction request. This should be done for all recognizers that the application has loaded, excluding the default recognizer. The RC Manager calls ConfigRecognizer in the new default recognizer with a WCR_RCCHANGE subfunction request.

SetGlobalRC does not save the RCP_MAPCHAR flag in the wRcPreferences member of the RC structure to the system registry. The RCP_MAPCHAR flag is reflected in the global RC for the current session only.

See Also

InitRC,  GetGlobalRC,  RC


SetGuideHRC [New - Windows 95]
 SetGuideHRC

2.0      [New - Windows 95]

Sets a guide structure into an HRC object.

int SetGuideHRC( HRC hrc, LPGUIDE lpguide, UINT nFirstVisible )

Parameters

hrc

Handle to the HRC object.

lpguide

Pointer to a GUIDE structure, or NULL. All coordinates are in screen coordinates.

nFirstVisible

For boxed controls, nFirstVisible refers to the first visible box (leftmost and topmost for left-right, top-down languages like English). For other controls, this is the first visible character position (leftmost for English) in a single-line control, and the first visible line (topmost for English) in multiline controls.

Return Value

Returns HRCR_OK if successful; otherwise, returns one of the following negative values:

Constant	Description
HRCR_ERROR	Invalid parameter or other error.
HRCR_INVALIDGUIDE	The guide structure is invalid.
HRCR_MEMERR	Insufficient memory.
Comments

This function is useful for doing boxed recognition. The GUIDE structure defines the size and position of the boxes. The nFirstVisible parameter notifies the recognizer which is the first visible character position (single-line controls) or line (multiline controls) in case the contents were scrolled. The writing direction affects the meaning of this value.

If lpguide is NULL, or if all the members in the GUIDE structure are 0, the recognizer does not use guides (free input).

See Also

GetGuideHRC, GUIDE


SetInternationalHRC [New - Windows 95]
 SetInternationalHRC

2.0      [New - Windows 95]

Sets the country, language, and script direction into a recognition context HRC.

int SetInternationalHRC( HRC hrc, UINT uCountry, LPCSTR lpszLangCode, UINT fuFlags, UINT uDir )

Parameters

hrc

Handle to the HRC object.

uCountry

The country code. A value of 0 indicates that this value should not be set.

lpszLangCode

A three-letter, null-terminated string identifying the language (for example, "enu" or "fra"), or NULL. A value of NULL indicates that the language code should not be changed. For a list of three-letter language identifiers, refer to Volume 1 of the Programmers Reference in the Windows Software Development Kit.

fuFlags

Flags. can be either SIH_ALLANSICHAR to indicate the user intends to use the entire ANSI character set, or 0.

uDir

The script direction. This parameter specifies which primary and secondary writing directions to set. The default directions are left to right for the primary direction and top to bottom for the secondary. A value of 0 indicates that the writing direction should not be changed. Possible values for uDir are:

Constant	Description
SSH_RD	Left to right and down (English).
SSH_RU	Left to right and up.
SSH_LD	Right to left and down (Hebrew).
SSH_LU	Right to left and up.
SSH_DL	Down and to the left (Chinese).
SSH_DR	Down and to the right (Chinese).
SSH_UL	Up and to the left.
SSH_UR	Up and to the right.
Return Value

Returns HRCR_OK if successful; otherwise, returns one of the following negative values:

Constant	Description
HRCR_ERROR	Invalid parameter or other error.
HRCR_MEMERR	Insufficient memory.
HRCR_UNSUPPORTED	The recognizer does not support this function.
Comments

Setting fuFlags to the value of SIH_ALLANSICHAR indicates the recognizer should interpret text written in any language based on ANSI characters. To constrain recognition to a particular language, an application should set fuFlags to 0 and provide the appropriate language code in lpszLangCode.

SetInternationalHRC overrides the default ALLANSICHAR setting in the recognizer set by ConfigHREC for the life of the HRC object. ConfigHREC should be used to change the default value.

See Also

GetInternationalHRC, ConfigHREC


SetMaxResultsHRC [New - Windows 95]
 SetMaxResultsHRC

2.0      [New - Windows 95]

Sets the maximum number of guesses a recognizer should make when interpreting pen data. When the recognizer formulates this number of results, the recognition process ends.

int SetMaxResultsHRC( HRC hrc, UINT cMaxResults )

Parameters

hrc

Handle to the HRC object for the recognizer.

cMaxResults

The maximum number of results a recognition context should generate. This value must be greater than 0.

Return Value

Returns HRCR_OK if successful; otherwise, returns one of the following negative values:

Constant	Description
HRCR_ERROR	Invalid parameter or other error.
HRCR_MEMERR	Insufficient memory.
HRCR_UNSUPPORTED	The recognizer does not support this function.
Comments

Subsequent calls to SetMaxResultsHRC override any previous settings. If the application does not call SetMaxResultsHRC to explicitly set a maximum value, the default number of results generated is 1.

See Also

GetMaxResultsHRC, CreateCompatibleHRC


SetPenAppFlags [New - Windows 95]
 SetPenAppFlags

2.0      [New - Windows 95]

An application calls this function to set pen-specific properties that apply globally to the application. This function replaces and enhances the RegisterPenApp function from version 1.0 of Pen Windows.

void SetPenAppFlags( UINT fuFlags, UINT uVersion )

Parameters

fuFlags

Flags specifying application options. The following flags can be combined by using the bitwise-OR operator:

Constant	Description
RPA_HEDIT	Specifies that the system should treat any EDIT-class controls in the application as having HEDIT class.
RPA_KANJIFIXEDBEDIT	Boxed edit controls are a fixed size appropriate for use with kanji. (Japanese version only.)
RPA_DBCSPRIORITY	By default, double-byte equivalents of single-byte characters (as used in Japan) are preferred in recognition results.
RPA_SBCSPRIORITY	By default, single-byte characters are preferred in recognition results. (Japanese version only.)
RPA_DEFAULT	Specifies default pen behavior for the application. This includes RPA_HEDIT.
uVersion

The Pen API version number. The nonzero value PENVER causes the application to be registered with Windows. A value of 0 unregisters the application.

Return Value

This function does not return a value.

Comments

SetPenAppFlags should be called when an application starts with PENVER for the uVersion parameter. PENVER is the Pen API version number, defined in PENWIN.H.

PENVER ensures that the structures used are appropriate for the version of the Pen API for which the application was compiled. In version 1.0, uVersion was a BOOL value, so by default the version number was 0x0001. Beginning with Pen API version 2.0, PENVER contains the major release number in the HIBYTE and the minor release number in the LOBYTE. Thus, for version 2.0, PENVER is defined as 0x0200.

When an application terminates, it should call SetPenAppFlags with uVersion set to 0. An application can unregister itself in this way more than once without error to accommodate alternative exit code paths.

An application can call GetPenAppFlags to determine which flags were set by an earlier call to SetPenAppFlags. However, normally only the system requires this information.

Applications written specifically for Windows 95 and later Windows versions automatically get RPA_DEFAULT so that any edit controls created by such applications become pen-aware.

See Also

GetPenAppFlags


SetPenHook [New - Windows 95]
 SetPenHook

1.0     2.0      [New - Windows 95]

Installs and removes a pen packet hook. This function is typically used by system-level applications such as Control Panel applications.

BOOL SetPenHook( HKP hkpOp, LPFNRAWHOOK lpfn )

Parameters

hkpOp

Operation to be performed. This parameter can be HKP_SETHOOK to install a hook or HKP_UNHOOK to remove a function from the hook list.

lpfn

Pointer to callback function to handle pen packets.

Return Value

Returns TRUE if successful or FALSE if GetPenInput is unable to set or remove the hook. The callback function returns FALSE to cancel the processing of a pen packet.

Comments

The pen device generates approximately 100 hardware interrupts per second. At each interrupt, the device sends data to the pen driver, which organizes the data into a pen packet. Each packet contains the x- and y-coordinates of the current pen position, the time, and possibly extra OEM data such as pen pressure, angle, and so forth. The pen device may require more than one hardware interrupt to send all the information for a single packet, so the rate at which the driver sends pen packets may be less than the rate of interrupts generated by the pen hardware.

When it has created a pen packet, the driver passes it to the system, which buffers the packets in an internal queue as they arrive from the pen driver. The internal queue is informally known as the "ten-second buffer" to indicate how much data it can hold before overflowing. An application must call GetPenInput regularly to remove data from the queue.

SetPenHook enables an application to examine, modify, or cancel pen packets as they arrive from the pen driver before GetPenInput sees them.

See Also

SetPenHookCallback, SetResultsHookHREC, GetPenInput


SetPenHookCallback [New - Windows 95]
 SetPenHookCallback

1.0     2.0      [New - Windows 95]

SetPenHookCallback represents the name of the callback function that the lpfn argument of SetPenHook points to. An application can use any name.

BOOL lpfn SetPenHookCallback( LPPENPACKET lppp )

Parameters

lppp

Far pointer to the most recent pen packet received from the pen driver.

Return Value

Returns TRUE to continue processing, FALSE to cancel pen packet.

Comments

For a definition of pen packet, see the description for SetPenHook.

At each interrupt, the system adds the latest packet from the pen driver to an internal queue. It then calls the application's SetPenHookCallback callback function, providing it with a pointer to the latest packet in the queue. This enables the callback function to examine, modify, or cancel each pen packet as it arrives from the pen driver.

To get the pen packet data from a version 2.0 pen driver, defined as OEM_PENPACKET, simply cast the LPPENPACKET value passed into this function to the type LPOEM_PENPACKET. The pen services detect the pen driver version automatically and return the correct data pen packet data type.

See Also

SetPenHook, PENPACKET


SetPenMiscInfo [New - Windows 95]
 SetPenMiscInfo

1.0     2.0      [New - Windows 95]

Sets constants pertaining to the pen system.

LONG SetPenMiscInfo( UINT wParam, LPARAM lParam )

Parameters

wParam

Specifies the identifier of the pen system measurement to set. The identifier must be a PMI_ value, and may be combined with PMI_SAVE (to force an immediate initialization file update) using the bitwise-OR operator for some values. See the following table for the possible PMI_ values in wParam.

lParam

Specifies the value of the pen system measurement to set. Depending on the value of wParam (listed in the first column of the table below), lParam can be the address of a structure or a value, as described here:

wParam constant	lParam description
PMI_BEDIT	lParam is the address of a BOXEDITINFO structure.
PMI_ENABLEFLAGS	lParam is a WORD value.
PMI_PENTIP	lParam is the address of a PENTIP structure.
PMI_TIMEOUT	lParam is a UINT value.
PMI_TIMEOUTGEST	lParam is a UINT value.
PMI_TIMEOUTSEL	lParam is a UINT value.
Return Value

Returns PMIR_OK if successful; otherwise, returns one of the following negative error values:

Constant	Description
PMIR_INDEX	wParam is out of range.
PMIR_INIERROR	Error writing to PENWIN.INI file.
PMIR_INVALIDBOXEDITINFO	BOXEDITINFO structure is invalid.
PMIR_NA	Support for this value of wParam is not available.
PMIR_VALUE	lParam is invalid.
Comments

The type of information SetPenMiscInfo sets depends on wParam. The function is provided for system applications such as Control Panel. User applications should not generally call SetPenMiscInfo.

A WM_PENMISCINFO message is posted to all top-level windows whenever SetPenMiscInfo successfully changes a setting, forwarding the value for wParam. In the case of PMI_BEDIT, a WM_PENMISC message is also broadcast to ensure compatibility with version 1.0 of the Pen API. The wParam is set to PMSC_BEDITCHANGE and lParam is a far pointer to a BOXEDITINFO structure.

SetPenMiscInfo cannot set all the values available in GetPenMiscInfo because certain values are determined by the system. These values are PMI_SYSREC, PMI_CXTABLET, PMI_CYTABLET, PMI_SYSFLAGS, PMI_TICKREF, PMI_INDEXFROMRGB, and PMI_RGBFROMINDEX.

The flag PMI_SAVE can be combined with the wParam identifier for the following values: PMI_BEDIT, PMI_ENABLEFLAGS, PMI_PENTIP, PMI_TIMEOUT, PMI_TIMEOUTGEST, and PMI_TIMEOUTSEL. This forces Windows to immediately update its initialization information.

Example

The following code sample changes the pen color to red and the time out to a half second (500 milliseconds), then forces a save-file update:

PENTIP tip;

GetPenMiscInfo( PMI_PENTIP, (LPARAM)(LPPENTIP) &tip );

tip.rgb = RGB(255, 0, 0);

SetPenMiscInfo( PMI_PENTIP, (LPARAM)(LPPENTIP) &tip );

SetPenMiscInfo( PMI_TIMEOUT | PMI_SAVE, (LPARAM)500 );

See Also

GetPenMiscInfo,  WM_PENMISCINFO,  PMI_


SetRecogHook [New - Windows 95]
 SetRecogHook

1.0     2.0      [New - Windows 95]

Installs and removes a recognition hook. This function works only for Pen API version 1.0 recognizers accessed through Recognize or RecognizeData.

Note  This function is provided only for compatibility with version 1.0 of the Pen API and will not be supported in future versions. Use SetResultsHookHREC instead.

BOOL SetRecogHook( UINT uScope, UINT uSetOp, HWND hwndHook )

Parameters

uScope

Scope of hook. The hook parameter uSetOp determines the scope of the hook. The following table lists the HWR_ values for uSetOp:

Constant	Description
HWR_RESULTS	The hook window receives a WM_HOOKRCRESULT message before a WM_RCRESULT message is sent to the target window.
HWR_APPWIDE	The hook window receives the message WM_HOOKRCRESULT before a WM_RCRESULT message is sent to the target window if the target window belongs to the same task as the window that set an HWR_APPWIDE hook. This is useful for implementing application-wide gestures.  The RCRT_ALREADYPROCESSED flag is set in the wResultsType member of the RCRESULTS structure sent with WM_RCRESULT if an application-wide hook has already processed the data.
uSetOp

Parameter to determine whether hook is set or removed. The operation parameter uSetOp determines whether the hook is set or removed. The following table lists the HKP_ values for uScope:

Constant	Description
HKP_SETHOOK	Installs a hook.
HKP_UNHOOK	Removes function from hook list.
hwndHook

Handle to a window.

Return Value

Returns TRUE if successful; otherwise, FALSE.

Comments

SetRecogHook enables a version 1.0 application to examine the results of recognition before they are sent to the target application.

The hook message is WM_HOOKRCRESULT. The wParam and lParam parameters are the same as for the WM_RCRESULT message. If the window procedure that receives the WM_HOOKRCRESULT message returns FALSE, the message WM_HOOKRCRESULT is not sent to any of the remaining hooks in the chain.

No drawing should occur during the processing of the WM_HOOKRCRESULT and before recognition is complete. Drawing at these times could cause timing problems, with ink reappearing in formerly invisible controls as they are redrawn.

See Also

SetResultsHookHREC


SetResultsHookHREC [New - Windows 95]
 SetResultsHookHREC

2.0      [New - Windows 95]

Sets up a hook callback function for recognition results.

HRECHOOK SetResultsHookHREC( HREC hrec, HRCRESULTHOOKPROC lpfnHook )

Parameters

hrec

Module handle of the recognizer library whose results are to be hooked. If hrec is set to NULL, the hook function specified in lpfnHook receives results from the system default recognizer. If hrec is set to SRH_HOOKALL, the hook function receives results for all recognizers the application has installed, including the system recognizer.

lpfnHook

Address of the hook function.

Return Value

Returns a handle to the installed hook if successful; otherwise, the return value is NULL. The application must provide this handle when calling UnhookResultsHookHREC to remove the hook.

Comments

An application can set multiple hooks. The system calls the hooks in reverse order —that is, the most-recently-set hook is called first, then the previous hook, and so on. If a hook function captures a result, the function that requested the results returns HRCR_HOOKED to the application.

See Also

ResultsHookHREC, UnhookResultsHookHREC


SetStrokeAttributes [New - Windows 95]
 SetStrokeAttributes

2.0      [New - Windows 95]

Sets attributes of a stroke or of a class of strokes in an HPENDATA object.

int SetStrokeAttributes( HPENDATA hpndt, UINT iStrk, LPARAM lParam, UINT uOption )

Parameters

hpndt

Handle to the HPENDATA object.

iStrk

Zero-based stroke index. A value of IX_END can be used to specify the last available stroke in the pen data.

lParam

A pointer to a structure (cast to the LPARAM type), or a byte, word, or double-word value, depending on uOption. This parameter cannot be NULL.

uOption

Specifies the attributes to set. This parameter has one of the following values:

Constant	Description
SSA_DOWN	Set the up and down state of the pen tip for the stroke specified by iStrk. lParam is nonzero to make it a downstroke or 0 to make it an upstroke.
SSA_PENTIP	Set the pen-tip characteristics (color, width, nib type) used by the stroke specified by iStrk. lParam is a pointer to a PENTIP structure. If this attribute does not already exist in the stroke class table, a new entry for this type of stroke is created. There can be up to 255 different types of strokes.
SSA_PENTIPCLASS	Set the pen-tip characteristics (color, width, nib) for all strokes of which the stroke specified by iStrk is a member. lParam is a pointer to a PENTIP structure. If the new type already exists in the stroke class table, the types are merged.
SSA_SELECT	Set the selection status of the stroke specified by iStrk. lParam is nonzero to select it or 0 to deselect it.
SSA_TIME	Set the absolute time of the stroke. lParam is a pointer to an ABSTIME structure. The sec member of the ABSTIME structure specifies the number of seconds since Jan 1, 1970, and the ms member specifies the number of milliseconds offset from that time to the beginning of the stroke.
SSA_USER	Set the user value for the stroke specified by iStrk. lParam is a BYTE, WORD, or DWORD value, and the pen data must have been created with the corresponding size allocated for user values.
SSA_USERCLASS	Set the user value for the class of strokes of which the stroke specified by iStrk is a member. lParam is a BYTE, WORD, or DWORD value, and the pen data must have been created with the corresponding size allocated for user values.
Return Value

Returns PDR_OK if successful; otherwise, returns one of the following negative values:

Constant	Description
PDR_COMPRESSED	Pen data is compressed.
PDR_ERROR	Parameter or other unspecified error.
PDR_MEMERR	Memory error.
PDR_PNDTERR	Invalid pen data.
PDR_SCTERR	Stroke class table may be full, or related error.
PDR_STRKINDEXERR	Invalid stroke index.
PDR_TIMESTAMPERR	Timing information was removed.
PDR_VERSIONERR	Could not convert old pen data.
Comments

The bounding rectangle of the pen data is recalculated each time the SSA_DOWN option is used, because the rectangle represents the bounds of only the pen-down points. Setting a pen-up point to the down state simply adds (union) the bounding rectangles of the existing pen data and the stroke. Setting a pen-down point to the up state is more calculation-intensive, however, since the bounding rectangle must be calculated from all of the remaining strokes.

See Also

CreatePenDataEx, GetStrokeAttributes, GetStrokeTableAttributes, SetStrokeTableAttributes, PENTIP


SetStrokeTableAttributes [New - Windows 95]
 SetStrokeTableAttributes

2.0      [New - Windows 95]

Sets attributes of a stroke's class within an HPENDATA object. (The class is an entry in a table stored in the PENDATAHEADER structure. Modifying the table entry affects all the strokes described by the entry.)

int SetStrokeTableAttributes( HPENDATA hpndt, UINT iTblEntry, LPARAM lParam, UINT uOption )

Parameters

hpndt

Handle to the HPENDATA object.

iTblEntry

Zero-based table index to the class entry in the pen data header.

lParam

A pointer to a structure (cast to the LPARAM type), or a byte, word, or doubleword value, depending on uOption. This parameter cannot be NULL.

uOption

Specifies the attributes to set. This parameter can be one of the following:

SSA_PENTIPTABLE

Set the pen-tip characteristics (color, width, nib) of the class of strokes specified by iTblEntry. lParam is a pointer to a PENTIP structure. All the strokes sharing this entry in the stroke class table receive the new pen-tip attribute.

SSA_USERTABLE

Set the user value, if any, of the class of strokes specified by iTblEntry. lParam is a byte, word, or doubleword value, and the pen data must have been created with the corresponding size allocated for user values. All the strokes sharing this stroke class table entry receive the new user value.

Return Value

Returns PDR_OK if successful; otherwise, returns one of the following negative values:

Constant	Description
PDR_COMPRESSED	Pen data is compressed.
PDR_ERROR	Parameter or other unspecified error.
PDR_MEMERR	Memory error.
PDR_PNDTERR	Invalid pen data.
PDR_SCTERR	Stroke class table may be full, or related error.
PDR_VERSIONERR	Could not convert old pen data.
See Also

CreatePenDataEx, GetStrokeAttributes, GetStrokeTableAttributes, SetStrokeAttributes, PENTIP


SetWordlistCoercionHRC [New - Windows 95]
 SetWordlistCoercionHRC

2.0      [New - Windows 95]

Specifies to what degree input must match a word list set into an HRC. SetWordlistCoercionHRC determines the influence a recognizer's word list or dictionary has on the recognizer's guesses.

int SetWordlistCoercionHRC( HRC hrc, UINT uCoercion )

Parameters

hrc

Handle to the HRC object.

uCoercion

Coercion flag. This can be one of the following:

SCH_ADVISE

The word list serves only to advise the recognizer, but lacks a strong degree of influence. Recognition results are not strongly coerced to match the word list.

SCH_FORCE

If the recognizer's guess is not found in the word list, the closest matching entry in the list is returned. For example, if the recognizer interprets writing as "Cana", it returns "Canada" from a word list of country names.

SCH_NONE

Do not coerce. This flag can be used to turn off a previous request.

Return Value

Returns HRCR_OK if successful; otherwise, returns one of the following negative values:

Constant	Description
HRCR_ERROR	Invalid parameter or other error, including an attempt to set coercion with no word lists set into the recognition context.
HRCR_MEMERR	Insufficient memory.
HRCR_UNSUPPORTED	The recognizer does not support this function.
Comments

The default type of coercion a recognizer provides is SCH_ADVISE. That is, results are not strongly coerced to any word list that might be set into a recognition context.

Coercion is used only if a word list (HWL) has actually been set into an HRC with SetWordlistHRC, or if the recognizer's dictionary is enabled by EnableSystemDictionaryHRC. If the HRC is configured with a word list and the recognizer's dictionary is also enabled, coercion is done on both; the priority depends on the recognizer.

See Also

CreateHWL, GetWordlistCoercionHRC


SetWordlistHRC [New - Windows 95]
 SetWordlistHRC

2.0      [New - Windows 95]

Sets a word list into a recognition context HRC object.

int SetWordlistHRC( HRC hrc, HWL hwl )

Parameters

hrc

Handle to the HRC object.

hwl

Handle to a word list to use, or NULL. A value of NULL means that the recognizer should not constrain recognition based on any word list, including its own dictionary.

Return Value

Returns HRCR_OK if successful; otherwise, returns one of the following negative values:

Constant	Description
HRCR_ERROR	Invalid parameter or other error.
HRCR_MEMERR	Insufficient memory.
HRCR_UNSUPPORTED	The recognizer does not support this function.
Comments

Specifying NULL for hrc does not destroy the word list specified by hwl. Applications must call DestroyHWL to destroy a word list.

Only one word list can be set into an HRC at a time. This is independent of the recognizer's dictionary, which can be manipulated through the function EnableSystemDictionaryHRC.

For a description of word lists and how a recognizer uses them, see "Configuring the HRC" in Chapter 5, "The Recognition Process."

See Also

CreateHWL, DestroyHWL


ShowKeyboard [New - Windows 95]
 ShowKeyboard

1.0     2.0      [New - Windows 95]

Shows or hides the on-screen keyboard. (Not supported in Japanese version.)

Note  This function is provided only for compatibility with version 1.0 of the Pen API, and will not be supported in future versions. It is not supported for 32-bit applications. Applications should interface directly with the on-screen keyboard.

BOOL ShowKeyboard( HWND hwnd, UINT wCommand, LPPOINT lppt, LPSKBINFO lpSKBInfo )

Parameters

hwnd

Handle of window invoking the on-screen keyboard.

wCommand

A show request and optional keypad. The values for the show requests are listed in the "Comments" section below.

lppt

Address of a POINT structure containing the keyboard position in screen coordinates. If NULL, the keyboard appears centered on the display.

lpSKBInfo

Address of an SKBINFO structure to be filled with values for the current keyboard. This parameter is ignored if NULL. If the hwnd member of the SKBINFO structure is NULL, no on-screen keyboard has been loaded.

Return Value

Returns TRUE if successful; otherwise FALSE.

Comments

Any user action on the keyboard itself overrides the function requests. For example, if the user closes the on-screen keyboard, the keyboard becomes unregistered for all windows in all applications. If the user minimizes the keyboard, the active SKBINFO structure is changed to reflect the new state.

ShowKeyboard tracks registration information for up to 20 window handles. If one application displays the keyboard and then another one does the same thing, both applications must request that the keyboard be hidden before it actually disappears.

The following SKB_ requests can be specified in the wCommand parameter:

Constant	Description
SKB_HIDE	Hides the on-screen keyboard. This request may not actually hide the keyboard if another application is also using it. The command decrements the use count for the keyboard. SKB_HIDE automatically loads the on-screen keyboard if it is not already present.
SKB_QUERY	Returns the current state of the keyboard pointed to  by the lpSKBInfo parameter without invoking a new keyboard state. This command does not automatically load the on-screen keyboard.
SKB_SHOW	Shows the on-screen keyboard in a restored state at  the most recently used screen location. This command increments a window-use count. SKB_SHOW automatically loads the on-screen keyboard if it is not present.
The SKB_SHOW command in the wCommand parameter can be combined using the bitwise-OR operator with any of the command or keypad requests listed in the following tables:

Constant	Description
SKB_CENTER	Centers the keyboard on the display. This command  has higher priority than SKB_MOVE.
SKB_MINIMIZE	Displays the on-screen keyboard in a minimized state. This command can be used with SKB_CENTER or SKB_MOVE. If it is used with SKB_MOVE, the location specified will be used when the keyboard is restored.
SKB_MOVE	Moves the keyboard to the location specified by the lppt parameter. If lppt is NULL, the keyboard is centered on the screen. If it is not NULL, lppt specifies a pointer to the x and y screen coordinates of the upper-left corner of the restored keyboard.
The following keypad requests can be used with SKB_SHOW in the wCommand parameter. The SKB_BASIC, SKB_FULL, and SKB_NUMPAD constants can not be combined with the OR operator:

Constant	Description
SKB_BASIC	Switches the keyboard to a partial keyboard with no extended keys.
SKB_FULL	Switches the keyboard to the full 101-key display.
SKB_NUMPAD	Switches the keyboard to a partial keyboard consisting only of ESC, TAB, SHIFT, and the numeric keypad.
The following three bitmaps are provided for owner-draw push buttons that can be used to invoke the on-screen keyboard. The application must process WM_DRAWITEM and other button-related code. On-screen keyboard push buttons should behave the same way as other standard buttons (for example, the Minimize button) and take the appropriate action when a button-up message is received following a button-down message.

Constant	Description
OBM_SKBBTNUP	Push button is up.
OBM_SKBBTNDOWN	Push button is down.
OBM_SKBBTNDISABLED	Push button is disabled.
Example

The up bitmap, for example, can be loaded as shown in the following code sample:

HANDLE hDLL = GetSystemMetrics( SM_PENWINDOWS );

HBITMAP hBitmap = LoadBitmap( hDLL,

MAKEINTRESOURCE(OBM_SKBBTNUP) );

The application must call the Windows DeleteObject function to delete each bit-map handle returned by the Windows LoadBitmap function.

The button should be left in the up state after it is released. If the user closes the keyboard and the buttons are up, they will still be up the next time the keyboard is opened. The following code sample retrieves the current keyboard and restores the current state:

#include <penwin.h>

if (ShowKeyboard( hwnd, SKB_SHOW, NULL, NULL)) // Nonzero: no error.

{

.

.                        // Perform some tasks.

.

ShowKeyboard( hwnd, SKB_HIDE, NULL, NULL );

}

else

ErrorMsg( "Unable to use Screen Keyboard" );

The following code sample moves the keyboard and then puts it back into its starting position:

SKBINFO skbinfo;

WORD wCommand = SKB_SHOW | SKB_MOVE;

POINT pnt;

pnt.x = wSKBLeft;    // Initialize point.

pnt.y = wSKBTop;

// Show the keyboard.

ShowKeyboard( hwnd, wCommand, &pnt, &skbinfo );

.

.

.

// Now restore the keyboard.

if (skbinfo.fVisible)

wCommand = SKB_SHOW | SKB_MOVE |

(skbinfo.fMinimized ? SKB_MINIMIZED : 0);

else

wCommand = SKB_HIDE;

ShowKeyboard( hwnd, wCommand, (LPPOINT)(&skbinfo.rect), NULL) ;


StartInking [New - Windows 95]
 StartInking

2.0      [New - Windows 95]

Starts inking feedback while pen input is being collected.

int StartInking( HPCM hpcm, UINT idEvent, LPINKINGINFO lpinkinginfo )

Parameters

hpcm

Handle to the current collection. This is the return value from StartPenInput.

idEvent

The identifier of the packet at which to start inking.

lpinkinginfo

Address of an INKINGINFO structure, used to specify the characteristics of the ink. This parameter can be NULL to use the default ink characteristics. Otherwise, the structure's cbSize member must be initialized with sizeof( INKINGINFO ).

Return Value

Returns PCMR_OK if inking started successfully; otherwise, returns one of the following:

Constant	Description
PCMR_DISPLAYERR	There is no display device, or it was unable to ink at this time, or there was an error in setting the pen-tip characteristics.
PCMR_ERROR	The INKINGINFO structure contains invalid values, or there was some other unspecified error.
PCMR_INVALIDCOLLECTION	The hpcm handle is invalid because the calling application did not start input by calling StartPenInput.
PCMR_INVALID_PACKETID	The idEvent parameter is invalid.
Comments

An application calls StartInking to track pen movement while the pen tip is down. When pen input is started by calling the StartPenInput function, Windows initializes the internal INKINGINFO structure as follows:

•	The wFlags member is set to PII_INKPENTIP | PII_INKCLIPRECT.

•	The tip member is set to the system default pen tip, as obtained by calling the GetPenMiscInfo function.

•	The rectClip member is set to the client area, in screen coordinates, of the window that was used in the call to the StartPenInput function.

The first call to StartInking with the lpinkinginfo parameter set to NULL starts inking with the settings listed above. If the calling application uses a non-NULL value for lpinkinginfo, the appropriate internal inking parameters are modified before inking starts, depending on the flags set in the wFlags member of the INKINGINFO structure.

Whenever StartInking is called, the current settings of the internal inking structure are added to or replaced. Specific values must be set in the members of INKINGINFO to disable them. Refer to the description of each member in the INKINGINFO structure for these values.

If a region is passed in for clipping or stopping the ink, the application must destroy the region. Since a copy is made, the region can be destroyed immediately following the call to StartInking. The application can specify either a clip region or a clip rectangle. Specifying both will result in the clip rectangle being ignored.

Example

The following code example changes the inking tip from the default (as set by a call to StartPenInput) to red ink, 5 pixels wide. It also adds an inkstop rectangle (inking stops if the pen touches down inside the inkstop rectangle). The clipping rectangle remains unchanged from the default settings.

INKINGINFO inkinginfo;

inkinginfo.cbSize           = sizeof( INKINGINFO );

inkinginfo.wFlags           = PII_INKPENTIP | PII_INKSTOPRECT;

inkinginfo.tip.cbSize       = sizeof( PENTIP );

inkinginfo.tip.rgb          = RGB( 255,0,0 );

inkinginfo.tip.bwidth       = 5;

inkinginfo.rectInkStop.left = rectInkTop.top = 0;

inkinginfo.rectInkStop.right = rectInkTop.bottom = 100;

ClientToScreen( hwnd, (LPPOINT)&(inkinginfo.rectInkStop) );

ClientToScreen( hwnd, (LPPOINT)&(inkinginfo.rectInkStop.right) );

StartInking( hpcm, wEventRef, &inkinginfo );

See Also

INKINGINFO, StartPenInput, StopInking


StartPenInput [New - Windows 95]
 StartPenInput

2.0      [New - Windows 95]

Begins collecting information from the pen input stream.

HPCM StartPenInput( HWND hwnd, UINT idEvent, LPPCMINFO lppcmInfo, LPINT lpiErrRet )

Parameters

hwnd

Handle of the window that receives the WM_PENEVENT messages generated by StartPenInput.

idEvent

Identifies the packet in the global queue of pen packets maintained internally by the system. The idEvent is the low-order word of the value returned from the GetMessageExtraInfo function when processing a WM_LBUTTONDOWN message. For a definition of pen packet, see the description for SetPenHook.

lppcmInfo

Address of a PCMINFO structure. If NULL, the system creates a default PCMINFO structure with the following values:

Constant	Description
dwPcm	PCM_RECTBOUND | PCM_TIMEOUT | PCM_TAPNHOLD
rectBound	The bounding rectangle of the window identified by hwnd These values determine that the input session (a) terminates when pen activity ceases for a specified time-out period; (b) terminates when the pen moves outside the bounds of the window; or (c) does not begin at all if the user taps and holds the pen for a specified time-out period (about one-half second). This "tap-and-hold" gesture switches the system from input mode to selection mode. Usually, the cursor changes from a pen (indicating input) to an upside-down arrow (indicating selection) to acknowledge the switch. Subsequent pen movement then behaves as a mouse with the left button held down. This allows the user to make selections as though dragging the mouse.
lpiErrRet

Address of an integer that receives a return code when StartPenInput terminates. If NULL, no return code is provided. If not NULL, the return code is one of the following values:

Constant	Description
PCMR_OK	Pen collection was successfully started.
PCMR_ALREADYCOLLECTING	StartPenInput has already been called for this session.
PCMR_ERROR	Illegal parameter or unspecified error.
PCMR_INVALID_PACKETID	Invalid idEvent parameter.
PCMR_SELECT	Tap-and-hold gesture detected. Collection is not started, as described in the description of the lppcmInfo parameter.
PCMR_TAP	The pen has briefly tapped the tablet. This event may be inadvertent and in any case does not indicate that the user has started to write; therefore, collection is not started.
Return Value

Returns a handle to the application's queue of pen packets, if successful. Returns NULL to indicate an error or the detection of a tap or press-and-hold condition.

Comments

When this function returns successfully, Windows creates a queue of pen packets for the calling application. All subsequent pen packets from the pen device, beginning with the packet identified by the idEvent argument, are placed into the queue. Until a termination condition occurs (as specified in the lppcmInfo parameter), or until the application calls StopPenInput, the queue continues to receive all the packets generated by the pen device as the pen moves.

An application can retrieve all the pen input in its queue of pen packets but should never destroy the queue.

In event mode (the default mode), the collection session specified by the hpcm of the GetPenInput function becomes invalid when the WM_PENEVENT message (with the PE_TERMINATED submessage) is removed from the application's message queue. This message is posted to the application's message queue either as a consequence of automatic termination or a call to StopPenInput.

In polling mode, the application's queue of pen packets is destroyed (and the hpcm of GetPenInput becomes invalid) after a successful call to StopPenInput or a termination return value from the GetPenInput function.

If lppcmInfo is NULL, a default PCMINFO structure is established with the dwPcm member set to PCM_RECTBOUND | PCM_TIMEOUT | PCM_TAPHOLD, the rectBound member set to the bounds of hwnd, and the dwTimeout member set to the default system time out.

If the dwPcm member of PCMINFO does not have the PCM_DOPOLLING flag set, WM_PENEVENT messages are sent to the specified window for significant events such as pen down, pen up, or after some threshold number of points has been received. Otherwise, the application should poll for data using GetPenInput.

Other bits in the dwPcm member of PCMINFO can be used to determine which conditions, if any, terminate pen input. An application can also call StopPenInput to explicitly terminate the input.

Example

The following example initiates pen input in a window procedure on detection of pen down:

static HPCM vhpcm;

//... omitted ...

switch (message)

{

case WM_LBUTTONDOWN:

{

// Get extra info associated with event:

DWORD dwExtraInfo = GetMessageExtraInfo();

if (IsPenEvent( message, dwExtraInfo ))   // Checks PDK bits

{

PCMINFO pcminfo;        // Pen collection mode structure

pcminfo.cbSize    = sizeof( PCMINFO );

pcminfo.dwPcm     = PCM_RECTBOUND | PCM_TIMEOUT;

pcminfo.dwTimeout = dwTimeOutDefault;   // 1 second

// Set inclusion rect to client area, but in screen coords:

GetClientRect( hwnd, &pcminfo.rectBound );

ClientToScreen( hwnd, (LPPOINT) &pcminfo.rectBound );

ClientToScreen( hwnd, (LPPOINT) &pcminfo.rectBound.right );

// Start gathering input:

if (vhpcm = StartPenInput( hwnd,

LOWORD( dwExtraInfo ), &pcminfo, NULL ))

return 1L;                         // We handled it

}

// Else fall into DefWindowProc below...

}

break;

See Also

GetPenInput, StopPenInput, PCMINFO WM_PENEVENT, PCM_


StopInking [New - Windows 95]
 StopInking

2.0      [New - Windows 95]

Stops inking feedback.

int StopInking( HPCM hpcm )

Parameters

hpcm

Handle to the current collection. This is the return value from StartPenInput.

Return Value

Returns PCMR_OK if successful; otherwise, returns the following value:

Constant	Description
PCMR_INVALIDCOLLECTION	The hpcm handle is invalid, or there is no collection, or inking has not been started.
Comments

Inking must have been started by using the StartInking function for this function to have any effect.

See Also

StartInking


StopPenInput [New - Windows 95]
 StopPenInput

2.0      [New - Windows 95]

Terminates collection of pen input.

int StopPenInput( HPCM hpcm, UINT idEvent, int nTermReason )

Parameters

hpcm

Handle to the collection of the pen data gathered during the input session. HPCM stands for "handle to a pen collection mode."

idEvent

The identifier of the packet in the task-specific queue at which the pen input should be terminated. If this value is PID_CURRENT, pen input stops immediately (that is, at the latest position in the task queue) and no further input is collected. The idEvent parameter is the low-order word of the value returned from the Windows GetMessageExtraInfo function when processing a WM_LBUTTONDOWN message.

nTermReason

The reason for termination. This value is passed to the termination message PE_TERMINATED. It can be one of the following:

Constant	Description
PCMR_APPTERMINATED	Application terminated input.
PCMR_TERMBOUND	Pen was pressed outside bounding rectangle or region.
PCMR_TERMEX	Pen was pressed inside exclusion rectangle or region.
PCMR_TERMPENUP	Pen was lifted from the tablet.
PCMR_TERMRANGE	Pen left the tablet's range of sensitivity.
PCMR_TERMTIMEOUT	Time-out expired.
Return Value

Returns PCMR_OK if successful; otherwise, the return value can be one of the following:

Constant	Description
PCMR_INVALIDCOLLECTION	The hpcm handle is invalid because the calling application did not start input with StartPenInput.
PCMR_INVALID_PACKETID	idEvent is invalid.
Comments

This function allows an application to explicitly terminate pen collection without waiting for one of the conditions specified by StartPenInput in the dwPcm member of PCMINFO.

Due to the asynchronous nature of pen input messages, the application should wait for the WM_PENEVENT message with wParam set to PE_TERMINATED to make sure that the pen input process has completely terminated. This does not apply if the application is using the polling method of pen input.

See Also

StartPenInput


SymbolToCharacter [New - Windows 95]
 SymbolToCharacter

1.0     2.0      [New - Windows 95]

Converts an array of SYV_ symbol values to an ANSI string.

BOOL SymbolToCharacter( LPSYV lpsyv, int cSyv, LPSTR lpstr, LPINT lpnConv )

Parameters

lpsyv

Address of the array of SYV_ symbol values.

cSyv

Count of symbols in the lpsyv array, including the terminating SYV_NULL.

lpstr

Address of a buffer that receives the ANSI string. The buffer should be large enough to hold at least cSyv number of ANSI characters (including SYV_NULL).

lpnConv

If not NULL, lpnConv contains the number of symbols converted when the function returns. If NULL, this parameter is ignored.

Return Value

Returns TRUE if successful. If one or more symbols cannot be converted to ANSI, the return value is FALSE.

Comments

For ANSI characters, the size of the lpstr buffer must be at least cSyv bytes. For double-byte characters (kanji, for example), the buffer size must be at least (2 * cSyv) bytes. The SymbolToCharacter function converts at most cSyv symbol values from lpsyv and places the equivalent ANSI characters in the lpstr buffer. The conversion proceeds until an SYV_NULL value is encountered or until cSyv symbols have been converted. An SYV_NULL is converted to 0. The actual number of symbols converted is returned in lpnConv if lpnConv is not NULL.

See Also

CharacterToSymbol, SYG, SYV_


TargetPoints [New - Windows 95]
 TargetPoints

2.0      [New - Windows 95]

Determines the target to which pen data belongs.

int TargetPoints( LPTARGINFO lptarginfo, LPPOINT lppt, DWORD dwReserved, UINT fuReserved, LPSTROKEINFO lpsi )

Parameters

lptarginfo

Address of a targeting data TARGINFO structure.

lppt

Address of a buffer of POINT structures in tablet coordinates.

dwReserved

This parameter is reserved for future use and its value is ignored.

fuReserved

This parameter is reserved for future use and its value is ignored.

lpsi

A pointer to a STROKEINFO structure. This structure holds information about the stroke being targeted.

Return Value

Returns an array index, starting from 0, of the target in the rgTarget array of the TARGINFO structure, if successful. If no suitable target is found, or if there are no points to target, TargetPoints returns −1.

Comments

To select the desired targeting behavior, the application should set the dwFlags member of the TARGINFO structure that lptarginfo points to.

See Also

GetPenInput,  TARGET,  TARGINFO


TPtoDP [New - Windows 95]
 TPtoDP

1.0     2.0      [New - Windows 95]

Converts points in tablet coordinates to display (screen) coordinates.

BOOL TPtoDP( LPPOINT lppt, int cPnt )

Parameters

lppt

Address of an array of POINT structures to convert to display coordinates. This parameter cannot be NULL.

cPnt

Number of POINT structures to convert.

Return Value

Returns TRUE if the conversion was successful; otherwise, returns FALSE.

Comments

The conversion fails if some tablet points lie outside the region mapped to the screen.

Because of rounding errors, the DPtoTP and TPtoDP functions are not guaranteed to be perfect inverses of each other.

See Also

DPtoTP


TrainContext [New - Windows 95]
 TrainContext

1.0     2.0      [New - Windows 95]

Provides the recognizer a previous recognition result that may contain errors, plus the correct interpretation of the raw data.

Note  This function is provided only for compatibility with version 1.0 of the Pen API and will not be supported in future versions. Use TrainHREC instead.

BOOL TrainContext( LPRCRESULT lprcresult, LPSYE lpsye, int csye, LPSYC lpsyc, int csyc )

Parameters

lprcresult

Address of the RCRESULT structure containing the handle to the pen data that contains the raw data and the recognizer's original interpretation of that data. This parameter cannot be NULL.

lpsye

Address of an array of SYE structures that specify the correct interpretation of the raw data. The values of the  iSyc members of these structures index the SYC structures pointed to be the lpsyc parameter.

csye

The number of SYE structures in the lpsye array.

lpsyc

An array of SYC structures that establish the mapping between the raw data and the characters in the hpendata member of the structure pointed to by the lprcresult parameter.

csyc

The number of SYC structures in the lpsyc array.

Return Value

Returns TRUE if the ink is accepted for training; otherwise, returns FALSE.

Comments

TrainContext is called by an application with a recognition result that may contain mistakes, along with a correct interpretation, so that the recognizer can learn from the mistake and improve subsequent recognition. A second, simpler training function for 1.0 recognizers is provided by TrainInk.

TrainContext internally calls the function TrainContextInternal exported by the recognizer identified by the hrec member of the RC structure pointed to by the lprc member of the RCRESULT structure. A version 1.0 recognizer should export both TrainContextInternal and TrainInkInternal, but can simply return FALSE from both functions if the recognizer does not support this type of training.

When a training application is able to provide contextual information (such as segmentation suggestions) to the version 1.0 recognizer, it calls the TrainContext function. The lprcresult parameter points to an RCRESULT structure that contains the results of a previous recognition. The raw data is also contained in the hpendata member of the structure pointed to be lprcresult.

In addition to providing the incorrect interpretation of the data (by means of the symbol graph, the lpsyv member in the RCRESULT structure), a more detailed, correct interpretation is also provided by the SYE structures and SYC structures. Because the correct interpretation is passed by SYE structures, it is possible to suggest segmentation boundaries to the recognizer.

Suppose, for example, that a user writes "lc," and the recognizer interprets it as "k". A trainer calls TrainContext using, first, an array of SYC structures that point to the ink of the "lc" and, second, the two SYE structures with the SYV values "l" and "c". These two SYE structures share the same index into the lpsyc array, indicating that both use the ink that was interpreted as "k".

Segmentation errors can be corrected in the other direction as well. Suppose, for example, the user writes "k" and the recognizer interprets it as "lc". A trainer could call TrainContext using a single SYE with SYV values equal to "k" and an array of SYC structures that incorporate the ink the recognizer had previously assigned to the "l" and the "c".

To train several SYV symbol values to a single piece of ink (for example, a long stroke that is an "he" ligature), there will be two consecutive SYE structures—one for the "h" and one for the "e". Both SYE structures have the same iSyc member; this means that the SYE structures both point to the same ink. A recognizer must take this into consideration to avoid training the two characters separately using the same ink for both; that would result in having "he" trained as "he he".

A recognizer can supply its own custom training dialog boxes. An application should check whether the recognizer supports custom training by calling ConfigRecognizer with the WCR_TRAIN subfunction.

The trainer does not display an error message if TrainInk or TrainContext returns FALSE. Error messages that occur when training fails must be handled by the recognizer.

See Also

ConfigRecognizer, TrainInk, TrainHREC, SYC,  SYE,  SYV_


TrainHREC [New - Windows 95]
 TrainHREC

2.0      [New - Windows 95]

Passes ink and its symbol interpretation to the recognizer for training.

int TrainHREC( HREC hrec, LPSYV lpsyv, UINT cSyv, HPENDATA hpndt, UINT uConflict )

Parameters

hrec

Module handle of the recognizer library. If this value is NULL, the system default recognizer is used.

lpsyv

Address of an array of symbols to train.

cSyv

Count of symbols in lpsyv. This must be greater than 0.

hpndt

Handle to an HPENDATA object.

uConflict

One of the following TH_ values that specify how to handle training conflicts:

Constant	Description
TH_QUERY	Query the user if the proposed training conflicts with symbols in the database.
TH_FORCE	Perform the training without querying the user, even if there is a conflict with the database.
TH_SUGGEST	Abandon the training if there is any conflict with the database and return an error (HRCR_CONFLICT).
Return Value

Returns HRCR_OK if training is successful; otherwise, returns one of the following negative values:

Constant	Description
HRCR_ERROR	Invalid parameter or other error.
HRCR_CONFLICT	TH_SUGGEST was specified but there was a conflict with the database. No training was done.
HRCR_INVALIDPNDT	Invalid HPENDATA object.
HRCR_MEMERR	Insufficient memory.
HRCR_UNSUPPORTED	The recognizer does not support this function.
Comments

Typically, an application calls TrainHREC to train a single symbol. In other words, lpsyv points to a single symbol that is followed by an SYV_NULL terminator. However, multiple symbols—for example, those representing the character string "ng"—may also be trainable, depending on the recognizer.

If uConflict is TH_QUERY, the recognizer is free to prompt the user with a dialog box to resolve training conflicts. If it is TH_FORCE, the training is performed regardless of conflicts and the original conflicting data may be lost. TH_SUGGEST trains the recognizer only if there are no conflicts; otherwise, the call fails and returns HRCR_CONFLICT.

If the user picks a meaning for some ink from a list of alternatives, such as in a boxed edit control, the application can elect to train the recognizer with this information. In this case, either TH_FORCE or TH_SUGGEST is a suitable value for uConflict.

Training gestures depends on the recognizer. The Microsoft Handwriting Recognizer (GRECO.DLL) does not support training for gestures.

See Also

CreateCompatibleHREC


TrainInk [New - Windows 95]
 TrainInk

1.0     2.0      [New - Windows 95]

Provides raw data and a correct interpretation of the data to the recognizer.

Note  This function is provided only for compatibility with version 1.0 of the Pen API and will not be supported in future versions. Use TrainHREC instead.

BOOL TrainInk( LPRC lprc, HPENDATA hpndt, LPSYV lpsyv )

Parameters

lprc

Address of an RC structure, or NULL. If this parameter is NULL, the RC Manager replaces it with a pointer to the global RC structure, then calls the recognizer associated with the global RC. If lprc is not NULL, the RC Manager calls the recognizer identified by the hrec member of the RC structure.

hpndt

Handle to an HPENDATA object containing the ink to be trained. This parameter cannot be NULL.

lpsyv

Pointer to a string of SYV symbol values terminated by SYV_NULL. This parameter cannot be NULL.

Return Value

Returns TRUE if the ink described by the pen data could be trained; otherwise, it returns FALSE.

Comments

Applications call TrainInk with raw data accompanied by a correct interpretation of the data, so that the recognizer can improve subsequent recognition. A second, more complex training function for version 1.0 recognizers is provided by TrainContext.

TrainInk is called by an application to access the TrainInkInternal function in the recognizer library. A private 1.0 recognizer must export both TrainInkInternal and TrainContextInternal, but the functions can simply return FALSE if the recognizer does not support this type of training.

TrainInk provides the lowest level of basic shape training. It requests the recognizer to assign the meaning in lpsyv to the ink in hpndt. The recognizer should interpret the ink to meet that request.

In the most common case, lpsyv points to a single character, and the recognizer will train a new shape based on the ink and that character. In other cases, multiple SYV symbol values can be passed, indicating that the ink represents multiple characters. The recognizer must decide whether to simply add a new shape with a meaning based on multiple SYV symbol values or to segment the ink into separate shapes for each SYV.

An application should check whether a recognizer supports training by calling ConfigRecognizer with the WCR_TRAIN subfunction.

The trainer does not display an error message if TrainInk or TrainContext returns FALSE. Error messages that occur when training fails must be handled by the recognizer.

See Also

ConfigRecognizer,  TrainContext,  TrainHREC, SYV_


TrimPenData [New - Windows 95]
 TrimPenData

2.0      [New - Windows 95]

Removes selected data from an HPENDATA object.

HPENDATA TrimPenData( HPENDATA hpndt, DWORD dwTrimOptions, DWORD dwReserved )

Parameters

hpndt

Handle to the HPENDATA object.

dwTrimOptions

The following option flags are listed in the order in which the trimming operations are performed. For example, OEM data is removed (TPD_OEMDATA) before duplicate points (TPD_COLLINEAR).

Constant	Description
TPD_RECALCSIZE	Recalculate size of pen data and reallocate if smaller.
TPD_UPPOINTS	Remove pen-up strokes from the HPENDATA object.
PHW_PRESSURE	Remove OEM pressure information.
PHW_HEIGHT	Remove OEM height information.
PHW_ANGLEXY	Remove OEM XY-angle information.
PHW_ANGLEZ	Remove OEM Z-angle information.
PHW_BARRELROTATION	Remove OEM barrel rotation information.
PHW_OEMSPECIFIC	Remove OEM-specific value information.
PHW_PDK	Remove per-point Pen Driver Kit (PDK_) information.
TPD_PHW	Remove all OEM and PDK information, but not stroke tick or user data.
TPD_OEMDATA	Remove all OEM values and PDK data.
TPD_PENINFO	Remove PENINFO structure from header. Note that any OEM information present is discarded.
TPD_COLLINEAR	Remove collinear and duplicate (coincident) points. There may not be any OEM data.
TPD_USER	Remove per-stroke user information.
TPD_TIME	Remove per-stroke timing information.
TPD_EMPTYSTROKES	Remove all strokes with 0 points.
TPD_EVERYTHING	Remove everything possible except pen-down strokes. This includes both TPD_ and PHW_ flags.
dwReserved

Must be 0.

Return Value

Returns PDR_OK if successful; otherwise, it returns one of the following negative values:

Constant	Description
PDR_COMPRESSED	The pen data was compressed.
PDR_ERROR	An unspecified memory error occurred.
PDR_MEMERR	Memory error.
PDR_OEMDATAERR	The pen data does not have specific pressure or height (PHW_) information. Thus, the specified PHW_ data could not be selectively trimmed. Use TPD_OEMDATA to remove all OEM information.
PDR_PNDTERR	Invalid pen data.
PDR_VERSIONERR	A version 1.0 pen data object could not be converted to the 2.0 format.
Comments

TrimPenData supplements the capabilities of CompressPenData. Together, these two functions replace the version 1.0 Pen API function CompactPenData, which is supported for compatibility only.

The data that hpndt points to must not be compressed. If it is, TrimPenData simply retrieves the original (untrimmed) pen data.

See Also

CompactPenData, CompressPenData, PDK_


UnhookResultsHookHREC [New - Windows 95]
 UnhookResultsHookHREC

2.0      [New - Windows 95]

Unhooks a recognizer result hook set with the SetResultsHookHREC function.

int UnhookResultsHookHREC( HREC hrec, HRECHOOK hHook )

Parameters

hrec

Module handle of the recognizer library. If this value is NULL, the system default recognizer is used.

hHook

Handle of the hook function.

Return Value

Returns HRCR_OK if successful; otherwise, returns one of the following negative values:

Constant	Description
HRCR_ERROR	Invalid parameter or other error.
HRCR_MEMERR	Insufficient memory.
See Also

ResultsHookHREC, SetResultsHookHREC


UninstallRecognizer [New - Windows 95]
 UninstallRecognizer

1.0     2.0      [New - Windows 95]

Unloads a recognizer previously installed with InstallRecognizer.

void UninstallRecognizer( HREC hrec )

Parameters

hrec

Recognizer handle.

Return Value

This function does not return a value.

Comments

Windows maintains a use count for all installed recognizers and doesn't unload a recognizer until the last remaining client application has called UninstallRecognizer. For every call an application makes to InstallRecognizer, it must must make a matching call to UninstallRecognizer.

Before unloading a recognizer library, the system calls the recognizer's ConfigRecognizer function with the subfunction WCR_CLOSERECOGNIZER.

It is not necessary to uninstall the default recognizer; an application must uninstall all recognizers that it explicitly loads.

See Also

InstallRecognizer, ConfigHREC


UpdatePenInfo [New - Windows 95]
 UpdatePenInfo

1.0     2.0      [New - Windows 95]

Notifies the RC Manager that a PENINFO value has changed. This function is called by pen drivers compatible with version 1.0 of the Pen API.

Note  This function is provided only for compatibility with version 1.0 of the Pen API and will not be supported in future versions.

void UpdatePenInfo( LPPENINFO lppeninfo )

Parameters

lppeninfo

Address of a PENINFO structure containing the new information.

Return Value

This function does not return a value.

Comments

A PENINFO value may change when the user alters the driver parameters in the configuration dialog box. When this happens, the pen driver must call UpdatePenInfo to notify the RC Manager of the change.

See Also

PENINFO


WriteHWL [New - Windows 95]
 WriteHWL

2.0      [New - Windows 95]

Writes a word list to a file.

int WriteHWL( HWL hwl, HFILE hfile )

Parameters

hwl

Handle to a word list.

hfile

A handle to a file previously opened for writing.

Return Value

Returns HRCR_OK if successful; otherwise, returns one of the following negative values:

Constant	Description
HRCR_ERROR	Invalid parameter, or file or other error.
HRCR_MEMERR	Insufficient memory.
Comments

The words are saved as ANSI text, one word per line, followed by a carriage return and linefeed. The file must already exist and be open for writing. An application can append to the file by positioning the file pointer at the end before calling WriteHWL. In this context, a word can represent a phrase and contain spaces or other noncharacters, such as "New York" and "ne're-do-well."

For a description of word lists and how a recognizer uses them, see "Configuring the HRC" in Chapter 5, "The Recognition Process."

See Also

CreateHWL, ReadHWL


 Pen Application Programming Interface Structures

This chapter describes in alphabetical order the structures defined by the Pen Application Programming Interface (API). Each entry includes the structure typedef definition, descriptions of the structure members, and cross-references where appropriate. The entry heading identifies the Pen API version, such as 1.0 or 2.0, that supports the structure.


ABSTIME [New - Windows 95]
 ABSTIME

2.0      [New - Windows 95]

Absolute time structure.

typedef struct {

DWORD sec;

UINT ms;

} ABSTIME;

Members

sec

Number of seconds since 12:00 A.M. of January 1, 1970, as returned by the C run time library time function.

ms

Additional offset in milliseconds. This member can be any value from 0 through 999.

See Also

GetStrokeAttributes, SetStrokeAttributes, INTERVAL


ANIMATEINFO [New - Windows 95]
 ANIMATEINFO

2.0      [New - Windows 95]

Animation information used by the DrawPenDataEx function for animation control.

typedef struct {

DWORD cbSize;

UINT uSpeedPct;

UINT uPeriodCB;

UINT fuFlags;

LPARAM lParam;

DWORD dwReserved;

} ANIMATEINFO;

Members

cbSize

Size of this structure in bytes.

uSpeedPct

Drawing speed, expressed as a percentage of the user's entry speed. To redraw pen data at the same speed at which it was created, this value should be set to 100. A value of 0 halts drawing. Setting uSpeedPct to 0 is valid only if the lpfnAnimateCB parameter of DrawPenDataEx is defined. Otherwise, the drawing halts with no way to restart it. uSpeedPct can be changed by a call-back function.

uPeriodCB

Callback period in milliseconds. Typical values are 1 (very fast), 250 (fast), 1000 (slow), or 0 (never). Any value in uPeriodCB is ignored if the DrawPenDataEx argument lpfnAnimateCB is NULL. uPeriodCB may also be AI_CBSTROKE, to indicate that the callback should occur after each stroke is drawn.

fuFlags

Flags that control animation (can be 0). The AI_SKIPUPSTROKES option specifies that the time taken to account for the points in the up strokes should be ignored. If this flag is 0, and if the value in uSpeedPct is small enough, there will be a delay between pen-down strokes, reflecting the user's inter-stroke delay during creation of the pen data.

lParam

Application value to pass to the callback function set up by the lpfnAnimateCB argument of DrawPenDataEx.

dwReserved

Must be 0.

Comments

Before using ANIMATEINFO, an application must initialize cbSize with sizeof( ANIMATEINFO ).

See Also

AnimateProc, DrawPenDataEx


BOXEDITINFO [New - Windows 95]
 BOXEDITINFO

2.0      [New - Windows 95]

Size information for boxed edit control.

typedef struct {

int cxBox;

int cyBox;

int cxBase;

int cyBase;

int cyMid;

BOXLAYOUT boxlayout;

UINT wFlags;

BYTE szFaceName[BEI_FACESIZE];

UINT wFontHeight;

UINT rgwReserved[8];

} BOXEDITINFO;

Members

cxBox

Width of a single box.

cyBox

Height of a single box.

cxBase

In-box x-margin to guideline.

cyBase

In-box y-offset from top to baseline.

cyMid

Reserved for future use; must be set to 0.

boxlayout

BOXLAYOUT structure.

wFlags

Flags specifying boxed edit options. Currently, the only defined option is BEIF_BOXCROSS.

szFaceName[BEI_FACESIZE]

Font face name, where BEI_FACESIZE is defined as 32.

wFontHeight

Font height.

rgwReserved[8]

Reserved for future use; must be set to 0.

See Also

BOXLAYOUT


BOXLAYOUT [New - Windows 95]
 BOXLAYOUT

1.0    2.0      [New - Windows 95]

Specifies some of the characteristics of a bedit control. The GUIDE and BOXEDITINFO structures determine the rest. The HE_GETBOXLAYOUT and HE_SETBOXLAYOUT wParam values of the WM_PENCTL message retrieve and set the BOXLAYOUT structure for a bedit control.

For more details, see the WM_PENCTL message.

typedef struct {

int cyCusp;

int cyEndCusp;

UINT style;

DWORD dwReserved1;

DWORD dwReserved2;

DWORD dwReserved3;

} BOXLAYOUT;

Members

cyCusp

Height of the box in pixels when BXS_RECT is specified; otherwise, height of the cusp in pixels (in comb style).

cyEndCusp

Height of cusps, in pixels, at extreme ends.

style

Bitwise-OR combination of the following BXS_ flags:

Constant	Description
BXS_NONE	Default comb style.
BXS_RECT	Rectangular boxes (instead of comb style).
BXS_BOXCROSS	(Japanese version only.) Rectangular boxes with a small cross at the center of each cell. Note that any state set via this flag (or the absence of it) may be overridden by the user's selection of the BOXCROSS setting in the Bedit Control Panel.
dwReserved1

Reserved; must be set to 0.

dwReserved2

Reserved; must be set to 0.

dwReserved3

Reserved; must be set to 0.

Comments

The following table lists the default values for the BOXLAYOUT structure.

Value	Description
cyCusp	Equivalent in pixels of BXD_CUSPHEIGHT dialog units.
cyEndCusp	Equivalent in pixels of BXD_ENDCUSPHEIGHT dialog units.
style	Comb style.
Figure 11.1 shows the general layout of a boxed edit control. Some of the terms in the figure are explained in the reference entry for the GUIDE structure. Figure 11.2 shows an individual cell from a boxed edit control.

See Also

BOXEDITINFO, WM_PENCTL, GUIDE, BXD_


BOXRESULTS [New - Windows 95]
 BOXRESULTS

2.0      [New - Windows 95]

Contains box results for the GetBoxResultsHRC function.

typedef struct {

int indxBox;

HINKSET hinksetBox;

SYV rgSyv[1];

} BOXRESULTS;

Members

indxBox

Index of the box with respect to the GUIDE structure.

hinksetBox

An inkset representing the pen data that belongs to the box, if requested by the GetBoxResultsHRC function. This member can be NULL.

rgSyv[1]

Variable-length array of alternative guesses made by the recognizer. The guesses are arranged in descending order of confidence, so that the first alternative in the array is the most likely choice.

See Also

GetBoxResultsHRC, GUIDE


CALBSTRUCT [New - Windows 95]
 CALBSTRUCT

1.0    2.0      [New - Windows 95]

Pen calibration information.

typedef struct {

int wOffsetX;

int wOffsetY;

int wDistinctWidth;

int wDistinctHeight;

} CALBSTRUCT;

Members

wOffsetX

Value in tablet units to add to x-coordinates for proper calibration.

wOffsetY

Value in tablet units to add to y-coordinates for proper calibration.

wDistinctWidth

Specifies the number of distinct x-coordinates the tablet can detect.

wDistinctHeight

Specifies the number of distinct y-coordinates the tablet can detect. The wDistinctWidth and wDistinctHeight members have the same meanings and values as the identically-named members in the PENINFO structure.


CTLINITBEDIT [New - Windows 95]
 CTLINITBEDIT

2.0      [New - Windows 95]

Initialization information for a boxed edit (bedit) control.

typedef struct {

DWORD cbSize;

HWND hwnd;

int id;

int wSizeCategory;

WORD wFlags;

DWORD dwReserved;

} CTLINITBEDIT;

Members

cbSize

Size of this structure in bytes.

hwnd

Handle of a boxed edit window.

id

Control identifier.

wSizeCategory

Size category, which can be one of the following BESC_ constants:

Constant	Description
BESC_DEFAULT	Use the default size parameters to create the  boxed edit control. This results in the same behavior as BESC_KANJIFIXED for applications that have registered themselves through the  use of the SetPenAppFlags function with the RPI_KANJIFIXEDBEDIT flag. For all other applications, it results in the same behavior as BESC_ROMANFIXED.
BESC_ROMANFIXED	Comb-style bedit control with dimensions indicated by BXD_ constants (in dialog units). Meant for use with Roman characters.
BESC_KANJIFIXED	(Japanese version only.) Box-style bedit control with dimensions indicated by BXDK_ constants (in dialog units). Meant for use with kanji characters. This value should be used by applications that cannot handle user-defined box sizes.
BESC_USERDEFINED	A bedit control that can handle the box size parameters defined by the user. For further details, see the description for PMSC_BEDITCHANGE in the reference section for the WM_PENMISC message.
wFlags

Flags that determine certain properties of the boxed edit control. This can be a combination of the following values:

Constant	Description
CIB_NOGDMSG	(Not supported in Japanese version.)  Do not display the garbage-detection message box when writing in the bedit control.
CIB_NOACTIONHANDLE	Do not create action handles.
CIB_NOFLASHCURSOR	Do not change the cursor if tap-and-hold action is detected.
CIB_NOWRITING	(Japanese version only.) Do not allow pen input into the control. Other methods of inputting text, such as keyboard input or pasting from the keyboard, are allowed.
dwReserved

Reserved, should be set to 0.

Comments

Before using CTLINITBEDIT, an application must initialize cbSize with sizeof( CTLINITBEDIT ).

See Also

WM_CTLINIT


CTLINITHEDIT [New - Windows 95]
 CTLINITHEDIT

2.0      [New - Windows 95]

Initialization information for a handwriting edit (hedit) control.

typedef struct {

DWORD cbSize;

HWND hwnd;

int id;

DWORD dwFlags;

DWORD dwReserved;

} CTLINITHEDIT;

Members

cbSize

Size of this structure in bytes.

hwnd

Handle of boxed edit window.

id

Control identifier.

dwFlags

Flags that determine some properties of the hedit control. This can be a combination of the following values:

Constant	Description
CIH_NOGDMSG	(Not supported in Japanese version.) Do not put up the garbage-detection message box when writing in this hedit control.
CIH_NOACTIONHANDLE	Do not create action handles for this hedit control.
CIH_NOEDITTEXT	Do not show the edit text, insert text, or  writing tool dialogs when writing in this hedit control.
CIH_NOFLASHCURSOR	Do not change the cursor while doing tap-and-hold selection in this hedit control.
dwReserved

Reserved, should be set to 0.

Comments

Before using CTLINITHEDIT, an application must initialize cbSize with sizeof( CTLINITHEDIT ).

See Also

WM_CTLINIT


CTLINITIEDIT [New - Windows 95]
 CTLINITIEDIT

2.0      [New - Windows 95]

Specifies the initial settings and options of an ink edit (iedit) control. A pointer to this structure is passed to the parent window of the control as the lParam parameter of the WM_CTLINIT message. This forms the last step of the control's processing of the WM_CREATE message.

typedef struct {

DWORD cbSize;

HWND hwnd;

int id;

WORD ieb;

WORD iedo;

WORD iei;

WORD ien;

WORD ierec;

WORD ies;

WORD iesec;

HPENDATA hpndt;

WORD pdts;

HGDIOBJ hgdiobj;

HPEN hpenGrid;

POINT ptOrgGrid;

WORD wVGrid;

WORD wHGrid;

DWORD dwApp;

DWORD dwReserved;

} CTLINITIEDIT;

Members

cbSize

Size of this structure in bytes.

hwnd

Handle to an ink edit window.

id

Control identifier.

ieb

Background IEB_ bit values (see IE_SETBKGND).

iedo

Draw options IEDO_ bit values (see IE_SETDRAWOPTS).

iei

Ink input IEI_ bit values (see IE_SETINKINPUT).

ien

Notification IEN_ bit values (see IE_SETNOTIFY).

ierec

Recognition IEREC_ bit values (see IE_SETRECOG).

ies

Style IES_ bit values (see IE_GETSTYLE).

iesec

Security IESEC_ bit values (see IE_SETSECURITY).

hpndt

Initial pen data.

pdts

Initial map mode.

hgdiobj

Brush or bitmap, depending on background bits option in ieb.

hpenGrid

Pen to use in drawing grid.

ptOrgGrid

Point of origin for the grid lines.

wVGrid

Vertical grid line spacing.

wHGrid

Horizontal grid line spacing.

dwApp

Application data.

dwReserved

Reserved.

Comments

Before using CTLINITIEDIT, an application must initialize cbSize with sizeof( CTLINITIEDIT ).

See Also

IE_SETBKGND, IE_SETDRAWOPTS, IE_SETNOTIFY, IE_SETRECOG, IE_SETSECURITY, IE_GETSTYLE, IE_SETDRAWOPTS, WM_CTLINIT


CWX [New - Windows 95]
 CWX

2.0      [New - Windows 95]

Specifies optional parameters for the CorrectWritingEx function. (Japanese version only.)

typedef struct {

DWORD cbSize;

WORD wApplyFlags;

HWND hwndText;

HRC hrc;

char szCaption[CBCAPTIONCWX];

DWORD dwEditStyle;

DWORD dwSel;

DWORD dwFlags;

WORD ixkb;

WORD rgState[CKBCWX];

POINT ptUL;

SIZE sizeHW;

} CWX;

Members

cbSize

Size of this structure in bytes. This field must be initialized to sizeof(CWX).

wApplyFlags

Options to specify which members of this structure are to be used to override the most-recently-used values provided by default; not all fields qualify. If this value is 0, the most-recently-used settings will be shown; otherwise, this value can be a combination of the following values:

Constant	Description
CWXA_CONTEXT	Use the dwFlags member to specify context.
CWXA_KBD	Use the ixkb member to specify a keyboard.
CWXA_STATE	Apply the states provided in the rgState array.
CWXA_PTUL	Move the dialog box upper corner to the screen position specified by the ptUL member.
CWXA_SIZE	Use the window size specified by the sizeHW member while using the handwriting recognition tab.
CWXA_NOUPDATEMRU	Do not update the registry with the last state of the correction dialog. This causes any changes made to the position and state of the Data Input Window to be discarded. This has no effect on user changes to the text, however.
hwndText

Text window to which to send WM_GETTEXT and WM_SETTEXT messages. If this is NULL, the owner of the Correct Writing dialog box will be used.

hrc

Handle to a recognition context. If this is NULL, a WM_PENMISC message with the wParam parameter of PMSC_GETHRC will be sent to the owner window to get a recognition context. If that too is NULL, then a default context will be used. The system will destroy its copy of hrc before the call returns.

szCaption[CBCAPTIONCWX]

A null-terminated array of characters to be used for a dialog caption. If this string has 0 length, then the default caption "Edit Text" will be used. The maximum length of caption allowed is specified by the CBCAPTIONCWX constant.

dwEditStyle

Style to use for the Data Input Window's edit control. By default this is ES_LEFT. If this style includes ES_MULTILINE, entry of Return and Tab characters is allowed; otherwise, they are not allowed. In any case, the style of the actual edit control will look like a multiline edit control.

dwSel

Specifies the selection. The low-order word (LOWORD) is the start position and the high-order word (HIWORD) is the end position. The default values are 0 for start and 0xFFFF for end, to select all text.

dwFlags

Specifies context flags, provided that the CWXA_CONTEXT bit is set in the wApplyFlags member; otherwise, the most-recently-used context flags are used and this field is ignored. On return, this field contains the updated flags. The flags may be CWX_DEFAULT (0), or a bitwise-OR combination of the following constant values:

Constant	Description
CWX_TOPMOST	Specifies that the dialog window is to be a topmost window. The window is not topmost by default.
CWX_NOTOOLTIPS	Disables showing tool tips for graphical buttons. They are shown by default.
CWX_JPERIOD	Specifies that the Japanese period is to be used on some keys on the Data Input Window keypads. The English period is used by default.
CWX_JCOMMA	Specifies that the Japanese comma is to be used on some keys on the Data Input Window keypads. The English comma is used by default.
CWX_DEFAULT	Zero; none of the above flags are set.
ixkb

Specifies which Data Input Window keyboard, or handwriting input, is to be used first, provided that the CWXA_KBD bit is set in the wApplyFlags member; otherwise, the most-recently use keyboard is used and this field is ignored. On return, this field contains the updated keyboard identifier. This may be one of the following values:

Constant	Description
CWXK_HW	Handwriting, not keyboard, input. If this value is specified, most of the dialog will be available for handwriting input, and the dialog will be sizable.
CWXK_50	50-On keyboard.
CWXK_QWERTY	QWERTY keyboard, including Hiragana, Katakana, and Romaji-to-Kana conversion alternative states.
CWXK_ROMAJI	Condensed Romaji-to-Kana keyboard, similar to some pocket computers.
CWXK_NUM	Numeric and Telephone keyboard.
CWXK_KANJI	Kanji keyboard, which provides a method of specifying a Kanji character based on its strokes.
CWXK_CODE	Kanji Code Finder keyboard, which allows the lookup of a Kanji character based on its JIS, Shift-JIS, or Kuten code value.
CWXK_YOMI	Kanji character finder based on the sound, or "reading" (Yomi) of the character.
rgState[CKBCWX]

An array of keyboard states with which to initialize the CKBCWX number of keyboards, provided that the CWXA_STATE bit is set in the wApplyFlags member; otherwise, the most-recently-used states are used and this member is ignored. On return, this member contains the updated states. Each element of the array may be CWXKS_DEFAULT (0, which is equivalent to CWXKS_HAN + CWXKS_ROMA), or a bitwise-OR combination of the following constants:

Constant	Description
CWXKS_CAPS	Set CAPSLOCK state on QWERTY keyboard.
CWXKS_HAN	Set Hankaku (single-byte) state.
CWXKS_ZEN	Set Zenkaku (double-byte) state.
CWXKS_ROMA	Set Romaji characters state.
CWXKS_HIRA	Set Hiragana characters state.
CWXKS_KATA	Set Katakana characters state.
ptUL

Specifies the upper-left corner of the dialog in screen coordinates, provided that the CWXA_PTUL bit is set in the wApplyFlags member; otherwise, the most-recently-used position is used and this member is ignored. On return, this member contains the updated screen position of the upper-left corner.

sizeHW

Specifies the size of the dialog when it is in handwriting input mode, provided that the CWXA_SIZE bit is set in the wApplyFlags member; otherwise, the most-recently-used size is used and this field is ignored. On return, this field contains the updated size.

Comments

Note that even if some bits are not set in wApplyFlags, the corresponding structure members are still updated with the last-used values on return.

See Also

CorrectWritingEx


GUIDE [New - Windows 95]
 GUIDE

1.0    2.0      [New - Windows 95]

Specifies the characteristics of any guidelines used in the writing area.

typedef struct {

int xOrigin;

int yOrigin;

int cxBox;

int cyBox;

int cxBase;

int cyBase;

int cHorzBox;

int cVertBox;

int cyMid;

} GUIDE;

Members

xOrigin

Position of left edge of the first box in screen coordinates.

yOrigin

Position of top edge of the first box in screen coordinates.

cxBox

Width of each box in screen pixels.

cyBox

Height of each box in screen pixels.

cxBase

Margin to the guideline. This is one-half the distance in pixels between adjacent boxes.

cyBase

Vertical distance in pixels from the baseline to the top of the box.

cHorzBox

Number of columns of boxes.

cVertBox

Number of rows of boxes.

cyMid

Distance in pixels from the baseline to the midline, or 0 if midline is not present.

Comments

If the application has drawn guidelines on the screen on which the user is expected to write, the application should set the values in the GUIDE structure to inform the recognizer. The GUIDE structure is for the recognizer's use only. Setting the GUIDE structure does not by itself draw any visual clues on the display. It is the responsibility of the application or the control to draw the visual clues. The appearance of a boxed edit control is determined by the BOXLAYOUT and GUIDE structures together.

The xOrigin and yOrigin members are screen coordinates of the top-left corner of the area to write in. The cyBox and cxBox members are the height and width of the individual boxes to write in. The cHorzBox and cVertBox members specify the number of columns and rows. cyBase specifies a baseline within the box. (Setting cyBase to 0 indicates no baseline.) The cxBase member gives a horizontal displacement of the edge of the guideline from the edge of the box where writing is expected to start.

If only horizontal lines are present, set cxBox to 0. In this case, only yOrigin, cyBox, cyBase, and cyMid are valid. A default GUIDE structure has all elements set to 0.

To establish a guide, initialize a GUIDE structure and set it into an HRC with the SetGuideHRC function. This also applies to a standard bedit, as demonstrated in "The bedit Control" in Chapter 3.

For boxed input, the GetBoxMappingHRCRESULT function returns an index to the box containing the requested input character. This is numbered in zero-based row-major order. In Figure 11.3 below, for example, the "h" character is in box 12.

For best recognition results, the pair-wise ratios of cxBox, cyBox, and cyBase should be similar to the default ratios.

See Also

SetGuideHRC, BOXLAYOUT, BXD_


INKINGINFO [New - Windows 95]
 INKINGINFO

2.0      [New - Windows 95]

Provides information about where and how the system should display ink.

typedef struct {

DWORD cbSize;

UINT wFlags;

PENTIP tip;

RECT rectClip;

RECT rectInkStop;

HRGN hrgnClip;

HRGN hrgnInkStop;

} INKINGINFO;

Members

cbSize

Size of this structure in bytes.

wFlags

A bitwise-OR combination of the following PII_ flags:

Constant	Description
PII_INKPENTIP	Use tip for pen characteristics.
PII_INKCLIPRECT	Clip ink using rectClip.
PII_INKSTOPRECT	Terminate inking on a pen-down event inside rectInkStop.
PII_INKCLIPRGN	Clip ink using hrgnClip. If hrgnClip is set,  any value in rectClip is disregarded.
PII_INKSTOPRGN	Terminate inking on a pen-down event inside hrgnInkStop.
PII_SAVEBACKGROUND	Save the background that is being inked on.  The saved background is restored when the current input session terminates.
PII_CLIPSTOP	Directs Windows to stop inking if the pen  goes down outside rectClip or hrgnClip, if either have been set.
tip

A PENTIP structure defining the pen type, size, and color.

rectClip

Clipping rectangle for the ink. Setting rectClip to {−32767, −32767, 32767, 32767} is equivalent to having no clipping region.

rectInkStop

Rectangle in which a pen-down event stops inking. Setting rectInkStop to empty is equivalent to not having an ink stop region.

hrgnClip

Clipping region for the ink. Setting hrgnClip to NULL is equivalent to not having a clipping region.

hrgnInkStop

Region in which a pen-down event stops inking. Setting hrgnInkStop to NULL is equivalent to not having an ink stop region.

Comments

All areas are in screen coordinates.

The wFlags member specifies which of the other members contain valid information. For example, if PII_INKCLIPRECT is set in wFlags, the rectClip member specifies the clipping rectangle. Otherwise, a default value is used.

Before using INKINGINFO, an application must initialize cbSize with sizeof( INKINGINFO ).

See Also

PENTIP, StartInking, WM_PENEVENT


INPPARAMS [New - Windows 95]
 INPPARAMS

2.0      [New - Windows 95]

Describes a set of targets.

typedef struct {

DWORD cbSize;

DWORD dwFlags;

HPENDATA hpndt;

TARGET target;

} INPPARAMS;

Members

cbSize

Size of this structure in bytes.

dwFlags

Reserved for future use; must be 0.

hpndt

Handle to a pen data object.

target

A TARGET structure where input is directed.

Comments

Before using INPPARAMS, an application must initialize cbSize with sizeof( INPPARAMS ).

See Also

TARGET


INTERVAL [New - Windows 95]
 INTERVAL

2.0      [New - Windows 95]

Interval structure for inksets.

typedef struct {

ABSTIME atBegin;

ABSTIME atEnd;

} INTERVAL;

Members

atBegin

Beginning of 1-millisecond granularity interval.

atEnd

Time at 1 millisecond past end of interval.

See Also

ABSTIME


OEMPENINFO [New - Windows 95]
 OEMPENINFO

1.0    2.0      [New - Windows 95]

Structure containing original equipment manufacturer (OEM) hardware information for the pen or tablet.

typedef struct {

UINT wPdt;

UINT wValueMax;

UINT wDistinct;

} OEMPENINFO;

Members

wPdt

A combination of PDT_ values.

wValueMax

The largest value returned by the device.

wDistinct

The number of distinct readings possible.

Comments

The OEMPENINFO structure contains a description of the additional OEM information that the hardware can generate. It is a component of the PENINFO structure.

Besides capturing the x- and y- coordinates of the pen movement, a pen device has the option of providing a number of other types of input data, such as pen pressure, height of the pen tip above the tablet surface, angle of the pen, and so on. A pen driver can capture up to MAXOEMDATAWORDS types of data, where MAXOEMDATAWORDS is defined as six. An application can access the OEM data through the GetPenInput function. A recognizer can receive OEM data from an application through the AddPenInputHRC function. It is the up to the application whether to send this data or not.

Each pen event generates a packet of information from the pen driver that contains the current pen position and, optionally, other types of OEM information. The cbOemData member of the PENINFO structure specifies the width of the optional OEM data in bytes. Each type of data is one word wide. The type of data in the nth word of the OEM data packet is given by the nth element of the rgoempeninfo member (an array of OEMPENINFO structures) in the PENINFO structure.

For the wPdt member, PDT_NULL indicates no data. Values greater than PDT_OEMSPECIFIC are reserved for private use by drivers for data types not currently defined as standard. The wValueMax member contains the largest variable size the device can return for that data type. The wDistinct member is the number of distinct readings the device can take between 0 and wValueMax.

For a list of values for the wPdt member, see the entry for PDT_ values in Chapter 13, "Pen Application Programming Interface Constants."

Example

As an example of how to use OEMPENINFO, consider a device that can sense both the height above the tablet surface and the Z-angle of the pen. Assume the device can sense 256 levels of height in a range from 0 to 10 centimeters and has a resolution of 1 degree on the angle of the pen. The two additional words of OEM information occupy 4 bytes, so the cbOemData and rgoempeninfo members of PENINFO look like this:

peninfo.cbOemData = 4

peninfo.rgoempeninfo[MAXOEMDATAWORDS] = {

{PDT_HEIGHT, 1000, 256},

{PDT_ANGLEZ, 1800, 180},

{PDT NULL, 0, 0},

{PDT_NULL, 0, 0},

{PDT_NULL, 0, 0},

{PDT_NULL, 0, 0} };

This optional information is saved by the pen driver in the same manner as the x- and y- coordinate data. There must be a one-to-one correspondence between the OEM event data and the coordinate data.

Figure 11.5 shows the pen in a position where both the Xy-angle and Z-angle are approximately 45 degrees.

See Also

PENINFO


OEM_PENPACKET [New - Windows 95]
 OEM_PENPACKET

2.0      [New - Windows 95]

A pen packet used by Pen API, version 2.0, consisting of the information received from the pen device for a single sample. For a definition of pen packet, see SetPenHook.

typedef struct {

UINT wTabletX;

UINT wTabletY;

UINT wPDK;

UINT rgwOemData[MAXOEMDATAWORDS];

DWORD dwTime;

} PENPACKET;

Members

wTabletX

The x-dimension in raw tablet coordinates.

wTabletY

The y-dimension in raw tablet coordinates.

wPDK

Pen hardware state bits, expressed as a combination of PDK_ values.

rgwOemData[MAXOEMDATAWORDS]

Array of OEM-specific data. MAXOEMDATAWORDS is defined as 6.

dwTime

Time stamp indicating when the pen packet originated.

Comments

A pen packet is the basic unit of communication between the pen driver and Windows. A pen packet contains all of the information about a single logical event: x-y coordinate position, button states, and any optional information such as pressure or barrel rotation. Several physical events—that is, interrupts—may be needed to construct a single logical event.

The rgwOemData member contains the data relating to the OEM hardware, such as pen pressure, angle, and so forth.

See Also

SetPenHookCallback, OEMPENINFO, PENPACKET


PCMINFO [New - Windows 95]
 PCMINFO

2.0      [New - Windows 95]

Pen collection mode information. All regions and rectangles are in screen coordinates. Time-out values are in milliseconds.

typedef struct {

DWORD cbSize;

DWORD dwPcm;

RECT rectBound;

RECT rectExclude;

HRGN hrgnBound;

HRGN hrgnExclude;

DWORD dwTimeout;

} PCMINFO;

Members

cbSize

Size of this structure in bytes.

dwPcm

A combination of PCM_ flags specifying options for pen collection.

rectBound

Bounding rectangle for pen collection.

rectExclude

Exclusion rectangle for pen collection.

hrgnBound

Bounding region for pen collection.

hrgnExclude

Exclusion region for pen collection.

dwTimeout

Time-out before terminating pen collection.

Comments

Before using PCMINFO, an application must initialize cbSize with sizeof( PCMINFO ).

See Also

StartPenInput, WM_PENEVENT, PCM_


PDEVENT [New - Windows 95]
 PDEVENT

2.0      [New - Windows 95]

Provides details of the pointing-device event that is the subject of an IN_PDEVENT notification. A pointing-device event can be a pen tap, mouse double-click, and so on. This structure is returned by the IE_GETPDEVENT message.

typedef struct {

DWORD cbSize;

HWND hwnd;

UINT wm;

WPARAM wParam;

LPARAM lParam;

POINT pt;

BOOL fPen;

LONG lExInfo;

DWORD dwReserved;

} PDEVENT;

Members

cbSize

Size of this structure in bytes.

hwnd

Handle to ink edit window.

wm

Window WM_ message.

wParam

wParam of event.

lParam

lParam of event.

pt

Event point in ink edit client coordinates.

fPen

TRUE if pen event, FALSE if mouse event.

lExInfo

Windows GetMessageExtraInfo function return value.

dwReserved

Reserved.

Comments

Before using PDEVENT, an application must initialize cbSize with sizeof( PDEVENT ).

For descriptions of the WM_ messages that pertain to pen-based computing, refer to Chapter 12, "Pen Application Programming Interface Messages."

See Also

IE_GETPDEVENT, IN_PDEVENT


PENDATAHEADER [New - Windows 95]
 PENDATAHEADER

1.0    2.0      [New - Windows 95]

Main header of an HPENDATA memory block.

typedef struct {

UINT wVersion;

UINT cbSizeUsed;

UINT cStrokes;

UINT cPnt;

UINT cPntStrokeMax;

RECT rectBound;

UINT wPndts;

int nInkWidth;

DWORD rgbInk;

} PENDATAHEADER;

Members

wVersion

Pen data format version. Same as the version number for the Pen API, which is currently 0x0002. Calling GetPenDataAttributes with the GPA_VERSION argument retrieves the value of wVersion.

cbSizeUsed

Size (in bytes) of pen data memory block.

cStrokes

Number of strokes in the block. (Each pen-down and pen-up sequence counts as a single stroke.)

cPnt

Count of all points in the block. Calling GetPenDataAttributes with the GPA_POINTS argument retrieves the value of cPnt.

cPntStrokeMax

Length (in points) of longest stroke. Calling GetPenDataAttributes with the GPA_MAXLEN argument retrieves the value of cPntStrokeMax.

rectBound

Bounding rectangle of all pen-down points.

wPndts

Data scaling metric value, expressed as a bitwise-OR combination of PDTS_ values.

nInkWidth

Ink width, in pixels.

rgbInk

Ink color.

Comments

The PENDATAHEADER structure describes the contents of an HPENDATA memory block. Use the GetPenDataInfo or GetPenDataAttributes function to retrieve information from a PENDATAHEADER structure.

For a description of the HPENDATA memory block, see "The HPENDATA Object" in Chapter 4, "The Inking Process."

For a list of data scaling values, refer to the entry for PDTS_ values in Chapter 13, "Pen Application Programming Interface Constants."

See Also

GetPenDataInfo, GetPenDataAttributes, PDTS_


PENINFO [New - Windows 95]
 PENINFO

1.0    2.0      [New - Windows 95]

Contains dimensions, sampling rate, and other information about the pen or tablet hardware.

typedef struct {

UINT cxRawWidth;

UINT cyRawHeight;

UINT wDistinctWidth;

UINT wDistinctHeight;

int nSamplingRate;

int nSamplingDist;

LONG lPdc;

int cPens;

int cbOemData;

OEMPENINFO rgoempeninfo[MAXOEMDATAWORDS];

UINT rgwReserved[7];

UINT fuOEM;

} PENINFO;

Members

cxRawWidth

Width of tablet in thousandths of an inch. Also specifies the maximum tablet x-coordinate.

cyRawHeight

Height of tablet in thousandths of an inch. Also specifies the maximum tablet y-coordinate.

wDistinctWidth

Number of distinct x-coordinates the hardware can detect.

wDistinctHeight

Number of distinct y-coordinates the hardware can detect. Together, the wDistinctWidth and wDistinctHeight members express the x-y resolution of the tablet. For example, if a tablet is 8 inches wide and has a resolution of 1/500 of an inch, cxRawWidth is 8000 and wDistinctWidth is 4000 because the tablet hardware can return 4000 distinct x-order values ranging from 0 to 8000.

nSamplingRate

Specifies the number of samples per second the tablet can return. This value may be less than the number of hardware interrupts per second the tablet generates because several interrupts may be required to create one pen packet sample. See the "Comments" section below for information on adjusting the sampling rate.

nSamplingDist

Specifies the distance in distinct tablet units a pen must travel before a new pen event is generated. See the "Comments" section below for information on adjusting the sampling distance.

lPdc

Pen-device capabilities, expressed as a bitwise-OR combination of the PDC_ flags.

cPens

Number of pens the tablet can simultaneously support.

cbOemData

Specifies the width, in bytes, of the additional OEM data passed in each pen packet. For example, if a tablet can detect pressure and Z-angle information, this information occupies two additional words of OEM data, so cbOemData is 4.

rgoempeninfo[MAXOEMDATAWORDS]

An array of OEMPENINFO structures. Each structure describes one word of additional OEM data contained in each pen packet. (MAXOEMDATAWORDS is defined as 6.)

rgwReserved[7]

Reserved for internal use.

fuOEM

Flags representing which OEM data to report in rgoempeninfo; used by applications to determine the OEM data used in an HPENDATA object. This member is set and used internally by the pen services and should never be modified by an application. This member is a bitwise-OR combination of the following values:

Constant	Description
PHW_ALL	Report all available OEM data.
PHW_PRESSURE	Report pressure if available.
PHW_HEIGHT	Report height if available.
PHW_ANGLEXY	Report Xy-angle if available.
PHW_ANGLEZ	Report Z-angle if available.
PHW_BARRELROTATION	Report barrel rotation if available.
PHW_OEMSPECIFIC	Report OEM-specific value if available.
PHW_PDK	Report per-point PDK_ values.
Comments

The DRV_GetPenInfo pen driver message fills a PENINFO structure with the current device parameters. DRV_GetPenInfo returns FALSE if a tablet is not present. If this occurs, the PENINFO structure that the message's lParam1 points to is not valid. Note that an application should retrieve tablet information with the GetPenDataInfo and GetPenDataAttributes functions, rather than accessing the pen driver directly.

An application can also adjust the tablet sampling rate and sampling distance by sending the DRV_SetSamplingRate or DRV_SetSamplingDist messages to the device driver. For more information, see Appendix E, "Accessing the Pen Device Driver."

For a list of state bits for the pen driver, refer to the entry for PDK_ values in Chapter 13, "Pen Application Programming Interface Constants."

See Also

CreatePenDataEx, GetPenDataInfo, TrimPenData, UpdatePenInfo, OEMPENINFO


PENPACKET [New - Windows 95]
 PENPACKET

1.0    2.0      [New - Windows 95]

A pen packet used by Pen Windows, version 1.0, consisting of the information received from the pen device for a single sample. For a definition of pen packet, see SetPenHook.

typedef struct {

UINT wTabletX;

UINT wTabletY;

UINT wPDK;

UINT rgwOemData[MAXOEMDATAWORDS];

} PENPACKET;

Members

wTabletX

The x-dimension in raw tablet coordinates.

wTabletY

The y-dimension in raw tablet coordinates.

wPDK

Pen hardware state bits, expressed as a combination of PDK_ values.

rgwOemData[MAXOEMDATAWORDS]

Array of OEM-specific data. MAXOEMDATAWORDS is defined as 6.

Comments

A pen packet is the basic unit of communication between the pen driver and Windows. A pen packet contains all of the information about a single logical event: x-y coordinate position, button states, and any optional information such as pressure or barrel rotation. Several physical events—that is, interrupts—may be needed to construct a single logical event.

The rgwOemData member contains the real-time values associated with the pen data types described in the entry for the OEMPENINFO structure.

See Also

SetPenHookCallback, OEMPENINFO, OEM_PENPACKET


PENTIP [New - Windows 95]
 PENTIP

2.0      [New - Windows 95]

Pen tip characteristics.

typedef struct {

DWORD cbSize;

BYTE btype;

BYTE bwidth;

BYTE bheight;

BYTE bOpacity;

COLORREF rgb;

DWORD dwFlags;

DWORD dwReserved;

} PENTIP;

Members

cbSize

Size of this structure in bytes.

btype

Pen nib type. Types in the range 0 through 63 are reserved for predefined standard types. An application can use values in the range 64 through 255.

bwidth

Pen nib width, in display device units (pixels).

bheight

Pen nib height, in display device units (pixels). In the current version of the Pen API, this member is ignored.

bOpacity

Opacity of the ink, which corresponds to the JOT standard. bOpacity must have one of the following values:

Constant	Description
PENTIP_OPAQUE	New ink overwrites any existing ink.
PENTIP_HILITE	New ink is visible but partly transparent, possibly interacting with underlying ink.
PENTIP_TRANSPARENT	Ink is completely transparent. There is no interaction with any underlying ink.
rgb

RGB pen color.

dwFlags

Reserved.

dwReserved

Reserved; must be set to 0.

Comments

Before using PENTIP, an application must initialize cbSize with sizeof( PENTIP ).

See Also

GetStrokeAttributes, SetStrokeAttributes, GetStrokeTableAttributes, SetStrokeTableAttributes, GetPenMiscInfo, SetPenMiscInfo, INKINGINFO


RC [New - Windows 95]
 RC

1.0    2.0      [New - Windows 95]

Defines a recognition context (RC) for applications compatible with version 1.0 of the Pen API. Applications that do not call the superseded functions Recognize or RecognizeData do not use the RC structure. These applications instead use HRC objects, which render RC obsolete.

Note

The RC structure is provided only for compatibility with version 1.0 of the Pen API and will not be supported in future versions.

typedef struct {

HREC hrec;

HWND hwnd;

UINT wEventRef;

UINT wRcPreferences;

LONG lRcOptions;

RCYIELDPROC lpfnYield;

BYTE lpUser[cbRcUserMax];

UINT wCountry;

UINT wIntlPreferences;

char lpLanguage[cbRcLanguageMax];

LPDF rglpdf[MAXDICTIONARIES];

UINT wTryDictionary;

CL clErrorLevel;

ALC alc;

ALC alcPriority;

BYTE rgbfAlc[cbRcrgbfAlcMax];

UINT wResultMode;

UINT wTimeOut;

LONG lPcm;

RECT rectBound;

RECT rectExclude;

GUIDE guide;

UINT wRcOrient;

UINT wRcDirect;

int nInkWidth;

COLORREF rgbInk;

DWORD dwAppParam;

DWORD dwDictParam;

DWORD dwRecognizer;

UINT rgwReserved[cwRcReservedMax];

} RC;

Members

hrec

Handle of recognizer to use.

hwnd

Window to which results are sent.

wEventRef

Index into ink buffer.

wRcPreferences

Flags specifying preferences, described in "Comments" section.

lRcOptions

Recognition options, described in "Comments" section.

lpfnYield

Procedure called during processing of the Yield Windows function.

lpUser[cbRcUserMax]

Current writer.

wCountry

Country code.

wIntlPreferences

Flags for international preferences.

lpLanguage[cbRcLanguageMax]

Language strings.

rglpdf[MAXDICTIONARIES]

List of dictionary functions.

wTryDictionary

Maximum enumerations to search.

clErrorLevel

Level where recognizer should reject input.

alc

Enabled ALC_ alphabet codes.

alcPriority

Sets priority of the ALC_ codes.

rgbfAlc[cbRcrgbfAlcMax]

Bit field for enabled characters.

wResultMode

Result return mode specifying when to send (either as soon as possible or when complete). The RRM_ codes are described in "Comments" section.

wTimeOut

Recognition time-out in milliseconds.

lPcm

Bitwise-OR combination of PCM_ flags for ending the recognition session.

rectBound

Bounding rectangle for inking. By default, the rectangle is in screen coordinates.

rectExclude

A pen-down event inside this rectangle terminates recognition.

guide

GUIDE structure that defines guidelines for recognizer.

wRcOrient

Orientation of writing with regard to the tablet.

wRcDirect

Direction of writing.

nInkWidth

Ink width of 1−15 pixels. A value of 0 prevents display of the ink.

rgbInk

Ink color.

dwAppParam

For application use.

dwDictParam

For application use; to be passed on to dictionaries.

dwRecognizer

For application use; to be passed on to recognizer.

rgwReserved[cwRcReservedMax]

Reserved.

Comments

The following paragraphs discuss the RC members, listed in the order in which they appear in the preceding structure.

hrec

The hrec member is the handle of the recognizer to use. This value should be set to the value returned by a previous call to InstallRecognizer, or to RC_WDEFAULT for the default recognizer.

If hrec is NULL, no recognizer is used. WM_RCRESULT messages are generated as with a real recognizer, but the wResultsType member of RCRESULT is set to RCRT_NORECOG, and the hSyv and lpsyv members are set to NULL. (For a list of other values in wResultsType, see the entry for RCRT_ values in Chapter 13, "Pen Application Programming Interface Constants.")

hwnd

The hwnd member specifies the window to send recognition results to. This member cannot be NULL. Also, the mouse capture is set to this window to clear the queue of pending mouse messages that were meant for recognition.

wEventRef

The value for wEventRef indicates which tablet data to begin recognition with. The wEventRef member is returned from the GetMessageExtraInfo function.

InitRC sets this member to RC_WDEFAULT. If Recognize is called during the processing of the WM_LBUTTONDOWN message that initiates the input session, the application need take no other action.

Before an application starts recognition on some other Windows event, it should use GetMessageExtraInfo to save the event reference of the appropriate mouse message and place this value in wEventRef before calling Recognize.

This member is not used on calls to RecognizeData.

wRcPreferences

The wRcPreferences member specifies the user preferences as a combination of RCP_ constants.

lRcOptions

The lRcOptions member specifies various options for recognition. It is a bitwise-OR combination of RCO_ constants.

lpfnYield

The lpfnYield member points to a callback function used by the recognizer before it yields. The application sets this to NULL for no yield processing. Recognition can often take more than a few seconds; therefore, a recognizer should periodically call the yield function to yield control to other Windows tasks. The default yield function is:

BOOL FAR PASCAL StandardYieldFunction()

{

Yield( );

return 1;

}

If Recognize or RecognizeData is called with lpfnYield set to RC_LDEFAULT, then the default yield function is called. If the lpfnYield member is not NULL, the recognizer calls lpfnYield every time before it yields.

lpUser

#define	cbRcUserMax	32

BYTE	lpUser[cbRcUserMax];

The lpUser member specifies the name of the current writer. The current writer is used to specify any custom prototype sets that might be available to the recognizer. If the lpUser member is NULL, it means that the recognizer should use the standard prototype set—that is, the prototype set as it existed before it was modified (through training, for example).

wCountry

The wCountry member contains the country code. The values for country code are the same as the values used by the International item of the Control Panel for the iCountry member in the [intl] section of the WIN.INI file.

wIntlPreferences

The wIntlPreferences member contains a combination of various RCIP_ flags. Currently, this member can be only 0 or RCIP_ALLANSICHAR. If 0, only characters from the current language or languages are enabled. If wIntlPreferences is RCIP_ALLANSICHAR, the entire ANSI character set is enabled.

lpLanguage

#define	cbRcLanguageMax	44

char	lpLanguage[cbRcLanguageMax]

The lpLanguage member is a list of language strings. Each string is null-terminated and the list ends with a null string.

The set of values for each language string is the same as the set used by the International item of the Control Panel for the sLanguage member in the [Intl] section of the WIN.INI file. These three-letter codes are documented in the Microsoft Windows Software Development Kit.

A recognizer should implement recognition of the ANSI character set and then use this information during recognition to limit a match to the appropriate subset. The lpLanguage member holds strictly optional information; a recognizer may choose to ignore it. By definition, the character set implied by a language string is the set of characters that can be generated from the country-specific keyboard without using the ALT+numeric keypad combinations. It is still possible to enter ANSI characters outside the given language through the use of the onscreen keyboard and ALT+numeric keypad combinations.

rglpdf

#define	MAXDICTIONARIES 16

LPDF	rglpdf[MAXDICTIONARIES]

The dictionary path member rglpdf specifies which dictionaries are called by the RC Manager to convert symbol graphs into strings.

If rglpdf[0] is NULL, the NULL dictionary path is used. The NULL dictionary path indicates that the first enumeration from the symbol graph is used as the best enumeration. The array of dictionary functions is null-terminated. During recognition, the dictionary functions are called in the order in which they appear. For more details, see the entry for the DictionarySearch function.

wTryDictionary

The wTryDictionary member specifies the maximum number of enumerations generated from the symbol graph during dictionary processing on the results of recognition. The minimum number allowed is 1 and the maximum is 4096. The default value is 100.

clErrorLevel

Recognition accuracy is defined as the percentage of times the recognizer accurately assigns a symbol to an input. There is no penalty or gain if the recognizer does not attempt a match and returns "unknown." The value can range from 0 to 100.

There are situations in which a higher accuracy rating is preferable despite an increased number of unknown results. For example, in a forms application, the Social Security field must be correctly recognized. If the recognizer is unsure, it can get the application to prompt the user again for the input (or a portion of it). At other times, it is preferable that the recognizer make a guess, no matter how wild, in order to limit the number of unknown results. For example, while taking notes in a meeting, the user may not care whether all of the results are transcribed perfectly.

The clErrorLevel member allows the application to signal its preference to the recognizer. Recognizers should return the SYV_UNKNOWN symbol for any symbol having a confidence level below clErrorLevel.

alc

The alc member is used to define the enabled alphabet for any RC structure with ALC_ constants. Any of the ALC_ constants can be combined together with a bitwise-OR operator to form the desired set of characters.

The actual characters enabled depend on the language. For example, if the user has requested French language support, the letter "è" is included in the lowercase alphabet. In the same way, "£" replaces "$" if ALC_MONETARY is set in British systems. For a list of alphabet values, see the entry for ALC_ values in Chapter 13, "Pen Application Programming Interface Constants."

Setting the RCIP_ALLANSICHAR flag in the wIntlPreferences member of the RC structure enables all characters of the appropriate set regardless of the language setting.

A recognizer that recognizes characters other than ANSI can ignore this member. If you want an application to pass character subset information to private non-ANSI recognizers, you can use the dwRecognizer member.

A recognizer should not return a symbol value outside the specified subset. However, a recognizer does not have to force a match to the subset; it can return SYV_UNKNOWN if a suitable match is not found.

alcPriority

The alcPriority member sets the priority of the ALC_ codes used to enable alphabets. It does this by telling the recognizer in which order to list options in the symbol graph.

The alcPriority member uses the same ALC_ codes used in the alc member. The bits set in alcPriority should be a subset of those set in alc. Bits set in alcPriority that are not also set in the alc member have no effect.

A recognizer can recognize a glyph that belongs to more than one enabled ALC_ subset. For example, a vertical stroke can be the letter "l" in the ALC_LCALPHA subset or the number "1" in the ALC_NUMERIC subset. The alcPriority member specifies that the recognizer should first return those interpretations that are in the subsets indicated in alcPriority. If no interpretations are in any of the alcPriority sets, or no priority members are set, the recognizer returns all possibilities within the enabled sets.

For example, suppose the user writes a symbol that looks like either a "q" or a "9." The generated symbol graph contains {q | 9 }. The alcPriority member determines the exact look of the symbol graph. If alcPriority has the ALC_ALPHA bit set, the recognizer should return { q | 9 } in the symbol graph. If alcPriority has the ALC_NUMERIC bit set, the recognizer should return { 9 | q } in the symbol graph.

Note that alcPriority does not affect the dictionary processing directly.

If ALC_USEBITMAP is set, the rgbfAlc member indicates which characters have priority.

rgbfAlc

#define	cbRcrgbfAlcMax	32

BYTE	rgbfAlc[cbRcrgbfAlcMax];

The rgbfAlc member is the bit field used for enabled characters. For more details, see the description of ALC_ constants. If ALC_USEBITMAP is set, the 256-bit bit field in rgbfAlc is used to indicate which characters from the ANSI character set are currently enabled. Character 0 is the low bit of the low-order byte in the array. Characters thus indicated are connected by OR operators to any characters enabled using the other ALC_ codes. A "1" set in a bit array indicates that the character is enabled.

As an example, to enable the "$" character, set the fifth bit of byte four like this:

rgbfAlc[4] |= 0x10

A recognizer that recognizes characters other than ANSI can ignore this member. If an application wants to pass character subset information to private non-ANSI recognizers, it can use the dwRecognizer member of the RC structure.

A set of macros, defined in PENWIN.H, simplifies user setting and testing the rgbfAlc bits for an RC structure. The ANSI macros listed in the following table set (bit=1), clear (bit=0), or test (TRUE if bit==1, else FALSE) the appropriate bits in lprc->rgbfAlc corresponding to the index i, which is the ANSI value to use. The lprc is a pointer to the RC structure containing the rgbfAlc[] array.

Macro	Description
SetAlcBitAnsi( lprc, i )	Sets the bit specified by i in rgbfAlc of lprc to 1.
ResetAlcBitAnsi( lprc, i )	Resets the bit specified by i in rgbfAlc of lprc to 0.
IsAlcBitAnsi( lprc, i )	Returns TRUE if the bit specified by i in rgbfAlc of lprc is set.
Only the IsAlcBitAnsi macro returns a value (BOOL). The return values of the other macros are undefined.

Setting bits in rgbfAlc[] also requires combining ALC_USEBITMAP by an OR operator with alc for the bits to have meaning. The bits are used in addition to other alc settings. For example, adding ALC_NUMERIC does not also set the bits in rgbfAlc that correspond to 0 through 9. Thus, to recognize octal numbers (the set 0 to 7), use the following code:

RC rc;

int i;

rc.alc = ALC_USEBITMAP;                // Note no ALC_NUMERIC

for (i = (int)'0'; i <= (int)'7'; i++)

SetAlcBitAnsi( &rc, i );

wResultMode

The wResultMode member specifies the timing and granularity of the results messages to be sent back to the specified window. The following times are defined.

Constant	Description
RRM_WORD	The granularity is set at a word boundary. As soon as the recognizer sees a word break, it can send all symbols up to the point of the word break.
RRM_NEWLINE	The granularity is set at a new line. As soon as the recognizer sees a line break, it sends the result to that point.
RRM_COMPLETE	When recognition is completed by one of the methods (for example, time-out or barrel button), the results message is sent just before Recognize returns.
RRM_STROKE	The granularity is set at the stroke level. A result message is sent at each stroke. This is used in the NULL recognizer.
RRM_SYMBOL	The granularity is set at the symbol level. A result message is sent at each symbol. Default dictionary processing is disabled when this value is used.
A recognizer is free to send the messages any time after the requested time (defined in the preceding order), but it cannot send any messages sooner. Because of recognizer constraints, a recognizer may combine intermediate results messages. For example, if an application requests RRM_WORD, the recognizer may choose to return results on a line-by-line basis instead.

Results sent at a word boundary do not have to be sent strictly one word at a time. The requirements are as follows:

•	The raw data returned must be contiguous, and it must begin with a pen-down and end with a pen-up.

•	The returned "word" may contain spaces. For example, "fat{space | NULL}cat" would be resolved into two words, "fat cat." This is also necessary if the raw data for successive words overlaps.

•	The recognizer should not send a word until it knows what follows the word. If the word is followed by a word on the same line, the word should be space-terminated. If the word is followed by text on a new line, the recognizer should append a soft newline symbol. The key point is that the recognizer must make it possible for the application to detect word and line spacing so it can display the recognized text appropriately.

•	Once a word has been sent, the recognizer cannot change the results because of the late arrival of more strokes.

The rules for returning results with RRM_NEWLINE are similar:

•	The new line should be included with the symbol graph in the result.

•	Once a word has been sent, the recognizer cannot change the results because of the late arrival of more strokes.

wTimeOut

The wTimeOut member specifies the time-out threshold. After the time-out threshold has passed, the recognizer stops the recognition process.

Time-out occurs if more than wTimeOut milliseconds elapse between the most recent pen-up and the next pen-down. If time-out occurs, the recognition context is closed. Closing a recognition context means no more data is accepted; the existing data is processed and the results are sent to the application. This value is ignored if lPcm does not enable time-out.

In general, applications should use the value set by the user in the Control Panel. This value can be set by setting this member to RC_WDEFAULT.

The maximum value allowed is 65,534 milliseconds. If wTimeOut is set to 0xFFFF (65,535), the system-level value is used.

lPcmrectBound
rectExclude

These three members of the RC structure set the conditions for ending recognition. The lPcm member sets the flags for ending recognition, expressed as a bitwise-OR combination of PCM_ values.

The two RECT members specify inclusive and exclusive rectangles for inking. The rectangle values are in screen coordinates or, if RCO_TABLETCOORD is set, in tablet coordinates. RCO_TABLETCOORD cannot be used with ProcessWriting.

When RCRESULT is returned, the rectBound and rectExclude values are converted from screen to tablet coordinates and the RCO_TABLETCOORD flag is set.

Only pen events within rectBound are collected as part of the recognition context. If PCM_RECTBOUND is set in lPcm, the first pen-down event outside the rectangle closes the context. Dragging the pen outside the rectangle after starting inside does not close the context; the data is still collected outside the rectangle.

If PCM_RECTEXCLUDE is set in lPcm, any pen-down event within rectExclude closes the context. The event that ends pen collection mode—that is, an event outside the bounding rectangle or inside the exclusion—is entered into Windows as a mouse event. For hit-testing the rectangles, the top and left borders are included, but not the right or bottom borders.

The bounding rectangle set by InitRC is valid only until the window is resized or moved. If the window is moved or resized, the application should specify again the rectBound member in the RC structure.

guide

The guide member is a structure of the GUIDE type. It contains information that specifies the placement of guidelines in the writing area for the recognizer's use.

wRcOrient

The wRcOrient member specifies the orientation of the tablet, expressed as RCOR_ values. For a list of orientation values, see the entry for RCOR_ values in Chapter 13, "Pen Application Programming Interface Constants."

wRcDirect

The wRcDirect member informs the recognizer of the direction of writing, expressed as RCOR_ values. There are both primary and secondary directions. For example, English is written from left to right (primary) and then down the page (secondary). Chinese is often written from the top down (primary) and then right to left across the page (secondary). For a list of direction values, see the entry for RCD_ values in Chapter 13, "Pen Application Programming Interface Constants."

The high byte of the direction indicates primary direction; the low byte, secondary direction. A recognizer can choose to ignore this word and support only the natural direction of the given language. The default value is determined by the recognizer.

Not all recognizers can respond to this member.

nInkWidth
rgbInk

These two members specify the ink width and color to be used during inking. The nInkWidth member is the thickness in pixels of the pen to use during inking. If this value is 0, no ink is drawn. The current maximum value allowed is 15. The default is the ink width set in the global RC.

The rgbInk member is the color to use for inking. If this is not a solid color, it is mapped to the closest solid color. The default is the ink color set in the global RC.

dwAppParam
dwRecognizer

These two members are analogous to the dwDictParam member described below. The dwAppParam value is provided for use by the application and passed to the application by way of the lprc member in the RCRESULT structure.

The dwRecognizer value is passed to the recognizer specified in rc.hrec. Applications can use this to pass information to a private recognizer for functionality not directly supported.

These values are set to 0 by InitRC and should remain 0 if they are not used by the application or recognizer.

dwDictParam

The dwDictParam parameter is set by an application and passed on to the dictionary by the RC Manager. It is intended to provide for dictionary functionality not directly supported. For example, a dictionary can request that the application pass in a pointer to a structure that contains a given sentence. You can use this information to extend the dictionary functionality—to highlight misspelled words, for example.

If it is not used by the application, dwDictParam should be left to the value (0) set by InitRC.

rgwReserved[cwRcReservedMax]

The rgwReserved member is reserved. Applications should not change the values set by InitRC for this member.

See Also

GUIDE, PCMINFO

ALC_, RCRT_, PCM_, RCD_, RCOR_


RCRESULT [New - Windows 95]
 RCRESULT

1.0    2.0      [New - Windows 95]

Applications that do not call the superseded functions RecognizeData or Recognize do not use the RCRESULT structure. In conforming to version 2.0 of the Pen API, applications instead use HRCRESULT objects, which render RCRESULT obsolete.

Note

The RCRESULT structure is provided only for compatibility with version 1.0 of the Pen API, and will not be supported in future versions.

typedef struct {

SYG syg;

UINT wResultsType;

int cSyv;

LPSYV lpsyv;

HANDLE hSyv;

int nBaseLine;

int nMidLine;

HPENDATA hpendata;

RECT rectBoundInk;

POINT pntEnd;

LPRC lprc;

} RCRESULT;

Members

syg

Symbol graph.

wResultsType

An RCRT_ value.

cSyv

Number of symbol values, not including the NULL terminator.

lpsyv

Null-terminated pointer to the recognizer's best guess.

hSyv

Globally shared handle to the symbol value specified by the lpsyv member.

nBaseLine

Zero or baseline of input writing.

nMidLine

Zero or midline of input writing.

hpendata

Handle to pen data.

rectBoundInk

Bounding rectangle for ink.

pntEnd

Point that terminated recognition.

lprc

Recognition context used.

Comments

When an application calls Recognize, RecognizeData, or ProcessWriting, the WM_RCRESULT message is sent to the appropriate window procedure when the recognizer has a result to return. The wParam parameter of the message contains the reason recognition ended (one of the REC_ codes). It is REC_OK if more results will be sent; otherwise, it is the same value for the last message returned by Recognize or RecognizeData. The lParam parameter is a far pointer to an RCRESULT structure. All of the data in the RCRESULT structure is in tablet coordinates.

 The following sections elaborate on the RCRESULT members. All of the members are allocated with GMEM_SHARE so they can be passed between processes.

syg

This member contains the raw results returned by the recognizer. These include the various possible interpretations of the pen input, the mapping of the results to the raw data, and locations of any hot spots if the result is a gesture. The syg.lpsyc member is not valid unless RCP_MAPCHAR was set in the RC structure when Recognize or RecognizeData was called.

wResultsType

This member indicates the type of recognition results, expressed as a bitwise-OR combination of RCRT_ values. The RCRT_ values are not mutually exclusive. Note that the recognizer should never have to set RCRT_GESTURETOKEYS, RCRT_ALREADYPROCESSED,  or RCRT_GESTURETRANSLATED. For a list of values, see the entry for RCRT_ values in Chapter 13, "Pen Application Programming Interface Constants."

lpsyv

This member contains the symbols that are recognized. An application should use these values to display the text or gestures recognized. The lpsyv member is the result of any dictionary search on the SYG structure or further postprocessing. It is NULL if the NULL recognizer is used.

hpendata

This member contains the raw data captured during inking.

rectBoundInk

This is the bounding rectangle of the ink drawn during recognition. It is in coordinates of the window that receives the results. If the user attempts to draw ink outside rc.rectbound, the ink will not be displayed. However, rectBoundInk is calculated as though the ink were drawn.

If data is collected outside the bounding rectangle, the rectBound member of PENDATAHEADER reflects this. (Note that rectBound applies only to pen-down points.) This means, however, that a portion of the rectBoundInk rectangle lies outside the rc.rectBound rectangle. The actual ink drawn lies in the intersection of rectBoundInk and the rc.rectBound rectangle. Before calculating the intersection, convert rectBoundInk from tablet to screen coordinates. The bounding rectangle includes the width of the ink drawn.

pntEnd

If recognition ended on a tap outside the bounding rectangle or inside the exclusive rectangle, pntEnd contains the coordinates of those points in display coordinates.

lprc

This is the RC used for recognition. Any default values (RC_WDEFAULT or RC_LDEFAULT) are replaced by the correct default value.

See Also

RC, SYG, RCRT_


RECTOFS [New - Windows 95]
 RECTOFS

1.0    2.0      [New - Windows 95]

Rectangle offset for nonisometric inflation of a rectangular writing area.

typedef struct {

int dLeft;

int dTop;

int dRight;

int dBottom;

} RECTOFS;

Members

dLeft

Inflation margin leftward from left side.

dTop

Inflation margin upward from top.

dRight

Inflation margin rightward from right.

dBottom

Inflation margin downward from bottom.

Comments

Inflation margins are in screen (pixel) coordinates. To inflate a window rectangle, dLeft and dTop should be negative (moving in the negative x- and y-directions, respectively) and dRight and dBottom should be positive. To deflate the rectangle, reverse the signs of the margins.

In addition to having the basic characteristics of an edit control, an hedit or bedit control must make allowances for the input of handwriting. The client rectangle often needs to be adjusted to a larger size to allow for easier writing.

For example, the cut gesture typically extends above the selected text it is deleting. If the gesture is arbitrarily clipped off at the edge of the client window, recognition accuracy suffers. Likewise, restricting handwriting input to stay within the lines can also hinder recognition accuracy. To correct this, rectangle offsets are used in hedit and bedit controls to make the writing area slightly larger than the client window size of a normal edit control. The HE_SETINFLATE and HE_GETINFLATE wParam values of the WM_PENCTL message are used for this purpose. These messages use a RECTOFS structure as a parameter. The values in the RECTOFS structure are added to the corresponding client area to create the bounding rectangle for the ink.

The inflation does not need to be symmetrical in every direction.

See Also

WM_PENCTL, HE_SETINFLATE, HE_GETINFLATE


SKBINFO [New - Windows 95]
 SKBINFO

1.0    2.0      [New - Windows 95]

Stores information about the current onscreen keyboard.

typedef struct {

HWND hwnd;

UINT nPad;

BOOL fVisible;

BOOL fMinimized;

RECT rect;

DWORD dwReserved;

} SKBINFO;

Members

hwnd

Handle of window for onscreen keyboard.

nPad

Current view of the keypad. Either SKB_FULL, SKB_BASIC, or SKB_NUMPAD for full, basic, or numeric keypad, respectively.

fVisible

TRUE if the keyboard is available and visible, FALSE otherwise.

fMinimized

TRUE if the keyboard is minimized, FALSE otherwise.

rect

Screen coordinates or the restored keyboard rectangle.

dwReserved

Must be 0.

See Also

ShowKeyboard


STRKFMT [New - Windows 95]
 STRKFMT

2.0      [New - Windows 95]

Provides a method for retrieving or changing the attributes of specified strokes in an iedit control. This structure is used by the IE_GETFORMAT and IE_SETFORMAT messages.

typedef struct {

DWORD cbSize;

UINT iesf;

UINT iStrk;

PENTIP tip;

DWORD dwUser;

DWORD dwReserved;

} STRKFMT;

Members

cbSize

Size of this structure in bytes.

iesf

Stroke format flags. Note that the first three flags cannot be combined with each other by the bitwise OR operator:

Constant	Description
IESF_ALL	Assume all strokes in the control.
IESF_SELECTION	Assume all selected strokes.
IESF_STROKE	Assume the stroke specified in the iStrk member, described in "Comments" section.
IESF_PENTIP	Set both pen tip color and width.
IESF_TIPCOLOR	Set only pen tip color.
IESF_TIPWIDTH	Set only pen tip width.
iStrk

Index of a specific stroke.

tip

PENTIP structure, containing ink tip attributes.

dwUser

User data for stroke.

dwReserved

Reserved.

Comments

When sending either IE_GETFORMAT or IE_SETFORMAT, the application initializes the iesf member with bit flags, indicating:

•	The strokes in the iedit control to which the IE_ messages refer.

•	The attributes (color and/or width) of those strokes.

Setting the IESF_STROKE bit flag in iesf limits action to the single stroke identified in iStrk. Setting IESF_SELECTION references all selected strokes. Setting IESF_ALL references all strokes in the control. These flags are mutually exclusive and cannot be combined.

The application must also set the bit flags IESF_TIPCOLOR or IESF_TIPWIDTH in the iesf member of the structure. These bit flags identify the stroke attribute to which the IE_ messages refer. For convenience, the defined value IESF_PENTIP combines IESF_TIPCOLOR and IESF_TIPWIDTH to identify both color and width.

With these bit flags, an application can alter stroke color and width at the same time or alter only one attribute while leaving the other unchanged.

Sending an IE_GETFORMAT message to the control produces the following results:

•	If the requested strokes have the same color and width, the returned STRKFMT contains the common color and width in the rgb and bwidth members of its PENTIP structure. The return value from IE_GETFORMAT is 0.

•	If the requested strokes do not all share the same attribute, the returned STRKFMT contains the attribute of the last stroke in the group. The return value from IE_GETFORMAT contains the bit flags IESF_TIPCOLOR and/or IESF_TIPWIDTH to indicate the attribute in which the strokes differ.

Before using STRKFMT, an application must initialize cbSize with sizeof( STRKFMT ).

See Also

IE_GETFORMAT, IE_SETFORMAT, PENTIP


STROKEINFO [New - Windows 95]
 STROKEINFO

1.0    2.0      [New - Windows 95]

Contains information about a sequence of pen data.

typedef struct {

UINT cPnt;

UINT cbPnts;

UINT wPdk;

DWORD dwTick;

} STROKEINFO;

Members

cPnt

Count of points in the stroke.

cbPnts

Used internally to contain length of compressed data. Applications should ignore this value.

wPdk

State of the stroke, expressed as a PDK_ value.

dwTick

Time at beginning of the stroke. dwTick holds the number of milliseconds that have elapsed since the system tick reference that Windows determines at startup.

Comments

The STROKEINFO structure serves two main purposes. First, it is returned by the  GetPenHwEventData functions with each piece of new data from the tablet. Second, it is used in certain pen data functions such as AddPenInputHRC, AddPointsPenData, and GetPenDataStroke as a header for each stroke. In both cases, it contains information about a sequence of data from the tablet.

For examples and further information about STROKEINFO and its members, see the section "Recognition Functions" in Chapter 8, "Writing a Recognizer."

For a list of stroke state bits, refer to the entry for PDK_ values in Chapter 13, "Pen Application Programming Interface Constants."

See Also

AddPenInputHRC, GetPenDataStroke, GetPenInput, GetPenHwEventData, InsertPenDataStroke, TargetPoints, PDK_


SYC [New - Windows 95]
 SYC

1.0    2.0      [New - Windows 95]

The SYC symbol correspondence structure is best described in context with the SYG symbol graph and SYE symbol element structures. For a description of the SYC structure, see the entry for SYG below.

Note

The SYC structure is provided only for compatibility with version 1.0 of the Pen API and will not be supported in future versions.

A single shape can be identified by one or more SYC structures.

typedef struct {

UINT    wStrokeFirst;

UINT    wPntFirst;

UINT    wStrokeLast;

UINT    wPntLast;

BOOL    fLastSyc;

} SYC;

Members

wStrokeFirst

Index number of the first stroke of the correspondence.

wPntFirst

Index number of the first point in the stroke identified by wStrokeFirst.

wStrokeLast

Index number of the last stroke of the correspondence.

wPntLast

Index number of the last point in the stroke identified by wStrokeLast.

fLastSyc

TRUE if there are no more SYC structures for the current SYE (symbol element).

Comments

All indexes are zero-based, so that an index of 0 indicates the first of a sequence.

Figure 11.6 illustrates the relationship of symbol values and symbol graphs. The first line shows that a symbol value is a single SYE symbol element. A series of symbol values can be connected by the SYV_OR value to create an OR string, as the second line illustrates. This OR string begins with the SYV_BEGINOR value and ends with a symbol value followed by SYV_ENDOR. The third line shows a symbol graph that is simply a symbol value or an OR string, in either case ending with the SYV_NULL value.

See Also

RCRESULT, TrainContext, SYV_


SYE [New - Windows 95]
 SYE

1.0    2.0      [New - Windows 95]

The SYE symbol element structure is best described in context with the SYG symbol graph and SYC symbol correspondence structures. For a description of the SYE structure, see the entry for SYG below.

Note

The SYE structure is provided only for compatibility with version 1.0 of the Pen API, and will not be supported in future versions.

An SYE structure contains a symbol, which can be a character, gesture, or string.

typedef struct {

SYV     syv;

LONG    lRecogVal;

CL      cl;

int     iSyc;

} SYE;

Members

syv

Symbol value.

lRecogVal

Reserved.

cl

Confidence level.

iSyc

Index into array of SYC structures. The array identifies the raw data that makes up the symbol. It is possible for several SYE structures to use the same SYC structures.


SYG [New - Windows 95]
 SYG

1.0    2.0      [New - Windows 95]

A symbol graph, which represents the possible interpretations identified by the recognizer.

typedef struct {

POINT rgpntHotSpots[MAXHOTSPOT];

int cHotSpot;

int nFirstBox;

LONG lRecogVal;

LPSYE lpsye;

int cSye;

LPSYC lpsyc;

int cSyc;

SYV syv;

LONG lRecogVal;

CL cl;

int iSyc;

UINT wStrokeFirst;

UINT wPntFirst;

UINT wStrokeLast;

UINT wPntLast;

BOOL fLastSyc;

} SYG;

Members

rgpntHotSpots[MAXHOTSPOT]

Hot spots of the symbol (if any). MAXHOTSPOT is defined as 8.

cHotSpot

Number of valid hot spots in rgpntHotSpots.

nFirstBox

Row-major index to box of first character in result.

lRecogVal

Reserved.

lpsye

Pointer to array of SYE structures representing nodes of symbol graph.

cSye

Number of SYE structures in array lpsye.

lpsyc

Pointer to corresponding array of SYC symbol ink structures.

cSyc

Number of SYC structures in symbol graph.

Comments

All indexes are zero-based.

If a single entity recognized by the recognizer is mapped to a string of several symbol values, the recognizer creates multiple SYE. This is the case for recognizers that can recognize highly stylized sequences of characters—for example, "ing"—in which the individual characters are not necessarily recognized.

The nFirstBox member has no meaning for gestures. A gesture is applied to the location indicated by its hot spot.

The SYG, SYE, and SYC structures define the relationship between raw pen data and recognized results. However, in version 2.0 of the Pen API they are rarely of interest to applications for two reasons. First, API functions return recognition results without forcing the application to deal with the complexities of raw pen data. And second, SYG, SYE, and SYC apply mainly to recognizers.

All nontrivial recognizers should somehow track the pen strokes that form each character in the returned results. To be compatible with version 1.0, a recognizer must use the SYG, SYE, and SYC structures and return a symbol graph—an SYG structure—as a member of the RCRESULT structure. Version 2.0 does not mandate how a recognizer should map pen data to symbols. However, these three structures represent a viable method. Recognizer developers writing for version 2.0 may want to use the structures or create variations.

The following information applies to version 1.0 applications and recognizers, and to version 2.0 recognizers that employ symbol graphs to relate strokes to recognized symbols. For further information about SYG, SYE, and SYC, see "Returning Results" in Chapter 8, "Writing a Recognizer."

A symbol graph is a representation of the possible interpretations identified by the recognizer. The RC Manager processes the symbol graph using the dictionary path to identify the best interpretation. This best interpretation is returned in the results message along with the symbol graph.

A symbol value is a 32-bit value that represents a glyph (such as a character or a gesture) recognized by a recognizer. This is sometimes referred to as a symbol. A symbol string is an array of symbols terminated with SYV_NULL.

Each element of the symbol graph, an SYE, contains information about the recognized character—for example, bounding rectangle and hot spots. The SYC structure maps SYE structures back to the corresponding raw data. If two or more consecutive SYE structures map to the same SYC, they represent an indivisible unit. For example, the user might teach the system of "th" with the crossbar of the "t" connected to the "h." SYC structures are used primarily for training.

A version 1.0 application generally does not use the symbol graph directly. Instead, it uses the hSyv member of RCRESULT, which contains a symbol string that represents the best interpretation from the symbol graph. SYE and SYC structures work together with the HPENDATA memory block to identify strokes and meanings for ink. The following table lists the basic functions of these structures.

Structure	Description
HPENDATA	Contains raw data information: strokes, pen up, pen down, points, and so on.
SYC	A symbol character map. SYC structures delimit strokes in an HPENDATA. A single shape can be identified  by one or more SYC structures. Each SYC identifies a starting stroke, an ending stroke, a starting point, and an ending point. A flag also indicates whether subsequent SYC structures in the array contain additional strokes for the shape. (This feature is used for delayed strokes, such as the cross stroke of the letter "t.")
SYE	A symbol element. An SYE contains a symbol, which can be a character, a gesture, or a string. The symbol  is denoted by an SYV. The SYE contains an index into an array of SYC structures; this array identifies the  raw data that makes up the symbol. It is possible for several SYEs to use the same SYC structures. The  SYC structures contain indexes into the raw data.
SYV	A symbol value.
SYG	A symbol graph.
A set of SYEs and SYCs, together with an HPENDATA structure, is sufficient to define ink and specify how that ink should be interpreted. The training functions TrainContext and TrainInk use this information in training.


TARGET [New - Windows 95]
 TARGET

2.0      [New - Windows 95]

Contains information about a single target.

typedef struct {

DWORD dwFlags;

DWORD idTarget;

HTRG htrgTarget;

RECTL rectBound;

DWORD dwData;

RECTL rectBoundInk;

RECTL rectBoundLastInk;

} TARGET;

Members

dwFlags

Reserved for future extensions. Must be set to 0.

idTarget

Array index to the target within rgTarget array in TARGINFO structure.

htrgTarget

Handle to the owner window that receives messages on behalf of the target.

rectBound

Bounding rectangle of the target.

dwData

Target-specific extra information to be filled during data collection.

rectBoundInk

Reserved; must be 0.

rectBoundLastInk

Reserved; must be 0.

See Also

TargetPoints, TARGINFO, WM_PENEVENT, INPPARAMS


TARGINFO [New - Windows 95]
 TARGINFO

2.0      [New - Windows 95]

A set of targets.

typedef struct {

DWORD cbSize;

DWORD dwFlags;

HTRG htrgOwner;

WORD cTargets;

WORD iTargetLast;

TARGET rgTarget[1];

} TARGINFO;

Members

cbSize

Size of this structure in bytes. Note that this is the original size, which assumes only a single TARGET structure in rgTarget. The value should be sizeof( TARGINFO ).

dwFlags

Flags have been defined to get different targeting behavior depending on the needs of the calling application. These flags work as hints for the targeting algorithm. The flags are considered by the Pen API in the order in which they appear in the following list. If none of the flags are set, the stroke is not assigned to any target.

TPT_TEXTUAL

When this flag is set, Windows applies textual heuristics, such as identifying word breaks, while deciding the target to which a stroke should be assigned.

If there is no text to intersect with, the input is disregarded completely. Therefore, this option should not generally be used by itself.

TPT_INTERSECTINK

Indicates that if the stroke being targeted intersects with the ink in a target, the stroke should be assigned to that target. Intersection is determined based on the bounding rectangle of the stroke and the bounding rectangle of the pen data assigned to a target. If there is no ink to intersect with, the input is disregarded completely. Therefore, this option should not generally be used by itself.

TPT_CLOSEST

Indicates that the stroke should be targeted to the target closest to the stroke. The bounding rectangle of the stroke and the bounding rectangle of the target are specified by the rectBound element of the TARGET structure.

htrgOwner

Handle to the owner target. Use the HtrgFromHwnd and HwndFromHtrg macros to convert a target handle of HTRG type to and from an HWND type.

cTargets

Number of targets.

iTargetLast

Last target. Used by the TargetPoints function during textual heuristics. iTargetLast contains the number of the target window that last received data. The system uses this value to optimize its determination of the next target. Applications can read but should not overwrite iTargetLast.

rgTarget[1]

Variable-length array of targets.

Comments

For best results, most applications should set all hints for targeting. That is, the dwFlags member of TARGINFO should be set to TPT_DEFAULT, which is the combination of TPT_TEXTUAL | TPT_INTERSECTINK | TPT_CLOSEST.

Before using TARGINFO, an application must initialize cbSize with sizeof( TARGINFO ).

See Also

TARGET, TargetPoints


 Pen Application Programming Interface Messages

This chapter describes in alphabetical order many of the messages and submessages defined by the Pen Application Programming Interface. Each entry describes a separate message organized under the following topic headings:

Topic heading	Description
Parameters	Message wParam and lParam parameters.
Return Value	Return value from the Windows SendMessage function (if applicable).
Comments	Additional information about the message.
See Also	Cross-references to related API services.


HE_CANCELCONVERT [New - Windows 95]
 HE_CANCELCONVERT

[New - Windows 95]

Cancels Kana-to-Kanji conversion. Submessage of WM_PENCTL. (Japanese version only.)

Parameters

wParam

HE_CANCELCONVERT.

lParam

Reserved and must be 0.

Return Value

Returns TRUE if there are no errors; otherwise, returns FALSE.


HE_CHAROFFSET [New - Windows 95]
 HE_CHAROFFSET

[New - Windows 95]

Converts the logical character position of a character in a control into a byte offset to the character. Submessage of WM_PENCTL.

Parameters

wParam

HE_CHAROFFSET.

lParam

The low-order word contains the logical character position. The high-order word is reserved and must be 0.

Return Value

If the supplied logical character position is less than the total number of logical characters in the control, the low-order word of the return value contains the requested byte offset of the position and the high-order word is 0. Otherwise, the low-order word contains the length of the text in bytes and the high word contains 0xFFFF.

Comments

This submessage is for bedit controls only. Both the logical character position and the byte offset are zero-based.

See Also

WM_PENCTL


HE_CHARPOSITION [New - Windows 95]
 HE_CHARPOSITION

[New - Windows 95]

Converts a byte offset in the text buffer of a control to the logical character position, which contains the byte specified by the byte offset. Submessage of WM_PENCTL.

Parameters

wParam

HE_CHARPOSITION.

lParam

The low-order word contains the byte offset. The high word is reserved and must be 0.

Return Value

If the supplied byte offset is less than the length of the text in bytes, the low-order word of the return value contains the logical character position and the high-order word is 0; otherwise, the low-order word contains the total number of logical characters in the text of the control and the high-order word contains 0xFFFF.

Comments

This submessage is for bedit controls only. Both the byte offset and the logical character position are zero-based.

See Also

HE_CHAROFFSET, WM_PENCTL


HE_DEFAULTFONT [New - Windows 95]
 HE_DEFAULTFONT

[New - Windows 95]

Switches the font of a bedit control to the default font that the bedit control selected at the time of creation. Submessage of WM_PENCTL.

Parameters

wParam

HE_DEFAULTFONT.

lParam

If the low-order word is nonzero, the control is repainted.

Return Value

The return value is undefined.

Comments

This submessage is for bedit controls only.

See Also

WM_PENCTL


HE_ENABLEALTLIST [New - Windows 95]
 HE_ENABLEALTLIST

[New - Windows 95]

Enables or disables the alternate list in a bedit control. Submessage of WM_PENCTL.

Parameters

wParam

HE_ENABLEALTLIST.

lParam

If the low-order word is nonzero, the alternate list menu is enabled; otherwise, it is disabled.

Return Value

The return value is undefined.

Comments

This submessage is for bedit controls only.

See Also

HE_HIDEALTLIST, HE_SHOWALTLIST, WM_PENCTL


HE_FIXKKCONVERT [New - Windows 95]
 HE_FIXKKCONVERT

[New - Windows 95]

Confirm undetermined string and close Input Method Editor (IME). Submessage of WM_PENCTL. (Japanese version only.)

Parameters

wParam

HE_FIXKKCONVERT.

lParam

Reserved and must be 0.

Return Value

Returns TRUE if there are no errors; otherwise, returns FALSE.

Comments

When in preconversion mode, the marked conversion string area is removed. Marked conversion strings are indicated in the Input Method Editor (IME) in a different shade than standard edit control text selection. When in conversion mode (no marked string), the string is confirmed and the IME is closed. Available for bedits only.


HE_GETBOXLAYOUT [New - Windows 95]
 HE_GETBOXLAYOUT

[New - Windows 95]

Retrieves the box layout for a control. Submessage of WM_PENCTL.

Parameters

wParam

HE_GETBOXLAYOUT.

lParam

Address of a BOXLAYOUT structure that is filled with the current box layout for the control.

Return Value

The return value is undefined.

Comments

This submessage is for bedit controls only.

See Also

BOXLAYOUT, WM_PENCTL


HE_GETCONVERTRANGE [New - Windows 95]
 HE_GETCONVERTRANGE

[New - Windows 95]

Gets the range of the marked conversion string. Submessage of WM_PENCTL. (Japanese version only.)

Parameters

wParam

HE_GETCONVERTCHAR.

lParam

Not used.

Return Value

Returns a 32-bit value with the starting character position (not byte position) of the marked conversion string in the low-order word and the position of the last character of the marked conversion string plus 1 in the high-order word.

Comments

Available for bedits only. The message returns a valid value only when in preconversion mode; otherwise, it returns 0.


HE_GETINFLATE [New - Windows 95]
 HE_GETINFLATE

[New - Windows 95]

Retrieves the inflation rectangle for a control. Submessage of WM_PENCTL.

Parameters

wParam

HE_GETINFLATE.

lParam

Address of a RECTOFS structure that is filled with the current values for the inflation rectangle.

Return Value

Returns TRUE if successful; otherwise, FALSE.

Comments

For a description of how to increase or decrease the writing area of a control, see "HE_SETINFLATE Submessage" in Chapter 3, "The Writing Process."

See Also

HE_SETINFLATE, RECTOFS, WM_PENCTL


HE_GETINKHANDLE [New - Windows 95]
 HE_GETINKHANDLE

[New - Windows 95]

Retrieves the ink handle for the current control. Submessage of WM_PENCTL.

Parameters

wParam

HE_GETINKHANDLE.

lParam

Unused.

Return Value

The low-order word of the return value contains a handle to the captured ink. If the return value is NULL, the control is not in ink mode.

Comments

The returned ink handle is valid only during the life of the control. The handle becomes invalid after the control is destroyed.

See Also

WM_PENCTL


HE_GETKKCONVERT [New - Windows 95]
 HE_GETKKCONVERT

[New - Windows 95]

Determines if the Input Method Editor (IME) is in conversion mode. Submessage of WM_PENCTL. (Japanese version only.)

Parameters

wParam

HE_GETKKCONVERT.

lParam

Reserved and must be 0.

Return Value

Returns TRUE if the IME is in conversion mode; otherwise, returns FALSE.

Comments

Available for bedits only.


HE_GETKKSTATUS [New - Windows 95]
 HE_GETKKSTATUS

[New - Windows 95]

Determines the mode of the Kana-to-Kanji conversion in the Input Method Editor (IME). Submessage of WM_PENCTL. (Japanese version only.)

Parameters

wParam

HE_GETKKSTATUS.

lParam

Reserved and must be 0.

Return Value

Returns one of the following values or FALSE:

Value	Current Status
HEKKR_PRECONVERT	In preconversion mode.
HEKKR_CONVERT	In conversion mode
HHEKKR_NOCONVERT	In nonconversion mode
Comments

The IME recognizes three modes: preconversion mode, conversion mode, and non-conversion mode. In preconversion mode, the user has entered text intended for conversion by the IME and the text is marked. When the user invokes the IME on the marked range of characters, the conversion mode is entered and the IME is active. Once the user confirms an IME conversion, the nonconversion mode (normal mode) is entered.

The term "marked" refers to the range of cells in the bedit that have been selected for character conversion. Characters marked for conversion appear differently to the user than normally selected characters.

This submessage is available for bedits only. This message can also be used to determine keyboard IME status by checking for HEKKR_CONVERT.


HE_GETUNDERLINE [New - Windows 95]
 HE_GETUNDERLINE

[New - Windows 95]

Queries for the current underline mode. Submessage of WM_PENCTL.

Parameters

wParam

HE_GETUNDERLINE.

lParam

Unused.

Return Value

Returns TRUE if the underline mode is set; otherwise, FALSE.

Comments

This submessage is for hedit controls only.

See Also

WM_PENCTL


HE_HIDEALTLIST [New - Windows 95]
 HE_HIDEALTLIST

[New - Windows 95]

Hides the alternate list in a bedit control, assuming an alternate list menu is being displayed. Submessage of WM_PENCTL.

Parameters

wParam

HE_HIDEALTLIST.

lParam

If the low-order word is HEAL_DEFAULT, the alternate list menu is hidden.

Return Value

The return value is undefined.

Comments

This submessage is for bedit controls only.

See Also

HE_ENABLEALTLIST, HE_SHOWTLIST, WM_PENCTL


HE_KKCONVERT [New - Windows 95]
 HE_KKCONVERT

[New - Windows 95]

Starts Kana-to-Kanji conversion. Submessage of WM_PENCTL. (Japanese version only.)

Parameters

wParam

HE_KKCONVERT.

lParam

Must be one of the following values:

Value	Meaning
HEKK_DEFAULT	The first time the conversion is specified, the selected character string is replaced with the conversion result; the second time it is specified, the conversion candidate dialog box appears.
HEKK_CONVERT	The selected character string is replaced with the conversion result regardless of how many times conversion has been specified.
HEKK_CANDIDATE	Causes the conversion candidate dialog box to appear.
HEKK_DBCSCHAR	The SBCS characters (0x20 − 0x7E, 0xA1 − 0xDF) are replaced by their DBCS equivalents.
HEKK_SBCSCHAR	The DBCS characters in the selected character string or marked conversion string that have equivalent SBCS representations are replaced by their equivalent SBCS characters.
HEKK_HIRAGANA	The katakana characters (DBCS or SBCS) in the selected character string or marked conversion string are replaced with their hiragana equivalents.
HEKK_KATAKANA	The hiragana characters in the selected character string or marked conversion string are replaced with their DBCS katakana representation.
Return Value

Returns TRUE if there are no errors; otherwise, returns FALSE:

Comments

In this message, "marked conversion string" indicates the string in the Input Method Editor (IME) that is marked for conversion. Text marked for conversion is indicated by a different selection color than that used for normal text selection in a standard text edit control. Available for bedits only.


HE_PUTCONVERTCHAR [New - Windows 95]
 HE_PUTCONVERTCHAR

[New - Windows 95]

Sends a character to the Input Method Editor (IME) and marks it for conversion. Submessage of WM_PENCTL. (Japanese version only.)

Parameters

wParam

HE_PUTCONVERTCHAR.

lParam

The low-order word contains the character code, which can be an SBCS or DBCS character.

Return Value

Returns TRUE if there are no errors; otherwise, returns FALSE.

Comments

Posting this message is exactly like posting a WM_CHAR message to a bedit or edit control with the exception that the posted character also acquires the attribute of being a character marked for conversion in the Input Method Editor. This sub-message is available for bedits only.


HE_SETBOXLAYOUT [New - Windows 95]
 HE_SETBOXLAYOUT

[New - Windows 95]

Sets the box layout for a control. Submessage of WM_PENCTL. Submessage of WM_PENCTL.

Parameters

wParam

HE_SETBOXLAYOUT.

lParam

Address of the BOXLAYOUT structure to be set.

Return Value

Returns TRUE if successful; otherwise, returns FALSE.

Comments

This submessage is for bedit controls only.

See Also

WM_PENCTL


HE_SETCONVERTRANGE [New - Windows 95]
 HE_SETCONVERTRANGE

[New - Windows 95]

Sets the range of the marked conversion string. Submessage of WM_PENCTL. (Japanese version only.)

Parameters

wParam

HE_SETIMEDEFAULT.

lParam

The low-order word contains the starting character position (not byte position) of the marked conversion string. The high-order word contains the ending character position plus 1.

Return Value

Returns TRUE if there are no errors; otherwise, returns FALSE.

Comments

Available for bedits only. If the starting character position is 0 and the ending char-acter position is −1, all the text in the control becomes the marked conversion string. If the starting character is −1, the marked conversion string area is removed. When characters are marked for conversion, the Input Method Editor is said to be in preconversion mode.

Returns FALSE if in conversion mode. If there is a selection, the selection will be cleared. The caret will be moved to the end of the marked conversion string.


HE_SETINFLATE [New - Windows 95]
 HE_SETINFLATE

[New - Windows 95]

Sets the inflation rectangle for a control. Submessage of WM_PENCTL.

Parameters

wParam

HE_SETINFLATE.

lParam

Address of a RECTOFS structure specifying the inflation margins for the writing window.

Return Value

Returns TRUE if successful, or FALSE if an invalid window rectangle is specified.

Comments

This is a submessage of the WM_PENCTL message.

For a description of how to increase or decrease the writing area of a control, see "HE_SETINFLATE Submessage" in Chapter 3, "The Writing Process."

See Also

HE_GETINFLATE, RECTOFS, WM_PENCTL


HE_SETINKMODE [New - Windows 95]
 HE_SETINKMODE

[New - Windows 95]

Starts ink data collection in a control. Submessage of WM_PENCTL.

Parameters

wParam

HE_SETINKMODE.

lParam

The low-order word is the initial HPENDATA object or NULL. If the initial HPENDATA is supplied, it must be relative to the top-left corner of the client rectangle of the control.

Return Value

Returns TRUE if successful; otherwise, returns FALSE.

Comments

This is a submessage of the WM_PENCTL message.

See Also

WM_PENCTL


HE_SETUNDERLINE [New - Windows 95]
 HE_SETUNDERLINE

[New - Windows 95]

Sets or cancels underline mode in an hedit control. Submessage of WM_PENCTL.

Parameters

wParam

HE_SETUNDERLINE.

lParam

The low-order word is TRUE to set underline mode and FALSE to cancel it.

Return Value

Returns the current underline mode.

Comments

This submessage is for single-line hedit controls only.

See Also

WM_PENCTL


HE_SHOWALTLIST [New - Windows 95]
 HE_SHOWALTLIST

[New - Windows 95]

Displays the alternate list menu for the current cell in a bedit control, assuming that alternate lists are enabled. Submessage of WM_PENCTL.

Parameters

wParam

HE_SHOWALTLIST.

lParam

If the low-order word is HEAL_DEFAULT, the alternate list menu is displayed.

Return Value

If more than one character is selected, the alternate list of the first character in the selection is displayed. If nothing is selected, the alternate list for the character to the right of the caret is displayed and the return value is TRUE.

Comments

This submessage is for bedit controls only. If more than one box is selected, the HE_SHOWALTLIST message will drop a word alternate list menu; otherwise, it will drop a character alternate list menu.

See Also

HE_ENABLEALTLIST, HE_HIDEALTLIST, WM_PENCTL


HE_STOPINKMODE [New - Windows 95]
 HE_STOPINKMODE

[New - Windows 95]

Stops ink collection in a control. Submessage of WM_PENCTL.

Parameters

wParam

HE_STOPINKMODE.

lParam

If the low-order word is HEP_RECOG, the control performs recognition and displays text. If the low-order word is HEP_NORECOG (0), the control removes the ink without performing recognition. If the low-order word is HEP_WAITFORTAP, the control performs recognition when the next tap in the writing area occurs.

Return Value

Returns TRUE if successful; otherwise, returns FALSE.

Comments

This is a submessage of the WM_PENCTL message.

See Also

WM_PENCTL


HN_BEGINDIALOG [New - Windows 95]
 HN_BEGINDIALOG

[New - Windows 95]

Sent by a bedit or hedit control to its parent window just before the control puts up any kind of dialog, including the lens, edit text, or garbage-detection dialogs.

The control's parent window receives this notification message through a WM_COMMAND message.

Parameters

wParam

Specifies the identifier of the hedit or bedit control.

lParam

Specifies the handle of the hedit or bedit control in the low-order word and the HN_BEGINDIALOG notification message in the high-order word.

Return Value

If the parent window returns TRUE to this notification message, the bedit or hedit control refrains from opening the dialog; otherwise, the dialog is opened. Note that the application can disable the hedit or bedit control's ability to open a dialog by specificying CIH_NOEDITTEXT in the WM_CTLINIT message.


HN_ENDDIALOG [New - Windows 95]
 HN_ENDDIALOG

[New - Windows 95]

Sent by a bedit or hedit control to its parent window of the dialog when a dialog opened by the control is destroyed.

The control's parent window receives this notification message through a WM_COMMAND message.

Parameters

wParam

Specifies the identifier of the hedit or bedit control.

lParam

Specifies the handle of the hedit or bedit control in the low-order word and the HN_ENDDIALOG notification message in the high-order word.

Return Value

The return value is ignored.


HN_ENDKKCONVERT [New - Windows 95]
 HN_ENDKKCONVERT

[New - Windows 95]

Sent after a bedit control has completed the Kana-to-Kanji conversion. Submessage of WM_PENCTL. (Japanese version only.)

The control's parent window receives this notification message through a WM_COMMAND message.

Parameters

wParam

Specifies the identifier of the hedit or bedit control.

lParam

Specifies the handle of the hedit or bedit control in the low-order word and the HN_ENDKKCONVERT notification message in the high-order word.

Return Value

The return value is ignored.


HN_ENDREC [New - Windows 95]
 HN_ENDREC

[New - Windows 95]

Sent after an hedit or bedit control has acted upon the results of recognition from a recognition session.

The control's parent window receives this notification message through a WM_COMMAND message.

Parameters

wParam

Specifies the identifier of the hedit or bedit control.

lParam

Specifies the handle of the hedit or bedit control in the low-order word and the HN_ENDREC notification message in the high-order word.

Return Value

The return value is ignored.


HN_RESULT [New - Windows 95]
 HN_RESULT

[New - Windows 95]

Sent when an hedit or bedit control receives results of inking or recognition from a recognition session, but before the control absorbs the results into its internal data structures.

The control's parent window receives this notification message through a WM_COMMAND message.

Parameters

wParam

Specifies the identifier of the hedit or bedit control.

lParam

Specifies the handle of the hedit or bedit control in the low-order word and the HN_RESULT notification message in the high-order word.

Return Value

The return value is ignored.

Comments

The application can get the results and optionally modify them using the WM_PENMISC message with the PMSC_GETSYMBOLCOUNT, PMSC_GETSYMBOLS, and the PMSC_SETSYMBOLS submessages.

See Also

WM_PENMISC


IE_CANUNDO [New - Windows 95]
 IE_CANUNDO

[New - Windows 95]

Retrieves an indication of whether the control can undo the last user operation.

Parameters

wParam

Not used; must be 0.

lParam

Not used; must be 0.

Return Value

Returns one of the following values:

Constant	Description
IER_YES	The control can undo the last operation.
IER_NO	The control cannot undo the last operation or the control has security protection disallowing an undo operation.
IER_PARAMERR	wParam or lParam is invalid.


IE_DOCOMMAND [New - Windows 95]
 IE_DOCOMMAND

[New - Windows 95]

Causes an ink edit control to execute a command.

Parameters

wParam

Contains one of the following command message codes:

Constant	Description
IEM_CLEAR	Clear (delete) the selection.
IEM_COPY	Copy selected strokes.
IEM_CUT	Cut selected strokes.
IEM_ERASE	Use eraser mode to erase.
IEM_LASSO	Use lasso mode to select strokes.
IEM_PASTE	Paste Clipboard contents to the iedit control.
IEM_PROPERTIES	Invoke the properties dialog box on the selected strokes.
IEM_RESIZE	Resize selected strokes.
IEM_SELECTALL	Select all the strokes in the control.
IEM_UNDO	Undo the last action.
lParam

Not used; must be 0.

Return Value

Returns IER_OK if successful; otherwise, returns one of the following:

Constant	Description
IER_PARAMERR	wParam or lParam is invalid.
IER_MEMERR	A memory error occurred.
IER_SECURITY	The control has security protection disallowing the operation.
Comments

An application can use this message to force the ink edit control to execute a valid command. For example, an application might have a toolbar button or menu item that can be used to trigger a copy command. The IE_DOCOMMAND message can be used in response to the user's pressing the button or selecting the menu item to have the iedit control copy the selected ink to the Clipboard.

The iedit control sends its parent an IN_COMMAND notification if the IEN_EDIT notify bit is set, to which the parent can respond in the usual ways. Sending a command that the iedit control cannot interpret (that is, a command code of IEM_USER or above) causes any specified notification but the iedit control takes no other action.

The IEN_EDIT bit is set by default. It should be cleared if the control's parent does not want to receive the IN_COMMAND notification message.

See Also

IE_GETCOMMAND


IE_EMPTYUNDOBUFFER [New - Windows 95]
 IE_EMPTYUNDOBUFFER

[New - Windows 95]

Empties the undo buffer.

Parameters

wParam

Not used; must be 0.

lParam

Not used; must be 0.

Return Value

Returns one of the following:

Constant	Description
IER_OK	Success.
IER_PARAMERR	wParam or lParam is invalid.
IER_SECURITY	The control has security protection disallowing the operation.
Comments

If there is nothing in the undo buffer, this message returns IER_OK but does nothing else. As long as the buffer remains empty after sending IE_EMPTYUNDOBUFFER, the messages IE_CANUNDO and WM_UNDO return FALSE.

See Also

IE_CANUNDO


IE_GETAPPDATA [New - Windows 95]
 IE_GETAPPDATA

[New - Windows 95]

Retrieves the application data saved in the ink edit control.

Parameters

wParam

Not used; must be 0.

lParam

Not used; must be 0.

Return Value

Returns the contents of the application data area if successful; otherwise, returns IER_PARAMERR to indicate that wParam or lParam is invalid.

Comments

An application can save any DWORD value with the ink edit control. The control does not use this data. The IE_SETAPPDATA and IE_GETAPPDATA messages provide the only means for an application to interact with the data.

See Also

IE_SETAPPDATA


IE_GETBKGND [New - Windows 95]
 IE_GETBKGND

[New - Windows 95]

Retrieves the current background painting options of an ink edit control.

Parameters

wParam

Not used; must be 0.

lParam

Address of a WORD variable that receives the current background options, as given in the following list:

Constant	Description
IEB_BIT_CENTER	Center supplied bitmap in control.
IEB_BIT_STRETCH	Stretch bitmap to fit control.
IEB_BIT_TILE	Tile supplied bitmap repeatedly in control.
IEB_BIT_UL	Align supplied bitmap to upper-left corner in the control. (UL stands for "upper left.")
IEB_BRUSH	Use application-supplied brush in lParam.
IEB_DEFAULT	Do default background (use COLOR_WINDOW).
IEB_OWNERDRAW	Parent will draw background.
Return Value

If successful, returns a handle to the background bitmap or a brush, or NULL, according to the option specified in lParam; otherwise, returns IER_PARAMERR to indicate that wParam or lParam is invalid.

Comments

The returned handle is owned by the iedit control; the application should not delete it. If the application needs to preserve this information, it should copy the handle.

See Also

IE_SETBKGND, IE_GETGRIDPEN, IE_SETGRIDPEN


IE_GETCOMMAND [New - Windows 95]
 IE_GETCOMMAND

[New - Windows 95]

Retrieves the menu item number of a selected command.

Parameters

wParam

Not used; must be 0.

lParam

Not used; must be 0.

Return Value

Returns the menu item number if successful; otherwise, returns one of the following:

Constant	Description
IER_PARAMERR	wParam or lParam is invalid.
IER_NOCOMMAND	Attempt to issue IE_GETCOMMAND when no command was selected.
Comments

The application sends the IE_GETCOMMAND message when it receives an IN_COMMAND notification to find out what menu item the user selected. This message can be sent only during processing of an IN_COMMAND notification. It returns the IER_NOCOMMAND error code if sent at any other time.

See Also

IE_DOCOMMAND


IE_GETCOUNT [New - Windows 95]
 IE_GETCOUNT

[New - Windows 95]

Retrieves the count of strokes in the control.

Parameters

wParam

Not used; must be 0.

lParam

Not used; must be 0.

Return Value

If successful, returns the total number of strokes in the control; otherwise, returns IER_PARAMERR to indicate that wParam or lParam is invalid.

See Also

IE_GETSELCOUNT


IE_GETDRAWOPTS [New - Windows 95]
 IE_GETDRAWOPTS

[New - Windows 95]

Retrieves the ink-drawing option.

Parameters

wParam

Not used; must be 0.

lParam

Not used; must be 0.

Return Value

Returns one of the following ink-drawing options:

Constant	Description
IEDO_FAST	Drawing is done as fast as possible. This is the default setting.
IEDO_NONE	No drawing is done (disabled drawing).
IEDO_SAVEUPSTROKES	Save pen-up strokes in the HPENDATA object.
Comments

IEDO_FAST and IEDO_NONE are mutually exclusive options.

See Also

IE_SETDRAWOPTS


IE_GETERASERTIP [New - Windows 95]
 IE_GETERASERTIP

[New - Windows 95]

Retrieves the eraser pen tip.

Parameters

wParam

Not used; must be 0.

lParam

Address of a PENTIP structure.

Return Value

Returns IER_OK if successful; otherwise, returns IER_PARAMERR to indicate that wParam or lParam is invalid.

Comments

The PENTIP structure is filled with the current pen tip used for erasing.

See Also

PENTIP, IE_SETERASERTIP


IE_GETFORMAT [New - Windows 95]
 IE_GETFORMAT

[New - Windows 95]

Retrieves the current format of a stroke or a set of strokes in an iedit control.

Parameters

wParam

Not used; must be 0.

lParam

Address of a STRKFMT structure.

Return Value

If successful, returns bit flags that indicate whether the strokes identified in the STRKFMT structure have different color or width, as described in the "Comments" section.

If an error occurs, returns one of the following values:

Constant	Description
IER_ERROR	Unknown error.
IER_PARAMERR	wParam or lParam is invalid. Also returned when there is an invalid stroke index and the IESF_STROKE option is specified in the iesf member of the STRKFMT structure.
IER_SECURITY	The control has security protection disallowing the operation.
IER_SELECTION	No valid selection when the IESF_SELECTION option is specified in the iesf member of the STRKFMT structure.
Comments

If the value in the iesf member of the STRKFMT structure has the IESF_STROKE bit set, IE_GETFORMAT refers to the single stroke identified in the iStrk member. In this case:

•	The return value is 0.

•	The bwidth and rgb members in PENTIP specified in the STRKFMT structure contain the stroke's color and width.

If either the bit IESF_SELECTION or IESF_ALL is set in iesf, IE_GETFORMAT retrieves format information for multiple strokes. In this case, the return value con-tains the IESF_TIPCOLOR or IESF_TIPWIDTH bit flags that indicate whether the multiple strokes share the same ink color and width.

For example, if the multiple requested strokes all have the same width, then

•	The IESF_TIPWIDTH bit of the return value is 0 to indicate the strokes all have the same width.

•	The bwidth member in PENTIP specified in the STRKFMT structure contains the common width.

If the strokes do not all have the same color, IE_GETFORMAT returns the following information:

•	The IESF_TIPCOLOR bit is set in the return value to indicate the strokes do not share a common color.

•	The rgb member in PENTIP specified in the STRKFMT structure contains the color of the last stroke in the group.

The caller must initialize the cbSize member of the STRKFMT structure to sizeof( STRKFMT ) before sending IE_GETFORMAT.

The supplied STRKFMT structure specifies the stroke or strokes for which the attributes are desired. The structure is filled according to the request and the actual stroke attributes.

See Also

IE_SETFORMAT, PENTIP, STRKFMT


IE_GETGESTURE [New - Windows 95]
 IE_GETGESTURE

[New - Windows 95]

Retrieves the specifics of a gesture.

Parameters

wParam

Not used; must be 0.

lParam

Not used; must be 0.

Return Value

Returns an HRCRESULT of the gesture if successful; otherwise, returns one of the following:

Constant	Description
IER_PARAMERR	wParam or lParam is invalid.
IER_NOGESTURE	Indicates an attempt to issue IE_GETGESTURE when no gesture was performed.
Comments

An application sends IE_GETGESTURE when it receives an IN_GESTURE notifi-cation, to retrieve the specifics of the user's gesture. This message can be sent only during processing of an IN_GESTURE notification. It returns the error code IER_NOGESTURE if it is set at any other time.

If successful, the application receives an HRCRESULT, which can then be used to get information about the gesture specifics. This handle is still owned by the iedit control, however, and the application must neither delete the handle nor modify the data to which it refers.


IE_GETGRIDORIGIN [New - Windows 95]
 IE_GETGRIDORIGIN

[New - Windows 95]

Retrieves the current origin of the rule or grid-line settings for the control.

Parameters

wParam

Not used; must be 0.

lParam

Not used; must be 0.

Return Value

Returns the x-coordinate of the origin in the low-order word and the y-coordinate of the origin in the high-order word, if successful; otherwise, returns IER_PARAMERR to indicate that wParam or lParam is invalid.

See Also

IE_GETBKGND, IE_GETGRIDORIGIN, IE_GETGRIDSIZE, IE_SETBKGND, IE_SETGRIDORIGIN, IE_SETGRIDPEN, IE_SETGRIDSIZE


IE_GETGRIDPEN [New - Windows 95]
 IE_GETGRIDPEN

[New - Windows 95]

Retrieves the current GDI pen used to draw the rules or grid lines for the control.

Parameters

wParam

Not used; must be 0.

lParam

Not used; must be 0.

Return Value

If successful, returns a handle to a GDI pen that is being used to draw the grid lines. This handle can be NULL; otherwise, returns IER_PARAMERR to indicate that wParam or lParam is invalid.

Comments

The handle of the GDI pen returned remains the property of the iedit control. The application must not delete this handle.

See Also

IE_GETBKGND, IE_GETGRIDORIGIN, IE_GETGRIDSIZE, IE_SETBKGND, IE_SETGRIDORIGIN, IE_SETGRIDPEN, IE_SETGRIDSIZE


IE_GETGRIDSIZE [New - Windows 95]
 IE_GETGRIDSIZE

[New - Windows 95]

Retrieves the current horizontal and vertical spacing of the rule or grid-line settings for the control.

Parameters

wParam

Not used; must be 0.

lParam

Not used; must be 0.

Return Value

If successful, the low-order word has the horizontal spacing and the high-order word has the vertical spacing; otherwise, returns IER_PARAMERR to indicate that wParam or lParam is invalid.

See Also

IE_GETBKGND, IE_GETGRIDORIGIN, IE_GETGRIDPEN, IE_SETBKGND, IE_SETGRIDORIGIN, IE_SETGRIDPEN, IE_SETGRIDSIZE


IE_GETINK [New - Windows 95]
 IE_GETINK

[New - Windows 95]

Retrieves the contents of an ink edit control.

Parameters

wParam

IEGI_ALL to get the entire ink, or IEGI_SELECTION to get only the selected ink.

lParam

Not used; must be 0.

Return Value

Returns the handle to the HPENDATA structure if successful; otherwise, returns one of the following:

Constant	Description
IER_PARAMERR	wParam or lParam is invalid.
IER_MEMERR	A memory error occurred.
IER_SECURITY	The control has security protection disallowing the operation.
IER_SELECTION	Nothing is selected in the control; operation assumes a selection.
Comments

The returned HPENDATA structure becomes the property of the application, which must eventually destroy it. This handle is a copy of the handle used internally by the control. An application cannot change the control by modifying the pen data referred to by this handle, although the modified handle can subsequently be used in an IE_SETINK call, which modifies the control's contents.

See Also

IE_SETINK


IE_GETINKINPUT [New - Windows 95]
 IE_GETINKINPUT

[New - Windows 95]

Retrieves the current ink input options for the control.

Parameters

wParam

Not used; must be 0.

lParam

Not used; must be 0.

Return Value

Returns the current ink input bits if successful; otherwise, returns IER_PARAMERR to indicate that wParam or lParam is invalid.

Comments

The ink input bits are as follows:

Constant	Description
IEI_MOVE	Move all ink inside the control.
IEI_RESIZE	Resize all ink to fit inside the control.
IEI_CROP	Crop all ink that falls outside the control.
IEI_DISCARD	Discard all ink if any falls outside the control.
See Also

IE_SETINKINPUT


IE_GETINKRECT [New - Windows 95]
 IE_GETINKRECT

[New - Windows 95]

Retrieves the bounding rectangle of the ink.

Parameters

wParam

Not used; must be 0.

lParam

Address of a RECT structure.

Return Value

Returns IER_OK if successful; otherwise, returns IER_PARAMERR to indicate that wParam or lParam is invalid.

Comments

The RECT structure is filled with the bounding rectangle of the current ink in the control. The rectangle is in the same coordinates as the scaling mode the HPENDATA object is in.


IE_GETMENU [New - Windows 95]
 IE_GETMENU

[New - Windows 95]

Retrieves a handle to an ink edit control's pop-up menu.

Parameters

wParam

Not used; must be 0.

lParam

Not used; must be 0.

Return Value

Returns the handle to the menu if successful; otherwise, returns IER_PARAMERR to indicate that wParam or lParam is invalid.

Comments

The iedit control continues to own the menu handle.

The application can perform standard menu operations upon the returned handle, including the addition, deletion, and modification of menu items. The application's changes are reflected the next time the pop-up menu is invoked.


IE_GETMODE [New - Windows 95]
 IE_GETMODE

[New - Windows 95]

Retrieves the current mode the control is in.

Parameters

wParam

Not used; must be 0.

lParam

Not used; must be 0.

Return Value

If successful, returns one of the following values indicating the current control mode:

Constant	Description
IEMODE_READY	The control is ready for inking, moving strokes, tapping, resizing, and so on.
IEMODE_ERASE	The control is set to erasing mode.
IEMODE_LASSO	The control is set to lasso selection mode.
Otherwise, returns IER_PARAMERR to indicate that wParam or lParam is invalid.

See Also

IE_SETMODE


IE_GETMODIFY [New - Windows 95]
 IE_GETMODIFY

[New - Windows 95]

Queries whether the contents of the control have been modified since the control was created.

Parameters

wParam

Not used; must be 0.

lParam

Not used; must be 0.

Return Value

Returns one of the following values:

Constant	Description
IER_YES	The control's contents have been modified.
IER_NO	The control's contents have not been modified.
IER_PARAMERR	wParam or lParam is invalid.
Comments

This command succeeds regardless of the security setting.

See Also

IE_SETMODIFY


IE_GETNOTIFY [New - Windows 95]
 IE_GETNOTIFY

[New - Windows 95]

Retrieves the current notification options for the control.

Parameters

wParam

Not used; must be 0.

lParam

Not used; must be 0.

Return Value

If successful, returns the current notification bits, as listed here:

Constant	Description
IEN_EDIT	Require notifications of editing or command events.
IEN_FOCUS	Require notifications of focus events.
IEN_PAINT	Require notifications of painting events.
IEN_PDEVENT	Require notifications of pointing-device events (clicks and taps).
IEN_PROPERTIES	Require notifications before bringing up the properties dialog box.
IEN_SCROLL	Require notifications of scrolling events.
Otherwise, returns IER_PARAMERR to indicate that wParam or lParam is invalid.

See Also

IE_SETNOTIFY


IE_GETPAINTDC [New - Windows 95]
 IE_GETPAINTDC

[New - Windows 95]

Retrieves the handle to the device context (HDC), which is used to paint an ink edit control. This HDC was supplied to the iedit control by BeginPaint; therefore, its clipping region is set according to those portions of the iedit control that have been invalidated.

Parameters

wParam

Not used; must be 0.

lParam

Not used; must be 0.

Return Value

Returns the HDC if successful; otherwise, returns one of the following:

Constant	Description
IER_PARAMERR	wParam or lParam is invalid.
IER_NOTINPAINT	Attempted IE_GETPAINTDC outside of paint notification.
Comments

The application can send this message only when the parent window is processing one of the painting notifications: IN_PREPAINT, IN_PAINT, IN_POSTPAINT, or IN_ERASEBKGND. An attempt to send it at any other time will fail, returning IER_NOTINPAINT.

The clipping region is already appropriately set when sending IE_GETPAINTDC. The HDC is in the MM_TEXT mapping mode. The HDC must not be released; the iedit control does this after returning from the painting notification.


IE_GETPDEVENT [New - Windows 95]
 IE_GETPDEVENT

[New - Windows 95]

Retrieves the pointing-device event that triggered the IN_PDEVENT notification. This can be from a mouse, pen, or other device.

Parameters

wParam

Not used; must be 0.

lParam

Address of a PDEVENT structure that is filled by the control when it receives this message.

Return Value

Returns one of the following:

Constant	Description
IER_OK	Success.
IER_PARAMERR	wParam or lParam is invalid.
IER_NOPDEVENT	No event occurred.
Comments

This message can succeed only during the processing of an IN_PDEVENT notification. At all other times its use is invalid. The caller must initialize the cbSize member of the PDEVENT structure to sizeof( PDEVENT ) before sending this message.

The application can cause the event to be discarded by returning TRUE to the IN_PDEVENT notification.

See Also

IN_PDEVENT, PDEVENT


IE_GETPENTIP [New - Windows 95]
 IE_GETPENTIP

[New - Windows 95]

Retrieves the default ink pen tip.

Parameters

wParam

Not used; must be 0.

lParam

Address of a PENTIP structure.

Return Value

Returns IER_OK if successful; otherwise, returns IER_PARAMERR to indicate that wParam or lParam is invalid.

Comments

The PENTIP structure is filled with the current pen tip used for default inking.

See Also

PENTIP, IE_SETPENTIP


IE_GETRECOG [New - Windows 95]
 IE_GETRECOG

[New - Windows 95]

Retrieves the current recognition setting of the control.

Parameters

wParam

Not used; must be 0.

lParam

Not used; must be 0.

Return Value

If successful, returns the following recognition flags, which can be combined using the bitwise-OR operator:

Constant	Description
IEREC_ALL	All recognition enabled.
IEREC_GESTURE	Gesture recognition enabled.
IEREC_NONE	Recognition disabled.
Otherwise, returns IER_PARAMERR to indicate that wParam or lParam is invalid.

Comments

Currently, IEREC_GESTURE and IEREC_ALL are equivalent.

See Also

IE_SETRECOG


IE_GETSECURITY [New - Windows 95]
 IE_GETSECURITY

[New - Windows 95]

Retrieves the current security setting of the control.

Parameters

wParam

Not used; must be 0.

lParam

Not used; must be 0.

Return Value

If successful, returns the following security flags, which can be combined using the bitwise-OR operator:

Constant	Description
IESEC_NOCOPY	Copying not allowed.
IESEC_NOCUT	Cutting, deleting, and clearing not allowed.
IESEC_NOPASTE	Pasting disabled.
IESEC_NOUNDO	Undo not permitted.
IESEC_NOINK	Inking not allowed.
IESEC_NOERASE	Erasing not allowed.
IESEC_NOGET	The IE_GETINK message is disabled.
IESEC_NOSET	The IE_SETINK message is disabled.
Otherwise, returns IER_SECURITY to indicate that the control has security pro-tection disallowing the operation.

See Also

IE_SETSECURITY


IE_GETSEL [New - Windows 95]
 IE_GETSEL

[New - Windows 95]

Retrieves the selection status of a particular stroke.

Parameters

wParam

Contains the zero-based index of the stroke whose selection status is queried.

lParam

Not used; must be 0.

Return Value

Returns one of the following values:

Constant	Description
IER_YES	The stroke is selected.
IER_NO	The stroke is not selected.
IER_PARAMERR	wParam or lParam is invalid.
See Also

IE_SETSEL


IE_GETSELCOUNT [New - Windows 95]
 IE_GETSELCOUNT

[New - Windows 95]

Retrieves the number of selected strokes.

Parameters

wParam

Not used; must be 0.

lParam

Not used; must be 0.

Return Value

If successful, returns the number of selected strokes; otherwise, returns IER_PARAMERR to indicate that wParam or lParam is invalid.

See Also

IE_GETSEL, IE_GETCOUNT


IE_GETSELITEMS [New - Windows 95]
 IE_GETSELITEMS

[New - Windows 95]

Retrieves a list of all selected strokes in the control.

Parameters

wParam

Size of the buffer passed in.

lParam

Address of a buffer of UINT variables that will be filled with the indices of the selected strokes in the control. This buffer must be large enough to hold all requested indices. The application can ensure this by first getting the number of selected strokes with the IE_GETSELCOUNT message and then calculating the required size of the buffer.

Return Value

Returns IER_OK if successful; otherwise, returns IER_PARAMERR to indicate that wParam or lParam is invalid.

See Also

IE_GETSELCOUNT


IE_GETSTYLE [New - Windows 95]
 IE_GETSTYLE

[New - Windows 95]

Retrieves the current style attributes of an ink edit control.

Parameters

wParam

Not used; must be 0.

lParam

Not used; must be 0.

Return Value

If successful, returns the following current style bits:

Constant	Description
IES_BORDER	Border drawn around control.
IES_HSCROLL	Horizontally scrollable control.
IES_VSCROLL	Vertically scrollable control.
IES_OWNERDRAW	Application will do all ink drawing.
Otherwise, returns IER_PARAMERR to indicate that wParam or lParam is invalid.


IE_SETAPPDATA [New - Windows 95]
 IE_SETAPPDATA

[New - Windows 95]

Sets the application data saved in the ink edit control.

Parameters

wParam

Not used; must be 0.

lParam

Data to be saved.

Return Value

Returns the previous contents of the application data area, if successful; otherwise, returns IER_PARAMERR to indicate that wParam or lParam is invalid.

Comments

An application can save any DWORD value with the ink edit control. The control does not use this data. The IE_SETAPPDATA and IE_GETAPPDATA messages provide the only means for an application to interact with the data.

See Also

IE_GETAPPDATA


IE_SETBKGND [New - Windows 95]
 IE_SETBKGND

[New - Windows 95]

Sets the background painting options for the control.

Parameters

wParam

Specifies the background options, as given in the following list:

Constant	Description
IEB_BIT_CENTER	Center bitmap in control. The lParam parameter contains bitmap.
IEB_BIT_STRETCH	Stretch bitmap to fit control. The lParam parameter contains bitmap.
IEB_BIT_TILE	Tile supplied bitmap repeatedly in control. The lParam parameter contains bitmap.
IEB_BIT_UL	Align supplied bitmap to upper-left corner in the control. (UL stands for "upper left.") The lParam parameter contains bitmap.
IEB_BRUSH	Use brush supplied in lParam.
IEB_DEFAULT	Do default background (use COLOR_WINDOW).
IEB_OWNERDRAW	Parent will draw background.
lParam

Contains a handle to the background bitmap or a brush, or is NULL, according to the specified option in wParam.

Return Value

Returns IER_OK if successful; otherwise, returns IER_PARAMERR to indicate that wParam or lParam is invalid.

Comments

The application can change the background at any time. The control is synchro-nously repainted upon any change.

The HBITMAP or HBRUSH handle, if there is one, becomes the property of the iedit control. The application must make no further use of the handle if the message returns IER_OK. If the IEB_OWNERDRAW option is selected, the parent window must process the IN_ERASEBKGND notification. If an application must place such objects as icons or metafiles in the background, it must do so either in an owner-draw capacity or during the IN_PREPAINT notification.

See Also

IE_GETBKGND, IE_GETGRIDPEN, IE_SETGRIDPEN


IE_SETDRAWOPTS [New - Windows 95]
 IE_SETDRAWOPTS

[New - Windows 95]

Sets the ink drawing option.

Parameters

wParam

Contains the drawing option.

Constant	Description
IEDO_FAST	Drawing is done as fast as possible. This is the default setting.
IEDO_NONE	No drawing is done (disabled drawing).
IEDO_SAVEUPSTROKES	Save pen-up strokes in the HPENDATA object.
lParam

Not used; must be 0.

Return Value

Returns IER_OK if successful; the previous draw option is returned in the high-order word; otherwise, returns one of the following:

Constant	Description
IER_PARAMERR	wParam or lParam is invalid.
IER_OWNERDRAW	The control is an owner-draw control; setting draw options is invalid.
IER_SECURITY	The control has security protection disallowing the operation.
Comments

Unlike using the WM_SETREDRAW message, IEDO_NONE controls only the drawing of the ink. The control's background, grid lines, and so forth are redrawn as usual. By default, pen-up strokes are not saved in the HPENDATA object.


IE_SETERASERTIP [New - Windows 95]
 IE_SETERASERTIP

[New - Windows 95]

Sets the eraser pen tip.

Parameters

wParam

Not used; must be 0.

lParam

Address of a PENTIP structure.

Return Value

Returns IER_OK if successful; otherwise, returns IER_PARAMERR to indicate that wParam or lParam is invalid.

Comments

The pen tip specified by PENTIP is used for erasing in the control.

See Also

PENTIP, IE_GETERASERTIP


IE_SETFORMAT [New - Windows 95]
 IE_SETFORMAT

[New - Windows 95]

Sets the format of a stroke or a set of strokes in an ink edit control.

Parameters

wParam

Not used; must be 0.

lParam

Address of a STRKFMT structure.

Return Value

Returns IER_OK if successful; otherwise, returns one of the following:

Constant	Description
IER_ERROR	Unknown error.
IER_PARAMERR	wParam or lParam is invalid. Also returned when there is an invalid stroke index and the IESF_STROKE option is specified in the iesf member of the STRKFMT structure.
IER_MEMERR	A memory error occurred.
IER_SECURITY	The control has security protection disallowing the operation.
IER_SELECTION	No valid selection with the IESF_SELECTION option in the iesf member of the STRKFMT structure.
Comments

The stroke or strokes indicated by the STRKFMT structure are modified as indicated and repainted (unless drawing has been turned off using the IEDO_NONE bit in IE_SETDRAWOPTS).

The iesf member of the STRKFMT structure contains the IESF_TIPCOLOR or IESF_TIPWIDTH bit flags to selectively adjust the color or width attributes of the ink. This allows setting only the color, for example, while leaving the width unchanged. If the value in iesf has either IESF_TIPCOLOR or IESF_TIPWIDTH set, the ink in the control adopts the new color or width given in the rgb or bwidth members of the PENTIP structure identified in the tip member of STRKFMT.

The caller must initialize the cbSize member of the STRKFMT structure to sizeof( STRKFMT ) before sending this message.

See Also

IE_GETFORMAT, IE_SETDRAWOPTS, STRKFMT


IE_SETGRIDORIGIN [New - Windows 95]
 IE_SETGRIDORIGIN

[New - Windows 95]

Sets the origin of the rules or grid lines.

Parameters

wParam

Not used; must be 0.

lParam

The low-order word has the x-coordinate of the origin and the high-order word has the y-coordinate of the origin.

Return Value

Returns IER_OK if successful; otherwise, returns IER_PARAMERR to indicate that wParam or lParam is invalid.

Comments

Rules and grids are painted after the background and before the ink (and the IN_PREPAINT notification), and are treated separately from both.

The default setting is for no grid lines. The grid lines act purely as guides for the user; the ink does not interact with the grid in any way. The specification of the grid lines is in the MM_TEXT mapping mode (that is, display pixel).

See Also

IE_GETBKGND, IE_GETGRIDPEN, IE_GETGRIDSIZE, IE_SETGRIDORIGIN, IE_SETGRIDPEN, IE_SETGRIDSIZE, IE_SETBKGND


IE_SETGRIDPEN [New - Windows 95]
 IE_SETGRIDPEN

[New - Windows 95]

Sets the GDI pen for the background rules or grid lines.

Parameters

wParam

Not used; must be 0.

lParam

Contains a handle to a GDI pen used to draw the grid lines.

Return Value

Returns IER_OK if successful; otherwise, returns IER_PARAMERR to indicate that wParam or lParam is invalid.

Comments

Rules and grids are painted after the background and before the ink (and the IN_PREPAINT notification), and are treated separately from both. A GDI pen, if specified, becomes the property of the ink edit control and must not be deleted or otherwise used by the application. If the application needs to change the settings, it must create a new pen each time it sends the IE_SETGRIDPEN message.

The default setting is for no grid lines. The grid lines act purely as guides for the user; the ink does not interact with the grid in any way. The specification of the grid lines is in the MM_TEXT mapping mode (that is, display pixel). If the GDI pen handle is NULL, the ink edit control will use a default pen. (The default pen attributes are a solid line, a width of 1 pixel, and the window grayed text color.) The maximum grid spacing is 255 pixels.

See Also

IE_GETBKGND, IE_GETGRIDORIGIN, IE_GETGRIDPEN, IE_GETGRIDSIZE, IE_SETGRIDORIGIN, IE_SETGRIDSIZE, IE_SETBKGND


IE_SETGRIDSIZE [New - Windows 95]
 IE_SETGRIDSIZE

[New - Windows 95]

Sets the vertical and horizontal spacing of the rules or grid lines.

Parameters

wParam

Not used; must be 0.

lParam

The low-order word has the horizontal spacing and the high-order word has the vertical spacing.

Return Value

Returns IER_OK if successful; otherwise, returns IER_PARAMERR to indicate that wParam or lParam is invalid.

Comments

Rules and grids are painted after the background and before the ink (and the IN_PREPAINT notification), and are treated separately from both.

The default setting is for no grid lines. The grid lines act purely as guides for the user; the ink does not interact with the grid in any way. The specification of the grid lines is in the MM_TEXT mapping mode (that is, display pixel).

See Also

IE_GETBKGND, IE_GETGRIDORIGIN, IE_GETGRIDPEN, IE_GETGRIDSIZE, IE_SETGRIDORIGIN, IE_SETGRIDPEN, IE_SETBKGND


IE_SETINK [New - Windows 95]
 IE_SETINK

[New - Windows 95]

Sets the contents of an ink edit control.

Parameters

wParam

Contains IESI_REPLACE to replace any existing control contents with the supplied ink, or IESI_APPEND to append the supplied ink to the existing contents of the ink edit control.

lParam

Contains a handle to pen data with which to initialize or reinitialize the contents of the control. If NULL, the contents of the control are cleared; any pen data in the control is discarded.

Return Value

Returns IER_OK if successful; otherwise, returns one of the following:

Constant	Description
IER_PARAMERR	wParam or lParam is invalid.
IER_MEMERR	A memory error occurred.
IER_SECURITY	The control has security protection disallowing the operation.
IER_SCALE	Attempted to merge ink of incompatible scale factors.
Comments

The application can clear or change the contents of the control at any time with this function. During the creation of controls with existing contents, this message might be sent in response to the WM_CTLINIT message.

The HPENDATA handle becomes the property of the control; the application must make no further use of the handle if the message returns success. On a merge operation, the original HPENDATA is destroyed following a successful merge. If the result of IE_SETINK indicates there is no ink left in the control, the mode is reset to IEMODE_READY if the previous mode was either IEMODE_ERASE or IEMODE_LASSO. The corresponding IN_MODECHANGED notification is also sent at this time.

See Also

IE_GETINK


IE_SETINKINPUT [New - Windows 95]
 IE_SETINKINPUT

[New - Windows 95]

Sets the ink input options for an ink edit control.

Parameters

wParam

Consists of one or two flags specifying the new ink input option. Any one of the following flags can be used as the wParam value. If IEI_MOVE is specified, one (and only one) additional value can combined to indicate a secondary option if all ink will not fit inside the control when moved. For example, the combi-nation IEI_MOVE|IEI_RESIZE specifies to move ink into the control and resize the control to fit if necessary. Bitwise-OR combinations of constants not including IEI_MOVE are not valid.

Constant	Description
IEI_MOVE	Move all ink inside the control.
IEI_RESIZE	Resize all ink to fit inside the control.
IEI_CROP	Crop all ink that falls outside the control.
IEI_DISCARD	Discard all ink if any falls outside the control.
lParam

Not used; must be 0.

Return Value

Returns the previous ink input bits if successful; otherwise, returns IER_PARAMERR to indicate that wParam or lParam is invalid.

Comments

An application can dynamically modify the ink input options. If more than 1 bit is set, the order of priority is as listed in the previous table.

See Also

IE_GETINKINPUT


IE_SETMODE [New - Windows 95]
 IE_SETMODE

[New - Windows 95]

Sets the control to a particular mode.

Parameters

wParam

Specifies the mode to set the control to, as follows:

Constant	Description
IEMODE_READY	The control is ready for inking, moving strokes, tapping, and so forth.
IEMODE_ERASE	The control is set to erasing mode.
IEMODE_LASSO	The control is set to lasso selection mode.
lParam

Not used; must be 0.

Return Value

Returns one of the following values:

Constant	Description
IER_OK	Success.
IER_PARAMERR	wParam or lParam is invalid.
IER_PENDATA	Attempted to set erase or lasso mode with a null HPENDATA handle in the control.
See Also

IE_GETMODE


IE_SETMODIFY [New - Windows 95]
 IE_SETMODIFY

[New - Windows 95]

Sets the modify bit in the control, indicating whether the contents of the control have been modified.

Parameters

wParam

The new value of the modify bit. Must be either TRUE or FALSE.

lParam

Not used; must be 0.

Return Value

Returns IER_OK if successful; otherwise, returns IER_PARAMERR to indicate that wParam or lParam is invalid.

Comments

The modify bit is set in the control whenever the user takes some action that changes the ink in the control. Such actions include drawing new ink, erasing, pasting, changing attributes, and moving ink. Note that calling a function to change the contents of the control also sets the modify bit.

To preserve the value of the modify bit during some modifying action, the appli-cation must first retrieve the bit's value with IE_GETMODIFY, then restore the value after completing the action.

This command succeeds regardless of the security setting.

See Also

IE_GETMODIFY


IE_SETNOTIFY [New - Windows 95]
 IE_SETNOTIFY

[New - Windows 95]

Sets the notification options for an ink edit control.

Parameters

wParam

Consists of flags specifying the kinds of notifications required:

Constant	Description
IEN_EDIT	Require notifications of editing or command events. Notifications sent: IN_CHANGE, IN_UPDATE, IN_GESTURE, IN_COMMAND.
IEN_FOCUS	Require notifications of focus events. Notifications sent: IN_SETFOCUS, IN_KILLFOCUS.
IEN_PAINT	Require notifications of painting events. Notifications sent: IN_PREPAINT, IN_POSTPAINT.
IEN_PDEVENT	Require notifications of pointing-device events (clicks and taps). Notification sent: IN_PDEVENT.
IEN_PROPERTIES	Require notifications before bringing up the properties dialog box. Notification sent: IN_PROPERTIES.
IEN_SCROLL	Require notifications of scrolling events. Notifications sent: IN_HSCROLL, IN_VSCROLL.
lParam

Not used; must be 0.

Return Value

Returns the previous notification bits if successful; otherwise, returns IER_PARAMERR to indicate that wParam or lParam is invalid.

Comments

An application can dynamically modify the kinds of notifications and the frequency with which they are generated.

Unless otherwise specified, the parent window receives no notifications beyond the default messages sent by Windows to the parent of a child window.

See Also

IE_GETNOTIFY


IE_SETPENTIP [New - Windows 95]
 IE_SETPENTIP

[New - Windows 95]

Sets the default ink pen tip.

Parameters

wParam

Not used; must be 0.

lParam

Address of a PENTIP structure.

Return Value

Returns IER_OK if successful; otherwise, returns IER_PARAMERR to indicate that wParam or lParam is invalid.

Comments

The pen tip specified by PENTIP is used for all default inking in the control. Note that the new pen tip applies only to new ink entered into the control. It does not change the attributes of existing ink in the control.

See Also

PENTIP, IE_GETPENTIP


IE_SETRECOG [New - Windows 95]
 IE_SETRECOG

[New - Windows 95]

Sets the recognition options of the control.

Parameters

wParam

Contains bits designating the new recognition options, as listed here:

Constant	Description
IEREC_ALL	All recognition enabled.
IEREC_GESTURE	Gesture recognition enabled.
IEREC_NONE	Recognition disabled.
lParam

Not used; must be 0.

Return Value

Returns the previous recognition bits if successful; otherwise, returns IER_PARAMERR to indicate that wParam or lParam is invalid.

Comments

By default, all recognition is enabled. Currently, IEREC_GESTURE and IEREC_ALL are equivalent.

See Also

IE_GETRECOG


IE_SETSECURITY [New - Windows 95]
 IE_SETSECURITY

[New - Windows 95]

Sets the security options of the control.

Parameters

wParam

Contains the new security bits. The high-order word is unused and must be 0. The security flags can be combined using the bitwise-OR operator.

Constant	Description
IESEC_NOCOPY	Copying not allowed.
IESEC_NOCUT	Cutting, deleting, and clearing not allowed.
IESEC_NOPASTE	Pasting disabled.
IESEC_NOUNDO	Undo not permitted.
IESEC_NOINK	Inking not allowed.
IESEC_NOERASE	Erasing not allowed.
IESEC_NOGET	The IE_GETINK message is disabled.
IESEC_NOSET	The IE_SETINK message is disabled.
lParam

Not used; must be 0.

Return Value

Returns the previous security bits if successful; otherwise, returns one of the following:

Constant	Description
IER_PARAMERR	wParam or lParam is invalid.
IER_SECURITY	The control has security protection disallowing the operation.
See Also

IE_GETSECURITY


IE_SETSEL [New - Windows 95]
 IE_SETSEL

[New - Windows 95]

Sets the selection status of a particular stroke.

Parameters

wParam

Contains the zero-based index of the stroke whose selection status is to be set. A value of IX_END sets the selection status of all the strokes in the control.

lParam

lParam is TRUE to select the stroke or FALSE to remove the selection. Other values produce an IER_PARAMERR return value.

Return Value

Returns one of the following values:

Constant	Description
IER_YES	The stroke was previously selected.
IER_NO	The stroke was not previously selected.
IER_PARAMERR	wParam or lParam is invalid.
Comments

This message affects the selection status of only the specified stroke. The selection status of other strokes remains unchanged.

See Also

IE_GETSEL


IN_CHANGE [New - Windows 95]
 IN_CHANGE

[New - Windows 95]

Sent after the contents of the control have been modified and repainted.

The control's parent window receives this notification message through a WM_COMMAND message if the IEN_EDIT bit has been set using the IE_SETNOTIFY message.

Parameters

wParam

Specifies the identifier of the ink edit control.

lParam

Specifies the handle of the iedit control in the low-order word and the IN_CHANGE notification message in the high-order word.

See Also

IE_SETNOTIFY


IN_CLOSE [New - Windows 95]
 IN_CLOSE

[New - Windows 95]

Sent when the control is closing and about to be destroyed.

The control's parent window receives this notification message through a WM_COMMAND message.

Parameters

wParam

Specifies the identifier of the ink edit control.

lParam

Specifies the handle of the iedit control in the low-order word and the IN_CLOSE notification message in the high-order word.

Return Value

The application should return TRUE to prevent the control from being closed or FALSE for default handling.


IN_COMMAND [New - Windows 95]
 IN_COMMAND

[New - Windows 95]

Sent when the user has selected an item from the pop-up menu.

The control's parent window receives this notification message through a WM_COMMAND message if the IEN_EDIT bit has been set using the IE_SETNOTIFY message.

Parameters

wParam

Specifies the identifier of the ink edit control.

lParam

Specifies the handle of the iedit control in the low-order word and the IN_COMMAND notification message in the high-order word.

Return Value

The application should return TRUE to discard the command selection or FALSE for default processing.

Comments

The application can retrieve details about the selection by using the IE_GETCOMMAND message.

See Also

IE_GETCOMMAND, IE_SETNOTIFY


IN_ERASEBKGND [New - Windows 95]
 IN_ERASEBKGND

[New - Windows 95]

Sent to the parents of ink edit controls that have the IEB_OWNERDRAW option to request the painting of the control background.

The control's parent window receives this notification message through a WM_COMMAND message.

Parameters

wParam

Specifies the identifier of the ink edit control.

lParam

Specifies the handle of the ink edit control in the low-order word and the IN_ERASEBKGND notification message in the high-order word.

Comments

The application should use the IE_GETPAINTDC message to retrieve such information as the correct device context and clipping region.

See Also

IE_GETPAINTDC


IN_GESTURE [New - Windows 95]
 IN_GESTURE

[New - Windows 95]

Sent when the user has performed a gesture in the iedit control.

The control's parent window receives this notification message through a WM_COMMAND message if the IEN_EDIT bit has been set using the IE_SETNOTIFY message.

Parameters

wParam

Specifies the identifier of the ink edit control.

lParam

Specifies the handle of the ink edit control in the low-order word and the IN_GESTURE notification message in the high-order word.

Return Value

The application should return TRUE to discard the gesture or FALSE for default processing.

Comments

An application can retrieve details about the gesture by using the IE_GETGESTURE message.

See Also

IE_SETNOTIFY


IN_HSCROLL [New - Windows 95]
 IN_HSCROLL

[New - Windows 95]

The IN_HSCROLL notification message is sent when the user has clicked the ink edit control's horizontal scroll bar.

The control's parent window receives this notification message through a WM_COMMAND message if the IEN_SCROLL bit has been set using the IE_SETNOTIFY message. This bit is set by default and should be cleared if the control's parent does not require this notification message.

Parameters

wParam

Specifies the identifier of the ink edit control.

lParam

Specifies the handle of the ink edit control in the low-order word and the IN_HSCROLL notification message in the high-order word.

Return Value

The application should return TRUE to discard the scrolling request.

See Also

IE_SETNOTIFY


IN_KILLFOCUS [New - Windows 95]
 IN_KILLFOCUS

[New - Windows 95]

Sent to inform the parent window that the control is losing the focus.

The control's parent window receives this notification message through a WM_COMMAND message if the IEN_FOCUS bit has been set using the IE_SETNOTIFY message. This bit is set by default and should be cleared if the control's parent does not require this notification message.

Parameters

wParam

Specifies the identifier of the ink edit control.

lParam

Specifies the handle of the iedit control in the low-order word and the IN_KILLFOCUS notification message in the high-order word.

Return Value

The application should return TRUE to prevent the control from losing the focus.

See Also

IE_SETNOTIFY


IN_MEMERR [New - Windows 95]
 IN_MEMERR

[New - Windows 95]

Sent when the system is unable to satisfy a memory request made by the control.

The control's parent window receives this notification message through a WM_COMMAND message.

Parameters

wParam

Specifies the identifier of the ink edit control.

lParam

Specifies the handle of the ink edit control in the low-order word and the IN_MEMERR notification message in the high-order word.

Return Value

The application should return TRUE to retry the operation (generally after it frees memory). If it returns TRUE and the control still cannot perform the memory operation, another IN_MEMERR notification is generated.

Comments

The ink edit control does not display an error message of any kind. Any such error messages must be displayed by the application.


IN_MODECHANGED [New - Windows 95]
 IN_MODECHANGED

[New - Windows 95]

Sent after the control mode has changed.

The control's parent window receives this notification message through a WM_COMMAND message if the IEN_EDIT bit has been set using the IE_SETNOTIFY message.

Parameters

wParam

Specifies the identifier of the ink edit control.

lParam

Specifies the handle of the ink edit control in the low-order word and the IN_MODECHANGED notification message in the high-order word.

See Also

IE_SETNOTIFY, IE_GETMODE, IE_SETMODE


IN_PAINT [New - Windows 95]
 IN_PAINT

[New - Windows 95]

Sent to the parent window of an owner-draw ink edit control to indicate that the control should be painted.

The control's parent window receives this notification message through a WM_COMMAND message.

Parameters

wParam

Specifies the identifier of the ink edit control.

lParam

Specifies the handle of the ink edit control in the low-order word and the IN_PAINT notification message in the high-order word.

Comments

The application should use the IE_GETPAINTDC message to retrieve the details of the required painting.

See Also

IE_GETPAINTDC


IN_PDEVENT [New - Windows 95]
 IN_PDEVENT

[New - Windows 95]

Sent when a pointing-device transition event (such as a tap, up-click, or double-tap) occurs.

The control's parent window receives this notification message through a WM_COMMAND message if the IEN_PDEVENT bit has been set using the IE_SETNOTIFY message.

Parameters

wParam

Specifies the identifier of the ink edit control.

lParam

Specifies the handle of the ink edit control in the low-order word and the IN_PDEVENT notification message in the high-order word.

Return Value

The application should return TRUE to discard the event, or FALSE for normal processing.

Comments

The application can retrieve a PDEVENT structure describing the event by sending the IE_GETPDEVENT message.

See Also

IE_GETPDEVENT, IE_SETNOTIFY


IN_POSTPAINT [New - Windows 95]
 IN_POSTPAINT

[New - Windows 95]

Sent to inform the parent that painting is finished.

The control's parent window receives this notification message through a WM_COMMAND message if the IEN_PAINT bit has been set using the IE_SETNOTIFY message.

Parameters

wParam

Specifies the identifier of the ink edit control.

lParam

Specifies the handle of the ink edit control in the low-order word and the IN_POSTPAINT notification message in the high-order word.

Comments

The application can send the IE_GETPAINTDC message to retrieve a device con-text with the correct clipping region to perform any additional painting on top of the ink edit control.

See Also

IE_GETPAINTDC, IE_SETNOTIFY


IN_PREPAINT [New - Windows 95]
 IN_PREPAINT

[New - Windows 95]

Sent just before the control paints the ink.

The control's parent window receives this notification message through a WM_COMMAND message if the IEN_PAINT bit has been set using the IE_SETNOTIFY message.

Parameters

wParam

Specifies the identifier of the ink edit control.

lParam

Specifies the handle of the ink edit control in the low-order word and the IN_PREPAINT notification message in the high-order word.

Comments

The application can send the IE_GETPAINTDC message to retrieve a device context with the correct clipping region to perform any additional painting before the ink edit control paints.

See Also

IE_GETPAINTDC, IE_SETNOTIFY


IN_PROPERTIES [New - Windows 95]
 IN_PROPERTIES

[New - Windows 95]

Signals the iedit control's standard Properties dialog box is about to be displayed on the screen.

The control's parent window receives the IN_PROPERTIES notification message through a WM_COMMAND message if the IEN_PROPERTIES bit has been set using the IE_SETNOTIFY message. This bit is set by default and should be cleared if the control's parent does not require this notification message.

Parameters

wParam

Specifies the identifier of the ink edit control.

lParam

Specifies the handle of the ink edit control in the low-order word and the IN_PROPERTIES notification message in the high-order word.

Return Value

The application should return TRUE to avoid displaying the iedit control's standard Properties dialog box.

See Also

IE_SETNOTIFY


IN_SETFOCUS [New - Windows 95]
 IN_SETFOCUS

[New - Windows 95]

Sent to inform the parent window that the control is gaining the focus.

The control's parent window receives this notification message through a WM_COMMAND message if the IEN_FOCUS bit has been set using the IE_SETNOTIFY message. This bit is set by default and should be cleared if the control's parent does not require this notification message.

Parameters

wParam

Specifies the identifier of the ink edit control.

lParam

Specifies the handle of the ink edit control in the low-order word and the IN_SETFOCUS notification message in the high-order word.

Return Value

The application should return TRUE to prevent acquiring the focus.

See Also

IE_SETNOTIFY


IN_UPDATE [New - Windows 95]
 IN_UPDATE

[New - Windows 95]

Sent when the contents of the control have been modified but not yet repainted.

The control's parent window receives this notification message through a WM_COMMAND message if the IEN_EDIT bit has been set using the IE_SETNOTIFY message.

Parameters

wParam

Specifies the identifier of the ink edit control.

lParam

Specifies the handle of the ink edit control in the low-order word and the IN_UPDATE notification message in the high-order word.

See Also

IE_SETNOTIFY


IN_VSCROLL [New - Windows 95]
 IN_VSCROLL

[New - Windows 95]

Sent when the user has clicked the ink edit control's vertical scroll bar.

The control's parent window receives this notification message through a WM_COMMAND message if the IEN_SCROLL bit has been set using the IE_SETNOTIFY message. This bit is set by default and should be cleared if the control's parent does not require this notification message.

Parameters

wParam

Specifies the identifier of the ink edit control.

lParam

Specifies the handle of the ink edit control in the low-order word and the IN_VSCROLL notification message in the high-order word.

Return Value

The application should return TRUE to discard the scrolling request.

See Also

IE_SETNOTIFY


PE_BEGINDATA [New - Windows 95]
 PE_BEGINDATA

[New - Windows 95]

Sent to the window specified by the htrgTarget member of the TARGET structure the first time any pen data is directed toward that window. Submessage of WM_PENEVENT.

Parameters

wParam

PE_BEGINDATA

lParam

Address of a TARGET structure.

Comments

A target window can initialize the dwData member of the TARGET structure with a handle to pen data (HPENDATA), a handwriting recognition object (HRC), or some private data type. If dwData is an HPENDATA object, the HPENDATA object should be in standard scale with no OEM data. For example, the HPENDATA object can be created as follows:

CreatePenDataEx(NULL, PDTS_STANDARDSCALE, CPD_TIME, 0);

The target window informs Windows of the type of data in the dwData member of the TARGET structure by returning LRET_HPENDATA, LRET_HRC, or LRET_PRIVATE (or LRET_DONE). If the application lets the message fall down to the Windows DefWindowProc function, then the function creates a handwriting recognition object (HRC) for this target.

The window can ignore all input except gestures. In this case, it must create a handwriting recognition object and customize it to recognize only gestures.

For an example of how an application can handle PE_BEGINDATA, see the source code for PENAPP.C in Chapter 7, "A Sample Pen Application."

See Also

TARGET, WM_PENEVENT


PE_BEGININPUT [New - Windows 95]
 PE_BEGININPUT

[New - Windows 95]

Begins default input processing. Submessage of WM_PENEVENT.

Parameters

wParam

PE_BEGININPUT

lParam

The high-order word is the handle of the window in which the pen first touched down, and the low-order word is the event reference identifier returned from GetMessageExtraInfo.

Return Value

Returns PCMR_OK if successful; otherwise, it returns one of the following values:

Constant	Description
PCMR_ALREADYCOLLECTING	StartPenInput has already been called for this session.
PCMR_APPTERMINATED	The application terminated input.
PCMR_ERROR	Parameter or unspecified error.
PCMR_INVALID_PACKETID	A packet identifier is invalid.
PCMR_SELECT	Press-and-hold action was detected. Collection is not started.
PCMR_TAP	A tap was detected. Collection is not started.
Comments

A control can initiate default pen-input processing by sending this message to its parent. If the parent allows the message to be processed by passing it to DefWindowProc, default pen-input behavior begins. The DoDefaultPenInput function uses this technique.

For further information about default processing, refer to Chapter 2, "Starting Out with System Defaults."

See Also

DoDefaultPenInput, WM_PENEVENT


PE_BUFFERWARNING [New - Windows 95]
 PE_BUFFERWARNING

[New - Windows 95]

Generated by the pen driver component of the system when the input queue is approximately half full. When an application receives PE_BUFFERWARNING, it should immediately call GetPenInput to drain the input queue. Submessage of WM_PENEVENT.

Parameters

wParam

PE_BUFFERWARNING.

lParam

Extra information encapsulating a reference to the event and the HPCM that generated it. Applications can use the EventRefFromWpLp and HpcmFromWpLp macros to retrieve these values.

Comments

If an application receives this message, it has fallen behind in processing the input. The buffer is in danger of overflowing. The application should repeatedly call GetPenInput to gather the unprocessed pen input.

See Also

GetPenInput, WM_PENEVENT


PE_ENDDATA [New - Windows 95]
 PE_ENDDATA

[New - Windows 95]

Sent at the termination of pen input to all windows specified by the htrgTarget member of the TARGET structure that have received a PE_BEGINDATA message. Submessage of WM_PENEVENT.

Parameters

wParam

PE_ENDDATA.

lParam

Address of a TARGET structure.

Comments

A target can inform the recognizer that pen input has ended and process the HRC in response to this message. If this message is allowed to fall through to the DefWindowProc function, default result processing is done if the value in the dwData member of the TARGET structure is of type HRC. EndPenInput is called followed by a call to ProcessHRC. Then the PE_RESULT submessage is sent to the target to allow the target to get results and process them.

If the dwData member of the TARGET structure has the HPENDATA or HRC type, the object is destroyed by DefWindowProc on completion of results processing.

See Also

TARGET, WM_PENEVENT


PE_ENDINPUT [New - Windows 95]
 PE_ENDINPUT

[New - Windows 95]

Sent to indicate that the default collection has terminated. Submessage of WM_PENEVENT.

Parameters

wParam

PE_ENDINPUT.

lParam

Not used.

See Also

WM_PENEVENT


PE_GETINKINGINFO [New - Windows 95]
 PE_GETINKINGINFO

[New - Windows 95]

Fills an INKINGINFO structure. Submessage of WM_PENEVENT.

Parameters

wParam

PE_GETINKINGINFO.

lParam

Address of an INKINGINFO structure, which is initialized with default values.

Return Value

The targeted windows in the application should return 1 to customize inking information. A return value of 0 results in default inking behavior.

Comments

Before beginning default pen input, Windows sends PE_GETINKINGINFO to all the windows specified by the htrgTarget member of the TARGET structure. (The TARGET structure is part of the TARGINFO structure created during processing of the earlier PE_SETTARGETS messages.)

The default values are the same as those used when StartInking is called with lpinkinginfo set to NULL, but the PII_SAVEBACKGROUND flag is forced on in the wFlags member of the INKINGINFO structure to automatically save and restore the inking background.

The hrgnClip member of the INKINGINFO structure temporarily contains the index of the target in the TARGINFO structure retrieved by the PE_SETTARGETS message. Note that this is an overloading of this member to identify the targets. If the htrgTarget window specified in the TARGET structure returns 1 to this message, the following actions are taken:

•	If both the PII_INKPENTIP and PII_RECTCLIP flags are set, the pen tip specified by the tip member of the INKINGINFO structure is saved and used whenever the pen goes down within the area defined by the rectClip member. In most cases, the ink color changes at or near the clipping boundary, even when the pen is dragged over it. Because inking is done on a per-segment basis, there may be a slight overlap of color near a common boundary.

•	If the width given in the tip member is 0, no ink will appear within the area specified by the rectClip member. Password fields can be implemented using this technique.

•	If the PII_SAVEBACKGROUND flag is clear (0), any ink dropped within the area specified by the rectClip member is not removed at the termination of the collection. The ink edit control, for example, uses this technique. However, the parent window can override this default behavior when it finally receives a PE_GETINKINGINFO message after all its targets have been called.

•	If the PII_INKSTOP flag is set, the rectInkStop member is folded into the region specified by the hrgnInkStop member, which is used in calls to the StartInking function. When inking stops due to a pen-down event in the rectInkStop rectangle, a WM_PENMISC message with the PMSC_INKSTOP submessage is sent to the window specified by the htrgTarget member of the TARGET structure. lParam is the same as in the PE_PENDOWN message that caused the inking to stop. As with PII_SAVEBACKGROUND, hwnd can override the preprocessed values accumulated by the targets.

For further information about PE_GETINKINGINFO, see Chapter 2, "Starting Out with System Defaults."

See Also

INKINGINFO, PE_SETTARGETS, StartInking, TARGET, TARGINFO, WM_PENEVENT


PE_GETPCMINFO [New - Windows 95]
 PE_GETPCMINFO

[New - Windows 95]

Fills a PCMINFO structure, which is then used in a call to StartPenInput. Submessage of WM_PENEVENT.

Parameters

wParam

PE_GETPCMINFO.

lParam

Address of a PCMINFO structure, which is initialized with default values.

Comments

The default values are the same as those applied when StartPenInput is called with the lppcminfo parameter set to NULL:

•	Inking terminates when the time-out period elapses.

•	Inking terminates when a tap occurs outside the client rectangle of hwnd.

•	Inking does not start if the initial pen input consists of a press-and-hold gesture.

However, an exclusion region specified by the hrgnExclude member of the PCMINFO structure may have accumulated while processing PE_SETTARGETS messages. The window procedure can modify the values to customize the collection parameters before pen input begins.

If the PCM_DOPOLLING flag in the dwPcm member of the PCMINFO structure is set, it is disregarded and pen input remains in event mode.

See Also

PCMINFO, PE_SETTARGETS, StartPenInput, WM_PENEVENT


PE_MOREDATA [New - Windows 95]
 PE_MOREDATA

[New - Windows 95]

Sent to the window specified by the htrgTarget member of the TARGET structure to indicate that more pen data is available for that window. Submessage of WM_PENEVENT.

Parameters

wParam

PE_MOREDATA.

lParam

Address of an INPPARAMS structure.

Comments

DefWindowProc collects the pen input in response to the PE_PENDOWN, PE_PENUP, and PE_PENMOVE messages and sends the input on a stroke-by-stroke basis to one of the targets in the TARGINFO structure. On a pen-tip transition—that is, from pen-down to pen-up or vice versa — the Windows DefWindowProc function sends a PE_MOREDATA message to the window specified by the htrgTarget member of the TARGET structure identified in the PE_BEGINDATA message.

If it receives a PE_MOREDATA message, DefWindowProc uses AddPointsPendata or AddPenInputHRC, or does nothing, depending on whether the data type in the dwData member of the TARGET structure is a handle to an HPENDATA, an HRC handle for handwriting recognition, or some private data type.

See Also

AddPenInputHRC, AddPointsPendata, INPPARAMS, PE_PENMOVE, PE_PENDOWN, PE_PENUP, TARGET, TARGINFO, WM_PENEVENT


PE_PENDOWN [New - Windows 95]
 PE_PENDOWN

[New - Windows 95]

Generated by the pen driver component of the system when the pen tip touches the tablet surface. Submessage of WM_PENEVENT.

Parameters

wParam

PE_PENDOWN.

lParam

Extra information encapsulating a reference to the event and the HPCM that generated it. Applications can use the EventRefFromWpLp and HpcmFromWpLp macros to retrieve these values.

See Also

WM_PENEVENT


PE_PENMOVE [New - Windows 95]
 PE_PENMOVE

[New - Windows 95]

Generated by the pen driver component of the system when the pen moves, forcing more packets into the input queue. Submessage of WM_PENEVENT.

Parameters

wParam

PE_PENMOVE.

lParam

Extra information encapsulating a reference to the event and the HPCM that generated it. Applications can use the EventRefFromWpLp and HpcmFromWpLp macros to retrieve these values.

Comments

This message is analogous to WM_MOUSEMOVE. It provides notification that the pen is moving. Like its mouse counterpart, PE_PENMOVE messages are coalesced so that only a single such message exists in the application's message queue. How-ever, the event the message represents is the first of these coalesced events, not the last event, as is the case with WM_MOUSEMOVE.

An application need not handle this message if transition events like PE_PENUP and PE_PENDOWN are sufficient notification. PE_PENMOVE is useful when an application must monitor pen movement with greater frequency than PE_PENUP or PE_PENDOWN allows.

See Also

WM_PENEVENT


PE_PENUP [New - Windows 95]
 PE_PENUP

[New - Windows 95]

Generated by the pen driver component of the system when the pen tip leaves the tablet surface. Submessage of WM_PENEVENT.

Parameters

wParam

PE_PENUP.

lParam

Extra information encapsulating a reference to the event and the HPCM that generated it. Applications can use the EventRefFromWpLp and HpcmFromWpLp macros to retrieve these values.

See Also

WM_PENEVENT


PE_RESULT [New - Windows 95]
 PE_RESULT

[New - Windows 95]

During the processing of the PE_ENDDATA submessage, sent to all windows specified by the htrgTarget member of the TARGET structure that have received a PE_BEGINDATA message. PE_RESULT applies only to recognition and is sent only if the value in the dwData member of the TARGET structure is of type HRC. Submessage of WM_PENEVENT.

Parameters

wParam

PE_RESULT.

lParam

HRC object for the recognition session.

Comments

A target can perform recognition-result processing in response to PE_RESULT. If it receives this message, the Windows DefWindowProc function performs default result processing. The first HRCRESULT object for the HRC is obtained using the GetResultsHRC function. The HRCRESULT handle is used to retrieve a string of symbols that are converted, one by one, into characters. The characters are then posted as WM_CHAR messages to the window specified by the htrgTarget member of the TARGET structure.

The clear, cut, copy, paste, and undo gestures are converted to WM_CLEAR, WM_CUT, WM_COPY, WM_PASTE, and WM_UNDO messages. They are posted to the htrgTarget target, together with appropriate mouse messages, so that the target can perform appropriate processing (such as selection) before applying the gestures.

See Also

TARGET, WM_PENEVENT


PE_SETTARGETS [New - Windows 95]
 PE_SETTARGETS

[New - Windows 95]

Sent to an application window so that it can set its own targeting structure. Submessage of WM_PENEVENT.

Parameters

wParam

PE_SETTARGETS.

lParam

Address of a far pointer to a TARGINFO structure. (Note that lParam is a pointer to a pointer.)

Return Value

The application should return LRET_DONE to indicate that it has set up the targeting information for the child windows. A return of 0 indicates that the application is the only target. The application can also return LRET_ABORT to abort the targeting process altogether.

Comments

The DefWindowProc function enumerates all the descendants of the window specified in its first parameter and sends each one a PE_GETPCMINFO message. For every descendant that returns 1 to this message, the PCM_RECTBOUND and PCM_RECTEXCLUDE flags of the PCMINFO structure are examined. If the PCM_RECTBOUND flag is set, the descendant is included in the list of potential targets and the rectBound member in PCMINFO is copied to the rectBound member of the TARGET structure. If the PCM_RECTEXCLUDE flag is set, the rectExclude member of PCMINFO is added to an exclusion region that is passed (as the hrgnExclude member of the PCMINFO structure) to the StartInput call. If there are no descendants, or if the window procedure of hwnd returns 0, a TARGINFO structure is constructed with hwnd as the single target.

For default processing behavior, the application should allow PE_SETTARGETS to fall through to DefWindowProc. A PE_GETPCMINFO message will follow to establish targets or termination conditions (buttons, for example).

For further information about PE_SETTARGETS, see Chapter 2, "Starting Out with System Defaults."

An application can replace the default targeting with a set of targets it defines itself. In this case, the application allocates enough memory for the TARGINFO structure plus all the TARGET structures.

Example

The following example illustrates how to handle PW_SETTARGETS for n targets, where each target is in the array rgHwnd. Notice the code increases the allocation by n−1 TARGET structures, since TARGINFO already contains one TARGET structure.

DWORD cbAlloc         = sizeof(TARGINFO) + (n-1) * sizeof(TARGET);

HGLOBAL hTargets      = GlobalAlloc( GHND, cbAlloc );

LPTARGINFO lptarginfo = GlobalLock( hTargets );

lptarginfo->cbSize    = sizeof(TARGINFO);

lptarginfo->cTargets  = n;                   // Number of targets

lptarginfo->htrgOwner = HtrgFromHwnd(hwnd);  // Macro in penwin.h

lptarginfo->dwFlags   = TPT_TEXTUAL;         // For text

for (i = 0; i < n; i++)

{

HWND hwnd = (HTRG)rgHwnd[i];	// Window of this target

lptarginfo->rgTarget[i].dwFlags    = 0;	// Reserved

lptarginfo->rgTarget[i].idTarget   = i;

lptarginfo->rgTarget[i].htrgTarget = HtrgFromHwnd(hwnd);

lptarginfo->rgTarget[i].dwData = 0;

// Use screen coords of each window:

  {

// Note: rectBound is a RECTL. In 16-bit code, one has to assign each

// field separately. In 32-bit code, you can use the rectBound directly.

  RECT rect;

GetClientRect( hwnd, &rect);

ClientToScreen( hwnd, (LPPOINT)&rectBound.left);

ClientToScreen( hwnd, (LPPOINT)&rectBound.right);

  lptarginfo->rgTarget[i].rectBound.left = rect.left;

  lptarginfo->rgTarget[i].rectBound.top = rect.top;

  lptarginfo->rgTarget[i].rectBound.right = rect.right;

  lptarginfo->rgTarget[i].rectBound.bottom = rect.bottom;

  }

}

// Return our structures:

*(LPTARGINFO FAR *)lParam = lptarginfo;

See Also

PCMINFO, TARGET, TARGINFO, WM_PENEVENT


PE_TERMINATED [New - Windows 95]
 PE_TERMINATED

[New - Windows 95]

Generated by the pen driver component of the system when pen input terminates. Submessage of WM_PENEVENT.

Parameters

wParam

PE_TERMINATED.

lParam

Extra information encapsulating a reason for termination and the current HPCM. Applications can use the TerminationFromWpLp and HpcmFromWpLp macros to retrieve these values.

Comments

When an application receives the PE_TERMINATED message, collection has already terminated and the HPCM handle returned from StartPenInput has become invalid. PE_TERMINATED indicates an application should perform such tasks as final results processing, repainting, and cleanup.

See Also

WM_PENEVENT


PE_TERMINATING [New - Windows 95]
 PE_TERMINATING

[New - Windows 95]

Generated by the pen driver component of the system when pen input is about to terminate. Submessage of WM_PENEVENT.

Parameters

wParam

PE_TERMINATING.

lParam

Extra information encapsulating a reason for termination and the current HPCM. Applications can use the TerminationFromWpLp and HpcmFromWpLp macros to retrieve these values.

Comments

When it receives PE_TERMINATING, the application must immediately retrieve any remaining points.

See Also

WM_PENEVENT


WM_CTLINIT [New - Windows 95]
 WM_CTLINIT

[New - Windows 95]

Sent to the parent of a bedit, hedit, or iedit control while the control is being created in order to get extra information about the control.

Parameters

wParam

Type of control. This parameter can be CTLINIT_BEDIT, CTLINIT_IEDIT, or CTLINIT_HEDIT.

lParam

Address of a control structure, depending on wParam. For values of CTLINIT_BEDIT, CTLINIT_HEDIT, or CTLINIT_IEDIT in wParam, lParam points to either a CTLINITBEDIT, CTLINITHEDIT, or CTLINITIEDIT structure, respectively.

Comments

Each of the CTLINIT structures has its first three members already initialized: cbSize (size of the structure), hwnd (handle to the control window), and id (child identifier of the control). The parent of the control can set appropriate values to the rest of the members in the structure and the control will then use those values when initializing itself.

See Also

CTLINITHEDIT, CTLINITBEDIT, CTLINITIEDIT


WM_GLOBALRCCHANGE [New - Windows 95]
 WM_GLOBALRCCHANGE

[New - Windows 95]

See WM_PENMISCINFO.


WM_HOOKRCRESULT [New - Windows 95]
 WM_HOOKRCRESULT

[New - Windows 95]

Sent to a window before WM_RCRESULT is sent to the target window.

Note

The WM_HOOKRCRESULT message is provided only for compatibility with version 1.0 of the Pen API and will not be supported in future versions.

Parameters

wParam

REC_ code indicating why recognition ended.

lParam

Address of an RCRESULT structure.

Comments

The application may examine the results in the RCRESULT structure. Changing any of the values leads to unpredictable results. The application should make a copy of any information it needs.

See Also

RCRESULT, SetRecogHook, WM_RCRESULT


WM_PENCTL [New - Windows 95]
 WM_PENCTL

[New - Windows 95]

Performs several actions, including:

•	Converts a logical character position to a byte offset.

•	Converts a byte offset to a logical character position.

•	Switches the font in a bedit control to the default font.

Parameters

wParam

Submessage identifier as described in the following table. Each submessage is documented separately.

Constant	Description
HE_CANCELCONVERT	Cancels Kana-to-Kanji conversion. (Japanese version only.)
HE_CHAROFFSET	Converts logical character position of a character in the control to byte offset to the character. For bedit controls only.
HE_CHARPOSITION	Converts byte offset in the text buffer of the control to the logical character position, which contains the byte specified by the byte offset. For bedit controls only.
HE_DEFAULTFONT	Switches the font of the bedit control to the default font that the bedit selects at the time of creation. For bedit controls only.
HE_ENABLEALTLIST	Enables or disables the alternate list in a bedit control.
HE_FIXKKCONVERT	Confirm undetermined string and close Input Method Editor (IME). (Japanese version only.)
HE_GETBOXLAYOUT	Points to the BOXLAYOUT structure, which is filled with the current box layout for the control. For bedit controls only.
HE_GETCONVERTRANGE	Gets the range of the marked conversion string. (Japanese version only.)
HE_GETINFLATE	LPRECTOFS filled with current value.
HE_GETINKHANDLE	Retrieves a handle to the captured ink.
HE_GETKKCONVERT	Determines if the Input Method Editor (IME) is in pen (or keyboard) conversion mode. (Japanese version only.)
HE_GETKKSTATUS	Determines the mode of the Kana-to-Kanji conversion. (Japanese version only.)
HE_GETRC	Fills an RC structure, whose address is passed in the lParam, with current values. See the note that follows.
HE_GETUNDERLINE	Queries whether underline mode is set. For hedit controls only.
HE_HIDEALTLIST	Hides the alternate list in a bedit control, assuming it is being displayed.
HE_KKCONVERT	Starts Kana-to-Kanji conversion. (Japanese version only.)
HE_PUTCONVERTCHAR	Sends a character, marked for conversion, to the IME. (Japanese version only.)
HE_SETBOXLAYOUT	Sets a BOXLAYOUT structure. For bedit controls only.
HE_SETCONVERTRANGE	Sets the range of the marked conversion string. (Japanese version only.)
HE_SETINFLATE	Specifies adjustments to the control window to specify the size of the writing window.
HE_SETINKMODE	Starts the collection of inking.
HE_SETRC	Sets the RC structure, whose address is passed in the lParam. See the note that follows.
HE_SETUNDERLINE	Sets or cancels underline mode. For hedit controls only.
HE_SHOWALTLIST	Displays the alternate list menu in a bedit control, assuming that alternate lists are enable.
HE_STOPINKMODE	Stops the collection of ink.
Note

The HE_GETRC and HE_SETRC submessages are provided only for compatibility with version 1.0 of the Pen API and will not be supported in future versions.

lParam

Depends on wParam. See the individual HE_ submessage descriptions for more information.

Comments

Any control message (a message with the EM_ prefix) that can be sent to an edit control can also be sent to an hedit window. Most of these control messages are also supported by bedit controls.

The HE_ submessages are also common to both hedit and bedit controls except as noted in the preceding table. In a bedit control, each cell contains one logical character. Carriage return (CR) and line-feed (LF) bytes together form one logical character.

Before using the HE_SETBOXLAYOUT or HE_SETINFLATE submessages, it is often useful to retrieve the current structure associated with the control using the HE_GETBOXLAYOUT or HE_GETINFLATE submessages. You should then change the appropriate members in the retrieved structure. This procedure reduces the risk of inadvertent changes to the structure.

In older applications compatible with version 1.0 of the Pen API, placing the value RRM_SYMBOL in wResultMode of the RC structure disables all default diction-ary processing in a bedit control. The 1.0 application can perform dictionary pro-cessing on its own by retrieving the recognition results during the processing of the HN_RESULT notification and calling the DictionarySearch function.

See Also

HE_CANCELCONVERT, HE_CHAROFFSET, HE_CHARPOSITION, HE_DEFAULTFONT, HE_ENABLEALTLIST, HE_FIXKKCONVERT, HE_GETBOXLAYOUT, HE_GETIMEDEFAULT, HE_GETINFLATE, HE_GETINKHANDLE, HE_GETKKCONVERT, HE_GETKKSTATUS, HE_GETUNDERLINE, HE_SETBOXLAYOUT, HE_SETIMEDEFAULT, HE_SETINFLATE, HE_SETINKMODE, HE_SETUNDERLINE, HE_SHOWALTLIST, HE_STOPINKMODE


WM_PENEVENT [New - Windows 95]
 WM_PENEVENT

[New - Windows 95]

Sent to an application after StartPenInput has initiated a pen collection.

Parameters

wParam

Submessage identifier as described in the following table. Each submessage is documented separately.

Constant	Description
PE_BEGINDATA	Initialization message to all targets.
PE_BEGININPUT	Begin default input.
PE_BUFFERWARNING	The input queue is getting full. The application should call GetPenInput.
PE_ENDDATA	Termination message to all targets.
PE_RESULT	Recognition result message to all targets.
PE_ENDINPUT	Input termination message to window.
PE_GETINKINGINFO	Get inking information.
PE_GETPCMINFO	Get input collection information.
PE_MOREDATA	Target gets more data.
PE_PENMOVE	The pen moved, placing more packets into the input queue without a tip transition. This mes-sage is coalesced with other PE_PENMOVE messages, so the Windows queue has only a single such message waiting.
PE_PENDOWN	The pen tip went down.
PE_PENUP	The pen tip went up.
PE_SETTARGETS	Set TARGINFO target data structure.
PE_TERMINATED	Pen input terminated. The HPCM handle for the current collection has become invalid.
PE_TERMINATING	Pen input is about to terminate. The application must retrieve any remaining points immediately.
lParam

Depends on wParam. In most cases, this is extra information encapsulating a reference to the event and the HPCM that generated it. These are retrieved using the EventRefFromWpLp and HpcmFromWpLp macros.

Comments

This message is not sent if polling is used—that is, if the dwPcm member of the PCMINFO structure contains the PCM_DOPOLLING flag.

See Also

GetPenInput, StartPenInput, TARGINFO


WM_PENMISC [New - Windows 95]
 WM_PENMISC

[New - Windows 95]

Sent to notify an application of some pen-related change, such as a change in a bedit control. WM_PENMISC is also used to get information from a window about pen-related attributes.

Parameters

wParam

One of the following subfunctions:

PMSC_BEDITCHANGE

Indicates that system settings for bedit controls have been changed. When it receives this message, a bedit control updates its state according to the settings indicated by the BOXEDITINFO structure that lParam points to.

PMSC_GETHRC

Return a copy of the HRC handle associated with the window. lParam is unused and should be set to 0. If a window has no associated HRC structure, NULL is returned. It is the caller's responsibility to destroy any HRC the message returns.

PMSC_GETINKINGINFO

Retrieve the INKINGINFO structure associated with the window and copy it to the structure pointed to by lParam. The message is ignored if lParam is NULL.

PMSC_GETPCMINFO

Retrieve the PCMINFO structure associated with the window and copy it to the structure pointed to by lParam. If a window has no associated PCMINFO structure, NULL is returned. The message is ignored if lParam is NULL. The system initializes PCMINFO as follows:

•	dwPcm is a combination of the PCM_RECTBOUND, PCM_TIMEOUT, and PCM_TAPNHOLD flags.

•	rectBound is the client area of hwnd, in screen coordinates.

•	dwTimeout is the current writing time-out in milliseconds, as reported by GetPenMiscInfo using PMI_TIMEOUT.

•	All other members are 0.

PMSC_INKSTOP

Inking has stopped because of a pen-down event. lParam contains the HPCM handle corresponding to the collection and the event reference at which the inking stopped. An application can retrieve these values with the HpcmFromWpLp and EventRefFromWpLp macros, respectively.

PMSC_KKCTLENABLE

WM_PENMISC is broadcast when kana-kanji controls are enabled. (Japanese version only.)

PMSC_LOADPW

WM_PENMISC is broadcast when PENWIN.DLL loads or unloads. lParam is one of the following:

•	PMSCL_LOADED (PENWIN.DLL just loaded).

•	PMSCL_UNLOADED (PENWIN.DLL just unloaded).

•	PMSCL_UNLOADING (PENWIN.DLL is about to unload).

PMSC_PENUICHANGE

Broadcast to indicate that the pen user interface DLL (PENUI) has been changed. (Japanese version only.)

PMSC_SETHRC

Associate the HRC handle in lParam with the window. The window makes a copy of the HRC for itself so that the sender of the message can destroy its copy. Returns nonzero if successful; otherwise, returns 0.

PMSC_SETINKINGINFO

Associate the INKINGINFO structure pointed to by lParam with the window. Returns nonzero if successful; otherwise, returns 0.

PMSC_SETPCMINFO

Associate the PCMINFO structure pointed to by lParam with the window. The cbSize member of the structure must be initialized with sizeof( PCMINFO ). Returns nonzero if successful; otherwise, returns 0.

PMSC_SUBINPCHANGE

Indicates the character finder DLL (SUBINPUT) has been changed. (Japanese version only.)

PMSC_GETSYMBOLCOUNT

Retrieve the number of symbols contained in the last recognition result. lParam should be 0. This message should be sent by the window that received the HN_RESULT notification before returning from the notification message.

PMSC_GETSYMBOLS

Retrieve the symbols contained in the last recognition result. lParam should be a pointer to a buffer large enough to accommodate the number of symbols contained in the result followed by SYV_NULL. The number of symbols in the result can be obtained by sending the WM_PENMISC message to the window with the PMSC_GETSYMBOLCOUNT submessage. This message should be sent by the window that received the HN_RESULT notification before returning from the notification message. A nonzero value is returned to indicate success.

PMSC_SETSYMBOLS

Change the symbols for the last recognition result. lParam should be a pointer to a buffer containing the array of symbols to be set terminated by SYV_NULL. lParam may be NULL to indicate an empty result. The control receiving this message should not perform any garbage detection on results set in this manner. This allows the application to perform its own garbage detection. In the case of the bedits controls, the number of symbols set must be the same as the number of symbols obtained using the WM_PENMISC message with the PMSC_GETSYMBOLCOUNT submessage. If not, the symbols are not set. This message should be sent by the window that received the HN_RESULT notification before returning from the notifi-cation message. A nonzero value is returned to indicate success.

lParam

Depends on wParam.

See Also

BOXEDITINFO, INKINGINFO, PCMINFO


WM_PENMISCINFO [New - Windows 95]
 WM_PENMISCINFO

[New - Windows 95]

Posted to all top-level windows whenever a pen system change is made.

Parameters

wParam

PMI_ value that identifies the system change.

lParam

New value, depending on wParam.

Comments

This message is broadcast to all top-level windows whenever a new global pen default is set by a call to the SetPenMiscInfo function. (Control Panel is the principal source of these changes.) A series of WM_PENMISCINFO broadcasts is typically made after a Control Panel application is closed.

In version 2.0 of the Pen API, the message parameters have been defined and the name of this message has been changed from WM_GLOBALRCCHANGE to WM_PENMISCINFO, although the value is the same for compatibility with version 1.0. The wParam and lParam parameters are the same as the parameter values provided to the SetPenMiscInfo function.

For version 1.0 compatibility, a call to the SetGlobalRC function also causes a posted broadcast of this message to all top-level windows, but the parameters are both 0. PMI_RCCHANGE may be used as an alias for 0 for wParam; however, PMI_RCCHANGE is not a valid parameter to GetPenMiscInfo or SetPenMiscInfo.

See Also

SetPenMiscInfo, GetPenMiscInfo, SetGlobalRC, PMI_


WM_RCRESULT [New - Windows 95]
 WM_RCRESULT

[New - Windows 95]

Sent to an application by a recognizer with the results of a recognition.

Note

The WM_RCRESULT message is provided only for compatibility with version 1.0 of the Pen API and will not be supported in future versions.

Parameters

wParam

REC_ code indicating why recognition ended.

lParam

Address of an RCRESULT structure.

See Also

ProcessWriting, RCRESULT, Recognize, RecognizeData


 Pen Application Programming Interface Constants

This chapter describes some of the many manifest constants defined by the Pen Application Programming Interface, listed alphabetically. Constants listed in this chapter are primarily those that do not contain a complete listing in any individual function or message description elsewhere in this documentation. Constants that pertain to individual functions or messages can be found with the descriptions of those functions or messages.

Each entry includes a complete description of the constant. For a comprehensive list of the Pen API constants, see Chapter 9, "Summary of the Pen Application Programming Interface," or refer to the PENWIN.H header file. Refer to the index to locate the descriptions of any of the Pen API constants.


ALC_ Alphabet Codes [New - Windows 95]
 ALC_ Alphabet Codes

[New - Windows 95]

The ALC_ constants enable a subset of the active character set, depending on the current language.

For example, the French language includes "h" in the lowercase alphabet. In the same way, "£" replaces "$" if ALC_MONETARY is set in British systems. For more information about alphabets, see "Specifying an Alphabet Set" in Chapter 8 and "Alphabet" in Chapter 5.

Comments

The following ALC_ constants are are supported:

Constant	Description
ALC_ALL	All characters except Japanese characters.
ALC_ALPHA	ALC_LCALPHA | ALC_UCALPHA.
ALC_ALPHANUMERIC	ALC_LCALPHA | ALC_UCALPHA | ALC_NUMERIC.
ALC_ASCII	Seven-bit characters ASCII #20−ASCII #0x7F
ALC_DBCS	Allow double-byte character set (DBCS) variety of single-byte character set (SBCS).
ALC_DEFAULT	Default value; uses complete set of recognizable char-acters and gestures. The set of these is defined by the recognizer. It is the set of characters at or above ALC_SYSMINIMUM that the recognizer can accurately distinguish. If an application sets ALC_DEFAULT in the HRC object, and the recognizer is an alphanumeric system recognizer, the recognizer must at least support ALC_SYSMINIMUM as a default. ALC_DEFAULT should be the same character set as the complete character set for the given language minus the ALC_OTHER characters. If an application combines ALC_DEFAULT with other ALC_ values, ALC_DEFAULT is ignored.
ALC_GESTURE	Gestures.
ALC_GLOBALPRIORITY	Specifies that the global recognition priorities (from Tool Palette) are to be used during recognition. An application can control its own recognition priority in a control by clearing this flag and then setting its own priorities in the HRC.
ALC_HIRAGANA	Hiragana characters. (Japanese version only.)
ALC_JIS1	All Kanji Shift JIS level 1 characters. (Japanese version only.)
ALC_KANJI	Kanji characters, Shift JIS levels 1, 2, and 3. (Japanese version only.)
ALC_KANJIALL	ALC_ALL | ALC_HIRAGANA | ALC_KATAKANA | ALC_KANJI. (Japanese version only.)
ALC_KANJISYSMINIMUM	Minimum set of characters needed for Japanese system recognizer. Same as ALC_SYSMINIMUM | ALC_HIRAGANA | ALC_KATAKANA | ALC_JIS1. (Japanese version only.)
ALC_KATAKANA	Katakana characters. (Japanese version only.)
ALC_LCALPHA	Lowercase letters a−z.
ALC_MATH	Math symbols:  %^*()-+={}<>,/.
ALC_MONETARY	Monetary symbols:  ,.$ or appropriate currency desig-nation such as the yen or pound sterling symbol, accord-ing to the current language setting.
ALC_NONPRINT	Space, tab, carriage-return, and control glyphs.
ALC_NOPRIORITY	No priority. This value means the application has no preference for one type of symbol over another.
ALC_NUMERIC	Numerals 0−9.
ALC_OEM	Bits reserved for recognizer capabilities specific to the original equipment manufacturer (OEM).
ALC_OTHER	Other symbols:  @ # | _ ~ [ ]. That is, all other symbols not included in ALC_ALPHANUMERIC, ALC_MONETARY, ALC_MATH, and ALC_PUNC.
ALC_PUNC	Punctuation:  !-;`"?()&.,\.
ALC_RESERVED	Reserved.
ALC_SYSMINIMUM	Minimum set of characters needed for Roman alphabet system recognizers:  ALPHANUMERIC | ALC_PUNC | ALC_WHITE | ALC_GEST.
ALC_UCALPHA	Uppercase letters A−Z.
ALC_USEBITMAP	(Description follows table.)
ALC_WHITE	White space. If this value is not set in the HRC object, the recognizer should ignore any white space left between characters. Thus, ALC_WHITE is included in the ALC_DEFAULT. For example, in the zip code field of the Hform sample application, where ALC_NUMERIC | ALC_GESTURE is set, the user does not have to worry about getting any extraneous spaces.
If ALC_USEBITMAP is set, it indicates the recognizer should adopt an alphabet set defined by the application. The defined set specifies individual characters of an alphabet by setting bits in a 256-bit bitfield. The lowest bit corresponds to the first character of the alphabet, the second bit to the second character, and so forth.

An application passes the bitfield to a recognizer through the SetAlphabetHRC or SetBoxAlphabetHRC functions. The following code shows how. Assume the array rgbfSet holds the desired bit values.

HRC     hrc;                         // HRC handle

BYTE    rgbfSet[cbRcrgbfAlcMax]      // 256-bit bitfield

SetAlphabetHRC( hrc, ALC_USEBITMAP, (LPBYTE) rgbSet );

ALC_USEBITMAP can be combined with other ALC_ values using the bitwise-OR operator. An application can thus, for example, select certain letters with a defined bitmap and combine them with all numerals and punctuation.

For Asian languages other than Japanese, refer to the appropriate subsets within the language: phonetic symbols for words within the language, phonetic symbols for words outside the language, and native pictographs. For example, in Korean, ALC_HANGUEL equals ALC_KATAKANA, and ALC_HANJA equals ALC_KANJI.

For kanji and other Asian encodings, different effects are possible depending on the state of ALC_DBCS. These effects are described in the following table.

Character in	ALC_DBCS = 0	ALC_DBCS = 1
ALC_HIRAGANA	N/A	Shift JIS characters 0x8154, 0x8155, and 0x829F − 0x82F1.
ALC_JIS1	N/A	All Kanji Shift JIS level 1 characters.
ALC_KATAKANA	0xA1 - 0xDF	Shift JIS characters 0x814A, 0x814B, 0x8152, 0x8153, 0x815B, and 0x8340 − 0x8396.
ALC_KANJI	N/A	All Kanji characters, Shift JIS levels 1, 2, and 3.
The following table shows the characters in Shift-JIS in each ALC_ set supported in the Japanese version:

ALC_ value	Shift JIS Code
ALC_HIRAGANA	0x8154, 0x8155, and 0x829F − 0x82F1
ALC_JIS1	0x8156 − 0x815A, 0x889F − 0x9872
ALC_KANJI	0x8156 − 0x815A, 0x889F − 0xEAA4, 0xED40 − 0xEDFC, 0xEE40 − 0xEEFC, 0xF040 − 0xF9FC, 0xFAF0 − 0xFAFC, 0xFB40 − 0xFBFC, 0xFC40 − 0xFC4B
ALC_KATAKANA	0x814A, 0x814B, 0x8152, 0x8153, 0x815B, 0x8340 − 0x8396
ALC_LCALPHA	0x8281 − 0x829A
ALC_MATH	0x8143, 0x8144, 0x814F, 0x815E, 0x8169, 0x816A, 0x816F, 0x8170, 0x817B − 0x817E, 0x8180 − 0x8188, 0x8193, 0x8196
ALC_MONETARY	0x8143, 0x8144, 0x818F − 0x8192
ALC_NONPRINT	0x8140
ALC_NUMERIC	0x824F − 0x8258
ALC_OTHER	0x814C − 0x814E, 0x8150, 0x8151, 0x8160 − 0x8164, 0x816B, 0x816C, 0x8171 − 0x8174, 0x8179, 0x817A, 0x817F,  0x8189 − 0x818E, 0x8194, 0x8197 − 0x81FC, 0x8240 − 0x824E, 0x8259 − 0x825F, 0x827A − 0x8280, 0x829B − 0x829E, 0x82F2 − 0x82FC, 0x837F, 0x897 − 0x83FC, 0x8840 − 0x84FC, 0x8740 − 0x879D
ALC_PUNC	0x8141 − 0x8149, 0x815B − 0x815F, 0x8165 − 0x816A, 0x816D − 0x8170, 0x8175 − 0x8178, 0x817C, 0x8195
ALC_UCALPHA	0x8260 − 0x8279
ALC_WHITE	0x8140
A recognizer must not return a symbol value outside the specified subset. However, a recognizer does not have to force a match to the subset; it can instead return "unknown" if a suitable match is not found.

You can set the ALC_ value for an hedit or bedit control in a dialog box by insert-ing a special string in the .RC file's CONTROL statement. This string is in the form ALC<xxxx> where xxxx represents a case-independent hexadecimal ALC_ code, without a preceding 0x qualifier. You can append normal window text after the ALC_ entry.

The following line demonstrates setting the ALC_ value for an hedit control using a CONTROL statement:

CONTROL "ALC<402C>Dollars", IDD_PAID, "hedit", ES_LEFT | ... etc.

In the above example, the ALC<402C> value is stripped out with "Dollars" left as window text. The number 402C is the hexadecimal equivalent of:

ALC_NUMERIC | ALC_PUNC | ALC_MONETARY | ALC_GESTURE

The following example allows only kanji characters, katakana characters, and gestures; it does not specify initial window text:

CONTROL "ALC<74000>", IDD_J, "hedit", ES_LEFT | ... etc.


BXD_ Boxed Edit Control [New - Windows 95]
 BXD_ Boxed Edit Control

[New - Windows 95]

The BXD_ values define the initial dimensions of the various components of a boxed edit (bedit) control. These are constants defined in terms of dialog units. They are converted to pixel dimensions by the bedit control before use.

For more information, see the entries for the BOXLAYOUT and GUIDE structures in Chapter 11, "Pen Application Programming Interface Structures."

The following table lists the BXD_ values.

Constant	Value	Description
BXD_BASEHEIGHT	13	Initial value for cyBase in GUIDE structure after conversion from dialog units to pixels.
BXD_BASEHORZ	0	Initial value for cxBase in GUIDE structure after conversion from dialog units to pixels.
BXD_CELLHEIGHT	16	Initial value for cyBox in GUIDE structure after conversion from dialog units to pixels.
BXD_CELLWIDTH	12	Initial value for cxBox in GUIDE structure after conversion from dialog units to pixels.
BXD_CUSPHEIGHT	2	Initial value for cyCusp in BOXLAYOUT structure after conversion from dialog units to pixels.
BXD_ENDCUSPHEIGHT	4	Initial value for cyEndCusp in BOXLAYOUT structure after conversion from dialog units to pixels.
BXD_MIDFROMBASE	0	Same as BXD_BASEHORZ.


BXDK_ Japanese Boxed Edit Control [New - Windows 95]
 BXDK_ Japanese Boxed Edit Control

[New - Windows 95]

The BXDK_ values define the initial dimensions of the various components of a Japanese boxed edit (bedit) control. These are constants defined in terms of dialog units. They are converted to pixel dimensions by the bedit control before use.

For more information, see the entries for the BOXLAYOUT and GUIDE structures in Chapter 11, "Pen Application Programming Interface Structures."

The following table lists the BXDK_ values.

Constant	Value	Description
BXDK_BASEHEIGHT	28	Initial value for cyBase in GUIDE structure after conversion from dialog units to pixels.
BXDK_BASEHORZ	0	Initial value for cxBase in GUIDE structure after conversion from dialog units to pixels.
BXDK_CELLHEIGHT	32	Initial value for cyBox in GUIDE structure after conversion from dialog units to pixels.
BXDK_CELLWIDTH	32	Initial value for cxBox in GUIDE structure after conversion from dialog units to pixels.
BXDK_CUSPHEIGHT	28	Initial value for cyCusp in BOXLAYOUT structure after conversion from dialog units to pixels.
BXDK_ENDCUSPHEIGHT	10	Initial value for cyEndCusp in BOXLAYOUT structure after conversion from dialog units to pixels.


IDC_ Display Cursor [New - Windows 95]
 IDC_ Display Cursor

[New - Windows 95]

A pen-aware display driver must define the following new cursor types.

Constant	Value	Description
IDC_ALTSELECT	32501	Upside-down standard arrow used for tap-and-hold selection.
IDC_PEN	32631	Default pen. Pen points up and to the left.
Example

You can access the tap-and-hold cursor with the following code:

HANDLE	hPenDLL = GetSystemMetrics( SM_PENWINDOW);

if (hPenDLL)

SetCursor( LoadCursor( hPenDLL, IDC_ALTSELECT ) );


PCM_ Pen Collection Mode [New - Windows 95]
 PCM_ Pen Collection Mode

[New - Windows 95]

Pen collection mode values define the condition that terminates an input session. (The system is said to be in "pen collection mode" during an input session when pen movement generates input data instead of being interpreted as mouse movement.) Pen collection can be stopped on any of the following conditions set by the PCM_ values in the dwPcm member of the PCMINFO structure:

Constant	Description
PCM_ADDDEFAULTS	Combine the default termination conditions with those specified by the application.
PCM_DOPOLLING	Request polling mode, rather than the default WM_PENEVENT messages.
PCM_INVERT	Stop pen collection if the user touches the "eraser" end of the pen to the tablet. Not all tablets can detect this event.
PCM_PENUP	Stop pen collection when the pen is lifted from the tablet.
PCM_RANGE	Stop pen collection when the pen leaves tablet's range of sensitivity. Not all tablets can detect this event.
PCM_RECTBOUND	Stop when the pen is placed down outside the inclusion rectangle. The inclusion rectangle is specified in the rectBound member of the PCMINFO structure.
PCM_RECTEXCLUDE	Stop when the pen touches inside the exclusion rectangle. The exclusion rectangle is specified in the rectExclude member of the PCMINFO structure.
PCM_RGNBOUND	Stop when the pen touches outside the bounding region specified in the hrgnBound member of the PCMINFO structure.
PCM_RGNEXCLUDE	Stop when the pen touches inside the exclusion region specified in the hrgnExclude member of the PCMINFO structure.
PCM_TAPNHOLD	Enable detection of the tap-and-hold gesture.
PCM_TIMEOUT	Stop pen collection if there is no pen activity for a specified time-out. The time-out value is specified in the dwTimeout member of the PCMINFO structure.


PDC_ Pen Device Capabilities [New - Windows 95]
 PDC_ Pen Device Capabilities

[New - Windows 95]

The following table lists the values for the lPdc member of the PENINFO structure:

Constant	Description
PDC_BARREL1	Barrel button 1 is present.
PDC_BARREL2	Barrel button 2 is present.
PDC_BARREL3	Barrel button 3 is present.
PDC_INTEGRATED	Tablet surface is also a display monitor.
PDC_INVERT	The tablet can detect when the "eraser" end of the pen is in contact with the tablet.
PDC_PROXIMITY	The tablet can detect when the pen is near but not in contact with the tablet surface.
PDC_RANGE	The tablet can detect when the pen leaves or enters the tablet's range of sensitivity.
PDC_RELATIVE	The pen driver can generate only relative coordinates.
For additional details, see the entry for the PENINFO structure in Chapter 11, "Pen Application Programming Interface Structures."


PDK_ State Bits for Pen Driver Kit [New - Windows 95]
 PDK_ State Bits for Pen Driver Kit

[New - Windows 95]

The PDK_ values inform the system when a mouse event is being generated by pen movement, as well as the current state of any barrel buttons. This information is contained in the wPDK and wPdk members of the STROKEINFO and PENPACKET structures, respectively. The GetPenAsyncState function also accepts a PDK_ value as its only argument. The following table lists the PDK_ values:

Constant	Value	Description
PDK_NULL	0x0000	No flags set (default).
PDK_UP	0x0000	Same as PDK_NULL.
PDK_BARREL1	0x0002	Barrel button 1 is depressed.
PDK_BARREL2	0x0004	Barrel button 2 is depressed.
PDK_BARREL3	0x0008	Barrel button 3 is depressed.
PDK_DOWN	0x0001	Pen is in contact with the tablet.
PDK_SWITCHES	0x000F	All of the above.
PDK_TIPMASK	0x0001	Mask for testing PDK_DOWN.
PDK_TRANSITION	0x0010	Only has meaning if set by pen services. This bit is set if the first point in the sequence being returned is in a different pen-tip state (up or down) from the previous points returned. If set on a call to AddPointsPenData, a new stroke is created even if the previous call to AddPointsPenData appended points of the same pen state. By default, a sub-sequent call to AddPointsPenData adding points of the same state as the previous call appends the points to the last stroke instead of creating a new stroke.
PDK_EVENT	0x0010	Alias for PDK_TRANSITION.
PDK_PENIDMASK	0x0F00	Mask for bits 8−11 (see paragraph following table).
PDK_INVERTED	0x0080	Pen is upside down ("eraser" end is in contact with tablet).
PDK_INKSTOPPED	0x2000	Inking has stopped.
PDK_OUTOFRANGE	0x4000	Set if the tablet detects the pen leaving the range of detection. If set, other information in the packet is invalid.
PDK_DRIVER	0x8000	Set if event is generated by the pen driver (as opposed to the mouse driver).
For PDK_ values other than PDK_PENIDMASK, bits 8 through 11 contain the identification number of the physical pen that generated the event. Pen numbering begins at 0.

See Also

PENPACKET, STROKEINFO


PDT_ OEM-Specific Data [New - Windows 95]
 PDT_ OEM-Specific Data

[New - Windows 95]

PDT_ values provide information specific to the tablet hardware. These values are used in the wPdt member of the OEMPENINFO structure.

Constant	Value	Description
PDT_NULL	0	Null value.
PDT_PRESSURE	1	Tablet can detect change in pen pressure.
PDT_HEIGHT	2	Tablet can detect height of pen above surface.
PDT_ANGLEXY	3	Tablet can detect change in pen horizontal angle.
PDT_ANGLEZ	4	Tablet can detect change in pen vertical angle.
PDT_BARRELROTATION	5	Tablet can detect rotation of pen barrel.
PDT_OEMSPECIFIC	16	Maximum number of values allowed.
For additional information, see the PENINFO and OEMPENINFO structures in Chapter 11, "Pen Application Programming Interface Structures."


PDTS_ Pen Data Scaling [New - Windows 95]
 PDTS_ Pen Data Scaling

[New - Windows 95]

The PDTS_ data scaling units are used in the uScale and wPndtNew arguments of the CreatePenData and MetricScalePenData functions, respectively. These units are used for the wPndts member of the PENDATAHEADER structure. Positive x-coordinate is to the right; positive y-coordinate is down.

The following table lists the PDTS_ values. These values cannot be combined with the bitwise-OR operator.

Constant	Description
PDTS_ARBITRARY	The application has done its own scaling of the data point.
PDTS_COMPRESS2NDDERIV	The second derivative between points is stored.
PDTS_DISPLAY	Each logical unit is equivalent to a display pixel. Positive x is to the right; positive y is down.
PDTS_HIENGLISH	Each logical unit is mapped to 0.001 inch. Positive x is to the right; positive y is down.
PDTS_HIMETRIC	Each logical unit is mapped to 0.001 millimeter. Positive x is to the right; positive y is down.
PDTS_LOMETRIC	Each logical unit is mapped to 0.01 millimeter. Positive x is to the right; positive y is down.
PDTS_STANDARDSCALE	The standard scaling metric, equivalent to PDTS_HIENGLISH. Standard recognizers scale to this value.
The following table lists the PDTS_ bit settings. These bit settings can be combined using the bitwise-OR operator.

Constant	Description
PDTS_COMPRESSED	The data is compressed.
PDTS_NOCOLLINEAR	All redundant points removed.
PDTS_NOEMPTYSTROKES	All empty strokes removed.
PDTS_NOOEMDATA	OEM data removed.
PDTS_NOPENINFO	The PENINFO structure has been trimmed from the header.
PDTS_NOTICK	Timing information removed.
PDTS_NOUPPOINTS	All pen-up strokes removed.
PDTS_NOUSER	User information removed.
The following table lists the PDTS_ mask values:

Constant	Description
PDTS_COMPRESSMETHOD	Bits encode the compression scheme that is used.
PDTS_SCALEMASK	Mask scaling bits for hardware information.
For additional information, see the entries for the CompactPenData and MetricScalePenData functions in Chapter 10, "Pen Application Programming Interface Functions."


PDTT_ Pen Data Trimming [New - Windows 95]
 PDTT_ Pen Data Trimming

[New - Windows 95]

PDTT_ values are used as arguments for the CompactPenData function. The following table describes the PDTT_ values:

Constant	Description
PDTT_DEFAULT	Reallocates memory block to fit data; does not trim the data.
PDTT_ALL	Removes PENINFO structure from header, all pen-up points, OEM data, and collinear points.
PDTT_COLLINEAR	Removes coincident and collinear points from the pen data.
PDTT_COMPRESS	Compresses the data without losing any information.
PDTT_DECOMPRESS	Decompresses the data.
PDTT_OEMDATA	Removes all OEM data.
PDTT_PENINFO	Removes PENINFO structure from header.
PDTT_UPPOINTS	Removes all data from pen-up points (points collected when the pen is not in contact with the tablet).
For additional information, see the CompactPenData function in Chapter 10, "Pen Application Programming Interface Functions."


PMI_ Pen Miscellaneous Information [New - Windows 95]
 PMI_ Pen Miscellaneous Information

[New - Windows 95]

The PMI_ values are used as arguments for the GetPenMiscInfo and SetPenMiscInfo functions. The WM_PENMISCINFO message also uses PMI_ values in its wParam parameter.

The following table describes the PMI_ values:

Constant	Description
PMI_BEDIT	Boxed edit information.
PMI_CXTABLET	Width of tablet (in units of 0.001 inch) if present, else the width of the screen.
PMI_CYTABLET	Height of tablet (in units of 0.001 inch) if present, else the height of the screen.
PMI_ENABLEFLAGS	Flags describing whether certain Pen API features are enabled. The flags can be a combination of the following values: PWE_AUTOWRITE   Enable pen functionality where the I-Beam cursor is present.  PWE_ACTIONHANDLES   Enable action handles in controls.  PWE_INPUTCURSOR   Show cursor while writing.  PWE_LENS   Enable pop-up letter guides (that is, the lens).
PMI_INDEXFROMRGB	A standard RGB pen-tip color value from 0 to 0xFFFFFF.
PMI_PENTIP	Address of current pen-tip structure.
PMI_RGBFROMINDEX	An integer index from 0 to 15 for the standard pen-tip color table.
PMI_SAVE	Save settings to file.
PMI_SYSFLAGS	Flags describing which pen system components are loaded. The flags can be a combination of the following values: PWF_RC1   Support available for Pen API version 1.0 Recognition Context (RC) and associated functions.  PWF_PEN   Pen/tablet hardware is present.  PWF_INKDISPLAY   Ink-compatible display driver is present.  PWF_RECOGNIZER   System recognizer is present.  PWF_BEDIT   Boxed edit (bedit) control is available.  PWF_HEDIT   Handwriting edit (hedit) control is available.  PWF_IEDIT   Ink edit (iedit) control is available.  PWF_ENHANCED   Enhanced features, including gesture support and 1 millisecond timing, are available.  PWF_FULL   All components listed above are present.
PMI_SYSREC	Handle to system recognizer, if present.
PMI_TICKREF	Absolute reference time that the system uses to calculate time-stamps for strokes in pen data objects and inksets.
PMI_TIMEOUT	Time-out value to end handwriting input, in milliseconds.
PMI_TIMEOUTGEST	Time-out value to end a gesture, in milliseconds.
PMI_TIMEOUTSEL	Time-out value in milliseconds for press-and-hold gesture. The range of permissible values is 0 to 5000. If press-and-hold has been disabled, this value is 65,535.
For additional information, see the entries for the GetPenMiscInfo and SetPenMiscInfo functions in Chapter 10, "Pen Application Programming Interface Functions."


RCD_ Writing Direction [New - Windows 95]
 RCD_ Writing Direction

[New - Windows 95]

RCD_ values are used in the wRcDirect member of the global RC structure. The RC structure is passed to a version 1.0 recognizer in the lpRC argument of InitRC and informs the recognizer of the writing direction. To set the writing direction differently than the default direction, call SetGlobalRC with the desired RCD_ value in wRcDirect.

Note

RCD_ constants are provided only for compatibility with version 1.0 of the Pen API and will not be supported in future versions.

The writing direction consists of both primary and secondary directions. For example, English is written from left to right (primary) and then down the page (secondary). Chinese is often written from the top down (primary) and then right to left across the page (secondary).

The high byte of the direction indicates primary direction; the low byte indicates secondary direction. A recognizer can choose to ignore this word and support only the natural direction of the given language. The default value is determined by the recognizer.

The following table lists the RCD_ values:

Constant	Description
RCD_DEFAULT	Default value.
RCD_BT	Bottom to top.
RCD_LR	Left to right.
RCD_RL	Right to left.
RCD_TB	Top to bottom.
Example

For example, the value for standard English writing direction is defined as follows:

#define wRcDirectRoman  ((RCD_LR<<8) | RCD_TB)

See Also

RC


RCO_ Recognition Options [New - Windows 95]
 RCO_ Recognition Options

[New - Windows 95]

RCO_ values apply only to recognizers compatible with version 1.0 of the Pen API. They are used in the lRcOptions member of the RC structure, which specifies various options for recognition. RCO_ values can be combined with a logical-OR operator.

Constant	Description
RCO_BOXCROSS	Display a plus sign (+) at center of each box in a bedit control.
RCO_BOXED	Set if the writer is expected to write in boxes and the GUIDE structure contains valid data.
RCO_COLDRECOG	Set in results messages if the result is coming from cold recognition.
RCO_DISABLEGESMAP	Disables gesture mapping during the Recognize function call.
RCO_NOFLASHCURSOR	No flash cursor feedback.
RCO_NOFLASHUNKNOWN	If set in the RC structure and nothing was recognized, the cursor will not momentarily change to a question-mark cursor shape.
RCO_NOHIDECURSOR	If set, doesn't remove cursor while inking.
RCO_NOHOOK	Prevents application-wide and system-wide hooks from being called.
RCO_NOPOINTEREVENT	If set, the RC Manager will not try to recognize a pointer event but will pass on all data to the recog-nizer. This is useful, for example, if the application has installed a shape recognizer so the user can enter dots of ink. If the null recognizer is selected into the RC, RCO_NOPOINTEREVENT is assumed to be set.
RCO_NOSPACEBREAK	If set, indicates that the results passed back from the recognizer should be passed on to the dictionaries without breaking at space boundaries.
RCO_SAVEALLDATA	Saves all the pen data in the RCRESULT structure that is generated by the tablet, including any data for pen-up strokes and optional data such as pressure. By default, only data used by the recognizer is saved. The Microsoft recognizer collects all data from first to last pen-down stroke, including pen-up strokes in between, and any available OEM data for each stroke.
RCO_SAVEHPENDATA	Saves the pen data. If this is set, the recognizer does not delete the data when the application returns from WM_RCRESULT. It is the application's responsibility to free the pen data.
RCO_SUGGEST	If set, the following actions take place: After all dictionaries have been unsuccessfully searched with strings from the symbol graph, each dictionary is called with DIRQ_SUGGEST to allow the diction-aries to make suggestions. If a string is not yet identified by a dictionary, the null dictionary is used to create a symbol string from the symbol graph.
RCO_TABLETCOORD	If set, indicates that the members representing coordi-nate values in the RC structure are in tablet coordi-nates instead of screen coordinates. This can be used to collect recognition data on the portion of the tablet not mapped to the screen.


RCOR_ Tablet Orientation [New - Windows 95]
 RCOR_ Tablet Orientation

[New - Windows 95]

RCOR_ values are used in the wRcOrient member of the global RC structure. The RC structure is passed to a version 1.0 recognizer in the lpRC argument of InitRC and informs the recognizer of the tablet orientation. The recognizer can optionally use the orientation to direct the transformation of tablet coordinates to ideal coordi-nates used for recognition.

Note

RCOR_ constants are provided only for compatibility with version 1.0 of the Pen API and will not be supported in future versions.

The following table lists the RCOR_ values:

Constant	X-coordinate	Y-coordinate
RCOR_NORMAL	X = X'	Y = Y'
RCOR_LEFT	X = yMax - Y'	Y = X'
RCOR_RIGHT	X = Y'	Y = xMax - X'
RCOR_UPSIDEDOWN	X = xMax - X'	Y = yMax - Y'
As with the preceding values, direction is provided as a clue to the recognizer. A recognizer may attempt to identify the direction of writing by itself.

See Also

RC


RCP_ User Preferences [New - Windows 95]
 RCP_ User Preferences

[New - Windows 95]

RCP_ values are used in the wRcPreferences member of the global RC structure. The RC structure is passed to a version 1.0 recognizer in the lpRC argument of InitRC and informs the recognizer of the user preferences.

Note

RCP_ constants are provided only for compatibility with version 1.0 of the Pen API and will not be supported in future versions.

The following table lists the RCP_ values:

Constant	Description
RCP_LEFTHAND	User writes with left hand.
RCP_MAPCHAR	Tells a version 1.0 recognizer to fill in segmentation information in the lpsyc member of the SYG structure. This value cannot be set by the user because there is no Control Panel access to it. RCP_MAPCHAR is used by the Trainer.
See Also

RC


RCRT_ Results Type [New - Windows 95]
 RCRT_ Results Type

[New - Windows 95]

RCRT_ values apply only to recognizers compatible with version 1.0 of the Pen API. They are used in the wResultsType member of the RCRESULT structure, which specifies the type of results as described in the following table:

Constant	Description
RCRT_ALREADYPROCESSED	Set by a hook if the result has already been acted upon. If an application receives a result with this bit already set, it should erase the ink and perform no other pro-cessing. An application-wide hook can set this flag. The Hform sample application demonstrates its use.
RCRT_DEFAULT	Normal return type.
RCRT_GESTURE	Result is a gesture symbol.
RCRT_NORECOG	Nothing recognized; only the data is returned. No recognition was attempted.
RCRT_NOSYMBOLMATCH	Nothing recognized. The ink drawn did not match any enabled symbols.
RCRT_PRIVATE	Recognizer-specific symbol recognized.
RCRT_UNIDENTIFIED	Result contained unidentified results.
Example

The code below shows an example of how to use RCRT_ values:

if ((lpr->wResultsType & (RCRT_NOSYMBOLMATCH | RCRT_ALREADYPROCESSED |

   RCRT_NORECOG | RCRT_PRIVATE ) ) == 0 )

{

// A gesture or character

if (lpr->wResultsType & RCRT_GESTURE)

{

.

.	// Handle Gesture

.

}

else

{

.

.	// Character results

.

}

}

else

{

.	// Handle special cases as necessary.  In general,

.	// should just ignore.  This is what hedits do.

.

}


REC_ Recognition Functions [New - Windows 95]
 REC_ Recognition Functions

[New - Windows 95]

The REC_ constants specify return values from the GetPenHwEventData and GetPenHwData functions. They are also returned from the obsolete functions Recognize, RecognizeData, and ProcessWriting, and as the wParam value of the WM_RCRESULT message. Return values less than REC_DEBUG are provided for debugging purposes only and represent abnormal termination.

Constant	Description
REC_OK	This result message to be followed by other results before Recognize terminates. This is a valid wParam value for WM_RCRESULT, but it can never be the return value for Recognize.
REC_ABORT	Recognition stopped by a call to EndPenCollection with this value. The lpPnt data is not valid.
REC_BADHPENDATA	Returned if HPENDATA cannot be locked or has an invalid header. This value is also returned if HPENDATA has no data in it or if the data is in an incorrect scale or compressed.
REC_BUFFERTOOSMALL	Returned by GetPenHwEventData.
REC_BUSY	Returned if another task is currently performing recognition.
REC_DONE	Returned by RecognizeData upon normal completion.
REC_NA	Function not available.
REC_NOINPUT	Returned by RecognizeData if the buffer contains no data, or returned by Recognize if recognition ended before any data was collected. For example, a pen-down stroke may have occurred outside the bounding rectangle before any data was collected.
REC_NOTABLET	Tablet not physically present.
REC_OOM	Out-of-memory error.
REC_OVERFLOW	Data overflow during execution of the call.
REC_POINTEREVENT	Returned if the user makes contact with the tablet surface and lifts the pen before the pen tip travels a short distance. This value is also returned if the user does a press-and-hold action; that is, the pen makes contact with the tablet and remains in that position for a short period of time. REC_POINTEREVENT informs the application it should begin selection actions rather than inking or recognition. If REC_POINTEREVENT is returned, no WM_RCRESULT message is generated and no ink is displayed.
REC_TERMBOUND	Recognition ended because of a hit test outside the bounding rectangle. The pntEnd member of RCRESULT is filled with the point causing the stop.
REC_TERMEX	Recognition ended because of a hit test inside the exclusion rectangle. The pntEnd member of RCRESULT is filled with the point causing the stop.
REC_TERMOEM	Values greater than or equal to 512 reserved for recognizer-specific termination reasons.
REC_TERMPENUP	Recognition ended on pen up. ThepntEnd member of RCRESULT is filled with the pen-up point that terminated recognition.
REC_TERMRANGE	Recognition ended because the pen left the proximity range.
REC_TERMTIMEOUT	Recognition ended on time-out. (The pen was up con-tinuously for a given amount of time.)


 Debugging Values

All of the values listed in the following table are in the debug version of PENWIN.DLL only. No WM_RCRESULT message is generated if these values are returned by Recognize.

Constant	Description
REC_DEBUG	All debugging return values are less than or equal to this.
REC_ALC	Invalid enabled alphabet.
REC_BADEVENTREF	Returned when the wEventRef member in the RC structure is invalid.
REC_CLVERIFY	Invalid verification level.
REC_DICT	Invalid dictionary parameters.
REC_ERRORLEVEL	Invalid error level.
REC_GUIDE	Invalid GUIDE structure.
REC_HREC	Invalid recognition handle.
REC_HWND	Invalid handle to window to send results to.
REC_INVALIDREF	Invalid data reference parameter.
REC_LANGUAGE	Returned by the recognizer when the lpLanguage member of RC contains a language that is not supported by the recognizer. Call ConfigRecognizer with the WCR_QUERYLANGUAGE subfunction to determine whether or not a particular language is supported.
REC_NOCOLLECTION	Returned by GetPenHwData if collection mode has not been set.
REC_OEM	Error values below REC_OEM (−1024) are specific to the recognizer.
REC_PCM	Invalid lPcm member in RC structure. There is no way for the recognition to end.
REC_PARAMERR	Invalid parameter.
REC_RECTBOUND	Invalid rectangle.
REC_RECTEXCLUDE	Invalid rectangle.
REC_RESULTMODE	Unsupported results mode requested.


SYV_ Symbol Values [New - Windows 95]
 SYV_ Symbol Values

[New - Windows 95]

Each glyph a recognizer can identify has an associated symbol value. It is this value that is returned to the application by the recognizer.

The high-order and low-order words of a symbol value have the following meanings:

High-order word	Low-order word
0	System symbols.
1	ANSI character code.
2	Gestures.
3	Shift character codes (kanji).
4	Shapes.
5	Unicode.
6	Virtual keys.
7-0x7EFF	Reserved for future use.
0x7F00-0x7FFF	Recognizer-specific symbols.
>=0x8000	Character code for given code page. The low 15 bits of the high-order word indicate the code page.
Recognizers for the European market should return symbol values using ANSI and gesture symbol values (ANSI is the native character set for Windows in the European market). For the Japanese market, recognizers can use Shift JIS Level 1 and gestures. When writing a recognizer, bear in mind that symbol values outside these ranges cannot be interpreted by all Windows applications.


 System Symbol Values

The following system symbol values are supported for recognizers:

Constant	Description
SYV_BEGINOR	Begins a list of choices; in the bedit guide, displayed as an opening brace character ({).
SYV_EMPTY	Empty.
SYV_ENDOR	Ends a list of choices. In the bedit guide, displayed as a closing brace character (}).
SYV_NULL	Null terminator.
SYV_OR	Separator for list of choices; in the bedit guide, displayed as a vertical bar (|).
SYV_SOFTNEWLINE	Translated to a space by SymbolToCharacter.
SYV_SPACENULL	Used in a symbol graph to indicate an alternative to a space.
SYV_UNKNOWN	Unrecognized glyph.


 Gesture Symbol Values

All system recognizers are expected to recognize a special set of glyphs used as commands. In the following table, the "Windows Equivalent" column shows the mouse and keyboard equivalents in Windows.

Constant	Value	Description	Windows equivalent
. . .	00−0x00FF	Command gesture given. The low byte specifies which ANSI character was modified by the command gesture.	Nonstandard (usually CTRL+key).
SYV_BACKSPACE	0x00020008	Deletes character under gesture and sets insertion point.	BACKSPACE.
SYV_CLEAR	0x0002FFD5	Clears the selection.	DEL.
SYV_CLEARCHAR	0x0002FFD2	Clears the selection.	DEL.
SYV_CLEARWORD	0x0002FFDD	Deletes word or object under gesture.	Double-click, DEL.
SYV_COPY	0x0002FFDA	Copies selection to Clipboard.	CTRL+INS.
SYV_CORRECT	0x0002FFDF	Corrects selection or word under gesture.	None.
SYV_CONTEXT	0x0002FFD7	Displays a context menu	Right mouse click.
SYV_CUT	0x0002FFDB	Cuts selection and places it on Clipboard.	SHIFT+DEL.
SYV_EXTENDSELECT	0x0002FFD8	For linear selection (text), selects all text between current insertion point and point of extend-selection gesture. For nonlinear selection (objects), adds object under gesture to selection.	SHIFT+mouse click.
SYV_INSERT	0x0002FFD6	Opens the lens to allow text to be inserted.	None
SYV_KKCONVERT	0x0002FFD4	Starts Kana-to-Kanji converter. (Japanese version only.)	N/A
SYV_PASTE	0x0002FFDC	Pastes selection at point indicated by hot spot of paste gesture.	Click (place insertion point) followed by SHIFT+INS.
SYV_RETURN	0x0002000D	Enters carriage-return key.	Click, RETURN.
SYV_SPACE	0x00020020	Adds space character.	Click, SPACEBAR.
SYV_TAB	0x00020009	Enters tab.	Click, TAB.
SYV_UNDO	0x0002FFD9	Undoes previous action.	ALT+BACKSPACE.
SYV_USER	0x0002FFDE	Any circle gesture.	See the following section.


 Circle Gesture Symbol Values

A circle gesture consists of a circled letter, either uppercase or lowercase. The Pen API version 2.0 does not explicitly support circle gestures. They are defined only for application or recognizer use.

The following table lists the SYV_ values for the circle gestures. Intervening values correspond to the letters between "a" and "z".

Constant	Value	Description
SYV_APPGESTUREMASK	0x00020000	Mask value for circle gestures.
SYV_CIRCLELOA	0x000224D0	Lowercase "a" circle gesture.
SYV_CIRCLELOZ	0x000224E9	Lowercase "z" circle gesture.
SYV_CIRCLEUPA	0x000224B6	Uppercase "A" circle gesture.
SYV_CIRCLEUPZ	0x000224CF	Uppercase "Z" circle gesture.


 Selection Symbol Values

The following table lists the SYV_values for selection symbol gestures.

Constant	Value	Description
SYV_SELECTFIRST	0x0002FFC2	Minimum value for section SYVs.
SYV_LASSO	0x0002FFC1	Lasso selection (equivalent to double-click).
SYV_SELECTLEFT	0x0002FFC2	Select text to the left (not supported by the Microsoft Handwriting Recognizer).
SYV_SELECTRIGHT	0x0002FFC3	Select text to the right (not supported by the Microsoft Handwriting Recognizer).
SYV_SELECTLAST	0X0002FFCF	Maximum value for selection SYVs.


 Shape Symbol Values

These values should be used by shape recognizers.

Constant	Value	Description
SYV_SHAPELINE	0x00040001	Shape recognized as a line.
SYV_SHAPEELLIPSE	0x00040002	Shape recognized as an ellipse.
SYV_SHAPERECT	0x00040003	Shape recognized as a rectangle.
SYV_SHAPEMIN	0x00040001	Minimum value for recognized shape SYVs.
SYV_SHAPEMAX	0x00040003	Maximum value for recognized shape SYVs.


 Appendix   Differences Between Versions 1.0 and 2.0 of the Pen Application Programming Interface

Version 2.0 of the Pen Application Programming Interface (API) provides more services — and more avenues for innovation — than did version 1.0. A skimming of Chapters 10 and 11, which identify functions and structures new to version 2.0, indicates the extent of the enhancements added to the API.

However, if you have used version 1.0 of the Pen API, also known as Microsoft Windows for Pen Computing, you will find more than additional functions and other services in this release. Programming philosophy has changed as well. Partic-ularly in the area of recognition, the Pen API now allows greater freedom and responsibility for the handling and interpretation of pen input.

This appendix identifies some of the most important changes and improvements to the Pen API since version 1.0. It would require a number of pages to itemize all the improvements incorporated into version 2.0, which are described throughout this book. The purpose of this appendix is to help the developer familiar with version 1.0 to quickly identify several important areas of version 2.0 that reflect significant change. You will find that version 2.0 of the Pen API opens up new possibilities for collected ink data other than simply passing it to a recognizer.


 Improvements to the bedit Control

The bedit control of version 2.0 of the Pen API has been significantly improved over that of version 1.0. The improvements aim to make text entry more convenient and more intuitive for the user. The following list briefly describes the major improvements:

•	The current insertion point is now indicated by an action handle instead of the caret of version 1.0.

•	The user can select text by dragging the insertion point action handle. Selected text appears in reverse video.

•	The user can move selected text within the control window by dragging it to a new position.

•	Single-line bedit windows can automatically scroll horizontally when the user fills either of the last two visible boxes. The last character remains visible after the scroll to help orient the user. The control window also provides scroll arrows for horizontal scrolling.

•	A single tap near the center of a character displays a list of alternative characters determined by the recognizer. Double-tapping brings up a menu with a list of alternative words that can replace the entire word above the tap. The user selects a letter or complete word by tapping the menu selection.

•	As do other controls in Microsoft Windows 95, bedit controls now provide a context menu from which the user can cut or copy a selection, paste, insert, and so forth.

•	If the user inserts a carriage return in a line of a multiline bedit, text to the right of the carriage return automatically wraps to the next line.

•	Empty cells are marked with a light-gray dot to help distinguish them from spaces.

The EM_LIMITTEXT message has a slightly different effect on bedit controls in version 2.0 of the Pen API. In version 1.0, sending EM_LIMITTEXT to a bedit control window set the number of boxes in the control as specified by the message's wParam parameter. In version 2.0, EM_LIMITTEXT sets the maximum number of bytes of text the control can hold instead of the number of boxes. For more infor-mation about EM_LIMITTEXT, see "The bedit Control" in Chapter 3, "The Writing Process."


 Recognition

Version 2.0 of the Pen API significantly changes the way an application interacts with a recognizer. It allows an application to install multiple recognizers and use them selectively, first creating an HRC object for each recognizer to configure the recognition process. Version 2.0 provides many more recognition functions than did version 1.0, but places the full burden of recognition on the recognizer. All recognition functions are provided by the installed recognizer dynamic-link libraries (DLLs) and not by Windows.

The change in philosophy mentioned at the beginning of this chapter is particulary true with regard to recognition. Recognizers are now more clearly separate from the system and enjoy a corresponding freedom in their implementation. The Pen API defines the interaction between application and recognizer, but stops short of man-dating how a recognizer performs its tasks. The recognizer objects described in Chapter 8, "Writing a Recognizer," are called objects to emphasize that their forms are invisible to the application. The objects are "black box" entities, which the recognizer developer designs without restraint from the system.

For a description of the HRC object and other elements of recognition, see Chapter 5, "The Recognition Process."


 The RC Structure

The core of the recognition process in version 1.0 was the RC data structure. The structure still exists in version 2.0, but it is made obsolete by the HRC object that governs the recognition process. An application can still use an RC structure when calling the obsolete version 1.0 functions ProcessWriting, InitRC, Recognize, and RecognizeData.

The following table lists the members of the RC structure. For each member, the second column describes the corresponding services in version 2.0 of the Pen API. Use this table to update your version 1.0 applications to use the new services. See the reference chapters in Part 2 for descriptions of the functions, messages, and constants cited in the table.

RC member	Equivalent service in Pen API 2.0
hrec	Return value from InstallRecognizer.
hwnd	PE_SETTARGETS message. (See "Step 2: PE_SETTARGETS Message" in Chapter 2.)
wEventRef	Return value from GetMessageExtraInfo. (See sample code in "InputWndProc" in Chapter 7.)
wRcPreferences	ConfigHREC with WCR_GETHAND or WCR_SETHAND.
lRcOptions	Various HRC functions described in Chapters 5 and 8.
lpfnYield	Not applicable in version 2.0.
lpUser	GetPenMiscInfo with PMI_USER. Cannot set new user in version 2.0.
wCountry	GetInternationalHRC or SetInternationalHRC.
wIntlPreferences	ConfigHREC with WCR_GETANSISTATE or WCR_SETANSISTATE.
lpLanguage	GetInternationalHRC or SetInternationalHRC.
rglpdf	Not applicable in version 2.0.
wTryDictionary	Not applicable in version 2.0.
clErrorLevel	Not applicable in version 2.0.
alc	GetAlphabetHRC or SetAlphabetHRC. (See "Specifying an Alphabet Set" in Chapter 8.)
alcPriority	GetAlphabetPriorityHRC or SetAlphabetPriorityHRC. Also ConfigHREC with WCR_GETALCPRIORITY or WCR_SETALCPRIORITY.
rgbfAlc	GetAlphabetHRC or SetAlphabetHRC.
wResultMode	Not applicable in version 2.0.
wTimeOut	GetPenMiscInfo or SetPenMiscInfo with PMI_TIMEOUT.
lPcm rectBound rectExclude	These three members are replaced by PE_GETPCMINFO message. (See "Step 3: PE_GETPCMINFO Message" in Chapter 2.)
guide	GetGuideHRC or SetGuideHRC.
wRcOrient	Not applicable in version 2.0.
wRcDirect	ConfigHREC with WCR_GETDIRECTION or WCR_SETDIRECTION.
nInkWidth rgbInk	These two members are replaced by GetPenMiscInfo and SetPenMiscInfo with PMI_PENTIP.
dwAppParam	Determined by recognizer.
dwDictParam	Not applicable in version 2.0.
dwRecognizer	Determined by recognizer.


 The RCRESULT Structure

The RCRESULT structure provides the means for a version 1.0 recognizer to communicate results to the application. When the recognizer finishes its work, the application receives a WM_RCRESULT message containing a pointer to an RCRESULT structure. It then reads the recognizer's guesses from the structure.

In version 2.0, the RCRESULT structure is made obsolete by the HRCRESULT object. Although they have similar names, do not confuse the two or attempt to draw parallels between them. The HRCRESULT contains the recognizer's results in a format determined by the recognizer. This format most likely has nothing to do with RCRESULT. The application simply calls into the recognizer for recognition results.

For complete descriptions of the version 2.0 recognition functions, see Chapters 5 and 8 and the reference entries in Chapter 10.


 Default Recognition

The version 2.0 application collects, displays, and distributes ink to the recognizer while the user is writing. The Pen API provides convenient and flexible default processing for these tasks in the DoDefaultPenInput function, which completely supersedes ProcessWriting.

Nearly all pen-based applications should take advantage of the capabilities of DoDefaultPenInput. Through a system of messages, the function allows an application to monitor and govern the recognition process, or simply accept the default decisions of DefWindowProc.

For a description of DoDefaultPenInput and the message traffic it generates, read Chapter 2, "Starting Out with System Defaults." To see DoDefaultPenInput in use, refer to the code for the PENAPP sample application presented in Chapter 7, "A Sample Pen Application."


 Recognition Processing

In version 2.0, applications have much greater control over scheduling the recog-nition process. If it does not use DoDefaultPenInput, an application continuously feeds pen data to a recognizer through the AddPenInputHRC function. By calling ProcessHRC, the application can also schedule regular time slots for the recog-nizer to see the input as the user writes.

This real-time recognition processing contrasts with the recognition procedures of version 1.0, in which the application relinquished control to the obsolete Recognize function for the duration of the input session. The version 2.0 recognizer can now "cook" pen input virtually as it arrives from the pen driver, with the application determining how often and how long the recognizer has control.


 Initializing and Closing a Recognizer

The recognition functions InitRecognizer and CloseRecognizer are obsolete in version 2.0 of the Pen API. In their place, two new subfunctions have been added to ConfigRecognizer. When the pen system loads a recognizer, it now calls ConfigRecognizer with the subfunction WCR_INITRECOGNIZER. In response to this call, the recognizer should perform the required initialization tasks formerly conducted by InitRecognizer.

Similarly, the system also calls ConfigRecognizer when it unloads the recognizer, this time with the subfunction WCR_CLOSERECOGNIZER. This call informs the recognizer it is being unloaded and it should conduct any required cleanup operations.

Applications based on version 2.0 do not call ConfigRecognizer. This is because the function has no argument that refers to a specific recognizer of the several that may be currently installed. Instead, version 2.0 applications call the new API function ConfigHREC to configure a recognizer or query for its capabilities. The system determines the intended recognizer and passes the call on to that recog-nizer's ConfigRecognizer function. Thus, a version 2.0 recognizer exports ConfigRecognizer, which an application accesses by calling ConfigHREC.


 Word Lists and Dictionaries

Word lists are new to version 2.0. An application can select from among any number of word lists to help a recognizer verify its guesses. Word-list files must have standard text formatting to allow users to create or modify them with a text editor, but otherwise have no restrictions in size or content.

Dictionaries existed in version 1.0 as DLL files. In version 2.0, a dictionary serves a recognizer invisibly as a large word list. The application has no access to a dic-tionary except to tell the recognizer whether or not to use one. Dictionary files can have any format, but are usually compressed in some manner private to the recog-nizer.

A dictionary is thus a private (and optional) tool of a recognizer. The "system" in the name EnableSystemDictionaryHRC does not refer to the operating system, but simply emphasizes ownership. In this case, "system" means "not application."


 Gestures

Version 2.0 no longer provides explicit support for user-defined gestures. The burden of recognizing and handling new gestures instead falls to the recognizer and application. The Gesture Manager (GESTMAN.EXE) and API function ExecuteGesture do not exist in version 2.0.

The standard set of "circle-letter" gestures remains, however. All version 2.0 edit controls — hedit, bedit, and iedit — respond normally to the gestures listed in the following table. An application or recognizer is free to provide support for any other gesture.

This table lists the gestures available in version 2.0 edit controls. Note that the V-circle and check-mark-circle gestures have identical behavior. The V-circle gesture is provided only to prevent confusion with the check-mark-circle gesture.

Gesture	Name	Action
	Lasso-tap	Select
	X-circle	Cut current selection
	C-circle	Copy current selection
	P-circle	Paste
	Check-mark-circle	Edit/Properties
	V-circle	Edit/Properties
	Caret-circle	Insert text
	M-circle	Display context menu
	D-circle	Clear/Delete
	S-circle	Space
	N-circle	Newline (carriage return)
	T-circle	Tab
	U-circle	Undo


 Action Handles

In version 2.0, edit controls have small icons called action handles. Action handles provide the user a more intuitive and discoverable means for carrying out certain editing tasks than do gestures. With action handles, the user can:

•	Select text.

•	Cut, copy, and paste.

•	Change the insertion point.

•	Drag-and-drop a selection.

•	Access a menu of options.


 On-Screen Keyboard

In version 2.0, the on-screen keyboard is an independent application named SK.EXE, which can be launched in the same way any application is launched in Windows; for example, by using the WinExec() function.

The ShowKeyboard function, which invoked the on-screen keyboard in version 1.0, is still supported but for older applications, but has been modified due to the fact that the on-screen keyboard is a separate application in version 2.0.

The WM_SKB message, available in version 1.0, is no longer sent to top-level windows when the on-screen keyboard changes.


 Timing Information

The new HINKSET object allows an application to refer to stroke data completely or partially by time, rather than by coordinates. The HINKSET object is a tem-poral version of HPENDATA. It sees each stroke as an interval of time instead of a collection of physical points. See "The HINKSET Object" in Chapter 4 for a description of stroke timing and HINKSET.

Stroke timing allows a new characteristic of ink rendering called animation. Through animation, an application can control the speed at which pen data is displayed. For more information, see the description of DrawPenDataEx in Chapter 10, "Pen Application Programming Interface Functions."


 Targeting

An application based on version 2.0 of the Pen API can create multiple windows and writing areas on the screen that simultaneously accept pen input. Targeting allows the application to govern the distribution of input data to the proper window.

For example, a forms application can establish targeting information for each of several controls on the screen. Even if the user writes in the controls in arbitrary order, targeting ensures the pen data arrives at the proper window procedure.

For more information on targeting, see "Step 2: PE_SETTARGETS Message" in Chapter 2, "Starting Out with System Defaults." Also see the reference sections for TARGET and TARGINFO in Chapter 11, "Pen Application Programming Interface Structures."


 HPENDATA Memory Block

The internal structure of the HPENDATA memory block has changed since ver-sion 1.0. As described in "Data Within an HPENDATA Object" in Chapter 4, the stroke header no longer incorporates a STROKEINFO structure. However, to maintain compatibility with version 1.0, the GetPenDataStroke function provides a copy of a STROKEINFO structure for the requested data points.

Since the HPENDATA format may again change in future versions, applications should avoid attempting to read the memory block directly and instead rely on the appropriate HPENDATA functions described in Chapter 4, "The Inking Process."

The PENINFO structure in the block's HPENDATAHEADER has also changed since version 1.0. PENINFO contains a new member, fuOEM, that indicates the type of original equipment manufacturer (OEM) data the HPENDATA object contains.


 Registry Configuration

In version 1.0, the PENWIN.INI file contained system configuration information such as the name of the default recognizer and the time-out value for selection. Version 2.0 removes configuration information from the PENWIN.INI file and instead stores it in the system registry.

For example, the following code fragment sets the fictitious recognizer RECOG1.DLL as the default system recognizer. The code presumes that RECOG1.DLL:

•	Resides in a location where Windows can find it (usually the system subdirectory).

•	Is capable of taking on the role of system recognizer.

For more information about recognizers, see Chapter 8, "Writing a Recognizer." For descriptions of the registry functions RegSetValueEx, RegCreateKey, and RegCloseKey, see the documentation included in the Win32 Software Develop-ment Kit.

    HKEY    hk;             // Key handle returned by RegCreateKey

        .

        .

        .

    // Open (or create) the registry for the parent key

    if ((lRes = RegCreateKey( HKEY_LOCAL_MACHINE,

                              (LPSTR)REGSTR_PATH_CONTROL,

                              &hk )) == ERROR_SUCCESS)

    {

        // If successful, set "RECOG1.DLL" as the system recognizer

        RegSetValueEx( hk, REGSTR_VAL_PEN_RECOG, NULL, REG_SZ,

                    (LPBYTE)(LPSTR)"RECOG1.DLL", 0 );

        // Close it

        RegCloseKey( hk );

    }

The PENREG.H header file defines values pertaining to the system registry. Note that, generally, applications should not change the system configuration, relying instead on the user to do so through the Control Panel.

For information on retrieving and setting other pen system parameters, see the reference entries for GetPenMiscInfo and SetPenMiscInfo in Chapter 10, "Pen Application Programming Interface Functions."


 Appendix   Using the 32-Bit Pen Application Programming Interface

This appendix describes the 32-bit pen services provided by the PENWIN32.DLL and PKPD32.DLL libraries. With some exceptions, these dynamic-link libraries (DLLs) offer Win32™-based applications the same pen-based support as the 16-bit libraries PENWIN.DLL and PKPD.DLL without requiring the intermediate steps of thunk conversions.

The services not supported by the 32-bit Pen Application Programming Interface (API) consist mainly of outdated functions no longer required in version 2.0. These outdated functions are supported in the 16-bit Pen API only to maintain backward compatibility with version 1.0. They will not be supported in future versions.

To enable 32-bit pen services, an application must be created in a 32-bit environ-ment — that is, the compiler, linker, libraries, and header files must be of 32-bit type. Before including pertinent header files, the application must define the constant WIN32 as shown here:

#define    WIN32

#include   <windows.h>

#include   <penwin.h>

A 32-bit application links to the pen system libraries in the same way it links to any other Windows library, with either of the following methods:

•	Link to the import library PKPD32.LIB (not recommended for PENWIN32.LIB) , or

•	Explicitly load PENWIN32.DLL and PKPD32.DLL with the LoadLibrary function. After loading the libraries, the application must call GetProcAddress to obtain the address of each Pen API function it intends to use. Before termin-ating, the application should call FreeLibrary to unload the libraries from memory.

The first method should normally be used to link functions in PKPD32.LIB. This method can be used for functions in PENWIN32.LIB if it is known for certain that the application will always be run on systems that have pen services installed, in which case the application should test for the existence of pen services at startup and exit if not found.

The second method should be used for PENWIN32.DLL functions when it is anticipated that the application may be run on systems where pen services are not installed. The reason for not linking PENWIN32.LIB is to prevent the application from loading PENWIN32.DLL on a system that has not loaded pen services at startup. This could happen, for example, on a computer that has PENWIN32.DLL on the path but has not installed pen services. Loading PENWIN32.DLL dynamic-ally does not sufficiently start pen services and errors are likely to occur.

In a 32-bit application, the call

GetSystemMetrics( SM_PENWINDOWS );

returns the handle of PENWIN32.DLL. This DLL makes available some of the same resources (such as cursors) provided by the 16-bit PENWIN.DLL library.


 32-Bit Functions

The following table lists the functions supported by the 32-bit Pen API. The syntax for each function remains the same as for 16-bit applications. For the description and syntax of each function, refer to Chapter 10, "Pen Application Programming Interface Functions."

The table also uses an asterisk (*) to identify the functions PKPD32.DLL exports. These functions are always available to 32-bit applications running with Windows 95, regardless of whether the PENWIN32.DLL file is present. For more informa-tion, see "Pen Kernel Functions" in Chapter 9, "Summary of the Pen Application Programming Interface."

AddInksetInterval*

AddPenDataHRC

AddPenInputHRC

AddPointsPenData*

AddWordsHWL

BoundingRectFromPoints*

CharacterToSymbol

CompressPenData*

ConfigHREC

ConfigRecognizer

CorrectWriting

CorrectWritingEx

CreateCompatibleHRC

CreateHWL

CreateInkset*

CreateInksetHRCRESULT

CreatePenData

CreatePenDataEx*

CreatePenDataHRC

CreatePenDataRegion*

DestroyHRC

DestroyHRCRESULT

DestroyHWL

DestroyInkset*

DestroyPenData*

DoDefaultPenInput

DPtoTP

DrawPenDataEx*

DuplicatePenData*

EnableGestureSetHRC

EnableSystemDictionaryHRC

EndPenInputHRC

ExtractPenDataPoints*

ExtractPenDataStrokes*

GetAlphabetHRC

GetAlphabetPriorityHRC

GetAlternateWordsHRCRESULT

GetBoxMappingHRCRESULT

GetBoxResultsHRC

GetGuideHRC

GetHotspotsHRCRESULT

GetHRECFromHRC

GetInksetInterval*

GetInksetIntervalCount*

GetInternationalHRC

GetMaxResultsHRC

GetPenAppFlags

GetPenAsyncState

GetPenDataAttributes*

GetPenDataInfo*

GetPenInput

GetPenMiscInfo

GetPenResource

GetPointsFromPenData*

GetResultsHRC

GetStrokeAttributes*

GetStrokeTableAttributes*

GetSymbolCountHRCRESULT

GetSymbolsHRCRESULT

GetVersionPenWin

GetWordlistCoercionHRC

GetWordlistHRC

HitTestPenData*

InsertPenData*

InsertPenDataPoints*

InsertPenDataStroke*

InstallRecognizer

IsPenEvent

MetricScalePenData*

OffsetPenData*

PeekPenInput

PenDataFromBuffer*

PenDataToBuffer*

ProcessHRC

ReadHWL

RedisplayPenData*

RemovePenDataStrokes*

ResizePenData*

SetAlphabetHRC

SetAlphabetPriorityHRC

SetBoxAlphabetHRC

SetGuideHRC

SetInternationalHRC

SetMaxResultsHRC

SetPenAppFlags*

SetPenMiscInfo

SetResultsHookHREC

SetStrokeAttributes*

SetStrokeTableAttributes*

SetWordlistCoercionHRC

SetWordlistHRC

StartInking

StartPenInput

StopInking

StopPenInput

SymbolToCharacter

TargetPoints

TPtoDP

TrainHREC

TrimPenData*

UnhookResultsHookHREC

UninstallRecognizer

WriteHWL


 32-Bit Messages

The 32-bit Pen API does not support all the 16-bit messages described in Chap-ter 12, "Pen Application Programming Interface Messages." This section lists the messages that are supported by the 32-bit Pen API. Although most 32-bit messages behave the same way as 16-bit messages, certain WM_PENEVENT submessages behave differently.


 WM_PENEVENT Submessages

The following submessages of WM_PENEVENT require different treatment in 32-bit applications:

PE_BEGININPUT

PE_BUFFERWARNING

PE_PENDOWN

PE_PENMOVE

PE_PENUP

PE_TERMINATED

PE_TERMINATING

In 16-bit applications, these submessages store different values in the high-order and low-order words of their lParam:

•	wParam = PE_ submessage number

•	LOWORD( lParam ) = event reference or termination code

•	HIWORD( lParam ) = HPCM handle

This scheme is not possible in Win32-based applications because lParam must contain a single 32-bit handle; therefore, the parameters for the submessages listed above are arranged differently in the 32-bit Pen API:

•	LOWORD( wParam ) = PE_ submessage number

•	HIWORD( wParam ) = event reference or termination code

•	lParam = HPCM handle

To extract data from the parameters, use the following macros defined in the PENWIN.H header file. These macros render the differences in the parameters transparent to an application because they automatically adjust for 16-bit or 32-bit type of programs:

Macro	Description
HpcmFromWpLp	Retrieves HPCM handle returned from StartPenInput. If the application calls DoDefaultPenInput, that function calls StartPenInput internally.
EventRefFromWpLp	Retrieves event reference value for session returned from GetMessageExtraInfo. Both DoDefaultPenInput and StartPenInput take this value as their second argument.
TerminationFromWpLp	Retrieves a PCM_ value indicating the reason for termination from the PE_TERMINATED and PE_TERMINATING submessages.
SubPenMsgFromWpLp	Retrieves PE_ submessage value.
The macros take both wParam and lParam as arguments and automatically return the desired value for both 16-bit and 32-bit applications. For example:

HPCM      hpcm;           // HPCM handle created by StartPenInput

LONG      lInfo;          // Return value from GetMessageExtraInfo

int       iRet;           // Error code

.

.

.

case WM_LBUTTONDOWN:

lInfo = GetMessageExtraInfo( );

if (IsPenEvent( msg, lInfo ))

{

iRet = DoDefaultPenInput( hwnd, LOWORD(lInfo) );

}

.

.

.

case WM_PENEVENT:

switch( SubPenMsgFromWpLp( wParam ) );

{

case PE_PENDOWN:

hpcm  = HpcmFromWpLp( wParam, lParam );

//

// Note lInfo and EventRefFromWpLp( wParam, lParam )

// contain the same event reference value.

//


 List of 32-Bit Window Messages

The following table lists the WM_ window messages and corresponding sub-messages supported by the 32-bit Pen API (submessages available in the Japanese version are indicated by an asterisk):

WM_ messages	Submessages
WM_PENMISCINFO WM_PENCTL	* HE_CANCELCONVERT HE_CHAROFFSET HE_CHARPOSITION HE_DEFAULTFONT HE_ENABLEALTLIST * HE_FIXKKCONVERT HE_GETBOXLAYOUT * HE_GETCONVERTRANGE HE_GETINFLATE HE_GETINKHANDLE* HE_GETKKCONVERT * HE_GETKKSTATUS HE_GETUNDERLINE HE_HIDEALTLIST * HE_KKCONVERT * HE_PUTCONVERTCHARHE_SETBOXLAYOUT * HE_SETCONVERTRANGE HE_SETINFLATE HE_SETINKMODE HE_SETUNDERLINE HE_SHOWALTLIST HE_STOPINKMODE
WM_ messages	Submessages
WM_PENMISC	PMSC_BEDITCHANGE PMSC_GETHRC PMSC_GETINKINGINFO PMSC_GETPCMINFOPMSC_GETSYMBOLCOUNT PMSC_GETSYMBOLS PMSC_INKSTOP * PMSC_KKCTLENABLE PMSC_LOADPW * PMSC_PENUICHANGE PMSC_SETHRC PMSC_SETINKINGINFO PMSC_SETPCMINFO PMSC_SETSYMBOLS * PMSC_SUBINPCHANGE
WM_CTLINIT	CTLINIT_BEDIT CTLINIT_HEDIT CTLINIT_IEDIT
WM_PENEVENT	PE_BEGINDATA PE_BEGININPUT PE_BUFFERWARNING PE_ENDDATA PE_ENDINPUT PE_GETINKINGINFO PE_GETPCMINFO PE_MOREDATA PE_PENDOWN PE_PENMOVE PE_PENUP PE_RESULT PE_SETTARGETS PE_TERMINATED PE_TERMINATING


 List of 32-Bit iedit Control Messages

The following table lists the IE_ messages available for iedit controls in 32-bit applications:

IE_CANUNDO

IE_DOCOMMAND

IE_EMPTYUNDOBUFFER

IE_GETAPPDATA

IE_GETBKGND

IE_GETCOMMAND

IE_GETCOUNT

IE_GETDRAWOPTS

IE_GETERASERTIP

IE_GETFORMAT

IE_GETGESTURE

IE_GETGRIDORIGIN

IE_GETGRIDPEN

IE_GETGRIDSIZE

IE_GETINK

IE_GETINKINPUT

IE_GETINKRECT

IE_GETMENU

IE_GETMODE

IE_GETMODIFY

IE_GETNOTIFY

IE_GETPAINTDC

IE_GETPDEVENT

IE_GETPENTIP

IE_GETRECOG

IE_GETSECURITY

IE_GETSEL

IE_GETSELCOUNT

IE_GETSELITEMS

IE_GETSTYLE

IE_SETAPPDATA

IE_SETBKGND

IE_SETDRAWOPTS

IE_SETERASERTIP

IE_SETFORMAT

IE_SETGRIDORIGIN

IE_SETGRIDPEN

IE_SETGRIDSIZE

IE_SETINK

IE_SETINKINPUT

IE_SETMODE

IE_SETMODIFY

IE_SETNOTIFY

IE_SETPENTIP

IE_SETRECOG

IE_SETSECURITY

IE_SETSEL

IE_UNDO


 Appendix   Modifying the SYSTEM.INI File

This appendix describes the settings used in the SYSTEM.INI. The SYSTEM.INI file contains all of the editable information used by the Pen Application Program-ming Interface (API). All other system information concerning the Pen API version 2.0 is maintained in the Windows 95 system registry and will not require modifica-tion except by using the Control Panel Pen icon after Pen Services for Windows 95 is installed.

It is also unlikely that you will manually edit the pen entries in SYSTEM.INI in the Windows 95 environment. A setup information file (PENWIN.INF) provided by Microsoft contains the script that Windows 95 Setup uses to install Pen Services for Windows 95 as an optional system component. This script adds the entries shown in the table below to the SYSTEM.INI file. The one SYSTEM.INI entry that you may want to edit manually after Pen Services is installed is the level of non-critical errors reported. For this, you will have to manually edit the PenWinErrors entry in the [boot] section of SYSTEM.INI, using one of the values shown in the table below.

In versions of Windows previous to Windows 95, pen services were removed from a system by manually editing the SYSTEM.INI file and deleting the entries shown in the table below. This should not be done with Windows 95. Use the Control Panel Add/Remove Programs icon to remove Pen Services for Windows 95. This will automatically delete all the Pen Services entries from SYSTEM.INI.

The following table lists the pen-related entries for SYSTEM.INI

SYSTEM.INI Entry Made at Installation Time	Description
[boot]	Section name.
drivers=pen penwindows	Defines installable drivers.
PenWinErrors=1	Determines the level of non-critical errors displayed. 0 = show no errors or warnings. 1 = show errors only. 2 = show errors and warnings.
[drivers]	Section name.
pen=penc.drv	Sets the pen driver.
penwindows=penwin.dll	Pen API library.


 Appendix   Accessing the Pen Device Driver

There are no specific functions in the Pen Application Programming Interface (API) for pen driver use. Instead, the pen driver functionality is implemented with install-able driver messages.

The pen driver is a 16-bit installable driver in the Microsoft Windows 95 operating system. All communication with an installable driver is through driver messages. A 16-bit application can send a message to the pen driver with the Windows API SendDriverMessage function.

Because a call to SendDriverMessage must originate from a 16-bit virtual machine, 32-bit applications cannot use SendDriverMessage to send messages directly to the pen driver. To communicate with the pen driver, a 32-bit application must provide its own 16-bit dynamic-link library (DLL) to "thunk" calls to SendDriverMessage.

The installable portion of the pen driver may not exist in future versions of Win-dows. For this reason, an application should not query for device information directly from the driver unless necessary. Instead, an application should get hardware information about an HPENDATA object by calling GetPenDataInfo or GetPenDataAttributes. These functions can apprise an application of various hardware characteristics (such as sampling rate) current when collecting the HPENDATA.


 Opening the Pen Driver

Before sending a driver a message, an application must first obtain a handle to the driver with the Windows OpenDriver function. The following code demonstrates this:

HDRVR	hDrvPen;

.

.

.

hDrvPen = OpenDriver( "pen", NULL, NULL );

if( hDrvPen == NULL )

{

// The pen driver does not exist.

// Either display an error message and exit,

// or continue to function as a pen-unaware application.

}

As an example of how to send the driver messages, the following code uses the pen driver message DRV_SetPenSamplingRate to set the sampling rate to 200 points per second. A later segment of code then queries the driver to get relevant pen infor-mation.

WORD	wOldRate;

wOldRate = SendDriverMessage( hDrvPen,                 // Driver handle

                              DRV_SetPenSamplingRate,  // Message

                              200,                     // New rate in Hz

                              NULL );                  // Not applicable

.

.

.

// Get information about the pen driver

PENINFO  pi;

BOOL     PenHardwareExists;

fPenHardwareExists = SendDriverMessage( hDrvPen,

                                        DRV_GetPenInfo,

                                        (DWORD)(LPPENINFO)&pi,

                                        NULL );

When finished, an application must close the handle to the installable driver with the CloseDriver function, as shown here:

CloseDriver( hDrvPen, NULL, NULL );


 Pen Driver Return Values

All the values that can be returned by the Pen Driver in response to a message are listed in the table below. These return value constants are defined in PENDRV.H.

Return Value	Description
DRV_SUCCESS	The message request was completed successfully.
DRV_FAILURE	The message request was attempted, but was not completed successfully.
DRV_BADPARAM1	The message request was not attempted because the first parameter in the message was invalid.
DRV_BADPARAM2	The message request was not attempted because the second parameter in the message was invalid.
DRV_BADSTRUCT	The message request was not attempted because a message parameter that must point to a structure was not pointing to a valid structure of the required type. For example, a message parameter that should point to a PENINFO structure does not point to a writeable block of memory large enough to contain a PENINFO structure.


 Pen Driver Messages

The following table describes the pen driver messages an application can use, the parameters that must be provided with each message, and the message return values.

Pen driver message	Meaning	Parameters	Return value
DRV_Configure	Requests the driver to display a configuration dialog box.	lParam1 LOWORD is the handle to a window that will own the dialog box; lParam2 is 0.	Returns DRV_SUCCESS or, if the window handle is invalid, returns DRV_FAILURE.
DRV_GetCalibration	Instructs the driver to  fill a CALBSTRUCT structure with the cur-rent calibration settings, including size and off- set values.	lParam1 is a far pointer to a CALBSTRUCT structure to be filled; lParam2 is 0.	Returns DRV_SUCCESS or DRV_FAILURE if the installed tablet does not support re calibration. DRV_BADPARAM1 is returned if lParam1 is invalid.
DRV_GetName	Reports the name of the pen hardware.	lParam1 LOWORD is the length of the name buffer; lParam2 is a LPSTR pointer to the name buffer.	If successful, returns the number of characters copied into the name buffer, which is the number of characters in the driver name plus 1 (the string null termina-tion character is copied into the buffer).  Otherwise, returns DRV_BADPARAM1 because provided buffer length is insufficient or DRV_BADPARAM2 because the provided memory block is not a writeable block of the specified size.
DRV_GetPenInfo	Fills in the PENINFO structure pointed to by the message's lParam1 parameter with the current pen parameters. If lParam1 is set to NULL, the driver checks for the presence of a pen tablet only.	lParam1 is a far pointer to a PENINFO structure to be filled; lParam2 is 0.	Returns DRV_SUCCESS or DRV_FAILURE if no pen device is currently connected. DRV_BADPARAM1 is returned if the provided block of memory is not writeable or not large enough to contain a PENINFO structure.
DRV_GetPenSamplingRate	Returns the current sampling rate.	lParam1 is 0; lParam2 is 0.	LOWORD contains the current sampling rate.
DRV_GetVersion	Reports the Pen API version number the driver supports and the pen packet size.	lParam1 is 0; lParam2 is 0.	HIWORD contains the pen packet size in bytes. Within the LOWORD, HIBYTE contains the minor version number, LOBYTE is the major version number.
DRV_PenPlayBack	Sends an array of recorded pen packets  to the driver, which the driver then sends back  to the system as though receiving the packets  in real time from the device.	lParam1 is a far pointer to an array of pen packets to be played through the system; lParam2 LOWORD is the number of pen packets to play back, HIWORD is 0.	If successful, returns 1; if failure, returns a value less than 1.
DRV_PenPlayStart	Informs the pen driver  of the format of the  pen packet data it will receive after it receives the next DRV_PenPlayBack message. The driver  does not begin sending pen packets into the system until it receives the DRV_PenPlayBack message.	lParam1 is a far pointer to a DWORD that is updated when the driver is done playing back pen packets; lParam2 is either 0 or 1 and specifies the format of the pen packets passed to the driver (0 means version 1.0 packets and 1 means version 2.0 packets).	Returns DRV_SUCCESS or DRV_FAILURE if the pen system is already  in playback mode.
DRV_PenPlayStop	Forces the driver out of playback mode.	lParam1 is 0; lParam2 is 0.	Always returns DRV_SUCCESS (the pen driver was in play-back mode and the playback mode was successfully stopped  or the pen driver was already out of playback mode).
DRV_Query	Returns whether or not the version 2.0 pen driver supports the specified message.	lParam1 LOWORD specifies the message queried about; lParam2 is 0.	Returns DRV_SUCCESS if the message is supported  or DRV_FAILURE if it is not.
DRV_QueryConfigure	Returns whether or not the driver can provide a configuration dialog box.	lParam1 is 0; lParam2 is 0.	Returns DRV_SUCCESS if the driver provides a configuration dialog  box or DRV_FAILURE if it does not.
DRV_SetCalibration	Sets the tablet calibration.	lParam1 is a far pointer to a CALBSTRUCT structure that describes the new calibration parameters the pen  driver must use; lParam2 is 0.	Returns DRV_SUCCESS or DRV_FAILURE if the tablet does not sup- port calibration. DRV_BADPARAM1  is returned if lparam1  is not a pointer to a CALBSTRUCT structure.
DRV_SetPenSamplingDist	Sets the minimum pen sampling distance. Successive points less than the given distance do not generate new points. The distance is defined in raw tablet coordinates as the maximum of the change in x and y. The default distance is 0, which means that all pen events generate new events. A pen driver does not have to simulate non zero sampling distances. An application must use the DRV_GetPenInfo driver message to determine the actual sampling distance set. Pressing or releasing a pen barrel button gen-erates a new event, even if the pen does not move.	lParam1 HIWORD is 0; lParam1 LOWORD is a new sampling distance; lParam2 is 0.	If successful, HIWORD contains 0; LOWORD contains the previous sampling distance. Otherwise, returns DRV_FAILURE.
DRV_SetPenSamplingRate	Sets the pen sampling rate in samples per second.	lParam1 HIWORD is 0; lParam1 LOWORD is a new sampling rate; lParam2 is 0.	If successful, HIWORD contains 0; LOWORD contains the previous sampling rate. Otherwise, returns DRV_FAILURE.
The calibration driver messages use the CALBSTRUCT structure defined as follows:

typedef struct

{

int  wOffsetX;

int  wOffsetY;

int  wDistinctWidth;

int  wDistinctHeight;

} CALBSTRUCT, FAR * LPCALPSTRUCT;

The wOffsetX and wOffsetY members are the amount in tablet coordinates that need to be added to the x- and y-coordinate values returned by the hardware for proper calibration. The wDistinctWidth and wDistinctHeight members have the same meaning as in the PENINFO structure.


BLANK PAGE

IMPORTANT: This text will appear on screen, but will not print on a PostScript printer.

This page should be the last one in this file; it was inserted by running the InsertBlankPage macro.

Do not type any additional text on this page!


Glossary_fred_1525
 Glossary

A

action handle

A small icon provided in edit controls that facilitates an editing tasks such as dragging or insertion.

B

baseline

An imaginary horizontal line on which handwritten text rests. Analogous to the lines of lined notebook paper.

C

comb

A form of writing guide, such as those used in many common forms and questionnaires, consisting of a horizontal line with spaced tick marks. The guide gets its name from the resemblance of the tick marks to the teeth of a comb. The user writes in a comb guide with individual characters separated by the tick marks.

confidence level

A value assigned by a recognizer to indicate its degree of certainty in the results of a recognition. For example, in recognizing the word "clear," a recognizer assigns a confidence level to each of the five letters and can also assign a confidence level to the entire word. Word lists and dictionaries can influence confidence levels. See also recognizer.

D

dictionary

A list of words or phrases private to a recognizer. A recognizer can use its dictionaries to verify recognition guesses, as directed through the EnableSystemDictionary

G

gesture

A predefined pen motion that signifies some desired action, such as a "lasso" to select or an X to delete. See also lasso.

H

hook

A callback function provided by an application that receives certain data before the normal recipient of the data. The hook function can thus examine or modify the data before passing it on.

hot spots

Critical points on symbols, particularly gestures, identified by a recognizer during recognition. See also gesture, recognizer, symbol.

I

ink

(1) A trail of colored pixels left on the screen that marks the path of the pen's motion. (2) Input data generated by the moving pen; pen data.

inkset

An object that maps data points to time intervals. The points recorded in an inkset object may describe one or more strokes. See also stroke.

irreversible compression

A data-compression technique that produces a high degree of compression, but at the cost of lost information. After uncompression, the pen data can be redisplayed but recognition accuracy may be reduced. See also reversible compression.

L

lasso

A gesture formed by circling a section of text or other displayed data. See also gesture.

lens

A standard Windows pen interface dialog box that offers an on-screen keyboard or letter guides and is used for entering and editing text.

lossless compression

See reversible compression.

lossy compression

See irreversible compression.

O

OEM data

Data about pen pressure, angle, height, and other aspects of pen input that is collected in addition to data points. The specific OEM data collected depends on the hardware and the data it reports.

on-screen keyboard

(1) An image of a keyboard displayed on the screen. (2) The applet (Screen Keyboard or SKB) that displays the image. The user "types" on the on-screen keyboard by pressing the pen on the desired keys, as though typing on a real keyboard.

P

packet

A collection of pen data sent by the pen driver at a frequency determined by the sampling rate. Each packet contains the current coordinates of the pen, the time, and, optionally, other information. Collectively, the packets represent a digitized history of the pen's movement. See also sampling rate.

pen collection mode

The system state in which pen movement generates data, instead of being interpreted as mouse movement. Also known as input session.

pen-down stroke

Data points collected while the pen is in contact with the tablet. Together, these points comprise a stroke. See also pen state, pen tip transition, pen-up points, proximity stroke.

pen packet

See packet.

pen state

The condition of the pen relative to the tablet surface — either up or down, depending on whether the pen is in contact with the tablet.

pen tip transition

The act of touching a pen to or lifting the pen from the tablet surface. The former begins a pen-down stroke, while the latter ends a pen-down stroke and begins a pen-up stroke. See also stroke, proximity stroke.

pen-up stroke

Data points received when the pen is not in actual contact with the tablet, but near enough for the tablet to sense movement. Together, these points comprise a proximity stroke. See also pen-down points, pen state, pen tip transition, proximity stroke.

proximity stroke

A stroke formed while the pen is near but not on the tablet surface. Also called "pen-up stroke." Not all pen tablets can detect proximity strokes. See also pen tip transition, pen-up points, stroke.

R

real time

In the context of pen-based computing, real time means "while the pen is moving."

recognition function

One of the 43 Pen Application Programming Interface (API) functions exported by a recognizer dynamic-link library. See also recognizer.

recognizer

A dynamic-link library of functions that collectively serve to recognize ink data as characters, numerals, words, foreign script, or other symbols.

reentrancy

The condition in which a function is interrupted during execution and restarted from its beginning in response to another caller.

reversible compression

A data-compression technique that loses no information, so data can be redisplayed and recognized with no loss of accuracy after uncompression. See also irreversible compression.

S

sampling rate

The frequency at which the pen driver sends packets to the pen system. A typical sampling rate is 100 − 120 packets per second, but does not necessarily equal the rate of hardware interrupts generated by the pen tablet. See also packets.

Screen Keyboard

See on-screen keyboard.

SKB

See on-screen keyboard.

stroke

The pen data generated between two pen tip transitions. For example, when the pen touches the tablet (pen down), all data generated as the pen moves comprises a pen-down stroke until the pen leaves the tablet. If the tablet can sense proximity strokes, the pen movement above the tablet surface forms a separate pen-up stroke until the pen either leaves the tablet's range of sensitivity or touches down again. Thus, in noncursive printing, the letter "c" is formed as a single stroke while the letter "E" requires several pen-down strokes separated by pen-up strokes. See also pen-down points, pen tip transitions, pen-up points, proximity strokes.

symbol

An element interpreted by a recognizer from raw pen data. For example, the default system recognizer sees an individual letter or numeral as a symbol. A word is thus a string of symbols. A recognizer for cursive writing, however, may see an entire word as a single symbol without distinguishing each letter of the word. See also recognizer.

symbol correspondence

A map of the ink data that forms a recognized symbol. See also symbol element.

symbol element

An SYE structure containing a symbol value, its confidence level, and an identification of the ink data that forms the symbol. See also confidence level, symbol value.

symbol value

A numerical value that represents a recognized character or set of characters. A symbol value is internal to the recognizer and by itself has little meaning to the application. To translate a symbol value to a character such as a letter or numeral, an application must call the SymbolToCharacter function.

T

target

A window or writing area that receives pen input data.

trainer

An application that trains a recognizer. The trainer application may operate in the background, which is known as "passive training," or be activated by the user, which is "active training." See also recognizer, training.

training

The process used to update a recognizer's database so that it better reflects the individual style and writing characteristics of a particular user, thus increasing the recognizer's accuracy in handwriting interpretation. See also recognizer, trainer.


 Programmer's Guide to Pen Services for Microsoft® Windows® 95 (Addendum)

This addendum to the Programmer's Guide to Pen Services for Microsoft Windows 95 contains updated information intended for international application development, particularly for Japanese pen-based applications. The changes listed in this addendum are divided by chapter and appendix.


 Introduction

•	The last sentence of first paragraph should read as follows:

Following the reference, a number of appendixes provide information about the differences between versions 1.x and 2.0 of the Pen API, the 32-bit pen services, and more.


 Organization

•	In the table describing the parts of the book, note that the title of Appendix A should refer to Versions 1.x and 2.0 rather than 1.0 and 2.0.


 Books and Articles for Further Reading

•	The description of Ray Duncan's article, "Power Programming," in PC Magazine, should refer to version 1.x of the Pen API, not version 1.0.


 Chapter 1  Overview of the Pen Application Programming Interface

•	Note the version change in the final introductory paragraph:

The architecture of version 2.0 of the Pen API remains similar to version 1.x, but its style and design differ considerably. Even if you have worked with version 1.x, you should read this chapter to understand the shift in programming philosophy in version 2.0.


 Architecture of the Pen API

•	Note the version change in this paragraph from the "Windows" section.

In version 1.x of Pen Windows, the application was required to call RegisterPenApp in order to tell the system to convert all edit controls to handwriting edit (hedit) controls. With Pen API version 2.0, however, this is not necessary; all edit controls in applications are automatically converted. If the application is version-stamped as a Windows 95-based application, the conversion is automatic; otherwise, applications version-stamped as Windows 3.1-based applications require the call to RegisterPenApp that was required for Pen Windows, version 1.x.

•	Information about handwriting recognizers has been added to this paragraph in the "Recognizer" section.

Although many recognizers may be available to an application, only one serves as the system default recognizer. This is the recognizer that Windows automatically installs and calls by default. To use other recognizers, an application must first specifically install them. (For information about how to install multiple recognizers, see Chapter 5, "The Recognition Process.") The Microsoft Handwriting Recognizer (GRECO.DLL in US, RODAN.DLL in Japan) is provided as the default system recognizer on most OEM tablet installations of Microsoft pen services. GRECO.DLL recognizes all European letters, numerals, and punctuation, with emphasis on English, French, and German. RODAN.DLL recognizes Kanji, Kana, and other Japanese characters. An application can set up a different system recognizer by identifying the new file in the Windows registry. Appendix A explains how to set up a new default recognizer.

•	The following section was added at the end of the "Recognizer" section.


 	IME (Input Method Editor, for converting Kana to Kanji)

In Japanese Pen Services 1.1 (for Windows 3.1) special extensions to the system IME were required to convert handwritten characters to Kanji. For Windows 95, the IME has become standardized as a system DLL, with a new, extended API set. No special API set is required for use with handwriting input.

Although the IME shipped with Windows 3.1 for Pen may be used in Windows 95, it cannot be used to convert handwritten characters into Kanji. Some of the original 1.1 Pen APIs used for Kana to Kanji conversion have been updated, and remain backwardly compatible, and some new APIs have been added. For more information, see Chapter 10, "Pen Application Programming Interface Functions."


 Chapter 2  Starting Out with System Defaults


 Pen-Unaware Applications

•	This paragraph was added as the last in the section.

In Japan, these applets are combined into a single application called the Data Input Window (PENSKJ.EXE). In addition, an applet to set system recognition priorities (Tool Palette, PENTPJ.EXE) and an applet to train Japanese characters (Trainer, PENTRJ.EXE) are also provided.


 Chapter 3  The Writing Process

•	The second introductory paragraph has been changed, as follows:

The writing process includes the various ways a user can write input to a pen-based application. These involve not only writing words and scribbling figures with a pen, but also gesturing with predefined pen movements and tapping an on-screen keyboard or Data Input Window.

•	The following Note has been added as the final item in "The hedit Control" section.

Note  The Microsoft Japanese Handwriting Recognizer (RODAN.DLL) does not support "free input" into hedit controls. An application should either use a BEDIT control or provide access to the Data Input Window—with a Lens button, for example.

•	Figure 3.1 has been renumbered as 3.1a, and a new piece of art (Figure 3.1b) has been added.

Japanese characters typically use large, separated boxes, often with a small cross at the center of each as a writing aid:

•	The version number in the first sentence of the third paragraph in the "bedit Control Messages"section has been changed.

The EM_LIMITTEXT message deserves special mention because it has changed slightly from version 1.x of the Pen API.

•	In the same section, a final bulleted item has been added to the ending list.

•	If limiting the text splits a double-byte character, the whole character is discarded.


 The On-screen Keyboard

•	The following paragraph has been added after the second paragraph.

In Japan, the ShowKeyboard API has been replaced by the CorrectWritingEx function, which displays the Data Input Window.


 Chapter 4  The Inking Process

•	Note the version change in this paragraph from the "Stroke Headers" section of "Data Within an HPENDATA Object."

As Figure 4.1 shows, a stroke header prefaces each collection of pen coordinates that make up a single stroke. Note that the structure of the stroke header in version 2.0 of the Pen API is different from the stroke header of version 1.x, since the stroke header now consists of a variable-length array instead of the STROKEINFO structure used in version 1.x. The current STROKEINFO structure is, nevertheless, compatible with version 1.x stroke headers.

•	Note the version change in the following Note from the "Creating an HPENDATA Object" section.

Note  	It is highly recommended that you use only the functions from version 2.0 of the Pen API. Although API from version 1.x are included for backward compatibility, it is not guaranteed that they will be supported in future versions of the Pen API.


 Chapter 5  The Recognition Process


 Using the HRC Functions

•	In the section "Creating the HRC," a bulleted item has been added following the third paragraph. Also, the paragraph after the bulleted list contains a change.

Either or both arguments can be NULL. Giving NULL as the first argument creates a new HRC with default settings. The next section, "Configuring the HRC," describes the default parameters, which include the following settings:

•	Recognition ends after a brief period of inactivity or when the user taps outside the target window.

•	The target window does not use guides.

•	The recognizer returns only its best guess without alternative guesses.

•	In Japan, recognition priority defaults to the settings specified by the Tool Palette applet, if it is active; otherwise the recognizer default setting is used.

Giving NULL as the second argument binds the HRC to the system default recognizer. Microsoft Windows sets the supplied file GRECO.DLL as the system default recognizer (RODAN.DLL in Japan), specified in the Microsoft Windows 95 system registry. Refer to Appendix A for an explanation of how to change the default to another recognizer.

•	The following information has been added immediately before the "Gesture" section.

ALC_KANJISYSMINIMUM	Minimum set of characters needed for Japanese system recognizer. Same as ALC_SYSMINIMUM | ALC_HIRAGANA | ALC_KATAKANA | ALC_JIS1. (Japanese version only.)
If an application does not specify alphabet configuration either through an existing HRC model or by calling the function SetBoxAlphabetHRC or SetAlphabetHRC, Windows assumes ALC_SYSMINIMUM (or ALC_KANJISYSMINIMUM) as the default alphabet configuration. For a complete list of ALC_ values, including Japanese-specific ones, see Chapter 13, "Pen Application Programming Interface Constants."


 	Alphabet Priority

The SetAlphabetPriorityHRC function provides a hint to the recognizer about which alphabet the user intends to use while inputting handwritten characters. Some written symbols have more than one interpretation, depending on alphabet (this is especially true in Japanese, which uses multiple alphabets). A crosslike character like the English plus sign (+) could also be interpreted as a lower case "t", katakana "na" or "me", or Kanji "juu" (the number 10), for example. Moreover, there are both SBCS and DBCS versions of English and katakana characters, corresponding to half-and full-pitch widths, so it's useful for a user or application to be able to pre-specify widths and character set preferences to minimize recognition errors.

Applications may use the SetAlphabetPriorityHRC API to set width and alphabet priority for HRC scope, or the SetPenAppFlags API to set width (DBCS or SBCS) preference for application scope. The Tool Palette application may be used to set system-wide priorities. Any priority set into an HRC supersedes application priority, which supersedes system priority as set (and if set) by the Tool Palette; in the event of not Tool Palette, the recognizer's default priority is used. The ALC_GLOBALPRIORITY bit will be set in all default HRCs, unless it is explicitly cleared with SetAlphabetPriorityHRC. To specify no priority, as opposed to default priority, an application should clear the ALC_GLOBALPRIORITY bit and set ALC_NOPRIORITY.

•	The following constant has been added to the "Gesture" section.

GST_KKCONVERT	Kana-Kanji convert. (Japanese version only)
•	In the "Unboxed Recognition" section, the following paragraphs have been changed.

An HRCRESULT object does not contain a normal text (ASCII for English) string representation of a guess. This is not possible since a guess might be made up of a gesture, shape, or other entity that has no text equivalent. Instead, an HRCRESULT contains a string of symbol values, which are 32-bit numbers type-defined as SYV.

Symbol values can represent geometric shapes, gestures, letters of the alphabet, Japanese kanji characters, musical notes, electronic symbols, or any other symbols defined by the recognizer. The Pen API provides the function SymbolToCharacter to convert the null-terminated symbol string in HRCRESULT to a normal text string.

•	In the section "Getting Results from the RCRESULT Structure," note the version change in the first sentence of this paragraph.

The RCRESULT structure applies only when an application calls either of the version 1.x recognition functions, Recognize or RecognizeData. In this case, the system sends a WM_RCRESULT message to the application. The wParam of this message contains a REC_ submessage that indicates why recognition ended. The lParam of WM_RCRESULT points to an RCRESULT structure, which contains all the results of the recognition.

•	Note the change to "text string" (formerly "ASCII string") in this paragraph.

The RCRESULT structure identifies the recognizer's "best guess," which is the guess in which the recognizer places the most confidence. With this information, an application can conveniently retrieve a text string of the best guess by calling SymbolToCharacter:


 Chapter 6  Design Considerations


 Recognition: Use and Misuse

•	In the section "bedit Is Better Than hedit," the following third paragraph has been added.

In Japan the bedit is almost always used for input, either directly, or via the Data Input Window.

•	In the section "Provide Easy Access to the On-screen Keyboard," the following sentence has been added after the first paragraph.

In Japan, this information is served by the Data Input Window.


 Guidelines for Applications

•	The "Word Processor" section has been changed.

Although the pen does not reasonably serve to create a word-processor document for English or European languages, it can serve well for small editing tasks on an existing document, such as cut-and-paste operations, formatting changes, rewriting small amounts of text, and navigation (scrolling)....

•	In Far Eastern countries such as Japan, Korea, and China, where ideographic characters such as Kanji are used, a full-featured pen-input word processing application would greatly simplify input of text.


 Chapter 7  A Sample Pen Application


 Overview of PENAPP

•	In the first bulleted item following the third paragraph, the phrase "and it supports free input" has been added and the word "ANSI" has been deleted.


 Window Procedures

•	The following code has been changed in the "InputWndProc" section.

#define   MAX_GUESS   5     // Maximum number of guesses

#define   MAX_CHAR    20    // Maximum number of characters per guess

// Global Variables ***************************************************

HRCRESULT   vrghresult[MAX_GUESS];        // Array of results

SYV    vsyvSymbol[MAX_GUESS][MAX_CHAR];   // Array of symbol strings

int         vcSyv[MAX_GUESS];             // Array of string lengths

.

.

.

LRESULT CALLBACK      InputWndProc(

                           HWND hwnd,      // Window handle

                           UINT message,   // Message

                           WPARAM wParam,  // Varies

                           LPARAM lParam ) // Varies

{

   LONG            lRet = 0L;      // Initialize return code to FALSE

   HRC           hrc;              // HRC object

   HDC           hdc;

   PAINTSTRUCT   ps;

   DWORD         dwInfo;

   int           i, cGuess;

   switch (message)

   {

         .

         .

         .

case WM_LBUTTONDOWN:

//

// Two possibilities exist: user is using mouse or the pen.

// The latter case indicates the user is starting to write.

//

dwInfo = GetMessageExtraInfo();

if (IsPenEvent( message, dwInfo ))

{

    if (DoDefaultPenInput( vhwndInput, (UINT)dwInfo ) == PCMR_OK)

        lRet = TRUE;

    else

        lRet = DefWindowProc( hwnd, message, wParam, lParam );

}

break;

case WM_PENEVENT:

    switch (wParam)

    {

        case PE_GETPCMINFO:

        //

        // If using SREC recognizer, ensure session ends

        // on pen-up.

        //

        if (viMenuSel == miSample)

            ((LPPCMINFO) lParam)->dwPcm |= PCM_PENUP;

        lRet = DefWindowProc( hwnd, message, wParam, lParam );

        break;

case PE_BEGINDATA:

    //

    // Action based on current menu selection:

    //

    // 1) If currently using sample recognizer, create an HRC

    // for it and specify it in the TARGET structure pointed

    // to by lParam.  This tells DoDefaultPenInput to use

    // the sample recognizer rather than the system default.

    //

    // 2) If displaying mirror image of ink, create an

    // HPENDATA for it and specify it in the TARGET structure

    // pointed to by lParam.  This tells DoDefaultPenInput to

    // collect data into the HPENDATA block instead of

    // passing it to a recognizer.

    //

    // 3) If using the default recognizer, pass to DefWindowProc,

    // which sets the maximum number of guesses to 1 and may

    // or may not require any guide information. The Japanese

    // default recognizer (RODAN.DLL) does require a guide

    // for character recognition. The following code shows

    // how to access the HRC that DefWindowProc creates,

    // reset the number of guesses to MAX_GUESS, and set

    // up the client rectangle of the input window as a

    // single guide.

    //

    if (vhpendata)

    {

        DestroyPenData( vhpendata );

        vhpendata = 0;

    }

    switch (viMenuSel)

    {

        case miSample:

            hrc = CreateCompatibleHRC( NULL, vhrec );

            if (hrc)

            {

                ((LPTARGET) lParam)->dwData = hrc;

                lRet = LRET_HRC;

            }

            break;

        case miMirror:

            vhpendata = CreatePenData( NULL, 0,

                                    PDTS_HIENGLISH, 0 );

            if (vhpendata)

            {

                ((LPTARGET) lParam)->dwData = vhpendata;

                lRet = LRET_HPENDATA;

            }

            break;

        case miSystem:

            lRet = DefWindowProc( hwnd, message,

                                wParam, lParam );

            //

            // On return, lParam->dwData points to HRC.

            // Use it to reset max number of guesses.

            //

            SetMaxResultsHRC( ((LPTARGET) lParam)->dwData,

                            MAX_GUESS );

            {

            GUIDE guide;

            RECT rc;

            GetClientRect(vhwndInput, &rc);

            ClientToScreen(vhwndInput, (LPPOINT) &rc.left);

            ClientToScreen(vhwndInput,    (LPPOINT) &rc.right);

            guide.xOrigin = rc.left;

            guide.yOrigin = rc.top;

            guide.cxBox = rc.right - rc.left;

            guide.cyBox = rc.bottom - rc.top;

            guide.cxBase =    0;

            guide.cyBase =    guide.cyBox;

            guide.cHorzBox = 1;

            guide.cVertBox = 1;

            guide.cyMid = guide.cyBox / 2;

            SetGuideHRC(((LPTARGET) lParam)->dwData, &guide, 0);

            }

            break;

}

    break;

case PE_ENDDATA:

//

// DefWindowProc will destroy vhpendata, so if collecting

// mirror image, don't let DefWindowProc handle message

//

if (viMenuSel != miMirror)

        lRet = DefWindowProc( hwnd, message, wParam, lParam );

    break;

case PE_RESULT:

//

// At end of input, collect recognition results (if any)

// into symbol strings.  DoDefaultPenInput generates the

// PE_RESULT submessage only when using a recognizer.

// The lParam contains the HRC for the recognition process.

//

// NOTE:

//    Do not destroy HRC, even after getting results!

//    DefWindowProc takes care of destroying the object.

//

// Collect pen data for DrawRawData

vhpendata = CreatePenDataHRC( (HRC) lParam );

// Initialize array to zero

for (i = 0; i < MAX_GUESS; i++)

    vcSyv[i] = 0;

// Get number of guesses available

cGuess = GetResultsHRC( (HRC) lParam,

                    GRH_ALL,

                    (LPHRCRESULT) vrghresult,

                    MAX_GUESS );

// Get guesses (in vsyvSymbol) and their lengths (invcSyv)

if (cGuess != HRCR_ERROR)

    for (i = 0; i < cGuess; i++)

        vcSyv[i] = GetSymbolsHRCRESULT( vrghresult[i],

                            0,

                            (LPSYV) vsyvSymbol[i],

                            MAX_CHAR );

// Destroy the HRCRESULTS

for (i = 0; i < cGuess; i++)

    DestroyHRCRESULT(vrghresult[i]);

                break;

                .

                .

                .

        default:

            lRet = DefWindowProc( hwnd, message, wParam, lParam );

    }                    // End switch (message)

    return lRet;

}

•	In the "DisplayGuesses" section of the "InfoWndProc" section, the following code has changed.

VOID        DisplayGuesses( HDC hdc )                // DC handle

{

    TEXTMETRIC  tm;

    int            nX, nY;                            // Text coords

        .

        .

        .

    for (i = 0; i < MAX_GUESS; i++)

    {

        if (vcSyv[i] > 0)

        {

            SymbolToCharacter( (LPSYV) vsyvSymbol[i],

                            vcSyv[i],

                            (LPSTR) szText,

                            (LPINT) &cChar );

            for (nLen = 0; cChar > 0; cChar--)

                nLen += IsDBCSLeadByte(*(szText + nLen)) ? 2 : 1;

            TextOut( hdc, nX, nY, (LPSTR) szText, nLen );

            nY += tm.tmExternalLeading + tm.tmHeight;

        }

    }

}


 Chapter 8  Writing a Recognizer


 How a Recognizer Works

•	Version information has been changed in the first paragraph.

The Pen API specifies the following functions for initializing, modifying, and closing down the recognizer. Note that, in version 2.0 of the Pen API, the required function ConfigRecognizer handles all initialization and configuration tasks. The other initialization functions are obsolete in version 2.0 and should only be included in a recognizer if it is expected to work with older applications that work with a version 1.x recognizer (see the Microsoft Pen Windows, version 1.x documentation for descriptions of these functions).

Note that the table following the first paragraph should refer to version 1.x rather than 1.0.

•	In the "HRCRESULT Section," note that the GetAlternateWordsHRCRESULT function is not supported.

•	In the "Training" section, note the version changes in the following paragraph and in the table it introduces.

The following table lists the functions that a recognizer with training capabilities can export. Only TrainHREC is used by version 2.0 Pen API. The other functions are obsolete in version 2.0 and should be included in a recognizer only if it is expected to work with older applications that work with a version 1.x recognizer (see the Microsoft Pen Windows, version 1.x documentation for descriptions of these functions).

•	In the "Processing Raw Data" section of the "Interpreting Input" section, note the additional .DLL in the first sentence of the second paragraph.

The Microsoft Handwriting Recognizer (GRECO.DLL or RODAN.DLL) processes only coordinate data.

•	In the section "Segmentation of Symbols," following Figure 8.1, the final sentence has been changed.

The Pen API places few restrictions on the recognizer. At a minimum, however, a default recognizer that supports free (unboxed) input must be able to recognize discrete characters because many applications do not use boxed input.

•	In the "Results Messages" section of the "Returning Results" section, note the version change in the second bulleted item.

•	In the section "The RCRESULT Structure" in the "Returning Results" section, the note should refer to version 1.x, not 1.0. Also in this section, the "Location and Position of the Input" section, the final sentence in the first bulleted item has been changed.

The Microsoft Handwriting Recognizer (GRECO.DLL or RODAN.DLL) sets nBaseLine to 0.


 Writing a Recognizer

•	In the "DestroyHRC" section, the code has been changed.

int WINAPI    DestroyHRC( HRC hrc )

{

    LPHRCinternal  lphrc = (LPHRCinternal) hrc;  // Pointer to HRC

    if (GlobalUnlock( lphrc->hglobal ) || GlobalFree(lphrc->hglobal))

        return HRCR_ERROR;

    else

        return HRCR_OK;

}


 Chapter 9  Summary of the Pen Application Programming Interface


 Pen API Functions

•	Note the version change in the table of function categories.

Obsolete	Obsolete functions of version 1.x maintained by version 2.0 only for compatibility reasons.
•	In the "List of Pen API Functions" section, the descriptions of several functions have been changed.

ShowKeyboard	Displays or hides the on-screen keyboard. (Not supported in Japan)
GetAlternateWordsHRCRESULT	Gets alternative guesses made by a recognizer. (Not supported in Japan)
CorrectWriting	Displays lens or Correct Text dialog box to allow user to correct text. (In Japan, this is wrapper for CorrectWritingEx)
KKConvert	Activates the Kana-to-Kanji converter. (Japanese version only.)
StartPenInput	Begins collecting into an internal buffer ink data generated by the moving pen. See also the descriptions of StartInking and DoDefaultPenInput.
Recognize	Begins recognition for a version 1.x recognizer.
RecognizeData	Delayed recognition for a version 1.x recognizer.
SetRecogHook	Installs and removes a recognition hook in version 1.x. Superseded by SetResultsHookHREC.


 Pen API Structures

•	In the "List of Pen API Structures" section, the descriptions of several structures have been changed.

RC	Various information about the recognition context used by version 1.x recognition functions.
RCRESULT	Results of recognition initiated through a version 1.x recognition function.


 Pen API Constants

•	The following items have been either redescribed or added to the table of constants.

CWX_	Options for CorrectWritingEx.
CWXA_	Options for CorrectWritingEx.
CWXK_	Options for CorrectWritingEx.
CWXKS_	Options for CorrectWritingEx.
CWXR_	Return types for CorrectWritingEx
GPR_	Options for GetPenResource.
REC_	Return codes from a version 1.x recognizer.


 Chapter 10  Pen Application Programming
Interface Functions

•	In the second paragraph, the phrase "for example, 1.0 or 2.0" should read "for example, 1.x or 2.0."

•	The CWR_KKCONVERT constant has been removed from the dwFlags parameter of the CorrectWriting function. Also, in the same function, the final sentence has been changed as follows:

Note that in the Japanese version, CorrectWriting is supported but internally calls CorrectWritingEx, which opens a Data Input Window.

•	The first sentence of the CorrectWritingEx funtion has been changed:

Sends text to the Japanese Data Input Window to allow the user to edit text. (Japanese version only.)

In the description of the lpText parameter of CorrectWritingEx, the phrase "and gets modified by the user" has been appended to the second sentence.

•	In the description of the cbText parameter, the second sentence should read as follows:

If the source of the text is an edit control that is constrained by EM_LIMITTEXT, cbText should be set to the limiting size plus one.

•	In the Example of CompactWritingEx, the second-to-last code block has been changed.

// don't update most-recently used settings for this one-shot:

cwx.wApplyFlags |= CWXA_NOUPDATEMRU;

cwx.ixkb = CWXK_QWERTY;

cwx.rgState[CWXK_QWERTY-CWXK_FIRST] = CWXKS_ROMAHAN;

cwx.dwFlags = CWX_NOTOOLTIPS | CWX_TOPMOST;    // no distractions

•	In the GetHotspotsHRCRESULT function, the final sentence of the first Comments paragraph has been changed.

The Microsoft Handwriting Recognizer (GRECO.DLL in US, RODAN.DLL in Japan), supports this function for gesture symbols only.

•	In the GetPenAppFlags function, the three references to the RegisterPenApp function have been changed to SetPenAppFlags.

•	The GetPenResource function has been added.


GetPenResource [New - Windows 95]
 GetPenResource

[New - Windows 95]

The GetPenResource function retrieves a copy of a pen services resource. (Japanese version only.)

HANDLE GetPenResource( WPARAM wParam )

Parameters

wParam

Specifies the pen services resource for which to retrieve a handle. This may be one of the following:

Constant	Description
GPR_CURSPEN	Standard pen cursor.
GPR_CURSCOPY	Copy cursor.
GPR_CURSUNKNOWN	Unknown cursor.
GPR_CURSERASE	Erase cursor.
GPR_BMCRMONO	Monochrome Return bitmap.
GPR_BMLFMONO	Monochrome LineFeed bitmap.
GPR_BMTABMONO	Monochrome Tab bitmap.
GPR_BMDELETE	Delete bitmap.
GPR_BMLENSBTN	Lens buttonface bitmap.
GPR_BMHSPMONO	Hankaku space bitmap (Japanese version only).
GPR_BMZSPMONO	Zenkaku space bitmap (Japanese version only).
Comments

An application can use this function to get a copy of a cursor or bitmap used by pen services. It is the application's responsibility to destroy the object by calling either the DestroyCursor or DeleteObject Windows API.

Return Value

•	This function returns a handle to an object, depending on the index specified by wParam if successful. Otherwise the return value is NULL.

•	The following sentence has been added to the Comments section of the SetPenAppFlags function.

If both RPA_DBCSPRIORITY and RPA_SBCSPRIORITY are specified, the RPA_SBCSPRIORITY is ignored.

•	In the TrainHREC function, the following sentence has been appended to the Comments section.

Training gestures depends on the recognizer. The Microsoft Handwriting Recognizer (GRECO.DLL in US, RODAN.DLL in Japan) does not support training for gestures.


 Chapter 11  Pen Application Programming
Interface Structures

•	Note that throughout this chapter structures marked as version 1.0 should be marked as version 1.x.

•	The final sentence of the introductory paragraph has been changed.

The entry heading identifies the Pen API version, such as 1.x or 2.0, that supports the structure.

•	In the CWX structure, the description of the CWXA_CONTEXT constant has changed.

Constant	Description
CWXA_CONTEXT	Use the dwFlags member to specify context. (topmost, tooltips, period, comma)
•	Two CWX_ constant descriptions have been changed.

Constant	Description
CWX_EPERIOD	Specifies that the English period is to be used on some keys on the Data Input Window keypads. The Japanese period is used by default.
CWX_ECOMMA	Specifies that the English comma is to be used on some keys on the Data Input Window keypads. The Japanese comma is used by default.
•	The CWXK_ROMAJI constant has been removed from the list of CWXK_ constants.

•	The description of the CWXK_KANJI constant should read as follows:

Kanji finder, which provides a method of specifying a Kanji character based on its strokes.

•	The paragraph describing the rgState member of the CWX structure has been changed. The constant descriptions have also changed.

…and this member is ignored. The zero-based order is: 50-On Keyboard, QWERTY Keyboard, Numeric Keyboard, Stroke/Radical Finder, Code Finder, and Yomi Finder. On return, this member contains the updated states. Each element of the array may be CWXKS_DEFAULT, which causes the existing saved state to be used, or one of the following constant values, depending on the keyboard:

Constant	Description	Applicable Keyboards
CWXKS_HAN	Set Hankaku (single-byte) state.	Numeric
CWXKS_ZEN	Set Zenkaku (double-byte) state.	Numeric
CWXKS_ROMAHAN	Set Hankaku Romaji state.	QWERTY
CWXKS_ROMAZEN	Set Zenkaku Romaji .	QWERTY
CWXKS_HIRAZEN	Set Hiragana state.	50-On, QWERTY
CWXKS_KATAHAN	Set Hankaku Katakana state.	50-On, QWERTY
CWXKS_KATAZEN	Set Zenkaku Katakana state.	50-On, QWERTY
•	The SKBINFO structure is not available in the Japanese version of the Pen API.


 Chapter 12  Pen Application Programming
Interface Messages


HE_KKCONVERT [New - Windows 95]
 HE_KKCONVERT

[New - Windows 95]

Starts Kana-to-Kanji conversion. Submessage of WM_PENCTL. (Japanese version only.)

Parameters

wParam

HE_KKCONVERT.

lParam

Must be one of the following values:

Value	Meaning
HEKK_DEFAULT	The first time the conversion is specified, the selected or marked character string is replaced with the conversion result. The behavior for successive calls depends on the IME. For example, a candidate list may appear.
HEKK_CONVERT	The selected or marked character string is replaced with the conversion result; the conversion candidate list doesn't appear regardless of how many times conversion has been specified.
HEKK_CANDIDATE	The selected or marked character string is replaced with the conversion result; this causes the conversion candidate list to appear.
HEKK_DBCSCHAR	The SBCS characters (0x20 − 0x7E, 0xA1 − 0xDF) are replaced by their DBCS equivalents.
HEKK_SBCSCHAR	The DBCS characters in the selected or marked character string that have equivalent SBCS representations are replaced by their equivalent SBCS characters.
HEKK_HIRAGANA	The katakana characters (DBCS or SBCS) in the selected or marked character string are replaced with their hiragana equivalents.
HEKK_KATAKANA	The hiragana characters in the selected or marked character string are replaced with their DBCS katakana representation.
Return Value

Returns TRUE if there are no errors; otherwise, returns FALSE:

Comments

In this message, "marked character string" indicates the string that is marked for conversion. Text marked for conversion is indicated by a different selection color than that used for normal text selection in a standard text edit control. Available for bedits only.


HE_PUTCONVERTCHAR [New - Windows 95]
 HE_PUTCONVERTCHAR

[New - Windows 95]

Sends a character to the control and marks it for conversion. Submessage of WM_PENCTL. (Japanese version only.)

Parameters

wParam

HE_PUTCONVERTCHAR.

lParam

The low-order word contains the character code, which can be an SBCS or DBCS character.

Return Value

Returns TRUE if there are no errors; otherwise, returns FALSE.

Comments

Posting this message is similar to posting a WM_CHAR message to a bedit control, with the exceptions that the posted character also acquires the attribute of being a character marked for conversion in the Input Method Editor, and DBCS characters may be specified in the LOWORD of lParam. This submessage is available for bedits only.


WM_PENMISC [New - Windows 95]
 WM_PENMISC

[New - Windows 95]

•	The PMSC_KKCTLENABLE, PMSC_PENUICHANGE, and PMSC_SUBINPCHANGE subfunctions have been removed.


 Chapter 13  Pen Application Programming
Interface Constants


 ALC_Alphabet Codes

Constant	Description
ALC_KANJISYSMINIMUM	Minimum set of characters needed for Japanese system recognizer. Same as ALC_SYSMINIMUM | ALC_HIRAGANA | ALC_KATAKANA | ALC_JIS1. (Japanese version only.)


 RCD_ Writing Direction

•	Note the Note: The RCD_ constants are provided only for compatibility with version 1.x the Pen API and will not be supported in future versions.


 RCP_ User Preferences

•	Note the Note:  RCP_ constants are provided only for compatibility with version 1.x of the Pen API and will not be supported in future versions.


 RCRT_ Results Type

•	The RCRT_ALREADYPROCESSED constant description has been changed.

Constant	Description
RCRT_DEFAULT	Normal return type.


 Appendix A  Differences Between Versions 1.x and 2.0 of the Pen Application Programming Interface

Note the title change, from version 1.0 to 1.x. This change is reflected throughout this chapter and will not be mentioned here unless text has otherwise changed.


 Improvements to the bedit Control

•	The final paragraph of this section has been changed.

Because Japanese and other Far Eastern languages may use double-byte characters, an application must specify double the number of bytes for EM_LIMITTEXT than applications expecting only single-byte characters (or halve the number of boxes). Note that even without explicitly limiting text with EM_LIMITTEXT, input into single-line, nonscrollable BEDIT controls is limited to the number of boxes available. For example, a 3-box postal code BEDIT allows only three characters, be they SBCS or DBCS. For more information about EM_LIMITTEXT, see "The bedit Control" in Chapter 3, "The Writing Process."

•	In the section "The RC Structure," the table following the second paragraph has been changed.

RC member	Equivalent service in Pen API 2.0
lpUser	GetPenMiscInfo with PMI_USER. Cannot set new user in version 2.0.


 Gestures

•	The gesture table has been changed.

Gesture	Name	Action
	T-circle	Tab
or    or	K-circle  or  symbol-circle (drawin Right to Left)	Kana to Kanji conversion


 Action Handles

•	A sentence has been added at the end of this section.

In the Japanese version, action handles can be disabled with the Control Panel.


 On-Screen Keyboard

•	A sentence has been added at the end of this section.

In the Japanese version, ShowKeyboard is not available. Rather, CorrectWritingEx allows access to the Data Input Window.


 Appendix B  Using the 32-Bit Pen Application Programming Interface


 32-Bit Functions

•	The KKConvert function has been added to the list of functions supported by the 32-bit Pen API.


 Introduction

The Programmer's Guide to Microsoft® Windows® 95 presents a series of articles covering programming issues specific to the Windows 95 operating system. This guide provides conceptual and reference information that is not available in any other document. Topics range widely from issues regarding the Win32® applica-tion programming interface to how to take advantage of Windows 95 features to extend existing MS-DOS®−based applications. To better focus this range of topics, the guide is divided into six main parts.

•	Part 1, "Understanding Windows 95," discusses the Windows 95 architecture and the API differences between version 3.x−based and Windows 95−based applications.

•	Part 2, "Developing Applications for Windows 95," discusses common controls and dialog boxes, the registry, and dragging and dropping. This part also discusses how to create applications for multimedia and pen, and provides an overview about installing applications.

•	Part 3, "Extending the Windows 95 Shell," discusses the shell namespace, shell extensions, application desktop toolbars, shell links, and the taskbar notification area.

•	Part 4, "Using Windows 95 Features," discusses file viewers, file parsers, briefcase reconcilers, the Passwords control panel, device I/O control, system policies, and ToolHelp functions.

•	Part 5, "Using Microsoft MS-DOS Extensions," discusses, MS-DOS extensions, long filenames, exclusive volume locking, program information file (PIF) management, and virtual machine services.

•	Part 6, "Applications for International Markets," discusses guidelines for developing international applications. This part also covers the use of double-byte characters and input method editors (IMEs), and outlines how to write  Middle-Eastern applications.

•	Part 7, "Advanced Programming," discusses the thunk compiler, a tool that assists developers in porting existing applications to the Win32 API.


 Windows 95 Architecture

This article introduces the types of software components that you can build for Microsoft® Windows® 95, and it briefly describes the features of Windows 95 that those components can use.


 Software Components

The operating environment for Windows 95 consists of a computer's hardware devices and the following software components:

•	Virtual machine manager (VMM).

•	Virtual devices (VxDs).

•	Read-only memory (ROM) basic input and output system (BIOS).

•	Installable device drivers and terminate-and-stay-resident (TSR) programs.

•	16- and 32-bit Windows dynamic-link libraries (DLLs).

•	Microsoft® MS-DOS® − based applications.

•	16- and 32-bit Windows-based applications.


 Virtual Machine Manager

The virtual machine manager (VMM) is the 32-bit protected-mode operating system at the core of Windows 95. Its primary responsibility is to create, run, monitor, and terminate virtual machines. The VMM provides services that manage memory, processes, interrupts, and exceptions such as general protection faults. The VMM works with virtual devices, 32-bit protected-mode modules, to allow the virtual devices to intercept interrupts and faults to control the access that an application has to hardware devices and installed software.

Both the VMM and virtual devices run in a single, 32-bit, flat model address space at privilege level 0 (also called ring 0). The system creates two global descriptor table (GDT) selectors, one for code and the other for data, and uses the selectors in the CS, DS, SS, and ES segment registers. Both selectors have a base address of zero and a limit of 4 gigabytes (GBs), so all the segment registers point to the same range of addresses. The VMM and virtual devices never change these registers.

The VMM provides multiple-threaded, preemptive multitasking. It runs multiple applications simultaneously by sharing CPU (central processing unit) time between the virtual machines in which the applications run. The VMM is also nonreentrant. This means that virtual devices must synchronize access to the VMM services. The VMM provides services, such as semaphores and events, to help virtual devices prevent reentering the VMM.

For more information about the VMM, including descriptions of the services that it provides to virtual devices, see the documentation included in the Microsoft Windows 95 Device Driver Kit (DDK).


 Virtual Devices

Virtual devices (VxDs) are 32-bit programs that support the device-independent VMM by managing the computer's hardware devices and supporting software. VxDs support all hardware devices for a typical computer, including the programmable interrupt controller (PIC), timer, direct memory access (DMA) device, disk controller, serial ports, parallel ports, keyboard, and display adapter. A VxD is required for any hardware device that has settable operating modes or retains data over any period of time. In other words, if the state of the hardware device can be disrupted by switching between multiple virtual machines or applications, the device must have a corresponding VxD.

Some VxDs support software, but no corresponding hardware device. In general, a VxD can provide any kind of services for the VMM and other virtual devices. Windows 95 allows the user to install new virtual device drivers to support an add-on hardware device or provide some system-wide software service.

A VxD can also provide application programming interface (API) functions for applications running in virtual 8086 mode or protected mode. These functions can give applications direct access to the features of the VxD.

Windows 95 includes a device input and output control (IOCTL) interface that allows Microsoft® Win32® − based applications to communicate directly with VxDs. Applications typically use this interface to carry out selected MS-DOS system functions, to obtain information about a device, or to carry out input and output (I/O) operations that are not available through standard Win32 functions. For more information about the device IOCTL interface, see "Device I/O Control."

For more information about virtual devices, see the documentation included in the Windows 95 DDK.


 Device Drivers

A Windows device driver is a DLL that Windows uses to interact with a hardware device, such as a display or keyboard. Rather than access devices directly, Windows loads device drivers and calls functions in the drivers to carry out actions on the device. Each device driver exports a set of functions; Windows calls these functions to complete an action, such as drawing a circle or translating a keyboard scan code. The driver functions also contain the device-specific code needed to carry out actions on the device.

Windows requires device drivers for the display, keyboard, and communication ports. Other drivers may also be required if the user adds optional devices to the system.

The Windows 95 DDK provides independent hardware and software vendors (IHVs and ISVs) with the resources to build device drivers and VxDs that are compatible with the Windows 95 operating system. The resources include a configurable development environment, documentation, tools, and header files and libraries for several device types. The Windows 95 DDK contains the following components:

•	Header files and libraries for building device drivers and VxDs.

•	Sample source code for device drivers and VxDs.

•	16- and 32-bit versions of the driver development tools.


 Dynamic-Link Libraries

Dynamic linking provides a mechanism for linking applications to libraries of functions at run time. The libraries reside in their own executable files and are not copied into an application's executable file as with static linking. These libraries are "dynamically linked" because they are linked to an application when it is loaded and executed rather than when it is linked. When an application uses a DLL, the operating system loads the DLL into memory, resolves references to functions in the DLL so that they can be called by the application, and unloads the DLL when it is no longer needed. Dynamic linking can be performed explicitly by applications or implicitly by the operating system.

DLLs are designed to provide resources to applications. Many applications can use the code in a DLL, meaning that only one copy of the code is resident in the system. Also, it is possible to update a DLL without changing applications that use the DLL, as long as the interface to the functions in the DLL does not change.

Software developers can extend the Windows environment by creating a DLL that contains routines for performing operations and then making the DLL available to other Windows-based applications (in addition to internal Windows routines). DLLs most often appear as files with a .DLL filename extension; however, they may also have an .EXE or other filename extension.

Windows 95 supports 32-bit DLLs as well as 16-bit DLLs that were written for Windows version 3.x. For a discussion of the issues involved in mixing 16- and 32-bit components in the Windows 95 environment, see "Thunk Compiler."

For more information about dynamic-link libraries, see the documentation included in the Microsoft Win32 Software Development Kit (SDK).


MS-DOS - Based Applications
 MS-DOS − Based Applications

Windows 95 supports applications written for MS-DOS. Each MS-DOS − based application can run as a full-screen application, or it can run in a window on the Windows 95 desktop.

The system can run multiple MS-DOS − based applications at the same time. To do so, it creates a separate virtual machine (VM) for each MS-DOS − based application and shares the microprocessor among the MS-DOS VMs and the system VM (which contains all Windows-based applications). A VM can run an MS-DOS − based application in either the virtual 8086 mode or protected mode of the microprocessor.

Although most MS-DOS − based applications run fine in a window or as a full-screen application, some may not. To ensure absolute backward compatibility for all MS-DOS − based applications, Windows 95 provides a separate operating mode called "single MS-DOS application mode." When in this mode, Windows 95 runs only one MS-DOS − based application at a time. No Windows-based applications run in that mode; in fact, none of the graphical user interface (GUI) components of the system are even loaded.

Windows 95 supports the complete set of MS-DOS system functions and interrupts and provides extensions that permit MS-DOS − based applications to take advantage of long filenames and other Windows 95 features, such as exclusive volume locking, virtual machine services, and program information file management.

Disk utilities and other applications that directly modify file system structures, such as directory entries, must request exclusive use of the volume before making modifications to the structures. Windows 95 provides a set of input and output control (IOCTL) functions to manage exclusive volume use. Exclusive use prevents applications from inadvertently changing the file system while a disk utility is trying modify it.

Virtual machine services let Microsoft MS-DOS − based applications take advantage of features provided by Windows 95 when the applications run in a window. MS-DOS − based applications can retrieve and, optionally, set the title of the window in which they run. Virtual machine services also allow MS-DOS − based applications to periodically check the state of an internal close flag and terminate if the flag is set. Windows 95 sets this flag when the user chooses the Close command from the system menu of the window in which the MS-DOS − based application runs. Close-aware applications enable the Close command, which gives the user an alternate way to exit the application and close the window.

Program information file management lets Microsoft Windows − based applications create, examine, and modify program information files (.PIF files). These files contain the detailed information needed by the operating system to prepare virtual machines for running Microsoft MS-DOS − based applications. Installation programs and other applications can open the files, retrieve and set information in the files, and display the information to the user for editing.

For more information, see the following articles in this guide: "MS-DOS Extensions," "Long Filenames," "Exclusive Volume Locking," "Virtual Machine Services," and "Program Information File Management."


 Windows-Based Applications

Windows 95 supports 16-bit applications written for Windows version 3.x as well as 32-bit applications that use the Win32 or Microsoft® Win32s® API. For 16-bit applications, Windows 95 preserves the cooperative multitasking model used in Windows version 3.x; that is, all 16-bit applications share the same virtual address space, the same message queue, and the same thread of execution. By contrast, each 32-bit Windows-based application has its own address space, a private message queue, and one or more threads of execution. In addition, each 32-bit thread is preemptively multitasked.

All new applications should be 32-bit applications developed using the Win32 API. For information about porting a 16-bit application to Win32, see "Version Differences."


 Shell Features and Extensions

Windows 95 includes a number of component object module (COM) interfaces and functions that applications can use to enhance various aspects of the shell. This section describes the aspects of the shell that applications can enhance.


 Shell Namespace

A namespace is a collection of symbols, such as file and directory names or database keys. The Windows 95 shell uses a single hierarchical namespace to organize all objects of interest to the user, including files, storage devices, printers, and network resources — in short, anything that can be viewed using Windows Explorer. The namespace is similar to the directory structure of a file system except that the namespace contains objects other than files and directories.

The Windows 95 shell provides a COM interface and several functions that allow an application to browse the namespace and retrieve information about the objects in the namespace. For more information about the shell's namespace, its COM interface, and related functions, see "Shell's Namespace."


 Shortcuts

A shortcut (also called a shell link) is a data object that contains information used to access another object located anywhere in the shell's namespace. A shortcut allows an application to access an object without having to know the current name and location of the object. Objects that can be accessed through shortcuts include files, folders, disk drives, printers, and network resources.

Windows 95 includes a COM interface that an application can use to implement shortcuts. For example, an application that manipulates documents might use shortcuts to provide the user with a list of the most recently opened documents. For more information about shortcuts, see "Shell Links."


 Shell Extensions

An application developer can extend the Windows 95 shell in a number of different ways. Extending the shell involves adding information to the system registry or writing an OLE COM in-process server (InProcServer32).

A context menu handler is a type of shell extension that modifies the contents of a context menu. The system displays a context menu when the user clicks or drags an object using mouse button 2. The context menu contains commands that apply specifically to the object that was clicked or dragged.

Most context menus have a Properties command that displays the property sheet for the selected item. A property sheet contains information about an object in a set of overlapping windows called pages. A property sheet handler is a shell extension that adds pages to a system-defined property sheet or replaces pages in a Control Panel application's property sheet.

The system uses icons to represent files in the shell's namespace. By default, the system displays the same icon for all files that have the same filename extension. An icon handler can override the default and set the icon for a particular file.

A copy hook handler is an shell extension that approves or disapproves the moving, copying, deleting, or renaming of a file object.

For more information about extending the shell, see "Shell Extensions."


 File Viewers and Parsers

The shell includes a Quick View command that allows the user to view the contents of a file without having to run the application that created it and without even requiring the presence of the application. When the user chooses Quick View from the File menu or from the context menu for a file, the system runs the file viewer associated with the selected file. The shell uses the filename extension to determine which viewer to run.

A file viewer provides the user interface for viewing a file. It is an OLE component object implemented in an in-process server DLL. You can provide file viewers for new file formats or replace an existing viewer with one that includes more functionality. For more information about file viewers, see "File Viewers."

A file viewer works in conjunction with a file parser, which is a DLL that provides the low-level parsing needed to generate the "quick view" of a file of a given type. You can extend the file viewing capabilities of Windows 95 by supplying additional file parsers. Each file parser is responsible for a specific type or class of file and is associated with a display engine. For example, you can allow a quick view to be generated for a .DOC file by creating a file parser to support the file type and associating the file parser with the word processor display engine. For more information about file parsers, see "File Parsers."


 Control Panel Applications

A Control Panel application is a special purpose DLL that lets the user configure the Windows environment. Even though Windows provides a number of standard Control Panel applications, you can create additional applications to let the user examine and modify the settings and operation modes of specific hardware and software. For information about creating Control Panel applications, see the documentation included in the Win32 SDK.


 Screen Savers

A screen saver is an application that the system automatically starts when the mouse and keyboard have been idle for a period of time. A screen saver avoids damage to the display caused by static images on the screen or conceals sensitive information left on the screen. The property sheet for the display allows the user to select from a list of screen savers, specify how much time should elapse before the screen saver is started, configure screen savers, and preview screen savers. For information about how to create a screen saver, see the documentation included in the Win32 SDK.


 System Features

This section describes some of the main features of Windows 95 that you can use in your Windows-based applications.


 Registry

The registry is a central storage location that contains current information about the computer hardware configuration, installed software applications, settings and preferences of the current user, and associations between types of files and the applications that access and manipulate their contents. Much of the information  that was stored in initialization files in previous versions of the Windows operating system is now stored in the Windows 95 registry.

Mentions of the registry occur in several places in documentation for Windows and Win32. The Windows Interface Guidelines for Software Design has a chapter containing a general discussion of the registry. A chapter in the Microsoft Windows 95 Resource Kit explains how to integrate an application into Windows 95 by storing information in the registry. This guide also includes an article that addresses registry coding issues for a program that installs a software application. Finally, the documentation included in the Win32 SDK provides a detailed description of the functions and structures that provide an application with access to the registry.


 Fonts

Fonts are used to draw text on video displays and other output devices. In Windows 95, a font is a collection of characters and symbols that share a common design. The three major elements of this design are typeface, style, and size. A typeface is a set of characters that share common characteristics, such as stroke width and the presence or absence of serifs. For example, Arial® and Courier are each typefaces. The font style refers to font characteristics, such as italic and bold. Font size refers to the point size of a font. Applications may use the Font common dialog box to display available fonts and allow users to select the typeface, style, and size. Windows 95 provides functions and related structures that allow applications to enumerate the available fonts on the system and select a specific font.

In addition to enumerating and selecting fonts, Windows 95 provides a set of functions and related structures that allow developers to perform the following tasks:

•	Use a stock font to draw text.

•	Check the text capabilities of a device.

•	Set the text alignment.

•	Draw text from different fonts on the same line.

•	Rotate lines of text.

•	Retrieve character outlines of a TrueType font.

•	Use portable TrueType metrics to achieve a WYSIWYG (what you see is what you get) effect.

•	Use PANOSE™ numbers of a TrueType font.

•	Create and install customized fonts.

For more information about fonts, see the documentation included in the Win32 SDK.


 Printing

Windows 95 provides a complete set of functions that allow applications to print on a variety of devices: laser printers, vector plotters, raster printers, and fax machines. One of the chief features of these functions is their support of device independence. Instead of issuing device-specific commands to draw output on a particular printer or plotter, an application calls high-level functions from graphics device interface (GDI). The various printing components in Windows 95 interact with GDI to convert the high-level commands to raw device commands and spool the print job to the printer.

In addition to GDI, the following Windows 95 components are involved in printing.

Device driver	A Windows DLL that supports the Windows device driver interface (DDI). A device driver generates raw device commands when it processes calls to DDI functions made by GDI. The commands are processed by the printer when it prints the image.
Print spooler	The primary component of the printing interface. The print spooler is a Windows executable file that manages the printing process. Management of printing involves retrieving the location of the correct printer driver, loading the driver, converting high-level function calls to journal records, storing the journal records on disk as a print job, and so on.
Print processor	A Windows DLL that reads and converts journal records into DDI calls.
Port monitor	A Windows DLL that passes the raw device commands over the network, through a parallel port, or through a serial port to the device.
Windows 95 provides functions that allow applications to monitor many aspects of the printing process. Applications may enumerate and obtain information about these aspects:

•	Monitors for a specified server.

•	Print jobs for a specified printer.

•	Ports that are available for printing on a specified server.

•	Printer drivers installed on a specified printer server.

•	Available printers, print servers, domains, or print providers.

•	Print processors installed on the specified server.

•	Data types that a specified print processor supports.

For more information about printing, see the documentation included in the Win32 SDK.


 File System

The file allocation table (FAT) file system is the original file system of MS-DOS. Except for the introduction of 16-bit FAT in MS-DOS version 3.0, this file system has remained essentially unchanged since MS-DOS version 2.0. Windows 95, however, introduces the following major change: the enhancement of the FAT file system to support long filenames. A long filename is a name for a file or directory that exceeds the standard 8.3 filename format.

The protected-mode FAT file system is the default file system used by Windows 95 for mass storage devices, such as hard disk and floppy disk drives. Protected-mode FAT is compatible with the MS-DOS FAT file system, using file allocation tables and directory entries to store information about the contents of a disk drive. Protected-mode FAT also supports long filenames, storing these names as well as the date and time that the file was created and the date that the file was last accessed in the FAT file system structures.

Win32-based applications automatically have access to long filenames through the use of the Win32 file management functions as well as the common dialog boxes used to open and save files. Applications should support long filenames and use long filenames for displaying all document and data filenames in the shell, in title bars, in dialog boxes and controls, and with icons.

For more information about the file system, see "MS-DOS Extensions" and "Long Filenames."


 Plug and Play

Plug and Play is the name of a new industry standard for personal computers that lets personal computers (PCs) and attached hardware work together automatically. The goal of the Plug and Play technology is to make it easier than ever before for users to change the hardware configuration of their computers.

The most obvious beneficiaries of Plug and Play are the users of mobile PCs, whose hardware configurations change whenever they use a PCMCIA (Personal Computer Memory Card International Association) card or docking station. Every PC user, though, will benefit from Plug and Play; anyone who has ever had trouble setting up a new modem, sound card, or compact disc read-only memory (CD-ROM) drive understands the need for this technology.

Most of the Plug and Play architecture is implemented in new hardware, updated device drivers, and Windows itself; for most Windows-based applications, little extra code is required to support Plug and Play. A Windows-based application should be enabled for Plug and Play if it uses hardware that could be reconfigured, added to a system, or removed from a system while the application is running. Any Windows-based application that can be run on a mobile PC or that depends on the state of the monitor or other external devices should check for changes to the system hardware and take appropriate action when changes occur.

The system uses the following messages to send information about configuration changes to Windows applications.

WM_DEVICECHANGE	Tells applications about device changes. It is the most important Plug and Play message. The wParam parameter of this message contains an event code that an application can use to react to the change. For example, the DBT_DEVICEQUERYREMOVE event code asks an application for permission to remove a device. An application can return TRUE to grant permission or FALSE to deny it.
WM_DISPLAYCHANGE	Alerts applications to changes in the resolution of the screen.
WM_POWERBROADCAST	Tells applications about changes in the system's power status, including pending standby requests.
For more information about these messages, see the documentation included in the Win32 SDK. For information about the Plug and Play system architecture and how to write Plug and Play device drivers, see the Windows 95 DDK. For information about the design of Plug and Play hardware, see the Hardware Design Guide for Microsoft Windows 95.


 Win32 Application Programming Interface

The Microsoft Win32 API allows applications to exploit the power of 32 bits using the Windows family of operating systems. The Win32 functions, messages, and structures form a consistent and uniform API for all of Microsoft's 32-bit platforms: Windows 95, Microsoft® Windows NT™, and Windows version 3.1 with Win32s. Using the Win32 API, you can develop applications that run successfully on all platforms while still being able to take advantage of unique features and capabilities of any given platform.

With a few minor exceptions, Microsoft ensures consistent and uniform behavior of the Win32 API across all platforms. Differences in the implementation of the Win32 functions depend on the capabilities of the underlying features of the platform. The most notable difference is that some Win32 functions carry out their tasks only on the more powerful platforms. For example, security functions are only available on the Windows NT operating system. Most other differences are system limitations, such as restrictions on the range of values or the number of items a given function can manage. For more information about system limitations, see "Win32 Limitations in Windows 95."

The Win32 API provides a wide and varied set of functions, messages, and structures that give your 32-bit applications access to the unique features and capabilities of the Windows operating system. The Win32 API can be grouped into these functional categories:

•	Graphics Device Interface (GDI)

•	Windows Management

•	System Services

•	Multimedia

•	Remote Procedure Calls (RPC)


 Graphics Device Interface

Graphics device interface (GDI) provides functions and related structures that an application can use to generate graphical output for displays, printers, and other devices. Using GDI functions, you can draw lines, curves, closed figures, paths, text, and bitmapped images. The color and style of the items you draw depends on the drawing objects — that is, pens, brushes, and fonts — that you create. You can use pens to draw lines and curves, brushes to fill the interiors of closed figures, and fonts to write text.

Applications direct output to a given device by creating a device context (DC) for the device. The device context is a GDI-managed structure containing information about the device, such as its operating modes and current selections. An application creates a DC by using device context functions. GDI returns a device context handle, which is used in subsequent calls to identify the device. For example, using the handle, an application can retrieve information about the capabilities of the device, such as its technology type (display, printer, or other device) and the dimensions and resolution of the display surface.

Applications can direct output to a physical device, such as a display or printer, or to a "logical" device, such as a memory device or metafile. Logical devices give applications the means to store output in a form that is easy to send subsequently to a physical device. Once an application records output in a metafile, it can play that metafile any number of times, sending the output to any number of physical devices.

Applications use attribute functions to set the operating modes and current selections for the device. The operating modes include the text and background colors, the mixing mode (also called the binary raster operation) that specifies how colors in a pen or brush combine with colors already on the display surface, and the mapping mode that specifies how GDI maps the coordinates used by the application to the coordinate system of the device. The current selections identify which drawing objects are used when drawing output.


 Window Management

Window management gives applications the means to create and manage a user interface. Using the window management functions, you create and use windows to display output, prompt for user input, and carry out the other tasks necessary to support interaction with the user. Nearly all applications create at least one main window.

Applications define the general behavior and appearance of their windows by creating window classes and corresponding window procedures. The window class identifies default characteristics, such as whether the window processes double clicks of the mouse buttons or has a menu. The window procedure contains the code that defines the behavior of the window, carries out requested tasks, and processes user input.

Applications generate output for a window using the GDI functions. Because all windows share the display screen, applications do not receive access to the entire screen. Instead, the system manages all output so that it is aligned and clipped to fit within the corresponding window. Applications can draw in a window in response to a request from the system or while processing input messages. When the size or position of a window changes, the system typically sends a message to the application requesting that it paint any previously unexposed area of its window.

Applications receive mouse and keyboard input in the form of messages. The system translates mouse movement, mouse button clicks, and keystrokes into input messages and places these messages in the message queue for the application. The system automatically provides a queue for each application. The application uses message functions to extract messages from the queue and dispatch them to the appropriate window procedure for processing.

Applications can process the mouse and keyboard input directly or let the system translate this low-level input into command messages by using menus and keyboard accelerators. You use menus to present a list of commands to the user. The system manages all the actions required to let the user choose a command and then sends a message identifying the choice to the window procedure. Keyboard accelerators are application-defined combinations of keystrokes that the system translates into messages. Accelerators typically correspond to commands in a menu and generate the same messages.

Applications often respond to command messages by prompting the user for additional information with dialog boxes. A dialog box is a temporary window that displays information or requests input. A dialog box typically includes controls — small, single-purpose windows — that represent buttons and boxes through which the user makes choices or enters information. There are controls for entering text, scrolling text, selecting items from a list of items, and so on. Dialog boxes manage and process the input from these controls, making this information available to the application so that it can complete the requested command.

Window management functions provide other features related to windows. For example, the clipboard functions provide the means to copy and paste information within the same window, between windows in the same application, and between windows in different applications. Applications also use the clipboard functions to carry out dynamic data exchange (DDE). DDE operations let applications exchange information without requiring specific direction from the user.


 System Services

System services are a set of functions that give applications access to the resources of the computer and the features of the underlying operating system, such as memory, file systems, and processes. An application uses system services functions to manage and monitor the resources that it needs to complete its work. For example, an application uses memory management functions to allocate and free memory and uses process management and synchronization functions to start and coordinate the operation of multiple applications or multiple threads of execution within a single application.

System services functions provide access to files, directories, and input and output (I/O) devices. The file I/O functions give applications access to files and directories on disks and other the storage devices on a given computer and on computers in a network. These functions support a variety of file systems, from the MS-DOS FAT file system to the CD-ROM file system (CDFS). The network functions create and manage connections to shared resources, such as directories and printers, on computers in the network. Communications functions read from and write to communications ports as well as control the operating modes of these ports.

System services functions provide methods for applications to share resources with other applications. For example, you can make useful procedures available to all applications by placing these procedures in DLLs. Applications access these procedures by using DLL functions to load the libraries and retrieve the addresses of the procedures. You can share useful data, such as bitmaps, icons, fonts, and strings, by adding this data as "resources" to the file for an application or DLL. Applications retrieve the data by using the resource functions to locate the resources and load them into memory.

System services functions provide access to information about the system and other applications. System information functions let applications determine specific characteristic about the computer, such as whether a mouse is present and what dimensions elements of the screen have. Registry and initialization functions let applications store application-specific information in system files so that new instances of the application or even other applications can retrieve and use the information.

System services also let applications share information with applications running on the same computer or on other computers in a network. Applications can copy information between processes by using the mailslot and pipe functions to carry out interprocess communication (IPC). For operating systems that provide security features, the security functions give applications access to secure data as well as protect data from intentional or unintentional access or damage.

System services functions provide features that applications can use to handle special conditions during execution, such as handling errors, logging events, and handling exceptions. There are features that applications can use to debug and improve performance. For example, debugging functions permit single-step control of the execution of other processes, and performance monitoring allows for detailing the path of execution through a process.


 Multimedia

Multimedia functions give applications access to high-quality audio and video. Multimedia functions let you enhance and expand the capabilities of your application, giving users the ability to combine these forms of communication with more traditional forms of computer output. Using multimedia functions, applications can create documents and presentations that incorporate music, sound effects, and video clips as well as text and graphics. The multimedia functions provide services for audio, video, file I/O, media control, joysticks, and timers.

Applications use audio functions to play and record audio data using waveform, Musical Instrument Digital Interface (MIDI), and auxiliary audio formats. When playing audio, an application can mix sounds by routing selected audio to specified devices. To ensure efficient storage of audio data, the audio functions provide access to audio compressors and decompressors through the Audio Compression Manager (ACM).

Applications use video functions to capture video clips, compress the clips, and control their playback. An application captures video clips by using simple messages to access video and wave audio acquisition hardware, such as a video tape machine, and to stream selected video clips to disk. To store video data efficiently, an application can use the video compressors and decompressors provided by the Installable Compression Manager (ICM). Applications can play back video clips either on the computer screen or on other media devices by using the Media Control Interface (MCI) indirectly through the functions of the MCIWnd window class.

Applications use file I/O functions to store and retrieve the different types of multimedia data. An application can use unbuffered and buffered I/O with multimedia files, access and navigate Resource Interchange File Format (RIFF) files, and integrate custom I/O functions for multimedia data types. Of particular significance is the audio-video interleaved (AVI) file format, which provides for storing digital video clips consisting of both video and audio data. An AVI file is a RIFF file that has an extensible file architecture. This means that an application can customize AVI files to store and retrieve nonstandard data streams.

The Media Control Interface (MCI) provides a common set of high-level commands through which applications control media devices, such as animation devices, audio compact discs (CDs), digital-video devices, MIDI sequencers, video overlay devices, video disks, VISCA tape recorders (VCRs), and waveform (digital sound) devices. To communicate with a device, an application sends messages or command strings through MCI. The corresponding device handler interprets the message or string and executes the appropriate command at the device.

Applications use joystick functions to provide support for up to two joystick devices. An application can retrieve information about a joystick, calibrate the sensitivity of the device, and receive messages related to movement and button activity. Multimedia timer functions provide high-resolution timing for single or periodic events.


 Remote Procedure Calls

Remote procedure calls (RPCs) give applications the means to carry out distributed computing, enabling them to tap the resources and computational power of computers on a network. Using RPC, you create distributed applications, each consisting of a client that presents information to the user and a server that stores, retrieves, and manipulates data and generally handles the bulk of the computing tasks for the client. Shared databases, remote file servers, and remote printer servers are examples of distributed applications.

A distributed application, running as a process in one address space, makes procedure calls that execute in an address space on another computer. Within the application, such calls appear to be standard local procedure calls, but these calls activate stub procedures that interact with the RPC run-time library to carry out the necessary steps to execute the call in the remote address space. RPC manages the network communications needed to support these calls, even the details such as network protocols. This means distributed applications need little or no network-specific code, making development of such applications relatively easy.

Microsoft RPC is just one part of a complete environment for distributed computing defined by the Open Software Foundation (OSF), a consortium of companies that was formed to define the components of a complete environment supporting distributed computing. Microsoft's implementation of RPC is compatible with the OSF standard with minor differences. Client or server applications written using Microsoft RPC version 1.0 will interoperate with any Distributed Computing Environment (DCE) RPC client or server whose run-time libraries implement the connection-based model and run over a supported protocol.


 Extension Libraries

Extension libraries give applications services and capabilities beyond the basic services of the Win32 API. The extension libraries either expand on services already provided by the Win32 API or provide unique services that are commonly used by Win32 applications. There are the following extension libraries:

•	Common Controls

•	Common Dialog Boxes

•	Data Decompression

•	File Installation

•	Dynamic Data Exchange (DDE) Management

•	Network DDE


 Common Controls and Dialog Boxes

The Windows 95 shell incorporates a number of control windows and dialog boxes that help give Windows 95 its distinctive look and feel. Because these controls and dialog boxes are supported by DLLs that are a part of Windows 95, they are available to all applications. Using the common controls and dialog boxes helps keep an application's user interface consistent with that of the shell and other applications. Because developing a control or dialog box can be a substantial undertaking, using the common controls and dialog boxes can also save you a significant amount of development time.

The common controls are a set of control windows that are supported by the common control library, COMCTL32.DLL. Like other control windows, a common control is a child window that an application uses in conjunction with another window to perform I/O tasks. The common control DLL includes a programming interface that applications use to create and manipulate the controls as well as to receive user input from them. For more information about common controls, see the documentation included in the Win32 SDK.

The common dialog boxes provide a ready-made user interface that you can use to retrieve various kinds of information from the user. They are supported by the common dialog box library, COMDLG32.DLL. The library includes dialog boxes for selecting and creating colors, finding and replacing strings, opening and saving files, and setting printer options. For more information about the common dialog boxes, see the documentation included in the Win32 SDK.


 Data Decompression and File Installation

The data decompression and file installation libraries provide useful functions for applications that install files. The data decompression library provides functions that applications use to expand files that have been compressed using the Microsoft File Compression Utility (COMPRESS.EXE). The file installation library provides functions that make it easier for applications to analyze currently installed files and install new files properly.


 DDEML and Network DDE

The DDE management and network DDE libraries simplify the process of exchanging data with other applications. The DDE management library (DDEML) provides functions that minimize the amount of code needed in an application to carry out dynamic data exchange and gives an application the means to exchange data without requiring user interaction. The network DDE library provides functions that an application can use to connect to DDE servers on other computers in the network. These functions minimize the amount of code that an application needs to access the network; they also ensure security across network connections.


 Win32 Software Development Kit

The Win32 SDK includes the tools and resources you need to build 32-bit applications that use the Win32 API. The Win32 SDK contains the following components:

•	Win32s components for building Win32-based applications that run on Windows version 3.x platforms.

•	32-bit header files and libraries for building Win32 applications that run with the Windows 95 and Windows NT operating systems.

•	Retail and debug versions of the Windows 95 core system DLLs.

•	Applications and utilities that aid in the development process.

•	Sample source code that demonstrates how to implement the Win32 API.

•	Documentation of the Win32 API and information describing how to use Win32 to develop Windows 95 − based applications.

•	Online text of the style guide for Windows-based applications, The Windows Interface Guidelines for Software Design.

•	Articles from the Windows 95 Knowledge Base.

For a description of the features and contents of the Win32 SDK as well as instructions on how to install and use it, see the Getting Started booklet included in the Win32 SDK.


 OLE

OLE is a set of API services that allows an application to create documents consisting of information from different applications. Each piece of information is represented as an object and can consist of text, bitmap images, vector graphics, and even voice annotation and video clips. Representing information as objects makes it easier for applications to exchange, incorporate, and process data from applications created by different vendors. Applications that take advantage of OLE can interact seamlessly, allowing the user to focus on creating and managing information rather than on remembering how to perform procedures.

OLE associates two major types of data with an object: presentation data and native data. An object's presentation data is information needed to render the object on a display device, while its native data is all the information needed for an application to edit the object.

An object can be linked to or embedded in a document. Linking is a process whereby only an object's presentation data and a reference (or pointer) to its native data are placed in a document. The actual native data associated with the object exists in another location, such as in a file on disk. Whenever an application updates the object, it appears updated within the document. To the user, a linked object acts as if it were wholly contained within the document. By contrast, embedding places an object's presentation data and its native data physically within a document. All information necessary to edit the object is contained in the document.

Embedding makes a document larger, but it allows the object to be transferred with the document to another computer and to be edited on a different computer. Linked objects cannot "travel" with documents outside the local file system of the computer, but they are more efficient than embedded objects because a single instance of the object's data can serve many different documents.

OLE not only gives applications the ability to add linked and embedded objects to documents but also includes the following powerful features that you incorporate into your Windows-based applications.

Visual editing	Lets the user directly activate an object in-place within a document without switching to a different window. This includes operations such as in-place editing, displaying, recording, and playing.
Nested objects	Lets the user directly manipulate an object nested within another other object and to establish links to nested objects.
Drag and drop	Lets the user drag an object from one application window to another or to drop an object inside another object.
Storage-independent links	Allows links between embedded objects that are not stored as files on disk, enabling embedded objects within the same or different documents to update one another's data, whether or not they are recognized by the file system.
Adaptable links	Enables links between objects to be maintained in certain move or copy operations.
OLE automation	Enables the creation of command sets that operate both within and across applications. For example, a user can activate a command from a word processing application that sorts a range of cells in a spreadsheet created by a different application.
Version management	Allows an object to contain information about the application and the version of the application that created it.
Object conversion	Allows an object type to be converted so that different applications can be used with the same object. For example, an object created with one brand of spreadsheet could be converted so that it could be interpreted by a different spreadsheet application for editing.
OLE is supported by Windows version 3.1, Windows NT, and Windows 95, allowing your application to work the same way on all Windows platforms. The OLE documentation included in the Win32 SDK contains a set of DLLs, sample source code, extensive online information, and tools to assist in adding OLE capabilities to Windows-based applications.


 Telephony Application Programming Interface

Telephony application programming interface (TAPI) makes it possible to create applications that combine the capabilities of the personal computer with the telephone. TAPI was created in cooperation with telecommunications companies, personal computer manufacturers, and software vendors as the standard for integrating telephones with PCs running the Windows operating system.

By integrating the PC and the telephone networks, TAPI makes possible the following new classes of applications.

Screen-based telephony	Provides a visual interface for accessing existing phone features and makes new features possible that cannot be implemented due to the today's limited telephone user interface.
Communications management	Provides end-user programmability that enables intelligent filtering and forwarding of telephone communications.
Personal productivity	Automates telephone calls and integrates them into personal productivity software. Calls can be automatically dialed to save time, and call details can be logged.
Integrated messaging	Allows the user to access their different electronic communications media, such as electronic mail, voice mail, and faxes from a single point on the desktop or from a remote location.
Ubiquitous voice on the desktop	Digitizes audio from the telephone directly into the PC, or retrieves audio seamlessly from a voice server and plays it back over a phone's speaker.
Conferencing	Provides video conferences as well as less bandwidth intensive tasks, such as sharing documents or "virtual whiteboards," to create a richer communications medium and attain the benefits of proximity at a distance.
Wide area data networking	Provides cleaner integration with the global telephone network, which facilitates fax and data communications from the PC.
Vertical solutions	Integrates telephone communications with business information systems. For example, an incoming call can be routed to the first available agent by a computer-based queuing system, and the customer's record "popped" onto the agent's screen before they even pick up the phone with caller identification-like functionality.
TAPI provides a standard interface, allowing an application to take advantage of the many capabilities and services of the telephone. At the same time, TAPI isolates an application from the complexity and variability of the underlying telephone network, greatly simplifying the application development task. In addition, TAPI is independent of the method of connection between the PC and telephone. This gives maximum flexibility to integrate the PC with the telephone system.

TAPI is part of the Microsoft Windows Open Services Architecture (WOSA), which provides a single set of open-ended interfaces to enterprise computing services. WOSA services, such as TAPI, consist of two interfaces. Developers write to an applications programming interface (API). The other interface, referred to as the service provider interface (SPI), is used to establish the connection to the specific telephone network.

Applications can combine TAPI with other capabilities of Windows to provide a combination of services. For example, an application can use TAPI to establish a connection and then use the Windows audio functionality to record and play back voice information over the connection.

For more information about TAPI, see the documentation included in the Win32 SDK.


 Messaging Application Programming Interface

Windows 95 includes the messaging application programming interface (MAPI). You can use MAPI to add messaging features to your Windows-based applications that make it easy for users to electronically share information, such as charts and reports.

The MAPI architecture is designed to make it easy to write powerful messaging-enabled applications that are independent of the underlying messaging system. To achieve this, MAPI provides two interfaces: the (API), which provides messaging services to an application, and the service-provider interface (SPI), which provides the link to the messaging system. MAPI provides a layer of functionality between an application and the underlying messaging system, allowing them to be developed independently of one other.

MAPI services are high-level (compared to most networking functions) and allow you to implement sophisticated messaging features with a small amount of code. You deal only with functions for sending, receiving, and addressing messages; the underlying messaging system is completely transparent. MAPI also provides other functionality such as access to address books — that is, customized lists of message recipients.

MAPI supports existing standards such as the X.400 API Association's Common Messaging Calls (CMC). By using the CMC or Simple MAPI, you can easily add message capabilities to an existing application's user interface. For example, a word processing program can include a Send Message command that sends a document as a mail message to a recipient. MAPI also supports application macro languages, such as those used in Microsoft® Excel and Word. For example, a spreadsheet user can write a macro that automatically sends a monthly budget spreadsheet to a designated recipient when the file is updated with new sales figures.

You can also use CMC or Simple MAPI to create an application that is centered around messaging capabilities. One example is a scheduling application in which users can view the schedules of their coworkers and send meeting requests to the coworkers' calendars. Another example is a forms-routing application that sends an expense report to a series of recipients and records their approval or disapproval.

MAPI also supports workgroup applications that require full access to all of the back-end messaging services, including the message store, address book or directory, and transport functions. These applications include e-mail clients, workflow automation programs, and bulletin board services. For example, a workflow application might allow a user to inspect a message stored in a certain project folder to see if the appropriate workers have signed off on their tasks. This application could also include a sophisticated search and store feature that retrieves relevant files from a bulletin board system and stores them in the folders of certain recipients. Advanced workgroup applications take advantage of Extended MAPI.

For more information about MAPI, see the documentation included in the Win32 SDK.


 Pen

Every computer running Windows 95 can display and manipulate data that was collected on a pen-enabled system. These capabilities are provided by a dynamic-link library, either PKPD.DLL or PKPD32.DLL. A Windows-based application can use pen data in the following ways:

•	To display a signature for letters or faxes.

•	To verify signatures collected on a pen-based mobile computer.

•	To display graphics, maps, or handwritten notes that have been drawn on a pen-based system.

Displaying and manipulating ink, the common term for pen data, is only a subset of the pen services available to Windows-based applications. Pen-enabled applications use the entire set of Pen functions to add ink collection and recognition to their feature sets. Pen services for Microsoft Windows 95 requires either the PENWIN.DLL or PENWIN32.DLL library for all of the functionality of pen data collection. The library is supplied by the pen tablet or computer manufacturer that bundles Microsoft pen services with their product. (Pen-enabled systems use the same pen display library that is available on every Windows 95 computer for pen data manipulation and display: PKPD.DLL or PKPD32.DLL.)

For more information about the pen capabilities of Windows 95, see "Displaying and Using Pen Data." The Programming Guide to Pen Services for Microsoft Windows 95, which is included in the Win32 SDK, provides information about using the entire set of pen API to collect, recognize, manipulate, and display ink.


 International Applications

Within six months of its final release, Windows 95 will be available in 30 different language versions. To support all of these languages, Microsoft has developed three separate code bases: one for single-byte character sets (SBCS), one for double-byte character sets (DBCS), and one for the languages of the Middle East.

The DBCS versions, which ship to the Far East, include the input method editor (IME) for complex writing systems, an end-user defined character (EUDC) editor, and all the code for passing DBCS (mixture of 8- or 16-bit) characters through the user interface. For more information about the input method editor, see "Using Input Method Editors." For more information about creating applications that can handle DBCS characters, see "Using Double-Byte Characters."

The versions for the Middle East support both left to right and right to left text placement as well as special ligature and text justification (Kashida) handling. For more information about developing applications for the Middle East, see "Writing Applications for Middle-Eastern Languages."

To make localization easy, you should develop all language-dependent user-interface elements as Win32 resources. Using resources allows you to create versions of your application in any number of languages without having to recompile your application's components. For more information about resources, see the documentation included in the Win32 SDK.

For more information about internationalization issues, see "International Guidelines," and read the International Handbook for Software Design, which is available in the Microsoft Developer Network Development Library.


 Creating Great Applications

The Microsoft® Windows® 95 user interface is based on a datacentric design; that is, rather than focusing on applications, the user interface design emphasizes data and tasks that involve the manipulation of data. The interface has been designed to allow the user to browse for data and documents and to edit them directly without necessarily having to locate an appropriate editor or application first. This type of design frees the user to focus on information and tasks rather than on applications and how they interact.


 About Creating Great Applications

This article briefly describes some of the features you should use and guidelines you should follow to ensure that your application is a "great" Windows 95 − based application. A great Windows 95 − based application is one that integrates seamlessly with the user interface in Windows 95 and conforms to the system's datacentric design principles. In addition to reading this article, you should follow the user interface guidelines presented in The Windows Interface Guidelines for Software Design.


 File Information

Throughout the Windows 95 shell, files appear as icons. When you click on a file's icon using mouse button 2, the system displays a context menu containing commands that perform actions on the file. One of the commands, Properties, displays a special dialog box called a property sheet that contains information about the file. By viewing a file's property sheet, the user can find out information about a file without having to open it.

By default, a file's property sheet contains general information about the file, including its name, size, location, creation date, attributes, and so on. The following illustration shows the default property sheet for a typical file.

If your application creates files with additional properties that the user may be interested in, you should add more pages to the property sheets for the files. One way to add property sheet pages to an application using OLE structured storage is to store documents in compound files (also called docfiles) and use the Document Summary Information Property Set to store summary information and editing statistics for the documents. When the user activates the property sheet for the document, the shell automatically gathers the summary information and editing statistics from the document and adds them to the property sheet as two additional pages. The following illustration shows a property sheet with Summary and Statistics pages added based on data gathered from the document.

For more information about saving document information using the OLE Document Summary Information Property Set, see the OLE documentation included in the Microsoft® Win32® Software Development Kit (SDK).

Another way to add pages to file property sheets is to write a shell extension (OLE InProcServer32) that includes a property sheet handler. Whenever the user activates the property sheet for a file, the system checks the registry to see if any property sheet handlers are registered for the file type. If there are some registered, the system calls the handlers before displaying the property sheet. The handlers can add any number of pages to the property sheet before it is displayed. For more information about shell extensions and property sheet handlers, see "Shell Extensions."


 Long Filenames

Windows 95 allows users and applications to create and use long filenames for their files and directories. A long filename is a name for a file or directory that is longer than the standard 8.3 filename format. In the past, long filenames typically appeared on network servers that used file systems other than the Microsoft® MS-DOS® file allocation table (FAT) file system. In Windows 95, however, long filenames are available for use with network servers and with local disk drives supporting the protected-mode FAT file system.

An application should support long filenames and display them correctly. You can use the SHGetFileInfo function in your application to retrieve the long filename for a file as well as the file's icon, type name, attributes, and so on. If you include the File Open and Save As common dialog boxes in your application, you can use the OFN_LONGNAMES value to direct the dialog boxes to display and return long filenames. Before an application displays a long filename, it should hide the filename extension. For example, the application should display a filename like "My letter to Mom" instead of "My letter to Mom.Doc." An application can hide filename extensions on a file-specific basis by using the SHGetFileInfo function.

The following illustration shows a folder containing documents with long filenames.

If an application is used to view or edit a document or data file, the title bar of the window that contains the file should display the long filename for the file. If the title bar also includes the application's name, it should appear to the right of the filename. Displaying the filename first places the emphasis on the document or data rather than on the application. For more information about long filenames, see "Long Filenames."

You should also support Universal Naming Convention (UNC) path names for files in your application. Using UNC names enables users to browse documents on the network directly and to open an application's files on remote machines without needing to know the location of the file on the network or having to make an explicit network connection.


 Context Menus

A context menu is a pop-up menu containing a set of commands that are specific to a particular object. Window 95 provides a context menu for all objects that appear in the shell, including files, folders, printers, and so on. A context menu appears when the user clicks an object using mouse button 2. Because context menus are displayed at the pointer's current location, they eliminate the need for the user to move the pointer to the menu bar or toolbar. They also help eliminate screen clutter.

You should provide context menus for all objects in an application and should display the context menu whenever the user clicks an object using mouse button 2. Each context menu should include a Properties command that displays a property sheet for the object.

In addition to displaying a context menu for objects, an application should also display a context menu when the user clicks the small icon in the title bar using mouse button 2. The commands in the context menu should operate on the object that is open in the window, not on the window itself. To see an example of a context menu associated with a title bar icon, click the title bar icon of a folder window in the shell using mouse button 2. For more information about context menus, see "Shell Extensions."


 Icons

If your application supports OLE, you should make sure that the icons for your embedded and linked objects are consistent with the shell. For example, when the user drags an icon from the shell into your container, the icon and its name should stay the same.

You should support interactions with embedded icons the same way that the shell does. For example, when the user selects the icon for an embedded object, you should dither the icon with the system highlight color rather than enclosing it in a rectangle that has resizing handles.


 Shortcuts

A shortcut (also called a shell link) is a data object that contains information used to access another object in the system, such as a file, folder, disk drive, or printer. A shortcut has an icon associated with it; the user accesses the object associated with a shortcut by double-clicking the shortcut's icon. The associated object can be stored anywhere in the system.

Typically, the user creates shortcuts to gain quick access to objects stored in subfolders on the same machine or to shared folders on other machines. For example, the user can create a shortcut to a Microsoft Word document located in a subfolder and can place the shortcut icon on the desktop. The user can later start Word and open the document simply by double-clicking the shortcut icon. If the document is later moved or renamed, the system takes steps to update the shortcut the next time the user selects it.

An application should support shortcuts. For example, a word processing application might allow the user to drag and drop a shortcut icon into a document file. An application should also correctly dereference shortcuts. For example, if the user specifies the filename of a shortcut when using an application's Open command on the File menu, the application should open the object associated with the shortcut, not the shortcut file itself. For more information about shortcuts, see "Shell Links."


 Clipboard Data Transfer Operations

Windows 95 supports two types of clipboard data transfer operations — those involving menu commands (such as Cut, Copy, and Paste), and those involving the direct manipulation of objects (drag and drop). An application should support both types extensively.

You should support the OLE style of drag and drop. If you support drag and drop, the user can easily move data among the desktop, folders, and other applications. You should support dragging with mouse button 2 and display a context menu at the end of the drag operation, as the shell does. At a minimum, the menu should include these commands: Move Here, Copy Here, Create Shortcut(s) Here, and Cancel. For more information about supporting the OLE style of drag and drop, see "Dragging and Dropping."

You should make sure your application's menu-based data transfer model works well with the shell. You should test various scenarios, such as copying a shortcut or file in a shell folder to the clipboard and then pasting the shortcut or file into your application. Also, if your application supports shortcuts to its documents, you should offer a link to your OLE data object when the user drags an object out of a document.


 Common Controls and Dialog Boxes

The Windows 95 shell incorporates a number of control windows and dialog boxes that help give Windows 95 its distinctive look and feel. Because these controls and dialog boxes are supported by DLLs that are a part of Windows 95, they are available to all applications. You should use the common controls and dialog boxes — rather than developing similar controls and dialog boxes of your own — because they help keep your application's user interface consistent with that of the shell and other applications. Because developing a control or dialog box can be a substantial undertaking, using the common controls and dialog boxes can also save you a significant amount of development time.


 Common Controls

The common controls are a set of control windows that are supported by the common control library, which is a DLL called COMCTRL32.DLL. Like other control windows, a common control is a child window that an application uses in conjunction with another window to perform input and output (I/O) tasks. The common control DLL includes a programming interface that you use to create and manipulate the controls and dialog boxes and to receive user input from them. This section describes some of the controls provided by the common control DLL.

Header Control. A header control provides headings for columns of text or numbers. It can be divided into many parts, and each part can have its own heading text. The user can adjust the width of the columns by dragging the dividers that separate the parts.

Property Sheet. A property sheet displays the properties of an object, such as a document file or a cell in a spreadsheet. Related properties can be grouped together and placed on separate, overlapping pages within the property sheet. Each page has a tab that the user can select to bring the page to the foreground.

An application can create a special type of property sheet called a wizard control. The control displays a sequence of pages that guide the user through the steps of an operation, such as setting up a device or creating a birthday card.

Up-Down Control. An up-down control consists of a pair of arrow buttons that the user can click to increment or decrement a value, such as a scroll position or a number displayed in an accompanying edit control.

Tree View Control. A tree view control displays a hierarchical list of items, such as the headings in a document, the entries in an index, or the files and directories on a disk. By clicking an item, the user can expand or collapse the associated list of subordinate items. The user can select items, edit item labels, and drag items from one location to another.

Status Window. A status window displays information that may be useful to the user. It is typically positioned along the bottom of a window and can be divided into parts to display different types of information simultaneously.

Toolbar. A toolbar contains buttons that carry out commands when the user selects them. Typically, the buttons correspond to menu items, providing a quicker, more direct way for the user to access an application's commands.

Progress Bar. A progress bar indicates the progress of a lengthy operation. It consists of a rectangle that is gradually filled with color, from left to right, as the operation progresses.

List View Control. A list view control displays a collection of related items, each consisting of an icon and a descriptive label. The items can be arranged and displayed in different ways to suit the user's preferences. The user can select items, edit item labels, and drag items from one location to another.

Trackbar. A trackbar allows the user to select a value from a range of consecutive values. To select a value, the user drags the trackbar's slider to the desired position.


 Common Dialog Boxes

Windows 95 provides several common dialog boxes that your application can use to obtain various kinds of information from the user. There are the following types of common dialog boxes.

Dialog box	Description
Color	Enables the user to select and create colors.
Find	Enables the user to specify a search string.
Open	Enables the user to specify the location and filename of a file to be opened.
Page Setup	Enables the user to set the attributes of a printed page, including the paper type, the paper source, the page orientation, and the width of the page margins.
Print	Enables the user to configure a printer for a particular print job. The user can set print job parameters, such as the print quality, print range, and number of copies.
Replace	Enables the user to specify strings for use in a search and replace operation.
Save As	Enables the user to specify the location and name of a file to be saved.
For more information about the common dialog boxes, see the topic "Common Dialog Box Library." Note that the Print Setup dialog box provided in previous versions of Windows is now obsolete; new applications should use the Page Setup dialog box.

The Open and Save As common dialog boxes accessed from the File menu are especially useful because they support many features of the Windows 95 shell, including shell links, long filenames, and direct browsing of the network. If you cannot use the Open and Save As dialog boxes, you should incorporate the following features into your open and save dialog boxes to ensure that they are consistent with the shell, the Windows accessories, and other applications:

•	Support the same namespace hierarchy as the shell; that is, Desktop should be at the root of the hierarchy, followed by all folders and objects on the desktop, including My Computer, My Network, and so on. For more information about the shell namespace, see "Shell's Namespace."

•	Support shortcuts (also known as shell links). Note that opening a shortcut should open the target of the shortcut rather than the shortcut file itself. For more information about shortcuts, see "Shell Links."

•	Display filenames with the corresponding icons and filename extensions removed, as the shell does.

•	Allow the user to browse the network hierarchy directly.

•	Make sure that all of your dialog boxes (not just your open and save dialog boxes) use only nonbold fonts. In addition, you should use the DS_3DLOOK style to give your dialog boxes the three-dimensional look used throughout the system.


 Other Development Considerations

In addition to supporting common controls and dialog boxes, an application should include other new shell features, such as context menus, property sheets (with extensions), the details view, and so on. For more information about context menus and property sheets, see "Shell Extensions."

If your application supports 256 colors, you should use the Windows halftone palette, as the shell does. It helps system performance, because the system does not need to load a new palette every time the execution focus switches between the shell and your application. For more information about palettes, see the documentation included in the Win32 SDK.


 Windows 95 Help

The Windows Help application has been improved for Windows 95. It includes many new features that you can use to provide help information that is task- or object-specific as well as readily accessible and unobtrusive. You should consider including the following features in your application's help file:

•	Provide context-sensitive help for your dialog boxes and documents. The user can access context-sensitive help by clicking mouse button 2 (if there is no context menu available) or pressing the F1 key to display help information for a specific object or element in the application. The following illustration shows context-sensitive help for a control in a dialog box.

•	Use secondary windows for procedural help. A secondary window does not have menus, and it remains open until it is explicitly closed.

•	Embed shortcut buttons in your help text. A shortcut button allows the user to start an application from within a help file.

•	Use sizable topic windows to make help text easier to read.

•	Consider using the built-in support for training cards.

For more information about the Windows 95 Help application, see the topic "Help" and the documentation included with the Microsoft Windows Help Compiler.


 Multiple Instances

You should not let the user open multiple views of the same document. Multiple views confuse the user and conflict with the datacentric design of Windows 95.

When the user attempts to open a document file associated with an application, typically by double-clicking the document file's icon, the application should determine if the document file is already open. If it is, the application should check whether the current user has attempted to open the file. The application should do more than just compare user names because the user may be logged onto more than one computer. If the current user already has the document file open, the application should immediately restore the window containing the open document file.

If the current user has not attempted to open the document file (meaning that someone else on the network has), the application should prompt the user with the following message.

This document has already been opened by <name>. Would you like to make a copy?

If the user does not want to make a copy, the application should exit; otherwise, it should make a copy.

You should also handle the case where the user double-clicks an application's icon when the application is already running. If the application's default action is to open a blank document when the user double-clicks the icon, the application should present the user with a list of currently opened documents. Opening a new document, however, should be the default action.


 Pen Input

An application should support pen input so that it is easy to use on pen-based platforms, such as notebook computers and desktop tablets. The following list briefly describes what you need to do to support pen input:

•	Use functions from the Windows pen application programming interface (API) to activate the pen in your application. If you activate the pen, the user can enter text using handwriting recognition and edit documents using gestures.

•	Incorporate ink-edit controls into your application. Ink-edit controls allow the user to enter scribbled notes, drawings, and signatures.

•	Add other natural pen-oriented features and gestures to your application.

For more information about supporting pen input, see "Displaying and Using Pen Data."


 Application Installation Guidelines

You should follow the Windows 95 guidelines for installing your application so that it works well when running with Windows 95. Some of the important installation guidelines follow:

•	Create a subdirectory in the Applications directory at the root of the hard disk and store your application's executable file and any sample files there. If the Applications directory does not exist at the root of the hard disk, your installation program should create it. If you have any other executable or data files, such as .DLL and .HLP files that are specific to your application, your program should create another subdirectory named Application Extensions in the Applications directory. It should copy the remaining files (except shared files) to this new subdirectory.

•	Copy all system-wide shared files (files shared by applications from many different vendors) to the \Applications\Shared Components directory. If this directory does not exist, your installation program should create it. If a given file already exists in this directory, your program should overwrite it with your file only if your file is a more recent version.

•	Copy all shared files (files shared by applications from the same vendor) to a vendor-specific directory in the \Applications\Shared Components directory. If the vendor-specific directory does not exist, your installation program should create it.

•	Place a single icon (shortcut) for your main application either directly in the Programs folder of the Start menu or in a subfolder of the Programs folder. If your installation program adds a shortcut, the user can easily start your application from the Start menu. However, your program should not overload the Start menu. To prevent overloading that menu, you may want your installation program to prompt the user to choose which shortcuts to add.

•	Register your application-specific icons and commands as described in "Registry" later in this topic.

•	Support the Add/Remove Programs application in Control Panel so that the shell automatically runs your installation and uninstall programs. Note that on some types of hardware, the shell automatically runs your installation program as soon as the user inserts the floppy disk or compact disc (CD).

For more information about installing your application to run with Windows 95, see "Installing Applications."


 Registry

Integrating your application into the Windows 95 shell requires that you make full and correct use of the system registry. Your installation program should add the following items to the registry:

•	Register your application under the HKEY_LOCAL_MACHINE\SOFTWARE key. Your installation program should include keys for your company name, product name, and version number.

•	Store user-specific initialization data under the HKEY_CURRENT_USER\SOFTWARE key. Your installation program should not store initialization data in the WIN.INI file.

•	Add application-specific paths to the registry so that Windows sets the PATH environment appropriately when starting your application. Your installation program should set the path in the HKEY_LOCAL_MACHINE root under the \SOFTWARE\Microsoft\Windows\CurrentVersion\AppPaths key and create a new key having the same name as your application's executable file. Under this new key, your program should create the Path value name and assign it a path using the same format as that expected by the PATH environment variable.

•	Register an icon for each type of data file created by your application. When the system displays one of your data files in the shell, the registered icon for that file's type appears along with the file's name. If your installation program does not register icons for data files, the system will generate icons for them, but they may not be as distinctive as you would like them to be.

•	Register data-specific commands for your data files; these commands appear in the context menus for your data files. For example, if your application creates sound files, your installation program might register a Play command that enables the user to play a sound by choosing Play from the context menu.

•	Register a "Print To command" for your data files. Including a printto canonical verb in the registry enables the user to print your data files by performing a drag and drop operation to a specific printer object. Note, however, that the printto canonical verb does not add a command to the context menu of your data files.

For a description of additional items you should add as well as instructions on how to add the items described in the preceding list, see "Installing Applications."


 Window 95 Logo Requirements

This section describes the technical requirements that software programs and hardware devices must meet to qualify for the Windows 95 Logo. These requirements are periodically updated. To obtain information about the current requirements, contact Microsoft.


 General Requirements for Applications

The requirements for the Windows 95 Logo apply to the following four main types of programs:

•	File-based applications — that is, applications that provide Open, Save, and Close File menu options.

•	Applications that are not file-based and applications that run exclusively in full screen mode. An application that runs exclusively in full screen mode is one that cannot run in a window or be minimized.

•	Utilities (for example, virus scanners and disk management programs).

•	Development tools (for example, compilers and linkers).

To qualify for the Windows 95 Logo, an application must meet the appropriate requirements in the following list. The first five requirements apply to all types of applications.

1.	An application must use the Win32 application programming interface (API) and must be compiled using a 32-bit compiler that generates an executable file of the Portable Executable (PE) format. If your application is not represented in the PE format (for example, it uses interpreted code), the "run-time engine" must be a Win32 executable file in the PE format. For example, if you develop an application in Microsoft Access, your application is an .MDB file, not an .EXE, but ACCESS.EXE would need to be a Win32 PE format executable file.

2.	An application must support the Windows 95 shell and user interface. At a minimum, an application must meet the following requirements:

•	Register both 16- by 16-pixel and 32- by 32-pixel icons for each file type and the application.

•	Follow the user interface guidelines described in The Windows Interface Guidelines for Software Design. An application should also use the system-defined dialog boxes and controls.

•	Use the system metrics for setting the size of elements within the application.

•	Use the system-defined colors.

•	Use the right mouse button for context menus (and not for any other purpose).

•	Follow the Windows 95 application installation guidelines to make the application properly visible in the shell. At a minimum, this means that you should use the registry, you should not add information to the WIN.INI or SYSTEM.INI file, and you should provide complete uninstall capabilities with your application. In addition, the installation process must be automated. For more information about installation guidelines, see "Installing Applications."

For detailed guidelines about supporting the shell and user interface, see The Windows Interface Guidelines for Software Design.

3.	An application must be tested on the latest version of Microsoft® Windows NT™. If the application uses features that are available only in Windows 95, the features must degrade gracefully in Windows NT. Conversely, if it uses features available only in Windows NT, the features must degrade gracefully in Windows 95. The application must run successfully with both Windows 95 and Windows NT, unless architectural differences between the two operating system prevent it.

4.	An application must support long filenames and use them to display all document and data filenames in the shell, in title bars, in dialog boxes and controls, and with icons. In addition, an application should hide the extensions of filenames that are displayed within the application itself.

5.	An application should process Plug and Play events. For example, it should be aware of slow links and should react to system messages that occur when a new device is attached or removed.

The next three requirements apply to file-based applications that do not run in full screen mode. Some games and children's software run exclusively in full screen mode and need not follow these three requirements.

6.	An application must support Universal Naming Conventions (UNC) names for paths.

7.	An application must support OLE containers or objects, or both. It must also support the OLE style of drag and drop. An application should also support OLE automation and compound files (with document summary information included).

8.	An application must support simple mail enabling using the Messaging Application Programming Interface (MAPI) or the Common Messaging Call (CMC) API. That is, it must include Send Mail functionality.

The following items are modified requirements for utilities, such as disk optimizers and anti-virus software:

9.	Same as number 1, except for components that must use exclusive volume locking functions, soft interrupts, or components that must talk directly to 16-bit drivers. The user interface and other components of these applications must be 32 bits and use the Windows 95 thunking mechanism to access the 16-bit components.

10.	Same as number 2.

11.	Same as number 3, except for products like disk utilities that implement platform-specific functionality that does not make sense in Windows NT version 3.5.

12.	Same as number 4.

13.	Numbers 5 through 8 are recommended, but not required. However, number 6 is required if your product accesses network resources.

The following items are modified requirements for compilers and other development tools:

14.	In addition to the requirements that follow, if Windows is one of the target platforms of a compiler or development tool, the compiler or tool must be capable of generating applications that can meet all of the Windows 95 Logo requirements.

15.	Same as number 1.

16.	Same as  number 2, except that when icons are registered for each file type and the application, common source filename extensions, such as .C, .CPP, .H, and .HPP, are excluded.

17.	Same as number 3.

18.	Same as number 4.

19.	Same as number 5.

20.	Same as number 6.

21.	Compilers and development tools must support OLE in the following ways:

•	Support the OLE style of drag and drop (recommended within the tool's design environment).

•	Support OLE automation (recommended, but not required).

•	Provide an easy way to create applications with OLE container or object support, or provide this functionality by default.

22.	Same as number 8 (recommended, but not required).


 Personal Computer Systems

For a personal computer (PC) system to qualify for the Windows 95 Logo, it must meet a minimum set of requirements as outlined below and pass the System Compatibility Test (SCT) for Windows 95. The SCT tests are included in the Microsoft Windows 95 Device Driver Kit (DDK), along with instructions for OEM participation. System testing is OEM-administered, and results are sent to Microsoft Compatibility Labs (MCL).

A PC system must meet the following requirements:

1.	80386 or compatible processor. (However, 33-megahertz 80486 or better is recommended.)

2.	4 megabytes (MB) random-access memory (RAM). (However, 8 MB is recommended.)

3.	Plug and Play basic input/output system (BIOS) version 1.0a or later that reads back all resources. (However, a BIOS that soft-sets all resources is recommended.)

4.	Molded-in or permanently printed icon labels on the computer case for built-in ports. Ideally, icons on the cable connectors should match the icons on the computer case.

5.	Optional read-only memory (ROM) chips on expansion cards must use the Plug and Play header format documented in the Plug and Play BIOS specification.

6.	A Video Graphics Array (VGA) display adapter that uses a packed-pixel frame buffer and provides a resolution of at least 640 by 480 pixels and 8 bits per pixel (bpp) for desktop systems and a 64-shade gray scale for mobile systems. (However, VGA 1024 by 768 pixels and 8 bpp is recommended for desktop systems, and 64 colors is recommended for mobile systems.)

7.	One parallel port that supports IEEE-P1284-I mode protocols for compatibility mode and nibble mode. The system must be capable of receiving the parallel device's identifier in nibble mode. (However, ECP P1284-I is recommended.)

8.	One integrated or separate serial port, with 1-16550A required for mobile systems. Also recommended are 1-16550A for desktop systems, an additional PS/2 style port, pen devices with a barrel button, and serial infrared devices meeting the Infrared Data Association (IrDA) specification.

9.	Advanced Power Management (APM) version 1.1 is required for mobile systems. (However, it is recommended also for desktop systems.)

If the system ships with expansion cards or peripheral devices integrated onto the motherboard, it is recommended that the cards or devices meet the Windows 95 Logo specifications defined in this article and use 32-bit Windows 95 − based device drivers.

For more information about qualifying a PC for the Windows 95 Logo, see the Hardware Design Guide for Windows 95.


 Hardware Peripheral Devices

For a peripheral device to qualify for the Windows 95 Logo, it must meet the requirements described in the Hardware Design Guide for Windows 95 and pass the compatibility tests conducted by MCL. For information about prequalifying test tools and MCL device and driver submission details, see the Windows 95 DDK. The Windows 95 DDK also contains detailed information about designing Windows 95 − based device drivers.

To carry the Windows 95 Logo, a device driver must support the following Plug and Play capabilities in Windows 95:

1.	Retrieves configuration information from Configuration Manager.

2.	Is dynamically loadable.

3.	Is dynamically reconfigurable.

4.	Reacts to system messages that occur when a device is attached or removed.

An ideal Windows 95 − based Plug and Play driver requires minimal user interaction to select the proper driver. In addition, the settings for the device may need to change based on which user is logged in, whether the machine is docked or not, or both.


 Display Adapters

Display adapters must meet the following requirements:

1.	Support the VGA graphics standard.

2.	Support at least a 640- by 480-pixel, 8 bpp display driver. Desktop systems must be able to display at least 256 colors, and mobile systems must support an 8 bpp driver and map colors into at least a 64 gray scale display so that changes to higher-resolution external monitors can be made without restarting Windows 95.

3.	Use a packed-pixel frame buffer with at least 8 bpp.

4.	Use a VGA BIOS that, if it exists separately, has its base address fixed at C000h. (However, an alternate address is recommended.)

5.	Use a standard VGA with a page frame and I/O address resource that can be static — that is, not relocatable.

6.	Support the Video Electronics Standards Association (VESA) ergonomic timings.

7.	Be capable of being disabled if a conflicting VGA expansion card is added to the system.

8.	Provide at least one alternate configuration in case of conflict during initial program load (IPL) boot (non-VGA display resources only). The VGA BIOS must be able to use alternate configuration register addresses.

9.	Have the display adapter circuitry come up active when power is turned on or the system is reset. This requirement applies only to an Industry Standard Architecture (ISA) Plug and Play display adapter expansion cards used as a system boot device.


 Audio Adapters

Audio adapters must meet the following requirements:

1.	Be able to produce 22 kilohertz (kHz), 8-bit, monaural, output-only sound (minimum performance).

2.	Support either Sound Blaster or the Microsoft Windows Sound System to use built-in drivers for Windows 95.

3.	Use a one-eighth inch miniature phone jack wired for stereo as the output connector.

4.	Map the base input and output (I/O) address to configurations compatible with either Sound Blaster or the Microsoft Sound System.

5.	Support at least all interrupt request (IRQ) signals used either by Sound Blaster or the Microsoft Windows Sound System.

6.	Support the selection of at least three available Direct Memory Access (DMA) channels, either 8 bit or 16 bit, if DMA is supported.

7.	Support disabling in case of resource conflicts with other devices.


 Storage Devices

This section lists the requirements for storage devices, including floppy disk controllers, ATA (IDE) adapters, ATA (IDE) peripherals, small computer system interface (SCSI) host adapters, and SCSI devices.

Floppy Disk Controllers

Floppy disk controllers must meet the following requirements:

1.	Use at least three static I/O addresses: 3F2h, 3F4h, and 3F5h.

2.	Support IRQ6.

3.	Support at least DMA 2, if DMA is used. In addition, the controller should be capable of selecting at least two other available DMA channels, either 8 bit or 16 bit.

4.	Be capable of being independently disabled.

ATA (IDE) Adapters

ATA (IDE) adapters must meet the following requirements:

1.	Use the first device attached to the adapter as the boot device.

2.	Use the standard I/O addresses: 1F0h through 1F7h and 3F6h.

3.	Support at least IRQ14.

4.	Be capable of being disabled if an ATA (IDE) expansion card is added to the system. In addition, if a single adapter card contains a floppy disk drive controller, the adapter must be able to independently disable the floppy drive controller if a conflict occurs.

ATA (IDE) Peripherals

ATA (IDE) peripherals must meet the following requirements:

1.	Support the ATA Packet Interface (ATAPI) protocol for CD-ROMs defined in SFF-8020 version 1.2.

2.	Comply with the requirements specified in the ATA 2 specification.

3.	Set the signature after an ATA Read or ATA Identify Command is received.

4.	Implement the SEEK command and set the DSC bit when the ATAPI seek is complete, but not change the drive select bit.

5.	Return the CANNOT READ MEDIUM - INCOMPATIBLE FORMAT additional sense code qualifier when a READ is received on an audio track.

6.	Support CD-DA.

7.	Support the READ_CD command sector types mode 2 form 1, mode 2 form 2, mode 1 form 1, and mode 1 form 2.

8.	Support the Test_Unit_Ready command.

SCSI Host Adapters

SCSI host adapters must meet the following requirements:

1.	Meet the standards described in the current version of the Plug and Play SCSI specification.

2.	Support the SCSI Configured Auto-Magically (SCAM) Level 1 protocol for automatic SCSI identifier assignment.

3.	Use the 50-pin, high-density shielded device connector defined in the SCSI-2 standard (external SCSI peripheral subsystems only).

4.	Select at least three available DMA channels, either 8 bit or 16 bit, if DMA is supported.

5.	Support disabling in case of resource conflicts with other devices.

6.	Support automatic switchable termination for Plug and Play operation of internal, external, or mixed SCSI configurations.

SCSI Devices

SCSI® devices must meet the following requirements:

1.	Meet the standards described in the current version of the Plug and Play SCSI specification.

2.	Support the SCSI Configured Auto-Magically (SCAM) Level 1 protocol for automatic SCSI identifier assignment.

3.	Use the 50-pin, high-density shielded device connector defined in the SCSI-2 standard (external SCSI peripheral subsystems only).

4.	Use the drivers and receivers that meet the specifications defined in the single-ended alternative of the SPI.

5.	Use cables that conform to the cable requirements defined in clause 6 of the SPI specification.

6.	Ensure that external SCSI peripherals contain two connectors for the SCSI cable: a SCSI in connector and a SCSI out connector. The last peripheral in the chain uses a terminator on the SCSI out connector.

7.	Support the attachment of a permanent terminator to the end of the cable for internal SCSI peripherals.

8.	Ensure that internal SCSI peripherals do not terminate the SCSI bus.

9.	Ensure that terminations conform to the terminator requirements in the SPI specification over the terminator power (TERMPWR) voltage range of 4.0 to 5.25 VDC.

10.	Power terminators from the TERMPWR line on the SCSI bus.

11.	Provide overcurrent protection for the TERMPWR line or lines.

12.	Ensure that only terminators draw power from TERMPWR.

13.	Implement the SCSI Bus Parity signal defined in the SCSI-2 specifications.


 Parallel Port Devices

Parallel port devices (printers) must meet the following requirements:

1.	Meet the standards described in the current version of the Plug and Play Parallel Port Device specification.

2.	Comply with IEEE P1284-I.

3.	Support the compatibility and nibble mode protocols to read the device identifier from the peripheral.


 External Communications Devices

An external communications device must be able to identify itself using the identification method described in the Plug and Play External COM Device Specification.


 Modems

Modems must meet the following requirements:

1.	Support at least 9600 bits per second (bps) V.32 with V42/V42bis protocol for data modems.

2.	Support the TIA-602 (Hayes-compatible) AT command set, with extensions for flow control, V42/V42bis.

3.	Support fax capabilities of at least 9600 bps V.29 with class 1 (TIA-578A).

4.	Support Plug and Play device identification, using the appropriate Plug and Play specification (for example, ISA bus, COM port, PCMCIA slot, or LPT port).

5.	Support the 16550A compatible universal asynchronous receiver-transmitter (UART) interface.


 Network Adapters

Network adapters must meet the following requirements:

1.	Support the network driver interface specification (NDIS) 3.1 network device driver, which allows dynamic starting and stopping of the network card.

2.	Provide a means of automatically enabling the adapter as a boot device or enabling the adapter as a nonbootable device, if the network adapter is designed with Remote Initial Program Load (RIPL) capability.

3.	Do not hook Interrupt 18 and Interrupt 19 on ISA bus systems. This is a requirement for an ISA Plug and Play card.

4.	Support at least seven IRQ signals and enable/disable.

5.	Select at least three available DMA channels, either 8 bit or 16 bit, if DMA is supported.

6.	Support disabling in case of resource conflicts with other devices.


 Win32 Limitations in Windows 95

Microsoft® Windows® 95 implements some Microsoft® Win32® functions and messages differently than Microsoft® Windows NT™.


 About Windows 95 System Limitations

If you intend to run 32-bit applications on both platforms, you need to understand these differences to minimize development and debugging time.


 General Limitations

Some Win32 functions and messages, such as for security and event logging, are not supported by Windows 95. Windows 95 provides stub routines for these unsupported functions so that applications designed for other operating systems that fully support the Win32 application programming interface (API) can run with Windows 95 without errors.

By design, Win32 functions that take string parameters can handle either Unicode™ (wide character) or ANSI strings. However, Windows 95 does not implement the Unicode (or wide character) version of most Win32 functions. With few exceptions, these functions are implemented as stubs that simply return an error value. However, Windows 95 does provide Unicode implementations of the following functions.

ExtTextOut GetCharWidth GetTextExtentExPoint GetTextExtentPoint	MessageBox MessageBoxEx TextOut
In addition, Windows 95 implements the MultiByteToWideChar and WideCharToMultiByte functions for converting strings to and from Unicode.

Although all Boolean functions in the documentation for the Microsoft Win32 Software Development Kit (SDK) are described as returning 1 for TRUE and zero for FALSE, these return values are not necessarily true for Win32 functions in Windows 95. Instead, these functions are guaranteed to return a nonzero value for TRUE and zero for FALSE.


 Window Management (User)

Windows 95 implements some window management features in 16 bits. The use of 16 bits imposes some restrictions on parameters in functions and messages and places limits on internal storage. For example, the standard edit control is limited to somewhat less than 64 kilobytes (K) of text. In some cases, Windows 95 provides new features that can be used to avoid these restrictions and limitations, such as the rich edit control in which the amount of text is limited only by available memory.

The wParam parameter for the SendMessageCallback, SendMessageTimeout, and SendNotifyMessage functions is limited to a 16-bit value.

In Windows 95, the wParam parameter in list box messages, such as LB_INSERTSTRING or LB_SETITEMDATA, is limited to a 16-bit value. One effect of this limit is that 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. In contrast, a 64K data limit is imposed by Windows version 3.1.

Windows 95 permits up to 16,364 window handles and 16,364 menu handles. Although these limits are less than in Windows NT, they are significantly greater than the limits imposed by Windows version 3.1.

In Windows 95, the ActivateKeyboardLayout, GetKeyboardLayoutName, and UnloadKeyboardLayout functions do not support extended error code values; that is, you cannot retrieve errors for these functions by using the GetLastError function.

In Windows 95, only one desktop is available while the system runs. Although the thread desktop functions, GetThreadDesktop and SetThreadDesktop, are available under Windows 95, they do not do anything.

Any private application message must be defined above WM_USER + 0x100. A value above this will ensure that there is no collision between private messages and dialog box control messages.

Windows 95 automatically applies the standard three-dimensional shading and color scheme to dialog boxes created by applications marked as version 4.0 or later. Applications that are marked for earlier versions can still get the three-dimensional appearance by applying the DS_3DLOOK style to dialog boxes. If this style is used, the system automatically applies the three-dimensional look without requiring the application to check the operating system version. This is useful, for example, in applications developed for Windows NT version 3.5. The DS_3DLOOK style is ignored in Windows NT version 3.1.

The IDC_SIZE and IDC_ICON values used with the LoadCursor function are obsolete and should not be used in a Windows 95 − based application or in a Win32-based application that is marked as version 4.0.

In Windows 95, the MB_ICONQUESTION style used with the MessageBox, MessageBoxEx, and MessageBoxIndirect functions is obsolete. Win32-based applications should use the MB_ICONEXCLAMATION style instead. Similarly, applications should use the MB_ICONINFORMATION style instead of the MB_ICONASTERISK style and the MB_ICONSTOP style instead of the MB_ICONHAND style.


 Graphics Device Interface (GDI)

Windows 95 uses a 16-bit world coordinate system and restricts x- and y- coordinates for text and graphics to the range ±32K. Windows NT uses a 32-bit world coordinate system and allows coordinates in the range ±2 gigabytes (GB). If you pass full 32-bit coordinates to text and graphics functions in Windows 95, the system truncates the upper 16 bits of the coordinates before carrying out the requested operation.

Because Windows 95 uses a 16-bit coordinate system, the sum of the coordinates of the bounding rectangle specified by the Arc, Chord, Pie, Ellipse, and RoundRect functions cannot exceed 32K. In addition, the sum of the nLeftRect and nRightRect parameters or the nTopRect and nBottomRect parameters cannot exceed 32K.

In Windows 95, regions are allocated from the 32-bit heap and can, therefore, be as large as available memory. (In Windows version 3.1, regions were limited to 64K.) All other logical objects, however, share the 64K local heap. In addition, the number of region handles cannot exceed 16K.

To ensure that adequate space is always available for logical objects, applications should always delete objects when no longer needed. The following functions create objects that are placed in the local heap and have corresponding functions used to delete the objects.

Object	Create with	Delete with
Bitmap	CreateBitmap, CreateBitmapIndirect, CreateCompatibleBitmap, CreateDIBitmap, CreateDIBSection, CreateDiscardableBitmap	DeleteObject
Brush	CreateBrushIndirect, CreateDIBPatternBrush, CreateDIBPatternBrushPt, CreateHatchBrush, CreatePatternBrush, CreateSolidBrush	DeleteObject
Color space	CreateColorSpace	DeleteColorSpace
Device context (DC)	CreateDC,  GetDC	DeleteDC, ReleaseDC
Enhanced metafile	CloseEnhMetaFile, CopyEnhMetaFile, GetEnhMetaFile, SetEnhMetaFileBits	DeleteEnhMetaFile
Enhanced metafile DC	CreateEnhMetaFile	CloseEnhMetaFile
Extended pen	ExtCreatePen	DeleteObject
Font	CreateFont, CreateFontIndirect	DeleteObject
Memory DC	CreateCompatibleDC	DeleteDC
Metafile	CloseMetaFile, CopyMetaFile,  GetMetaFile, SetMetaFileBitsEx	DeleteMetaFile
Metafile DC	CreateMetafile	CloseMetaFile
Palette	CreatePalette	DeleteObject
Pen	CreatePen, CreatePenIndirect	DeleteObject
Region	CombineRgn, CreateEllipticRgn, CreateEllipticRgnIndirect, CreatePolygonRgn, CreatePolyPolygonRgn, CreateRectRgn, CreateRectRgnIndirect, CreateRoundRectRgn, ExtCreateRegion, PathToRegion	DeleteObject
Physical objects have always existed in global memory and are, therefore, not limited.

Windows 95 does not support world transformations that involve either shearing or rotations. The ExtCreateRegion function fails if the transformation matrix is anything other than a scaling or translation of the region.

In Windows 95, pens and brushes have several limitations. The ExtCreatePen function supports solid colors only (the PS_SOLID style), and the PS_ALTERNATE and PS_USERSTYLE styles are not supported. Geometric pens (the PS_GEOMETRIC style) are limited to the BS_SOLID brush style specified in the LOGBRUSH structure passed to ExtCreatePen. In addition, the following pen styles are supported in paths only.

PS_ENDCAP_FLAT PS_ENDCAP_ROUND PS_ENDCAP_SQUARE	PS_JOIN_BEVEL PS_JOIN_MITER PS_JOIN_ROUND
Windows 95 does not support the dashed or dotted pen styles, such as PS_DASH or PS_DOT, in wide lines. The BS_DIBPATTERN brush style is limited to an 8- by 8-pixel brush.

Windows 95 does not support brushes from bitmaps or device independent bitmaps (DIBs) that are larger than 8 by 8 pixels. Although bitmaps larger than 8 by 8 pixels can be passed to the CreatePatternBrush or CreateDIBPatternBrush function, only a portion of the bitmap is used to create the brush.

Windows 95 does not provide automatic tracking of the brush origin. An application is responsible for using the UnrealizeObject, SetBrushOrgEx, and SelectObject functions each time it paints using a pattern brush.

Windows 95 does not support the CBM_CREATEDIB value for the CreateDIBitmap function. The CreateDIBSection function should be used instead to create a DIB. CreateDIBSection is also available in Windows NT version 3.5.

If the biCompression member of the BITMAPINFOHEADER structure is the BI_BITFIELDS value, the bmiColors member of the BITMAPINFO structure contains three doubleword color masks that specify the red, green, and blue components, respectively, of each pixel. Windows 95 only supports the following color masks for 16 and 32 bits per pixel (bpp).

16bpp	The blue mask is 0x001F, the green mask is 0x03E0, and the red mask is 0x7C00.
16bpp	The blue mask is 0x001F, the green mask is 0x07E0, and the red mask is 0xF800.
32bpp	The blue mask is 0x000000FF, the green mask is 0x0000FF00, and the red mask is 0x00FF0000.
If the lpvBits parameter is NULL, the GetDIBits function fills in the dimensions and format of the bitmap in the BITMAPINFO structure pointed to by the lpbi parameter. In this case, if the function is successful, the return value in Windows 95 is the total number of scan lines in the bitmap. In Windows NT versions 3.1 and 3.5, however, the return value is 1 (TRUE), indicating success.

Deletion of drawing objects is slightly different in Windows 95 than in Windows NT. In Windows NT, if a drawing object (pen or brush) is deleted while it is still selected into a DC, the DeleteObject function fails. In Windows 95, the function succeeds, but the result is a nonfunctioning object. This nonfunctioning object is automatically destroyed when the DC is deleted.

When a path is constructed in Windows 95, only the following functions are recorded: ExtTextOut, LineTo, MoveToEx, PolyBezier, PolyBezierTo, Polygon, Polyline, PolylineTo, PolyPolygon, PolyPolyline, and TextOut.

In Windows 95, the GetGraphicsMode and SetGraphicsMode functions support the GM_COMPATIBLE value only. The GM_ADVANCED value is not supported.

In Windows 95, the DeviceCapabilities function returns  − 1 when called with the DC_FILEDEPENDENCIES value because that capability is not supported. In Windows 95, DeviceCapabilities supports the following additional capabilities.

DC_DATATYPE_PRODUCED	Retrieves an array of strings containing the data types that the printer driver supports. A return value of   − 1 indicates that the printer driver only understands device-specific commands (in other words, "RAW" data) that are native to the printer. A return value of 2 or more indicates the number of strings in the array.
DC_EMF_COMPLIANT	Returns a flag that indicates if the specified printer driver is capable of accepting an enhanced metafile (EMF) spooled by the system (that is, the printer driver is EMF-compliant). The function returns 1 if the printer driver is EMF-compliant and  − 1 if the printer driver is not.
Although Windows 95 imposes no restrictions on the PlayEnhMetaFile and PlayEnhMetaFileRecord functions, the files and records that these functions execute are subject to the limitations described in this section. For example, the functions ignore records that attempt to draw outside of the 16-bit coordinate space or that apply shearing or rotation to world transformations.

In Windows 95, the maximum length of the description string for an enhanced metafile is 16K. This limit applies to the GetEnhMetaFileDescription, GetEnhMetaFileHeader, and GetEnhMetaFile functions.

In Windows 95, the dmDeviceName member of the DEVMODE structure specifies the "friendly" name of the printer, which may be set to any user-defined value. Windows 95, however, does not support the the following members; they are included for compatibility with Windows NT.

dmBitsPerPel dmDisplayFlags dmDisplayFrequency	dmFormName dmPelsHeight dmPelsWidth
Windows 95 does not support print monitor dynamic-link libraries (DLLs) that have been developed for Windows NT. To add a monitor using the AddMonitor function, you must specify a monitor DLL that has been explicitly created for Windows 95. The following printing and print spooling functions are not available in Windows 95.

AddForm AddPrinterConnection ConnectToPrinterDlg DeleteForm DeletePrinterConnection EnumForms FindClosePrinterChangeNotification	FindFirstPrinterChangeNotification FindNextPrinterChangeNotification GetForm ResetPrinter SetForm WaitForPrinterChange
In Windows 95, the SetPrinter function ignores the pShareName member of the PRINTER_INFO_2 structure. The PRINTER_INFO_3 and PRINTER_INFO_4 structures used with the SetPrinter, GetPrinter, and EnumPrinters functions are not supported in Windows 95. The PRINTER_INFO_5 structure, which is available in Windows 95, is not supported in Windows NT versions 3.1 and 3.5.

The PRINTER_ENUM_CONNECTIONS value used with the EnumPrinters function is not supported in Windows 95. The DOC_INFO_2 structure used with the StartDocPrinter function and the PORT_INFO_2 structure used with the EnumPorts function are not supported in Windows NT versions 3.1 and 3.5.

Windows 95 supports the DRAWPATTERNRECT printer escape.

Win32-based applications that send output to PostScript™ printers should use the GetDeviceCaps function to check for the PC_PATHS value to determine whether to use path functions or printer escapes to draw paths. Applications should use paths functions whenever possible. The following example shows how to check for this capability.

// Determine whether to use path functions on the device.
// hDC is the output device.

OSVERSIONINFO osvi;

osvi.dwOSVersionInfoSize = sizeof(osvi);
GetVersionEx(&osvi);

if ((osvi.dwPlatformId == VER_PLATFORM_WIN32_NT) ||
     ((osvi.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) &&
       (GetDeviceCaps(hDC, POLYCAPS) & PC_PATHS)))
    bUsePaths = TRUE;
else
    bUsePaths = FALSE;

In Windows 95, printer drivers typically set this capability to zero. This means that Win32-based applications sending output to Postscript printers need to use the ExtEscape function and the printer-specific escapes to draw paths at the printer. (The Escape function cannot be used for this.)

In Windows NT, the string specified in the lpszDeviceName parameter of the EnumDisplaySettings function must be of the form "\\.\DisplayX", where X can be 1, 2, or 3. In Windows 95, lpszDeviceName must be NULL.


 System Services (Kernel)

The extended error codes returned by the GetLastError function are not guaranteed to be the same in Windows 95 and Windows NT. This difference applies to extended error codes generated by calls to GDI, window management, and system services functions.

Windows 95 does not support asynchronous file input and output (I/O), except on serial devices. Therefore, the ReadFile and WriteFile functions will fail if you pass in an overlapped region on anything other than a serial device. The GetOverlappedResult function works only on serial devices or on files opened by using the DeviceIoControl function.

In Windows 95, the ReadFileEx and WriteFileEx functions will fail if you pass in the handle of a serial device (for example, COM2). ReadFile and WriteFile, however, accept the handle of a serial device.

In Windows NT, the FileTimeToDosDateTime and DosDateTimeToFileTime functions allow dates up to 12/31/2107. In Windows 95, these functions allow dates up to 12/31/2099.

The precision of the time for a file on a file allocation table (FAT) file system volume is 2 seconds. If Windows 95 is connected through a network to a different file system, the time precision is limited only by the remote device.

In Windows NT, the DeleteFile function fails if you attempt to delete a file that is open for normal I/O or is opened as a memory mapped file. In Windows 95, DeleteFile deletes such files. Because deleting open files may cause loss of data and application failure, you must take every precaution to close files before attempting to delete them by using DeleteFile.

In Windows 95, fixed memory blocks cannot be reallocated to be movable. The GMEM_MODIFY and GMEM_MOVEABLE combination of values has no effect when a memory block is reallocated by using the GlobalReAlloc function. Similarly, the LMEM_MODIFY and LMEM_MOVEABLE combination has no effect when a memory block is reallocated by using the LocalReAlloc function.

In Windows 95, committing memory for a page that is already committed is an expensive operation that has no ultimate effect (it is expensive because additional storage is allocated and subsequently freed for each committed page). When committing memory by using the VirtualAlloc function, an application should specify only the pages that actually need to be committed.

Although applications can request that memory allocation be at a specific virtual address, applications must not depend on any given address range always being available on every operating system. Applications can query the address space by using the GetSystemInfo function.

In Windows 95, memory allocated by Win32-based applications falls in the address range 4 megabytes (MB) − 2GB for private memory and 2GB − 3GB for shared memory (shared mapped files). The PAGE_WRITECOPY and PAGE_GUARD access protection values are not supported. Instead of using the PAGE_GUARD value and handling the EXCEPTION_GUARD_PAGE exception, applications can use the PAGE_NOACCESS value and handle the EXCEPTION_ACCESS_VIOLATION exception.

The SEC_IMAGE and SEC_NOCACHE values for the fdwProtect parameter of the CreateFileMapping function are not supported in Windows 95. In addition, the dwMaximumSizeHigh parameter of CreateFileMapping is ignored in Windows 95, so applications should specify zero for the parameter.

In Windows 95, shared memory mapped files that are created by using the MapViewOfFileEx function appear in the same address space across all 32-bit processes in the system. If you pass in a specific base offset in the lpvBase parameter of MapViewOfFileEx and the function succeeds, you are guaranteed that the same memory region is available in every process. This is not true in Windows NT because MapViewOfFileEx fails for any process that already has the given memory region in use.

Coherence guarantees that the data accessible in a file view is an identical copy of the file's contents on disk. In Windows 95, file views derived from a single file-mapping object are coherent only if the file is accessed through one of the views. A view of a file is not guaranteed to be coherent if the file is accessed by normal file I/O functions, such as ReadFile or WriteFile, or by views created from a different file-mapping object.

If you close a file handle that was used to create a file mapping object, both Windows NT and Windows 95 hold the file open until you unmap the last view of the file by using the UnmapViewOfFile function. However, Windows NT holds the file open with no sharing restrictions, whereas Windows 95 holds it open using the sharing restrictions of the original file handle. To ensure exclusive access to a file in Windows NT, the file handle must remain open for the life of the file-mapping object. Because Windows 95 retains the sharing restrictions, both the file handle and the handle to the file-mapping object may be closed after calling MapViewOfFile and exclusive access to the file is ensured.

In Windows 95, if the FILE_MAP_COPY value is specified for the fdwAccess parameter of MapViewOfFile (or MapViewOfFileEx), the hMapObject parameter must have been created with the PAGE_WRITECOPY value. In addition, the dwOffsetHigh parameter of MapViewOfFile (or MapViewOfFileEx) is ignored, so applications should specify zero for the parameter.

Windows 95 implements copy-on-write file mappings slightly differently than Windows NT. In Windows 95, a call to MapViewOfFile with FILE_MAP_COPY returns an error unless PAGE_WRITECOPY was used with the CreateFileMapping function. In both Windows NT and Windows 95, creating the map with PAGE_WRITECOPY and the view with FILE_MAP_COPY produces a view to the file that makes the pages swappable and prevents modifications from going to the original data file. In Windows 95, PAGE_WRITECOPY must be passed to CreateFileMapping, but this is optional in Windows NT.

If you share the mapping between multiple processes by using the DuplicateHandle or OpenFileMapping function and one process writes to a view, the modifications will not be propagated to the other process in Windows NT. However, the modifications will be propagated in Windows 95. The original file, though, will not change on either platform.

In Windows 95, the CreateFile function does not support the standard "\\.\C:" and "\\.\PhysicalDrive0" formats used to gain access to the logical or physical drives. To gain access, applications must specify a virtual device (VxD) name instead and use the DeviceIoControl function to send requests through the VxD to the logical and physical drives. For more information, see "Device I/O Control."

In Windows 95, the DuplicateHandle function cannot duplicate handles of registry keys as it can in Windows NT. The function returns an error if an application attempts to duplicate the handle of a registry key. In addition, when a file handle is duplicated, the duplicated handle will not be granted more access than the original.

The LoadLibrary function does not support loading 16-bit DLLs into a Win32 process.

Thread locales, retrieved and set by using the GetThreadLocale and SetThreadLocale functions, are static and can only be changed at system boot time.

In Windows 95, the FlushInstructionCache function always returns TRUE. Windows 95 supports single processor machines only.

In Windows 95, a call to the FreeResource function must be included for every call to the LoadResource function. The call to FreeResource allows the system to discard a resource that an application no longer needs. Windows NT automatically frees resources, so a call to FreeResource is not required.

The SYNCHRONIZE standard access rights flag is not supported in Windows 95. The following functions are affected.

DuplicateHandle	OpenSemaphore
MsgWaitForMultipleObjects	WaitForMultipleObjects
OpenEvent	WaitForMultipleObjectsEx
OpenMutex	WaitForSingleObject
OpenProcess	WaitForSingleObjectEx
The Windows 95 registry does not allow key names containing control characters. In addition, if the lpszSubKey parameter is an empty string (""), the RegDeleteKey function deletes the key identified by the hKey parameter.

In Windows 95, the RegCreateKeyEx function creates a non-volatile key even if the REG_OPTION_VOLATILE value is specified.


 Multimedia

The sndAlias macro is not supported in Windows 95. In addition, the SND_ALIAS and SND_ALIAS_ID values for the PlaySound function are not supported in Windows 95.

The Windows 95 multimedia functions are not designed to be used by two or more threads in the same process. Although most multimedia functions will work if they are called by multiple threads, some are likely to fail. Functions that are particularly likely to fail include PlaySound, any of the functions that prepare or unprepare headers, and any of the open and close functions. PlaySound can never be used simultaneously by multiple threads in the same process. The functions that prepare or unprepare headers and the open and close functions can be used simultaneously by multiple threads in the same process, but only if they do not pass the same structure.


 Version Differences

This article describes the differences in the way Windows 95 treats applications based on their subsystem version numbers. It is intended to help you identify areas in an application written for Windows version 3.x that you must revise to take advantage of the new features provided by Windows 95.


 About Version Differences

The Microsoft® Windows® 95 operating system supports Windows-based applications that have a subsystem version number of either 3.x or 4.0. An application's subsystem version number is set by the linker.


 General Window Management Differences

When a version 4.0 application uses the SetWindowLong function (with GWL_STYLE) to change a window's style, Windows 95 sends the window a WM_STYLECHANGING message before changing the style. The message's lParam parameter is the address of a STYLESTRUCT structure. The styleOld and styleNew members of the structure specify the old and new styles. By processing WM_STYLECHANGING, an application can inspect the styles and perhaps change them.

Windows 95 sends the WM_STYLECHANGED message after changing the style. Again, the lParam parameter is the address of a STYLESTRUCT structure that specifies the new styles. The application can use WM_STYLECHANGED to update any style-dependent information stored in the application's internal data structures.

Windows 95, however, does not send the WM_STYLECHANGING and WM_STYLECHANGED messages to a version 3.x application.

A version 4.0 application cannot use the SetWindowLong function to set the WS_EX_TOPMOST style for a window or to remove the style from a window. The application must use the SetWindowPos function to set or remove the WS_EX_TOPMOST style.

Windows 95 automatically adds and removes the WS_EX_WINDOWEDGE style for windows in both version 3.x and 4.0 applications. In a version 3.x application, Windows 95 adds the WS_EX_WINDOWEDGE style to a window if, in version 3.1, the window would have a dialog border or a sizable border. Windows 95 removes the WS_EX_WINDOWEDGE style if the window's style changes so that it would no longer have a dialog border or sizable border in version 3.1. Windows 95 uses similar criteria for adding and removing the WS_EX_WINDOWEDGE style for a Windows version 4.0 application, except that any window that has a title bar receives the WS_EX_WINDOWEDGE style, regardless of the window's other border styles.

When the user drags the icon of a minimized window created by a version 3.x application, Windows 95 sends the window a WM_QUERYDRAGICON message to retrieve the cursor to use while dragging. Windows 95 also sends WM_QUERYDRAGICON to retrieve the icon to display in the task-switch window that appears when the user presses the ALT+TAB key combination. Windows 95 does not send WM_QUERYDRAGICON to a window created by a version 4.0 application. Instead, the application is expected either to use the WM_SETICON and WM_GETICON messages or to set the big and small icons when registering the window class.

When a window in a version 4.0 application loses the mouse capture as a result of a call to the SetCapture function, the window receives a WM_CAPTURECHANGED message, but Windows 95 sends the message asynchronously. In other words, the window receives the message, but possibly not right away. Some of the ways in which a window can lose the mouse capture include:

•	The user activated a different application by clicking one of its windows.

•	The DefWindowProc function changed the capture in response to a WM_CANCELMODE message.

•	Another window using the same message queue called the SetCapture function. (All 16-bit applications share the same queue, but each 32-bit thread has its own queue.)

If a child window in a version 3.x application has the WS_EX_NOPARENTNOTIFY style, Windows 95 disregards the style when the user clicks the child window. That is, Windows 95 sends the WM_PARENTNOTIFY message to all windows in the parent chain regardless of whether the child window has the WS_EX_NOPARENTNOTIFY style. If a child window in a version 4.0 application has this style, Windows 95 does not send WM_PARENTNOTIFY messages when the user clicks the child window.

In a version 3.x application, it is possible for the horizontal coordinate on the left side of a window's client area to be greater than that on the right side. This happens because version 3.x sometimes incorrectly handles an empty client rectangle that contains a vertical scroll bar. (Fixing the problem would cause some applications to generate general protection faults.) In a version 4.0 application, it is not possible for the horizontal coordinate of the left side of a client area to be greater than that of the right side.


 Dialog Boxes

A dialog box created by a version 4.0 application automatically receives the DS_3DLOOK style. This style gives three-dimensional borders to child controls in the dialog box and draws the entire dialog box using the three-dimensional color scheme. The DS_3DLOOK style is available to a dialog box created by a version 3.x application, but you must explicitly add the style to the dialog box template. The application that creates the dialog box determines the version number of the dialog box.

Windows 95 performs a strict validation check on the DS_ styles specified in a dialog box template. If the template contains any styles that Windows 95 does not recognize and a version 4.0 application is creating the dialog box, the creation fails. If a version 3.x application is creating the dialog box, the system debugger generates a warning, but Windows 95 creates the dialog box anyway.


 Buttons

The parent window of a button (except push buttons) in a version 3.x application receives a WM_CTLCOLORBTN message when the button is about to be drawn. In a version 4.0 application, however, the parent window of a button receives the WM_CTLCOLORSTATIC message, which retrieves a color appropriate for drawing text on the background of the dialog box. Windows 95 sends WM_CTLCOLORSTATIC to retrieve the background and text colors for the text area of check boxes, radio buttons, and group buttons. An application should process WM_CTLCOLORSTATIC in order to correctly set the colors of any dialog box item that contains text and appears directly on the dialog area.

Windows 95 perform default handling of the WM_CTLCOLORBTN message differently depending on an application's version. For a version 3.x application, the default handling for button colors is to use the COLOR_WINDOW value for the background color and the COLOR_WINDOWTEXT value for the foreground color. For a version 4.0 application, Windows 95 uses the COLOR_3DFACE value for the background and the COLOR_BTNTEXT value for the foreground.

In a version 3.x application, a push button's outer top left corner is nonwhite because the button is typically drawn on a white background. If the border was white, the background would appear to bleed into the button. In a version 4.0 application, a push button's outer top left corner is white (COLOR_3DHILIGHT) because the button is typically drawn on a nonwhite background (COLOR_3DFACE).


 Edit Controls

In a version 3.x application, an edit control that is the descendant of an inactive window takes the input focus when the user clicks the control; an edit control in a version 4.0 application does not. Not taking the input focus prevents the situation where the user can enter text into what appears to be an inactive window.

An edit control in a version 3.x application retrieves its text and background colors by sending the WM_CTLCOLOREDIT message to its parent window. In a version 4.0 application, an edit control sends the WM_CTLCOLOREDIT or WM_CTLCOLORSTATIC message. The edit control sends WM_CTLCOLORSTATIC if it is disabled or read-only; otherwise, it sends WM_CTLCOLOREDIT. In addition, a disabled multiline edit control in a version 4.0 application uses the COLOR_GRAYTEXT value as its text color.

A multiline edit control in a version 4.0 application has a proportional scroll box (thumb), but a multiline edit control in a version 3.x application does not.

In a version 3.x application, the wParam parameter of the EM_REPLACESEL message is not used. In a version 4.0 application, the wParam parameter is a flag that specifies whether the replacement operation can be undone.


 List Boxes

In a version 4.0 application, a list box that is part of a combo box uses the WM_CAPTURECHANGED notification message to hide its drop-down list if it is open. For more information, see "Combo Boxes" later in this topic.

The DDL_EXCLUSIVE flag of the DlgDirList function does not have the expected result in a version 3.x application. Specifically, the flag does not exclude read-write files from the list. In a version 4.0 application, the DDL_EXCLUSIVE flag excludes read-write files.

If a list box in a version 3.x application has either the WS_HSCROLL or WS_VSCROLL style, the list box receives both horizontal and vertical scroll bars. Although one of the scroll bars is typically hidden, Windows 95 displays the hidden scroll bar if its scrolling range becomes greater than zero. In a version 4.0 application, a list box does not receive a horizontal scroll bar, unless it has the WS_HSCROLL style. Likewise, it does not receive a vertical scroll bar unless it has the WS_VSCROLL style.

When creating a list box in a version 3.x application, Windows 95 always increases the size of the list box by adding the border width to each side. This is done because Windows 95 assumes that the dimensions specified by the application or the dialog template are for the client area of the list box. Unfortunately, increasing the size in this way makes aligning a list box rather difficult. Windows 95 does not increase the size when creating a list box in a version 4.0 application; Windows 95 assumes that the specified size includes the borders.


 Combo Boxes

A combo box in a version 4.0 application passes the control color messages (WM_CTLCOLOR*) from its child components (edit control and list box) to the parent window of the combo box. In a version 3.x application, a combo box passes those messages to the DefWindowProc function.

A combo box in a version 4.0 application uses the WM_CAPTURECHANGED message to hide its drop-down list box if it is open. Windows 95 sends the message when another window takes the mouse capture, which typically happens when the user clicks another window. In a version 3.x application, a combo box does not use WM_CAPTURECHANGED to hide the drop-down list.

A combo box in a version 3.x application uses the WM_CTLCOLORLISTBOX message to retrieve the text and background colors. In a version 4.0 application, a combo box uses the WM_CTLCOLOREDIT or WM_CTLCOLORSTATIC message instead. The combo box uses WM_CTLCOLORSTATIC if it is disabled or contains a read-only selection field (in an edit control); otherwise, it uses WM_CTLCOLOREDIT.

In a version 3.x application, the background of the static text area in read-only combo boxes is filled with the system highlight color (COLOR_HILIGHT). In a version 4.0 application, Windows 95 fills the background of the static text area only for a combo box that is not owner drawn.

In a version 4.0 application, Windows 95 adds the ODS_COMBOBOXEDIT value to the itemState member of the DRAWITEMSTRUCT structure when Windows 95 sends the WM_DRAWITEM message to the parent window of an owner-drawn combo box to draw an item in the selection field. The ODS_COMBOBOXEDIT value tells the parent window that the drawing takes place in the selection field of the combo box rather than in the list box.


 Menus

A 16-bit version 3.x application that creates or loads a menu is considered to be the owner of the menu. However, when the application exits, the menu is "orphaned" until no 16-bit version components for Windows version 3.x remain. For 16-bit version 4.0 applications and all 32-bit applications, the application that creates the menu is the owner, and the menu is destroyed as soon as the application exits. Unlike graphics device interface (GDI) objects, there is no way to change the ownership of a menu.

In a version 3.x application, the Close command cannot be deleted from the System menu of an multiple document interface (MDI) child window. In a version 4.0 application, the Close command can be deleted.

Windows 95 increases the width of hierarchical, owner-drawn menu items in a version 3.x application. Some applications rely on this increased width and use it to include icons that simulate toolbars. In a version 4.0 application, Windows 95 does not automatically increase the width of hierarchical, owner-drawn menu items.

The wParam parameter of the WM_MENUSELECT message is interpreted differently depending on the subsystem version number of the application and whether the application is written for 16 or 32 bits:

•	In a 16-bit version 3.x application, the wParam parameter is the handle of the pop-up menu if the selected item activates a pop-up menu.

•	In a 16-bit version 4.0 application, wParam is the identifier of the menu item, regardless of whether the item activates a pop-up menu.

•	In a 32-bit application (both subsystem versions), the low-order word of wParam is the identifier of the menu item or, if the item activates a pop-up menu, the index of the pop-up menu. This high-order word contains the menu flags.


 System Bitmaps and Colors

In 16-bit version 3.x applications, purpose windows, such as dialog boxes, message boxes, and system-defined control windows, receive WM_CTLCOLOR messages when they are about to be drawn. The high-order word of the lParam parameter indicates the type of special purpose window about to be drawn (CTLCOLOR_BTN, CTLCOLOR_EDIT, and so on). By default, a special purpose window passes the WM_CTLCOLOR message to the parent or owner window (for both subsystem versions), allowing the parent or owner to set the foreground and background colors of the special purpose window. The same is true for 32-bit applications, except that the special purpose window receives one or more of the following messages instead of WM_CTLCOLOR.

WM_CTLCOLORBTN WM_CTLCOLORDLG WM_CTLCOLOREDIT WM_CTLCOLORLISTBOX	WM_CTLCOLORMSGBOX WM_CTLCOLORSCROLLBAR WM_CTLCOLORSTATIC
In 32-bit applications, the message itself indicates the type of special purpose window about to be drawn. The lParam parameter contains the window's 32-bit handle.

Display drivers for Windows version 3.x provide the bitmaps, icons, and cursors used by previous versions of Windows. Because Windows 95 renders and scales the system bitmaps, icons, and cursors itself, its display drivers do not (and should not) contain any OBM_, OIC_, or OCR_ resources.

For a version 3.x application, the default handling of the WM_CTLCOLORSTATIC and WM_CTLCOLORDLG messages is to use the COLOR_WINDOW value for the background and the COLOR_WINDOWTEXT value for the foreground. For a version 4.0 application, Windows 95 uses the COLOR_3DFACE value for the background and the COLOR_WINDOWTEXT value for the foreground.

When an application calls the GetClientRect function to retrieve the client rectangle of a minimized window created by a version 3.x application, Windows 95 retrieves the old dimensions for a minimized window (0, 0, 36, 36). For a minimized window in a version 3.1 or 4.0 application, Windows 95 retrieves 0, 0, GetSystemMetrics(SM_CXMINIMIZED), GetSystemMetrics(SM_CYMINIMIZED). These metrics change if the user changes the title bar height or minimized window width by using Control Panel. In other words, the GetClientRect function returns the dimensions of the entire minimized window, preventing an application from causing a general protection (GP) fault because of an unexpectedly empty client rectangle.


 System Metrics

When a version 3.x application calls the GetSystemMetrics function to retrieve the SM_CYVSCROLL or SM_CYHSCROLL metric value, the function returns a value that is one pixel more than the actual height of the corresponding type of standard scroll bar. Windows 95 adds a pixel because applications written for previous versions of windows routinely subtract one pixel from the return value. Subtracting one pixel accounts for the way a standard scroll bar in a version 3.x application overlaps the border of the window in which it resides. A version 4.0 application receives the actual height of the scroll bar.

When a version 3.x application retrieves the SM_CXDLGFRAME and SM_CYDLGFRAME system metric values, GetSystemMetrics returns a value that is one pixel less that the actual frame width or height. A version 4.0 application receives the actual width or height.

GetSystemMetrics returns one pixel more than the actual height of a title bar when a version 3.x application requests the SM_CYCAPTION system metric value. A version 4.0 application receives the actual height of the title bar.

GetSystemMetrics returns one pixel less than the actual height of a menu bar when a version 3.x application requests the SM_CYMENU system metric value. A version 4.0 application receives the actual height of the menu bar.

When a version 3.x application calls GetSystemMetrics to retrieve the SM_CYFULLSCREEN value (height of a maximized window's client area), the function returns a value that is one pixel less than the actual height. This is because GetSystemMetrics returns one pixel more than the actual title bar height when an application retrieves the SM_CYCAPTION value. (The sum of the height of a maximized window's client area and the height of a title bar must equal the height of the working area of the screen.) A version 4.0 application receives the actual height of the maximized window's client area when it requests the SM_CYFULLSCREEN value.


 Parameter Validation

If a 32-bit version 3.x application specifies invalid class styles when calling the RegisterClass function, Windows 95 strips out the invalid bits and generates warnings in the system debugger, but allows RegisterClass to succeed anyway. If a 32-bit version 4.0 application passes invalid class styles to RegisterClass, the function fails.

In a version 3.x application, Windows 95 does not validate the length member of the WINDOWPLACEMENT structure that is passed to the GetWindowPlacement and SetWindowPlacement functions. The length member, however, is validated for a version 4.0 application; Windows 95 fails these functions if the value of length is incorrect.

Windows 95 does not validate the cbSize member of the STARTUPINFO structure specified in the CreateProcess and GetStartupInfo functions for applications written for Windows version 3.x. The cbSize member is validated, however, for version 4.0 applications.

In the debugging version of Windows 95, the system fills the specified buffer with zeros up to the length specified by the cbSize parameter when a version 4.0 application calls the LoadString function. The buffer is not filled with zeros for a version 3.x application.


 Using Common Controls and Dialog Boxes

This article explains how a developer can create an Explorer-like application that displays real-estate listings for houses.


 About Using Common Controls and Dialog Boxes

The Microsoft® Windows® 95 shell looks quite a bit different from the shell used currently by Windows version 3.1x and Microsoft® Windows NT™. This new shell includes Explorer, which integrates the functionality of File Manager and Program Manager in Windows 3.1x. Explorer uses many of the new Windows 95 common controls and follows the guidelines specified in The Windows Interface Guidelines for Software Design.

Because Explorer follows the interface guidelines so closely and uses many of the new Windows 95 controls, developers may want to use it as a model for their new Windows 95−based applications.

This article is based on the article "Creating a Windows 95 Explorer-like Application" and the CHICOAPP sample application, both by Nancy Cluts, available in the Microsoft Developer Network Development Library.


 Appearance of Explorer

Explorer includes some new interface objects, such as a toolbar, a status bar, a tree view control, and a list view control. These controls work together to provide a usable and intuitive interface for the objects contained in the system. For more information about these new controls, see the documentation included in the Microsoft® Win32® Software Development Kit (SDK) and the six part series of articles entitled "Win32 Common Controls" in the Microsoft Developer Network Development Library (under Technical Articles), written by Nancy Cluts.

The new controls are provided in a dynamic-link library (DLL) called COMCTL32.DLL. The COMCTL32.DLL file is included in Windows 95 and will also be supported in Microsoft® Win32s® (running with Windows version 3.1x) and in Windows NT. The new controls are 32-bit only; they will not be supported in 16-bit Windows environments.

The following illustration shows the Windows 95 Explorer.


 Designing the Sample Application

The sample application displays a real estate listing with the following functionality:

•	A toolbar at the top of the screen with tooltip controls for easy access to commands.

•	A status window at the bottom of the screen displaying the currently selected city and the number of houses listed for that city.

•	A tree view control displaying the cities that have houses for sale.

•	A list view control displaying the houses for sale.

•	A pop-up context menu that can be displayed by mouse clicking.

•	Property sheets for viewing and changing house properties.

•	Long filename support for saving and opening house listing files.

The following illustration shows the finished application. It displays the main screen with an open listing for the city of Seattle.

The application-defined structures used to hold the data for the sample application follow. For more information about how these structures are used, see the section "Parsing and Storing the Data" later in this topic.

typedef struct tagCITYINFO

{

    char szCity[MAX_CITY];  // city name

    int NumHouses;          // number of houses listed in city

    HTREEITEM hItem;        // handle of tree view item

} CITYINFO;

typedef struct tagHOUSEINFO

{

    char szAddress[MAX_ADDRESS];  // address

    char szCity[MAX_CITY];        // city

    int iPrice;                   // price

    int iBeds;                    // number of bedrooms

    int iBaths;                   // number of bathrooms

    int iImage;                   // bitmap index for house

    char szAgent[MAX_CITY];       // listing agent

    char szNumber[MAX_CITY];      // listing agent's phone number

} HOUSEINFO;

The following constants and global variables are used in the sample application.

// Global variables

#define NUM_BUTTONS 8

#define TEMP_LEN 10

// Structure containing information about the for sale listing.

LISTINFO g_Listing;

// Arrays to hold house and city information.

HOUSEINFO rgHouses[MAX_HOUSES];

CITYINFO  rgCities[MAX_CITIES];

// File input and output (I/O) global variables.

OPENFILENAME OpenFileName;

TCHAR        szDirName[MAX_PATH]   = TEXT("");

TCHAR        szFile[MAX_PATH]      = TEXT("\0");

TCHAR        szFileTitle[MAX_PATH];

// Filter specification for the OPENFILENAME structure.

TCHAR szFilter[] = TEXT("Text Files (*.TXT)\0*.TXT\0All Files (*.*)\0*.*\0");

char *lpBufPtr;


 Creating the Windows

Because the windows used in the sample application are part of the Windows 95 common control library, you must call InitCommonControls to ensure that COMCTL32.DLL is loaded before calling any functions that use the new common controls. The status window has two parts: the left part, which displays the currently selected city, and the right part, which displays the number of houses listed for that city. The following example demonstrates how the status bar is implemented and calls helper functions to create the toolbar and the list view and tree view windows.

BOOL CreateAppWindows( HWND hwndParent )

{

    RECT rcl;

    int lpSBParts[2];

    static TCHAR szBuf[MAX_PATH];

    // Make sure that the common control library is loaded.

    InitCommonControls();

    // Get the size and position of the parent window.

    GetClientRect(hwndParent, &rcl);

    // First, create the status window.

    g_Listing.hWndStatus = CreateStatusWindow(

    WS_CHILD | WS_BORDER | WS_VISIBLE,  // window styles

    TEXT(""),                           // default window text

    hwndParent,                         // parent window

    ID_STATUS);                         // identifier

    if (g_Listing.hWndStatus == NULL)

         MessageBox (NULL, TEXT("Status Bar not created!"), NULL,
                     MB_OK );

    // Make the multiple parts for the status window.

    lpSBParts[0] = (rcl.right - rcl.left) / 2;

    lpSBParts[1] = -1;

    SendMessage(g_Listing.hWndStatus, SB_SETPARTS, (WPARAM)2,
    (LPARAM)&lpSBParts);

    // Set the text for the status window.

    ChangeSBText(g_Listing.hInst, g_Listing.hWndStatus, -1);

    // Next, create the toolbar.

    g_Listing.hWndToolBar = CreateTheToolbar(hwndParent);

    if (g_Listing.hWndToolBar == NULL )

        MessageBox (NULL, "Toolbar Bar not created!", NULL, MB_OK);

    // Create the list view window.

    g_Listing.hWndListView = LV_CreateListView(hwndParent,
    g_Listing.hInst, g_Listing.NumHouses, &rgHouses[0]);

    if (g_Listing.hWndListView == NULL)

    {

        MessageBox (NULL, "Listview not created!", NULL, MB_OK );

        return FALSE;

    }

    // Create the tree view window, and initialize its

    // image list.

    g_Listing.hWndTreeView = TV_CreateTreeView(hwndParent,
    g_Listing.hInst, g_Listing.NumCities, rgCities);

    if (g_Listing.hWndTreeView == NULL)

    {

        MessageBox(NULL, TEXT("Tree View not created!"), NULL, MB_OK);

        return FALSE;

    }

    return TRUE;

}

VOID ChangeSBText(HINSTANCE hInst, HWND hwnd, int iNumSelected)

{

    static TCHAR szBuf1[MAX_LEN];

    static TCHAR szBuf2[MAX_LEN];

    static TCHAR szSelected[MAX_LEN];

    TCHAR szText[MAX_ITEMLEN];

    int NumHouses;

    if (szBuf1[0] == '\0')

        LoadString (hInst, IDS_SELECTED, szBuf1, sizeof(szBuf1));

    if (szBuf2[0] == '\0')

         LoadString (hInst, IDS_NUMHOUSES, szBuf2, sizeof(szBuf2));

    if (iNumSelected == -1)

    {

        lstrcpy( szSelected, TEXT("None"));

        NumHouses = 0;

    }

    else

    {

        lstrcpy( szSelected, rgCities[iNumSelected].szCity);

        NumHouses = rgCities[iNumSelected].NumHouses;

    }

    wsprintf(szText, TEXT("%s %s"), szBuf1, szSelected);

    SendMessage(hwnd, SB_SETTEXT, 0, (LPARAM)szText);

    wsprintf(szText, TEXT("%s %d"), szBuf2, NumHouses);

    SendMessage(hwnd, SB_SETTEXT, 1, (LPARAM)szText);

}

To make a toolbar, create a bitmap for each button and then create a larger bitmap by stringing together each of the small bitmaps into one long bitmap. The standard toolbar bitmaps are built into COMCTL32.DLL. You can add these images to your toolbar by using the TB_ADDBITMAP message. In the following example, three of the standard file bitmaps (new, open, and save) and four of the view bitmaps (large icon, small icon, list view, and details view) are included in the toolbar. The TBBUTTON structure is filled in with the predefined bitmap indices for the desired bitmaps.

// Toolbar buttons.

TBBUTTON tbButtons[] = {

    { STD_FILENEW, IDM_NEW, TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, 0L, 0},

    { STD_FILEOPEN, IDM_OPEN, TBSTATE_ENABLED, TBSTYLE_BUTTON, 0,
      0L, 0},

    { STD_FILESAVE, IDM_SAVE, TBSTATE_ENABLED, TBSTYLE_BUTTON, 0,
      0L, 0},

    { 0, 0, TBSTATE_ENABLED, TBSTYLE_SEP, 0, 0L, 0},

    { VIEW_LARGEICONS, IDM_LARGEICON, TBSTATE_ENABLED, TBSTYLE_BUTTON,
      0, 0L, 0},

    { VIEW_SMALLICONS, IDM_SMALLICON, TBSTATE_ENABLED, TBSTYLE_BUTTON,
      0, 0L, 0},

    { VIEW_LIST, IDM_LISTVIEW, TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, 0L,
      0},

    { VIEW_DETAILS, IDM_REPORTVIEW, TBSTATE_ENABLED, TBSTYLE_BUTTON,
      0, 0L, 0},

};

In the code that creates the toolbar, the application calls the CreateToolbarEx function, specifying HINST_COMMCTRL as the handle of the instance, IDB_STD_SMALL_COLOR as the bitmap identifier, and a pointer to the TBBUTTON structure. Note that the number of buttons specified is 4 because the last 4 buttons (the view buttons) come from a different bitmap.

HWND CreateTheToolbar(HWND hWndParent)
{
    HWND hWndToolbar;
    TBADDBITMAP tb;
    int index, stdidx;

    hWndToolbar = CreateToolbarEx(hWndParent,
        WS_CHILD | WS_BORDER | WS_VISIBLE |
        TBSTYLE_TOOLTIPS, ID_TOOLBAR, 11, (HINSTANCE)HINST_COMMCTRL,
        IDB_STD_SMALL_COLOR, (LPCTBBUTTON)&tbButtons,
        4, 0, 0, 100, 30, sizeof(TBBUTTON));

    // Add the system-defined view bitmaps.
    tb.hInst = HINST_COMMCTRL;
    tb.nID = IDB_VIEW_SMALL_COLOR;
    stdidx = SendMessage(hWndToolbar, TB_ADDBITMAP, 12, (LPARAM)&tb);

    // Update the indices to the bitmaps.
    for (index = 4; index < NUM_BUTTONS; index++)
        tbButtons[index].iBitmap += stdidx;

    // Add the view buttons.
    SendMessage(hWndToolbar, TB_ADDBUTTONS, 4, (LONG) &tbButtons[4]);

    return (hWndToolbar);
}

The next step is to create the list view and tree view windows. In the following example, the tree view control is one-fourth the width of the window's client area, and its height takes into account the vertical size of the toolbar and status bar. The example demonstrates how to create the tree view window. For this example, the values that determine the size of the controls are hard-coded. Applications should obtain these values by calling the GetSystemMetrics function.

HWND TV_CreateTreeView (HWND hWndParent, HINSTANCE hInst,
                       int NumCities, CITYINFO *pCity)
{
    HWND hwndTree;      // handle to tree view window
    RECT rcl;           // rectangle for setting size of window
    HBITMAP hBmp;       // handle to bitmap
    HIMAGELIST hIml;    // handle to image list

    // Get the size and position of the parent window.
    GetClientRect(hWndParent, &rcl);

    // Create the tree view window, make it 1/4 the width of the
    // parent window, and take the status bar and toolbar into
    // account.

    hwndTree = CreateWindow (
        WC_TREEVIEW,                // window class
        "",                         // no default text
        WS_VISIBLE | WS_CHILD | WS_BORDER | TVS_HASLINES |
           TVS_HASBUTTONS | TVS_LINESATROOT,
        0, 27,                      // x,y
        (rcl.right - rcl.left)/4,   // cx
        rcl.bottom - rcl.top - 45,  // cy
        hWndParent,                 // parent
        (HMENU) ID_TREEVIEW,        // identifier
        hInst,                      // instance
        NULL );
    if (hWndTree == NULL)
        return NULL;

        //  First, create the image list that is needed.
        hIml = ImageList_Create(BITMAP_WIDTH, BITMAP_HEIGHT,FALSE,
        2, 10);

    // Load the bitmaps, and add them to the image lists.
    hBmp = LoadBitmap(hInst, MAKEINTRESOURCE(FORSALE_BMP));
    idxForSale = ImageList_Add(hIml, hBmp, NULL);
    hBmp = LoadBitmap(hInst, MAKEINTRESOURCE(CITY_BMP));
    idxCity = ImageList_Add(hIml, hBmp, NULL);
    hBmp = LoadBitmap(hInst, MAKEINTRESOURCE(SELCITY_BMP));
    idxSelect = ImageList_Add(hIml, hBmp, NULL);

    // Make sure that all of the bitmaps are added.
    if (ImageList_GetImageCount(hIml) != 3)
        return FALSE;

    // Associate the image list with the tree view control.
    TreeView_SetImageList(hwndTree, hIml, idxForSale);

    // Initialize the tree view by adding "Houses For Sale."
    TV_InitTreeView(hInst, hwndTree);

    return (hwndTree);
}

VOID TV_InitTreeView(HINSTANCE hInst, HWND hwndTree)
{
    TCHAR szText[MAX_CITY];

    // Add the root item "Houses for Sale."
    LoadString(hInst, IDS_FORSALE, szText, MAX_LEN);
    hTPrev = (HTREEITEM)TVI_ROOT;
    iImage = idxForSale;
    hParent = (HTREEITEM)NULL;
    iSelect = idxForSale;
    hTRoot = TV_AddOneItem(szText, hwndTree, -1 );

    // Reset the previous item and image.
    hParent = hTRoot;
    hTPrev = (HTREEITEM)TVI_FIRST;
    iImage = idxCity;
    iSelect = idxSelect;
}

In the following example, you create the list view window, make it three-fourths the width of the parent window's client area, place it on the right side, and account vertically for the toolbar and status bar.

HWND LV_CreateListView (HWND hWndParent, HINSTANCE hInst,
                        int NumHouses, HOUSEINFO *pHouse)

{
    HWND hWndList;     // handle to list view window
    RECT rcl;          // rectangle for setting size of window
    HICON hIcon;       // handle to icon
    int index;         // index used in FOR loops
    HIMAGELIST hSmall, hLarge; // handles to image lists
    LV_COLUMN lvC;      // list view column structure
    char szText[64];    // place to store some text
    int iWidth;         // column width

    // Get the size and position of the parent window.
    GetClientRect(hWndParent, &rcl);

    // Create the list view window, make it 3/4 the size of the
    // parent window, and take the status bar and toolbar into
    // account.

    iWidth = (rcl.right - rcl.left) - ((rcl.right - rcl.left)/4);
    hWndList = CreateWindowEx( 0L,
        WC_LISTVIEW,                        // list view class
        "",                                 // no default text
        WS_VISIBLE | WS_CHILD | WS_BORDER | LVS_REPORT,  // styles
        (rcl.right - rcl.left)/4, 27,       // x, y
        iWidth, rcl.bottom - rcl.top - 42,  // cx, cy
        hWndParent,                         // parent
        (HMENU) ID_LISTVIEW,                // identifier
        hInst,                              // instance
        NULL );

    if (hWndList == NULL )
      return NULL;

    // First, initialize the image lists that are needed.
    // Create an image list for the small and large icons.
    // FALSE specifies large icons, and TRUE specifies small icons.
    hSmall = ImageList_Create( 16, 16, TRUE, 1, 0 );
    hLarge = ImageList_Create( 32, 32, FALSE, 1, 0 );

    // Load the icons, and add them to the image lists.
    hIcon = LoadIcon ( hInst, MAKEINTRESOURCE(HOUSE_ICON));
    if ((ImageList_AddIcon(hSmall, hIcon) == -1) ||
        (ImageList_AddIcon(hLarge, hIcon) == -1))
        return NULL;

    // Associate the image list with the list view control.
    ListView_SetImageList(hWndList, hSmall, LVSIL_SMALL);
    ListView_SetImageList(hWndList, hLarge, LVSIL_NORMAL);

    // Initialize the LV_COLUMN structure.
    // The mask specifies that the .fmt, .cx, width, and .isubitem
    // members of the structure are valid.
    lvC.mask = LVCF_FMT | LVCF_WIDTH | LVCF_TEXT | LVCF_SUBITEM;
    lvC.fmt = LVCFMT_LEFT;  // left-align the column
    lvC.cx = iWidth / NUM_COLUMNS + 1; // width of column,
                                       // in pixels

    lvC.pszText = szText;

    // Add the columns.
    for (index = 0; index < NUM_COLUMNS; index++)
    {
        lvC.iSubItem = index;
        LoadString( hInst,
        IDS_ADDRESS + index,
        szText,
        sizeof(szText));
        if (ListView_InsertColumn(hWndList, index, &lvC) == -1)
        return NULL;
 }

    return (hWndList);

}


 Sizing Issues

After creating the windows, you will need to resize the application's main window. To resize all of the windows at the same time, use the DeferWindowPos function. DeferWindowPos updates a structure that contains multiple window positions. You use this function as you would use the window enumeration functions; that is, you begin, defer, and end. The following example illustrates how to resize all of the windows.

BOOL ResizeWindows(HWND hwnd)
{
    RECT rcl;
    HDWP hdwp;

    // Get the client area of the parent window.
    GetClientRect(hwnd, &rcl);

    // Defer four windows.
    hdwp = BeginDeferWindowPos(4);
    if (hdwp == NULL)
         return FALSE;

    // First, reset the status bar size.
    DeferWindowPos(hdwp, g_Listing.hWndStatus, NULL, 0, 0,
         rcl.right - rcl.left, 20, SWP_NOZORDER | SWP_NOMOVE);

    // Next, reset the toolbar size.
    DeferWindowPos(hdwp, g_Listing.hWndToolBar, NULL, 0, 0,
         rcl.right - rcl.left, 20, SWP_NOZORDER | SWP_NOMOVE);

    // Next, reset the tree view size.
    DeferWindowPos(hdwp, g_Listing.hWndTreeView, NULL, 0, 0,
         (rcl.right - rcl.left ) / 4, rcl.bottom - rcl.top - 45,
         SWP_NOZORDER | SWP_NOMOVE);

    // Last, reset the list view size.
    DeferWindowPos(hdwp, g_Listing.hWndListView, NULL,
         (rcl.right - rcl.left ) / 4, 25,
         (rcl.right - rcl.left) - ((rcl.right - rcl.left)/4),
         rcl.bottom - rcl.top - 42,
         SWP_NOZORDER );

    return (EndDeferWindowPos(hdwp));
}


 Parsing and Storing the Data

Once the windows are created and resized, you need a method for reading in and storing the house listing data. The easiest way to store the house listing data is to save it to an ASCII file. The file should contain the following information:

•	Number of cities

•	City name (one name per line)

•	Number of houses

•	Information about each house (one house per line with each item of information separated by commas)

The ASCII file has the following form.

3

Bellevue

Redmond

Seattle

9

 100 Main Street,Redmond,175000,3,2,Joan Smith,555-1212

 523 Pine Lake Road,Redmond,125000,4,2,Ed Jones,555-1111

 1212 112th Place SE,Redmond,200000,4,3,Mary Wilson,555-2222

 22 Lake Washington Blvd,Bellevue,2500000,4,4,Joan Smith,555-1212

 33542 116th Ave. NE,Bellevue,180000,3,2,Ed Jones,555-1111

 64134 Nicholas Lane,Bellevue,250000,4,3,Mary Wilson,555-2222

 33 Queen Anne Hill,Seattle,350000,3,2,Joan Smith,555-1212

 555 SE Fifth St,Seattle,140000,3,2,Ed Jones,555-1111

 446 Mariners Way,Seattle,225000,4,3,Mary Wilson,555-2222

To parse the file, use the sscanf function and then convert some of the strings to integers, copy data to the structure, and update the file pointer. The structures used contain information about the houses, the cities, and the current state of the application. You should fill out a CITYINFO structure for each city listed and a HOUSEINFO structure for each house listed. When saving the information to a file, you reverse the procedure.


 Using the Common Dialog Boxes

To support long filenames, use the new common dialog boxes to open and save the house listing information. If you have existing code written for the Windows version 3.1 common dialog boxes, you will be able to recompile some of it, and the application will display the new dialog boxes. You will need to hide the filename extension (.TXT, in this case) before setting the caption text for the main window. As shown in the following illustration, the new File Open common dialog box has no problem with long filenames, such as "Listing for the Puget Sound" or "Another saved listing."

The following example demonstrates how to use the common dialog boxes to open and save a file. It also shows how to read and parse the file to initialize the structures.

BOOL OpenNewFile( HWND hWnd )

{

    HANDLE hFile;

    DWORD dwBytesRead;

    DWORD dwFileSize;

    lstrcpy( szFile, TEXT(""));

    lstrcpy( szFileTitle, TEXT(""));

    OpenFileName.lStructSize       = sizeof(OPENFILENAME);

    OpenFileName.hwndOwner         = hWnd;

    OpenFileName.hInstance         = (HANDLE) g_Listing.hInst;

    OpenFileName.lpstrFilter       = szFilter;

    OpenFileName.lpstrCustomFilter = (LPTSTR) NULL;

    OpenFileName.nMaxCustFilter    = 0L;

    OpenFileName.nFilterIndex      = 1L;

    OpenFileName.lpstrFile         = szFile;

    OpenFileName.nMaxFile          = sizeof(szFile);

    OpenFileName.lpstrFileTitle    = szFileTitle;

    OpenFileName.nMaxFileTitle     = sizeof(szFileTitle);

    OpenFileName.lpstrInitialDir   = NULL;

    OpenFileName.lpstrTitle        = TEXT("Open a File");

    OpenFileName.nFileOffset       = 0;

    OpenFileName.nFileExtension    = 0;

    OpenFileName.lpstrDefExt       = TEXT("*.txt");

    OpenFileName.lCustData         = 0;

    OpenFileName.Flags             = OFN_SHOWHELP | OFN_PATHMUSTEXIST
                                     | OFN_FILEMUSTEXIST
                                     | OFN_HIDEREADONLY;

    if (GetOpenFileName(&OpenFileName))

    {

    if ((hFile = CreateFile((LPCTSTR)OpenFileName.lpstrFile,

         GENERIC_READ,

         FILE_SHARE_READ,

         NULL,

         OPEN_EXISTING,

         FILE_ATTRIBUTE_NORMAL,

         (HANDLE)NULL)) == (HANDLE)-1)

    {

         MessageBox( hWnd, TEXT("File open failed."), NULL, MB_OK );

        return FALSE;

    }

    // Get the size of the file.

    dwFileSize = GetFileSize(hFile, NULL);

    if (dwFileSize == 0xFFFFFFFF)

    {

        MessageBox( NULL, TEXT("GetFileSize failed!"), NULL, MB_OK);

        return FALSE;

    }

    // Allocate a buffer for the file to be read into.

    lpBufPtr = (TCHAR *)GlobalAlloc( GMEM_FIXED, dwFileSize );

    if (lpBufPtr == NULL)

    {

        MessageBox( NULL, TEXT("GlobalAlloc failed!"), NULL, MB_OK);

        CloseHandle( hFile );

        return FALSE;

    }

    // Read its contents into a buffer.

    ReadFile(hFile,(LPVOID)lpBufPtr, dwFileSize, &dwBytesRead, NULL);

    if (dwBytesRead == 0)

    {

        MessageBox( hWnd, TEXT("Zero bytes read."), NULL, MB_OK );

        CloseHandle(hFile);

        GlobalFree(lpBufPtr);

        return FALSE;

    }

    // Close the file.

    CloseHandle(hFile);

    // Parse the file buffer.

    return (ParseFile());

    }

    else

    {

    ProcessCDError(CommDlgExtendedError(), hWnd );

    return FALSE;

    }

}

BOOL ParseFile ( VOID )

{

    int count, result, index;

    TCHAR szTemp[MAX_PATH], szBeds[TEMP_LEN], szBaths[TEMP_LEN];

    TCHAR * lpSave;

    HTREEITEM hPrev;

    // Initialize the tree view and list view windows.

    InitTreeAndList();

    lpSave = lpBufPtr;

    // Read in the first line to get the number of cities.

    sscanf( lpBufPtr, TEXT("%s\n"), szTemp);

    g_Listing.NumCities = atoi(szTemp);

    // Move the buffer pointer.

    while (*lpBufPtr != 0x0A)

       lpBufPtr++;

    lpBufPtr++;

    if (g_Listing.NumCities == 0 || g_Listing.NumCities > MAX_CITIES)

    {

        MessageBox(NULL, TEXT("Number of cities must be between 1 and 16"), NULL, MB_OK);

        GlobalFree(lpBufPtr);

        return FALSE;

    }

    // Read a city for each line.

    for (count= 0; count < g_Listing.NumCities; count++)

    {

        sscanf( lpBufPtr, TEXT("%s\n"), rgCities[count].szCity);

        // Move the buffer pointer.

        while (*lpBufPtr != 0x0A)

            lpBufPtr++;

        lpBufPtr++;

        // Add the city to the tree view control.

        hPrev = TV_AddOneItem( rgCities[count].szCity,
        g_Listing.hWndTreeView, count);

    }

    // Get the number of houses.

    sscanf( lpBufPtr, TEXT("%s\n"), szTemp);

    g_Listing.NumHouses = atoi(szTemp);

    // Move the buffer pointer.

    while (*lpBufPtr != 0x0A)

    lpBufPtr++;

    lpBufPtr++;

    if (g_Listing.NumHouses == 0 || g_Listing.NumHouses > MAX_HOUSES)

    {

    MessageBox(NULL, TEXT("Number of houses must be between 1 and 256"), NULL, MB_OK);

    GlobalFree(lpBufPtr);

    return FALSE;

    }

    // Read the house information for each line.

    for (count= 0; count < g_Listing.NumHouses; count++)

    {

        result = sscanf(lpBufPtr,
        TEXT("%[^','],%[^','],%[^','],%[^','],%[^','],%[^','],%s"),

        rgHouses[count].szAddress,rgHouses[count].szCity,

        szTemp, szBeds, szBaths, rgHouses[count].szAgent,

        rgHouses[count].szNumber);

        rgHouses[count].iPrice = atoi(szTemp);

        rgHouses[count].iBeds = atoi(szBeds);

        rgHouses[count].iBaths = atoi(szBaths);

        // Move the buffer pointer.

        while (*lpBufPtr != 0x0A)

            lpBufPtr++;

        lpBufPtr++;

    // Increment the house count for the city.

    for (index=0;index < g_Listing.NumCities; index++)

    {

        if (lstrcmp(rgHouses[count].szCity, rgCities[index].szCity) ==
         0)
        {

            rgCities[index].NumHouses++;

            break;

        }

    }

    }

    // Free up the buffer.

    GlobalFree(lpBufPtr);

    // Then add the cities and houses to the list view and tree

    // view controls.

    return TRUE;

}

VOID UpdateListView( HWND hwndLV, int iSelected )

{

    int count, index;

    LV_RemoveAllItems(hwndLV);

    for (index = 0, count = 0; count < g_Listing.NumHouses; count++)

    {

        if (lstrcmp(rgHouses[count].szCity,
             rgCities[iSelected].szCity) == 0)

        {

            // Add the house to the list view control.

            if (!LV_AddItem(hwndLV, index, &rgHouses[count]))

                MessageBox(NULL, TEXT("LV_AddItem failed!"), NULL,
                MB_OK);

            index++;

        }

    }

}

BOOL SaveToFile( HWND hWnd )

{

   HANDLE hFile;

   DWORD dwOpen;

   DWORD dwBytesWritten;

   TCHAR buf[MAX_PATH];

   DWORD dwFileSize;

   dwFileSize = GetDataBufferAndSize();

   if (dwFileSize == 0)

   {

       MessageBox(NULL,TEXT( "GetDataBufferAndSize failed!"), NULL,
                  MB_OK);

       return FALSE;

   }

   dwOpen = CREATE_ALWAYS;

   // Open the file.

   if ((hFile = CreateFile((LPCTSTR)OpenFileName.lpstrFile,

            GENERIC_WRITE,

            FILE_SHARE_WRITE,

            NULL,

            dwOpen,

            FILE_ATTRIBUTE_NORMAL,

            (HANDLE)NULL)) == (HANDLE)-1)

   {

        sprintf( buf, TEXT("Could not create file %s"),
             OpenFileName.lpstrFile );

         MessageBox( hWnd, buf, NULL, MB_OK );

         return FALSE;

   }

   // Write its contents into a file.

   if (WriteFile( hFile, (LPCVOID)lpBufPtr, dwFileSize,

     &dwBytesWritten, NULL) == FALSE)

   {

      MessageBox( hWnd, TEXT("Error writing file."), NULL, MB_OK );

      return FALSE;

   }

   // Close the file.

   CloseHandle(hFile);

   // Free up the file buffer.

   GlobalFree(lpBufPtr);

   return TRUE;

}

VOID InitTreeAndList( VOID )

{

    g_Listing.NumCities = 0;

    g_Listing.NumHouses = 0;

    g_Listing.iSelected = -1;

g_Listing.iSelHouse = -1;

    TreeView_DeleteAllItems(g_Listing.hWndTreeView);

    ListView_DeleteAllItems(g_Listing.hwndListView);

    TV_InitTreeView(g_Listing.hInst, g_Listing.hWndTreeView);

}


 Handling Notification Messages

Notification messages are used extensively to manipulate the behavior and appearance of controls. Because status windows, toolbars, list view controls, and tree view controls all expect notification messages, you must ensure that each control gets the notifications it needs. In the main window procedure for the application, trap the WM_NOTIFY message and either handle the notification messages directly or pass them to handler functions.

case WM_NOTIFY:

    lpToolTipText = (LPTOOLTIPTEXT)lParam;

    if (lpToolTipText->hdr.code == TTN_NEEDTEXT)

    {

        LoadString(g_Listing.hInst,

                   lpToolTipText->hdr.idFrom,  // string ID == cmd ID

                   szBuf,

                   sizeof(szBuf));

        lpToolTipText->lpszText = szBuf;

    }

    if (TV_NotifyHandler(hWnd, message, wParam, lParam, &g_Listing))

    {

        // Update the list view control to show houses

        // in the selected city.

        UpdateListView(g_Listing.hWndListView, g_Listing.iSelected);

        // Update the status text.

        ChangeSBText(g_Listing.hInst, g_Listing.hWndStatus,
                     g_Listing.iSelected );

    }

    LV_NotifyHandler(hWnd, message, wParam, lParam, g_Listing.hInst);

    break;

For the toolbar, the sample application only traps the TTN_NEEDTEXT notification message, which is sent whenever the system needs to display a tooltip control associated with a toolbar button. In response to this notification message, the application must load the appropriate text string into the lpszText member of the LPTOOLTIPTEXT structure.

The tree view window's notification handler only handles the TVN_SELCHANGED notification message, which is sent to the tree view window whenever the selection changes.

LRESULT TV_NotifyHandler(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM
                         lParam, LISTINFO *pList)

{

    static NM_TREEVIEW *pNm;

    pNm = (NM_TREEVIEW *)lParam;

    if (pNm->hdr.idFrom != ID_TREEVIEW)

        return 0L;

    switch(pNm->hdr.code)

    {

        case TVN_SELCHANGED:

            pList->iSelected = (int)(pNm->itemNew.lParam);

            return 1;

            break;

        default:

            break;

    }

return 0L;

In response, the application needs to update the list view control and status bar to reflect the house listings for the newly selected city.

VOID UpdateListView( HWND hwndLV, int iSelected )

{

    int count, index;

    // Remove the previous items.

    LV_RemoveAllItems(hwndLV);

    // Loop through the house listings.

    for (index = 0, count = 0; count < g_Listing.NumHouses; count++)

    {

        // Check whether the house is listed for the new city.

         if (strcmp(rgHouses[count].szCity,
             rgCities[iSelected].szCity) == 0)

         {

             // If it is, add the house to the list view control.

             if (!LV_AddItem(hwndLV, index, &rgHouses[count]))

                 MessageBox(NULL, "LV_AddItem failed!", NULL, MB_OK);

             index++;

         }

    }

}

Handling notification messages for the list view window is a bit more complicated. The application implements the list view control using a callback function that receives the text for each item, so the notification handler needs to trap the LVN_GETDISPINFO notification message and fill in the pszText member of the LV_ITEM structure with the appropriate text, depending on the column.

The application also processes the LVN_COLUMNCLICK notification message in the list view notification handler. This notification message is sent whenever the user clicks a column heading in the list view control. In response, the application must sort the items in the list view control based on the criteria presented in the selected column. For example, if the user clicks the Bedrooms column, the application sorts the list in ascending order by the number of bedrooms for the item (that is, the house). The application uses a simple callback function that is called by using the ListView_SortItems macro. The callback function sorts the data using simple math (returning the greater of two values) for the columns that have integer sort criteria and using the strcmp function for the columns that have string sort criteria.

LRESULT LV_NotifyHandler(HWND hWnd, UINT uMsg, WPARAM wParam,
                          LPARAM lParam, HINSTANCE hInst)

{

    LV_DISPINFO *pLvdi = (LV_DISPINFO *)lParam;

    NM_LISTVIEW *pNm = (NM_LISTVIEW *)lParam;

    HOUSEINFO *pHouse = (HOUSEINFO *)(pLvdi->item.lParam);

    static TCHAR szText[TEMP_LEN];

    if (pNm->hdr.idFrom != ID_LISTVIEW)

        return 0L;

    switch(pLvdi->hdr.code)

    {

        case LVN_GETDISPINFO:

            switch (pLvdi->item.iSubItem)

            {

                case 0:     // address

                    pLvdi->item.pszText = pHouse->szAddress;

                    break;

                case 1:     // city

                    pLvdi->item.pszText = pHouse->szCity;

                    break;

                case 2:     // price

                    sprintf(szText, "$%u", pHouse->iPrice);

                    pLvdi->item.pszText = szText;

                    break;

                case 3:     // number of bedrooms

                    sprintf(szText, "%u", pHouse->iBeds);

                    pLvdi->item.pszText = szText;

                    break;

                case 4:     // number of bathrooms

                    sprintf(szText, "%u", pHouse->iBaths);

                    pLvdi->item.pszText = szText;

                    break;

                default:

                    break;

            }

            break;

        case LVN_COLUMNCLICK:

            // The user clicked on one of the column headings,
            // so sort by this column.

            ListView_SortItems(pNm->hdr.hwndFrom,ListViewCompareProc,

                               (LPARAM)(pNm->iSubItem));

            break;

        default:

            break;

    }

    return 0L;

}

int CALLBACK ListViewCompareProc(LPARAM lParam1, LPARAM lParam2,
                                 LPARAM lParamSort)

{

    HOUSEINFO *pHouse1 = (HOUSEINFO *)lParam1;

    HOUSEINFO *pHouse2 = (HOUSEINFO *)lParam2;

    int iResult;

    if (pHouse1 && pHouse2)

    {

        switch( lParamSort)

        {

            case 0:     // sort by address

                iResult = lstrcmpi(pHouse1->szAddress,

                    pHouse2->szAddress);

                break;

            case 1:     // sort by city

                iResult = lstrcmpi(pHouse1->szCity, pHouse2->szCity);

                break;

            case 2:     // sort by price

                iResult = pHouse1->iPrice - pHouse2->iPrice;

                break;

            case 3:     // sort by number of bedrooms

                iResult = pHouse1->iBeds - pHouse2->iBeds;

                break;

            case 4:     // sort by number of bathrooms

                iResult = pHouse1->iBaths - pHouse2->iBaths;

                break;

            default:

                iResult = 0;

                break;

        }

    }

    return(iResult);

}


 Adding Pop-up Context Menus

At this point, the application is functional, but you still need to add the pop-up menu that is displayed when the user clicks mouse button 2. There are two ways to do this. The easiest method is to trap the WM_CONTEXTMENU message and check the wParam parameter to see if the click occurred in the list view window. WM_CONTEXTMENU is sent whenever the user clicks mouse button 2. Another method is to handle the NM_RCLICK notification message and call the ListView_HitTest macro to determine which item, if any, the user has clicked. NM_RCLICK is sent whenever the user clicks mouse button 2 in the list view window.

To display a context menu for an item, you load the menu and call the TrackPopupMenu function. When the user chooses an item from the menu, the appropriate command is generated and sent to the window procedure in the form of a WM_COMMAND message.

case WM_CONTEXTMENU:

    // Mouse button 2 has been clicked.

    if ((HWND)wParam == g_Listing.hWndListView)

    {

         // Get the menu for the pop-up menu from the resource file.

         hMenu = LoadMenu(g_Listing.hInst, "HousePopupMenu");

         if (!hMenu)

             break;

         // Get the first submenu in it for TrackPopupMenu.

         hMenuTrackPopup = GetSubMenu(hMenu, 0);

         // Draw the "floating" pop-up menu, and track it.

         TrackPopupMenu(hMenuTrackPopup,

                        TPM_LEFTALIGN | TPM_RIGHTBUTTON,

                        LOWORD(lParam), HIWORD(lParam),

                        0, g_Listing.hWndListView, NULL);

        // Destroy the menu.

        DestroyMenu(hMenu);

    }

    break;


 Incorporating Property Sheets

Property sheets (also known as tabbed dialog boxes) allow users to view and change the properties of an item. In the sample application, the item is a house listing. Each property sheet contains one or more overlapping windows (called pages) that contain a logical grouping of properties. The user switches between pages by clicking tabs that label each property page. The sample contains two property sheets: one allowing the user to view and change the properties for a particular house listing (for example, address and city) and the other displaying information about the listing agent (for example, name and phone number). The following illustration shows the House Listing property sheet page. (An illustration of the Listing Agent property sheet page is found later in this section.)

Processing a property sheet page is similar to processing a dialog box with one major difference. When you process a property sheet page, you handle notification messages instead of the commands generated for the OK and Cancel buttons. You should process the property sheet pages in the following manner:

•	Save the original values for the item in response to the WM_INITDIALOG message.

•	Reset the values of the item in response to the PSN_APPLY and PSN_KILLACTIVE notification messages.

•	Reset the values of the item in response to a PSN_RESET notification message.

•	Set the edit fields in the page for the item in response to the PSN_SETACTIVE notification message.

To initialize the property sheet pages, you need to determine which house is currently selected and save that information for future reference. The first property sheet page displayed is the House Listing page. Responding to the WM_INITDIALOG message gives you the first chance to determine the currently selected house. The following example determines the index of the selected house within the global array of houses.

static char szAddSave[MAX_ADDRESS];

BOOL bErr;

int index, count;

LV_ITEM lvItem;

.

.

.

  case WM_INITDIALOG:

    // Fill in the list box with the cities.

    for (index = 0; index < g_Listing.NumCities; index++)

        SendDlgItemMessage(hDlg, IDE_CITY, CB_INSERTSTRING,
                           (WPARAM)(-1),
                           (LPARAM)(rgCities[index].szCity));

    // Get the index to the selected list view item.

    index = ListView_GetNextItem(g_Listing.hWndListView,

                                 -1, MAKELPARAM(LVNI_SELECTED, 0));

    // Get the house address.

    lvItem.iItem = index;

    lvItem.iSubItem = 0;

    lvItem.mask = LVIF_TEXT;

    lvItem.cchTextMax = sizeof(szAddSave);

    lvItem.pszText = szAddSave;

    ListView_GetItem(g_Listing.hWndListView,&lvItem);

    // Find the house in the list.

    for (count=0; count < g_Listing.NumHouses; count++)

    {

        if (strcmp(lvItem.pszText, rgHouses[count].szAddress) == 0)

            break;

    }

    g_Listing.iSelHouse = count;

.

.

.

The Listing Agent property sheet page allows the user to view and change the name and phone number of the listing agent associated with the selected house. The code used to handle this page is quite similar to that used for the House Listing page, except that the szAgent and szNumber members of the array of HOUSEINFO structures are modified instead of the other house-specific fields. The following illustration shows the Listing Agent property sheet page.


 Using the Registry

The registry is a central storage location that contains current information about the computer hardware configuration, installed software applications, settings and preferences of the current user, and associations between types of files and the applications that access and manipulate their contents. Much of the information that was stored in initialization files in early versions of the Microsoft® Windows® operating system is now stored in the registry in Windows 95.


 About Using the Registry

Mentions of the registry occur in several places in the documentation for Windows 95 and in the Microsoft® Win32® Software Development Kit (SDK). The documentation included in the Win32 SDK provides a detailed description of the functions and structures that provide an application with access to the registry. The Windows Interface Guidelines for Software Design has a chapter containing a general discussion of the registry. The Microsoft Windows 95 Resource Kit devotes a chapter to integrating an application into the Windows 95 operating system by storing information in the registry.  If you are unfamiliar with the registry or the arrangement of information within it, you should read about the registry before beginning this article. This article assumes you are already familiar with the registry and focuses on using the registry functions to navigate and load the registry as part of installing an application.

After briefly introducing registry terminology, this article identifies procedures involved in working with the registry when installing a software product. Other issues, such as the general registry structure and Windows 95 style recommendations, are mentioned in support of the registry coding described here.

This article describes how to record the following types of information in the registry:

•	Application state information

•	Application path information

•	Filename extensions

•	New data files

•	Icons

•	Icon commands

•	Uninstall information

This article frequently refers to a fictitious company called Buzz Productions, whose fictitious product is named BeeSounds. The product comprises an executable file named BUZZER.EXE, a dynamic-link library (DLL) named BUZZEXT.DLL, and a help file named BUZZER.HLP. Data files used by the product are identified by the .BZZ filename extension.


 Introducing the Registry

The registry is a hierarchical database. The database is made up of keys that are linked together to form hierarchies or tree structures. The keys are the fundamental entities in the database. The registry has six keys, also called root keys, that serve as entrypoints to the database for any application. Links provide a mechanism to traverse the database from a root key to other keys. The link between two keys also serves to establish the relationship of a subkey. A subkey is further from the root of the hierarchy than the other key in the link.

Each key has a name and a default value. A key can also have other named values associated with it. A value can be named or unnamed and has its own storage area for a data value. The data value can store binary, numerical, string, or other types of data.

The registry contains information that is critical to the correct operation of the computer. Before accessing and modifying the contents of the registry, you should make a back up copy of the registry. You can do this using the RegEdit utility.

Note  The registries for Windows 95 and Microsoft® Windows NT™ differ in how they handle class information associated with a key. The Windows 95 registry treats all classes alike. If you pass in a valid lpszClass buffer pointer to RegQueryInfoKey but do not pass in a valid lpcchClass pointer (that is, if you pass in NULL), Windows 95 lets the function call proceed.

The Window NT registry, however, distinguishes the different classes. In Windows NT, if you pass in a valid lpszClass buffer pointer to RegQueryInfoKey but do not pass in a valid lpcchClass pointer (that is, if you pass in NULL), the system returns the ERROR_INVALID_PARAMETER error value.


 Registering Application State Information

Application state information identifies information about a specific release of a software product, such as the product name, version number, user preferences, and component location. The registry provides two entry level hierarchies for storing this information. Application state information for the current version of a software product that is user-specific is stored in the registry in the following portion of the HKEY_CURRENT_USER hierarchy.

HKEY_CURRENT_USER
    Software
        BuzzProductions
            BeeSounds
                Version2.00

Application state information for the current version of a software product that is specific to an installation (and relevant to all users) is stored in the following portion of the HKEY_LOCAL_MACHINE hierarchy.

HKEY_LOCAL_MACHINE
    SOFTWARE
        BuzzProductions
            BeeSounds
                Version2.00

You can add additional keys and values under your application's Version key in each hierarchy. Key names are canonical; they cannot be changed, so you can use them to group the information types being stored. Key values can easily be changed and are ideal for storing information that changes, such as user preferences.

If the amount of installation-specific and user version information exceeds a few thousand bytes, you might still want to create an initialization (.INI) file.


 Registering Application Path Information

Application path information identifies where the application file (.EXE file), application extension files (.DLL files), and other support files for an application are stored in the Windows 95 file system. By following the conventions recommended in The Windows Interface Guidelines for Software Design, the files for the BeeSounds sample product would be installed in the following directories.

Filename	Directory
BUZZER.EXE	\Program Files\BeeSounds
BUZZEXT.DLL	\Program Files\BeeSounds\System
BUZZER.HLP	\Program Files\BeeSounds\System
*.BZZ (data files)	\Program Files\BeeSounds\System
The registry stores directory information that locates the installed application files and their associated application extension files in one or more keys of the HKEY_LOCAL_MACHINE hierarchy. For the BUZZER.EXE file, the key is inserted in the following hierarchy.

HKEY_LOCAL_MACHINE

    SOFTWARE

        Microsoft

            Windows

                CurrentVersion

                    App Paths

                        BUZZER.EXE

Each installed application file should have a key under the App Paths key named after the application file.

The BUZZER.EXE key has two values. The Default value specifies the path to the application file. The optional Path value specifies the paths to other application files.

Note  If an application shares application extension files, the installation program should create a SharedDLLs key under the CurrentVersion key. Under the SharedDLLs key, the installation program should create a key and a data value for each shared file. The key name for each shared file must specify the path and filename of the shared file. The data value associated with the key for a shared file tracks the number of applications that share the application extension file.

You can add keys under the CurrentVersion key in both the HKEY_CURRENT_USER and the HKEY_LOCAL_MACHINE hierarchies to expand the capabilities of an application.

For example, you can automatically start your application whenever Windows 95 starts up by adding the Run key beneath the CurrentVersion key and by including a data value for the Run key that specifies the command line to start the application.

You can automatically restart an application that was interrupted by a system shutdown when Windows 95 starts up by adding the RunOnce key beneath the CurrentVersion key and by including a data value for the RunOnce key that specifies the command line to restart the application. The command line must specify the path to the application file, appropriate data files, and any options needed to restore the application.


 Registering Filename Extensions

You can distinguish new file types by registering the filename extensions in the registry. Every file type that you install in the registry requires at least two registry keys. One of the mandatory keys specifies the filename extension. The other mandatory key specifies the application identifier and defines a long (40 character) description of the application identifier or class name that end users will see. Additional keys can specify a class identifier and a short (15 character) description of the application identifier or class name.

The registry stores filename extensions in the HKEY_CLASSES_ROOT hierarchy. The keys needed to register the filename extension used by the BeeSounds data files follow. Note that the CLSID class identifier is not a literal value; it is a unique identifier that can be obtained by running the UUIDGEN.EXE utility included in the Win32 SDK.

HKEY_CLASSES_ROOT
    .BZZ = BeeSounds

    BeeSounds

        CLSID

    CLSID

        {CLSID identifier}

            AuxUserType

                2


 Registering Data Files for Creation

If you would like users to be able to create new data files for an application directly from the desktop or folder without running the application, you should register the filename extension for creation.

The registry stores information for data file creation in the HKEY_CLASSES_ROOT hierarchy. The keys needed to register data files used by the BeeSounds data files follow. The ShellNew key has a value associated with it. The value used is the default value, and it contains the string "NullFile".

HKEY_CLASSES_ROOT
    .BZZ

        ShellNew


 Registering Icons

Windows 95 determines the icon to display for each file from information stored in the registry. If you would like the user to distinguish data files used by your application from other generic (unidentified) files stored on the file system, you can install icons to associate with a specific file type and register the icon and file association in the registry.

The registry stores icon information in the HKEY_CLASSES_ROOT hierarchy. The keys needed to register an icon for data files used by the BeeSounds data files follow. The DefaultIcon key has a value associated with it. The value used is the default value, and it contains a string identifying the path and file that contains the icon, and either an positive index value or a negative resource identifier that specifies the icon resource within the file. The value can be "%", indicating a per-instance icon (for more infomation about per-instance icons, see "Shell Extensions."

The following example shows a sample DefaultIcon key and its associated value:

HKEY_CLASSES_ROOT
    BeeSounds

        DefaultIcon = "C:\BEE\buzzer.exe, 1"

The file containing the icon can be an application file, an application extension file, or a resource file containing one or more resources. If the first resource in a file is the icon you want to associate with a file, you can omit the comma and index value from the data of the default value.


 Registering Icon Commands

Clicking with mouse button 2 on an icon displays a menu of commands that can be executed with the icon. Support for many of these commands is provided by the container (folder or desktop) containing the icon. However, containers do not provide support for the primary commands (Open, Edit, Play, and Print) that can be executed with an icon, nor do they provide support for custom commands. For each primary command or custom command that you want to provide to the user, you must register information for the command. For example, the BeeSounds product supports the Play primary command and the custom command "Play in Reverse."

The registry stores information for icon command support in the HKEY_CLASSES_ROOT hierarchy. The keys needed to register data files used by the BeeSounds data files follow. The Shell key has a value associated with it. The value's name is default, and it has contains the string "Play, Play_In_Reverse".

HKEY_CLASSES_ROOT
    BeeSounds

        Shell

            Play

                command = "C:\WINDOWS\buzzer.exe /play %1"

            Play_In_Reverse

                command = C:\WINDOWS\buzzer.exe /reverse %1"

The Play key has a value associated with it. The value used is the default value, and it contains the text that is displayed in the menu. This value must be localized (for example, "&Play"). If key name matches the menu text, you do not need to specify a value for the key. The command key under the Play key specifies as its value the command line that implements the Play command.

The Play_In_Reverse key uses the default value that contains the "Play In Reverse" text that appears in the menu. The command key under the Play_In_Reverse key specifies as its value the command line that implements the "Play in Reverse" command.

When displaying the menu for an icon, the system lists the order of the commands as they appear under the Shell key. You can override that sequence by specifying a preferred sequence as a comma-delineated key list in the default value of the Shell key. The first command listed in the menu becomes the default command for an icon.


 Registering Uninstall Information

Windows 95 includes a property sheet for Control Panel for installing and removing applications. Users might need to remove an application to recover disk space or to move the application to another location. To facilitate this, you should provide an uninstall program with your software application that removes the files and their settings and records information about the application in the registry.

The registry stores uninstall information in the HKEY_LOCAL_MACHINE hierarchy. The keys needed to register uninstall information for the BUZZER.EXE application follow.

HKEY_LOCAL_MACHINE
    SOFTWARE
        Microsoft
            Windows
                CurrentVersion

                    Uninstall

                        BUZZER.EXE

The BUZZER.EXE key has two named values that are required for each application key in the Uninstall hierarchy. The DisplayName value specifies a text string that the Add/Remove Programs property sheet of Control Panel displays to the user. The UninstallString value specifies the command line that runs the uninstall program, and it must specify the path, application file, and needed command-line arguments. For the BeeSounds product, this value is "c:\Program Files\BeeSounds\NOBUZZ.EXE /q."

The following example registers the uninstall information for the BeeSounds product.

case  IDM_REGUNINSTALL:        //register uninstall information

// 1. Navigate to the CurrentVersion key.

// 2. Create CurrentVersion\Uninstall\BUZZER.EXE key(s).

// 3. Create DisplayName and UninstallString values for BUZZER.EXE key.

// 4. Close the keys.

    // Prepare to navigate to the CurrentVersion key.

    hKey = HKEY_LOCAL_MACHINE;

    lstrcpy(lpszChildKey,
        (LPCSTR)"SOFTWARE\\Microsoft\\Windows\\CurrentVersion");

    dwReserved = 0;

    hChildKey = NULL;

    lpszKeyValue = szKeyValue;

    if (ERROR_SUCCESS == RegOpenKeyEx(hKey, lpszChildKey, dwReserved,
        KEY_READ|KEY_WRITE, &hChildKey))

    {

        MessageBox(hwnd, lpszChildKey, "Register Uninstall",MB_OK);

    }

    else {

        MessageBox(hwnd,"Key is not immediate child of other key",
            "Register App Path",MB_OK);

        break;

    }

    // Prepare to create Uninstall\BUZZER.EXE key(s).

    hKey = hChildKey;

    // Identify the filename extension.

    lstrcpy(lpszChildKey,(LPCSTR)"Uninstall\\BUZZER.EXE");

    lstrcpy(lpszClassType,"");     // class identifier for new key

    dwReserved = 0;

    hChildKey = NULL;

    fdwOptions = REG_OPTION_NON_VOLATILE;

    dwDisposition = 0L;    // clear returning parameter for create

    lpdwDisposition = &dwDisposition;

    dwDisposition2 = 0L;   // clear return parameter for nested create

    lpdwDisposition2 = &dwDisposition2;

    if (ERROR_SUCCESS == RegCreateKeyEx(hKey, lpszChildKey, dwReserved,
            lpszClassType, fdwOptions,
            KEY_ALL_ACCESS, NULL, &hChildKey, lpdwDisposition))

    {

        switch (dwDisposition){

        case REG_CREATED_NEW_KEY:

            // Create the DisplayName and UninstallString values.

            MessageBox(hwnd,"Create BUZZER.EXE a Success",
                "Creating key",MB_OK);

            lstrcpy (lpszKeyValueName, (LPCSTR)"DisplayName");

            lstrcpy (lpszKeyValue,
                (LPCSTR)"BeeSounds Removal Application");

            RegSetValueEx(hChildKey, lpszKeyValueName, dwReserved,
                REG_SZ, lpszKeyValue, sizeof(*szKeyValue));

            lstrcpy (lpszKeyValueName, (LPCSTR)"UninstallString");

            lstrcpy (lpszKeyValue,
                (LPCSTR)"C:\\Program Files\\BeeSounds\\NOBUZZ.EXE /q");

            RegSetValueEx(hChildKey, lpszKeyValueName, dwReserved,
                REG_SZ, lpszKeyValue, sizeof(*szKeyValue));

            RegCloseKey(hChildKey);

            RegCloseKey(hKey);

            break;

        case REG_OPENED_EXISTING_KEY:

        // This case should not apply, assuming it is a new installation

        // or the CurrentVersion hierarchy was copied and then deleted.

        // So, delete the existing key and create a new one.

            MessageBox(hwnd,"Create BUZZER.EXE failed",
                "Creating key",MB_OK);

            RegDeleteKey(hKey, hChildKey);

            RegCreateKeyEx(hKey, lpszChildKey, dwReserved,
                lpszClassType, fdwOptions,
                KEY_ALL_ACCESS, NULL, &hChildKey, lpdwDisposition2);

            if (dwDisposition2 == REG_CREATED_NEW_KEY)

            {

            // The second try worked. Now add values.

            lstrcpy (lpszKeyValueName, (LPCSTR)"DisplayName");

            lstrcpy (lpszKeyValue,
                (LPCSTR)"BeeSounds Removal Application");

            RegSetValueEx(hChildKey, lpszKeyValueName, dwReserved,
                REG_SZ, lpszKeyValue, sizeof(*szKeyValue));

            lstrcpy (lpszKeyValueName, (LPCSTR)"UninstallString");

            lstrcpy (lpszKeyValue,
                (LPCSTR)"C:\\Program Files\\BeeSounds\\NOBUZZ.EXE /q");

            RegSetValueEx(hChildKey, lpszKeyValueName, dwReserved,
                REG_SZ, lpszKeyValue, sizeof(*szKeyValue));

            RegCloseKey(hChildKey);

            RegCloseKey(hKey);

            }

            break;

        default:        // other status returned?

            MessageBox(hwnd,"Function successful,
                but status unexpected", "Creating key",MB_OK);

        }

    }

    else {

        MessageBox(hwnd,"Error--Couldn't create key",
            "Creating key",MB_OK);

    }

    // The second attempt did not create a new key.

    if (dwDisposition2 != REG_CREATED_NEW_KEY)

    {  // Place the error correction code here.

    }

    break;

If an application is being removed, the usage count for each shared and system-wide shared application extension file needs to be decremented. If the usage count for a file reaches zero, the user should be given the option of deleting the file.


 Dragging and Dropping

This article explains the general concepts that you need to know to support OLE drag and drop capabilities in your applications and lists the basic steps for implementing drag and drop support.


 About Dragging and Dropping

A Microsoft® Windows® 95 − based application should fully support the source and target drag and drop capabilities provided by OLE. One of the most attractive features of drag and drop in OLE is that the code that handles the actual data transfer — your implementation of the IDataObject interface — is reusable. You will be able to use the same code to implement cut and paste. OLE separates what the user does to cause the data transfer from how the applications actually transfer the data. This allows you to use the same "back-end" IDataObject interface for any number of ways that the user may want to transfer data.

This article is based in part on "Drag and Drop Target Practice: Implementing OLE 2.0 Support in Your Applications," (Microsoft Developers Network News, January 1994), by Sara Williams.


 General OLE Concepts

One of the most attractive aspects of OLE is that it is completely modular. It is designed so that each component can exist, for the most part, on its own. For example, you can add drag and drop support to your application without bothering with in-place activation, automation, or compound storage.

Even if your application only uses a small part of OLE, the Component Object Model (COM) enables other applications to know what your application's OLE capabilities are. COM is the fundamental, underlying model that OLE is based upon; all OLE objects are also component objects.

COM stipulates that any component object must control its own life span and be able to tell other objects about its capabilities in a strictly defined manner. To control its life span, a component object maintains a reference count. Capabilities are grouped into logical sets called interfaces; each interface is a set of member functions necessary to support a certain capability. The "strictly defined manner" that component objects must use is itself an interface, which is called IUnknown. Because all OLE interfaces are derived from IUnknown, they are component objects. IUnknown has three member functions: QueryInterface, AddRef, and Release.

An object uses QueryInterface to tell other objects about its capabilities. If the object implements the requested interface, it returns a pointer to the interface. If it does not implement it, it returns the E_NOTIMPL error value stating that the object does not support the requested interface. AddRef and Release are used to control the object's life span. An object's AddRef member function is called when another object holds a pointer to the object, and the Release member function is called when the pointer is no longer needed. If a call to Release causes the object's reference count to go to zero, the object can safely unload itself.

COM provides a couple of immediate benefits:

•	An object can determine in advance if another object supports a certain feature. If the other object does not support the feature, the calling object can react accordingly.

•	Objects do not remain in memory longer (or shorter) than necessary, and they do not rely on the user to launch or close them.

OLE's new data transfer mechanism is a crucial element of drag and drop support. Data transfer in OLE allows objects to be very specific about the data that they transfer. Instead of simply being able to transfer a plain old bitmap, an object can now transfer a bitmap of the object's contents rendered for a printer device and stored in a stream to be released by OLE.

To accomplish this, OLE uses the IDataObject interface and the FORMATETC and STGMEDIUM structures. Applications implement IDataObject to accomplish all data transfer in OLE; it includes member functions that set and retrieve an object's data, enumerate the available data formats, and receive data change notifications. FORMATETC and STGMEDIUM provide the specific details about the data that is being transferred—that is, the target device, aspect, storage medium, and release method.

Every drag and drop operation involves two objects: a source and a target. The source object contains the data to be dragged, and the target object accepts the dragged data.


 Adding Drop Source Capabilities

To enable your application to become the source of a drag and drop operation, follow these steps:

1.	Initialize the OLE libraries. Any application that uses the OLE libraries must check the version of the libraries and call the OleInitialize function during its initialization.

You should use the GetBuildVersion function to make sure that the system's OLE libraries are at least as recent as the ones for which the application was written.

Before you call any other OLE functions, you must call OleInitialize to initialize the OLE libraries. Because each call to OleInitialize must have a matching call to the OleUninitialize function, you should maintain an fOleInitialized flag so that you will know whether to call OleUninitialize when your application exits.

2.	Implement the IDropSource interface. Not including the member functions that it inherits from IUnknown, IDropSource has only two member functions: QueryContinueDrag and GiveFeedback. OLE calls QueryContinueDrag intermittently during the drag operation. Its parameters include the state of the keyboard, which the drop source uses to control the drag operation. The drop source returns the S_OK value to continue dragging, the DRAGDROP_CANCEL value to cancel dragging, or the DRAGDROP_DROP value to drop the object.

3.	OLE calls GiveFeedback to tell the drop source to update the cursor and ask the source window for visual feedback about what would happen if the user dropped at the current point. It sounds like a lot of work to update the cursor, but OLE will use its default cursors if the DRAGDROP_S_USEDEFAULTCURSORS value is returned.

4.	Implement the IDataObject interface, which is used by OLE applications to transfer data. In a drag and drop operation, the drop source gives OLE a pointer to its IDataObject implementation. OLE saves the pointer and passes it to the drop target when the cursor first enters the target window and when the drop occurs. Fortunately, you only need to implement the following (non-IUnknown) IDataObject member functions for drag and drop support: GetData, GetDataHere, QueryGetData, and EnumFormatEtc.

5.	Call the DoDragDrop function to begin the drag operation. After you have detected that the user wants to drag something, you should call DoDragDrop. OLE uses the IDataObject and IDropSource pointers that are passed in, along with its list of registered drop targets, to control the drag operation. When the drag operation is complete, DoDragDrop returns either the DRAGDROP_S_DROP or DRAGDROP_S_CANCEL value. In addition, OLE returns a DWORD in the address pointed to by pdwEffect that tells how the drop should affect the source data—that is, whether the operation was a move, copy, link, or scroll. You should look at the pdwEffect value and modify the source data as necessary.

6.	Call OleUninitialize. Before an OLE application exits, it must call OleUninitialize to release the OLE libraries. You should check your fOleInitialized flag before calling OleUninitialize and should only call OleUninitialize if OleInitialize returned successfully.


 Adding Drop Target Capabilities

To enable your application to become a drop target, follow these steps:

1.	Initialize the OLE libraries. You should check the build version and call the OleInitialize function exactly as you would for a drop source.

2.	Call the RegisterDragDrop function. OLE keeps a list of the windows that are drop targets. Every window that accepts dropped objects must register itself and its IDropTarget interface pointer. Then when the user drags the object over a drop target window, OLE has the IDropTarget interface pointer handy.

3.	Implement the IDropTarget interface. OLE uses the IDropTarget interface pointer that you registered with RegisterDragDrop to keep you informed of the state of a drop operation.

When the cursor first enters a registered drop target window, OLE calls the IDropTarget::DragEnter member function. In this member function, you should ensure that your application can create the dragged object if it is dropped. Your application may also display visual feedback showing where the dropped object will appear, if appropriate.

When the cursor moves around inside a drop target window, OLE calls the IDropTarget::DragOver member function, just as Windows 95 sends WM_MOUSEMOVE messages. Here you should update any visual feedback that your application displays to reflect the current cursor position. When the cursor leaves a drop target window, OLE calls the IDropTarget::DragLeave member function. In your DragLeave member function, you should remove any feedback you displayed during DragOver or DragEnter.

OLE calls your IDropTarget::Drop member function when the user drops the object. To be precise, a drop occurs when the drop source returns the DRAGDROP_DROP value from the IDropSource::QueryContinueDrag member function. In your Drop member function, you should create an appropriate object from IDataObject that is passed as a parameter. The following example shows how to implement IDropTarget::Drop.

STDMETHODIMP CDropTarget::Drop (LPDATAOBJECT pDataObj,
    DWORD grfKeyState, POINTL pointl, LPDWORD pdwEffect)

{

    FORMATETC fmtetc;

    SCODE sc = S_OK;

    UndrawDragFeedback(); // removes any visual feedback

    // QueryDrop returns TRUE if the app. can accept a drop based on

    // the current key state, requested action, and cursor position.

    if (pDataObj && QueryDrop(grfKeyState,pointl,FALSE,pdwEffect)) {

        m_pDoc->m_lpSite = CSimpleSite::Create(m_pDoc);

        m_pDoc->m_lpSite->m_dwDrawAspect = DVASPECT_CONTENT;

        // Initialize the FORMATETC structure.

        fmtetc.cfFormat = NULL;

        fmtetc.ptd = NULL;

        fmtetc.lindex = -1;

        fmtetc.dwAspect = DVASPECT_CONTENT; // draws object's content

        fmtetc.tymed = TYMED_NULL;

        HRESULT hrErr = OleCreateFromData

            (pDataObj,IID_IOleObject,OLERENDER_DRAW,

            	&fmtetc, &m_pDoc->m_lpSite->m_OleClientSite,

            m_pDoc->m_lpSite->m_lpObjStorage,

            (LPVOID FAR *)&m_pDoc->m_lpSite->m_lpOleObject);

        if (hrErr == NOERROR)

            // The object was created successfully.

        else

            // The object creation failed.

            sc = GetScode(hrErr);

    }

    return ResultFromScode(sc);

}

4.	Call the RevokeDragDrop function. Before a drop target window is destroyed, it must call RevokeDragDrop to allow OLE to remove the window from its list of drop targets.

5.	Uninitialize the OLE libraries. Like a drop source, your application needs to uninitialize the OLE libraries before terminating.


 Other Drag and Drop Considerations

You can use OLE drag and drop to add drag and drop support within your own application. There is nothing to stop your application from being both a drop source and a drop target or from accepting dropped objects from itself.

This article does not discuss reference counting, although it is a crucial part of implementing a stable OLE application.


 Scrap Files

Windows 95 allows the user to transfer objects within a data file to the desktop or a folder. The result of the transfer operation is a file icon called a scrap. An OLE application automatically supports the creation of scrap files if its IDataObject interface supports enough data formats so that the drop target can create either an embedding or a shortcut object. You do not need to add any other functionality to your application to allow the user to create a scrap file. However, there are two optional features you may wish to add to your application: round-trip support and caching additional data formats in a scrap file. Round-trip support means that an object can be dragged out of a document and into a new container and then dragged from the new container back into the original document.


 Round-Trip Support

When the user transfers a scrap into your application, it should integrate the scrap as if it were being transferred from its original source. For example, if a selected range of cells from a spreadsheet is transferred to the desktop, they become a scrap. If the user transfers the resulting scrap into a word processing document, the cells should be incorporated as if they were transferred directly from the spreadsheet. Similarly, if the user transfers the scrap back into the spreadsheet, the cells should be integrated as if they were originally transferred within that spreadsheet.

Your application must include code that integrates a scrap into a document; otherwise, the embedding object of the scrap is copied into the document rather than the data associated with the scrap. To retrieve the data for the scrap, your application must examine the class identifier, CLSID, of the scrap object by retrieving the CF_OBJECTEDESCRIPTOR file format data. If the application recognizes the CLSID, the application should transfer the native data into the document rather than calling the OleCreateFromData function.


 Caching Additional Data Formats

When an IDataObject is dropped onto a file system folder, such as the desktop, the shell receives the CLSID of the object and looks for the list of clipboard formats to be cached in the scrap file. The list is located in the following registry location.

HKEY_CLASSES_ROOT\CLSID\{clsid}\DataFormats\PriorityCacheFormats

The clipboard formats should be added to the registry as the names of named values (the value should be empty). The additional formats give the user more choices when copying the scrap file and opening the Paste Special dialog box from another application. You should choose only useful formats to keep the scrap file from becoming too large. For example, WordPad scrap-caches the RTF format, and MSPaint scrap-caches the CF_BITMAP format.

HKEY_CLASSES_ROOT\CLSID\{D3E34B21-9D75-101A-8C3D-00AA001A1652}\DataFormats\PriorityCacheFormats,"#8",,""

HKEY_CLASSES_ROOT\CLSID\{73FDDC80-AEA9-101A-98A7-00AA00374959}\DataFormats\PriorityCacheFormats,"Rich Text Format",,""


 Delayed Rendering

You can specify the list of clipboard formats to be delay-rendered under the HKEY_CLASSESROOT\CLSID\{clsid}\DataFormats\PriorityCacheFormats key. The IDataObject of a scrap object with this CLSID will offer these formats in addition to the native data and cached data. When the drop target requests one of these formats, the shell runs the application and renders the format from the active object. However, you should avoid using this mechanism because it does not work if the server is not available or if the application is a non-OLE application.


 Clipboard Formats for Shell Data Transfers

Windows 95 allows the user to transfer data objects between applications and the shell. The user can transfer data objects, such as printers, files, shortcuts, and folders, either by dragging and dropping them or by using the Cut, Copy, and Paste menu commands. Both transfer methods involve the clipboard.

Windows 95 defines several clipboard formats that you must support to transfer objects between your application and the shell. The Windows header files do not include predefined clipboard format identifiers for these clipboard formats. Instead, they provide a set of clipboard format names and corresponding values. To obtain an identifier for a clipboard format, you simply pass the format's value to the RegisterClipboardFormat function. The following table lists the values and corresponding clipboard format names.

Value	Format name
CFSTR_SHELLIDLIST	"Shell IDList Array"
CFSTR_SHELLIDLISTOFFSET	"Shell Object Offsets"
CFSTR_NETRESOURCES	"Net Resource"
CFSTR_FILEDESCRIPTOR	"FileGroupDescriptor"
CFSTR_FILECONTENTS	"FileContents"
CFSTR_FILENAME	"FileName"
CFSTR_PRINTERGROUP	"PrinterFriendlyName"
CFSTR_FILENAMEMAP	"FileNameMap"
The following sections describe the clipboard formats used to transfer data between applications and the shell.


 "FileName" Format

The global memory object contains a single null-terminated and fully qualified filename. This format is supported for compatibility with applications written for Windows version 3.1. New applications should support the CF_HDROP clipboard format instead of the "FileName" format.


 "FileNameMap" Format

The "FileNameMap" format is used with the CF_HDROP clipboard format to rename a list of files that are copied to a new location during a copy and paste operation or a drag and drop operation. Data in the "FileNameMap" format consist of a double-null terminated list of filenames that correspond to the filenames in the CF_HDROP data. When the files listed in the CF_HDROP data are copied to the new location, the files receive the new names specified in the "FileNameMap" data. For example, if the CF_HDROP data contains two files with the names c:\temp.000 and c:\temp.001, the "FileNameMap" data contains the following list of filenames.

"new.txt\0another.txt\0\0"

If the files are copied to c:\target, they receive the following names.

c:\target\new.txt(was c:\temp.000)

c:\target\another.txt(was c:\temp.001)

The system stores files in the recycle bin using a coding system for the filenames (dcxxxx.ext). When the user drags or copies files from the recycle bin, the system uses the filenames specified in the "FileNameMap" format to rename the files.


 CF_HDROP Format

The global memory object contains a DROPFILES structure. If the object was copied to the clipboard as part of a drag and drop operation, the pt member of DROPFILES includes the coordinates of the point where the drop occurred. The pFiles member is the offset to a double − null-terminated list of filenames. An application can retrieve information from the data object by passing the object's handle to the DragQueryInfo, DragQueryFile, and DragQueryPoint functions.


 "PrinterFriendlyName" Format

This format is similar to the CF_HDROP format, except that the pFiles member of the DROPFILES structure is the address of a double − null-terminated list of printer "friendly" names.


 "FileContents" Format

The data object contains the contents of one or more files in a format that can be written to a file. When a group of files is being transferred, the target of the drag and drop operation can use the lindex member of the FORMATETC structure to indicate which file to retrieve. The names and attributes of each file are contained in the "FileGroupDescriptor" data.


 "FileGroupDescriptor" Format

The data object contains the filenames and attributes of a group of files being transferred during an OLE style drag and drop operation. The data object consists of a FILEGROUPDESCRIPTOR structure and any number of FILEDESCRIPTOR structures (one for each file in the group).


 "Shell Object Offsets" Format

The global memory object contains an array of POINT structures. The first structure specifies the screen coordinates of a group of shell objects, and the remaining structures specify the relative offsets of each item in the group. All coordinates are in pixels.


 "Net Resource" Format

The global memory object contains a list of network resources. The memory object consists of a NRESARRAY structure and any number of NETRESOURCE structures (one for each network resource in the list). Note that the string parameters (LPSTR types) in the NETRESOURCE structure contain offsets instead of addresses.


 "Shell IDList Array" Format

The global memory object contains an array of item identifier lists. The memory object consists of a CIDA structure that contains offsets to any number of item identifier lists (ITEMIDLIST structures). The first structure in the array corresponds to a folder, and subsequent structures correspond to file objects within the folder.


 Additional Information

For more information about how to support drag and drop in your applications, you can read the following documentation:

•	OLE documentation included in the Microsoft® Win32® Software Development Kit (SDK).

Information covered includes drag and drop operations as well as the IDataObject function and the FORMATETC and STGMEDIUM structures. The SimpDnD and Outline samples demonstrate drag and drop implementation.

•	Inside OLE 2 by Craig Brockschmidt, published by Microsoft® Press.

This book provides a thorough description of data transfer and drag and drop operations.


 Reference

The following structures define the clipboard formats used to transfer data between applications and the shell.


DROPFILES [New - Windows 95]
 DROPFILES

[New - Windows 95]

typedef struct _DROPFILES {

    DWORD pFiles; // offset of file list

    POINT pt;     // drop point (coordinates depend on fNC)

    BOOL fNC;     // see below

    BOOL fWide;   // TRUE if file contains wide characters,

                  // FALSE otherwise

} DROPFILES, FAR * LPDROPFILES;

Defines the CF_HDROP and CF_PRINTERS clipboard formats. In the CF_HDROP case, the data that follows is a double − null-terminated list of file names. For CF_PRINTERS, the data that follows are the printer friendly names.

fNC

Nonclient area flag. If this member is TRUE, pt specifies the screen coordinates of a point in a window's nonclient area. If it is FALSE, pt specifies the client coordinates of a point in the client area.


FD_FLAGS [New - Windows 95]
 FD_FLAGS

[New - Windows 95]

typedef enum {

    FD_CLSID = 0x0001,

    FD_SIZEPOINT = 0x0002,

    FD_ATTRIBUTES = 0x0004,

    FD_CREATETIME = 0x0008,

    FD_ACCESSTIME = 0x0010,

    FD_WRITESTIME = 0x0020,

    FD_FILESIZE = 0x0040,

    FD_LINKUI = 0x8000,

} FD_FLAGS;

Specifies an enumerate type that defines the flags used with the dwFlags member of the FILEDESCRIPTOR structure.


FILEDESCRIPTOR [New - Windows 95]
 FILEDESCRIPTOR

[New - Windows 95]

typedef struct _FILEDESCRIPTOR { // fod

    DWORD    dwFlags;          // see below

    CLSID    clsid;            // file class identifier

    SIZEL    sizel;            // width and height of file icon

    POINTL   pointl;           // screen coordinates of file object

    DWORD    dwFileAttributes; // file attribute flags (FILE_ATTRIBUTE_)

    FILETIME ftCreationTime;   // time of file creation

    FILETIME ftLastAccessTime; // time of last access to file

    FILETIME ftLastWriteTime;  // time of last write operation

    DWORD    nFileSizeHigh;    // high-order word of file size, in bytes

    DWORD    nFileSizeLow;     // low-order word of file size, in bytes

    CHAR     cFileName[ MAX_PATH ]; // name of file (null-terminated)

} FILEDESCRIPTOR, *LPFILEDESCRIPTOR;

Describes the properties of a file that is being copied by means of the clipboard during an OLE drag and drop operation.

dwFlags

Array of flags that indicate which of the other structure members contain valid data. This member can be a combination of these values:

FD_ACCESSTIME	The ftLastAccessTime member is valid.
FD_ATTRIBUTES	The dwFileAttributes member is valid.
FD_CLSID	The clsid member is valid.
FD_CREATETIME	The ftCreationTime member is valid.
FD_FILESIZE	The nFileSizeHigh and nFileSizeLow members are valid.
FD_LINKUI	Treat the operation as "Link."
FD_SIZEPOINT	The sizel and pointl members are valid.
FD_WRITESTIME	The ftLastWriteTime member is valid.


FILEGROUPDESCRIPTOR [New - Windows 95]
 FILEGROUPDESCRIPTOR

[New - Windows 95]

typedef struct _FILEGROUPDESCRIPTOR { // fgd

     UINT cItems;           // number of elements in fgd

     FILEDESCRIPTOR fgd[1]; // array of file descriptor structures

} FILEGROUPDESCRIPTOR, * LPFILEGROUPDESCRIPTOR;

Defines the CF_FILEGROUPDESCRIPTOR clipboard format.


NRESARRAY [New - Windows 95]
 NRESARRAY

[New - Windows 95]

typedef struct _NRESARRAY { // anr

    UINT        cItems; // number of elements in nr

    NETRESOURCE nr[1];  // see below

} NRESARRAY, * LPNRESARRAY;

Defines the CF_NETRESOURCE clipboard format.

nr

Array of NETRESOURCE structures that contain information about network resources. The string members (LPSTR types) in the structure contain offsets instead of addresses.


 Creating Multimedia Applications

Multimedia is experiencing a technological explosion. Advances in video and audio compression algorithms provide new uses for PC multimedia. Traditional publishing and entertainment industries are converging with multimedia as well. To participate fully in this evolution, companies need to identify the significant trends, new products, and business opportunities likely to influence the future of multimedia.


 About Multimedia Applications

Microsoft® Windows® version 3.0 provided the first Windows-based system support for multimedia. This system shipped in the summer of 1991. The multimedia support enabled the Windows operating system to speak, play music, synthesize sounds, show high-quality color images, and access time-dependent data using compact disc read-only memory (CD-ROM). Until that time, Windows had been silent except for system beeps. Later in 1991, the introduction of the Media Control Interface (MCI) allowed Windows to control video and audio recorders, laser disk players, and virtually any other audio or video device.

To enable multimedia, personal computers (PCs) running Windows needed to be equipped with high-performance hardware as well as new drivers for audio, video, and storage. In response to that need, computer manufacturers began introducing PCs specifically designed for Windows multimedia in consultation with Microsoft and with guidance from the Multimedia PC Marketing Council, which was formed to set performance specifications for video, audio, and CD-ROM subsystems. Companies also introduced multimedia upgrade kits for the large, installed base of silent PCs.

As a result of these improvements, Windows has become the leading multimedia PC platform, and hardware and developer support has skyrocketed. Every major PC manufacturer makes multimedia-ready models, and there are more than a dozen multimedia upgrade kits available for Windows.


 Future Directions in Multimedia

Multimedia is experiencing a technological explosion. Advances in video and audio compression algorithms provide new uses for PC multimedia. Traditional publishing and entertainment industries are converging with multimedia as well. To participate fully in this evolution, companies need to identify the significant trends, new products, and business opportunities likely to influence the future of multimedia.

Perhaps the most important trend is the rapid adoption of Microsoft Windows on multimedia-ready computers for the home. Both market share and sales rates of home computers are growing, driven largely by falling hardware prices. Continued growth of Windows-based multimedia in the home depends on three factors: ease of use, high-quality video performance, and the availability of great titles.

Microsoft's Plug and Play specification for multimedia components, from audio to video capture adapters, provides the ease of use essential to the continued acceptance of multimedia hardware in the home. For the user, this means hardware that automatically configures itself upon installation, eliminating the need to adjust dip switches or configure drivers.

Video playback has increased in Windows by up to 50 percent, and improved standards for high-performance video rendering are being developed.

In addition to displaying enhanced video, Windows-based computers will be used more frequently for high-quality video capture and editing. Several manufacturers are already demonstrating MPEG-quality video running with Windows, and Microsoft is working with hardware and software developers to specify a true MPEG implementation for Windows. As a result of this work, inexpensive MPEG decoding hardware is becoming available for Windows.

Future work will center on specifying requirements for video and bus performance; implementing MPEG, MPEG 2, and motion JPEG hardware-assisted compression; and using the capabilities of Windows 95 and Windows NT.


 Introduction to Writing Multimedia Applications

The remainder of this article covers three main issues related to creating Windows multimedia applications:

•	Working with or without multimedia hardware.

•	Coping with unavailable resources.

•	Yielding resources to other applications.

This article is only an overview of some of the global issues. For discussions of specific categories of multimedia applications and the Windows API that supports each class, see the multimedia documentation included in the Microsoft® Win32® Software Development Kit (SDK).


 Classes of Applications

Multimedia applications fall into two general classes: applications that are completely dependent on multimedia support in Windows and applications that take advantage of the support if multimedia hardware is available. Applications in the latter class are called "multimedia aware," because they recognize the multimedia hardware but are not fully dependent on it.


 Multimedia-Dependent Applications

Some applications make sense only in a multimedia environment. For example, a speak and spell tutor requires support for playing sounds. The application will not run on a computer that has no multimedia support. Developers should strive to create applications that either fail gracefully or have reduced functionality if a feature they require is unavailable.


 Multimedia-Aware Applications

An application that is multimedia aware uses multimedia hardware if it is available. If a user, for example, starts a multimedia-aware application on a computer that does not have a sound card, the application simply disables the audio portion of its interface and continues to run.


 Selected Multimedia Components

Applications can be sensitive to the presence of multimedia support or to individual components. For example, an application that displays text and uses animations, waveform, the Musical Instrument Digital Interface (MIDI), and compact disc (CD) audio sounds in various places might at first seem impossible without multimedia support. However, if the application were an encyclopedia that displayed mostly text, occasionally augmented by multimedia inserts, it could provide most of its functionality on a computer with no special multimedia hardware. It would only need the standard Windows window management and graphics device interface (GDI) libraries to display its text.


 Video Performance Guidelines

This section discusses issues related to maximizing video performance in multimedia applications.


 Window Size and Position

To achieve the best video playback rate (that is, the most frames per second), the playback window must be horizontally aligned on a four-pixel boundary. Without this alignment, playback may be slower by up to 50 percent.

The system typically aligns the playback window automatically. However, if an application plays an audio-video interleaved (AVI) file into a window that is not near the upper left corner of a pop-up window, the automatic alignment does not occur. (In this case, the playback window could move off the screen or could move back and forth repeatedly.) Because automatic alignment is not guaranteed, every programmer must ensure that the upper left corner of a playing AVI file is either on a pixel whose number is evenly divisible by four in the horizontal direction or in the upper left corner of a pop-up window that the system can safely align for the application.

Stretching video playback can slow performance significantly. Performance suffers whenever an AVI file is played back at any size other than its actual dimensions. It is impaired even if the playback size is smaller than the AVI frame size.


 Video Compression

To improve image and audio quality, you should avoid compressing an AVI file more than once. You should combine uncompressed pieces of video in your editing system before compressing the final product. Using this method not only promotes image and audio quality, it is faster as well, because editing is always faster with uncompressed video.

To achieve better video compression, you should follow these guidelines:

•	Capture the video on high-end equipment.

•	Keep noise out of the signal to prevent even worse noise in the compressed video.

•	Use a low-pass filter to decrease noise.

You can use the AVISaveOptions or ICCompressorChoose function to display a dialog box that lists compression options. One of these options is "quality." A higher quality setting equates to a larger frame. If you set a target data rate, the highest quality setting uses the entire data rate. However, a lower quality setting results in an even smaller data rate than you requested. Typically, you should set the target data rate in the dialog box and set the quality to maximum.


 Interleave Options

Although interleave options are unimportant for editing, they are important for video at run time. At run time, the interleave should be 1:1.


 Data and Frame Rates

The data rate your application uses depends on the speed of the CD-ROM player on your target platforms. For single-speed players, 150 kilobytes (K) per second is a reasonable rate.

Most video cards will support 15 fps at sizes up to 320 by 240 pixels. In fact, most video cards will support good full-screen playback at 15 fps if the AVI file is that size or less. If the video is larger than 320 by 240 pixels, however, the performance of full-screen playback is very poor.

Most developers test their applications on a variety of hardware platforms to gauge the data and frame rates.


 Key Frames

Most applications use the default setting for key frames. Using fewer key frames can produce a slightly better image quality. However, if the target system cannot keep up with the data rate during playback, an application will stall for a longer time than it would otherwise and performance will suffer. A higher setting for key frames will cause fewer frames to be skipped when playback cannot keep up with the data rate.


 Palette Flashing

It is important to avoid palette flashing when an application plays different AVI files and shows different bitmaps. The PALMAP sample application found in the Samples subdirectory of the Win32 SDK shows how to generate an optimal palette from a variety of pictures. Applications should create such a palette using all the AVI files and images to be displayed and should realize this palette when processing the WM_QUERYNEWPALETTE and WM_PALETTECHANGED messages. To cause a video to play mapped to the chosen palette and to avoid palette flashing, MCI applications can send the MCI_REALIZE command with the MCI_DGV_REALIZE_BKGD value (or the realize command with the "background" flag). Similarly, applications can use the DrawDibDraw function with the DDF_BACKGROUNDPAL value when drawing bitmaps.


 General Programming Guidelines

This section discusses issues related to developing multimedia applications.


 Calling Functions From Within Callback Functions

Win32 applications can call virtually any API element from within a callback function. For Windows 16-bit applications, however, the list of functions that you can safely call is still very small. The list includes the following functions:

•	midiOutLongMsg

•	midiOutShortMsg

•	OutputDebugStr

•	PostMessage

•	timeGetSystemTime

•	timeGetTime

•	timeKillEvent

•	timeSetEvent

Applications that require cross-platform portability must take this restriction into account.


 Multiple-Thread Limitations

The Windows 95 multimedia functions are not designed to be used by two or more threads in the same process. Although most multimedia functions will work if they are called by multiple threads, some are likely to fail. Functions that are particularly likely to fail include PlaySound, any of the functions that prepare or unprepare headers, and any of the open and close functions.  The PlaySound function can never be used simultaneously by multiple threads in the same process. The functions that prepare or unprepare headers and the open and close functions can be used simultaneously by multiple threads in the same process, but only if they do not pass the same structure.


 Resource Availability

Ideally, an application uses a device or feature only when it is needed and closes it when it is no longer required. If a resource is not available, the application should either continue without it (for example, disable the button that plays sound) or ask the user to release the device or feature from another application.

Unfortunately, loading on demand can result in significant timing delays, especially if a dynamic-link library (DLL) has to be loaded and initialized. A good compromise is to open the device before it is required and release it when another application requires it or when the application terminates. An application will know whether the device is available well before it needs to use it, so it can avoid the delays associated with loading code. To load on demand well, an application must process any WM_ACTIVATEAPP messages it receives. If an application receives WM_ACTIVATEAPP with a wParam value of zero, it should close any devices that it has open when it is no longer active. A subsequent WM_ACTIVATEAPP message with a nonzero wParam value indicates that the application should attempt to reopen any devices it needs because it is active once again.

An application can determine the availability of the multimedia features it uses and selectively disable the parts that are not going to work. The application has the option of notifying the user of the reduced functionality.

An application that tolerates limited functionality must check the error return code after each attempt to open a device so that it can avoid failing when the system configuration changes. You can inform the user either directly (through a dialog box) or indirectly (by disabling a button) that a feature has been lost.


 Yielding Resources to Other Applications

Applications that hold devices open for long periods should process the WM_ACTIVATEAPP messages sent to them so that other applications can also use multimedia capabilities. For example, during a game that allows the user to speak a part by recording his or her own voice, the user might decide to bring up Sound Recorder to alter a sound file recorded previously. If the game does not yield control of the waveform-audio output device, Sound Recorder will not work as expected.

As a rule, applications should not play animations or sounds while they are inactive. An exception to this general rule is an application that plays audio CDs, because the user may want to continue playing a CD while running another application. If an application needs to use a CD drive that is unavailable because another application has it open, the application must tell the user about the conflict.

An application should also give the user the option of turning off certain multimedia features, particularly sounds. (This is often done using a menu.) The user may want a background application to play MIDI files or may want to hear an audio CD while using an application. Also, the user may get tired of hearing the same sounds from an application repeatedly.


 Hardware Compatibility

The existence of multimedia DLLs on a system does not guarantee that appropriate device drivers are available. For example, the system may be installed on a computer with no sound card, or it may have no multimedia features at all. The existence of multimedia API elements does not mean that all of the multimedia personal computer (MPC) standard features are available either.

In addition, the presence of a CD-ROM device does not mean that it meets MPC specifications. Documentation for an application should inform the user that application performance may suffer if the user does not have MPC- or MPC2-compatible hardware. An application should either fail gracefully (with a message at startup) or tolerate the unavailability of multimedia support at run time.

You should also consider the role of your installation program in this process. If your installation program cannot find multimedia support and consequently disables your application's features, you should provide some way to enable these features if the user later adds multimedia support (for example, a sound card). You could require the user to rerun the installation program, or, preferably, you could put a detection mechanism into the startup code for the application (checking, for example, the registry for the existence of the device). The application does not need to know which sound driver to add; it must simply recognize that the multimedia API elements are now supported. This is easy to detect at run time.

The ability to load and unload drivers on demand adds another layer of complication to an application's use of multimedia. Because the number of available device drivers during the run time of an application may vary, it is not sufficient to simply enumerate them at application startup. To use every available driver while running, an application should check for the WM_DEVICECHANGE message to discover whether a device is changing.


 Displaying and Using Pen Data

A subset of the pen services for Microsoft® Windows® 95 is available on every Windows 95 system through the pen display dynamic-link library (DLL) called PKPD.DLL or PKPD32.DLL. Functions in this library allow any Windows 95 − based application to display and manipulate pen data (also called "ink") that was originally collected on a pen-enabled system.


 About Displaying and Using Pen

A few practical applications for pen services might include:

•	Using Windows-based applications to display a signature for letters or faxes.

•	Verifying signatures collected on a pen-based mobile computer.

•	Animating the display of ink for presentations or games.

•	Merging, compressing, and storing ink collected on pen-based systems, which might later be recognized as text on a pen-based system.

•	Displaying graphics, maps, or handwritten notes that have been drawn on a pen-based system.

The Programmer's Guide to Pen Services for Microsoft Windows 95, which is included in the Microsoft® Win32® Software Development Kit (SDK), provides information about using the entire set of pen functions to collect, recognize, manipulate, and display ink. The set of functions supported in the Windows 95 pen display library is limited to manipulating and displaying ink. Chapter 4, "The Inking Process," in that guide describes the functions available for displaying pen data, most of which are also available in the pen display library.

This article concentrates on the functions most likely to be used in the pen data display library on a standard Windows 95 system. It also presents a sample application that allows you to display pen data using various methods. The following topics are presented in both overview and sample code descriptions:

•	Retrieving pen data from a file and saving pen data to a file.

•	Scaling pen data.

•	Compressing, decompressing, and trimming pen data.

•	Animating the display of pen data.

•	Retrieving information about pen data.

The final sectionof this article provides guidelines for writing Windows 95 − based applications so that they will run successfully on pen-enabled systems. Although the pen services automatically supply user interface tools to the user so that your application can be used without a keyboard, you should be aware of the issues described in this article  to ensure that your application works well in a pen-enabled environment.


 Overview of Pen Services

Pen services for Microsoft Windows 95 provide all of the software requirements for operating a pen-based system. This includes data collection from a tablet- or screen-based pen device, display of ink, routing of data to one or more DLLs for character recognition, and the ability to persist data. It also includes Windows controls for pen input, which are used to recognize ink as text or create ink drawings, and tools, such as the on-screen keyboard. The first five chapters in the Programmer's Guide to Pen Services for Microsoft Windows 95 provide a comprehensive overview of these topics. You should read these chapters in addition to this article  if you need more information about pen services.

This section compares the pen display library functions in Windows 95 to the total set of pen services.


 Data Collection and Recognition

Pen data can be collected on a pen-enabled system by using either high-level or low-level calls to pen functions. High-level programming provides defaults for most steps and makes pen data collection and recognition straightforward. Lower-level programming adds a few more function calls to the process; however, data collection and recognition are essentially the same using both programming methods. The high-level method is described here because of its simplicity. For more information about this method, see Chapter 2, "Starting Out with System Defaults," in Programmer's Guide to Pen Services for Microsoft Windows 95.

At the highest level, a pen-aware application makes a call to the pen DoDefaultInput function, passing it a window handle. After this, the window and its child windows start receiving messages generated by the pen services. The first message allows the application to enable or disable itself or its child windows as pen targets. By default, all child windows are set as targets, capable of accepting pen input. Another set of messages sets up each target window's inking information, such as pen color, width, clipping range, and so on. After more "overhead" messages of this sort, the application is required to create an object in memory to collect the data. This object can be a recognition context object (HRC) or a pen data object (HPENDATA). The latter is relevant to this article , because it is the type of data that can be read and displayed using the pen display library functions.

As pen data arrives to each target window, the window is notified by a message, and the collected pen data is placed into the created object (HRC or HPENDATA) by default. Finally, when ink input ends, each target window receives a data-ending message. If an HPENDATA object was created, the application has the opportunity to duplicate or save the data. If an HRC object was created, the default behavior is to send the data to a recognizer. A recognizer is a DLL that is loaded to translate pen strokes into characters. When the recognizer has finished, the window receives a results message, and the default behavior of the pen services is to send the recognizer's "best guess" to the target window as a string of WM_CHAR messages.


 Display of Data

Pen services for Microsoft Windows 95 require the PENWIN.DLL or PENWIN32.DLL library for all of the functionality of pen data collection. The library is supplied by the pen tablet or computer manufacturer that bundles the services with their product.

Pen-enabled systems, however, use the same pen display library that is available on every Windows 95 system for pen data manipulation and display: PKPD.DLL or PKPD32.DLL. The remainder of this article  provides information about these services. Because of the overlap of use by both pen-enabled and penless systems, you will find a few functions in the pen display library that are included primarily for pen-enabled systems. These are noted and usually discussed after the functions that are more relevant to displaying ink on standard Windows 95 systems.


 Functions in the Pen Display Library

Before turning to the sample application, it might be helpful to provide some information about the pen display library functions used by the application and to describe the categories of functions in the pen display library. It is also highly recommended that you read Chapter 4, "The Inking Process," of the Programmer's Guide to Pen Services for Microsoft Windows 95 for a more information about these functions and consult the reference documentation in that guide for any individual function descriptions.

The functions in the pen display library can be organized into groups according to the following activities:

•	Creating pen data objects.

•	Scaling pen data.

•	Displaying pen data.

•	Examining pen data.

•	Editing or copying pen data.

•	Compressing pen data.

•	Using inkset objects.

Each of these groups and the functions that comprise them are discussed in this section. Functions in Pen Windows version 1.0 that have been superseded by the Pen Windows version 2.0 are not generally discussed in this section.

Before the pen display library functions are presented, it is important to describe exactly what constitutes pen data. Pen data is a collection of strokes composed of coordinate points. When ink is drawn, all of the points collected while the pen is down on the tablet comprise a "pen down stroke." (The time durations collected while the pen is not on the tablet are called a "pen up stroke.") After pen data is collected, it is stored in a pen data (or HPENDATA) object. This pen data object is accessed through a window handle, similar to the way that handles are used to access other Windows objects, such as device contexts.

Internally, a pen data object is composed of a main header followed by a sequence of strokes. The main header provides information, such as the number of strokes and points, the bounding rectangle, the ink color and width, and so on.

Each stroke contains a set of data points, which indicate the positions of the pen during the stroke, and a stroke header, which indicates the number of points in the stroke and when the stroke occurred.

Each point is initially stored in pen tablet coordinates with a resolution of 0.001 inch and an origin in the upper left corner of the tablet. The resolution can be scaled later to a different display resolution if needed.

Additional information provided by the original equipment manufacturer (OEM) for the pen tablet may also be contained in the stroke. If OEM data exists, it follows the point data in the stroke.

The following illustration shows the format of a pen data (HPENDATA) object.


 Creating Pen Data Objects

Three functions are associated with the creation of pen data objects:

•	CreatePenDataEx

•	DuplicatePenData

•	DestroyPenData

Although CreatePenDataEx has many parameters, most are only useful when creating a pen data object used to accept pen input. Applications using the Windows 95 display libraries on systems without a pen should normally set the uScale parameter to the PDTS_STANDARDSCALE value and pass zero or NULL to the other parameters.

DuplicatePenData makes a copy in memory of the pen data object and returns a handle to it.

Any memory allocated for pen data objects created by using CreatePenDataEx or DuplicatePenData can and must eventually be freed by using DestroyPenData.


 Scaling Pen Data

Three functions are associated with the scaling of pen data points:

•	MetricScalePenData

•	OffsetPenData

•	ResizePenData

MetricScalePenData scales the pen data to display resolutions corresponding to the Windows mapping modes. For example, passing the PDTS_HIENGLISH value to MetricScalePenData is equivalent to MM_HIENGLISH resolution, passing the PDTS_HIMETRIC value is equivalent to MM_HIMETRIC resolution, passing the PDTS_LOMETRIC value is equivalent to MM_LOMETRIC resolution, and so on. The original tablet coordinates are the same as the Windows mapping mode called MM_HIENGLISH (0.001 inch).

OffsetPenData can be used to offset the bounding rectangle within the pen data coordinates. For example, you can pass negative values to this function to move the rectangle containing the points to the left or top edge.

ResizePenData is useful for arbitrarily scaling points to fall within a given rectangle. You might want to use this function on pen data to scale it to a predetermined window size.

Note that rescaling pen data to a lower resolution causes information to be lost. If you need to maintain the highest resolution possible for your pen data, you may want to use the DrawPenDataEx function to scale your data to a window because that method leaves the original data alone and only scales the points as they are displayed.


 Displaying Pen Data

Four functions are associated with displaying pen data:

•	DrawPenDataEx

•	DrawPenData (not available in PKPD32.DLL)

•	RedisplayPenData

•	CreatePenDataRegion

Of these functions, DrawPenDataEx is the most useful for systems that are not pen-enabled. DrawPenDataEx is very versatile and handles all of the details of drawing pen data to the device context that it is passed. It has the ability to draw all strokes, a selected range of strokes, or a selected range of points. It also has the ability to animate the drawing of ink, playing back the strokes in their original succession and duration, by reading the timing information stored with each stroke. Part of the animation process involves automatic calls made by DrawPenDataEx to a callback function that you specify. Along with the address of a callback function, an ANIMATEINFO structure is also passed to this function to provide more information about the animation. The sample application and accompanying text describes this process in greater detail.

The other functions listed here are used less often on standard Windows 95 systems. DrawPenData is a 16-bit display function that has been superseded by DrawPenDataEx. RedisplayPenData is primarily designed for displaying ink immediately after a user has drawn it (such as in an ink control) so that pen data objects can be merged.

 CreatePenDataRegion is also primarily used on pen-enabled systems that use "gestures" to communicate system-level commands to the operating system, such as cutting or pasting operations. Gestures are pen movements (such as "circle-P") that require immediate ink display anywhere on the screen.


 Examining Pen Data

Nine functions are used to examine the contents of a pen data object:

•	GetPenDataAttributes

•	GetStrokeAttributes and SetStrokeAttributes

•	GetStrokeTableAttributes and SetStrokeTableAttributes

•	BeginEnumStrokes, GetPenDataStroke, and EndEnumStrokes

•	HitTestPenData

GetPenDataAttributes is used to retrieve information from the pen data object's main header, such as the bounding rectangle, the total number of points and strokes, the time that the pen data was created, and the device sampling rate. This function is used in the sample application to retrieve the bounding rectangle of ink before it scaled. It is also used to determine the scaling and compression of the pen data object.

Most of the other functions in this group provide access to individual or group stroke attributes either indirectly through a function call or by providing direct access to the pen data object in memory.

GetStrokeAttributes and SetStrokeAttributes retrieve and modify, respectively, the attributes of individual strokes, including the pen state (up or down), the ink color and width, and the time that the stroke was recorded.

GetStrokeTableAttributes and SetStrokeTableAttributes retrieve and modify, respectively, attributes that are shared by a group of strokes. For example, if all strokes use a red pen color and a width of 1, that attribute can be modified for all strokes by using only one call to SetStrokeTableAttributes.

BeginEnumStrokes returns a far pointer to the HPENDATA object within the global heap, GetPenDataStroke retrieves pointers to point data within the HPENDATA object, and EndEnumStrokes unlocks the pen data memory block and invalidates any pointers retrieved.

HitTestPenData determines if a given point lies on or near a point in the pen data object.


 Editing or Copying Pen Data

Functions in this group can be organized into three subgroups. The first subgroup of functions adds strokes to or extracts strokes from a pen data object.

ExtractPenDataStrokes	Copies and, optionally, deletes strokes from a pen data object.
InsertPenDataStroke	Inserts a stroke into an existing pen data object.
RemovePenDataStrokes	Deletes a contiguous set of strokes from a pen data object in memory.
The second subgroup of functions adds points to or extracts points from an existing stroke.

ExtractPenDataPoints	Copies points from a specified stroke in a pen data object to a buffer, optionally removing the points.
GetPointsFromPenData	Copies points from a stroke in a pen data object to a buffer (superseded by ExtractPenDataPoints).
InsertPenDataPoints	Inserts points into an existing stroke in a pen data object.
AddPointsPenData	Appends a set of points to a stroke in a pen data object (used mainly by pen-enabled systems).
The third subgroup performs operations on the entire pen data object.

InsertPenData	Merges two separate pen data objects into a single object.
PenDataToBuffer	Writes the data in an existing HPENDATA object to a serial buffer. The function is used to transfer pen data to a file or the clipboard.
PenDataFromBuffer	Creates and loads an HPENDATA object with the data from the serial buffer created by PenDataToBuffer. The function is used to transfer pen data from a file or the clipboard.


 Compressing Pen Data

Data compression plays an important role in pen-based computing. The high sampling rates of a pen device, combined with large amounts of input, result in large blocks of pen data. The pen display library offers two methods of compression, each with advantages and disadvantages depending on the intended use of the pen data. These two functions are associated with data compression:

•	CompressPenData

•	TrimPenData

CompressPenData is generally used to compress pen data before saving it to disk or passing it to the clipboard. It is also used to decompress the data before it is used again. Compressed data must be decompressed to be used by most functions in the pen display library. Compression provides from 60 to 70 percent reduction in pen data size with no loss of data when the data is decompressed (this is called lossless compression).

TrimPenData, in contrast, irreversibly removes data from the pen data object. Much of the information stored in a pen data object can be removed if the data is only to be used for display purposes. Some of the data that you might want to trim from a pen data object includes colinear and duplicate points, empty strokes, timing and "up stroke" information, OEM hardware information, and so on.


 Using Inkset Objects

An inkset object consists of time intervals for either individual strokes or a collection of strokes. In turn, the interval of each stroke consists of the times at which the stroke begins and ends. In this way, a pen-based application can refer to a stroke not only by the points it contains but also by the time interval in which the stroke occurs.

Timing information principally serves recognizers. It provides them with an additional characteristic of the raw data that may offer clues for interpretation.

Timing information, though, has other uses as well. For example, it enables an application to accurately verify a signature by comparing not only the coordinates but also the duration of each stroke against a copy of the original signature. This type of verification is an effective safeguard against forgery because of the difficulty of simultaneously duplicating both the pattern and duration of the original signature.

Because inkset objects are more complicated than can be easily described in this article  and because they are not used in the sample application, see the Programmer's Guide to Pen Services for Microsoft Windows 95, which is included in the Win32 SDK, for more information about their use.


 AN_PKPD Sample Application

The sample application discussed in this article  is called AN_PKPD. It is based on another animation sample called ANIMATE (provided for pen application developers in the SAMPLES\WIN16\PEN directory of the Win32 SDK), which collects, displays, saves, and loads pen data. The ANIMATE sample requires a pen tablet and the installation of the pen services for Microsoft Windows 95. The AN_PKPD sample, on the other hand, requires only Windows 95, the pen data, and either PKPD.DLL or PKPD32.DLL, both of which are supplied with Windows 95.

Sample pen data files, generated from the ANIMATE sample, are provided with the source code for AN_PKPD so that the sample application has some data to work with. These pen data files contain nothing more than pen data objects that are saved directly to disk without compression or any other alteration. You can, however, save these files in compressed format after displaying them. It is suggested that you do not overwrite the original files if you decide to save them as compressed files.


 Reading, Writing, and Compressing Pen Data

The application-defined LoadSave function loads and saves pen data information. The original pen data supplied with the sample files was generated using the ANIMATE sample and is not compressed or trimmed. In the AN_PKPD sample, you have the option of saving any of the files that you load and display. If you do save a file, it is saved in a compressed state. If it has been displayed as "clipped" data (drawn to the original scale, not scaled to a window), it is also in reduced resolution rather than tablet resolution and is trimmed of excess pen data. It is suggested that you do not overwrite the original files if you save them as compressed files.

This section describes the LoadSave function, which calls two internal functions, ReadPenData and WritePenData. The full source for all three functions is at the end of this section.

After retrieving a file name using the FGetFileName local function, CreatePenDataEx is called to create an HPENDATA object that is accessed by the vhpndt variable.

vhpndt = CreatePenDataEx((LPPENINFO)NULL, PDTS_STANDARDSCALE, 0, 0);

Note that CreatePenDataEx specifies the data scaling as the PDTS_STANDARDSCALE value, which is equivalent to PDTS_HIENGLISH (.001 inch per logical unit). This keeps the scaling of the pen data at the highest possible resolution initially — that is, at the same resolution as the pen tablet. All pen tablets are scaled at .001 inches per logical unit.

After opening the file and getting a file handle (hfile), the fOpen variable is checked to determine whether the function was called for reading or writing pen data. If it was called for reading a file, the DestroyPenData function is called on the pen data object to remove any existing ink from a previously displayed file. Then the pen data is read into the pen data object by calling the ReadPenData local function. ReadPenData uses the Windows lread function internally to read the data into the buffer and the pen display library's PenDataFromBuffer function to place that data in the pen data object created by CreatePenDataEx.

Next, the GetPenDataAttributes function is called to determine whether or not the pen data was compressed when it was saved. If it was compressed, the CompressPenData function is called to decompress it. Pen display library functions do not work on compressed data.

The following example shows this process in the LoadSave function.

if (fOpen)

{

   if (vhpndt)  DestroyPenData(vhpndt);

   vhpndt = ReadPenData(hfile);

   // Determine whether the pen data is compressed.

   vnPDTS = GetPenDataAttributes(vhpndt, NULL, GPA_PDTS);

   // If it is compressed, decompress it.

   if ((vnPDTS & PDTS_COMPRESSED) == PDTS_COMPRESSED)

      CompressPenData(vhpndt, CMPD_DECOMPRESS, 0);

Redraw();

}

The final step of loading a file is to call the Redraw local macro, which basically invalidates the window. Redraw can be expanded in the following manner.

PostMessage(vhwndOut, WM_USER, 0, 0);

In the window procedure for vhwndOut, the WM_USER message is handled as follows.

...

   case WM_USER:  // for Redraw macro

      InvalidateRect(hwnd, NULL, TRUE);

      if (IsWindow(vhdlg))

         EnableWindow(GetDlgItem(vhdlg, IDD_PBCLEAR), vhpndt != NULL);

      SetFocus(vhwndOut);     // catch Esc

      break;

...

When data is saved by using the LoadSave function, it is automatically compressed by using the CompressPenData function. Then the internal WritePenData function is called; it uses the pen display library PenDataToBuffer function and the Windows _lwrite function to write the data to a buffer and then to the file. Finally, the pen data in memory is decompressed to its original state so that it can be displayed again.

Compression of pen data is not mandatory, but it is often very useful because it can achieve as much as 70% reduction in size on the disk. To compare compressed and noncompressed pen file sizes, try loading one of the sample pen data files and then save it with a different name. The difference is quite apparent. Here is an example showing WritePenData that compresses, saves, and decompresses the data.

if (fOpen)

{

.

.

.

// Load the pen data here.

.

.

.

}

else{

    // Compress the pen data before saving it.

    CompressPenData(vhpndt, CMPD_COMPRESS, 0);

    WritePenData(hfile, vhpndt);

    // Decompress the pen data for further displaying.

    CompressPenData(vhpndt, CMPD_DECOMPRESS, 0);

 }

Following are the complete listings for the application-defined LoadSave, ReadPenData, and WritePenData functions.

VOID NEAR PASCAL

LoadSave(

   BOOL fOpen)

   {

   HCURSOR hCursor = SetCursor(LoadCursor(NULL, IDC_WAIT));

   HFILE hfile;

   static char const szOpenTitle[] = "Open File";

   static char const szSaveTitle[] = "Save File";

   if (!*vszFile)

      lstrcpy((LPSTR)vszFile, vszSaveFileDef);

   if (FGetFileName(vhwndAN, fOpen, vszFile))

      {

      OFSTRUCT of;

      if (!vhpndt)

        // Create a pen data object to read pen data into.

        vhpndt = CreatePenDataEx((LPPENINFO)NULL, PDTS_STANDARDSCALE, 0, 0);

      if ((hfile = OpenFile((LPSTR)vszFile, &of,

         fOpen? OF_READ: OF_CREATE)) != HFILE_ERROR)

        {

        if (fOpen)

         {

            if (vhpndt)  DestroyPenData(vhpndt);

            vhpndt = ReadPenData(hfile);

            // Determine whether the pen data is compressed.

            vnPDTS = GetPenDataAttributes(vhpndt, NULL, GPA_PDTS);

            // If it is compressed, decompress it.

            if ((vnPDTS & PDTS_COMPRESSED) == PDTS_COMPRESSED)

               CompressPenData(vhpndt, CMPD_DECOMPRESS, 0);

            Redraw();

         }

         else{

            // Compress the pen data before saving it.

            CompressPenData(vhpndt, CMPD_COMPRESS, 0);

            WritePenData(hfile, vhpndt);

            // Decompress the pen data for further displaying.

            CompressPenData(vhpndt, CMPD_DECOMPRESS, 0);

         }

         _lclose(hfile);

         }

      else ErrBox("error opening file", szOpenTitle);

      }

   else if (fOpen)

      InfoBox("did not get file", szOpenTitle);

   else

      InfoBox("did not save file", szOpenTitle);

   SetCursor(hCursor);

//-------------------------------------------------------------------------

//  ReadPenData - reads pen data from a file. The file format at this

//  point is a UINT value representing the size of the pen data,

//  followed by that many bytes of pen data.

//

//  Before calling this function, the caller should have already

//  opened the file specified by hfile and ensured that the

//  file pointer is offset to the beginning of the pen data.

//  When the function returns, the file pointer will be offset

//  to the end of the pen data in the file.

HPENDATA NEAR PASCAL ReadPenData(   // return handle to pen data

   HFILE hfile)   // handle of open file

   {

   HPENDATA hpndt = NULL;

   LONG     cb, cbRead, cbHpndt;

   BYTE     lpbBuf[cbBufMax];    // buffer

   DWORD    dwState = 0L;        // required init

   BOOL     fError = FALSE;

   if (!hfile

      || (cb = _lread(hfile, &cbHpndt, sizeof(LONG))) == HFILE_ERROR

      || cb != sizeof(LONG))

         return NULL;

   while (cbHpndt > 0)

      {

      if ((cbRead = _lread(hfile, lpbBuf, (UINT)min(cbHpndt, cbBufMax)))

         == HFILE_ERROR

         || PenDataFromBuffer(&hpndt, 0, lpbBuf, cbBufMax, &dwState) < 0)

         {

         if (hpndt)

            DestroyPenData(hpndt);

         return NULL;

         }

      cbHpndt -= cbRead;

      }

   return hpndt;

   }

//-------------------------------------------------------------------------

//  WritePenData - writes pen data into a file, preceded by a UINT

//  consisting of the size of the pen data, in bytes.

//

//  Before calling this function, the caller should have

//  already opened the file specified by hfile and ensured that

//  the file pointer is correctly placed.  When the function

//  returns, the file pointer will be offset to the end of the

//  pen data in the file. The function fails if the pen data is

//  larger than 64K.

BOOL NEAR PASCAL WritePenData(   // returns true if successful

   HFILE hfile,         // handle to open file

   HPENDATA hpndt)      // pen data to write

   {

   BYTE lpbBuf[cbBufMax];

   DWORD dwState = 0L;  // required initialization

   LONG cb;

   LONG cbSize;

   if (!hfile || !hpndt)

      return FALSE;

   if (GetPenDataAttributes(hpndt, (LPVOID)&cbSize, GPA_SIZE) < 0)

      return FALSE;

   if (_lwrite(hfile, (LPCSTR)&cbSize, sizeof(LONG)) == HFILE_ERROR)

      return FALSE;

   while ((cb = PenDataToBuffer(hpndt, lpbBuf, cbBufMax, &dwState)) > 0L)

      if (_lwrite(hfile, lpbBuf, (UINT)cb) == HFILE_ERROR)

         return FALSE;

   return cb >= 0;

   }


 Scaling and Trimming Pen Data

It may or may not be necessary to scale pen data for your application. If your application only requires that the pen data be drawn to the scale of the client window, pen services take care of the scaling of the drawing (not the pen data) during the DrawPenDataEx function. All you need do is pass in the rectangle of the client window as a parameter along with a handle to a device context for the window.

If you want to keep the aspect ratios the same as when the ink was drawn on the tablet, you will need to scale the pen data to fit your display. You can do this on a point by point basis with each pen data point, or you can use the built-in scaling capabilities of the pen services.

The example in this section, taken from the ANOutWndProc window procedure's WM_PAINT case, demonstrates how you might go about setting the proper scale for the pen data and trimming unneeded data from the pen data object. In the AN_PKPD sample, the ANDLG dialog box structure contains an fRenderScale member that determines whether to scale the output to the client window or "clip" the drawing, based on the selection in the Drawing Options dialog box. Clipping means that the pen data is displayed in its original aspect ratios and is not confined to the client window area.

When the Scale option is chosen in the Rendering section of the Drawing Options dialog box, vandlg.fRenderScale is set true and the Windows GetClientRect function is called to retrieve the rectangle into which the drawing will be scaled.

if (vandlg.fRenderScale)            // scale to window

     GetClientRect(hwnd, &r);

When Clip is chosen in the Rendering section of the Drawing Options dialog box, vandlg.fRenderScale is set to FALSE and the pen data is to drawn to its original scale. In this case, you will probably want to fit the entire pen data on the display, although some of it may fall outside the client window, thereby being clipped.

In the sample application, this is done by calling the MetricScalePenData function and scaling the pen data to its lowest possible resolution. The lowest display resolution for pen data corresponds to the MM_TEXT mapping mode in Windows, which is set by using the Windows SetMapMode function. Following this, unneeded data is trimmed from the pen data by calling the TrimPenData function.

else

if (vfScaled == FALSE)

 {

    // Display in same aspect ratio as the original ink, and

    // clip the pen data if it is outside the window.

    // Scale the pen data to display the coordinates and trim the

    // excess data.

    if(MetricScalePenData(vhpndt, PDTS_DISPLAY))

       TrimPenData(vhpndt, TPD_COLLINEAR |    // duplicate strokes

                           TPD_EMPTYSTROKES | // strokes w/o points

                           TPD_USER |         // header info

                           TPD_PENINFO |      // OEM data

                           TPD_OEMDATA ,      // OEM data

                           0);

    // Use the following function if there is no animation or

    // up strokes.

    //TrimPenData(vhpndt, TPD_EVERYTHING, 0);

    // Set the mapping mode to the same as PDTS_DISPLAY.

    SetMapMode(hdc, MM_TEXT);

The TrimPenData function could also be called with just the TPD_EVERYTHING value. However, this removes timing data necessary for correct animation as well as up strokes, which you may find interesting to examine using this sample application.

The GetPenDataAttributes function is called next to retrieve the new bounding rectangle of the pen data. This rectangle is used to determine if the data fits on the screen and also used to calculate an aspect ratio if the data does not fit or needs to be further resized. The screen width and height are then retrieved to determine if the new scaling will fit on the screen.

// Get the bounding rectangle of the pen data in PDTS_DISPLAY

// mapping mode.

GetPenDataAttributes(vhpndt, &r, GPA_RECTBOUND);

nMapWidth = r.right - r.left;

nMapHeight = r.bottom - r.top;

// Get the screen resolution.

nDisplayWidth=GetDeviceCaps(hdc, HORZRES);

nDisplayHeight=GetDeviceCaps(hdc, VERTRES);

If the scaling mode is still too large, the data can be resized to fit the screen by using the ResizePenData function. Note that the use of ResizePenData is only recommended for one-time resizing. Resolution is lost when data is repeatedly resized.

In the example used to resize the data, an aspect ratio is determined from the bounding rectangle of the pen data and the rectangle is reduced for margins to 80% of the screen size. This new rectangle is then passed to ResizePenData, which does the work of modifying the coordinates of each of the points in the pen data object.

// If the pen data is still too big, resize it to fit on the screen.

if (r.right > nDisplayWidth || r.bottom > nDisplayHeight)

{

    // Resize the rectangle, maintaining the aspect ratio.

    if(nMapWidth > nMapHeight)

       AspectRatio = (float)nDisplayWidth/(float)nMapWidth;

    else

       AspectRatio = (float)nDisplayHeight/(float)nMapHeight;

    // Reduce slightly for margins on the screen.

    AspectRatio *= (float) 0.8;

    // Set the right and bottom of the rectangle to a new size.

    r.right = (int) (AspectRatio * (float)r.right);

    r.bottom = (int) (AspectRatio * (float)r.bottom);

    // Resize the pen data to a new rectangle.

    ResizePenData(vhpndt, &r);

}

Remember that when data is reduced in scale by using MetricScalePenData or ResizePenData, data is lost. Rescaling it to a higher resolution will not regain the lost data. If you save the data at this point, you should not overwrite the original file.

There are, of course, other methods than those shown here to display ink in the correct aspect ratio. For example, you could use GetPenDataAttributes to retrieve the rectangle of ink and then size a window to the same aspect ratio and let the DrawPenDataEx function scale the drawing into that window.

The following example demonstrates the effect of setting the Rendering option in the Drawing Options dialog box to either Scale or Clip.

//-------------------------------------------------------------------------

LRESULT CALLBACK        // return LRESULT

ANOutWndProc(           // drawing window procedure

   HWND hwnd,           // == vhwndOut

   UINT message,

   WPARAM wParam,

   LPARAM lParam)

   {

   LRESULT lRet = 1L;

   static char const szBoxTitle[] = "DrawPenDataEx";

   int nDisplayWidth, nDisplayHeight, nMapWidth, nMapHeight;

   switch (message)

      {

   	case WM_USER:  // for Redraw macro

    .

    .

    .

   	case WM_CHAR:

    .

    .

    .

   	case WM_PAINT:

    .

    .

    .

            if (vandlg.fRenderScale)            // scale to window

               GetClientRect(hwnd, &r);

            else

             if (vfScaled == FALSE)

               {

                 // Display in the same aspect ratio as the original ink, and

                 // clip the pen data if it is outside the window.

                 // Scale the pen data to display the coordinates and trim the

                 // excess data.

                 if(MetricScalePenData(vhpndt, PDTS_DISPLAY))

                    TrimPenData(vhpndt, TPD_COLLINEAR |	// duplicate strokes

                                        TPD_EMPTYSTROKES |	// strokes w/o points

                                        TPD_USER |	// header info

                                        TPD_PENINFO |	// OEM data

                                        TPD_OEMDATA ,	// OEM data

                                        0);

                 // Use the following function if there is no animation or

                 // up strokes.

                 //TrimPenData(vhpndt, TPD_EVERYTHING, 0);

                 // Set the mapping mode to the same as PDTS_DISPLAY.

                 SetMapMode(hdc, MM_TEXT);

                 // Get the bounding rectangle of the pen data in the PDTS_DISPLAY

                 // mapping mode.

                 GetPenDataAttributes(vhpndt, &r, GPA_RECTBOUND);

                 nMapWidth = r.right - r.left;

                 nMapHeight = r.bottom - r.top;

                 // Get the screen resolution.

                 nDisplayWidth=GetDeviceCaps(hdc, HORZRES);

                 nDisplayHeight=GetDeviceCaps(hdc, VERTRES);

                 // If the pen data is still too big, resize it to fit on the screen.

                 if (r.right > nDisplayWidth || r.bottom > nDisplayHeight)

                 {

                     // Resize the rectangle, maintaining the aspect ratio.

                     if(nMapWidth > nMapHeight)

                       AspectRatio = (float)nDisplayWidth/(float)nMapWidth;

                     else

                       AspectRatio = (float)nDisplayHeight/(float)nMapHeight;

                     // Reduce slightly for margins on the screen.

                     AspectRatio *= (float) 0.8;

                     // Set the right and bottom of the rectangle to a new size.

                     r.right = (int) (AspectRatio * (float)r.right);

                     r.bottom = (int) (AspectRatio * (float)r.bottom);

                     // Resize the pen data to the new rectangle.

                     ResizePenData(vhpndt, &r);

             }

             // Do scaling only once.

             vfScaled = TRUE;


 Displaying the Pen Data

The AN_PKPD.RC resource file sets a menu with two drawing procedure options: AnimatePenData and DrawPenDataEx. The DrawPenDataEx function is used for both procedures.

For nonanimated drawing (IDM_DRAWPARTIAL selection), the DrawPenDataPartial local macro is used.

#define DrawPenDataPartial(hdc, lprect, hpndt, s0, s1, p0, p1)\

   DrawPenDataEx(hdc, lprect, hpndt, s0, s1, p0, p1, NULL, NULL, 0)

Starting and ending strokes and starting and ending points, which can be set in the Drawing Options dialog box, are sent to the DrawPenDataEx function. The following example shows the result of selecting DrawPenDataEx from the DrawProc menu before loading pen data.

case DPDPART:  // partial drawing

  default:

   DrawPenDataPartial(hdc, // DC

      &r,                  // rectangle for scaling and clipping

      vhpndt,              // pen data

      vandlg.uStrk0,       // first stroke to draw

      vandlg.uStrk1,       // last stroke to draw

      vandlg.uPt0,         // first point in first stroke to draw

      vandlg.uPt1);        // last point in last stroke to draw

    break;

  }

The second way that DrawPenDataEx is used in the sample application is for animation. Animation is a process by which DrawPenDataEx draws the pen data using timing information stored when the ink was originally drawn by the user and timing information passed to the function when it is called. Animation requires a callback function and an ANIMATEINFO structure.

To animate pen data, the lpai parameter of DrawPenDataEx must be the address of an ANIMATEINFO structure. The AN_PKPD sample application fills in this structure with the following information.

ANIMATEINFO ai =

{

    sizeof(ANIMATEINFO),                   // structure size

    vandlg.uSpeedPct,                      // speed as a percent

    MakeMs(vandlg.uCBPeriodCode),          // callback period in ms.

    vandlg.fSkipUp? AI_SKIPUPSTROKES: 0,   // options

    0L,                                    // lParam

    0L                                     // reserved

};

The second member of this structure (set here to vandlg.uSpeedPct) sets an animation speed relative to the original speed at which it was drawn. A setting of 100% produces the original speed. The third member sets the callback period. If this is set to None in the dialog box, the callback function is never called and you lose access to the dialog box until animation has finished.

The fourth member of this structure allows you to set options—in this case, the option of skipping "up strokes," which comprise the timing information recorded when the pen is not on the tablet.

To enable animation, you must also supply the address of a callback function to DrawPenDataEx. The AN_PKPD sample application uses a callback function called AnimateProc, which is defined as follows.

AnimateProc(                  // animation callback procedure

   HPENDATA hpndt,            // pen data

   UINT wStroke,              // current stroke

   UINT cPnts,                // number of points yet to draw

   UINT FAR *lpuSpeedPct,     // address of speed percent

   LPARAM lParam)             // application value

The animation callback function is typically used to allow for user activity to occur during animation. For example, the user may want to change the speed of the animation. For this reason, a pointer to the uSpeedPct member of the ANIMATEINFO structure is passed to the animation callback function so that it can be set by the function. The AnimateProc callback function in the application also displays the number of callbacks calls made in the window title of the application, if the user has selected Callback Display from the View menu.

The following example shows the code involved in the three methods of displaying data in the AN_PKPD sample application. Note that some sections of code,  indicated by ellipses, have been removed in order to show only code sections relevant to displaying data. For the complete listing, see the sample application.

AN_PKPD.RC

.

.

.

    POPUP "&DrawProc"

    BEGIN

        MENUITEM "&AnimatePenData",             IDM_DRAWEX, CHECKED

        MENUITEM "DrawPenDataE&x",              IDM_DRAWPARTIAL

    END

AN_PKPD.C

.

.

.

// Defines

.

.

.

#define DPDEX           (IDM_DRAWEX - IDM_DRAWEX)

#define DPDPART         (IDM_DRAWPARTIAL - IDM_DRAWEX)

.

.

.

// Type definitions

typedef struct tagANDLG // dialog box initialization [default values in brackets]

   {

   UINT uStrk0;         // first stroke to render [0]

   UINT uPt0;           // point offset in first stroke [0]

   UINT uStrk1;         // last stroke to render [-1]

   UINT uPt1;           // point offset in last stroke [-1]

   BOOL fSkipUp;        // FALSE to animate upstrokes, TRUE to skip them

   BOOL fAutoRepeat;    // FALSE to end after one rendering, TRUE to repeat to tap

   UINT uCBPeriodCode;  // callback period code [CALLBACKNEVER]

   UINT uSpeedPct;      // speed of animation [100%]

   BOOL fRenderScale;   // TRUE to scale pen data to output window, FALSE to clip

   }

   ANDLG, FAR *LPANDLG;

.

.

.

// Macros

.

.

.

// Draw only part of the pen data.

#define DrawPenDataPartial(hdc, lprect, hpndt, s0, s1, p0, p1)\

   DrawPenDataEx(hdc, lprect, hpndt, s0, s1, p0, p1, NULL, NULL, 0)

.

.

.

//-------------------------------------------------------------------------------

LRESULT CALLBACK        // returns LRESULT

ANOutWndProc(           // drawing window procedure

   HWND hwnd,           // == vhwndOut

   UINT message,

   WPARAM wParam,

   LPARAM lParam)

   {

    .

    .

    .

   switch (message)

      {

   	case WM_USER:  // for Redraw macro

     .

     .

     .

   	case WM_CHAR:

     .

     .

     .

   	case WM_PAINT:

     .

     .

     .

      if (vhpndt)

         {

         PAINTSTRUCT ps;

         HDC hdc = BeginPaint(hwnd, &ps);

         vfDrawing = TRUE;       // set semaphore

         if (hdc)

            {

            RECT r;

            int iRet;

            int nWidthDPD = 1;

            COLORREF crDPD = RGB(0, 255, 255);  // cyan default for DrawPenData pen

            ANIMATEINFO ai =

               {

               sizeof(ANIMATEINFO),                   // structure size

               vandlg.uSpeedPct,                      // speed as a percent

               MakeMs(vandlg.uCBPeriodCode),          // callback Period in ms.

               vandlg.fSkipUp? AI_SKIPUPSTROKES: 0,   // options

               0L,                                    // lParam

               0L                                     // reserved

               };

            .

            .

            .

           // Scaling done here. For more information, see "Scaling

           // and Trimming Pen Data."

            .

            .

            .

            switch (nDrawProc)

               {

            case DPDEX:                      // animation

               vcCB = 0;                     // animation callback counter

               vfReqCxl = FALSE;             // reset

               ShowCancel(vandlg.uCBPeriodCode != CALLBACKNEVER);

               iRet = DrawPenDataEx(

                  hdc,                       // handle to DC

                  &r,                        // rectangle for scaling and clipping

                  vhpndt,                    // pen data

                  vandlg.uStrk0,             // first stroke

                  vandlg.uStrk1,             // last stroke

                  vandlg.uPt0,               // first point in first stroke

                  vandlg.uPt1,               // last point in last stroke

                  vlpfnAnimateProc,          // AnimateProc callback function

                  &ai,

                  0);

               if (iRet < 0 && iRet >= -10)

                  {

                .

                .

                .

                // Error handling code goes here.

                .

                .

                .

               vfReqCxl = FALSE;

               break;

            case DPDPART:  // partial drawing

            default:

               DrawPenDataPartial(hdc, // DC

                  &r,                  // rectangle for scaling and clipping

                  vhpndt,              // pen data

                  vandlg.uStrk0,       // first stroke to draw

                  vandlg.uStrk1,       // last stroke to draw

                  vandlg.uPt0,         // first point in first stroke to draw

                  vandlg.uPt1);        // last point in last stroke to draw

               break;

               }

            ClearAppQueue();  // handle message backlog, if any

            if (vandlg.fAutoRepeat)

               Redraw();

            }

         EndPaint(hwnd, &ps);

         vfDrawing = FALSE;

         }

...

//-------------------------------------------------------------------------

BOOL CALLBACK               // return LRESULT; NB _export to ensure correct ds

AnimateProc(                // animation callback procedure

   HPENDATA hpndt,          // pen data

   UINT wStroke,            // current stroke

   UINT cPnts,              // number of points yet to draw

   UINT FAR *lpuSpeedPct,   // address of speed percent

   LPARAM lParam)           // application value

   {

   BOOL fRet = !vfReqCxl;     // set in dialog box and File menu

   hpndt, wStroke, cPnts, lParam;   // unused

   if (fRet)

      {

      char sz[cbSzTMax];

      if (!vcCB)

         ShowCancel(TRUE);

      ClearAppQueue();     // handle message backlog in app. queue

      *lpuSpeedPct = vandlg.uSpeedPct;    // get latest speed setting

      wsprintf((LPSTR)sz, (LPSTR)"CB=%u", ++vcCB);

        if (vfCB)

         SetWindowText(vhwndAN, (LPSTR)sz);

      // vfReqCxl may have gotten set in ANOutWndProc's WM_PAINT if

      // the user, for example, changed the window size during a callback.

      fRet = !vfReqCxl;

      }

   return fRet;

   }


 Enabling Your Applications For Pen-Based Systems

Windows 95 implements pen services that all developers of Windows 95 − based applications need to be aware of, regardless of whether their applications make use of the functions found in the Pen Windows version 2.0. Windows 95 can run on mobile platforms, and physical keyboards may not be available for these devices. In addition, applications for Far-Eastern markets may need to function without keyboard input. To ensure that your Windows 95 − based applications work appropriately on systems that do not use a keyboard, use the guidelines listed in this section.

For personal computer systems that have a pen installed, Windows 95 provides the pen user with a base level of functionality that includes handwriting edit controls and lens buttons. For Windows 95 − based applications to work well when the pen is the only input device, application developers need to implement the functionality described below and to design the interface to work well with a pen.


 Handwriting Edit Controls

When the version stamp on your application identifies it as a Windows 95 − based application, all edit controls will be replaced by handwriting edit (hedit) controls. To ensure that your application uses hedit controls appropriately, follow the guidelines in this section.

To support hedit controls, you should mark your application as a Windows 95 − based application.

You should also keep the following points in mind when designing your application to use hedit controls:

•	The behavior of the hedit control may not be exactly identical to that of a standard edit control.

•	A hedit control may not cause the display of a dialog box to change; it may display the lens tool or confirmation dialog boxes.

•	If the focus leaves the dialog box, it may not indicate that the user is finished with the field. Pen-related derivative dialog boxes can be disabled on a case-by-case basis at WM_CTLINIT message and HN_BEGINDIALOG or  HN_ENDDIALOG notification message time.


 Lens Buttons

Single-line hedit controls can include a lens button that the user chooses to open a writing window over the control if space permits and if the control is scrollable. This pop-up window acts like a dialog box for entering text. When the window is dismissed, it sends the text to the hedit control. To ensure that your application uses lens buttons appropriately, follow the guidelines in this section.

To support lens buttons, you should include the following in your application:

•	Give multiline edit controls access to the lens tool for multiline edit controls.

•	Leave plenty of room in your hedit controls for the lens button. You should create all single-line hedit controls with the WS_AUTOHSCROLL style even if you think they are wide enough. (Lens buttons will not appear on hedit controls that do not include this style.)

You should also keep the following points in mind when designing your application to use lens buttons:

•	Editing may not only occur within the hedit control.

•	A hedit control may never cause a dialog box to appear.

•	The focus may not have gone away when the hedit control loses focus; the focus may be in the lens control (which is a child of the hedit control).


 Installing Applications

This article describes a standard set of guidelines for installing applications to run with the Microsoft® Windows® 95 operating system.


 About Installing Applications

The purpose of the guidelines described in this article is to enable all application developers to support the same general method of installation for applications. The prime benefit is for users, many of whom have said they prefer a consistent installation method so that they do not need to learn a different method with each new software purchase. These guidelines also benefit the application developer by helping to standardize the organization and management of application files, thereby making initial installations, updates, and application removals easier.


 Installation Program

The installation program plays the primary role in carrying out application installation. The program retrieves information from the user and the computer and installs the files and information needed to run the application successfully. Every installation program carries out these basic steps:

1.	Determines the user's hardware and software configuration and available disk space.

2.	Copies application executable and data files to the appropriate directories on the hard disk.

3.	Sets up the execution environment for the application by modifying existing files and adding entries to the registry.

An installation program (or a companion program) should also be prepared to update or remove an already installed application.

You are responsible for designing and implementing the installation program for your application. Windows does not provide a default installation program, but it does provide an Add/Remove Programs application in Control Panel that helps guide the user through starting the installation, update, or removal process. When the user chooses to install an application, Add/Remove Programs automatically checks the floppy and compact disc read-only memory (CD-ROM) drives for installation programs, searching for filenames such as SETUP.EXE and INSTALL.EXE. If a file is found and the user agrees to finish the installation, Add/Remove Programs starts the program and exits. After that, the started program is responsible for guiding the user through the rest of the installation process.


 Designing the Installation Program

Your installation program should be a "good" Windows-based application, employing the standard Windows graphical user interface, presenting users with options and status. It is recommended that you use the InstallShield SE Toolkit included in the Microsoft® Win32® Software Development Kit (SDK) to develop your installation programs. You should also read relevant sections of The Windows Interface Guidelines for Software Design for information about designing an application that is consistent with the look and feel of the Windows shell. It will also give you information about easy-to-implement features that will add value to your application and make use of new usability functionality in the shell.

Your installation program should always offer setup options. The following options are recommended.

Typical setup	Installs the application with all of the most common settings and copies the most commonly used files. This should be the default setup option.
Compact setup	Copies the fewest number of files needed to operate your application. This option is useful for laptops and computers on which disk space is at a premium.
Custom setup	Allows the user to determine the details of the installation, such as the directories to receive the files and the application features to enable. This option, which is typically used by the power user, should also include an option to set up components left out during a typical or compact setup.
Silent setup	Runs setup without user interaction. This should just be a command line option so that your installation program can be run within a batch script.
Your installation program should always supply defaults. In particular, it should supply a common response to every option so that all the user has to do is press the ENTER key.

Your installation program should never ask the user to install a disk more than once and should make the computer beep when it is time for the user to insert a new disk.

Your installation program should always include a progress indicator to show users how far along they are in the setup procedure.

Your installation program should always give the user a chance to cancel the setup process before it is finished. Your program should keep a log of files that have been copied and settings that have been made so that it can clean up a canceled installation. If the installation is canceled, your program should remove any registry entries it may have made, remove any shortcuts it may have added to the desktop, and delete any files it may have copied onto the user's hard disk.


 Determining the Configuration

Your installation program should determine the hardware and software config-uration of the user's computer before copying files and setting the environment. It is important for the installation program to verify that everything needed to successfully run the application is available. For example, if your application depends on specific hardware or software, your installation program should make sure the hardware or software is present. If it is not, the program should notify the user immediately and recommend a course of action.

Your installation program should always tell the user how much disk space is needed. For custom setup, the installation program should adjust the "space needed" figure as the user selects and deselects options. Your installation program should verify that enough disk space is present for the options that the user selects. If there is not enough free space, the program should notify the user but give the user the option to override the warning.

Your installation program should always determine whether any of the files to be installed are already on the hard disk. This is especially important for shared files, such as commonly used dynamic-link libraries (DLLs). If the files already exist, your installation program should check the version number to ensure that it is not replacing a file with an older version. In other words, the installation program should always make sure the most recent version of a file is installed on the user's disk.


 Copying Files

Your installation program should copy all necessary executable and data files to the appropriate directories. It should never copy files to the WINDOWS or SYSTEM directories. Instead, it should create a directory in the Program Files directory and copy its files there. If the Program Files directory does not exist on the root of the hard disk, your installation program should create it.

It is recommended that your installation program use a long filename for the directory, such as the application name or another descriptive and unique name. Your program should copy the main executable file for your application and any other executable or data files that the user may want to open directly to the newly created directory. For example, if your application's name is "My Wizzy Application.Exe", your installation program should create the \Program Files\My Wizzy Application directory, and copy My Wizzy Application.Exe to that directory.

If you have any other executable or data files, such as .DLL and .HLP files that are specific to your application, your installation program should create a subdirectory, named System, in your application's directory. It should copy the remaining files (except shared files) to this new directory. For example, if your application has a DLL named MWASUP.DLL, your installation program should create the \Program Files\My Wizzy Application\System directory and copy the DLL there.

If any of your executable or data files are shared, your installation program needs to copy the files to yet another directory, depending on how widely the file is to be shared. A file is system-wide shared if many applications from different vendors use it. For example, the VBRUN300.DLL file is a system-wide shared file, because it is used by any application built with Visual Basic. A file is a shared file if it is shared by a set of applications from the same vendor. A common example of this would be an office suite that might use the same drawing program for its word processor as it does for its spreadsheet.

Your installation program should copy all system-wide shared files to the Windows SYSTEM directory. If a given file already exists in this directory, the program should overwrite it with your application file only if your file is a more recent version. The GetFileTime, GetFileVersionInfo, and GetFileInformationByHandle functions can be used to determine which file is more recent. After copying a DLL file, your installation program should increment the usage counter for the DLL in the registry. For more information about the usage counter, see "Adding Entries to the Registry" later in this article.

Your installation program should copy all shared files to a System directory in the \Program Files\Common Files directory. If the directory does not exist, the installation program should create it. Again, it is recommended that your program use a descriptive and unique name. For example, if there is a shared file named My Wizzy Speller.Exe, your program should create a directory named \Program Files\Common Files\System and copy the file there. The location of the Program Files and Common Files directories is registered (using the macro REGSTR_PATH_SETUP) in the HKEY_LOCAL_MACHINE root under the SOFTWARE\Microsoft\Windows\CurrentVersion key. The value names are ProgramFilesDir and CommonFilesDir.

When your installation program installs applications on computers running Microsoft® Win32s® with Windows version 3.x, it needs to be aware that the system does not support long filenames. Your installation program will need to use the short 8.3 filename equivalent for Program Files and Common Files, which is Progra~1 and Common~1, respectively.


 Using a WININIT.INI File to Replace DLLs in Windows 95

Installation programs often need to replace old .DLL files with new versions. However, Windows 95 does not allow a .DLL file to be replaced if the DLL is currently loaded into memory. To solve this problem, your installation program must copy the new .DLL files to the user's machine, giving each new .DLL file a temporary name that is different from that of the corresponding old .DLL file. Your installation program must also copy a file called WININIT.INI to the user's machine. The WININIT.INI file is processed by the WININIT.EXE program when the system is restarted, before any DLLs are loaded. The WININIT.INI file specifies the destination path and filename for each new DLL.

The WININIT.INI file contains a [rename] section that specifies the source and destination path and filenames for the new DLLs. The entries in the [rename] section have the following syntax.

DestinationFileName=SourceFileName

The following syntax is used to delete a file.

NUL=SourceFileName

The following example shows a [rename] section from a WININIT.INI file.

[rename]

C:\WINDOWS\Fonts\arial.ttf=C:\WINDOWS\Fonts\arial.win

C:\WINDOWS\SYSTEM\advapi32.dll=C:\WINDOWS\SYSTEM\advapi32.tmp

When the system is restarted, it searches for a WININIT.INI file and, if it finds one, runs WININIT.EXE on the file. After processing the file, WININIT.EXE renames it to WININIT.BAK.

The DestinationFileName and SourceFileName must both be short (8.3) names instead of long filenames because WININIT.EXE is a non-Windows application and runs before the protected mode disk system is loaded. Because long filenames are only visible when the protected mode disk system is loaded, WININIT.EXE won't see them, and therefore, won't process them.

WININIT.INI is not supported in Microsoft® Windows NT™. To replace DLLs already loaded in memory, use the MoveFileEx function.


 Setting Up the Environment

Your installation program needs to set up the proper environment for your application. The environment consists of application-specific entries in the initialization files, the registry, and the Start button.


 Setting Initialization Files

Windows does not require the AUTOEXEC.BAT and CONFIG.SYS files. Because these files may not be present on the hard disk, you should make sure that your application does not require entries in those files.

Windows does not require you to modify the PATH environment variable. Instead, Windows looks for your .EXE and .DLL files in the application-specific path specified in the registry. Your installation program is responsible for setting the application-specific path when it installs the application.

Windows does not require an application to load device drivers at boot time. This means that your application does not need to specify drivers in the CONFIG.SYS file. Instead, your application can dynamically load the drivers when it starts by using the virtual device loader functions of Windows or the CreateFile and DeviceIoControl functions of Win32.

Your installation program should not make entries in the WIN.INI file. It should use the registry instead. If you have information that you do not want to put in the registry, your installation program should create a private initialization file and place it in the same directory that contains your application's executable files.


 Adding Entries to the Registry

Your installation program should add information about your application to the registry. In particular, it should always add the following entries.

HKEY_LOCAL_MACHINE\SOFTWARE\CompanyName\ProductName\Version

Stores information pertaining to this particular copy of the application.

HKEY_CURRENT_USER\SOFTWARE

Stores user-specific preferences. This is information that application vendors used to store in the WIN.INI file. For example Microsoft Word might store the fact that a user wants the automatic save feature turned off here.

Your installation program should always add application-specific paths to the registry for your application. If your installation program registers an path, Windows sets the PATH environment to be the registered path when it starts your application. Your program sets the path in the HKEY_LOCAL_MACHINE root under the \SOFTWARE\Microsoft\Windows\CurrentVersion\AppPaths key (using the REGSTR_PATH_APPPATHS macro). Your installation program must create a new key having the same name as your application's executable file. Under this new key, it creates the Path value name and assigns it a path using the same format as expected by the PATH environment variable.

The following example shows application-specific paths for both Windows® Excel, Excel.Exe, and My Wizzy Application.Exe.

HKEY_LOCAL_MACHINE
  SOFTWARE\Microsoft\Windows\CurrentVersion\AppPaths
    Excel.Exe
      Default=D:\Program Files\MS Office\Excel\Excel.Exe
      Path= D:\Program Files\MS Office\Excel\Excel.Exe;D:\Program
          Files\Common Files\MS Office;

    My Wizzy App.Exe
         Default=d:\Program Files\My Wizzy Application\My Wizzy
             Application.Exe
         Path= D:\Program Files\My Wizzy Application;D:\Program Files\My
             Wizzy Application\Application Extensions;

In the preceding example, the Default value specifies the full path to the corresponding executable file. This value is typically used by Windows in the Start Run command. If the user types the name of your application but Windows fails to find it in the current path, Windows uses this value to locate and start your application.

Your installation program should keep track of shared DLLs. When installing an application that uses shared DLLs, it should increment the usage counter for the DLL in the registry. When removing an application, it should decrement the usage counter. If the result is zero, the user should be given the option of deleting the DLL. The user should be warned that other applications may actually need the DLL and will not work if it is missing. The following example shows the general format for usage counters in the registry.

\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\SharedDLLs
    C:\Program Files\Common Files\System\vbrun300.DLL=3


 Supporting Context Menu Operations

Your installation program can provide support for context menu operations, such as Open, Print, and Print To, by setting appropriate registry entries. The context menu appears when the user clicks mouse button 2 on a document associated with your application.

Enabling Print in the registry gives the shell instructions about what to execute when the user chooses Print from the context menu. Usually an application will display a dialog box that says " Printing page n of N on LPTX."

Enabling Print To in the registry specifies the default action for "drag print." Print To displays the same dialog box as Print when you drag it to a specific printer. The Print To option is not displayed on the context menu, so it does not bring up anything (that is, it cannot be chosen).

The following example shows how to set commands for the context menu for files having the .WRI filename extension.

HKEY_CLASSES_ROOT\.wri = wrifile
HKEY_CLASSES_ROOT\wrifile = Write Document
HKEY_CLASSES_ROOT\wrifile\DefaultIcon =
    C:\Progra~1\Access~1\WORDPAD.EXE,2
HKEY_CLASSES_ROOT\wrifile\shell\open\command = WORDPAD.EXE %1
HKEY_CLASSES_ROOT\wrifile\shell\print\command =
    C:\Progra~1\Access~1\WORDPAD.EXE /p "%1"
HKEY_CLASSES_ROOT\wrifile\shell\printto\command =
    C:\Progra~1\Access~1\WORDPAD.EXE /pt "%1" "%2" "%3" "%4"

In the preceding commands, the %1 parameter is the filename, %2 is the printer name, %3 is the driver name, and %4 is the port name. In Windows 95, you can ignore the %3 and %4 parameters (the printer name is unique in Windows 95).


 Adding the Application to the Start Button

Your installation program can still create a "Program Group" in the Programs folder by using dynamic data exchange (DDE) as used in Windows version 3.1, but this is no longer the preferred method. Instead, your installation program should add an icon for your primary application to the Start menu. The program can, optionally, prompt the user to choose which program icons to place in the menu. However, icons should not be added for every application in your package, and an extensive hierarchy of programs and folders should not be created on the Start menu.

To add an icon to the Start menu, your installation program should create a link to your application's executable file and place the link in the directory named \WINDOWS\STARTMEN\PROGRAMS. (Note that the WINDOWS directory should actually be the path returned by the GetWindowsDirectory function.) An installation program can create a link by using the IShellLink interface.


 Using Filename Extensions

In Windows 95, filename extensions should always describe a file type. Your installation program should not rename old or backup files by giving them filename extensions like .001, .BAK, or .XX1. If the file type does not change, the program should give the file a new name. For example, it can use long filenames to change the old version of a filename, such as SAMPLE.DLL being changed to Copyof SAMPLE.DLL.

The following table lists filename extensions currently used in Windows. You should not use these filename extensions, unless your file fits the given type description.

Extension	Type description
386	Windows virtual device driver
3GR	Screen grabber for Microsoft® MS-DOS®  − based applications
GR3	Windows version 3.0 screen grabber
ACM	Audio Compression Manager driver
ADF	Administration configuration files
ANI	Animated mouse cursor
AVI	Video clip
AWD	Fax viewer document
AWP	Fax key viewer
AWS	Fax signature viewer
BAK	Backed-up file
BAT	MS-DOS batch file
BFC	Briefcase
BIN	Binary data file
BMP	Picture (Windows bitmap)
CAB	Windows setup file
CAL	Windows Calendar file
CDA	CD audio track
CFG	Configuration file
CNT	Help contents
COM	MS-DOS −based  program
CPD	Fax cover page
CPE	Fax cover page
CPI	International code page
CPL	Control Panel application
CRD	Windows Cardfile document
CSV	Command-separated data file
CUR	Cursor (pointer)
DAT	System data file
DCX	Fax viewer document
DLL	Application extension (dynamic-link library)
DOC	WordPad document
DOS	MS-DOS − based file (also extension for NDIS2 net card and protocol drivers)
DRV	Device driver
EXE	Application
FND	Saved search results
FON	Font file
FOT	Shortcut to font
GR3	Windows version 3.0 screen grabber
GRP	Program group file
HLP	Help file
HT	HyperTerminal file
ICM	Image color matching (ICM) profile
ICO	Icon
IDF	MIDI instrument definition
INF	Setup information
INI	Configuration settings
KBD	Keyboard layout
LGO	Windows logo driver
LIB	Static-link library
LNK	Shortcut
LOG	Log file
MCI	MCI command set
MDB	File viewer extension
MID	MIDI sequence
MIF	MIDI instrument file
MMF	Microsoft Mail message file
MMM	Animation
MPD	Mini-port driver
MSG	Microsoft Exchange mail document
MSN	The Microsoft Network home base
MSP	Windows Paintbrush picture
NLS	Natural language services driver
PAB	Microsoft Exchange personal address book
PCX	Picture (PCX format)
PDR	Port driver
PF	ICM profile
PIF	Shortcut to MS-DOS − based application
PPD	PostScript® printer description file
PRT	Printer formatted file (result of Print to File option)
PST	Microsoft Exchange personal information store
PWL	Password list
QIC	Backup set for Microsoft Backup
REC	Windows Recorder file
REG	Application registration file
RLE	Picture (RLE format)
RMI	MIDI sequence
RTF	Document (rich text format)
SCR	Screen saver
SET	File set for Microsoft Backup
SHB	Shortcut into a document
SHS	Scrap
SPD	PostScript printer description file
SWP	Virtual memory storage
SYS	System file
TIF	Picture (TIFF format)
TMP	Temporary file
TRN	Translation file
TSP	Windows telephony service provider
TTF	TrueType font
TXT	Text document
VBX	Visual Basic control file
VER	Version description file
VXD	Virtual device driver
WAV	Sound wave
WPC	WordPad file converter
WRI	Windows Write document
XAB	Microsoft Mail address book
You should also investigate filename extensions commonly used by popular applications so that you can avoid creating a new extension that might conflict with them, unless you intend to replace or supersede the functionality of those applications.


 Register Document Types

Your installation program should register every file type used that is not provided by Windows 95:

•	For the files of interest to the user, such as document types, the installation program should register both an icon and a description. It should provide good OLE/shell verbs and also add a "ShellNew" entry so your document type shows up in the "New" menu. This menu is available when the user clicks mouse button 2 on any container or chooses the File menu in a folder window.

•	For files that the user would have a good reason to double-click, the installation program should provide the file with a good icon and description and also a registered "open" action so that the user can double-click it.

•	For files that are less interesting to the user, such as .INI or configuration files, the installation program should provide the file with a good icon and description. The best way to do this is to consistently use predefined filename extensions, such as .INI, .SYS, and .TXT.

•	For files of little interest to the user, the installation program should minimally register a file type so that there is a decent description in "Details" view (and possibly an icon). If the program does not register the type, the file is identified by whatever the filename extension may be. Registering the type ensures that the file is identified by the description and related icon.


 Network Issues

Most corporate customers would like to run their applications from a network server. To support running from a server, you need to provide your installation application in both a server and client package. The server package consists of executable files, DLLs, data files, and any files that must be shared across the network. The client package consists of the portions of the application that are user-specific, including registry settings, details about the user's configuration, and information about how to locate the server package.

Generally, you should have two installation programs or modes for installing the packages: an administrative installation program that an administrator runs for preparing the server and a client installation program that runs on each client machine and sets up the connection to the server. The client installation program should also have a batch or silent installation option so that an administrator can deploy your application with automatic software distribution tools. Ideally, the client installation functions are built into the application so that it configures itself when it starts (perhaps by reading options set by the administrative installation program).

Corporate customers typically run Windows from a shared copy on a server. The following directories are stored on the server; your application and client installation program may or may not have write access to these directories.

\Windows

    \Command

    \Inf

    \Fonts

    \Help

    \Hyperterm

    \Pif

    \System

        \Color

        \Iosubsys

        \Viewers

        \VMM32

You should use the GetSystemDirectory function to find the SYSTEM subdirectory. To find the WINDOWS directory, look in the following registry location.

HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Setup

    SharedDir=

Your application should store files that cannot be shared (machine-specific files) in a "machine" directory with write access. The machine directory contains files and settings that are specific to a particular machine. If one user changes settings, anyone else who uses that computer gets those settings. If the machine has user profiles turned on, Windows copies the user-specific settings into and out of the machine directory when the user logs on and off. That way, if a user changes a machine setting (that is, a hardware setting), every user is affected, but if the user changes a user-specific setting, the change affects only that user.

The machine directory should not contain any executable files. You can find the machine directory by calling the GetWindowsDirectory function. The following files and directories are stored in the machine directory.

WIN.COM WININIT.EXE *.INI *.GRP	\Spool \Desktop \Startmen \Nethood
Your application and installation program should fully support Universal Naming Convention (UNC) paths. If an application is being installed on a network path, the installation program should store a UNC path in any shortcuts it makes for the Start menu. Your installation program can use the Windows network functions (WinNet*) to determine if a path is a network path.

You should consider what configuration settings an administrator might want to set for a user and what restrictions an administrator might want to place on a user (for example, not letting a user access a configuration menu). You should put these settings and restrictions in a System Policy template (.ADM) file.

For more information about network issues relating to Windows 95, see the Microsoft Windows 95 Resource Kit.


 CD-ROM Considerations

Autorun is a feature that is supported on CD-ROM drives. When the user loads a compact disc (CD) into the drive, Windows 95 automatically runs a file on the CD. The file to run must be specified in an AUTORUN.INF file located in the CD's root directory. The following example shows a typical entry in an AUTORUN.INF file.

[AutoRun]

OPEN=myprog.exe

The autorun feature can be disabled by the device manager or by an entry in the SYSTEM.INI file. Your application must not rely on the autorun feature being available. Also, the autorun feature should not be used to automatically install your application on a user's hard disk without the user being asked first.

If you provide your application on a CD, your installation program should give the user the choice of running the application from the CD or installing it on the hard disk. You should keep the following points in mind when using the autorun feature:

•	Even if the user chooses to run your application from the CD, your program will need to copy some files to the hard disk (for example, writable files and files containing the user's preferences).

•	If you include a shortcut on the desktop, your application should display a message when the user selects the shortcut and the CD is not loaded.


 Installing Fonts

By carrying out these steps, you can write a single font installation routine that works for both Microsoft® Windows NT™ and Windows 95:

1.	Determine whether the platform is Windows 95 or Windows NT. This distinction is important because Windows 95 allows a shared network installation where most system files, including fonts, are stored on a centrally managed server. To determine the platform, look in the following registry location for a "SharedDir" value.

HKeyLocalMachine\Software\Microsoft\Windows\CurrentVersion\Setup

The data value of "SharedDir" is the UNC name of the server and sharepoint of the shared directory. In most cases, a shared directory is marked as read-only by the system administrator, so your installation program should also check to see if it can write to this location. If it cannot, it should let the user install the fonts in a different location, or stop the setup process.

2.	Check whether the TrueType® font being installed is already present on the system by using the EnumFontsEx function. If that font is present, the program should check to see if its version is newer by matching the installed font name with the filename on the disk. The font name is stored in the following registry location for both Windows 95 and Windows NT.

HKeyLocalMachine\Software\Microsoft\Windows\CurrentVersion\Fonts

The subkeys in this registry location contain the full name of the font file as the value key, followed by the filename of the .TTF file as the key data. If the filename in the registry is just a filename with no path information, the font is installed in the \WINDOWS\FONTS directory for Windows 95 or the \WINDOWS\SYSTEM directory for Windows NT. Because TrueType font files do not carry a version resource, your program will need to retrieve the version string from the 'name' table in the .TTF file.

•	Before copying the .TTF file to the appropriate directory, the installation program should check to see if the filename already exists in that directory. If it does, the program should rename your .TTF file to some other name, perhaps by appending a number to the end of the basename.

•	After copying the .TTF file to the user's disk, the installation program should inform the system that it wants the font to be available. The program should pass it the .TTF filename directly by using the AddFontResource function. Windows 95 and Windows NT do not require the creation of .FOT files.

•	To make the font installation permanent, the installation program should add the font name and filename to the registry by writing both of the values to the following registry location.

HKeyLocalMachine\Software\Microsoft\Windows\CurrentVersion\Fonts


 Removing an Application

Your installation program can direct the Add/Remove Programs application in Control Panel to list your application as an application that can be "automatically removed" by adding the following entries to the registry.

HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Uninstall\application-name    DisplayName=product-name    UninstallString=full-path-to-program  command-line-parameters

Add/Remove Programs displays the product name specified by the DisplayName value in its list of applications that can be removed. Windows uses the value specified by the UninstallString value to start the uninstall program to carry out the removal of the application. This string needs to completely specify the command-line parameters needed to execute the uninstall program and remove the application. A full path is required. If both the DisplayName and UninstallString values are not complete, Add/Remove Programs will not list the application.

Windows needs to know when the removal of the application is done, so it requires the UninstallString value to specify the uninstall program that actually carries out the removal. A batch file or other program that starts the removal program should not be specified.

Your installation program should use casual names, including spaces, for the application-name and DisplayName value. Casual names help keep the tree comprehensible for users who browse the registry. The registry locations are defined as constants for C programmers in the REGSTR.H header file. Descriptions of the macros follow.

REGSTR_PATH_UNINSTALL	Path to uninstall branch
REGSTR_VAL_UNINSTALLER_DISPLAYNAME	DisplayName
REGSTR_VAL_UNINSTALLER_COMMANDLINE	UninstallString
The uninstall program must display a user interface that informs the user that the removal process is taking place. It is recommended that you use the sample uninstall program in the InstallShield SE Toolkit as the starting point for your own uninstall program. The sample illustrates the appropriate user interface and application removal tasks.

Your uninstall program should provide a silent option that allows the user to run it remotely. The uninstall program should also display clear and helpful messages for any errors it encounters during the removal of the application. Windows will only detect and report a failure to start the uninstall program.

Because computers running Microsoft® Win32s® and Windows NT do not provide Add/Remove Programs in Control Panel, your installation program needs to include an Icon in the Applications program group so that the user can launch the uninstall program.

To summarize, an uninstall program should complete the following steps:

•	Remove all information used by the application from the registry. If decrementing a DLL's usage count results in a usage count of zero, the uninstall program should display a message offering to delete the DLL or save it in case it may be needed later.

•	Remove any shortcuts to the application from the desktop.

•	Remove all program files related to the application. The uninstall program should not remove files that the user created with the application unless the user agrees to delete them. If the user's files are stored in the application's directory tree, the uninstall program should ask the user if the files should be moved to a new directory.

•	Remove empty directories left by the application.


 Quick Checklist for Planning an Installation Program

You should keep the following points in mind when you plan an installation program for your application:

•	Store private initialization (.INI) files in the application directory if the application is running locally or in the directory returned by the GetWindowsDirectory function if the application is shared.

•	Do not copy files to the WINDOWS or SYSTEM directories. If you include fonts with your application, you should put the fonts in the Fonts folder.

•	Tell the user how much space the installation will take and use a progress indicator.

•	Make sure to create all directories in the user selected path.

•	Do not assume that floppies are on Drive A.

•	Always supply defaults.

•	Name your installation program SETUP.EXE.


 Shell's Namespace

A namespace is a collection of symbols, such as database keys or file and directory names.


 About the Shell's Namespace

The Microsoft® Windows® 95 shell uses a single hierarchical namespace to organize all objects of interest to the user: files, storage devices, printers, network resources, and anything else that can be viewed using Windows Explorer. The root of this unified namespace is the Windows 95 desktop.

In many ways, the shell's namespace is analogous to a file system's directory structure. However, the namespace contains more types of objects than just files and directories. Familiar file system concepts, such as filename and path, have been replaced by more general and powerful associations. This article discusses some of these associations, outlines the organization of the shell's namespace, and describes the functions and interfaces associated with the namespace.


 Folders and File Objects

A folder is a collection of items in the shell's namespace. A folder is analogous to a file system directory, and many folders are, in fact, directories. However, there are also other types of folders, such as remote computers, storage devices, the desktop folder, the Control Panel, the Printers folder, and the Fonts folder. A folder may contain other folders as well as items called file objects. A file object may be an actual file, or it can be a Control Panel application, a printer, or another type of object. Each type of folder can only contain certain kinds of file objects; for example, you cannot move a Control Panel application into a file system directory.

Because there are many kinds of folders and file objects, each folder is a OLE component object model (COM) object that "knows" how to enumerate its contents and carry out other actions. More precisely, each folder implements the IShellFolder interface. Retrieving the IShellFolder object for a shell folder is referred to as binding to the folder. An application that binds to a folder must eventually free the IShellFolder interface object by calling its Release member function.

You can bind to the desktop folder (retrieve the folder's IShellFolder interface) by using the SHGetDesktopFolder member function. You can enumerate subfolders by using the IShellFolder::EnumObjects member function. You can bind to a subfolder of any given folder by using the IShellFolder::BindToObject member function. Using these three functions, an application can navigate throughout the shell's entire namespace.


 Item Identifiers and Pointers to Item Identifier Lists

Objects in the shell's namespace are assigned item identifiers and item identifier lists. An item identifier uniquely identifies an item within its parent folder. An item identifier list uniquely identifies an item within the shell's namespace by tracing a path to the item from the desktop. A pointer to an item identifier list, which is sometimes called a PIDL (pronounced piddle), is used with many functions.

Item identifiers and PIDLs are much like the filenames and paths used in a file system. However, they share this important difference: item identifiers and PIDLs are binary data structures that never appear to the user. Item names called display names that can be shown to the user are described later.

An item identifier is defined by the variable-length SHITEMID structure. The first two bytes of this structure specify its size, and the format of the remaining bytes depends on the parent folder, or more precisely on the software that implements the parent folder's IShellFolder interface. Except for the first two bytes, item identifiers are not strictly defined, and applications should make no assumptions about their format. To determine whether two item identifiers are equal, an application can use the IShellFolder::CompareIDs member function.

The ITEMIDLIST structure defines an element in an item identifier list (the only member of this structure is an SHITEMID structure). An item identifier list consists of one or more consecutive ITEMIDLIST structures packed on byte boundaries, followed by a 16-bit zero value. An application can walk a list of item identifiers by examining the size specified in each SHITEMID structure and stopping when it finds a size of zero.

Item identifier lists are almost always allocated using the shell's allocator (an IMalloc interface that you can retrieve by using the SHGetMalloc function). For example, some shell functions create an item identifier list and return a PIDL to it. In such cases, it is usually the application's responsibility to free the PIDL using the shell's allocator. Note that the SHGetMalloc function retrieves the task allocator for OLE applications.


 Folder Locations

Certain folders have special meanings for the shell. An application can use shell functions to retrieve the locations of these special folders and to enable the user to browse for specific folders.

Some special folders are virtual folders — so called because they are not actual directories on any storage device, local or remote. Virtual folders like the desktop folder, the My Computer folder, and the Network Neighborhood folder make a unified namespace possible by serving as containers for any number of storage devices and network resources. Other virtual folders contain file objects, such as printers, that are not part of the file system.

File system directories that the shell uses for specific purposes are also considered special folders. Examples include the Programs folder (which contains the user's program groups) and the desktop directory (which is used to physically store files that have been copied to the desktop folder). The locations of special file system folders are stored in the registry under the HKEY_CURRENT_USER / Software / Microsoft / Windows / CurrentVersion / Explorer / Shell Folders key.

You can use the SHGetSpecialFolderLocation function to retrieve the location of a special folder, which can be virtual or part of the file system. The function returns a PIDL, which the application must eventually free using the shell's allocator. If the folder is part of the file system, you can convert the PIDL to a file system path by using the SHGetPathFromIDList function. For a list of special folders, see the description of the SHGetSpecialFolderLocation function.

To display a dialog box that enables the user to browse for a folder, you can use the SHBrowseForFolder function. An application might use this function to prompt the user for a directory or remote computer. This function can also be used to browse for network printers, even though printers are not considered folders. An application can specify the root folder to browse from. For example, to prompt the user for a program group, you might call SHBrowseForFolder specifying the PIDL for the Programs folder as the root.


 Item Enumeration

An application that uses the IShellFolder interface for a folder can determine the folder's contents by using the EnumObjects member function. This member function creates an item enumeration object, which is a set of item identifiers that can be retrieved by using the IEnumIDList interface.

One or more item identifiers can be retrieved from the enumeration object by using the IEnumIDList::Next member function. Calling this function repeatedly allows an application to retrieve all of the item identifiers one or more at a time. Using other member functions, you can skip items in the sequence, return to the beginning of the sequence, or "clone" the enumeration object to save its state.

When you are finished using the enumeration object, you must free it by calling the IEnumIDList::Release member function.


 Display Names and Filenames

Because item identifiers are binary data structures, each item in a shell folder also has a display name, which is a string that can be shown to the user. You can use member functions in the IShellFolder interface to retrieve an item's display name, to find an item with the specified display name, or to change an item's display name.

The IShellFolder::GetDisplayNameOf member function can be used to retrieve a display name. The actual string returned depends on the type of display name specified. Values identifying the different types of display names are defined by the SHGNO enumerated type and have the SHGDN prefix. The type of display name that an application requests might depend on whether an item is shown by itself or within its parent folder. (A shared directory might be labeled Public on 'bill' in the former case and simply Public in the latter case.)

A special type of display name is one that can be converted back to an item identifier by using the IShellFolder::ParseDisplayName member function. You might use this type of display name as a parameter to the ShellExecute function or as a command-line argument for an application. For items within the file system, the display name for parsing is the same as the file system path. You can also convert a PIDL to a file system path by using the SHGetPathFromIDList function.

The IShellFolder::SetNameOf member function can be used to change the display name of a file object or subfolder. Changing an item's display name also changes its item identifier, so the function returns a PIDL containing the new item identifier. For file objects or folders within the file system, changing the display name renames the file or directory.


 Object Attributes and Interfaces

Every file object and folder has attributes that determine, among other things, what actions can be carried out on it. An application can determine the attributes of any file object or folder and can retrieve interfaces for items in a shell folder.

To determine the attributes of a file object or folder, an application can use the IShellFolder::GetAttributesOf member function. Attributes include capabilities (such as whether a file object can be deleted or can be a drop target), display attributes (such as whether a folder is shared), contents flags (such as whether a folder has subfolders), as well as other attributes (such as whether an object is a folder, whether it is part of the file system, and so on). For a list of attributes, see the description of the IShellFolder::GetAttributesOf member function.

An application can retrieve interfaces that can be used to carry out actions on a file object or folder by using the IShellFolder::GetUIObjectOf member function. For example, the application can display the property sheets for a file object by retrieving the object's IContextMenu interface and activating the Properties command.


 Using the Shell's Namespace

This section contains examples that demonstrate the functions and interfaces associated with the shell's namespace.


 Using PIDLs and Display Names

This section presents an example illustrating how to retrieve the location of a special folder, walk an item identifier list, and use the IShellFolder interface to retrieve display names. The example is a Microsoft® Win32®-based console application that prints the display names of the folders a user would have to open to get to the Programs folder. To display them, the application would carry out these steps:

1.	Retrieve the PIDL (obtain a pointer to an item identifier list) for the Programs folder by using the SHGetSpecialFolderLocation function.

2.	Bind to the desktop folder (retrieve the folder's IShellFolder interface) by using the SHGetDesktopFolder function.

3.	Walk the item identifier list and process elements as follows: print the subfolder's display name, bind to the subfolder, and release the parent folder's IShellFolder interface.

Before carrying out any of the preceding steps, the application uses the SHGetMalloc function to retrieve a pointer to the shell's IMalloc interface, which it saves in the following global variable.

// Global pointer to the shell's IMalloc interface.

LPMALLOC g_pMalloc;

The following example shows the application's main function. This function carries out all of the steps described previously, although it calls the application-defined GetNextItemID and CopyItemID functions to walk the item identifier list and the application-defined PrintStrRet function to print the display names. These application-defined functions are described later in this section.

// main - the application's entrypoint function

int __cdecl main()

{

    LPITEMIDLIST pidlPrograms;

    LPSHELLFOLDER pFolder;

    // Get the shell's allocator.

    if (!SUCCEEDED(SHGetMalloc(&g_pMalloc)))

        return 1;

    // Get the PIDL for the Programs folder.

    if (SUCCEEDED(SHGetSpecialFolderLocation(NULL,

            CSIDL_PROGRAMS, &pidlPrograms))) {

        // Start with the desktop folder.

        if (SUCCEEDED(SHGetDesktopFolder(&pFolder))) {

            LPITEMIDLIST pidl;

            // Process each item identifier in the list.

            for (pidl = pidlPrograms; pidl != NULL;

                    pidl = GetNextItemID(pidl)) {

                STRRET sName;

                LPSHELLFOLDER pSubFolder;

                LPITEMIDLIST pidlCopy;

                // Copy the item identifier to a list by itself.

                if ((pidlCopy = CopyItemID(pidl)) == NULL)

                    break;

                // Display the name of the subfolder.

                if (SUCCEEDED(pFolder->lpVtbl->GetDisplayNameOf(

                        pFolder, pidlCopy, SHGDN_INFOLDER,

                        &sName)))

                    PrintStrRet(pidlCopy, &sName);

                // Bind to the subfolder.

                if (!SUCCEEDED(pFolder->lpVtbl->BindToObject(

                        pFolder, pidlCopy, NULL,

                        &IID_IShellFolder, &pSubFolder))) {

                    g_pMalloc->lpVtbl->Free(g_pMalloc, pidlCopy);

                    break;

                }

                // Free the copy of the item identifier.

                g_pMalloc->lpVtbl->Free(g_pMalloc, pidlCopy);

                // Release the parent folder and point to the

                // subfolder.

                pFolder->lpVtbl->Release(pFolder);

                pFolder = pSubFolder;

            }

            // Release the last folder that was bound to.

            if (pFolder != NULL)

                pFolder->lpVtbl->Release(pFolder);

        }

        // Free the PIDL for the Programs folder.

        g_pMalloc->lpVtbl->Free(g_pMalloc, pidlPrograms);

    }

    // Release the shell's allocator.

    g_pMalloc->lpVtbl->Release(g_pMalloc);

    return 0;

}

Following is the GetNextItemID function. Given a pointer to an element in an item identifier list, the function returns a pointer to the next element (or NULL if there are no more elements). The main function calls this function to walk the item identifier list for the Programs folder.

// GetNextItemID - points to the next element in an item identifier
//     list.

// Returns a PIDL if successful or NULL if at the end of the list.

// pdil - previous element

LPITEMIDLIST GetNextItemID(LPITEMIDLIST pidl)

{

    // Get the size of the specified item identifier.

    int cb = pidl->mkid.cb;

    // If the size is zero, it is the end of the list.

    if (cb == 0)

        return NULL;

    // Add cb to pidl (casting to increment by bytes).

    pidl = (LPITEMIDLIST) (((LPBYTE) pidl) + cb);

    // Return NULL if it is null-terminating or a pidl otherwise.

    return (pidl->mkid.cb == 0) ? NULL : pidl;

}

Following is the CopyItemID function. Given a pointer to an element in an item identifier list, the function allocates a new list containing only the specified element followed by a terminating zero. The main function uses this function to create single-element PIDLs, which it passes to IShellFolder member functions.

// CopyItemID - creates an item identifier list containing the first

//     item identifier in the specified list.

// Returns a PIDL if successful or NULL if out of memory.

LPITEMIDLIST CopyItemID(LPITEMIDLIST pidl)

{

    // Get the size of the specified item identifier.

    int cb = pidl->mkid.cb;

    // Allocate a new item identifier list.

    LPITEMIDLIST pidlNew = (LPITEMIDLIST)

        g_pMalloc->lpVtbl->Alloc(g_pMalloc, cb + sizeof(USHORT));

    if (pidlNew == NULL)

        return NULL;

    // Copy the specified item identifier.

    CopyMemory(pidlNew, pidl, cb);

    // Append a terminating zero.

    *((USHORT *) (((LPBYTE) pidlNew) + cb)) = 0;

    return pidlNew;

}

The IShellFolder::GetDisplayNameOf member function returns a display name in a STRRET structure. The display name may be returned in one of three ways, which is specified by the uType member of the STRRET structure. The main function calls the following PrintStrRet function to print the display name.

// PrintStrRet - prints the contents of a STRRET structure.

// pidl - PIDL containing the display name if STRRET_OFFSET

// lpStr - address of the STRRET structure

void PrintStrRet(LPITEMIDLIST pidl, LPSTRRET lpStr)

{

    LPSTR lpsz;

    int cch;

    switch (lpStr->uType) {

        case STRRET_WSTR:

            cch = WideCharToMultiByte(CP_OEMCP, WC_DEFAULTCHAR,

                lpStr->pOleStr, -1, NULL, 0, NULL, NULL);

            lpsz = (LPSTR) g_pMalloc->lpVtbl->Alloc(g_pMalloc, cch);

            if (lpsz != NULL) {

                WideCharToMultiByte(CP_OEMCP, WC_DEFAULTCHAR,

                    lpStr->pOleStr, -1, lpsz, cch, NULL, NULL);

                printf("%s\n", lpsz);

                g_pMalloc->lpVtbl->Free(g_pMalloc, lpsz);

            }

            break;

        case STRRET_OFFSET:

            printf("%s\n", ((char *) pidl) + lpStr->uOffset);

            break;

        case STRRET_CSTR:

            printf("%s\n", lpStr->cStr);

            break;

    }

}


 Browsing for Folders

The following example uses the SHBrowseForFolder function to prompt the user for a program group. The Programs directory is specified as the root.

// Main_OnBrowse - browses for a program folder.

// hwnd - handle of the application's main window

//

// Uses the global variable g_pMalloc, which is assumed to point

//     to the shell's IMalloc interface.

void Main_OnBrowse(HWND hwnd)

{

    BROWSEINFO bi;

    LPSTR lpBuffer;

    LPITEMIDLIST pidlPrograms;  // PIDL for Programs folder

    LPITEMIDLIST pidlBrowse;    // PIDL selected by user

    // Allocate a buffer to receive browse information.

    if ((lpBuffer = (LPSTR) g_pMalloc->lpVtbl->Alloc(

            g_pMalloc, MAX_PATH)) == NULL)

        return;

    // Get the PIDL for the Programs folder.

    if (!SUCCEEDED(SHGetSpecialFolderLocation(

            hwnd, CSIDL_PROGRAMS, &pidlPrograms))) {

        g_pMalloc->lpVtbl->Free(g_pMalloc, lpBuffer);

        return;

    }

    // Fill in the BROWSEINFO structure.

    bi.hwndOwner = hwnd;

    bi.pidlRoot = pidlPrograms;

    bi.pszDisplayName = lpBuffer;

    bi.lpszTitle = "Choose a Program Group";

    bi.ulFlags = 0;

    bi.lpfn = NULL;

    bi.lParam = 0;

    // Browse for a folder and return its PIDL.

    pidlBrowse = SHBrowseForFolder(&bi);

    if (pidlBrowse != NULL) {

        // Show the display name, title, and file system path.

        MessageBox(hwnd, lpBuffer, "Display name", MB_OK);

        if (SHGetPathFromIDList(pidlBrowse, lpBuffer))

            SetWindowText(hwnd, lpBuffer);

        // Free the PIDL returned by SHBrowseForFolder.

        g_pMalloc->lpVtbl->Free(g_pMalloc, pidlBrowse);

    }

    // Clean up.

    g_pMalloc->lpVtbl->Free(g_pMalloc, pidlPrograms);

    g_pMalloc->lpVtbl->Free(g_pMalloc, lpBuffer);

}


 Reference

The following interfaces, member functions, structures, macros, and types are associated with the shell's namespace.


 Interfaces and Member Functions


IShellFolder [New - Windows 95]
 IShellFolder

[New - Windows 95]

Designates an interface implemented by the shell and used to determine the contents of a folder. The IShellFolder interface has the following member functions.

BindToObject	Retrieves the specified interface for the specified subfolder.
BindToStorage	Reserved; this function is not currently implemented.
CompareIDs	Compares two item identifier lists and returns the result.
CreateViewObject	Reserved for use by the shell; do not use.
EnumObjects	Enumerates the objects in the folder.
GetAttributesOf	Retrieves the attributes of the specified file object or subfolder.
GetDisplayNameOf	Retreives the display name of a file object or subfolder.
GetUIObjectOf	Creates an OLE interface that can be used to carry out operations on a file object or subfolder.
ParseDisplayName	Translates a display name into an item identifier list.
SetNameOf	Sets the display name of the specified file object or subfolder and changes its identifier accordingly.
Like all OLE interfaces, IShellFolder also includes the QueryInterface, AddRef, and Release member functions.


IShellFolder::ParseDisplayName [New - Windows 95]
 IShellFolder::ParseDisplayName

[New - Windows 95]

HRESULT IShellFolder::ParseDisplayName(

    LPSHELLFOLDER pIface, HWND hwndOwner, LPBC pbcReserved,

    LPWSTR lpwszDisplayName, ULONG *pchEaten,

    LPITEMIDLIST *ppidl, ULONG *pdwAttributes

    );

Translates a file object or folder's display name into an item identifier.

•	Returns the NOERROR value if successful or an OLE-defined error value otherwise.

pIface

Address of the IShellFolder interface. In C++, this parameter is implicit.

hwndOwner

Handle of the owner window that the client should specify if it displays a dialog box or message box.

pbcReserved

Reserved; this parameter is always NULL.

lpwszDisplayName

Address of a null-terminated Unicode string specifying the display name. This parameter must be a display name for parsing — that is, a display name retrieved using the SHGDN_FORPARSING value.

pchEaten

Address of an unsigned long value that receives the number of characters of the display name that were parsed.

ppidl

Address that receives a pointer to the new item identifier list for the object. If an error occurs, a NULL pointer is returned in this address.

The returned item identifier list specifies the relative path (from the parent folder) that corresponds to the specified display name. It contains only one SHITEMID structure followed by a terminating zero.

pdwAttributes

Address that receives the attributes of the file object.

This member function is similar to the IParseDisplayName::IParseDisplayName member function defined by OLE.


IShellFolder::EnumObjects [New - Windows 95]
 IShellFolder::EnumObjects

[New - Windows 95]

HRESULT IShellFolder::EnumObjects(

    LPSHELLFOLDER pIface, HWND hwndOwner, DWORD grfFlags,

    LPENUMIDLIST *ppenumIDList

    );

Creates an item enumeration object (an IEnumIDList interface) that can be used to enumerate the contents of a folder.

•	Returns the NOERROR value if successful or an OLE-defined error value otherwise.

pIface

Address of the IShellFolder interface. In C++, this parameter is implicit.

hwndOwner

Handle of the owner window that the client should specify if it displays a dialog box or message box.

grfFlags

Flags determining which items to include in the enumeration. For a list of possible values, see the description of the SHCONTF type.

ppenumIDList

Address that receives a pointer to the IEnumIDList interface created by this member function. If an error occurs, a NULL pointer is returned in this address.

The calling application must free the returned IEnumIDList object by calling its Release member function.

This member function is similar to the IOleContainer::EnumObjects member function defined by OLE.


IShellFolder::BindToObject [New - Windows 95]
 IShellFolder::BindToObject

[New - Windows 95]

HRESULT IShellFolder::BindToObject(

    LPSHELLFOLDER pIface, LPCITEMIDLIST pidl, LPBC pbcReserved,

    REFIID riid, LPVOID *ppvOut

    );

Creates an IShellFolder object for a subfolder.

•	Returns the NOERROR value if successful or an OLE-defined error value otherwise.

pIface

Address of the IShellFolder interface. In C++, this parameter is implicit.

pidl

Address of an ITEMIDLIST structure that identifies the subfolder relative to its parent folder.

pbcReserved

Reserved; applications should specify NULL for this parameter.

riid

Identifier of the interface to return. This parameter is almost always the IID_IShellFolder interface identifier.

ppvOut

Address that receives the interface pointer. If an error occurs, a NULL pointer is returned in this address.


IShellFolder::BindToStorage [New - Windows 95]
 IShellFolder::BindToStorage

[New - Windows 95]

This member function is reserved for future use and is not currently implemented.


IShellFolder::CompareIDs [New - Windows 95]
 IShellFolder::CompareIDs

[New - Windows 95]

HRESULT IShellFolder::CompareIDs(

    LPSHELLFOLDER pIface, LPARAM lParam,

    LPCITEMIDLIST pidl1, LPCITEMIDLIST pidl2

    );

Determines the relative ordering of two file objects or folders, given their item identifier lists.

•	Returns a handle to a result code. If this member function is successful, the CODE field of the status code (SCODE) has the following meaning:

CODE field	Meaning
Less than zero	The first item should precede the second (pidl1 < pidl2).
Greater than zero	The first item should follow the second (pidl1 > pidl2).
Zero	The two items are the same (pidl1 = pidl2).
pIface

Address of the IShellFolder interface. In C++, this parameter is implicit.

lParam

Value specifying the type of comparison to perform. The calling application should always specify zero, indicating that the two items should be sorted by name.

pidl1 and pidl2

Addresses of two ITEMIDLIST structures that uniquely identify the items to be compared. Both item identifier lists are relative to the parent folder.


IShellFolder::CreateViewObject [New - Windows 95]
 IShellFolder::CreateViewObject

[New - Windows 95]

This member function is reserved for use by the shell and should not be called by applications.


IShellFolder::GetAttributesOf [New - Windows 95]
 IShellFolder::GetAttributesOf

[New - Windows 95]

HRESULT IShellFolder::GetAttributesOf(

    LPSHELLFOLDER pIface, UINT cidl, LPCITEMIDLIST *apidl,

    ULONG *rgfInOut

    );

Retrieves the attributes of one or more file objects or subfolders.

•	Returns the NOERROR value if successful or an OLE-defined error value otherwise.

pIface

Address of the IShellFolder interface. In C++, this parameter is implicit.

cidl

Number of file objects to get the attributes of.

apidl

Address of an array of pointers to ITEMIDLIST structures, each of which uniquely identifies a file object relative to the parent folder. Each ITEMIDLIST structure must contain exactly one SHITEMID structure followed by a terminating zero.

rgfInOut

Address of an array of values that specify file object attributes. The calling application should initialize each array element by specifying which file object attributes to retrieve.

This member function returns the actual attributes of each file object in the corresponding array element; it may return all attributes or just the requested attributes.

The following attribute flags may be returned by this member function. File object attributes include capability flags, display attributes, contents flags, and miscellaneous attributes.

A file object's capability flags may include zero or more of these values:

SFGAO_CANCOPY	The specified file objects or folders can be copied (same value as the DROPEFFECT_COPY value).
SFGAO_CANDELETE	The specified file objects or folders can be deleted.
SFGAO_CANLINK	It is possible to create shortcuts for the specified file objects or folders (same value as the DROPEFFECT_LINK value).
SFGAO_CANMOVE	The specified file objects or folders can be moved (same value as the DROPEFFECT_MOVE value).
SFGAO_CANRENAME	The specified file objects or folders can be renamed.
SFGAO_CAPABILITYMASK	Mask for the capability flags.
SFGAO_DROPTARGET	The specified file objects or folders are drop targets.
SFGAO_HASPROPSHEET	The specified file objects or folders have property sheets.
A file object's display attributes may include zero or more of these values:

SFGAO_DISPLAYATTRMASK	Mask for the display attributes.
SFGAO_GHOSTED	The specified file objects or folders should be displayed using a ghosted icon.
SFGAO_LINK	The specified file objects are shortcuts.
SFGAO_READONLY	The specified file objects or folders are read-only.
SFGAO_SHARE	The specified folders are shared.
A file object's contents flags may include zero or more of these values:

SFGAO_CONTENTSMASK	Mask for the contents attributes.
SFGAO_HASSUBFOLDER	The specified folders have subfolders (and are, therefore, expandable in the left pane of Windows Explorer).
A file object may have zero or more of the following miscellaneous attributes:

SFGAO_FILESYSANCESTOR	The specified folders contain one or more file system folders.
SFGAO_FILESYSTEM	The specified folders or file objects are part of the file system (that is, they are files, directories, or root directories).
SFGAO_FOLDER	The specified items are folders.
SFGAO_REMOVABLE	The specified file objects or folders are on removable media.
SFGAO_VALIDATE	Validate cached information.


IShellFolder::GetUIObjectOf [New - Windows 95]
 IShellFolder::GetUIObjectOf

[New - Windows 95]

HRESULT IShellFolder::GetUIObjectOf(

    LPSHELLFOLDER pIface, HWND hwndOwner, UINT cidl,

    LPCITEMIDLIST *apidl, REFIID riid, UINT *prgfReserved,

    LPVOID *ppvOut

    );

Returns an interface that can be used to carry out actions on the specified file objects or folders — typically, to create context menus or carry out drag and drop operations.

•	Returns the NOERROR value if successful or an OLE-defined error value otherwise.

pIface

Address of the IShellFolder interface. In C++, this parameter is implicit.

hwndOwner

Handle of the owner window that the client should specify if it displays a dialog box or message box.

cidl

Number of file objects or subfolders specified by apidl.

apidl

Address of an array of pointers to ITEMIDLIST structures, each of which uniquely identifies a file object or subfolder relative to the parent folder. Each item identifier list must contain exactly one SHITEMID structure followed by a terminating zero.

riid

Identifier of the interface to return. This parameter can be a pointer to the IID_IExtractIcon, IID_IContextMenu, IID_IDataObject, or IID_IDropTarget interface identifier.

prgfReserved

Reserved for future versions of Windows; must be NULL.

ppvOut

Address that receives the interface pointer. If an error occurs, a NULL pointer is returned in this address.


IShellFolder::GetDisplayNameOf [New - Windows 95]
 IShellFolder::GetDisplayNameOf

[New - Windows 95]

HRESULT IShellFolder::GetDisplayNameOf(

    LPSHELLFOLDER pIface, LPCITEMIDLIST pidl, DWORD uFlags,

    LPSTRRET lpName

    );

Retrieves the display name for the specified file object or subfolder.

•	Returns the NOERROR value if successful or an OLE-defined error value otherwise.

pIface

Address of the IShellFolder interface. In C++, this parameter is implicit.

pidl

Address of an ITEMIDLIST structure that uniquely identifies the file object or subfolder relative to the parent folder.

uFlags

Flag indicating the type of display name to return. For a list of possible values, see the description of the SHGNO enumerated type.

lpName

Address of a STRRET structure in which to return the display name. The string returned in this structure depends on the type of display name requested.


IShellFolder::SetNameOf [New - Windows 95]
 IShellFolder::SetNameOf

[New - Windows 95]

HRESULT IShellFolder::SetNameOf(

    LPSHELLFOLDER pIface, HWND hwndOwner, LPCITEMIDLIST pidl,

    LPCOLESTR lpszName, DWORD uFlags, LPITEMIDLIST *ppidlOut

    );

Changes the name of a file object or subfolder, changing its item identifier in the process.

•	Returns the NOERROR value if successful or an OLE-defined error value otherwise.

pIface

Address of the IShellFolder interface. In C++, this parameter is implicit.

hwndOwner

Handle of the owner window that the client should specify if it displays a dialog box or message box.

pidl

Address of an ITEMIDLIST structure that uniquely identifies the file object or subfolder relative to the parent folder.

lpszName

Address of a null-terminated string that specifies the new display name.

uFlags

Flag indicating the type of name specified by lpszName. For a list of possible values, see the description of the SHCONTF enumerated type.

ppidlOut

Address in which the member function returns a pointer to the new ITEMIDLIST structure. This parameter can be NULL, and the member function does not return the new structure for the object in that case.

If this parameter is not NULL, this member function frees the specified ITEMIDLIST structure and allocates a new one using the task allocator. The calling application is responsible for freeing the new ITEMIDLIST structure. If an error occurs, the member function returns NULL in this address.


IEnumIDList [New - Windows 95]
 IEnumIDList

[New - Windows 95]

Designates an interface used to enumerate item identifiers. The IShellFolder::EnumObjects member function creates an IEnumIDList interface. The IEnumIDList interface has the following member functions.

Clone	Creates a new item enumeration object having the same contents and state as the given one.
Next	Retrieves one or more item identifiers and advances the current position.
Reset	Returns to the beginning of the enumeration sequence.
Skip	Skips over one or more items in the enumeration sequence.
Like all OLE interfaces, IEnumIDList also includes the QueryInterface, AddRef, and Release methods.


IEnumIDList::Clone [New - Windows 95]
 IEnumIDList::Clone

[New - Windows 95]

HRESULT Clone(IEnumIDList FAR * pEnumIDList,
    IEnumIDList **ppenum);

Creates a new item enumeration object with the same contents and state as the current one.

•	Returns the NOERROR value if successful or an OLE-defined error value otherwise.

pEnumIDList

Address of the IEnumIDList interface. In C++, this parameter is implicit.

ppenum

Address that receives a pointer to the new enumeration object. The calling application must eventually free the new object by calling its Release member function.

This member function makes it possible to record a particular point in the enumeration sequence and then return to that point at a later time.


IEnumIDList::Next [New - Windows 95]
 IEnumIDList::Next

[New - Windows 95]

HRESULT Next(IEnumIDList FAR * pEnumIDList,
    ULONG celt, LPITEMIDLIST *rgelt, ULONG *pceltFetched);

Retrieves the specified number of item identifiers in the enumeration sequence and advances the current position.

•	Returns the NOERROR value if successful, the S_FALSE value if there are no more items in the enumeration sequence, or an OLE-defined error value if an error occurs.

pEnumIDList

Address of the IEnumIDList interface. In C++, this parameter is implicit.

celt

Specifies the number of elements in the array pointed to by the rgelt parameter.

rgelt

Address of an array in which to return the item identifiers. The calling application must free the item identifiers by using the task allocator (retrieved by the SHGetMalloc function).

pceltFetched

Address of a value that receives a count of the item identifiers actually returned in rgelt. The count can be smaller than the value specified in the celt parameter. This parameter can be NULL if, and only if, celt is one.

If this member function returns any value other than NOERROR, no entries in the rgelt array are valid on exit. They are all in an indeterminate state.


IEnumIDList::Reset [New - Windows 95]
 IEnumIDList::Reset

[New - Windows 95]

HRESULT Reset(IEnumIDList FAR * pEnumIDList,);

Returns to the beginning of the enumeration sequence.

•	Returns the NOERROR value if successful or an OLE-defined error value otherwise.

pEnumIDList

Address of the IEnumIDList interface. In C++, this parameter is implicit.


IEnumIDList::Skip [New - Windows 95]
 IEnumIDList::Skip

[New - Windows 95]

HRESULT Skip(IEnumIDList FAR * pEnumIDList,
    ULONG celt);

Skips over the specified number of elements in the enumeration sequence.

•	Returns the NOERROR value if successful or an OLE-defined error value otherwise.

pEnumIDList

Address of the IEnumIDList interface. In C++, this parameter is implicit.

celt

Number of item identifiers to skip.


 Functions

The following functions are used with the shell's namespace.


BrowseCallbackProc [New - Windows 95]
 BrowseCallbackProc

[New - Windows 95]

int BrowseCallbackProc(HWND hwnd, UINT uMsg, LPARAM lParam,

    LPARAM lpData);

Specifies an application-defined callback function used with the SHBrowseForFolder function. A browse dialog box calls this function to notify it about events. The BFFCALLBACK type defines a pointer to this callback function.

•	Returns zero.

hwnd

Handle of the browse dialog box. The callback function can send the following messages to the window:

BFFM_ENABLEOK	Enables the OK button if wParam is nonzero or disables it if wParam is zero.
BFFM_SETSELECTION	Selects the specified folder. lParam is the PIDL of the folder to select if wParam is FALSE, or it is the path of the folder otherwise.
BFFM_SETSTATUSTEXT	Sets the status text to the null-terminated string specified by lParam.
uMsg

Value identifying the event. This parameter can be one of these values:

BFFM_INITIALIZED	The browse dialog box has finished initializing. lpData is NULL.
BFFM_SELCHANGED	The selection has changed. lpData is a pointer to the item identifier list for the newly selected folder.
lParam

Message-specific value. For more information, see the description of uMsg.

lpData

Application-defined value that was specified in the lParam member of the BROWSEINFO structure.


SHAddToRecentDocs [New - Windows 95]
 SHAddToRecentDocs

[New - Windows 95]

void SHAddToRecentDocs(UINT uFlags, LPCVOID pv);

Adds a document to the shell's list of recently used documents or clears all documents from the list. The user accesses the list through the Start menu of the Windows taskbar.

•	No return value.

uFlags

Flag that indicates the meaning of pv. This parameter can be one of these values:

SHARD_PATH	pv is the address of a path string.
SHARD_PIDL	pv is the address of an item identifier list.
pv

Address of a buffer that contains the path and filename of the document, or the address of an ITEMIDLIST structure that contains an item identifier list uniquely identifying the document. If this parameter is NULL, the function clears all documents from the list.


SHBrowseForFolder [New - Windows 95]
 SHBrowseForFolder

[New - Windows 95]

LPITEMIDLIST SHBrowseForFolder(LPBROWSEINFO lpbi);

Displays a browse dialog box that enables the user to select a shell folder.

•	Returns a pointer to an item identifier list that specifies the location of the selected folder relative to the root of the namespace. If the user chooses the Cancel button in the dialog box, the return value is NULL.

lpbi

Address of a BROWSEINFO structure that contains information used to display the dialog box.

The calling application is responsible for freeing the returned item identifier list using the shell's task allocator.


SHChangeNotify [New - Windows 95]
 SHChangeNotify

[New - Windows 95]

void SHChangeNotify(LONG wEventId, UINT uFlags,
    LPCVOID dwItem1, LPCVOID dwItem2);

Notifies the system of an event that an application has performed. An application should use this function if it performs an action that may affect the shell.

•	No return value.

wEventId

Array of flags that specifies the events. This parameter can be a combination of these values:

SHCNE_ASSOCCHANGED	Changed a file type association.
SHCNE_ATTRIBUTES	Changed a file's attributes.
SHCNE_CREATE	Created a file.
SHCNE_DELETE	Deleted a file.
SHCNE_DRIVEADD	Added a network drive.
SHCNE_DRIVEADDGUI	Added a network drive by way of a graphic user interface (GUI).
SHCNE_DRIVEREMOVED	Removed a network drive.
SHCNE_INTERRUPT	Performed the event as a result of a system interrupt.
SHCNE_MEDIAINSERTED	Added removable media, such as a compact-disc read-only memory (CD-ROM) drive.
SHCNE_MEDIAREMOVED	Removed a removable medium, such as a CD-ROM drive.
SHCNE_MKDIR	Created a new directory.
SHCNE_NETSHARE	Shared a resource on the network.
SHCNE_NETUNSHARE	Stopped sharing a resource.
SHCNE_RENAMEFOLDER	Renamed a folder.
SHCNE_RENAMEITEM	Renamed an item in a folder.
SHCNE_RMDIR	Removed a directory.
SHCNE_SERVERDISCONNECT	Disconnected a network server.
SHCNE_UPDATEDIR	Updated the contents of a directory.
SHCNE_UPDATEIMAGE	Changed an image in the system global image list.
SHCNE_UPDATEITEM	Changed the properties of a printer or file.
uFlags

Flag that indicates the meaning of dwItem1 and dwItem2. This parameter can be one of these values:

SHCNF_DWORD	The dwItem1 and dwItem2 parameters are doubleword values.
SHCNF_FLUSH	Flushes the system event buffer. The function does not return until the system is finished processing the given event.
SHCNF_FLUSHNOWAIT	Flushes the system event buffer. The function returns immediately regardless of whether the system is finished processing the given event.
SHCNF_IDLIST	dwItem1 and dwItem2 are the addresses of item identifier lists.
SHCNF_PATH	dwItem1 and dwItem2 are paths.
SHCNF_PRINTER	dwItem1 and dwItem2 are printer "friendly" names.
dwItem1

First event-dependent value.

dwItem2

Second event-dependent value.


SHFileOperation [New - Windows 95]
 SHFileOperation

[New - Windows 95]

int SHFileOperation(LPSHFILEOPSTRUCT lpFileOp);

Performs a copy, move, rename, or delete operation on a file system object.

•	Returns zero if successful or nonzero if an error occurs.

lpFileOp

Address of an SHFILEOPSTRUCT structure containing information that the function needs to carry out the operation.


SHFreeNameMappings [New - Windows 95]
 SHFreeNameMappings

[New - Windows 95]

void SHFreeNameMappings(HANDLE hNameMappings);

Frees a filename mapping object that was retrieved by the SHFileOperation function.

•	No return value.

hNameMappings

Handle of the filename mapping object to free.


SHGetDesktopFolder [New - Windows 95]
 SHGetDesktopFolder

[New - Windows 95]

HRESULT SHGetDesktopFolder(LPSHELLFOLDER *ppshf);

Retrieves the IShellFolder interface for the desktop folder, which is the root of the shell's namespace.

•	Returns the NOERROR value if successful or an OLE-defined error result otherwise.

ppshf

Address that receives an IShellFolder interface pointer for the desktop folder. The calling application is responsible for eventually freeing the interface by calling its Release member function.


SHGetFileInfo [New - Windows 95]
 SHGetFileInfo

[New - Windows 95]

DWORD SHGetFileInfo(LPCSTR pszPath,
    DWORD dwFileAttributes, SHFILEINFO FAR *psfi, UINT cbFileInfo,
    UINT uFlags);

Retrieves information about an object in the file system, such as a file, a folder, a directory, or a drive root.

•	Returns a value whose meaning depends on the uFlags parameter. If uFlags specifies the SHGFI_EXETYPE value, the return value indicates the type of the executable file. For more information, see the comments below.

If uFlags includes the SHGFI_ICON or SHGFI_SYSICONINDEX value, the return value is the handle of the system image list that contains the large icon images. If the SHGFI_SMALLICON value is also included, the return value is the handle of the image list that contains the small icon images.

If uFlags does not include SHGFI_EXETYPE, SHGFI_ICON, SHGFI_SYSICONINDEX, or SHGFI_SMALLICON, the return value is nonzero if successful or zero otherwise.

pszPath

Address of a buffer that contains the path and filename. Both absolute and relative paths are valid. If uFlags includes the SHGFI_PIDL value, pszPath must be the address of an ITEMIDLIST structure that contains the list of item identifiers uniquely identifying the file within the shell's namespace.

dwFileAttributes

Array of file attribute flags (FILE_ATTRIBUTE_ values). If uFlags does not include the SHGFI_USEFILEATTRIBUTES value, this parameter is ignored.

psfi and cbFileInfo

Address and size, in bytes, of the SHFILEINFO structure that receives the file information.

uFlags

Flag that specifies the file information to retrieve. This parameter can be a combination of these values:

SHGFI_ATTRIBUTES	Retrieves the file attribute flags. The flags are copied to the dwAttributes member of the structure specified by psfi.
SHGFI_DISPLAYNAME	Retrieves the display name for the file. The name is copied to the szDisplayName member of the structure specified by psfi.
SHGFI_EXETYPE	Returns the type of the executable file if pszPath identifies an executable file. For more information, see the comments below.
SHGFI_ICON	Retrieves the handle of the icon that represents the file and the index of the icon within the system image list. The handle is copied to the hIcon member of the structure specified by psfi, and the index is copied to the iIcon member. The return value is the handle of the system image list.
SHGFI_ICONLOCATION	Retrieves the name of the file that contains the icon representing the file. The name is copied to the szDisplayName member of the structure specified by psfi.
SHGFI_LARGEICON	Modifies SHGFI_ICON, causing the function to retrieve the file's large icon.
SHGFI_LINKOVERLAY	Modifies SHGFI_ICON, causing the function to add the link overlay to the file's icon.
SHGFI_OPENICON	Modifies SHGFI_ICON, causing the function to retrieve the file's open icon. A container object displays an open icon to indicate that the container is open.
SHGFI_PIDL	Indicates that pszPath is the address of an ITEMIDLIST structure rather than a path name.
SHGFI_SELECTED	Modifies SHGFI_ICON, causing the function to blend the file's icon with the system highlight color.
SHGFI_SHELLICONSIZE	Modifies SHGFI_ICON, causing the function to retrieve a shell-sized icon. If this value is not specified, the function sizes the icon according to the system metric values.
SHGFI_SMALLICON	Modifies SHGFI_ICON, causing the function to retrieve the file's small icon.
SHGFI_SYSICONINDEX	Retrieves the index of the icon within the system image list. The index is copied to the iIcon member of the structure specified by psfi. The return value is the handle of the system image list.
SHGFI_TYPENAME	Retrieves the string that describes the file's type. The string is copied to the szTypeName member of the structure specified by psfi.
SHGFI_USEFILEATTRIBUTES	Indicates that the function should use dwFileAttributes. This flag must be set when retrieving an icon for a file that does not exist.
To retrieve the executable file type, uFlags must specify only SHGFI_EXETYPE. The return value specifies the type of the executable file:

0	Nonexecutable file or an error condition
LOWORD = NE or PE HIWORD = 3.0, 3.5, or 4.0	Windows-based application
LOWORD = MZ HIWORD = 0	Microsoft® MS-DOS® .EXE, .COM, or .BAT file
LOWORD = PE HIWORD = 0	Win32-based console application


SHGetInstanceExplorer [New - Windows 95]
 SHGetInstanceExplorer

[New - Windows 95]

HRESULT SHGetInstanceExplorer(IUnknown **ppunk);

Retrieves the address of Explorer's IUnknown interface.

•	Returns the NOERROR value if successful or the E_FAIL value otherwise.

ppunk

Address of a value that receives the address of Explorer's IUnknown interface.


SHGetMalloc [New - Windows 95]
 SHGetMalloc

[New - Windows 95]

HRESULT SHGetMalloc(LPMALLOC * ppMalloc);

Retrieves a pointer to the shell's IMalloc interface. A shell extension must use this interface to allocate memory that is later freed by the shell.

•	Returns the NOERROR value if successful or E_FAIL otherwise.

ppMalloc

Address of a value that receives the address of the shell's IMalloc interface.


SHGetPathFromIDList [New - Windows 95]
 SHGetPathFromIDList

[New - Windows 95]

BOOL SHGetPathFromIDList(LPCITEMIDLIST pidl,

    LPSTR pszPath);

Converts an item identifier list to a file system path.

•	Returns TRUE if successful or FALSE if an error occurs — for example, if the location specified by pidl is not part of the file system.

pidl

Address of an item identifier list that specifies a file or directory location relative to the root of the namespace (the desktop).

pszPath

Address of a buffer that receives the file system path. The size of this buffer is assumed to be MAX_PATH bytes.


SHGetSpecialFolderLocation [New - Windows 95]
 SHGetSpecialFolderLocation

[New - Windows 95]

HRESULT SHGetSpecialFolderLocation(HWND hwndOwner,

    int nFolder, LPITEMIDLIST * ppidl);

Retrieves the location of a special folder.

•	Returns the NOERROR value if successful or an OLE-defined error result otherwise.

hwndOwner

Handle of the owner window that the client should specify if it displays a dialog box or message box.

nFolder

Value specifying the folder to retrieve the location for. This parameter can be one of these values:

CSIDL_BITBUCKET	Recycle bin — file system directory containing file objects in the user's recycle bin. The location of this directory is not in the registry; it is marked with the hidden and system attributes to prevent the user from moving or deleting it.
CSIDL_CONTROLS	Control Panel — virtual folder containing icons for Control Panel applications.
CSIDL_DESKTOP	Windows desktop — virtual folder at the root of the namespace.
CSIDL_DESKTOPDIRECTORY	File system directory used to physically store file objects on the desktop (not to be confused with the desktop folder itself).
CSIDL_DRIVES	My Computer — virtual folder containing everything on the local computer: storage devices, printers, and Control Panel. The folder may also contain mapped network drives.
CSIDL_FONTS	Virtual folder containing fonts.
CSIDL_NETHOOD	File system directory containing objects that appear in Network Neighborhood.
CSIDL_NETWORK	Network Neighborhood — virtual folder representing the top level of the network hierarchy.
CSIDL_PERSONAL	File system directory that serves as a common repository for documents.
CSIDL_PRINTERS	Printers folder — virtual folder containing installed printers.
CSIDL_PROGRAMS	File system directory that contains the user's program groups (which are also file system directories).
CSIDL_RECENT	File system directory that contains the user's most recently used documents.
CSIDL_SENDTO	File system directory that contains Send To menu items.
CSIDL_STARTMENU	File system directory containing Start menu items.
CSIDL_STARTUP	File system directory that corresponds to the user's Startup program group.
CSIDL_TEMPLATES	File system directory that serves as a common repository for document templates.
ppidl

Address that receives a pointer to an item identifier list specifying the folder's location relative to the root of the namespace (the desktop).


SHLoadInProc [New - Windows 95]
 SHLoadInProc

[New - Windows 95]

HRESULT SHLoadInProc(REFCLSID rclsid);

Creates an instance of the specified object class from within the context of the shell's process.

•	Returns the NOERROR value if successful or an OLE-defined error result otherwise.

rclsid

Class identifier (CLSID) of the object class to be created.


 Structures, Macros, and Types

The following structures, macros, and types are used with the shell's namespace.


BROWSEINFO [New - Windows 95]
 BROWSEINFO

[New - Windows 95]

typedef struct _browseinfo {

    HWND hwndOwner;          // see below

    LPCITEMIDLIST pidlRoot;  // see below

    LPSTR pszDisplayName;    // see below

    LPCSTR lpszTitle;        // see below

    UINT ulFlags;            // see below

    BFFCALLBACK lpfn;        // see below

    LPARAM lParam;           // see below

    int iImage;              // see below

} BROWSEINFO, *PBROWSEINFO, *LPBROWSEINFO;

Contains parameters for the the SHBrowseForFolder function and receives information about the folder selected by the user.

hwndOwner

Handle of the owner window for the dialog box.

pidlRoot

Address of an item identifier list (an ITEMIDLIST structure) specifying the location of the "root" folder to browse from. Only the specified folder and its subfolders appear in the dialog box. This member can be NULL, and the namespace root (the desktop folder) is used in that case.

pszDisplayName

Address of a buffer that receives the display name of the folder selected by the user. The size of this buffer is assumed to be MAX_PATH bytes.

lpszTitle

Address of a null-terminated string that is displayed above the tree view control in the dialog box. This string can be used to specify instructions to the user.

ulFlags

Value specifying the types of folders to be listed in the dialog box as well as other options. This member can include zero or more of these values:

BIF_BROWSEFORCOMPUTER	Only returns computers. If the user selects anything other than a computer, the OK button is grayed.
BIF_BROWSEFORPRINTER	Only returns printers. If the user selects anything other than a printer, the OK button is grayed.
BIF_DONTGOBELOWDOMAIN	Does not include network folders below the domain level in the tree view control.
BIF_RETURNFSANCESTORS	Only returns file system ancestors. If the user selects anything other than a file system ancestor, the OK button is grayed.
BIF_RETURNONLYFSDIRS	Only returns file system directories. If the user selects folders that are not part of the file system, the OK button is grayed.
BIF_STATUSTEXT	Includes a status area in the dialog box. The callback function can set the status text by sending messages to the dialog box.
lpfn

Address an application-defined function that the dialog box calls when events occur. For more information, see the description of the BrowseCallbackProc function. This member can be NULL.

lParam

Application-defined value that the dialog box passes to the callback function, if one is specified.

iImage

Variable that receives the image associated with the selected folder. The image is specified as an index to the system image list.


CIDA [New - Windows 95]
 CIDA

[New - Windows 95]

typedef struct _IDA {

    UINT cidl;        // number of array elements

    UINT aoffset[1];  // see below

} CIDA, * LPIDA;

Corresponds to the CF_IDLIST clipboard format.

aoffset

Array of offsets relative to the beginning of the CIDA structure. The first element is the offset of the ITEMIDLIST structure for a folder (absolute from the root). Subsequent elements are offsets of ITEMIDLIST structures for file objects (relative from the parent folder).


SHCONTF [New - Windows 95]
 SHCONTF

[New - Windows 95]

typedef enum tagSHCONTF {

    SHCONTF_FOLDERS = 32,         // for shell browser

    SHCONTF_NONFOLDERS = 64,      // for default view

    SHCONTF_INCLUDEHIDDEN = 128,  // for hidden or system objects

} SHCONTF;

Specifies an enumerated type that defines flags used with the IShellFolder::EnumObjects member function.


SHFILEINFO [New - Windows 95]
 SHFILEINFO

[New - Windows 95]

typedef struct _SHFILEINFO { // shfi

    HICON hIcon;                   // see below

    int   iIcon;                   // see below

    DWORD dwAttributes;            // see below

    char  szDisplayName[MAX_PATH]; // see below

    char  szTypeName[80];          // see below

} SHFILEINFO;

Contains information about a file object.

hIcon

Handle of the icon that represents the file.

iIcon

Index of the icon image within the system image list.

dwAttributes

Array of flags that indicates the attributes of the file object. For information about the flags, see the description of the IShellFolder::GetAttributesOf member function.

szDisplayName

String that contains the name of the file as it appears in the Windows shell, or the path and filename of the file that contains the icon representing the file.

szTypeName

String that describes the type of the file.

This structure is used with the SHGetFileInfo function.


SHFILEOPSTRUCT [New - Windows 95]
 SHFILEOPSTRUCT

[New - Windows 95]

typedef struct _SHFILEOPSTRUCT { // shfos

    HWND         hwnd;                  // see below

    UINT         wFunc;                 // see below

    LPCSTR       pFrom;                 // see below

    LPCSTR       pTo;                   // see below

    FILEOP_FLAGS fFlags;                // see below

    BOOL         fAnyOperationsAborted; // see below

    LPVOID       hNameMappings;         // see below

    LPCSTR       lpszProgressTitle;     // see below

} SHFILEOPSTRUCT, FAR *LPSHFILEOPSTRUCT;

Contains information that the SHFileOperation function uses to perform file operations.

hwnd

Handle of the dialog box used to display information about the status of the operation. If fFlags includes the FOF_CREATEPROGRESSDLG value, this parameter is the handle of the parent window for the progress dialog box created by the system.

wFunc

Operation to perform. This member can be one of these values:

FO_COPY	Copies the files specified by pFrom to the location specified by pTo.
FO_DELETE	Deletes the files specified by pFrom (pTo is ignored).
FO_MOVE	Moves the files specified by pFrom to the location specified by pTo.
FO_RENAME	Renames the files specified by pFrom.
pFrom

Address of a string that contains the names of the source files.

pTo

Address of a string that specifies the destination for the moved, copied, or renamed file.

fFlags

Flags that control the file operation. This member can be a combination of these values:

FOF_ALLOWUNDO	Preserves undo information, if possible.
FOF_CONFIRMMOUSE	Not implemented.
FOF_FILESONLY	Performs the operation only on files if a wildcard filename (*.*) is specified.
FOF_MULTIDESTFILES	Indicates that the pTo member specifies multiple destination files (one for each source file) rather than one directory where all source files are to be deposited.
FOF_NOCONFIRMATION	Responds with "yes to all" for any dialog box that is displayed.
FOF_NOCONFIRMMKDIR	Does not confirm the creation of a new directory if the operation requires one to be created.
FOF_RENAMEONCOLLISION	Gives the file being operated on a new name (such as "Copy #1 of...") in a move, copy, or rename operation if a file of the target name already exists.
FOF_SILENT	Does not display a progress dialog box.
FOF_SIMPLEPROGRESS	Displays a progress dialog box, but does not show the filenames.
FOF_WANTMAPPINGHANDLE	Fills in the hNameMappings member. The handle must be freed by using the SHFreeNameMappings function.
fAnyOperationsAborted

Value that receives TRUE if the user aborted any file operations before they were completed or FALSE otherwise.

hNameMappings

Handle of a filename mapping object that contains an array of SHNAMEMAPPING structures. Each structure contains the old and new paths for each file that was moved, copied, or renamed. This member is used only if fFlags includes FOF_WANTMAPPINGHANDLE.

lpszProgressTitle

Address of a string to use as the title for a progress dialog box. This member is used only if fFlags includes FOF_SIMPLEPROGRESS.

If pFrom or pTo are unqualified names, the current directories are taken from the global current drive and directory settings as managed by the GetCurrentDirectory and SetCurrentDirectory functions.

The SHGetNameMappingPtr macro retrieves a pointer to the filename mapping object returned in the hNameMappings member. The SHGetNameMappingCount macro retrieves the number of SHNAMEMAPPING structures in the object.


SHNAMEMAPPING [New - Windows 95]
 SHNAMEMAPPING

[New - Windows 95]

typedef struct _SHNAMEMAPPING { // shnm

    LPSTR pszOldPath; // address of old path

    LPSTR pszNewPath; // address of new path

    int   cchOldPath; // number of characters in old path

    int   cchNewPath; // number of characters in new path

} SHNAMEMAPPING, FAR *LPSHNAMEMAPPING;

Contains the old and new paths for each file that was moved, copied, or renamed by the SHFileOperation function.


STRRET [New - Windows 95]
 STRRET

[New - Windows 95]

typedef struct _STRRET { // str

    UINT uType; // see below

    union

    {

        LPWSTR pOleStr;        // address of OLE string to free

        UINT   uOffset;        // offset into item identifier list

        char   cStr[MAX_PATH]; // buffer to receive display name

    } DUMMYUNIONNAME;

} STRRET, *LPSTRRET;

Contains strings returned from IShellFolder member functions, such as GetDisplayNameOf.

uType

Value that specifies the desired format of the string. This member can be one of these values:

STRRET_CSTR	The string is returned in cStr.
STRRET_OFFSET	The string is located at uOffset bytes from the beginning of the item identifier list.
STRRET_WSTR	The string is at the address pointed to by pOleStr.
The system may or may not provide the display name in the desired format. When IShellFolder::GetDisplayNameOf returns, uType indicates the format.


SHGetNameMappingCount [New - Windows 95]
 SHGetNameMappingCount

[New - Windows 95]

int SHGetNameMappingCount(HANDLE hNameMappings)

Retrieves the number of SHNAMEMAPPING structures in a filename mapping object.

•	Returns the number of SHNAMEMAPPING structures.

hNameMappings

Handle of a filename mapping object retrieved by the SHFileOperation function.

The SHGetNameMappingCount macro is defined as follows.

#define SHGetNameMappingCount(_hnm) \
    DSA_GetItemCount(_hnm)


SHGetNameMappingPtr [New - Windows 95]
 SHGetNameMappingPtr

[New - Windows 95]

lpshnm = SHGetNameMappingPtr(HANDLE hNameMappings, int iItem)

Retrieves the address of a SHNAMEMAPPING structure contained in a file mapping object.

•	Returns the address of the SHNAMEMAPPING structure specified by iItem.

hNameMappings

Handle of a filename mapping object retrieved by the SHFileOperation function.

iItem

Index of the SHNAMEMAPPING structure to be retrieved.

The SHGetNameMappingPtr macro is defined as follows.

#define SHGetNameMappingPtr(_hnm, _iItem) \
    (LPSHNAMEMAPPING)DSA_GetItemPtr(_hnm, _iItem)


SHGNO [New - Windows 95]
 SHGNO

[New - Windows 95]

typedef enum tagSHGDN {

    SHGDN_NORMAL = 0,           // see below

    SHGDN_INFOLDER = 1,         // see below

    SHGDN_FORPARSING = 0x8000,  // see below

} SHGNO;

Specifies an enumerated type that defines flags used with the IShellFolder::GetDisplayNameOf and IShellFolder::SetNameOf member functions.

SHGDN_NORMAL

Default display name that is suitable for a file object displayed by itself, as shown in the following examples.

File system path	Corresponding display name
C:\WINDOWS\FILE.TXT	File
\\COMPUTER\SHARE	Share on computer
C:\ (where drive C has the volume name My Drive)	My Drive (C)
SHGDN_INFOLDER

Display name that is suitable for a file object displayed within its respective folder, as shown in the following examples.

File system path	Corresponding display name
C:\WINDOWS\FILE.TXT	File
\\COMP\SHARE	User
C:\ (where drive C has the volume name My Drive)	My Drive (C)
SHGDN_FORPARSING

Display name that can be passed to the ParseDisplayName member function of the parent folder's IShellFolder object.

File system path	Corresponding display name
C:\WINDOWS\FILE.TXT	C:\WINDOWS\FILE.TXT
\\COMP\SHARE	\\COMP\SHARE
C:\ (where drive C has the volume name My Drive)	C:\


 Shell Extensions

In Microsoft® Windows® 95, applications can extend the shell in a number of ways. A shell extension enhances the shell by providing additional means of manipulating file objects, by simplifying the task of browsing through the file system and networks, or by giving the user easier access to tools that manipulate objects in the file system. For example, a shell extension can assign an icon to each file or add commands to the context menu and File menu for a file.


 About Shell Extensions

Windows 95 supports two groups of shell extensions. The first group are registered for each type of file:

•	Context menu handlers. They add items to the context menu for a particular file object. (The context menu is displayed when the user clicks a file object with mouse button 2.)

•	Icon handlers. They typically add instance-specific icons for file objects. They can also be used to add icons for all files belonging to the same class.

•	Data handlers. They provide a type-specific IDataObject interface to be passed to the OLE DoDragDrop function.

•	Drop handlers. They provide type-specific drop behavior to files that can accept drag and drop objects.

•	Property sheet handlers. They add pages to the property sheet dialog box that the shell displays for a file object. The pages are specific to a class of files or a particular file object.

The second group of shell extensions are associated with file operations such as move, copy, rename, and so on:

•	Copy hook handlers. They are called when a folder object is about to be copied, moved, deleted, or renamed. They can either allow or prevent the operation.

•	Drag and drop handlers. They are context menu handlers that the system calls when the user drops an object after dragging it to a new position.

The design of a shell extension is based on the OLE Component Object Model (COM). The shell accesses an object through interfaces. An application implements the interfaces in a shell extension dynamic-link library (DLL), which is essentially an OLE in-process server DLL.

This article explains how to create shell extensions and describes how the shell interacts with them.


 Shell Extension Terms

You should be familiar with the following shell extension terms before proceeding.

file object

A file object is an item within the shell. The most familiar file objects are files and directories. However, a file object may not actually be a part of the file system; it may only appear that way. For example, printers, Control Panel applications, and network shares, servers, and workgroups are also considered to be file objects.

file class

Each file object is a member of a file class. The file class refers to the code that "owns" the manipulation of files belonging to the class. For example, text files and Microsoft Word documents are examples of file classes. Each file class has specific shell extensions associated with it. When the shell is about to take an action involving a file object, it uses the file class to determine the shell extensions to load.

handler

A handler is the code that implements a particular shell extension.


 Registry Entries for Extending the Shell

An application that creates and maintains files, such as a spreadsheet, word proces-sor, or graphics application, typically adds two keys to the system registry: a file association key and an application identifier key. The file association key maps a filename extension to an application identifier. For example, a word processing application might register the following key under HKEY_CLASSES_ROOT.

HKEY_CLASSES_ROOT

    .doc=AWordProcessor

The value name (.doc) specifies the filename extension, and the value (AWordProcessor) denotes the key name that contains the information about the application handling the filename extension.

The application identifier key is the second registry entry made by an application handling files.

HKEY_CLASSES_ROOT

    AWordProcessor=A Word Processor

The value (A Word Processor) is a string describing the application that recognizes files having the given filename extension. (In this case, it is the .DOC filename extension.)

Extending the shell requires that you add other entries below the file association and application identifier keys. The system checks these entries to determine the commands to add to various shell menus, when to load an extension DLL, where to find the DLL, and so on.

There are several registry keys that allow you to extend the shell without having to write any code at all. These keys let you set the default icon for a class of files or add commands to the File menu and its New submenu in Windows Explorer.


 Setting Default Icons for File Classes

The system uses icons to represent file objects in the shell. Typically, all files of the same class have the same icon. By adding the DefaultIcon key to the file association key for a particular file class, you can specify the icon that the system displays for all files of the class. The value of the DefaultIcon key specifies the executable file (or DLL) that contains the icon and the index of the icon within the file.

HKEY_CLASSES_ROOT

    .doc=AWordProcessor

        DefaultIcon=C:\MYDIR\MYAPP.EXE,1

If the registry does not contain a DefaultIcon key for a particular file class, the system uses the default icon for the class. One of the advantages of using a class icon is that it requires no programming; the shell handles displaying the icon for the class.

By writing an icon handler, you give each instance of a file a different icon. For more information about icon handlers, see "Icon Handlers" later in this article.


 Modifying the Context Menu for a File Class

When the user clicks a file object using mouse button 2, the system displays a context menu for the object. The context menu contains a set of menu items that allow the user to perform various operations on the file object, such as opening or printing it. A context menu contains two types of items: dynamic items and static items. Dynamic items are added to a context menu by a context menu handler (described later in this article).

Static menu items are listed in the system registry and are automatically added to a context menu by the system. Because static items are listed in the system registry based on their class, the context menus for all file objects belonging to a particular class receive the same set of static items.

You specify static menu items for a file class by adding a shell key below the application identifier key of the file class and then adding verb and command value entries below the shell key. Following is the registry format for static items.

HKEY_CLASSES_ROOT

    <applicationID> = <"description">

        shell

            <verb> = <"menu-item text">

                command = <"command string">

Each verb value entry specifies a menu-item text string for the system to add to the context menu. The command value entry specifies the action that the system takes when the user chooses the menu item. Typically, the command string value specifies the path and filename of an application and includes command-line options that direct the application to perform an action on the corresponding file object. For example, the following registry keys add an Open command and a Print command to the context menu for all files with the .WRI filename extension.

HKEY_CLASSES_ROOT

  wrifile = Write Document

      shell

        open

          command = C:\Progra~1\Access~1\WORDPAD.EXE %1

            print

          command = C:\Progra~1\Access~1\WORDPAD.EXE /p "%1"

            printto

          command =

            C:\Progra~1\Access~1\WORDPAD.EXE /pt "%1" "%2" "%3" "%4"

In the preceding commands, the %1 parameter is the filename, %2 is the printer name, %3 is the driver name, and %4 is the port name. In Windows 95, you can ignore the %3 and %4 parameters (the printer name is unique in Windows 95).

The system defines a set of verbs called canonical verbs that introduce an element of language-independence to context menus. When you include a canonical verb in the registry, the system automatically generates a localized menu item string for the verb before adding it to the context menu. The canonical verbs include the open, print, explore, find, openas, and properties verbs. The printto verb is also canonical, but it is a special case because it is never actually displayed. Instead, it allows the user to print a file by dragging it to a printer object. Canonical verbs are also used with context menu handlers.

If the open canonical verb is included in the registry entries for a file class, the system adds an Open menu item to the corresponding context menu and makes it the default item. If the open verb is not included, the menu item corresponding to the verb listed in the registry is the default item. A context menu handler can change the default item. For more information about context menu handlers, see "Context Menu Handlers" later in this article.


 Modifying the New Submenu

The File menu in a file system folder contains a New submenu that, by default, includes the Shortcut and Folder commands. These commands allow the user to create new shortcuts and folders within the current folder. The New submenu can also include other nondefault commands that let the user create new files of various types within the current folder, such as sound files, text files, and bitmap files. For example, the New submenu might include a Sound command that creates a .WAV file in the current folder.

If your application creates a type of file that the user may want to create from within a file system folder, you should consider adding a command for it to the New submenu. For example, suppose you have created a graphics application that creates files with the .XYZ filename extension. You could add a command, such as XYZ Picture, that creates a new .XYZ file or launches your application and opens a new .XYZ file for editing.

You add a command to the New submenu by including a ShellNew key below the file association key for your filetype. When the system needs to create the New submenu, it searches through the file association entries for instances of the ShellNew key. When it finds an instance of ShellNew, the system retrieves the string associated with the application identifier key (xyzfile) and adds the string to the New submenu as a new command. Note that an Open command must be registered below the application identifier key; otherwise, the system does not add the Open command to the New submenu.

The following example shows the registry entries needed to add the XYZ Picture command to the New submenu.

HKEY_CLASSES_ROOT
    .xyz="xyzfile"
        ShellNew

            NullFile=""

    .

    .

    .

    xyzfile="XYZ Picture"

        shell

            open

                command="C:\XYZ\XYZAPP.EXE %1

The data names for the ShellNew key specify the method to use to create a new file of the type designated by the filename extension. There are four possible data names and values for the ShellNew key.

Data name	Value	Description
NullFile	""	Creates an empty (null) file. If this data name is specified, Data and FileName are ignored.
Data	binary-value	Creates a file that contains the data specified by binary-value. This data name is ignored if either NullFile or FileName is specified.
FileName	path-name	Creates a copy of the file specified by path-name. This data name is ignored if NullFile is specified.
Command	path-name	Executes the command specified by path-name when the file is created. For example, the command might start a wizard.


 Registering Shell Extensions

A shell extension must be registered in the Windows registry. The class identifier of each handler must be registered under the HKEY_CLASSES_ROOT\CLSID key. The CLSID key contains a list of class identifier key values, such as {00030000-0000-0000-C000-000000000046}. Each class identifier key is a globally unique identifier (GUID) generated by the UUIDGEN tool. Within each class identifier key, the handler adds an InProcServer32 key that gives the location of the handler's DLL. It is best to give the complete path for the handler; using the complete path keeps the handler independent of the current path and speeds up the load time for the DLL.

The information that the shell uses to associate a shell extension handler with a file type is stored under the shellex key. The shell also uses several other special keys under HKEY_CLASSES_ROOT to look for shell extensions: *, Folder, Drives, Printers, and keys for network providers. Descriptions of the keys follow:

•	You can use the * key to register handlers that the shell calls whenever it creates a context menu or property sheet for a file object in the following manner.

HKEY_CLASSES_ROOT

  * = *

    shellex

      ContextMenuHandlers

          {00000000-1111-2222-3333-00000000000001}

      PropertySheetHandlers

          {00000000-1111-2222-3333-00000000000002}

The shell uses instances of the ExtraMenu and SummaryInfo handlers to add to the context menus and property sheets for every file object.

•	You can use Folder key to register a shell extension for directories in the file system. You can register context menu handlers, copy hook handlers, and property sheet handlers in the same way you register these handlers for the * key. An additional handler, the drag and drop handler, applies only to the Folder and Printers keys. An example showing the Folder key follows.

Folder = Folder

  shellex

    DragDropHandlers

        {00000000-1111-2222-3333-00000000000004}

    CopyHookHandlers

        {00000000-1111-2222-3333-00000000000005}

•	You can use the Drives key for the same registrations as the Folder key, but the Drives key is called only for root paths (for example, C: \).

•	The Printers key allows the same registrations as the Folder key, but it uses additional handlers for printer events, deletion or removal of printers (through the copy hook handler), and printer properties (with property sheet handlers and context menu handlers).

To avoid conflicts with other classes, you must use real GUIDs, not the sample strings shown in the previous examples.


 Debugging Tips

The shell automatically unloads a DLL when the DLL's usage count is zero, but only after the DLL has not been used for a period of time. The inactive period may be unacceptably long at times, especially when a shell extension DLL is being debugged. You can shorten the inactive period by adding the following information to the registry.

HKLM

    Software

        Microsoft

            Windows

                CurrentVersion

                    Explorer

                        AlwaysUnloadDll

AlwaysUnloadDll shortens the inactive period so that DLLs are unloaded quickly.

While debugging your extension, you may want to shut down the Windows 95 shell without closing the currently running applications. To do so, follow these steps:

1.	From the Start menu on the Windows taskbar, choose Shut Down.

2.	While holding down the CTRL+ALT+SHIFT key combination, click the No button in the Shut Down Windows dialog box.


 How the Shell Accesses Shell Extension Handlers

The shell uses two interfaces to initialize instances (objects created by IClassFactory::CreateInstance) of shell extensions: IShellExtInit and IPersistFile. The shell uses the IShellExtInit interface to initialize instances of context menu handlers, drag and drop handlers, and property sheet handlers. The shell uses IPersistFile to initialize instances of icon handlers, data handlers, and drop handlers. This interface is defined by OLE.

The IShellExtInit interface adds an additional member function, Initialize, to the standard IUnknown interface. A handler's Initialize function should keep a copy of the parameters that the shell passes to the function for later use. An example showing how to initialize instances follows.

STDMETHODIMP CShellExt::Initialize(LPCITEMIDLIST pIDFolder,
    LPDATAOBJECT pDataObj, HKEY hRegKey)

{

    // Initialize can be called more than once.

    if (m_pDataObj)

        m_pDataObj->Release();

    // Save the object pointer.

    if (pDataObj) {

        m_pDataObj = pDataObj;

        pDataObj->AddRef();

    }

    // Duplicate the registry handle.

    if (hRegKey)

        RegOpenKeyEx(hRegKey, NULL, 0L, MAXIMUM_ALLOWED,

            &this->hRegKey);

    return NOERROR;

}

A shell extension handler must implement three functions: an entrypoint function (often called DllMain or LibMain), DllCanUnloadNow, and DllGetClassObject.

DllCanUnloadNow and DllGetClassObject are essentially the same as they would be for any OLE in-process server DLL. The use of DllCanUnloadNow is shown in the following example.

STDAPI DllCanUnloadNow(void)

{

    // g_cRefThisDll must be placed in the instance-specifc
    // data section.

    return ResultFromScode((g_cRefThisDll==0) ? S_OK : S_FALSE);

}

DllGetClassObject needs to expose the class factory for the object in the DLL. For more information about exposing the class factory, see the OLE documentation included in the Microsoft® Win32® Software Development Kit (SDK). The following example shows how to expose the class factory.

// DllGetClassObject - a DLL entrypoint function used by
// most in-process server DLLs.

STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppvOut)

{

    *ppvOut = NULL; // assume failure

    if (IsEqualIID(rclsid, CLSID_ShellExtension)) {

        return CShellExtSample_Create(riid, ppvOut);

    } else {

        return CLASS_E_CLASSNOTAVAILABLE;

    }

}


 Context Menu Handlers

A context menu handler is a shell extension that adds menu items to any of the shell's context menus. There are two types of context menu handlers. Each type has a different purpose, but the same implementation. Context menu extensions are used when the user clicks a file object by using mouse button 2, and drag and drop handlers are used when the user drags a file object using mouse button 2. This section describes the types of context menu handlers, how they are used, how they are added to the registry, and the interfaces that they must implement.


 Context Menu Extensions

When the user clicks mouse button 2 on an item within the shell's namespace (that is, file, directory, server, work group, and so on), it creates the default context menu for the type of item and then loads context menu extensions that are registered for the type (and its base type) so that they can add extra menu items. The context menu extensions are registered at the following location.

HKCR\{ProgID}\shellex\ContextMenuHandlers


 IContextMenu Interface

An application implements a context menu handler interface, IContextMenu, to add menu items to the context menu for a file object. The shell displays the object's context menu when the user clicks the object with mouse button 2. The menu items can be either class-specific (that is, applicable to all files of a particular type) or instance-specific (that is, applicable to an individual file).

When the user clicks a file object by using mouse button 2, the system passes the address of the object's context menu to the context menu handler, which should use the handle only to add items to the menu. The handler should not delete or modify existing menu items, because other handlers may add items either before or after it does. In addition, the shell adds items to the menu after all context menu handlers have been called.

Context menu handlers are entered in the registry under the shellex key within an application's information area. The ContextMenuHandlers key lists the names of subkeys that contain the CLSID of each context menu handler. An example showing the ContextMenuHandlers key follows.

ContextMenuHandlers

    {00000000-1111-2222-3333-00000000000001}

You can register multiple context menu handlers for a file type.

In addition to the standard IUnknown member functions, the context menu handler interface uses the QueryContextMenu, InvokeCommand, and GetCommandString member functions.

When the user selects one of the menu items added by a context menu handler, the shell calls the handler's IContextMenu::InvokeCommand member function to let the handler process the command. If multiple context menu handlers are registered for a file type, the value of the ContextMenuHandlers key determines the order of the commands.

When the system is about to display a context menu (or the File menu on the menu bar) for a file object, the system calls the context menu handler's QueryContextMenu member function. The context menu handler inserts menu items by position (MF_POSITION) directly into the context menu by calling the InsertMenu function. The following example shows that menu items must be string items (MF_STRING).

STDMETHODIMP CShellExt::QueryContextMenu(HMENU hMenu,

    UINT indexMenu, UINT idCmdFirst, UINT idCmdLast, UINT uFlags)

{

    UINT idCmd = idCmdFirst;

    char szMenuText[64];

    char szMenuText2[64];

    char szMenuText3[64];

    char szMenuText4[64];

    BOOL bAppendItems=TRUE;

    if ((uFlags & 0x000F) == CMF_NORMAL) {

        lstrcpy(szMenuText, "&New .GAK menu 1, Normal File");

        lstrcpy(szMenuText2, "&New .GAK menu 2, Normal File");

        lstrcpy(szMenuText3, "&New .GAK menu 3, Normal File");

        lstrcpy(szMenuText4, "&New .GAK menu 4, Normal File");

    } else if (uFlags & CMF_VERBSONLY) {

        lstrcpy(szMenuText, "&New .GAK menu 1, Shortcut File");

        lstrcpy(szMenuText2, "N&ew .GAK menu 2, Shortcut File");

        lstrcpy(szMenuText3, "&New .GAK menu 3, Shortcut File");

        lstrcpy(szMenuText4, "&New .GAK menu 4, Shortcut File");

    } else if (uFlags & CMF_EXPLORE) {

        lstrcpy(szMenuText, "&New .GAK menu 1,

            Normal File right click in Explorer");

        lstrcpy(szMenuText2, "N&ew .GAK menu 2,

            Normal File right click in Explorer");

        lstrcpy(szMenuText3, "&New .GAK menu 3,

            Normal File right click in Explorer");

        lstrcpy(szMenuText4, "&New .GAK menu 4,

            Normal File right click in Explorer");

    } else if (uFlags & CMF_DEFAULTONLY) {

        bAppendItems = FALSE;

    } else {

        char szTemp[32];

       bAppendItems = FALSE;

    }

    if (bAppendItems) {

        InsertMenu(hMenu, indexMenu++, MF_SEPARATOR | MF_BYPOSITION,

            0, NULL);

        InsertMenu(hMenu, indexMenu++, MF_STRING | MF_BYPOSITION,

            idCmd++, szMenuText);

        InsertMenu(hMenu, indexMenu++, MF_SEPARATOR | MF_BYPOSITION,

            0, NULL);

        InsertMenu(hMenu, indexMenu++, MF_STRING | MF_BYPOSITION,

            idCmd++, szMenuText2);

        InsertMenu(hMenu, indexMenu++, MF_SEPARATOR | MF_BYPOSITION,

            0, NULL);

        InsertMenu(hMenu, indexMenu++, MF_STRING | MF_BYPOSITION,

            idCmd++, szMenuText3);

        InsertMenu(hMenu, indexMenu++, MF_STRING | MF_BYPOSITION,

            idCmd++, szMenuText4);

        // Must return the number of menu items added.

        return ResultFromShort(idCmd-idCmdFirst);

    }

    return NOERROR;

}

The system calls the InvokeCommand member function when the user selects a menu item that the context menu handler added to the context menu. The InvokeCommand function in the following example handles the commands associated with the menu items added by the previous example.

STDMETHODIMP CShellExt::InvokeCommand(LPCMINVOKECOMMANDINFO lpcmi)

{

    HRESULT hr = E_INVALIDARG;

    // If the high-order word of lpcmi->lpVerb is not NULL, this

    // function was called by an application and lpVerb is a command

    // that should be activated. Otherwise, the shell has called this

    // function, and the low-order word of lpcmi->lpVerb is the

    // identifier of the menu item that the user selected.

    if (!HIWORD(lpcmi->lpVerb)) {

        UINT idCmd = LOWORD(lpcmi->lpVerb);

        switch (idCmd) {

            case 0:

                hr = DoGAKMenu1(lpcmi->hwnd, lpcmi->lpDirectory,

                    lpcmi->lpVerb, lpcmi->lpParameters, lpcmi->nShow);

                break;

            case 1:

                hr = DoGAKMenu2(lpcmi->hwnd, lpcmi->lpDirectory,

                    lpcmi->lpVerb, lpcmi->lpParameters, lpcmi->nShow);

                break;

            case 2:

                hr = DoGAKMenu3(lpcmi->hwnd, lpcmi->lpDirectory,

                    lpcmi->lpVerb, lpcmi->lpParameters, lpcmi->nShow);

                break;

            case 3:

                hr = DoGAKMenu4(lpcmi->hwnd, lpcmi->lpDirectory,

                    lpcmi->lpVerb, lpcmi->lpParameters, lpcmi->nShow);

                break;

        }

    }

    return hr;

}

Windows calls the GetCommandString member function to get a language-independent command string or the help text for a context menu item.


 Drag and Drop Handlers

Drag and drop handlers implement the IContextMenu interface. In fact, a drag and drop handler is simply a context menu handler affecting the menu that the shell displays when a user drags and drops a file object with mouse button 2. Because this menu is called the drag and drop menu, shell extensions that add items to this menu are called drag and drop handlers. Drag and drop handlers work the same way as context menu handlers.

Note that drag and drop handlers are registered under the key of folder types (typically the Directory key). To change the behavior of the dragged object (IDataObject), you need to implement a data handler.


 Icon Handlers

An application can customize the icons that the shell displays for the application's file types. The icon interface also allows an application to specify icons for folders and subfolders within the application's file structure.

An application can specify icons for its file types in two ways. The simplest way is to specify a class icon to be used for all files of a particular file type by adding a DefaultIcon key to the registry under the program information. For information about specifying a class icon, see "Setting Default Icons for File Classes" earlier in this article.

An application can use the %1 value with the DefaultIcon key. This value denotes that each file instance of this type can have a different icon. The application must supply an icon handler for the file type and add an IconHandler key to the shellex key for the application. An application can have only one entry for the IconHandler key, and the value of its key denotes the CLSID of the icon handler.

shellex

    IconHandler

        {00000000-1111-2222-3333-00000000000003}

DefaultIcon = %1

To have customized icons, an application must provide an icon handler that implements the IExtractIcon interface. The system follows these steps when it is about to display an icon for a file type that has instance-specific icons:

1.	Retrieves the class identifier of the handler.

2.	Creates a handler object by calling the CoCreateInstance function with the CLSID.

3.	Initializes the instance by calling the IPersistFile::Load member function.

4.	Uses the QueryInterface member function to get to the IExtractIcon interface.

5.	Calls the IExtractIcon::GetIconLocation and IExtractIcon::Extract member functions.

The IExtractIcon interface has the Extract and GetIconLocation member functions in addition to the usual IUnknown member functions.

The system calls the GetIconLocation member function to get the location and index of an icon to display. Typically, the icon location is an executable or DLL filename, but it can be any file.

The system calls the Extract member function when it needs to display an icon for a file that does not reside in an executable or DLL file. Applications usually have the file icons in their executable or DLL files, so icon handlers can simply implement this member function as a return-only function that returns the E_FAIL error value. You need to implement the Extract member function only if the icon image is stored in a file in an application-defined format. When the icon for a file is in a separate .ICO file (or any other type of file), the icon handler must extract the icon for the shell and return it in this member function.


 Property Sheet Handlers

Another way the shell can be extended is by custom property sheets. When the user selects the properties for a file, the shell displays a standard property sheet. If the registered file type has a property sheet handler, the shell allows the user to access additional sheets that the handler provides. Property sheet handlers implement the IShellPropSheetExt interface.

Property sheet handlers are entered in the registry under the shellex key within an application's information area. The PropertySheetHandlers key lists the names of subkeys that contain the class identifier of each context menu handler, as shown in the following example.

PropertySheetHandlers

    {00000000-1111-2222-3333-00000000000002}

You can register multiple property sheet handlers for a file type. In this case, the order of the subkey names in the PropertySheetHandlers key determines the order of the additional property sheets. You can use a maximum of 24 (the value of MAXPROPPAGES) pages in a property sheet.


 Adding Property Sheet Pages

The property sheet handler uses the AddPages member function in addition to the usual IUnknown member functions. The system calls the AddPages member function when it is about to display a property sheet. The system calls each property sheet handler registered to the file type to allow the handlers to add pages to the property sheets. The following example shows how to implement the AddPages member function.

STDMETHODIMP CSamplePageExt::AddPages(LPFNADDPROPSHEETPAGE lpfnAddPage,

    LPARAM lParam)

{

    PROPSHEETPAGE psp;

    HPROPSHEETPAGE hpage;

    psp.dwSize      = sizeof(psp);   // no extra data

    psp.dwFlags     = PSP_USEREFPARENT | PSP_USERELEASEFUNC;

    psp.hInstance   = (HINSTANCE)g_hmodThisDll;

    psp.pszTemplate = MAKEINTRESOURCE(DLG_FSPAGE);

    psp.pfnDlgProc  = FSPage_DlgProc;

    psp.pcRefParent = &g_cRefThisDll;

    psp.pfnRelease  = FSPage_ReleasePage;

    psp.lParam      = (LPARAM)hdrop;

    hpage = CreatePropertySheetPage(&psp);

    if (hpage) {

        if (!lpfnAddPage(hpage, lParam))

            DestroyPropertySheetPage(hpage);

    }

    return NOERROR;

}


 Replacing Control Panel Pages

The ReplacePage member function is called only by Control Panel applications. It allows you to replace the property sheet of a standard Control Panel application with a custom page. For example, if a mouse manufacturer adds extra buttons to its mouse, the manufacturer can replace the standard Mouse Control Panel's "Buttons" property sheet page. The ReplacePage member function is not called by the shell because the shell does not have any property sheet pages that can be replaced by a shell extension. Currently, only Control Panel applications call this member function, but other property sheet suppliers could use this member function to allow their property sheet pages to be replaced.

Each property sheet handler that allows a property sheet page to be replaced must specify the registry location where other handlers that replace pages register themselves. For standard Control Panel applications, this location is defined by the REGSTR_PATH_CONTROLSFOLDER macro in the REGSTR.H file. The macro defines the key under the HKEY_LOCAL_MACHINE key in which all Control Panel property sheet page replacement handlers must register. For example, a property sheet handler that needs to replace a property sheet page for the  Mouse Control Panel would register a property sheet extension handler in the following registry location.

HKEY_LOCAL_MACHINE

  REGSTR_PATH_CONTROLSFOLDER

    Mouse

      shellex

        PropertySheetHandlers = NewMousePage

            NewMousePage = {00000000-1111-2222-3333-00000000000002}

In addition, a property sheet handler that allows replaceable pages must define identifiers for each page that can be replaced.

Standard Control Panel applications define this location in the REGSTR.H and CPLEXT.H header files. In REGSTR.H, the REGSTR_PATH_CONTROLSFOLDER macro defines the key under the HKEY_LOCAL_MACHINE key in which all Control Panel property sheet page replacement handlers must register. CPLEXT.H defines the subkey for each Control Panel application that contains a replacable property sheet page: \Mouse for a Mouse Control Panel application and \Keyboard for a Keyboard Control Panel application.

Standard Control Panel applications define these identifiers in CPLEXT.H. For example, CPLPAGE_MOUSE_BUTTONS defines the identifier for the Mouse Control Panel's Buttons page, and CPLPAGE_KEYBOARD_SPEED defines the identifier for the Keyboard Control Panel's Speed page.


 Copy Hook Handlers

A copy hook handler is a shell extension that the shell calls before copying, moving, deleting, or renaming a folder object. The copy hook handler does not perform the task itself, but the handler provides approval for the task. When the shell receives approval from the copy hook handler, it performs the actual file system operation (that is, copies, moves, deletes, or renames). Copy hook handlers are not informed about the success of the operation, so they cannot monitor actions that occur to folder objects.

The shell initializes the copy hook handler interface directly — that is, without using an IShellExtInit or IPersistFile interface first. A folder object can have multiple copy hook handlers. The copy hook handler interface has one member function, CopyCallBack, in addition to the standard IUnknown member functions.

The shell calls the CopyCallBack member function before it copies, moves, deletes, or renames a folder object. The function returns an integer value that indicates whether the shell should perform the operation. The shell will call each copy hook handler registered for a folder object until either all the handlers have been called or any handler returns the IDCANCEL value. The handler can also return the IDYES value to specify that the operation should be carried out or the IDNO value to specify that the operation should not be performed.


 Data Handlers

When a file is dragged from the shell (or copied to the clipboard from the shell), the shell creates a default IDataObject interface that supports standard clipboard formats (CF_HDROP, "Shell IDList Array", and so on). An application can add more clipboard formats by providing a data handler for the file type. A data handler must support both the IPersistFile and IDataObject interfaces. The shell initializes a data handler by calling the IPersistFile::Load member function. When a data handler is provided, the default IDataObject interface delegates some member function calls to the data handler so that the additional clipboard data formats become available to the drop target.

You register a data handler by adding a DataHandler key and class identifier for the handler under the shellex key for the file type as shown in the following example.

shellex

    DataHandler = {00000000-1111-2222-3333-00000000000003}


 Drop Handlers

By default, a file is not a drop target. By providing a drop handler for the file types created by your application, you can make the files into drop targets. A drop handler must support both the IPersistFile and IDropTarget interfaces. The shell initializes a drop handler by calling the IPersistFile::Load member function. When the user drags an object over one of your application's files or drops an object onto one of its files, the system calls the appropriate member functions of the IDropTarget interface.

You register a drop handler by adding a DropHandler key and class identifier for the handler under the shellex key for the file type as shown in the followng example.

shellex

    DropHandler = {00000000-1111-2222-3333-00000000000003}


 Reference

The following interfaces, member functions, and structures are associated with shell extensions.


 Interfaces and Member Functions


IContextMenu [New - Windows 95]
 IContextMenu

[New - Windows 95]

Designates an interface that enables the shell to retrieve extensions to context menus. The IContextMenu interface has the following member functions.

GetCommandString	Retrieves the language-independent name of a menu command or the help text for a menu command.
InvokeCommand	Carries out a menu command, either in response to user input or otherwise.
QueryContextMenu	Adds commands to a context menu.
Like all OLE interfaces, IContextMenu also includes the QueryInterface, AddRef, and Release member functions.


IContextMenu::GetCommandString [New - Windows 95]
 IContextMenu::GetCommandString

[New - Windows 95]

HRESULT IContextMenu::GetCommandString(
    LPCONTEXTMENU pIface, UINT idCmd, UINT uFlags,
    UINT *pwReserved, LPSTR pszName, UINT cchMax);

Retrieves the language-independent command string or the help text for a context menu item.

•	Returns the NOERROR value if successful or an OLE-defined error code otherwise.

pIface

Address of the IContextMenu interface. In C++, this parameter is implicit.

idCmd

Menu item identifier offset.

uFlags

Flag specifying the information to retrieve. This parameter can be one of these values:

GCS_HELPTEXT	Returns the help text for the menu item.
GCS_VALIDATE	Validates that the menu item exists.
GCS_VERB	Returns the language-independent command name for the menu item.
pwReserved

Reserved. Applications must specify NULL when calling this member function, and handles must ignore this parameter when called.

pszName and cchMax

Address and size of the buffer that receives the null-terminated string.

The language-independent command name is a name that can be passed to the IContextMenu::InvokeCommand member function to activate a command by an application. The help text is a description that Explorer displays in its status bar; it should be reasonably short (under 40 characters).


IContextMenu::InvokeCommand [New - Windows 95]
 IContextMenu::InvokeCommand

[New - Windows 95]

HRESULT IContextMenu::InvokeCommand(
    LPCONTEXTMENU pIface, LPCMINVOKECOMMANDINFO lpici);

Carries out the command associated with a context menu item.

•	Returns the NOERROR value if successful or an OLE-defined error code otherwise.

pIface

Address of the IContextMenu interface. In C++, this parameter is implicit.

lpici

Address of a CMINVOKECOMMANDINFO structure containing information about the command.

The shell calls this member function when the user chooses a command that the handler added to a context menu. This member function may also be called by an application without any corresponding user action.


IContextMenu::QueryContextMenu [New - Windows 95]
 IContextMenu::QueryContextMenu

[New - Windows 95]

HRESULT IContextMenu::QueryContextMenu(

    LPCONTEXTMENU pIface, HMENU hmenu, UINT indexMenu,

    UINT idCmdFirst, UINT idCmdLast, UINT uFlags

    );

Adds menu items to the specified menu. The menu items should be inserted at a given position in the menu, and their menu item identifiers must be in a given range.

•	Returns an HRESULT structure in which, if successful, the code member contains the menu identifier offset of the last menu item added.

pIface

Address of the IContextMenu interface. In C++, this parameter is implicit.

hmenu

Handle of the menu. The handler should specify this handle when calling the InsertMenu or InsertMenuItem function.

indexMenu

Zero-based position at which to insert the first menu item.

idCmdFirst and idCmdLast

Minimum and maximum values that the handler can specify for menu item identifiers. The actual identifier of each menu item should be idCmdFirst plus a menu identifier offset in the range zero through (idCmdLast − idCmdFirst).

uFlags

Flag specifying zero or more of these values:

CMF_DEFAULTONLY	The user is activating the default action, typically by double-clicking. A context menu extension or drag and drop handler should not add any menu items if this value is specified. A namespace extension should add only the default item, if any.
CMF_EXPLORE	Context menu handlers should ignore this value. This value is specified if the context menu is for an object in the left pane of the explorer.
CMF_NORMAL	Indicates normal operation. A context menu extension, namespace extension, or drag and drop handler can add any menu items.
CMF_VERBSONLY	Context menu handlers should ignore this value. This value is specified if the context menu is for a shortcut object.
The remaining bits of the low-order word are reserved by the system. The high-order word may be used for context-specific communications.

An extension must not modify other menu items or insert menu items at a location other than that specified by indexMenu. Such an extension will not work in a future version of the Windows operating system.


ICopyHook [New - Windows 95]
 ICopyHook

[New - Windows 95]

Designates an interface that allows a copy hook handler to prevent a folder or printer object from being copied, moved, deleted, or renamed. The shell calls a copy hook handler whenever file system directories are about to be copied, moved, deleted, or renamed and whenever the status of a printer is about to change.

The shell creates the copy hook handler interface directly — that is, without using the IShellExtInit or IPersistFile interface first. A folder object can have multiple copy hook handlers.

A copy hook handler interface has one member function, CopyCallBack, in addi-tion to the standard QueryInterface, AddRef, and Release member functions.


ICopyHook::CopyCallback [New - Windows 95]
 ICopyHook::CopyCallback

[New - Windows 95]

UINT CopyCallback(ICopyHook FAR * pCopyHook,
    HWND hwnd, UINT wFunc, UINT wFlags, LPCSTR pszSrcFile,
    DWORD dwSrcAttribs, LPCSTR pszDestFile, DWORD dwDestAttribs);

Either allows the shell to carry out a copy, move, delete, or rename operation on a folder object, or prevents the shell from carrying out the operation. The shell calls each copy hook handler registered for a folder object until either all the handlers have been called or any handler returns the IDCANCEL value.

•	Returns an integer value that indicates whether the shell should perform the operation. It can be one of the following values:

IDCANCEL	Prevents the current operation and cancels any pending operations.
IDNO	Prevents the operation on this folder, but continues with any other operations (for example, a batch copy operation).
IDYES	Allows the operation.
pCopyHook

Address of the ICopyHook interface. In C++, this parameter is implicit.

hwnd

Handle of the window that the copy hook handler should use as the parent window for any user interface elements the handler may need to display. If the FOF_SILENT value is specified, the member function should ignore this parameter.

wFunc

Operation to perform. This parameter can be one of these values:

FO_COPY	Copies the file specified by pszSrcFile to the location specified by pszDestFile.
FO_DELETE	Deletes the file specified by pszSrcFile.
FO_MOVE	Moves the file specified by pszSrcFile to the location specified by pszDestFile.
FO_RENAME	Renames the file specified by pszSrcFile.
PO_DELETE	Deletes the printer specified by pszSrcFile.
PO_PORTCHANGE	Changes the printer port. pszSrcFile and pszDestFile contain double-null terminated lists of strings. Each list contains the printer name followed by the port name. The port name in pszSrcFile is the current printer port, and the port name in pszDestFile is the new printer port.
PO_RENAME	Renames the printer specified by pszSrcFile.
PO_REN_PORT	Combination of PO_RENAME and PO_PORTCHANGE.
wFlags

Flags that control the operation. This parameter can be a combination of these values:

FOF_ALLOWUNDO	Preserves undo information, if possible.
FOF_CONFIRMMOUSE	Not implemented.
FOF_FILESONLY	Not implemented. The shell calls a copy hook handler only for folder objects, not files.
FOF_MULTIDESTFILES	Indicates that the SHFileOperation function specifies multiple destination files (one for each source file) rather than one directory where all the source files are to be deposited. A copy hook handler typically ignores this value.
FOF_NOCONFIRMATION	Responds with "yes to all" for any dialog box that is displayed.
FOF_NOCONFIRMMKDIR	Does not confirm the creation of any needed directories if the operation requires a new directory to be created.
FOF_RENAMEONCOLLISION	Gives the file being operated on a new name (such as, "Copy #1 of ...") in a copy, move, or rename operation if a file of the target name already exists.
FOF_SILENT	Displays no progress dialog box.
FOF_SIMPLEPROGRESS	Displays a progress dialog box, but the dialog box does not show the names of the files.
pszSrcFile

Address of a string that contains the name of the source file.

dwSrcAttribs

Attributes of the source file. This parameter can be a combination of any of the file attribute (FILE_ATTRIBUTE_) flags defined in the Windows header files.

pszDestFile

Address of a string that contains the name of the destination file.

dwDestAttribs

Attributes of the source file. This parameter can be a combination of any of the file attribute (FILE_ATTRIBUTE_) flags defined in the Windows header files.


IExtractIcon [New - Windows 95]
 IExtractIcon

[New - Windows 95]

Designates an interface that enables the shell to retrieve icons for file objects. The IExtractIcon interface has the following member functions.

GetIconLocation	Retrieves the icon location for a file object.
Extract	Extracts an icon from the specified location.
Like all OLE interfaces, IExtractIcon also includes the QueryInterface, AddRef, and Release member functions.


IExtractIcon::GetIconLocation [New - Windows 95]
 IExtractIcon::GetIconLocation

[New - Windows 95]

HRESULT IExtractIcon::GetIconLocation(

    LPEXTRACTICON pIface, UINT uFlags, LPSTR szIconFile,

    UINT cchMax, int *piIndex, UINT *pwFlags

    );

Retrieves the location and index of an icon.

•	Returns the NOERROR value if the function returned a valid location or the S_FALSE value if the shell should use a default icon.

pIface

Address of the IExtractIcon interface. In C++, this parameter is implicit.

uFlags

Flags. This parameter can be zero or these values:

GIL_FORSHELL	The icon is to be displayed in a shell folder.
GIL_OPENICON	The icon is for a folder that is open.
szIconFile and cchMax

Address and size of the buffer that receives the icon location. The icon location is a null-terminated string that typically specifies the name of an icon file.

piIndex

Address of an integer that receives the icon index.

pwFlags

Address of an unsigned integer that receives zero or more of these values:

GIL_DONTCACHE	The shell should use the Extract member function rather than look up the icon in its internal cache.
GIL_NOTFILENAME	The location is not a filename. Instead, it is an extension-specific string that identifies the icon. The caller must use the Extract member function to retrieve the icon image no matter what flags are returned.
GIL_PERCLASS	All file objects of this class have the same icon.
GIL_PERINSTANCE	Each file object of this class has its own icon.
GIL_SIMULATEDOC	The shell should create a document icon using the specified icon.


IExtractIcon::Extract [New - Windows 95]
 IExtractIcon::Extract

[New - Windows 95]

HRESULT IExtractIcon::Extract(

    LPEXTRACTICON pIface, LPCSTR pszFile, UINT nIconIndex,

    HICON *phiconLarge, HICON *phiconSmall, UINT nIconSize

    );

Extracts an icon image from the specified location.

•	Returns the NOERROR value if the function extracted the icon or the S_FALSE value if the calling application should extract the icon by calling the ExtractIcon function.

pIface

Address of the IExtractIcon interface. In C++, this parameter is implicit.

pszFile

Address of a null-terminated string specifying the icon location. This parameter must be a string returned by the GetIconLocation member function.

nIconIndex

Icon index.

phiconLarge and phiconSmall

Addresses of variables that receive the handles of the large and small icons, respectively.

nIconSize

Value specifying the size, in pixels, of the large icon required. The size specified can be the width or height. The width of an icon always equals its height.

The icon location and index are the same values as returned by the IExtractIcon::GetIconLocation member function. If this function returns S_FALSE, these values must specify an icon filename and index. If this function does not return S_FALSE, the calling application should make no assumptions about the meanings of the pszFile and nIconIndex parameters.


IShellPropSheetExt [New - Windows 95]
 IShellPropSheetExt

[New - Windows 95]

Designates an interface that allows a property sheet handler to add or replace pages in the property sheet for a file object. The IShellPropSheetExt interface has the following member functions.

AddPages	Adds one or more pages to a property sheet for a file object.
ReplacePage	Replaces a page in a property sheet for a Control Panel object.
Like all OLE interfaces, IShellPropSheetExt also includes the QueryInterface, AddRef, and Release member functions.


IShellPropSheetExt::AddPages [New - Windows 95]
 IShellPropSheetExt::AddPages

[New - Windows 95]

HRESULT AddPages(IShellPropSheetExt FAR * pProp,
    LPFNADDPROPSHEETPAGE lpfnAddPage, LPARAM lParam);

Adds one or more pages to a property sheet that the shell displays for a file object. When it is about to display the property sheet, the shell calls the AddPages member function of each property sheet handler registered to the file type.

•	Returns the NOERROR value if successful or an OLE-defined error value otherwise.

pProp

Address of the IShellPropSheetExt interface. In C++, this parameter is implicit.

lpfnAddPage

Address of a callback function that the property sheet handler calls to add a page to the property sheet. The function takes a property sheet handle returned by the CreatePropertySheetPage function and the lParam parameter passed to the AddPages member function. For more information about the callback function, see the description of the AddPropSheetPageProc function in the documentation included with the Win32 Software Development Kit (SDK).

lParam

Parameter to pass to the function pointed to by lpfnAddPage.

For each page it needs to add to a property sheet, a property sheet handler fills a PROPSHEETPAGE structure, calls CreatePropertySheetPage, and then calls the function pointed to by lpfnAddPage.


IShellPropSheetExt::ReplacePage [New - Windows 95]
 IShellPropSheetExt::ReplacePage

[New - Windows 95]

HRESULT ReplacePage(IShellPropSheetExt FAR * pProp,
    UINT uPageID, LPFNADDPROPSHEETPAGE lpfnReplacePage, LPARAM lParam);

Replaces a page in a property sheet for a Control Panel object.

•	Returns the NOERROR value if successful or an OLE-defined error value otherwise.

pProp

Address of the IShellPropSheetExt interface. In C++, this parameter is implicit.

uPageID

Identifier of the page to replace. The values for this parameter for Control Panels can be found in CPLEXT.H.

lpfnReplacePage

Address of a function that the property sheet handler calls to replace a page to the property sheet. The function takes a property sheet handle returned by the CreatePropertySheetPage function and the lParam parameter passed to the ReplacePage member function.

lParam

Parameter to pass to the function pointed to by lpfnReplacePage.

To replace a page, a property sheet handler fills a PROPSHEETPAGE structure, calls CreatePropertySheetPage, and then calls the function pointed to by lpfnReplacePage.


IShellExtInit [New - Windows 95]
 IShellExtInit

[New - Windows 95]

Designates an interface used to initialize a property sheet extension, context menu extension, or drag and drop handler. The IShellExtInit interface has the following member functions.

Initialize	Initializes the shell extension.
Like all OLE interfaces, IShellExtInit also includes the QueryInterface, AddRef, and Release member functions.


IShellExtInit::Initialize [New - Windows 95]
 IShellExtInit::Initialize

[New - Windows 95]

HRESULT IShellExtInit::Initialize(

    LPSHELLEXTINIT pIface, LPCITEMIDLIST pidlFolder,

    LPDATAOBJECT lpdobj, HKEY hkeyProgID

    );

Initializes a property sheet extension, context menu extension, or drag and drop handler.

•	Returns the NOERROR value if successful or an OLE-defined error value otherwise.

pIface

Address of the IShellExtInit interface. In C++, this parameter is implicit.

pidlFolder

Address of an ITEMIDLIST structure (item identifier list) that uniquely identifies a folder. This parameter is NULL for property sheet extensions and context menu extensions. For nondefault drag and drop menu extensions, this parameter must specify the target folder.

lpdobj

Address of an IDataObject interface object that can be used to retrieve the objects being acted upon.

hkeyProgID

Registry key for the file object or folder type.

This is the first member function that the shell calls (besides AddRef, Release, and QueryInterface) after it creates an instance of a property sheet extension, context menu extension, or drag and drop handler.

The meanings of some parameters depend on the extension type. For drag and drop handlers, the item identifier list specifies the destination folder (the drop target), the IDataObject interface identifies the items being dropped, and the registry key specifies the file class of the destination folder (typically "Directory").

For property sheet extensions and context menu extensions, the item identifier list specifies the folder that contains the selected file objects, the IDataObject interface identifies the selected file objects, and the registry key specifies the file class of the file object that has the focus.


 Structures

The following structures are used with shell extensions.


CMINVOKECOMMANDINFO [New - Windows 95]
 CMINVOKECOMMANDINFO

[New - Windows 95]

typedef struct _CMInvokeCommandInfo {

    DWORD cbSize;        // sizeof(CMINVOKECOMMANDINFO)

    DWORD fMask;         // see below

    HWND hwnd;           // see below

    LPCSTR lpVerb;       // see below

    LPCSTR lpParameters; // see below

    LPCSTR lpDirectory;  // see below

    int nShow;           // see below

    DWORD dwHotKey;      // see below

    HANDLE hIcon;        // see below

} CMINVOKECOMMANDINFO, *LPCMINVOKECOMMANDINFO;

Contains information about a context menu command.

fMask

Value specifying zero or more of these flags:

CMIC_MASK_HOTKEY	Specifies that dwHotKey is valid.
CMIC_MASK_ICON	Specifies that hIcon is valid.
CMIC_MASK_FLAG_NO_UI	Prevents the system from displaying user interface elements (for example, error messages) while carrying out a command.
hwnd

Handle of the window that owned the context menu, such as the desktop, Explorer, or the tray. An extension might specify this handle as the owner window of any message boxes or dialog boxes that it displays.

lpVerb

32-bit value containing zero in the high-order word and the menu-identifier offset of the command to carry out in the low-order word. The shell specifies this value (using the MAKEINTRESOURCE macro) when the user chooses a menu command.

If the high-order word is not zero, this member is the address of a null-terminated string specifying the language-independent name of the command to carry out. This member is typically a string when a command is being activated by an application. The system provides predefined constant values for the following command strings:

Value	String
CMDSTR_NEWFOLDER	"NewFolder"
CMDSTR_VIEWDETAIL	"ViewDetails"
CMDSTR_VIEWLIST	"ViewList"
lpParameters

Optional parameters. This member is always NULL for menu items inserted by a shell extension.

lpDirectory

Optional working directory name. This member is always NULL for menu items inserted by a shell extension.

nShow

Flag to pass to the ShowWindow function if the command displays a window or starts an application.

dwHotKey

Optional hot key to assign any application activated by the command. If fMask does not specify CMIC_MASK_HOTKEY, this member is ignored. A shell extension should ignore this member.

hIcon

Icon to use for any application activated by the command. If fMask does not specify CMIC_MASK_ICON, this member is ignored. A shell extension should ignore this member.

The address of this structure is passed to the IContextMenu::InvokeCommand member function.


ITEMIDLIST [New - Windows 95]
 ITEMIDLIST

[New - Windows 95]

typedef struct _ITEMIDLIST { // idl

    SHITEMID mkid;  // list of item identifers

} ITEMIDLIST, * LPITEMIDLIST;

typedef const ITEMIDLIST * LPCITEMIDLIST;

Contains a list of item identifiers. For more information, see Article 11, "Shell's Namespace."


SHITEMID [New - Windows 95]
 SHITEMID

[New - Windows 95]

typedef struct _SHITEMID {       // mkid

    USHORT cb;       // size of identifier, including cb itself

    BYTE   abID[1];  // variable-length item identifier

} SHITEMID, * LPSHITEMID;

typedef const SHITEMID  * LPCSHITEMID;

Defines an item identifier.


 Application Desktop Toolbars

An application desktop toolbar (also called an appbar) is a window that is similar to the Microsoft® Windows® taskbar. It is anchored to an edge of the screen, and it typically contains buttons that give the user quick access to other applications and windows. The system prevents other applications from using the desktop area occupied by an appbar. Any number of appbars can exist on the desktop at any given time.


 About Application Desktop Toolbars

Windows provides an application programming interface (API) that lets you take advantage of appbar services provided by the system. The services help ensure that application-defined appbars operate smoothly with one another and with the taskbar. The system maintains information about each appbar and sends the appbars messages to notify them about events that can effect their size, position, and appearance.


 Sending Messages

An application uses a special set of messages, called appbar messages, to add or remove an appbar, set an appbar's size and position, and retrieve information about the size, position, and state of the taskbar. To send an appbar message, an application must use the SHAppBarMessage function. The function's parameters include a message identifier, such as ABM_NEW, and the address of an APPBARDATA structure. The structure members contain information that the system needs to process the given message.

For any given appbar message, the system uses some members of the APPBARDATA structure and ignores the others. However, because the system always uses the cbSize and hWnd members, an application must fill these members for every appbar message. The cbSize member specifies the size of the structure, and the hWnd member is the handle of the appbar's window.

Some appbar messages request information from the system. When processing these messages, the system copies the requested information into the APPBARDATA structure.


 Registration

The system keeps an internal list of appbars and maintains information about each bar in the list. The system uses the information to manage appbars, perform services for them, and send them notification messages.

An application must register an appbar (that is, add it to the internal list) before it can receive appbar services from the system. To register an appbar, an application sends the ABM_NEW message. The accompanying APPBARDATA structure includes the handle of the appbar's window and an application-defined message identifier. The system uses the message identifier to send notification messages to the window procedure of the appbar window. For more information about appbar notification messages, see "Notification Messages" later in this topic.

An application unregisters an appbar by sending the ABM_REMOVE message. Unregistering an appbar removes it from the system's internal list of appbars. The system no longer sends notification messages to the appbar nor prevents other applications from using the screen area occupied by the appbar. An application should always send ABM_REMOVE before destroying an appbar.


 Size and Position

An application should set an appbar's size and position so that it does not interfere with any other appbars or the taskbar. Every appbar must be anchored to a particular edge of the screen, and multiple appbars can be anchored to an edge. However, if an appbar is anchored to the same edge as the taskbar, the system ensures that the taskbar is always on the outermost edge.

To set the size and position of an appbar, an application first proposes a screen edge and bounding rectangle for the appbar by sending the ABM_QUERYPOS message. The system determines whether any part of the screen area within the proposed rectangle is occupied by the taskbar or another appbar, adjusts the rectangle (if necessary), and returns the adjusted rectangle to the application.

Next, the application sends the ABM_SETPOS message to set the new bounding rectangle for the appbar. Again, the system may adjust the rectangle before returning it to the application. For this reason, the application should use the adjusted rectangle returned by ABM_SETPOS to set the final size and position. The application can use the MoveWindow function to move the appbar into position.

By using a two-step process to set the size and position, the system allows the application to provide intermediate feedback to the user during the move operation. For example, if the user drags an appbar, the application might display a shaded rectangle indicating the new position before the appbar actually moves.

An application should set the size and position of its appbar after registering it and whenever the appbar receives the ABN_POSCHANGED notification message. An appbar receives this notification message whenever a change occurs in the taskbar's size, position, or visibility state and whenever another appbar on the same side of the screen is resized, added, or removed.

Whenever an appbar receives the WM_ACTIVATE message, it should send the ABM_ACTIVATE message. Similarly, when an appbar receives a WM_WINDOWPOSCHANGED message, it must call ABM_WINDOWPOSCHANGED. Sending these messages ensures that the system properly sets the Z order of any autohide appbars on the same edge.


 Autohide Application Desktop Toolbars

An autohide appbar is one that is normally hidden, but becomes visible when the user moves the mouse cursor to the screen edge that the appbar is associated with. The appbar hides itself again when the user moves the mouse cursor out of the bar's bounding rectangle.

Although the system allows a number of different appbars at any given time, it allows only one autohide appbar at a time for each screen edge on a first come, first served basis. The system automatically maintains the Z order of an autohide appbar (within its Z order group only).

An application uses the ABM_SETAUTOHIDEBAR message to register or unregister an autohide appbar. The message specifies the edge for the appbar and a flag that specifies whether the appbar is to be registered or unregistered. The message fails if an autohide appbar is being registered, but one is already associated with the specified edge. An application can retrieve the handle of the autohide appbar associated with an edge by sending the ABM_GETAUTOHIDEBAR message.

An autohide appbar does not need to register as a normal appbar; that is, it does not need to be registered by sending the ABM_NEW message. An appbar that is not registered by ABM_NEW overlaps any appbars anchored on the same edge of the screen.


 Notification Messages

The system sends messages to notify an appbar about events that can effect its position and appearance. The messages are sent in the context of an application-defined message. The application specifies the identifier of the message when it sends the ABM_NEW message to register the appbar. The notification code is in the wParam parameter of the application-defined message.

An appbar receives the ABN_POSCHANGED notification message when the taskbar's size, position, or visibility state changes, when another appbar is added to the same edge of the screen, or when another appbar on the same edge of the screen is resized or removed. An appbar should respond to this notification message by sending ABM_QUERYPOS and ABM_SETPOS messages. If an appbar's position has changed, it should call the MoveWindow function to move itself to the new position.

The system sends the ABN_STATECHANGE notification message whenever the taskbar's autohide or always-on-top state has changed — that is, when the user checks or unchecks the "Always on top" or "Auto hide" check box on the taskbar's property sheet. An appbar can use this notification message to set its state to conform to that of the taskbar, if desired.

When a full-screen application is started or when the last full-screen application is closed, an appbar receives the ABN_FULLSCREENAPP notification message. The lParam parameter indicates whether the full-screen application is opening or closing. If it is opening, the appbar must drop to the bottom of the Z order. The appbar should restore its Z order position when the last full-screen application has closed.

An appbar receives the ABN_WINDOWARRANGE notification message when the user selects the Cascade, Tile Horizontally, or Tile Vertically command from the task bar's context menu. The system sends the message two times — before rearranging the windows (lParam is TRUE) and after arranging the windows (lParam is FALSE).

An appbar can use ABN_WINDOWARRANGE messages to exclude itself from the cascade or tile operation. To exclude itself, the appbar should hide itself when lParam is TRUE and show itself when lParam is FALSE. If an appbar hides itself in response to this message, it does not need to send the ABM_QUERYPOS and ABM_SETPOS messages in response to the cascade or tile operation.


 Using Application Desktop Toolbars

This section includes examples that demonstrate how to perform the following tasks:

•	Register an application desktop toolbar (appbar).

•	Set its size and position.

•	Process the notification messages that the system sends to a registered appbar.


 Registering an Application Desktop Toolbar

An application must register an appbar by sending the ABM_NEW message. Registering an appbar adds it to the system's internal list and provides the system with a message identifier to use to send notification messages to the appbar. Before exiting, an application must unregister the appbar by sending the ABM_REMOVE message. Unregistering removes the appbar from the system's internal list and prevents the bar from receiving appbar notification messages.

The function in the following example either registers or unregisters an appbar, depending on the value of a Boolean flag parameter.

// RegisterAccessBar - registers or unregisters an appbar.

// Returns TRUE if successful or FALSE otherwise.

// hwndAccessBar - handle of the appbar

// fRegister - register and unregister flag

//

// Global variables

//     g_uSide - screen edge (defaults to ABE_TOP)

//     g_fAppRegistered - flag indicating whether the bar is registered

BOOL RegisterAccessBar(HWND hwndAccessBar, BOOL fRegister)

{

    APPBARDATA abd;

    // Specify the structure size and handle of the appbar.

    abd.cbSize = sizeof(APPBARDATA);

    abd.hWnd = hwndAccessBar;

    if (fRegister) {

        // Provide an identifier for notification messages.

        abd.uCallbackMessage = APPBAR_CALLBACK;

        // Register the appbar.

        if (!SHAppBarMessage(ABM_NEW, &abd))

            return FALSE;

        g_uSide = ABE_TOP;       // default edge

        g_fAppRegistered = TRUE;

    } else {

        // Unregister the appbar.

        SHAppBarMessage(ABM_REMOVE, &abd);

        g_fAppRegistered = FALSE;

    }

    return TRUE;

}


 Setting the Size and Position

An application should set an appbar's size and position after registering the appbar, after the user user moves or sizes the appbar, and whenever the appbar receives the ABN_POSCHANGED notification message. Before setting the size and position of the appbar, the application queries the system for an approved bounding rectangle by sending the ABM_QUERYPOS message. The system returns a bounding rectangle that does not interfere with the taskbar or any other appbar. The system adjusts the rectangle purely by rectangle subtraction; it makes no effort to preserve the rectangle's initial size. For this reason, the appbar should readjust the rectangle, as necessary, after sending ABM_QUERYPOS.

Next, the application passes the bounding rectangle back to the system by using the ABM_SETPOS message. Then it calls the MoveWindow function to move the appbar into position.

The following example shows how to set an appbar's size and position.

// AppBarQuerySetPos - sets the size and position of an appbar.

// uEdge - screen edge to which the appbar is to be anchored

// lprc - current bounding rectangle of the appbar

// pabd - address of APPBARDATA structure with the hWnd and

//     cbSize members filled

void PASCAL AppBarQuerySetPos(UINT uEdge, LPRECT lprc, PAPPBARDATA pabd)

{

    int iHeight = 0;

    int iWidth = 0;

    pabd->rc = *lprc;

    pabd->uEdge = uEdge;

    // Copy the screen coordinates of the appbar's bounding

    // rectangle into the APPBARDATA structure.

    if ((uEdge == ABE_LEFT) ||

            (uEdge == ABE_RIGHT)) {

        iWidth = pabd->rc.right - pabd->rc.left;

        pabd->rc.top = 0;

        pabd->rc.bottom = GetSystemMetrics(SM_CYSCREEN);

    } else {

        iHeight = pabd->rc.bottom - pabd->rc.top;

        pabd->rc.left = 0;

        pabd->rc.right = GetSystemMetrics(SM_CXSCREEN);

    }

    // Query the system for an approved size and position.

    SHAppBarMessage(ABM_QUERYPOS, pabd);

    // Adjust the rectangle, depending on the edge to which the

    // appbar is anchored.

    switch (uEdge) {

        case ABE_LEFT:

            pabd->rc.right = pabd->rc.left + iWidth;

            break;

        case ABE_RIGHT:

            pabd->rc.left = pabd->rc.right - iWidth;

            break;

        case ABE_TOP:

            pabd->rc.bottom = pabd->rc.top + iHeight;

            break;

        case ABE_BOTTOM:

            pabd->rc.top = pabd->rc.bottom - iHeight;

            break;

    }

    // Pass the final bounding rectangle to the system.

    SHAppBarMessage(ABM_SETPOS, pabd);

    // Move and size the appbar so that it conforms to the

    // bounding rectangle passed to the system.

    MoveWindow(pabd->hWnd, pabd->rc.left, pabd->rc.top,

        pabd->rc.right - pabd->rc.left,

        pabd->rc.bottom - pabd->rc.top, TRUE);

}


 Processing Notification Messages

An appbar receives a notification message when the state of the task bar changes, when a full screen application starts (or the last one closes), or when an event occurs that can affect the appbar's size and position. The following example shows how to process the various notification messages.

// AppBarCallback - processes notification messages sent by the system.

// hwndAccessBar - handle of the appbar

// uNotifyMsg - identifier of the notification message

// lParam - message parameter

void AppBarCallback(HWND hwndAccessBar, UINT uNotifyMsg,

    LPARAM lParam)

{

    APPBARDATA abd;

    UINT uState;

    abd.cbSize = sizeof(abd);

    abd.hWnd = hwndAccessBar;

    switch (uNotifyMsg) {

        case ABN_STATECHANGE:

            // Check to see if the taskbar's always-on-top state has

            // changed and, if it has, change the appbar's state

            // accordingly.

            uState = SHAppBarMessage(ABM_GETSTATE, &abd);

            SetWindowPos(hwndAccessBar,

                (ABS_ALWAYSONTOP & uState) ? HWND_TOPMOST : HWND_BOTTOM,

                0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);

            break;

        case ABN_FULLSCREENAPP:

            // A full screen application has started, or the last full

            // screen application has closed. Set the appbar's

            // Z order appropriately.

            if (lParam) {

                SetWindowPos(hwndAccessBar,

                    (ABS_ALWAYSONTOP & uState) ?

                                            HWND_TOPMOST : HWND_BOTTOM,

                    0, 0, 0, 0,

                    SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);

            } else {

                uState = SHAppBarMessage(ABM_GETSTATE, &abd);

                if (uState & ABS_ALWAYSONTOP)

                    SetWindowPos(hwndAccessBar, HWND_TOPMOST,

                        0, 0, 0, 0,

                        SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);

        }

        case ABN_POSCHANGED:

            // The taskbar or another appbar has changed its

            // size or position.

            AppBarPosChanged(&abd);

            break;

    }

}

The following function adjusts an appbar's bounding rectangle and then calls the application-defined AppBarQuerySetPos function (included in the previous section) to set the bar's size and position accordingly.

// AppBarPosChanged - adjusts the appbar's size and position.

// pabd - address of an APPBARDATA structure that contains information

//     used to adjust the size and position

void PASCAL AppBarPosChanged(PAPPBARDATA pabd)

{

    RECT rc;

    RECT rcWindow;

    int iHeight;

    int iWidth;

    rc.top = 0;

    rc.left = 0;

    rc.right = GetSystemMetrics(SM_CXSCREEN);

    rc.bottom = GetSystemMetrics(SM_CYSCREEN);

    GetWindowRect(pabd->hWnd, &rcWindow);

    iHeight = rcWindow.bottom - rcWindow.top;

    iWidth = rcWindow.right - rcWindow.left;

    switch (g_uSide) {

        case ABE_TOP:

            rc.bottom = rc.top + iHeight;

            break;

        case ABE_BOTTOM:

            rc.top = rc.bottom - iHeight;

            break;

        case ABE_LEFT:

            rc.right = rc.left + iWidth;

            break;

        case ABE_RIGHT:

            rc.left = rc.right - iWidth;

            break;

        }

        AppBarQuerySetPos(g_uSide, &rc, pabd);

    }


 Reference

The following function, structure, messages, and notification messages are associated with appbars.


 Function and Structure

The following function and structure are used with appbars.


SHAppBarMessage [New - Windows 95]
 SHAppBarMessage

[New - Windows 95]

WINSHELLAPI UINT APIENTRY SHAppBarMessage(DWORD dwMessage,

    PAPPBARDATA pabd);

Sends an appbar message to the system.

•	Returns a message-dependent value. For more information, see the documentation for the individual appbar messages.

dwMessage

Identifier of the appbar message to send. This parameter can be one of these values:

ABM_ACTIVATE	Notifies the system that an appbar has been activated.
ABM_GETAUTOHIDEBAR	Retrieves the handle of the autohide appbar associated with a particular edge of the screen.
ABM_GETSTATE	Retrieves the autohide and always-on-top states of the Windows taskbar.
ABM_GETTASKBARPOS	Retrieves the bounding rectangle of the Windows taskbar.
ABM_NEW	Registers a new appbar and specifies the message identifier that the system should use to send notification messages to the appbar.
ABM_QUERYPOS	Requests a size and screen position for an appbar.
ABM_REMOVE	Unregisters an appbar, removing the bar from the system's internal list.
ABM_SETAUTOHIDEBAR	Registers or unregisters an autohide appbar for an edge of the screen.
ABM_SETPOS	Sets the size and screen position of an appbar.
ABM_WINDOWPOSCHANGED	Notifies the system when an appbar's position has changed.
pabd

Address of an APPBARDATA structure. The content of the structure depends on the value of dwMessage.


APPBARDATA [New - Windows 95]
 APPBARDATA

[New - Windows 95]

typedef struct _AppBarData { // abd

    DWORD  cbSize;           // sizeof(APPBARDATA)

    HWND   hWnd;             // handle of appbar

    UINT   uCallbackMessage; // see below

    UINT   uEdge;            // see below

    RECT   rc;               // see below

    LPARAM lParam;           // see below

} APPBARDATA, *PAPPBARDATA;

Contains information that the system uses to process appbar messages.

uCallbackMessage

Application-defined message identifier. The application uses the specified identifier for notification messages that it sends to the the appbar identified by the hWnd member. This member is used when sending the ABM_NEW message.

uEdge

Flag that specifies an edge of the screen. This member can be one of these values:

ABE_BOTTOM	Bottom edge
ABE_LEFT	Left edge
ABE_RIGHT	Right edge
ABE_TOP	Top edge
This member is used when sending the ABM_GETAUTOHIDEBAR, ABM_QUERYPOS, ABM_SETAUTOHIDEBAR, and ABM_SETPOS messages.

rc

RECT structure that contains the bounding rectangle, in screen coordinates, of an appbar or the Windows taskbar. This member is used when sending the ABM_GETTASKBARPOS, ABM_QUERYPOS, and ABM_SETPOS messages.

lParam

Message-dependent value. This member is used with the ABM_SETAUTOHIDEBAR message.

This structure is used with the SHAppBarMessage function.


 Messages

An application sends appbar messages to register an appbar with the system; to set an appbar's size, position, and state; to retrieve information about the Windows taskbar; and so on. To send an appbar message, an application uses the SHAppBarMessage function. There are the following appbar messages.


ABM_ACTIVATE [New - Windows 95]
 ABM_ACTIVATE

[New - Windows 95]

SHAppBarMessage(ABM_ACTIVATE, pabd);

Notifies the system that an appbar has been activated. An appbar should call this message in response to the WM_ACTIVATE message.

•	Always returns TRUE.

pabd

Address of an APPBARDATA structure that identifies the appbar to activate. You must specify the cbSize and hWnd members when sending this message; all other members are ignored.

This message is ignored if the hWnd member of the structure pointed to by pabd identifies an autohide appbar. The system automatically sets the Z order for an autohide appbar.


ABM_GETAUTOHIDEBAR [New - Windows 95]
 ABM_GETAUTOHIDEBAR

[New - Windows 95]

hwndAutoHide = (HWND) SHAppBarMessage(ABM_GETAUTOHIDEBAR, pabd);

Retrieves the handle of the autohide appbar associated with an edge of the screen.

•	Returns the handle of the autohide appbar. The return value is NULL if an error occurs or if no autohide appbar is associated with the given edge.

pabd

Address of an APPBARDATA structure that specifies the screen edge. You must specify the cbSize, hWnd, and uEdge members when sending this message; all other members are ignored.


ABM_GETSTATE [New - Windows 95]
 ABM_GETSTATE

[New - Windows 95]

fuState = (UINT) SHAppBarMessage(ABM_GETSTATE, pabd);

Retrieves the autohide and always-on-top states of the Windows taskbar.

•	Returns zero if the taskbar is not in the autohide or always-on-top state. Otherwise, the return value is one or both of these values:

ABS_ALWAYSONTOP	The taskbar is in the always-on-top state.
ABS_AUTOHIDE	The taskbar is in the autohide state.
pabd

Address of an APPBARDATA structure. You must specify the cbSize and hWnd members when sending this message; all other members are ignored.


ABM_GETTASKBARPOS [New - Windows 95]
 ABM_GETTASKBARPOS

[New - Windows 95]

fResult = (BOOL) SHAppBarMessage(ABM_GETTASKBARPOS, pabd);

Retrieves the bounding rectangle of the Windows taskbar.

•	Returns TRUE if successful or FALSE otherwise.

pabd

Address of an APPBARDATA structure whose rc member receives the bounding rectangle, in screen coordinates, of the taskbar. You must specify the cbSize and hWnd members when sending this message; all other members are ignored.


ABM_NEW [New - Windows 95]
 ABM_NEW

[New - Windows 95]

fRegistered = (BOOL) SHAppBarMessage(ABM_NEW, pabd);

Registers a new appbar and specifies the message identifier that the system should use to send notification messages to the appbar. An appbar should send this message before sending any other appbar messages.

•	Returns TRUE if successful or FALSE if an error occurs or the appbar is already registered.

pabd

Address of an APPBARDATA structure that contains the new appbar's window handle and message identifier. You must specify the cbSize, hWnd, and uCallbackMessage members when sending this message; all other members are ignored.


ABM_QUERYPOS [New - Windows 95]
 ABM_QUERYPOS

[New - Windows 95]

SHAppBarMessage(ABM_QUERYPOS, pabd);

Requests a size and screen position for an appbar. The message proposes a screen edge and a bounding rectangle for the appbar. The system adjusts the bounding rectangle so that the appbar does not interfere with the Windows taskbar or any other appbars. An appbar should send this message before sending the ABM_SETPOS message.

•	Always returns TRUE.

pabd

Address of an APPBARDATA structure. The uEdge member specifies a screen edge, and the rc member contains the proposed bounding rectangle. When the SHAppBarMessage function returns, rc contains the approved bounding rectangle. You must specify the cbSize, hWnd, uEdge, and rc members when sending this message; all other members are ignored.


ABM_REMOVE [New - Windows 95]
 ABM_REMOVE

[New - Windows 95]

SHAppBarMessage(ABM_REMOVE, pabd);

Unregisters an appbar, removing it from the system's internal list. The system no longer sends notification messages to the appbar nor prevents other applications from using the screen area occupied by the appbar.

•	Always returns TRUE.

pabd

Address of an APPBARDATA structure that contains the handle of the appbar to unregister. You must specify the cbSize and hWnd members when sending this message; all other members are ignored.

This message causes the system to send the ABN_POSCHANGED notification message to all appbars.


ABM_SETAUTOHIDEBAR [New - Windows 95]
 ABM_SETAUTOHIDEBAR

[New - Windows 95]

fSuccess = (BOOL) SHAppBarMessage(ABM_SETAUTOHIDEBAR, pabd);

Registers or unregisters an autohide appbar for an edge of the screen. The system allows only one autohide appbar for each edge on a first come, first served basis.

•	Returns TRUE if successful or FALSE if an error occurs or an autohide appbar is already registered for the given edge.

pabd

Address of an APPBARDATA structure. The uEdge member specifies the screen edge. The lParam parameter is set to TRUE to register the appbar or FALSE to unregister it. You must specify the cbSize, hWnd, uEdge, and lParam members when sending this message; all other members are ignored.


ABM_SETPOS [New - Windows 95]
 ABM_SETPOS

[New - Windows 95]

SHAppBarMessage(ABM_SETPOS, pabd);

Sets the size and screen position for an appbar. The message specifies a screen edge and a bounding rectangle for the appbar. The system may adjust the bounding rectangle so that the appbar does not interfere with the Windows taskbar or any other appbars.

•	Always returns TRUE.

pabd

Address of an APPBARDATA structure. The uEdge member specifies a screen edge, and the rc member contains the bounding rectangle. When the SHAppBarMessage function returns, rc contains the approved bounding rectangle. You must specify the cbSize, hWnd, uEdge, and rc members when sending this message; all other members are ignored.

This message causes the system to send the ABN_POSCHANGED notification message to all appbars.


ABM_WINDOWPOSCHANGED [New - Windows 95]
 ABM_WINDOWPOSCHANGED

[New - Windows 95]

SHAppBarMessage(ABM_WINDOWPOSCHANGED, pabd);

Notifies the system when an appbar's position has changed. An appbar should call this message in response to the WM_WINDOWPOSCHANGED message.

•	Always returns TRUE.

pabd

Address of an APPBARDATA structure that identifies the appbar to activate. You must specify the cbSize and hWnd members when sending this message; all other members are ignored.

This message is ignored if the hWnd member of the structure pointed to by pabd identifies an autohide appbar.


 Notification Messages

The system sends notification messages to an appbar to notify it about events. The message identifier for the notification messages is an application-defined value that is set when the application sends the ABM_NEW message. The system sends the following notification messages to an appbar.


ABN_FULLSCREENAPP [New - Windows 95]
 ABN_FULLSCREENAPP

[New - Windows 95]

ABN_FULLSCREENAPP

fOpen = (BOOL) lParam;

Notifies an appbar when a full-screen application is opening or closing. When a full-screen application is opening, an appbar must drop to the bottom of the Z order. When it is closing, the appbar should restore its Z order position. This notification message is sent in the form of an application-defined message that is set by the ABM_NEW message.

•	No return value.

fOpen

Flag specifying whether a full-screen application is opening or closing. This parameter is TRUE if it is opening or FALSE if it is closing.


ABN_POSCHANGED [New - Windows 95]
 ABN_POSCHANGED

[New - Windows 95]

Notifies an appbar when an event has occurred that may effect the appbar's size and position. Events include changes in the taskbar's size, position, and visibility state as well as the addition, removal, or resizing of another appbar on the same side of the screen.

•	No return value.

An appbar should respond to this notification message by sending the ABM_QUERYPOS and ABM_SETPOS messages. If its position has changed, the appbar should call the MoveWindow function to move itself to the new position.


ABN_STATECHANGE [New - Windows 95]
 ABN_STATECHANGE

[New - Windows 95]

ABN_STATECHANGE

Notifies an appbar that the taskbar's autohide or always-on-top state has changed — that is, the user has checked or unchecked the "Always on top" or "Auto hide" check box on the taskbar's property sheet. An appbar can use this notification message to set its state to conform to that of the taskbar, if desired.

•	No return value.


ABN_WINDOWARRANGE [New - Windows 95]
 ABN_WINDOWARRANGE

[New - Windows 95]

ABN_WINDOWARRANGE

fBeginning = (BOOL) lParam;

Notifies an appbar that the user has selected the Cascade, Tile Horizontally, or Tile Vertically command from the taskbar's context menu.

•	No return value.

fBeginning

Flag specifying whether the cascade or tile operation is beginning. This parameter is TRUE if the operation is beginning and the windows have not yet been moved. It is FALSE if the operation has completed.

The system sends this notification message twice — first with lParam set to TRUE and then with lParam set to FALSE. The first notification is sent before the windows are cascaded or tiled, and the second is sent after the cascade or tile operation has occurred.


 Shell Links

A shell link is a data object that contains information used to access another object in the shell's namespace — that is, any object visible through Microsoft® Windows® Explorer. The objects that can be accessed through shell links include files, folders, disk drives, and printers. A shell link allows the user or an application to access an object from anywhere in the namespace; the user or application does not need to know the current name and location of the object.


 About Shell Links

The user creates a shell link by choosing the Create Shortcut command from an object's context menu. The system automatically creates an icon for the shell link by combining the object's icon with a small arrow (known as the system-defined link overlay icon) that appears in the lower left corner of the icon. A shell link that has an icon is called a shortcut; however, the terms shell link and shortcut are often used interchangeably. Typically, the user creates shortcuts to gain quick access to objects stored in subfolders or in shared folders on other machines. For example, a user can create a shortcut to a Microsoft Word document located in a subfolder and place the shortcut icon on the desktop. Later the user can start Word and open the document simply by double-clicking the shortcut icon. If the document is later moved or renamed, the system takes steps to update the shortcut the next time the user selects it.

Applications can also create and use shell links and shortcuts. For example, a word processing application might create a shell link to implement a list of the most recently used documents. An application creates a shell link by using the IShellLink interface to create a shell link object and uses the IPersistFile or IPersistStream interface to store the object in a file or stream. This article  describes the IShellLink interface and explains how to use the interface to create and resolve shell links from within a Windows-based application.

Because the design of shell links is based on the OLE Component Object Model (COM), you should be familiar with the basic concepts of COM and OLE programming before reading this article . For more information, see the OLE documentation included in the Microsoft Windows Software Development Kit (SDK).


 Link Resolution

If a user creates a shortcut to an object and the name or location of the object is subsequently changed, the system automatically takes steps to update, or resolve, the shortcut the next time the user selects it. However, if an application creates a shell link and stores it in a stream, the system does not automatically attempt to resolve the link. The application must resolve the link by calling the IShellLink::Resolve member function.

When a shell link is created, the system saves information about the link. When resolving a link (either automatically or if IShellLink::Resolve is called), the system first retrieves the path associated with the shell link by using a pointer to the shell link's identifier list. (For more information about the identifier list, see "Item Identifiers and Identifier Lists" later in this topic.) The system searches for the associated object in that path and, if it finds the object, resolves the link. If the system cannot find the object, it looks in the same directory for an object that has the same file creation time and attributes, but a different name. This type of search resolves a link to an object that has been renamed.

If the system still cannot find the object, it searches the subdirectories of the current directory, looking recursively though the directory tree for a match with either the same name or creation time. If the system does not find a match after that, it displays a dialog box prompting the user for a location. An application can suppress the dialog box by specifying the SLR_NO_UI value in a call to IShellLink::Resolve.


 Initialization of the Component Object Library

Before an application can create and resolve shortcuts, it must initialize the component object library by calling the CoInitialize function. Each call to CoInitialize requires a corresponding call to the CoUninitialize function, which an application should call when it terminates. The call to CoUninitialize ensures that the application does not terminate until it has received all of its pending messages.


 Location-Independent Names

The system provides location-independent names for shell links to objects stored in shared folders. If the object is stored locally, the system provides the local path and filename for the object. If the object is stored remotely, the system provides the Universal Naming Convention (UNC) network resource name for the object. Because the system provides location-independent names, a shell link can serve as a universal name for a file that can be transferred to other machines.


 Link Files

When the user creates a shortcut to an object by choosing the Create Shortcut command from the object's context menu, Windows stores the information it needs to access the object in a link file — that is, a binary file that has the .LNK filename extension. A link file contains the following information:

•	The location (path) of the object referenced by the shortcut (called the "corresponding object" in this article ).

•	The working directory of the corresponding object.

•	The list of arguments that the system passes to the corresponding object when the IContextMenu::InvokeCommand member function is activated for the shortcut.

•	The show (SW_) command used to set the initial show state of the corresponding object.

•	The location (path and index) of the shortcut's icon.

•	The shortcut's description string.

•	The hot key for the shortcut.

When a link file is deleted, the corresponding object is not affected.

If you create a shortcut to another shortcut, the system simply copies the link file rather than creating a new link file. This is important to remember if you are assuming that the shortcuts will remain independent of each other.

An application can register a filename extension as a "shortcut" file type. If a file has a filename extension that has been registered as a shortcut file type, the system automatically adds the system-defined link overlay icon (a small arrow) to the file's icon. To register a filename extension as a shortcut file type, you must add the "IsShortcut" value to the registry description of the filename extension. Note that the shell must be restarted for the overlay icon to take effect.

HKEY_CLASSES_ROOT

  .xyz    (Default) = "XYZApp"

  .

  .

  .

  XYZApp  IsShortcut = ""


 Location in the Namespace

A shortcut can exist on the desktop or anywhere in the shell's namespace. Similarly, the object that is associated with the shortcut can also exist anywhere in the shell's namespace. An application can use the IShellLink::SetPath member function to set the path and filename for the associated object, and the IShellLink::GetPath member function to retrieve the current path and filename for the object.


 Working Directory

The working directory is the directory where the corresponding object of a shortcut loads or stores files when the user does not identify a specific directory. A link file contains the name of the working directory for the corresponding object. An application can set the name of the working directory for the corresponding object by using the IShellLink::SetWorkingDirectory member function and can retrieve the name of the current working directory for the corresponding object by using the IShellLink::GetWorkingDirectory member function.


 Command-Line Arguments

A link file contains command-line arguments that the shell passes to the corresponding object when the user selects the link. An application can set the command-line arguments for a shortcut by using the IShellLink::SetArguments member function. It is useful to set command-line arguments when the corresponding application, such as a linker or compiler, takes special flags as arguments. An application can retrieve the command-line arguments from a shortcut by using the IShellLink::GetArguments member function.


 Show Command

When the user double-clicks a shortcut, the system starts the application associated with the corresponding object and sets the initial show state of the application based on the show command specified by the shortcut. The show command can be any of the SW_ values included in the description of the ShowWindow function. An application can set the show command for a shortcut by using the IShellLink::SetShowCmd member function and can retrieve the current show command by using the IShellLink::GetShowCmd member function.


 Shortcut Icon and Description

Like other shell objects, a shortcut has an icon. The user accesses the object associated with a shortcut by double-clicking the shortcut's icon. When the system creates an icon for a shortcut, it uses the bitmap of the corresponding object and adds the system-defined link overlay icon (a small arrow) to the lower left corner. An application can set the location (path and index) of a shortcut's icon by using the IShellLink::SetIconLocation member function. An application can retrieve the current location (path and index) of a shortcut's icon by using the IShellLink::GetIconLocation member function.

A shortcut also has a description, which is a brief string that appears below the shell link icon. By default, the description consists of the words "Shortcut to" followed by the filename of the object. The user can edit the description string by selecting it and entering a new string. An application can set the description string by using the IShellLink::SetDescription member function and can retrieve the current description string by using the IShellLink::GetDescription member function.


 Hot Key

A shortcut object can have a hot key associated with it. A hot key allows the user to use the shortcut by pressing a particular combination of keys. An application can set the hot key for a shortcut by using the IShellLink::SetHotkey member function and can retrieve the current hot key for a shortcut by using the IShellLink::GetHotkey member function.


 Item Identifiers and Identifier Lists

The shell uses object identifiers within the shell namespace. All of the objects that are visible in the shell (files, directories, servers, workgroups, and so on) have an identifier that is unique among the objects within the parent folder. These identifiers are called item identifiers, and they have the SHITEMID data type as defined in the SHLOBJ.H header file. An item identifier is a variable-length byte stream that contains information for identifying an object within a folder. Only the creator of an item identifier knows the content and format of the identifier. The only part of an item identifier that the shell uses is the first two bytes, which specify the size of the identifier.

Each parent folder has its own item identifier that identifies it within its own parent folder. Thus, any shell object can be uniquely identified by a list of item identifiers. A parent folder keeps a list of identifiers for the items in the folder. The list has the ITEMIDLIST data type. Item identifier lists are allocated by the shell and may be passed across shell interfaces, such as IShellFolder. It is important to remember that each identifier in an item identifier list is only meaningful within the context of the parent folder.

An application can set a shortcut's item identifier list by using the IShellLink::SetIDList member function. This function is useful when setting a shortcut to an object that is not a file, such as a printer or disk drive. An application can retrieve a shortcut's item identifier list by using the IShellLink::GetIDList member function.


 Using Shell Links

This section contains examples that demonstrate how to create and resolve shortcuts from within a Windows-based application.


 Creating a Shortcut to a File

The CreateLink function in the following example creates a shortcut. The parameters include a pointer to the name of the file to link to, a pointer to the name of the shortcut that you are creating, and a pointer to the description of the link. The description consists of the string, "Shortcut to filename," where filename is the name of the file to link to.

Because CreateLink calls the CoCreateInstance function, it is assumed that the CoInitialize function has already been called. CreateLink uses the IPersistFile interface to save the shortcut and the IShellLink interface to store the filename and description.

// CreateLink - uses the shell's IShellLink and IPersistFile interfaces

//   to create and store a shortcut to the specified object.

// Returns the result of calling the member functions of the interfaces.

// lpszPathObj - address of a buffer containing the path of the object

// lpszPathLink - address of a buffer containing the path where the

//   shell link is to be stored

// lpszDesc - address of a buffer containing the description of the

//   shell link

HRESULT CreateLink(LPCSTR lpszPathObj,

    LPSTR lpszPathLink, LPSTR lpszDesc)

{

    HRESULT hres;

    IShellLink* psl;

    // Get a pointer to the IShellLink interface.

    hres = CoCreateInstance(&CLSID_ShellLink, NULL,

        CLSCTX_INPROC_SERVER, &IID_IShellLink, &psl);

    if (SUCCEEDED(hres)) {

        IPersistFile* ppf;

        // Set the path to the shortcut target, and add the

        // description.

        psl->lpVtbl->SetPath(psl, lpszPathObj);

        psl->lpVtbl->SetDescription(psl, lpszDesc);

       // Query IShellLink for the IPersistFile interface for saving the

       // shortcut in persistent storage.

        hres = psl->lpVtbl->QueryInterface(psl, &IID_IPersistFile,

            &ppf);

        if (SUCCEEDED(hres)) {

            WORD wsz[MAX_PATH];

            // Ensure that the string is ANSI.

            MultiByteToWideChar(CP_ACP, 0, lpszPathLink, -1,

                wsz, MAX_PATH);

            // Save the link by calling IPersistFile::Save.

            hres = ppf->lpVtbl->Save(ppf, wsz, TRUE);

            ppf->lpVtbl->Release(ppf);

        }

        psl->lpVtbl->Release(psl);

    }

    return hres;

}


 Resolving A Shortcut

An application may need to access and manipulate a shortcut that was created previously. This operation is referred to as "resolving" the shortcut.

The application-defined ResolveIt function in the following example resolves a shortcut. Its parameters include a window handle, a pointer to the path of the shortcut, and the address of a buffer that receives the new path to the object. The window handle identifies the parent window for any message boxes that the shell may need to display. For example, the shell can display a message box if the link is on unshared media, if network problems occur, if the user needs to insert a floppy disk, and so on.

The ResolveIt function calls the CoCreateInstance function and assumes that the CoInitialize function has already been called. Note that ResolveIt needs to use the IPersistFile interface to store the link information. IPersistFile is implemented by the IShellLink object. The link information must be loaded before the path information is retrieved, which happens later in the example. Failing to load the link information causes the calls to the IShellLink::GetPath and IShellLink::GetDescription member functions to fail.

HRESULT ResolveIt(HWND hwnd, LPCSTR lpszLinkFile, LPSTR lpszPath)

{

    HRESULT hres;

    IShellLink* psl;

    char szGotPath[MAX_PATH];

    char szDescription[MAX_PATH];

    WIN32_FIND_DATA wfd;

    *lpszPath = 0; // assume failure

    // Get a pointer to the IShellLink interface.

    hres = CoCreateInstance(&CLSID_ShellLink, NULL,

            CLSCTX_INPROC_SERVER, &IID_IShellLink, &psl);

    if (SUCCEEDED(hres)) {

        IPersistFile* ppf;

        // Get a pointer to the IPersistFile interface.

        hres = psl->lpVtbl->QueryInterface(psl, &IID_IPersistFile,

            &ppf);

        if (SUCCEEDED(hres)) {

            WORD wsz[MAX_PATH];

            // Ensure that the string is Unicode.

            MultiByteToWideChar(CP_ACP, 0, lpszLinkFile, -1, wsz,

                MAX_PATH);

            // Load the shortcut.

            hres = ppf->lpVtbl->Load(ppf, wsz, STGM_READ);

            if (SUCCEEDED(hres)) {

                // Resolve the link.

                hres = psl->lpVtbl->Resolve(psl, hwnd, SLR_ANY_MATCH);

                if (SUCCEEDED(hres)) {

                    // Get the path to the link target.

                    hres = psl->lpVtbl->GetPath(psl, szGotPath,

                        MAX_PATH, (WIN32_FIND_DATA *)&wfd,

                        SLGP_SHORTPATH );

                    if (!SUCCEEDED(hres)

                        HandleErr(hres); // application-defined function

                    // Get the description of the target.

                    hres = psl->lpVtbl->GetDescription(psl,

                        szDescription, MAX_PATH);

                    if (!SUCCEEDED(hres))

                        HandleErr(hres);

                    lstrcpy(lpszPath, szGotPath);

                }

            }

        // Release the pointer to the IPersistFile interface.

        ppf->lpVtbl->Release(ppf);

        }

    // Release the pointer to the IShellLink interface.

    psl->lpVtbl->Release(psl);

    }

    return hres;

}


 Creating a Link to a Nonfile Object

Creating a shortcut to a nonfile object, such as a printer, is similar to creating a shortcut to a file. The main difference is that, rather than setting the path to the file, you must set the identifier list to the printer. To set the identifier list, you must call the IShellLink::SetIDList member function, specifying the address of an identifier list.

Each object within the shell's namespace has an item identifier, a variable-length byte stream containing information that identifies the object within its folder. The shell often concatenates item identifiers into null-terminated lists consisting of any number of item identifiers.

In general, if you need to set a shortcut to an item that does not have a filename, such as a printer, you will already have a pointer to the object's IShellFolder interface. The IShellFolder interface is used to create namespace extensions.

Once you have the class identifier for the IShellFolder interface, you can call the CoCreateInstance function to get the address of the interface. Then you can call the interface to enumerate the objects in the folder and retrieve the address of the item identifier for the object that you are searching for. Finally, you can use the address in a call to the IShellLink::SetIDList member function to create a shortcut to the object.


 Reference

The following interface is used with shell links.


 Interfaces and Member Functions


IShellLink [New - Windows 95]
 IShellLink

[New - Windows 95]

Designates an interface that allows an application to create and resolve shell links. The IShellLink interface has the following member functions.

GetArguments	Retrieves the command-line arguments associated with a shell link object.
GetDescription	Retrieves the description string for a shell link object.
GetHotkey	Retrieves the hot key for a shell link object.
GetIconLocation	Retrieves the location (path and index) of the icon for a shell link object.
GetIDList	Retrieves the list of item identifiers for a shell link object.
GetPath	Retrieves the path and filename of a shell link object.
GetShowCmd	Retrieves the show (SW_) command for a shell link object.
GetWorkingDirectory	Retrieves the name of the working directory for a shell link object.
Resolve	Resolves a shell link by searching for the shell link object and updating the shell link path and its list of identifiers, if necessary.
SetArguments	Sets the command-line arguments associated with a shell link object.
SetDescription	Sets the description string for a shell link object.
SetHotkey	Sets the hot key for a shell link object.
SetIconLocation	Sets the location (path and index) of the icon for a shell link object.
SetIDList	Sets the list of item identifiers for a shell link object.
SetPath	Sets the path and filename of a shell link object.
SetRelativePath	Sets the relative path for a shell link object.
SetShowCmd	Sets the show (SW_) command for a shell link object.
SetWorkingDirectory	Sets the name of the working directory for a shell link object.
Like all OLE interfaces, IShellLink also includes the QueryInterface, AddRef, and Release member functions.


IShellLink::GetArguments [New - Windows 95]
 IShellLink::GetArguments

[New - Windows 95]

HRESULT GetArguments(ISHELLLINK FAR * pShlLnk,

    LPSTR pszArgs, int cchMaxPath);

Retrieves the command-line arguments associated with a shell link object.

•	Returns the NOERROR value if successful or an OLE-defined error value otherwise.

pShlLnk

Address of the IShellLink interface. In C++, this parameter is implicit.

pszArgs

Address of a buffer that receives the command-line arguments.

cchMaxPath

Maximum number of characters to copy to the buffer pointed to by pszArgs.


IShellLink::GetDescription [New - Windows 95]
 IShellLink::GetDescription

[New - Windows 95]

RESULT GetDescription(ISHELLLINK FAR * pShlLnk,

    LPSTR pszName, int cchMaxName);

Retrieves the description string for a shell link object.

•	Returns the NOERROR value if successful or an OLE-defined error value otherwise.

pShlLnk

Address of the IShellLink interface. In C++, this parameter is implicit.

pszName

Address of a buffer that receives the description string.

cchMaxName

Maximum number of characters to copy to the buffer pointed to by pszName.


IShellLink::GetHotkey [New - Windows 95]
 IShellLink::GetHotkey

[New - Windows 95]

HRESULT GetHotkey(ISHELLLINK FAR * pShlLnk,

    WORD *pwHotkey);

Retrieves the hot key for a shell link object.

•	Returns the NOERROR value if successful or an OLE-defined error value otherwise.

pShlLnk

Address of the IShellLink interface. In C++, this parameter is implicit.

pwHotkey

Address of the hot key. The virtual-key code is in the low-order byte, and the modifier flags are in the high-order byte. The modifier flags can be a combination of these values:

HOTKEYF_ALT	ALT key
HOTKEYF_CONTROL	CTRL key
HOTKEYF_EXT	Extended key
HOTKEYF_SHIFT	SHIFT key


IShellLink::GetIconLocation [New - Windows 95]
 IShellLink::GetIconLocation

[New - Windows 95]

HRESULT GetIconLocation(ISHELLLINK FAR * pShlLnk,

    LPSTR pszIconPath, int cchIconPath, int *piIcon);

Retrieves the location (path and index) of the icon for a shell link object.

•	Returns the NOERROR value if successful or an OLE-defined error value otherwise.

pShlLnk

Address of the IShellLink interface. In C++, this parameter is implicit.

pszIconPath

Address of a buffer that receives the path of the file containing the icon.

cchIconPath

Maximum number of characters to copy to the buffer pointed to by pszIconPath.

piIcon

Address of a value that receives the index of the icon.


IShellLink::GetIDList [New - Windows 95]
 IShellLink::GetIDList

[New - Windows 95]

HRESULT GetIDList(ISHELLLINK FAR * pShlLnk,

    LPITEMIDLIST * ppidl);

Retrieves the list of item identifiers for a shell link object.

•	Returns the NOERROR value if successful or an OLE-defined error value otherwise.

pShlLnk

Address of the IShellLink interface. In C++, this parameter is implicit.

ppidl

Address of a pointer to a list of item identifiers.


IShellLink::GetPath [New - Windows 95]
 IShellLink::GetPath

[New - Windows 95]

HRESULT GetPath(IShellLink FAR * pShlLnk,

    LPSTR pszFile, int cchMaxPath, WIN32_FIND_DATA *pfd, DWORD fFlags);

Retrieves the path and filename of a shell link object.

•	Returns the NOERROR value if successful or an OLE-defined error value otherwise.

pShlLnk

Address of the IShellLink interface. In C++, this parameter is implicit.

pszFile

Address of a buffer that receives the path and filename of the shell link object.

cchMaxPath

Maximum number of bytes to copy to the buffer pointed to by pszFile.

pfd

Address of a WIN32_FIND_DATA structure that contains information about the shell link object.

fFlags

Flags that specify the type of path information to retrieve. This parameter can be a combination of these values:

SLGP_SHORTPATH	Retrieves the standard short (8.3) filename.
SLGP_UNCPRIORITY	Retrieves the Universal Naming Convention (UNC) path for the file.


IShellLink::GetShowCmd [New - Windows 95]
 IShellLink::GetShowCmd

[New - Windows 95]

HRESULT GetShowCmd(ISHELLLINK FAR * pShlLnk,

    int *piShowCmd);

Retrieves the show command for a shell link object.

•	Returns the NOERROR value if successful or an OLE-defined error value otherwise.

pShlLnk

Address of the IShellLink interface. In C++, this parameter is implicit.

piShowCmd

Address of the show command. For a list of show commands, see the description of the ShowWindow function.


IShellLink::GetWorkingDirectory [New - Windows 95]
 IShellLink::GetWorkingDirectory

[New - Windows 95]

HRESULT GetWorkingDirectory(ISHELLLINK FAR * pShlLnk,

    LPSTR pszDir, int cchMaxPath);

Retrieves the name of the working directory for a shell link object.

•	Returns the NOERROR value if successful or an OLE-defined error value otherwise.

pShlLnk

Address of the IShellLink interface. In C++, this parameter is implicit.

pszDir

Address of a buffer that receives the name of the working directory.

cchMaxPath

Maximum number of characters to copy to the buffer pointed to by pszDir. The name of the working directory is truncated if it is longer than the maximum specified by this parameter.


IShellLink::Resolve [New - Windows 95]
 IShellLink::Resolve

[New - Windows 95]

HRESULT Resolve(ISHELLLINK FAR * pShlLnk, HWND hwnd,

    DWORD fFlags);

Resolves a shell link. The system searches for the shell link object and, if necessary, updates the shell link path and its list of identifiers.

•	Returns the NOERROR value if successful or an OLE-defined error value otherwise.

pShlLnk

Address of the IShellLink interface. In C++, this parameter is implicit.

hwnd

Handle of a window that the shell uses as the parent window for a dialog box. The shell displays the dialog box if it needs to prompt the user for more information while resolving a shell link.

fFlags

Action flags. This parameter can be a combination of these values:

SLR_ANY_MATCH	Resolves the link, displaying a dialog box if the system needs information from the user.
SLR_NO_UI	Prevents the shell from displaying a dialog box if it cannot resolve the shell link. When this value is specified, the high-order word of this parameter specifies a time-out duration, in milliseconds. The function returns if the link cannot be resolved within the time-out duration. If the high-order word is set to zero, the time-out duration defaults to 3000 milliseconds (3 seconds).
SLR_UPDATE	Directs the shell to update the path to the link and the list of identifiers if the link object has been changed. If this value is used, it is not necessary to call the IPersistFile::IsDirty member function to determine whether the link object has changed.
When this member function is called, the system retrieves the path associated with the current link object and searches for the object in that path. If the system finds the object, it resolves the link. If the system cannot find the object, it looks in the same directory for an object with the same file creation time and attributes, but with a different name. This type of search resolves a link to an object that has been renamed.

If the system still cannot find the link object, it searches the subdirectories of the current directory. It does a recursive search of the directory tree looking for a match with either the same name or creation time. If it does not find a match after that, the shell displays a dialog box prompting the user for a location. An application can suppress the dialog box by specifying the SLR_NO_UI value in a call to this member function.


IShellLink::SetArguments [New - Windows 95]
 IShellLink::SetArguments

[New - Windows 95]

HRESULT SetArguments(ISHELLLINK FAR * pShlLnk,

    LPCSTR pszArgs);

Sets the command-line arguments for a shell link object.

•	Returns the NOERROR value if successful or an OLE-defined error value otherwise.

pShlLnk

Address of the IShellLink interface. In C++, this parameter is implicit.

pszArgs

Address of a buffer that contains the new command-line arguments.

This member function is useful when creating a link to an application that takes special flags as arguments, such as a compiler.


IShellLink::SetDescription [New - Windows 95]
 IShellLink::SetDescription

[New - Windows 95]

HRESULT SetDescription(ISHELLLINK FAR * pShlLnk,

    LPCSTR pszName);

Sets the description for a shell link object. The description can be any application-defined string.

•	Returns the NOERROR value if successful or an OLE-defined error value otherwise.

pShlLnk

Address of the IShellLink interface. In C++, this parameter is implicit.

pszName

Address of a buffer containing the new description string.


IShellLink::SetHotkey [New - Windows 95]
 IShellLink::SetHotkey

[New - Windows 95]

HRESULT SetHotkey(ISHELLLINK FAR * pShlLnk,

    WORD wHotkey);

Sets a hot key for a shell link object.

•	Returns the NOERROR value if successful or an OLE-defined error value otherwise.

pShlLnk

Address of the IShellLink interface. In C++, this parameter is implicit.

wHotkey

Hot key. The virtual-key code is in the low-order byte, and the modifier flags are in the high-order byte. The modifier flags can be a combination of the values specified in the description of the IShellLink::GetHotkey member function.

Setting a hot key allows the user to activate the object by pressing a particular combination of keys.


IShellLink::SetIconLocation [New - Windows 95]
 IShellLink::SetIconLocation

[New - Windows 95]

HRESULT SetIconLocation(ISHELLLINK FAR * pShlLnk,

    LPCSTR pszIconPath, int iIcon);

Sets the location (path and index) of the icon for a shell link object.

•	Returns the NOERROR value if successful or an OLE-defined error value otherwise.

pShlLnk

Address of the IShellLink interface. In C++, this parameter is implicit.

pszIconPath

Address of a buffer that contains the path of the file containing the icon.

iIcon

Index of the icon.


IShellLink::SetIDList [New - Windows 95]
 IShellLink::SetIDList

[New - Windows 95]

HRESULT SetIDList(ISHELLLINK FAR * pShlLnk,

    LPCITEMIDLIST pidl);

Sets the list of item identifiers for a shell link object.

•	Returns the NOERROR value if successful or an OLE-defined error value otherwise.

pShlLnk

Address of the IShellLink interface. In C++, this parameter is implicit.

pidl

Address of a list of item identifiers.

This member function is useful when an application needs to set a shell link to an object that is not a file, such as a Control Panel application, a printer, or another computer.


IShellLink::SetPath [New - Windows 95]
 IShellLink::SetPath

[New - Windows 95]

HRESULT SetPath(ISHELLLINK FAR * pShlLnk,

    LPCSTR pszFile);

Sets the path and filename of a shell link object.

•	Returns the NOERROR value if successful or an OLE-defined error value otherwise.

pShlLnk

Address of the IShellLink interface. In C++, this parameter is implicit.

pszFile

Address of a buffer that contains the new path.


IShellLink::SetRelativePath [New - Windows 95]
 IShellLink::SetRelativePath

[New - Windows 95]

HRESULT SetRelativePath(ISHELLLINK FAR * pShlLnk,

    LPCSTR pszPathRel, DWORD dwReserved);

Sets the relative path to the shell link object.

•	Returns the NOERROR value if successful or an OLE-defined error value otherwise.

pShlLnk

Address of the IShellLink interface. In C++, this parameter is implicit.

pszPathRel

Address of a buffer that contains the new relative path.

dwReserved

Reserved; must be zero.

This function sets the relative path for a shortcut that is saved in a stream using the IPersistStream interface, or to override the default relative path tracking for a shortcut. When a shortcut is saved in a file, the system keeps track of the relative path between the file in which the shortcut is saved and the target of the shortcut (if there is one). If the link is broken, the system uses SetRelativePath to attempt to restore the link. For a shortcut is saved in a stream instead of a file, SetRelativePath allows an application to set the link between the shortcut and its target.


IShellLink::SetShowCmd [New - Windows 95]
 IShellLink::SetShowCmd

[New - Windows 95]

HRESULT SetShowCmd(ISHELLLINK FAR * pShlLnk,

    int iShowCmd);

Sets the show command for a shell link object. The show command sets the initial show state of the window.

•	Returns the NOERROR value if successful or an OLE-defined error value otherwise.

pShlLnk

Address of the IShellLink interface. In C++, this parameter is implicit.

iShowCmd

Show command. For a list of the show commands, see the description of the ShowWindow function.


IShellLink::SetWorkingDirectory [New - Windows 95]
 IShellLink::SetWorkingDirectory

[New - Windows 95]

HRESULT SetWorkingDirectory(ISHELLLINK FAR * pShlLnk,

    LPCSTR pszDir);

Sets the name of the working directory for a shell link object.

•	Returns the NOERROR value if successful or an OLE-defined error value otherwise.

pShlLnk

Address of the IShellLink interface. In C++, this parameter is implicit.

pszDir

Address of a buffer that contains the name of the new working directory.

The working directory must be set only if the object requires it to be set. For example, if an application creates a shell link to a Microsoft Word document that uses a template that resides in a different directory, the application would use this method to set the working directory.


 Taskbar Notification Area

The Microsoft® Windows® taskbar includes a notification area where an application can put an icon to indicate the status of an operation or to notify the user about an event. For example, an application might put a printer icon in the taskbar to show that a print job is under way. The notification area is at the right end of the taskbar (if the taskbar has a horizontal orientation) or at the bottom (if the taskbar has a vertical orientation).


 About the Taskbar Notification Area

An icon in the taskbar can have a tooltip control associated with it. In addition, the system can send notification messages to the application whenever a mouse event occurs in the bounding rectangle of the icon.


 Sending Messages

An application sends messages to add, modify, or delete taskbar icons. To send a message, an application must use the Shell_NotifyIcon function. The function parameters include the identifier of the message to send, such as NIM_ADD, and the address of an NOTIFYICONDATA structure. The structure members contain information that the system needs to process the given message.

To add an icon to the taskbar's notification area, send the NIM_ADD message. The NOTIFYICONDATA structure that accompanies the message specifies the handle of the icon, the identifier of the icon, and, if desired, the tooltip text for the icon. If the taskbar has the Show Clock option selected, the system places the new icon to the immediate left of the clock. Otherwise, the icon appears on the right side or at the bottom of the toolbar. Any existing icons are shifted to the left to make room for the new icon.

An application can delete an icon from the taskbar notification area by sending the NIM_DELETE message. It can send the NIM_MODIFY message to modify the information that the system maintains for a taskbar icon, including its icon handle, tooltip text, and callback message identifier.


 Receiving Callback Messages

Each taskbar icon can have an application-defined callback message associated with it. If an icon has a callback message, the system will send the message to the application whenever a mouse event occurs within the icon. In this way, the system can notify an application whenever the user clicks or double-clicks the icon, or moves the mouse cursor into the icon's bounding rectangle.

An application defines an icon's callback message when it adds the icon to the taskbar. The uCallbackMessage member of the NOTIFYICONDATA structure included with the NIM_ADD message specifies the identifier of the callback message. When a mouse event occurs, the system sends the callback message to the window identified by the hWnd member. The message's lParam parameter is the identifier of the mouse message that the system generated as a result of the mouse event. For example, when the mouse cursor moves into a taskbar icon, the lParam parameter of the resulting callback message contains the WM_MOUSEMOVE identifier. The wParam parameter contains the identifier of the taskbar icon in which the mouse event occurred.


 Using the Taskbar Notification Area

This section includes examples that demonstrate how to add icons to the taskbar notification area and how to process callback messages for taskbar icons.


 Adding and Deleting Icons

You add an icon to the taskbar notification area by filling a NOTIFYICONDATA structure and then sending the structure through the NIM_ADD message. The structure members must specify the handle of the window that is adding the icon and the icon identifier and icon handle. You can also specify tooltip text for the icon, and, if you need to receive mouse messages for the icon, the identifier of the callback message that the system should use to send the message to your window.

The function in the following example demonstrates how to add an icon to the taskbar.

// MyTaskBarAddIcon - adds an icon to the taskbar notification area.

// Returns TRUE if successful or FALSE otherwise.

// hwnd - handle of the window to receive callback messages

// uID - identifier of the icon

// hicon - handle of the icon to add

// lpszTip - tooltip text

BOOL MyTaskBarAddIcon(HWND hwnd, UINT uID, HICON hicon, LPSTR lpszTip)

{

    BOOL res;

    NOTIFYICONDATA tnid;

    tnid.cbSize = sizeof(NOTIFYICONDATA);

    tnid.hWnd = hwnd;

    tnid.uID = uID;

    tnid.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;

    tnid.uCallbackMessage = MYWM_NOTIFYICON;

    tnid.hIcon = hicon;

    if (lpszTip)

        lstrcpyn(tnid.szTip, lpszTip, sizeof(tnid.szTip));

    else

        tnid.szTip[0] = '\0';

    res = Shell_NotifyIcon(NIM_ADD, &tnid);

    if (hicon)

        DestroyIcon(hicon);

    return res;

}

To delete an icon from the taskbar notification area, you must fill a NOTIFYICONDATA structure and send it to the system in the context of an NIM_DELETE message. When deleting a taskbar icon, you need to specify only the cbSize, hWnd, and uID members, as the following example shows.

// MyTaskBarDeleteIcon - deletes an icon from the taskbar

//     notification area.

// Returns TRUE if successful or FALSE otherwise.

// hwnd - handle of the window that added the icon

// uID - identifier of the icon to delete

BOOL MyTaskBarDeleteIcon(HWND hwnd, UINT uID)

{

BOOL res;

NOTIFYICONDATA tnid;

tnid.cbSize = sizeof(NOTIFYICONDATA);

tnid.hWnd = hwnd;

tnid.uID = uID;

res = Shell_NotifyIcon(NIM_DELETE, &tnid);

return res;

}


 Receiving Mouse Events

If you specify a callback message for a taskbar icon, the system sends the message to your application whenever a mouse event occurs in the icon's bounding rectangle. The wParam parameter specifies the identifier of the taskbar icon, and the lParam parameter specifies the mouse message that the system generated as a result of the mouse event.

The function in the following example is from an application that adds both a battery icon and a printer icon to the taskbar. The application calls the function when it receives a callback message. The function determines if the user has clicked one of the icons and, if a click has occurred, calls an application-defined function to display status information.

// On_MYWM_NOTIFYICON - processes callback messages for taskbar icons.

// wParam - first message parameter of the callback message

// lParam - second message parameter of the callback message

void On_MYWM_NOTIFYICON(WPARAM wParam, LPARAM lParam)

{

    UINT uID;

    UINT uMouseMsg;

    uID = (UINT) wParam;

    uMouseMsg = (UINT) lParam;

    if (uMouseMsg == WM_LBUTTONDOWN) {

        switch (uID) {

            case IDI_MYBATTERYICON:

                // The user clicked the battery icon. Display the

                // battery status.

                ShowBatteryStatus();

                break;

            case IDI_MYPRINTERICON:

                // The user clicked the printer icon. Display the

                // status of the print job.

                ShowJobStatus();

                break;

            default:

                break;

        }

     }

     return;

 }


 Reference

The following function, structure, and messages are associated with the taskbar notification area.


 Function and Structure

The following function and structure are used with the taskbar notification area.


Shell_NotifyIcon [New - Windows 95]
 Shell_NotifyIcon

[New - Windows 95]

WINSHELLAPI BOOL WINAPI Shell_NotifyIcon(DWORD dwMessage,

    PNOTIFYICONDATA pnid);

Sends a message to the system to add, modify, or delete a taskbar icon.

•	Returns TRUE if successful or FALSE otherwise.

dwMessage

Identifier of the message to send. This parameter can be one of these values:

NIM_ADD	Adds an icon to the taskbar notification area.
NIM_DELETE	Deletes an icon from the taskbar notification area.
NIM_MODIFY	Modifies an icon in the taskbar notification area.
pnid

Address of an NOTIFYICONDATA structure. The content of the structure depends on the value of dwMessage.


NOTIFYICONDATA [New - Windows 95]
 NOTIFYICONDATA

[New - Windows 95]

typedef struct _NOTIFYICONDATA { // nid

    DWORD cbSize;          // sizeof(NOTIFYICONDATA)

    HWND hWnd;             // see below

    UINT uID;              // see below

    UINT uFlags;           // see below

    UINT uCallbackMessage; // see below

    HICON hIcon;           // see below

    char szTip[64];        // see below

} NOTIFYICONDATA, *PNOTIFYICONDATA;

Contains information that the system needs to process taskbar notification area messages.

hWnd

Handle of the window that receives notification messages associated with an icon in the taskbar notification area.

uID

Application-defined identifier of the taskbar icon.

uFlags

Array of flags that indicate which of the other structure members contain valid data. This member can be a combination of these values:

NIF_ICON	The hIcon member is valid.
NIF_MESSAGE	The uCallbackMessage member is valid.
NIF_TIP	The szTip member is valid.
uCallbackMessage

Application-defined message identifier. The system uses the specified identifier for notification messages that it sends to the window identified by hWnd whenever a mouse event occurs in the bounding rectangle of the icon.

hIcon

Handle of the taskbar icon to add, modify, or delete.

szTip

Tooltip text to display for the taskbar icon.


 Messages

An application sends messages to add, modify, or delete taskbar icons. To send a message, an application uses the Shell_NotifyIcon function. The following messages are associated with taskbar icons.


NIM_ADD [New - Windows 95]
 NIM_ADD

[New - Windows 95]

fAdded = Shell_NotifyIcon(NIM_ADD, pnid);

Adds an icon to the taskbar notification area.

•	Returns TRUE if successful or FALSE otherwise.

pnid

Address of an NOTIFYICONDATA structure that contains information about the icon to add.


NIM_DELETE [New - Windows 95]
 NIM_DELETE

[New - Windows 95]

fDeleted = Shell_NotifyIcon(NIM_DELETE, pnid);

Deletes an icon from the taskbar notification area.

•	Returns TRUE if successful or FALSE otherwise.

pnid

Address of an NOTIFYICONDATA structure that contains information about the taskbar icon to delete.


NIM_MODIFY [New - Windows 95]
 NIM_MODIFY

[New - Windows 95]

fModified = Shell_NotifyIcon(NIM_MODIFY, pnid);

Changes the icon, tooltip text, or notification message identifier for an icon in the taskbar notification area.

•	Returns TRUE if successful or FALSE otherwise.

pnid

Address of an NOTIFYICONDATA structure that contains the information used to change the icon, tooltip text, or notification message identifier for the taskbar icon.


 File Viewers

A file viewer is an OLE component object (not a compound document object) implemented inside a 32-bit in-process server dynamic-link library (DLL), which is associated, in turn, with the file viewer's class identifier. A file viewer provides the user interface for viewing a file. Menu items, a toolbar, and a status bar are standard parts of the file viewer interface. A file viewer can optionally add other functionality for further shell integration.


 About File Viewers

The Microsoft® Windows® 95 shell allows the user to browse the information in the file system and on the network. The Quick View feature of the shell allows the user to quickly view the contents of a file without having to run the full application that created it and without even the presence of the application. To view the file contents, the user selects a file and chooses the Quick View command from the context menu of the selection (or from the File menu). The following illustration shows the context menu.

In response to the user choosing the Quick View command, the shell activates a file-specific viewer for the selected file. The shell uses the extension of the file to determine which viewer to activate. A file viewer associates itself with file classes and filename extensions in the system registry.

A file viewer is an OLE component object (not a compound document object) implemented inside a 32-bit in-process server dynamic-link library (DLL), which is associated, in turn, with the file viewer's class identifier. A file viewer provides the user interface for viewing a file. Menu items, a toolbar, and a status bar are standard parts of the file viewer interface. A file viewer can optionally add other functionality for further shell integration.

A file viewer object, which is separate from the class factory object in the in-process server, uses the standard OLE IPersistFile interface as well as the IFileViewer interface described later in this article. The shell does not interact directly with file viewer objects. Instead, the shell starts an instance of a small program called Quick View (QUIKVIEW.EXE) for each file to be viewed. Each instance of Quick View defines a process for a file viewer, giving the viewer its own message queue. Although Quick View is a Windows executable file, it is not a complete Windows-based application. It associates a path with a file viewer, creates an instance of the file viewer object, and instructs the file viewer to load and display the file.

Because a file viewer is an OLE component object, additional interfaces and functionality can be added in future versions of Windows to support new features. For example, a file viewer can act as an OLE container application and can perform in-place activation of embedded objects inside the file being viewed. A file viewer can let the user make a selection in a document and copy the selection to the clipboard or use the selection in a drag and drop operation. However, such functionality is entirely up to the developer of the file viewer. This article describes the basic functionality that a file viewer must provide and discusses user interface guidelines that all developers of file viewers should follow.


 Adding or Replacing File Viewers

The File Viewer interfaces allow you to add file viewers to Windows 95. For example, you may need to add a file viewer that supports a new file format or provides additional functionality. To understand how to add a file viewer to Windows 95, it is important first to understand how the default file viewers work.

The shell calls the Quick View program to display a file. Quick View manages the file viewing process and presents error messages for error conditions returned by the display engines — a collection of DLLs that draws the viewer window and displays the file. Windows 95 includes display engines for word processing documents, spreadsheets, databases, vector graphics, and raster graphics. File parser DLLs are associated with a particular display engine and are specific to a type or class of files. For example, spreadsheet and database files are associated with the spreadsheet or database display engine. These DLLs are typically between 25K and 75K in size and do all the low-level parsing of the files to be viewed.

There are two methods to add file viewing functionality to Windows 95. First, a particular file parser DLL may be added to the system. The advantage of this method is that file parsers are relatively straightforward to write and debug. The disadvantage is that the limitations built into the default display engines (such as no printing and no cut, copy, and paste operations) remain even when a new file parsing DLL is used. For more information about the interface between the file parsers and the display engines, see "File Parsers."

The second method of including file viewing functionality in Windows 95 is to add one or more DLLs that work directly with Quick View. The interaction between QUIKVIEW.EXE and the display engines is the subject of this article. An example of one of these file viewing systems for ASCII files is found in the Samples subdirectory of the Microsoft® Win32® Software Development Kit (SDK). The main advantage of this method is that the code you write can support whatever file viewing functionality you wish to provide. This may be particularly important if your file format does not display well with one of the four default display engines. For example, an accounting package might have this problem. The main disadvantage of this method is that writing for the Quick View interface requires more development and testing effort.

The remainder of this article discusses the interaction between QUIKVIEW.EXE and the display engines. The discussion is split into three sections. The first section describes the entries in the registry necessary to support associations between a pathname and a file viewer. The second section describes how the shell starts Quick View and outlines the steps Quick View performs to locate an appropriate file viewer and activate it. The last section describes the structure and implementation of a file viewer OLE component, including the recommended user interface features.

The file viewing technology used by the Quick View feature in Windows 95 was developed jointly by Microsoft Corporation and Systems Compatibility Corporation.


 File Viewer Registration

During installation, a file viewer should ensure that entries exist in the registry that accurately associate a file with the class identifier of the file viewer's in-process server DLL. The file viewer's installation program may merge the contents of a registration (.REG) file into the registry. A file viewer can register itself for more than one file type if it can handle multiple file formats. If a file type has more than one registered file viewer, the shell activates the most recently registered viewer for the file type when the user chooses the Quick View command.


 Determining File Types

The Quick View program attempts a simple association using the filename extension. If there is no filename extension or if there are no file viewers registered for the filename extension, Quick View calls each registered file viewer to see if any of them recognize the file. If more than one file viewer is registered for the same filename extension, Quick View calls each file viewer starting with the last one in the list. If Quick View cannot find a file viewer that can read the file, the Quick View operation fails and Quick View displays the following message.

There are no viewers registered for this type of file. Would you like to try the default viewer?

The default viewer displays a hexadecimal dump using the word processing engine.

For more information, see "Quick View Program" later in this topic.


 Structure of Registry Entries

The following registry structure is required for Quick View to associate a class identifier or filename extension with the class identifier of a file viewer.

HKEY_CLASSES_ROOT

    \QuickView

        \<extension> = <human-readable document type>

            \{<CLSID>} = <human-readable viewer name>

            \{<CLSID>} = <human-readable viewer name>

            \{<CLSID>} = <human-readable viewer name>

        ...[More extension entries for additional file types]

            ...

    \CLSID

        \{<CLSID>} = <human-readable viewer name>

            \InprocServer32 = <full path to file viewer DLL>

                            = ThreadingModel = "Apartment"

        ...[More class IDs for file viewers and other object servers]

A description of the registry entries follows.

Entry	Description
HKEY_CLASSES_ROOT	Root of the registry.
QuickView	Top-level key under which associations are stored.
CLSID	16-byte OLE class identifier spelled out in hexadecimal digits in the form of 12345678-1234-1234-1234-1234567890AB with the hyphens included. All class identifiers are surrounded by curly braces when stored in the registry.
human-readable document type	String describing the file type associated with the class identifier or filename extension that can be displayed to the user. A file viewer can change the type when it is installed so that the name always reflects the preferred viewer. For example, this string might be "Windows Write Document."
human-readable viewer name	String that describes the vendor of the file viewer, as it might be displayed in an About box, such as "Company ABC Write Document Viewer."
<extension>	Three-character filename extension with the period, as is consistent with the standard 8.3 filename format — for example, .WRI.
CLSID and InprocServer32 are standard OLE (32-bit) subkey names. The "ThreadingModel = Apartment" entry is required for file viewers. The apartment threading model, which is new for OLE in Windows 95 and Microsoft® Windows NT™ version 3.51, allows the OleInitialize and CoInitialize functions to be called from multiple threads.

The QuickView key can have any number of filename extension subkeys, each representing a registered file type. Each filename extension subkey can have one or more class identifier subkeys, each representing a registered file viewer object. The most recently registered file viewer appears first in the list of class identifier subkeys, and it is the first one found when Quick View enumerates the registered file viewers.

Note  The file viewer class identifier should always differ from the file type class identifier because the application that created the file may already be using the class identifier to identify the application as a compound document server.

Each class identifier stored under the filename extension subkeys must correspond to an entry of the same class identifier stored under the top-level key called CLSID. This is the standard location for storing information for OLE object servers. For file viewers, there must be an InprocServer32 subkey under the file viewer's class identifier key. The value of the InprocServer32 subkey is the full path to the file viewer DLL. You should store the full path and not depend on the DLL being in the path of the Windows 95 environment. InprocServer32 is a standard OLE subkey where the path to a component object server is stored. Using this subkey allows the Quick View program to use standard OLE member functions to access and create objects from file viewer servers.


 Registering a File Viewer

This section shows how to register a hypothetical file viewer for "AcmeWord Document" files with the .AWD filename extension. The file viewer is implemented in an in-process server DLL called ACMEWRDV.DLL. The DLL has this class identifier: 00021116-0000-0000-C000-000000000046. The program that installs the file viewer creates the following registry entries.

HKEY_CLASSES_ROOT

    \QuickView

        \.AWD = AcmeWord Document

            \{00021117-0000-0000-C000-000000000046} = AcmeWord Document
                                                      Viewer

    \CLSID

        \{00021117-0000-0000-C000-000000000046} = AcmeWord Document
                                                  Viewer

            \InprocServer32 = c:\acmeword\acmewrdv.dll

                            = ThreadingModel = "Apartment"

The .REG file, which is an ASCII text file, contains these entries. (Note that wrapped lines are indented on the second line.)

HKEY_CLASSES_ROOT\QuickView\.AWD = AcmeWord Document

HKEY_CLASSES_ROOT\QuickView\.AWD \{00021117-0000-0000-C000-
    000000000046} = AcmeWord Document Viewer

HKEY_CLASSES_ROOT\CLSID\{00021117-0000-0000-C000-000000000046} =
    AcmeWord Document Viewer

HKEY_CLASSES_ROOT\CLSID\{00021117-0000-0000-C000-000000000046}
    \InprocServer32 = c:\acmeword\acmewrdv.dll

                    = ThreadingModel = "Apartment"

The Quick View program uses these registry entries to associate a path with the class identifier of a file viewer's in-process server DLL.


 Quick View Program

The Quick View program (QUIKVIEW.EXE) acts on behalf of the shell to locate and activate a file viewer for a given path. There is a one to one correspondence between each running instance of Quick View and each file being displayed in a file viewer. Each instance of Quick View defines a process for a file viewer, giving the file viewer its own message queue. Quick View turns over execution of the process to the file viewer until the file viewer shuts down.


 Quick View Execution and Error Conditions

The lifetime of each instance of the Quick View program consists of the following steps:

1.	When the user chooses the Quick View or Print command, the shell starts an instance of QUIKVIEW.EXE for each selected file (by using the Win32 CreateProcess or WinExec function). The shell may specify a show command, and Quick View passes the command to the file viewer. The command-line argument that the shell passes to Quick View has the following options.

Option	Meaning
-f:pathname	Path of the file to view or print. Universal Naming Convention (UNC) filenames are allowed. If this option is not specified, Quick View terminates without displaying any messages.
-v	File to be opened for viewing in the file viewer. If this option is specified, Quick View ignores all of the options described below. This is the default option in the absence of both -v and -p.
-d	Quick View and the file viewer to suppress all user interface (UI) elements if -p is also specified. Quick View suppresses any error messages, and the file viewer should not display any dialog boxes for printing. Quick View ignores this option in the absence of -p.
-p	File to be opened for printing. If -v is also present, Quick View ignores this option.
-&:pathname	Printer driver to use to print the file. Quick View ignores this option in the absence of -p. If -p is present but -& is not, Quick View instructs the file viewer to use the default printer driver.
2.	Quick View starts and checks for a path on the command line. If there is no path, the user has attempted to start Quick View by itself and the program immediately terminates without displaying any messages.

3.	Quick View parses the filename extension from the path given in the -f option. If no filename extension is given, Quick View proceeds to stage E1 (error condition 1). Otherwise, Quick View uses the following procedure to find a file viewer class identifier associated with the given filename extension.

a.	Quick View attempts to open the HKEY_CLASS_ROOT\QuickView\extension key, where extension is parsed from the path.

i.	If the filename extension maps to a type such as HKEY_CLASS_ROOT\extension = typename and there is a registry entry with the form HKEY_CLASS_ROOT\typename\QuickView = *, Quick View looks for file viewer class identifiers under HKEY_CLASS_ROOT\QuickView\*. If a key with the HKEY_CLASS_ROOT\*\QuickView = * form exists, the system attempts to use all the viewers listed under the "*" section.
ii.	Otherwise, Quick View begins enumerating the file viewer class identifiers under the HKEY_CLASS_ROOT\QuickView\extension key. If the enumeration fails (that is, there is nothing in the registry to enumerate), Quick View closes the key and proceeds to stage E2. Otherwise, Quick View reads the first file viewer class identifier in the enumeration and proceeds to step 4.
b.	If an error occurs in step 4, the enumeration continues until all file viewer class identifiers have been tried. If no file viewer is activated, Quick View closes the key from (a) and proceeds to stage E2.

4.	Given a class identifier of a file viewer DLL, Quick View attempts to create an instance of a file viewer object of the given class by using the following procedure.

a.	Quick View calls a function to create an instance of a file viewer object, specifying parameters that include the class identifier and the IID_IPersistFile interface identifier. This instructs OLE to load the DLL listed under the class identifier's InprocServer32 subkey, obtain an instance of the object from the DLL, and return an IPersistFile interface pointer to the object. If the instance cannot be created because of lack of memory, Quick View proceeds to stage E4. If it fails for some other reason, Quick View proceeds to stage E3. (Note that, because DLL objects are involved, any call to QueryInterface will not fail with REGDB_IID_NOTREG, which typically signals a corrupted registry. That error is generated only when LRPC proxies and stubs are involved.)

b.	Given the IPersistFile interface pointer pIPersistFile, Quick View calls the Load member function of the IPersistFile interface, specifying the path of the file and the STGM_READ and STGM_SHARE_DENY_NONE values, which instruct the object to open the file for read access. If Load fails, Quick View calls the Release member function of pIPersistFile and proceeds to stage E4 if the error is due to a lack of memory. Otherwise, Quick View proceeds to stage E3.

c.	Quick View obtains the file viewer object's IFileViewer interface by specifying the IID_IFileViewer interface identifier in a call to the QueryInterface member function of pIPersistFile. Quick View calls the Release member function of pIPersistFile, regardless of the outcome. If this call fails due to lack of memory, Quick View proceeds to stage E4. Otherwise, Quick View proceeds to stage E3.

d1.	If the -v option was present or both the -v and -p options were absent, Quick View calls the ShowInitialize member function of pIFileViewer, which instructs the file viewer to load the file and perform any preshowing initialization that is prone to failure (including the creation of windows, the loading of resources, and so on). This is the file viewer's one chance to fail. If it fails, Quick View proceeds to stage E4 if the error is due to lack of memory or to stage E3 otherwise. If ShowInitialize succeeds, Quick View calls the Show member function of pIFileViewer, specifying the show command that was passed to Quick View's WinMain function. Show does not return until the user closes the file viewer, and it always returns NOERROR in that case. If Show is called before ShowInitialize, it returns E_UNEXPECTED.

d2.	If the -p option was present (and the -v option was absent), Quick View calls the PrintTo member function of pIFileViewer specifying the path of the printer driver provided in the -& option (or NULL if -& was absent) and a value indicating if the -d option was present on the command line (UI suppression flag). PrintTo does not return until printing is complete or an error occurs. If an error occurs, the file viewer is responsible for notifying the user if the UI suppression flag is FALSE.

e.	When Show or PrintTo returns (whichever was called in steps d1 or d2), Quick View calls the Release member function of pIFileViewer, regardless of the return value. If the file viewer successfully executed the IFileViewer::ShowInitialize member function, the Release member function will not fail. Release fails only if it is called before ShowInitialize. If PrintTo fails but the -d option was not specified on the command line, Quick View assumes that the file viewer displayed a message to indicate printing failed, and Quick View fails without displaying a message in that case. In any case, Quick View proceeds to step 5.

5.	Quick View releases any interface pointers it may have had and calls OleUninitialize (which calls CoFreeUnusedLibraries internally). Quick View then terminates normally.

Quick View may encounter these four error conditions (stages E1 through E4) during the lifetime of an instance.

E1.	If Quick View fails to associate the path with a file viewer class identifier (using a filename extension), it displays this message.

There are no viewers for this type of file. Would you like to try the default viewers.

If the user clicks No, Quick View terminates. If the user clicks Yes, Quick View displays the Searching dialog box, enumerates all registered file viewers (regardless of file type or filename extension ), and attempts to have each one load and display the file. Quick View tries each file viewer of a given class identifier once. If no file viewer successfully displays the file, Quick View removes the Searching dialog box and displays this message.

Error opening or reading file.

When the user closes the dialog box, Quick View terminates.

E2.	 If Quick View successfully determines the file type but fails to enumerate any file viewers associated with the filename extension, it displays the Searching dialog box and attempts to have each registered viewer display the file, trying each file viewer class identifier once. If that fails, the Quick View removes the Searching dialog box and displays this message.

There are no viewers capable of viewing <human-readable document type> files.

When the user closes the dialog box, Quick View terminates.

E3.	If Quick View successfully locates an initial file viewer but fails to view the file for any reason other than an out of memory condition, Quick View displays the Searching dialog box and continues enumerating viewers under the class identifier or filename extension key currently in use (steps 3d or 4c). If Quick View tries all viewers registered for the type unsuccessfully, processing continues as in stage E2 by trying all registered viewers regardless of registered type.

E4.	If an out of memory condition occurs for one file viewer, it is likely that other viewers will not succeed either. In that case, Quick View displays a dialog box (using MB_ICONEXCLAMATION) with this message.

There is not enough memory to view or print <filename>. Quit one or more files or programs, and then try again.

A file viewer can return a number of error values to Quick View. When Quick View receives an error value, it displays an error message. Quick View recognizes the following error values.

FV_E_BADFILE 	((HRESULT)0x8534E102L)
FV_E_EMPTYFILE	((HRESULT)0x8534E108L)
FV_E_FILEOPENFAILED	((HRESULT)0x8534E105L)
FV_E_INVALIDID	((HRESULT)0x8534E106L)
FV_E_MISSINGFILES	((HRESULT)0x8534E104L)
FV_E_NOFILTER	((HRESULT)0x8534E100L)
FV_E_NONSUPPORTEDTYPE	((HRESULT)0x8534E101L)
FV_E_NOVIEWER 	((HRESULT)0x8534E10AL)
FV_E_OUTOFMEMORY	((HRESULT)0x8534E107L)
FV_E_PROTECTEDFILE	((HRESULT)0x8534E109L)
FV_E_UNEXPECTED	((HRESULT)0x8534E103L)


 Pinned Windows

The shell can request Quick View to display a new file in the same window as that used by the previous file viewer; that is, Quick View can "pin" a viewer window. Quick View communicates the shell's request by sending a WM_DROPFILES message to the file viewer. The message contains an internal drop files structure whose members include the path of the new file to be displayed. A file viewer uses the same code to handle both the "pinned" state and drag and drop operations in which the file viewer displays a file that the user has dragged and dropped on the file viewer's window.

Quick View implements the IFileViewerSite interface, which allows a file viewer to retrieve the handle of the current pinned window, if there is any, or set a new pinned window. When Quick View calls a file viewer's IFileViewer::ShowInitialize member function, the file viewer receives the address of Quick View's IFileViewerSite interface. If the file viewer saves the address of the interface, it should call the IFileViewerSite::AddRef member function to increment the reference count.

Only one pinned window can exist at a time. A file viewer uses the IFileViewerSite::SetPinnedWindow interface to set a new pinned window and the IFileViewerSite::GetPinnedWindow interface to retrieve the handle of the current pinned window.

When Quick View calls the file viewer's IFileViewer::Show member function, the file viewer receives the address of a FVSHOWINFO structure that includes a optional RECT structure. A valid RECT structure is a hint from the shell that the file viewer window should be pinned; the file viewer should set the size and position of its window based on the information in the structure.

If the file viewer window receives a WM_DROPFILES message, it should fill in the strNewFile member of the FVSHOWINFO structure with the path of the new file to be displayed, fill the rect member with the size and position of the viewer window, and set the appropriate values in the dwFlags member. The file viewer should also fill the punkrel member with the address of an interface that the new file viewer should call to release the previous file viewer. Doing this allows the previous file viewer to perform cleanup operations. The new file viewer may be the same as the current file viewer if the current one supports the new file. If the old file viewer is the same as the new one, the release does not do anything because the reference count is greater than zero.

If a file viewer returns a file but Quick View cannot find a viewer for the new file, it calls the IFileViewer::Show member function for the old file viewer with the FVSIF_NEWFAILED value. The file viewer can either terminate or continue showing the previous file.


 Searching Dialog Box

When Quick View must enumerate more than one file viewer from the registry, it displays a dialog box containing a message that reads, as follows.

Searching for a viewer to display or print the <human-readable

document type> in <filename>. Press Cancel to stop the search.

If the document type is not known, the following message appears.

Searching for a viewer to display or print <filename>.

Press Cancel to stop the search.

Quick View animates the magnifying glass icon in the dialog box to indicate that Quick View is searching the hard disk. Pressing the Cancel button stops any search in progress and closes Quick View without performing any further actions or providing any user interface.


 File Viewer Structure and Implementation

A file viewer is an OLE component object in an in-process server DLL where the object implements the IPersistFile and IFileViewer interfaces. The in-process server exports the DllGetClassObject and DllCanUnloadNow functions, implements a class factory object with the IClassFactory interface, and implements the file viewer object with the interfaces required. The following illustration shows the structure of a file viewer.

There are a number of reasons why a file viewer is best implemented in a DLL with the given interfaces. In general, a DLL is faster to load and usually comes in a small package. In the future, these same DLLs will provide other nonuser interface features, such as content indexing, and a component object DLL will be the most efficient and fastest way to access those features. In some cases, a file viewer object may need to display pop-up windows and process messages through its own message loop as in Windows 95. The DLL structure still allows this when used in conjunction with a stub process like Quick View, which gives the file viewer DLL the right to execute a message loop.

The IPersistFile interface in the file viewer object is intended to be a general mechanism through which the object is given a path for a file. From then on, the component that loaded the object can ask it to do any number of things with the file. Through Quick View, the Windows 95 shell asks the object to show the file  by using the IFileViewer::ShowInitialize and IFileViewer::Show member functions or asks the object to print the file to a specific printer by using the IFileViewer::PrintTo member function. In the future, the shell may ask the object to perform content indexing, which would happen through an interface other than IFileViewer. For this reason, the file loading member functions of IPersistFile are separate from the operations that perform on the file, which is why IFileViewer was not just extended with its own Load member function. This latter option is a little more efficient (because it avoids IPersistFile entrypoint functions that are not implemented), but the design given here is easier to extend.


 IFileViewer Interface

The shell uses the IFileViewer interface to tell a file viewer object when to show its user interface for the file being viewed or to print the file. In addition to the usual IUnknown members, the interface includes the ShowInitialize, Show, and PrintTo member functions.

Before calling the Show member function, the shell calls ShowInitialize to instruct the file viewer to perform any creations, allocations, or loading. ShowInitialize may fail, whereas Show may not because Quick View needs to know, before anything becomes visible and before transferring control to the file viewer, whether the file viewer can show the file. If the file viewer can show the file, Quick View hides its Searching dialog box before the file viewer window appears.

The ShowInitialize member function should return the same FV_ error codes listed in "Structure of Registry Entries" earlier in this topic. Although the sample file viewer included in the Win32 SDK uses a more generic form of error codes, new file viewer DLLs should use the FV_ form.

The Show member function is similar to the Windows ShowWindow function in that it receives a Show command indicating how the file viewer should initially display its window. The meaning of the Show command is exactly the same as for ShowWindow. In general, Quick View passes the Show command from its WinMain function directly to IFileViewer::Show, which passes the command to ShowWindow. Since Quick View obtains this parameter from the shell, this design enables the shell to open a file viewer in the minimized, normal, or maximized state and even allows the shell to hide a file viewer (with the SW_HIDE value). There is no extra overhead in providing this flexibility. Note that the Windows 95 shell always starts Quick View with the SW_SHOWNORMAL value.

The only case when Show may fail is if ShowInitialize has not been called. In that case, it returns the E_UNEXPECTED status code (SCODE). Otherwise, Show must return the NOERROR error code.

The PrintTo member function is like Show in that it does not return until it finishes printing or an error occurs. If an error occurs, the file viewer object is responsible for informing the user of the problem. When calling PrintTo, the shell specifies the name of the printer driver that the file viewer should use to print the file. The shell also specifies a flag that indicates whether the file viewer should display any UI elements, including error message, during the print operation. If the flag is FALSE, the file viewer may show Print dialog boxes, Printer Setup dialog boxes, error messages, and so on.

The interface identifier of IFileViewer is defined in the Windows header files as the IID_IFileViewer interface identifier.


 File Viewer Creation

You can create a file viewer that interacts appropriately with Quick View by following these steps:

1.	Define the file viewer object to use the IPersistFile and IFileViewer interfaces. The object must also implement a separate IUnknown interface that does not delegate calls in aggregation situations. In general, a file viewer object creates or attaches to a window that displays a file's contents.

2.	Implement the Load and GetCurFile member functions (as well as the IUnknown member functions) of the IPersistFile interface. The IsDirty member function can simply return ResultFromScode(S_FALSE) because a file viewer does not modify the file, and the Save and SaveCompleted member functions should simply return ResultFromScode(E_NOTIMPL). Load stores the filename, but delays opening the file until the later call to the IFileViewer::ShowInitialize member function. GetCurFile returns ResultFromScode(E_UNEXPECTED) if Load has not yet been called. Otherwise, it copies the pathname and returns the NOERROR error code.

3.	Implement the IFileViewer::ShowInitialize and IFileViewer::Show member functions (as well as the IUnknown member functions of IFileViewer). ShowInitialize must perform all operations that are prone to failure such that if ShowInitialize succeeds, Show will never fail. The implementation of these two member functions is like an implementation of an application's WinMain function, where ShowInitialize registers window classes (using the instance handle that the DLL receives in its DllEntryPoint function, not the instance of Quick View), creates the necessary windows to meet the UI guidelines, and loads the file as read-only with the path given in IPersistFile::Load. Then Show displays the contents of that file in the viewport window, shows the top-level file viewer window, and enters a message loop. To enhance the appearance of the UI, the file should be loaded and completely displayed in the viewport window before the windows are made visible.

Show does not return until the user has closed the window; that is, Quick View waits for Show to return before terminating. Quick View delegates the responsibility of the message loop to the Show member function, so ShowInitialize and Show look and behave exactly like a WinMain function in any application (the code is just stored in a DLL).

Note that the path in the IPersistFile::Load member function may be a uniform naming convention (UNC) path. Functions such as Win32 OpenFile and OLE StgOpenStorage automatically handle UNC paths. If you open a file any other way, you must be sure to handle UNC paths properly.

4.	Define the class factory object with the IClassFactory interface and implement the interface completely to create a file viewer object. The class factory must support aggregation and server locking, as required by the IClassFactory interface.

5.	Implement the DllGetClassObject function to create an instance of the class factory mentioned in step 4 and return a pointer to one of its interfaces, as required for any component object DLL.

6.	Implement the DllCanUnloadNow function to return the appropriate code, depending on the number of file viewer objects in service and the number of lock counts implemented by using the IClassFactory::LockServer member function, as required for any component object DLL.

7.	Include the Print To feature by using the IFileViewer::PrintTo member function. This step is optional. If this feature is not implemented, the member function must return ResultFromScode(E_NOTIMPL).

8.	Finish the DLL implementation by using the DllEntryPoint function, as required for any Win32 DLL.

In general, only the implementations of IPersistFile::Load and the IFileViewer member functions are specific to a file viewer. The other steps that deal with creating an OLE component object are standard OLE mechanisms. For more information about these mechanisms, including objects and interfaces, see the OLE documentation included in the Win32 SDK as well as Chapters 3 and 4 of Inside OLE 2 from Microsoft® Press.


 File Viewer User Interface Guidelines

This section describes the minimal user interface recommended for a file viewer. These guidelines are provided to promote a consistent user interface in all file viewers. You should follow these guidelines as closely as possible and include viewer-specific features within the context of these guidelines.


 Window Appearance

A file viewer's main window should have Minimize, Maximize, and Close buttons and these top-level menu items: File, View, and Help (the contents of these menus is described later). A file viewer should also include a toolbar and a status window. The appearance and contents of the viewport window, which occupies all space not used by the toolbar and status window, is left to the developer. However, the viewport window typically has proportional scroll bars if the file contents are not entirely visible in the viewport.

The following illustration shows the typical initial state of a file viewer window. The initial state can be minimized or maximized if the file viewer is given a different show command through the IFileViewer::Show member function.

A file viewer can include other top-level menu items for file-specific features. For example, a file viewer should include an Edit menu with a single &Copy item to allow the user to make a selection in the viewport window and copy it to the clipboard. However, such extensions are not part of the basic user interface for a file viewer.

You should also use the new window flags in Windows 95 to create a three-dimensional window appearance and use scroll bars with proportional scroll boxes.


 File Menu Items

The standard file viewer File menu has the following four items (as well as separators), two of which are optional. A file viewer can add other items to the menu, but in most cases there is no need for other items.

Menu item string	Result of selecting the menu item
"&Open File for Editing"	Locates and starts the application that can open and edit the file. After successfully starting the application, the file viewer should hide its window immediately, shut down, and eventually return from IFileViewer::Show, after which the Quick View process terminates. If the file viewer fails to start the application, it should display the following message. There is no application available that can open this file.
Separator	Not applicable.
"Page Set&up" (optional)	Activates the standard Page Setup dialog box (or an application-specific dialog box if desired), the results of which affect the display of the file in the viewport window. The effects of the Page Setup command last only for the duration of the file viewer and do not affect the contents of the disk file. This menu item should appear if the file viewer supports printing and only if the Print menu item appears as well.
"&Print\tCtrl+P" (optional)	Activates the standard Print/Printer Setup property sheet. Any changes made to the printer setup that would affect the display of the file in the viewport window last only for the duration of the file viewer and do not affect the contents of the disk file. This menu item should appear only if the file viewer supports printing a file without starting the full application.
Separator	Not applicable.
"E&xit"	Hides the window, closes the file, destroys all the windows, performs other necessary cleanup, and returns with the NOERROR error code from IFileViewer::Show. The window should be hidden before cleanup happens to avoid marring its appearance, when the system destroys the toolbar and other controls.


 View Menu Items

The View menu of a standard file viewer has the following items.

Menu item string	Result of selecting the menu item
"&Toolbar"	Toggles the visibility of the toolbar. This item is checked when the toolbar is visible and unchecked when it is hidden.
"&Status Bar"	Toggles the visibility of the status window. This item is checked when the status line is visible and unchecked when it is hidden.
"&Page View"	Toggles between a full-sized view and a single-page view.
"Replace &Window"	Toggles between reusing the current window to view a file and creating a new window to view a file.
Separator	Not applicable.
"&Landscape"	Toggles between landscape and portrait view when in page view.
"&Rotate"	Rotates a raster graphic image 90 degrees every time the image is selected.
Separator	Not applicable.
"&Font"	Displays a dialog box that allows the user to select a font and point size for viewing word processing documents and spreadsheets.


 Help Menu Items

The standard file viewer Help menu has the following items.

Menu item string	Result of selecting the menu item
"&Help Topics"	Activates WINHELP.EXE with the file viewer's help file.
"&About fileviewer name"	Displays an About dialog box for the file viewer. The About dialog box identifies the vendor of the file viewer.
A file viewer can also add other help items and context-sensitive help.


 Toolbar Buttons

A file viewer must include a toolbar with a single button tied to the Open File for Editing menu item on the File menu described previously. The image in this button is a 16- by 15-pixel bitmap derived from the icon of the application that would be started if the user opened the file from the shell (using the shell's association route). The image is obtained by calling the SHGetFileInfo function with the path of the file. If this function fails, a file viewer can include a button that contains its own image and attempt to start the parent application, or the file viewer can remove the button and disable the Open File for Editing menu item on the File menu. This single button must be the leftmost item on the toolbar and must be separated from any other buttons that are specific to the file viewer.

Other buttons should correspond roughly to the functions present in the file viewer menus. A file viewer that supports a Font menu item should have Increase Font Size and Decrease Font Size buttons. Other file viewer classes may need to include printing and rotation buttons on the toolbar.

A standard toolbar button is the Replace Window button. The default behavior for file viewers is for a new file viewer instance to be created whenever the user chooses the Quick View menu item. When the Replace Window button is toggled to the on position, however, a new instance is not created; instead, the contents of the relevant file viewer window are replaced by a view of the new file.

All buttons should have a corresponding tooltip control that displays some context information when the mouse cursor is positioned on the button. The standard Windows 95 toolbar control provides built-in support for tooltip controls such that you only have to provide the text string. <> The following illustration shows a tooltip control for a toolbar button.

The recommended tooltip strings for various toolbar buttons follow.

Toolbar button	Tooltip string
Open File for Editing	"Open File for Editing"
Font Increase	"Increase Font Size"
Font Decrease	"Decrease Font Size"
Small View	"Toggle view size"
Landscape	"Toggle portrait/landscape"
Rotate [Again]	"Rotate image 90 degrees"
Replace Window	"Replace Window"


 Status Window Messages

A file viewer should display status window messages for the system menu and all top-level and pop-up menu items. The messages for the system menu and other menu items used by the default Windows 95 file viewers follow.

[Menu] item	Message
[System]	"Commands for manipulating this and other windows."
[System] Restore	"Restores this window to normal size." / "Expands this window to full screen size."
[System] Move	"Move this window to another screen location."
[System] Size	"Resizes this window."
[System] Minimize	"Collapses this window to an icon."
[System] Maximize	"Expands this window to full screen size."
[System] Close	"Closes this window."
[System] Switch To...	"Switch to another task."
[File]	"Contains commands for opening the file and quitting Quick View."
[File] Open File for Editing	"Opens the file for editing."
[File] Page Setup	"Changes the page setup for printing."
[File] Print...	"Prints the file contents."
[File] Exit	"Quits Quick View."
[View]	"Contains commands for customizing this window."
[View] Toolbar	"Shows or hides the toolbar."
[View] Status Bar	"Shows or hides the status bar."
[View] Page View	"Switches between document and page views."
[View] Replace Window	"Displays new files in current Quick View window."
[View] Landscape	"Switches between portrait and landscape."
[View] Rotate (Again)	"Rotates the image by 90 degrees."
[View] Font	"Changes the display font."
[Help]	"Contains commands for displaying Help and information about Quick View."
[Help] Help Topics	"Displays the Help Contents and Index."
[Help] About	"Displays program information, version number and copyright."
The following standard messages for other conditions not related to menu items are implemented in the Windows 95 default file viewers:

•	In the inactive state, when the user is doing nothing else, the status line should read as follows.

Display details may be inaccurate.

This line should be the first visible message when the file viewer appears.

•	When the mouse cursor is positioned over the viewport window, the status window should read as follows.

To edit, click Open File for Editing on the File menu.

Note that the document type is specific for the file viewer in use, as shown in the following illustration.

•	The status window should reflect longer versions of tooltip messages when tooltip controls are displayed. For example, a longer version of the "Increase Font Size" tooltip is "Increase the font size of the display" shown at the same time in the status window.


 Viewport Window Contents and Context Menu

The viewport window is where you provide most file-specific UI elements. The viewport occupies all space in the client area of the main window not used for the toolbar and status bar. It displays the file contents in whatever mode is applicable, and it is sensitive to the user-selected printer and page setup, as well as other View menu commands.

If the contents of the file are too large to be completely displayed within the viewport, the file viewer should provide scroll bars (with proportional scroll boxes) to shift the image. If the contents of the file are smaller than the viewport window, no scroll bars should appear. In addition, the file contents should not be initially scaled to fill the viewport window unless the user selects scaling through the View menu commands.

The only other requirement for the viewport window is that it should provide a context menu for the file. The context menu should appear when the user clicks the viewport with the mouse button 2. The context menu should include the following items.

Menu item string	Equivalent found on other menu
"&Open File for Editing"	Open File for Editing command on the File menu
Separator	Not applicable
"Page Se&tup" (optional)	Page Setup command on the File menu
"&Print" (optional)	Print command on the File menu (note, no accelerator)
Separator	Not applicable
A file viewer may add more items as necessary. The Toolbar and Status bar menu items commands on the View menu should not appear in the context menu.


 Drag and Drop Functionality

The default file viewers in Windows 95 allow the user to drag a file from the desktop or Explorer and drop the file on a file viewer's window. A file viewer should show the small document icon that includes the "+" sign when the mouse is over the file viewer's window before the drop takes place. The Replace Window command in the View menu controls whether another file viewer window is displayed or the same window is reused.


 Sophisticated File Viewers

This article only describes the minimal file viewer UI. There are, of course, many other possibilities besides just rudimentary printing and viewing capabilities. One useful feature is the ability to copy data from a document either to the clipboard or in a drag and drop operation. In such cases, the file viewer needs to provide the ability to select data in the file, a Copy command (on an Edit menu as well as in a context menu), and the ability to pick up the selection and drag it elsewhere. However, the file viewer should not be a drop target and should not support the Cut and Paste commands on the Edit menu (or other variants) because those operations modify the file.

If the parent application creating the files that are handled in a specific file viewer is an OLE compound document container, the file viewer itself must be sensitive to viewing a compound document. That means that the file viewer itself will support some minimal container features and will, of course, use OLE to load and display compound document objects in the file itself. If the file viewer also supports in-place activation, it can activate inside-out objects in-place to allow the user to select and copy data from embeddings. While there are no standards for such functionality in Windows 95, there will be in future versions of Windows.


 Reference

A file viewer in-process server DLL must implement the IFileViewer and IPersistFile interfaces. This section describes the IFileViewer interface and its member functions. For information about the IPersistFile interface and its member functions, see the OLE documentation included in the Win32 SDK.


 Interfaces and Member Functions


IFileViewer [New - Windows 95]
 IFileViewer

[New - Windows 95]

Designates an interface that allows a registered file viewer to be notified when it must show or print a file. The Windows 95 shell calls this interface when the user selects the Quick View command from a file's context menu and the file is a type that the file viewer recognizes. The IFileViewer interface has the following member functions:

PrintTo	Prints a file.
Show	Displays a file.
ShowInitialize	Prepares to display a file.
Like all OLE interfaces, IFileViewer also includes the QueryInterface, AddRef, and Release member functions.


IFileViewer::PrintTo [New - Windows 95]
 IFileViewer::PrintTo

[New - Windows 95]

HRESULT PrintTo(IFileViewer FAR * pFileViewer,
    LPSTR pszDriver, BOOL fSuppressUI);

Prints a file.

•	Returns the NOERROR value if successful or an OLE-defined error value otherwise.

pFileViewer

Address of the IFileViewer interface. In C++, this parameter is implicit.

pszDriver

Address of a buffer that contains the name of the printer device driver that should print the file. If this parameter is NULL, the file viewer determines which device driver to use.

fSuppressUI

User interface suppression flag. If this parameter TRUE, the file viewer should not display any UI whatsoever, including error messages, during the print operation. If this parameter FALSE, the file viewer can show dialog boxes, as needed.

The shell specifies the name of the file to print by calling the file viewer's IPersistFile::Load member function.


IFileViewer::Show [New - Windows 95]
 IFileViewer::Show

[New - Windows 95]

HRESULT Show(IFileViewer FAR * pFileViewer,
    LPFVSHOWINFO pvsi);

Displays a file.

•	Returns the NOERROR value if successful or the E_UNEXPECTED value if the IFileViewer::ShowInitialize member function was not called before IFileViewer::Show.

pFileViewer

Address of the IFileViewer interface. In C++, this parameter is implicit.

pvsi

Address of an FVSHOWINFO structure containing information that the file viewer uses to display the file. A file viewer can return information to the shell by modifying the members of the structure.

The shell specifies the name of the file to display by calling the file viewer's IPersistFile::Load member function.

IFileViewer::Show can fail only if IFileViewer::ShowInitialize was not called first, and the return value must be E_UNEXPECTED in that case. Otherwise, IFileViewer::Show must return NOERROR.


IFileViewer::ShowInitialize [New - Windows 95]
 IFileViewer::ShowInitialize

[New - Windows 95]

HRESULT ShowInitialize(IFileViewer FAR * pFileViewer,
    LPFILEVIEWERSITE lpfsi);

Allows a file viewer to determine whether it can display a file and, if it can, to perform initialization operations before showing the file.

•	Returns the NOERROR value if successful or an OLE-defined error value otherwise.

pFileViewer

Address of the IFileViewer interface. In C++, this parameter is implicit.

lpfsi

Address of a IFileViewerSite interface. A file viewer uses this interface to retrieve the handle of the current pinned window or to specify a new pinned window.

The shell calls this member function before the IFileViewer::Show member function. The shell specifies the name of the file to display by calling the file viewer's IPersistFile::Load member function.

IFileViewer::ShowInitialize must perform all operations that are prone to failure so that if it succeeds, IFileViewer::Show will not fail.


IFileViewerSite [New - Windows 95]
 IFileViewerSite

[New - Windows 95]

Designates an interface that allows a file viewer to retrieve the handle of the current pinned window or to set a new pinned window. The pinned window is the window in which the current file viewer is displaying a file. When the user selects a new file to view, the shell directs the file viewer to display the new file in the pinned window rather than to create a new window.

The IFileViewerSite interface has the following member functions.

GetPinnedWindow	Retrieves the handle of the current pinned window.
SetPinnedWindow	Sets a new pinned window.
Like all OLE interfaces, IFileViewerSite also includes the QueryInterface, AddRef, and Release member functions.


IFileViewerSite::GetPinnedWindow [New - Windows 95]
 IFileViewerSite::GetPinnedWindow

[New - Windows 95]

HRESULT GetPinnedWindow(IFileViewerSite FAR * pFileVS,
    HWND *phwnd);

Retrieves the handle of the current pinned window, if it exists.

•	Returns the NOERROR value if successful or an OLE-defined error value otherwise.

pFileVS

Address of the IFileViewer interface. In C++, this parameter is implicit.

phwnd

Address of a window handle of the current pinned window or NULL if no pinned window exists.


IFileViewerSite::SetPinnedWindow [New - Windows 95]
 IFileViewerSite::SetPinnedWindow

[New - Windows 95]

HRESULT SetPinnedWindow(IFileViewerSite FAR * pFileVS,
    HWND hwnd);

Sets a new pinned window.

•	Returns the NOERROR value if successful or an OLE-defined error value otherwise.

pFileVs

Address of the IFileViewer interface. In C++, this parameter is implicit.

hwnd

Handle of the new pinned window or NULL if there is to be no pinned window.

When the user selects a new file to view, the shell directs the file viewer to display the new file in the pinned window instead of creating a new window.


 Structure

The following structure is used with file viewers.


FVSHOWINFO [New - Windows 95]
 FVSHOWINFO

[New - Windows 95]

typedef struct {

    DWORD     cbSize;    // size of structure, in bytes

    HWND      hwndOwner; // see below

    int       iShow;     // see below

    DWORD     dwFlags;   // see below

    RECT      rect;      // see below

    LPUNKNOWN punkrel;   // see below

    OLECHAR   strNewFile[MAX_PATH];  // see below

} FVSHOWINFO, *LPFVSHOWINFO;

Contains information that the IFileViewer::Show member function uses to display a file.

hwndOwner

Handle of the owner window. When a file viewer creates a window to display a file, it should specify this handle as the owner of the window.

iShow

Show command. For a list of show commands, see the description of the ShowWindow function.

dwFlags

Show information flags. This member can be a combination of these values:

FVSIF_CANVIEWIT	The file viewer can display the file.
FVSIF_NEWFAILED	The file viewer specified a new file to display, but no viewer could display the file. The file viewer should either terminate or continue to display the previous file.
FVSIF_NEWFILE	A drag and drop operation has dropped a file on the file viewer window. The file viewer passes the name of the file to the shell by copying the name to strNewFile. The shell attempts to load a file viewer that can display the new file.
FVSIF_PINNED	A pinned window exists. A file viewer should either use the pinned window to display the file or set a new pinned window and display the file in it.
FVSIF_RECT	rect contains valid data.
rect

Address of a RECT structure that specifies the size and position of the file viewer's window. This member is valid only if dwFlags includes the FVSIF_RECT value.

punkrel

Address of an interface whose Release member function is called by a new file viewer to release the previous file viewer. This member is used when a drag and drop operation drops a file on the file viewer's window.

strNewFile

Address of a string that specifies the name of a new file to display. A file viewer sets this member when a drag and drop operation drops a file on the file viewer's window.

The shell uses this structure to pass information to a file viewer, and a file viewer uses it to return information to the shell.


 File Parsers

A file parser is a dynamic-link library (DLL) that provides the low-level parsing needed to generate a "quick view" for a file of a given type.


 About File Parsers

File parsers work in conjunction with the file viewing components of the Microsoft® Windows® 95 operating system. These components are the shell, the Quick View program (QUIKVIEW.EXE), display engines, and file parsers. The shell responds to user requests to generate a quick view for a file by calling the Quick View program. The program manages the process, directing one of the display engines to draw the Quick View window and fill it with a view of the file. The display engine uses a file parser to determine the contents of the file and to draw those contents correctly.

You can extend the file viewing capabilities of Windows 95 by supplying additional file parsers. Each file parser is responsible for a specific type or class of file and is associated with one of the display engines. For example, you can allow a quick view to be generated for a .DOC file by creating a file parser to support that file type and associating the file parser with the word processor display engine.

This article describes the file parser interface and explains how to write file parsers for word processing documents, spreadsheets, databases, bitmapped graphics, and vector graphics. The functions, macros, and structures described here can be found with the file parser sample code in the Samples subdirecory of the Microsoft® Win32® Software Development Kit (SDK). For information about extending the file viewing capabilities in other ways, see "File Viewers."

The file viewing technology used in the Quick View feature of the Microsoft Windows 95 operating system has been jointly developed by Microsoft Corporation and Systems Compatibility Corporation.


 Adding or Removing File Parsers

For performance reasons, the file viewer builds a cache of the file parsers in the system the first time the Quick View feature is used. This cache is stored in the registry. If a file parser is added or removed, this cache must be rebuilt. To make the system rebuild the cache, set verify data not equal to zero under the following key.

\\HKEY_LOCAL_MACHINE\SOFTWARE\SCC\Viewer Technology\MS1


 File Parser Functions

Every file parser must implement the following functions.

VwStreamCloseFunc	VwStreamSectionFunc
VwStreamOpenFunc	VwStreamSeekFunc
VwStreamReadFunc	VwStreamTellFunc
VwStreamReadRecordFunc
The display engine calls these functions to display a file of the type supported by the file parser.

The display engine starts the file viewing process by calling VwStreamOpenFunc, sending the name of a file to the file parser. The first responsibility of any parser is to verify that the given file has the proper format and can be processed. If the file is viewable, the file parser returns a value to the display engine acknowledging the request.

Once the parser completes verification, the display engine calls VwStreamSectionFunc, directing the file parser to identify the type and name of the first section of the file to be processed. A section is a portion of the file in which all the data is of one type; it forms a logical breaking point for the processing of the file. The standard section types are word processing, spreadsheet, database, bitmapped graphics, and vector graphics. A file can consist of a single section, multiple sections of the same type, or a combination of sections of different types. The actions that the display engine takes to display the file depend on the type of section currently being processed. The file parser must call the SOPutSectionType and SOPutSectionName functions to output the section type and to set the section name.

Before the file parser returns from VwStreamSectionFunc, it may need to provide the display engine with additional information. If the portion to be processed is a word processing section, the file parser must set entries for the font table by using the SOPutFontTableEntry function. If it is a spreadsheet section, the file parser must set the column width by calling the SOPutColumnInfo function. If it is a database section, the file parser must set the field format by calling the SOPutFieldInfo function. The file parser can also set the date base used by spreadsheets and databases to calculate dates by using the SOSetDateBase function. In addition, the file parser can set header entries by calling the SOPutHdrEntry function.

After the section type and general information is set, the display engine requests data for the section by calling VwStreamReadFunc. The file parser fulfills this request by calling the stream output functions. These functions pass the data to the display engine in a form that is easiest for the engine to display, copy to the clipboard, or write to disk.

The stream output functions used by the file parser depend on the section type. For word processing sections, the file parser uses the SOPutParaSpacing, SOPutCharAttr, and SOPutChar functions to set the spacing for paragraphs, set the style attributes for characters, and output characters. For spreadsheet sections, the parser uses the SOPutDataCell and SOPutTextCell functions to output the content (data or text) of cells. For database sections, it uses the SOPutField and SOPutVarField functions to output the data of fields. The parser uses the SOPutBitmapHeader and SOPutScanLineData functions for bitmapped graphics sections and the SOVectorAttr and SOVectorObject functions for vector graphics sections.

To set a break for a paragraph, cell, or field, the file parser calls the SOPutBreak function with an appropriate value, either SO_PARABREAK, SO_CELLBREAK, or SO_RECORDBREAK. The return value from SOPutBreak tells the file parser how to proceed. If it is the SO_STOP value, the file parser stops all processing and returns from VwStreamReadFunc.

The file parser continues to output data until it reaches the end of the section. The parser must end a section by calling SOPutBreak with the SO_SECTIONBREAK value. If this is the last section in the file, the file parser indicates that the end of the file has been reached by using the SO_EOFBREAK value instead.

If there are subsequent sections in the file, the display engine calls VwStreamSectionFunc again to request the type and name of the next section, and processing continues just as it did for the first section.

After the last section, the display engine calls VmStreamCloseFunc to indicate that processing is complete and that no further requests for data will be made. The file parser must close the file and any related files it has opened and clean up resources, such as freeing memory.

If an error occurs while a file is parsed, the file parser should call the SOBailOut function to notify the display engine of the error condition. The parser must immediately return from VwStreamReadFunc after calling the SOBailOut function.


 Restartable Parsing

You must design the file parser so that parsing can be efficiently restarted at discrete locations within the file. The goal is to give the display engine the best performance without it having to store a completely converted copy of a file.

To facilitate restartable parsing, the display engine incorporates a module, which is called the chunker, that essentially caches data from the parser. The chunker does not cache all the data, only the data that the display engine has most recently requested. However, it does cache state data for restartable locations in the file. This means that as long as the parser maintains its own internal data in a way that can be efficiently restarted, the display engine and the parser can work cooperatively to locate and restart processing at the cached locations.

The file parser is responsible for determining the best locations for restarting parsing. It does this by calling the SOPutBreak function. The chunker assumes that each break is a restartable location in the file. Before calling SOPutBreak, however, the file parser must save up-to-date data about the location so that it can quickly retrieve and begin processing the data at the location if requested to do so.

The display engine uses the VwStreamSeekFunc and VwStreamTellFunc functions to direct the file parser to a restartable location.


 Word Processing Sections

Word processing sections contain text organized as paragraphs, tables, and subdocuments. Of these, paragraphs and tables can have attributes, such as indentation, tab stops, and spacing. The text in word processing sections consists of characters having attributes, such as typeface, height, and weight. Word processing sections can also include embedded objects, allowing bitmapped art and other graphics to be included with the text.

A file parser processes the text associated with a word processing section when the display engine calls the VwStreamReadFunc function. The file parser must set all attributes before calling the SOPutChar function or other text output functions. The file parser must never automatically set an attribute as a default. If the state of a current attribute is not known, the file parser must not set it.


 Paragraph Attributes

The file parser sets the attributes of a paragraph before outputting characters for the paragraph. The attributes are the alignment, indent, spacing, tab stops, and margins.

The file parser sets the alignment to be left, right, centered, or justified by using the SOPutParaAlign function and sets the left, right, and first line indents by using the SOPutParaIndents function. The file parser sets the spacing before and after the paragraph and between lines of the paragraph by using the SOPutParaSpacing function. The file parser sets tab stops by using the SOPutTabStop function, calling the function once for each tab stop. To mark the start and end of a tab stop definition, the file parser calls the SOStartTabStops and SOEndTabStops functions. The file parser sets page margins for the paragraph by using the SOPutParaMargins function.


 Tables

The file parser can add tables to text output by using the SOBeginTable and SOEndTable functions to mark the start and end of the table definition and can format the rows and cells in tables by using the SOPutTableRowFormat and SOPutTableCellInfo functions. The file parser uses the character and paragraph functions to output the text for each cell and set the attributes.

The file parser marks the end of each cell and each row by using the SOPutBreak function with the SO_TABLECELLBREAK and SO_TABLEROWBREAK values. A file parser must insert a cell break after each cell and a row break at the end of each row. If a file parser inserts a row break before inserting as many cells as were defined for the row, the remaining cells are assumed to be empty. Empty cells may be inserted in the middle of a row by inserting consecutive cell breaks.

Row and cell formats must be defined before the last cell of a row. After defining the row properties by using the SOPutTableRowFormat function, the parser must call the SOPutTableCellInfo function for each cell in the row. After a row is defined, the row properties are assumed to apply to subsequent rows until new row properties are specified. A filter may, thus, define an entire table by specifying the row and cell properties once and then using the appropriate row and cell breaks.

You can add borders to cells by setting the pLeftBorder, pRightBorder, pTopBorder, and pBottomBorder members of the SOTABLECELLINFO structure to appropriate values when setting the cell format.

You can add tabs to cells by using the special character, the SO_CHCELLTAB value. This character is defined for cells that are merged with their neighbors and acts as a tab that moves the current text position to the location of the next boundary that would have existed if the cells had not been merged.


 Subdocuments

The file parser adds subdocuments — that is, headers, footers, footnotes, and comments — to the document by using the SOPutBreak function. The file parser must call SOPutBreak with the SO_SUBDOCBEGINBREAK value to start a subdocument and with the SO_SUBDOCENDBREAK value to end it.

After ending a subdocument, the file parser must restore character and paragraph attributes to their state before the subdocument was started. The file parser can use the SUUserPushData and SUUserPopData functions to save and restore nested subdocument information. A parser can nest subdocuments without limit. The following example shows when to save and restore this information.

This is a <Bold On> test

    // At this point, the filter should save its internal
    // information to reflect the fact that bold is on.
    SOPutBreak(SO_SUBDOCBEGINBREAK);
    SoPutSubdocInfo(...);
<Subdoc Begin> This is a <Bold Off>subdocument<Subdoc End>

    // At this point, the filter should restore its internal
    // information to reflect the fact that bold is on.
    SOPutBreak(SO_SUBDOCENDBREAK);

document <Bold Off>of mine.

File parsers are not expected to correctly exit a subdocument when run from a regular paragraph break (with the SO_PARABREAK value) inside the subdocument. The display engine lets the file parser run to the subdocument's end break (that is, the SO_SUBDOCENDBREAK value) and returns the SO_STOP value to it.


 Characters and Character Attributes

The file parser outputs characters by using the SOPutChar function. It can specify extra properties for a character, such as grouped or hidden, when outputting by using the SOPutCharX function. The file parser outputs special characters, such as tabs, hard line breaks, hard page breaks, and hyphens by using the SOPutSpecialCharX function.

Before outputting characters, the file parser sets character attributes by using the SOPutCharAttr, SOPutCharFontById, SOPutCharFontByName, and SOPutCharHeight functions. These functions set the style, font, height, and width of the character. The SOPutCharAttr function lets the file parser set style attributes, such as italic, underline, and strikeout. The SOPutCharFontById and SOPutCharFontByName functions can specify any font that the parser added to the font table during processing of the VwStreamSectionFunc function. The SOPutCharHeight function sets the character height, in half points.


 Embedded Objects

The file parser can embed graphics objects in the text of a paragraph section by using the SOPutEmbeddedObject function. The function inserts the embedded graphics object at the current location.


 Spreadsheet Sections

The file parser outputs content (data or text) for cells in a spreadsheet by using the SOPutDataCell and SOPutTextCell functions. Before outputting cell data, the file parser must get the range of columns to be output by using the SOGetInfo function with the SOINFO_COLUMNRANGE value. When SOGetInfo returns, the low-order word of its pInfo parameter identifies the first column of data to generate output for, and the high-order word identifies the last column. The file parser should only call SOPutDataCell or SOPutTextCell for cells within the range indicated by a call to SOGet. When there is no more data within a range of columns, the file parser must call the SOPutBreak function with either the SO_EOFBREAK or SO_SECTIONBREAK value, whichever applies. This must be done for each range of columns in the document.

For example, if the first column is 10 and the last column is 19, the filter reads the file from its current position, but it only calls SOPutDataCell or SOPutTextCell for cells that belong in columns 10 through column 19, inclusively. (Column numbers are zero based.) The parser skips over cells that belong in columns outside of this range. The filter must produce cells for all columns in the range, filling in with empty cells, if necessary. As before, the filter continues until SOPutBreak returns the SO_STOP value.

In general, the file parser should carry out the following steps:

1.	Determine the desired range of columns.

2.	Determine the next cell available from the input file.

3.	If the cell is not in the given range of columns, jump to step 2.

4.	If the cell is not empty, call SOPutDataCell or SOPutTextCell with the current data. Otherwise, call SOPutDataCell for a cell of the SO_CELLEMPTY type.

5.	Update local variables, such as row and column numbers.

6.	Call SOPutBreak with the SO_CELLBREAK value.

7.	If SOPutBreak returns the SO_STOP value, return from the VwStreamReadFunc function.

8.	If at the beginning of the next section, call SOPutBreak with the SO_SECTIONBREAK value and return.

9.	If at the end of the file, call SOPutBreak with the SO_EOFBREAK value and return.

10.	Repeat steps 2 through 10.

When the chunker saves local data for various seek positions in a document, it does so within SOPutBreak, when the break is of the SO_CELLBREAK type. Thus, when a file parser has its local data restored for a random seek position, the data will reflect the state of the file parser during its call to SOPutBreak for the last cell of the previous chunk in the current range of cells. Any tracking done by the parser, such as the current row number, should be updated before SOPutBreak is called for each cell.

Every horizontal range of columns, specified by dwExtraData in each call to your VwStreamReadFunc function, must eventually be terminated by a call to SOPutBreak with SO_EOFBREAK or SO_SECTIONBREAK value, whichever is applicable. The type of break depends on the input file. A file parser must not put a section break at the end of the file, and an end-of-file (EOF) break, of course, cannot occur anywhere but at the actual end of the file.

For example, if the input document contains a single spreadsheet that is 30 columns wide, the display engine can call the parser with three different ranges of columns: 0 to 11, 12 to 23, and 24 to 29. The file parser calls SOPutBreak with an EOF break three times, once for each time it reaches the end of the file while processing a given range.

When calling SOPutBreak with a section break, the file parser must be sure that the seek position is at the beginning of the next section — that is, the file position where the file parser needs to be when VwStreamSectionFunc is next called. Any one of the calls to SOPutBreak for a section break may be the one that sets the seek position for the top of the next section.


 Database Sections

The file parser outputs data and text for a database by using the SOPutField, SOPutMoreVarField, and SOPutVarField functions. The parser uses the SOPutField function for fields of a fixed size. The other functions are used for variable length fields. The parser sets field information by using the SOPutFieldInfo function while processing the VmStreamSectionFunc function.


 Bitmapped Sections

The file parser starts a bitmapped section by calling the SOPutSectionType function with the SO_BITMAP value while processing the VmStreamSectionFunc function. The file parser must also set the bitmap header information for the section by using the SOPutBitmapHeader function before returning from VmStreamSectionFunc. The information in the bitmap header allows the chunker to allocate storage for other bitmap information, such as the palette. This means that the file parser must call SOPutBitmapHeader before any other bitmapped section functions.


 Palettes

The file parser must generate a palette for those sections that have the SO_COLORPALETTE value set in the wImageFlags member of the SOBITMAPHEADER structure. The parser uses the SOStartPalette, SOPutPaletteEntry, and SOEndPalette functions to define the color palette for a bitmapped section. Only one palette may be defined for a bitmapped section.

All SOCOLORREF members set during the stream read can use RGB (red, green, blue) values, palette index values, or palette-relative RGB values. All settings of these values must be done through the SOPALETTEINDEX, SORGB, or SOPALETTERGB macro. For more information about these types of color values, see the description of the COLORREF value.


 Tiles and Scan Lines

A bitmap image in a bitmapped section consists of tiles and scan lines. A tile is a rectangular portion of an image, containing at least one scan line. An image is one or more tiles wide and one or more tiles long. A tile column is the horizontal positioning of a tile; the tiles that have their x-coordinate equal to zero belong to tile column zero, with tile column numbers incrementing in the direction of the increasing x-coordinates.

The file parser specifies its tile length in terms of scan lines. Once the length is specified, the display engine always requests bitmap data as whole tiles; that is, it tells the parser to stop only on integral multiples of the tile length. For formats that contain multiple tiles, file parsers should set the tile length to the minimum number of scan lines required for a single tile. Formats that are not stored in tiles should have the tile width set equal to the image width and the tile length set to one scan line.

The following values are expected to be valid when tiles are created.

TILESACROSS = (ImageWidth+TileWidth-1)/TileWidth
TILESDOWN = (ImageLength+TileLength-1)/TileLength
TILESPERIMAGE=TILESACROSS*TILESDOWN

To output bitmap data, the file parser outputs a scan line at a time, in sequential order, by using the SOPutScanLineData function. All of the scan line must belong to the same tile column. After each scan line, the file parser calls the SOPutBreak function with the SO_SCANLINEBREAK value. As is normally the case, the return value from SOPutBreak indicates whether the file parser should return from the VwStreamReadFunc function.


 Building Scan Lines

The file parser builds the scan line data as a continuous stream of bits that define each pixel. Each pixel is packed into an array of bytes in such a way that if the data were written out in hexadecimal or binary numbers, the pixels could be read in order from left to right. That is, for a 4-bit-per-pixel format, the first pixel is stored in the high-order bits of the first byte (bit 7, bit 6, bit 5, and bit 4), and the second pixel is stored in low-order bits of that byte (bit 3, bit 2, bit 1, and bit 0). Thus, if the first eight pixels of a 4-bit-per-pixel scan line have the hex values of 0, 2, C, 9, A, 4, 3, and F, the first four bytes of scan line data would be 02, C9, A4, and 3F.

If the parser provides a palette for the image, the data for each pixel is interpreted as an index into the palette. If no palette exists for the image, the bits for each pixel specify either a true color (24-bit only) or a gray scale value. For 24-bit color, each 3 bytes of a scan line represent the intensities of red, green, and blue of a single pixel.

When the scan line has been completely specified, the parser must call SOPutBreak with the SO_SCANLINEBREAK value, except for the last line of the bitmap. The last line of the bitmap must end with a break of the SO_SECTIONBREAK or SO_EOFBREAK type, whichever applies.

The following example illustrates the use of the bitmapped functions in the simplest possible case: a parser with scan line data stored one tile wide and with the same format that parsers are required to provide it, so the data requires no additional processing after being read in. This example also does not check for EOF or read errors.

WORD  wBytesRead;
WORD  wBufSize = Proc.ScanLineBufSize;

do
{
...

xread( hFile, Proc.ScanLineBuf, wBufSize, &wBytesRead );

SOPutScanLineData( Proc.ScanLineBuf, hProc );

...

} while( SOPutBreak( SO_SCANLINEBREAK, 0, hProc ) == SO_CONTINUE );


 Vector Graphics Sections

The file parser starts a vector graphics section by calling the SOPutSectionType function with the SO_VECTOR value while processing the VmStreamSectionFunc function. The file parser must also set the vector header by using the SOPutVectorHeader function before returning from VmStreamSectionFunc. The information in the SOVECTORHEADER structure defines the size and attributes of the rectangle in which vector graphics are drawn.

The vector graphics functions are similar to the primitive GDI functions, but they include extensions that are based on the file formats being supported. All vector graphics objects are described in two-dimensional space on a logical coordinate system. The direction and resolution of the x- and y-axis is defined in SOVECTORHEADER.

The file parser uses two functions to transfer data. The SOVectorAttr function sets attributes related to drawing vector graphics objects, and the SOVectorObject function defines a vector graphics object to be drawn. The parser specifies an identifier, a data size, and the address of data when it calls a function. The identifier specifies the action to take and the size and data-defined details of the action. Each action has a corresponding structure in which the data must be given. For example, to define a logical font, the parser must set the members of the SOLOGFONT structure and pass the structure to SOVectorAttr.

Although vector graphics functions are similar to the graphics device interface (GDI) functions, they are not exactly the same. This means, for example, that the members of the SOLOGFONT and LOGFONT structures are not necessarily the same.

The file parser should call the SOPutBreak function with the SO_VECTOROBJECTBREAK value after drawing every object.


 Writing a File Parser

File parsers should be contained in a set of source and include files as follows, where XXX represents a mnemonic for the data format. For specific examples, see the sample ASCII filter files identified in the following table.

Generic file name	Contents	Sample ASCII filter file
VS_XXX.C	Code	VS_ASC.C
VSD_XXX.C	Data	VSD_ASC.C
VS_XXX.H	Type definitions	VS_ASC.H
VSP_XXX.H	Portability information	VSP_ASC.H
The portability information file makes porting of filters between 16- and 32-bit versions of Windows and multiple Microsoft® Windows NT™ platforms easier. To allow file parsers to be used for content indexing, a set of include files is provided that will allow conditional compilations to yield executable DLLs for all of these needs from the same set of source files.

Your VSP_XXX.H file should look something like the following. (For further information, see the corresponding ASCII filter file.)

•	The structure type and name of the static data.

#define VwStreamStaticType  ???
#define VwStreamStaticName  ???

The parser must not change the contents of the structure, because it is shared among all instances of the parser.

•	The structure type and name of the dynamic data.

#define VwStreamDynamicType  ???
#define VwStreamDynamicName  ???

VwStreamDynamicName is for consistency and has no real use, because all dynamic data is accessed through the pseudonym Proc. Each instance of the parser has a separate copy of dynamic data.

•	The structure type and name of the save data.

#define VwStreamSaveType  ???
#define VwStreamSaveName  ???

VwStreamSaveName should reference an element in the VwStreamDynamicType structure. The data in this structure is saved after every call to VwStreamSectionFunc and VwStreamReadFunc and restored before every call to VwStreamReadFunc.

•	The structure type and name of the section data.

#define VwStreamSectionType  ???
#define VwStreamSectionName  ???

If neither of these is defined, the file parser is assumed to be single section only. VwStreamSectionName should reference an element in the VwStreamDynamicType structure. The data in this structure is saved after each call to VwStreamSectionFunc and is guaranteed to contain the current section's data on entry to VwStreamReadFunc.

The example below shows the relationship of the various save areas to the dynamic data structure.

typedef struct {
 ...
} VwStreamSaveType;
typedef struct {
 ...
} VwStreamSectionType;
typedef struct {
 ...
    VwStreamSectionType VwStreamSectionName; // multisection only
    VwStreamSaveType VwStreamSaveName;
} VwStreamDynamicType;

•	The stream identifier name and count.

#define VwStreamIdName   ???
#define VwStreamIdCount   ???

VwStreamIdName is the name of the FILTER_DESC array in VSD_XXX.C, and VwStreamIdCount is the number of elements in this array. Like the static data, this data should never be changed by a parser.

•	The name of the include file. All the structure types used by the parser should be defined in this file.

#define VwInclude              "vs_xxx.h"
#define VwStreamUserSaveType   ???
#define VwStreamGenSeekName    ???
#define VwStreamOpenFunc        xxx_stream_open
#define VwStreamSeekFunc        xxx_stream_seek
#define VwStreamTellFunc        xxx_stream_tell
#define VwStreamReadFunc        xxx_stream_read
#define VwStreamReadRecordFunc  xxx_stream_readrecord
#define VwStreamSectionFunc     xxx_stream_section
#define VwStreamCloseFunc       xxx_stream_close
#define VwGetInfoFunc           xxx_getinfo
#define VwGetRtnsFunc           xxx_getrtns
#define VwGetDataFunc           xxx_getdata
#define VwSetDataFunc           xxx_setdata
#define VwAllocProcFunc         xxx_alloc_proc
#define VwFreeProcFunc          xxx_free_proc
#define VwLocalUpFunc           xxx_local_up
#define VwLocalDownFunc         xxx_local_down
#define VwGetSectionDataFunc    xxx_getsectiondata
#define VwSetSectionDataFunc    xxx_setsectiondata

•	The top of the VS_XXX.C file should look like this.

#include "VSP_XXX.H"
#include "VSCTOP.H"
#include "VS_XXX.PRO"


 Reference

The following functions, helper functions, and structures are associated with file parsers.


 Functions

The following functions are used with file parsers.


VwStreamCloseFunc [New - Windows 95]
 VwStreamCloseFunc

[New - Windows 95]

VOID VwStreamCloseFunc(SOFILE hFile, HPROC reserved);

Closes the file. The file parser must carry out any necessary cleanup, such as closing any other open files related to the given file.

•	No return value.

hFile

Handle of the file for execute input and output (XIO) routines.

reserved

Reserved; do not use.


VwStreamOpenFunc [New - Windows 95]
 VwStreamOpenFunc

[New - Windows 95]

INT VwStreamOpenFunc(SOFILE hFile, INT wFileId,
    U_BYTE VWPTR * pFileName, SOFILTERINFO VWPTR * pFilterInfo,
    HPROC reserved);

Checks the validity of the specified file and returns information about the file parser.

•	Returns the VWERR_OK value if successful or one of the following error values otherwise:

VWERR_BADFILE	Corrupt or unreadable file
VWERR_EMPTYFILE	Empty file
VWERR_PROTECTEDFILE	Password-protected or encrypted file
VWERR_SUPFILEOPENFAILS	Supplementary file failed to open
hFile

Handle of the file for execute input and output (XIO) routines.

wFileId

Identifier for the file.

pFileName

Address of the null-terminated string specifying the base name of the file. This string does not include path information.

pFilterInfo

Address of the SOFILTERINFO structure that receives information about the file parser.

reserved

Reserved; do not use.


VwStreamReadFunc [New - Windows 95]
 VwStreamReadFunc

[New - Windows 95]

INT VwStreamReadFunc(SOFILE hFile, HPROC reserved);

Outputs characters, cells, or fields, depending on the current section type and file contents.

•	Returns zero if successful or  − 1 if the end of the file is reached.

hFile

Handle of the file for execute input and output (XIO) routines.

reserved

Reserved; do not use.


VwStreamReadRecordFunc [New - Windows 95]
 VwStreamReadRecordFunc

[New - Windows 95]

VOID VwStreamReadRecordFunc(SOFILE hFile, DWORD dwData, HPROC reserved);

Outputs a single record by calling various stream output functions.

•	No return value.

hFile

Handle of the file for execute input and output (XIO) routines.

dwData

Data to be saved for the record.

reserved

Reserved; do not use.

This function should output a single record and then call the SOPutBreak function with the SO_RECORDBREAK value before returning. The SO_EOFBREAK and SO_SECTIONBREAK conditions do not need to be trapped by this function.


VwStreamSectionFunc [New - Windows 95]
 VwStreamSectionFunc

[New - Windows 95]

INT VwStreamSectionFunc(SOFILE hFile, HPROC reserved);

Sets the parameters for a section.

•	Always returns zero.

hFile

Handle of the file for execute input and output (XIO) routines.

reserved

Reserved; do not use.

At a minimum, this function should call the SOPutSectionType and SOPutSectionName functions to set the section type and name. The function should also set the cell width if the section is a spreadsheet or the field format if the section is a database.

The display engine calls the function after calling the VwStreamOpenFunc function but before calling the VwStreamReadFunc function. It is also called after any VwStreamReadFunc that ends with a call to the SOPutBreak function with the SO_SECTIONBREAK value.


VwStreamSeekFunc [New - Windows 95]
 VwStreamSeekFunc

[New - Windows 95]

INT VwStreamSeekFunc(SOFILE hFile, HPROC reserved);

Same definition as the line filters Seek function

•	Returns zero if successful or  − 1 if the function fails.

hFile

Handle of the file for execute input and output (XIO) routines.

reserved

Reserved; do not use.


VwStreamTellFunc [New - Windows 95]
 VwStreamTellFunc

[New - Windows 95]

INT VwStreamTellFunc(SOFILE hFile, HPROC reserved);

Same definition as the line filters Tell function.

•	Returns zero if successful or  − 1 if the function fails.

hFile

Handle of the file for execute input and output (XIO) routines.

reserved

Reserved; do not use.


 Helper Functions


SOBailOut [New - Windows 95]
 SOBailOut

[New - Windows 95]

VOID SOBailOut(WORD wError, HPROC reserved);

Allows the file parser to return an error condition.

•	No return value.

wError

Error flag. This parameter can be one of these values:

SOERROR_BADFILE	Invalid file format
SOERROR_EOF	Unexpected end of file (EOF)
SOERROR_GENERAL	Unspecified error
reserved

Reserved; do not use.

The parser should return from the VwReadStreamFunc function as soon as possible after this function is called.


SOBeginTable [New - Windows 95]
 SOBeginTable

[New - Windows 95]

VOID SOBeginTable(HPROC reserved);

Starts a table definition, indicating that the text in subsequent output calls is part of a table.

•	No return value.

reserved

Reserved; do not use.

This function must be called between paragraphs and before row and cell formats are specified.


SOEndColumnInfo [New - Windows 95]
 SOEndColumnInfo

[New - Windows 95]

VOID SOEndColumnInfo(HPROC reserved);

Ends the definition of column information.

•	No return value.

reserved

Reserved; do not use.

The file parser must call this function immediately after setting the column information. This function can only be called from the VwStreamSection function.


SOEndFieldInfo [New - Windows 95]
 SOEndFieldInfo

[New - Windows 95]

VOID SOEndFieldInfo(HPROC reserved);

Ends the definition of field information.

•	No return value.

reserved

Reserved; do not use.

The file parser must have previously called the SOStartFieldInfo function.

The file parser calls this function immediately after setting the field information. This function can only be called from the VwStreamSection function.


SOEndFontTable [New - Windows 95]
 SOEndFontTable

[New - Windows 95]

VOID SOEndFontTable(HPROC reserved);

Ends the definition of a font table.

•	No return value.

reserved

Reserved; do not use.

The file parser must call this function immediately after setting font entries. This function can only be called from the VwStreamSection function.


SOEndPalette [New - Windows 95]
 SOEndPalette

[New - Windows 95]

VOID SOEndPalette( HPROC reserved );

Ends the definition of a color palette.

•	No return value.

reserved

Reserved; do not use.

The file parser calls this function immediately after specifying the last palette entry.


SOEndTable [New - Windows 95]
 SOEndTable

[New - Windows 95]

VOID SOEndTable(HPROC reserved);

Ends a table definition, indicating that the text in subsequent output calls is no longer part of a table.

•	No return value.

reserved

Reserved; do not use.

The function must be called after a row break.


SOEndTabStops [New - Windows 95]
 SOEndTabStops

[New - Windows 95]

VOID SOEndTabStops(HPROC reserved);

Ends the definition of tabs stops for a paragraph.

•	No return value.

reserved

Reserved; do not use.

To set tab stops, use the SOPutTabStop function.

The file parser calls this function immediately after setting the last tab stop for the paragraph.


SOGetInfo [New - Windows 95]
 SOGetInfo

[New - Windows 95]

VOID SOGetInfo(WORD wInfo, void VWPTR * pInfo, HPROC reserved);

Retrieves information about a spreadsheet.

•	No return value.

wInfo

Information type. If this parameter is the SOINFO_COLUMNRANGE value, the function retrieves the range of columns for a spreadsheet to read.

pInfo

Address of a 32-bit variable that receives the first column number in the low-order word and the second column number in the high-order word.

reserved

Reserved; do not use.


SOGetScanLineBuffer [New - Windows 95]
 SOGetScanLineBuffer

[New - Windows 95]

WORD SOGetScanLineBuffer(VOID VWPTR * ppScanLineData, HPROC reserved );

Retrieves the address of the buffer for storing the current scan line.

•	Returns the size, in bytes, of the scan line data buffer. The size is the maximum number of bytes that may be accessed using the returned address and is guaranteed to be sufficient to hold a scan line as wide as the entire tile.

ppScanLineData

Address of the variable that receives the address of the scan line data buffer.

reserved

Reserved; do not use.

This function is called from the VwStreamReadFunc function for each scan line produced.

This function sets the variable pointed to by ppScanLineData to the address where the scan line data should be built.


SOPutBitmapHeader [New - Windows 95]
 SOPutBitmapHeader

[New - Windows 95]

VOID SOPutBitmapHeader(PSOBITMAPHEADER pBitmapHeader, HPROC reserved);

Outputs information about a bitmap.

•	No return value.

pBitmapHeader

Address of the SOBITMAPHEADER structure that contains the bitmap header information.

reserved

Reserved; do not use.


SOPutBreak [New - Windows 95]
 SOPutBreak

[New - Windows 95]

WORD SOPutBreak(WORD wType, DWORD dwInfo, HPROC reserved);

Sets a paragraph, cell, record, page, section, or other type of break.

•	Returns the SO_STOP value to direct the file parser to stop processing and return or the SO_CONTINUE value to direct the file parser to continue processing.

wType

Type of break. This parameter can one of these values:

SO_CELLBREAK	Regular cell break
SO_EOFBREAK	End of file (EOF) break, which implies a section break
SO_PARABREAK	Regular paragraph break
SO_RECORDBREAK	Regular record break
SO_SECTIONBREAK	Section break
SO_SUBDOCBEGINBREAK	Subdocument's begin break
SO_SUBDOCENDBREAK	Subdocument's end break
dwInfo

Data to save for each record. This data is for database section breaks. For all other section types, this parameter should be zero.

reserved

Reserved; do not use.

dwInfo is saved after every SOPutBreak function and, like the regular save information, should represent the next record, not the one just read.

In spreadsheet sections, the last cell in a section must have an associated SO_CELLBREAK break before the SO_SECTIONBREAK or SO_EOFBREAK break.

In database sections, the last record in a section must have an associated SO_RECORDBREAK break before the SO_SECTIONBREAK or SO_EOFBREAK break.

In word processing sections, the last paragraph does not need an SO_PARABREAK break before the SO_SECTIONBREAK or SO_EOFBREAK break.


SOPutChar [New - Windows 95]
 SOPutChar

[New - Windows 95]

VOID SOPutChar(WORD wCh, HPROC reserved);

Outputs a character, applying the current font, height, and attributes.

•	No return value.

wCh

Character value. This parameter must be within the range specified by the current character set.

reserved

Reserved; do not use.

The character is assumed to belong to the character set selected by the open function and is countable and visible.


SOPutCharAttr [New - Windows 95]
 SOPutCharAttr

[New - Windows 95]

VOID SOPutCharAttr(WORD wAttr, WORD wState, HPROC reserved);

Sets the style attributes for characters in text.

•	No return value.

wAttr

Style attribute type. This parameter can be one of these values:

SO_BOLD	Bold
SO_CAPS	All capital letters
SO_DOTUNDERLINE	Dotted underline
SO_DUNDERLINE	Double underline
SO_ITALIC	Italic
SO_OUTLINE	Outlined rather than solid
SO_SHADOW	Shadow slightly beneath and behind
SO_SMALLCAPS	Small capital letters
SO_STRIKEOUT	Strikeout
SO_SUBSCRIPT	Subscript
SO_SUPERSCRIPT	Superscript
SO_UNDERLINE	Single underline
SO_WORDUNDERLINE	Underline
wState

Style attribute state. This parameter can be the SO_ON or SO_OFF value.

reserved

Reserved; do not use.


SOPutCharFontById [New - Windows 95]
 SOPutCharFontById

[New - Windows 95]

VOID SOPutCharFontById(DWORD dwFontId, HPROC reserved);

Sets the font for characters in text.

•	No return value.

dwFontId

Font identifier, relative to the previously given font table.

reserved

Reserved; do not use.


SOPutCharFontByName [New - Windows 95]
 SOPutCharFontByName

[New - Windows 95]

VOID SOPutCharFontByName(WORD wFontType, char VWPTR * pFontName, HPROC reserved);

Sets the font for characters in text.

•	No return value.

wFontType

Font family. This parameter can be one of these values:

SO_FAMILYDECORATIVE	Fancy display font
SO_FAMILYMODERN	Fixed width
SO_FAMILYROMAN	Variable width with serifs
SO_FAMILYSCRIPT	Handwriting
SO_FAMILYSWISS	Variable width without serifs
SO_FAMILYSYMBOL	Symbol font
SO_FAMILYUNKNOWN	Not known
pFontName

Address of a null-terminated string specifying the name of the font.

reserved

Reserved; do not use.


SOPutCharHeight [New - Windows 95]
 SOPutCharHeight

[New - Windows 95]

VOID SOPutCharHeight(WORD wHeight, HPROC reserved);

Sets the height, in half points, of a character in text.

•	No return value.

wHeight

Height, in half points, of the character.

reserved

Reserved; do not use.


SOPutCharX [New - Windows 95]
 SOPutCharX

[New - Windows 95]

VOID SOPutCharX(WORD wCh, WORD wType, HPROC reserved);

Outputs a character, applying the specified character type.

•	No return value.

wCh

Character value. This parameter must be within the range specified by the current character set.

wType

Type flag. This parameter can be one or more of these values:

SO_COUNT	The character is countable and may be deleted. Characters without this value are for display purposes and do not enter into character count calculations for write back.
SO_HIDDEN	The character is not visible on the display.
SO_LIMITEDIT	Consecutive characters of this type will be deleted as a group. No write back command will begin on one of these characters, but it may encompass a group of these characters.
reserved

Reserved; do not use.

The character is assumed to belong to the character set selected by the open function.


SOPutColumnInfo [New - Windows 95]
 SOPutColumnInfo

[New - Windows 95]

VOID SOPutColumnInfo(PSOCOLUMN pColumn, HPROC reserved);

Sets column information.

•	No return value.

pColumn

Address of the SOCOLUMN structure containing the column information.

reserved

Reserved; do not use.

The file parser must call the SOStartColumnInfo function before calling this function.

This function can only be called from the VwStreamSection function.


SOPutDataCell [New - Windows 95]
 SOPutDataCell

[New - Windows 95]

VOID SOPutDataCell(PSODATACELL pCell, HPROC reserved);

Outputs data for a cell.

•	No return value.

pCell

Address of a SODATACELL structure.

reserved

Reserved; do not use.


SOPutEmbeddedObject [New - Windows 95]
 SOPutEmbeddedObject

[New - Windows 95]

VOID SOPutEmbeddedObject(PSOEMBEDDEDOBJECT pObject, HPROC reserved);

Sets an embedded graphics object.

•	No return value.

pObject

Address of the SOEMBEDDEDOBJECT structure that contains information about the object to be embedded.

reserved

Reserved; do not use.

The file parser must set the SOEMBEDDEDOBJECT structure with the appropriate values.


SOPutField [New - Windows 95]
 SOPutField

[New - Windows 95]

VOID SOPutField(void VWPTR * pData, HPROC reserved);

Outputs data for a field.

•	No return value.

pData

Address of the data for the field.

reserved

Reserved; do not use.

This function is used for all wStorage types except the SO_FIELDTEXTVAR value.


SOPutFieldInfo [New - Windows 95]
 SOPutFieldInfo

[New - Windows 95]

VOID SOPutFieldInfo(PSOFIELD pField, HPROC reserved);

Sets field information.

•	No return value.

pField

Address of the SOFIELD structure containing the field information.

reserved

Reserved; do not use.

The file parser must call the SOStartFieldInfo function before calling this function.

This function can only be called from the VwStreamSection function.


SOPutFontTableEntry [New - Windows 95]
 SOPutFontTableEntry

[New - Windows 95]

VOID SOPutFontTableEntry(DWORD dwFontId, WORD wFontType,
    char VWPTR * pFontName, HPROC reserved);

Sets a font table entry.

•	No return value.

dwFontId

Font identifier. This parameter can be any number, but it must be unique within the font table.

wFontType

Font family. This parameter can be one of these values:

SO_FAMILYDECORATIVE	Fancy display font
SO_FAMILYMODERN	Fixed width
SO_FAMILYROMAN	Variable width with serifs
SO_FAMILYSCRIPT	Handwriting
SO_FAMILYSWISS	Variable width without serifs
SO_FAMILYSYMBOL	Symbol font
SO_FAMILYUNKNOWN	Not known
pFontName

Address of a null-terminated string specifying the name of the font.

reserved

Reserved; do not use.

The file parser must call the SOStartFontTable function before calling this function. SOPutFontTableEntry must be called once for each font to be added to the table. Font identifiers must be unique, but they can be given in any order.

This function can only be called from the VwStreamSection function.


SOPutHdrEntry [New - Windows 95]
 SOPutHdrEntry

[New - Windows 95]

VOID SOPutHdrEntry(char VWPTR *pLabel, char VWPTR * pData, WORD wId,
    HPROC reserved);

Sets strings for the header information.

•	No return value.

pLabel

Label that the display engine should use when presenting this value.

pData

Value to display.

wId

Identifier for this item that the display engine and filter agree upon.

reserved

Reserved; do not use.

This function can only be called from the VwStreamSection function.


SOPutMoreText [New - Windows 95]
 SOPutMoreText

[New - Windows 95]

VOID SOPutMoreText(WORD wCount, char VWPTR * pText, WORD bMore,
    HPROC reserved);

Outputs the text for a cell and indicates whether there is more text to be output for the cell.

•	No return value.

wCount

Number of characters pointed to by pText. The number must not exceed 128 bytes.

pText

Address of the string of text characters to output.

bMore

More data flag. This parameter can be the SO_YES value to indicate more text to be output or the SO_NO value to indicate none.

reserved

Reserved; do not use.

This function is used to output a sequence of text initially started by using the SOPutText function.

If there is more text to output, the file parser must use a subsequent call or calls to the SOPutMoreText function to output the text. The 128 byte limit is for the convenience of the function processing SOPutMoreText.


SOPutMoreVarField [New - Windows 95]
 SOPutMoreVarField

[New - Windows 95]

VOID SOPutMoreVarField(VOID VWPTR * pData, WORD wCount, WORD bMore,
    HPROC reserved);

Outputs data for a variable field and indicates whether there is more data to be output for the field.

•	No return value.

pData

Address of the data for the field.

wCount

Number of bytes pointed to by pData. The number must not exceed 128 bytes.

bMore

More data flag. This parameter can be the SO_YES value to indicate more data to be output or the SO_NO value to indicate none.

reserved

Reserved; do not use.

This function can be called any number of times.

If there is more data to output, the file parser must use a subsequent call or calls to SOPutMoreVarField to output the data. The 128 byte limit is for the convenience of the function processing SOPutMoreVarField.

This function is used to output a sequence of data initially started using the SOPutVarField function.


SOPutPaletteEntry [New - Windows 95]
 SOPutPaletteEntry

[New - Windows 95]

VOID SOPutPaletteEntry(unsigned char Red, unsigned char Green,
    unsigned char Blue, HPROC reserved);

Sets the colors for a palette entry.

•	No return value.

Red

Relative red intensity in the range 0 to 255.

Green

Relative green intensity in the range 0 to 255.

Blue

Relative blue intensity in the range 0 to 255.

reserved

Reserved; do not use.

The file parser must call the SOStartPalette function before calling this function.

The order of calls to this function determines the order of entries in the color table for an image. The first palette entry is color 0, the color displayed for pixels with a value of 0; the second palette entry is color 1; and so on.


SOPutParaAlign [New - Windows 95]
 SOPutParaAlign

[New - Windows 95]

VOID SOPutParaAlign(WORD wType,HPROC reserved);

Sets the alignment for a paragraph.

•	No return value.

wType

Type of alignment. This parameter can be the SO_ALIGNLEFT, SO_ALIGNRIGHT, SO_ALIGNCENTER, or SO_ALIGNJUSTIFY value.

reserved

Reserved; do not use.


SOPutParaIndents [New - Windows 95]
 SOPutParaIndents

[New - Windows 95]

VOID SOPutParaIndents(LONG dwLeft, LONG dwRight, LONG dwFirst,
    HPROC reserved);

Sets indents for a paragraph. Indents are relative to the corresponding left or right margin.

•	No return value.

dwLeft

Width, in twips, of the left indent. The indent is measured from the left page margin.

dwRight

Width, in twips, of the right indent. The indent is measured from the right page margin.

dwFirst

Width, in twips, of the left indent for the first line in the paragraph. The indent is measured from the left page margin.

reserved

Reserved; do not use.


SOPutParaMargins [New - Windows 95]
 SOPutParaMargins

[New - Windows 95]

VOID SOPutParaMargins(LONG dwLeft, LONG dwRight, HPROC reserved);

Sets paragraph margins. The margins are relative to the left or right edge of the page.

•	No return value.

dwLeft

Width, in twips, of the left margin.

dwRight

Width, in twips, of the right margin.

reserved

Reserved; do not use.


SOPutParaSpacing [New - Windows 95]
 SOPutParaSpacing

[New - Windows 95]

VOID SOPutParaSpacing(WORD wLineHeightType, DWORD dwLineHeight,
    DWORD dwSpaceBefore, DWORD dwSpaceAfter, HPROC reserved);

Sets the spacing for a paragraph.

•	No return value.

wLineHeightType

Type of line height. This parameter can be one of these values:

SO_HEIGHTATLEAST	Sets the line height to the height given by dwLineHeight or sets it to fit the tallest character in the line, whichever height is greater.
SO_HEIGHTAUTO	Sets the line height automatically to fit the tallest character in the line.
SO_HEIGHTEXACTLY	Sets the line height to the height given by dwLineHeight.
dwLineHeight

Baseline to baseline height, in twips.

dwSpaceBefore

Space before the paragraph, in twips.

dwSpaceAfter

Space after the paragraph, in twips.

reserved

Reserved; do not use.


SOPutScanLineData [New - Windows 95]
 SOPutScanLineData

[New - Windows 95]

VOID SOPutScanLineData(U_BYTE VWPTR * pScanLineData, HPROC reserved);

Sets the bit values in a single scan line of a bitmap.

•	No return value.

pScanLineData

Address of the bitmap data for the current scan line.

reserved

Reserved; do not use.

The bitmap format must have been previously defined by using the SOPutBitmapHeader function.


SOPutSectionName [New - Windows 95]
 SOPutSectionName

[New - Windows 95]

VOID SOPutSectionName(char VWPTR * pName, HPROC reserved);

Sets the name of a section.

•	No return value.

pName

Address of a null-terminated string specifying the name of the section.

reserved

Reserved; do not use.


SOPutSectionType [New - Windows 95]
 SOPutSectionType

[New - Windows 95]

VOID SOPutSectionType(WORD wType, HPROC reserved);

Outputs a section type.

•	No return value.

wType

Section type. This parameter can be one of these values:

SO_BITMAP	Sets the section type to be a bitmap. When generating output for the section, the file parser should use only general and bitmap stream output functions.
SO_CELLS	Sets the section type to be a spreadsheet consisting of cells. When generating output for the section, the file parser should use only the general and spreadsheet stream output functions.
SO_FIELDS	Sets the section type to be a database consisting of fields. When generating output for the section, the file parser should use only the general and database stream output functions.
SO_PARAGRAPHS	Sets the section type to be a word processing document consisting of paragraphs. When generating output for the section, the file parser should use only general and word processing stream output functions.
SO_VECTOR	Sets the section type to be a vector graphics section consisting of graphics objects. When generating output for the section, the file parser should use only the general and vector graphics stream output functions.
reserved

Reserved; do not use.


SOPutSpecialCharX [New - Windows 95]
 SOPutSpecialCharX

[New - Windows 95]

VOID SOPutSpecialCharX(WORD wCh, WORD wType, HPROC reserved);

Outputs a special character, applying the specified character type.

•	No return value.

wCh

Character value. This parameter can be one of these values:

SO_CHDATE	Automatic current date
SO_CHHHYPHEN	Nonbreaking hyphen
SO_CHHLINE	Hard line break
SO_CHHPAGE	Hard page break
SO_CHHSPACE	Nonbreaking space
SO_CHPAGENUMBER	Automatic page number
SO_CHSHYPHEN	Hyphen
SO_CHTAB	Tab
SO_CHTIME	Automatic current time
SO_CHUNKNOWN	Default character
wType

Type flag. This parameter can be one or more of these values:

SO_COUNT	The character is countable and may be deleted. Characters without this value are for display purposes and do not enter into character count calculations for write back.
SO_HIDDEN	The character is not visible on the display.
SO_LIMITEDIT	Consecutive characters of this type will be deleted as a group. No write back command will begin on one of these characters, but it may encompass a group of these characters.
reserved

Reserved; do not use.


SOPutSubdocInfo [New - Windows 95]
 SOPutSubdocInfo

[New - Windows 95]

VOID SOPutSubdocInfo(WORD wType, WORD wSubType, HPROC reserved);

Outputs subdocument data.

•	No return value.

wType

Type of data. This parameter can be one of these values:

SO_COMMENT	The data is a comment.
SO_FOOTER	The data applies to the document footer.
SO_FOOTNOTE	The data applies to a footnote.
SO_HEADER	The data applies to the document header.
wSubType

Subtype of data. This parameter can be one of these values:

SO_BOTH	The data is for a header or footer on both left and right pages. This value is used with SO_HEADER or SO_FOOTER.
SO_LEFT	The data is for a header or footer on even pages only. This value is used with SO_HEADER or SO_FOOTER.
SO_RIGHT	The data is for a header or footer on odd pages only. This value is used with SO_HEADER or SO_FOOTER.
0 through 65535	The data is a footnote number. This value is used with SO_FOOTNOTE only.
If wType is SO_COMMENT, no subtype is needed.

reserved

Reserved; do not use.


SOPutTableCellInfo [New - Windows 95]
 SOPutTableCellInfo

[New - Windows 95]

VOID SOPutTableCellInfo(PSOTABLECELLINFO pCellInfo, HPROC reserved);

Sets cell information.

•	No return value.

pCellInfo

Address of a SOTABLECELLINFO structure containing information about the cell.

reserved

Reserved; do not use.


SOPutTableRowFormat [New - Windows 95]
 SOPutTableRowFormat

[New - Windows 95]

VOID SOPutTableRowFormat(WORD wLeftEdge, WORD wRowHeight,
    WORD wRowHeightType, WORD wCellMargin, WORD wRowAlignment,
    WORD wNumCells, HPROC reserved );

Sets the format of a row in a table.

•	No return value.

wLeftEdge

Position, in twips, of the left edge of the table, relative to the left margin.

wRowHeight

Row height, in twips.

wRowHeightType

Type of height for the row. This parameter can be one of these values:

SO_HEIGHTATLEAST	Sets the  row height at least as high as that given by wRowHeight.
SO_HEIGHTAUTO	Sets the  row height automatically to fit text in the row.
SO_HEIGHTEXACTLY	Sets the row height exactly as given by wRowHeight.
wCellMargin

White space on either side of text in a cell within the specified cell width. It is equal to half the total white space between adjacent cells.

wRowAlignment

Alignment of row within margins. This parameter can be the SO_ALIGNLEFT, SO_ALIGNRIGHT, or SO_ALIGNCENTER value.

wNumCells

Number of cells in the row.

reserved

Reserved; do not use.


SOPutTabStop [New - Windows 95]
 SOPutTabStop

[New - Windows 95]

VOID SOPutTabStop(PSOTAB pTabs, HPROC reserved);

Sets a tab stop for the paragraph.

•	No return value.

pTabs

Address of the SOTAB structure containing the tab stop information.

reserved

Reserved; do not use.

The file parser must call the SOStartTabStops function before calling this function and can set multiple tab stops for a paragraph by calling it multiple times. The file parser must not call any other output function while setting tab stops and must call the SOEndTabStops function after setting the last tab stop.


SOPutTextCell [New - Windows 95]
 SOPutTextCell

[New - Windows 95]

VOID SOPutTextCell(PSOTEXTCELL pCell, WORD wCount, char VWPTR * pText,
    WORD bMore, HPROC reserved);

Outputs the text for a cell and indicates whether there is more text to be output for the cell.

•	No return value.

pCell

Address of a SOTEXTCELL structure.

wCount

Number of characters pointed to by pText. The number must not exceed 128 bytes.

pText

Address of the string of text characters to be output.

bMore

More data flag. This parameter can be the SO_YES value to indicate more text to be output or the SO_NO value to indicate none.

reserved

Reserved; do not use.

If there is more text to be output, the file parser must use a subsequent call or calls to the SOPutMoreText function to output the text.


SOPutVarField [New - Windows 95]
 SOPutVarField

[New - Windows 95]

VOID SOPutVarField(void VWPTR * pData, WORD wCount, WORD bMore,
    HPROC reserved);

Outputs data for a variable field and indicates whether there is more data to be output for the field.

•	No return value.

pData

Address of the data for the variable field.

wCount

Number of bytes pointed to by pData. The number must not exceed 128 bytes.

bMore

More data flag. This parameter can be the SO_YES value to indicate more data to be output or the SO_NO value to indicate none.

reserved

Reserved; do not use.

If there is more data to be output, the file parser must use a subsequent call or calls to the SOPutMoreVarField function to output the data.


SOPutVectorHeader [New - Windows 95]
 SOPutVectorHeader

[New - Windows 95]

VOID SOPutVectorHeader(PSOVECTORHEADER pVectorHeader, HPROC reserved);

Outputs the vector header, specifying the display resolution, x- and y-axis orientation, background color, and color value type (RGB or palette).

•	No return value.

pVectorHeader

Address of a SOVECTORHEADER structure.

reserved

Reserved; do not use.


SOSetDateBase [New - Windows 95]
 SOSetDateBase

[New - Windows 95]

VOID SOSetDateBase(DWORD dwBase, WORD wFlags, HPROC reserved);

Sets the base date. All subsequent dates are calculated as the sum of the base date and the given date value.

•	No return value.

dwBase

Base number of Julian days to be automatically added to dates. All dates are entered in Julian day format in the following manner:

Jan. 1, 4713 B.C.	Julian Day 1
Jan. 1, 1 A.D.	Julian Day 1721424
Jan. 1, 1900	Julian Day 2415021
Jan. 1, 1904	Julian Day 2416481
Formats supporting dates before 1582 are not supported.

wFlags

Action flag. This parameter can be the SO_LOTUSHELL value to correct for the Lotus 1-2-3® 1990 leap year bug.

reserved

Reserved; do not use.

This function can only be called from the VwStreamSection function.


SOStartColumnInfo [New - Windows 95]
 SOStartColumnInfo

[New - Windows 95]

VOID SOStartColumnInfo(HPROC reserved);

Starts the definition of column information.

•	No return value.

reserved

Reserved; do not use.

The file parser must call this function immediately before setting the information. This function can only be called from the VwStreamSection function.


SOStartFieldInfo [New - Windows 95]
 SOStartFieldInfo

[New - Windows 95]

VOID SOStartFieldInfo(HPROC reserved);

Starts the definition of field information.

•	No return value.

reserved

Reserved; do not use.

The file parser calls this function immediately before setting field information. This function can only be called from the VwStreamSection function.


SOStartFontTable [New - Windows 95]
 SOStartFontTable

[New - Windows 95]

VOID SOStartFontTable(HPROC reserved);

Starts the definition of a font table.

•	No return value.

reserved

Reserved; do not use.

The file parser must call this function immediately before setting font entries. The function can only be called from the VwStreamSection function.


SOStartPalette [New - Windows 95]
 SOStartPalette

[New - Windows 95]

VOID SOStartPalette(HPROC reserved);

Starts the definition of a color palette.

•	No return value.

reserved

Reserved; do not use.

The file parser calls this function immediately before defining palette entries.


SOStartTabStops [New - Windows 95]
 SOStartTabStops

[New - Windows 95]

VOID SOStartTabStops(HPROC reserved);

Starts the definition of tab stops for a paragraph.

•	No return value.

reserved

Reserved; do not use.

To set tab stops, use the SOPutTabStop function.

The file parser calls this function immediately before setting the first tab stop for the paragraph.


SOVectorAttr [New - Windows 95]
 SOVectorAttr

[New - Windows 95]

VOID SOVectorAttr(INT nItemId, DWORD wDataSize, VOID VWPTR *pData,
    HPROC reserved);

Sets attributes related to drawing vector graphics objects.

•	No return value.

nItemId

Action identifier. This parameter, which specifies the action to carry out and determines the appropriate values for wDataSize and pData, can be one of the vector attribute values in "Constants" later in this topic.

wDataSize

Size, in bytes, of data pointed to by pData.

pData

Address of a buffer containing the information used to carry out the requested action. The meaning and format of the buffer depends on the value of nItemId.

reserved

Reserved; do not use.


SOVectorObject [New - Windows 95]
 SOVectorObject

[New - Windows 95]

VOID SOVectorObject(INT nItemId, DWORD dwDataSize, VOID VWPTR *pData,
    HPROC reserved );

Draws or defines the given vector graphics object.

•	No return value.

nItemId

Action flag. This parameter, which specifies the action to carry out and determines the appropriate values for wDataSize and pData, can be one of the vector object values in "Constants" later in this topic.

wDataSize

Size, in bytes, of the data pointed to by pData.

pData

Address of a buffer containing the information used to carry out the requested action. The meaning and format of the buffer depends on the value of nItemId.

reserved

Reserved; do not use.


SUUserPopData [New - Windows 95]
 SUUserPopData

[New - Windows 95]

VOID SUUserPopData(VOID VWPTR * pData, HPROC reserved);

Pops user data. The data must have been pushed previously by using the SUUserPushData function.

•	No return value.

pData

Address of the VwStreamUserSaveType structure receiving the data.

reserved

Reserved; do not use.


SUUserPushData [New - Windows 95]
 SUUserPushData

[New - Windows 95]

VOID SUUserPushData(VOID VWPTR * pData, HPROC reserved);

Pushes user data.

•	No return value.

pData

Address of a VwStreamUserSaveType structure containing the data to be saved.

reserved

Reserved; do not use.

The data can be retrieved by using the SUUserPopData function.


SUUserRetrieveData [New - Windows 95]
 SUUserRetrieveData

[New - Windows 95]

VOID SUUserRetrieveData(WORD wIndex, VOID VWPTR * pData, HPROC reserved);

Retrieves user data.

•	No return value.

wIndex

Index value specifying the data to retrieve. This value must have been previously returned by the SUUserSaveData function.

pData

Address of the VwStreamUserSaveType structure receiving the data.

reserved

Reserved; do not use.

The data must have been previously saved by using the SUUserSaveData function.

This function should not be used. The SUUserPopData function should be used instead.


SUUserSaveData [New - Windows 95]
 SUUserSaveData

[New - Windows 95]

WORD SUUserSaveData(VOID VWPTR * pData, HPROC reserved);

Saves user data.

•	Returns the index used to retrieve the data. Indexes are guaranteed to be zero-based and sequential.

pData

Address of a VwStreamUserSaveType structure containing the data to be saved.

reserved

Reserved; do not use.

This function should not be used. The SUUserPushData function should be used instead.


 Macros

The following macros are used with file parsers.


SOANGLETENTHS [New - Windows 95]
 SOANGLETENTHS

[New - Windows 95]

SOANGLETENTHS(AngleInTenthsOfADegree)

Sets the angle in tenths of a degree.


SOPALETTEINDEX [New - Windows 95]
 SOPALETTEINDEX

[New - Windows 95]

SOPALETTEINDEX(Index)

Creates a palette-index color value. Index must specify a valid palette entry index. When this color value is used, the system uses the color from the given palette entry.


SOPALETTERGB [New - Windows 95]
 SOPALETTERGB

[New - Windows 95]

SOPALETTERGB(Red, Green, Blue)

Creates a palette-relative RGB color value. Red, Green, and Blue specify the red, green, and blue color intensities and must be in the range 0 to 255. When this color value is specified, the system uses the palette entry that has the color that most closely matches this value.


SORGB [New - Windows 95]
 SORGB

[New - Windows 95]

SORGB(Red, Green, Blue)

Creates an RGB color value. Red, Green, and Blue specify the red, green, and blue color intensities and must be in the range 0 to 255.


SOSETRATIO [New - Windows 95]
 SOSETRATIO

[New - Windows 95]

SOSETRATIO(Numerator, Denominator)

Sets the ratio. Numerator and Denominator specify the ratio factors and must be values in the range 0 to 65,535.


 Structures

The following structures are used with file parsers.


SOARCINFO [New - Windows 95]
 SOARCINFO

[New - Windows 95]

typedef struct SOARCINFOtag {
    SORECT Rect;        // see below
    SOANGLE StartAngle; // see below
    SOANGLE EndAngle;   // see below
} SOARCINFO, VWPTR *PSOARCINFO;

Contains information defining the arc to be drawn.

Rect

Rectangle that bounds the ellipse containing the arc.

StartAngle

Angle specifying the starting point of the arc. The angle is defined in tenths of a degree, counterclockwise from the positive x-axis. To set this member, use the SOANGLETENTHS macro.

EndAngle

Angle specifying the ending point of the arc. The angle is defined in tenths of a degree, counterclockwise from the positive x-axis. To set this member, use the SOANGLETENTHS macro.


SOBITMAPHEADER [New - Windows 95]
 SOBITMAPHEADER

[New - Windows 95]

typedef struct SOBITMAPHEADERtag {
    WORD wStructSize;   // see below
    WORD wImageFlags;   // see below
    WORD wImageWidth;   // see below
    WORD wImageLength;  // see below
    WORD wTileWidth;    // see below
    WORD wTileLength;   // see below
    WORD wBitsPerPixel; // see below
    WORD wNPlanes;      // see below
    WORD wHDpi;         // see below
    WORD wVDpi;         // see below
} SOBITMAPHEADER, VWPTR *PSOBITMAPHEADER;

Contains information about the bitmap to be output.

wStructSize

Size, in bytes, of the structure.

wImageFlags

Image flags. This member can be a combination of one (and only one) color format value and other attribute values.

The color format can be one of these values:

SO_BGRCOLOR	Pixel values are RGB color values (24-bit only); bytes are stored consecutively in the order B,G,R.
SO_BLACKANDWHITE	Pixels are black or white (1 bit per pixel only).
SO_COLORPALETTE	Pixel values are indexes into the color palette for the bitmap.
SO_GRAYSCALE	Pixel values are gray scale values.
SO_RGBCOLOR	Pixel values are RGB color values (24-bit only); bytes are stored consecutively in the order R,G,B.
Other attributes can be a combination of these values:

SO_BOTTOMTOTOP	The image is provided in scan lines from the bottom up. The default is top to bottom.
SO_WHITEZERO	For gray scale images and black and white images only, a pixel with a value of zero is a white pixel, and increasing pixel values become darker. By default, a value of zero is defined as a black pixel with increasing values becoming lighter.
wImageWidth

Horizontal width, in pixels, of the image.

wImageLength

Vertical length, in pixels, of the image.

wTileWidth

Horizontal width, in pixels, of the tile.

wTileLength

Vertical length, in pixels, of the tile.

wBitsPerPixel

Number of consecutive bits that define the pixel color. The number is currently limited to 1, 4, 8, or 24.

wNPlanes

Color planes. This member must be 1.

wHDpi

Horizontal resolution, in pixels per inch, of the display on which the image originated. If the resolution is not known, this member can be zero.

wVDpi

Vertical resolution, in pixels per inch, of the display on which the image originated. If the resolution is not known, this member can be zero.


SOBORDER [New - Windows 95]
 SOBORDER

[New - Windows 95]

typedef struct SOBORDERtag {
    WORD wWidth;         // see below
    SOCOLORREF rgbColor; // see below
    WORD wFlags;         // see below
} SOBORDER, VWPTR * PSOBORDER;

Contains information about the border around a cell in table.

wWidth

Width, in twips, of the border.

rgbColor

Color of the border. This member can be a RGB color value. To set this member, use the SORGB macro.

wFlags

Type of border and the edges to which it applies. This member can be a combination of the SO_BORDERNONE, SO_BORDERDOUBLE, SO_BORDERHAIRLINE, SO_BORDERTHICK, SO_BORDERSHADOW, and SO_BORDERDOTTED values.


SOCOLUMN [New - Windows 95]
 SOCOLUMN

[New - Windows 95]

typedef struct SOCOLUMNtag {
    WORD wStructSize; // see below
    LONG dwWidth;     // see below
    char szName[40];  // see below
} SOCOLUMN, VWPTR * PSOCOLUMN;

Contains information about the columns in a spreadsheet.

wStructSize

Size, in bytes, of the structure.

dwWidth

Width, in characters, of the column.

szName

Null-terminated string specifying the name of the column.


SOCPARCANGLE [New - Windows 95]
 SOCPARCANGLE

[New - Windows 95]

typedef struct SOCPARCANGLEtag {
    SOPOINT Center;     // center point
    SOANGLE SweepAngle; // sweep angle
} SOCPARCANGLE, VWPTR *PSOCPARCANGLE;

Contains information defining an arc for use in vector graphics output.


SOCPPIEANGLE [New - Windows 95]
 SOCPPIEANGLE

[New - Windows 95]

typedef struct SOCPPIEANGLEtag {
    INT nRadius;        // radius
    SOANGLE StartAngle; // starting angle
    SOANGLE SweepAngle; // sweep angle
} SOCPPIEANGLE, VWPTR *PSOCPPIEANGLE;

Contains information defining a pie shape for use in vector graphics output.


SOCPTEXTATPOINT [New - Windows 95]
 SOCPTEXTATPOINT

[New - Windows 95]

typedef struct SOCPTEXTATPOINTtag {
    WORD wFormat;    // format of text
    INT nTextLength; // text length
} SOCPTEXTATPOINT, VWPTR *PSOCPTEXTATPOINT;

Contains information defining the format and length of text for use in vector graphics output.


SODATACELL [New - Windows 95]
 SODATACELL

[New - Windows 95]

typedef struct SODATACELLtag {
    WORD wStructSize;   //see below
    WORD wStorage;      //see below
    WORD wDisplay;      //see below
    DWORD dwSubDisplay; //see below
    WORD wPrecision;    //see below
    WORD wAlignment;    //see below
    WORD wAttribute;    //see below
    union {
        SOINT32S Int32S; //see below
        SOINT32U Int32U; //see below
        BYTE IEEE4[4];   //see below
        BYTE IEEE8[8];   //see below
        BYTE IEEE10[10]; //see below
        BYTE BCD8[8];    //see below
    } uStorage;
} SODATACELL, VWPTR * PSODATACELL;

Contains information about the data to be placed in a cell of a spreadsheet.

wStructSize

Size, in bytes, of the structure.

wStorage

Storage type. This member can be one of these values:

SO_CELLBCD8I	Packed BCD excess-63.
SO_CELLEMPTY	The cell is empty.
SO_CELLERROR	The cell has an error condition.
SO_CELLIEEE4I	IEEE 4-byte in Intel® (PC) ordering.
SO_CELLIEEE8I	IEEE 8-byte in Intel (PC) ordering.
SO_CELLIEEE10I	IEEE 10-byte in Intel (PC) ordering.
SO_CELLINT32S	32-bit signed integer.
SO_CELLINT32U	32-bit unsigned integer.
wDisplay

Display type. This member can be one of these values:

SO_CELLBOOL	Boolean (0 = FALSE and 1 = TRUE).
SO_CELLDATE	Julian Days since the base date. wStorage may be either an IEEE or integer value.
SO_CELLDATETIME	Julian Days since the base date. wStorage may be either an IEEE or integer value.
SO_CELLDECIMAL	Decimal notation.
SO_CELLDOLLARS	Dollar sign.
SO_CELLEXPONENT	Exponential notation.
SO_CELLNUMBER	General number format.
SO_CELLPERCENT	Percent (not constrained to 0 − 100).
SO_CELLTIME	Decimal part of a day if wStorage is an IEEE value or seconds since 00:00 if wStorage is an integer value.
dwSubDisplay

Display subtype. The values depend on wDisplay value.

For SO_CELLNUMBER and SO_CELLDOLLARS, this member can be a combination of one negative-number format, thousands separator, and cell multiplier.

Negative Number Format
SO_CELLNEG_MINUS	Negative numbers have a minus sign.
SO_CELLNEG_MINUSRED	Negative numbers have a minus sign and are red.
SO_CELLNEG_PAREN	Negative numbers have parentheses.
SO_CELLNEG_PARENRED	Negative numbers have parentheses and are red.
Thousands Separator
SO_CELL1000SEP_COMMA	Commas as 1,000s separator.
SO_CELL1000SEP_NONE	No 1000s separator.
Cell Multiplier
SO_CELLMULT_1	Used for all file parsers.
SO_CELLMULT_01	Used only for Microsoft® Excel viewer.
SO_CELLMULT_05	Used only for Lotus viewer.
SO_CELLMULT_005	Used only for Lotus viewer.
SO_CELLMULT_0005	Used only for Lotus viewer.
SO_CELLMULT_00005	Used only for Lotus viewer.
SO_CELLMULT_500	Used only for Lotus viewer.
SO_CELLMULT_5000	Used only for Lotus viewer.
SO_CELLMULT_0625	Used only for Lotus viewer.
SO_CELLMULT_015625	Used only for Lotus viewer.
For SO_CELLDATETIME, SO_CELLDATE, and SO_CELLTIME, this member can be a combination of one date separator, day format, month format, year format, day of week format, and time format.

Date Separator
SO_CELLDATESEP_MINUS
SO_CELLDATESEP_NONE
SO_CELLDATESEP_PERIOD
SO_CELLDATESEP_SPACE
Day Format
SO_CELLDAY_NONE
SO_CELLDAY_NUMBER
Month Format
SO_CELLMONTH_ABBREV
SO_CELLMONTH_FULL
SO_CELLMONTH_NONE
SO_CELLMONTH_NUMBER
Year Format
SO_CELLYEAR_ABBREV
SO_CELLYEAR_FULL
SO_CELLYEAR_NONE
Day of Week Format
SO_CELLDAYOFWEEK_ABBREV
SO_CELLDAYOFWEEK_FULL
SO_CELLDAYOFWEEK_NONE
Time Format
SO_CELLTIME_HHMM24
SO_CELLTIME_HHMMAM
SO_CELLTIME_HHMMHMS	For example, 14h45m
SO_CELLTIME_HHMMSS24
SO_CELLTIME_HHMMSSAM
SO_CELLTIME_HHMMSSHMS	For example, 14h45m34s
SO_CELLTIME_NONE
wPrecision

Precision or positioning value, depending on the wDisplay value.

For SO_CELLNUMBER and SO_CELLDOLLARS, this member specifies the number of places to the right of the decimal point.

For SO_CELLDATETIME, SO_CELLDATE, and SO_CELLTIME, this member specifies the position in the date time string of each element. It must be a combination of one value for each of the day of week position, month position, day position, year position, and time position.

Day of Week Position
SO_CELLDAYOFWEEK_1
SO_CELLDAYOFWEEK_2
SO_CELLDAYOFWEEK_3
SO_CELLDAYOFWEEK_4
SO_CELLDAYOFWEEK_5
Month Position
SO_CELLMONTH_1
SO_CELLMONTH_2
SO_CELLMONTH_3
SO_CELLMONTH_4
SO_CELLMONTH_5
Day Position
SO_CELLDAY_1
SO_CELLDAY_2
SO_CELLDAY_3
SO_CELLDAY_4
SO_CELLDAY_5
Year Position
SO_CELLYEAR_1
SO_CELLYEAR_2
SO_CELLYEAR_3
SO_CELLYEAR_4
SO_CELLYEAR_5
Time Position
SO_CELLTIME_1
SO_CELLTIME_2
SO_CELLTIME_3
SO_CELLTIME_4
SO_CELLTIME_5
wAlignment

Alignment of data in the cell. This member can be the SO_CELLLEFT, SO_CELLRIGHT, or SO_CELLCENTER value.

wAttribute

Attribute of data in the cell. This member can be a combination of the SO_CELLBOLD, SO_CELLITALIC, SO_CELLUNDERLINE, and SO_CELLSTRIKEOUT values.

Int32S

Signed 32-bit integer.

Int32U

Unsigned 32-bit integer.

IEEE4

Four-byte array representing an IEEE 4-byte floating-point number.

IEEE8

Eight-byte array representing an IEEE 8-byte floating-point number.

IEEE10

Ten-byte array representing an IEEE 10-byte floating-point number.

BCD8

Eight-byte array representing an excess-63 floating-point packed BCD.


SOEMBEDDEDGRAPHIC [New - Windows 95]
 SOEMBEDDEDGRAPHIC

[New - Windows 95]

typedef struct SOEMBEDDEDGRAPHICtag {
    SOPOINT Size;       // see below
    SORECT Crop;        // see below
    SOPOINT ScaledSize; // see below
    WORD wBorder;       // see below
    DWORD dwFlags;      // see below
} SOEMBEDDEDGRAPHIC;

Contains information about the size and positioning of an embedded graphics object.

Size

Initial size of the image before scaling and cropping.

Crop

Cropping amount on the top, bottom, left, and right edges.

ScaledSize

Final size of the image after scaling and cropping.

wBorder

Border thickness, in twips. If this member is zero, there is no border.

dwFlags

Flags. This member can be a combination of these values:

SO_CENTERIMAGE	The image is centered in its final rectangle.
SO_MAINTAINASPECT	The image aspect ratio is preserved.


SOEMBEDDEDOBJECT [New - Windows 95]
 SOEMBEDDEDOBJECT

[New - Windows 95]

typedef struct SOEMBEDDEDOBJECTtag {
    WORD wStructSize;   // see below
    WORD wObjectType;   // see below
    char szFile[144];   // see below
    WORD wFIType;       // see below
    DWORD dwFileOffset; // see below
    SOEMBEDINFO Info;   // see below
} SOEMBEDDEDOBJECT, VWPTR * PSOEMBEDDEDOBJECT;

Contains information about an embedded object.

wStructSize

Size, in bytes, of the structure.

wObjectType

Type of object type. This member can be the SOEMBED_GRAPHIC or SO_UNKNOWN value.

szFile

Null-terminated string specifying the path and filename of the file that contains the object. If the object is in the current file, this member is NULL.

wFIType

File identifier for object's file. If the object type is the SO_UNKNOWN value, this member is zero.

dwFileOffset

Offset, in bytes, to the embedded object from the start of the given file.

Info

Union containing object-specific information.


SOEMBEDINFO [New - Windows 95]
 SOEMBEDINFO

[New - Windows 95]

typedef union SOEMBEDINFOtag {
    SOEMBEDDEDGRAPHIC Graphic; // embedded graphics structure
} SOEMBEDINFO;

Contains information specific to embedded graphics objects.


SOFIELD [New - Windows 95]
 SOFIELD

[New - Windows 95]

typedef struct SOFIELDtag {
    WORD wStructSize;
    LONG dwWidth;
    char szName[40];
    WORD wStorage;
    WORD wDisplay;
    DWORD dwSubDisplay;
    WORD wPrecision;
    WORD wAlignment;
} SOFIELD, VWPTR * PSOFIELD;

Contains information about a field in a database.

wStructSize

Size, in bytes, of the structure.

dwWidth

Width, in characters, of the column.

szName

Null-terminated string specifying the name of the field.

wStorage

Storage type. This member can be one of these values:

SO_CELLBCD8I	Packed BCD excess-63.
SO_CELLEMPTY	The cell is empty.
SO_CELLERROR	The cell has an error condition.
SO_CELLIEEE4I	IEEE 4-byte in Intel (PC) ordering.
SO_CELLIEEE8I	IEEE 8-byte in Intel (PC) ordering.
SO_CELLIEEE10I	IEEE 10-byte in Intel (PC) ordering.
SO_CELLINT32S	32-bit signed integer.
SO_CELLINT32U	32-bit unsigned integer.
SO_FIELDTEXTFIX	The field contains a string of fixed length.
SO_FIELDTEXTVAR	The field contains a string of unknown length.
wDisplay

Display type. For more information, see the wDisplay member in the SODATACELL structure.

dwSubDisplay

Display subtype. For more information, see the dwSubDisplay member in the SODATACELL structure.

wPrecision

Precision or positioning value. For more information, see the wPrecision member in the SODATACELL structure.

If wStorage is the SO_FIELDTEXTFIX value, this member specifies the number of characters in the string.

wAlignment

Alignment of data in the cell. This member can be the SO_CELLLEFT, SO_CELLRIGHT, or SO_CELLCENTER value.


SOFILTERINFO [New - Windows 95]
 SOFILTERINFO

[New - Windows 95]

typedef struct SOFILTERINFOtag {
    INT wFilterCharSet;      // see below
    U_BYTE szFilterName[32]; // see below
} SOFILTERINFO;

Contains information identifying the file parser.

wFilterCharSet

Character set used for text by the file parser. This member must be the SO_WINDOWS value.

szFilterName

Null-terminated string specifying the name of the file parser. The name should identify either the format of the files being parsed or the product that created the files.


SOGROUPINFO [New - Windows 95]
 SOGROUPINFO

[New - Windows 95]

typedef struct SOGROUPINFOtag {
    WORD wStructSize;    // see below
    SORECT BoundingRect; // see below
    INT nTransforms;     // see below
} SOGROUPINFO, VWPTR *PSOGROUPINFO;

Contains information about a group for use with vector graphics output.

wStructSize

Size, in bytes, of the structure.

BoundingRect

Rectangle that bounds all points displayed in the group. This rectangle does not cause clipping to occur. If clipping is needed, a clipping path must be selected.

nTransforms

Number of transformation structures following this structure.


SOLOGBRUSH [New - Windows 95]
 SOLOGBRUSH

[New - Windows 95]

typedef struct SOLOGBRUSHtag {
    WORD lbStyle;       // see below
    SOCOLORREF lbColor; // see below
    INT lbHatch;        // see below
} SOLOGBRUSH, VWPTR *PSOLOGBRUSH;

Contains information defining a logical brush for use with vector graphics output.

lbStyle

Brush style. This member can be the SOBS_HATCHED, SOBS_HOLLOW, or SOBS_SOLID value.

lbColor

Color of the brush. This member can be an RGB or palette-relative value. To set this member, use the SORGB or SOPALETTE macro.

lbHatch

Hatch style. This member is used only if lbStyle is SO_HATCHED. This member can be the SOHS_BDIAGONAL, SOHS_CROSS, SOHS_DIAGCROSS, SOHS_FDIAGONAL, SOHS_HORIZONTAL, or SOHS_VERTICAL value.

For a complete definition of the members, see the LOGBRUSH structure.


SOLOGFONT [New - Windows 95]
 SOLOGFONT

[New - Windows 95]

typedef struct SOLOGFONTtag {
    INT lfHeight;                   // font height
    INT lfWidth;                    // font width
    INT lfEscapement;               // angle of text line
    INT lfOrientation;              // angle of character baseline
    INT lfWeight;                   // font weight
    BYTE lfItalic;                  // italics
    BYTE lfUnderline;               // underline
    BYTE lfStrikeOut;               // strikeout
    BYTE lfCharSet;                 // character set
    BYTE lfOutputPrecision;         // output precision
    BYTE lfClipPrecision;           // clipping precision
    BYTE lfQuality;                 // output quality
    BYTE lfPitchAndFamily;          // pitch and family of font
    BYTE lfFaceName[SOLF_FACESIZE]; // typeface name of font
} SOLOGFONT, VWPTR *PSOLOGFONT;

Contains information that defines a logical font for use with vector graphics output. The lfHeight and lfWidth members must be in the same logical units as all of the other drawing commands. For a description of the members, see the LOGFONT structure.


SOLOGPEN [New - Windows 95]
 SOLOGPEN

[New - Windows 95]

typedef struct SOLOGPENtag {
    INT loPenStyle;     // see below
    SOPOINT loWidth;    // see below
    SOCOLORREF loColor; // see below
} SOLOGPEN, VWPTR *PSOLOGPEN;

Contains information that defines a logical pen for use with vector graphics output. For a complete definition of the members, see the LOGPEN structure.

loPenStyle

Pen Style. This member can be the SOPS_SOLID, SOPS_DASH, SOPS_DOT, SOPS_DASHDOT, SOPS_DASHDOTDOT, SOPS_NULL, or SOPS_INSIDEFRAME value.

loWidth

Width, in logical units, of the pen. The x member in the POINT structure is used, and the y member is ignored.

loColor

Color of the brush. This member can be an RGB or palette-relative value. To set this member, use the SORGB or SOPALETTE macro.


SOPARAINDENTS [New - Windows 95]
 SOPARAINDENTS

[New - Windows 95]

typedef struct SOPARAINDENTStag {
    INT FirstLineIndent; // see below
    INT LeftIndent;      // see below
    INT RightIndent;     // see below
} SOPARAINDENTS, VWPTR *PSOPARAINDENTS;

Contains information about paragraph indents for use with vector graphics output.

FirstLineIndent

Distance, from the left edge of the frame, to indent the first line of each paragraph.

LeftIndent

Distance, from the left edge of the frame, to indent all lines but the the first line of each paragraph.

RightIndent

Distance, from the right edge of the frame, to indent all lines of each paragraph.


SOPATHINFO [New - Windows 95]
 SOPATHINFO

[New - Windows 95]

typedef struct SOPATHINFOtag {
    WORD wStructSize;    // see below
    SORECT BoundingRect; // see below
    INT nTransforms;     // see below
} SOPATHINFO, VWPTR *PSOPATHINFO;

Contains information about a path for use with vector graphics output.

wStructSize

Size, in bytes, of the structure.

BoundingRect

Rectangle that bounds all points displayed in the path. This rectangle does not cause clipping to occur. If clipping is needed, a clipping path must be selected.

nTransforms

Number of transformation structures following this structure.


SOPOINT [New - Windows 95]
 SOPOINT

[New - Windows 95]

typedef struct SOPOINTtag {
    INT x;  // x-coordinate
    INT y;  // y-coordinate
} SOPOINT, VWPTR *PSOPOINT;

Contains coordinates for a point.


SOPOLYINFO [New - Windows 95]
 SOPOLYINFO

[New - Windows 95]

typedef struct SOPOLYINFOtag {
    WORD wFormat; // see below
    INT nPoints;  // see below
} SOPOLYINFO, VWPTR *PSOPOLYINFO;

Contains information about the type and number of vertices of a polyline, polygon, spline, or Bezier curve.

wFormat

Format type. This member can be one of these values:

SOPT_BEZIERCLOSE	SOPT_POLYGON
SOPT_BEZIEROPEN	SOPT_POLYLINE
SOPT_CPPOLYGON	SOPT_SPLINECLOSE
SOPT_CPPOLYLINE	SOPT_SPLINEOPEN
nPoints

Number of vertices in the object.


SORECT [New - Windows 95]
 SORECT

[New - Windows 95]

typedef struct SORECTtag {
    INT left;    // x-coordinate of upper left corner
    INT top;     // y-coordinate of upper left corner
    INT right;   // x-coordinate of lower right corner
    INT bottom;  // y-coordinate of lower right corner
} SORECT, VWPTR *PSORECT;

Contains the dimensions of a rectangle.


SOTAB [New - Windows 95]
 SOTAB

[New - Windows 95]

typedef struct SOTABtag {
    WORD wType;    // see below
    WORD wChar;    // see below
    WORD wLeader;  // see below
    LONG dwOffset; // see below
} SOTAB, VWPTR * PSOTAB;

Contains information about tab stops.

wType

Type of tab stop. This member can be the SO_TABLEFT, SO_TABRIGHT, SO_TABCENTER, or SO_TABCHAR value.

wChar

Alignment character if wType is SO_TABCHAR. Tabs are aligned on this character.

wLeader

Repeating leader character for the tab. If this member is zero, there is no leader.

dwOffset

Offset of the tab from the left page margin.


SOTABLECELLINFO [New - Windows 95]
 SOTABLECELLINFO

[New - Windows 95]

typedef struct SOTABLECELLINFOtag {
    WORD wWidth;             // see below
    WORD wMerge;             // see below
    WORD wShading;           // see below
    PSOBORDER pLeftBorder;   // see below
    PSOBORDER pRightBorder;  // see below
    PSOBORDER pTopBorder;    // see below
    PSOBORDER pBottomBorder; // see below
} SOTABLECELLINFO, VWPTR *PSOTABLECELLINFO;

Contains information about cells in a table.

wWidth

Width, in twips, of the cell.

wMerge

Merge flag specifying whether the cell is merged with any neighboring cells. This member can be a combination of the SO_MERGELEFT, SO_MERGERIGHT, SO_MERGEABOVE, and SO_MERGEBELOW values.

wShading

Intensity value for background shading in the range of 0 to 255. If this member is zero, there is no background shading.

pLeftBorder

Left border.

pRightBorder

Right border.

pTopBorder

Top border.

pBottomBorder

Bottom border.


SOTEXTATARCANGLE [New - Windows 95]
 SOTEXTATARCANGLE

[New - Windows 95]

typedef struct SOTEXTATARCANGLEtag {
    SOARCINFO ArcInfo; // see below
    WORD wFormat;      // see below
    INT nTextLength;   // see below
} SOTEXTATARCANGLE, VWPTR *PSOTEXTATARCANGLE;

Contains information about text for use with vector graphics output.

ArcInfo

Arc information defining the arc relative to which the text is located. Only the starting angle is used to locate the point; the ending angle is ignored.

wFormat

Alignment format, indicating the relationship between the given point and the base line or bounding rectangle of the text. This member can be a combination of these values:

SOTA_BASELINE	Aligns the point and base line of the font.
SOTA_BOTTOM	Aligns the point and bottom of the bounding rectangle.
SOTA_CENTER	Aligns the point and horizontal center of the bounding rectangle.
SOTA_LEFT	Aligns the point and left side of the bounding rectangle.
SOTA_RIGHT	Aligns the point and right side of the bounding rectangle.
SOTA_TOP	Aligns the point and top of the bounding rectangle.
nTextLength

Length of text string that follows the structure.


SOTEXTATPOINT [New - Windows 95]
 SOTEXTATPOINT

[New - Windows 95]

typedef struct SOTEXTATPOINTtag {
    SOPOINT Point;   // see below
    WORD wFormat;    // see below
    INT nTextLength; // see below
} SOTEXTATPOINT, VWPTR *PSOTEXTATPOINT;

Contains information about text at a point.

Point

Point that locates the text.

wFormat

Alignment format, indicating the relationship between the point and the base line or bounding rectangle of the text. This member can be a combination of these values:

SOTA_BASELINE	Aligns the point and base line of the font.
SOTA_BOTTOM	Aligns the point and bottom of the bounding rectangle.
SOTA_CENTER	Aligns the point and horizontal center of the bounding rectangle.
SOTA_LEFT	Aligns the point and left side of the bounding rectangle.
SOTA_RIGHT	Aligns the point and right side of the bounding rectangle.
SOTA_TOP	Aligns the point and top of the bounding rectangle.
nTextLength

Length of the text string that follows the structure.


SOTEXTCELL [New - Windows 95]
 SOTEXTCELL

[New - Windows 95]

typedef struct SOTEXTCELLtag {
    WORD wStructSize; // see below
    WORD wAlignment;  // see below
    WORD wAttribute;  // see below
} SOTEXTCELL, VWPTR * PSOTEXTCELL;

Contains information about the alignment and attributes of text in a spreadsheet cell.

wStructSize

Size, in bytes, of the structure.

wAlignment

Alignment. This member can be the SO_CELLLEFT, SO_CELLRIGHT, SO_CELLCENTER, or SO_CELLFILL value.

wAttribute

Attributes. This member can be a combination of the SO_CELLBOLD, SO_CELLITALIC, SO_CELLUNDERLINE, and SO_CELLSTRIKEOUT values.


SOTEXTINRECT [New - Windows 95]
 SOTEXTINRECT

[New - Windows 95]

typedef struct SOTEXTINRECTtag {
    SORECT Rect;     // see below
    WORD wFormat;    // see below
    INT nTextLength; // see below
} SOTEXTINRECT, VWPTR *PSOTEXTINRECT;

Contains information about text for use with vector graphics output.

Rect

Rectangle in which text is formatted.

wFormat

Format of the string. This member can be a combination of these values:

SODT_BOTTOM	SODT_NOPREFIX
SODT_CALCRECT	SODT_RIGHT
SODT_CENTER	SODT_SINGLELINE
SODT_EXPANDTABS	SODT_TABSTOP
SODT_EXTERNALLEADING	SODT_TOP
SODT_LEFT	SODT_VCENTER
SODT_NOCLIP	SODT_WORDBREAK
nTextLength

Length of the text string that follows the structure.


SOTRANSFORM [New - Windows 95]
 SOTRANSFORM

[New - Windows 95]

typedef struct SOTRANSFORMtag {
    WORD wTransformFlags;  // see below
    SOPOINT Origin;        // see below
    INT xOffset;           // see below
    INT yOffset;           // see below
    SORATIO xScale;        // see below
    SORATIO yScale;        // see below
    SORATIO xSkew;         // see below
    SORATIO ySkew;         // see below
    SOANGLE RotationAngle; // see below
} SOTRANSFORM, VWPTR *PSOTRANSFORM;

Contains information about a transformation for use with vector graphics output.

wTransformFlags

Type of transformation. This member can be a combination of these values:

SOTF_NOTRANSFORM	SOTF_XSKEW
SOTF_ROTATE	SOTF_YOFFSET
SOTF_XOFFSET	SOTF_YSCALE
SOTF_XSCALE	SOTF_YSKEW
TSOTF_ROTATE may be combined only with SOTF_XOFFSET and SOTF_YOFFSET. In addition, no other values may be combined with SOTF_NOTRANSFORM.

Origin

Point of origin for all transformations, except for SOTF_XOFFSET and SOTF_YOFFSET.

xOffset and yOffset

Offset values to use for the SOTF_XOFFSET and OTF_YOFFSET transformations. The x and y members of this value are added to the x- and y-coordinates of all points in the transformed object.

xScale

Ratio to use for SOTF_XSCALE transformations. This ratio is used to scale the image on the x-axis from the given origin. To set this member, use the SOSETRATIO macro.

yScale

Ratio to use for SOTF_YSCALE transformations. This ratio is used to scale the image on the y-axis from the given origin. To set this member, use the SOSETRATIO macro.

xSkew

Ratio to use for SOTF_XSKEW transformations. This ratio used to skew the image horizontally from the given origin. To set this member, use the SOSETRATIO macro.

ySkew

Ratio to use for SOTF_YSKEW transformations. This ratio used to skew the image vertically from the given origin. To set this member, use the SOSETRATIO macro.

RotationAngle

Angle, in tenths of a degree, to use for SOTF_ROTATE transformations. All points are rotated this many degrees about the given origin. This value must be set by using the SOANGLETENTHS macro. A SOANGLE variable should not be set directly. Additional macros will be made available as needed.

The transformation equation follows.

x' = Origin.x + (xScale * (x-Origin.x)) + (xSkew*(y-Origin.y)) + xOffset
y' = Origin.y + (yScale * (y-Origin.y)) + (ySkew*(x-Origin.x)) + yOffset


SOVECTORHEADER [New - Windows 95]
 SOVECTORHEADER

[New - Windows 95]

typedef struct SOVECTORHEADERtag {
    WORD wStructSize;    // see below
    SORECT BoundingRect; // see below
    WORD wHDPI;          // see below
    WORD wVDPI;          // see below
    WORD wImageFlags;    // see below
    SOCOLOR BkgColor;    // see below
} SOVECTORHEADER, VWPTR *PSOVECTORHEADER;

Contains information defining the size and attributes of the rectangle in which vector graphics are drawn.

wStructSize

Size, in bytes, of the structure.

BoundingRect

Rectangle that bounds all drawing commands.

wHDpI

Dots per inch resolution along the x-axis.

wVDpI

Dots per inch resolution along the y-axis.

wImageFlags

Image flags. This member can be a combination of these values:

SO_VECTORCOLORPALETTE	Uses a color palette. Color values must be palette entry indexes or palette-relative RGB values.
SO_VECTORRGBCOLOR	Uses RGB color values.
SO_XISLEFT	Has positive x-coordinates left of the y-axis.
SO_YISUP	Has positive y-coordinates up from the x-axis.
BkgColor

Color of the background in the bounding rectangle. This value must be set by using one of the three color macros: SOPALETTEINDEX, SORGB, or SOPALETTERGB. However, SORGB should not be used if a palette is defined.


 Constants

The following vector object values and vector attribute values are used with the vector graphics functions.


Vector Object Values [New - Windows 95]
 Vector Object Values

[New - Windows 95]

SO_ARC

Draws an arc. dwDataSize must be 4* sizeof(SOPOINT), and pData must be the address of four SOPOINT structures.

SO_ARCCLOCKWISE

Draws an arc in the clockwise direction. dwDataSize must be 4* sizeof(SOPOINT), and pData must be the address of four SOPOINT structures.

SO_ARCANGLE

Draws an arc by defining the angles of the two points on the ellipse that locate the start and end of the arc. dwDataSize must be sizeof(SOARCINFO), and pData must be the address of a SOARCINFO structure that defines the arc.

SO_ARCANGLECLOCKWISE

Draws an arc in the clockwise direction by defining the angles of the two points on the ellipse that locate the start and end of the arc. dwDataSize must be sizeof(SOARCINFO), and pData must be the address of a SOARCINFO structure.

SO_CHORD

Draws a chord. dwDataSize must be 4 * sizeof(SOPOINT), and pData must be the address of four SOPOINT structures.

SO_CHORDANGLE

Draws a chord by defining the angles of the two points on the ellipse that locate the start and end of the chord. dwDataSize must be sizeof(SOARCINFO), and pData must be the address of a SOARCINFO structure that defines the chord in terms of the arc located on the chord.

SO_TEXTINRECT

Draws text in a rectangle. dwDataSize must be sizeof(SOTEXTINRECT) added to the length of the text string, and pData must be the address of a SOTEXTINRECT structure followed by the text string.

SO_ELLIPSE

Draws an ellipse. dwDataSize must be 2 * sizeof(SOPOINT), and pData must be the address of two SOPOINT structures.

SO_FLOODFILL

Fills the area with the given color. dwDataSize must be sizeof(SOPOINT) added to sizeof(SOCOLORREF), and pData must be the address of a variable containing the coordinates of the point to start at followed by the RGB color value to use to fill the area.

SO_LINE

Draws a line from point 1 to point 2 using the current pen. dwDataSize must be 2 * sizeof(SOPOINT), and pData must be the address of two SOPOINT structures.

SO_PIE

Draws a pie shape. dwDataSize must be 4 * sizeof(SOPOINT), and pData must be the address of four SOPOINT structures.

SO_PIEANGLE

Draws a pie by defining the angles of the two points on the ellipse that locate the start and end of the pie. dwDataSize must be sizeof(SOARCINFO), and pData must be the address of a SOARCINFO structure that defines the pie in terms of the arc located on the pie.

SO_STARTPOLY

Starts drawing of a polygon. dwDataSize must be sizeof(SOPOLYINFO), and pData must be the address of a SOPOLYINFO structure.

SO_POINTS

Specifies vertices of a polygon. dwDataSize must be N * sizeof(SOPOINT), and pData must be the address of consecutively stored SOPOINT structures. At most, SOMAXPOINTS can be passed in a single SO_POINTS object. Multiple SO_POINTS objects can be generated to define all of the points associated with a polygon object. The number of points defined in SO_STARTPOLY must be defined using SO_POINTS before the object is closed with SO_ENDPOLY.

SO_ENDPOLY

Ends drawing of a polygon. dwDataSize must be zero, and pData must be NULL.

SO_RECTANGLE

Draws a rectangle. dwDataSize must be 2 * sizeof(SOPOINT), and pData must be the address of two SOPOINT structures.

SO_ROUNDRECT

Draws a rectangle with rounded corners. dwDataSize must be 3 * sizeof(SOPOINT), and pData must be address of the three SOPOINT structures.

SO_SETPIXEL

Sets the color of a pixel. dwDataSize must be sizeof(SOPOINT) added to sizeof(SOCOLORREF), and pData must be the address of a variable containing the pixel point followed by the RGB color value to set.

SO_TEXTATPOINT

Draws text at the given point. dwDataSize must be sizeof(SOTEXTATPOINT) added to the length of the text string, and pData must be the address of a SOTEXTATPOINT structure followed by the text string.

SO_TEXTATARCANGLE

Draws text at the given location. dwDataSize must be sizeof(SOTEXTATARCANGLE) added to the length of the text string, and pData must be the address of a SOTEXTATARCANGLE structure followed by the text string.

SO_BEGINPATH

Starts the definition of a path. dwDataSize must be sizeof(SOPATHINFO) added to GroupInfo.nTransforms*sizeof(SOTRANSFORM), and pData must be the address of a SOPATHINFO structure followed by the number of SOTRANSFORM structures defined in the nTransforms member of the SOPATHINFO structure. The transformations will occur to all objects in the path in the order supplied. For more information, see the SO_OBJECTTRANSFORM vector attribute value.

This item is used to begin the definition of a path. Paths are a collection of points connected by lines that form opened or closed objects. Multiple subpaths may be created using SO_CLOSESUBPATH while defining a path. Note that the current object and group transformations will also apply during creation of a path. This allows maximum flexibility with transforming paths. Any object can be rendered to create the path. However, due to current limitations, text objects will not be added to the path. Multiple levels of paths are also allowed.

SO_ENDPATH

Ends the definition of a path. dwDataSize must be zero, and pData must be NULL.

SO_CLOSESUBPATH

Closes the current subpath. dwDataSize must be zero, and pData must be NULL.

SO_DRAWPATH

Strokes, fills, or both strokes and fills the current path with the current pen and brush. Since the group, path, and object transformations were applied when the path was created, they are not applied again. dwDataSize must be sizeof(WORD), and pData must be the address of a variable containing the SODP_STROKE or SODP_FILL value, or both.

SO_BEGINGROUP

Starts the definition of a group. dwDataSize must be sizeof(SOGROUPINFO) added to GroupInfo.nTransforms*sizeof(SOTRANSFORM), and pData must be the address of a SOGROUPINFO structure followed by the number of SOTRANSFORM structures defined in the nTransforms member of the SOGROUPINFO structure. The transformations will occur to all objects in the group in the order supplied. For more information, see the SO_OBJECTTRANSFORM vector attribute value.

SO_ENDGROUP

Ends the definition of a group. dwDataSize must be zero, and pData must be NULL.

SO_CPSET

Moves the current pen position to this point. dwDataSize must be sizeof(SOPOINT), and pData must be the address of the variable containing the point.

SO_CPLINE

Draws a line from the current pen position. dwDataSize must be sizeof(SOPOINT), and pData must be the address of a variable containing the point to draw to.

SO_CPRECTANGLE

Draws a rectangle starting at the current pen position. dwDataSize must be sizeof(SOPOINT), and pData must be the address of a variable containing the point to be the opposite corner of the rectangle.

SO_CPELLIPSE

Draws an ellipse around the current point with an x- and y-radius described by the SOPOINT data. dwDataSize must be sizeof(SOPOINT), and pData must be the address of a variable containing the x- and y-radius values.

SO_CPARCTRIPLE

Draws a circle arc from the current point through the first point and ending at the second point. dwDataSize must be 2*(sizeof(SOPOINT), and pData must be the address of two SOPOINT structures.

SO_CPARCANGLE

Draws an arc from the current point pivoting around the center point of the specified sweep angle. dwDataSize must be sizeof(SOCPARCANGLE), and pData must be the address of a SOCPARCANGLE structure that gives the center point of the arc and the sweep angle.

SO_CPPIEANGLE

Draws a pie with the current position as the center and with the given start and sweep angles. dwDataSize must be sizeof(SOCPPIECANGLE), and pData must be the address of a SOCPPIEANGLE structure that gives the radius of the circle.

SO_BEGINSYMBOL

Starts the definition of a symbol. A symbol is collection of vector commands that together make up a single symbol. Symbols are considered in the wrapping algorithm of frame text. dwDataSize must be sizeof(SORECT), and pData must be the address of a SORECT structure that identifies the bounding rectangle of all commands used within the symbol.

SO_ENDSYMBOL

Ends the definition of a symbol. dwDataSize must be zero, and pData must be NULL.

SO_BEGINTEXTFRAME

Starts the definition of a text frame. A text frame is used in conjunction with SO_TEXTINPARA to wrap text within a frame. Text is wrapped according to the SO_PARAINDENTS vector attribute value. Symbols are included in the wrapping algorithm. dwDataSize must be sizeof(SORECT), and pData must be the address of a SORECT structure that identifies the bounding rectangle of the text frame.

SO_ENDTEXTFRAME

Ends the definition of a text frame. dwDataSize must be zero, and pData must be NULL.

SO_TEXTINPARA

Draws the text string in the current font and text attributes at the current wrap location. The wrap location is moved by the text extent. Any words that would extend beyond the right indent of the frame are wrapped. This object is only valid within a text frame. dwDataSize must be sizeof(INT) added to the length of the text string, and pData must be the address of a integer variable containing the size of the text string that follows.

SO_PARAEND

Ends a paragraph. dwDataSize must be zero, and pData must be NULL.


Vector Attribute Values [New - Windows 95]
 Vector Attribute Values

[New - Windows 95]

SO_SELECTFONT

Selects the given font. dwDataSize must be sizeof(SOLOGFONT), and pData must be the address of a SOLOGFONT structure.

SO_SELECTPEN

Selects the given pen. dwDataSize must be sizeof(SOLOGPEN), and pData must be the address of a SOLOGPEN structure.

SO_SELECTBRUSH

Selects the given brush. dwDataSize must be sizeof(SOLOGBRUSH), and pData must be the address of a SOLOGBRUSH structure.

SO_POLYFILLMODE

Sets the polygon-filling mode. dwDataSize must be sizeof(INT), and pData must be the address of a variable containing either the SOPF_ALTERNATE or SOPF_WINDING value.

SO_TEXTCHAREXTRA

Sets the text character extra value. dwDataSize must be sizeof(INT), and pData must be the address of a variable containing a value. This attribute affects text objects.

SO_DRAWMODE

Sets the drawing mode used when drawing the pen and interiors. dwDataSize  must be sizeof(INT), and pData must be the address of a variable containing one of these values:

SOR2_BLACK	SOR2_NOT
SOR2_COPYPEN	SOR2_NOTCOPYPEN
SOR2_MASKNOTPEN	SOR2_NOTMASKPEN
SOR2_MASKPEN	SOR2_NOTMERGEPEN
SOR2_MASKPENNOT	SOR2_NOTXORPEN
SOR2_MERGENOTPEN	SOR2_WHITE
SOR2_MERGEPEN	SOR2_XORPEN
SOR2_NOP
SO_TEXTCOLOR

Sets the foreground color. dwDataSize must be sizeof(SOCOLORREF), and pData must be the address of a variable containing a RGB or palette-relative color value. To set this value, use the SORGB or SOPALETTE macro.

SO_BKMODE

Sets the background mode. dwDataSize must be sizeof(INT), and pData must be the address of a variable containing either the SOBK_OPAQUE or SOBK_TRANSPARENT value.

SO_BKCOLOR

Sets the background color used for styled lines, hatched brushes, and text when the background mode is SOBK_OPAQUE. dwDataSize must be sizeof(SOCOLORREF), and pData must be the address of a variable containing an RGB or palette-relative color value. To set this value, use the SORGB or SOPALETTE macro.

SO_OBJECTTRANSFORM

Sets object transformations. dwDataSize must be sizeof (INT) added to nCount*sizeof(SOTRANSFORM), and pData must be one INT (nCount) followed by that  number of SOTRANSFORM structures. The transformations will occur in the order supplied.

SO_CLIPMODE

Sets the clipping mode. dwDataSize must be sizeof(WORD), and pData must be the address of a variable containing either the SO_DONOTCLIP or SO_CLIPTOPATH value.

SO_POINTRELATION

Sets the coordinate orientation. dwDataSize must be sizeof(INT), and pData must be the address of a variable containing the SOPR_ABSOLUTE or SOPR_RELATIVE value.

SO_PARAINDENTS

Sets the paragraph indents within a text frame, defining the first, left, and right indents of paragraph text being built into the frame. These values are only valid when within a text frame. All values are in the current coordinate system. dwDataSize must be sizeof(SOPARAINDENTS), and pData must be the address of a SOPARAINDENTS structure.

SO_PARAALIGN

Sets the alignment of paragraph text being built into a text frame. dwDataSize must be sizeof(WORD), and pData must be the address of a 16-bit variable containing the SO_ALIGNLEFT, SO_ALIGNCENTER, SO_ALIGNRIGHT, or SO_ALIGNJUSTIFY value.


 Briefcase Reconcilers

A briefcase reconciler gives the Windows 95 Briefcase the means to reconcile different versions of a document.


 About Briefcase Reconcilers

A briefcase reconciler combines different input versions of a document to produce a single, new output version of the document. You may need to create a briefcase reconciler to support your type of document. This article describes briefcase reconcilers and explains how to create them.


 Reconciliation

A document is a collection of information that can be copied and changed. A document is said to have versions if the content of at least two copies of the document are different. Reconciliation produces a single version of a document from two or more initial versions. Typically, the final version is a combination of information from the initial versions with the most recent or most useful information preserved.

Reconciliation is initiated by the Briefcase when it determines that two or more copies of the same document are different. The Briefcase, which is called the initiator in this context, locates and starts the briefcase reconciler associated with the given document type. The reconciler compares the documents and determines which portions of the documents to retain. Some reconcilers may require user interaction to complete reconciliation. Others may complete reconciliation without user interaction. The reconciler can be contained within an application or be an extension implemented as a dynamic-link library (DLL).

Some briefcase reconcilers may create residues. A residue is a document, usually having the same file type as the initial document, that contains information not saved in the merged version. Residues are typically used to give authors a quick way to determine what information from their original document is not in the final merged version. If a reconciler supports residues, it creates one residue for each of the original versions of the document. Residues are not created unless the initiator requests them. The Briefcase does not currently request residues, but future initiators may.

Some briefcase reconcilers work in conjunction with the Briefcase to provide the user with a means to terminate reconciliation. This capability is useful for a user who may decide that the reconciliation should not proceed. A reconciler typically provides a termination object when the reconciliation requires user interaction and may be lengthy. In some environments, a reconciler may allow partial reconciliation, enabling a user to temporarily suspend a reconciliation and resume it later. The Briefcase does not currently support partial reconciliation, but future initiators may.


 Creating a Briefcase Reconciler

You create a briefcase reconciler by implementing the reconciliation interfaces. At a minimum, a reconciler implements the IReconcilableObject interface and the IPersistStorage or IPersistFile interface. As the initiator, the Briefcase determines when reconciliation is needed and calls the IReconcilableObject::Reconcile member function to initiate reconciliation.

Although the Reconcile member function can provide a wide-ranging set of reconciliation capabilities, a briefcase reconciler carries out only minimal reconciliation in most cases. In particular, the Briefcase does not require the reconciler to support residue generation or to support the termination object. Also, the reconciler carries out a single top to bottom reconciliation and must not return the REC_E_NOTCOMPLETE value; that is, it should not attempt partial reconciliation.

The Briefcase provides the IReconcileInitiator interface. The briefcase reconciler can use the IReconcileInitiator::SetAbortCallback member function to set the termination object. The Briefcase does not use version identifiers and can, therefore, not provide previous versions of a document if a reconciler requests them using the corresponding member functions in IReconcileInitiator.

The Briefcase passes file monikers to Reconcile representing the versions of the document to be reconciled. The briefcase reconciler gains access to the versions by using either the IMoniker::BindToObject or IMoniker::BindToStorage member function. The latter is generally faster and is recommended. The reconciler must release any objects or storage to which it binds.

When the briefcase reconciler uses BindToStorage, it binds to storage that is either flat storage (a stream) or OLE-defined structured storage. If the reconciler expects flat storage, it should use BindToStorage to request the IStream interface. If the reconciler expects structured storage, it should request the IStorage interface. In both cases, it should request read-only direct (nontransacted) access to the storage; read-write access may not generally be available.

A minimal briefcase reconciler typically looks directly at the storage of the other versions and deals with embedded objects in a very primitive manner, such as merging two versions of the object by including both versions in the output version.

The initiator locates the appropriate briefcase reconciler by using a subset of the logic implemented by the GetClassFile function to determine the class of a given file and then looks in the registry for the reconciler class associated with the given file class. The Briefcase, like other shell components, determines the class of a file solely by the filename extension. A file's extension must have a registered class for the Briefcase to invoke a reconciler for the file. You must set a registry entry of the following form when installing your reconciler.

CLSID\clsid\Roles\Reconciler\reconciler-classid

The class must be quick loading, must be designated _MULTIPLEUSE, and, unless marshallers are provided for the reconciliation interface, must be an in-process server (contained in a DLL) rather than a local server (implemented in an .EXE file).


 User Interaction

A briefcase reconciler should attempt to carry out reconciliation without user intervention. The more automated the reconciliation, the better the user's perception of the process.

In some cases, user intervention may be valuable. For example, a document system may require a user to review changes before accepting the merged version of a document or may require comments from the user explaining the changes that have been made. In these cases, the initiator, not the briefcase reconciler, is responsible for querying the user and carrying out the user's instructions.

In other cases, user intervention may be necessary. For example, when two versions have been edited in incompatible ways. In such cases, either the initiator or briefcase reconciler must query the user for instructions on how to resolve the conflict. In general, no initiator can rely on completing a reconciliation without expecting some user interaction. Reconcilers, on the other hand, have the option of interacting with the user to resolve conflicts or requiring the initiator to do so.


 Embedded Objects

When reconciling a document, the briefcase reconciler itself may become an initiator if it discovers an embedded object of a type that it cannot reconcile. In this case, the reconciler needs to recursively reconcile each of the embedded objects and assume all the responsibilities of an initiator.

To carry out the recursion, the briefcase reconciler loads the object and queries for the appropriate interface. The handler for the object must support the interface. If any member function of the interface returns the OLE_E_NOTRUNNING value, the reconciler must run the object in order to carry out the operation. Because code for embedded objects is not always available, a reconciler must provide a solution for this condition. For example, the reconciler might include both old and new versions of the embedded object in the reconciled version. The reconciler must not attempt to reconcile across links.

The initiator stores the document versions being merged. In many cases, the initiator has access to the storage of each version and saves the result of reconciliation using similar storage. Sometimes, however, the initiator may have an in-memory object for which no persistent version is available. This situation can occur when a document containing open embedded objects must be reconciled before being saved. In such cases, the initiator saves the result of the reconciliation in the version found in memory.

The initiator uses the IPersistStorage interface to bind (load) the merged version. The initiator uses the IPersistStorage::Load member function if an initial version has already been created and uses the IPersistStorage::InitNew member function for the initial version. Once the merged version is loaded, the initiator uses QueryInterface to retrieve the address of the IReconcilableObject interface. This interface gives the initiator access to the storage of the existing residues and gives it a way to create storage for any new residues. Then the initiator directs the interface to carry out the reconciliation. The initiator actually queries for the IPersistFile interface before IPersistStorage. If the reconciler supports IPersistFile, the initiator manipulates the replica through the IPersistFile rather than IPersistStorage member functions. This permits reconciliation of files that are not stored as compound documents.

Once the reconciliation is complete, the initiator can save the merged version by using the IPersistStorage or IPersistFile interface. During reconciliation, the briefcase reconciler creates residues as needed and writes their persistent bits to storage. If the merged version is a stream, the IStorage interface passed to IPersistStorage::Load contains a stream named "Contents" with its storage state set to STATEBITS_FLAT. (You can set the state bits by using the IStorage::Stat member function.) After the merge, the initiator saves the merged version by writing the data in an appropriate manner. It should ensure that STATEBITS_FLAT is set as appropriate for the storage.


 Residues

The initiator indicates whether it wants residues by setting the pstgNewResidues parameter to a valid address when calling the IReconcilableObject::Reconcile member function. If the reconciler does not support the creation of residues, it must return immediately the REC_E_NORESIDUES value, unless the dwFlags parameter specifies the RECONCILEF_NORESIDUESOK value.

The briefcase reconciler returns residues to the initiator by creating new storage elements and copying them to the array pointed to by pstgNewResidues. For structured storage residues, the reconciler copies an IStorage interface, and for flat storage residues, it copies either an IStream or IStorage interface with the STATEBITS_FLAT flag set. The reconciler uses IStorage to create the necessary storage, using IStorage::CreateStream to create flat storage for a residue that is a stream and IStorage::CreateStorage to create structured storage.

The initiator prepares pstgNewResidues such that it contains no elements in the nonreserved part of the IStorage namespace. The briefcase reconciler places each residue in an element whose name corresponds to the order of its initial version. For example, the first residue is contained in "1," the second in "2," and so on. If the reconciled object itself produces a residue, that is found in the element named "0."

The briefcase reconciler commits each of the newly created elements individually, ensuring that the initiator has access to the information. The reconciler does not, however, commit pstgNewResidues itself. The initiator is responsible for committing this or otherwise disposing of it.


 Reference

This section contains information about the reconciliation interfaces. When handling errors, a member function can return only those error values that are explicitly defined as possible return values. Furthermore, the member function must set all variables whose addresses are passed as parameters to NULL before returning from the error.


 Interfaces and Member Functions


IReconcilableObject [New - Windows 95]
 IReconcilableObject

[New - Windows 95]

The IReconcilableObject interface carries out the reconciliation of a document. This interface has the GetProgressFeedbackMaxEstimate and Reconcile member functions. The briefcase reconciler is responsible for implementing this interface.


IReconcilableObject::GetProgressFeedbackMaxEstimate [New - Windows 95]
 IReconcilableObject::GetProgressFeedbackMaxEstimate

[New - Windows 95]

HRESULT IReconcilableObject::GetProgressFeedbackMaxEstimate(
    ULONG * pulProgressMax);

Retrieves an estimated measurement of the amount of work required to complete a reconciliation. This value corresponds to a similar value that is passed with the IReconcileInitiator::SetProgressFeedback member function during reconciliation. Reconcilers typically use this member function to estimate the work needed to reconcile an embedded document.

•	Returns the S_OK value if successful. Otherwise, the member function returns one of the following error values:

OLE_E_NOTRUNNING	The object is an OLE embedded document that must be run before this operation can be carried out. The object state is unchanged as a result of the call.
E_UNEXPECTED	Unspecified error.
pulProgressMax

Address of the variable that receives the work estimate value.

The work estimate value, if available, is only approximate.


IReconcilableObject::Reconcile [New - Windows 95]
 IReconcilableObject::Reconcile

[New - Windows 95]

HRESULT IReconcilableObject::Reconcile(
    IReconcileInitiator * pInitiator,
    DWORD dwFlags,
    HWND hwndOwner,

    HWND hwndProgressFeedback,
    ULONG ulcInput,
    IMoniker ** rgpmkOtherInput,
    LONG * plOutIndex,
    IStorage * pstgNewResidues,
    void * pvReserved);

Reconciles the state of an object with one or more other objects. The reconciliation updates the internal state of the object by merging the states of all objects to form a combined state.

•	Returns one of the following success values if successful:

S_OK
	Reconciliation was completed successfully, and the changes must be propagated to the other objects.
S_FALSE
	No reconciliation actions were performed. The briefcase reconciler wishes to fall back to the initiator's bit copy implementation. This value may only be returned if RECONCILEF_ONLYYOUWERECHANGED is set in dwFlags.
REC_S_IDIDTHEUPDATES
	Reconciliation was completed successfully, and all the objects involved (the object implementing the Reconcile member function and all the other objects described by the passed-in monikers) have been updated appropriately. The initiator does not need, therefore, to do anything further to propagate the changes. The variable pointed to by plOutIndex should be set to  − 1L if Reconcile returns this value. The initiator will not save the source object's storage if Reconcile returns this value. This value may only be returned if RECONCILEF_YOUMAYDOTHEUPDATES was set in dwFlags.
REC_S_NOTCOMPLETE
	The briefcase reconciler completed some, but not all, of the reconciliation. It may need user interaction. The changes will not be propagated to other objects.
REC_S_NOTCOMPLETEBUTPROPAGATE
	The briefcase reconciler completed some, but not all, of the reconciliation. It may need user interaction. The changes will be propagated to the other objects.
Otherwise, the member function returns one of the following error values:

REC_E_NORESIDUES
	The briefcase reconciler does not support the generation of residues, so the request for residues is denied. The state of the object is unchanged.
REC_E_ABORTED
	The briefcase reconciler terminated reconciliation in response to a termination request from the initiator (for more information, see IReconcileInitiator::SetAbortCallback). The state of the object is unspecified.
REC_E_TOODIFFERENT
	Reconciliation cannot be carried out because the provided document versions are too dissimilar.
REC_E_INEEDTODOTHEUPDATES
	The object's Reconcile implementation was called with RECONCILEF_YOUMAYDOTHEUPDATES clear in dwFlags; the object's Reconcile implementation requires that value to be set in dwFlags.
OLE_E_NOTRUNNING
	The object is an OLE embedded object that must be run before this operation can be carried out. The state of the object is unchanged.
E_UNEXPECTED
	Unspecified error.
pInitiator

Address of the IReconcileInitiator interface for the initiator of the reconciliation process. This parameter must not be NULL.

dwFlags

Control flags for the reconciliation. This parameter may be zero or a combination of these values:

RECONCILEF_FEEDBACKWINDOWVALID
	hwndProgressFeedback is valid.
RECONCILEF_MAYBOTHERUSER
	The briefcase reconciler can prompt for user interaction if it is needed. Without this value, user interaction is not permitted. hwndOwner is valid.
RECONCILEF_NORESIDUESOK
	The briefcase reconciler can ignore requests for residues and carry out reconciliation. Reconcilers that do not support residues should check for this value whenever an initiator requests residues. Without this value, a reconciler that does not support residues must immediately return REC_E_NORESIDUES.
RECONCILEF_OMITSELFRESIDUE
	The briefcase reconciler can discard any residue associated with this object. Initiators typically use this value for reconciliations that loop from generation to generation.
RECONCILEF_ONLYYOUWERECHANGED
	The Reconcile member function is being called to propagate changes in the changed object to other unchanged objects. This value will only be set if the HKEY_CLASSES_ROOT\CLSID\clsid_of_reconciler\SingleChangeHook key exists in the registry. If that key is not present in the registry, the initiator carries out reconciliation by making the other unchanged objects binary identical copies of the changed object. The rgpmkOtherInput monikers identify the other objects. This value will only be set in dwFlags if RECONCILEF_YOUMAYDOTHEUPDATES is also set. If the briefcase reconciler completes the updates itself successfully, REC_S_IDIDTHEUPDATES should be returned and the variable pointed to by plOutIndex should be set to  − 1L. Note that S_OK should not be returned on success if this value is set in dwFlags. The initiator will not save the source object's storage if Reconcile returns REC_S_IDIDTHEUPDATES. If the reconciler wishes to fall back to the initiator's bit copy implementation, it may return S_FALSE.
RECONCILEF_RESUMEDRECONCILIATION
	The briefcase reconciler should resume reconciliation, using the partial residues provided. Without this value, the reconciler should ignore any "considered but rejected" information in any of the input versions.
RECONCILEF_YOUMAYDOTHEUPDATES
	The briefcase reconciler may do the updates itself. Without this value, the reconciler may not do the updates itself. If reconciliation is completed successfully, the reconciler should return REC_S_IDIDTHEUPDATES if it did the updates itself or S_OK if it did not do the updates itself.
hwndOwner

Handle of the parent window to use for child windows that the briefcase reconciler creates. This parameter is valid only if RECONCILEF_MAYBOTHERUSER is specified in dwFlags.

hwndProgressFeedback

Handle of the progress feedback window displayed by the initiator. This parameter is valid only if RECONCILEF_FEEDBACKWINDOWVALID is specified in dwFlags. The briefcase reconciler may call the SetWindowText function using this window handle to display additional reconciliation status information to the user.

ulcInput

Number of versions or partial residues specified in dwFlags. This parameter must not be zero.

rgpmkOtherInput

Address of an array that contains the addresses of the monikers to use to access the versions or partial residues to be reconciled.

plOutIndex

Address of the variable that receives an index value indicating whether the result of the reconciliation is identical to one of the initial versions. The variable is set to  − 1L if the reconciliation result is a combination of two or more versions. Otherwise, it is a zero-based index, with 0 indicating this object, 1 indicating the first version, 2 indicating the second version, and so on.

pstgNewResidues

Address of the IStorage interface used to store newly created residues. This parameter may be NULL to indicate that residues should not be saved.

pvReserved

Reserved; must be NULL.


IReconcileInitiator [New - Windows 95]
 IReconcileInitiator

[New - Windows 95]

The IReconcileInitiator interface provides the briefcase reconciler with the means to notify the initiator of its progress, to set a termination object, and to request a given version of a document. This interface has the SetArbortCallback and SetProgressFeedback member functions. The initiator is responsible for implementing this interface.


IReconcileInitiator::SetAbortCallback [New - Windows 95]
 IReconcileInitiator::SetAbortCallback

[New - Windows 95]

HRESULT IReconcileInitiator::SetAbortCallback(
    IUnknown * pUnkForAbort);

Sets the object through which the initiator can asynchronously terminate a reconciliation. A briefcase reconciler typically sets this object for reconciliations that are lengthy or involve user interaction.

•	Returns the S_OK value if successful. Otherwise, the member function returns one of the following error values:

REC_E_NOCALLBACK	The initiator does not support termination of reconciliation operations and does not hold the specified object.
E_UNEXPECTED	Unspecified error.
pUnkForAbort

Address of the IUnknown interface for the object. The initiator signals a request to terminate the reconciliation by using the IUnknown::Release member function to release the object. This parameter may be NULL to direct the initiator to remove the previously specified object.

The initiator can accept or reject the object. If the initiator accepts the object, the briefcase reconciler must later remove the object by subsequently calling this function with a NULL parameter when the reconciliation is complete. Because the reconciler removes the object after completing reconciliation, there may be times when the initiator releases the object after reconciliation is complete. In such cases, the reconciler ignores the request to terminate.

If the reconciliation is terminated, the IReconcilableObject::Reconcile member function must return either the REC_E_ABORTED or REC_E_NOTCOMPLETE value.


IReconcileInitiator::SetProgressFeedback [New - Windows 95]
 IReconcileInitiator::SetProgressFeedback

[New - Windows 95]

HRESULT IReconcileInitiator::SetProgressFeedback(
    ULONG ulProgress,
    ULONG ulProgressMax);

Indicates the amount of progress the briefcase reconciler has made toward completing the reconciliation. The amount is a fraction of 1 and is computed as the quotient of the ulProgress and ulProgressMax. Reconcilers should call this member function periodically during their reconciliation process.

•	Returns the S_OK value if successful or the E_UNEXPECTED value if some unspecified error occurred.

ulProgress

Numerator of the progress fraction.

ulProgressMax

Denominator of the progress fraction.

The initiator typically uses this measure of progress to update a thermometer gauge or some other form of visual feedback for the user. The briefcase reconciler can change the value of ulProgressMax from call to call. This means successive calls to this member function do not necessarily indicate steady forward progress. Backward progress is legal, although not desirable. It is the responsibility of the initiator to determine whether backward progress should be revealed to the user.


INotifyReplica [New - Windows 95]
 INotifyReplica

[New - Windows 95]

The INotifyReplica interface provides the initiator with the means to notify an object that it may be subject to subsequent reconciliation. This interface has the YouAreAReplica member function. The briefcase reconciler is responsible for implementing this interface.


INotifyReplica::YouAreAReplica [New - Windows 95]
 INotifyReplica::YouAreAReplica

[New - Windows 95]

HRESULT INotifyReplica::YouAreAReplica(
    ULONG ulcOtherReplicas,
    IMoniker ** rgpmkOtherReplicas);

Notifies on object that it may be subject to subsequent reconciliation through the IReconilableObject::Reconcile member function.

Briefcase calls INotifyReplica when objects are added to it.

•	Returns the S_OK value if successful. Otherwise, the member function returns one of the following error values:

E_UNEXPECTED	Unspecified error.
ulcOtherReplicas

Number of other replicas of the object. This parameter must not be zero.

rgpmkOtherReplicas

Address of an array that contains the addresses of the monikers to use to access the other replicas.

An object may be notified that it is a replica more than once. Briefcase reconcilers are not required to implement this interface. Initiators are not required to call this interface if it is implemented. However, an object's implementation of IReconcilableObject::Reconcile may reasonably fail if that object has not previously been notified through INotifyReplica::YouAreAReplica that it may be subject to reconciliation.


 Device I/O Control

Microsoft® Windows® 95 includes a device input and output control (IOCTL) interface that allows applications developed for the Microsoft® Win32® application programming interface (API) to communicate directly with virtual device drivers.


 About Device I/O Control

Applications typically use the IOCTL interface to carry out selected Microsoft® MS-DOS® system functions, to obtain information about a device, or to carry out input and output (I/O) operations that are not available through standard Win32 functions.

This article describes the device IOCTL interface, explains how to use the interface in applications, and describes how to implement the interface in virtual devices (VxDs). For information about the device IOCTL interface for other operating systems that support the Win32 API, see the documentation included in the Microsoft Win32 Software Development Kit (SDK).


 Input and Output Control in Applications

You use the device IOCTL interface in an application to carry out "low-level" operations that are not supported by the Win32 API and that require direct communication with a VxD. Windows 95 implements the interface through the DeviceIoControl function, which sends commands and accompanying data directly to the given VxD. To use the interface, you open the VxD by using the CreateFile function, send commands to the VxD by using DeviceIoControl, and finally close the VxD by using the CloseHandle function.


 Opening the VxD

You can open a static or dynamically loadable VxD by specifying the module name, filename, or registry entry identifying the VxD in a call to the CreateFile function. If the VxD exists and it supports the device IOCTL interface, the function returns a device handle that you can use in subsequent calls to the DeviceIoControl function. Otherwise, the function fails and sets the last error value to ERROR_NOT_SUPPORTED or ERROR_FILE_NOT_FOUND. You can use the GetLastError function to retrieve the error value.

When you open a VxD, you must specify a name having the following form.

\\.\VxdName

VxDName can be the module name of the VxD, the name of the VxD file, or the name of a registry entry that specifies the filename.

CreateFile checks for a filename extension to determine whether VxDName specifies a file. If a filename extension (such as .VXD) is present, the function looks for the file in the standard search path. In the following example, CreateFile looks for the SAMPLE.VXD file in the standard search path.

HANDLE hDevice;

hDevice = CreateFile("\\\\.\\SAMPLE.VXD", 0, 0, NULL, 0,
    FILE_FLAG_DELETE_ON_CLOSE, NULL);

If VxDName has no filename extension, CreateFile checks the registry to see if the name is also a value name under the KnownVxDs key in HKLM\System\CurrentControlSet\Control\SessionManager. If it is a value name, CreateFile uses the current value associated with the name as the full path of the VxD file. This method is useful for specifying VxDs that are not in the standard search path. In the following example, CreateFile searches the registry for the MYVXDPATH value.

hDevice = CreateFile("\\\\.\\MYVXDPATH", 0, 0, NULL, 0,
    FILE_FLAG_DELETE_ON_CLOSE, NULL);

If VxDName has no filename extension and is not in the registry, CreateFile assumes that the name is a VxD module name and searches the internally maintained device descriptor blocks for an already loaded VxD having the given name. In the following example, CreateFile opens the standard VxD named VWIN32.VXD.

hDevice = CreateFile("\\\\.\\VWIN32", 0, 0, NULL, 0,
    0, NULL);

In all cases, if CreateFile cannot find or load the VxD, it sets the last error value to ERROR_FILE_NOT_FOUND. If the function loads the VxD but the VxD does not support the device IOCTL interface, CreateFile sets the last error value to ERROR_NOT_SUPPORTED.

You can open the same VxD any number of times. CreateFile provides a unique handle each time you open a VxD, but it makes sure that no more than one copy of the VxD is loaded into memory. To ensure that the system removes the VxD from memory when you close the last instance of the VxD, use the FILE_FLAG_DELETE_ON_CLOSE value when opening dynamically loadable VxDs. Static VxDs cannot be removed from memory.

Although CreateFile has several parameters, only the lpName and fdwAttrsAndFlags parameters are useful when opening an VxD. fdwAttrsAndFlags can be zero, the FILE_FLAG_DELETE_ON_CLOSE value, or the FILE_FLAG_OVERLAPPED value. FILE_FLAG_OVERLAPPED is used for asynchronous operation and is described later in this article.


 Sending Commands

You use DeviceIoControl to send commands to a VxD. You must specify the previously opened device handle, control code, and input and output parameters for the call. The device handle identifies the VxD, and the control code specifies an action for the VxD to perform. In the following example, the DIOC_GETVERSION control code directs the given VxD to return version information.

HANDLE hDevice
BYTE bOutput[4];
DWORD cb;

fResult = DeviceIoControl(
    hDevice,          // device handle
    DIOC_GETVERSION,  // control code
    NULL, 0,          // input parameters
    bOutput, 4, &cb,  // output parameters
    0);

The input and output parameters of DeviceIoControl include the addresses and sizes of any buffers needed to pass data into or out of the VxD. Whether you use these parameters depends on how the VxD processes the control code. You supply an input buffer if the VxD requires that you pass it data for processing, and you supply an output buffer if the VxD returns the results of processing. In the previous example, only the output parameters are supplied. These include the address of the output buffer; the size, in bytes, of the buffer; and the address of the variable to receive the count of bytes actually copied to the buffer by the VxD.

Although the Win32 header files define a set of standard control codes, Windows 95 does not support these standard codes. Instead, the meaning and value of control codes in Windows 95 are specific to each VxD. Different VxDs may support different control codes.

Some VxDs support the DIOC_GETVERSION control code, which directs the VxD to return version information in the output buffer. Although the version information can have any format that helps the application determine the version of the VxD, keeping the information to 4 bytes or less is recommended. The VxD returns the version information only if you supply a buffer and specify a nonzero size for the buffer.

If you opened the VxD using the FILE_FLAG_OVERLAPPED value, you must also provide an OVERLAPPED structure when calling DeviceIoControl. This structure contains information that the VxD uses to process the control code asynchronously.


 Closing a VxD

When you have finished using a VxD, you can close the associated device handle by using the CloseHandle function, or you can let the operating system close the handle when the application terminates. The following example closes a VxD.

CloseHandle(hDevice);

Closing a VxD does not necessarily remove the VxD from memory. If you open a dynamically loadable VxD using the FILE_FLAG_DELETE_ON_CLOSE value, CloseHandle also removes the VxD if no other valid handles are present in the system. The system maintains a reference count for dynamically loadable VxDs, incrementing the count each time the VxD is opened and decrementing when the VxD is closed. CloseHandle checks this count and removes the VxD from memory when the count reaches zero. The system does not keep a reference count for static VxDs; it does not remove these VxDs when their corresponding handles are closed.

In rare cases, you may need to use the DeleteFile function to remove a dynamically loadable VxD from memory. For example, you use DeleteFile if another application has loaded the VxD and you just want to unload it. You also use DeleteFile if you have successfully loaded a VxD by using CreateFile, but the VxD does not support the device IOCTL interface. In such cases, CreateFile loads the VxD but provides no handle to close and remove the VxD. The following example removes the VxD named SAMPLE from memory.

DeleteFile("\\\\.\\SAMPLE");

In this example, SAMPLE is the module name of the VxD. (Do not specify the filename.) Be aware that the module name of a VxD is not necessarily the same as the VxD's filename without a filename extension. In general, avoid using DeleteFile to remove a VxD from memory.


 Asynchronous Operations

You can direct a VxD to process a control code asynchronously. In an asynchronous operation, the DeviceIoControl function returns immediately, regardless of whether the VxD has finished processing the control code. Asynchronous operation allows an application to continue while the VxD processes the control code in the background. You request an asynchronous operation by specifying the address of an OVERLAPPED structure in the DeviceIoControl function. The hDevice member of OVERLAPPED specifies the handle of an event that the system sets to the signaled state when the VxD has completed the operation.

Asynchronous (overlapped) operations are useful for lengthy operations, such as formatting a disk. To perform an asynchronous operation, you must specify the FILE_FLAG_OVERLAPPED value when calling CreateFile to obtain a device handle. When calling DeviceIoControl, you must specify the address of an OVERLAPPED structure in the lpOverlapped parameter and the handle of a manual reset event in the hEvent member of the structure. The system ignores all other members.

If DeviceIoControl completes the operation before returning, it returns TRUE; otherwise, it returns FALSE. When the operation is finished, the system signals the manual reset event. You should call GetOverlappedResult when the thread that called DeviceIoControl needs to wait (that is, stop executing) until the operation has finished.


 Using VWIN32 to Carry Out MS-DOS Functions

Windows 95 provides a VxD called VWIN32.VXD that supports a set of control codes that Win32 applications can use to carry out selected MS-DOS system functions. These system-defined control codes consist of the following values.

Control code (value)	Meaning
VWIN32_DIOC_DOS_INT13 (4)	Performs Interrupt 13h commands.
VWIN32_DIOC_DOS_INT25 (2)	Performs the Absolute Disk Read command (Interrupt 25h).
VWIN32_DIOC_DOS_INT26 (3)	Performs the Absolute Disk Write command (Interrupt 25h).
VWIN32_DIOC_DOS_IOCTL (1)	Performs the specified MS-DOS device I/O control function (Interrupt 21h Function 4400h through 4411h).
When a Windows 95 − based application calls DeviceIoControl with the dwIoControlCode parameter set to one of the predefined control codes, the lpvInBuffer and lpvOutBuffer parameters must specify the addresses of DIOC_REGISTERS structures. The DIOC_REGISTERS structure specified by lpvInBuffer contains a set of register values that specify a command for the VxD to execute and any data that the VxD needs to execute the command. After completing the command, the VxD fills the DIOC_REGISTERS structure specified by lpvOutBuffer with the register values that resulted from executing the command. The meaning of the register values depends on the specified command.

Some interrupt functions require far pointers passed in segment:offset pairs where the segment is placed in a segment register. Because the 32-bit code does not have segments, the DIOC_REGISTERS structure contains no segment registers. To specify segment:offset pairs, place the full pointer into the structure member that corresponds to the register used to hold the offset portion of the real-mode pointer. For example, use reg_EDX for pointers that go into the DS:DX registers.

Many of the MS-DOS and BIOS functions require segment registers, but segment registers are not part of the DIOC_REGISTERS structure. To specify an address that includes a segment selector, use the structure member that corresponds to the offset of the real-mode segment:offset register pair to hold the entire address. For example, a pointer in the ES:DI registers would be put into the reg_EDI member.

When a Windows 95 − based application uses the DeviceIoControl function to send commands to a VxD other than VWIN32.VXD, the meaning of the function's parameters are defined by the VxD. The system does not validate any parameter.

The system VxD, VWIN32.VXD, supports the IOCTL functions originally provided by MS-DOS Interrupt 21h. The following example shows how to call Get Media ID (Interrupt 21h Function 440Dh Minor Code 66h) from a Win32-based application.

#define VWIN32_DIOC_DOS_IOCTL 1

typedef struct _DIOC_REGISTERS {
    DWORD reg_EBX;
    DWORD reg_EDX;
    DWORD reg_ECX;
    DWORD reg_EAX;
    DWORD reg_EDI;
    DWORD reg_ESI;
    DWORD reg_Flags;
} DIOC_REGISTERS, *PDIOC_REGISTERS;

// Important: All MS_DOS data structures must be packed on a
// one-byte boundary.

#pragma pack(1)
typedef struct _MID {
    WORD  midInfoLevel;
    DWORD midSerialNum;
    BYTE  midVolLabel[11];
    BYTE  midFileSysType[8];
} MID, *PMID;
#pragma pack()

HANDLE hDevice;
DIOC_REGISTERS reg;
MID mid;
BOOL fResult;
DWORD cb;
int nDrive = 3;  // Drive C:

hDevice = CreateFile("\\\\.\\vwin32",
    0, 0, NULL, 0, FILE_FLAG_DELETE_ON_CLOSE, NULL);

reg.reg_EAX = 0x440D;       /* IOCTL for block devices           */
reg.reg_EBX = nDrive;       /* zero-based drive identifier       */
reg.reg_ECX = 0x0866;       /* Get Media ID command              */
reg.reg_EDX = (DWORD) &mid; /* receives media identifier info.   */
reg.reg_Flags = 0x0001;     /* assume error (carry flag is set)  */

fResult = DeviceIoControl(hDevice,
    VWIN32_DIOC_DOS_IOCTL,
    &reg, sizeof(reg),
    &reg, sizeof(reg),
    &cb, 0);

if (!fResult || (reg.reg_Flags & 0x0001))
    ; // error if carry flag is set

CloseHandle(hDevice);


 Supporting Input-Output Control in VxDs

A VxD can support the device IOCTL interface by processing the W32_DEVICEIOCONTROL message in the VxD's control procedure. You can take advantage of the device IOCTL interface by providing a VxD that performs privileged (ring 0) operations for your application.


 Loading and Opening the VxD

When your application calls CreateFile, the system sends the W32_DEVICEIOCONTROL message to the control procedure of the specified VxD to determine if it supports the device IOCTL interface. The ESI register contains the address of a DIOCParams structure whose dwIoControlCode member specifies the DIOC_GETVERSION control code. A VxD that supports the device IOCTL interface must respond to the DIOC_GETVERSION control code by clearing the EAX register. (A VxD can also return version information in the buffer pointed to by the lpvOutBuffer member so long as the cbOutBuffer member is nonzero. If cbOutBuffer is zero, the calling application is not interested in version information, but the VxD must still return zero to indicate success.) If the VxD does not support the device IOCTL interface, it must place a nonzero value in EAX.

For dynamically loadable VxDs, the system sends a SYS_DYNAMIC_INIT control message to the VxD the first time that it is opened. If the VxD returns success, the system sends the W32_DEVICEIOCONTROL message with the DIOC_OPEN (identical in value to the DIOC_GETVERSION control code) control code. The VxD must return zero to inform the calling application that it supports W32_DEVICEIOCONTROL. The system sets the reference count for the VxD to 1. On every subsequent call to CreateFile for the VxD, the VxD receives the W32_DEVICEIOCONTROL message with the DIOC_OPEN control code and the reference count for the VxD is incremented.

The VxD receives a W32_DEVICEIOCONTROL message with the DIOC_CLOSEHANDLE control code if the application closes the device handle by calling the CloseHandle function, or if the operating system closes the handle when the application terminates (or DeleteFile if the VxD was not opened with the FILE_FLAG_DELETE_ON_CLOSE value). The VxD can use this notification to perform cleanup operations and release structures associated with the application. The reference count for the VxD is decremented before the message is sent. If the reference count is decremented to zero, the VxD receives the SYS_DYNAMIC_EXIT message and is subsequently unloaded.


 Processing Control Codes

When an application calls DeviceIoControl, the system calls the control procedure of the VxD identified by the given device handle. The EAX register contains the W32_DEVICEIOCONTROL message, and the ESI register contains the address of a DIOCParams structure. The structure contains all of the parameters that the application specified in the DeviceIoControl function as well as additional information. The VxD should examine the dwIoControlCode member of the DIOCParams structure to determine the action to perform. The lpvInBuffer member contains supporting data that the VxD needs to complete the action. After processing the control code, the VxD should copy any information that it needs to return to the application to the buffer specified by the lpvOutBuffer member.

If the VxD successfully processes the control code, it should clear the EAX register before returning. Otherwise, the VxD should set EAX to a nonzero value.


 Asynchronous Operations

A VxD can determine whether an application has requested an asynchronous operation by checking the lpoOverlapped member of the DIOCParams structure. If lpoOverlapped specifies the address of an OVERLAPPED structure, the application has requested an asynchronous operation. In that case, the VxD should return  − 1 in the EAX register and then process the specified control code.

The operating system does not take any steps to make the application's memory available to the VxD at all times (in all contexts) for asynchronous operations. When implementing asynchronous operations, the VxD must use the appropriate virtual machine manager (VMM) services, such as LinPageLock with the PAGEMAPGLOBAL value, to make the application's memory pages available across contexts, including access to the OVERLAPPED structure.

When the VxD finishes processing the control code, it must notify the application by calling the VWIN32_DIOCCompletionRoutine service provided by VWIN32.VXD. The EBX register must contain the value of the Internal member of the OVERLAPPED structure. This member is reserved for operating system use only. Also, if the VxD copies any data to the buffer specified by the lpvOutBuffer member of the DIOCParams structure, the VxD must specify the count of bytes copied to the buffer in the InternalHigh member of OVERLAPPED. The remaining members of OVERLAPPED, Offset and OffsetHigh, can be used for developer-defined data.

Essentially, the VWIN32_DIOCCompletionRoutine service helps signal the event identified by the hEvent member of the OVERLAPPED structure. The application monitors the event to determine when the asynchronous operation is completed.


 Reference

The following structures, system messages, and service are associated with the device IOCTL interface.


 Structures

These structures are used to carry out device IOCTL functions.


DIOC_REGISTERS [New - Windows 95]
 DIOC_REGISTERS

[New - Windows 95]

typedef struct DIOCRegs {

    DWORD   reg_EBX;   // EBX register

    DWORD   reg_EDX;   // EDX register

    DWORD   reg_ECX;   // ECX register

    DWORD   reg_EAX;   // EAX register

    DWORD   reg_EDI;   // EDI register

    DWORD   reg_ESI;   // ESI register

    DWORD   reg_Flags; // Flags register

} DIOC_REGISTERS;

Contains the register values for calling Interrupt 21h commands through the DeviceIoControl function. The meaning of the registers depends on the given command.

Some interrupt functions require far pointers passed in segment:offset pairs where the segment is placed in a segment register. Since the 32-bit code does not have segments, the DIOC_REGISTERS structure contains no segment registers. You should place the full pointer into the structure member that corresponds to the register used to hold the offset portion of the real-mode pointer. For example, use reg_EDX for pointers that go into the DS:DX registers.


DIOCParams [New - Windows 95]
 DIOCParams

[New - Windows 95]

include vwin32.inc

DIOCParams STRUC
    Internal1             DD  ?  ; reserved
    VMHandle              DD  ?  ; handle of virtual machine
    Internal2             DD  ?  ; reserved
    dwIoControlCode       DD  ?  ; see below
    lpvInBuffer           DD  ?  ; see below
    cbInBuffer            DD  ?  ; see below
    lpvOutBuffer          DD  ?  ; see below
    cbOutBuffer           DD  ?  ; see below
    lpcbBytesReturned     DD  ?  ; see below
    lpoOverlapped         DD  ?  ; see below
    hDevice               DD  ?  ; handle of device
    tagProcess            DD  ?  ; see below
DIOCParams ENDS

Contains information that an application has passed to the virtual device driver (VxD) by calling the DeviceIoControl function.

dwIoControlCode

Control code to process. This member can be a developer-defined value or one of these system-defined values:

DIOC_CLOSEHANDLE	Notifies a VxD that an application has closed its device handle for the VxD. The VxD should perform cleanup operations and release any structures associated with the application.
DIOC_GETVERSION	Queries the VxD to determine if it supports the device IOCTL interface. If the VxD supports the interface, it must clear the EAX register. Otherwise, it must place a nonzero value in EAX. If cbOutBuffer is nonzero and the VxD supports the interface, the VxD should copy version information to the lpvOutBuffer.
lpvInBuffer

Address of a buffer that contains data needed to process the control code.

cbInBuffer

Size, in bytes, of the buffer pointed to by lpvInBuffer.

lpvOutBuffer

Address of a buffer that receives the results of processing the control code.

cbOutBuffer

Size, in bytes, of the buffer pointed to by lpvOutBuffer.

lpcbBytesReturned

Number of bytes copied to the buffer pointed to by lpvOutBuffer.

lpoOverlapped

Address of an OVERLAPPED structure that contains information used to complete the command asynchronously. If the command is to be completed synchronously, this member is NULL.

tagProcess

Information that the VxD can use to tag the current request along with hDevice. When the VxD receives a DIOC_CLOSEHANDLE control code for hDevice and tagProcess, it should perform appropriate cleanup operations.


 System Message

The following system message is used to implement the device IOCTL interface of a VxD.


W32_DEVICEIOCONTROL [New - Windows 95]
 W32_DEVICEIOCONTROL

[New - Windows 95]

include VMM.INC

mov ebx, VMHandle           ; see below

mov eax, W32_DEVICEIOCONTROL

mov esi, OFFSET32 dioparams ; see below

VMMCall System_Control

Passes a control code and related information to a virtual device driver.

•	Returns one of the following values in the EAX register:

0	The control code processed successfully.
− 1	An asynchronous operation is in progress. A VxD must return this value only if the lpoOverlapped member of the DIOCParams structure is not NULL.
Error code	An error occurred. For a list of Win32 error codes, see the documentation included in the Win32 SDK.
VMHandle

Handle of the virtual machine.

dioparams

Address of a DIOCParams structure containing a control code and information that the VxD needs to process the control code.

This message is sent to a VxD when an application specifies the name of a VxD in the CreateFile function and when an application specifies the device handle of the VxD in a call to the DeviceIoControl or CloseHandle function. This message uses the ESI register.


 Service

The following service is used with device IOCTL.


VWIN32_DIOCCompletionRoutine [New - Windows 95]
 VWIN32_DIOCCompletionRoutine

[New - Windows 95]

mov ebx, Internal  ; see below
VxDCall VWIN32_DIOCCompletionRoutine

Notifies the system that an asynchronous operation in a virtual device driver is complete. The VxD calls this service after the asynchronous input and output (I/O) operation to signal the application.

•	No return value.

Internal

Event identifier. This parameter must be the same value initially passed to the VxD in the Internal member of the OVERLAPPED structure.

Before calling this service, the VxD must set the InternalHigh member of the OVERLAPPED structure to the number of bytes of return data.


 System Policies

System administrators can use Microsoft® Windows® 95 system policies to control user and computer configurations from a single location on a network. System Policies propagate registry settings to a large number of computers without requiring the administrator to have detailed knowledge of the registry.


 About System Policies

There are many settings in the registry, and multiple registry settings must often be manipulated to achieve a particular result. The System Policies feature provides a layer of abstraction that makes it easier to control registry settings.

Instead of changing individual registry settings, a system administrator can specify policies. Each policy has some text that describes its effect. Some examples of policies follow:

•	Disable file sharing.

•	Display a custom logon banner.

•	Remove the Run command from the Start menu.

•	Use user-level security.


 Registry Settings

Each policy is associated with one or more registry settings. When the administrator chooses to enforce a policy, the System Policies tool identifies registry changes that must be made and then makes the changes to the registries of the users and computers for which the policy applies. The administrator can specify policies for individual users, user groups, and individual computers. Default values can also be specified.

Policies have been implemented for most of the registry settings that an administrator might want to control and propagate. Although System Policies control only a subset of the registry, they are extensible. Application developers are encouraged to supply template files and implement policies for registry settings used by their products so that customers can plug the template files into a policy editor and control policies for the application.


 Policy Editors and Downloaders

There are two administrative components involved in specifying policies: a policy editor and a policy downloader. A policy editor is an application that lets administrators specify registry settings for particular computers, users, and user groups, and a policy downloader is a small program installed on every client computer that merges the administrator's settings into the local registry.

The policy editor uses a template file, which is a text file describing registry settings and specifying how the settings should appear in the policy editor's user interface. The policy editor creates a policy file, which is a single file containing policy settings for a number of computers, users, and user groups. The policy file is a registry hive that is created and manipulated using Microsoft® Win32® functions. Windows 95 includes a policy editor, the System Policy Editor. Developers may create their own policy editors, but the editors must be able to read template files and be able to read and write policy files.

Windows 95 provides a policy downloader, which is built into Multiple Provider Router (MPR). Developers may also create their own policy downloaders. Policy downloaders may be installed so that MPR will call the installed component to do the downloading rather than doing so itself. Because the policy file format allows for extensions, developers may provide additional functionality.


 Architecture

A computer's configuration is defined in terms of policies. The policies are ultimately stored in the local computer's registry. Every component that provides a policy is responsible for reading the registry at appropriate times and acting accordingly. For example, the policy that removes the Run command from the Start menu requires the shell code that displays the Start menu to check the appropriate registry setting to determine whether or not it is supposed to display the Run command. The policies are generic data items; the administrative tools and components have no information about them besides their names, their associated data, and where they reside in the registry. The only responsibilities of the administrative components are to allow the administrator to make policy settings and propagate those settings to the user's registry.


 Policy Primitives

The following definitions are important for a complete understanding of policies:

•	A policy is a permission or attribute for a particular item, action, or object. It is either enabled or disabled.

•	A part is a subcomponent of a policy. A policy may have zero or more parts. Policy parts may have various data types, including Boolean values, numeric values, and string values. The values of the parts apply only if the policy is enabled.

•	A category is a collection of similar policies.

Some policies do not need any parts. For instance, "Lock Desktop Links" could be a policy. For such a policy, it would be sufficient to say that it was either enabled or disabled. If it were enabled, the user could not modify his or her desktop links in any way. "Desktop Links" could be another policy, and it could have the Boolean parts "Create Links," "Delete Links," and "Modify Links." As another example, "Password Expiration" could be a policy, and "Number of days" (a numeric value) could be its part.

Policies and parts are analogous to a group of controls in a dialog box that are all enabled by a single check box. The check box, which corresponds to whether or not the policy is enabled, "turns on" the controls in the dialog box (the policy parts) and allows data to be entered into the controls. A policy with no parts (that is, no associated controls) is analogous to a single check box.

The following types of policies can be specified:

•	A user-specific policy can be specified for each user or group. A default set of policies can be specified for users or groups who do not have sets of policies defined for them explicitly. Most policies are user-specific. User-specific policies are always merged into the HKEY_CURRENT_USER key of the registry.

•	A machine-specific policy should not change according to user. A machine-specific policy applies to all users. It does not follow users as they move between different computers. Machine-specific policies are always merged into the HKEY_LOCAL_MACHINE key of the registry.


 Policy Information

Any application or component can define a policy. The policy will appear in the administrator user interface, and information that the administrator sets about the policy will migrate to the local computer's registry. The application or component that defines a policy must check the registry appropriately to enforce its own policy.

Policy information is typically added to a local registry in the following sequence:

1.	Categories, policies, and parts are described in a template (.ADM) file. The .ADM file format is described in "Template File Format" later in this topic. An ADMIN.ADM file with all the policies that the system supports is shipped with Windows 95. Developers, however, may also provide their own template files.

2.	The administrator runs the policy editor, which reads one or more policies and lists the available categories and policies. The administrator sets up the desired policies, and the policy editor uses registry functions to save the work to a policy (.POL) file. The format of policy files is described in "Policy File Format" later in this topic.

3.	After the user logs on (and user profiles are reconciled if they are enabled), the policy downloader is activated. It determines where to find the file on the network, opens the policy file, and merges the appropriate computer, user, and user group policies into the local registry.


 Default User and Computer Names

There is a standard user name called DEFAULT USER and a standard computer name called DEFAULT COMPUTER. When the policy downloader updates machine- and user-specific policies, it first tries to find an entry in the policy file for the local computer name or user name. If the downloader does not find an entry, it looks for the DEFAULT USER or DEFAULT COMPUTER entry and uses those entries for the update. If there are no entries for a particular user or computer and default entries do not exist, no update takes place.

The DEFAULT USER and DEFAULT COMPUTER entries are powerful because administrators can set policies for a large number of users and computers and then manage the exceptions by creating specific user and computer entries in a .POL file.


 Policy Downloading

Policy downloading can be set in one of the following three states:

•	Off

•	Automatic

•	Manual

If policy downloading is off, no downloading takes place.

If policy downloading is set to automatic, MPR asks the primary network provider to provide a place to look on the network for the policy file. Microsoft® Windows NT™ and Novell® NetWare® providers both support this capability. (For a Windows NT network, MPR looks in the primary domain controller's NETLOGON directory for a file named CONFIG.POL. For a NetWare version 3..x network, MPR looks on the preferred server's SYS\PUBLIC directory for a file named CONFIG.POL.) Any software vendor who provides a 32-bit network provider can support this capability by implementing the NPGetPolicyPath function. If policy downloading is set to automatic and the primary network provider does not support NPGetPolicyPath, no downloading takes place.

If policy downloading is set to manual, a specific path to the policy file must also be supplied. It can be either a Universal Naming Convention (UNC) path or a path beginning with a drive letter. (In the latter case, the drive letter must be appropriately mapped before downloading takes place.)

The default setting for policy downloading is automatic. No error messages are displayed if a policy file cannot be found in the location that the network provider suggests. This means that a site can install a number of Windows 95 clients and then deploy the policies at a later date. To deploy them, the administrator just needs to place the policy file(s) in the appropriate location(s) on the network, and the clients will immediately begin using them the next time they log on.


 Policy Editor User Interface

This section describes the user interface of the System Policy Editor that ships with Windows 95. Other software vendors may, however, choose to use a different user interface.

The System Policy Editor requires an .ADM file describing the available policies to use. By default, it will use a file named ADMIN.ADM, but different template files may be specified using the Templates menu.

The main window of the System Policy Editor displays the users and computers that have entries in the policy file that is currently open. To create a new policy file, choose the New command on the File menu. A new policy file contains entries for the default user and default computer. To add entries for particular users or particular computers, use the Add User, Add Group, or Add Computer button. Note that policies for all of the entries shown in the main window are saved to one policy file. Typically, an administrator saves the policy file to the network location where the policy downloader looks by default.

The following illustration shows the main window of the System Policy Editor.

Double-clicking an entry, such as Default Computer, brings up a properties dialog box containing the policies for the entry. The Default Computer Properties dialog box shown in the following illustration has an upper section listing the policies and a lower section showing settings for a specific policy.

A check box in the properties dialog box has three states. If it is checked, the policy will be enforced; that is, the corresponding settings will be added to the registry when the policy is downloaded. If the check box is empty, the settings will be deleted from the registry when the policy is downloaded. If the check box is gray, the registry settings will not be changed when the policy is downloaded; that is, the user has the freedom to choose settings, assuming that the settings can be changed from the user interface.

For example, there is a user policy for desktop wallpaper. By checking that policy, the administrator specifies the particular wallpaper that the user will have. Even if the user uses the Display Control Panel application to change the wallpaper, the wallpaper specified by the administrator will appear the next time he or she logs on. If the administrator unchecks this policy, the wallpaper setting is deleted so that when the user logs on, there is no wallpaper. If the administrator makes the check box gray, nothing is enforced, and the user can choose the wallpaper.

As a second example, there is a user policy "Remove Run from Start menu" (under the Shell/Restrictions registry key). Checking this policy adds a registry setting that tells the shell not to include the Run command on the Start menu. By unchecking this policy, this registry key is deleted, and the shell displays the Run command. If the policy is left gray, the setting will not be changed. If the policy was already in force, it will stay that way, and the Run command will continue to be denied to the user. If the policy had not been applied already, the user would continue to see the Run command. Note that unlike the wallpaper example, the user cannot change this setting by using Control Panel or another user interface element.

The System Policy Editor can also operate directly on the local registry rather than on a policy file. This capability is useful for troubleshooting problems that may be policy-related, because it shows what policies are currently in place for a user on a particular computer. There is no policy file involved in this mode. To switch to the local registry view, use the Open Registry command on the File menu. Note that the check boxes will show only two states, checked and unchecked, because the registry settings for the policy are either present (the policy is on) or not present (the policy is off).


 Template File Format

A template (.ADM) file describes a number of categories. Each category can contain zero or more policies, and each policy can contain zero or more parts. The following sections describe categories, policies, policy parts, and part types.

The ADMIN.ADM file that ships with Windows 95 identifies strings that are important for an internal localization tool by using two exclamation points (!!). Each of these strings is explicitly defined in the [strings] section of ADMIN.ADM. You do not need to use this mechanism when you create a template file.


 Categories

A category is specified as follows.

CATEGORY name TYPE category type
[KEYNAME key name]

[... policy definition statements ...]

END CATEGORY

name

Category name as it should appear in the System Policy Editor list box. It may optionally be enclosed by double quotation marks. (Names with spaces must be enclosed by double quotation marks.)

category type

Type, which must be USER or MACHINE. It specifies whether the category is user-specific or machine-specific.

key name

Optional registry key name to use for the category. If a key name is specified, it will be used by all child categories, policies, and parts, unless they specifically provide a key name of their own.

A policy definition statement may not appear more than once in a single category.


 Policies

A policy is specified as follows.

POLICY name
[KEY key name]
[... part definition statements ...]
END POLICY

name

Policy name as it should appear in the System Policy Editor list box. It may optionally be enclosed by double quotation marks. (Names with spaces must be enclosed by double quotation marks.)

key name

Optional registry key name to use for the policy. If a key name is specified, it will be used by all child parts of the policy, unless they specifically provide a key name of their own.


 Policy Parts

A policy part is specified as follows.

PART name TYPE part type
type-dependent data
[KEYNAME key name ]
VALUENAME value name
END PART

name

Part name as it should appear in the System Policy Editor list box. It may optionally be enclosed by double quotation marks. (Names with spaces must be enclosed by double quotation marks.)

part type

Policy part type. Part types are discussed individually in the following section.

type-dependent data

Information about the part. Type-dependent data is discussed in the following section.

key name

Optional key name to use. If no key name is specified, the previous key name in hierarchy is used.

value name

Value name to use to set the data for this part.


 Part Types

The following policy part types are defined:

CHECKBOX	Displays a check box. The value is set in the registry with the REG_DWORD type. The value will be nonzero if the check box is checked by the user and zero if it is unchecked.
COMBOBOX	Displays a combo box.
DROPDOWNLIST	Displays a combo box with a drop-down list style. The user may only choose from one of the entries supplied. The main advantage of a combo box with a drop-down list is that a number of extra registry edits may be specified, based on the user's selection.
EDITTEXT	Displays an edit field that accepts alphanumeric text. The text is set in the registry with the REG_SZ type.
LISTBOX	Displays a list box with "add" and "remove" buttons. This is the only part type that can be used to manage multiple values under one key.
NUMERIC	Displays an edit field with an optional spinner control (an up-down control) that accepts a numeric value. The value is set in the registry with the REG_DWORD type.
TEXT	Displays a line of static (label) text. There is no associated registry value with this part type.
Descriptions of these policy part types follow.


CHECKBOX Part Type [New - Windows 95]
 CHECKBOX Part Type

[New - Windows 95]

The CHECKBOX part type accepts the following options:

ACTIONLISTOFF	Specifies an optional action list to be used if the check box is turned off. For more information, see "Action Lists" later in this topic.
ACTIONLISTON	Specifies an optional action list to be used if the check box is turned on. For more information, see "Action Lists" later in this topic.
DEFCHECKED	Causes the check box to be initially checked.
VALUEOFF	Overrides the default "off" behavior of the check box if specified.
VALUEON	Overrides the default "on" behavior of the check box if specified.
The default behavior of a check box is to write the value 1 to the registry if it is checked and 0 if it is unchecked. VALUEON and VALUEOFF are used to override this behavior. For example, the following option writes "Fred" to the registry when the check box is checked.

VALUEON "Fred"

The following option writes the value 12 to the registry when the check box is unchecked.

VALUEOFF NUMERIC 12


COMBOBOX Part Type [New - Windows 95]
 COMBOBOX Part Type

[New - Windows 95]

The COMBOBOX part type accepts all the options that EDITTEXT does as well as the following option:

SUGGESTIONS	Begins a list of suggestions to be placed in the drop-down list. Suggestions are separated with spaces and can be enclosed by double quotation marks. The list ends with END SUGGESTIONS. Following is an example: SUGGESTIONS Alaska Alabama Mississippi "New York" END SUGGESTIONS


DROPDOWNLIST Part Type [New - Windows 95]
 DROPDOWNLIST Part Type

[New - Windows 95]

The DROPDOWNLIST part type accepts the following options:

ITEMLIST	Begins a list of the items in the drop-down list. The list must end with END ITEMLIST.
REQUIRED	Specifies that the policy editor will not allow a policy containing this part to be enabled unless a value has been entered for the part.
Each item in the ITEMLIST option must be specified as follows.

NAME name VALUE value
[ACTIONLIST actionlist]
...

name

Text to be displayed in the drop-down list for this item.

value

Value to be written as the part's value if this item is selected. Values are assumed to be strings, unless they are preceded by NUMERIC. The following example shows both string and numeric values.

   VALUE "Some value"

   VALUE NUMERIC 1

If VALUE is followed by DELETE (for example, VALUE DELETE), the registry valuename and value pair will be deleted.

actionlist

Optional action list to be used if this value is selected. For more information about action lists, see "Action Lists" later in this topic.


EDITTEXT Part Type [New - Windows 95]
 EDITTEXT Part Type

[New - Windows 95]

The EDITTEXT part type accepts the following options:

DEFAULT value	Specifies the initial string to place in the edit field. If this option is not specified, the field is initially empty.
MAXLEN value	Specifies the maximum length of a string. The string in the edit field is limited to this length.
REQUIRED	Specifies that the policy editor will not allow a policy containing this part to be enabled, unless a value has been entered for this part.
OEMCONVERT	Sets the ES_OEMCONVERT style in the edit field so that typed text is mapped from ANSI to OEM and back.


LISTBOX Part Type [New - Windows 95]
 LISTBOX Part Type

[New - Windows 95]

The VALUENAME option cannot be used with the LISTBOX part type, because there is no single value name associated with this type. By default, only one column appears in the list box, and for each entry a value is created whose name and value are the same. For instance, a "fred" entry in the list box would create a value named "fred" whose data was "fred".

The LISTBOX part type accepts the following options:

ADDITIVE	By default, the content of list boxes will "override" whatever values are set in the target registry. (That is, a control value is inserted in the policy file, which causes existing values to be deleted before the values set in the policy file are merged.) If this option is specified, existing values are not deleted, and the values set in the list box will be in addition to whatever values exist in the target registry.
EXPLICITVALUE	This option makes the user specify not only the value data, but the value name as well. The list box will show two columns for each item, one for the name and one for the data. This option cannot be used with the VALUEPREFIX option.
VALUEPREFIX prefix	The prefix specified is used in determining value names. If a prefix is specified, the prefix and an incremented integer will be used instead of the default value naming scheme described previously. For example, a prefix of "SomeName" will generate the value names "SomeName1", "SomeName2", and so on. The prefix can be empty (""), which will cause the value names to be "1", "2", and so on.


NUMERIC Part Type [New - Windows 95]
 NUMERIC Part Type

[New - Windows 95]

The NUMERIC part type accepts the following options:

DEFAULT value	Specifies the initial numeric value for the edit field. If this option is not specified, the field is initially empty.
MAX value	Specifies the maximum value for the number. The default value is 9999.
MIN value	Specifies the minimum value for the number. The default value is 0.
REQUIRED	Specifies that the policy editor will not allow a policy containing this part to be enabled unless a value has been entered for this part.
SPIN value	Specifies increments to use for the spinner control. SPIN 0 removes the spinner control. SPIN 1 is the default.
TXTCONVERT	Writes values as REG_SZ strings ("1," "2," or "128") rather than as binary values.


TEXT Part Type [New - Windows 95]
 TEXT Part Type

[New - Windows 95]

The TEXT part type accepts no type-specific data.


 Action Lists

An action list is a set of arbitrary changes to the registry that are made in response to a control being in a certain state. For instance, if a check box is turned on, an application could install some virtual device drivers and record some other changes.

The syntax for an actionlist follows.

ACTIONLIST
    [KEYNAME key name]
    VALUENAME value name
    VALUE value
    [KEYNAME key name]
    VALUENAME value name
    VALUE value
    ....
END ACTIONLIST

The actionlist specifies a number of key name, value name, and value triplets. A key name is not required for every action, but if it is not listed, the key name from the previous action will be used. (This is useful for writing a number of values to one key.) Values are treated as strings unless they are preceded by NUMERIC, as in the following examples.

VALUE "Some value"

VALUE NUMERIC 1

If VALUE is followed by DELETE (for example, VALUE DELETE), the registry valuename and value pair will be deleted.


 Comments

Comments can be added to a template (.ADM) file by preceding the line with two forward slashes (//) or a semicolon (;).


 Conditional Expressions

Future policy editors may include new capabilities. If these new capabilities require revisions to the template file format, older versions of the System Policy Editor will not be able to read the new template files. You can use conditional expressions to ensure that any future template files you create will be compatible with older policy editors.

The System Policy Editor supports two conditional expressions. The first one allows you to include different parts of the template file, based on the version number. This expression has the following syntax.

#if VERSION operator version_number

.

.

.

[#else]

.

.

.

#endif

The operator can be one of the following symbols: >, >=, <, <=, ==, or !=. The version_number can be any integer; for Windows 95, the version number is 1.

The other conditional expression is #ifdef. This expression has the following syntax.

[#ifdef | #ifndef] keyword

.

.

.

[#else]

.

.

.

#endif

Keywords are implicitly understood by the policy editor. For example, a fictitious company named PolicyCorp might implement its own policy editor that could recognize the POLICYCORP keyword. This company could use the #ifdef and #endif conditional expressions to make sure its template files can be recognized by the Windows 95 System Policy Editor. (Because the Windows 95 System Policy Editor does not currently recognize any keywords, #ifdef always evaluates to FALSE and #ifndef always evaluates to TRUE.)


 Policy File Format

A policy (.POL) file is a registry hive, which is created by using the Win32 RegSaveKey function.

The following top-level keys are defined:

•	Computers

•	Groups

•	GroupData

•	Users

•	Misc

A policy downloader uses the following steps to download policies:

1.	Locates the appropriate computer key, if any, under Computers. Beneath that key is an image of the registry settings to be merged. The policy downloader should walk through all the subkeys and values and merge those settings into the HKEY_LOCAL_MACHINE key, paying attention to the control codes that are defined in the following section.

2.	Locates the appropriate groups key(s), if any, under Groups. Under the Groups keys is an image of the registry settings to be merged. These settings must be merged into the HKEY_CURRENT_USER key.

3.	Locates the appropriate user key, if any, under Users. Under the Users key is an image of the registry settings to be merged. These settings must be merged into the HKEY_CURRENT_USER key.


 Control Codes

Control codes are used to signify that special processing of a value or key name must take place. All control codes are prefixes to a value or key name and take the form of the code name (that is, **code.) directly followed by value name or key name.

The following control codes are defined for use with value names.

**del.	Specifies that the value name following the control code should be deleted.
**delvals.	Deletes all values under this key in the local registry before propagating values under this key from the policy file. When processing a particular key, a downloader must look for and process this value first. This control code is inserted by a list box control so that existing values are removed before the new values are added.
**soft.	Specifies that it is a soft value. The downloader only propagates the value name following the control code if a value by that name does not exist in the local registry; that is, the downloader does not overwrite existing settings with soft values.
No control codes are currently defined for use with key names.

If a policy downloader encounters a control code that it does not understand, it must not process the key or value. If the control code is part of a value name, the policy downloader should skip that value in the hive file but continue to process other values under that key and its subkeys. If the control code is part of a key name, the downloader should ignore the key and not process any values under it or its subkeys. This behavior is important because it allows developers to create new control codes without breaking existing downloaders.

Developers may create new control codes in the same format as shown in the preceding table (that is, **code.). Developers who do so should notify Microsoft so that Microsoft can document the new codes.


 Computers Key

Underneath the Computers key is a list of computers that have entries in the policy file. The steps to use in locating a Computers key follow:

1.	Determine whether there is a key that is the same as the computer name. If there is one, merge the registry image beneath it into the HKEY_LOCAL_MACHINE key.

2.	If the key is not there, determine whether there is a key called ".default". (This appears in the System Policy Editor user interface as Default Computer.) If a default key exists, merge the registry image beneath it.

3.	If neither of the two steps work, do nothing.


 Groups and GroupData Keys

Underneath the Groups key is a list of user groups who have entries in the policy file. Since a user may belong to many groups and those groups may have conflicting settings, it is important to specify an order in which groups are processed. This order is contained in the GroupData\Priority key, which has values in the form "1"="group name", "2"="group name", and so on. "1" is highest priority, and the priority diminishes as the number in the value name increases. The downloader reads the group priority values and then processes groups from lowest priority to highest; that is, the downloader begins with the highest numbered value and works to the value "1".

For each group in the priority list, the downloader determines if the user is a member of the group. If the user is in the group, the downloader should try to find a key with the group name under the Groups key. If such a key exists, the downloader merges the registry image under that key into the HKEY_CURRENT_USER key. It is not an error if a group is specified in the priority list but does not have an entry under the Groups key; it simply means that nothing happens. This process is repeated for each group in the priority list. (If a group has an entry under the Groups key but does not have an entry in the priority list, it is never processed.)


 Users Key

Underneath the Users key is a list of computers that have entries in the policy file. The steps to use in locating a Users key follow:

1.	Determine whether there is a key that is the same as the user name. If there is one, merge the registry image beneath it into the HKEY_CURRENT_USER key.

2.	If the key is not there, determine whether there is a key called ".default". This appears in the System Policy Editor user interface as Default User. If a default key exists, merge the registry image beneath it.

3.	If neither of the two steps work, do nothing.


 Misc Key

The Misc key can be used by developers to store vendor-specific data. The naming convention for this key follows.

Misc\Vendor Name \Product Name\Version\ data

A software vendor may store any needed information in data. A key or value containing version information is highly recommended. As is recommended for the registry, Version should be "CurrentVersion" for the most current version of the product.


 Installable Policy Downloaders

An installable policy downloader must be a Win32 dynamic-link library (DLL). It should export a named function that has the following form.

VOID FAR PASCAL ProcessPolicies(HWND hwndOwner,
LPSTR lpszPolicyFilePath, LPSTR lpszUserName,
LPSTR lpszComputerName, DWORD dwFlags);

hwndOwner

Handle of the parent window.

lpszPolicyFilePath

Address of the full path and filename that MPR would have used to look for the policy file. The downloader may use this parameter, or ignore it and use a different path.

lpszUserName

Address of the user name for the user who is logged on.

lpszComputerName

Address of the local computer name.

dwFlags

Flags. This parameter can be this value:

PP_DISPLAYERRORS	Displays error messages about errors encountered during downloading (including the file is not found, the network resource is not found, and so on). Otherwise, the function should fail silently if there is an error.
In addition to defining and exporting this function, an application must record it in the registry. The following entry should be added under the HKEY_LOCAL_MACHINE\Network\Logon key.

PolicyHandler = "dll name, function name"

In this example, dll name is the name of the DLL containing the function, and function name is the exported function name.


 Tool Help Functions

Tool help functions make it easier for developers to obtain information about currently executing Microsoft® Win32®-based applications. These functions are designed to streamline the creation of Win32-hosted tools, specifically Windows-based debugging applications.


 About Tool Help Functions

The following topics are discussed in this article:

•	Snapshots of the system

•	Process walking

•	Thread walking

•	Module walking

•	Heap lists and heap walking


 Snapshots of the System

Snapshots are at the core of the tool help functions. A snapshot is a read-only copy of the current state of one or more of the following lists that reside in system memory: processes, threads, modules, and heaps.

Win32 processes that use tool help functions access these lists from snapshots instead of directly from the operating system. The lists in system memory change when processes are started and ended, threads are created and destroyed, executable modules are loaded and unloaded from system memory, and heaps are created and destroyed. The use of information from a snapshot prevents inconsistencies. Otherwise, changes to a list could possibly cause a thread to incorrectly traverse the list or cause an access violation (a GP fault). For example, if an application traverses the thread list while other threads are created or terminated, information that the application is using to traverse the thread list might become outdated and could cause an error for the application traversing the list.

You can take a snapshot of the system memory by using the CreateToolhelp32Snapshot function. You can control the content of a snapshot by specifying one or more of the following values when calling this function: TH32CS_SNAPHEAPLIST, TH32CS_SNAPMODULE, TH32CS_SNAPPROCESS, and TH32CS_SNAPTHREAD.

The TH32CS_SNAPHEAPLIST and TH32CS_SNAPMODULE values are process specific. When these values are specified, the heap and module lists of the specified process are included in the snapshot. If no process identifier is specified, the current process is assumed. The TH32CS_SNAPTHREAD value always creates a system-wide snapshot even if a process identifier is passed to CreateToolhelp32Snapshot.

You can enumerate the heap or module state for all Win32 processes by specifying the TH32CS_SNAPALL value and the current process. Then, for each process in the snapshot that is not the current process, you can call CreateToolhelp32Snapshot again, specifying the process identifier and the TH32CS_SNAPHEAPLIST or TH32CS_SNAPMODULE value.

You can retrieve an extended error status code for CreateToolhelp32Snapshot by using the GetLastError function. For more information about GetLastError, see the documentation included in the Microsoft Win32 Software Development Kit (SDK).

When your process finishes using a snapshot, you should destroy it by using the CloseHandle function. Not destroying a snapshot causes the process to leak memory until the process exits, at which time the system reclaims the memory. For more information about CloseHandle, see the documentation included in the Win32 SDK.

Note  The snapshot handle acts like a file handle and is subject to the same rules regarding which processes and threads it is valid in.


 Process Walking

A snapshot that includes the Win32 process list contains information about each currently executing process. You can retrieve information for the first process in the list by using the Process32First function. After retrieving the first process in the list, you can traverse the process list for subsequent entries by using the Process32Next function. Process32First and Process32Next fill a PROCESSENTRY32 structure with information about a process in the snapshot.

You can retrieve an extended error status code for Process32First and Process32Next by using the GetLastError function. For more information about GetLastError, see the documentation included in the Win32 SDK.

You can read the memory in a specific process into a buffer by using the Toolhelp32ReadProcessMemory function (or the VirtualQueryEx function).

Note  The contents of the th32ProcessID and th32ParentProcessID members of PROCESSENTRY32 are Win32 process identifiers and can be used with other Win32 application programming interface (API) elements.


 Thread Walking

A snapshot that includes the Win32 thread list contains information about each thread of each currently executing Win32 process. You can retrieve information for the first thread in the list by using the Thread32First function. After retrieving the first thread in the list, you can retrieve information for subsequent threads by using the Thread32Next function. Thread32First and Thread32Next fill a THREADENTRY32 structure with information about individual threads in the snapshot.

You can enumerate the threads of a specific process by taking a snapshot that includes the threads and then by traversing the thread list, keeping information about the threads that have the same process identifier as the specified process.

You can retrieve an extended error status code for Thread32First and Thread32Next by using the GetLastError function. For more information about GetLastError, see the documentation included in the Win32 SDK.


 Module Walking

A snapshot that includes the module list for a specified Win32 process contains information about each module, executable file, or dynamic-link library (DLL), used by the specified process. You can retrieve information for the first module in the list by using the Module32First function. After retrieving the first module in the list, you can retrieve information for subsequent modules in the list by using the Module32Next function. Module32First and Module32Next fill a MODULEENTRY32 structure with information about the module.

You can retrieve an extended error status code for Module32First and Module32Next by using the GetLastError function. For more information about GetLastError, see the documentation included in the Win32 SDK.

Note  The module identifier, which is specified in the th32ModuleID member of MODULEENTRY32, has meaning only to the tool help functions. It is not a handle, nor is it usable by other Win32 API elements.


 Heap Lists and Heap Walking

A snapshot that includes the heap list for a specified Win32 process contains identification information for each heap associated with the specified process and detailed information about each heap. You can retrieve an identifier for the first heap of the heap list by using the Heap32ListFirst function. After retrieving the first heap in the list, you can traverse the heap list for subsequent heaps associated with the process by using the Heap32ListNext function. Heap32ListFirst and Heap32ListNext fill a HEAPLIST32 structure with the process identifier, the heap identifier, and flags describing the heap.

You can retrieve information about the first block of a heap by using the Heap32First function. After retrieving the first block of a heap, you can retrieve information about subsequent blocks of the same heap by using the Heap32Next function. Heap32First and Heap32Next fill a HEAPENTRY32 structure with information for the appropriate block of a heap.

You can retrieve an extended error status code for Heap32ListFirst, Heap32ListNext, Heap32First, and Heap32Next by using the GetLastError function. For more information about GetLastError, see the documentation included in the Win32 SDK.

Note  The heap identifier, which is specified in the th32HeapID member of the HEAPENTRY32 structure, has meaning only to the tool help functions. It is not a handle, nor is it usable by other Win32 API elements.


 Using the Tool Help Functions

This section contains examples demonstrating how to perform the following tasks:

•	Access tool help functions.

•	Take a snapshot and view the processes in the system address space.

•	Traverse the threads listed in a snapshot.

•	Traverse the modules listed for a specific process.

The following examples have been taken from the PVIEW95 application included in the Win32 SDK.

Note  Each of the HEAPENTRY32, HEAPLIST32, MODULEENTRY32, PROCESSENTRY32, and THREADENTRY32 structures that are used with the tool help functions has a dwSize member that must be initialized to the size of the structure before the structure is included in a call to a tool help function. The value of dwSize is used to indicate the version of the tool help functions used. If your application does not initialize dwSize, the tool help function will fail.


 Accessing the Tool Help Functions

The tool help functions reside in the operating system kernel. The following example provides a platform-independent approach to accessing the tool help functions.

#include <tlhelp32.h> // needed for tool help declarations

// Type definitions for pointers to call tool help functions.

typedef BOOL (WINAPI *MODULEWALK)(HANDLE hSnapshot,
    LPMODULEENTRY32 lpme);

typedef BOOL (WINAPI *THREADWALK)(HANDLE hSnapshot,
    LPTHREADENTRY32 lpte);

typedef BOOL (WINAPI *PROCESSWALK)(HANDLE hSnapshot,
    LPPROCESSENTRY32 lppe);

typedef HANDLE (WINAPI *CREATESNAPSHOT)(DWORD dwFlags,
    DWORD th32ProcessID);

// File scope globals. These pointers are declared because of the need

// to dynamically link to the functions.  They are exported only by

// the Windows 95 kernel. Explicitly linking to them will make this

// application unloadable in Microsoft(R) Windows NT(TM) and will

// produce an ugly system dialog box.

static CREATESNAPSHOT pCreateToolhelp32Snapshot = NULL;

static MODULEWALK  pModule32First  = NULL;

static MODULEWALK  pModule32Next   = NULL;

static PROCESSWALK pProcess32First = NULL;

static PROCESSWALK pProcess32Next  = NULL;

static THREADWALK  pThread32First  = NULL;

static THREADWALK  pThread32Next   = NULL;

// Function that initializes tool help functions.

BOOL InitToolhelp32 (void)

{

    BOOL   bRet  = FALSE;

    HANDLE hKernel = NULL;

    // Obtain the module handle of the kernel to retrieve addresses of

    // the tool helper functions.

    hKernel = GetModuleHandle("KERNEL32.DLL");

    if (hKernel){

        pCreateToolhelp32Snapshot =

            (CREATESNAPSHOT)GetProcAddress(hKernel,
            "CreateToolhelp32Snapshot");

        pModule32First  = (MODULEWALK)GetProcAddress(hKernel,

            "Module32First");

        pModule32Next   = (MODULEWALK)GetProcAddress(hKernel,

            "Module32Next");

        pProcess32First = (PROCESSWALK)GetProcAddress(hKernel,

            "Process32First");

        pProcess32Next  = (PROCESSWALK)GetProcAddress(hKernel,

            "Process32Next");

        pThread32First  = (THREADWALK)GetProcAddress(hKernel,

            "Thread32First");

        pThread32Next   = (THREADWALK)GetProcAddress(hKernel,

            "Thread32Next");

        // All addresses must be non-NULL to be successful.

        // If one of these addresses is NULL, one of

        // the needed lists cannot be walked.

        bRet =  pModule32First && pModule32Next  && pProcess32First &&

                pProcess32Next && pThread32First && pThread32Next &&

                pCreateToolhelp32Snapshot;

    }

    else

        bRet = FALSE; // could not even get the module handle of kernel

    return bRet;

}


 Taking a Snapshot and Viewing Processes

The following function takes a snapshot of the currently executing processes in the system and walks through the list recorded in the snapshot.

BOOL GetProcessList (VOID)

{

    HANDLE         hSnapshot = NULL;

    BOOL           bRet      = FALSE;

    PROCESSENTRY32 pe32      = {0};

    //  Take a snapshot of all processes currently in the system.

    hSnapshot = pCreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);

    if (hProcessSnap == (HANDLE)-1)

        return (FALSE);

    //  Fill in the size of the structure before using it.

    pe32.dwSize = sizeof(PROCESSENTRY32);

    //  Walk the snapshot of the processes, and for each process, get

    //  information to display.

    if (pProcess32First(hProcessSnap, &pe32)) {

        BOOL          bGotModule = FALSE;

        MODULEENTRY32 me32       = {0};

        PINFO         pi         = {0};

        do {

            bGotModule = GetProcessModule(pe32.th32ProcessID,

                pe32.th32ModuleID, &me32, sizeof(MODULEENTRY32));

            if (bGotModule) {

                HANDLE hProcess;

                // Get the actual priority class.

                hProcess = OpenProcess (PROCESS_ALL_ACCESS,

                    FALSE, pe32.th32ProcessID);

                pi.dwPriorityClass = GetPriorityClass (hProcess);

                CloseHandle (hProcess);

                // Get the process's base priority value.

                pi.pcPriClassBase = pe32.pcPriClassBase;

                pi.pid            = pe32.th32ProcessID;

                pi.cntThreads     = pe32.cntThreads;

                lstrcpy(pi.szModName, me32.szModule);

                lstrcpy(pi.szFullPath, me32.szExePath);

                AddProcessItem(hListView, pi);

            }

        }

        while (pProcess32Next(hProcessSnap, &pe32));

        bRet = TRUE;

    }

    else

        bRet = FALSE;    // could not walk the list of processes

    // Do not forget to clean up the snapshot object.

    CloseHandle (hProcessSnap);

    return (bRet);

}


 Traversing the Thread List

The following function takes a snapshot of the threads currently executing in the system and walks through the list recorded in the snapshot.

// Returns TRUE if the threads were successfully enumerated

//   and listed or FALSE if the threads could not be enumerated

//   or listed.

// hListView  - handle of the listview that lists thread information

// dwOwnerPID - identifier of the process whose threads are to

//   be listed

BOOL RefreshThreadList (HWND hListView, DWORD dwOwnerPID)

{

    HANDLE        hThreadSnap = NULL;

    BOOL          bRet        = FALSE;

    THREADENTRY32 te32        = {0};

    // Take a snapshot of all threads currently in the system.

    hThreadSnap = pCreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);

    if (hThreadSnap == (HANDLE)-1)

        return (FALSE);

    // Clear the current contents of the thread list view

    // (which are now old).

    ListView_DeleteAllItems(g_hwndThread);

    // Fill in the size of the structure before using it.

    te32.dwSize = sizeof(THREADENTRY32);

    // Walk the thread snapshot to find all the threads of the process.

    // If the thread belongs to the process, add its information

    // to the display list.

    if (pThread32First(hThreadSnap, &te32)) {

        do {

            if (te32.th32OwnerProcessID == dwOwnerPID) {

                TINFO ti;

                ti.tid        = te32.th32ThreadID;

                ti.pidOwner   = te32.th32OwnerProcessID;

                ti.tpDeltaPri = te32.tpDeltaPri;

                ti.tpBasePri  = te32.tpBasePri;

                AddThreadItem(hListView, ti);

            }

        }

        while (pThread32Next(hThreadSnap, &te32));

        bRet = TRUE;

    }

    else

        bRet = FALSE;          // could not walk the list of threads

    // Do not forget to clean up the snapshot object.

    CloseHandle (hThreadSnap);

    return (bRet);

}


 Traversing the Module List

The following function takes a snapshot of the modules in the address space of a specified Win32 process and retrieves information for a specific module from the list recorded in the snapshot.

// Returns TRUE if there is information about the specified module or

//   FALSE if it could not enumerate the modules in the process or

//   the module is not found in the process.

// dwPID - identifier of the process that owns the module to

//   retrieve information about.

// dwModuleID - tool help identifier of the module within the

//   process

// lpMe32 - structure to return data about the module

// cbMe32 - size of the buffer pointed to by lpMe32 (to ensure

//   the buffer is not over filled)

BOOL GetProcessModule (DWORD dwPID, DWORD dwModuleID,
        LPMODULEENTRY32 lpMe32, DWORD cbMe32)

{

    BOOL          bRet        = FALSE;

    BOOL          bFound      = FALSE;

    HANDLE        hModuleSnap = NULL;

    MODULEENTRY32 me32        = {0};

    // Take a snapshot of all modules in the specified process.

    hModuleSnap = pCreateToolhelp32Snapshot(TH32CS_SNAPMODULE, dwPID);

    if (hModuleSnap == (HANDLE)-1)

        return (FALSE);

    // Fill the size of the structure before using it.

    me32.dwSize = sizeof(MODULEENTRY32);

    // Walk the module list of the process, and find the module of

    // interest. Then copy the information to the buffer pointed

    // to by lpMe32 so that it can be returned to the caller.

    if (pModule32First(hModuleSnap, &me32)) {

        do {

            if (me32.th32ModuleID == dwModuleID) {

                CopyMemory (lpMe32, &me32, cbMe32);

                bFound = TRUE;

            }

        }

        while (!bFound && pModule32Next(hModuleSnap, &me32));

        bRet = bFound;   // if this sets bRet to FALSE, dwModuleID

                         // no longer exists in specified process

    }

    else

        bRet = FALSE;           // could not walk module list

    // Do not forget to clean up the snapshot object.

    CloseHandle (hModuleSnap);

    return (bRet);

}


 Reference

The following functions and structures are associated with the tool help services.


 Functions

The following functions are used with tool help services.


CreateToolhelp32Snapshot [New - Windows 95]
 CreateToolhelp32Snapshot

[New - Windows 95]

HANDLE WINAPI CreateToolhelp32Snapshot(DWORD dwFlags,
    DWORD th32ProcessID);

Takes a snapshot of the Win32 processes, heaps, modules, and threads used by the Win32 processes.

•	Returns an open handle to the specified snapshot if successful or  − 1 otherwise.

dwFlags

Flags specifying portions of the system to include in the snapshot. These values are defined:

TH32CS_INHERIT	Indicates that the snapshot handle is to be inheritable.
TH32CS_SNAPALL	Equivalent to specifying the TH32CS_SNAPHEAPLIST, TH32CS_SNAPMODULE, TH32CS_SNAPPROCESS, and TH32CS_SNAPTHREAD values.
TH32CS_SNAPHEAPLIST	Includes the heap list of the specified Win32 process in the snapshot.
TH32CS_SNAPMODULE	Includes the module list of the specified Win32 process in the snapshot.
TH32CS_SNAPPROCESS	Includes the Win32 process list in the snapshot.
TH32CS_SNAPTHREAD	Includes the Win32 thread list in the snapshot.
th32ProcessID

Win32 process identifier. This parameter can be zero to indicate the current process. This parameter is used when the TH32CS_SNAPHEAPLIST or TH32CS_SNAPMODULE value is specified. Otherwise, it is ignored.

The snapshot taken by this function is examined by the other tool help functions to provide their results. Access to the snapshot is read only. The snapshot handle acts like a Win32 object handle and is subject to the same rules regarding which processes and threads it is valid in.

To retrieve an extended error status code generated by this function, use the GetLastError function.

To destroy the snapshot, use the CloseHandle function.


Heap32First [New - Windows 95]
 Heap32First

[New - Windows 95]

BOOL WINAPI Heap32First(LPHEAPENTRY32 lphe, DWORD th32ProcessID,
    DWORD th32HeapID);

Retrieves information about the first block of a heap that has been allocated by a Win32 process.

•	Returns TRUE if information for the first heap block has been copied to the buffer or FALSE otherwise. The ERROR_NO_MORE_FILES error value is returned by the GetLastError function if the heap is invalid or empty.

lphe

Address of a buffer containing a HEAPENTRY32 structure.

th32ProcessID

Identifier of the Win32 process context that owns the heap.

th32HeapID

Identifier of the heap to enumerate.

The calling application must set the dwSize member of HEAPENTRY32 to the size, in bytes, of the structure.

To access subsequent blocks of the same heap, use the Heap32Next function.


Heap32ListFirst [New - Windows 95]
 Heap32ListFirst

[New - Windows 95]

BOOL WINAPI Heap32ListFirst(HANDLE hSnapshot, LPHEAPLIST32 lphl);

Retrieves information about the first heap that has been allocated by a specified Win32 process.

•	Returns TRUE if the first entry of the heap list has been copied to the buffer or FALSE otherwise. The ERROR_NO_MORE_FILES error value is returned by the GetLastError function when no heap list exists or the snapshot does not contain heap list information.

hSnapshot

Handle of the snapshot returned from a previous call to the CreateToolhelp32Snapshot function.

lphl

Address of a buffer containing a HEAPLIST32 structure.

The calling application must set the dwSize member of HEAPLIST32 to the size, in bytes, of the structure.

To retrieve information about other heaps in the heap list, use the Heap32ListNext function.


Heap32ListNext [New - Windows 95]
 Heap32ListNext

[New - Windows 95]

BOOL WINAPI Heap32ListNext(HANDLE hSnapshot, LPHEAPLIST32 lphl);

Retrieves information about the next heap that has been allocated by a Win32 process.

•	Returns TRUE if the next entry of the heap list has been copied to the buffer or FALSE otherwise. The ERROR_NO_MORE_FILES error value is returned by the GetLastError function when no more entries in the heap list exist.

hSnapshot

Handle of the snapshot returned from a previous call to the CreateToolhelp32Snapshot function.

lphl

Address of a buffer containing a HEAPLIST32 structure.

The calling application must set the dwSize member of HEAPLIST32 to the size, in bytes, of the structure.

To retrieve information about the first heap in a heap list, use the Heap32ListFirst function.


Heap32Next [New - Windows 95]
 Heap32Next

[New - Windows 95]

BOOL WINAPI Heap32Next(LPHEAPENTRY32 lphe);

Retrieves information about the next block of a heap that has been allocated by a Win32 process.

•	Returns TRUE if information about the next block in the heap has been copied to the buffer or FALSE otherwise. The ERROR_NO_MORE_FILES error value is returned by the GetLastError function when no more objects in the heap exist.

lphe

Address of a buffer containing a HEAPENTRY32 structure.

The calling application must set the dwSize member of HEAPENTRY32 to the size, in bytes, of the structure.

To retrieve information for the first block of a heap, use the Heap32First function.


Module32First [New - Windows 95]
 Module32First

[New - Windows 95]

BOOL WINAPI Module32First(HANDLE hSnapshot, LPMODULEENTRY32 lpme);

Retrieves information about the first module associated with a Win32 process.

•	Returns TRUE if the first entry of the module list has been copied to the buffer or FALSE otherwise. The ERROR_NO_MORE_FILES error value is returned by the GetLastError function if no modules exist or the snapshot does not contain module information.

hSnapshot

Handle of the snapshot returned from a previous call to the CreateToolhelp32Snapshot function.

lpme

Address of a buffer containing a MODULEENTRY32 structure.

The calling application must set the dwSize member of MODULEENTRY32 to the size, in bytes, of the structure.

To retrieve information about other modules associated with the specified process, use the Module32Next function.


Module32Next [New - Windows 95]
 Module32Next

[New - Windows 95]

BOOL WINAPI Module32Next(HANDLE hSnapshot, LPMODULEENTRY32 lpme);

Retrieves information about the next module associated with a Win32 process or thread.

•	Returns TRUE if the next entry of the module list has been copied to the buffer or FALSE otherwise. The ERROR_NO_MORE_FILES error value is returned by the GetLastError function if no more modules exist.

hSnapshot

Handle of the snapshot returned from a previous call to the CreateToolhelp32Snapshot function.

lpme

Address of a buffer containing a MODULEENTRY32 structure.

The calling application must set the dwSize member of MODULEENTRY32 to the size, in bytes, of the structure.

To retrieve information about first module associated with a Win32 process, use the Module32First function.


Process32First [New - Windows 95]
 Process32First

[New - Windows 95]

BOOL WINAPI Process32First(HANDLE hSnapshot, LPPROCESSENTRY32 lppe);

Retrieves information about the first Win32 process encountered in a system snapshot.

•	Returns TRUE if the first entry of the process list has been copied to the buffer or FALSE otherwise. The ERROR_NO_MORE_FILES error value is returned by the GetLastError function if no processes exist or the snapshot does not contain process information.

hSnapshot

Handle of the snapshot returned from a previous call to the CreateToolhelp32Snapshot function.

lppe

Address of a PROCESSENTRY32 structure.

The calling application must set the dwSize member of PROCESSENTRY32 to the size, in bytes, of the structure.

To retrieve information about other processes recorded in the same snapshot, use the Process32Next function.


Process32Next [New - Windows 95]
 Process32Next

[New - Windows 95]

BOOL WINAPI Process32Next(HANDLE hSnapshot, LPPROCESSENTRY32 lppe);

Retrieves information about the next Win32 process recorded in a system snapshot.

•	Returns TRUE if the next entry of the process list has been copied to the buffer or FALSE otherwise. The ERROR_NO_MORE_FILES error value is returned by the GetLastError function if no processes exist or the snapshot does not contain process information.

hSnapshot

Handle of the snapshot returned from a previous call to the CreateToolhelp32Snapshot function.

lppe

Address of a PROCESSENTRY32 structure.

The calling application must set the dwSize member of PROCESSENTRY32 to the size, in bytes, of the structure.

To retrieve information about the first process recorded in a snapshot, use the Process32First function.


Thread32First [New - Windows 95]
 Thread32First

[New - Windows 95]

BOOL WINAPI Thread32First(HANDLE hSnapshot, LPTHREADENTRY32 lpte);

Retrieves information about the first thread of any Win32 process encountered in a system snapshot.

•	Returns TRUE if the first entry of the thread list has been copied to the buffer or FALSE otherwise. The ERROR_NO_MORE_FILES error value is returned by the GetLastError function if no threads exist or the snapshot does not contain thread information.

hSnapshot

Handle of the snapshot returned from a previous call to the CreateToolhelp32Snapshot function.

lpte

Address of a THREADENTRY32 structure.

The calling application must set the dwSize member of THREADENTRY32 to the size, in bytes, of the structure.

To retrieve information about other threads recorded in the same snapshot, use the Thread32Next function.


Thread32Next [New - Windows 95]
 Thread32Next

[New - Windows 95]

BOOL WINAPI Thread32Next(HANDLE hSnapshot, LPTHREADENTRY32 lpte);

Retrieves information about the next thread of any Win32 process encountered in the system memory snapshot.

•	Returns TRUE if the next entry of the thread list has been copied to the buffer or FALSE otherwise. The ERROR_NO_MORE_FILES error value is returned by the GetLastError function if no threads exist or the snapshot does not contain thread information.

hSnapshot

Handle of the snapshot returned from a previous call to the CreateToolhelp32Snapshot function.

lpte

Address of a THREADENTRY32 structure.

The calling application must set the dwSize member of THREADENTRY32 to the size, in bytes, of the structure.

To retrieve information about the first thread recorded in a snapshot, use the Thread32First function.


Toolhelp32ReadProcessMemory [New - Windows 95]
 Toolhelp32ReadProcessMemory

[New - Windows 95]

BOOL WINAPI Toolhelp32ReadProcessMemory(DWORD th32ProcessID,
    LPCVOID lpBaseAddress, LPVOID lpBuffer, DWORD cbRead,
    LPDWORD lpNumberOfBytesRead);

Copies memory allocated to another process into an application-supplied buffer.

•	Returns TRUE if successful.

th32ProcessID

Identifier of the Win32 process whose memory is being copied. This parameter can be zero to copy the memory of the current process.

lpBaseAddress

Base address in the specified process to read. Before transferring any data, the system verifies that all data in the base address and memory of the specified size is accessible for read access. If this is the case, the function proceeds. Otherwise, the function fails.

lpBuffer

Address of the buffer that receives the contents of the address space of the specified process.

cbRead

Number of bytes to read from the specified process.

lpNumberOfBytesRead

Number of bytes copied to the specified buffer. If this parameter is NULL, it is ignored.


 Structures

The following structures are used with tool help services.


HEAPENTRY32 [New - Windows 95]
 HEAPENTRY32

[New - Windows 95]

typedef struct tagHEAPENTRY32

{

    DWORD  dwSize;         // size, in bytes, of structure

    HANDLE hHandle;        // handle of heap block

    DWORD  dwAddress;      // linear address of start of block

    DWORD  dwBlockSize;    // size, in bytes, of heap block

    DWORD  dwFlags;        // see below

    DWORD  dwLockCount;    // see below

    DWORD  dwResvd;        // reserved; do not use

    DWORD  th32ProcessID;  // see below

    DWORD  th32HeapID;     // see below

} HEAPENTRY32;

typedef HEAPENTRY32 *  PHEAPENTRY32;

typedef HEAPENTRY32 *  LPHEAPENTRY32;

Describes one entry (block) of a heap that is being examined.

dwFlags

Flags. These values are defined:

LF32_FIXED	The memory block has a fixed (unmovable) location.
LF32_FREE	The memory block is not used.
LF32_MOVEABLE	The memory block location can be moved.
dwLockCount

Lock count on the memory block. The lock count is incremented each time the GlobalLock or LocalLock function is called on the block either by the application or the DLL that the heap belongs to.

th32ProcessID

Identifier of the Win32 process to examine. The contents of this member can be used by other Win32 functions and macros.

th32HeapID

Heap identifier in the owning process context. The contents of this member has meaning only to the tool help functions. It is not a handle, nor is it usable by other Win32 API elements.


HEAPLIST32 [New - Windows 95]
 HEAPLIST32

[New - Windows 95]

typedef struct tagHEAPLIST32 {

    DWORD dwSize;         // size, in bytes, of structure

    DWORD th32ProcessID;  // see below

    DWORD th32HeapID;     // see below

    DWORD dwFlags;        // see below

} HEAPLIST32;

typedef HEAPLIST32 *  PHEAPLIST32;

typedef HEAPLIST32 *  LPHEAPLIST32;

Describes an entry from a list that enumerates the heaps used by a specified process.

th32ProcessID

Identifier of the Win32 process to examine. The contents of this member can be used by other Win32 functions and macros.

th32HeapID

Heap identifier in the owning process context. The contents of this member has meaning only to the tool help functions. It is not a handle, nor is it usable by other Win32 API elements.

dwFlags

Flags. These values are defined:

HF32_DEFAULT	Process's default heap
HF32_SHARED	Shared heap


MODULEENTRY32 [New - Windows 95]
 MODULEENTRY32

[New - Windows 95]

typedef struct tagMODULEENTRY32 {

    DWORD   dwSize;         // size, in bytes, of structure

    DWORD   th32ModuleID;   // see below

    DWORD   th32ProcessID;  // see below

    DWORD   GlblcntUsage;   // see below

    DWORD   ProccntUsage;   // see below

    BYTE  * modBaseAddr;    // see below

    DWORD   modBaseSize;    // see below

    HMODULE hModule;        // see below

    char    szModule[MAX_MODULE_NAME32 + 1];

    char    szExePath[MAX_PATH];

} MODULEENTRY32;

typedef MODULEENTRY32 *  PMODULEENTRY32;

typedef MODULEENTRY32 *  LPMODULEENTRY32;

Describes an entry from a list that enumerates the modules used by a specified process.

th32ModuleID

Module identifier in the context of the owning process. The contents of this member has meaning only to the tool help functions. It is not a handle, nor is it usable by other Win32 API elements.

th32ProcessID

Identifier of the Win32 process being examined. The contents of this member can be used by other Win32 functions and macros.

GlblcntUsage

Global usage count on the module.

ProccntUsage

Module usage count in the context of the owning process.

modBaseAddr

Base address of the module in the context of the owning process.

modBaseSize

Size, in bytes, of the module.

hModule

Handle of the module in the context of the owning process.

szModule

String containing the module name.

szExePath

String containing the location (path) of the module.

Note  modBaseAddr and hModule are valid only in the context of the process specified by th32ProcessID.


PROCESSENTRY32 [New - Windows 95]
 PROCESSENTRY32

[New - Windows 95]

typedef struct tagPROCESSENTRY32 {

    DWORD dwSize;               // size, in bytes, of structure

    DWORD cntUsage;             // see below

    DWORD th32ProcessID;        // specified process

    DWORD th32DefaultHeapID;    // see below

    DWORD th32ModuleID;         // see below

    DWORD cntThreads;           // see below

    DWORD th32ParentProcessID;  // see below

    LONG  pcPriClassBase;       // see below

    DWORD dwFlags;              // reserved; do not use

    char szExeFile[MAX_PATH];   // see below

} PROCESSENTRY32;

typedef PROCESSENTRY32 *  PPROCESSENTRY32;

typedef PROCESSENTRY32 *  LPPROCESSENTRY32;

Describes an entry from a list that enumerates the processes residing in the system address space when a snapshot was taken.

cntUsage

Number of references to the process. A process exists as long as its usage count is nonzero. As soon as its usage count becomes zero, a process terminates.

th32ProcessID

Identifier of the Win32 process. The contents of this member can be used by other Win32 functions and macros.

th32DefaultHeapID

Identifier of the default heap for the process. The contents of this member has meaning only to the tool help functions. It is not a handle, nor is it usable by other Win32 API elements.

th32ModuleID

Module identifier of the process. The contents of this member has meaning only to the tool help functions. It is not a handle, nor is it usable by other Win32 API elements.

cntThreads

Number of execution threads started by the process.

th32ParentProcessID

Identifier of the Win32 process that created the process being examined. The contents of this member can be used by other Win32 functions and macros.

pcPriClassBase

Base priority of any threads created by this process.

szExeFile

Path and filename of the executable file for the process.


THREADENTRY32 [New - Windows 95]
 THREADENTRY32

[New - Windows 95]

typedef struct tagTHREADENTRY32{

    DWORD  dwSize;              // size, in bytes, of structure

    DWORD  cntUsage;            // see below

    DWORD  th32ThreadID;        // see below

    DWORD  th32OwnerProcessID;  // see below

    LONG   tpBasePri;           // see below

    LONG   tpDeltaPri;          // see below

    DWORD  dwFlags;             // reserved; do not use

} THREADENTRY32;

typedef THREADENTRY32 *  PTHREADENTRY32;

typedef THREADENTRY32 *  LPTHREADENTRY32;

Describes an entry from a list that enumerates the threads executing in the system when a snapshot was taken.

cntUsage

Number of references to the thread. A thread exists as long as its usage count is nonzero. As soon as its usage count becomes zero, a thread terminates.

th32ThreadID

Identifier of the thread. The contents of this member has meaning only to the tool help functions. It is not usable by other Win32 API elements.

th32OwnerProcessID

Identifier of the process that created the thread. The contents of this member can be used by other Win32 functions and macros.

tpBasePri

Initial priority level assigned to a thread. These values are defined:

THREAD_PRIORITY_IDLE

Indicates a base priority level of 1 for IDLE_PRIORITY_CLASS, NORMAL_PRIORITY_CLASS, or HIGH_PRIORITY_CLASS processes, and a base priority level of 16 for REALTIME_PRIORITY_CLASS processes.

THREAD_PRIORITY_LOWEST

Indicates 2 points below normal priority for the priority class.

THREAD_PRIORITY_BELOW_NORMAL

Indicates 1 point below normal priority for the priority class.

THREAD_PRIORITY_NORMAL

Indicates normal priority for the priority class.

THREAD_PRIORITY_ABOVE_NORMAL

Indicates 1 point above normal priority for the priority class.

THREAD_PRIORITY_HIGHEST

Indicates 2 points above normal priority for the priority class.

THREAD_PRIORITY_TIME_CRITICAL

Indicates a base priority level of 15 for IDLE_PRIORITY_CLASS, NORMAL_PRIORITY_CLASS, or HIGH_PRIORITY_CLASS processes, and a base priority level of 31 for REALTIME_PRIORITY_CLASS processes.

tpDeltaPri

Change in the priority level of a thread. This value is a signed delta from the base priority level assigned to the thread.

For additional information about thread priority levels, see the documentation included in the Win32 SDK.


 MS-DOS Extensions

This article describes various MS-DOS extensions for Windows 95 and provides general information about the file system.


 About MS-DOS Extensions

Microsoft® Windows 95® not only supports the complete set of Microsoft® MS-DOS® system functions and interrupts but also provides extensions that permit MS-DOS − based applications to take advantage of Windows 95 features, such as long filenames, exclusive volume locking, virtual machine services, message services, and program information file management. For more information about these topics, see the articles with those names in this guide. For more information about MS-DOS functions and interrupts, see the Microsoft MS-DOS Programmer's Reference.


 Windows 95 Version of MS-DOS

When running with Windows 95, MS-DOS − based applications can check the operating system version by using Get MS-DOS Version Number (Interrupt 21h, Function 30h). For Windows 95, this function returns 7 as the major version number and 0 as the minor version number.

If you need to know that the system is running MS-DOS version 7.0, you must use Interrupt 2Fh Function 4A33h. This function returns zero in the AX register for MS-DOS version 7.0 or higher and returns a nonzero value in AX for any other versions of the disk operating system. In addition to the AX register, this function uses the DS, SI, DX, and BX registers.


 File System Support

Windows 95 supports the long filename file allocation table (FAT) when running Windows. Any physical file on this extended FAT file system will logically be associated with two names — namely, the primary filename (also referred to as the long filename) and its alternate name or alias. Windows 95 automatically generates the alias, and it is always in the standard 8.3 filename format. When a file is saved to disk, the system creates a directory entry for both the long filename and alias. Because the number of entries in the root directory is limited, it is best to store files in a directory below it to avoid filling up the root. For more information about the filename conventions and how the system generates the alias, see "Long Filenames."


 Filename Limitations Under Real Mode

If Windows 95 is started in single MS-DOS application mode (real mode), only the standard FAT file system (and not the long filename FAT file system) is supported. This means that long filenames that are created in a Windows environment will not be visible when the user exits to single MS-DOS application mode, although the names themselves are physically present on the media. Only the alias (the 8.3 filename) will be visible.

When down-level file systems (such as MS-DOS version 6.0, Windows version 3.1, Microsoft® Windows NT™ version 3.1, and OS/2® version 2.11) read a floppy disk that contains long filenames created using Windows 95, the long filename will not be visible; only the alias (the 8.3 filename) will be visible. However, Windows NT version 3.5 supports long filenames. Windows 95 will see the long filenames of files on a floppy disk that were created using Microsoft Windows NT version 3.5, and Windows NT version 3.5 will see the long filenames of files on a floppy disk that were created using Windows 95. Windows 95 will be able to see the long filenames on New Technology file system (NTFS), OS/2's high performance file system (HPFS), or Novell NetWare's file system if there are long filenames on the server.

Because down-level systems are not aware of long filenames, they will not preserve them. If you copy a file from a floppy disk to the hard disk on a down-level system, the long filename associated with the file is not copied over. If you edit a file on the floppy disk using the alias and then save a new copy back on the floppy disk using the down-level system, the long filename associated with the file will most likely be lost. If you take the floppy disk back to the Windows 95 system, only the alias will be associated with the file.


 Preserving Filenames

Certain operations, such as copy, backup, and restore, using older versions of utilities that have not been updated to support long filenames will destroy the long filename. Running a utility called LFNBK that comes with Windows 95 before using older backup utilities will preserve the long filenames. Following are the steps for using LFNBK to backup and restore a disk:

1.	Preserve the long filename and alias (the 8.3 filename) association by running LFNBK /b drive-letter, where drive-letter is the drive that you plan to back up.

2.	Back up the drive (specified as drive-letter in the previous step) using an old backup program that is not be aware of long filenames.

3.	Restore the backup files to a drive, when necessary at some later point, using an old restore program that is not be aware of long filenames.

4.	Restore the long filenames on the drive, by running LFNBK /r drive-letter, where drive-letter is the drive where the files were restored to.


 Searching Filenames

Searches of filenames apply to both the filename and its alias. The system presents a single unified namespace so that a single physical view of the file is preserved. However, if the result of a search shows only the long filename, it could be confusing to the user. For example, a set of files in a directory might include the following filenames and aliases.

Filename	Alias
LongFileName	LONGFI~1
File-1	FILE-1
A search of files in the directory using DIR *1 would display the following information.

LONGFI~1    123    05-11-95    15:26    LongFileName

FILE-1      352    05-11-95    16:01    File-1

Note that the DIR command displays the alias first for compatibility with the older DIR format. However, a search utility that is aware of long filenames but displays only the filename, would also show both the LongFileName and File-1 files. This could be confusing at first glance to the user because the LongFileName file does not have the number 1 as specified in the search criteria. The file was matched to the search pattern because its alias contains the number 1.

The wildcard searches have been expanded in Windows 95. Using the old search criteria, the first * encountered caused all following characters to be ignored. However, in the preceding example, *1 is a valid specification. More than one wildcard can be used in Windows 95 when specifying search criteria. For example, to search for all files that contain the word mid somewhere in the filename, *mid* can be specified as the search criteria.


 Exclusive Volume Locking

Previously reserved fields in the file system directory entry are used for storing the last access date and the creation date and time. A file with a long filename, which is longer than 5 characters, will also cause the system to use previously reserved fields in the directory entry. In previous versions of MS-DOS and Windows, these reserved entries were zero. Older disk repair and checking utilities that have not been updated for Windows 95 might display errors about the disk because of the usage of these reserved entries. It is possible that an older disk repair utility could either destroy the long filename or the actual data in a file because it would mistakenly interpret the file as corrupted. For this reason, Windows 95 is designed to fail utilities that perform direct disk writes. This feature is called exclusive volume locking. A newer version of the utility that understands the newer on-disk file system structures will obtain an exclusive volume lock and proceed correctly.

Exclusive volume locking is also needed because the system is a multitasking system and disk utilities need exclusive access so that they can modify the file system without causing the file system to be inconsistent for the other executing applications. For more information, see "Exclusive Volume Locking."


 Storing Filenames

When an application stores filenames, it should follow these guidelines:

•	Using an alias instead of a long filename can break the association with the file because certain operations, such as editing the file, can potentially change the alias. For example, if the server side of a network uses the alias instead of the long filename of a client file to store information related to the file (such as access permissions), it will be more susceptible to lose the association of permissions with the file. If the user edits the file on the client side, the alias may potentially change, and if it changes, the server side will lose the associated information.

•	When an application caches the absolute path to a filename, the path itself can be a mixture of filenames and aliases. Because of this, applications that need to store a path should store a canonical form of the absolute path. Applications may use either Get Short Path Name (Interrupt 21h Function 7160h) or the Microsoft® Win32® GetShortPathName function to retrieve the canonical form of a path. Applications that need to determine if two files are the same can use the nFileIndexHigh and nFileIndexLow members of the BY_HANDLE_FILE_INFORMATION structure. Note, however, that nFileIndexHigh and nFileIndexLow might not be supported on real-mode file systems, such as Microsoft CD-ROM Extensions (MSCDEX), or real-mode networks.

•	An installation program that needs to enter information into configuration files, such as CONFIG.SYS, should make sure it uses paths that only consist of 8.3 filename components, because the long filenames will not be visible at boot up time when startup files, such as CONFIG.SYS and AUTOEXEC.BAT, are processed. Again, the GetShortPathName function should be used for this purpose.


 Filename Functions

With the exception of the OpenFile function, all of the functions in Windows version 3. x that require the application to pass in a filename (such as LoadLibrary, WinExec, _lopen, and _lcreate) have been updated to support long filenames. For compatibility reasons, functions that return filenames should return only aliases (8.3 filenames) to 16-bit Windows − based applications marked less than 4.0.

MS-DOS − based applications generally use the Interrupt 21h functions. Except for Extended Open/Create (Interrupt 21h Function 6Ch), the older Interrupt 21h functions have not changed in Windows 95. Extended Open/Create has been enhanced in Windows 95 to make use of the last access date for a file. To support long filenames, Windows 95 provides many new Interrupt 21h functions. Any MS-DOS − based application that will use long filenames must be updated to support the new functions. For information about the long filename Interrupt 21h functions, see "Long Filenames."

Windows 95 supports the new Interrupt 21h long filename functions on as many file systems as possible. On file systems, such as MSCDEX, Flash, and real-mode network redirectors, that do not support long filenames, the system automatically translates the newer Interrupt 21h calls to the appropriate older Interrupt 21h calls, as long as the filename passed as a parameter is a valid alias (8.3 filename). Applications may use Get Volume Information (Interrupt 21h Function 71A0h) to retrieve information on the capabilities of the underlying file system.


 Command Interpreter for Command

The for command in the command interpreter (COMMAND.COM) is modal. The default is LFNFOR=OFF, which causes the for command to use the old Interrupt 21h function calls. In that case, only aliases (8.3 filenames) can be used in the for command. If LFNFOR=ON is set, the for command uses the new Interrupt 21h functions, and long filenames can be used as part of the for command.


 Long Command Lines

Although in previous versions of MS-DOS the limit for environment variables and batch file lines is 128 characters, it is 1024 characters in Windows 95. The limit for the keyboard buffer, however, is still 128 characters. Although 1024 and 128 are the standard limits, users may configure their systems to lower these limits.

In previous versions of MS-DOS, command-line arguments are located in the command tail of the program segment prefix (PSP). The command tail in the PSP is limited to 128 characters, including the leading byte that specifies the length of the command line and the trailing carriage return character. In Windows 95, if the command line is less than or equal to 126 characters, it is set in the command tail of the PSP. For command lines that are greater than 126 characters, an application should follow these steps:

1.	Set the count byte in the command tail to 7Fh.

2.	Fill in 7Eh bytes of the command tail followed by the carriage return character (0Dh).

3.	Place the rest of the command line in the CMDLINE environment variable.


 Reference

This section provides information about the following functions and structures.

Get Compressed File Size	Interrupt 21h Function 4302h
Lock/Unlock Removable Media	Interrupt 21h Function 440Dh Minor Code 48h
Eject Removable Media	Interrupt 21h Function 440Dh Minor Code 49h
Get Drive Map Info	Interrupt 21h Function 440Dh Minor Code 6Fh
Get First Cluster	Interrupt 21h Function 440Dh Minor Code 71h
Extended Open/Create	Interrupt 21h Function 6Ch
DRIVE_MAP_INFO	Get Drive Map Info returns information about the specified drive in this structure.
MID	This structure, which is used by Get Media ID (Interrupt 21h Function 440Dh Minor Code 66h) and Set Media ID (Interrupt 21h Function 440Dh Minor Code 46h), has been updated to support compact disc (CD) file systems. For information about using these functions, see the Microsoft MS-DOS Programmer's Reference.
PARAMBLOCK	This structure is needed by Lock/Unlock Removable Media.


 Functions

The following functions are used with MS-DOS extensions.


Interrupt 21h Function 4302h Get Compressed File Size [New - Windows 95]
 Interrupt 21h Function 4302h Get Compressed File Size

[New - Windows 95]

mov ax, 4302h            ; Get Compressed File Size
mov dx, seg PathName     ; see below
mov ds, dx
mov dx, offset PathName
int 21h

jc error

Obtains the compressed size, in bytes, of a given file or directory.

•	Clears the carry flag if successful. Otherwise, the function sets the carry flag and sets the AX register to an error value.

PathName

Address of a null-terminated string that specifies the file or directory to retrieve the file size for.

The function obtains the actual number of bytes of disk storage used to store the file. If the file is located on a volume that supports compression and the file is compressed, the value obtained is the compressed size of the specified file. If the file is not located on a volume that supports compression or if the file is not compressed, the value obtained is the file size, in bytes, rounded up to the nearest cluster boundary.


Interrupt 21h Function 440Dh Minor Code 48h  Lock/Unlock Removable Media [New - Windows 95]
 Interrupt 21h Function 440Dh Minor Code 48h  Lock/Unlock Removable Media

[New - Windows 95]

mov ax, 440Dh           ; generic IOCTL
mov bx, DriveNum        ; see below
mov ch, 8               ; device category
mov cl, 48h             ; Lock or Unlock Removable Media
mov dx, seg ParamBlock  ; see below
mov ds, dx
mov dx, offset ParamBlock
int 21h

jc  error

Locks or unlocks the volume in the given drive (preventing or permitting its removal) or returns the locked status of the given drive.

•	Clears the carry flag and copies the number of pending locks on the given drive to the NumLocks member of the PARAMBLOCK structure if successful. Otherwise, the function sets the carry flag and sets the AX register to one of the following error values:

01h	The function is not supported.
B0h	The volume is not locked in the drive.
B2h	The volume is not removable.
B4h	The lock count has been exceeded.
DriveNum

Drive to lock or unlock. This parameter can be 0 for default drive, 1 for A, 2 for B, and so on.

ParamBlock

Address of a PARAMBLOCK structure that specifies the operation to carry out and receives a count of the number of locks on the drive.


Interrupt 21h Function 440Dh Minor Code 49h  Eject Removable Media [New - Windows 95]
 Interrupt 21h Function 440Dh Minor Code 49h  Eject Removable Media

[New - Windows 95]

mov ax, 440Dh     ; generic IOCTL
mov bx, DriveNum  ; see below
mov ch, 8         ; device category
mov cl, 49h       ; Eject Removable Media
int 21h

jc  error

Ejects the specified media.

•	Clears the carry flag if successful. Otherwise, the function sets the carry flag and sets the AX register to one of the following error values:

01h	The function is not supported.
B1h	The volume is locked in the drive.
B2h	The volume is not removable.
B5h	The valid eject request has failed.
DriveNum

Drive to eject. This parameter can be 0 for default drive, 1 for A, 2 for B, and so on.

If a given physical drive has more than one logical volume, all volumes must be unlocked by using Lock/Unlock Removable Media (Interrupt 21h Function 440Dh Minor Code 48h) before the drive will eject.


Interrupt 21h Function 440Dh Minor Code 6Fh  Get Drive Map Info [New - Windows 95]
 Interrupt 21h Function 440Dh Minor Code 6Fh  Get Drive Map Info

[New - Windows 95]

mov ax, 440Dh            ; generic IOCTL
mov bx, DriveNum         ; see below
mov ch, 8                ; device category
mov cl, 6Fh              ; Get Drive Map Info
mov dx, seg DriveMapInfo ; see below
mov ds, dx
mov dx, offset DriveMapInfo
int 21h

jc  error

Retrieves information about the specified drive.

DriveNum

Drive to obtain information about. This parameter can be 0 for the default drive, 1 for A, 2 for B, and so on.

DriveMapInfo

Address of the DRIVE_MAP_INFO structure that receives information about the specified drive.


Interrupt 21h Function 440Dh Minor Code 71h  Get First Cluster [New - Windows 95]
 Interrupt 21h Function 440Dh Minor Code 71h  Get First Cluster

[New - Windows 95]

mov ax, 440Dh            ; generic IOCTL
mov bx, CharSet          ; see below
mov ch, 08h              ; device category
mov cl, 71h              ; Get First Cluster
mov dx, seg PathName     ; see below

mov ds, dx
mov dx, offset PathName
int 21h

jc error

Retrieves the first cluster of the specified file or directory.

•	Clears the carry flag and sets DX:AX to the first cluster number if successful. Otherwise, the function sets the carry flag and returns either the ERROR_INVALID_FUNCTION or ERROR_ACCESS_DENIED value in AX.

CharSet

Character set of PathName. This parameter must be one of these values:

BCS_WANSI (0)	Windows ANSI character set
BCS_OEM (1)	Current OEM character set
BCS_UNICODE (2)	Unicode character set
PathName

Address of a null-terminated string containing the path of the file or directory to retrieve the first cluster for.

The first cluster of a file is the first cluster of the FAT cluster chain describing the data associated with the file. The first cluster of a directory is the first cluster of the FAT cluster chain associated with the directory. It is the cluster that contains the "." and ".." entries. The function finds any file or directory regardless of attribute (system, hidden, or read-only). It does not find volume labels.

If your application is unable to accommodate a 32-bit cluster number, you must check to see if the value returned in the DX register is greater than zero.

if(MAKELONG(regAX,regDX) > 0x0000FFF8)
    b32BitNum = TRUE;
else
    b32BitNum = FALSE;

It is the calling application's responsibility to check to see if the returned cluster number is valid.

if((MAKELONG(regAX,regDX) < 2L) || (MAKELONG(regAX,regDX) > maxClus))
    bInvalidNum = TRUE;
else
    bInvalidNum = FALSE;

In the preceding example, the maxClus variable is the maximum legal cluster number, as a DWORD type, computed from the drive parameters.


Interrupt 21h Function 6Ch  Extended Open/Create [New - Windows 95]
 Interrupt 21h Function 6Ch  Extended Open/Create

[New - Windows 95]

mov ah, 6Ch             ; Extended Open/Create
mov bx, ModeAndFlags    ; see below
mov cx, Attributes      ; see below
mov dx, Action          ; action to take
mov si, seg Filename    ; see below
mov ds, si
mov si, offset Filename
int 21h

jc error
mov [Handle], ax        ; file handle
mov [ActionTaken], cx   ; action taken to open file

Opens or creates a file having the given name and attributes.

•	Clears the carry flag, copies the file handle to the AX register, and sets CX to one of the following values if successful:

ACTION_OPENED (0001h)

ACTION_CREATED_OPENED (0002h)

ACTION_REPLACED_OPENED (0003h)

Otherwise, this function sets the carry flag and sets the AX register to one of the following error values:

ERROR_INVALID_FUNCTION (0001h)

ERROR_FILE_NOT_FOUND (0002h)

ERROR_PATH_NOT_FOUND (0003h)

ERROR_TOO_MANY_OPEN_FILES (0004h)

ERROR_ACCESS_DENIED (0005h)

ModeAndFlags

Combination of access mode, sharing mode, and open flags. This parameter can be one value each from the access and sharing modes and any combination of open flags:

Access mode	Meaning
OPEN_ACCESS_READONLY (0000h)
	Opens the file for reading only.
OPEN_ACCESS_WRITEONLY (0001h)
	Opens the file for writing only.
OPEN_ACCESS_READWRITE (0002h)
	Opens the file for reading and writing.
0003h
	Reserved; do not use.
OPEN_ACCESS_RO_NOMODLASTACCESS (0004h)
	Opens the file for reading only without modifying the file's last access date.
Sharing mode	Meaning
OPEN_SHARE_COMPATIBLE (0000h)
	Opens the file with compatibility mode, allowing any process on a given computer to open the file any number of times.
OPEN_SHARE_DENYREADWRITE (0010h)
	Opens the file and denies both read and write access to other processes.
OPEN_SHARE_DENYWRITE (0020h)
	Opens the file and denies write access to other processes.
OPEN_SHARE_DENYREAD (0030h)
	Opens the file and denies read access to other processes.
OPEN_SHARE_DENYNONE (0040h)
	Opens the file without denying read or write access to other processes, but no process may open the file with compatibility mode.
Open flags	Meaning
OPEN_FLAGS_NOINHERIT (0080h)
	If this flag is set, a child process created with Load and Execute Program (Interrupt 21h Function 4B00h) does not inherit the file handle. If the handle is needed by the child process, the parent process must pass the handle value to the child process. If this flag is not set, child processes inherit the file handle.
OPEN_FLAGS_NOCRITERR (2000h)
	If a critical error occurs while MS-DOS is opening this file, Critical-Error Handler (Interrupt 24h) is not called. Instead, MS-DOS simply returns an error value to the program.
OPEN_FLAGS_COMMIT (4000h)
	After each write operation, MS-DOS commits the file (flushes the contents of the cache buffer to disk).
Attributes

Attributes for files that are created or truncated. This parameter may be a combination of these values:

FILE_ATTRIBUTE_NORMAL (0000h)
	The file can be read from or written to. This value is valid only if used alone.
FILE_ATTRIBUTE_READONLY (0001h)
	The file can be read from, but not written to.
FILE_ATTRIBUTE_HIDDEN (0002h)
	The file is hidden and does not appear in an ordinary directory listing.
FILE_ATTRIBUTE_SYSTEM (0004h)
	The file is part of the operating system or is used exclusively by it.
FILE_ATTRIBUTE_VOLUME (0008h)
	The name specified by Filename is used as the volume label for the current medium.
FILE_ATTRIBUTE_ARCHIVE (0020h)
	The file is an archive file. Applications use this value to mark files for backup or removal.
Action

Action to take it the file exists or does not exist. This parameter can be a combination of these values:

FILE_CREATE (0010h)	Creates a new file if it does not already exist or fails if the file already exists.
FILE_OPEN (0001h)	Opens the file. The function fails if the file does not exist.
FILE_TRUNCATE (0002h)	Opens the file and truncates it to zero length (replaces the existing file). The function fails if the file does not exist.
The only valid combinations are FILE_CREATE combined with FILE_OPEN or FILE_CREATE combined with FILE_TRUNCATE.

Filename

Address of a null-terminated string specifying the name of the file to be opened or created. The name must be in the standard MS-DOS 8.3 filename format. The string must be a valid path for the volume associated with the given drive.

This function does not support long filenames. If the specified name is too long, this function truncates the name to the standard 8.3 format following the same naming scheme that the system uses when creating an alias for a long filename.

A file on a remote directory — that is, a directory on the network — cannot be opened, unless appropriate permissions for the directory exist.


 Structures

The following structures are used with MS-DOS extensions.


DRIVE_MAP_INFO [New - Windows 95]
 DRIVE_MAP_INFO

[New - Windows 95]

DRIVE_MAP_INFO	struc

    dmiAllocationLength   db ?  ; see below
    dmiInfoLength         db ?  ; see below
    dmiFlags              db ?  ; see below
    dmiInt13Unit          db ?  ; see below
    dmiAssociatedDriveMap dd ?  ; see below
    dmiPartitionStartRBA  dq ?  ; see below
DRIVE_MAP_INFO	ends

Contains information about the drive specified in the call to Get Drive Map Info (Interrupt 2lh Function 440Dh Minor Code 6Fh).

dmiAllocationLength

Length of the buffer provided by the application calling Get Drive Map Info. This value should be the size of the DRIVE_MAP_INFO structure.

dmiInfoLength

Number of bytes that Get Drive Map Info used in the buffer provided by the calling application. Typically, this value is the size of the DRIVE_MAP_INFO structure.

dmiFlags

Flags describing the given drive. This member, which is filled by Get Drive Map Info, can be a combination of these values:

PROT_MODE_LOGICAL_DRIVE (01h)	A protected-mode driver is in use for this logical drive.
PROT_MODE_PHYSICAL_DRIVE (02h)	A protected-mode driver is in use for the physical drive corresponding to this logical drive.
PROT_MODE_ONLY_DRIVE (04h)	The drive is not available when running with MS-DOS.
PROT_MODE_EJECT (08h)	A protected-mode drive supports an electronic eject operation.
PROT_MODE_ASYNC_NOTIFY (10h)	The drive issues media arrival and removal notifications. This value is currently used for CD-ROM drives that are controlled by the protected-mode driver and that cause a broadcast message when media is removed or inserted without the application having to make a request to the drive. It can also be used by disk drivers.
dmiInt13Unit

Physical drive number of the given drive. This member, which is filled by Get Drive Map Info, can be one of these values:

00 - 7Fh	Floppy disk drive (00 for the first floppy drive, 01 for the second, and so on).
80 - FEh	Hard disk drive (80 for the first hard disk drive, 81 for the second, and so on).
FFh	The given drive does not map to a physical drive.
dmiAssociatedDriveMap

Logical drive numbers that are associated with the given physical drive. For example, a host drive C with child drive letters A and B would return with bits 0 and 1 set.

dmiPartitionStartRBA

Relative block address offset from the start of the physical volume to the start of the given partition.

Before an application makes a call to Get Drive Map Info, the dmiAllocationLength member must be set to the size of the DRIVE_MAP_INFO structure. All other members of the structure are filled in by Get Drive Map Info.


MID [New - Windows 95]
 MID

[New - Windows 95]

MID struc
    midInfoLevel   dw 0           ; see below
    midSerialNum   dd ?           ; see below
    midVolLabel    db 11 dup (?)  ; see below
    midFileSysType db 8 dup (?)   ; see below
MID ends

Contains information that uniquely identifies a disk or other storage medium.

midInfoLevel

Information level. This member must be zero.

midSerialNum

Serial number for the medium.

midVolLabel

Volume label for the medium. If the label has fewer than 11 characters, space characters (ASCII 20h) fill the remaining bytes in this member.

midFileSysType

Type of file system as an 8-byte ASCII string. This member can be one of these values:

FAT12	12-bit file allocation table (FAT)
FAT16	16-bit FAT
CDROM	High Sierra file system
CD001	ISO9660 file system
CDAUDIO	Audio disk
If the name has fewer than eight characters, space characters (ASCII 20h) fill the remaining bytes in this member.


PARAMBLOCK [New - Windows 95]
 PARAMBLOCK

[New - Windows 95]

PARAMBLOCK struc
    Operation db ?  ; see below
    NumLocks  db ?  ; see below
PARAMBLOCK ends

Contains information about locked drives.

Operation

Operation to carry out provided by the calling application of Lock/Unlock Removable Media (Interrupt 21h Function 440Dh Minor Code 48h). This member can be one of these values:

0	Locks the volume in the drive.
1	Unlocks the volume in the drive.
2	Returns the lock or unlock status.
All other values are reserved.

NumLocks

Number of locks pending on the given drive filled in by Lock/Unlock Removable Media.


 Long Filenames

Microsoft® Windows® 95 allows users and applications to create and use long names for their files and directories. A long filename is a name for a file or directory that exceeds the standard 8.3 filename format.


 About Long Filenames

In the past, long filenames typically appeared on network servers that used file systems other than the Microsoft® MS-DOS® file allocation table (FAT) file system. In Windows 95, however, long filenames are available for use with network servers and with local disk drives supporting the protected-mode FAT file system.

This article describes the long filename functions and explains how to create and use long filenames in applications written for MS-DOS and 16-bit Windows version 3. x. Microsoft® Win32®-based applications automatically have access to long filenames through the use of the corresponding Win32 file management functions.


 Long Filenames and the Protected-Mode FAT File System

The protected-mode FAT file system is the default file system used by Windows 95 for mass storage devices, such as hard disk and floppy disk drives. Protected-mode FAT is compatible with the MS-DOS FAT file system, using file allocation tables and directory entries to store information about the contents of a disk drive. Protected-mode FAT also supports long filenames, storing these names as well as the date and time that the file was created and the date that the file was last accessed in the FAT file system structures.

The protected-mode FAT file system allows filenames of up to 256 characters, including the terminating null character. In this regard, it is similar to the Microsoft® Windows NT™ file system (NTFS), which allows filenames of up to 256 characters. Protected-mode FAT allows directory paths (excluding the filename) of up to 246 characters, including the drive letter, colon, and leading backslash. This limit of 246 allows for the addition of a filename in the standard 8.3 format with the terminating null character. The maximum number of characters in a full path, including the drive letter, colon, leading backslash, filename, and terminating null character, is 260.

When an application creates a file or directory that has a long filename, the system automatically generates a corresponding alias for that file or directory using the standard 8.3 format. The characters used in the alias are the same characters that are available for use in MS-DOS file and directory names. Valid characters for the alias are any combination of letters, digits, or characters with ASCII codes greater than 127, the space character (ASCII 20h), as well as any of the following special characters.

$ % ' - _ @   ~ ` ! ( ) { } ^ # &

The space character has been available to applications for filenames and directory names through the functions in current and earlier versions of MS-DOS. However, many applications do not recognize the space character as a valid character, and the system does not use the space character when it generates an alias for a long filename. MS-DOS does not distinguish between uppercase and lowercase letters in filenames and directory names, and this is also true for aliases.

The set of valid characters for long filenames includes all the characters that are valid for an alias as well as the following additional characters.

+ , ; = [ ]

Windows 95 preserves the case of the letters used in long filenames. However, the protected-mode FAT file system, which is not case sensitive, will not allow more than one file to have the same name except for case in the same directory. For example, files named Long File Name and long file name are not allowed to exist in the same directory. Although extended ASCII characters (characters with ASCII codes greater than 127) are also permitted in filenames, programs should avoid them, because the meanings of the extended characters may vary according to code page. On disk, the characters in the alias are stored using the OEM character set of the current code page, and the long filename is stored using Unicode format.

Although the protected-mode FAT file system is the default file system in Windows 95, it is not the only file system accessible to applications running with Windows 95. For example, applications that connect to network drives may encounter other file systems, such as NTFS. Before using long filenames for files and directories on a volume in a given drive, you must determine the maximum lengths of filenames and paths by using Get Volume Information (Interrupt 21h Function 71A0h). The function returns values that you can use to make sure your filenames and paths are within the limits of the file system.

In general, you should avoid using static buffers for filenames and paths. Instead, you should use the values returned by Get Volume Information to allocate buffers as you need them. If you must use static buffers, you should reserve 256 characters for filenames and 260 characters for paths. These are the maximum sizes currently recommended for Win32-based applications.


 Filename Aliases

When an application creates a file or directory that has a long filename, the system automatically generates a corresponding short filename (alias) for that file or directory, using the standard 8.3 format. Aliases ensure that existing applications that do not handle long filenames can, nevertheless, access those files and directories.

If the long filename follows the standard 8.3 format, the alias has the same name except that all lowercase letters are converted to uppercase. For example, if the long filename is Examples.Txt, the corresponding alias will be EXAMPLES.TXT.

If the long filename does not follow the standard 8.3 format, the system automatically generates an alias, using the following scheme to ensure that the alias has a unique name. The system tries to create a name by using the first 6 characters of the long filename followed by a numeric tail. A numeric tail consists of the tilde (~) character followed by a number. The system starts with the number 1 in the numeric tail. If that filename already exists, it uses the number 2. It continues in this fashion until a unique name is found. If the long filename has a filename extension, the system will use the first three characters of the long filename's extension as the extension for the alias.

As the number of digits in the numeric tail grows, fewer characters in the long filename are used for the 8 characters in the alias. For example, the alias for Long File Name.File would be LONGFI~10.FIL if the names LONGFI~1.FIL through LONGFI~9.FIL already existed in the directory. Applications can override the default alias numbering scheme when creating a file by specifying the OPEN_FLAGS_ALIAS_HINT value and supplying a number to use in the call to Create or Open File (Interrupt 21h Function 716Ch).

A period is just another character in a long filename. Leading periods are allowed in a long filename, but trailing periods are stripped. A file can have multiple periods as part of its name. For example, MyFile.081293.Document is a valid filename, and its alias will be MYFILE~1.DOC. The first three characters after the last period in the filename are used as the filename extension for the alias, as long as the last period is not a leading period. A filename of .login is also valid, and its alias is LOGIN~1.

In a given directory, the long filename and its alias must uniquely identify a file. For example, if there is a file with the long filename Long File Name and the alias LONGFI~1, the system will not allow either Long File Name or LONGFI~1 to be used as another file's long filename.

If a file with a long filename is copied or edited, the alias for the resulting file may be different from the original alias. For example, if the destination directory contains an alias that conflicts with the original alias, the system generates another unique alias. If a long filename LongFileName is associated with the alias LONGFI~2 and is later copied to a different directory using the long filename, the alias in the destination directory might be LONGFI~1 (unless a file with that name already existed in the destination directory). The system always generates new aliases during these operations and always chooses aliases that do not conflict with existing filenames. An application must never rely on an alias being the same for all copies and versions of a given file.

Applications can open, read, and write from a file using the alias without affecting the long filename. However, some operations on the alias, such as copy, move, backup, and restore, may result in the original long filename being destroyed. For example, older versions of utilities that do not support long filenames can destroy the long filename while performing those operations.

The system attempts to preserve a long filename, even when the file associated with it is edited by an application that is not aware of long filenames. Typically, these applications operate on a temporary copy of the file, and when the user elects to save the file, the application deletes the destination file or renames it to another name. The application then renames the temporary file to the destination name or creates a new file with new contents.

When an application makes a system call to delete or rename an alias, the system first gathers and saves a packet of information about the file and then performs the delete or rename operation. The information saved includes the long filename as well as the creation date and time, the last modification date and time, and the last access date of the original file. After the system performs the delete or rename operation, the system watches for a short period of time (the default is 15 seconds) to see if a call is made to create or rename a file with the same name. If the system detects a create or rename operation of a recently deleted alias, it applies the packet of information that it had saved to the new file, thus preserving the long filename.

Currently, Load and Execute Program (Interrupt 21h Function 4B00h) does not accept long filenames. If an application starts other applications, it must retrieve the filename alias for the given executable file and pass that alias to Load and Execute Program.


 File and Directory Management

The standard MS-DOS file and directory management functions do not accept long filenames. You must, therefore, use the long filename functions to create and manage files and directories having long names. The long filename functions are similar to existing MS-DOS system functions. You copy function parameters to registers and issue an Interrupt 21h instruction to carry out the call. The function sets or clears the carry flag to indicate whether the operation was successful and may also return information in registers.

If a long filename function has a corresponding MS-DOS function, the number that identifies the long filename function is four digits long, beginning with the number 71 and ending in the same number as the corresponding MS-DOS function. For example, the long filename function Make Directory (Interrupt 21h Function 7139h) corresponds to MS-DOS Create Directory (Interrupt 21h Function 39h).

You can create or open a file having a long filename by using Create or Open File (Interrupt 21h Function 716Ch). This function takes the name and attributes of the file to create or open and returns a handle that you use to identify the file in subsequent calls to standard MS-DOS functions, such as Read File or Device (Interrupt 21h Function 3Fh) and Write File or Device (Interrupt 21h Function 40h).

You can set or retrieve the time and attributes for a file having a long filename by using Get or Set File Time (Interrupt 21h Function 57h) and Get or Set File Attributes (Interrupt 21h Function 7143h). You can move a file having a long filename by using Rename File (Interrupt 21h Function 7156h) or delete the file by using Delete File (Interrupt 21h Function 7141h).

You can create a directory having a long filename by using Make Directory (Interrupt 21h Function 7139h) or remove the directory by using Remove Directory (Interrupt 21h Function 713Ah).

You can set and retrieve the current directory by using Change Directory (Interrupt 21h Function 713Bh) and Get Current Directory (Interrupt 21h Function 7147h).


 File Searches

You can search directories for selected files by using Find First File and Find Next File (Interrupt 21h Functions 714Eh and 714Fh). These functions search for and return information about files having long filenames and aliases (filenames in the standard 8.3 format). The functions return information in a WIN32_FIND_DATA structure, which contains both the filename and the corresponding alias, if any.

Unlike MS-DOS Find First File (Interrupt 21h Function 4Eh), the long filename version of Find First File allocates internal storage for the search operations and returns a handle that identifies the storage. This handle is used with Find Next File. To make sure the internal storage is freed, you must use Find Close (Interrupt 21h Function 71A1h) to end the search.

You pass the Delete File (Interrupt 21h Function 7141h) and Find First File functions a filename, which may contain wildcard characters, such as an asterisk (*) or question mark (?). Because Find First File, Find Next File, and Delete File examine long filenames and aliases during the search, some wildcard searches may yield unexpected results. For example, if the system has generated the alias LONGFI~1 for the long filename LongFileName, a search for names that match the *1 pattern would always return the LongFileName file, even though that name does not end with a 1. Searches are not case-sensitive. For example, a search for names that match the *mid* pattern will yield the same results as that for the *MID* pattern. In general, you should check both names returned in the WIN32_FIND_DATA structure to determine which of them matched the pattern.

Wildcard searches are more flexible in Windows 95 than in MS-DOS. In the preceding examples, *1 finds the filenames that end in a 1 and *mid* finds filenames that contain the characters mid. In MS-DOS and in Windows 95 searching on real-mode FAT directories, all characters after the first * are ignored.


 Down-Level Systems

Long filenames, file last access date, and file creation date and time are not supported while the file system is in single MS-DOS application mode. They are not supported either in versions of MS-DOS that only use the real-mode FAT file system. These file systems and others that do not support long filenames are referred to as down-level systems. If you intend for an application to run with both Windows 95 and down-level systems, you should always check the system to determine whether it supports the long filename functions. The easiest way to check is to call Get Volume Information (Interrupt 21h Function 71A0h). This function returns an error if the system does not support the long filename functions.

Another way of handling down-level systems is to use a combination of calls to long filename and standard MS-DOS functions to carry out file management. In this case, you call the standard function only if the long filename function is not supported. To indicate an unsupported function, the system sets the AL register to zero but leaves the AH register and the carry flag unchanged. The following example shows how to combine long filename and standard functions to carry out a file or directory management operation.

stc            ; set carry for error flag
               ; set registers here for LFN function call
int 21h        ; call long filename function
jnc success    ; call succeeded, continue processing
cmp ax, 7100h  ; is call really not supported?
jne failure    ; supported, but error occurred
               ; set registers here for MS-DOS function call
int 21h        ; call standard MS-DOS function

Application developers have to decide what to do when users save a file with a long filename to a down-level system. One approach is to imitate the behavior of the command interpreter (COMMAND.COM) and save the file using the alias without informing the user. A different approach is to have the application inform the user that the file system does not support long filenames and allow the user to save the file with a filename in the standard 8.3 format.


 Last Access Date

The Windows 95 last access date is intended to reflect the last time a file was accessed for the purpose for which it was created. This date is intended to provide a means for applications, users, or both to determine which files have not been used recently. When an application saves a file, the system automatically resets the last access date. An application that cannot understand the contents of the files it is accessing should save the last access date and restore it after closing the file. For example, applications that back up a file, search files for strings, and scan for viruses should save and restore the last access date.

Applications should allow the system to set the last access date in the following cases:

•	Running a program should set the last access date for the .EXE file.

•	Loading a dynamic-link library (DLL) should set the last access date for the .DLL file.

•	Editing or printing a document should set the last access date for the document file.

•	In general, any use of a document by an application that creates or modifies that type of document should set the last access date (unless the document is being opened only to decide whether it is to be used in a find operation).

•	Application use of peripheral files (.INI files and so on) should set the last access date.

Win32-based applications can preserve the last access date by using the GetFileTime and SetFileTime functions. Applications written for MS-DOS or Windows version 3. x can use Get Last Access Date and Time (Interrupt 21h Function 5704h) and Set Last Access Date and Time (Interrupt 21h Function 5705h), or they can open the file with Create or Open File (Interrupt 21h Function 716Ch) using the OPEN_ACCESS_RO_NOMODLASTACCESS (0004h) access mode.


 Reference

The long filename functions described previously match the following Win32 file management functions.

Long filename function	Win32 function
Interrupt 21h Function 5704h Get Last Access Date and Time	GetFileTime
Interrupt 21h Function 5705h Set Last Access Date and Time	SetFileTime
Interrupt 21h Function 5706h Get Creation Date and Time	GetFileTime
Interrupt 21h Function 5707h Set Creation Date and Time	SetFileTime
Interrupt 21h Function 7139h Make Directory	CreateDirectory
Interrupt 21h Function 713Ah Remove Directory	RemoveDirectory
Interrupt 21h Function 713Bh Change Directory	SetCurrentDirectory
Interrupt 21h Function 7141h Delete File	DeleteFile
Interrupt 21h Function 7143h Get or Set File Attributes	GetFileAttributes, SetFileAttributes
Interrupt 21h Function 7147h Get Current Directory	GetCurrentDirectory
Interrupt 21h Function 714Eh Find First File	FindFirstFile
Interrupt 21h Function 714Fh Find Next File	FindNextFile
Interrupt 21h Function 7156h Rename File	MoveFile
Interrupt 21h Function 7160h Get Full Path Name	GetFullPathName
Interrupt 21h Function 7160h Get Short Path Name	GetShortPathName
Interrupt 21h Function 7160h Get Long Path Name	No Win32 function equivalent.
Interrupt 21h Function 716Ch Create or Open File	CreateFile, OpenFile
Interrupt 21h Function 71A0h Get Volume Information	GetVolumeInformation
Interrupt 21h Function 71A1h Find Close	FindClose
Interrupt 21h Function 71A6h Get File Info By Handle	GetFileInformationByHandle
Interrupt 21h Function 71A7h  File Time To DOS Time	FileTimeToDOSDateTime
Interrupt 21h Function 71A7h  DOS Time To File Time	DOSDateTimeToFileTime
Interrupt 21h Function 71A8h Generate Short Name	No Win32 function equivalent
Interrupt 21h Function 71A9h  Server Create or Open File	No Win32 function equivalent
Interrupt 21h Function 71AAh Create Subst	No Win32 function equivalent
Interrupt 21h Function 71AAh Terminate Subst	No Win32 function equivalent
Interrupt 21h Function 71AAh Query Subst	No Win32 function equivalent
Note that Interrupt 21h Functions 71A2h through 71A5h exist, but they are for internal use by Windows 95 only.


 Functions

The following functions are associated with long filenames.


Interrupt 21h Function 5704h  Get Last Access Date and Time [New - Windows 95]
 Interrupt 21h Function 5704h  Get Last Access Date and Time

[New - Windows 95]

mov ax, 5704h   ; Get Last Access Date and Time
mov bx, Handle  ; see below
int 21h

jc  error
mov [Date], dx  ; last access date
mov [Time], cx  ; currently not supported, always 0

Retrieves the last access date for the given file.

•	Clears the carry flag and sets the CX register to zero and the DX register to these values if successful:

Bits	Contents
0−4	Day of the month (1−31)
5−8	Month (1 = January, 2 = February, and so on)
9−15	Year offset from 1980 (that is, add 1980 to get the actual year)
Otherwise, the function sets the carry flag and sets the AX register to an error value.

Handle

File handle.


Interrupt 21h Function 5705h  Set Last Access Date and Time [New - Windows 95]
 Interrupt 21h Function 5705h  Set Last Access Date and Time

[New - Windows 95]

mov ax, 5705h       ; Set Last Access Date and Time
mov bx, Handle      ; see below
mov cx, 0           ; time currently not supported, always 0
mov dx, AccessDate  ; see below
int 21h

jc  error

Sets the last access date for the given file.

•	Clears the carry flag if successful. Otherwise, the function sets the carry flag and sets the AX register to an error value.

Handle

File handle.

AccessDate

New access date. The date is a packed 16-bit value with this form:

Bits	Contents
0−4	Day of the month (1−31)
5−8	Month (1 = January, 2 = February, and so on)
9−15	Year offset from 1980 (that is, add 1980 to get the actual year)


Interrupt 21h Function 5706h  Get Creation Date and Time [New - Windows 95]
 Interrupt 21h Function 5706h  Get Creation Date and Time

[New - Windows 95]

mov ax, 5706h           ; Get Creation Date and Time
mov bx, Handle          ; see below
int 21h

jc  error
mov [Time], cx          ; creation time
mov [Date], dx          ; creation date
mov [MilliSeconds], si  ; number of 10 ms intervals in 2 seconds

Retrieves the creation date and time for the given file.

•	Clears the carry flag and sets the CX, DX, and SI registers to these values if successful:

CX	Creation time. The time is a packed 16-bit value with the following form:
Bits	Contents
0−4	Second divided by 2
5−10	Minute (0−59)
11−15	Hour (0−23 on a 24-hour clock)
DX	Creation date. The date is a packed 16-bit value with the following form:
Bits	Contents
0−4	Day of the month (1−31)
5−8	Month (1 = January, 2 = February, and so on)
9−15	Year offset from 1980 (that is, add 1980 to get the actual year)
SI	Number of 10 millisecond intervals in 2 seconds to add to the MS-DOS time. The number can be a value in the range of 0 to 199.
Otherwise, the function sets the carry flag and sets the AX register to an error value.

Handle

File handle.


Interrupt 21h Function 5707h  Set Creation Date and Time [New - Windows 95]
 Interrupt 21h Function 5707h  Set Creation Date and Time

[New - Windows 95]

mov ax, 5707h         ; Set Creation Date and Time
mov bx, Handle        ; see below
mov cx, Time          ; see below
mov dx, Date          ; see below
mov si, MilliSeconds  ; see below
int 21h

jc  error

Sets the creation date and time for the given file.

•	Clears the carry flag if successful. Otherwise, the function sets the carry flag and sets the AX register to an error value.

Handle

File handle.

Time

New creation time. The time is a packed 16-bit value with the following form:

Bits	Contents
0−4	Second divided by 2
5−10	Minute (0−59)
11−15	Hour (0−23 on a 24-hour clock)
Date

New creation date. The date is a packed 16-bit value with the following form:

Bits	Contents
0−4	Day of the month (1−31)
5−8	Month (1 = January, 2 = February, and so on)
9−15	Year offset from 1980 (that is, add 1980 to get the actual year)
MilliSeconds

Number of 10 millisecond intervals in 2 seconds to add to the MS-DOS time. The number can be a value in the range 0 to 199.


Interrupt 21h Function 7139h  Make Directory [New - Windows 95]
 Interrupt 21h Function 7139h  Make Directory

[New - Windows 95]

mov ax, 7139h     ; Make Directory
mov dx, seg Name  ; see below
mov ds, dx
mov dx, offset Name
int 21h

jc  error

Creates a new directory having the given name.

•	Clears the carry flag if successful. Otherwise, the function sets the carry flag and sets the AX register to an error value.

Name

Address of a null-terminated string specifying the name of the directory to create. Long filenames are allowed.


Interrupt 21h Function 713Ah  Remove Directory [New - Windows 95]
 Interrupt 21h Function 713Ah  Remove Directory

[New - Windows 95]

mov ax, 713Ah     ; Remove Directory
mov dx, seg Name  ; see below
mov ds, dx
mov dx, offset Name
int 21h

jc  error

Removes the given directory. The directory must be empty.

•	Clears the carry flag if successful. Otherwise, the function sets the carry flag and sets the AX register to an error value.

Name

Address of a null-terminated string specifying the name of the directory to remove. Long filenames are allowed.

The root directory cannot be deleted.


Interrupt 21h Function 713Bh  Change Directory [New - Windows 95]
 Interrupt 21h Function 713Bh  Change Directory

[New - Windows 95]

mov ax, 713Bh     ; Change Directory
mov dx, seg Path  ; see below
mov ds, dx
mov dx, offset Path
int 21h

jc error

Changes the current directory to the directory specified by the given path.

•	Clears the carry flag if successful. Otherwise, the function sets the carry flag and sets the AX register to an error value.

Path

Address of a null-terminated string specifying the directory to change to. The path, which can include the drive letter, must be a valid path for the given volume. Long filenames are allowed.

The current or default directory is the directory that the system uses whenever an application supplies a filename that does not explicitly specify a directory. Similarly, the current or default drive is the drive the system uses whenever an application supplies a path that does not explicitly specify a drive. If a drive other than the default drive is specified as part of the new directory path, this function changes the current directory on that drive but does not change the default drive. Set Default Drive (Interrupt 21h Function 0Eh) can be used to change the default drive.


Interrupt 21h Function 7141h  Delete File [New - Windows 95]
 Interrupt 21h Function 7141h  Delete File

[New - Windows 95]

mov ax, 7141h             ; Delete File
mov ch, MustMatchAttrs    ; see below

mov cl, SearchAttrs       ; see below
mov dx, seg Filename      ; see below
mov ds, dx
mov dx, offset Filename
mov si, WildcardAndAttrs  ; see below
int 21h

jc error

Deletes the given file or files. If the specified filename contains a wildcard character, this function can delete multiple files that match the wildcard.

•	Clears the carry flag if successful. Otherwise, the function sets the carry flag and sets the AX register to an error value.

MustMatchAttrs

Additional filter on the attributes specified in SearchAttrs. This parameter can be a combination of these values:

FILE_ATTRIBUTE_NORMAL (0000h)
	The file can be read from or written to. This value is valid only if used alone.
FILE_ATTRIBUTE_READONLY (0001h)
	The file can be read from, but not written to.
FILE_ATTRIBUTE_HIDDEN (0002h)
	The file is hidden and does not appear in an ordinary directory listing.
FILE_ATTRIBUTE_SYSTEM (0004h)
	The file is part of the operating system or is used exclusively by it.
FILE_ATTRIBUTE_VOLUME (0008h)
	The name specified by Filename is used as the volume label for the current medium.
FILE_ATTRIBUTE_DIRECTORY (0010h)
	The name specified by Filename is used as a directory, not a file.
FILE_ATTRIBUTE_ARCHIVE (0020h)
	The file is an archive file. Applications use this value to mark files for backup or removal.
SearchAttrs

File attributes to search for. This parameter can be a combination of these values:

FILE_ATTRIBUTE_NORMAL (0000h)

FILE_ATTRIBUTE_READONLY (0001h)

FILE_ATTRIBUTE_HIDDEN (0002h)

FILE_ATTRIBUTE_SYSTEM (0004h)

FILE_ATTRIBUTE_VOLUME (0008h)

FILE_ATTRIBUTE_DIRECTORY (0010h)

FILE_ATTRIBUTE_ARCHIVE (0020h)

Filename

Address of a null-terminated string specifying the name of the file to delete. If WildcardAndAttrs is 1, the "*" and "?" wildcard characters are permitted in the filename. Long filenames are allowed.

WildcardAndAttrs

Search criteria. This parameter must be one of these values:

0	Wildcard characters are not allowed in Filename. Any specified attributes are ignored.
1	Wildcard characters are allowed in Filename. Files with specified attributes are matched.
Wildcard searches are more flexible in Windows 95 than in MS-DOS. Both long filenames and aliases are considered in searches. For example, *1 finds Windows 95 filenames (both long filenames and aliases) that end in a 1 and *mid* finds filenames that contain the characters mid. In MS-DOS and in Windows 95 searching on real-mode FAT directories, all characters after the first * are ignored.

For more information about how MustMatchAttrs and SearchAttrs are used, see the comments for Find First File (Interrupt 21h Function 714Eh).


Interrupt 21h Function 7143h  Extended Get or Set File Attributes [New - Windows 95]
 Interrupt 21h Function 7143h  Extended Get or Set File Attributes

[New - Windows 95]

mov ax, 7143h         ; Get or Set File Attributes
mov bl, Action        ; see below
mov cx, Attributes    ; see below
mov di, Date          ; see below
mov cx, Time          ; see below
mov si, MilliSeconds  ; see below
mov dx, seg Filename  ; see below
mov ds, dx
mov dx, offset Filename
int 21h

jc  error
; see below for return values

Retrieves or sets the file attributes, gets the compressed file size, or retrieves or sets the date and time for the given file.

•	Clears the carry flag if successful.

If Action is zero (retrieve attributes), the file attributes returned in the CX register may be a combination of the following values :

FILE_ATTRIBUTE_NORMAL (0000h)

FILE_ATTRIBUTE_READONLY (0001h)

FILE_ATTRIBUTE_HIDDEN (0002h)

FILE_ATTRIBUTE_SYSTEM (0004h)

FILE_ATTRIBUTE_VOLUME (0008h)

FILE_ATTRIBUTE_DIRECTORY (0010h)

FILE_ATTRIBUTE_ARCHIVE (0020h)

If Action is 2 (get physical size of a compressed file), the size, in bytes, of the compressed file is returned in DX:AX. This value is the physical size of the compressed file — that is, the actual number of bytes that the compressed file occupies on disk.

If Action is 4 (get last write date/time) or 8 (get creation date/time), the CX register contains the time as a packed 16-bit value with the following form:

Bits	Contents
0−4	Second divided by 2
5−10	Minute (0−59)
11−15	Hour (0−23 on a 24-hour clock)
If Action is 4 (get last write date/time), 6 (get last access date), or 8 (get creation date/time), the DI register contains the date as a packed 16-bit value with the following form:

Bits	Contents
0−4	Day of the month (1−31)
5−8	Month (1 = January, 2 = February, and so on)
9−15	Year offset from 1980 (that is, add 1980 to get the actual year)
If Action is 8 (get creation date/time), the SI register contains the number of 10 millisecond intervals in 2 seconds to add to the MS-DOS time. The number can be a value in the range of 0 to 199.

If the function is not successful, it sets the carry flag and sets the AX register to an error value.

Action

Action to take. This parameter can be one of the following values:

0	Retrieve attributes.
1	Set specified attributes.
2	Get physical size of a compressed file.
3	Set last write date/time.
4	Get last write date/time.
5	Set last access date.
6	Get last access date.
7	Set creation date/time.
8	Get creation date/time.
Attributes

File attributes to set, which are used only if Action is 1. This parameter can be a combination of these values:

FILE_ATTRIBUTE_NORMAL (0000h)
	The file can be read from or written to. This value is valid only if used alone.
FILE_ATTRIBUTE_READONLY (0001h)
	The file can be read from, but not written to.
FILE_ATTRIBUTE_HIDDEN (0002h)
	The file is hidden and does not appear in an ordinary directory listing.
FILE_ATTRIBUTE_SYSTEM (0004h)
	The file is part of the operating system or is used exclusively by it.
FILE_ATTRIBUTE_ARCHIVE (0020h)
	The file is an archive file. Applications use this value to mark files for backup or removal.
Time

New time to set, which is used only if Action is 3 (set last write date/time) or 7 (set creation date/time) The time is a packed 16-bit value with the following form:

Bits	Contents
0−4	Second divided by 2
5−10	Minute (0−59)
11−15	Hour (0−23 on a 24-hour clock)
Date

New date to set, which is used only if Action is 3 (set last write date/time), 5 (set last access date), or 7 (set creation date/time). The date is a packed 16-bit value with the following form:

Bits	Contents
0−4	Day of the month (1−31)
5−8	Month (1 = January, 2 = February, and so on)
9−15	Year offset from 1980 (that is, add 1980 to get the actual year)
MilliSeconds

Number of 10 millisecond intervals in 2 seconds to add to the MS-DOS time. The number can be a value in the range 0 to 199. This value is only used if Action is 7 (set creation date/time).

Filename

Address of a null-terminated string specifying the name of the file to retrieve or set attributes for. Long filenames are allowed.


Interrupt 21h Function 7147h  Get Current Directory [New - Windows 95]
 Interrupt 21h Function 7147h  Get Current Directory

[New - Windows 95]

mov ax, 7147h       ; Get Current Directory
mov dl, Drive       ; see below
mov si, seg Buffer  ; see below
mov ds, si
mov si, offset Buffer
int 21h

jc  error

Copies the path of the current directory for the given drive to the buffer. The copied path does not include the drive letter or the leading backslash.

•	Clears the carry flag and copies the path if successful. Otherwise, the function sets the carry flag and sets the AX register to an error value.

Drive

Drive number. This parameter can be 0 for current drive, 1 for A, 2 for B, and so on.

Buffer

Address of the buffer that receives the path. The buffer must be at least as big as the maximum allowed path for this volume as returned by Get Volume Information (Interrupt 21h Function 71A0h).


Interrupt 21h Function 714Eh  Find First File [New - Windows 95]
 Interrupt 21h Function 714Eh  Find First File

[New - Windows 95]

mov ax, 714Eh             ; Find First File
mov ch, MustMatchAttrs    ; see below

mov cl, SearchAttrs       ; see below
mov dx, seg Filename      ; see below
mov ds, dx
mov dx, offset Filename
mov di, seg FindData      ; see below
mov es, di
mov di, offset FindData
mov si, DateTimeFormat    ; see below
int 21h

jc  error
mov [Handle], ax          ; search handle
mov [ConversionCode], cx  ; Unicode to OEM/ANSI conversion OK?

Searches a directory for the first file or directory whose name and attributes match the specified name and attributes.

•	Clears the carry flag, copies information about the file to the specified buffer, returns the search handle in the AX register, and sets the CX register to a combination of the following values if successful:

0x0000	All characters in the primary and alternate name members in the structure specified by FindData were successfully converted from Unicode.
0x0001	The primary name returned in the structure specified by FindData contains underscore characters in place of characters that could not be converted from Unicode.
0x0002	The alternate name returned in the structure specified by FindData contains underscore characters in place of characters that could not be converted from Unicode.
Otherwise, the function sets the carry flag and sets the AX register to an error value.

MustMatchAttrs

Additional filter on the attributes specified in SearchAttrs. This parameter can be a combination of these values:

FILE_ATTRIBUTE_NORMAL (0000h)
	The file can be read from or written to. This value is valid only if used alone.
FILE_ATTRIBUTE_READONLY (0001h)
	The file can be read from, but not written to.
FILE_ATTRIBUTE_HIDDEN (0002h)
	The file is hidden and does not appear in an ordinary directory listing.
FILE_ATTRIBUTE_SYSTEM (0004h)
	The file is part of the operating system or is used exclusively by it.
FILE_ATTRIBUTE_VOLUME (0008h)
	The name specified by Filename is used as the volume label for the current medium.
FILE_ATTRIBUTE_DIRECTORY (0010h)
	The name specified by Filename is used as a directory, not a file.
FILE_ATTRIBUTE_ARCHIVE (0020h)
	The file is an archive file. Applications use this value to mark files for backup or removal.
SearchAttrs

File attributes to search for. This parameter can be a combination of these values:

FILE_ATTRIBUTE_NORMAL (0000h)

FILE_ATTRIBUTE_READONLY (0001h)

FILE_ATTRIBUTE_HIDDEN (0002h)

FILE_ATTRIBUTE_SYSTEM (0004h)

FILE_ATTRIBUTE_VOLUME (0008h)

FILE_ATTRIBUTE_DIRECTORY (0010h)

FILE_ATTRIBUTE_ARCHIVE (0020h)

Filename

Address of a null-terminated string specifying the name of the file or directory to search for. The name, which must be a valid filename or directory name, can include the "*" and "?" wildcard characters. Long filenames are allowed.

FindData

Address of a WIN32_FIND_DATA structure that receives information about the file.

DateTimeFormat

Date and time format to be returned. This parameter must be one of these values:

0	Returns the date and time in 64-bit file time format.
1	Returns the MS-DOS date and time values. MS-DOS date and time values are returned in the low doubleword of the FILETIME structure. Within the doubleword, the date is returned in the high-order word; the time is in the low-order word.
Find First File and subsequent calls to Find Next File (Interrupt 21h Function 714Fh) use the following algorithm to match the attributes of a file or directory (referred to as Attributes in the algorithm) against MustMatchAttrs and SearchAttrs.

if  ((((<MustMatchAttrs> & ~<Attributes>) & 0x3F) == 0)
      && (((~<SearchAttrs> & <Attributes>) & 0x1E) == 0))
    {
         return the file or directory name
    }
    else
    {
         continue searching for the next name
    }

The following table lists the MustMatchAttrs and SearchAttrs values for some common searches where the specified filename is "*.*". In the table, the word normal means that the read only, hidden, or system attributes have not been set. Parentheses are used to indicate that a file or directory has more than one attribute. For example, (hidden and system) indicates that a file or directory has both the hidden attribute and the system attribute.

MustMatchAttrs	SearchAttrs	Find results
10h	10h	All normal directories
10h	12h	All normal and hidden directories
10h	14h	All normal and system directories
10h	16h	All normal, hidden, system and (hidden and system) directories
12h	12h	All hidden directories
14h	14h	All system directories
16h	16h	All (hidden and system) directories
00h	00h	All normal files
00h	01h	All normal and read only files
00h	02h	All normal and hidden files
00h	04h	All normal and system files
00h	06h	All normal, hidden, system, and (hidden and system) files
00h	10h	All normal files and directories
01h	01h	All read only files
02h	02h	All hidden files
02h	06h	All hidden and (hidden and system) files
This function can be used to return the volume label by specifying only FILE_ATTRIBUTE_VOLUME (0008h) in both MustMatchAttrs and SearchAttrs.

An application may use the handle returned in the AX register in subsequent calls to Find Next File (Interrupt 21h Function 714Fh). It is important to close the handle when it is no longer needed by calling Find Close (Interrupt 21h Function 71A1h).

Wildcard searches are more flexible in Windows 95 than in MS-DOS. For example, *1 finds the filenames (both long filenames and aliases) that end in a 1, and *mid* finds filenames that contain the characters mid. In MS-DOS and in Windows 95 searching on real-mode FAT directories, all characters after the first * are ignored.


Interrupt 21h Function 714Fh  Find Next File [New - Windows 95]
 Interrupt 21h Function 714Fh  Find Next File

[New - Windows 95]

mov ax, 714Fh            ; Find Next File
mov bx, Handle           ; see below
mov di, seg FindData     ; see below
mov es, di
mov di, offset FindData
mov si, DateTimeFormat   ; see below
int 21h

jc error
mov [ConversionCode], cx  ; Unicode to OEM/ANSI conversion OK?

Searches for the next file in a directory, returning information about the file in the given buffer.

•	Clears the carry flag, copies information to the specified buffer, and sets the CX register to a combination of these values if successful:

0x0000	All characters in the primary and alternate name member in the structure specified by FindData were successfully converted from Unicode.
0x0001	The primary name returned in the structure specified by FindData contains underscore characters in place of characters that could not be converted from Unicode.
0x0002	The alternate name returned in the structure specified by FindData contains underscore characters in place of characters that could not be converted from Unicode.
Otherwise, the function sets the carry flag and sets the AX register to an error value.

Handle

Search handle. It must have been previously returned from Find First File (Interrupt 21h Function 714Eh).

FindData

Address of a WIN32_FIND_DATA structure that receives information about the file.

DateTimeFormat

Date and time format to be returned. This parameter must be one of these values:

0	Returns the date and time in 64-bit file time format.
1	Returns the MS-DOS date and time values. MS-DOS date and time values are returned in the low doubleword of the FILETIME structure. Within the doubleword, the date is returned in the high-order word; the time is in the low-order word.
It is important to close the handle when it is no longer needed by calling Find Close (Interrupt 21h Function 71A1h).


Interrupt 21h Function 7156h  Rename File [New - Windows 95]
 Interrupt 21h Function 7156h  Rename File

[New - Windows 95]

mov ax, 7156h           ; Rename File
mov dx, seg OldName     ; see below
mov ds, dx

mov dx, offset OldName
mov di, seg NewName     ; see below
mov es, di

mov di, offset NewName
int 21h

jc  error

Changes the name of the given file or directory to the new name.

•	Clears the carry flag if successful. Otherwise, the function sets the carry flag and sets the AX register to an error value.

OldName

Address of a null-terminated string specifying the original name of the file or the directory to rename. Long filenames are allowed.

NewName

Address of a null-terminated string specifying the new name for the file or the directory. The function will fail if this parameter specifies an existing file or directory. The new name must not specify a drive different than the original drive. Long filenames are allowed.


Interrupt 21h Function 7160h  Get Full Path Name [New - Windows 95]
 Interrupt 21h Function 7160h  Get Full Path Name

[New - Windows 95]

mov ax, 7160h
mov cl, 0                  ; Get Full Path Name
mov ch, SubstExpand        ; see below
mov si, seg SourcePath     ; see below
mov ds, si
mov si, offset SourcePath
mov di, seg DestPath       ; see below
mov es, di
mov di, offset DestPath
int 21h

jc  error

Retrieves the full path for the specified file or path.

•	Clears the carry flag, modifies the AX register, and returns the full path in the given buffer if successful. Otherwise, the function sets the carry flag and sets the AX register to an error value.

SubstExpand

Flag that indicates whether the returned path should contain a SUBST drive letter or the path associated with the SUBST drive. Zero is specified to indicate that the returned path should contain the path associated with the SUBST drive, and 80h is specified to indicate that the returned path should contain the SUBST drive letter.

SourcePath

Address of a null-terminated string that names the file or path to retrieve the full path for. Either the long filename or the standard 8.3 filename format is acceptable.

DestPath

Address of the buffer that receives the full path. The buffer should be large enough to contain the largest possible Windows 95 path (260 characters, including the drive letter, colon, leading backslash, and terminating null character).

When just a filename is specified, this function merges the name of the current drive and directory with the specified filename to determine the full path. Relative paths containing the characters "." and ".." in SourcePath are fully expanded. The function does no validation, so the specified filename or path does not need to exist.


Interrupt 21h Function 7160h  Get Short Path Name [New - Windows 95]
 Interrupt 21h Function 7160h  Get Short Path Name

[New - Windows 95]

mov ax, 7160h
mov cl, 1                  ; Get Short Path Name
mov ch, SubstExpand        ; see below
mov si, seg SourcePath     ; see below
mov ds, si
mov si, offset SourcePath
mov di, seg DestPath       ; see below
mov es, di
mov di, offset DestPath
int 21h
jc  error

Retrieves the complete path in its short form (the standard 8.3 format) for the specified file or path. The function returns the 8.3 filename for all directories in the path.

•	Clears the carry flag, modifies the AX register, and returns the complete short path in the given buffer if successful. Otherwise, the function sets the carry flag and sets the AX register to an error value.

SubstExpand

Flag that indicates if the returned path should contain a SUBST drive letter or the path associated with the SUBST drive. Zero is specified to indicate that the returned path should contain the path associated with the SUBST drive, and 80h is specified to indicate that the returned path should contain the SUBST drive letter.

SourcePath

Address of a null-terminated string that names the file or path to retrieve the complete short path for. Either the long or short form is acceptable as the source string.

DestPath

Address of the buffer that receives the complete path. The buffer should be large enough to contain the largest possible Windows 95 path in the short form (260 characters, including the drive letter, colon, leading backslash, and terminating null character).

Relative paths containing the characters "." and ".." in SourcePath are fully expanded. Since this function performs validation, SourcePath must contain either a valid filename or path.


Interrupt 21h Function 7160h  Get Long Path Name [New - Windows 95]
 Interrupt 21h Function 7160h  Get Long Path Name

[New - Windows 95]

mov ax, 7160h
mov cl, 2                  ; Get Long Path Name
mov ch, SubstExpand        ; see below
mov si, seg SourcePath     ; see below
mov ds, si
mov si, offset SourcePath
mov di, seg DestPath       ; see below
mov es, di
mov di, offset DestPath
int 21h
jc  error

Retrieves the complete path in its long filename form for the specified file or path. The function returns the long name for all directories in the path.

•	Clears the carry flag, modifies the AX register, and returns the complete long path in the given buffer if successful. Otherwise, the function sets the carry flag and sets the AX register to an error value.

SubstExpand

Flag that indicates if the returned path should contain a SUBST drive letter or the path associated with the SUBST drive. Zero is specified to indicate that the returned path should contain the path associated with the SUBST drive, and 80h is specified to indicate that the returned path should contain the SUBST drive letter.

SourcePath

Address of a null-terminated string that names the file or path to retrieve the complete long path for. Either the long filename or the short form is acceptable as the source string.

DestPath

Address of the buffer that receives the complete path. The buffer should be large enough to contain the largest possible Windows 95 path (260 characters, including the drive letter, colon, leading backslash, and terminating null character).

Relative paths containing the characters "." and ".." in SourcePath are fully expanded. Since this function performs validation, SourcePath must contain either a valid filename or path.


Interrupt 21h Function 716Ch  Create or Open File [New - Windows 95]
 Interrupt 21h Function 716Ch  Create or Open File

[New - Windows 95]

mov ax, 716Ch          ; Create or Open File
mov bx, ModeAndFlags   ; see below
mov cx, Attributes     ; see below
mov dx, Action         ; see below
mov si, seg Filename   ; see below
mov ds, si
mov si, offset Filename
mov di, AliasHint      ; see below
int 21h

jc error
mov [Handle], ax       ; file handle
mov [ActionTaken], cx  ; action taken to open file

Creates or opens a file.

•	Clears carry flag, copies the file handle to the AX register, and sets the CX register to one of the following values if successful:

ACTION_OPENED (0001h)

ACTION_CREATED_OPENED (0002h)

ACTION_REPLACED_OPENED (0003h)

Otherwise, the function sets the carry flag and sets the AX register to an error value.

ModeAndFlags

Combination of access mode, sharing mode, and open flags. This parameter can be one value each from the access and sharing modes and any combination of open flags:

Access mode	Meaning
OPEN_ACCESS_READONLY (0000h)
	Opens the file for reading only.
OPEN_ACCESS_WRITEONLY (0001h)
	Opens the file for writing only.
OPEN_ACCESS_READWRITE (0002h)
	Opens the file for reading and writing.
0003h
	Reserved; do not use.
OPEN_ACCESS_RO_NOMODLASTACCESS (0004h)
	Opens the file for reading only without modifying the file's last access date.
Sharing mode	Meaning
OPEN_SHARE_COMPATIBLE (0000h)
	Opens the file with compatibility mode, allowing any process on a given computer to open the file any number of times.
OPEN_SHARE_DENYREADWRITE (0010h)
	Opens the file and denies both read and write access to other processes.
OPEN_SHARE_DENYWRITE (0020h)
	Opens the file and denies write access to other processes.
OPEN_SHARE_DENYREAD (0030h)
	Opens the file and denies read access to other processes.
OPEN_SHARE_DENYNONE (0040h)
	Opens the file without denying read or write access to other processes, but no process may open the file for compatibility access.
Open flags	Meaning
OPEN_FLAGS_NOINHERIT (0080h)
	If this flag is set, a child process created with Load and Execute Program (Interrupt 21h Function 4B00h) does not inherit the file handle. If the handle is needed by the child process, the parent process must pass the handle value to the child process. If this flag is not set, child processes inherit the file handle.
OPEN_FLAGS_NO_BUFFERING (0100h)
	The file is to be opened with no intermediate buffering or caching done by the system. Read and write operations access the disk directly. All reads and writes to the file must be done at file positions that are multiples of the disk sector size, in bytes, and the number of bytes read or written should also be a multiple of the sector size. Applications can determine the sector size, in bytes, with the Get Disk Free Space function (Interrupt 21h, Function 36h).
OPEN_FLAGS_NO_COMPRESS (0200h)
	The file should not be compressed on a volume that performs file compression. If the volume does not perform file compression, this flag is ignored. This flag is valid only on file creation and is ignored on file open.
OPEN_FLAGS_ALIAS_HINT (0400h)
	The number in the DI register is to be used as the numeric tail for the alias (short filename). For more information, see AliasHint below.
OPEN_FLAGS_NOCRITERR (2000h)
	If a critical error occurs while MS-DOS is opening this file, Critical-Error Handler (Interrupt 24h) is not called. Instead, MS-DOS simply returns an error value to the program.
OPEN_FLAGS_COMMIT (4000h)
	After each write operation, MS-DOS commits the file (flushes the contents of the cache buffer to disk).
Attributes

Attributes for files that are created or truncated. This parameter may be a combination of these values:

FILE_ATTRIBUTE_NORMAL (0000h)
	The file can be read from or written to. This value is valid only if used alone.
FILE_ATTRIBUTE_READONLY (0001h)
	The file can be read from, but not written to.
FILE_ATTRIBUTE_HIDDEN (0002h)
	The file is hidden and does not appear in an ordinary directory listing.
FILE_ATTRIBUTE_SYSTEM (0004h)
	The file is part of the operating system or is used exclusively by it.
FILE_ATTRIBUTE_VOLUME (0008h)
	The name specified by Filename is used as the volume label for the current medium and is restricted to the standard 8.3 format. For information about an alternative way to set the volume label, see Set Media ID (Interrupt 21h Function 440Dh Minor Code 46h) in the Microsoft MS-DOS Programmer's Reference.
FILE_ATTRIBUTE_ARCHIVE (0020h)
	The file is an archive file. Applications use this value to mark files for backup or removal.
Action

Action to take it the file exists or if it does not exist. This parameter can be a combination of these values:

FILE_CREATE (0010h)	Creates a new file if it does not already exist. The function fails if the file already exists.
FILE_OPEN (0001h)	Opens the file. The function fails if the file does not exist.
FILE_TRUNCATE (0002h)	Opens the file and truncates it to zero length (replaces the existing file). The function fails if the file does not exist.
The only valid combinations are FILE_CREATE combined with FILE_OPEN or FILE_CREATE combined with FILE_TRUNCATE.

Filename

Address of a null-terminated string specifying the name of the file to be opened or created. The string must be a valid path for the volume associated with the given drive. Long filenames are allowed.

AliasHint

Number that is used in the numeric tail for the alias (short filename). A numeric tail, which consists of the tilde character (~) followed a number, is appended to the end of a filename. The system constructs the alias from the first few characters of the long filename followed by the numeric tail. The system starts with the number 1 in the numeric tail. If that filename is in use, it uses the number 2. It continues in this fashion until a unique name is found. To override the default numbering scheme, you must specify the OPEN_FLAGS_ALIAS_HINT value when you create the file in addition to specifying this parameter. If a filename already exists with the specified numeric tail, the system uses the default numbering scheme. You should specify a number for this parameter, not the tilde character.

A file on a remote directory — that is, a directory on the network — cannot be opened, created, or modified, unless the appropriate permissions for the directory exist.


Interrupt 21h Function 71A0h  Get Volume Information [New - Windows 95]
 Interrupt 21h Function 71A0h  Get Volume Information

[New - Windows 95]

mov ax, 71A0h          ; Get Volume Information
mov di, seg Buffer     ; see below
mov es, di
mov di, offset Buffer
mov cx, BufSize        ; see below
mov dx, seg RootName   ; see below
mov ds, dx
mov dx, offset RootName
int 21h

jc  error
mov [Flags], bx        ; file system flags
mov [MaxFilename], cx  ; max. filename length, excluding null
mov [MaxPath], dx      ; max. path length, including null

Returns information about the volume associated with the given root directory.

•	Clears the carry flag, copies the file system name to the buffer given by the ES:DI register pair, and sets the BX, CX, and DX registers to the following values if successful:

BX	File system flags, which can be a combination of these values:

FS_CASE_SENSITIVE (0001h)
Specifies that searches are case-sensitive.

FS_CASE_IS_PRESERVED (0002h)
Preserves case in directory entries.

FS_UNICODE_ON_DISK (0004h)
Uses Unicode characters in file and directory names.

FS_LFN_APIS (4000h)
Supports new long filename functions.

FS_VOLUME_COMPRESSED (8000h)
Specifies that the volume is compressed.

CX	Maximum allowed length, excluding the terminating null character, of a filename for this volume. For example, on the protected-mode FAT file system, this value is 255.
DX	Maximum allowed length of a path for this volume, including the drive letter, colon, leading slash, and terminating null character. For example, on the protected-mode FAT file system, this value is 260.
Otherwise, the function sets the carry flag and sets the AX register to an error value.

Buffer

Address of a buffer that receives a null-terminated string specifying the name of the file system.

BufSize

Size, in bytes, of the buffer that receives the name. The buffer should include space for the terminating null character.

RootName

Address of a null-terminated string specifying the name of the root directory of the volume to check. This parameter must not be NULL, or the function will fail. The format for this parameter is "C:\".

This function accesses the disk the first time it is called, but subsequent calls do not access the disk.


Interrupt 21h Function 71A1h  Find Close [New - Windows 95]
 Interrupt 21h Function 71A1h  Find Close

[New - Windows 95]

mov ax, 71A1h   ; Find Close
mov bx, Handle  ; see below
int 21h

jc  error

Closes the file search identified by the search handle.

•	Clears the carry flag if successful. Otherwise, the function sets the carry flag and sets the AX register to an error value.

Handle

Search handle. It must have been previously returned from Find First File (Interrupt 21h Function 714Eh).

Unlike MS-DOS Find First File (Interrupt 21h Function 4Eh), the long filename version of Find First File (Interrupt 21h Function 714Eh) allocates internal storage for the search operations and returns a handle that identifies the storage. This handle is used with Find Next File. To make sure this internal storage is freed, you must call Find Close to end the search.


Interrupt 21h Function 71A6h  Get File Info By Handle [New - Windows 95]
 Interrupt 21h Function 71A6h  Get File Info By Handle

[New - Windows 95]

mov ax, 71a6h              ; Get File Info By Handle
mov bx, Handle             ; see below
mov dx, seg lpFileInfo     ; see below
mov ds, dx
mov dx, offset lpFileInfo
stc                        ; must set carry flag
int 21h

jnc success
cmp ax, 7100h
je not_supported

Retrieves information about the specified file.

•	Clears the carry flag if successful. Otherwise, the function sets the carry flag and sets the AX register to an error value.

Handle

File handle to retrieve information about.

lpFileInfo

Address of a BY_HANDLE_FILE_INFORMATION structure that receives the file information. The structure can be used in subsequent calls to Get File Info By Handle to refer to the information about the file.

Note that it is important to explicitly set the carry flag before calling this function.


Interrupt 21h Function 71A7h  File Time To DOS Time [New - Windows 95]
 Interrupt 21h Function 71A7h  File Time To DOS Time

[New - Windows 95]

mov ax, 71A7h           ; date and time format conversion
mov bl, 0               ; File Time To DOS Time
mov si, seg lpft        ; see below
mov ds, si
mov si, offset lpft
int 21h

jc  error
mov [DOSTime], cx
mov [DOSDate], dx
mov [MilliSeconds], bh  ; number of 10ms intervals in 2 seconds

Converts a 64-bit file time to MS-DOS date and time values.

•	Clears the carry flag, and sets the BH, CX, and DX registers to these values if successful:

BH	Number of 10 millisecond intervals in 2 seconds to add to the MS-DOS time. It can be a value in the range 0 to 199.
CX	MS-DOS time. The time is a packed 16-bit value with the following form:
Bits	Contents
0−4	Second divided by 2
5−10	Minute (0−59)
11−15	Hour (0−23 on a 24-hour clock)
DX	MS-DOS date. The date is a packed 16-bit value with the following form:
Bits	Contents
0−4	Day of the month (1−31)
5−8	Month (1 = January, 2 = February, and so on)
9−15	Year offset from 1980 (that is, add 1980 to get the actual year)
Otherwise, the function sets the carry flag and sets the AX register to an error value.

lpft

Address of a FILETIME structure containing the 64-bit file time to convert to the MS-DOS date and time format.

The MS-DOS date format can represent only dates between 1/1/1980 and 12/31/2107; this conversion fails if the input file time is outside this range.

The time in FILETIME must be Coordinated Universal Time (UTC). The MS-DOS time is local time.


Interrupt 21h Function 71A7h  DOS Time To File Time [New - Windows 95]
 Interrupt 21h Function 71A7h  DOS Time To File Time

[New - Windows 95]

mov ax, 71A7h         ; date and time format conversion
mov bl, 1             ; Dos Time To File Time
mov bh, MilliSeconds  ; see below
mov cx, DOSTime       ; see below
mov dx, DOSDate       ; see below
mov di, seg lpft      ; see below
mov es, di
mov di, offset lpft
int 21h

jc  error

Converts MS-DOS date and time values to 64-bit file time.

•	Clears the carry flag and returns the 64-bit file time in the specified structure if successful. Otherwise, the function sets the carry flag and sets the AX register to an error value.

MilliSeconds

Number of 10 millisecond intervals in 2 seconds to add to the MS-DOS time. The number can be a value in the range 0 to 199.

DOSTime

MS-DOS time to convert. The time is a packed 16-bit value with the following form:

Bits	Contents
0−4	Second divided by 2
5−10	Minute (0−59)
11−15	Hour (0−23 on a 24-hour clock)
DOSDate

MS-DOS date to convert. The date is a packed 16-bit value with the following form:

Bits	Contents
0−4	Day of the month (1−31)
5−8	Month (1 = January, 2 = February, and so on)
9−15	Year offset from 1980 (that is, add 1980 to get the actual year)
lpft

Address of a FILETIME structure to receive the converted 64-bit file time.

The time in FILETIME must be Coordinated Universal Time (UTC). The MS-DOS time is local time.


Interrupt 21h Function 71A8h  Generate Short Name [New - Windows 95]
 Interrupt 21h Function 71A8h  Generate Short Name

[New - Windows 95]

mov ax, 71a8h               ; generate short name
mov si, seg LongFilename    ; see below

mov ds, si
mov si, offset LongFilename
mov di, seg ShortFilename   ; see below

mov es, di

mov di, offset ShortFilename
mov dh, ShortNameFormat     ; see below
mov dl, CharSet             ; see below
int 21h

Generates an alias (a filename in the 8.3 format) for the specified long filename.

•	Returns the generated alias in the specified buffer if successful.

LongFilename

Address of null-terminated string that names the long filename to generate an alias for. This string must contain only a filename, not a path.

ShortFilename

Address of null-terminated string that receives the generated alias.

ShortNameFormat

Format for the returned alias (0 is specified for an 11 character directory entry format or 1 for an 8.3 format).

CharSet

Character set of both the long filename and alias. This parameter is a packed 8-bit value with the following form:

Bits	Contents
0−3	Specifies the character set of the source long filename.
4−7	Specifies the character set of the destination alias.
One of the following values is specified to indicate the character set for the long filename and alias:

BCS_WANSI (0)	Windows ANSI character set
BCS_OEM (1)	Current OEM character set
BCS_UNICODE (2)	Unicode character set
This function generates the alias using the same algorithm that the system uses with the exception that the returned alias will never have a numeric tail. A numeric tail is appended to the end of an alias and consists of the tilde character (~) followed a number. When the system generates an alias, it may attach a numeric tail if the default alias already exists in the current directory. Because this function does not check the current directory to see if the alias already exists, the returned alias will never have a numeric tail. This service is useful for disk utilities that are trying to establish whether the alias, which seems to be associated with a long filename, is correctly associated.


Interrupt 21h Function 71A9h Server Create or Open File [New - Windows 95]
 Interrupt 21h Function 71A9h Server Create or Open File

[New - Windows 95]

Creates or opens a file. This function is for use by real-mode servers only. It takes the same parameters as Create or Open File (Interrupt 21h Function 716Ch) and returns a global file handle. For more information, see Create or Open File.


Interrupt 21h Function 71AAh  Create Subst [New - Windows 95]
 Interrupt 21h Function 71AAh  Create Subst

[New - Windows 95]

mov ax, 71aah            ; SUBST
mov bh, 0                ; Create Subst
mov bl, DriveNum         ; see below
mov dx, seg PathName     ; see below
mov ds, dx
mov dx, offset PathName
int 21h

jc error

Associates a path with a drive letter.

•	Clears the carry flag if successful. Otherwise the function sets the carry flag and returns an error value in the AX register

DriveNum

Drive to SUBST. This parameter can be 0 for the default drive, 1 for A, 2 for B, and so on.

PathName

Address of path to associate the drive with.


Interrupt 21h Function 71AAh  Terminate Subst [New - Windows 95]
 Interrupt 21h Function 71AAh  Terminate Subst

[New - Windows 95]

mov ax, 71aah            ; SUBST
mov bh, 1                ; Terminate Subst
mov bl, DriveNum         ; see below
int 21h

jc error

Terminate the association between a path and a drive letter.

•	Clears the carry flag if successful. Otherwise, the function sets the carry flag and returns an error value in the AX register.

DriveNum

Drive to terminate SUBST. This parameter can 1 for A, 2 for B, and so on. Note that DriveNum cannot be 0 to indicate the default drive.


Interrupt 21h Function 71AAh  Query Subst [New - Windows 95]
 Interrupt 21h Function 71AAh  Query Subst

[New - Windows 95]

mov ax, 71aah            ; SUBST
mov bh, 2                ; Query SUBST
mov bl, DriveNum         ; see below
mov dx, seg PathName     ; see below
mov ds, dx
mov dx, offset PathName

int 21h

jc error

Determines if the specified drive is associated with a path and, if it is, retrieves the associated path.

•	Clears the carry flag and retrieves the associated path in the specified buffer if successful. Otherwise, the function sets the carry flag and returns an error value in the AX register.

DriveNum

Drive to SUBST. This parameter can 1 for A, 2 for B, and so on. Note that DriveNum cannot be 0 to indicate the default drive.

PathName

Address of buffer that receives the null-terminated string of the path associated with the specified drive. The buffer must be of MAXPATHLEN size.


 Structures

The following structures are used with long filenames.


BY_HANDLE_FILE_INFORMATION [New - Windows 95]
 BY_HANDLE_FILE_INFORMATION

[New - Windows 95]

BY_HANDLE_FILE_INFORMATION struc
    dwFileAttributes     dd ?         ; see below
    ftCreationTime       dd 2 dup(?)  ; see below
    ftLastAccessTime     dd 2 dup(?)  ; see below
    ftLastWriteTime      dd 2 dup(?)  ; see below
    dwVolumeSerialNumber dd ?         ; see below
    nFileSizeHigh        dd ?         ; see below
    nFileSizeLow         dd ?         ; see below
    nNumberOfLinks       dd ?         ; see below
    nFileIndexHigh       dd ?         ; see below
    nFileIndexLow        dd ?         ; see below
BY_HANDLE_FILE_INFORMATION ends

Contains file information retrieved by Get File Info By Handle (Interrupt 21h Function 71A6h).

dwFileAttributes

File attributes. This parameter can be one or more of these values:

FILE_ATTRIBUTE_NORMAL (00000000h)
	The file can be read from or written to. This value is valid only if used alone.
FILE_ATTRIBUTE_READONLY (00000001h)
	The file can be read from, but not written to.
FILE_ATTRIBUTE_HIDDEN (00000002h)
	The file is hidden and does not appear in an ordinary directory listing.
FILE_ATTRIBUTE_SYSTEM (00000004h)
	The file is part of the operating system or is used exclusively by it.
FILE_ATTRIBUTE_DIRECTORY (00000010h)
	The name specifies a directory, not a file.
FILE_ATTRIBUTE_ARCHIVE (00000020h)
	The file is an archive file. Applications use this value to mark files for backup or removal.
ftCreationTime

Time that the file was created in 64-bit file time format. A value of 0,0 indicates that the file system containing the file does not support this member.

ftLastAccessTime

Time that the file was last accessed in 64-bit file time format. A value of 0,0 indicates that the file system containing the file does not support this member.

ftLastWriteTime

Time that the file was last written to in 64-bit file time format. All file systems support this member. If the underlying file system does not support the last write time, this member is the time that the file was created.

dwVolumeSerialNumber

Serial number of the volume that contains the file.

nFileSizeHigh

High-order word of the file size.

nFileSizeLow

Low-order word of the file size.

nNumberOfLinks

Number of links to this file. For FAT and HPFS file systems, this member is always 1. For the NTFS file system, this member may be more than 1.

nFileIndexHigh

High-order word of a unique identifier associated with the file.

nFileIndexLow

Low-order word of a unique identifier associated with the file. This identifier and the volume serial number uniquely identify a file. This number may change when the system is restarted or when the file is opened. After a process opens a file, the identifier is constant until the file is closed. An application can use this identifier and the volume serial number to determine whether two handles refer to the same file.

The value returned by nFileIndexHigh and nFileIndexLow may be invalid on some file systems, such as real-mode network redirected file systems. In this case, an invalid index value will be returned.


FILETIME [New - Windows 95]
 FILETIME

[New - Windows 95]

FILETIME struc
    dwLowDateTime  dd ?  ; see below
    dwHighDateTime dd ?  ; see below
FILETIME ends

Contains a 64-bit value specifying the number of 100-nanosecond intervals that have elapsed since 12:00 A.M. January 1, 1901.

dwLowDateTime

Low-order 32 bits of the file time.

dwHighDateTime

High-order 32 bits of the file time.


WIN32_FIND_DATA [New - Windows 95]
 WIN32_FIND_DATA

[New - Windows 95]

WIN32_FIND_DATA struc
    dwFileAttributes   dd ?         ; see below
    ftCreationTime     dd 2 dup(?)  ; see below
    ftLastAccessTime   dd 2 dup(?)  ; see below
    ftLastWriteTime    dd 2 dup(?)  ; see below
    nFileSizeHigh      dd ?         ; high word of file size, in bytes
    nFileSizeLow       dd ?         ; low word of file size, in bytes
    dwReserved0        dd 0         ; reserved; do not use
    dwReserved1        dd 0         ; reserved; do not use
    cFileName          db MAX_PATH dup(?)  ; see below
    cAlternateFileName db 14 dup(?)        ; see below
WIN32_FIND_DATA ends

Describes a file found by Find First File (Interrupt 21h Function 714Eh) or Find Next File (Interrupt 21h Function 714Fh).

dwFileAttributes

File attributes of the file found. This parameter can be one or more of these values:

FILE_ATTRIBUTE_NORMAL (00000000h)
	The file can be read from or written to. This value is valid only if used alone.
FILE_ATTRIBUTE_READONLY (00000001h)
	The file can be read from, but not written to.
FILE_ATTRIBUTE_HIDDEN (00000002h)
	The file is hidden and does not appear in an ordinary directory listing.
FILE_ATTRIBUTE_SYSTEM (00000004h)
	The file is part of the operating system or is used exclusively by it.
FILE_ATTRIBUTE_DIRECTORY (00000010h)
	The name specifies a directory, not a file.
FILE_ATTRIBUTE_ARCHIVE (00000020h)
	The file is an archive file. Applications use this value to mark files for backup or removal.
ftCreationTime

Time that the file was created in either MS-DOS date and time format or in 64-bit file time format, depending on the date and time format specified in either Find First File or Find Next File. A value of 0,0 indicates that the file system containing the file does not support this member.

ftLastAccessTime

Time that the file was last accessed in either MS-DOS date and time format or in 64-bit file time format, depending on the date and time format specified in either Find First File or Find Next File. A value of 0,0 indicates that the file system containing the file does not support this member.

ftLastWriteTime

Time that the file was last written to in either MS-DOS date and time format or in 64-bit file time format, depending on the date and time format specified in either Find First File or Find Next File. All file systems support this member.

cFileName

Null-terminated string that is the name of the file. Because long filenames are allowed, the buffer size must be large enough for 256 characters, including the terminating null character.

cAlternateFileName

Null-terminated string, in the standard 8.3 filename format, that is an alternate name of the file. If the cFileName member contains an 8.3 format name or the file system does not permit 8.3 format alternates, this member is set to zero.


 Exclusive Volume Locking

This article describes exclusive volume locking and provides guidelines for applications that carry out direct access on volumes while running with Microsoft® Windows® 95. This article also describes the input and output control (IOCTL) functions that applications need for managing exclusive volume locking.


 About Exclusive Volume Locking

Disk utilities and other applications that directly modify file system structures, such as directory entries, must request exclusive volume locking (that is, exclusive use of the volume) before making modifications to the structures. Exclusive use prevents applications from inadvertently changing the file system while a disk utility is trying modify it and ensures that the information on a volume represents the current state of the volume.


 Direct Access

Applications typically use direct access to make changes to the directory entries, paths, and allocation chains in the file allocation table (FAT) of a given volume. The applications access this information by using the Interrupt 13h functions, Absolute Disk Read and Write (Interrupts 25h and 26h), or the Interrupt 21h read, write, and format track IOCTL functions. Some applications may also access the volume using the disk controller input and output (I/O) ports.

As a multitasking operating system, Windows 95 permits any number of applications to access a volume at a given time. Applications that change the file system structures of a volume without regard to other applications risk corruption of that information and subsequent data loss. To prevent data loss, the system manages all requests for direct access. With the exception of floppy disk drives, Windows 95 does not permit direct write operations, unless the volume has been locked by the application. The system returns the ERROR_WRITE_PROTECT error value to functions or interrupts that attempt direct write operations when the volume has not been locked. An application can read directly from a volume, but the system may satisfy the request by reading from internal caches rather than from the medium itself. An application cannot access disk controller I/O ports; the system traps all access.

An application can override the default behavior of the system by requesting exclusive use of the volume using the lock and unlock volume IOCTL functions. An application that has exclusive use of a volume can read and write directly to the medium, and because the system flushes internal caches to the medium, the information there reflects the actual state of the volume. Locking a volume (including the floppy disk drives) ensures consistency of data, because other processes cannot update information about the volume while it is locked.


 Exclusive Use Lock

To request exclusive use of a volume, an application use either Lock Logical Volume (Interrupt 21h Function 440Dh Minor Code 4Ah) or Lock Physical Volume (Interrupt 21h Function 440Dh Minor Code 4Bh). Before issuing an Interrupt 13h function, an application must acquire a physical volume lock. An application that only modifies logical volumes should acquire a logical volume lock. The calling interface for both locks is the same except for how the volume to lock is specified; the physical lock requires an Interrupt 13h device unit number, but the logical lock requires a logical drive number. When an application obtains a lock on a physical drive, the system acquires a logical volume lock for each logical volume on the physical drive. Obtaining a lock on a logical volume that is the parent (or host) drive also locks the child drives. For example, a compressed volume is locked when its host drive is locked.

The application that owns the lock can carry out direct disk write operations. Only one application at a time can lock the volume. If an application already owns the volume lock, the system fails subsequent calls to lock the volume.

The volume-locking functions allow the lock owner to control the kind of access that other processes have to the volume. There are three categories of access: read operations, which include opening a file as well as reading from a file; write operations, which include deleting and renaming a file as well as writing to a file; and new file mappings.

When an application calls either of the lock volume functions, it specifies a lock level and, depending on the level, passes in additional information known as permissions. The lock level and permissions specify what kind of operations the system allows processes other than the lock owner to do on the volume while it is locked.

When another process attempts to access the volume, the file system will fail the operation and return the ERROR_WRITE_PROTECT error value or it will block the operation, depending on the lock level and permissions. The system queues a blocked operation and puts the process requesting the operation to sleep until the lock is released and the operation can be performed.

When an application has completed its work, it must unlock the volume. Depending on whether it acquired a logical or physical lock, the application unlocks the volume by calling either Unlock Logical Volume (Interrupt 21h Function 440Dh Minor Code 6Ah) or Unlock Physical Volume (Interrupt 21h Function 440Dh Minor Code 6Bh). Unlocking the volume lets the system perform any blocked operations (in the order that they occurred) and resume normal activity. If an application exits without releasing the lock, the system automatically releases it.

If an application has a lock and the user attempts to close the virtual machine in which the application is running, the system displays a message warning the user that closing the virtual machine could result in damage to the volume. If the user confirms the closing, the system releases the lock and closes the virtual machine.

An application can lock volumes on local drives, but not on network drives or on drives that are not managed by the I/O supervisor, a virtual device driver. Also, the lock and unlock volume IOCTL functions are not available in previous versions of Microsoft® MS-DOS®. If the functions are used with a previous version, they return an error value.

Windows 95 provides 4 levels of exclusive volume locks. The level 0 lock is used alone, and lock levels 1, 2, and 3 form a hierarchy that increasingly restricts access to the file system based on the permissions set when the application obtains the level 1 lock. Although the level 0 lock is not part of the locking hierarchy formed by lock levels 1, 2, and 3, it has a more restrictive sublevel for applications that format volumes. Applications should perform direct disk write operations only in either a level 0 or 3 lock.


 Level 0 Lock

The level 0 lock cannot be obtained on volumes that have any open files or handles. This restriction includes handles returned by the Windows FindFirstFile and FindFirstChangeNotification functions. Because the system always has open files, an application cannot take a level 0 lock on the drive that contains the Windows 95 system files. The locking hierarchy can be used on volumes with open files and handles. If the system fails a level 0 lock request because of open files, an application can obtain a list of all the open files on the volume by calling Enumerate Open Files (Interrupt 21h Function 440Dh Minor Code 6Dh).

Before returning from the call to lock the volume, Windows 95 flushes to disk all data from the file system cache. To ensure that the disk and file system remain in a consistent state, the system puts the cache into write-through mode so that it can immediately commit to disk all data from file write operations. If an application has obtained a lock on a child volume, the system does not automatically flush the file system cache after a write operation to the parent volume. To ensure that the cache is flushed when opening files with Open or Create File (Interrupt 21h Function 716Ch), an application should specify the OPEN_FLAGS_NO_BUFFERING (0100h) value. If a file has not been opened with OPEN_FLAGS_NO_BUFFERING or Absolute Disk Write (Interrupt 26h) has been used to write to the parent volume, an application should call Reset Drive (Interrupt 21h Function 710Dh) to flush the cache.

After a process obtains a level 0 lock, the system only allows the lock owner to have access to the volume. The system fails all read operations, write operations, and new file mappings by other processes until the lock owner releases the lock. An application should use a level 0 lock whenever possible, because it guarantees that no other process can access the locked volume.

An application that formats volumes must obtain a more restrictive mode of the level 0 lock. To format a volume, the application should follow these steps:

1.	Call the lock volume function to obtain a level 0 lock.

2.	Do any needed file system I/O that uses the Interrupt 21h file handle I/O functions while in the level 0 lock.

3.	Call the lock volume function a second time to obtain the more restrictive level 0 lock for formatting. When calling the lock volume function the second time, an application should specify 0 as the lock level and specify 4 in the permissions. The application, however, must already own the level 0 lock to obtain this lock.

4.	Format the disk using the Interrupt 21h IOCTL functions (such as Read/Write/Format/Verify Track on Logical Drive or Get/Set Device Parameters). Interrupt 13h will work too, but it is not the preferred method for performance reasons. The system allows direct disk I/O, but it fails all other file system I/O that uses the Interrupt 21h file handle I/O functions while the restrictive level 0 lock is in effect.

5.	Release the level 0 lock for formatting. An application is still in a level 0 lock at this point. Before the application releases this lock, the disk must be in a state that would be recognizable as normal FAT media. Otherwise, the functions mentioned in step 6 will not work.

6.	Resume normal file system I/O using the Interrupt 21h file handle I/O functions.

7.	Release the level 0 lock.


 Locking Hierarchy

The locking hierarchy allows an application to obtain a lock in preparation for modifying the file system and yet allows other processes access to the drive. In this way, other processes are only denied access to the volume when absolutely necessary.

An application should perform direct disk write operations only within a level 3 lock. To obtain a level 3 lock, an application must make three calls to the lock volume function — first to obtain a level 1 lock, then a level 2 lock, and finally a level 3 lock. After obtaining the level 3 lock, the application can safely access the volume directly.

To release the lock on a volume, an application must call the appropriate unlock volume function the same number of times that the corresponding lock volume function was called. Each call to the unlock volume function decrements the lock level. For example, a level 3 lock returns to a level 2 lock, and the system processes any blocked read operations. A level 2 lock returns to a level 1 lock, and the system processes any blocked write operations or new file mappings. A call to the unlock volume function on a level 1 lock, however, releases the lock on the volume and allows other processes to obtain the lock.

Exclusive volume locks are owned by a process, not a thread. If necessary, a multithreaded application can obtain a level 1 lock in one thread, a level 2 lock in another, and a level 3 lock in yet another.

Even though the system may block or fail new file mappings, other processes are allowed to write to files through existing file mappings, because file mappings cannot be resized. Writing to an existing file mapping only changes the contents of the memory-mapped file, it does not cause changes to the file system.


 Level 1

The level 1 lock acts as a sentinel to guarantee that only one application may obtain the level 2 and 3 locks. An application specifies permissions only when requesting the level 1 lock. The lock level and permissions determine the kind of access that processes other than the lock owner have to the volume while it is locked. Bit 0 of the Permissions parameter for the lock volume function determines if the system allows or fails write operations by other processes. Bit 1 of Permissions determines if the system allows or fails new file mappings by other processes. Bit 2 of Permissions is only used when obtaining the restrictive level 0 lock for formatting and is ignored for a level 1 lock. The following table shows which operations are allowed at each lock level based on the permissions set on the level 1 lock.

Permissions	Level 1	Level 2	Level 3
Bit 0 = 0 Bit 1 = 0	Write operations are    failed. New file mappings    are allowed.  Read operations are    allowed.	Write operations are    failed. New file mappings    are allowed. Read operations are    allowed.	Write operations are    failed. New file mappings    are blocked. Read operations are    blocked.
Bit 0 = 0 Bit 1 = 1	Write operations are    failed. New file mappings    are failed. Read operations are    allowed.	Write operations are    failed. New file mappings    are failed. Read operations are    allowed.	Write operations are    failed. New file mappings    are failed. Read operations are    blocked.
Bit 0 = 1 Bit 1 = 0	Write operations are    allowed. New file mappings    are allowed. Read operations are    allowed.	Write operations    are blocked. New file mappings    are allowed. Read operations    are allowed.	Write operations are    blocked. New file mappings     are blocked. Read operations are    blocked.
Bit 0 = 1 Bit 1 = 1	Write operations are    allowed. New file mappings    are failed. Read operations are    allowed.	Write operations are    blocked. New file mappings    are failed. Read operations are    allowed.	Write operations are    blocked. New file mappings    are failed. Read operations are    blocked.
Calling an unlock physical or logical volume function on a level 1 lock completely releases the lock on the volume.


 Level 2

The level 2 lock prevents all processes except the lock owner from writing to the disk, but the lock allows any application to read from it. Depending on the permissions set when the application obtained the level 1 lock, the system will either block or fail write operations and either allow or fail new file mappings. Before obtaining a level 3 lock, an application should call Get Lock Flag State (Interrupt 21h Function 440Dh Minor Code 6Ch) to determine if anything on the disk has changed, such as the swap file growing or shrinking. Calling Get Lock Flag State at this point is an optimization that is done to avoid obtaining the level 3 lock unnecessarily.

Calling an unlock physical or logical volume function on a level 2 lock decrements the lock level to 1 and causes the system to perform previously blocked operations that are allowed at the lower lock level.


 Level 3

The level 3 lock prevents all processes except the lock owner from reading or writing to the disk. Read operations are blocked, and write operations and new file mappings are either blocked or failed depending on the permissions set in the level 1 lock. This is the most restrictive lock, not only because it prevents all other processes from accessing the disk but also because the lock owner is limited in what it can do.

Because read operations are blocked in the level 3 lock, an application must not execute any user interface or screen update functions, spawn applications, load dynamic-link libraries (DLLs), or yield to avoid deadlock. For example, if an application yields to a process with a discardable segment that the system has discarded, the system cannot reload the discarded segment because the process cannot read from the disk. This situation results in deadlock. Whenever a process obtains a level 3 lock, it should keep the lock for as short a period as possible to avoid severely degrading system performance. The purpose of the level 3 lock is to write changes to disk, so processes should only call disk I/O functions inside the lock.

After a level 3 lock is obtained, the file system takes several steps to allow a process to write directly to the disk. First, the system flushes all file system buffers and caches. Next, it puts the cache into write-through mode so that changes will be written to disk immediately. Finally, all open files are closed at the file system driver (FSD) level, which is invisible to all processes. While an application is in a level 3 lock, the system does not permit the swap file to grow or shrink, but it can still be read from or written to.

If an application has obtained a lock on a child volume, the system does not automatically flush the file system cache after a write operation to the parent volume. To ensure that the cache is flushed when Open or Create File (Interrupt 21h Function 716Ch) is used, the application should specify the OPEN_FLAGS_NO_BUFFERING (0100h) value. If the file has not been opened with OPEN_FLAGS_NO_BUFFERING or Absolute Disk Write (Interrupt 26h) has been used to write to the parent volume, the application should call Reset Drive (Interrupt 21h Function 710Dh) to flush the cache.

Before releasing the level 3 lock, the process is responsible for putting the file system into a state consistent with what existed before the lock was obtained. The process must be careful to correctly update all file system data, such as the FAT or directory entries. If a file was opened, it must not be deleted, renamed, or moved to a different volume. Otherwise, the system can become very unstable. An application should use Enumerate Open Files (Interrupt 21h Function 440Dh Minor Code 6Dh) to obtain a list of all open files on the volume.

When the level 3 lock is released, the system unblocks all pending read operations, reopens closed files on demand, and puts the cache back into write-behind mode. The lock owner returns to a level 2 lock.


 Using the Locking Hierarchy

An application should obtain a level 1 lock before beginning an operation, such as a complete defragmentation or compression. The application should release the level 1 lock only after the entire operation is finished. This approach prevents other processes from obtaining a lock on the same disk, which would keep the lock owner from finishing its work.

To minimize the time spent in the level 3 lock, a process should remain in the level 2 lock to perform certain tasks, such as computing disk statistics and preparing data packets to be written before actually writing them in the level 3 lock. As soon as a process enters the level 3 lock, the application must call Get Lock Flag State (Interrupt 21h Function 440Dh Minor Code 6Ch) to determine if anything on the disk has changed, such as the swap file growing or shrinking. If a change has occurred, the process should release the level 3 lock, return to the level 2 lock to recompute any needed information, and then obtain the level 3 lock again. If Get Lock Flag State shows that the disk has not changed, the process should do its writing and then release the level 3 lock.


 Swap File

The system pager requires access to the swap file at all times, even when an application has locked the volume containing the file. To ensure access, the system always gives the system pager the opportunity to accept or reject a lock request.

If the system grants a lock to a process, the requesting process must ensure that data for the swap file remains unchanged and that the pager can safely read from or write to the swap file at any time. In particular, the process must not change the allocation chain of the swap file, and if it moves the swap file's directory entry, it must ensure that the path to it is always consistent. Failure to observe these guidelines can result in a system crash.

An application can determine the directory entry and allocation chain of the swap file by retrieving the path of the file using Find Swap File (Interrupt 21h Function 440Dh Minor Code 6Eh).

The system permits the swap file to grow or shrink in the level 1 and 2 locks. Because of this, an application should call Get Lock Flag State (Interrupt 21h Function 440Dh Minor Code 6Ch) after obtaining a level 3 lock to determine if anything on the disk has changed as the result of the swap file growing or shrinking.


 Virtual Devices

The system broadcasts a message to all virtual devices (VxDs) when an application makes a request for a lock. Any VxD that uses virtual block device and I/O supervisor services to carry out direct I/O on the given volume must check for this message and either accept or reject the request when the message is received.

If the VxD rejects the request, it must return the appropriate error value. In such cases, the system does not grant the lock to the requesting application. If a VxD accepts the request, it must avoid all operations that may affect the consistency of the volume for the duration of the lock.

When the application releases the lock, the system again issues a broadcast message. The VxD can resume normal operation at this point.


 Volume-Locking Guidelines

Applications that lock and modify volumes should follow these guidelines to avoid degrading system performance and to prevent data loss:

•	If there are no open files on the volume, applications should perform direct disk writes in a level 0 lock. Otherwise, they should use the locking hierarchy and perform disk write operations in a level 3 lock.

•	Applications should utilize the locking hierarchy to minimize the time spent in a level 3 lock. They should only call disk I/O functions inside a level 3 lock and drop down to a level 1 or 2 lock whenever possible.

•	Applications should neither terminate or relinquish control nor leave a level 0 or 3 lock if the volume information is incomplete or invalid. When applications leave one of these locks, the file system must be consistent with what it was when they entered the lock because other applications will regain access to the drive.

•	Because the Interrupt 21h file handle I/O functions rely on accurate information about the volume, applications should not use these functions when the volume information is incomplete or invalid.

•	Applications should not move the swap file.

•	Applications should not move memory-mapped files opened for write access. Read-only memory-mapped files may be moved cluster by cluster.

•	Applications may only move 32-bit Windows-based DLLs and executables cluster by cluster.

•	Applications may move directory entries for the swap file and open memory-mapped files, but the path to them must always be consistent, even in a level 3 lock.

Because read operations are blocked in the level 3 lock, all applications written for 16-bit Windows, 32-bit Windows, or MS-DOS should follow these guidelines to avoid deadlock while in a level 3 lock:

•	Applications should only access the disk by using the low-level disk functions (Interrupt 13h, Interrupt 25h, and Interrupt 26h) or the Interrupt 21h file handle read, write, seek, and IOCTL functions. Other MS-DOS functions are not guaranteed to work. Windows or C run-time library file I/O functions should not be used, because these functions may contain code or call code that is not safe to execute inside the level 3 lock.

•	Applications should not yield control, update the screen, execute any user-interface code, or do anything else that could cause Windows 95 to load a new or previously discarded segment, such as by spawning an application or loading a DLL.

•	Windows-based applications must have all the code for a level 3 lock contained within the processing for a single message. The application should not process other messages or call any Windows functions.


 Special Considerations for 32-bit Windows-Based Applications

32-bit Windows-based applications must call the exclusive volume-locking IOCTL functions indirectly by opening VWIN32.VXD and using its DeviceIoControl interface.

In response, VWIN32.VXD issues the low-level disk I/O functions (Interrupt 13h, Interrupt 25h, and Interrupt 26h) as well as the MS-DOS Interrupt 21h file handle read, write, seek, and IOCTL functions in the context of the calling process.

32-bit Windows-based applications may safely call the Windows ReadFile, WriteFile, SetFilePointer, and DeviceIoControl functions within a level 3 lock. Other Windows or C run-time library functions should not be used while in the level 3 lock, because these functions may call other functions that are not safe inside a level 3 lock.


 Special Considerations for 16-bit Windows-Based Applications

16-bit Windows-based applications may call the exclusive volume-locking IOCTL functions directly using the Interrupt 21h interface, which is described in the reference material. These applications must mark all of the code, data, and resource segments that will be accessed while inside the level 2 and 3 locks as PRELOAD NONDISCARDABLE in the module-definition (.DEF) file. This marking prevents deadlock in case the system needs to load one of the application's segments from the executable file inside a level 3 lock.


Special Considerations for MS- DOS - Based Applications
 Special Considerations for MS- DOS − Based Applications

MS-DOS − based applications may directly call the volume-locking IOCTL functions by using Interrupt 21h, as described in the reference material.

When a windowed MS-DOS − based application obtains a level 3 lock, the system forces it to full screen mode to avoid deadlock with the display driver. When the application releases the level 3 lock, it remains in full screen mode.

Applications must not call the Advanced SCSI Programming Interface (ASPI) functions inside a level 3 lock. These functions bypass the file system, leaving it in an inconsistent state.

When MS-DOS − based applications run in single MS-DOS application mode (real mode), they may issue the volume-locking IOCTL functions and the functions will succeed. However, because there is no multitasking, there is only one lock rather than a hierarchy as when Windows 95 is running. The volume-locking IOCTL functions will fail on down-level versions of MS-DOS.


 Functions

The following functions can be used to manage exclusive volume locking.

Lock Logical Volume	Interrupt 21h Function 440Dh Minor Code 4Ah
Lock Physical Volume	Interrupt 21h Function 440Dh Minor Code 4Bh
Unlock Logical Volume	Interrupt 21h Function 440Dh Minor Code 6Ah
Unlock Physical Volume	Interrupt 21h Function 440Dh Minor Code 6Bh
Get Lock Flag State	Interrupt 21h Function 440Dh Minor Code 6Ch
Enumerate Open Files	Interrupt 21h Function 440Dh Minor Code 6Dh
Find Swap File	Interrupt 21h Function 440Dh Minor Code 6Eh
Get Current Lock State	Interrupt 21h Function 440Dh Minor Code 70h
Reset Drive	Interrupt 21h Function 710Dh
The exclusive-volume locking IOCTL functions are similar to other MS-DOS functions. An application must copy function parameters to registers and issue an Interrupt 21h instruction to carry out the call.


 Reference

The following functions and structures are associated with exclusive-volume locking IOCTL.


 Functions


Interrupt 21h Function 440Dh Minor Code 4Ah  Lock Logical Volume [New - Windows 95]
 Interrupt 21h Function 440Dh Minor Code 4Ah  Lock Logical Volume

[New - Windows 95]

mov ax, 440Dh        ; generic IOCTL
mov bh, LockLevel    ; see below
mov bl, DriveNum     ; see below
mov ch, 08h          ; device category (must be 08h)
mov cl, 4Ah          ; Lock Logical Volume
mov dx, Permissions  ; see below
int 21h

jc error

Locks the logical volume.

•	Clears the carry flag if successful. Otherwise, the function sets the carry flag and sets the AX register to an error value.

LockLevel

Level of the lock. This parameter must be either 0, 1, 2, or 3.

DriveNum

Drive to lock. This parameter can be 0 for the default drive, 1 for A, 2 for B, and so on.

Permissions

Operations that the system permits while the volume is locked. This parameter is specified only when a level 1 lock is obtained or when a level 0 lock is obtained for the second time for formatting the volume. For other lock levels, this parameter is zero. When a level 1 lock is obtained, bits 0 and 1 of this parameter specify whether the system permits write operations, new file mappings, or both by other processes during a level 1 lock as well as during level 2 and 3 locks. If this parameter specifies that write operations, new file mappings, or both are failed, these operations are failed during level 1, 2, and 3 locks. This parameter has the following form:

Bit	Meaning
0	0 = Write operations are failed (specified when a level 1 lock is obtained).
0	1 = Write operations are allowed (specified when a level 1 lock is obtained).
1	0 = New file mapping are allowed (specified when a level 1 lock is obtained).
1	1 = New file mapping are failed (specified when a level 1 lock is obtained).
2	1 = The volume is locked for formatting (specified when a level 0 lock is obtained for the second time).
The volume must be locked before the application performs direct disk write operations by using Interrupt 26h or the IOCTL control functions. Lock Physical Volume (Interrupt 21h Function 440Dh Minor Code 4Bh) is used instead of this function before a call to an Interrupt 13h function. Unlock Logical Volume (Interrupt 21h Function 440Dh Minor Code 6Ah) should be used to release the lock.


Interrupt 21h Function 440Dh Minor Code 4Bh  Lock Physical Volume [New - Windows 95]
 Interrupt 21h Function 440Dh Minor Code 4Bh  Lock Physical Volume

[New - Windows 95]

mov ax, 440Dh        ; generic IOCTL
mov bh, LockLevel    ; see below
mov bl, DriveNum     ; see below
mov ch, 08h          ; device category (must be 08h)
mov cl, 4Bh          ; Lock Physical Volume
mov dx, Permissions  ; see below
int 21h

jc error

Locks the physical volume.

•	Clears the carry flag if successful. Otherwise, the function sets the carry flag and sets the AX register to an error value.

LockLevel

Level of the lock. This parameter must be either 0, 1, 2, or 3.

DriveNum

Drive to lock. This parameter must be one of these values (same device unit numbers as for Interrupt 13h):

00 - 7Fh	Floppy disk drive (00 for the first floppy drive, 01 for the second, and so on).
80 - FFh	Hard disk drive (80 for the first hard disk drive, 81 for the second, and so on).
Permissions

Operations that the system permits while the volume is locked. This parameter is specified only when a level 1 lock is obtained or when a level 0 lock is obtained for the second time for formatting the volume. For other lock levels, this parameter is zero. When a level 1 lock is obtained, bits 0 and 1 of this parameter specify whether the system permits write operations, new file mappings, or both by other processes during a level 1 lock as well as during level 2 and 3 locks. If this parameter specifies that write operations, new file mappings, or both are failed, these operations are failed during level 1, 2, and 3 locks. This parameter has the following form:

Bit	Meaning
0	0 = Write operations are failed (specified when a level 1 lock is obtained).
0	1 = Write operations are allowed (specified when a level 1 lock is obtained).
1	0 = New file mapping are allowed (specified when a level 1 lock is obtained).
1	1 = New file mapping are failed (specified when a level 1 lock is obtained).
2	1 = The volume is locked for formatting (specified when a level 0 lock is obtained for the second time).
The volume must be locked before the application performs direct disk write operations by using Interrupt 13h, Interrupt 26h, or the Interrupt 21h IOCTL functions. A single physical volume may be divided into more than one logical volume, which is also called a partition. The system automatically takes a logical volume lock on all logical volumes on the specified physical drive. If the application performs disk writes only to a logical drive, Lock Logical Volume (Interrupt 21h Function 440Dh Minor Code 4Ah) is used instead of this function. Unlock Physical Volume (Interrupt 21h Function 440Dh Minor Code 6Bh) should be called to release the lock.


Interrupt 21h Function 440Dh Minor Code 6Ah  Unlock Logical Volume [New - Windows 95]
 Interrupt 21h Function 440Dh Minor Code 6Ah  Unlock Logical Volume

[New - Windows 95]

mov ax, 440Dh      ; generic IOCTL
mov bl, DriveNum   ; see below
mov ch, 08h        ; device category (must be 08h)
mov cl, 6Ah        ; Unlock Logical Volume
int 21h

jc error

Unlocks the logical volume or decrements the lock level.

•	Clears the carry flag if successful. Otherwise, the function sets the carry flag and sets the AX register to an error value.

DriveNum

Drive to unlock. This parameter can be 0 for the default drive, 1 for A, 2 for B, and so on.

This function is used to release the lock obtained by using Lock Logical Volume (Interrupt 21h Function 440Dh Minor Code 4Ah). Only the lock owner can release the lock on a volume.

To release the lock on the volume, an application must call Unlock Logical Volume the same number of times that Lock Logical Volume was called.


Interrupt 21h Function 440Dh Minor Code 6Bh  Unlock Physical Volume [New - Windows 95]
 Interrupt 21h Function 440Dh Minor Code 6Bh  Unlock Physical Volume

[New - Windows 95]

mov ax, 440Dh      ; generic IOCTL
mov bl, DriveNum   ; see below
mov ch, 08h        ; device category (must be 08h)
mov cl, 6Bh        ; Unlock Physical Volume
int 21h

jc enter

Unlocks the physical volume or decrements the lock level.

•	Clears the carry flag if successful. Otherwise, the function sets the carry flag and sets the AX register to an error value.

DriveNum

Drive to unlock. This parameter must be one of these values (same device unit numbers as for Interrupt 13h):

00 - 7Fh	Floppy disk drive (00 for the first floppy drive, 01 for the second, and so on).
80 - FFh	Hard disk drive (80 for the first hard disk drive, 81 for the second, and so on).
This function is used to release the lock obtained by using Lock Physical Volume (Interrupt 21h Function 440Dh Minor Code 4Bh). Only the lock owner can release the lock on a volume.

To release the lock on the volume, an application must call Unlock Physical Volume the same number of times that Lock Physical Volume was called.


Interrupt 21h Function 440Dh Minor Code 6Ch  Get Lock Flag State [New - Windows 95]
 Interrupt 21h Function 440Dh Minor Code 6Ch  Get Lock Flag State

[New - Windows 95]

mov ax, 440Dh        ; generic IOCTL
mov bl, DriveNum     ; see below
mov ch, 08h          ; device category (must be 08h)
mov cl, 6Ch          ; Get Lock Flag State
int 21h

jc error
mov [AccessFlag], ax  ; state of access flag

Polls the state of the access flag on a volume to determine if a write operation (for example, deleting or renaming a file or writing to a file) or a new file mapping has occurred since the last poll.

•	Clears the carry flag and sets the AX register to one of the following values if successful:

0	No write operations or file mappings have occurred since the last poll.
1	A write operation has occurred since the last poll (clears the volume access flag).
2	A file mapping has occurred since the last poll, or a 32-bit Windows-based DLL or executable has been opened (clears the volume access flag).
Otherwise, the function sets the carry flag and sets the AX register to an error value.

DriveNum

Drive to poll. This parameter can be 0 for the default drive, 1 for A, 2 for B, and so on.

Only the current lock owner may poll the access flag. The system fails other processes with ERROR_ACCESS_DENIED error value. Write operations performed by the lock owner do not cause a change in the state of the access flag.

When a lock is obtained that allows write operations or new file mappings, the system sets a flag whenever one of these operations happens on the volume. If a write operation or new file mapping has occurred since the last poll, Get Lock Flag State returns 1 or 2 respectively in the AX register and clears the volume access flag. If the swap file has grown or shrunk since the last poll, Get Lock Flag State returns 1. Note that write operations to the swap file that do not cause a change in size do not cause a change in the state of the access flag. If a 32-bit Windows-based DLL or executable has been opened since the last poll, Get Lock Flag State returns 2.


Interrupt 21h Function 440Dh Minor Code 6Dh  Enumerate Open Files [New - Windows 95]
 Interrupt 21h Function 440Dh Minor Code 6Dh  Enumerate Open Files

[New - Windows 95]

mov ax, 440Dh           ; generic IOCTL
mov bx, DriveNum        ; see below
mov ch, 08h             ; device category (must be 08h)
mov cl, 6Dh             ; Enumerate Open Files
mov dx, seg PathBuf     ; see below
mov ds, dx
mov dx, offset PathBuf
mov si, FileIndex       ; see below
mov di, EnumType        ; see below
int 21h

jc  error
mov [OpenMode], ax      ; mode file was opened in
mov [FileType], cx      ; normal file or memory-mapped file

Enumerates open files on the specified drive.

•	Clears the carry flag, copies the path of an open file to the given buffer, and sets the AX and CX registers to the following values if successful:

AX	Mode that the file was opened in, which is a combination of access mode, sharing mode, and open flags. It can be one value each from the access and sharing modes and any combination of open flags.
	Access modes
	OPEN_ACCESS_READONLY (0000h)
	OPEN_ACCESS_WRITEONLY (0001h)
	OPEN_ACCESS_READWRITE (0002h)
	OPEN_ACCESS_RO_NOMODLASTACCESS (0004h)
	Share modes
	OPEN_SHARE_COMPATIBLE (0000h)
	OPEN_SHARE_DENYREADWRITE (0010h)
	OPEN_SHARE_DENYWRITE (0020h)
	OPEN_SHARE_DENYREAD (0030h)
	OPEN_SHARE_DENYNONE (0040h)
	Open flags
	OPEN_FLAGS_NOINHERIT (0080h)
	OPEN_FLAGS_NO_BUFFERING (0100h)
	OPEN_FLAGS_NO_COMPRESS (0200h)
	OPEN_FLAGS_ALIAS_HINT (0400h)
	OPEN_FLAGS_NOCRITERR (2000h)
	OPEN_FLAGS_COMMIT (4000h)
CX	File type. It can be one of the following values:
	0	For normal files
	1	For a memory-mapped files (memory-mapped files are unmovable)
	2	For any other unmovable files (32-bit Windows-based DLLs and executables)
	4	For the swap file
Note that if a memory-mapped file is returned (CX = 1), the value returned in the AX register is limited to the following values:

OPEN_ACCESS_READONLY (0000h)
OPEN_ACCESS_READWRITE (0002h)
Otherwise, the function sets the carry flag and sets the AX register to the following error value:

ERROR_ACCESS_DENIED	The value of FileIndex exceeds the number of open files on the drive.
DriveNum

Drive on which to enumerate the files. This parameter can be 0 for the default drive, 1 for A, 2 for B, and so on.

PathBuf

Address of a buffer that receives the path of the open file. The length of the buffer varies depending on the volume. Get Volume Information (Interrupt 21h Function 71A0h) is used to determine the maximum allowed length of a path for the volume.

FileIndex

Index of the file to retrieve the path for.

EnumType

Kind of file to enumerate. This parameter can be 0 to enumerate all open files or 1 to enumerate only open unmovable files, including open memory-mapped files and other open unmovable files (32-bit Windows-based DLLs and executables).

This function returns information about one file at a time. To enumerate all open files, the function must be called repeatedly with FileIndex set to a new value for each call. FileIndex should be set to zero initially and then incremented by one for each subsequent call. The function returns the ERROR_NO_MORE_FILES error value when all open files on the volume have been enumerated.

This function may return inconsistent results when used to enumerate files on an active volume — that is, on a volume where other processes may be opening and closing files. Applications should use Lock Logical Volume (Interrupt 21h Function 440Dh Minor Code 4Ah) to take a level 3 lock before enumerating open files.


Interrupt 21h Function 440Dh Minor Code 6Eh  Find Swap File [New - Windows 95]
 Interrupt 21h Function 440Dh Minor Code 6Eh  Find Swap File

[New - Windows 95]

mov ax, 440Dh           ; generic IOCTL
mov ch, 08h             ; device category (must be 08h)
mov cl, 6Eh             ; Find Swap File
mov dx, seg PathBuf     ; see below
mov ds, dx
mov dx, offset PathBuf
int 21h

jc  error
mov [PagerType], ax            ; pager type
mov WORD PTR [FileSize], bx    ; swap file size in 4K pages
mov WORD PTR [FileSize+2], cx

Retrieves information about the swap file.

•	Clears the carry flag, copies the swap file path to the given buffer, and sets the following registers if successful:

AX	Pager type. It can be 1 for no pager, 2 for paging through MS-DOS, and 3 for paging through the protected-mode input and output (I/O) supervisor.
CX:BX	Current size of the swap file in 4K pages.
Otherwise, this function sets the carry flag and sets the AX register to an error value.

PathBuf

Address of the buffer that receives the path of the swap file. To determine the maximum allowed length of a path for the volume, call Get Volume Information (Interrupt 21h Function 71A0h).


Interrupt 21h Function 440Dh Minor Code 70h  Get Current Lock State [New - Windows 95]
 Interrupt 21h Function 440Dh Minor Code 70h  Get Current Lock State

[New - Windows 95]

mov ax, 440Dh        ; generic IOCTL
mov bl, DriveNum     ; see below
mov ch, 08h          ; device category (must be 08h)
mov cl, 70h          ; Get Current Lock State
int 21h

jc error

Retrieves the current lock level and permissions on the specified drive.

•	Clears the carry flag and sets the AX and CX registers to these values if successful:

AX	Current lock level. It may be either  0, 1, 2 or 3. If the volume is not locked, AX contains  − 1
CX	Lock permissions. The bits have the following form:
Bit	Meaning
0	0 = Write operations are failed.
0	1 = Write operations are allowed, unless they are blocked by the lock level.
1	0 = New file mapping are allowed, unless they are blocked by the lock level.
1	1 = New file mapping are failed.
2	1 = The volume is locked for formatting.
DriveNum

Drive to retrieve lock information about. This parameter can be 0 for the default drive, 1 for A, 2 for B, and so on.

The lock level and the permissions determine the kind of access processes other than the lock owner have to the volume while it is locked. The following operations are allowed by processes other than lock owner at each lock level:

Level	Operations
0	Read operations, write operations, and new file mappings are failed.
1	Read operations are allowed. Write operations and new file mappings are either allowed or failed based on permissions.
2	Read operations are allowed. Write operations and new file mappings are either failed or blocked based on permissions.
3	Read operations are blocked. Write operations and new file mappings are either failed or blocked based on permissions.


Interrupt 21h Function 710Dh  Reset Drive [New - Windows 95]
 Interrupt 21h Function 710Dh  Reset Drive

[New - Windows 95]

mov ax, 710Dh      ; Reset Drive
mov cx, Flag       ; see below
mov dx, DriveNum   ; see below
int 21h

jc  error

Flushes file system buffers and caches and optionally remounts the drivespace volume. Any write operations that the system has buffered are performed, and all waiting data is written to the appropriate drive.

•	This function has no return value.

Flag

Flag specifying whether the system should flush and invalidate the data in the cache as well as the file system buffers. This parameter must be one of these values:

0000h	Resets the drive and flushes the file system buffers for the given drive.
0001h	Resets the drive, flushes the file system buffers, and flushes and invalidates the cache for the specified drive.
0002h	Remounts the drivespace volume.
The Flag value of 0002h is only supported on drivespace volumes. You should specify this value when the on-media format of the drivespace volume has changed and you want the file system to reinitialize and read the new format.

DriveNum

Drive to reset. This parameter can be 0 for the default drive, 1 for A, 2 for B, and so on.


 Program Information File Management

This article describes program information file management and the corresponding functions and structures provided by the dynamic-link library (DLL) called PIFMGR.DLL.


 About Program Information File Management

Program information file management lets Microsoft® Windows® − based applications create, examine, and modify program information files (.PIF files). Program information files contain the detailed information needed by the operating system to prepare virtual machines for running Microsoft® MS-DOS® − based applications. Installation programs and other applications can open the files, retrieve and set information in these files, and display the information to the user for editing.


 Program Information Files

A .PIF file contains information about the properties of an MS-DOS − based application. These properties define how the application uses resources, such as memory, and specify the computer's devices, the virtual machine, and the window that the application is displayed in.

A .PIF file typically has the same filename as the corresponding MS-DOS − based application, but with the .PIF filename extension. Every .PIF file contains one or more sections called information groups. Each group has a unique name or ordinal. Applications use the name or ordinal to identify the group to be examined or modified.

Many groups are predefined and have associated structures that define the content of the group. The following predefined groups are listed by their ordinal.

Group ordinal	Information
GROUP_ENV	Environment. This group uses a PROPENV structure.
GROUP_FNT	Fonts. This group uses a PROPFNT structure.
GROUP_KBD	Keyboard. This group uses a PROPKBD structure.
GROUP_MEM	Memory. This group uses a PROPMEM structure.
GROUP_MSE	Mouse. This group uses a PROPMSE structure.
GROUP_PRG	Program. This group uses a PROPPRG structure.
GROUP_TSK	Task. This group uses a PROPTSK structure.
GROUP_VID	Video. This group uses a PROPVID structure.
GROUP_WIN	Windows. This group uses a PROPWIN structure.
The following predefined groups are identified by name (null-terminated string).

Group name	Information
AUTOEXECBAT 4.0	AUTOEXEC.BAT file image used for an application if the application is marked to run in MS-DOS mode.
CONFIG SYS 4.0	CONFIG.SYS file image used for an application if the application is marked to run in MS-DOS mode.
MICROSOFT PIFEX	Windows versions 1. x and 2. x information.
WINDOWS 286 3.0	Windows version 3. x standard mode information. This group uses a W286PIF30 structure.
WINDOWS 386 3.0	Windows version 3. x enhanced mode information. This group uses a W386PIF30 structure.
WINDOWS VMM 4.0	Windows 95 information. This group uses a WENHPIF40 structure.
Applications can also create new groups called PIF extensions to store information that is specific to the given MS-DOS − based application. All new groups are identified by name only, and the format of the information is entirely application-defined. If PIF extensions are used to store application-specific information, applications do not need to store the information in .INI files.

Program information file management supports .PIF files in these formats: Windows version 1. x, Windows version 2. x, Windows version 3. x, and Windows 95.


 Properties

To access the properties in a .PIF file, you first open the file by using the OpenProperties function. You can open a .PIF file directly by supplying the name of the file. Otherwise, you can supply the name of an MS-DOS − based application (that is, a file having the .COM, .EXE, or .BAT filename extension), and the function will open the corresponding .PIF file. If the function does not find the .PIF file in the current directory, it searches the WINDOWS directory, the Windows SYSTEM directory, the Windows PIF directory, and finally the directories on the current path to locate the file.

After opening the .PIF file, OpenProperties loads the properties into memory and returns a properties handle that you use in subsequent functions to identify the information. If you try to open a .PIF file that does not exist, the function creates a temporary file in memory and initializes it using internal data or data from the _DEFAULT.PIF file. To locate _DEFAULT.PIF, the function first searches the PIF directory and then searches for it in the directories on the current path. Unlike Windows version 3.1, Windows 95 does not create a _DEFAULT.PIF file. A system will have a _DEFAULT.PIF file only if it inherited one from a Windows version 3.1 installation, or if one was created manually.

You can retrieve individual properties by using the GetProperties function. You specify the property to retrieve by group name or ordinal. The name can be any predefined name, as given in the previous section, or the name of your own group. If you do not know the size of the information group, you can determine it by using the GetProperties function, specifying zero as the size. The function copies no data, but it returns the size of the requested group. You use this size in a subsequent call to retrieve the group.

You can change property information by using the SetProperties function. You specify the property to change by group name or ordinal and provide a copy of the new information. SetProperties typically saves changes to disk as you make the changes. You can direct SetProperties to cache the changes in memory by specifying the SETPROPS_CACHE value. Caching the changes lets you use the FlushProperties function later to either discard the changes or save them to disk.

You can create your own information group by using the SetProperties function, specifying the format for the information in the group. The operating system returns the information in exactly the same format as you create it. You can also use SetProperties to remove an information group.

Once you have finished using the properties information from a .PIF file, you must close it by using the CloseProperties function. If you make changes to a temporary file, CloseProperties will permanently save the property information in a new file on disk.

You can enumerate all loaded .PIF files by using the EnumProperties function. Each call to the function retrieves a properties handle, which you can use in the next call to EnumProperties to retrieve the next handle. The function returns zero when all open properties have been enumerated.

You can enumerate all named information groups associated with a properties handle by using the GetProperties function. The function copies the name of the group that corresponds to a zero-based group index to the specified 16-byte buffer. You can continue to call GetProperties, incrementing the index before each call, to retrieve all group names. The function returns zero when all groups have been enumerated. To minimize disk usage, the PIF manager does not store an information group if all settings have default values. This means that GetProperties may return the name of a group for which no PIF extension actually exists.

You can let the user edit property information by using the EditProperties function. The function displays a property sheet for each group listed in the previous section. When the user chooses a sheet, the function displays all the properties within the group and allows the user to edit the properties. EditProperties saves any changes, copying them back to the .PIF file. Some changes may not affect currently running applications, but they will apply to subsequently started applications.

The operating system may associate a given virtual machine or window handle with a specific set of properties. You can determine which handles are associated with a given set by using the AssociateProperties function. Generally, only system components should change these associations.

You can retrieve a complete copy of the .PIF file by specifying the OPENPROPS_RAWIO value when opening the file by using the OpenProperties function. Reading or writing the entire file requires a thorough understanding of the .PIF file format and is not recommended.


 Property Sheets

A property sheet is a set of controls that gives users access to the information in an information group. Property sheets are used by the EditProperties function to create a dialog box that displays the current values for settings in the information group and lets users edit those values. EditProperties uses default property sheets for each of the predefined information groups, but the function requires custom property sheets for any information groups that contain application-specific information.

An application or DLL can add a property sheet to the system by using the AddPropertySheet function. Before adding the property sheet, you must fill a PROPSHEETPAGE structure with names or values identifying the dialog box template, dialog box procedure, icon resource, and other resources to be used to display and manage the property sheet. Property sheets can be simple or advanced. Simple property sheets typically display a small set of values from the information group, and advanced property sheets display all values. You specify the property sheet type when you add the property sheet to the .PIF file.

You can retrieve information about the property sheets associated with a .PIF file by using the EnumPropertySheets function. For each property sheet, the function copies information, such as the name of the dialog box template and dialog box procedure, to a PROPSHEETPAGE structure. To use EnumPropertySheets, you must first load the property sheets by using the LoadPropertySheets function. After retrieving the property sheet information, you should free the loaded sheets by using the FreePropertySheets function.

To remove a property sheet from the system, use the RemovePropertySheet function.


 Property Libraries

A property library is a DLL that provides dialog box templates and procedures for displaying property sheets and editing properties. Property libraries let you develop property sheets for information groups that are specific to your MS-DOS − based applications. These libraries ensure that system applications, such as the shell, can display the application-specific information and allow users to edit it.

You can register a property library by using the LoadPropertyLib function. The function records the name of the library and returns a handle, but it does not actually load the library. You use the handle when adding property sheets to the .PIF file to identify the library containing the template and dialog box procedure for the property sheet. The system eventually loads the library when the user attempts to access the property sheet. You can enumerate the currently registered property libraries by using the EnumPropertyLibs function. When you no longer need a given property library, you should free it by using the FreePropertyLib function.


 Properties and Virtual Devices

Virtual devices (VxDs) also have access to information in .PIF files. This means that any VxDs you create to support MS-DOS − based applications can use information in the .PIF file. Typically, you add a specific PIF extension for use by the VxD and create corresponding a property sheet to give the user the opportunity to edit the information.

A VxD cannot retrieve property information directly. Instead, it installs a callback procedure using the SHELL_Hook_Properties service provided by the Shell virtual device (SHELL.VXD). The system notifies the VxD of changes to the properties by calling the callback procedure. The VxD can install callback procedures as either predefined or customized groups.


 Reference

The following functions and structures are associated with program information file management.


 Functions

The following functions are used with program information file management.


AddPropertySheet [New - Windows 95]
 AddPropertySheet

[New - Windows 95]

int AddPropertySheet(LPPROPSHEETPAGE lppsi, int iType)

Adds a new property sheet.

•	Returns a property sheet handle if successful or NULL otherwise.

lppsi

Address of the PROPSHEETPAGE structure containing the property sheet information.

iType

Sheet type. This parameter can be either the SHEETTYPE_SIMPLE or SHEETTYPE_ADVANCED value.


AssociateProperties [New - Windows 95]
 AssociateProperties

[New - Windows 95]

long AssociateProperties(int hProps, int iAssociate, long lData)

Associates data with the given property information. This function can also return the currently associated data without associating new data.

•	Returns the data previously associated with the given index data. If no data was previously associated or an error occurs, the function returns zero.

hProps

Properties handle. It must have been created previously by using the OpenProperties function.

iAssociate

Association index. This parameter can be the HVM_ASSOCIATION or HWND_ASSOCIATION value.

lData

Data to associate. This parameter can be any 32-bit value or address.

Association of data is reserved exclusively for system components. Applications may use this function to retrieve the associated data, but they must not set the associated data.

If iAssociate is negative, the currently associated value is returned, but it is not modified. In other words, lData is ignored.


CloseProperties [New - Windows 95]
 CloseProperties

[New - Windows 95]

int CloseProperties(int hProps, int flOpt)

Closes the property information for the application.

•	Returns NULL if successful or the properties handle otherwise.

hProps

Properties handle. It must have been created previously by using the OpenProperties function.

flOpt

Operation flag. This parameter can be the CLOSEPROPS_DISCARD value to discard the data or zero to save cached program information data by copying it to the .PIF file on disk.


EditProperties [New - Windows 95]
 EditProperties

[New - Windows 95]

int EditProperties(int hProps, LPSTR lpszTitle, UINT uStartPage,
    HWND hwnd, UINT uMsgPost)

Displays the editing dialog box, allowing the user to edit the given property sheet information.

•	Returns TRUE if successful or FALSE otherwise.

hProps

Properties handle. It must have been created previously by using the OpenProperties function.

lpszTitle

Address of null-terminated string specifying the title of the editing dialog box. If no title is needed, this parameter can be NULL.

uStartPage

Number of the first property sheet to edit.

hwnd

Parent window handle. If no parent window needed, this parameter can be NULL.

uMsgPost

Notification message value. If no notification message is needed, this parameter can be zero. If it is not zero, the function posts a message having this value to the parent window whenever properties change. The wParam parameter in the posted message specifies the size of the changed data, and the lParam parameter specifies the name or ordinal of the changed group.


EnumProperties [New - Windows 95]
 EnumProperties

[New - Windows 95]

int EnumProperties(int hProps)

Enumerates all open properties handles.

•	Returns a properties handle or zero if all properties have been enumerated.

hProps

Properties handle. It must have been previously returned by EnumProperties, or it must be NULL to start enumeration.


EnumPropertyLibs [New - Windows 95]
 EnumPropertyLibs

[New - Windows 95]

int EnumPropertyLibs(int iLib, LPHANDLE lphDLL, LPSTR lpszDLL,
    int cbszDLL)

Enumerates property libraries, filling the variables with the module handle and name of each library.

•	Returns a library identifier if successful. If all libraries have been enumerated or an error occurs, the function returns zero.

iLib

Library identifier. It must have been previously returned by the EnumPropertyLibs function or must be zero to start enumeration.

lphDLL

Address of the variable that receives the module handle of the library. If the handle is not needed, this parameter can be NULL.

lpszDLL

Address of the buffer that receives the zero-terminated name of the library. If the name is not needed, this parameter can be NULL.

cbszDLL

Size, in bytes, of the buffer pointed to by lpszDLL.


EnumPropertySheets [New - Windows 95]
 EnumPropertySheets

[New - Windows 95]

int EnumPropertySheets(int hProps, int iType, int iSheet,
    LPPROPSHEETPAGE lppsi)

Enumerates property sheets.

•	Returns a property sheet handle if successful. If all property sheets have been enumerated or an error occurs, the function returns zero.

hProps

Properties handle. It must have been created previously by using the Open Properties function.

iType

Sheet type. This parameter can be either the SHEETTYPE_SIMPLE or SHEETTYPE_ADVANCED value.

iSheet

Property sheet handle. It must have been previously returned by EnumPropertySheets or must be zero to start enumeration.

lppsi

Address of the PROPSHEETPAGE structure that receives the property sheet information.


FlushProperties [New - Windows 95]
 FlushProperties

[New - Windows 95]

int FlushProperties(int hProps, int flOpt)

Flushes or discards cached property information. The function flushes data by copying the data to the corresponding .PIF file on disk.

•	Returns TRUE if successful or FALSE otherwise.

hProps

Properties handle. It must have been created previously by using the OpenProperties function.

flOpt

Operations flag. This parameter can be the FLUSHPROPS_DISCARD value to discard the cached program information data or zero to flush the data to the corresponding .PIF file.


FreePropertyLib [New - Windows 95]
 FreePropertyLib

[New - Windows 95]

BOOL FreePropertyLib(int hLib)

Frees an installable property library.

•	Returns TRUE if successful or FALSE otherwise.

hLib

Handle of the property library.


FreePropertySheets [New - Windows 95]
 FreePropertySheets

[New - Windows 95]

int FreePropertySheets(int hProps, int flags)

Frees all property sheets for the .PIF file identified by the given properties handle.

•	No return value.

hProps

Properties handle. It must have been created previously by using the OpenProperties function.

flags

Reserved; must be zero.


GetProperties [New - Windows 95]
 GetProperties

[New - Windows 95]

int GetProperties(int hProps, LPSTR lpszGroup, LPVOID lpProps,
    int cbProps, int flOpt)

Retrieves property information for the given group; retrieves the size, in bytes, of the property information; or enumerates all named groups in the .PIF file.

•	Returns the size, in bytes, of the information retrieved if successful. If the group is not found, all groups have been enumerated, or an error occurred, the function returns zero.

hProps

Properties handle.

lpszGroup

Group ordinal, address of a null-terminated string specifying the name of the property group, or NULL. If a name is given, it must be the name of a valid PIF extension or one of these predefined group names:

MICROSOFT PIFEX	WINDOWS 386 3.0
WINDOWS 286 3.0	WINDOWS VMM 4.0
If a group ordinal is given, it can be one of these predefined ordinals:

GROUP_ENV	GROUP_PRG
GROUP_KBD	GROUP_TSK
GROUP_MEM	GROUP_VID
GROUP_MSE	GROUP_WIN
The ordinal must be in the low-order word, and zero must be in the high-order word.

If NULL is specified, the function enumerates all named groups. In this case, cbProps must be a zero-based group name index, and lpProps must be the address of the 16-byte buffer that receives the name of the given group.

lpProps

Address of the buffer that receives the property information. The size of the buffer depends on the type of information retrieved.

cbProps

Size, in bytes, of the buffer pointed to by lpProps. If cbProps is zero and lpszGroup is not NULL, the function returns the size of the corresponding property information without copying that information to the lpProps buffer.

flOpt

Operations flag. This parameter can be the GETPROPS_RAWIO value to read the entire .PIF file as a single, unformatted block (that is, lpszGroup is ignored) or zero to read the given group.


LoadPropertyLib [New - Windows 95]
 LoadPropertyLib

[New - Windows 95]

int LoadPropertyLib(LPSTR lpszDLL, int fLoad)

Loads a property library.

•	Returns the handle of the property library if successful or FALSE otherwise.

lpszDLL

Address of a null-terminated string specifying the name of a property library.

fLoad

Load flags. This parameter can be either zero or the LOADPROPLIB_.DEFER value. Specifying LOADPROPLIB_.DEFER defers loading of the property library until LoadPropertySheets is called and automatically unloads the library when FreePropertySheets is called. LoadPropertySheets and FreePropertySheets may be called directly by an application or indirectly when an application calls the EditProperties function. When a deferred library is loaded, its initialization handler must call AddPropertySheet for all the sheets to be added. When the deferred library is unloaded, its Windows exit procedure (WEP) handler must call RemovePropertySheet for all added sheets if it has not already freed them.


LoadPropertySheets [New - Windows 95]
 LoadPropertySheets

[New - Windows 95]

int LoadPropertySheets(int hProps, int flags)

Loads all property sheets for the .PIF file identified by the given properties handle.

•	Returns the number of sheets loaded if successful or zero otherwise.

hProps

Properties handle. It must have been created previously by using the  OpenProperties function.

flags

Reserved; must be zero.


OpenProperties [New - Windows 95]
 OpenProperties

[New - Windows 95]

int OpenProperties(LPSTR lpszApp, LPSTR lpszPIF, int hInf, int flOpt)

Opens the .PIF file associated with the given application and returns a properties handle that identifies the property information for the application.

•	Returns a properties handle if successful. If the .PIF file cannot be opened or there is insufficient memory to load the PIF data, the function returns FALSE.

lpszApp

Address of a null-terminated string specifying the filename of an MS-DOS − based application.

lpszPIF

Address of a null-terminated string specifying a new PIF filename to create. If the file is created successfully, the returned properties handle operates on that file. Any .PIF file for the specified MS-DOS − based application that exists in the PIF directory or on the path is still opened and read to obtain the initial set of properties to be stored in the new .PIF file.

hInf

Information handle. This parameter can be zero if no information handle is needed or  − 1 to prevent information processing. If zero is specified, the APPS.INF file is used by default.

flOpt

Operations flag. This parameter can be the OPENPROPS_RAWIO value to open the .PIF file for raw file input and output (I/O) or zero to open the file for standard access.

The function loads the content of the given .PIF file into memory and then closes the file, preserving the contents in memory until the properties handle is closed. If the given .PIF file does not exist, the function allocates memory and loads it with default PIF data. This function fails if there is insufficient memory for the PIF data or the given .PIF file exists but cannot be opened.


RemovePropertySheet [New - Windows 95]
 RemovePropertySheet

[New - Windows 95]

BOOL RemovePropertySheet(int hSheet)

Removes a property sheet.

•	Returns TRUE if successful or FALSE otherwise.

hSheet

Property sheet handle. It must have been previously created by using the AddPropertySheet function.


SetProperties [New - Windows 95]
 SetProperties

[New - Windows 95]

int SetProperties(int hProps, LPSTR lpszGroup, LPVOID lpProps,
    int cbProps, int flOpt)

Sets property information for the given group, removes the given group from the .PIF file, or writes raw data to the .PIF file.

•	Returns the number of information bytes written to the .PIF file if successful. If the group does not exist or an error occurs, the function returns zero.

hProps

Properties handle. It must have been previously opened by using the OpenProperties function.

lpszGroup

Group ordinal or address of a null-terminated string specifying the name of the property group. If a name is given, it must be the name of a valid PIF extension or one of these predefined names:

MICROSOFT PIFEX	WINDOWS 386 3.0
WINDOWS 286 3.0	WINDOWS VMM 4.0
If a group ordinal is given, it can be one of these predefined ordinals:

GROUP_ENV	GROUP_PRG
GROUP_KBD	GROUP_TSK
GROUP_MEM	GROUP_VID
GROUP_MSE	GROUP_WIN
The ordinal must be in the low-order word, and zero must be in the high-order word.

lpProps

Address of the buffer that contains the property information to write to the .PIF file.

cbProps

Size, in bytes, of the information pointed to by lpProps. If cbProps is zero and lpszGroup is not NULL, the function removes the given group from the .PIF file.

flOpt

Operations flag. This parameter can be one of these values:

0	Writes information to the given group.
SETPROPS_RAWIO	Writes data to the .PIF file as if it were a single, unformatted block. (The lpszGroup parameter is ignored).
SETPROPS_CACHE	Caches changes until properties are closed by using the CloseProperties function.


 Structure

The following structure is used with program information file management.


PROPSHEETPAGE [New - Windows 95]
 PROPSHEETPAGE

[New - Windows 95]

typedef struct _PROPSHEETPAGE {
    DWORD  dwSize;           // size of structure, in bytes
    DWORD  dwFlags;          // see below
    HINSTANCE  hInstance;    // instance handle for template
    union {
        LPCSTR  pszTemplate;        // resource name of template
        const VOID FAR *pResource;  // address of resource in memory
    };
    union {
        HICON       hIcon;   // icon handle
        LPCSTR      pszIcon; // icon name or identifier
    };
    LPCSTR      pszTitle;    // string or string identifier
    DLGPROC     pfnDlgProc;  // address of dialog box procedure
    LPARAM      lParam;      // user data
    LPFNRELEASEPROPSHEETPAGE pfnRelease; // see below
    UINT FAR * pcRefParent;  // address of ref count variable
} PROPSHEETPAGE, FAR *LPPROPSHEETPAGE;

Contains information about the property sheet.

dwFlags

Flags identifying which members contain valid values. This member can be a combination of these values:

PSP_DEFAULT	The pszTemplate member contains address of resource template name. The pResource member is not valid. The hIcon, pszIcon, pfnRelease, and pcRefParent members are not used.
PSP_DLGINDIRECT	The pResource member contains address of a dialog box template in memory. The pszTemplate member is not valid.
PSP_USEICON	The hIcon member contains a valid icon handle.  The pszIcon member is not valid.
PSP_USEICONID	The pszIcon member contains the address of a valid resource name or resource identifier. The hIcon member is not valid.
PSP_USERELEASEFUNC	The pfnRelease member has the address of the function to call before releasing the property sheet.
PSP_USERREFPARENT	The pcRefParent member contains the address of the variable to the receive reference count.
pfnRelease

Address of the release function. The operating system calls this function before destroying the given property sheet.


 Virtual Machine Services

This article describes the virtual machine services and shows how to use them in MS-DOS − based applications.


 About Virtual Machine Services

Virtual machine services allow Microsoft® MS-DOS® − based applications to take advantage of features provided by Microsoft® Windows® 95 when the applications run in a window. MS-DOS − based applications can retrieve and, optionally, set the title of the window in which they run.


 Window Title

The window title for an MS-DOS − based application, which is displayed when the application runs in a window, identifies the application and its operating state. The operating system sets the title when an application first starts, but the application can change portions of the title to better communicate its state to the user.

The window title consists of three strings: a virtual machine state, a virtual machine title, and an application title. The system creates the window title by concatenating the three strings, separating the strings with a system-defined separator, typically a hyphen.

The virtual machine state, which can be set by the operating system only, identifies whether the virtual machine is inactive or whether the user is carrying out tasks, such as cut and paste operations. The state is frequently an empty string. The virtual machine title and the application title, which can be set by an application, identify the application and the current document or activity of the application, respectively.

By default, the operating system sets the virtual machine title to the title stored in the corresponding .PIF file or to a title specified by the shell. You can determine the current virtual machine title by using the Get Virtual Machine Title function. You can change the title by using the Set Virtual Machine Title function.

The system typically sets the application title to the name of the application, so the virtual machine title and application title are frequently the same when the application first starts. Many applications change this title to the name of the current document or to an empty string if there is no current document. You can determine the current application title by using the Get Application Title function. You can change the title by using the Set Application Title function.

If you set the virtual machine title or application title, the length of the individual titles must not exceed 30 and 80 characters, respectively.

You can call the window title functions at any time. Furthermore, you can call these functions regardless of whether your application is running with the Windows 95 or MS-DOS operating system. However, not all operating systems support these calls. The functions are not supported if a call to a function leaves the AX register unchanged.


 Close-Aware Applications

A close-aware application is any MS-DOS − based application that periodically checks the state of an internal close flag and terminates if the flag is set. Windows 95 sets this flag when the user chooses the Close command from the system menu of the window in which the MS-DOS − based application runs. Close-aware applications enable the Close command, which gives the user an alternate way to exit the application and close the window.

An application enables or disables the Close command by using the Enable or Disable Close Command function. The function takes a flag indicating whether to enable or disable the command. Once the command is enabled, the application must periodically check the close flag by using the Query Close function. The function returns zero in the AX register if the user has chosen the command.

If the Query Close function returns zero in AX, the application should call the Acknowledge Close function to acknowledge the close state of the internal close flag. After the application acknowledges the close state, subsequent calls to the Query Close function will return 1 in AX, indicating that the user has chosen the Close command and the close state has been acknowledged. After acknowledging the close state, an application should take all necessary steps to shut down and eventually exit, or it should cancel the close operation by calling the Cancel Close function.

An application should acknowledge the close state if it needs to perform additional keyboard input before exiting. When the close state has been signaled but has not yet been acknowledged by the application, all keyboard reads will return NULL and buffered line input will return an empty string.

After an application acknowledges the close state, the state reverts to unacknowledged if the application either exits or cancels the close operation. If the application acknowledges the close state and then exits, the parent process will be in an unacknowledged close state. The application must then acknowledge the close state to perform additional keyboard input before exiting or canceling the close operation.

For example, if a text editor receives a positive response from the Query Close function and has some buffers that have not been saved, it should call Acknowledge Close and ask the user if the buffers should be saved with these possible responses: "Yes," "No," or "Cancel."

If the user responds "Yes" or "No," the text editor should save (or not save if the response was "No") the buffers and then exit. The close state remains active, and the parent process (probably the command interpreter) will also receive a positive response from Query Close and will also terminate.

If the response is "Cancel," the application should call the Cancel Close function and not exit. Canceling the close operation informs the system that any attempted shutdown should be abandoned.

This sequence of operations is analogous to the way that Windows-based applications handle the WM_QUERYENDSESSION message.

Depending on the tasking option chosen for the application, there may be some time between when the user chooses the Close command and the application checks the internal close flag. During this time, the system changes the window title of the application, appending the word "Closing" to it, and gives the user the opportunity to cancel the command by changing the command name to Cancel Close. If the user chooses the Cancel Close command, the close flag is reset, preventing the application from closing. If a close-aware application fails to check the close flag within a system-defined amount of time, the system automatically abandons the operation and resets the close flag.

The system tracks the close-awareness and close state for each process. For the virtual machine to close, all applications in the virtual machine must close. When the user chooses the Close command, the operating system detects applications that are not close-aware and displays a dialog box with a warning message, but gives the user the option of forcing the application to exit anyway. If you make an application close-aware, it can shut down cleanly.


 Reference

The following functions and commands are associated with virtual machine services.


 Window Title Functions

The following window title functions are used with virtual machine services.


Get Application Title [New - Windows 95]
 Get Application Title

[New - Windows 95]

mov  ah, 16h           ; Windows multiplex function
mov  al, 8Eh           ; VM Title
mov  di, seg AppTitle  ; see below
mov  es, di
mov  di, offset AppTitle
mov  cx, Size          ; see below
mov  dx, 2             ; Get Application Title
int  2Fh
cmp  ax, 1
je   success

Copies the application title to the specified buffer.

•	Returns 1 in the AX register if successful or zero otherwise.

AppTitle

Address of a buffer that receives the application title. This parameter must not be zero.

Size

Size, in bytes, of the buffer pointed to by AppTitle.

Get Application Title copies as much of the title as possible, but never more than the specified number of bytes. The function always appends a terminating null character to the title in the buffer.


Get Virtual Machine Title [New - Windows 95]
 Get Virtual Machine Title

[New - Windows 95]

mov  ah, 16h           ; Windows multiplex function
mov  al, 8Eh           ; VM Title
mov  di, seg VMTitle   ; see below
mov  es, di
mov  di, offset VMTitle
mov  cx, Size          ; see below
mov  dx, 3             ; Get Virtual Machine Title
int  2Fh
cmp  ax, 1
je   success

Copies the virtual machine title to the specified buffer.

•	Returns 1 in the AX register if successful or zero otherwise.

VMTitle

Address of a buffer that receives the virtual machine title. This parameter must not be zero.

Size

Size, in bytes, of the buffer pointed to by VMTitle.

Get Virtual Machine Title copies as much of the title as possible, but never more than the specified number of bytes. The function always appends a terminating null character to the title in the buffer.


Set Application Title [New - Windows 95]
 Set Application Title

[New - Windows 95]

mov  ah, 16h           ; Windows multiplex function
mov  al, 8Eh           ; VM Title
mov  di, seg AppTitle  ; see below
mov  es, di
mov  di, offset AppTitle
mov  dx, 0             ; Set Application Title
int  2Fh
cmp   ax, 1
je   success

Sets the application title to the given string.

•	Returns 1 in the AX register if successful or zero otherwise.

AppTitle

Address of a null-terminated string specifying the application title. The title must not exceed 80 characters, including the terminating null character. If this parameter is zero or points to an empty string, the function removes the current application title.

Although not common, Set Application Title may return 1 in the AX register even though the title was not changed. In general, applications must not rely on the operating system to keep an accurate copy of the current title.


Set Virtual Machine Title [New - Windows 95]
 Set Virtual Machine Title

[New - Windows 95]

mov  ah, 16h           ; Windows multiplex function
mov  al, 8Eh           ; VM Title
mov  di, seg VMTitle   ; see below
mov  es, di
mov  di, offset VMTitle
mov  dx, 1             ; Set Virtual Machine Title
int  2Fh
cmp   ax, 1
je   success

Sets the virtual machine title to the given string. Applications should not change the virtual machine title except under explicit instructions from the user.

•	Returns 1 in the AX register if successful or zero otherwise.

VMTitle

Address of a null-terminated string specifying the virtual machine title. The title must not exceed 30 characters, including the terminating null character. If this parameter is zero or points to an empty string, the function removes the current virtual machine title.

Although not common, Set Virtual Machine Title may return 1 in the AX register even though the title was not changed. In general, applications must not rely on the operating system to keep an accurate copy of the current title.


 Close-Aware Application Functions

The following close-aware application functions are used with virtual machine services.


Acknowledge Close [New - Windows 95]
 Acknowledge Close

[New - Windows 95]

mov ah, 16h    ; Windows multiplex function

mov al, 8Fh    ; VM Close

mov dh, 2      ; Acknowledge Close

mov dl, 0      ; always 0

int 2Fh

or ax, ax

jz success

Acknowledges the close state of the internal close flag.

•	Returns zero in the AX register if successful.

Acknowledging the close state is necessary if an application needs to perform additional keyboard input before exiting. If the close state has been signaled but not yet acknowledged by an application, all keyboard read operations will return NULL and buffered line input will return an empty string.


Cancel Close [New - Windows 95]
 Cancel Close

[New - Windows 95]

mov ah, 16h    ; Windows multiplex function

mov al, 8Fh    ; VM Close

mov dh, 3      ; Cancel Close

mov dl, 0      ; always 0

int 2Fh

or ax, ax

jz success

Cancels the close operation.

•	Returns zero in the AX register if successful.

After acknowledging the close state of the internal close flag, an application should either exit or cancel the close operation by calling Cancel Close.


Enable or Disable Close Command [New - Windows 95]
 Enable or Disable Close Command

[New - Windows 95]

mov ah, 16h    ; Windows multiplex function

mov al, 8Fh    ; VM Close

mov dh, 0      ; Enable or Disable Close Command

mov dl, Flags  ; see below

int 2Fh

or ax, ax

jz success

Enables or disables the Close command in the system menu.

•	Returns zero in the AX register if successful.

Flags

Close flags. This parameter can be one of these values:

00h	Disables the Close command.
01h	Enables the Close command.


Query Close [New - Windows 95]
 Query Close

[New - Windows 95]

mov ah, 16h   ; Windows multiplex function

mov al, 8Fh   ; VM Close

mov dh, 1     ; Query Close

mov dl, 0     ; always 0

int 2Fh

Indicates whether the user has attempted to close an MS-DOS − based application from Windows by choosing the Close command from the system menu.

•	Returns one of the following values in the AX register:

0	The close command was chosen, and the application has not acknowledged the close state.
1	The close command was chosen, and the application has acknowledged the close state.
168Fh	The close command has not been chosen, and the application should continue running.
Query Close returns a nonzero value if the application has not enabled the Close command by using the Enable or Disable Close Command function.


 International Guidelines

This overview describes the rules you should follow when writing Windows 95 modules or applications for international audiences.


 About International Guidelines

This section is a reference guide to help developers write modules or applications that can be localized and that take full advantage of the Microsoft® Windows® 95 international environment.


 Windows 95 Platform Strategy

Windows 95 is available in many different languages. The languages and the rules associated with them can be divided into these three groups:

•	Western/Eastern European languages, such as German, French, and Russian. These languages use an 8-bit character set and are written from left to right. In this article, these languages are called "WE" languages.

•	Middle-Eastern languages, such as Hebrew and Arabic. These languages use an 8-bit character set and are written from both left to right and right to left. In this article, these languages are called "ME" languages.

•	Far-Eastern languages, such as Japanese and Chinese. These languages use a 16-bit character set (also referred to as a double-byte character set or DBCS) and are written from left to right or top to bottom. In this article, these languages are called "FE" languages.

Windows 95 is a multiple character-set system, which means you can use more than one character set at a time. To accommodate the text management rules associated with WE, ME, and FE languages, Windows 95 uses a three-platform strategy that can be summarized in the following manner.


 WE Platform

The WE platform (U.S. Windows 95) is the code base of Windows 95. It supports all WE languages and the rules associated with them, and it includes application programming interface (API) elements and other mechanisms for manipulating these languages. The WE platform is also the base on which the ME and FE platforms are built. Applications built for the WE platform can also run on the ME and FE platforms, but they can not take advantage of functions written specifically for those platforms.

The WE platform will be localized in the following languages: German, French, Spanish, Swedish, Dutch, Italian, Norwegian, Danish, Finnish, Portuguese (Brazil), Portuguese (Portugal), Russian, Czech, Polish, Hungarian, Turkish, Greek, and Catalan.


 ME Platform

The ME platform is built on the WE platform. It includes the API elements and other mechanisms found in the WE platform. It also includes additional API elements specifically designed to support ME languages. To take full advantage of the ME platform, an application must use the additional API elements and may need to be recompiled.

The ME platform will be localized in the Arabic and Hebrew languages.


 FE Platform

The FE platform is built on the WE platform. It includes the API elements and other mechanisms found in the WE platform. It also includes additional API elements specifically designed to support FE languages. To take full advantage of the FE platform, an application must use the additional API elements and may need to be recompiled.

The FE platform will be localized in the Japanese, Chinese (Traditional), Chinese (Simplified), and Korean languages.


 International Language Requirements

This section is divided into three subsections: localization, national language support functions, and multilingual content support. Each subsection describes a set of rules that you should follow when writing Windows 95 modules or applications for international audiences.


 Localization

Certain rules should be followed so that Windows 95 modules or applications can be translated into different languages. For example, you should use resources for all elements to be localized, including strings, messages, icons, and so on.


 General Programming Guidelines

You should follow these general programming guidelines when writing applications for international audiences:

•	Do not store handles or identifiers in resources.

•	Do not shift resource identifiers when adding resources to a file. Instead, just add an identifier (allowing no duplicate identifiers).

•	Do not store user interface elements (strings, messages, menus, and so on) in initialization (.INI) files.

•	Use the FormatMessage function to dynamically allocate buffer sizes for your Microsoft® Win32® − based applications. For more information, see the description of FormatMessage.

•	Do not hard code filenames into a binary file. Windows 95 modules or applications may use long filenames, and these filenames appear on the desktop. Because the filenames are visible to the user, they may need to be translated. Windows 95 − based modules or applications should be able to be renamed without requiring any code change.


 Guidelines for Using Strings

You should follow these guidelines when using strings in applications for international audiences:

•	Do not concatenate strings in dialog box controls. Doing so can create a string that crosses a character set boundary. For example, setting a control's text to be the result of "Can not find %s" will create a string that does not make sense if the user types in Greek in an application with English resources. You should use two controls instead of one in this situation.

•	Use %numbers instead of %letters when using a string with variables in case translators and localizers need to invert the variables. The wrong and right approaches follow.

WRONG	"The file type %s on the drive %s should first be copied to the drive %s."
RIGHT	"The file type %1 on the drive %2 should first be copied to the drive %3."
•	Do not allow English text strings to use more than 70 percent of the available space in dialog boxes. Providing extra space ensures that a translated string will not exceed the length limit. An English string of 240 characters will sometimes result in a localized string of 300 characters. In a dialog box where the string limit is 256 characters, incomplete and improper localization will appear. In general, if a string that must be localized exceeds 70 percent of the limit, it should be split into two parts.


 National Language Support Functions

Windows 95 includes a set of functions that allows Windows 95 − based modules or applications to find and use locale-dependent information. A locale is a collection of user-preference information related to the user's language and sublanguage, represented as a list of values. The system has one default locale, but an application can also get locale information that is specific to an application or task. To take advantage of this feature, an application must use the National Language Support (NLS) functions described in the Microsoft Win32 Software Development Kit (SDK).


 Multilingual Content Support

Windows 95 includes multilingual content support for documents, which means Windows 95 applications can mix characters from different character sets in the same document. For example, an application can mix Greek and German in the same document, even though characters for these languages belong to two different character sets. This feature makes Windows 95 a multiple character set (or multiple code page) operating system.

The basic multilingual architecture is based on languages, especially keyboard languages. A user can create a list of keyboard languages from the set of all keyboard languages available. The system can be started with one language active, and the additional selected languages loaded and available. When the user switches from one language to another, a WM_INPUTLANGCHANGE message is sent to the application with the focus to indicate that the language has changed. The message includes the handle of the new keyboard layout (language) and character. The application can then use the information to determine whether the locale has changed and whether the character set has changed.

To take full advantage of multilingual content support, you should not assume that the character set is U.S. ANSI. Many "ANSI" character sets are available today. For example, Russian Windows 95 uses the "Cyrillic ANSI" character set, which is different from the one used by U.S. Windows 95 (U.S. ANSI). In addition, you should always use the Choose Font common dialog box. If that is not possible, you should use the EnumFontFamiliesEx function. Finally, you should always save the character set with the font names in documents and process multilingual Windows messages, including WM_INPUTLANGCHANGEREQUEST and WM_INPUTLANGCHANGE. They either request that the keyboard language be changed or indicate that a the keyboard language has changed.

Note  You should store the character set and keyboard layout of the next run of text when your application receives the WM_INPUTLANGCHANGEREQUEST or WM_INPUTLANGCHANGE message. You should also modify your Find or Search dialog boxes or algorithms so that they support multilingual search and replace operations. In addition, any headers, footers, and other peripheral annotations should be able to handle different fonts and languages.

After the keyboard language has changed, you should use the following API elements:

•	Determine whether the character set has changed by using the wParam parameter from the WM_INPUTLANGCHANGE message.

•	Select a new font by using EnumFontFamiliesEx function if the character set has changed.

•	Use the "Ex" versions of keyboard functions — for example, ToAsciiEx instead of ToAscii.

•	Use the CR_ formats with the SetClipboardData function when placing text on the clipboard and with the GetClipboardData function when getting text from the clipboard.

•	Use the GetCharacterPlacement and GetFontLanguageInfo functions when drawing text, calculating caret positions, or performing any other action related to a device. The functions provide intermediate information that make caret placement easier and allow the application to take advantage of new features in graphics device interface (GDI). They also ensure that the application is compatible across all three platforms. Even if you write your application for non-ME and non-FE platforms, using GetFontLanguageInfo allows you to detect when the user tries to use one of the ME or FE fonts and allows you to prevent the user from producing strange text on the screen and printer.

For more information about multilingual content and support, see the reference pages for the functions and messages mentioned in this section.


 Using the Far-Eastern Platform

For your Windows 95 − based module or application to run on the FE platform, you must enable your module or application to use double-byte characters by using the CharNext, CharPrev, and IsDBCSLeadByte functions. For information about double-byte characters enabling, see "Using Double-Byte Characters." You should also enable your module to use the IMM (Input Method Manager) functions and modify your application to interact with an IME (Input Method Editor) so that the user will be able to use Far-Eastern characters. For information about FE enabling, see "Using Input Method Editors."


 Using the Middle-Eastern Platform

You should follow certain guidelines to enable your Windows 95 − based module or application to run on the ME platform:

•	Use the Windows 95 functions. There are no specific ME functions. All of the functions for writing ME-based software are built into the basic Windows 95 code, and all the items mentioned under "Multilingual Content Support" earlier in this topic are also relevant. However, for standard left to right languages, these features are desirable, but not necessary.

•	Call the GetCharacterPlacement function to provide line layout support for getting the visual orientation, character widths, and character placement required for laying out and displaying any single-byte character text.

•	Call the GetFontLanguageInfo function to determine which services are required for a particular language. The main difference between ME and WE languages is that the text may be oriented to the right of the page instead of to the left. This means that you need some form of user interface for switching direction, and you need the ability to write text from right to left instead of left to right. You can achieve this by using the SetTextAlign function.

•	Use the ME-specific window styles and common control styles. If you have enabled your application to run using ME resources (for example, right to left menus), you must also modify calls to functions, such as MessageBox and CreateWindow, to use the ME-specific flags (for example, to allow right to left orientation of menus). If a particular window class has no specific right to left style, like the button class, use extended window styles, such as WS_EX_RTLREADING and WS_EX_RIGHT.

For more information about ME enabling, see "Writing Applications for Middle-Eastern Languages."


 Using Double-Byte Characters

This article provides guidelines to reduce the work necessary to port an application written for a single-byte character set system (SBCS) to a double-byte character set (DBCS) system.


 About Using Double-Byte Characters

String operations in applications running with an operating system that uses a DBCS are slightly different from those in applications running with a system that uses a single-byte character set. A DBCS-enabled application allows users to create, edit, print, and save documents in their own languages, even if the user interface has not been localized. DBCS enabling involves adding code to handle DBCS strings, which are made up of a mixture of 1-byte and 2-byte characters. For example, a user could run an English version of a DBCS-enabled application with a Japanese version of Microsoft® Windows®, freely typing in and editing kanji strings without any problem.

DBCS enabling is only one step in internationalizing an application. For more information about DBCS and other internationalization issues, see Developing International Software for Microsoft Windows by Nadine Kano, available through Microsoft Press®.


 Code Pages

Accented characters are an integral part of many languages. However, the 7-bit ASCII character set does not provide support for accented characters. To compensate, Microsoft® MS-DOS® uses 8-bit code pages as a means of providing support for character sets and keyboard layouts used in different countries. Each code page table relates the binary character codes used by an application to keys on the keyboard or to the appearance of characters on the display.

Over the years, support for code pages that include different accented characters has been added to MS-DOS. In each of these code pages, the characters numbered 32 through 127 are the same characters that form the 7-bit ASCII set. The characters above 127, known as extended characters, vary from code page to code page. The set of extended characters, which contains accented characters, determines which languages the code page can support.

Microsoft Windows 95 uses the same type of code pages introduced in Windows version 3.1. These code pages are different from the ones in MS-DOS. For example, the line-drawing characters that allow MS-DOS − based applications to draw boxes have not been included in Windows code pages and have been replaced with additional publishing characters.


 Double-Byte Character Sets

The Chinese language defines more than 10,000 basic ideographic characters. Each ideographic character represents a word or syllable, and many of these characters were adapted long ago by other Far-Eastern languages. These characters are called kanji in Japanese, hantsu or hanzi in Chinese, and hanja in Korean. Because there are so many ideographic characters, single-byte character sets, which have room for only 256 characters, are too small to accommodate those languages.

The solution used in Windows 95 (and in earlier versions of Windows) has been to encode most characters (primarily ideographs) with 2-byte values, making many more than 256 characters available. However, characters, such as the ASCII set, the Japanese phonetic syllabary known as katakana, and some symbols still have single-byte representations. The result is a code page that mixes 1-byte and 2-byte characters. Double-byte character sets typically contain a mixture of 1-byte and 2-byte characters.

The mixing of byte lengths in Far-Eastern versions of Windows leads to more complex string parsing code. Each 2-byte character is composed of a lead byte and a trail byte, which must be stored together and manipulated as a unit. A lead byte value always falls into one or more ranges above 127. Although 1-byte characters may be defined above 127, they cannot exist in the lead byte ranges. NULL can never be a trail byte, but the range of possible trail bytes can overlap to some degree with the ASCII character set. Lead byte values are frequently indistinguishable from trail byte values; the only way to tell the difference is from the context of the surrounding characters. For that reason, if a trail byte is taken without its lead byte, it can be mistaken for a 1-byte character.

Because 1-byte characters are displayed in half the width of 2-byte characters for most fonts on Far-Eastern versions of Windows, they are sometimes referred to as half-width characters. Most half-width characters also have a full-width (2-byte) representation to make column layout on a display easier. Ideographic characters exist only in full-width form; there is, for example, no such thing as a 1-byte kanji character. In Windows 95, ASCII characters can be drawn with proportional fonts, but ideographic characters, including Japanese kanji, are always monospaced.


 Using Double-Byte Characters in an Application

To handle 2-byte characters, you should have any code that searches, selects, edits, moves, replaces, deletes, or inserts text check for double-byte pairs. An application should not split 2-byte characters and should accommodate 2-byte characters in its display operations. Rules of selection, cursor placement, and cursor movement are the same as for alphabetic characters; the cursor should always end up between characters, never in the middle of one.

Because 1- and 2-byte characters can be mixed, it is not safe to use unary operators, such as ++ or - -, which increment or decrement string pointers one byte at a time instead of a character at a time. These operators can be replaced with the Microsoft® Win32® CharNext and CharPrev functions (or the AnsiNext and AnsiPrev functions used in Windows version 3.x). These functions increment string pointers properly whether the current character is a single byte or a double byte.

In addition, it is not safe to access a string with 2-byte characters randomly in the following manner.

Mychar = string[i]

Unless a string is searched from the beginning, there is no way of knowing if the byte accessed is a single byte, lead byte, or trail byte.

For string processing, it is often important to determine if a byte is a lead byte. The IsDBCSLeadByte function can be used to test whether a particular byte is in the default code page's lead byte range, and the IsDBCSLeadByteEx function can be used to check the lead byte range of a specified code page. The following example shows how to search for a backslash ('\') character in a DBCS string by using IsDBCSLeadByte.

// Returns a pointer to the first '\' in a given string.

char* GetBackSlash( char *pszString)

{

 while(*pszString)

 {

     if (!IsDBCSLeadByte(*pszString))

     {

        if (*pszString == '\\')

            break;

     }

     else // it is a lead byte

     {

        // Increment the pointer 1 byte to point to the trail byte.

        pszString++;

     }

     // Increment the pointer 1 byte to point to the next character.

     pszString++;

 }

 return( pszString);

}

Although IsDBCSLeadByte and IsDBCSLeadByteEx are convenient, calls to these functions may impact performance if you have a large number of bytes to test. As an alternative, you can check the ranges yourself by calling the GetCPInfo function, which returns the lead byte ranges in the LeadByte member of the CPINFO structure. LeadByte is an array of bytes. Each range, which consists of two bytes, specifies a starting and ending value for the range. Ranges are inclusive, and there can be a maximum of five ranges. Any unused bytes in LeadByte are set to zero.

To further optimize your code, you should only call DBCS functions or special string handling code when using a DBCS code page. There are several methods of doing this. For example, an application can determine whether it is running on a DBCS system at run time by using GetCPInfo in its initialization code. GetCPInfo returns the maximum number of bytes for a character in the code page in the MaxCharSize member of the CPINFO structure. The advantage of this method is that it requires having only one executable file.

Another method is to use a DBCS command-line option at compile time and bracket sections of string handling code with #ifdef directives. The number of #ifdef blocks can be greatly reduced by defining the following macros.

#ifndef DBCS

#define CharNext(pc)    ((*pc) ? pc + 1 : pc)

#define CharPrev(pcStart, pc) ((pc > pcStart) ? \

                                     pc - 1 : pcStart)

#ifndef WIN32

#define IsDBCSLeadByte (bByte) (FALSE)

#endif

#endif


 Using Input Method Editors

This article shows some simple ways to customize the operation of an input method editor (IME) for your application.


 About Using Input Method Editors

In Asian versions of Microsoft® Windows® 95, an IME allows users to generate single- and double-byte characters by typing at the keyboard. By default, Windows 95 carries out all actions required to enable the user to generate characters for input to your application. However, you can also customize this process by using input method manager (IMM) functions to carry out actions on your own. For more information about the IMM functions, see the documentation included in the Microsoft® Win32® Software Development Kit (SDK).


 Handling Character Input

You receive character input from an IME in the form of WM_CHAR or WM_IME_CHAR messages. Windows 95 provides a default IME that automatically displays a status window enabling users to choose the conversion mode and other properties for generating single- and double-byte characters for the current application. (Users can also purchase third-party IMEs that may have additional capabilities.)

Depending on the conversion mode, an IME provides a composition window into which the user types the initial characters and a candidates window from which the user picks the final character(s). Selecting the final character causes the IME to send either one or two WM_CHAR messages to the window procedure for the application.

You can use the IsDBCSLeadByte function to determine whether the character in a WM_CHAR message is the first byte of a double-byte character. If it is, the next WM_CHAR message contains the second byte. Once you have both bytes, you can display the character by using a function such as ExtTextOut.

In some cases, you may receive WM_IME_CHAR messages from the IME. The wParam parameter of this message contains one or two bytes, depending on the user's final selection. To determine the size of the character, you need to use the IsDBCSLeadByte function in the following manner.

WORD wChar;

case WM_IME_CHAR:
    wChar = (WORD) wParam;
    if (IsDBCSLeadByte(HIBYTE(wChar) == TRUE)
        // wChar is a double-byte character.
    else
        // wChar is a single-byte character.
    break;

If you choose not to handle the WM_IME_CHAR message, you can pass it to the DefWindowProc function. This function converts the message into one or two WM_CHAR messages and sends them to your window procedure.


 Managing the IME

You manage the IME by enabling (opening) it for conversions, setting the conversion modes, and positioning the composition window. By default, the IME opens when the user chooses a conversion mode from the status window, and the IME displays the composition window when the user begins to type. You can change this default behavior by using the ImmSetOpenStatus, ImmSetConversionStatus, and ImmSetCompositionWindow functions.

You open the IME when you want to allow users to enter characters for conversion. You can determine whether the IME is currently open by by using the ImmGetOpenStatus function. If it is not, you can open the IME by using the ImmSetOpenStatus function as follows.

HIMC hIMC;
BOOL bOpen;

if (hIMC = ImmGetContext(hwnd)){
    bOpen = ImmGetOpenStatus(hIMC);
    if (!bOpen)
        ImmSetOpenStatus(hIMC, TRUE);
    ImmReleaseContext(hwnd,hIMC);
}

Once you open the IME, the composition window opens as soon as the user begins to type in the window associated with the input context. By default, the composition is displayed as a pop-up window placed near the window having the input focus. You can change this default position and appearance by using the ImmSetCompositionWindow function. The following example shows how to embed the composition window into the current line of text (similar to edit controls) by using the CFS_POINT style.

HIMC hIMC;
COMPOSITIONFORM cf;

if (hIMC = ImmGetContext(hwnd)){
    cf.dwStyle = CFS_POINT;
    cf.ptCurrentPos.x = ptCurrent.x;
    cf.ptCurrentPos.y = ptCurrent.y;
    ImmSetCompositionWindow(hIMC, &cf);
    ImmReleaseContext(hWnd,hIMC);
}

In this example, the ptCurrent member contains the coordinates of the caret in the window identified by the hwnd parameter. The function places the composition window at that position, and characters that the user types appear there.

Once the user starts typing, the IME converts and displays the characters using the current conversion and sentence modes. The user typically sets the modes through the status window, but you can set them as well by using the ImmSetConversionStatus function. In most cases, it is best to retrieve and change the current modes by using both the ImmGetConversionStatus and ImmSetConversionStatus functions in the following manner.

HIMC hIMC;
DWORD dwConvMode, dwSentence;

if (hIMC = ImmGetContext(hWnd)){
    // Get the current modes.
    ImmGetConversionStatus(hIMC, &fdwConversion, &fdwSentence);
    // Change to full shape input mode.
    fdwConversion |= IME_CMODE_FULLSHAPE;
    // Set the new modes.
    ImmSetConversionStatus(hIMC, fdwConversion, fdwSentence);
    ImmReleaseContext(hWnd,hIMC);
}


 Managing the IME Window

Windows 95 creates an IME window for each thread in an application. The IME window, belonging to the system-defined "IME" window class, creates and owns the status, composition, and candidates windows that give users the means to control the conversion of characters. The IME window carries out default processing for the status, composition, and candidates windows for the application, so changing the IME window changes those windows too.

You can control the position and style of the status, composition, and candidates windows directly by using functions such as ImmSetStatusWindow, ImmSetCompositionWindow, and ImmSetCandidateWindow. You can also control the windows indirectly be sending WM_IME_CONTROL messages to the IME window. You can retrieve the handle of the IME window by using the ImmGetDefaultIMEWnd function.

The following example shows how to create an IME window by using the "IME" window class in a call to the CreateWindowEx function.

hwndIME = CreateWindowEx(
    0,
    "IME",                  // IME class
    NULL,                   // no window title
    WS_DISABLED | WS_POPUP, // disabled window
    0, 0, 0, 0,             // no need to set size
    hwnd,                   // owner window
    NULL,
    hinstance,
    NULL);

If your application does not process character input from the keyboard, you can close an IME window by retrieving the handle and passing it to the DestroyWindow function.


 Monitoring the Composition

You can monitor the user's interaction with the status, composition, and candidates windows by processing WM_IME_NOTIFY and WM_IME_COMPOSITION messages. The IME sends these messages to the window having the input focus whenever the user carries out some action in one of the IME windows.

WM_IME_NOTIFY is useful for monitoring changes that the user makes through the status window. For example, the IME sends this message with the IMN_SETCONVERSIONMODE value when the user changes modes in the status window. When you receive this message, you can use the ImmGetConversionStatus function to determine the new conversion and sentence modes.

WM_IME_NOTIFY is also useful for monitoring selections made by the user in the candidates window. The IME sends this message with the IMN_CHANGECANDIDATE value when the user changes the selection. When you receive this message, you can use the ImmGetCandidateList function to retrieve the list of candidates and the index of the current selection.

WM_IME_COMPOSITION is useful for monitoring input and conversions made in the composition window. The IME sends this message whenever the user types a character. When you receive this message, you can use the ImmGetCompositionString function, as shown in the following example, to retrieve the characters typed by the user or the converted characters proposed by the IME.

HIMC hIMC;
char szComp[256];
DWORD dwSize;

case WM_IME_COMPOSITION:
    if ((hIMC = ImmGetContext(hwnd)) == NULL)
        break;

    // Get the composition string.
    dwSize = ImmGetCompositionString(hIMC, GCS_COMPSTR, szComp, 256);

    ImmReleaseContext(hWnd,hIMC);
    break;

The IME sets the lParam parameter in WM_IME_COMPOSITION to the GCS_RESULTSTR value when the user completes the composition. The following example shows how to retrieve the final result of the conversion by using ImmGetCompositionString.

HIMC hIMC:
LPSTR lpstr;
DWORD dwSize;

case WM_IME_COMPOSITION:
    if (!(lParam & GCS_RESULTSTR))
        break;

    // Get the context.
    if ((hIMC = ImmGetContext(hwnd)) == NULL)
        break;

    // Get the result string size, and add 1 for the terminating
    // null character.
    dwSize = ImmGetCompositionString(hIMC, GCS_RESULTSTR, NULL, 0);

    // Allocate memory to receive the string.
    if ((lpstr = GlobalAlloc(GPTR, dwSize)) == NULL) {
         MyError();
         break;
    }

    // Get the result string.
    ImmGetCompositionString(hIMC, GCS_RESULTSTR, lpstr, dwSize);

    // Release the context when it is no longer needed.
    ImmReleaseContext(hWnd,hIMC);

    // Do something with the result string here.

    // Free the memory now.
    GlobalFree((HGLOBAL)lpstr);
    break;

When you process WM_IME_COMPOSITION in this manner, you can safely ignore any WM_IME_CHAR messages sent for the result string.


 Customizing the User Interface

You can customize the user interface for the IME by replacing the default IME window with your own window. In this case, you define your own IME window class and window procedure and create the IME window for your application after destroying the default IME window.

Your IME window must provide the same capabilities as the default IME window, or your application windows must be prepared to provide the same functionality as the status, composition, and candidates windows. The window also must handle any WM_IME_CONTROL messages sent to it and send WM_IME_NOTIFY and other messages in response to any user input to it.

To ensure that your IME window receives all appropriate messages, you must call the ImmIsUIMessage function from every window procedure in your application that accepts character input from the keyboard. The following example shows how to restructure your window procedure to process these messages.

HWND hwndIME;  // handle of IME window

long CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{

    if (ImmIsUIMessage(hwndIME, msg, wParam, lParam)==TRUE) {
        // Already processed and ready for post-processing.
        switch(msg) {
            // Post-process WM_IME_COMPOSITION and other messages.
        }
        return 0;
    } else {
        // Not processed yet.
        switch(msg) {
        case WM_CREATE:
             // Create your IME window here.
             break;
        case WM_DESTROY:
             // Destroy your IME window here.
             break;
        }
    }
}

If you choose not to create an IME window and provide instead the status, composition, and candidates functionality from within the window procedures of your application, your window procedures must handle the following IME messages rather than pass them to the DefWindowProc function.

COMPOSITIONFORM cf;
POINT ptMyPoint;
LOGFONT lf;

// The message was not handled by the IME window.
switch(uMsg) {
    case WM_CREATE:
        hIMC = ImmCreateContext();
        hOldIMC = ImmAssociateContext(hWnd ,hIMC);
        break;

    case WM_IME_STARTCOMPOSITION:
        // Prepare to receive the WM_IME_COMPOSITION message.
        break;

    case WM_IME_ENDCOMPOSITION:
        // Finish handling the composition string.
        break;

    case WM_IME_COMPOSITION:
        // Get the composition string, the result string,
        // and also the information for displaying the strings.
        break;

    case WM_IME_SETCONTEXT:
        // Remove bits from lParam to indicate that
        // this window can draw the composition string
        // and index 0 candidate list.
        lParam &= ~(ISC_SHOWUICOMPOSITIONWINDOW &
                    ISC_SHOWUICANDIDATEWINDOW);
        return DefWindowProc(hWnd, uMsg, wParam, lParam);

    case WM_IME_NOTIFY:
        // Handle each IMN_ submessage, and display the IME
        // and candidate list status.
        switch (wParam) {
        case IMN_OPENCANDIDATE:
        case IMN_CHANGECANDIDATE:
        case IMN_CLOSECANDIDATE:
            // This application can draw only one candidate list
            //  whose index is 0.

            if (lParam == 0x01)  // Bit 0 is On, it is index 0.

                // Draw the candidate list.
            else
                return DefWindowProc(hWnd, uMsg, wParam, lParam);
            break;
        default:

            // Make a notification to the IME window.
            return DefWindowProc(hWnd, uMsg, wParam, lParam);
        }

    break;

    case WM_IME_COMPOSITIONFULL:
        // Adjust the size of the window/area to draw the
        // composition string.
        break;

    case WM_DESTROY:
        ImmAssociateContext(hWnd, hOldIMC);
        ImmDestroyContext(hIMC);
        break;
}

To draw the composition string without the default IME window, you need to handle the WM_IME_COMPOSITION, WM_IME_STARTCOMPOSITION, and WM_IME_ENDCOMPOSITION messages. If you receive WM_IME_COMPOSITION and the composition is not final, you need to retrieve the attribute information as well as the composition characters to determine how to draw the characters.

HIMC hIMC:
LPSTR lpCompStr;
LPBYTE lpbAttr;
LPSTR lpResultStr;
DWORD dwStrSize;
DWORD dwAttrSize;

case WM_IME_COMPOSITION:
    if ((hIMC = ImmGetContext(hwnd)) == NULL)
        break;

    if (lParam & GCS_RESULTSTR) {
         // Received the final result, so grab it.
         dwSize = ImmGetCompositionString(hIMC, GCS_RESULTSTR,
             NULL, 0);

         // Allocate space for the string and attributes.

         // Draw the result string here.

    } else if (lParam & (GCS_COMPSTR | GCS_COMPATTR)) {

        // Get the size of the composition string and the attribute
        // information.
        dwStrSize = ImmGetCompositionString(hIMC, GCS_COMPSTR, NULL, 0);
        dwAttrSize = ImmGetCompositionString(hIMC, GCS_COMPATTR,
            NULL, 0);

        // Allocate space for the string and attributes.

        // Get the strings and attributes.
        ImmGetCompositionString(hIMC, GCS_COMPSTR, lpCompStr, dwSize);
        ImmGetCompositionString(hIMC, GCS_COMPATTR, lpAttrStr, dwSize);

        // Draw text using attributes to distinguish converted
        // characters from user input.
    }

    // Free the memory for the buffers here.

    ImmReleaseContext(hWnd,hIMC);

case WM_IME_SETCONTEXT:
    // Remove bits from lParam to indicate that
    // this window can draw the composition string.
    lParam &= ~(ISC_SHOWUICOMPOSITIONWINDOW);
    return DefWindowProc(hWnd, uMsg, wParam, lParam);


 Setting the IME Context

Applications that use the default IME window must pass the WM_IME_SETCONTEXT message to the DefWindowProc or ImmIsUIMessage function without modification. This message identifies the current IME context and specifies which window or windows must be shown. If you choose to customize the IME interface by drawing the composition string, candidate lists, guideline string, and soft keyboard on your own, you must process WM_IME_SETCONTEXT before passing the message to DefWindowProc or ImmIsUIMessage by modifying the lParam parameter.

If you draw the composition string in addition to processing the WM_IME_STARTCOMPOSITION, WM_IME_ENDCOMPOSTION, and WM_IME_COMPOSITION messages, you must also clear the ISC_SHOWUICOMPOSITIONWINDOW value in the lParam parameter of WM_IME_SETCONTEXT before passing the message to DefWindowProc or ImmIsUIMessage.

If you draw the candidate lists in addition to processing the IMN_OPENCANDIDATEWINDOW, IMN_CLOSECANDIDATEWINDOW, and IMN_CHANGECANDIDATEWINDOW notification messages (passed with the WM_IME_NOTIFY message), you must clear the ISC_SHOWUICANDIDATEWINDOW values in the lParam parameter of WM_IME_SETCONTEXT that correspond to the candidate lists that you can draw. For example, if you draw the second candidate list (index 2), you must clear the corresponding ISC_SHOWUICANDIDATEWINDOW value as follows.

lParam &= ~ISC_SHOWUICANDIDATEWINDOW<<2;

If you draw all candidate lists, clear all values by using the ISC_SHOWUIALLCANDIDATEWINDOW value in the following manner.

lParam &= ~ISC_SHOWUIALLCANDIDATEWINDOW;

If you draw the guideline string in addition to processing the IMN_GUIDELINE notification message (passed with the WM_IME_NOTIFY message), you must clear the ISC_SHOWUIGUIDEWINDOW value in the lParam parameter of WM_IME_SETCONTEXT before passing the message to DefWindowProc or ImmIsUIMessage.

If you hide the soft keyboard, you must clear the ISC_SHOWUISOFTKBD value in the lParam parameter of WM_IME_SETCONTEXT before passing the message to DefWindowProc or ImmIsUIMessage.


 Compatibility

Windows 95 supports IME applications that were written for previous versions of the operating system as long as the applications are compatible with the Windows version 3.1 IME. In addition Windows 95 supports Windows version 3.1 IMEs and can load and assign any Windows version 3.1 IME to a keyboard layout, making the IME available to applications written for either Windows version 3.1 or Windows 95. Also, because Windows 95 manages the interface with Windows version 3.1 IMEs, applications can use either the Windows 95 or Windows 3.1 input method management functions to access Windows version 3.1 IMEs. You can retrieve the operating system version number of an IME by using the ImmGetProperty function and specifying the IGP_GETIMEVERSION value. (Note, however, that Korean Windows version 3.1 IMEs are not supported by Korean Windows 95.)

Although any application can use a Windows version 3.1 IME, not all functions and messages are available. In particular, the ImmGetCandidateListCount, ImmGetCandidateList, ImmGetGuideLine, and ImmGetConversionList functions return an error if called, and the IMC_OPENSTATUSWINDOW, IMC_CLOSESTATUSWINDOW, IMC_GETSTATUSWINDOWPOS, and IMC_SETSTATUSWINDOWPOS messages are not available. Also, the clause information of the result string and the reading information of the composition string are not available.

Windows 95 does not support IME applications written for versions of IME that are earlier than Windows version 3.1 IME.


 Writing Applications for Middle-Eastern Languages

This article describes the process of developing applications for Middle-Eastern languages. It is assumed that the reader is familiar with techniques used to write international applications, especially separating resources from code.


 About Writing Applications for Middle-Eastern Languages

Writing applications for the Middle-Eastern languages is relatively simple. The multilingual features of the Microsoft® Win32® application programming interface (API) together with the unified architecture of international versions of Microsoft® Windows® 95 makes it possible to develop these applications just by changing the application resource files.


 Middle-Eastern Language Elements

In Middle-Eastern languages, portions of written text are read right to left and other portions are read left to right. Arabic and Hebrew are two such languages. These languages have the following similarities:

•	Both have a right to left orientation of characters within each word.

•	Both have a right to left orientation for reading order of words, but both find a left to right reading order acceptable in some cases.

•	Both have a left to right order of numbers and characters in foreign (Latin-based) text.

•	Both use a left to right reading order for foreign (Latin-based) text.

•	Both have diacritics, as most Latin scripts do. A diacritic is an accent or phonetic element that modifies another element (for example, ` + A = À).

•	Both are single-byte character set languages. In some cases, two or more of their characters may actually represent a single character called a ligature. A ligature is two or more letters joined together (for example, A + E = Æ).

Arabic and Hebrew language are different in these ways:

•	Arabic has contextual shaping of characters, depending on whether the character is positioned at the beginning, middle, or end of a word or whether it stands alone. (Hebrew has a few characters that change at the end of a sentence, but these are typed as a separate character.)

•	Arabic uses kashidas. A kashida is a null element that is the extension of the end of a character, either filling empty space or joining two characters.

In general, the languages and cultures of the Middle East have a general right to left orientation just as Latin-based languages and cultures have a left to right orientation. This means that lists, menus, sets of buttons, or anything else that can have an alignment should be designed with a right to left orientation. Although this general right to left orientation and contextual shaping of Arabic may be intimidating at first, Windows 95 provides the resources and functions needed to make handling these language easier.


 System Resources and Text Handling

In Windows 95, any string of text is saved in the order typed. This means that what you see on the screen or on the printed page may be in a different order than what you typed in. Obviously, this makes the modification of existing text a little tricky, but the Windows 95 and Win32 functions help make this easier.

Whenever possible, applications should use system edit controls for text input, subclassing them as necessary. If an application edits and displays text, it should use the GetCharacterPlacement function to determine the order in which the individual characters in the string are displayed. If the application displays a caret with the text, it should use GetCharacterPlacement to determine the caret position for each character in the text. The function also returns information about the order and number of glyphs for the string. This information is useful for determining whether the displayed string contains ligatures or extra characters, such as kashidas.

Everything in the resource file that pertains to country specific information should be thought of as part of the localization process. For the Middle East, this includes the orientation of menu items, buttons, dialog boxes, and so on. All these should be set in the resource file. If an application has menus, dialog boxes, lists, list boxes, and other visual elements that contain text, it must display the text in right to left order. Because Windows 95 allows applications to use the same functions to display text in right to left order as are used to display in left to right order, you can adapt a carefully designed application for the Middle Eastern market simply by changing the text strings, control positions, and text orientation styles in the resource file. In such cases, the application does not need to be recompiled.

In some cases, it may still make sense to modify and recompile your application source code — for example, if you need a highly optimized version of your application to compete successfully in the Middle-Eastern market.


 Thunk Compiler

These topics describe how to use thunking to avoid porting all of your code to 32 bits or to take advantage of 16-bit components in order to save development time. In addition, these topics describe issues related to thunking that may make you choose to avoid it in your application.


 About the Thunk Compiler

Writing applications for the Microsoft® Win32® application programming interface (API) is recommended for these reasons:

•	The flat address space — that is, no segments or offsets

•	Better performance

•	Greater robustness

However, as compelling as arguments are to move to the 32-bit programming model, there may be pragmatic reasons for not making the move all at once. Certain components of an application may lend themselves to the migration to 32 bits, while other components may be more tightly bound to the 16-bit environment. For example, an application developer may want to move the application's user interface code to 32 bits to take advantage of new system features, but may have an existing dynamic-link library (DLL) specifically optimized for the 16-bit architecture. Rather than delay the release of a new version of the application, the developer can decide instead to take advantage of the Microsoft Thunk Compiler to mix 16- and 32-bit components.


 Thunking Mechanics

The Thunk Compiler needs to check for these elements in a mixed 16- and 32-bit environment:

•	Pointers consist of a selector and a 16-bit offset in a 16-bit Microsoft Windows® environment. However, in a 32-bit Windows environment, pointers essentially consist of a 32-bit offset; that is, the DS, ES, SS, and CS registers all contain selectors with the same base address. All pointers in this environment are considered to be near 0:32 pointers. Translating a 16:16 pointer to a 0:32 pointer involves determining the segment base for the selector portion of the pointer and adding the offset to it. Translating a 0:32 pointer to a 16:16 pointer involves allocating a selector and calculating the offset from the base of the corresponding segment.

•	Both 16- and 32-bit applications pass function parameters on the stack. However, 16-bit applications address the stack using the SS:SP registers, but 32-bit applications use the SS:ESP registers. When thunking from 16 bits to 32 bits (or thunking back in the other direction), the processor's method of addressing the stack must be switched.

•	The word size is 32 bits in a 32-bit environment and 16 bits in a 16-bit environment. When an application uses both 16- and 32-bit environments, some piece of software must be able to translate 16-bit words to 32-bit words. The following 16-bit function can be used to illustrate the translation.

DWORD Sample(WORD i);

If a 32-bit component calls this 16-bit function, it pushes a 32-bit argument on the stack, but the 16-bit function only pops 16 bits off the stack. Later, when the function returns, it places the returned doubleword value in the DX:AX register pair, but the 32-bit calling application expects the return value to be in the EAX register. It is the thunking layer's responsibility to negotiate these translations.

•	To correctly handle packing and conversion, the Thunk Compiler translates structure members one at a time. The Thunk Compiler supports structure packing on 1-, 2-, or 4-byte boundaries (corresponding to the /Zp1, /Zp2, and /Zp4 compiler options for Microsoft C language products). However, 8-byte structure alignment is not supported. Structure packing boundaries must be the same on both sides of a thunk.

•	Unlike 32-bit code, 16-bit code is usually not reentrant; 16-bit code is typically written with the assumption of a cooperative mulitasking model. The thunk layer must serialize access to 16-bit code. In contrast, 32-bit code must execute without serialization to prevent deadlocks. The thunk layer manages serialization on transitions in both directions.


 Thunking Benefits and Drawbacks

If you use thunking to avoid porting all of your code to 32 bits or to take advantage of 16-bit components, you may save development time. In addition, your executable files may have a smaller memory footprint than if they were full 32-bit applications. However, there are some issues related to thunking that may make you choose to avoid it in your application. These issues are described in the following sections.


 Thunking Models

Microsoft® Win32s®, Microsoft® Windows NT™, and Windows 95 use different thunking models. Win32s supports "universal thunks," which are not supported by either Windows NT or Windows 95. Window NT supports "generic thunks," which only allow thunking from 16 bits to 32 bits. Although Windows 95 supports generic thunks, it does not support the underlying process model used by Windows NT. Use of the Windows 95 model can lead to serious incompatibilities with the Windows NT generic thunking model. (For more information about generic thunks in Windows 95, see "Generic Thunking Mechanism" later in this topic.) Windows 95 implements a new thunking model, "flat thunks." Flat thunks allow thunking from 32 bits to 16 bits or vice versa. The flat thunking model requires use of the Thunk Compiler described in this topic.

If you use flat thunks, your application cannot be ported to Windows NT.


 Compatibility with Existing 16-Bit DLLs

The Thunk Compiler accepts the following compatibility statement.

win31compat = true;

You must use this statement if a 16-bit DLL replaces a DLL that is currently used in a Windows version 3.1 environment or if the DLL runs as part of a graphics device interface (GDI) device driver. You should probably use this statement even if your 16-bit DLL does not fit into one of these categories, because it provides extra protection against poorly behaved DLLs that might be used by your thunk DLL.

The compatibility statement causes the unloading of a 32-bit DLL to be deferred until the containing process terminates. Use of this statement ensures that interprocess loading and freeing procedures, which may have worked with a pure 16-bit DLL, will not cause the thunked version of the 32-bit DLL to be freed prematurely. It also allows the 16-bit library to be freed without execution of the 32-bit DLL's notification routine — an occurrence that could cause reentry into 16-bit code.


 16- to 32-Bit Thunks and Preemption

Because 16-bit processes multitask cooperatively with respect to each other, 16-bit code is often written with the assumption that it will not be interrupted by another process until it explicitly yields the 16-bit scheduler (typically by calling the GetMessage function). In contrast, 32-bit code is written with the expectation that it can wait on Win32 synchronization objects without impeding the progress of other processes. If you mix code written under these different assumptions, you should take care to avoid deadlocks or errors due to unexpected reentrancy.

While a process is executing 32-bit code, it is possible for other processes to enter 16-bit code, possibly reentering the 16-bit code that was thunked from. That is, entering a 16- to 32-bit thunk releases the 16-bit subsystem for use by other processes (under certain conditions noted in the following paragraph). Thus, 16- to 32-bit thunks should not be used if your code cannot be reentered at that time. In addition, you should avoid using 16- to 32-bit thunks inside callback functions passed to a third-party DLL, unless it is documented that the code calling the callback function is reentrant. (For example, if the callback function is allowed to yield, it is probably reentrant.)

If the process executing the thunk is 32 bits, any other process can reenter 16-bit code inside a 16- to 32-bit thunk. On the other hand, if the process executing the thunk is 16 bits, only 32-bit processes can reenter 16-bit code, because 16-bit processes are cooperatively multitasked with respect to each other. Thus, if your 16-bit code is used only by 16-bit processes, the reentrancy requirement can be relaxed, because other 16-bit processes can get control only if your 16-bit process yields. (A DLL cannot control what applications call it, of course, so guaranteeing that your 16-bit code will be used only by 16-bit processes is difficult.) There are other restrictions on what can be done in 16-bit processes, as described in the following section, "Behavior of Win32 Functions Inside 16-Bit Processes" later in this topic.


 Behavior of Win32 Functions Inside 16-Bit Processes

In Windows 95, 16- to 32-bit thunks are primarily useful for implementing callback thunks on 32-bit processes. They can also be used to execute 32-bit code in 16-bit processes. Although the latter can improve performance and multitasking, there are important restrictions on what can be done in a 16-bit process.

The "bitness" of a process is determined by the format of the executable file that launched it, and it is a permanent attribute of the process. A 16-bit process executing 32-bit code is not the same as a 32-bit process executing the same code. The following important differences apply:

•	The 32-bit code will still execute on the stack reserved by the 16-bit application, which is much smaller than the 1MB stack used by true 32-bit applications.

•	16-bit processes cannot create new threads. Certain Win32 API elements, such as the functions supporting the new common dialog boxes or those supporting console applications, create threads on behalf of the calling application. These functions cannot be used in a 16-bit process.

•	Thunking into 32-bit code releases the 16-bit subsystem to other 32-bit processes, but other 16-bit processes will still be blocked, unless your process explicitly yields (typically by calling the GetMessage function). In other words, 16-bit applications still multitask cooperatively even when executing 32-bit code. This means that no 16-bit application will get processing time if a 16-bit application blocks for a long time without yielding. A common problem is using the CreateProcess function to launch a 16-bit application and then waiting on a synchronization object to do something. If the application does not yield, the new application will never run and signal the object, so deadlock will occur.

One way to avoid this problem is to use the MsgWaitForMultipleObjects function to wait for either messages or synchronization objects. Although this solution is effective when required, it still results in a less efficient blocking operation than that of a 32-bit application.

In general, 32-bit code within 16-bit processes should be limited to code that uses the 32-bit heap functions, memory-mapped file functions, file functions, and functions involving the current process and thread. 32-bit code using GDI, dialog box, message box, and message functions will also work within 16-bit processes. You should avoid using third party libraries, unless you are sure they work safely in a 16 bit-environment.


 Globally Fixing Handles

Translating a 16:16 pointer to a 0:32 pointer involves determining the segment base for the selector portion of the pointer and adding the offset to it. The global memory compacter in Windows 95 may move a block of memory at any time, however, making the linear address invalid. When the Thunk Compiler converts pointers from 16 bits to 32 bits, it fixes the segment portion before computing the linear address. If you translate pointers without using the Thunk Compiler, however, you must be aware of the requirement to fix the segment portion. For more information about the functions you can use to translate pointers, see "Translating Pointers Outside Thunks" later in this topic.


 16- to 32-Bit Thunks in GDI Device Drivers

The following compatibility statement is required for any 16- to 32-bit thunk script that runs as part of a GDI device driver.

win31compat = true;

You may only thunk using the following control display driver interface (DDI) functions in a GDI device driver.

Control(ABORTDOC)

Control(ENDDOC)

Control(NEWFRAME)

Control(NEXTBAND)

Control(STARTDOC)

If you use thunking, your driver must be reentrant.

You may call the OpenJob, StartSpoolPage, EndSpoolPage, CloseJob, and DeleteJob functions during the five listed control DDI calls. These calls will go through drivers written for Windows version 3.x for the sake of backward compatibility, but they will fail for Windows 95−based drivers.


 Generic Thunking Mechanism

Windows 95 supports the Windows NT generic thunk functions and the Windows NT version 3.5 extensions. The Win32s universal thunk mechanism is not supported.

The same limitations apply to generic thunks as to the flat thunks introduced in Windows 95. For more information, see "Thunking Models" earlier in this topic.

The following thunking functions are implemented in the Windows 95 KRNL386 and can be called by 16-bit Windows applications.

CallProc32W	GetProcAddress32W
CallProcEx32W	GetVDMPointer32W
FreeLibraryEx32W	LoadLibraryEx32W
The following WOW32 thunking functions are implemented in Windows 95. Win32 applications can call these functions. (You should avoid using these functions inside shared DLLs.)

WOWCallback16	WOWGlobalFree16
WOWCallback16Ex	WOWGlobalLock16
WOWGetVDMPointer	WOWGlobalLockSize16
WOWGetVDMPointerFix	WOWGlobalUnlock16
WOWGetVDMPointerUnfix	WOWGlobalUnlockFree16
WOWGlobalAlloc16	WOWHandle16
WOWGlobalAllocLock16	WOWHandle32
Because of architectural differences between Windows NT and Windows 95, programs using generic thunks may not be portable between the two platforms. In particular, a Win32 function that works with Windows NT in a 16-bit process is not guaranteed to do so with Windows 95 and vice versa. Also, Windows 95 may invoke the global memory compacter at times where Windows NT would not and vice versa. Finally, generic thunks work differently in 32-bit processes in Windows 95, and they do not work at all on 32-bit processes in Windows NT.

Because generic thunks are wrappers around flat thunks, they are subject to the same synchronization issues as flat thunks. For more information about synchronization issues, see "Compatibility with Existing 16-Bit DLLs" earlier in this topic and "Behavior of Win32 Functions Inside 16-Bit Processes" earlier in this topic.


 Using the Thunk Compiler

The Microsoft Win32 Software Development Kit (SDK) includes a sample application that illustrates the use of the Thunk Compiler. This application, APP32.EXE, simply thunks some basic types from 32 bits to 16 bits. This sample is an important supplement to the information in this topic.

The thunk compiler's input is a "thunk script," which is a list of C style function prototypes and type definitions. The compiler produces an .ASM file, which is really two .ASM files in one. You can assemble this .ASM file with the -DIS_16 option to get the 16-bit .OBJ file to link to the 16-bit component and then assemble it with the -DIS_32 option to get the 32-bit .OBJ file to link to the 32-bit component.

The 16-bit component of the .ASM file contains a jump table containing the 16:16 address of each function named in the thunk scripts. (The linker must be able to resolve these references; the functions must use the Pascal calling convention and either be implemented in the 16-bit DLL or be imported by the DLL.) The 32-bit half of the .ASM file contains a Stdcall function for each thunk, which converts its parameters to 16 bits and then employs some internal processing to call the 16-bit target referenced in the jump table. When a 32-bit application uses a thunked function, it calls these compiler-generated Stdcall functions directly.

For example, a thunk script's declaration for the LineTo function might look like this.

typedef          int INT;

typedef unsigned int UINT;

typedef UINT         HANDLE;

typedef HANDLE       HDC;

BOOL LineTo(HDC, INT, INT) {

}

For more information about thunk script files, see "Script Files" later in this topic.

An application would never include the LineTo function in a thunk script, of course, because this function already exists in 16- and 32-bit versions. This example (and the assembly language example that follows) are intended to illustrate the process; the assembly language code, in particular, could differ from the actual code that is generated by the current version of the Thunk Compiler.

When the preceding example from a thunk script is processed by the Thunk Compiler, the following assembly language code is generated. On the 16-bit half, there is the following jump table.

externDef LineTo:far16

FT_gdiTargetTable label word

    dw    offset LineTo

    dw       seg LineTo

The 32-bit half contains the following code.

public LineTo@12

LineTo@12:

    mov    cl,0

; LineTo(16) = LineTo(32) {}

;

; dword ptr [ebp+8]:  param1

; dword ptr [ebp+12]:  param2

; dword ptr [ebp+16]:  param3

;

public IILineTo@12

IILineTo@12:

    call    QT_Entry

    push    word ptr [ebp+8]    ;param1: dword->word

    push    word ptr [ebp+12]    ;param2: dword->word

    push    word ptr [ebp+16]    ;param3: dword->word

    call    QT_Target_gdi

    movsx    ebx,ax

    jmp        QT_Exit12

When a Win32-based application calls the LineTo function, it transfers directly to this routine, which builds a 16-bit call frame and calls a local routine asking it to look up the appropriate address in the jump table and sign-extend the return value. (Each component receives its own set of QT_ routines, which automatically use the correct jump table. The QT_ and FT_ routines are exported by the kernel.)


 Script Files

Script files contain descriptions of the functions that are thunked. These files usually have a .THK filename extension. The script files are easily created using function prototypes. For example, a function might be prototyped in the following manner.

BOOL WINAPI Sample(int n);

The corresponding definition would look like this in the script file.

typedef bool BOOL;

typedef int INT;

BOOL Sample(INT n)

{

}

Many functions take pointers in their parameter lists. Some pointers are for input only, some are output only, and some are for both input and output. For example, a "ThunkIt" function might take a pointer to an input string, update a second string, and produce a third string as output in the following manner.

BOOL WINAPI ThunkIt(LPSTR lpstrInput, LPSTR lpstrInOut, LPSTR Output);

The corresponding thunk script declaration for the function follows.

typedef char *LPSTR;

BOOL ThunkIt(LPSTR lpstrInput, LPSTR lpstrInOut, LPSTR Output)

{

    pstrInput = input;      // optional, because pointers are input

                            // by default

    lpstrInOut = inout;     // pointer taken in and updated

    lpstrOutput = output;   // pointer returned

}

When a pointer is passed from 32-bit to 16-bit code, a single selector with a limit of 64K is allocated in the thunk. If the Win16 code needs to access more than the first 64K of the block, it must change the base address of the selector or allocate additional selectors to access the block.

The thunk compiler supports the following constructions:

•	Structures passed by value or reference.

•	Structures within structures.

•	Pointers within structures, provided that the object pointed to does not require repacking. The object can be another structure.

•	Arrays of scalar values embedded in structures.

•	The "input", "output," and "inout" qualifiers for pointers, as shown in the preceding example. The default qualifier is "input."

•	Returning pointers for 32- to 16-bit thunks, provided that the object pointed to requires no repacking. The object can be a structure. The segment is not globally fixed by the thunk compiler. As a general rule, the Thunk Compiler deallocates the selectors that it allocates.

•	The bool type. This type is preferred over int in situations where an application may use nonzero values other than 1 to represent TRUE.

The Thunk Compiler does not support arrays of pointers, arrays of structures, or floating-point types (such as float or double).


 Procedure for Adding Flat Thunks

You should follow these steps to add flat thunks:

1.	Write a thunk script containing thunk declarations and type definitions for the functions that need to be thunked. You should place the following line at the beginning of the script to create 32- to 16-bit thunks.

enablemapdirect3216 = true;     // creates 32 to 16 thunks

Alternatively, you can use this line to create 16- to 32-bit thunks.

enablemapdirect1632 = true;     // creates 16 to 32 thunks

2.	Compile your thunk script.

thunk.exe <inputfile> [-o <outputfile>]

The thunk compiler has the following command line.

thunk [{-|/}options] infile[.ext]

?	Displays the help screen.
h	Displays the help screen.
o name	Overrides the default output filename.
p n	Changes the 16-bit structure alignment (default = 2).
P n	Changes the 32-bit structure alignment (default = 4).
t name	Overrides the default base name.
Nx name	Specifies the name segment or class where x is either C32 (for 32-bit code segment name) or C16 (for 16-bit code segment name).
3.	Assemble the resulting .ASM file to create the 16-bit side of the thunk, and make sure to define the DIS_16 option. For example, using Microsoft MASM version 6.11, you might use the following command line.

ml /DIS_16 /c /W3 /nologo /Fo thk16.obj 32to16.asm

4.	Make sure to mark your 16-bit DLL as being compatible with subsystem version 4.0 by running the Microsoft Resource Compiler (RC.EXE), which is included in the Win32 SDK, on the DLL.

\mstools\bin16\rc -40 <.DLL output file>

Important  	If the 16-bit DLL is not marked for subsystem version 4.0, the 32-bit DLL will not load. For more information, see "Troubleshooting" later in this topic.

5.	Assemble the resulting .ASM file to create the 32-bit side of the thunk, and make sure to define the DIS_32 option. For example, using Microsoft MASM version 6.11, you might use the following command line.

ml /DIS_32 /c /W3 /nologo /Fo thk32.obj 32to16.asm

6.	Add the entrypoint functions to the DLLs and the export and import statements to their module-definition (.DEF) files.

7.	Compile and link the 16- and 32-bit components.

8.	The code generated by the Thunk Compiler links to several Windows 95 entrypoint functions in KRNL386.EXE and KERNEL32.DLL. These entrypoint functions are specific to the Thunk Compiler and are not supported in Windows NT.

The entrypoint functions for KERNEL32.DLL are defined in THUNK32.LIB. You must link your 32-bit DLL with this library file.

In addition, the following two import statements should be added to the .DEF file for the 16-bit DLL.

C16ThkSL01     = KERNEL.631
ThunkConnect16 = KERNEL.651

Once again, these entrypoint functions exist only in Windows 95 and not in Windows NT. Attempts to load DLLs that use these functions will fail in Windows NT.


 Implementing a Thunking Layer

The thunking model allows either the 16- or 32-bit thunk component to start first and clean up everything afterward. Follow these steps to implement the thunking layer:

1.	Add a procedure named "DllEntryPoint" to your 16-bit DLL. This procedure should look like the following example. (The names of the DLLs are for illustration only.)

BOOL FAR PASCAL __export SAMP_ThunkConnect16(LPSTR pszDll16,

    LPSTR pszDll32, WORD hInst, DWORD dwReason);

BOOL FAR PASCAL __export DllEntryPoint(DWORD dwReason, WORD hInst,

        WORD wDS, WORD wHeapSize, DWORD dwReserved1,
        WORD wReserved2) {

    if (!(SAMP_ThunkConnect16("DLL16.DLL", // name of 16-bit DLL

            "DLL32.DLL",                   // name of 32-bit DLL

            hInst, dwReason))) {

        return FALSE;

    }

    return TRUE;

}

In this example, "SAMP" is the base name — that is, the name of the thunk script file, not including the path and filename extension. If you used the /t option with the Thunk Compiler to specify a different base name, you would use the new base name in your procedure. You could, for example, use following command line.

THUNK /t MYNAME SAMP.THK

The thunk compiler generates the MYNAME_ThunkConnect16 routine, which should then be called in the DllEntryPoint procedure.

2.	Add the following import and export statements to your 16-bit DLL's module definition (.DEF) file, picking ordinals that are appropriate for your DLL.

EXPORTS
DllEntryPoint       @1 RESIDENTNAME
SAMP_ThunkData16    @2
IMPORTS
C16ThkSL01     = KERNEL.631
ThunkConnect16 = KERNEL.651

3.	Add the following function to your 32-bit DLL's entrypoint procedure (named DllMain by default). Again, the names of the DLLs are for illustration only.

BOOL WINAPI SAMP_ThunkConnect32(LPSTR pszDll16, LPSTR pszDll32,
    DWORD hIinst, DWORD dwReason);
BOOL _stdcall DllMain(DWORD hInst, DWORD dwReason,
        DWORD dwReserved) {
    if (!(SAMP_ThunkConnect32("DLL16.DLL", // name of 16-bit DLL
            "DLL32.DLL",                   // name of 32-bit DLL
            hInst, dwReason))) {
        return FALSE;

    }

    // Process dwReason.
}

4.	Add the following export statement to your 32-bit DLL's .DEF file.

EXPORT
SAMP_ThunkData32

The following implementation rules are very important:

•	The 16-bit DllEntryPoint function is called each time the module's usage count is incremented or decremented. The dwReason parameter is 1 when the usage count is incremented and zero when it is decremented.

•	Because the system calls the DllEntryPoint function while loading is underway, the value returned by the GetModuleUsage function is not reliable if you call it inside your DllEntryPoint function.

•	Do not call thunks inside the DllEntryPoint routines. Do not perform operations that reenter the 16-bit loader, yield the 16-bit scheduler, or release the 16-bit subsystem. These actions could cause unpredictable results and are not guaranteed to work in future versions of the Thunk Compiler.

•	You can have multiple ThunkConnectXX calls, so long as they connect to the same DLL. In fact, this is the only way to get both 32- to 16-bit and 16- to 32-bit thunks in one thunk-paired DLL set. The procedure is to have a thunk script for each direction and link both into each DLL. Then each entrypoint function will have two ThunkConnect calls.


 Translating Pointers Outside Thunks

You may occasionally need to translate 16:16 pointers to 0:32 pointers outside of thunks. The GetVDMPointer32W, WOWGetVDMPointer, and WOWGetVDMPointerFix functions accomplish this. These functions are only required outside of thunks, because when pointers are thunked from 16 to 32 bits by the Thunk Compiler, no special handling is required to fix the segments. Because the Thunk Compiler fixes these segments automatically, 16:16 pointers can be passed to these thunks with no special treatment.

GetVDMPointer32W is a 16-bit function and is portable across Windows NT versions 3.1 and 3.5.

WOWGetVDMPointer is a 32-bit function and is portable across Windows NT version 3.5, but not Windows NT version 3.1.

WOWGetVDMPointerFix is a new 32-bit function. It is similar to WOWGetVDMPointer, but ensures that the memory pointed to will not be moved by the global memory compacter until WOWGetVDMPointerUnfix has been called. Using WOWGetVDMPointerFix and WOWGetVDMPointerUnfix is faster and easier than using WOWGetVDMPointer or GetVDMPointer32W.

If you use GetVDMPointer32W or WOWGetVDMPointer and the affected segment points to a movable global memory manager block, it is important to call the GlobalFix or GlobalWire function on the segment portion before computing its linear address. In Windows 95, the global memory compacter can break in at any time when your process is in 32-bit code. If this happens, the block may move and the linear address will become invalid. The debugging version of Windows 95 generates warnings about calls to GetVDMPointer32W on unfixed segments.

WOWGetVDMPointerFix converts a 16:16 pointer to a linear address like WOWGetVDMPointer. However, it also performs an implicit GlobalFix operation on the selector, if necessary. If the selector is allocated as a fixed block or if it is not from the global memory manager, no special action is taken. You should use this function instead of calling GlobalFix separately, because it is easier to implement and performance is better.

WOWGetVDMPointerUnfix takes a 16:16 address and undoes the effect of WOWGetVDMPointerFix on the segment (the offset portion is ignored). This function should be called once the linear address is no longer needed to avoid bottlenecks in the global memory manager. It is faster than the GlobalUnfix function and correctly handles (that is, ignores) selectors that are not from the global memory manager.

Note that the CallProc32W and CallProc32ExW functions do not call these functions for you. Pointers passed to these functions must be fixed manually.


 Late Loading

Windows 95 improves system performance by supporting late loading for thunk DLLs. Loading the 16-bit DLL does not cause the corresponding 32-bit DLL to load immediately. Instead, the thunk subsystem loads the 32-bit DLL when the first 16- to 32-bit thunk is started.

Late loading has the following implications:

•	The performance and working set are improved for 16-bit applications that use only the 16-bit portions of thunked DLLs. The 32-bit DLL will not load into those processes.

•	The 16-bit DLL must not depend on any action taken by the 32-bit DLL's initialization code until at least one 16- to 32-bit thunk has been called.

•	Missing 32-bit DLLs or failed 32-bit loads will not be detected until the first call is made to a 16- to 32-bit thunk. If the 32-bit DLL cannot load or fails to initialize, the 16- to 32-bit thunk call will return a value of zero. This error code may be changed on a thunk by thunk basis by including a faulterrorcode = dword; line between the curly braces of a function call. For example, the following function instructs the thunk subsytem to return a  − 1 from the thunk call if it is the first thunk call and the 32-bit DLL cannot finish loading.

int Sample(void) {
    faulterrorcode = -1;
}

Although late loading is a valuable optimization for a 16-bit DLL that can execute autonomously from its 32-bit partner, it does complicate error recovery. Late loading can be disabled by including the following line in the thunk script.

preload32 = true;

If you use this option, the 16-bit subsystem will be released during the loading of your 16-bit DLL, possibly causing other 16-bit code to be reentered. For this reason, the preload32 statement is not available if your thunk script requires the win31compat statement. For more information about the win31compat statement, see "Compatibility with Existing 16-Bit DLLs" earlier in this topic.

Although the thunk compiler supports a "preload16" keyword for future expansion, late loading of 16-bit DLLs is neither supported nor planned.


 Troubleshooting

This section outlines two common problems when thunking is implemented and describes their likely causes.

•	The 32-bit DLL will not load.

The Windows 95 loader requires that the 16-bit DLL be marked as subsystem version 4.0 or greater for the DllEntryPoint function to run. In addition, DllEntryPoint must be exported using the name "DllEntryPoint" and must be marked RESIDENTNAME.

To check the version number, run the Microsoft EXE File Header Utility (EXEHDR), using the following command line.

exehdr -v <your-16-bit-DLL>

The output should contain the following line.

Operating system: Microsoft Windows - version 4.0

If the subsystem version number is less than 4.0, you should use RC.EXE from the Win32 SDK to set the version of your 16-bit DLL correctly.

•	Loading the 16-bit DLL does not load the 32-bit DLL.

This is by design. A 32-bit DLL does not load into a process context until that process calls its first 16- to 32-bit thunk. For more information, see "Late Loading" earlier in this topic.

If this feature is incompatible with your DLL design, you may disable it by including the following line in your thunk script.

preload32 = true;


 Reference

The following functions are associated with the Thunk Compiler.


 16-bit WOW Functions

The functions in this section are 16-bit WOW API elements exported by KERNEL for use in generic thunks.


CallProc32W [New - Windows 95]
 CallProc32W

[New - Windows 95]

DWORD FAR PASCAL CallProc32W(DWORD param1, DWORD param2, ... ,
    LPVOID lpProcAddress32, DWORD fAddressConvert, DWORD nParams);

Used by a 16-bit thunk dynamic-link library (DLL) to call an entrypoint function in a 32-bit DLL.

•	Returns a 32-bit value if successful. This value is the return value from the 32-bit entrypoint function represented by lpProcAddress32. The return value can also be zero if lpProcAddress32 is zero or if nParams is greater than 32.

param1 through param32

Parameters for the 32-bit procedure represented by lpProcAddress32.

lpProcAddress32

32-bit value corresponding to the procedure to be called, which is returned by the GetProcAddress32 function.

fAddressConvert

Bit mask representing which parameters will be treated as 16:16 pointers and translated into flat linear pointers before being passed to the 32-bit procedure.

nParams

Number of DWORD parameters passed (not counting fAddressConvert and nParams). For functions that take no parameters, this parameter will be zero.

CallProc32W takes at least three parameters: lpProcAddress32, fAddressConvert, and nParams. In addition, it can take a maximum of 32 optional parameters. These parameters must be DWORD types and must match the type that the 32-bit thunk DLL is expecting. If the appropriate bit is set in the fAddressConvert mask, the parameter will be translated from a 16:16 pointer to a 32-bit flat linear pointer. Note that the lowest bit in the mask represents param1, the second lowest bit represents param2, and so on.

This function causes Windows 95 to release the 16-bit subsystem. If this function is used exclusively in 16-bit processes (as in Windows NT), there are no new reentrancy issues. Otherwise, the use of this function can cause 16-bit code to be reentered. For more information about reentrancy issues, see "Behavior of Win32 Functions Inside 16-Bit Processes" earlier in this topic.

Unlike the flat thunks, CallProc32W and CallProc32WEx do not automatically fix global memory handles that are translated to 0:32 pointers. Therefore, you must call the GlobalFix or GlobalWire function on the handle first. In Windows 95, global compaction can move memory blocks at any time while the current thread is executing 32-bit code. Because of this, certain pointer translation practices that worked in Windows NT may cause small, but undesirable, race conditions in Windows 95.

Note  You should be careful when using this function, because there is no compiler check made on the number and type of parameters, no conversion of types (all parameters are passed as DWORDs and are passed directly to the function called without conversion). No checks of the 16:16 address are made (limit checks, NULL checks, correct ring level, and so on).


CallProcEx32W [New - Windows 95]
 CallProcEx32W

[New - Windows 95]

DWORD FAR CallProcEx32W(DWORD nParams, DWORD fAddressConvert,
    DWORD lpProcAddress, DWORD param1, ...);

Used by a 16-bit thunk dynamic-link library (DLL) to call an entrypoint function in a 32-bit DLL.

•	Returns a 32-bit value if successful. This value is the return value from the 32-bit entrypoint function represented by lpProcAddress. The return value can also be zero if lpProcAddress is zero or if nParams is greater than 32.

nParams

Number of DWORD parameters passed (not counting fAddressConvert and nParams). For functions that take no parameters, this parameter will be zero.

fAddressConvert

Bit mask representing which parameters will be treated as 16:16 pointers and translated into flat linear pointers before being passed to the 32-bit procedure.

lpProcAddress

32-bit value corresponding to the procedure to be called, which is returned by the GetProcAddress32 function.

param1 through param32

Parameters for the 32-bit procedure represented by lpProcAddress

CallProcEx32W is similar to CallProc32W, but it uses the C calling convention to allow easier and more flexible prototyping.

This function causes Windows 95 to release the 16-bit subsystem. If this function is used exclusively in 16-bit processes (as in Windows NT), there are no new reentrancy issues. Otherwise, the use of this function can cause 16-bit code to be reentered. For more information about reentrancy issues, see "Behavior of Win32 Functions Inside 16-Bit Processes" earlier in this topic.

Unlike the flat thunks, CallProc32W and CallProc32WEx do not automatically fix global memory handles that are translated to 0:32 pointers. Therefore, you must call the GlobalFix or GlobalWire function on the handle first. In Windows 95, global compaction can move memory blocks at any time while the current thread is executing 32-bit code. Because of this, certain pointer translation practices that worked in Windows NT may cause small, but undesirable, race conditions in Windows 95.


FreeLibrary32W [New - Windows 95]
 FreeLibrary32W

[New - Windows 95]

BOOL FAR PASCAL FreeLibrary32W(DWORD hInst);

Allows a 16-bit thunk dynamic-link library (DLL) to free a 32-bit thunk DLL that it had previously loaded by using the LoadLibraryEx32W function.

•	Returns TRUE if successful or FALSE otherwise.

hInst

This function thunks to the Win32 FreeLibrary function. For a complete description of this parameter, see the documentation included in the Win32 SDK.

Note that WOW does not do any cleanup of 32-bit thunk DLLs when the WOW task exits. It is up to the 16-bit thunk DLLs to free the 32-bit thunk DLLs, as necessary.

This function causes Windows 95 to release the 16-bit subsystem. Therefore, your code may be reentered during the call to this function. However, if this function is only used in 16-bit processes (as in Windows NT) and none of the DLL's notification routines yield, this reentrancy will not occur.


GetProcAddress32W [New - Windows 95]
 GetProcAddress32W

[New - Windows 95]

DWORD FAR PASCAL GetProcAddress32W(DWORD hModule, LPCSTR lpszProc);

Allows a 16-bit thunk dynamic-link library (DLL) to retrieve a value that corresponds to a 32-bit thunk routine.

•	Returns a 32-bit value if successful. This value must be passed as a parameter to the CallProc32W or CallProcEx32W function rather than being used directly.

hModule through lpszProc

This function thunks to the Win32 GetProcAddress function. For a complete description of this parameter, see the documentation included in the Win32 SDK.

This function causes Windows 95 to release the 16-bit subsystem. Therefore, your code may be reentered during the call to this function. However, if this function is only used in 16-bit processes (as in Windows NT) and none of the DLL's notification routines yield, this reentrancy will not occur.


GetVDMPointer32W [New - Windows 95]
 GetVDMPointer32W

[New - Windows 95]

DWORD FAR PASCAL GetVDMPointer32W(LPVOID lpAddress, UINT fMode);

Allows a 16-bit thunk dynamic-link library (DLL) to translate a 16-bit far pointer into a 32-bit flat pointer for use by a 32-bit thunk DLL.

•	Returns a 32-bit linear address if successful or NULL otherwise.

lpAddress

Valid 16:16 address, either in protected or real mode.

fMode

One of the following flags:

1	The address is interpreted as a protected-mode address.
0	The address is interpreted as a real-mode address.
The WOW KERNEL memory manager moves segments in memory and keeps the selectors the same. However, if you get the linear address, it may not be valid if the memory manager has moved memory. You should assume that global compaction can occur any time that a 16- to 32-bit flat thunk or generic thunk is entered, a function is called, or the current task yields.


LoadLibraryEx32W [New - Windows 95]
 LoadLibraryEx32W

[New - Windows 95]

DWORD FAR PASCAL LoadLibraryEx32W(LPCSTR lpszLibFile, DWORD hFile,
    DWORD dwFlags);

Allows a 16-bit thunk dynamic-link library (DLL) to load a 32-bit thunk DLL.

•	Returns a 32-bit handle to a DLL instance if successful or NULL otherwise.

lpszLibFile through dwFlags

This function thunks to the Win32 LoadLibraryEx function. For a complete description of this parameter, see the documentation included in the Win32 SDK.

After calling this function, the 16-bit thunk DLL can call the GetProcAddress32W function to get the address of the 32-bit entrypoint function(s) and then call the thunk(s) by using the CallProc32W function.

This function causes Windows 95 to release the 16-bit subsystem. Therefore, your code may be reentered during the call to this function. However, if this function is only used in 16-bit processes (as in Windows NT) and none of the DLL's notification routines yield, this reentrancy will not occur.


 32-bit WOW Functions

The functions in this section are 32-bit WOW API elements exported by WOW32.DLL.


WOWCallback16 [New - Windows 95]
 WOWCallback16

[New - Windows 95]

DWORD WINAPI WOWCallback16(DWORD vpfn16, DWORD dwParam);

Used in 32-bit code called from 16-bit code (through generic thunks) to call back to the 16-bit side (generic callback).

•	The return value comes from the callback routine. If the callback routine returns a WORD types instead of a DWORD types, the upper 16 bits of the return value are undefined. If the callback routine has no return value, the entire return value of this function is undefined.

vpfn16

Pointer to 16-bit callback routine, which is passed from the 16-bit side.

dwParam

Parameter for the 16-bit callback routine.

This function will not work when called in a 32-bit process.

The 16-bit function to be called must be declared with one of the following types.

   LONG FAR PASCAL CallbackRoutine(DWORD dwParam);

   LONG FAR PASCAL CallbackRoutine(VOID FAR *vp);

The type used is determined by whether the parameter is a pointer.

If you are passing a pointer, you will need to get the pointer by using either the WOWGlobalAlloc16 or WOWGlobalAllocLock16 function.


WOWCallback16Ex [New - Windows 95]
 WOWCallback16Ex

[New - Windows 95]

BOOL WINAPI WOWCallback16Ex(DWORD vpfn16, DWORD dwFlags, DWORD cbArgs,
    PVOID pArgs, PDWORD pdwRetCode);

Used in 32-bit code called from 16-bit code (through generic thunks) to call back to the 16-bit side (generic callback).

•	If cbArgs is larger than the WCB16_MAX_ARGS bytes that the system supports, the return value is FALSE and the GetLastError function returns the ERROR_INVALID_PARAMETER value. Otherwise, the return value is TRUE and the DWORD pointed to by pdwRetCode contains the return code from the callback routine. If the callback routine returns a WORD types, the upper 16 bits of the return code are undefined and should be ignored by using LOWORD(dwRetCode).

vpfn16

Pointer to 16-bit callback routine, which is passed from the 16-bit side.

dwFlags

One of the following flags:

WCB16_CDECL	Calls a _cdecl callback routine.
WCB16_PASCAL	Calls a _pascal callback routine (default).
cbArgs

Count of bytes in arguments (used to properly clean the 16-bit stack).

pArgs

Arguments for the callback routine.

pdwRetCode

Return code from the callback routine.

This function will not work when called in a 32-bit process.

WOWCallback16Ex allows any combination of arguments up to WCB16_MAX_CBARGS bytes total to be passed to the 16-bit callback routine. Regardless of the value of cbArgs, WCB16_MAX_CBARGS bytes will always be copied from pArgs to the 16-bit stack. If pArgs is less than WCB16_MAX_CBARGS bytes from the end of a page and the next page is inaccessible, WOWCallback16Ex will incur an access violation.

The arguments pointed to by pArgs must be in the correct order for the callback routine's calling convention. For example, to call the Pascal routine SetWindowText, pArgs would point to an array of words.

LONG FAR PASCAL SetWindowText(HWND hwnd, LPCSTR lpsz);

WORD SetWindowTextArgs[] = {OFFSETOF(lpsz), SELECTOROF(lpsz), hwnd};

In other words, the arguments are placed in the array in reverse order, with the least significant word first for DWORD types and offset first for FAR pointers.

To call the _cdecl routine wsprintf, pArgs would also point to an array of words.

LPSTR lpszFormat = "%d %s";

int _cdecl wsprintf(lpsz, lpszFormat, nValue. lpszString);

WORD wsprintfArgs[] = {OFFSETOF(lpsz), SELECTOROF(lpsz),
    OFFSETOF(lpszFormat), SELECTOROF(lpszFormat), nValue,
    OFFSETOF(lpszString), SELECTOROF(lpszString)};

In other words, the arguments are placed in the array in the order listed in the function prototype with the least significant word first for DWORD types and offset first for FAR pointers.


WOWGetVDMPointer [New - Windows 95]
 WOWGetVDMPointer

[New - Windows 95]

LPVOID WINAPI WOWGetVDMPointer(DWORD vp, DWORD dwBytes,
    BOOL fProtectedMode);

Converts a 16:16 address to the equivalent flat address.

•	Returns a 32-bit address if successful. If the selector is invalid, the return value is NULL.

vp

Valid 16:16 address.

dwBytes

Size of the block pointed to by vp.

fProtectedMode

One of the following flags:

1	The upper 16 bits are treated as a selector in the local descriptor table.
0	The upper 16 bits are treated as a real-mode segment value.
Limit checking is performed only in the checked (debugging) build of WOW32.DLL, which will cause NULL to be returned when the limit is exceeded by the supplied offset.

This function should never be used on a 16-bit global memory handle selector that has not been previously fixed in memory by using the GlobalFix or GlobalWire function. You should assume that global compaction can occur at any time the 16-bit subsystem is not locked by the current thread.


WOWGetVDMPointerFix [New - Windows 95]
 WOWGetVDMPointerFix

[New - Windows 95]

LPVOID WINAPI WOWGetVDMPointerFix(DWORD vp, DWORD dwBytes,
    BOOL fProtectedMode);

Converts a 16:16 address to the equivalent flat address. Unlike the WOWGetVDMPointer function, this function calls the GlobalFix function before returning the flat address so that the 16-bit memory will not move around in linear space.

•	Returns a 32-bit address if successful. If the selector is invalid, the return value is NULL.

vp

Valid 16:16 address.

dwBytes

Size of the block pointed to by vp.

fProtectedMode

One of the following flags:

1	The upper 16 bits are treated as a selector in the local descriptor table.
0	The upper 16 bits are treated as a real-mode segment value.


WOWGetVDMPointerUnfix [New - Windows 95]
 WOWGetVDMPointerUnfix

[New - Windows 95]

VOID WINAPI WOWGetVDMPointerUnfix(DWORD vp);

Uses the GlobalUnfix function to unfix a pointer retrieved by the WOWGetVDMPointerFix function.

•	No return value.

vp

Address retrieved by the WOWGetVDMPointerFix function.


WOWGlobalAlloc16 [New - Windows 95]
 WOWGlobalAlloc16

[New - Windows 95]

WORD  WINAPI WOWGlobalAlloc16(WORD wFlags, DWORD cb);

Thunks to the 16-bit version of the function with the same name. For more information, see the documentation for the 16-bit versions.


WOWGlobalAllocLock16 [New - Windows 95]
 WOWGlobalAllocLock16

[New - Windows 95]

DWORD WINAPI WOWGlobalAllocLock16(WORD wFlags, DWORD cb, WORD *phMem);

Combines the functionality of the WOWGlobalAlloc16 and WOWGlobalLock16 functions, thunking to the 16-bit versions of the functions with those names. For more information, see the documentation for the 16-bit versions.


WOWGlobalFree16 [New - Windows 95]
 WOWGlobalFree16

[New - Windows 95]

WORD  WINAPI WOWGlobalFree16(WORD hMem);

Thunks to the 16-bit version of the function with the same name. For more information, see the documentation for the 16-bit versions.


WOWGlobalLock16 [New - Windows 95]
 WOWGlobalLock16

[New - Windows 95]

DWORD WINAPI WOWGlobalLock16(WORD hMem);

Thunks to the 16-bit version of the function with the same name. For more information, see the documentation for the 16-bit versions.


WOWGlobalLockSize16 [New - Windows 95]
 WOWGlobalLockSize16

[New - Windows 95]

DWORD WINAPI WOWGlobalLockSize16(WORD hMem, PDWORD pcb);

Combines the functionality of the WOWGlobalLock16 and GlobalSize functions, thunking to the 16-bit versions of the functions with those names. For more information, see the documentation for the 16-bit versions.


WOWGlobalUnlock16 [New - Windows 95]
 WOWGlobalUnlock16

[New - Windows 95]

BOOL  WINAPI WOWGlobalUnlock16(WORD hMem);

Thunks to the 16-bit version of the function with the same name. For more information, see the documentation for the 16-bit versions.


WOWGlobalUnlockFree16 [New - Windows 95]
 WOWGlobalUnlockFree16

[New - Windows 95]

WORD  WINAPI WOWGlobalUnlockFree16(DWORD vpMem);

Combines the functionality of the WOWGlobalUnlock16 and WOWGlobalFree16 functions, thunking to the 16-bit versions of the functions with those names. For more information, see the documentation for the 16-bit versions.


WOWHandle16 [New - Windows 95]
 WOWHandle16

[New - Windows 95]

WORD WINAPI WOWHandle16(HANDLE, WOW_HANDLE_TYPE);

This function (and the associated macro) is used to map a 32-bit handle to a 16-bit handle. Because the relationship between a Win16 handle and a Win32 handle may change in the future, this function should be used instead of any private knowledge of the relationship between them.

This function uses the WOW_HANDLE_TYPE parameter to indicate the type of handle being translated. Types supported include HWND, HMENU, HDWP, HDROP, HDC, HFONT, HMETAFILE, HRGN, HBITMAP, HBRUSH, HPALETTE, HPEN, HACCEL, HTASK, and FULLHWND.

The WOW_HANDLE_TYPE name corresponding to each of these types is of the form WOW_TYPE_handle (for example, WOW_TYPE_HWND).

You can use macros to map handles between Win16 and Win32. For example, to map a Win16 HWND to a Win32 HWND, you would use the HWND_32 macro.

(hWnd32 = HWND_32(hWnd16))

A "full" hWnd is a hWnd that a Win32-based application would see (and therefore can be used in comparisons with 32-bit hWnds received from Win32 functions.) The other hWnd type has a different value, but is recognized by the system. Do not make assumptions about the relationship between the 16-bit hWnd, the 32-bit Hwnd, and the 32-bit Full hWnd. This relationship has changed in the past (for performance reasons), and it may change again in the future.


WOWHandle32 [New - Windows 95]
 WOWHandle32

[New - Windows 95]

HANDLE WINAPI WOWHandle32(WORD, WOW_HANDLE_TYPE);

This function (and the associated macro) is used to map a 16-bit handle to a 32-bit handle. Because the relationship between a Win16 handle and a Win32 handle may change in the future, this function should be used instead of any private knowledge of the relationship between them.

This function uses the WOW_HANDLE_TYPE parameter to indicate the type of handle being translated. Types supported include HWND, HMENU, HDWP, HDROP, HDC, HFONT, HMETAFILE, HRGN, HBITMAP, HBRUSH, HPALETTE, HPEN, HACCEL, HTASK, and FULLHWND.

The WOW_HANDLE_TYPE name corresponding to each of these types is of the form WOW_TYPE_handle (for example, WOW_TYPE_HWND).

You can use macros to map handles between Win16 and Win32. For example, to map a Win16 HWND to a Win32 HWND, you would use the HWND_32 macro.

(hWnd32 = HWND_32(hWnd16))

A "full" hWnd is a hWnd that a Win32-based application would see (and therefore can be used in comparisons with 32-bit hWnds received from Win32 functions.) The other hWnd type has a different value, but is recognized by the system. Do not make assumptions about the relationship between the 16-bit hWnd, the 32-bit Hwnd, and the 32-bit Full hWnd. This relationship has changed in the past (for performance reasons), and it may change again in the future.


accessor function

A function that sets or retrieves the value of a property. Most properties have a pair of accessor functions; properties that are read-only may have only one accessor function.


Application object

The top-level object in an application's object hierarchy. The Application object identifies the application to the system and typically becomes active when the application starts. Specified by the appobj attribute in the type library.


class identifier (CLSID)

A UUID that identifies an OLE object. An object registers its CLSID in the system registration database so that it can be loaded and programmed by other applications.


class factory

An object that implements the IClassFactory interface, which allows it to create other objects of a specific class.


coclass

Component object model class; a top-level object in the object hierarchy.


collection object

A grouping of exposed objects. A collection object enables you to address multiple occurrences of an object as a unit, for example, to draw a set of points.


component object

A Windows object identified by a unique class identifier (CLSID), which associates the object with a DLL or an .EXE file.


compound document

A document that contains data of different formats, such as sound clips, spreadsheets, text, and bitmaps, created by different applications. Compound documents are stored by container applications.


container application

An application that provides storage, a display site, and access to a compound document object.


Dispatch identifier (DISPID)

The number by which a member function, parameter, or data member of an object is known internally to IDispatch.


dispinterface

An IDispatch interface that responds only to a certain fixed set of names. The properties and methods of the dispinterface are not in the virtual function table (VTBL) for the object.


dual interface

An interface that supports both IDispatch and VTBL binding.


event

An action recognized by an object, such as clicking the mouse or pressing a key, and for which you can write code to respond. In OLE Automation, an event is a method that is called, rather than implemented, by an OLE Automation object.


event sink

A function that handles events. The code associated with a Visual Basic form, which contains event handlers for one or more controls, is an event sink.


event source

A control that experiences events and calls an event handler to dispose of them.


exposed object

See OLE Automation object.


HRESULT

A value returned from a function call to an interface, consisting of a severity code, context information, a facility code, and a status code that describes the result. For 16-bit Windows systems, the HRESULT is an opaque result handle defined to be zero for a successful return from a function, and nonzero if error or status information is to be returned. To convert an HRESULT into the more detailed SCODE, applications call GetSCode(). See SCODE.


ID binding

The ability to bind member names to DISPIDs at compile time, for example, by obtaining the IDs from a type library. This approach eliminates the need for calls to IDispatch::GetIDsOfNames and results in improved performance over late-bound calls. See also late binding.


in-place activation

The ability to activate an object from within an OLE control and to associate a verb with that activation (for example, edit, play, change). Sometimes referred to as in-place editing or visual editing.


in-process server

An object application that runs in the same process space as the OLE Automation controller.


interface

One or more well-defined base classes providing member functions that, when implemented in an application, provide a specific service. Interfaces may include compiled support functions to simplify their implementation.


late binding

The ability to bind names to IDs at run time, rather than compile time.


local server

An object application implemented in an .EXE file that  runs in a separate process space from the OLE Automation controller.


locale identifier (LCID)

A 32-bit value that identifies the human language preferred by a user, region, or application.


marshaling

The process of packaging and sending interface parameters across process boundaries.


member function

One of a group of related functions that make up an interface. See also method and property.


method

Member functions of an exposed object that perform some action on the object, such as saving it to disk.


multiple-document interface (MDI) application

An application that can support multiple documents from one application instance.  MDI object applications can simultaneously service a user and one or more embedding containers. See also single-document interface (SDI) application.


object

A unit of information that resides in a compound document and whose behavior is constant no matter where it is located or used.


Object Description Language (ODL)

A scripting language used to describe exposed libraries, objects, types, and interfaces. ODL scripts are compiled into type libraries by the MkTypLib tool.


OLE

An acronym for Object Linking and Embedding.


OLE Automation

A technology that provides a way to manipulate objects defined by an application or library from outside the application. OLE Automation enables programmability.


OLE Automation controller

An application, programming tool, or scripting language that accesses OLE Automation objects. Visual Basic is an OLE Automation controller.


OLE Automation object

An instance of a class defined within an application that is exposed for access by other applications or programming tools by means of OLE Automation interfaces.


OLE Automation server

An application, type library, or other source that makes OLE Automation objects available for programming by other applications, programming tools, or scripting languages.


programmable object


See OLE Automation object. property

A data member of an exposed object. Properties are set or returned by means of get and put accessor functions.


proxy

An interface-specific object that packages parameters for that interface in preparation for a remote method call. A proxy runs in the address space of the sender and communicates with a corresponding stub in the receiver's address space. See also stub, marshaling, and unmarshaling.


safe array

An array that contains information about the number of dimensions and the bounds of its dimensions. Safe arrays are passed by IDispatch::Invoke within VARIANTARGs. Their base type is VT_tag | VT_ARRAY.


SCODE

A DWORD value that is used to pass detailed information to the caller of an interface member or API function. The status codes for OLE interfaces and API's are defined in FACILITY_ITF. See HRESULT.


single-document interface (SDI) application

An application that can support only one document at a time. Multiple instances of an SDI application must be started to service both an embedded object and a user. See also multiple-document interface (MDI) application.


stub

An interface-specific object that unpackages the parameters for that interface after they are marshaled across the process boundary, and makes the requested method call. The stub runs in the address space of the receiver and communicates with a corresponding proxy in the sender's address space. See proxy, marshaling, and unmarshaling.


type description

The information used to build the type information for one or more aspects of an application's interface. Type descriptions are written in Object Description Language (ODL) and include both programmable and nonprogrammable interfaces.


type information

Information that describes the interfaces of an application. Type information is created from type descriptions using OLE Automation tools, such as MkTypLib or the CreateDispTypeInfo function. Type information may be accessed through the ITypeInfo interface.


type information element

A unit of information identified by one of these statements in a type description: typedef, enum, struct, module, interface, dispinterface, or coclass.


type library

A file or component within another file that contains type information. Type libraries are created from type descriptions using MkTypLib, and may be accessed through the ITypeLib interface.


unmarshaling

The process of unpackaging parameter that have been sent across process boundaries.


Value property

The property that defines the default behavior of an object when no other methods or properties are specified. You indicate the Value property by specifying the default attribute in ODL.


virtual function table (VTBL)

A table of function pointers, such as an implementation of a class in C++. The pointers in the VTBL point to the members of the interfaces that an object supports.


  Legal Information

Information in this online help system is subject to change without notice and does not represent a commitment on the part of Microsoft Corporation. The software and/or files described in this online help system are furnished under a license agreement or nondisclosure agreement. The software and/or files may be used or copied only in accordance with the terms of the agreement. The purchaser may make one copy of the software for backup purposes. No part of this online help system may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or information and retrieval systems, for any purpose other than the purchaser's personal use, without the written permission of Microsoft Corporation.

Microsoft may have patents or pending patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document. The furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property rights except as expressly provided in any written license agreement from Microsoft.

Copyright © 1992-1995 Microsoft Corporation. All rights reserved.

Microsoft, MS, MS-DOS, Win32, Win32s, and Windows are registered trademarks, and Windows NT is a trademark of Microsoft Corporation.

Portions of this documentation are provided under license from Digital Equipment Corporation. Copyright © 1990, 1992 Digital Equipment Corporation. All rights reserved.

DEC, DECnet and PATHWORKS are trademarks of Digital Equipment Corporation.


Activation

The process of binding an object in order to put it into its running state. Also refers to invoking a particular operation on an object. See also Binding.


Absolute moniker

A moniker that specifies the absolute location of an object. An absolute moniker is analogous to a full pathname. See also Moniker.


Advisory sink

An object that can receive notifications of changes in an embedded object or linked object because it implements the IAdviseSink interface (and possibly the IAdviseSink2 interface). Notifications originate in the object application, where they are cached in an advise holder, which passes them to advisory sinks implemented by object handlers. For an embedded object, the corresponding object handler forwards the notification to the object's container. For a linked object, the object handler forwards the notification to the link object, which in turn passes it on to the container. See also Object handler, Embedded object, Link object, Linked object, Container application.


Aggregate object

A component object that is made up of one or more other component objects. One object in the aggregate is designated the control object, which controls which interfaces in the aggregate are exposed and which are private. The control object has a special implementation of IUnknown called the controlling unknown. All non-controlling objects in the aggregate must pass calls to IUnknown methods through the controlling unknown.


Aggregation

A composition technique for implementing component objects. It allows you to build a new object with one or more existing objects that support some or all of the new object's required interfaces.


Anti-moniker

The inverse of a file, item, or pointer moniker. An anti-moniker is added to the end of a file-, item-, or pointer moniker to nullify it. This is analogous to the way that ".." nullifies a directory component of a pathname (that is, \work\art\.. equals \work). Anti-monikers are used in the construction of relative monikers. See also Relative Moniker.


Artificial reference counting

A technique used to safeguard an object before making a call that could result in its premature destruction by ensuring it won't be de-allocated. A process calls the AddRef method of IUnknown to increment the count before making the call that could otherwise free the object prematurely, and after the function returns, calls the IUnknown::Release method to decrement the count.


Asynchronous call

A function that allows the next instruction in the process to be executed as soon as the call is made, without waiting for the function to return. Most OLE functions and interface methods are synchronous; that is, the function must return before the next instruction is executed. OLE defines six asynchronous methods, five within the IAdviseSink interface—OnDataChange, OnViewChange, OnRename, OnSave, and OnClose—and one within the IAdviseSink2 interface—OnLinkSourceChange.


Automation

See OLE Automation


Bind context

An object that implements the IBindCtx interface. Bind contexts are used in moniker operations. A bind context holds references to the objects activated when a moniker is bound, contains parameters that apply to all operations during the binding of a generic composite moniker, and provides the means by which the moniker implementation should retrieve information about its environment. See Binding, Moniker.


Binding

Generically, binding is the process of associating a name to its referent. When referring to monikers specifically, binding is the process of locating the object named by the moniker, activating it (loading it in memory) if it isn't already, and returning an interface pointer to it. Binding puts an object into its running state, allowing the operations it supports to be invoked. Objects can be bound at run time (also called late binding or dynamic binding) or at compile time (also called static binding). In OLE Automation, vtable-based binding is referred to as "early binding" and IDispatch-based binding is referred to as "late binding."


Cache

Generally, a cache is a (usually temporary) local store of information. In OLE, the term cache is used in connection with linked or embedded objects, in which the cache contains information that defines the presentation of a contained object when the container is opened.


Cache initialization

The process of filling an embedded object's cache with data formats. The IOleCache interface provides methods that a container object can call to control the data that gets cached for embedded objects.. The IOleCache::InitCache method fills the cache using data provided by a transfer from the Clipboard or from a drag-and-drop operation. The IOleCache::SetData method fills the cache using data in a storage object.


Class

In object-oriented programming, a class is a set of objects whose behavior is defined by the same set of code (they share the same implementation).
A COM class is not necessarily the same as a class in an object-oriented language. A COM class can be identified by a CLSID, though for most COM operations, it is not necessary to know an object's class.


Class factory

A object that you use to create one or more instances of a an object identified by a given CLSID (class identifier). A class factory object implements the IClassFactory interface. A class factory is the most frequently used type of class object in OLE. See also CLSID.


Class identifier (CLSID)

A unique identification tag (UUID) associated with an OLE class object. A class object that is intended to create more than one object registers its CLSID in a task table in the registration database to enable clients to locate and load the executable code associated with the object(s). Every OLE object application (or container that allows linking to its embedded objects) must register a CLSID for each supported object definition.


Class object

In COM, class objects are called class factories, and typically have no behavior except to create new instances of the class. In object-oriented programming, an object whose state is shared by all the objects in a class, and whose behavior acts on that class-wide state data. See also Class factory.


Client

In referring to OLE objects, an object that requests services from another object. See also Container.


Client site

The display site for an embedded or linked object within a compound document. The client site is the principal means by which an object requests services from its container.


CLSID

See Class identifier


Component object

An object that conforms to the OLE component object model (COM) Clients deal with a component object only through a pointer to an interface (a related set of functions called methods). With the pointer, clients can call the methods that perform operations or manipulate the data associated with the object. Component objects are instances of an object definition, which specifies an implementation of the interfaces on the object.


Composite moniker

A moniker that consists of two or more monikers composed together. A composite moniker can be non-generic, meaning that its component monikers have special knowledge of each other, or generic, meaning that its component monikers know nothing about each other except that they are monikers. See Generic composite moniker.


Commit

The act of persistently saving any changes made to an object since its storage was opened or since the last time changes were saved. See also Revert.


Component object model (COM)

The OLE object-oriented programming model that defines how objects interact within a single application or between applications. In COM, clients have access to an OLE object through a pointer to an interface (a related set of functions called methods) on the object.


Composite menu

A shared menu bar composed of menu groups from both an in-place container and an in-place object application. The object application must install and remove the menu from the container's frame window.


Compound document

A document that contains data of different formats, created by different applications. Compound documents are created in a container application, such as Word, and information from other applications (such as spreadsheets, sound clips, and bitmaps) is either embedded in or linked to the container application. When the compound document is saved, the container application saves it.


Compound file

An OLE-provided implementation of structured storage which includes the IStorage, the IStream, and the ILockBytes interfaces. You use a set of StgXxx API functions to create and use a compound file.


Container

See Container application.


Container application

An application that supports compound documents. Container applications provide storage for the object, a site for display, access to the display site, and an advisory sink for receiving notifications of changes in the object. See also Compound document, Client site, and Advisory sink.


Container/Object

An application that has implemented OLE interfaces such that the application supports the features and capabilities of both a container and object application.


Container/Server

See Container/Object.


Control object

The object within an Aggregate object that controls which interfaces within the aggregate object are exposed and which are private.. The control object has a special implementation of IUnknown called the controlling unknown, and all other objects in the aggregate must pass calls to IUnknown methods through the controlling unknown. See Aggregate object.


Data transfer object

An object that supports the IDataObject interface and contains data to be transferred from one object to another either through the Clipboard or drag-and-drop operations.


Default object handler

A DLL provided with the OLE SDK that provides a partial implementation of basic interfaces. It is a surrogate in the processing space of the container application for the real object.

With the default object handler, it is possible to look at an object's stored data without actually activating the object. The default object handler performs other tasks on behalf of a loaded object, such as rendering an object from its cached state when the object is loaded into memory.


Direct access mode

One of two access modes in which a storage object can be opened. In direct mode, all changes are immediately committed to the root storage object. See also Transacted access mode.


Drag and drop

OLE specifies a set of data transfer and drag-and drop-interface-specific interfaces that allow applications to implement drag and drop, an operation in which the end-user uses the mouse or other pointing device to drag data from one window and drop it into another location in the same window or into another window.


Embedded object

A compound-document object that is stored with the container application, but when it is running, lives in the process space of the server application, which creates and subsequently edits it. The default handler provides a surrogate in the processing space of the container application for the real object.


Explicit caching

One of two ways an object can cache its presentation data. Explicit caching requires the physical creation of the cache nodes needed to save the data formats of the object. See also Implicit caching.


File moniker

A moniker based on a path in the file system. File monikers can be used to identify objects that are saved in their own files. A file moniker is an object that represents an implementation of the IMoniker interface for the file class. See also Item moniker and Generic composite moniker.


Global memory

See Shared application memory.


Generic composite moniker

The generic composite moniker is a sequenced collection of other types of monikers, starting with a file moniker to provide the document-level path and continuing with one or more item monikers. See also Item moniker and File moniker.


Handler

See Object handler.


Helper function

A function that encapsulates other functions and interface methods publicly available in the OLE SDK.


HRESULT

An opaque result handle defined to be zero for a successful return from a function and non-zero if error or status information is to be returned. To convert an HRESULT into the more detailed SCODE, applications call GetScode(). See SCODE.


Implicit caching

The "implied" caching of presentation data by an object that is capable of rendering itself using its native data. Cache nodes are not created with implicit caching. See also Explicit caching.


In parameter

A parameter that is allocated, set, and freed by the caller of a function.


In/Out parameter

A parameter that is initially allocated by the caller of a function and set, freed, and reallocated if necessary by that which is called.


In-process server

An object server or application implemented as a DLL that runs in the process space of the object's container. See also Local server, Remote server.


Instance

An object for which memory is allocated or which is persistent.


Instantiate

The process of creating an activating an obnect based on its definition.


Interface

A group of related functions that provide access to OLE objects. The set of OLE interfaces define a contract that allow objects to interact according to the Component Object Model (COM). While OLE provides many interface implementations, most interfaces can also be implemented by developers designing OLE applications.


Interface identifier (IID)

A unique identification tag associated with each interface. Some functions take IIDs as parameters to allow the callers to specify what type of interface pointer should be returned.


Item moniker

A moniker based on a string that identifies an object in a container. Item monikers can be used to identify objects smaller than a file, including embedded objects in a compound document, or a pseudo-object (like a range of cells in a spreadsheet). See also File moniker and Generic composite moniker.


Link object

A component object that is instantiated when a linked compound document object is created or loaded. The link object implements the IOleLink interface and is provided by OLE.


Linked object

A compound-document object whose source data physically resides where it was initially created. Only a moniker that represents the source data and the appropriate presentation data is kept with the compound document. Changes made to the link source are automatically reflected in the linked compound-document object in the container(s).


Link source

The data that is the source of a linked compound document object. A link source may be a file or a portion of a file, such as an embedded object or a selected range within a file (also called a pseudo object).


Loaded state

The state of a compound-document object after its data structures have been loaded into container memory. The data structures are created by the object handler. See also Passive state and Running state.


Local server

An server application implemented as an EXE running on the same machine as the client application using it. Because the server application is an EXE, it runs in its own process. See also In-Process server and Remote server.


Lock

OLE defines two types of locks that can be held on an object: strong and weak. A strong lock will keep an object in memory, a weak lock will not.


LRPC (Lightweight remote procedure call)

OLE's RPC-based protocol for interprocess communication. LRPC is "lightweight" in that it handles communication between processes on one machine only.


Marshaling

The process of packaging and sending interface parameters across process boundaries.


Moniker

An object that implements the IMoniker interface. A moniker acts as a name that uniquely identifies a COM object. You can think of a moniker as a generalization of a pathname; in the same way that a pathname identifies a file in the file system, a moniker identifies a COM object. Monikers support an operation known as "binding," which is the process of locating the object named by the moniker, activating it (loading it in memory) if it isn't already, and returning an interface pointer to it.


Moniker class

An implementation of the IMoniker interface. System-supplied moniker classes include file monikers, item monikers, generic composite monikers, anti-monikers, and pointer monikers.


Moniker client

An application that uses monikers to acquire interface pointers to objects managed by another application.


Moniker provider

An application that hands out monikers that identify  the objects it manages, so that they are accessible to other applications.


Multiple Document Interface (MDI) Application

An application that can support multiple documents from one application instance. MDI object applications can simultaneously serve a user and one or more embedding containers. See also Single Document Interface (SDI) application.


Native data

The data used by an OLE server application when editing an embedded object. See also Presentation data.


Nested object

An OLE object that is embedded within another OLE object through the use of a combination container/server application. OLE objects can be arbitrarily nested to any level.


Object

Generally, an instance of an entity that embodies both specific data and the functions that manipulate it.
Specifically in object-oriented programming, an object is an entity that has state, behavior and identity. An object's state consists of its attributes and and the attributes' current values. An object's behavior consists of the operations that can be performed on it and the accompanying state changes. An object's identity is what you use to distinguish it from other objects.
In contrast, COM objects' behavior is defined by the interfaces it supports. A COM object's state is not explicitly specified, but is implied by its interfaces. A COM object's identity is defined by the ability to use IUnknown::QueryInterface to move between interfaces.
A COM object follows a specific model in which clients (those using an object's services) gain access to the object's data only through a pointer to an interface consisting of a set of methods (related functions). The client can then call these methods to perform desired operations. There is no direct access to an OLE object's data.


Object application

An OLE-aware application that can create compound document objects. Containers can then embed or link to these objects.


Object handler

A piece of class-specific code that is dynamically loaded into the address space of its container. Object handlers process requests for specific classes of objects, so that much of the communication can be in-process. This is more efficient because it reduces the need for remote procedure calls.


Object state

One of three relationships between a compound document object in its container and the application responsible for the object's creation: passive, loaded, and running. Passive objects are stored (on disk or in a database), and the object is not selected or active. In the loaded state, its data structures have been loaded into memory, but is not yet available for operations such as editing. Running objects are both loaded and available for all operations.


Object type name

A unique identification string that is stored as part of the information available for an object in the registration database—for example, Acme Drawing.


OLE Automation

A way to manipulate an application's objects from outside the application. OLE automation is typically used to create applications that expose objects to programming tools and macro languages, create and manipulate one application's objects from another applications, or to create tools for accessing and manipulating objects. For information on OLE Automation, refer to the OLE Programmer's Reference, Volume 2.


Out parameter

A function parameter that is allocated and set by whatever a function calls, and must be freed by the caller.


Passive state

The state of an OLE object when it is stored (on disk or in a database). The object is not selected or active. See also Loaded state and Running state.


Persistent storage

Storage of a file or object in a medium such as a file system or database so that the file can be closed and then re-opened at a later time. Data can be retrieved from the file until the underlying file is deleted.


Pointer moniker

A moniker that wraps an interface pointer to an object in memory. Whereas most monikers identify objects that can be saved to persistent storage, pointer monikers identify objects that cannot. They allow such objects to participate in a moniker binding operation.


Presentation data

The data used by an OLE container applicationto display embedded or linked objects. See also Native data.


Primary verb

The action associated with the most common, preferred operation users perform on an object; the primary verb is always defined as verb zero in the system registration database. An object's primary verb is executed by double-clicking on the object.


Proxy

An interface-specific object that packages parameters for that interface in preparation for a remote method call. A proxy runs in the address space of the sender and communicates with a corresponding stub in the receiver's address space. See also Stub, Marshaling, and Unmarshaling.


Proxy manager

Manages all the proxies for a single object.


Pseudo object

A selection of data within a document or embedded object that can be the source for a compound-document object.


Reference counting

Keeping a count of each interface pointer instance to ensure that an object is not destroyed before all references to it are released.


Relative moniker

A moniker that specifies the location of an object  relative to the location of another object. A relative moniker is analogous to a relative pathname (such as "..\backup\report.old").


Remote Server

A server application, implemented as an EXE, running on a different machine from the client application using it. See also In-process server, Local server.l


Revert

The act of discarding any change(s) made to an object since the last time the changes were committed or the object's storage was opened. See also Commit, Transacted access mode


Root IStorage object

The outermost IStorage instance in a document; also called the root storage object. Compound-document objects are always saved as children of a root IStorage object.


Running state

The state of an OLE object when the object application is running and it is possible to edit the object, access its interfaces, and receive notification of changes. See also Loaded state and Passive state.


Running object table (ROT)

A globally-accessible table on each machine that  keeps track of all the OLE objects that can be identified by a moniker and are currently running on the machine. Monikers use the Running Object Table. Registering an object in the running object table increments the object's reference count. Before the object can be destroyed, its moniker must be released from the running object table.


SCODE

A DWORD value that is used to pass detailed information to the caller of an interface method or function. See also HRESULT.


Server

See object application.


Shared application memory

Memory that is primarily used between processes to optimize the data copying that occurs in LPRC calls.


Single Document Interface (SDI) Application

An application that can support only one document at a time. Multiple instances of an SDI application must be started to service both an embedded object and a user. See also Multiple Document Interface (MDI) application.


Single object application

An application that is capable of creating and manipulating one class of object. See also Multiple object application.


Stand-alone object application

An object application implemented as an executable (EXE) program, rather than as a DLL object application.


State

See Loaded state, Passive state, and Running state.


Static object

An object that contains only a presentation, with no native data. A container application can treat a static object as though it were a linked or embedded object, except that it is not possible to edit a static object.
A static object can result, for example, from the breaking of a link on a linked object; you don't want the linked object to be updated anymore.


Storage object

An object that implements the IStorage interface. A storage object contains nested storage objects or stream objects, resulting in a directory/file system within a single file. It provides the underlying storage for compound documents. Container applications provide a nested storage object for each of their embedded objects. The embedded object stores its data nested storage and stream objects within the storage object provided by its container. See also Root IStorage object and Stream object.


Stream object

An object that implements the IStream interface. A stream object is analogous to a file in a directory/file system. See also Storage object.


Structured storage model

A specification that defines a hierarchical method of storing objects. OLE provides an implementation of the structured storage model called Compound Files. See Compound file.


Stub

When a function's or interface method's parameters are marshaled across a process boundary, the stub is an interface-specific object that unpackages the marshaled parameters and calls the required method. The stub runs in the receiver's address space and communicates with a corresponding proxy in the sender's address space. See Proxy, Marshaling, and Unmarshaling.


Stub manager

Manages all of the stubs for a single object.


Synchronous call

A function that does not allow further instructions in the process to be executed until the function returns. Most OLE interface methods, except some of the IAdviseSink methods, are synchronous calls. See also Asychronous call.


Transacted access mode

One of two access modes in which a storage object can be opened. When opened in transacted mode, changes are stored in temporary buffers until the root IStorage object commits its changes. See also Direct access mode, Commit, Revert.


Uniform data transfer

A model for transferring data via the Clipboard, drag and drop, or through automation. Objects conforming to the model implement the IDataObject interface. This model replaces DDE (dynamic data exchange). See Data transfer object.


Unmarshaling

The processing of unpackaging parameters that have been sent across process boundaries.


Virtual Table (VTBL)

An array of pointers that point to interface method implementations.


Visual Editing

A term in end-user documents that refers to the user's ability to interact with a compound-document object in the context of its container. The term most often used by developers is in-place activation. See also In-place activation.


AbortProc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user-defined
Header File	wingdi.h
Unicode	No
Platform Notes	None


acmDriverEnumCallback
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user-defined
Header File	msacm.h
Unicode	No
Platform Notes	None


acmDriverProc
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user-defined
Header File	msacm.h
Unicode	No
Platform Notes	None


acmFilterChooseHookProc
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user-defined
Header File	msacm.h
Unicode	WinNT
Platform Notes	None


acmFilterEnumCallback
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user-defined
Header File	msacm.h
Unicode	WinNT
Platform Notes	None


acmFilterTagEnumCallback
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user-defined
Header File	msacm.h
Unicode	WinNT
Platform Notes	None


acmFormatChooseHookProc
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user-defined
Header File	msacm.h
Unicode	WinNT
Platform Notes	None


acmFormatEnumCallback
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user-defined
Header File	msacm.h
Unicode	WinNT
Platform Notes	None


acmFormatTagEnumCallback
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user-defined
Header File	msacm.h
Unicode	WinNT
Platform Notes	None


acmStreamConvertCallback
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user-defined
Header File
Unicode
Platform Notes	None


AddPropSheetPageProc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user-defined
Header File	prsht.h
Unicode
Platform Notes	None


BrowseCallbackProc
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


CallWndProc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user-defined
Header File	winuser.h
Unicode	No
Platform Notes	None


CallWndRetProc
Windows NT	No
Win95	Yes
Win32s	No
Import Library	user-defined
Header File	winuser.h
Unicode
Platform Notes	None


CBTProc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user-defined
Header File	winuser.h
Unicode	No
Platform Notes	None


CplApplet
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user-defined
Header File	cpl.h
Unicode	No
Platform Notes	None


DdeCallback
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user-defined
Header File	ddeml.h
Unicode	No
Platform Notes	None


DebugProc
Windows NT	Yes
Win95	No
Win32s	No
Import Library	user-defined
Header File	winuser.h
Unicode
Platform Notes	None


DialogProc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user-defined
Header File	winuser.h
Unicode	No
Platform Notes	None


DrawStateProc
Windows NT	No
Win95	Yes
Win32s	No
Import Library	user-defined
Header File	winuser.h
Unicode
Platform Notes	None


DriverProc
Windows NT	No
Win95	Yes
Win32s	No
Import Library	user-defined
Header File	mmsystem.h
Unicode
Platform Notes	None


EditWordBreakProc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user-defined
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


EditWordBreakProcEx
Windows NT	No
Win95	Yes
Win32s	No
Import Library	user-defined
Header File	richedit.h
Unicode
Platform Notes	None


EnhMetaFileProc
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user-defined
Header File	wingdi.h
Unicode	No
Platform Notes	None


EnumCalendarInfoProc
Windows NT	New
Win95	No
Win32s	New
Import Library	user-defined
Header File	winnls.h
Unicode	WinNT
Platform Notes	None


EnumChildProc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user-defined
Header File	winuser.h
Unicode	No
Platform Notes	None


EnumCodePagesProc
Windows NT	New
Win95	No
Win32s	New
Import Library	user-defined
Header File	winnls.h
Unicode	WinNT
Platform Notes	None


EnumDateFormatsProc
Windows NT	New
Win95	No
Win32s	New
Import Library	user-defined
Header File	winnls.h
Unicode	WinNT
Platform Notes	None


EnumDesktopProc
Windows NT	Yes
Win95	No
Win32s	No
Import Library	user-defined
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


EnumFontFamExProc
Windows NT	No
Win95	Yes
Win32s	No
Import Library	user-defined
Header File	wingdi.h
Unicode
Platform Notes	None


EnumFontFamProc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user-defined
Header File	wingdi.h
Unicode	No
Platform Notes	None


EnumFontsProc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user-defined
Header File	wingdi.h
Unicode	No
Platform Notes	None


EnumICMProfilesProc
Windows NT	No
Win95	Yes
Win32s	No
Import Library	user-defined
Header File	wingdi.h
Unicode	WinNT
Platform Notes	None


EnumLocalesProc
Windows NT	New
Win95	No
Win32s	New
Import Library	user-defined
Header File	winnls.h
Unicode	WinNT
Platform Notes	None


EnumMetaFileProc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user-defined
Header File	wingdi.h
Unicode	No
Platform Notes	None


EnumObjectsProc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user-defined
Header File	wingdi.h
Unicode	No
Platform Notes	None


EnumRegisterWordProc
Windows NT	No
Win95	Yes
Win32s	No
Import Library	user-defined
Header File	imm.h
Unicode	No
Platform Notes	None


EnumResLangProc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user-defined
Header File	winbase.h
Unicode	No
Platform Notes	None


EnumResNameProc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user-defined
Header File	winbase.h
Unicode	No
Platform Notes	None


EnumResTypeProc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user-defined
Header File	winbase.h
Unicode	No
Platform Notes	None


EnumThreadWndProc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user-defined
Header File	winuser.h
Unicode	No
Platform Notes	None


EnumTimeFormatsProc
Windows NT	New
Win95	No
Win32s	New
Import Library	user-defined
Header File	winnls.h
Unicode	WinNT
Platform Notes	None


EnumWindowsProc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user-defined
Header File	winuser.h
Unicode	No
Platform Notes	None


EnumWindowStationProc
Windows NT	New
Win95	No
Win32s	No
Import Library	user-defined
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


ExtensionPropSheetPageProc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user-defined
Header File	prsht.h
Unicode	No
Platform Notes	None


FileIOCompletionRoutine
Windows NT	Yes
Win95	No
Win32s	No
Import Library	user-defined
Header File	winbase.h
Unicode
Platform Notes	None


FMExtensionProc
Windows NT	Yes
Win95	No
Win32s	No
Import Library	user-defined
Header File	wfext.h
Unicode	WinNT
Platform Notes	Windows 95: Only supports 16-bit FileManager


ForegroundIdleProc
Windows NT	Yes
Win95	No
Win32s	No
Import Library	user-defined
Header File	winuser.h
Unicode	No
Platform Notes	None


GetMsgProc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user-defined
Header File	winuser.h
Unicode	No
Platform Notes	None


IOProc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user-defined
Header File	mmsystem.h
Unicode	No
Platform Notes	None


JournalPlaybackProc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user-defined
Header File	winuser.h
Unicode	No
Platform Notes	None


JournalRecordProc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user-defined
Header File	winuser.h
Unicode	No
Platform Notes	None


KeyboardProc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user-defined
Header File	winuser.h
Unicode	No
Platform Notes	None


LineDDAProc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user-defined
Header File	wingdi.h
Unicode	No
Platform Notes	None


MessageProc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user-defined
Header File	winuser.h
Unicode	No
Platform Notes	None


MidiInProc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user-defined
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MidiOutProc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user-defined
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MidiProc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user-defined
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MMIOProc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user-defined
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MouseProc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user-defined
Header File	winuser.h
Unicode	No
Platform Notes	None


MyStatusProc
Windows NT
Win95	Yes
Win32s
Import Library	user-defined
Header File	vfw.h
Unicode
Platform Notes	None


OutputProc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user-defined
Header File	winuser.h
Unicode	No
Platform Notes	None


PropEnumProc
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user-defined
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


PropEnumProcEx
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user-defined
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


PropSheetPageProc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user-defined
Header File	prsht.h
Unicode	WinNT
Platform Notes	None


PropSheetProc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user-defined
Header File	prsht.h
Unicode	No
Platform Notes	None


RasDialFunc
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user-defined
Header File	ras.h
Unicode	No
Platform Notes	None


RasDialFunc1
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user-defined
Header File	ras.h
Unicode	No
Platform Notes	None


SendAsyncProc
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user-defined
Header File	winuser.h
Unicode	No
Platform Notes	None


ShellProc
Windows NT	Yes
Win95	Yes
Win32s
Import Library	user-defined
Header File	winuser.h
Unicode	No
Platform Notes	None


SoundSentryProc
Windows NT	Yes
Win95	Yes
Win32s
Import Library	user-defined
Header File
Unicode
Platform Notes	None


SysMsgProc
Windows NT	Yes
Win95	Yes
Win32s
Import Library	user-defined
Header File	winuser.h
Unicode
Platform Notes	None


TimeProc
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user-defined
Header File	mmsystem.h
Unicode
Platform Notes	None


TimerProc
Windows NT	Yes
Win95	No
Win32s	No
Import Library	user-defined
Header File	winuser.h
Unicode	No
Platform Notes	None


UndeleteFile
Windows NT
Win95
Win32s
Import Library	user-defined
Header File	wfext.h
Unicode	No
Platform Notes	None


waveInProc
Windows NT	Yes
Win95	Yes
Win32s
Import Library	user-defined
Header File	mmsystem.h
Unicode
Platform Notes	None


waveOutProc
Windows NT	Yes
Win95	Yes
Win32s
Import Library	user-defined
Header File	mmsystem.h
Unicode
Platform Notes	None


WaveProc
Windows NT	Yes
Win95	Yes
Win32s
Import Library	user-defined
Header File	mmsystem.h
Unicode
Platform Notes	None


WindowProc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user-defined
Header File	winuser.h
Unicode
Platform Notes	None


BS_3STATE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


BS_AUTO3STATE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


BS_AUTOCHECKBOX
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


BS_AUTORADIOBUTTON
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


BS_BITMAP
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


BS_BOTTOM
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


BS_CENTER
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


BS_CHECKBOX
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


BS_DEFPUSHBUTTON
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


BS_DIBPATTERN
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: Only supports 8x8 brushes


BS_DIBPATTERN8X8
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	wingdi.h
Unicode	No
Platform Notes	None


BS_DIBPATTERNPT
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	wingdi.h
Unicode	No
Platform Notes	None


BS_GROUPBOX
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


BS_HATCHED
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	wingdi.h
Unicode	No
Platform Notes	None


BS_HOLLOW
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	wingdi.h
Unicode	No
Platform Notes	None


BS_ICON
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


BS_INDEXED
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	wingdi.h
Unicode	No
Platform Notes	None


BS_LEFT
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


BS_MULTILINE
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


BS_NOTIFY
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


BS_NULL
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	wingdi.h
Unicode	No
Platform Notes	None


BS_OWNERDRAW
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


BS_PATTERN
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	wingdi.h
Unicode	No
Platform Notes	None


BS_PATTERN8X8
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	wingdi.h
Unicode	No
Platform Notes	None


BS_PUSHBUTTON
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


BS_PUSHLIKE
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


BS_RADIOBUTTON
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


BS_RIGHT
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


BS_RIGHTBUTTON
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


BS_SOLID
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	wingdi.h
Unicode	No
Platform Notes	None


BS_TEXT
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


BS_TOP
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


BS_VCENTER
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CBS_AUTOHSCROLL
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CBS_DISABLENOSCROLL
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CBS_DROPDOWN
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CBS_DROPDOWNLIST
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CBS_HASSTRINGS
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CBS_LOWERCASE
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CBS_NOINTEGRALHEIGHT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CBS_OEMCONVERT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


GetSaveFileName
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	comdlg32.lib
Header File	commdlg.h
Unicode	WinNT
Platform Notes	None


GetSaveFileNamePreview
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	WinNT
Platform Notes	None


GetScrollInfo
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetScrollPos
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetScrollRange
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetSecurityDescriptorControl
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetSecurityDescriptorDacl
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetSecurityDescriptorGroup
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetSecurityDescriptorLength
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetSecurityDescriptorOwner
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetSecurityDescriptorSacl
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


getservbyname
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	wsock32.lib
Header File	winsock.h
Unicode	No
Platform Notes	None


getservbyport
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	wsock32.lib
Header File	winsock.h
Unicode	No
Platform Notes	None


GetService
Windows NT	Yes
Win95	No
Win32s	No
Import Library	wsock32.lib
Header File	nspapi.h
Unicode	WinNT
Platform Notes	None


GetServiceDisplayName
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winsvc.h
Unicode	WinNT
Platform Notes	None


GetServiceKeyName
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winsvc.h
Unicode	WinNT
Platform Notes	None


GetShortPathName
Windows NT	New
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


GetSidIdentifierAuthority
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetSidLengthRequired
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetSidSubAuthority
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetSidSubAuthorityCount
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


getsockname
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	wsock32.lib
Header File	winsock.h
Unicode	No
Platform Notes	None


getsockopt
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	wsock32.lib
Header File	winsock.h
Unicode	No
Platform Notes	None


GetStartupInfo
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


GetStdHandle
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetStockObject
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


GetStretchBltMode
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


GetStringTypeA
Windows NT	New
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winnls.h
Unicode	Unicode
Platform Notes	None


GetStringTypeEx
Windows NT	New
Win95	New
Win32s	New
Import Library	kernel32.lib
Header File	winnls.h
Unicode	No
Platform Notes	None


GetStringTypeW
Windows NT	Yes
Win95	No
Win32s	No
Import Library	kernel32.lib
Header File	winnls.h
Unicode	Unicode
Platform Notes	None


GetSubMenu
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetSysColor
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetSysColorBrush
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetSysModalWindow
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


GetSystemDefaultLangID
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winnls.h
Unicode	No
Platform Notes	None


GetSystemDefaultLCID
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winnls.h
Unicode	No
Platform Notes	None


GetSystemDirectory
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


GetSystemInfo
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetSystemMenu
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetSystemMetrics
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetSystemPaletteEntries
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


GetSystemPaletteUse
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


GetSystemPowerStatus
Windows NT	No
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetSystemTime
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetSystemTimeAdjustment
Windows NT	New
Win95	No
Win32s	New
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetSystemTimeAsFileTime
Windows NT	New
Win95	Yes
Win32s
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetTabbedTextExtent
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


GetTapeParameters
Windows NT	Yes
Win95	No
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetTapePosition
Windows NT	Yes
Win95	No
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetTapeStatus
Windows NT	Yes
Win95	No
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetTempFileName
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


GetTempPath
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


GetTextAlign
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


GetTextCharacterExtra
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


GetTextCharset
Windows NT	No
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


GetTextCharsetInfo
Windows NT	No
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


GetTextColor
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


GetTextExtentExPoint
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	WinNT; Win95
Platform Notes	Windows 95: int == 16 bits


GetTextExtentPoint
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	WinNT; Win95
Platform Notes	Windows 95: int == 16 bits


GetTextExtentPoint32
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	WinNT; Win95
Platform Notes	Windows 95: int == 16 bits


GetTextFace
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	WinNT
Platform Notes	Windows 95: int == 16 bits


GetTextMetrics
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	WinNT
Platform Notes	Windows 95: int == 16 bits


GetThreadContext
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetThreadDesktop
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	Windows 95: NOP; only one desktop


GetThreadLocale
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winnls.h
Unicode	No
Platform Notes	Windows 95: Locales are static & can change only at system boot


GetThreadPriority
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetThreadSelectorEntry
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetThreadTimes
Windows NT	Yes
Win95	No
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetTickCount
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetTimeFormat
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winnls.h
Unicode	WinNT
Platform Notes	None


GetTimeZoneInformation
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetTokenInformation
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetTopWindow
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetTypeByName
Windows NT	Yes
Win95	No
Win32s	No
Import Library	wsock32.lib
Header File	nspapi.h
Unicode	WinNT
Platform Notes	None


GetUpdateRect
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetUpdateRgn
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetUserDefaultLangID
Windows NT	Yes
Win95	Yes
Win32s	New
Import Library	kernel32.lib
Header File	winnls.h
Unicode	No
Platform Notes	None


GetUserDefaultLCID
Windows NT	Yes
Win95	Yes
Win32s	New
Import Library	kernel32.lib
Header File	winnls.h
Unicode	No
Platform Notes	None


GetUserName
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


GetUserObjectInformation
Windows NT	Yes
Win95	No
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


GetUserObjectSecurity
Windows NT	Yes
Win95	No
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetVersion
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetVersionEx
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetViewportExtEx
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


GetViewportOrgEx
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


GetVolumeInformation
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


GetWindow
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetWindowContextHelpId
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetWindowDC
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetWindowExtEx
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


GetWindowLong
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


GetWindowOrgEx
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


GetWindowPlacement
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetWindowRect
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetWindowRgn
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetWindowsDirectory
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


GetWindowTask
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


GetWindowText
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


GetWindowTextLength
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


GetWindowThreadProcessId
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetWindowWord
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetWinMetaFileBits
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


GetWorldTransform
Windows NT	Yes
Win95	No
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


glAccum
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glAddSwapHintRectWIN
Windows NT	New
Win95	No
Win32s	No
Import Library
Header File	gl.h
Unicode
Platform Notes	None


glAlphaFunc
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glArrayElementEXT
Windows NT	New
Win95	No
Win32s	No
Import Library
Header File	gl.h
Unicode
Platform Notes	None


glBegin
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glBitmap
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glBlendFunc
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glCallList
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glCallLists
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glClear
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glClearAccum
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glClearColor
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glClearDepth
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glClearIndex
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glClearStencil
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glClipPlane
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glColor3b
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glColor3bv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glColor3d
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glColor3dv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glColor3f
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glColor3fv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glColor3i
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glColor3iv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glColor3s
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glColor3sv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glColor3ub
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glColor3ubv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glColor3ui
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glColor3uiv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glColor3us
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glColor3usv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glColor4b
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glColor4bv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glColor4d
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glColor4dv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glColor4f
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glColor4fv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glColor4i
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glColor4iv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glColor4s
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glColor4sv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glColor4ub
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glColor4ubv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glColor4ui
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glColor4uiv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glColor4us
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glColor4usv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glColorMask
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glColorMaterial
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glColorPointerEXT
Windows NT	New
Win95	No
Win32s	No
Import Library
Header File	gl.h
Unicode
Platform Notes	None


glCopyPixels
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glCullFace
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glDeleteLists
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glDepthFunc
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glDepthMask
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glDepthRange
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glDisable
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glDrawArraysEXT
Windows NT	New
Win95	No
Win32s	No
Import Library
Header File	gl.h
Unicode
Platform Notes	None


glDrawBuffer
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glDrawPixels
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glEdgeFlag
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glEdgeFlagPointerEXT
Windows NT	New
Win95	No
Win32s	No
Import Library
Header File	gl.h
Unicode
Platform Notes	None


glEdgeFlagv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glEnable
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glEnd
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glEndList
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glEvalCoord1d
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glEvalCoord1dv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glEvalCoord1f
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glEvalCoord1fv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glEvalCoord2d
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glEvalCoord2dv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glEvalCoord2f
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glEvalCoord2fv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glEvalMesh1
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glEvalMesh2
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glEvalPoint1
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glEvalPoint2
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glFeedbackBuffer
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glFinish
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glFlush
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glFogf
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glFogfv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glFogi
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glFogiv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glFrontFace
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glFrustum
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glGenLists
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glGetBooleanv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glGetClipPlane
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glGetDoublev
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glGetError
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glGetFloatv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glGetIntegerv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glGetLightfv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glGetLightiv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glGetMapdv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glGetMapfv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glGetMapiv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glGetMaterialfv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glGetMaterialiv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glGetPixelMapfv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glGetPixelMapuiv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glGetPixelMapusv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glGetPointervEXT
Windows NT	New
Win95	No
Win32s	No
Import Library
Header File	gl.h
Unicode
Platform Notes	None


glGetPolygonStipple
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glGetString
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glGetTexEnvfv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glGetTexEnviv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glGetTexGendv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glGetTexGenfv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glGetTexGeniv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glGetTexImage
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glGetTexLevelParameterfv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glGetTexLevelParameteriv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glGetTexParameterfv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glGetTexParameteriv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glHint
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glIndexd
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glIndexdv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glIndexf
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glIndexfv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glIndexi
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glIndexiv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glIndexMask
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glIndexPointEXT
Windows NT	New
Win95	No
Win32s	No
Import Library
Header File	gl.h
Unicode
Platform Notes	None


glIndexs
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glIndexsv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glInitNames
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glIsEnabled
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glIsList
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glLightf
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glLightfv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glLighti
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glLightiv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glLightModelf
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glLightModelfv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glLightModeli
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glLightModeliv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glLineStipple
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glLineWidth
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glListBase
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glLoadIdentity
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glLoadMatrixd
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glLoadMatrixf
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glLoadName
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glLogicOp
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glMap1d
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glMap1f
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glMap2d
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glMap2f
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glMapGrid1d
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glMapGrid1f
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glMapGrid2d
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glMapGrid2f
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glMaterialf
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glMaterialfv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glMateriali
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glMaterialiv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glMatrixMode
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glMultMatrixd
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glMultMatrixf
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glNewList
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glNormal3b
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glNormal3bv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glNormal3d
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glNormal3dv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glNormal3f
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glNormal3fv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glNormal3i
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glNormal3iv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glNormal3s
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glNormal3sv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glNormalPointerEXT
Windows NT	New
Win95	No
Win32s	No
Import Library
Header File	gl.h
Unicode
Platform Notes	None


GlobalAddAtom
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


GlobalAlloc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	GMEM_FIXED is expensive (locks pages) on Win32s - use GMEM_MOVEABLE


GlobalCompact
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GlobalDeleteAtom
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GlobalDiscard
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winbase.h
Unicode	No
Platform Notes	None


GlobalFindAtom
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


GlobalFlags
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GlobalFree
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GlobalGetAtomName
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


GlobalHandle
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GlobalLock
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GlobalLRUNewest
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winbase.h
Unicode	No
Platform Notes	None


GlobalLRUOldest
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winbase.h
Unicode	No
Platform Notes	None


GlobalMemoryStatus
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GlobalReAlloc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GlobalSize
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GlobalUnlock
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


glOrtho
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glPassThrough
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glPixelMapfv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glPixelMapuiv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glPixelMapusv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glPixelStoref
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glPixelStorei
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glPixelTransferf
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glPixelTransferi
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glPixelZoom
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glPointSize
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glPolygonMode
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glPolygonStipple
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glPopAttrib
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glPopMatrix
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glPopName
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glPushAttrib
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glPushMatrix
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glPushName
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glRasterPos2d
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glRasterPos2dv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glRasterPos2f
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glRasterPos2fv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glRasterPos2i
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glRasterPos2iv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glRasterPos2s
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glRasterPos2sv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glRasterPos3d
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glRasterPos3dv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glRasterPos3f
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glRasterPos3fv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glRasterPos3i
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glRasterPos3iv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glRasterPos3s
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glRasterPos3sv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glRasterPos4d
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glRasterPos4dv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glRasterPos4f
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glRasterPos4fv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glRasterPos4i
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glRasterPos4iv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glRasterPos4s
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glRasterPos4sv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glReadBuffer
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glReadPixels
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glRectd
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glRectdv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glRectf
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glRectfv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glRecti
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glRectiv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glRects
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glRectsv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glRenderMode
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glRotated
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glRotatef
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glScaled
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glScalef
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glScissor
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glSelectBuffer
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glShadeModel
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glStencilFunc
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glStencilMask
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glStencilOp
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glTexCoord1d
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glTexCoord1dv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glTexCoord1f
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glTexCoord1fv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glTexCoord1i
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glTexCoord1iv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glTexCoord1s
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glTexCoord1sv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glTexCoord2d
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glTexCoord2dv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glTexCoord2f
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glTexCoord2fv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glTexCoord2i
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glTexCoord2iv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glTexCoord2s
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glTexCoord2sv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glTexCoord3d
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glTexCoord3dv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glTexCoord3f
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glTexCoord3fv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glTexCoord3i
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glTexCoord3iv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glTexCoord3s
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glTexCoord3sv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glTexCoord4d
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glTexCoord4dv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glTexCoord4f
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glTexCoord4fv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glTexCoord4i
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glTexCoord4iv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glTexCoord4s
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glTexCoord4sv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glTexCoordPointerEXT
Windows NT	New
Win95	No
Win32s	No
Import Library
Header File	gl.h
Unicode
Platform Notes	None


glTexEnvf
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glTexEnvfv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glTexEnvi
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glTexEnviv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glTexGend
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glTexGendv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glTexGenf
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glTexGenfv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glTexGeni
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glTexGeniv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glTexImage1D
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glTexImage2D
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glTexParameterf
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glTexParameterfv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glTexParameteri
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glTexParameteriv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glTranslated
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glTranslatef
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


gluBeginCurve
Windows NT	Yes
Win95	No
Win32s	No
Import Library	glu32.lib
Header File	glu.h
Unicode	No
Platform Notes	None


gluBeginPolygon
Windows NT	Yes
Win95	No
Win32s	No
Import Library	glu32.lib
Header File	glu.h
Unicode	No
Platform Notes	None


gluBeginSurface
Windows NT	Yes
Win95	No
Win32s	No
Import Library	glu32.lib
Header File	glu.h
Unicode	No
Platform Notes	None


gluBeginTrim
Windows NT	Yes
Win95	No
Win32s	No
Import Library	glu32.lib
Header File	glu.h
Unicode	No
Platform Notes	None


gluBuild1DMipmaps
Windows NT	Yes
Win95	No
Win32s	No
Import Library	glu32.lib
Header File	glu.h
Unicode	No
Platform Notes	None


gluBuild2DMipmaps
Windows NT	Yes
Win95	No
Win32s	No
Import Library	glu32.lib
Header File	glu.h
Unicode	No
Platform Notes	None


gluCylinder
Windows NT	Yes
Win95	No
Win32s	No
Import Library	glu32.lib
Header File	glu.h
Unicode	No
Platform Notes	None


gluDeleteNurbsRenderer
Windows NT	Yes
Win95	No
Win32s	No
Import Library	glu32.lib
Header File	glu.h
Unicode	No
Platform Notes	None


gluDeleteQuadric
Windows NT	Yes
Win95	No
Win32s	No
Import Library	glu32.lib
Header File	glu.h
Unicode	No
Platform Notes	None


gluDeleteTess
Windows NT	Yes
Win95	No
Win32s	No
Import Library	glu32.lib
Header File	glu.h
Unicode	No
Platform Notes	None


gluDisk
Windows NT	Yes
Win95	No
Win32s	No
Import Library	glu32.lib
Header File	glu.h
Unicode	No
Platform Notes	None


gluEndCurve
Windows NT	Yes
Win95	No
Win32s	No
Import Library	glu32.lib
Header File	glu.h
Unicode	No
Platform Notes	None


gluEndPolygon
Windows NT	Yes
Win95	No
Win32s	No
Import Library	glu32.lib
Header File	glu.h
Unicode	No
Platform Notes	None


gluEndSurface
Windows NT	Yes
Win95	No
Win32s	No
Import Library	glu32.lib
Header File	glu.h
Unicode	No
Platform Notes	None


gluEndTrim
Windows NT	Yes
Win95	No
Win32s	No
Import Library	glu32.lib
Header File	glu.h
Unicode	No
Platform Notes	None


gluErrorString
Windows NT	Yes
Win95	No
Win32s	No
Import Library	glu32.lib
Header File	glu.h
Unicode	No
Platform Notes	None


gluErrorUnicodeStringEXT
Windows NT	Yes
Win95	No
Win32s	No
Import Library	glu32.lib
Header File	glu.h
Unicode	WinNT
Platform Notes	None


gluGetNurbsProperty
Windows NT	Yes
Win95	No
Win32s	No
Import Library	glu32.lib
Header File	glu.h
Unicode	No
Platform Notes	None


gluGetString
Windows NT	New
Win95	No
Win32s	No
Import Library	glu32.lib
Header File	glu.h
Unicode	No
Platform Notes	None


gluGetTessProperty
Windows NT	New
Win95	No
Win32s	No
Import Library	glu32.lib
Header File	glu.h
Unicode	No
Platform Notes	None


gluLoadSamplingMatrices
Windows NT	Yes
Win95	No
Win32s	No
Import Library	glu32.lib
Header File	glu.h
Unicode	No
Platform Notes	None


gluLookAt
Windows NT	Yes
Win95	No
Win32s	No
Import Library	glu32.lib
Header File	glu.h
Unicode	No
Platform Notes	None


gluNewNurbsRenderer
Windows NT	Yes
Win95	No
Win32s	No
Import Library	glu32.lib
Header File	glu.h
Unicode	No
Platform Notes	None


gluNewQuadric
Windows NT	Yes
Win95	No
Win32s	No
Import Library	glu32.lib
Header File	glu.h
Unicode	No
Platform Notes	None


gluNewTess
Windows NT	Yes
Win95	No
Win32s	No
Import Library	glu32.lib
Header File	glu.h
Unicode	No
Platform Notes	None


gluNextContour
Windows NT	Yes
Win95	No
Win32s	No
Import Library	glu32.lib
Header File	glu.h
Unicode	No
Platform Notes	None


gluNurbsCallback
Windows NT	Yes
Win95	No
Win32s	No
Import Library	glu32.lib
Header File	glu.h
Unicode	No
Platform Notes	None


gluNurbsCurve
Windows NT	Yes
Win95	No
Win32s	No
Import Library	glu32.lib
Header File	glu.h
Unicode	No
Platform Notes	None


gluNurbsProperty
Windows NT	Yes
Win95	No
Win32s	No
Import Library	glu32.lib
Header File	glu.h
Unicode	No
Platform Notes	None


gluNurbsSurface
Windows NT	Yes
Win95	No
Win32s	No
Import Library	glu32.lib
Header File	glu.h
Unicode	No
Platform Notes	None


gluOrtho2D
Windows NT	Yes
Win95	No
Win32s	No
Import Library	glu32.lib
Header File	glu.h
Unicode	No
Platform Notes	None


gluPartialDisk
Windows NT	Yes
Win95	No
Win32s	No
Import Library	glu32.lib
Header File	glu.h
Unicode	No
Platform Notes	None


gluPerspective
Windows NT	Yes
Win95	No
Win32s	No
Import Library	glu32.lib
Header File	glu.h
Unicode	No
Platform Notes	None


gluPickMatrix
Windows NT	Yes
Win95	No
Win32s	No
Import Library	glu32.lib
Header File	glu.h
Unicode	No
Platform Notes	None


gluProject
Windows NT	Yes
Win95	No
Win32s	No
Import Library	glu32.lib
Header File	glu.h
Unicode	No
Platform Notes	None


gluPwlCurve
Windows NT	Yes
Win95	No
Win32s	No
Import Library	glu32.lib
Header File	glu.h
Unicode	No
Platform Notes	None


gluQuadricCallback
Windows NT	Yes
Win95	No
Win32s	No
Import Library	glu32.lib
Header File	glu.h
Unicode	No
Platform Notes	None


gluQuadricDrawStyle
Windows NT	Yes
Win95	No
Win32s	No
Import Library	glu32.lib
Header File	glu.h
Unicode	No
Platform Notes	None


gluQuadricNormals
Windows NT	Yes
Win95	No
Win32s	No
Import Library	glu32.lib
Header File	glu.h
Unicode	No
Platform Notes	None


gluQuadricOrientation
Windows NT	Yes
Win95	No
Win32s	No
Import Library	glu32.lib
Header File	glu.h
Unicode	No
Platform Notes	None


gluQuadricTexture
Windows NT	Yes
Win95	No
Win32s	No
Import Library	glu32.lib
Header File	glu.h
Unicode	No
Platform Notes	None


gluScaleImage
Windows NT	Yes
Win95	No
Win32s	No
Import Library	glu32.lib
Header File	glu.h
Unicode	No
Platform Notes	None


gluSphere
Windows NT	Yes
Win95	No
Win32s	No
Import Library	glu32.lib
Header File	glu.h
Unicode	No
Platform Notes	None


gluTessBeginContour
Windows NT	New
Win95	No
Win32s	No
Import Library	glu32.lib
Header File	glu.h
Unicode	No
Platform Notes	None


gluTessBeginPolygon
Windows NT	New
Win95	No
Win32s	No
Import Library	glu32.lib
Header File	glu.h
Unicode	No
Platform Notes	None


gluTessCallback
Windows NT	Yes
Win95	No
Win32s	No
Import Library	glu32.lib
Header File	glu.h
Unicode	No
Platform Notes	None


gluTessEndContour
Windows NT	New
Win95	No
Win32s	No
Import Library	glu32.lib
Header File	glu.h
Unicode	No
Platform Notes	None


gluTessEndPolygon
Windows NT	New
Win95	No
Win32s	No
Import Library	glu32.lib
Header File	glu.h
Unicode	No
Platform Notes	None


gluTessNormal
Windows NT	New
Win95	No
Win32s	No
Import Library	glu32.lib
Header File	glu.h
Unicode	No
Platform Notes	None


gluTessProperty
Windows NT	New
Win95	No
Win32s	No
Import Library	glu32.lib
Header File	glu.h
Unicode	No
Platform Notes	None


gluTessVertex
Windows NT	Yes
Win95	No
Win32s	No
Import Library	glu32.lib
Header File	glu.h
Unicode	No
Platform Notes	None


gluUnProject
Windows NT	Yes
Win95	No
Win32s	No
Import Library	glu32.lib
Header File	glu.h
Unicode	No
Platform Notes	None


glVertex2d
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glVertex2dv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glVertex2f
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glVertex2fv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glVertex2i
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glVertex2iv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glVertex2s
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glVertex2sv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glVertex3d
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glVertex3dv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glVertex3f
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glVertex3fv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glVertex3i
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glVertex3iv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glVertex3s
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glVertex3sv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glVertex4d
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glVertex4dv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glVertex4f
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glVertex4fv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glVertex4i
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glVertex4iv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glVertex4s
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glVertex4sv
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


glVertexPointerEXT
Windows NT	New
Win95	No
Win32s	No
Import Library
Header File	gl.h
Unicode
Platform Notes	None


glViewport
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	gl.h
Unicode	No
Platform Notes	None


GrayString
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


Handler
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File
Unicode	No
Platform Notes	None


HandlerRoutine
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File
Unicode	No
Platform Notes	None


HeapAlloc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


HeapCompact
Windows NT	New
Win95	No
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


HeapCreate
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


HeapDestroy
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


HeapFree
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


HeapLock
Windows NT	New
Win95	No
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


HeapReAlloc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


HeapSize
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


HeapUnlock
Windows NT	New
Win95	No
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


HeapValidate
Windows NT	New
Win95	No
Win32s	in debug version only
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


HeapWalk
Windows NT	New
Win95	No
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


HideCaret
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


HiliteMenuItem
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


htonl
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	wsock32.lib
Header File	winsock.h
Unicode	No
Platform Notes	None


htons
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	wsock32.lib
Header File	winsock.h
Unicode	No
Platform Notes	None


I_BrowserDebugTrace
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmbrowsr.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


I_BrowserQueryOtherDomains
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmbrowsr.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


I_BrowserQueryStatistics
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmbrowsr.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


I_BrowserResetNetlogonState
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmbrowsr.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


I_BrowserResetStatistics
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmbrowsr.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


I_BrowserServerEnum
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmbrowsr.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


I_NetLogonControl
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmaccess.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


I_NetLogonControl2
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmaccess.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


I_RpcAllocate
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdcep.h
Unicode
Platform Notes	None


I_RpcBindingCopy
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdcep.h
Unicode
Platform Notes	None


I_RpcBindingInqDynamicEndpoint
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdcep.h
Unicode
Platform Notes	None


I_RpcBindingInqTransportType
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdcep.h
Unicode	No
Platform Notes	None


I_RpcBindingIsClientLocal
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdcep.h
Unicode
Platform Notes	None


I_RpcClearMutex
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdcep.h
Unicode
Platform Notes	None


I_RpcDeleteMutex
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdcep.h
Unicode
Platform Notes	None


I_RpcFree
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdcep.h
Unicode
Platform Notes	None


I_RpcFreeBuffer
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdcep.h
Unicode
Platform Notes	None


I_RpcGetAssociationContext
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdcep.h
Unicode
Platform Notes	None


I_RpcGetBuffer
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdcep.h
Unicode
Platform Notes	None


I_RpcGetCurrentCallHandle
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdcep.h
Unicode
Platform Notes	None


I_RpcIfInqTransferSyntaxes
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdcep.h
Unicode
Platform Notes	None


I_RpcMapWin32Status
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpc.h
Unicode
Platform Notes	None


I_RpcMonitorAssociation
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdcep.h
Unicode
Platform Notes	None


I_RpcNsBindingSetEntryName
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdcep.h
Unicode
Platform Notes	None


I_RpcNsGetBuffer
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcns4.lib
Header File	rpcnsip.h
Unicode
Platform Notes	None


I_RpcNsRaiseException
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcns4.lib
Header File	rpcnsip.h
Unicode
Platform Notes	None


I_RpcNsSendReceive
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcns4.lib
Header File	rpcnsip.h
Unicode
Platform Notes	None


I_RpcPauseExecution
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdcep.h
Unicode
Platform Notes	None


I_RpcReBindBuffer
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcns4.lib
Header File	rpcdcep.h
Unicode
Platform Notes	None


I_RpcRequestMutex
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdcep.h
Unicode
Platform Notes	None


I_RpcSendReceive
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdcep.h
Unicode
Platform Notes	None


I_RpcServerRegisterForwardFunction
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdcep.h
Unicode	No
Platform Notes	None


I_RpcSetAssociationContext
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdcep.h
Unicode
Platform Notes	None


I_RpcSsDontSerializeContext
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdcep.h
Unicode	No
Platform Notes	None


I_RpcStopMonitorAssociation
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdcep.h
Unicode
Platform Notes	None


I_UuidCreate
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdcep.h
Unicode
Platform Notes	None


ICClose
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	WinNT
Platform Notes	None


ICCompress
Windows NT	New
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


ICCompressorChoose
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


ICCompressorFree
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


ICDecompress
Windows NT	New
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


ICDecompressEx
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h
Unicode	No
Platform Notes	None


ICDecompressExBegin
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h
Unicode	No
Platform Notes	None


ICDecompressExQuery
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h
Unicode	No
Platform Notes	None


ICDraw
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


ICDrawBegin
Windows NT	New
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


ICDrawSuggestFormat
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h
Unicode	No
Platform Notes	None


ICGetDisplayFormat
Windows NT	New
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


ICGetInfo
Windows NT	New
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


ICImageCompress
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


ICImageDecompress
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


ICInfo
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


ICInstall
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


ICLocate
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


ICOpen
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


ICOpenFunction
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


ICRemove
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


ICSendMessage
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


ICSeqCompressFrame
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


ICSeqCompressFrameEnd
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


ICSeqCompressFrameStart
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


ICSetState
Windows NT	New
Win95	Yes
Win32s	No
Import Library
Header File	vfw.h
Unicode	No
Platform Notes	None


ICSetStatusProc
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h
Unicode
Platform Notes	None


IIDFromString
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	WinNT; Win95; Win32s
Platform Notes	All 32-bit OLE Apis are UNICODE only


ImageList_Add
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	commctrl.h
Unicode	No
Platform Notes	None


ImageList_AddMasked
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	commctrl.h
Unicode	No
Platform Notes	None


ImageList_BeginDrag
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	commctrl.h
Unicode	No
Platform Notes	None


ImageList_Create
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	commctrl.h
Unicode	No
Platform Notes	None


ImageList_Destroy
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	commctrl.h
Unicode	No
Platform Notes	None


ImageList_DragEnter
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	commctrl.h
Unicode	No
Platform Notes	None


ImageList_DragLeave
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	commctrl.h
Unicode	No
Platform Notes	None


ImageList_DragMove
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	commctrl.h
Unicode	No
Platform Notes	None


ImageList_DragShowNolock
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	commctrl.h
Unicode	No
Platform Notes	None


ImageList_Draw
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	commctrl.h
Unicode	No
Platform Notes	None


ImageList_DrawEx
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	commctrl.h
Unicode	No
Platform Notes	None


ImageList_EndDrag
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	commctrl.h
Unicode	No
Platform Notes	None


ImageList_ExtractIcon
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	commctrl.h
Unicode	No
Platform Notes	None


ImageList_GetBkColor
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	commctrl.h
Unicode	No
Platform Notes	None


ImageList_GetDragImage
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	commctrl.h
Unicode	No
Platform Notes	None


ImageList_GetIcon
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	commctrl.h
Unicode	No
Platform Notes	None


ImageList_GetIconSize
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	commctrl.h
Unicode	No
Platform Notes	None


ImageList_GetImageCount
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	commctrl.h
Unicode	No
Platform Notes	None


ImageList_GetImageInfo
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	commctrl.h
Unicode	No
Platform Notes	None


ImageList_LoadBitmap
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	commctrl.h
Unicode	No
Platform Notes	None


ImageList_LoadImage
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	commctrl.h
Unicode	WinNT
Platform Notes	None


ImageList_Merge
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	commctrl.h
Unicode	No
Platform Notes	None


ImageList_Read
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	commctrl.h
Unicode	No
Platform Notes	None


ImageList_Remove
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	commctrl.h
Unicode	No
Platform Notes	None


ImageList_Replace
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	commctrl.h
Unicode	No
Platform Notes	None


ImageList_ReplaceIcon
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	commctrl.h
Unicode	No
Platform Notes	None


ImageList_SetBkColor
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	commctrl.h
Unicode	No
Platform Notes	None


ImageList_SetDragCursorImage
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	commctrl.h
Unicode	No
Platform Notes	None


ImageList_SetIconSize
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	commctrl.h
Unicode	No
Platform Notes	None


ImageList_SetOverlayImage
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	commctrl.h
Unicode	No
Platform Notes	None


ImageList_Write
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	commctrl.h
Unicode	No
Platform Notes	None


ImmAssociateContext
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	imm.h
Unicode
Platform Notes	None


ImmConfigureIME
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	imm.h
Unicode
Platform Notes	None


ImmCreateContext
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	imm.h
Unicode
Platform Notes	None


ImmDestroyContext
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	imm.h
Unicode
Platform Notes	None


ImmEnumRegisterWord
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	imm.h
Unicode
Platform Notes	None


ImmEscape
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	imm.h
Unicode
Platform Notes	None


ImmGetCandidateList
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	imm.h
Unicode
Platform Notes	None


ImmGetCandidateListCount
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	imm.h
Unicode
Platform Notes	None


ImmGetCandidateWindow
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	imm.h
Unicode
Platform Notes	None


ImmGetCompositionFont
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	imm.h
Unicode
Platform Notes	None


ImmGetCompositionString
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	imm.h
Unicode
Platform Notes	None


ImmGetCompositionWindow
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	imm.h
Unicode
Platform Notes	None


ImmGetContext
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	imm.h
Unicode
Platform Notes	None


ImmGetConversionList
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	imm.h
Unicode
Platform Notes	None


ImmGetConversionStatus
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	imm.h
Unicode
Platform Notes	None


ImmGetDefaultIMEWnd
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	imm.h
Unicode
Platform Notes	None


ImmGetDescription
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	imm.h
Unicode
Platform Notes	None


ImmGetGuideLine
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	imm.h
Unicode
Platform Notes	None


ImmGetIMEFileName
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	imm.h
Unicode
Platform Notes	None


ImmGetOpenStatus
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	imm.h
Unicode
Platform Notes	None


ImmGetProperty
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	imm.h
Unicode
Platform Notes	None


ImmGetRegisterWordStyle
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	imm.h
Unicode
Platform Notes	None


ImmGetStatusWindowPos
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	imm.h
Unicode
Platform Notes	None


ImmGetVirtualKey
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	imm.h
Unicode
Platform Notes	None


ImmInstallIME
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	imm.h
Unicode
Platform Notes	None


ImmIsIME
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	imm.h
Unicode
Platform Notes	None


ImmIsUIMessage
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	imm.h
Unicode
Platform Notes	None


ImmNotifyIME
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	imm.h
Unicode
Platform Notes	None


ImmRegisterWord
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	imm.h
Unicode
Platform Notes	None


ImmReleaseContext
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	imm.h
Unicode
Platform Notes	None


ImmSetCandidateWindow
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	imm.h
Unicode
Platform Notes	None


ImmSetCompositionFont
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	imm.h
Unicode
Platform Notes	None


ImmSetCompositionString
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	imm.h
Unicode
Platform Notes	None


ImmSetCompositionWindow
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	imm.h
Unicode
Platform Notes	None


ImmSetConversionStatus
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	imm.h
Unicode
Platform Notes	None


ImmSetOpenStatus
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	imm.h
Unicode
Platform Notes	None


ImmSetStatusWindowPos
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	imm.h
Unicode
Platform Notes	None


ImmSimulateHotKey
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	imm.h
Unicode
Platform Notes	None


ImmUnregisterWord
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	imm.h
Unicode
Platform Notes	None


ImpersonateDdeClientWindow
Windows NT	Yes
Win95	No
Win32s	No
Import Library	user32.lib
Header File	dde.h
Unicode	No
Platform Notes	None


ImpersonateLoggedOnUser
Windows NT	Yes
Win95	No
Win32s	No
Import Library
Header File	winbase.h
Unicode	No
Platform Notes	None


ImpersonateNamedPipeClient
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


ImpersonateSelf
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


inet_addr
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	wsock32.lib
Header File	winsock.h
Unicode	No
Platform Notes	None


inet_ntoa
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	wsock32.lib
Header File	winsock.h
Unicode	No
Platform Notes	None


InflateRect
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


InitAtomTable
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


InitCommonControls
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	commctrl.h
Unicode	No
Platform Notes	None


InitializeAcl
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


InitializeCriticalSection
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


InitializeSecurityDescriptor
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


InitializeSid
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


InitiateSystemShutdown
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winreg.h
Unicode	WinNT
Platform Notes	None


InSendMessage
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


InsertMenu
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


InsertMenuItem
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


Int32x32To64
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	winnt.h
Unicode	No
Platform Notes	None


Int64ShllMod32
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	winnt.h
Unicode	No
Platform Notes	None


Int64ShraMod32
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	winnt.h
Unicode	No
Platform Notes	None


Int64ShrlMod32
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	winnt.h
Unicode	No
Platform Notes	None


InterlockedDecrement
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


InterlockedExchange
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


InterlockedIncrement
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


IntersectClipRect
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


IntersectRect
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


InvalidateRect
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


InvalidateRgn
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


InvertRect
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


InvertRgn
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


ioctlsocket
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	wsock32.lib
Header File	winsock.h
Unicode	No
Platform Notes	None


IsAccelerator
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


IsBadCodePtr
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


IsBadHugeReadPtr
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


IsBadHugeWritePtr
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


IsBadReadPtr
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


IsBadStringPtr
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


IsBadWritePtr
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


IsCharAlpha
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


IsCharAlphaNumeric
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


IsCharLower
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


IsCharUpper
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


IsChild
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


IsClipboardFormatAvailable
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


IsDBCSLeadByte
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winnls.h
Unicode	No
Platform Notes	None


IsDBCSLeadByteEx
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winnls.h
Unicode	No
Platform Notes	None


IsDialogMessage
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


IsDlgButtonChecked
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


IsEqualGUID
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	No
Platform Notes	None


IsIconic
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


IsMenu
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


IsRectEmpty
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


IsTextUnicode
Windows NT	New
Win95	No
Win32s	New
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


IsValidAcl
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


IsValidCodePage
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winnls.h
Unicode	No
Platform Notes	None


IsValidLocale
Windows NT	New
Win95	New
Win32s	New
Import Library	kernel32.lib
Header File	winnls.h
Unicode	No
Platform Notes	None


IsValidPtrOut
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	No
Platform Notes	None


IsValidSecurityDescriptor
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


IsValidSid
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


IsWindow
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


IsWindowEnabled
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


IsWindowUnicode
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


IsWindowVisible
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


IsZoomed
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


joyGetDevCaps
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	WinNT
Platform Notes	None


joyGetNumDevs
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


joyGetPos
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


joyGetThreshold
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


joyReleaseCapture
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


joySetCapture
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


joySetThreshold
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


keybd_event
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


KillTimer
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


LBItemFromPt
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	commctrl.h
Unicode	No
Platform Notes	None


LCMapString
Windows NT	New
Win95	Yes
Win32s	New
Import Library	kernel32.lib
Header File	winnls.h
Unicode	WinNT
Platform Notes	None


LeaveCriticalSection
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


LHashValOfNameSys
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	WinNT; Win95; Win32s
Platform Notes	All 32-bit OLE Apis are UNICODE only


LineDDA
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


LineTo
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


listen
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	wsock32.lib
Header File	winsock.h
Unicode	No
Platform Notes	None


LoadAccelerators
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


LoadBitmap
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


LoadCursor
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


LoadCursorFromFile
Windows NT	New
Win95	New
Win32s	New
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


LoadIcon
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


LoadImage
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


LoadImageColorMatcher
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	WinNT
Platform Notes	None


LoadKeyboardLayout
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	Windows 95: Only 1 keybrd loaded at once


LoadLibrary
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


LoadLibraryEx
Windows NT	Yes
Win95	Yes
Win32s	New
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	Windows 95 limitations


LoadMenu
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


LoadMenuIndirect
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


LoadModule
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


LoadRegTypeLib
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


LoadResource
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


LoadString
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


LoadTypeLib
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	WinNT; Win95; Win32s
Platform Notes	All 32-bit OLE Apis are UNICODE only


LocalAlloc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


LocalCompact
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


LocalDiscard
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winbase.h
Unicode	No
Platform Notes	None


LocalFileTimeToFileTime
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


LocalFlags
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


LocalFree
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


LocalHandle
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


LocalLock
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


LocalReAlloc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


LocalShrink
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


LocalSize
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


LocalUnlock
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


LockFile
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


LockFileEx
Windows NT	Yes
Win95	No
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


LockResource
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


LockSegment
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winbase.h
Unicode	No
Platform Notes	None


LockServiceDatabase
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winsvc.h
Unicode	No
Platform Notes	None


LockWindowUpdate
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


LogonUser
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


long_array_from_ndr
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcndr.h
Unicode
Platform Notes	None


long_from_ndr
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcndr.h
Unicode
Platform Notes	None


long_from_ndr_temp
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcndr.h
Unicode
Platform Notes	None


LookupAccountName
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


LookupAccountSid
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


LookupIconIdFromDirectory
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


LookupIconIdFromDirectoryEx
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


LookupPrivilegeDisplayName
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


LookupPrivilegeName
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


LookupPrivilegeValue
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


LPtoDP
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


lstrcat
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


lstrcmp
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


lstrcmpi
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


lstrcpy
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


lstrcpyn
Windows NT	New
Win95	Yes
Win32s	New
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


lstrlen
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT; Win95
Platform Notes	None


LZClose
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	lz32.lib
Header File	lzexpand.h
Unicode	No
Platform Notes	None


LZCopy
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	lz32.lib
Header File	lzexpand.h
Unicode	No
Platform Notes	None


LZDone
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	lz32.lib
Header File	lzexpand.h
Unicode	No
Platform Notes	None


LZInit
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	lz32.lib
Header File	lzexpand.h
Unicode	No
Platform Notes	None


LZOpenFile
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	lz32.lib
Header File	lzexpand.h
Unicode	WinNT
Platform Notes	None


LZRead
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	lz32.lib
Header File	lzexpand.h
Unicode	No
Platform Notes	None


LZSeek
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	lz32.lib
Header File	lzexpand.h
Unicode	No
Platform Notes	None


LZStart
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	lz32.lib
Header File	lzexpand.h
Unicode	No
Platform Notes	None


MakeAbsoluteSD
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


MakeDragList
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	commctrl.h
Unicode	No
Platform Notes	None


MakeProcInstance
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winbase.h
Unicode	No
Platform Notes	None


MakeSelfRelativeSD
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


MapDialogRect
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


MapGenericMask
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


MapViewOfFile
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	Windows 95: Memory mapped files appear in the same address space in all processes


MapViewOfFileEx
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	Windows 95: Memory mapped files appear in the same address space in all processes


MapVirtualKey
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


MapVirtualKeyEx
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


MapWindowPoints
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


MaskBlt
Windows NT	Yes
Win95	No
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


mciGetCreatorTask
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


mciGetDeviceID
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	WinNT
Platform Notes	None


mciGetDeviceIDFromElementID
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	WinNT
Platform Notes	None


mciGetErrorString
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	WinNT
Platform Notes	None


mciGetYieldProc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


mciSendCommand
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	WinNT
Platform Notes	None


mciSendString
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	WinNT
Platform Notes	None


mciSetYieldProc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MCIWndCreate
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	WinNT
Platform Notes	None


MCIWndRegisterClass
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


MenuHelp
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	commctrl.h
Unicode	No
Platform Notes	None


MenuItemFromPoint
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


MesBufferHandleReset
Windows NT	New
Win95
Win32s	No
Import Library	rpcrt4.lib
Header File	midles.h
Unicode	No
Platform Notes	None


MesDecodeBufferHandleCreate
Windows NT	New
Win95
Win32s	No
Import Library	rpcrt4.lib
Header File	midles.h
Unicode	No
Platform Notes	None


MesDecodeIncrementalHandleCreate
Windows NT	New
Win95
Win32s	No
Import Library	rpcrt4.lib
Header File	midles.h
Unicode	No
Platform Notes	None


MesEncodeDynBufferHandleCreate
Windows NT	New
Win95
Win32s	No
Import Library	rpcrt4.lib
Header File	midles.h
Unicode	No
Platform Notes	None


MesEncodeFixedBufferHandleCreate
Windows NT	New
Win95
Win32s	No
Import Library	rpcrt4.lib
Header File	midles.h
Unicode	No
Platform Notes	None


MesEncodeIncrementalHandleCreate
Windows NT	New
Win95
Win32s	No
Import Library	rpcrt4.lib
Header File	midles.h
Unicode	No
Platform Notes	None


MesHandleFree
Windows NT	New
Win95
Win32s	No
Import Library	rpcrt4.lib
Header File	midles.h
Unicode	No
Platform Notes	None


MesIncrementalHandleReset
Windows NT	New
Win95
Win32s	No
Import Library	rpcrt4.lib
Header File	midles.h
Unicode	No
Platform Notes	None


MesInqProcEncodingId
Windows NT	New
Win95
Win32s	No
Import Library	rpcrt4.lib
Header File	midles.h
Unicode	No
Platform Notes	None


MessageBeep
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


MessageBox
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT; Win95
Platform Notes	None


MessageBoxEx
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT; Win95
Platform Notes	None


MessageBoxIndirect
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


midiConnect
Windows NT	Stub
Win95	Yes
Win32s
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


midiDisconnect
Windows NT	Stub
Win95	Yes
Win32s
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


midiInAddBuffer
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


midiInClose
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


midiInGetDevCaps
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	WinNT
Platform Notes	None


midiInGetErrorText
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	WinNT
Platform Notes	None


midiInGetID
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


midiInGetNumDevs
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


midiInMessage
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


midiInOpen
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


midiInPrepareHeader
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


midiInReset
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


midiInStart
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


midiInStop
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


midiInUnprepareHeader
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


midiOutCacheDrumPatches
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


midiOutCachePatches
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


midiOutClose
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


midiOutGetDevCaps
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	WinNT
Platform Notes	None


midiOutGetErrorText
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	WinNT
Platform Notes	None


midiOutGetID
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


midiOutGetNumDevs
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


midiOutGetVolume
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


midiOutLongMsg
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


midiOutMessage
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


midiOutOpen
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


midiOutPrepareHeader
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


midiOutReset
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


midiOutSetVolume
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


midiOutShortMsg
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


midiOutUnprepareHeader
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


midiStreamClose
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


midiStreamOpen
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


midiStreamOut
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


midiStreamPause
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


midiStreamPosition
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


midiStreamProperty
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


midiStreamRestart
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


midiStreamStop
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


midl_allocate
Windows NT	Yes
Win95	No
Win32s	No
Import Library
Header File	rpcndr.h
Unicode
Platform Notes	None


MIDL_user_allocate
Windows NT	Yes
Win95	No
Win32s	No
Import Library	user defined
Header File	rpcndr.h
Unicode
Platform Notes	None


MIDL_wchar_strcpy
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcndr.h
Unicode
Platform Notes	None


MIDL_wchar_strlen
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcndr.h
Unicode
Platform Notes	None


mixerClose
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


mixerGetControlDetails
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	WinNT
Platform Notes	None


mixerGetDevCaps
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	WinNT
Platform Notes	None


mixerGetID
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


mixerGetLineControls
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	WinNT
Platform Notes	None


mixerGetLineInfo
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	WinNT
Platform Notes	None


mixerGetNumDevs
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


mixerMessage
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


mixerOpen
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


mixerSetControlDetails
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MkParseDisplayName
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	WinNT; Win95; Win32s
Platform Notes	All 32-bit OLE Apis are UNICODE only


mmioAdvance
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


mmioAscend
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


mmioClose
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


mmioCreateChunk
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


mmioDescend
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


mmioFlush
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


mmioGetInfo
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


mmioInstallIOProc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	WinNT
Platform Notes	None


mmioOpen
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	WinNT
Platform Notes	None


mmioRead
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


mmioRename
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	WinNT
Platform Notes	None


mmioSeek
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


mmioSendMessage
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


mmioSetBuffer
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


mmioSetInfo
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


mmioStringToFOURCC
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	WinNT
Platform Notes	None


mmioWrite
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


mmsystemGetVersion
Windows NT	No
Win95	No
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


ModifyMenu
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


ModifyWorldTransform
Windows NT	Yes
Win95	No
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


MonikerCommonPrefixWith
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	No
Platform Notes	None


MonikerRelativePathTo
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	No
Platform Notes	None


mouse_event
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


MoveFile
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


MoveFileEx
Windows NT	Yes
Win95	No
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


MoveMemory
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winbase.h
Unicode	No
Platform Notes	None


MoveToEx
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


MoveWindow
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


MsgWaitForMultipleObjects
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


MulDiv
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


MultiByteToWideChar
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winnls.h
Unicode	No
Platform Notes	None


NDdeGetErrorString
Windows NT	Yes
Win95	No
Win32s	No
Import Library	nddeapi.lib
Header File	nddeapi.h
Unicode	WinNT
Platform Notes	None


NDdeGetShareSecurity
Windows NT	Yes
Win95	No
Win32s	No
Import Library	nddeapi.lib
Header File	nddeapi.h
Unicode	WinNT
Platform Notes	None


NDdeGetTrustedShare
Windows NT	Yes
Win95	No
Win32s	No
Import Library	nddeapi.lib
Header File	nddeapi.h
Unicode	WinNT
Platform Notes	None


NDdeIsValidAppTopicList
Windows NT	Yes
Win95	No
Win32s	No
Import Library	nddeapi.lib
Header File	nddeapi.h
Unicode	WinNT
Platform Notes	None


NDdeIsValidShareName
Windows NT	Yes
Win95	No
Win32s	No
Import Library	nddeapi.lib
Header File	nddeapi.h
Unicode	WinNT
Platform Notes	None


NDdeSetShareSecurity
Windows NT	Yes
Win95	No
Win32s	No
Import Library	nddeapi.lib
Header File	nddeapi.h
Unicode	WinNT
Platform Notes	None


NDdeSetTrustedShare
Windows NT	Yes
Win95	No
Win32s	No
Import Library	nddeapi.lib
Header File	nddeapi.h
Unicode	WinNT
Platform Notes	None


NDdeShareAdd
Windows NT	Yes
Win95	No
Win32s	No
Import Library	nddeapi.lib
Header File	nddeapi.h
Unicode	WinNT
Platform Notes	None


NDdeShareDel
Windows NT	Yes
Win95	No
Win32s	No
Import Library	nddeapi.lib
Header File	nddeapi.h
Unicode	WinNT
Platform Notes	None


NDdeShareEnum
Windows NT	Yes
Win95	No
Win32s	No
Import Library	nddeapi.lib
Header File	nddeapi.h
Unicode	WinNT
Platform Notes	None


NDdeShareGetInfo
Windows NT	Yes
Win95	No
Win32s	No
Import Library	nddeapi.lib
Header File	nddeapi.h
Unicode	WinNT
Platform Notes	None


NDdeShareSetInfo
Windows NT	Yes
Win95	No
Win32s	No
Import Library	nddeapi.lib
Header File	nddeapi.h
Unicode	WinNT
Platform Notes	None


NDdeTrustedShareEnum
Windows NT	Yes
Win95	No
Win32s	Yes
Import Library	nddeapi.lib
Header File	nddeapi.h
Unicode	WinNT
Platform Notes	None


NDRCContextBinding
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcndr.h
Unicode
Platform Notes	None


NDRCContextMarshall
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcndr.h
Unicode
Platform Notes	None


NDRCContextUnmarshall
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcndr.h
Unicode
Platform Notes	None


NDRcopy
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcndr.h
Unicode
Platform Notes	None


NDRSContextMarshall
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcndr.h
Unicode
Platform Notes	None


NDRSContextUnmarshall
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcndr.h
Unicode
Platform Notes	None


NetAccessAdd
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	lmaccess.h
Unicode	WinNT
Platform Notes	None


NetAccessCheck
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File
Unicode	WinNT
Platform Notes	None


NetAccessDel
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	lmaccess.h
Unicode	WinNT
Platform Notes	None


NetAccessEnum
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	lmaccess.h
Unicode	WinNT
Platform Notes	None


NetAccessGetInfo
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	lmaccess.h
Unicode	WinNT
Platform Notes	None


NetAccessGetUserPerms
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	lmaccess.h
Unicode	WinNT
Platform Notes	None


NetAccessSetInfo
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	lmaccess.h
Unicode	WinNT
Platform Notes	None


NetAlertRaise
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmalert.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetAlertRaiseEx
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmalert.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetApiBufferAllocate
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmapibuf.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetApiBufferFree
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmapibuf.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetApiBufferReallocate
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmapibuf.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetApiBufferSize
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmapibuf.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetapipBufferAllocate
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmapibuf.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetAuditClear
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmapibuf.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetAuditRead
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmapibuf.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetAuditWrite
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmaudit.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


Netbios
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	netapi32.lib
Header File	nb30.h
Unicode	No
Platform Notes	None


NetConfigGet
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmconfig.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetConfigGetAll
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmconfig.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetConfigSet
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmconfig.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetConnectionEnum
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	netapi32.lib
Header File	lmshare.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetErrorLogClear
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmerrlog.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetErrorLogRead
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmerrlog.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetErrorLogWrite
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmerrlog.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetFileClose
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	netapi32.lib
Header File	lmshare.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetFileEnum
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	netapi32.lib
Header File	lmshare.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetFileGetInfo
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmaccess.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetGetAnyDCName
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmaccess.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetGetDCName
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmaccess.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetGroupAdd
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmaccess.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetGroupAddUser
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmaccess.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetGroupDel
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmaccess.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetGroupDelUser
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmaccess.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetGroupEnum
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmaccess.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetGroupGetInfo
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmaccess.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetGroupGetUsers
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmaccess.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetGroupSetInfo
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmaccess.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetGroupSetUsers
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmaccess.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetLocalGroupAdd
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmaccess.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetLocalGroupAddMember
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmaccess.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetLocalGroupDel
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmaccess.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetLocalGroupDelMember
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmaccess.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetLocalGroupEnum
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmaccess.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetLocalGroupGetInfo
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmaccess.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetLocalGroupGetMembers
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmaccess.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetLocalGroupSetInfo
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmaccess.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetLocalGroupSetMembers
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmaccess.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetMessageBufferSend
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmmsg.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetMessageNameAdd
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmmsg.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetMessageNameDel
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmmsg.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetMessageNameEnum
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmmsg.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetMessageNameGetInfo
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmmsg.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetRemoteComputerSupports
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmremutl.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetRemoteTOD
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmremutl.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetReplExportDirAdd
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmrepl.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetReplExportDirDel
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmrepl.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetReplExportDirEnum
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmrepl.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetReplExportDirGetInfo
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmrepl.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetReplExportDirLock
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmrepl.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetReplExportDirSetInfo
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmrepl.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetReplExportDirUnlock
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmrepl.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetReplGetInfo
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmrepl.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetReplImportDirAdd
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmrepl.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetReplImportDirDel
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmrepl.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetReplImportDirEnum
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmrepl.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetReplImportDirGetInfo
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmrepl.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetReplImportDirLock
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmrepl.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetReplImportDirUnlock
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmrepl.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetReplSetInfo
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmrepl.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetScheduleJobAdd
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmat.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetScheduleJobDel
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmat.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetScheduleJobEnum
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmat.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetScheduleJobGetInfo
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmat.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetServerDiskEnum
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmserver.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetServerEnum
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmserver.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetServerGetInfo
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	netapi32.lib
Header File	lmserver.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetServerSetInfo
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	netapi32.lib
Header File	lmserver.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetServerTransportAdd
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmserver.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetServerTransportDel
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmserver.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetServerTransportEnum
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmserver.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetServiceControl
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmsvc.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetServiceEnum
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmsvc.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetServiceGetInfo
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmsvc.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetServiceInstall
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmsvc.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetSessionDel
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	netapi32.lib
Header File	lmshare.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetSessionEnum
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmshare.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetSessionGetInfo
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmshare.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetShareAdd
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmshare.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetShareCheck
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmshare.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetShareDel
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmshare.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetShareDelSticky
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmshare.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetShareEnum
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	netapi32.lib
Header File	lmshare.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetShareEnumSticky
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmshare.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetShareGetInfo
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	netapi32.lib
Header File	lmshare.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetShareSetInfo
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	netapi32.lib
Header File	lmshare.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetStatisticsGet
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmstats.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetUseAdd
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmuse.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetUseDel
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmuse.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetUseEnum
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmuse.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetUseGetInfo
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmuse.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetUserAdd
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmaccess.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetUserChangePassword
Windows NT	Yes
Win95	No
Win32s	No
Import Library
Header File	lmaccess.h
Unicode	WinNT
Platform Notes	None


NetUserDel
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmaccess.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetUserEnum
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmaccess.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetUserGetGroups
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmaccess.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetUserGetInfo
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmaccess.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetUserGetLocalGroups
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmaccess.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetUserModalsGet
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmaccess.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetUserModalsSet
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmaccess.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetUserSetGroups
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmaccess.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetUserSetInfo
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmaccess.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetWkstaGetInfo
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmwksta.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetWkstaSetInfo
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmwksta.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetWkstaTransportAdd
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmwksta.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetWkstaTransportDel
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmwksta.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetWkstaTransportEnum
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmwksta.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetWkstaUserEnum
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmwksta.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetWkstaUserGetInfo
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmwksta.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NetWkstaUserSetInfo
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmwksta.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


NotifyBootConfigStatus
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winsvc.h
Unicode	No
Platform Notes	None


NotifyChangeEventLog
Windows NT	New
Win95	No
Win32s	New
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


ntohl
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	wsock32.lib
Header File	winsock.h
Unicode	No
Platform Notes	None


ntohs
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	wsock32.lib
Header File	winsock.h
Unicode	No
Platform Notes	None


OaBuildVersion
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


ObjectCloseAuditAlarm
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


ObjectOpenAuditAlarm
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


ObjectPrivilegeAuditAlarm
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


OemKeyScan
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


OemToAnsi
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


OemToAnsiBuff
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


OemToChar
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


OemToCharBuff
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


OffsetClipRgn
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


OffsetRect
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


OffsetRgn
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


OffsetViewportOrgEx
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


OffsetWindowOrgEx
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


OleBuildVersion
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


OleConvertIStorageToOLESTREAM
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


OleConvertIStorageToOLESTREAMEx
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


OleConvertOLESTREAMToIStorage
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


OleConvertOLESTREAMToIStorageEx
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


OleCreate
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


OleCreateDefaultHandler
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


OleCreateEmbeddingHelper
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


OleCreateFromData
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


OleCreateFromFile
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	WinNT; Win95; Win32s
Platform Notes	All 32-bit OLE Apis are UNICODE only


OleCreateLink
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


OleCreateLinkFromData
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


OleCreateLinkToFile
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	WinNT; Win95; Win32s
Platform Notes	All 32-bit OLE Apis are UNICODE only


OleCreateMenuDescriptor
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


OleCreateStaticFromData
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


OleDestroyMenuDescriptor
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


OleDoAutoConvert
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


OleDraw
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


OleDuplicateData
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


OleFlushClipboard
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


OleGetAutoConvert
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


OleGetClipboard
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


OleGetIconOfClass
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


OleGetIconOfFile
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	WinNT; Win95; Win32s
Platform Notes	All 32-bit OLE Apis are UNICODE only


OleInitialize
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


OleIsCurrentClipboard
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


OleIsRunning
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


OleLoad
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


OleLoadFromStream
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


OleLockRunning
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


OleMetafilePictFromIconAndLabel
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	WinNT; Win95; Win32s
Platform Notes	All 32-bit OLE Apis are UNICODE only


OleNoteObjectVisible
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


OleQueryCreateFromData
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


OleQueryLinkFromData
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


OleRegEnumFormatEtc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


OleRegEnumVerbs
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


OleRegGetMiscStatus
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


OleRegGetUserType
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


OleRun
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


OleSave
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


OleSaveToStream
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


OleSetAutoConvert
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


OleSetClipboard
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


OleSetContainedObject
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


OleSetMenuDescriptor
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


OleTranslateAccelerator
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


OleUninitialize
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


OpenBackupEventLog
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


OpenClipboard
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


OpenDesktop
Windows NT	Yes
Win95	No
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


OpenEvent
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


OpenEventLog
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


OpenFile
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


OpenFileMapping
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


OpenIcon
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


OpenInputDesktop
Windows NT	Yes
Win95	No
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


OpenMutex
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


OpenPrinter
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	winspool.lib
Header File	winspool.h
Unicode	WinNT
Platform Notes	None


OpenProcess
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	On Win32s fdwAccess and fInherit ignored (set to PROCESS_ALL_ACCCESS and TRUE)


OpenProcessToken
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


OpenSCManager
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winsvc.h
Unicode	WinNT
Platform Notes	None


OpenSemaphore
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


OpenService
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winsvc.h
Unicode	WinNT
Platform Notes	None


OpenThreadToken
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


OpenWindowStation
Windows NT	Yes
Win95	No
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


OutputDebugString
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


PackDDElParam
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	dde.h
Unicode	No
Platform Notes	None


PaintDesktop
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


PaintRgn
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


PatBlt
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


PathToRegion
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


PeekConsoleInput
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	wincon.h
Unicode	WinNT
Platform Notes	None


PeekMessage
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


PeekNamedPipe
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


Pie
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


PlayEnhMetaFile
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	no dashed widelines
Platform Notes	Windows 95: Skips records which couldn't be processed under Windows 95's GDI: greater than 16-bit coordinates


PlayEnhMetaFileRecord
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	no dashed widelines
Platform Notes	Windows 95: Skips records which couldn't be processed under Windows 95's GDI: greater than 16-bit coordinates


PlayMetaFile
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


PlayMetaFileRecord
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


PlaySound
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	WinNT
Platform Notes	None


PlgBlt
Windows NT	Yes
Win95	No
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


PolyBezier
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


PolyBezierTo
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


PolyDraw
Windows NT	Yes
Win95	No
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


Polygon
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


Polyline
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


PolylineTo
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


PolyPolygon
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


PolyPolyline
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


PolyTextOut
Windows NT	Yes
Win95	No
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	WinNT
Platform Notes	None


PostAppMessage
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


PostMessage
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


PostQueuedCompletionStatus
Windows NT	Yes
Win95	No
Win32s	No
Import Library
Header File	winbase.h
Unicode	No
Platform Notes	None


PostQuitMessage
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


PostThreadMessage
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


PrepareTape
Windows NT	Yes
Win95	No
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


PrintDlg
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	comdlg32.lib
Header File	commdlg.h
Unicode	WinNT
Platform Notes	None


PrinterMessageBox
Windows NT	Yes
Win95	No
Win32s	No
Import Library	winspool.lib
Header File	winspool.h
Unicode	WinNT
Platform Notes	None


PrinterProperties
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	winspool.lib
Header File	winspool.h
Unicode	No
Platform Notes	None


PrivilegeCheck
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


PrivilegedServiceAuditAlarm
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


PtInRect
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


PtInRegion
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


PtVisible
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


PulseEvent
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


PurgeComm
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


QueryDosDevice
Windows NT	Yes
Win95	No
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


QueryPathOfRegTypeLib
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


QueryPerformanceCounter
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


QueryPerformanceFrequency
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


QueryServiceConfig
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winsvc.h
Unicode	WinNT
Platform Notes	None


QueryServiceLockStatus
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winsvc.h
Unicode	WinNT
Platform Notes	None


QueryServiceObjectSecurity
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winsvc.h
Unicode	No
Platform Notes	None


QueryServiceStatus
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winsvc.h
Unicode	No
Platform Notes	None


RaiseException
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


RasDial
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rasapi32.lib
Header File	ras.h
Unicode	WinNT
Platform Notes	None


RasEnumConnections
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rasapi32.lib
Header File	ras.h
Unicode	WinNT
Platform Notes	None


RasEnumEntries
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rasapi32.lib
Header File	ras.h
Unicode	WinNT
Platform Notes	None


RasGetConnectStatus
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rasapi32.lib
Header File	ras.h
Unicode	WinNT
Platform Notes	None


RasGetErrorString
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rasapi32.lib
Header File	ras.h
Unicode	WinNT
Platform Notes	None


RasGetProjectionInfo
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rasapi32.lib
Header File	ras.h
Unicode	WinNT
Platform Notes	None


RasHangUp
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rasapi32.lib
Header File	ras.h
Unicode	WinNT
Platform Notes	None


ReadClassStg
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


ReadClassStm
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


ReadConsole
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	wincon.h
Unicode	WinNT
Platform Notes	None


ReadConsoleInput
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	wincon.h
Unicode	WinNT
Platform Notes	None


ReadConsoleOutput
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	wincon.h
Unicode	WinNT
Platform Notes	None


ReadConsoleOutputAttribute
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	wincon.h
Unicode	No
Platform Notes	None


ReadConsoleOutputCharacter
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	wincon.h
Unicode	WinNT
Platform Notes	None


ReadEventLog
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


ReadFile
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	New
Platform Notes	Windows 95: No overlapped regions


ReadFileEx
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	Windows 95 limitations


ReadFmtUserTypeStg
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	WinNT; Win95; Win32s
Platform Notes	All 32-bit OLE Apis are UNICODE only


ReadPrinter
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	winspool.lib
Header File	winspool.h
Unicode	No
Platform Notes	None


ReadProcessMemory
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


RealizePalette
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


Rectangle
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


RectInRegion
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


RectVisible
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


recv
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	wsock32.lib
Header File	winsock.h
Unicode	No
Platform Notes	None


recvfrom
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	wsock32.lib
Header File	winsock.h
Unicode	No
Platform Notes	None


RedrawWindow
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


RegCloseKey
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	advapi32.lib
Header File	winreg.h
Unicode	No
Platform Notes	None


RegConnectRegistry
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	advapi32.lib
Header File	winreg.h
Unicode	WinNT
Platform Notes	None


RegCreateKey
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	advapi32.lib
Header File	winreg.h
Unicode	WinNT
Platform Notes	None


RegCreateKeyEx
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	advapi32.lib
Header File	winreg.h
Unicode	WinNT
Platform Notes	None


RegDeleteKey
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	advapi32.lib
Header File	winreg.h
Unicode	WinNT
Platform Notes	None


RegDeleteValue
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	advapi32.lib
Header File	winreg.h
Unicode	WinNT
Platform Notes	None


RegEnumKey
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	advapi32.lib
Header File	winreg.h
Unicode	WinNT
Platform Notes	None


RegEnumKeyEx
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	advapi32.lib
Header File	winreg.h
Unicode	WinNT
Platform Notes	None


CBS_OWNERDRAWFIXED
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CBS_OWNERDRAWVARIABLE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CBS_SIMPLE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CBS_SORT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CBS_UPPERCASE
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


LBS_DISABLENOSCROLL
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


LBS_EXTENDEDSEL
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


LBS_HASSTRINGS
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


LBS_MULTICOLUMN
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


LBS_MULTIPLESEL
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


LBS_NODATA
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


LBS_NOINTEGRALHEIGHT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


LBS_NOREDRAW
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


LBS_NOTIFY
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


LBS_OWNERDRAWFIXED
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


LBS_OWNERDRAWVARIABLE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


LBS_SORT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


LBS_STANDARD
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


LBS_USETABSTOPS
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


LBS_WANTKEYBOARDINPUT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


PS_ALTERNATE
Windows NT	Yes
Win95	No
Win32s	No
Import Library
Header File	wingdi.h
Unicode	No
Platform Notes	None


PS_COSMETIC
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	wingdi.h
Unicode	No
Platform Notes	None


PS_DASH
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: Doesn't support this in a wideline


PS_DASHDOT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: Doesn't support this in a wideline


PS_DASHDOTDOT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: Doesn't support this in a wideline


PS_DOT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: Doesn't support this in a wideline


PS_ENDCAP_FLAT
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: Supported only in a path


PS_ENDCAP_ROUND
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: Supported only in a path


PS_ENDCAP_SQUARE
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: Supported only in a path


PS_GEOMETRIC
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	wingdi.h
Unicode	No
Platform Notes	None


PS_INSIDEFRAME
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	wingdi.h
Unicode	No
Platform Notes	None


PS_JOIN_BEVEL
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: Supported only in a path


PS_JOIN_MITER
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: Supported only in a path


PS_JOIN_ROUND
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: Supported only in a path


PS_NULL
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	wingdi.h
Unicode	No
Platform Notes	None


PS_SOLID
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	wingdi.h
Unicode	No
Platform Notes	None


PS_USERSTYLE
Windows NT	Yes
Win95	No
Win32s	No
Import Library
Header File	wingdi.h
Unicode	No
Platform Notes	None


WM_DDE_FIRST
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	dde.h
Unicode	No
Platform Notes	None


WM_DDE_LAST
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	dde.h
Unicode	No
Platform Notes	None


WM_MOUSEFIRST
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode
Platform Notes	None


WM_MOUSELAST
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode
Platform Notes	None


WM_PENWINFIRST
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_PENWINLAST
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WS_EX_ACCEPTFILES
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WS_EX_DLGMODALFRAME
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WS_EX_NOPARENTNOTIFY
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WS_EX_TOPMOST
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WS_EX_TRANSPARENT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


XTYP_ADVDATA
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	ddeml.h
Unicode
Platform Notes	None


XTYP_ADVREQ
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	ddeml.h
Unicode
Platform Notes	None


XTYP_ADVSTART
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	ddeml.h
Unicode
Platform Notes	None


XTYP_ADVSTOP
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	ddeml.h
Unicode
Platform Notes	None


XTYP_CONNECT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	ddeml.h
Unicode
Platform Notes	None


XTYP_CONNECT_CONFIRM
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	ddeml.h
Unicode
Platform Notes	None


XTYP_DISCONNECT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	ddeml.h
Unicode
Platform Notes	None


XTYP_ERROR
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	ddeml.h
Unicode
Platform Notes	None


XTYP_EXECUTE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	ddeml.h
Unicode
Platform Notes	None


XTYP_MONITOR
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	ddeml.h
Unicode
Platform Notes	None


XTYP_POKE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	ddeml.h
Unicode
Platform Notes	None


XTYP_REGISTER
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	ddeml.h
Unicode
Platform Notes	None


XTYP_REQUEST
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	ddeml.h
Unicode
Platform Notes	None


XTYP_UNREGISTER
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	ddeml.h
Unicode
Platform Notes	None


XTYP_WILDCONNECT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	ddeml.h
Unicode
Platform Notes	None


XTYP_XACT_COMPLETE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	ddeml.h
Unicode
Platform Notes	None


FSCTL_DISMOUNT_VOLUME
Windows NT	Yes
Win95	No
Win32s	No
Import Library
Header File	winioctl.h
Unicode	No
Platform Notes	None


FSCTL_GET_COMPRESSION
Windows NT	Yes
Win95	No
Win32s	No
Import Library
Header File	winioctl.h
Unicode	No
Platform Notes	None


FSCTL_LOCK_VOLUME
Windows NT	Yes
Win95	No
Win32s	No
Import Library
Header File	winioctl.h
Unicode	No
Platform Notes	None


FSCTL_SET_COMPRESSION
Windows NT	Yes
Win95	No
Win32s	No
Import Library
Header File	winioctl.h
Unicode	No
Platform Notes	None


FSCTL_UNLOCK_VOLUME
Windows NT	Yes
Win95	No
Win32s	No
Import Library
Header File	winioctl.h
Unicode	No
Platform Notes	None


IOCTL_DISK_CHECK_VERIFY
Windows NT	Yes
Win95	No
Win32s	No
Import Library
Header File	winioctl.h
Unicode	No
Platform Notes	None


IOCTL_DISK_EJECT_MEDIA
Windows NT	Yes
Win95	No
Win32s	No
Import Library
Header File	winioctl.h
Unicode	No
Platform Notes	None


IOCTL_DISK_FORMAT_TRACKS
Windows NT	Yes
Win95	No
Win32s	No
Import Library
Header File	winioctl.h
Unicode	No
Platform Notes	None


IOCTL_DISK_GET_DRIVE_GEOMETRY
Windows NT	Yes
Win95	No
Win32s	No
Import Library
Header File	winioctl.h
Unicode	No
Platform Notes	None


IOCTL_DISK_GET_DRIVE_LAYOUT
Windows NT	Yes
Win95	No
Win32s	No
Import Library
Header File	winioctl.h
Unicode	No
Platform Notes	None


IOCTL_DISK_GET_MEDIA_TYPES
Windows NT	Yes
Win95	No
Win32s	No
Import Library
Header File	winioctl.h
Unicode	No
Platform Notes	None


IOCTL_DISK_GET_PARTITION_INFO
Windows NT	Yes
Win95	No
Win32s	No
Import Library
Header File	winioctl.h
Unicode	No
Platform Notes	None


IOCTL_DISK_LOAD_MEDIA
Windows NT	Yes
Win95	No
Win32s	No
Import Library
Header File	winioctl.h
Unicode	No
Platform Notes	None


IOCTL_DISK_MEDIA_REMOVAL
Windows NT	Yes
Win95	No
Win32s	No
Import Library
Header File	winioctl.h
Unicode	No
Platform Notes	None


IOCTL_DISK_PERFORMANCE
Windows NT	Yes
Win95	No
Win32s	No
Import Library
Header File	winioctl.h
Unicode	No
Platform Notes	None


IOCTL_DISK_REASSIGN_BLOCKS
Windows NT	Yes
Win95	No
Win32s	No
Import Library
Header File	winioctl.h
Unicode	No
Platform Notes	None


IOCTL_DISK_SET_DRIVE_LAYOUT
Windows NT	Yes
Win95	No
Win32s	No
Import Library
Header File	winioctl.h
Unicode	No
Platform Notes	None


IOCTL_DISK_SET_PARTITION_INFO
Windows NT	Yes
Win95	No
Win32s	No
Import Library
Header File	winioctl.h
Unicode	No
Platform Notes	None


IOCTL_DISK_VERIFY
Windows NT	Yes
Win95	No
Win32s	No
Import Library
Header File	winioctl.h
Unicode	No
Platform Notes	None


IOCTL_SERIAL_LSRMST_INSERT
Windows NT	Yes
Win95	No
Win32s	No
Import Library
Header File	winioctl.h
Unicode	No
Platform Notes	None


ACL_INFORMATION_CLASS
Windows NT	Yes
Win95	No
Win32s	No
Import Library
Header File	winnt.h
Unicode
Platform Notes	None


FD_FLAGS
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


MEDIA_TYPE
Windows NT	Yes
Win95	No
Win32s	No
Import Library
Header File	winioctl.h
Unicode
Platform Notes	None


RASCONNSTATE
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	ras.h
Unicode
Platform Notes	None


RASPROJECTION
Windows NT	Yes
Win95	No
Win32s	No
Import Library
Header File	ras.h
Unicode
Platform Notes	None


SECURITY_IMPERSONATION_LEVEL
Windows NT	Yes
Win95	No
Win32s	No
Import Library
Header File	winnt.h
Unicode
Platform Notes	None


SID_NAME_USE
Windows NT	Yes
Win95	No
Win32s	No
Import Library
Header File	winnt.h
Unicode
Platform Notes	None


TOKEN_INFORMATION_CLASS
Windows NT	Yes
Win95	No
Win32s	No
Import Library
Header File	winnt.h
Unicode
Platform Notes	None


TOKEN_TYPE
Windows NT	Yes
Win95	No
Win32s	No
Import Library
Header File	winnt.h
Unicode
Platform Notes	None


__WSAFDIsSet
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	wsock32.lib
Header File	winsock.h
Unicode	No
Platform Notes	None


_hread
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


_hwrite
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


_lclose
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


_lcreat
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


_llseek
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


_lopen
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


_lread
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


_lwrite
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


AbnormalTermination
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	rpc.h
Unicode	No
Platform Notes	None


AbortDoc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


AbortPath
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


AbortPrinter
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	winspool.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


AbortSystemShutdown
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winreg.h
Unicode	WinNT
Platform Notes	None


accept
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	wsock32.lib
Header File	winsock.h
Unicode	No
Platform Notes	None


AccessCheck
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


AccessCheckAndAuditAlarm
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


acmDriverAdd
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	msacm32.lib
Header File	msacm.h
Unicode	WinNT
Platform Notes	None


acmDriverClose
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	msacm32.lib
Header File	msacm.h
Unicode	No
Platform Notes	None


acmDriverDetails
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	msacm32.lib
Header File	msacm.h
Unicode	WinNT
Platform Notes	None


acmDriverEnum
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	msacm32.lib
Header File	msacm.h
Unicode	No
Platform Notes	None


acmDriverID
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	msacm32.lib
Header File	msacm.h
Unicode	No
Platform Notes	None


acmDriverMessage
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	msacm32.lib
Header File	msacm.h
Unicode	No
Platform Notes	None


acmDriverOpen
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	msacm32.lib
Header File	msacm.h
Unicode	No
Platform Notes	None


acmDriverPriority
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	msacm32.lib
Header File	msacm.h
Unicode	No
Platform Notes	None


acmDriverRemove
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	msacm32.lib
Header File	msacm.h
Unicode	No
Platform Notes	None


acmFilterChoose
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	msacm32.lib
Header File	msacm.h
Unicode	WinNT
Platform Notes	None


acmFilterDetails
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	msacm32.lib
Header File	msacm.h
Unicode	WinNT
Platform Notes	None


RegEnumValue
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	advapi32.lib
Header File	winreg.h
Unicode	WinNT
Platform Notes	None


RegFlushKey
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	advapi32.lib
Header File	winreg.h
Unicode	No
Platform Notes	None


RegGetKeySecurity
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winreg.h
Unicode	No
Platform Notes	None


RegisterActiveObject
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


RegisterClass
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


RegisterClassEx
Windows NT	Stub
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


RegisterClipboardFormat
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


RegisterDialogClasses
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	scrnsave.lib
Header File	scrnsave.h
Unicode	No
Platform Notes	None


RegisterDragDrop
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


RegisterEventSource
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


RegisterHotKey
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


RegisterServiceCtrlHandler
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winsvc.h
Unicode	WinNT
Platform Notes	None


RegisterTypeLib
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	WinNT; Win95; Win32s
Platform Notes	All 32-bit OLE Apis are UNICODE only


RegisterWindowMessage
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


RegLoadKey
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	advapi32.lib
Header File	winreg.h
Unicode	WinNT
Platform Notes	None


RegNotifyChangeKeyValue
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winreg.h
Unicode	No
Platform Notes	None


RegOpenKey
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	advapi32.lib
Header File	winreg.h
Unicode	WinNT
Platform Notes	None


RegOpenKeyEx
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	advapi32.lib
Header File	winreg.h
Unicode	WinNT
Platform Notes	None


RegQueryInfoKey
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	advapi32.lib
Header File	winreg.h
Unicode	WinNT
Platform Notes	None


RegQueryMultipleValues
Windows NT	No
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode
Platform Notes	None


RegQueryValue
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	advapi32.lib
Header File	winreg.h
Unicode	WinNT
Platform Notes	None


RegQueryValueEx
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	advapi32.lib
Header File	winreg.h
Unicode	WinNT
Platform Notes	None


RegReplaceKey
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	advapi32.lib
Header File	winreg.h
Unicode	WinNT
Platform Notes	None


RegRestoreKey
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winreg.h
Unicode	WinNT
Platform Notes	None


RegSaveKey
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	advapi32.lib
Header File	winreg.h
Unicode	WinNT
Platform Notes	None


RegSetKeySecurity
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winreg.h
Unicode	No
Platform Notes	None


RegSetValue
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	advapi32.lib
Header File	winreg.h
Unicode	WinNT
Platform Notes	None


RegSetValueEx
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	advapi32.lib
Header File	winreg.h
Unicode	WinNT
Platform Notes	None


RegUnLoadKey
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	advapi32.lib
Header File	winreg.h
Unicode	WinNT
Platform Notes	None


ReleaseCapture
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


ReleaseDC
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


ReleaseMutex
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


ReleaseSemaphore
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


ReleaseStgMedium
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


RemoveDirectory
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


RemoveFontResource
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	WinNT
Platform Notes	Windows 95: int == 16 bits


RemoveMenu
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


RemoveProp
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


ReplaceText
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	comdlg32.lib
Header File	commdlg.h
Unicode	WinNT
Platform Notes	None


ReplyMessage
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


ReportEvent
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


ResetDC
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	WinNT
Platform Notes	Windows 95: int == 16 bits


ResetDisplay
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


ResetEvent
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


ResetPrinter
Windows NT	Yes
Win95	No
Win32s	No
Import Library	winspool.lib
Header File	winspool.h
Unicode	WinNT
Platform Notes	None


ResizePalette
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


RestoreDC
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


ResumeThread
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


ReuseDDElParam
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	dde.h
Unicode	No
Platform Notes	None


RevertToSelf
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


RevokeActiveObject
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


RevokeDragDrop
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


RoundRect
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


RpcAbnormalTermination
Windows NT	New
Win95	Yes
Win32s	No
Import Library
Header File	rpc.h
Unicode	No
Platform Notes	None


RpcBindingCopy
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode	No
Platform Notes	None


RpcBindingFree
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode	No
Platform Notes	None


RpcBindingFromStringBinding
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode	WinNT
Platform Notes	None


RpcBindingInqAuthClient
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode
Platform Notes	None


RpcBindingInqAuthInfo
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode	WinNT
Platform Notes	None


RpcBindingInqObject
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode	No
Platform Notes	None


RpcBindingReset
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode	No
Platform Notes	None


RpcBindingServerFromClient
Windows NT	Yes
Win95	Yes
Win32s
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode	No
Platform Notes	None


RpcBindingSetAuthInfo
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode
Platform Notes	None


RpcBindingSetObject
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode	No
Platform Notes	None


RpcBindingToStringBinding
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode	WinNT
Platform Notes	None


RpcBindingVectorFree
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode	No
Platform Notes	None


RpcCancelThread
Windows NT	New
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode	No
Platform Notes	None


RpcEndExcept
Windows NT	New
Win95	Yes
Win32s	No
Import Library
Header File	rpc.h
Unicode	No
Platform Notes	None


RpcEndFinally
Windows NT	New
Win95	Yes
Win32s	No
Import Library
Header File	rpc.h
Unicode	No
Platform Notes	None


RpcEpRegister
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode	WinNT
Platform Notes	None


RpcEpRegisterNoReplace
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode	WinNT
Platform Notes	None


RpcEpResolveBinding
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode	No
Platform Notes	None


RpcEpUnregister
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode	No
Platform Notes	None


RpcExcept
Windows NT	New
Win95	Yes
Win32s	No
Import Library
Header File	rpc.h
Unicode	No
Platform Notes	None


RpcExceptionCode
Windows NT	New
Win95	Yes
Win32s	No
Import Library
Header File	rpc.h
Unicode	No
Platform Notes	None


RpcFinally
Windows NT	New
Win95	Yes
Win32s	No
Import Library
Header File	rpc.h
Unicode	No
Platform Notes	None


RpcIfIdVectorFree
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode	No
Platform Notes	None


RpcIfInqId
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode	No
Platform Notes	None


RpcImpersonateClient
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpc.h
Unicode
Platform Notes	None


RpcMgmtEnableIdleCleanup
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode	No
Platform Notes	None


RpcMgmtEpEltInqBegin
Windows NT	New
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode	No
Platform Notes	None


RpcMgmtEpEltInqDone
Windows NT	New
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode	No
Platform Notes	None


RpcMgmtEpEltInqNext
Windows NT	New
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode	WinNT
Platform Notes	None


RpcMgmtEpUnregister
Windows NT	New
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode	No
Platform Notes	None


RpcMgmtInqComTimeout
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode	No
Platform Notes	None


RpcMgmtInqDefaultProtectLevel
Windows NT	Yes
Win95	Yes
Win32s
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode	No
Platform Notes	None


RpcMgmtInqIfIds
Windows NT	Yes
Win95	Yes
Win32s
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode	No
Platform Notes	None


RpcMgmtInqServerPrincName
Windows NT	New
Win95
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode	WinNT
Platform Notes	None


RpcMgmtInqStats
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode	No
Platform Notes	None


RpcMgmtIsServerListening
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode	No
Platform Notes	None


RpcMgmtSetAuthorizationFn
Windows NT	New
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode	No
Platform Notes	None


RpcMgmtSetCancelTimeout
Windows NT	New
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode	No
Platform Notes	None


RpcMgmtSetComTimeout
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode	No
Platform Notes	None


RpcMgmtSetServerStackSize
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode	No
Platform Notes	None


RpcMgmtStatsVectorFree
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode	No
Platform Notes	None


RpcMgmtStopServerListening
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode	No
Platform Notes	None


RpcMgmtWaitServerListen
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode	No
Platform Notes	None


RpcNetworkInqProtseqs
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode	WinNT
Platform Notes	None


RpcNetworkIsProtseqValid
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode	WinNT
Platform Notes	None


RpcNsBindingExport
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcns4.lib
Header File	rpcnsi.h
Unicode	WinNT
Platform Notes	None


RpcNsBindingImportBegin
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcns4.lib
Header File	rpcnsi.h
Unicode	WinNT
Platform Notes	None


RpcNsBindingImportDone
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcns4.lib
Header File	rpcnsi.h
Unicode	No
Platform Notes	None


RpcNsBindingImportNext
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcns4.lib
Header File	rpcnsi.h
Unicode	No
Platform Notes	None


RpcNsBindingInqEntryName
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode	WinNT
Platform Notes	None


RpcNsBindingLookupBegin
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcns4.lib
Header File	rpcnsi.h
Unicode	WinNT
Platform Notes	None


RpcNsBindingLookupDone
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcns4.lib
Header File	rpcnsi.h
Unicode	No
Platform Notes	None


RpcNsBindingLookupNext
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcns4.lib
Header File	rpcnsi.h
Unicode	No
Platform Notes	None


RpcNsBindingSelect
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcns4.lib
Header File	rpcnsi.h
Unicode	No
Platform Notes	None


RpcNsBindingUnexport
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcns4.lib
Header File	rpcnsi.h
Unicode	WinNT
Platform Notes	None


RpcNsEntryExpandName
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcns4.lib
Header File	rpcnsi.h
Unicode	WinNT
Platform Notes	None


RpcNsEntryObjectInqBegin
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcns4.lib
Header File	rpcnsi.h
Unicode	WinNT
Platform Notes	None


RpcNsEntryObjectInqDone
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcns4.lib
Header File	rpcnsi.h
Unicode	No
Platform Notes	None


RpcNsEntryObjectInqNext
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcns4.lib
Header File	rpcnsi.h
Unicode	No
Platform Notes	None


RpcNsGroupDelete
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcns4.lib
Header File	rpcnsi.h
Unicode	WinNT
Platform Notes	None


RpcNsGroupMbrAdd
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcns4.lib
Header File	rpcnsi.h
Unicode	WinNT
Platform Notes	None


RpcNsGroupMbrInqBegin
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcns4.lib
Header File	rpcnsi.h
Unicode	WinNT
Platform Notes	None


RpcNsGroupMbrInqDone
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcns4.lib
Header File	rpcnsi.h
Unicode	No
Platform Notes	None


RpcNsGroupMbrInqNext
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcns4.lib
Header File	rpcnsi.h
Unicode	WinNT
Platform Notes	None


RpcNsGroupMbrRemove
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcns4.lib
Header File	rpcnsi.h
Unicode	WinNT
Platform Notes	None


RpcNsMgmtBindingUnexport
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcns4.lib
Header File	rpcnsi.h
Unicode	WinNT
Platform Notes	None


RpcNsMgmtEntryCreate
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcns4.lib
Header File	rpcnsi.h
Unicode	WinNT
Platform Notes	None


RpcNsMgmtEntryDelete
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcns4.lib
Header File	rpcnsi.h
Unicode	WinNT
Platform Notes	None


RpcNsMgmtEntryInqIfIds
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcns4.lib
Header File	rpcnsi.h
Unicode	WinNT
Platform Notes	None


RpcNsMgmtHandleSetExpAge
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcns4.lib
Header File	rpcnsi.h
Unicode	No
Platform Notes	None


RpcNsMgmtInqExpAge
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcns4.lib
Header File	rpcnsi.h
Unicode	No
Platform Notes	None


RpcNsMgmtSetExpAge
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcns4.lib
Header File	rpcnsi.h
Unicode	No
Platform Notes	None


RpcNsProfileDelete
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcns4.lib
Header File	rpcnsi.h
Unicode	WinNT
Platform Notes	None


RpcNsProfileEltAdd
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcns4.lib
Header File	rpcnsi.h
Unicode	WinNT
Platform Notes	None


RpcNsProfileEltInqBegin
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcns4.lib
Header File	rpcnsi.h
Unicode	WinNT
Platform Notes	None


RpcNsProfileEltInqDone
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcns4.lib
Header File	rpcnsi.h
Unicode	No
Platform Notes	None


RpcNsProfileEltInqNext
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcns4.lib
Header File	rpcnsi.h
Unicode	WinNT
Platform Notes	None


RpcNsProfileEltRemove
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcns4.lib
Header File	rpcnsi.h
Unicode	WinNT
Platform Notes	None


RpcObjectInqType
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode	No
Platform Notes	None


RpcObjectSetInqFn
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode	No
Platform Notes	None


RpcObjectSetType
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode	No
Platform Notes	None


RpcProtseqVectorFree
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode
Platform Notes	None


RpcRaiseException
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode
Platform Notes	None


RpcRevertToSelf
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpc.h
Unicode
Platform Notes	None


RpcServerInqBindings
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode
Platform Notes	None


RpcServerInqIf
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode
Platform Notes	None


RpcServerListen
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode
Platform Notes	None


RpcServerRegisterAuthInfo
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode
Platform Notes	None


RpcServerRegisterIf
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode
Platform Notes	None


RpcServerUnregisterIf
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode
Platform Notes	None


RpcServerUseAllProtseqs
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode
Platform Notes	None


RpcServerUseAllProtseqsIf
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode
Platform Notes	None


RpcServerUseProtseq
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode
Platform Notes	None


RpcServerUseProtseqEp
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode
Platform Notes	None


RpcServerUseProtseqIf
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode
Platform Notes	None


RpcSmAllocate
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	rpcrt4.lib
Header File	rpcndr.h
Unicode	No
Platform Notes	None


RpcSmClientFree
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	rpcrt4.lib
Header File	rpcndr.h
Unicode	No
Platform Notes	None


RpcSmDestroyClientContext
Windows NT	New
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcndr.h
Unicode	No
Platform Notes	None


RpcSmDisableAllocate
Windows NT	New
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcndr.h
Unicode	No
Platform Notes	None


RpcSmEnableAllocate
Windows NT	New
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcndr.h
Unicode	No
Platform Notes	None


RpcSmFree
Windows NT	New
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcndr.h
Unicode	No
Platform Notes	None


RpcSmGetThreadHandle
Windows NT	Yes
Win95	Yes
Win32s
Import Library	rpcrt4.lib
Header File	rpcndr.h
Unicode	No
Platform Notes	None


RpcSmSetClientAllocFree
Windows NT	New
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcndr.h
Unicode	No
Platform Notes	None


RpcSmSetThreadHandle
Windows NT	Yes
Win95	Yes
Win32s
Import Library	rpcrt4.lib
Header File	rpcndr.h
Unicode	No
Platform Notes	None


RpcSmSwapClientAllocFree
Windows NT	New
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcndr.h
Unicode	No
Platform Notes	None


RpcSsAllocate
Windows NT	Yes
Win95	Yes
Win32s
Import Library	rpcrt4.lib
Header File	rpcndr.h
Unicode	No
Platform Notes	None


RpcSsDestroyClientContext
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcndr.h
Unicode	No
Platform Notes	None


RpcSsDisableAllocate
Windows NT	Yes
Win95	Yes
Win32s
Import Library	rpcrt4.lib
Header File	rpcndr.h
Unicode	No
Platform Notes	None


RpcSsEnableAllocate
Windows NT	Yes
Win95	Yes
Win32s
Import Library	rpcrt4.lib
Header File	rpcndr.h
Unicode	No
Platform Notes	None


RpcSsFree
Windows NT	Yes
Win95	Yes
Win32s
Import Library	rpcrt4.lib
Header File	rpcndr.h
Unicode	No
Platform Notes	None


RpcSsGetThreadHandle
Windows NT	Yes
Win95	Yes
Win32s
Import Library	rpcrt4.lib
Header File	rpcndr.h
Unicode	No
Platform Notes	None


RpcSsSetClientAllocFree
Windows NT	New
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcndr.h
Unicode	No
Platform Notes	None


RpcSsSetThreadHandle
Windows NT	Yes
Win95	Yes
Win32s
Import Library	rpcrt4.lib
Header File	rpcndr.h
Unicode	No
Platform Notes	None


RpcSsSwapClientAllocFree
Windows NT	New
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcndr.h
Unicode	No
Platform Notes	None


RpcStringBindingCompose
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode	WinNT
Platform Notes	None


RpcStringBindingParse
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode	WinNT
Platform Notes	None


RpcStringFree
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode	WinNT
Platform Notes	None


RpcTestCancel
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode	WinNT
Platform Notes	None


RpcTryExcept
Windows NT	New
Win95	Yes
Win32s	No
Import Library
Header File	rpc.h
Unicode	No
Platform Notes	None


RpcTryFinally
Windows NT	New
Win95	Yes
Win32s	No
Import Library
Header File	rpc.h
Unicode	No
Platform Notes	None


RxNetAccessAdd
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmaccess.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


RxNetAccessDel
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmaccess.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


RxNetAccessEnum
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmaccess.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


RxNetAccessGetInfo
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmaccess.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


RxNetAccessGetUserPerms
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmaccess.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


RxNetAccessSetInfo
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmaccess.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


RxRemoteApi
Windows NT	Yes
Win95	No
Win32s	No
Import Library	netapi32.lib
Header File	lmremutl.h
Unicode	WinNT
Platform Notes	All LanMan APIs are UNICODE only


SafeArrayAccessData
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


SafeArrayAllocData
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


SafeArrayAllocDescriptor
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


SafeArrayCopy
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


SafeArrayCreate
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


SafeArrayDestroy
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


SafeArrayDestroyData
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


SafeArrayDestroyDescriptor
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


SafeArrayGetDim
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


SafeArrayGetElement
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


SafeArrayGetElemsize
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


SafeArrayGetLBound
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


SafeArrayGetUBound
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


SafeArrayLock
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


SafeArrayPtrOfIndex
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


SafeArrayPutElement
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


SafeArrayRedim
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


SafeArrayUnaccessData
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


SafeArrayUnlock
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


SaveDC
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


ScaleViewportExtEx
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


ScaleWindowExtEx
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


ScheduleJob
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	winspool.lib
Header File	winspool.h
Unicode	No
Platform Notes	None


ScreenSaverConfigureDialog
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	scrnsave.lib
Header File	scrnsave.h
Unicode	No
Platform Notes	None


ScreenSaverProc
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	scrnsave.lib
Header File	scrnsave.h
Unicode	No
Platform Notes	None


ScreenToClient
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


ScrollConsoleScreenBuffer
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	wincon.h
Unicode	WinNT
Platform Notes	None


ScrollDC
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


ScrollWindow
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


ScrollWindowEx
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


SearchPath
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


select
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	wsock32.lib
Header File	winsock.h
Unicode	No
Platform Notes	None


SelectClipPath
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


SelectClipRgn
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


SelectObject
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes


SelectPalette
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


send
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	wsock32.lib
Header File	winsock.h
Unicode	No
Platform Notes	None


SendDlgItemMessage
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


SendMessage
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


SendMessageCallback
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


SendMessageTimeout
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


SendNotifyMessage
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


sendto
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	wsock32.lib
Header File	winsock.h
Unicode	No
Platform Notes	None


ServiceMain
Windows NT	Yes
Win95	No
Win32s	No
Import Library
Header File
Unicode	No
Platform Notes	None


SetAbortProc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


SetAclInformation
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


SetActiveWindow
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


SetArcDirection
Windows NT	Yes
Win95	No
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


SetBitmapBits
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


SetBitmapDimensionEx
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


SetBkColor
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


SetBkMode
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


SetBoundsRect
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


SetBrushOrgEx
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


SetCapture
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


SetCaretBlinkTime
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


SetCaretPos
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


SetClassLong
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


SetClassWord
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


SetClipboardData
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


SetClipboardViewer
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


SetColorAdjustment
Windows NT	Yes
Win95	No
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


SetColorSpace
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


SetCommBreak
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


SetCommConfig
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


SetCommMask
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


SetCommState
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


SetCommTimeouts
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


SetComputerName
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


SetConsoleActiveScreenBuffer
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	wincon.h
Unicode	No
Platform Notes	None


SetConsoleCP
Windows NT	Yes
Win95	No
Win32s	No
Import Library	kernel32.lib
Header File	wincon.h
Unicode	No
Platform Notes	None


SetConsoleCtrlHandler
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	wincon.h
Unicode	No
Platform Notes	None


SetConsoleCursorInfo
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	wincon.h
Unicode	No
Platform Notes	None


SetConsoleCursorPosition
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	wincon.h
Unicode	No
Platform Notes	None


SetConsoleMode
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	wincon.h
Unicode	No
Platform Notes	None


SetConsoleOutputCP
Windows NT	Yes
Win95	No
Win32s	No
Import Library	kernel32.lib
Header File	wincon.h
Unicode	No
Platform Notes	None


SetConsoleScreenBufferSize
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	wincon.h
Unicode	No
Platform Notes	None


SetConsoleTextAttribute
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	wincon.h
Unicode	No
Platform Notes	None


SetConsoleTitle
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	wincon.h
Unicode	WinNT
Platform Notes	None


SetConsoleWindowInfo
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	wincon.h
Unicode	No
Platform Notes	None


SetConvertStg
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


SetCurrentDirectory
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


SetCursor
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


SetCursorPos
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


SetDebugErrorLevel
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


SetDefaultCommConfig
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


SetDeviceGammaRamp
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


SetDIBColorTable
Windows NT	New
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


SetDIBits
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


SetDIBitsToDevice
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


SetDlgItemInt
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


SetDlgItemText
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


SetDoubleClickTime
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


SetEndOfFile
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


SetEnhMetaFileBits
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


SetEnvironmentVariable
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


SetErrorInfo
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


SetErrorMode
Windows NT	New
Win95	Yes
Win32s	New
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	This is used for RISC platforms only. x86 platforms and Windows 95 return a constant


SetEvent
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


SetFileApisToANSI
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	On Win32s all file APIs are ANSI


SetFileApisToOEM
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	On Win32s the file APIs are always OEM


SetFileAttributes
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


SetFilePointer
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


SetFileSecurity
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


SetFileTime
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


SetFocus
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


SetForegroundWindow
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


SetForm
Windows NT	Yes
Win95	No
Win32s	No
Import Library	winspool.lib
Header File	winspool.h
Unicode	WinNT
Platform Notes	None


SetGraphicsMode
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: Only GM_COMPATIBLE is supported


SetHandleCount
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


SetHandleInformation
Windows NT	Yes
Win95	No
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


SetICMMode
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


SetICMProfile
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	WinNT
Platform Notes	None


SetJob
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	winspool.lib
Header File	winspool.h
Unicode	WinNT
Platform Notes	None


SetKernelObjectSecurity
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


SetKeyboardState
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


SetLastError
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


SetLastErrorEx
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


SetLocaleInfo
Windows NT	New
Win95	New
Win32s	New
Import Library	kernel32.lib
Header File	winnls.h
Unicode	WinNT
Platform Notes	None


SetLocalTime
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


SetMailslotInfo
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


SetMapMode
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


SetMapperFlags
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


SetMenu
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


SetMenuContextHelpId
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


SetMenuDefaultItem
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


SetMenuItemBitmaps
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


SetMenuItemInfo
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


SetMessageExtraInfo
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


SetMessageQueue
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


SetMetaFileBitsEx
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


SetMetaRgn
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


SetMiterLimit
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


SetNamedPipeHandleState
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


SetPaletteEntries
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


SetParent
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


SetPixel
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


SetPixelFormat
Windows NT	Yes
Win95	No
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


SetPixelV
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


SetPolyFillMode
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


SetPrinter
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	winspool.lib
Header File	winspool.h
Unicode	WinNT
Platform Notes	None


SetPrinterData
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	winspool.lib
Header File	winspool.h
Unicode	WinNT
Platform Notes	None


SetPriorityClass
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


SetPrivateObjectSecurity
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


SetProcessShutdownParameters
Windows NT	Yes
Win95	No
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


SetProcessWindowStation
Windows NT	Yes
Win95	No
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


SetProcessWorkingSetSize
Windows NT	Yes
Win95	No
Win32s	New
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


SetProp
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


SetRect
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


SetRectEmpty
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


SetRectRgn
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


SetROP2
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


SetScrollInfo
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


SetScrollPos
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


SetScrollRange
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


SetSecurityDescriptorDacl
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


SetSecurityDescriptorGroup
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


SetSecurityDescriptorOwner
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


SetSecurityDescriptorSacl
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


SetService
Windows NT	Yes
Win95	No
Win32s	No
Import Library	wsock32.lib
Header File	nspapi.h
Unicode	WinNT
Platform Notes	None


SetServiceBits
Windows NT	New
Win95	No
Win32s	New
Import Library	advapi32.lib
Header File	lmserver.h
Unicode	No
Platform Notes	None


SetServiceObjectSecurity
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winsvc.h
Unicode	No
Platform Notes	None


SetServiceStatus
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winsvc.h
Unicode	No
Platform Notes	None


setsockopt
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	wsock32.lib
Header File	winsock.h
Unicode	No
Platform Notes	None


SetStdHandle
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


SetStretchBltMode
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


SetSwapAreaSize
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winbase.h
Unicode	No
Platform Notes	None


SetSysColors
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


SetSysModalWindow
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


SetSystemCursor
Windows NT	New
Win95	Yes
Win32s	New
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


SetSystemPaletteUse
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


SetSystemPowerState
Windows NT	No
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


SetSystemTime
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


SetSystemTimeAdjustment
Windows NT	New
Win95	No
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


SetTapeParameters
Windows NT	Yes
Win95	No
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


SetTapePosition
Windows NT	Yes
Win95	No
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


SetTextAlign
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


SetTextCharacterExtra
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


SetTextColor
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


SetTextJustification
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


SetThreadAffinityMask
Windows NT	New
Win95	New
Win32s	New
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	This is valid on SMP platforms only; Windows 95 returns a constant


SetThreadContext
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


SetThreadDesktop
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	Windows 95: NOP; only one desktop


SetThreadLocale
Windows NT	Yes
Win95	No
Win32s	No
Import Library	kernel32.lib
Header File	winnls.h
Unicode	No
Platform Notes	Windows 95: Locales are static & can change only at system boot


SetThreadPriority
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


SetThreadToken
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


SetTimer
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


SetTimeZoneInformation
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


SetTokenInformation
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


SetUnhandledExceptionFilter
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


SetupComm
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


SetUserObjectInformation
Windows NT	Yes
Win95	No
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


SetUserObjectSecurity
Windows NT	Yes
Win95	No
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


SetViewportExtEx
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


SetViewportOrgEx
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


SetVolumeLabel
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


SetWindowContextHelpId
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


SetWindowExtEx
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


SetWindowLong
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


SetWindowOrgEx
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


SetWindowPlacement
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


SetWindowPos
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


SetWindowRgn
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


SetWindowsHook
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


SetWindowsHookEx
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


SetWindowText
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


SetWindowWord
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


SetWinMetaFileBits
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


SetWorldTransform
Windows NT	Yes
Win95	No
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


SHAddToRecentDocs
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


SHAppBarMessage
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shellapi.h
Unicode
Platform Notes	None


SHBrowseForFolder
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


SHChangeNotify
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


Shell_NotifyIcon
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shellapi.h
Unicode
Platform Notes	None


ShellAbout
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	shell32.lib
Header File	shellapi.h
Unicode	WinNT
Platform Notes	None


ShellExecute
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	shell32.lib
Header File	shellapi.h
Unicode	WinNT
Platform Notes	None


ShellExecuteEx
Windows NT
Win95	Yes
Win32s
Import Library
Header File	shellapi.h
Unicode
Platform Notes	None


SHFileOperation
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


SHFreeNameMappings
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


SHGetDesktopFolder
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


SHGetFileInfo
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


SHGetInstanceExplorer
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


SHGetMalloc
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


SHGetPathFromIDList
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


SHGetSpecialFolderLocation
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


SHLoadInProc
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


short_array_from_ndr
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcndr.h
Unicode
Platform Notes	None


short_from_ndr
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcndr.h
Unicode
Platform Notes	None


short_from_ndr_temp
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcndr.h
Unicode
Platform Notes	None


ShowCaret
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


ShowCursor
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


ShowHideMenuCtl
Windows NT	Yes
Win95	Yes
Win32s
Import Library
Header File	commctrl.h
Unicode	No
Platform Notes	None


ShowOwnedPopups
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


ShowScrollBar
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


ShowWindow
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


ShowWindowAsync
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


shutdown
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	wsock32.lib
Header File	winsock.h
Unicode	No
Platform Notes	None


SizeofResource
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


Sleep
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


SleepEx
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


sndPlaySound
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	WinNT
Platform Notes	None


socket
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	wsock32.lib
Header File	winsock.h
Unicode	No
Platform Notes	None


StartDoc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	WinNT
Platform Notes	Windows 95: int == 16 bits


StartDocPrinter
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	winspool.lib
Header File	winspool.h
Unicode	WinNT
Platform Notes	None


StartPage
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


StartPagePrinter
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	winspool.lib
Header File	winspool.h
Unicode	No
Platform Notes	None


StartService
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winsvc.h
Unicode	WinNT
Platform Notes	None


StartServiceCtrlDispatcher
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winsvc.h
Unicode	WinNT
Platform Notes	None


StgCreateDocfile
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	WinNT; Win95; Win32s
Platform Notes	All 32-bit OLE Apis are UNICODE only


StgCreateDocfileOnILockBytes
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	No
Platform Notes	None


StgIsStorageFile
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	WinNT; Win95; Win32s
Platform Notes	All 32-bit OLE Apis are UNICODE only


StgIsStorageILockBytes
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	No
Platform Notes	None


StgOpenStorage
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	WinNT; Win95; Win32s
Platform Notes	All 32-bit OLE Apis are UNICODE only


StgOpenStorageOnILockBytes
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	No
Platform Notes	None


StgSetTimes
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	WinNT; Win95; Win32s
Platform Notes	All 32-bit OLE Apis are UNICODE only


StretchBlt
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


StretchDIBits
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


StringFromCLSID
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	WinNT; Win95; Win32s
Platform Notes	All 32-bit OLE Apis are UNICODE only


StringFromGUID2
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	WinNT; Win95; Win32s
Platform Notes	All 32-bit OLE Apis are UNICODE only


StringFromIID
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	WinNT; Win95; Win32s
Platform Notes	All 32-bit OLE Apis are UNICODE only


StrokeAndFillPath
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


StrokePath
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


SubtractRect
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


SuspendThread
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


SwapBuffers
Windows NT	Yes
Win95	No
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


SwapMouseButton
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


SwitchDesktop
Windows NT	Yes
Win95	No
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


SysAllocString
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	WinNT; Win95; Win32s
Platform Notes	All 32-bit OLE Apis are UNICODE only


SysAllocStringByteLen
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	WinNT; Win95; Win32s
Platform Notes	All 32-bit OLE Apis are UNICODE only


SysAllocStringLen
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	WinNT; Win95; Win32s
Platform Notes	All 32-bit OLE Apis are UNICODE only


SysFreeString
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	WinNT; Win95; Win32s
Platform Notes	All 32-bit OLE Apis are UNICODE only


SysReAllocString
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	WinNT; Win95; Win32s
Platform Notes	All 32-bit OLE Apis are UNICODE only


SysReAllocStringLen
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	WinNT; Win95; Win32s
Platform Notes	All 32-bit OLE Apis are UNICODE only


SysStringByteLen
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	WinNT; Win95; Win32s
Platform Notes	All 32-bit OLE Apis are UNICODE only


SysStringLen
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	WinNT; Win95; Win32s
Platform Notes	All 32-bit OLE Apis are UNICODE only


SystemParametersInfo
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


SystemTimeToFileTime
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


SystemTimeToTzSpecificLocalTime
Windows NT	New
Win95	No
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


TabbedTextOut
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


TerminateProcess
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


TerminateThread
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


TextOut
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	WinNT; Win95
Platform Notes	Windows 95: 16-bit coordinates only


TileWindows
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


timeBeginPeriod
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


timeEndPeriod
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


timeGetDevCaps
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


timeGetSystemTime
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


timeGetTime
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


timeKillEvent
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


timeSetEvent
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


TlsAlloc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


TlsFree
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


TlsGetValue
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


TlsSetValue
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


ToAscii
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


ToAsciiEx
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


ToUnicode
Windows NT	Yes
Win95	No
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


TrackPopupMenu
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


TrackPopupMenuEx
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


TransactNamedPipe
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


TranslateAccelerator
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


TranslateCharsetInfo
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	wingdi.h
Unicode	No
Platform Notes	None


TranslateMDISysAccel
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


TranslateMessage
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


TransmitCommChar
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


TransmitFile
Windows NT	Yes
Win95	No
Win32s	No
Import Library	wsock32.lib
Header File	winsock.h
Unicode	No
Platform Notes	None


tree_into_ndr
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcndr.h
Unicode
Platform Notes	None


tree_peek_ndr
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcndr.h
Unicode
Platform Notes	None


tree_size_ndr
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcndr.h
Unicode
Platform Notes	None


UInt32x32To64
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	winnt.h
Unicode	No
Platform Notes	None


UnhandledExceptionFilter
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


UnhookWindowsHook
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


UnhookWindowsHookEx
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


UnionRect
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


UnloadKeyboardLayout
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


UnlockFile
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


UnlockFileEx
Windows NT	Yes
Win95	No
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


UnlockResource
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winbase.h
Unicode	No
Platform Notes	None


UnlockSegment
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winbase.h
Unicode	No
Platform Notes	None


UnlockServiceDatabase
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winsvc.h
Unicode	No
Platform Notes	None


UnmapViewOfFile
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


UnpackDDElParam
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	dde.h
Unicode	No
Platform Notes	None


UnrealizeObject
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


UnregisterClass
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


UnregisterHotKey
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


UpdateColors
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


UpdateResource
Windows NT	Yes
Win95	No
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


UpdateWindow
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


UuidCompare
Windows NT	New
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode	No
Platform Notes	None


UuidCreate
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode	No
Platform Notes	None


UuidCreateNil
Windows NT	New
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode	No
Platform Notes	None


UuidEqual
Windows NT	New
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode	No
Platform Notes	None


UuidFromString
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode	WinNT
Platform Notes	None


UuidHash
Windows NT	New
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode	No
Platform Notes	None


UuidIsNil
Windows NT	New
Win95	Yes
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode	No
Platform Notes	None


UuidToString
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode	WinNT
Platform Notes	None


ValidateRect
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


ValidateRgn
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


VarBoolFromCy
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarBoolFromDate
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarBoolFromDisp
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarBoolFromI2
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarBoolFromI4
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarBoolFromR4
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarBoolFromR8
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarBoolFromStr
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	WinNT; Win95; Win32s
Platform Notes	All 32-bit OLE Apis are UNICODE only


VarBoolFromUI1
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarBstrFromBool
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	WinNT; Win95; Win32s
Platform Notes	All 32-bit OLE Apis are UNICODE only


VarBstrFromCy
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	WinNT; Win95; Win32s
Platform Notes	All 32-bit OLE Apis are UNICODE only


VarBstrFromDate
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	WinNT; Win95; Win32s
Platform Notes	All 32-bit OLE Apis are UNICODE only


VarBstrFromDisp
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	WinNT; Win95; Win32s
Platform Notes	All 32-bit OLE Apis are UNICODE only


VarBstrFromI2
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	WinNT; Win95; Win32s
Platform Notes	All 32-bit OLE Apis are UNICODE only


VarBstrFromI4
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	WinNT; Win95; Win32s
Platform Notes	All 32-bit OLE Apis are UNICODE only


VarBstrFromR4
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	WinNT; Win95; Win32s
Platform Notes	All 32-bit OLE Apis are UNICODE only


VarBstrFromR8
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	WinNT; Win95; Win32s
Platform Notes	All 32-bit OLE Apis are UNICODE only


VarBstrFromUI1
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	WinNT; Win95; Win32s
Platform Notes	All 32-bit OLE Apis are UNICODE only


VarCyFromBool
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarCyFromDate
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarCyFromDisp
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarCyFromI2
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarCyFromI4
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarCyFromR4
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarCyFromR8
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarCyFromStr
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	WinNT; Win95; Win32s
Platform Notes	All 32-bit OLE Apis are UNICODE only


VarCyFromUI1
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarDateFromBool
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarDateFromCy
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarDateFromDisp
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarDateFromI2
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarDateFromI4
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarDateFromR4
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarDateFromR8
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarDateFromStr
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	WinNT; Win95; Win32s
Platform Notes	All 32-bit OLE Apis are UNICODE only


VarDateFromUI1
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarI2FromBool
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarI2FromCy
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarI2FromDate
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarI2FromDisp
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarI2FromI4
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarI2FromR4
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarI2FromR8
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarI2FromStr
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	WinNT; Win95; Win32s
Platform Notes	All 32-bit OLE Apis are UNICODE only


VarI2FromUI1
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarI4FromBool
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarI4FromCy
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarI4FromDate
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarI4FromDisp
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarI4FromI2
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarI4FromR4
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarI4FromR8
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarI4FromStr
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	WinNT; Win95; Win32s
Platform Notes	All 32-bit OLE Apis are UNICODE only


VarI4FromUI1
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VariantChangeType
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VariantChangeTypeEx
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VariantClear
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VariantCopy
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VariantCopyInd
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VariantInit
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VariantTimeToDosDateTime
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarR4FromBool
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarR4FromCy
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarR4FromDate
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarR4FromDisp
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarR4FromI2
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarR4FromI4
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarR4FromR8
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarR4FromStr
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	WinNT; Win95; Win32s
Platform Notes	All 32-bit OLE Apis are UNICODE only


VarR4FromUI1
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarR8FromBool
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarR8FromCy
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarR8FromDate
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarR8FromDisp
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarR8FromI2
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarR8FromI4
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarR8FromR4
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarR8FromStr
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarR8FromUI1
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarUI1FromBool
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarUI1FromCy
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarUI1FromDate
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarUI1FromDisp
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarUI1FromI2
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarUI1FromI4
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarUI1FromR4
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarUI1FromR8
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


VarUI1FromStr
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	WinNT; Win95; Win32s
Platform Notes	All 32-bit OLE Apis are UNICODE only


VerFindFile
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	version.lib
Header File	winver.h
Unicode	WinNT
Platform Notes	None


VerInstallFile
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	version.lib
Header File	winver.h
Unicode	WinNT
Platform Notes	None


VerLanguageName
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winver.h
Unicode	WinNT
Platform Notes	None


VerQueryValue
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	version.lib
Header File	winver.h
Unicode	WinNT
Platform Notes	None


VideoForWindowsVersion
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


VirtualAlloc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


VirtualFree
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


VirtualLock
Windows NT	Yes
Win95	Stub
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


VirtualProtect
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


VirtualProtectEx
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


VirtualQuery
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


VirtualQueryEx
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


VirtualUnlock
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


VkKeyScan
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


VkKeyScanEx
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


WaitCommEvent
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


WaitForDebugEvent
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


WaitForInputIdle
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


WaitForMultipleObjects
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


WaitForMultipleObjectsEx
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


WaitForPrinterChange
Windows NT	Yes
Win95	No
Win32s	No
Import Library	winspool.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


WaitForSingleObject
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


WaitForSingleObjectEx
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


WaitMessage
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


WaitNamedPipe
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


waveInAddBuffer
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


waveInClose
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


waveInGetDevCaps
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	WinNT
Platform Notes	None


waveInGetErrorText
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	WinNT
Platform Notes	None


waveInGetID
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


waveInGetNumDevs
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


waveInGetPosition
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


waveInMessage
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


waveInOpen
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


waveInPrepareHeader
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


waveInReset
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


waveInStart
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


waveInStop
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


waveInUnprepareHeader
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


waveOutBreakLoop
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


waveOutClose
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


waveOutGetDevCaps
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	WinNT
Platform Notes	None


waveOutGetErrorText
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	WinNT
Platform Notes	None


waveOutGetID
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


waveOutGetNumDevs
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


waveOutGetPitch
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


waveOutGetPlaybackRate
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


waveOutGetPosition
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


waveOutGetVolume
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


waveOutMessage
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


waveOutOpen
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


waveOutPause
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


waveOutPrepareHeader
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


waveOutReset
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


waveOutRestart
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


waveOutSetPitch
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


waveOutSetPlaybackRate
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


waveOutSetVolume
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


waveOutUnprepareHeader
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


waveOutWrite
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


wglCreateContext
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


wglDeleteContext
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


wglGetCurrentContext
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


wglGetCurrentDC
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


wglGetProcAddress
Windows NT	New
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


wglMakeCurrent
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


wglShareLists
Windows NT	New
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	wingdi.h
Unicode
Platform Notes	None


wglUseFontBitmaps
Windows NT	Yes
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	wingdi.h
Unicode	WinNT
Platform Notes	None


wglUseFontOutlines
Windows NT	New
Win95	No
Win32s	No
Import Library	opengl32.lib
Header File	wingdi.h
Unicode	WinNT
Platform Notes	None


WideCharToMultiByte
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winnls.h
Unicode	No
Platform Notes	None


WidenPath
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


WindowFromDC
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


WindowFromPoint
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


WinExec
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


WinHelp
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


WinMain
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winbase.h
Unicode	No
Platform Notes	None


WNetAddConnection
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	mpr.lib
Header File	winnetwk.h
Unicode	WinNT
Platform Notes	None


WNetAddConnection2
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	mpr.lib
Header File	winnetwk.h
Unicode	WinNT
Platform Notes	None


WNetAddConnection3
Windows NT	Yes
Win95
Win32s	No
Import Library	mpr.lib
Header File	winnetwk.h
Unicode	WinNT
Platform Notes	None


WNetCancelConnection
Windows NT	Yes
Win95	Yes
Win32s	1.30 only
Import Library	mpr.lib
Header File	winnetwk.h
Unicode	WinNT
Platform Notes	None


WNetCancelConnection2
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	mpr.lib
Header File	winnetwk.h
Unicode	WinNT
Platform Notes	None


WNetCloseEnum
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	mpr.lib
Header File	winnetwk.h
Unicode	No
Platform Notes	None


WNetConnectionDialog
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	mpr.lib
Header File	winnetwk.h
Unicode	No
Platform Notes	None


WNetDisconnectDialog
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	mpr.lib
Header File	winnetwk.h
Unicode	No
Platform Notes	None


WNetEnumResource
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	mpr.lib
Header File	winnetwk.h
Unicode	WinNT
Platform Notes	None


WNetGetConnection
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	mpr.lib
Header File	winnetwk.h
Unicode	WinNT
Platform Notes	None


WNetGetLastError
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	mpr.lib
Header File	winnetwk.h
Unicode	WinNT
Platform Notes	None


WNetGetUniversalName
Windows NT	Yes
Win95
Win32s	No
Import Library	mpr.lib
Header File	winnetwk.h
Unicode	WinNT
Platform Notes	None


WNetGetUser
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	mpr.lib
Header File	winnetwk.h
Unicode	WinNT
Platform Notes	None


WNetOpenEnum
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	mpr.lib
Header File	winnetwk.h
Unicode	WinNT
Platform Notes	None


WriteClassStg
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


WriteClassStm
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


WriteConsole
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	wincon.h
Unicode	WinNT
Platform Notes	None


WriteConsoleInput
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	wincon.h
Unicode	WinNT
Platform Notes	None


WriteConsoleOutput
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	wincon.h
Unicode	WinNT
Platform Notes	None


WriteConsoleOutputAttribute
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	wincon.h
Unicode	No
Platform Notes	None


WriteConsoleOutputCharacter
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	wincon.h
Unicode	WinNT
Platform Notes	None


WriteFile
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	New
Platform Notes	Windows 95: No overlapped regions


WriteFileEx
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	Windows 95 limitations


WriteFmtUserTypeStg
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	WinNT; Win95; Win32s
Platform Notes	All 32-bit OLE Apis are UNICODE only


WritePrinter
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	winspool.lib
Header File	winspool.h
Unicode	No
Platform Notes	None


WritePrivateProfileSection
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


WritePrivateProfileString
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


WritePrivateProfileStruct
Windows NT	Yes
Win95	Yes
Win32s
Import Library
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


WriteProcessMemory
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


WriteProfileSection
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


WriteProfileString
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


WriteTapemark
Windows NT	Yes
Win95	No
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


WSAAsyncGetHostByAddr
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	wsock32.lib
Header File	winsock.h
Unicode	No
Platform Notes	None


WSAAsyncGetHostByName
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	wsock32.lib
Header File	winsock.h
Unicode	No
Platform Notes	None


WSAAsyncGetProtoByName
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	wsock32.lib
Header File	winsock.h
Unicode	No
Platform Notes	None


WSAAsyncGetProtoByNumber
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	wsock32.lib
Header File	winsock.h
Unicode	No
Platform Notes	None


WSAAsyncGetServByName
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	wsock32.lib
Header File	winsock.h
Unicode	No
Platform Notes	None


WSAAsyncGetServByPort
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	wsock32.lib
Header File	winsock.h
Unicode	No
Platform Notes	None


WSAAsyncSelect
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	wsock32.lib
Header File	winsock.h
Unicode	No
Platform Notes	None


WSACancelAsyncRequest
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	wsock32.lib
Header File	winsock.h
Unicode	No
Platform Notes	None


WSACancelBlockingCall
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	wsock32.lib
Header File	winsock.h
Unicode	No
Platform Notes	None


WSACleanup
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	wsock32.lib
Header File	winsock.h
Unicode	No
Platform Notes	None


WSAGetLastError
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	wsock32.lib
Header File	winsock.h
Unicode	No
Platform Notes	None


WSAIsBlocking
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	wsock32.lib
Header File	winsock.h
Unicode	No
Platform Notes	None


WSARecvEx
Windows NT	Yes
Win95
Win32s	No
Import Library	wsock32.lib
Header File	winsock.h
Unicode	No
Platform Notes	None


WSASetBlockingHook
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	wsock32.lib
Header File	winsock.h
Unicode	No
Platform Notes	None


WSASetLastError
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	wsock32.lib
Header File	winsock.h
Unicode	No
Platform Notes	None


WSAStartup
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	wsock32.lib
Header File	winsock.h
Unicode	No
Platform Notes	None


WSAUnhookBlockingHook
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	wsock32.lib
Header File	winsock.h
Unicode	No
Platform Notes	None


wsprintf
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


wvsprintf
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


ZeroMemory
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winbase.h
Unicode	No
Platform Notes	None


IAVIEditStream::Clone
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h; aviiface.h
Unicode
Platform Notes	None


IAVIEditStream::Copy
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h; aviiface.h
Unicode
Platform Notes	None


IAVIEditStream::Cut
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h; aviiface.h
Unicode
Platform Notes	None


IAVIEditStream::Paste
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h; aviiface.h
Unicode
Platform Notes	None


IAVIEditStream::SetInfo
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h; aviiface.h
Unicode
Platform Notes	None


IAVIFile::CreateStream
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h; aviiface.h
Unicode
Platform Notes	None


IAVIFile::EndRecord
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h; aviiface.h
Unicode
Platform Notes	None


IAVIFile::GetStream
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h; aviiface.h
Unicode
Platform Notes	None


IAVIFile::Info
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h; aviiface.h
Unicode
Platform Notes	None


IAVIFile::Open
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h; aviiface.h
Unicode
Platform Notes	None


IAVIFile::ReadData
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h; aviiface.h
Unicode
Platform Notes	None


IAVIFile::WriteData
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h; aviiface.h
Unicode
Platform Notes	None


IAVIStream::Create
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h; aviiface.h
Unicode
Platform Notes	None


IAVIStream::Delete
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h; aviiface.h
Unicode
Platform Notes	None


IAVIStream::FindSample
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h; aviiface.h
Unicode
Platform Notes	None


IAVIStream::Info
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h; aviiface.h
Unicode
Platform Notes	None


IAVIStream::Read
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h; aviiface.h
Unicode
Platform Notes	None


IAVIStream::ReadData
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h; aviiface.h
Unicode
Platform Notes	None


IAVIStream::ReadFormat
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h; aviiface.h
Unicode
Platform Notes	None


IAVIStream::SetFormat
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h; aviiface.h
Unicode
Platform Notes	None


IAVIStream::Write
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h; aviiface.h
Unicode
Platform Notes	None


IAVIStream::WriteData
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h; aviiface.h
Unicode
Platform Notes	None


IAVIStreaming::Begin
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h; aviiface.h
Unicode
Platform Notes	None


IAVIStreaming::End
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h; aviiface.h
Unicode
Platform Notes	None


IContextMenu::GetCommandString
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


IContextMenu::InvokeCommand
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


IContextMenu::QueryContextMenu
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


ICopyHook::CopyCallback
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


IEnumIDList::Clone
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


IEnumIDList::Next
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


IEnumIDList::Reset
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


IEnumIDList::Skip
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


IExtractIcon::Extract
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


IExtractIcon::GetIconLocation
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


IFileViewer::PrintTo
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


IFileViewer::Show
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


IFileViewer::ShowInitialize
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


IFileViewerSite::GetPinnedWindow
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


IFileViewerSite::SetPinnedWindow
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


IGetFrame::Begin
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h
Unicode
Platform Notes	None


IGetFrame::End
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h
Unicode
Platform Notes	None


IGetFrame::GetFrame
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h
Unicode
Platform Notes	None


IGetFrame::SetFormat
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h
Unicode
Platform Notes	None


IShellExtInit::Initialize
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


IShellFolder::BindToObject
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


IShellFolder::BindToStorage
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


IShellFolder::CompareIDs
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


IShellFolder::CreateViewObject
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


IShellFolder::EnumObjects
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


IShellFolder::GetAttributesOf
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


IShellFolder::GetDisplayNameOf
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


IShellFolder::GetUIObjectOf
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


IShellFolder::ParseDisplayName
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


IShellFolder::SetNameOf
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


IShellLink::GetArguments
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


IShellLink::GetDescription
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


IShellLink::GetHotkey
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


IShellLink::GetIconLocation
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


IShellLink::GetIDList
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


IShellLink::GetPath
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


IShellLink::GetShowCmd
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


IShellLink::GetWorkingDirectory
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


IShellLink::Resolve
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


IShellLink::SetArguments
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


IShellLink::SetDescription
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


IShellLink::SetHotkey
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


IShellLink::SetIconLocation
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


IShellLink::SetIDList
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


IShellLink::SetPath
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


IShellLink::SetRelativePath
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


IShellLink::SetShowCmd
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


IShellLink::SetWorkingDirectory
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


IShellPropSheetExt::AddPages
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


IShellPropSheetExt::ReplacePage
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


Animate_Close
Windows NT	Yes
Win95	Yes
Win32s
Import Library
Header File	commctrl.h
Unicode	No
Platform Notes	None


Animate_Create
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	commctrl.h
Unicode	No
Platform Notes	None


Animate_Open
Windows NT	Yes
Win95	Yes
Win32s
Import Library
Header File	commctrl.h
Unicode	WinNT
Platform Notes	None


Animate_Play
Windows NT	Yes
Win95	Yes
Win32s
Import Library
Header File	commctrl.h
Unicode	No
Platform Notes	None


Animate_Seek
Windows NT	Yes
Win95	Yes
Win32s
Import Library
Header File	commctrl.h
Unicode	No
Platform Notes	None


Animate_Stop
Windows NT	Yes
Win95	Yes
Win32s
Import Library
Header File	commctrl.h
Unicode	No
Platform Notes	None


AVIStreamDataSize
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h
Unicode
Platform Notes	None


AVIStreamEnd
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h
Unicode
Platform Notes	None


AVIStreamEndTime
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h
Unicode
Platform Notes	None


AVIStreamFormatSize
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h
Unicode
Platform Notes	None


AVIStreamIsKeyFrame
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h
Unicode
Platform Notes	None


AVIStreamLengthTime
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h
Unicode
Platform Notes	None


AVIStreamNearestKeyFrame
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h
Unicode
Platform Notes	None


AVIStreamNearestKeyFrameTime
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h
Unicode
Platform Notes	None


AVIStreamNearestSample
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h
Unicode
Platform Notes	None


AVIStreamNearestSampleTime
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h
Unicode
Platform Notes	None


AVIStreamNextKeyFrame
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h
Unicode
Platform Notes	None


AVIStreamNextKeyFrameTime
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h
Unicode
Platform Notes	None


AVIStreamNextSample
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h
Unicode
Platform Notes	None


AVIStreamNextSampleTime
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h
Unicode
Platform Notes	None


AVIStreamPrevKeyFrame
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h
Unicode
Platform Notes	None


AVIStreamPrevKeyFrameTime
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h
Unicode
Platform Notes	None


AVIStreamPrevSample
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h
Unicode
Platform Notes	None


AVIStreamPrevSampleTime
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h
Unicode
Platform Notes	None


AVIStreamSampleSize
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h
Unicode
Platform Notes	None


AVIStreamSampleToSample
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h
Unicode
Platform Notes	None


AVIStreamStartTime
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h
Unicode
Platform Notes	None


CMYK
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	wingdi.h
Unicode	No
Platform Notes	None


DrawDibUpdate
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	vfw.h
Unicode	No
Platform Notes	None


FORWARD_WM_NOTIFY
Windows NT	Yes
Win95	Yes
Win32s
Import Library
Header File	commctrl.h
Unicode	No
Platform Notes	None


GetBValue
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	wingdi.h
Unicode	No
Platform Notes	None


GetCValue
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	wingdi.h
Unicode	No
Platform Notes	None


GetGValue
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	wingdi.h
Unicode	No
Platform Notes	None


GetKValue
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	wingdi.h
Unicode	No
Platform Notes	None


GetMValue
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	wingdi.h
Unicode	No
Platform Notes	None


GetRValue
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	wingdi.h
Unicode	No
Platform Notes	None


GetYValue
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	wingdi.h
Unicode	No
Platform Notes	None


HANDLE_WM_NOTIFY
Windows NT	Yes
Win95	Yes
Win32s
Import Library
Header File	commctrl.h
Unicode	No
Platform Notes	None


HIBYTE
Windows NT	Yes
Win95	Yes
Win32s
Import Library
Header File	windef.h
Unicode	No
Platform Notes	None


HIWORD
Windows NT	Yes
Win95	Yes
Win32s
Import Library
Header File	windef.h
Unicode	No
Platform Notes	None


ICAbout
Windows NT	New
Win95	Yes
Win32s	No
Import Library
Header File	vfw.h
Unicode	No
Platform Notes	None


ICCompressBegin
Windows NT	New
Win95	Yes
Win32s	No
Import Library
Header File	vfw.h
Unicode	No
Platform Notes	None


ICCompressEnd
Windows NT	New
Win95	Yes
Win32s	No
Import Library
Header File	vfw.h
Unicode	No
Platform Notes	None


ICCompressGetFormat
Windows NT	New
Win95	Yes
Win32s	No
Import Library
Header File	vfw.h
Unicode	No
Platform Notes	None


ICCompressGetFormatSize
Windows NT	New
Win95	Yes
Win32s	No
Import Library
Header File	vfw.h
Unicode	No
Platform Notes	None


ICCompressGetSize
Windows NT	New
Win95	Yes
Win32s	No
Import Library
Header File	vfw.h
Unicode	No
Platform Notes	None


ICCompressQuery
Windows NT	New
Win95	Yes
Win32s	No
Import Library
Header File	vfw.h
Unicode	No
Platform Notes	None


ICConfigure
Windows NT	New
Win95	Yes
Win32s	No
Import Library
Header File	vfw.h
Unicode	No
Platform Notes	None


ICDecompressBegin
Windows NT	New
Win95	Yes
Win32s	No
Import Library
Header File	vfw.h
Unicode	No
Platform Notes	None


ICDecompressEnd
Windows NT	New
Win95	Yes
Win32s	No
Import Library
Header File	vfw.h
Unicode	No
Platform Notes	None


ICDecompressGetFormat
Windows NT	New
Win95	Yes
Win32s	No
Import Library
Header File	vfw.h
Unicode	No
Platform Notes	None


ICDecompressGetFormatSize
Windows NT	New
Win95	Yes
Win32s	No
Import Library
Header File	vfw.h
Unicode	No
Platform Notes	None


ICDecompressGetPalette
Windows NT	New
Win95	Yes
Win32s	No
Import Library
Header File	vfw.h
Unicode	No
Platform Notes	None


ICDecompressOpen
Windows NT	New
Win95	Yes
Win32s	No
Import Library
Header File	vfw.h
Unicode	No
Platform Notes	None


ICDecompressQuery
Windows NT	New
Win95	Yes
Win32s	No
Import Library
Header File	vfw.h
Unicode	No
Platform Notes	None


ICDrawEnd
Windows NT	New
Win95	Yes
Win32s	No
Import Library
Header File	vfw.h
Unicode	No
Platform Notes	None


ICDrawFlush
Windows NT	New
Win95	Yes
Win32s	No
Import Library
Header File	vfw.h
Unicode	No
Platform Notes	None


ICDrawGetTime
Windows NT	New
Win95	Yes
Win32s	No
Import Library
Header File	vfw.h
Unicode	No
Platform Notes	None


ICDrawOpen
Windows NT	New
Win95	Yes
Win32s	No
Import Library
Header File	vfw.h
Unicode	No
Platform Notes	None


ICDrawQuery
Windows NT	New
Win95	Yes
Win32s	No
Import Library
Header File	vfw.h
Unicode	No
Platform Notes	None


ICDrawRealize
Windows NT	New
Win95	Yes
Win32s	No
Import Library
Header File	vfw.h
Unicode	No
Platform Notes	None


ICDrawSetTime
Windows NT	New
Win95	Yes
Win32s	No
Import Library
Header File	vfw.h
Unicode	No
Platform Notes	None


ICDrawStart
Windows NT	New
Win95	Yes
Win32s	No
Import Library
Header File	vfw.h
Unicode	No
Platform Notes	None


ICDrawStartPlay
Windows NT	New
Win95	Yes
Win32s	No
Import Library
Header File	vfw.h
Unicode	No
Platform Notes	None


ICDrawStop
Windows NT	New
Win95	Yes
Win32s	No
Import Library
Header File	vfw.h
Unicode	No
Platform Notes	None


ICDrawStopPlay
Windows NT	New
Win95	Yes
Win32s	No
Import Library
Header File	vfw.h
Unicode	No
Platform Notes	None


ICDrawWindow
Windows NT	New
Win95	Yes
Win32s	No
Import Library
Header File	vfw.h
Unicode	No
Platform Notes	None


ICGetBuffersWanted
Windows NT	New
Win95	Yes
Win32s	No
Import Library
Header File	vfw.h
Unicode	No
Platform Notes	None


ICGetDefaultKeyFrameRate
Windows NT	New
Win95	Yes
Win32s	No
Import Library
Header File	vfw.h
Unicode	No
Platform Notes	None


ICGetDefaultQuality
Windows NT	New
Win95	Yes
Win32s	No
Import Library
Header File	vfw.h
Unicode	No
Platform Notes	None


ICGetState
Windows NT	New
Win95	Yes
Win32s	No
Import Library
Header File	vfw.h
Unicode	No
Platform Notes	None


ICGetStateSize
Windows NT	New
Win95	Yes
Win32s	No
Import Library
Header File	vfw.h
Unicode	No
Platform Notes	None


ICQueryAbout
Windows NT	New
Win95	Yes
Win32s	No
Import Library
Header File	vfw.h
Unicode	No
Platform Notes	None


ICQueryConfigure
Windows NT	New
Win95	Yes
Win32s	No
Import Library
Header File	vfw.h
Unicode	No
Platform Notes	None


ImageList_AddIcon
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	commctrl.h
Unicode	No
Platform Notes	None


INDEXTOOVERLAYMASK
Windows NT	New
Win95	Yes
Win32s	No
Import Library
Header File	commctrl.h
Unicode	No
Platform Notes	None


INDEXTOSTATEIMAGEMASK
Windows NT	New
Win95	Yes
Win32s	No
Import Library
Header File	commctrl.h
Unicode	No
Platform Notes	None


LANGIDFROMLCID
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winnt.h
Unicode	No
Platform Notes	None


LOBYTE
Windows NT	Yes
Win95	Yes
Win32s
Import Library
Header File	windef.h
Unicode	No
Platform Notes	None


LOWORD
Windows NT	Yes
Win95	Yes
Win32s
Import Library
Header File	windef.h
Unicode	No
Platform Notes	None


MAKEINTATOM
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winbase.h
Unicode	No
Platform Notes	None


MAKEINTRESOURCE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


MAKELANGID
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winnt.h
Unicode	No
Platform Notes	None


MAKELCID
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winnt.h
Unicode	No
Platform Notes	None


MAKELONG
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	windef.h
Unicode	No
Platform Notes	None


MAKELPARAM
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


MAKELRESULT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


MAKEPOINTS
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	wingdi.h
Unicode	No
Platform Notes	None


MAKEROP4
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	wingdi.h
Unicode	No
Platform Notes	None


MAKEWORD
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	windef.h
Unicode	No
Platform Notes	None


MAKEWPARAM
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


max
Windows NT	Yes
Win95	Yes
Win32s
Import Library
Header File	windef.h
Unicode	No
Platform Notes	None


MCI_HMS_HOUR
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MCI_HMS_MINUTE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MCI_HMS_SECOND
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MCI_MAKE_HMS
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MCI_MAKE_MSF
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MCI_MAKE_TMSF
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MCI_MSF_FRAME
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MCI_MSF_MINUTE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MCI_MSF_SECOND
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MCI_TMSF_FRAME
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MCI_TMSF_MINUTE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MCI_TMSF_SECOND
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MCI_TMSF_TRACK
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MCIWndCanConfig
Windows NT
Win95	Yes
Win32s
Import Library
Header File	vfw.h
Unicode
Platform Notes	None


MCIWndCanEject
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndCanPlay
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndCanRecord
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndCanSave
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndCanWindow
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndChangeStyles
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndClose
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndDestroy
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndEject
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndEnd
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndGetActiveTimer
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndGetAlias
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndGetDest
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndGetDevice
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndGetDeviceID
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndGetEnd
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndGetError
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndGetFileName
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndGetInactiveTimer
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndGetLength
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndGetMode
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndGetPalette
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndGetPosition
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndGetPositionString
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndGetRepeat
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndGetSource
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndGetSpeed
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndGetStart
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndGetStyles
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndGetTimeFormat
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndGetVolume
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndGetZoom
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndHome
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndNew
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndOpen
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndOpenDialog
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndOpenInterface
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndPause
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndPlay
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndPlayFrom
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndPlayFromTo
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndPlayReverse
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndPlayTo
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndPutDest
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndPutSource
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndRealize
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndRecord
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndResume
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndReturnString
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndSave
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndSaveDialog
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndSeek
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndSendString
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndSetActiveTimer
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndSetInactiveTimer
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndSetOwner
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndSetPalette
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndSetRepeat
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndSetSpeed
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndSetTimeFormat
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndSetTimers
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndSetVolume
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndSetZoom
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndStep
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndStop
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndUseFrames
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndUseTime
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWndValidateMedia
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MEVT_EVENTPARM
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File
Unicode
Platform Notes	None


MEVT_EVENTTYPE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File
Unicode
Platform Notes	None


min
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File
Unicode
Platform Notes	None


mmioFOURCC
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


PALETTEINDEX
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	wingdi.h
Unicode	No
Platform Notes	None


PALETTERGB
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	wingdi.h
Unicode	No
Platform Notes	None


POINTSTOPOINT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


POINTTOPOINTS
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


PRIMARYLANGID
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winnt.h
Unicode	No
Platform Notes	None


RGB
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	wingdi.h
Unicode	No
Platform Notes	None


SHGetNameMappingCount
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


SHGetNameMappingPtr
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


SORTIDFROMLCID
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winnt.h
Unicode	No
Platform Notes	None


SUBLANGID
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winnt.h
Unicode	No
Platform Notes	None


TEXT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File
Unicode
Platform Notes	None


ABM_ACTIVATE
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shellapi.h
Unicode
Platform Notes	None


ABM_GETAUTOHIDEBAR
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shellapi.h
Unicode
Platform Notes	None


ABM_GETSTATE
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shellapi.h
Unicode
Platform Notes	None


ABM_GETTASKBARPOS
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shellapi.h
Unicode
Platform Notes	None


ABM_NEW
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shellapi.h
Unicode
Platform Notes	None


ABM_QUERYPOS
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shellapi.h
Unicode
Platform Notes	None


ABM_REMOVE
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shellapi.h
Unicode
Platform Notes	None


ABM_SETAUTOHIDEBAR
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shellapi.h
Unicode
Platform Notes	None


ABM_SETPOS
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shellapi.h
Unicode
Platform Notes	None


ABM_WINDOWPOSCHANGED
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shellapi.h
Unicode
Platform Notes	None


ABN_FULLSCREENAPP
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shellapi.h
Unicode
Platform Notes	None


ABN_POSCHANGED
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shellapi.h
Unicode
Platform Notes	None


ABN_STATECHANGE
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shellapi.h
Unicode
Platform Notes	None


ABN_WINDOWARRANGE
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shellapi.h
Unicode
Platform Notes	None


ACM_OPEN
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ACM_PLAY
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ACM_STOP
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ACN_START
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ACN_STOP
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


BM_CLICK
Windows NT	Yes
Win95	Yes
Win32s
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


BM_GETCHECK
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


BM_GETSTATE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


BM_SETCHECK
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


BM_SETSTATE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


BM_SETSTYLE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


BN_CLICKED
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


BN_DBLCLK
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


BN_DISABLE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


BN_DOUBLECLICKED
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


BN_HILITE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


BN_KILLFOCUS
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


BN_PAINT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


BN_PUSHED
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


BN_SETFOCUS
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


BN_UNHILITE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


BN_UNPUSHED
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CB_ADDSTRING
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CB_DELETESTRING
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CB_DIR
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CB_FINDSTRING
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CB_FINDSTRINGEXACT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CB_GETCOUNT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CB_GETCURSEL
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CB_GETDROPPEDCONTROLRECT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CB_GETDROPPEDSTATE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CB_GETDROPPEDWIDTH
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CB_GETEDITSEL
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CB_GETEXTENDEDUI
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CB_GETHORIZONTALEXTENT
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CB_GETITEMDATA
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CB_GETITEMHEIGHT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CB_GETLBTEXT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CB_GETLBTEXTLEN
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CB_GETLOCALE
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CB_GETTOPINDEX
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CB_INITSTORAGE
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CB_INSERTSTRING
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CB_LIMITTEXT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CB_MSGMAX
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CB_RESETCONTENT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CB_SELECTSTRING
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CB_SETCURSEL
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CB_SETDROPPEDWIDTH
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CB_SETEDITSEL
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CB_SETEXTENDEDUI
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CB_SETHORIZONTALEXTENT
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CB_SETITEMDATA
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CB_SETITEMHEIGHT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CB_SETLOCALE
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CB_SETTOPINDEX
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CB_SHOWDROPDOWN
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CBN_CLOSEUP
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CBN_DBLCLK
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CBN_DROPDOWN
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CBN_EDITCHANGE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CBN_EDITUPDATE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CBN_ERRSPACE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CBN_KILLFOCUS
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CBN_SELCHANGE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CBN_SELENDCANCEL
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CBN_SELENDOK
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CBN_SETFOCUS
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CPL_DBLCLK
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	cpl.h
Unicode	No
Platform Notes	None


CPL_EXIT
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	cpl.h
Unicode	No
Platform Notes	None


CPL_GETCOUNT
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	cpl.h
Unicode	No
Platform Notes	None


CPL_INIT
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	cpl.h
Unicode	No
Platform Notes	None


CPL_INQUIRE
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	cpl.h
Unicode	No
Platform Notes	None


CPL_NEWINQUIRE
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	cpl.h
Unicode	No
Platform Notes	None


CPL_SELECT
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	cpl.h
Unicode	No
Platform Notes	None


CPL_STOP
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	cpl.h
Unicode	No
Platform Notes	None


DBT_APPYBEGIN
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	dbt.h
Unicode
Platform Notes	None


DBT_APPYEND
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	dbt.h
Unicode
Platform Notes	None


DBT_CONFIGCHANGECANCELED
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	dbt.h
Unicode
Platform Notes	None


DBT_CONFIGCHANGED
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	dbt.h
Unicode
Platform Notes	None


DBT_CONFIGMGAPI32
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	dbt.h
Unicode
Platform Notes	None


DBT_CONFIGMGPRIVATE
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	dbt.h
Unicode
Platform Notes	None


DBT_DEVICEARRIVAL
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	dbt.h
Unicode
Platform Notes	None


DBT_DEVICEQUERYREMOVE
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	dbt.h
Unicode
Platform Notes	None


DBT_DEVICEQUERYREMOVEFAILED
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	dbt.h
Unicode
Platform Notes	None


DBT_DEVICEREMOVECOMPLETE
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	dbt.h
Unicode
Platform Notes	None


DBT_DEVICEREMOVEPENDING
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	dbt.h
Unicode
Platform Notes	None


DBT_DEVICETYPESPECIFIC
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	dbt.h
Unicode
Platform Notes	None


DBT_DEVNODES_CHANGED
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	dbt.h
Unicode
Platform Notes	None


DBT_DEVTYP_OEM
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	dbt.h
Unicode
Platform Notes	None


DBT_DEVTYP_PORT
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	dbt.h
Unicode
Platform Notes	None


DBT_DEVTYP_VOLUME
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	dbt.h
Unicode
Platform Notes	None


DBT_MONITORCHANGE
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	dbt.h
Unicode
Platform Notes	None


DBT_NO_DISK_SPACE
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	dbt.h
Unicode
Platform Notes	None


DBT_QUERYCHANGECONFIG
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	dbt.h
Unicode
Platform Notes	None


DBT_SHELLLOGGEDON
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	dbt.h
Unicode
Platform Notes	None


DBT_USERDEFINED
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	dbt.h
Unicode
Platform Notes	None


DBT_VOLLOCKLOCKFAILED
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	dbt.h
Unicode
Platform Notes	None


DBT_VOLLOCKLOCKRELEASED
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	dbt.h
Unicode
Platform Notes	None


DBT_VOLLOCKLOCKTAKEN
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	dbt.h
Unicode
Platform Notes	None


DBT_VOLLOCKQUERYLOCK
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	dbt.h
Unicode
Platform Notes	None


DBT_VOLLOCKQUERYUNLOCK
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	dbt.h
Unicode
Platform Notes	None


DBT_VOLLOCKUNLOCKFAILED
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	dbt.h
Unicode
Platform Notes	None


DL_BEGINDRAG
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	commctrl.h
Unicode
Platform Notes	None


DL_CANCELDRAG
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	commctrl.h
Unicode
Platform Notes	None


DL_COPYCURSOR
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	commctrl.h
Unicode
Platform Notes	None


DL_CURSORSET
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	commctrl.h
Unicode
Platform Notes	None


DL_DRAGGING
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	commctrl.h
Unicode
Platform Notes	None


DL_DROPPED
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	commctrl.h
Unicode
Platform Notes	None


DL_MOVECURSOR
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	commctrl.h
Unicode
Platform Notes	None


DL_STOPCURSOR
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	commctrl.h
Unicode
Platform Notes	None


DM_GETDEFID
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


DM_REPOSITION
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


DM_SETDEFID
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


DRV_CLOSE
Windows NT
Win95
Win32s
Import Library
Header File	mmsystem.h
Unicode
Platform Notes	None


DRV_CONFIGURE
Windows NT
Win95
Win32s
Import Library
Header File	mmsystem.h
Unicode
Platform Notes	None


DRV_DISABLE
Windows NT
Win95
Win32s
Import Library
Header File	mmsystem.h
Unicode
Platform Notes	None


DRV_ENABLE
Windows NT
Win95
Win32s
Import Library
Header File	mmsystem.h
Unicode
Platform Notes	None


DRV_EXITSESSION
Windows NT
Win95
Win32s
Import Library
Header File	mmsystem.h
Unicode
Platform Notes	None


DRV_FREE
Windows NT
Win95
Win32s
Import Library
Header File	mmsystem.h
Unicode
Platform Notes	None


DRV_INSTALL
Windows NT
Win95
Win32s
Import Library
Header File	mmsystem.h
Unicode
Platform Notes	None


DRV_LOAD
Windows NT
Win95
Win32s
Import Library
Header File	mmsystem.h
Unicode
Platform Notes	None


DRV_OPEN
Windows NT
Win95
Win32s
Import Library
Header File	mmsystem.h
Unicode
Platform Notes	None


DRV_POWER
Windows NT
Win95
Win32s
Import Library
Header File	mmsystem.h
Unicode
Platform Notes	None


DRV_QUERYCONFIGURE
Windows NT
Win95
Win32s
Import Library
Header File	mmsystem.h
Unicode
Platform Notes	None


DRV_REMOVE
Windows NT
Win95
Win32s
Import Library
Header File	mmsystem.h
Unicode
Platform Notes	None


EM_CANPASTE
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	richedit.h
Unicode
Platform Notes	None


EM_CANUNDO
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


EM_CHARFROMPOS
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


EM_DISPLAYBAND
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	richedit.h
Unicode
Platform Notes	None


EM_EMPTYUNDOBUFFER
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


EM_EXGETSEL
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	richedit.h
Unicode
Platform Notes	None


EM_EXLIMITTEXT
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	richedit.h
Unicode
Platform Notes	None


EM_EXLINEFROMCHAR
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	richedit.h
Unicode
Platform Notes	None


EM_EXSETSEL
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	richedit.h
Unicode
Platform Notes	None


EM_FINDTEXT
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	richedit.h
Unicode
Platform Notes	None


EM_FINDTEXT_EX
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	richedit.h
Unicode
Platform Notes	None


EM_FINDWORDBREAK
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	richedit.h
Unicode
Platform Notes	None


EM_FMTLINES
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


EM_FORMATRANGE
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	richedit.h
Unicode
Platform Notes	None


EM_GETCHARFORMAT
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	richedit.h
Unicode
Platform Notes	None


EM_GETEVENTMASK
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	richedit.h
Unicode
Platform Notes	None


EM_GETFIRSTVISIBLELINE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	For Single Line Edit controls Win32s returns 0


EM_GETHANDLE
Windows NT	Yes
Win95	No
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


EM_GETIMECOLOR
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	richedit.h
Unicode
Platform Notes	None


EM_GETIMEOPTIONS
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	richedit.h
Unicode
Platform Notes	None


EM_GETLIMITTEXT
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


EM_GETLINE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


EM_GETLINECOUNT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


EM_GETMARGINS
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


EM_GETMODIFY
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


EM_GETOLEINTERFACE
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	richedit.h
Unicode
Platform Notes	None


EM_GETOPTIONS
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	richedit.h
Unicode
Platform Notes	None


EM_GETOPTIONS
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	richedit.h
Unicode
Platform Notes	None


EM_GETPARAFORMAT
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	richedit.h
Unicode
Platform Notes	None


EM_GETPASSWORDCHAR
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


EM_GETPUNCTUATION
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	richedit.h
Unicode
Platform Notes	None


EM_GETRECT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


EM_GETSEL
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


EM_GETSELTEXT
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	richedit.h
Unicode
Platform Notes	None


EM_GETTEXTRANGE
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	richedit.h
Unicode
Platform Notes	None


EM_GETTHUMB
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


EM_GETWORDBREAKPROC
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


EM_GETWORDBREAKPROCEX
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	richedit.h
Unicode	No
Platform Notes	None


EM_GETWORDWRAPMODE
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	richedit.h
Unicode
Platform Notes	None


EM_HIDESELECTION
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	richedit.h
Unicode
Platform Notes	None


EM_LIMITTEXT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


EM_LINEFROMCHAR
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


EM_LINEINDEX
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


EM_LINELENGTH
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


EM_LINESCROLL
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


EM_PASTESPECIAL
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	richedit.h
Unicode
Platform Notes	None


EM_POSFROMCHAR
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


EM_REPLACESEL
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


EM_REQUESTRESIZE
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	richedit.h
Unicode
Platform Notes	None


EM_SCROLL
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


EM_SCROLLCARET
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


EM_SELECTIONTYPE
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	richedit.h
Unicode
Platform Notes	None


EM_SETBKGNDCOLOR
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	richedit.h
Unicode
Platform Notes	None


EM_SETCHARFORMAT
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	richedit.h
Unicode
Platform Notes	None


EM_SETEVENTMASK
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	richedit.h
Unicode
Platform Notes	None


EM_SETHANDLE
Windows NT	Yes
Win95	No
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


EM_SETIMECOLOR
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	richedit.h
Unicode
Platform Notes	None


EM_SETIMEOPTIONS
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	richedit.h
Unicode
Platform Notes	None


EM_SETLIMITTEXT
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


EM_SETMARGINS
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


EM_SETMODIFY
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


EM_SETOLECALLBACK
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	richedit.h
Unicode
Platform Notes	None


EM_SETOLECALLBACK
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	richedit.h
Unicode
Platform Notes	None


EM_SETOPTIONS
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	richedit.h
Unicode
Platform Notes	None


EM_SETOPTIONS
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	richedit.h
Unicode
Platform Notes	None


EM_SETPARAFORMAT
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	richedit.h
Unicode
Platform Notes	None


EM_SETPASSWORDCHAR
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


EM_SETPUNCTUATION
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	richedit.h
Unicode
Platform Notes	None


EM_SETREADONLY
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


EM_SETRECT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


EM_SETRECTNP
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


EM_SETSEL
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


acmFilterEnum
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	msacm32.lib
Header File	msacm.h
Unicode	WinNT
Platform Notes	None


acmFilterTagDetails
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	msacm32.lib
Header File	msacm.h
Unicode	WinNT
Platform Notes	None


acmFilterTagEnum
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	msacm32.lib
Header File	msacm.h
Unicode	WinNT
Platform Notes	None


acmFormatChoose
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	msacm32.lib
Header File	msacm.h
Unicode	WinNT
Platform Notes	None


acmFormatDetails
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	msacm32.lib
Header File	msacm.h
Unicode	WinNT
Platform Notes	None


acmFormatEnum
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	msacm32.lib
Header File	msacm.h
Unicode	WinNT
Platform Notes	None


acmFormatSuggest
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	msacm32.lib
Header File	msacm.h
Unicode	No
Platform Notes	None


acmFormatTagDetails
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	msacm32.lib
Header File	msacm.h
Unicode	WinNT
Platform Notes	None


acmFormatTagEnum
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	msacm32.lib
Header File	msacm.h
Unicode	WinNT
Platform Notes	None


acmGetVersion
Windows NT	New
Win95	Yes
Win32s	No
Import Library	msacm32.lib
Header File	msacm.h
Unicode	No
Platform Notes	None


acmMetrics
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	msacm32.lib
Header File	msacm.h
Unicode	No
Platform Notes	None


acmStreamClose
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	msacm32.lib
Header File	msacm.h
Unicode	No
Platform Notes	None


acmStreamConvert
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	msacm32.lib
Header File	msacm.h
Unicode	No
Platform Notes	None


acmStreamOpen
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	msacm32.lib
Header File	msacm.h
Unicode	No
Platform Notes	None


acmStreamPrepareHeader
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	msacm32.lib
Header File	msacm.h
Unicode	No
Platform Notes	None


acmStreamReset
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	msacm32.lib
Header File	msacm.h
Unicode	No
Platform Notes	None


acmStreamSize
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	msacm32.lib
Header File	msacm.h
Unicode	No
Platform Notes	None


acmStreamUnprepareHeader
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	msacm32.lib
Header File	msacm.h
Unicode	No
Platform Notes	None


AcsLan
Windows NT	Yes
Win95	No
Win32s	No
Import Library	dlcapi.lib
Header File	dlcapi.h
Unicode	No
Platform Notes	None


ActivateKeyboardLayout
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


AddAccessAllowedAce
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


AddAccessDeniedAce
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


AddAce
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


AddAtom
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


AddAuditAccessAce
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


AddFontResource
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	WinNT
Platform Notes	Windows 95: int == 16 bits


AddForm
Windows NT	Yes
Win95	No
Win32s	No
Import Library	winspool.lib
Header File	winspool.h
Unicode	WinNT
Platform Notes	None


AddJob
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	winspool.lib
Header File	winspool.h
Unicode	WinNT
Platform Notes	None


AddMonitor
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	winspool.lib
Header File	winspool.h
Unicode	WinNT
Platform Notes	None


AddPort
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	winspool.lib
Header File	winspool.h
Unicode	WinNT
Platform Notes	None


AddPrinter
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	winspool.lib
Header File	winspool.h
Unicode	WinNT
Platform Notes	None


AddPrinterDriver
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	winspool.lib
Header File	winspool.h
Unicode	WinNT
Platform Notes	None


AddPrintProcessor
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	winspool.lib
Header File	winspool.h
Unicode	WinNT
Platform Notes	None


AddPrintProvidor
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	winspool.lib
Header File	winspool.h
Unicode	WinNT
Platform Notes	None


AdjustTokenGroups
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


AdjustTokenPrivileges
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


AdjustWindowRect
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


AdjustWindowRectEx
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


AdvancedDocumentProperties
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	winspool.lib
Header File	winspool.h
Unicode	WinNT
Platform Notes	None


AllocateAndInitializeSid
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


AllocateLocallyUniqueId
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


AllocConsole
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	wincon.h
Unicode	No
Platform Notes	None


AngleArc
Windows NT	Yes
Win95	No
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


AnimatePalette
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


AnsiLower
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


AnsiLowerBuff
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


AnsiNext
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


AnsiPrev
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


AnsiToOem
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


AnsiToOemBuff
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


AnsiUpper
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


AnsiUpperBuff
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


AnyPopup
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


AppendMenu
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


Arc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


ArcTo
Windows NT	Yes
Win95	No
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


AreAllAccessesGranted
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


AreAnyAccessesGranted
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


AreFileApisANSI
Windows NT	New
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	On Win32s the file APIs are always ANSI


ArrangeIconicWindows
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


AttachThreadInput
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


auxGetDevCaps
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	WinNT
Platform Notes	None


auxGetNumDevs
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


auxGetVolume
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


auxOutMessage
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


auxSetVolume
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


AVIBuildFilter
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	WinNT
Platform Notes	None


AVIClearClipboard
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


AVIFileAddRef
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


AVIFileCreateStream
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


AVIFileEndRecord
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


AVIFileExit
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


AVIFileGetStream
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


AVIFileInfo
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	WinNT
Platform Notes	None


AVIFileInit
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


AVIFileOpen
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	WinNT
Platform Notes	None


AVIFileReadData
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


AVIFileRelease
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


AVIFileWriteData
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


AVIGetFromClipboard
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


AVIMakeCompressedStream
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


AVIMakeFileFromStreams
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


AVIMakeStreamFromClipboard
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


AVIPutFileOnClipboard
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


AVISave
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	WinNT
Platform Notes	None


AVISaveOptions
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


AVISaveOptionsFree
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


AVISaveV
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	WinNT
Platform Notes	None


AVIStreamAddRef
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


AVIStreamBeginStreaming
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


AVIStreamCreate
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


AVIStreamEndStreaming
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


AVIStreamFindSample
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


AVIStreamGetFrame
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


AVIStreamGetFrameClose
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


AVIStreamGetFrameOpen
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


AVIStreamInfo
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	WinNT
Platform Notes	None


AVIStreamLength
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


AVIStreamOpenFromFile
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	WinNT
Platform Notes	None


AVIStreamRead
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


AVIStreamReadData
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


AVIStreamReadFormat
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


AVIStreamRelease
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


AVIStreamSampleToTime
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


AVIStreamSetFormat
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


AVIStreamStart
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


AVIStreamTimeToSample
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


AVIStreamWrite
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


AVIStreamWriteData
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


BackupEventLog
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


BackupRead
Windows NT	Yes
Win95	No
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


BackupSeek
Windows NT	Yes
Win95	No
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


BackupWrite
Windows NT	Yes
Win95	No
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


Beep
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


BeginDeferWindowPos
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


BeginPaint
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


BeginPath
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


BeginUpdateResource
Windows NT	Yes
Win95	No
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


bind
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	wsock32.lib
Header File	winsock.h
Unicode	No
Platform Notes	None


BindMoniker
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	No
Platform Notes	None


BitBlt
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


EM_SETTABSTOPS
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


EM_SETTARGETDEVICE
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	richedit.h
Unicode
Platform Notes	None


EM_SETWORDBREAK
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


EM_SETWORDBREAKPROC
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


EM_SETWORDBREAKPROCEX
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	richedit.h
Unicode	No
Platform Notes	None


EM_SETWORDWRAPMODE
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	richedit.h
Unicode
Platform Notes	None


EM_STREAMIN
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	richedit.h
Unicode
Platform Notes	None


EM_STREAMOUT
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	richedit.h
Unicode
Platform Notes	None


EM_UNDO
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


EN_CHANGE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


EN_DROPFILES
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	richedit.h
Unicode
Platform Notes	None


EN_ERRSPACE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


EN_HSCROLL
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


EN_KILLFOCUS
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


EN_MAXTEXT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


EN_MSGFILTER
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	richedit.h
Unicode
Platform Notes	None


EN_OLEOPFAILED
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	richedit.h
Unicode
Platform Notes	None


EN_PROTECTED
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	richedit.h
Unicode
Platform Notes	None


EN_REQUESTRESIZE
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	richedit.h
Unicode
Platform Notes	None


EN_SAVECLIPBOARD
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	richedit.h
Unicode
Platform Notes	None


EN_SELCHANGE
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	richedit.h
Unicode
Platform Notes	None


EN_SETFOCUS
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


EN_STOPNOUNDO
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	richedit.h
Unicode
Platform Notes	None


EN_UPDATE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


EN_VSCROLL
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


FM_GETDRIVEINFO
Windows NT	Yes
Win95	No
Win32s	No
Import Library
Header File	wfext.h
Unicode	WinNT
Platform Notes	Windows 95: Only supports 16-bit FileManager


FM_GETFILESEL
Windows NT	Yes
Win95	No
Win32s	No
Import Library
Header File	wfext.h
Unicode	WinNT
Platform Notes	Windows 95: Only supports 16-bit FileManager


FM_GETFILESELLFN
Windows NT	Yes
Win95	No
Win32s	No
Import Library
Header File	wfext.h
Unicode	WinNT
Platform Notes	Windows 95: Only supports 16-bit FileManager


FM_GETFOCUS
Windows NT	Yes
Win95	No
Win32s	No
Import Library
Header File	wfext.h
Unicode	No
Platform Notes	Windows 95: Only supports 16-bit FileManager


FM_GETSELCOUNT
Windows NT	Yes
Win95	No
Win32s	No
Import Library
Header File	wfext.h
Unicode	No
Platform Notes	Windows 95: Only supports 16-bit FileManager


FM_GETSELCOUNTLFN
Windows NT	Yes
Win95	No
Win32s	No
Import Library
Header File	wfext.h
Unicode	No
Platform Notes	Windows 95: Only supports 16-bit FileManager


FM_REFRESH_WINDOWS
Windows NT	Yes
Win95	No
Win32s	No
Import Library
Header File	wfext.h
Unicode	No
Platform Notes	Windows 95: Only supports 16-bit FileManager


FM_RELOAD_EXTENSIONS
Windows NT	Yes
Win95	No
Win32s	No
Import Library
Header File	wfext.h
Unicode	No
Platform Notes	Windows 95: Only supports 16-bit FileManager


FMEVENT_HELPMENUITEM
Windows NT	Yes
Win95	No
Win32s	No
Import Library
Header File	wfext.h
Unicode	No
Platform Notes	Windows 95: Only supports 16-bit FileManager


FMEVENT_HELPSTRING
Windows NT	Yes
Win95	No
Win32s	No
Import Library
Header File	wfext.h
Unicode	No
Platform Notes	Windows 95: Only supports 16-bit FileManager


FMEVENT_INITMENU
Windows NT	Yes
Win95	No
Win32s	No
Import Library
Header File	wfext.h
Unicode	No
Platform Notes	Windows 95: Only supports 16-bit FileManager


FMEVENT_LOAD
Windows NT	Yes
Win95	No
Win32s	No
Import Library
Header File	wfext.h
Unicode	No
Platform Notes	Windows 95: Only supports 16-bit FileManager


FMEVENT_SELCHANGE
Windows NT	Yes
Win95	No
Win32s	No
Import Library
Header File	wfext.h
Unicode	No
Platform Notes	Windows 95: Only supports 16-bit FileManager


FMEVENT_TOOLBARLOAD
Windows NT	Yes
Win95	No
Win32s	No
Import Library
Header File	wfext.h
Unicode	No
Platform Notes	Windows 95: Only supports 16-bit FileManager


FMEVENT_UNLOAD
Windows NT	Yes
Win95	No
Win32s	No
Import Library
Header File	wfext.h
Unicode	No
Platform Notes	Windows 95: Only supports 16-bit FileManager


FMEVENT_USER_REFRESH
Windows NT	Yes
Win95	No
Win32s	No
Import Library
Header File	wfext.h
Unicode	No
Platform Notes	Windows 95: Only supports 16-bit FileManager


HDM_DELETEITEM
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


HDM_GETITEM
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


HDM_GETITEMCOUNT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


HDM_HITTEST
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


HDM_INSERTITEM
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


HDM_LAYOUT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


HDM_SETITEM
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


HDN_BEGINTRACK
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


HDN_DIVIDERDBLCLICK
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


HDN_ENDTRACK
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


HDN_ITEMCHANGED
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


HDN_ITEMCHANGING
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


HDN_ITEMCLICK
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


HDN_ITEMDBLCLICK
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


HDN_TRACK
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


HKM_GETHOTKEY
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


HKM_SETHOTKEY
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


HKM_SETRULES
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICM_ABOUT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICM_COMPRESS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICM_COMPRESS_BEGIN
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICM_COMPRESS_END
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICM_COMPRESS_FRAMES_INFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICM_COMPRESS_GET_FORMAT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICM_COMPRESS_GET_SIZE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICM_COMPRESS_QUERY
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICM_CONFIGURE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICM_DECOMPRESS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICM_DECOMPRESS_BEGIN
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICM_DECOMPRESS_END
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICM_DECOMPRESS_GET_FORMAT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICM_DECOMPRESS_GET_PALETTE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICM_DECOMPRESS_QUERY
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICM_DECOMPRESS_SET_PALETTE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICM_DECOMPRESSEX
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICM_DECOMPRESSEX_BEGIN
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICM_DECOMPRESSEX_END
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICM_DECOMPRESSEX_QUERY
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICM_DRAW
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICM_DRAW_BEGIN
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICM_DRAW_CHANGEPALETTE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICM_DRAW_END
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICM_DRAW_FLUSH
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICM_DRAW_GET_PALETTE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICM_DRAW_GETTIME
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICM_DRAW_QUERY
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICM_DRAW_REALIZE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICM_DRAW_RENDERBUFFER
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICM_DRAW_SETTIME
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICM_DRAW_START
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICM_DRAW_START_PLAY
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICM_DRAW_STOP
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICM_DRAW_STOP_PLAY
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICM_DRAW_SUGGESTFORMAT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICM_DRAW_WINDOW
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICM_GET
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICM_GETBUFFERSWANTED
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICM_GETDEFAULTKEYFRAMERATE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICM_GETDEFAULTQUALITY
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICM_GETINFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICM_GETQUALITY
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICM_GETSTATE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICM_SET_STATUS_PROC
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICM_SETQUALITY
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICM_SETSTATE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


IMC_GETCANDIDATEPOS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


IMC_GETCOMPOSITIONFONT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


IMC_GETCOMPOSITIONWINDOW
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


IMC_GETCONVERSIONMODE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


IMC_GETOPENSTATUS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


IMC_GETSENTENCEMODE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


IMC_GETSTATUSWINDOWPOS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


IMC_SETCANDIDATEPOS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


IMC_SETCOMPOSITIONFONT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


IMC_SETCOMPOSITIONWINDOW
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


IMC_SETCONVERSIONMODE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


IMC_SETOPENSTATUS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


IMC_SETSENTENCEMODE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


IMC_SETSTATUSWINDOWPOS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


IMN_CHANGECANDIDATE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


IMN_CLOSECANDIDATE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


IMN_CLOSESTSTATUSWINDOW
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


IMN_GUIDELINE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


IMN_OPENCANDIDATE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


IMN_OPENSTATUSWINDOW
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


IMN_SETCANDIDATEPOS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


IMN_SETCOMPOSITIONFONT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


IMN_SETCOMPOSITIONWINDOW
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


IMN_SETCONVERSIONMODE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


IMN_SETOPENSTATUS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


IMN_SETSENTENCEMODE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


IMN_SETSTATUSWINDOWPOS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LB_ADDFILE
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


LB_ADDSTRING
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


LB_DELETESTRING
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	Windows 95: wParam is 16-bits


LB_DIR
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


LB_FINDSTRING
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	Windows 95: wParam is 16-bits


LB_FINDSTRINGEXACT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	Windows 95: wParam is 16-bits


LB_GETANCHORINDEX
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


LB_GETCARETINDEX
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


LB_GETCOUNT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


LB_GETCURSEL
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


LB_GETHORIZONTALEXTENT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


LB_GETITEMDATA
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	Windows 95: wParam is 16-bits


LB_GETITEMHEIGHT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	Windows 95: wParam is 16-bits


LB_GETITEMRECT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	Windows 95: wParam is 16-bits


LB_GETLOCALE
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


LB_GETSEL
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	Windows 95: wParam is 16-bits


LB_GETSELCOUNT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


LB_GETSELITEMS
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	Windows 95: wParam is 16-bits


LB_GETTEXT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	Windows 95: wParam is 16-bits


LB_GETTEXTLEN
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	Windows 95: wParam is 16-bits


LB_GETTOPINDEX
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


LB_INITSTORAGE
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


LB_INSERTSTRING
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	Windows 95: wParam is 16-bits


LB_ITEMFROMPOINT
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


LB_RESETCONTENT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


LB_SELECTSTRING
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	Windows 95: wParam is 16-bits


LB_SELITEMRANGE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	Windows 95: wParam is 16-bits


LB_SELITEMRANGEEX
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


LB_SETANCHORINDEX
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


LB_SETCARETINDEX
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	Windows 95: wParam is 16-bits


LB_SETCOLUMNWIDTH
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


LB_SETCOUNT
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


LB_SETCURSEL
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	Windows 95: wParam is 16-bits


LB_SETHORIZONTALEXTENT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


LB_SETITEMDATA
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	Windows 95: wParam is 16-bits


LB_SETITEMHEIGHT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	Windows 95: wParam is 16-bits


LB_SETLOCALE
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


LB_SETSEL
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	Windows 95: wParam is 16-bits


LB_SETTABSTOPS
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


LB_SETTOPINDEX
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	Windows 95: wParam is 16-bits


LBN_DBLCLK
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


LBN_ERRSPACE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


LBN_KILLFOCUS
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


LBN_SELCANCEL
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


LBN_SELCHANGE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


LBN_SETFOCUS
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


LVM_ARRANGE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVM_CREATEDRAGIMAGE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVM_DELETEALLITEMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVM_DELETECOLUMN
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVM_DELETEITEM
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVM_EDITLABEL
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVM_ENSUREVISIBLE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVM_FINDITEM
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVM_GETBKCOLOR
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVM_GETCALLBACKMASK
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVM_GETCOLUMN
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVM_GETCOLUMNWIDTH
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVM_GETCOUNTPERPAGE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVM_GETEDITCONTROL
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVM_GETIMAGELIST
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVM_GETITEM
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVM_GETITEMCOUNT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVM_GETITEMPOSITION
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVM_GETITEMRECT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVM_GETITEMSPACING
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVM_GETITEMSTATE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVM_GETITEMTEXT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVM_GETNEXTITEM
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVM_GETORIGIN
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVM_GETSELECTEDCOUNT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVM_GETSTRINGWIDTH
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVM_GETTEXTBKCOLOR
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVM_GETTEXTCOLOR
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVM_GETTOPINDEX
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVM_GETVIEWRECT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVM_HITTEST
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVM_INSERTCOLUMN
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVM_INSERTITEM
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVM_REDRAWITEMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVM_SCROLL
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVM_SETBKCOLOR
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVM_SETCALLBACKMASK
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVM_SETCOLUMN
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVM_SETCOLUMNWIDTH
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVM_SETIMAGELIST
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVM_SETITEM
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVM_SETITEMCOUNT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVM_SETITEMPOSITION
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVM_SETITEMPOSITION32
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVM_SETITEMSTATE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVM_SETITEMTEXT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVM_SETTEXTBKCOLOR
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVM_SETTEXTCOLOR
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVM_SORTITEMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVM_UPDATE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVN_BEGINDRAG
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVN_BEGINLABELEDIT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVN_BEGINRDRAG
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVN_COLUMNCLICK
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVN_DELETEALLITEMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVN_DELETEITEM
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVN_ENDLABELEDIT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVN_GETDISPINFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVN_INSERTITEM
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVN_ITEMCHANGED
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVN_ITEMCHANGING
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVN_KEYDOWN
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVN_PEN
Windows NT	No
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LVN_SETDISPINFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_BREAK
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MCI_CAPTURE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_CLOSE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MCI_CONFIGURE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_COPY
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MCI_CUE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MCI_CUT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MCI_DELETE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MCI_ESCAPE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MCI_FREEZE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MCI_GETDEVCAPS
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MCI_INDEX
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_INFO
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MCI_LIST
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_LOAD
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MCI_MARK
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_MONITOR
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_OPEN
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MCI_PASTE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MCI_PAUSE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MCI_PLAY
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MCI_PUT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MCI_QUALITY
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_REALIZE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MCI_RECORD
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MCI_RESERVE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_RESTORE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_RESUME
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MCI_SAVE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MCI_SEEK
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MCI_SET
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MCI_SETAUDIO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_SETTIMECODE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_SETTUNER
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_SETVIDEO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_SIGNAL
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_SPIN
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MCI_STATUS
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MCI_STEP
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MCI_STOP
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MCI_SYSINFO
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MCI_UNDO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_UNFREEZE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MCI_UPDATE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MCI_WHERE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MCI_WINDOW
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MCIWNDM_NOTIFYERROR
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWNDM_NOTIFYMEDIA
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWNDM_NOTIFYMODE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWNDM_NOTIFYPOS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCIWNDM_NOTIFYSIZE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MIM_CLOSE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MIM_DATA
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MIM_ERROR
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MIM_LONGDATA
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MIM_LONGERROR
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MIM_MOREDATA
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MIM_OPEN
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MM_ACM_FILTERCHOOSE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MM_ACM_FORMATCHOOSE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MM_JOY1BUTTONDOWN
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MM_JOY1BUTTONUP
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MM_JOY1MOVE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MM_JOY1ZMOVE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MM_JOY2BUTTONDOWN
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MM_JOY2BUTTONUP
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MM_JOY2MOVE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MM_JOY2ZMOVE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MM_MCINOTIFY
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MM_MCISIGNAL
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MM_MIM_CLOSE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MM_MIM_DATA
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MM_MIM_ERROR
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MM_MIM_LONGDATA
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MM_MIM_LONGERROR
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MM_MIM_MOREDATA
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MM_MIM_OPEN
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MM_MIXM_CONTROL_CHANGE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MM_MIXM_LINE_CHANGE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MM_MOM_CLOSE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MM_MOM_DONE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MM_MOM_OPEN
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MM_MOM_POSITIONCB
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MM_WIM_CLOSE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MM_WIM_DATA
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MM_WIM_OPEN
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MM_WOM_CLOSE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MM_WOM_DONE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MM_WOM_OPEN
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MMIOM_CLOSE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MMIOM_OPEN
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MMIOM_READ
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MMIOM_RENAME
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MMIOM_SEEK
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MMIOM_WRITE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MMIOM_WRITEFLUSH
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MOM_CLOSE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MOM_DONE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MOM_OPEN
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


MOM_POSITIONCB
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


NIM_ADD
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shellapi.h
Unicode
Platform Notes	None


NIM_DELETE
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shellapi.h
Unicode
Platform Notes	None


NIM_MODIFY
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shellapi.h
Unicode
Platform Notes	None


NM_CLICK
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


NM_DBLCLK
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


NM_ENDWAIT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


NM_KILLFOCUS
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


NM_OUTOFMEMORY
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


NM_RCLICK
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


NM_RDBLCLK
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


NM_RETURN
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


NM_SETFOCUS
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


NM_STARTWAIT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PBM_DELTAPOS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PBM_SETPOS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PBM_SETRANGE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PBM_SETSTEP
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PBM_STEPIT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PBT_APMBATTERYLOW
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	pbt.h
Unicode
Platform Notes	None


PBT_APMOEMEVENT
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	pbt.h
Unicode
Platform Notes	None


PBT_APMPOWERSTATUSCHANGE
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	pbt.h
Unicode
Platform Notes	None


PBT_APMQUERYSTANDBY
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	pbt.h
Unicode
Platform Notes	None


PBT_APMQUERYSTANDBYFAILED
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	pbt.h
Unicode
Platform Notes	None


PBT_APMQUERYSUSPEND
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	pbt.h
Unicode
Platform Notes	None


PBT_APMQUERYSUSPENDFAILED
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	pbt.h
Unicode
Platform Notes	None


PBT_APMRESUMECRITICAL
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	pbt.h
Unicode
Platform Notes	None


PBT_APMRESUMEFROMFAILURE
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	pbt.h
Unicode
Platform Notes	None


PBT_APMRESUMESTANDBY
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	pbt.h
Unicode
Platform Notes	None


PBT_APMRESUMESUSPEND
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	pbt.h
Unicode
Platform Notes	None


PBT_APMSTANDBY
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	pbt.h
Unicode
Platform Notes	None


PBT_APMSUSPEND
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	pbt.h
Unicode
Platform Notes	None


PSM_ADDPAGE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PSM_APPLY
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PSM_CANCELTOCLOSE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PSM_CHANGED
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PSM_GETTABCONTROL
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PSM_PRESSBUTTON
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PSM_QUERYSIBLINGS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PSM_REBOOTSYSTEM
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PSM_REMOVEPAGE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PSM_RESTARTWINDOWS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PSM_SETCURSEL
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PSM_SETCURSELID
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PSM_SETFINISHTEXT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PSM_SETTITLE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PSM_SETWIZBUTTONS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PSM_UNCHANGED
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PSN_APPLY
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PSN_HASHELP
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PSN_HELP
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PSN_KILLACTIVE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PSN_QUERYCANCEL
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PSN_RESET
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PSN_SETACTIVE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PSN_WIZBACK
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PSN_WIZFINISH
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PSN_WIZNEXT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


SB_GETBORDERS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


SB_GETPARTS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


SB_GETRECT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


SB_GETTEXT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


SB_GETTEXTLENGTH
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


SB_SETMINHEIGHT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


SB_SETPARTS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


SB_SETTEXT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


SB_SIMPLE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


SBM_ENABLE_ARROWS
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


SBM_GETPOS
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


SBM_GETRANGE
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


SBM_GETSCROLLINFO
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


SBM_SETPOS
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


SBM_SETRANGE
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


SBM_SETRANGEREDRAW
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


SBM_SETSCROLLINFO
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


STM_GETICON
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


STM_GETIMAGE
Windows NT	Yes
Win95	Yes
Win32s
Import Library
Header File	winuser.h
Unicode
Platform Notes	None


STM_SETICON
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


STM_SETIMAGE
Windows NT	Yes
Win95	Yes
Win32s
Import Library
Header File	winuser.h
Unicode
Platform Notes	None


STN_CLICKED
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


STN_DBLCLK
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


STN_DISABLE
Windows NT	No
Win95	Yes
Win32s
Import Library
Header File	winuser.h
Unicode
Platform Notes	None


STN_ENABLE
Windows NT	No
Win95	Yes
Win32s
Import Library
Header File	winuser.h
Unicode
Platform Notes	None


TB_ADDBITMAP
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TB_ADDBUTTONS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TB_ADDSTRING
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TB_AUTOSIZE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TB_BUTTONCOUNT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TB_BUTTONSTRUCTSIZE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TB_CHANGEBITMAP
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TB_CHECKBUTTON
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TB_COMMANDTOINDEX
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TB_CUSTOMIZE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TB_DELETEBUTTON
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TB_ENABLEBUTTON
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TB_GETBITMAP
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TB_GETBITMAPFLAGS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TB_GETBUTTON
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TB_GETBUTTONTEXT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TB_GETITEMRECT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TB_GETROWS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TB_GETSTATE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TB_GETTOOLTIPS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TB_HIDEBUTTON
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TB_INDETERMINATE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TB_INSERTBUTTON
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TB_ISBUTTONCHECKED
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TB_ISBUTTONENABLED
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TB_ISBUTTONHIDDEN
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TB_ISBUTTONINDETERMINATE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TB_ISBUTTONPRESSED
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TB_PRESSBUTTON
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TB_SAVERESTORE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TB_SETBITMAPSIZE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TB_SETBUTTONSIZE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TB_SETCMDID
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TB_SETPARENT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TB_SETROWS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TB_SETSTATE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TB_SETTOOLTIPS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TBM_CLEARSEL
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TBM_CLEARTICS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TBM_GETCHANNELRECT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TBM_GETLINESIZE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TBM_GETNUMTICS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TBM_GETPAGESIZE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TBM_GETPOS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TBM_GETPTICS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TBM_GETRANGEMAX
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TBM_GETRANGEMIN
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TBM_GETSELEND
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TBM_GETSELSTART
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TBM_GETTHUMBLENGTH
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TBM_GETTHUMBRECT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TBM_GETTIC
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TBM_GETTICPOS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TBM_SETLINESIZE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TBM_SETPAGESIZE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TBM_SETPOS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TBM_SETRANGE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TBM_SETRANGEMAX
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TBM_SETRANGEMIN
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TBM_SETSEL
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TBM_SETSELEND
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TBM_SETSELSTART
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TBM_SETTHUMBLENGTH
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TBM_SETTIC
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TBM_SETTICFREQ
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TBN_BEGINADJUST
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TBN_BEGINDRAG
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TBN_CUSTHELP
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TBN_ENDADJUST
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TBN_ENDDRAG
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TBN_GETBUTTONINFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TBN_QUERYDELETE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TBN_QUERYINSERT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TBN_RESET
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TBN_TOOLBARCHANGE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TCM_ADJUSTRECT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TCM_DELETEALLITEMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TCM_DELETEITEM
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TCM_GETBKCOLOR
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TCM_GETCURFOCUS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TCM_GETCURSEL
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TCM_GETIMAGELIST
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TCM_GETITEM
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TCM_GETITEMCOUNT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TCM_GETITEMRECT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TCM_GETROWCOUNT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TCM_GETTOOLTIPS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TCM_HITTEST
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TCM_INSERTITEM
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TCM_REMOVEIMAGE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TCM_SETBKCOLOR
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TCM_SETCURSEL
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TCM_SETIMAGELIST
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TCM_SETITEM
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TCM_SETITEMEXTRA
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TCM_SETITEMSIZE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TCM_SETPADDING
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TCM_SETTOOLTIPS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TCN_KEYDOWN
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TCN_SELCHANGE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TCN_SELCHANGING
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TTM_ACTIVATE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TTM_ADDTOOL
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TTM_DELTOOL
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TTM_ENUMTOOLS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TTM_GETCURRENTTOOL
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TTM_GETTEXT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TTM_GETTOOLCOUNT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TTM_GETTOOLINFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TTM_HITTEST
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TTM_NEWTOOLRECT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TTM_RELAYEVENT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TTM_SETDELAYTIME
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TTM_SETTOOLINFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TTM_UPDATETIPTEXT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TTM_WINDOWFROMPOINT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TTN_NEEDTEXT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TTN_POP
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TTN_SHOW
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TVM_CREATEDRAGIMAGE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TVM_DELETEITEM
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TVM_EDITLABEL
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TVM_ENDEDITLABELNOW
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TVM_ENSUREVISIBLE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TVM_EXPAND
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TVM_GETCOUNT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TVM_GETEDITCONTROL
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TVM_GETIMAGELIST
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TVM_GETINDENT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TVM_GETISEARCHSTRING
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TVM_GETITEM
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TVM_GETITEMRECT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TVM_GETNEXTITEM
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TVM_GETVISIBLECOUNT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TVM_HITTEST
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TVM_INSERTITEM
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TVM_SELECTITEM
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TVM_SETIMAGELIST
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TVM_SETINDENT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TVM_SETITEM
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TVM_SORTCHILDREN
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TVM_SORTCHILDRENCB
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TVN_BEGINDRAG
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TVN_BEGINLABELEDIT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TVN_BEGINRDRAG
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TVN_DELETEITEM
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TVN_ENDLABELEDIT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TVN_GETDISPINFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TVN_ITEMEXPANDED
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TVN_ITEMEXPANDING
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TVN_KEYDOWN
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TVN_SELCHANGED
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TVN_SELCHANGING
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TVN_SETDISPINFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


UDM_DELTAPOS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


UDM_GETACCEL
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


UDM_GETBASE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


UDM_GETBUDDY
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


UDM_GETPOS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


UDM_GETRANGE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


UDM_SETACCEL
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


UDM_SETBASE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


UDM_SETBUDDY
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


UDM_SETPOS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


UDM_SETRANGE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WIM_CLOSE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WIM_DATA
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WIM_OPEN
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WM_ACTIVATE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_ACTIVATEAPP
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_APP
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_ASKCBFORMATNAME
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_CANCELJOURNAL
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_CANCELMODE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_CAP_ABORT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WM_CAP_DLG_VIDEOCOMPRESSION
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WM_CAP_DLG_VIDEODISPLAY
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WM_CAP_DLG_VIDEOFORMAT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WM_CAP_DLG_VIDEOSOURCE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WM_CAP_DRIVER_CONNECT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WM_CAP_DRIVER_DISCONNECT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WM_CAP_DRIVER_GET_CAPS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WM_CAP_DRIVER_GET_NAME
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WM_CAP_DRIVER_GET_VERSION
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WM_CAP_EDIT_COPY
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WM_CAP_FILE_ALLOCATE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WM_CAP_FILE_GET_CAPTURE_FILE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WM_CAP_FILE_SAVEAS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WM_CAP_FILE_SAVEDIB
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WM_CAP_FILE_SET_CAPTURE_FILE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WM_CAP_FILE_SET_INFOCHUNK
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WM_CAP_GET_AUDIOFORMAT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WM_CAP_GET_MCI_DEVICE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WM_CAP_GET_SEQUENCE_SETUP
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WM_CAP_GET_STATUS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WM_CAP_GET_USER_DATA
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WM_CAP_GET_VIDEOFORMAT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WM_CAP_GRAB_FRAME
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WM_CAP_GRAB_FRAME_NOSTOP
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WM_CAP_PAL_AUTOCREATE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WM_CAP_PAL_MANUALCREATE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WM_CAP_PAL_OPEN
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WM_CAP_PAL_PASTE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WM_CAP_PAL_SAVE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WM_CAP_SEQUENCE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WM_CAP_SEQUENCE_NOFILE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WM_CAP_SET_AUDIOFORMAT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WM_CAP_SET_CALLBACK_CAPCONTROL
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WM_CAP_SET_CALLBACK_ERROR
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WM_CAP_SET_CALLBACK_FRAME
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WM_CAP_SET_CALLBACK_STATUS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WM_CAP_SET_CALLBACK_VIDEOSTREAM
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WM_CAP_SET_CALLBACK_WAVESTREAM
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WM_CAP_SET_CALLBACK_YIELD
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WM_CAP_SET_MCI_DEVICE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WM_CAP_SET_OVERLAY
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WM_CAP_SET_PREVIEW
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WM_CAP_SET_PREVIEWRATE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WM_CAP_SET_SCALE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WM_CAP_SET_SCROLL
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WM_CAP_SET_SEQUENCE_SETUP
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WM_CAP_SET_USER_DATA
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WM_CAP_SET_VIDEOFORMAT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WM_CAP_SINGLE_FRAME
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WM_CAP_SINGLE_FRAME_CLOSE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WM_CAP_SINGLE_FRAME_OPEN
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WM_CAP_STOP
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WM_CAPTURECHANGED
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_CHANGECBCHAIN
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_CHAR
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_CHARTOITEM
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_CHILDACTIVATE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_CHOOSEFONT_GETLOGFONT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	commdlg.h
Unicode	No
Platform Notes	None


WM_CLEAR
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_CLOSE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_COMMAND
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_COMMNOTIFY
Windows NT	No
Win95	No
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_COMPACTING
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_COMPAREITEM
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_CONTEXTMENU
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_CONVERTREQUESTEX
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	imm.h
Unicode
Platform Notes	None


WM_COPY
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_COPYDATA
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_CPL_LAUNCH
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	cpl.h
Unicode	No
Platform Notes	None


WM_CPL_LAUNCHED
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	cpl.h
Unicode	No
Platform Notes	None


WM_CREATE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_CTLCOLORBTN
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_CTLCOLORDLG
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_CTLCOLOREDIT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_CTLCOLORLISTBOX
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_CTLCOLORMSGBOX
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_CTLCOLORSCROLLBAR
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_CTLCOLORSTATIC
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_CUT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_DDE_ACK
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	dde.h
Unicode	No
Platform Notes	None


WM_DDE_ADVISE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	dde.h
Unicode	No
Platform Notes	None


WM_DDE_DATA
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	dde.h
Unicode	No
Platform Notes	None


WM_DDE_EXECUTE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	dde.h
Unicode	No
Platform Notes	None


WM_DDE_INITIATE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	dde.h
Unicode	No
Platform Notes	None


WM_DDE_POKE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	dde.h
Unicode	No
Platform Notes	None


WM_DDE_REQUEST
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	dde.h
Unicode	No
Platform Notes	None


WM_DDE_TERMINATE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	dde.h
Unicode	No
Platform Notes	None


WM_DDE_UNADVISE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	dde.h
Unicode	No
Platform Notes	None


WM_DEADCHAR
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_DELETEITEM
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_DESTROY
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_DESTROYCLIPBOARD
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_DEVICECHANGE
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode
Platform Notes	None


WM_DEVMODECHANGE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_DISPLAYCHANGE
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_DRAWCLIPBOARD
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_DRAWITEM
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_DROPFILES
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_ENABLE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_ENDSESSION
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_ENTERIDLE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_ENTERMENULOOP
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_ENTERSIZEMOVE
Windows NT	Yes
Win95	Yes
Win32s
Import Library
Header File	winuser.h
Unicode
Platform Notes	None


WM_ERASEBKGND
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_EXITMENULOOP
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_EXITSIZEMOVE
Windows NT	Yes
Win95	Yes
Win32s
Import Library
Header File	winuser.h
Unicode
Platform Notes	None


WM_FONTCHANGE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_GETDLGCODE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_GETFONT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_GETHOTKEY
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_GETICON
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_GETMINMAXINFO
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_GETTEXT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_GETTEXTLENGTH
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_HELP
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_HOTKEY
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_HSCROLL
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_HSCROLLCLIPBOARD
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_ICONERASEBKGND
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_IME_CHAR
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	imm.h
Unicode
Platform Notes	None


WM_IME_COMPOSITION
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	imm.h
Unicode
Platform Notes	None


WM_IME_COMPOSITIONFULL
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	imm.h
Unicode
Platform Notes	None


WM_IME_CONTROL
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	imm.h
Unicode
Platform Notes	None


WM_IME_ENDCOMPOSITION
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	imm.h
Unicode
Platform Notes	None


WM_IME_KEYDOWN
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	imm.h
Unicode
Platform Notes	None


WM_IME_KEYLAST
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	imm.h
Unicode
Platform Notes	None


WM_IME_KEYUP
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	imm.h
Unicode
Platform Notes	None


WM_IME_NOTIFY
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	imm.h
Unicode
Platform Notes	None


WM_IME_SELECT
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	imm.h
Unicode
Platform Notes	None


WM_IME_SETCONTEXT
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	imm.h
Unicode
Platform Notes	None


WM_IME_STARTCOMPOSITION
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	imm.h
Unicode
Platform Notes	None


WM_INITDIALOG
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_INITMENU
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_INITMENUPOPUP
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_KEYDOWN
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_KEYFIRST
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_KEYLAST
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_KEYUP
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_KILLFOCUS
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_LBUTTONDBLCLK
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_LBUTTONDOWN
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_LBUTTONUP
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_MBUTTONDBLCLK
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_MBUTTONDOWN
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_MBUTTONUP
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_MDIACTIVATE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_MDICASCADE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_MDICREATE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_MDIDESTROY
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_MDIGETACTIVE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_MDIICONARRANGE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_MDIMAXIMIZE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_MDINEXT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_MDIREFRESHMENU
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_MDIRESTORE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_MDISETMENU
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_MDITILE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_MEASUREITEM
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_MENUCHAR
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_MENUSELECT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_MOUSEACTIVATE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_MOUSEMOVE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_MOVE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_MOVING
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_NCACTIVATE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_NCCALCSIZE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_NCCREATE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_NCDESTROY
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_NCHITTEST
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_NCLBUTTONDBLCLK
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_NCLBUTTONDOWN
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_NCLBUTTONUP
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_NCMBUTTONDBLCLK
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_NCMBUTTONDOWN
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_NCMBUTTONUP
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_NCMOUSEMOVE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_NCPAINT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_NCRBUTTONDBLCLK
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_NCRBUTTONDOWN
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_NCRBUTTONUP
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_NEXTDLGCTL
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_NOTIFY
Windows NT	Yes
Win95	Yes
Win32s
Import Library
Header File	winuser.h
Unicode
Platform Notes	None


WM_NOTIFYFORMAT
Windows NT	Yes
Win95	Yes
Win32s
Import Library
Header File	winuser.h
Unicode
Platform Notes	None


WM_NULL
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_PAINT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_PAINTCLIPBOARD
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_PAINTICON
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_PALETTECHANGED
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_PALETTEISCHANGING
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_PARENTNOTIFY
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_PASTE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_POWER
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_POWERBROADCAST
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_PRINT
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_PRINTCLIENT
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_QUERYDRAGICON
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_QUERYENDSESSION
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_QUERYNEWPALETTE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_QUERYOPEN
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_QUEUESYNC
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_QUIT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_RASDIALEVENT
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	ras.h
Unicode	No
Platform Notes	None


WM_RBUTTONDBLCLK
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_RBUTTONDOWN
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_RBUTTONUP
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_RENDERALLFORMATS
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_RENDERFORMAT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_SETCURSOR
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_SETFOCUS
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_SETFONT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_SETHOTKEY
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_SETICON
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_SETREDRAW
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_SETTEXT
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_SETTINGCHANGE
Windows NT	No
Win95	Yes
Win32s
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_SHOWWINDOW
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_SIZE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_SIZECLIPBOARD
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_SIZING
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_SPOOLERSTATUS
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_STYLECHANGED
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_STYLECHANGING
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_SYSCHAR
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_SYSCOLORCHANGE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_SYSCOMMAND
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_SYSDEADCHAR
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_SYSKEYDOWN
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_SYSKEYUP
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_TCARD
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode
Platform Notes	None


WM_TIMECHANGE
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_TIMER
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_UNDO
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_USER
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_USERCHANGED
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode
Platform Notes	None


WM_VKEYTOITEM
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_VSCROLL
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_VSCROLLCLIPBOARD
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_WINDOWPOSCHANGED
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_WINDOWPOSCHANGING
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WM_WININICHANGE
Windows NT	Yes
Win95	No
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WOM_CLOSE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WOM_DONE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WOM_OPEN
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WS_EX_CLIENTEDGE
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WS_EX_MDICHILD
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


WS_EX_WINDOWEDGE
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


_DEV_BROADCAST_USER_DEFINED
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ABC
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ABCFLOAT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ACCEL
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ACCESS_ALLOWED_ACE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ACCESS_DENIED_ACE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ACCESS_MASK
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ACCESSTIMEOUT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ACE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ACE_HEADER
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ACL
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ACL_REVISION_INFORMATION
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ACL_SIZE_INFORMATION
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ACMDRIVERDETAILS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ACMFILTERCHOOSE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ACMFILTERDETAILS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ACMFILTERTAGDETAILS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ACMFORMATCHOOSE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ACMFORMATDETAILS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ACMFORMATTAGDETAILS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ACMSTREAMHEADER
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ACTION_HEADER
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ADAPTER_STATUS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ADDJOB_INFO_1
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ANIMATIONINFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


APPBARDATA
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shellapi.h
Unicode
Platform Notes	None


AUXCAPS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


AVICOMPRESSOPTIONS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


AVIFILEINFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


AVISTREAMINFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


BITMAP
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


BITMAPCOREHEADER
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


BITMAPCOREINFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


BITMAPFILEHEADER
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


BITMAPINFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


BITMAPINFOHEADER
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


BITMAPV4HEADER
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


BLOB
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


BROWSEINFO
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


BY_HANDLE_FILE_INFORMATION
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


CANDIDATEFORM
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


CANDIDATELIST
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


CAPDRIVERCAPS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


CAPINFOCHUNK
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


CAPSTATUS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


CAPTUREPARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


CBT_CREATEWND
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


CBTACTIVATESTRUCT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


CHAR_INFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


CHARFORMAT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


CHARRANGE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


CHARSET
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


CHARSETINFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


CHOOSECOLOR
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


CHOOSEFONT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


CIDA
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


CIEXYZ
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


CIEXYZTRIPLE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


CLIENTCREATESTRUCT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


CMINVOKECOMMANDINFO
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


COLORADJUSTMENT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


COLORMAP
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


COLORREF
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


COMMCONFIG
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


COMMPROP
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


COMMTIMEOUTS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


COMPAREITEMSTRUCT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


COMPCOLOR
Windows NT
Win95
Win32s
Import Library
Header File	richedit.h
Unicode
Platform Notes	None


COMPOSITIONFORM
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


COMPVARS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


COMSTAT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


CONSOLE_CURSOR_INFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


CONSOLE_SCREEN_BUFFER_INFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


CONTEXT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


CONVCONTEXT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


CONVINFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


COORD
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


COPYDATASTRUCT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


CPINFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


CPLINFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


CREATE_PROCESS_DEBUG_INFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


CREATE_THREAD_DEBUG_INFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


CREATESTRUCT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


CSADDR_INFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


CURRENCYFMT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


CURSORSHAPE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


CWPRETSTRUCT
Windows NT	No
Win95	Yes
Win32s
Import Library
Header File	winuser.h
Unicode
Platform Notes	None


CWPSTRUCT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


DATATYPES_INFO_1
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


DCB
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


DDEACK
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


DDEADVISE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


DDEDATA
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


DDELN
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


DDEML_MSG_HOOK_DATA
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


DDEPOKE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


DDEUP
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


DEBUG_EVENT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


DEBUGHOOKINFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


DELETEITEMSTRUCT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


DEV_BROADCAST_DEVNODE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


DEV_BROADCAST_HDR
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


DEV_BROADCAST_NET
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


DEV_BROADCAST_OEM
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


DEV_BROADCAST_PORT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


DEV_BROADCAST_VOLUME
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


DEVMODE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


DEVNAMES
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


DIBSECTION
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


DISK_GEOMETRY
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


DISK_PERFORMANCE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


DLGITEMTEMPLATE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


DLGTEMPLATE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


DOC_INFO_1
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


DOC_INFO_2
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


DOCINFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


DRAGLISTINFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


DRAWDIBTIME
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


DRAWITEMSTRUCT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


DRAWTEXTPARAMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


DRIVE_LAYOUT_INFORMATION
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


DRIVER_INFO_1
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


DRIVER_INFO_2
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


DRIVER_INFO_3
Windows NT	No
Win95	Yes
Win32s
Import Library
Header File	winspool.h
Unicode
Platform Notes	None


DROPFILES
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


DRVCONFIGINFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EDITSTREAM
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EMR
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EMRANGLEARC
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EMRARC
Windows NT	EMRARCTO
Win95	EMRCHORD
Win32s	EMRPIE
Import Library
Header File
Unicode
Platform Notes	None


EMRBITBLT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EMRCREATEBRUSHINDIRECT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EMRCREATECOLORSPACE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EMRCREATEDIBPATTERNBRUSHPT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EMRCREATEMONOBRUSH
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EMRCREATEPALETTE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EMRCREATEPEN
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EMRELLIPSE
Windows NT	EMRRECTANGLE
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EMREOF
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EMREXCLUDECLIPRECT
Windows NT	EMRINTERSECTCLIPRECT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EMREXTCREATEFONTINDIRECTW
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EMREXTCREATEPEN
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EMREXTFLOODFILL
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EMREXTSELECTCLIPRGN
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EMREXTTEXTOUTA
Windows NT	EMREXTTEXTOUTW
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EMRFILLPATH
Windows NT	EMRSTROKEANDFILLPATH
Win95	EMRSTROKEPATH
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EMRFILLRGN
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EMRFORMAT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EMRFRAMERGN
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EMRGDICOMMENT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EMRINVERTRGN
Windows NT	EMRPAINTRGN
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EMRLINETO
Windows NT	EMRMOVETOEX
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EMRMASKBLT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EMRMODIFYWORLDTRANSFORM
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EMROFFSETCLIPRGN
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EMRPLGBLT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EMRPOLYDRAW
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EMRPOLYDRAW16
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EMRPOLYLINE
Windows NT	EMRPOLYBEZIER
Win95	EMRPOLYGON
Win32s	EMRPOLYBEZIERTO
Import Library
Header File
Unicode
Platform Notes	None


EMRPOLYLINE16
Windows NT	EMRPOLYBEZIER16
Win95	EMRPOLYGON16
Win32s	EMRPOLYBEZIERTO16
Import Library
Header File
Unicode
Platform Notes	None


EMRPOLYPOLYLINE
Windows NT	EMRPOLYPOLYGON
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EMRPOLYPOLYLINE16
Windows NT	EMRPOLYPOLYGON16
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EMRPOLYTEXTOUTA
Windows NT	EMRPOLYTEXTOUTW
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EMRRESIZEPALETTE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EMRRESTOREDC
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EMRROUNDRECT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EMRSCALEVIEWPORTEXTEX
Windows NT	EMRSCALEWINDOWEXTEX
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EMRSELECTCOLORSPACE
Windows NT	EMRDELETECOLORSPACE
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EMRSELECTOBJECT
Windows NT	EMRDELETEOBJECT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EMRSELECTPALETTE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EMRSETARCDIRECTION
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EMRSETBKCOLOR
Windows NT	EMRSETTEXTCOLOR
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EMRSETCOLORADJUSTMENT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EMRSETDIBITSTODEVICE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EMRSETMAPPERFLAGS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EMRSETMITERLIMIT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EMRSETPALETTEENTRIES
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EMRSETPIXELV
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EMRSETVIEWPORTEXTEX
Windows NT	EMRSETWINDOWEXTEX
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EMRSETVIEWPORTORGEX
Windows NT	EMRSETWINDOWORGEX
Win95	EMRSETBRUSHORGEX
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EMRSETWORLDTRANSFORM
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EMRSTRETCHBLT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EMRSTRETCHDIBITS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EMRTEXT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ENCORRECTTEXT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ENDROPFILES
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ENHMETAHEADER
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ENHMETARECORD
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ENOLEOPFAILED
Windows NT
Win95
Win32s
Import Library
Header File	richedit.h
Unicode
Platform Notes	None


ENPROTECTED
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ENSAVECLIPBOARD
Windows NT
Win95
Win32s
Import Library
Header File	richedit.h
Unicode
Platform Notes	None


ENUM_SERVICE_STATUS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ENUMLOGFONT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ENUMLOGFONTEX
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EVENTLOGRECORD
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EVENTMSG
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EXCEPTION_DEBUG_INFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EXCEPTION_POINTERS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EXCEPTION_RECORD
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EXIT_PROCESS_DEBUG_INFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EXIT_THREAD_DEBUG_INFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EXT_BUTTON
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EXTLOGFONT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


EXTLOGPEN
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


FILEDESCRIPTOR
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File
Unicode
Platform Notes	None


FILEGROUPDESCRIPTOR
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File
Unicode
Platform Notes	None


FILETIME
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


FILTERKEYS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


FIND_NAME_BUFFER
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


FIND_NAME_HEADER
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


FINDREPLACE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


FINDTEXT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


FINDTEXTEX
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


FIXED
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


FMS_GETDRIVEINFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


FMS_GETFILESEL
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


FMS_LOAD
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


FMS_TOOLBARLOAD
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


FOCUS_EVENT_RECORD
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


FONTSIGNATURE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


FORM_INFO_1
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


FORMAT_PARAMETERS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


FORMATRANGE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


FVSHOWINFO
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


GCP_RESULTS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


GENERIC_MAPPING
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


GLYPHMETRICS
Windows NT	Yes
Win95	No
Win32s	No
Import Library
Header File	wingdi.h
Unicode
Platform Notes	None


GLYPHMETRICSFLOAT
Windows NT	New
Win95	No
Win32s	No
Import Library
Header File	wingdi.h
Unicode
Platform Notes	None


HANDLETABLE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


HD_HITTESTINFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


HD_ITEM
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


HD_LAYOUT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


HD_NOTIFY
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


HELPINFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


HELPWININFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


HIGHCONTRAST
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


HSZPAIR
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICCOMPRESS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICCOMPRESSFRAMES
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICDECOMPRESS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICDECOMPRESSEX
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICDRAW
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICDRAWBEGIN
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICDRAWSUGGEST
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICINFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICONINFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICONMETRICS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICOPEN
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ICSETSTATUSPROC
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


IMAGEINFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


INPUT_RECORD
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ITEMIDLIST
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


JOB_INFO_1
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


JOB_INFO_2
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


JOYCAPS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


JOYCAPS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


JOYINFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


JOYINFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


KERNINGPAIR
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


KEY_EVENT_RECORD
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


KEYARRAY
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LANA_ENUM
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LARGE_INTEGER
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LDT_ENTRY
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LIST_ENTRY
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LOAD_DLL_DEBUG_INFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LOCALESIGNATURE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LOCALGROUP_MEMBERS_INFO_0
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LOCALGROUP_MEMBERS_INFO_3
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LOGBRUSH
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LOGCOLORSPACE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LOGFONT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LOGPALETTE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LOGPEN
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LUID
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LUID_AND_ATTRIBUTES
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LV_COLUMN
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LV_DISPINFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LV_FINDINFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LV_HITTESTINFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LV_ITEM
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


LV_KEYDOWN
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MAT2
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_ANIM_OPEN_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_ANIM_PLAY_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_ANIM_RECT_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_ANIM_STEP_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_ANIM_UPDATE_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_ANIM_WINDOW_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_BREAK_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_DGV_CAPTURE_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_DGV_COPY_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_DGV_CUE_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_DGV_CUT_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_DGV_DELETE_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_DGV_FREEZE_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_DGV_INFO_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_DGV_LIST_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_DGV_LOAD_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_DGV_MONITOR_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_DGV_OPEN_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_DGV_PASTE_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_DGV_PAUSE_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_DGV_PLAY_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_DGV_PUT_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_DGV_QUALITY_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_DGV_RECORD_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_DGV_RECT_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_DGV_RESERVE_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_DGV_RESTORE_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_DGV_RESUME_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_DGV_SAVE_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_DGV_SET_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_DGV_SETAUDIO_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_DGV_SETVIDEO_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_DGV_SIGNAL_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_DGV_STATUS_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_DGV_STEP_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_DGV_STOP_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_DGV_UPDATE_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_DGV_WINDOW_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_GENERIC_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_GENERIC_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_GETDEVCAPS_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_GETDEVCAPS_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_INFO_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_INFO_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_LOAD_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_LOAD_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_OPEN_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_OPEN_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_OVLY_LOAD_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_OVLY_LOAD_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_OVLY_OPEN_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_OVLY_OPEN_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_OVLY_RECT_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_OVLY_RECT_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_OVLY_SAVE_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_OVLY_SAVE_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_OVLY_WINDOW_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_OVLY_WINDOW_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_PLAY_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_PLAY_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_RECORD_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_RECORD_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_SAVE_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_SAVE_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_SEEK_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_SEEK_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_SEQ_SET_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_SEQ_SET_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_SET_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_SET_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_STATUS_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_STATUS_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_SYSINFO_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_SYSINFO_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_VCR_CUE_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_VCR_LIST_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_VCR_PLAY_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_VCR_RECORD_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_VCR_SEEK_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_VCR_SET_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_VCR_SETAUDIO_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


BringWindowToTop
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


BroadcastSystemMessage
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


BuildCommDCB
Windows NT	New
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


BuildCommDCBAndTimeouts
Windows NT	New
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


CallMsgFilter
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


CallNamedPipe
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


CallNextHookEx
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


CallProc32W
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


CallProcEx32W
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


CallWindowProc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


CancelDC
Windows NT	Yes
Win95	No
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


capCreateCaptureWindow
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	WinNT
Platform Notes	None


capGetDriverDescription
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	WinNT
Platform Notes	None


CascadeWindows
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


ChangeClipboardChain
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


ChangeDisplaySettings
Windows NT	Yes
Win95	Yes
Win32s
Import Library
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


ChangeMenu
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


ChangeServiceConfig
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winsvc.h
Unicode	WinNT
Platform Notes	None


char_array_from_ndr
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcndr.h
Unicode
Platform Notes	None


char_from_ndr
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcndr.h
Unicode
Platform Notes	None


CharLower
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


CharLowerBuff
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


CharNext
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


CharNextExA
Windows NT	No
Win95	Yes
Win32s
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


CharPrev
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


CharPrevExA
Windows NT	No
Win95	Yes
Win32s
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


CharToOem
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


CharToOemBuff
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


CharUpper
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


CharUpperBuff
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


CheckColorsInGamut
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


CheckDlgButton
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


CheckMenuItem
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


CheckMenuRadioItem
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


CheckRadioButton
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


ChildWindowFromPoint
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


ChildWindowFromPointEx
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


ChooseColor
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	comdlg32.lib
Header File	commdlg.h
Unicode	WinNT
Platform Notes	None


ChooseFont
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	comdlg32.lib
Header File	commdlg.h
Unicode	WinNT
Platform Notes	None


ChoosePixelFormat
Windows NT	Yes
Win95	No
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


Chord
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


ClearCommBreak
Windows NT	New
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


ClearCommError
Windows NT	New
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


ClearEventLog
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


ClientToScreen
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


ClipCursor
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


CloseClipboard
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


CloseDesktop
Windows NT	Yes
Win95	No
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


CloseEnhMetaFile
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


CloseEventLog
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


CloseFigure
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


CloseHandle
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


CloseMetaFile
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


ClosePrinter
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	winspool.lib
Header File	winspool.h
Unicode	No
Platform Notes	None


CloseServiceHandle
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winsvc.h
Unicode	No
Platform Notes	None


closesocket
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	wsock32.lib
Header File	winsock.h
Unicode	No
Platform Notes	None


CloseWindow
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


CloseWindowStation
Windows NT	Yes
Win95	No
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


CLSIDFromProgID
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	WinNT; Win95; Win32s
Platform Notes	All 32-bit OLE Apis are UNICODE only


CLSIDFromString
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	WinNT; Win95; Win32s
Platform Notes	All 32-bit OLE Apis are UNICODE only


CoBuildVersion
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	No
Platform Notes	None


CoCreateGuid
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	No
Platform Notes	None


CoCreateInstance
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	No
Platform Notes	None


CoDisconnectObject
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	No
Platform Notes	None


CoDosDateTimeToFileTime
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	No
Platform Notes	None


CoFileTimeNow
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	No
Platform Notes	None


CoFileTimeToDosDateTime
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	No
Platform Notes	None


CoFreeAllLibraries
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	No
Platform Notes	None


CoFreeLibrary
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	No
Platform Notes	None


CoFreeUnusedLibraries
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	No
Platform Notes	None


CoGetClassObject
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	No
Platform Notes	None


CoGetCurrentProcess
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	No
Platform Notes	None


CoGetMalloc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	No
Platform Notes	None


CoGetMarshalSizeMax
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	No
Platform Notes	None


CoGetStandardMarshal
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	No
Platform Notes	None


CoGetState
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	No
Platform Notes	None


CoGetTreatAsClass
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	No
Platform Notes	None


CoInitialize
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	No
Platform Notes	None


CoIsHandlerConnected
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	No
Platform Notes	None


CoIsOle1Class
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	No
Platform Notes	None


CoLoadLibrary
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	No
Platform Notes	None


CoLockObjectExternal
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	No
Platform Notes	None


ColorMatchToTarget
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


CoMarshalHresult
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	No
Platform Notes	None


CoMarshalInterface
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	No
Platform Notes	None


CombineRgn
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


CombineTransform
Windows NT	Yes
Win95	No
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


CommandLineToArgvW
Windows NT	New
Win95	No
Win32s	New
Import Library	shell32.lib
Header File	shellapi.h
Unicode	No
Platform Notes	None


CommConfigDialog
Windows NT	New
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


CommDlgExtendedError
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	comdlg32.lib
Header File	commdlg.h
Unicode	No
Platform Notes	None


CompareFileTime
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


CompareString
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winnls.h
Unicode	WinNT
Platform Notes	None


ConfigurePort
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	winspool.lib
Header File	winspool.h
Unicode	WinNT
Platform Notes	None


connect
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	wsock32.lib
Header File	winsock.h
Unicode	No
Platform Notes	None


ConnectNamedPipe
Windows NT	Yes
Win95	No
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


ConnectToPrinterDlg
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	winspool.lib
Header File	winspool.h
Unicode	No
Platform Notes	None


ContinueDebugEvent
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


ControlService
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winsvc.h
Unicode	No
Platform Notes	None


ConvertDefaultLocale
Windows NT	New
Win95	New
Win32s	New
Import Library	kernel32.lib
Header File	winnls.h
Unicode	No
Platform Notes	None


CopyAcceleratorTable
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


CopyCursor
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CopyEnhMetaFile
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	WinNT
Platform Notes	None


CopyFile
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


CopyIcon
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


CopyImage
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


CopyLZFile
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	lz32.lib
Header File	lzexpand.h
Unicode	No
Platform Notes	None


CopyMemory
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winbase.h
Unicode	No
Platform Notes	None


CopyMetaFile
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	WinNT
Platform Notes	Windows 95: int == 16 bits


CopyRect
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


CopySid
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


CoRegisterClassObject
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	No
Platform Notes	None


CoRegisterMessageFilter
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	No
Platform Notes	None


CoReleaseMarshalData
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	No
Platform Notes	None


CoRevokeClassObject
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	No
Platform Notes	None


CoTaskMemAlloc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	No
Platform Notes	None


CoTaskMemFree
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	No
Platform Notes	None


CoTaskMemRealloc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	No
Platform Notes	None


CoTreatAsClass
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	No
Platform Notes	None


CoUninitialize
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	No
Platform Notes	None


CoUnmarshalHresult
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	No
Platform Notes	None


CoUnmarshalInterface
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	No
Platform Notes	None


MCI_VCR_SETTUNER_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_VCR_SETVIDEO_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_VCR_STATUS_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_VCR_STEP_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_VD_ESCAPE_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_VD_ESCAPE_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_VD_PLAY_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_VD_PLAY_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_VD_STEP_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_VD_STEP_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_WAVE_DELETE_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_WAVE_DELETE_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_WAVE_OPEN_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_WAVE_OPEN_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_WAVE_SET_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MCI_WAVE_SET_PARMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MDICREATESTRUCT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MEASUREITEMSTRUCT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MEMORY_BASIC_INFORMATION
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MEMORYSTATUS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MENU_EVENT_RECORD
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MENUEX_TEMPLATE_HEADER
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MENUEX_TEMPLATE_ITEM
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MENUITEMINFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MENUITEMTEMPLATE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MENUITEMTEMPLATEHEADER
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


METAFILEPICT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


METAHEADER
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


METARECORD
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MIDIEVENT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MIDIHDR
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MIDIHDR
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MIDIINCAPS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MIDIINCAPS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MIDIOUTCAPS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MIDIOUTCAPS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MIDIPROPTEMPO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MIDIPROPTIMEDIV
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MIDISTRMBUFFVER
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MINIMIZEDMETRICS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MINMAXINFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MIXERCAPS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MIXERCONTROL
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MIXERCONTROLDETAILS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MIXERCONTROLDETAILS_BOOLEAN
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MIXERCONTROLDETAILS_LISTTEXT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MIXERCONTROLDETAILS_SIGNED
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MIXERCONTROLDETAILS_UNSIGNED
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MIXERLINE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MIXERLINECONTROLS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MMCKINFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MMCKINFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MMIOINFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MMIOINFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MMTIME
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MMTIME
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MODEMDEVCAPS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MODEMSETTINGS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MONCBSTRUCT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MONCONVSTRUCT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MONERRSTRUCT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MONHSZSTRUCT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MONITOR_INFO_1
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MONITOR_INFO_2
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MONLINKSTRUCT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MONMSGSTRUCT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MOUSE_EVENT_RECORD
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MOUSEHOOKSTRUCT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MOUSEKEYS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MSG
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MSGBOXPARAMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MSGFILTER
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MULTIKEYHELP
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


MULTIKEYHELP
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


NAME_BUFFER
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


NCB
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


NCCALCSIZE_PARAMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


NDDESHAREINFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


NETRESOURCE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


NEWCPLINFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


NEWTEXTMETRIC
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


NEWTEXTMETRICEX
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


NM_LISTVIEW
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


NM_LISTVIEW
Windows NT
Win95
Win32s
Import Library
Header File	commctrl.h
Unicode
Platform Notes	None


NM_TREEVIEW
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


NM_UPDOWN
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


NMHDR
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


NONCLIENTMETRICS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


NOTIFYICONDATA
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shellapi.h
Unicode
Platform Notes	None


NRESARRAY
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


NS_SERVICE_INFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


NUMBERFMT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


OFSTRUCT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


OPENFILENAME
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


OSVERSIONINFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


OUTLINETEXTMETRIC
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


OUTPUT_DEBUG_STRING_INFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


OVERLAPPED
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PAINTSTRUCT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PALETTEENTRY
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PANOSE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PARAFORMAT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PARTITION_INFORMATION
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PATCHARRAY
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PCMWAVEFORMAT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PCMWAVEFORMAT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PERF_COUNTER_BLOCK
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PERF_COUNTER_DEFINITION
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PERF_DATA_BLOCK
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PERF_INSTANCE_DEFINITION
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PERF_OBJECT_TYPE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


POINT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


POINTFLOAT
Windows NT	New
Win95	No
Win32s	No
Import Library
Header File	wingdi.h
Unicode
Platform Notes	None


POINTFX
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


POINTL
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


POINTS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


POLYTEXT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PORT_INFO_1
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PORT_INFO_2
Windows NT	No
Win95	Yes
Win32s
Import Library
Header File	winspool.h
Unicode
Platform Notes	None


PREVENT_MEDIA_REMOVAL
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PRINTDLG
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PRINTER_DEFAULTS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PRINTER_INFO_1
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PRINTER_INFO_2
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PRINTER_INFO_3
Windows NT	Yes
Win95	No
Win32s
Import Library
Header File	winspool.h
Unicode
Platform Notes	None


PRINTER_INFO_4
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PRINTER_INFO_5
Windows NT	No
Win95	Yes
Win32s
Import Library
Header File	winspool.h
Unicode
Platform Notes	None


PRINTER_NOTIFY_INFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PRINTER_NOTIFY_INFO_DATA
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PRINTER_NOTIFY_OPTIONS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PRINTER_NOTIFY_OPTIONS_TYPE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PRINTPROCESSOR_INFO_1
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PRIVILEGE_SET
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PROCESS_HEAP_ENTRY
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PROCESS_INFORMATION
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PROPSHEETHEADER
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PROPSHEETPAGE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PROTOCOL_INFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PROVIDOR_INFO_1
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PSHNOTIFY
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


PUNCTUATION
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


QUERY_SERVICE_CONFIG
Windows NT	Yes
Win95	No
Win32s
Import Library
Header File	winsvc.h
Unicode
Platform Notes	None


QUERY_SERVICE_LOCK_STATUS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


RASAMB
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


RASCONN
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


RASCONNSTATUS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


RASDIALEXTENSIONS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


RASDIALPARAMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


RASENTRYNAME
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


RASPPPIP
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


RASPPPIPX
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


RASPPPNBF
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


RASTERIZER_STATUS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


REASSIGN_BLOCKS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


RECT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


RECTL
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


REGISTERWORD
Windows NT
Win95
Win32s
Import Library
Header File	imm.h
Unicode
Platform Notes	None


REMOTE_NAME_INFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


REOBJECT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


REPASTESPECIAL
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


REQRESIZE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


RGBQUAD
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


RGBTRIPLE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


RGNDATA
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


RGNDATAHEADER
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


RIP_INFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


SCROLLINFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


SECURITY_ATTRIBUTES
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


SECURITY_DESCRIPTOR
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


SECURITY_DESCRIPTOR_CONTROL
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


SECURITY_INFORMATION
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


SECURITY_QUALITY_OF_SERVICE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


SELCHANGE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


SERIALKEYS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


SERVICE_ADDRESS
Windows NT	Yes
Win95	No
Win32s
Import Library
Header File	nspapi.h
Unicode
Platform Notes	None


SERVICE_ADDRESSES
Windows NT	Yes
Win95	No
Win32s
Import Library
Header File	nspapi.h
Unicode
Platform Notes	None


SERVICE_INFO
Windows NT	Yes
Win95	No
Win32s
Import Library
Header File	nspapi.h
Unicode
Platform Notes	None


SERVICE_STATUS
Windows NT	Yes
Win95	No
Win32s
Import Library
Header File	winsvc.h
Unicode
Platform Notes	None


SERVICE_TABLE_ENTRY
Windows NT	Yes
Win95	No
Win32s
Import Library
Header File	winsvc.h
Unicode
Platform Notes	None


SERVICE_TYPE_INFO_ABS
Windows NT	Yes
Win95	No
Win32s
Import Library
Header File	nspapi.h
Unicode
Platform Notes	None


SERVICE_TYPE_VALUE_ABS
Windows NT	Yes
Win95	No
Win32s
Import Library
Header File	nspapi.h
Unicode
Platform Notes	None


SESSION_BUFFER
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


SESSION_HEADER
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


SET_PARTITION_INFORMATION
Windows NT	Yes
Win95	No
Win32s
Import Library
Header File	winioctl.h
Unicode
Platform Notes	None


SHCONTF
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


SHFILEINFO
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


SHFILEOPSTRUCT
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


SHGNO
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


SHITEMID
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


SHNAMEMAPPING
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


SID
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


SID_AND_ATTRIBUTES
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


SID_IDENTIFIER_AUTHORITY
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


SINGLE_LIST_ENTRY
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


SIZE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


SMALL_RECT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


SOUNDSENTRY
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


STARTUPINFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


STICKYKEYS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


String
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


StringFileInfo
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


StringTable
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


STRRET
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	shlobj.h
Unicode
Platform Notes	None


STYLEBUF
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


STYLESTRUCT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


SYSTEM_ALARM_ACE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


SYSTEM_AUDIT_ACE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


SYSTEM_INFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


SYSTEM_POWER_STATUS
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	winbase.h
Unicode
Platform Notes	None


SYSTEMTIME
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TAPE_ERASE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TAPE_GET_DRIVE_PARAMETERS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TAPE_GET_MEDIA_PARAMETERS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TAPE_GET_POSITION
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TAPE_PREPARE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TAPE_SET_DRIVE_PARAMETERS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TAPE_SET_MEDIA_PARAMETERS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TAPE_SET_POSITION
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TAPE_WRITE_MARKS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TBADDBITMAP
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TBBUTTON
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TBNOTIFY
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TBSAVEPARAMS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TC_HITTESTINFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TC_ITEM
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TC_ITEMHEADER
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TC_KEYDOWN
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TEXTMETRIC
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TEXTRANGE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TIME_ZONE_INFORMATION
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TIMECAPS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TOGGLEKEYS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TOKEN_CONTROL
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TOKEN_DEFAULT_DACL
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TOKEN_GROUPS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TOKEN_OWNER
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TOKEN_PRIMARY_GROUP
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TOKEN_PRIVILEGES
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TOKEN_SOURCE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TOKEN_STATISTICS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TOKEN_USER
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TOOLINFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TOOLTIPTEXT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TPMPARAMS
Windows NT	No
Win95	Yes
Win32s
Import Library
Header File	winuser.h
Unicode
Platform Notes	None


TRANSMIT_FILE_BUFFERS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TTHITTESTINFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TTPOLYCURVE
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TTPOLYGONHEADER
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TV_DISPINFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TV_HITTESTINFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TV_INSERTSTRUCT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TV_ITEM
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TV_KEYDOWN
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


TV_SORTCB
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


UDACCEL
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


ULARGE_INTEGER
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


UNIVERSAL_NAME_INFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


UNLOAD_DLL_DEBUG_INFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


USEROBJECTFLAGS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


VALENT
Windows NT
Win95	Yes
Win32s
Import Library
Header File
Unicode
Platform Notes	None


Var
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


VarFileInfo
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


VERIFY_INFORMATION
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


VS_FIXEDFILEINFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


VS_VERSION_INFO
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WAVEFILTER
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WAVEFORMAT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WAVEFORMAT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WAVEFORMATEX
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WAVEHDR
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WAVEHDR
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WAVEINCAPS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WAVEINCAPS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WAVEOUTCAPS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WAVEOUTCAPS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WIN32_FIND_DATA
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WIN32_STREAM_ID
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WINDOW_BUFFER_SIZE_RECORD
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WINDOWPLACEMENT
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WINDOWPOS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WNDCLASS
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


WNDCLASSEX
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


XFORM
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


CountClipboardFormats
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


CreateAcceleratorTable
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


CreateAntiMoniker
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	No
Platform Notes	None


CreateBindCtx
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	No
Platform Notes	None


CreateBitmap
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


CreateBitmapIndirect
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


CreateBrushIndirect
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


CreateCaret
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


CreateColorSpace
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	WinNT
Platform Notes	None


CreateCompatibleBitmap
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


CreateCompatibleDC
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


CreateConsoleScreenBuffer
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	wincon.h
Unicode	No
Platform Notes	None


CreateCursor
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


CreateDataAdviseHolder
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	No
Platform Notes	None


CreateDataCache
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	No
Platform Notes	None


CreateDC
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	WinNT
Platform Notes	Windows 95: int == 16 bits


CreateDesktop
Windows NT	Yes
Win95	No
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


CreateDialog
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CreateDialogIndirect
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CreateDialogIndirectParam
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


CreateDialogParam
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


CreateDIBitmap
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


CreateDIBPatternBrush
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


CreateDIBPatternBrushPt
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


CreateDIBSection
Windows NT	New
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


CreateDirectory
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


CreateDirectoryEx
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


CreateDiscardableBitmap
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


CreateDispTypeInfo
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	WinNT; Win95; Win32s
Platform Notes	All 32-bit OLE Apis are UNICODE only


CreateEditableStream
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


CreateEllipticRgn
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


CreateEllipticRgnIndirect
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


CreateEnhMetaFile
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	WinNT
Platform Notes	None


CreateErrorInfo
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


CreateEvent
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


CreateFile
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


CreateFileMapping
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


CreateFileMoniker
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	WinNT; Win95; Win32s
Platform Notes	All 32-bit OLE Apis are UNICODE only


CreateFont
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	WinNT
Platform Notes	Windows 95: int == 16 bits


CreateFontIndirect
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	WinNT
Platform Notes	Windows 95: int == 16 bits


CreateGenericComposite
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	No
Platform Notes	None


CreateHalftonePalette
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


CreateHatchBrush
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


CreateIC
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	WinNT
Platform Notes	Windows 95: int == 16 bits


CreateIcon
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


CreateIconFromResource
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


CreateIconFromResourceEx
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


CreateIconIndirect
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


CreateILockBytesOnHGlobal
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


CreateIoCompletionPort
Windows NT	New
Win95	No
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


CreateItemMoniker
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	WinNT; Win95; Win32s
Platform Notes	All 32-bit OLE Apis are UNICODE only


CreateMailslot
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


CreateMappedBitmap
Windows NT	Yes
Win95	Yes
Win32s
Import Library
Header File	commctrl.h
Unicode	No
Platform Notes	None


CreateMDIWindow
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


CreateMenu
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


CreateMetaFile
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	WinNT
Platform Notes	Windows 95: int == 16 bits


CreateMutex
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


CreateNamedPipe
Windows NT	Yes
Win95	No
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


CreateOleAdviseHolder
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


CreatePalette
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


CreatePatternBrush
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


CreatePen
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


CreatePenIndirect
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


CreatePipe
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


CreatePointerMoniker
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	No
Platform Notes	None


CreatePolygonRgn
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


CreatePolyPolygonRgn
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


CreatePopupMenu
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


CreatePrivateObjectSecurity
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


CreateProcess
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


CreateProcessAsUser
Windows NT	New
Win95	No
Win32s	No
Import Library
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


CreatePropertySheetPage
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	prsht.h
Unicode	WinNT
Platform Notes	None


CreateRectRgn
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


CreateRectRgnIndirect
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


CreateRemoteThread
Windows NT	Yes
Win95	No
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


CreateRoundRectRgn
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


CreateScalableFontResource
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	WinNT
Platform Notes	Windows 95: int == 16 bits


CreateSemaphore
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


CreateService
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winsvc.h
Unicode	WinNT
Platform Notes	None


CreateSolidBrush
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


CreateStatusWindow
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	commctrl.h
Unicode	WinNT
Platform Notes	None


CreateStdDispatch
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


CreateStreamOnHGlobal
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


CreateTapePartition
Windows NT	Yes
Win95	No
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


CreateThread
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


CreateToolbarEx
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	commctrl.h
Unicode	No
Platform Notes	None


CreateTypeLib
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	WinNT; Win95; Win32s
Platform Notes	All 32-bit OLE Apis are UNICODE only


CreateUpDownControl
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	commctrl.h
Unicode	No
Platform Notes	None


CreateWindow
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


CreateWindowEx
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	hMenu limited to WORD on Win32s


CreateWindowStation
Windows NT	Yes
Win95	No
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


data_from_ndr
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcndr.h
Unicode
Platform Notes	None


data_into_ndr
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcndr.h
Unicode
Platform Notes	None


data_size_ndr
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcndr.h
Unicode
Platform Notes	None


DceErrorInqText
Windows NT	New
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcdce.h
Unicode	WinNT
Platform Notes	None


DdeAbandonTransaction
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	ddeml.h
Unicode	No
Platform Notes	None


DdeAccessData
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	ddeml.h
Unicode	No
Platform Notes	None


DdeAddData
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	ddeml.h
Unicode	No
Platform Notes	None


DdeClientTransaction
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	ddeml.h
Unicode	No
Platform Notes	None


DdeCmpStringHandles
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	ddeml.h
Unicode	No
Platform Notes	None


DdeConnect
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	ddeml.h
Unicode	No
Platform Notes	None


DdeConnectList
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	ddeml.h
Unicode	No
Platform Notes	None


DdeCreateDataHandle
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	ddeml.h
Unicode	No
Platform Notes	None


DdeCreateStringHandle
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	ddeml.h
Unicode	WinNT
Platform Notes	None


DdeDisconnect
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	ddeml.h
Unicode	No
Platform Notes	None


DdeDisconnectList
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	ddeml.h
Unicode	No
Platform Notes	None


DdeEnableCallback
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	ddeml.h
Unicode	No
Platform Notes	None


DdeFreeDataHandle
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	ddeml.h
Unicode	No
Platform Notes	None


DdeFreeStringHandle
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	ddeml.h
Unicode	No
Platform Notes	None


DdeGetData
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	ddeml.h
Unicode	No
Platform Notes	None


DdeGetLastError
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	ddeml.h
Unicode	No
Platform Notes	None


DdeImpersonateClient
Windows NT	Yes
Win95	No
Win32s	No
Import Library	user32.lib
Header File	ddeml.h
Unicode	No
Platform Notes	None


DdeInitialize
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	ddeml.h
Unicode	WinNT
Platform Notes	None


DdeKeepStringHandle
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	ddeml.h
Unicode	No
Platform Notes	None


DdeNameService
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	ddeml.h
Unicode	No
Platform Notes	None


DdePostAdvise
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	ddeml.h
Unicode	No
Platform Notes	None


DdeQueryConvInfo
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	ddeml.h
Unicode	No
Platform Notes	None


DdeQueryNextServer
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	ddeml.h
Unicode	No
Platform Notes	None


DdeQueryString
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	ddeml.h
Unicode	WinNT
Platform Notes	None


DdeReconnect
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	ddeml.h
Unicode	No
Platform Notes	None


DdeSetQualityOfService
Windows NT	Yes
Win95	No
Win32s	No
Import Library	user32.lib
Header File	dde.h
Unicode	No
Platform Notes	None


DdeSetUserHandle
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	ddeml.h
Unicode	No
Platform Notes	None


DdeUnaccessData
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	ddeml.h
Unicode	No
Platform Notes	None


DdeUninitialize
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	ddeml.h
Unicode	No
Platform Notes	None


DebugActiveProcess
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


DebugBreak
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


DefDlgProc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


DefDriverProc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


DeferWindowPos
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


DefFrameProc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


DefHookProc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


DefineDosDevice
Windows NT	Yes
Win95	No
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


DefineHandleTable
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winbase.h
Unicode	No
Platform Notes	None


DefMDIChildProc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


DefScreenSaverProc
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	scrnsave.lib
Header File	scrnsave.h
Unicode	No
Platform Notes	None


DefWindowProc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


DeleteAce
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


DeleteAtom
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


DeleteColorSpace
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


DeleteCriticalSection
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


DeleteDC
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


DeleteEnhMetaFile
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


DeleteFile
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


DeleteForm
Windows NT	Yes
Win95	No
Win32s	No
Import Library	winspool.lib
Header File	winspool.h
Unicode	WinNT
Platform Notes	None


DeleteMenu
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


DeleteMetaFile
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


DeleteMonitor
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	winspool.lib
Header File	winspool.h
Unicode	WinNT
Platform Notes	None


DeleteObject
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


DeletePort
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	winspool.lib
Header File	winspool.h
Unicode	WinNT
Platform Notes	None


DeletePrinter
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	winspool.lib
Header File	winspool.h
Unicode	No
Platform Notes	None


DeletePrinterDriver
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	winspool.lib
Header File	winspool.h
Unicode	WinNT
Platform Notes	None


DeletePrintProcessor
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	winspool.lib
Header File	winspool.h
Unicode	WinNT
Platform Notes	None


DeletePrintProvidor
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	winspool.lib
Header File	winspool.h
Unicode	WinNT
Platform Notes	None


DeleteService
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winsvc.h
Unicode	No
Platform Notes	None


DeregisterEventSource
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


DescribePixelFormat
Windows NT	Yes
Win95	No
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


DestroyAcceleratorTable
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


DestroyCaret
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


DestroyCursor
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


DestroyIcon
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


DestroyMenu
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


DestroyPrivateObjectSecurity
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


DestroyPropertySheetPage
Windows NT	Yes
Win95	Yes
Win32s
Import Library
Header File	prsht.h
Unicode	No
Platform Notes	None


DestroyWindow
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


DeviceCapabilitiesEx
Windows NT	No
Win95	No
Win32s	No
Import Library	gdi32.lib
Header File
Unicode	No
Platform Notes	None


DeviceIoControl
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


DialogBox
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


DialogBoxIndirect
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


DialogBoxIndirectParam
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


DialogBoxParam
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


DisableThreadLibraryCalls
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


DisconnectNamedPipe
Windows NT	Yes
Win95	No
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


DispatchMessage
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


DispGetIDsOfNames
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


DispGetParam
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


DispInvoke
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


DlgDirList
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


DlgDirListComboBox
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


DlgDirSelectComboBoxEx
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


DlgDirSelectEx
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


DllEntryPoint
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File
Unicode	No
Platform Notes	None


DllGetClassObject
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	objbase.h
Unicode
Platform Notes	None


DocumentProperties
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	winspool.lib
Header File	winspool.h
Unicode	WinNT
Platform Notes	None


DoDragDrop
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


DosDateTimeToFileTime
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


DosDateTimeToVariantTime
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


double_array_from_ndr
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcndr.h
Unicode
Platform Notes	None


double_from_ndr
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcndr.h
Unicode
Platform Notes	None


DPtoLP
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


DragAcceptFiles
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	shell32.lib
Header File	shellapi.h
Unicode	No
Platform Notes	None


DragDetect
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


DragFinish
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	shell32.lib
Header File	shellapi.h
Unicode	No
Platform Notes	None


DragObject
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


DragQueryFile
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	shell32.lib
Header File	shellapi.h
Unicode	WinNT
Platform Notes	None


DragQueryPoint
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	shell32.lib
Header File	shellapi.h
Unicode	No
Platform Notes	None


DrawAnimatedRects
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


DrawCaption
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


DrawDibBegin
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


DrawDibChangePalette
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


DrawDibClose
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


DrawDibDraw
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


DrawDibEnd
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


DrawDibGetBuffer
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


DrawDibGetPalette
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


DrawDibOpen
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


DrawDibProfileDisplay
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


DrawDibRealize
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


DrawDibSetPalette
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


DrawDibStart
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


DrawDibStop
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


DrawDibTime
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


DrawEdge
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


DrawEscape
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


DrawFocusRect
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


DrawFrameControl
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


DrawIcon
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


DrawIconEx
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


DrawInsert
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	commctrl.h
Unicode	No
Platform Notes	None


DrawMenuBar
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


DrawState
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


DrawStatusText
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	commctrl.h
Unicode	WinNT
Platform Notes	None


DrawText
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


DrawTextEx
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


DriverCallback
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	digitalv.h
Unicode	No
Platform Notes	None


DrvGetModuleHandle
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


DrvSendMessage
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File	mmsystem.h
Unicode	No
Platform Notes	None


DuplicateHandle
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


DuplicateIcon
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	shell32.lib
Header File	shellapi.h
Unicode	No
Platform Notes	None


DuplicateToken
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


EditStreamClone
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


EditStreamCopy
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


EditStreamCut
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


EditStreamPaste
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	No
Platform Notes	None


EditStreamSetInfo
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	WinNT
Platform Notes	None


EditStreamSetName
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	WinNT
Platform Notes	None


Ellipse
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


EmptyClipboard
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


EnableMenuItem
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


EnableScrollBar
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


EnableWindow
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


EndDeferWindowPos
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


EndDialog
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


EndDoc
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


EndDocPrinter
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	winspool.lib
Header File	winspool.h
Unicode	No
Platform Notes	None


EndPage
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


EndPagePrinter
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	winspool.lib
Header File	winspool.h
Unicode	No
Platform Notes	None


EndPaint
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


EndPath
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


EndUpdateResource
Windows NT	Yes
Win95	No
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


EnterCriticalSection
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


enum_from_ndr
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcndr.h
Unicode
Platform Notes	None


EnumCalendarInfo
Windows NT	New
Win95	New
Win32s	New
Import Library	kernel32.lib
Header File	winnls.h
Unicode	WinNT
Platform Notes	None


EnumChildWindows
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


EnumClipboardFormats
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


EnumDateFormats
Windows NT	New
Win95	New
Win32s	New
Import Library	kernel32.lib
Header File	winnls.h
Unicode	WinNT
Platform Notes	None


EnumDependentServices
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winsvc.h
Unicode	WinNT
Platform Notes	None


EnumDesktops
Windows NT	Yes
Win95	No
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


EnumDesktopWindows
Windows NT	Yes
Win95	No
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


EnumDisplaySettings
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


EnumEnhMetaFile
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


EnumFontFamilies
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	WinNT
Platform Notes	Windows 95: int == 16 bits


EnumFontFamiliesEx
Windows NT	No
Win95	Yes
Win32s	No
Import Library
Header File
Unicode
Platform Notes	None


EnumFonts
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	WinNT
Platform Notes	Windows 95: int == 16 bits


EnumForms
Windows NT	Yes
Win95	No
Win32s	No
Import Library	winspool.lib
Header File	winspool.h
Unicode	WinNT
Platform Notes	None


EnumICMProfiles
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	WinNT
Platform Notes	None


EnumJobs
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	winspool.lib
Header File	winspool.h
Unicode	WinNT
Platform Notes	None


EnumMetaFile
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


EnumMonitors
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	winspool.lib
Header File	winspool.h
Unicode	WinNT
Platform Notes	None


EnumObjects
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


EnumPorts
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	winspool.lib
Header File	winspool.h
Unicode	WinNT
Platform Notes	None


EnumPrinterDrivers
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	winspool.lib
Header File	winspool.h
Unicode	WinNT
Platform Notes	None


EnumPrinters
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	winspool.lib
Header File	winspool.h
Unicode	WinNT
Platform Notes	None


EnumPrintProcessorDatatypes
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	winspool.lib
Header File	winspool.h
Unicode	WinNT
Platform Notes	None


EnumPrintProcessors
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	winspool.lib
Header File	winspool.h
Unicode	WinNT
Platform Notes	None


EnumProps
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


EnumPropsEx
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


EnumProtocols
Windows NT	Yes
Win95	No
Win32s	No
Import Library	wsock32.lib
Header File	nspapi.h
Unicode	WinNT
Platform Notes	None


EnumResourceLanguages
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT; Win95
Platform Notes	None


EnumResourceNames
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT; Win95
Platform Notes	None


EnumResourceTypes
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT; Win95
Platform Notes	None


EnumServicesStatus
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winsvc.h
Unicode	WinNT
Platform Notes	None


EnumSystemCodePages
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winnls.h
Unicode	WinNT
Platform Notes	None


EnumSystemLocales
Windows NT	New
Win95	New
Win32s	New
Import Library	kernel32.lib
Header File	winnls.h
Unicode	WinNT
Platform Notes	None


EnumTaskWindows
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


EnumThreadWindows
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


EnumTimeFormats
Windows NT	New
Win95	New
Win32s	New
Import Library	kernel32.lib
Header File	winnls.h
Unicode	WinNT
Platform Notes	None


EnumWindows
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


EnumWindowStations
Windows NT	Yes
Win95	No
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


EqualPrefixSid
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


EqualRect
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


EqualRgn
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


EqualSid
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


EraseTape
Windows NT	Yes
Win95	No
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


Escape
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


EscapeCommFunction
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


ExcludeClipRect
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


ExcludeUpdateRgn
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


ExitProcess
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


ExitThread
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


ExitWindows
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


ExitWindowsEx
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


ExpandEnvironmentStrings
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


ExtCreatePen
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	New
Platform Notes	Windows 95: Only supports solid colors (e.g.


ExtCreateRegion
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: Fails if the transform involves a shearing or rotation; int == 16 bits


ExtEscape
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


ExtFloodFill
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


ExtractAssociatedIcon
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	shell32.lib
Header File	shellapi.h
Unicode	WinNT
Platform Notes	None


ExtractIcon
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	shell32.lib
Header File	shellapi.h
Unicode	WinNT
Platform Notes	None


ExtractIconEx
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library
Header File	shellapi.h
Unicode
Platform Notes	None


ExtSelectClipRgn
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


ExtTextOut
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	WinNT; Win95
Platform Notes	Windows 95: 16-bit coordinates only


FatalAppExit
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


FatalExit
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


FileTimeToDosDateTime
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


FileTimeToLocalFileTime
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	Win32s always uses LocalTime never UTC


FileTimeToSystemTime
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


FillConsoleOutputAttribute
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	wincon.h
Unicode	No
Platform Notes	None


FillConsoleOutputCharacter
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	wincon.h
Unicode	WinNT
Platform Notes	None


FillMemory
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winbase.h
Unicode	No
Platform Notes	None


FillPath
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


FillRect
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


FillRgn
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


FindAtom
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


FindClose
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


FindCloseChangeNotification
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


FindClosePrinterChangeNotification
Windows NT	New
Win95	No
Win32s	No
Import Library	winspool.lib
Header File	winspool.h
Unicode	No
Platform Notes	None


FindExecutable
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	shell32.lib
Header File	shellapi.h
Unicode	WinNT
Platform Notes	None


FindFirstChangeNotification
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


FindFirstFile
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	Win32s returns times in LocalTime


FindFirstFreeAce
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


FindFirstPrinterChangeNotification
Windows NT	New
Win95	No
Win32s	No
Import Library	winspool.lib
Header File	winspool.h
Unicode	No
Platform Notes	None


FindNextChangeNotification
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


FindNextFile
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	Win32s returns times in LocalTime


FindNextPrinterChangeNotification
Windows NT	New
Win95	No
Win32s	No
Import Library	winspool.lib
Header File	winspool.h
Unicode	No
Platform Notes	None


FindResource
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT; Win95
Platform Notes	None


FindResourceEx
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT; Win95
Platform Notes	None


FindText
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	comdlg32.lib
Header File	commdlg.h
Unicode	WinNT
Platform Notes	None


FindWindow
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


FindWindowEx
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


FixBrushOrgEx
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


FlashWindow
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


FlattenPath
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


float_array_from_ndr
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcndr.h
Unicode
Platform Notes	None


float_from_ndr
Windows NT	Yes
Win95	No
Win32s	No
Import Library	rpcrt4.lib
Header File	rpcndr.h
Unicode
Platform Notes	None


FloodFill
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


FlushConsoleInputBuffer
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	wincon.h
Unicode	No
Platform Notes	None


FlushFileBuffers
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


FlushInstructionCache
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	This is valid on SMP platforms only; Windows 95 returns a constant


FlushViewOfFile
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


FoldString
Windows NT	Yes
Win95	No
Win32s	Yes
Import Library	kernel32.lib
Header File	winnls.h
Unicode	WinNT
Platform Notes	None


FormatMessage
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


FrameRect
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


FrameRgn
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


FreeConsole
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	wincon.h
Unicode	No
Platform Notes	None


FreeDDElParam
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	dde.h
Unicode	No
Platform Notes	None


FreeEnvironmentStrings
Windows NT	New
Win95	New
Win32s	New
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


FreeImageColorMatcher
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


FreeLibrary
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


FreeLibraryAndExitThread
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


FreeModule
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winbase.h
Unicode	No
Platform Notes	None


FreeProcInstance
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winbase.h
Unicode	No
Platform Notes	None


FreeResource
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


FreeSid
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GdiComment
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


GdiFlush
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


GdiGetBatchLimit
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


GdiSetBatchLimit
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


GenerateConsoleCtrlEvent
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	wincon.h
Unicode	No
Platform Notes	None


GetAce
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetAclInformation
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetACP
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winnls.h
Unicode	No
Platform Notes	None


GetActiveObject
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


GetActiveWindow
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetAddressByName
Windows NT	Yes
Win95	No
Win32s	No
Import Library	wsock32.lib
Header File	nspapi.h
Unicode	WinNT
Platform Notes	None


GetArcDirection
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


GetAspectRatioFilterEx
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


GetAsyncKeyState
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetAtomName
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


GetBinaryType
Windows NT	New
Win95	No
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


GetBitmapBits
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


GetBitmapDimensionEx
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


GetBkColor
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


GetBkMode
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


GetBoundsRect
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


GetBrushOrgEx
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


GetCapture
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetCaretBlinkTime
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetCaretPos
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetCharABCWidths
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	WinNT
Platform Notes	Windows 95: int == 16 bits


GetCharABCWidthsFloat
Windows NT	Yes
Win95	No
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	WinNT
Platform Notes	None


GetCharacterPlacement
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	WinNT
Platform Notes	None


GetCharWidth
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	WinNT; Win95
Platform Notes	Windows 95: int == 16 bits


GetCharWidth32
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	WinNT
Platform Notes	Windows 95: int == 16 bits


GetCharWidthFloat
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	WinNT
Platform Notes	Windows 95: int == 16 bits


GetClassFile
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	WinNT; Win95; Win32s
Platform Notes	All 32-bit OLE Apis are UNICODE only


GetClassInfo
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


GetClassInfoEx
Windows NT	Stub
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


GetClassLong
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


GetClassName
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


GetClassWord
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetClientRect
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetClipboardData
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetClipboardFormatName
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


GetClipboardOwner
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetClipboardViewer
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetClipBox
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


GetClipCursor
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetClipRgn
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


GetColorAdjustment
Windows NT	Yes
Win95	No
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


GetColorSpace
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


GetCommandLine
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT; Win95
Platform Notes	None


GetCommConfig
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetCommMask
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetCommModemStatus
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetCommProperties
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetCommState
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetCommTimeouts
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetCompressedFileSize
Windows NT	New
Win95	No
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


GetComputerName
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


GetConsoleCP
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	wincon.h
Unicode	No
Platform Notes	Windows 95 limitations


GetConsoleCursorInfo
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	wincon.h
Unicode	No
Platform Notes	None


GetConsoleMode
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	wincon.h
Unicode	No
Platform Notes	None


GetConsoleOutputCP
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	wincon.h
Unicode	No
Platform Notes	Windows 95 limitations


GetConsoleScreenBufferInfo
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	wincon.h
Unicode	No
Platform Notes	None


GetConsoleTitle
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	wincon.h
Unicode	WinNT
Platform Notes	None


GetConvertStg
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	No
Platform Notes	None


GetCPInfo
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winnls.h
Unicode	No
Platform Notes	None


GetCurrencyFormat
Windows NT	New
Win95	New
Win32s	New
Import Library	kernel32.lib
Header File	winnls.h
Unicode	WinNT
Platform Notes	None


GetCurrentDirectory
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


GetCurrentObject
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


GetCurrentPositionEx
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


GetCurrentProcess
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetCurrentProcessId
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetCurrentThread
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetCurrentThreadId
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetCurrentTime
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winbase.h
Unicode	No
Platform Notes	None


GetCursor
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetCursorPos
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetDateFormat
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winnls.h
Unicode	WinNT
Platform Notes	None


GetDC
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetDCEx
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetDCOrgEx
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


GetDefaultCommConfig
Windows NT	No
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


GetDesktopWindow
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetDeviceCaps
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


GetDeviceGammaRamp
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


GetDialogBaseUnits
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetDIBColorTable
Windows NT	New
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


GetDIBits
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


GetDiskFreeSpace
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


GetDlgCtrlID
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetDlgItem
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetDlgItemInt
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetDlgItemText
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


GetDoubleClickTime
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetDriverModuleHandle
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	winmm.lib
Header File	mmsystem.h
Unicode	No
Platform Notes	None


GetDriveType
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


GetEffectiveClientRect
Windows NT	Yes
Win95	Yes
Win32s
Import Library
Header File	commctrl.h
Unicode	No
Platform Notes	None


GetEnhMetaFile
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	WinNT
Platform Notes	None


GetEnhMetaFileBits
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


GetEnhMetaFileDescription
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	WinNT
Platform Notes	None


GetEnhMetaFileHeader
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


GetEnhMetaFilePaletteEntries
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


GetEnvironmentStrings
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetEnvironmentVariable
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


GetErrorInfo
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	oleaut32.lib
Header File	oleauto.h
Unicode	No
Platform Notes	None


GetExceptionCode
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File
Unicode
Platform Notes	None


GetExceptionInformation
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File
Unicode
Platform Notes	None


GetExitCodeProcess
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetExitCodeThread
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetExpandedName
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	lz32.lib
Header File	lzexpand.h
Unicode	WinNT
Platform Notes	None


GetFileAttributes
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


GetFileInformationByHandle
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetFileSecurity
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


GetFileSize
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetFileTime
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetFileTitle
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	comdlg32.lib
Header File	commdlg.h
Unicode	WinNT
Platform Notes	None


GetFileType
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetFileVersionInfo
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	version.lib
Header File	winver.h
Unicode	WinNT
Platform Notes	None


GetFileVersionInfoSize
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	version.lib
Header File	winver.h
Unicode	WinNT
Platform Notes	None


GetFocus
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetFontData
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


GetFontLanguageInfo
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


GetForegroundWindow
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetForm
Windows NT	Yes
Win95	No
Win32s	No
Import Library	winspool.lib
Header File	winspool.h
Unicode	WinNT
Platform Notes	None


GetFreeSpace
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winbase.h
Unicode	No
Platform Notes	None


GetFullPathName
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


GetGlyphOutline
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


GetGraphicsMode
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: Only GM_COMPATIBLE is supported


GetHandleInformation
Windows NT	Yes
Win95	No
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetHGlobalFromILockBytes
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


GetHGlobalFromStream
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	ole2.h
Unicode	No
Platform Notes	None


gethostbyaddr
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	wsock32.lib
Header File	winsock.h
Unicode	No
Platform Notes	None


gethostbyname
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	wsock32.lib
Header File	winsock.h
Unicode	No
Platform Notes	None


gethostname
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	wsock32.lib
Header File	winsock.h
Unicode	No
Platform Notes	None


GetICMProfile
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	WinNT
Platform Notes	None


GetIconInfo
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetInputState
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetJob
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	winspool.lib
Header File	winspool.h
Unicode	WinNT
Platform Notes	None


GetKBCodePage
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetKernelObjectSecurity
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetKerningPairs
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


GetKeyboardLayout
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetKeyboardLayoutList
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetKeyboardLayoutName
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


GetKeyboardState
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetKeyboardType
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetKeyNameText
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


GetKeyState
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetLargestConsoleWindowSize
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	wincon.h
Unicode	No
Platform Notes	None


GetLastActivePopup
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetLastError
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetLengthSid
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetLocaleInfo
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winnls.h
Unicode	WinNT
Platform Notes	None


GetLocalTime
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetLogColorSpace
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	WinNT
Platform Notes	None


GetLogicalDrives
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetLogicalDriveStrings
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


GetMailslotInfo
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetMapMode
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


GetMenu
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetMenuCheckMarkDimensions
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetMenuContextHelpId
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetMenuDefaultItem
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetMenuItemCount
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetMenuItemID
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetMenuItemInfo
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


GetMenuItemRect
Windows NT	Stub
Win95	Yes
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetMenuState
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetMenuString
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


GetMessage
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


GetMessageExtraInfo
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetMessagePos
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetMessageTime
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetMetaFile
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	WinNT
Platform Notes	Windows 95: int == 16 bits


GetMetaFileBitsEx
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


GetMetaRgn
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


GetMiterLimit
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


GetModuleFileName
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


GetModuleHandle
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


GetNameByType
Windows NT	Yes
Win95	No
Win32s	No
Import Library	wsock32.lib
Header File	nspapi.h
Unicode	WinNT
Platform Notes	None


GetNamedPipeHandleState
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


GetNamedPipeInfo
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetNearestColor
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


GetNearestPaletteIndex
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


GetNextDlgGroupItem
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetNextDlgTabItem
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetNextWindow
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library
Header File	winuser.h
Unicode	No
Platform Notes	None


GetNumberFormat
Windows NT	New
Win95	New
Win32s	New
Import Library	kernel32.lib
Header File	winnls.h
Unicode	WinNT
Platform Notes	None


GetNumberOfConsoleInputEvents
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	wincon.h
Unicode	No
Platform Notes	None


GetNumberOfConsoleMouseButtons
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	wincon.h
Unicode	No
Platform Notes	None


GetNumberOfEventLogRecords
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetObject
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	WinNT
Platform Notes	Windows 95: int == 16 bits


GetObjectType
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


GetOEMCP
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winnls.h
Unicode	No
Platform Notes	None


GetOldestEventLogRecord
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetOpenClipboardWindow
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetOpenFileName
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	comdlg32.lib
Header File	commdlg.h
Unicode	WinNT
Platform Notes	None


GetOpenFileNamePreview
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	vfw32.lib
Header File	vfw.h
Unicode	WinNT
Platform Notes	None


GetOutlineTextMetrics
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	WinNT
Platform Notes	Windows 95: int == 16 bits


GetOverlappedResult
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	Windows 95: Only on serial and IOCTL devices


GetPaletteEntries
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


GetParent
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetPath
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


getpeername
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	wsock32.lib
Header File	winsock.h
Unicode	No
Platform Notes	None


GetPixel
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: 16-bit coordinates only


GetPixelFormat
Windows NT	Yes
Win95	No
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	None


GetPolyFillMode
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


GetPrinter
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	winspool.lib
Header File	winspool.h
Unicode	WinNT
Platform Notes	None


GetPrinterData
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	winspool.lib
Header File	winspool.h
Unicode	WinNT
Platform Notes	None


GetPrinterDriver
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	winspool.lib
Header File	winspool.h
Unicode	WinNT
Platform Notes	None


GetPrinterDriverDirectory
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	winspool.lib
Header File	winspool.h
Unicode	WinNT
Platform Notes	None


GetPrintProcessorDirectory
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	winspool.lib
Header File	winspool.h
Unicode	WinNT
Platform Notes	None


GetPriorityClass
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetPriorityClipboardFormat
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetPrivateObjectSecurity
Windows NT	Yes
Win95	No
Win32s	No
Import Library	advapi32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetPrivateProfileInt
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


GetPrivateProfileSection
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


GetPrivateProfileSectionNames
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


GetPrivateProfileString
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


GetPrivateProfileStruct
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


GetProcAddress
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetProcessAffinityMask
Windows NT	New
Win95	New
Win32s	New
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	This is valid on SMP platforms only; Windows 95 returns a constant


GetProcessHeap
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetProcessHeaps
Windows NT	New
Win95	Yes
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetProcessShutdownParameters
Windows NT	Yes
Win95	No
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetProcessTimes
Windows NT	Yes
Win95	No
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetProcessVersion
Windows NT	New
Win95	New
Win32s	No
Import Library
Header File	winbase.h
Unicode	No
Platform Notes	None


GetProcessWindowStation
Windows NT	Yes
Win95	No
Win32s	No
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetProcessWorkingSetSize
Windows NT	New
Win95	No
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetProfileInt
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


GetProfileSection
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


GetProfileSectionNames
Windows NT	No
Win95	No
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


GetProfileString
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	kernel32.lib
Header File	winbase.h
Unicode	WinNT
Platform Notes	None


GetProp
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	WinNT
Platform Notes	None


getprotobyname
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	wsock32.lib
Header File	winsock.h
Unicode	No
Platform Notes	None


getprotobynumber
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	wsock32.lib
Header File	winsock.h
Unicode	No
Platform Notes	None


GetQueuedCompletionStatus
Windows NT	New
Win95	No
Win32s	No
Import Library	kernel32.lib
Header File	winbase.h
Unicode	No
Platform Notes	None


GetQueueStatus
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	user32.lib
Header File	winuser.h
Unicode	No
Platform Notes	None


GetRasterizerCaps
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


GetRegionData
Windows NT	Yes
Win95	Yes
Win32s	No
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


GetResourceID
Windows NT
Win95
Win32s
Import Library
Header File
Unicode
Platform Notes	None


GetRgnBox
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


GetROP2
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	gdi32.lib
Header File	wingdi.h
Unicode	No
Platform Notes	Windows 95: int == 16 bits


GetRunningObjectTable
Windows NT	Yes
Win95	Yes
Win32s	Yes
Import Library	ole32.lib
Header File	objbase.h
Unicode	No
Platform Notes	None


Microsoft Win32 Developer's Reference
Microsoft Win32 Developer’s Reference

You have requested information from the Microsoft Win32 Developer’s Reference. One or more of these help files is not available on your system.


OLE Glossary
 Glossary

A

Activation

The process of binding an object in order to put it into its running state. Also refers to invoking a particular operation on an object. See also Binding.

Absolute moniker

A moniker that specifies the absolute location of an object. An absolute moniker is analogous to a full pathname. See also Moniker.

Advisory sink

An object that can receive notifications of changes in an embedded object or linked object because it implements the IAdviseSink interface (and possibly the IAdviseSink2 interface). Notifications originate in the object application, where they are cached in an advise holder, which passes them to advisory sinks implemented by object handlers. For an embedded object, the corresponding object handler forwards the notification to the object's container. For a linked object, the object handler forwards the notification to the link object, which in turn passes it on to the container. See also Object handler, Embedded object, Link object, Linked object, Container application.

Aggregate object

A component object that is made up of one or more other component objects. One object in the aggregate is designated the control object, which controls which interfaces in the aggregate are exposed and which are private. The control object has a special implementation of IUnknown called the controlling unknown. All non-controlling objects in the aggregate must pass calls to IUnknown methods through the controlling unknown.

Aggregation

A composition technique for implementing component objects. It allows you to build a new object with one or more existing objects that support some or all of the new object's required interfaces.

Anti-moniker

The inverse of a file, item, or pointer moniker. An anti-moniker is added to the end of a file-, item-, or pointer moniker to nullify it. This is analogous to the way that ".." nullifies a directory component of a pathname (that is, \work\art\.. equals \work). Anti-monikers are used in the construction of relative monikers. See also Relative Moniker.

Artificial reference counting

A technique used to safeguard an object before making a call that could result in its premature destruction by ensuring it won't be de-allocated. A process calls the AddRef method of IUnknown to increment the count before making the call that could otherwise free the object prematurely, and after the function returns, calls the IUnknown::Release method to decrement the count.

Asynchronous call

A function that allows the next instruction in the process to be executed as soon as the call is made, without waiting for the function to return. Most OLE functions and interface methods are synchronous; that is, the function must return before the next instruction is executed. OLE defines six asynchronous methods, five within the IAdviseSink interface — OnDataChange, OnViewChange, OnRename, OnSave, and OnClose — and one within the IAdviseSink2 interface — OnLinkSourceChange.

Automation

See OLE Automation

B

Bind context

An object that implements the IBindCtx interface. Bind contexts are used in moniker operations. A bind context holds references to the objects activated when a moniker is bound, contains parameters that apply to all operations during the binding of a generic composite moniker, and provides the means by which the moniker implementation should retrieve information about its environment. See Binding, Moniker.

Binding

Generically, binding is the process of associating a name to its referent. When referring to monikers specifically, binding is the process of locating the object named by the moniker, activating it (loading it in memory) if it isn't already, and returning an interface pointer to it. Binding puts an object into its running state, allowing the operations it supports to be invoked. Objects can be bound at run time (also called late binding or dynamic binding) or at compile time (also called static binding). In OLE Automation, vtable-based binding is referred to as "early binding" and IDispatch-based binding is referred to as "late binding."

C

Cache

Generally, a cache is a (usually temporary) local store of information. In OLE, the term cache is used in connection with linked or embedded objects, in which the cache contains information that defines the presentation of a contained object when the container is opened.

Cache initialization

The process of filling an embedded object's cache with data formats. The IOleCache interface provides methods that a container object can call to control the data that gets cached for embedded objects.. The IOleCache::InitCache method fills the cache using data provided by a transfer from the Clipboard or from a drag-and-drop operation. The IOleCache::SetData method fills the cache using data in a storage object.

Class

In object-oriented programming, a class is a set of objects whose behavior is defined by the same set of code (they share the same implementation).
A COM class is not necessarily the same as a class in an object-oriented language. A COM class can be identified by a CLSID, though for most COM operations, it is not necessary to know an object's class.

Class factory

A object that you use to create one or more instances of a an object identified by a given CLSID (class identifier). A class factory object implements the IClassFactory interface. A class factory is the most frequently used type of class object in OLE. See also CLSID.

Class identifier (CLSID)

A unique identification tag (UUID) associated with an OLE class object. A class object that is intended to create more than one object registers its CLSID in a task table in the registration database to enable clients to locate and load the executable code associated with the object(s). Every OLE object application (or container that allows linking to its embedded objects) must register a CLSID for each supported object definition.

Class object

In COM, class objects are called class factories, and typically have no behavior except to create new instances of the class. In object-oriented programming, an object whose state is shared by all the objects in a class, and whose behavior acts on that class-wide state data. See also Class factory.

Client

In referring to OLE objects, an object that requests services from another object. See also Container.

Client site

The display site for an embedded or linked object within a compound document. The client site is the principal means by which an object requests services from its container.

CLSID

See Class identifier

Component object

An object that conforms to the OLE component object model (COM). Clients deal with a component object only through a pointer to an interface (a related set of functions called methods). With the pointer, clients can call the methods that perform operations or manipulate the data associated with the object. Component objects are instances of an object definition, which specifies an implementation of the interfaces on the object.

Composite moniker

A moniker that consists of two or more monikers composed together. A composite moniker can be non-generic, meaning that its component monikers have special knowledge of each other, or generic, meaning that its component monikers know nothing about each other except that they are monikers. See Generic composite moniker.

Commit

The act of persistently saving any changes made to an object since its storage was opened or since the last time changes were saved. See also Revert.

Component object model (COM)

The OLE object-oriented programming model that defines how objects interact within a single application or between applications. In COM, clients have access to an OLE object through a pointer to an interface (a related set of functions called methods) on the object.

Composite menu

A shared menu bar composed of menu groups from both an in-place container and an in-place object application. The object application must install and remove the menu from the container's frame window.

Compound document

A document that contains data of different formats, created by different applications. Compound documents are created in a container application, such as Word, and information from other applications (such as spreadsheets, sound clips, and bitmaps) is either embedded in or linked to the container application. When the compound document is saved, the container application saves it.

Compound file

An OLE-provided implementation of structured storage which includes the IStorage, the IStream, and the ILockBytes interfaces. You use a set of StgXxx API functions to create and use a compound file.

Container

See Container application.

Container application

An application that supports compound documents. Container applications provide storage for the object, a site for display, access to the display site, and an advisory sink for receiving notifications of changes in the object. See also Compound document, Client site, and Advisory sink.

Container/Object

An application that has implemented OLE interfaces such that the application supports the features and capabilities of both a container and object application.

Container/Server

See Container/Object.

Control object

The object within an Aggregate object that controls which interfaces within the aggregate object are exposed and which are private.. The control object has a special implementation of IUnknown called the controlling unknown, and all other objects in the aggregate must pass calls to IUnknown methods through the controlling unknown. See Aggregate object.

D

Data transfer object

An object that supports the IDataObject interface and contains data to be transferred from one object to another either through the Clipboard or drag-and-drop operations.

Default object handler

A DLL provided with the OLE SDK that provides a partial implementation of basic interfaces. It is a surrogate in the processing space of the container application for the real object.

With the default object handler, it is possible to look at an object's stored data without actually activating the object. The default object handler performs other tasks on behalf of a loaded object, such as rendering an object from its cached state when the object is loaded into memory.

Direct access mode

One of two access modes in which a storage object can be opened. In direct mode, all changes are immediately committed to the root storage object. See also Transacted access mode.

Drag and drop

OLE specifies a set of data transfer and drag-and drop-interface-specific interfaces that allow applications to implement drag and drop, an operation in which the end-user uses the mouse or other pointing device to drag data from one window and drop it into another location in the same window or into another window.

E

Embedded object

A compound-document object that is stored with the container application, but when it is running, lives in the process space of the server application, which creates and subsequently edits it. The default handler provides a surrogate in the processing space of the container application for the real object.

Explicit caching

One of two ways an object can cache its presentation data. Explicit caching requires the physical creation of the cache nodes needed to save the data formats of the object. See also Implicit caching.

F

File moniker

A moniker based on a path in the file system. File monikers can be used to identify objects that are saved in their own files. A file moniker is an object that represents an implementation of the IMoniker interface for the file class. See also Item moniker and Generic composite moniker.

G

Global memory

See Shared application memory.

Generic composite moniker

The generic composite moniker is a sequenced collection of other types of monikers, starting with a file moniker to provide the document-level path and continuing with one or more item monikers. See also Item moniker and File moniker.

H

Handler

See Object handler.

Helper function

A function that encapsulates other functions and interface methods publicly available in the OLE SDK.

HRESULT

An opaque result handle defined to be zero for a successful return from a function and non-zero if error or status information is to be returned. To convert an HRESULT into the more detailed SCODE, applications call GetScode(). See SCODE.

I

Implicit caching

The "implied" caching of presentation data by an object that is capable of rendering itself using its native data. Cache nodes are not created with implicit caching. See also Explicit caching.

In parameter

A parameter that is allocated, set, and freed by the caller of a function.

In/Out parameter

A parameter that is initially allocated by the caller of a function and set, freed, and reallocated if necessary by that which is called.

In-process server

An object server or application implemented as a DLL that runs in the process space of the object's container. See also Local server, Remote server.

Instance

An object for which memory is allocated or which is persistent.

Instantiate

The process of creating an activating an obnect based on its definition.

Interface

A group of related functions that provide access to OLE objects. The set of OLE interfaces define a contract that allow objects to interact according to the Component Object Model (COM). While OLE provides many interface implementations, most interfaces can also be implemented by developers designing OLE applications.

Interface identifier (IID)

A unique identification tag associated with each interface. Some functions take IIDs as parameters to allow the callers to specify what type of interface pointer should be returned.

Item moniker

A moniker based on a string that identifies an object in a container. Item monikers can be used to identify objects smaller than a file, including embedded objects in a compound document, or a pseudo-object (like a range of cells in a spreadsheet). See also File moniker and Generic composite moniker.

L

Link object

A component object that is instantiated when a linked compound document object is created or loaded. The link object implements the IOleLink interface and is provided by OLE.

Linked object

A compound-document object whose source data physically resides where it was initially created. Only a moniker that represents the source data and the appropriate presentation data is kept with the compound document. Changes made to the link source are automatically reflected in the linked compound-document object in the container(s).

Link source

The data that is the source of a linked compound document object. A link source may be a file or a portion of a file, such as an embedded object or a selected range within a file (also called a pseudo object).

Loaded state

The state of a compound-document object after its data structures have been loaded into container memory. The data structures are created by the object handler. See also Passive state and Running state.

Local server

An server application implemented as an EXE running on the same machine as the client application using it. Because the server application is an EXE, it runs in its own process. See also In-Process server and Remote server.

Lock

OLE defines two types of locks that can be held on an object: strong and weak. A strong lock will keep an object in memory, a weak lock will not.

LRPC (Lightweight remote procedure call)

OLE's RPC-based protocol for interprocess communication. LRPC is "lightweight" in that it handles communication between processes on one machine only.

M

Marshaling

The process of packaging and sending interface parameters across process boundaries.

Moniker

An object that implements the IMoniker interface. A moniker acts as a name that uniquely identifies a COM object. You can think of a moniker as a generalization of a pathname; in the same way that a pathname identifies a file in the file system, a moniker identifies a COM object. Monikers support an operation known as "binding," which is the process of locating the object named by the moniker, activating it (loading it in memory) if it isn't already, and returning an interface pointer to it.

Moniker class

An implementation of the IMoniker interface. System-supplied moniker classes include file monikers, item monikers, generic composite monikers, anti-monikers, and pointer monikers.

Moniker client

An application that uses monikers to acquire interface pointers to objects managed by another application.

Moniker provider

An application that hands out monikers that identify  the objects it manages, so that they are accessible to other applications.

Multiple Document Interface (MDI) Application

An application that can support multiple documents from one application instance. MDI object applications can simultaneously serve a user and one or more embedding containers. See also Single Document Interface (SDI) application.

N

Native data

The data used by an OLE server application when editing an embedded object. See also Presentation data.

Nested object

An OLE object that is embedded within another OLE object through the use of a combination container/server application. OLE objects can be arbitrarily nested to any level.

O

Object

Generally, an instance of an entity that embodies both specific data and the functions that manipulate it.
Specifically in object-oriented programming, an object is an entity that has state, behavior and identity. An object's state consists of its attributes and and the attributes' current values. An object's behavior consists of the operations that can be performed on it and the accompanying state changes. An object's identity is what you use to distinguish it from other objects.
In contrast, COM objects' behavior is defined by the interfaces it supports. A COM object's state is not explicitly specified, but is implied by its interfaces. A COM object's identity is defined by the ability to use IUnknown::QueryInterface to move between interfaces.
A COM object follows a specific model in which clients (those using an object's services) gain access to the object's data only through a pointer to an interface consisting of a set of methods (related functions). The client can then call these methods to perform desired operations. There is no direct access to an OLE object's data.

Object application

An OLE-aware application that can create compound document objects. Containers can then embed or link to these objects.

Object handler

A piece of class-specific code that is dynamically loaded into the address space of its container. Object handlers process requests for specific classes of objects, so that much of the communication can be in-process. This is more efficient because it reduces the need for remote procedure calls.

Object state

One of three relationships between a compound document object in its container and the application responsible for the object's creation: passive, loaded, and running. Passive objects are stored (on disk or in a database), and the object is not selected or active. In the loaded state, its data structures have been loaded into memory, but is not yet available for operations such as editing. Running objects are both loaded and available for all operations.

Object type name

A unique identification string that is stored as part of the information available for an object in the registration database—for example, Acme Drawing.

OLE Automation

A way to manipulate an application's objects from outside the application. OLE automation is typically used to create applications that expose objects to programming tools and macro languages, create and manipulate one application's objects from another applications, or to create tools for accessing and manipulating objects. For information on OLE Automation, refer to the OLE Programmer's Reference, Volume 2.

Out parameter

A function parameter that is allocated and set by whatever a function calls, and must be freed by the caller.

P

Passive state

The state of an OLE object when it is stored (on disk or in a database). The object is not selected or active. See also Loaded state and Running state.

Persistent storage

Storage of a file or object in a medium such as a file system or database so that the file can be closed and then re-opened at a later time. Data can be retrieved from the file until the underlying file is deleted.

Pointer moniker

A moniker that wraps an interface pointer to an object in memory. Whereas most monikers identify objects that can be saved to persistent storage, pointer monikers identify objects that cannot. They allow such objects to participate in a moniker binding operation.

Presentation data

The data used by an OLE container applicationto display embedded or linked objects. See also Native data.

Primary verb

The action associated with the most common, preferred operation users perform on an object; the primary verb is always defined as verb zero in the system registration database. An object's primary verb is executed by double-clicking on the object.

Proxy

An interface-specific object that packages parameters for that interface in preparation for a remote method call. A proxy runs in the address space of the sender and communicates with a corresponding stub in the receiver's address space. See also Stub, Marshaling, and Unmarshaling.

Proxy manager

Manages all the proxies for a single object.

Pseudo object

A selection of data within a document or embedded object that can be the source for a compound-document object.

R

Reference counting

Keeping a count of each interface pointer instance to ensure that an object is not destroyed before all references to it are released.

Relative moniker

A moniker that specifies the location of an object  relative to the location of another object. A relative moniker is analogous to a relative pathname (such as "..\backup\report.old").

Remote Server

A server application, implemented as an EXE, running on a different machine from the client application using it. See also In-process server, Local server.

Revert

The act of discarding any change(s) made to an object since the last time the changes were committed or the object's storage was opened. See also Commit, Transacted access mode.

Root IStorage object

The outermost IStorage instance in a document; also called the root storage object. Compound-document objects are always saved as children of a root IStorage object.

Running state

The state of an OLE object when the object application is running and it is possible to edit the object, access its interfaces, and receive notification of changes. See also Loaded state and Passive state.

Running object table (ROT)

A globally-accessible table on each machine that keeps track of all the OLE objects that can be identified by a moniker and are currently running on the machine. Monikers use the Running Object Table. Registering an object in the running object table increments the object's reference count. Before the object can be destroyed, its moniker must be released from the running object table.

S

SCODE

A DWORD value that is used to pass detailed information to the caller of an interface method or function. See also HRESULT.

Server

See Object application.

Shared application memory

Memory that is primarily used between processes to optimize the data copying that occurs in LPRC calls.

Single Document Interface (SDI) Application

An application that can support only one document at a time. Multiple instances of an SDI application must be started to service both an embedded object and a user. See also Multiple Document Interface (MDI) application.

Single object application

An application that is capable of creating and manipulating one class of object. See also Multiple object application.

Stand-alone object application

An object application implemented as an executable (EXE) program, rather than as a DLL object application.

State

See Loaded state, Passive state, and Running state.

Static object

An object that contains only a presentation, with no native data. A container application can treat a static object as though it were a linked or embedded object, except that it is not possible to edit a static object.
A static object can result, for example, from the breaking of a link on a linked object; you don't want the linked object to be updated anymore.

Storage object

An object that implements the IStorage interface. A storage object contains nested storage objects or stream objects, resulting in a directory/file system within a single file. It provides the underlying storage for compound documents. Container applications provide a nested storage object for each of their embedded objects. The embedded object stores its data nested storage and stream objects within the storage object provided by its container. See also Root IStorage object and Stream object.

Stream object

An object that implements the IStream interface. A stream object is analogous to a file in a directory/file system. See also Storage object.

Structured storage model

A specification that defines a hierarchical method of storing objects. OLE provides an implementation of the structured storage model called Compound Files. See Compound file.

Stub

When a function's or interface method's parameters are marshaled across a process boundary, the stub is an interface-specific object that unpackages the marshaled parameters and calls the required method. The stub runs in the receiver's address space and communicates with a corresponding proxy in the sender's address space. See Proxy, Marshaling, and Unmarshaling.

Stub manager

Manages all of the stubs for a single object.

Synchronous call

A function that does not allow further instructions in the process to be executed until the function returns. Most OLE interface methods, except some of the IAdviseSink methods, are synchronous calls. See also Asychronous call.

T

Transacted access mode

One of two access modes in which a storage object can be opened. When opened in transacted mode, changes are stored in temporary buffers until the root IStorage object commits its changes. See also Direct access mode, Commit, Revert.

U

Uniform data transfer

A model for transferring data via the Clipboard, drag and drop, or through automation. Objects conforming to the model implement the IDataObject interface. This model replaces DDE (dynamic data exchange). See Data transfer object.

Unmarshaling

The processing of unpackaging parameters that have been sent across process boundaries.

V

Virtual Table (VTBL)

An array of pointers that point to interface method implementations.

Visual Editing

A term in end-user documents that refers to the user's ability to interact with a compound-document object in the context of its container. The term most often used by developers is in-place activation. See also In-place activation.